From 74dd0a9cf58d9f1f3b55c318b64ff48869acb320 Mon Sep 17 00:00:00 2001 From: Alvin Date: Thu, 19 Nov 2026 20:31:29 +0100 Subject: [PATCH] Implement video thumbnail generation and Windows 11 UI --- rust_media_viewer_v2/index.html | 10 +- rust_media_viewer_v2/src-tauri/Cargo.lock | 1 + rust_media_viewer_v2/src-tauri/Cargo.toml | 1 + rust_media_viewer_v2/src-tauri/src/lib.rs | 11 +- rust_media_viewer_v2/src-tauri/src/media.rs | Bin 1902 -> 948 bytes .../src-tauri/src/thumbnails.rs | 55 +++++++++ rust_media_viewer_v2/src/main.ts | 104 ++++++++++++++++-- rust_media_viewer_v2/src/styles.css | 84 ++++++++++---- 8 files changed, 229 insertions(+), 37 deletions(-) create mode 100644 rust_media_viewer_v2/src-tauri/src/thumbnails.rs diff --git a/rust_media_viewer_v2/index.html b/rust_media_viewer_v2/index.html index 5f1a574..28d2565 100644 --- a/rust_media_viewer_v2/index.html +++ b/rust_media_viewer_v2/index.html @@ -6,7 +6,7 @@ Media Viewer - +

Media Viewer

@@ -14,7 +14,7 @@
-
+
@@ -22,12 +22,12 @@
-
- -
+
+ + diff --git a/rust_media_viewer_v2/src-tauri/Cargo.lock b/rust_media_viewer_v2/src-tauri/Cargo.lock index 3eaeea8..c7bba05 100644 --- a/rust_media_viewer_v2/src-tauri/Cargo.lock +++ b/rust_media_viewer_v2/src-tauri/Cargo.lock @@ -4239,6 +4239,7 @@ name = "tauri-app" version = "0.1.0" dependencies = [ "anyhow", + "base64 0.23.1", "image", "serde", "serde_json", diff --git a/rust_media_viewer_v2/src-tauri/Cargo.toml b/rust_media_viewer_v2/src-tauri/Cargo.toml index e1f99bc..2a058fd 100644 --- a/rust_media_viewer_v2/src-tauri/Cargo.toml +++ b/rust_media_viewer_v2/src-tauri/Cargo.toml @@ -26,6 +26,7 @@ anyhow = "1.0.104" tokio = { version = "1.54.1", features = ["full"] } image = "0.25.10" tauri-plugin-dialog = "2.8.4" +base64 = "0.23.1" # Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration diff --git a/rust_media_viewer_v2/src-tauri/src/lib.rs b/rust_media_viewer_v2/src-tauri/src/lib.rs index 23b9a34..d7239a6 100644 --- a/rust_media_viewer_v2/src-tauri/src/lib.rs +++ b/rust_media_viewer_v2/src-tauri/src/lib.rs @@ -1,12 +1,20 @@ mod media; +mod thumbnails; use media::{list_files, FileInfo}; +use thumbnails::{ThumbnailCache, get_thumbnail}; +use tauri::State; #[tauri::command] async fn list_files_command(dir_path: String) -> Result, String> { list_files(&dir_path).map_err(|e| e.to_string()) } +#[tauri::command] +async fn get_thumbnail_command(path: String, cache: State<'_, ThumbnailCache>) -> Result { + get_thumbnail(&path, cache.inner()).await.map_err(|e| e.to_string()) +} + #[tauri::command] fn greet(name: &str) -> String { format!("Hello, {}! You've been greeted from Rust!", name) @@ -17,7 +25,8 @@ pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_dialog::init()) - .invoke_handler(tauri::generate_handler![greet, list_files_command]) + .manage(ThumbnailCache::default()) + .invoke_handler(tauri::generate_handler![greet, list_files_command, get_thumbnail_command]) .run(tauri::generate_context!()) .expect("error while running tauri application"); } diff --git a/rust_media_viewer_v2/src-tauri/src/media.rs b/rust_media_viewer_v2/src-tauri/src/media.rs index ef61d81a8cc3a12bb32ac7076ea775dd1030ce5a..b23bc6ba21e90469a65dd789cbc2fadef5c142a8 100644 GIT binary patch literal 948 zcmb7C%WA_g5WM><779gz)E}U{Zh@Xs8tA1Iqr~e*)Rv4TH%*)TdsmX}I;2qQgN0Y) znc3NGErNBq5QUv4ZU0eAw-@4p-dz!!9EI3mqhzT*F;=BM?#)4nN3?C}rb%-1oD zgwS{xIQTSJ_L!=55CjNFL=i{#0icS&k;V=f@3?&kg=qk_YmT5a6jq1^W$ycAUX?FL zP!IP~5k8OSGFtF={s~sl$y_=~P69Nox&q_BpuOqLk70lh6~R)gB-I?6XY@;DYOrF4Io5x}n=$nJ;F@H&%?zWH{IcmYi{NKk;$)-U66h`H~LP3R|Hr`Tx zv2)434t&L^5$EK!-h2;g+J>Ix1%)y92~nAMS}R$Qame1`TToHJXZ6eEGka;aIZ?+l zN4#XOCe5R>x+gE#IMV$Jtjy&?NJ)jC4>U+$UI5*zbv$M@LmlJSptj2Cx zrR?fY{649Awf4VTQ-O0OdzR=}ueX6&wVbk|>xkH;(&Jleey8emZKUpOmF8}}l diff --git a/rust_media_viewer_v2/src-tauri/src/thumbnails.rs b/rust_media_viewer_v2/src-tauri/src/thumbnails.rs new file mode 100644 index 0000000..1d3277a --- /dev/null +++ b/rust_media_viewer_v2/src-tauri/src/thumbnails.rs @@ -0,0 +1,55 @@ +use std::collections::HashMap; +use std::sync::Mutex; +use image::GenericImageView; +use base64::{engine::general_purpose, Engine as _}; +use anyhow::{Result, anyhow}; + +#[derive(Default)] +pub struct ThumbnailCache { + pub cache: Mutex>, +} + +impl ThumbnailCache { + pub fn get(&self, path: &str) -> Option { + let cache = self.cache.lock().unwrap(); + cache.get(path).cloned() + } + + pub fn set(&self, path: String, thumbnail: String) { + let mut cache = self.cache.lock().unwrap(); + cache.insert(path, thumbnail); + } +} + +pub async fn get_thumbnail(path: &str, cache: &ThumbnailCache) -> Result { + let path_str = path.to_string(); + + // Check cache first + if let Some(cached) = cache.get(path_str.as_str()) { + return Ok(cached); + } + + // Generate thumbnail + let thumbnail_base64 = generate_thumbnail_base64(path).await?; + + // Store in cache + cache.set(path_str, thumbnail_base64.clone()); + + Ok(thumbnail_base64) +} + +async fn generate_thumbnail_base64(path: &str) -> Result { + let img = image::open(path).map_err(|e| anyhow!("Failed to open image: {}", e))?; + + // Resize to 128x128 + let thumbnail = img.thumbnail(128, 128); + + let mut buffer = std::io::Cursor::new(Vec::new()); + thumbnail.write_to(&mut buffer, image::ImageFormat::Png) + .map_err(|e| anyhow!("Failed to write thumbnail: {}", e))?; + + let bytes = buffer.into_inner(); + let base64_str = general_purpose::STANDARD.encode(bytes); + + Ok(format!("data:image/png;base64,{}", base64_str)) +} diff --git a/rust_media_viewer_v2/src/main.ts b/rust_media_viewer_v2/src/main.ts index 41d7a07..1c23c36 100644 --- a/rust_media_viewer_v2/src/main.ts +++ b/rust_media_viewer_v2/src/main.ts @@ -13,6 +13,71 @@ let fileListEl: HTMLElement | null; let titleEl: HTMLElement | null; let viewerEl: HTMLElement | null; let viewerContentEl: HTMLElement | null; +let videoThumbElement: HTMLVideoElement | null; +let canvasElement: HTMLCanvasElement | null; + +async function generateVideoThumbnail(url: string): Promise { + return new Promise((resolve, reject) => { + if (!videoThumbElement || !canvasElement) { + reject(new Error("Elements not initialized")); + return; + } + + videoThumbElement.src = url; + videoThumbElement.currentTime = 1; // Seek to 1s to avoid black frame + videoThumbElement.load(); + videoThumbElement.muted = true; + videoThumbElement.playsInline = true; + + videoThumbElement.onloadeddata = () => { + videoThumbElement.currentTime = 1; + }; + + videoThumbElement.onseeked = () => { + canvasElement.width = videoThumbElement.videoWidth > 128 ? 128 : videoThumbElement.videoWidth; + canvasElement.height = (videoThumbElement.videoHeight / videoThumbElement.videoWidth) * canvasElement.width; + const ctx = canvasElement.getContext("2d"); + if (ctx) { + ctx.drawImage(videoThumbElement, 0, 0, canvasElement.width, canvasElement.height); + resolve(canvasElement.toDataURL()); + } else { + reject(new Error("Could not get canvas context")); + } + }; + + videoThumbElement.onerror = (e) => reject(e); + }); +} + +async function loadThumbnail(file: FileInfo, iconSpan: HTMLElement) { + try { + const url = await convertFileUrl(file.path); + + if (file.extension) { + const ext = file.extension.toLowerCase(); + // Video formats for thumbnail generation + if (["mp4", "webm", "ogg", "mov"].includes(ext)) { + try { + const thumbDataUrl = await generateVideoThumbnail(url); + iconSpan.innerHTML = ``; + } catch (e) { + iconSpan.textContent = "🎬"; + } + } else { + // For images, we use the backend thumbnailer (faster/better for large images) + // Or just use the asset URL directly if it's small enough + // But to keep it consistent, let's use the backend for images. + const base64 = await invoke("get_thumbnail_command", { path: file.path }); + iconSpan.innerHTML = ``; + } + } else { + iconSpan.textContent = "📄"; + } + } catch (e) { + iconSpan.textContent = "🖼️"; + console.error("Thumbnail error:", e); + } +} async function listFiles(path: string) { const files = await invoke("list_files_command", { @@ -26,16 +91,31 @@ async function listFiles(path: string) { fileListEl.innerHTML = ""; titleEl!.textContent = `Files in: ${path}`; - for (file of files) { + for (const file of files) { const fileDiv = document.createElement("div"); fileDiv.className = `file-item ${file.is_dir ? "is-dir" : ""}`; - fileDiv.innerHTML = ` - ${file.is_dir ? "📁" : "📄"} - ${file.name} - `; + + const iconSpan = document.createElement("span"); + iconSpan.className = "icon"; + + if (file.is_dir) { + iconSpan.textContent = "📁"; + } else { + iconSpan.className = "icon thumbnail"; + iconSpan.textContent = "⏳"; // Loading indicator + loadThumbnail(file, iconSpan); + } + + const nameSpan = document.createElement("span"); + nameSpan.className = "name"; + nameSpan.textContent = file.name; + + fileDiv.appendChild(iconSpan); + fileDiv.appendChild(nameSpan); + fileDiv.onclick = () => { if (file.is_dir) { - // For now, just ignore directories if clicked in the list + // We could open the folder if we wanted } else { showViewer(file.path, file.extension); } @@ -89,8 +169,12 @@ async function handleOpenDir() { } } -document.getElementById("close-viewer-btn")?.addEventListener("click", () => { - viewerEl!.style.display = "none"; +// Initialize elements +window.addEventListener("DOMContentLoaded", () => { + videoThumbElement = document.getElementById("thumbnail-video") as HTMLVideoElement; + canvasElement = document.getElementById("thumbnail-canvas") as HTMLCanvasElement; + document.getElementById("open-dir-btn")?.addEventListener("click", handleOpenDir); + document.getElementById("close-viewer-btn")?.addEventListener("click", () => { + viewerEl!.style.display = "none"; + }); }); - -document.getElementById("open-dir-btn")?.addEventListener("click", handleOpenDir); diff --git a/rust_media_viewer_v2/src/styles.css b/rust_media_viewer_v2/src/styles.css index ba78e31..b583e26 100644 --- a/rust_media_viewer_v2/src/styles.css +++ b/rust_media_viewer_v2/src/styles.css @@ -1,85 +1,118 @@ body { - font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; + font-family: 'Segoe UI Variable', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f3f3f3; margin: 0; color: #333; + overflow: hidden; } #app { display: flex; flex-direction: column; height: 100vh; + width: 100vw; } header { display: flex; justify-content: space-between; align-items: center; - padding: 10px 20px; - background-color: #ffffff; - border-bottom: 1px solid #ddd; - box-shadow: 0 2px 4px rgba(0,0,0,0.05); + padding: 8px 24px; + background-color: rgba(255, 255, 255, 0.7); + backdrop-filter: blur(20px); + border-bottom: 1px solid rgba(0, 0, 0, 0.05); + z-index: 10; } header h1 { - font-size: 1.2rem; + font-size: 1rem; margin: 0; + font-weight: 600; + color: #000; } .controls button { - padding: 8px 16px; + padding: 6px 16px; border-radius: 4px; - border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, 0.1); background-color: #ffffff; cursor: pointer; - font-size: 0.9rem; - transition: background-color 0.2s; + font-size: 0.85rem; + font-weight: 500; + transition: all 0.2s ease; } .controls button:hover { + background-color: #f5f5f5; + border-color: rgba(0, 0, 0, 0.2); + box-shadow: 0 2px 4px rgba(0,0,0,0.05); +} + +.controls button:active { background-color: #e5e5e5; + transform: scale(0.98); } main { flex: 1; overflow-y: auto; - padding: 20px; + padding: 24px; + background-color: #f3f3f3; } .file-list { display: grid; - grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); - gap: 20px; + grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); + gap: 24px; } .file-item { display: flex; flex-direction: column; align-items: center; - padding: 10px; + padding: 12px; border-radius: 8px; cursor: pointer; - transition: background-color 0.2s, transform 0.1s; + transition: all 0.2s ease; text-align: center; + border: 1px solid transparent; } .file-item:hover { - background-color: #e5e5e5; - transform: scale(1.05); + background-color: rgba(255, 255, 255, 0.6); + border-color: rgba(0, 0, 0, 0.05); + transform: translateY(-4px); + box-shadow: 0 8px 16px rgba(0,0,0,0.08); } .file-item .icon { - font-size: 2.5rem; - margin-bottom: 5px; + width: 80px; + height: 80px; + margin-bottom: 12px; + display: flex; + justify-content: center; + align-items: center; + background-color: #ffffff; + border-radius: 8px; + box-shadow: inset 0 0 2px rgba(0,0,0,0.1); + overflow: hidden; +} + +.file-item .icon img { + width: 100%; + height: 100%; + object-fit: cover; } .file-item .name { font-size: 0.85rem; + font-weight: 400; word-break: break-all; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; + color: #222; } /* Viewer Styles */ @@ -95,6 +128,7 @@ main { justify-content: center; align-items: center; z-index: 1000; + backdrop-filter: blur(10px); } .viewer-controls { @@ -105,13 +139,18 @@ main { } .viewer-controls button { - padding: 10px 20px; + padding: 8px 20px; background-color: #fff; color: #000; border: none; border-radius: 4px; cursor: pointer; - font-weight: bold; + font-weight: 600; + box-shadow: 0 4px 12px rgba(0,0,0,0.5); +} + +.viewer-controls button:hover { + background-color: #f0f0f0; } .viewer-content { @@ -121,10 +160,13 @@ main { justify-content: center; align-items: center; overflow: hidden; + padding: 40px; } .media-element { max-width: 90%; max-height: 90%; object-fit: contain; + box-shadow: 0 10px 30px rgba(0,0,0,0.5); + transition: transform 0.3s ease; }