diff --git a/App_Resources/Android/src/main/AndroidManifest.xml b/App_Resources/Android/src/main/AndroidManifest.xml index 774f9ae2..6c3d39c8 100644 --- a/App_Resources/Android/src/main/AndroidManifest.xml +++ b/App_Resources/Android/src/main/AndroidManifest.xml @@ -10,7 +10,7 @@ - diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaController.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaController.java index d2d1ee4a..57d91429 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaController.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaController.java @@ -203,9 +203,9 @@ public class FaceclawMediaController { /** * Album art for the active session's current item, grayscale, scaled to - * fit within maxSize x maxSize preserving aspect. Returns - * [widthLo, widthHi, heightLo, heightHi, pixels...] or an empty array - * when no art is available. + * fit within maxSize x maxSize preserving aspect. Returns a gray packet + * (see ImageFileLoader.bitmapToGrayPacket) or an empty array when no art + * is available. */ public byte[] getAlbumArtGray(int maxSize) { Bitmap art; @@ -225,38 +225,7 @@ public class FaceclawMediaController { art = metadata.getBitmap(MediaMetadata.METADATA_KEY_DISPLAY_ICON); } } - if (art == null || art.getWidth() <= 0 || art.getHeight() <= 0 || maxSize <= 0) { - return new byte[0]; - } - try { - float scale = Math.min(1f, Math.min( - (float) maxSize / art.getWidth(), - (float) maxSize / art.getHeight())); - int width = Math.max(1, Math.round(art.getWidth() * scale)); - int height = Math.max(1, Math.round(art.getHeight() * scale)); - Bitmap scaled = Bitmap.createScaledBitmap(art, width, height, true); - if (scaled.getConfig() == Bitmap.Config.HARDWARE) { - scaled = scaled.copy(Bitmap.Config.ARGB_8888, false); - } - int[] pixels = new int[width * height]; - scaled.getPixels(pixels, 0, width, 0, 0, width, height); - byte[] out = new byte[4 + width * height]; - out[0] = (byte) (width & 0xff); - out[1] = (byte) ((width >> 8) & 0xff); - out[2] = (byte) (height & 0xff); - out[3] = (byte) ((height >> 8) & 0xff); - for (int i = 0; i < pixels.length; i++) { - int p = pixels[i]; - int r = (p >> 16) & 0xff; - int g = (p >> 8) & 0xff; - int b = p & 0xff; - out[4 + i] = (byte) ((r * 299 + g * 587 + b * 114) / 1000); - } - return out; - } catch (Exception e) { - Log.w("FaceclawMedia", "album art conversion failed", e); - return new byte[0]; - } + return ImageFileLoader.bitmapToGrayPacket(art, maxSize, maxSize); } /** diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/ImageFileLoader.java b/App_Resources/Android/src/main/java/com/faceclaw/app/ImageFileLoader.java new file mode 100644 index 00000000..17614712 --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/ImageFileLoader.java @@ -0,0 +1,94 @@ +package com.faceclaw.app; + +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.util.Log; + +/** + * Decodes image files (and bitmaps generally) to the grayscale packet format + * used across the TS bridge: [widthLo, widthHi, heightLo, heightHi, + * pixels...] with one byte per pixel, row-major, or an empty array on + * failure. FaceclawMediaController's album art shares bitmapToGrayPacket. + */ +public final class ImageFileLoader { + private static final String TAG = "ImageFileLoader"; + + private ImageFileLoader() {} + + /** + * Decode an image file and downscale it to fit within maxWidth x + * maxHeight, preserving aspect ratio and never upscaling. + */ + public static byte[] loadGray(String path, int maxWidth, int maxHeight) { + if (path == null || maxWidth <= 0 || maxHeight <= 0) { + return new byte[0]; + } + try { + BitmapFactory.Options bounds = new BitmapFactory.Options(); + bounds.inJustDecodeBounds = true; + BitmapFactory.decodeFile(path, bounds); + if (bounds.outWidth <= 0 || bounds.outHeight <= 0) { + return new byte[0]; + } + // Power-of-two subsampling during decode keeps large photos from + // allocating full-size ARGB buffers; exact fitting happens in + // bitmapToGrayPacket. + BitmapFactory.Options opts = new BitmapFactory.Options(); + opts.inSampleSize = 1; + while (bounds.outWidth / (opts.inSampleSize * 2) >= maxWidth + && bounds.outHeight / (opts.inSampleSize * 2) >= maxHeight) { + opts.inSampleSize *= 2; + } + Bitmap bitmap = BitmapFactory.decodeFile(path, opts); + if (bitmap == null) { + return new byte[0]; + } + return bitmapToGrayPacket(bitmap, maxWidth, maxHeight); + } catch (Exception | OutOfMemoryError e) { + Log.w(TAG, "image decode failed: " + path, e); + return new byte[0]; + } + } + + /** + * Scale a bitmap to fit within maxWidth x maxHeight (preserving aspect, + * never upscaling) and convert it to the grayscale packet format. + * Transparent pixels darken toward black (the on-glasses background). + */ + public static byte[] bitmapToGrayPacket(Bitmap source, int maxWidth, int maxHeight) { + if (source == null || source.getWidth() <= 0 || source.getHeight() <= 0 + || maxWidth <= 0 || maxHeight <= 0) { + return new byte[0]; + } + try { + float scale = Math.min(1f, Math.min( + (float) maxWidth / source.getWidth(), + (float) maxHeight / source.getHeight())); + int width = Math.max(1, Math.round(source.getWidth() * scale)); + int height = Math.max(1, Math.round(source.getHeight() * scale)); + Bitmap scaled = Bitmap.createScaledBitmap(source, width, height, true); + if (scaled.getConfig() == Bitmap.Config.HARDWARE) { + scaled = scaled.copy(Bitmap.Config.ARGB_8888, false); + } + int[] pixels = new int[width * height]; + scaled.getPixels(pixels, 0, width, 0, 0, width, height); + byte[] out = new byte[4 + width * height]; + out[0] = (byte) (width & 0xff); + out[1] = (byte) ((width >> 8) & 0xff); + out[2] = (byte) (height & 0xff); + out[3] = (byte) ((height >> 8) & 0xff); + for (int i = 0; i < pixels.length; i++) { + int p = pixels[i]; + int a = (p >>> 24) & 0xff; + int r = (p >> 16) & 0xff; + int g = (p >> 8) & 0xff; + int b = p & 0xff; + out[4 + i] = (byte) (((r * 299 + g * 587 + b * 114) / 1000) * a / 255); + } + return out; + } catch (Exception | OutOfMemoryError e) { + Log.w(TAG, "bitmap conversion failed", e); + return new byte[0]; + } + } +} diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts index b86ee575..0639c1ed 100644 --- a/app/g2/dashboard-controller.ts +++ b/app/g2/dashboard-controller.ts @@ -55,11 +55,12 @@ import { DEBUG_TESTS_WINDOW_ID, } from "../ui/shell/debug-tests-app"; import { - createTelepromptBrowserWindow, - createTelepromptDocumentWindow, - TELEPROMPT_SURFACE_ID, - TELEPROMPT_WINDOW_ID, -} from "../ui/shell/teleprompt-app"; + createFilesAppWindow, + createImageDocumentWindow, + createTextDocumentWindow, + FILES_SURFACE_ID, + FILES_WINDOW_ID, +} from "../ui/shell/files-app"; import { createNightscoutAppWindow, NIGHTSCOUT_SURFACE_ID, @@ -264,7 +265,7 @@ class DashboardController { apps: [ { appId: "timer", label: "Timer", icon: "timer" }, { appId: "terminal", label: "Terminal", icon: "terminal" }, - { appId: "teleprompt", label: "Teleprompt", icon: "file-text" }, + { appId: "files", label: "Files", icon: "folder" }, { appId: "music", label: "Music", icon: "music" }, { appId: "nightscout", label: "Nightscout", icon: "nightscout" }, { appId: "transcribe", label: "Transcribe", icon: "mic" }, @@ -922,21 +923,31 @@ class DashboardController { } /** A document arrived via Android's Share intent: open it as a new window. */ - async openTelepromptDocument(text: string): Promise { - this.appendLog(`teleprompt document received (${text.length} chars)`); + async openSharedTextDocument(text: string): Promise { + this.appendLog(`shared text document received (${text.length} chars)`); if (!shell.isScreenOn()) { shell.wake("sidebar"); } - this.openTelepromptDocumentWindow("Shared text", text); + this.openTextDocumentWindow("Shared text", text); } - /** Open a teleprompt document as its own (closeable, non-singleton) window. */ - private openTelepromptDocumentWindow(title: string, text: string): void { - const windowId = `teleprompt:doc:${this.nextWindowSerial++}`; + /** Open a text document as its own (closeable, non-singleton) window. */ + private openTextDocumentWindow(title: string, text: string): void { + const windowId = `files:doc:${this.nextWindowSerial++}`; void this.launchInProcessApp(windowId, `window:${windowId}`, (options) => - createTelepromptDocumentWindow(windowId, title, text, options), + createTextDocumentWindow(windowId, title, text, options), ).catch((error) => { - this.appendLog(`teleprompt window failed: ${this.formatError(error)}`); + this.appendLog(`text document window failed: ${this.formatError(error)}`); + }); + } + + /** Open an image file as its own (closeable, non-singleton) window. */ + private openImageDocumentWindow(title: string, path: string): void { + const windowId = `files:doc:${this.nextWindowSerial++}`; + void this.launchInProcessApp(windowId, `window:${windowId}`, (options) => + createImageDocumentWindow(windowId, title, path, options), + ).catch((error) => { + this.appendLog(`image window failed: ${this.formatError(error)}`); }); } @@ -1252,11 +1263,12 @@ class DashboardController { ); return; } - if (appId === "teleprompt") { - await this.launchInProcessApp(TELEPROMPT_WINDOW_ID, TELEPROMPT_SURFACE_ID, (options) => - createTelepromptBrowserWindow({ + if (appId === "files") { + await this.launchInProcessApp(FILES_WINDOW_ID, FILES_SURFACE_ID, (options) => + createFilesAppWindow({ ...options, - openDocumentWindow: (title, text) => this.openTelepromptDocumentWindow(title, text), + openDocumentWindow: (title, text) => this.openTextDocumentWindow(title, text), + openImageWindow: (title, path) => this.openImageDocumentWindow(title, path), }), ); return; diff --git a/app/graphics/icons.ts b/app/graphics/icons.ts index af735e58..8b8f30e4 100644 --- a/app/graphics/icons.ts +++ b/app/graphics/icons.ts @@ -26,6 +26,16 @@ export const ICON_SVGS = { '', "file-text": '', + file: + '', + folder: + '', + image: + '', + film: + '', + "hard-drive": + '', music: '', activity: diff --git a/app/native/file-access.ts b/app/native/file-access.ts index bea525e4..4f0dfd0f 100644 --- a/app/native/file-access.ts +++ b/app/native/file-access.ts @@ -18,6 +18,8 @@ export type DirectoryEntry = { path: string; isDirectory: boolean; sizeBytes: number; + /** Last-modified time in epoch ms; 0 when unknown. */ + modifiedMs: number; }; export function hasAllFilesAccess(): boolean { @@ -60,6 +62,7 @@ export function listDirectory(path: string): DirectoryEntry[] | null { path: String(file.getAbsolutePath()), isDirectory: Boolean(file.isDirectory()), sizeBytes: Number(file.length()), + modifiedMs: Number(file.lastModified()), }); } entries.sort((a, b) => { @@ -73,6 +76,24 @@ export function listDirectory(path: string): DirectoryEntry[] | null { } } +/** Stat a single path; null when it does not exist or cannot be checked. */ +export function statPath(path: string): DirectoryEntry | null { + try { + const file = new java.io.File(path); + if (!file.exists()) return null; + return { + name: String(file.getName()), + path: String(file.getAbsolutePath()), + isDirectory: Boolean(file.isDirectory()), + sizeBytes: Number(file.length()), + modifiedMs: Number(file.lastModified()), + }; + } catch (error) { + console.warn(`statPath failed for ${path}: ${error}`); + return null; + } +} + /** Write UTF-8 text to a file in the public Downloads directory; returns its path or null. */ export function writeTextToDownloads(filename: string, text: string): string | null { try { diff --git a/app/native/image-files.ts b/app/native/image-files.ts new file mode 100644 index 00000000..78a335e7 --- /dev/null +++ b/app/native/image-files.ts @@ -0,0 +1,48 @@ +/** + * Image-file decoding for the on-glasses image viewer, backed by the Java + * ImageFileLoader (BitmapFactory handles PNG/JPEG/GIF/BMP/WebP/HEIC). + */ +import { GrayImage } from "../graphics/image"; +import { toUint8Array } from "../util/array-util"; + +declare const com: any; +declare const global: any; + +/** File extensions BitmapFactory can decode (no SVG). */ +const DECODABLE_IMAGE = /\.(png|jpe?g|gif|bmp|webp|heic|heif)$/i; + +export function isDecodableImageFile(name: string): boolean { + return DECODABLE_IMAGE.test(name); +} + +/** + * Decode a gray packet ([widthLo, widthHi, heightLo, heightHi, pixels...], + * the format the Java helpers return) into a GrayImage; null when empty or + * malformed. + */ +export function grayImageFromPacket(raw: ArrayLike | null | undefined): GrayImage | null { + const bytes = toUint8Array(raw); + if (bytes.length < 4) return null; + const width = bytes[0]! | (bytes[1]! << 8); + const height = bytes[2]! | (bytes[3]! << 8); + if (width <= 0 || height <= 0 || bytes.length < 4 + width * height) return null; + const image = new GrayImage(width, height, 0); + image.pixels.set(bytes.subarray(4, 4 + width * height)); + return image; +} + +/** + * Load an image file as grayscale, downscaled to fit maxWidth x maxHeight + * (aspect preserved, never upscaled); null when unreadable or undecodable. + */ +export function loadImageFileAsGray(path: string, maxWidth: number, maxHeight: number): GrayImage | null { + if (!global.isAndroid) return null; + try { + return grayImageFromPacket( + com.faceclaw.app.ImageFileLoader.loadGray(path, Math.round(maxWidth), Math.round(maxHeight)), + ); + } catch (error) { + console.warn(`loadImageFileAsGray failed for ${path}: ${error}`); + return null; + } +} diff --git a/app/native/media-controller.ts b/app/native/media-controller.ts index d09afeab..c17a8480 100644 --- a/app/native/media-controller.ts +++ b/app/native/media-controller.ts @@ -1,6 +1,6 @@ import { Utils } from "@nativescript/core"; import { GrayImage } from "../graphics/image"; -import { toUint8Array } from "../util/array-util"; +import { grayImageFromPacket } from "./image-files"; declare const com: any; @@ -140,14 +140,7 @@ export class FaceclawMediaControllerBridge { if (!global.isAndroid) return null; this.ensureController(); if (!this.controller) return null; - const bytes = toUint8Array(this.controller.getAlbumArtGray(Math.round(maxSize))); - if (bytes.length < 4) return null; - const width = bytes[0]! | (bytes[1]! << 8); - const height = bytes[2]! | (bytes[3]! << 8); - if (width <= 0 || height <= 0 || bytes.length < 4 + width * height) return null; - const image = new GrayImage(width, height, 0); - image.pixels.set(bytes.subarray(4, 4 + width * height)); - return image; + return grayImageFromPacket(this.controller.getAlbumArtGray(Math.round(maxSize))); } /** The player's queue (playlist), empty when the player exposes none. */ diff --git a/app/native/share-intents.ts b/app/native/share-intents.ts index a134ea91..07eab7d0 100644 --- a/app/native/share-intents.ts +++ b/app/native/share-intents.ts @@ -29,7 +29,7 @@ async function handleShareIntent(intent: android.content.Intent): Promise return; } const { dashboardController } = await import("../g2/dashboard-controller"); - await dashboardController.openTelepromptDocument(text); + await dashboardController.openSharedTextDocument(text); } function readPlainTextShare(intent: android.content.Intent): string | null { diff --git a/app/ui/apps/file-browser.ts b/app/ui/apps/file-browser.ts index 723d8149..11e03d75 100644 --- a/app/ui/apps/file-browser.ts +++ b/app/ui/apps/file-browser.ts @@ -1,12 +1,17 @@ import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont"; import { GrayImage } from "../../graphics/image"; +import { renderIcon, type IconName } from "../../graphics/icons"; import { clamp } from "../../util/numeric-util"; -import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK } from "../gestures"; -import { drawSelectionHighlight, scrollToKeepSelectionVisible } from "../menu"; +import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL } from "../gestures"; +import { drawListScrollbar, drawSelectionHighlight, scrollToKeepSelectionVisible, type MenuItem } from "../menu"; +import { ConfigSettingEnum } from "../dashboard-settings"; +import { getStringSetting, setStringSetting } from "../../native/settings-store"; import { + externalStorageRootPath, hasAllFilesAccess, listDirectory, requestAllFilesAccess, + statPath, type DirectoryEntry, } from "../../native/file-access"; import { Layer, type DashboardInputEvent, type LayerContext } from "../layers"; @@ -16,148 +21,559 @@ const ROW_HEIGHT = 16; const LIST_X = 20; const FOOTER_HEIGHT = 22; +const GRID_COLS = 5; +const GRID_VISIBLE_ROWS = 3; +const GRID_BOTTOM_MARGIN = 20; +const ICON_SIZE = 44; +const LABEL_GAP = 2; + +export type FilesViewMode = "icons" | "list"; + +export const filesViewModeSetting = new ConfigSettingEnum({ + id: "files-view-mode", + label: "View", + storageKey: "files.viewMode", + defaultValue: "icons", + values: ["icons", "list"], + formatValue: (value) => (value === "icons" ? "Icons" : "List"), +}); + +// Bookmarked paths, in bookmarking order, stored as a JSON string array. +const BOOKMARKS_KEY = "files.bookmarks"; + +export function getBookmarkedPaths(): string[] { + try { + const parsed = JSON.parse(getStringSetting(BOOKMARKS_KEY, "[]")); + return Array.isArray(parsed) ? parsed.filter((path): path is string => typeof path === "string") : []; + } catch { + return []; + } +} + +export function isBookmarked(path: string): boolean { + return getBookmarkedPaths().includes(path); +} + +export function toggleBookmark(path: string): void { + const paths = getBookmarkedPaths(); + const next = paths.includes(path) ? paths.filter((p) => p !== path) : [...paths, path]; + setStringSetting(BOOKMARKS_KEY, JSON.stringify(next)); +} + +const TEXT_EXT = /\.(txt|md|markdown|log|json|xml|csv|ini|conf|cfg|yaml|yml|ts|js|py|java|c|cpp|h|sh|html|css)$/i; +const IMAGE_EXT = /\.(png|jpe?g|gif|bmp|webp|heic|heif|svg)$/i; +const VIDEO_EXT = /\.(mp4|mkv|webm|avi|mov|3gp|m4v)$/i; +const AUDIO_EXT = /\.(mp3|m4a|aac|ogg|oga|opus|flac|wav|mid)$/i; + +function fileIconName(name: string): IconName { + if (TEXT_EXT.test(name)) return "file-text"; + if (IMAGE_EXT.test(name)) return "image"; + if (VIDEO_EXT.test(name)) return "film"; + if (AUDIO_EXT.test(name)) return "music"; + return "file"; +} + export type FileBrowserOptions = { - startPath: string; - /** Files failing this are listed dimmed and cannot be picked. */ + /** Files failing this are listed dimmed (not viewable); picking them still fires onFilePicked. */ isSupportedFile: (name: string) => boolean; onFilePicked: (entry: DirectoryEntry, ctx: LayerContext) => void; - /** Double-click while already at startPath (leave the browser). */ + /** Double-click while already at the Places level (leave the browser). */ onLeave: () => void; }; -type BrowserRow = - | { kind: "grant"; label: string } - | { kind: "info"; label: string } - | { kind: "entry"; label: string; entry: DirectoryEntry; supported: boolean }; +type EntryItem = { + kind: "entry"; + label: string; + icon: IconName; + entry: DirectoryEntry; + supported: boolean; + /** A bookmark whose path no longer exists (listed only for unbookmarking). */ + missing?: boolean; + /** An item on the Places level (a bookmark or a fixed storage root). */ + place: boolean; + /** Fixed Places roots cannot be bookmarked or unbookmarked. */ + fixed: boolean; +}; + +type BrowserItem = { kind: "grant"; label: string } | { kind: "info"; label: string } | EntryItem; + +type IconRow = + | { kind: "special"; item: BrowserItem; flatIndex: number } + | { kind: "grid"; items: EntryItem[]; firstIndex: number }; + +type IconMode = "row" | "item"; /** - * Minimal filesystem browser: scroll to select, click to descend into a - * directory or pick a supported file, double-click to go up (leaving the - * browser when already at the top). Sized to its hosting stack. + * Filesystem browser with two views. The top "Places" level lists bookmarks + * and the storage roots; descending browses real directories. Icons view is a + * 5-column grid with launcher-style two-level selection (scroll picks a row, + * click drops into the row, scroll picks the item); list view is a flat list. + * Click descends into a directory or picks a supported file; double-click + * backs out one level (item selection, then parent directory, then Places, + * then leaving the browser). Sized to its hosting stack. */ export class FileBrowserLayer implements Layer { - private currentPath: string; + /** Current directory, or null at the Places level. */ + private location: string | null = null; + /** The Places entry we descended through; going up from it returns to Places. */ + private navRoot: string | null = null; private entries: DirectoryEntry[] | null = null; private listingFailed = false; - private selectedIndex = 0; + + private listIndex = 0; + private selectedRow = 0; + private selectedCol = 0; + private iconMode: IconMode = "row"; private scrollRow = 0; - constructor(private readonly options: FileBrowserOptions) { - this.currentPath = options.startPath; - } + constructor(private readonly options: FileBrowserOptions) {} paint(ctx: LayerContext): GrayImage { const font = getDefaultSmallFont(); const { width, height } = ctx.stack.getBaseSize(); const image = new GrayImage(width, height, 0); - this.loadEntries(); - const rows = this.buildRows(); - this.selectedIndex = clamp(this.selectedIndex, 0, Math.max(0, rows.length - 1)); + const rows = this.flatRows(); - image.drawText(font, 20, 8, "Teleprompt files", 220); - image.drawText(font, 20, 22, truncateLeft(font, this.currentPath, width - 40), 130); + image.drawText(font, 20, 8, "Files", 220); + const pathLabel = this.location === null ? "Places" : this.location; + image.drawText(font, 20, 22, truncateLeft(font, pathLabel, width - 40), 130); + + if (filesViewModeSetting.get() === "list") { + this.paintList(image, font, rows, ctx); + } else { + this.paintIcons(image, font, rows, ctx); + } + return image; + } + + private paintList(image: GrayImage, font: BdfFont, rows: BrowserItem[], ctx: LayerContext): void { + const { width, height } = ctx.stack.getBaseSize(); + this.listIndex = clamp(this.listIndex, 0, Math.max(0, rows.length - 1)); const listHeight = height - HEADER_HEIGHT - FOOTER_HEIGHT; const visibleRows = Math.max(1, (listHeight / ROW_HEIGHT) | 0); - this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.selectedIndex, visibleRows, rows.length); + this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.listIndex, visibleRows, rows.length); const lastVisible = Math.min(rows.length, this.scrollRow + visibleRows); for (let index = this.scrollRow; index < lastVisible; index++) { const row = rows[index]!; const y = HEADER_HEIGHT + (index - this.scrollRow) * ROW_HEIGHT; - const selected = index === this.selectedIndex; + const selected = index === this.listIndex; if (selected) { drawSelectionHighlight(image, LIST_X - 6, y - 1, width - 2 * LIST_X + 12, ROW_HEIGHT - 1, ctx.stack.isFocused(), 4); } - const value = rowValue(row, selected); + const value = itemValue(row, selected); image.drawText(font, LIST_X, y + 1, truncateRight(font, row.label, width - 2 * LIST_X), value); } image.drawText(font, 20, height - 16, `${GESTURE_CLICK} open ${GESTURE_DOUBLE_CLICK} up / back`, 110); - return image; + } + + private paintIcons(image: GrayImage, font: BdfFont, rows: BrowserItem[], ctx: LayerContext): void { + const { width, height } = ctx.stack.getBaseSize(); + const focused = ctx.stack.isFocused(); + const iconRows = buildIconRows(rows); + this.selectedRow = clamp(this.selectedRow, 0, Math.max(0, iconRows.length - 1)); + + const gridTop = HEADER_HEIGHT; + const gridBottom = height - GRID_BOTTOM_MARGIN; + const rowH = Math.floor((gridBottom - gridTop) / GRID_VISIBLE_ROWS); + const colW = width / GRID_COLS; + this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.selectedRow, GRID_VISIBLE_ROWS, iconRows.length); + + const lastVisible = Math.min(iconRows.length, this.scrollRow + GRID_VISIBLE_ROWS); + for (let rowIndex = this.scrollRow; rowIndex < lastVisible; rowIndex++) { + const row = iconRows[rowIndex]!; + const y = gridTop + (rowIndex - this.scrollRow) * rowH; + const selected = rowIndex === this.selectedRow; + + if (row.kind === "special") { + const textY = y + (((rowH - font.lineHeight) / 2) | 0); + if (selected) { + drawSelectionHighlight(image, LIST_X - 6, textY - 2, width - 2 * LIST_X + 12, font.lineHeight + 4, focused, 4); + } + image.drawText(font, LIST_X, textY, truncateRight(font, row.item.label, width - 2 * LIST_X), itemValue(row.item, selected)); + continue; + } + + if (selected) { + if (this.iconMode === "row") { + drawSelectionHighlight(image, 4, y + 1, width - 8, rowH - 2, focused, 6); + } else { + this.selectedCol = clamp(this.selectedCol, 0, row.items.length - 1); + drawSelectionHighlight(image, this.selectedCol * colW + 4, y + 1, colW - 8, rowH - 2, focused, 6); + } + } + + for (let col = 0; col < row.items.length; col++) { + const item = row.items[col]!; + const centerX = col * colW + colW / 2; + const blockTop = y + Math.max(2, (rowH - ICON_SIZE - font.lineHeight - LABEL_GAP) / 2); + const icon = renderIcon(item.icon, ICON_SIZE); + if (icon) { + image.bitBlt(item.supported ? icon : dimmedIcon(item.icon, icon), Math.round(centerX - icon.width / 2), Math.round(blockTop), { + transparentZero: true, + }); + } + const label = truncateRight(font, item.label, colW - 8); + const labelY = Math.round(blockTop + ICON_SIZE + LABEL_GAP); + image.drawText(font, Math.round(centerX - font.measureText(label) / 2), labelY, label, item.supported ? 210 : 100); + } + } + + if (iconRows.length > GRID_VISIBLE_ROWS) { + drawListScrollbar(image, width - 5, gridTop, GRID_VISIBLE_ROWS * rowH - 4, this.scrollRow, GRID_VISIBLE_ROWS, iconRows.length); + } + + const hint = + this.iconMode === "row" + ? `${GESTURE_SCROLL} row ${GESTURE_CLICK} pick ${GESTURE_DOUBLE_CLICK} up / back` + : `${GESTURE_SCROLL} item ${GESTURE_CLICK} open ${GESTURE_DOUBLE_CLICK} row`; + image.drawText(font, 20, height - 16, hint, 110); } async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise { - const rows = this.buildRows(); + if (filesViewModeSetting.get() === "list") { + await this.handleListInput(event, ctx); + } else { + await this.handleIconsInput(event, ctx); + } + } + + private async handleListInput(event: DashboardInputEvent, ctx: LayerContext): Promise { + const rows = this.flatRows(); switch (event.type) { case "scroll-up": - this.selectedIndex = Math.max(0, this.selectedIndex - 1); + this.listIndex = Math.max(0, this.listIndex - 1); return; case "scroll-down": - this.selectedIndex = Math.min(Math.max(0, rows.length - 1), this.selectedIndex + 1); + this.listIndex = Math.min(Math.max(0, rows.length - 1), this.listIndex + 1); return; case "click": { - const row = rows[clamp(this.selectedIndex, 0, Math.max(0, rows.length - 1))]; - if (!row) return; - if (row.kind === "grant") { - requestAllFilesAccess(); - this.entries = null; // re-list after the user returns from Settings - return; - } - if (row.kind !== "entry") return; - if (row.entry.isDirectory) { - this.navigateTo(row.entry.path); - } else if (row.supported) { - this.options.onFilePicked(row.entry, ctx); - } + const row = rows[clamp(this.listIndex, 0, Math.max(0, rows.length - 1))]; + if (row) await this.activateItem(row, ctx); return; } - case "double-click": { - if (this.currentPath === this.options.startPath) { - this.options.onLeave(); - return; - } - const parent = this.currentPath.slice(0, this.currentPath.lastIndexOf("/")); - this.navigateTo(parent.length >= this.options.startPath.length ? parent : this.options.startPath); + case "double-click": + this.navigateUp(); return; - } default: return; } } - private navigateTo(path: string): void { - this.currentPath = path; - this.entries = null; - this.selectedIndex = 0; + private async handleIconsInput(event: DashboardInputEvent, ctx: LayerContext): Promise { + const rows = this.flatRows(); + const iconRows = buildIconRows(rows); + this.selectedRow = clamp(this.selectedRow, 0, Math.max(0, iconRows.length - 1)); + const row = iconRows[this.selectedRow]; + switch (event.type) { + case "scroll-up": + case "scroll-down": { + const delta = event.type === "scroll-down" ? 1 : -1; + if (this.iconMode === "item" && row?.kind === "grid") { + this.selectedCol = clamp(this.selectedCol + delta, 0, row.items.length - 1); + } else { + this.selectedRow = clamp(this.selectedRow + delta, 0, Math.max(0, iconRows.length - 1)); + } + return; + } + case "click": { + if (!row) return; + if (row.kind === "special") { + await this.activateItem(row.item, ctx); + return; + } + if (this.iconMode === "row") { + this.iconMode = "item"; + // Default to the middle column (clamped to the row's item count). + this.selectedCol = Math.min(Math.floor(GRID_COLS / 2), row.items.length - 1); + } else { + const item = row.items[clamp(this.selectedCol, 0, row.items.length - 1)]; + if (item) await this.activateItem(item, ctx); + } + return; + } + case "double-click": + if (this.iconMode === "item") { + this.iconMode = "row"; + } else { + this.navigateUp(); + } + return; + default: + return; + } + } + + /** + * App-specific entries for the window long-press menu: the view switch, + * plus bookmark/unbookmark for the selected entry (in icons view only once + * an item, not just a row, is selected). + */ + buildMenuItems(): MenuItem[] { + const items: MenuItem[] = []; + const mode = filesViewModeSetting.get(); + items.push({ + label: mode === "icons" ? "View as list" : "View as icons", + onSelect: (ctx) => { + this.setViewMode(mode === "icons" ? "list" : "icons"); + ctx.stack.pop(); + }, + }); + const target = this.currentItem(); + if (target && target.kind === "entry" && !target.fixed) { + const path = target.entry.path; + const name = truncateChars(target.entry.name || path, 24); + items.push({ + label: isBookmarked(path) ? `Remove bookmark: ${name}` : `Bookmark: ${name}`, + onSelect: (ctx) => { + toggleBookmark(path); + const rows = this.flatRows(); + this.listIndex = clamp(this.listIndex, 0, Math.max(0, rows.length - 1)); + ctx.stack.pop(); + }, + }); + } + return items; + } + + /** The item an entry-specific action would apply to, if one is selected. */ + private currentItem(): BrowserItem | null { + const rows = this.flatRows(); + if (!rows.length) return null; + if (filesViewModeSetting.get() === "list") { + return rows[clamp(this.listIndex, 0, rows.length - 1)] ?? null; + } + const iconRows = buildIconRows(rows); + const row = iconRows[clamp(this.selectedRow, 0, iconRows.length - 1)]; + if (!row) return null; + if (row.kind === "special") return row.item; + if (this.iconMode !== "item") return null; + return row.items[clamp(this.selectedCol, 0, row.items.length - 1)] ?? null; + } + + private setViewMode(mode: FilesViewMode): void { + if (filesViewModeSetting.get() === mode) return; + const rows = this.flatRows(); + const iconRows = buildIconRows(rows); + if (mode === "list") { + // Carry the icon-grid selection into the flat list (clamped column when + // only a row was selected). + const row = iconRows[clamp(this.selectedRow, 0, Math.max(0, iconRows.length - 1))]; + if (row) { + this.listIndex = + row.kind === "special" ? row.flatIndex : row.firstIndex + clamp(this.selectedCol, 0, row.items.length - 1); + } + } else { + this.setGridSelectionFromFlatIndex(rows, clamp(this.listIndex, 0, Math.max(0, rows.length - 1))); + this.iconMode = "row"; + } + filesViewModeSetting.set(mode); this.scrollRow = 0; } - private loadEntries(): void { - if (this.entries !== null) return; - const listing = listDirectory(this.currentPath); - this.listingFailed = listing === null; - this.entries = listing ?? []; + private async activateItem(item: BrowserItem, ctx: LayerContext): Promise { + if (item.kind === "grant") { + requestAllFilesAccess(); + this.entries = null; // re-list after the user returns from Settings + return; + } + if (item.kind !== "entry" || item.missing) return; + if (item.entry.isDirectory) { + this.navigateTo(item.entry.path, item.place); + } else { + // Every real file opens the picked-file dialog, viewable or not (the + // dialog shows metadata; open actions depend on the type). + this.options.onFilePicked(item.entry, ctx); + } } - private buildRows(): BrowserRow[] { - this.loadEntries(); - const rows: BrowserRow[] = []; + private navigateTo(path: string, asRoot = false): void { + if (asRoot) this.navRoot = path; + this.location = path; + this.entries = null; + this.resetSelection(); + } + + private navigateUp(): void { + const from = this.location; + if (from === null) { + this.options.onLeave(); + return; + } + if (from === this.navRoot || from === "/") { + this.location = null; + this.entries = null; + this.resetSelection(); + this.selectPath(this.navRoot ?? from); + this.navRoot = null; + return; + } + const parentRaw = from.slice(0, from.lastIndexOf("/")); + this.navigateTo(parentRaw.length ? parentRaw : "/"); + this.selectPath(from); + } + + private resetSelection(): void { + this.listIndex = 0; + this.selectedRow = 0; + this.selectedCol = 0; + this.iconMode = "row"; + this.scrollRow = 0; + } + + /** Select the item with the given path (e.g. the directory just left). */ + private selectPath(path: string): void { + const rows = this.flatRows(); + const index = rows.findIndex((row) => row.kind === "entry" && row.entry.path === path); + if (index < 0) return; + this.listIndex = index; + this.setGridSelectionFromFlatIndex(rows, index); + } + + private setGridSelectionFromFlatIndex(rows: BrowserItem[], index: number): void { + const specials = leadingSpecialCount(rows); + if (index < specials) { + this.selectedRow = index; + this.selectedCol = 0; + return; + } + const ordinal = index - specials; + this.selectedRow = specials + Math.floor(ordinal / GRID_COLS); + this.selectedCol = ordinal % GRID_COLS; + } + + private flatRows(): BrowserItem[] { + const rows: BrowserItem[] = []; if (!hasAllFilesAccess()) { rows.push({ kind: "grant", label: "Grant file access (opens phone Settings)" }); } + if (this.location === null) { + for (const path of getBookmarkedPaths()) { + rows.push(this.bookmarkItem(path)); + } + rows.push(this.placeItem("Internal storage", externalStorageRootPath())); + rows.push(this.placeItem("/", "/")); + return rows; + } + this.loadEntries(); for (const entry of this.entries ?? []) { rows.push({ kind: "entry", entry, - supported: entry.isDirectory || this.options.isSupportedFile(entry.name), label: entry.isDirectory ? `${entry.name}/` : entry.name, + icon: entry.isDirectory ? "folder" : fileIconName(entry.name), + supported: entry.isDirectory || this.options.isSupportedFile(entry.name), + place: false, + fixed: false, }); } - if (!rows.length || (this.listingFailed && rows.every((row) => row.kind !== "entry"))) { + if (!rows.some((row) => row.kind === "entry")) { rows.push({ kind: "info", label: this.listingFailed ? "(unreadable directory)" : "(empty directory)" }); } return rows; } + + private placeItem(label: string, path: string): EntryItem { + return { + kind: "entry", + entry: { name: label, path, isDirectory: true, sizeBytes: 0, modifiedMs: 0 }, + label, + icon: "hard-drive", + supported: true, + place: true, + fixed: true, + }; + } + + private bookmarkItem(path: string): EntryItem { + const stat = statPath(path); + if (!stat) { + const name = basename(path); + return { + kind: "entry", + entry: { name, path, isDirectory: false, sizeBytes: 0, modifiedMs: 0 }, + label: `${name} (missing)`, + icon: "file", + supported: false, + missing: true, + place: true, + fixed: false, + }; + } + const name = stat.name || path; + return { + kind: "entry", + entry: stat, + label: stat.isDirectory ? `${name}/` : name, + icon: stat.isDirectory ? "folder" : fileIconName(name), + supported: stat.isDirectory || this.options.isSupportedFile(name), + place: true, + fixed: false, + }; + } + + private loadEntries(): void { + if (this.entries !== null || this.location === null) return; + const listing = listDirectory(this.location); + this.listingFailed = listing === null; + this.entries = listing ?? []; + } } -function rowValue(row: BrowserRow, selected: boolean): number { - if (row.kind === "info") return 120; - if (row.kind === "grant") return selected ? 255 : 210; - if (!row.supported) return selected ? 140 : 100; +function buildIconRows(flat: BrowserItem[]): IconRow[] { + const rows: IconRow[] = []; + let index = 0; + // Special rows (grant prompt, empty/unreadable info) lead the list; each + // gets a full-width row of its own. Entries follow, chunked into grid rows. + while (index < flat.length && flat[index]!.kind !== "entry") { + rows.push({ kind: "special", item: flat[index]!, flatIndex: index }); + index++; + } + for (; index < flat.length; index += GRID_COLS) { + rows.push({ kind: "grid", items: flat.slice(index, index + GRID_COLS) as EntryItem[], firstIndex: index }); + } + return rows; +} + +function leadingSpecialCount(rows: BrowserItem[]): number { + let count = 0; + while (count < rows.length && rows[count]!.kind !== "entry") count++; + return count; +} + +function itemValue(item: BrowserItem, selected: boolean): number { + if (item.kind === "info") return 120; + if (item.kind === "grant") return selected ? 255 : 210; + if (!item.supported) return selected ? 140 : 100; return selected ? 255 : 200; } +// Unsupported files draw their grid icon at half brightness; rendered once +// per icon name and cached (all grid icons share one size). +const dimmedIconCache = new Map(); + +function dimmedIcon(name: IconName, icon: GrayImage): GrayImage { + const cached = dimmedIconCache.get(name); + if (cached) return cached; + const dimmed = new GrayImage(icon.width, icon.height, 0); + for (let i = 0; i < icon.pixels.length; i++) { + dimmed.pixels[i] = icon.pixels[i]! >> 1; + } + dimmedIconCache.set(name, dimmed); + return dimmed; +} + +function basename(path: string): string { + const parts = path.split("/").filter((part) => part.length > 0); + return parts[parts.length - 1] ?? path; +} + +function truncateChars(text: string, maxLength: number): string { + return text.length <= maxLength ? text : `${text.slice(0, Math.max(0, maxLength - 3))}...`; +} + function truncateRight(font: BdfFont, text: string, maxWidth: number): string { if (font.measureText(text) <= maxWidth) return text; let out = text; diff --git a/app/ui/apps/file-info-dialog.ts b/app/ui/apps/file-info-dialog.ts new file mode 100644 index 00000000..d5ced05a --- /dev/null +++ b/app/ui/apps/file-info-dialog.ts @@ -0,0 +1,119 @@ +import { getDefaultSmallFont } from "../../graphics/bdffont"; +import { GrayImage } from "../../graphics/image"; +import { wrapText } from "../../graphics/textwrap"; +import type { DirectoryEntry } from "../../native/file-access"; +import { GESTURE_DOUBLE_CLICK } from "../gestures"; +import { Layer, type DashboardInputEvent, type LayerContext, type PaintBelow } from "../layers"; +import { drawSelectionHighlight } from "../menu"; + +const DIALOG_X = 8; +const DIALOG_Y = 8; +const DIALOG_WIDTH = 272; +const PADDING = 10; +const INFO_LINE_STEP = 14; +const ACTION_ROW_HEIGHT = 20; +const MAX_NAME_LINES = 3; + +export type FileInfoAction = { + label: string; + onSelect: (ctx: LayerContext) => Promise | void; +}; + +/** + * The picked-file dialog: metadata (full untruncated name, size, modified + * date) followed by the open actions for viewable file types — possibly none + * for files nothing can open. Opened by the browser for every file; + * double-click closes it. + */ +export class FileInfoDialogLayer implements Layer { + private selectedIndex = 0; + + constructor( + private readonly entry: DirectoryEntry, + private readonly actions: FileInfoAction[], + ) {} + + paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage { + const font = getDefaultSmallFont(); + const { height: viewportHeight } = ctx.stack.getBaseSize(); + const image = paintBelow(); + + const textWidth = DIALOG_WIDTH - 2 * PADDING - 4; + const nameLines = wrapText(font, this.entry.name, textWidth, { breakLongWords: true }).slice(0, MAX_NAME_LINES); + const infoLines = [ + `Size: ${formatSize(this.entry.sizeBytes)}`, + `Modified: ${formatDate(this.entry.modifiedMs)}`, + ]; + const bodyTop = PADDING + (nameLines.length + infoLines.length) * INFO_LINE_STEP + 6; + const bodyHeight = this.actions.length ? this.actions.length * ACTION_ROW_HEIGHT : INFO_LINE_STEP; + const height = Math.min(bodyTop + bodyHeight + PADDING, viewportHeight - 2 * DIALOG_Y); + + // Fill 1, not 0: identical after 4bpp quantization, but 0 is the + // transparent color key when painting on the shell surface. + image.fillRoundedRect(DIALOG_X, DIALOG_Y, DIALOG_WIDTH, height, 1); + image.drawRoundedRect(DIALOG_X, DIALOG_Y, DIALOG_WIDTH, height, 72); + + let y = DIALOG_Y + PADDING; + for (const line of nameLines) { + image.drawText(font, DIALOG_X + PADDING + 2, y, line, 230); + y += INFO_LINE_STEP; + } + for (const line of infoLines) { + image.drawText(font, DIALOG_X + PADDING + 2, y, line, 150); + y += INFO_LINE_STEP; + } + y += 6; + + if (!this.actions.length) { + image.drawText(font, DIALOG_X + PADDING + 2, y + 3, `${GESTURE_DOUBLE_CLICK} close`, 110); + return image; + } + const focused = ctx.stack.isFocused(); + for (let index = 0; index < this.actions.length; index++) { + const rowY = y + index * ACTION_ROW_HEIGHT; + const selected = index === this.selectedIndex; + if (selected) { + drawSelectionHighlight(image, DIALOG_X + 12, rowY, DIALOG_WIDTH - 24, ACTION_ROW_HEIGHT - 1, focused, 8); + } + image.drawText(font, DIALOG_X + 22, rowY + 3, this.actions[index]!.label, selected ? 255 : 200); + } + return image; + } + + async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise { + switch (event.type) { + case "scroll-up": + if (this.actions.length) { + this.selectedIndex = (this.selectedIndex + this.actions.length - 1) % this.actions.length; + } + return; + case "scroll-down": + if (this.actions.length) { + this.selectedIndex = (this.selectedIndex + 1) % this.actions.length; + } + return; + case "click": + await this.actions[this.selectedIndex]?.onSelect(ctx); + return; + case "double-click": + ctx.stack.pop(); + return; + default: + return; + } + } +} + +function formatSize(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; + return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`; +} + +function formatDate(ms: number): string { + if (!ms) return "unknown"; + const date = new Date(ms); + const pad = (n: number) => String(n).padStart(2, "0"); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`; +} diff --git a/app/ui/apps/image-viewer.ts b/app/ui/apps/image-viewer.ts new file mode 100644 index 00000000..8ec2ac65 --- /dev/null +++ b/app/ui/apps/image-viewer.ts @@ -0,0 +1,65 @@ +import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont"; +import { GrayImage } from "../../graphics/image"; +import { loadImageFileAsGray } from "../../native/image-files"; +import { GESTURE_DOUBLE_CLICK } from "../gestures"; +import { Layer, type DashboardInputEvent, type LayerContext } from "../layers"; + +const MARGIN_X = 18; +const TITLE_Y = 8; +const BODY_TOP = 24; +const BODY_MARGIN = 2; + +/** + * Image viewer for a file on disk: title line, then the image decoded to + * grayscale and downscaled to fit the remaining area (never upscaled). + * Double-click closes it. Sized to its hosting stack (a Files document + * window, or pushed over the file browser for view-in-place). + */ +export class ImageViewerLayer implements Layer { + private image: GrayImage | null = null; + private loadAttempted = false; + + constructor( + private readonly path: string, + private readonly title: string, + ) {} + + paint(ctx: LayerContext): GrayImage { + const font = getDefaultSmallFont(); + const { width, height } = ctx.stack.getBaseSize(); + const out = new GrayImage(width, height, 0); + out.drawText(font, MARGIN_X, TITLE_Y, truncateToWidth(font, this.title, width - 2 * MARGIN_X), 220); + + const bodyHeight = height - BODY_TOP - BODY_MARGIN; + if (!this.loadAttempted) { + this.loadAttempted = true; + this.image = loadImageFileAsGray(this.path, width - 2 * BODY_MARGIN, bodyHeight); + } + if (!this.image) { + out.drawText(font, MARGIN_X, BODY_TOP + 16, "(could not load image)", 160); + out.drawText(font, MARGIN_X, height - 16, `${GESTURE_DOUBLE_CLICK} back`, 110); + return out; + } + out.bitBlt( + this.image, + Math.round((width - this.image.width) / 2), + BODY_TOP + Math.round((bodyHeight - this.image.height) / 2), + ); + return out; + } + + handleInput(event: DashboardInputEvent, ctx: LayerContext): void { + if (event.type === "double-click") { + ctx.stack.pop(); + } + } +} + +function truncateToWidth(font: BdfFont, text: string, maxWidth: number): string { + if (font.measureText(text) <= maxWidth) return text; + let out = text; + while (out.length > 1 && font.measureText(`${out}...`) > maxWidth) { + out = out.slice(0, -1); + } + return `${out}...`; +} diff --git a/app/ui/apps/teleprompt.ts b/app/ui/apps/text-viewer.ts similarity index 96% rename from app/ui/apps/teleprompt.ts rename to app/ui/apps/text-viewer.ts index 8d28ae32..74160021 100644 --- a/app/ui/apps/teleprompt.ts +++ b/app/ui/apps/text-viewer.ts @@ -11,10 +11,10 @@ const LINE_STEP = 14; const FOOTER_MARGIN = 36; /** - * Paged text viewer for a document. Sized to its hosting stack (a teleprompt + * Paged text viewer for a document. Sized to its hosting stack (a Files * document window, or pushed over the file browser for view-in-place). */ -export class TelepromptLayer implements Layer { +export class TextViewerLayer implements Layer { private lines: string[] | null = null; private wrappedForWidth = 0; private firstLine = 0; @@ -22,7 +22,7 @@ export class TelepromptLayer implements Layer { constructor( private readonly documentText: string, - private readonly title = "Teleprompt", + private readonly title = "Text", ) {} paint(ctx: LayerContext): GrayImage { diff --git a/app/ui/shell/files-app.ts b/app/ui/shell/files-app.ts new file mode 100644 index 00000000..bcdb2ab0 --- /dev/null +++ b/app/ui/shell/files-app.ts @@ -0,0 +1,153 @@ +import { readTextFile, type DirectoryEntry } from "../../native/file-access"; +import { isDecodableImageFile } from "../../native/image-files"; +import { FileBrowserLayer } from "../apps/file-browser"; +import { FileInfoDialogLayer, type FileInfoAction } from "../apps/file-info-dialog"; +import { ImageViewerLayer } from "../apps/image-viewer"; +import { TextViewerLayer } from "../apps/text-viewer"; +import { + createInProcessWindow, + YieldAtRootLayer, + type InProcessAppOptions, + type InProcessWindow, +} from "./in-process-window"; +import { shell } from "./shell"; + +export const FILES_WINDOW_ID = "files"; +export const FILES_SURFACE_ID = "window:files"; + +const TEXT_FILE = /\.(txt|md|log)$/i; + +export type FilesAppOptions = InProcessAppOptions & { + /** Open a text document as its own shell window (also used by the share intent). */ + openDocumentWindow: (title: string, text: string) => void; + /** Open an image file as its own shell window. */ + openImageWindow: (title: string, path: string) => void; +}; + +/** + * The Files app's launcher-opened window: a file browser over Places + * (bookmarks and storage roots). Picking any file opens an info dialog with + * metadata plus, for viewable types (text, images), the open actions. + */ +export function createFilesAppWindow(options: FilesAppOptions): InProcessWindow { + let created: InProcessWindow | null = null; + const browser = new FileBrowserLayer({ + isSupportedFile: (name) => TEXT_FILE.test(name) || isDecodableImageFile(name), + // The browser handles double-click itself (up a level), so it is not + // wrapped in YieldAtRootLayer; it yields explicitly from the top level. + onLeave: () => shell.yieldFocusToSidebar(), + onFilePicked: (entry, ctx) => { + ctx.stack.push(new FileInfoDialogLayer(entry, fileOpenActions(entry, options))); + }, + }); + created = createInProcessWindow({ + appId: "files", + windowId: FILES_WINDOW_ID, + title: "Files", + iconLetter: "F", + icon: "folder", + closeable: true, + // Browser actions (view switch, bookmarks) only apply while the browser + // itself is on top; a pushed viewer or dialog gets just the defaults. + menuItems: () => (created && !created.stack.isAtBase() ? [] : browser.buildMenuItems()), + actions: options.actions, + baseLayer: browser, + submitFrame: options.submitFrame, + setSurfaceVisible: options.setSurfaceVisible, + removeSurface: options.removeSurface, + onClosed: options.onClosed, + }); + return created; +} + +/** One opened text document as its own window (from the browser or a share intent). */ +export function createTextDocumentWindow( + windowId: string, + title: string, + text: string, + options: InProcessAppOptions, +): InProcessWindow { + return createInProcessWindow({ + appId: "files", + windowId, + title, + iconLetter: "F", + icon: "file-text", + closeable: true, + actions: options.actions, + baseLayer: new YieldAtRootLayer(new TextViewerLayer(text, title)), + submitFrame: options.submitFrame, + setSurfaceVisible: options.setSurfaceVisible, + removeSurface: options.removeSurface, + onClosed: options.onClosed, + }); +} + +/** One opened image file as its own window. */ +export function createImageDocumentWindow( + windowId: string, + title: string, + path: string, + options: InProcessAppOptions, +): InProcessWindow { + return createInProcessWindow({ + appId: "files", + windowId, + title, + iconLetter: "F", + icon: "image", + closeable: true, + actions: options.actions, + baseLayer: new YieldAtRootLayer(new ImageViewerLayer(path, title)), + submitFrame: options.submitFrame, + setSurfaceVisible: options.setSurfaceVisible, + removeSurface: options.removeSurface, + onClosed: options.onClosed, + }); +} + +/** + * The open actions for the picked-file dialog: View here / Open in new + * window for viewable types, empty for everything else (metadata only). + */ +function fileOpenActions(entry: DirectoryEntry, options: FilesAppOptions): FileInfoAction[] { + if (TEXT_FILE.test(entry.name)) { + return [ + { + label: "View here", + onSelect: (ctx) => { + const text = readTextFile(entry.path); + ctx.stack.pop(); + ctx.stack.push(new TextViewerLayer(text ?? "(could not read file)", entry.name)); + }, + }, + { + label: "Open in new window", + onSelect: (ctx) => { + const text = readTextFile(entry.path); + ctx.stack.pop(); + options.openDocumentWindow(entry.name, text ?? "(could not read file)"); + }, + }, + ]; + } + if (isDecodableImageFile(entry.name)) { + return [ + { + label: "View here", + onSelect: (ctx) => { + ctx.stack.pop(); + ctx.stack.push(new ImageViewerLayer(entry.path, entry.name)); + }, + }, + { + label: "Open in new window", + onSelect: (ctx) => { + ctx.stack.pop(); + options.openImageWindow(entry.name, entry.path); + }, + }, + ]; + } + return []; +} diff --git a/app/ui/shell/teleprompt-app.ts b/app/ui/shell/teleprompt-app.ts deleted file mode 100644 index 93c45ace..00000000 --- a/app/ui/shell/teleprompt-app.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { externalStorageRootPath, readTextFile, type DirectoryEntry } from "../../native/file-access"; -import { FileBrowserLayer } from "../apps/file-browser"; -import { TelepromptLayer } from "../apps/teleprompt"; -import { MenuLayer } from "../menu"; -import { APP_VIEWPORT } from "./geometry"; -import { - createInProcessWindow, - YieldAtRootLayer, - type InProcessAppOptions, - type InProcessWindow, -} from "./in-process-window"; -import { shell } from "./shell"; - -export const TELEPROMPT_WINDOW_ID = "teleprompt"; -export const TELEPROMPT_SURFACE_ID = "window:teleprompt"; - -const SUPPORTED_FILE = /\.(txt|md|log)$/i; - -export type TelepromptBrowserOptions = InProcessAppOptions & { - /** Open a document as its own shell window (also used by the share intent). */ - openDocumentWindow: (title: string, text: string) => void; -}; - -/** - * The Teleprompt app's launcher-opened window: a file browser over external - * storage. Picking a supported (text) file offers viewing it in this window - * or opening it as a new window. - */ -export function createTelepromptBrowserWindow(options: TelepromptBrowserOptions): InProcessWindow { - const browser = new FileBrowserLayer({ - startPath: externalStorageRootPath(), - isSupportedFile: (name) => SUPPORTED_FILE.test(name), - // The browser handles double-click itself (up a directory), so it is not - // wrapped in YieldAtRootLayer; it yields explicitly from the top level. - onLeave: () => shell.yieldFocusToSidebar(), - onFilePicked: (entry, ctx) => { - ctx.stack.push(createFilePickedMenu(entry, options.openDocumentWindow)); - }, - }); - return createInProcessWindow({ - appId: "teleprompt", - windowId: TELEPROMPT_WINDOW_ID, - title: "Teleprompt", - iconLetter: "Tp", - icon: "file-text", - closeable: true, - actions: options.actions, - baseLayer: browser, - submitFrame: options.submitFrame, - setSurfaceVisible: options.setSurfaceVisible, - removeSurface: options.removeSurface, - onClosed: options.onClosed, - }); -} - -/** One opened document as its own window (from the browser or a share intent). */ -export function createTelepromptDocumentWindow( - windowId: string, - title: string, - text: string, - options: InProcessAppOptions, -): InProcessWindow { - return createInProcessWindow({ - appId: "teleprompt", - windowId, - title, - iconLetter: "Tp", - icon: "file-text", - closeable: true, - actions: options.actions, - baseLayer: new YieldAtRootLayer(new TelepromptLayer(text, title)), - submitFrame: options.submitFrame, - setSurfaceVisible: options.setSurfaceVisible, - removeSurface: options.removeSurface, - onClosed: options.onClosed, - }); -} - -function createFilePickedMenu( - entry: DirectoryEntry, - openDocumentWindow: (title: string, text: string) => void, -): MenuLayer { - return new MenuLayer( - entry.name, - [ - { - label: "View here", - onSelect: (ctx) => { - const text = readTextFile(entry.path); - ctx.stack.pop(); - ctx.stack.push(new TelepromptLayer(text ?? "(could not read file)", entry.name)); - }, - }, - { - label: "Open in new window", - onSelect: (ctx) => { - const text = readTextFile(entry.path); - ctx.stack.pop(); - openDocumentWindow(entry.name, text ?? "(could not read file)"); - }, - }, - ], - { - x: 8, - y: 8, - width: 272, - minHeight: 0, - maxHeight: APP_VIEWPORT.height - 16, - }, - ); -}