Implement video thumbnail generation and Windows 11 UI

This commit is contained in:
Alvin-Zilverstand committed 2026-11-19 20:31:29 +01:00
1 parent a1af08aa00
commit 74dd0a9cf5
8 files changed
+228 -36

No files matched your search

+5 -5
View File
@@ -6,7 +6,7 @@
<link rel="stylesheet" href="/styles.css" /> <link rel="stylesheet" href="/styles.css" />
<title>Media Viewer</title> <title>Media Viewer</title>
</head> </head>
<body> <body id="body">
<div id="app"> <div id="app">
<header id="main-header"> <header id="main-header">
<h1 id="app-title">Media Viewer</h1> <h1 id="app-title">Media Viewer</h1>
@@ -14,7 +14,7 @@
<button id="open-dir-btn">Open Directory</button> <button id="open-dir-btn">Open Directory</button>
</div> </div>
</header> </header>
<main id="main-content"> <main>
<div id="file-list" class="file-list"> <div id="file-list" class="file-list">
<!-- Files will be listed here --> <!-- Files will be listed here -->
</div> </div>
@@ -22,12 +22,12 @@
<div class="viewer-controls"> <div class="viewer-controls">
<button id="close-viewer-btn">Close</button> <button id="close-viewer-btn">Close</button>
</div> </div>
<div class="viewer-content" id="viewer-content"> <div class="viewer-content" id="viewer-content"></div>
<!-- Image or Video will be here -->
</div>
</div> </div>
</main> </main>
</div> </div>
<video id="thumbnail-video" style="display: none;" playsinline></video>
<canvas id="thumbnail-canvas" style="display: none;"></canvas>
<script type="module" src="/src/main.ts"></script> <script type="module" src="/src/main.ts"></script>
</body> </body>
</html> </html>
+1
View File
@@ -4239,6 +4239,7 @@ name = "tauri-app"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"base64 0.23.1",
"image", "image",
"serde", "serde",
"serde_json", "serde_json",
@@ -26,6 +26,7 @@ anyhow = "1.0.104"
tokio = { version = "1.54.1", features = ["full"] } tokio = { version = "1.54.1", features = ["full"] }
image = "0.25.10" image = "0.25.10"
tauri-plugin-dialog = "2.8.4" tauri-plugin-dialog = "2.8.4"
base64 = "0.23.1"
# Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration # Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration
+10 -1
View File
@@ -1,12 +1,20 @@
mod media; mod media;
mod thumbnails;
use media::{list_files, FileInfo}; use media::{list_files, FileInfo};
use thumbnails::{ThumbnailCache, get_thumbnail};
use tauri::State;
#[tauri::command] #[tauri::command]
async fn list_files_command(dir_path: String) -> Result<Vec<FileInfo>, String> { async fn list_files_command(dir_path: String) -> Result<Vec<FileInfo>, String> {
list_files(&dir_path).map_err(|e| e.to_string()) list_files(&dir_path).map_err(|e| e.to_string())
} }
#[tauri::command]
async fn get_thumbnail_command(path: String, cache: State<'_, ThumbnailCache>) -> Result<String, String> {
get_thumbnail(&path, cache.inner()).await.map_err(|e| e.to_string())
}
#[tauri::command] #[tauri::command]
fn greet(name: &str) -> String { fn greet(name: &str) -> String {
format!("Hello, {}! You've been greeted from Rust!", name) format!("Hello, {}! You've been greeted from Rust!", name)
@@ -17,7 +25,8 @@ pub fn run() {
tauri::Builder::default() tauri::Builder::default()
.plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_dialog::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!()) .run(tauri::generate_context!())
.expect("error while running tauri application"); .expect("error while running tauri application");
} }
Binary file not shown.
@@ -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<HashMap<String, String>>,
}
impl ThumbnailCache {
pub fn get(&self, path: &str) -> Option<String> {
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<String> {
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<String> {
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))
}
+93 -9
View File
@@ -13,6 +13,71 @@ let fileListEl: HTMLElement | null;
let titleEl: HTMLElement | null; let titleEl: HTMLElement | null;
let viewerEl: HTMLElement | null; let viewerEl: HTMLElement | null;
let viewerContentEl: HTMLElement | null; let viewerContentEl: HTMLElement | null;
let videoThumbElement: HTMLVideoElement | null;
let canvasElement: HTMLCanvasElement | null;
async function generateVideoThumbnail(url: string): Promise<string> {
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 = `<img src="${thumbDataUrl}" />`;
} 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<string>("get_thumbnail_command", { path: file.path });
iconSpan.innerHTML = `<img src="${base64}" />`;
}
} else {
iconSpan.textContent = "📄";
}
} catch (e) {
iconSpan.textContent = "🖼️";
console.error("Thumbnail error:", e);
}
}
async function listFiles(path: string) { async function listFiles(path: string) {
const files = await invoke<FileInfo[]>("list_files_command", { const files = await invoke<FileInfo[]>("list_files_command", {
@@ -26,16 +91,31 @@ async function listFiles(path: string) {
fileListEl.innerHTML = ""; fileListEl.innerHTML = "";
titleEl!.textContent = `Files in: ${path}`; titleEl!.textContent = `Files in: ${path}`;
for (file of files) { for (const file of files) {
const fileDiv = document.createElement("div"); const fileDiv = document.createElement("div");
fileDiv.className = `file-item ${file.is_dir ? "is-dir" : ""}`; fileDiv.className = `file-item ${file.is_dir ? "is-dir" : ""}`;
fileDiv.innerHTML = `
<span class="icon">${file.is_dir ? "📁" : "📄"}</span> const iconSpan = document.createElement("span");
<span class="name">${file.name}</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 = () => { fileDiv.onclick = () => {
if (file.is_dir) { if (file.is_dir) {
// For now, just ignore directories if clicked in the list // We could open the folder if we wanted
} else { } else {
showViewer(file.path, file.extension); showViewer(file.path, file.extension);
} }
@@ -89,8 +169,12 @@ async function handleOpenDir() {
} }
} }
document.getElementById("close-viewer-btn")?.addEventListener("click", () => { // 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"; viewerEl!.style.display = "none";
});
}); });
document.getElementById("open-dir-btn")?.addEventListener("click", handleOpenDir);
+63 -21
View File
@@ -1,85 +1,118 @@
body { 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; background-color: #f3f3f3;
margin: 0; margin: 0;
color: #333; color: #333;
overflow: hidden;
} }
#app { #app {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
height: 100vh; height: 100vh;
width: 100vw;
} }
header { header {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
padding: 10px 20px; padding: 8px 24px;
background-color: #ffffff; background-color: rgba(255, 255, 255, 0.7);
border-bottom: 1px solid #ddd; backdrop-filter: blur(20px);
box-shadow: 0 2px 4px rgba(0,0,0,0.05); border-bottom: 1px solid rgba(0, 0, 0, 0.05);
z-index: 10;
} }
header h1 { header h1 {
font-size: 1.2rem; font-size: 1rem;
margin: 0; margin: 0;
font-weight: 600;
color: #000;
} }
.controls button { .controls button {
padding: 8px 16px; padding: 6px 16px;
border-radius: 4px; border-radius: 4px;
border: 1px solid #ccc; border: 1px solid rgba(0, 0, 0, 0.1);
background-color: #ffffff; background-color: #ffffff;
cursor: pointer; cursor: pointer;
font-size: 0.9rem; font-size: 0.85rem;
transition: background-color 0.2s; font-weight: 500;
transition: all 0.2s ease;
} }
.controls button:hover { .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; background-color: #e5e5e5;
transform: scale(0.98);
} }
main { main {
flex: 1; flex: 1;
overflow-y: auto; overflow-y: auto;
padding: 20px; padding: 24px;
background-color: #f3f3f3;
} }
.file-list { .file-list {
display: grid; display: grid;
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 20px; gap: 24px;
} }
.file-item { .file-item {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
padding: 10px; padding: 12px;
border-radius: 8px; border-radius: 8px;
cursor: pointer; cursor: pointer;
transition: background-color 0.2s, transform 0.1s; transition: all 0.2s ease;
text-align: center; text-align: center;
border: 1px solid transparent;
} }
.file-item:hover { .file-item:hover {
background-color: #e5e5e5; background-color: rgba(255, 255, 255, 0.6);
transform: scale(1.05); 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 { .file-item .icon {
font-size: 2.5rem; width: 80px;
margin-bottom: 5px; 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 { .file-item .name {
font-size: 0.85rem; font-size: 0.85rem;
font-weight: 400;
word-break: break-all; word-break: break-all;
display: -webkit-box; display: -webkit-box;
-webkit-line-clamp: 2; -webkit-line-clamp: 2;
-webkit-box-orient: vertical; -webkit-box-orient: vertical;
overflow: hidden; overflow: hidden;
color: #222;
} }
/* Viewer Styles */ /* Viewer Styles */
@@ -95,6 +128,7 @@ main {
justify-content: center; justify-content: center;
align-items: center; align-items: center;
z-index: 1000; z-index: 1000;
backdrop-filter: blur(10px);
} }
.viewer-controls { .viewer-controls {
@@ -105,13 +139,18 @@ main {
} }
.viewer-controls button { .viewer-controls button {
padding: 10px 20px; padding: 8px 20px;
background-color: #fff; background-color: #fff;
color: #000; color: #000;
border: none; border: none;
border-radius: 4px; border-radius: 4px;
cursor: pointer; 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 { .viewer-content {
@@ -121,10 +160,13 @@ main {
justify-content: center; justify-content: center;
align-items: center; align-items: center;
overflow: hidden; overflow: hidden;
padding: 40px;
} }
.media-element { .media-element {
max-width: 90%; max-width: 90%;
max-height: 90%; max-height: 90%;
object-fit: contain; object-fit: contain;
box-shadow: 0 10px 30px rgba(0,0,0,0.5);
transition: transform 0.3s ease;
} }