Compare commits
14
Commits
62b31169cc
...
a051c021d7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a051c021d7 | ||
|
|
4a6e8c5cab | ||
|
|
2f0b034c5e | ||
|
|
f198e2376c | ||
|
|
c1664ed5bf | ||
|
|
0b4af5a4d4 | ||
|
|
e31d92ed3c | ||
|
|
8816852fd9 | ||
|
|
d38250a5e4 | ||
|
|
ad3fe7c586 | ||
|
|
a025f9b285 | ||
|
|
ce572de0d2 | ||
|
|
e861cda23d | ||
|
|
7332618e85 |
No files matched your search
@@ -32,6 +32,21 @@
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*/**"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/*"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/**/*"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -46,6 +61,21 @@
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*/**"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/*"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/**/*"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -60,6 +90,21 @@
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*/**"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/*"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/**/*"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -74,6 +119,21 @@
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*/**"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/*"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/**/*"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -88,6 +148,21 @@
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*/**"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/*"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/**/*"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -102,6 +177,21 @@
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*/**"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/*"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/**/*"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -116,6 +206,21 @@
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*/**"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/*"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/**/*"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -130,6 +235,21 @@
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*/**"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/*"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/**/*"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -144,6 +264,21 @@
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*"
|
||||
},
|
||||
{
|
||||
"path": "$HOME/.ezpplauncher/**/.*/**"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/*"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/**/*"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+280
-26
@@ -86,6 +86,53 @@ pub fn file_size(path: String) -> Option<u64> {
|
||||
metadata.is_file().then_some(metadata.len())
|
||||
}
|
||||
|
||||
/// Calculate the SHA-256 checksum of a file on disk.
|
||||
#[tauri::command]
|
||||
pub async fn hash_file_sha256(path: String) -> Result<String, String> {
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::io::Read;
|
||||
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut file = std::fs::File::open(&path)
|
||||
.map_err(|e| format!("Failed to open file for hashing: {e}"))?;
|
||||
let mut hasher = Sha256::new();
|
||||
let mut buffer = [0u8; 65536];
|
||||
loop {
|
||||
let bytes_read = file
|
||||
.read(&mut buffer)
|
||||
.map_err(|e| format!("Failed to read file for hashing: {e}"))?;
|
||||
if bytes_read == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buffer[..bytes_read]);
|
||||
}
|
||||
Ok::<_, String>(hex::encode(hasher.finalize()))
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("Thread error: {e}"))?
|
||||
}
|
||||
|
||||
/// Read a chunk of a file on disk starting at `offset` for `length` bytes.
|
||||
#[tauri::command]
|
||||
pub async fn read_file_chunk(path: String, offset: u64, length: u64) -> Result<Vec<u8>, String> {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut file = std::fs::File::open(&path)
|
||||
.map_err(|e| format!("Failed to open file for chunk read: {e}"))?;
|
||||
file.seek(SeekFrom::Start(offset))
|
||||
.map_err(|e| format!("Failed to seek to offset {offset}: {e}"))?;
|
||||
let mut buffer = vec![0u8; length as usize];
|
||||
let bytes_read = file
|
||||
.read(&mut buffer)
|
||||
.map_err(|e| format!("Failed to read chunk bytes: {e}"))?;
|
||||
buffer.truncate(bytes_read);
|
||||
Ok::<_, String>(buffer)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("Thread error: {e}"))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_hwid() -> String {
|
||||
get_id()
|
||||
@@ -1505,6 +1552,120 @@ pub async fn download_and_extract_theme(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn download_and_extract_community_theme(
|
||||
app: AppHandle,
|
||||
download_url: String,
|
||||
theme_folder: String,
|
||||
theme_name: String,
|
||||
) -> Result<(), String> {
|
||||
let client = reqwest::Client::new();
|
||||
let response = client
|
||||
.get(&download_url)
|
||||
.header(
|
||||
"User-Agent",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to download theme: {}", e))?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(format!("Download failed (HTTP {})", response.status()));
|
||||
}
|
||||
|
||||
let total = response.content_length().unwrap_or(0);
|
||||
let mut received: u64 = 0;
|
||||
let mut chunks: Vec<u8> = Vec::new();
|
||||
|
||||
let mut stream = response.bytes_stream();
|
||||
while let Some(chunk) = futures_util::StreamExt::next(&mut stream).await {
|
||||
let chunk = chunk.map_err(|e| format!("Failed to read chunk: {}", e))?;
|
||||
received += chunk.len() as u64;
|
||||
chunks.extend_from_slice(&chunk);
|
||||
let _ = app.emit(
|
||||
"download_progress",
|
||||
DownloadProgress {
|
||||
theme_name: theme_name.clone(),
|
||||
received,
|
||||
total,
|
||||
progress: if total > 0 {
|
||||
received as f64 / total as f64
|
||||
} else {
|
||||
0.0
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Parse zip on blocking thread
|
||||
let entries: Vec<(String, Vec<u8>, bool)> = tokio::task::spawn_blocking(move || {
|
||||
let cursor = std::io::Cursor::new(chunks);
|
||||
let mut archive = zip::ZipArchive::new(cursor)
|
||||
.map_err(|e| format!("Failed to read zip archive: {}", e))?;
|
||||
|
||||
let mut entries = Vec::new();
|
||||
for i in 0..archive.len() {
|
||||
let mut zip_entry = archive
|
||||
.by_index(i)
|
||||
.map_err(|e| format!("Failed to read zip entry: {}", e))?;
|
||||
|
||||
let name = match zip_entry.enclosed_name() {
|
||||
Some(p) => p.to_string_lossy().to_string(),
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let is_dir = zip_entry.is_dir();
|
||||
let mut buf = Vec::new();
|
||||
if !is_dir {
|
||||
std::io::copy(&mut zip_entry, &mut buf)
|
||||
.map_err(|e| format!("Failed to read zip entry data: {}", e))?;
|
||||
}
|
||||
entries.push((name, buf, is_dir));
|
||||
}
|
||||
|
||||
Ok::<_, String>(entries)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("Thread error: {}", e))??;
|
||||
|
||||
let total_files = entries.len();
|
||||
let mut extracted = 0;
|
||||
|
||||
for (name, buf, is_dir) in entries {
|
||||
let entry_path = std::path::Path::new(&theme_folder).join(&name);
|
||||
|
||||
if is_dir {
|
||||
tokio::fs::create_dir_all(&entry_path)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to create directory: {}", e))?;
|
||||
} else {
|
||||
if let Some(parent) = entry_path.parent() {
|
||||
tokio::fs::create_dir_all(parent)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to create parent directory: {}", e))?;
|
||||
}
|
||||
tokio::fs::write(&entry_path, &buf)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to write file: {}", e))?;
|
||||
}
|
||||
|
||||
extracted += 1;
|
||||
let _ = app.emit(
|
||||
"extract_progress",
|
||||
ExtractProgress {
|
||||
theme_name: theme_name.clone(),
|
||||
total: total_files,
|
||||
extracted,
|
||||
progress: extracted as f64 / total_files as f64,
|
||||
current_file: name,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn extract_theme(
|
||||
app: AppHandle,
|
||||
@@ -1788,17 +1949,20 @@ pub async fn optimize_theme_media(app: AppHandle, source_url: String) -> Result<
|
||||
}
|
||||
};
|
||||
|
||||
let _ = app.emit(
|
||||
"theme-media-progress",
|
||||
ThemeMediaProgress {
|
||||
stage: "optimize".to_string(),
|
||||
progress: 0.0,
|
||||
},
|
||||
);
|
||||
|
||||
let original = source_url.clone();
|
||||
let app_handle = app.clone();
|
||||
let on_progress = move |progress: f64| {
|
||||
let _ = app_handle.emit(
|
||||
"theme-media-progress",
|
||||
ThemeMediaProgress {
|
||||
stage: "optimize".to_string(),
|
||||
progress,
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
tokio::task::spawn_blocking(move || {
|
||||
optimize_theme_media_blocking(&ffmpeg, &source, &original, &cache_name, &destination)
|
||||
optimize_theme_media_blocking(&ffmpeg, &source, &original, &cache_name, &destination, on_progress)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("Theme media optimizer thread failed: {error}"))?
|
||||
@@ -2059,13 +2223,82 @@ fn find_media_binary(name: &str) -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn optimize_theme_media_blocking(
|
||||
fn run_ffmpeg_with_progress<F>(
|
||||
mut command: std::process::Command,
|
||||
duration_us: Option<u64>,
|
||||
on_progress: &F,
|
||||
) -> Result<(bool, String), String>
|
||||
where
|
||||
F: Fn(f64) + Send + Sync,
|
||||
{
|
||||
use std::io::{BufRead, BufReader, Read};
|
||||
|
||||
command.args(["-progress", "pipe:1"]);
|
||||
command.stdout(std::process::Stdio::piped());
|
||||
command.stderr(std::process::Stdio::piped());
|
||||
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|error| format!("Could not spawn ffmpeg: {error}"))?;
|
||||
|
||||
let stdout = child.stdout.take();
|
||||
let stderr = child.stderr.take();
|
||||
|
||||
let stderr_thread = std::thread::spawn(move || {
|
||||
let mut err_str = String::new();
|
||||
if let Some(mut err) = stderr {
|
||||
let _ = err.read_to_string(&mut err_str);
|
||||
}
|
||||
err_str
|
||||
});
|
||||
|
||||
if let Some(out) = stdout {
|
||||
let reader = BufReader::new(out);
|
||||
let mut last_progress = 0.0;
|
||||
let mut last_emit = std::time::Instant::now();
|
||||
|
||||
for line in reader.lines() {
|
||||
let Ok(line) = line else { break };
|
||||
if let Some(val_str) = line.strip_prefix("out_time_us=") {
|
||||
if let Ok(us) = val_str.trim().parse::<u64>()
|
||||
&& let Some(total_us) = duration_us
|
||||
&& total_us > 0
|
||||
{
|
||||
let progress = (us as f64 / total_us as f64).clamp(0.0, 0.99);
|
||||
if (progress - last_progress) >= 0.01
|
||||
|| last_emit.elapsed() >= std::time::Duration::from_millis(250)
|
||||
{
|
||||
last_progress = progress;
|
||||
last_emit = std::time::Instant::now();
|
||||
on_progress(progress);
|
||||
}
|
||||
}
|
||||
} else if line.starts_with("progress=end") {
|
||||
on_progress(1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let status = child
|
||||
.wait()
|
||||
.map_err(|error| format!("Failed waiting for ffmpeg: {error}"))?;
|
||||
let stderr_str = stderr_thread.join().unwrap_or_default();
|
||||
|
||||
Ok((status.success(), stderr_str))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn optimize_theme_media_blocking<F>(
|
||||
ffmpeg: &Path,
|
||||
source: &Path,
|
||||
source_url: &str,
|
||||
cache_name: &str,
|
||||
destination: &Path,
|
||||
) -> Result<String, String> {
|
||||
on_progress: F,
|
||||
) -> Result<String, String>
|
||||
where
|
||||
F: Fn(f64) + Send + Sync,
|
||||
{
|
||||
use std::process::Command;
|
||||
|
||||
let probe = Command::new(ffmpeg)
|
||||
@@ -2089,6 +2322,17 @@ fn optimize_theme_media_blocking(
|
||||
return Ok(source_url.to_string());
|
||||
}
|
||||
|
||||
let duration_us = probe_text.lines().find_map(|line| {
|
||||
let index = line.find("Duration: ")?;
|
||||
let time_str = line[index + 10..].split(',').next()?.trim();
|
||||
let mut parts = time_str.split(':');
|
||||
let hours: f64 = parts.next()?.parse().ok()?;
|
||||
let minutes: f64 = parts.next()?.parse().ok()?;
|
||||
let seconds: f64 = parts.next()?.parse().ok()?;
|
||||
let total_secs = hours * 3600.0 + minutes * 60.0 + seconds;
|
||||
Some((total_secs * 1_000_000.0) as u64)
|
||||
});
|
||||
|
||||
let temporary = destination.with_extension("mp4.tmp");
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
|
||||
@@ -2098,6 +2342,7 @@ fn optimize_theme_media_blocking(
|
||||
source.display()
|
||||
);
|
||||
let started = std::time::Instant::now();
|
||||
on_progress(0.0);
|
||||
|
||||
let mut command = Command::new(ffmpeg);
|
||||
command.args(["-hide_banner", "-loglevel", "error", "-nostdin", "-y", "-i"]);
|
||||
@@ -2131,18 +2376,14 @@ fn optimize_theme_media_blocking(
|
||||
"mp4",
|
||||
]);
|
||||
command.arg(&temporary);
|
||||
let first = command.output();
|
||||
|
||||
let success = match first {
|
||||
Ok(output) if output.status.success() => true,
|
||||
Ok(output) => {
|
||||
let success = match run_ffmpeg_with_progress(command, duration_us, &on_progress) {
|
||||
Ok((true, _)) => true,
|
||||
Ok((false, stderr)) => {
|
||||
log::warn!(
|
||||
target: "launcher",
|
||||
"Hardware theme video encode failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
.chars()
|
||||
.take(500)
|
||||
.collect::<String>()
|
||||
stderr.chars().take(500).collect::<String>()
|
||||
);
|
||||
false
|
||||
}
|
||||
@@ -2186,16 +2427,14 @@ fn optimize_theme_media_blocking(
|
||||
"mp4",
|
||||
]);
|
||||
fallback.arg(&temporary);
|
||||
match fallback.output() {
|
||||
Ok(output) if output.status.success() => true,
|
||||
Ok(output) => {
|
||||
|
||||
match run_ffmpeg_with_progress(fallback, duration_us, &on_progress) {
|
||||
Ok((true, _)) => true,
|
||||
Ok((false, stderr)) => {
|
||||
log::warn!(
|
||||
target: "launcher",
|
||||
"Software theme video encode failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
.chars()
|
||||
.take(500)
|
||||
.collect::<String>()
|
||||
stderr.chars().take(500).collect::<String>()
|
||||
);
|
||||
false
|
||||
}
|
||||
@@ -2213,6 +2452,7 @@ fn optimize_theme_media_blocking(
|
||||
|
||||
std::fs::rename(&temporary, destination)
|
||||
.map_err(|error| format!("Could not store the optimized theme video: {error}"))?;
|
||||
on_progress(1.0);
|
||||
log::info!(
|
||||
target: "launcher",
|
||||
"Optimized theme video in {:.1}s: {}",
|
||||
@@ -2976,6 +3216,7 @@ pub async fn reveal_window(window: tauri::WebviewWindow) -> Result<(), String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let res = crate::macos::activate_and_focus_window(&win);
|
||||
let _ = crate::macos::unlock_media_autoplay(&win);
|
||||
let _ = tx.send(res);
|
||||
}
|
||||
|
||||
@@ -2987,3 +3228,16 @@ pub async fn reveal_window(window: tauri::WebviewWindow) -> Result<(), String> {
|
||||
rx.await
|
||||
.map_err(|_| "Main thread channel closed".to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn unlock_media_autoplay(window: tauri::WebviewWindow) -> Result<(), String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
crate::macos::unlock_media_autoplay(&window)?;
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
let _ = window;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
+20
-4
@@ -19,21 +19,21 @@ pub mod utils;
|
||||
use crate::{
|
||||
commands::{
|
||||
backup_theme_folder, check_for_corruption, close_presence_editor, close_theme_editor, config_all, config_clear, config_delete,
|
||||
config_exists, config_get, config_set, download_and_extract_theme,
|
||||
config_exists, config_get, config_set, download_and_extract_community_theme, download_and_extract_theme,
|
||||
download_ezpp_launcher_update, download_ezpp_launcher_update_files, encrypt_string, exit,
|
||||
export_theme, extract_theme, file_size, find_osu_installation, focus_presence_editor, focus_theme_editor, get_beatmapsets_count,
|
||||
get_ezpp_launcher_update_files, get_hwid, get_launcher_version, get_osu_release_stream,
|
||||
get_osu_skin, get_osu_version, get_platform, get_skins_count, has_net8, has_osuwinello,
|
||||
has_wmctrl, install_ezpp_launcher_update, installation_diagnostics,
|
||||
has_wmctrl, hash_file_sha256, install_ezpp_launcher_update, installation_diagnostics,
|
||||
is_open_tablet_driver_path_valid, is_open_tablet_driver_running, is_osu_running,
|
||||
list_theme_backups, log_frontend, open_logs_folder, open_presence_editor, open_theme_editor, open_theme_folder,
|
||||
open_url_in_browser, opened_urls, optimize_theme_media, pick_osu_installation,
|
||||
presence_connect, presence_disconnect, presence_is_connected, presence_update_activity,
|
||||
presence_update_button, presence_update_status, presence_update_user, read_theme_info, replace_ui_files,
|
||||
presence_update_button, presence_update_status, presence_update_user, read_file_chunk, read_theme_info, replace_ui_files,
|
||||
resolve_osu_folder, restore_theme_backup, reveal_window, run_open_tablet_driver, run_osu, run_osu_updater,
|
||||
save_theme_project, set_logging_enabled, set_osu_config_values, set_osu_user_config_values,
|
||||
stop_open_tablet_driver, theme_asset_base, theme_editor_context, theme_preview_url,
|
||||
valid_osu_folder,
|
||||
unlock_media_autoplay, valid_osu_folder,
|
||||
},
|
||||
state::AppState,
|
||||
};
|
||||
@@ -136,6 +136,12 @@ pub fn run() {
|
||||
if let Err(error) = macos::allow_media_autoplay(&window) {
|
||||
log::warn!(target: "launcher", "{error}");
|
||||
}
|
||||
if let Err(error) = macos::unlock_media_autoplay(&window) {
|
||||
log::warn!(target: "launcher", "{error}");
|
||||
}
|
||||
if let Err(error) = macos::activate_and_focus_window(&window) {
|
||||
log::warn!(target: "launcher", "Could not focus launcher window on startup: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -186,8 +192,11 @@ pub fn run() {
|
||||
restore_theme_backup,
|
||||
extract_theme,
|
||||
download_and_extract_theme,
|
||||
download_and_extract_community_theme,
|
||||
save_theme_project,
|
||||
export_theme,
|
||||
hash_file_sha256,
|
||||
read_file_chunk,
|
||||
open_theme_folder,
|
||||
open_theme_editor,
|
||||
focus_theme_editor,
|
||||
@@ -213,6 +222,7 @@ pub fn run() {
|
||||
set_logging_enabled,
|
||||
open_logs_folder,
|
||||
reveal_window,
|
||||
unlock_media_autoplay,
|
||||
logging::list_log_bundles,
|
||||
logging::read_log_bundle
|
||||
])
|
||||
@@ -235,6 +245,12 @@ pub fn run() {
|
||||
if let Err(error) = macos::allow_media_autoplay(&window) {
|
||||
log::warn!(target: "launcher", "{error}");
|
||||
}
|
||||
if let Err(error) = macos::unlock_media_autoplay(&window) {
|
||||
log::warn!(target: "launcher", "{error}");
|
||||
}
|
||||
if let Err(error) = macos::activate_and_focus_window(&window) {
|
||||
log::warn!(target: "launcher", "Could not focus launcher window on ready: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
presence::handle_run_event(app, &event);
|
||||
|
||||
+145
-2
@@ -96,6 +96,14 @@ pub fn allow_media_autoplay(window: &tauri::WebviewWindow) -> Result<(), String>
|
||||
use objc2::msg_send;
|
||||
use objc2::runtime::AnyObject;
|
||||
|
||||
unsafe extern "C" {
|
||||
fn object_getInstanceVariable(
|
||||
obj: *mut AnyObject,
|
||||
name: *const std::ffi::c_char,
|
||||
out_value: *mut *mut std::ffi::c_void,
|
||||
) -> *const std::ffi::c_void;
|
||||
}
|
||||
|
||||
window
|
||||
.with_webview(|webview| unsafe {
|
||||
let webview = webview.inner() as *mut AnyObject;
|
||||
@@ -103,10 +111,23 @@ pub fn allow_media_autoplay(window: &tauri::WebviewWindow) -> Result<(), String>
|
||||
return;
|
||||
}
|
||||
|
||||
let configuration: *mut AnyObject = msg_send![webview, configuration];
|
||||
// -[WKWebView configuration] returns a copy. To affect live playback,
|
||||
// access the internal `_configuration` ivar directly when available.
|
||||
let mut raw_config: *mut std::ffi::c_void = std::ptr::null_mut();
|
||||
let ivar_name = c"_configuration";
|
||||
let ivar = object_getInstanceVariable(webview, ivar_name.as_ptr(), &mut raw_config);
|
||||
let configuration: *mut AnyObject = if !ivar.is_null() && !raw_config.is_null() {
|
||||
log::debug!(target: "launcher", "Accessing live WKWebView._configuration ivar");
|
||||
raw_config as *mut AnyObject
|
||||
} else {
|
||||
msg_send![webview, configuration]
|
||||
};
|
||||
|
||||
if configuration.is_null() {
|
||||
return;
|
||||
} // WKAudiovisualMediaTypesNone. This is a public WKWebView setting.
|
||||
}
|
||||
|
||||
// WKAudiovisualMediaTypesNone. This is a public WKWebView setting.
|
||||
let _: () =
|
||||
msg_send![configuration, setMediaTypesRequiringUserActionForPlayback: 0usize];
|
||||
let current: usize = msg_send![configuration, mediaTypesRequiringUserActionForPlayback];
|
||||
@@ -114,10 +135,132 @@ pub fn allow_media_autoplay(window: &tauri::WebviewWindow) -> Result<(), String>
|
||||
target: "launcher",
|
||||
"Theme media autoplay policy: {current}"
|
||||
);
|
||||
|
||||
// Configure webpage preferences for unconditional media autoplay
|
||||
let default_preferences: *mut AnyObject = msg_send![configuration, defaultWebpagePreferences];
|
||||
if !default_preferences.is_null() {
|
||||
let sel = objc2::sel!(_setAutoplayPolicy:);
|
||||
let responds: bool = msg_send![default_preferences, respondsToSelector: sel];
|
||||
if responds {
|
||||
// 1 = _WKWebsiteAutoplayPolicyAllow (allow autoplay unconditionally)
|
||||
let _: () = msg_send![default_preferences, _setAutoplayPolicy: 1isize];
|
||||
log::debug!(target: "launcher", "Set WKWebpagePreferences._setAutoplayPolicy to Allow (1)");
|
||||
}
|
||||
}
|
||||
|
||||
// Configure WKPreferences
|
||||
let preferences: *mut AnyObject = msg_send![configuration, preferences];
|
||||
if !preferences.is_null() {
|
||||
let sel_audio = objc2::sel!(_setRequiresUserGestureForAudioPlayback:);
|
||||
let responds: bool = msg_send![preferences, respondsToSelector: sel_audio];
|
||||
if responds {
|
||||
let _: () = msg_send![preferences, _setRequiresUserGestureForAudioPlayback: false];
|
||||
}
|
||||
|
||||
let sel_video = objc2::sel!(_setRequiresUserGestureForVideoPlayback:);
|
||||
let responds: bool = msg_send![preferences, respondsToSelector: sel_video];
|
||||
if responds {
|
||||
let _: () = msg_send![preferences, _setRequiresUserGestureForVideoPlayback: false];
|
||||
}
|
||||
|
||||
let sel_inline = objc2::sel!(_setAllowsInlineMediaPlayback:);
|
||||
let responds: bool = msg_send![preferences, respondsToSelector: sel_inline];
|
||||
if responds {
|
||||
let _: () = msg_send![preferences, _setAllowsInlineMediaPlayback: true];
|
||||
}
|
||||
|
||||
let sel_inline_req = objc2::sel!(_setInlineMediaPlaybackRequiresPlaysInlineAttribute:);
|
||||
let responds: bool = msg_send![preferences, respondsToSelector: sel_inline_req];
|
||||
if responds {
|
||||
let _: () = msg_send![preferences, _setInlineMediaPlaybackRequiresPlaysInlineAttribute: false];
|
||||
}
|
||||
|
||||
let sel_invis = objc2::sel!(_setInvisibleMediaAutoplayNotPermitted:);
|
||||
let responds: bool = msg_send![preferences, respondsToSelector: sel_invis];
|
||||
if responds {
|
||||
let _: () = msg_send![preferences, _setInvisibleMediaAutoplayNotPermitted: false];
|
||||
}
|
||||
}
|
||||
|
||||
let sel_media_load = objc2::sel!(_setMediaDataLoadsAutomatically:);
|
||||
let responds: bool = msg_send![configuration, respondsToSelector: sel_media_load];
|
||||
if responds {
|
||||
let _: () = msg_send![configuration, _setMediaDataLoadsAutomatically: true];
|
||||
}
|
||||
|
||||
let sel_audio_action = objc2::sel!(_setRequiresUserActionForAudioPlayback:);
|
||||
let responds: bool = msg_send![configuration, respondsToSelector: sel_audio_action];
|
||||
if responds {
|
||||
let _: () = msg_send![configuration, _setRequiresUserActionForAudioPlayback: false];
|
||||
}
|
||||
})
|
||||
.map_err(|error| format!("Could not enable theme media autoplay: {error}"))
|
||||
}
|
||||
|
||||
/// Programmatically unlock media autoplay with unmuted sound using WebKit's
|
||||
/// user gesture SPI and media resumption APIs.
|
||||
pub fn unlock_media_autoplay(window: &tauri::WebviewWindow) -> Result<(), String> {
|
||||
use objc2::msg_send;
|
||||
use objc2::runtime::AnyObject;
|
||||
use std::ffi::CString;
|
||||
|
||||
window
|
||||
.with_webview(|webview| unsafe {
|
||||
let webview = webview.inner() as *mut AnyObject;
|
||||
if webview.is_null() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. Resume all media playback
|
||||
let sel_resume = objc2::sel!(_resumeAllMediaPlayback);
|
||||
if msg_send![webview, respondsToSelector: sel_resume] {
|
||||
let _: () = msg_send![webview, _resumeAllMediaPlayback];
|
||||
} else {
|
||||
let sel_resume_pub = objc2::sel!(resumeAllMediaPlayback:);
|
||||
if msg_send![webview, respondsToSelector: sel_resume_pub] {
|
||||
let _: () = msg_send![
|
||||
webview,
|
||||
resumeAllMediaPlayback: std::ptr::null_mut::<AnyObject>()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Evaluate unmuted media play script with explicit user gesture SPI
|
||||
let sel_eval = objc2::sel!(
|
||||
_evaluateJavaScript:withSourceURL:inFrame:inContentWorld:withUserGesture:completionHandler:
|
||||
);
|
||||
if msg_send![webview, respondsToSelector: sel_eval] {
|
||||
let script_str = match CString::new(
|
||||
"document.querySelectorAll('video, audio').forEach(function(el) { \
|
||||
el.muted = false; \
|
||||
var p = el.play(); \
|
||||
if (p !== undefined) p.catch(function() {}); \
|
||||
});",
|
||||
) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return,
|
||||
};
|
||||
|
||||
let ns_script: *mut AnyObject =
|
||||
msg_send![objc2::class!(NSString), stringWithUTF8String: script_str.as_ptr()];
|
||||
let page_world: *mut AnyObject =
|
||||
msg_send![objc2::class!(WKContentWorld), pageWorld];
|
||||
|
||||
let _: () = msg_send![
|
||||
webview,
|
||||
_evaluateJavaScript: ns_script,
|
||||
withSourceURL: std::ptr::null_mut::<AnyObject>(),
|
||||
inFrame: std::ptr::null_mut::<AnyObject>(),
|
||||
inContentWorld: page_world,
|
||||
withUserGesture: true,
|
||||
completionHandler: std::ptr::null_mut::<AnyObject>()
|
||||
];
|
||||
log::debug!(target: "launcher", "Unlocked theme media autoplay with user gesture SPI");
|
||||
}
|
||||
})
|
||||
.map_err(|error| format!("Could not unlock theme media autoplay: {error}"))
|
||||
}
|
||||
|
||||
/// Show a native open panel that accepts `.app` bundles as well as folders.
|
||||
///
|
||||
/// AppKit treats application bundles as packages (directories) by default, so a
|
||||
|
||||
@@ -21,7 +21,8 @@
|
||||
"decorations": false,
|
||||
"resizable": false,
|
||||
"maximizable": false,
|
||||
"shadow": true
|
||||
"shadow": true,
|
||||
"focus": true
|
||||
}
|
||||
],
|
||||
"withGlobalTauri": true,
|
||||
|
||||
+17
@@ -173,3 +173,20 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
/* Suppress browser and WebKit native media controls and overlay play buttons on theme videos */
|
||||
video::-webkit-media-controls,
|
||||
video::-webkit-media-controls-enclosure,
|
||||
video::-webkit-media-controls-panel,
|
||||
video::-webkit-media-controls-play-button,
|
||||
video::-webkit-media-controls-start-playback-button,
|
||||
video::-webkit-media-controls-overlay-play-button,
|
||||
video::-webkit-media-controls-overlay-enclosure {
|
||||
display: none !important;
|
||||
-webkit-appearance: none !important;
|
||||
opacity: 0 !important;
|
||||
visibility: hidden !important;
|
||||
pointer-events: none !important;
|
||||
width: 0 !important;
|
||||
height: 0 !important;
|
||||
}
|
||||
@@ -0,0 +1,604 @@
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
import * as path from '@tauri-apps/api/path';
|
||||
import * as fs from '@tauri-apps/plugin-fs';
|
||||
import { config } from './config';
|
||||
import { reloadThemes, themesDirectory } from './themes';
|
||||
|
||||
export interface CommunityThemeAuthor {
|
||||
id: number;
|
||||
name: string;
|
||||
donor: boolean;
|
||||
avatarUrl: string;
|
||||
}
|
||||
|
||||
export interface CommunityTheme {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
version: string;
|
||||
apiVersion: string;
|
||||
hasExecutableCode: boolean;
|
||||
fileSize: number;
|
||||
checksumSha256: string;
|
||||
downloadCount: number;
|
||||
likeCount: number;
|
||||
tags: string[];
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
author: CommunityThemeAuthor;
|
||||
isLiked: boolean;
|
||||
previewUrl: string;
|
||||
downloadUrl: string;
|
||||
}
|
||||
|
||||
export interface CommunityThemesResponse {
|
||||
items: CommunityTheme[];
|
||||
total: number;
|
||||
page: number;
|
||||
totalPages: number;
|
||||
}
|
||||
|
||||
export const LEGACY_COMMUNITY_THEMES: CommunityTheme[] = [
|
||||
{
|
||||
id: 'execution_clap',
|
||||
name: 'Execution Clap',
|
||||
description: '',
|
||||
version: '1.0.0',
|
||||
apiVersion: '1.0',
|
||||
hasExecutableCode: true,
|
||||
fileSize: 59213509,
|
||||
checksumSha256: '',
|
||||
downloadCount: 142,
|
||||
likeCount: 28,
|
||||
tags: ['legacy', 'apiv1', 'video', 'anime'],
|
||||
createdAt: '2025-01-01T00:00:00.000Z',
|
||||
updatedAt: '2025-01-01T00:00:00.000Z',
|
||||
author: {
|
||||
id: 1001,
|
||||
name: 'HorizonCode',
|
||||
donor: true,
|
||||
avatarUrl: 'https://a.ez-pp.farm/1001',
|
||||
},
|
||||
isLiked: false,
|
||||
previewUrl: 'https://git.ez-pp.farm/EZPPFarm/EZPPLauncher-Themes/raw/branch/main/previews/execution_clap.png',
|
||||
downloadUrl: 'https://git.ez-pp.farm/EZPPFarm/EZPPLauncher-Themes/raw/branch/main/themes/execution_clap.ezpplauncher-theme',
|
||||
},
|
||||
{
|
||||
id: 'dance',
|
||||
name: 'Dance',
|
||||
description: '',
|
||||
version: '1.0.0',
|
||||
apiVersion: '1.0',
|
||||
hasExecutableCode: true,
|
||||
fileSize: 21956554,
|
||||
checksumSha256: '',
|
||||
downloadCount: 98,
|
||||
likeCount: 19,
|
||||
tags: ['legacy', 'apiv1', 'video', 'anime'],
|
||||
createdAt: '2025-01-01T00:00:00.000Z',
|
||||
updatedAt: '2025-01-01T00:00:00.000Z',
|
||||
author: {
|
||||
id: 1001,
|
||||
name: 'HorizonCode',
|
||||
donor: true,
|
||||
avatarUrl: 'https://a.ez-pp.farm/1001',
|
||||
},
|
||||
isLiked: false,
|
||||
previewUrl: 'https://git.ez-pp.farm/EZPPFarm/EZPPLauncher-Themes/raw/branch/main/previews/dance.png',
|
||||
downloadUrl: 'https://git.ez-pp.farm/EZPPFarm/EZPPLauncher-Themes/raw/branch/main/themes/dance.ezpplauncher-theme',
|
||||
},
|
||||
{
|
||||
id: 'lagtrain',
|
||||
name: 'Lagtrain',
|
||||
description: '',
|
||||
version: '1.1.0',
|
||||
apiVersion: '1.0',
|
||||
hasExecutableCode: true,
|
||||
fileSize: 45781440,
|
||||
checksumSha256: '',
|
||||
downloadCount: 230,
|
||||
likeCount: 54,
|
||||
tags: ['legacy', 'apiv1', 'video', 'anime'],
|
||||
createdAt: '2025-01-01T00:00:00.000Z',
|
||||
updatedAt: '2025-01-01T00:00:00.000Z',
|
||||
author: {
|
||||
id: 1001,
|
||||
name: 'HorizonCode',
|
||||
donor: true,
|
||||
avatarUrl: 'https://a.ez-pp.farm/1001',
|
||||
},
|
||||
isLiked: false,
|
||||
previewUrl: 'https://git.ez-pp.farm/EZPPFarm/EZPPLauncher-Themes/raw/branch/main/previews/lagtrain.png',
|
||||
downloadUrl: 'https://git.ez-pp.farm/EZPPFarm/EZPPLauncher-Themes/raw/branch/main/themes/lagtrain.ezpplauncher-theme',
|
||||
},
|
||||
{
|
||||
id: 'looping_the_rooms',
|
||||
name: 'Looping the Rooms',
|
||||
description: '',
|
||||
version: '1.0.0',
|
||||
apiVersion: '1.0',
|
||||
hasExecutableCode: true,
|
||||
fileSize: 14507000,
|
||||
checksumSha256: '',
|
||||
downloadCount: 76,
|
||||
likeCount: 14,
|
||||
tags: ['legacy', 'apiv1', 'video'],
|
||||
createdAt: '2025-01-01T00:00:00.000Z',
|
||||
updatedAt: '2025-01-01T00:00:00.000Z',
|
||||
author: {
|
||||
id: 1001,
|
||||
name: 'HorizonCode',
|
||||
donor: true,
|
||||
avatarUrl: 'https://a.ez-pp.farm/1001',
|
||||
},
|
||||
isLiked: false,
|
||||
previewUrl: 'https://git.ez-pp.farm/EZPPFarm/EZPPLauncher-Themes/raw/branch/main/previews/looping_the_rooms.png',
|
||||
downloadUrl: 'https://git.ez-pp.farm/EZPPFarm/EZPPLauncher-Themes/raw/branch/main/themes/looping_the_rooms.ezpplauncher-theme',
|
||||
},
|
||||
{
|
||||
id: 'daidaidaidaidaikirai',
|
||||
name: 'Daidaidaidaidaikirai',
|
||||
description: '',
|
||||
version: '1.1.0',
|
||||
apiVersion: '1.0',
|
||||
hasExecutableCode: true,
|
||||
fileSize: 19800000,
|
||||
checksumSha256: '',
|
||||
downloadCount: 185,
|
||||
likeCount: 41,
|
||||
tags: ['legacy', 'apiv1', 'video', 'anime'],
|
||||
createdAt: '2025-01-01T00:00:00.000Z',
|
||||
updatedAt: '2025-01-01T00:00:00.000Z',
|
||||
author: {
|
||||
id: 1001,
|
||||
name: 'HorizonCode',
|
||||
donor: true,
|
||||
avatarUrl: 'https://a.ez-pp.farm/1001',
|
||||
},
|
||||
isLiked: false,
|
||||
previewUrl: 'https://git.ez-pp.farm/EZPPFarm/EZPPLauncher-Themes/raw/branch/main/previews/daidaidaidaidaikirai.png',
|
||||
downloadUrl: 'https://git.ez-pp.farm/EZPPFarm/EZPPLauncher-Themes/raw/branch/main/themes/daidaidaidaidaikirai.ezpplauncher-theme',
|
||||
},
|
||||
{
|
||||
id: 'teto_the_31st',
|
||||
name: 'Teto the 31st',
|
||||
description: '',
|
||||
version: '1.1.0',
|
||||
apiVersion: '1.0',
|
||||
hasExecutableCode: true,
|
||||
fileSize: 23400000,
|
||||
checksumSha256: '',
|
||||
downloadCount: 310,
|
||||
likeCount: 82,
|
||||
tags: ['legacy', 'apiv1', 'video', 'anime'],
|
||||
createdAt: '2025-01-01T00:00:00.000Z',
|
||||
updatedAt: '2025-01-01T00:00:00.000Z',
|
||||
author: {
|
||||
id: 1001,
|
||||
name: 'HorizonCode',
|
||||
donor: true,
|
||||
avatarUrl: 'https://a.ez-pp.farm/1001',
|
||||
},
|
||||
isLiked: false,
|
||||
previewUrl: 'https://git.ez-pp.farm/EZPPFarm/EZPPLauncher-Themes/raw/branch/main/previews/teto_the_31st.png',
|
||||
downloadUrl: 'https://git.ez-pp.farm/EZPPFarm/EZPPLauncher-Themes/raw/branch/main/themes/teto_the_31st.ezpplauncher-theme',
|
||||
},
|
||||
];
|
||||
|
||||
const DEFAULT_THEMES_SERVICE_URL = 'http://127.0.0.1:3000';
|
||||
let cachedSessionToken: string | null = null;
|
||||
|
||||
export async function getThemesServiceUrl(): Promise<string> {
|
||||
const customUrl = await config.value<string>('themes_service_url').get('');
|
||||
return customUrl.trim().length > 0 ? customUrl.trim().replace(/\/+$/, '') : DEFAULT_THEMES_SERVICE_URL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns authentication headers using stored username and password,
|
||||
* plus session token if available.
|
||||
*/
|
||||
export async function getAuthHeaders(): Promise<Record<string, string>> {
|
||||
const headers: Record<string, string> = {};
|
||||
const username = await config.value<string>('username').get('');
|
||||
const password = await config.value<string>('password').get('');
|
||||
|
||||
if (username.length > 0 && password.length > 0) {
|
||||
headers['X-Username'] = username;
|
||||
headers['X-Password'] = password;
|
||||
}
|
||||
|
||||
const token = await getThemesAuthToken();
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
export async function getThemesAuthToken(forceRefresh = false): Promise<string | null> {
|
||||
if (!forceRefresh && cachedSessionToken) {
|
||||
return cachedSessionToken;
|
||||
}
|
||||
|
||||
const storedToken = await config.value<string>('themes_auth_token').get('');
|
||||
if (!forceRefresh && storedToken.trim().length > 0) {
|
||||
cachedSessionToken = storedToken.trim();
|
||||
return cachedSessionToken;
|
||||
}
|
||||
|
||||
// Attempt automatic login using saved username & password
|
||||
const username = await config.value<string>('username').get('');
|
||||
const password = await config.value<string>('password').get('');
|
||||
|
||||
if (username.length > 0 && password.length > 0) {
|
||||
try {
|
||||
const baseUrl = await getThemesServiceUrl();
|
||||
const res = await fetch(`${baseUrl}/v1/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
const data = (await res.json()) as { token: string };
|
||||
if (data.token) {
|
||||
cachedSessionToken = data.token;
|
||||
await config.value<string>('themes_auth_token').set(data.token);
|
||||
return cachedSessionToken;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[CommunityThemes] Auto-login failed:', err);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function fetchCommunityThemes(options?: {
|
||||
q?: string;
|
||||
tag?: string;
|
||||
authorId?: number;
|
||||
sort?: 'popular' | 'recent' | 'likes' | 'downloads';
|
||||
page?: number;
|
||||
limit?: number;
|
||||
}): Promise<CommunityThemesResponse> {
|
||||
let remoteData: CommunityThemesResponse | null = null;
|
||||
let remoteError: Error | null = null;
|
||||
|
||||
try {
|
||||
const baseUrl = await getThemesServiceUrl();
|
||||
const headers = await getAuthHeaders();
|
||||
|
||||
const url = new URL(`${baseUrl}/v1/themes`);
|
||||
if (options?.q) url.searchParams.set('q', options.q);
|
||||
if (options?.tag) url.searchParams.set('tag', options.tag);
|
||||
if (options?.authorId) url.searchParams.set('authorId', String(options.authorId));
|
||||
if (options?.sort) url.searchParams.set('sort', options.sort);
|
||||
if (options?.page) url.searchParams.set('page', String(options.page));
|
||||
if (options?.limit) url.searchParams.set('limit', String(options.limit));
|
||||
|
||||
const res = await fetch(url.toString(), { headers });
|
||||
if (res.ok) {
|
||||
remoteData = (await res.json()) as CommunityThemesResponse;
|
||||
for (const item of remoteData.items) {
|
||||
if (item.previewUrl && !item.previewUrl.startsWith('http')) {
|
||||
item.previewUrl = `${baseUrl}${item.previewUrl}`;
|
||||
}
|
||||
if (item.downloadUrl && !item.downloadUrl.startsWith('http')) {
|
||||
item.downloadUrl = `${baseUrl}${item.downloadUrl}`;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
remoteError = new Error(`Failed to load themes (HTTP ${res.status})`);
|
||||
}
|
||||
} catch (err) {
|
||||
remoteError = err instanceof Error ? err : new Error(String(err));
|
||||
console.warn('[CommunityThemes] Microservice unavailable, falling back to legacy catalogue:', err);
|
||||
}
|
||||
|
||||
// Filter legacy themes based on options
|
||||
const matchingLegacy = LEGACY_COMMUNITY_THEMES.filter((item) => {
|
||||
if (options?.authorId && options.authorId !== item.author.id) return false;
|
||||
if (options?.tag && options.tag !== 'all' && !item.tags.includes(options.tag.toLowerCase())) return false;
|
||||
if (options?.q && options.q.trim().length > 0) {
|
||||
const q = options.q.trim().toLowerCase();
|
||||
const text = `${item.name} ${item.description} ${item.id}`.toLowerCase();
|
||||
if (!text.includes(q)) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
if (!remoteData) {
|
||||
if (matchingLegacy.length > 0 || !remoteError) {
|
||||
return {
|
||||
items: matchingLegacy,
|
||||
total: matchingLegacy.length,
|
||||
page: 1,
|
||||
totalPages: 1,
|
||||
};
|
||||
}
|
||||
throw remoteError;
|
||||
}
|
||||
|
||||
// If remoteData returned, merge legacy themes if not already present in the list
|
||||
const existingIds = new Set(remoteData.items.map((i) => i.id.toLowerCase()));
|
||||
const missingLegacy = matchingLegacy.filter((l) => !existingIds.has(l.id.toLowerCase()));
|
||||
|
||||
const allItems = [...remoteData.items, ...missingLegacy];
|
||||
return {
|
||||
items: allItems,
|
||||
total: remoteData.total + missingLegacy.length,
|
||||
page: remoteData.page,
|
||||
totalPages: Math.ceil((remoteData.total + missingLegacy.length) / (options?.limit || 24)) || 1,
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchCommunityThemeDetails(themeId: string): Promise<CommunityTheme> {
|
||||
const cleanId = themeId.trim().toLowerCase();
|
||||
try {
|
||||
const baseUrl = await getThemesServiceUrl();
|
||||
const headers = await getAuthHeaders();
|
||||
|
||||
const res = await fetch(`${baseUrl}/v1/themes/${encodeURIComponent(cleanId)}`, { headers });
|
||||
if (res.ok) {
|
||||
const item = (await res.json()) as CommunityTheme;
|
||||
if (item.previewUrl && !item.previewUrl.startsWith('http')) {
|
||||
item.previewUrl = `${baseUrl}${item.previewUrl}`;
|
||||
}
|
||||
if (item.downloadUrl && !item.downloadUrl.startsWith('http')) {
|
||||
item.downloadUrl = `${baseUrl}${item.downloadUrl}`;
|
||||
}
|
||||
return item;
|
||||
}
|
||||
} catch {}
|
||||
|
||||
const legacy = LEGACY_COMMUNITY_THEMES.find((t) => t.id === cleanId);
|
||||
if (legacy) return legacy;
|
||||
|
||||
throw new Error('Theme not found.');
|
||||
}
|
||||
|
||||
export async function toggleCommunityThemeLike(themeId: string): Promise<{ liked: boolean; likeCount: number }> {
|
||||
const baseUrl = await getThemesServiceUrl();
|
||||
const headers = await getAuthHeaders();
|
||||
|
||||
if (!headers['X-Username'] && !headers['Authorization']) {
|
||||
throw new Error('Please log in to like community themes.');
|
||||
}
|
||||
|
||||
const res = await fetch(`${baseUrl}/v1/themes/${encodeURIComponent(themeId)}/like`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorJson = (await res.json().catch(() => ({}))) as { error?: string };
|
||||
throw new Error(errorJson.error || `Failed to like theme (HTTP ${res.status})`);
|
||||
}
|
||||
|
||||
return (await res.json()) as { liked: boolean; likeCount: number };
|
||||
}
|
||||
|
||||
export async function deleteCommunityTheme(themeId: string): Promise<void> {
|
||||
const baseUrl = await getThemesServiceUrl();
|
||||
const headers = await getAuthHeaders();
|
||||
|
||||
if (!headers['X-Username'] && !headers['Authorization']) {
|
||||
throw new Error('Please log in to manage your community themes.');
|
||||
}
|
||||
|
||||
const res = await fetch(`${baseUrl}/v1/themes/${encodeURIComponent(themeId)}`, {
|
||||
method: 'DELETE',
|
||||
headers,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorJson = (await res.json().catch(() => ({}))) as { error?: string };
|
||||
throw new Error(errorJson.error || `Failed to delete theme (HTTP ${res.status})`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 3-step Cloudflare-compliant chunked upload protocol (~15 MB slices).
|
||||
*/
|
||||
export async function publishThemeToWorkshop(options: {
|
||||
themeFolder: string;
|
||||
themeId: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
version?: string;
|
||||
apiVersion?: string;
|
||||
tags?: string[];
|
||||
previewImageBase64?: string;
|
||||
onProgress?: (status: string, percentage: number) => void;
|
||||
}): Promise<{ success: boolean; theme: any }> {
|
||||
const { onProgress = () => {} } = options;
|
||||
const baseUrl = await getThemesServiceUrl();
|
||||
const authHeaders = await getAuthHeaders();
|
||||
|
||||
if (!authHeaders['X-Username'] && !authHeaders['Authorization']) {
|
||||
throw new Error('You must be logged in to EZPPFarm to publish themes.');
|
||||
}
|
||||
|
||||
onProgress('Packaging theme archive...', 5);
|
||||
|
||||
const baseThemesDir = await themesDirectory();
|
||||
const tmpDir = await path.join(baseThemesDir, 'export_temp');
|
||||
if (!(await fs.exists(tmpDir))) {
|
||||
await fs.mkdir(tmpDir, { recursive: true });
|
||||
}
|
||||
|
||||
const destinationZip = await path.join(tmpDir, `${options.themeId}_workshop_export.zip`);
|
||||
|
||||
try {
|
||||
// 1. Export theme to a local zip archive
|
||||
await invoke('export_theme', {
|
||||
themeFolder: options.themeFolder,
|
||||
destinationPath: destinationZip,
|
||||
});
|
||||
|
||||
onProgress('Calculating checksum...', 10);
|
||||
|
||||
const totalSize = (await invoke<number>('file_size', { path: destinationZip })) ?? 0;
|
||||
if (totalSize === 0) {
|
||||
throw new Error('Failed to create theme archive (0 bytes).');
|
||||
}
|
||||
|
||||
const sha256 = await invoke<string>('hash_file_sha256', { path: destinationZip });
|
||||
|
||||
const CHUNK_SIZE = 15 * 1024 * 1024; // 15 MB
|
||||
const totalChunks = Math.ceil(totalSize / CHUNK_SIZE);
|
||||
|
||||
onProgress('Initializing upload session...', 15);
|
||||
|
||||
// Step 1: Init upload session
|
||||
const initRes = await fetch(`${baseUrl}/v1/themes/upload/init`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...authHeaders,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
themeId: options.themeId,
|
||||
name: options.name,
|
||||
description: options.description || '',
|
||||
version: options.version || '1.0.0',
|
||||
apiVersion: options.apiVersion || '2.0.0',
|
||||
totalSize,
|
||||
totalChunks,
|
||||
sha256,
|
||||
tags: options.tags || [],
|
||||
}),
|
||||
});
|
||||
|
||||
if (!initRes.ok) {
|
||||
const errData = (await initRes.json().catch(() => ({}))) as { error?: string };
|
||||
throw new Error(errData.error || `Upload initialization failed (HTTP ${initRes.status})`);
|
||||
}
|
||||
|
||||
const { uploadId } = (await initRes.json()) as { uploadId: string };
|
||||
|
||||
// Step 2: Upload chunks sequentially
|
||||
for (let i = 0; i < totalChunks; i++) {
|
||||
const offset = i * CHUNK_SIZE;
|
||||
const length = Math.min(CHUNK_SIZE, totalSize - offset);
|
||||
|
||||
const progressStart = 20 + Math.round((i / totalChunks) * 65);
|
||||
onProgress(`Uploading chunk ${i + 1} of ${totalChunks}...`, progressStart);
|
||||
|
||||
const chunkBytes = await invoke<number[]>('read_file_chunk', {
|
||||
path: destinationZip,
|
||||
offset,
|
||||
length,
|
||||
});
|
||||
|
||||
const chunkData = new Uint8Array(chunkBytes);
|
||||
|
||||
const chunkRes = await fetch(`${baseUrl}/v1/themes/upload/${uploadId}/chunk/${i}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/octet-stream',
|
||||
...authHeaders,
|
||||
},
|
||||
body: chunkData,
|
||||
});
|
||||
|
||||
if (!chunkRes.ok) {
|
||||
const errData = (await chunkRes.json().catch(() => ({}))) as { error?: string };
|
||||
throw new Error(errData.error || `Failed uploading chunk ${i + 1}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Step 3: Complete upload
|
||||
onProgress('Verifying integrity & finalizing...', 90);
|
||||
|
||||
const completeRes = await fetch(`${baseUrl}/v1/themes/upload/${uploadId}/complete`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...authHeaders,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
previewImageBase64: options.previewImageBase64,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!completeRes.ok) {
|
||||
const errData = (await completeRes.json().catch(() => ({}))) as { error?: string };
|
||||
throw new Error(errData.error || `Finalizing upload failed (HTTP ${completeRes.status})`);
|
||||
}
|
||||
|
||||
const completeData = await completeRes.json();
|
||||
onProgress('Theme published successfully!', 100);
|
||||
|
||||
return { success: true, theme: completeData };
|
||||
} finally {
|
||||
// Clean up temporary local zip
|
||||
if (await fs.exists(destinationZip)) {
|
||||
await fs.remove(destinationZip).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Download, extract, and register a community theme into ~/.ezpplauncher/themes/.
|
||||
*/
|
||||
export async function downloadAndInstallCommunityTheme(
|
||||
theme: CommunityTheme,
|
||||
onProgress?: (status: string, percentage: number) => void
|
||||
): Promise<{ success: boolean; folderName: string }> {
|
||||
const { onProgress: reportProgress = () => {} } = { onProgress };
|
||||
const baseThemesDir = await themesDirectory();
|
||||
const folderName = theme.id;
|
||||
const targetFolder = await path.join(baseThemesDir, folderName);
|
||||
|
||||
reportProgress('Downloading theme package...', 10);
|
||||
|
||||
const unlistenDownload = await listen<{ received: number; total: number; progress: number }>(
|
||||
'download_progress',
|
||||
(event) => {
|
||||
reportProgress('Downloading theme package...', Math.round(10 + event.payload.progress * 50));
|
||||
}
|
||||
);
|
||||
|
||||
const unlistenExtract = await listen<{ extracted: number; total: number; progress: number }>(
|
||||
'extract_progress',
|
||||
(event) => {
|
||||
reportProgress('Extracting theme files...', Math.round(60 + event.payload.progress * 38));
|
||||
}
|
||||
);
|
||||
|
||||
try {
|
||||
try {
|
||||
await invoke('download_and_extract_community_theme', {
|
||||
downloadUrl: theme.downloadUrl,
|
||||
themeFolder: targetFolder,
|
||||
themeName: theme.name,
|
||||
});
|
||||
} catch (err) {
|
||||
// Fallback for legacy themes directly to git repo
|
||||
if (theme.apiVersion === '1.0' || theme.tags?.includes('legacy')) {
|
||||
const fallbackUrl = `https://git.ez-pp.farm/EZPPFarm/EZPPLauncher-Themes/raw/branch/main/themes/${theme.id}.ezpplauncher-theme`;
|
||||
await invoke('download_and_extract_community_theme', {
|
||||
downloadUrl: fallbackUrl,
|
||||
themeFolder: targetFolder,
|
||||
themeName: theme.name,
|
||||
});
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
reportProgress('Theme installed!', 100);
|
||||
|
||||
// Refresh themes in launcher state
|
||||
await reloadThemes();
|
||||
|
||||
return { success: true, folderName };
|
||||
} finally {
|
||||
unlistenDownload();
|
||||
unlistenExtract();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import {
|
||||
fetchCommunityThemes,
|
||||
toggleCommunityThemeLike,
|
||||
downloadAndInstallCommunityTheme,
|
||||
type CommunityTheme,
|
||||
} from '$lib/communityThemes';
|
||||
import { active_custom_theme, custom_themes } from '$lib/global';
|
||||
import { reduceAnimations } from '$lib/userSettings';
|
||||
import { isThemeTrusted } from '$lib/themeTrust';
|
||||
import type { Theme } from '$lib/themes';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { Input } from '$lib/components/ui/input';
|
||||
import Badge from '$lib/components/ui/badge/badge.svelte';
|
||||
import ScrollContainer from '$lib/components/ui/scroll-container/ScrollContainer.svelte';
|
||||
import { sileo } from 'sileo';
|
||||
import {
|
||||
Check,
|
||||
Code2,
|
||||
Download,
|
||||
Globe,
|
||||
Heart,
|
||||
LoaderCircle,
|
||||
RefreshCw,
|
||||
Search,
|
||||
ShieldCheck,
|
||||
Sparkles,
|
||||
Tag,
|
||||
} from '@lucide/svelte';
|
||||
import DefaultThemePreview from '$assets/default_preview.png';
|
||||
|
||||
let {
|
||||
onApplyTheme,
|
||||
onRequestTrust,
|
||||
}: {
|
||||
onApplyTheme: (theme: Theme) => Promise<void>;
|
||||
onRequestTrust: (theme: Theme) => void;
|
||||
} = $props();
|
||||
|
||||
let searchQuery = $state('');
|
||||
let selectedTag = $state('all');
|
||||
let selectedSort = $state<'popular' | 'recent' | 'likes' | 'downloads'>('popular');
|
||||
|
||||
let themes = $state<CommunityTheme[]>([]);
|
||||
let totalThemes = $state(0);
|
||||
let loading = $state(false);
|
||||
let error = $state<string | null>(null);
|
||||
|
||||
let downloadingId = $state<string | null>(null);
|
||||
let downloadProgress = $state(0);
|
||||
let downloadStatus = $state('');
|
||||
|
||||
const TAGS = ['all', 'legacy', 'anime', 'minimal', 'video', 'audio', 'game', 'dark', 'clean'];
|
||||
|
||||
const localThemeMap = $derived.by(() => {
|
||||
const map = new Map<string, Theme>();
|
||||
for (const t of $custom_themes) {
|
||||
map.set(t.folder_name.toLowerCase(), t);
|
||||
map.set(t.name.toLowerCase(), t);
|
||||
}
|
||||
return map;
|
||||
});
|
||||
|
||||
async function loadWorkshopThemes() {
|
||||
loading = true;
|
||||
error = null;
|
||||
try {
|
||||
const res = await fetchCommunityThemes({
|
||||
q: searchQuery.trim().length > 0 ? searchQuery.trim() : undefined,
|
||||
tag: selectedTag !== 'all' ? selectedTag : undefined,
|
||||
sort: selectedSort,
|
||||
limit: 50,
|
||||
});
|
||||
themes = res.items;
|
||||
totalThemes = res.total;
|
||||
} catch (err) {
|
||||
console.warn('[Workshop] Failed to load community themes:', err);
|
||||
error = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
let searchDebounceTimeout: any = null;
|
||||
function handleSearchInput() {
|
||||
clearTimeout(searchDebounceTimeout);
|
||||
searchDebounceTimeout = setTimeout(() => {
|
||||
loadWorkshopThemes();
|
||||
}, 300);
|
||||
}
|
||||
|
||||
function handleTagClick(tag: string) {
|
||||
if (selectedTag === tag) return;
|
||||
selectedTag = tag;
|
||||
loadWorkshopThemes();
|
||||
}
|
||||
|
||||
function handleSortChange(sort: 'popular' | 'recent' | 'likes' | 'downloads') {
|
||||
if (selectedSort === sort) return;
|
||||
selectedSort = sort;
|
||||
loadWorkshopThemes();
|
||||
}
|
||||
|
||||
async function handleLike(theme: CommunityTheme, event: MouseEvent) {
|
||||
event.stopPropagation();
|
||||
const prevLiked = theme.isLiked;
|
||||
const prevCount = theme.likeCount;
|
||||
|
||||
// Optimistic update
|
||||
theme.isLiked = !prevLiked;
|
||||
theme.likeCount = prevLiked ? Math.max(0, prevCount - 1) : prevCount + 1;
|
||||
|
||||
try {
|
||||
const res = await toggleCommunityThemeLike(theme.id);
|
||||
theme.isLiked = res.liked;
|
||||
theme.likeCount = res.likeCount;
|
||||
} catch (err) {
|
||||
// Revert on error
|
||||
theme.isLiked = prevLiked;
|
||||
theme.likeCount = prevCount;
|
||||
sileo.error({
|
||||
title: 'Could not like theme',
|
||||
description: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDownloadAndApply(theme: CommunityTheme) {
|
||||
if (downloadingId) return;
|
||||
|
||||
downloadingId = theme.id;
|
||||
downloadProgress = 10;
|
||||
downloadStatus = 'Downloading theme package...';
|
||||
|
||||
try {
|
||||
const res = await downloadAndInstallCommunityTheme(theme, (msg, progress) => {
|
||||
downloadStatus = msg;
|
||||
downloadProgress = progress;
|
||||
});
|
||||
|
||||
sileo.success({
|
||||
title: 'Theme Installed',
|
||||
description: `"${theme.name}" has been installed to your library.`,
|
||||
});
|
||||
|
||||
// Find locally installed theme object
|
||||
const installed = $custom_themes.find(
|
||||
(t) => t.folder_name.toLowerCase() === res.folderName.toLowerCase()
|
||||
);
|
||||
|
||||
if (installed) {
|
||||
if (!isThemeTrusted(installed)) {
|
||||
onRequestTrust(installed);
|
||||
} else {
|
||||
await onApplyTheme(installed);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
sileo.error({
|
||||
title: 'Download failed',
|
||||
description: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
} finally {
|
||||
downloadingId = null;
|
||||
downloadProgress = 0;
|
||||
downloadStatus = '';
|
||||
}
|
||||
}
|
||||
|
||||
async function handleApplyExisting(theme: CommunityTheme) {
|
||||
const installed =
|
||||
localThemeMap.get(theme.id.toLowerCase()) ||
|
||||
localThemeMap.get(theme.name.toLowerCase());
|
||||
if (!installed) {
|
||||
await handleDownloadAndApply(theme);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isThemeTrusted(installed)) {
|
||||
onRequestTrust(installed);
|
||||
} else {
|
||||
await onApplyTheme(installed);
|
||||
}
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes === 0) return '0 B';
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`;
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
loadWorkshopThemes();
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="flex h-full flex-col overflow-hidden">
|
||||
<!-- Workshop Filter & Search Toolbar -->
|
||||
<div class="flex flex-col gap-2.5 pb-3">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<!-- Tag Chips -->
|
||||
<div class="flex min-w-0 flex-wrap items-center gap-1">
|
||||
{#each TAGS as tag}
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors {selectedTag === tag
|
||||
? 'bg-primary text-primary-foreground shadow-sm'
|
||||
: 'bg-theme-900/60 text-muted-foreground hover:bg-theme-800/60 hover:text-white'}"
|
||||
onclick={() => handleTagClick(tag)}
|
||||
>
|
||||
{tag === 'all' ? 'All Tags' : `#${tag}`}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<!-- Controls Right: Sort & Refresh -->
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<select
|
||||
class="h-7.5 rounded-lg border border-theme-800 bg-theme-950/80 px-2.5 text-[11px] text-muted-foreground outline-none transition-colors hover:text-white focus:border-primary/50"
|
||||
value={selectedSort}
|
||||
onchange={(e) => handleSortChange(e.currentTarget.value as any)}
|
||||
>
|
||||
<option value="popular">Most Popular</option>
|
||||
<option value="recent">Most Recent</option>
|
||||
<option value="likes">Most Liked</option>
|
||||
<option value="downloads">Most Downloaded</option>
|
||||
</select>
|
||||
|
||||
<div class="relative w-48">
|
||||
<Search class="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
class="h-7.5 border-theme-800 bg-theme-950/80 pl-8 text-[11px]"
|
||||
placeholder="Search workshop..."
|
||||
bind:value={searchQuery}
|
||||
oninput={handleSearchInput}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="size-7.5 text-muted-foreground hover:text-white"
|
||||
title="Refresh Workshop"
|
||||
onclick={loadWorkshopThemes}
|
||||
disabled={loading}
|
||||
>
|
||||
<RefreshCw class="size-3.5 {loading ? 'animate-spin' : ''}" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Content Grid / Status -->
|
||||
<div class="min-h-0 flex-1 pt-1">
|
||||
<ScrollContainer class="pr-2">
|
||||
{#if loading && themes.length === 0}
|
||||
<div class="flex h-64 flex-col items-center justify-center gap-3 text-muted-foreground">
|
||||
<LoaderCircle class="size-6 animate-spin text-primary" />
|
||||
<p class="text-xs">Connecting to EZPPFarm Community Workshop...</p>
|
||||
</div>
|
||||
{:else if error && themes.length === 0}
|
||||
<div class="flex h-64 flex-col items-center justify-center gap-3 text-center">
|
||||
<div class="rounded-full bg-red-500/10 p-3 text-red-400">
|
||||
<Globe class="size-6" />
|
||||
</div>
|
||||
<div class="max-w-md">
|
||||
<p class="text-sm font-semibold text-white">Workshop Offline or Unreachable</p>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
{error}. Ensure the themes microservice container is running.
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="secondary" size="sm" class="mt-2 text-xs" onclick={loadWorkshopThemes}>
|
||||
<RefreshCw class="mr-1.5 size-3.5" />
|
||||
Try Again
|
||||
</Button>
|
||||
</div>
|
||||
{:else if themes.length === 0}
|
||||
<div class="flex h-64 flex-col items-center justify-center gap-2 text-muted-foreground">
|
||||
<Globe class="size-8 opacity-40" />
|
||||
<p class="text-xs">No community themes found matching your search.</p>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="grid grid-cols-3 gap-3 pb-4">
|
||||
{#each themes as theme (theme.id)}
|
||||
{@const localTheme = localThemeMap.get(theme.id.toLowerCase()) || localThemeMap.get(theme.name.toLowerCase())}
|
||||
{@const isInstalled = Boolean(localTheme)}
|
||||
{@const isActive = Boolean(localTheme && $active_custom_theme?.folder_name === localTheme.folder_name)}
|
||||
{@const isDownloading = downloadingId === theme.id}
|
||||
{@const hasUpdate = Boolean(localTheme && localTheme.version !== theme.version)}
|
||||
|
||||
<div
|
||||
class="group flex flex-col overflow-hidden rounded-xl border bg-theme-900/30 {isActive
|
||||
? 'border-primary/60 ring-1 ring-primary/20'
|
||||
: 'border-theme-800/60'} transition-all duration-300 hover:-translate-y-0.5 hover:border-white/20 hover:bg-theme-900/50 hover:shadow-xl hover:shadow-black/30"
|
||||
>
|
||||
<!-- 16:9 Thumbnail -->
|
||||
<div class="relative aspect-video w-full shrink-0 overflow-hidden bg-theme-950/70">
|
||||
<img
|
||||
src={theme.previewUrl}
|
||||
alt={theme.name}
|
||||
class="h-full w-full object-cover object-center transition-transform duration-500 group-hover:scale-[1.03]"
|
||||
onerror={(e) => {
|
||||
// Fallback to default theme preview if server preview not loaded
|
||||
(e.currentTarget as HTMLImageElement).src = DefaultThemePreview;
|
||||
}}
|
||||
/>
|
||||
<div class="pointer-events-none absolute inset-0 bg-gradient-to-t from-theme-950/90 via-transparent to-transparent"></div>
|
||||
|
||||
<!-- Top Left: Trust Badge -->
|
||||
<div class="absolute top-2 left-2 flex items-center gap-1.5">
|
||||
{#if theme.apiVersion === '1.0' || theme.tags?.includes('legacy')}
|
||||
<span
|
||||
class="flex items-center gap-1 rounded-md border border-purple-500/40 bg-purple-950/80 px-1.5 py-0.5 text-[9px] font-medium text-purple-300 backdrop-blur-sm"
|
||||
title="Legacy v1 theme: video/audio playback"
|
||||
>
|
||||
<Sparkles class="size-3 text-purple-300" />
|
||||
Legacy v1
|
||||
</span>
|
||||
{:else if !theme.hasExecutableCode}
|
||||
<span
|
||||
class="flex items-center gap-1 rounded-md border border-emerald-500/30 bg-emerald-950/80 px-1.5 py-0.5 text-[9px] font-medium text-emerald-300 backdrop-blur-sm"
|
||||
title="Sandboxed Declarative Theme: pure styles, no executable JS code"
|
||||
>
|
||||
<ShieldCheck class="size-3" />
|
||||
Declarative
|
||||
</span>
|
||||
{:else}
|
||||
<span
|
||||
class="flex items-center gap-1 rounded-md border border-amber-500/30 bg-amber-950/80 px-1.5 py-0.5 text-[9px] font-medium text-amber-300 backdrop-blur-sm"
|
||||
title="Contains custom Svelte 5 executable logic"
|
||||
>
|
||||
<Code2 class="size-3" />
|
||||
Svelte Code
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Top Right: Version -->
|
||||
<div class="absolute top-2 right-2">
|
||||
<span class="rounded-md bg-black/60 px-1.5 py-0.5 text-[9px] font-medium text-white/90 backdrop-blur-sm">
|
||||
v{theme.version}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Bottom: Author Info -->
|
||||
<div class="absolute right-2 bottom-2 left-2 flex items-center justify-between gap-2">
|
||||
<div class="flex min-w-0 items-center gap-1.5">
|
||||
<img
|
||||
src={theme.author.avatarUrl}
|
||||
alt={theme.author.name}
|
||||
class="size-5 rounded-full border border-white/20 bg-theme-900 object-cover"
|
||||
onerror={(e) => {
|
||||
(e.currentTarget as HTMLElement).style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
<span class="truncate text-[11px] font-semibold text-white/95 drop-shadow-sm">
|
||||
{theme.author.name}
|
||||
</span>
|
||||
{#if theme.author.donor}
|
||||
<span
|
||||
class="flex items-center gap-0.5 rounded-full bg-amber-500/20 px-1 py-0.5 text-[8px] font-bold text-amber-300 border border-amber-500/30"
|
||||
title="EZPPFarm Supporter"
|
||||
>
|
||||
<Sparkles class="size-2.5 fill-amber-300" />
|
||||
Supporter
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
<span class="text-[9px] text-muted-foreground/90 tabular-nums">
|
||||
{formatBytes(theme.fileSize)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Body -->
|
||||
<div class="flex flex-1 flex-col justify-between gap-2 p-3">
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<h3 class="truncate text-[13px] font-bold text-white group-hover:text-primary transition-colors">
|
||||
{theme.name}
|
||||
</h3>
|
||||
|
||||
<!-- Interactive Like Button -->
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] transition-colors {theme.isLiked
|
||||
? 'bg-rose-500/20 text-rose-300 hover:bg-rose-500/30'
|
||||
: 'bg-theme-800/40 text-muted-foreground hover:bg-theme-800/80 hover:text-white'}"
|
||||
onclick={(e) => handleLike(theme, e)}
|
||||
title={theme.isLiked ? 'Unlike' : 'Like'}
|
||||
>
|
||||
<Heart class="size-3 {theme.isLiked ? 'fill-rose-400 text-rose-400' : ''}" />
|
||||
<span class="tabular-nums text-[10px]">{theme.likeCount}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if theme.description}
|
||||
<p class="mt-1 line-clamp-2 text-[10px] leading-relaxed text-muted-foreground">
|
||||
{theme.description}
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
{#if theme.tags && theme.tags.length > 0}
|
||||
<div class="mt-2 flex flex-wrap gap-1">
|
||||
{#each theme.tags.slice(0, 3) as tag}
|
||||
<span class="rounded bg-theme-800/50 px-1.5 py-0.5 text-[9px] text-muted-foreground">
|
||||
#{tag}
|
||||
</span>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Footer Action Row -->
|
||||
<div class="mt-2 flex items-center justify-between border-t border-theme-800/40 pt-2.5">
|
||||
<div class="flex items-center gap-1 text-[10px] text-muted-foreground">
|
||||
<Download class="size-3" />
|
||||
<span class="tabular-nums">{theme.downloadCount}</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{#if isDownloading}
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-[10px] text-primary tabular-nums">{downloadProgress}%</span>
|
||||
<div class="h-1.5 w-16 overflow-hidden rounded-full bg-theme-800">
|
||||
<div
|
||||
class="h-full bg-primary transition-all duration-200"
|
||||
style="width: {downloadProgress}%"
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
{:else if isActive}
|
||||
<Badge variant="outline" class="border-emerald-500/40 bg-emerald-950/20 text-emerald-300 text-[10px]">
|
||||
<Check class="mr-1 size-3" /> In use
|
||||
</Badge>
|
||||
{:else if isInstalled && hasUpdate}
|
||||
<Button
|
||||
size="sm"
|
||||
class="h-7 text-xs bg-cyan-600 hover:bg-cyan-500 text-white font-medium"
|
||||
onclick={() => handleDownloadAndApply(theme)}
|
||||
>
|
||||
Update
|
||||
</Button>
|
||||
{:else if isInstalled}
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
class="h-7 text-xs"
|
||||
onclick={() => handleApplyExisting(theme)}
|
||||
>
|
||||
Apply
|
||||
</Button>
|
||||
{:else}
|
||||
<Button
|
||||
size="sm"
|
||||
class="h-7 text-xs"
|
||||
onclick={() => handleDownloadAndApply(theme)}
|
||||
>
|
||||
<Download class="mr-1 size-3" />
|
||||
Download & Apply
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</ScrollContainer>
|
||||
</div>
|
||||
</div>
|
||||
@@ -76,6 +76,7 @@
|
||||
themeAssetName,
|
||||
themeHasLaunchButton,
|
||||
type ThemeV2Asset,
|
||||
type ThemeV2Audio,
|
||||
type ThemeV2Background,
|
||||
type ThemeV2BehaviorTarget,
|
||||
type ThemeV2ButtonAction,
|
||||
@@ -99,6 +100,7 @@
|
||||
themesDirectory,
|
||||
toSafeName,
|
||||
} from '$lib/themes';
|
||||
import { publishThemeToWorkshop } from '$lib/communityThemes';
|
||||
import type { EZPPUser, EZPPUserInfo } from '$lib/types';
|
||||
import { currentUser } from '$lib/userAuthentication';
|
||||
import { osuInstallationPath } from '$lib/userSettings';
|
||||
@@ -125,6 +127,7 @@
|
||||
EyeOff,
|
||||
Film,
|
||||
Gauge,
|
||||
Globe,
|
||||
GripVertical,
|
||||
Hand,
|
||||
Image as ImageIcon,
|
||||
@@ -252,6 +255,7 @@
|
||||
let lastGradientBackground = $state<Extract<ThemeV2Background, { type: 'gradient' }> | undefined>(
|
||||
undefined
|
||||
);
|
||||
let lastAudio = $state<ThemeV2Audio | undefined>(undefined);
|
||||
let assetBase = $state('');
|
||||
let savedFolder = $state<string | undefined>(undefined);
|
||||
let editorFolderPath = $state<string | undefined>(undefined);
|
||||
@@ -1803,6 +1807,7 @@
|
||||
? normalizeThemeV2(JSON.parse(context.themeJson) as Partial<ThemeV2Definition>)
|
||||
: createDefaultThemeV2();
|
||||
definition = ensureDefaults(parsed);
|
||||
lastAudio = parsed.audio ? { ...parsed.audio } : undefined;
|
||||
savedFolder = context.folderName ?? undefined;
|
||||
editorFolderPath = context.folderPath ?? undefined;
|
||||
const httpBase = await themeAssetBase();
|
||||
@@ -1992,6 +1997,9 @@
|
||||
color: current.type === 'color' ? current.color : (lastColorBackground?.color ?? '#181825'),
|
||||
opacity: lastColorBackground?.opacity ?? opacity,
|
||||
};
|
||||
if (!definition.audio && lastAudio) {
|
||||
definition.audio = { ...lastAudio };
|
||||
}
|
||||
} else if (type === 'gradient') {
|
||||
definition.background = {
|
||||
type: 'gradient',
|
||||
@@ -2004,6 +2012,9 @@
|
||||
: (lastGradientBackground?.angle ?? 135),
|
||||
opacity: lastGradientBackground?.opacity ?? opacity,
|
||||
};
|
||||
if (!definition.audio && lastAudio) {
|
||||
definition.audio = { ...lastAudio };
|
||||
}
|
||||
} else if (type === 'video') {
|
||||
const candidateVideo =
|
||||
current.type === 'video' && current.src
|
||||
@@ -2024,6 +2035,9 @@
|
||||
if (candidateVideo) {
|
||||
lastVideoBackground = { ...definition.background };
|
||||
}
|
||||
if (definition.audio) {
|
||||
lastAudio = { ...definition.audio };
|
||||
}
|
||||
definition.audio = undefined;
|
||||
} else {
|
||||
const candidateImage =
|
||||
@@ -2043,6 +2057,9 @@
|
||||
if (candidateImage) {
|
||||
lastImageBackground = { ...definition.background };
|
||||
}
|
||||
if (!definition.audio && lastAudio) {
|
||||
definition.audio = { ...lastAudio };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2086,6 +2103,7 @@
|
||||
const asset = await chooseAsset('audio');
|
||||
if (!asset) return;
|
||||
definition.audio = { src: asset.name, loop: definition.audio?.loop !== false };
|
||||
lastAudio = { ...definition.audio };
|
||||
}
|
||||
|
||||
function uniqueFamily(label: string) {
|
||||
@@ -3313,6 +3331,100 @@
|
||||
}
|
||||
}
|
||||
|
||||
let publishModalOpen = $state(false);
|
||||
let publishThemeId = $state('');
|
||||
let publishName = $state('');
|
||||
let publishDescription = $state('');
|
||||
let publishVersion = $state('1.0.0');
|
||||
let publishTags = $state('anime, video');
|
||||
let publishing = $state(false);
|
||||
let publishStatusMessage = $state('');
|
||||
let publishProgress = $state(0);
|
||||
|
||||
async function openPublishDialog() {
|
||||
if (exporting || saving || publishing) return;
|
||||
|
||||
if (!$currentUser) {
|
||||
sileo.error({
|
||||
title: 'Authentication Required',
|
||||
description:
|
||||
'You must be logged in to your EZPPFarm account to publish themes to the workshop.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const report = await validateTheme();
|
||||
validationReport = report;
|
||||
const errors = report.issues.some((issue) => issue.level === 'error');
|
||||
if (errors) {
|
||||
validationOpen = true;
|
||||
exportAfterValidation = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (dirty) {
|
||||
await saveTheme({ notify: false });
|
||||
}
|
||||
|
||||
publishThemeId = savedFolder || toSafeName(definition.name);
|
||||
publishName = definition.name || 'My Theme';
|
||||
publishDescription = definition.description || '';
|
||||
publishVersion = definition.version || '1.0.0';
|
||||
publishTags = 'workshop, v2';
|
||||
publishProgress = 0;
|
||||
publishStatusMessage = '';
|
||||
publishModalOpen = true;
|
||||
}
|
||||
|
||||
async function handlePublishToWorkshop() {
|
||||
if (publishing) return;
|
||||
if (!savedFolder) {
|
||||
await saveTheme({ notify: false });
|
||||
if (!savedFolder) return;
|
||||
}
|
||||
|
||||
publishing = true;
|
||||
publishProgress = 5;
|
||||
publishStatusMessage = 'Packaging theme archive...';
|
||||
|
||||
try {
|
||||
const baseThemesDir = await themesDirectory();
|
||||
const themeFolder = await path.join(baseThemesDir, savedFolder);
|
||||
|
||||
await publishThemeToWorkshop({
|
||||
themeFolder,
|
||||
themeId: publishThemeId,
|
||||
name: publishName,
|
||||
description: publishDescription,
|
||||
version: publishVersion,
|
||||
apiVersion: definition.apiVersion || '2.0.0',
|
||||
tags: publishTags
|
||||
.split(',')
|
||||
.map((t) => t.trim())
|
||||
.filter(Boolean),
|
||||
onProgress: (msg, pct) => {
|
||||
publishStatusMessage = msg;
|
||||
publishProgress = pct;
|
||||
},
|
||||
});
|
||||
|
||||
sileo.success({
|
||||
title: 'Published to Workshop!',
|
||||
description: `"${publishName}" is now live in the Community Themes Workshop.`,
|
||||
});
|
||||
|
||||
publishModalOpen = false;
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
sileo.error({
|
||||
title: 'Publish Failed',
|
||||
description: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
} finally {
|
||||
publishing = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function closeEditor() {
|
||||
if (saving) return;
|
||||
if (dirty) {
|
||||
@@ -3735,7 +3847,7 @@
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onclick={() => exportCurrentTheme()}
|
||||
disabled={exporting || saving}
|
||||
disabled={exporting || saving || publishing}
|
||||
>
|
||||
{#if exporting}
|
||||
<LoaderCircle class="animate-spin" />
|
||||
@@ -3744,6 +3856,20 @@
|
||||
{/if}
|
||||
Export
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onclick={openPublishDialog}
|
||||
disabled={exporting || saving || publishing}
|
||||
class="border-cyan-500/30 bg-cyan-950/20 text-cyan-300 hover:bg-cyan-950/40 hover:text-cyan-200"
|
||||
>
|
||||
{#if publishing}
|
||||
<LoaderCircle class="animate-spin" />
|
||||
{:else}
|
||||
<Globe class="size-4" />
|
||||
{/if}
|
||||
Publish
|
||||
</Button>
|
||||
<Button size="sm" onclick={() => saveTheme()} disabled={saving || loading}>
|
||||
{#if saving}
|
||||
<LoaderCircle class="animate-spin" />
|
||||
@@ -5622,7 +5748,10 @@
|
||||
size="icon"
|
||||
class="size-8 text-muted-foreground"
|
||||
title="Remove music"
|
||||
onclick={() => (definition.audio = undefined)}
|
||||
onclick={() => {
|
||||
definition.audio = undefined;
|
||||
lastAudio = undefined;
|
||||
}}
|
||||
>
|
||||
<X class="size-3.5" />
|
||||
</Button>
|
||||
@@ -6612,4 +6741,167 @@
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if publishModalOpen}
|
||||
<div
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/75 p-6 backdrop-blur-md"
|
||||
role="presentation"
|
||||
>
|
||||
<div
|
||||
class="w-full max-w-lg rounded-2xl border border-theme-800 bg-theme-950 p-6 shadow-2xl"
|
||||
role="dialog"
|
||||
aria-labelledby="publish-dialog-title"
|
||||
>
|
||||
<div class="flex items-center justify-between border-b border-theme-800/60 pb-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="rounded-lg bg-cyan-500/10 p-2 text-cyan-400">
|
||||
<Globe class="size-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 id="publish-dialog-title" class="text-base font-semibold text-white">
|
||||
Publish to Community Workshop
|
||||
</h2>
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
Share your theme with the EZPPFarm community.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{#if !publishing}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="size-7 text-muted-foreground hover:text-white"
|
||||
onclick={() => (publishModalOpen = false)}
|
||||
>
|
||||
<X class="size-4" />
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if $currentUser}
|
||||
<div class="mt-4 flex items-center justify-between rounded-xl border border-theme-800/70 bg-theme-900/40 px-3.5 py-2.5">
|
||||
<div class="flex items-center gap-2.5">
|
||||
<img
|
||||
src={`https://a.ez-pp.farm/${$currentUser.id}`}
|
||||
alt={$currentUser.name}
|
||||
class="size-8 rounded-full border border-white/20 bg-theme-800 object-cover"
|
||||
onerror={(e) => {
|
||||
(e.currentTarget as HTMLElement).style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
<div>
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="text-xs font-semibold text-white">{$currentUser.name}</span>
|
||||
{#if $currentUser.donor}
|
||||
<span class="rounded bg-amber-500/20 px-1 py-0.2 text-[8px] font-bold text-amber-300 border border-amber-500/30">
|
||||
Supporter
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
<span class="text-[10px] text-muted-foreground">Creator & Publisher</span>
|
||||
</div>
|
||||
</div>
|
||||
<span class="text-[10px] text-emerald-400 font-medium">Verified Account</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mt-4 flex flex-col gap-3">
|
||||
<div>
|
||||
<Label class="text-[11px] text-muted-foreground">Workshop Identifier (Slug)</Label>
|
||||
<Input
|
||||
class="mt-1 h-8 border-theme-800 bg-theme-900/50 text-xs font-mono"
|
||||
bind:value={publishThemeId}
|
||||
placeholder="e.g. lucoa-theme"
|
||||
disabled={publishing}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-3 gap-2">
|
||||
<div class="col-span-2">
|
||||
<Label class="text-[11px] text-muted-foreground">Theme Name</Label>
|
||||
<Input
|
||||
class="mt-1 h-8 border-theme-800 bg-theme-900/50 text-xs"
|
||||
bind:value={publishName}
|
||||
placeholder="My Awesome Theme"
|
||||
disabled={publishing}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label class="text-[11px] text-muted-foreground">Version</Label>
|
||||
<Input
|
||||
class="mt-1 h-8 border-theme-800 bg-theme-900/50 text-xs font-mono"
|
||||
bind:value={publishVersion}
|
||||
placeholder="1.0.0"
|
||||
disabled={publishing}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label class="text-[11px] text-muted-foreground">Description</Label>
|
||||
<Textarea
|
||||
class="mt-1 border-theme-800 bg-theme-900/50 text-xs leading-relaxed"
|
||||
rows={2}
|
||||
bind:value={publishDescription}
|
||||
placeholder="Tell others about your theme..."
|
||||
disabled={publishing}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label class="text-[11px] text-muted-foreground">Tags (comma-separated)</Label>
|
||||
<Input
|
||||
class="mt-1 h-8 border-theme-800 bg-theme-900/50 text-xs"
|
||||
bind:value={publishTags}
|
||||
placeholder="anime, video, clean"
|
||||
disabled={publishing}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if publishing}
|
||||
<div class="mt-4 rounded-xl border border-cyan-500/20 bg-cyan-950/20 p-3">
|
||||
<div class="flex items-center justify-between text-xs">
|
||||
<span class="flex items-center gap-1.5 text-cyan-300 font-medium">
|
||||
<LoaderCircle class="size-3.5 animate-spin" />
|
||||
{publishStatusMessage}
|
||||
</span>
|
||||
<span class="font-mono text-cyan-400 font-bold tabular-nums">{publishProgress}%</span>
|
||||
</div>
|
||||
<div class="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-theme-900">
|
||||
<div
|
||||
class="h-full bg-cyan-400 transition-all duration-300"
|
||||
style="width: {publishProgress}%"
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mt-5 flex justify-end gap-2 border-t border-theme-800/60 pt-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onclick={() => (publishModalOpen = false)}
|
||||
disabled={publishing}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
class="bg-cyan-600 hover:bg-cyan-500 text-white font-medium gap-1.5"
|
||||
onclick={handlePublishToWorkshop}
|
||||
disabled={publishing || publishThemeId.trim().length < 2 || publishName.trim().length === 0}
|
||||
>
|
||||
{#if publishing}
|
||||
<LoaderCircle class="size-3.5 animate-spin" />
|
||||
Publishing...
|
||||
{:else}
|
||||
<Globe class="size-3.5" />
|
||||
Publish to Workshop
|
||||
{/if}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -2231,7 +2231,7 @@
|
||||
element.widget = val as ThemeV2WidgetKind;
|
||||
if (val === 'player-card') {
|
||||
element.width = 380;
|
||||
element.height = 180;
|
||||
element.height = 220;
|
||||
} else if (val === 'avatar') {
|
||||
element.width = 72;
|
||||
element.height = 72;
|
||||
@@ -2296,12 +2296,18 @@
|
||||
if (val === 'minimal') {
|
||||
element.width = 280;
|
||||
element.height = 64;
|
||||
} else if (val === 'banner') {
|
||||
element.width = 340;
|
||||
element.height = 76;
|
||||
element.showStats = false;
|
||||
} else if (val === 'compact') {
|
||||
element.width = 340;
|
||||
element.height = 120;
|
||||
element.height = 140;
|
||||
element.showStats = true;
|
||||
} else if (val === 'full') {
|
||||
element.width = 380;
|
||||
element.height = 200;
|
||||
element.height = 220;
|
||||
element.showStats = true;
|
||||
}
|
||||
} else if (element.widget === 'recent-activity') {
|
||||
if (val === 'minimal') {
|
||||
@@ -2356,6 +2362,14 @@
|
||||
: element.variant === 'icon-only'
|
||||
? 'Icon-Only (Circle)'
|
||||
: 'Primary (Capsule)'}
|
||||
{:else if element.widget === 'player-card'}
|
||||
{element.variant === 'compact'
|
||||
? 'Compact (2 Stats)'
|
||||
: element.variant === 'minimal'
|
||||
? 'Minimal (Pill)'
|
||||
: element.variant === 'banner'
|
||||
? 'Banner (Profile & Level Only)'
|
||||
: 'Full (4 Stats)'}
|
||||
{:else}
|
||||
{element.variant === 'compact'
|
||||
? 'Compact'
|
||||
@@ -2373,6 +2387,11 @@
|
||||
<Select.Item value="primary" label="Primary (Capsule)" />
|
||||
<Select.Item value="compact" label="Compact (Pill)" />
|
||||
<Select.Item value="icon-only" label="Icon-Only (Circle)" />
|
||||
{:else if element.widget === 'player-card'}
|
||||
<Select.Item value="full" label="Full (4 Stats)" />
|
||||
<Select.Item value="compact" label="Compact (2 Stats)" />
|
||||
<Select.Item value="banner" label="Banner (Profile & Level Only)" />
|
||||
<Select.Item value="minimal" label="Minimal (Pill)" />
|
||||
{:else}
|
||||
<Select.Item value="full" label="Full" />
|
||||
<Select.Item value="compact" label="Compact" />
|
||||
@@ -2382,6 +2401,33 @@
|
||||
</Select.Root>
|
||||
</div>
|
||||
|
||||
{#if element.widget === 'player-card' && element.variant !== 'minimal'}
|
||||
<div class="space-y-2 border-t border-theme-800 pt-2">
|
||||
<Label class={label}>Player Card Options</Label>
|
||||
<div class="space-y-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="element-player-stats"
|
||||
checked={element.showStats !== false && element.variant !== 'banner'}
|
||||
onCheckedChange={(checked) => {
|
||||
element.showStats = checked === true;
|
||||
if (!checked) {
|
||||
element.variant = 'banner';
|
||||
element.height = Math.min(element.height, 80);
|
||||
} else {
|
||||
element.variant = 'full';
|
||||
element.height = Math.max(element.height, 220);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Label for="element-player-stats" class="text-xs text-theme-100 cursor-pointer">
|
||||
Show stats grid (rank, pp, accuracy, plays)
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if element.widget === 'avatar'}
|
||||
<div class="space-y-2 border-t border-theme-800 pt-2">
|
||||
<Label class={label}>Avatar Display Options</Label>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { custom_theme_volume } from '$lib/global';
|
||||
import { themeMediaSource, themeVideoLifecycle } from '$lib/themeMedia';
|
||||
import { playThemeMedia, themeMediaSource, themeVideoLifecycle } from '$lib/themeMedia';
|
||||
import type { ThemeV2Definition } from '$lib/themeV2';
|
||||
import { themeAssetUrl } from '$lib/themeV2';
|
||||
import { reduceAnimations } from '$lib/userSettings';
|
||||
@@ -64,6 +64,14 @@
|
||||
if (animFrame !== undefined) {
|
||||
cancelAnimationFrame(animFrame);
|
||||
}
|
||||
if (audioElement) {
|
||||
try {
|
||||
audioElement.pause();
|
||||
audioElement.src = '';
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const assetUrl = (path: string | undefined) => {
|
||||
@@ -126,10 +134,8 @@
|
||||
$effect(() => {
|
||||
if (!audioElement || !definition.audio) return;
|
||||
audioElement.volume = $custom_theme_volume;
|
||||
if (!preview) {
|
||||
audioElement.play().catch(() => {
|
||||
// Autoplay can be rejected until the window has been interacted with.
|
||||
});
|
||||
if (!preview && audioElement.paused) {
|
||||
playThemeMedia(audioElement);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
@@ -225,6 +231,8 @@
|
||||
use:themeMediaSource={assetUrl(definition.audio.src)}
|
||||
loop={definition.audio.loop !== false}
|
||||
autoplay
|
||||
preload="auto"
|
||||
playsinline
|
||||
></audio>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -2027,7 +2027,7 @@
|
||||
|
||||
{#if element.variant === 'minimal'}
|
||||
<div
|
||||
class="flex h-full w-full items-center gap-2.5 rounded-2xl border border-white/10 bg-black/55 px-3 py-2 text-theme-50 shadow-xl backdrop-blur-md"
|
||||
class="flex h-full w-full items-center gap-2.5 overflow-hidden rounded-2xl border border-white/10 bg-black/55 px-3 py-2 text-theme-50 shadow-xl backdrop-blur-md"
|
||||
>
|
||||
<div class="relative shrink-0">
|
||||
<Avatar.Root
|
||||
@@ -2067,7 +2067,7 @@
|
||||
</div>
|
||||
{:else if element.variant === 'compact'}
|
||||
<div
|
||||
class="flex h-full w-full flex-col justify-between rounded-2xl border border-white/10 bg-black/55 p-3 text-theme-50 shadow-xl backdrop-blur-md"
|
||||
class="flex h-full w-full flex-col justify-between overflow-hidden rounded-2xl border border-white/10 bg-black/55 p-3 text-theme-50 shadow-xl backdrop-blur-md"
|
||||
>
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="relative shrink-0">
|
||||
@@ -2125,9 +2125,56 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{:else if element.variant === 'banner' || element.showStats === false || element.height < 140}
|
||||
<div
|
||||
class="flex h-full w-full items-center gap-3 overflow-hidden rounded-2xl border border-white/10 bg-black/55 p-3.5 text-theme-50 shadow-xl backdrop-blur-md"
|
||||
>
|
||||
<div class="relative shrink-0">
|
||||
<Avatar.Root
|
||||
class="size-12 rounded-xl border border-white/15 bg-theme-900 shadow-md"
|
||||
>
|
||||
<Avatar.Image
|
||||
src="https://a.ez-pp.farm/{playerId}"
|
||||
alt={playerName}
|
||||
class="h-full w-full object-cover"
|
||||
/>
|
||||
<Avatar.Fallback
|
||||
class="flex h-full w-full items-center justify-center bg-theme-900 text-primary"
|
||||
>
|
||||
<ThemeIcon name="user" set={iconSet} size={22} />
|
||||
</Avatar.Fallback>
|
||||
</Avatar.Root>
|
||||
{#if country}
|
||||
<span
|
||||
class="absolute -bottom-1 -right-1 flex items-center justify-center rounded-md border border-white/20 bg-black/90 px-1 py-0.5 text-[10px] leading-none shadow"
|
||||
title={country.toUpperCase()}
|
||||
>
|
||||
{countryCodeToEmoji(country)}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="min-w-0 flex flex-col justify-center flex-1">
|
||||
<span class="block truncate text-sm font-bold text-white">{playerName}</span>
|
||||
<div class="flex items-center gap-2 mt-1">
|
||||
<span class="text-[11px] font-semibold text-white/80 shrink-0">
|
||||
Lv.{levelVal}
|
||||
</span>
|
||||
<div class="w-20 rounded-full bg-white/10 h-1.5 overflow-hidden">
|
||||
<div
|
||||
class="h-full bg-primary rounded-full transition-all"
|
||||
style="width: {levelProgress}%"
|
||||
></div>
|
||||
</div>
|
||||
<span class="text-[10px] text-muted-foreground font-mono">
|
||||
{levelProgress}%
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div
|
||||
class="flex h-full w-full flex-col justify-between rounded-2xl border border-white/10 bg-black/55 p-3.5 text-theme-50 shadow-xl backdrop-blur-md"
|
||||
class="flex h-full w-full flex-col justify-between overflow-hidden rounded-2xl border border-white/10 bg-black/55 p-3.5 text-theme-50 shadow-xl backdrop-blur-md"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-3 min-w-0">
|
||||
@@ -2514,7 +2561,21 @@
|
||||
<span
|
||||
class="absolute -top-7 left-0 rounded bg-primary px-1.5 py-0.5 text-[10px] font-semibold text-primary-foreground shadow"
|
||||
>
|
||||
{element.type}
|
||||
{element.type === 'widget'
|
||||
? element.widget === 'player-card'
|
||||
? 'Player Card'
|
||||
: element.widget === 'recent-activity'
|
||||
? 'Recent Activity'
|
||||
: element.widget === 'launch-button'
|
||||
? 'Launch Button'
|
||||
: element.widget === 'telemetry'
|
||||
? 'Telemetry Bar'
|
||||
: element.widget === 'header'
|
||||
? 'Header Title'
|
||||
: element.widget === 'avatar'
|
||||
? 'Player Avatar'
|
||||
: 'Widget'
|
||||
: element.type}
|
||||
</span>
|
||||
{/if}
|
||||
|
||||
|
||||
@@ -27,57 +27,55 @@
|
||||
</script>
|
||||
|
||||
<div data-tauri-drag-region class="titlebar z-[100]" class:macos-window={$platform === 'macos'}>
|
||||
{#if $custom_theme_audio_playing}
|
||||
{#if $custom_theme_audio_playing}
|
||||
<div class="relative flex items-center justify-center group">
|
||||
<div class="relative flex items-center justify-center p-1 cursor-pointer">
|
||||
<div
|
||||
class="absolute inset-0 bg-background rounded
|
||||
scale-80 opacity-0
|
||||
group-hover:opacity-100
|
||||
group-hover:scale-100
|
||||
{$reduceAnimations ? '' : 'transition-all duration-200 ease-out'}"
|
||||
></div>
|
||||
{#if $custom_theme_audio_playing || ($active_custom_theme && $active_custom_theme.name !== 'Default')}
|
||||
<div class="relative flex items-center justify-center group">
|
||||
<div class="relative flex items-center justify-center p-1 cursor-pointer">
|
||||
<div
|
||||
class="absolute inset-0 bg-background rounded
|
||||
scale-80 opacity-0
|
||||
group-hover:opacity-100
|
||||
group-hover:scale-100
|
||||
{$reduceAnimations ? '' : 'transition-all duration-200 ease-out'}"
|
||||
></div>
|
||||
|
||||
{#if $custom_theme_volume > 0.7}
|
||||
<ThemeIcon name="volume" set={iconSet} class="z-10 pointer-events-none" size={14} />
|
||||
{:else if $custom_theme_volume >= 0.15}
|
||||
<ThemeIcon name="volume-low" set={iconSet} class="z-10 pointer-events-none" size={14} />
|
||||
{:else if $custom_theme_volume > 0}
|
||||
<ThemeIcon name="volume-low" set={iconSet} class="z-10 pointer-events-none" size={14} />
|
||||
{:else}
|
||||
<ThemeIcon name="volume-off" set={iconSet} class="z-10 pointer-events-none" size={14} />
|
||||
{/if}
|
||||
</div>
|
||||
{#if $custom_theme_volume > 0.7}
|
||||
<ThemeIcon name="volume" set={iconSet} class="z-10 pointer-events-none" size={14} />
|
||||
{:else if $custom_theme_volume >= 0.15}
|
||||
<ThemeIcon name="volume-low" set={iconSet} class="z-10 pointer-events-none" size={14} />
|
||||
{:else if $custom_theme_volume > 0}
|
||||
<ThemeIcon name="volume-low" set={iconSet} class="z-10 pointer-events-none" size={14} />
|
||||
{:else}
|
||||
<ThemeIcon name="volume-off" set={iconSet} class="z-10 pointer-events-none" size={14} />
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="absolute top-full right-0 translate-x-[7px]
|
||||
opacity-0 invisible pointer-events-none -translate-y-2
|
||||
group-hover:opacity-100 group-hover:visible group-hover:pointer-events-auto group-hover:translate-y-0
|
||||
{$reduceAnimations ? '' : 'transition-all duration-200 ease-out'}
|
||||
z-50"
|
||||
>
|
||||
<div class="h-2 w-full"></div>
|
||||
|
||||
<div
|
||||
class="absolute top-full right-0 translate-x-[7px]
|
||||
opacity-0 invisible pointer-events-none -translate-y-2
|
||||
group-hover:opacity-100 group-hover:visible group-hover:pointer-events-auto group-hover:translate-y-0
|
||||
{$reduceAnimations ? '' : 'transition-all duration-200 ease-out'}
|
||||
z-50"
|
||||
class="flex items-center justify-center h-[120px] w-[35px]
|
||||
bg-black/20 backdrop-blur-sm border border-white/10 rounded-xl"
|
||||
>
|
||||
<div class="h-2 w-full"></div>
|
||||
|
||||
<div
|
||||
class="flex items-center justify-center h-[120px] w-[35px]
|
||||
bg-black/20 backdrop-blur-sm border border-white/10 rounded-xl"
|
||||
>
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="1"
|
||||
step="0.01"
|
||||
bind:value={$custom_theme_volume}
|
||||
oninput={() => {
|
||||
config.value<number>('volume').set($custom_theme_volume);
|
||||
}}
|
||||
class="volume-slider"
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="1"
|
||||
step="0.01"
|
||||
bind:value={$custom_theme_volume}
|
||||
oninput={() => {
|
||||
config.value<number>('volume').set($custom_theme_volume);
|
||||
}}
|
||||
class="volume-slider"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="relative flex items-center justify-center p-1 group" id="titlebar-minimize">
|
||||
<div
|
||||
|
||||
+85
-35
@@ -15,7 +15,8 @@
|
||||
*/
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
import { writable } from 'svelte/store';
|
||||
import { get, writable } from 'svelte/store';
|
||||
import { custom_theme_volume } from './global';
|
||||
|
||||
type MediaCleanup = () => void;
|
||||
|
||||
@@ -66,7 +67,11 @@ const ensureStatusListener = async () => {
|
||||
} else if (stage === 'extract') {
|
||||
themeMediaStatus.set('Installing video engine…');
|
||||
} else if (stage === 'optimize') {
|
||||
themeMediaStatus.set('Converting theme video for hardware playback…');
|
||||
if (progress > 0) {
|
||||
themeMediaStatus.set(`Converting theme video… ${Math.round(progress * 100)}%`);
|
||||
} else {
|
||||
themeMediaStatus.set('Converting theme video…');
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -74,6 +79,14 @@ const ensureStatusListener = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
export const initThemeMediaStatusListener = () => {
|
||||
void ensureStatusListener();
|
||||
};
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
void ensureStatusListener();
|
||||
}
|
||||
|
||||
const blobUrlPromises = new Map<string, Promise<string>>();
|
||||
const optimizedUrlPromises = new Map<string, Promise<string>>();
|
||||
const objectUrls = new Set<string>();
|
||||
@@ -108,7 +121,7 @@ const optimizedThemeMediaUrl = async (source: string, video: boolean): Promise<s
|
||||
}
|
||||
|
||||
setPreparing(1);
|
||||
themeMediaStatus.set('Preparing theme video for smooth playback…');
|
||||
themeMediaStatus.set('Converting theme video…');
|
||||
await ensureStatusListener();
|
||||
try {
|
||||
const optimized = await invoke<string>('optimize_theme_media', {
|
||||
@@ -187,31 +200,57 @@ const armAutoplayRetry = (node: HTMLMediaElement) => {
|
||||
autoplayArmed.add(node);
|
||||
|
||||
const retry = () => {
|
||||
document.removeEventListener('pointerdown', retry, true);
|
||||
document.removeEventListener('keydown', retry, true);
|
||||
window.removeEventListener('pointerdown', retry, true);
|
||||
window.removeEventListener('keydown', retry, true);
|
||||
window.removeEventListener('click', retry, true);
|
||||
window.removeEventListener('focus', retry, true);
|
||||
autoplayArmed.delete(node);
|
||||
if (node.isConnected) void node.play().catch(() => {});
|
||||
if (node.isConnected) {
|
||||
node.muted = false;
|
||||
const targetVolume = get(custom_theme_volume);
|
||||
if (targetVolume >= 0) node.volume = targetVolume;
|
||||
void node.play().catch(() => {});
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('pointerdown', retry, true);
|
||||
document.addEventListener('keydown', retry, true);
|
||||
window.addEventListener('pointerdown', retry, true);
|
||||
window.addEventListener('keydown', retry, true);
|
||||
window.addEventListener('click', retry, true);
|
||||
window.addEventListener('focus', retry, true);
|
||||
};
|
||||
|
||||
export const playThemeMedia = (node: HTMLMediaElement) => {
|
||||
void node
|
||||
.play()
|
||||
.then(() => {
|
||||
console.debug('Theme media playing', {
|
||||
element: node.tagName,
|
||||
muted: node.muted,
|
||||
volume: node.volume,
|
||||
source: node.currentSrc,
|
||||
if (node instanceof HTMLVideoElement) {
|
||||
node.playsInline = true;
|
||||
node.setAttribute('playsinline', '');
|
||||
node.setAttribute('webkit-playsinline', '');
|
||||
node.controls = false;
|
||||
node.removeAttribute('controls');
|
||||
}
|
||||
|
||||
node.muted = false;
|
||||
const currentVolume = get(custom_theme_volume);
|
||||
if (currentVolume >= 0) {
|
||||
node.volume = currentVolume;
|
||||
}
|
||||
|
||||
const playPromise = node.play();
|
||||
if (playPromise !== undefined) {
|
||||
playPromise
|
||||
.then(() => {
|
||||
console.debug('Theme media playing', {
|
||||
element: node.tagName,
|
||||
muted: node.muted,
|
||||
volume: node.volume,
|
||||
source: node.currentSrc,
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn('Theme media autoplay was blocked', error);
|
||||
armAutoplayRetry(node);
|
||||
void invoke('unlock_media_autoplay').catch(() => {});
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn('Theme media autoplay was blocked', error);
|
||||
armAutoplayRetry(node);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -225,13 +264,7 @@ const loadMediaSource = (node: HTMLMediaElement, source: string) => {
|
||||
mediaCleanups.delete(node);
|
||||
|
||||
const previousTime = Number.isFinite(node.currentTime) ? node.currentTime : 0;
|
||||
const wasPlaying = !node.paused;
|
||||
const needsPreparation =
|
||||
node instanceof HTMLVideoElement && isMac && loopbackThemePattern.test(source);
|
||||
|
||||
// Keep the last frame visible while the first H.264 encode runs instead of
|
||||
// letting WebKit struggle through the software VP9 track.
|
||||
if (needsPreparation) node.pause();
|
||||
const wasPlaying = !node.paused || node.autoplay;
|
||||
|
||||
void themeMediaUrl(source, node instanceof HTMLVideoElement).then((url) => {
|
||||
if (mediaTokens.get(node) !== token || !node.isConnected) return;
|
||||
@@ -258,7 +291,7 @@ const loadMediaSource = (node: HTMLMediaElement, source: string) => {
|
||||
}
|
||||
}
|
||||
|
||||
if (wasPlaying || node.autoplay) playThemeMedia(node);
|
||||
playThemeMedia(node);
|
||||
};
|
||||
|
||||
const onError = () => {
|
||||
@@ -270,7 +303,7 @@ const loadMediaSource = (node: HTMLMediaElement, source: string) => {
|
||||
if (node.src !== source) {
|
||||
node.src = source;
|
||||
node.load();
|
||||
if (wasPlaying || node.autoplay) playThemeMedia(node);
|
||||
playThemeMedia(node);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -570,17 +603,34 @@ export function smoothThemeMedia(node: HTMLElement) {
|
||||
const videoLifecycles = new WeakMap<HTMLVideoElement, () => void>();
|
||||
|
||||
const prepare = (media: HTMLMediaElement) => {
|
||||
if (media instanceof HTMLVideoElement && !videoLifecycles.has(media)) {
|
||||
const lifecycle = themeVideoLifecycle(media);
|
||||
videoLifecycles.set(media, () => lifecycle.destroy());
|
||||
if (media instanceof HTMLVideoElement) {
|
||||
media.playsInline = true;
|
||||
media.setAttribute('playsinline', '');
|
||||
media.setAttribute('webkit-playsinline', '');
|
||||
media.controls = false;
|
||||
media.removeAttribute('controls');
|
||||
|
||||
if (!videoLifecycles.has(media)) {
|
||||
const lifecycle = themeVideoLifecycle(media);
|
||||
videoLifecycles.set(media, () => lifecycle.destroy());
|
||||
}
|
||||
} else {
|
||||
media.controls = false;
|
||||
media.removeAttribute('controls');
|
||||
}
|
||||
|
||||
const source =
|
||||
media.getAttribute('src') ??
|
||||
media.querySelector<HTMLSourceElement>('source[src]')?.getAttribute('src') ??
|
||||
undefined;
|
||||
if (!source) return;
|
||||
if (!isThemeAssetUrl(source) && !loopbackThemePattern.test(source)) return;
|
||||
if (!source) {
|
||||
playThemeMedia(media);
|
||||
return;
|
||||
}
|
||||
if (!isThemeAssetUrl(source) && !loopbackThemePattern.test(source)) {
|
||||
playThemeMedia(media);
|
||||
return;
|
||||
}
|
||||
if (lastSource.get(media) === source) return;
|
||||
|
||||
lastSource.set(media, source);
|
||||
|
||||
+39
-34
@@ -1662,7 +1662,7 @@ const drawWidgetElement = async (context: PreviewContext, element: ThemeV2Widget
|
||||
ctx.fillText(plays, cell2X + cellW - 8, bottomY + 14);
|
||||
ctx.restore();
|
||||
} else {
|
||||
// full
|
||||
// full or banner
|
||||
fillRoundedRect(
|
||||
ctx,
|
||||
element.x,
|
||||
@@ -1683,9 +1683,12 @@ const drawWidgetElement = async (context: PreviewContext, element: ThemeV2Widget
|
||||
1
|
||||
);
|
||||
|
||||
const avatarSize = 48;
|
||||
const showStats =
|
||||
element.variant !== 'banner' && element.showStats !== false && element.height >= 140;
|
||||
const isBanner = element.variant === 'banner' || !showStats;
|
||||
const avatarSize = isBanner ? Math.min(48, Math.max(32, element.height - 24)) : 48;
|
||||
const avatarX = element.x + 16;
|
||||
const avatarY = element.y + 16;
|
||||
const avatarY = isBanner ? element.y + (element.height - avatarSize) / 2 : element.y + 16;
|
||||
fillRoundedRect(ctx, avatarX, avatarY, avatarSize, avatarSize, 12, 'rgba(20, 20, 28, 0.9)');
|
||||
strokeRoundedRect(
|
||||
ctx,
|
||||
@@ -1730,42 +1733,44 @@ const drawWidgetElement = async (context: PreviewContext, element: ThemeV2Widget
|
||||
ctx.font = '500 10px monospace';
|
||||
ctx.fillText(`${levelProgress}%`, barX + barW + 8, barY - 2);
|
||||
|
||||
const divY = avatarY + avatarSize + 16;
|
||||
ctx.strokeStyle = 'rgba(255, 255, 255, 0.06)';
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(element.x + 16, divY);
|
||||
ctx.lineTo(element.x + element.width - 16, divY);
|
||||
ctx.stroke();
|
||||
if (showStats) {
|
||||
const divY = avatarY + avatarSize + 16;
|
||||
ctx.strokeStyle = 'rgba(255, 255, 255, 0.06)';
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(element.x + 16, divY);
|
||||
ctx.lineTo(element.x + element.width - 16, divY);
|
||||
ctx.stroke();
|
||||
|
||||
const gridY = divY + 12;
|
||||
const gap = 8;
|
||||
const cellW = (element.width - 32 - gap) / 2;
|
||||
const cellH = Math.max(34, (element.height - (gridY - element.y) - 14 - gap) / 2);
|
||||
const gridY = divY + 12;
|
||||
const gap = 8;
|
||||
const cellW = (element.width - 32 - gap) / 2;
|
||||
const cellH = Math.max(34, (element.height - (gridY - element.y) - 14 - gap) / 2);
|
||||
|
||||
const stats = [
|
||||
{ label: 'Rank', value: rank, valueColor: '#ffffff' },
|
||||
{ label: 'Performance', value: pp, valueColor: accent },
|
||||
{ label: 'Accuracy', value: acc, valueColor: '#ffffff' },
|
||||
{ label: 'Plays', value: plays, valueColor: '#ffffff' },
|
||||
];
|
||||
const stats = [
|
||||
{ label: 'Rank', value: rank, valueColor: '#ffffff' },
|
||||
{ label: 'Performance', value: pp, valueColor: accent },
|
||||
{ label: 'Accuracy', value: acc, valueColor: '#ffffff' },
|
||||
{ label: 'Plays', value: plays, valueColor: '#ffffff' },
|
||||
];
|
||||
|
||||
stats.forEach((st, idx) => {
|
||||
const col = idx % 2;
|
||||
const row = Math.floor(idx / 2);
|
||||
const cx = element.x + 16 + col * (cellW + gap);
|
||||
const cy = gridY + row * (cellH + gap);
|
||||
stats.forEach((st, idx) => {
|
||||
const col = idx % 2;
|
||||
const row = Math.floor(idx / 2);
|
||||
const cx = element.x + 16 + col * (cellW + gap);
|
||||
const cy = gridY + row * (cellH + gap);
|
||||
|
||||
fillRoundedRect(ctx, cx, cy, cellW, cellH, 10, 'rgba(255, 255, 255, 0.05)');
|
||||
ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
|
||||
ctx.font = canvasFont(context, bodyFont, 9, 500);
|
||||
ctx.textAlign = 'left';
|
||||
ctx.textBaseline = 'top';
|
||||
ctx.fillText(st.label, cx + 10, cy + 6);
|
||||
fillRoundedRect(ctx, cx, cy, cellW, cellH, 10, 'rgba(255, 255, 255, 0.05)');
|
||||
ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
|
||||
ctx.font = canvasFont(context, bodyFont, 9, 500);
|
||||
ctx.textAlign = 'left';
|
||||
ctx.textBaseline = 'top';
|
||||
ctx.fillText(st.label, cx + 10, cy + 6);
|
||||
|
||||
ctx.fillStyle = st.valueColor;
|
||||
ctx.font = canvasFont(context, bodyFont, 12, 700);
|
||||
ctx.fillText(st.value, cx + 10, cy + cellH - 18);
|
||||
});
|
||||
ctx.fillStyle = st.valueColor;
|
||||
ctx.font = canvasFont(context, bodyFont, 12, 700);
|
||||
ctx.fillText(st.value, cx + 10, cy + cellH - 18);
|
||||
});
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
} else if (element.widget === 'recent-activity') {
|
||||
|
||||
+6
-1
@@ -534,7 +534,8 @@ export type ThemeV2WidgetVariant =
|
||||
| 'icon-only'
|
||||
| 'circle'
|
||||
| 'rounded'
|
||||
| 'square';
|
||||
| 'square'
|
||||
| 'banner';
|
||||
|
||||
export type ThemeV2WidgetElement = ThemeV2ElementBase & {
|
||||
type: 'widget';
|
||||
@@ -543,6 +544,7 @@ export type ThemeV2WidgetElement = ThemeV2ElementBase & {
|
||||
showCountry?: boolean;
|
||||
showLevel?: boolean;
|
||||
showOnlineRing?: boolean;
|
||||
showStats?: boolean;
|
||||
};
|
||||
|
||||
export type ThemeV2Element =
|
||||
@@ -1262,6 +1264,7 @@ const normalizeElement = (raw: unknown, index: number): ThemeV2Element | undefin
|
||||
'circle',
|
||||
'rounded',
|
||||
'square',
|
||||
'banner',
|
||||
] as const,
|
||||
widget === 'launch-button' ? 'primary' : widget === 'avatar' ? 'circle' : 'full'
|
||||
);
|
||||
@@ -1269,6 +1272,7 @@ const normalizeElement = (raw: unknown, index: number): ThemeV2Element | undefin
|
||||
const showLevel = typeof source.showLevel === 'boolean' ? source.showLevel : false;
|
||||
const showOnlineRing =
|
||||
typeof source.showOnlineRing === 'boolean' ? source.showOnlineRing : true;
|
||||
const showStats = typeof source.showStats === 'boolean' ? source.showStats : true;
|
||||
return {
|
||||
...base,
|
||||
type,
|
||||
@@ -1277,6 +1281,7 @@ const normalizeElement = (raw: unknown, index: number): ThemeV2Element | undefin
|
||||
showCountry,
|
||||
showLevel,
|
||||
showOnlineRing,
|
||||
showStats,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+46
-101
@@ -1,5 +1,5 @@
|
||||
import { active_custom_theme, custom_theme_audio_playing, custom_themes } from './global';
|
||||
import { clearThemeMediaCache } from './themeMedia';
|
||||
import { clearThemeMediaCache, playThemeMedia } from './themeMedia';
|
||||
import { isThemeV2, normalizeThemeV2, type ThemeV2Asset, type ThemeV2Definition } from './themeV2';
|
||||
import { disableMediaControls, setGlobalVolume } from './utils';
|
||||
import { betterFetch } from '@better-fetch/fetch';
|
||||
@@ -7,7 +7,6 @@ import { convertFileSrc, invoke } from '@tauri-apps/api/core';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
import * as path from '@tauri-apps/api/path';
|
||||
import * as fs from '@tauri-apps/plugin-fs';
|
||||
import { SemVer } from 'semver';
|
||||
|
||||
export type Theme = {
|
||||
folder_name: string;
|
||||
@@ -102,51 +101,12 @@ const patchTheme = (name: string, patch: (theme: Theme) => Theme) => {
|
||||
);
|
||||
};
|
||||
|
||||
export const getDownloadableThemes = async () => {
|
||||
const themes: Theme[] = [];
|
||||
|
||||
const downloadableThemes = await betterFetch<
|
||||
{
|
||||
name: string;
|
||||
version: string;
|
||||
author: string;
|
||||
apiVersion?: string;
|
||||
description?: string;
|
||||
nsfw?: boolean;
|
||||
}[]
|
||||
>(`${THEME_REPOSITORY}/raw/branch/main/themes.json`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
'User-Agent':
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
|
||||
},
|
||||
});
|
||||
if (downloadableThemes.data) {
|
||||
for (const theme of downloadableThemes.data) {
|
||||
themes.push({
|
||||
folder_name: `${toSafeName(theme.name)}-${generateRandomString(16)}`,
|
||||
name: theme.name,
|
||||
version: theme.version,
|
||||
apiVersion: theme.apiVersion ?? '1.0',
|
||||
author: theme.author,
|
||||
description: theme.description ?? '',
|
||||
nsfw: theme.nsfw === true,
|
||||
scriptUrl: '',
|
||||
assets: '',
|
||||
preview: `${THEME_REPOSITORY}/raw/branch/main/previews/${toSafeName(theme.name)}.png`,
|
||||
status: 'not-installed',
|
||||
progress: 0,
|
||||
updateAvailable: false,
|
||||
cssStyle: '',
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.error('Failed to fetch downloadable themes');
|
||||
console.error(downloadableThemes.error);
|
||||
}
|
||||
return themes;
|
||||
/**
|
||||
* Legacy API v1 remote repository loading has been moved to the Community Themes Workshop.
|
||||
* @deprecated Browse and download themes through the Community Themes Workshop instead.
|
||||
*/
|
||||
export const getDownloadableThemes = async (): Promise<Theme[]> => {
|
||||
return [];
|
||||
};
|
||||
|
||||
const themeFromFolder = async (
|
||||
@@ -233,7 +193,7 @@ export const getThemes = async (): Promise<Theme[]> => {
|
||||
author: 'EZPPFarm',
|
||||
name: 'Default',
|
||||
version: '1.0.0',
|
||||
apiVersion: '1.0',
|
||||
apiVersion: '',
|
||||
description: 'The default EZPPLauncher look.',
|
||||
nsfw: false,
|
||||
scriptUrl: '',
|
||||
@@ -434,6 +394,7 @@ export const loadTheme = async (theme: Theme, themeContainer: HTMLElement, volum
|
||||
if (theme.definition) {
|
||||
setGlobalVolume(volume);
|
||||
disableMediaControls();
|
||||
void invoke('unlock_media_autoplay').catch(() => {});
|
||||
return;
|
||||
}
|
||||
if (theme.scriptUrl.length > 0) {
|
||||
@@ -442,6 +403,15 @@ export const loadTheme = async (theme: Theme, themeContainer: HTMLElement, volum
|
||||
}
|
||||
setGlobalVolume(volume);
|
||||
disableMediaControls();
|
||||
|
||||
// Ensure all media elements mounted by v1 themes start playback automatically
|
||||
themeContainer.querySelectorAll<HTMLMediaElement>('video, audio').forEach((media) => {
|
||||
media.muted = false;
|
||||
media.volume = volume;
|
||||
playThemeMedia(media);
|
||||
});
|
||||
|
||||
void invoke('unlock_media_autoplay').catch(() => {});
|
||||
};
|
||||
|
||||
export const deleteTheme = async (themeToUninstall: Theme) => {
|
||||
@@ -524,78 +494,53 @@ export const importThemeFromFile = async (themeName: string, filePath: string) =
|
||||
};
|
||||
|
||||
export const reloadThemes = async () => {
|
||||
const [downloadableThemes, installedThemes] = await Promise.all([
|
||||
getDownloadableThemes(),
|
||||
getThemes(),
|
||||
]);
|
||||
|
||||
const installedThemes = await getThemes();
|
||||
const installedMap = new Map(installedThemes.map((t) => [t.name, t]));
|
||||
const combinedMap = new Map(installedThemes.map((t) => [t.name, { ...t }]));
|
||||
|
||||
for (const downloadable of downloadableThemes) {
|
||||
const installed = installedMap.get(downloadable.name);
|
||||
|
||||
if (installed) {
|
||||
try {
|
||||
if (new SemVer(downloadable.version).compare(new SemVer(installed.version)) > 0) {
|
||||
const installedTheme = combinedMap.get(downloadable.name)!;
|
||||
installedTheme.updateAvailable = true;
|
||||
installedTheme.availableVersion = downloadable.version;
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed versions instead of breaking the whole theme list.
|
||||
}
|
||||
} else {
|
||||
combinedMap.set(downloadable.name, downloadable);
|
||||
}
|
||||
}
|
||||
|
||||
const combinedThemes = [...combinedMap.values()];
|
||||
|
||||
custom_themes.update((storeThemes) => {
|
||||
const storeMap = new Map(storeThemes.map((t) => [t.name, t]));
|
||||
const ACTIVE_STATUSES = new Set(['downloading', 'extracting', 'deleting']);
|
||||
|
||||
const updatedThemes = storeThemes.map((storeTheme) => {
|
||||
if (ACTIVE_STATUSES.has(storeTheme.status)) return storeTheme;
|
||||
const theme = combinedMap.get(storeTheme.name);
|
||||
if (!theme) return storeTheme;
|
||||
const updatedThemes = storeThemes
|
||||
.filter((storeTheme) => installedMap.has(storeTheme.name) || ACTIVE_STATUSES.has(storeTheme.status))
|
||||
.map((storeTheme) => {
|
||||
if (ACTIVE_STATUSES.has(storeTheme.status)) return storeTheme;
|
||||
const theme = installedMap.get(storeTheme.name);
|
||||
if (!theme) return storeTheme;
|
||||
|
||||
// Replace the object rather than mutating it so the theme cards see the
|
||||
// new values when the list is rendered from a filtered derived array.
|
||||
return {
|
||||
...storeTheme,
|
||||
scriptUrl: theme.scriptUrl,
|
||||
assets: theme.assets,
|
||||
preview: theme.preview,
|
||||
version: theme.version,
|
||||
author: theme.author,
|
||||
apiVersion: theme.apiVersion,
|
||||
description: theme.description,
|
||||
nsfw: theme.nsfw,
|
||||
definition: theme.definition,
|
||||
updateAvailable: theme.updateAvailable,
|
||||
availableVersion: theme.availableVersion,
|
||||
cssStyle: theme.cssStyle,
|
||||
backups: theme.backups ?? storeTheme.backups,
|
||||
};
|
||||
});
|
||||
// Replace the object rather than mutating it so the theme cards see the
|
||||
// new values when the list is rendered from a filtered derived array.
|
||||
return {
|
||||
...storeTheme,
|
||||
scriptUrl: theme.scriptUrl,
|
||||
assets: theme.assets,
|
||||
preview: theme.preview,
|
||||
version: theme.version,
|
||||
author: theme.author,
|
||||
apiVersion: theme.apiVersion,
|
||||
description: theme.description,
|
||||
nsfw: theme.nsfw,
|
||||
definition: theme.definition,
|
||||
updateAvailable: theme.updateAvailable,
|
||||
availableVersion: theme.availableVersion,
|
||||
cssStyle: theme.cssStyle,
|
||||
backups: theme.backups ?? storeTheme.backups,
|
||||
};
|
||||
});
|
||||
|
||||
const newThemes = combinedThemes.filter((t) => !storeMap.has(t.name));
|
||||
const newThemes = installedThemes.filter((t) => !storeMap.has(t.name));
|
||||
const merged = [...updatedThemes, ...newThemes];
|
||||
|
||||
return merged.sort((a, b) => {
|
||||
if (a.name === 'Default') return -1;
|
||||
if (b.name === 'Default') return 1;
|
||||
if (a.status === 'installed' && b.status !== 'installed') return -1;
|
||||
if (a.status !== 'installed' && b.status === 'installed') return 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
});
|
||||
|
||||
active_custom_theme.update((active) => {
|
||||
if (!active) return active;
|
||||
const updated = combinedMap.get(active.name);
|
||||
const updated = installedMap.get(active.name);
|
||||
return updated ? { ...active, ...updated } : active;
|
||||
});
|
||||
};
|
||||
|
||||
+3
-1
@@ -267,12 +267,13 @@ export function trackMediaContainer(node: HTMLElement) {
|
||||
|
||||
function update() {
|
||||
custom_theme_audio_playing.set(
|
||||
Array.from(media).some((el) => !el.paused && !(el instanceof HTMLVideoElement && el.muted))
|
||||
Array.from(media).some((el) => !el.paused)
|
||||
);
|
||||
}
|
||||
|
||||
function register(el: HTMLMediaElement) {
|
||||
media.add(el);
|
||||
update();
|
||||
|
||||
const handler = () => update();
|
||||
el.addEventListener('play', handler);
|
||||
@@ -280,6 +281,7 @@ export function trackMediaContainer(node: HTMLElement) {
|
||||
|
||||
return () => {
|
||||
media.delete(el);
|
||||
update();
|
||||
el.removeEventListener('play', handler);
|
||||
el.removeEventListener('pause', handler);
|
||||
};
|
||||
|
||||
+30
-26
@@ -38,6 +38,7 @@
|
||||
import { exit, getLauncherVersion, getPlatform, setLoggingEnabled } from '$lib/osuUtil';
|
||||
import * as presence from '$lib/presence';
|
||||
import {
|
||||
initThemeMediaStatusListener,
|
||||
smoothThemeMedia,
|
||||
themeMediaPreparing,
|
||||
themeMediaStatus,
|
||||
@@ -46,7 +47,7 @@
|
||||
} from '$lib/themeMedia';
|
||||
import { isThemeTrusted } from '$lib/themeTrust';
|
||||
import { themeV2Css } from '$lib/themeV2';
|
||||
import { getDownloadableThemes, getThemes, loadTheme } from '$lib/themes';
|
||||
import { getThemes, loadTheme } from '$lib/themes';
|
||||
import { currentUser } from '$lib/userAuthentication';
|
||||
import {
|
||||
cursorSmoothening,
|
||||
@@ -64,7 +65,6 @@
|
||||
import { WebviewWindow } from '@tauri-apps/api/webviewWindow';
|
||||
import { getCurrentWindow } from '@tauri-apps/api/window';
|
||||
import { Buffer } from 'buffer';
|
||||
import { SemVer } from 'semver';
|
||||
import { sileo } from 'sileo';
|
||||
import { onDestroy, onMount } from 'svelte';
|
||||
import { get } from 'svelte/store';
|
||||
@@ -148,6 +148,8 @@
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
initThemeMediaStatusListener();
|
||||
|
||||
try {
|
||||
const ver = await getLauncherVersion();
|
||||
if (ver) launcherVersion.set(ver);
|
||||
@@ -274,9 +276,12 @@
|
||||
const last_theme = localThemes.find((t) => t.name === lastThemeName);
|
||||
const canLoadLastTheme = Boolean(last_theme && isThemeTrusted(last_theme));
|
||||
|
||||
const initialVolume = await config_theme_volume.get(0.15);
|
||||
custom_theme_volume.set(initialVolume);
|
||||
|
||||
if (!last_theme || !canLoadLastTheme) {
|
||||
await config.value<string>('theme').set('Default');
|
||||
loadTheme(defaultTheme, $custom_theme_container!, await config_theme_volume.get(0.15));
|
||||
loadTheme(defaultTheme, $custom_theme_container!, initialVolume);
|
||||
if (last_theme && !canLoadLastTheme) {
|
||||
sileo.error({
|
||||
title: 'Theme needs approval',
|
||||
@@ -285,10 +290,10 @@
|
||||
});
|
||||
}
|
||||
} else {
|
||||
loadTheme(last_theme, $custom_theme_container!, await config_theme_volume.get(0.15));
|
||||
loadTheme(last_theme, $custom_theme_container!, initialVolume);
|
||||
}
|
||||
|
||||
custom_theme_volume.set(await config_theme_volume.get(0.15));
|
||||
void invoke('reveal_window').catch(() => {});
|
||||
patch.set(await config_patching.get(true));
|
||||
customCursor.set(await config_custom_cursor.get(true));
|
||||
cursorSmoothening.set(await config_cursor_smoothening.get(true));
|
||||
@@ -342,31 +347,13 @@
|
||||
|
||||
try {
|
||||
currentLoadingInfo.set('Loading themes...');
|
||||
const downloadableThemes = await getDownloadableThemes();
|
||||
const combinedThemes = [...localThemes];
|
||||
for (const theme of downloadableThemes) {
|
||||
if (!combinedThemes.find((t) => t.name === theme.name)) combinedThemes.push(theme);
|
||||
const installedTheme = localThemes.find((t) => t.name === theme.name);
|
||||
if (installedTheme) {
|
||||
const installedThemeVersion = new SemVer(installedTheme.version);
|
||||
const downloadableThemeVersion = new SemVer(theme.version);
|
||||
if (downloadableThemeVersion.compare(installedThemeVersion) > 0) {
|
||||
installedTheme.updateAvailable = true;
|
||||
const index = combinedThemes.findIndex((t) => t.name === theme.name);
|
||||
combinedThemes[index] = installedTheme;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
combinedThemes.sort((a, b) => {
|
||||
localThemes.sort((a, b) => {
|
||||
if (a.name === 'Default') return -1;
|
||||
if (b.name === 'Default') return 1;
|
||||
if (a.status === 'installed' && b.status !== 'installed') return -1;
|
||||
if (a.status !== 'installed' && b.status === 'installed') return 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
custom_themes.set(combinedThemes);
|
||||
custom_themes.set(localThemes);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
sileo.error({
|
||||
@@ -378,6 +365,23 @@
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<style>
|
||||
video::-webkit-media-controls,
|
||||
video::-webkit-media-controls-enclosure,
|
||||
video::-webkit-media-controls-panel,
|
||||
video::-webkit-media-controls-play-button,
|
||||
video::-webkit-media-controls-start-playback-button,
|
||||
video::-webkit-media-controls-overlay-play-button,
|
||||
video::-webkit-media-controls-overlay-enclosure {
|
||||
display: none !important;
|
||||
-webkit-appearance: none !important;
|
||||
opacity: 0 !important;
|
||||
visibility: hidden !important;
|
||||
pointer-events: none !important;
|
||||
width: 0 !important;
|
||||
height: 0 !important;
|
||||
}
|
||||
</style>
|
||||
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
|
||||
{@html `<style>${$active_custom_theme?.cssStyle || ''}</style>`}
|
||||
{#if $active_custom_theme?.definition}
|
||||
@@ -528,7 +532,7 @@
|
||||
<div
|
||||
class="pointer-events-none fixed bottom-4 left-1/2 z-50 -translate-x-1/2 rounded-full border border-white/10 bg-black/75 px-4 py-2 text-xs font-medium text-white/80 shadow-xl backdrop-blur animate-pulse"
|
||||
>
|
||||
{$themeMediaStatus || 'Preparing theme video for smooth playback…'}
|
||||
{$themeMediaStatus || 'Converting theme video…'}
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
+87
-74
@@ -19,6 +19,7 @@
|
||||
import Progress from '$lib/components/ui/progress/progress.svelte';
|
||||
import ScrollContainer from '$lib/components/ui/scroll-container/ScrollContainer.svelte';
|
||||
import * as Select from '$lib/components/ui/select';
|
||||
import CommunityWorkshopView from '$lib/components/theme/CommunityWorkshopView.svelte';
|
||||
import { config } from '$lib/config';
|
||||
import { currentUserInfo } from '$lib/data';
|
||||
import {
|
||||
@@ -156,6 +157,7 @@
|
||||
ChevronRight,
|
||||
Clock,
|
||||
ExternalLink,
|
||||
Globe,
|
||||
Medal,
|
||||
TrendingDown,
|
||||
TrendingUp,
|
||||
@@ -281,6 +283,7 @@
|
||||
>(undefined);
|
||||
let themeInstalling = $state(false);
|
||||
let themeSearch = $state('');
|
||||
let activeThemesTab = $state<'library' | 'workshop'>('library');
|
||||
let themeSavedUnlisten: (() => void) | undefined;
|
||||
let refreshingThemes = $state(false);
|
||||
let reloadingActiveTheme = $state(false);
|
||||
@@ -303,8 +306,6 @@
|
||||
|
||||
const themeFilterOptions = [
|
||||
{ id: 'all', label: 'All themes', icon: 'all-themes' },
|
||||
{ id: 'installed', label: 'Installed', icon: 'installed' },
|
||||
{ id: 'available', label: 'Available', icon: 'available' },
|
||||
{ id: 'updates', label: 'Updates', icon: 'updates' },
|
||||
] as const;
|
||||
type ThemeFilter = (typeof themeFilterOptions)[number]['id'];
|
||||
@@ -318,21 +319,8 @@
|
||||
: 'text-muted-foreground hover:bg-theme-900/60 hover:text-theme-100'
|
||||
}`;
|
||||
|
||||
/** A theme is local while installed, being removed, or updating in place. */
|
||||
const themeIsInstalled = (theme: Theme) =>
|
||||
theme.status === 'installed' ||
|
||||
theme.status === 'deleting' ||
|
||||
((theme.status === 'downloading' || theme.status === 'extracting') && theme.updateAvailable);
|
||||
|
||||
/** Keep a fresh download visible in the gallery while it progresses. */
|
||||
const themeIsAvailable = (theme: Theme) =>
|
||||
theme.status === 'not-installed' ||
|
||||
((theme.status === 'downloading' || theme.status === 'extracting') && !theme.updateAvailable);
|
||||
|
||||
const themeCounts = $derived({
|
||||
all: $custom_themes.length,
|
||||
installed: $custom_themes.filter(themeIsInstalled).length,
|
||||
available: $custom_themes.filter(themeIsAvailable).length,
|
||||
updates: $custom_themes.filter((theme) => theme.updateAvailable).length,
|
||||
});
|
||||
|
||||
@@ -340,12 +328,11 @@
|
||||
const query = themeSearch.trim().toLowerCase();
|
||||
|
||||
return $custom_themes.filter((theme) => {
|
||||
if (themeFilter === 'installed' && !themeIsInstalled(theme)) return false;
|
||||
if (themeFilter === 'available' && !themeIsAvailable(theme)) return false;
|
||||
if (themeFilter === 'updates' && !theme.updateAvailable) return false;
|
||||
if (!query) return true;
|
||||
|
||||
return `${theme.name} ${theme.author} ${theme.description} ${theme.apiVersion}`
|
||||
const apiPart = theme.name === 'Default' ? '' : theme.apiVersion;
|
||||
return `${theme.name} ${theme.author} ${theme.description} ${apiPart}`
|
||||
.toLowerCase()
|
||||
.includes(query);
|
||||
});
|
||||
@@ -3612,17 +3599,40 @@
|
||||
>
|
||||
<header class="shrink-0 border-b border-theme-800/50 px-5 pt-4 pb-3">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-baseline gap-2">
|
||||
<h1 class="text-lg font-semibold tracking-tight">Themes</h1>
|
||||
<span
|
||||
class="rounded-full bg-theme-900/70 px-1.5 py-0.5 text-[9px] tabular-nums text-muted-foreground/70"
|
||||
title="Themes in your library"
|
||||
>
|
||||
{$custom_themes.length}
|
||||
</span>
|
||||
<div class="flex min-w-0 items-center gap-4">
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-baseline gap-2">
|
||||
<h1 class="text-lg font-semibold tracking-tight">Themes</h1>
|
||||
</div>
|
||||
<p class="mt-0.5 text-[11px] text-muted-foreground">Make it feel like yours.</p>
|
||||
</div>
|
||||
|
||||
<!-- Tab Switcher: Installed vs Community Workshop -->
|
||||
<div class="flex items-center rounded-lg border border-theme-800/60 bg-theme-900/50 p-0.5">
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors {activeThemesTab === 'library'
|
||||
? 'bg-primary text-primary-foreground shadow-sm'
|
||||
: 'text-muted-foreground hover:text-white'}"
|
||||
onclick={() => (activeThemesTab = 'library')}
|
||||
>
|
||||
<ThemeIcon name="library" set={iconSet} class="size-3.5" />
|
||||
<span>Installed</span>
|
||||
<span class="rounded-full bg-black/30 px-1.5 py-0.2 text-[9px] tabular-nums">
|
||||
{$custom_themes.length}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors {activeThemesTab === 'workshop'
|
||||
? 'bg-primary text-primary-foreground shadow-sm'
|
||||
: 'text-muted-foreground hover:text-white'}"
|
||||
onclick={() => (activeThemesTab = 'workshop')}
|
||||
>
|
||||
<Globe class="size-3.5" />
|
||||
<span>Community Workshop</span>
|
||||
</button>
|
||||
</div>
|
||||
<p class="mt-0.5 text-[11px] text-muted-foreground">Make it feel like yours.</p>
|
||||
</div>
|
||||
<div class="flex shrink-0 items-center gap-1.5">
|
||||
<Button
|
||||
@@ -3681,40 +3691,48 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 flex items-center justify-between gap-3">
|
||||
<nav class="flex min-w-0 items-center gap-0.5" aria-label="Theme filters">
|
||||
{#each themeFilterOptions as option (option.id)}
|
||||
<button
|
||||
type="button"
|
||||
class={themeFilterClass(option.id)}
|
||||
aria-current={themeFilter === option.id ? 'page' : undefined}
|
||||
onclick={() => (themeFilter = option.id)}
|
||||
>
|
||||
<ThemeIcon name={option.icon} set={iconSet} class="size-3.5 shrink-0" />
|
||||
<span>{option.label}</span>
|
||||
<span class="text-[8px] tabular-nums text-muted-foreground/60">
|
||||
{themeCounts[option.id]}
|
||||
</span>
|
||||
</button>
|
||||
{/each}
|
||||
</nav>
|
||||
<div class="relative w-44 shrink-0">
|
||||
<ThemeIcon
|
||||
name="search"
|
||||
set={iconSet}
|
||||
class="pointer-events-none absolute top-1/2 left-2 size-3 -translate-y-1/2 text-muted-foreground"
|
||||
/>
|
||||
<Input
|
||||
class="h-8 border-theme-800 bg-theme-950/80 pl-7 text-[11px]"
|
||||
placeholder="Search themes..."
|
||||
bind:value={themeSearch}
|
||||
/>
|
||||
{#if activeThemesTab === 'library'}
|
||||
<div class="mt-3 flex items-center justify-between gap-3">
|
||||
<nav class="flex min-w-0 items-center gap-0.5" aria-label="Theme filters">
|
||||
{#each themeFilterOptions as option (option.id)}
|
||||
<button
|
||||
type="button"
|
||||
class={themeFilterClass(option.id)}
|
||||
aria-current={themeFilter === option.id ? 'page' : undefined}
|
||||
onclick={() => (themeFilter = option.id)}
|
||||
>
|
||||
<ThemeIcon name={option.icon} set={iconSet} class="size-3.5 shrink-0" />
|
||||
<span>{option.label}</span>
|
||||
<span class="text-[8px] tabular-nums text-muted-foreground/60">
|
||||
{themeCounts[option.id]}
|
||||
</span>
|
||||
</button>
|
||||
{/each}
|
||||
</nav>
|
||||
<div class="relative w-44 shrink-0">
|
||||
<ThemeIcon
|
||||
name="search"
|
||||
set={iconSet}
|
||||
class="pointer-events-none absolute top-1/2 left-2 size-3 -translate-y-1/2 text-muted-foreground"
|
||||
/>
|
||||
<Input
|
||||
class="h-8 border-theme-800 bg-theme-950/80 pl-7 text-[11px]"
|
||||
placeholder="Search themes..."
|
||||
bind:value={themeSearch}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</header>
|
||||
|
||||
<div class="min-h-0 flex-1 px-5 pt-4 pb-1">
|
||||
<ScrollContainer class="pr-2">
|
||||
{#if activeThemesTab === 'workshop'}
|
||||
<CommunityWorkshopView
|
||||
onApplyTheme={applyInstalledTheme}
|
||||
onRequestTrust={(theme) => requestThemeTrust(theme, false)}
|
||||
/>
|
||||
{:else}
|
||||
<ScrollContainer class="pr-2">
|
||||
{#if filteredThemes.length > 0}
|
||||
{#key themeFilter}
|
||||
<div class="grid grid-cols-3 gap-3 pb-4 pr-1">
|
||||
@@ -3778,12 +3796,14 @@
|
||||
{#if isActive}
|
||||
<Badge class="absolute top-1.5 left-1.5 text-[9px]">In use</Badge>
|
||||
{/if}
|
||||
<Badge
|
||||
variant="secondary"
|
||||
class="absolute top-1.5 right-1.5 bg-black/50 px-1.5 py-0 text-[9px] backdrop-blur-sm"
|
||||
>
|
||||
API {theme.apiVersion.startsWith('2') ? '2.0' : '1.0'}
|
||||
</Badge>
|
||||
{#if theme.name !== 'Default' && theme.folder_name !== 'default' && theme.apiVersion}
|
||||
<Badge
|
||||
variant="secondary"
|
||||
class="absolute top-1.5 right-1.5 bg-black/50 px-1.5 py-0 text-[9px] backdrop-blur-sm"
|
||||
>
|
||||
API {theme.apiVersion.startsWith('2') ? '2.0' : '1.0'}
|
||||
</Badge>
|
||||
{/if}
|
||||
{#if theme.nsfw && !revealedNsfw.includes(theme.name)}
|
||||
<button
|
||||
type="button"
|
||||
@@ -3988,10 +4008,6 @@
|
||||
No themes match "{themeSearch}"
|
||||
{:else if themeFilter === 'updates'}
|
||||
Everything is up to date
|
||||
{:else if themeFilter === 'available'}
|
||||
No themes left to install
|
||||
{:else if themeFilter === 'installed'}
|
||||
No installed themes yet
|
||||
{:else}
|
||||
No themes found
|
||||
{/if}
|
||||
@@ -4001,12 +4017,8 @@
|
||||
Try a different name, author or API version.
|
||||
{:else if themeFilter === 'updates'}
|
||||
You are running the latest version of every installed theme.
|
||||
{:else if themeFilter === 'available'}
|
||||
Every gallery theme is already installed.
|
||||
{:else if themeFilter === 'installed'}
|
||||
Download a theme from the gallery to get started.
|
||||
{:else}
|
||||
Try refreshing the gallery, or create a new API 2.0 theme.
|
||||
Discover themes in the Community Workshop or create a new API 2.0 theme.
|
||||
{/if}
|
||||
</p>
|
||||
{#if themeSearch || themeFilter !== 'all'}
|
||||
@@ -4025,7 +4037,8 @@
|
||||
</div>
|
||||
{/if}
|
||||
</ScrollContainer>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user