diff --git a/README.md b/README.md index 79be9ab..559f8aa 100644 --- a/README.md +++ b/README.md @@ -4,16 +4,16 @@ A Windows desktop app for building and maintaining Minecraft modpacks. It create projects and installs real mods from Modrinth, with every change reviewed before it is applied. Awake Launcher is not required. -> **What's new in 1.3.0:** see [docs/releases/v1.3.0.md](docs/releases/v1.3.0.md). +> **What's new in 1.3.1:** see [docs/releases/v1.3.1.md](docs/releases/v1.3.1.md). -**Version 1.3.0 · Windows x64 · English, ไทย, 简体中文, 繁體中文 · GPL-3.0-only** +**Version 1.3.1 · Windows x64 · English, ไทย, 简体中文, 繁體中文 · GPL-3.0-only** ## Install -1. Download `Awake-Modpack-Manager-v1.3.0-Windows-x64-Setup.exe` from the +1. Download `Awake-Modpack-Manager-v1.3.1-Windows-x64-Setup.exe` from the [latest release](https://github.com/awakenginexe/Awake-Modpack-Manager/releases/latest). 2. Optional: check it against `SHA256SUMS.txt` from the same release - (`Get-FileHash .\Awake-Modpack-Manager-v1.3.0-Windows-x64-Setup.exe`). + (`Get-FileHash .\Awake-Modpack-Manager-v1.3.1-Windows-x64-Setup.exe`). 3. Run the installer. It installs for your Windows user only (no administrator rights) into `%LOCALAPPDATA%\Awake Modpack Manager`. The installer is **not code-signed** yet, so Windows SmartScreen may warn that it is from an diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index cf84d69..8452f22 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -1,10 +1,10 @@ -# Development checkpoint: Manager 1.3.0 and Native Core 0.4.2 +# Development checkpoint: Manager 1.3.1 and Native Core 0.4.2 -Unreleased until the owner approves the pull request and tags `v1.3.0`. +Unreleased until the owner approves the pull request and tags `v1.3.1`. ## Where things are -- Manager: branch `release/1.3.0`. `npm ci`, then `npm test`, `npm run typecheck`, `cargo test --manifest-path src-tauri/Cargo.toml --lib`. +- Manager: branch `release/1.3.1`. `npm ci`, then `npm test`, `npm run typecheck`, `cargo test --manifest-path src-tauri/Cargo.toml --lib`. - Native Core: Awake Launcher branch `release/3.2.2`. `.github/workflows/native-core-package.yml` builds it with the recorded toolchain and commits a delivery under `native-core/redistribution//`. `scripts/helper-pin.json` pins that delivery. - Release: pushing a version tag runs `.github/workflows/awake-beta.yml`, which builds, verifies, assembles every asset and publishes the release. `SHA256SUMS.txt` is required by in-app updates. @@ -12,7 +12,7 @@ Unreleased until the owner approves the pull request and tags `v1.3.0`. - `src-tauri/src/providers.rs`: five modpack catalogs, pack downloads, batched project metadata and update lookups. The CurseForge key stays in the host and the helper's environment. - `src-tauri/src/updater.rs`: GitHub release check and checksum-verified installer run. -- `src-tauri/src/desktop.rs`: content folders of a project or managed Launcher instance (list a folder, edit a text file, add files, Recycle Bin), shell open. Mods are never touched here. +- `src-tauri/src/desktop.rs`: content folders of a project or managed Launcher instance (list a folder, edit a text file, view an image (1.3.1), add files, Recycle Bin), shell open. Mods are never touched here. - `src-tauri/src/content.rs` (1.3.0): resource pack and shader search, versions and direct, checksum-verified install into `resourcepacks` / `shaderpacks`. - `HelperClient.installPack`: one local operation over fetch, upload, create, prepare and apply. A failure removes the created project. - FTB versions become a generated `.mrpack` manifest; ATLauncher and Technic become a CurseForge-format archive of overrides. diff --git a/docs/releases/v1.3.1.md b/docs/releases/v1.3.1.md new file mode 100644 index 0000000..5474d7f --- /dev/null +++ b/docs/releases/v1.3.1.md @@ -0,0 +1,22 @@ +# Awake Modpack Manager 1.3.1 + +Works with **Awake Launcher 3.2.2**. No Launcher update is needed. + +## Added + +- **View images on the Files page.** Clicking a picture (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, `.bmp`, `.ico`) now opens it inside the Manager, the same way a text file opens in the editor, instead of answering "This is not a text file". The viewer shows the picture's size in pixels and on disk, fits large pictures to the window, enlarges small textures with sharp pixels, and draws transparent areas over a checkerboard. Pictures are listed with their own icon, and the right-click menu says "View" for them. + +## How it behaves + +- Pictures are only shown, never changed: there is nothing to save, so going back to the folder never asks. +- A file is shown only if its first bytes are those of a picture format the viewer knows, whatever its name ends in. Anything else is refused with a message. +- Pictures over 16 MB are left to other programs. A picture that is damaged says so instead of showing an empty frame. +- `.svg` files are text and still open in the editor. + +## Safety + +- The viewer reads through the same path checks as the editor: inside the six content folders only, and never through a link or junction. + +## Not verified on a real machine yet + +The demo data and the automated tests cover the viewer, and the host's reading and format check have their own tests. Still unverified: the viewer in the desktop app against a real instance. diff --git a/package-lock.json b/package-lock.json index 844036c..6f5800e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "awake-modpack-manager", - "version": "1.3.0", + "version": "1.3.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "awake-modpack-manager", - "version": "1.3.0", + "version": "1.3.1", "license": "GPL-3.0-only", "dependencies": { "@lucide/vue": "1.59.0", diff --git a/package.json b/package.json index 17f5ecc..a970c45 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "awake-modpack-manager", "private": true, - "version": "1.3.0", + "version": "1.3.1", "license": "GPL-3.0-only", "type": "module", "engines": { diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 29fe642..3f27215 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -224,7 +224,7 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "awake-modpack-manager" -version = "1.3.0" +version = "1.3.1" dependencies = [ "md-5", "serde", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 6ab9c26..5d89067 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "awake-modpack-manager" -version = "1.3.0" +version = "1.3.1" description = "Awake Modpack Manager desktop host" license = "GPL-3.0-only" repository = "https://github.com/awakenginexe/Awake-Modpack-Manager" diff --git a/src-tauri/src/desktop.rs b/src-tauri/src/desktop.rs index 052301a..ac0fec4 100644 --- a/src-tauri/src/desktop.rs +++ b/src-tauri/src/desktop.rs @@ -18,6 +18,8 @@ const AREAS: [&str; 6] = ["config", "defaultconfigs", "kubejs", "scripts", "reso const LIST_MAX: usize = 20_000; /// The largest text file the built-in editor opens or saves. const TEXT_MAX: u64 = 2 << 20; +/// The largest picture the built-in viewer shows. +const IMAGE_MAX: u64 = 16 << 20; pub fn is_uuid(id: &str) -> bool { id.len() == 36 && id.bytes().enumerate().all(|(i, b)| if [8, 13, 18, 23].contains(&i) { b == b'-' } else { b.is_ascii_hexdigit() }) @@ -163,6 +165,57 @@ pub async fn workspace_write_text(workspace: String, area: String, path: String, .unwrap_or_else(|e| err("internal", e.to_string())) } +#[derive(Serialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct ImageFile { + /// `data:image/...;base64,...`, the only form the page's content policy lets an `` load from disk. + data_url: String, + size_bytes: u64, +} + +/// The picture formats the web view draws, told by their first bytes and never by the file name. +pub fn image_mime(bytes: &[u8]) -> Option<&'static str> { + match bytes { + [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, ..] => Some("image/png"), + [0xff, 0xd8, 0xff, ..] => Some("image/jpeg"), + [b'G', b'I', b'F', b'8', b'7' | b'9', b'a', ..] => Some("image/gif"), + [b'R', b'I', b'F', b'F', _, _, _, _, b'W', b'E', b'B', b'P', ..] => Some("image/webp"), + [b'B', b'M', ..] => Some("image/bmp"), + [0, 0, 1, 0, ..] => Some("image/x-icon"), + _ => None, + } +} + +fn base64(bytes: &[u8]) -> String { + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let n = u32::from(chunk[0]) << 16 | u32::from(*chunk.get(1).unwrap_or(&0)) << 8 | u32::from(*chunk.get(2).unwrap_or(&0)); + for i in 0..4 { + out.push(if i <= chunk.len() { ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char } else { '=' }); + } + } + out +} + +/// A picture for the built-in viewer. Only read, never changed; anything that is not one is refused. +pub fn read_image(path: &Path) -> HostResult { + let meta = regular_file(path)?; + if meta.len() > IMAGE_MAX { + return err("too-large", "This image is too large to show here (16 MB at most). Open its folder to see it in another program."); + } + let bytes = fs::read(path).or_else(|e| err("io", e.to_string()))?; + let Some(mime) = image_mime(&bytes) else { return err("not-image", "This is not an image the Manager can show.") }; + Ok(ImageFile { data_url: format!("data:{mime};base64,{}", base64(&bytes)), size_bytes: bytes.len() as u64 }) +} + +#[tauri::command] +pub async fn workspace_read_image(workspace: String, area: String, path: String) -> HostResult { + tauri::async_runtime::spawn_blocking(move || read_image(&checked_path(&game_dir(&workspace)?, &area, &path)?)) + .await + .unwrap_or_else(|e| err("internal", e.to_string())) +} + #[derive(Serialize, Debug, Default, PartialEq)] pub struct AddedFiles { added: Vec, @@ -433,6 +486,33 @@ mod tests { fs::remove_dir_all(&game).unwrap(); } + #[test] + fn the_viewer_shows_pictures_and_refuses_everything_else() { + let game = scratch("image"); + let config = game.join("config"); + fs::create_dir_all(config.join("sub")).unwrap(); + let png = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 1, 2]; + fs::write(config.join("icon.png"), png).unwrap(); + let shown = read_image(&config.join("icon.png")).unwrap(); + assert_eq!(shown.data_url, "data:image/png;base64,iVBORw0KGgoBAg=="); + assert_eq!(shown.size_bytes, 10); + // The first bytes decide, not the name: a script renamed to .png is not handed to the page as a picture. + fs::write(config.join("fake.png"), "").unwrap(); + assert_eq!(read_image(&config.join("fake.png")).unwrap_err().code, "not-image"); + fs::write(config.join("empty.png"), "").unwrap(); + assert_eq!(read_image(&config.join("empty.png")).unwrap_err().code, "not-image"); + fs::write(config.join("big.png"), vec![0u8; IMAGE_MAX as usize + 1]).unwrap(); + assert_eq!(read_image(&config.join("big.png")).unwrap_err().code, "too-large"); + assert_eq!(read_image(&config.join("sub")).unwrap_err().code, "invalid"); + assert_eq!(read_image(&config.join("gone.png")).unwrap_err().code, "not-found"); + assert_eq!(image_mime(&[0xff, 0xd8, 0xff, 0xe0]), Some("image/jpeg")); + assert_eq!(image_mime(b"GIF89a.."), Some("image/gif")); + assert_eq!(image_mime(b"RIFF\x10\0\0\0WEBPVP8 "), Some("image/webp")); + assert_eq!(image_mime(b"RIFF\x10\0\0\0WAVEfmt "), None); + assert_eq!((base64(b""), base64(b"f"), base64(b"fo"), base64(b"foo"), base64(b"foob")), ("".into(), "Zg==".into(), "Zm8=".into(), "Zm9v".into(), "Zm9vYg==".into())); + fs::remove_dir_all(&game).unwrap(); + } + #[test] fn adding_files_never_overwrites() { let root = scratch("add"); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index de6fee3..a48f88d 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -108,6 +108,7 @@ pub fn run() { desktop::workspace_list, desktop::workspace_recycle, desktop::workspace_read_text, + desktop::workspace_read_image, desktop::workspace_write_text, desktop::workspace_add_files, content::content_search, diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index f7461ac..0a48499 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Awake Modpack Manager", - "version": "1.3.0", + "version": "1.3.1", "identifier": "io.github.awakenginexe.AwakeModpackManager", "build": { "frontendDist": "../dist", diff --git a/src/backend/ManagerBackend.ts b/src/backend/ManagerBackend.ts index b56ec42..a2544f4 100644 --- a/src/backend/ManagerBackend.ts +++ b/src/backend/ManagerBackend.ts @@ -2,7 +2,7 @@ import type { Accepted, ImportInspection, LoaderKind, WorkspaceSnapshot, ProjectVersion, ProviderId, VersionCatalog, ApplyRequest, ContentArea, ContentEntry, CreateInstanceRequest, Draft, ExportFormat, ExportReport, ExportRequest, Handshake, InstallPackRequest, PackSearchPage, PackSearchQuery, PackVersion, InstanceSummary, InstanceWarning, Installation, ModInventory, OperationStatus, RecoveryStatus, ResolvedPlan, SearchPage, SearchQuery, DependencyResolution, VersionRef, WorkspaceExportItem, ExportFileMatch, ExportRestriction, InstanceZipResult, - AddedContent, ContentKind, ContentSearchPage, ContentSearchQuery, ContentTextFile, ContentVersion, InstalledContent, ProviderInfo } from './contract'; + AddedContent, ContentImage, ContentKind, ContentSearchPage, ContentSearchQuery, ContentTextFile, ContentVersion, InstalledContent, ProviderInfo } from './contract'; import type { LauncherProfile } from './launcher/transport'; import type { ProjectDetail } from './host'; @@ -66,6 +66,8 @@ export interface ManagerBackend { /** What is directly inside a content folder (`folder` is relative to the area; its top when absent). */ listContent(instanceId: string, area: ContentArea, folder?: string): Promise; readContentText?(instanceId: string, area: ContentArea, path: string): Promise; + /** A picture for the built-in viewer. Rejects for anything that is not one. */ + readContentImage?(instanceId: string, area: ContentArea, path: string): Promise; /** Save over the file that was read. Rejects if it changed on disk since. Resolves to its new `modifiedMs`. */ writeContentText?(instanceId: string, area: ContentArea, path: string, text: string, expectedModifiedMs: number): Promise; /** Let the user pick files to copy into a content folder. Null when they cancel; nothing is overwritten. */ diff --git a/src/backend/composite.ts b/src/backend/composite.ts index 327d7b4..c992ada 100644 --- a/src/backend/composite.ts +++ b/src/backend/composite.ts @@ -152,6 +152,7 @@ export function createCompositeBackend(helper: ManagerBackend, launcher: Manager recycleContent: async (id, area, paths) => { await byInstance(id).backend.recycleContent?.(id, area, paths); }, openFolder: async (id, area, folder) => { await byInstance(id).backend.openFolder?.(id, area, folder); }, readContentText: (id, area, path) => { const b = byInstance(id).backend; return b.readContentText ? b.readContentText(id, area, path) : noHelper(); }, + readContentImage: (id, area, path) => { const b = byInstance(id).backend; return b.readContentImage ? b.readContentImage(id, area, path) : noHelper(); }, writeContentText: (id, area, path, text, expected) => { const b = byInstance(id).backend; return b.writeContentText ? b.writeContentText(id, area, path, text, expected) : noHelper(); }, addContentFiles: (id, area, folder) => { const b = byInstance(id).backend; return b.addContentFiles ? b.addContentFiles(id, area, folder) : noHelper(); }, // Resource packs and shaders are found by the Manager's own side, whichever list is on screen. diff --git a/src/backend/contract.ts b/src/backend/contract.ts index 769b366..71db2e4 100644 --- a/src/backend/contract.ts +++ b/src/backend/contract.ts @@ -496,6 +496,8 @@ export interface ContentEntry { /** A file opened in the editor. `modifiedMs` goes back with the save, so a newer file on disk is never overwritten. */ export interface ContentTextFile { text: string; modifiedMs: number } +/** A picture to show: `dataUrl` is `data:image/...;base64,...`, checked by the side that read the file. */ +export interface ContentImage { dataUrl: string; sizeBytes: number } export interface AddedContent { added: string[]; skipped: string[] } /* ---------- Resource packs & shaders (installed straight into their folder, never through a plan) ---------- */ diff --git a/src/backend/helper/HelperClient.ts b/src/backend/helper/HelperClient.ts index 632dc43..4876d91 100644 --- a/src/backend/helper/HelperClient.ts +++ b/src/backend/helper/HelperClient.ts @@ -1042,6 +1042,10 @@ export function createHelperClient(options: HelperClientOptions): ManagerBackend if (!options.host) return notYet('editing files'); return options.host.workspaceReadText(workspaceOf(instanceId).workspaceId, area, path); }, + async readContentImage(instanceId, area, path) { + if (!options.host) return notYet('viewing images'); + return options.host.workspaceReadImage(workspaceOf(instanceId).workspaceId, area, path); + }, async writeContentText(instanceId, area, path, text, expectedModifiedMs) { if (!options.host) return notYet('editing files'); return options.host.workspaceWriteText(workspaceOf(instanceId).workspaceId, area, path, text, expectedModifiedMs); diff --git a/src/backend/host.ts b/src/backend/host.ts index 7b1a6b0..b2a9cd4 100644 --- a/src/backend/host.ts +++ b/src/backend/host.ts @@ -1,4 +1,4 @@ -import { BackendError, type AddedContent, type ContentEntry, type ContentKind, type ContentSearchPage, type ContentSearchQuery, type ContentTextFile, type ContentVersion, type InstalledContent, type ExportFileMatch, type InstanceZipResult, type PackHit, type PackProviderId, type PackProviderInfo, type PackVersion, type ProviderId } from './contract'; +import { BackendError, type AddedContent, type ContentEntry, type ContentImage, type ContentKind, type ContentSearchPage, type ContentSearchQuery, type ContentTextFile, type ContentVersion, type InstalledContent, type ExportFileMatch, type InstanceZipResult, type PackHit, type PackProviderId, type PackProviderInfo, type PackVersion, type ProviderId } from './contract'; /** A pack the desktop host downloaded and verified, ready to upload to the helper. */ export interface FetchedPack { token: string; format: 'mrpack' | 'curseforge'; size: number; sha256: string; notes: string[] } @@ -26,6 +26,7 @@ export interface HostApi { workspaceRecycle(workspace: string, area: string, paths: string[]): Promise; workspaceOpen(workspace: string, area?: string, folder?: string): Promise; workspaceReadText(workspace: string, area: string, path: string): Promise; + workspaceReadImage(workspace: string, area: string, path: string): Promise; workspaceWriteText(workspace: string, area: string, path: string, text: string, expectedModifiedMs: number): Promise; workspaceAddFiles(workspace: string, area: string, folder: string): Promise; contentSearch(query: ContentSearchQuery): Promise; @@ -70,6 +71,7 @@ export function createHostApi(): HostApi { modUpdates: (items, minecraftVersion, loader) => hostInvoke('mod_updates', { items, minecraftVersion, loader }), workspaceList: (workspace, area, folder) => hostInvoke('workspace_list', { workspace, area, folder: folder || null }), workspaceReadText: (workspace, area, path) => hostInvoke('workspace_read_text', { workspace, area, path }), + workspaceReadImage: (workspace, area, path) => hostInvoke('workspace_read_image', { workspace, area, path }), workspaceWriteText: (workspace, area, path, text, expectedModifiedMs) => hostInvoke('workspace_write_text', { workspace, area, path, text, expectedModifiedMs }), workspaceAddFiles: (workspace, area, folder) => hostInvoke('workspace_add_files', { workspace, area, folder }), contentSearch: ({ provider, kind, text, minecraftVersion, offset, limit }) => hostInvoke('content_search', { provider, kind, text, minecraftVersion, offset, limit }), diff --git a/src/backend/mock/MockBackend.ts b/src/backend/mock/MockBackend.ts index b60191d..0d16343 100644 --- a/src/backend/mock/MockBackend.ts +++ b/src/backend/mock/MockBackend.ts @@ -1,4 +1,4 @@ -import type { AddedContent, ContentHit, ContentKind, ContentSearchPage, ContentSearchQuery, ContentTextFile, ContentVersion, ExportFileMatch, ExportRestriction, InstalledContent, InstanceZipResult, ProviderId, WorkspaceExportItem, WorkspaceSnapshot } from '../contract'; +import type { AddedContent, ContentHit, ContentImage, ContentKind, ContentSearchPage, ContentSearchQuery, ContentTextFile, ContentVersion, ExportFileMatch, ExportRestriction, InstalledContent, InstanceZipResult, ProviderId, WorkspaceExportItem, WorkspaceSnapshot } from '../contract'; import { ALL_CAPABILITIES, BackendError, TERMINAL_STATES, type Accepted, type ApplyRequest, type Capability, type ContentArea, type ContentEntry, type CreateInstanceRequest, @@ -12,7 +12,9 @@ import type { ConnectionState, ManagerBackend } from '../ManagerBackend'; import { buildCatalog, buildContentCatalog, buildInstances, buildInventory, buildPackCatalog, type CatalogProject } from './fixtures'; /** A demo file: text when it can be edited, otherwise only a size. */ -interface DemoFile { text?: string; size: number; modifiedMs: number } +interface DemoFile { text?: string; image?: string; size: number; modifiedMs: number } +/** A 16 x 16 item texture, so the demo has a picture to show. */ +const DEMO_TEXTURE = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAa0lEQVR42mNgwAHcQzP/Y2MzEKthyuIdYIzOxmogTBGIhrEfvfiAgtHlcRqCrhGXQQQ1w2yDYbyGoBsA4ls3fUPByIagGECMZoKG4DIAJobLALgXKDKAKl6gKBCpEo1US0gUJ2WyMxMl2RkAv0AgR3utPPUAAAAASUVORK5CYII='; const FOLDER_OF: Record = { resourcepack: 'resourcepacks', shader: 'shaderpacks' }; export interface MockOptions { @@ -486,6 +488,7 @@ export class MockBackend implements ManagerBackend { text('config/fml.toml', 'maxThreads = -1\r\nversionCheck = true\r\n'); text('kubejs/startup_scripts/items.js', "StartupEvents.registry('item', (event) => {\n event.create('demo_gear')\n})\n"); text('kubejs/server_scripts/recipes.js', "ServerEvents.recipes((event) => {\n event.remove({ output: 'minecraft:stick' })\n})\n"); + files.set('kubejs/assets/demo/textures/item/demo_gear.png', { image: DEMO_TEXTURE, size: 164, modifiedMs: at }); text('scripts/ores.zs', 'import crafttweaker.api.item.IItemStack;\n'); files.set('resourcepacks/Faithful 32x - Demo.zip', { size: 18_400_000, modifiedMs: at }); files.set('shaderpacks/ComplementaryReimagined_demo.zip', { size: 6_300_000, modifiedMs: at }); @@ -514,6 +517,14 @@ export class MockBackend implements ManagerBackend { return { text: file.text, modifiedMs: file.modifiedMs }; }); } + readContentImage(instanceId: string, area: ContentArea, path: string): Promise { + return this.call(() => { + const file = this.filesOf(instanceId).get(`${area}/${path}`); + if (!file) throw new BackendError('rejected', 'This file is not there any more.', 'not-found'); + if (!file.image) throw new BackendError('rejected', 'This is not an image the Manager can show.', 'not-image'); + return { dataUrl: file.image, sizeBytes: file.size }; + }); + } writeContentText(instanceId: string, area: ContentArea, path: string, text: string, expectedModifiedMs: number): Promise { return this.call(() => { const file = this.filesOf(instanceId).get(`${area}/${path}`); diff --git a/src/i18n/en.ts b/src/i18n/en.ts index c9a01de..29279dd 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -759,6 +759,9 @@ export const en = { filesNoMatch: "Nothing in this folder matches.", filesOpen: "Open", filesEdit: "Edit", + filesView: "View", + filesImage: "Image", + filesImageBroken: "This image could not be shown. It may be damaged.", filesSaved: "Saved {name}", filesUnsaved: "Unsaved changes", filesDiscardTitle: "Discard your changes to \"{name}\"?", diff --git a/src/i18n/th.ts b/src/i18n/th.ts index 51a4ff3..49703a4 100644 --- a/src/i18n/th.ts +++ b/src/i18n/th.ts @@ -761,6 +761,9 @@ export const th: Catalog = { filesNoMatch: "ไม่มีรายการที่ตรงกันในโฟลเดอร์นี้", filesOpen: "เปิด", filesEdit: "แก้ไข", + filesView: "ดู", + filesImage: "รูปภาพ", + filesImageBroken: "แสดงรูปภาพนี้ไม่ได้ ไฟล์อาจเสียหาย", filesSaved: "บันทึก {name} แล้ว", filesUnsaved: "ยังไม่ได้บันทึก", filesDiscardTitle: "ทิ้งการแก้ไขใน \"{name}\" ใช่ไหม", diff --git a/src/i18n/zh-CN.ts b/src/i18n/zh-CN.ts index 7127e05..acd1c99 100644 --- a/src/i18n/zh-CN.ts +++ b/src/i18n/zh-CN.ts @@ -761,6 +761,9 @@ export const zhCN: Catalog = { filesNoMatch: "此文件夹中没有匹配的项目。", filesOpen: "打开", filesEdit: "编辑", + filesView: "查看", + filesImage: "图片", + filesImageBroken: "无法显示此图片,文件可能已损坏。", filesSaved: "已保存 {name}", filesUnsaved: "有未保存的更改", filesDiscardTitle: "放弃对“{name}”的更改?", diff --git a/src/i18n/zh-TW.ts b/src/i18n/zh-TW.ts index 5fb4b6b..ae5e9e3 100644 --- a/src/i18n/zh-TW.ts +++ b/src/i18n/zh-TW.ts @@ -761,6 +761,9 @@ export const zhTW: Catalog = { filesNoMatch: "此資料夾中沒有符合的項目。", filesOpen: "開啟", filesEdit: "編輯", + filesView: "檢視", + filesImage: "圖片", + filesImageBroken: "無法顯示此圖片,檔案可能已損毀。", filesSaved: "已儲存 {name}", filesUnsaved: "有未儲存的變更", filesDiscardTitle: "要捨棄對「{name}」的變更嗎?", diff --git a/src/views/FilesView.vue b/src/views/FilesView.vue index bf2c4eb..ce9c6b0 100644 --- a/src/views/FilesView.vue +++ b/src/views/FilesView.vue @@ -70,11 +70,27 @@ const saving = ref(false); const saveError = ref(''); const opening = ref(''); const editor = ref(null); +/** The picture on screen instead of the editor. Pictures are only shown, never changed. */ +const viewing = ref<{ area: ContentArea; path: string; dataUrl: string; sizeBytes: number } | null>(null); +const pixels = ref<{ width: number; height: number } | null>(null); +const broken = ref(false); +// SVG is text: it opens in the editor like any other. +const isImage = (path: string) => /\.(png|jpe?g|gif|webp|bmp|ico)$/i.test(path); +/** Textures are tiny: show them enlarged, in whole steps so every pixel stays square. */ +const zoom = computed(() => { + const longest = pixels.value ? Math.max(pixels.value.width, pixels.value.height) : 0; + return longest > 0 && longest <= 256 ? Math.max(1, Math.min(8, Math.floor(384 / longest))) : 1; +}); +function imageLoaded(e: Event) { + const img = e.target as HTMLImageElement; + pixels.value = { width: img.naturalWidth, height: img.naturalHeight }; +} // A text box always hands back plain line breaks, so compare like with like. const dirty = computed(() => !!editing.value && draft.value !== editing.value.original.replace(/\r\n/g, '\n')); /** True when there is nothing unsaved, or the user agreed to lose it. */ async function leaveEditor(): Promise { + viewing.value = null; if (!editing.value) return true; if (dirty.value && !await confirmDialog({ title: t('filesDiscardTitle', { name: nameOf(editing.value.path) }), body: t('filesDiscardBody'), confirm: t('filesDiscard'), cancel: t('cancel'), danger: true })) return false; editing.value = null; @@ -85,16 +101,26 @@ async function leaveEditor(): Promise { onMounted(() => { leaveGuard.value = leaveEditor; }); onBeforeUnmount(() => { if (leaveGuard.value === leaveEditor) leaveGuard.value = null; }); async function openFile(e: ContentEntry) { - if (!id.value || !session.backend.readContentText || opening.value) return; + if (!id.value || opening.value) return; + const asImage = isImage(e.path) && !!session.backend.readContentImage; + if (!asImage && !session.backend.readContentText) return; opening.value = e.path; try { + if (asImage) { + const image = await session.backend.readContentImage!(id.value, area.value, e.path); + pixels.value = null; + broken.value = false; + viewing.value = { area: area.value, path: e.path, ...image }; + return; + } + if (!session.backend.readContentText) return; const file = await session.backend.readContentText(id.value, area.value, e.path); editing.value = { area: area.value, path: e.path, modifiedMs: file.modifiedMs, original: file.text }; draft.value = file.text.replace(/\r\n/g, '\n'); saveError.value = ''; void nextTick(() => editor.value?.focus()); } catch (err) { - toast(asError(err).message, asError(err).detail === 'not-text' || asError(err).detail === 'too-large' ? 'info' : 'error'); + toast(asError(err).message, ['not-text', 'not-image', 'too-large'].includes(asError(err).detail ?? '') ? 'info' : 'error'); } finally { opening.value = ''; } @@ -165,7 +191,7 @@ async function recycle(e: ContentEntry) { const openFolder = () => session.backend.openFolder?.(id.value!, area.value, folder.value).catch((e) => toast(asError(e).message, 'error')); function entryMenu(event: MouseEvent, e: ContentEntry) { openMenu(event, [ - e.kind === 'directory' ? { label: t('filesOpen'), icon: FolderOpen, action: () => go(e.path) } : { label: t('filesEdit'), icon: Pencil, disabled: !session.backend.readContentText, action: () => openFile(e) }, + e.kind === 'directory' ? { label: t('filesOpen'), icon: FolderOpen, action: () => go(e.path) } : isImage(e.path) && session.backend.readContentImage ? { label: t('filesView'), icon: Image, action: () => openFile(e) } : { label: t('filesEdit'), icon: Pencil, disabled: !session.backend.readContentText, action: () => openFile(e) }, { label: t('copyPath'), icon: Copy, action: () => copyText(`${area.value}/${e.path}`) }, separator, { label: t('recycleAction'), icon: Trash2, danger: true, disabled: !canWrite.value || !session.backend.recycleContent, action: () => recycle(e) }, @@ -213,6 +239,21 @@ function entryMenu(event: MouseEvent, e: ContentEntry) { > +
+
+ +

{{ viewing.path }}

+ {{ formatBytes(viewing.sizeBytes) }} +
+ +
+ +
+ +