From 26e13d40bcbf1bef15062a0a47acb886a686e16a Mon Sep 17 00:00:00 2001 From: Aviral Shukla Date: Mon, 30 Nov 2026 15:10:49 +0530 Subject: [PATCH 1/4] feat: release v0.3.0 live wallpapers --- .github/workflows/check.yml | 36 +++++++++ CHANGELOG.md | 16 ++++ README.md | 41 +++++++--- bun.lock | 2 +- dist/gui-experimental.cjs | 44 ++++++++--- package.json | 7 +- script/check-package.ts | 2 +- script/check-styles.ts | 152 ++++++++++++++++++++++++++++++++++-- src/catalog.ts | 67 ++++++++++++++-- src/contract.ts | 11 ++- src/gui.tsx | 32 ++++++-- src/i18n/en.ts | 21 +++-- src/image.ts | 49 ++++++++---- src/live-icon.tsx | 7 ++ src/media-server.test.ts | 141 +++++++++++++++++++++++++++++++++ src/media-server.ts | 76 ++++++++++++++++++ src/media.ts | 117 +++++++++++++++++++++++++++ src/model.test.ts | 35 ++++++++- src/model.ts | 23 ++++-- src/picker.tsx | 9 ++- src/preferences.test.ts | 11 +++ src/preview.tsx | 37 +++++++++ src/settings.css | 47 ++++++++++- src/settings.tsx | 58 ++++++++++---- src/style.ts | 28 +++++-- src/thumbnail.tsx | 11 ++- 26 files changed, 972 insertions(+), 108 deletions(-) create mode 100644 .github/workflows/check.yml create mode 100644 CHANGELOG.md create mode 100644 src/live-icon.tsx create mode 100644 src/media-server.test.ts create mode 100644 src/media-server.ts create mode 100644 src/media.ts create mode 100644 src/preview.tsx diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml new file mode 100644 index 0000000..41a0ca1 --- /dev/null +++ b/.github/workflows/check.yml @@ -0,0 +1,36 @@ +name: Check plugin + +on: + pull_request: + branches: [main] + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: check-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + check: + runs-on: ubuntu-latest + timeout-minutes: 10 + env: + CHROME_BIN: google-chrome + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: "24" + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: "1.4.4" + - run: bun install --frozen-lockfile --ignore-scripts + - run: bun run check + - run: git diff --exit-code -- dist/gui-experimental.cjs + - run: node --test .github/scripts/owner-approval.test.cjs diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..e62d4d0 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,16 @@ +# Changelog + +## 0.3.0 + +- Add muted, looping MP4 and WebM wallpapers, animated GIF and APNG uploads, and self-contained HTML wallpapers. +- Add Static and Live gallery filters, live indicators, and hover or keyboard-focus previews. +- Keep gallery thumbnails still until previewed. Support companion poster images for HTML and video wallpapers. +- Serve video and HTML from a token-protected loopback endpoint with video byte-range support. Images and HTML retain the 8 MiB limit; videos allow up to 256 MiB. +- Sandbox HTML scripts and block external asset loading and fetch requests. Only use trusted HTML; the sandbox is not a network firewall. +- Include live wallpapers in slideshow order. Video and HTML switch instantly; fades remain available between images. +- Add compatibility with OpenCode 2.4.x from 2.4.3. +- Preserve existing uploaded wallpapers, selections, and appearance preferences. + +## 0.2.0 + +- Add wallpaper slideshows with configurable display time and image fades. diff --git a/README.md b/README.md index 4c96ea6..1d1afe0 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ # OpenCode Backdrop -

Use your own wallpapers in OpenCode Desktop. Supports OpenCode 2.2.x from 2.2.6 and 2.3.x from 2.3.2 through the GUI plugin API.

+

Use your own wallpapers in OpenCode Desktop. Supports OpenCode 2.2.x from 2.2.6, 2.3.x from 2.3.2, and 2.4.x from 2.4.3 through the GUI plugin API.

image ## Install ```sh -opencode plugin add 'github:viralcodex/opencode-backdrop#v0.2.0' +opencode plugin add 'github:viralcodex/opencode-backdrop#v0.3.0' ``` This installs the plugin globally. Alternatively, add it to your global `opencode.json` or `opencode.jsonc`, keeping any existing plugins. Do not add it to `cli.json`. @@ -14,7 +14,7 @@ This installs the plugin globally. Alternatively, add it to your global `opencod ```jsonc { "$schema": "https://opencode.ai/config.json", - "plugins": ["github:viralcodex/opencode-backdrop#v0.2.0"], + "plugins": ["github:viralcodex/opencode-backdrop#v0.3.0"], } ``` @@ -22,19 +22,31 @@ This installs the plugin globally. Alternatively, add it to your global `opencod 1. Open **Settings > Wallpapers**. 2. Choose **Change folder** to use a local folder, or **+** to upload an image. -3. Select an image and adjust tint, brightness and fit. +3. Select a wallpaper and adjust tint, brightness and fit. -Wallpaper starts off with an empty gallery. Images and preferences stay local, and images are not sent to models. Files must be non-empty and no larger than 8 MiB. +Wallpaper starts off with an empty gallery. Wallpapers and preferences stay local and are not sent to models. Images and HTML must be non-empty and no larger than 8 MiB; videos can be up to 256 MiB. -- Folder images support PNG, JPEG, WebP and SVG, including subfolders. Changes appear automatically. -- Uploads support PNG, JPEG and WebP. -- The gallery shows at most two rows, including the **+** tile. Use **Show more** to see all images, or **Show less** to collapse it. +- Folders support PNG, JPEG, WebP, SVG, GIF, APNG, MP4, WebM, and self-contained HTML, including subfolders. Changes appear automatically. +- Uploads support PNG, JPEG, WebP, GIF and APNG. Add video and HTML through the wallpaper folder. +- Videos play muted and loop continuously. MP4 with H.264 is recommended; other codecs depend on Desktop support. Animated images keep their original animation. +- HTML wallpapers run in a sandbox without access to the OpenCode interface or local storage. CSP blocks external scripts, styles, assets, and fetch requests. Embed everything in the HTML and use files from sources you trust. This is not a network firewall; a script can still navigate its own frame to another URL. +- Filter the gallery by **All wallpapers**, **Static**, or **Live**. Live tiles have a small play icon beside their name. Hover or keyboard-focus a live tile to preview it without changing your selected wallpaper. +- Videos and animated images show static thumbnail frames until previewed. For an HTML poster, put `Name.poster.png`, `.jpg`, `.jpeg`, or `.webp` beside `Name.html`. Poster files stay out of the gallery. Without a poster, HTML tiles show a live-wallpaper label until previewed. +- The gallery shows at most two rows, including the **+** tile. Use **Show more** to see all wallpapers, or **Show less** to collapse it. - More tint improves text contrast. **Fill background** crops the image; **Show whole image** keeps it fully visible. - Use `/wallpaper` in chat to switch images or turn wallpaper off. Escape cancels the picker. - Turn **Show wallpaper** off to restore the app's backgrounds without losing your choices. -- Turn **Wallpaper slideshow** on to cycle through all gallery images in order. Choose **None** or **Fade** in the transition dropdown and set **Display time** in seconds, from 5 to 86400. The default is 60 seconds. Slideshow needs at least two images, and fades respect reduced-motion settings. +- Turn **Wallpaper slideshow** on to cycle through all wallpapers in gallery order, regardless of the gallery filter. Choose **None** or **Fade** and set **Display time** in seconds, from 5 to 86400. The default is 60 seconds. Slideshow needs at least two wallpapers. Fades apply between images and respect reduced-motion settings; video and HTML switch instantly. Live playback itself does not pause under reduced motion. -To remove an upload, hover or focus its tile and click **X**. Remove folder images by moving or deleting their source files. +To remove an upload, hover or focus its tile and click **X**. Remove folder wallpapers by moving or deleting their source files. + +## Koi Pond example + +[Koi Pond](https://github.com/Himanshu-Sangshetti/koipond) is a live WebGL wallpaper, not a video. Download `koipond-linux.tar.gz` from its [wallpaper release](https://github.com/Himanshu-Sangshetti/koipond/releases/tag/wallpaper-v0.2.0), extract `web/index.html`, and save it in your wallpaper folder as `Koi Pond.html`. No installer is needed. Select it in **Settings > Wallpapers**. + +Save the repo's [poster image](https://raw.githubusercontent.com/Himanshu-Sangshetti/koipond/main/.github/assets/hero.webp) beside it as `Koi Pond.poster.webp` to show the pond before hovering. + +Other HTML animations work the same way when bundled into one file. The wallpaper cannot intercept clicks or read the OpenCode interface. HTML fills the panel; the fit setting applies to images and videos. ## Optional folder configuration @@ -45,7 +57,7 @@ You can set an initial folder with an absolute path instead of choosing one in S "$schema": "https://opencode.ai/config.json", "plugins": [ { - "package": "github:viralcodex/opencode-backdrop#v0.2.0", + "package": "github:viralcodex/opencode-backdrop#v0.3.0", "options": { "folder": "/absolute/path/to/wallpapers" }, }, ], @@ -58,8 +70,11 @@ The folder chosen in Settings takes precedence over this option. ```sh bun run check -bun run test:styles bun run test:storage /path/to/opencode ``` -`check` includes native Node filesystem-watcher tests and rebuilds the GUI bundle. `test:styles` runs that bundle's setup, wallpaper switching, stylesheet cleanup, and gallery-toggle checks in headless Chrome; set `CHROME_BIN` if Chrome is installed elsewhere. `test:storage` checks migration against an OpenCode checkout's actual persistence decoder. Pass the checkout path or set `OPENCODE_CHECKOUT`. +`check` rebuilds the GUI bundle and runs unit, native Node filesystem-watcher, headless Chrome, and package checks. Set `CHROME_BIN` to a Chrome or Chromium executable if it is installed elsewhere. The PR workflow runs these checks and rejects a stale committed bundle. `test:storage` checks migration against an OpenCode checkout's actual persistence decoder. Pass the checkout path or set `OPENCODE_CHECKOUT`. + +## Release + +See [CHANGELOG.md](CHANGELOG.md) for the 0.3.0 release notes. Before tagging `v0.3.0`, run `bun install --frozen-lockfile --ignore-scripts` and `bun run check`, then commit the rebuilt `dist/gui-experimental.cjs` with the source changes. Run the host-storage check against a supported OpenCode checkout and smoke-test the installed package in Desktop. Keep the local `showcase/` captures and artwork out of this PR. diff --git a/bun.lock b/bun.lock index 674ff44..87ac944 100644 --- a/bun.lock +++ b/bun.lock @@ -16,7 +16,7 @@ "vite-plugin-solid": "2.11.10", }, "peerDependencies": { - "@opencode/plugin": "~2.2.6 || ~2.3.2 || ^0.0.0-dev", + "@opencode/plugin": "~2.2.6 || ~2.3.2 || ~2.4.3 || ^0.0.0-dev", "effect": "^4.1.0", "solid-js": "^1.9.17", }, diff --git a/dist/gui-experimental.cjs b/dist/gui-experimental.cjs index f974c7d..be383f2 100644 --- a/dist/gui-experimental.cjs +++ b/dist/gui-experimental.cjs @@ -1,12 +1,12 @@ -"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const n=require("solid-js/web"),O=require("@opencode/plugin/gui"),h=require("solid-js"),p=require("effect"),de=require("solid-js/store"),ie=require("node:fs"),N=require("node:fs/promises"),_=require("node:path"),Se=require("node:os"),G=8*1024*1024,ke=p.Schema.Struct({id:p.Schema.String,title:p.Schema.String,version:p.Schema.String}),xe=p.Schema.Struct({id:p.Schema.String,version:p.Schema.String}),le=O.Ipc.define({id:"wallpaper.catalog.v5",state:p.Schema.Struct({folder:p.Schema.String,folderLabel:p.Schema.optional(p.Schema.String),ready:p.Schema.Boolean,images:p.Schema.Array(ke),error:p.Schema.String}),methods:{refresh:{output:p.Schema.Boolean},setFolder:{input:p.Schema.NonEmptyString,output:p.Schema.Boolean},read:{input:xe,output:p.Schema.String}}}),$e=/^[A-Za-z0-9+/]+={0,2}$/,Ee=new Set(["image/png","image/jpeg","image/webp"]),pe=p.Schema.String.check(p.Schema.isPattern(/^(?:data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2})?$/),p.Schema.isMaxLength(23+4*Math.ceil(G/3)),p.Schema.makeFilter(e=>{const t=X(e);return!e||t.length%4===0&&ge(t)<=G}));function Ce(e){if(!Ee.has(e.type))throw new Error("image.typeError");if(e.size===0||e.size>G)throw new Error("image.sizeError")}function ue(e){const t=/^data:(image\/(?:png|jpeg|webp|svg\+xml))(;base64)?,([\s\S]+)$/.exec(e);if(!t)throw new Error("image.decodeError");const[,a,i,r]=t;if(i&&(r.length%4!==0||ge(r)>G||!$e.test(r)))throw new Error("image.decodeError");if(!i&&a!=="image/svg+xml")throw new Error("image.decodeError");try{const l=new Blob([i?Uint8Array.from(atob(r),d=>d.charCodeAt(0)):decodeURIComponent(r)],{type:a});if(l.size===0||l.size>G)throw new Error("image.decodeError");return l}catch(l){throw new Error("image.decodeError",{cause:l})}}async function ee(e,t){t.throwIfAborted();const a=new Image,i=()=>{a.src=""};t.addEventListener("abort",i,{once:!0});try{return a.src=e,await a.decode(),t.throwIfAborted(),a}catch(r){throw t.throwIfAborted(),new Error("image.decodeError",{cause:r})}finally{t.removeEventListener("abort",i)}}async function Ae(e,t){t.throwIfAborted();const a=URL.createObjectURL(ue(e));try{const i=await ee(a,t),r=document.createElement("canvas"),l=Math.min(1,320/i.naturalWidth,200/i.naturalHeight);r.width=Math.max(1,Math.round(i.naturalWidth*l)),r.height=Math.max(1,Math.round(i.naturalHeight*l));const d=r.getContext("2d");if(!d)throw new Error("image.decodeError");d.drawImage(i,0,0,r.width,r.height);const g=await new Promise((c,b)=>{r.toBlob(f=>f?c(f):b(new Error("image.decodeError")),"image/png")});return t.throwIfAborted(),{blob:g,width:r.width,height:r.height}}finally{URL.revokeObjectURL(a)}}async function Le(e,t){t.throwIfAborted(),Ce(e);const a=URL.createObjectURL(e);try{await ee(a,t)}finally{URL.revokeObjectURL(a)}return t.throwIfAborted(),new Promise((i,r)=>{const l=new FileReader,d=()=>l.abort(),g=()=>t.removeEventListener("abort",d);l.onload=()=>{g(),typeof l.result!="string"?r(new Error("image.readError")):i(l.result)},l.onerror=()=>{g(),r(new Error("image.readError"))},l.onabort=()=>{g(),r(t.reason)},t.addEventListener("abort",d,{once:!0});try{l.readAsDataURL(e)}catch(c){g(),r(new Error("image.readError",{cause:c}))}})}function Q(e,t){return e.startsWith("image.")?t(e):`${t("image.readError")} ${e}`}function X(e){return e.slice(e.indexOf(",")+1)}function ge(e){return e.length/4*3-(e.endsWith("==")?2:e.endsWith("=")?1:0)}const P={tint:{min:0,max:100,initial:80},brightness:{min:25,max:150,initial:100}},me=["tint","brightness"],j={min:5,max:86400,duration:60,transition:"fade"},he=800,Re=p.Schema.Struct({id:p.Schema.String.check(p.Schema.isPattern(/^(?:custom|upload:.+)$/)),name:p.Schema.String.check(p.Schema.isMinLength(1)),image:pe.check(p.Schema.isMinLength(1))}),U={enabled:p.Schema.Boolean,preset:p.Schema.String,images:p.Schema.Array(Re).check(p.Schema.makeFilter(e=>new Set(e.map(t=>t.id)).size===e.length)),tint:p.Schema.Int.check(p.Schema.isBetween({minimum:P.tint.min,maximum:P.tint.max})),brightness:p.Schema.Int.check(p.Schema.isBetween({minimum:P.brightness.min,maximum:P.brightness.max})),fit:p.Schema.Literals(["cover","contain"]),slideshow:p.Schema.Boolean,duration:p.Schema.Int.check(p.Schema.isBetween({minimum:j.min,maximum:j.max})),transition:p.Schema.Literals(["none","fade"])},z=p.Schema.Struct({...U,images:p.Schema.optional(U.images),tint:p.Schema.optional(U.tint),brightness:p.Schema.optional(U.brightness),slideshow:p.Schema.optional(U.slideshow),duration:p.Schema.optional(U.duration),transition:p.Schema.optional(U.transition),image:p.Schema.optional(pe),imageName:p.Schema.optional(p.Schema.String),strength:p.Schema.optional(p.Schema.Int.check(p.Schema.isBetween({minimum:5,maximum:45}))),hidden:p.Schema.optional(p.Schema.Array(p.Schema.String))}),Me=z.pipe(p.Schema.decodeTo(p.Schema.Struct(U),{decode:p.SchemaGetter.transform(e=>({enabled:e.enabled,preset:e.preset,fit:e.fit,images:e.image&&!e.images?.some(t=>t.id==="custom")?[{id:"custom",name:e.imageName||"Wallpaper",image:e.image},...e.images??[]]:e.images??[],tint:e.tint??(e.strength===void 0?P.tint.initial:100-e.strength),brightness:e.brightness??P.brightness.initial,slideshow:e.slideshow??!1,duration:e.duration??j.duration,transition:e.transition??j.transition})),encode:p.SchemaGetter.transform(e=>e)})),D={enabled:!1,preset:"",images:[],tint:P.tint.initial,brightness:P.brightness.initial,fit:"cover",slideshow:!1,duration:j.duration,transition:j.transition};function T(e,t){return p.Schema.withDecodingDefaultType(p.Effect.succeed(t))(e).pipe(p.Schema.catchDecoding(()=>p.Effect.succeed(p.Option.some(t))))}const Ie=p.Schema.Struct({enabled:T(U.enabled,D.enabled),preset:T(U.preset,D.preset),fit:T(U.fit,D.fit),images:T(z.fields.images,void 0),tint:T(z.fields.tint,void 0),brightness:T(z.fields.brightness,void 0),slideshow:T(z.fields.slideshow,void 0),duration:T(z.fields.duration,void 0),transition:T(z.fields.transition,void 0),image:T(z.fields.image,void 0),imageName:T(z.fields.imageName,void 0),strength:T(z.fields.strength,void 0)}).pipe(p.Schema.decodeTo(Me));function fe(e){return{tint:e.tint,brightness:e.brightness}}function V(e,t){return e?.id===t?.id&&e?.version===t?.version&&e?.image===t?.image}function Y(e,t){return t.find(a=>a.id===e.preset)}function be(e){return e.images}function We(e=[],t=D,a=[]){const i=new Map(a.map(r=>[r.id,r]));return[...e,...be(t).map(r=>{const l=we(r.name),d=i.get(r.id);return d?.image===r.image&&d.title===l?d:{id:r.id,title:l,version:"custom",image:r.image}})]}function te(e){return e.id==="custom"||e.id.startsWith("upload:")}function _e(e,t,a){if(!te(t)||(e.images=e.images.filter(r=>r.id!==t.id),e.preset!==t.id))return;const i=a[a.findIndex(r=>r.id===t.id)+1]??a.find(r=>r.id!==t.id);e.preset=i?.id??D.preset,i||(e.enabled=!1)}function re(e,t){e.enabled=t!=="off",t!=="off"&&(e.preset=t)}function Te(e,t,a){re(e,t?Y(e,a)?.id??a[0]?.id??"off":"off")}function H(e,t){return te(e)?e.title||t("image.custom"):e.title}function se(e,t,a){const i=K(e.name),r=X(e.image??"");for(const l of be(t)){if(l.name&&K(l.name)===i)throw new Error("image.duplicateName");if(r&&r===X(l.image))throw new Error("image.duplicateImage")}for(const l of a){const d=Ue(l.id);if(d&&K(d)===i)throw new Error("image.duplicateName")}}function Ue(e){if(!e.startsWith("file:"))return"";const t=e.slice(5);return decodeURIComponent(t)}function K(e){return we(e).normalize("NFC").toLowerCase()}function we(e){const t=(e.split(/[\\/]/).at(-1)??e).trim();return t.replace(/\.(?:png|jpe?g|webp|svg)$/i,"")||t}function ze(e,t,a,i,r,l){return{id:"choose",title:e.t("picker.title"),description:e.t("picker.description"),keywords:"wallpaper background image",slash:{name:"wallpaper"},async run(){e.signal.aborted||(await a(),!e.signal.aborted&&l({title:e.t("picker.title"),placeholder:e.t("picker.search"),current:i(),options:t().map(d=>({title:H(d,e.t),value:d.id}))},d=>{if(!e.signal.aborted){if(d==="settings"){e.layout.settings("wallpaper");return}r(d)}}))}}}function ve(e){return h.createMemo(()=>{const t=e();return t?{...t}:void 0},void 0,{equals:V})}function Pe(e,t,a){const[i,r]=h.createSignal(e()),[l,d]=h.createSignal();let g;const c=()=>{clearTimeout(g),g=void 0},b=f=>{c();const C=t()&&!a()?he:0;h.batch(()=>{d(C?{show:f,duration:C}:void 0),!C&&!f&&r(!1)}),C&&(g=setTimeout(()=>{g=void 0,h.batch(()=>{d(void 0),f||r(!1)})},C))};return h.createEffect(h.on(()=>[e(),a()],([f,C])=>{if(c(),!f)return b(!1);r(!0),C&&d(void 0)})),h.createEffect(h.on(()=>e()&&t(),(f,C)=>{f&&!C&&b(!0)})),h.onCleanup(c),{enabled:i,fade:l}}function je(e,t,a=()=>0){const[i,r]=de.createStore({url:"",width:0,height:0,loading:!1,error:"",choice:void 0,previous:void 0,transition:0});let l;const d=()=>{clearTimeout(l),l=void 0,i.previous&&URL.revokeObjectURL(i.previous.url),r({previous:void 0,transition:0})};h.onCleanup(()=>{d(),i.url&&URL.revokeObjectURL(i.url)});const g=ve(e);return h.createEffect(h.on(g,c=>{const b=new AbortController;let f="";if(h.onCleanup(()=>{b.abort(),f&&URL.revokeObjectURL(f),f=""}),r({loading:!!c,error:""}),!c){d(),i.url&&URL.revokeObjectURL(i.url),r({url:"",width:0,height:0,choice:void 0});return}if(i.url&&V(c,i.choice)){r({loading:!1});return}(async()=>{try{const C=c.image??await t(c,b.signal);b.signal.throwIfAborted(),f=URL.createObjectURL(ue(C));const y=await ee(f,b.signal);b.signal.throwIfAborted(),d();const $=h.untrack(a),L=i.url&&$>0?{url:i.url,width:i.width,height:i.height}:void 0;i.url&&!L&&URL.revokeObjectURL(i.url);const I={url:f,width:y.naturalWidth,height:y.naturalHeight};f="",r({...I,choice:c,previous:L,transition:L?$:0,loading:!1,error:""}),L&&(l=setTimeout(d,$))}catch(C){f&&URL.revokeObjectURL(f),f="",b.signal.aborted||r({loading:!1,error:C instanceof Error?C.message:String(C)})}})()})),i}function Fe(e,t){const[a,i]=de.createStore({url:"",width:0,height:0,loading:!1,error:""}),r=ve(e);return h.createRenderEffect(()=>{const l=r(),d=new AbortController;let g;if(h.onCleanup(()=>{d.abort(),g?.release()}),i({url:"",width:0,height:0,loading:!!l,error:""}),!!l)try{if(g=t.acquire(l),g.value){i({...g.value,loading:!1});return}g.ready.then(c=>{d.signal.aborted||i({...c,loading:!1})},c=>{d.signal.aborted||i({loading:!1,error:c instanceof Error?c.message:String(c)})})}catch(c){i({loading:!1,error:c instanceof Error?c.message:String(c)})}}),a}function Be(e){const t=new Map;return Object.assign((i,r,l)=>{const d=t.get(i)??new Set,g=new Set(l.filter(Boolean)),c=[...g].filter(b=>!d.has(b));g.size?t.set(i,g):t.delete(i),c.length&&e.show({variant:"error",icon:"outline-photo",title:r,description:c.join(` +"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const o=require("solid-js/web"),Z=require("@opencode/plugin/gui"),u=require("solid-js"),p=require("effect"),he=require("solid-js/store"),Se=require("node:fs"),X=require("node:fs/promises"),U=require("node:path"),Oe=require("node:os"),Be=require("node:crypto"),Fe=require("node:http"),Ne=require("node:stream/promises"),te=8*1024*1024,qe=256*1024*1024,He=p.Schema.Struct({id:p.Schema.String,title:p.Schema.String,version:p.Schema.String,kind:p.Schema.optional(p.Schema.Literals(["video","html"])),animated:p.Schema.optional(p.Schema.Boolean),poster:p.Schema.optional(p.Schema.Struct({id:p.Schema.String,version:p.Schema.String}))}),ue=p.Schema.Struct({id:p.Schema.String,version:p.Schema.String}),ke=Z.Ipc.define({id:"wallpaper.catalog.v7",state:p.Schema.Struct({folder:p.Schema.String,folderLabel:p.Schema.optional(p.Schema.String),ready:p.Schema.Boolean,images:p.Schema.Array(He),error:p.Schema.String}),methods:{refresh:{output:p.Schema.Boolean},setFolder:{input:p.Schema.NonEmptyString,output:p.Schema.Boolean},read:{input:ue,output:p.Schema.String},source:{input:ue,output:p.Schema.String}}}),De=/^[A-Za-z0-9+/]+={0,2}$/,Ve=new Set(["image/png","image/jpeg","image/webp","image/gif","image/apng"]),Ce=p.Schema.String.check(p.Schema.isPattern(/^(?:data:image\/(?:png|jpeg|webp|gif|apng);base64,[A-Za-z0-9+/]+={0,2})?$/),p.Schema.isMaxLength(23+4*Math.ceil(te/3)),p.Schema.makeFilter(e=>{const t=ce(e);return!e||t.length%4===0&&Me(t)<=te}));function Ge(e){if(!Ve.has(e.type))throw new Error("image.typeError");if(e.size===0||e.size>te)throw new Error("image.sizeError")}function Ae(e,t){if(t==="image/gif"||t==="image/apng")return!0;if(t==="image/webp")return e.length>20&&new TextDecoder().decode(e.subarray(12,16))==="VP8X"&&!!(e[20]&2);if(t==="image/svg+xml")return/<(?:animate\w*|set)\b|\banimation(?:-[\w-]+)?\s*[:=]/i.test(new TextDecoder().decode(e).replace(//g,""));if(t!=="image/png")return!1;const r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let a=8;a+12<=e.length;a+=r.getUint32(a)+12){const n=r.getUint32(a+4);if(n===1633899596)return a+16<=e.length&&r.getUint32(a+8)>1;if(n===1229209940)return!1}return!1}function be(e){const t=/^data:(image\/(?:png|jpeg|webp|gif|apng|svg\+xml))(;base64)?,([\s\S]+)$/.exec(e);if(!t)throw new Error("image.decodeError");const[,r,a,n]=t;if(a&&(n.length%4!==0||Me(n)>te||!De.test(n)))throw new Error("image.decodeError");if(!a&&r!=="image/svg+xml")throw new Error("image.decodeError");try{const i=new Blob([a?Uint8Array.from(atob(n),l=>l.charCodeAt(0)):decodeURIComponent(n)],{type:r});if(i.size===0||i.size>te)throw new Error("image.decodeError");return i}catch(i){throw new Error("image.decodeError",{cause:i})}}async function we(e,t){t.throwIfAborted();const r=new Image,a=()=>{r.src=""};t.addEventListener("abort",a,{once:!0});try{return r.src=e,await r.decode(),t.throwIfAborted(),r}catch(n){throw t.throwIfAborted(),new Error("image.decodeError",{cause:n})}finally{t.removeEventListener("abort",a)}}async function Ke(e,t){t.throwIfAborted();const r=URL.createObjectURL(be(e));try{const a=await we(r,t);return await Le(a,a.naturalWidth,a.naturalHeight,t)}finally{URL.revokeObjectURL(r)}}async function Le(e,t,r,a){a.throwIfAborted();const n=document.createElement("canvas"),i=Math.min(1,320/t,200/r);n.width=Math.max(1,Math.round(t*i)),n.height=Math.max(1,Math.round(r*i));const l=n.getContext("2d");if(!l)throw new Error("image.decodeError");l.drawImage(e,0,0,n.width,n.height);const s=await new Promise((c,g)=>{n.toBlob(b=>b?c(b):g(new Error("image.decodeError")),"image/png")});return a.throwIfAborted(),{blob:s,width:n.width,height:n.height}}async function Je(e,t){t.throwIfAborted(),Ge(e);const r=URL.createObjectURL(e);try{await we(r,t)}finally{URL.revokeObjectURL(r)}return t.throwIfAborted(),new Promise((a,n)=>{const i=new FileReader,l=()=>i.abort(),s=()=>t.removeEventListener("abort",l);i.onload=()=>{s(),typeof i.result!="string"?n(new Error("image.readError")):a(i.result)},i.onerror=()=>{s(),n(new Error("image.readError"))},i.onabort=()=>{s(),n(t.reason)},t.addEventListener("abort",l,{once:!0});try{i.readAsDataURL(e)}catch(c){s(),n(new Error("image.readError",{cause:c}))}})}function ge(e,t){return e.startsWith("image.")?t(e):`${t("image.readError")} ${e}`}function ce(e){return e.slice(e.indexOf(",")+1)}function Me(e){return e.length/4*3-(e.endsWith("==")?2:e.endsWith("=")?1:0)}const G={tint:{min:0,max:100,initial:80},brightness:{min:25,max:150,initial:100}},Re=["tint","brightness"],K={min:5,max:86400,duration:60,transition:"fade"},Ie=800,Xe=p.Schema.Struct({id:p.Schema.String.check(p.Schema.isPattern(/^(?:custom|upload:.+)$/)),name:p.Schema.String.check(p.Schema.isMinLength(1)),image:Ce.check(p.Schema.isMinLength(1))}),q={enabled:p.Schema.Boolean,preset:p.Schema.String,images:p.Schema.Array(Xe).check(p.Schema.makeFilter(e=>new Set(e.map(t=>t.id)).size===e.length)),tint:p.Schema.Int.check(p.Schema.isBetween({minimum:G.tint.min,maximum:G.tint.max})),brightness:p.Schema.Int.check(p.Schema.isBetween({minimum:G.brightness.min,maximum:G.brightness.max})),fit:p.Schema.Literals(["cover","contain"]),slideshow:p.Schema.Boolean,duration:p.Schema.Int.check(p.Schema.isBetween({minimum:K.min,maximum:K.max})),transition:p.Schema.Literals(["none","fade"])},V=p.Schema.Struct({...q,images:p.Schema.optional(q.images),tint:p.Schema.optional(q.tint),brightness:p.Schema.optional(q.brightness),slideshow:p.Schema.optional(q.slideshow),duration:p.Schema.optional(q.duration),transition:p.Schema.optional(q.transition),image:p.Schema.optional(Ce),imageName:p.Schema.optional(p.Schema.String),strength:p.Schema.optional(p.Schema.Int.check(p.Schema.isBetween({minimum:5,maximum:45}))),hidden:p.Schema.optional(p.Schema.Array(p.Schema.String))}),Ze=V.pipe(p.Schema.decodeTo(p.Schema.Struct(q),{decode:p.SchemaGetter.transform(e=>({enabled:e.enabled,preset:e.preset,fit:e.fit,images:e.image&&!e.images?.some(t=>t.id==="custom")?[{id:"custom",name:e.imageName||"Wallpaper",image:e.image},...e.images??[]]:e.images??[],tint:e.tint??(e.strength===void 0?G.tint.initial:100-e.strength),brightness:e.brightness??G.brightness.initial,slideshow:e.slideshow??!1,duration:e.duration??K.duration,transition:e.transition??K.transition})),encode:p.SchemaGetter.transform(e=>e)})),ee={enabled:!1,preset:"",images:[],tint:G.tint.initial,brightness:G.brightness.initial,fit:"cover",slideshow:!1,duration:K.duration,transition:K.transition};function N(e,t){return p.Schema.withDecodingDefaultType(p.Effect.succeed(t))(e).pipe(p.Schema.catchDecoding(()=>p.Effect.succeed(p.Option.some(t))))}const Qe=p.Schema.Struct({enabled:N(q.enabled,ee.enabled),preset:N(q.preset,ee.preset),fit:N(q.fit,ee.fit),images:N(V.fields.images,void 0),tint:N(V.fields.tint,void 0),brightness:N(V.fields.brightness,void 0),slideshow:N(V.fields.slideshow,void 0),duration:N(V.fields.duration,void 0),transition:N(V.fields.transition,void 0),image:N(V.fields.image,void 0),imageName:N(V.fields.imageName,void 0),strength:N(V.fields.strength,void 0)}).pipe(p.Schema.decodeTo(Ze));function Te(e){return{tint:e.tint,brightness:e.brightness}}function oe(e,t){return e?.id===t?.id&&e?.version===t?.version&&e?.image===t?.image&&e?.kind===t?.kind&&e?.animated===t?.animated&&e?.poster?.id===t?.poster?.id&&e?.poster?.version===t?.poster?.version}function Q(e){return!!e.kind||!!e.animated}function Ye(e,t){return t==="all"?e:e.filter(r=>Q(r)===(t==="live"))}function me(e,t){return t.find(r=>r.id===e.preset)}function We(e){return e.images}function et(e=[],t=ee,r=[]){const a=new Map(r.map(n=>[n.id,n]));return[...e,...We(t).map(n=>{const i=ze(n.name),l=a.get(n.id);if(l?.image===n.image&&l.title===i)return l;const s=n.image.slice(5,n.image.indexOf(";")),c=Uint8Array.from(atob(ce(n.image).slice(0,87380)),g=>g.charCodeAt(0));return{id:n.id,title:i,version:"custom",image:n.image,...Ae(c,s)?{animated:!0}:{}}})]}function ve(e){return e.id==="custom"||e.id.startsWith("upload:")}function tt(e,t,r){if(!ve(t)||(e.images=e.images.filter(n=>n.id!==t.id),e.preset!==t.id))return;const a=r[r.findIndex(n=>n.id===t.id)+1]??r.find(n=>n.id!==t.id);e.preset=a?.id??ee.preset,a||(e.enabled=!1)}function ye(e,t){e.enabled=t!=="off",t!=="off"&&(e.preset=t)}function rt(e,t,r){ye(e,t?me(e,r)?.id??r[0]?.id??"off":"off")}function Y(e,t){return ve(e)?e.title||t("image.custom"):e.title}function xe(e,t,r){const a=pe(e.name),n=ce(e.image??"");for(const i of We(t)){if(i.name&&pe(i.name)===a)throw new Error("image.duplicateName");if(n&&n===ce(i.image))throw new Error("image.duplicateImage")}for(const i of r){const l=at(i.id);if(l&&pe(l)===a)throw new Error("image.duplicateName")}}function at(e){if(!e.startsWith("file:"))return"";const t=e.slice(5);return decodeURIComponent(t)}function pe(e){return ze(e).normalize("NFC").toLowerCase()}function ze(e){const t=(e.split(/[\\/]/).at(-1)??e).trim();return t.replace(/\.(?:png|jpe?g|webp|svg|gif|apng|mp4|webm|html?)$/i,"")||t}function nt(e,t,r,a,n,i){return{id:"choose",title:e.t("picker.title"),description:e.t("picker.description"),keywords:"wallpaper background image",slash:{name:"wallpaper"},async run(){e.signal.aborted||(await r(),!e.signal.aborted&&i({title:e.t("picker.title"),placeholder:e.t("picker.search"),current:a(),options:t().map(l=>({title:Y(l,e.t),value:l.id}))},l=>{if(!e.signal.aborted){if(l==="settings"){e.layout.settings("wallpaper");return}n(l)}}))}}}function Pe(e){return u.createMemo(()=>{const t=e();return t?{...t}:void 0},void 0,{equals:oe})}function ot(e,t,r){const[a,n]=u.createSignal(e()),[i,l]=u.createSignal();let s;const c=()=>{clearTimeout(s),s=void 0},g=b=>{c();const C=t()&&!r()?Ie:0;u.batch(()=>{l(C?{show:b,duration:C}:void 0),!C&&!b&&n(!1)}),C&&(s=setTimeout(()=>{s=void 0,u.batch(()=>{l(void 0),b||n(!1)})},C))};return u.createEffect(u.on(()=>[e(),r()],([b,C])=>{if(c(),!b)return g(!1);n(!0),C&&l(void 0)})),u.createEffect(u.on(()=>e()&&t(),(b,C)=>{b&&!C&&g(!0)})),u.onCleanup(c),{enabled:a,fade:i}}function it(e,t,r=()=>0){const[a,n]=he.createStore({url:"",width:0,height:0,loading:!1,error:"",choice:void 0,previous:void 0,transition:0});let i;const l=()=>{clearTimeout(i),i=void 0,a.previous&&URL.revokeObjectURL(a.previous.url),n({previous:void 0,transition:0})};u.onCleanup(()=>{l(),a.url&&URL.revokeObjectURL(a.url)});const s=Pe(e);return u.createEffect(u.on(s,c=>{const g=new AbortController;let b="";if(u.onCleanup(()=>{g.abort(),b&&URL.revokeObjectURL(b),b=""}),n({loading:!!c,error:""}),!c){l(),a.url&&URL.revokeObjectURL(a.url),n({url:"",width:0,height:0,choice:void 0});return}if(a.url&&oe(c,a.choice)){n({loading:!1});return}(async()=>{try{const C=c.image??await t(c,g.signal);g.signal.throwIfAborted(),b=URL.createObjectURL(be(C));const w=await we(b,g.signal);g.signal.throwIfAborted(),l();const v=u.untrack(r),k=a.url&&v>0?{url:a.url,width:a.width,height:a.height}:void 0;a.url&&!k&&URL.revokeObjectURL(a.url);const z={url:b,width:w.naturalWidth,height:w.naturalHeight};b="",n({...z,choice:c,previous:k,transition:k?v:0,loading:!1,error:""}),k&&(i=setTimeout(l,v))}catch(C){b&&URL.revokeObjectURL(b),b="",g.signal.aborted||n({loading:!1,error:C instanceof Error?C.message:String(C)})}})()})),a}function lt(e,t){const[r,a]=he.createStore({url:"",width:0,height:0,loading:!1,error:""}),n=Pe(e);return u.createRenderEffect(()=>{const i=n(),l=new AbortController;let s;if(u.onCleanup(()=>{l.abort(),s?.release()}),a({url:"",width:0,height:0,loading:!!i,error:""}),!!i)try{if(s=t.acquire(i),s.value){a({...s.value,loading:!1});return}s.ready.then(c=>{l.signal.aborted||a({...c,loading:!1})},c=>{l.signal.aborted||a({loading:!1,error:c instanceof Error?c.message:String(c)})})}catch(c){a({loading:!1,error:c instanceof Error?c.message:String(c)})}}),r}function st(e){const t=new Map;return Object.assign((a,n,i)=>{const l=t.get(a)??new Set,s=new Set(i.filter(Boolean)),c=[...s].filter(g=>!l.has(g));s.size?t.set(a,s):t.delete(a),c.length&&e.show({variant:"error",icon:"outline-photo",title:n,description:c.join(` -`)})},{retain(i){const r=new Set(i);for(const l of t.keys())r.has(l)||t.delete(l)}})}function Oe(e,{maxEntries:t=48,maxBytes:a=8*1024*1024,concurrency:i=2,signal:r}={}){const l=new Map,d=new Set,g=new Map,c=p.Semaphore.makeUnsafe(i);let b=0,f=!1;function C(s){const w=g.get(s);w!==void 0&&(g.delete(s),b-=w)}function y(s){C(s),s.value&&URL.revokeObjectURL(s.value.url),s.value=void 0,d.delete(s)}function $(s){s.retired||(C(s),l.get(s.choice.id)===s&&l.delete(s.choice.id),s.retired=!0,s.controller.abort(),s.reject(s.controller.signal.reason),s.users?d.add(s):y(s))}function L(s){if(!(s.users||s.retired))for(C(s),g.set(s,s.bytes),b+=s.bytes;g.size>t||b>a;){const w=g.keys().next().value;if(!w)break;$(w)}}function I(s){p.Effect.runPromise(c.withPermit(p.Effect.tryPromise({try:w=>e(s.choice,w),catch:w=>w})),{signal:s.controller.signal}).then(w=>{s.controller.signal.throwIfAborted(),s.value={url:URL.createObjectURL(w.blob),width:w.width,height:w.height},s.bytes=w.blob.size,s.resolve(s.value),L(s)}).catch(w=>{s.reject(w),$(s)})}function x(s){if(f)throw new DOMException("Thumbnail cache is disposed.","AbortError");let w=l.get(s.id);if(w&&!V(w.choice,s)&&($(w),w=void 0),!w){const{promise:o,resolve:m,reject:u}=Promise.withResolvers();w={choice:{...s},controller:new AbortController,ready:o,resolve:m,reject:u,users:0,bytes:0,retired:!1},I(w)}const A=w;C(A),A.users++,l.set(s.id,A);let v=!1;return{value:A.value,ready:A.ready,release(){v||(v=!0,A.users--,A.retired&&!A.users?y(A):L(A))}}}function E(){if(!f){f=!0,r?.removeEventListener("abort",E);for(const s of new Set([...l.values(),...d]))$(s),y(s);l.clear(),d.clear(),g.clear(),b=0}}return r?.addEventListener("abort",E,{once:!0}),r?.aborted&&E(),{acquire:x,peek(s){const w=l.get(s.id);return w&&V(w.choice,s)?w.value:void 0},retain(s){const w=new Map(s.map(A=>[A.id,A]));for(const A of l.values())V(A.choice,w.get(A.choice.id))||$(A)},dispose:E}}function qe(e,t){const a=document.createElement("style"),i=document.createElement("style"),r=document.createElement("style");return a.dataset.wallpaperStyle="settings",i.dataset.wallpaperStyle="canvas",r.dataset.wallpaperStyle="image",a.textContent=e,i.textContent=t,i.disabled=!0,document.head.append(a,i,r),{update(l){r.textContent=l,i.disabled=!l},dispose(){a.remove(),i.remove(),r.remove()}}}const F='[data-slot="home-panel"], [data-slot="session-chat-panel"] > .bg-v2-background-bg-base, [data-component="new-session"]',ae=` +`)})},{retain(a){const n=new Set(a);for(const i of t.keys())n.has(i)||t.delete(i)}})}function ct(e,{maxEntries:t=48,maxBytes:r=8*1024*1024,concurrency:a=2,signal:n}={}){const i=new Map,l=new Set,s=new Map,c=p.Semaphore.makeUnsafe(a);let g=0,b=!1;function C(d){const m=s.get(d);m!==void 0&&(s.delete(d),g-=m)}function w(d){C(d),d.value&&URL.revokeObjectURL(d.value.url),d.value=void 0,l.delete(d)}function v(d){d.retired||(C(d),i.get(d.choice.id)===d&&i.delete(d.choice.id),d.retired=!0,d.controller.abort(),d.reject(d.controller.signal.reason),d.users?l.add(d):w(d))}function k(d){if(!(d.users||d.retired))for(C(d),s.set(d,d.bytes),g+=d.bytes;s.size>t||g>r;){const m=s.keys().next().value;if(!m)break;v(m)}}function z(d){p.Effect.runPromise(c.withPermit(p.Effect.tryPromise({try:m=>e(d.choice,m),catch:m=>m})),{signal:d.controller.signal}).then(m=>{d.controller.signal.throwIfAborted(),d.value={url:URL.createObjectURL(m.blob),width:m.width,height:m.height},d.bytes=m.blob.size,d.resolve(d.value),k(d)}).catch(m=>{d.reject(m),v(d)})}function R(d){if(b)throw new DOMException("Thumbnail cache is disposed.","AbortError");let m=i.get(d.id);if(m&&!oe(m.choice,d)&&(v(m),m=void 0),!m){const{promise:T,resolve:f,reject:E}=Promise.withResolvers();m={choice:{...d},controller:new AbortController,ready:T,resolve:f,reject:E,users:0,bytes:0,retired:!1},z(m)}const A=m;C(A),A.users++,i.set(d.id,A);let $=!1;return{value:A.value,ready:A.ready,release(){$||($=!0,A.users--,A.retired&&!A.users?w(A):k(A))}}}function y(){if(!b){b=!0,n?.removeEventListener("abort",y);for(const d of new Set([...i.values(),...l]))v(d),w(d);i.clear(),l.clear(),s.clear(),g=0}}return n?.addEventListener("abort",y,{once:!0}),n?.aborted&&y(),{acquire:R,peek(d){const m=i.get(d.id);return m&&oe(m.choice,d)?m.value:void 0},retain(d){const m=new Map(d.map(A=>[A.id,A]));for(const A of i.values())oe(A.choice,m.get(A.choice.id))||v(A)},dispose:y}}function dt(e,t){const r=document.createElement("style"),a=document.createElement("style"),n=document.createElement("style");return r.dataset.wallpaperStyle="settings",a.dataset.wallpaperStyle="canvas",n.dataset.wallpaperStyle="image",r.textContent=e,a.textContent=t,a.disabled=!0,document.head.append(r,a,n),{update(i){n.textContent=i,a.disabled=!i},dispose(){r.remove(),a.remove(),n.remove()}}}const H='[data-slot="home-panel"], [data-slot="session-chat-panel"] > .bg-v2-background-bg-base, [data-component="new-session"]',de=` [data-slot="home-panel"] .sticky.bg-v2-background-bg-base, [data-slot="session-chat-panel"] [data-session-title] > .bg-v2-background-bg-base, [data-slot="session-chat-panel"] [data-slot="session-location-bar"], [data-slot="session-chat-panel"] [data-component="collapsed-tool-group"] > [data-component="collapsible"] > [data-slot="collapsible-trigger"][aria-expanded="true"], [data-slot="session-chat-panel"] :is([data-component="edit-tool"], [data-component="write-tool"], [data-component="apply-patch-tool"]) > [data-component="collapsible"] > [data-slot="collapsible-trigger"]:is([aria-expanded="true"], [data-locked]) -`;function Ne(e){const t=`:is(${e})`;return` +`;function pt(e){const t=`:is(${e})`;return` ${t}::before, ${t}::after { content: ""; @@ -34,15 +34,15 @@ z-index: -99; background: var(--wallpaper-tint, transparent); } - `}const De=` - :is(${F}) { + `}const ut=` + :is(${H}) { position: relative; isolation: isolate; --wallpaper-secondary: color-mix(in srgb, var(--v2-text-text-base) 88%, var(--v2-background-bg-base)); --wallpaper-text-shadow: 0 1px 2px var(--v2-background-bg-base), 0 0 4px var(--v2-background-bg-base); } - :is(${F}) [data-wallpaper-backed] { + :is(${H}) [data-wallpaper-backed] { isolation: isolate; background: var(--v2-background-bg-base); } @@ -115,10 +115,28 @@ [data-component="new-session"] [data-slot="brick-breaker-hud"] :is(.bg-v2-border-border-base, .bg-v2-icon-icon-faint) { background-color: var(--wallpaper-secondary); } -`,Ge=De+Ne(`${F}, :is(${F}) [data-wallpaper-backed]`);function Ve(e,t){const a=e.enabled&&!!t,{tint:i,brightness:r}=fe(e);return{"--wallpaper-image":a?`url(${JSON.stringify(t)})`:"none","--wallpaper-fit":e.fit,"--wallpaper-tint":a?`color-mix(in srgb, var(--v2-background-bg-base) ${i}%, transparent)`:"transparent","--wallpaper-filter":a?`brightness(${r}%) contrast(85%) saturate(90%)`:"none"}}function He(e,t){if(!e.enabled||!t)return"";const a=Object.entries(Ve(e,t)).map(([i,r])=>`${i}: ${r};`).join(` - `);return`${F} { +`,gt=ut+pt(`${H}, :is(${H}) [data-wallpaper-backed]`)+` + .opencode-wallpaper-media { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + z-index: -100; + border: 0; + border-radius: inherit; + pointer-events: none; + object-fit: var(--wallpaper-fit, cover); + filter: var(--wallpaper-filter, none); + background: var(--v2-background-bg-base); + } + + [data-wallpaper-media] :is(${de}) { + background: var(--v2-background-bg-base); + } +`;function mt(e,t,r=!1){const a=e.enabled&&!!t,{tint:n,brightness:i}=Te(e);return{"--wallpaper-image":a&&!r?`url(${JSON.stringify(t)})`:"none","--wallpaper-fit":e.fit,"--wallpaper-tint":a?`color-mix(in srgb, var(--v2-background-bg-base) ${n}%, transparent)`:"transparent","--wallpaper-filter":a?`brightness(${i}%) contrast(85%) saturate(90%)`:"none"}}function ft(e,t,r=!1){if(!e.enabled||!t)return"";const a=Object.entries(mt(e,t,r)).map(([n,i])=>`${n}: ${i};`).join(` + `);return`${H} { ${a} -}`}function ye(e,t,a,i){const r=Math[i==="cover"?"max":"min"](e.width/a.width,e.height/a.height),l=a.width*r,d=a.height*r,g=(e.width-l)/2-(t.left-e.left),c=(e.height-d)/2-(t.top-e.top),b=f=>`${Math.round(f*1e3)/1e3}px`;return{"--wallpaper-background-size":`${b(l)} ${b(d)}`,"--wallpaper-background-position":`${b(g)} ${b(c)}`}}function Ke(e){if(!(e.image.width>0&&e.image.height>0))return()=>{};const t=new Map,a=new Set;let i=0,r=!1,l=!0,d=[];const g=(y,$)=>{$.attribute===null?y.removeAttribute("data-wallpaper-backed"):y.setAttribute("data-wallpaper-backed",$.attribute);for(const[L,I]of $.properties)I.value?y.style.setProperty(L,I.value,I.priority):y.style.removeProperty(L)},c=()=>{!r&&!i&&(i=requestAnimationFrame(f))},b=new ResizeObserver(c);function f(){if(i=0,r)return;l&&(d=[...document.querySelectorAll(ae)],l=!1);const y=new Set,$=new Set,L=new Map,I=[];for(const x of d){const E=x.closest(F);if(!E)continue;const s=x.getBoundingClientRect(),w=L.get(E)??E.getBoundingClientRect();L.set(E,w),!(!s.width||!s.height||!w.width||!w.height)&&(y.add(x),$.add(E),$.add(x),I.push({element:x,geometry:ye(w,s,e.image,e.fit)}))}for(const[x,E]of t)y.has(x)||(g(x,E),t.delete(x));for(const{element:x,geometry:E}of I){t.has(x)||t.set(x,{attribute:x.getAttribute("data-wallpaper-backed"),properties:new Map(Object.keys(E).map(s=>[s,{value:x.style.getPropertyValue(s),priority:x.style.getPropertyPriority(s)}]))});for(const[s,w]of Object.entries(E))x.style.getPropertyValue(s)!==w&&x.style.setProperty(s,w);x.hasAttribute("data-wallpaper-backed")||x.setAttribute("data-wallpaper-backed","")}for(const x of a)$.has(x)||(b.unobserve(x),a.delete(x));for(const x of $)a.has(x)||(b.observe(x),a.add(x))}const C=new MutationObserver(()=>{l=!0,c()});return C.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["aria-expanded","data-locked","class"]}),document.addEventListener("scroll",c,{capture:!0,passive:!0}),window.addEventListener("resize",c,{passive:!0}),c(),()=>{if(!r){r=!0,cancelAnimationFrame(i),C.disconnect(),b.disconnect(),document.removeEventListener("scroll",c,!0),window.removeEventListener("resize",c);for(const[y,$]of t)g(y,$);t.clear(),a.clear(),d=[]}}}var Je=n.template(""),Ze=n.template(""),Qe=n.template("");function Xe(e){const[t,a]=h.createSignal(!!e.cache.peek(e.choice));let i;h.onMount(()=>{const l=new IntersectionObserver(d=>{a(d.some(g=>g.isIntersecting))},{rootMargin:"200px"});l.observe(i),h.onCleanup(()=>l.disconnect())});const r=Fe(()=>t()?e.choice:void 0,e.cache);return(()=>{var l=Je(),d=i;return typeof d=="function"?n.use(d,l):i=l,n.insert(l,n.createComponent(h.Show,{get when(){return r.url},get fallback(){return n.createComponent(h.Show,{get when(){return r.error},get children(){var g=Ze();return n.insert(g,()=>e.t("image.unavailable")),n.effect(c=>{var b=Q(r.error,e.t),f=Q(r.error,e.t);return b!==c.e&&n.setAttribute(g,"title",c.e=b),f!==c.t&&n.setAttribute(g,"aria-label",c.t=f),c},{e:void 0,t:void 0}),g}})},children:g=>(()=>{var c=Qe();return n.effect(()=>n.setAttribute(c,"src",g())),c})()})),n.effect(()=>n.setAttribute(l,"aria-busy",r.loading)),l})()}var Ye=n.template(" + @@ -176,7 +314,7 @@ try { try { const page = await browser.newPage() await page.goto(pathToFileURL(html).href) - await page.waitForFunction(() => document.body.hasAttribute("data-result"), undefined, { timeout: 10000 }) + await page.waitForFunction(() => document.body.hasAttribute("data-result"), undefined, { timeout: 20000 }) const encoded = await page.locator("body").getAttribute("data-result") assert(encoded, "Chrome did not report the stylesheet test result") const report = JSON.parse(Buffer.from(encoded, "base64").toString()) as { pass: boolean; message?: string } @@ -184,7 +322,9 @@ try { } finally { await browser.close() } - console.log("Browser checks passed: built GUI setup, image reads, wallpaper switching, on/off, gallery layout, disclosure accessibility, and cleanup.") + console.log("Browser checks passed: built GUI setup, static/live switching, muted video playback, thumbnails, HTML isolation, previews, route changes, on/off, gallery accessibility, and cleanup.") } finally { + media.dispose() + catalog.dispose() await rm(directory, { recursive: true, force: true }) } diff --git a/src/catalog.ts b/src/catalog.ts index c75706d..7f280d8 100644 --- a/src/catalog.ts +++ b/src/catalog.ts @@ -3,7 +3,8 @@ import { open, readdir, realpath, stat } from "node:fs/promises" import path from "node:path" import { homedir } from "node:os" import { Effect, Schema, Semaphore } from "effect" -import { Catalog, ImageRequest, maxImageBytes } from "./contract" +import { Catalog, ImageRequest, maxImageBytes, maxVideoBytes } from "./contract" +import { animatedImage } from "./image" const formats: Readonly> = { ".png": "image/png", @@ -11,8 +12,16 @@ const formats: Readonly> = { ".jpeg": "image/jpeg", ".webp": "image/webp", ".svg": "image/svg+xml", + ".gif": "image/gif", + ".apng": "image/apng", + ".mp4": "video/mp4", + ".webm": "video/webm", + ".html": "text/html", + ".htm": "text/html", } const missing = Schema.is(Schema.Struct({ code: Schema.Literal("ENOENT") })) +const posterFile = /\.poster\.(?:png|jpe?g|webp)$/i +const posterExtensions = [".png", ".jpg", ".jpeg", ".webp"] export function wallpaperFolder(options: unknown) { const configured = Schema.decodeUnknownSync(Schema.optional(Schema.Union([ @@ -165,21 +174,38 @@ export function createCatalog(folder: string, changed: () => void) { if (lifetime.signal.aborted) return try { const info = await stat(file) - requireSize(info.size) + requireSize(info.size, file) const version = stamp(info) const id = `file:${encodeURIComponent(file)}` const title = path.relative(root, file).slice(0, -path.extname(file).length) const previous = cache.get(id) + const type = formats[path.extname(file).toLowerCase()] + const kind = type.startsWith("video/") ? "video" as const : type === "text/html" ? "html" as const : undefined const image = previous?.image.version === version && previous.image.title === title - ? previous.image : { id, title, version } + ? previous.image : { id, title, version, ...(kind ? { kind } : {}), ...(await fileAnimated(file, type) ? { animated: true } : {}) } next.set(id, { file, image }) } catch (error) { errors.push(`${path.relative(root, file)}: ${error instanceof Error ? error.message : String(error)}`) } } if (lifetime.signal.aborted) return + const posters = new Map() + for (const entry of next.values()) { + if (!posterFile.test(entry.file)) continue + const stem = entry.file.slice(0, -path.extname(entry.file).length).replace(/\.poster$/i, ".poster") + const previous = posters.get(stem) + if (previous && posterExtensions.indexOf(path.extname(previous.file).toLowerCase()) <= posterExtensions.indexOf(path.extname(entry.file).toLowerCase())) continue + posters.set(stem, entry) + } + for (const entry of next.values()) { + if (!entry.image.kind) continue + const stem = entry.file.slice(0, -path.extname(entry.file).length) + const poster = posters.get(`${stem}.poster`)?.image + if (entry.image.poster?.id === poster?.id && entry.image.poster?.version === poster?.version) continue + entry.image = { ...entry.image, poster: poster ? { id: poster.id, version: poster.version } : undefined } + } cache = next - const images = [...cache.values()].map((entry) => entry.image).sort((a, b) => a.id.localeCompare(b.id)) + const images = [...cache.values()].filter((entry) => !posterFile.test(entry.file)).map((entry) => entry.image).sort((a, b) => a.id.localeCompare(b.id)) const error = [...new Set(errors)].sort().join("\n") if (value.ready && error === value.error && images.length === value.images.length && images.every((image, i) => image === value.images[i])) return value = { folder, ready: true, images, error } @@ -191,6 +217,7 @@ export function createCatalog(folder: string, changed: () => void) { async try(signal) { const entry = cache.get(request.id) if (!entry || entry.image.version !== request.version) throw new Error("The selected wallpaper is missing or has changed.") + if (entry.image.kind) throw new Error("Use the wallpaper media URL.") const file = await open(entry.file, "r") try { const info = await file.stat() @@ -219,6 +246,20 @@ export function createCatalog(folder: string, changed: () => void) { state: () => value, refresh, read, + async openMedia(request: typeof ImageRequest.Type) { + const entry = cache.get(request.id) + if (lifetime.signal.aborted || !entry?.image.kind || entry.image.version !== request.version) throw new Error("The selected wallpaper is missing or has changed.") + const file = await open(entry.file, "r") + try { + const info = await file.stat() + requireSize(info.size, entry.file) + if (!info.isFile() || stamp(info) !== request.version) throw new Error("The selected wallpaper has changed. Refresh the gallery.") + return { file, size: info.size, type: formats[path.extname(entry.file).toLowerCase()] } + } catch (error) { + await file.close() + throw error + } + }, dispose() { lifetime.abort() watcher?.close() @@ -229,8 +270,22 @@ export function createCatalog(folder: string, changed: () => void) { } } -function requireSize(size: number) { - if (size === 0 || size > maxImageBytes) throw new Error("image.sizeError") +async function fileAnimated(file: string, type: string) { + if (type === "image/gif" || type === "image/apng") return true + if (!["image/png", "image/webp", "image/svg+xml"].includes(type) || posterFile.test(file)) return false + const handle = await open(file, "r") + try { + const buffer = Buffer.alloc(64 * 1024) + const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0) + return animatedImage(buffer.subarray(0, bytesRead), type) + } finally { + await handle.close() + } +} + +function requireSize(size: number, file = "") { + const video = formats[path.extname(file).toLowerCase()]?.startsWith("video/") + if (size === 0 || size > (video ? maxVideoBytes : maxImageBytes)) throw new Error(video ? "image.videoSizeError" : "image.sizeError") } function stamp(info: { size: number; mtimeMs: number; ctimeMs: number; dev: number; ino: number }) { diff --git a/src/contract.ts b/src/contract.ts index b90494b..73c50e9 100644 --- a/src/contract.ts +++ b/src/contract.ts @@ -2,13 +2,19 @@ import { Ipc } from "@opencode/plugin/gui" import { Schema } from "effect" export const maxImageBytes = 8 * 1024 * 1024 +export const maxVideoBytes = 256 * 1024 * 1024 -export const Wallpaper = Schema.Struct({ id: Schema.String, title: Schema.String, version: Schema.String }) +export const Wallpaper = Schema.Struct({ + id: Schema.String, title: Schema.String, version: Schema.String, + kind: Schema.optional(Schema.Literals(["video", "html"])), + animated: Schema.optional(Schema.Boolean), + poster: Schema.optional(Schema.Struct({ id: Schema.String, version: Schema.String })), +}) export const ImageRequest = Schema.Struct({ id: Schema.String, version: Schema.String }) export const Catalog = Ipc.define({ - id: "wallpaper.catalog.v5", + id: "wallpaper.catalog.v7", state: Schema.Struct({ folder: Schema.String, folderLabel: Schema.optional(Schema.String), @@ -20,5 +26,6 @@ export const Catalog = Ipc.define({ refresh: { output: Schema.Boolean }, setFolder: { input: Schema.NonEmptyString, output: Schema.Boolean }, read: { input: ImageRequest, output: Schema.String }, + source: { input: ImageRequest, output: Schema.String }, }, }) diff --git a/src/gui.tsx b/src/gui.tsx index dcae154..f83b798 100644 --- a/src/gui.tsx +++ b/src/gui.tsx @@ -3,7 +3,7 @@ import { batch, createEffect, createMemo, createSignal, onCleanup } from "solid- import { Schema } from "effect" import { wallpaperCommand } from "./command" import { Catalog } from "./contract" -import { changeWallpaper, setWallpaperEnabled, wallpaperCatalog, wallpaperTitle, type WallpaperChoice } from "./model" +import { changeWallpaper, isLiveWallpaper, setWallpaperEnabled, wallpaperCatalog, wallpaperTitle, type WallpaperChoice } from "./model" import { appearanceKeys, StoredPreferences, initial, wallpaperFadeDuration } from "./preferences" import { createWallpaperImage, createWallpaperVisibility, type WallpaperReader } from "./render" import { imageError, thumbnailBlob } from "./image" @@ -14,6 +14,7 @@ import { createWallpaperStyles, wallpaperCanvasStyle, wallpaperVariableStyle } f import { WallpaperSettings } from "./settings" import { WallpaperPicker } from "./picker" import { createWallpaperSlideshow } from "./slideshow" +import { createWallpaperMedia, videoThumbnailBlob } from "./media" import { createWallpaperVisibilityAnimation, fadeWallpaper, wallpaperTransitionStyle } from "./transition" import en from "./i18n/en" import css from "./settings.css?inline" @@ -23,10 +24,14 @@ export default Plugin.define({ i18n: { en }, async main(ctx) { const { createCatalog, wallpaperFolder, wallpaperFolderLabel } = await import("./catalog") + const { createWallpaperMediaServer } = await import("./media-server") ctx.signal.throwIfAborted() const folder = ctx.storage.store("folder", { schema: Schema.String, initial: "" }) let catalog = createCatalog(wallpaperFolder(folder.value || (ctx.options.folder ?? ctx.options.folders)), changed) ctx.onCleanup(() => catalog.dispose()) + const media = await createWallpaperMediaServer((request) => catalog.openMedia(request)) + ctx.onCleanup(media.dispose) + ctx.signal.throwIfAborted() let lastError = "" const state = () => { const value = catalog.state() @@ -54,6 +59,11 @@ export default Plugin.define({ async read(request, caller) { return catalog.read(request, AbortSignal.any([caller.signal, ctx.signal])) }, + async source(request, caller) { + caller.signal.throwIfAborted() + ctx.signal.throwIfAborted() + return media.source(request) + }, }) await catalog.refresh() }, @@ -66,7 +76,7 @@ export default Plugin.define({ ) const settings = ctx.stores.preferences const slideshow = createWallpaperSlideshow(() => settings.value, images, () => - !image.loading && !image.previous && !visibility.fade() && (!!image.url || !!image.error), + !image.loading && !media.loading && !image.previous && !visibility.fade() && (!!image.url || !!media.url || !!image.error || !!media.error), ) const selected = slideshow.selected const select = (choice: string) => batch(() => { @@ -84,10 +94,12 @@ export default Plugin.define({ onCleanup(() => motion.removeEventListener("change", motionChanged)) const read: WallpaperReader = async (choice, signal) => { if (!catalog) throw new Error("image.readError") - return catalog.read({ id: choice.id, version: choice.version }, { signal: AbortSignal.any([signal, ctx.signal]) }) + const method = choice.kind ? catalog.source : catalog.read + return method({ id: choice.id, version: choice.version }, { signal: AbortSignal.any([signal, ctx.signal]) }) } + const media = createWallpaperMedia(() => settings.value.enabled && selected()?.kind ? selected() : undefined, read) const visibility = createWallpaperVisibility(() => settings.value.enabled, () => !!image.url, reducedMotion) - const painted = createMemo(() => settings.value.enabled ? selected() : visibility.enabled() ? image.choice : undefined) + const painted = createMemo(() => selected()?.kind ? undefined : settings.value.enabled ? selected() : visibility.enabled() ? image.choice : undefined) const image = createWallpaperImage(painted, read, () => settings.value.slideshow && settings.value.transition === "fade" && !reducedMotion() ? wallpaperFadeDuration : 0, @@ -98,7 +110,8 @@ export default Plugin.define({ ) const thumbnails = createThumbnailCache(async (choice, signal) => { try { - const thumbnail = await thumbnailBlob(choice.image ?? await read(choice, signal), signal) + const source = choice.poster ? await read({ ...choice.poster, title: choice.title }, signal) : choice.image ?? await read(choice, signal) + const thumbnail = choice.kind === "video" && !choice.poster ? await videoThumbnailBlob(source, signal) : await thumbnailBlob(source, signal) reportImage(choice, "") return thumbnail } catch (error) { @@ -114,7 +127,7 @@ export default Plugin.define({ if (state) report(`folder:${state.folder}`, ctx.t("folders.title"), state.error ? state.error.split("\n").map((error) => error.replace(/image\.[A-Za-z]+$/, (key) => ctx.t(key))) : []) const choice = selected() - if (choice && !image.loading) reportImage(choice, image.error) + if (choice && !(choice.kind ? media.loading : image.loading)) reportImage(choice, choice.kind ? media.error : image.error) const preferences = ctx.stores.preferences.value const missing = preferences.enabled && preferences.preset.startsWith("file:") && state?.ready && !state.error && !choice report(`missing:${preferences.preset}`, ctx.t("title"), missing ? [ctx.t("folders.missing")] : []) @@ -125,7 +138,7 @@ export default Plugin.define({ }) const styles = createWallpaperStyles(css, wallpaperCanvasStyle + wallpaperTransitionStyle) onCleanup(styles.dispose) - const variables = createMemo(() => wallpaperVariableStyle({ ...settings.value, enabled: visibility.enabled() }, image.url)) + const variables = createMemo(() => wallpaperVariableStyle({ ...settings.value, enabled: media.url ? settings.value.enabled : visibility.enabled() }, media.url || image.url, !!media.url)) createEffect(() => styles.update(variables())) createKeyed(() => image.url ? { url: image.url, width: image.width, height: image.height, fit: settings.value.fit } : undefined, (frame) => onCleanup(alignWallpaperHeaders({ image: frame, fit: frame.fit })), @@ -153,7 +166,7 @@ export default Plugin.define({ return ["enabled", ...(ctx.desktop ? ["folders"] : []), "preset", "slideshow", ...(settings.value.slideshow ? ["transition", "duration"] : []), ...appearanceKeys].map((id) => ({ id: `wallpaper-${id}`, title: ctx.t(`${id}.title`), - keywords: "wallpaper background image upload fit folder tint brightness contrast slideshow transition fade duration seconds", + keywords: "wallpaper background image upload fit folder tint brightness contrast slideshow transition fade duration seconds live static animation video preview", })) }, render: () => ( @@ -163,6 +176,7 @@ export default Plugin.define({ select={select} setEnabled={setEnabled} thumbnails={thumbnails} + read={read} folder={() => catalog?.state()?.folderLabel ?? catalog?.state()?.folder ?? ""} changeFolder={async (folder, signal) => { if (!catalog) throw new Error("Wallpaper folders are unavailable.") @@ -191,9 +205,11 @@ export default Plugin.define({ } }, () => settings.value.enabled ? selected()?.id ?? settings.value.preset : "off", select, (options, choose) => { + const live = new Set(images().filter(isLiveWallpaper).map((image) => image.id)) ctx.dialogs.open((dialog) => settings.value.enabled} + isLive={(choice) => live.has(choice)} onToggle={setEnabled} onSelect={(value) => { dialog.close(); choose(value) }} />) diff --git a/src/i18n/en.ts b/src/i18n/en.ts index a951b4d..284709c 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -5,6 +5,11 @@ export default { "preset.title": "Choose a wallpaper", "gallery.showMore": "Show more", "gallery.showLess": "Show less", + "gallery.filter": "Wallpaper type", + "gallery.all": "All wallpapers", + "gallery.static": "Static", + "gallery.live": "Live", + "gallery.empty": "No wallpapers match this filter.", "picker.title": "Choose wallpaper", "picker.description": "Choose a background without leaving the conversation.", "picker.search": "Search wallpapers", @@ -12,7 +17,7 @@ export default { "picker.enable": "Turn wallpaper on", "picker.settings": "Wallpaper settings", "folders.title": "Wallpaper folder", - "folders.description": "PNG, JPEG, WebP and SVG files up to 8 MiB, including subfolders.", + "folders.description": "Images and self-contained HTML up to 8 MiB. MP4 and WebM up to 256 MiB. Includes subfolders.", "folders.choose": "Change folder", "folders.changeError": "The wallpaper folder could not be changed.", "folders.missing": "The selected wallpaper file is missing or unreadable. Choose another wallpaper or restore the file.", @@ -20,11 +25,13 @@ export default { "image.remove": "Remove wallpaper", "image.loading": "Reading image...", "image.unavailable": "Unavailable", + "image.live": "Live wallpaper", "image.custom": "Custom image", - "image.typeError": "Choose a PNG, JPEG or WebP image.", - "image.sizeError": "Choose a non-empty image up to 8 MiB.", - "image.readError": "The image could not be read. Try another file.", - "image.decodeError": "The file is not a readable image. Try another file.", + "image.typeError": "Choose a PNG, JPEG, WebP, GIF or APNG image.", + "image.sizeError": "Choose a non-empty image or HTML file up to 8 MiB.", + "image.videoSizeError": "Choose a non-empty video up to 256 MiB.", + "image.readError": "The wallpaper could not be read. Try another file.", + "image.decodeError": "The file is not a readable image or supported video. Try another file.", "image.duplicateName": "A wallpaper with this name is already available.", "image.duplicateImage": "This image is already added, even if its filename is different.", "tint.title": "Wallpaper tint", @@ -35,9 +42,9 @@ export default { "fit.cover": "Fill background", "fit.contain": "Show whole image", "slideshow.title": "Wallpaper slideshow", - "slideshow.description": "Cycle through all wallpapers in gallery order. Add at least two images to start.", + "slideshow.description": "Cycle through all wallpapers in gallery order. Add at least two wallpapers to start.", "transition.title": "Wallpaper transition", - "transition.description": "Choose how wallpapers change. Fade respects reduced-motion settings.", + "transition.description": "Fade applies between images and respects reduced-motion settings. Video and HTML switch instantly.", "transition.none": "None", "transition.fade": "Fade", "duration.title": "Display time", diff --git a/src/image.ts b/src/image.ts index 2d516e6..dae68af 100644 --- a/src/image.ts +++ b/src/image.ts @@ -2,10 +2,10 @@ import { Schema } from "effect" import { maxImageBytes } from "./contract" const base64 = /^[A-Za-z0-9+/]+={0,2}$/ -const rasterTypes = new Set(["image/png", "image/jpeg", "image/webp"]) +const rasterTypes = new Set(["image/png", "image/jpeg", "image/webp", "image/gif", "image/apng"]) export const StoredImage = Schema.String.check( - Schema.isPattern(/^(?:data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2})?$/), + Schema.isPattern(/^(?:data:image\/(?:png|jpeg|webp|gif|apng);base64,[A-Za-z0-9+/]+={0,2})?$/), Schema.isMaxLength("data:image/jpeg;base64,".length + 4 * Math.ceil(maxImageBytes / 3)), Schema.makeFilter((image: string) => { const data = imageBytes(image) @@ -18,8 +18,22 @@ export function checkImage(file: Pick) { if (file.size === 0 || file.size > maxImageBytes) throw new Error("image.sizeError") } +export function animatedImage(data: Uint8Array, type: string) { + if (type === "image/gif" || type === "image/apng") return true + if (type === "image/webp") return data.length > 20 && new TextDecoder().decode(data.subarray(12, 16)) === "VP8X" && !!(data[20] & 2) + if (type === "image/svg+xml") return /<(?:animate\w*|set)\b|\banimation(?:-[\w-]+)?\s*[:=]/i.test(new TextDecoder().decode(data).replace(//g, "")) + if (type !== "image/png") return false + const view = new DataView(data.buffer, data.byteOffset, data.byteLength) + for (let offset = 8; offset + 12 <= data.length; offset += view.getUint32(offset) + 12) { + const chunk = view.getUint32(offset + 4) + if (chunk === 0x6163544c) return offset + 16 <= data.length && view.getUint32(offset + 8) > 1 + if (chunk === 0x49444154) return false + } + return false +} + export function wallpaperBlob(image: string) { - const match = /^data:(image\/(?:png|jpeg|webp|svg\+xml))(;base64)?,([\s\S]+)$/.exec(image) + const match = /^data:(image\/(?:png|jpeg|webp|gif|apng|svg\+xml))(;base64)?,([\s\S]+)$/.exec(image) if (!match) throw new Error("image.decodeError") const [, type, encoded, data] = match if (encoded && (data.length % 4 !== 0 || base64Size(data) > maxImageBytes || !base64.test(data))) throw new Error("image.decodeError") @@ -58,23 +72,28 @@ export async function thumbnailBlob(data: string, signal: AbortSignal): Promise< const url = URL.createObjectURL(wallpaperBlob(data)) try { const image = await decodeWallpaper(url, signal) - const canvas = document.createElement("canvas") - const scale = Math.min(1, 320 / image.naturalWidth, 200 / image.naturalHeight) - canvas.width = Math.max(1, Math.round(image.naturalWidth * scale)) - canvas.height = Math.max(1, Math.round(image.naturalHeight * scale)) - const context = canvas.getContext("2d") - if (!context) throw new Error("image.decodeError") - context.drawImage(image, 0, 0, canvas.width, canvas.height) - const blob = await new Promise((resolve, reject) => { - canvas.toBlob((blob) => blob ? resolve(blob) : reject(new Error("image.decodeError")), "image/png") - }) - signal.throwIfAborted() - return { blob, width: canvas.width, height: canvas.height } + return await thumbnail(image, image.naturalWidth, image.naturalHeight, signal) } finally { URL.revokeObjectURL(url) } } +export async function thumbnail(image: CanvasImageSource, width: number, height: number, signal: AbortSignal): Promise { + signal.throwIfAborted() + const canvas = document.createElement("canvas") + const scale = Math.min(1, 320 / width, 200 / height) + canvas.width = Math.max(1, Math.round(width * scale)) + canvas.height = Math.max(1, Math.round(height * scale)) + const context = canvas.getContext("2d") + if (!context) throw new Error("image.decodeError") + context.drawImage(image, 0, 0, canvas.width, canvas.height) + const blob = await new Promise((resolve, reject) => { + canvas.toBlob((blob) => blob ? resolve(blob) : reject(new Error("image.decodeError")), "image/png") + }) + signal.throwIfAborted() + return { blob, width: canvas.width, height: canvas.height } +} + export async function uploadImage(file: File, signal: AbortSignal) { signal.throwIfAborted() checkImage(file) diff --git a/src/live-icon.tsx b/src/live-icon.tsx new file mode 100644 index 0000000..c47dd3b --- /dev/null +++ b/src/live-icon.tsx @@ -0,0 +1,7 @@ +export function WallpaperLiveIcon(props: { label: string }) { + return + {props.label} + + + +} diff --git a/src/media-server.test.ts b/src/media-server.test.ts new file mode 100644 index 0000000..4bb11a0 --- /dev/null +++ b/src/media-server.test.ts @@ -0,0 +1,141 @@ +import { expect, test } from "bun:test" +import { mkdtemp, realpath, rm, truncate } from "node:fs/promises" +import { tmpdir } from "node:os" +import path from "node:path" +import { createCatalog } from "./catalog" +import { createWallpaperMediaServer } from "./media-server" +import { StoredImage, wallpaperBlob } from "./image" +import { Schema } from "effect" + +test("serves only current catalog media, supports video ranges, and isolates HTML", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "opencode-wallpaper-media-")) + const catalog = createCatalog(directory, () => {}) + const server = await createWallpaperMediaServer(catalog.openMedia) + try { + await Bun.write(path.join(directory, "pond.html"), "") + await Bun.write(path.join(directory, "pond.POSTER.PNG"), "poster") + await Bun.write(path.join(directory, "pond.poster.webp"), "fallback poster") + await Bun.write(path.join(directory, "loop.mp4"), "0123456789") + await Bun.write(path.join(directory, "large.webm"), "0") + await truncate(path.join(directory, "large.webm"), 9 * 1024 * 1024) + await Bun.write(path.join(directory, "fish.gif"), "GIF89a") + await catalog.refresh() + const video = catalog.state().images.find((image) => image.title === "loop")! + const html = catalog.state().images.find((image) => image.title === "pond")! + expect(video.kind).toBe("video") + expect(html.kind).toBe("html") + expect(html.poster?.id).toBe(`file:${encodeURIComponent(await realpath(path.join(directory, "pond.POSTER.PNG")))}`) + expect(catalog.state().images.some((image) => /poster/i.test(image.title))).toBe(false) + expect(await catalog.read(html.poster!)).toBe("data:image/png;base64,cG9zdGVy") + const previous = catalog.state().images + await catalog.refresh() + expect(catalog.state().images).toBe(previous) + expect(catalog.state().images.find((image) => image.title === "large")?.kind).toBe("video") + expect(catalog.state().images.find((image) => image.title === "fish")?.kind).toBeUndefined() + const url = await server.source(video) + const range = await fetch(url, { headers: { Range: "bytes=2-5" } }) + expect(range.status).toBe(206) + expect(range.headers.get("content-range")).toBe("bytes 2-5/10") + expect(await range.text()).toBe("2345") + expect(await (await fetch(url, { headers: { Range: "bytes=-3" } })).text()).toBe("789") + expect((await fetch(url, { headers: { Range: "bytes=50-" } })).status).toBe(416) + expect((await fetch(url, { method: "HEAD" })).headers.get("content-length")).toBe("10") + expect((await fetch(url.replace(new URL(url).pathname, "/wrong"))).status).toBe(404) + const page = await fetch(await server.source(html)) + expect(page.headers.get("content-type")).toBe("text/html; charset=utf-8") + expect(page.headers.get("content-security-policy")).toContain("sandbox allow-scripts") + expect(page.headers.get("content-security-policy")).toContain("default-src 'none'") + expect(page.headers.get("permissions-policy")).toContain("camera=()") + expect(page.headers.get("permissions-policy")).toContain("autoplay=()") + expect(page.headers.get("referrer-policy")).toBe("no-referrer") + await page.text() + await Bun.write(path.join(directory, "pond.POSTER.PNG"), "new poster") + await catalog.refresh() + expect(catalog.state().images.find((image) => image.id === html.id)?.poster?.version).not.toBe(html.poster?.version) + await expect(catalog.read(html.poster!)).rejects.toThrow("changed") + await rm(path.join(directory, "pond.POSTER.PNG")) + await catalog.refresh() + const fallback = catalog.state().images.find((image) => image.id === html.id)! + expect(fallback.poster?.id).toEndWith("pond.poster.webp") + await rm(path.join(directory, "pond.poster.webp")) + await catalog.refresh() + expect(catalog.state().images.find((image) => image.id === html.id)?.poster).toBeUndefined() + await expect(catalog.read(video)).rejects.toThrow("media URL") + await Bun.write(path.join(directory, "loop.mp4"), "changed") + expect((await fetch(url)).status).toBe(404) + await expect(server.source({ id: "file:outside", version: "1" })).rejects.toThrow("missing") + server.dispose() + await expect(server.source(html)).rejects.toThrow("unavailable") + } finally { + server.dispose() + catalog.dispose() + await rm(directory, { recursive: true, force: true }) + } +}) + +test("rejects malformed ranges and requests without the media token", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "opencode-wallpaper-ranges-")) + const catalog = createCatalog(directory, () => {}) + const server = await createWallpaperMediaServer(catalog.openMedia) + try { + await Bun.write(path.join(directory, "loop.webm"), "0123456789") + await catalog.refresh() + const url = await server.source(catalog.state().images[0]) + for (const range of ["bytes=", "bytes=-", "bytes=-0", "bytes=5-2", "bytes=0-2,5-7", "bytes=9007199254740992-"]) { + const response = await fetch(url, { headers: { Range: range } }) + expect(response.status).toBe(416) + expect(response.headers.get("content-range")).toBe("bytes */10") + await response.text() + } + for (const range of ["bytes=0-99", "bytes=-99", "bytes=0-"]) { + const response = await fetch(url, { headers: { Range: range } }) + expect(response.status).toBe(206) + expect(response.headers.get("content-range")).toBe("bytes 0-9/10") + expect(await response.text()).toBe("0123456789") + } + expect((await fetch(new URL(url).origin)).status).toBe(404) + expect((await fetch(url, { method: "POST" })).status).toBe(404) + const malformed = new URL(url) + malformed.searchParams.delete("version") + expect((await fetch(malformed)).status).toBe(404) + } finally { + server.dispose() + catalog.dispose() + await rm(directory, { recursive: true, force: true }) + } +}) + +test("enforces separate image, HTML, and video limits", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "opencode-wallpaper-limits-")) + const catalog = createCatalog(directory, () => {}) + try { + for (const [name, size] of [ + ["max.mp4", 256 * 1024 * 1024], + ["large.webm", 256 * 1024 * 1024 + 1], + ["large.html", 8 * 1024 * 1024 + 1], + ["empty.mp4", 0], + ] as const) { + await Bun.write(path.join(directory, name), "0") + await truncate(path.join(directory, name), size) + } + await catalog.refresh() + expect(catalog.state().images.map((image) => image.title)).toEqual(["max"]) + expect(catalog.state().error).toBe("empty.mp4: image.videoSizeError\nlarge.html: image.sizeError\nlarge.webm: image.videoSizeError") + const media = await catalog.openMedia(catalog.state().images[0]) + expect(media.size).toBe(256 * 1024 * 1024) + await media.file.close() + catalog.dispose() + await expect(catalog.openMedia({ id: "file:missing", version: "1" })).rejects.toThrow("missing") + } finally { + catalog.dispose() + await rm(directory, { recursive: true, force: true }) + } +}) + +test("accepts animated image uploads without converting their bytes", () => { + for (const type of ["gif", "webp", "apng"]) { + const data = `data:image/${type};base64,R0lGODlh` + expect(Schema.decodeUnknownSync(StoredImage)(data)).toBe(data) + expect(wallpaperBlob(data).type).toBe(`image/${type}`) + } +}) diff --git a/src/media-server.ts b/src/media-server.ts new file mode 100644 index 0000000..0a5db5b --- /dev/null +++ b/src/media-server.ts @@ -0,0 +1,76 @@ +import { randomBytes } from "node:crypto" +import { createServer } from "node:http" +import { pipeline } from "node:stream/promises" +import { Schema } from "effect" +import { ImageRequest } from "./contract" +import type { createCatalog } from "./catalog" + +const htmlPolicy = "default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval' blob:; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; media-src data: blob:; base-uri 'none'; form-action 'none'; sandbox allow-scripts" + +export async function createWallpaperMediaServer(open: ReturnType["openMedia"]) { + const token = randomBytes(24).toString("hex") + const server = createServer((request, response) => { + void (async () => { + const url = new URL(request.url ?? "", "http://127.0.0.1") + if (url.pathname !== `/${token}` || !["GET", "HEAD"].includes(request.method ?? "")) { + response.writeHead(404).end() + return + } + const input = Schema.decodeUnknownSync(ImageRequest)({ id: url.searchParams.get("id"), version: url.searchParams.get("version") }) + const { file, size, type } = await open(input) + try { + const range = request.headers.range + const match = range ? /^bytes=(\d*)-(\d*)$/.exec(range) : undefined + const start = match ? match[1] ? Number(match[1]) : Math.max(0, size - Number(match[2])) : 0 + const end = match?.[1] && match[2] ? Math.min(size - 1, Number(match[2])) : size - 1 + if (range && (!match || (!match[1] && !match[2]) || start > end || start >= size || !Number.isSafeInteger(start) || !Number.isSafeInteger(end))) { + response.writeHead(416, { "Content-Range": `bytes */${size}` }).end() + return + } + response.writeHead(range ? 206 : 200, { + "Content-Type": type === "text/html" ? "text/html; charset=utf-8" : type, + "Content-Length": end - start + 1, + "Accept-Ranges": "bytes", + "Access-Control-Allow-Origin": "*", + "Cache-Control": "no-store", + "X-Content-Type-Options": "nosniff", + ...(type === "text/html" ? { + "Content-Security-Policy": htmlPolicy, + "Permissions-Policy": "camera=(), microphone=(), geolocation=(), display-capture=(), fullscreen=(), autoplay=()", + "Referrer-Policy": "no-referrer", + } : {}), + ...(range ? { "Content-Range": `bytes ${start}-${end}/${size}` } : {}), + }) + if (request.method === "HEAD") response.end() + else await pipeline(file.createReadStream({ start, end, autoClose: false }), response) + } finally { + await file.close() + } + })().catch(() => { + if (!response.headersSent) response.writeHead(404).end() + else response.destroy() + }) + }) + await new Promise((resolve, reject) => { + server.once("error", reject) + server.listen(0, "127.0.0.1", () => { server.removeListener("error", reject); resolve() }) + }) + const address = server.address() + if (!address || typeof address === "string") throw new Error("Wallpaper media server is unavailable.") + let disposed = false + return { + async source(request: typeof ImageRequest.Type) { + if (disposed) throw new Error("Wallpaper media server is unavailable.") + const media = await open(request) + await media.file.close() + if (disposed) throw new Error("Wallpaper media server is unavailable.") + return `http://127.0.0.1:${address.port}/${token}?${new URLSearchParams(request)}` + }, + dispose() { + if (disposed) return + disposed = true + server.close() + server.closeAllConnections() + }, + } +} diff --git a/src/media.ts b/src/media.ts new file mode 100644 index 0000000..84343cb --- /dev/null +++ b/src/media.ts @@ -0,0 +1,117 @@ +import { createEffect, createMemo, on, onCleanup, type Accessor } from "solid-js" +import { createStore } from "solid-js/store" +import type { WallpaperChoice } from "./model" +import type { WallpaperReader } from "./render" +import { wallpaperPanels } from "./style" +import { thumbnail } from "./image" + +export function createWallpaperMedia(selected: Accessor, read: WallpaperReader) { + const [state, setState] = createStore({ url: "", loading: false, error: "" }) + const source = createMemo(selected, undefined, { + equals: (left, right) => left?.id === right?.id && left?.version === right?.version && left?.kind === right?.kind, + }) + createEffect(on(source, (choice) => { + const controller = new AbortController() + let release: (() => void) | undefined + onCleanup(() => { controller.abort(); release?.() }) + setState({ url: "", loading: !!choice, error: "" }) + if (!choice?.kind) return + void read(choice, controller.signal).then((url) => { + controller.signal.throwIfAborted() + release = mountWallpaperMedia(url, choice.kind!, (error) => { + if (!controller.signal.aborted) setState({ loading: false, error, url: error ? "" : url }) + }) + setState({ url }) + }).catch((error) => { + if (!controller.signal.aborted) setState({ loading: false, error: error instanceof Error ? error.message : String(error) }) + }) + })) + return state +} + +function mountWallpaperMedia(url: string, kind: "video" | "html", loaded: (error: string) => void) { + const element = wallpaperMediaElement(url, kind, loaded) + element.className = "opencode-wallpaper-media" + let frame = 0 + const attach = () => { + frame = 0 + const panel = [...document.querySelectorAll(wallpaperPanels)].findLast((panel) => + panel.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) && panel.getBoundingClientRect().height > 0, + ) + if (element.parentElement === panel) return + element.parentElement?.removeAttribute("data-wallpaper-media") + if (panel) { + panel.setAttribute("data-wallpaper-media", "") + panel.append(element) + if (element instanceof HTMLVideoElement) void element.play().catch(() => {}) + } else { + if (element instanceof HTMLVideoElement) element.pause() + element.remove() + } + } + const schedule = () => { if (!frame) frame = requestAnimationFrame(attach) } + const observer = new MutationObserver(schedule) + observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["class", "style", "hidden", "data-active"] }) + const resized = new ResizeObserver(schedule) + resized.observe(document.body) + window.addEventListener("resize", schedule) + attach() + return () => { + observer.disconnect() + resized.disconnect() + window.removeEventListener("resize", schedule) + cancelAnimationFrame(frame) + element.parentElement?.removeAttribute("data-wallpaper-media") + element.remove() + element.removeAttribute("src") + if (element instanceof HTMLVideoElement) element.load() + } +} + +export function wallpaperMediaElement(url: string, kind: "video" | "html", loaded: (error: string) => void) { + const element = document.createElement(kind === "video" ? "video" : "iframe") + element.setAttribute("aria-hidden", "true") + element.tabIndex = -1 + element.inert = true + element.onerror = () => loaded("image.decodeError") + if (element instanceof HTMLVideoElement) { + element.autoplay = true + element.muted = true + element.loop = true + element.playsInline = true + element.onloadeddata = () => loaded("") + } else { + element.setAttribute("sandbox", "allow-scripts") + element.referrerPolicy = "no-referrer" + element.onload = () => loaded("") + } + element.src = url + return element +} + +export async function videoThumbnailBlob(url: string, signal: AbortSignal) { + signal.throwIfAborted() + const video = document.createElement("video") + video.muted = true + video.preload = "auto" + video.crossOrigin = "anonymous" + const listeners = new AbortController() + const timeout = AbortSignal.timeout(15000) + const lifetime = AbortSignal.any([signal, timeout]) + try { + await new Promise((resolve, reject) => { + video.onloadeddata = () => resolve() + video.onerror = () => reject(new Error("image.decodeError")) + lifetime.addEventListener("abort", () => reject(signal.aborted ? signal.reason : new Error("image.decodeError")), { once: true, signal: listeners.signal }) + lifetime.throwIfAborted() + video.src = url + }) + return await thumbnail(video, video.videoWidth, video.videoHeight, signal) + } finally { + listeners.abort() + video.onloadeddata = null + video.onerror = null + video.removeAttribute("src") + video.load() + } +} diff --git a/src/model.test.ts b/src/model.test.ts index 807db7b..b05f6f5 100644 --- a/src/model.test.ts +++ b/src/model.test.ts @@ -2,12 +2,36 @@ import { describe, expect, test } from "bun:test" import type { Mutable, SelectOptions } from "@opencode/plugin/gui" import { Schema } from "effect" import { wallpaperCommand } from "./command" -import { canRemoveWallpaper, changeWallpaper, checkWallpaperDuplicate, removeWallpaper, selectedWallpaper, setWallpaperEnabled, wallpaperCatalog, wallpaperTitle, type WallpaperChoice } from "./model" +import { canRemoveWallpaper, changeWallpaper, checkWallpaperDuplicate, filterWallpapers, removeWallpaper, sameWallpaper, selectedWallpaper, setWallpaperEnabled, wallpaperCatalog, wallpaperTitle, type WallpaperChoice } from "./model" +import { animatedImage } from "./image" import { Preferences, initial } from "./preferences" const customImage = "data:image/png;base64,aGVsbG8=" const customUpload = { id: "custom", name: "Wallpaper", image: customImage } +test("filters static images separately from videos, HTML and animated image uploads", () => { + const images = wallpaperCatalog([ + { id: "static", title: "Static", version: "1" }, + { id: "video", title: "Video", version: "1", kind: "video" }, + { id: "html", title: "HTML", version: "1", kind: "html" }, + ], { images: [{ id: "upload:gif", name: "fish.gif", image: "data:image/gif;base64,R0lGODlh" }] }) + expect(filterWallpapers(images, "all")).toBe(images) + expect(filterWallpapers(images, "static").map((image) => image.id)).toEqual(["static"]) + expect(filterWallpapers(images, "live").map((image) => image.id)).toEqual(["video", "html", "upload:gif"]) + const webp = new Uint8Array(21) + webp.set(new TextEncoder().encode("VP8X"), 12) + expect(animatedImage(webp, "image/webp")).toBe(false) + webp[20] = 2 + expect(animatedImage(webp, "image/webp")).toBe(true) + const png = new Uint8Array(28) + const view = new DataView(png.buffer) + view.setUint32(8, 8) + view.setUint32(12, 0x6163544c) + view.setUint32(16, 2) + expect(animatedImage(png, "image/png")).toBe(true) + expect(animatedImage(new TextEncoder().encode(''), "image/svg+xml")).toBe(true) +}) + test("resolves only the selected upload or folder image", () => { const settings = { ...initial, enabled: true, preset: "custom", images: [customUpload] } const file = { id: "file:example.png", title: "example", version: "1" } @@ -17,6 +41,15 @@ test("resolves only the selected upload or folder image", () => { expect(selectedWallpaper(selected, images)).toBe(file) }) +test("invalidates cached choices when live metadata or poster versions change", () => { + const choice: WallpaperChoice = { id: "file:pond", title: "Pond", version: "1", kind: "html", poster: { id: "file:poster", version: "1" } } + expect(sameWallpaper(choice, { ...choice })).toBe(true) + expect(sameWallpaper(choice, { ...choice, kind: "video" })).toBe(false) + expect(sameWallpaper(choice, { ...choice, animated: true })).toBe(false) + expect(sameWallpaper(choice, { ...choice, poster: { ...choice.poster!, version: "2" } })).toBe(false) + expect(sameWallpaper(choice, { ...choice, poster: undefined })).toBe(false) +}) + describe("removing wallpapers", () => { const file = { id: "file:example.png", title: "example", version: "1" } diff --git a/src/model.ts b/src/model.ts index e550d8d..22d5bd6 100644 --- a/src/model.ts +++ b/src/model.ts @@ -1,12 +1,23 @@ import type { Wallpaper } from "./contract" -import { imageBytes } from "./image" +import { animatedImage, imageBytes } from "./image" import { initial, type UploadedWallpaper, type WallpaperPreferences } from "./preferences" export type WallpaperChoice = typeof Wallpaper.Type & { readonly image?: string } type SavedImages = Pick export function sameWallpaper(left: WallpaperChoice | undefined, right: WallpaperChoice | undefined) { - return left?.id === right?.id && left?.version === right?.version && left?.image === right?.image + return left?.id === right?.id && left?.version === right?.version && left?.image === right?.image && left?.kind === right?.kind && left?.animated === right?.animated + && left?.poster?.id === right?.poster?.id && left?.poster?.version === right?.poster?.version +} + +export type WallpaperFilter = "all" | "static" | "live" + +export function isLiveWallpaper(choice: WallpaperChoice) { + return !!choice.kind || !!choice.animated +} + +export function filterWallpapers(images: readonly WallpaperChoice[], filter: WallpaperFilter) { + return filter === "all" ? images : images.filter((image) => isLiveWallpaper(image) === (filter === "live")) } export function selectedWallpaper(settings: Pick, images: readonly WallpaperChoice[]) { @@ -24,8 +35,10 @@ export function wallpaperCatalog(images: readonly (typeof Wallpaper.Type)[] = [] ...uploadedWallpapers(settings).map((upload) => { const title = wallpaperName(upload.name) const cached = saved.get(upload.id) - return cached?.image === upload.image && cached.title === title - ? cached : { id: upload.id, title, version: "custom", image: upload.image } + if (cached?.image === upload.image && cached.title === title) return cached + const type = upload.image.slice(5, upload.image.indexOf(";")) + const header = Uint8Array.from(atob(imageBytes(upload.image).slice(0, 87380)), (character) => character.charCodeAt(0)) + return { id: upload.id, title, version: "custom", image: upload.image, ...(animatedImage(header, type) ? { animated: true } : {}) } }), ] } @@ -82,5 +95,5 @@ function filenameKey(name: string) { function wallpaperName(name: string) { const filename = (name.split(/[\\/]/).at(-1) ?? name).trim() - return filename.replace(/\.(?:png|jpe?g|webp|svg)$/i, "") || filename + return filename.replace(/\.(?:png|jpe?g|webp|svg|gif|apng|mp4|webm|html?)$/i, "") || filename } diff --git a/src/picker.tsx b/src/picker.tsx index 21ccb6e..82b5d14 100644 --- a/src/picker.tsx +++ b/src/picker.tsx @@ -1,9 +1,11 @@ import { batch, createMemo, createSignal, createUniqueId, For, onMount, Show, type Accessor } from "solid-js" import { usePlugin, type SelectOptions } from "@opencode/plugin/gui" +import { WallpaperLiveIcon } from "./live-icon" export function WallpaperPicker(props: { options: SelectOptions enabled: Accessor + isLive: (choice: string) => boolean onToggle: (enabled: boolean) => void onSelect: (choice: string) => void }) { @@ -77,10 +79,15 @@ export function WallpaperPicker(props: { class="opencode-wallpaper-picker-choice" tabIndex={-1} aria-selected={active() === index()} + aria-label={option.title} + aria-description={props.isLive(option.value) ? ctx.t("image.live") : undefined} onPointerMove={() => setActive(index())} onFocus={() => setActive(index())} onClick={() => props.onSelect(option.value)} - >{option.title}} + > + {option.title} + + }
{ctx.t("palette.empty")}
diff --git a/src/preferences.test.ts b/src/preferences.test.ts index ef98d2b..123021b 100644 --- a/src/preferences.test.ts +++ b/src/preferences.test.ts @@ -26,6 +26,17 @@ test("rejects duplicate upload identities", () => { expect(() => Schema.decodeUnknownSync(Preferences)({ ...initial, images: [upload, upload] })).toThrow() }) +test("round-trips animated uploads alongside existing images without changing bytes or selection", () => { + const saved = { ...initial, enabled: true, preset: "upload:gif", tint: 42, images: [ + { id: "upload:png", name: "old.png", image: "data:image/png;base64,YWJj" }, + { id: "upload:gif", name: "fish.gif", image: "data:image/gif;base64,R0lGODlh" }, + { id: "upload:apng", name: "fish.apng", image: "data:image/apng;base64,YWJj" }, + ] } + const restored = Schema.decodeUnknownSync(StoredPreferences)(saved) + expect(restored).toEqual(saved) + expect(Schema.decodeUnknownSync(StoredPreferences)(Schema.encodeSync(StoredPreferences)(restored))).toEqual(saved) +}) + test("recovers unrelated persisted fields without dropping legacy or current uploads", () => { const image = "data:image/png;base64,YWJj" const uploaded = { id: "upload:one", name: "one.png", image } diff --git a/src/preview.tsx b/src/preview.tsx new file mode 100644 index 0000000..8b4d789 --- /dev/null +++ b/src/preview.tsx @@ -0,0 +1,37 @@ +import { createEffect, createSignal, on, onCleanup, Show } from "solid-js" +import { wallpaperBlob } from "./image" +import { wallpaperMediaElement } from "./media" +import type { WallpaperChoice } from "./model" +import type { WallpaperReader } from "./render" + +export function WallpaperPreview(props: { choice: WallpaperChoice; read: WallpaperReader }) { + const [element, setElement] = createSignal() + createEffect(on(() => props.choice, (choice) => { + const controller = new AbortController() + let preview: ReturnType + let url = "" + setElement(undefined) + onCleanup(() => { + controller.abort() + preview?.removeAttribute("src") + if (preview instanceof HTMLVideoElement) preview.load() + if (url) URL.revokeObjectURL(url) + }) + void Promise.resolve(choice.image ?? props.read(choice, controller.signal)).then((source) => { + controller.signal.throwIfAborted() + const loaded = (error = "") => { if (!error && preview) preview.style.opacity = "1" } + if (choice.kind) preview = wallpaperMediaElement(source, choice.kind, loaded) + else { + preview = new Image() + preview.alt = "" + preview.onload = () => loaded() + url = URL.createObjectURL(wallpaperBlob(source)) + preview.src = url + } + preview.className = "opencode-wallpaper-preview-media" + preview.style.opacity = "0" + setElement(preview) + }).catch(() => {}) + })) + return {(element) => element()} +} diff --git a/src/settings.css b/src/settings.css index 28eeb49..0316b45 100644 --- a/src/settings.css +++ b/src/settings.css @@ -66,6 +66,13 @@ gap: 8px; } +.opencode-wallpaper-gallery-controls { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8px; +} + .opencode-wallpaper-gallery button { padding: 4px; border-radius: 6px; @@ -136,14 +143,49 @@ overflow: hidden; } -.opencode-wallpaper-gallery span, +.opencode-wallpaper-thumbnail { + position: relative; + border-radius: 3px; + font-size: 12px; +} + +.opencode-wallpaper-gallery .opencode-wallpaper-preview-media { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + border: 0; + border-radius: inherit; + object-fit: cover; + pointer-events: none; +} + +.opencode-wallpaper-gallery .opencode-wallpaper-caption, .opencode-wallpaper-gallery .opencode-wallpaper-add::after { - display: block; padding: 5px 2px 1px; font-size: 12px; overflow-wrap: anywhere; } +.opencode-wallpaper-caption { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.opencode-wallpaper-live-icon { + width: 16px; + height: 16px; + flex-shrink: 0; + color: var(--v2-icon-icon-muted); +} + +.opencode-wallpaper-gallery-empty { + color: var(--v2-text-text-muted); + font-size: 12px; +} + .opencode-wallpaper-folder { overflow-wrap: anywhere; } @@ -165,6 +207,7 @@ } .opencode-wallpaper-gallery .opencode-wallpaper-add::after { + display: block; content: "\00a0"; } diff --git a/src/settings.tsx b/src/settings.tsx index 2e7f709..73b7e76 100644 --- a/src/settings.tsx +++ b/src/settings.tsx @@ -1,12 +1,14 @@ import { createMemo, createRenderEffect, createSignal, createUniqueId, For, on, onCleanup, onMount, Show, type Accessor } from "solid-js" import { usePlugin } from "@opencode/plugin/gui" import type definition from "./gui" -import { canRemoveWallpaper, changeWallpaper, checkWallpaperDuplicate, removeWallpaper, wallpaperTitle, type WallpaperChoice } from "./model" +import { canRemoveWallpaper, changeWallpaper, checkWallpaperDuplicate, filterWallpapers, isLiveWallpaper, removeWallpaper, wallpaperTitle, type WallpaperChoice, type WallpaperFilter } from "./model" import { uploadImage } from "./image" import { appearanceControls, appearanceKeys, slideshowControls, wallpaperAppearance, type WallpaperTransition } from "./preferences" import type { ThumbnailCache } from "./thumbnail-cache" import { WallpaperThumbnail } from "./thumbnail" import { WallpaperGalleryToggle } from "./gallery-toggle" +import { WallpaperLiveIcon } from "./live-icon" +import type { WallpaperReader } from "./render" export function WallpaperSettings(props: { images: Accessor @@ -14,6 +16,7 @@ export function WallpaperSettings(props: { select: (choice: string) => void setEnabled: (enabled: boolean) => void thumbnails: ThumbnailCache + read: WallpaperReader folder: Accessor changeFolder: (folder: string, signal: AbortSignal) => Promise }) { @@ -23,12 +26,17 @@ export function WallpaperSettings(props: { const [folderRequest, setFolderRequest] = createSignal() const [expanded, setExpanded] = createSignal(false) const [columns, setColumns] = createSignal(1) + const [filter, setFilter] = createSignal("all") + const [hovered, setHovered] = createSignal() + const [focused, setFocused] = createSignal() + const preview = () => hovered() ?? focused() const galleryId = createUniqueId() let gallery!: HTMLDivElement let fileInput!: HTMLInputElement const appearance = createMemo(() => wallpaperAppearance(settings.value)) const limit = () => columns() * 2 - 1 - const visibleImages = createMemo(() => expanded() ? props.images() : props.images().slice(0, limit())) + const filtered = createMemo(() => filterWallpapers(props.images(), filter())) + const visibleImages = createMemo(() => expanded() ? filtered() : filtered().slice(0, limit())) onMount(() => { const measure = () => { const tracks = getComputedStyle(gallery).gridTemplateColumns @@ -124,15 +132,23 @@ export function WallpaperSettings(props: { {ctx.t("preset.title")} - - label={ctx.t("fit.title")} - value={settings.value.fit} - options={[ - { value: "cover", label: ctx.t("fit.cover") }, - { value: "contain", label: ctx.t("fit.contain") }, - ]} - onChange={(value) => settings.update((draft) => { draft.fit = value })} - /> + }> - limit()}> + + limit()}> } > - void chooseFolder()}> + { void chooseFolder() }}> {ctx.t("folders.choose")}