diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..b0b5bd5 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,22 @@ +root = true + +[*] +charset = utf-8 +indent_style = space +indent_size = 4 +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{csproj,props,targets,slnx,json,yml,yaml}] +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false + +[*.cs] +csharp_style_namespace_declarations = block_scoped:suggestion +csharp_new_line_before_open_brace = all +dotnet_sort_system_directives_first = true + +[tests/**.cs] +dotnet_diagnostic.CA1707.severity = none diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..302e6bf --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +* text=auto +*.cs text eol=crlf +*.ps1 text eol=crlf +*.cmd text eol=crlf +*.sh text eol=lf diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..ea5cc50 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,25 @@ +# Weekly dependency updates into develop. Branches are named dependabot/*, which branch-policy allows. +version: 2 +updates: + - package-ecosystem: nuget + directory: / + target-branch: develop + schedule: + interval: weekly + open-pull-requests-limit: 5 + commit-message: + prefix: chore(deps) + groups: + nuget-minor-and-patch: + update-types: [minor, patch] + - package-ecosystem: github-actions + directory: / + target-branch: develop + schedule: + interval: weekly + open-pull-requests-limit: 5 + commit-message: + prefix: chore(ci) + groups: + actions: + patterns: ["*"] diff --git a/.github/rulesets/develop.json b/.github/rulesets/develop.json new file mode 100644 index 0000000..63e0e7c --- /dev/null +++ b/.github/rulesets/develop.json @@ -0,0 +1,27 @@ +{ + "name": "develop", + "target": "branch", + "enforcement": "active", + "conditions": { + "ref_name": { + "include": ["refs/heads/develop"], + "exclude": [] + } + }, + "rules": [ + { "type": "deletion" }, + { "type": "non_fast_forward" }, + { + "type": "pull_request", + "parameters": { + "required_approving_review_count": 0, + "dismiss_stale_reviews_on_push": true, + "require_code_owner_review": false, + "require_last_push_approval": false, + "required_review_thread_resolution": true, + "allowed_merge_methods": ["squash", "merge"] + } + } + ], + "bypass_actors": [] +} diff --git a/.github/rulesets/main.json b/.github/rulesets/main.json new file mode 100644 index 0000000..d43858c --- /dev/null +++ b/.github/rulesets/main.json @@ -0,0 +1,27 @@ +{ + "name": "main", + "target": "branch", + "enforcement": "active", + "conditions": { + "ref_name": { + "include": ["refs/heads/main"], + "exclude": [] + } + }, + "rules": [ + { "type": "deletion" }, + { "type": "non_fast_forward" }, + { + "type": "pull_request", + "parameters": { + "required_approving_review_count": 0, + "dismiss_stale_reviews_on_push": true, + "require_code_owner_review": false, + "require_last_push_approval": false, + "required_review_thread_resolution": true, + "allowed_merge_methods": ["merge"] + } + } + ], + "bypass_actors": [] +} diff --git a/.github/workflows/branch-policy.yml b/.github/workflows/branch-policy.yml new file mode 100644 index 0000000..2dcdad1 --- /dev/null +++ b/.github/workflows/branch-policy.yml @@ -0,0 +1,38 @@ +name: Branch policy + +on: + pull_request_target: + types: [opened, reopened, synchronize, edited] + +permissions: {} + +jobs: + branch-policy: + name: branch-policy + runs-on: ubuntu-latest + steps: + - name: Check source branch + env: + BASE: ${{ github.base_ref }} + HEAD: ${{ github.head_ref }} + HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }} + REPO: ${{ github.repository }} + run: | + case "$BASE" in + main) + if [ "$HEAD" != "develop" ] || [ "$HEAD_REPO" != "$REPO" ]; then + echo "::error::main accepts pull requests only from develop in $REPO (got $HEAD_REPO:$HEAD)." + exit 1 + fi + ;; + develop) + case "$HEAD" in + feature/*|slice/*|fix/*|chore/*|docs/*|dependabot/*) ;; + *) + echo "::error::develop accepts pull requests only from feature/, slice/, fix/, chore/, docs/, or dependabot/ branches (got $HEAD)." + exit 1 + ;; + esac + ;; + esac + echo "Pull request $HEAD -> $BASE is allowed." diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..eb97fa6 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,25 @@ +name: CI + +on: + pull_request: + types: [opened, reopened, synchronize, edited] + push: + branches: [main, develop] + +permissions: + contents: read + +jobs: + build: + runs-on: windows-latest + env: + DOTNET_NOLOGO: true + DOTNET_CLI_TELEMETRY_OPTOUT: true + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-dotnet@v6 + with: + global-json-file: global.json + - run: dotnet restore FocusRGB-Plugin-SignalRGB.slnx + - run: dotnet build FocusRGB-Plugin-SignalRGB.slnx -c Release --no-restore + - run: dotnet test --solution FocusRGB-Plugin-SignalRGB.slnx -c Release --no-build diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..03988e7 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,102 @@ +name: Release + +on: + push: + tags: ['v*'] + workflow_dispatch: + pull_request: + paths: + - .github/workflows/release.yml + - src/FocusRgb.Plugin.SignalRgb/** + - LICENSE + +permissions: + contents: read + +jobs: + release: + runs-on: windows-latest + env: + DOTNET_NOLOGO: true + DOTNET_CLI_TELEMETRY_OPTOUT: true + PACKAGE_SUFFIX: ${{ github.event_name == 'push' && github.ref_name || format('dry-run-{0}', github.run_number) }} + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + - name: Validate release tag + if: github.event_name == 'push' + shell: pwsh + env: + RELEASE_REF: ${{ github.ref_name }} + run: | + if ($env:RELEASE_REF -notmatch '^v([0-9]+\.[0-9]+\.[0-9]+)$') { + throw "Release tags must use vMAJOR.MINOR.PATCH." + } + $tagVersion = $Matches[1] + $manifest = Get-Content src/FocusRgb.Plugin.SignalRgb/focusrgb-plugin.json -Raw | ConvertFrom-Json + if ($manifest.version -ne $tagVersion) { + throw "Plugin manifest version must equal tag version $tagVersion." + } + git fetch origin --no-tags "+refs/heads/main:refs/remotes/origin/main" + if ($LASTEXITCODE -ne 0) { throw "Could not refresh main history." } + git merge-base --is-ancestor $env:GITHUB_SHA origin/main + if ($LASTEXITCODE -ne 0) { throw "Release commits must belong to main history." } + exit 0 + - uses: actions/setup-dotnet@v6 + with: + global-json-file: global.json + - run: dotnet restore FocusRGB-Plugin-SignalRGB.slnx + - run: dotnet test --solution FocusRGB-Plugin-SignalRGB.slnx -c Release + - name: Assemble package + shell: pwsh + run: | + dotnet publish src/FocusRgb.Plugin.SignalRgb/FocusRgb.Plugin.SignalRgb.csproj -c Release --no-restore --no-self-contained -o build/package/signalrgb + Copy-Item src/FocusRgb.Plugin.SignalRgb/focusrgb-plugin.json build/package/signalrgb/ + Copy-Item LICENSE build/package/signalrgb/ + $zip = "build/FocusRGB-Plugin-SignalRGB-${{ env.PACKAGE_SUFFIX }}.zip" + $manifest = "build/focusrgb-plugin.json" + Compress-Archive build/package/signalrgb/* $zip + Copy-Item src/FocusRgb.Plugin.SignalRgb/focusrgb-plugin.json $manifest + $checksumLines = @($zip, $manifest) | ForEach-Object { + $hash = (Get-FileHash $_ -Algorithm SHA256).Hash.ToLowerInvariant() + "$hash $(Split-Path $_ -Leaf)" + } + $checksumPath = Join-Path $PWD build/SHA256SUMS + [IO.File]::WriteAllText( + $checksumPath, ($checksumLines -join "`n") + "`n", [Text.UTF8Encoding]::new($false)) + if ([IO.File]::ReadAllText($checksumPath).Contains("`r")) { + throw "SHA256SUMS must use LF line endings." + } + if ((Get-Content build/SHA256SUMS).Count -ne 2) { + throw "SHA256SUMS must contain the package and manifest hashes." + } + - name: Upload release assets + uses: actions/upload-artifact@v7 + with: + name: FocusRGB-Plugin-SignalRGB-${{ env.PACKAGE_SUFFIX }} + path: | + build/FocusRGB-Plugin-SignalRGB-${{ env.PACKAGE_SUFFIX }}.zip + build/focusrgb-plugin.json + build/SHA256SUMS + if-no-files-found: error + + publish: + if: github.event_name == 'push' + needs: release + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/download-artifact@v8 + with: + name: FocusRGB-Plugin-SignalRGB-${{ github.ref_name }} + path: build + - uses: softprops/action-gh-release@v3 + with: + files: | + build/FocusRGB-Plugin-SignalRGB-${{ github.ref_name }}.zip + build/focusrgb-plugin.json + build/SHA256SUMS + generate_release_notes: true + prerelease: true diff --git a/.gitignore b/.gitignore index d202df7..790c803 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ build/ +graphify-out/ bin/ obj/ TestResults/ diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..94fd716 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,19 @@ + + + $(MSBuildThisFileDirectory)build/artifacts + net10.0 + latest + enable + enable + true + latest-recommended + true + true + $(MSBuildThisFileDirectory)=/_/,$(ArtifactsPath)=/_/artifacts/ + 0.2.0 + Devantix + Devantix + Copyright (c) 2026 Devantix + FocusRGB SignalRGB Plugin + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..2903b25 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,9 @@ + + + true + + + + + + diff --git a/FocusRGB-Plugin-SignalRGB.slnx b/FocusRGB-Plugin-SignalRGB.slnx new file mode 100644 index 0000000..4cd86a7 --- /dev/null +++ b/FocusRGB-Plugin-SignalRGB.slnx @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/LICENSE b/LICENSE index b9d5a99..2bb5f7f 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2026 Amin Javan +Copyright (c) 2026 Devantix Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/NuGet.Config b/NuGet.Config new file mode 100644 index 0000000..02d939c --- /dev/null +++ b/NuGet.Config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/README.md b/README.md new file mode 100644 index 0000000..7c967df --- /dev/null +++ b/README.md @@ -0,0 +1,54 @@ +# FocusRGB SignalRGB plugin + +> See the [SignalRGB plugin guide](https://github.com/FocusRGB/FocusRGB/wiki/SignalRGB-plugin) for setup, requirements, and output status. + +FocusRGB logo + +This repository contains the optional SignalRGB output plugin for +[FocusRGB](https://github.com/FocusRGB/FocusRGB). It is independently buildable and consumes the +published `FocusRgb.PluginSdk` package; it is not a submodule and has no source dependency on the +FocusRGB checkout. + +Version 1.0 provides: + +- SignalRGB process and launcher discovery without pinning an installed version; +- a degraded, read-only catalog of installed bundled and downloaded effects; +- effect selection through SignalRGB's documented application URL while SignalRGB is already + running; and +- honest `unsupported` results for layout catalog, selection, and export. + +The plugin never starts SignalRGB implicitly. Application-URL submission cannot confirm visible +lighting, so a successful request returns `unverified`, not `applied`. Layout omission sends no +layout command and preserves SignalRGB's current placements. + +## Build and test + +`FocusRgb.PluginSdk` restores from nuget.org without repository credentials: + +```powershell +dotnet restore FocusRGB-Plugin-SignalRGB.slnx +dotnet build FocusRGB-Plugin-SignalRGB.slnx -c Release --no-restore +dotnet test --solution FocusRGB-Plugin-SignalRGB.slnx -c Release --no-build +``` + +## Package permissions + +The manifest declares the resources used by the plugin: + +- `process.read` checks whether SignalRGB is already running; +- `filesystem.read` discovers the installed launcher and effect files; and +- `process.start` submits an application URL through the launcher only after the running-process + check succeeds. + +Provider research and developer utilities moved from the main repository are retained under +[`research/`](research/) for evidence and reproduction. They are not part of the release package. + +## Releases and discovery + +The repository uses the `focusrgb-plugin` GitHub topic so FocusRGB can discover it as an official +plugin. Each stable release publishes the installable zip, a standalone `focusrgb-plugin.json` +for listing metadata, and `SHA256SUMS` covering both files. Pull requests that change packaging +run the same assembly path and upload those three files as a dry-run artifact. + + +Assisted-by: OpenAI Codex diff --git a/assets/logo-128.png b/assets/logo-128.png new file mode 100644 index 0000000..c09f8e3 Binary files /dev/null and b/assets/logo-128.png differ diff --git a/global.json b/global.json new file mode 100644 index 0000000..0777cf7 --- /dev/null +++ b/global.json @@ -0,0 +1,9 @@ +{ + "sdk": { + "version": "10.0.401", + "rollForward": "latestFeature" + }, + "test": { + "runner": "Microsoft.Testing.Platform" + } +} diff --git a/research/archive/screen-ambience-deskoff-pro-required.html b/research/archive/screen-ambience-deskoff-pro-required.html new file mode 100644 index 0000000..0312b52 --- /dev/null +++ b/research/archive/screen-ambience-deskoff-pro-required.html @@ -0,0 +1,203 @@ + + Screen Ambience Desk Off (Pro-required experiment) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/research/docs/capability-investigation-2026-10-18.md b/research/docs/capability-investigation-2026-10-18.md new file mode 100644 index 0000000..db38ea0 --- /dev/null +++ b/research/docs/capability-investigation-2026-10-18.md @@ -0,0 +1,105 @@ +# SignalRGB capability investigation — 2026-10-18 + +This is the read-only evidence record for Slice 14. The installed client was not started, no +application URL was submitted, and no lighting, layout, device, account, or provider setting was +changed. Results are specific to SignalRGB 2.5.80 and the account/cache state on this machine. + +## Decision table + +| Capability | Result | Evidence and consequence for Slice 15 | +|---|---|---| +| Process discovery | Verified | `SignalRgb.exe` is the process name and the latest executable is `%LOCALAPPDATA%\VortxEngine\app-2.5.80\Signal-x64\SignalRgb.exe` (file version `2.5.80.0`). No process was running during this check. Discover the newest semantic `app-*` directory; do not pin a version. | +| Launcher discovery | Verified | `%LOCALAPPDATA%\VortxEngine\SignalRgbLauncher.exe` exists (file version `1.0.0.1`). The reviewer's live check found the `signalrgb:` protocol registered in both HKCU and HKCR and pointing to this launcher. SignalRGB also documents direct launcher use with `--url`; use the launcher path because shell registration cannot be assumed on every machine. | +| Effect catalog | Verified with limits | Five bundled effects and two downloaded cached effects were readable without starting SignalRGB. The cache is evidence for this installation, not a stable API. Prefer the documented Local API when authorized; use file discovery only as an explicitly degraded catalog with honest availability. | +| Current effect | Unavailable in this session | The documented read-only endpoint is `GET http://127.0.0.1:16038/api/v1/lighting`. SignalRGB was stopped and port 16038 was not listening. A prior 2.5.74 check found the lighting API Pro-gated on this account. Do not infer the current effect from cache files. | +| Effect selection | Verified historically; not repeated | The documented `signalrgb://effect/apply/` route previously selected installed/free effects through `SignalRgbLauncher.exe`. It provides no trustworthy confirmation of visible output. The Local API apply route was Pro-gated on this account. Slice 15 may expose launcher selection, but must report submission separately from confirmed application. | +| Layout catalog/current layout | Unavailable in this session | SignalRGB documents `GET /api/v1/scenes/layouts` and `GET /api/v1/scenes/current_layout`. The process was stopped, and no readable local layout state was present. The plugin must report this capability unavailable until a live authorized check succeeds. | +| Layout export/geometry | Unavailable | The documented Local API lists layout names and the selected layout only. It exposes no read/export endpoint for device positions, rotation, scale, inversion, or layout brightness. Do not advertise layout export from this interface. | +| Account restrictions | Verified | Official API documentation says most Local API endpoints require Pro and return HTTP 403 when the running user is unsigned or not Pro. The earlier 2.5.74 live check received this result for lighting reads and writes. URL submission is not an entitlement bypass. | +| External application endpoints | Verified | Officially documented surfaces are application URLs for effect/page navigation and Canvas events at `http://localhost:16034/canvas/event`. Canvas events target a selected custom lightscript; they do not select that effect. No request was sent during this read-only slice. | +| MCP transport | Unavailable in 2.5.80 | `app-2.5.74\Signal-x64\SignalRgbMcp.exe` exists (file version `1.0.0.1`), but the executable was removed from `app-2.5.80`. The repository launcher selects the newest `app-*` directory and therefore fails with 2.5.80. MCP tool names recorded in old research are not a supported wire contract for the plugin. | + +## Resolved fixture names + +The exact installed names are: + +| Profile | Effect name | Local evidence | +|---|---|---| +| Default | `Aurora` | Cache catalog ID `-M6kb-ZFTdoKW5tRxV8Y`, price 0, downloaded effect file present | +| Programming | `Aurora` | Same catalog item | +| Movie | `Screen Ambience` | Bundled `Effects\Dynamic\Screen Ambience.html`; its HTML title is also `Screen Ambience` | +| Music | `Logarithmic Visualizer` | Cache catalog ID `-NZhF99k6cK__Zyh4yNx`, price 0, downloaded effect file present | + +`Screen Ambient` was not present in the bundled effects, downloaded effect cache, or cached +catalog. The seeded Movie fixture has therefore been corrected to `Screen Ambience`. Resource +IDs remain unset in defaults because the two marketplace IDs are provider-owned cache data and +the built-in effect uses a filename rather than the same catalog identifier shape. Slice 15 must +resolve fresh, exact, case-sensitive names through the provider catalog. + +## Reproduce the local read-only checks + +Run these commands without starting SignalRGB: + +```powershell +$base = Join-Path $env:LOCALAPPDATA 'VortxEngine' +$app = Get-ChildItem -LiteralPath $base -Directory -Filter 'app-*' | + Sort-Object { [version]($_.Name.Substring(4)) } -Descending | + Select-Object -First 1 +$signalDir = Join-Path $app.FullName 'Signal-x64' + +Get-Item -LiteralPath (Join-Path $base 'SignalRgbLauncher.exe'), + (Join-Path $signalDir 'SignalRgb.exe') | + Select-Object FullName, @{n='FileVersion';e={$_.VersionInfo.FileVersion}} + +Get-CimInstance Win32_Process -Filter "Name = 'SignalRgb.exe'" +Get-NetTCPConnection -State Listen | + Where-Object LocalPort -in 16034,16038 + +Get-ChildItem -LiteralPath (Join-Path $signalDir 'Effects') -File -Recurse -Filter '*.html' | + Select-Object BaseName, FullName + +reg.exe query 'HKCU\Software\Classes\signalrgb' /s +reg.exe query 'HKCR\signalrgb' /s + +Get-ChildItem -LiteralPath $base -File -Recurse -Filter 'SignalRgbMcp.exe' +``` + +The cached marketplace catalog used only to reconcile fixture spelling is: + +```text +%LOCALAPPDATA%\WhirlwindFX\SignalRgb\cache\catalog_en.json +``` + +Its timestamp was `2026-10-15 14:26:35Z`. Treat it as stale whenever SignalRGB has not refreshed +it, and never treat a marketplace entry as installed merely because it appears in this file. + +## Documented interfaces + +- [Local API introduction](https://docs.signalrgb.com/developer/signalrgb-api/introduction/) + documents the `http://127.0.0.1:16038/api/v1` base URL, unstable contract warning, and Pro + restriction. +- [Lighting API](https://docs.signalrgb.com/developer/signalrgb-api/lighting/) documents current + effect and installed-effect reads plus effect application. +- [Layouts API](https://docs.signalrgb.com/developer/signalrgb-api/layouts/) documents current + layout and layout-name reads; it does not document geometry export. +- [Application URLs](https://docs.signalrgb.com/developer/application-urls/) and + [game/app integrations](https://docs.signalrgb.com/lightscripts/creating-dev-integrations/) + document effect URLs, direct launcher use, URL encoding, silent launch, and Canvas events. +- [Pro features](https://docs.signalrgb.com/gettingstarted/free-vs--pro/) documents account and + device-class restrictions that can affect otherwise installed effects. + +## Slice 15 constraints + +- Implement process and launcher discovery without a pinned application version. +- Treat capabilities independently: launcher effect submission may be supported while current + effect, effect catalog, or layouts are unavailable. +- Never claim an effect was applied from launcher exit alone; expose a pending/unconfirmed result + unless a read-back surface verifies it. +- Do not implement layout export or MCP transport against this client version. +- Schema 4 settings migrate the unresolved seeded Movie effect from `Screen Ambient` to + `Screen Ambience`; resolved or custom resource references are preserved. +- Preserve provider authority: the plugin selects provider resources but does not control devices + directly. + +Assisted-by: OpenAI Codex + diff --git a/research/docs/developer-cheatsheet.md b/research/docs/developer-cheatsheet.md new file mode 100644 index 0000000..3fda3a6 --- /dev/null +++ b/research/docs/developer-cheatsheet.md @@ -0,0 +1,108 @@ +# SignalRGB developer cheat sheet + +## Paths + +| What | Path | +|---|---| +| Custom effects | `%USERPROFILE%\Documents\WhirlwindFX\Effects\` | +| User plugins | `%USERPROFILE%\Documents\WhirlwindFX\Plugins\` | +| Components | `%USERPROFILE%\Documents\WhirlwindFX\Components\` | +| Built-in plugins/effects | `%LOCALAPPDATA%\VortxEngine\app-\Signal-x64\Plugins\`, `...\effects\` | +| Logs | `%LOCALAPPDATA%\VortxEngine\app-\Signal-x64\Logs\` | +| Canvas API | `POST http://localhost:16034/canvas/event?sender=&event=` | + +New effect files: restart SignalRGB. User plugins override built-ins with the same VID/PID. + +## Effects (lightscripts) + +An effect is an HTML page. SignalRGB renders it on a 320x200 canvas and each device samples +its own rectangle of that canvas. + +```html + + Name + + + + + + + + + + + + +``` + +Game integrations are effects that either (a) implement `onCanvasApiEvent` and get HTTP POSTs +from a game/mod/script, or (b) use a UI analyzer to read screen pixels (see docs). + +## Plugins (device drivers) + +Exports SignalRGB calls: + +| Export | Returns | +|---|---| +| `Name()`, `Publisher()`, `Documentation()` | strings | +| `VendorId()`, `ProductId()` | `0xNNNN` | +| `Type()` | `"Hid"` (default) or `"RawUsb"` | +| `Size()` | `[w, h]` canvas cells | +| `DefaultPosition()`, `DefaultScale()` | `[x, y]`, float 1..30 | +| `LedNames()`, `LedPositions()` | arrays, same length, positions `[x, y]` within Size | +| `ControllableParameters()` | array of `{property,label,type,default,min,max,step,values,group}` | +| `Validate(endpoint)` | bool; `endpoint.interface / usage / usage_page / collection` | +| `ConflictingProcesses()` | `["Foo.exe"]` | +| `ImageUrl()` | string | +| `Initialize()` | once on connect | +| `Render()` | every frame (~30 ms) | +| `Shutdown(SystemSuspending)` | on exit / sleep | +| `onChanged()` | after a control changes | + +Device object inside a plugin: + +| Call | Meaning | +|---|---| +| `device.color(x, y)` | `[r,g,b]` sampled from the canvas | +| `device.write(bytes, len)` | HID output report | +| `device.send_report(bytes, len)` | HID feature report | +| `device.read(bytes, len, timeoutMs?)` | HID input read (blocking; `0` = peek) | +| `device.get_report(bytes, len)` | HID feature read | +| `device.getLastReadSize()` | bytes returned by last read | +| `device.clearReadBuffer()`, `device.flush()` | drop queued input | +| `device.control_transfer(...)` | raw USB control transfer (RawUsb) | +| `device.pause(ms)` | throttle the render loop | +| `device.log(text)` | to device log / console | + +Control types: `boolean`, `number`, `hue`, `color`, `combobox`, `textfield`. +Declare a top-level `let = ` for each control. + +## Finding VID/PID and endpoints on this PC + +```powershell +Get-PnpDevice -PresentOnly | Where-Object InstanceId -match 'VID_1532' | + ForEach-Object { $_.InstanceId; (Get-PnpDeviceProperty $_.InstanceId DEVPKEY_Device_HardwareIds).Data -match 'UP:' } +``` + +`UP:xxxx_U:yyyy` in the hardware ID is the usage page / usage a `Validate()` can match on. +Razer vendor collections are usually `usage_page 0xFF00`-range. Wireshark + USBPcap captures the +packets the vendor app sends; see the plugin tutorial. + +## Links + +- https://docs.signalrgb.com/developer/ +- https://docs.signalrgb.com/developer/lightscripts/ +- https://docs.signalrgb.com/developer/lightscripts/creating-dev-integrations/ +- https://docs.signalrgb.com/developer/plugins/plugin-exports/ +- https://docs.signalrgb.com/developer/plugins/writes-and-reads/ +- https://docs.signalrgb.com/developer/plugins/user-controls/ +- https://docs.signalrgb.com/developer/plugins/tutorial/ +- https://docs.signalrgb.com/guides/installation-setup/file-locations/ +- https://github.com/SRGBmods/public +- https://github.com/Derek4aty1/signalrgb-extras + diff --git a/research/effects/README.md b/research/effects/README.md new file mode 100644 index 0000000..af9fb83 --- /dev/null +++ b/research/effects/README.md @@ -0,0 +1,14 @@ +# effects/ + +Active custom SignalRGB effects only. The install script copies every `.html` and matching +`.png` in this folder into SignalRGB's user Effects folder. + +This folder is currently empty because no custom effect is part of the live setup. + +- Starter: `../templates/signalrgb-effect.html` +- Canvas API example: `../examples/signalrgb-canvas-event-demo.html` +- Blocked Pro experiment: `../archive/screen-ambience-deskoff-pro-required.html` + +Copy a file here only when it should be installed, then run +`..\tools\install-signalrgb-content.ps1 -Effects`. Restart SignalRGB when adding a new file. + diff --git a/research/examples/signalrgb-canvas-event-demo.html b/research/examples/signalrgb-canvas-event-demo.html new file mode 100644 index 0000000..012e21f --- /dev/null +++ b/research/examples/signalrgb-canvas-event-demo.html @@ -0,0 +1,69 @@ + + SignalRGB Canvas Event Demo + + + + + + + + + + + + + + + + diff --git a/research/plugins/README.md b/research/plugins/README.md new file mode 100644 index 0000000..4bd9015 --- /dev/null +++ b/research/plugins/README.md @@ -0,0 +1,21 @@ +# plugins/ + +These are **SignalRGB USB device plugins**, not the planned controller's plugin system. +For app-detection and external-app/RGB adapters, see +[controller architecture](../../../docs/plugin-architecture.md). + +One `.js` per USB device. SignalRGB matches the file to hardware by `VendorId()` + `ProductId()`. +A user plugin here overrides the built-in one with the same IDs, so you can also patch +SignalRGB's own Razer plugin by copying it from +`%LOCALAPPDATA%\VortxEngine\app-\Signal-x64\Plugins\` and editing. + +This folder is currently empty because the keyboard and mouse use SignalRGB's built-in +Razer plugin and WLED needs no user plugin. + +Start new device work from `../templates/signalrgb-device-plugin.js`, then copy the completed +plugin here and run `..\tools\install-signalrgb-content.ps1 -Plugins`. + +Workflow for a new device: capture USB traffic from the vendor app with Wireshark + USBPcap, +find the color packet format, then fill in `Validate`, `Initialize`, and `sendColors`. +See https://docs.signalrgb.com/developer/plugins/tutorial/ + diff --git a/research/staging-overview.md b/research/staging-overview.md new file mode 100644 index 0000000..744c3d6 --- /dev/null +++ b/research/staging-overview.md @@ -0,0 +1,100 @@ +# Migrated SignalRGB research material + +This directory preserves the SignalRGB research, examples, and tools moved from the FocusRGB +staging module when this external plugin repository was created. The production plugin is under +`src/`; research content is not installed or packaged with releases. + +Everything specific to the interim SignalRGB backend lives in this directory. The future +controller accesses it only through the provider-neutral integration interface and loads the +SignalRGB implementation as a separate plugin. SignalRGB code must not be compiled into or +referenced by the core or Avalonia app projects. Removing this plugin must not require +rewriting detection, persistence, rules, layouts, or other application integrations. + +The controller plugin must expose SignalRGB's available effects and layouts through the shared +catalog contract where supported and apply the user's effect with provider rendering authority. +An explicit layout is optional: omission retains SignalRGB's existing LED placements. While +active, SignalRGB's effect/layout wins and the controller must not run its native renderer on +the same owned devices. Catalog discovery and application success must be reported honestly; +do not invent resources or treat a submitted URL as proof of visible output. + +SignalRGB already outputs to WLED. Its authority supersedes app rendering, placements, routing, +and calibration on managed devices; a separate WLED plugin is used after release for native +tests. Optional layout export supplies placement data only and does not grant device ownership. + +## Layout + +```text +effects/ active custom lightscripts; currently empty +plugins/ active SignalRGB user device plugins; currently empty +templates/ starters that are not installed automatically +examples/ integration examples that are not installed automatically +archive/ retained experiments that are not part of the live setup +tools/ SignalRGB install, Canvas API, and MCP launch utilities +docs/ SignalRGB reference and capability research +``` + +Only files deliberately placed in `effects/` or `plugins/` are installed into SignalRGB. +The research directory remains separate from the controller runtime and published plugin SDK. + +## Where SignalRGB looks + +| Content | Path | +|---|---| +| Custom effects | `%USERPROFILE%\Documents\WhirlwindFX\Effects\` | +| User plugins | `%USERPROFILE%\Documents\WhirlwindFX\Plugins\` | +| Components | `%USERPROFILE%\Documents\WhirlwindFX\Components\` | +| Built-ins | `%LOCALAPPDATA%\VortxEngine\app-\Signal-x64\` | +| Logs | `%LOCALAPPDATA%\VortxEngine\app-\Signal-x64\Logs\` | + +The installer detects redirected Documents folders such as OneDrive. User plugins override +built-in plugins with the same VID/PID and survive SignalRGB updates. + +## Content workflow + +1. Check the [recorded limitations](../../docs/integration-evidence.md). Available features + depend on the effect, device, account, and interface. +2. Copy a starter from `templates/` or `examples/` into `effects/` or `plugins/` only when it + should become active SignalRGB user content. +3. From the repository root, run: + + ```powershell + research\tools\install-signalrgb-content.ps1 + ``` + + Add `-Watch`, `-Effects`, or `-Plugins` when needed. +4. Restart SignalRGB for a new effect file. Existing effects reload when reselected; plugins + reload after device reconnect or SignalRGB restart. + +## Canvas API example + +Effects receive external events at: + +```text +POST http://localhost:16034/canvas/event?sender=&event= +``` + +```powershell +research\tools\send-signalrgb-canvas-event.ps1 -Sender demo -Event hit +python research\tools\send-signalrgb-canvas-event.py demo hit +``` + +[`examples/signalrgb-canvas-event-demo.html`](examples/signalrgb-canvas-event-demo.html) +handles `hit`, `heal`, `low`, and `idle`. Copy it into `effects/`, install it, and select it +manually before sending events. + +## MCP launcher + +`tools/signalrgb-mcp.cmd` resolves the newest installed SignalRGB version instead of pinning +an `app-*` directory. The executable was removed from SignalRGB 2.5.80, so the tool is retained +only for reproducing older-version observations. + +## References + +- [Slice 14 capability investigation](docs/capability-investigation-2026-10-18.md) +- [Developer cheat sheet](docs/developer-cheatsheet.md) +- [SignalRGB developer hub](https://docs.signalrgb.com/developer/) +- [Lightscripts](https://docs.signalrgb.com/developer/lightscripts/) +- [Game/app integrations](https://docs.signalrgb.com/developer/lightscripts/creating-dev-integrations/) +- [Plugin exports](https://docs.signalrgb.com/developer/plugins/plugin-exports/) +- [Plugin tutorial](https://docs.signalrgb.com/developer/plugins/tutorial/) + diff --git a/research/templates/signalrgb-device-plugin.js b/research/templates/signalrgb-device-plugin.js new file mode 100644 index 0000000..c78c693 --- /dev/null +++ b/research/templates/signalrgb-device-plugin.js @@ -0,0 +1,95 @@ +// SignalRGB device plugin template. Copy it into plugins/ before installing. +// Copy, rename, fill in VID/PID/endpoint/packet format. Loaded from Documents\WhirlwindFX\Plugins\. +// Reference: https://docs.signalrgb.com/developer/plugins/plugin-exports/ +// Tutorial (capture USB traffic with Wireshark, then map it): https://docs.signalrgb.com/developer/plugins/tutorial/ + +export function Name() { return "SignalRGB Device Template"; } +export function Publisher() { return "you"; } +export function VendorId() { return 0x0000; } // USB VID, e.g. 0x1532 for Razer +export function ProductId() { return 0x0000; } // USB PID +export function Documentation() { return "troubleshooting/brand"; } +export function Type() { return "Hid"; } // "Hid" (default) or "RawUsb" +export function Size() { return [8, 2]; } // canvas cells [width, height] the device occupies +export function DefaultPosition() { return [120, 80]; } +export function DefaultScale() { return 8.0; } +export function ImageUrl() { return ""; } // 1024x1024 png URL, optional + +// Executables that must not be running for this plugin to initialize. +export function ConflictingProcesses() { return []; } + +/* global +shutdownColor:readonly +LightingMode:readonly +forcedColor:readonly +*/ +export function ControllableParameters() { + return [ + { "property": "shutdownColor", "group": "lighting", "label": "Shutdown Color", "min": "0", "max": "360", "type": "color", "default": "#009bde" }, + { "property": "LightingMode", "group": "lighting", "label": "Lighting Mode", "type": "combobox", "values": ["Canvas", "Forced"], "default": "Canvas" }, + { "property": "forcedColor", "group": "lighting", "label": "Forced Color", "min": "0", "max": "360", "type": "color", "default": "#009bde" }, + ]; +} + +// One entry per LED. Positions are [x, y] inside Size(). +const vLedNames = [ + "Led 1", "Led 2", "Led 3", "Led 4", "Led 5", "Led 6", "Led 7", "Led 8", +]; +const vLedPositions = [ + [0, 0], [1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], +]; +export function LedNames() { return vLedNames; } +export function LedPositions() { return vLedPositions; } + +// Pick which HID interface/collection to open. Get these numbers from the +// device's HID report descriptor or from SignalRGB's device log. +export function Validate(endpoint) { + return endpoint.interface === 0 && endpoint.usage === 0x0000 && endpoint.usage_page === 0x0000 && endpoint.collection === 0x0000; +} + +export function Initialize() { + // Send any handshake / "enter software mode" packets here. + device.log("Initialize"); +} + +export function Render() { + sendColors(); + device.pause(1); // ms; keeps the render loop from saturating the USB bus +} + +export function Shutdown(SystemSuspending) { + if (SystemSuspending) { + sendColors("#000000"); // go dark on sleep/shutdown + } else { + sendColors(shutdownColor); // user-chosen color when SignalRGB exits + } +} + +// Called by SignalRGB right after a user changes the matching control. +export function onLightingModeChanged() { device.log("LightingMode -> " + LightingMode); } + +function sendColors(overrideColor) { + // Example: [reportId, header..., r,g,b, r,g,b, ...] -- replace with your device's real format. + const packet = [0x00, 0x00, 0x00, 0x00]; + const headerLen = packet.length; + + for (let i = 0; i < vLedPositions.length; i++) { + const [x, y] = vLedPositions[i]; + let rgb; + if (overrideColor) rgb = hexToRgb(overrideColor); + else if (LightingMode === "Forced") rgb = hexToRgb(forcedColor); + else rgb = device.color(x, y); // sample the canvas + packet[headerLen + i * 3 + 0] = rgb[0]; + packet[headerLen + i * 3 + 1] = rgb[1]; + packet[headerLen + i * 3 + 2] = rgb[2]; + } + + // device.write(packet, 65) -> HID output report + // device.send_report(packet, 65) -> HID feature report + device.send_report(packet, 65); +} + +function hexToRgb(hex) { + const m = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + return m ? [parseInt(m[1], 16), parseInt(m[2], 16), parseInt(m[3], 16)] : [0, 0, 0]; +} + diff --git a/research/templates/signalrgb-effect.html b/research/templates/signalrgb-effect.html new file mode 100644 index 0000000..dac856a --- /dev/null +++ b/research/templates/signalrgb-effect.html @@ -0,0 +1,53 @@ + + SignalRGB Effect Template + + + + + + + + + + + + + + + + + diff --git a/research/tools/install-signalrgb-content.ps1 b/research/tools/install-signalrgb-content.ps1 new file mode 100644 index 0000000..3c541b5 --- /dev/null +++ b/research/tools/install-signalrgb-content.ps1 @@ -0,0 +1,65 @@ +<# +.SYNOPSIS + Installs active effects/ and plugins/ from this module into SignalRGB's user folders. +.EXAMPLE + .\install-signalrgb-content.ps1 # one-shot install + .\install-signalrgb-content.ps1 -Watch # re-install whenever a file changes + .\install-signalrgb-content.ps1 -Effects # only effects + .\install-signalrgb-content.ps1 -Plugins # only plugins +#> +param( + [switch]$Watch, + [switch]$Effects, + [switch]$Plugins +) + +$ErrorActionPreference = 'Stop' +$repo = Split-Path -Parent $PSScriptRoot + +# SignalRGB reads from Documents\WhirlwindFX; Documents may be redirected to OneDrive. +$docs = [Environment]::GetFolderPath('MyDocuments') +$base = Join-Path $docs 'WhirlwindFX' + +if (-not $Effects -and -not $Plugins) { $Effects = $true; $Plugins = $true } + +$jobs = @() +if ($Effects) { $jobs += @{ src = Join-Path $repo 'effects'; dst = Join-Path $base 'Effects'; filter = @('*.html','*.png') } } +if ($Plugins) { $jobs += @{ src = Join-Path $repo 'plugins'; dst = Join-Path $base 'Plugins'; filter = @('*.js') } } + +function Sync-Once { + foreach ($j in $jobs) { + if (-not (Test-Path $j.dst)) { New-Item -ItemType Directory -Force -Path $j.dst | Out-Null } + $files = Get-ChildItem -Path $j.src -Include $j.filter -File -Recurse + foreach ($f in $files) { + $target = Join-Path $j.dst $f.Name + $changed = -not (Test-Path $target) -or ((Get-Item $target).LastWriteTimeUtc -lt $f.LastWriteTimeUtc) + if ($changed) { + Copy-Item -Path $f.FullName -Destination $target -Force + Write-Host ("[{0}] {1} -> {2}" -f (Get-Date -Format 'HH:mm:ss'), $f.Name, $j.dst) + } + } + } +} + +Write-Host "SignalRGB user folder: $base" +Sync-Once + +if ($Watch) { + Write-Host "Watching for changes (Ctrl+C to stop)..." + $watchers = @() + foreach ($j in $jobs) { + $w = New-Object System.IO.FileSystemWatcher $j.src + $w.IncludeSubdirectories = $true + $w.EnableRaisingEvents = $true + $watchers += $w + } + try { + while ($true) { + Start-Sleep -Milliseconds 500 + Sync-Once + } + } finally { + $watchers | ForEach-Object { $_.Dispose() } + } +} + diff --git a/research/tools/send-signalrgb-canvas-event.ps1 b/research/tools/send-signalrgb-canvas-event.ps1 new file mode 100644 index 0000000..2e2e09e --- /dev/null +++ b/research/tools/send-signalrgb-canvas-event.ps1 @@ -0,0 +1,24 @@ +<# +.SYNOPSIS + Sends a test event to SignalRGB's canvas API so an integration effect can react to it. +.EXAMPLE + .\send-signalrgb-canvas-event.ps1 -Sender demo -Event hit + .\send-signalrgb-canvas-event.ps1 demo low +#> +param( + [Parameter(Position=0)] [string]$Sender = 'demo', + [Parameter(Position=1)] [string]$Event = 'hit', + [int]$Port = 16034 +) +$s = [uri]::EscapeDataString($Sender) +$e = [uri]::EscapeDataString($Event) +$url = "http://localhost:$Port/canvas/event?sender=$s&event=$e" +try { + $r = Invoke-WebRequest -Method Post -Uri $url -UseBasicParsing -TimeoutSec 3 + Write-Host "POST $url -> $($r.StatusCode)" +} catch { + Write-Host "POST $url failed: $($_.Exception.Message)" + Write-Host "Is SignalRGB running, and is an effect that implements onCanvasApiEvent selected?" + exit 1 +} + diff --git a/research/tools/send-signalrgb-canvas-event.py b/research/tools/send-signalrgb-canvas-event.py new file mode 100644 index 0000000..163054c --- /dev/null +++ b/research/tools/send-signalrgb-canvas-event.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +"""Send a test event to SignalRGB's Canvas API. +Usage: python send-signalrgb-canvas-event.py [sender] [event] [--port 16034] +Example: python send-signalrgb-canvas-event.py demo hit +""" +import argparse +import sys +import urllib.parse +import urllib.request + +def send(sender="demo", event="hit", port=16034): + q = urllib.parse.urlencode({"sender": sender, "event": event}) + url = f"http://localhost:{port}/canvas/event?{q}" + req = urllib.request.Request(url, method="POST", data=b"") + with urllib.request.urlopen(req, timeout=3) as r: + print(f"POST {url} -> {r.status}") + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("sender", nargs="?", default="demo") + parser.add_argument("event", nargs="?", default="hit") + parser.add_argument("--port", type=int, default=16034) + args = parser.parse_args() + try: + send(args.sender, args.event, args.port) + except Exception as e: + print(f"failed: {e}\nIs SignalRGB running with an onCanvasApiEvent effect selected?") + return 1 + return 0 + +if __name__ == "__main__": + sys.exit(main()) + diff --git a/research/tools/signalrgb-mcp.cmd b/research/tools/signalrgb-mcp.cmd new file mode 100644 index 0000000..182714d --- /dev/null +++ b/research/tools/signalrgb-mcp.cmd @@ -0,0 +1,15 @@ +@echo off +REM Launch SignalRGB's MCP server, resolving the newest installed app-* version. +REM Pinning the version directly breaks on every SignalRGB update. +setlocal +set "BASE=%LOCALAPPDATA%\VortxEngine" +set "LATEST=" +for /f "delims=" %%d in ('dir /b /ad /o-d "%BASE%\app-*" 2^>nul') do ( + if not defined LATEST set "LATEST=%%d" +) +if not defined LATEST ( + echo SignalRGB install not found under %BASE% 1>&2 + exit /b 1 +) +"%BASE%\%LATEST%\Signal-x64\SignalRgbMcp.exe" %* + diff --git a/src/FocusRgb.Plugin.SignalRgb/FocusRgb.Plugin.SignalRgb.csproj b/src/FocusRgb.Plugin.SignalRgb/FocusRgb.Plugin.SignalRgb.csproj new file mode 100644 index 0000000..93b55dc --- /dev/null +++ b/src/FocusRgb.Plugin.SignalRgb/FocusRgb.Plugin.SignalRgb.csproj @@ -0,0 +1,13 @@ + + + Exe + FocusRgb.Plugin.SignalRgb + FocusRgb.Plugin.SignalRgb + + + + + + + + diff --git a/src/FocusRgb.Plugin.SignalRgb/ISignalRgbPlatform.cs b/src/FocusRgb.Plugin.SignalRgb/ISignalRgbPlatform.cs new file mode 100644 index 0000000..fc2e1fd --- /dev/null +++ b/src/FocusRgb.Plugin.SignalRgb/ISignalRgbPlatform.cs @@ -0,0 +1,15 @@ +namespace FocusRgb.Plugin.SignalRgb +{ + internal interface ISignalRgbPlatform + { + bool IsProviderRunning(); + + string? FindLauncher(); + + IReadOnlyList ListEffects(); + + void SubmitEffect(string launcherPath, string applicationUrl); + } + + internal sealed record SignalRgbEffect(string ResourceId, string DisplayName, bool Available, string? UnavailableReason = null); +} diff --git a/src/FocusRgb.Plugin.SignalRgb/Program.cs b/src/FocusRgb.Plugin.SignalRgb/Program.cs new file mode 100644 index 0000000..5cf966e --- /dev/null +++ b/src/FocusRgb.Plugin.SignalRgb/Program.cs @@ -0,0 +1,13 @@ +using FocusRgb.PluginSdk; + +namespace FocusRgb.Plugin.SignalRgb +{ + internal static class Program + { + public static Task Main() => PluginServer.RunAsync( + new SignalRgbPlugin(new WindowsSignalRgbPlatform()), + Console.In, + Console.Out, + Console.Error); + } +} diff --git a/src/FocusRgb.Plugin.SignalRgb/SignalRgbPlugin.cs b/src/FocusRgb.Plugin.SignalRgb/SignalRgbPlugin.cs new file mode 100644 index 0000000..773b9db --- /dev/null +++ b/src/FocusRgb.Plugin.SignalRgb/SignalRgbPlugin.cs @@ -0,0 +1,181 @@ +using FocusRgb.Contracts; +using FocusRgb.PluginSdk; + +namespace FocusRgb.Plugin.SignalRgb +{ + internal sealed class SignalRgbPlugin(ISignalRgbPlatform platform) : IFocusRgbPlugin + { + private static readonly PluginReason LayoutUnsupported = new() + { + Code = "capability-unsupported", + Message = "No supported SignalRGB layout interface is available. Omit the layout to retain provider placements." + }; + + public Task InitializeAsync( + InitializeParameters parameters, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(parameters); + return Task.FromResult(new InitializeResult + { + PluginId = "signalrgb", + PluginVersion = typeof(SignalRgbPlugin).Assembly.GetName().Version!.ToString(3), + ContractVersion = ContractVersion.Current, + Capabilities = + [ + Capability("provider.effect.catalog", "supported"), + Capability("provider.effect.select", "unverified", "selection-not-observable", + "SignalRGB accepts application URLs, but the selected effect cannot be read back reliably."), + Capability("provider.selection.observe", "unverified", "selection-not-observable", + "The current SignalRGB effect cannot be read back reliably."), + Capability("provider.layout.catalog", "unsupported", LayoutUnsupported.Code, LayoutUnsupported.Message), + Capability("provider.layout.select", "unsupported", LayoutUnsupported.Code, LayoutUnsupported.Message), + Capability("provider.layout.export", "unsupported", "capability-unsupported", + "SignalRGB does not expose layout geometry through a verified interface."), + Capability("provider.devices.report", "unsupported", "capability-unsupported", + "SignalRGB does not expose a verified managed-device catalog to this plugin.") + ] + }); + } + + public Task GetStatusAsync(CancellationToken cancellationToken) => + Task.FromResult(platform.IsProviderRunning() + ? new PluginStatusResult + { + Availability = "available", + Reason = Reason("selection-not-observable", + "SignalRGB is running, but its current effect cannot be read back reliably.") + } + : new PluginStatusResult + { + Availability = "unavailable", + Reason = Reason("provider-not-running", + "SignalRGB is not running. It will not be started automatically.") + }); + + public Task ListCatalogAsync( + CatalogListParameters parameters, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(parameters); + if (!string.Equals(parameters.Kind, "effect", StringComparison.Ordinal)) + { + return Task.FromResult(new PluginCatalogResult + { + Support = "unsupported", + Reason = LayoutUnsupported + }); + } + + var items = platform.ListEffects() + .Select(effect => new PluginCatalogItem + { + ResourceId = effect.ResourceId, + DisplayName = effect.DisplayName, + Available = effect.Available, + Reason = effect.Available + ? null + : Reason("resource-not-found", effect.UnavailableReason ?? "The effect is unavailable.") + }) + .ToArray(); + return Task.FromResult(new PluginCatalogResult + { + Support = "supported", + RefreshedAt = DateTimeOffset.UtcNow, + Items = items + }); + } + + public Task ApplyBindingAsync( + BindingApplyParameters parameters, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(parameters); + if (!string.Equals(parameters.RenderingAuthority, "provider", StringComparison.Ordinal)) + { + return Applied("unsupported", "capability-unsupported", + "The SignalRGB plugin supports provider rendering authority only."); + } + if (!string.Equals(parameters.DeviceScope.Kind, "provider-managed", StringComparison.Ordinal) + || parameters.DeviceScope.DeviceIds is { Count: > 0 }) + { + return Applied("unsupported", "capability-unsupported", + "The SignalRGB plugin supports provider-managed device scope only."); + } + if (parameters.Layout is not null) + { + return Task.FromResult(new BindingApplyResult + { + Outcome = "unsupported", + Reason = LayoutUnsupported + }); + } + if (parameters.Effect is null || string.IsNullOrWhiteSpace(parameters.Effect.ResourceId)) + { + return Applied("rejected", "resource-not-found", "A resolved SignalRGB effect is required."); + } + if (!platform.IsProviderRunning()) + { + return Applied("unavailable", "provider-not-running", + "SignalRGB is not running. It will not be started automatically."); + } + + var effect = platform.ListEffects().SingleOrDefault(item => + string.Equals(item.ResourceId, parameters.Effect.ResourceId, StringComparison.Ordinal)); + if (effect is null + || !effect.Available + || !string.Equals(effect.DisplayName, parameters.Effect.DisplayName, StringComparison.Ordinal)) + { + return Applied("unavailable", "resource-not-found", + "The requested SignalRGB effect is not present in the current catalog."); + } + + var launcher = platform.FindLauncher(); + if (launcher is null) + { + return Applied("unavailable", "provider-not-running", "The SignalRGB launcher was not found."); + } + + var encodedName = Uri.EscapeDataString(effect.DisplayName); + var applicationUrl = $"signalrgb://effect/apply/{encodedName}?-silentlaunch-"; + try + { + platform.SubmitEffect(launcher, applicationUrl); + } + catch (Exception exception) when (exception is InvalidOperationException or System.ComponentModel.Win32Exception) + { + return Applied("unavailable", "provider-not-running", exception.Message); + } + + return Applied("unverified", "selection-not-observable", + "The effect request was submitted, but visible output could not be read back."); + } + + public Task ReleaseBindingAsync( + BindingReleaseParameters parameters, + CancellationToken cancellationToken) => + Task.FromResult(new BindingReleaseResult { Outcome = "nothing-to-release" }); + + public Task ShutdownAsync(CancellationToken cancellationToken) => Task.CompletedTask; + + private static PluginCapability Capability( + string id, + string support, + string? code = null, + string? message = null) => new() + { + Id = id, + Support = support, + Reason = code is null || message is null ? null : Reason(code, message) + }; + + private static PluginReason Reason(string code, string message) => new() { Code = code, Message = message }; + + private static Task Applied(string outcome, string code, string message) => + Task.FromResult(new BindingApplyResult + { + Outcome = outcome, + Reason = Reason(code, message) + }); + } +} diff --git a/src/FocusRgb.Plugin.SignalRgb/WindowsSignalRgbPlatform.cs b/src/FocusRgb.Plugin.SignalRgb/WindowsSignalRgbPlatform.cs new file mode 100644 index 0000000..6340fd3 --- /dev/null +++ b/src/FocusRgb.Plugin.SignalRgb/WindowsSignalRgbPlatform.cs @@ -0,0 +1,166 @@ +using System.Diagnostics; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace FocusRgb.Plugin.SignalRgb +{ + internal sealed partial class WindowsSignalRgbPlatform : ISignalRgbPlatform + { + private const string BuiltInPrefix = "builtin:"; + private const string CatalogPrefix = "catalog:"; + private readonly string _localApplicationData; + + public WindowsSignalRgbPlatform() + : this(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)) + { + } + + internal WindowsSignalRgbPlatform(string localApplicationData) => + _localApplicationData = localApplicationData; + + public bool IsProviderRunning() + { + var processes = Process.GetProcessesByName("SignalRgb"); + try + { + return processes.Length > 0; + } + finally + { + foreach (var process in processes) process.Dispose(); + } + } + + public string? FindLauncher() + { + var path = Path.Combine(_localApplicationData, "VortxEngine", "SignalRgbLauncher.exe"); + return File.Exists(path) ? path : null; + } + + public IReadOnlyList ListEffects() + { + var effects = new List(); + AddBuiltInEffects(effects); + AddCachedEffects(effects); + return effects + .DistinctBy(effect => effect.ResourceId, StringComparer.Ordinal) + .OrderBy(effect => effect.DisplayName, StringComparer.Ordinal) + .ThenBy(effect => effect.ResourceId, StringComparer.Ordinal) + .ToArray(); + } + + public void SubmitEffect(string launcherPath, string applicationUrl) + { + var startInfo = new ProcessStartInfo + { + FileName = launcherPath, + UseShellExecute = false, + CreateNoWindow = true + }; + startInfo.ArgumentList.Add($"--url={applicationUrl}"); + using var process = Process.Start(startInfo) + ?? throw new InvalidOperationException("The SignalRGB launcher did not start."); + } + + private void AddBuiltInEffects(List effects) + { + var application = FindLatestApplicationDirectory(); + if (application is null) return; + var root = Path.Combine(application, "Signal-x64", "Effects"); + if (!Directory.Exists(root)) return; + foreach (var file in Directory.EnumerateFiles(root, "*.html", SearchOption.AllDirectories)) + { + var relative = Path.GetRelativePath(root, file).Replace('\\', '/'); + effects.Add(new SignalRgbEffect( + BuiltInPrefix + Uri.EscapeDataString(relative), + ReadHtmlTitle(file) ?? Path.GetFileNameWithoutExtension(file), + true)); + } + } + + private void AddCachedEffects(List effects) + { + var cache = Path.Combine(_localApplicationData, "WhirlwindFX", "SignalRgb", "cache"); + var effectsRoot = Path.Combine(cache, "effects"); + if (!Directory.Exists(effectsRoot)) return; + var names = ReadCatalogNames(Path.Combine(cache, "catalog_en.json")); + foreach (var directory in Directory.EnumerateDirectories(effectsRoot)) + { + var id = Path.GetFileName(directory); + var effectFile = Path.Combine(directory, "effect.html"); + var name = names.GetValueOrDefault(id) + ?? (File.Exists(effectFile) ? ReadHtmlTitle(effectFile) : null) + ?? id; + effects.Add(new SignalRgbEffect( + CatalogPrefix + Uri.EscapeDataString(id), + name, + File.Exists(effectFile), + "The catalog item has not been downloaded.")); + } + } + + private string? FindLatestApplicationDirectory() + { + var root = Path.Combine(_localApplicationData, "VortxEngine"); + if (!Directory.Exists(root)) return null; + return Directory.EnumerateDirectories(root, "app-*", SearchOption.TopDirectoryOnly) + .Select(path => new { Path = path, Parsed = Version.TryParse(Path.GetFileName(path)[4..], out var version), Version = version }) + .Where(candidate => candidate.Parsed) + .OrderByDescending(candidate => candidate.Version) + .Select(candidate => candidate.Path) + .FirstOrDefault(); + } + + private static string? ReadHtmlTitle(string path) + { + try + { + var match = TitlePattern().Match(File.ReadAllText(path)); + return match.Success ? System.Net.WebUtility.HtmlDecode(match.Groups[1].Value.Trim()) : null; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return null; + } + } + + private static Dictionary ReadCatalogNames(string path) + { + if (!File.Exists(path)) return new Dictionary(StringComparer.Ordinal); + try + { + using var document = JsonDocument.Parse(File.ReadAllText(path)); + var names = new Dictionary(StringComparer.Ordinal); + CollectCatalogNames(document.RootElement, names); + return names; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException) + { + return new Dictionary(StringComparer.Ordinal); + } + } + + private static void CollectCatalogNames(JsonElement element, Dictionary names) + { + if (element.ValueKind == JsonValueKind.Object) + { + var id = ReadString(element, "_id") ?? ReadString(element, "id"); + var name = ReadString(element, "name") ?? ReadString(element, "title"); + if (!string.IsNullOrWhiteSpace(id) && !string.IsNullOrWhiteSpace(name)) names.TryAdd(id, name); + foreach (var property in element.EnumerateObject()) CollectCatalogNames(property.Value, names); + } + else if (element.ValueKind == JsonValueKind.Array) + { + foreach (var item in element.EnumerateArray()) CollectCatalogNames(item, names); + } + } + + private static string? ReadString(JsonElement element, string propertyName) => + element.TryGetProperty(propertyName, out var value) && value.ValueKind == JsonValueKind.String + ? value.GetString() + : null; + + [GeneratedRegex("]*>(.*?)", RegexOptions.IgnoreCase | RegexOptions.Singleline)] + private static partial Regex TitlePattern(); + } +} diff --git a/src/FocusRgb.Plugin.SignalRgb/focusrgb-plugin.json b/src/FocusRgb.Plugin.SignalRgb/focusrgb-plugin.json new file mode 100644 index 0000000..c1a9313 --- /dev/null +++ b/src/FocusRgb.Plugin.SignalRgb/focusrgb-plugin.json @@ -0,0 +1,13 @@ +{ + "schemaVersion": 1, + "id": "signalrgb", + "version": "0.2.0", + "contractVersion": "1.2", + "entryPoint": "FocusRgb.Plugin.SignalRgb.dll", + "operatingSystems": ["windows"], + "architectures": ["x64", "arm64"], + "roles": ["integration", "output", "effect"], + "resources": ["process.read", "filesystem.read", "process.start"], + "license": "MIT", + "source": "https://github.com/FocusRGB/FocusRGB-Plugin-SignalRGB" +} diff --git a/tests/FocusRgb.Plugin.SignalRgb.Tests/FocusRgb.Plugin.SignalRgb.Tests.csproj b/tests/FocusRgb.Plugin.SignalRgb.Tests/FocusRgb.Plugin.SignalRgb.Tests.csproj new file mode 100644 index 0000000..83bcc11 --- /dev/null +++ b/tests/FocusRgb.Plugin.SignalRgb.Tests/FocusRgb.Plugin.SignalRgb.Tests.csproj @@ -0,0 +1,18 @@ + + + Exe + false + true + + + + + + + + + + + diff --git a/tests/FocusRgb.Plugin.SignalRgb.Tests/GlobalUsings.cs b/tests/FocusRgb.Plugin.SignalRgb.Tests/GlobalUsings.cs new file mode 100644 index 0000000..c802f44 --- /dev/null +++ b/tests/FocusRgb.Plugin.SignalRgb.Tests/GlobalUsings.cs @@ -0,0 +1 @@ +global using Xunit; diff --git a/tests/FocusRgb.Plugin.SignalRgb.Tests/PluginManifestTests.cs b/tests/FocusRgb.Plugin.SignalRgb.Tests/PluginManifestTests.cs new file mode 100644 index 0000000..45995c6 --- /dev/null +++ b/tests/FocusRgb.Plugin.SignalRgb.Tests/PluginManifestTests.cs @@ -0,0 +1,30 @@ +using System.Text.Json; +using FocusRgb.Contracts; + +namespace FocusRgb.Plugin.SignalRgb.Tests +{ + public sealed class PluginManifestTests + { + [Fact] + public void ContractVersion_MatchesSdkCurrentVersion() + { + using JsonDocument manifest = JsonDocument.Parse( + File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "focusrgb-plugin.json"))); + + Assert.Equal( + ContractVersion.Current, + manifest.RootElement.GetProperty("contractVersion").GetString()); + } + + [Fact] + public void PluginVersion_MatchesAssemblyVersion() + { + using JsonDocument manifest = JsonDocument.Parse( + File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "focusrgb-plugin.json"))); + + Assert.Equal( + typeof(SignalRgbPlugin).Assembly.GetName().Version!.ToString(3), + manifest.RootElement.GetProperty("version").GetString()); + } + } +} diff --git a/tests/FocusRgb.Plugin.SignalRgb.Tests/SignalRgbPluginTests.cs b/tests/FocusRgb.Plugin.SignalRgb.Tests/SignalRgbPluginTests.cs new file mode 100644 index 0000000..f2445ac --- /dev/null +++ b/tests/FocusRgb.Plugin.SignalRgb.Tests/SignalRgbPluginTests.cs @@ -0,0 +1,186 @@ +using System.Text.Json; +using FocusRgb.Contracts; + +namespace FocusRgb.Plugin.SignalRgb.Tests +{ + public sealed class SignalRgbPluginTests + { + [Fact] + public async Task Initialize_ReportsManifestVersionAndVerifiedCapabilityLimits() + { + var result = await Plugin().InitializeAsync(Initialize(), TestContext.Current.CancellationToken); + using var manifest = JsonDocument.Parse( + File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "focusrgb-plugin.json"))); + + Assert.Equal("signalrgb", result.PluginId); + Assert.Equal(manifest.RootElement.GetProperty("version").GetString(), result.PluginVersion); + Assert.Equal(ContractVersion.Current, result.ContractVersion); + Assert.Equal("unverified", result.Capabilities.Single(item => item.Id == "provider.effect.select").Support); + Assert.Equal("unsupported", result.Capabilities.Single(item => item.Id == "provider.layout.select").Support); + } + + [Fact] + public async Task Status_ReturnsUnavailable_WithoutStartingProvider() + { + var platform = new FakePlatform { Running = false }; + + var result = await Plugin(platform).GetStatusAsync(TestContext.Current.CancellationToken); + + Assert.Equal("unavailable", result.Availability); + Assert.Equal("provider-not-running", result.Reason?.Code); + Assert.Empty(platform.Submissions); + } + + [Fact] + public async Task Apply_EncodesEffectName_AndReturnsUnverified() + { + var platform = new FakePlatform + { + Effects = [new SignalRgbEffect("catalog:one", "Aurora & Snow/Fire", true)] + }; + + var result = await Plugin(platform).ApplyBindingAsync( + Apply(new PluginResourceReference + { + ResourceId = "catalog:one", + DisplayName = "Aurora & Snow/Fire" + }), + TestContext.Current.CancellationToken); + + Assert.Equal("unverified", result.Outcome); + var submission = Assert.Single(platform.Submissions); + Assert.Equal("signalrgb://effect/apply/Aurora%20%26%20Snow%2FFire?-silentlaunch-", submission.Url); + } + + [Fact] + public async Task Apply_DoesNotSubmit_WhenProviderIsStopped() + { + var platform = new FakePlatform + { + Running = false, + Effects = [new SignalRgbEffect("catalog:one", "Aurora", true)] + }; + + var result = await Plugin(platform).ApplyBindingAsync( + Apply(new PluginResourceReference { ResourceId = "catalog:one", DisplayName = "Aurora" }), + TestContext.Current.CancellationToken); + + Assert.Equal("unavailable", result.Outcome); + Assert.Equal("provider-not-running", result.Reason?.Code); + Assert.Empty(platform.Submissions); + } + + [Fact] + public async Task Apply_RejectsMismatchedCatalogIdentity() + { + var platform = new FakePlatform + { + Effects = [new SignalRgbEffect("catalog:one", "Aurora", true)] + }; + + var result = await Plugin(platform).ApplyBindingAsync( + Apply(new PluginResourceReference { ResourceId = "catalog:one", DisplayName = "aurora" }), + TestContext.Current.CancellationToken); + + Assert.Equal("unavailable", result.Outcome); + Assert.Equal("resource-not-found", result.Reason?.Code); + Assert.Empty(platform.Submissions); + } + + [Fact] + public async Task Apply_ReturnsUnsupported_WhenLayoutIsRequested() + { + var parameters = Apply(new PluginResourceReference { ResourceId = "catalog:one", DisplayName = "Aurora" }); + parameters = new BindingApplyParameters + { + Profile = parameters.Profile, + BindingId = parameters.BindingId, + RenderingAuthority = parameters.RenderingAuthority, + DeviceScope = parameters.DeviceScope, + Effect = parameters.Effect, + Layout = new PluginResourceReference { ResourceId = "desk", DisplayName = "Desk" } + }; + + var result = await Plugin().ApplyBindingAsync(parameters, TestContext.Current.CancellationToken); + + Assert.Equal("unsupported", result.Outcome); + Assert.Equal("capability-unsupported", result.Reason?.Code); + } + + [Fact] + public async Task Apply_ReportsLauncherFailure() + { + var platform = new FakePlatform + { + Effects = [new SignalRgbEffect("catalog:one", "Aurora", true)], + ThrowOnSubmit = true + }; + + var result = await Plugin(platform).ApplyBindingAsync( + Apply(new PluginResourceReference { ResourceId = "catalog:one", DisplayName = "Aurora" }), + TestContext.Current.CancellationToken); + + Assert.Equal("unavailable", result.Outcome); + Assert.Equal("provider-not-running", result.Reason?.Code); + } + + [Fact] + public async Task Catalog_ReturnsEffects_AndRejectsLayouts() + { + var platform = new FakePlatform + { + Effects = + [ + new SignalRgbEffect("builtin:one", "One", true), + new SignalRgbEffect("catalog:two", "Two", false, "Not downloaded.") + ] + }; + var plugin = Plugin(platform); + + var effects = await plugin.ListCatalogAsync( + new CatalogListParameters { Kind = "effect" }, TestContext.Current.CancellationToken); + var layouts = await plugin.ListCatalogAsync( + new CatalogListParameters { Kind = "layout" }, TestContext.Current.CancellationToken); + + Assert.Equal("supported", effects.Support); + Assert.Equal(2, effects.Items.Count); + Assert.False(effects.Items.Single(item => item.ResourceId == "catalog:two").Available); + Assert.Equal("unsupported", layouts.Support); + } + + private static SignalRgbPlugin Plugin(FakePlatform? platform = null) => new(platform ?? new FakePlatform()); + + private static InitializeParameters Initialize() => new() + { + ContractVersion = ContractVersion.Current, + Host = new PluginHostInfo { Name = "tests", Version = "1.0.0" } + }; + + private static BindingApplyParameters Apply(PluginResourceReference effect) => new() + { + Profile = "default", + BindingId = "main", + RenderingAuthority = "provider", + DeviceScope = new PluginDeviceScope { Kind = "provider-managed" }, + Effect = effect + }; + + private sealed class FakePlatform : ISignalRgbPlatform + { + public bool Running { get; init; } = true; + public IReadOnlyList Effects { get; init; } = []; + public bool ThrowOnSubmit { get; init; } + public List<(string Launcher, string Url)> Submissions { get; } = []; + + public bool IsProviderRunning() => Running; + public string? FindLauncher() => "SignalRgbLauncher.exe"; + public IReadOnlyList ListEffects() => Effects; + + public void SubmitEffect(string launcherPath, string applicationUrl) + { + if (ThrowOnSubmit) throw new InvalidOperationException("Launcher failed."); + Submissions.Add((launcherPath, applicationUrl)); + } + } + } +} diff --git a/tests/FocusRgb.Plugin.SignalRgb.Tests/WindowsSignalRgbPlatformTests.cs b/tests/FocusRgb.Plugin.SignalRgb.Tests/WindowsSignalRgbPlatformTests.cs new file mode 100644 index 0000000..c5e55c5 --- /dev/null +++ b/tests/FocusRgb.Plugin.SignalRgb.Tests/WindowsSignalRgbPlatformTests.cs @@ -0,0 +1,56 @@ +using System.Text.Json; + +namespace FocusRgb.Plugin.SignalRgb.Tests +{ + public sealed class WindowsSignalRgbPlatformTests : IDisposable + { + private readonly string _root = Path.Combine(Path.GetTempPath(), $"focusrgb-signalrgb-{Guid.NewGuid():N}"); + + [Fact] + public void ListEffects_UsesLatestSemanticInstall_AndDownloadedCatalogNames() + { + WriteEffect("app-2.5.9", "Old.html", "Old"); + WriteEffect("app-2.5.80", "Dynamic/Screen Ambience.html", "Screen Ambience"); + var cache = Path.Combine(_root, "WhirlwindFX", "SignalRgb", "cache"); + Directory.CreateDirectory(Path.Combine(cache, "effects", "effect-id")); + File.WriteAllText(Path.Combine(cache, "effects", "effect-id", "effect.html"), "Wrong fallback"); + File.WriteAllText(Path.Combine(cache, "catalog_en.json"), JsonSerializer.Serialize(new + { + effects = new[] { new { _id = "effect-id", name = "Aurora" } } + })); + + var effects = new WindowsSignalRgbPlatform(_root).ListEffects(); + + Assert.DoesNotContain(effects, item => item.DisplayName == "Old"); + Assert.Contains(effects, item => item.DisplayName == "Screen Ambience" && item.ResourceId.StartsWith("builtin:", StringComparison.Ordinal)); + Assert.Contains(effects, item => item.DisplayName == "Aurora" && item.ResourceId == "catalog:effect-id" && item.Available); + } + + [Fact] + public void ListEffects_MarksUndownloadedCacheEntryUnavailable() + { + var cache = Path.Combine(_root, "WhirlwindFX", "SignalRgb", "cache"); + Directory.CreateDirectory(Path.Combine(cache, "effects", "not-downloaded")); + File.WriteAllText(Path.Combine(cache, "catalog_en.json"), + "{\"items\":[{\"id\":\"not-downloaded\",\"title\":\"Paid Effect\"}]}"); + + var effect = Assert.Single(new WindowsSignalRgbPlatform(_root).ListEffects()); + + Assert.Equal("Paid Effect", effect.DisplayName); + Assert.False(effect.Available); + } + + public void Dispose() + { + if (Directory.Exists(_root)) Directory.Delete(_root, recursive: true); + } + + private void WriteEffect(string version, string relativePath, string title) + { + var path = Path.Combine(_root, "VortxEngine", version, "Signal-x64", "Effects", + relativePath.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, $"{title}"); + } + } +}