Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Improve icon handling on startup (#65173)
Kirill Bulatov6110aa61e1da
diff --git a/crates/project_panel/src/project_panel.rs b/crates/project_panel/src/project_panel.rsindex e456d7b2fea..ecbf0bd90c4 100644--- a/crates/project_panel/src/project_panel.rs+++ b/crates/project_panel/src/project_panel.rs@@ -4855,6 +4855,7 @@ impl ProjectPanel {this.update_visible_entries_task.autoscroll = false;this.autoscroll(cx);}+ this.preload_initial_entry_icons(window, cx);cx.notify();}).ok();@@ -4868,6 +4869,77 @@ impl ProjectPanel {};}+ fn preload_initial_entry_icons(&self, window: &Window, cx: &mut Context<Self>) {+ if self.state.edit_state.is_some() {+ return;+ }+ {+ let scroll = self.scroll_handle.0.borrow();+ if scroll+ .last_item_size+ .is_some_and(|size| size.contents.height > Pixels::ZERO)+ || scroll.base_handle.offset().y != Pixels::ZERO+ || scroll.deferred_scroll_to_item.is_some()+ {+ return;+ }+ }++ let Some(workspace) = Workspace::for_window(window, cx)+ .filter(|workspace| workspace.entity_id() == self.workspace.entity_id())+ else {+ return;+ };+ let workspace = workspace.read(cx);+ let panel_id = cx.entity_id();+ if workspace+ .zoomed_item()+ .and_then(|view| view.upgrade())+ .is_some_and(|view| view.entity_id() != panel_id)+ || !workspace.all_docks().into_iter().any(|dock| {+ dock.read(cx)+ .visible_panel()+ .is_some_and(|panel| panel.panel_id() == panel_id)+ })+ {+ return;+ }++ let scale_factor = window.scale_factor();+ if !scale_factor.is_finite() || scale_factor <= 0.0 {+ return;+ }+ let font_size = ThemeSettings::get_global(cx).ui_font_size(cx).as_f32();+ let minimum_row_height = (1.5 * font_size * scale_factor).floor() / scale_factor;+ let row_count = (window.viewport_size().height.as_f32() / minimum_row_height).ceil();+ if minimum_row_height <= 0.0 || !row_count.is_finite() || row_count <= 0.0 {+ return;+ }+ let row_count = (row_count as usize).saturating_add(1);+ for (worktree_id, entry) in self+ .state+ .visible_entries+ .iter()+ .flat_map(|worktree| {+ worktree+ .entries+ .iter()+ .map(move |entry| (worktree.worktree_id, entry))+ })+ .take(row_count)+ {+ let is_expanded = self+ .state+ .expanded_dir_ids+ .get(&worktree_id)+ .is_some_and(|entries| entries.binary_search(&entry.id).is_ok());+ let (chevron, icon) = Self::entry_icons(entry, is_expanded, cx);+ for path in chevron.into_iter().chain(icon) {+ Icon::from_path(path).preload(cx);+ }+ }+ }+fn expand_entry(&mut self,worktree_id: WorktreeId,@@ -6948,6 +7020,33 @@ impl ProjectPanel {)}+ fn entry_icons(+ entry: &Entry,+ is_expanded: bool,+ cx: &App,+ ) -> (Option<SharedString>, Option<SharedString>) {+ let settings = ProjectPanelSettings::get_global(cx);+ match entry.kind {+ EntryKind::File => {+ let icon = if settings.file_icons {+ FileIcons::get_icon(entry.path.as_std_path(), cx)+ } else {+ None+ };+ (None, icon)+ }+ _ => {+ let indicator = FileIcons::get_folder_indicators(+ settings.folder_indicator,+ is_expanded,+ entry.path.as_std_path(),+ cx,+ );+ (indicator.chevron, indicator.icon)+ }+ }+ }+fn details_for_entry(&self,entry: &Entry,@@ -6959,10 +7058,7 @@ impl ProjectPanel {_window: &mut Window,cx: &mut Context<Self>,) -> EntryDetails {- let (show_file_icons, folder_indicator) = {- let settings = ProjectPanelSettings::get_global(cx);- (settings.file_icons, settings.folder_indicator)- };+ let folder_indicator = ProjectPanelSettings::get_global(cx).folder_indicator;let expanded_entry_ids = self.state@@ -6972,25 +7068,7 @@ impl ProjectPanel {.unwrap_or(&[]);let is_expanded = expanded_entry_ids.binary_search(&entry.id).is_ok();- let (chevron, icon) = match entry.kind {- EntryKind::File => {- let icon = if show_file_icons {- FileIcons::get_icon(entry.path.as_std_path(), cx)- } else {- None- };- (None, icon)- }- _ => {- let indicator = FileIcons::get_folder_indicators(- folder_indicator,- is_expanded,- entry.path.as_std_path(),- cx,- );- (indicator.chevron, indicator.icon)- }- };+ let (chevron, icon) = Self::entry_icons(entry, is_expanded, cx);let path_style = self.project.read(cx).path_style(cx);let (depth, difference) =@@ -8155,6 +8233,14 @@ impl Panel for ProjectPanel {})}+ fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {+ if active {+ cx.defer_in(window, |panel, window, cx| {+ panel.preload_initial_entry_icons(window, cx);+ });+ }+ }+fn activation_priority(&self) -> u32 {1}diff --git a/crates/theme/src/registry.rs b/crates/theme/src/registry.rsindex 6d8ae4ab863..dcbf61da6f6 100644--- a/crates/theme/src/registry.rs+++ b/crates/theme/src/registry.rs@@ -1,5 +1,8 @@use std::sync::Arc;-use std::{fmt::Debug, path::Path};+use std::{+ fmt::Debug,+ path::{Path, PathBuf},+};use anyhow::Result;use collections::HashMap;@@ -9,7 +12,7 @@ use thiserror::Error;use crate::{Appearance, AppearanceContent, ChevronIcons, DEFAULT_ICON_THEME_NAME, DirectoryIcons,- IconDefinition, IconTheme, IconThemeFamilyContent, Theme, ThemeFamily, default_icon_theme,+ IconDefinition, IconTheme, Theme, ThemeFamily, default_icon_theme, deserialize_icon_theme,};/// The metadata for a theme.@@ -59,6 +62,7 @@ impl Global for GlobalThemeRegistry {}struct ThemeRegistryState {themes: HashMap<SharedString, Arc<Theme>>,icon_themes: HashMap<SharedString, Arc<IconTheme>>,+ loaded_icon_theme: Option<LoadedIconTheme>,/// Whether the extensions have been loaded yet.extensions_loaded: bool,}@@ -69,6 +73,12 @@ pub struct ThemeRegistry {assets: Box<dyn AssetSource>,}+struct LoadedIconTheme {+ path: PathBuf,+ icons_root_dir: PathBuf,+ contents: Vec<u8>,+}+impl ThemeRegistry {/// Returns the global [`ThemeRegistry`].pub fn global(cx: &App) -> Arc<Self> {@@ -103,6 +113,7 @@ impl ThemeRegistry {state: RwLock::new(ThemeRegistryState {themes: HashMap::default(),icon_themes: HashMap::default(),+ loaded_icon_theme: None,extensions_loaded: false,}),assets,@@ -129,7 +140,9 @@ impl ThemeRegistry {/// Sets the flag indicating that the extensions have loaded.pub fn set_extensions_loaded(&self) {- self.state.write().extensions_loaded = true;+ let mut state = self.state.write();+ state.extensions_loaded = true;+ state.loaded_icon_theme = None;}/// Inserts the given theme families into the registry.@@ -149,6 +162,7 @@ impl ThemeRegistry {#[cfg(any(test, feature = "test-support"))]pub fn register_test_icon_themes(&self, icon_themes: impl IntoIterator<Item = IconTheme>) {let mut state = self.state.write();+ state.loaded_icon_theme = None;for icon_theme in icon_themes {state.icon_themes@@ -237,8 +251,11 @@ impl ThemeRegistry {/// Removes the icon themes with the given names from the registry.pub fn remove_icon_themes(&self, icon_themes_to_remove: &[SharedString]) {- self.state- .write()+ let mut state = self.state.write();+ if !icon_themes_to_remove.is_empty() {+ state.loaded_icon_theme = None;+ }+ state.icon_themes.retain(|name, _| !icon_themes_to_remove.contains(name))}@@ -249,9 +266,25 @@ impl ThemeRegistry {/// the relative paths to icons in the theme should be resolved against.pub fn load_icon_theme(&self,- icon_theme_family: IconThemeFamilyContent,+ path: &Path,icons_root_dir: &Path,+ contents: Vec<u8>,) -> Result<()> {+ if self+ .state+ .read()+ .loaded_icon_theme+ .as_ref()+ .is_some_and(|loaded| {+ loaded.path == path+ && loaded.icons_root_dir == icons_root_dir+ && loaded.contents == contents+ })+ {+ return Ok(());+ }++ let icon_theme_family = deserialize_icon_theme(&contents)?;let resolve_icon_path = |path: SharedString| {icons_root_dir.join(path.as_ref())@@ -319,6 +352,11 @@ impl ThemeRegistry {.icon_themes.insert(icon_theme.name.clone(), Arc::new(icon_theme));}+ state.loaded_icon_theme = (!state.extensions_loaded).then(|| LoadedIconTheme {+ path: path.to_path_buf(),+ icons_root_dir: icons_root_dir.to_path_buf(),+ contents,+ });Ok(())}diff --git a/crates/theme_extension/src/theme_extension.rs b/crates/theme_extension/src/theme_extension.rsindex 85351a91f37..cba49a616af 100644--- a/crates/theme_extension/src/theme_extension.rs+++ b/crates/theme_extension/src/theme_extension.rs@@ -1,11 +1,11 @@use std::path::PathBuf;use std::sync::Arc;-use anyhow::Result;+use anyhow::{Context as _, Result};use extension::{ExtensionHostProxy, ExtensionThemeProxy};use fs::Fs;use gpui::{App, BackgroundExecutor, SharedString, Task};-use theme::{ThemeRegistry, deserialize_icon_theme};+use theme::ThemeRegistry;use theme_settings;pub fn init(@@ -31,8 +31,11 @@ impl ExtensionThemeProxy for ThemeRegistryProxy {fn list_theme_names(&self, theme_path: PathBuf, fs: Arc<dyn Fs>) -> Task<Result<Vec<String>>> {self.executor.spawn(async move {- let themes =- theme_settings::deserialize_user_theme(&fs.load_bytes(&theme_path).await?)?;+ let contents = fs+ .load_bytes(&theme_path)+ .await+ .with_context(|| format!("loading theme bytes from {theme_path:?}"))?;+ let themes = theme_settings::deserialize_user_theme(&contents)?;Ok(themes.themes.into_iter().map(|theme| theme.name).collect())})}@@ -44,7 +47,11 @@ impl ExtensionThemeProxy for ThemeRegistryProxy {fn load_user_theme(&self, theme_path: PathBuf, fs: Arc<dyn Fs>) -> Task<Result<()>> {let theme_registry = self.theme_registry.clone();self.executor.spawn(async move {- theme_settings::load_user_theme(&theme_registry, &fs.load_bytes(&theme_path).await?)+ let contents = fs+ .load_bytes(&theme_path)+ .await+ .with_context(|| format!("loading theme bytes from {theme_path:?}"))?;+ theme_settings::load_user_theme(&theme_registry, &contents)})}@@ -58,8 +65,11 @@ impl ExtensionThemeProxy for ThemeRegistryProxy {fs: Arc<dyn Fs>,) -> Task<Result<Vec<String>>> {self.executor.spawn(async move {- let icon_theme_family =- theme::deserialize_icon_theme(&fs.load_bytes(&icon_theme_path).await?)?;+ let contents = fs+ .load_bytes(&icon_theme_path)+ .await+ .with_context(|| format!("loading icon bytes from {icon_theme_path:?}"))?;+ let icon_theme_family = theme::deserialize_icon_theme(&contents)?;Ok(icon_theme_family.themes.into_iter()@@ -80,9 +90,11 @@ impl ExtensionThemeProxy for ThemeRegistryProxy {) -> Task<Result<()>> {let theme_registry = self.theme_registry.clone();self.executor.spawn(async move {- let icon_theme_family =- deserialize_icon_theme(&fs.load_bytes(&icon_theme_path).await?)?;- theme_registry.load_icon_theme(icon_theme_family, &icons_root_dir)+ let contents = fs+ .load_bytes(&icon_theme_path)+ .await+ .with_context(|| format!("loading icon bytes from {icon_theme_path:?}"))?;+ theme_registry.load_icon_theme(&icon_theme_path, &icons_root_dir, contents)})}diff --git a/crates/ui/src/components/icon.rs b/crates/ui/src/components/icon.rsindex 26659006466..8935e181afd 100644--- a/crates/ui/src/components/icon.rs+++ b/crates/ui/src/components/icon.rs@@ -5,7 +5,10 @@ use std::path::{Path, PathBuf};use std::sync::Arc;pub use decorated_icon::*;-use gpui::{AnimationElement, AnyElement, Hsla, IntoElement, Rems, Transformation, img, svg};+use gpui::{+ AnimationElement, AnyElement, Hsla, ImgResourceLoader, IntoElement, Rems, Resource,+ Transformation, img, svg,+};pub use icon_decoration::*;pub use icons::*;@@ -186,6 +189,12 @@ impl Icon {}}+ pub fn preload(&self, cx: &mut App) {+ if let IconSource::External(path) = &self.source {+ drop(cx.fetch_asset::<ImgResourceLoader>(&Resource::Path(path.clone())));+ }+ }+pub fn color(mut self, color: Color) -> Self {self.color = color;selfdiff --git a/crates/zed/src/main.rs b/crates/zed/src/main.rsindex f720fefad6c..c3bde91b04d 100644--- a/crates/zed/src/main.rs+++ b/crates/zed/src/main.rs@@ -1924,7 +1924,12 @@ fn load_user_themes_in_background(fs: Arc<dyn fs::Fs>, cx: &mut App) {let Some(theme_path) = theme_path.log_err() else {continue;};- let Some(bytes) = fs.load_bytes(&theme_path).await.log_err() else {+ let Some(bytes) = fs+ .load_bytes(&theme_path)+ .await+ .with_context(|| format!("loading theme bytes from {theme_path:?}"))+ .log_err()+ else {continue;};@@ -1956,7 +1961,11 @@ fn watch_themes(fs: Arc<dyn fs::Fs>, cx: &mut App) {.is_some_and(|m| !m.is_dir){let theme_registry = cx.update(|cx| ThemeRegistry::global(cx));- if let Some(bytes) = fs.load_bytes(&event.path).await.log_err()+ if let Some(bytes) = fs+ .load_bytes(&event.path)+ .await+ .with_context(|| format!("loading theme bytes from {:?}", event.path))+ .log_err()&& load_user_theme(&theme_registry, &bytes).log_err().is_some(){cx.update(theme_settings::reload_theme);diff --git a/crates/zed/src/zed.rs b/crates/zed/src/zed.rsindex a5d947b9675..3f20c8cf24f 100644--- a/crates/zed/src/zed.rs+++ b/crates/zed/src/zed.rs@@ -88,7 +88,7 @@ use std::{sync::atomic::{self, AtomicBool},};use terminal_view::terminal_panel::{self, TerminalPanel};-use theme::{ActiveTheme, SystemAppearance, ThemeRegistry, deserialize_icon_theme};+use theme::{ActiveTheme, SystemAppearance, ThemeRegistry};use theme_settings::{ThemeSettings, load_user_theme};use ui::{Navigable, NavigableEntry, PopoverMenuHandle, TintColor, prelude::*};use util::markdown::MarkdownString;@@ -2833,18 +2833,24 @@ pub(crate) fn eager_load_active_theme_and_icon_theme(fs: Arc<dyn Fs>, cx: &mut Ascope.spawn(async move {match load_target {LoadTarget::Theme(theme_path) => {- if let Some(bytes) = fs.load_bytes(&theme_path).await.log_err()+ if let Some(bytes) = fs+ .load_bytes(&theme_path)+ .await+ .with_context(|| format!("loading theme bytes from {theme_path:?}"))+ .log_err()&& load_user_theme(theme_registry, &bytes).log_err().is_some(){reload_tasks.lock().push(ReloadTarget::Theme);}}LoadTarget::IconTheme((icon_theme_path, icons_root_path)) => {- if let Some(bytes) = fs.load_bytes(&icon_theme_path).await.log_err()- && let Some(icon_theme_family) =- deserialize_icon_theme(&bytes).log_err()+ if let Some(bytes) = fs+ .load_bytes(&icon_theme_path)+ .await+ .with_context(|| format!("loading icon bytes from {icon_theme_path:?}"))+ .log_err()&& theme_registry- .load_icon_theme(icon_theme_family, &icons_root_path)+ .load_icon_theme(&icon_theme_path, &icons_root_path, bytes).log_err().is_some(){