Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
# OpenCode Backdrop

<p>Use your own wallpapers in OpenCode Desktop. Supports OpenCode 2.2.6 and later 2.2.x versions through the GUI plugin API.</p>
<p>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.</p>
<img width="3020" height="1910" alt="image" src="https://github.com/user-attachments/assets/8d1626f2-7048-496c-8aa9-7745f19e1531" />

## Install

```sh
opencode plugin add 'github:viralcodex/opencode-backdrop#v0.1.0'
opencode plugin add 'github:viralcodex/opencode-backdrop#v0.2.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`.

```jsonc
{
"$schema": "https://opencode.ai/config.json",
"plugins": ["github:viralcodex/opencode-backdrop#v0.1.0"],
"plugins": ["github:viralcodex/opencode-backdrop#v0.2.0"],
}
```

Expand All @@ -28,9 +28,11 @@ Wallpaper starts off with an empty gallery. Images and preferences stay local, a

- 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.
- 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.

To remove an upload, hover or focus its tile and click **X**. Remove folder images by moving or deleting their source files.

Expand All @@ -43,7 +45,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.1.0",
"package": "github:viralcodex/opencode-backdrop#v0.2.0",
"options": { "folder": "/absolute/path/to/wallpapers" },
},
],
Expand Down
2 changes: 1 addition & 1 deletion bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 21 additions & 9 deletions dist/gui-experimental.cjs

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "opencode-backdrop",
"version": "0.1.0",
"version": "0.2.0",
"description": "Use your own local wallpapers in OpenCode Desktop",
"type": "module",
"license": "MIT",
Expand Down Expand Up @@ -31,10 +31,10 @@
"check": "bun run test && bun run typecheck && bun run build:gui && bun run check:package",
"check:package": "bun script/check-package.ts",
"typecheck": "tsc --noEmit",
"test": "bun test src"
"test": "bun test --conditions=browser src"
},
"peerDependencies": {
"@opencode/plugin": "~2.2.6 || ^0.0.0-dev",
"@opencode/plugin": "~2.2.6 || ~2.3.2 || ^0.0.0-dev",
"effect": "^4.1.0",
"solid-js": "^1.9.17"
},
Expand Down
2 changes: 1 addition & 1 deletion script/check-package.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ for (const [name, version] of [manifest.devDependencies, manifest.peerDependenci
assert(!/^(?:link:|file:|workspace:)/.test(version), `Local dependency cannot be published: ${name}`)
}

// Ignore lifecycle scripts here: prepack runs this check itself.
// Ignore lifecycle scripts during package inspection.
const result = Bun.spawn(["npm", "pack", "--dry-run", "--ignore-scripts", "--json"], {
cwd: fileURLToPath(new URL("..", import.meta.url)),
stdout: "pipe",
Expand Down
24 changes: 0 additions & 24 deletions src/catalog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import { afterEach, expect, jest, test } from "bun:test"
import { mkdir, mkdtemp, realpath, rm, symlink, truncate } from "node:fs/promises"
import os from "node:os"
import path from "node:path"
import { Schema } from "effect"
import { createCatalog, wallpaperFolder, wallpaperFolderLabel } from "./catalog"
import { Catalog } from "./contract"
import { selectedWallpaper, wallpaperCatalog } from "./model"
import { initial } from "./preferences"

Expand Down Expand Up @@ -66,26 +64,6 @@ test("loads selected bytes on demand and retains selection through edits, remova
expect(await catalog.read(selected()!)).toContain(Buffer.from(svg).toString("base64"))
})

test("round-trips filesystem images through the catalog IPC codecs", async () => {
const directory = await fixture()
await Bun.write(path.join(directory, "wall.svg"), svg)
await Bun.write(path.join(directory, "pixel.png"), pixel)
const catalog = tracked(directory)
await catalog.refresh()
const wire = (value: unknown): unknown => JSON.parse(JSON.stringify(value))
const state = Schema.decodeUnknownSync(Catalog.spec.state)(
wire(Schema.encodeUnknownSync(Catalog.spec.state)(catalog.state())),
)
const method = Catalog.spec.methods.read
for (const image of state.images) {
const request = Schema.decodeUnknownSync(method.input)(wire(Schema.encodeUnknownSync(method.input)(image)))
const source = Schema.decodeUnknownSync(method.output)(
wire(Schema.encodeUnknownSync(method.output)(await catalog.read(request))),
)
expect(Buffer.from(source.split(",")[1]!, "base64")).toEqual(image.title === "pixel" ? pixel : Buffer.from(svg))
}
})

test("keeps the catalog small for an 8 MiB image and excludes empty or oversized files", async () => {
const directory = await fixture()
await Bun.write(path.join(directory, "pixel.png"), pixel)
Expand All @@ -97,8 +75,6 @@ test("keeps the catalog small for an 8 MiB image and excludes empty or oversized
await catalog.refresh()
expect(catalog.state().images.map((image) => image.title)).toEqual(["pixel"])
expect(Buffer.byteLength(JSON.stringify(catalog.state()))).toBeLessThan(4096)
expect(catalog.state().error).toContain("empty.svg")
expect(catalog.state().error).toContain("large.svg")
expect(catalog.state().error).toBe("empty.svg: image.sizeError\nlarge.svg: image.sizeError")
const image = catalog.state().images[0]!
expect(Buffer.from((await catalog.read(image)).split(",")[1]!, "base64").length).toBe(8 * 1024 * 1024)
Expand Down
19 changes: 7 additions & 12 deletions src/command.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import type { Command, Context, Persisted } from "@opencode/plugin/gui"
import { changeWallpaper, wallpaperTitle, type WallpaperChoice } from "./model"
import type { WallpaperPreferences } from "./preferences"
import type { Command, Context } from "@opencode/plugin/gui"
import { wallpaperTitle, type WallpaperChoice } from "./model"

export function wallpaperCommand(
ctx: Pick<Context, "t" | "signal"> & {
stores: {
preferences: Pick<Persisted<WallpaperPreferences, WallpaperPreferences>, "value" | "update">
}
dialogs: Pick<Context["dialogs"], "select">
layout: Pick<Context["layout"], "settings">
},
images: () => readonly WallpaperChoice[],
refresh: () => Promise<boolean>,
current: () => string,
select: (choice: string) => void,
): Command {
return {
id: "choose",
Expand All @@ -23,11 +21,10 @@ export function wallpaperCommand(
if (ctx.signal.aborted) return
await refresh()
if (ctx.signal.aborted) return
const preferences = ctx.stores.preferences
const choice = await ctx.dialogs.select<typeof preferences.value.preset | "off" | "settings">({
const choice = await ctx.dialogs.select<string>({
title: ctx.t("picker.title"),
placeholder: ctx.t("picker.search"),
current: preferences.value.enabled ? preferences.value.preset : "off",
current: current(),
options: [
...images().map((preset) => ({
title: wallpaperTitle(preset, ctx.t),
Expand All @@ -42,9 +39,7 @@ export function wallpaperCommand(
ctx.layout.settings("wallpaper")
return
}
preferences.update((draft) => {
changeWallpaper(draft, choice)
})
select(choice)
},
}
}
1 change: 0 additions & 1 deletion src/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,4 @@ test("image failures are shared across the active image and thumbnails, but new
expect(shown).toHaveLength(1)
report("image:example:2", "Wallpapers", ["Unreadable image"])
expect(shown).toHaveLength(2)
expect(shown.every((toast) => toast.variant === "error" && toast.persistent !== true)).toBe(true)
})
65 changes: 50 additions & 15 deletions src/gui.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import { Command, Plugin, SettingsPage, Store, Style } from "@opencode/plugin/gui"
import { createEffect, createMemo, onCleanup } from "solid-js"
import { Command, Plugin, SettingsPage, Store } from "@opencode/plugin/gui"
import { batch, createEffect, createMemo, createSignal, onCleanup } from "solid-js"
import { Schema } from "effect"
import { wallpaperCommand } from "./command"
import { Catalog } from "./contract"
import { selectedWallpaper, wallpaperCatalog, wallpaperTitle, type WallpaperChoice } from "./model"
import { appearanceKeys, Preferences, initial } from "./preferences"
import { changeWallpaper, wallpaperCatalog, wallpaperTitle, type WallpaperChoice } from "./model"
import { appearanceKeys, Preferences, initial, slideshowControls, wallpaperFadeDuration } from "./preferences"
import { createWallpaperImage, type WallpaperReader } from "./render"
import { imageError, thumbnailBlob } from "./image"
import { createWallpaperErrorReporter } from "./errors"
import { createThumbnailCache } from "./thumbnail-cache"
import { alignWallpaperHeaders } from "./backdrop"
import { wallpaperCanvasStyle, wallpaperLayers, wallpaperVariableStyle } from "./style"
import { wallpaperCanvasStyle, wallpaperVariableStyle } from "./style"
import { WallpaperSettings } from "./settings"
import { createWallpaperSlideshow } from "./slideshow"
import { fadeWallpaper, wallpaperTransitionStyle } from "./transition"
import en from "./i18n/en"
import css from "./settings.css?inline"

Expand Down Expand Up @@ -86,14 +88,28 @@ export default Plugin.define({
wallpaperCatalog(catalog?.state()?.images, ctx.stores.preferences.value, previous),
[],
)
const selected = createMemo(() =>
ctx.stores.preferences.value.enabled ? selectedWallpaper(ctx.stores.preferences.value, images()) : undefined,
const settings = ctx.stores.preferences
const slideshow = createWallpaperSlideshow(() => settings.value, images, () =>
!image.loading && !image.previous && (!!image.url || !!image.error),
)
const selected = slideshow.selected
const select = (choice: string) => batch(() => {
slideshow.reset()
settings.update((draft) => { changeWallpaper(draft, choice) })
})
const motion = window.matchMedia("(prefers-reduced-motion: reduce)")
const [reducedMotion, setReducedMotion] = createSignal(motion.matches)
const motionChanged = () => setReducedMotion(motion.matches)
motion.addEventListener("change", motionChanged)
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 image = createWallpaperImage(selected, read)
const image = createWallpaperImage(selected, read, () =>
settings.value.slideshow && (settings.value.transition ?? slideshowControls.transition) === "fade" && !reducedMotion()
? wallpaperFadeDuration : 0,
)
const reportImage = (choice: WallpaperChoice, error: string) => report(
`image:${choice.id}:${choice.version}`, ctx.t("title"),
[`${wallpaperTitle(choice, ctx.t)}: ${imageError(error, ctx.t)}`],
Expand All @@ -120,30 +136,49 @@ export default Plugin.define({
report(`missing:${preferences.preset}`, ctx.t("title"), [ctx.t("folders.missing")])
}
})
ctx.add(Style, css + wallpaperLayers(".opencode-wallpaper-preview"))
ctx.add(Style, () => ctx.stores.preferences.value.enabled && image.url ? wallpaperCanvasStyle : "")
ctx.add(Style, () => wallpaperVariableStyle(ctx.stores.preferences.value, image.url))
const settingsStyle = document.createElement("style")
const canvasStyle = document.createElement("style")
const imageStyle = document.createElement("style")
settingsStyle.dataset.wallpaperStyle = "settings"
canvasStyle.dataset.wallpaperStyle = "canvas"
imageStyle.dataset.wallpaperStyle = "image"
settingsStyle.textContent = css
canvasStyle.textContent = wallpaperCanvasStyle + wallpaperTransitionStyle
canvasStyle.disabled = true
document.head.append(settingsStyle, canvasStyle, imageStyle)
onCleanup(() => { settingsStyle.remove(); canvasStyle.remove(); imageStyle.remove() })
createEffect(() => {
const variables = wallpaperVariableStyle(settings.value, image.url)
imageStyle.textContent = variables
canvasStyle.disabled = !variables
})
createEffect(() => {
if (!image.url || !image.width || !image.height) return
onCleanup(alignWallpaperHeaders({ image: { width: image.width, height: image.height }, fit: ctx.stores.preferences.value.fit }))
})
createEffect(() => {
const previous = image.previous
if (!previous || reducedMotion() || !settings.value.enabled || !settings.value.slideshow || settings.value.transition === "none") return
onCleanup(fadeWallpaper(previous, settings.value.fit, image.transition))
})
ctx.add(SettingsPage, {
id: "wallpaper",
icon: "outline-photo",
get title() {
return ctx.t("title")
},
get entries() {
return ["enabled", ...(ctx.desktop ? ["folders"] : []), "preset", ...appearanceKeys].map((id) => ({
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",
keywords: "wallpaper background image upload fit folder tint brightness contrast slideshow transition fade duration seconds",
}))
},
render: () => (
<WallpaperSettings
images={images}
image={image}
selected={selected}
select={select}
thumbnails={thumbnails}
folder={() => catalog?.state()?.folderLabel ?? catalog?.state()?.folder ?? ""}
changeFolder={async (folder, signal) => {
Expand All @@ -169,7 +204,7 @@ export default Plugin.define({
if (!ctx.signal.aborted) report("refresh", ctx.t("folders.title"), [String(error)])
return false
}
}),
}, () => settings.value.enabled ? selected()?.id ?? settings.value.preset : "off", select),
)
},
})
10 changes: 10 additions & 0 deletions src/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ export default {
description: "Backdrops that suit your style",
"enabled.title": "Show wallpaper",
"preset.title": "Choose a wallpaper",
"gallery.showMore": "Show more",
"gallery.showLess": "Show less",
"picker.title": "Choose wallpaper",
"picker.description": "Choose a background without leaving the conversation.",
"picker.search": "Search wallpapers",
Expand Down Expand Up @@ -31,4 +33,12 @@ export default {
"fit.title": "Image fit",
"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.",
"transition.title": "Wallpaper transition",
"transition.description": "Choose how wallpapers change. Fade respects reduced-motion settings.",
"transition.none": "None",
"transition.fade": "Fade",
"duration.title": "Display time",
"duration.description": "Seconds each wallpaper stays on screen (5 - 86400).",
}
4 changes: 2 additions & 2 deletions src/image.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test"
import { Schema } from "effect"
import { checkImage, wallpaperBlob } from "./image"
import { Preferences, initial } from "./preferences"
import { wallpaperStyle } from "./style"
import { wallpaperVariableStyle } from "./style"

describe("local wallpaper images", () => {
test("accepts supported uploads at the size limit and rejects invalid types or sizes", () => {
Expand Down Expand Up @@ -43,7 +43,7 @@ describe("local wallpaper images", () => {
const blob = wallpaperBlob(image)
const url = URL.createObjectURL(blob)
try {
const css = wallpaperStyle({ ...initial, enabled: true, preset: "file:large.png" }, url)
const css = wallpaperVariableStyle({ ...initial, enabled: true, preset: "file:large.png" }, url)
expect(css).toContain(`url(${JSON.stringify(url)})`)
expect(css.length).toBeLessThan(16 * 1024)
expect(css).not.toContain(image)
Expand Down
Loading