Compare commits

...

17 commits

Author SHA1 Message Date
6f5dc01876
Changes for Anatase compatibility 2026-09-09 14:28:31 -05:00
sakanaa
f912f491e2
Add deprecation notice 2025-12-01 04:36:04 +01:00
Fisch03
13d5c3c75e bump version 2025-12-01 04:00:12 +01:00
Andrii Malytskyi
105cbaffb6
fix(#15): Fix get_flatpaks function; (#17) 2025-12-01 03:55:59 +01:00
Fisch03
bf767ad808 Bump Version 2024-02-09 17:10:54 +01:00
Fisch03
ba5cc801c5 Add decky user flatpaks to list 2024-02-09 17:00:32 +01:00
Lars
82b4160655
Custom file support, global DFL (#11)
* Minimally Functional Custom File Shortcut Creation (#9)

* Add method to get decky user home

* Add shortcut options modal

* Split newShortcut to insert custom file codepath

* Integrate file picker a bit better into the rest

* switch to global DFL, better compat tool support, fix shortcut parameters being overwritten

* Actually move DFL to devDependencies

---------

Co-authored-by: jurassicplayer <jurassicplayer75@gmail.com>
2024-02-09 16:58:22 +01:00
Fisch03
9c5660deeb Fix for new AddShortcut params in preview 2023-07-01 19:53:05 +02:00
Fisch03
e6c900f4ce Update lockfile to v6 2023-04-05 22:15:36 +02:00
Fisch03
563b855e36 Use the .gitignore from the Plugin Template 2023-04-05 19:55:55 +02:00
JoaoCostaIFG
8ca4213bed
Include deck user application files in the list (#7)
* Include deck user application files in the list

* Fix parsing of desktop files that are indented

* Small optimization to the dedup process of the apps' names.

* Use env var provided by decky to dynamically search the user's desktop files
2023-04-05 19:49:04 +02:00
Fisch03
0b2eb1867a Bump Version 2023-03-19 01:51:52 +01:00
Fisch03
f6d820c323 Add better Images 2023-03-19 01:49:27 +01:00
Fisch03
a0d4300fa0 Allow starring Apps 2023-03-19 01:37:24 +01:00
Fisch03
e929080078 Dynamically change the Shortcut name 2023-03-18 22:16:09 +01:00
Fisch03
a94d624af9 UI changes 2023-03-18 21:28:52 +01:00
Fisch03
03998f1fd8 Add some more info to the README 2023-03-18 20:19:57 +01:00
19 changed files with 1421 additions and 844 deletions

21
.gitignore vendored
View file

@ -1,5 +1,3 @@
.vscode
lib-cov
*.seed
*.log
@ -15,9 +13,6 @@ logs
results
tmp
# Build
public/css/main.css
# Coverage reports
coverage
@ -27,6 +22,7 @@ coverage
# Dependency directory
node_modules
bower_components
.pnpm-store
# Editors
.idea
@ -39,5 +35,16 @@ Thumbs.db
# Ignore built ts files
dist/
# ignore yarn.lock
yarn.lock
__pycache__/
/.yalc
yalc.lock
.vscode/settings.json
# Ignore output folder
backend/out
# Make sure to ignore any instance of the loader's decky_plugin.py
decky_plugin.py

12
.vscode/config.sh vendored Executable file
View file

@ -0,0 +1,12 @@
#!/usr/bin/env bash
SCRIPT_DIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]:-$0}"; )" &> /dev/null && pwd 2> /dev/null; )";
# printf "${SCRIPT_DIR}\n"
# printf "$(dirname $0)\n"
if ! [[ -e "${SCRIPT_DIR}/settings.json" ]]; then
printf '.vscode/settings.json does not exist. Creating it with default settings. Exiting afterwards. Run your task again.\n\n'
cp "${SCRIPT_DIR}/defsettings.json" "${SCRIPT_DIR}/settings.json"
exit 1
else
printf '.vscode/settings.json does exist. Congrats.\n'
printf 'Make sure to change settings.json to match your deck.\n'
fi

10
.vscode/defsettings.json vendored Executable file
View file

@ -0,0 +1,10 @@
{
"deckip" : "0.0.0.0",
"deckport" : "22",
"deckpass" : "ssap",
"deckkey" : "-i ${env:HOME}/.ssh/id_rsa",
"deckdir" : "/home/deck",
"python.analysis.extraPaths": [
"./py_modules"
]
}

116
.vscode/tasks.json vendored Executable file
View file

@ -0,0 +1,116 @@
{
"version": "2.0.0",
"tasks": [
// OTHER
{
"label": "checkforsettings",
"type": "shell",
"group": "none",
"detail": "Check that settings.json has been created",
"command": "bash -c ${workspaceFolder}/.vscode/config.sh",
"problemMatcher": []
},
// BUILD
{
"label": "pnpmsetup",
"type": "shell",
"group": "build",
"detail": "Setup pnpm",
"command": "pnpm i",
"problemMatcher": []
},
{
"label": "updatefrontendlib",
"type": "shell",
"group": "build",
"detail": "Update deck-frontend-lib",
"command": "pnpm update decky-frontend-lib --latest",
"problemMatcher": []
},
{
"label": "build",
"type": "npm",
"group": "build",
"detail": "rollup -c",
"script": "build",
"path": "",
"problemMatcher": []
},
{
"label": "buildall",
"group": "build",
"detail": "Build decky-plugin-template",
"dependsOrder": "sequence",
"dependsOn": [
"pnpmsetup",
"build"
],
"problemMatcher": []
},
// DEPLOY
{
"label": "createfolders",
"detail": "Create plugins folder in expected directory",
"type": "shell",
"group": "none",
"dependsOn": [
"checkforsettings"
],
"command": "ssh deck@${config:deckip} -p ${config:deckport} ${config:deckkey} 'mkdir -p ${config:deckdir}/homebrew/pluginloader && mkdir -p ${config:deckdir}/homebrew/plugins'",
"problemMatcher": []
},
{
"label": "deploy",
"detail": "Deploy dev plugin to deck",
"type": "shell",
"group": "none",
"dependsOn": [
"createfolders",
"chmodfolders"
],
"command": "rsync -azp --delete --chmod=D0755,F0755 --rsh='ssh -p ${config:deckport} ${config:deckkey}' --exclude='.git/' --exclude='.github/' --exclude='.vscode/' --exclude='node_modules/' --exclude='src/' --exclude='*.log' --exclude='.gitignore' . deck@${config:deckip}:${config:deckdir}/homebrew/plugins/${workspaceFolderBasename}",
"problemMatcher": []
},
{
"label": "restartloader",
"detail": "Restart the plugin loader (to load updated python code)",
"type": "shell",
"group": "none",
"dependsOn": [],
"command": "ssh deck@${config:deckip} -p ${config:deckport} ${config:deckkey} 'echo '${config:deckpass}' | sudo -S systemctl restart plugin_loader'",
"problemMatcher": []
},
{
"label": "chmodfolders",
"detail": "chmods folders to prevent perms issues",
"type": "shell",
"group": "none",
"command": "ssh deck@${config:deckip} -p ${config:deckport} ${config:deckkey} 'echo '${config:deckpass}' | sudo -S chmod -R ug+rw ${config:deckdir}/homebrew/'",
"problemMatcher": []
},
{
"label": "deployall",
"dependsOrder": "sequence",
"group": "none",
"dependsOn": [
"deploy",
"chmodfolders"
],
"problemMatcher": []
},
// ALL-IN-ONE
{
"label": "allinone",
"detail": "Build and deploy",
"dependsOrder": "sequence",
"group": "test",
"dependsOn": [
"buildall",
"deployall"
// Uncomment this line if you'd like your python code reloaded after deployment (this will restart Steam)
// ,"restartloader"
],
"problemMatcher": []
}
]
}

View file

@ -1,10 +1,14 @@
> [!TIP]
> This is a fork of [Quick Launch by Fisch03](https://github.com/Fisch03/SDH-QuickLaunch) that has been modified to work on [Anatase](https://anatase.org/). Since Anatase runs Steam in a Flatpak, launching other Flatpaks and apps doesn't normally work. The purpose of this fork is to replace calls to /usr/bin/flatpak to /app/bin/flatpak, which is a wrapper that allows launching other Flatpaks within Anatase's Steam package.
# SDH-QuickLaunch
[Decky Loader](https://github.com/SteamDeckHomebrew/PluginLoader) Plugin to Quickly Launch Apps from the Steam Deck Quick Access Menu without adding them as Shortcuts
[Decky Loader](https://github.com/SteamDeckHomebrew/PluginLoader) Plugin to quickly launch Apps from the Quick Access Menu without adding them as shortcuts, and add new shortcuts entirely
![plugin_demo](./ui.png)
## Tips
Feel free to hide the QuickLaunch Shortcut this creates from your library, it wont affect the functionality
- Feel free to hide the QuickLaunch Shortcut this creates from your library, it wont affect the functionality
- To obtain a SteamGridDB API Key, login/register at [SteamGridDB](https://www.steamgriddb.com/). You can then generate an API Key [here](https://www.steamgriddb.com/profile/preferences/api)
## Caveats
- You can only have one application open at at time
You can only have one application open at at time

133
main.py
View file

@ -1,4 +1,7 @@
import os, json, base64, ssl, certifi
from pathlib import Path
from json import dumps as jsonDumps
from itertools import chain
import decky_plugin
@ -7,57 +10,129 @@ from subprocess import Popen, PIPE
from urllib.error import HTTPError
from urllib.request import urlopen, Request
FLATPAK_RUNNER = "flatpak" # or explicitly: /app/bin/flatpak
HOST_RUNNER = "hrun" # or explicitly: /app/bin/hrun
confdir = os.environ['DECKY_PLUGIN_SETTINGS_DIR']
confdir = os.environ["DECKY_PLUGIN_SETTINGS_DIR"]
send_buffer = []
def split_string(string):
return [string[i:i+1024*60] for i in range(0, len(string), 1024*60)] # every 60KB
return [
string[i : i + 1024 * 60] for i in range(0, len(string), 1024 * 60)
] # every 60KB
class Plugin:
async def get_flatpaks(self):
proc = Popen('flatpak list -d --app | awk \'BEGIN {FS="\\t"} {print "{\\"name\\":\\""$1"\\",\\"exec\\":\\"/usr/bin/flatpak run "$3"\\"},"}\\\'', stdout=PIPE, stderr=None, shell=True)
packages = proc.communicate()[0]
packages = packages.decode("utf-8")
packages = packages[:-2]
return "["+packages+"]"
def list_flatpaks(cmd):
flatpaks = []
clean_env = os.environ.copy()
clean_env["LD_LIBRARY_PATH"] = ""
with Popen(cmd, stdout=PIPE, stderr=None, env=clean_env, text=True) as p:
for line in p.stdout:
if '\t' not in line:
continue
name, app_id = line.strip().split('\t', 1)
name = name.strip()
app_id = app_id.strip()
if not name or not app_id:
continue
flatpaks.append({
"id": app_id,
"name": name,
"exec": f"{FLATPAK_RUNNER} run {app_id}"
})
return flatpaks
global_flatpaks = list_flatpaks([
'flatpak', 'list', '--app', '--columns=name,application'
])
local_flatpaks = list_flatpaks([
'runuser', '-l', decky_plugin.DECKY_USER, '-c',
'flatpak list --app --columns=name,application'
])
seen = set()
unique_flatpaks = []
for flatpak in global_flatpaks + local_flatpaks:
if flatpak["id"] not in seen:
seen.add(flatpak["id"])
unique_flatpaks.append(flatpak)
sorted_items = sorted(unique_flatpaks, key=lambda x: x.get("name", "").lower())
return jsonDumps(sorted_items)
async def get_desktops(self):
#Really REALLY scuffed way of reading desktop files...
proc = Popen('ls -l /usr/share/applications | gawk \'{path="/usr/share/applications/"$9; while(( getline line<path) > 0) {if(line ~ /^Exec=/ && exec=="") { exec=substr(line,6);}; if(line ~ /^Name=/ && name=="") { name=substr(line,6); }; if(exec!="" && name!="") { break }};gsub(/"/,"\\\\\\"",exec);print("{\\"name\\":\\""name"\\",\\"exec\\":\\""exec"\\"},");exec="";name=""}\'', stdout=PIPE, stderr=None, shell=True)
packages = proc.communicate()[0]
packages = packages.decode("utf-8")
packages = packages[:-2]
return "["+packages+"]"
packages = []
for desktopFile in chain(
Path("/usr/share/applications").glob("*.desktop"),
Path(f"{decky_plugin.DECKY_USER_HOME}/.local/share/applications/").glob("*.desktop"),
Path("/var/usrlocal/share/applications").glob("*.desktop"),
):
if not desktopFile.is_file():
continue
with open(desktopFile) as f:
package = {}
foundName = foundExec = False
for line in f:
line = line.strip()
if line.startswith("Name="):
foundName = True
package["name"] = line[5:]
elif line.startswith("Exec="):
foundExec = True
execTarget = line[5:].split(" ", 1)
decky_plugin.logger.info("- Exec path: " + str(execTarget))
runner = FLATPAK_RUNNER if execTarget[0].endswith("flatpak") else HOST_RUNNER
package["exec"] = f"{runner} {execTarget[1]}"
if foundName and foundExec:
decky_plugin.logger.info("+ Desktop app: " + package["name"])
packages.append(package)
break
return jsonDumps(packages)
async def get_DECKY_USER_HOME(self):
return decky_plugin.DECKY_USER_HOME
async def get_config(self):
with open(os.path.join(confdir,"config.json"), "r") as f:
with open(os.path.join(confdir, "config.json"), "r") as f:
return json.load(f)
async def set_config_value(self, key, value):
config = json.load(open(os.path.join(confdir,"config.json")))
config = json.load(open(os.path.join(confdir, "config.json")))
config[key] = value
with open(os.path.join(confdir,"config.json"), "w") as f:
with open(os.path.join(confdir, "config.json"), "w") as f:
json.dump(config, f)
return config
async def get_id(self):
with open(os.path.join(confdir,"scid.txt"), "r") as sc:
with open(os.path.join(confdir, "scid.txt"), "r") as sc:
id = sc.read()
try:
id = int(id)
return id
except ValueError:
return -1
async def set_id(self, id):
with open(os.path.join(confdir,"scid.txt"), "w") as sc:
with open(os.path.join(confdir, "scid.txt"), "w") as sc:
sc.write(str(id))
async def get_req_imgb64(self, url):
global send_buffer
if(len(send_buffer) != 0):
if len(send_buffer) != 0:
return
req = Request(url)
@ -65,13 +140,15 @@ class Plugin:
req.add_header("User-Agent", "SDH-QuickLaunch")
try:
content = urlopen(req, context=ssl.create_default_context(cafile=certifi.where())).read()
img = base64.b64encode(content).decode('ascii')
content = urlopen(
req, context=ssl.create_default_context(cafile=certifi.where())
).read()
img = base64.b64encode(content).decode("ascii")
send_buffer = split_string(img)
new_chunk = send_buffer.pop(0)
return {"data": new_chunk, "is_last": len(send_buffer) == 0}
return {"data": new_chunk, "is_last": len(send_buffer) == 0}
except HTTPError:
decky_plugin.logger.error("HTTPError while requesting "+url)
decky_plugin.logger.error("HTTPError while requesting " + url)
pass
async def receive_next_chunk(self):
@ -81,19 +158,19 @@ class Plugin:
async def _main(self):
decky_plugin.logger.info("Loading plugin")
try:
os.mkdir(confdir)
except FileExistsError:
pass
try:
sc = open(os.path.join(confdir,"scid.txt"), "x")
sc = open(os.path.join(confdir, "scid.txt"), "x")
sc.close()
except FileExistsError:
pass
try:
sc = open(os.path.join(confdir,"config.json"), "x")
sc = open(os.path.join(confdir, "config.json"), "x")
sc.write("{}")
sc.close()
except FileExistsError:

View file

@ -1,7 +1,7 @@
{
"name": "sdh-quicklaunch",
"version": "1.0.0",
"description": "Quickly Launch Apps from the Steam Deck Quick Access Menu without adding them as Shortcuts",
"name": "sdh-quicklaunch-anatase",
"version": "1.2.1",
"description": "Quickly launch apps from the Steam Deck Quick Access Menu without adding them as shortcuts",
"scripts": {
"build": "shx rm -rf dist && rollup -c",
"watch": "rollup -c -w",
@ -9,7 +9,7 @@
},
"repository": {
"type": "git",
"url": "git+https://github.com/Fisch03/SDH-QuickLaunch.git"
"url": "git+https://gitdab.com/dj/SDH-QuickLaunch-Anatase.git"
},
"keywords": [
"decky",
@ -17,12 +17,12 @@
"steam-deck",
"deck"
],
"author": "Fisch03",
"author": "Fisch03 & djsime1",
"license": "GPL-3.0-or-later",
"bugs": {
"url": "https://github.com/Fisch03/SDH-QuickLaunch/issues"
"url": "https://gitdab.com/dj/SDH-QuickLaunch-Anatase/issues"
},
"homepage": "https://github.com/Fisch03/SDH-QuickLaunch#readme",
"homepage": "https://gitdab.com/dj/SDH-QuickLaunch-Anatase",
"devDependencies": {
"@rollup/plugin-commonjs": "^21.1.0",
"@rollup/plugin-json": "^4.1.0",
@ -31,6 +31,7 @@
"@rollup/plugin-typescript": "^8.3.3",
"@types/react": "16.14.0",
"@types/webpack": "^5.28.0",
"decky-frontend-lib": "^3.24.5",
"rollup": "^2.77.1",
"rollup-plugin-import-assets": "^1.1.1",
"shx": "^0.3.4",
@ -38,14 +39,14 @@
"typescript": "^4.7.4"
},
"dependencies": {
"decky-frontend-lib": "^3.19.2",
"react-icons": "^4.8.0"
},
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"react",
"react-dom"
"react-dom",
"decky-frontend-lib"
]
}
}

View file

@ -1,11 +1,10 @@
{
"name": "Quick Launch",
"author": "Fisch03",
"author": "Fisch03 & djsime1",
"flags": ["root"],
"publish": {
"discord_id": "431374517462499328",
"description": "Quickly Launch Non-Steam-Apps from the Quick Access menu without adding them as Shortcuts, or add them to the Steam Library.",
"tags": [ "utility" ],
"image": "https://raw.githubusercontent.com/Fisch03/SDH-QuickLaunch/master/ui.png"
"image": "https://gitdab.com/dj/SDH-QuickLaunch-Anatase/raw/branch/master/ui_full.png"
}
}

1590
pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff

View file

@ -24,12 +24,13 @@ export default defineConfig({
})
],
context: 'window',
external: ['react', 'react-dom'],
external: ['react', 'react-dom', 'decky-frontend-lib'],
output: {
file: 'dist/index.js',
globals: {
react: 'SP_REACT',
'react-dom': 'SP_REACTDOM',
'decky-frontend-lib': 'DFL',
},
format: 'iife',
exports: 'default',

47
src/appoperations.tsx Normal file
View file

@ -0,0 +1,47 @@
import { ServerAPI } from "decky-frontend-lib";
import { App, getLaunchOptions, getTarget } from "./apptypes";
import { getImagesForGame } from "./steamgriddb";
import { gameIDFromAppID, getShortcutID, createShortcut } from "./utils";
import { Settings } from "./settings";
export async function launchApp(sAPI: ServerAPI, app: App) {
let id: number = await getShortcutID(sAPI);
SteamClient.Apps.SetShortcutName(id, `[QL] ${app.name}`)
SteamClient.Apps.SetShortcutLaunchOptions(id, getLaunchOptions(app))
SteamClient.Apps.SetShortcutExe(id, `"${getTarget(app)}"`)
SteamClient.Apps.SetShortcutStartDir(id, "/app/bin")
SteamClient.Apps.SpecifyCompatTool(id, app.compatTool === undefined ? "" : app.compatTool)
setTimeout(() => {
let gid = gameIDFromAppID(id);
SteamClient.Apps.RunGame(gid,"",-1,100);
}, 500)
}
export function createAppShortcut(sAPI: ServerAPI, app: App, settings: Settings, launchOptions?: string, target?: string) {
let shortcutLaunchOptions = launchOptions === undefined ? getLaunchOptions(app) : launchOptions
let shortcutTarget = target === undefined ? getTarget(app) : target
createShortcut(app.name, shortcutLaunchOptions, shortcutTarget).then((id:number) => {
if(settings.get("useGridDB")) {
getImagesForGame(sAPI, settings.get("gridDBKey") ,app.name)
.then(images => {
if(images.Grid !== null) SteamClient.Apps.SetCustomArtworkForApp(id, images.Grid, "png", 0);
if(images.Hero !== null) SteamClient.Apps.SetCustomArtworkForApp(id, images.Hero, "png", 1);
if(images.Logo !== null) SteamClient.Apps.SetCustomArtworkForApp(id, images.Logo, "png", 2);
//if(images.Grid !== null) SteamClient.Apps.SetCustomArtworkForApp(id, images.GridH, "png", 3);
})
.catch(() => {}); //Maybe display error to the user in the future?
}
//This should theoretically not be needed with the new SteamClient.Apps.AddShortcut params but they seem to be pretty broken rn. It's not like it hurts either.
setTimeout(() => {
SteamClient.Apps.SetShortcutName(id, app.name);
SteamClient.Apps.SetShortcutLaunchOptions(id, shortcutLaunchOptions);
SteamClient.Apps.SetShortcutExe(id, `"${shortcutTarget}"`);
SteamClient.Apps.SetShortcutStartDir(id, "/app/bin")
SteamClient.Apps.SpecifyCompatTool(id, app.compatTool === undefined ? "" : app.compatTool);
}, 500)
})
}

View file

@ -1,6 +1,7 @@
export interface App {
name: string;
exec: string;
compatTool?: string;
}
export function getLaunchOptions(app: App) {

101
src/fileoptions.tsx Normal file
View file

@ -0,0 +1,101 @@
import {
ServerAPI,
ConfirmModal,
ToastData,
TextField,
FilePickerRes,
ToggleField
} from "decky-frontend-lib"
import { useEffect, useState } from "react"
import { App } from "./apptypes"
import { createAppShortcut, launchApp } from "./appoperations"
import { Settings } from "./settings"
export const FileOptionsModal = (props: {closeModal?: CallableFunction, settings: Settings, starApp: CallableFunction, filepath: FilePickerRes, serverAPI: ServerAPI}) => {
const closeModal = () => { if (props.closeModal) {props.closeModal()} }
const {settings, starApp, filepath, serverAPI} = props
const [appName, setAppName] = useState<string>(filepath.path)
const [compatTool, setCompatTool] = useState<string|undefined>()
const [addToFavorites, setAddToFavorites] = useState<boolean>(false)
const [addAsShortcut, setAddAsShortcut] = useState<boolean>(false)
useEffect(()=>{
let filenameWithExtension = filepath.realpath.split(/[\\\/]/).pop() // potentially has an extension
let filename = filenameWithExtension
let fileext = ''
if (filenameWithExtension) {
filename = filenameWithExtension.slice(0, filenameWithExtension.lastIndexOf('.'))
fileext = filenameWithExtension.slice(filenameWithExtension.lastIndexOf('.')+1, filenameWithExtension.length).toLowerCase()
}
let path = filepath.realpath.substring(0, filepath.realpath.length - (filenameWithExtension ? filenameWithExtension.length : 0))
localStorage.setItem('decky-addtosteam', path)
let appName = filename || filenameWithExtension || 'MissingAppName'
setAppName(appName)
if (['exe', 'bat'].includes(fileext)) setCompatTool('proton-experimental')
},[])
const onOK = () => {
let app: App = {
name: appName,
exec: filepath.realpath,
compatTool: compatTool
}
if (addAsShortcut) {
createAppShortcut(serverAPI, app, settings, "", app.exec)
let toastData: ToastData = {
title: 'Added Shortcut',
body: appName,
playSound: true,
showToast: true
}
serverAPI.toaster.toast(toastData)
} else if (addToFavorites) {
//TODO: Doing this looses information about the compat tool. An app should also be able to store data about compat tools.
starApp(app);
} else {
launchApp(serverAPI, app);
}
}
const nameField = <TextField
label='Name'
focusOnMount={true}
value={appName}
onChange={(e) => setAppName(e.currentTarget.value)}
/>
return (
<ConfirmModal
strTitle='File Options'
strOKButtonText={addAsShortcut ? 'Add Shortcut' : addToFavorites ? 'Add to starred Apps' : 'Launch'}
closeModal={closeModal}
onOK={onOK}
onCancel={closeModal}
onEscKeypress={closeModal}
>
<ToggleField
label='Add to favorites'
checked={addToFavorites}
onChange={addToFavorites => {
setAddToFavorites(addToFavorites);
if(addToFavorites) setAddAsShortcut(false);
}}
/>
<ToggleField
label='Add as shortcut'
checked={addAsShortcut}
onChange={addAsShortcut => {
setAddAsShortcut(addAsShortcut);
if(addAsShortcut) setAddToFavorites(false);
}}
/>
{ (addToFavorites || addAsShortcut) && nameField }
</ConfirmModal>
)
}

View file

@ -6,21 +6,29 @@ import {
MultiDropdownOption,
PanelSection,
PanelSectionRow,
ButtonItem,
ToggleField,
showModal,
ModalRoot,
SingleDropdownOption,
DropdownOption
DropdownOption,
DialogButton,
Focusable,
FileSelectionType
} from "decky-frontend-lib";
import { Fragment, useEffect } from "react";
import { VFC, useState } from "react";
import { FaRocket } from "react-icons/fa";
import { FaRocket, FaStar, FaRegStar } from "react-icons/fa";
import { App, getLaunchOptions, getTarget } from "./apptypes";
import { App } from "./apptypes";
import { Settings } from "./settings";
import { GridDBPanel, getImagesForGame } from "./steamgriddb";
import { fetchApps, launchApp, createShortcut } from "./utils";
import { GridDBPanel } from "./steamgriddb";
import { fetchApps } from "./utils";
import { FileOptionsModal } from "./fileoptions";
import { launchApp, createAppShortcut } from "./appoperations";
enum SpecialSelections {
FileShortcut = -1,
}
let appList: App[] = [];
@ -30,42 +38,61 @@ const Content: VFC<{ serverAPI: ServerAPI }> = ({ serverAPI }) => {
const [settings] = useState<Settings>(new Settings(serverAPI))
const [buttonText, setButtonText] = useState<string>("Launch!");
const updateButtonText = () => settings.get("createNewShortcut")? setButtonText("Create!") : setButtonText("Launch!");
const [showKeyInput, setShowKeyInput] = useState<boolean>(false);
const [isStarred, setIsStarred] = useState<boolean>(false);
useEffect(() => {
settings.readSettings().then(() => {
if(dropdownOptions.length === 0 || appList.length === 0)
buildAppList();
updateButtonText();
setShowKeyInput(settings.get("useGridDB"));
//setKeyInputValue(settings.get("gridDBKey"));
});
}, []);
function buildAppList() {
return new Promise<void>((resolve) => {
let newDropdownOptions: DropdownOption[] = [];
appList = [];
if(settings.get("enableAll")) {
let newDropdownOptions: MultiDropdownOption[] = [];
fetchApps(serverAPI, "flatpaks")
.then(list => {
newDropdownOptions.push(createSubcategory("Flatpaks", list));
return fetchApps(serverAPI, "desktops");
})
.then(list => {
newDropdownOptions.push(createSubcategory(".desktop files", list));
setDropdownOptions(newDropdownOptions);
let starredApps = settings.get("starredApps");
if(starredApps.length > 0)
newDropdownOptions.push(...createSubcategory("Starred Apps", settings.get("starredApps")).options);
fetchApps(serverAPI, "flatpaks")
.then(list => {
list = list.filter(app => {
for(let starredApp of starredApps) {
if(starredApp.name === app.name) return false;
}
return true;
});
} else {
fetchApps(serverAPI, "flatpaks")
.then(list => {
setDropdownOptions(createSubcategory("Flatpaks", list).options)
appList = list
})
}
newDropdownOptions.push(createSubcategory("Flatpaks", list));
if(settings.get("enableAll")) {
return fetchApps(serverAPI, "desktops")
} else {
return Promise.resolve([]);
}
})
.then(list => {
if(list.length > 0) {
list = list.filter(app => {
for(let starredApp of starredApps) {
if(starredApp.name === app.name) return false;
}
return true;
});
newDropdownOptions.push(createSubcategory(".desktop files", list));
}
})
.finally(() => {
if(settings.get("enableAll")) newDropdownOptions.push({label: "Choose a file...", data: SpecialSelections.FileShortcut} as SingleDropdownOption);
setDropdownOptions(newDropdownOptions);
resolve();
})
})
}
function createSubcategory(categoryName: string, list: App[]) {
@ -78,30 +105,45 @@ const Content: VFC<{ serverAPI: ServerAPI }> = ({ serverAPI }) => {
}
function doButtonAction() {
if(selectedApp === null) return;
let app = appList[selectedApp];
if(settings.get("createNewShortcut")) {
createShortcut(app.name).then((id:number) => {
if(settings.get("useGridDB")) {
getImagesForGame(serverAPI, settings.get("gridDBKey"),app.name)
.then(images => {
if(images.Grid !== null) SteamClient.Apps.SetCustomArtworkForApp(id, images.Grid, "png", 0);
if(images.Hero !== null) SteamClient.Apps.SetCustomArtworkForApp(id, images.Hero, "png", 1);
if(images.Logo !== null) SteamClient.Apps.SetCustomArtworkForApp(id, images.Logo, "png", 2);
//if(images.Grid !== null) SteamClient.Apps.SetCustomArtworkForApp(id, images.GridH, "png", 3);
})
.catch(() => {}); //Maybe display error to the user in the future?
}
setTimeout(() => {
SteamClient.Apps.SetShortcutLaunchOptions(id, getLaunchOptions(app));
SteamClient.Apps.SetShortcutExe(id, `"${getTarget(app)}"`);
}, 500)
})
async function createFileShortcut() {
let lastUsedPath = localStorage.getItem('decky-addtosteam')
let deckyUserHome = (await serverAPI.callPluginMethod('get_DECKY_USER_HOME', {})).result
let path: string
if (lastUsedPath != null) {
path = lastUsedPath
} else if (typeof deckyUserHome === 'string') {
path = deckyUserHome
} else {
launchApp(serverAPI, app);
return
}
let filepath = await serverAPI.openFilePickerV2(
FileSelectionType.FILE,
path,
true,
undefined,
undefined,
undefined,
false,
true
)
if (!filepath) { return }
const starApp = async (app: App) => {
let starredApps = settings.get("starredApps");
if(!starredApps.find((a: App) => a.name === app.name && a.exec === app.exec))
starredApps.push(app);
settings.set("starredApps", starredApps);
await buildAppList();
setSelectedApp(appList.findIndex((a: App) => a.name === app.name && a.exec === app.exec));
}
showModal(<FileOptionsModal filepath={filepath} starApp={starApp} settings={settings} serverAPI={serverAPI}/>)
}
function newShortcut() {
if(selectedApp != null){
createAppShortcut(serverAPI, appList[selectedApp], settings)
}
}
@ -109,27 +151,73 @@ const Content: VFC<{ serverAPI: ServerAPI }> = ({ serverAPI }) => {
<Fragment>
<PanelSection>
<PanelSectionRow>
<Dropdown
strDefaultLabel="Select App..."
rgOptions={dropdownOptions}
selectedOption={selectedApp}
onChange={(e: SingleDropdownOption) => {setSelectedApp(e.data);}}
/>
<Focusable flow-children="horizontal" style={{display: "flex", justifyContent: "space-between", padding: 0, gap: "8px"}}>
<div style={{flexGrow: 1}}>
<Dropdown
strDefaultLabel="Select App..."
rgOptions={dropdownOptions}
selectedOption={selectedApp}
onChange={(e: SingleDropdownOption) => {
setIsStarred(e.data < settings.get("starredApps").length);
if(e.data === SpecialSelections.FileShortcut) {
createFileShortcut();
setSelectedApp(null);
}
else setSelectedApp(e.data);
}}
/>
</div>
<DialogButton style={{minWidth: 0, width: "15%", padding: 0}} onClick={() => {
if(selectedApp === null) return;
let toBeStarred = appList[selectedApp];
setIsStarred(!isStarred);
let starredApps = settings.get("starredApps");
if(isStarred) {
starredApps.splice(starredApps.indexOf(appList[selectedApp]), 1);
} else {
starredApps.push(appList[selectedApp]);
}
settings.set("starredApps", starredApps);
buildAppList()
.then(() => {
if(isStarred) {
let foundApp = 0;
for(let app of appList) {
if(app.name === toBeStarred.name) {
foundApp = appList.indexOf(app);
break;
}
}
setSelectedApp(foundApp);
} else {
setSelectedApp(starredApps.length-1);
}
})
}}>
{isStarred ? <FaStar /> : <FaRegStar />}
</DialogButton>
</Focusable>
</PanelSectionRow>
<PanelSectionRow>
<ButtonItem layout="below" onClick={() => doButtonAction()}>
{buttonText}
</ButtonItem>
<DialogButton style={{ marginTop: "8px" }} onClick={() => {
if(selectedApp === null) return;
launchApp(serverAPI, appList[selectedApp])
}}>
Launch!
</DialogButton>
</PanelSectionRow>
<PanelSectionRow>
<DialogButton style={{ marginTop: "8px" }} onClick={() => {newShortcut()}}>
Create Shortcut
</DialogButton>
</PanelSectionRow>
</PanelSection>
<PanelSection title="Settings">
<PanelSectionRow>
<ToggleField
label="Add as a separate Shortcut"
checked={settings.get("createNewShortcut")}
onChange={(e) => {settings.set("createNewShortcut", e); updateButtonText()}}
/>
</PanelSectionRow>
<PanelSectionRow>
<ToggleField
label="Automatically download Artworks from SteamGridDB"

View file

@ -11,6 +11,8 @@ export class Settings {
private gridDBKey: string = "";
//@ts-ignore
private enableAll: boolean = false;
//@ts-ignore
private starredApps: App[] = [];
constructor(sAPI: ServerAPI, startingSettings: Settings = {} as Settings) {
this.sAPI = sAPI;

View file

@ -129,10 +129,9 @@ const searchGame = (sAPI: ServerAPI, key: string, gameName: string) => apiReques
const getGrids = (sAPI: ServerAPI, key: string, gameID: number) => apiRequest(sAPI, key, "/grids/game", gameID) as Promise<ImageAPIResponse>
const getHeroes = (sAPI: ServerAPI, key: string, gameID: number) => apiRequest(sAPI, key, "/heroes/game", gameID) as Promise<ImageAPIResponse>
const getLogos = (sAPI: ServerAPI, key: string, gameID: number) => apiRequest(sAPI, key, "/logos/game", gameID) as Promise<ImageAPIResponse>
//const getIcons = (sAPI: ServerAPI, key: string, gameID: number) => apiRequest(sAPI, key, "/icons/game", gameID) as Promise<ImageAPIResponse>
//const getGridH = (sAPI: ServerAPI, key: string, gameID: number) => apiRequest(sAPI, key, "/grids/game", gameID) as Promise<ImageAPIResponse>
export function getImagesForGame(sAPI: ServerAPI, key: string, gameName: string): Promise<ImageCollection> {
return new Promise<ImageCollection>((resolve, reject) => {
searchGame(sAPI, key, gameName)

View file

@ -1,10 +1,9 @@
import { ServerAPI } from "decky-frontend-lib";
import { App, getLaunchOptions, getTarget } from "./apptypes";
import { App } from "./apptypes";
export const createShortcut = (name: string) => {
//@ts-ignore
return SteamClient.Apps.AddShortcut(name,"/usr/bin/ifyouseethisyoufoundabug") //The Part after the last Slash does not matter because it should always be replaced when launching an app
export const createShortcut = (name: string, launchOptions: string = "", target:string = "") => {
return SteamClient.Apps.AddShortcut(name,"/usr/bin/ifyouseethisyoufoundabug", target, launchOptions); //The Part after the last Slash does not matter because it should always be replaced when launching an app
}
export const gameIDFromAppID = (appid: number) => {
@ -19,49 +18,22 @@ export const gameIDFromAppID = (appid: number) => {
}
export async function fetchApps(sAPI: ServerAPI, type: string): Promise<App[]> {
const result = await sAPI.callPluginMethod<any, string>(`get_${type}`, {});
const result = await sAPI.callPluginMethod<any, string>(`get_${type}`, {});
let apps: App[] = []
if(result.success) {
//...i guess it works
let apps_withDuplicates: App[] = JSON.parse(result.result);
let names: String[] = []
for(let app of apps_withDuplicates) {
if(!names.includes(app.name) && app.name !== "") {
names.push(app.name)
}
}
for(let name of names) {
let app = apps_withDuplicates.find(app => app.name === name);
if(app !== undefined) {
apps.push(app);
if (result.success) {
let appsDict = new Map<string, App>();
for (let app of JSON.parse(result.result)) {
if (app.name !== "" && !appsDict.has(app.name)) {
appsDict.set(app.name, app);
}
}
apps.sort((a, b) => {
if(a.name < b.name) { return -1; }
if(a.name > b.name) { return 1; }
return 0;
})
// map values to list
apps = Array.from(appsDict.values()).sort((a, b) => a.name.localeCompare(b.name));
}
return apps
}
export const launchApp = async (sAPI: ServerAPI, app: App) => {
let id: number = await getShortcutID(sAPI);
//@ts-ignore
SteamClient.Apps.SetShortcutLaunchOptions(id, getLaunchOptions(app))
//@ts-ignore
SteamClient.Apps.SetShortcutExe(id, `"${getTarget(app)}"`)
setTimeout(() => {
let gid = gameIDFromAppID(id);
//@ts-ignore
SteamClient.Apps.RunGame(gid,"",-1,100);
}, 500)
}
export const getShortcutID = async (sAPI: ServerAPI) => {
const result = await sAPI.callPluginMethod<any, number>("get_id", {})
@ -81,4 +53,4 @@ export const getShortcutID = async (sAPI: ServerAPI) => {
}
return -1
}
}

BIN
ui.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 112 KiB

After

Width:  |  Height:  |  Size: 110 KiB

Before After
Before After

BIN
ui_full.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 307 KiB