diff --git a/README.en.md b/README.en.md index 63b3820..513fc89 100644 --- a/README.en.md +++ b/README.en.md @@ -78,7 +78,7 @@ The screen has the following tabs. Values change one step at a time with the lef | Long press | Whether a long press disconnects, the button for each hand, time to disconnect, time to the warning vibration, pause after a disconnect, which side to disconnect (the pressed side or both), input priority | | Vibration & power | Whether to vibrate before disconnecting and how strongly, power saving settings | | Update | Automatic updates and the check interval. The current version and the time of the last check are also shown | -| General | Display language. The default, "Auto", follows the Steam display language | +| General | Display language (the default, "Auto", follows the Steam display language), and whether to start automatically with Frame. You can also quit the tool here | A change of the long press button takes effect after you close the dashboard. If you assign a button to KxFrameControllerManager in the SteamVR controller binding screen, that binding takes precedence. @@ -107,6 +107,22 @@ You can also update from a terminal with the following command. Running the inst To stop automatic updates, turn off "Update automatically" in the "Update" tab. +## Quitting and autostart + +To stop the tool, press "Quit KxFCM" twice in the "General" tab of the settings screen. +The tab disappears when the tool quits. +The tool starts again the next time Frame starts. +To bring it back right away, run the following command in a terminal. + +```sh +~/.local/bin/kx-frame-controller-manager start +``` + +If you do not want the tool to start with Frame, turn off "Start automatically with Frame" in the same tab. +Turning it off does not stop the running tool. +From then on, the tool runs only when you run `start` above. +From a terminal, `autostart on` and `autostart off` switch it, and `autostart` alone shows the current state. + ## Uninstalling The following command stops the background service and automatic updates and removes their registration. @@ -139,7 +155,7 @@ Start by running `status` to see where things stop. - **`27062: not reachable`** (shown as "Disconnect: unavailable" on the settings screen): the mechanism inside SteamVR that disconnects controllers is not responding. Restart SteamVR and try again. A SteamVR update may also have broken it - **The serials do not match**: for safety, that hand is never disconnected by a long press. Reconnect the controller and run `status` again - **The long press does nothing only while in a game**: the game may be taking the input. Set "Input priority" to "Highest" in the "Long press" tab and enable "Experimental overlay input overrides" in SteamVR. The assigned button then no longer works inside the game -- **The "KxFCM" tab does not appear**: check that the tool is running with `systemctl --user status kx-frame-controller-manager`. If it is not, start it again with `systemctl --user restart kx-frame-controller-manager` +- **The "KxFCM" tab does not appear**: check that the tool is running with `systemctl --user status kx-frame-controller-manager`. If it is not, start it with `~/.local/bin/kx-frame-controller-manager start` Logs are available with `journalctl --user -u kx-frame-controller-manager`. They are also kept per day in `~/.local/state/KxFrameControllerManager/logs/`. diff --git a/README.md b/README.md index 81ad433..a6cf800 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ sudo は要らず、ホームの外には何も書かない。 | 長押し | 長押しで切るかどうか、左右それぞれに使うボタン、切断までの時間、予告の振動までの時間、切断の後に長押しを受け付けない時間、切る範囲(押した側か左右の両方か)、入力の優先度 | | 振動と省電力 | 予告と切断の前の振動の有無と強さ、省電力の設定 | | 更新 | 自動更新の有無と確認の間隔。今の版と最後に確認した時刻も見られる | -| 全般 | 表示言語。既定の「自動」は Steam の表示言語に従う | +| 全般 | 表示言語(既定の「自動」は Steam の表示言語に従う)、Frame の起動時に自動で起動するか。本ツールの終了もここから行う | 長押しに使うボタンを変えたときは、ダッシュボードを閉じた後で反映される。 SteamVR のコントローラーバインド画面で KxFrameControllerManager を選んでボタンを割り当てた場合は、そちらが優先される。 @@ -107,6 +107,22 @@ SteamVR のコントローラーバインド画面で KxFrameControllerManager 自動更新を止めるときは、「更新」のタブで「自動で更新する」を OFF にする。 +## 終了と自動起動 + +本ツールを止めるときは、設定画面の「全般」のタブで「KxFCM を終了」を 2 回押す。 +終了するとタブも消える。 +次に Frame を起動したときに、本ツールも起動し直す。 +すぐに戻すときは、端末から次のコマンドを実行する。 + +```sh +~/.local/bin/kx-frame-controller-manager start +``` + +Frame の起動時に本ツールを起動させたくないときは、同じタブで「Frame の起動時に自動で起動」を OFF にする。 +OFF にしても、動いている本ツールはそのまま動き続ける。 +以後は上の `start` を実行したときだけ動く。 +端末からは `autostart on` と `autostart off` で切り替えられ、`autostart` だけなら今の状態を表示する。 + ## アンインストール 次のコマンドで、常駐と自動更新を止めて登録を消す。 @@ -139,7 +155,7 @@ SteamVR を動かした状態で本ツールを一度起動すると戻る。 - **`27062: 届きません`(設定画面では「切断機能: 使えません」)と出る**:SteamVR の中のコントローラーを切る仕組みが応えていない。SteamVR を起動し直して、もう一度試す。SteamVR の更新で使えなくなった可能性もある - **シリアルが一致しない**:その手は安全のため長押ししても切らない。コントローラーをつなぎ直してから、もう一度 `status` を見る - **ゲーム中だけ長押しが効かない**:ゲームが入力を取っている可能性がある。「長押し」のタブで「入力の優先度」を「最優先」にし、SteamVR の「Experimental overlay input overrides」を有効にする。この場合、割り当てたボタンはゲームの中では効かなくなる -- **「KxFCM」のタブが出ない**:本ツールが動いているかを `systemctl --user status kx-frame-controller-manager` で確かめる。動いていなければ `systemctl --user restart kx-frame-controller-manager` で起動し直す +- **「KxFCM」のタブが出ない**:本ツールが動いているかを `systemctl --user status kx-frame-controller-manager` で確かめる。動いていなければ `~/.local/bin/kx-frame-controller-manager start` で起動する ログは `journalctl --user -u kx-frame-controller-manager` で見られる。 `~/.local/state/KxFrameControllerManager/logs/` にも日ごとに残る。 diff --git a/docs/architecture.md b/docs/architecture.md index 3d9caba..adbc4ab 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -41,7 +41,7 @@ src/ cairo.cr libcairo を dlopen して描く実装 models.cr 画面へ見せる状態、画面から変える項目と 1 段ぶんの変え方 view.cr 画面の組み立てと、押せる場所の一覧 - usecase.cr タブの作成と破棄、操作の受け取り、描き直し、手動の切断 + usecase.cr タブの作成と破棄、操作の受け取り、描き直し、手動の切断、終了と自動起動 config/ 設定 update/ 更新 models.cr 版、添付、リリース @@ -56,7 +56,7 @@ src/ i18n.cr 表示する文字列の辞書 scheduler.cr 主ループの 1 拍で何を呼ぶか cli.cr コマンドの解釈 - systemd.cr ユニットの書き出しと systemctl --user の呼び出し + systemd.cr ユニットの書き出し、systemctl --user の呼び出し、自動起動の状態の読み取り error/ usecase.cr 例外のログ記録 actions/ SteamVR Input のアクションマニフェストと frame_controller の既定バインド diff --git a/docs/setup.md b/docs/setup.md index 50ba562..ddcc585 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -111,6 +111,7 @@ SteamVR を動かし、左右のコントローラーをつないだ状態で `s - 長押しに使うボタン、時間、切る範囲、振動、省電力を、左右の矢印か − と + で 1 段ずつ変える - 「更新」のタブで、自動更新の有無と確認の間隔を変え、今の版、最後に確認した時刻、更新の進み具合と最後の結末(元の版へ戻したことを含む)を見る - 「更新を確認」で新しい版があるかだけを見る。「今すぐ更新」(2 回押し)で、間隔を待たずに更新する +- 「全般」のタブで、表示言語と自動起動を切り替え、「KxFCM を終了」(2 回押し)で常駐を終える 状態の「切断機能」は、ヘッドセット内の SteamVR ウェブサーバー(`127.0.0.1:27062`)へ届くかを表す。 本ツールはこのサーバーへ切断要求を送ってコントローラーを切るため、届かない間は長押しでも画面のボタンでも切断できない。 @@ -154,6 +155,31 @@ journalctl --user -u kx-frame-controller-manager # ログ ログは `~/.local/state/KxFrameControllerManager/logs/` にも日ごとに残る。 +### 終了と自動起動 + +設定画面の「KxFCM を終了」は、常駐を終了コード 0 で終える。 +ユニットは `Restart=on-failure` なので、systemd は起動し直さない。 +`systemctl --user stop` と同じく、ユニットは止まった状態になる。 +更新が走っている間はこのボタンを押せない。置き換えた版の起動を確かめている最中に止めると、起動しなかったものと取り違えて元の版へ戻すためである。 + +自動起動は、ユニットの `enable` と `disable` そのものである。設定ファイルには持たない。 +ユニットは `default.target` に掛けてあり、systemd のユーザーセッションが始まるとき(Frame の起動後にログインしたとき)に起動する。 +設定画面の切り替えと次のコマンドは、どれも今の常駐を起動も停止もしない。 + +```sh +~/.local/bin/kx-frame-controller-manager start # 常駐を起動する(systemctl --user start と同じ) +~/.local/bin/kx-frame-controller-manager stop # 常駐を止める(自動起動は変えない。走っている更新があれば終わるのを待つ) +~/.local/bin/kx-frame-controller-manager autostart # 自動起動の状態を表示する +~/.local/bin/kx-frame-controller-manager autostart off # 自動起動を無効にする(on で有効) +``` + +自動更新のタイマーは、自動起動を無効にしても止めない。 +タイマーから起きた更新は、常駐が止まっていれば実行ファイルを置き換えるだけで、常駐を起動しない。 +終了した常駐や、自動起動を無効にした常駐を、更新が勝手に起こすことはない。 + +`install` をやり直すと(導入の 1 行の再実行を含む)、自動起動は有効に戻る。 +`install` は導入の手順そのものであり、利用者が明示して実行するためである。 + ## 更新と削除 新しい版は、既定では 6 時間ごとに自動で確かめて置き換える。 diff --git a/docs/status.md b/docs/status.md index 5ac87ce..389894b 100644 --- a/docs/status.md +++ b/docs/status.md @@ -11,6 +11,7 @@ v1 として予定した機能はひととおり入っている。 - `status`、`list`、`disconnect` で疎通と照合を確かめ、長押しを経ずに切断できる - SteamVR のダッシュボードに設定画面のタブ「KxFCM」が出る。状態の確認、手動の切断、ボタンの割り当てと時間と省電力の設定、更新、表示言語の切り替えができる。状態の「切断機能」は、上の `127.0.0.1:27062` へ届くかを表す - systemd のユーザーユニットで常駐する。導入は `curl ... | bash` の 1 行で済む +- 設定画面か `start`、`stop`、`autostart` のコマンドで、常駐を終え、起動し、自動起動を切り替えられる - 自動更新のタイマーが新しい版を確かめて置き換え、起動しなければ元の版へ戻す - 両方が切れている間は明るさと画質を下げる省電力が使える。既定では省電力も明るさを下げる項目も無効なので、設定画面か設定ファイルで有効にする @@ -23,5 +24,6 @@ v1 として予定した機能はひととおり入っている。 - Background アプリから SteamVR Input が読めるか - 振動が出るか +- 設定画面からの終了と自動起動の切り替え(2026-11-10 追加) 実機でしか確かめられない項目の一覧は、[開発ガイド](development.md#実機でしか確かめられないこと)にある。 diff --git a/locales/de.json b/locales/de.json index 25373a5..8a4681c 100644 --- a/locales/de.json +++ b/locales/de.json @@ -5,7 +5,7 @@ "meta.steamvr_tag": "de_DE", "meta.steam_languages": "german", "meta.posix": "de", - "cli.usage": "Verwendung: kx-frame-controller-manager \n\nBefehle:\n run Als Hintergrundprozess ausführen (wird von der systemd-Unit gestartet)\n status Erreichbarkeit von SteamVR und 27062 sowie den Seriennummernabgleich je Hand anzeigen\n list Die von 27062 gemeldeten Controller auflisten\n disconnect Ohne langes Drücken trennen. Ziel ist left, right, both oder eine Seriennummer\n install systemd-Benutzer-Unit und Update-Timer schreiben und aktivieren\n uninstall systemd-Benutzer-Unit stoppen und entfernen\n update [--auto] Durch eine neuere Version ersetzen, die Unit neu starten und bei fehlgeschlagenem Start zurücksetzen. Der Update-Timer übergibt --auto\n channel [stable|test] Update-Kanal anzeigen. Mit stable oder test umschalten. test bezieht auch Vorabversionen und ist für Entwickler gedacht\n version Version anzeigen", + "cli.usage": "Verwendung: kx-frame-controller-manager \n\nBefehle:\n run Als Hintergrundprozess ausführen (wird von der systemd-Unit gestartet)\n status Erreichbarkeit von SteamVR und 27062 sowie den Seriennummernabgleich je Hand anzeigen\n list Die von 27062 gemeldeten Controller auflisten\n disconnect Ohne langes Drücken trennen. Ziel ist left, right, both oder eine Seriennummer\n install systemd-Benutzer-Unit und Update-Timer schreiben und aktivieren\n uninstall systemd-Benutzer-Unit stoppen und entfernen\n update [--auto] Durch eine neuere Version ersetzen, die Unit neu starten und bei fehlgeschlagenem Start zurücksetzen. Der Update-Timer übergibt --auto\n channel [stable|test] Update-Kanal anzeigen. Mit stable oder test umschalten. test bezieht auch Vorabversionen und ist für Entwickler gedacht\n start Hintergrundprozess starten. Damit holen Sie einen im Einstellungsbildschirm beendeten Prozess zurück\n stop Hintergrundprozess stoppen. Der Autostart bleibt unverändert\n autostart [on|off] Anzeigen, ob der Autostart aktiv ist. Mit on oder off umschalten\n version Version anzeigen", "cli.unknown_command": "Unbekannter Befehl: {command}", "cli.unexpected_argument": "Dieser Befehl nimmt keine Argumente: {argument}", "cli.disconnect_needs_target": "Geben Sie für disconnect genau ein Ziel an: left, right, both oder eine Seriennummer", @@ -54,6 +54,19 @@ "channel.changed.test": "Update-Kanal auf test umgestellt. Ab jetzt werden auch Vorabversionen bezogen. Bei aktivem Auto-Update installiert die nächste Prüfung (innerhalb von 30 Minuten) sie. Mit update sofort installieren", "channel.waits_for_stable": "Die laufende Version {version} ist eine Vorabversion. Sie wird nicht auf ein älteres offizielles Release zurückgestuft, sondern ersetzt, sobald ein neueres offizielles Release erscheint", "channel.config_unreadable": "Die Konfigurationsdatei kann nicht gelesen werden, daher wurde der Kanal nicht umgestellt. Konfiguration korrigieren und erneut versuchen", + "cli.autostart_invalid": "autostart erwartet genau on oder off", + "service.not_installed": "Die systemd-Unit ist nicht installiert. Führen Sie zuerst install aus", + "service.started": "Hintergrundprozess gestartet", + "service.start_failed": "Hintergrundprozess konnte nicht gestartet werden. Prüfen Sie die Ausgabe von systemctl oben", + "service.stopped": "Hintergrundprozess gestoppt. Mit start wieder starten", + "service.stop_failed": "Hintergrundprozess konnte nicht gestoppt werden. Prüfen Sie die Ausgabe von systemctl oben", + "autostart.current.on": "Autostart: aktiv (startet bei der Anmeldung)", + "autostart.current.off": "Autostart: inaktiv (läuft erst nach start)", + "autostart.unchanged.on": "Autostart ist bereits aktiv", + "autostart.unchanged.off": "Autostart ist bereits inaktiv", + "autostart.changed.on": "Autostart aktiviert. Startet ab der nächsten Anmeldung", + "autostart.changed.off": "Autostart deaktiviert. Der laufende Prozess läuft weiter. Künftig mit start starten", + "autostart.failed": "Autostart konnte nicht umgeschaltet werden. Prüfen Sie die Ausgabe von systemctl oben", "error.config_reload": "Neuladen der Konfiguration fehlgeschlagen", "error.steamvr_open": "Verbindung mit SteamVR fehlgeschlagen", "error.steamvr_poll": "Abfragen der SteamVR-Ereignisse fehlgeschlagen", @@ -178,6 +191,15 @@ "dashboard.language.auto": "Auto ({name})", "dashboard.language.note": "Auto folgt der Anzeigesprache von Steam, oder dem Systemgebietsschema, wenn diese nicht lesbar ist", "dashboard.language.machine_translated": "Diese Sprache wurde maschinell übersetzt. Fehler bitte in einem GitHub-Issue melden", + "dashboard.field.autostart": "Mit Frame automatisch starten", + "dashboard.autostart.unavailable": "N/V", + "dashboard.autostart.not_installed": "Der Dienst ist nicht als systemd-Unit installiert, daher kann der Autostart nicht umgeschaltet werden. Führen Sie install aus", + "dashboard.autostart.failed": "Autostart konnte nicht umgeschaltet werden", + "dashboard.quit": "KxFCM beenden", + "dashboard.quit.confirm": "Erneut drücken zum Beenden", + "dashboard.quit.quitting": "Wird beendet", + "dashboard.quit.busy": "Ein Update läuft, daher kann jetzt nicht beendet werden. Nach dem Update erneut versuchen", + "dashboard.quit.note": "Beim Beenden verschwindet auch dieser Tab. Er kommt beim nächsten Start von Frame (bei aktivem Autostart) oder mit dem Befehl start zurück", "steamvr.description": "Schaltet Steam-Frame-Controller durch langes Drücken aus.", "steamvr.action_set": "KxFrameControllerManager", "steamvr.action.power_off": "Diesen Controller ausschalten (halten)", diff --git a/locales/en.json b/locales/en.json index e5204a4..a1d4e2e 100644 --- a/locales/en.json +++ b/locales/en.json @@ -5,7 +5,7 @@ "meta.steamvr_tag": "en_US", "meta.steam_languages": "english", "meta.posix": "en", - "cli.usage": "Usage: kx-frame-controller-manager \n\nCommands:\n run Run as a resident process (started by the systemd unit)\n status Show SteamVR and 27062 reachability, and the serial match for each hand\n list List the controllers reported by 27062\n disconnect Disconnect without a long press. Target is left, right, both, or a serial\n install Write and enable the systemd user unit and the update timer\n uninstall Stop and remove the systemd user unit\n update [--auto] Replace the executable with a newer release, restart the unit, and roll back if it does not start. The update timer passes --auto\n channel [stable|test] Show the release channel used for updates. Pass stable or test to switch. test also takes prereleases and is meant for developers\n version Print the version", + "cli.usage": "Usage: kx-frame-controller-manager \n\nCommands:\n run Run as a resident process (started by the systemd unit)\n status Show SteamVR and 27062 reachability, and the serial match for each hand\n list List the controllers reported by 27062\n disconnect Disconnect without a long press. Target is left, right, both, or a serial\n install Write and enable the systemd user unit and the update timer\n uninstall Stop and remove the systemd user unit\n update [--auto] Replace the executable with a newer release, restart the unit, and roll back if it does not start. The update timer passes --auto\n channel [stable|test] Show the release channel used for updates. Pass stable or test to switch. test also takes prereleases and is meant for developers\n start Start the resident process. Use it to bring back a process quit from the settings screen\n stop Stop the resident process. Autostart is left as it is\n autostart [on|off] Show whether autostart is enabled. Pass on or off to switch\n version Print the version", "cli.unknown_command": "Unknown command: {command}", "cli.unexpected_argument": "This command takes no arguments: {argument}", "cli.disconnect_needs_target": "Give disconnect one target: left, right, both, or a serial", @@ -54,6 +54,19 @@ "channel.changed.test": "Switched the update channel to test. Prereleases will be taken from now on. With auto-update on, the next check (within 30 minutes) installs them. Run update to install now", "channel.waits_for_stable": "The running version {version} is a prerelease. It is not downgraded to an older official release; it is replaced when a newer official release comes out", "channel.config_unreadable": "The config file cannot be read, so the channel was not switched. Fix the config and try again", + "cli.autostart_invalid": "autostart takes one of on or off", + "service.not_installed": "The systemd unit is not installed. Run install first", + "service.started": "Started the resident process", + "service.start_failed": "Could not start the resident process. Check the systemctl output above", + "service.stopped": "Stopped the resident process. Run start to bring it back", + "service.stop_failed": "Could not stop the resident process. Check the systemctl output above", + "autostart.current.on": "Autostart: enabled (starts when you log in)", + "autostart.current.off": "Autostart: disabled (does not run until you run start)", + "autostart.unchanged.on": "Autostart is already enabled", + "autostart.unchanged.off": "Autostart is already disabled", + "autostart.changed.on": "Enabled autostart. It will start the next time you log in", + "autostart.changed.off": "Disabled autostart. The running process keeps running. From now on, use start to run it", + "autostart.failed": "Could not switch autostart. Check the systemctl output above", "error.config_reload": "Failed to reload the configuration", "error.steamvr_open": "Failed to connect to SteamVR", "error.steamvr_poll": "Failed to poll SteamVR events", @@ -178,6 +191,15 @@ "dashboard.language.auto": "Auto ({name})", "dashboard.language.note": "Auto follows the Steam display language, or the system locale if that cannot be read", "dashboard.language.machine_translated": "This language was machine-translated. Please report mistakes in a GitHub issue", + "dashboard.field.autostart": "Start automatically with Frame", + "dashboard.autostart.unavailable": "N/A", + "dashboard.autostart.not_installed": "The service is not installed as a systemd unit, so autostart cannot be switched. Run install", + "dashboard.autostart.failed": "Could not switch autostart", + "dashboard.quit": "Quit KxFCM", + "dashboard.quit.confirm": "Press again to quit", + "dashboard.quit.quitting": "Quitting", + "dashboard.quit.busy": "An update is running, so the tool cannot quit now. Try again after the update finishes", + "dashboard.quit.note": "Quitting also removes this tab. It comes back the next time Frame starts (if autostart is on) or when you run the start command", "steamvr.description": "Turns off Steam Frame controllers with a long press.", "steamvr.action_set": "KxFrameControllerManager", "steamvr.action.power_off": "Turn off this controller (hold)", diff --git a/locales/es.json b/locales/es.json index 89b9c46..935396d 100644 --- a/locales/es.json +++ b/locales/es.json @@ -5,7 +5,7 @@ "meta.steamvr_tag": "es_ES", "meta.steam_languages": "spanish,latam", "meta.posix": "es", - "cli.usage": "Uso: kx-frame-controller-manager \n\nComandos:\n run Ejecutar en segundo plano (lo inicia la unidad de systemd)\n status Mostrar el acceso a SteamVR y 27062, y la coincidencia de números de serie de cada mano\n list Listar los mandos que informa 27062\n disconnect Desconectar sin pulsación larga. El destino es left, right, both o un número de serie\n install Escribir y activar la unidad de usuario de systemd y el temporizador de actualización\n uninstall Detener y eliminar la unidad de usuario de systemd\n update [--auto] Sustituir por una versión más reciente, reiniciar la unidad y revertir si no arranca. El temporizador pasa --auto\n channel [stable|test] Mostrar el canal de actualizaciones. Indique stable o test para cambiarlo. test también obtiene versiones preliminares y es para desarrolladores\n version Mostrar la versión", + "cli.usage": "Uso: kx-frame-controller-manager \n\nComandos:\n run Ejecutar en segundo plano (lo inicia la unidad de systemd)\n status Mostrar el acceso a SteamVR y 27062, y la coincidencia de números de serie de cada mano\n list Listar los mandos que informa 27062\n disconnect Desconectar sin pulsación larga. El destino es left, right, both o un número de serie\n install Escribir y activar la unidad de usuario de systemd y el temporizador de actualización\n uninstall Detener y eliminar la unidad de usuario de systemd\n update [--auto] Sustituir por una versión más reciente, reiniciar la unidad y revertir si no arranca. El temporizador pasa --auto\n channel [stable|test] Mostrar el canal de actualizaciones. Indique stable o test para cambiarlo. test también obtiene versiones preliminares y es para desarrolladores\n start Iniciar el proceso residente. Sirve para recuperar un proceso cerrado desde la pantalla de ajustes\n stop Detener el proceso residente. El inicio automático no cambia\n autostart [on|off] Mostrar el estado del inicio automático. Añada on u off para cambiarlo\n version Mostrar la versión", "cli.unknown_command": "Comando desconocido: {command}", "cli.unexpected_argument": "Este comando no admite argumentos: {argument}", "cli.disconnect_needs_target": "Indica un único destino para disconnect: left, right, both o un número de serie", @@ -54,6 +54,19 @@ "channel.changed.test": "Canal de actualizaciones cambiado a test. A partir de ahora también se obtienen versiones preliminares. Con la actualización automática activada, la próxima comprobación (en 30 minutos como máximo) las instala. Ejecute update para instalarlas ya", "channel.waits_for_stable": "La versión en ejecución {version} es preliminar. No se baja a una versión oficial más antigua; se sustituye cuando salga una versión oficial más reciente", "channel.config_unreadable": "No se puede leer el archivo de configuración, así que no se cambió el canal. Corrija la configuración e inténtelo de nuevo", + "cli.autostart_invalid": "autostart requiere on u off", + "service.not_installed": "La unidad de systemd no está instalada. Ejecute install primero", + "service.started": "Proceso residente iniciado", + "service.start_failed": "No se pudo iniciar el proceso residente. Revise la salida de systemctl de arriba", + "service.stopped": "Proceso residente detenido. Use start para volver a iniciarlo", + "service.stop_failed": "No se pudo detener el proceso residente. Revise la salida de systemctl de arriba", + "autostart.current.on": "Inicio automático: activado (se inicia al iniciar sesión)", + "autostart.current.off": "Inicio automático: desactivado (no se ejecuta hasta usar start)", + "autostart.unchanged.on": "El inicio automático ya está activado", + "autostart.unchanged.off": "El inicio automático ya está desactivado", + "autostart.changed.on": "Inicio automático activado. Se iniciará en el próximo inicio de sesión", + "autostart.changed.off": "Inicio automático desactivado. El proceso actual sigue en marcha. A partir de ahora, inícielo con start", + "autostart.failed": "No se pudo cambiar el inicio automático. Revise la salida de systemctl de arriba", "error.config_reload": "Error al recargar la configuración", "error.steamvr_open": "Error al conectar con SteamVR", "error.steamvr_poll": "Error al leer los eventos de SteamVR", @@ -178,6 +191,15 @@ "dashboard.language.auto": "Auto ({name})", "dashboard.language.note": "Auto sigue el idioma de Steam, o la configuración regional del sistema si no se puede leer", "dashboard.language.machine_translated": "Este idioma se tradujo automáticamente. Informa de los errores en un issue de GitHub", + "dashboard.field.autostart": "Iniciar automáticamente con Frame", + "dashboard.autostart.unavailable": "N/D", + "dashboard.autostart.not_installed": "El servicio no está instalado como unidad de systemd, así que no se puede cambiar el inicio automático. Ejecute install", + "dashboard.autostart.failed": "No se pudo cambiar el inicio automático", + "dashboard.quit": "Salir de KxFCM", + "dashboard.quit.confirm": "Pulse de nuevo para salir", + "dashboard.quit.quitting": "Saliendo", + "dashboard.quit.busy": "Hay una actualización en curso, así que no se puede salir ahora. Inténtelo de nuevo cuando termine", + "dashboard.quit.note": "Al salir también desaparece esta pestaña. Vuelve la próxima vez que inicie Frame (si el inicio automático está activado) o con el comando start", "steamvr.description": "Apaga los mandos de Steam Frame con una pulsación larga.", "steamvr.action_set": "KxFrameControllerManager", "steamvr.action.power_off": "Apagar este mando (mantener)", diff --git a/locales/fr.json b/locales/fr.json index 14e2334..cd5931b 100644 --- a/locales/fr.json +++ b/locales/fr.json @@ -5,7 +5,7 @@ "meta.steamvr_tag": "fr_FR", "meta.steam_languages": "french", "meta.posix": "fr", - "cli.usage": "Utilisation : kx-frame-controller-manager \n\nCommandes :\n run S'exécuter en arrière-plan (lancé par l'unité systemd)\n status Afficher l'accès à SteamVR et 27062, et la correspondance des numéros de série par main\n list Lister les manettes signalées par 27062\n disconnect Déconnecter sans appui long. La cible est left, right, both ou un numéro de série\n install Écrire et activer l'unité utilisateur systemd et le minuteur de mise à jour\n uninstall Arrêter et supprimer l'unité utilisateur systemd\n update [--auto] Remplacer par une version plus récente, redémarrer l'unité et revenir en arrière si elle ne démarre pas. Le minuteur passe --auto\n channel [stable|test] Afficher le canal de mise à jour. Indiquer stable ou test pour en changer. test récupère aussi les préversions et est destiné aux développeurs\n version Afficher la version", + "cli.usage": "Utilisation : kx-frame-controller-manager \n\nCommandes :\n run S'exécuter en arrière-plan (lancé par l'unité systemd)\n status Afficher l'accès à SteamVR et 27062, et la correspondance des numéros de série par main\n list Lister les manettes signalées par 27062\n disconnect Déconnecter sans appui long. La cible est left, right, both ou un numéro de série\n install Écrire et activer l'unité utilisateur systemd et le minuteur de mise à jour\n uninstall Arrêter et supprimer l'unité utilisateur systemd\n update [--auto] Remplacer par une version plus récente, redémarrer l'unité et revenir en arrière si elle ne démarre pas. Le minuteur passe --auto\n channel [stable|test] Afficher le canal de mise à jour. Indiquer stable ou test pour en changer. test récupère aussi les préversions et est destiné aux développeurs\n start Démarrer le processus résident. Sert à relancer un processus quitté depuis l'écran des réglages\n stop Arrêter le processus résident. Le démarrage automatique n'est pas modifié\n autostart [on|off] Afficher l'état du démarrage automatique. Ajoutez on ou off pour basculer\n version Afficher la version", "cli.unknown_command": "Commande inconnue : {command}", "cli.unexpected_argument": "Cette commande ne prend pas d'argument : {argument}", "cli.disconnect_needs_target": "Indiquez une seule cible à disconnect : left, right, both ou un numéro de série", @@ -54,6 +54,19 @@ "channel.changed.test": "Canal de mise à jour passé à test. Les préversions seront aussi récupérées désormais. Avec la mise à jour automatique active, la prochaine vérification (sous 30 minutes) les installe. Lancer update pour installer tout de suite", "channel.waits_for_stable": "La version en cours {version} est une préversion. Elle n'est pas rétrogradée vers une version officielle plus ancienne ; elle sera remplacée à la sortie d'une version officielle plus récente", "channel.config_unreadable": "Le fichier de configuration est illisible, le canal n'a donc pas été changé. Corriger la configuration puis réessayer", + "cli.autostart_invalid": "autostart attend on ou off", + "service.not_installed": "L'unité systemd n'est pas installée. Exécutez d'abord install", + "service.started": "Processus résident démarré", + "service.start_failed": "Impossible de démarrer le processus résident. Vérifiez la sortie de systemctl ci-dessus", + "service.stopped": "Processus résident arrêté. Utilisez start pour le relancer", + "service.stop_failed": "Impossible d'arrêter le processus résident. Vérifiez la sortie de systemctl ci-dessus", + "autostart.current.on": "Démarrage automatique : activé (démarre à la connexion)", + "autostart.current.off": "Démarrage automatique : désactivé (ne tourne pas avant start)", + "autostart.unchanged.on": "Le démarrage automatique est déjà activé", + "autostart.unchanged.off": "Le démarrage automatique est déjà désactivé", + "autostart.changed.on": "Démarrage automatique activé. Il démarrera à la prochaine connexion", + "autostart.changed.off": "Démarrage automatique désactivé. Le processus en cours continue. Désormais, lancez-le avec start", + "autostart.failed": "Impossible de basculer le démarrage automatique. Vérifiez la sortie de systemctl ci-dessus", "error.config_reload": "Échec du rechargement de la configuration", "error.steamvr_open": "Échec de la connexion à SteamVR", "error.steamvr_poll": "Échec de la lecture des événements SteamVR", @@ -178,6 +191,15 @@ "dashboard.language.auto": "Auto ({name})", "dashboard.language.note": "Auto suit la langue d'affichage de Steam, ou la locale du système si elle est illisible", "dashboard.language.machine_translated": "Cette langue a été traduite automatiquement. Signalez les erreurs dans une issue GitHub", + "dashboard.field.autostart": "Démarrer automatiquement avec Frame", + "dashboard.autostart.unavailable": "N/D", + "dashboard.autostart.not_installed": "Le service n'est pas installé comme unité systemd, le démarrage automatique ne peut donc pas être basculé. Exécutez install", + "dashboard.autostart.failed": "Impossible de basculer le démarrage automatique", + "dashboard.quit": "Quitter KxFCM", + "dashboard.quit.confirm": "Appuyez à nouveau pour quitter", + "dashboard.quit.quitting": "Fermeture", + "dashboard.quit.busy": "Une mise à jour est en cours, impossible de quitter maintenant. Réessayez une fois la mise à jour terminée", + "dashboard.quit.note": "Quitter fait aussi disparaître cet onglet. Il revient au prochain démarrage de Frame (si le démarrage automatique est activé) ou avec la commande start", "steamvr.description": "Éteint les manettes Steam Frame par un appui long.", "steamvr.action_set": "KxFrameControllerManager", "steamvr.action.power_off": "Éteindre cette manette (appui long)", diff --git a/locales/ja.json b/locales/ja.json index 4d3967f..3210e30 100644 --- a/locales/ja.json +++ b/locales/ja.json @@ -5,7 +5,7 @@ "meta.steamvr_tag": "ja_JP", "meta.steam_languages": "japanese", "meta.posix": "ja", - "cli.usage": "使い方: kx-frame-controller-manager <コマンド>\n\nコマンド:\n run 常駐します。systemd のユニットから呼びます\n status SteamVR と 27062 の疎通、左右のシリアルと照合の結果を表示します\n list 27062 から取ったコントローラーの一覧を表示します\n disconnect <対象> 長押しを経ずに切断します。対象は left、right、both、またはシリアルです\n install systemd のユーザーユニットと自動更新のタイマーを書き出して有効にします\n uninstall systemd のユーザーユニットを止めて消します\n update [--auto] 新しい版があれば置き換え、ユニットを再起動して起動を確かめます。起動しなければ戻します。--auto は自動更新のタイマーが付けます\n channel [stable|test] 更新で追うチャンネルを表示します。stable か test を付けると切り替えます。test はプレリリースも取る開発者向けです\n version 版を表示します", + "cli.usage": "使い方: kx-frame-controller-manager <コマンド>\n\nコマンド:\n run 常駐します。systemd のユニットから呼びます\n status SteamVR と 27062 の疎通、左右のシリアルと照合の結果を表示します\n list 27062 から取ったコントローラーの一覧を表示します\n disconnect <対象> 長押しを経ずに切断します。対象は left、right、both、またはシリアルです\n install systemd のユーザーユニットと自動更新のタイマーを書き出して有効にします\n uninstall systemd のユーザーユニットを止めて消します\n update [--auto] 新しい版があれば置き換え、ユニットを再起動して起動を確かめます。起動しなければ戻します。--auto は自動更新のタイマーが付けます\n channel [stable|test] 更新で追うチャンネルを表示します。stable か test を付けると切り替えます。test はプレリリースも取る開発者向けです\n start 常駐を起動します。設定画面から終了した常駐を戻すときに使います\n stop 常駐を止めます。自動起動の設定は変えません\n autostart [on|off] 自動起動の状態を表示します。on か off を付けると切り替えます\n version 版を表示します", "cli.unknown_command": "不明なコマンドです: {command}", "cli.unexpected_argument": "このコマンドは引数を取りません: {argument}", "cli.disconnect_needs_target": "disconnect には対象(left、right、both、またはシリアル)を 1 つ指定してください", @@ -54,6 +54,19 @@ "channel.changed.test": "更新チャンネルを test に切り替えました。以降はプレリリースも取ります。自動更新が有効なら次の確認(30 分以内)で入ります。すぐ入れるには update を実行してください", "channel.waits_for_stable": "今の版 {version} はプレリリースです。古い正式リリースへは戻さず、これより新しい正式リリースが出たときに置き換えます", "channel.config_unreadable": "設定ファイルを読めないため、チャンネルを切り替えません。設定を直してからやり直してください", + "cli.autostart_invalid": "autostart には on か off を 1 つ指定してください", + "service.not_installed": "systemd のユニットが入っていません。先に install を実行してください", + "service.started": "常駐を起動しました", + "service.start_failed": "常駐を起動できませんでした。上の systemctl の出力を確かめてください", + "service.stopped": "常駐を止めました。start で起動し直せます", + "service.stop_failed": "常駐を止められませんでした。上の systemctl の出力を確かめてください", + "autostart.current.on": "自動起動: 有効(ログインしたときに常駐を始めます)", + "autostart.current.off": "自動起動: 無効(start を実行するまで常駐しません)", + "autostart.unchanged.on": "自動起動は既に有効です", + "autostart.unchanged.off": "自動起動は既に無効です", + "autostart.changed.on": "自動起動を有効にしました。次にログインしたときから常駐を始めます", + "autostart.changed.off": "自動起動を無効にしました。今の常駐は止めません。次からは start で起動してください", + "autostart.failed": "自動起動を切り替えられませんでした。上の systemctl の出力を確かめてください", "error.config_reload": "設定の再読み込みに失敗した", "error.steamvr_open": "SteamVR への接続に失敗した", "error.steamvr_poll": "SteamVR のイベントの確認に失敗した", @@ -178,6 +191,15 @@ "dashboard.language.auto": "自動({name})", "dashboard.language.note": "自動では Steam の表示言語に従います。読めなければシステムのロケールに従います", "dashboard.language.machine_translated": "この言語の文言は機械翻訳です。誤りは GitHub の issue でお知らせください", + "dashboard.field.autostart": "Frame の起動時に自動で起動", + "dashboard.autostart.unavailable": "使えません", + "dashboard.autostart.not_installed": "常駐が systemd のユニットとして入っていないため、自動起動は切り替えられません。install を実行してください", + "dashboard.autostart.failed": "自動起動を切り替えられませんでした", + "dashboard.quit": "KxFCM を終了", + "dashboard.quit.confirm": "もう一度押すと終了", + "dashboard.quit.quitting": "終了します", + "dashboard.quit.busy": "更新が走っているため終了できません。更新が終わってからもう一度押してください", + "dashboard.quit.note": "終了するとこのタブも消えます。次に Frame を起動したとき(自動起動が有効な場合)か、start コマンドで再開します", "steamvr.description": "長押しで Steam Frame のコントローラーを切断します。", "steamvr.action_set": "KxFrameControllerManager", "steamvr.action.power_off": "このコントローラーを切断(長押し)", diff --git a/locales/ko.json b/locales/ko.json index 60e3f04..faf7ceb 100644 --- a/locales/ko.json +++ b/locales/ko.json @@ -5,7 +5,7 @@ "meta.steamvr_tag": "ko_KR", "meta.steam_languages": "koreana", "meta.posix": "ko", - "cli.usage": "사용법: kx-frame-controller-manager <명령>\n\n명령:\n run 상주 실행합니다 (systemd 유닛이 시작함)\n status SteamVR과 27062의 연결 상태, 좌우 시리얼 대조 결과를 표시합니다\n list 27062가 보고한 컨트롤러 목록을 표시합니다\n disconnect <대상> 길게 누르지 않고 연결을 끊습니다. 대상은 left, right, both 또는 시리얼입니다\n install systemd 사용자 유닛과 자동 업데이트 타이머를 작성하고 활성화합니다\n uninstall systemd 사용자 유닛을 중지하고 삭제합니다\n update [--auto] 새 버전이 있으면 교체하고 유닛을 다시 시작해 실행을 확인합니다. 실행되지 않으면 되돌립니다. --auto는 자동 업데이트 타이머가 붙입니다\n channel [stable|test] 업데이트에 사용할 채널을 표시합니다. stable 또는 test를 붙이면 전환합니다. test는 프리릴리스도 받는 개발자용입니다\n version 버전을 표시합니다", + "cli.usage": "사용법: kx-frame-controller-manager <명령>\n\n명령:\n run 상주 실행합니다 (systemd 유닛이 시작함)\n status SteamVR과 27062의 연결 상태, 좌우 시리얼 대조 결과를 표시합니다\n list 27062가 보고한 컨트롤러 목록을 표시합니다\n disconnect <대상> 길게 누르지 않고 연결을 끊습니다. 대상은 left, right, both 또는 시리얼입니다\n install systemd 사용자 유닛과 자동 업데이트 타이머를 작성하고 활성화합니다\n uninstall systemd 사용자 유닛을 중지하고 삭제합니다\n update [--auto] 새 버전이 있으면 교체하고 유닛을 다시 시작해 실행을 확인합니다. 실행되지 않으면 되돌립니다. --auto는 자동 업데이트 타이머가 붙입니다\n channel [stable|test] 업데이트에 사용할 채널을 표시합니다. stable 또는 test를 붙이면 전환합니다. test는 프리릴리스도 받는 개발자용입니다\n start 상주 프로세스를 시작합니다. 설정 화면에서 종료한 상주 프로세스를 되돌릴 때 사용합니다\n stop 상주 프로세스를 중지합니다. 자동 시작 설정은 바꾸지 않습니다\n autostart [on|off] 자동 시작 상태를 표시합니다. on 또는 off를 붙이면 전환합니다\n version 버전을 표시합니다", "cli.unknown_command": "알 수 없는 명령입니다: {command}", "cli.unexpected_argument": "이 명령은 인수를 받지 않습니다: {argument}", "cli.disconnect_needs_target": "disconnect에 대상(left, right, both 또는 시리얼)을 하나 지정하세요", @@ -54,6 +54,19 @@ "channel.changed.test": "업데이트 채널을 test로 전환했습니다. 이후에는 프리릴리스도 받습니다. 자동 업데이트가 켜져 있으면 다음 확인(30분 이내)에서 설치됩니다. 바로 설치하려면 update를 실행하세요", "channel.waits_for_stable": "현재 버전 {version}은 프리릴리스입니다. 이전 정식 릴리스로 되돌리지 않고, 이보다 새로운 정식 릴리스가 나오면 교체합니다", "channel.config_unreadable": "설정 파일을 읽을 수 없어 채널을 전환하지 않았습니다. 설정을 고친 뒤 다시 시도하세요", + "cli.autostart_invalid": "autostart에는 on 또는 off 중 하나를 지정하세요", + "service.not_installed": "systemd 유닛이 설치되어 있지 않습니다. 먼저 install을 실행하세요", + "service.started": "상주 프로세스를 시작했습니다", + "service.start_failed": "상주 프로세스를 시작할 수 없습니다. 위의 systemctl 출력을 확인하세요", + "service.stopped": "상주 프로세스를 중지했습니다. start로 다시 시작할 수 있습니다", + "service.stop_failed": "상주 프로세스를 중지할 수 없습니다. 위의 systemctl 출력을 확인하세요", + "autostart.current.on": "자동 시작: 사용(로그인할 때 상주를 시작합니다)", + "autostart.current.off": "자동 시작: 사용 안 함(start를 실행할 때까지 상주하지 않습니다)", + "autostart.unchanged.on": "자동 시작이 이미 사용 중입니다", + "autostart.unchanged.off": "자동 시작이 이미 꺼져 있습니다", + "autostart.changed.on": "자동 시작을 켰습니다. 다음 로그인부터 상주를 시작합니다", + "autostart.changed.off": "자동 시작을 껐습니다. 지금의 상주 프로세스는 멈추지 않습니다. 앞으로는 start로 시작하세요", + "autostart.failed": "자동 시작을 전환할 수 없습니다. 위의 systemctl 출력을 확인하세요", "error.config_reload": "설정 다시 읽기에 실패함", "error.steamvr_open": "SteamVR 연결에 실패함", "error.steamvr_poll": "SteamVR 이벤트 확인에 실패함", @@ -178,6 +191,15 @@ "dashboard.language.auto": "자동 ({name})", "dashboard.language.note": "자동은 Steam 표시 언어를 따르며, 읽을 수 없으면 시스템 로캘을 따릅니다", "dashboard.language.machine_translated": "이 언어의 문구는 기계 번역입니다. 오류는 GitHub issue로 알려 주세요", + "dashboard.field.autostart": "Frame 시작 시 자동 실행", + "dashboard.autostart.unavailable": "사용 불가", + "dashboard.autostart.not_installed": "상주 프로세스가 systemd 유닛으로 설치되어 있지 않아 자동 시작을 전환할 수 없습니다. install을 실행하세요", + "dashboard.autostart.failed": "자동 시작을 전환할 수 없습니다", + "dashboard.quit": "KxFCM 종료", + "dashboard.quit.confirm": "한 번 더 누르면 종료", + "dashboard.quit.quitting": "종료합니다", + "dashboard.quit.busy": "업데이트 중이라 지금은 종료할 수 없습니다. 업데이트가 끝난 뒤 다시 눌러 주세요", + "dashboard.quit.note": "종료하면 이 탭도 사라집니다. 다음에 Frame을 시작할 때(자동 시작이 켜져 있으면) 또는 start 명령으로 다시 시작합니다", "steamvr.description": "길게 눌러 Steam Frame 컨트롤러의 전원을 끕니다.", "steamvr.action_set": "KxFrameControllerManager", "steamvr.action.power_off": "이 컨트롤러 연결 끊기 (길게 누르기)", diff --git a/locales/ru.json b/locales/ru.json index 5e8df9f..0bbeb2c 100644 --- a/locales/ru.json +++ b/locales/ru.json @@ -5,7 +5,7 @@ "meta.steamvr_tag": "ru_RU", "meta.steam_languages": "russian", "meta.posix": "ru", - "cli.usage": "Использование: kx-frame-controller-manager <команда>\n\nКоманды:\n run Работать в фоне (запускается юнитом systemd)\n status Показать доступность SteamVR и 27062 и сверку серийных номеров для каждой руки\n list Показать контроллеры, о которых сообщает 27062\n disconnect <цель> Отключить без долгого нажатия. Цель: left, right, both или серийный номер\n install Записать и включить пользовательский юнит systemd и таймер обновлений\n uninstall Остановить и удалить пользовательский юнит systemd\n update [--auto] Заменить на более новую версию, перезапустить юнит и откатиться, если он не запустится. Таймер передаёт --auto\n channel [stable|test] Показать канал обновлений. Укажите stable или test, чтобы переключить. test получает и предварительные версии и предназначен для разработчиков\n version Показать версию", + "cli.usage": "Использование: kx-frame-controller-manager <команда>\n\nКоманды:\n run Работать в фоне (запускается юнитом systemd)\n status Показать доступность SteamVR и 27062 и сверку серийных номеров для каждой руки\n list Показать контроллеры, о которых сообщает 27062\n disconnect <цель> Отключить без долгого нажатия. Цель: left, right, both или серийный номер\n install Записать и включить пользовательский юнит systemd и таймер обновлений\n uninstall Остановить и удалить пользовательский юнит systemd\n update [--auto] Заменить на более новую версию, перезапустить юнит и откатиться, если он не запустится. Таймер передаёт --auto\n channel [stable|test] Показать канал обновлений. Укажите stable или test, чтобы переключить. test получает и предварительные версии и предназначен для разработчиков\n start Запустить фоновый процесс. Нужно, чтобы вернуть процесс, завершённый из экрана настроек\n stop Остановить фоновый процесс. Автозапуск не меняется\n autostart [on|off] Показать состояние автозапуска. Укажите on или off, чтобы переключить\n version Показать версию", "cli.unknown_command": "Неизвестная команда: {command}", "cli.unexpected_argument": "Эта команда не принимает аргументов: {argument}", "cli.disconnect_needs_target": "Укажите для disconnect одну цель: left, right, both или серийный номер", @@ -54,6 +54,19 @@ "channel.changed.test": "Канал обновлений переключён на test. Теперь будут получаться и предварительные версии. При включённом автообновлении следующая проверка (в течение 30 минут) их установит. Чтобы установить сразу, выполните update", "channel.waits_for_stable": "Запущенная версия {version} предварительная. Она не откатывается на более старый официальный релиз, а будет заменена, когда выйдет более новый официальный релиз", "channel.config_unreadable": "Не удалось прочитать файл настроек, поэтому канал не переключён. Исправьте настройки и повторите", + "cli.autostart_invalid": "Для autostart укажите on или off", + "service.not_installed": "Юнит systemd не установлен. Сначала выполните install", + "service.started": "Фоновый процесс запущен", + "service.start_failed": "Не удалось запустить фоновый процесс. Проверьте вывод systemctl выше", + "service.stopped": "Фоновый процесс остановлен. Запустите снова командой start", + "service.stop_failed": "Не удалось остановить фоновый процесс. Проверьте вывод systemctl выше", + "autostart.current.on": "Автозапуск: включён (запускается при входе в систему)", + "autostart.current.off": "Автозапуск: выключен (не работает, пока не выполнить start)", + "autostart.unchanged.on": "Автозапуск уже включён", + "autostart.unchanged.off": "Автозапуск уже выключен", + "autostart.changed.on": "Автозапуск включён. Процесс запустится при следующем входе в систему", + "autostart.changed.off": "Автозапуск выключен. Текущий процесс продолжает работать. Дальше запускайте командой start", + "autostart.failed": "Не удалось переключить автозапуск. Проверьте вывод systemctl выше", "error.config_reload": "Не удалось перечитать конфигурацию", "error.steamvr_open": "Не удалось подключиться к SteamVR", "error.steamvr_poll": "Не удалось прочитать события SteamVR", @@ -178,6 +191,15 @@ "dashboard.language.auto": "Авто ({name})", "dashboard.language.note": "«Авто» следует языку интерфейса Steam, а если его не прочитать — языку системы", "dashboard.language.machine_translated": "Этот язык переведён машинным способом. Сообщайте об ошибках в issue на GitHub", + "dashboard.field.autostart": "Запускать вместе с Frame", + "dashboard.autostart.unavailable": "Н/Д", + "dashboard.autostart.not_installed": "Служба не установлена как юнит systemd, поэтому автозапуск переключить нельзя. Выполните install", + "dashboard.autostart.failed": "Не удалось переключить автозапуск", + "dashboard.quit": "Выйти из KxFCM", + "dashboard.quit.confirm": "Нажмите ещё раз для выхода", + "dashboard.quit.quitting": "Завершение", + "dashboard.quit.busy": "Идёт обновление, поэтому выйти сейчас нельзя. Повторите после завершения обновления", + "dashboard.quit.note": "При выходе эта вкладка тоже исчезнет. Она вернётся при следующем запуске Frame (если включён автозапуск) или по команде start", "steamvr.description": "Выключает контроллеры Steam Frame долгим нажатием.", "steamvr.action_set": "KxFrameControllerManager", "steamvr.action.power_off": "Выключить этот контроллер (удерживать)", diff --git a/locales/zh-Hans.json b/locales/zh-Hans.json index 5e328fe..8524037 100644 --- a/locales/zh-Hans.json +++ b/locales/zh-Hans.json @@ -5,7 +5,7 @@ "meta.steamvr_tag": "zh_CN", "meta.steam_languages": "schinese", "meta.posix": "zh_CN,zh_SG,zh", - "cli.usage": "用法: kx-frame-controller-manager <命令>\n\n命令:\n run 常驻运行(由 systemd 单元启动)\n status 显示 SteamVR 与 27062 的连通情况,以及左右手序列号的匹配结果\n list 列出 27062 报告的控制器\n disconnect <目标> 不经长按直接断开。目标为 left、right、both 或序列号\n install 写入并启用 systemd 用户单元和自动更新计时器\n uninstall 停止并删除 systemd 用户单元\n update [--auto] 若有新版本则替换可执行文件,重启单元并确认启动;未能启动则回滚。--auto 由自动更新计时器添加\n channel [stable|test] 显示更新所用的渠道。加上 stable 或 test 即可切换。test 也会获取预发布版本,供开发者使用\n version 显示版本", + "cli.usage": "用法: kx-frame-controller-manager <命令>\n\n命令:\n run 常驻运行(由 systemd 单元启动)\n status 显示 SteamVR 与 27062 的连通情况,以及左右手序列号的匹配结果\n list 列出 27062 报告的控制器\n disconnect <目标> 不经长按直接断开。目标为 left、right、both 或序列号\n install 写入并启用 systemd 用户单元和自动更新计时器\n uninstall 停止并删除 systemd 用户单元\n update [--auto] 若有新版本则替换可执行文件,重启单元并确认启动;未能启动则回滚。--auto 由自动更新计时器添加\n channel [stable|test] 显示更新所用的渠道。加上 stable 或 test 即可切换。test 也会获取预发布版本,供开发者使用\n start 启动常驻进程。用于恢复在设置界面中退出的常驻进程\n stop 停止常驻进程。不更改自动启动设置\n autostart [on|off] 显示自动启动状态。加上 on 或 off 可切换\n version 显示版本", "cli.unknown_command": "未知命令: {command}", "cli.unexpected_argument": "此命令不接受参数: {argument}", "cli.disconnect_needs_target": "请为 disconnect 指定一个目标:left、right、both 或序列号", @@ -54,6 +54,19 @@ "channel.changed.test": "已将更新渠道切换为 test。之后也会获取预发布版本。若已启用自动更新,下次检查(30 分钟内)时会安装。要立即安装请运行 update", "channel.waits_for_stable": "当前版本 {version} 为预发布版本。不会回退到较旧的正式版本,而是在发布更新的正式版本时替换", "channel.config_unreadable": "无法读取配置文件,因此未切换渠道。请修正配置后重试", + "cli.autostart_invalid": "autostart 需要指定 on 或 off 之一", + "service.not_installed": "未安装 systemd 单元。请先运行 install", + "service.started": "已启动常驻进程", + "service.start_failed": "无法启动常驻进程。请检查上方 systemctl 的输出", + "service.stopped": "已停止常驻进程。可用 start 重新启动", + "service.stop_failed": "无法停止常驻进程。请检查上方 systemctl 的输出", + "autostart.current.on": "自动启动:已启用(登录时开始常驻)", + "autostart.current.off": "自动启动:已禁用(运行 start 之前不会常驻)", + "autostart.unchanged.on": "自动启动已是启用状态", + "autostart.unchanged.off": "自动启动已是禁用状态", + "autostart.changed.on": "已启用自动启动。下次登录时开始常驻", + "autostart.changed.off": "已禁用自动启动。当前的常驻进程不会停止。今后请用 start 启动", + "autostart.failed": "无法切换自动启动。请检查上方 systemctl 的输出", "error.config_reload": "重新加载配置失败", "error.steamvr_open": "连接 SteamVR 失败", "error.steamvr_poll": "读取 SteamVR 事件失败", @@ -178,6 +191,15 @@ "dashboard.language.auto": "自动({name})", "dashboard.language.note": "自动时跟随 Steam 的显示语言;无法读取时跟随系统区域设置", "dashboard.language.machine_translated": "此语言的文字为机器翻译。如有错误,请在 GitHub issue 中告知", + "dashboard.field.autostart": "随 Frame 启动自动运行", + "dashboard.autostart.unavailable": "不可用", + "dashboard.autostart.not_installed": "常驻进程未作为 systemd 单元安装,无法切换自动启动。请运行 install", + "dashboard.autostart.failed": "无法切换自动启动", + "dashboard.quit": "退出 KxFCM", + "dashboard.quit.confirm": "再按一次退出", + "dashboard.quit.quitting": "正在退出", + "dashboard.quit.busy": "正在更新,暂时无法退出。请在更新完成后再试", + "dashboard.quit.note": "退出后此标签页也会消失。下次启动 Frame 时(若启用了自动启动)或运行 start 命令即可恢复", "steamvr.description": "长按即可关闭 Steam Frame 的控制器。", "steamvr.action_set": "KxFrameControllerManager", "steamvr.action.power_off": "断开此控制器(长按)", diff --git a/locales/zh-Hant.json b/locales/zh-Hant.json index fe0e58c..4f1b92b 100644 --- a/locales/zh-Hant.json +++ b/locales/zh-Hant.json @@ -5,7 +5,7 @@ "meta.steamvr_tag": "zh_TW", "meta.steam_languages": "tchinese", "meta.posix": "zh_TW,zh_HK,zh_MO", - "cli.usage": "用法: kx-frame-controller-manager <指令>\n\n指令:\n run 常駐執行(由 systemd 單元啟動)\n status 顯示 SteamVR 與 27062 的連線狀態,以及左右手序號的比對結果\n list 列出 27062 回報的控制器\n disconnect <目標> 不經長按直接中斷連線。目標為 left、right、both 或序號\n install 寫入並啟用 systemd 使用者單元與自動更新計時器\n uninstall 停止並移除 systemd 使用者單元\n update [--auto] 若有新版本則取代執行檔,重新啟動單元並確認啟動;無法啟動則還原。--auto 由自動更新計時器加上\n channel [stable|test] 顯示更新所用的頻道。加上 stable 或 test 即可切換。test 也會取得預發行版本,供開發者使用\n version 顯示版本", + "cli.usage": "用法: kx-frame-controller-manager <指令>\n\n指令:\n run 常駐執行(由 systemd 單元啟動)\n status 顯示 SteamVR 與 27062 的連線狀態,以及左右手序號的比對結果\n list 列出 27062 回報的控制器\n disconnect <目標> 不經長按直接中斷連線。目標為 left、right、both 或序號\n install 寫入並啟用 systemd 使用者單元與自動更新計時器\n uninstall 停止並移除 systemd 使用者單元\n update [--auto] 若有新版本則取代執行檔,重新啟動單元並確認啟動;無法啟動則還原。--auto 由自動更新計時器加上\n channel [stable|test] 顯示更新所用的頻道。加上 stable 或 test 即可切換。test 也會取得預發行版本,供開發者使用\n start 啟動常駐程序。用於恢復在設定畫面中結束的常駐程序\n stop 停止常駐程序。不變更自動啟動設定\n autostart [on|off] 顯示自動啟動狀態。加上 on 或 off 可切換\n version 顯示版本", "cli.unknown_command": "未知的指令: {command}", "cli.unexpected_argument": "此指令不接受引數: {argument}", "cli.disconnect_needs_target": "請為 disconnect 指定一個目標:left、right、both 或序號", @@ -54,6 +54,19 @@ "channel.changed.test": "已將更新頻道切換為 test。之後也會取得預發行版本。若已啟用自動更新,下次檢查(30 分鐘內)時會安裝。要立即安裝請執行 update", "channel.waits_for_stable": "目前版本 {version} 為預發行版本。不會退回較舊的正式版本,而是在發布更新的正式版本時取代", "channel.config_unreadable": "無法讀取設定檔,因此未切換頻道。請修正設定後再試一次", + "cli.autostart_invalid": "autostart 需要指定 on 或 off 其中之一", + "service.not_installed": "尚未安裝 systemd 單元。請先執行 install", + "service.started": "已啟動常駐程序", + "service.start_failed": "無法啟動常駐程序。請檢查上方 systemctl 的輸出", + "service.stopped": "已停止常駐程序。可用 start 重新啟動", + "service.stop_failed": "無法停止常駐程序。請檢查上方 systemctl 的輸出", + "autostart.current.on": "自動啟動:已啟用(登入時開始常駐)", + "autostart.current.off": "自動啟動:已停用(執行 start 之前不會常駐)", + "autostart.unchanged.on": "自動啟動已是啟用狀態", + "autostart.unchanged.off": "自動啟動已是停用狀態", + "autostart.changed.on": "已啟用自動啟動。下次登入時開始常駐", + "autostart.changed.off": "已停用自動啟動。目前的常駐程序不會停止。之後請用 start 啟動", + "autostart.failed": "無法切換自動啟動。請檢查上方 systemctl 的輸出", "error.config_reload": "重新載入設定失敗", "error.steamvr_open": "連線到 SteamVR 失敗", "error.steamvr_poll": "讀取 SteamVR 事件失敗", @@ -178,6 +191,15 @@ "dashboard.language.auto": "自動({name})", "dashboard.language.note": "自動時依照 Steam 的顯示語言;無法讀取時依照系統地區設定", "dashboard.language.machine_translated": "此語言的文字為機器翻譯。如有錯誤,請在 GitHub issue 中告知", + "dashboard.field.autostart": "隨 Frame 啟動自動執行", + "dashboard.autostart.unavailable": "無法使用", + "dashboard.autostart.not_installed": "常駐程序未以 systemd 單元安裝,無法切換自動啟動。請執行 install", + "dashboard.autostart.failed": "無法切換自動啟動", + "dashboard.quit": "結束 KxFCM", + "dashboard.quit.confirm": "再按一次結束", + "dashboard.quit.quitting": "正在結束", + "dashboard.quit.busy": "正在更新,暫時無法結束。請在更新完成後再試", + "dashboard.quit.note": "結束後此分頁也會消失。下次啟動 Frame 時(若已啟用自動啟動)或執行 start 指令即可恢復", "steamvr.description": "長按即可關閉 Steam Frame 的控制器。", "steamvr.action_set": "KxFrameControllerManager", "steamvr.action.power_off": "中斷此控制器(長按)", diff --git a/scripts/preview_dashboard.cr b/scripts/preview_dashboard.cr index c674700..ecebc35 100644 --- a/scripts/preview_dashboard.cr +++ b/scripts/preview_dashboard.cr @@ -37,6 +37,7 @@ snapshot = Dashboard::Snapshot.new( gain_range: {0.5, 1.6}, config_errors: [] of String, update: update, + autostart: true, ) translate = ->(key : String, vars : Hash(String, String)) { Runtime::I18n.t(key, vars) } diff --git a/spec/dashboard/usecase_spec.cr b/spec/dashboard/usecase_spec.cr index 495352a..91b79e0 100644 --- a/spec/dashboard/usecase_spec.cr +++ b/spec/dashboard/usecase_spec.cr @@ -13,7 +13,7 @@ private def update_status(phase : String? = nil, installed : Bool = true, outcom ) end -private def snapshot(errors = [] of String, update = update_status) : Dashboard::Snapshot +private def snapshot(errors = [] of String, update = update_status, autostart : Bool? = true) : Dashboard::Snapshot Dashboard::Snapshot.new( steamvr_connected: true, left: Dashboard::HandStatus.new(true, "cv.aaaaaaaaaaaa", "view"), @@ -24,6 +24,7 @@ private def snapshot(errors = [] of String, update = update_status) : Dashboard: gain_range: {0.5, 1.6}, config_errors: errors, update: update, + autostart: autostart, ) end @@ -236,6 +237,86 @@ describe Dashboard::Usecase do usecase.state.update_message.should eq "dashboard.update.check.unreachable" end + it "終了は 2 回目で求める" do + usecase, _, _, _ = build + quits = 0 + usecase.quit = -> { quits += 1; true } + usecase.state.snapshot = snapshot + now = Time.instant + usecase.act("quit", now) + quits.should eq 0 + usecase.state.armed.should eq "quit" + usecase.act("quit", now) + quits.should eq 1 + usecase.state.general_message.should eq "dashboard.quit.quitting" + end + + it "更新の排他を取れず終えられなければ知らせる" do + usecase, _, _, _ = build + usecase.quit = -> { false } + usecase.state.snapshot = snapshot + usecase.act("quit") + usecase.act("quit") + usecase.state.general_message.should eq "dashboard.quit.busy" + usecase.state.general_tone.should eq Dashboard::Tone::Warn + end + + it "終了の確かめ待ちは時間が経つと解ける" do + usecase, _, _, _ = build + quits = 0 + usecase.quit = -> { quits += 1; true } + usecase.state.snapshot = snapshot + now = Time.instant + usecase.act("quit", now) + usecase.act("quit", now + Dashboard::Usecase::ARM_TIMEOUT) + quits.should eq 0 + usecase.state.armed.should eq "quit" + end + + it "更新が走っている間は終了を受け付けない" do + usecase, _, _, _ = build + quits = 0 + usecase.quit = -> { quits += 1; true } + usecase.state.snapshot = snapshot(update: update_status(phase: "restarting")) + usecase.act("quit") + usecase.act("quit") + quits.should eq 0 + usecase.state.armed.should be_nil + end + + it "自動起動は今の状態の逆へ切り替え、別のファイバで待つ" do + usecase, _, _, _ = build + requested = [] of Bool + usecase.set_autostart = ->(enabled : Bool) { requested << enabled; true } + usecase.state.snapshot = snapshot(autostart: true) + usecase.act("autostart") + usecase.state.autostart_changing?.should be_true + sleep 10.milliseconds + requested.should eq [false] + usecase.state.autostart_changing?.should be_false + usecase.state.general_message.should be_nil + end + + it "自動起動を切り替えられなければ知らせる" do + usecase, _, _, _ = build + usecase.set_autostart = ->(_enabled : Bool) { false } + usecase.state.snapshot = snapshot(autostart: false) + usecase.act("autostart") + sleep 10.milliseconds + usecase.state.general_message.should eq "dashboard.autostart.failed" + usecase.state.general_tone.should eq Dashboard::Tone::Error + end + + it "ユニットが入っていなければ自動起動は切り替えない" do + usecase, _, _, _ = build + requested = [] of Bool + usecase.set_autostart = ->(enabled : Bool) { requested << enabled; true } + usecase.state.snapshot = snapshot(autostart: nil) + usecase.act("autostart") + sleep 10.milliseconds + requested.should be_empty + end + it "close でタブを消し、次の tick で作り直す" do usecase, repository, _, _ = build usecase.tick @@ -378,6 +459,39 @@ describe Dashboard::View do canvas.texts.should contain "dashboard.update.not_installed" end + it "全般のタブには、自動起動の切り替えと終了のボタンがある" do + translate = ->(key : String, _vars : Hash(String, String)) { key } + state = Dashboard::ViewState.new + state.tab = Dashboard::Tab::General + state.snapshot = snapshot + canvas = Fakes::Canvas.new + actions = Dashboard::View.new(translate, "").render(canvas, state, Config::Root.default).map(&.action) + actions.should contain "autostart" + actions.should contain "quit" + canvas.texts.should contain "dashboard.quit.note" + end + + it "ユニットが入っていなければ自動起動は押せず、そう知らせる" do + translate = ->(key : String, _vars : Hash(String, String)) { key } + state = Dashboard::ViewState.new + state.tab = Dashboard::Tab::General + state.snapshot = snapshot(autostart: nil) + canvas = Fakes::Canvas.new + actions = Dashboard::View.new(translate, "").render(canvas, state, Config::Root.default).map(&.action) + actions.should_not contain "autostart" + actions.should contain "quit" + canvas.texts.should contain "dashboard.autostart.not_installed" + end + + it "更新が走っている間は終了のボタンを押せない" do + translate = ->(key : String, _vars : Hash(String, String)) { key } + state = Dashboard::ViewState.new + state.tab = Dashboard::Tab::General + state.snapshot = snapshot(update: update_status(phase: "downloading")) + actions = Dashboard::View.new(translate, "").render(Fakes::Canvas.new, state, Config::Root.default).map(&.action) + actions.should_not contain "quit" + end + it "切断の処理中は切断のボタンを押せない" do translate = ->(key : String, _vars : Hash(String, String)) { key } state = Dashboard::ViewState.new diff --git a/spec/runtime/cli_spec.cr b/spec/runtime/cli_spec.cr index e66b3f8..c65f8b3 100644 --- a/spec/runtime/cli_spec.cr +++ b/spec/runtime/cli_spec.cr @@ -44,6 +44,24 @@ describe Runtime::CLI do Runtime::CLI.parse(["channel", "test", "stable"]).error.should eq "cli.channel_invalid" end + it "start と stop は引数を取らず、autostart は on か off で切り替える" do + Runtime::CLI.parse(["start"]).command.should eq Runtime::CLI::Command::Start + Runtime::CLI.parse(["stop"]).command.should eq Runtime::CLI::Command::Stop + Runtime::CLI.parse(["start", "x"]).error.should eq "cli.unexpected_argument" + + show = Runtime::CLI.parse(["autostart"]) + show.command.should eq Runtime::CLI::Command::Autostart + show.argument.should be_nil + show.error.should be_nil + %w[on off].each do |name| + parsed = Runtime::CLI.parse(["autostart", name]) + parsed.argument.should eq name + parsed.error.should be_nil + end + Runtime::CLI.parse(["autostart", "yes"]).error.should eq "cli.autostart_invalid" + Runtime::CLI.parse(["autostart", "on", "off"]).error.should eq "cli.autostart_invalid" + end + it "channel が受け付ける綴りは、設定 update.channel の値と同じ" do Runtime::CLI::CHANNELS.should eq Update::CHANNELS Runtime::CLI::CHANNELS.should eq Config::Usecase::UPDATE_CHANNELS diff --git a/spec/runtime/systemd_spec.cr b/spec/runtime/systemd_spec.cr index 4bc7c4d..79f617d 100644 --- a/spec/runtime/systemd_spec.cr +++ b/spec/runtime/systemd_spec.cr @@ -88,4 +88,41 @@ describe Runtime::Systemd do FileUtils.rm_rf(directory) end end + + it "自動起動の状態は、enable が default.target.wants に置くリンクで見る" do + directory = File.tempname("kxfcm-systemd") + begin + Dir.mkdir_p(File.join(directory, "default.target.wants")) + path = File.join(directory, Runtime::Systemd::UNIT_NAME) + File.write(path, "x") + Runtime::Systemd.installed?(path).should be_true + Runtime::Systemd.autostart_enabled?(path).should be_false + File.symlink(path, File.join(directory, "default.target.wants", Runtime::Systemd::UNIT_NAME)) + Runtime::Systemd.autostart_enabled?(path).should be_true + Runtime::Systemd.installed?(File.join(directory, "missing.service")).should be_false + ensure + FileUtils.rm_rf(directory) + end + end + + it "自動起動の切り替えは enable と disable だけを呼び、常駐の起動と停止はしない" do + systemctl = FakeSystemctl.new + Runtime::Systemd.set_autostart(false, systemctl).should be_true + Runtime::Systemd.set_autostart(true, systemctl).should be_true + systemctl.calls.should eq [ + ["disable", "--quiet", Runtime::Systemd::UNIT_NAME], + ["enable", "--quiet", Runtime::Systemd::UNIT_NAME], + ] + end + + it "start は起動の回数の制限を解いてから起動し、stop は止めるだけにする" do + systemctl = FakeSystemctl.new + Runtime::Systemd.start(systemctl).should be_true + Runtime::Systemd.stop(systemctl).should be_true + systemctl.calls.should eq [ + ["reset-failed", Runtime::Systemd::UNIT_NAME], + ["start", Runtime::Systemd::UNIT_NAME], + ["stop", Runtime::Systemd::UNIT_NAME], + ] + end end diff --git a/src/dashboard/models.cr b/src/dashboard/models.cr index 6c552b1..151553a 100644 --- a/src/dashboard/models.cr +++ b/src/dashboard/models.cr @@ -38,7 +38,9 @@ module Dashboard gain_range : {Float64, Float64}?, # 最後に読んだ設定ファイルの誤り。表示する言語の文にしてある。 config_errors : Array(String), - update : UpdateStatus do + update : UpdateStatus, + # 自動起動(systemd のユニットの enable)が有効か。ユニットが入っていなければ nil で、画面から切り替えられない。 + autostart : Bool? = nil do def hand(hand : PowerOff::Hand) : HandStatus hand.left? ? left : right end diff --git a/src/dashboard/usecase.cr b/src/dashboard/usecase.cr index ce0c267..3867562 100644 --- a/src/dashboard/usecase.cr +++ b/src/dashboard/usecase.cr @@ -38,6 +38,11 @@ module Dashboard property check_update : Proc({String, String?}) = -> { {"unknown", nil.as(String?)} } # 今すぐの更新を、常駐とは別のユニットで始める。始められたら真を返す。 property start_update : Proc(Bool) = -> { false } + # 自動起動を切り替える。切り替えられたら真を返す。 + property set_autostart : Proc(Bool, Bool) = ->(_enabled : Bool) { false } + # 常駐を終える。主ループに終わりを伝えるだけで、すぐには戻らない。 + # 更新が走っていて終えられなければ偽を返す。 + property quit : Proc(Bool) = -> { false } # 描画先を作る。libcairo が無ければ nil を返す。 property canvas_factory : Proc(Int32, Int32, Canvas?) = ->(_w : Int32, _h : Int32) { nil.as(Canvas?) } @@ -111,10 +116,15 @@ module Dashboard @state.tab = Tab.parse(rest) @state.message = nil @state.update_message = nil + @state.general_message = nil when "disconnect" press_disconnect(rest, now) when "update" rest == "run" ? press_update(now) : check_for_update + when "autostart" + toggle_autostart + when "quit" + press_quit(now) when "set" key, _, direction = rest.rpartition(':') change(key, direction.to_i) @@ -268,6 +278,60 @@ module Dashboard @last_status = nil end + # 自動起動の切り替えは systemctl を待つ。主ループを止めないよう別のファイバで行う。 + # 画面の値は、次に状態を読み直したときに実際のユニットの状態から出す。設定ファイルには持たない。 + # 持つと、手で打った systemctl や install のやり直しと食い違うためである。 + private def toggle_autostart : Nil + return if @state.autostart_changing? + current = @state.snapshot.try(&.autostart) + return if current.nil? + @state.autostart_changing = true + @state.general_message = nil + spawn(name: "dashboard_autostart") do + begin + unless @set_autostart.call(!current) + @state.general_message = @view.t("dashboard.autostart.failed") + @state.general_tone = Tone::Error + end + rescue exception + Log.error(exception: exception) { "設定画面から自動起動を切り替えられなかった" } + @state.general_message = @view.t("dashboard.autostart.failed") + @state.general_tone = Tone::Error + ensure + @state.autostart_changing = false + @last_status = nil + @dirty = true + end + end + end + + # 終了も 2 回押しで動かす。終えるとこのタブも消え、VR の中からは起動し直せないためである。 + # + # 更新が走っている間は受け付けない。置き換えた版の起動を確かめている最中に止めると、 + # 自動更新は起動しなかったものと取り違えて元の版へ戻す。 + private def press_quit(now : Time::Instant) : Nil + return if @state.snapshot.try(&.update.phase) + expire_arm(now) + unless @state.armed == "quit" + @state.armed = "quit" + @armed_at = now + @state.general_message = nil + return + end + + @state.armed = nil + @armed_at = nil + unless @quit.call + # 画面の状態は 1 秒ごとの写しなので、1 回目の後に更新が始まっていることがある。 + @state.general_message = @view.t("dashboard.quit.busy") + @state.general_tone = Tone::Warn + return + end + Log.info { "設定画面から終了を求められた" } + @state.general_message = @view.t("dashboard.quit.quitting") + @state.general_tone = Tone::Info + end + # GitHub への問い合わせは数秒かかりうる。主ループを止めないよう別のファイバで行う。 private def check_for_update : Nil return if @state.checking? diff --git a/src/dashboard/view.cr b/src/dashboard/view.cr index 926390c..ecec258 100644 --- a/src/dashboard/view.cr +++ b/src/dashboard/view.cr @@ -30,6 +30,7 @@ module Dashboard # - "tab:hold" / "tab:power" / "tab:update" / "tab:general" # - "disconnect:left" / "disconnect:right" / "disconnect:both" # - "update:check"(新しい版があるかだけを見る) / "update:run"(今すぐ更新する) + # - "autostart"(自動起動を切り替える) / "quit"(常駐を終える) # - "set:<セクション.キー>:<+1 か -1>"(Toggle は +1 だけ) record Hit, x : Float64, y : Float64, w : Float64, h : Float64, action : String do def contains?(px : Float64, py : Float64) : Bool @@ -41,7 +42,7 @@ module Dashboard class ViewState property tab : Tab = Tab::Hold property snapshot : Snapshot? = nil - # 1 回目を押して確かめ待ちの対象(left / right / both、または今すぐの更新の update)。 + # 1 回目を押して確かめ待ちの対象(left / right / both、今すぐの更新の update、終了の quit)。 property armed : String? = nil # 切断を処理しているか。 property? running : Bool = false @@ -60,6 +61,11 @@ module Dashboard # 画面で確かめたせいで、見つけた版の自動での置き換えが間隔ぶん遅れないようにするためである。 # 表示ではどちらか新しいほうを「最後の確認」に出す。 property checked_at : Time? = nil + # 自動起動を切り替えている途中か。 + property? autostart_changing : Bool = false + # 全般のタブに出す知らせ。 + property general_message : String? = nil + property general_tone : Tone = Tone::Info end # 画面を描き、押せる場所の一覧を返す。 @@ -139,6 +145,7 @@ module Dashboard row(canvas, root, state.snapshot, key, FIELDS_TOP + index * ROW_H, hits) end update_panel(canvas, state, root, hits) if state.tab.update? + general_panel(canvas, state, hits) if state.tab.general? footer(canvas, state) hits end @@ -242,8 +249,7 @@ module Dashboard in .toggle? on = value_of(root, key) == "true" x = right - TOGGLE_W - canvas.fill_rect(x, control_top, TOGGLE_W, CONTROL_H, on ? OK : BUTTON, CONTROL_H / 2) - fit_text(canvas, x + TOGGLE_W / 2, center, t(on ? "dashboard.on" : "dashboard.off"), BODY_SIZE, on ? BACKGROUND : MUTED, TOGGLE_W - 12, bold: true, align: Align::Center) + toggle(canvas, x, control_top, on, t(on ? "dashboard.on" : "dashboard.off")) hits << Hit.new(x, control_top, TOGGLE_W, CONTROL_H, "set:#{key}:+1") in .choice?, .stepper? plus_x = right - ARROW_W @@ -258,6 +264,11 @@ module Dashboard end end + private def toggle(canvas : Canvas, x : Float64, y : Float64, on : Bool, label : String) : Nil + canvas.fill_rect(x, y, TOGGLE_W, CONTROL_H, on ? OK : BUTTON, CONTROL_H / 2) + fit_text(canvas, x + TOGGLE_W / 2, y + CONTROL_H / 2, label, BODY_SIZE, on ? BACKGROUND : MUTED, TOGGLE_W - 12, bold: true, align: Align::Center) + end + private def arrow(canvas : Canvas, x : Float64, y : Float64, label : String) : Nil canvas.fill_rect(x, y, ARROW_W, CONTROL_H, BUTTON, 10.0) canvas.text(x + ARROW_W / 2, y + CONTROL_H / 2, label, BODY_SIZE, ACCENT, bold: true, align: Align::Center) @@ -430,6 +441,56 @@ module Dashboard end end + # 全般のタブの下半分の枠。上には表示言語の説明が最長で 6 行入り、下には設定の誤りの 2 行が入る。 + GENERAL_PANEL_TOP = 392.0 + GENERAL_PANEL_H = 196.0 + + # 全般のタブの下半分。自動起動の切り替えと、常駐の終了を並べる。 + # + # 自動起動は設定ファイルの項目ではなく systemd のユニットの状態なので、Editor::FIELDS には載せず、ここで描く。 + private def general_panel(canvas : Canvas, state : ViewState, hits : Array(Hit)) : Nil + top = GENERAL_PANEL_TOP + canvas.fill_rect(RIGHT_X, top, RIGHT_W, GENERAL_PANEL_H, PANEL, 14.0) + snapshot = state.snapshot + autostart = snapshot.try(&.autostart) + + center = top + 8 + ROW_H / 2 + control_top = center - CONTROL_H / 2 + toggle_x = RIGHT_X + RIGHT_W - 20 - TOGGLE_W + fit_text(canvas, RIGHT_X + 20, center, t("dashboard.field.autostart"), BODY_SIZE, TEXT, toggle_x - RIGHT_X - 40) + if autostart.nil? + toggle(canvas, toggle_x, control_top, false, snapshot ? t("dashboard.autostart.unavailable") : "-") + else + label = state.autostart_changing? ? "…" : t(autostart ? "dashboard.on" : "dashboard.off") + toggle(canvas, toggle_x, control_top, autostart, label) + hits << Hit.new(toggle_x, control_top, TOGGLE_W, CONTROL_H, "autostart") unless state.autostart_changing? + end + + # 更新が走っている間は終えさせない。置き換えた版の起動を確かめている最中に止めると、戻されてしまう。 + enabled = snapshot.try(&.update.phase).nil? + armed = state.armed == "quit" + button_x = RIGHT_X + 20 + button_y = top + 8 + ROW_H + 4 + button_w = RIGHT_W - 40 + canvas.fill_rect(button_x, button_y, button_w, 52.0, armed ? DANGER : BUTTON, 10.0) + canvas.stroke_rect(button_x, button_y, button_w, 52.0, enabled ? DANGER : LINE, 10.0, 2.0) + label = armed ? t("dashboard.quit.confirm") : t("dashboard.quit") + fit_text(canvas, button_x + button_w / 2, button_y + 26, label, BODY_SIZE, enabled ? TEXT : MUTED, button_w - 16, bold: armed, align: Align::Center) + hits << Hit.new(button_x, button_y, button_w, 52.0, "quit") if enabled + + message = state.general_message + text, color = if message + {message, tone_color(state.general_tone)} + elsif snapshot && autostart.nil? + {t("dashboard.autostart.not_installed"), WARN} + else + {t("dashboard.quit.note"), MUTED} + end + wrap(canvas, text, RIGHT_W - 40, SMALL_SIZE).first(3).each_with_index do |line, index| + canvas.text(RIGHT_X + 20, button_y + 70 + index * 22, line, SMALL_SIZE, color) + end + end + private def outcome_color(outcome : String) : Color case outcome when "restarted", "applied", "up_to_date" then OK diff --git a/src/main.cr b/src/main.cr index 1a7b9aa..92ec2b0 100644 --- a/src/main.cr +++ b/src/main.cr @@ -187,6 +187,8 @@ module KxFrameControllerManager # シグナルのハンドラは別のファイバで走る。主ループはこの印を見て動く。 @stop_requested = false @reload_requested = false + # 設定画面から終えるときに取った更新の排他。終わるまで手放さない。 + @quit_lock = nil.as(Update::FileStateStore?) # 27062 の疎通を確かめた接続の番号。つながるたびに 1 回だけ確かめる(仕様書 4.2 節)。 @probed_generation = nil.as(Int32?) # 言語を決め直した接続の番号。Steam の表示言語は SteamVR を起動し直さないと変わらないため、つながるたびに見る。 @@ -272,6 +274,27 @@ module KxFrameControllerManager {result.outcome.to_s.underscore, result.release.try(&.tag)} end dashboard.start_update = -> { Runtime::Systemd.start_manual_update(Runtime::Paths.executable_path) } + dashboard.set_autostart = ->(enabled : Bool) do + changed = Runtime::Systemd.set_autostart(enabled) + Log.info { "設定画面から自動起動を#{enabled ? "有効" : "無効"}にした" } if changed + changed + end + # 終了コード 0 で終える。ユニットは Restart=on-failure なので、systemd は起動し直さない。 + # systemctl stop を呼ばないのは、ユニットを経ずに `run` を起動した場合にも同じように終えるためである。 + # + # 更新の排他を取れたときだけ終える。取れなければ更新が走っており、置き換えた版の起動を確かめている最中に + # 止めると、更新は起動しなかったものと取り違えて元の版へ戻し、常駐を起動し直してしまう。 + # 排他はプロセスが終わるまで持ち、終える途中で更新が始まらないようにする(flock はプロセスの終了で外れる)。 + dashboard.quit = -> do + state = Update::FileStateStore.new(Runtime::Paths.update_state_path, Runtime::Paths.running_marker_path, Runtime::Paths.update_lock_path) + if state.try_lock + @quit_lock = state + @stop_requested = true + true + else + false + end + end dashboard.canvas_factory = ->(width : Int32, height : Int32) { Dashboard::CairoCanvas.create(width, height).as(Dashboard::Canvas?) } dashboard end @@ -296,6 +319,7 @@ module KxFrameControllerManager gain_range: connected ? parts.settings.gain_range : nil, config_errors: @config_errors.map { |error| KxFrameControllerManager.describe(error) }, update: update_status, + autostart: Runtime::Systemd.installed? ? Runtime::Systemd.autostart_enabled? : nil, ) end @@ -638,6 +662,71 @@ module KxFrameControllerManager 1 end + # 常駐のユニットを起動する。設定画面から終えた常駐を戻すのに使う。 + def start : Int32 + return not_installed unless Runtime::Systemd.installed? + if Runtime::Systemd.start + puts t("service.started") + 0 + else + STDERR.puts t("service.start_failed") + 1 + end + end + + # 常駐のユニットを止める。自動起動の設定は変えない。 + # + # 走っている更新が終わるのを、更新の排他を取って待ってから止める(uninstall と同じ)。 + # 置き換えた版の起動を確かめている最中に止めると、更新は起動しなかったものと取り違えて元の版へ戻し、 + # 常駐を起動し直してしまう。排他は止め終わるまで持ち、その間に更新が始まらないようにする。 + def stop : Int32 + return not_installed unless Runtime::Systemd.installed? + state = Update::FileStateStore.new(Runtime::Paths.update_state_path, Runtime::Paths.running_marker_path, Runtime::Paths.update_lock_path) + stopped = begin + state.lock + Runtime::Systemd.stop + ensure + state.unlock + end + if stopped + puts t("service.stopped") + 0 + else + STDERR.puts t("service.stop_failed") + 1 + end + end + + # 自動起動の状態を見せる。target(on、off)を渡せばそちらへ切り替える。 + # + # 状態は systemd のユニットの enable そのもので、設定ファイルには持たない。 + # 切り替えても今の常駐は起動も停止もしない。 + def autostart(target : String?) : Int32 + return not_installed unless Runtime::Systemd.installed? + current = Runtime::Systemd.autostart_enabled? + unless target + puts t(current ? "autostart.current.on" : "autostart.current.off") + return 0 + end + + enabled = target == "on" + if enabled == current + puts t(current ? "autostart.unchanged.on" : "autostart.unchanged.off") + return 0 + end + unless Runtime::Systemd.set_autostart(enabled) + STDERR.puts t("autostart.failed") + return 1 + end + puts t(enabled ? "autostart.changed.on" : "autostart.changed.off") + 0 + end + + private def not_installed : Int32 + STDERR.puts t("service.not_installed") + 1 + end + # 自動更新の前回の確認時刻を消し、次のタイマー(30 分以内)で新しいチャンネルを確かめさせる。 # 消さないと、切り替えても update.check_interval_h が経つまで何も起きない。 # 更新が走っている最中なら触らない。その更新が時刻を書き戻すためである。 @@ -737,6 +826,9 @@ module KxFrameControllerManager in .uninstall? then Tool.new.uninstall in .update? then Tool.new.update(auto: parsed.argument == Runtime::CLI::AUTO) in .channel? then Tool.new.channel(parsed.argument) + in .start? then Tool.new.start + in .stop? then Tool.new.stop + in .autostart? then Tool.new.autostart(parsed.argument) in .version? puts VERSION 0 diff --git a/src/runtime/cli.cr b/src/runtime/cli.cr index c79880f..7041819 100644 --- a/src/runtime/cli.cr +++ b/src/runtime/cli.cr @@ -12,12 +12,15 @@ module Runtime Uninstall Update Channel + Start + Stop + Autostart Version Help end # 解釈の結果。argument は disconnect の対象(left、right、both、シリアル)、update の --auto、 - # channel の切り替え先(stable、test)に使う。 + # channel の切り替え先(stable、test)、autostart の切り替え先(on、off)に使う。 # error が入っていれば、使い方の誤りとして終了コード 2 で終える。 record Parsed, command : Command, argument : String? = nil, error : String? = nil @@ -27,6 +30,9 @@ module Runtime # CLI は update を知らないため、同じ並びであることは spec で確かめる。 CHANNELS = %w[stable test] + # autostart が受け付ける綴り。 + AUTOSTART = %w[on off] + def self.parse(args : Array(String)) : Parsed name = args.first? rest = args[1..]? || [] of String @@ -46,6 +52,14 @@ module Runtime target = rest.first return Parsed.new(Command::Channel, target, "cli.channel_invalid") if rest.size > 1 || !CHANNELS.includes?(target) Parsed.new(Command::Channel, target) + when "start" then no_argument(Command::Start, rest) + when "stop" then no_argument(Command::Stop, rest) + when "autostart" + # 引数が無ければ今の状態を見せ、on か off があればそちらへ切り替える。 + return Parsed.new(Command::Autostart) if rest.empty? + target = rest.first + return Parsed.new(Command::Autostart, target, "cli.autostart_invalid") if rest.size > 1 || !AUTOSTART.includes?(target) + Parsed.new(Command::Autostart, target) when "version", "--version" then Parsed.new(Command::Version) when nil then Parsed.new(Command::Help, error: "") when "help", "--help", "-h" then Parsed.new(Command::Help) diff --git a/src/runtime/systemd.cr b/src/runtime/systemd.cr index 336156d..c3be7c0 100644 --- a/src/runtime/systemd.cr +++ b/src/runtime/systemd.cr @@ -93,6 +93,39 @@ module Runtime File.exists?(File.join(File.dirname(unit_path), UPDATE_TIMER_NAME)) end + # 常駐のユニットが書き出されているか。`install` を経ずに `run` を直接起動した環境には無い。 + def self.installed?(unit_path : String = Paths.systemd_unit_path) : Bool + File.exists?(unit_path) + end + + # 自動起動が有効か。`systemctl --user enable` が置くリンクがあるかで見る。 + # + # systemctl is-enabled を呼ばずにリンクを見るのは、設定画面が状態を 1 秒ごとに読み直すためである。 + # そのたびにプロセスを起こすのは重い。ユニットの WantedBy は default.target なので、リンクはその .wants に置かれる。 + def self.autostart_enabled?(unit_path : String = Paths.systemd_unit_path) : Bool + link = File.join(File.dirname(unit_path), "default.target.wants", UNIT_NAME) + !File.info?(link, follow_symlinks: false).nil? + end + + # 自動起動を切り替える。enable と disable はユニットの起動と停止をしないので、今の常駐はそのまま動き続ける。 + # + # 自動更新のタイマーは切り替えない。タイマーから起きた更新は、常駐が動いていなければ置き換えるだけで起動しない + # (Update::AutoUpdater)。自動起動を切っても、更新が常駐を勝手に起こすことは無い。 + def self.set_autostart(enabled : Bool, systemctl : Systemctl = Systemctl.new) : Bool + systemctl.run([enabled ? "enable" : "disable", "--quiet", UNIT_NAME]) + end + + # 常駐を起動する。起動の回数の制限に掛かっていれば、それを解いてから起動する。 + def self.start(systemctl : Systemctl = Systemctl.new) : Bool + systemctl.run(["reset-failed", UNIT_NAME]) + systemctl.run(["start", UNIT_NAME]) + end + + # 常駐を止める。止めた常駐は、次にログインするまで(自動起動が有効なら)か `start` まで動かない。 + def self.stop(systemctl : Systemctl = Systemctl.new) : Bool + systemctl.run(["stop", UNIT_NAME]) + end + # 自動更新から常駐のユニットを操作する。 class UpdateService < Update::ServiceControl def initialize(@systemctl : Systemctl = Systemctl.new)