fix assets

This commit is contained in:
2026-08-31 17:51:31 +07:00
parent 963a641f39
commit 070c6a7e87
9 changed files with 433 additions and 57 deletions
+8
View File
@@ -8,4 +8,12 @@ publish.workspace = true
gpui.workspace = true
anyhow.workspace = true
log.workspace = true
[target.'cfg(not(target_family = "wasm"))'.dependencies]
rust-embed.workspace = true
[target.'cfg(target_family = "wasm")'.dependencies]
futures.workspace = true
reqwest = { version = "0.12", default-features = false }
wasm-bindgen-futures = "0.4"
web-sys = { version = "0.3", features = ["Window", "Location"] }
+58
View File
@@ -0,0 +1,58 @@
//! Generates a compile-time manifest of the asset files served on wasm, so
//! the web entrypoint can preload them before the first frame.
//!
//! `WASM_ASSETS` is emitted into `OUT_DIR` and included by
//! `src/wasm_assets.rs` on wasm targets. Native builds keep using
//! `rust-embed` and ignore it.
use std::path::Path;
use std::{env, fs};
fn main() {
let manifest_dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set by cargo");
let assets_dir = Path::new(&manifest_dir).join("../../assets");
let mut paths = Vec::new();
for dir in ["icons", "brand"] {
let dir_path = assets_dir.join(dir);
let entries = fs::read_dir(&dir_path).unwrap_or_else(|error| {
panic!(
"expected asset directory {} to exist: {error}",
dir_path.display()
)
});
for entry in entries {
let entry = entry.expect("failed to read asset directory entry");
if entry.file_type().is_ok_and(|t| t.is_file()) {
let name = entry.file_name().to_string_lossy().into_owned();
if !name.starts_with('.') {
paths.push(format!("{dir}/{name}"));
}
}
}
}
paths.sort();
let manifest = format!(
"/// Asset files served by the wasm asset loader. Generated by build.rs.\npub const WASM_ASSETS: &[&str] = &[\n{}\n];\n",
paths
.iter()
.map(|path| format!(" \"{path}\","))
.collect::<Vec<_>>()
.join("\n")
);
let out_dir = env::var("OUT_DIR").expect("OUT_DIR not set by cargo");
fs::write(Path::new(&out_dir).join("wasm_assets.rs"), manifest)
.expect("failed to write wasm asset manifest");
// Rerun when the asset files change (adding/removing files updates the
// directory mtime).
for dir in ["icons", "brand"] {
if let Ok(canonical) = assets_dir.join(dir).canonicalize() {
println!("cargo:rerun-if-changed={}", canonical.display());
}
}
println!("cargo:rerun-if-changed=build.rs");
}
+16 -48
View File
@@ -1,51 +1,19 @@
use anyhow::Context;
use gpui::{App, AssetSource, Result, SharedString};
use rust_embed::RustEmbed;
//! Application assets for Coop.
//!
//! ## Platform differences
//!
//! - **Native (desktop)**: assets are embedded into the binary at compile time
//! with `rust-embed`.
//! - **WASM (web)**: assets are downloaded on demand from `{endpoint}/assets/{path}`
//! and cached in memory. This keeps the WASM bundle size small.
#[derive(RustEmbed)]
#[folder = "../../assets"]
#[include = "fonts/**/*"]
#[include = "brand/**/*"]
#[include = "icons/**/*"]
#[include = "themes/**/*"]
#[exclude = "*.DS_Store"]
pub struct Assets;
#[cfg(not(target_family = "wasm"))]
mod native_assets;
impl AssetSource for Assets {
fn load(&self, path: &str) -> Result<Option<std::borrow::Cow<'static, [u8]>>> {
Self::get(path)
.map(|f| Some(f.data))
.with_context(|| format!("loading asset at path {path:?}"))
}
#[cfg(target_family = "wasm")]
mod wasm_assets;
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
Ok(Self::iter()
.filter_map(|p| {
if p.starts_with(path) {
Some(p.into())
} else {
None
}
})
.collect())
}
}
impl Assets {
/// Populate the [`TextSystem`] of the given [`AppContext`] with all `.ttf` fonts in the `fonts` directory.
pub fn load_fonts(&self, cx: &App) -> anyhow::Result<()> {
let font_paths = self.list("fonts")?;
let mut embedded_fonts = Vec::new();
for font_path in font_paths {
if font_path.ends_with(".ttf") {
let font_bytes = cx
.asset_source()
.load(&font_path)?
.expect("Assets should never return None");
embedded_fonts.push(font_bytes);
}
}
cx.text_system().add_fonts(embedded_fonts)
}
}
#[cfg(not(target_family = "wasm"))]
pub use native_assets::Assets;
#[cfg(target_family = "wasm")]
pub use wasm_assets::Assets;
+63
View File
@@ -0,0 +1,63 @@
use std::borrow::Cow;
use anyhow::Context;
use gpui::{App, AssetSource, Result, SharedString};
use rust_embed::RustEmbed;
/// Native implementation using `rust-embed`: assets are embedded into the
/// binary at compile time.
#[derive(RustEmbed)]
#[folder = "../../assets"]
#[include = "fonts/**/*"]
#[include = "brand/**/*"]
#[include = "icons/**/*"]
#[include = "themes/**/*"]
#[exclude = "*.DS_Store"]
pub struct Assets;
impl Assets {
/// Create a new Assets instance. The endpoint parameter is ignored for
/// native builds.
pub fn new(_endpoint: impl Into<SharedString>) -> Self {
Self
}
}
impl AssetSource for Assets {
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
Self::get(path)
.map(|f| Some(f.data))
.with_context(|| format!("loading asset at path {path:?}"))
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
Ok(Self::iter()
.filter_map(|p| {
if p.starts_with(path) {
Some(p.into())
} else {
None
}
})
.collect())
}
}
impl Assets {
/// Populate the [`TextSystem`] of the given [`AppContext`] with all `.ttf` fonts in the `fonts` directory.
pub fn load_fonts(&self, cx: &App) -> anyhow::Result<()> {
let font_paths = self.list("fonts")?;
let mut embedded_fonts = Vec::new();
for font_path in font_paths {
if font_path.ends_with(".ttf") {
let font_bytes = cx
.asset_source()
.load(&font_path)?
.expect("Assets should never return None");
embedded_fonts.push(font_bytes);
}
}
cx.text_system().add_fonts(embedded_fonts)
}
}
+176
View File
@@ -0,0 +1,176 @@
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use gpui::{AssetSource, Result, SharedString};
use wasm_bindgen_futures::spawn_local;
// Compile-time manifest of every asset file served on wasm (see build.rs).
include!(concat!(env!("OUT_DIR"), "/wasm_assets.rs"));
/// Path prefixes that the wasm loader serves. Fonts and themes are not
/// downloaded on web: the web platform bundles its own fonts, and the theme
/// registry falls back to the built-in default theme.
const SERVED_PREFIXES: [&str; 2] = ["icons/", "brand/"];
/// WASM implementation - download assets on demand.
///
/// Assets are fetched from `{endpoint}/assets/{path}` and cached in memory
/// after the first successful download. This keeps the WASM bundle small
/// while still providing the full asset set at runtime.
pub struct Assets {
endpoint: SharedString,
cache: Arc<RwLock<HashMap<String, Vec<u8>>>>,
pending: Arc<RwLock<HashMap<String, bool>>>,
}
impl Assets {
/// Create a new Assets instance backed by the given endpoint.
///
/// Assets are resolved as `{endpoint}/assets/{path}`. An empty endpoint
/// resolves against the current page origin (e.g. `/assets/icons/foo.svg`).
pub fn new(endpoint: impl Into<SharedString>) -> Self {
Self {
endpoint: endpoint.into(),
cache: Arc::new(RwLock::new(HashMap::new())),
pending: Arc::new(RwLock::new(HashMap::new())),
}
}
/// Absolute URL of the given asset path.
///
/// `reqwest` requires absolute URLs, so a relative endpoint is resolved
/// against the current page origin.
fn asset_url(&self, path: &str) -> String {
let endpoint = if self.endpoint.is_empty() {
web_sys::window()
.and_then(|window| window.location().origin().ok())
.unwrap_or_default()
} else {
self.endpoint.to_string()
};
format!("{endpoint}/assets/{path}")
}
/// Download every asset in [`WASM_ASSETS`] into the cache, in parallel,
/// before the app starts.
///
/// Preloading is required for two reasons:
/// - Assets loaded through GPUI's [`gpui::Asset`] machinery (e.g. `img()`)
/// cache failed loads and never retry them.
/// - SVG painting only re-attempts an empty load on the next repaint, so
/// an icon would stay invisible until the window happens to redraw.
pub async fn preload(&self) {
let downloads = WASM_ASSETS.iter().map(|path| async move {
let result = reqwest::get(self.asset_url(path)).await;
match result {
Ok(response) if response.status().is_success() => match response.bytes().await {
Ok(bytes) => {
if let Ok(mut cache) = self.cache.write() {
cache.insert(path.to_string(), bytes.to_vec());
}
}
Err(e) => {
log::warn!("Failed to read asset {}: {}", path, e);
}
},
Ok(response) => {
log::warn!(
"Failed to download asset {}: HTTP {}",
path,
response.status()
);
}
Err(e) => {
log::warn!("Failed to fetch asset {}: {}", path, e);
}
}
});
futures::future::join_all(downloads).await;
}
}
impl AssetSource for Assets {
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
if path.is_empty() {
return Ok(None);
}
// Only serve paths the web build actually ships.
if !SERVED_PREFIXES
.iter()
.any(|prefix| path.starts_with(prefix))
{
return Ok(None);
}
// Serve from the in-memory cache when available.
if let Ok(cache) = self.cache.read() {
if let Some(data) = cache.get(path) {
return Ok(Some(Cow::Owned(data.clone())));
}
}
// Kick off a single download per path; concurrent requests for the
// same path share it.
let is_pending = self
.pending
.read()
.map(|pending| pending.contains_key(path))
.unwrap_or(false);
if !is_pending {
if let Ok(mut pending) = self.pending.write() {
pending.insert(path.to_string(), true);
}
let url = self.asset_url(path);
let path_clone = path.to_string();
let cache = self.cache.clone();
let pending = self.pending.clone();
spawn_local(async move {
match reqwest::get(&url).await {
Ok(response) if response.status().is_success() => {
match response.bytes().await {
Ok(bytes) => {
if let Ok(mut cache) = cache.write() {
cache.insert(path_clone.clone(), bytes.to_vec());
}
}
Err(e) => {
log::warn!("Failed to read asset {}: {}", path_clone, e);
}
}
}
Ok(response) => {
log::warn!(
"Failed to download asset {}: HTTP {}",
path_clone,
response.status()
);
}
Err(e) => {
log::warn!("Failed to fetch asset {}: {}", path_clone, e);
}
}
// Allow retrying failed downloads on subsequent requests.
if let Ok(mut pending) = pending.write() {
pending.remove(&path_clone);
}
});
}
// The asset is not available yet. GPUI's SVG atlas does not cache
// empty loads, so the next repaint will call `load` again and find
// the asset in the cache once the download completes.
Ok(None)
}
fn list(&self, _path: &str) -> Result<Vec<SharedString>> {
// The asset manifest is not available at runtime on web; embedded
// directories are not listed.
Ok(Vec::new())
}
}