From eeefcb54c9ee709a0b5c2a1c2cff27d46c4e4c96 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 07:01:57 +0000 Subject: [PATCH 1/2] =?UTF-8?q?VR=20=E3=81=AE=E3=83=A1=E3=83=8B=E3=83=A5?= =?UTF-8?q?=E3=83=BC=E3=81=AE=E3=80=8C=E3=83=97=E3=83=AD=E3=82=B0=E3=83=A9?= =?UTF-8?q?=E3=83=A0=E3=82=92=E8=B5=B7=E5=8B=95=E3=80=8D=E3=81=8B=E3=82=89?= =?UTF-8?q?=E5=B8=B8=E9=A7=90=E3=82=92=E8=B5=B7=E5=8B=95=E3=81=A7=E3=81=8D?= =?UTF-8?q?=E3=82=8B=E3=82=88=E3=81=86=E3=81=AB=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Steam は ~/.local/share/applications の .desktop から一覧を作るため、 install と常駐の起動時に .desktop を書き出し、uninstall で消す。 選ぶと start を実行する。あわせて start の reset-failed が出す 「not loaded」の警告を出さないようにする。 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WFzzs99PCwsU4KiFvipgdu --- README.en.md | 5 +- README.md | 5 +- docs/architecture.md | 3 ++ docs/development.md | 1 + docs/setup.md | 20 +++++++- docs/status.md | 2 + locales/de.json | 4 +- locales/en.json | 4 +- locales/es.json | 4 +- locales/fr.json | 4 +- locales/ja.json | 4 +- locales/ko.json | 4 +- locales/ru.json | 4 +- locales/zh-Hans.json | 4 +- locales/zh-Hant.json | 4 +- spec/runtime/desktop_entry_spec.cr | 59 ++++++++++++++++++++++ spec/runtime/paths_spec.cr | 9 ++++ spec/runtime/systemd_spec.cr | 7 ++- src/main.cr | 18 +++++++ src/runtime/desktop_entry.cr | 80 ++++++++++++++++++++++++++++++ src/runtime/paths.cr | 5 ++ src/runtime/systemd.cr | 14 ++++-- 22 files changed, 245 insertions(+), 19 deletions(-) create mode 100644 spec/runtime/desktop_entry_spec.cr create mode 100644 src/runtime/desktop_entry.cr diff --git a/README.en.md b/README.en.md index 513fc89..a3d994a 100644 --- a/README.en.md +++ b/README.en.md @@ -112,7 +112,8 @@ To stop automatic updates, turn off "Update automatically" in the "Update" tab. 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. +To bring it back right away, choose "KxFrameControllerManager" from "Launch a program" in the VR menu. +Running the following command in a terminal does the same. ```sh ~/.local/bin/kx-frame-controller-manager start @@ -120,7 +121,7 @@ To bring it back right away, run the following command in a terminal. 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 then on, the tool runs only when you choose it from "Launch a program" or run `start` above. From a terminal, `autostart on` and `autostart off` switch it, and `autostart` alone shows the current state. ## Uninstalling diff --git a/README.md b/README.md index a6cf800..fb18e91 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,8 @@ SteamVR のコントローラーバインド画面で KxFrameControllerManager 本ツールを止めるときは、設定画面の「全般」のタブで「KxFCM を終了」を 2 回押す。 終了するとタブも消える。 次に Frame を起動したときに、本ツールも起動し直す。 -すぐに戻すときは、端末から次のコマンドを実行する。 +すぐに戻すときは、VR のメニューの「プログラムを起動」から「KxFrameControllerManager」を選ぶ。 +端末から次のコマンドを実行しても同じである。 ```sh ~/.local/bin/kx-frame-controller-manager start @@ -120,7 +121,7 @@ SteamVR のコントローラーバインド画面で KxFrameControllerManager Frame の起動時に本ツールを起動させたくないときは、同じタブで「Frame の起動時に自動で起動」を OFF にする。 OFF にしても、動いている本ツールはそのまま動き続ける。 -以後は上の `start` を実行したときだけ動く。 +以後は「プログラムを起動」から選んだときか、上の `start` を実行したときだけ動く。 端末からは `autostart on` と `autostart off` で切り替えられ、`autostart` だけなら今の状態を表示する。 ## アンインストール diff --git a/docs/architecture.md b/docs/architecture.md index adbc4ab..3bd3f11 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -57,6 +57,7 @@ src/ scheduler.cr 主ループの 1 拍で何を呼ぶか cli.cr コマンドの解釈 systemd.cr ユニットの書き出し、systemctl --user の呼び出し、自動起動の状態の読み取り + desktop_entry.cr VR のメニューの「プログラムを起動」に出す .desktop の書き出しと削除 error/ usecase.cr 例外のログ記録 actions/ SteamVR Input のアクションマニフェストと frame_controller の既定バインド @@ -184,6 +185,8 @@ SteamVR が動いていないことは `VRInitError_Init_NoServerForBackgroundAp vrmanifest は接続のたびに書き出し直して登録する。 目的は SteamVR のコントローラーバインド画面に本ツールを出すことであり、自動起動には使わない。 +VR のメニューの「プログラムを起動」の一覧も vrmanifest からは作られない。 +その一覧は Steam が `.desktop` ファイルから作るため、`Runtime::DesktopEntry` が別に書き出す([導入](setup.md#vr-のメニューからの起動))。 実行ファイルのパスは `binary_path_linux` に書く。 ## 仕様書からの変更点 diff --git a/docs/development.md b/docs/development.md index bb35867..f30702d 100644 --- a/docs/development.md +++ b/docs/development.md @@ -125,3 +125,4 @@ crystal run scripts/preview_dashboard.cr -- tmp/dashboard-preview - SteamVR の起動でつながり、vrmanifest を登録できること - SteamVR の終了で OpenVR を閉じ、次の起動でつなぎ直すこと - `IVRSystem_026` と `IVRApplications_008` が `VR_IsInterfaceVersionValid` を通ること +- VR のメニューの「プログラムを起動」の一覧に「KxFrameControllerManager」が出て、選ぶと常駐が起動すること diff --git a/docs/setup.md b/docs/setup.md index ddcc585..1df9c22 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -143,6 +143,7 @@ SteamVR そのものは再起動しない。 | ログ | `~/.local/state/KxFrameControllerManager/logs/` | | 省電力で変える前の値 | `~/.local/state/KxFrameControllerManager/power_save.json` | | systemd のユニット | `~/.config/systemd/user/kx-frame-controller-manager.service` | +| 「プログラムを起動」の項目 | `~/.local/share/applications/kx-frame-controller-manager.desktop` | ## 常駐の管理 @@ -177,6 +178,23 @@ journalctl --user -u kx-frame-controller-manager # ログ タイマーから起きた更新は、常駐が止まっていれば実行ファイルを置き換えるだけで、常駐を起動しない。 終了した常駐や、自動起動を無効にした常駐を、更新が勝手に起こすことはない。 +### VR のメニューからの起動 + +VR のメニューの「プログラムを起動」には「KxFrameControllerManager」が出る。 +選ぶと `start` を実行する。常駐が既に動いていれば何も起きない。 + +この一覧は Steam が作る。 +Steam は `~/.local/share/applications/` などにある `.desktop` ファイルを集めて並べ、選ばれたらその `Exec` の行を実行する。 +vrmanifest の登録はこの一覧に関わらない。 +本ツールは `install` のときと、常駐が起動するたびに `kx-frame-controller-manager.desktop` を書き出す。 +常駐の起動のたびに書くのは、自動更新が `install` を通らずに版を上げるためである。 +この項目が無い版から自動更新で上げた環境にも、新しい版が起動した時点で入る。 +`uninstall` はこのファイルも消す。 +Steam のファイル(`shortcuts.vdf` など)は書き換えない。 + +書き出した直後は一覧に出ないことがある。 +Steam が一覧を作り直すまでの間である。一覧を一度開き直すか、Frame を再起動すると出る。 + `install` をやり直すと(導入の 1 行の再実行を含む)、自動起動は有効に戻る。 `install` は導入の手順そのものであり、利用者が明示して実行するためである。 @@ -188,7 +206,7 @@ journalctl --user -u kx-frame-controller-manager # ログ ```sh ~/.local/bin/kx-frame-controller-manager update # 待たずに確かめ、新しい版があれば置き換えて起動し直す -~/.local/bin/kx-frame-controller-manager uninstall # ユニットとタイマーを止めて消す +~/.local/bin/kx-frame-controller-manager uninstall # ユニットとタイマーを止めて消し、「プログラムを起動」の項目も消す ``` 導入の 1 行をもう一度実行しても、最新の版へ置き換えて起動し直す。 diff --git a/docs/status.md b/docs/status.md index 389894b..4f5530f 100644 --- a/docs/status.md +++ b/docs/status.md @@ -12,6 +12,7 @@ v1 として予定した機能はひととおり入っている。 - SteamVR のダッシュボードに設定画面のタブ「KxFCM」が出る。状態の確認、手動の切断、ボタンの割り当てと時間と省電力の設定、更新、表示言語の切り替えができる。状態の「切断機能」は、上の `127.0.0.1:27062` へ届くかを表す - systemd のユーザーユニットで常駐する。導入は `curl ... | bash` の 1 行で済む - 設定画面か `start`、`stop`、`autostart` のコマンドで、常駐を終え、起動し、自動起動を切り替えられる +- VR のメニューの「プログラムを起動」に「KxFrameControllerManager」が出て、選ぶと常駐を起動する - 自動更新のタイマーが新しい版を確かめて置き換え、起動しなければ元の版へ戻す - 両方が切れている間は明るさと画質を下げる省電力が使える。既定では省電力も明るさを下げる項目も無効なので、設定画面か設定ファイルで有効にする @@ -25,5 +26,6 @@ v1 として予定した機能はひととおり入っている。 - Background アプリから SteamVR Input が読めるか - 振動が出るか - 設定画面からの終了と自動起動の切り替え(2026-11-10 追加) +- 「プログラムを起動」の一覧に出ること、選んで常駐が起動すること(2026-11-10 追加) 実機でしか確かめられない項目の一覧は、[開発ガイド](development.md#実機でしか確かめられないこと)にある。 diff --git a/locales/de.json b/locales/de.json index 8a4681c..6cab55b 100644 --- a/locales/de.json +++ b/locales/de.json @@ -29,6 +29,7 @@ "disconnect.unconfirmed": "{target}: Anfrage gesendet, Trennung aber nicht bestätigt ({serial})", "disconnect.send_failed": "{target}: Anfrage konnte nicht gesendet werden ({serial})", "install.done": "Unit geschrieben und gestartet: {path}\nProgrammdatei: {executable}", + "install.desktop_entry": "Zu „Programm starten“ im VR-Menü hinzugefügt: {path}", "install.failed": "Aktivieren der Unit fehlgeschlagen. Prüfen Sie die Ausgabe von systemctl oben", "uninstall.done": "Unit gestoppt und entfernt", "uninstall.failed": "Entfernen der Unit fehlgeschlagen. Prüfen Sie die Ausgabe von systemctl oben", @@ -203,5 +204,6 @@ "steamvr.description": "Schaltet Steam-Frame-Controller durch langes Drücken aus.", "steamvr.action_set": "KxFrameControllerManager", "steamvr.action.power_off": "Diesen Controller ausschalten (halten)", - "steamvr.action.haptic": "Haptisches Feedback" + "steamvr.action.haptic": "Haptisches Feedback", + "desktop_entry.comment": "Startet KxFCM, das Steam-Frame-Controller per langem Drücken ausschaltet" } diff --git a/locales/en.json b/locales/en.json index a1d4e2e..51f2f5a 100644 --- a/locales/en.json +++ b/locales/en.json @@ -29,6 +29,7 @@ "disconnect.unconfirmed": "{target}: sent the request, but could not confirm the disconnect ({serial})", "disconnect.send_failed": "{target}: could not send the request ({serial})", "install.done": "Wrote and started the unit: {path}\nExecutable: {executable}", + "install.desktop_entry": "Added to \"Launch a program\" in the VR menu: {path}", "install.failed": "Failed to enable the unit. Check the systemctl output above", "uninstall.done": "Stopped and removed the unit", "uninstall.failed": "Failed to remove the unit. Check the systemctl output above", @@ -203,5 +204,6 @@ "steamvr.description": "Turns off Steam Frame controllers with a long press.", "steamvr.action_set": "KxFrameControllerManager", "steamvr.action.power_off": "Turn off this controller (hold)", - "steamvr.action.haptic": "Haptic feedback" + "steamvr.action.haptic": "Haptic feedback", + "desktop_entry.comment": "Starts KxFCM, which turns off Steam Frame controllers with a long press" } diff --git a/locales/es.json b/locales/es.json index 935396d..656aef0 100644 --- a/locales/es.json +++ b/locales/es.json @@ -29,6 +29,7 @@ "disconnect.unconfirmed": "{target}: se envió la solicitud, pero no se pudo confirmar la desconexión ({serial})", "disconnect.send_failed": "{target}: no se pudo enviar la solicitud ({serial})", "install.done": "Unidad escrita e iniciada: {path}\nEjecutable: {executable}", + "install.desktop_entry": "Añadido a «Iniciar un programa» en el menú de RV: {path}", "install.failed": "No se pudo activar la unidad. Revisa la salida de systemctl de arriba", "uninstall.done": "Unidad detenida y eliminada", "uninstall.failed": "No se pudo eliminar la unidad. Revisa la salida de systemctl de arriba", @@ -203,5 +204,6 @@ "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)", - "steamvr.action.haptic": "Vibración" + "steamvr.action.haptic": "Vibración", + "desktop_entry.comment": "Inicia KxFCM, que apaga los mandos de Steam Frame con una pulsación larga" } diff --git a/locales/fr.json b/locales/fr.json index cd5931b..0ecac44 100644 --- a/locales/fr.json +++ b/locales/fr.json @@ -29,6 +29,7 @@ "disconnect.unconfirmed": "{target} : requête envoyée, mais déconnexion non confirmée ({serial})", "disconnect.send_failed": "{target} : impossible d'envoyer la requête ({serial})", "install.done": "Unité écrite et démarrée : {path}\nExécutable : {executable}", + "install.desktop_entry": "Ajouté à « Lancer un programme » dans le menu VR : {path}", "install.failed": "Échec de l'activation de l'unité. Consultez la sortie de systemctl ci-dessus", "uninstall.done": "Unité arrêtée et supprimée", "uninstall.failed": "Échec de la suppression de l'unité. Consultez la sortie de systemctl ci-dessus", @@ -203,5 +204,6 @@ "steamvr.description": "Éteint les manettes Steam Frame par un appui long.", "steamvr.action_set": "KxFrameControllerManager", "steamvr.action.power_off": "Éteindre cette manette (appui long)", - "steamvr.action.haptic": "Retour haptique" + "steamvr.action.haptic": "Retour haptique", + "desktop_entry.comment": "Démarre KxFCM, qui éteint les manettes Steam Frame par un appui long" } diff --git a/locales/ja.json b/locales/ja.json index 3210e30..c856de2 100644 --- a/locales/ja.json +++ b/locales/ja.json @@ -29,6 +29,7 @@ "disconnect.unconfirmed": "{target}: 切断要求を送りましたが、切れたことを確かめられませんでした({serial})", "disconnect.send_failed": "{target}: 切断要求を送れませんでした({serial})", "install.done": "ユニットを書き出して起動しました: {path}\n実行ファイル: {executable}", + "install.desktop_entry": "VR のメニューの「プログラムを起動」に追加しました: {path}", "install.failed": "ユニットの有効化に失敗しました。上の systemctl の出力を確かめてください", "uninstall.done": "ユニットを止めて消しました", "uninstall.failed": "ユニットの解除に失敗しました。上の systemctl の出力を確かめてください", @@ -203,5 +204,6 @@ "steamvr.description": "長押しで Steam Frame のコントローラーを切断します。", "steamvr.action_set": "KxFrameControllerManager", "steamvr.action.power_off": "このコントローラーを切断(長押し)", - "steamvr.action.haptic": "振動" + "steamvr.action.haptic": "振動", + "desktop_entry.comment": "KxFCM の常駐を起動します。長押しで Steam Frame のコントローラーを切断します" } diff --git a/locales/ko.json b/locales/ko.json index faf7ceb..0d8a25f 100644 --- a/locales/ko.json +++ b/locales/ko.json @@ -29,6 +29,7 @@ "disconnect.unconfirmed": "{target}: 요청을 보냈지만 연결이 끊긴 것을 확인하지 못했습니다 ({serial})", "disconnect.send_failed": "{target}: 요청을 보내지 못했습니다 ({serial})", "install.done": "유닛을 작성하고 시작했습니다: {path}\n실행 파일: {executable}", + "install.desktop_entry": "VR 메뉴의 \"프로그램 실행\"에 추가했습니다: {path}", "install.failed": "유닛 활성화에 실패했습니다. 위의 systemctl 출력을 확인하세요", "uninstall.done": "유닛을 중지하고 삭제했습니다", "uninstall.failed": "유닛 삭제에 실패했습니다. 위의 systemctl 출력을 확인하세요", @@ -203,5 +204,6 @@ "steamvr.description": "길게 눌러 Steam Frame 컨트롤러의 전원을 끕니다.", "steamvr.action_set": "KxFrameControllerManager", "steamvr.action.power_off": "이 컨트롤러 연결 끊기 (길게 누르기)", - "steamvr.action.haptic": "진동" + "steamvr.action.haptic": "진동", + "desktop_entry.comment": "KxFCM 상주 프로그램을 시작합니다. 길게 눌러 Steam Frame 컨트롤러를 끕니다" } diff --git a/locales/ru.json b/locales/ru.json index 0bbeb2c..a30ebf0 100644 --- a/locales/ru.json +++ b/locales/ru.json @@ -29,6 +29,7 @@ "disconnect.unconfirmed": "{target}: запрос отправлен, но отключение не подтверждено ({serial})", "disconnect.send_failed": "{target}: не удалось отправить запрос ({serial})", "install.done": "Юнит записан и запущен: {path}\nИсполняемый файл: {executable}", + "install.desktop_entry": "Добавлено в «Запустить программу» в меню VR: {path}", "install.failed": "Не удалось включить юнит. Проверьте вывод systemctl выше", "uninstall.done": "Юнит остановлен и удалён", "uninstall.failed": "Не удалось удалить юнит. Проверьте вывод systemctl выше", @@ -203,5 +204,6 @@ "steamvr.description": "Выключает контроллеры Steam Frame долгим нажатием.", "steamvr.action_set": "KxFrameControllerManager", "steamvr.action.power_off": "Выключить этот контроллер (удерживать)", - "steamvr.action.haptic": "Вибрация" + "steamvr.action.haptic": "Вибрация", + "desktop_entry.comment": "Запускает KxFCM, который выключает контроллеры Steam Frame долгим нажатием" } diff --git a/locales/zh-Hans.json b/locales/zh-Hans.json index 8524037..6b1d47c 100644 --- a/locales/zh-Hans.json +++ b/locales/zh-Hans.json @@ -29,6 +29,7 @@ "disconnect.unconfirmed": "{target}: 已发送断开请求,但无法确认已断开({serial})", "disconnect.send_failed": "{target}: 无法发送断开请求({serial})", "install.done": "已写入并启动单元: {path}\n可执行文件: {executable}", + "install.desktop_entry": "已添加到 VR 菜单的“启动程序”: {path}", "install.failed": "启用单元失败。请查看上方 systemctl 的输出", "uninstall.done": "已停止并删除单元", "uninstall.failed": "删除单元失败。请查看上方 systemctl 的输出", @@ -203,5 +204,6 @@ "steamvr.description": "长按即可关闭 Steam Frame 的控制器。", "steamvr.action_set": "KxFrameControllerManager", "steamvr.action.power_off": "断开此控制器(长按)", - "steamvr.action.haptic": "振动" + "steamvr.action.haptic": "振动", + "desktop_entry.comment": "启动 KxFCM 常驻程序。长按即可断开 Steam Frame 控制器" } diff --git a/locales/zh-Hant.json b/locales/zh-Hant.json index 4f1b92b..4e56ddd 100644 --- a/locales/zh-Hant.json +++ b/locales/zh-Hant.json @@ -29,6 +29,7 @@ "disconnect.unconfirmed": "{target}: 已送出中斷請求,但無法確認已中斷({serial})", "disconnect.send_failed": "{target}: 無法送出中斷請求({serial})", "install.done": "已寫入並啟動單元: {path}\n執行檔: {executable}", + "install.desktop_entry": "已加入 VR 選單的「啟動程式」: {path}", "install.failed": "啟用單元失敗。請查看上方 systemctl 的輸出", "uninstall.done": "已停止並移除單元", "uninstall.failed": "移除單元失敗。請查看上方 systemctl 的輸出", @@ -203,5 +204,6 @@ "steamvr.description": "長按即可關閉 Steam Frame 的控制器。", "steamvr.action_set": "KxFrameControllerManager", "steamvr.action.power_off": "中斷此控制器(長按)", - "steamvr.action.haptic": "震動" + "steamvr.action.haptic": "震動", + "desktop_entry.comment": "啟動 KxFCM 常駐程式。長按即可中斷 Steam Frame 控制器" } diff --git a/spec/runtime/desktop_entry_spec.cr b/spec/runtime/desktop_entry_spec.cr new file mode 100644 index 0000000..abb6e04 --- /dev/null +++ b/spec/runtime/desktop_entry_spec.cr @@ -0,0 +1,59 @@ +require "../spec_helper" +require "../../src/runtime/desktop_entry" + +describe Runtime::DesktopEntry do + it "Steam の一覧に出る形で書き、選んだら start を実行させる" do + content = Runtime::DesktopEntry.content("/home/deck/.local/bin/kx-frame-controller-manager") + content.should start_with "[Desktop Entry]\n" + content.should contain "Type=Application\n" + content.should contain "Name=KxFrameControllerManager\n" + content.should contain %(Exec="/home/deck/.local/bin/kx-frame-controller-manager" start\n) + content.should contain "TryExec=/home/deck/.local/bin/kx-frame-controller-manager\n" + # Steam は NoDisplay=true と、gamescope を外す OnlyShowIn・NotShowIn の項目を一覧から除く。 + content.should_not contain "NoDisplay" + content.should_not contain "OnlyShowIn" + content.should_not contain "NotShowIn" + end + + it "説明文を全言語ぶん並べ、既定は英語にする" do + content = Runtime::DesktopEntry.content("/x") + content.should contain "Comment=#{Runtime::I18n.t_in("en", "desktop_entry.comment")}\n" + content.should contain "Comment[ja]=#{Runtime::I18n.t_in("ja", "desktop_entry.comment")}\n" + content.should contain "Comment[zh_CN]=" + content.should contain "Comment[zh_TW]=" + content.should_not contain "Comment[en]=" + Runtime::I18n::CODES.size.should eq content.lines.count(&.starts_with?("Comment")) + end + + it "Exec の % を %% にし、TryExec はそのまま書く" do + content = Runtime::DesktopEntry.content("/home/deck/my apps/kx%fcm") + content.should contain %(Exec="/home/deck/my apps/kx%%fcm" start\n) + content.should contain "TryExec=/home/deck/my apps/kx%fcm\n" + end + + it "引用符の中で逃がしが要る文字を含むパスは受け付けない" do + ["/a\"b", "/a`b", "/a$b", "/a\\b", "/a\nb"].each do |path| + expect_raises(ArgumentError) { Runtime::DesktopEntry.content(path) } + end + end + + it "中身が変わったときだけ書き、消せば無くなる" do + directory = File.tempname("kxfcm-desktop") + path = File.join(directory, "applications", Runtime::DesktopEntry::FILE_NAME) + begin + Runtime::DesktopEntry.write("/a", path).should be_true + File.read(path).should eq Runtime::DesktopEntry.content("/a") + Runtime::DesktopEntry.write("/a", path).should be_false + Runtime::DesktopEntry.write("/b", path).should be_true + File.read(path).should contain "TryExec=/b\n" + File.exists?("#{path}.new").should be_false + + Runtime::DesktopEntry.delete(path) + File.exists?(path).should be_false + # 無いものを消しても何も起きない。 + Runtime::DesktopEntry.delete(path) + ensure + FileUtils.rm_rf(directory) + end + end +end diff --git a/spec/runtime/paths_spec.cr b/spec/runtime/paths_spec.cr index 249ca7e..2fe5df8 100644 --- a/spec/runtime/paths_spec.cr +++ b/spec/runtime/paths_spec.cr @@ -35,3 +35,12 @@ describe "Runtime::Paths.systemd_unit_path" do .should eq "/home/deck/.config/systemd/user/kx-frame-controller-manager.service" end end + +describe "Runtime::Paths.desktop_entry_path" do + it "XDG_DATA_HOME の下の applications に置く" do + Runtime::Paths.desktop_entry_path({"HOME" => "/home/deck"}) + .should eq "/home/deck/.local/share/applications/kx-frame-controller-manager.desktop" + Runtime::Paths.desktop_entry_path({"HOME" => "/home/deck", "XDG_DATA_HOME" => "/data"}) + .should eq "/data/applications/kx-frame-controller-manager.desktop" + end +end diff --git a/spec/runtime/systemd_spec.cr b/spec/runtime/systemd_spec.cr index 79f617d..7203d7e 100644 --- a/spec/runtime/systemd_spec.cr +++ b/spec/runtime/systemd_spec.cr @@ -2,10 +2,13 @@ require "../spec_helper" private class FakeSystemctl < Runtime::Systemd::Systemctl getter calls = [] of Array(String) + # 出力を捨てた呼び出し。calls にも同じものを積む。 + getter quiet_calls = [] of Array(String) property fail = false - def run(arguments : Array(String)) : Bool + def run(arguments : Array(String), quiet : Bool = false) : Bool @calls << arguments + @quiet_calls << arguments if quiet !@fail end @@ -124,5 +127,7 @@ describe Runtime::Systemd do ["start", Runtime::Systemd::UNIT_NAME], ["stop", Runtime::Systemd::UNIT_NAME], ] + # 読み込まれていないユニットの reset-failed は失敗して警告を出すが、起動には差し支えない。 + systemctl.quiet_calls.should eq [["reset-failed", Runtime::Systemd::UNIT_NAME]] end end diff --git a/src/main.cr b/src/main.cr index 92ec2b0..ebf54f4 100644 --- a/src/main.cr +++ b/src/main.cr @@ -8,6 +8,7 @@ require "./frame_link/websocket_repository" require "./power_off/usecase" require "./power_save/usecase" require "./runtime/cli" +require "./runtime/desktop_entry" require "./runtime/i18n" require "./runtime/logging" require "./runtime/paths" @@ -201,6 +202,7 @@ module KxFrameControllerManager load_config trap_signals mark_running + write_desktop_entry check_update until @stop_requested @@ -383,6 +385,18 @@ module KxFrameControllerManager end # 起動したことを残す。自動更新は、置き換えた版がここまで来たことで起動を確かめる。 + # VR のメニューの「プログラムを起動」に出す .desktop を、無いか古ければ書き出す。 + # + # `install` も書き出すが、自動更新は `install` を通らずに実行ファイルを置き換えて常駐を起動し直す。 + # .desktop より前の版から上げた環境にも、置き換えた版が起動した時点で入るようにする。 + # `install` を経ずに `run` を直接起動した環境(開発中など)には書かない。 + private def write_desktop_entry : Nil + return unless Runtime::Systemd.installed? + Runtime::DesktopEntry.write(Runtime::Paths.executable_path) + rescue exception : ArgumentError | File::Error + Log.warn(exception: exception) { ".desktop を書き出せなかった" } + end + private def mark_running : Nil @errors.guard("error.update") do Update::FileStateStore.write_marker(Runtime::Paths.running_marker_path, VERSION, Process.pid) @@ -555,6 +569,8 @@ module KxFrameControllerManager executable = Runtime::Paths.executable_path if Runtime::Systemd.install(executable) puts t("install.done", {"path" => Runtime::Paths.systemd_unit_path, "executable" => executable}) + Runtime::DesktopEntry.write(executable) + puts t("install.desktop_entry", {"path" => Runtime::Paths.desktop_entry_path}) 0 else STDERR.puts t("install.failed") @@ -573,6 +589,8 @@ module KxFrameControllerManager ensure state.unlock end + # 一覧の項目は、ユニットの解除に失敗しても消す。残すと、選んでも起動できない項目が並ぶ。 + Runtime::DesktopEntry.delete if removed puts t("uninstall.done") 0 diff --git a/src/runtime/desktop_entry.cr b/src/runtime/desktop_entry.cr new file mode 100644 index 0000000..178da34 --- /dev/null +++ b/src/runtime/desktop_entry.cr @@ -0,0 +1,80 @@ +require "log" +require "./i18n" +require "./paths" + +module Runtime + # VR のメニューの「プログラムを起動」に本ツールを出すための .desktop ファイル。 + # + # その一覧は Steam が作る。Steam は XDG のアプリケーションのディレクトリ(~/.local/share/applications など)にある + # .desktop を集め、NoDisplay=true のものと、OnlyShowIn か NotShowIn で gamescope を外したものを除いて並べる。 + # 選ぶと Exec の行を実行する。vrmanifest の登録はこの一覧に関わらない。 + # + # Steam のファイル(shortcuts.vdf など)は書き換えない。Steam の稼働中に書くと上書きされるか壊れうるためである。 + # .desktop は ~ の下に置く 1 ファイルで済み、消せば元に戻る。 + # + # 選んだときは `start` を実行する。常駐が既に動いていれば systemd は何もしない。 + module DesktopEntry + Log = ::Log.for("desktop_entry") + + FILE_NAME = "kx-frame-controller-manager.desktop" + NAME = "KxFrameControllerManager" + # freedesktop のアイコン名の決まりにある名前。Steam が描かなくても一覧には出る。 + ICON = "input-gaming" + + # 中身を組み立てる。説明文は全言語ぶんを Comment[言語] で並べ、既定は英語にする。 + # + # Exec の引数は二重引用符で囲む。引用符の中で逃がしが要る文字(" ` $ \)と改行を含むパスは受け付けない。 + # Exec の % は欄の指定子として読まれるため %% にする。TryExec は欄の指定子を持たないので、そのまま書く。 + # TryExec の実行ファイルが無ければ、Steam もデスクトップも一覧から外す。 + def self.content(executable : String) : String + if executable.each_char.any? { |char| char.in?('"', '`', '$', '\\', '\n', '\r') } + raise ArgumentError.new(".desktop に書けない文字が実行ファイルのパスに含まれている: #{executable}") + end + + String.build do |io| + io << "[Desktop Entry]\n" + io << "Type=Application\n" + io << "Version=1.5\n" + io << "Name=" << NAME << '\n' + io << "Comment=" << I18n.t_in("en", "desktop_entry.comment") << '\n' + I18n::CODES.each do |code| + next if code == "en" + io << "Comment[" << tag(code) << "]=" << I18n.t_in(code, "desktop_entry.comment") << '\n' + end + io << %(Exec="#{executable.gsub("%", "%%")}" start\n) + io << "TryExec=" << executable << '\n' + io << "Icon=" << ICON << '\n' + io << "Terminal=false\n" + io << "Categories=Utility;\n" + end + end + + # .desktop の言語の札。中国語は簡体と繁体を地域で分け、それ以外は言語だけにする。 + def self.tag(code : String) : String + steamvr = I18n.steamvr_tag(code) + steamvr.starts_with?("zh") ? steamvr : steamvr.split('_').first + end + + # 書き出す。中身が同じなら書かない。変えたら true を返す。 + # + # 隣へ書いてからリネームで置き換える。Steam が一覧を作る最中に、書きかけのファイルを読ませないためである。 + def self.write(executable : String, path : String = Paths.desktop_entry_path) : Bool + expected = content(executable) + return false if File.exists?(path) && File.read(path) == expected + + Dir.mkdir_p(File.dirname(path)) + temporary = "#{path}.new" + File.write(temporary, expected) + File.rename(temporary, path) + Log.info { ".desktop を書き出した: #{path}" } + true + end + + # 消す。無ければ何もしない。消せなければログに残すだけにする。 + def self.delete(path : String = Paths.desktop_entry_path) : Nil + Log.info { ".desktop を消した: #{path}" } if File.delete?(path) + rescue exception : File::Error + Log.warn(exception: exception) { ".desktop を消せなかった: #{path}" } + end + end +end diff --git a/src/runtime/paths.cr b/src/runtime/paths.cr index 90d3669..ca9aec7 100644 --- a/src/runtime/paths.cr +++ b/src/runtime/paths.cr @@ -70,6 +70,11 @@ module Runtime File.join(xdg("XDG_CONFIG_HOME", ".config", env), "systemd", "user", "kx-frame-controller-manager.service") end + # VR のメニューの「プログラムを起動」に出す .desktop。既定は ~/.local/share/applications/。 + def self.desktop_entry_path(env = ENV) : String + File.join(xdg("XDG_DATA_HOME", File.join(".local", "share"), env), "applications", "kx-frame-controller-manager.desktop") + end + # 起動した実行ファイルの絶対パス。 # vrmanifest の binary_path_linux と、更新での置き換えに使う。 def self.executable_path : String diff --git a/src/runtime/systemd.cr b/src/runtime/systemd.cr index c3be7c0..0bada1f 100644 --- a/src/runtime/systemd.cr +++ b/src/runtime/systemd.cr @@ -42,8 +42,11 @@ module Runtime # systemctl --user の呼び出し。spec では差し替えて呼び出しを記録する。 class Systemctl # 呼び出しが成功したら true を返す。出力はそのまま利用者へ見せる。 - def run(arguments : Array(String)) : Bool - Process.run("systemctl", ["--user"] + arguments, output: Process::Redirect::Inherit, error: Process::Redirect::Inherit).success? + # + # quiet が真なら出力を捨てる。失敗しても構わない呼び出し(reset-failed)の警告を見せないために使う。 + def run(arguments : Array(String), quiet : Bool = false) : Bool + redirect = quiet ? Process::Redirect::Close : Process::Redirect::Inherit + Process.run("systemctl", ["--user"] + arguments, output: redirect, error: redirect).success? rescue exception : File::NotFoundError | IO::Error Log.error { "systemctl を呼べなかった: #{exception.message}" } false @@ -116,8 +119,11 @@ module Runtime end # 常駐を起動する。起動の回数の制限に掛かっていれば、それを解いてから起動する。 + # + # reset-failed は、ユニットが読み込まれていなければ「not loaded」と失敗する。 + # 自動起動を切って Frame を起動し直した後がそうであり、起動には差し支えないので、出力を捨てて結果も見ない。 def self.start(systemctl : Systemctl = Systemctl.new) : Bool - systemctl.run(["reset-failed", UNIT_NAME]) + systemctl.run(["reset-failed", UNIT_NAME], quiet: true) systemctl.run(["start", UNIT_NAME]) end @@ -144,7 +150,7 @@ module Runtime end def reset_failed : Nil - @systemctl.run(["reset-failed", UNIT_NAME]) + @systemctl.run(["reset-failed", UNIT_NAME], quiet: true) end end From d2f9a8dc3e66d3544cd6123b82b99fac2faed70d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 07:06:13 +0000 Subject: [PATCH 2/2] =?UTF-8?q?.desktop=20=E3=81=AE=E6=9B=B8=E3=81=8D?= =?UTF-8?q?=E5=87=BA=E3=81=97=E3=81=A7=E3=80=81=E6=9B=B8=E3=81=8D=E8=BE=BC?= =?UTF-8?q?=E3=81=BF=E3=81=94=E3=81=A8=E3=81=AB=E5=88=A5=E3=81=AE=E4=B8=80?= =?UTF-8?q?=E6=99=82=E3=83=95=E3=82=A1=E3=82=A4=E3=83=AB=E3=82=92=E4=BD=BF?= =?UTF-8?q?=E3=81=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit install と、それが起動した常駐が同時に書くと、共通の .new を 取り合ってリネームが失敗し、書きかけの中身も公開しうるため。 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WFzzs99PCwsU4KiFvipgdu --- spec/runtime/desktop_entry_spec.cr | 24 +++++++++++++++++++++++- src/runtime/desktop_entry.cr | 14 +++++++++++--- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/spec/runtime/desktop_entry_spec.cr b/spec/runtime/desktop_entry_spec.cr index abb6e04..fa70377 100644 --- a/spec/runtime/desktop_entry_spec.cr +++ b/spec/runtime/desktop_entry_spec.cr @@ -37,6 +37,27 @@ describe Runtime::DesktopEntry do end end + it "同時に書いても、どちらも失敗せず、書き終えた中身が残る" do + directory = File.tempname("kxfcm-desktop") + path = File.join(directory, Runtime::DesktopEntry::FILE_NAME) + begin + done = Channel(Exception?).new + 20.times do |index| + spawn do + Runtime::DesktopEntry.write("/#{index % 2}", path) + done.send(nil) + rescue exception + done.send(exception) + end + end + 20.times { done.receive.should be_nil } + ["/0", "/1"].map { |exe| Runtime::DesktopEntry.content(exe) }.should contain File.read(path) + Dir.children(directory).should eq [Runtime::DesktopEntry::FILE_NAME] + ensure + FileUtils.rm_rf(directory) + end + end + it "中身が変わったときだけ書き、消せば無くなる" do directory = File.tempname("kxfcm-desktop") path = File.join(directory, "applications", Runtime::DesktopEntry::FILE_NAME) @@ -46,7 +67,8 @@ describe Runtime::DesktopEntry do Runtime::DesktopEntry.write("/a", path).should be_false Runtime::DesktopEntry.write("/b", path).should be_true File.read(path).should contain "TryExec=/b\n" - File.exists?("#{path}.new").should be_false + # 隣に書いたファイルは残さない。 + Dir.children(File.dirname(path)).should eq [Runtime::DesktopEntry::FILE_NAME] Runtime::DesktopEntry.delete(path) File.exists?(path).should be_false diff --git a/src/runtime/desktop_entry.cr b/src/runtime/desktop_entry.cr index 178da34..6ade13d 100644 --- a/src/runtime/desktop_entry.cr +++ b/src/runtime/desktop_entry.cr @@ -1,4 +1,5 @@ require "log" +require "random/secure" require "./i18n" require "./paths" @@ -58,14 +59,21 @@ module Runtime # 書き出す。中身が同じなら書かない。変えたら true を返す。 # # 隣へ書いてからリネームで置き換える。Steam が一覧を作る最中に、書きかけのファイルを読ませないためである。 + # 隣のファイルの名前は書き込みごとに変える。`install` と、それが起動した常駐は同時に書きうる。 + # 名前が同じだと、先にリネームした側が相手の書きかけを公開し、後の側のリネームは失敗する。 + # 名前の末尾は .desktop にしないので、Steam は隣のファイルを一覧に入れない。 def self.write(executable : String, path : String = Paths.desktop_entry_path) : Bool expected = content(executable) return false if File.exists?(path) && File.read(path) == expected Dir.mkdir_p(File.dirname(path)) - temporary = "#{path}.new" - File.write(temporary, expected) - File.rename(temporary, path) + temporary = "#{path}.#{Process.pid}.#{Random::Secure.hex(4)}.new" + begin + File.write(temporary, expected) + File.rename(temporary, path) + ensure + File.delete?(temporary) + end Log.info { ".desktop を書き出した: #{path}" } true end