gpui: Reduce workspace dependencies (#67636)

## Summary

Reduce the local crates needed to extract `gpui` and `gpui_platform`
from 26 to 20, counting all targets, optional features, and
dev-dependencies.

- Share Fx and `TypeId` collection types through
`gpui_util::collections`, preserving hashers and the existing
`collections` API for Zed.
- Run the three GPUI style tests as ordinary tests rather than pulling
in `util_macros` and the `perf` runner.
- Use `tracing::instrument` directly in `sum_tree` and `env_logger` for
its randomized test. Tree spans now follow the active tracing subscriber
instead of the `ztracing` compile-time switch.

Release Notes:

- [GPUI] n/a
This commit is contained in:
Lukas Wirth
2026-11-30 15:04:37 +00:00
committed by GitHub
parent 5e0441335b
commit 579a992fa0
71 changed files with 378 additions and 306 deletions
Generated
+3 -12
View File
@@ -7478,7 +7478,6 @@ dependencies = [
"bench_metrics",
"bitflags 2.13.1",
"chrono",
"collections",
"criterion",
"derive_more",
"dioxus-cli-config",
@@ -7521,7 +7520,6 @@ dependencies = [
"raw-window-handle",
"refineable",
"regex",
"reqwest_client",
"resvg",
"scheduler",
"schemars 1.0.4",
@@ -7543,7 +7541,6 @@ dependencies = [
"unicode-segmentation",
"url",
"usvg",
"util_macros",
"uuid",
"waker-fn",
"wasm-bindgen",
@@ -7561,7 +7558,6 @@ dependencies = [
"async-task",
"block2 0.6.2",
"cbindgen",
"collections",
"core-foundation 0.10.0",
"core-foundation-sys",
"core-graphics",
@@ -7625,7 +7621,6 @@ dependencies = [
"bytemuck",
"calloop",
"calloop-wayland-source",
"collections",
"filedescriptor",
"futures 0.3.34",
"gpui",
@@ -7664,7 +7659,6 @@ dependencies = [
"accesskit_macos",
"anyhow",
"block2 0.6.2",
"collections",
"core-foundation 0.10.0",
"core-foundation-sys",
"core-graphics",
@@ -7750,6 +7744,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"log",
"rustc-hash 2.1.3",
"which",
]
@@ -7762,6 +7757,7 @@ dependencies = [
"console_error_panic_hook",
"futures 0.3.34",
"gpui",
"gpui_util",
"gpui_wgpu",
"http_client",
"js-sys",
@@ -7787,7 +7783,6 @@ version = "0.1.0"
dependencies = [
"anyhow",
"bytemuck",
"collections",
"cosmic-text",
"criterion",
"etagere",
@@ -7817,7 +7812,6 @@ dependencies = [
"accesskit",
"accesskit_windows",
"anyhow",
"collections",
"dunce",
"etagere",
"futures 0.3.34",
@@ -17723,15 +17717,12 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
name = "sum_tree"
version = "0.1.0"
dependencies = [
"ctor",
"env_logger 0.11.8",
"heapless",
"log",
"proptest",
"rand 0.9.4",
"rayon",
"tracing",
"zlog",
"ztracing",
]
[[package]]
+1 -3
View File
@@ -2,10 +2,8 @@ pub type HashMap<K, V> = FxHashMap<K, V>;
pub type HashSet<T> = FxHashSet<T>;
pub type IndexMap<K, V> = indexmap::IndexMap<K, V, rustc_hash::FxBuildHasher>;
pub type IndexSet<T> = indexmap::IndexSet<T, rustc_hash::FxBuildHasher>;
pub type TypeIdHashMap<V> =
std::collections::HashMap<std::any::TypeId, V, gpui_util::TypeIdHashBuilder>;
pub type TypeIdHashSet = std::collections::HashSet<std::any::TypeId, gpui_util::TypeIdHashBuilder>;
pub use gpui_util::collections::{TypeIdHashMap, TypeIdHashSet};
pub use indexmap::Equivalent;
pub use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet, FxHasher};
pub use std::collections::*;
-5
View File
@@ -20,7 +20,6 @@ workspace = true
default = ["font-kit", "wayland", "x11", "windows-manifest"]
test-support = [
"bench_metrics?/test-support",
"collections/test-support",
"http_client/test-support",
"wayland",
"x11",
@@ -65,7 +64,6 @@ async-task.workspace = true
backtrace.workspace = true
bitflags.workspace = true
collections.workspace = true
bench_metrics = { workspace = true, optional = true }
criterion = { workspace = true, optional = true }
derive_more = { workspace = true, features = ["add", "add_assign", "mul", "mul_assign", "not"] }
@@ -174,7 +172,6 @@ windows = { workspace = true, features = [
[dev-dependencies]
backtrace.workspace = true
collections = { workspace = true, features = ["test-support"] }
env_logger.workspace = true
futures-concurrency.workspace = true
postage = { workspace = true, features = ["blocking"] }
@@ -184,12 +181,10 @@ gpui_util.workspace = true
lyon_extra = "1.1.0"
rand = { workspace = true, default-features = true }
scheduler = { workspace = true, features = ["test-support"] }
util_macros.workspace = true
[target.'cfg(not(target_family = "wasm"))'.dev-dependencies]
http_client = { workspace = true, features = ["test-support"] }
proptest.workspace = true
reqwest_client = { workspace = true, features = ["test-support"] }
[target.'cfg(target_os = "macos")'.dev-dependencies]
objc2.workspace = true
@@ -0,0 +1,90 @@
use gpui::Application;
use std::sync::Arc;
#[cfg(target_family = "wasm")]
pub fn with_client(app: Application) -> Application {
let client = gpui_web::FetchHttpClient::new(app.foreground_executor().to_send());
app.with_http_client(Arc::new(client))
}
#[cfg(not(target_family = "wasm"))]
const IMAGES: &[(&str, &str, &[u8])] = &[
(
"icon.png",
"image/png",
include_bytes!("../image/app-icon.png"),
),
(
"colors.svg",
"image/svg+xml",
include_bytes!("../image/color.svg"),
),
(
"arrow.svg",
"image/svg+xml",
include_bytes!("../image/arrow_circle.svg"),
),
(
"oriented.jpg",
"image/jpeg",
include_bytes!("../image/exif-orientation-rotate-180.jpg"),
),
];
#[cfg(not(target_family = "wasm"))]
pub fn fixture_url(id: usize) -> String {
let (name, _, _) = IMAGES[id % IMAGES.len()];
// Keep cache entries distinct even when they serve the same fixture.
format!("https://images.example/{name}?id={id}")
}
#[cfg(not(target_family = "wasm"))]
fn fixture_client() -> Arc<dyn http_client::HttpClient> {
use http_client::{AsyncBody, FakeHttpClient, Response, StatusCode};
FakeHttpClient::create(|request| async move {
let uri = request.uri();
if uri.host() == Some("images.example")
&& let Some((_, content_type, bytes)) = IMAGES
.iter()
.find(|(name, _, _)| uri.path().strip_prefix('/') == Some(*name))
{
return Ok(Response::builder()
.header("content-type", *content_type)
.body(AsyncBody::from(*bytes))?);
}
Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(AsyncBody::empty())?)
})
}
#[cfg(not(target_family = "wasm"))]
pub fn with_client(app: Application) -> Application {
app.with_http_client(fixture_client())
}
#[cfg(all(test, not(target_family = "wasm")))]
#[test]
fn fixture_urls_are_distinct_cache_keys_for_bundled_images() -> anyhow::Result<()> {
use futures::AsyncReadExt as _;
let client = fixture_client();
futures::executor::block_on(async {
for (id, (_, content_type, expected)) in IMAGES.iter().enumerate() {
let url = fixture_url(id);
assert_ne!(url, fixture_url(id + IMAGES.len()));
let mut response = client.get(&url, ().into(), true).await?;
assert!(response.status().is_success());
assert_eq!(response.headers()["content-type"], *content_type);
let mut bytes = Vec::new();
response.body_mut().read_to_end(&mut bytes).await?;
assert_eq!(bytes.as_slice(), *expected);
}
let missing = client
.get("https://images.example/missing", ().into(), true)
.await?;
assert_eq!(missing.status(), http_client::StatusCode::NOT_FOUND);
Ok(())
})
}
+19 -16
View File
@@ -2,6 +2,8 @@
#[path = "../example_support/fonts.rs"]
mod example_support;
#[path = "../example_support/image_http.rs"]
mod image_http;
use std::fs;
use std::path::PathBuf;
@@ -13,8 +15,6 @@ use gpui::{
SharedString, SharedUri, TitlebarOptions, Window, WindowBounds, WindowOptions, actions, div,
img, prelude::*, px, rgb, size,
};
#[cfg(not(target_family = "wasm"))]
use reqwest_client::ReqwestClient;
struct Assets {
base: PathBuf,
@@ -79,6 +79,10 @@ struct ImageShowcase {
impl Render for ImageShowcase {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
#[cfg(target_family = "wasm")]
let badge = "https://github.com/zed-industries/zed/actions/workflows/ci.yml/badge.svg";
#[cfg(not(target_family = "wasm"))]
let badge = image_http::fixture_url(2);
div()
.id("main")
.bg(gpui::white())
@@ -92,9 +96,7 @@ impl Render for ImageShowcase {
.justify_center()
.items_center()
.gap_8()
.child(img(
"https://github.com/zed-industries/zed/actions/workflows/ci.yml/badge.svg",
))
.child(img(badge))
.child(
div()
.flex()
@@ -107,7 +109,11 @@ impl Render for ImageShowcase {
self.local_resource.clone(),
))
.child(ImageContainer::new(
"Image loaded from a remote resource",
if cfg!(target_family = "wasm") {
"Image loaded from a remote resource"
} else {
"Image loaded from a fixture-backed URL"
},
self.remote_resource.clone(),
))
.child(ImageContainer::new(
@@ -124,13 +130,13 @@ impl Render for ImageShowcase {
div()
.flex_col()
.child("Auto Width")
.child(img("https://picsum.photos/800/400").h(px(180.))),
.child(img(self.remote_resource.clone()).h(px(180.))),
)
.child(
div()
.flex_col()
.child("Auto Height")
.child(img("https://picsum.photos/800/400").w(px(180.))),
.child(img(self.remote_resource.clone()).w(px(180.))),
),
)
.child(
@@ -143,7 +149,7 @@ impl Render for ImageShowcase {
.border_1()
.border_color(rgb(0xC0C0C0))
.child("image with max width 100%")
.child(img("https://picsum.photos/800/400").max_w_full()),
.child(img(self.remote_resource.clone()).max_w_full()),
),
)
}
@@ -154,13 +160,7 @@ actions!(image, [Quit]);
fn run_example() {
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let app = gpui_platform::application();
#[cfg(not(target_family = "wasm"))]
let http_client =
ReqwestClient::user_agent("gpui example").expect("failed to create HTTP client");
#[cfg(target_family = "wasm")]
let http_client = gpui_web::FetchHttpClient::new(app.foreground_executor().to_send());
let app = app.with_http_client(Arc::new(http_client));
let app = image_http::with_client(gpui_platform::application());
app.with_assets(Assets {
base: manifest_dir.join("examples"),
})
@@ -198,7 +198,10 @@ fn run_example() {
local_resource: manifest_dir
.join("examples/image/exif-orientation-rotate-180.jpg")
.into(),
#[cfg(target_family = "wasm")]
remote_resource: "https://picsum.photos/800/400".into(),
#[cfg(not(target_family = "wasm"))]
remote_resource: image_http::fixture_url(0).into(),
asset_resource: "image/color.svg".into(),
})
})
+17 -25
View File
@@ -2,6 +2,8 @@
#[path = "example_support/fonts.rs"]
mod example_support;
#[path = "example_support/image_http.rs"]
mod image_http;
use gpui::{
App, AppContext, Bounds, ClickEvent, Context, ElementId, Entity, ImageCache,
@@ -9,14 +11,12 @@ use gpui::{
TitlebarOptions, Window, WindowBounds, WindowOptions, actions, div, hash, image_cache, img,
prelude::*, px, rgb, size,
};
#[cfg(not(target_family = "wasm"))]
use reqwest_client::ReqwestClient;
use std::{collections::HashMap, sync::Arc};
use gpui_util::collections::FxHashMap;
use std::sync::Arc;
const IMAGES_IN_GALLERY: usize = 30;
struct ImageGallery {
image_key: String,
items_count: usize,
total_count: usize,
image_cache: Entity<RetainAllImageCache>,
@@ -27,12 +27,6 @@ impl ImageGallery {
self.image_cache
.update(cx, |image_cache, cx| image_cache.clear(window, cx));
let t = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis();
self.image_key = format!("{}", t);
self.total_count += self.items_count;
cx.notify();
}
@@ -40,8 +34,14 @@ impl ImageGallery {
impl Render for ImageGallery {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let image_url: SharedString =
format!("https://picsum.photos/400/200?t={}", self.image_key).into();
let gallery_image = |index| {
let id = self.total_count + index;
#[cfg(not(target_family = "wasm"))]
let url = image_http::fixture_url(id);
#[cfg(target_family = "wasm")]
let url = format!("https://picsum.photos/400/200?t={id}");
img(url).size_20()
};
div()
.flex()
@@ -96,7 +96,7 @@ impl Render for ImageGallery {
.justify_around()
.children(
(0..self.items_count)
.map(|ix| img(format!("{}-{}", image_url, ix)).size_20()),
.map(gallery_image),
),
),
)
@@ -126,7 +126,7 @@ impl Render for ImageGallery {
.justify_around()
.children(
(0..self.items_count)
.map(|ix| img(format!("{}-{}", image_url, ix)).size_20()),
.map(gallery_image),
),
)
))
@@ -169,7 +169,7 @@ impl ImageCacheProvider for SimpleLruCacheProvider {
struct SimpleLruCache {
max_items: usize,
usages: Vec<u64>,
cache: HashMap<u64, gpui::ImageCacheItem>,
cache: FxHashMap<u64, gpui::ImageCacheItem>,
}
impl SimpleLruCache {
@@ -186,7 +186,7 @@ impl SimpleLruCache {
Self {
max_items,
usages: Vec::with_capacity(max_items),
cache: HashMap::with_capacity(max_items),
cache: FxHashMap::with_capacity_and_hasher(max_items, Default::default()),
}
}
}
@@ -241,14 +241,7 @@ fn run_example() {
let app = gpui_platform::application();
#[cfg(target_family = "wasm")]
let app = gpui_platform::single_threaded_web();
#[cfg(not(target_family = "wasm"))]
let http_client =
ReqwestClient::user_agent("gpui example").expect("failed to create HTTP client");
#[cfg(target_family = "wasm")]
let http_client = gpui_web::FetchHttpClient::new(app.foreground_executor().to_send());
let app = app.with_http_client(Arc::new(http_client));
app.run(move |cx: &mut App| {
image_http::with_client(app).run(move |cx: &mut App| {
if !example_support::load_fonts(cx) {
return;
}
@@ -276,7 +269,6 @@ fn run_example() {
cx.open_window(window_options, |_, cx| {
cx.new(|ctx| ImageGallery {
image_key: "".into(),
items_count: IMAGES_IN_GALLERY,
total_count: 0,
image_cache: RetainAllImageCache::new(ctx),
+8 -8
View File
@@ -1,6 +1,6 @@
use anyhow::{Context as _, Result};
use collections::{HashMap, TypeIdHashMap};
pub use gpui_macros::Action;
use gpui_util::collections::{FxHashMap, TypeIdHashMap};
pub use no_action::{NoAction, Unbind, is_no_action, is_unbind};
use serde_json::json;
use std::{
@@ -231,12 +231,12 @@ impl Display for ActionBuildError {
type ActionBuilder = fn(json: serde_json::Value) -> anyhow::Result<Box<dyn Action>>;
pub(crate) struct ActionRegistry {
by_name: HashMap<&'static str, ActionData>,
by_name: FxHashMap<&'static str, ActionData>,
names_by_type_id: TypeIdHashMap<&'static str>,
all_names: Vec<&'static str>, // So we can return a static slice.
deprecated_aliases: HashMap<&'static str, &'static str>, // deprecated name -> preferred name
deprecation_messages: HashMap<&'static str, &'static str>, // action name -> deprecation message
documentation: HashMap<&'static str, &'static str>, // action name -> documentation
deprecated_aliases: FxHashMap<&'static str, &'static str>, // deprecated name -> preferred name
deprecation_messages: FxHashMap<&'static str, &'static str>, // action name -> deprecation message
documentation: FxHashMap<&'static str, &'static str>, // action name -> documentation
}
impl Default for ActionRegistry {
@@ -397,15 +397,15 @@ impl ActionRegistry {
.map(|action_data| (action_data.json_schema)(generator))
}
pub fn deprecated_aliases(&self) -> &HashMap<&'static str, &'static str> {
pub fn deprecated_aliases(&self) -> &FxHashMap<&'static str, &'static str> {
&self.deprecated_aliases
}
pub fn deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
pub fn deprecation_messages(&self) -> &FxHashMap<&'static str, &'static str> {
&self.deprecation_messages
}
pub fn documentation(&self) -> &HashMap<&'static str, &'static str> {
pub fn documentation(&self) -> &FxHashMap<&'static str, &'static str> {
&self.documentation
}
}
+15 -9
View File
@@ -2,6 +2,7 @@ use scheduler::Instant;
use std::{
any::{TypeId, type_name},
cell::{Cell, Ref, RefCell, RefMut},
collections::VecDeque,
ffi::OsString,
marker::PhantomData,
mem::{self, DropGuard},
@@ -25,10 +26,13 @@ pub use bench_context::{
BenchAppContext, BenchMeasurement, BenchReport, BenchWindowContext, CountingAllocator,
MetricReport, bench_platform,
};
use collections::{FxHashMap, FxHashSet, HashMap, TypeIdHashMap, TypeIdHashSet, VecDeque};
pub use context::*;
pub use entity_map::*;
use gpui_util::{ResultExt, debug_panic};
use gpui_util::{
ResultExt,
collections::{FxHashMap, FxHashSet, TypeIdHashMap, TypeIdHashSet},
debug_panic,
};
#[cfg(any(test, feature = "test-support"))]
pub use headless_app_context::*;
use http_client::{HttpClient, Url};
@@ -423,7 +427,7 @@ impl DisplayState {
}
}
fn read_displays(platform: &dyn Platform) -> HashMap<DisplayId, DisplayState> {
fn read_displays(platform: &dyn Platform) -> FxHashMap<DisplayId, DisplayState> {
platform
.displays()
.into_iter()
@@ -439,8 +443,8 @@ fn read_displays(platform: &dyn Platform) -> HashMap<DisplayId, DisplayState> {
/// The events that turn one snapshot of the connected displays into the next.
fn display_events(
previous: &HashMap<DisplayId, DisplayState>,
current: &HashMap<DisplayId, DisplayState>,
previous: &FxHashMap<DisplayId, DisplayState>,
current: &FxHashMap<DisplayId, DisplayState>,
) -> Vec<DisplayEvent> {
let removed = previous
.keys()
@@ -918,7 +922,7 @@ pub struct App {
pub(crate) display_observers: SingleSubscriberSet<DisplayHandler>,
/// The connected displays, as of the platform's last display change
/// notification.
displays: HashMap<DisplayId, DisplayState>,
displays: FxHashMap<DisplayId, DisplayState>,
pub(crate) system_sleep_observers: SingleSubscriberSet<Handler>,
pub(crate) system_wake_observers: SingleSubscriberSet<Handler>,
app_lifecycle_observers: SingleSubscriberSet<AppLifecycleHandler>,
@@ -2980,17 +2984,19 @@ impl App {
}
/// Get a map from a deprecated action name to the canonical name.
pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
pub fn deprecated_actions_to_preferred_actions(
&self,
) -> &FxHashMap<&'static str, &'static str> {
self.actions.deprecated_aliases()
}
/// Get a map from an action name to the deprecation messages.
pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
pub fn action_deprecation_messages(&self) -> &FxHashMap<&'static str, &'static str> {
self.actions.deprecation_messages()
}
/// Get a map from an action name to the documentation.
pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
pub fn action_documentation(&self) -> &FxHashMap<&'static str, &'static str> {
self.actions.documentation()
}
+9 -9
View File
@@ -1,7 +1,9 @@
use crate::{App, AppContext, GpuiBorrow, VisualContext, Window, seal::Sealed};
use anyhow::{Context as _, Result};
use collections::FxHashSet;
use derive_more::{Deref, DerefMut};
#[cfg(any(test, gpui_leak_detection))]
use gpui_util::collections::FxHashMap;
use gpui_util::collections::FxHashSet;
use parking_lot::{RwLock, RwLockUpgradableReadGuard};
use slotmap::{KeyData, SecondaryMap, SlotMap};
use std::{
@@ -22,8 +24,6 @@ use std::{
use super::Context;
use crate::util::atomic_incr_if_not_zero;
#[cfg(any(test, gpui_leak_detection))]
use collections::HashMap;
slotmap::new_key_type! {
/// A unique identifier for a entity across the application.
@@ -108,7 +108,7 @@ impl EntityMap {
#[cfg(any(test, gpui_leak_detection))]
leak_detector: LeakDetector {
next_handle_id: 0,
entity_handles: HashMap::default(),
entity_handles: FxHashMap::default(),
},
})),
}
@@ -1043,7 +1043,7 @@ pub(crate) struct HandleId {
#[cfg(any(test, gpui_leak_detection))]
pub(crate) struct LeakDetector {
next_handle_id: u64,
entity_handles: HashMap<EntityId, EntityLeakData>,
entity_handles: FxHashMap<EntityId, EntityLeakData>,
}
/// A snapshot of the set of alive entities at a point in time.
@@ -1055,12 +1055,12 @@ pub(crate) struct LeakDetector {
#[derive(Default)]
pub struct LeakDetectorSnapshot {
#[cfg(any(test, gpui_leak_detection))]
entity_ids: collections::HashSet<EntityId>,
entity_ids: FxHashSet<EntityId>,
}
#[cfg(any(test, gpui_leak_detection))]
struct EntityLeakData {
handles: HashMap<HandleId, Option<backtrace::Backtrace>>,
handles: FxHashMap<HandleId, Option<backtrace::Backtrace>>,
type_name: &'static str,
}
@@ -1083,7 +1083,7 @@ impl LeakDetector {
.entity_handles
.entry(entity_id)
.or_insert_with(|| EntityLeakData {
handles: HashMap::default(),
handles: FxHashMap::default(),
type_name: type_name.unwrap_or("<unknown>"),
});
handles.handles.insert(
@@ -1298,7 +1298,7 @@ impl fmt::Debug for BacktraceFormatter {
#[cfg(test)]
mod test {
use crate::EntityMap;
use collections::FxHashSet;
use gpui_util::collections::FxHashSet;
struct TestEntity {
pub i: i32,
+2 -2
View File
@@ -1,6 +1,6 @@
use crate::{App, EntityId, SharedString, SharedUri, Task};
use collections::FxHashSet;
use futures::{Future, TryFutureExt};
use gpui_util::collections::{FxBuildHasher, FxHashSet};
use std::cell::RefCell;
use std::fmt::Debug;
@@ -137,7 +137,7 @@ where
/// Use a quick, non-cryptographically secure hash function to get an identifier from data
pub fn hash<T: Hash>(data: &T) -> u64 {
collections::FxBuildHasher.hash_one(data)
FxBuildHasher.hash_one(data)
}
#[cfg(test)]
+3 -2
View File
@@ -38,6 +38,7 @@ use crate::{
FocusHandle, InspectorElementId, LayoutId, Pixels, Point, Size, Style, Window,
util::FluentBuilder, window::with_element_arena,
};
use gpui_util::collections::FxHasher;
use std::{
any::Any,
fmt::{self, Debug, Display},
@@ -243,7 +244,7 @@ impl PathHash {
/// The hash of this path with `id` appended.
pub(crate) fn extend(self, id: &ElementId) -> Self {
use std::hash::{Hash, Hasher};
let mut hasher = collections::FxHasher::with_seed(self.0 as usize);
let mut hasher = FxHasher::with_seed(self.0 as usize);
id.hash(&mut hasher);
Self(hasher.finish())
}
@@ -889,7 +890,7 @@ mod global_element_id_tests {
}
fn fx_hash(value: &impl Hash) -> u64 {
let mut hasher = collections::FxHasher::default();
let mut hasher = FxHasher::default();
value.hash(&mut hasher);
hasher.finish()
}
+2 -3
View File
@@ -26,8 +26,7 @@ use crate::{
Point, Render, ScrollEvent, SharedString, Size, Style, StyleRefinement, Styled, Task,
TooltipId, TouchPhase, Visibility, Window, WindowControlArea, point, px, size,
};
use collections::HashMap;
use gpui_util::ResultExt;
use gpui_util::{ResultExt, collections::FxHashMap};
use refineable::Refineable;
use smallvec::SmallVec;
use std::{
@@ -4146,7 +4145,7 @@ fn handle_tooltip_check_visible_and_update(
}
#[derive(Default)]
pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
pub(crate) struct GroupHitboxes(FxHashMap<SharedString, SmallVec<[HitboxId; 1]>>);
impl Global for GroupHitboxes {}
+6 -5
View File
@@ -5,9 +5,10 @@ use crate::{
};
use crate::asset_cache::CachedLoad;
use gpui_util::collections::FxHashMap;
use refineable::Refineable;
use smallvec::SmallVec;
use std::{collections::HashMap, fmt, sync::Arc};
use std::{fmt, sync::Arc};
/// An image cache element, all its child img elements will use the cache specified by this element.
/// Note that this could as simple as passing an `Entity<T: ImageCache>`
@@ -211,7 +212,7 @@ impl<T: ImageCache> ImageCacheProvider for Entity<T> {
}
/// An implementation of ImageCache, that uses an LRU caching strategy to unload images when the cache is full
pub struct RetainAllImageCache(HashMap<u64, ImageCacheItem>);
pub struct RetainAllImageCache(FxHashMap<u64, ImageCacheItem>);
impl fmt::Debug for RetainAllImageCache {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
@@ -225,9 +226,9 @@ impl RetainAllImageCache {
/// Create a new image cache.
#[inline]
pub fn new(cx: &mut App) -> Entity<Self> {
let e = cx.new(|_cx| RetainAllImageCache(HashMap::new()));
let e = cx.new(|_cx| RetainAllImageCache(FxHashMap::default()));
cx.observe_release(&e, |image_cache, cx| {
for (_, item) in std::mem::replace(&mut image_cache.0, HashMap::new()) {
for (_, item) in std::mem::take(&mut image_cache.0) {
if let Some(Ok(image)) = item.get() {
cx.drop_image(image, None);
}
@@ -256,7 +257,7 @@ impl RetainAllImageCache {
/// Clear the image cache.
pub fn clear(&mut self, window: &mut Window, cx: &mut App) {
for (_, item) in std::mem::replace(&mut self.0, HashMap::new()) {
for (_, item) in std::mem::take(&mut self.0) {
if let Some(Ok(image)) = item.get() {
cx.drop_image(image, Some(window));
}
+1 -2
View File
@@ -13,9 +13,8 @@ use crate::{
Overflow, Pixels, Point, ScrollDelta, ScrollEvent, Size, Style, StyleRefinement, Styled,
Window, point, px, size,
};
use collections::VecDeque;
use refineable::Refineable as _;
use std::{cell::RefCell, ops::Range, rc::Rc};
use std::{cell::RefCell, collections::VecDeque, ops::Range, rc::Rc};
use sum_tree::{Bias, Dimensions, SumTree};
type RenderItemFn = dyn FnMut(usize, &mut Window, &mut App) -> AnyElement + 'static;
+5 -2
View File
@@ -22,8 +22,11 @@ pub use conditional::*;
mod conditional {
use super::*;
use crate::{AnyElement, App, Context, Empty, IntoElement, Render, Window};
use collections::{FxHashMap, TypeIdHashMap, hash_map::Entry};
use std::any::{Any, TypeId};
use gpui_util::collections::{FxHashMap, TypeIdHashMap};
use std::{
any::{Any, TypeId},
collections::hash_map::Entry,
};
/// `GlobalElementId` qualified by source location of element construction.
#[derive(Debug, Eq, PartialEq, Hash)]
+1 -1
View File
@@ -53,7 +53,7 @@ use crate::{
Action, ActionRegistry, App, DispatchPhase, EntityId, FocusId, KeyBinding, KeyContext, Keymap,
Keystroke, ModifiersChangedEvent, Window,
};
use collections::FxHashMap;
use gpui_util::collections::FxHashMap;
use smallvec::SmallVec;
use std::{
any::{Any, TypeId},
+2 -2
View File
@@ -5,7 +5,7 @@ pub use binding::*;
pub use context::*;
use crate::{Action, AsKeystroke, Keystroke, Unbind, is_no_action, is_unbind};
use collections::{HashSet, TypeIdHashMap};
use gpui_util::collections::{FxHashSet, TypeIdHashMap};
use smallvec::SmallVec;
/// An opaque identifier of which version of the keymap is currently active.
@@ -253,7 +253,7 @@ impl Keymap {
first_binding_index.get_or_insert(ix);
}
let mut pending = HashSet::default();
let mut pending = FxHashSet::default();
for (ix, binding) in pending_bindings.into_iter().rev() {
if let Some(binding_ix) = first_binding_index
&& binding_ix > ix
+2 -1
View File
@@ -708,6 +708,7 @@ mod tests {
use crate::{
ContentMask, Outline, PaintedPath, Path, PathBuilder, Pixels, Scene, black, px, size,
};
use gpui_util::collections::FxHashMap;
/// A rectangle spanning many cells is four edge strips, four corners and
/// one interior, however many cells it covers.
@@ -810,7 +811,7 @@ mod tests {
("dashed stroke", dashed),
] {
let (curves, _) = builder.outline().unwrap();
let mut balance = collections::HashMap::<(u32, u32), i32>::default();
let mut balance = FxHashMap::<(u32, u32), i32>::default();
for curve in &curves {
for (endpoint, step) in curve.endpoints() {
*balance
+3 -3
View File
@@ -49,8 +49,8 @@ use crate::{
use anyhow::bail;
use anyhow::{Context as _, Result};
use async_task::Runnable;
use collections::FxHashMap;
use futures::channel::oneshot;
use gpui_util::collections::FxHashMap;
#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
use image::RgbaImage;
use image::codecs::{gif::GifDecoder, webp::WebPDecoder};
@@ -3921,7 +3921,7 @@ mod frame_signal_tests {
#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
mod tests {
use super::*;
use std::collections::HashSet;
use gpui_util::collections::FxHashSet;
#[test]
fn test_refresh_interval_from_hz() {
@@ -4056,7 +4056,7 @@ mod tests {
.flatten()
.map(WindowButton::id)
.collect();
let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
let unique_button_ids = button_ids.iter().copied().collect::<FxHashSet<_>>();
assert_eq!(unique_button_ids.len(), button_ids.len());
assert_eq!(layout.format(), "close:maximize,minimize");
}
+3 -3
View File
@@ -1,4 +1,4 @@
use collections::HashMap;
use gpui_util::collections::FxHashMap;
use crate::{KeybindingKeystroke, Keystroke};
@@ -20,7 +20,7 @@ pub trait PlatformKeyboardMapper {
) -> KeybindingKeystroke;
/// Get the key equivalents for the current keyboard layout,
/// only used on macOS
fn get_key_equivalents(&self) -> Option<&HashMap<char, char>>;
fn get_key_equivalents(&self) -> Option<&FxHashMap<char, char>>;
}
/// A dummy implementation of the platform keyboard mapper
@@ -35,7 +35,7 @@ impl PlatformKeyboardMapper for DummyKeyboardMapper {
KeybindingKeystroke::from_keystroke(keystroke)
}
fn get_key_equivalents(&self) -> Option<&HashMap<char, char>> {
fn get_key_equivalents(&self) -> Option<&FxHashMap<char, char>> {
None
}
}
+2 -2
View File
@@ -10,10 +10,10 @@ use crate::{
#[cfg(any(test, feature = "test-support"))]
use crate::{DisplayId, NoopTextSystem, PathPromptOptions};
use anyhow::Result;
#[cfg(any(test, feature = "test-support"))]
use collections::VecDeque;
use futures::channel::oneshot;
use parking_lot::Mutex;
#[cfg(any(test, feature = "test-support"))]
use std::collections::VecDeque;
use std::{
cell::{Cell, RefCell},
path::{Path, PathBuf},
+4 -3
View File
@@ -1,5 +1,6 @@
//! Profiling utilities for task, frame, and thread performance tracking.
use gpui_util::collections::FxHashMap;
#[cfg(feature = "profiler")]
use hdrhistogram::Histogram;
use itertools::Itertools;
@@ -8,7 +9,7 @@ use scheduler::{Instant, SpawnTime};
use smallvec::SmallVec;
use std::{
cell::LazyCell,
collections::{HashMap, VecDeque},
collections::VecDeque,
hash::{DefaultHasher, Hash, Hasher},
sync::{
Arc,
@@ -340,14 +341,14 @@ pub struct ThreadTimingsDelta {
#[doc(hidden)]
pub struct ProfilingCollector {
startup_time: Instant,
cursors: HashMap<ThreadId, u64>,
cursors: FxHashMap<ThreadId, u64>,
}
impl ProfilingCollector {
pub fn new(startup_time: Instant) -> Self {
Self {
startup_time,
cursors: HashMap::default(),
cursors: FxHashMap::default(),
}
}
+5 -4
View File
@@ -12,8 +12,9 @@
//! preceding each boundary into a [`FrameSnapshot`]. The sealer does not infer
//! boundaries from elapsed time or from incidental event kinds such as draws.
use gpui_util::collections::FxHashMap;
use std::cell::{RefCell, UnsafeCell};
use std::collections::{HashMap, VecDeque};
use std::collections::VecDeque;
use std::mem::MaybeUninit;
use std::sync::{
Arc,
@@ -476,7 +477,7 @@ struct ForegroundJournalWriter {
foreground_runnables: ForegroundRunnableCounter,
publisher: JournalPublisher,
turn_depth: usize,
windows: HashMap<WindowId, WindowFrameState>,
windows: FxHashMap<WindowId, WindowFrameState>,
power: PowerState,
power_changed_at: Option<Instant>,
read_suspended_time: fn() -> Option<Duration>,
@@ -491,7 +492,7 @@ impl ForegroundJournalWriter {
foreground_runnables,
publisher,
turn_depth: 0,
windows: HashMap::new(),
windows: FxHashMap::default(),
power: PowerState::Awake,
power_changed_at: None,
read_suspended_time: system_suspended_time,
@@ -2966,7 +2967,7 @@ mod tests {
struct ModelWriter {
turn_depth: usize,
runnables: usize,
pending_frames: HashMap<u64, u64>,
pending_frames: FxHashMap<u64, u64>,
retained_since_boundary: bool,
small_polls: Option<ModelSmallPolls>,
entries: Vec<WriterEntry>,
+3 -3
View File
@@ -467,7 +467,7 @@ impl<T> FusedIterator for TryIter<T> {}
#[cfg(test)]
mod tests {
use collections::HashSet;
use gpui_util::collections::FxHashSet;
use super::*;
@@ -521,8 +521,8 @@ mod tests {
drop(tx);
assert_eq!(
rx.iter().collect::<HashSet<_>>(),
[30, 31, 20, 21, 10].into_iter().collect::<HashSet<_>>()
rx.iter().collect::<FxHashSet<_>>(),
[30, 31, 20, 21, 10].into_iter().collect::<FxHashSet<_>>()
)
}
+20 -20
View File
@@ -8,7 +8,7 @@ use crate::{
TextAlign, TextOverflow, UnderlineStyle, UniformListScrollHandle, WhiteSpace, Window, anchored,
deferred, div, fill, list, point, px, relative, rems, size, uniform_list, util::FluentBuilder,
};
use collections::{HashMap, HashSet};
use gpui_util::collections::{FxHashMap, FxHashSet};
use rand::{Rng as _, SeedableRng as _, rngs::StdRng};
use std::{
cell::RefCell,
@@ -317,7 +317,7 @@ pub struct RandomizedElementTreeSnapshot {
children: Vec<RandomizedElementNode>,
next_element_id: u64,
render_options: RenderOptions,
paths_by_element_id: HashMap<u64, Vec<usize>>,
paths_by_element_id: FxHashMap<u64, Vec<usize>>,
}
impl RandomizedElementTreeSnapshot {
@@ -631,9 +631,9 @@ pub struct RecoloredChildren {
pub struct RandomizedElementTree {
snapshot: Rc<RefCell<RandomizedElementTreeSnapshot>>,
entities: Rc<RefCell<RandomizedElementEntities>>,
scroll_handles: Rc<RefCell<HashMap<u64, crate::ScrollHandle>>>,
list_states: Rc<RefCell<HashMap<u64, (ListState, u64)>>>,
uniform_list_scroll_handles: Rc<RefCell<HashMap<u64, (UniformListScrollHandle, u64)>>>,
scroll_handles: Rc<RefCell<FxHashMap<u64, crate::ScrollHandle>>>,
list_states: Rc<RefCell<FxHashMap<u64, (ListState, u64)>>>,
uniform_list_scroll_handles: Rc<RefCell<FxHashMap<u64, (UniformListScrollHandle, u64)>>>,
work_counters: Rc<RefCell<RandomizedElementTreeWorkCounters>>,
config: RandomizedElementTreeConfig,
rng: StdRng,
@@ -688,13 +688,13 @@ impl RandomizedElementTree {
id_generation: 0,
root_scope: 0,
},
paths_by_element_id: HashMap::default(),
paths_by_element_id: FxHashMap::default(),
};
snapshot.rebuild_element_paths();
Self {
snapshot: Rc::new(RefCell::new(snapshot)),
entities: Rc::new(RefCell::new(HashMap::default())),
entities: Rc::new(RefCell::new(FxHashMap::default())),
scroll_handles: Rc::default(),
list_states: Rc::default(),
uniform_list_scroll_handles: Rc::default(),
@@ -709,7 +709,7 @@ impl RandomizedElementTree {
Self {
config: RandomizedElementTreeConfig::new(0, snapshot.descendant_count()),
snapshot: Rc::new(RefCell::new(snapshot)),
entities: Rc::new(RefCell::new(HashMap::default())),
entities: Rc::new(RefCell::new(FxHashMap::default())),
scroll_handles: Rc::default(),
list_states: Rc::default(),
uniform_list_scroll_handles: Rc::default(),
@@ -1060,7 +1060,7 @@ impl RandomizedElementTree {
let other = self.rng.random_range(index..sample_from.max(index + 1));
paths.swap(index, other);
}
let mut owners = HashSet::default();
let mut owners = FxHashSet::default();
for path in &paths[..count] {
owners.insert(nearest_entity_id(&snapshot.children, path));
if let Some(node) = node_at_path_mut(&mut snapshot.children, path) {
@@ -1231,7 +1231,7 @@ impl RandomizedElementTree {
})
.collect::<Vec<_>>()
};
let entity_id_set = entity_ids.iter().copied().collect::<HashSet<_>>();
let entity_id_set = entity_ids.iter().copied().collect::<FxHashSet<_>>();
self.entities
.borrow_mut()
@@ -1339,7 +1339,7 @@ impl Render for RandomizedElementTree {
}
}
type RandomizedElementEntities = HashMap<u64, Entity<RandomizedElementEntity>>;
type RandomizedElementEntities = FxHashMap<u64, Entity<RandomizedElementEntity>>;
/// Element IDs carry the tree's ID generation above this bit, so churning IDs never
/// changes the element number the low bits identify.
@@ -1358,9 +1358,9 @@ struct RandomizedElementEntity {
element_id: u64,
snapshot: Rc<RefCell<RandomizedElementTreeSnapshot>>,
entities: Weak<RefCell<RandomizedElementEntities>>,
scroll_handles: Rc<RefCell<HashMap<u64, crate::ScrollHandle>>>,
list_states: Rc<RefCell<HashMap<u64, (ListState, u64)>>>,
uniform_list_scroll_handles: Rc<RefCell<HashMap<u64, (UniformListScrollHandle, u64)>>>,
scroll_handles: Rc<RefCell<FxHashMap<u64, crate::ScrollHandle>>>,
list_states: Rc<RefCell<FxHashMap<u64, (ListState, u64)>>>,
uniform_list_scroll_handles: Rc<RefCell<FxHashMap<u64, (UniformListScrollHandle, u64)>>>,
work_counters: Rc<RefCell<RandomizedElementTreeWorkCounters>>,
}
@@ -2347,9 +2347,9 @@ enum RandomizedChildMutation {
fn render_node(
node: &RandomizedElementNode,
entities: &RandomizedElementEntities,
scroll_handles: &RefCell<HashMap<u64, crate::ScrollHandle>>,
list_states: &RefCell<HashMap<u64, (ListState, u64)>>,
uniform_list_scroll_handles: &RefCell<HashMap<u64, (UniformListScrollHandle, u64)>>,
scroll_handles: &RefCell<FxHashMap<u64, crate::ScrollHandle>>,
list_states: &RefCell<FxHashMap<u64, (ListState, u64)>>,
uniform_list_scroll_handles: &RefCell<FxHashMap<u64, (UniformListScrollHandle, u64)>>,
work_counters: &mut RandomizedElementTreeWorkCounters,
options: RenderOptions,
) -> AnyElement {
@@ -2426,9 +2426,9 @@ fn render_rich_text(
fn render_node_body(
node: &RandomizedElementNode,
entities: Option<&RandomizedElementEntities>,
scroll_handles: &RefCell<HashMap<u64, crate::ScrollHandle>>,
list_states: &RefCell<HashMap<u64, (ListState, u64)>>,
uniform_list_scroll_handles: &RefCell<HashMap<u64, (UniformListScrollHandle, u64)>>,
scroll_handles: &RefCell<FxHashMap<u64, crate::ScrollHandle>>,
list_states: &RefCell<FxHashMap<u64, (ListState, u64)>>,
uniform_list_scroll_handles: &RefCell<FxHashMap<u64, (UniformListScrollHandle, u64)>>,
work_counters: &mut RandomizedElementTreeWorkCounters,
options: RenderOptions,
) -> AnyElement {
+5 -7
View File
@@ -11,7 +11,7 @@ use crate::{
PointRefinement, Rgba, SharedString, Size, SizeRefinement, Styled, TextRun, Window, black, phi,
point, px, quad, rems, size,
};
use collections::HashSet;
use gpui_util::collections::FxHashSet;
use refineable::Refineable;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
@@ -1004,7 +1004,7 @@ pub fn combine_highlights(
endpoints.sort_unstable_by_key(|(position, _, _)| *position);
let mut endpoints = endpoints.into_iter().peekable();
let mut active_styles = HashSet::default();
let mut active_styles = FxHashSet::default();
let mut ix = 0;
iter::from_fn(move || {
while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
@@ -1334,9 +1334,7 @@ mod tests {
use super::*;
use util_macros::perf;
#[perf]
#[test]
fn test_basic_highlight_style_combination() {
let style_a = HighlightStyle::default();
let style_b = HighlightStyle::default();
@@ -1421,7 +1419,7 @@ mod tests {
);
}
#[perf]
#[test]
fn test_combine_highlights() {
assert_eq!(
combine_highlights(
@@ -1510,7 +1508,7 @@ mod tests {
);
}
#[perf]
#[test]
fn test_text_style_refinement() {
let mut style = Style::default();
style.refine(&StyleRefinement::default().text_size(px(20.0)));
+1 -1
View File
@@ -1,7 +1,7 @@
use collections::BTreeMap;
use gpui_util::post_inc;
use std::{
cell::{Cell, RefCell},
collections::BTreeMap,
fmt::Debug,
mem,
rc::Rc,
+9 -9
View File
@@ -2,7 +2,7 @@ use crate::{
AssetSource, DevicePixels, IsZero, RenderImage, Result, SharedString, Size,
swap_rgba_pa_to_bgra,
};
use collections::HashMap;
use gpui_util::collections::FxHashMap;
use image::Frame;
use parking_lot::Mutex;
use resvg::tiny_skia::Pixmap;
@@ -161,9 +161,9 @@ impl SvgRenderer {
fix_generic_font_families(&mut db);
Mutex::new(FontDatabase {
database: Arc::new(db),
owned_faces: HashMap::default(),
owned_faces: FxHashMap::default(),
remaining_owned_bytes: MAX_OWNED_FONT_BYTES,
fallback_faces: HashMap::default(),
fallback_faces: FxHashMap::default(),
})
});
if db.is_empty() {
@@ -368,9 +368,9 @@ 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>,
owned_faces: FxHashMap<usvg::fontdb::ID, usvg::fontdb::ID>,
remaining_owned_bytes: u64,
fallback_faces: HashMap<(usvg::fontdb::ID, char), Option<usvg::fontdb::ID>>,
fallback_faces: FxHashMap<(usvg::fontdb::ID, char), Option<usvg::fontdb::ID>>,
}
impl FontDatabase {
@@ -660,9 +660,9 @@ mod tests {
database.load_font_file(&lilex_path)?;
let mut fonts = FontDatabase {
database: Arc::new(database),
owned_faces: HashMap::default(),
owned_faces: FxHashMap::default(),
remaining_owned_bytes: IBM_PLEX_REGULAR.len() as u64,
fallback_faces: HashMap::default(),
fallback_faces: FxHashMap::default(),
};
let mut db = fonts.database.clone();
let face_ids = db.faces().map(|face| face.id).collect::<Vec<_>>();
@@ -690,9 +690,9 @@ mod tests {
let (base, fallback) = (face_ids[0], face_ids[1]);
let fontdb = Mutex::new(FontDatabase {
database: Arc::new(database),
owned_faces: HashMap::default(),
owned_faces: FxHashMap::default(),
remaining_owned_bytes: 0,
fallback_faces: HashMap::default(),
fallback_faces: FxHashMap::default(),
});
let selections = Cell::new(0);
let fallback_face = |ch, fonts: &[usvg::fontdb::ID]| {
+1 -1
View File
@@ -1,6 +1,6 @@
use std::fmt::Debug;
use collections::FxHashMap;
use gpui_util::collections::FxHashMap;
use crate::{FocusHandle, FocusId};
+1 -1
View File
@@ -6,7 +6,7 @@ use crate::{
round_to_device_pixel,
},
};
use collections::{FxHashMap, FxHashSet};
use gpui_util::collections::{FxHashMap, FxHashSet};
use slotmap::{DefaultKey, KeyData, SecondaryMap};
use smallvec::SmallVec;
use std::{any::Any, fmt::Debug, ops::Range};
+4 -2
View File
@@ -17,10 +17,12 @@ use crate::{
StrikethroughStyle, TextRenderingMode, UnderlineStyle, px,
};
use anyhow::Context as _;
use collections::{FxHashMap, FxHashSet};
use core::fmt;
use derive_more::{Add, Deref, FromStr, Sub};
use gpui_util::canonical_float_bits;
use gpui_util::{
canonical_float_bits,
collections::{FxHashMap, FxHashSet},
};
use itertools::Itertools;
use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
use smallvec::{SmallVec, smallvec};
+1 -1
View File
@@ -1,5 +1,5 @@
use crate::{FontId, GlyphId, Pixels, PlatformTextSystem, Point, SharedString, Size, point, px};
use collections::{FxHashMap, FxHashSet};
use gpui_util::collections::{FxHashMap, FxHashSet};
use itertools::Itertools;
use smallvec::SmallVec;
use std::{
+3 -3
View File
@@ -1,5 +1,5 @@
use crate::{FontId, Pixels, SharedString, TextRun, TextSystem, px};
use collections::HashMap;
use gpui_util::collections::FxHashMap;
use std::{borrow::Cow, iter, ops::Range, sync::Arc};
use unicode_segmentation::UnicodeSegmentation;
@@ -38,14 +38,14 @@ pub struct LineWrapper {
/// Cached character widths for one font and size.
pub(crate) struct CharWidthCache {
ascii: [Option<Pixels>; 128],
other: HashMap<char, Pixels>,
other: FxHashMap<char, Pixels>,
}
impl Default for CharWidthCache {
fn default() -> Self {
Self {
ascii: [None; 128],
other: HashMap::default(),
other: FxHashMap::default(),
}
}
}
+1 -1
View File
@@ -6,7 +6,7 @@ use crate::{
};
use crate::{Empty, Window};
use anyhow::Result;
use collections::FxHashSet;
use gpui_util::collections::FxHashSet;
use refineable::Refineable;
use std::mem;
use std::{
+5 -3
View File
@@ -31,11 +31,13 @@ use crate::{
use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecognizer};
use crate::interactive::TouchEvent;
use anyhow::{Context as _, Result, anyhow};
use collections::{FxHashMap, FxHashSet};
use derive_more::{Deref, DerefMut};
use futures::channel::oneshot;
use gpui_util::post_inc;
use gpui_util::{ResultExt, measure};
use gpui_util::{
ResultExt,
collections::{FxHashMap, FxHashSet},
measure, post_inc,
};
use itertools::FoldWhile::{Continue, Done};
use itertools::Itertools;
#[cfg(any(target_os = "macos", target_os = "ios"))]
+2 -2
View File
@@ -104,7 +104,7 @@ pub(crate) mod debug;
use crate::{App, Bounds, FocusId, Pixels, SharedString, Window};
use accesskit::{Action, NodeId, TreeUpdate};
use collections::{FxHashMap, FxHashSet};
use gpui_util::collections::{FxHashMap, FxHashSet};
use smallvec::SmallVec;
use std::hash::{Hash, Hasher};
use std::sync::{
@@ -372,7 +372,7 @@ pub(crate) struct A11yNodeBuilder {
ids_stack: SmallVec<[NodeId; 16]>,
nodes_stack: SmallVec<[accesskit::Node; 16]>,
/// This is the exact type required by accesskit, so we can't just make it a
/// `HashMap<NodeId, Node>` to remove the need for `seen_ids`
/// `FxHashMap<NodeId, Node>` to remove the need for `seen_ids`
all_nodes: Vec<(NodeId, accesskit::Node)>,
seen_ids: FxHashSet<NodeId>,
/// The node that GPUI considers focused. Note that this may be different to
+1 -1
View File
@@ -6,7 +6,7 @@
//! we capture extra info.
use accesskit::{Action, NodeId, TreeUpdate};
use collections::FxHashMap;
use gpui_util::collections::FxHashMap;
use crate::{Pixels, SharedString, Size};
+2 -2
View File
@@ -6,7 +6,7 @@ use crate::{
Style, Styled, Window, div,
};
use anyhow::{Context as _, Result};
use collections::HashSet;
use gpui_util::collections::FxHashSet;
use std::{
any::{Any, TypeId},
cell::{Cell, RefCell},
@@ -76,7 +76,7 @@ pub(crate) struct NativeViewState {
/// The hitbox of the occurrence that shows the view, which is the one
/// painted first in a frame that paints the view more than once.
shown_hitbox: Cell<Option<HitboxId>>,
reserved_actions: RefCell<HashSet<TypeId>>,
reserved_actions: RefCell<FxHashSet<TypeId>>,
_attachment: Box<dyn Any>,
}
-1
View File
@@ -26,7 +26,6 @@ gpui.workspace = true
anyhow.workspace = true
async-task.workspace = true
block2.workspace = true
collections.workspace = true
core-foundation.workspace = true
core-foundation-sys.workspace = true
core-graphics.workspace = true
+10 -10
View File
@@ -1,5 +1,4 @@
use anyhow::anyhow;
use collections::{HashMap, HashSet};
use core_foundation::{
array::{CFArray, CFArrayRef},
attributed_string::CFMutableAttributedString,
@@ -38,6 +37,7 @@ use gpui::{
Result, SUBPIXEL_VARIANTS_X, ShapedGlyph, ShapedRun, SharedString, Size, TextRenderingMode,
point, px, size, swap_rgba_pa_to_bgra,
};
use gpui_util::collections::{FxHashMap, FxHashSet};
use parking_lot::{RwLock, RwLockUpgradableReadGuard};
use pathfinder_geometry::{
rect::{RectF, RectI},
@@ -73,10 +73,10 @@ struct AppleTextSystemState {
memory_source: MemSource,
system_source: SystemSource,
fonts: Vec<FontKitFont>,
font_selections: HashMap<Font, FontId>,
font_ids_by_postscript_name: HashMap<String, FontId>,
font_ids_by_font_key: HashMap<FontKey, SmallVec<[FontId; 4]>>,
postscript_names_by_font_id: HashMap<FontId, String>,
font_selections: FxHashMap<Font, FontId>,
font_ids_by_postscript_name: FxHashMap<String, FontId>,
font_ids_by_font_key: FxHashMap<FontKey, SmallVec<[FontId; 4]>>,
postscript_names_by_font_id: FxHashMap<FontId, String>,
}
impl AppleTextSystem {
@@ -86,10 +86,10 @@ impl AppleTextSystem {
memory_source: MemSource::empty(),
system_source: SystemSource::new(),
fonts: Vec::new(),
font_selections: HashMap::default(),
font_ids_by_postscript_name: HashMap::default(),
font_ids_by_font_key: HashMap::default(),
postscript_names_by_font_id: HashMap::default(),
font_selections: FxHashMap::default(),
font_ids_by_postscript_name: FxHashMap::default(),
font_ids_by_font_key: FxHashMap::default(),
postscript_names_by_font_id: FxHashMap::default(),
}))
}
}
@@ -290,7 +290,7 @@ impl AppleTextSystemState {
let name = gpui::font_name_with_fallbacks(name, ".AppleSystemUIFont");
let mut font_ids = SmallVec::new();
let mut postscript_names_seen = HashSet::default();
let mut postscript_names_seen = FxHashSet::default();
let family = self
.memory_source
.select_family_by_name(name)
-1
View File
@@ -57,7 +57,6 @@ accesskit.workspace = true
accesskit_unix = { workspace = true, optional = true }
anyhow.workspace = true
bytemuck.workspace = true
collections.workspace = true
futures.workspace = true
gpui.workspace = true
gpui_util.workspace = true
+1 -2
View File
@@ -91,7 +91,6 @@ mod tests {
use anyhow::Context as _;
use futures::channel::mpsc;
use std::{
collections::HashMap,
io::{BufRead as _, BufReader},
process::{Child, Stdio},
sync::Arc,
@@ -232,7 +231,7 @@ mod tests {
"PropertiesChanged",
&(
service,
HashMap::from([(
gpui_util::collections::FxHashMap::from_iter([(
"ActiveProfile",
ashpd::zbus::zvariant::Value::from(profile),
)]),
@@ -1,8 +1,8 @@
//! System notifications over the XDG notifications D-Bus interface, via
//! `notify-rust`.
use gpui_util::collections::FxHashMap;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use futures::StreamExt as _;
@@ -44,7 +44,7 @@ impl SystemNotificationState {
.summary(&notification.title)
.body(&notification.body)
.action(DEFAULT_ACTION, DEFAULT_ACTION);
let mut action_ids = HashMap::new();
let mut action_ids = FxHashMap::default();
for (index, action) in notification.actions.iter().enumerate() {
let transport_id = format!("gpui-action-{index}");
builder.action(&transport_id, &action.label);
@@ -120,7 +120,7 @@ impl SystemNotificationState {
fn response_action_id(
transport_id: &str,
action_ids: &HashMap<String, SharedString>,
action_ids: &FxHashMap<String, SharedString>,
) -> Option<Option<SharedString>> {
if transport_id == DEFAULT_ACTION {
Some(None)
@@ -135,7 +135,7 @@ mod tests {
#[test]
fn caller_action_ids_do_not_collide_with_transport_action_ids() {
let action_ids = HashMap::from([
let action_ids = FxHashMap::from_iter([
("gpui-action-0".to_string(), SharedString::from("default")),
("gpui-action-1".to_string(), SharedString::from("__closed")),
]);
+11 -12
View File
@@ -18,9 +18,8 @@ use calloop::{
timer::{TimeoutAction, Timer},
};
use calloop_wayland_source::WaylandSource;
use collections::HashMap;
use filedescriptor::Pipe;
use gpui_util::ResultExt as _;
use gpui_util::{ResultExt as _, collections::FxHashMap};
use http_client::Url;
use smallvec::SmallVec;
use wayland_backend::client::ObjectId;
@@ -376,15 +375,15 @@ pub(crate) struct WaylandClientState {
composing: bool,
last_ime_cursor_rectangle: Option<ImeCursorRectangle>,
// Surface to Window mapping
windows: HashMap<ObjectId, WaylandWindowStatePtr>,
windows: FxHashMap<ObjectId, WaylandWindowStatePtr>,
// Output to scale mapping
outputs: HashMap<ObjectId, Output>,
outputs: FxHashMap<ObjectId, Output>,
// Kept after each `done`, since outputs only resend the properties that
// changed before the next one.
in_progress_outputs: HashMap<ObjectId, InProgressOutput>,
wl_outputs: HashMap<ObjectId, wl_output::WlOutput>,
in_progress_outputs: FxHashMap<ObjectId, InProgressOutput>,
wl_outputs: FxHashMap<ObjectId, wl_output::WlOutput>,
// Registry global names of the outputs, for `global_remove`.
output_globals: HashMap<u32, ObjectId>,
output_globals: FxHashMap<u32, ObjectId>,
keyboard_layout: LinuxKeyboardLayout,
keymap_state: Option<xkb::State>,
compose_state: Option<xkb::compose::State>,
@@ -1001,10 +1000,10 @@ impl WaylandConnection {
let mut seat: Option<wl_seat::WlSeat> = None;
#[allow(clippy::mutable_key_type)]
let mut in_progress_outputs = HashMap::default();
let mut in_progress_outputs = FxHashMap::default();
#[allow(clippy::mutable_key_type)]
let mut wl_outputs: HashMap<ObjectId, wl_output::WlOutput> = HashMap::default();
let mut output_globals: HashMap<u32, ObjectId> = HashMap::default();
let mut wl_outputs: FxHashMap<ObjectId, wl_output::WlOutput> = FxHashMap::default();
let mut output_globals: FxHashMap<u32, ObjectId> = FxHashMap::default();
globals.contents().with_list(|list| -> anyhow::Result<()> {
for global in list {
match &global.interface[..] {
@@ -1080,11 +1079,11 @@ impl WaylandConnection {
ime_pre_edit: None,
composing: false,
last_ime_cursor_rectangle: None,
outputs: HashMap::default(),
outputs: FxHashMap::default(),
in_progress_outputs,
output_globals,
wl_outputs,
windows: HashMap::default(),
windows: FxHashMap::default(),
common,
keyboard_layout: LinuxKeyboardLayout::new(UNKNOWN_KEYBOARD_LAYOUT_NAME),
keymap_state: None,
@@ -1,4 +1,4 @@
use collections::HashMap;
use gpui_util::collections::FxHashMap;
use wayland_client::{Proxy, protocol::wl_surface};
#[derive(Debug, Hash, PartialEq, Eq)]
@@ -44,14 +44,14 @@ struct Press {
#[derive(Debug)]
/// Helper for tracking of different serial kinds.
pub(crate) struct SerialTracker {
serials: HashMap<SerialKind, Serial>,
serials: FxHashMap<SerialKind, Serial>,
latest_press: Option<Press>,
}
impl SerialTracker {
pub fn new() -> Self {
Self {
serials: HashMap::default(),
serials: FxHashMap::default(),
latest_press: None,
}
}
@@ -8,8 +8,8 @@ use std::{
};
use calloop::ping::Ping;
use collections::{FxHashMap, HashMap};
use futures::channel::oneshot::Receiver;
use gpui_util::collections::FxHashMap;
use raw_window_handle as rwh;
use wayland_backend::client::ObjectId;
@@ -112,7 +112,7 @@ pub struct WaylandWindowState {
kde_blur: Option<org_kde_kwin_blur::OrgKdeKwinBlur>,
background_effects: Option<ext_background_effect_surface_v1::ExtBackgroundEffectSurfaceV1>,
viewport: Option<wp_viewport::WpViewport>,
outputs: HashMap<ObjectId, Output>,
outputs: FxHashMap<ObjectId, Output>,
display: Option<(ObjectId, Output)>,
globals: Globals,
/// Taken when the window is dropped. Its GPU objects use the Wayland connection, so they
@@ -616,7 +616,7 @@ impl WaylandWindowState {
background_effects: None,
viewport,
globals,
outputs: HashMap::default(),
outputs: FxHashMap::default(),
display: None,
renderer: Some(renderer),
bounds: options.bounds,
@@ -1422,7 +1422,7 @@ impl WaylandWindowStatePtr {
pub fn handle_surface_event(
&self,
event: wl_surface::Event,
outputs: HashMap<ObjectId, Output>,
outputs: FxHashMap<ObjectId, Output>,
) {
let mut state = self.state.borrow_mut();
+16 -13
View File
@@ -4,16 +4,18 @@ use calloop::{
LoopHandle, RegistrationToken,
generic::{FdWrapper, Generic},
};
use collections::HashMap;
use core::str;
use gpui::{Capslock, GraphicalEnvironment};
use gpui_util::ResultExt as _;
use gpui_util::{
ResultExt as _,
collections::{FxHashMap, FxHashSet},
};
use http_client::Url;
use log::Level;
use smallvec::SmallVec;
use std::{
cell::{RefCell, RefMut},
collections::{BTreeMap, HashSet},
collections::BTreeMap,
ops::Deref,
path::PathBuf,
rc::{Rc, Weak},
@@ -207,7 +209,7 @@ pub struct X11ClientState {
pub(crate) x_root_index: usize,
pub(crate) resource_database: Database,
pub(crate) atoms: XcbAtoms,
pub(crate) windows: HashMap<xproto::Window, WindowRef>,
pub(crate) windows: FxHashMap<xproto::Window, WindowRef>,
pub(crate) mouse_focused_window: Option<xproto::Window>,
pub(crate) keyboard_focused_window: Option<xproto::Window>,
pub(crate) xkb: xkbc::State,
@@ -226,8 +228,8 @@ pub struct X11ClientState {
pub(crate) composing: bool,
pub(crate) pre_key_char_down: Option<Keystroke>,
pub(crate) cursor_handle: cursor::Handle,
pub(crate) cursor_styles: HashMap<xproto::Window, CursorStyle>,
pub(crate) cursor_cache: HashMap<CursorStyle, Option<xproto::Cursor>>,
pub(crate) cursor_styles: FxHashMap<xproto::Window, CursorStyle>,
pub(crate) cursor_cache: FxHashMap<CursorStyle, Option<xproto::Cursor>>,
pub(crate) invisible_cursor_cache: Option<xproto::Cursor>,
pub(crate) cursor_hidden_window: Option<xproto::Window>,
@@ -528,7 +530,7 @@ impl X11Connection {
x_root_index,
resource_database,
atoms,
windows: HashMap::default(),
windows: FxHashMap::default(),
mouse_focused_window: None,
keyboard_focused_window: None,
xkb: xkb_state,
@@ -542,8 +544,8 @@ impl X11Connection {
composing: false,
cursor_handle,
cursor_styles: HashMap::default(),
cursor_cache: HashMap::default(),
cursor_styles: FxHashMap::default(),
cursor_cache: FxHashMap::default(),
cursor_hidden_window: None,
invisible_cursor_cache: None,
@@ -659,7 +661,7 @@ impl X11Client {
) -> Result<(), EventHandlerError> {
loop {
let mut events = Vec::new();
let mut windows_to_refresh = HashSet::new();
let mut windows_to_refresh = FxHashSet::default();
let mut last_key_release = None;
@@ -2776,8 +2778,8 @@ fn legacy_get_randr_scale_factor(connection: &XCBConnection, root: u32) -> Optio
}
}
let mut crtc_infos: HashMap<randr::Crtc, randr::GetCrtcInfoReply> = HashMap::default();
let mut valid_outputs: HashSet<randr::Output> = HashSet::new();
let mut crtc_infos: FxHashMap<randr::Crtc, randr::GetCrtcInfoReply> = FxHashMap::default();
let mut valid_outputs: FxHashSet<randr::Output> = FxHashSet::default();
for (crtc, cookie) in crtc_cookies {
if let Ok(reply) = cookie.reply()
&& reply.width > 0
@@ -2799,7 +2801,8 @@ fn legacy_get_randr_scale_factor(connection: &XCBConnection, root: u32) -> Optio
output_cookies.push((output, cookie));
}
}
let mut output_infos: HashMap<randr::Output, randr::GetOutputInfoReply> = HashMap::default();
let mut output_infos: FxHashMap<randr::Output, randr::GetOutputInfoReply> =
FxHashMap::default();
for (output, cookie) in output_cookies {
if let Ok(reply) = cookie.reply() {
output_infos.insert(output, reply);
+3 -2
View File
@@ -21,7 +21,7 @@
use std::{
borrow::Cow,
cell::RefCell,
collections::{HashMap, hash_map::Entry},
collections::hash_map::Entry,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
@@ -48,6 +48,7 @@ use x11rb::{
};
use gpui::{ClipboardItem, Image, ImageFormat, hash};
use gpui_util::collections::FxHashMap;
use strum::IntoEnumIterator;
type Result<T, E = Error> = std::result::Result<T, E>;
@@ -96,7 +97,7 @@ x11rb::atom_manager! {
}
thread_local! {
static ATOM_NAME_CACHE: RefCell<HashMap<Atom, &'static str>> = Default::default();
static ATOM_NAME_CACHE: RefCell<FxHashMap<Atom, &'static str>> = Default::default();
}
// Some clipboard items, like images, may take a very long time to produce a
+1 -2
View File
@@ -12,8 +12,7 @@ use gpui::{
};
use gpui_wgpu::{CompositorGpuHint, WgpuRenderer, WgpuSurfaceConfig};
use collections::FxHashSet;
use gpui_util::{ResultExt, maybe};
use gpui_util::{ResultExt, collections::FxHashSet, maybe};
use raw_window_handle as rwh;
use x11rb::{
connection::Connection,
-1
View File
@@ -28,7 +28,6 @@ accesskit.workspace = true
accesskit_macos.workspace = true
anyhow.workspace = true
block2.workspace = true
collections.workspace = true
core-foundation.workspace = true
core-foundation-sys.workspace = true
core-graphics.workspace = true
+5 -5
View File
@@ -1,4 +1,4 @@
use collections::HashMap;
use gpui_util::collections::FxHashMap;
use std::ffi::c_void;
use objc2::msg_send;
@@ -16,7 +16,7 @@ pub(crate) struct MacKeyboardLayout {
}
pub(crate) struct MacKeyboardMapper {
key_equivalents: Option<HashMap<char, char>>,
key_equivalents: Option<FxHashMap<char, char>>,
}
impl PlatformKeyboardLayout for MacKeyboardLayout {
@@ -45,7 +45,7 @@ impl PlatformKeyboardMapper for MacKeyboardMapper {
KeybindingKeystroke::from_keystroke(keystroke)
}
fn get_key_equivalents(&self) -> Option<&HashMap<char, char>> {
fn get_key_equivalents(&self) -> Option<&FxHashMap<char, char>> {
self.key_equivalents.as_ref()
}
}
@@ -114,7 +114,7 @@ impl MacKeyboardMapper {
// output to remove languages with no mappings and other oddities, and converting it to a less verbose representation with:
// jq -s 'map(to_entries | map({key: .key, value: [(.value | to_entries | map(.key) | concat()), (.value | to_entries | map(.value) | concat())]}) | from_entries) | add'
// From there I used multi-cursor to produce this match statement.
fn get_key_equivalents(layout_id: &str) -> Option<HashMap<char, char>> {
fn get_key_equivalents(layout_id: &str) -> Option<FxHashMap<char, char>> {
let mappings: &[(char, char)] = match layout_id {
"com.apple.keylayout.ABC-AZERTY" => &[
('!', '1'),
@@ -1504,5 +1504,5 @@ fn get_key_equivalents(layout_id: &str) -> Option<HashMap<char, char>> {
_ => return None,
};
Some(HashMap::from_iter(mappings.iter().cloned()))
Some(FxHashMap::from_iter(mappings.iter().cloned()))
}
+3 -3
View File
@@ -1,11 +1,11 @@
use anyhow::{Result, anyhow};
use block2::RcBlock;
use collections::HashMap;
use futures::channel::oneshot;
use gpui::{
DevicePixels, ForegroundExecutor, ScreenCaptureFrame, ScreenCaptureSource, ScreenCaptureStream,
SharedString, SourceMetadata, size,
};
use gpui_util::collections::FxHashMap;
use objc2::{
AnyThread, DefinedClass, MainThreadMarker, define_class, msg_send,
rc::Retained,
@@ -171,9 +171,9 @@ struct ScreenMeta {
is_main: bool,
}
fn screen_id_to_human_label(marker: MainThreadMarker) -> HashMap<CGDirectDisplayID, ScreenMeta> {
fn screen_id_to_human_label(marker: MainThreadMarker) -> FxHashMap<CGDirectDisplayID, ScreenMeta> {
let screens = NSScreen::screens(marker);
let mut map = HashMap::default();
let mut map = FxHashMap::default();
let screen_number_key = NSString::from_str("NSScreenNumber");
@@ -9,8 +9,8 @@
//! A single worker owns the center so those waits never block the UI, while
//! preserving the order of posting and dismissing notifications.
use gpui_util::collections::FxHashMap;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::mpsc::{Sender, channel};
@@ -165,7 +165,7 @@ struct NotificationCenter {
/// by notifications with identical actions because macOS replaces the
/// entire registered set whenever a category is added.
categories:
HashMap<Vec<SystemNotificationAction>, (SharedString, Retained<UNNotificationCategory>)>,
FxHashMap<Vec<SystemNotificationAction>, (SharedString, Retained<UNNotificationCategory>)>,
authorization_requested: bool,
}
@@ -173,7 +173,7 @@ impl NotificationCenter {
fn new() -> Self {
Self {
center: UNUserNotificationCenter::currentNotificationCenter(),
categories: HashMap::new(),
categories: FxHashMap::default(),
authorization_requested: false,
}
}
+1
View File
@@ -11,6 +11,7 @@ doctest = false
[dependencies]
log = { workspace = true, features = ["serde"] }
anyhow.workspace = true
rustc-hash.workspace = true
[target.'cfg(target_os = "windows")'.dependencies]
which.workspace = true
+7
View File
@@ -0,0 +1,7 @@
use crate::TypeIdHashBuilder;
use std::{any::TypeId, collections};
pub use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet, FxHasher};
pub type TypeIdHashMap<V> = collections::HashMap<TypeId, V, TypeIdHashBuilder>;
pub type TypeIdHashSet = collections::HashSet<TypeId, TypeIdHashBuilder>;
+1
View File
@@ -14,6 +14,7 @@ use std::{
};
pub mod arc_cow;
pub mod collections;
#[cfg(target_os = "windows")]
const CREATE_NO_WINDOW: u32 = 0x0800_0000_u32;
+2
View File
@@ -24,6 +24,7 @@ unicode-segmentation.workspace = true
[target.'cfg(target_family = "wasm")'.dependencies]
gpui.workspace = true
gpui_util.workspace = true
scheduler.workspace = true
parking_lot = { workspace = true, features = ["nightly"] }
gpui_wgpu.workspace = true
@@ -99,6 +100,7 @@ web-sys = { workspace = true, features = [
[dev-dependencies]
anyhow.workspace = true
gpui.workspace = true
gpui_util.workspace = true
smallvec.workspace = true
[package.metadata.cargo-shear]
+3 -2
View File
@@ -1,4 +1,5 @@
use std::{collections::HashMap, rc::Rc};
use gpui_util::collections::FxHashMap;
use std::rc::Rc;
use gpui::{
Capslock, ClipboardEntry, ClipboardItem, ClipboardString, DispatchEventResult, GestureTuning,
@@ -94,7 +95,7 @@ pub(crate) struct ClickState {
#[derive(Default)]
pub(crate) struct TouchIds {
next: u64,
active: HashMap<i32, TouchId>,
active: FxHashMap<i32, TouchId>,
}
impl TouchIds {
+2 -2
View File
@@ -1,6 +1,6 @@
use anyhow::Result;
use gpui::{FontId, GlyphId, SharedString};
use std::collections::HashMap;
use gpui_util::collections::FxHashMap;
#[derive(Clone)]
pub(crate) struct CanvasGlyph {
@@ -12,7 +12,7 @@ pub(crate) struct CanvasGlyph {
#[derive(Default)]
pub(crate) struct GlyphCache {
glyphs: Vec<CanvasGlyph>,
ids_by_font: HashMap<(FontId, bool), HashMap<SharedString, GlyphId>>,
ids_by_font: FxHashMap<(FontId, bool), FxHashMap<SharedString, GlyphId>>,
}
impl GlyphCache {
+5 -4
View File
@@ -8,9 +8,10 @@ use gpui::{
MissingGlyphSink, Pixels, PlatformTextSystem, RenderGlyphParams, SUBPIXEL_VARIANTS_X,
SUBPIXEL_VARIANTS_Y, ShapedGlyph, Size, TextRenderingMode, point, px, size,
};
use gpui_util::collections::FxHashMap;
use gpui_wgpu::CosmicTextSystem;
use parking_lot::RwLock;
use std::{borrow::Cow, collections::HashMap, sync::Arc};
use std::{borrow::Cow, sync::Arc};
// Cosmic's font IDs index its loaded-font vector. Keep browser IDs in a disjoint namespace.
const CANVAS_FONT_BIT: usize = 1 << (usize::BITS - 1);
@@ -25,11 +26,11 @@ pub(crate) struct WebTextSystem {
#[derive(Default)]
struct State {
missing_glyph_sink: Option<Arc<dyn MissingGlyphSink>>,
descriptors: HashMap<FontId, Font>,
descriptors: FxHashMap<FontId, Font>,
canvas_fonts: Vec<Arc<CanvasFont>>,
canvas_font_ids: HashMap<FontId, FontId>,
canvas_font_ids: FxHashMap<FontId, FontId>,
glyphs: GlyphCache,
measurements: HashMap<(FontId, GlyphId, Pixels), CanvasTextMetrics>,
measurements: FxHashMap<(FontId, GlyphId, Pixels), CanvasTextMetrics>,
}
struct CanvasFont {
-1
View File
@@ -22,7 +22,6 @@ test-support = ["gpui/test-support", "dep:image"]
gpui.workspace = true
anyhow.workspace = true
bytemuck.workspace = true
collections.workspace = true
cosmic-text = "0.19.0"
etagere.workspace = true
itertools.workspace = true
+10 -10
View File
@@ -1,5 +1,4 @@
use anyhow::{Context as _, Ok, Result};
use collections::HashMap;
use cosmic_text::{
Attrs, AttrsList, Ellipsize, Family, Font as CosmicTextFont,
FontFeatures as CosmicFontFeatures, FontSystem, ShapeBuffer, ShapeLine, Stretch, Style, Weight,
@@ -11,6 +10,7 @@ use gpui::{
ShapedRun, SharedString, Size, TextRenderingMode, point, size,
};
use gpui_util::collections::FxHashMap;
use itertools::Itertools;
use parking_lot::RwLock;
use smallvec::SmallVec;
@@ -50,13 +50,13 @@ struct CosmicTextSystemState {
font_system: FontSystem,
scratch: ShapeBuffer,
swash_scale_context: ScaleContext,
pending_glyph_images: HashMap<RenderGlyphParams, swash::scale::image::Image>,
pending_glyph_images: FxHashMap<RenderGlyphParams, swash::scale::image::Image>,
/// Contains all already loaded fonts, including all faces. Indexed by `FontId`.
loaded_fonts: Vec<LoadedFont>,
loaded_font_ids_by_key: HashMap<LoadedFontKey, FontId>,
loaded_font_ids_by_key: FxHashMap<LoadedFontKey, FontId>,
/// Caches the `FontId`s associated with a specific family to avoid iterating the font database
/// for every font face in a family.
font_ids_by_family_cache: HashMap<FontKey, SmallVec<[FontId; 4]>>,
font_ids_by_family_cache: FxHashMap<FontKey, SmallVec<[FontId; 4]>>,
system_font_fallback: String,
missing_glyph_sink: Option<Arc<dyn MissingGlyphSink>>,
}
@@ -135,10 +135,10 @@ impl CosmicTextSystem {
font_system,
scratch: ShapeBuffer::default(),
swash_scale_context: ScaleContext::new(),
pending_glyph_images: HashMap::default(),
pending_glyph_images: FxHashMap::default(),
loaded_fonts: Vec::new(),
loaded_font_ids_by_key: HashMap::default(),
font_ids_by_family_cache: HashMap::default(),
loaded_font_ids_by_key: FxHashMap::default(),
font_ids_by_family_cache: FxHashMap::default(),
system_font_fallback: system_font_fallback.to_string(),
missing_glyph_sink: None,
}))
@@ -154,10 +154,10 @@ impl CosmicTextSystem {
font_system,
scratch: ShapeBuffer::default(),
swash_scale_context: ScaleContext::new(),
pending_glyph_images: HashMap::default(),
pending_glyph_images: FxHashMap::default(),
loaded_fonts: Vec::new(),
loaded_font_ids_by_key: HashMap::default(),
font_ids_by_family_cache: HashMap::default(),
loaded_font_ids_by_key: FxHashMap::default(),
font_ids_by_family_cache: FxHashMap::default(),
system_font_fallback: system_font_fallback.to_string(),
missing_glyph_sink: None,
}))
+1 -1
View File
@@ -1,11 +1,11 @@
use crate::{CompositorGpuHint, DeviceErrorState, WgpuAtlas, WgpuContext};
use anyhow::{Context as _, Result};
use bytemuck::{Pod, Zeroable};
use collections::FxHashMap;
use gpui::{
AtlasTextureId, Bounds, DevicePixels, GpuSpecs, PaintedPath, PrimitiveBatch, ScaledPixels,
Scene, Size, get_gamma_correction_ratios, quad_depth, quad_depth_scale,
};
use gpui_util::collections::FxHashMap;
use log::warn;
#[cfg(not(target_family = "wasm"))]
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
-1
View File
@@ -22,7 +22,6 @@ screen-capture = ["gpui/screen-capture", "scap"]
accesskit.workspace = true
accesskit_windows.workspace = true
anyhow.workspace = true
collections.workspace = true
dunce.workspace = true
etagere.workspace = true
futures.workspace = true
+1 -1
View File
@@ -1,7 +1,7 @@
use std::sync::LazyLock;
use anyhow::Result;
use collections::FxHashMap;
use gpui_util::collections::FxHashMap;
use itertools::Itertools;
use windows::Win32::{
Foundation::{HANDLE, HGLOBAL},
+5 -6
View File
@@ -5,8 +5,7 @@ use std::{
};
use anyhow::{Context, Result};
use collections::HashMap;
use gpui_util::{ResultExt, maybe};
use gpui_util::{ResultExt, collections::FxHashMap, maybe};
use parking_lot::{RwLock, RwLockUpgradableReadGuard};
use smallvec::SmallVec;
use windows::{
@@ -62,8 +61,8 @@ struct DirectWriteState {
system_font_collection: IDWriteFontCollection1,
custom_font_collection: IDWriteFontCollection1,
fonts: Vec<FontInfo>,
font_to_font_id: HashMap<Font, FontId>,
font_info_cache: HashMap<usize, FontId>,
font_to_font_id: FxHashMap<Font, FontId>,
font_info_cache: FxHashMap<usize, FontId>,
layout_line_scratch: Vec<u16>,
}
@@ -113,8 +112,8 @@ impl DirectWriteTextSystem {
system_font_collection,
custom_font_collection,
fonts: Vec::new(),
font_to_font_id: HashMap::default(),
font_info_cache: HashMap::default(),
font_to_font_id: FxHashMap::default(),
font_info_cache: FxHashMap::default(),
layout_line_scratch: Vec::new(),
}),
})
+8 -8
View File
@@ -1,5 +1,5 @@
use anyhow::Result;
use collections::HashMap;
use gpui_util::collections::FxHashMap;
use windows::Win32::UI::{
Input::KeyboardAndMouse::{
GetKeyboardLayoutNameW, MAPVK_VK_TO_CHAR, MAPVK_VK_TO_VSC, MapVirtualKeyW, ToUnicode,
@@ -20,9 +20,9 @@ pub(crate) struct WindowsKeyboardLayout {
}
pub(crate) struct WindowsKeyboardMapper {
key_to_vkey: HashMap<String, (u16, bool)>,
vkey_to_key: HashMap<u16, String>,
vkey_to_shifted: HashMap<u16, String>,
key_to_vkey: FxHashMap<String, (u16, bool)>,
vkey_to_key: FxHashMap<u16, String>,
vkey_to_shifted: FxHashMap<u16, String>,
}
impl PlatformKeyboardLayout for WindowsKeyboardLayout {
@@ -85,7 +85,7 @@ impl PlatformKeyboardMapper for WindowsKeyboardMapper {
KeybindingKeystroke::new(keystroke, modifiers, key)
}
fn get_key_equivalents(&self) -> Option<&HashMap<char, char>> {
fn get_key_equivalents(&self) -> Option<&FxHashMap<char, char>> {
None
}
}
@@ -112,9 +112,9 @@ impl WindowsKeyboardLayout {
impl WindowsKeyboardMapper {
pub(crate) fn new() -> Self {
let mut key_to_vkey = HashMap::default();
let mut vkey_to_key = HashMap::default();
let mut vkey_to_shifted = HashMap::default();
let mut key_to_vkey = FxHashMap::default();
let mut vkey_to_key = FxHashMap::default();
let mut vkey_to_shifted = FxHashMap::default();
for vkey in CANDIDATE_VKEYS {
if let Some(key) = get_key_from_vkey(*vkey) {
key_to_vkey.insert(key.clone(), (vkey.0, false));
@@ -1,7 +1,8 @@
//! System notifications as Windows toast notifications.
use gpui_util::collections::FxHashMap;
use std::cell::RefCell;
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash as _, Hasher as _};
use std::rc::Rc;
@@ -21,7 +22,7 @@ type ResponseCallback = Rc<RefCell<Option<Box<dyn FnMut(SystemNotificationRespon
pub(crate) struct SystemNotificationState {
notifier: Option<ToastNotifier>,
active_toasts: HashMap<SharedString, ToastNotification>,
active_toasts: FxHashMap<SharedString, ToastNotification>,
response_sender: mpsc::UnboundedSender<SystemNotificationResponse>,
response_receiver: Option<mpsc::UnboundedReceiver<SystemNotificationResponse>>,
callback: ResponseCallback,
@@ -33,7 +34,7 @@ impl SystemNotificationState {
let (response_sender, response_receiver) = mpsc::unbounded();
Self {
notifier: None,
active_toasts: HashMap::new(),
active_toasts: FxHashMap::default(),
response_sender,
response_receiver: Some(response_receiver),
callback: Rc::new(RefCell::new(None)),
+1 -8
View File
@@ -16,20 +16,13 @@ doctest = false
[dependencies]
heapless.workspace = true
rayon.workspace = true
ztracing.workspace = true
tracing.workspace = true
proptest = { workspace = true, optional = true }
[dev-dependencies]
log.workspace = true
ctor.workspace = true
env_logger.workspace = true
rand.workspace = true
proptest.workspace = true
zlog.workspace = true
[package.metadata.cargo-shear]
ignored = ["tracing"]
[features]
test-support = ["proptest"]
-5
View File
@@ -1,7 +1,6 @@
use super::*;
use heapless::Vec as ArrayVec;
use std::{cmp::Ordering, mem, sync::Arc};
use ztracing::instrument;
#[derive(Clone)]
struct StackEntry<'a, T: Item, D> {
@@ -212,7 +211,6 @@ where
}
#[track_caller]
#[instrument(skip_all)]
pub fn prev(&mut self) {
self.search_backward(|_| true)
}
@@ -404,7 +402,6 @@ where
{
/// Returns whether we found the item you were seeking for.
#[track_caller]
#[instrument(skip_all)]
pub fn seek<Target>(&mut self, pos: &Target, bias: Bias) -> bool
where
Target: SeekTarget<'a, T::Summary, D>,
@@ -419,7 +416,6 @@ where
///
/// If we did not seek before, use seek instead in that case.
#[track_caller]
#[instrument(skip_all)]
pub fn seek_forward<Target>(&mut self, pos: &Target, bias: Bias) -> bool
where
Target: SeekTarget<'a, T::Summary, D>,
@@ -461,7 +457,6 @@ where
/// Returns whether we found the item you were seeking for.
#[track_caller]
#[instrument(skip_all)]
fn seek_internal(
&mut self,
target: &dyn SeekTarget<'a, T::Summary, D>,
+1 -9
View File
@@ -10,7 +10,6 @@ use std::marker::PhantomData;
use std::mem;
use std::{cmp::Ordering, fmt, iter::FromIterator, sync::Arc};
pub use tree_map::{MapSeekTarget, TreeMap, TreeSet};
use ztracing::instrument;
#[cfg(test)]
pub const TREE_BASE: usize = 2;
@@ -395,7 +394,6 @@ impl<T: Item> SumTree<T> {
/// A more efficient version of `Cursor::new()` + `Cursor::seek()` + `Cursor::item()`.
///
/// Only returns the item that exactly has the target match.
#[instrument(skip_all)]
pub fn find_exact<'a, 'slf, D, Target>(
&'slf self,
cx: <T::Summary as Summary>::Context<'a>,
@@ -421,7 +419,6 @@ impl<T: Item> SumTree<T> {
}
/// A more efficient version of `Cursor::new()` + `Cursor::seek()` + `Cursor::item()`
#[instrument(skip_all)]
pub fn find<'a, 'slf, D, Target>(
&'slf self,
cx: <T::Summary as Summary>::Context<'a>,
@@ -506,7 +503,6 @@ impl<T: Item> SumTree<T> {
}
/// A more efficient version of `Cursor::new()` + `Cursor::seek()` + `Cursor::item()`
#[instrument(skip_all)]
pub fn find_with_prev<'a, 'slf, D, Target>(
&'slf self,
cx: <T::Summary as Summary>::Context<'a>,
@@ -1560,11 +1556,6 @@ mod tests {
use rand::{distr::StandardUniform, prelude::*};
use std::cmp;
#[ctor::ctor(unsafe)]
fn init_logger() {
zlog::init_test();
}
#[test]
fn test_extend_and_push_tree() {
let mut tree1 = SumTree::default();
@@ -1579,6 +1570,7 @@ mod tests {
#[test]
fn test_random() {
env_logger::builder().is_test(true).init();
let mut starting_seed = 0;
if let Ok(value) = std::env::var("SEED") {
starting_seed = value.parse().expect("invalid SEED variable");