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"
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",
"type": "shell",
"group": "build",
"detail": "Update deck-frontend-lib aka DFL",
"command": "pnpm update decky-frontend-lib --latest",
"detail": "Update @decky/ui aka DFL",
"command": "pnpm update @decky/ui --latest",
"problemMatcher": []
},
//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.
"""
__version__ = '0.1.0'
__version__ = '1.0.0'
import logging
from typing import Any
"""
Constants
"""
@ -50,7 +52,6 @@ Environment variable: `DECKY_USER`.
e.g.: `deck`
"""
DECKY_USER_HOME: str
"""
The home of the user where decky resides in.
@ -172,3 +173,12 @@ Logging
logger: logging.Logger
"""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
# The decky plugin module is located at decky-loader/plugin
# For easy intellisense checkout the decky-loader code one directory up
# or add the `decky-loader/plugin` path to `python.analysis.extraPaths` in `.vscode/settings.json`
import decky_plugin
# For easy intellisense checkout the decky-loader code repo
# and add the `decky-loader/plugin/imports` path to `python.analysis.extraPaths` in `.vscode/settings.json`
import decky
import asyncio
class Plugin:
# A normal method. It can be called from JavaScript using call_plugin_function("method_1", argument1, argument2)
async def add(self, left, right):
# A normal method. It can be called from the TypeScript side using @decky/api.
async def add(self, left: int, right: int) -> int:
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
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
async def _unload(self):
decky_plugin.logger.info("Goodbye World!")
decky.logger.info("Goodbye World!")
pass
async def start_timer(self):
self.loop.create_task(self.long_running())
# Migrations that should be performed before entering `_main()`.
async def _migration(self):
decky_plugin.logger.info("Migrating")
decky.logger.info("Migrating")
# Here's a migration example for logs:
# - `~/.config/decky-template/template.log` will be migrated to `decky_plugin.DECKY_PLUGIN_LOG_DIR/template.log`
decky_plugin.migrate_logs(os.path.join(decky_plugin.DECKY_USER_HOME,
# - `~/.config/decky-template/template.log` will be migrated to `decky.decky_LOG_DIR/template.log`
decky.migrate_logs(os.path.join(decky.DECKY_USER_HOME,
".config", "decky-template", "template.log"))
# Here's a migration example for settings:
# - `~/homebrew/settings/template.json` is migrated to `decky_plugin.DECKY_PLUGIN_SETTINGS_DIR/template.json`
# - `~/.config/decky-template/` all files and directories under this root are migrated to `decky_plugin.DECKY_PLUGIN_SETTINGS_DIR/`
decky_plugin.migrate_settings(
os.path.join(decky_plugin.DECKY_HOME, "settings", "template.json"),
os.path.join(decky_plugin.DECKY_USER_HOME, ".config", "decky-template"))
# - `~/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.decky_SETTINGS_DIR/`
decky.migrate_settings(
os.path.join(decky.DECKY_HOME, "settings", "template.json"),
os.path.join(decky.DECKY_USER_HOME, ".config", "decky-template"))
# 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/`
# - `~/.local/share/decky-template/` all files and directories under this root are migrated to `decky_plugin.DECKY_PLUGIN_RUNTIME_DIR/`
decky_plugin.migrate_runtime(
os.path.join(decky_plugin.DECKY_HOME, "template"),
os.path.join(decky_plugin.DECKY_USER_HOME, ".local", "share", "decky-template"))
# - `~/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.decky_RUNTIME_DIR/`
decky.migrate_runtime(
os.path.join(decky.DECKY_HOME, "template"),
os.path.join(decky.DECKY_USER_HOME, ".local", "share", "decky-template"))

View file

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

View file

@ -2,6 +2,7 @@
"name": "Example Plugin",
"author": "John Doe",
"flags": ["debug", "_root"],
"api_version": 1,
"publish": {
"tags": ["template", "root"],
"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 typescript from '@rollup/plugin-typescript';
import { defineConfig } from 'rollup';
import del from 'rollup-plugin-delete';
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({
input: './src/index.tsx',
plugins: [
del({ targets: './dist/*', force: true }),
commonjs(),
nodeResolve(),
nodeResolve({
browser: true
}),
externalGlobals({
react: 'SP_REACT',
'react-dom': 'SP_REACTDOM',
'@decky/ui': 'DFL',
'@decky/manifest': JSON.stringify(manifest)
}),
typescript(),
json(),
replace({
@ -20,19 +32,18 @@ export default defineConfig({
'process.env.NODE_ENV': JSON.stringify('production'),
}),
importAssets({
publicPath: `http://127.0.0.1:1337/plugins/${name}/`
publicPath: `http://127.0.0.1:1337/plugins/${manifest.name}/`
})
],
context: 'window',
external: ["react", "react-dom", "decky-frontend-lib"],
external: ['react', 'react-dom', '@decky/ui'],
output: {
file: "dist/index.js",
globals: {
react: "SP_REACT",
"react-dom": "SP_REACTDOM",
"decky-frontend-lib": "DFL"
},
format: 'iife',
exports: 'default',
dir: 'dist',
format: 'esm',
sourcemap: true,
// **Don't** change this.
sourcemapPathTransform: (relativeSourcePath) => relativeSourcePath.replace(/^\.\.\//, `decky://decky/plugin/${encodeURIComponent(manifest.name)}/`),
exports: 'default'
},
});

View file

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