support new APIs fully

This commit is contained in:
AAGaming 2024-06-13 18:11:44 -04:00
parent cbd489150f
commit b939274d15
No known key found for this signature in database
GPG key ID: 00CFCD925A3E0C50
10 changed files with 1062 additions and 383 deletions

2
.vscode/build.sh vendored
View file

@ -7,4 +7,4 @@ printf "Please input sudo password to proceed.\n"
# printf "\n" # printf "\n"
echo $sudopass | sudo $CLI_LOCATION/decky plugin build $(pwd) echo $sudopass | sudo -E $CLI_LOCATION/decky plugin build $(pwd)

4
.vscode/tasks.json vendored
View file

@ -131,8 +131,8 @@
"label": "updatefrontendlib", "label": "updatefrontendlib",
"type": "shell", "type": "shell",
"group": "build", "group": "build",
"detail": "Update deck-frontend-lib aka DFL", "detail": "Update @decky/ui aka DFL",
"command": "pnpm update decky-frontend-lib --latest", "command": "pnpm update @decky/ui --latest",
"problemMatcher": [] "problemMatcher": []
}, },
//Used chmod plugins folder to allow copy-over of files //Used chmod plugins folder to allow copy-over of files

View file

@ -12,10 +12,12 @@ Some basic migration helpers are available: `migrate_any`, `migrate_settings`, `
A logging facility `logger` is available which writes to the recommended location. A logging facility `logger` is available which writes to the recommended location.
""" """
__version__ = '0.1.0' __version__ = '1.0.0'
import logging import logging
from typing import Any
""" """
Constants Constants
""" """
@ -50,7 +52,6 @@ Environment variable: `DECKY_USER`.
e.g.: `deck` e.g.: `deck`
""" """
DECKY_USER_HOME: str DECKY_USER_HOME: str
""" """
The home of the user where decky resides in. The home of the user where decky resides in.
@ -172,3 +173,12 @@ Logging
logger: logging.Logger logger: logging.Logger
"""The main plugin logger writing to `DECKY_PLUGIN_LOG`.""" """The main plugin logger writing to `DECKY_PLUGIN_LOG`."""
"""
Event handling
"""
# TODO better docstring im lazy
async def emit(event: str, *args: Any) -> None:
"""
Send an event to the frontend.
"""

50
main.py
View file

@ -1,41 +1,49 @@
import os import os
# The decky plugin module is located at decky-loader/plugin # The decky plugin module is located at decky-loader/plugin
# For easy intellisense checkout the decky-loader code one directory up # For easy intellisense checkout the decky-loader code repo
# or add the `decky-loader/plugin` path to `python.analysis.extraPaths` in `.vscode/settings.json` # and add the `decky-loader/plugin/imports` path to `python.analysis.extraPaths` in `.vscode/settings.json`
import decky_plugin import decky
import asyncio
class Plugin: class Plugin:
# A normal method. It can be called from JavaScript using call_plugin_function("method_1", argument1, argument2) # A normal method. It can be called from the TypeScript side using @decky/api.
async def add(self, left, right): async def add(self, left: int, right: int) -> int:
return left + right return left + right
async def long_running(self):
await asyncio.sleep(15)
await decky.emit("test_event", "Hello from the backend!", True, 2)
# Asyncio-compatible long-running code, executed in a task when the plugin is loaded # Asyncio-compatible long-running code, executed in a task when the plugin is loaded
async def _main(self): async def _main(self):
decky_plugin.logger.info("Hello World!") self.loop = asyncio.get_event_loop()
decky.logger.info("Hello World!")
# Function called first during the unload process, utilize this to handle your plugin being removed # Function called first during the unload process, utilize this to handle your plugin being removed
async def _unload(self): async def _unload(self):
decky_plugin.logger.info("Goodbye World!") decky.logger.info("Goodbye World!")
pass pass
async def start_timer(self):
self.loop.create_task(self.long_running())
# Migrations that should be performed before entering `_main()`. # Migrations that should be performed before entering `_main()`.
async def _migration(self): async def _migration(self):
decky_plugin.logger.info("Migrating") decky.logger.info("Migrating")
# Here's a migration example for logs: # Here's a migration example for logs:
# - `~/.config/decky-template/template.log` will be migrated to `decky_plugin.DECKY_PLUGIN_LOG_DIR/template.log` # - `~/.config/decky-template/template.log` will be migrated to `decky.decky_LOG_DIR/template.log`
decky_plugin.migrate_logs(os.path.join(decky_plugin.DECKY_USER_HOME, decky.migrate_logs(os.path.join(decky.DECKY_USER_HOME,
".config", "decky-template", "template.log")) ".config", "decky-template", "template.log"))
# Here's a migration example for settings: # Here's a migration example for settings:
# - `~/homebrew/settings/template.json` is migrated to `decky_plugin.DECKY_PLUGIN_SETTINGS_DIR/template.json` # - `~/homebrew/settings/template.json` is migrated to `decky.decky_SETTINGS_DIR/template.json`
# - `~/.config/decky-template/` all files and directories under this root are migrated to `decky_plugin.DECKY_PLUGIN_SETTINGS_DIR/` # - `~/.config/decky-template/` all files and directories under this root are migrated to `decky.decky_SETTINGS_DIR/`
decky_plugin.migrate_settings( decky.migrate_settings(
os.path.join(decky_plugin.DECKY_HOME, "settings", "template.json"), os.path.join(decky.DECKY_HOME, "settings", "template.json"),
os.path.join(decky_plugin.DECKY_USER_HOME, ".config", "decky-template")) os.path.join(decky.DECKY_USER_HOME, ".config", "decky-template"))
# Here's a migration example for runtime data: # Here's a migration example for runtime data:
# - `~/homebrew/template/` all files and directories under this root are migrated to `decky_plugin.DECKY_PLUGIN_RUNTIME_DIR/` # - `~/homebrew/template/` all files and directories under this root are migrated to `decky.decky_RUNTIME_DIR/`
# - `~/.local/share/decky-template/` all files and directories under this root are migrated to `decky_plugin.DECKY_PLUGIN_RUNTIME_DIR/` # - `~/.local/share/decky-template/` all files and directories under this root are migrated to `decky.decky_RUNTIME_DIR/`
decky_plugin.migrate_runtime( decky.migrate_runtime(
os.path.join(decky_plugin.DECKY_HOME, "template"), os.path.join(decky.DECKY_HOME, "template"),
os.path.join(decky_plugin.DECKY_USER_HOME, ".local", "share", "decky-template")) os.path.join(decky.DECKY_USER_HOME, ".local", "share", "decky-template"))

View file

@ -2,6 +2,7 @@
"name": "decky-plugin-template", "name": "decky-plugin-template",
"version": "0.0.1", "version": "0.0.1",
"description": "A template to quickly create decky plugins from scratch, based on TypeScript and webpack", "description": "A template to quickly create decky plugins from scratch, based on TypeScript and webpack",
"type": "module",
"scripts": { "scripts": {
"build": "shx rm -rf dist && rollup -c", "build": "shx rm -rf dist && rollup -c",
"watch": "rollup -c -w", "watch": "rollup -c -w",
@ -18,29 +19,33 @@
"steam-deck", "steam-deck",
"deck" "deck"
], ],
"author": "Jonas Dellinger <jonas@dellinger.dev>", "author": "You <you@you.tld>",
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"bugs": { "bugs": {
"url": "https://github.com/SteamDeckHomebrew/decky-plugin-template/issues" "url": "https://github.com/SteamDeckHomebrew/decky-plugin-template/issues"
}, },
"homepage": "https://github.com/SteamDeckHomebrew/decky-plugin-template#readme", "homepage": "https://github.com/SteamDeckHomebrew/decky-plugin-template#readme",
"devDependencies": { "devDependencies": {
"@rollup/plugin-commonjs": "^21.1.0", "@rollup/plugin-commonjs": "^26.0.1",
"@rollup/plugin-json": "^4.1.0", "@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "^13.3.0", "@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-replace": "^4.0.0", "@rollup/plugin-replace": "^5.0.7",
"@rollup/plugin-typescript": "^8.3.3", "@rollup/plugin-typescript": "^11.1.6",
"@types/react": "16.14.0", "@types/react": "18.3.3",
"@types/webpack": "^5.28.0", "@types/react-dom": "18.3.0",
"rollup": "^2.77.1", "@types/webpack": "^5.28.5",
"rollup": "^4.18.0",
"rollup-plugin-delete": "^2.0.0",
"rollup-plugin-external-globals": "^0.10.0",
"rollup-plugin-import-assets": "^1.1.1", "rollup-plugin-import-assets": "^1.1.1",
"shx": "^0.3.4", "shx": "^0.3.4",
"tslib": "^2.4.0", "tslib": "^2.6.3",
"typescript": "^4.7.4" "typescript": "^5.4.5"
}, },
"dependencies": { "dependencies": {
"decky-frontend-lib": "^3.24.5", "@decky/api": "^1.0.4",
"react-icons": "^4.4.0" "@decky/ui": "^4.0.2",
"react-icons": "^5.2.1"
}, },
"pnpm": { "pnpm": {
"peerDependencyRules": { "peerDependencyRules": {

View file

@ -2,6 +2,7 @@
"name": "Example Plugin", "name": "Example Plugin",
"author": "John Doe", "author": "John Doe",
"flags": ["debug", "_root"], "flags": ["debug", "_root"],
"api_version": 1,
"publish": { "publish": {
"tags": ["template", "root"], "tags": ["template", "root"],
"description": "Decky example plugin.", "description": "Decky example plugin.",

File diff suppressed because it is too large Load diff

View file

@ -4,15 +4,27 @@ import { nodeResolve } from '@rollup/plugin-node-resolve';
import replace from '@rollup/plugin-replace'; import replace from '@rollup/plugin-replace';
import typescript from '@rollup/plugin-typescript'; import typescript from '@rollup/plugin-typescript';
import { defineConfig } from 'rollup'; import { defineConfig } from 'rollup';
import del from 'rollup-plugin-delete';
import importAssets from 'rollup-plugin-import-assets'; import importAssets from 'rollup-plugin-import-assets';
import externalGlobals from 'rollup-plugin-external-globals';
import { name } from "./plugin.json"; // replace "assert" with "with" once node implements that
import manifest from './plugin.json' assert { type: 'json' };
export default defineConfig({ export default defineConfig({
input: './src/index.tsx', input: './src/index.tsx',
plugins: [ plugins: [
del({ targets: './dist/*', force: true }),
commonjs(), commonjs(),
nodeResolve(), nodeResolve({
browser: true
}),
externalGlobals({
react: 'SP_REACT',
'react-dom': 'SP_REACTDOM',
'@decky/ui': 'DFL',
'@decky/manifest': JSON.stringify(manifest)
}),
typescript(), typescript(),
json(), json(),
replace({ replace({
@ -20,19 +32,18 @@ export default defineConfig({
'process.env.NODE_ENV': JSON.stringify('production'), 'process.env.NODE_ENV': JSON.stringify('production'),
}), }),
importAssets({ importAssets({
publicPath: `http://127.0.0.1:1337/plugins/${name}/` publicPath: `http://127.0.0.1:1337/plugins/${manifest.name}/`
}) })
], ],
context: 'window', context: 'window',
external: ["react", "react-dom", "decky-frontend-lib"], external: ['react', 'react-dom', '@decky/ui'],
output: { output: {
file: "dist/index.js", dir: 'dist',
globals: { format: 'esm',
react: "SP_REACT", sourcemap: true,
"react-dom": "SP_REACTDOM", // **Don't** change this.
"decky-frontend-lib": "DFL" sourcemapPathTransform: (relativeSourcePath) => relativeSourcePath.replace(/^\.\.\//, `decky://decky/plugin/${encodeURIComponent(manifest.name)}/`),
}, exports: 'default'
format: 'iife',
exports: 'default',
}, },
}); });

View file

@ -1,67 +1,63 @@
import { import {
ButtonItem, ButtonItem,
definePlugin,
DialogButton,
Menu,
MenuItem,
Navigation,
PanelSection, PanelSection,
PanelSectionRow, PanelSectionRow,
ServerAPI, Router,
showContextMenu, // ServerAPI,
staticClasses, staticClasses,
} from "decky-frontend-lib"; } from "@decky/ui";
import { VFC } from "react"; import {
addEventListener,
removeEventListener,
callable,
definePlugin,
toaster,
// routerHook
} from "@decky/api"
// import { call, callable } from "@decky/backend";
import { useState } from "react";
import { FaShip } from "react-icons/fa"; import { FaShip } from "react-icons/fa";
import logo from "../assets/logo.png"; // import logo from "../assets/logo.png";
// interface AddMethodArgs { // interface AddMethodArgs {
// left: number; // left: number;
// right: number; // right: number;
// } // }
const add = callable<[first: number, second: number], number>("add");
const startTimer = callable<[], void>("start_timer");
function Content() {
const [result, setResult] = useState<number | undefined>();
const Content: VFC<{ serverAPI: ServerAPI }> = ({serverAPI}) => { const onClick = async () => {
// const [result, setResult] = useState<number | undefined>(); const result = await add(Math.random(), Math.random());
setResult(result);
// const onClick = async () => { };
// const result = await serverAPI.callPluginMethod<AddMethodArgs, number>(
// "add",
// {
// left: 2,
// right: 2,
// }
// );
// if (result.success) {
// setResult(result.result);
// }
// };
return ( return (
<PanelSection title="Panel Section"> <PanelSection title="Panel Section">
<PanelSectionRow> <PanelSectionRow>
<ButtonItem <ButtonItem
layout="below" layout="below"
onClick={(e) => onClick={onClick}
showContextMenu(
<Menu label="Menu" cancelText="CAAAANCEL" onCancel={() => {}}>
<MenuItem onSelected={() => {}}>Item #1</MenuItem>
<MenuItem onSelected={() => {}}>Item #2</MenuItem>
<MenuItem onSelected={() => {}}>Item #3</MenuItem>
</Menu>,
e.currentTarget ?? window
)
}
> >
Server says yolo {result || "Add two numbers via Python"}
</ButtonItem>
</PanelSectionRow>
<PanelSectionRow>
<ButtonItem
layout="below"
onClick={() => startTimer()}
>
{"Start Python timer"}
</ButtonItem> </ButtonItem>
</PanelSectionRow> </PanelSectionRow>
<PanelSectionRow> {/* <PanelSectionRow>
<div style={{ display: "flex", justifyContent: "center" }}> <div style={{ display: "flex", justifyContent: "center" }}>
<img src={logo} /> <img src={logo} />
</div> </div>
</PanelSectionRow> </PanelSectionRow> */}
<PanelSectionRow> <PanelSectionRow>
<ButtonItem <ButtonItem
@ -78,28 +74,30 @@ const Content: VFC<{ serverAPI: ServerAPI }> = ({serverAPI}) => {
); );
}; };
const DeckyPluginRouterTest: VFC = () => { export default definePlugin(() => {
return ( // serverApi.routerHook.addRoute("/decky-plugin-test", DeckyPluginRouterTest, {
<div style={{ marginTop: "50px", color: "white" }}> // exact: true,
Hello World! // });
<DialogButton onClick={() => Navigation.NavigateToLibraryTab()}> // console.log("init plugin", call, callable)
Go to Library const listener = addEventListener<[
</DialogButton> test1: string,
</div> test2: boolean,
); test3: number
}; ]>("test_event", (test1, test2, test3) => {
console.log("Template got event", test1, test2, test3)
export default definePlugin((serverApi: ServerAPI) => { toaster.toast({
serverApi.routerHook.addRoute("/decky-plugin-test", DeckyPluginRouterTest, { title: "template got event",
exact: true, body: `${test1}, ${test2}, ${test3}`
});
}); });
return { return {
title: <div className={staticClasses.Title}>Example Plugin</div>, title: <div className={staticClasses.Title}>API v2 Example Plugin</div>,
content: <Content serverAPI={serverApi} />, content: <Content />,
icon: <FaShip />, icon: <FaShip />,
onDismount() { onDismount() {
serverApi.routerHook.removeRoute("/decky-plugin-test"); console.log("Unloading")
removeEventListener("test_event", listener);
// serverApi.routerHook.removeRoute("/decky-plugin-test");
}, },
}; };
}); });

View file

@ -15,9 +15,7 @@
"noImplicitThis": true, "noImplicitThis": true,
"noImplicitAny": true, "noImplicitAny": true,
"strict": true, "strict": true,
"suppressImplicitAnyIndexErrors": true, "allowSyntheticDefaultImports": true
"allowSyntheticDefaultImports": true,
"skipLibCheck": true
}, },
"include": ["src"], "include": ["src"],
"exclude": ["node_modules"] "exclude": ["node_modules"]