mirror of
https://github.com/SteamFramelyHomebrew/framely.git
synced 2026-10-18 01:02:16 +02:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
76eba81eff | ||
|
|
3427786053 | ||
|
|
2e5496a2bd | ||
|
|
cdb24fd31d | ||
|
|
3039c9ef0e | ||
|
|
41137e1d26 |
No files matched your search
@@ -54,6 +54,34 @@ jobs:
|
||||
key: cef-linux-arm64-154.0.32-682c378
|
||||
- name: Fetch pinned CEF
|
||||
run: test -d target/cef || bash tools/fetch-cef.sh
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '25'
|
||||
architecture: aarch64
|
||||
- name: Prepare pinned q2f inputs
|
||||
run: |
|
||||
mkdir -p target/q2f-input
|
||||
curl -fsSL --retry 3 -o target/q2f-input/cli-jar.zip https://github.com/ovrport/app/releases/download/1.2.3/cli-jar.zip
|
||||
python3 - <<'PY'
|
||||
import zipfile
|
||||
with zipfile.ZipFile('target/q2f-input/cli-jar.zip') as source:
|
||||
name = 'overportcli-1.2.3-all.jar'
|
||||
with source.open(name) as data, open('target/q2f-input/' + name, 'xb') as output:
|
||||
import shutil
|
||||
shutil.copyfileobj(data, output)
|
||||
PY
|
||||
curl -fsSL --retry 3 -o target/q2f-input/libraries.zip https://files.crx.moe/ovrport/tracker/releases/download/3.4.3-23204ea/libraries.zip
|
||||
curl -fsSL --retry 3 -o target/q2f-input/LICENSE https://raw.githubusercontent.com/ovrport/app/c790854/LICENSE
|
||||
curl -fsSL --retry 3 -o target/q2f-input/source.tar.gz https://github.com/ovrport/app/archive/c790854.tar.gz
|
||||
sha256sum -c <<'EOF'
|
||||
307d58a69a5c9722f912d1b6566b0dd1e0ebe1440c6d1e56cab6cb883d74fef2 target/q2f-input/overportcli-1.2.3-all.jar
|
||||
6cec6c176e1aeee8d9ec4f9b4e3982f71da7b44a36a293249620073a06f00e5e target/q2f-input/libraries.zip
|
||||
2db2c0f597a8be01d9742180019627b4c23fd0213f04f5034fbad53f0d296eb3 target/q2f-input/source.tar.gz
|
||||
EOF
|
||||
jlink --strip-debug --no-man-pages --no-header-files --compress=2 \
|
||||
--add-modules java.base,java.datatransfer,java.xml,java.prefs,java.desktop,java.logging,java.net.http,jdk.crypto.ec,jdk.unsupported \
|
||||
--output target/q2f-input/java
|
||||
- name: Validate
|
||||
run: |
|
||||
npm ci
|
||||
@@ -66,11 +94,16 @@ jobs:
|
||||
env:
|
||||
RELEASE_REPO: ${{ github.repository }}
|
||||
RELEASE_TAG: ${{ github.ref_name }}
|
||||
Q2F_JAVA_HOME: target/q2f-input/java
|
||||
Q2F_CLI_JAR: target/q2f-input/overportcli-1.2.3-all.jar
|
||||
Q2F_LIBRARIES_ZIP: target/q2f-input/libraries.zip
|
||||
Q2F_LICENSE: target/q2f-input/LICENSE
|
||||
Q2F_SOURCE_ARCHIVE: target/q2f-input/source.tar.gz
|
||||
run: |
|
||||
bash tools/package-release.sh target/cef
|
||||
mkdir -p release-assets
|
||||
archive=$(find release -maxdepth 1 -name 'framely-*-linux-arm64.tar.gz' ! -name '*-offline-linux-arm64.tar.gz' ! -name 'framely-cef-*' -print -quit)
|
||||
cp release/*.tar.gz release/framely-cef.json release-assets/
|
||||
cp release/*.tar.gz release/framely-cef.json release/framely-q2f.json release-assets/
|
||||
cp tools/bootstrap.py release-assets/bootstrap.py
|
||||
cp install.sh release-assets/install.sh
|
||||
"$CARGO_TARGET_DIR/release/framely" release-manifest --archive "$archive" --url "https://github.com/$RELEASE_REPO/releases/download/$RELEASE_TAG/$(basename "$archive")" --output release-assets/framely-release.json --changelog "Framely $RELEASE_TAG"
|
||||
@@ -99,8 +132,8 @@ jobs:
|
||||
RELEASE_TAG: ${{ github.ref_name }}
|
||||
run: |
|
||||
cd release-assets
|
||||
sha256sum -- *.tar.gz bootstrap.py install.sh framely-release.json framely-cef.json > SHA256SUMS
|
||||
printf 'Framely %s\n\nFirst install: choose the complete *-offline-linux-arm64.tar.gz package. Updates: choose the smaller Framely package without CEF. A separate framely-cef-* archive is available for runtime downloads.\n\nInstall on Frame over SSH using the repository install.sh. SHA256SUMS verifies archives; each archive also includes internal checksums.\n' "$RELEASE_TAG" > release-notes.txt
|
||||
sha256sum -- *.tar.gz bootstrap.py install.sh framely-release.json framely-cef.json framely-q2f.json > SHA256SUMS
|
||||
printf 'Framely %s\n\nFirst install: choose the complete *-offline-linux-arm64.tar.gz package. Updates: choose the smaller Framely package without CEF. Separate framely-cef-* and framely-q2f-* archives provide the browser and optional Quest converter.\n\nInstall on Frame over SSH using the repository install.sh. SHA256SUMS verifies archives; each archive also includes internal checksums.\n' "$RELEASE_TAG" > release-notes.txt
|
||||
prerelease=false
|
||||
latest=true
|
||||
if [[ "$RELEASE_TAG" == *-* ]]; then
|
||||
@@ -108,5 +141,5 @@ jobs:
|
||||
latest=false
|
||||
fi
|
||||
gh release create "$RELEASE_TAG" --verify-tag --title "Framely $RELEASE_TAG" --notes-file release-notes.txt --draft --latest=false --prerelease="$prerelease"
|
||||
gh release upload "$RELEASE_TAG" -- *.tar.gz SHA256SUMS bootstrap.py install.sh framely-release.json framely-cef.json
|
||||
gh release upload "$RELEASE_TAG" -- *.tar.gz SHA256SUMS bootstrap.py install.sh framely-release.json framely-cef.json framely-q2f.json
|
||||
gh release edit "$RELEASE_TAG" --draft=false --latest="$latest" --prerelease="$prerelease"
|
||||
@@ -20,3 +20,6 @@
|
||||
/media/bin/
|
||||
|
||||
/media/source/
|
||||
|
||||
# Local agent operating notes
|
||||
/AGENTS.md
|
||||
Generated
+1
-1
@@ -425,7 +425,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "framely"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0-preview.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "framely"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0-preview.1"
|
||||
edition = "2021"
|
||||
license = "AGPL-3.0-only"
|
||||
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@ Prerelease suffixes create GitHub Prereleases without Latest. Installer releases
|
||||
|
||||
Only tags publish. After every product build succeeds, publication creates a draft, uploads assets/checksums, then makes it public. Failed drafts are not stable download targets. Manual runs leave Actions artifacts only.
|
||||
|
||||
Device attachments include the core archive without CEF, the complete `*-offline-linux-arm64.tar.gz` archive, a separate `framely-cef-*` runtime archive, `framely-release.json`, `framely-cef.json`, `bootstrap.py`, `install.sh` and `SHA256SUMS`. The update descriptor always targets the core archive. First installation selects the complete offline archive. CEF is verified and shared under `/home/.framely/cef/<runtime-id>`; missing or newly required runtimes download separately, and previous runtimes remain available for rollback. See [package selection and runtime recovery](user-guide/installation.md#release-packages-and-cef). Installer releases have five platform packages and checksums only. Desktop installers download archive/checksums without user-managed scripts.
|
||||
Device attachments include the core archive without CEF, the complete `*-offline-linux-arm64.tar.gz` archive, a separate `framely-cef-*` runtime archive, an optional `framely-q2f-*` Quest conversion archive, `framely-release.json`, `framely-cef.json`, `framely-q2f.json`, `bootstrap.py`, `install.sh` and `SHA256SUMS`. The update descriptor always targets the core archive. First installation selects the complete offline archive. CEF is verified and shared under `/home/.framely/cef/<runtime-id>`; missing or newly required runtimes download separately, and previous runtimes remain available for rollback. The q2f archive is downloaded only when Quest conversion is chosen; each release pins a verified runtime identity, and already installed APKs are not automatically reconverted. See [package selection and runtime recovery](user-guide/installation.md#release-packages-and-cef). Installer releases have five platform packages and checksums only. Desktop installers download archive/checksums without user-managed scripts.
|
||||
|
||||
External checksums cover downloaded archives; internal checksums cover extracted payload. Neither independently proves author identity. Online installation trusts the chosen repository/HTTPS, local installation the supplied archive/checksums. Redirects never downgrade HTTPS.
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# APK Manager
|
||||
|
||||
In **APK → Apps → Manage**, set **Custom Steam name** for each app. Leave it blank to restore the original app name. The name survives APK updates and is applied to existing and future Steam entries; if Steam is unavailable, it syncs when Steam is ready. This does not rename the app in Framely or change its package, container or saved data.
|
||||
|
||||
Global controller and container lifecycle preferences are under **APK → Settings**, separate from the application list. Per-application display and launch preferences remain in each app’s management dialog.
|
||||
|
||||
[简体中文](../zh-CN/user-guide/apk-manager.md)
|
||||
@@ -89,7 +91,7 @@ Do not invoke Lepton's global cleanup commands as an application-specific uninst
|
||||
|
||||
## Supported formats
|
||||
|
||||
The initial implementation supports individual APKs. Split APK bundles, XAPK/APKM, OBB import, Google Play installation and automatic Steam shortcut creation are outside this version. Unsupported bundles are rejected rather than treated as ordinary APKs.
|
||||
The initial implementation supports individual APKs. Optional Quest conversion downloads and verifies a separate `framely-q2f-*` runtime when selected in the APK install review. It preserves the original APK and reviews the converted, newly signed APK before installation. The runtime and per-package signing keys live in the configured APK storage location and move with it. An existing original APK may reject the new signature; Framely will not silently uninstall it or erase saves. Updating q2f does not automatically reconvert installed games. Games can continue downloading their own OBB data into persistent container storage. Split APK bundles, XAPK/APKM, manual OBB import, Google Play installation and automatic Steam shortcut creation are outside this version. Unsupported bundles are rejected rather than treated as ordinary APKs.
|
||||
|
||||
### Flat window orientation
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ Both services should be `active`. Open SteamVR Dashboard and find Framely in the
|
||||
|
||||
## Update and rollback
|
||||
|
||||
When an update source is configured, choose **Stable** or **Testing** in **About → Framely update**, then check, download and confirm installation. Stable checks stable releases only; Testing checks prereleases such as Preview, Beta and RC. The channel preference persists on the device. Switching channels clears the previous candidate and download, so check and download again before installation. Alternatively, use the desktop installer or run on Frame:
|
||||
When an update source is configured, choose **Stable** or **Testing** in **About → Framely update**, then check, download and confirm installation. Stable checks stable releases only; Testing checks both stable releases and prereleases such as Preview, Beta and RC, then selects the newest version. The channel preference persists on the device. Switching channels clears the previous candidate and download, so check and download again before installation. Alternatively, use the desktop installer or run on Frame:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/SteamFramelyHomebrew/framely/main/install.sh | bash -s -- update --version v0.4.2-preview.3
|
||||
|
||||
@@ -42,7 +42,7 @@ framely call system.source.save '{"source":{"url":"https://example.org/framely-r
|
||||
|
||||
每次构建生成不含 CEF 的本体包 `framely-<版本及构建号>-linux-arm64.tar.gz`、完整离线包 `framely-<版本及构建号>-offline-linux-arm64.tar.gz`、独立运行库 `framely-cef-<运行库标识>-linux-arm64.tar.gz`。更新清单 `framely-release.json` 固定指向不含 CEF 的本体包;首次安装固定选择完整离线包。`framely-cef.json` 提供独立 CEF 的 HTTPS 下载地址、大小及 SHA256。
|
||||
|
||||
CEF 按内容哈希保存在 `/home/.framely/cef/<运行库标识>`,更新时复用;旧安装中相同的运行库自动迁移。所需运行库缺失或 CEF 版本更换时单独下载并校验,各发行的运行库保留用于回滚。完整包可离线提供 CEF。参见[发行包与运行库恢复](user-guide/installation.md#发行包与-cef)。
|
||||
CEF 按内容哈希保存在 `/home/.framely/cef/<运行库标识>`,更新时复用;旧安装中相同的运行库自动迁移。所需运行库缺失或 CEF 版本更换时单独下载并校验,各发行的运行库保留用于回滚。完整包可离线提供 CEF。参见[发行包与运行库恢复](user-guide/installation.md#发行包与-cef)。可选的 Quest 转换工具另打 `framely-q2f-*` 包,发行包声明经过验证的确切版本;只有用户选择 Quest 转换时才校验缓存并按需下载,Framely 本体更新不自动重转已安装 APK。
|
||||
|
||||
## GitHub Actions 发布
|
||||
|
||||
@@ -71,7 +71,7 @@ git push origin installer-v0.4.1-preview.10
|
||||
|
||||
只有标签触发会发布。各工作流在自己的构建全部成功后创建草稿 Release,上传本产品产物及外部 `SHA256SUMS`,最后公开草稿。Framely Release 额外包含 `bootstrap.py`、入口脚本和更新清单;安装器 Release 只包含五个平台的安装器包和校验文件。失败的草稿不作为最新稳定版提供下载。手动触发用于验证,仅保留 Actions artifacts。
|
||||
|
||||
Framely 本体 Release 附件用途:`framely-*-linux-arm64.tar.gz` 为不含 CEF 的更新包,`framely-*-offline-linux-arm64.tar.gz` 为首次安装用的完整离线包,`framely-cef-*` 为独立运行库,`framely-cef.json` 提供运行库下载信息;`framely-release.json` 为内置更新功能的版本清单;`install.sh` 是命令行入口,调用 `bootstrap.py` 完成下载、校验和维护;`SHA256SUMS` 为附件校验清单。桌面安装器只需自动下载运行包和校验清单,用户无需手动下载脚本。安装器的五个平台包发布在独立的安装器 Release 中。
|
||||
Framely 本体 Release 附件用途:`framely-*-linux-arm64.tar.gz` 为不含 CEF 的更新包,`framely-*-offline-linux-arm64.tar.gz` 为首次安装用的完整离线包,`framely-cef-*` 为独立运行库,`framely-cef.json` 提供运行库下载信息;`framely-q2f-*` 为可选 Quest 转换工具包,`framely-q2f.json` 提供下载信息;`framely-release.json` 为内置更新功能的版本清单;`install.sh` 是命令行入口,调用 `bootstrap.py` 完成下载、校验和维护;`SHA256SUMS` 为附件校验清单。桌面安装器只需自动下载运行包和校验清单,用户无需手动下载脚本。安装器的五个平台包发布在独立的安装器 Release 中。
|
||||
|
||||
外部 `SHA256SUMS` 包含压缩包哈希,校验传输内容;包内同名文件校验解压后的载荷。哈希不能独立证明作者身份,在线安装依赖指定 GitHub 仓库与 HTTPS;本地安装依赖用户提供的可信包与校验文件。下载遵循 HTTPS 重定向,不允许降级。
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# APK 管理
|
||||
|
||||
在 **APK → 应用 → 管理** 中,可以为每个应用设置 **自定义 Steam 名称**。留空恢复应用原名;更新 APK 后保留,并应用于已有和以后创建的 Steam 入口。Steam 暂不可用时,会在就绪后同步。此设置不改变 Framely 中的应用名称、包名、容器或存档。
|
||||
|
||||
全局手柄与容器生命周期选项位于 **APK → 设置**,不再占用应用列表。每个应用的显示与启动选项仍保留在对应应用的管理弹窗内。
|
||||
|
||||
[English](../../user-guide/apk-manager.md)
|
||||
@@ -26,6 +28,8 @@ APK 管理用于安装和管理 Steam Frame 上的 Lepton 侧载应用,本地
|
||||
|
||||
点击“安装 APK”,选择单个 `.apk`,核对名称、包名、版本、最低 Android SDK 和目标容器。在 Frame 内选择本机 APK 会直接在设备上校验,不经过浏览器上传;确认阶段保留独立本机副本,不修改原文件。网络上传暂存于 Frame 持久化文件系统,避免占满较小的 `/tmp`。上传显示真实字节进度;后续显示处理阶段,不使用假百分比。
|
||||
|
||||
Quest 游戏可在安装审核中点击“转换此 APK”。Framely 首次使用时按发行包声明的标识下载独立的 `framely-q2f-*` 工具包,校验完整归档和内部文件,之后复用已验证缓存;普通 APK 安装无需下载。转换调用 OVR Port,原始 APK 不修改,转换结果重新读取并再次审核后才安装。转换会重新签名;原版 APK 已安装时可能出现签名不匹配,Framely 不会自动卸载应用或清除存档。工具包和每个包名的签名密钥保存在配置的 APK 存储目录,随该目录迁移;转换临时文件也使用该位置,不使用 `/tmp`。工具包更新只影响之后发起的转换,不自动重新转换已安装游戏。转换结果能否在 Frame 运行仍取决于游戏。
|
||||
|
||||
在 Frame 内,两个管理面板的文件选择入口统一使用 Framely 内置文件选择器,包括 APK、插件包和语言文件。默认打开下载目录,记住上次选择的目录;左侧为按需加载的文件夹树,覆盖主目录、临时目录和已挂载存储,支持逐级展开、收起和当前路径定位,提供目录导航、手动输入路径、搜索、隐藏文件和文件类型筛选。选中文件后确认;B/Escape 只取消选择器,不关闭管理面板。外部浏览器继续使用系统文件选择器。启动台右侧的“安装APK”按钮打开 APK 管理面板。
|
||||
|
||||
共享容器中的 APK 使用各自独立的 Android 安装目录。容器重启会保留 Android 外部存储中的已下载资源,包括未完成的下载片段和更新进度记录。无法识别的 Lepton 存储初始化脚本会在执行前拒绝,避免丢弃文件;游戏是否继续下载仍由自身更新器决定。旧版单 APK 挂载会在保存的安装包可用时恢复,旧 OBB 资源链接会在替换安装前迁移,并保留原目标。这只能防止后续丢失,旧版启动流程已经删除的下载资源无法仅靠 APK 还原。
|
||||
@@ -95,7 +99,7 @@ Android 清除已卸载包的保留状态时可能需要原签名 APK。Framely
|
||||
|
||||
## 格式范围
|
||||
|
||||
首版支持单个 APK。不包含分包、XAPK/APKM、OBB 导入、Google Play 安装及自动创建 Steam 快捷方式;不支持的包格式会明确拒绝。
|
||||
首版支持单个 APK。Quest 兼容转换同样只接受单个 APK;游戏自行下载的 OBB 资源继续使用持久化容器存储。不包含分包、XAPK/APKM、手动 OBB 导入、Google Play 安装及自动创建 Steam 快捷方式;不支持的包格式会明确拒绝。
|
||||
|
||||
### 平面窗口方向
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ sudo /var/lib/framely/current/bin/framely status
|
||||
|
||||
## 更新与回滚
|
||||
|
||||
已配置更新服务时,在“关于 → Framely 更新”选择“正式版”或“测试版”,再检查、下载并确认安装。正式版只检查正式 Release,测试版只检查 Preview、Beta、RC 等预发布版本;渠道选择保存在设备上。切换渠道会清除原候选版本和已下载包,需要重新检查和下载。也可以用桌面安装器,或在 Frame 执行:
|
||||
已配置更新服务时,在“关于 → Framely 更新”选择“正式版”或“测试版”,再检查、下载并确认安装。正式版只检查正式 Release;测试版同时检查正式版和 Preview、Beta、RC 等预发布版本,并选择最新版本。渠道选择保存在设备上。切换渠道会清除原候选版本和已下载包,需要重新检查和下载。也可以用桌面安装器,或在 Frame 执行:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/SteamFramelyHomebrew/framely/main/install.sh | bash -s -- update --version v0.4.2-preview.3
|
||||
|
||||
+71
-6
@@ -108,6 +108,7 @@ static bool menu_open=false,keyboard_open=false,keyboard_close_pending=false;
|
||||
static float notification_curve_radius=1.3f;
|
||||
static bool keyboard_toolbar=false,keyboard_chars=false,keyboard_done=false;
|
||||
static MenuButtonInput menu_button;
|
||||
static std::map<unsigned,uint64_t> menu_previous_buttons;
|
||||
static cef_frame_t* keyboard_frame=nullptr;
|
||||
static std::string keyboard_view;
|
||||
static KeyboardMenuGuard keyboard_menu;
|
||||
@@ -133,6 +134,7 @@ struct View {
|
||||
vr::VROverlayHandle_t overlay=0,thumbnail=0;GLuint textures[2]{};int texture_slot=0;bool texture_ready[2]{};PaintDamage texture_damage[2];std::vector<uint8_t> pixels;
|
||||
};
|
||||
static std::map<std::string,std::unique_ptr<View>> views;
|
||||
static bool permission_trigger_held[2]{};
|
||||
static View* find_browser(cef_browser_t* b){int id=b->get_identifier(b);for(auto& [key,v]:views)if(v->browser_id==id)return v.get();return nullptr;}
|
||||
static Handler<cef_client_t> client;
|
||||
static Handler<cef_render_handler_t> render_handler;
|
||||
@@ -268,8 +270,25 @@ static bool keyboard_event(const vr::VREvent_t& e,vr::VROverlayHandle_t source_o
|
||||
}else {keyboard_done=keyboard_done||e.eventType==vr::VREvent_KeyboardDone;keyboard_close_pending=true;}
|
||||
return true;
|
||||
}
|
||||
static void close_view(View& v){if(v.closing)return;if(v.key.rfind("framely.cast.",0)==0){std::lock_guard<std::mutex> lock(visibility_mutex);closed_casts.push_back(v.key.substr(13));}cancel_file_dialog(v);if(keyboard_view==v.key)close_keyboard();v.closing=true;if(v.key=="menu")overlays->SetOverlayFlag(v.overlay,vr::VROverlayFlags_WantsModalBehavior,false);overlays->ClearOverlayCursorPositionOverride(v.overlay);overlays->HideOverlay(v.overlay);v.host->close_browser(v.host,1);}
|
||||
static void close_view(View& v){if(v.closing)return;if(v.key.rfind("framely.cast.",0)==0){std::lock_guard<std::mutex> lock(visibility_mutex);closed_casts.push_back(v.key.substr(13));}cancel_file_dialog(v);if(keyboard_view==v.key)close_keyboard();v.closing=true;if(v.key=="menu"||v.key=="framely.apk.permission")overlays->SetOverlayFlag(v.overlay,vr::VROverlayFlags_WantsModalBehavior,false);overlays->ClearOverlayCursorPositionOverride(v.overlay);overlays->HideOverlay(v.overlay);v.host->close_browser(v.host,1);}
|
||||
static void anchor_to_head(View& v,float width,float x=0,float y=0,float z=-1.35f){vr::TrackedDevicePose_t poses[vr::k_unMaxTrackedDeviceCount]{};vr_system->GetDeviceToAbsoluteTrackingPose(vr::TrackingUniverseStanding,0,poses,vr::k_unMaxTrackedDeviceCount);if(!poses[0].bPoseIsValid)return;auto m=poses[0].mDeviceToAbsoluteTracking;for(int r=0;r<3;r++)m.m[r][3]+=m.m[r][0]*x+m.m[r][1]*y+m.m[r][2]*z;overlays->SetOverlayWidthInMeters(v.overlay,width);overlays->SetOverlayTransformAbsolute(v.overlay,vr::TrackingUniverseStanding,&m);}
|
||||
static void anchor_permission(View& v){
|
||||
vr::TrackedDevicePose_t poses[vr::k_unMaxTrackedDeviceCount]{};
|
||||
vr_system->GetDeviceToAbsoluteTrackingPose(vr::TrackingUniverseStanding,0,poses,vr::k_unMaxTrackedDeviceCount);
|
||||
if(!poses[0].bPoseIsValid)return;
|
||||
const auto& head=poses[0].mDeviceToAbsoluteTracking;
|
||||
float fx=head.m[0][2],fz=head.m[2][2],length=std::hypot(fx,fz);
|
||||
if(length<.01f)return;
|
||||
fx/=length;fz/=length;
|
||||
vr::HmdMatrix34_t upright{};
|
||||
upright.m[0][0]=fz;upright.m[1][1]=1;upright.m[2][0]=-fx;
|
||||
upright.m[0][2]=fx;upright.m[2][2]=fz;
|
||||
upright.m[0][3]=head.m[0][3]-.65f*fx;
|
||||
upright.m[1][3]=head.m[1][3];
|
||||
upright.m[2][3]=head.m[2][3]-.65f*fz;
|
||||
overlays->SetOverlayWidthInMeters(v.overlay,.85f);
|
||||
overlays->SetOverlayTransformAbsolute(v.overlay,vr::TrackingUniverseStanding,&upright);
|
||||
}
|
||||
static void anchor_notification(View& v){
|
||||
// Let the compositor follow the HMD's render pose; a captured standing-space
|
||||
// transform leaves the toast behind when the user turns or moves their head.
|
||||
@@ -290,7 +309,13 @@ static View& create_view(const std::string& key,const std::string& title,const s
|
||||
// texture upload and launcher mipmap generation scale with the pixel count.
|
||||
if(views.size()>=34)throw std::runtime_error("Window limit exceeded");auto v=std::make_unique<View>();v->key=key;v->plugin=plugin;v->title=title;v->dashboard=dashboard;v->width=width;v->height=height;v->render_scale=key=="launcher"?1.5f:(key=="framely.manager"||key=="menu"||key=="notifications")?2:1;
|
||||
auto error=dashboard?overlays->CreateDashboardOverlay(key.c_str(),title.c_str(),&v->overlay,&v->thumbnail):overlays->CreateOverlay(key.c_str(),title.c_str(),&v->overlay);if(error)throw std::runtime_error("Overlay creation failed: "+std::to_string(error));
|
||||
overlays->SetOverlayInputMethod(v->overlay,key=="notifications"?vr::VROverlayInputMethod_None:vr::VROverlayInputMethod_Mouse);vr::HmdVector2_t scale{{float(width),float(height)}};overlays->SetOverlayMouseScale(v->overlay,&scale);overlays->SetOverlayFlag(v->overlay,vr::VROverlayFlags_HideLaserIntersection,false);overlays->SetOverlayFlag(v->overlay,vr::VROverlayFlags_SendVRSmoothScrollEvents,true);overlays->SetOverlayFlag(v->overlay,vr::VROverlayFlags_VisibleInDashboard,true);overlays->SetOverlayFlag(v->overlay,vr::VROverlayFlags_MakeOverlaysInteractiveIfVisible,true);overlays->SetOverlayFlag(v->overlay,vr::VROverlayFlags_SortWithNonSceneOverlays,false);overlays->SetOverlaySortOrder(v->overlay,0);
|
||||
overlays->SetOverlayInputMethod(v->overlay,key=="notifications"?vr::VROverlayInputMethod_None:vr::VROverlayInputMethod_Mouse);vr::HmdVector2_t scale{{float(width),float(height)}};overlays->SetOverlayMouseScale(v->overlay,&scale);overlays->SetOverlayFlag(v->overlay,vr::VROverlayFlags_HideLaserIntersection,false);overlays->SetOverlayFlag(v->overlay,vr::VROverlayFlags_SendVRSmoothScrollEvents,true);overlays->SetOverlayFlag(v->overlay,vr::VROverlayFlags_VisibleInDashboard,true);overlays->SetOverlayFlag(v->overlay,vr::VROverlayFlags_MakeOverlaysInteractiveIfVisible,true);overlays->SetOverlayFlag(v->overlay,vr::VROverlayFlags_SortWithNonSceneOverlays,key=="framely.apk.permission");overlays->SetOverlaySortOrder(v->overlay,key=="framely.apk.permission"?100:0);if(key=="framely.apk.permission")overlays->SetOverlayFlag(v->overlay,vr::VROverlayFlags_WantsModalBehavior,true);
|
||||
if(key=="framely.apk.permission"){
|
||||
vr::VROverlayIntersectionMaskPrimitive_t mask{};
|
||||
mask.m_nPrimitiveType=vr::OverlayIntersectionPrimitiveType_Rectangle;
|
||||
mask.m_Primitive.m_Rectangle={0,0,float(width),float(height)};
|
||||
if(auto e=overlays->SetOverlayIntersectionMask(v->overlay,&mask,1))std::cerr<<"Permission input mask failed "<<e<<"\n";
|
||||
}
|
||||
|
||||
// Keep the runtime's full dashboard controls, including its keyboard and close buttons.
|
||||
if(dashboard){
|
||||
@@ -532,6 +557,32 @@ static void entry_actions(vr::VROverlayHandle_t button,bool available){
|
||||
}
|
||||
if(kind==0&&!active)entry_analog[hand].held=false;
|
||||
if(kind==0&&active)gaze_buttons[hand]|=down;
|
||||
if(kind==0){
|
||||
auto permission=views.find("framely.apk.permission");
|
||||
if(permission!=views.end()&&!permission->second->closing&&permission->second->shown&&pose_ok){
|
||||
auto& view=*permission->second;
|
||||
const auto& m=pose.pose.mDeviceToAbsoluteTracking;
|
||||
vr::VROverlayIntersectionParams_t ray{};ray.eOrigin=vr::TrackingUniverseStanding;
|
||||
for(int row=0;row<3;row++){ray.vSource.v[row]=m.m[row][3];ray.vDirection.v[row]=-m.m[row][2];}
|
||||
vr::VROverlayIntersectionResults_t point{};
|
||||
if(overlays->ComputeOverlayIntersection(view.overlay,&ray,&point)&&point.vUVs.v[0]>=0&&point.vUVs.v[0]<=1&&point.vUVs.v[1]>=0&&point.vUVs.v[1]<=1){
|
||||
cef_mouse_event_t mouse{};
|
||||
mouse.x=std::clamp(int(point.vUVs.v[0]*view.width),0,view.width-1);
|
||||
mouse.y=std::clamp(int((1-point.vUVs.v[1])*view.height),0,view.height-1);
|
||||
if(!overlays->IsHoverTargetOverlay(view.overlay)){
|
||||
view.host->send_mouse_move_event(view.host,&mouse,0);
|
||||
if(active&&down&&!permission_trigger_held[hand]){
|
||||
view.host->set_focus(view.host,1);
|
||||
mouse.modifiers=EVENTFLAG_LEFT_MOUSE_BUTTON;
|
||||
view.host->send_mouse_click_event(view.host,&mouse,MBT_LEFT,0,1);
|
||||
mouse.modifiers=0;
|
||||
view.host->send_mouse_click_event(view.host,&mouse,MBT_LEFT,1,1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
permission_trigger_held[hand]=active&&down;
|
||||
}
|
||||
bool was_held=entry_buttons[hand][kind].held;
|
||||
entry_buttons[hand][kind].update(active,down,hit,now);
|
||||
if(!(gaze_allowed&&gaze_active)&&kind==0&&active&&down&&!was_held&&launcher_open&&!launcher_calibrating&&!hit&&!launcher_dock_interaction()&&launcher_dismiss.allows(now,true)&&views.count("launcher")&&!overlays->IsHoverTargetOverlay(views.at("launcher")->overlay))launcher_outside_at=now+std::chrono::milliseconds(60);
|
||||
@@ -552,9 +603,9 @@ static void entry_actions(vr::VROverlayHandle_t button,bool available){
|
||||
if(gaze_allowed&&gaze_active)launcher_outside_at={};
|
||||
if(launcher_open&&launcher_outside_at.time_since_epoch().count()&&now>=launcher_outside_at){launcher_outside_at={};if(!keyboard_open&&!launcher_dock_interaction())launcher_back();}
|
||||
}
|
||||
static void commands(){std::deque<json> commands;{std::lock_guard<std::mutex> lock(queue_mutex);commands.swap(queue);}for(const auto& c:commands){try{auto kind=c.value("kind","");if(kind=="feedback.settings"){ui_haptics=c.value("haptics",true);ui_sounds=c.value("sounds",false);if(!ui_sounds)ui_audio.silence();}else if(kind=="file.dialog.complete"){for(auto& [key,view]:views){auto& v=*view;if(!v.file_dialog||v.file_dialog_id!=c.value("id",std::string{}))continue;auto paths=c.value("paths",json::array());if(paths.empty()){cancel_file_dialog(v);break;}if((!v.file_multiple&&paths.size()!=1)||paths.size()>64)break;auto* callback=v.file_dialog;v.file_dialog=nullptr;v.file_dialog_id.clear();auto list=cef_string_list_alloc();for(const auto& path:paths){cef_string_t value{};str(value,path.get<std::string>());cef_string_list_append(list,&value);cef_string_utf16_clear(&value);}callback->cont(callback,list);cef_string_list_free(list);callback->base.release(&callback->base);break;}}else if(kind=="gaze.correction"){gaze_correction=c.value("calibration",json(nullptr));}else if(kind=="gaze.target"){gaze_target_id=c.value("id",std::string{});gaze_target_u=c.value("x",.5f);gaze_target_v=1-c.value("y",.5f);gaze_preview=c.value("preview",json(nullptr));gaze_target_cached=false;}else if(kind=="launcher.calibrate"){gaze_target_id.clear();gaze_target_cached=false;gaze_preview=nullptr;launcher_calibrating=c.value("active",true);if(launcher_calibrating&&!launcher_open){if(!views.count("launcher"))create_view("launcher","Framely launcher",origin+"/launcher#calibrate",true,1440,800);toggle_entry(true);}if(views.count("launcher")){auto& v=*views.at("launcher");auto* frame=v.browser->get_main_frame(v.browser);execute(frame,std::string("location.hash=")+(launcher_calibrating?"'#calibrate'":"''")+";window.dispatchEvent(new Event('hashchange'))");frame->base.release(&frame->base);}}else if(kind=="launcher.close"){if(c.contains("launcherSession")&&!c["launcherSession"].is_null()&&c["launcherSession"]!=launcher_session)continue;bool handoff=c.value("handoff",false);hide_launcher(!handoff,handoff);}else if(kind=="menu.open"){hide_launcher(false);auto& menu=create_view("menu","Framely",origin+"/",false,600,840);navigate(menu,"#plugin:"+c.at("plugin").get<std::string>());menu_open=true;launcher_open=false;menu_button.opened(std::chrono::steady_clock::now());}else if(kind=="haptic"){auto key=c.value("view","");if(views.count(key)&&views.at(key)->shown&&!views.at(key)->closing){auto& view=*views.at(key);bool activation=c.value("feedback","hover")=="activate";if(activation&&key=="launcher"&&gaze_active&&launcher_gaze_allowed()){auto now=std::chrono::steady_clock::now();if(now-view.activation_at>=std::chrono::milliseconds(80)){view.activation_at=now;if(ui_sounds)ui_audio.play(true);}}else hover_haptic(view.overlay,activation?view.activation_at:view.haptic_at,activation);}}else if(kind=="manager.open"){hide_launcher(false);if(views.count("framely.manager")&&views.at("framely.manager")->closing){std::lock_guard<std::mutex> lock(queue_mutex);queue.push_back(c);continue;}auto page=c.value("page",std::string{});auto& manager=create_view("framely.manager","Framely",origin+"/manager"+((manager_navigation_page(page)||page.rfind("plugin:",0)==0)?"#"+page:""),true,1440,810);if(page.rfind("plugin:",0)==0)navigate(manager,"#"+page);if(manager_navigation_page(page)){auto* frame=manager.browser->get_main_frame(manager.browser);execute(frame,"location.hash="+json(page).dump()+";window.dispatchEvent(new Event(\"hashchange\"))");frame->base.release(&frame->base);}menu_open=false;launcher_open=false;}else if(kind=="agreement.decline"){auto key=c.value("view","");if(key=="menu"){menu_open=false;if(views.count("menu")){show(*views.at("menu"),false);views.at("menu")->browser->reload(views.at("menu")->browser);}}else if(views.count(key))close_view(*views.at(key));}else if(kind=="manager.close"){if(views.count("framely.manager"))close_view(*views.at("framely.manager"));}else if(kind=="menu.close"){menu_open=false;}else if(kind=="cast.window"){auto id=c.at("id").get<std::string>();auto key="framely.cast."+id;if(views.count(key)&&views.at(key)->closing){std::lock_guard<std::mutex> lock(queue_mutex);queue.push_back(c);continue;}int width=c.value("width",640),height=c.value("height",240);if(width<160||width>1920||height<112||height>8192)continue;auto& v=create_view(key,"Framely casting",origin+"/cast/window/"+id,false,width,height,"",2.f);v.cast_frame.path=c.at("frame").get<std::string>();if(v.width!=width||v.height!=height){v.width=width;v.height=height;v.pixels.clear();v.texture_ready[0]=v.texture_ready[1]=false;v.host->was_resized(v.host);vr::HmdVector2_t scale{{float(width),float(height)}};overlays->SetOverlayMouseScale(v.overlay,&scale);}menu_open=false;launcher_open=false;}else if(kind=="cast.close"){auto key="framely.cast."+c.at("id").get<std::string>();if(views.count(key))close_view(*views.at(key));}else if(kind=="window.open"){hide_launcher(false);std::string plugLine truncated
|
||||
static void commands(){std::deque<json> commands;{std::lock_guard<std::mutex> lock(queue_mutex);commands.swap(queue);}for(const auto& c:commands){try{auto kind=c.value("kind","");if(kind=="feedback.settings"){ui_haptics=c.value("haptics",true);ui_sounds=c.value("sounds",false);if(!ui_sounds)ui_audio.silence();}else if(kind=="file.dialog.complete"){for(auto& [key,view]:views){auto& v=*view;if(!v.file_dialog||v.file_dialog_id!=c.value("id",std::string{}))continue;auto paths=c.value("paths",json::array());if(paths.empty()){cancel_file_dialog(v);break;}if((!v.file_multiple&&paths.size()!=1)||paths.size()>64)break;auto* callback=v.file_dialog;v.file_dialog=nullptr;v.file_dialog_id.clear();auto list=cef_string_list_alloc();for(const auto& path:paths){cef_string_t value{};str(value,path.get<std::string>());cef_string_list_append(list,&value);cef_string_utf16_clear(&value);}callback->cont(callback,list);cef_string_list_free(list);callback->base.release(&callback->base);break;}}else if(kind=="gaze.correction"){gaze_correction=c.value("calibration",json(nullptr));}else if(kind=="gaze.target"){gaze_target_id=c.value("id",std::string{});gaze_target_u=c.value("x",.5f);gaze_target_v=1-c.value("y",.5f);gaze_preview=c.value("preview",json(nullptr));gaze_target_cached=false;}else if(kind=="launcher.calibrate"){gaze_target_id.clear();gaze_target_cached=false;gaze_preview=nullptr;launcher_calibrating=c.value("active",true);if(launcher_calibrating&&!launcher_open){if(!views.count("launcher"))create_view("launcher","Framely launcher",origin+"/launcher#calibrate",true,1440,800);toggle_entry(true);}if(views.count("launcher")){auto& v=*views.at("launcher");auto* frame=v.browser->get_main_frame(v.browser);execute(frame,std::string("location.hash=")+(launcher_calibrating?"'#calibrate'":"''")+";window.dispatchEvent(new Event('hashchange'))");frame->base.release(&frame->base);}}else if(kind=="launcher.close"){if(c.contains("launcherSession")&&!c["launcherSession"].is_null()&&c["launcherSession"]!=launcher_session)continue;bool handoff=c.value("handoff",false);hide_launcher(!handoff,handoff);}else if(kind=="menu.open"){hide_launcher(false);auto& menu=create_view("menu","Framely",origin+"/",false,600,840);navigate(menu,"#plugin:"+c.at("plugin").get<std::string>());menu_open=true;launcher_open=false;menu_button.opened(std::chrono::steady_clock::now());}else if(kind=="haptic"){auto key=c.value("view","");if(views.count(key)&&views.at(key)->shown&&!views.at(key)->closing){auto& view=*views.at(key);bool activation=c.value("feedback","hover")=="activate";if(activation&&key=="launcher"&&gaze_active&&launcher_gaze_allowed()){auto now=std::chrono::steady_clock::now();if(now-view.activation_at>=std::chrono::milliseconds(80)){view.activation_at=now;if(ui_sounds)ui_audio.play(true);}}else hover_haptic(view.overlay,activation?view.activation_at:view.haptic_at,activation);}}else if(kind=="manager.open"){hide_launcher(false);if(views.count("framely.manager")&&views.at("framely.manager")->closing){std::lock_guard<std::mutex> lock(queue_mutex);queue.push_back(c);continue;}auto page=c.value("page",std::string{});auto& manager=create_view("framely.manager","Framely",origin+"/manager"+((manager_navigation_page(page)||page.rfind("plugin:",0)==0)?"#"+page:""),true,1440,810);if(page.rfind("plugin:",0)==0)navigate(manager,"#"+page);if(manager_navigation_page(page)){auto* frame=manager.browser->get_main_frame(manager.browser);execute(frame,"location.hash="+json(page).dump()+";window.dispatchEvent(new Event(\"hashchange\"))");frame->base.release(&frame->base);}menu_open=false;launcher_open=false;}else if(kind=="agreement.decline"){auto key=c.value("view","");if(key=="menu"){menu_open=false;if(views.count("menu")){show(*views.at("menu"),false);views.at("menu")->browser->reload(views.at("menu")->browser);}}else if(views.count(key))close_view(*views.at(key));}else if(kind=="manager.close"){if(views.count("framely.manager"))close_view(*views.at("framely.manager"));}else if(kind=="menu.close"){menu_open=false;}else if(kind=="apk.permission.open"){auto key="framely.apk.permission";if(views.count(key)&&views.at(key)->closing){std::lock_guard<std::mutex> lock(queue_mutex);queue.push_back(c);continue;}auto& v=create_view(key,"Android permission",origin+"/apk/permission",false,1000,560,"",.85f);anchor_permission(v);}else if(kind=="apk.permission.close"){if(views.count("framely.apk.permission"))close_view(*views.at("framely.apk.permission"));}else if(kind=="cast.window"){auto id=c.at("id").get<std::string>();auto key="framely.cast."+id;if(views.count(key)&&views.at(key)->closing){std::lock_guard<std::mutex> lock(queue_mutex);queue.push_back(c);continue;}int width=c.value("width",640),height=c.value("height",240);if(width<160||width>1920||height<112||height>8192)continue;auto& v=create_view(key,"Framely casting",origin+"/cast/window/"+id,false,width,height,"",2.f);v.cast_frame.path=c.at("frame").get<std::string>();if(v.width!=width||v.height!=height){v.width=width;v.heighLine truncated
|
||||
}
|
||||
static void overlay_input(View& v,const vr::VREvent_t& e){if(v.closing)return;if((v.key=="notifications"||v.key=="launcher"||v.key=="menu")&&!v.shown&&e.eventType!=vr::VREvent_OverlayClosed)return;if(v.key=="launcher"&&!launcher_open&&e.eventType!=vr::VREvent_OverlayClosed)return;if(v.key=="launcher"&&!launcher_accepts(e)&&(e.eventType==vr::VREvent_Modal_Cancel||e.eventType==vr::VREvent_ButtonPress||e.eventType==vr::VREvent_MouseButtonDown||e.eventType==vr::VREvent_MouseButtonUp))return;if(keyboard_event(e,v.overlay))return;laser_cursor(v.overlay,e);cef_mouse_event_t mouse{};mouse.x=int(e.data.mouse.x);mouse.y=v.height-int(e.data.mouse.y);if(e.eventType==vr::VREvent_MouseMove||e.eventType==vr::VREvent_MouseButtonDown||e.eventType==vr::VREvent_MouseButtonUp){v.pointer=mouse;v.pointer_valid=true;v.pointer_device=e.trackedDeviceIndex;v.pointer_at=std::chrono::steady_clock::now();}switch(e.eventType){case vr::VREvent_Modal_Cancel:if(v.key=="launcher"&&!keyboard_open&&!gaze_active&&!launcher_dock_interaction()&&!overlays->IsHoverTargetOverlay(v.overlay))launcher_back();else if(v.key=="menu"&&!keyboard_open&&!keyboard_menu.holds(std::chrono::steady_clock::now())&&menu_button.can_cancel(std::chrono::steady_clock::now())){menu_open=false;std::cout<<"Menu closed: outside click"<<std::endl;}break;case vr::VREvent_OverlayClosed:if(v.key=="launcher")hide_launcher();else if(v.key!="menu"&&v.key!="notifications")close_view(v);break;case vr::VREvent_ButtonPress:if(e.data.controller.button==vr::k_EButton_ApplicationMenu){if(v.key=="launcher"){launcher_back();break;}auto* frame=v.browser->get_main_frame(v.browser);execute(frame,"window.dispatchEvent(new Event('framely.back'))");frame->base.release(&frame->base);}break;case vr::VREvent_FocusLeave:if(v.key=="launcher"&&v.launcher_pointer.holding(std::chrono::steady_clock::now()))break;if(v.key!="notifications"||!v.notification_click.active)v.host->send_mouse_move_event(v.host,&mouse,1);break;case vr::VREvent_MouseMove:if(v.key=="launcher")v.launcher_pointer.constrain(mouse.x,mouse.y,std::chrono::steady_clock::now());if(v.key!="notifications"||!v.notification_click.hold(mouse.x,mouse.y,std::chrono::steady_clock::now()))v.host->send_mouse_move_event(v.host,&mouse,0);break;case vr::VREvent_MouseButtonDown:case vr::VREvent_MouseButtonUp:{v.host->set_focus(v.host,1);auto button=e.data.mouse.button==vr::VRMouseButton_Right?MBT_RIGHT:MBT_LEFT;if(v.key=="launcher"&&button==MBT_LEFT){auto now=std::chrono::steady_clock::now();if(e.eventType==vr::VREvent_MouseButtonDown)v.launcher_pointer.begin(mouse.x,mouse.y,now);else{v.launcher_pointer.constrain(mouse.x,mouse.y,now);v.launcher_pointer.clear();}}if(v.key=="notifications"&&button==MBT_LEFT){auto now=std::chrono::steady_clock::now();if(e.eventType==vr::VREvent_MouseButtonDown)v.notification_click.begin(mouse.x,mouse.y,now);else v.notification_click.release(mouse.x,mouse.y,now);}mouse.modifiers=e.eventType==vr::VREvent_MouseButtonDown?EVENTFLAG_LEFT_MOUSE_BUTTON:0;v.host->send_mouse_click_event(v.host,&mouse,button,e.eventType==vr::VREvent_MouseButtonUp,1);break;}case vr::VREvent_ScrollSmooth:case vr::VREvent_ScrollDiscrete:if(v.stick_scrolling||keyboard_open||!v.pointer_valid)break;mouse=v.pointer;mouse.modifiers=0;v.host->send_mouse_wheel_event(v.host,&mouse,int(e.data.scroll.xdelta*120),int(e.data.scroll.ydelta*120));break;case vr::VREvent_OverlayGamepadFocusLost:if(!keyboard_open&&!v.dashboard&&v.key!="menu"&&v.key!="notifications"&&v.key!="launcher"&&v.key.rfind("framely.cast.",0)!=0)close_view(v);break;default:break;}}
|
||||
static void overlay_input(View& v,const vr::VREvent_t& e){if(v.closing)return;if((v.key=="notifications"||v.key=="launcher"||v.key=="menu")&&!v.shown&&e.eventType!=vr::VREvent_OverlayClosed)return;if(v.key=="launcher"&&!launcher_open&&e.eventType!=vr::VREvent_OverlayClosed)return;if(v.key=="launcher"&&!launcher_accepts(e)&&(e.eventType==vr::VREvent_Modal_Cancel||e.eventType==vr::VREvent_ButtonPress||e.eventType==vr::VREvent_MouseButtonDown||e.eventType==vr::VREvent_MouseButtonUp))return;if(keyboard_event(e,v.overlay))return;if(menu_open&&v.key!="menu"&&e.eventType==vr::VREvent_MouseButtonDown&&!keyboard_open&&menu_button.can_cancel(std::chrono::steady_clock::now()))menu_open=false;laser_cursor(v.overlay,e);cef_mouse_event_t mouse{};mouse.x=int(e.data.mouse.x);mouse.y=v.height-int(e.data.mouse.y);if(e.eventType==vr::VREvent_MouseMove||e.eventType==vr::VREvent_MouseButtonDown||e.eventType==vr::VREvent_MouseButtonUp){v.pointer=mouse;v.pointer_valid=true;v.pointer_device=e.trackedDeviceIndex;v.pointer_at=std::chrono::steady_clock::now();}switch(e.eventType){case vr::VREvent_Modal_Cancel:if(v.key=="launcher"&&!keyboard_open&&!gaze_active&&!launcher_dock_interaction()&&!overlays->IsHoverTargetOverlay(v.overlay))launcher_back();else if(v.key=="menu"&&!keyboard_open&&!keyboard_menu.holds(std::chrono::steady_clock::now())&&menu_button.can_cancel(std::chrono::steady_clock::now())){menu_open=false;std::cout<<"Menu closed: outside click"<<std::endl;}break;case vr::VREvent_OverlayClosed:if(v.key=="launcher")hide_launcher();else if(v.key!="menu"&&v.key!="notifications")close_view(v);break;case vr::VREvent_ButtonPress:if(e.data.controller.button==vr::k_EButton_ApplicationMenu){if(v.key=="launcher"){launcher_back();break;}auto* frame=v.browser->get_main_frame(v.browser);execute(frame,"window.dispatchEvent(new Event('framely.back'))");frame->base.release(&frame->base);}break;case vr::VREvent_FocusLeave:if(v.key=="launcher"&&v.launcher_pointer.holding(std::chrono::steady_clock::now()))break;if(v.key!="notifications"||!v.notification_click.active)v.host->send_mouse_move_event(v.host,&mouse,1);break;case vr::VREvent_MouseMove:if(v.key=="launcher")v.launcher_pointer.constrain(mouse.x,mouse.y,std::chrono::steady_clock::now());if(v.key!="notifications"||!v.notification_click.hold(mouse.x,mouse.y,std::chrono::steady_clock::now()))v.host->send_mouse_move_event(v.host,&mouse,0);break;case vr::VREvent_MouseButtonDown:case vr::VREvent_MouseButtonUp:{v.host->set_focus(v.host,1);auto button=e.data.mouse.button==vr::VRMouseButton_Right?MBT_RIGHT:MBT_LEFT;if(v.key=="launcher"&&button==MBT_LEFT){auto now=std::chrono::steady_clock::now();if(e.eventType==vr::VREvent_MouseButtonDown)v.launcher_pointer.begin(mouse.x,mouse.y,now);else{v.launcher_pointer.constrain(mouse.x,mouse.y,now);v.launcher_pointer.clear();}}if(v.key=="notifications"&&button==MBT_LEFT){auto now=std::chrono::steady_clock::now();if(e.eventType==vr::VREvent_MouseButtonDown)v.notification_click.begin(mouse.x,mouse.y,now);else v.notification_click.release(mouse.x,mouse.y,now);}mouse.modifiers=e.eventType==vr::VREvent_MouseButtonDown?EVENTFLAG_LEFT_MOUSE_BUTTON:0;v.host->send_mouse_click_event(v.host,&mouse,button,e.eventType==vr::VREvent_MouseButtonUp,1);break;}case vr::VREvent_ScrollSmooth:case vr::VREvent_ScrollDiscrete:if(v.stick_scrolling||keyboard_open||!v.pointer_valid)break;mouse=v.pointer;mouse.modifiers=0;v.host->send_mouse_wheel_event(v.host,&mouse,int(e.data.scroll.xdelta*120),int(e.data.scroll.ydelta*120));break;case vr::VREvent_OverlayGamepadFocusLost:if(!keyboard_open&&!v.dashboard&&v.key!="menu"&&v.key!="notifications"&&v.key!="launcher"&&v.key.rfind("framely.cast.",0)!=0&&v.key!="framely.apk.permission")close_view(v);break;default:break;}}
|
||||
|
||||
int main(int argc,char** argv){
|
||||
std::cout.setf(std::ios::unitbuf);std::string initial;int port=0;for(int i=1;i+1<argc;i++){std::string s=argv[i];if(s=="--url")initial=argv[++i];else if(s=="--port")port=std::stoi(argv[++i]);else if(s=="--runtime")runtime=argv[++i];}
|
||||
@@ -612,7 +663,7 @@ int main(int argc,char** argv){
|
||||
if(!main_overlay)main_overlay=active_main_window();
|
||||
if(main_overlay&&!overlays->GetOverlayMouseScale(main_overlay,&main_scale)&&!overlays->GetTransformForOverlayCoordinates(main_overlay,vr::TrackingUniverseStanding,{{main_scale.v[0]*.5f,main_scale.v[1]*.5f}},&main_pose))main=&main_pose;
|
||||
if(evidence.radius>0?dock_menu_placement(anchor,size,evidence.radius,evidence.pre_curve_pitch,popup):menu_placement(anchor,size,popup,0,main)){v.placement.apply(overlays,v.overlay,popup.transform,popup.width);v.placement.curve(overlays,v.overlay,popup.width,popup.radius);show(v,menu_open);}else show(v,false);}}else if(!keyboard_menu.holds(now)){if(overlays->IsOverlayVisible(button))overlays->ClearOverlayCursorPositionOverride(button);overlays->HideOverlay(button);if(views.count("menu"))show(*views.at("menu"),false);}
|
||||
if(was_visible&&!visible&&!keyboard_open&&!keyboard_menu.holds(now)){menu_button.pressed=false;menu_open=false;if(!overlays->IsDashboardVisible())hide_launcher(false,true);for(auto&[key,v]:views)if(!v->dashboard&&key!="menu"&&key!="notifications"&&key!="launcher"&&key.rfind("framely.cast.",0)!=0)close_view(*v);}was_visible=visible;
|
||||
if(was_visible&&!visible&&!keyboard_open&&!keyboard_menu.holds(now)){menu_button.pressed=false;menu_open=false;if(!overlays->IsDashboardVisible())hide_launcher(false,true);for(auto&[key,v]:views)if(!v->dashboard&&key!="menu"&&key!="notifications"&&key!="launcher"&&key.rfind("framely.cast.",0)!=0&&key!="framely.apk.permission")close_view(*v);}was_visible=visible;
|
||||
if(launcher_close_at.time_since_epoch().count()&&now>=launcher_close_at){launcher_close_at={};if(!launcher_open)finish_launcher_close();}
|
||||
// The runtime owns dashboard placement, curvature, visibility and switching.
|
||||
// Never move the launcher into standing space or hide another app's overlay.
|
||||
@@ -660,8 +711,22 @@ int main(int argc,char** argv){
|
||||
activate_entry(entry_hold.tick(std::chrono::steady_clock::now(),anchor_ok&&entry_connected,entry_inside));
|
||||
for(auto&[key,v]:views)v->stick_scrolling=false;
|
||||
entry_actions(button,anchor_ok);
|
||||
// Some dashboard runtimes do not emit Modal_Cancel for clicks on their own
|
||||
// overlays. Observe the same controller click edge as a fallback, without
|
||||
// consuming the click destined for the other surface.
|
||||
for(int hand=0;hand<2;hand++){
|
||||
auto device=vr_system->GetTrackedDeviceIndexForControllerRole(hand?vr::TrackedControllerRole_RightHand:vr::TrackedControllerRole_LeftHand);
|
||||
if(device==vr::k_unTrackedDeviceIndexInvalid)continue;
|
||||
vr::VRControllerState_t state{};
|
||||
if(!vr_system->GetControllerState(device,&state,sizeof(state))){menu_previous_buttons.erase(device);continue;}
|
||||
auto previous=menu_previous_buttons.find(device);
|
||||
uint64_t pressed=previous==menu_previous_buttons.end()?0:state.ulButtonPressed&~previous->second;
|
||||
menu_previous_buttons[device]=state.ulButtonPressed;
|
||||
const uint64_t click=vr::ButtonMaskFromId(vr::k_EButton_SteamVR_Trigger)|vr::ButtonMaskFromId(vr::k_EButton_A)|vr::ButtonMaskFromId(vr::k_EButton_DPad_Down);
|
||||
if(menu_open&&!keyboard_open&&menu_button.can_cancel(std::chrono::steady_clock::now())&&(pressed&click)&&views.count("menu")&&!overlays->IsHoverTargetOverlay(views.at("menu")->overlay)&&!overlays->IsHoverTargetOverlay(button))menu_open=false;
|
||||
}
|
||||
if(launcher_open){bool held=false;for(auto& hand:entry_buttons)for(auto& trigger:hand)held|=trigger.held;launcher_dismiss.observe(held);}
|
||||
for(auto&[key,v]:views){if(v->closing)continue;if(v->dashboard){bool active=overlays->IsDashboardVisible()&&overlays->IsActiveDashboardOverlay(v->overlay)&&overlays->IsOverlayVisible(v->overlay);if(active!=v->shown){if(!active&&key=="launcher"){if(v->launcher_pointer.active){cef_mouse_event_t outside{};outside.modifiers=EVENTFLAG_LEFT_MOUSE_BUTTON;v->host->send_mouse_move_event(v->host,&outside,0);outside.modifiers=0;v->host->send_mouse_click_event(v->host,&outside,MBT_LEFT,1,1);}v->launcher_pointer.clear();auto* frame=v->browser->get_main_frame(v->browser);execute(frame,"window.dispatchEvent(new Event('framely.launcher.cancelInput'))");frame->base.release(&frame->base);}v->host->was_hidden(v->host,!active);v->shown=active;}if(!active)v->active_seen=false;if(active&&!v->active_seen){v->active_seen=true;if(key!="launcher")for(auto&[other,t]:views)if(!t->dashboard&&other!="menu"&&other!="notifications"&&other!="launcher"&&other.rfind("framely.cast.",0)!=0&&!keyboard_open)close_view(*t);}}
|
||||
for(auto&[key,v]:views){if(v->closing)continue;if(v->dashboard){bool active=overlays->IsDashboardVisible()&&overlays->IsActiveDashboardOverlay(v->overlay)&&overlays->IsOverlayVisible(v->overlay);if(active!=v->shown){if(!active&&key=="launcher"){if(v->launcher_pointer.active){cef_mouse_event_t outside{};outside.modifiers=EVENTFLAG_LEFT_MOUSE_BUTTON;v->host->send_mouse_move_event(v->host,&outside,0);outside.modifiers=0;v->host->send_mouse_click_event(v->host,&outside,MBT_LEFT,1,1);}v->launcher_pointer.clear();auto* frame=v->browser->get_main_frame(v->browser);execute(frame,"window.dispatchEvent(new Event('framely.launcher.cancelInput'))");frame->base.release(&frame->base);}v->host->was_hidden(v->host,!active);v->shown=active;}if(!active)v->active_seen=false;if(active&&!v->active_seen){v->active_seen=true;if(key!="launcher")for(auto&[other,t]:views)if(!t->dashboard&&other!="menu"&&other!="notifications"&&other!="launcher"&&other.rfind("framely.cast.",0)!=0&&other!="framely.apk.permission"&&!keyboard_open)close_view(*t);}}
|
||||
while(overlays->PollNextOverlayEvent(v->overlay,&event,sizeof(event)))overlay_input(*v,event);
|
||||
if(!v->cast_frame.path.empty()){glXMakeContextCurrent(xdisplay,glsurface,glsurface,glcontext);if(v->cast_frame.update())v->dirty=true;}
|
||||
if(v->dirty&&!v->closing&&v->pixels.size()==size_t(v->width*v->render_scale)*size_t(v->height*v->render_scale)*4){
|
||||
|
||||
@@ -18,6 +18,9 @@ export function installKeyboard(open:(params:{existing:string;password:boolean;m
|
||||
};
|
||||
(window as any).__framelyEditKeyboard=(edit:string)=>{
|
||||
if(!field?.isConnected)return;
|
||||
// Embedded editors can consume the native keyboard without mutating their
|
||||
// hidden textarea. Ordinary inputs continue through the path below.
|
||||
if(!field.dispatchEvent(new CustomEvent('framely.keyboard.edit',{detail:edit,cancelable:true})))return;
|
||||
const value=field.value;
|
||||
let start=field.selectionStart??value.length,end=field.selectionEnd??start;
|
||||
const segments=Array.from(new (Intl as any).Segmenter(undefined,{granularity:'grapheme'}).segment(value)) as {index:number;segment:string}[];
|
||||
|
||||
+62
-2
@@ -24,6 +24,8 @@ mod cleanup;
|
||||
mod graphics;
|
||||
mod lifecycle;
|
||||
mod native;
|
||||
pub(crate) mod permissions;
|
||||
mod q2f;
|
||||
mod steam_bridge;
|
||||
mod steam_shortcuts;
|
||||
pub(crate) mod steam_ui;
|
||||
@@ -49,6 +51,8 @@ pub(crate) static TEST_SERIAL: Mutex<()> = Mutex::new(());
|
||||
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Record {
|
||||
#[serde(default)]
|
||||
steam_name: Option<String>,
|
||||
#[serde(default)]
|
||||
steam_launch: bool,
|
||||
#[serde(default)]
|
||||
@@ -993,7 +997,7 @@ pub fn list(home: &Path) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
Ok(
|
||||
json!({"apps":apps.iter().map(|a| { let mut v=serde_json::to_value(a).unwrap(); v["steamLaunch"]=json!(db.records.get(&a.id).is_none_or(steam_shortcuts::wanted)); v["steamRegistered"]=json!(db.records.get(&a.id).is_some_and(|r|r.steam_launch));v["steamRegistrationError"]=json!(db.records.get(&a.id).and_then(|r|r.steam_registration_error.as_ref())); v }).collect::<Vec<_>>(),"containers":cs.iter().map(|c| { let mut v=serde_json::to_value(c).unwrap(); v["acceptsAdditionalApps"]=json!(false); v }).collect::<Vec<_>>(),"warnings":warnings,"roots":db.roots,"available":runner(home).is_ok(),"retainSteamEntries":db.retain_steam_entries,"gamepadEnabled":db.gamepad_enabled,"gamepadSource":db.gamepad_source,"gamepadRumble":db.gamepad_rumble,"gamepadTriggerThreshold":db.gamepad_trigger_threshold,"autoStopContainer":db.auto_stop_container,"stopContainerOnClose":db.stop_container_on_close}),
|
||||
json!({"apps":apps.iter().map(|a| { let mut v=serde_json::to_value(a).unwrap(); v["steamName"]=json!(db.records.get(&a.id).and_then(|r|r.steam_name.as_ref())); v["steamLaunch"]=json!(db.records.get(&a.id).is_none_or(steam_shortcuts::wanted)); v["steamRegistered"]=json!(db.records.get(&a.id).is_some_and(|r|r.steam_launch));v["steamRegistrationError"]=json!(db.records.get(&a.id).and_then(|r|r.steam_registration_error.as_ref())); v }).collect::<Vec<_>>(),"containers":cs.iter().map(|c| { let mut v=serde_json::to_value(c).unwrap(); v["acceptsAdditionalApps"]=json!(false); v }).collect::<Vec<_>>(),"warnings":warnings,"roots":db.roots,"available":runner(home).is_ok(),"retainSteamEntries":db.retain_steam_entries,"gamepadEnabled":db.gamepad_enabled,"gamepadSource":db.gamepad_source,"gamepadRumble":db.gamepad_rumble,"gamepadTriggerThreshold":db.gamepad_trigger_threshold,"autoStopContainer":db.auto_stop_container,"stopContainerOnClose":db.stop_container_on_close}),
|
||||
)
|
||||
}
|
||||
pub fn storage_status(home: &Path) -> Result<Value> {
|
||||
@@ -2772,6 +2776,17 @@ pub fn reviews_drop(home: &Path, ticket: &str) -> Result<Value> {
|
||||
}
|
||||
Ok(json!(true))
|
||||
}
|
||||
pub fn q2f_convert(
|
||||
home: &Path,
|
||||
ticket: &str,
|
||||
cancel: &Cancellation,
|
||||
progress: impl Fn(Value) -> Result<()>,
|
||||
) -> Result<Value> {
|
||||
q2f::convert(home, ticket, cancel, progress)
|
||||
}
|
||||
pub fn q2f_status(home: &Path) -> Result<Value> {
|
||||
q2f::status(home)
|
||||
}
|
||||
pub fn operate(
|
||||
home: &Path,
|
||||
kind: &str,
|
||||
@@ -2787,7 +2802,7 @@ pub fn operate(
|
||||
}
|
||||
}
|
||||
let result = operate_internal(home, kind, p, cancel, progress, None);
|
||||
if matches!(kind, "install" | "steam.retention.settings") && result.is_ok() {
|
||||
if matches!(kind, "install" | "steam.retention.settings" | "settings") && result.is_ok() {
|
||||
steam_shortcuts::wake_registration();
|
||||
}
|
||||
result
|
||||
@@ -3163,6 +3178,11 @@ progress(json!({"phase":"starting"}));start(home,&c,Some(false),&log)?;
|
||||
);
|
||||
record_app(&mut db, &a);
|
||||
let rec = db.records.get_mut(id).unwrap();
|
||||
let steam_name = p.get("steamName").map(steam_shortcuts::parse_name).transpose()?;
|
||||
if let Some(name) = &steam_name {
|
||||
ensure!(!a.steam, "This app is already managed by Steam");
|
||||
rec.steam_name = name.clone();
|
||||
}
|
||||
if let Some(v) = p.get("activity") {
|
||||
let activity = v.as_str().filter(|s| !s.is_empty());
|
||||
ensure!(
|
||||
@@ -3193,6 +3213,14 @@ progress(json!({"phase":"starting"}));start(home,&c,Some(false),&log)?;
|
||||
rec.orientation = v.as_str().filter(|s| *s != "auto").map(str::to_owned);
|
||||
}
|
||||
cancel.commit(|| save(home, &db))?;
|
||||
if steam_name.is_some() {
|
||||
let rec = db.records.get_mut(id).unwrap();
|
||||
if rec.steam_launch && steam_shortcuts::linked(home, rec) {
|
||||
let result = steam_shortcuts::update_name(home, &a, rec);
|
||||
rec.steam_registration_error = result.err().map(|e| format!("{e:#}"));
|
||||
save(home, &db)?;
|
||||
}
|
||||
}
|
||||
Ok(json!(true))
|
||||
}
|
||||
"launch" | "close" | "uninstall" | "purge" | "clear" => {
|
||||
@@ -4703,6 +4731,38 @@ setup_props
|
||||
})
|
||||
}
|
||||
#[test]
|
||||
fn custom_steam_names_persist_reset_and_preserve_app_identity() {
|
||||
let f = Fixture::new();
|
||||
let id = "test/com.example.app";
|
||||
let before = list(&f.home).unwrap();
|
||||
let original = before["apps"][0]["metadata"]["name"].clone();
|
||||
f.operation("settings", json!({"app":id,"steamName":" 我的游戏 🎮 "})).unwrap();
|
||||
assert_eq!(load(&f.home).unwrap().records[id].steam_name.as_deref(), Some("我的游戏 🎮"));
|
||||
let after = list(&f.home).unwrap();
|
||||
assert_eq!(after["apps"][0]["steamName"], "我的游戏 🎮");
|
||||
assert_eq!(after["apps"][0]["metadata"]["name"], original);
|
||||
for value in [json!(42), json!("bad\nname"), json!("x".repeat(129))] {
|
||||
assert!(f.operation("settings", json!({"app":id,"steamName":value})).is_err());
|
||||
assert_eq!(load(&f.home).unwrap().records[id].steam_name.as_deref(), Some("我的游戏 🎮"));
|
||||
}
|
||||
let mut db = load(&f.home).unwrap();
|
||||
let (a, _) = app(&f.home, &db, id).unwrap();
|
||||
let record = db.records.get_mut(id).unwrap();
|
||||
record.steam_binding = Some(steam_shortcuts::Binding { game_id: steam_shortcuts::game_id(id), native: true, revision: "stale".into() });
|
||||
steam_ui::TEST_RESULT.with(|v| *v.borrow_mut() = Some(json!(true)));
|
||||
steam_shortcuts::update_name(&f.home, &a, record).unwrap();
|
||||
assert_ne!(record.steam_binding.as_ref().unwrap().revision, "stale");
|
||||
let current_revision = record.steam_binding.as_ref().unwrap().revision.clone();
|
||||
record.steam_name = Some("New name".into());
|
||||
steam_ui::TEST_RESULT.with(|v| *v.borrow_mut() = Some(json!(false)));
|
||||
assert!(steam_shortcuts::update_name(&f.home, &a, record).is_err());
|
||||
assert_eq!(record.steam_binding.as_ref().unwrap().revision, current_revision);
|
||||
f.operation("settings", json!({"app":id,"steamName":" "})).unwrap();
|
||||
assert!(load(&f.home).unwrap().records[id].steam_name.is_none());
|
||||
assert!(list(&f.home).unwrap()["apps"][0]["steamName"].is_null());
|
||||
assert_eq!(fs::read_to_string(f.home.join(".local/share/lepton/contexts/test/baked/data_overlay/data/com.example.app/files/save")).unwrap(), "saved progress");
|
||||
}
|
||||
#[test]
|
||||
fn transient_steam_entry_is_launch_only_protects_newer_launch_and_preserves_data() {
|
||||
let f = Fixture::new();
|
||||
list(&f.home).unwrap();
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
//! Mirrors only a pending Android runtime-permission dialog into a VR window.
|
||||
//! The user's click is delivered to Android's own PermissionController, so
|
||||
//! Android retains its one-time/while-in-use/denial semantics and callbacks.
|
||||
use super::*;
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use image::{DynamicImage, ImageFormat};
|
||||
use std::collections::BTreeSet;
|
||||
use std::io::{Cursor, Seek, SeekFrom};
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct Pending {
|
||||
pub id: String,
|
||||
pub app_name: String,
|
||||
pub package: String,
|
||||
runtime: String,
|
||||
instance: String,
|
||||
}
|
||||
|
||||
fn active_permission(runtime: &str) -> Result<bool> {
|
||||
let mut command = crate::process::tool("podman");
|
||||
command.args([
|
||||
"exec", &format!("lepton-{runtime}"), "sh", "-c",
|
||||
"dumpsys activity activities | grep -E 'topResumedActivity=|mResumedActivity:'; printf '\\nFRAMELY_PERMISSION_DONE\\n'",
|
||||
]);
|
||||
let text = output(command, Duration::from_secs(3), None)?;
|
||||
ensure!(text.ends_with("FRAMELY_PERMISSION_DONE\n"), "Incomplete permission probe");
|
||||
Ok(text.lines().any(|line| {
|
||||
(line.contains("topResumedActivity=") || line.contains("mResumedActivity:"))
|
||||
&& line.contains("com.android.permissioncontroller/")
|
||||
&& line.contains("GrantPermissionsActivity")
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn pending(home: &Path) -> Result<Option<Pending>> {
|
||||
let db = load(home)?;
|
||||
let mut command = crate::process::tool("podman");
|
||||
command.args(["ps", "--format", "{{.Names}}"]);
|
||||
let running = output(command, Duration::from_secs(3), None)?;
|
||||
let running: BTreeSet<_> = running.lines().collect();
|
||||
let contexts = containers(home, &db);
|
||||
for record in db.records.values().filter(|r| !r.removed && r.metadata.vr && !r.show_window.unwrap_or(false)) {
|
||||
let Some(base) = contexts.iter().find(|c| c.id == record.context) else { continue };
|
||||
let runtime = native::runtime_name(record).filter(|name| running.contains(format!("lepton-{name}").as_str()))
|
||||
.unwrap_or_else(|| base.name.clone());
|
||||
if !running.contains(format!("lepton-{runtime}").as_str()) { continue; }
|
||||
let mut probe = crate::process::tool("podman");
|
||||
probe.args(["exec", &format!("lepton-{runtime}"), "getprop", "lepton.active_app_id"]);
|
||||
let Ok(package) = output(probe, Duration::from_secs(3), None) else { continue };
|
||||
if package.trim() != record.metadata.package { continue; }
|
||||
if !active_permission(&runtime)? { continue; }
|
||||
let mut inspect = crate::process::tool("podman");
|
||||
inspect.args(["inspect", "--format", "{{.Id}}|{{.State.StartedAt}}|{{.State.Running}}", &format!("lepton-{runtime}")]);
|
||||
let Ok(instance) = output(inspect, Duration::from_secs(3), None) else { continue };
|
||||
let instance = instance.trim().to_owned();
|
||||
if !instance.ends_with("|true") || instance.split('|').count() != 3 { continue; }
|
||||
let id = hash(&format!("{}|{}|{}", runtime, instance, package.trim()));
|
||||
return Ok(Some(Pending {
|
||||
id,
|
||||
app_name: record.metadata.name.clone(),
|
||||
package: package.trim().to_owned(),
|
||||
runtime,
|
||||
instance,
|
||||
}));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn current(home: &Path, id: &str) -> Result<Pending> {
|
||||
let request = pending(home)?.context("Android permission request has ended")?;
|
||||
ensure!(request.id == id, "Android permission request has changed");
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
fn screenshot(runtime: &str) -> Result<Vec<u8>> {
|
||||
let mut file = tempfile::tempfile()?;
|
||||
let mut child = crate::process::tool("podman")
|
||||
.args(["exec", &format!("lepton-{runtime}"), "screencap", "-p"])
|
||||
.stdin(Stdio::null()).stdout(Stdio::from(file.try_clone()?)).stderr(Stdio::null())
|
||||
.spawn()?;
|
||||
let start = Instant::now();
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? { break status; }
|
||||
if start.elapsed() >= Duration::from_secs(3) {
|
||||
let _ = child.kill(); let _ = child.wait();
|
||||
bail!("Android permission capture timed out");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
ensure!(status.success(), "Android permission capture failed");
|
||||
ensure!(file.metadata()?.len() <= 8 * 1024 * 1024, "Android permission capture too large");
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
let mut bytes = Vec::new();
|
||||
file.read_to_end(&mut bytes)?;
|
||||
ensure!(bytes.starts_with(b"\x89PNG\r\n\x1a\n"), "Android permission capture is not PNG");
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn frame(home: &Path, id: &str) -> Result<Value> {
|
||||
let request = current(home, id)?;
|
||||
let image = image::load_from_memory_with_format(&screenshot(&request.runtime)?, ImageFormat::Png)?;
|
||||
let (width, height) = (image.width(), image.height());
|
||||
ensure!((320..=4096).contains(&width) && (240..=4096).contains(&height), "Unexpected Android display size");
|
||||
let crop_width = width * 11 / 20;
|
||||
let crop_height = height * 11 / 20;
|
||||
let left = (width - crop_width) / 2;
|
||||
let top = (height - crop_height) / 2;
|
||||
let cropped = image.crop_imm(left, top, crop_width, crop_height);
|
||||
let mut png = Cursor::new(Vec::new());
|
||||
DynamicImage::ImageRgba8(cropped.into_rgba8()).write_to(&mut png, ImageFormat::Png)?;
|
||||
ensure!(current(home, id)?.instance == request.instance, "Android permission request has changed");
|
||||
Ok(json!({"id":id,"appName":request.app_name,"package":request.package,
|
||||
"image":format!("data:image/png;base64,{}",STANDARD.encode(png.into_inner())),
|
||||
"left":left,"top":top,"width":crop_width,"height":crop_height}))
|
||||
}
|
||||
|
||||
const INPUT: &str = r#"
|
||||
set -eu
|
||||
for entry in $(cat /proc/$(pidof system_server)/environ | tr '\0' '\n' | grep -E '^(ANDROID_(ROOT|DATA|ART_ROOT|I18N_ROOT|TZDATA_ROOT)|BOOTCLASSPATH)='); do
|
||||
export "$entry"
|
||||
done
|
||||
exec input touchscreen tap "$1" "$2"
|
||||
"#;
|
||||
|
||||
pub(crate) fn click(home: &Path, id: &str, x: u32, y: u32) -> Result<Value> {
|
||||
let request = current(home, id)?;
|
||||
ensure!(x < 4096 && y < 4096, "Invalid Android input position");
|
||||
let image = image::load_from_memory_with_format(&screenshot(&request.runtime)?, ImageFormat::Png)?;
|
||||
ensure!(x < image.width() && y < image.height(), "Android input position outside display");
|
||||
ensure!(current(home, id)?.instance == request.instance, "Android permission request has changed");
|
||||
let mut command = crate::process::tool("podman");
|
||||
command.args([
|
||||
"exec", &format!("lepton-{}", request.runtime), "sh", "-c", INPUT,
|
||||
"framely-permission", &x.to_string(), &y.to_string(),
|
||||
]);
|
||||
output(command, Duration::from_secs(3), None)?;
|
||||
Ok(json!(true))
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
//! Optional Quest APK conversion. The runtime is versioned separately from Framely.
|
||||
use super::{apk_metadata, init, review, space, Cancellation, Metadata, MUTATION};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use serde_json::{json, Value};
|
||||
use std::{
|
||||
fs,
|
||||
os::unix::fs::{symlink, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, Stdio},
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
fn release_root() -> Result<PathBuf> {
|
||||
Ok(std::env::current_exe()?
|
||||
.parent()
|
||||
.context("Missing Framely binary directory")?
|
||||
.parent()
|
||||
.context("Missing Framely release directory")?
|
||||
.to_path_buf())
|
||||
}
|
||||
|
||||
fn requirement_path() -> Result<PathBuf> {
|
||||
if let Some(path) = std::env::var_os("FRAMELY_Q2F_DESCRIPTOR") {
|
||||
return Ok(PathBuf::from(path));
|
||||
}
|
||||
Ok(release_root()?.join("Q2F_RUNTIME.json"))
|
||||
}
|
||||
|
||||
fn tool_path() -> Result<PathBuf> {
|
||||
if let Some(path) = std::env::var_os("FRAMELY_Q2F_TOOL") {
|
||||
return Ok(PathBuf::from(path));
|
||||
}
|
||||
Ok(release_root()?.join("tools/q2f-runtime.py"))
|
||||
}
|
||||
|
||||
pub(super) fn status(home: &Path) -> Result<Value> {
|
||||
let requirement: Value = serde_json::from_slice(&fs::read(requirement_path()?)?)?;
|
||||
let identity = requirement["id"]
|
||||
.as_str()
|
||||
.context("Invalid q2f runtime identity")?;
|
||||
ensure!(
|
||||
!identity.is_empty()
|
||||
&& identity
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b".+-".contains(&b))
|
||||
&& !identity.contains(".."),
|
||||
"Invalid q2f runtime identity"
|
||||
);
|
||||
let cached = super::root(home).join("q2f/runtimes").join(identity);
|
||||
Ok(json!({"id":identity,"bytes":requirement["size"],
|
||||
"cached":fs::read_to_string(cached.join("VERSION")).is_ok_and(|v|v.trim()==identity)}))
|
||||
}
|
||||
|
||||
fn run(mut command: Command, log: &Path, cancel: &Cancellation) -> Result<()> {
|
||||
let output = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.write(true)
|
||||
.open(log)?;
|
||||
let errors = output.try_clone()?;
|
||||
let mut child = command
|
||||
.stdout(Stdio::from(output))
|
||||
.stderr(Stdio::from(errors))
|
||||
.spawn()?;
|
||||
loop {
|
||||
if let Err(error) = cancel.check() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err(error);
|
||||
}
|
||||
if let Some(status) = child.try_wait()? {
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
let detail = fs::read_to_string(log).unwrap_or_default();
|
||||
let tail = detail
|
||||
.chars()
|
||||
.rev()
|
||||
.take(3000)
|
||||
.collect::<String>()
|
||||
.chars()
|
||||
.rev()
|
||||
.collect::<String>();
|
||||
anyhow::bail!("Quest conversion failed ({}): {}", status, tail.trim());
|
||||
}
|
||||
thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
}
|
||||
|
||||
fn workspace(storage: &Path, runtime: &Path) -> Result<PathBuf> {
|
||||
let workspace = storage.join("q2f/workspace");
|
||||
fs::create_dir_all(workspace.join("signatures"))?;
|
||||
fs::set_permissions(
|
||||
workspace.join("signatures"),
|
||||
fs::Permissions::from_mode(0o700),
|
||||
)?;
|
||||
let libraries = workspace.join("libraries");
|
||||
if libraries.is_symlink() || libraries.exists() {
|
||||
if !libraries.is_symlink() {
|
||||
anyhow::bail!("Unexpected q2f libraries path");
|
||||
}
|
||||
fs::remove_file(&libraries)?;
|
||||
}
|
||||
let identity = runtime
|
||||
.file_name()
|
||||
.context("Missing q2f runtime identity")?;
|
||||
// Keep this relative so APK storage migration preserves the link.
|
||||
symlink(
|
||||
Path::new("../runtimes").join(identity).join("libraries"),
|
||||
&libraries,
|
||||
)?;
|
||||
fs::copy(
|
||||
runtime.join("overport-installed.json"),
|
||||
workspace.join("installed.json"),
|
||||
)?;
|
||||
Ok(workspace)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn workspace_library_link_survives_apk_storage_move() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let old = temp.path().join("old");
|
||||
let runtime = old.join("q2f/runtimes/test-id");
|
||||
fs::create_dir_all(runtime.join("libraries")).unwrap();
|
||||
fs::write(runtime.join("overport-installed.json"), "{}").unwrap();
|
||||
fs::write(runtime.join("libraries/probe"), "ok").unwrap();
|
||||
let work = workspace(&old, &runtime).unwrap();
|
||||
assert_eq!(
|
||||
fs::read_to_string(work.join("libraries/probe")).unwrap(),
|
||||
"ok"
|
||||
);
|
||||
let new = temp.path().join("new");
|
||||
fs::rename(old, &new).unwrap();
|
||||
assert_eq!(
|
||||
fs::read_to_string(new.join("q2f/workspace/libraries/probe")).unwrap(),
|
||||
"ok"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn convert(
|
||||
home: &Path,
|
||||
ticket: &str,
|
||||
cancel: &Cancellation,
|
||||
progress: impl Fn(Value) -> Result<()>,
|
||||
) -> Result<Value> {
|
||||
let _guard = MUTATION.lock().unwrap();
|
||||
cancel.check()?;
|
||||
let storage = init(home)?;
|
||||
let (source, before) = review(home, ticket)?;
|
||||
let source_apk = source.join("base.apk");
|
||||
let original_bytes = fs::metadata(&source_apk)?.len();
|
||||
// The observed OVR Port peak was roughly four source APK sizes, plus the
|
||||
// original review. Leave a fixed reserve for unrelated Android writes.
|
||||
space(
|
||||
&storage,
|
||||
original_bytes
|
||||
.saturating_mul(5)
|
||||
.saturating_add(1024 * 1024 * 1024),
|
||||
)?;
|
||||
let descriptor = requirement_path()?;
|
||||
ensure!(
|
||||
descriptor.is_file(),
|
||||
"This Framely build has no q2f runtime requirement"
|
||||
);
|
||||
let requirement: Value = serde_json::from_slice(&fs::read(&descriptor)?)?;
|
||||
let version = requirement["librariesVersion"]
|
||||
.as_str()
|
||||
.context("Invalid q2f runtime version")?;
|
||||
ensure!(
|
||||
version
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b".-".contains(&b)),
|
||||
"Invalid q2f runtime version"
|
||||
);
|
||||
progress(json!({"phase":"q2f-preparing","operation":"convert"}))?;
|
||||
let log = storage.join("logs").join(format!("q2f-{ticket}.log"));
|
||||
let mut prepare = Command::new("python3");
|
||||
prepare.arg(tool_path()?).arg(&descriptor).arg(&storage);
|
||||
run(prepare, &log, cancel)?;
|
||||
let runtime = PathBuf::from(
|
||||
fs::read_to_string(&log)?
|
||||
.lines()
|
||||
.last()
|
||||
.context("q2f runtime path missing")?,
|
||||
);
|
||||
ensure!(
|
||||
runtime.is_dir() && runtime.starts_with(storage.join("q2f/runtimes")),
|
||||
"Invalid q2f runtime path"
|
||||
);
|
||||
let work = workspace(&storage, &runtime)?;
|
||||
let output = source.join("converted");
|
||||
fs::create_dir_all(&output)?;
|
||||
progress(json!({"phase":"q2f-converting","operation":"convert","cancellable":true}))?;
|
||||
let mut java = Command::new(runtime.join("java/bin/java"));
|
||||
java.arg("-Xmx3g")
|
||||
.arg("-jar")
|
||||
.arg(runtime.join("overportcli.jar"))
|
||||
.arg("patch")
|
||||
.arg(format!("--input={}", source_apk.display()))
|
||||
.arg(format!("--output={}", output.display()))
|
||||
.arg("--output-name=base.apk")
|
||||
.arg(format!("--workspace={}", work.display()))
|
||||
.arg(format!("--version={version}"));
|
||||
let conversion = run(java, &log, cancel);
|
||||
let _ = fs::remove_dir_all(work.join("dec"));
|
||||
if let Err(error) = conversion {
|
||||
let _ = fs::remove_dir_all(&output);
|
||||
return Err(error);
|
||||
}
|
||||
let converted = output.join("base.apk");
|
||||
let result = (|| -> Result<Value> {
|
||||
ensure!(converted.is_file(), "Quest converter produced no APK");
|
||||
progress(json!({"phase":"q2f-verifying","operation":"convert"}))?;
|
||||
let after: Metadata = apk_metadata::read(&converted)?;
|
||||
ensure!(
|
||||
after.package == before.package && after.version_code == before.version_code,
|
||||
"Quest conversion changed APK package or version"
|
||||
);
|
||||
cancel.check()?;
|
||||
// Create a fresh review after conversion so the user has the full
|
||||
// review window even when patching takes several minutes.
|
||||
drop(_guard);
|
||||
super::inspect(home, &converted, cancel)
|
||||
})();
|
||||
let _ = fs::remove_dir_all(&output);
|
||||
let next = result?;
|
||||
Ok(
|
||||
json!({"ticket":next["ticket"],"metadata":next["metadata"],"bytes":next["bytes"],
|
||||
"q2fVersion":requirement["id"],"originalBytes":original_bytes}),
|
||||
)
|
||||
}
|
||||
@@ -210,7 +210,7 @@ pub(super) fn register(home: &Path, a: &App, r: &mut Record) -> Result<()> {
|
||||
r.steam_binding = Some(Binding {
|
||||
game_id: game.clone(),
|
||||
native: true,
|
||||
revision: revision(a),
|
||||
revision: revision(a, r),
|
||||
});
|
||||
rpc(home, "create-shortcut", Some(&game))?;
|
||||
let v: Value = serde_json::from_str(&rpc(home, "list-shortcuts", None)?)?;
|
||||
@@ -230,7 +230,7 @@ pub(super) fn register(home: &Path, a: &App, r: &mut Record) -> Result<()> {
|
||||
r.steam_app_id = Some(super::steam_ui::configure(
|
||||
&game,
|
||||
r.steam_app_id,
|
||||
&a.metadata.name,
|
||||
r.steam_name.as_deref().unwrap_or(&a.metadata.name),
|
||||
icon.as_deref(),
|
||||
&launch,
|
||||
&native_apk(home, &a.id),
|
||||
@@ -238,7 +238,7 @@ pub(super) fn register(home: &Path, a: &App, r: &mut Record) -> Result<()> {
|
||||
r.steam_binding = Some(Binding {
|
||||
game_id: game,
|
||||
native: true,
|
||||
revision: revision(a),
|
||||
revision: revision(a, r),
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
@@ -285,8 +285,30 @@ pub(super) fn unregister(home: &Path, r: &Record) -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn revision(a: &App) -> String {
|
||||
hash(&json!({"metadata":a.metadata,"showWindow":a.show_window}).to_string())
|
||||
pub(super) fn parse_name(value: &Value) -> Result<Option<String>> {
|
||||
let name = value.as_str().context("Invalid Steam display name")?.trim();
|
||||
ensure!(name.chars().count() <= 128 && !name.chars().any(char::is_control), "Steam display name must be at most 128 characters without control characters");
|
||||
Ok((!name.is_empty()).then(|| name.to_owned()))
|
||||
}
|
||||
fn revision(a: &App, r: &Record) -> String {
|
||||
let mut value = json!({"metadata":a.metadata,"showWindow":a.show_window});
|
||||
if let Some(name) = &r.steam_name {
|
||||
value["steamName"] = json!(name);
|
||||
}
|
||||
hash(&value.to_string())
|
||||
}
|
||||
pub(super) fn update_name(home: &Path, a: &App, r: &mut Record) -> Result<()> {
|
||||
let parameters = json!({"game":game_id(&a.id),"previous":r.steam_app_id,"exe":native_apk(home,&a.id),"name":r.steam_name.as_deref().unwrap_or(&a.metadata.name)});
|
||||
let result = steam_ui::evaluate(&format!(
|
||||
"(async()=>{{const p={parameters};const owned=await ({lookup})(p);SteamClient.Apps.SetShortcutName(owned.id,p.name);return true;}})()",
|
||||
lookup = include_str!("steam_shortcut_lookup.js")
|
||||
))?;
|
||||
ensure!(result == json!(true), "Steam name update was not acknowledged");
|
||||
let current_revision = revision(a, r);
|
||||
if let Some(binding) = &mut r.steam_binding {
|
||||
binding.revision = current_revision;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn icon_file(dir: &Path, metadata: &Metadata) -> Result<Option<PathBuf>> {
|
||||
use base64::Engine;
|
||||
@@ -369,7 +391,7 @@ pub(super) fn ensure_registered(home: &Path, id: &str, force: bool) -> Result<bo
|
||||
&& rec
|
||||
.steam_binding
|
||||
.as_ref()
|
||||
.is_some_and(|b| b.native && b.revision == revision(&a))
|
||||
.is_some_and(|b| b.native && b.revision == revision(&a, rec))
|
||||
{
|
||||
save(home, &db)?;
|
||||
return Ok(true);
|
||||
@@ -421,7 +443,7 @@ pub(super) fn synchronize(home: &Path) -> Result<()> {
|
||||
&& linked(home, r)
|
||||
&& r.steam_binding
|
||||
.as_ref()
|
||||
.is_some_and(|b| b.native && b.revision == revision(&a))
|
||||
.is_some_and(|b| b.native && b.revision == revision(&a, r))
|
||||
})
|
||||
{
|
||||
continue;
|
||||
|
||||
@@ -853,6 +853,10 @@ impl Agent {
|
||||
if remote && request["method"] == "ui.visibility.get" {
|
||||
request["params"] = json!({"view":""});
|
||||
}
|
||||
ensure!(
|
||||
!remote || !request["method"].as_str().is_some_and(|m| m.starts_with("apk.permission.")),
|
||||
"Headset permission window is local only"
|
||||
);
|
||||
let result = if remote && request["method"] == "agreement.decline" {
|
||||
Ok(json!({"closed":false}))
|
||||
} else {
|
||||
@@ -867,6 +871,7 @@ impl Agent {
|
||||
if path == "/"
|
||||
|| path == "/cast/watch"
|
||||
|| path.starts_with("/cast/window/")
|
||||
|| path == "/apk/permission"
|
||||
|| path == "/manager"
|
||||
|| path == "/notifications"
|
||||
|| path == "/launcher"
|
||||
@@ -1072,8 +1077,27 @@ impl Agent {
|
||||
&crate::steam::home()?,
|
||||
p["ticket"].as_str().context("Missing APK review")?,
|
||||
),
|
||||
"apk.q2f.status" => crate::apk::q2f_status(&crate::steam::home()?),
|
||||
"apk.q2f.start" => {
|
||||
let _gate = APK_STORAGE_API_GATE.lock().unwrap();
|
||||
ensure!(!self.jobs.active_kind("apk:storage") && !self.jobs.active_kind("apk:operation"), "请等待 APK 操作或存储迁移完成");
|
||||
let home = crate::steam::home()?;
|
||||
let ticket = p["ticket"].as_str().context("Missing APK review")?.to_owned();
|
||||
self.jobs.task_progress("apk:operation", move |cancel, progress| {
|
||||
crate::apk::q2f_convert(&home, &ticket, &cancel, |value| { progress(value); Ok(()) })
|
||||
})
|
||||
}
|
||||
"apk.cleanup.list" => crate::apk::cleanup_list(&crate::steam::home()?),
|
||||
"apk.storage.status" => crate::apk::storage_status(&crate::steam::home()?),
|
||||
"apk.permission.pending" => Ok(json!(crate::apk::permissions::pending(&crate::steam::home()?)?)),
|
||||
"apk.permission.frame" => crate::apk::permissions::frame(
|
||||
&crate::steam::home()?, p["id"].as_str().context("Missing permission request")?
|
||||
),
|
||||
"apk.permission.click" => crate::apk::permissions::click(
|
||||
&crate::steam::home()?, p["id"].as_str().context("Missing permission request")?,
|
||||
p["x"].as_u64().context("Invalid Android input position")?.try_into()?,
|
||||
p["y"].as_u64().context("Invalid Android input position")?.try_into()?,
|
||||
),
|
||||
"apk.storage.start" => {
|
||||
let _gate = APK_STORAGE_API_GATE.lock().unwrap();
|
||||
ensure!(!self.jobs.uploads.active() && !self.jobs.active_kind("apk:storage") && !self.jobs.active_kind("apk:operation"), "请等待 APK 上传或操作完成");
|
||||
@@ -1901,6 +1925,34 @@ pub fn serve(
|
||||
}
|
||||
cast_agent.maintain_cast();std::thread::sleep(Duration::from_millis(100));
|
||||
}});
|
||||
let permission_agent = agent.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut shown = String::new();
|
||||
let mut missing = 0u8;
|
||||
loop {
|
||||
if let Ok(home) = crate::steam::home() {
|
||||
if let Ok(pending) = crate::apk::permissions::pending(&home) {
|
||||
let next = pending.as_ref().map(|p| p.id.clone()).unwrap_or_default();
|
||||
if next.is_empty() && !shown.is_empty() && missing < 1 {
|
||||
missing += 1;
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
continue;
|
||||
}
|
||||
missing = 0;
|
||||
if next != shown {
|
||||
if !shown.is_empty() {
|
||||
push(&permission_agent.commands, json!({"kind":"apk.permission.close"}));
|
||||
}
|
||||
if let Some(request) = pending {
|
||||
push(&permission_agent.commands, json!({"kind":"apk.permission.open","id":request.id}));
|
||||
}
|
||||
shown = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
}
|
||||
});
|
||||
let file_agent = agent.clone();
|
||||
std::thread::spawn(move || loop {
|
||||
if let Ok(home) = crate::steam::home() {
|
||||
|
||||
+29
-19
@@ -182,10 +182,10 @@ fn resolve_release(
|
||||
let Ok(version) = semver::Version::parse(tag) else {
|
||||
continue;
|
||||
};
|
||||
let testing = channel == UpdateChannel::Testing;
|
||||
let is_prerelease = !version.pre.is_empty();
|
||||
if release.draft
|
||||
|| release.prerelease != testing
|
||||
|| version.pre.is_empty() == testing
|
||||
|| release.prerelease != is_prerelease
|
||||
|| (channel == UpdateChannel::Stable && is_prerelease)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -242,7 +242,7 @@ fn resolve_release(
|
||||
let release = verify_descriptor(&bytes)?;
|
||||
let version = descriptor_version(&release.version)?;
|
||||
ensure!(
|
||||
version.pre.is_empty() == (channel == UpdateChannel::Stable),
|
||||
channel == UpdateChannel::Testing || version.pre.is_empty(),
|
||||
"更新清单不属于所选渠道,请配置该渠道的清单地址"
|
||||
);
|
||||
Ok(Some((release, bytes, version.to_string())))
|
||||
@@ -678,17 +678,29 @@ mod tests {
|
||||
let testing = resolve_fixture(UpdateChannel::Testing, releases)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(testing.2, "0.4.2-preview.10");
|
||||
assert_eq!(testing.2, "0.4.2");
|
||||
assert!(resolve_fixture(
|
||||
UpdateChannel::Stable,
|
||||
vec![fixture("0.4.2-preview.1", false)]
|
||||
)
|
||||
.unwrap()
|
||||
.is_none());
|
||||
assert!(
|
||||
assert_eq!(
|
||||
resolve_fixture(UpdateChannel::Testing, vec![fixture("0.4.2", false)])
|
||||
.unwrap()
|
||||
.is_none()
|
||||
.unwrap()
|
||||
.2,
|
||||
"0.4.2"
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_fixture(
|
||||
UpdateChannel::Testing,
|
||||
vec![fixture("0.4.2", false), fixture("0.4.3-preview.1", false)]
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.2,
|
||||
"0.4.3-preview.1"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
@@ -762,9 +774,10 @@ mod tests {
|
||||
.ends_with("framely-0.4.2-preview.1-012345abcdef-linux-arm64.tar.gz"));
|
||||
}
|
||||
#[test]
|
||||
fn custom_descriptors_distinguish_channels_and_ignore_packaging_hashes() {
|
||||
fn custom_descriptors_allow_stable_on_testing_and_ignore_packaging_hashes() {
|
||||
for (version, channel) in [
|
||||
("0.4.2", UpdateChannel::Stable),
|
||||
("0.4.2", UpdateChannel::Testing),
|
||||
("0.4.2-beta.1", UpdateChannel::Testing),
|
||||
] {
|
||||
let (_, bytes) = fixture(version, false);
|
||||
@@ -780,17 +793,14 @@ mod tests {
|
||||
.2,
|
||||
version
|
||||
);
|
||||
let other_channel = if channel == UpdateChannel::Stable {
|
||||
UpdateChannel::Testing
|
||||
} else {
|
||||
UpdateChannel::Stable
|
||||
};
|
||||
assert!(
|
||||
resolve_release(&source, other_channel, &Default::default(), &mut |_, _| Ok(
|
||||
bytes.clone()
|
||||
))
|
||||
.is_err()
|
||||
);
|
||||
if version.contains('-') {
|
||||
assert!(
|
||||
resolve_release(&source, UpdateChannel::Stable, &Default::default(), &mut |_, _| Ok(
|
||||
bytes.clone()
|
||||
))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
|
||||
@@ -15,7 +15,7 @@ window.fetch=async(url,init)=>{if(String(url).startsWith('/host/files/')){const
|
||||
const id='job-'+counter++;let value:any=true;
|
||||
if(method==='apk.list.start')value={apps:structuredClone(apps),containers,roots:[],warnings:[],available:true,gamepadEnabled,gamepadTriggerThreshold,autoStopContainer,stopContainerOnClose};
|
||||
else if(method==='apk.inspect.start')value={ticket:'review-ticket',metadata:meta('com.example.new','New APK'),bytes:4};
|
||||
else{if(params.operation==='lifecycle.settings'){autoStopContainer=params.autoStopContainer;stopContainerOnClose=params.stopContainerOnClose;}if(params.operation==='gamepad.settings'){gamepadEnabled=params.enabled;if(params.triggerThreshold!==undefined)gamepadTriggerThreshold=params.triggerThreshold;}const app=apps.find(a=>a.id===params.app);if(params.operation==='steam.settings')app.steamLaunch=params.enabled;if(params.operation==='settings')Object.assign(app,{activity:params.activity,showWindow:params.showWindow});if(params.operation==='uninstall'&&!uninstallError)app.installed=false;if(params.operation==='cleanup'){cleanupItems=cleanupItems.filter(i=>!params.items.includes(i.id));value={freedBytes:4*1024*1024,failed:[]};}}
|
||||
else{if(params.operation==='lifecycle.settings'){autoStopContainer=params.autoStopContainer;stopContainerOnClose=params.stopContainerOnClose;}if(params.operation==='gamepad.settings'){gamepadEnabled=params.enabled;if(params.triggerThreshold!==undefined)gamepadTriggerThreshold=params.triggerThreshold;}const app=apps.find(a=>a.id===params.app);if(params.operation==='steam.settings')app.steamLaunch=params.enabled;if(params.operation==='settings'){if('steamName' in params)app.steamName=params.steamName.trim()||null;else Object.assign(app,{activity:params.activity,showWindow:params.showWindow});}if(params.operation==='uninstall'&&!uninstallError)app.installed=false;if(params.operation==='cleanup'){cleanupItems=cleanupItems.filter(i=>!params.items.includes(i.id));value={freedBytes:4*1024*1024,failed:[]};}}
|
||||
jobs.set(id,{id,kind:'apk',phase:method==='apk.operation.start'&&(fail||(params.operation==='uninstall'&&uninstallError))?'failed':'done',result:value,error:uninstallError??'Fixture signature mismatch',received:0});result={job:id};
|
||||
}else if(method==='job.status')result=jobs.get(params.job);
|
||||
return new Response(JSON.stringify({result}));};
|
||||
@@ -44,8 +44,17 @@ async function snapshot(name:string){await wait(220);console.log('FRAMELY_PREVIE
|
||||
button('Containers').click();await until(()=>document.querySelectorAll('.apk-container').length===3);
|
||||
for(const title of ['Start container','Stop container']){button(title).click();await until(()=>!!document.querySelector('.apk-dialog'));if(document.querySelector('.apk-dialog')!.textContent!.includes(t('永久删除的数据无法撤销。')))throw Error('Container operation displayed data deletion warning');if(!button('Confirm',document.querySelector('.apk-dialog')!).classList.contains('primary'))throw Error('Non-destructive container confirmation uses destructive styling');button('Cancel',document.querySelector('.apk-dialog')!).click();await until(()=>!document.querySelector('.apk-dialog'));}
|
||||
const external=document.querySelectorAll('.apk-container')[1];button('Delete container',external).click();await until(()=>document.querySelector('.apk-dialog'));if(!document.querySelector('.apk-dialog')!.textContent!.includes(t('容器数据、关联 APK 缓存和 Steam 库条目将永久删除,历史备份保留。')))throw Error('External deletion lacks data warning');button('Cancel',document.querySelector('.apk-dialog')!).click();await until(()=>!document.querySelector('.apk-dialog'));if(calls.some(c=>c.params.operation==='container.delete'))throw Error('Cancelled deletion modified external container');
|
||||
button('Apps').click();await until(()=>document.querySelectorAll('.apk-row').length===2);
|
||||
button('Manage',document.querySelector('.apk-row')!).click();await until(()=>document.querySelector('.apk-dialog'));const advanced=document.querySelector<HTMLDetailsElement>('.apk-advanced')!;advanced.open=true;document.querySelector<HTMLButtonElement>('[role=switch][aria-label="Handle window display automatically"]')!.click();await until(()=>calls.some(c=>c.method==='apk.operation.start'&&c.params.operation==='settings'));await until(()=>!document.querySelector('progress'));await until(()=>document.querySelector('.apk-dialog')&&!button('Uninstall app',document.querySelector('.apk-dialog')!).disabled);
|
||||
button(t('应用')).click();await until(()=>document.querySelectorAll('.apk-row').length===2);
|
||||
button('Manage',document.querySelector('.apk-row')!).click();await until(()=>document.querySelector('.apk-dialog'));const steamName=()=>document.querySelector<HTMLInputElement>('.apk-steam-name input')!;
|
||||
if(!steamName()||steamName().placeholder!=='Wolvic')throw Error('Per-app Steam name setting missing');
|
||||
for(const name of ['My Wolvic','']){
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value')!.set!.call(steamName(),name);steamName().dispatchEvent(new Event('input',{bubbles:true}));await wait();
|
||||
button('Save',document.querySelector('.apk-steam-name')!).click();
|
||||
await until(()=>calls.some(c=>c.params.operation==='settings'&&c.params.steamName===name));
|
||||
await until(()=>!!steamName()&&!steamName().disabled);
|
||||
if(steamName().value!==name||apps[0].metadata.name!=='Wolvic')throw Error('Custom name changed original APK name');
|
||||
}
|
||||
const advanced=document.querySelector<HTMLDetailsElement>('.apk-advanced')!;advanced.open=true;document.querySelector<HTMLButtonElement>('[role=switch][aria-label="Handle window display automatically"]')!.click();await until(()=>calls.some(c=>c.method==='apk.operation.start'&&c.params.operation==='settings'));await until(()=>!document.querySelector('progress'));await until(()=>document.querySelector('.apk-dialog')&&!button('Uninstall app',document.querySelector('.apk-dialog')!).disabled);
|
||||
button('Uninstall app',document.querySelector('.apk-dialog')!).click();await until(()=>document.querySelector('[role=switch][aria-label="Delete app data"]'));
|
||||
const purgeSwitch=()=>document.querySelector<HTMLButtonElement>('[aria-label="Delete app data"]')!;
|
||||
const deleteSwitch=()=>document.querySelector<HTMLButtonElement>('[aria-label="Delete container"]')!;
|
||||
|
||||
@@ -24,6 +24,13 @@ registerPlugin({QuickPage:Page});
|
||||
await native('X','x','keyboard-multiline-state');await native('ENTER','x\n','keyboard-multiline-state');
|
||||
await native('Y','x\ny','keyboard-multiline-state');
|
||||
await native('BACKSPACE','x\n','keyboard-multiline-state');await native('BACKSPACE','x','keyboard-multiline-state');await native('BACKSPACE','','keyboard-multiline-state');
|
||||
const editor=document.createElement('textarea'),edits:string[]=[];
|
||||
editor.addEventListener('framely.keyboard.edit',event=>{event.preventDefault();edits.push((event as CustomEvent<string>).detail);});
|
||||
document.body.appendChild(editor);editor.focus();editor.dispatchEvent(new FocusEvent('focusin',{bubbles:true}));
|
||||
console.log('FRAMELY_NATIVE_KEYBOARD_X');await until(()=>edits.length===1);
|
||||
console.log('FRAMELY_NATIVE_KEYBOARD_BACKSPACE');await until(()=>edits.length===2);
|
||||
if(edits[0]!=='x'||edits[1]!=='\b'||editor.value!=='')throw Error('custom keyboard editor did not consume native edits');
|
||||
editor.remove();
|
||||
console.log('FRAMELY_KEYBOARD_REACT_PASS');
|
||||
(window as any).__framelyKeyboardFixtureDone=true;
|
||||
}catch(e){console.error('FRAMELY_BRIDGE_FAIL '+e);}})();
|
||||
@@ -0,0 +1,63 @@
|
||||
import importlib.util
|
||||
import json
|
||||
import pathlib
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
SCRIPT = pathlib.Path(__file__).resolve().parents[1] / 'tools/q2f-runtime.py'
|
||||
SPEC = importlib.util.spec_from_file_location('q2f_runtime', SCRIPT)
|
||||
RUNTIME = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(RUNTIME)
|
||||
|
||||
|
||||
class Q2FRuntimeTests(unittest.TestCase):
|
||||
def test_exact_cache_is_reused_and_tampering_is_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
base = pathlib.Path(directory)
|
||||
identity = 'overport-test-123456789abc'
|
||||
payload = base / 'payload'
|
||||
(payload / 'java/bin').mkdir(parents=True)
|
||||
for name in ('java/bin/java', 'overportcli.jar', 'overport-installed.json', 'OVR_PORT_LICENSE'):
|
||||
(payload / name).write_text(name)
|
||||
files = sorted(p for p in payload.rglob('*') if p.is_file())
|
||||
sums = ''.join(f'{RUNTIME.digest(p)} {p.relative_to(payload)}\n' for p in files)
|
||||
(payload / 'VERSION').write_text(identity + '\n')
|
||||
(payload / 'SHA256SUMS').write_text(sums)
|
||||
archive = base / f'framely-q2f-{identity}-linux-arm64.tar.gz'
|
||||
with tarfile.open(archive, 'w:gz') as tar:
|
||||
tar.add(payload, arcname=f'framely-q2f-{identity}')
|
||||
descriptor = base / 'requirement.json'
|
||||
descriptor.write_text(json.dumps({'schemaVersion': 1, 'id': identity,
|
||||
'archive': archive.name, 'size': archive.stat().st_size,
|
||||
'sha256': RUNTIME.digest(archive), 'url': 'https://example.invalid/q2f'}))
|
||||
copies = []
|
||||
def copy(_requirement, destination):
|
||||
destination.write_bytes(archive.read_bytes())
|
||||
copies.append(destination)
|
||||
with patch.object(RUNTIME, 'download', copy):
|
||||
cached = RUNTIME.prepare(descriptor, base / 'storage')
|
||||
self.assertEqual(cached, RUNTIME.prepare(descriptor, base / 'storage'))
|
||||
self.assertEqual(len(copies), 1)
|
||||
(cached / 'overportcli.jar').write_text('changed')
|
||||
with self.assertRaisesRegex(ValueError, 'checksum mismatch'):
|
||||
RUNTIME.prepare(descriptor, base / 'storage')
|
||||
|
||||
def test_archive_rejects_link_and_escape(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
base = pathlib.Path(directory)
|
||||
identity = 'overport-test-123456789abc'
|
||||
archive = base / 'unsafe.tar.gz'
|
||||
for index, member in enumerate((f'framely-q2f-{identity}/../escape', f'framely-q2f-{identity}/link')):
|
||||
with tarfile.open(archive, 'w:gz') as tar:
|
||||
info = tarfile.TarInfo(member)
|
||||
info.type = tarfile.SYMTYPE if member.endswith('/link') else tarfile.REGTYPE
|
||||
info.size = 0
|
||||
tar.addfile(info)
|
||||
with self.assertRaisesRegex(ValueError, 'Unsafe'):
|
||||
RUNTIME.extract(archive, base / f'target-{index}', identity)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build an independently downloadable Quest conversion runtime."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import tarfile
|
||||
import tempfile
|
||||
import zipfile
|
||||
|
||||
CLI_VERSION = '1.2.3'
|
||||
LIBRARIES_VERSION = '3.4.3-23204ea'
|
||||
CLI_SHA256 = '307d58a69a5c9722f912d1b6566b0dd1e0ebe1440c6d1e56cab6cb883d74fef2'
|
||||
LIBRARIES_SHA256 = '6cec6c176e1aeee8d9ec4f9b4e3982f71da7b44a36a293249620073a06f00e5e'
|
||||
SOURCE_SHA256 = '2db2c0f597a8be01d9742180019627b4c23fd0213f04f5034fbad53f0d296eb3'
|
||||
|
||||
|
||||
def digest(path):
|
||||
with path.open('rb') as source:
|
||||
return hashlib.file_digest(source, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def safe_zip_extract(source, destination):
|
||||
with zipfile.ZipFile(source) as archive:
|
||||
for entry in archive.infolist():
|
||||
path = pathlib.PurePosixPath(entry.filename)
|
||||
if (path.is_absolute() or '..' in path.parts or '\\' in entry.filename
|
||||
or (entry.external_attr >> 16) & 0o170000 == 0o120000):
|
||||
raise ValueError('Unsafe OVR Port library entry')
|
||||
target = destination.joinpath(*path.parts)
|
||||
if entry.is_dir():
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
else:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
with archive.open(entry) as data, target.open('xb') as output:
|
||||
shutil.copyfileobj(data, output)
|
||||
|
||||
|
||||
def package(args):
|
||||
cli, libraries, java, source = map(pathlib.Path, (args.cli_jar, args.libraries_zip, args.java_home, args.source_archive))
|
||||
if digest(cli) != CLI_SHA256 or digest(libraries) != LIBRARIES_SHA256 or digest(source) != SOURCE_SHA256:
|
||||
raise ValueError('Pinned OVR Port artifact checksum mismatch')
|
||||
if not (java / 'bin/java').is_file() or not (java / 'legal/java.base/LICENSE').is_file():
|
||||
raise ValueError('Incomplete Java runtime')
|
||||
output = pathlib.Path(args.output)
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix='q2f-package-', dir=output) as scratch:
|
||||
payload = pathlib.Path(scratch) / 'payload'
|
||||
shutil.copytree(java, payload / 'java', symlinks=False)
|
||||
shutil.copy2(cli, payload / 'overportcli.jar')
|
||||
safe_zip_extract(libraries, payload / 'libraries' / LIBRARIES_VERSION)
|
||||
(payload / 'overport-installed.json').write_text(json.dumps({'releases': [
|
||||
{'version': LIBRARIES_VERSION, 'app_required': '1.2.0', 'is_experimental': True}
|
||||
]}) + '\n')
|
||||
shutil.copy2(args.license, payload / 'OVR_PORT_LICENSE')
|
||||
shutil.copy2(source, payload / 'OVR_PORT_SOURCE.tar.gz')
|
||||
(payload / 'SOURCE').write_text('https://github.com/ovrport/app/tree/c790854\n')
|
||||
entries = sorted(p for p in payload.rglob('*') if p.is_file())
|
||||
checksums = ''.join(f'{digest(p)} {p.relative_to(payload).as_posix()}\n' for p in entries)
|
||||
identity = f'overport-{CLI_VERSION}-{LIBRARIES_VERSION}-{hashlib.sha256(checksums.encode()).hexdigest()[:12]}'
|
||||
(payload / 'VERSION').write_text(identity + '\n')
|
||||
(payload / 'SHA256SUMS').write_text(checksums)
|
||||
archive = output / f'framely-q2f-{identity}-linux-arm64.tar.gz'
|
||||
with tarfile.open(archive, 'w:gz') as tar:
|
||||
tar.add(payload, arcname=f'framely-q2f-{identity}')
|
||||
requirement = {'schemaVersion': 1, 'id': identity,
|
||||
'cliVersion': CLI_VERSION, 'librariesVersion': LIBRARIES_VERSION,
|
||||
'archive': archive.name, 'size': archive.stat().st_size,
|
||||
'sha256': digest(archive),
|
||||
'url': f'https://github.com/{args.repo}/releases/download/{args.tag}/{archive.name}'}
|
||||
pathlib.Path(args.stage, 'Q2F_RUNTIME.json').write_text(json.dumps(requirement, indent=2) + '\n')
|
||||
pathlib.Path(output, 'framely-q2f.json').write_text(json.dumps(requirement, indent=2) + '\n')
|
||||
print(archive)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser()
|
||||
for name in ('stage', 'output', 'java-home', 'cli-jar', 'libraries-zip', 'license', 'source-archive', 'repo', 'tag'):
|
||||
parser.add_argument('--' + name, required=True)
|
||||
package(parser.parse_args())
|
||||
@@ -9,10 +9,22 @@ cargo build --release --locked
|
||||
npm ci --no-audit --no-fund
|
||||
npm run build
|
||||
bash tools/build-native.sh "$cef"
|
||||
bash tools/build-media.sh
|
||||
if [[ ${FRAMELY_USE_PREBUILT_MEDIA:-0} == 1 ]]; then
|
||||
[[ -z $(git status --porcelain -- media) ]] || { echo 'Media sources changed; rebuild media.' >&2; exit 1; }
|
||||
for file in media/bin/framely-panel-grab media/bin/framely-capture media/bin/mediamtx media/bin/uxplay media/bin/framely-receiver media/bin/libgstframely.so media/bin/libgstlibav.so media/bin/LICENSE media/bin/LICENSE.uxplay media/bin/LICENSE.gst-libav media/bin/LICENSE.llhttp; do
|
||||
[[ -s $file ]] || { echo "Missing prebuilt media: $file" >&2; exit 1; }
|
||||
done
|
||||
else
|
||||
bash tools/build-media.sh
|
||||
fi
|
||||
binary=${CARGO_TARGET_DIR:-target}/release/framely
|
||||
version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
|
||||
build_id="$version-$(find "$binary" target/native media/bin ui/dist sdk templates/plugin examples/showcase packaging tools docs assets/branding assets/search README.md README.zh-CN.md LICENSE -type f ! -path '*/__pycache__/*' -print0 | sort -z | xargs -0 sha256sum | sha256sum | cut -c1-12)"
|
||||
q2f_java=${Q2F_JAVA_HOME:-target/quest-conversion-jre}
|
||||
q2f_cli=${Q2F_CLI_JAR:-target/overportcli-1.2.3-all.jar}
|
||||
q2f_libraries=${Q2F_LIBRARIES_ZIP:-target/overport-libraries-3.4.3-23204ea.zip}
|
||||
q2f_license=${Q2F_LICENSE:-target/overport-source/LICENSE}
|
||||
q2f_source=${Q2F_SOURCE_ARCHIVE:-target/q2f-source.tar.gz}
|
||||
build_id="$version-$(find "$binary" target/native media/bin ui/dist sdk templates/plugin examples/showcase packaging tools docs assets/branding assets/search README.md README.zh-CN.md LICENSE "$q2f_java" "$q2f_cli" "$q2f_libraries" "$q2f_license" "$q2f_source" -type f ! -path '*/__pycache__/*' -print0 | sort -z | xargs -0 sha256sum | sha256sum | cut -c1-12)"
|
||||
stage="$base/release/framely-$build_id"
|
||||
[[ ! -e $stage ]] || { echo 'Release already exists.' >&2; exit 1; }
|
||||
mkdir -p "$stage"/{bin,lib/cef,lib/openvr,lib/media,share/ui,share/licenses,tools}
|
||||
@@ -67,10 +79,15 @@ cp -a assets/branding "$stage/tools/source/assets/"
|
||||
cp -a examples/showcase "$stage/tools/source/examples/"
|
||||
cp -a ui/src ui/locales ui/index.html ui/package.json "$stage/tools/source/ui/"
|
||||
cp tools/build-ui.mjs tools/build-branding.mjs tools/plugin-dev.mjs "$stage/tools/source/tools/"
|
||||
cp tools/extract-release.py tools/bootstrap.py tools/cef-runtime.py tools/export-diagnostics.py "$stage/tools/"
|
||||
cp tools/extract-release.py tools/bootstrap.py tools/cef-runtime.py tools/q2f-runtime.py tools/export-diagnostics.py "$stage/tools/"
|
||||
find "$stage/tools/source" -type d -name __pycache__ -prune -exec rm -rf -- {} +
|
||||
cp -a docs "$stage/share/"
|
||||
printf '%s\n' "$build_id" > "$stage/VERSION"
|
||||
chmod 755 "$stage"/*.sh "$stage/bin/"* "$stage/lib/cef/framely-vr"
|
||||
python3 tools/package-q2f.py --stage "$stage" --output release \
|
||||
--java-home "$q2f_java" --cli-jar "$q2f_cli" \
|
||||
--libraries-zip "$q2f_libraries" --license "$q2f_license" \
|
||||
--source-archive "$q2f_source" \
|
||||
--repo "${RELEASE_REPO:-SteamFramelyHomebrew/framely}" --tag "${RELEASE_TAG:-v$version}"
|
||||
python3 tools/package-runtime.py "$stage" "$cef" "${RELEASE_REPO:-SteamFramelyHomebrew/framely}" "${RELEASE_TAG:-v$version}"
|
||||
echo "Package: release/framely-$build_id-linux-arm64.tar.gz"
|
||||
@@ -0,0 +1,135 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Download and verify the exact optional Quest conversion runtime."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
MAX_ARCHIVE = 512 * 1024 * 1024
|
||||
MAX_EXPANDED = 1024 * 1024 * 1024
|
||||
|
||||
|
||||
def digest(path):
|
||||
with path.open('rb') as source:
|
||||
return hashlib.file_digest(source, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def validate(root, identity):
|
||||
if root.is_symlink() or not root.is_dir() or (root / 'VERSION').read_text().strip() != identity:
|
||||
raise ValueError('Invalid q2f runtime cache')
|
||||
lines = (root / 'SHA256SUMS').read_text().splitlines()
|
||||
expected = set()
|
||||
for line in lines:
|
||||
match = re.fullmatch(r'([a-f0-9]{64}) ([^\\]+)', line)
|
||||
if not match:
|
||||
raise ValueError('Invalid q2f checksum list')
|
||||
relative = pathlib.PurePosixPath(match[2])
|
||||
if relative.is_absolute() or '..' in relative.parts or not relative.parts:
|
||||
raise ValueError('Invalid q2f payload path')
|
||||
file = root.joinpath(*relative.parts)
|
||||
if file.is_symlink() or not file.is_file() or digest(file) != match[1]:
|
||||
raise ValueError('q2f payload checksum mismatch: ' + match[2])
|
||||
expected.add(relative.as_posix())
|
||||
actual = {p.relative_to(root).as_posix() for p in root.rglob('*') if p.is_file()}
|
||||
if actual != expected | {'VERSION', 'SHA256SUMS'}:
|
||||
raise ValueError('Unexpected q2f payload files')
|
||||
for required in ('java/bin/java', 'overportcli.jar', 'overport-installed.json', 'OVR_PORT_LICENSE'):
|
||||
if required not in expected:
|
||||
raise ValueError('Incomplete q2f runtime: ' + required)
|
||||
|
||||
|
||||
class HTTPSRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
if urllib.parse.urlparse(newurl).scheme != 'https':
|
||||
raise ValueError('HTTPS redirect downgrade rejected')
|
||||
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
||||
|
||||
|
||||
def download(requirement, destination):
|
||||
url = requirement['url']
|
||||
if urllib.parse.urlparse(url).scheme != 'https':
|
||||
raise ValueError('q2f URL must use HTTPS')
|
||||
request = urllib.request.Request(url, headers={'User-Agent': 'Framely-q2f'})
|
||||
with urllib.request.build_opener(HTTPSRedirect()).open(request, timeout=90) as response, destination.open('xb') as output:
|
||||
total = 0
|
||||
while block := response.read(256 * 1024):
|
||||
total += len(block)
|
||||
if total > requirement['size'] or total > MAX_ARCHIVE:
|
||||
raise ValueError('q2f download exceeds declared size')
|
||||
output.write(block)
|
||||
if total != requirement['size'] or digest(destination) != requirement['sha256']:
|
||||
raise ValueError('q2f archive checksum mismatch')
|
||||
|
||||
|
||||
def extract(archive, target, identity):
|
||||
prefix = f'framely-q2f-{identity}'
|
||||
target.mkdir(mode=0o700)
|
||||
with tarfile.open(archive, 'r:gz') as source:
|
||||
members = source.getmembers()
|
||||
if len(members) > 10000 or sum(m.size for m in members) > MAX_EXPANDED:
|
||||
raise ValueError('q2f archive is too large')
|
||||
seen = set()
|
||||
for member in members:
|
||||
path = pathlib.PurePosixPath(member.name)
|
||||
if (path.is_absolute() or '..' in path.parts or '\\' in member.name
|
||||
or not path.parts or path.parts[0] != prefix
|
||||
or member.name in seen or not (member.isfile() or member.isdir())):
|
||||
raise ValueError('Unsafe q2f archive member')
|
||||
seen.add(member.name)
|
||||
for member in members:
|
||||
parts = pathlib.PurePosixPath(member.name).parts[1:]
|
||||
if not parts:
|
||||
continue
|
||||
path = target.joinpath(*parts)
|
||||
if member.isdir():
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
else:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with source.extractfile(member) as data, path.open('xb') as output:
|
||||
shutil.copyfileobj(data, output)
|
||||
path.chmod(0o755 if member.mode & 0o111 else 0o644)
|
||||
validate(target, identity)
|
||||
|
||||
|
||||
def prepare(descriptor, storage):
|
||||
spec = json.loads(pathlib.Path(descriptor).read_text())
|
||||
identity = spec['id']
|
||||
archive_name = f'framely-q2f-{identity}-linux-arm64.tar.gz'
|
||||
if (spec['schemaVersion'] != 1 or not re.fullmatch(r'[a-zA-Z0-9.+-]+', identity)
|
||||
or '..' in identity or spec['archive'] != archive_name
|
||||
or not 0 < spec['size'] <= MAX_ARCHIVE
|
||||
or not re.fullmatch(r'[a-f0-9]{64}', spec['sha256'])):
|
||||
raise ValueError('Invalid q2f requirement')
|
||||
parent = pathlib.Path(storage) / 'q2f' / 'runtimes'
|
||||
if parent.is_symlink():
|
||||
raise ValueError('q2f storage must not be a symlink')
|
||||
parent.mkdir(parents=True, exist_ok=True)
|
||||
cached = parent / identity
|
||||
if cached.exists() or cached.is_symlink():
|
||||
validate(cached, identity)
|
||||
return cached
|
||||
with tempfile.TemporaryDirectory(prefix='.download-', dir=parent) as scratch:
|
||||
scratch = pathlib.Path(scratch)
|
||||
archive = scratch / archive_name
|
||||
download(spec, archive)
|
||||
payload = scratch / 'payload'
|
||||
extract(archive, payload, identity)
|
||||
payload.rename(cached)
|
||||
return cached
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
if len(sys.argv) != 3:
|
||||
raise ValueError('Usage: q2f-runtime.py DESCRIPTOR APK_STORAGE')
|
||||
print(prepare(*sys.argv[1:]), flush=True)
|
||||
except (KeyError, ValueError, OSError, tarfile.TarError) as error:
|
||||
print('Framely q2f: ' + str(error), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
+22
-2
@@ -417,7 +417,7 @@
|
||||
"正式版": "Stable",
|
||||
"测试版": "Testing",
|
||||
"仅检查正式版。": "Check stable releases only.",
|
||||
"仅检查测试版(Preview、Beta、RC 等)。": "Check testing releases only (Preview, Beta, RC, etc.).",
|
||||
"检查正式版和测试版(Preview、Beta、RC 等),选择最新版本。": "Check stable and testing releases (Preview, Beta, RC, etc.) and select the newest version.",
|
||||
"所选渠道暂无可用发行版本。": "No release is available in the selected channel.",
|
||||
"所选版本早于当前版本,安装将切换到较旧版本。": "The selected release is older than your current version. Installing will switch to that older version.",
|
||||
"通知": "Notifications",
|
||||
@@ -1279,6 +1279,26 @@
|
||||
"其他容器文件": "Other container files",
|
||||
"暂无数据": "No data yet",
|
||||
"其他磁盘": "Other drive",
|
||||
"{0} 项": "{0} items"
|
||||
"{0} 项": "{0} items",
|
||||
"自定义 Steam 名称": "Custom Steam name",
|
||||
"Steam 显示名称": "Steam display name",
|
||||
"分别设置应用在 Steam 中显示的名称。留空恢复应用原名;更新 APK 后保留。Steam 不可用时将在就绪后同步。": "Set each app’s name in Steam. Leave blank to use its original name. Names survive APK updates and sync when Steam is ready.",
|
||||
"Invalid Steam display name": "Invalid Steam display name",
|
||||
"Steam display name must be at most 128 characters without control characters": "Steam display name must be at most 128 characters without control characters",
|
||||
"Steam name update was not acknowledged": "Steam name update was not acknowledged",
|
||||
"Quest 兼容转换": "Quest compatibility conversion",
|
||||
"这是一个 Quest 游戏?": "Is this a Quest game?",
|
||||
"打开此选项将尝试进行兼容转换,但不保证一定成功": "Turn this on to try a compatibility conversion. Success is not guaranteed.",
|
||||
"此 APK 已完成兼容转换并重新签名。": "This APK has been converted and re-signed.",
|
||||
"可选:使用独立 q2f 工具包转换并重新签名 APK。首次使用会下载工具包,转换结果仍需在 Frame 上验证。": "Optional: convert and re-sign this APK with the separate q2f package. The package downloads on first use; the result still needs testing on Frame.",
|
||||
"已转换": "Converted",
|
||||
"转换此 APK": "Convert this APK",
|
||||
"准备 Quest 转换工具": "Preparing Quest converter",
|
||||
"正在转换 APK": "Converting APK",
|
||||
"校验转换结果": "Verifying converted APK",
|
||||
"转换完成,请确认安装。": "Conversion complete. Review the APK before installing.",
|
||||
"正在检查转换工具": "Checking converter",
|
||||
"工具包已缓存": "Converter cached",
|
||||
"首次使用需下载 {0} 工具包": "First use downloads the {0} converter"
|
||||
}
|
||||
}
|
||||
+22
-2
@@ -419,7 +419,7 @@
|
||||
"正式版": "正式版",
|
||||
"测试版": "测试版",
|
||||
"仅检查正式版。": "仅检查正式版。",
|
||||
"仅检查测试版(Preview、Beta、RC 等)。": "仅检查测试版(Preview、Beta、RC 等)。",
|
||||
"检查正式版和测试版(Preview、Beta、RC 等),选择最新版本。": "检查正式版和测试版(Preview、Beta、RC 等),选择最新版本。",
|
||||
"所选渠道暂无可用发行版本。": "所选渠道暂无可用发行版本。",
|
||||
"所选版本早于当前版本,安装将切换到较旧版本。": "所选版本早于当前版本,安装将切换到较旧版本。",
|
||||
"通知": "通知",
|
||||
@@ -1279,6 +1279,26 @@
|
||||
"其他容器文件": "其他容器文件",
|
||||
"暂无数据": "暂无数据",
|
||||
"其他磁盘": "其他磁盘",
|
||||
"{0} 项": "{0} 项"
|
||||
"{0} 项": "{0} 项",
|
||||
"自定义 Steam 名称": "自定义 Steam 名称",
|
||||
"Steam 显示名称": "Steam 显示名称",
|
||||
"分别设置应用在 Steam 中显示的名称。留空恢复应用原名;更新 APK 后保留。Steam 不可用时将在就绪后同步。": "分别设置应用在 Steam 中显示的名称。留空恢复应用原名;更新 APK 后保留。Steam 不可用时将在就绪后同步。",
|
||||
"Invalid Steam display name": "无效的 Steam 显示名称",
|
||||
"Steam display name must be at most 128 characters without control characters": "Steam 显示名称最多 128 个字符,不能包含控制字符",
|
||||
"Steam name update was not acknowledged": "Steam 未确认名称更新",
|
||||
"Quest 兼容转换": "Quest 兼容转换",
|
||||
"这是一个 Quest 游戏?": "这是一个 Quest 游戏?",
|
||||
"打开此选项将尝试进行兼容转换,但不保证一定成功": "打开此选项将尝试进行兼容转换,但不保证一定成功",
|
||||
"此 APK 已完成兼容转换并重新签名。": "此 APK 已完成兼容转换并重新签名。",
|
||||
"可选:使用独立 q2f 工具包转换并重新签名 APK。首次使用会下载工具包,转换结果仍需在 Frame 上验证。": "可选:使用独立 q2f 工具包转换并重新签名 APK。首次使用会下载工具包,转换结果仍需在 Frame 上验证。",
|
||||
"已转换": "已转换",
|
||||
"转换此 APK": "转换此 APK",
|
||||
"准备 Quest 转换工具": "准备 Quest 转换工具",
|
||||
"正在转换 APK": "正在转换 APK",
|
||||
"校验转换结果": "校验转换结果",
|
||||
"转换完成,请确认安装。": "转换完成,请确认安装。",
|
||||
"正在检查转换工具": "正在检查转换工具",
|
||||
"工具包已缓存": "工具包已缓存",
|
||||
"首次使用需下载 {0} 工具包": "首次使用需下载 {0} 工具包"
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@ import {t} from './i18n';
|
||||
import {installKeyboard} from '../../sdk/src/keyboard';
|
||||
import {installHoverFeedback} from '../../sdk/src/hover';
|
||||
export async function api<T=any>(method:string,params:unknown={},signal?:AbortSignal):Promise<T>{const r=await fetch('/api',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({method,params}),signal});if(r.status===401&&r.headers.get('X-Framely-Reauthenticate')==='1')location.replace('/manager');if(!r.ok)throw new Error(t('服务请求失败:{0}',{0:r.status}));const v=await r.json();if(v.error)throw new Error(t(v.error));return v.result;}
|
||||
export function viewKey(){const p=location.pathname.split('/');return p[1]==='manager'?'framely.manager':p[1]==='window'?`framely.window.${p[2]}.${p[3]}`:p[1]==='cast'&&p[2]==='window'?`framely.cast.${p[3]}`:p[1]==='notifications'?'notifications':p[1]==='launcher'?'launcher':'menu';}
|
||||
export function viewKey(){const p=location.pathname.split('/');return p[1]==='manager'?'framely.manager':p[1]==='window'?`framely.window.${p[2]}.${p[3]}`:p[1]==='cast'&&p[2]==='window'?`framely.cast.${p[3]}`:p[1]==='apk'&&p[2]==='permission'?'framely.apk.permission':p[1]==='notifications'?'notifications':p[1]==='launcher'?'launcher':'menu';}
|
||||
installKeyboard(params=>api('host.keyboard',{view:viewKey(),...params}));
|
||||
|
||||
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import React from 'react';
|
||||
import {IconFolder,IconInfoCircle} from '@tabler/icons-react';
|
||||
import {IconBrandMeta,IconFolder,IconInfoCircle} from '@tabler/icons-react';
|
||||
import {PluginImage} from './store';
|
||||
import {Select} from './localized-select';
|
||||
import {Switch} from './switch';
|
||||
import {t} from './i18n';
|
||||
|
||||
type Metadata={name:string;package:string;version:string;versionCode:number;minSdk:number;icon?:string;activities:string[];abis:string[]};
|
||||
type Props={metadata:Metadata;size:string;previous?:Metadata;updating:boolean;containerName:string;running:boolean;displayMode:string;busy:boolean;error:string;onDisplayMode:(value:string)=>void;onStop:()=>void;onCancel:()=>void;onConfirm:()=>void};
|
||||
export function ApkInstallReview({metadata,size,previous,updating,containerName,running,displayMode,busy,error,onDisplayMode,onStop,onCancel,onConfirm}:Props){
|
||||
type Props={metadata:Metadata;size:string;previous?:Metadata;updating:boolean;containerName:string;running:boolean;displayMode:string;busy:boolean;error:string;converted:boolean;q2f?:{cached:boolean;size:string};q2fError?:string;onDisplayMode:(value:string)=>void;onStop:()=>void;onCancel:()=>void;onConvert:()=>void;onRevert:()=>void;onConfirm:()=>void};
|
||||
export function ApkInstallReview({metadata,size,previous,updating,containerName,running,displayMode,busy,error,converted,q2f,q2fError,onDisplayMode,onStop,onCancel,onConvert,onRevert,onConfirm}:Props){
|
||||
const mismatch=!!previous&&previous.package!==metadata.package;
|
||||
return <div className="apk-install-review">
|
||||
<h2>{t(updating?'确认更新 APK':'确认安装 APK')}</h2>
|
||||
<p className="apk-install-intro">{t(updating?'更新应用并保留现有存档和设置。':'核对应用信息,选择合适的显示方式。')}</p>
|
||||
<header className="apk-install-app"><PluginImage kind="lepton" name={metadata.name} src={metadata.icon} size={60}/><div><h3>{metadata.name}</h3><code>{metadata.package}</code><p>{t('版本')} {previous&&`${previous.version} → `}{metadata.version||t('未声明')} <span>·</span> {size}</p></div></header>
|
||||
<section className="apk-install-location" aria-label={t('目标容器')}><IconFolder size={23} aria-hidden="true"/><div><b>{t(updating?'保留原容器':'创建独立容器')}</b>{updating&&<code>{containerName}</code>}<small>{t('每个新应用使用独立容器,更新保留原容器。')}</small></div></section>
|
||||
<section className="apk-install-option apk-quest-option"><IconBrandMeta size={25} stroke={1.7} aria-hidden="true"/><div><b>{t('这是一个 Quest 游戏?')}</b><small>{t('打开此选项将尝试进行兼容转换,但不保证一定成功')}</small>{!converted&&<small>{q2fError?q2fError:!q2f?t('正在检查转换工具'):q2f.cached?t('工具包已缓存'):t('首次使用需下载 {0} 工具包',{0:q2f.size})}</small>}</div><Switch label={t('这是一个 Quest 游戏?')} checked={converted} disabled={busy||(!converted&&(!q2f||!!q2fError))} onChange={checked=>checked?onConvert():onRevert()}/></section>
|
||||
<section className="apk-install-option apk-install-location" aria-label={t('目标容器')}><IconFolder size={23} aria-hidden="true"/><div><b>{t(updating?'保留原容器':'创建独立容器')}</b>{updating&&<code>{containerName}</code>}<small>{t('每个新应用使用独立容器,更新保留原容器。')}</small></div><Switch label={t(updating?'保留原容器':'创建独立容器')} checked disabled onChange={()=>{}}/></section>
|
||||
<div className="apk-install-display"><div><b>{t('显示方式')}</b><small>{t(displayMode==='vr'?'隐藏二维窗口,应用本身需要支持 VR。':'通过二维窗口显示并操作应用。')}</small></div><Select label={t('显示方式')} value={displayMode} disabled={busy} onChange={onDisplayMode} options={[{value:'flat',label:t('平面窗口')},{value:'vr',label:t('VR 应用')}]}/></div>
|
||||
<details className="apk-install-technical"><summary>{t('查看 APK 详情')}</summary><dl className="apk-meta"><dt>{t('版本代码')}</dt><dd>{metadata.versionCode}</dd><dt>{t('最低 Android SDK')}</dt><dd>{metadata.minSdk||t('未声明')}</dd><dt>{t('架构')}</dt><dd>{metadata.abis.join(', ')||t('未声明')}</dd><dt>{t('启动入口')}</dt><dd>{metadata.activities.length||t('未发现启动入口')}</dd></dl></details>
|
||||
{updating&&<div className="apk-install-update-note"><IconInfoCircle size={21} aria-hidden="true"/><div><p>{t('同包名更新保留数据;签名不匹配或降级不会自动卸载重装。')}</p><small>{t('共享容器的备份需手动恢复;独立侧载容器支持一键恢复。')}</small></div></div>}
|
||||
|
||||
@@ -9,5 +9,18 @@
|
||||
.apk-uninstall>h2{margin-bottom:8px}.apk-uninstall-intro{font-size:17px;line-height:1.6;color:var(--muted);margin-bottom:24px}.apk-uninstall-app{display:flex;align-items:center;gap:16px;margin:0 0 24px}.apk-uninstall-app>div{min-width:0}.apk-uninstall-app h3{margin:0 0 5px;font-size:23px}.apk-uninstall-app code{display:block;background:none;padding:0;font-size:15px;color:var(--muted);overflow-wrap:anywhere}.apk-uninstall-app small{display:block;margin-top:6px;font-size:15px}.apk-uninstall-options{border-top:1px solid var(--line);padding:8px 0}.apk-uninstall-options .switch-row{padding:16px 0;gap:20px}.apk-uninstall-options .switch-row small{font-size:16px;line-height:1.55}.apk-uninstall-result{display:flex;align-items:flex-start;gap:10px;padding:14px 16px;background:var(--control-hover);border-radius:5px;font-size:17px;line-height:1.55}.apk-uninstall-result p{margin:0}.apk-uninstall-result svg{margin-top:2px}.apk-uninstall-result small{display:block;font-size:15px;margin-top:4px}.apk-uninstall-result.destructive{color:#efa9a8}.apk-uninstall-result.destructive small{color:inherit}.apk-uninstall footer button{white-space:nowrap}.apk-uninstall footer .danger{font-weight:600;background:#362627;border-color:#895b5b}.apk-uninstall footer .danger:hover:not(:disabled){background:#493032}@media(max-width:700px){.apk-uninstall-app{align-items:flex-start}.apk-uninstall footer{display:grid;grid-template-columns:1fr}.apk-uninstall footer .danger{grid-row:1}.apk-uninstall-options .switch-row{gap:12px}}
|
||||
|
||||
.apk-install-review>h2{margin-bottom:8px}.apk-install-intro{font-size:17px;line-height:1.6;color:var(--muted);margin-bottom:24px}.apk-install-app{display:flex;align-items:center;gap:16px;margin-bottom:24px}.apk-install-app>div{min-width:0}.apk-install-app h3{font-size:23px;margin:0 0 5px}.apk-install-app code,.apk-install-location code{background:none;padding:0;font-size:15px;color:var(--muted)}.apk-install-app p{margin:6px 0 0;font-size:16px;color:var(--muted)}.apk-install-app p span{margin:0 6px}.apk-install-location{display:flex;gap:12px;padding:18px 0;border-top:1px solid var(--line);border-bottom:1px solid var(--line)}.apk-install-location svg{flex:none;margin-top:3px;color:var(--muted)}.apk-install-location b,.apk-install-display b{font-size:19px;font-weight:500}.apk-install-location small,.apk-install-display small{display:block;font-size:16px;line-height:1.55;color:var(--muted);margin-top:5px}.apk-install-location code{margin-top:6px;overflow-wrap:anywhere}.apk-install-display{display:flex;gap:20px;align-items:center;padding:22px 0}.apk-install-display>div:first-child{flex:1;min-width:0}.apk-install-display>.framely-select{flex:0 0 200px}.apk-install-technical{font-size:17px;color:var(--muted)}.apk-install-technical summary{cursor:pointer;padding:8px 0}.apk-install-technical .apk-meta{font-size:16px;margin:16px 0}.apk-install-technical dd{color:var(--text)}.apk-install-update-note{display:flex;gap:10px;margin-top:20px;font-size:16px;line-height:1.55;color:var(--muted)}.apk-install-update-note svg{flex:none;margin-top:3px}.apk-install-update-note p{margin:0}.apk-install-update-note small{display:block;font-size:15px;margin-top:6px}.apk-install-review footer button{white-space:nowrap}@media(max-width:700px){.apk-install-app{align-items:flex-start}.apk-install-display{flex-wrap:wrap;gap:12px}.apk-install-display>.framely-select{flex:1 1 100%}.apk-install-review footer{display:grid;grid-template-columns:1fr}.apk-install-review footer .primary{grid-row:1}}
|
||||
.apk-quest-option{display:flex;align-items:center;justify-content:space-between;gap:20px;padding:18px 0;border-top:1px solid var(--line)}.apk-quest-option>div{flex:1;min-width:0}.apk-quest-option b{display:block;font-size:19px;font-weight:500}.apk-quest-option small{display:block;margin-top:5px;color:var(--muted);font-size:15px;line-height:1.5}.apk-quest-option button{flex:none;margin:0}.apk-quest-option .badge{white-space:nowrap}@media(max-width:700px){.apk-quest-option{align-items:flex-start;flex-wrap:wrap}.apk-quest-option button{width:100%}}
|
||||
|
||||
.apk-install-option{display:flex;align-items:center;gap:14px;padding:18px 0;border-top:1px solid var(--line)}
|
||||
.apk-install-option>svg{flex:none;color:var(--muted)}
|
||||
.apk-install-option>div{flex:1;min-width:0}
|
||||
.apk-install-option b{display:block;font-size:19px;font-weight:500}
|
||||
.apk-install-option small{display:block;margin-top:5px;color:var(--muted);font-size:15px;line-height:1.5}
|
||||
.apk-install-option .ui-switch{flex:none;width:60px;min-width:60px;margin:0}
|
||||
.apk-install-location.apk-install-option{border-top:1px solid var(--line);border-bottom:1px solid var(--line)}
|
||||
.apk-install-location.apk-install-option .ui-switch:disabled{opacity:1;cursor:default}
|
||||
@media(max-width:700px){.apk-quest-option.apk-install-option{align-items:center;flex-wrap:nowrap}.apk-quest-option.apk-install-option .ui-switch{width:60px}}
|
||||
|
||||
.apk-trigger-setting{display:flex;align-items:center;gap:24px;padding:18px 0}.apk-trigger-setting>div:first-child{flex:1;min-width:0}.apk-trigger-setting label{margin:0}.apk-trigger-setting b{font-size:19px}.apk-trigger-setting small{display:block;font-size:17px;color:var(--muted);line-height:1.55;margin-top:5px}.apk-trigger-controls{display:flex;align-items:center;gap:16px;flex:0 0 390px}.apk-trigger-controls>div{display:flex;align-items:center;gap:12px;flex:1;min-width:0}.apk-trigger-controls input[type=range]{width:100%;min-width:0;accent-color:var(--blue);padding:0;margin:0;min-height:44px;cursor:pointer}.apk-trigger-controls output{font-size:18px;min-width:48px;text-align:right;font-variant-numeric:tabular-nums}.apk-trigger-controls button{margin:0}@media(max-width:700px){.apk-trigger-setting{flex-wrap:wrap;gap:12px}.apk-trigger-setting>div:first-child{flex-basis:100%}.apk-trigger-controls{flex:1 1 100%}}
|
||||
|
||||
.apk-steam-names{width:100%;margin-bottom:24px}.apk-steam-names>p{color:var(--muted);line-height:1.55}.apk-steam-name{display:flex;align-items:center;gap:24px;padding:18px 0;border-bottom:1px solid var(--line);width:100%}.apk-steam-name .apk-copy code{display:block;margin-top:6px;color:var(--muted)}.apk-steam-name-controls{display:flex;align-items:center;gap:12px;flex:0 1 50%;min-width:0}.apk-steam-name-controls input{flex:1;min-width:0;margin:0}.apk-steam-name-controls button{flex:none;margin:0}@media(max-width:700px){.apk-steam-name{flex-wrap:wrap;gap:12px}.apk-steam-name-controls{flex-basis:100%}}
|
||||
+22
-10
@@ -13,32 +13,44 @@ import {ApkUninstall} from './apk-uninstall';
|
||||
import {ApkInstallReview} from './apk-install-review';
|
||||
import {GamepadTriggerSetting} from './gamepad-trigger-setting';
|
||||
type Metadata={package:string;name:string;version:string;versionCode:number;minSdk:number;activities:string[];declaredActivities:string[];icon?:string;abis:string[];vr:boolean};
|
||||
type App={steamLaunch?:boolean;steamRegistered?:boolean;steamRegistrationError?:string;stateKnown?:boolean;id:string;context:string;metadata:Metadata;installed:boolean;running:boolean;managed:boolean;steam:boolean;size:number;pending?:string;activity?:string;showWindow?:boolean|null;orientation?:string|null;framebufferCompatibility?:boolean};
|
||||
type App={steamName?:string|null;steamLaunch?:boolean;steamRegistered?:boolean;steamRegistrationError?:string;stateKnown?:boolean;id:string;context:string;metadata:Metadata;installed:boolean;running:boolean;managed:boolean;steam:boolean;size:number;pending?:string;activity?:string;showWindow?:boolean|null;orientation?:string|null;framebufferCompatibility?:boolean};
|
||||
type Container={acceptsAdditionalApps?:boolean;id:string;name:string;baked:string;running:boolean;managed:boolean;steam:boolean};
|
||||
type Data={apps:App[];containers:Container[];warnings:string[];roots:string[];available:boolean;retainSteamEntries?:boolean;gamepadEnabled?:boolean;gamepadSource?:string;gamepadRumble?:boolean;gamepadTriggerThreshold?:number;autoStopContainer?:boolean;stopContainerOnClose?:boolean};
|
||||
type Cleanup={id:string;kind:string;name:string;bytes:number;sensitive:boolean;app?:string;context?:string;restorable?:boolean;unknown?:boolean};
|
||||
type Review={ticket:string;metadata:Metadata;bytes:number};
|
||||
type Review={ticket:string;metadata:Metadata;bytes:number;q2fVersion?:string};
|
||||
type Q2fStatus={id:string;bytes:number;cached:boolean};
|
||||
type Confirm={operation:string;app?:App;container?:Container;backup?:string;items?:string[];title:string;description:string;purge?:boolean;deleteContainer?:boolean};
|
||||
function bytes(n:number){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KiB`:n<1024**3?`${(n/1024**2).toFixed(1)} MiB`:`${(n/1024**3).toFixed(2)} GiB`;}
|
||||
const phases:Record<string,string>={loading:'正在读取',preparing:'准备中',uploading:'上传 APK',inspecting:'校验 APK',starting:'启动容器',launching:'启动应用',started:'应用已启动,正在检查',installing:'安装 APK',verifying:'核对安装结果','backing-up':'备份容器数据',uninstalling:'卸载应用',done:'完成',failed:'失败',cancelled:'操作已取消'};
|
||||
const phases:Record<string,string>={loading:'正在读取',preparing:'准备中',uploading:'上传 APK',inspecting:'校验 APK',starting:'启动容器',launching:'启动应用',started:'应用已启动,正在检查',installing:'安装 APK',verifying:'核对安装结果','backing-up':'备份容器数据',uninstalling:'卸载应用','q2f-preparing':'准备 Quest 转换工具','q2f-converting':'正在转换 APK','q2f-verifying':'校验转换结果',done:'完成',failed:'失败',cancelled:'操作已取消'};
|
||||
const operationLabels:Record<string,string>={'steam.settings':'保存 Steam 启动设置','steam.retention.settings':'保存 Steam 入口设置','lifecycle.settings':'保存容器退出设置','gamepad.settings':'保存手柄设置',install:'安装 APK',launch:'启动应用',close:'关闭应用',uninstall:'卸载应用',purge:'清除保留数据',clear:'清除应用数据',reconcile:'核对应用状态',settings:'保存设置','container.start':'启动容器','container.stop':'停止容器','container.delete':'删除容器',restore:'恢复备份',cleanup:'数据清理','root.add':'添加数据位置','root.remove':'移除数据位置'};
|
||||
function SteamNameSetting({app,busy,onSave}:{app:App;busy:boolean;onSave:(name:string)=>void}){
|
||||
const [name,setName]=useState(app.steamName??'');
|
||||
useEffect(()=>setName(app.steamName??''),[app.id,app.steamName]);
|
||||
return <form className="apk-steam-name" onSubmit={e=>{e.preventDefault();onSave(name);}}>
|
||||
<div className="apk-copy"><b>{t('Steam 显示名称')}</b>{app.steamRegistrationError&&<p className="error">{app.steamRegistrationError}</p>}</div>
|
||||
<div className="apk-steam-name-controls"><input aria-label={`${t('Steam 显示名称')} · ${app.metadata.name}`} placeholder={app.metadata.name} value={name} maxLength={128} disabled={busy} onChange={e=>setName(e.target.value)}/><button type="submit" disabled={busy||name.trim()===(app.steamName??'')}>{t('保存')}</button></div>
|
||||
</form>;
|
||||
}
|
||||
export function ApkManager({view:externalView,onViewChange}:{view?:string;onViewChange?:(view:string)=>void}={}){
|
||||
const[data,setData]=useState<Data>({apps:[],containers:[],warnings:[],roots:[],available:true}),[loading,setLoading]=useState(true),[localView,setLocalView]=useState('apps'),[filter,setFilter]=useState('installed'),[query,setQuery]=useState(''),[error,setError]=useState(''),[review,setReview]=useState<Review|null>(null),[target,setTarget]=useState(''),[displayMode,setDisplayMode]=useState('flat'),[updating,setUpdating]=useState<App|null>(null),[details,setDetails]=useState<App|null>(null),[confirm,setConfirm]=useState<Confirm|null>(null),[job,setJob]=useState<(Job&{cancellable?:boolean;operation?:string})|null>(null),[busy,setBusy]=useState(false),[cleanup,setCleanup]=useState<Cleanup[]>([]),[selected,setSelected]=useState<string[]>([]),[log,setLog]=useState<{name:string;text:string}|null>(null),[path,setPath]=useState(''),[contextName,setContextName]=useState(''),[notice,setNotice]=useState('');
|
||||
const[data,setData]=useState<Data>({apps:[],containers:[],warnings:[],roots:[],available:true}),[loading,setLoading]=useState(true),[localView,setLocalView]=useState('apps'),[filter,setFilter]=useState('installed'),[query,setQuery]=useState(''),[error,setError]=useState(''),[review,setReview]=useState<Review|null>(null),[originalReview,setOriginalReview]=useState<Review|null>(null),[q2f,setQ2f]=useState<Q2fStatus|null>(null),[q2fError,setQ2fError]=useState(''),[target,setTarget]=useState(''),[displayMode,setDisplayMode]=useState('flat'),[updating,setUpdating]=useState<App|null>(null),[details,setDetails]=useState<App|null>(null),[confirm,setConfirm]=useState<Confirm|null>(null),[job,setJob]=useState<(Job&{cancellable?:boolean;operation?:string})|null>(null),[busy,setBusy]=useState(false),[cleanup,setCleanup]=useState<Cleanup[]>([]),[selected,setSelected]=useState<string[]>([]),[log,setLog]=useState<{name:string;text:string}|null>(null),[path,setPath]=useState(''),[contextName,setContextName]=useState(''),[notice,setNotice]=useState('');
|
||||
const view=externalView??localView;const setView=(value:string)=>{setLocalView(value);onViewChange?.(value);};
|
||||
useEffect(()=>{if(view==='cleanup')void loadCleanup();},[view]);
|
||||
useEffect(()=>{if(!review||review.q2fVersion){setQ2f(null);setQ2fError('');return;}let active=true;setQ2f(null);setQ2fError('');void api<Q2fStatus>('apk.q2f.status').then(value=>{if(active)setQ2f(value);}).catch(e=>{if(active)setQ2fError(String(e));});return()=>{active=false;};},[review?.ticket]);
|
||||
const input=useRef<HTMLInputElement>(null),controller=useRef<AbortController|null>(null),selection=useRef<{app:string;uninstall:boolean}|null>(null),alive=useRef(true),busyRef=useRef(false);
|
||||
const updateJob=(v:Job)=>{if(alive.current)setJob(v);};
|
||||
async function resumeOperation(){let ownsBusy=false;try{const active=await api<{job?:string}>('apk.operation.active');if(!active.job||!alive.current||busyRef.current)return;ownsBusy=true;busyRef.current=true;setBusy(true);while(alive.current){const value=await api<Job&{cancellable?:boolean;operation?:string}>('job.status',{job:active.job});if(['done','failed','cancelled'].includes(value.phase)){setJob(null);if(value.phase==='failed')setError(t(value.error??'操作失败'));else setNotice(t('操作完成'));await refresh();break;}setJob(value);await new Promise(resolve=>setTimeout(resolve,300));}}catch(e){if(alive.current)setError(String(e));}finally{if(ownsBusy&&alive.current){busyRef.current=false;setBusy(false);}}}
|
||||
async function resumeOperation(){let ownsBusy=false;try{const active=await api<{job?:string}>('apk.operation.active');let saved:{job:string;app:App|null;context:string;review?:Review}|null=null;try{saved=JSON.parse(sessionStorage.getItem('framely.apk.q2f.job')||'null');}catch{}const id=active.job||saved?.job;if(!id||!alive.current||busyRef.current)return;ownsBusy=true;busyRef.current=true;setBusy(true);while(alive.current){const value=await api<Job&{cancellable?:boolean;operation?:string}>('job.status',{job:id});if(['done','failed','cancelled'].includes(value.phase)){setJob(null);if(saved?.job===id)sessionStorage.removeItem('framely.apk.q2f.job');if(value.phase==='failed')setError(t(value.error??'操作失败'));else if(value.result?.q2fVersion){setReview(value.result);setOriginalReview(saved?.review??null);setDisplayMode('vr');setUpdating(saved?.app??null);setTarget(saved?.context??'');setNotice(t('转换完成,请确认安装。'));}else setNotice(t('操作完成'));await refresh();break;}setJob(value);await new Promise(resolve=>setTimeout(resolve,300));}}catch(e){if(alive.current)setError(String(e));}finally{if(ownsBusy&&alive.current){busyRef.current=false;setBusy(false);}}}
|
||||
useEffect(()=>{if(data.retainSteamEntries===false||!data.apps.some(a=>a.installed&&!a.steam&&a.stateKnown!==false&&!a.pending&&(a.metadata.activities.length||a.activity)&&(a.steamLaunch??true)&&!a.steamRegistered))return;const timer=setInterval(()=>{if(!busyRef.current)void refresh();},20000);return()=>clearInterval(timer);},[data.apps,data.retainSteamEntries]);
|
||||
async function refresh(){setLoading(true);try{const r=await runJob('apk.list.start');if(alive.current){setData(r.result);setDetails(old=>old?r.result.apps.find((a:App)=>a.id===old.id)??null:null);}}catch(e){if(alive.current)setError(String(e));}finally{if(alive.current)setLoading(false);}}
|
||||
useEffect(()=>{alive.current=true;void refresh();void resumeOperation();const select=(e:Event)=>{const v=(e as CustomEvent).detail;if(v?.kind==='apk.selection'){selection.current={app:v.app,uninstall:!!v.uninstall};void refresh();}};window.addEventListener('framely.event',select);return()=>{alive.current=false;window.removeEventListener('framely.event',select);controller.current?.abort();};},[]);
|
||||
useEffect(()=>{if(selection.current){const a=data.apps.find(a=>a.id===selection.current!.app);if(a){if(a.steam){setError(t('请通过 Steam 管理此应用。'));selection.current=null;return;}if(selection.current.uninstall)askUninstall(a);else setDetails(a);selection.current=null;}}},[data]);
|
||||
useEffect(()=>{const close=(e:Event)=>{if(e instanceof KeyboardEvent&&e.key!=='Escape')return;if(busyRef.current)return;if(confirm)setConfirm(null);else if(log)setLog(null);else if(review)void discard();else setDetails(null);};window.addEventListener('keydown',close);window.addEventListener('framely.back',close);return()=>{window.removeEventListener('keydown',close);window.removeEventListener('framely.back',close);};},[confirm,log,review]);
|
||||
useEffect(()=>{const dialog=document.querySelector<HTMLElement>('.apk-dialog');if(!dialog)return;const prev=document.activeElement as HTMLElement;const controls=()=>Array.from(dialog.querySelectorAll<HTMLElement>('button:not(:disabled),input,select,a[href]')).filter(e=>e.getClientRects().length);controls()[0]?.focus();const key=(e:KeyboardEvent)=>{if(e.key!=='Tab')return;const a=controls();if(!a.length)return;if(e.shiftKey&&(document.activeElement===a[0]||!dialog.contains(document.activeElement))){e.preventDefault();a.at(-1)?.focus();}else if(!e.shiftKey&&(document.activeElement===a.at(-1)||!dialog.contains(document.activeElement))){e.preventDefault();a[0].focus();}};document.addEventListener('keydown',key);return()=>{document.removeEventListener('keydown',key);prev?.focus();};},[review,details,confirm,log,job?.id]);
|
||||
async function discard(){if(review)await api('apk.review.drop',{ticket:review.ticket}).catch(()=>{});setReview(null);setUpdating(null);}
|
||||
async function inspect(file:File|string,selectedApp:App|null=updating){if(!(typeof file==='string'?file:file.name).toLowerCase().endsWith('.apk')){setError(t('第一版仅支持单个 APK 文件。'));return;}setBusy(true);busyRef.current=true;setError('');const c=new AbortController();controller.current=c;setJob(typeof file==='string'?{id:'local',kind:'apk',phase:'inspecting',received:0,cancellable:false}:{id:'upload',kind:'apk',phase:'uploading',received:0,total:file.size});try{let result;if(typeof file==='string'){const response=await fetch('/host/files/apk-inspect',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({paths:[file]}),signal:c.signal});if(!response.ok)throw new Error(t('服务请求失败:{0}',{0:response.status}));const data=await response.json();if(data.error)throw new Error(t(data.error));result=await waitJob(data.result.job,updateJob);}else{const upload=await uploadFile(file,c.signal,percent=>setJob(j=>j?{...j,received:Math.round(file.size*percent/100)}:null),{start:size=>api('apk.upload.start',{size}),chunk:uploadChunk,abort:upload=>api('upload.abort',{upload})});result=await runJob('apk.inspect.start',{upload},updateJob);}if(!alive.current){await api('apk.review.drop',{ticket:result.result.ticket}).catch(()=>{});return;}setReview(result.result);setDisplayMode((selectedApp?.showWindow??!result.result.metadata.vr)?'flat':'vr');setTarget(selectedApp?.context??'');setJob(null);}catch(e){setJob(null);setError(String(e));}finally{setBusy(false);busyRef.current=false;controller.current=null;}}
|
||||
async function discard(){if(review)await api('apk.review.drop',{ticket:review.ticket}).catch(()=>{});if(originalReview)await api('apk.review.drop',{ticket:originalReview.ticket}).catch(()=>{});setReview(null);setOriginalReview(null);setUpdating(null);}
|
||||
async function convert(){if(!review||review.q2fVersion)return;setBusy(true);busyRef.current=true;setError('');try{const started=await api<{job:string}>('apk.q2f.start',{ticket:review.ticket});sessionStorage.setItem('framely.apk.q2f.job',JSON.stringify({job:started.job,app:updating,context:target,review}));const result=await waitJob(started.job,updateJob);sessionStorage.removeItem('framely.apk.q2f.job');setOriginalReview(review);setReview(result.result);setDisplayMode('vr');}catch(e){sessionStorage.removeItem('framely.apk.q2f.job');setError(String(e));}finally{setJob(null);setBusy(false);busyRef.current=false;}}
|
||||
async function revertConversion(){if(!review?.q2fVersion||!originalReview)return;setBusy(true);try{await api('apk.review.drop',{ticket:review.ticket});setReview(originalReview);setOriginalReview(null);setDisplayMode((updating?.showWindow??!originalReview.metadata.vr)?'flat':'vr');setError('');}catch(e){setError(String(e));}finally{setBusy(false);}}
|
||||
async function inspect(file:File|string,selectedApp:App|null=updating){if(!(typeof file==='string'?file:file.name).toLowerCase().endsWith('.apk')){setError(t('第一版仅支持单个 APK 文件。'));return;}setBusy(true);busyRef.current=true;setError('');const c=new AbortController();controller.current=c;setJob(typeof file==='string'?{id:'local',kind:'apk',phase:'inspecting',received:0,cancellable:false}:{id:'upload',kind:'apk',phase:'uploading',received:0,total:file.size});try{let result;if(typeof file==='string'){const response=await fetch('/host/files/apk-inspect',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({paths:[file]}),signal:c.signal});if(!response.ok)throw new Error(t('服务请求失败:{0}',{0:response.status}));const data=await response.json();if(data.error)throw new Error(t(data.error));result=await waitJob(data.result.job,updateJob);}else{const upload=await uploadFile(file,c.signal,percent=>setJob(j=>j?{...j,received:Math.round(file.size*percent/100)}:null),{start:size=>api('apk.upload.start',{size}),chunk:uploadChunk,abort:upload=>api('upload.abort',{upload})});result=await runJob('apk.inspect.start',{upload},updateJob);}if(!alive.current){await api('apk.review.drop',{ticket:result.result.ticket}).catch(()=>{});return;}setOriginalReview(null);setReview(result.result);setDisplayMode((selectedApp?.showWindow??!result.result.metadata.vr)?'flat':'vr');setTarget(selectedApp?.context??'');setJob(null);}catch(e){setJob(null);setError(String(e));}finally{setBusy(false);busyRef.current=false;controller.current=null;}}
|
||||
function choose(a?:App){setUpdating(a??null);if(input.current)openLocalFileInput(input.current,path=>{if(alive.current)void inspect(path,a??null);});}
|
||||
async function perform(operation:string,params:Record<string,unknown>={}){setBusy(true);busyRef.current=true;setError('');setNotice('');try{const r=await runJob('apk.operation.start',{operation,...params},updateJob);setJob(null);setConfirm(null);if(operation==='install'){setReview(null);setUpdating(null);setNotice(t('APK 已安装。应用数据和图标排序会保留。'));}else if(operation==='cleanup'){setNotice(t('已释放 {0},失败 {1} 项。',{0:bytes(r.result.freedBytes),1:r.result.failed.length}));if(r.result.failed.length)setError(r.result.failed.map((v:any)=>`${v.id}: ${v.error}`).join('\n'));await loadCleanup();}else if(operation==='restore')setNotice(t('备份已恢复,请启动应用验证存档;恢复前状态已另行备份。'));else setNotice(t('操作完成'));await refresh();}catch(e){setJob(null);setError(String(e));await refresh();}finally{setBusy(false);busyRef.current=false;}}
|
||||
async function perform(operation:string,params:Record<string,unknown>={}){setBusy(true);busyRef.current=true;setError('');setNotice('');try{const r=await runJob('apk.operation.start',{operation,...params},updateJob);setJob(null);setConfirm(null);if(operation==='install'){if(originalReview)await api('apk.review.drop',{ticket:originalReview.ticket}).catch(()=>{});setOriginalReview(null);setReview(null);setUpdating(null);setNotice(t('APK 已安装。应用数据和图标排序会保留。'));}else if(operation==='cleanup'){setNotice(t('已释放 {0},失败 {1} 项。',{0:bytes(r.result.freedBytes),1:r.result.failed.length}));if(r.result.failed.length)setError(r.result.failed.map((v:any)=>`${v.id}: ${v.error}`).join('\n'));await loadCleanup();}else if(operation==='restore')setNotice(t('备份已恢复,请启动应用验证存档;恢复前状态已另行备份。'));else setNotice(t('操作完成'));await refresh();}catch(e){setJob(null);setError(String(e));await refresh();}finally{setBusy(false);busyRef.current=false;}}
|
||||
function canDeleteContainer(a:App){const members=data.apps.filter(other=>other.context===a.context);const container=data.containers.find(c=>c.id===a.context);return !!container&&!container.steam&&members.length===1&&members[0].id===a.id&&a.stateKnown!==false&&!a.pending;}
|
||||
function askUninstall(a:App){setError('');setConfirm({operation:a.installed?'uninstall':'purge',app:a,title:a.installed?t('卸载应用'):t('清除保留数据'),description:'',purge:!a.installed,deleteContainer:!a.installed&&canDeleteContainer(a)});}
|
||||
async function loadCleanup(){try{const items=await api<Cleanup[]>('apk.cleanup.list');setCleanup(items);setSelected([]);}catch(e){setError(String(e));}}
|
||||
@@ -62,8 +74,8 @@ export function ApkManager({view:externalView,onViewChange}:{view?:string;onView
|
||||
{view==='containers'&&<><div className="apk-list">{data.containers.map(c=><article className="apk-container" key={c.id}><div className="apk-copy"><h2><IconFolder size={24}/>{containerTitle(c)}</h2><code>{c.baked}</code><p>{t(c.steam?'Steam 管理':c.managed?'Framely 管理':'已有侧载容器')} · {t(c.running?'运行中':'已停止')}</p>{!data.apps.some(a=>a.context===c.id&&a.installed)&&<p>{t('未发现已安装的应用,启动容器不会安装 APK。')}</p>}</div><div className="apk-actions"><button disabled={busy} onClick={()=>void showLog(c.id)}><IconFileText size={20}/>{t('日志')}</button>{!c.steam&&<><button disabled={busy} onClick={()=>containerAsk(c,c.running?'container.stop':'container.start')}>{t(c.running?'停止容器':'启动容器')}</button><button className="danger" disabled={busy} onClick={()=>containerAsk(c,'container.delete')}>{t('删除容器')}</button></>}</div></article>)}</div><section className="apk-locations"><h2>{t('其他数据位置')}</h2><p>{t('添加其他工具使用的 baked 数据目录,不移动原有应用。')}</p><div className="apk-filters"><input value={path} placeholder="/path/to/compatdata/baked" aria-label={t('Lepton 数据目录')} onChange={e=>setPath(e.target.value)}/><input value={contextName} placeholder={t('原容器名称(可选)')} aria-label={t('原容器名称(可选)')} onChange={e=>setContextName(e.target.value)}/><button disabled={busy||!path.trim()} onClick={()=>void perform('root.add',{path,context:contextName}).then(()=>setPath(''))}>{t('添加')}</button></div>{data.roots.map(p=><div className="apk-location" key={p}><code>{p}</code><button disabled={busy} onClick={()=>void perform('root.remove',{path:p})}>{t('移除扫描位置')}</button></div>)}</section></>}
|
||||
{view==='cleanup'&&<><div className="apk-cleanup-heading"><div><h2>{t('数据清理')}</h2><p>{t('存档、设置与恢复备份默认不选中。未知归属的数据不会自动删除。')}</p></div><button className="danger" disabled={busy||!selected.length} onClick={()=>setConfirm({operation:'cleanup',items:selected,title:t('确认数据清理'),description:cleanup.filter(i=>selected.includes(i.id)).map(i=>`${i.name} · ${bytes(i.bytes)}`).join('\n')+`\n${t('选中的文件将永久删除,无法撤销。')}`})}><IconTrash size={22}/>{t('清理所选')}</button></div>{cleanup.map(i=><article className="apk-cleanup-row" key={i.id}><Switch checked={selected.includes(i.id)} label={`${t('选择')} ${i.name}`} disabled={busy||i.unknown} onChange={checked=>setSelected(s=>checked?[...s,i.id]:s.filter(v=>v!==i.id))}/><div className="apk-copy"><b>{i.name}</b><p>{t(i.kind==='unknown'?'未知归属的数据':i.kind==='data'?'保留的应用数据':i.kind==='backups'?'恢复备份':(i.kind==='reviews'||i.kind==='uploads')?'过期上传文件':'旧 APK')} · {bytes(i.bytes)}</p>{i.unknown?<small>{t('无法确认归属,不提供自动删除。')}</small>:i.sensitive&&<small>{t('删除后不可恢复')}</small>}</div>{i.restorable&&<button disabled={busy} onClick={()=>setConfirm({operation:'restore',container:contextFor(i.context!),backup:i.name,title:t('恢复容器备份'),description:t('恢复将替换该容器内全部应用的状态;先保存恢复前备份,之后需启动验证。')})}>{t('恢复')}</button>}</article>)}{!cleanup.length&&<p className="empty">{t('没有可清理的数据。')}</p>}</>}
|
||||
{!!data.warnings.length&&<details className="apk-warnings"><summary>{t('部分容器无法读取')}</summary>{data.warnings.map((w,i)=><p key={i}>{w}</p>)}</details>}
|
||||
{details&&!confirm&&!review&&!log&&!job&&dialog(<><header className="apk-dialog-heading"><PluginImage kind="lepton" name={details.metadata.name} src={details.metadata.icon} size={64}/><div><h2>{details.metadata.name}</h2><code>{details.metadata.package}</code></div></header><dl className="apk-meta"><dt>{t('版本')}</dt><dd>{details.metadata.version} ({details.metadata.versionCode})</dd><dt>{t('容器')}</dt><dd>{contextFor(details.context)?.name??details.context}</dd><dt>{t('空间占用')}</dt><dd>{bytes(details.size)}</dd></dl>{details.pending&&<><p className="error">{t(details.pending)}</p><button disabled={busy} onClick={()=>void perform('reconcile',{app:details.id})}>{t('核对实际安装状态')}</button></>}<div className="apk-actions">{details.installed&&details.stateKnown!==false&&!details.steam&&<><button disabled={busy||!details.metadata.activities.length&&!details.activity} onClick={()=>void perform('launch',{app:details.id})}>{t('打开')}</button><button disabled={busy} onClick={()=>void perform('close',{app:details.id})}><IconPlayerStop size={20}/>{t('关闭应用')}</button><button disabled={busy} onClick={()=>choose(details)}>{t('安装新版 APK')}</button><button className="danger" disabled={busy} onClick={()=>setConfirm({operation:'clear',app:details,title:t('清除应用数据'),description:t('将永久删除该应用的存档和设置,无法撤销。')})}>{t('清除应用数据')}</button></>}{!details.installed&&details.stateKnown!==false&&!details.steam&&<button disabled={busy} onClick={()=>choose(details)}>{t('重新安装 APK')}</button>}<button disabled={busy} onClick={()=>void showLog(details)}><IconFileText size={20}/>{t('日志')}</button><button className="danger" disabled={busy||!!details.pending||details.stateKnown===false||details.steam} onClick={()=>askUninstall(details)}>{t(details.installed?'卸载应用':'清除保留数据')}</button></div>{details.installed&&details.stateKnown!==false&&!details.steam&&<details className="apk-advanced"><summary>{t('高级设置')}</summary><SwitchRow label={t('通过 Steam 启动')} description={t('通过 Steam 启动,可由 Steam 原生关闭窗口。入口是否常驻遵循 APK 设置页的选项。')} checked={details.steamLaunch??true} disabled={busy} onChange={enabled=>void perform('steam.settings',{app:details.id,enabled})}/>{data.retainSteamEntries!==false&&(details.steamLaunch??true)&&!details.steamRegistered&&<p role="status">{t('等待 Steam 注册,Steam 就绪后会自动重试。')}</p>}{details.steamRegistrationError&&<p className="error">{details.steamRegistrationError}</p>}<p>{t('默认自动处理窗口显示。此开关不改变应用的二维或 VR 类型。')}</p><SwitchRow label={t('自动处理窗口显示')} checked={details.showWindow==null} disabled={busy} onChange={checked=>void perform('settings',{app:details.id,showWindow:checked?null:true})}/>{details.showWindow!=null&&<SwitchRow label={t('显示安卓窗口')} checked={details.showWindow} disabled={busy} onChange={checked=>void perform('settings',{app:details.id,showWindow:checked})}/>}<p>{t('窗口设置将在下次打开应用时应用;必要时自动重启容器。')}</p><SwitchRow label={t('帧缓冲兼容修复')} description={t('仅用于部分游戏有声音但黑屏的问题,默认关闭。修改后需重启应用生效,不改变系统驱动或游戏文件。')} checked={details.framebufferCompatibility??false} disabled={busy} onChange={enabled=>void perform('settings',{app:details.id,framebufferCompatibility:enabled})}/><label>{t('窗口方向')}<Select label={t('窗口方向')} value={details.orientation??'auto'} disabled={busy} onChange={orientation=>void perform('settings',{app:details.id,orientation})} options={[{value:'auto',label:t('自动选择')},{value:'landscape',label:t('横屏')},{value:'portrait',label:t('竖屏')}]}/></label><label>{t('启动入口')}<Select label={t('启动入口')} value={details.activity??''} disabled={busy} onChange={activity=>void perform('settings',{app:details.id,activity})} options={[{value:'',label:t('自动选择')},...details.metadata.declaredActivities.map(a=>({value:a,label:a}))]}/></label></details>}<footer><button onClick={()=>setDetails(null)}>{t('完成')}</button></footer></>,t('管理应用'))}
|
||||
{review&&!confirm&&!job&&dialog(<ApkInstallReview metadata={review.metadata} size={bytes(review.bytes)} previous={updating?.metadata} displayMode={displayMode} onDisplayMode={setDisplayMode} containerName={installContainer?containerTitle(installContainer):target} updating={!!updating} running={!!installContainer?.running&&!installContainer.steam} busy={busy} error={error} onStop={()=>installContainer&&containerAsk(installContainer,'container.stop')} onCancel={()=>void discard()} onConfirm={()=>void perform('install',{ticket:review.ticket,context:target,app:updating?.id,showWindow:displayMode==='flat',approve:true})}/>,t('安装 APK'))}
|
||||
{details&&!confirm&&!review&&!log&&!job&&dialog(<><header className="apk-dialog-heading"><PluginImage kind="lepton" name={details.metadata.name} src={details.metadata.icon} size={64}/><div><h2>{details.metadata.name}</h2><code>{details.metadata.package}</code></div></header><dl className="apk-meta"><dt>{t('版本')}</dt><dd>{details.metadata.version} ({details.metadata.versionCode})</dd><dt>{t('容器')}</dt><dd>{contextFor(details.context)?.name??details.context}</dd><dt>{t('空间占用')}</dt><dd>{bytes(details.size)}</dd></dl>{details.installed&&details.stateKnown!==false&&!details.steam&&<section className="apk-steam-names"><h3>{t('自定义 Steam 名称')}</h3><p>{t('分别设置应用在 Steam 中显示的名称。留空恢复应用原名;更新 APK 后保留。Steam 不可用时将在就绪后同步。')}</p><SteamNameSetting app={details} busy={busy} onSave={steamName=>void perform('settings',{app:details.id,steamName})}/></section>}{details.pending&&<><p className="error">{t(details.pending)}</p><button disabled={busy} onClick={()=>void perform('reconcile',{app:details.id})}>{t('核对实际安装状态')}</button></>}<div className="apk-actions">{details.installed&&details.stateKnown!==false&&!details.steam&&<><button disabled={busy||!details.metadata.activities.length&&!details.activity} onClick={()=>void perform('launch',{app:details.id})}>{t('打开')}</button><button disabled={busy} onClick={()=>void perform('close',{app:details.id})}><IconPlayerStop size={20}/>{t('关闭应用')}</button><button disabled={busy} onClick={()=>choose(details)}>{t('安装新版 APK')}</button><button className="danger" disabled={busy} onClick={()=>setConfirm({operation:'clear',app:details,title:t('清除应用数据'),description:t('将永久删除该应用的存档和设置,无法撤销。')})}>{t('清除应用数据')}</button></>}{!details.installed&&details.stateKnown!==false&&!details.steam&&<button disabled={busy} onClick={()=>choose(details)}>{t('重新安装 APK')}</button>}<button disabled={busy} onClick={()=>void showLog(details)}><IconFileText size={20}/>{t('日志')}</button><button className="danger" disabled={busy||!!details.pending||details.stateKnown===false||details.steam} onClick={()=>askUninstall(details)}>{t(details.installed?'卸载应用':'清除保留数据')}</button></div>{details.installed&&details.stateKnown!==false&&!details.steam&&<details className="apk-advanced"><summary>{t('高级设置')}</summary><SwitchRow label={t('通过 Steam 启动')} description={t('通过 Steam 启动,可由 Steam 原生关闭窗口。入口是否常驻遵循 APK 设置页的选项。')} checked={details.steamLaunch??true} disabled={busy} onChange={enabled=>void perform('steam.settings',{app:details.id,enabled})}/>{data.retainSteamEntries!==false&&(details.steamLaunch??true)&&!details.steamRegistered&&<p role="status">{t('等待 Steam 注册,Steam 就绪后会自动重试。')}</p>}{details.steamRegistrationError&&<p className="error">{details.steamRegistrationError}</p>}<p>{t('默认自动处理窗口显示。此开关不改变应用的二维或 VR 类型。')}</p><SwitchRow label={t('自动处理窗口显示')} checked={details.showWindow==null} disabled={busy} onChange={checked=>void perform('settings',{app:details.id,showWindow:checked?null:true})}/>{details.showWindow!=null&&<SwitchRow label={t('显示安卓窗口')} checked={details.showWindow} disabled={busy} onChange={checked=>void perform('settings',{app:details.id,showWindow:checked})}/>}<p>{t('窗口设置将在下次打开应用时应用;必要时自动重启容器。')}</p><SwitchRow label={t('帧缓冲兼容修复')} description={t('仅用于部分游戏有声音但黑屏的问题,默认关闭。修改后需重启应用生效,不改变系统驱动或游戏文件。')} checked={details.framebufferCompatibility??false} disabled={busy} onChange={enabled=>void perform('settings',{app:details.id,framebufferCompatibility:enabled})}/><label>{t('窗口方向')}<Select label={t('窗口方向')} value={details.orientation??'auto'} disabled={busy} onChange={orientation=>void perform('settings',{app:details.id,orientation})} options={[{value:'auto',label:t('自动选择')},{value:'landscape',label:t('横屏')},{value:'portrait',label:t('竖屏')}]}/></label><label>{t('启动入口')}<Select label={t('启动入口')} value={details.activity??''} disabled={busy} onChange={activity=>void perform('settings',{app:details.id,activity})} options={[{value:'',label:t('自动选择')},...details.metadata.declaredActivities.map(a=>({value:a,label:a}))]}/></label></details>}<footer><button onClick={()=>setDetails(null)}>{t('完成')}</button></footer></>,t('管理应用'))}
|
||||
{review&&!confirm&&!job&&dialog(<ApkInstallReview metadata={review.metadata} size={bytes(review.bytes)} previous={updating?.metadata} displayMode={displayMode} onDisplayMode={setDisplayMode} containerName={installContainer?containerTitle(installContainer):target} updating={!!updating} running={!!installContainer?.running&&!installContainer.steam} busy={busy} error={error} converted={!!review.q2fVersion} q2f={q2f?{cached:q2f.cached,size:bytes(q2f.bytes)}:undefined} q2fError={q2fError} onStop={()=>installContainer&&containerAsk(installContainer,'container.stop')} onCancel={()=>void discard()} onConvert={()=>void convert()} onRevert={()=>void revertConversion()} onConfirm={()=>void perform('install',{ticket:review.ticket,context:target,app:updating?.id,showWindow:displayMode==='flat',approve:true})}/>,t('安装 APK'))}
|
||||
{confirm?.app&&!job&&['uninstall','purge'].includes(confirm.operation)&&dialog(<ApkUninstall app={confirm.app} size={bytes(confirm.app.size)} purge={!!confirm.purge} deleteContainer={!!confirm.deleteContainer&&!!confirm.purge&&canDeleteContainer(confirm.app)} exclusive={canDeleteContainer(confirm.app)} busy={busy} error={error} onPurge={purge=>setConfirm(c=>c?.app?{...c,purge,deleteContainer:purge&&canDeleteContainer(c.app)}:c)} onDeleteContainer={deleteContainer=>setConfirm(c=>c?{...c,deleteContainer}:c)} onCancel={()=>setConfirm(null)} onConfirm={()=>void perform(confirm.operation,{app:confirm.app!.id,purge:confirm.purge,deleteContainer:!!confirm.deleteContainer&&!!confirm.purge&&canDeleteContainer(confirm.app!),approve:true})}/>,confirm.title)}
|
||||
{confirm&&!job&&!(confirm.app&&['uninstall','purge'].includes(confirm.operation))&&dialog(<><h2>{confirm.title}</h2><p className="apk-confirm-copy">{confirm.description}</p>{confirm.app&&<p><b>{confirm.app.metadata.name}</b><br/><code>{confirm.app.metadata.package}</code></p>}{deletesData&&<p>{t('永久删除的数据无法撤销。')}</p>}{error&&<p className="error">{error}</p>}<footer><button disabled={busy} onClick={()=>setConfirm(null)}>{t('取消')}</button><button className={deletesData||confirm.operation==='uninstall'?'danger':'primary'} disabled={busy} onClick={()=>void perform(confirm.operation,{app:confirm.app?.id,context:confirm.container?.id,backup:confirm.backup,items:confirm.items,purge:confirm.purge,approve:true})}>{t('确认')}</button></footer></>,confirm.title)}
|
||||
{job&&dialog(<><h2>{t(job.phase==='preparing'&&job.operation?operationLabels[job.operation]??phases[job.phase]:phases[job.phase]??job.phase)}</h2><p>{t('操作进行中,请等待实际结果。')}</p><progress value={job.phase==='uploading'?job.received:undefined} max={job.phase==='uploading'?job.total:undefined}/>{job.phase==='uploading'&&<p>{bytes(job.received)} / {bytes(job.total??0)}</p>}{job.cancellable===false?<p>{t('操作已开始,请等待完成;此阶段无法取消。')}</p>:<button onClick={()=>{if(job.id==='upload')controller.current?.abort();else void api('job.cancel',{job:job.id}).catch(e=>setError(String(e)));}}>{t('取消')}</button>}</>,t('APK 操作进度'))}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
html:has(.apk-permission-view),body:has(.apk-permission-view),#root:has(.apk-permission-view){margin:0;width:100%;height:100%;background:transparent}
|
||||
.apk-permission-view{position:relative;box-sizing:border-box;width:100%;height:100%;display:flex;flex-direction:column;overflow:hidden;border:1px solid #35383d;border-radius:18px;background:#111316;color:#f3f4f6;font-family:system-ui,sans-serif;box-shadow:0 18px 60px #0008}
|
||||
.apk-permission-view header{display:flex;align-items:center;gap:14px;padding:19px 26px 13px}
|
||||
.apk-permission-mark{width:9px;height:9px;border-radius:50%;background:#87c8ff;box-shadow:0 0 16px #87c8ff88}
|
||||
.apk-permission-view header div{display:flex;align-items:baseline;gap:13px}
|
||||
.apk-permission-view header strong{font-size:17px;font-weight:650;letter-spacing:.01em}
|
||||
.apk-permission-view header small{font-size:14px;color:#aeb5be}
|
||||
.apk-permission-display{flex:1;min-height:0;display:flex;align-items:center;justify-content:center;padding:0 22px;background:#08090b}
|
||||
.apk-permission-display img{display:block;max-width:100%;max-height:100%;width:auto;height:auto;user-select:none}
|
||||
.apk-permission-display p{color:#aeb5be}
|
||||
.apk-permission-view footer{height:42px;box-sizing:border-box;padding:10px 26px;color:#aeb5be;font-size:13px}
|
||||
.apk-permission-view footer [role=alert]{color:#ffaaa5}
|
||||
.apk-permission-pointer{position:absolute;z-index:5;width:12px;height:12px;border:2px solid #fff;border-radius:50%;background:#81c8ff;box-shadow:0 0 0 5px #08131e99,0 0 16px #81c8ff;transform:translate(-50%,-50%);pointer-events:none}
|
||||
@@ -0,0 +1,53 @@
|
||||
import React,{useEffect,useRef,useState} from 'react';
|
||||
import {api} from './api';
|
||||
import {t} from './i18n';
|
||||
import './apk-permission.css';
|
||||
|
||||
type Pending={id:string;appName:string;package:string};
|
||||
type Frame={id:string;appName:string;package:string;image:string;left:number;top:number;width:number;height:number};
|
||||
|
||||
export function ApkPermission(){
|
||||
const [frame,setFrame]=useState<Frame|null>(null);
|
||||
const [error,setError]=useState('');
|
||||
const [busy,setBusy]=useState(false);
|
||||
const [pointer,setPointer]=useState<{x:number;y:number}|null>(null);
|
||||
const active=useRef(true);
|
||||
const loading=useRef(false);
|
||||
const choosing=useRef(false);
|
||||
async function refresh(){
|
||||
if(loading.current||choosing.current)return;
|
||||
loading.current=true;
|
||||
try{
|
||||
const pending=await api<Pending|null>('apk.permission.pending');
|
||||
if(!pending){if(active.current)setFrame(null);return;}
|
||||
const next=await api<Frame>('apk.permission.frame',{id:pending.id});
|
||||
if(active.current){setFrame(next);setError('');}
|
||||
}catch(e){if(active.current)setError(String(e));}
|
||||
finally{loading.current=false;}
|
||||
}
|
||||
useEffect(()=>{
|
||||
active.current=true;
|
||||
void refresh();
|
||||
const timer=window.setInterval(()=>void refresh(),2000);
|
||||
return()=>{active.current=false;window.clearInterval(timer);};
|
||||
},[]);
|
||||
async function choose(event:React.MouseEvent<HTMLImageElement>){
|
||||
if(event.button!==0||!frame||choosing.current)return;
|
||||
event.preventDefault();
|
||||
const box=event.currentTarget.getBoundingClientRect();
|
||||
const x=Math.floor(frame.left+(event.clientX-box.left)/box.width*frame.width);
|
||||
const y=Math.floor(frame.top+(event.clientY-box.top)/box.height*frame.height);
|
||||
choosing.current=true;setBusy(true);setError('');
|
||||
try{await api('apk.permission.click',{id:frame.id,x,y});setFrame(null);}
|
||||
catch(e){setError(String(e));}
|
||||
finally{choosing.current=false;setBusy(false);window.setTimeout(()=>void refresh(),350);}
|
||||
}
|
||||
return <main className="apk-permission-view" onMouseMove={event=>{const box=event.currentTarget.getBoundingClientRect();setPointer({x:event.clientX-box.left,y:event.clientY-box.top});}} onMouseLeave={()=>setPointer(null)}>
|
||||
<header><span className="apk-permission-mark" aria-hidden="true"/><div><strong>{t('安卓权限请求')}</strong><small>{frame?.appName??t('正在读取权限请求')}</small></div></header>
|
||||
<section className="apk-permission-display" aria-label={t('安卓权限选择')}>
|
||||
{frame?<img src={frame.image} alt={t('安卓原生权限对话框')} onMouseDown={choose} draggable={false} style={{cursor:busy?'wait':'pointer'}}/>:<p>{t('正在等待安卓权限画面…')}</p>}
|
||||
</section>
|
||||
<footer>{error?<span role="alert">{error}</span>:<span>{t('使用手柄激光选择原生权限选项')}</span>}</footer>
|
||||
{pointer&&<span className="apk-permission-pointer" style={{left:pointer.x,top:pointer.y}} aria-hidden="true"/>}
|
||||
</main>;
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import {TerminalManager} from './terminal';
|
||||
import {FrameFilePicker} from './file-picker';
|
||||
import {ManagerSwitcher,managerTab,sectionFor,type ManagerSection} from './manager-switcher';
|
||||
import {ApkManager} from './apk-manager';
|
||||
import {ApkPermission} from './apk-permission';
|
||||
import {Switch,SwitchRow} from './switch';
|
||||
import {PluginFrame,pluginLanguagePreference,setPluginLanguagePreference} from './plugin-frame';
|
||||
import {Launcher,LauncherSettings,type LauncherConfig} from './launcher';
|
||||
@@ -37,6 +38,7 @@ const managerMode=location.pathname==='/manager';
|
||||
const empty:Status={version:'0.4.0',database:{plugins:{},sources:[],safeMode:false},notifications:[],running:[]};
|
||||
|
||||
function App(){
|
||||
if(location.pathname==='/apk/permission')return <ApkPermission/>;
|
||||
if(location.pathname==='/cast/watch')return <CastViewer/>;
|
||||
if(location.pathname.startsWith('/cast/window/'))return <CastPlayer/>;
|
||||
const mobile=useMobileManager();useMobileViewport(managerMode&&mobile);
|
||||
|
||||
+8
-1
@@ -24,6 +24,13 @@ export function TerminalManager(){
|
||||
useEffect(()=>{void refresh();const timer=setInterval(()=>void refresh(),3000);return()=>clearInterval(timer);},[]);
|
||||
async function create(){if(busy)return;setBusy(true);try{const s=await managerApi<Session>('terminal',{operation:'create',name:t('终端')});setSelected(s.id);setName(s.name);await refresh();term.current?.focus();}catch(e){setError(String(e));}finally{setBusy(false);}}
|
||||
useEffect(()=>{if(!host.current||!selected)return;const terminal=new Terminal({fontSize:matchMedia('(max-width: 767px)').matches?13:16,scrollback:10000,allowTransparency:true,cursorBlink:!matchMedia('(prefers-reduced-motion: reduce)').matches,disableStdin:true,theme:{background:'#00000000',foreground:'#e8e8ed',selectionBackground:'#555555'}}),fitter=new FitAddon();terminal.loadAddon(fitter);terminal.open(host.current);term.current=terminal;fit.current=fitter;terminal.parser.registerOscHandler(52,()=>true);
|
||||
const keyboardInput=(event:Event)=>{
|
||||
event.preventDefault();
|
||||
if(terminal.options.disableStdin)return;
|
||||
const edit=(event as CustomEvent<string>).detail;
|
||||
terminal.input(edit==='\b'?'\x7f':edit==='\n'?'\r':edit,true);
|
||||
};
|
||||
terminal.textarea?.addEventListener('framely.keyboard.edit',keyboardInput);
|
||||
terminal.attachCustomKeyEventHandler(event=>{
|
||||
if(event.type!=='keydown'||!event.ctrlKey||!event.shiftKey||event.altKey||event.metaKey)return true;
|
||||
if(event.code==='KeyV')return false; // Native paste supplies the clipboard to xterm; do not emit Ctrl-V.
|
||||
@@ -44,7 +51,7 @@ export function TerminalManager(){
|
||||
ws.onmessage=e=>{if(!alive||socket.current!==ws)return;lastSeen=performance.now();try{const v=JSON.parse(e.data);setWritable(v.writable);terminal.options.disableStdin=!v.writable||v.exited;setExited(v.exited);if(v.truncated)setTruncated(true);if(v.data){const raw=atob(v.data);terminal.write(Uint8Array.from(raw,c=>c.charCodeAt(0)));}}catch(err){setError(String(err));}};
|
||||
ws.onclose=()=>{if(!alive||socket.current!==ws)return;if(timer)clearInterval(timer);setConnected(false);setWritable(false);terminal.options.disableStdin=true;retry=setTimeout(connect,2000);};ws.onerror=()=>setError(t('终端连接中断,正在重连。'));
|
||||
}
|
||||
const offline=()=>{if(localPanel)return;terminal.options.disableStdin=true;setConnected(false);setWritable(false);socket.current?.close();};window.addEventListener('offline',offline);window.addEventListener('online',connect);reconnect.current=connect;connect();return()=>{window.removeEventListener('offline',offline);window.removeEventListener('online',connect);alive=false;if(timer)clearInterval(timer);if(retry)clearTimeout(retry);observer.disconnect();input.dispose();socket.current?.close();socket.current=null;terminal.dispose();term.current=null;};
|
||||
const offline=()=>{if(localPanel)return;terminal.options.disableStdin=true;setConnected(false);setWritable(false);socket.current?.close();};window.addEventListener('offline',offline);window.addEventListener('online',connect);reconnect.current=connect;connect();return()=>{window.removeEventListener('offline',offline);window.removeEventListener('online',connect);terminal.textarea?.removeEventListener('framely.keyboard.edit',keyboardInput);alive=false;if(timer)clearInterval(timer);if(retry)clearTimeout(retry);observer.disconnect();input.dispose();socket.current?.close();socket.current=null;terminal.dispose();term.current=null;};
|
||||
},[selected]);
|
||||
const current=sessions.find(session=>session.id===selected);
|
||||
async function rename(){if(!name.trim()||busy)return;setBusy(true);try{await managerApi('terminal',{operation:'rename',id:selected,name:name.trim()});await refresh();setRenaming(false);}catch(e){setError(String(e));}finally{setBusy(false);}}
|
||||
|
||||
+1
-1
@@ -78,7 +78,7 @@ export function SystemUpdates({status,refresh}:{status:any;refresh:()=>Promise<v
|
||||
<p className="sub">{t('安装更新会保留插件和数据,Framely 界面会暂时关闭并重新启动。')}</p>
|
||||
{!source&&<p className="banner">{t('此版本尚未配置更新服务,请通过发行安装包更新。')}</p>}
|
||||
<Select label={t('更新渠道')} value={channel} disabled={busy||installing||!source} onChange={value=>void switchChannel(value)} options={[{value:'stable',label:t('正式版')},{value:'testing',label:t('测试版')}]}/>
|
||||
<p className="sub">{channel==='stable'?t('仅检查正式版。'):t('仅检查测试版(Preview、Beta、RC 等)。')}</p>
|
||||
<p className="sub">{channel==='stable'?t('仅检查正式版。'):t('检查正式版和测试版(Preview、Beta、RC 等),选择最新版本。')}</p>
|
||||
<div className="row">
|
||||
<button className="primary" disabled={busy||installing||!source} onClick={()=>{reset();void run('system.check.start',{},v=>{setRelease(v.release?{...v.release,targetVersion:v.version}:null);setReady(false);setChecked(true);setShowRelease(!!v.release&&!sameSystemVersion(v.release.version,status.build??status.version));});}}>{busy?t('处理中…'):t('检查更新')}</button>
|
||||
<button disabled={busy||installing||!status.previousRelease} onClick={()=>setConfirm('rollback')}>{t('回滚上一版本')}</button>
|
||||
|
||||
Reference in new issue
Block a user