diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..e404f61 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,51 @@ +# Project Guidelines + +## Core Principle + +Follow the code style, architectural decisions, and approaches already established in the project. Before making changes, study the surrounding code and configuration. Match the author's style: existing project conventions take precedence over personal preferences. + +## Change Requirements + +- Write clean, clear, and maintainable code. +- Choose the simplest solution that fully addresses the task. +- Do not produce AI slop: avoid boilerplate comments, unnecessary verbosity, redundant checks, wrappers, and abstractions. +- Do not overengineer or generalize prematurely. +- Fix the underlying cause instead of stacking patches or compatibility layers. +- Do not preserve duplicate implementations or compatibility code for behavior that has not shipped. +- Follow the project's established naming, file structure, formatting, and error-handling conventions. +- Whenever the user establishes or clarifies a project code-style rule, immediately record it in `AGENTS.md`. +- Before implementing helper logic or adding an abstraction, always inspect the existing project utilities and reuse an established utility when it fits. +- In multiline ternary expressions, keep `?` and `:` at the end of the preceding line. +- Prefer multiline JSX for nested elements; do not compress parent and child tags onto one line merely to save space. +- Do not use namespace imports (`import * as ...`); use explicit named imports instead. +- Use braces for an `if` statement whenever it has an `else` branch or its body spans multiple lines. +- Do not refactor or reformat code outside the scope of the current task unless necessary. +- Do not add dependencies when the task can reasonably be solved with the existing tools. +- Always ask the user for explicit confirmation before installing a new dependency. +- Preserve existing behavior and public interfaces unless the task explicitly requires changing them. +- After making changes, run the relevant project checks and fix any errors caused by the changes. + +## SolidJS + +- Strictly follow SolidJS's reactive model and idioms. +- Do not impose React approaches or its mental model on SolidJS code. +- Use signals, memos, effects, and stores according to their intended roles in SolidJS, preserving fine-grained reactivity. +- Avoid React patterns such as destructuring reactive props, unnecessary effects, manual state synchronization, and components designed around re-renders. +- Use lifecycle hooks for DOM measurement; do not defer layout work with `queueMicrotask` when the component lifecycle can express the correct timing. +- When a component requires data to render, make the prop required and handle conditional rendering at the caller instead of wrapping the entire component in `Show`. +- Avoid unnecessary JSX fragments; use the existing semantic or layout container when sibling elements share one. +- Before introducing a custom reactive abstraction, check whether the task can be solved more simply with SolidJS primitives and the project's existing patterns. + +## UX + +- Follow the existing Bootstrap and solid-bootstrap visual language; reuse nearby layout and interaction patterns before adding custom styles or components. +- Keep tool interfaces compact: prefer small controls, dense tables, concise action rows, and `mb-2`/`mb-3` spacing over cards, large headings, and excessive whitespace. +- Maximize useful information density: every visible element should support the current task, and labels or explanatory text should not repeat context that is already clear. +- Prefer single-line toolbars for secondary actions and numeric options, and compact inline lists for selectable collections. +- Do not use horizontal scrolling as a layout solution. Reflow or wrap controls, adapt the layout at narrow widths, and remove nonessential information instead. +- Do not use `table-layout: fixed`. Let columns size naturally from their content; percentage widths may be assigned to individual columns when proportions need to be controlled. +- Keep the primary workflow visible and group related controls in one row when practical. Let controls wrap responsively on narrow screens. +- Use modals for focused secondary configuration, not for primary actions or information that belongs on the page. +- Preserve accessibility with explicit labels or accessible names, visible status and error feedback, and keyboard-operable controls. +- Keep tables within the available width and preserve identifying context when results from multiple sources are combined. +- Use Playwright only for complex or high-risk UI scenarios where browser behavior materially needs verification, and only after the interface is complete. Do not run it for routine changes when the implementation and static checks provide sufficient confidence, or after each intermediate UI change. diff --git a/package.json b/package.json index bbda367..85e9a54 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "@codemirror/theme-one-dark": "^6.1.3", "@codemirror/view": "^6.40.0", "@material-design-icons/svg": "^0.14.15", + "@sie-js/ptr89": "^3.0.2", "@solid-primitives/context": "^0.3.2", "@solidjs/router": "^0.15.4", "@suid/types": "^0.8.0", @@ -40,10 +41,12 @@ "axios-cache-interceptor": "^1.12.0", "bootstrap": "^5.3.8", "bootstrap-icons": "^1.13.1", + "browser-fs-access": "^0.38.0", "clsx": "^2.1.1", "date-fns": "^3.6.0", "es-toolkit": "^1.45.1", "highlight.js": "^11.11.1", + "idb-keyval": "^6.3.0", "sass": "^1.98.0", "solid-bootstrap": "^1.0.21", "solid-js": "^1.9.11", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 30f93ef..dd925e2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -35,6 +35,9 @@ importers: '@material-design-icons/svg': specifier: ^0.14.15 version: 0.14.15 + '@sie-js/ptr89': + specifier: ^3.0.2 + version: 3.0.2 '@solid-primitives/context': specifier: ^0.3.2 version: 0.3.2(solid-js@1.9.11) @@ -71,6 +74,9 @@ importers: bootstrap-icons: specifier: ^1.13.1 version: 1.13.1 + browser-fs-access: + specifier: ^0.38.0 + version: 0.38.0 clsx: specifier: ^2.1.1 version: 2.1.1 @@ -83,6 +89,9 @@ importers: highlight.js: specifier: ^11.11.1 version: 11.11.1 + idb-keyval: + specifier: ^6.3.0 + version: 6.3.0 sass: specifier: ^1.98.0 version: 1.98.0 @@ -632,6 +641,9 @@ packages: cpu: [x64] os: [win32] + '@sie-js/ptr89@3.0.2': + resolution: {integrity: sha512-uRaVK4w3dv7A/uhbxqfnpVsYA1IEHO7Q4C6Reict8auWluhkSONvGW5nI5AE+fnQYiVKS8vuws+tDeQTZmhykg==} + '@solid-devtools/debugger@0.28.1': resolution: {integrity: sha512-6qIUI6VYkXoRnL8oF5bvh2KgH71qlJ18hNw/mwSyY6v48eb80ZR48/5PDXufUa3q+MBSuYa1uqTMwLewpay9eg==} peerDependencies: @@ -797,6 +809,9 @@ packages: peerDependencies: '@popperjs/core': ^2.11.8 + browser-fs-access@0.38.0: + resolution: {integrity: sha512-JveqW2w6pEZqFEEfMgCszXzYpE89dG+nPsmOdcs741mFFAROeL+iqjGEpR07RI+s0YY0EFr+4KnOoACprJTpOw==} + browserslist@4.28.1: resolution: {integrity: sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==} engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} @@ -1009,6 +1024,9 @@ packages: http-vary@1.0.3: resolution: {integrity: sha512-sx7Y8YTqF3o0mFJJvF66n8dbaE8v3liV1RgCz46XP5xK7dnzyZHvwMWRA115q5kjbCPBV65/nOMlgW54WLyiag==} + idb-keyval@6.3.0: + resolution: {integrity: sha512-um+2dgAWmYsu615EXpWVwSmapJhON0G43t3Ka/EVaohzPQXSMqKEqeDK/oIW3Ow+BXaF2PvSc+oBTFp793A5Ow==} + immutable@5.1.5: resolution: {integrity: sha512-t7xcm2siw+hlUM68I+UEOK+z84RzmN59as9DZ7P1l0994DKUWV7UXBMQZVxaoMSRQ+PBZbHCOoBt7a2wxOMt+A==} @@ -1705,6 +1723,8 @@ snapshots: '@rollup/rollup-win32-x64-msvc@4.59.0': optional: true + '@sie-js/ptr89@3.0.2': {} + '@solid-devtools/debugger@0.28.1(solid-js@1.9.11)': dependencies: '@nothing-but/utils': 0.17.0 @@ -1918,6 +1938,8 @@ snapshots: dependencies: '@popperjs/core': 2.11.8 + browser-fs-access@0.38.0: {} + browserslist@4.28.1: dependencies: baseline-browser-mapping: 2.10.7 @@ -2132,6 +2154,8 @@ snapshots: http-vary@1.0.3: {} + idb-keyval@6.3.0: {} + immutable@5.1.5: {} is-extglob@2.1.1: diff --git a/src/components/Layout/Root.tsx b/src/components/Layout/Root.tsx index 6723398..95dd880 100644 --- a/src/components/Layout/Root.tsx +++ b/src/components/Layout/Root.tsx @@ -8,6 +8,7 @@ const SwilibCheckPage = lazy(() => import("@/pages/SwilibCheck/SwilibCheckPage") const SwilibMergePage = lazy(() => import("@/pages/SwilibMerge/SwilibMergePage")); const SwilibMergeEditorPage = lazy(() => import("@/pages/SwilibMerge/SwilibMergeEditorPage")); const ReFilesPage = lazy(() => import("@/pages/ReFiles/ReFilesPage")); +const Ptr89Page = lazy(() => import("@/pages/Ptr89/Ptr89Page")); export const Root: Component = () => { const showAppError = (err: any) => { @@ -24,6 +25,7 @@ export const Root: Component = () => { + {/* Legacy routes */} diff --git a/src/components/Layout/Sidebar/Sidebar.tsx b/src/components/Layout/Sidebar/Sidebar.tsx index 56b2ee9..5e166f7 100644 --- a/src/components/Layout/Sidebar/Sidebar.tsx +++ b/src/components/Layout/Sidebar/Sidebar.tsx @@ -26,7 +26,7 @@ export const Sidebar: Component = (props) => { { title: "Reverse engineering", links: [ - { label: "Patterns finder", href: "/re/ptr89", icon: "bi bi-search", disabled: true }, + { label: "Patterns finder", href: "/re/ptr89", icon: "bi bi-search" }, { label: "Download symbols", href: "/re/symbols", icon: "bi bi-download" } ] }, diff --git a/src/index.scss b/src/index.scss index 93b7ab1..902a039 100644 --- a/src/index.scss +++ b/src/index.scss @@ -58,6 +58,10 @@ body { overflow-y: scroll; } +.form-control[size] { + width: auto; +} + .table-sticky-header { thead tr { position: sticky; diff --git a/src/pages/Ptr89/FolderSelect.tsx b/src/pages/Ptr89/FolderSelect.tsx new file mode 100644 index 0000000..48187f8 --- /dev/null +++ b/src/pages/Ptr89/FolderSelect.tsx @@ -0,0 +1,63 @@ +import { type Component, createSignal, For, Show } from "solid-js"; +import { Form } from "solid-bootstrap"; + +interface FolderSelectProps { + id?: string; + class?: string; + value: string; + folders: string[]; + onChange: (folder: string) => void; +} + +export const FolderSelect: Component = (props) => { + const [adding, setAdding] = createSignal(false); + const showInput = () => adding() || Boolean(props.value && !props.folders.includes(props.value)); + + const handleSelect = (select: HTMLSelectElement) => { + if (select.selectedOptions[0]?.dataset.action === "add") { + props.onChange(""); + setAdding(true); + } else { + setAdding(false); + props.onChange(select.value); + } + }; + + return ( + handleSelect(e.currentTarget)} + > + + {(folder) => } + + + } + > + props.onChange(e.currentTarget.value)} + onBlur={() => setAdding(false)} + onKeyDown={(e) => { + if (e.key === "Escape") { + props.onChange(""); + setAdding(false); + } + }} + /> + + ); +}; diff --git a/src/pages/Ptr89/FullflashAddModal.tsx b/src/pages/Ptr89/FullflashAddModal.tsx new file mode 100644 index 0000000..7c62ecc --- /dev/null +++ b/src/pages/Ptr89/FullflashAddModal.tsx @@ -0,0 +1,94 @@ +import { type Component, createMemo, createSignal, Show } from "solid-js"; +import { createStore } from "solid-js/store"; +import { Button, Modal, Spinner } from "solid-bootstrap"; +import { type FileWithHandle } from "browser-fs-access"; +import { FolderSelect } from "@/pages/Ptr89/FolderSelect"; +import type { Fullflash } from "@/pages/Ptr89/store/ptr89State"; +import { FullflashTable } from "@/pages/Ptr89/FullflashTable"; + +interface FullflashAddModalProps { + files: FileWithHandle[]; + folders: string[]; + onAdd: (fullflashes: Fullflash[], files: FileWithHandle[]) => Promise; + onHide: () => void; +} + +export const FullflashAddModal: Component = (props) => { + const [show, setShow] = createSignal(true); + const [saving, setSaving] = createSignal(false); + const [error, setError] = createSignal(); + const [commonFolder, setCommonFolder] = createSignal(""); + const [fullflashes, setFullflashes] = createStore(props.files.map((file) => ({ + id: crypto.randomUUID(), + name: file.name.replace(/\.[^.]+$/, "") || file.name, + folder: "", + arch: "arm", + }))); + const folders = createMemo(() => [...new Set([ + ...props.folders, + ...fullflashes.map((fullflash) => fullflash.folder), + ].filter(Boolean))].sort()); + const handleCommonFolderChange = (folder: string) => { + const previousFolder = commonFolder(); + setCommonFolder(folder); + setFullflashes(fullflashes.map((fullflash) => { + if (fullflash.folder && fullflash.folder !== previousFolder) + return fullflash; + return { ...fullflash, folder }; + })); + }; + + const handleAdd = async () => { + setSaving(true); + setError(undefined); + + try { + await props.onAdd(fullflashes, props.files); + setShow(false); + } catch (err) { + setError(err instanceof Error ? err.message : String(err)); + } finally { + setSaving(false); + } + }; + + return ( + !saving() && setShow(false)} onExited={props.onHide}> + + Add fullflashes + + +
+ + +
+ + + + + +
+ + + + +
+ ); +}; diff --git a/src/pages/Ptr89/FullflashSettingsModal.tsx b/src/pages/Ptr89/FullflashSettingsModal.tsx new file mode 100644 index 0000000..a910176 --- /dev/null +++ b/src/pages/Ptr89/FullflashSettingsModal.tsx @@ -0,0 +1,75 @@ +import { type Component, createMemo, createSignal, Show } from "solid-js"; +import { createStore } from "solid-js/store"; +import { Modal } from "solid-bootstrap"; +import type { Fullflash } from "@/pages/Ptr89/store/ptr89State"; +import { FullflashTable } from "@/pages/Ptr89/FullflashTable"; + +interface FullflashSettingsModalProps { + fullflashes: Fullflash[]; + folders: string[]; + onSave: (fullflashes: Fullflash[]) => void; + onRemove: (id: string) => Promise; + onHide: () => void; +} + +export const FullflashSettingsModal: Component = (props) => { + const [show, setShow] = createSignal(true); + const [saving, setSaving] = createSignal(false); + const [error, setError] = createSignal(); + const [fullflashes, setFullflashes] = createStore(props.fullflashes.map((fullflash) => ({ ...fullflash }))); + const folders = createMemo(() => [...new Set([ + ...props.folders, + ...fullflashes.map((fullflash) => fullflash.folder), + ].filter(Boolean))].sort()); + + const handleClose = () => { + if (saving()) + return; + + setError(undefined); + + try { + props.onSave(fullflashes); + setShow(false); + } catch (err) { + setError(err instanceof Error ? err.message : String(err)); + } + }; + + const handleRemove = async (id: string) => { + if (saving()) + return; + + setSaving(true); + setError(undefined); + try { + await props.onRemove(id); + setFullflashes(fullflashes.filter((fullflash) => fullflash.id !== id)); + } catch (err) { + setError(err instanceof Error ? err.message : String(err)); + } finally { + setSaving(false); + } + }; + + return ( + + + Fullflashes list + + + + + + + + + + ); +}; diff --git a/src/pages/Ptr89/FullflashTable.tsx b/src/pages/Ptr89/FullflashTable.tsx new file mode 100644 index 0000000..52705ce --- /dev/null +++ b/src/pages/Ptr89/FullflashTable.tsx @@ -0,0 +1,99 @@ +import { type Component, For, Show } from "solid-js"; +import { type SetStoreFunction } from "solid-js/store"; +import { Button, Form } from "solid-bootstrap"; +import { FolderSelect } from "@/pages/Ptr89/FolderSelect"; +import type { Fullflash } from "@/pages/Ptr89/store/ptr89State"; + +interface FullflashTableProps { + fullflashes: Fullflash[]; + setFullflashes: SetStoreFunction; + folders: string[]; + onRemove?: (id: string) => void; + removeDisabled?: boolean; +} + +export const FullflashTable: Component = (props) => ( + + + + + + + + + + + + + + + + + + + {(fullflash, index) => + + + + + + + + + + } + +
NameFolderArchBase
+ props.setFullflashes(index(), "name", e.currentTarget.value)} + /> + + props.setFullflashes(index(), "folder", folder)} + /> + + props.setFullflashes(index(), "arch", e.currentTarget.value as Fullflash["arch"])} + > + + + + + { + const value = e.currentTarget.value; + if (/^[0-9A-F]{0,8}$/i.test(value)) { + props.setFullflashes(index(), "base", value ? Number.parseInt(value, 16) : undefined); + } else { + e.currentTarget.value = fullflash.base?.toString(16).toUpperCase() ?? ""; + } + }} + /> + + +
+); diff --git a/src/pages/Ptr89/Ptr89Page.tsx b/src/pages/Ptr89/Ptr89Page.tsx new file mode 100644 index 0000000..10d7383 --- /dev/null +++ b/src/pages/Ptr89/Ptr89Page.tsx @@ -0,0 +1,496 @@ +import { type Component, createMemo, createResource, createSignal, For, onCleanup, onMount, Show } from "solid-js"; +import { Button, Form, Nav, Spinner } from "solid-bootstrap"; +import { fileOpen, type FileWithHandle } from "browser-fs-access"; +import type { Ptr89WorkerPayload, Ptr89WorkerResponse } from "@/pages/Ptr89/ptr89.worker"; +import { FullflashAddModal } from "@/pages/Ptr89/FullflashAddModal"; +import { FullflashSettingsModal } from "@/pages/Ptr89/FullflashSettingsModal"; +import { + SearchResults, + XRefResults, +} from "@/pages/Ptr89/Ptr89Results"; +import { + type Fullflash, + type FullflashMatch, + type SearchResult, + type XRefResult, + usePtr89State, +} from "@/pages/Ptr89/store/ptr89State"; + +type ActiveTab = "search" | "xrefs"; + +const parseAddress = (value: string) => Number(`0x${value.trim().replace(/^0x/i, "")}`); + +const getErrorMessage = (error: unknown) => error instanceof Error ? error.message : String(error); + +const resizePatternInput = (input: HTMLElement) => { + input.style.height = "auto"; + input.style.height = `${input.scrollHeight}px`; +}; + +const Ptr89Page: Component = () => { + const ptr89Worker = new Worker(new URL("./ptr89.worker.ts", import.meta.url), { type: "module" }); + let patternInput!: HTMLTextAreaElement; + const [ptr89State, ptr89] = usePtr89State(); + const [fileStorage] = createResource(ptr89.loadFiles); + const [pendingFiles, setPendingFiles] = createSignal(); + const [settingsOpen, setSettingsOpen] = createSignal(false); + const [activeTab, setActiveTab] = createSignal("search"); + const [searchResult, setSearchResult] = createSignal(); + const [xrefResult, setXrefResult] = createSignal(); + const [error, setError] = createSignal(); + const [adding, setAdding] = createSignal(false); + const [formatting, setFormatting] = createSignal(false); + const [searching, setSearching] = createSignal(false); + const [progress, setProgress] = createSignal(); + const folders = createMemo(() => [...new Set( + ptr89State.fullflashes.map((fullflash) => fullflash.folder).filter(Boolean) + )].sort()); + const selectedFolder = createMemo(() => folders().includes(ptr89State.folder) ? ptr89State.folder : ""); + const filteredFullflashes = createMemo(() => ptr89State.fullflashes.filter((fullflash) => + !selectedFolder() || fullflash.folder === selectedFolder() + )); + const selectedFullflashes = createMemo(() => + filteredFullflashes().filter((fullflash) => !ptr89State.disabledFullflashIds.includes(fullflash.id)) + ); + const selectedXrefFullflash = createMemo(() => { + const availableFullflashes = filteredFullflashes(); + return availableFullflashes.find((fullflash) => fullflash.id === ptr89State.xrefFullflashId) ?? + availableFullflashes[0]; + }); + onMount(() => resizePatternInput(patternInput)); + onCleanup(() => { + ptr89Worker.terminate(); + }); + + const runWorker = (payload: Ptr89WorkerPayload) => new Promise((resolve, reject) => { + ptr89Worker.onmessage = (event: MessageEvent) => resolve(event.data); + ptr89Worker.onerror = (event) => reject(new Error(event.message)); + ptr89Worker.postMessage(payload); + }); + + const handleAdd = async () => { + setAdding(true); + setError(undefined); + + try { + const files = await fileOpen({ + description: "Fullflash", + id: "ptr89-fullflash", + multiple: true, + }); + setPendingFiles(files); + } catch (err) { + if (!(err instanceof DOMException && err.name === "AbortError")) + setError(getErrorMessage(err)); + } finally { + setAdding(false); + } + }; + + const handleSaveSettings = (settings: Fullflash[]) => { + if (ptr89.updateFullflashes(settings)) { + setSearchResult(undefined); + setXrefResult(undefined); + } + }; + + const handleRemove = async (id: string) => { + await ptr89.removeFullflash(id); + setSearchResult(undefined); + setXrefResult(undefined); + }; + + const handleFullflashToggle = (id: string, enabled: boolean) => { + ptr89.setFullflashEnabled(id, enabled); + }; + + const handlePrettify = async () => { + if (formatting() || searching()) + return; + + setFormatting(true); + setError(undefined); + try { + const response = await runWorker({ operation: "prettify", pattern: ptr89State.pattern }); + if ("error" in response) + throw new Error(response.error); + if (!("pattern" in response)) + throw new Error("Unexpected worker response."); + ptr89.setState("pattern", response.pattern); + resizePatternInput(patternInput); + } catch (err) { + setError(getErrorMessage(err)); + } finally { + setFormatting(false); + } + }; + + const handleSearch = async (e: SubmitEvent) => { + e.preventDefault(); + if (searching() || formatting() || fileStorage.loading) + return; + + const searchFullflashes = selectedFullflashes(); + if (!searchFullflashes.length) { + setError("Select at least one fullflash first."); + return; + } + + setSearching(true); + setError(undefined); + setSearchResult(undefined); + const startedAt = performance.now(); + + try { + await ptr89.requestFilePermissions(searchFullflashes); + const foundMatches: FullflashMatch[] = []; + const searchIssues: SearchResult["issues"] = []; + let resultType: SearchResult["type"] | undefined; + + for (let i = 0; i < searchFullflashes.length; i++) { + const fullflash = searchFullflashes[i]; + setProgress(`Searching ${i + 1}/${searchFullflashes.length}: ${fullflash.name}`); + + try { + const file = await ptr89.readFile(fullflash); + const response = await runWorker({ + operation: "find", + file, + options: { arch: fullflash.arch, base: fullflash.base }, + pattern: ptr89State.pattern.trim(), + limit: ptr89State.limit, + align: ptr89State.align, + }); + if ("error" in response) + throw new Error(response.error); + if (!("matches" in response)) + throw new Error("Unexpected worker response."); + + resultType ??= response.type; + foundMatches.push(...response.matches.map((match) => ({ + ...match, + fullflashId: fullflash.id, + fullflashName: fullflash.name, + arch: fullflash.arch, + }))); + } catch (err) { + searchIssues.push({ fullflashName: fullflash.name, message: getErrorMessage(err) }); + } + } + if (!resultType) + throw new Error(searchIssues.map((issue) => `${issue.fullflashName}: ${issue.message}`).join(" ")); + + setSearchResult({ + matches: foundMatches, + issues: searchIssues, + type: resultType, + duration: performance.now() - startedAt, + }); + } catch (err) { + setError(getErrorMessage(err)); + } finally { + setProgress(undefined); + setSearching(false); + } + }; + + const handleXrefSearch = async (e: SubmitEvent) => { + e.preventDefault(); + if (searching() || formatting() || fileStorage.loading) + return; + + const fullflash = selectedXrefFullflash(); + if (!fullflash) { + setError("Select a fullflash first."); + return; + } + + setSearching(true); + setError(undefined); + setXrefResult(undefined); + const startedAt = performance.now(); + + try { + const address = parseAddress(ptr89State.xrefAddress); + await ptr89.requestFilePermissions([fullflash]); + + setProgress(`Searching ${fullflash.name}`); + const file = await ptr89.readFile(fullflash); + const response = await runWorker({ + operation: "findXRefs", + file, + options: { arch: fullflash.arch, base: fullflash.base }, + address, + limit: ptr89State.limit, + }); + if ("error" in response) + throw new Error(response.error); + if (!("xrefs" in response)) + throw new Error("Unexpected worker response."); + + setXrefResult({ + xrefs: response.xrefs, + duration: performance.now() - startedAt, + }); + } catch (err) { + setError(getErrorMessage(err)); + } finally { + setProgress(undefined); + setSearching(false); + } + }; + + return ( + <> + +
+ + + 0}> +
+ + { + ptr89.setState("folder", e.currentTarget.value); + setXrefResult(undefined); + }} + > + + {(folder) => } + +
+
+ +
+ + ptr89.setState("align", Number(e.currentTarget.value))} + /> +
+
+
+ + ptr89.setState("limit", Number(e.currentTarget.value))} + /> +
+ + + +
+ + {(files) => + setPendingFiles(undefined)} + /> + } + + setSettingsOpen(false)} + /> + + + + + Loading... + + + + + + 0} + fallback={
No fullflashes added.
} + > +
+ {(fullflash) => + + } +
+
+ + + + +
{progress()}
+
+ + + + + {(result) => + + } + {(result) => + + } + + ); +}; + +export default Ptr89Page; diff --git a/src/pages/Ptr89/Ptr89Results.tsx b/src/pages/Ptr89/Ptr89Results.tsx new file mode 100644 index 0000000..feff98b --- /dev/null +++ b/src/pages/Ptr89/Ptr89Results.tsx @@ -0,0 +1,288 @@ +import { type Component, createMemo, createSignal, For, Show } from "solid-js"; +import { Form } from "solid-bootstrap"; +import { + type Ptr89Arch, + type Ptr89SearchType, + type Ptr89XRefType, +} from "@sie-js/ptr89"; +import { formatAddress } from "@/utils/format"; +import { + type AddressSpace, + type FullflashMatch, + type SearchResult, + type XRefResult, + usePtr89State, +} from "@/pages/Ptr89/store/ptr89State"; + +interface SearchResultsProps { + result: SearchResult; +} + +interface XRefResultsProps { + result: XRefResult; +} + +const formatAddressBytes = (value: number) => [0, 8, 16, 24] + .map((shift) => ((value >>> shift) & 0xFF).toString(16).toUpperCase().padStart(2, "0")) + .join(" "); + +const formatC166Pointer = (value: number, addressSpace: AddressSpace) => { + const pageSize = addressSpace === "data" ? 0x4000 : 0x10000; + const pageWidth = addressSpace === "data" ? 4 : 2; + const offset = value % pageSize; + const page = Math.floor(value / pageSize); + return { + pointer: `${page.toString(16).toUpperCase().padStart(pageWidth, "0")}:${offset.toString(16).toUpperCase().padStart(4, "0")}`, + bytes: formatAddressBytes((page << 16) | offset), + }; +}; + +const AddressCell: Component<{ address: number; showBytes: boolean; fullflashName?: string }> = (props) => ( + + + {props.fullflashName} + +
{formatAddress(props.address)}
+ + {formatAddressBytes(props.address)} + + +); + +const C166PointerCell: Component<{ + address: number; + arch: Ptr89Arch; + addressSpace: AddressSpace; + showBytes: boolean; +}> = (props) => { + const pointer = createMemo(() => formatC166Pointer(props.address, props.addressSpace)); + + return ( + + +
{pointer().pointer}
+ + {pointer().bytes} + +
+ + ); +}; + +const BytesCell: Component<{ bytes?: string }> = (props) => { + const [expanded, setExpanded] = createSignal(false); + const bytes = createMemo(() => props.bytes?.replace(/\s/g, "").match(/.{1,2}/g) ?? []); + const visibleBytes = createMemo(() => (expanded() ? bytes() : bytes().slice(0, 16)).join(" ")); + + return ( + + 0} fallback="-"> + {visibleBytes()} + 16}> + … + + + + + ); +}; + +const formatDuration = (duration: number) => duration < 1000 ? + `${Math.round(duration)} ms` : + `${(duration / 1000).toFixed(2)} s`; + +const formatResultType = (type: Ptr89SearchType, count: number) => { + if (count === 1) + return type; + if (type === "address") + return "addresses"; + return type === "branch" ? "branches" : `${type}s`; +}; + +const resultColumnNames: Record = { + address: "Address", + pointer: "Pointer", + reference: "Address", + branch: "Function", +}; + +const xrefTypeNames: Record = { + pointer: "Pointer", + reference: "Address", + branch: "Branch", +}; + +export const SearchResults: Component = (props) => { + const [ptr89State, ptr89] = usePtr89State(); + const matchGroups = createMemo(() => { + const groups: FullflashMatch[][] = []; + for (const match of props.result.matches) { + const lastGroup = groups.at(-1); + if (lastGroup?.[0].fullflashId === match.fullflashId) { + lastGroup.push(match); + } else { + groups.push([match]); + } + } + return groups; + }); + const hasC166Matches = createMemo(() => props.result.matches.some((match) => match.arch === "c166")); + const resultColumnName = () => hasC166Matches() ? "Physical" : resultColumnNames[props.result.type]; + const resultSummary = () => `Found ${props.result.matches.length} ${formatResultType(props.result.type, props.result.matches.length)} in ${formatDuration(props.result.duration)}`; + + return ( +
+ 0}> + + +
+ {resultSummary()} +
+ 0}> +
+ ptr89.setState("showAddressBytes", e.currentTarget.checked)} + /> + + Address space: + ptr89.setState("addressSpace", "data")} + /> + ptr89.setState("addressSpace", "code")} + /> + +
+ + + + + + + + + + + + + + + {(group) => + + {(match, index) => + + + + {match.offset === undefined ? + : + + } + + + + + + + + } + + } +
+ File + + {resultColumnName()} + + Offset + + + Pointer + + + Bytes +
+ {index() === 0 ? match.fullflashName : ""} + -
+
+
+ ); +}; + +export const XRefResults: Component = (props) => { + const resultSummary = () => `Found ${props.result.xrefs.length} ${props.result.xrefs.length === 1 ? "x-reference" : "x-references"} in ${formatDuration(props.result.duration)}`; + + return ( +
+
+ {resultSummary()} +
+ 0}> + + + + + + + + + + {(xref) => + + + + + + } + +
+ Type + + X-Reference + + Offset +
{xrefTypeNames[xref.type]}{formatAddress(xref.xref)}{formatAddress(xref.offset)}
+
+
+ ); +}; diff --git a/src/pages/Ptr89/ptr89.worker.ts b/src/pages/Ptr89/ptr89.worker.ts new file mode 100644 index 0000000..92fc0e5 --- /dev/null +++ b/src/pages/Ptr89/ptr89.worker.ts @@ -0,0 +1,60 @@ +import { + type Ptr89OpenOptions, + type Ptr89SearchResult, + type Ptr89SearchType, + type Ptr89XRef, + prettify, + Ptr89, +} from "@sie-js/ptr89"; + +export type Ptr89WorkerPayload = { + operation: "find"; + file: File; + options: Ptr89OpenOptions; + pattern: string; + limit: number; + align: number; +} | { + operation: "findXRefs"; + file: File; + options: Ptr89OpenOptions; + address: number; + limit: number; +} | { + operation: "prettify"; + pattern: string; +}; + +export type Ptr89WorkerResponse = + | { matches: Ptr89SearchResult[]; type: Ptr89SearchType } + | { xrefs: Ptr89XRef[] } + | { pattern: string } + | { error: string }; + +const worker = self as unknown as Worker; +const ptr89 = new Ptr89(); + +worker.addEventListener("message", async (event: MessageEvent) => { + const request = event.data; + let response: Ptr89WorkerResponse; + + try { + if (request.operation === "prettify") { + response = { pattern: await prettify(request.pattern) }; + } else { + await ptr89.openFile(request.file, request.options); + if (request.operation === "find") { + const search = ptr89.find(request.pattern, request.limit, request.align); + response = { matches: search.results, type: search.type }; + } else { + response = { xrefs: ptr89.findXRefs(request.address, request.limit) }; + } + } + } catch (error) { + response = { error: error instanceof Error ? error.message : String(error) }; + } finally { + ptr89.close(); + } + + worker.postMessage(response); +}); diff --git a/src/pages/Ptr89/store/ptr89State.ts b/src/pages/Ptr89/store/ptr89State.ts new file mode 100644 index 0000000..e4b06fd --- /dev/null +++ b/src/pages/Ptr89/store/ptr89State.ts @@ -0,0 +1,107 @@ +import type { FileWithHandle } from "browser-fs-access"; +import type { + Ptr89Arch, + Ptr89SearchResult, + Ptr89SearchType, + Ptr89XRef, +} from "@sie-js/ptr89"; +import { createStoreWithApi } from "@/utils/createStoreWithApi"; +import { + loadPersistentFiles, + readPersistentFile, + removePersistentFile, + requestPersistentFilePermissions, + savePersistentFile, +} from "@/utils/persistentFiles"; + +export type AddressSpace = "data" | "code"; + +export interface Fullflash { + id: string; + name: string; + folder: string; + arch: Ptr89Arch; + base?: number; +} + +export interface FullflashMatch extends Ptr89SearchResult { + fullflashId: string; + fullflashName: string; + arch: Ptr89Arch; +} + +export interface SearchResult { + matches: FullflashMatch[]; + issues: Array<{ fullflashName: string; message: string }>; + type: Ptr89SearchType; + duration: number; +} + +export interface XRefResult { + xrefs: Ptr89XRef[]; + duration: number; +} + +export const usePtr89State = createStoreWithApi( + () => ({ + fullflashes: [] as Fullflash[], + disabledFullflashIds: [] as string[], + folder: "", + pattern: "", + align: 1, + limit: 10, + showAddressBytes: false, + addressSpace: "data" as AddressSpace, + xrefAddress: "", + xrefFullflashId: "", + }), + (state, setState) => ({ + setState, + loadFiles: loadPersistentFiles, + readFile(fullflash: Fullflash) { + return readPersistentFile(fullflash.id); + }, + requestFilePermissions(fullflashes: Fullflash[]) { + return requestPersistentFilePermissions(fullflashes.map((fullflash) => fullflash.id)); + }, + async addFullflashes(fullflashes: Fullflash[], files: FileWithHandle[]) { + const savedIds: string[] = []; + try { + for (let i = 0; i < fullflashes.length; i++) { + await savePersistentFile(fullflashes[i].id, files[i]); + savedIds.push(fullflashes[i].id); + } + } catch (error) { + await Promise.all(savedIds.map(removePersistentFile)); + throw error; + } + setState("fullflashes", (saved) => [...saved, ...fullflashes]); + }, + updateFullflashes(fullflashes: Fullflash[]) { + const savedFullflashes = new Map(state.fullflashes.map((fullflash) => [fullflash.id, fullflash])); + const changed = fullflashes.some((fullflash) => { + const saved = savedFullflashes.get(fullflash.id); + return !saved || + saved.name !== fullflash.name || + saved.arch !== fullflash.arch || + saved.base !== fullflash.base || + saved.folder !== fullflash.folder; + }); + if (changed) + setState("fullflashes", fullflashes); + return changed; + }, + async removeFullflash(id: string) { + await removePersistentFile(id); + setState("fullflashes", (fullflashes) => fullflashes.filter((fullflash) => fullflash.id !== id)); + setState("disabledFullflashIds", (ids) => ids.filter((disabledId) => disabledId !== id)); + }, + setFullflashEnabled(id: string, enabled: boolean) { + setState("disabledFullflashIds", (ids) => enabled ? + ids.filter((disabledId) => disabledId !== id) : + [...ids, id] + ); + }, + }), + { persist: { name: "ptr89", debounce: 250 } } +); diff --git a/src/utils/createStoreWithApi.ts b/src/utils/createStoreWithApi.ts index 41e5201..ca49f5c 100644 --- a/src/utils/createStoreWithApi.ts +++ b/src/utils/createStoreWithApi.ts @@ -12,9 +12,9 @@ export function createStoreWithApi( options?: CreateStoreWithApiOptions ): () => [store: S, api: A] { const [store, setStore] = createRoot(() => { - return options?.persist - ? makePersistedStore(createStore(initialData()), options.persist) - : createStore(initialData()); + return options?.persist ? + makePersistedStore(createStore(initialData()), options.persist) : + createStore(initialData()); }); const api = createApi(store, setStore); return () => [store, api]; diff --git a/src/utils/makePersistedStore.ts b/src/utils/makePersistedStore.ts index 99d08ce..671fe82 100644 --- a/src/utils/makePersistedStore.ts +++ b/src/utils/makePersistedStore.ts @@ -36,14 +36,11 @@ export function makePersistedStore(store: [Store, SetStoreFunction], op const storedValue = skipLoad ? null : storage.getItem(name); if (storedValue !== null) { const parsed = deserialize(storedValue) as PersistentStoreInternal; - if (parsed != null && parsed.version !== null) { - const typedState = parsed.state as T; - if (parsed.version !== version) { - parsed.state = migrate(typedState, parsed.version); - parsed.version = version; - } - parsed.state = merge(typedState, unwrap(store[0])); - store[1](reconcile(typedState)); + if (parsed != null && typeof parsed.version === "number") { + const persistedState = parsed.version === version ? + parsed.state as T : + migrate(parsed.state as T, parsed.version); + store[1](reconcile(merge(persistedState, unwrap(store[0])))); } } diff --git a/src/utils/persistentFiles.ts b/src/utils/persistentFiles.ts new file mode 100644 index 0000000..4c88ca9 --- /dev/null +++ b/src/utils/persistentFiles.ts @@ -0,0 +1,70 @@ +import { createStore, del, entries, get, set } from "idb-keyval"; +import type { FileSystemHandle, FileWithHandle } from "browser-fs-access"; + +const storage = createStore("web-dev-tools-files", "files"); +type FileHandle = NonNullable & FileSystemHandle; +type StoredFile = File | FileHandle; + +const fileHandles = new Map(); + +const isFileHandle = (file: StoredFile): file is FileHandle => "getFile" in file; + +const readFileHandle = async (handle: FileHandle) => { + if (await handle.queryPermission({ mode: "read" }) !== "granted") + throw new Error(`Access to ${handle.name} was not granted.`); + return handle.getFile(); +}; + +export const loadPersistentFiles = async (): Promise => { + fileHandles.clear(); + for (const [id, file] of await entries(storage)) { + if (isFileHandle(file)) + fileHandles.set(id, file); + } +}; + +export const savePersistentFile = async (id: string, file: FileWithHandle): Promise => { + if (file.handle) { + const handle = file.handle as FileHandle; + try { + await set(id, handle, storage); + fileHandles.set(id, handle); + return; + } catch { + // Fall back to storing the file when the browser cannot clone the handle. + } + } + + await set(id, file, storage); + fileHandles.delete(id); +}; + +export const requestPersistentFilePermissions = async (ids: string[]): Promise => { + const handles = ids.map((id) => fileHandles.get(id)).filter((handle) => handle !== undefined); + const permissions = await Promise.all(handles.map((handle) => handle.requestPermission({ mode: "read" }))); + + for (let i = 0; i < permissions.length; i++) { + if (permissions[i] !== "granted") + throw new Error(`Access to ${handles[i].name} was not granted.`); + } +}; + +export const readPersistentFile = async (id: string): Promise => { + const cachedHandle = fileHandles.get(id); + if (cachedHandle) + return readFileHandle(cachedHandle); + + const file = await get(id, storage); + if (!file) + throw new Error("File was not found."); + if (isFileHandle(file)) { + fileHandles.set(id, file); + return readFileHandle(file); + } + return file; +}; + +export const removePersistentFile = async (id: string): Promise => { + await del(id, storage); + fileHandles.delete(id); +}; diff --git a/vite.config.ts b/vite.config.ts index 848e81c..3ecbb83 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -89,7 +89,7 @@ export default defineConfig({ }), ], optimizeDeps: { - exclude: [], + exclude: ['@sie-js/ptr89'], }, server: { port: 3000,