Compare commits

...
116 changed files with 6985 additions and 277 deletions

No files matched your search

Generated
+185 -2
View File
@@ -8,6 +8,26 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "ahash"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9"
dependencies = [
"getrandom 0.2.17",
"once_cell",
"version_check",
]
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]]
name = "anstream"
version = "1.0.0"
@@ -85,6 +105,25 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bincode"
version = "2.0.0-rc.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7bb50c5a2ef4b9b1e7ae73e3a73b52ea24b20312d629f9c4df28260b7ad2c3c4"
dependencies = [
"bincode_derive",
"serde",
]
[[package]]
name = "bincode_derive"
version = "2.0.0-rc.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a45a23389446d2dd25dc8e73a7a3b3c43522b630cac068927f0649d43d719d2"
dependencies = [
"virtue",
]
[[package]]
name = "bitflags"
version = "2.13.2"
@@ -113,6 +152,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040"
dependencies = [
"find-msvc-tools",
"jobserver",
"libc",
"shlex",
]
@@ -183,6 +224,12 @@ dependencies = [
"libc",
]
[[package]]
name = "crawdad"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87fbd1ecd2ed790e11c8fbe034f9b3e7687404818d1bdfd8218d26ec645ec7c5"
[[package]]
name = "crc32fast"
version = "1.5.2"
@@ -208,6 +255,15 @@ dependencies = [
"typenum",
]
[[package]]
name = "csv-core"
version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782"
dependencies = [
"memchr",
]
[[package]]
name = "derive_arbitrary"
version = "1.4.2"
@@ -291,7 +347,7 @@ dependencies = [
[[package]]
name = "framely"
version = "0.4.2-preview.10"
version = "0.4.3-preview.3"
dependencies = [
"anyhow",
"base64",
@@ -299,6 +355,7 @@ dependencies = [
"hex",
"libc",
"pbkdf2",
"pinyin",
"rand",
"semver",
"serde",
@@ -306,9 +363,12 @@ dependencies = [
"sha2",
"tempfile",
"tiny_http",
"unicode-normalization",
"ureq",
"url",
"vibrato",
"zip",
"zstd",
]
[[package]]
@@ -343,6 +403,15 @@ dependencies = [
"r-efi",
]
[[package]]
name = "hashbrown"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
dependencies = [
"ahash",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
@@ -487,7 +556,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
"hashbrown 0.17.1",
]
[[package]]
@@ -502,6 +571,16 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "jobserver"
version = "0.1.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
dependencies = [
"getrandom 0.4.3",
"libc",
]
[[package]]
name = "libc"
version = "0.2.189"
@@ -570,6 +649,18 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pinyin"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e225f595052d9c46045755be4b8d7950b6d9f3c33e0c0b74ba58f11bbfa8c64b"
[[package]]
name = "pkg-config"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "potential_utf"
version = "0.1.6"
@@ -642,6 +733,35 @@ dependencies = [
"getrandom 0.2.17",
]
[[package]]
name = "regex"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "ring"
version = "0.17.14"
@@ -888,6 +1008,12 @@ dependencies = [
"zerovec",
]
[[package]]
name = "tinyvec"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "typenum"
version = "1.20.1"
@@ -900,6 +1026,15 @@ version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
[[package]]
name = "unicode-normalization"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
dependencies = [
"tinyvec",
]
[[package]]
name = "untrusted"
version = "0.9.0"
@@ -954,6 +1089,26 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "vibrato"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17bb75519548ea63e35dd02e9bc3cc672a25423a9b8757bd035f5387771eb4cd"
dependencies = [
"bincode",
"bincode_derive",
"crawdad",
"csv-core",
"hashbrown 0.12.3",
"regex",
]
[[package]]
name = "virtue"
version = "0.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b60dcd6a64dd45abf9bd426970c9843726da7fc08f44cd6fcebf68c21220a63"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
@@ -1215,3 +1370,31 @@ dependencies = [
"log",
"simd-adler32",
]
[[package]]
name = "zstd"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"
dependencies = [
"zstd-safe",
]
[[package]]
name = "zstd-safe"
version = "7.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882"
dependencies = [
"zstd-sys",
]
[[package]]
name = "zstd-sys"
version = "2.1.0+zstd.1.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ef0a8027ec3ee71300ab3bcbcd0393f434aa72b91ca6d635a39941deae8eea0"
dependencies = [
"cc",
"pkg-config",
]
+5 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "framely"
version = "0.4.2-preview.10"
version = "0.4.3-preview.3"
edition = "2021"
license = "AGPL-3.0-only"
@@ -20,6 +20,10 @@ url = "2"
ureq = { version = "2.12", features = ["json"] }
zip = { version = "2.4", default-features = false, features = ["deflate"] }
pbkdf2 = "0.12.2"
pinyin = "0.11"
vibrato = { version = "=0.5.0", default-features = false }
zstd = "0.13"
unicode-normalization = "0.1"
[dev-dependencies]
tempfile = "3"
+2
View File
@@ -9,6 +9,8 @@
A React plugin manager for Steam Frame, with a Rust core service, a separate CEF/OpenVR host, a network management panel, and a desktop installer. Manage plugins, sources, windows, notifications, and updates.
![Framely plugin library](docs/images/plugin-library.png)
## Installation
The target device is a Linux ARM64 Steam Frame. Download the `Framely Installer` for your computer from [Releases](https://github.com/SteamFramelyHomebrew/framely/releases), connect to the device, and install Framely. Alternatively, run this in the Frame SSH terminal to install the latest stable release:
+2
View File
@@ -9,6 +9,8 @@
Steam Frame 的 React 插件管理器:Rust 核心服务、独立 CEF/OpenVR 宿主、网络管理面板和电脑端安装器。可管理插件、来源、窗口、通知和更新。
![Framely 插件库](docs/images/plugin-library.png)
## 安装
目标为 Linux ARM64 Steam Frame。电脑端从 [Releases](https://github.com/SteamFramelyHomebrew/framely/releases) 下载对应平台的 `Framely Installer`,连接设备后安装本体。也可在 Frame 的 SSH 终端安装最新正式版:
+73
View File
@@ -0,0 +1,73 @@
Copyright 2000, 2001, 2002, 2003 Nara Institute of Science
and Technology.
Copyright 2023, LegalOn Technologies, Inc.
All Rights Reserved.
Use, reproduction, and distribution of this software is permitted.
Any copy of this software, whether in its original form or modified,
must include both the above copyright notice and the following
paragraphs.
Nara Institute of Science and Technology (NAIST),
the copyright holders, disclaims all warranties with regard to this
software, including all implied warranties of merchantability and
fitness, in no event shall NAIST be liable for
any special, indirect or consequential damages or any damages
whatsoever resulting from loss of use, data or profits, whether in an
action of contract, negligence or other tortuous action, arising out
of or in connection with the use or performance of this software.
A large portion of the dictionary entries
originate from ICOT Free Software. The following conditions for ICOT
Free Software applies to the current dictionary as well.
Each User may also freely distribute the Program, whether in its
original form or modified, to any third party or parties, PROVIDED
that the provisions of Section 3 ("NO WARRANTY") will ALWAYS appear
on, or be attached to, the Program, which is distributed substantially
in the same form as set out herein and that such intended
distribution, if actually made, will neither violate or otherwise
contravene any of the laws and regulations of the countries having
jurisdiction over the User or the intended distribution itself.
NO WARRANTY
The program was produced on an experimental basis in the course of the
research and development conducted during the project and is provided
to users as so produced on an experimental basis. Accordingly, the
program is provided without any warranty whatsoever, whether express,
implied, statutory or otherwise. The term "warranty" used herein
includes, but is not limited to, any warranty of the quality,
performance, merchantability and fitness for a particular purpose of
the program and the nonexistence of any infringement or violation of
any right of any third party.
Each user of the program will agree and understand, and be deemed to
have agreed and understood, that there is no warranty whatsoever for
the program and, accordingly, the entire risk arising from or
otherwise connected with the program is assumed by the user.
Therefore, neither ICOT, the copyright holder, or any other
organization that participated in or was otherwise related to the
development of the program and their respective officials, directors,
officers and other employees shall be held liable for any and all
damages, including, without limitation, general, special, incidental
and consequential damages, arising out of or otherwise in connection
with the use or inability to use the program or any product, material
or result produced or otherwise obtained by using the program,
regardless of whether they have been advised of, or otherwise had
knowledge of, the possibility of such damages at any time during the
project or thereafter. Each user will be deemed to have agreed to the
foregoing by his or her commencement of use of the program. The term
"use" as used herein includes, but is not limited to, the use,
modification, copying and distribution of the program and the
production of secondary products from the program.
In the case where the program, whether in its original form or
modified, was distributed or delivered to or received by a user from
any person, organization or entity other than ICOT, unless it makes or
grants independently of ICOT any specific warranty to the user in
writing, such person, organization or entity, will also be exempted
from and not be held liable to the user for any such damages as noted
above as far as the program is concerned.
÷÷
+7
View File
@@ -0,0 +1,7 @@
This software includes a binary version of data from
http://jaist.dl.sourceforge.net/project/mecab/mecab-ipadic/2.7.0-20070801/mecab-ipadic-2.7.0-20070801.tar.gz,
where the connection ids are remapped using CORE data in BCCWJ (except the PN category)
https://clrd.ninjal.ac.jp/bccwj/.
+21
View File
@@ -0,0 +1,21 @@
# Offline launcher search data
`ipadic.dic.zst` is the IPADic 2.7.0 dictionary compiled for Vibrato 0.5.0.
Vibrato is pinned to the matching reader format; upgrade the reader and dictionary together.
Source: https://github.com/daac-tools/vibrato/releases/download/v0.5.0/ipadic-mecab-2_7_0.tar.xz
Source archive SHA-256: `4764f983b7c3a9e1cb6a5ee945e00558efd812980e0dad61224f63ee3b0475d9`
Dictionary SHA-256: `82a6da70bb4a17be70f20ff44f650f9ad1d2b0b4fcb2f39c17fc797f92d0ab75`
Chinese pinyin uses rust-pinyin 0.11.0 and pinyin-data 0.15.0 (MIT); see `pinyin-LICENSE`.
Vibrato license notices are included as `vibrato-LICENSE-*`.
Keep `COPYING` and `NOTICE` with the dictionary. Release packaging copies this directory to
`share/search`, includes it in core updates and offline packages, and records its checksum.
The dictionary is loaded lazily by the session's search worker. No remote service is used.
中文:此目录包含 Vibrato 0.5.0 格式的 IPADic 2.7.0 离线日语读音词典。读入器与词典必须一起升级。
发布包复制到 `share/search`,包含于本体更新包和完整离线包,并纳入校验。
请保留 `COPYING` 和 `NOTICE`。词典由会话搜索线程按需加载,不使用远程服务。
Binary file not shown.
+22
View File
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2016 mozillazg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 legalforce-research
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+3
View File
@@ -33,3 +33,6 @@ Framely manages plugins on Steam Frame through device services, a SteamVR interf
- [Framely releases and updates](releases.md)
- [Desktop installer](../installer/README.md)
- [Space launcher](launcher.md)
- [Launcher actions and host compatibility](developer-guide/launcher.md)
+4
View File
@@ -82,3 +82,7 @@ Inspect Framely status and systemd logs. Do not mix debug messages into backend
Default GitHub Releases use tag `v<version>` and asset `<id>-<version>.framely`; source may omit `downloadUrl`. Community registration derives it automatically. Prepare a temporary packaged Manifest containing the final URL as shown in [publishing](publishing.md), because current `framely pack` does not read Git remotes. Set an explicit URL for custom downloads. Publish the Release/assets with usage, runtime-user details, changes and actual test coverage, then host a catalog or register a fixed source commit. Database registration also checks expected whole-package hashes and field compatibility.
For updates: bump version → regenerate the release Manifest (update explicit custom URLs if used) → rebuild/verify → device test → new Release → update the source pin. Never replace old assets.
## Launcher actions and host compatibility
[Launcher actions and host compatibility](launcher.md)
+73
View File
@@ -0,0 +1,73 @@
# Launcher, actions and host compatibility
[简体中文](../zh-CN/developer-guide/launcher.md) · [Manifest](manifest.md) · [SDK](sdk.md)
Available from Framely **0.4.3-preview.2**. Existing plugins need no changes: a short press opens their quick page and a long press offers Quick panel, Manage plugin and Uninstall plugin. A missing quick page disables that menu item. Uninstall always asks for confirmation.
## Host version requirement
```json
"engines": {"framely": ">=0.4.3-preview.2 <0.5.0"}
```
`engines.framely` is a mandatory host compatibility check, separate from `apiVersion` (the protocol version). It is optional for existing plugins and required when using launcher declarations. A declared launcher feature must have an explicit version floor of `0.4.3-preview.2` or newer.
Ranges use the same parser as plugin dependencies: exact versions (`0.4.3` or `=0.4.3`), comparisons, whitespace/comma intersections, `^`, `~`, and wildcards. `||` and hyphen ranges are not supported. A normal range excludes preview versions; to include a preview, explicitly name its major/minor/patch and prerelease in a comparator. For example `>=0.4.3-preview.2 <0.5.0` matches later 0.4.3 previews and compatible stable releases, but does not automatically include 0.4.4 previews. Build metadata does not affect matching.
The host checks before installation side effects, updates, version rollback, and runtime startup. Incompatible versions remain visible in the library but cannot be installed; dependency resolution skips them. Downgrading Framely preserves incompatible plugins and their enabled preferences while blocking execution. Published older hosts reject the unknown fields rather than run a new-format package; their error messages cannot be retroactively upgraded.
## Entry behavior
```json
"ui": {
"quickPage": "page.js",
"windows": {"main": {"entry": "page.js", "title": "Example"}},
"launch": {
"launcher": {"type": "window", "window": "main"},
"quickPanel": {"type": "quickPage"},
"manager": {"type": "window", "window": "main"}
}
}
```
Omitted entry behavior opens the plugin's quick page. The manager's separate management button is unaffected. The built-in **Quick panel** menu action always opens the quick page regardless of entry configuration. Window references must name a declared window; a `quickPage` target requires a declared quick page.
`plugin.open` retains its existing backend-start meaning. It does not apply entry navigation.
## Long-press actions
Declare buttons in order; Framely renders them above its three built-in actions. At most 16 custom actions are allowed, with unique valid IDs and nonempty labels up to 120 bytes. Labels are developer-provided text; choose localized content in your published package as appropriate.
```json
"launcherActions": [
{"id": "open", "label": "Open window", "target": {"type": "window", "window": "main"}},
{"id": "connect", "label": "Connect", "target": {"type": "backend", "method": "connect", "params": {"profile": "default"}}},
{"id": "notify", "label": "Send notification", "target": {"type": "frontend", "entry": "actions.js"}}
]
```
A backend target requires a backend and receives `{params, context}`; reserved `framely.*` methods are prohibited. A frontend target names a hashed payload bundle. It runs in a dedicated sandbox only when invoked, without rendering the quick page, and uses the existing scoped SDK capabilities. Frontend actions have a 90-second host deadline; failures stay visible for retry. Actions do not gain plugin management or arbitrary host-command privileges.
Build a separate `actions.ts` bundle (the scaffold's build command does this automatically):
```ts
import {registerLauncherActions, framely} from '@framely/sdk';
registerLauncherActions({
notify: async context => {
await framely.notifications.send({
id: 'hello', title: 'Hello', body: `From ${context.source}`, inbox: true,
});
},
});
```
## Startup context
```ts
const initial = await framely.ui.launchContext.get();
const unsubscribe = framely.ui.launchContext.onChanged(context => {
console.log(context.source, context.trigger, context.actionId);
});
```
`source` is `launcher`, `quickPanel`, or `manager`; `trigger` is `shortPress` or `menuAction`; custom menu actions additionally include `actionId`. Initial context is available after loading, and subsequent activations of a reused page/window send `ui.launch`. Frontend action callbacks receive context directly; backend actions receive it with their parameters. A backend `onStart` lifecycle context also includes `launchContext` when startup was caused by an entry launch. Old calls without a known entry use the quick-panel default.
+4
View File
@@ -96,3 +96,7 @@ Dependencies use ranges or `{version, source}`, with source pointing to an HTTPS
Manifest JSON is limited to 256 KiB and payload paths to 512 bytes. Payload paths allow ASCII letters/digits and `/._-+` only. Absolute paths, empty segments, `.`/`..`, symlinks and undeclared archive files are forbidden. Successful validation is not a safety review; users still assess runtime privileges.
`backend.uiVisibilityEvents` (boolean, default false) subscribes to manager-only `framely.ui.visibility` RPCs. Reply promptly. Delivery does not depend on mounted pages and requires a host supporting visibility events.
## Launcher actions and host compatibility
[Launcher actions and host compatibility](launcher.md)
+37 -4
View File
@@ -25,7 +25,8 @@ registerPlugin({QuickPage, windows: {main: MainWindow}});
| `framely.windows.open(key)` | Declared key; asynchronous result | Open a declared window |
| `framely.windows.close(key)` | Key; asynchronous result | Close a window without disabling the backend |
| `framely.notifications.send(notification)` | Notification; asynchronous result | Send or replace by ID |
| `framely.notifications.remove(id)` | Notification ID; asynchronous result | Withdraw notification |
| `framely.notifications.remove(id)` | Notification ID; asynchronous result | Close the popup and remove the inbox copy |
| `framely.notifications.dismiss(id)` | Notification ID; asynchronous result | Close the popup, retaining the inbox copy |
| `framely.dependencies()` | `Promise<DependencyStatus[]>` | Query declared dependency state |
| `framely.language.get()` | `Promise<{preference, language}>` | Language preference and effective language |
| `framely.onEvent(callback)` | Unsubscribe function | Receive forwarded events |
@@ -43,14 +44,38 @@ try {
```tsx
await framely.notifications.send({
id: 'task', title: 'Done', body: 'File processed', durationMs: 8000,
id: 'task', title: 'Done', body: 'File processed', inbox: true, durationMs: 8000,
actions: [{id: 'open', label: 'Open', icon: '↗'}],
});
```
`id`, `title`, `body` are required. Optional `image` accepts PNG/JPEG data URLs or HTTPS, up to a 1 MiB string. At most three actions, each with `id`, `label`, `icon`. `durationMs` is 1000–60000; omission defaults to 8000 ms. Notification/action IDs follow core ID rules; action IDs must be unique within a notification. Title is at most 160 bytes, body 4096, nonempty action label 80, and action icon 16. Each plugin may send at most ten notifications per ten seconds; the global queue permits 64 concurrent notifications. Updating an existing ID does not occupy another slot.
`id`, `title`, `body` are required. `inbox` defaults to `false`: with popups enabled, only notifications explicitly sent with `inbox: true` appear in the quick panel's Notifications tab. Inbox messages survive popup expiry, closing the popup, plugin disable/restart, and Framely restart. They are removed by an action's policy, explicit removal, or plugin uninstall. Restored inbox messages do not replay as popups.
Buttons invoke backend `notification.action` with `{id, action}` and forward a page event of the same name. UI-only plugins can listen for the event. Reuse an ID to update; remove it to withdraw.
| Field | Default | Behavior |
| --- | --- | --- |
| `inbox` | `false` | Save the message in the inbox; user popup settings may also require saving it |
| `durationMs` | `8000` | Popup countdown in milliseconds; `1000-60000`, or `0` to stay open until dismissed |
| `actions[].closeOnClick` | `true` | Close the popup after this action succeeds |
| `actions[].removeFromInboxOnClick` | `true` | Remove the inbox copy after this action succeeds |
User notification settings take priority over sender preferences. If the global popup switch or this plugin's popup switch is off, Framely suppresses the popup and saves the message in the inbox even when `inbox` is false. Reading the inbox clears the launcher unread badge but leaves messages and actions available. Plugins cannot override popup or badge settings.
The two action policies are independent. For a status button that keeps the message, set both to `false`:
```tsx
await framely.notifications.send({
id: 'capture', title: 'Recording', body: 'Recording is in progress.',
inbox: true, durationMs: 0,
actions: [{id: 'status', label: 'View status',
closeOnClick: false, removeFromInboxOnClick: false}],
});
```
Popups display the remaining auto-close countdown; inbox entries show their received time. Closing a popup keeps its saved inbox copy. `remove(id)` withdraws both copies; `dismiss(id)` closes only the popup. Reuse the same ID to replace a message and restart its countdown. Failed actions leave the message available for retry. Buttons use their text `label`; the legacy `icon` string remains optional for compatibility.
Optional `image` accepts PNG/JPEG data URLs or HTTPS, up to a 1 MiB string. At most three actions, each with required `id` and `label`. Notification/action IDs follow core ID rules; action IDs must be unique within a notification. Title is at most 160 bytes, body 4096, nonempty action label 80, and optional action icon 16. Each plugin may send at most ten notifications per ten seconds; the global queue permits 64 simultaneous popups and 256 saved inbox messages. When full, sending a new message fails; remove older messages first. Replacing an existing ID does not occupy another slot.
Buttons invoke backend `notification.action` with `{id, action}` and forward a page event of the same name after a successful backend response. UI-only plugins can listen for the event. A disabled plugin's saved messages remain readable and removable, but their action buttons are disabled until it is enabled again.
## React hooks
@@ -117,3 +142,11 @@ Development preview simulates windows, notifications and some bridge operations.
`framely.ui.getVisibility()` returns `{ known, captureObscured, pageVisible, sequence, sessionId }`. `framely.ui.onVisibilityChanged(callback, onError?)` subscribes and immediately queries the current snapshot; it returns an unsubscribe function. `useVisibility()` provides the same fields and `error`. Capture visibility combines the actual visibility of the quick panel, manager and every plugin window, excluding notifications and dock icons. Remote browser pages have `pageVisible: false` and cannot report headset visibility.
Declare `backend.uiVisibilityEvents: true` to receive the reserved JSON-line RPC `framely.ui.visibility` at startup and on changes, independently of mounted pages. Reply with the request id. The backend snapshot includes `known`, `captureObscured`, `sequence` and `views`; `pageVisible` is frontend-only. A native heartbeat missing for more than two seconds makes `known` false. Capture backends should pause on `!known || captureObscured`. Existing backends do not receive this RPC without opting in. Node/TS can use `registerVisibility` from `@framely/sdk/visibility`; Python supports `serve(dispatch, visibility=callback)`.
`framely.ui.close()` closes the current native surface: the quick panel or the current plugin window. It does not stop the backend or recording. Requires a host with this bridge method.
Standalone plugin windows display the plugin page without a host title bar. Plugins provide their own title, navigation and close button using `framely.ui.close()` or `framely.windows.close(id)`. Quick panels retain host navigation.
## Launcher actions and host compatibility
[Launcher actions and host compatibility](launcher.md)
Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

+33
View File
@@ -0,0 +1,33 @@
# Space launcher
[简体中文](zh-CN/launcher.md)
Point at the Framely Dock icon: use the upper trigger for the launcher and the primary trigger for the quick panel. **Manager → Launcher → Open launcher with the primary trigger** swaps these shortcuts immediately. Other controllers keep the ordinary click entry.
The launcher is a native Dock dashboard panel, 3 meters wide. Steam places and curves it and switches from the current Dock panel when it opens. It closes when the Dock is hidden. UI drawing is capped at 60 FPS independently of the headset refresh rate to limit pixel readback and texture upload load. This is a drawing limit, not a guaranteed measured frame rate. The renderer retains the high-resolution texture and uploads only changed regions. The icon area always reserves space for six columns and three rows, regardless of the number of apps. Each page holds up to 13 icons. Fill the first row with four icons, the second with five, then the third with four. The second row starts half a slot to the left; the third aligns with the first. Partial rows retain those starting positions: nine icons are 4 / 5, ten are 4 / 5 / 1. Collections of up to four icons use one centered row. The Done button uses the same translucent surface, border and highlights as the category selector. The visible gap beside the category selector is wider than the gap between adjacent icon artwork. The icon area is centered independently of the category selector, with a fixed 570-pixel height. All three row positions stay fixed, including when only one or two rows are populated. Button and joystick page changes slide and fade over 300 ms. Category changes slide vertically and fade in over 360 ms, with the category selector’s active surface sliding to the selected item; reduced-motion mode skips these transitions. Switching to another Dock panel replaces the launcher normally. Framely does not change other windows’ transparency or input settings. Closing the launcher returns to Steam’s Dock panel. Steam uses local cover artwork first and falls back to logos or initials. Use the side category selector for Favorites, All, Plugins, Steam, Lepton or Desktop apps, the bottom dots to change pages, and the star on hover to favorite apps. Favorited apps keep a visible filled blue star; click it again to remove the favorite without changing the icon order. The transparent surface curves around you; only icons, names and categories are normally visible. Disabled plugins are hidden; safe mode prevents third-party plugin launch. Steam lists installed apps from the Frame's local libraries, not account-only or remote-streaming apps.
Press and release may drift by up to 36 UI pixels without changing the initial hit. Icon and category hit areas are larger than the artwork. Deliberate movement cancels stabilization. Hold a plugin icon with the primary trigger for 400 ms to open its action menu; ordinary jitter keeps the hold active. It contains developer actions plus Quick panel, Manage plugin and Uninstall plugin. Press **B** or click an unused area to close the launcher. During icon arrangement, the first press or click exits arrangement and keeps the launcher open. Hold the primary trigger and swipe horizontally: the current page follows your movement while the adjacent page slides into view. Release to snap to that page, or return to the current page if the drag is too short or reaches the boundary. By default the action menu closes ten seconds after the pointer leaves; returning cancels the timer. Configure the switch and delay (1–300 seconds) in **Manager → Launcher**. Uninstall requires confirmation and keeps plugin data.
Keep holding for **800 ms** to enter icon arrangement. Drag any icon (including Framely itself, which opens the management panel) onto another position; icons shift and automatically fill the 4 / 5 / 4 slots without gaps. The left drag edge is to the right of the category selector; the selector itself does not trigger paging. Hold a dragged icon at either edge of the icon area for 650 ms to turn a page; continue holding to move across further pages. Release to save the order, or choose **Done** to finish arranging. Closing or hiding the Dock cancels an unfinished drag. Manual icon order is preserved across favorites, search, refreshes and reopening. Favoriting never moves icons to the front; the Favorites category filters the same order. Apps without a saved position are appended in name order.
Either controller's stick switches categories vertically and pages horizontally. A gesture uses only its dominant axis; return below the neutral threshold before the next navigation step. This prevents a diagonal or simultaneous stick input from performing both actions.
Desktop applications come from the session user's XDG application directories, including Flatpak exports; hidden entries and duplicate Steam game shortcuts are omitted. Steam-installed APK applications appear in the Lepton category and launch through Steam. Sideloaded Lepton apps are discovered from installed APKs in each context's package database; empty contexts and Android system packages are excluded. These launch in their existing user-owned context. Missing Android labels/artwork fall back to the package name and initials. Downloaded but uninstalled APK files are not included. Enumeration does not start containers.
Steam launch feedback confirms handoff to Steam rather than game readiness. Plugin-library entries can specify `engines.framely`; update Framely if your version does not satisfy the shown range.
## Categories and favorites
The manager has a dedicated **Launcher** page for trigger assignment, menu timeout and the categories included in **All**. Plugins (including Framely), Steam, Lepton and Desktop apps are included by default. Turning a category off only removes it from All; its own category and Favorites remain accessible. Turning every category off leaves All empty.
Every app type can be favorited using the star shown on hover. Existing plugin and Steam favorites are preserved. Disabled plugins stay hidden; favorites for temporarily unavailable apps are retained. Each opening clears the search and resets pagination. Once local enumeration completes, Favorites opens if any favorite is currently available; otherwise All opens. Removing the final favorite while viewing Favorites shows an empty state without switching categories until the next opening.
## Search
Click the capsule at the top to open the VR keyboard. Search stays within the selected category and preserves its ordering. Clear the field to restore its apps. While the keyboard is open, launcher stick navigation and background dismissal are paused; B closes the keyboard first. The icon canvas keeps its fixed size and position while searching.
Search accepts original names, English word initials, Chinese pinyin and Japanese romaji / syllable initials. Matching ignores case, width, tone marks, spaces and punctuation; it supports prefixes and continuous fragments. Examples: `toushi`, `tiaose` and `tsts` find **透视调色**; `sakura` and `skr` find **さくら**; `toukyou` finds **東京**; `hla` finds **Half-Life: Alyx**. Chinese alternate character readings are supported within a bounded index; uncommon names or compound readings may differ from the intended pronunciation.
Indexes are built asynchronously and cached on the device. Chinese uses offline pinyin data; Japanese uses the bundled Vibrato / IPADic reading dictionary. Han names receive both Chinese and Japanese candidates regardless of interface language. Unknown dictionary readings retain their original text. Original-name search remains available before phonetic indexing completes. No app names are sent to an external search service.
Session API: `launcher.search.index` accepts `{names: string[]}` and returns a name-keyed map of `{terms: string[]}`. `launcher.favorite` accepts `{key, favorite}` with the same stable keys as launcher ordering. Plugin and Steam keys update their existing favorites; `framely`, `desktop:` and local `lepton:` keys use `launcherFavorites`. `launcher.settings.save` now includes `allCategories` (`plugin`, `steam`, `lepton`, `desktop`); omitted fields migrate to all four categories, while an explicit empty array means none. Search dictionaries and notices are included in both core updates and offline packages under `share/search`.
+4
View File
@@ -84,3 +84,7 @@ Restart defaults to `on-failure`; `never` reports failure without retrying. Limi
States include starting/running/stopping/stopped/recovering/failed. Core management is serialized. Normal SIGTERM/SIGINT attempts to stop plugins; forced termination or power loss cannot guarantee hooks. Support safe recovery on next startup.
The log view includes backend and lifecycle logs; each retains a current 2 MiB file and a preceding copy. Failed pre-registration installs log to `/var/lib/framely/logs/<id>.lifecycle.log`. User data is under `/var/lib/framely/data/<id>/<identity>/`, relative to any custom core state root.
## Launch context
[Launch context](developer-guide/launcher.md)
+3 -3
View File
@@ -38,7 +38,7 @@ Deleted `/home` data cannot be recovered. OS updates may require manual interven
Device and installer share the repository with independent versions/tags/workflows:
- Device: root Cargo version, `v<version>` (currently `v0.4.2-preview.10`), `.github/workflows/release.yml`, Linux ARM64 and pinned CEF.
- Device: root Cargo version, `v<version>` (currently `v0.4.2-preview.12`), `.github/workflows/release.yml`, Linux ARM64 and pinned CEF.
- Installer: `installer/Cargo.toml`, `installer-v<version>` (currently `installer-v0.4.1-preview.8`), `.github/workflows/installer-release.yml`, Linux x64/ARM64, Windows x64, macOS Intel/Apple Silicon, pinned GPUI Kit.
Versions need not match or ship together. Update the relevant Cargo.lock with version changes. Installer package/macOS versions use the installer version.
@@ -47,8 +47,8 @@ Both workflows cache dependencies/builds by product/platform/toolchain/configura
```bash
# After committing and pushing the intended source:
git tag v0.4.2-preview.10
git push origin v0.4.2-preview.10
git tag v0.4.2-preview.12
git push origin v0.4.2-preview.12
# Independent installer release:
git tag installer-v0.4.1-preview.8
git push origin installer-v0.4.1-preview.8
+30 -3
View File
@@ -9,10 +9,11 @@
Click Framely in the SteamVR Dashboard Dock. First use requires accepting the terms and privacy statement; plugins do not automatically start before consent.
- **Favorites**: open favorite plugin quick pages.
- **Installed**: browse local plugins and their pages.
- **Settings**: language, safe mode and the plugin manager entry.
- **Installed**: browse enabled local plugins and their pages.
- **Notifications**: view saved notifications and update reminders, and toggle floating notifications.
- **Settings**: choose an installed language, toggle safe mode, open the plugin manager or **Check for updates**. The update entry opens the manager’s About/update page. Install language files and download the language template from the manager’s Settings page.
The manager opens a separate large window with navigation for plugins, plugin library, sources, settings and About. Installation, updates and source management happen here. A phone or computer can also use the [network panel](network-panel.md).
The manager opens a separate large window with navigation for plugins, plugin library, sources, settings, notification settings and About. Installation, updates and source management happen here. A phone or computer can also use the [network panel](network-panel.md).
## Plugins and windows
@@ -28,4 +29,30 @@ Safe mode pauses third-party plugins for troubleshooting; leave it after resolvi
In About, select the Stable or Testing update channel and check for updates. Choose **Download and install**, then confirm once: Framely downloads and verifies the release and automatically starts installation. Download and verification are displayed as separate stages, with byte progress for each. Download or verification failure stops installation and displays an error. Plugins and data remain; the Framely interface briefly closes and restarts.
Automatic update checks are enabled by default. Framely checks about 30 seconds after starting (once terms are accepted), then every 6 hours. In About, turn **Check for updates automatically** off or change the interval. Checks use the selected Stable/Testing channel and configured proxy, continue with the panel closed, and never download or install automatically. A newer version saves a notification to the inbox and shows a popup when notification settings allow it. **Ignore** dismisses that version's reminder; **Open updates** opens About's update page. The same version is not repeatedly announced, including after restart. Switching the source or channel clears the old reminder.
Floating notifications follow the headset near the upper-right of the view. Their input mask matches the visible card; short button clicks tolerate small tracking movements.
Notification popups display an auto-close countdown when the sender sets a duration. Closing a popup keeps any saved inbox copy. Remove a saved message from Notifications with its trash button. Action buttons close and remove messages by default; senders can configure different behavior. Ordinary notifications are not saved unless the sender opts in, except when popups are disabled.
The **Allow notifications** switch at the top of Notifications controls all floating popups. When off, new notifications are saved in the inbox even if the sender did not request it; active popups are also moved to the inbox. Turning popups back on does not replay old messages.
In the manager, **Notification settings** provides global **Floating notifications** and **Launcher badge** switches, plus independent **Badge** and **Popup** switches for Framely itself (including update reminders) and every installed plugin, including disabled plugins. Global switches take priority and preserve each app’s preferences. The Framely Dock launcher badge counts unread inbox messages from sources allowed to show a badge, displays `99+` for larger counts, and disappears when you view the inbox. Hidden headset panels do not mark messages as read. Reading keeps messages and their actions available; it does not remove them. Settings and read state survive restart.
Log commands are in the [installation guide](installation.md). A working manager does not establish that all plugins work. Enable plugins individually and verify their sources and runtime users.
## Export logs
Open **Settings → Recovery and diagnostics → Export logs**. In the headset, the ZIP is saved in `~/Downloads` on Frame and the panel shows its path. From the network panel, the ZIP downloads to your browser instead. Collection includes recent Framely/plugin logs, CEF renderer logs, GPU evidence, service status and version information. Missing sources or failed commands are recorded in `report.json`; they do not prevent exporting the remaining information. Each source and the total archive input are bounded.
If the panel cannot open, connect to Frame using the installer and choose **Export logs** in its footer. Select where to save the ZIP on your computer. It collects directly over SSH, includes the installer’s current operation log, and works when Framely services are stopped or its state file is damaged. No release package selection is required.
Plugin configuration, inbox contents and password files are excluded. Common credential patterns in logs are masked; review application logs before sharing the archive. Nothing is uploaded automatically.
For terminal recovery without a running daemon:
```bash
sudo /var/lib/framely/current/bin/framely export-logs --output /tmp/framely-logs.zip
```
The output must be a new file. If the binary cannot run, an extracted release also includes `tools/export-diagnostics.py`, usable with `sudo python3 tools/export-diagnostics.py --output /tmp/framely-logs.zip`.
+3
View File
@@ -35,3 +35,6 @@ Framely 是 Steam Frame 的插件管理器,包含设备端服务、SteamVR 界
- [Framely 发行与更新机制](releases.md)
- [电脑端安装器构建](../../installer/README.zh-CN.md)
- [空间启动台](launcher.md)
- [启动台操作与本体兼容](developer-guide/launcher.md)
+4
View File
@@ -82,3 +82,7 @@ sudo /var/lib/framely/current/bin/framely install ./yourname.my-plugin-0.1.0.fra
GitHub Release 默认使用标签 `v<version>` 和附件 `<id>-<version>.framely`,源码清单可以省略 `downloadUrl`。社区登记会自动拼接地址;打包前按[发布指南](publishing.md)生成包含最终地址的临时清单,因为当前 `framely pack` 不会自己读取仓库地址。自定义下载地址再显式填写 `downloadUrl`。随后公开 Release、上传包,提供使用说明、运行用户、更新记录和实际测试范围,再自行托管插件源或登记固定源码提交。社区数据库还需校验整包预期哈希和字段兼容性。
后续更新:提升版本号 → 重新生成发布清单(自定义地址时更新地址)→ 构建打包并校验 → 实机验证 → 新 Release → 更新来源登记。不要替换旧版本附件。
## 启动台操作与本体兼容
[启动台操作与本体兼容](launcher.md)
+71
View File
@@ -0,0 +1,71 @@
# 启动台、操作与本体兼容要求
[English](../../developer-guide/launcher.md) · [Manifest](manifest.md) · [SDK](sdk.md)
从 Framely **0.4.3-preview.2** 开始支持。旧插件无需修改:短按默认打开快捷页面,长按显示“快捷面板、管理插件、卸载插件”。没有快捷页面时对应按钮置灰,卸载始终需要确认。
## 本体版本要求
```json
"engines": {"framely": ">=0.4.3-preview.2 <0.5.0"}
```
`engines.framely` 是强制执行的本体兼容条件;`apiVersion` 表示协议版本,两者独立。旧插件可以省略;使用启动台新增声明时必须填写,并明确约束最低版本为 `0.4.3-preview.2` 或更新版本。
与插件依赖共用范围解析:精确版本(`0.4.3` 或 `=0.4.3`)、比较符、空格或逗号连接的交集、`^`、`~` 和通配符。不支持 `||` 和连字符区间。普通范围不匹配预览版;需要在比较条件中显式写出对应主、次、补丁版本及预览标识。例如 `>=0.4.3-preview.2 <0.5.0` 接受后续 0.4.3 预览版和兼容正式版,但不会自动接受 0.4.4 预览版。构建标识不影响匹配。
安装、更新、降级安装和启动均检查兼容性;不兼容安装在执行钩子或替换文件之前被拒绝。插件库仍展示不兼容版本及要求,依赖解析跳过这些版本。本体降级后保留插件文件及启用偏好,但阻止执行。已发布的旧本体会拒绝未知清单字段,无法追溯增加友好升级提示。
## 不同入口的行为
```json
"ui": {
"quickPage": "page.js",
"windows": {"main": {"entry": "page.js", "title": "Example"}},
"launch": {
"launcher": {"type": "window", "window": "main"},
"quickPanel": {"type": "quickPage"},
"manager": {"type": "window", "window": "main"}
}
}
```
未配置的入口默认进入对应插件快捷页面。管理面板独立管理按钮不受影响。长按菜单内置的“快捷面板”始终进入快捷页,不受入口配置影响。窗口目标必须引用已声明窗口,快捷页目标必须声明快捷页面。现有 `plugin.open` 仍仅启动后台,不执行入口导航。
## 长按操作
自定义按钮按声明顺序显示在三个内置操作上方;最多 16 个,ID 合法且不重复,名称非空且不超过 120 字节。名称由插件提供,发布时自行选择合适的语言。
```json
"launcherActions": [
{"id": "open", "label": "打开窗口", "target": {"type": "window", "window": "main"}},
{"id": "connect", "label": "连接", "target": {"type": "backend", "method": "connect", "params": {"profile": "default"}}},
{"id": "notify", "label": "发送通知", "target": {"type": "frontend", "entry": "actions.js"}}
]
```
后台目标必须有后台,接收 `{params, context}`,禁止使用保留的 `framely.*` 方法。前端目标必须指向包内带哈希的脚本;点击时在独立沙箱中加载,不渲染快捷页面,可使用现有 SDK 能力。前端操作最多等待 90 秒,失败保留菜单并支持重试。操作不会取得插件管理或任意系统命令权限。
新模板会自动把 `actions.ts` 构建为 `actions.js`:
```ts
import {registerLauncherActions, framely} from '@framely/sdk';
registerLauncherActions({
notify: async context => {
await framely.notifications.send({
id: 'hello', title: '你好', body: `来自 ${context.source}`, inbox: true,
});
},
});
```
## 启动上下文
```ts
const initial = await framely.ui.launchContext.get();
const unsubscribe = framely.ui.launchContext.onChanged(context => {
console.log(context.source, context.trigger, context.actionId);
});
```
`source` 为 `launcher`、`quickPanel` 或 `manager`;`trigger` 为 `shortPress` 或 `menuAction`;自定义操作还包含 `actionId`。首次加载即可查询,复用页面或窗口时接收 `ui.launch` 事件。前端操作直接接收上下文,后台操作随参数接收。入口导致后台首次启动时,`onStart` 生命周期参数也包含 `launchContext`。没有已知来源的旧调用默认标记为快捷面板。
+4
View File
@@ -96,3 +96,7 @@
清单 JSON 最大 256 KiB,载荷路径最多 512 字节。载荷路径仅允许 ASCII 字母、数字及 `/._-+`,禁止绝对路径、空段、`.`、`..`、软链接和未声明的附加包文件。清单通过校验后,运行权限仍需用户判断;文件哈希不代表插件安全审核。
`backend.uiVisibilityEvents`(boolean,默认 false):订阅宿主专用 `framely.ui.visibility` RPC。后端必须及时回复;通知无需页面挂载。该字段需要支持可见性事件的新版宿主。
## 启动台操作与本体兼容
[启动台操作与本体兼容](launcher.md)
+37 -4
View File
@@ -25,7 +25,8 @@ registerPlugin({QuickPage, windows: {main: MainWindow}});
| `framely.windows.open(key)` | 窗口 key;异步结果 | 打开已在 Manifest 声明的窗口 |
| `framely.windows.close(key)` | 窗口 key;异步结果 | 关闭窗口,不停用后端 |
| `framely.notifications.send(notification)` | 通知对象;异步结果 | 发送或按 ID 更新通知 |
| `framely.notifications.remove(id)` | 通知 ID;异步结果 | 撤回通知 |
| `framely.notifications.remove(id)` | 通知 ID;异步结果 | 关闭弹窗并移除收件箱副本 |
| `framely.notifications.dismiss(id)` | 通知 ID;异步结果 | 仅关闭弹窗,保留收件箱副本 |
| `framely.dependencies()` | `Promise<DependencyStatus[]>` | 查询本插件声明的依赖状态 |
| `framely.language.get()` | `Promise<{preference, language}>` | 获取语言偏好和当前生效语言 |
| `framely.onEvent(callback)` | 返回取消订阅函数 | 接收宿主转发的事件 |
@@ -43,14 +44,38 @@ try {
```tsx
await framely.notifications.send({
id: 'task', title: '完成', body: '文件已处理', durationMs: 8000,
id: 'task', title: '完成', body: '文件已处理', inbox: true, durationMs: 8000,
actions: [{id: 'open', label: '打开', icon: '↗'}],
});
```
`id`、`title`、`body` 必填。`image` 可选,接受 PNG/JPEG data URL 或 HTTPS URL,字符串最大 1 MiB。`actions` 最多 3 项,每项有 `id`、`label`、`icon`。`durationMs` 范围 1000–60000,省略时默认 8000 ms。`id` 和按钮 `id` 遵循本体 ID 规则,按钮 ID 在同一通知内不得重复;`title` 最大 160 字节、`body` 4096 字节、按钮 `label` 非空且最多 80 字节、`icon` 最多 16 字节。每插件每 10 秒最多发送 10 次,全局最多 64 条同时存在的通知;同 ID 更新不额外占队列位置。
`id`、`title`、`body` 必填。`inbox` 默认 `false`:浮窗启用时,只有明确设置 `inbox: true` 的通知才进入快捷面板的“通知”收件箱。收件箱消息在弹窗到期、关闭弹窗、插件停用或重启、本体重启后都会保留;按钮策略、主动移除或卸载插件会移除消息。重启后恢复的收件箱消息不会重新弹出。
按钮动作调用后端 `notification.action`,参数 `{id, action}`;同时转发 `notification.action` 页面事件。无后端插件可只监听页面事件。同一 ID 用于更新,调用 remove 撤回。
| 字段 | 默认值 | 行为 |
| --- | --- | --- |
| `inbox` | `false` | 保存到收件箱;用户浮窗设置也可要求保存 |
| `durationMs` | `8000` | 弹窗自动关闭倒计时,单位毫秒;支持 `1000-60000`,`0` 表示持续显示直到主动关闭 |
| `actions[].closeOnClick` | `true` | 此按钮操作成功后关闭弹窗 |
| `actions[].removeFromInboxOnClick` | `true` | 此按钮操作成功后移除收件箱副本 |
用户的通知设置优先于发送方偏好。全局浮窗或此插件的浮窗开关关闭时,Framely 不展示弹窗,并将消息转存到收件箱,即使 `inbox` 是 `false`。查看收件箱会清除启动图标的未读角标,但保留消息及按钮。插件不能覆盖用户的浮窗和角标设置。
两个按钮策略独立配置。例如查看状态后仍要保留消息,可将两个字段均设为 `false`:
```tsx
await framely.notifications.send({
id: 'capture', title: '录制中', body: '当前录制正在进行。',
inbox: true, durationMs: 0,
actions: [{id: 'status', label: '查看状态',
closeOnClick: false, removeFromInboxOnClick: false}],
});
```
弹窗显示剩余关闭时间,收件箱显示接收时间。关闭弹窗保留其收件箱副本。`framely.notifications.remove(id)` 同时撤回弹窗和收件箱消息;`framely.notifications.dismiss(id)` 仅关闭弹窗。重复发送同 ID 会替换消息并重新开始倒计时。按钮操作失败时保留消息供重试。按钮使用 `label` 文字显示,旧版 `icon` 字符串保持可选兼容。
`image` 可选,接受 PNG/JPEG data URL 或 HTTPS URL,字符串最大 1 MiB。`actions` 最多 3 项,每项必填 `id`、`label`。通知和按钮 ID 遵循本体 ID 规则,按钮 ID 在同一通知内不得重复;`title` 最大 160 字节、`body` 4096 字节、按钮 `label` 非空且最多 80 字节、可选 `icon` 最多 16 字节。每插件每 10 秒最多发送 10 次,全局最多 64 个同时显示的弹窗及 256 条收件箱消息。达到上限后,新消息发送会报错,请先移除旧消息;替换同 ID 不额外占用位置。
按钮调用后端 `notification.action`,参数为 `{id, action}`;后端调用成功后转发同名页面事件。纯前端插件可以监听该事件。插件停用时,其收件箱消息仍可查看和移除,操作按钮需重新启用插件后使用。
## React hooks
@@ -124,3 +149,11 @@ const off = framely.ui.onVisibilityChanged(state => {
});
// 页面卸载时调用 off()
```
`framely.ui.close()` 关闭当前原生界面:快捷页关闭 Framely 面板,插件窗口关闭自身;不会停止插件后端或当前录制。需要包含此 bridge 方法的新版宿主。
独立插件窗口直接展示插件页面,宿主不添加标题栏。插件应自行提供标题、导航和关闭按钮,可使用 `framely.ui.close()` 或 `framely.windows.close(id)`。快捷面板仍保留宿主导航。
## 启动台操作与本体兼容
[启动台操作与本体兼容](launcher.md)
+35
View File
@@ -0,0 +1,35 @@
# 空间启动台
[English](../launcher.md)
激光指向 Framely Dock 图标:上扳机打开启动台,主扳机打开快捷面板。在 **管理面板 → 启动台 → 主扳机打开启动台** 开启开关,两个入口立即互换。其他手柄保留普通点击入口。
启动台是 Dock 内宽 3 米的原生面板,由 Steam 管理位置和曲面;打开时通过 Dock 的面板切换机制替代当前面板,Dock 隐藏时关闭。界面绘制上限固定为 60 FPS,不跟随头显刷新率升高,以限制像素读回与纹理上传负担。这是绘制上限,并不保证实测达到该帧率。渲染保留高分辨率纹理,只上传发生变化的区域。图标区域始终保留六列三行的空间,不随应用数量变化;每页最多 13 个图标,按第一排 4 个、第二排 5 个、第三排 4 个的顺序填充。第二排向左错开半格,第三排与第一排对齐;未填满的第二、三排也从相同槽位开始,不按数量重新居中分配。9 个为 4/5,10 个为 4/5/1;1–4 个使用一排居中排列。图标区域独立于分类器居中,高度固定为 570 个界面像素;只有一排或两排图标时,每排的槽位位置仍保持不变。“完成”按钮使用与分类器相同的半透明背景、边框和高光,分类器与图标之间的可见留白大于图标之间的水平留白。按钮与摇杆翻页采用 300 毫秒横向滑动与淡入动效,分类切换采用 360 毫秒纵向滑动与淡入动效,分类器的激活底块同步滑动到选中项,系统启用减少动态效果时跳过这些过渡动画。切换到其他 Dock 面板会正常替代启动台,Framely 不修改其他窗口的透明度或输入设置。关闭启动台后返回 Steam 的 Dock 面板。Steam 优先使用本地封面,缺图时回退到 Logo 或首字母。透明界面沿用户面前弯曲,显示应用图标、名称、分类器和顶部搜索框。左侧切换收藏、全部、插件、Steam、Lepton 和桌面程序,底部圆点翻页,悬停图标显示收藏按钮。停用插件不显示,安全模式阻止第三方插件启动。Steam 仅展示 Frame 本机各库已安装应用,不包含仅在账号库或串流电脑中的应用。
按下后的激光落点允许在 36 个界面像素内抖动,点击区域大于图标本身;明显拖动会取消落点稳定处理。主扳机按住插件图标 400 毫秒展开操作菜单,普通抖动不会取消长按,包含开发者按钮和“快捷面板、管理插件、卸载插件”。按 **B** 或点击空白区域关闭启动台;处于图标整理状态时,第一次操作先退出整理,启动台继续显示。按住主扳机横向拖动时,当前页随手移动,相邻页同步滑入;松手后吸附到相邻页,拖动距离不足或到达边界则回到当前页。操作菜单默认在指针离开 10 秒后关闭,重新移入取消计时。在 **管理面板 → 启动台** 调整自动关闭开关与时长(1–300 秒)。卸载需要确认,并保留插件数据。
继续按住到 **800 毫秒**进入图标整理。拖动任意图标到其他位置,其他图标按顺序移动并自动补齐 4/5/4 槽位,不留空洞。Framely 本身也在启动台中,点击打开管理面板,并可一起排列。向左拖动的翻页边缘位于分类器右侧,分类器本身不会触发翻页。拖到图标区域左右边缘停留 650 毫秒自动翻页,继续停留可跨更多页面。放手保存排列,点击“完成”退出整理。关闭启动台或隐藏 Dock 会取消尚未完成的拖动。手动排列在收藏、搜索、刷新和重新打开后保持不变。收藏不会将图标移到前面,收藏分类按相同顺序筛选;尚无保存位置的应用按名称追加到末尾。
任一手柄的摇杆上下切换分类、左右翻页。每次拨动只取幅度较大的一个方向,回到中位范围后才允许再次导航,避免斜向或两个摇杆同时触发分类与翻页。
桌面程序从会话用户的 XDG 应用目录和 Flatpak 导出入口读取,隐藏入口及重复的 Steam 游戏快捷方式不会显示。Steam 安装的 APK 应用出现在 Lepton 分类,通过 Steam 启动;侧载应用从 Lepton 各容器的已安装 APK 与包数据库读取,排除空容器和 Android 系统组件,并在原有用户容器中启动。缺少 Android 名称、图片时使用包名和首字母。仅下载但未安装的 APK 不会加入启动台,读取应用列表也不会启动容器。
Steam 启动成功表示请求已交给 Steam,并不代表游戏加载完成。插件库版本可声明 `engines.framely`;当前本体不满足显示的范围时,请先升级本体。
## 分类与收藏
管理面板新增独立的 **启动台** 页面,集中设置扳机分配、菜单自动关闭及“全部包含的分类”。默认包含插件(含 Framely)、Steam、Lepton、桌面程序。关闭某个分类只影响“全部”,其单独分类和收藏仍可访问;全部关闭时,“全部”显示空状态。
所有类型的应用均可用悬停显示的星标收藏,已有插件与 Steam 收藏保持不变。停用插件不显示,暂时不可用的应用仍保留收藏记录。每次打开会清空搜索并重置分页,本地应用枚举完成后,有可显示的收藏则默认进入收藏,否则进入全部。在收藏页取消最后一个收藏时保持当前分类,显示空状态;下次打开才回退至全部。
## 搜索
点击顶部胶囊搜索框打开 VR 键盘。仅搜索当前分类,并保留原有排序;清空后恢复分类内容。键盘打开期间暂停摇杆导航及背景关闭,B先关闭键盘。搜索不会改变图标区域的固定大小或位置。
支持原文、英文单词首字母、中文拼音、日语罗马音及音节首字母。不区分大小写、全半角,忽略声调、空格与分隔符,支持前缀及连续片段。例如 `toushi`、`tiaose`、`tsts` 匹配“透视调色”;`sakura`、`skr` 匹配“さくら”;`toukyou` 匹配“東京”;`hla` 匹配“Half-Life: Alyx”。中文索引在有限大小内包含单字的其他读音,生僻名称或词组读音可能与实际读法不同。
索引在设备后台异步生成并缓存。中文使用离线拼音数据,日语使用随包提供的 Vibrato/IPADic 读音词典。汉字名称同时生成中文和日语候选,不依赖界面语言;词典无法识别的部分保留原文。读音索引尚未完成时仍可使用原文搜索,不会将应用名称发送至外部搜索服务。
会话接口:`launcher.search.index` 接收 `{names: string[]}`,返回名称对应的 `{terms: string[]}`。`launcher.favorite` 接收 `{key, favorite}`,使用与图标排列相同的稳定标识。插件和 Steam 仍更新原有收藏,`framely`、`desktop:` 和本地 `lepton:` 标识保存于 `launcherFavorites`。`launcher.settings.save` 新增 `allCategories`(`plugin`、`steam`、`lepton`、`desktop`);旧配置省略字段时默认全选,显式空数组表示全部不选。词典和许可说明位于发布包 `share/search`,同时包含于本体更新包和完整离线包。
已收藏应用的右上角显示常驻的蓝色实心星标,再次点击即可取消收藏;收藏状态变化不会改变图标排序。
+4
View File
@@ -93,3 +93,7 @@ restart 默认为 on-failure;never 只记录失败,不自动重启。restart
状态包含 starting、running、stopping、stopped、recovering、failed 等阶段,并发管理操作沿核心服务的串行调度执行。管理器正常 SIGTERM/SIGINT 会尝试逐个停止插件;强制终止、断电不能保证任何钩子执行。清理应同时可在下次启动时安全恢复。
日志页面合并展示后端日志与 lifecycle 日志;每种日志保留当前 2 MiB 与上一份。安装失败且插件尚未登记时,可从 `/var/lib/framely/logs/<id>.lifecycle.log` 查看。运行身份的数据目录为 `/var/lib/framely/data/<id>/<身份>/`(自定义核心数据目录时相应变化)。
## 启动上下文
[启动上下文](developer-guide/launcher.md)
+3 -3
View File
@@ -48,7 +48,7 @@ CEF 按内容哈希保存在 `/home/.framely/cef/<运行库标识>`,更新时
Framely 和桌面安装器保留在同一仓库,使用独立的版本号、标签和发布工作流:
- Framely:版本由根 `Cargo.toml` 定义,标签为 `v<版本>`(当前 `v0.4.2-preview.10`);`.github/workflows/release.yml` 只构建 Frame Linux ARM64 发行,使用锁定的 CEF 并执行自动检查。
- Framely:版本由根 `Cargo.toml` 定义,标签为 `v<版本>`(当前 `v0.4.2-preview.12`);`.github/workflows/release.yml` 只构建 Frame Linux ARM64 发行,使用锁定的 CEF 并执行自动检查。
- 安装器:版本由 `installer/Cargo.toml` 定义,标签为 `installer-v<版本>`(当前 `installer-v0.4.1-preview.8`);`.github/workflows/installer-release.yml` 只构建 Linux x64/ARM64、Windows x64、macOS x64/ARM64 的原生安装器,使用锁定的 GPUI Kit。
两个版本不需要相同,也不需要同时发布。修改各自版本时同步对应的 `Cargo.lock`;安装器包名及 macOS 应用版本使用安装器版本。
@@ -59,8 +59,8 @@ Framely 和桌面安装器保留在同一仓库,使用独立的版本号、标
```bash
# 提交并推送代码后,选择需要发布的产品
git tag v0.4.2-preview.10
git push origin v0.4.2-preview.10
git tag v0.4.2-preview.12
git push origin v0.4.2-preview.12
# 独立发布安装器,不触发 Framely 构建
git tag installer-v0.4.1-preview.8
+34 -3
View File
@@ -9,10 +9,11 @@
在 SteamVR Dashboard 点击 Framely Dock 图标打开快捷菜单。首次访问需阅读并同意协议及隐私声明;未同意时插件不会自动启动。
- **常用**:打开收藏的插件快捷页。
- **已安装**:查看本机插件,进入插件页面。
- **设置**:语言、安全模式和“管理插件”入口。
- **已安装**:查看已启用的本机插件,进入插件页面。
- **通知**:查看收件箱消息和更新提醒,并控制悬浮通知。
- **设置**:选择已安装的语言、切换安全模式,或打开“管理插件”和“检查更新”。“检查更新”打开管理窗口的关于/更新页面;安装语言文件和下载语言模板在管理窗口的设置中进行。
“管理插件”打开独立大窗口,左侧导航进入插件、插件库、插件源、设置和关于。安装、更新及来源管理在这里完成;电脑或手机也可使用[网络管理面板](network-panel.md)。
“管理插件”打开独立大窗口,左侧导航进入插件、插件库、插件源、设置、通知设置和关于。安装、更新及来源管理在这里完成;电脑或手机也可使用[网络管理面板](network-panel.md)。
## 插件启停与窗口
@@ -29,3 +30,33 @@
在“关于”选择正式版或测试版渠道并检查更新,点击“下载并安装”并确认一次:Framely 下载、校验发行包后自动开始安装。下载和校验分别显示阶段提示与实际字节进度。下载或校验失败时停止安装并显示原因。插件和数据保留,Framely 界面会暂时关闭并重新启动。
日志排查命令见[安装指南](installation.md#修复与日志)。界面能打开不代表所有插件都正常;先逐个启用,确认运行身份与来源可信。
## 通知收件箱与自动更新检查
快捷面板的“通知”标签展示明确设置为进入收件箱的消息,浮窗启用时,普通通知默认不保存;浮窗关闭时会转存到收件箱。浮动通知显示自动关闭倒计时,关闭浮动通知会保留已保存的收件箱副本;收件箱里的删除按钮会移除消息。通知按钮默认在操作成功后关闭弹窗并移除收件箱副本,发送方可以分别修改这两个行为。
“通知”顶部的“允许通知”开关控制全局浮窗。关闭后,新通知即使没有声明进入收件箱也会保存到这里,正在显示的浮窗也会转存。重新开启不会重新弹出旧消息。
悬浮通知跟随头显,显示在视野内右上方。激光命中区域与实际卡片对齐,短按按钮可容忍小幅追踪抖动。
管理窗口的“通知设置”提供全局“悬浮通知”和“启动图标角标”开关,并为 Framely 本体(包括更新提醒)及所有已安装插件(包括已停用插件)提供独立的“角标”和“悬浮”开关。全局开关优先,关闭后仍保留各应用偏好。Framely Dock 启动图标的角标统计允许显示角标来源的未读收件箱消息,超过 99 显示 `99+`;实际打开通知标签后消除角标,隐藏的头显面板不会自动标记已读。查看消息不会删除消息,也不会关闭其操作按钮。设置和已读状态均会保存并在重启后恢复。
本体默认在启动约 30 秒后检查更新(须已接受用户协议),之后每 6 小时检查一次;面板关闭时也会继续检查。可在管理窗口“关于”的更新页关闭自动检查或修改间隔。自动检查遵循所选正式版/测试版渠道及代理配置,只检查并提醒,不会自动下载或安装。
发现较新版本后会将提醒保存在收件箱,通知设置允许时同时显示浮窗。“忽略”关闭并移除此版本提醒,同一版本在重启后也不会重复提醒;“打开更新”直接打开管理窗口的更新页面。更改更新源或渠道会清除旧提醒。
## 导出日志
打开 **设置 → 恢复与诊断 → 导出日志**。在头显内,ZIP 保存到 Frame 的 `~/Downloads`,面板显示保存路径;通过网络面板访问时,ZIP 下载到浏览器。日志包包括本体与插件的近期日志、CEF 渲染日志、GPU 信息、服务状态和安装版本。缺失来源或命令失败会记录在 `report.json` 中,不影响导出其余信息;单个来源和总收集量均有大小限制。
管理面板无法打开时,使用安装器连接 Frame,点击底部的 **导出日志**,选择电脑上的保存位置。安装器直接通过 SSH 收集,也会加入当前安装器的操作日志;本体服务停止或状态文件损坏时仍可使用,无需选择发行版本或安装包。
日志包不包含插件配置、收件箱内容或密码文件,会过滤日志中的常见凭据格式;分享前仍应检查应用日志。不会自动上传。
无需运行本体服务,也可以通过终端导出:
```bash
sudo /var/lib/framely/current/bin/framely export-logs --output /tmp/framely-logs.zip
```
输出路径必须是新文件。本体程序无法运行时,解压发行包中的 `tools/export-diagnostics.py` 也可独立使用:`sudo python3 tools/export-diagnostics.py --output /tmp/framely-logs.zip`。
+1 -1
View File
@@ -1,4 +1,4 @@
import React,{useState} from 'react';
import {registerPlugin,framely,Section,Button} from '@framely/sdk';
function Page(){const [text,setText]=useState('');const [result,setResult]=useState('');const [count,setCount]=useState(0);async function run(f:()=>Promise<unknown>){try{setResult(JSON.stringify(await f(),null,2));}catch(e){setResult(String(e));}}return <><Section title="Framely 功能测试"><small>每个按钮都调用正式 SDK。</small><p><Button onClick={()=>setCount(n=>n+1)}>点击计数:{count}</Button><Button onClick={()=>void run(()=>framely.call('identity'))}>读取后端身份</Button></p></Section><Section title="输入与持久化"><input placeholder="点击后打开 Steam 虚拟键盘" value={text} onChange={e=>setText(e.target.value)}/><Button onClick={()=>void run(()=>framely.call('save',{text}))}>保存</Button><Button onClick={()=>void run(()=>framely.call('read'))}>读取</Button></Section><Section title="窗口"><Button onClick={()=>void run(()=>framely.windows.open('main'))}>打开原生 Dock 窗口</Button><Button onClick={()=>void run(()=>framely.windows.open('temporary'))}>打开临时窗口</Button><Button onClick={()=>void run(()=>framely.windows.close('main'))}>关闭大窗口</Button><Button onClick={()=>void run(()=>framely.windows.close('temporary'))}>关闭临时窗口</Button></Section><Section title="通知"><Button onClick={()=>void run(()=>framely.notifications.send({id:'showcase',title:'Framely 通知测试',body:'一张图片和三个按钮。重复发送会更新这条通知。',image:'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aN1kAAAAASUVORK5CYII=',durationMs:15000,actions:[{id:'ok',label:'确认',icon:'✓'},{id:'save',label:'保存',icon:'↓'},{id:'more',label:'详情',icon:'⋯'}]}))}>发送通知</Button><Button onClick={()=>void run(()=>framely.notifications.remove('showcase'))}>撤回</Button></Section><pre style={{whiteSpace:'pre-wrap',fontSize:16}}>{result}</pre><Section title="滚动测试">{Array.from({length:12},(_,i)=><p key={i}>测试条目 {i+1}</p>)}</Section></>}
function Page(){const [text,setText]=useState('');const [result,setResult]=useState('');const [count,setCount]=useState(0);async function run(f:()=>Promise<unknown>){try{setResult(JSON.stringify(await f(),null,2));}catch(e){setResult(String(e));}}return <><Section title="Framely 功能测试"><small>每个按钮都调用正式 SDK。</small><p><Button onClick={()=>setCount(n=>n+1)}>点击计数:{count}</Button><Button onClick={()=>void run(()=>framely.call('identity'))}>读取后端身份</Button></p></Section><Section title="输入与持久化"><input placeholder="点击后打开 Steam 虚拟键盘" value={text} onChange={e=>setText(e.target.value)}/><Button onClick={()=>void run(()=>framely.call('save',{text}))}>保存</Button><Button onClick={()=>void run(()=>framely.call('read'))}>读取</Button></Section><Section title="窗口"><Button onClick={()=>void run(()=>framely.windows.open('main'))}>打开原生 Dock 窗口</Button><Button onClick={()=>void run(()=>framely.windows.open('temporary'))}>打开临时窗口</Button><Button onClick={()=>void run(()=>framely.windows.close('main'))}>关闭大窗口</Button><Button onClick={()=>void run(()=>framely.windows.close('temporary'))}>关闭临时窗口</Button></Section><Section title="通知"><Button onClick={()=>void run(()=>framely.notifications.send({id:'showcase',inbox:true,title:'Framely 通知测试',body:'一张图片和三个按钮。重复发送会更新这条通知。',image:'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aN1kAAAAASUVORK5CYII=',durationMs:15000,actions:[{id:'ok',label:'确认',icon:'✓'},{id:'save',label:'保存',icon:'↓'},{id:'more',label:'详情',icon:'⋯'}]}))}>发送通知</Button><Button onClick={()=>void run(()=>framely.notifications.remove('showcase'))}>撤回</Button></Section><pre style={{whiteSpace:'pre-wrap',fontSize:16}}>{result}</pre><Section title="滚动测试">{Array.from({length:12},(_,i)=><p key={i}>测试条目 {i+1}</p>)}</Section></>}
registerPlugin({QuickPage:Page,WindowPage:Page});
+1 -1
View File
@@ -1985,7 +1985,7 @@ dependencies = [
[[package]]
name = "framely-installer"
version = "0.4.1-preview.8"
version = "0.4.1-preview.9"
dependencies = [
"anyhow",
"base64 0.22.1",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "framely-installer"
version = "0.4.1-preview.8"
version = "0.4.1-preview.9"
edition = "2024"
license = "AGPL-3.0-only"
+7 -1
View File
@@ -62,7 +62,7 @@ FRAMELY_INSTALLER_PREVIEW_DIR=installer/dist/previews installer/target/debug/fra
Preview requires an available GPU or software Vulkan renderer. Default release builds do not include preview support.
Installer versions are managed independently in this directory's `Cargo.toml` and `Cargo.lock`. Pushing an `installer-v<VERSION>` tag (currently `installer-v0.4.1-preview.8`) triggers `.github/workflows/installer-release.yml` to build and publish only the installer. The core uses `v<VERSION>` tags and a separate workflow. Manual Actions runs produce build artifacts only. Installer releases do not become the repository's Latest release, preserving Frame's default install/update URLs.
Installer versions are managed independently in this directory's `Cargo.toml` and `Cargo.lock`. Pushing an `installer-v<VERSION>` tag (currently `installer-v0.4.1-preview.9`) triggers `.github/workflows/installer-release.yml` to build and publish only the installer. The core uses `v<VERSION>` tags and a separate workflow. Manual Actions runs produce build artifacts only. Installer releases do not become the repository's Latest release, preserving Frame's default install/update URLs.
Actions builds Linux x64/ARM64, Windows x64, and macOS Intel/Apple Silicon. macOS produces an `.app` ZIP, Windows an EXE ZIP, and Linux a tar.gz. Apple notarization and Windows code signing are not configured; verify first-launch behavior on each system before publishing.
@@ -77,3 +77,9 @@ Discovery queries `frame.local` mDNS address records directly. It does not requi
```bash
cargo run --manifest-path installer/Cargo.toml --locked --no-default-features --example scan -- 192.168.5.0/24
```
## Export diagnostic logs
After connecting to Frame, click **Export logs** in the footer and choose a ZIP destination on your computer. You do not need to select a release or installation package. Collection runs directly over SSH with administrator access, independently of Framely’s web panel and daemon. It also works with stopped services or damaged state, and includes the installer’s current operation log. Export does not install, restart or change Framely.
The archive includes bounded recent service/plugin/CEF logs, GPU evidence, installation versions and a plugin status summary. Missing sources are listed in `report.json`. Plugin settings, inbox contents and password files are excluded; common credential patterns are masked. Review logs before sharing. Cancelling the save dialog leaves the installation untouched.
+7 -1
View File
@@ -62,7 +62,7 @@ FRAMELY_INSTALLER_PREVIEW_DIR=installer/dist/previews installer/target/debug/fra
预览依赖可用的 GPU 或软件 Vulkan 渲染器;默认发行构建不包含此预览功能。
安装器版本由本目录的 `Cargo.toml` 和 `Cargo.lock` 独立管理,不跟随 Framely 本体版本。推送 `installer-v<版本>` 标签(当前 `installer-v0.4.1-preview.8`)触发 `.github/workflows/installer-release.yml`,只构建并发布安装器;本体使用 `v<版本>` 标签和独立工作流。也可在 Actions 手动运行安装器工作流,仅生成构建产物。安装器 Release 不占用仓库的 Latest,以免影响 Frame 的默认安装和更新地址。
安装器版本由本目录的 `Cargo.toml` 和 `Cargo.lock` 独立管理,不跟随 Framely 本体版本。推送 `installer-v<版本>` 标签(当前 `installer-v0.4.1-preview.9`)触发 `.github/workflows/installer-release.yml`,只构建并发布安装器;本体使用 `v<版本>` 标签和独立工作流。也可在 Actions 手动运行安装器工作流,仅生成构建产物。安装器 Release 不占用仓库的 Latest,以免影响 Frame 的默认安装和更新地址。
Actions 构建 Linux x64/ARM64、Windows x64、macOS Intel/Apple Silicon。macOS 输出 `.app` ZIP,Windows 输出 EXE ZIP,Linux 输出 tar.gz。当前未配置 Apple 公证或 Windows 代码签名,发布前应分别验证系统的首次启动体验。
@@ -77,3 +77,9 @@ Actions 构建 Linux x64/ARM64、Windows x64、macOS Intel/Apple Silicon。macOS
```bash
cargo run --manifest-path installer/Cargo.toml --locked --no-default-features --example scan -- 192.168.5.0/24
```
## 导出诊断日志
连接 Frame 后,点击底部的 **导出日志**,选择电脑上的 ZIP 保存位置,无需选择发行版本或安装包。安装器通过 SSH 和管理员权限独立收集,不依赖网络面板或本体服务;服务停止、状态文件损坏时仍能导出,并包含安装器当前的操作日志。导出不会安装、重启或修改 Framely。
日志包包含有大小限制的近期服务、插件和 CEF 日志、GPU 信息、安装版本及插件状态摘要。缺失来源记录在 `report.json` 中。不包含插件设置、收件箱内容和密码文件,并过滤常见凭据格式;分享前仍应检查日志。取消保存弹窗不会改变安装状态。
+48
View File
@@ -42,6 +42,7 @@ enum Event {
Connected(Result<Connection, String>),
File(FileKind, Option<PathBuf>),
Log(String),
LogsExported(Result<Option<PathBuf>, String>),
Progress(Progress),
Done(Result<(), String>),
}
@@ -320,6 +321,20 @@ impl Installer {
self.status = progress.detail.clone();
self.progress = Some(progress);
}
Event::LogsExported(result) => {
self.busy = false;
match result {
Ok(Some(path)) => {
self.status = "日志已导出。".into();
self.notice("日志导出完成", format!("已保存到:{}", path.display()));
}
Ok(None) => self.status = "已取消导出日志。".into(),
Err(error) => {
self.status = "日志导出失败。".into();
self.notice("日志导出失败", error);
}
}
}
Event::Done(result) => {
self.busy = false;
self.error = None;
@@ -347,6 +362,39 @@ impl Installer {
}
self.present_prompt(window, cx);
}
fn export_logs(&mut self, cx: &mut Context<Self>) {
if self.busy {
return;
}
let Some(connection) = self.connection.clone() else {
return;
};
let password = Zeroizing::new(self.password.read(cx).value().to_string());
let sender = self.sender.clone();
self.busy = true;
self.status = "正在导出日志…".into();
let logs = self.logs.clone();
std::thread::spawn(move || {
let result = (|| -> anyhow::Result<Option<PathBuf>> {
let Some(path) = rfd::FileDialog::new()
.set_title("保存 Framely 日志包")
.set_file_name("framely-logs.zip")
.add_filter("ZIP 日志包", &["zip"])
.save_file()
else {
return Ok(None);
};
let guard = connection
.lock()
.map_err(|_| anyhow::anyhow!("设备连接不可用"))?;
remote::export_logs(&guard, &password, &path, &logs)?;
Ok(Some(path))
})()
.map_err(|e| format!("{e:#}"));
let _ = sender.send(Event::LogsExported(result));
});
cx.notify();
}
fn scan(&mut self, cx: &mut Context<Self>) {
self.cancelled.store(true, Ordering::Relaxed);
self.cancelled = Arc::new(AtomicBool::new(false));
+65
View File
@@ -507,3 +507,68 @@ mod tests {
eprintln!("stages={stages:?}; error={error}");
}
}
/// Collect directly over SSH; neither the web panel nor the daemon is required.
pub fn export_logs(
connection: &Connection,
password: &str,
destination: &Path,
logs: &[String],
) -> Result<()> {
use base64::engine::general_purpose::STANDARD;
ensure!(
!password.is_empty() && !password.contains(['\n', '\r']),
"请输入有效的设备登录密码"
);
connection.session.set_timeout(60_000);
let script = include_str!("../../tools/export-diagnostics.py");
// Keep archive output private and binary-safe. The ordinary text logger
// masks password substrings, which could corrupt a base64 archive.
let mut channel = connection.session.channel_session()?;
let local_log = logs.join("\n").replace(password, "[密码已隐藏]");
let recent: String = local_log
.chars()
.rev()
.take(64 * 1024)
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect();
channel.exec(&format!(
"sudo -S -p '' -- python3 -c {} --installer-log-base64 {}",
quote(script),
quote(&STANDARD.encode(recent))
))?;
channel.write_all(password.as_bytes())?;
channel.write_all(b"\n")?;
channel.flush()?;
channel.send_eof()?;
let mut output = String::new();
Read::by_ref(&mut channel)
.take(12 * 1024 * 1024)
.read_to_string(&mut output)?;
let mut error = String::new();
channel.stderr().take(4096).read_to_string(&mut error)?;
channel.wait_close()?;
ensure!(
channel.exit_status()? == 0,
"日志收集失败:{}",
error.replace(password, "[密码已隐藏]")
);
let archive: serde_json::Value =
serde_json::from_str(output.trim()).context("日志包响应无效")?;
let bytes = STANDARD.decode(archive["data"].as_str().context("日志包缺少数据")?)?;
ensure!(
bytes.len() <= 9 * 1024 * 1024 && bytes.starts_with(b"PK\x03\x04"),
"日志包格式无效"
);
let parent = destination
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let mut file = tempfile::NamedTempFile::new_in(parent).context("无法创建日志包")?;
file.write_all(&bytes).context("无法保存日志包")?;
file.as_file().sync_all()?;
file.persist(destination).context("无法保存日志包")?;
Ok(())
}
+6
View File
@@ -1111,6 +1111,12 @@ impl Render for Installer {
},
)),
);
footer = footer.child(
Button::new("export-diagnostic-logs")
.label("导出日志")
.disabled(self.busy || self.connection.is_none())
.on_click(cx.listener(|view, _, _, cx| view.export_logs(cx))),
);
if self.page < 2 {
let label = if self.page == 0 && self.connection.is_none() {
"先连接设备"
+237 -32
View File
@@ -8,13 +8,20 @@
#include "dock_uv_geometry.h"
#include "menu_geometry.h"
#include "menu_input.h"
#include "launcher_input.h"
#include "launcher_pointer.h"
#include <filesystem>
#include "overlay_placement.h"
#include "render_resolution.h"
#include "render_timing.h"
#include "paint_buffer.h"
#include "notification_geometry.h"
#include "notification_badge.h"
#include "keyboard_state.h"
#include "keyboard_input.h"
#include "brand_mask.h"
#include "ui_visibility.h"
#include "plugin_navigation.h"
#include <GL/gl.h>
#include <GL/glx.h>
#include <arpa/inet.h>
@@ -40,7 +47,25 @@ static vr::IVRSystem* vr_system=nullptr;
static Display* xdisplay=nullptr;
static GLXContext glcontext=nullptr;
static GLXPbuffer glsurface=0;
static std::atomic<unsigned> notification_badge_count{0};
static bool launcher_open=false;
static LauncherDismissGuard launcher_dismiss;
static LauncherDockGuard launcher_dock;
static EntryTrigger launcher_close_button;
static LauncherStick launcher_stick;
static std::chrono::steady_clock::time_point launcher_outside_at{};
static bool launcher_selected=false;
static std::chrono::steady_clock::time_point launcher_keyboard_back_until{};
static std::atomic<bool> launcher_primary{false};
static bool entry_actions_ready=false;
static vr::VRActionSetHandle_t entry_set=0;
static vr::VRActionHandle_t primary_action=0,upper_action=0,aim_action=0,close_action=0,navigate_action=0;
static vr::VRInputValueHandle_t hands[2]{};
static EntryTrigger entry_buttons[2][2];
static EntryAnalogTrigger entry_analog[2];
static EntryPointer entry_pointer;
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 cef_frame_t* keyboard_frame=nullptr;
@@ -59,9 +84,9 @@ template<class T> struct Handler {
};
struct View {
std::string key,plugin,title;int width=600,height=840,render_scale=1;bool dashboard=false,shown=false,dirty=false,closing=false,closed=false;
OverlayPlacement placement;std::chrono::steady_clock::time_point haptic_at{};
bool active_seen=false;int browser_id=0;cef_browser_t* browser=nullptr;cef_browser_host_t* host=nullptr;
vr::VROverlayHandle_t overlay=0,thumbnail=0;GLuint textures[2]{};int texture_slot=0;bool texture_ready[2]{};std::vector<uint8_t> pixels;
OverlayPlacement placement;NotificationClick notification_click;LauncherPointer launcher_pointer;std::chrono::steady_clock::time_point haptic_at{};
bool active_seen=false,notification_content=false;int browser_id=0;cef_browser_t* browser=nullptr;cef_browser_host_t* host=nullptr;
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 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;}
@@ -99,7 +124,7 @@ static json poll_http(int port){int fd=socket(AF_INET,SOCK_STREAM,0);if(fd<0)thr
// Keep a wider curved mesh around the narrow button; transparent margins never hit input.
static constexpr int dock_canvas_width=640,dock_canvas_height=128,dock_icon_left=256;
static std::vector<uint8_t> dock_icon(bool hover,bool active){
auto source=icon(hover,active);std::vector<uint8_t> canvas(dock_canvas_width*dock_canvas_height*4,0);
auto source=icon(hover,active);notification_badge(source,notification_badge_count.load());std::vector<uint8_t> canvas(dock_canvas_width*dock_canvas_height*4,0);
for(int row=0;row<dock_canvas_height;row++)std::copy_n(source.data()+row*128*4,128*4,canvas.data()+(row*dock_canvas_width+dock_icon_left)*4);
return canvas;
}
@@ -118,8 +143,31 @@ static void laser_cursor(vr::VROverlayHandle_t overlay,const vr::VREvent_t& even
if(event.eventType==vr::VREvent_MouseMove){vr::HmdVector2_t position{{event.data.mouse.x,event.data.mouse.y}};overlays->SetOverlayCursorPositionOverride(overlay,&position);}
else if(event.eventType==vr::VREvent_FocusLeave)overlays->ClearOverlayCursorPositionOverride(overlay);
}
static void show(View& v,bool shown){if(v.closing)return;if(v.key=="notifications")overlays->SetOverlayInputMethod(v.overlay,shown?vr::VROverlayInputMethod_Mouse:vr::VROverlayInputMethod_None);if(v.key=="menu"&&shown!=v.shown)overlays->SetOverlayFlag(v.overlay,vr::VROverlayFlags_WantsModalBehavior,shown&&!(keyboard_open&&keyboard_view=="menu"));bool actual=overlays->IsOverlayVisible(v.overlay);if(shown!=actual){auto e=shown?overlays->ShowOverlay(v.overlay):overlays->HideOverlay(v.overlay);if(e){std::cerr<<"Overlay visibility failed "<<v.key<<" "<<e<<"\n";return;}}if(shown!=v.shown){if(!shown)overlays->ClearOverlayCursorPositionOverride(v.overlay);if(v.key!="notifications")v.host->was_hidden(v.host,!shown);v.shown=shown;if(shown)v.host->invalidate(v.host,PET_VIEW);}}
static void close_keyboard(bool hide=true){if(keyboard_open&&hide)overlays->HideKeyboard();keyboard_open=false;keyboard_close_pending=false;keyboard_toolbar=false;keyboard_chars=false;keyboard_done=false;keyboard_target=0;keyboard_menu.end(std::chrono::steady_clock::now());if(keyboard_view=="menu"&&views.count("menu")&&!views.at("menu")->closing)overlays->SetOverlayFlag(views.at("menu")->overlay,vr::VROverlayFlags_WantsModalBehavior,views.at("menu")->shown);if(keyboard_frame){keyboard_frame->base.release(&keyboard_frame->base);keyboard_frame=nullptr;}keyboard_view.clear();}
static void update_menu_modal(){
if(!views.count("menu"))return;
auto& menu=*views.at("menu");
bool toast=views.count("notifications")&&views.at("notifications")->shown&&!views.at("notifications")->closing;
// A modal quick menu must not monopolize the laser while a toast needs input.
overlays->SetOverlayFlag(menu.overlay,vr::VROverlayFlags_WantsModalBehavior,menu.shown&&!toast&&!(keyboard_open&&keyboard_view=="menu"));
}
static void show(View& v,bool shown){
if(v.closing)return;
bool actual=overlays->IsOverlayVisible(v.overlay);
if(v.key=="notifications"&&(shown!=v.shown||shown!=actual)){
auto e=overlays->SetOverlayInputMethod(v.overlay,shown?vr::VROverlayInputMethod_Mouse:vr::VROverlayInputMethod_None);
if(!e)e=overlays->SetOverlayFlag(v.overlay,vr::VROverlayFlags_MakeOverlaysInteractiveIfVisible,shown);
if(e){std::cerr<<"Notification input state failed "<<e<<"\n";shown=false;overlays->SetOverlayInputMethod(v.overlay,vr::VROverlayInputMethod_None);}
}
if(shown!=actual){auto e=shown?overlays->ShowOverlay(v.overlay):overlays->HideOverlay(v.overlay);if(e){std::cerr<<"Overlay visibility failed "<<v.key<<" "<<e<<"\n";return;}}
if(shown!=v.shown){
if(!shown){overlays->ClearOverlayCursorPositionOverride(v.overlay);if(v.key=="notifications"&&v.notification_click.active){cef_mouse_event_t outside{};outside.x=outside.y=-1;v.host->send_mouse_click_event(v.host,&outside,MBT_LEFT,1,1);v.notification_click.clear();}}
if(v.key!="notifications")v.host->was_hidden(v.host,!shown);
v.shown=shown;if(shown)v.host->invalidate(v.host,PET_VIEW);
if(v.key=="menu"||v.key=="notifications")update_menu_modal();
}
}
static void keyboard_state(bool open){if(keyboard_frame)execute(keyboard_frame,std::string("window.dispatchEvent(new CustomEvent('framely.keyboard',{detail:")+(open?"true":"false")+"}))");}
static void close_keyboard(bool hide=true){keyboard_state(false);if(keyboard_open&&hide)overlays->HideKeyboard();keyboard_open=false;keyboard_close_pending=false;keyboard_toolbar=false;keyboard_chars=false;keyboard_done=false;keyboard_target=0;keyboard_menu.end(std::chrono::steady_clock::now());if(keyboard_view=="menu")update_menu_modal();if(keyboard_frame){keyboard_frame->base.release(&keyboard_frame->base);keyboard_frame=nullptr;}keyboard_view.clear();}
static bool keyboard_event(const vr::VREvent_t& e,vr::VROverlayHandle_t source_overlay=0){
// The runtime toolbar opens the keyboard without a host.keyboard request.
if(e.eventType==vr::VREvent_KeyboardOpened_Global){
@@ -130,7 +178,7 @@ static bool keyboard_event(const vr::VREvent_t& e,vr::VROverlayHandle_t source_o
close_keyboard(false);owner->host->set_focus(owner->host,1);
keyboard_frame=owner->browser->get_focused_frame(owner->browser);keyboard_view=owner->key;
keyboard_target=target;keyboard_token=e.data.keyboard.uUserValue;keyboard_open=true;keyboard_toolbar=true;
keyboard_menu.begin(owner->key=="menu");return true;
keyboard_menu.begin(owner->key=="menu");keyboard_state(true);return true;
}
if(e.eventType!=vr::VREvent_KeyboardCharInput&&e.eventType!=vr::VREvent_KeyboardDone&&e.eventType!=vr::VREvent_KeyboardClosed&&e.eventType!=vr::VREvent_KeyboardClosed_Global)return false;
if(!keyboard_open)return true;
@@ -144,24 +192,37 @@ static bool keyboard_event(const vr::VREvent_t& e,vr::VROverlayHandle_t source_o
}
static void close_view(View& v){if(v.closing)return;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 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_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.
vr::HmdMatrix34_t head{{{1,0,0,0},{0,1,0,0},{0,0,1,0}}};
NotificationPlacement toast{};
if(!notification_placement(head,notification_curve_radius,toast))return;
auto error=overlays->SetOverlayWidthInMeters(v.overlay,toast.width);
if(!error)error=overlays->SetOverlayTransformTrackedDeviceRelative(v.overlay,vr::k_unTrackedDeviceIndex_Hmd,&toast.transform);
if(error){std::cerr<<"Notification head attachment failed "<<error<<"\n";return;}
v.placement.transform=toast.transform;v.placement.width=toast.width;v.placement.valid=true;
v.placement.curve(overlays,v.overlay,toast.width,toast.radius);
}
static View& create_view(const std::string& key,const std::string& title,const std::string& url,bool dock,int width,int height,const std::string& plugin="",float physical_width=0){
if(views.count(key)){auto& v=*views.at(key);if(dock)overlays->ShowDashboard(key.c_str());else if(key!="notifications")show(v,true);return v;}
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=dock;v->width=width;v->height=height;v->render_scale=key=="framely.manager"?4:(key=="menu"||key=="notifications")?2:1;
if(views.count(key)){auto& v=*views.at(key);if(dock&&key!="launcher")overlays->ShowDashboard(key.c_str());else if(key!="notifications"&&key!="launcher")show(v,true);return v;}
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=dock;v->width=width;v->height=height;v->render_scale=(key=="framely.manager"||key=="launcher")?4:(key=="menu"||key=="notifications")?2:1;
auto error=dock?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,key=="notifications"?100: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,false);overlays->SetOverlaySortOrder(v->overlay,0);
// Keep the runtime's full dashboard controls, including its keyboard and close buttons.
if(dock){
auto result=overlays->SetOverlayFlag(v->overlay,vr::VROverlayFlags_MinimalControlBar,false);
if(key=="launcher")overlays->SetOverlayFlag(v->overlay,vr::VROverlayFlags_NoDashboardTab,true);
auto result=overlays->SetOverlayFlag(v->overlay,vr::VROverlayFlags_MinimalControlBar,key=="launcher");
if(result)std::cerr<<"Dashboard controls unavailable "<<key<<" "<<result<<"\n";
for(auto flag:{vr::VROverlayFlags_EnableControlBarKeyboard,vr::VROverlayFlags_EnableControlBarClose}){
result=overlays->SetOverlayFlag(v->overlay,flag,true);
if(result)std::cerr<<"Dashboard control unavailable "<<key<<" "<<result<<"\n";
}
}
if(dock){auto pixels=icon(false,true);overlays->SetOverlayRaw(v->thumbnail,pixels.data(),128,128,4);overlays->SetOverlayWidthInMeters(v->overlay,physical_width>0?physical_width:(key=="framely.manager"?3.2f:1.2f));}else if(key!="menu"&&key!="notifications"){anchor_to_head(*v,physical_width>0?physical_width:1.0f);}
cef_window_info_t info{};info.size=sizeof(info);info.windowless_rendering_enabled=1;cef_browser_settings_t bs{};bs.size=sizeof(bs);bs.windowless_frame_rate=30;bs.background_color=0;cef_string_t uri{};str(uri,url);auto* browser=cef_browser_host_create_browser_sync(&info,&client.api,&uri,&bs,nullptr,nullptr);cef_string_utf16_clear(&uri);
if(!browser){overlays->DestroyOverlay(v->overlay);if(v->thumbnail)overlays->DestroyOverlay(v->thumbnail);throw std::runtime_error("Browser creation failed");}v->browser=browser;v->browser_id=browser->get_identifier(browser);v->host=browser->get_host(browser);glGenTextures(2,v->textures);auto* ptr=v.get();views.emplace(key,std::move(v));ptr->host->notify_screen_info_changed(ptr->host);ptr->host->was_resized(ptr->host);ptr->host->was_hidden(ptr->host,key!="notifications");if(dock)overlays->ShowDashboard(key.c_str());else if(key!="menu"&&key!="notifications")show(*ptr,true);return *ptr;
if(dock){auto pixels=icon(false,true);overlays->SetOverlayRaw(v->thumbnail,pixels.data(),128,128,4);overlays->SetOverlayWidthInMeters(v->overlay,physical_width>0?physical_width:(key=="framely.manager"?3.2f:key=="launcher"?3.f:1.2f));}else if(key!="menu"&&key!="notifications"&&key!="launcher"){anchor_to_head(*v,physical_width>0?physical_width:1.0f);}
cef_window_info_t info{};info.size=sizeof(info);info.windowless_rendering_enabled=1;cef_browser_settings_t bs{};bs.size=sizeof(bs);bs.windowless_frame_rate=browser_frame_rate();bs.background_color=0;std::cout<<"Browser frame rate "<<key<<" "<<bs.windowless_frame_rate<<"\n";cef_string_t uri{};str(uri,url);auto* browser=cef_browser_host_create_browser_sync(&info,&client.api,&uri,&bs,nullptr,nullptr);cef_string_utf16_clear(&uri);
if(!browser){overlays->DestroyOverlay(v->overlay);if(v->thumbnail)overlays->DestroyOverlay(v->thumbnail);throw std::runtime_error("Browser creation failed");}v->browser=browser;v->browser_id=browser->get_identifier(browser);v->host=browser->get_host(browser);glGenTextures(2,v->textures);auto* ptr=v.get();views.emplace(key,std::move(v));ptr->host->notify_screen_info_changed(ptr->host);ptr->host->was_resized(ptr->host);ptr->host->was_hidden(ptr->host,key!="notifications");if(dock&&key!="launcher")overlays->ShowDashboard(key.c_str());else if(key!="menu"&&key!="notifications"&&key!="launcher")show(*ptr,true);return *ptr;
}
static void plugin_thumbnail(View& view,const std::string& encoded){
if(!view.thumbnail||encoded.empty()||encoded.size()>1400000)return;
@@ -177,9 +238,121 @@ static void plugin_thumbnail(View& view,const std::string& encoded){
for(int y=0;y<h;y++)for(int x=0;x<w;x++){int sx=std::min(width-1,int(x/scale)),sy=std::min(height-1,int(y/scale));std::copy_n(source.data()+(sy*width+sx)*4,4,pixels.data()+((y+(128-h)/2)*128+x+(128-w)/2)*4);}
overlays->SetOverlayRaw(view.thumbnail,pixels.data(),128,128,4);
}
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=="haptic"){auto key=c.value("view","");if(views.count(key)&&views.at(key)->shown&&!views.at(key)->closing)hover_haptic(views.at(key)->overlay,views.at(key)->haptic_at);}else if(kind=="manager.open"){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"+(page=="catalog"?"#catalog":""),true,1440,810);if(page=="catalog"){auto* frame=manager.browser->get_main_frame(manager.browser);execute(frame,"location.hash=\"catalog\";window.dispatchEvent(new Event(\"hashchange\"))");frame->base.release(&frame->base);}menu_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=="window.open"){std::string plugin=c.at("plugin"),win=c.at("window");auto key="framely.window."+plugin+"."+win;if(views.count(key)&&views.at(key)->closing){std::lock_guard<std::mutex> lock(queue_mutex);queue.push_back(c);continue;}auto spec=c.at("spec");auto& opened=create_view("framely.window."+plugin+"."+win,spec.at("title"),origin+"/window/"+plugin+"/"+win,spec.value("dockIcon",false),spec.value("width",1600),spec.value("height",900),plugin,spec.value("widthMeters",3.f));plugin_thumbnail(opened,spec.value("iconData",std::string{}));menu_open=false;}else if(kind=="window.close"){auto key="framely.window."+c.at("plugin").get<std::string>()+"."+c.at("window").get<std::string>();if(views.count(key))close_view(*views.at(key));}else if(kind=="plugin.disabled"){for(auto&[key,v]:views)if(v->plugin==c.at("plugin"))close_view(*v);}else if(kind=="notification.changed"){auto& v=create_view("notifications","Framely notifications",origin+"/notifications",false,600,360);anchor_to_head(v,.42f,.42f,.32f,-.8f);v.host->was_hidden(v.host,0);v.host->invalidate(v.host,PET_VIEW);}else if(kind=="keyboard"){auto key=c.value("view","menu");if(!views.count(key))continue;auto& v=*views.at(key);if(v.closing)continue;close_keyboard();v.host->set_focus(v.host,1);keyboard_frame=v.browser->get_focused_frame(v.browser);keyboard_view=key;keyboard_target=v.overlay;++keyboard_token;auto existing=c.value("existing","");if(key=="menu")overlays->SetOverlayFlag(v.overlay,vr::VROverlayFlags_WantsModalBehavior,false);auto e=overlays->ShowKeyboardForOverlay(v.overlay,c.value("password",false)?vr::k_EGamepadTextInputModePassword:vr::k_EGamepadTextInputModeNormal,c.value("multiline",false)?vr::k_EGamepadTextInputLineModeMultipleLines:vr::k_EGamepadTextInputLineModeSingleLine,vr::KeyboardFlag_Modal|vr::KeyboardFlag_Minimal|vr::KeyboardFlag_ShowArrowKeys,"Framely",4096,existing.c_str(),keyboard_token);keyboard_open=e==vr::VROverlayError_None;keyboard_menu.begin(keyboard_open&&key=="menu");if(!keyboard_open)close_keyboard();}else if(kind=="notifications.empty"){if(views.count("notifications"))show(*views.at("notifications"),false);}}catch(const std::exception& e){std::cerr<<"Native command error: "<<e.what()<<"\n";}}
static void navigate(View& view,const std::string& hash){auto* frame=view.browser->get_main_frame(view.browser);execute(frame,"location.hash="+json(hash).dump()+";window.dispatchEvent(new Event('hashchange'))");frame->base.release(&frame->base);}
static bool launcher_dock_interaction(){
// These are Steam's Dock bar and native window controls on Frame, not app
// content. The runtime keeps ownership of their positioning and interaction.
bool hovered=false;
for(const char* key:{"valve.steam.gamepadui.bar","valve.steam.gamepadui.floatingfooter","system.systemui"}){
vr::VROverlayHandle_t overlay=0;
if(!overlays->FindOverlay(key,&overlay)&&overlays->IsOverlayVisible(overlay)&&overlays->IsHoverTargetOverlay(overlay))hovered=true;
}
bool held=false;for(auto& hand:entry_buttons)for(auto& trigger:hand)held|=trigger.held;
auto now=std::chrono::steady_clock::now();launcher_dock.observe(hovered,held,now);
if(launcher_dock.holds(now)){launcher_outside_at={};return true;}
return false;
}
static void overlay_input(View& v,const vr::VREvent_t& e){if(v.closing||(v.key=="notifications"&&!v.shown))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);switch(e.eventType){case vr::VREvent_Modal_Cancel: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!="menu"&&v.key!="notifications")close_view(v);break;case vr::VREvent_ButtonPress:if(e.data.controller.button==vr::k_EButton_ApplicationMenu){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:v.host->send_mouse_move_event(v.host,&mouse,1);break;case vr::VREvent_MouseMove: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;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:mouse.x=v.width/2;mouse.y=v.height/2;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")close_view(v);break;default:break;}}
static void hide_launcher(){
if(keyboard_view=="launcher")close_keyboard();
launcher_open=false;launcher_selected=false;launcher_dock.clear();
if(views.count("launcher")&&overlays->IsActiveDashboardOverlay(views.at("launcher")->overlay))
overlays->ShowDashboard("valve.steam.gamepadui.main");
}
static void launcher_back(){
auto now=std::chrono::steady_clock::now();if(now<launcher_keyboard_back_until)return;
if(keyboard_open){launcher_keyboard_back_until=now+std::chrono::milliseconds(180);close_keyboard();return;}
if(!launcher_open||!views.count("launcher"))return;
auto& view=*views.at("launcher");auto* frame=view.browser->get_main_frame(view.browser);
execute(frame,"window.dispatchEvent(new Event('framely.back'))");frame->base.release(&frame->base);
}
static bool launcher_accepts(const vr::VREvent_t& e){
bool held=false;for(auto& hand:entry_buttons)for(auto& button:hand)held|=button.held;
return launcher_dismiss.allows(std::chrono::steady_clock::now(),held,e.eventAgeSeconds);
}
static void toggle_entry(bool launcher){
if(launcher){
menu_open=false;if(views.count("menu"))show(*views.at("menu"),false);
if(launcher_open){hide_launcher();return;}
auto& view=create_view("launcher","Framely launcher",origin+"/launcher",true,1200,800);
vr::VREvent_t stale{};while(overlays->PollNextOverlayEvent(view.overlay,&stale,sizeof(stale))){}
launcher_dock.clear();launcher_dismiss.opened(std::chrono::steady_clock::now());launcher_open=true;launcher_selected=false;launcher_stick={};launcher_outside_at={};
overlays->ShowDashboard("launcher");
auto* frame=view.browser->get_main_frame(view.browser);execute(frame,"window.dispatchEvent(new Event('framely.launcher.open'))");frame->base.release(&frame->base);
}else{hide_launcher();menu_open=!menu_open;if(menu_open)menu_button.opened(std::chrono::steady_clock::now());}
}
static void setup_entry_actions(){
char exe[4096]{};auto n=readlink("/proc/self/exe",exe,sizeof(exe)-1);if(n<=0)return;
auto base=std::filesystem::path(exe).parent_path();auto manifest=base/"../../share/input/actions.json";
if(!std::filesystem::exists(manifest))manifest=base/"../../native/input/actions.json";
auto* input=vr::VRInput();if(!input||!std::filesystem::exists(manifest))return;
auto error=input->SetActionManifestPath(std::filesystem::absolute(manifest).lexically_normal().c_str());if(error!=vr::VRInputError_None){std::cerr<<"Action manifest failed: "<<error<<std::endl;return;}
entry_actions_ready=input->GetActionSetHandle("/actions/entry",&entry_set)==vr::VRInputError_None&&input->GetActionHandle("/actions/entry/in/primary",&primary_action)==vr::VRInputError_None&&input->GetActionHandle("/actions/entry/in/upper",&upper_action)==vr::VRInputError_None&&input->GetActionHandle("/actions/entry/in/aim",&aim_action)==vr::VRInputError_None;
input->GetActionHandle("/actions/entry/in/close",&close_action);input->GetActionHandle("/actions/entry/in/navigate",&navigate_action);
input->GetInputSourceHandle("/user/hand/left",&hands[0]);input->GetInputSourceHandle("/user/hand/right",&hands[1]);
std::cout<<"Framely independent trigger bindings "<<(entry_actions_ready?"ready":"unavailable")<<std::endl;
}
static void entry_actions(vr::VROverlayHandle_t button,bool available){
if(!entry_actions_ready)return;auto* input=vr::VRInput();vr::VRActiveActionSet_t set{};set.ulActionSet=entry_set;
if(input->UpdateActionState(&set,sizeof(set),1)!=vr::VRInputError_None)return;
auto now=std::chrono::steady_clock::now();
float stick_x=0,stick_y=0;bool stick_active=false;
for(int hand=0;hand<2;hand++){
vr::InputPoseActionData_t pose{};auto device=vr_system->GetTrackedDeviceIndexForControllerRole(hand?vr::TrackedControllerRole_RightHand:vr::TrackedControllerRole_LeftHand);bool hit=available&&entry_pointer.hit(device);
bool pose_ok=available&&input->GetPoseActionDataRelativeToNow(aim_action,vr::TrackingUniverseStanding,0,&pose,sizeof(pose),hands[hand])==vr::VRInputError_None&&pose.bActive&&pose.pose.bPoseIsValid;
if(available&&!pose_ok&&device!=vr::k_unTrackedDeviceIndexInvalid){
vr::TrackedDevicePose_t tracked[vr::k_unMaxTrackedDeviceCount]{};vr_system->GetDeviceToAbsoluteTrackingPose(vr::TrackingUniverseStanding,0,tracked,vr::k_unMaxTrackedDeviceCount);
char model[256]{};vr_system->GetStringTrackedDeviceProperty(device,vr::Prop_RenderModelName_String,model,sizeof(model));
vr::RenderModel_ControllerMode_State_t mode{};vr::RenderModel_ComponentState_t tip{};
if(tracked[device].bDeviceIsConnected&&tracked[device].bPoseIsValid&&vr::VRRenderModels()->GetComponentStateForDevicePath(model,"tip",hands[hand],&mode,&tip)){
pose.pose.mDeviceToAbsoluteTracking=entry_tip_pose(tracked[device].mDeviceToAbsoluteTracking,tip.mTrackingToComponentLocal);pose_ok=true;
}
}
if(pose_ok){auto& m=pose.pose.mDeviceToAbsoluteTracking;vr::VROverlayIntersectionParams_t params{};params.eOrigin=vr::TrackingUniverseStanding;for(int r=0;r<3;r++){params.vSource.v[r]=m.m[r][3];params.vDirection.v[r]=-m.m[r][2];}vr::VROverlayIntersectionResults_t result{};hit=hit||(overlays->IsHoverTargetOverlay(button)&&overlays->ComputeOverlayIntersection(button,&params,&result)&&result.vUVs.v[0]>=float(dock_icon_left)/dock_canvas_width&&result.vUVs.v[0]<=float(dock_icon_left+128)/dock_canvas_width);}
for(int kind=0;kind<2;kind++){vr::InputDigitalActionData_t data{};bool active=input->GetDigitalActionData(kind?upper_action:primary_action,&data,sizeof(data),hands[hand])==vr::VRInputError_None&&data.bActive;
bool down=data.bState;if(kind==0&&active)entry_analog[hand].held=down;
// Dashboard focus suppresses action data. Frame's render-model components
// read the separate physical input paths, without changing Steam bindings
// or the user's global input-override setting.
if(!active&&device!=vr::k_unTrackedDeviceIndexInvalid&&vr_system->IsTrackedDeviceConnected(device)){
char type[256]{},model[256]{};vr_system->GetStringTrackedDeviceProperty(device,vr::Prop_ControllerType_String,type,sizeof(type));
if(std::string(type)=="frame_controller"){
vr_system->GetStringTrackedDeviceProperty(device,vr::Prop_RenderModelName_String,model,sizeof(model));
vr::RenderModel_ControllerMode_State_t mode{};vr::RenderModel_ComponentState_t state{};
active=vr::VRRenderModels()->GetComponentStateForDevicePath(model,kind?"bumper":"trigger",hands[hand],&mode,&state);
down=active&&(state.uProperties&vr::VRComponentProperty_IsPressed);
if(active&&kind==0){
// Frame's primary trigger is analog: its animated component has no
// IsPressed flag. Calibrate its travel from the model's legacy axis 1,
// then match Steam's 50% press / 45% release thresholds.
vr::VRControllerState_t rest_input{},full_input{};full_input.rAxis[1].x=1;
vr::RenderModel_ComponentState_t rest{},full{};float pull=0;
if(vr::VRRenderModels()->GetComponentState(model,"trigger",&rest_input,&mode,&rest)&&vr::VRRenderModels()->GetComponentState(model,"trigger",&full_input,&mode,&full)&&entry_trigger_pull(rest,full,state,pull))down=entry_analog[hand].update(pull)||down;
}
}
}
if(kind==0&&!active)entry_analog[hand].held=false;
bool was_held=entry_buttons[hand][kind].held;
if(entry_buttons[hand][kind].update(active,down,hit,now))toggle_entry(kind==0?launcher_primary.load():!launcher_primary.load());
else if(kind==0&&active&&down&&!was_held&&launcher_open&&!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);
}
if(!launcher_open)continue;
if(hand==1){vr::InputDigitalActionData_t close{};bool active=input->GetDigitalActionData(close_action,&close,sizeof(close),hands[hand])==vr::VRInputError_None&&close.bActive;bool down=close.bState;
if(!active&&device!=vr::k_unTrackedDeviceIndexInvalid&&vr_system->IsTrackedDeviceConnected(device)){char model[256]{};vr_system->GetStringTrackedDeviceProperty(device,vr::Prop_RenderModelName_String,model,sizeof(model));vr::RenderModel_ControllerMode_State_t mode{};vr::RenderModel_ComponentState_t state{};active=vr::VRRenderModels()->GetComponentStateForDevicePath(model,"button_b",hands[hand],&mode,&state);down=active&&(state.uProperties&vr::VRComponentProperty_IsPressed);}
if(launcher_close_button.update(active,down,true,now))launcher_back();
}
vr::InputAnalogActionData_t axis{};bool active=input->GetAnalogActionData(navigate_action,&axis,sizeof(axis),hands[hand])==vr::VRInputError_None&&axis.bActive;float x=axis.x,y=axis.y;
if(!active&&device!=vr::k_unTrackedDeviceIndexInvalid&&vr_system->IsTrackedDeviceConnected(device)){char model[256]{};vr_system->GetStringTrackedDeviceProperty(device,vr::Prop_RenderModelName_String,model,sizeof(model));vr::RenderModel_ControllerMode_State_t mode{};vr::RenderModel_ComponentState_t rest{},full_x{},full_y{},current{};vr::VRControllerState_t neutral{},sx{},sy{};sx.rAxis[0].x=1;sy.rAxis[0].y=1;auto* models=vr::VRRenderModels();active=models->GetComponentStateForDevicePath(model,"thumbstick",hands[hand],&mode,&current)&&models->GetComponentState(model,"thumbstick",&neutral,&mode,&rest)&&models->GetComponentState(model,"thumbstick",&sx,&mode,&full_x)&&models->GetComponentState(model,"thumbstick",&sy,&mode,&full_y)&&launcher_stick_axes(rest,full_x,full_y,current,x,y);}
// Pick a single controller and a single axis; never emit two directions.
if(active&&(!stick_active||std::max(std::abs(x),std::abs(y))>std::max(std::abs(stick_x),std::abs(stick_y)))){stick_active=true;stick_x=x;stick_y=y;}
}
if(launcher_open){int direction=launcher_stick.update(keyboard_open?0:stick_x,keyboard_open?0:stick_y,!keyboard_open&&stick_active);if(direction&&views.count("launcher")){auto* frame=views.at("launcher")->browser->get_main_frame(views.at("launcher")->browser);execute(frame,"window.dispatchEvent(new CustomEvent('framely.launcher.navigate',{detail:"+std::to_string(direction)+"}))");frame->base.release(&frame->base);}}
else{launcher_stick={};launcher_close_button={};}
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=="launcher.close"){hide_launcher();}else if(kind=="menu.open"){hide_launcher();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)hover_haptic(views.at(key)->overlay,views.at(key)->haptic_at);}else if(kind=="manager.open"){hide_launcher();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"+((page=="catalog"||page=="updates"||page=="notification-settings"||page=="launcher-settings"||page.rfind("plugin:",0)==0)?"#"+page:""),true,1440,810);if(page.rfind("plugin:",0)==0)navigate(manager,"#"+page);if(page=="catalog"||page=="updates"||page=="notification-settings"||page=="launcher-settings"){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=="window.open"){hide_launcher();std::string plugin=c.at("plugin"),win=c.at("window");auto key="framely.window."+plugin+"."+win;if(views.count(key)&&views.at(key)->closing){std::lock_guard<std::mutex> lock(queue_mutex);queue.push_back(c);continue;}auto spec=c.at("spec");auto& opened=create_view("framely.window."+plugin+"."+win,spec.at("title"),origin+"/window/"+plugin+"/"+win,spec.value("dockIcon",false),spec.value("width",1600),spec.value("height",900),plugin,spec.value("widthMeters",3.f));plugin_thumbnail(opened,spec.value("iconData",std::string{}));menu_open=false;launcher_open=false;}else if(kind=="window.close"){auto key="framely.window."+c.at("plugin").get<std::string>()+"."+c.at("window").get<std::string>();if(views.count(key))close_view(*views.at(key));}else if(kind=="plugin.disabled"){for(auto&[key,v]:views)if(v->plugin==c.at("plugin"))close_view(*v);}else if(kind=="notification.changed"){auto& v=create_view("notifications","Framely notifications",origin+"/notifications",false,600,360);anchor_notification(v);v.host->was_hidden(v.host,0);v.host->invalidate(v.host,PET_VIEW);}else if(kind=="keyboard"){auto key=c.value("view","menu");if(!views.count(key))continue;auto& v=*views.at(key);if(v.closing)continue;close_keyboard();v.host->set_focus(v.host,1);keyboard_frame=v.browser->get_focused_frame(v.browser);keyboard_view=key;keyboard_target=v.overlay;++keyboard_token;auto existing=c.value("existing","");if(key=="menu")overlays->SetOverlayFlag(v.overlay,vr::VROverlayFlags_WantsModalBehavior,false);auto e=overlays->ShowKeyboardForOverlay(v.overlay,c.value("password",false)?vr::k_EGamepadTextInputModePassword:vr::k_EGamepadTextInputModeNormal,c.value("multiline",false)?vr::k_EGamepadTextInputLineModeMultipleLines:vr::k_EGamepadTextInputLineModeSingleLine,vr::KeyboardFlag_Modal|vr::KeyboardFlag_Minimal|vr::KeyboardFlag_ShowArrowKeys,"Framely",4096,existing.c_str(),keyboard_token);keyboard_open=e==vr::VROverlayError_None;keyboard_menu.begin(keyboard_open&&key=="menu");keyboard_state(keyboard_open);if(!keyboard_open)close_keyboard();}else if(kind=="notifications.empty"){if(views.count("notifications")){views.at("notifications")->notification_content=false;show(*views.at("notifications"),false);}}}catch(const std::exception& e){std::cerr<<"Native command error: "<<e.what()<<"\n";}}
}
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_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);switch(e.eventType){case vr::VREvent_Modal_Cancel:if(v.key=="launcher"&&!keyboard_open&&!launcher_dock_interaction())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:mouse.x=v.width/2;mouse.y=v.height/2;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")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];}
@@ -193,22 +366,22 @@ int main(int argc,char** argv){
vr::VR_Shutdown();
// Frame's compositor requires the Overlay application type for visible UI.
// The session agent and service gate this renderer on all native services.
vr_system=vr::VR_Init(&vr_error,vr::VRApplication_Overlay);if(vr_error){std::cerr<<"SteamVR renderer unavailable "<<vr_error<<"\n";return 3;}overlays=vr::VROverlay();
vr_system=vr::VR_Init(&vr_error,vr::VRApplication_Overlay);if(vr_error){std::cerr<<"SteamVR renderer unavailable "<<vr_error<<"\n";return 3;}overlays=vr::VROverlay();setup_entry_actions();
xdisplay=XOpenDisplay(nullptr);if(!xdisplay){vr::VR_Shutdown();return 4;}int n=0;int attrs[]={GLX_DRAWABLE_TYPE,GLX_PBUFFER_BIT,GLX_RENDER_TYPE,GLX_RGBA_BIT,None};auto* configs=glXChooseFBConfig(xdisplay,DefaultScreen(xdisplay),attrs,&n);if(!configs||!n){vr::VR_Shutdown();return 4;}int pba[]={GLX_PBUFFER_WIDTH,16,GLX_PBUFFER_HEIGHT,16,None};glsurface=glXCreatePbuffer(xdisplay,configs[0],pba);glcontext=glXCreateNewContext(xdisplay,configs[0],GLX_RGBA_TYPE,nullptr,True);XFree(configs);if(!glcontext||!glXMakeContextCurrent(xdisplay,glsurface,glsurface,glcontext)){vr::VR_Shutdown();return 4;}
cef_settings_t settings{};settings.size=sizeof(settings);settings.windowless_rendering_enabled=1;std::string locale;for(const char* key:{"LC_ALL","LC_MESSAGES","LANG"}){const char* value=std::getenv(key);if(value&&*value){locale=value;break;}}auto suffix=locale.find_first_of(".@");if(suffix!=std::string::npos)locale.erase(suffix);std::replace(locale.begin(),locale.end(),'_','-');if(locale=="C"||locale=="POSIX"||locale.empty())locale="en-US";str(settings.accept_language_list,locale+",en-US,en");str(settings.root_cache_path,runtime+"/cef-cache");str(settings.log_file,runtime+"/cef.log");if(!cef_initialize(&args,&settings,nullptr,nullptr)){vr::VR_Shutdown();return 5;}
render_handler.api.get_view_rect=[](cef_render_handler_t*,cef_browser_t* b,cef_rect_t* r){auto* v=find_browser(b);*r={0,0,v?v->width:600,v?v->height:840};};
render_handler.api.get_screen_info=[](cef_render_handler_t*,cef_browser_t* b,cef_screen_info_t* info){auto* v=find_browser(b);return render_screen_info(info,v?v->width:600,v?v->height:840,v?v->render_scale:1);};
render_handler.api.on_paint=[](cef_render_handler_t*,cef_browser_t* b,cef_paint_element_type_t type,size_t,const cef_rect_t*,const void* data,int w,int h){auto* v=find_browser(b);if(!v||v->closing||type!=PET_VIEW||w!=v->width*v->render_scale||h!=v->height*v->render_scale)return;v->pixels.resize(w*h*4);auto* source=static_cast<const uint8_t*>(data);for(int y=0;y<h;y++)std::copy_n(source+y*w*4,w*4,v->pixels.data()+(h-1-y)*w*4);v->dirty=true;};
render_handler.api.on_paint=[](cef_render_handler_t*,cef_browser_t* b,cef_paint_element_type_t type,size_t dirty_count,const cef_rect_t* dirty,const void* data,int w,int h){auto* v=find_browser(b);if(!v||v->closing||type!=PET_VIEW||w!=v->width*v->render_scale||h!=v->height*v->render_scale)return;merge_paint(v->pixels,data,w,h,dirty_count,dirty,true);for(auto& damage:v->texture_damage)damage.add(w,h,dirty_count,dirty);v->dirty=true;};
life_handler.api.on_before_popup=[](cef_life_span_handler_t*,cef_browser_t*,cef_frame_t*,int,const cef_string_t*,const cef_string_t*,cef_window_open_disposition_t,int,const cef_popup_features_t*,cef_window_info_t*,cef_client_t**,cef_browser_settings_t*,cef_dictionary_value_t**,int*){return 1;};
life_handler.api.on_before_close=[](cef_life_span_handler_t*,cef_browser_t* b){auto* v=find_browser(b);if(v){v->closed=true;v->host->base.release(&v->host->base);v->host=nullptr;v->browser->base.release(&v->browser->base);v->browser=nullptr;}};
display_handler.api.on_console_message=[](cef_display_handler_t*,cef_browser_t* b,cef_log_severity_t,const cef_string_t* message,const cef_string_t*,int){auto* v=find_browser(b);std::cout<<"UI ["<<(v?v->key:"loading")<<"] "<<text(message)<<std::endl;return 1;};
request_handler.api.on_before_browse=[](cef_request_handler_t*,cef_browser_t*,cef_frame_t*,cef_request_t* r,int,int){auto* uri=r->get_url(r);auto s=text(uri);cef_string_userfree_utf16_free(uri);return int(s.rfind(origin+"/",0)!=0&&s!="about:blank");};
request_handler.api.on_render_process_terminated=[](cef_request_handler_t*,cef_browser_t* b,cef_termination_status_t,int,const cef_string_t*){auto* v=find_browser(b);if(v){std::cerr<<"Renderer crashed: "<<v->key<<"\n";close_view(*v);if(v->key=="menu")running=0;}};
request_handler.api.on_before_browse=[](cef_request_handler_t*,cef_browser_t* b,cef_frame_t* f,cef_request_t* r,int,int){auto* uri=r->get_url(r);auto s=text(uri);cef_string_userfree_utf16_free(uri);auto* v=find_browser(b);return int(!allow_plugin_navigation(s,origin,!f||f->is_main(f),v&&!v->plugin.empty()));};
request_handler.api.on_render_process_terminated=[](cef_request_handler_t*,cef_browser_t* b,cef_termination_status_t,int,const cef_string_t*){auto* v=find_browser(b);if(v){std::cerr<<"Renderer crashed: "<<v->key<<"\n";close_view(*v);if(v->key=="menu")running=0;if(v->key=="launcher")launcher_open=false;}};
client.api.get_render_handler=[](cef_client_t*){return render_handler.acquire();};client.api.get_life_span_handler=[](cef_client_t*){return life_handler.acquire();};client.api.get_display_handler=[](cef_client_t*){return display_handler.acquire();};client.api.get_request_handler=[](cef_client_t*){return request_handler.acquire();};
vr::VROverlayHandle_t button=0;auto err=overlays->CreateOverlay("framely.dock.button","Framely",&button);if(err){cef_shutdown();vr::VR_Shutdown();return 6;}auto pixels=dock_icon(false,false);overlays->SetOverlayRaw(button,pixels.data(),dock_canvas_width,dock_canvas_height,4);overlays->SetOverlayInputMethod(button,vr::VROverlayInputMethod_Mouse);vr::HmdVector2_t scale{{dock_canvas_width,dock_canvas_height}};overlays->SetOverlayMouseScale(button,&scale);vr::VROverlayIntersectionMaskPrimitive_t mask{};mask.m_nPrimitiveType=vr::OverlayIntersectionPrimitiveType_Rectangle;mask.m_Primitive.m_Rectangle={dock_icon_left,0,128,128};if(overlays->SetOverlayIntersectionMask(button,&mask,1)){std::cerr<<"Dock input mask unavailable\n";overlays->DestroyOverlay(button);cef_shutdown();vr::VR_Shutdown();return 6;}overlays->SetOverlayFlag(button,vr::VROverlayFlags_VisibleInDashboard,true);overlays->SetOverlayFlag(button,vr::VROverlayFlags_MakeOverlaysInteractiveIfVisible,true);overlays->SetOverlayFlag(button,vr::VROverlayFlags_SortWithNonSceneOverlays,false);overlays->SetOverlaySortOrder(button,0);overlays->SetOverlayFlag(button,vr::VROverlayFlags_HideLaserIntersection,false);
try{create_view("menu","Framely",initial,false,600,840);}catch(const std::exception& e){std::cerr<<e.what()<<"\n";running=0;}
std::thread poller([port]{int failures=0;while(running){try{auto data=poll_http(port);std::lock_guard<std::mutex> lock(queue_mutex);for(const auto& c:data.at("commands")){if(queue.size()<256)queue.push_back(c);}failures=0;}catch(const std::exception& e){if(++failures>=10){std::cerr<<"Agent connection lost: "<<e.what()<<"\n";running=0;}}std::this_thread::sleep_for(std::chrono::milliseconds(100));}});
DockUVState uv{};OverlayPlacement button_placement;bool icon_active=false,icon_hover=false;vr::VROverlayHandle_t last_dock=0;bool was_visible=false;vr::HmdMatrix34_t saved_anchor{},saved_frame{};float saved_size=0;DockCurveEvidence saved_evidence{};auto button_haptic_at=std::chrono::steady_clock::time_point{};auto anchored_at=std::chrono::steady_clock::time_point{};auto sampled_at=std::chrono::steady_clock::time_point{};
std::thread poller([port]{int failures=0;while(running){try{auto data=poll_http(port);notification_badge_count.store(data.value("notificationBadge",0u));launcher_primary.store(data.value("launcher",json::object()).value("primaryTrigger",false));std::lock_guard<std::mutex> lock(queue_mutex);for(const auto& c:data.at("commands")){if(queue.size()<256)queue.push_back(c);}failures=0;}catch(const std::exception& e){if(++failures>=10){std::cerr<<"Agent connection lost: "<<e.what()<<"\n";running=0;}}std::this_thread::sleep_for(std::chrono::milliseconds(100));}});
DockUVState uv{};OverlayPlacement button_placement;bool icon_active=false,icon_hover=false;unsigned icon_badge=0;vr::VROverlayHandle_t last_dock=0;bool was_visible=false;vr::HmdMatrix34_t saved_anchor{},saved_frame{};float saved_size=0;DockCurveEvidence saved_evidence{};auto button_haptic_at=std::chrono::steady_clock::time_point{};auto anchored_at=std::chrono::steady_clock::time_point{};auto sampled_at=std::chrono::steady_clock::time_point{};
while(running){auto frame_start=std::chrono::steady_clock::now();cef_do_message_loop_work();commands();vr::VREvent_t global{};while(vr_system->PollNextEvent(&global,sizeof(global))){if(global.eventType==vr::VREvent_Quit){vr_system->AcknowledgeQuit_Exiting();running=0;}keyboard_event(global);}vr::VROverlayHandle_t dock=0;vr::HmdVector2_t mouse_scale{};bool visible=!overlays->FindOverlay("valve.steam.gamepadui.bar",&dock)&&overlays->IsDashboardVisible()&&overlays->IsOverlayVisible(dock)&&!overlays->GetOverlayMouseScale(dock,&mouse_scale);
if(visible&&(!was_visible||dock!=last_dock)){uv={};anchored_at={};sampled_at={};}last_dock=dock;
// Width and aspect are only ray-solver seeds; physical size comes from intersections.
@@ -218,40 +391,62 @@ int main(int argc,char** argv){
vr::HmdMatrix34_t frame{};bool frame_ok=visible&&fresh&&!overlays->GetTransformForOverlayCoordinates(dock,vr::TrackingUniverseStanding,{{mouse_scale.v[0]*.5f,mouse_scale.v[1]*.5f}},&center)&&dock_rigid_frame(center,frame);
auto sample_now=std::chrono::steady_clock::now();
if(frame_ok&&sample_now-sampled_at>=std::chrono::milliseconds(100)){sampled_at=sample_now;anchor_ok=dock_probe_origin(center,head)&&dock_uv_anchor(overlays,dock,center,head,width,height,anchor,evidence,size,uv);}
auto now=std::chrono::steady_clock::now();if(anchor_ok){saved_anchor=anchor;saved_frame=frame;saved_size=size;saved_evidence=evidence;anchored_at=now;}else if(frame_ok&&now-anchored_at<std::chrono::milliseconds(350)){anchor=dock_follow_pose(saved_anchor,saved_frame,frame);size=saved_size;evidence=saved_evidence;anchor_ok=true;}
auto now=std::chrono::steady_clock::now();if(anchor_ok){if(evidence.radius>0)notification_curve_radius=evidence.radius;saved_anchor=anchor;saved_frame=frame;saved_size=size;saved_evidence=evidence;anchored_at=now;}else if(frame_ok&&now-anchored_at<std::chrono::milliseconds(350)){anchor=dock_follow_pose(saved_anchor,saved_frame,frame);size=saved_size;evidence=saved_evidence;anchor_ok=true;}
if(keyboard_menu.holds(now)){if(views.count("menu"))show(*views.at("menu"),menu_open);}else if(anchor_ok){// Apply the button tilt in its pose: nonzero API pre-curve pitch hid it on Frame.
auto icon_pose=anchor;float cp=std::cos(evidence.pre_curve_pitch),sp=std::sin(evidence.pre_curve_pitch);for(int r=0;r<3;r++){icon_pose.m[r][1]=anchor.m[r][1]*cp+anchor.m[r][2]*sp;icon_pose.m[r][2]=anchor.m[r][2]*cp-anchor.m[r][1]*sp;}button_placement.apply(overlays,button,icon_pose,size*5);button_placement.curve(overlays,button,size*5,evidence.radius,0);if(!overlays->IsOverlayVisible(button))overlays->ShowOverlay(button);if(views.count("menu")){MenuPlacement popup{};auto& v=*views.at("menu");vr::HmdMatrix34_t main_pose{};vr::VROverlayHandle_t main_overlay=0;vr::HmdVector2_t main_scale{};const vr::HmdMatrix34_t* main=nullptr;
for(auto&[key,view]:views)if(view->dashboard&&view->shown&&!view->closing)main_overlay=view->overlay;
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;for(auto&[key,v]:views)if(!v->dashboard&&key!="menu"&&key!="notifications")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())launcher_open=false;for(auto&[key,v]:views)if(!v->dashboard&&key!="menu"&&key!="notifications"&&key!="launcher")close_view(*v);}was_visible=visible;
// The runtime owns dashboard placement, curvature, visibility and switching.
// Never move the launcher into standing space or hide another app's overlay.
if(launcher_open)launcher_dock_interaction();
if(views.count("launcher")){
bool selected=overlays->IsActiveDashboardOverlay(views.at("launcher")->overlay);
if(launcher_open&&selected)launcher_selected=true;
if(launcher_open&&!selected&&overlays->IsDashboardVisible()&&!launcher_dock_interaction()&&(launcher_selected||now-launcher_dismiss.opened_at>std::chrono::seconds(1)))launcher_open=false;
}
// Toggle once for a matched left click; never activate on a stale release.
vr::VREvent_t event{};while(overlays->PollNextOverlayEvent(button,&event,sizeof(event))){
laser_cursor(button,event);
if(event.eventType==vr::VREvent_MouseMove||event.eventType==vr::VREvent_MouseButtonDown||event.eventType==vr::VREvent_MouseButtonUp)entry_pointer.move(event.trackedDeviceIndex,event.data.mouse.x,event.data.mouse.y);
if(event.eventType==vr::VREvent_FocusLeave)entry_pointer.leave();
if(event.eventType==vr::VREvent_MouseButtonDown||event.eventType==vr::VREvent_MouseButtonUp){
if(menu_button.event(event.eventType==vr::VREvent_MouseButtonDown,event.data.mouse.button==vr::VRMouseButton_Left,anchor_ok,now)){
menu_open=!menu_open;if(menu_open){menu_button.opened(now);if(views.count("menu"))views.at("menu")->host->set_focus(views.at("menu")->host,1);}
if(!entry_actions_ready&&menu_button.event(event.eventType==vr::VREvent_MouseButtonDown,event.data.mouse.button==vr::VRMouseButton_Left,anchor_ok,now)){
toggle_entry(launcher_primary.load());if(menu_open){menu_button.opened(now);if(views.count("menu"))views.at("menu")->host->set_focus(views.at("menu")->host,1);}
std::cout<<"Menu "<<(menu_open?"opened":"closed")<<std::endl;
}
}
}
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){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;for(auto&[other,t]:views)if(!t->dashboard&&other!="menu"&&other!="notifications"&&!keyboard_open)close_view(*t);}}
if(!anchor_ok)entry_pointer.leave();
entry_actions(button,anchor_ok);
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"&&!keyboard_open)close_view(*t);}}
while(overlays->PollNextOverlayEvent(v->overlay,&event,sizeof(event)))overlay_input(*v,event);
if(v->dirty&&!v->closing){
glXMakeContextCurrent(xdisplay,glsurface,glsurface,glcontext);
// Upload to the other texture; never redefine storage submitted this frame.
const int slot=1-v->texture_slot;const GLuint id=v->textures[slot];
auto& damage=v->texture_damage[slot];const int pixel_width=v->width*v->render_scale,pixel_height=v->height*v->render_scale;
static auto generate_mipmap=reinterpret_cast<PFNGLGENERATEMIPMAPPROC>(glXGetProcAddressARB(reinterpret_cast<const GLubyte*>("glGenerateMipmap")));
bool mipmapped=v->key=="launcher"&&generate_mipmap;
glBindTexture(GL_TEXTURE_2D,id);
glPixelStorei(GL_UNPACK_ALIGNMENT,4);glPixelStorei(GL_UNPACK_ROW_LENGTH,0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS,0);glPixelStorei(GL_UNPACK_SKIP_ROWS,0);
if(!v->texture_ready[slot]){
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,mipmapped?GL_LINEAR_MIPMAP_LINEAR:GL_LINEAR);glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA8,v->width*v->render_scale,v->height*v->render_scale,0,GL_BGRA,GL_UNSIGNED_BYTE,nullptr);
v->texture_ready[slot]=true;
damage.include(0,0,pixel_width,pixel_height);
}
if(!damage.empty()){
glPixelStorei(GL_UNPACK_ROW_LENGTH,pixel_width);
glTexSubImage2D(GL_TEXTURE_2D,0,damage.x,damage.y,damage.width,damage.height,GL_BGRA,GL_UNSIGNED_BYTE,v->pixels.data()+(size_t(damage.y)*pixel_width+damage.x)*4);
glPixelStorei(GL_UNPACK_ROW_LENGTH,0);damage.clear();
if(mipmapped)generate_mipmap(GL_TEXTURE_2D);
}
glTexSubImage2D(GL_TEXTURE_2D,0,0,0,v->width*v->render_scale,v->height*v->render_scale,GL_BGRA,GL_UNSIGNED_BYTE,v->pixels.data());
// glFlush queues the upload; glFinish makes the full image ready for sharing.
glFinish();vr::Texture_t texture{reinterpret_cast<void*>(uintptr_t(id)),vr::TextureType_OpenGL,vr::ColorSpace_Auto};
auto e=overlays->SetOverlayTexture(v->overlay,&texture);glFlush();
@@ -269,12 +464,22 @@ int main(int argc,char** argv){
auto error=overlays->SetOverlayIntersectionMask(v->overlay,&mask,1);
if(error){std::cerr<<"Notification input mask failed "<<error<<"\n";visible=false;}
}
show(*v,visible);
v->notification_content=visible;
}
}
}
if(key=="notifications"){
if(v->notification_click.active&&std::chrono::steady_clock::now()-v->notification_click.pressed>std::chrono::milliseconds(800)){
// A release outside the overlay may not arrive. Never leave CEF pressed.
cef_mouse_event_t outside{};outside.x=outside.y=-1;
v->host->send_mouse_click_event(v->host,&outside,MBT_LEFT,1,1);v->notification_click.clear();
}
if(v->notification_content&&!v->placement.valid)anchor_notification(*v);
if(v->placement.valid)v->placement.curve(overlays,v->overlay,v->placement.width,notification_curve_radius);
show(*v,v->notification_content&&v->placement.valid);
}
}
{json snapshot=json::object();for(auto&[key,v]:views){if(key=="menu"||key=="framely.manager"||key.rfind("framely.window.",0)==0)snapshot[key]=capture_view_visible(v->closing,overlays->IsOverlayVisible(v->overlay),v->dashboard,overlays->IsDashboardVisible(),overlays->IsActiveDashboardOverlay(v->overlay));}std::lock_guard<std::mutex> lock(visibility_mutex);visible_views=std::move(snapshot);}
{json snapshot=json::object();for(auto&[key,v]:views){if(key=="menu"||key=="launcher"||key=="framely.manager"||key.rfind("framely.window.",0)==0)snapshot[key]=capture_view_visible(v->closing,overlays->IsOverlayVisible(v->overlay),v->dashboard,overlays->IsDashboardVisible(),overlays->IsActiveDashboardOverlay(v->overlay));}std::lock_guard<std::mutex> lock(visibility_mutex);visible_views=std::move(snapshot);}
if(keyboard_close_pending){
// A non-minimal runtime keyboard may buffer text until Done. Drain overlay
// character events first so the global Done event cannot duplicate input.
@@ -282,7 +487,7 @@ int main(int argc,char** argv){
close_keyboard(false);
}
for(auto i=views.begin();i!=views.end();){auto& v=*i->second;if(v.closed){overlays->ClearOverlayTexture(v.overlay);overlays->DestroyOverlay(v.overlay);if(v.thumbnail)overlays->DestroyOverlay(v.thumbnail);glDeleteTextures(2,v.textures);i=views.erase(i);}else ++i;}
bool hovered=anchor_ok&&overlays->IsHoverTargetOverlay(button);if(hovered&&!icon_hover)hover_haptic(button,button_haptic_at);if(icon_active!=menu_open||icon_hover!=hovered){icon_active=menu_open;pixels=dock_icon(hovered,menu_open);overlays->SetOverlayRaw(button,pixels.data(),dock_canvas_width,dock_canvas_height,4);}icon_hover=hovered;
bool hovered=anchor_ok&&overlays->IsHoverTargetOverlay(button);if(hovered&&!icon_hover)hover_haptic(button,button_haptic_at);const auto badge=notification_badge_count.load();if(icon_active!=(menu_open||launcher_open)||icon_hover!=hovered||icon_badge!=badge){icon_badge=badge;icon_active=menu_open||launcher_open;pixels=dock_icon(hovered,icon_active);overlays->SetOverlayRaw(button,pixels.data(),dock_canvas_width,dock_canvas_height,4);}icon_hover=hovered;
auto sync=overlays->WaitFrameSync(8);
// A timeout already waited: never append another sleep to it. Bound retries
// only for immediate API failures, so a broken sync call cannot busy-spin.
+47
View File
@@ -0,0 +1,47 @@
{
"action_sets": [
{
"name": "/actions/entry",
"usage": "leftright"
}
],
"actions": [
{
"name": "/actions/entry/in/primary",
"type": "boolean"
},
{
"name": "/actions/entry/in/upper",
"type": "boolean"
},
{
"name": "/actions/entry/in/aim",
"type": "pose"
},
{
"name": "/actions/entry/in/close",
"type": "boolean"
},
{
"name": "/actions/entry/in/navigate",
"type": "vector2"
}
],
"default_bindings": [
{
"controller_type": "frame_controller",
"binding_url": "frame-controller.json"
}
],
"localization": [
{
"language_tag": "en_US",
"/actions/entry": "Framely launcher",
"/actions/entry/in/primary": "Primary trigger",
"/actions/entry/in/upper": "Upper trigger",
"/actions/entry/in/aim": "Pointer",
"/actions/entry/in/close": "Close launcher (B)",
"/actions/entry/in/navigate": "Launcher navigation"
}
]
}
+99
View File
@@ -0,0 +1,99 @@
{
"controller_type": "frame_controller",
"name": "Framely entry controls",
"bindings": {
"/actions/entry": {
"poses": [
{
"path": "/user/hand/left/pose/tip",
"output": "/actions/entry/in/aim"
},
{
"path": "/user/hand/right/pose/tip",
"output": "/actions/entry/in/aim"
}
],
"sources": [
{
"path": "/user/hand/left/input/trigger",
"mode": "button",
"inputs": {
"click": {
"output": "/actions/entry/in/primary"
}
},
"parameters": {
"haptic_amplitude": "0",
"click_activate_threshold": "0.5",
"click_deactivate_threshold": "0.45"
}
},
{
"path": "/user/hand/left/input/bumper",
"mode": "button",
"inputs": {
"click": {
"output": "/actions/entry/in/upper"
}
},
"parameters": {
"haptic_amplitude": "0"
}
},
{
"path": "/user/hand/right/input/trigger",
"mode": "button",
"inputs": {
"click": {
"output": "/actions/entry/in/primary"
}
},
"parameters": {
"haptic_amplitude": "0",
"click_activate_threshold": "0.5",
"click_deactivate_threshold": "0.45"
}
},
{
"path": "/user/hand/right/input/bumper",
"mode": "button",
"inputs": {
"click": {
"output": "/actions/entry/in/upper"
}
},
"parameters": {
"haptic_amplitude": "0"
}
},
{
"path": "/user/hand/right/input/b",
"mode": "button",
"inputs": {
"click": {
"output": "/actions/entry/in/close"
}
}
},
{
"path": "/user/hand/left/input/thumbstick",
"mode": "joystick",
"inputs": {
"position": {
"output": "/actions/entry/in/navigate"
}
}
},
{
"path": "/user/hand/right/input/thumbstick",
"mode": "joystick",
"inputs": {
"position": {
"output": "/actions/entry/in/navigate"
}
}
}
]
}
}
}
+97
View File
@@ -0,0 +1,97 @@
#pragma once
#include <chrono>
#include <algorithm>
#include <cmath>
#include "openvr.h"
struct EntryTrigger {
bool held=false,ready=false;
std::chrono::steady_clock::time_point last{};
bool update(bool active,bool down,bool hit,std::chrono::steady_clock::time_point now){
if(!active){held=false;ready=false;return false;}
if(!ready){held=down;ready=true;return false;}
bool rising=down&&!held;held=down;
if(!rising||!hit||now-last<std::chrono::milliseconds(180))return false;
last=now;return true;
}
};
// Steam's laser supplies the actual tip hit and originating controller. Keep
// its point while the trigger locks the pointer, until an explicit focus leave.
struct EntryPointer {
unsigned device=~0u;bool inside=false;
void move(unsigned source,float x,float y){device=source;inside=x>=256&&x<=384&&y>=0&&y<=128;}
void leave(){device=~0u;inside=false;}
bool hit(unsigned source)const{return inside&&source!=~0u&&source==device;}
};
inline vr::HmdMatrix34_t entry_tip_pose(const vr::HmdMatrix34_t& tracked,const vr::HmdMatrix34_t& tip){
vr::HmdMatrix34_t out{};
for(int r=0;r<3;r++)for(int c=0;c<4;c++){
for(int k=0;k<3;k++)out.m[r][c]+=tracked.m[r][k]*tip.m[k][c];
if(c==3)out.m[r][c]+=tracked.m[r][3];
}
return out;
}
inline float entry_rotation_angle(const vr::HmdMatrix34_t& from,const vr::HmdMatrix34_t& to){
float trace=0;for(int r=0;r<3;r++)for(int c=0;c<3;c++)trace+=from.m[r][c]*to.m[r][c];
return std::acos(std::clamp((trace-1.f)*.5f,-1.f,1.f));
}
inline bool entry_trigger_pull(const vr::RenderModel_ComponentState_t& rest,const vr::RenderModel_ComponentState_t& full,const vr::RenderModel_ComponentState_t& current,float& pull){
float travel=entry_rotation_angle(rest.mTrackingToComponentRenderModel,full.mTrackingToComponentRenderModel);
if(!std::isfinite(travel)||travel<.001f)return false;
pull=std::clamp(entry_rotation_angle(rest.mTrackingToComponentRenderModel,current.mTrackingToComponentRenderModel)/travel,0.f,1.f);return std::isfinite(pull);
}
struct EntryAnalogTrigger {
bool held=false;
bool update(float pull){held=std::isfinite(pull)&&pull>=(held?.45f:.5f);return held;}
};
// The press that opens a modal surface must not dismiss it as an outside click.
struct LauncherDismissGuard {
std::chrono::steady_clock::time_point opened_at{};bool released=false;
void opened(std::chrono::steady_clock::time_point now){opened_at=now;released=false;}
void observe(bool held){if(!held)released=true;}
bool allows(std::chrono::steady_clock::time_point now,bool held,float event_age=0){
observe(held);
return released&&now-opened_at>=std::chrono::milliseconds(300)&&
event_age>=0&&std::chrono::duration<float>(now-opened_at).count()>=event_age;
}
};
// One axis per gesture, with a dead zone and neutral re-arm. A diagonal never
// flips a category and a page together, even if its dominant axis changes.
struct LauncherStick {
bool ready=false,latched=false;
int update(float x,float y,bool active){
if(!active||!std::isfinite(x)||!std::isfinite(y)){ready=false;latched=false;return 0;}
float strength=std::max(std::abs(x),std::abs(y));
if(strength<.3f){ready=true;latched=false;return 0;}
if(!ready||latched||strength<.65f)return 0;
latched=true;
return std::abs(x)>=std::abs(y)?(x>0?1:-1):(y>0?2:-2);
}
};
inline void launcher_rotation_vector(const vr::HmdMatrix34_t& rest,const vr::HmdMatrix34_t& value,float out[3]){
float m[3][3]{};for(int r=0;r<3;r++)for(int c=0;c<3;c++)for(int k=0;k<3;k++)m[r][c]+=rest.m[k][r]*value.m[k][c];
out[0]=m[2][1]-m[1][2];out[1]=m[0][2]-m[2][0];out[2]=m[1][0]-m[0][1];
}
inline bool launcher_stick_axes(const vr::RenderModel_ComponentState_t& rest,const vr::RenderModel_ComponentState_t& full_x,const vr::RenderModel_ComponentState_t& full_y,const vr::RenderModel_ComponentState_t& current,float& x,float& y){
float a[3],b[3],v[3];launcher_rotation_vector(rest.mTrackingToComponentRenderModel,full_x.mTrackingToComponentRenderModel,a);launcher_rotation_vector(rest.mTrackingToComponentRenderModel,full_y.mTrackingToComponentRenderModel,b);launcher_rotation_vector(rest.mTrackingToComponentRenderModel,current.mTrackingToComponentRenderModel,v);
float aa=0,ab=0,bb=0,av=0,bv=0;for(int i=0;i<3;i++){aa+=a[i]*a[i];ab+=a[i]*b[i];bb+=b[i]*b[i];av+=a[i]*v[i];bv+=b[i]*v[i];}
float det=aa*bb-ab*ab;if(det<.00001f)return false;
x=std::clamp((av*bb-bv*ab)/det,-1.f,1.f);y=std::clamp((bv*aa-av*ab)/det,-1.f,1.f);return std::isfinite(x)&&std::isfinite(y);
}
// Runtime dashboard controls are outside the app surface. Preserve their drag
// gesture and delayed modal-cancel events without swallowing later empty clicks.
struct LauncherDockGuard {
std::chrono::steady_clock::time_point until{};bool dragging=false;
void observe(bool hovered,bool held,std::chrono::steady_clock::time_point now){
if(hovered&&held)dragging=true;
if(hovered||dragging)until=now+std::chrono::milliseconds(250);
if(!held)dragging=false;
}
bool holds(std::chrono::steady_clock::time_point now)const{return dragging||now<until;}
void clear(){until={};dragging=false;}
};
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include <chrono>
#include <cmath>
// Keep the initial hit during ordinary laser jitter, including a long press.
// A deliberate move or an abandoned hold releases the lock.
struct LauncherPointer {
using Time=std::chrono::steady_clock::time_point;
bool active=false,cancelled=false;int x=0,y=0;Time pressed{};
void begin(int px,int py,Time now){active=true;cancelled=false;x=px;y=py;pressed=now;}
bool holding(Time now)const{return active&&!cancelled&&now-pressed<=std::chrono::milliseconds(2500);}
bool constrain(int& px,int& py,Time now){
if(!active)return false;
if(!holding(now)||std::hypot(float(px-x),float(py-y))>36.f)cancelled=true;
if(cancelled)return false;
px=x;py=y;return true;
}
void clear(){active=false;cancelled=false;}
};
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include <algorithm>
#include <cstdint>
#include <string>
#include <vector>
// Rasterize the unread count directly onto the Dock's 128px icon texture.
// The zero state leaves the original icon byte-for-byte unchanged.
inline void notification_badge(std::vector<uint8_t>& rgba, unsigned count) {
if (!count || rgba.size()!=128*128*4) return;
const std::string label=count>99?"99+":std::to_string(count);
const int text_width=int(label.size())*12-3,width=text_width+14,left=124-width,top=4,height=29;
for(int y=top;y<top+height;y++)for(int x=left;x<124;x++){
const int dx=std::max({left+6-x,0,x-117}),dy=std::max({top+6-y,0,y-(top+height-7)});
if(dx*dx+dy*dy>36)continue;
auto i=(y*128+x)*4;rgba[i]=147;rgba[i+1]=197;rgba[i+2]=237;rgba[i+3]=255;
}
// Compact 3x5 numerals retain a readable count at the Frame Dock's display scale.
constexpr uint16_t digits[]={0b111101101101111,0b010110010010111,0b111001111100111,0b111001111001111,0b101101111001001,0b111100111001111,0b111100111101111,0b111001001001001,0b111101111101111,0b111101111001111};
for(size_t n=0;n<label.size();n++){
const uint16_t bits=label[n]=='+'?0b000010111010000:digits[label[n]-'0'];
for(int y=0;y<5;y++)for(int x=0;x<3;x++)if(bits&(1u<<(14-y*3-x)))
for(int sy=0;sy<3;sy++)for(int sx=0;sx<3;sx++){
auto i=((top+7+y*3+sy)*128+left+7+int(n)*12+x*3+sx)*4;
rgba[i]=23;rgba[i+1]=25;rgba[i+2]=28;rgba[i+3]=255;
}
}
}
+47 -2
View File
@@ -2,13 +2,41 @@
#include <cstdint>
#include <cstddef>
#include <vector>
#include <chrono>
#include "geometry_math.h"
struct NotificationPlacement {
vr::HmdMatrix34_t transform{};
float width=.32f,radius=0;
};
// Keep the compact toast at the upper right, but turn its front toward the eye.
// Copying the headset rotation leaves a side-offset overlay facing past the user.
inline bool notification_placement(const vr::HmdMatrix34_t& headset,float radius,NotificationPlacement& out){
vr::HmdMatrix34_t head{};
if(!dock_rigid_frame(headset,head)||!std::isfinite(radius)||radius<=0)return false;
vr::HmdVector3_t normal{},head_up{{head.m[0][1],head.m[1][1],head.m[2][1]}};
for(int r=0;r<3;r++){
out.transform.m[r][3]=head.m[r][3]+head.m[r][0]*.24f+head.m[r][1]*.12f-head.m[r][2]*1.f;
normal.v[r]=head.m[r][3]-out.transform.m[r][3];
}
if(!normalize_dock_vector(normal))return false;
auto right=cross_dock_vector(head_up,normal);
if(!normalize_dock_vector(right))return false;
auto up=cross_dock_vector(normal,right);
for(int r=0;r<3;r++){
out.transform.m[r][0]=right.v[r];out.transform.m[r][1]=up.v[r];out.transform.m[r][2]=normal.v[r];
}
out.radius=radius;return true;
}
struct NotificationBounds {
float x=0,y=0,width=0,height=0;
bool visible() const {return width>0&&height>0;}
};
// The submitted BGRA buffer is flipped in on_paint to OpenVR's bottom-left origin.
// BGRA rows are bottom-up after on_paint. Intersection rectangles use top-left
// coordinates, so the alpha bounds must be flipped back before submitting the mask.
inline NotificationBounds notification_bounds(const std::vector<uint8_t>& pixels,int width,int height,int scale){
if(width<=0||height<=0||scale<=0||pixels.size()!=size_t(width)*height*4)return {};
int left=width,low=height,right=-1,high=-1;
@@ -17,5 +45,22 @@ inline NotificationBounds notification_bounds(const std::vector<uint8_t>& pixels
if(x<left)left=x;if(x>right)right=x;if(y<low)low=y;if(y>high)high=y;
}
if(right<left)return {};
return {float(left)/scale,float(low)/scale,float(right-left+1)/scale,float(high-low+1)/scale};
return {float(left)/scale,float(height-1-high)/scale,float(right-left+1)/scale,float(high-low+1)/scale};
}
// Preserve the intended button during a brief click with normal tracking jitter.
// Deliberate movement and long holds cancel stabilization.
struct NotificationClick {
using Time=std::chrono::steady_clock::time_point;
bool active=false,cancelled=false;int x=0,y=0;Time pressed{};
void begin(int px,int py,Time now){active=true;cancelled=false;x=px;y=py;pressed=now;}
bool hold(int px,int py,Time now){
if(!active)return false;
if(now-pressed>std::chrono::milliseconds(800)||std::hypot(float(px-x),float(py-y))>18.f)cancelled=true;
return !cancelled;
}
bool release(int& px,int& py,Time now){
bool stable=hold(px,py,now);if(stable){px=x;py=y;}active=false;return stable;
}
void clear(){active=false;cancelled=false;}
};
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include <algorithm>
#include <cstdint>
#include <vector>
// Each alternating GPU texture retains its own pending damage until uploaded.
// Coordinates match the vertically flipped CPU buffer, not CEF's top-left view.
struct PaintDamage {
int x=0,y=0,width=0,height=0;
bool empty() const{return width<=0||height<=0;}
void clear(){*this={};}
void include(int left,int top,int right,int bottom){
if(right<=left||bottom<=top)return;
if(!empty()){right=std::max(right,x+width);bottom=std::max(bottom,y+height);left=std::min(left,x);top=std::min(top,y);}
x=left;y=top;width=right-left;height=bottom-top;
}
template<class Rect> void add(int w,int h,size_t count,const Rect* rects){
if(!count||!rects){include(0,0,w,h);return;}
for(size_t i=0;i<count;i++){
const auto& r=rects[i];const int left=std::clamp(r.x,0,w),top=std::clamp(r.y,0,h);
const int right=int(std::clamp<long long>(static_cast<long long>(r.x)+r.width,0,w)),bottom=int(std::clamp<long long>(static_cast<long long>(r.y)+r.height,0,h));
if(right>left&&bottom>top)include(left,h-bottom,right,h-top);
}
}
};
// CEF dirty rectangles use physical pixels. Preserve unchanged pixels between
// paints, and flip only the copied rows for OpenVR's bottom-left texture origin.
template<class Rect> inline void merge_paint(std::vector<uint8_t>& pixels,const void* buffer,int width,int height,size_t count,const Rect* dirty,bool flip=false){
const size_t bytes=size_t(width)*height*4;const auto* source=static_cast<const uint8_t*>(buffer);
auto copy=[&](int left,int top,int right,int bottom){for(int y=top;y<bottom;y++)std::copy_n(source+(size_t(y)*width+left)*4,size_t(right-left)*4,pixels.data()+(size_t(flip?height-1-y:y)*width+left)*4);};
if(pixels.size()!=bytes||!count||!dirty){pixels.resize(bytes);copy(0,0,width,height);return;}
for(size_t i=0;i<count;i++){const auto& r=dirty[i];int left=std::clamp(r.x,0,width),top=std::clamp(r.y,0,height),right=int(std::clamp<long long>(static_cast<long long>(r.x)+r.width,0,width)),bottom=int(std::clamp<long long>(static_cast<long long>(r.y)+r.height,0,height));if(right>left&&bottom>top)copy(left,top,right,bottom);}
}
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#include <string>
// Other localhost ports are only for embedded pages in plugin windows.
// The main frame remains on the Framely origin.
inline bool allow_plugin_navigation(const std::string& url, const std::string& origin,
bool main_frame, bool plugin_window) {
if (url == "about:blank" || url.rfind(origin + "/", 0) == 0) return true;
if (main_frame || !plugin_window) return false;
const std::string prefix = "http://localhost:";
if (url.rfind(prefix, 0) != 0) return false;
auto end = url.find('/', prefix.size());
if (end == std::string::npos || end == prefix.size()) return false;
unsigned port = 0;
for (auto i = prefix.size(); i < end; ++i) {
if (url[i] < '0' || url[i] > '9') return false;
port = port * 10 + unsigned(url[i] - '0');
if (port > 65535) return false;
}
return port > 0;
}
+3
View File
@@ -0,0 +1,3 @@
#pragma once
// Cap CEF painting independently of headset refresh to limit pixel readback.
inline constexpr int browser_frame_rate(float = 0){return 60;}
+27
View File
@@ -12,6 +12,7 @@
"examples/showcase"
],
"dependencies": {
"@tabler/icons-react": "3.48.0",
"react": "19.2.0",
"react-dom": "19.2.0"
},
@@ -713,6 +714,32 @@
"node": ">= 10"
}
},
"node_modules/@tabler/icons": {
"version": "3.48.0",
"resolved": "https://registry.npmjs.org/@tabler/icons/-/icons-3.48.0.tgz",
"integrity": "sha512-lQk06gVHNVBnJp0UOgtth54mcZBJM7rdYKsAxKOProj1bbSAx+/xiuOWfHlyvgdL3M+Y+I0HINrjHa3ygp8eXQ==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/codecalm"
}
},
"node_modules/@tabler/icons-react": {
"version": "3.48.0",
"resolved": "https://registry.npmjs.org/@tabler/icons-react/-/icons-react-3.48.0.tgz",
"integrity": "sha512-OCeAlpaWHEMV+EsgdVeGQ3YuKfmfnThZhc++CaZ/ujYzi5+/DONDQlX4OGvH1ikYhIfmc0grI4otJgHy7QAvng==",
"license": "MIT",
"dependencies": {
"@tabler/icons": "3.48.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/codecalm"
},
"peerDependencies": {
"react": ">= 16"
}
},
"node_modules/@types/react": {
"version": "19.2.0",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.0.tgz",
+1
View File
@@ -15,6 +15,7 @@
"plugin:init": "node tools/plugin-dev.mjs init"
},
"dependencies": {
"@tabler/icons-react": "3.48.0",
"react": "19.2.0",
"react-dom": "19.2.0"
},
+18
View File
@@ -146,6 +146,24 @@ rollback_on_failure() {
}
trap rollback_on_failure ERR
systemctl stop framely-session.service framely.service 2>/dev/null || true
# Clear the uninstall guard retained by older releases only for a clean reinstall.
# Existing installations, repairs and incomplete plugin cleanup retain safe mode.
if ! $repair && [[ -z $old && -f $root/state.json ]]; then
python3 - "$root/state.json" <<'PY_REINSTALL'
import json, os, pathlib, sys
path = pathlib.Path(sys.argv[1])
state = json.loads(path.read_text())
if state.get('safeMode') is True and state.get('plugins') == {}:
state['safeMode'] = False
temporary = path.with_name('state.json.reinstall')
with temporary.open('w') as output:
os.chmod(temporary, 0o600)
json.dump(state, output, ensure_ascii=False)
output.flush()
os.fsync(output.fileno())
os.replace(temporary, path)
PY_REINSTALL
fi
ln -s "releases/$version" "$root/current.new"
mv -Tf "$root/current.new" "$root/current"
cat > /etc/systemd/system/framely.service <<EOF
+6 -4
View File
@@ -1,20 +1,22 @@
export * from './launcher';
import {launchContext} from './launcher';
export * from './visibility';
import {createVisibilityApi, type UiVisibility} from './visibility';
export * from './lifecycle';
import {installScrollbars} from './scrollbars';
import React from 'react';
import {createRoot} from 'react-dom/client';
export interface NotificationAction {id:string;label:string;icon:string}
export interface Notification {id:string;title:string;body:string;image?:string;actions?:NotificationAction[];durationMs?:number}
export interface NotificationAction {id:string;label:string;icon?:string;closeOnClick?:boolean;removeFromInboxOnClick?:boolean}
export interface Notification {id:string;title:string;body:string;image?:string;actions?:NotificationAction[];durationMs?:number;inbox?:boolean}
type Bridge={request:(op:string,p?:unknown)=>Promise<any>;subscribe:(f:(e:unknown)=>void)=>()=>void};
function bridge():Bridge{const b=(window as any).__framelyBridge;if(!b)throw new Error('This page requires the Framely plugin host');return b;}
export const framely={
ui:createVisibilityApi(bridge),
ui:{launchContext,...createVisibilityApi(bridge),close:():Promise<unknown>=>bridge().request('ui.close')},
language:{get:():Promise<{preference:string;language:string}>=>bridge().request('language.get')},
call:<T=unknown>(method:string,params:unknown={}):Promise<T>=>bridge().request('call',{method,params}),
windows:{open:(window:string)=>bridge().request('window.open',{window}),close:(window:string)=>bridge().request('window.close',{window})},
dependencies:():Promise<DependencyStatus[]>=>bridge().request('dependencies'),
notifications:{send:(notification:Notification)=>bridge().request('notification.send',{notification}),remove:(id:string)=>bridge().request('notification.remove',{id})},
notifications:{send:(notification:Notification)=>bridge().request('notification.send',{notification}),remove:(id:string)=>bridge().request('notification.remove',{id}),dismiss:(id:string)=>bridge().request('notification.dismiss',{id})},
onEvent:(callback:(event:unknown)=>void)=>bridge().subscribe(callback),
};
export function registerPlugin(pages:{QuickPage:React.ComponentType;WindowPage?:React.ComponentType;windows?:Record<string,React.ComponentType>}){installScrollbars();const key=location.pathname.split('/').pop();const Page=key==='quick'?pages.QuickPage:pages.windows?.[key??'']??pages.WindowPage??pages.QuickPage;const style=document.createElement('style');style.textContent='*{box-sizing:border-box}body{margin:0;padding:20px;background:#101820;color:#edf2fa;font:20px system-ui}button,input,textarea{font:inherit;color:inherit;border:1px solid #52627a;border-radius:6px;padding:12px;background:#24333e;margin:6px 6px 6px 0;min-height:48px}button{cursor:pointer}button:disabled{opacity:.5}input,textarea{width:100%}p{line-height:1.6}small{color:#acb9cf}';document.head.append(style);createRoot(document.getElementById('root')!).render(<Boundary><Page/></Boundary>);console.log('FRAMELY_PLUGIN_READY');}
+9
View File
@@ -0,0 +1,9 @@
export interface LaunchContext {source:'launcher'|'quickPanel'|'manager';trigger:'shortPress'|'menuAction';actionId?:string}
type Bridge={request:(op:string,p?:unknown)=>Promise<any>;subscribe:(f:(e:any)=>void)=>()=>void};
function bridge():Bridge{const b=(window as any).__framelyBridge;if(!b)throw new Error('This script requires the Framely plugin host');return b;}
export const launchContext={get:():Promise<LaunchContext>=>bridge().request('ui.launchContext'),onChanged:(callback:(context:LaunchContext)=>void)=>bridge().subscribe(e=>{if(e.type==='ui.launch')callback(e.data);})};
/** Register callbacks in a separate bundle named by a frontend launcher action. */
export function registerLauncherActions(actions:Record<string,(context:LaunchContext)=>unknown|Promise<unknown>>){
let busy=false;const off=bridge().subscribe(async e=>{if(e.type!=='launcher.action'||busy)return;busy=true;try{const context=e.data as LaunchContext;const action=actions[context.actionId??''];if(!action)throw new Error('Launcher action handler not registered');await action(context);await bridge().request('launcher.done');}catch(error){await bridge().request('launcher.done',{error:String(error)});}finally{busy=false;}});
void bridge().request('launcher.ready').catch(console.error);window.addEventListener('pagehide',off,{once:true});return off;
}
+476
View File
@@ -0,0 +1,476 @@
//! User-session applications: XDG desktop entries and installed Lepton packages.
use anyhow::{ensure, Context, Result};
use serde::Serialize;
use std::{
collections::{BTreeMap, BTreeSet},
fs,
path::{Path, PathBuf},
process::Stdio,
};
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct App {
pub id: String,
pub name: String,
pub kind: &'static str,
pub icon: Option<String>,
#[serde(skip)]
target: Target,
}
#[derive(Clone, Debug)]
enum Target {
Desktop(PathBuf),
Lepton {
runner: PathBuf,
context: String,
package: String,
},
}
fn entries(input: &str) -> BTreeMap<String, String> {
let mut active = false;
let mut out = BTreeMap::new();
for line in input.lines() {
let line = line.trim();
if line.starts_with('[') {
active = line == "[Desktop Entry]";
continue;
}
if active && !line.starts_with('#') {
if let Some((k, v)) = line.split_once('=') {
out.insert(k.trim().into(), v.trim().into());
}
}
}
out
}
fn data_home(home: &Path) -> PathBuf {
std::env::var_os("XDG_DATA_HOME")
.map(PathBuf::from)
.filter(|p| p.is_absolute())
.unwrap_or_else(|| home.join(".local/share"))
}
fn data_dirs(home: &Path) -> Vec<PathBuf> {
let mut dirs = vec![data_home(home)];
dirs.extend(
std::env::var("XDG_DATA_DIRS")
.unwrap_or_else(|_| "/usr/local/share:/usr/share".into())
.split(':')
.map(PathBuf::from)
.filter(|p| p.is_absolute()),
);
for p in [
home.join(".local/share/flatpak/exports/share"),
PathBuf::from("/var/lib/flatpak/exports/share"),
] {
if !dirs.contains(&p) {
dirs.push(p);
}
}
dirs
}
fn icon_file(path: &Path) -> Option<String> {
let bytes = fs::read(path).ok()?;
if bytes.len() > 1024 * 1024 {
return None;
}
let mime = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
"image/png"
} else if bytes.starts_with(&[0xff, 0xd8, 0xff]) {
"image/jpeg"
} else if path.extension().is_some_and(|e| e == "svg")
&& std::str::from_utf8(&bytes).ok()?.contains("<svg")
{
"image/svg+xml"
} else {
return None;
};
use base64::Engine;
Some(format!(
"data:{mime};base64,{}",
base64::engine::general_purpose::STANDARD.encode(bytes)
))
}
fn icon(home: &Path, name: &str, dirs: &[PathBuf]) -> Option<String> {
let path = Path::new(name);
if path.is_absolute() {
return icon_file(path);
}
if name.contains('/') || name.is_empty() {
return None;
}
for base in std::iter::once(home.join(".icons")).chain(dirs.iter().map(|d| d.join("icons"))) {
for theme in ["hicolor", "breeze", "breeze-dark", "Adwaita"] {
for size in ["256x256", "128x128", "64x64", "48x48", "scalable", "32x32"] {
for ext in ["png", "svg"] {
if let Some(icon) = icon_file(
&base
.join(theme)
.join(size)
.join("apps")
.join(format!("{name}.{ext}")),
) {
return Some(icon);
}
}
}
}
}
dirs.iter().find_map(|d| {
["png", "svg", "xpm"]
.iter()
.find_map(|ext| icon_file(&d.join("pixmaps").join(format!("{name}.{ext}"))))
})
}
fn files(base: &Path, dir: &Path, depth: usize, out: &mut Vec<(String, PathBuf)>) {
if depth > 8 {
return;
}
if let Ok(entries) = fs::read_dir(dir) {
for entry in entries.flatten() {
let p = entry.path();
if entry.file_type().is_ok_and(|t| t.is_dir()) {
files(base, &p, depth + 1, out);
} else if p.extension().is_some_and(|e| e == "desktop") {
if let Ok(relative) = p.strip_prefix(base) {
out.push((relative.to_string_lossy().replace('/', "-"), p));
}
}
}
}
}
fn desktop_apps(home: &Path, dirs: &[PathBuf], steam: &BTreeSet<u32>) -> Vec<App> {
let mut seen = BTreeSet::new();
let mut apps = Vec::new();
let desktops = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default();
for dir in dirs {
let base = dir.join("applications");
let mut candidates = Vec::new();
files(&base, &base, 0, &mut candidates);
candidates.sort();
for (id, path) in candidates {
if !seen.insert(id.clone()) {
continue;
}
let Ok(content) = fs::read_to_string(&path) else {
continue;
};
if content.len() > 128 * 1024 {
continue;
}
let v = entries(&content);
let get = |k: &str| v.get(k).map(String::as_str).unwrap_or("");
if get("Type") != "Application"
|| get("Hidden") == "true"
|| get("NoDisplay") == "true"
|| get("Exec").is_empty()
{
continue;
}
let matches = |list: &str| {
list.split(';')
.any(|item| !item.is_empty() && desktops.split(':').any(|d| d == item))
};
if !get("OnlyShowIn").is_empty() && !matches(get("OnlyShowIn"))
|| matches(get("NotShowIn"))
{
continue;
}
if !get("TryExec").is_empty() {
let t = Path::new(get("TryExec"));
let exists = if t.is_absolute() {
t.is_file()
} else {
std::env::var_os("PATH").is_some_and(|paths| {
std::env::split_paths(&paths).any(|d| d.join(t).is_file())
})
};
if !exists {
continue;
}
}
// Steam already owns its game shortcuts and helper runtimes.
if get("Exec").split_whitespace().any(|word| {
word.trim_matches('"')
.strip_prefix("steam://rungameid/")
.and_then(|s| s.parse::<u32>().ok())
.is_some_and(|id| steam.contains(&id))
}) || id == "valve-steamvr.desktop"
|| id == "Lepton Development.desktop"
{
continue;
}
let locale = std::env::var("LC_MESSAGES")
.or_else(|_| std::env::var("LANG"))
.unwrap_or_default();
let locale = locale.split('.').next().unwrap_or("");
let language = locale.split('_').next().unwrap_or("");
let name = v
.get(&format!("Name[{locale}]"))
.or_else(|| v.get(&format!("Name[{language}]")))
.or_else(|| v.get("Name"))
.filter(|n| !n.is_empty());
let Some(name) = name else {
continue;
};
apps.push(App {
id,
name: name.clone(),
kind: "desktop",
icon: icon(home, get("Icon"), dirs),
target: Target::Desktop(path),
});
}
}
apps
}
fn attr<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
let rest = tag.split_once(&format!("{name}=\""))?.1;
Some(rest.split_once('"')?.0)
}
fn safe_component(s: &str) -> bool {
!s.is_empty()
&& !s.starts_with('-')
&& s.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
}
fn lepton_apps(home: &Path) -> Vec<App> {
let runner = [
home.join(".local/share/Steam/steamapps/common/Lepton/lepton"),
home.join(".steam/steam/steamapps/common/Lepton/lepton"),
]
.into_iter()
.find(|p| p.is_file());
let Some(runner) = runner else {
return Vec::new();
};
let mut apps = Vec::new();
let root = data_home(home).join("lepton/contexts");
let Ok(contexts) = fs::read_dir(root) else {
return apps;
};
for context in contexts.flatten() {
let name = context.file_name().to_string_lossy().into_owned();
if !safe_component(&name) || name.starts_with("steamlaunch-") {
continue;
}
let data = context.path().join("baked/data_overlay");
let Ok(xml) = fs::read_to_string(data.join("system/packages.xml")) else {
continue;
};
if xml.len() > 8 * 1024 * 1024 {
continue;
}
for tag in xml.split('<').filter(|t| t.starts_with("package ")) {
let Some(package) = attr(tag, "name").filter(|s| safe_component(s)) else {
continue;
};
let Some(code) = attr(tag, "codePath").and_then(|s| s.strip_prefix("/data/")) else {
continue;
};
// Android system packages are not launcher apps. A removed package's stale
// metadata is ignored; validate that its installed APK is still present.
let path = data.join(code);
if code.split('/').any(|s| s == "..") || !path.join("base.apk").is_file() {
continue;
}
let icon = icon_file(
&data
.join("system_ce/0/shortcut_service/bitmaps")
.join(format!("{package}.png")),
);
apps.push(App {
id: format!("{name}/{package}"),
name: package.rsplit('.').next().unwrap_or(package).into(),
kind: "lepton",
icon,
target: Target::Lepton {
runner: runner.clone(),
context: name.clone(),
package: package.into(),
},
});
}
}
apps
}
pub fn discover(home: &Path) -> Vec<App> {
let ids = crate::steam::discover(home)
.into_iter()
.map(|a| a.id)
.collect();
let mut apps = desktop_apps(home, &data_dirs(home), &ids);
apps.extend(lepton_apps(home));
apps.sort_by(|a, b| a.name.cmp(&b.name));
apps
}
pub fn launch(home: &Path, id: &str) -> Result<()> {
let app = discover(home)
.into_iter()
.find(|a| format!("{}:{}", a.kind, a.id) == id)
.context("Application is no longer installed")?;
launch_target(app.target)
}
fn launch_target(target: Target) -> Result<()> {
match target {
Target::Desktop(path) => {
let output = crate::process::tool("gio")
.arg("launch")
.arg(path)
.stdin(Stdio::null())
.output()
.context("Cannot launch desktop application")?;
ensure!(
output.status.success(),
"Desktop launch failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
Target::Lepton {
runner,
context,
package,
} => {
// Use the same session-owned context and Android launcher intent; never
// reinstall the APK or accept an arbitrary shell command from the UI.
let running = crate::process::tool("podman")
.args([
"inspect",
"--format",
"{{.State.Running}}",
&format!("lepton-{context}"),
])
.stdin(Stdio::null())
.output()
.is_ok_and(|o| {
o.status.success() && String::from_utf8_lossy(&o.stdout).trim() == "true"
});
let child = if running {
None
} else {
Some(
std::process::Command::new(&runner)
.args(["start", &context])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.context("Cannot start Lepton context")?,
)
};
let start = std::time::Instant::now();
let mut ready = false;
while start.elapsed() < std::time::Duration::from_secs(35) {
let output = crate::process::tool("podman")
.args([
"exec",
&format!("lepton-{context}"),
"monkey",
"-p",
&package,
"-c",
"android.intent.category.LAUNCHER",
"1",
])
.stdin(Stdio::null())
.output();
if output.is_ok_and(|o| o.status.success()) {
ready = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(500));
}
if let Some(mut child) = child {
std::thread::spawn(move || {
let _ = child.wait();
});
}
ensure!(
ready,
"Lepton application did not become ready; retry after the context starts"
);
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn xdg_priority_hidden_overrides_and_steam_duplicates() {
let dir = tempfile::tempdir().unwrap();
let a = dir.path().join("first");
let b = dir.path().join("second");
for p in [&a, &b] {
fs::create_dir_all(p.join("applications")).unwrap();
}
fs::write(
a.join("applications/hidden.desktop"),
"[Desktop Entry]\nHidden=true",
)
.unwrap();
fs::write(
b.join("applications/hidden.desktop"),
"[Desktop Entry]\nType=Application\nName=Hidden\nExec=test",
)
.unwrap();
fs::write(
a.join("applications/game.desktop"),
"[Desktop Entry]\nType=Application\nName=Game\nExec=steam steam://rungameid/42",
)
.unwrap();
fs::write(a.join("applications/terminal.desktop"),"[Other]\nName=Wrong\n[Desktop Entry]\nType=Application\nName=Terminal\nExec=terminal %U\nTerminal=true").unwrap();
let apps = desktop_apps(dir.path(), &[a, b], &BTreeSet::from([42]));
assert_eq!(apps.len(), 1);
assert_eq!(apps[0].id, "terminal.desktop");
}
#[test]
fn lepton_only_installed_third_party_packages() {
let dir = tempfile::tempdir().unwrap();
let runner = dir
.path()
.join(".local/share/Steam/steamapps/common/Lepton");
fs::create_dir_all(&runner).unwrap();
fs::write(runner.join("lepton"), "").unwrap();
let data = dir
.path()
.join(".local/share/lepton/contexts/test/baked/data_overlay");
fs::create_dir_all(data.join("system")).unwrap();
fs::create_dir_all(data.join("app/example")).unwrap();
fs::write(data.join("app/example/base.apk"), "apk").unwrap();
fs::write(data.join("system/packages.xml"),"<packages><package name=\"com.example.app\" codePath=\"/data/app/example\"/><package name=\"com.android.system\" codePath=\"/system/app/system\"/><package name=\"com.removed.app\" codePath=\"/data/app/missing\"/></packages>").unwrap();
let apps = lepton_apps(dir.path());
assert_eq!(apps.len(), 1);
assert_eq!(apps[0].id, "test/com.example.app");
}
#[test]
fn launch_handoffs_use_literal_arguments_and_reuse_live_lepton_context() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let tools = dir.path().join("tools");
fs::create_dir(&tools).unwrap();
for name in ["gio", "podman"] {
fs::write(tools.join(name),format!("#!/bin/sh\nif [ \"$1\" = inspect ]; then echo true; exit 0; fi\nprintf '%s\\n' \"$@\" > '{}'/{}-args\n",dir.path().display(),name)).unwrap();
fs::set_permissions(tools.join(name), fs::Permissions::from_mode(0o755)).unwrap();
}
crate::process::TEST_TOOLS.with(|p| *p.borrow_mut() = Some(tools));
let path = dir.path().join("app; literal.desktop");
launch_target(Target::Desktop(path.clone())).unwrap();
assert_eq!(
fs::read_to_string(dir.path().join("gio-args")).unwrap(),
format!("launch\n{}\n", path.display())
);
launch_target(Target::Lepton {
runner: dir.path().join("must-not-start"),
context: "existing".into(),
package: "com.example.app".into(),
})
.unwrap();
assert_eq!(fs::read_to_string(dir.path().join("podman-args")).unwrap(),"exec\nlepton-existing\nmonkey\n-p\ncom.example.app\n-c\nandroid.intent.category.LAUNCHER\n1\n");
crate::process::TEST_TOOLS.with(|p| *p.borrow_mut() = None);
}
#[test]
fn unknown_id_never_launches() {
let dir = tempfile::tempdir().unwrap();
assert!(launch(dir.path(), "desktop:../../arbitrary").is_err());
}
}
+57
View File
@@ -0,0 +1,57 @@
use anyhow::{ensure, Context, Result};
use serde_json::Value;
use std::{path::Path, process::Command};
pub fn collect(state: &Path) -> Result<Value> {
let output = Command::new("python3")
.args([
"-c",
include_str!("../tools/export-diagnostics.py"),
"--state",
])
.arg(state)
.output()
.context("Could not collect diagnostics")?;
ensure!(
output.status.success(),
"Diagnostic export failed: {}",
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).context("Invalid diagnostic archive")
}
#[cfg(test)]
mod tests {
use super::*;
use base64::{engine::general_purpose::STANDARD, Engine};
use std::io::{Cursor, Read};
#[test]
fn exports_without_a_running_daemon_and_with_corrupt_state() {
let state = tempfile::tempdir().unwrap();
std::fs::create_dir(state.path().join("logs")).unwrap();
std::fs::write(state.path().join("state.json"), "corrupt").unwrap();
std::fs::write(
state.path().join("logs/demo.log"),
"useful error\npassword=not-public",
)
.unwrap();
let result = collect(state.path()).unwrap();
let bytes = STANDARD.decode(result["data"].as_str().unwrap()).unwrap();
let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
let mut log = String::new();
archive
.by_name("logs/demo.log")
.unwrap()
.read_to_string(&mut log)
.unwrap();
assert!(log.contains("useful error"));
assert!(!log.contains("not-public"));
assert!(archive.by_name("report.json").is_ok());
assert!(archive.by_name("renderer/gpu.json").is_ok());
assert_eq!(
std::fs::read_to_string(state.path().join("state.json")).unwrap(),
"corrupt"
);
}
}
+28
View File
@@ -19,6 +19,12 @@ pub fn write(stream: &mut impl Write, v: &Value) -> Result<()> {
stream.flush()?;
Ok(())
}
pub(crate) fn response(result: Result<Value>) -> Value {
match result {
Ok(v) => json!({"result":v}),
Err(e) => json!({"error":format!("{e:#}")}),
}
}
pub fn call(path: &Path, method: &str, params: Value) -> Result<Value> {
call_timeout(path, method, params, Duration::from_secs(90))
}
@@ -38,6 +44,28 @@ pub fn call_timeout(path: &Path, method: &str, params: Value, timeout: Duration)
mod tests {
use super::*;
#[test]
fn service_errors_keep_the_cause_across_ipc() {
let dir = tempfile::tempdir().unwrap();
let socket = dir.path().join("service.sock");
let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
let worker = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let request = read(&mut stream).unwrap();
assert_eq!(request["method"], "install.batch");
let result = Err(anyhow::anyhow!("Permission denied (os error 13)"))
.context("安装插件 test.plugin 失败")
.context("批量安装失败,已恢复原版本和启用状态");
write(&mut stream, &response(result)).unwrap();
});
let error = call(&socket, "install.batch", json!({})).unwrap_err();
let message = error.to_string();
assert!(message.contains("批量安装失败,已恢复原版本和启用状态"));
assert!(message.contains("test.plugin"));
assert!(message.contains("Permission denied (os error 13)"));
worker.join().unwrap();
}
#[test]
fn package_messages_can_exceed_previous_transport_limit() {
let request = json!({"method":"install","params":{"package":"A".repeat(97 * 1024 * 1024)}});
+387
View File
@@ -0,0 +1,387 @@
//! Offline, cached phonetic indexes. This runs in the session HTTP worker, never CEF.
use anyhow::{Context, Result};
use pinyin::{ToPinyin, ToPinyinMulti};
use serde::Serialize;
use std::{
collections::{BTreeMap, BTreeSet},
fs::File,
path::Path,
};
use unicode_normalization::UnicodeNormalization;
use vibrato::{dictionary::Dictionary, Tokenizer};
#[derive(Clone, Serialize)]
pub struct SearchIndex {
terms: Vec<String>,
}
#[derive(Default)]
pub struct SearchCache {
tokenizer: Option<Tokenizer>,
entries: BTreeMap<String, SearchIndex>,
}
fn normalize(s: &str) -> String {
let decomposed = s
.nfkc()
.collect::<String>()
.nfd()
.filter(|c| {
!unicode_normalization::char::is_combining_mark(*c)
|| ['\u{3099}', '\u{309a}'].contains(c)
})
.collect::<String>();
decomposed
.nfc()
.flat_map(char::to_lowercase)
.filter(|c| c.is_alphanumeric())
.collect()
}
impl SearchCache {
pub fn batch(&mut self, path: &Path, names: &[String]) -> Result<serde_json::Value> {
if self.tokenizer.is_none() {
let reader = zstd::Decoder::new(
File::open(path).context("Japanese search dictionary missing")?,
)?;
self.tokenizer = Some(Tokenizer::new(Dictionary::read(reader)?).ignore_space(true)?);
}
// A bounded cache also avoids keeping every renamed app forever.
if self.entries.len() + names.len() > 8192 {
self.entries.clear();
}
for name in names {
if !self.entries.contains_key(name) {
self.entries
.insert(name.clone(), index(name, self.tokenizer.as_ref().unwrap()));
}
}
let result = serde_json::to_value(
names
.iter()
.map(|name| (name, &self.entries[name]))
.collect::<BTreeMap<_, _>>(),
)?;
let bytes: usize = self
.entries
.iter()
.map(|(name, index)| name.len() + index.terms.iter().map(String::len).sum::<usize>())
.sum();
if bytes > 8 * 1024 * 1024 {
self.entries.clear();
}
Ok(result)
}
}
fn index(name: &str, tokenizer: &Tokenizer) -> SearchIndex {
let name = name.nfkc().collect::<String>();
let mut terms = BTreeSet::new();
terms.insert(normalize(&name));
terms.insert(normalize(
&name
.split(|c: char| !c.is_alphanumeric())
.filter_map(|w| w.chars().next())
.collect::<String>(),
));
let parts: Vec<String> = name
.chars()
.map(|c| {
c.to_pinyin()
.map(|p| p.plain().into())
.unwrap_or_else(|| c.to_string())
})
.collect();
terms.insert(normalize(&parts.concat()));
terms.insert(normalize(
&parts
.iter()
.filter_map(|p| p.chars().next())
.collect::<String>(),
));
// Add individual alternate readings without a combinatorial expansion.
for (i, c) in name.chars().enumerate() {
if terms.len() >= 64 {
break;
}
if let Some(readings) = c.to_pinyin_multi() {
for reading in readings.into_iter().take(8) {
if terms.len() >= 64 {
break;
}
let mut variant = parts.clone();
variant[i] = reading.plain().into();
terms.insert(normalize(&variant.concat()));
terms.insert(normalize(
&variant
.iter()
.filter_map(|p| p.chars().next())
.collect::<String>(),
));
}
}
}
let mut worker = tokenizer.new_worker();
worker.reset_sentence(&name);
worker.tokenize();
let mut roman = String::new();
let mut initials = String::new();
for i in 0..worker.num_tokens() {
let token = worker.token(i);
let reading = token
.feature()
.split(',')
.nth(7)
.filter(|r| *r != "*")
.unwrap_or(token.surface());
let (full, short) = romanize(reading);
roman.push_str(&full);
initials.push_str(&short);
}
terms.insert(normalize(&roman));
terms.insert(normalize(&initials));
let (full, short) = romanize(&name);
terms.insert(normalize(&full));
terms.insert(normalize(&short));
terms.remove("");
SearchIndex {
terms: terms.into_iter().collect(),
}
}
// Hepburn-style syllables, retaining explicit vowels (トウキョウ -> toukyou).
fn romanize(value: &str) -> (String, String) {
let chars: Vec<char> = value
.nfkc()
.map(|c| {
if ('ぁ'..='ゖ').contains(&c) {
char::from_u32(c as u32 + 0x60).unwrap()
} else {
c
}
})
.collect();
let mut full = String::new();
let mut short = String::new();
let mut i = 0;
let mut geminate = false;
let mut in_latin = false;
while i < chars.len() {
let c = chars[i];
i += 1;
if c == 'ッ' {
geminate = true;
continue;
}
if c == 'ー' {
if let Some(v) = full.chars().rev().find(|c| "aeiou".contains(*c)) {
full.push(v);
}
continue;
}
let syllable = match c {
'ア' | 'ァ' => "a",
'イ' | 'ィ' => "i",
'ウ' | 'ゥ' => "u",
'エ' | 'ェ' => "e",
'オ' | 'ォ' => "o",
'カ' => "ka",
'キ' => "ki",
'ク' => "ku",
'ケ' => "ke",
'コ' => "ko",
'サ' => "sa",
'シ' => "shi",
'ス' => "su",
'セ' => "se",
'ソ' => "so",
'タ' => "ta",
'チ' => "chi",
'ツ' => "tsu",
'テ' => "te",
'ト' => "to",
'ナ' => "na",
'ニ' => "ni",
'ヌ' => "nu",
'ネ' => "ne",
'ノ' => "no",
'ハ' => "ha",
'ヒ' => "hi",
'フ' => "fu",
'ヘ' => "he",
'ホ' => "ho",
'マ' => "ma",
'ミ' => "mi",
'ム' => "mu",
'メ' => "me",
'モ' => "mo",
'ヤ' | 'ャ' => "ya",
'ユ' | 'ュ' => "yu",
'ヨ' | 'ョ' => "yo",
'ラ' => "ra",
'リ' => "ri",
'ル' => "ru",
'レ' => "re",
'ロ' => "ro",
'ワ' | 'ヮ' => "wa",
'ヰ' => "wi",
'ヱ' => "we",
'ヲ' => "wo",
'ン' => "n",
'ガ' => "ga",
'ギ' => "gi",
'グ' => "gu",
'ゲ' => "ge",
'ゴ' => "go",
'ザ' => "za",
'ジ' => "ji",
'ズ' => "zu",
'ゼ' => "ze",
'ゾ' => "zo",
'ダ' => "da",
'ヂ' => "ji",
'ヅ' => "zu",
'デ' => "de",
'ド' => "do",
'バ' => "ba",
'ビ' => "bi",
'ブ' => "bu",
'ベ' => "be",
'ボ' => "bo",
'パ' => "pa",
'ピ' => "pi",
'プ' => "pu",
'ペ' => "pe",
'ポ' => "po",
'ヴ' => "vu",
_ => "",
};
if syllable.is_empty() {
full.push(c);
if c.is_alphanumeric() {
if !in_latin {
short.push(c);
}
in_latin = true;
} else {
in_latin = false;
}
geminate = false;
continue;
}
in_latin = false;
let mut syllable = syllable.to_owned();
if i < chars.len() {
let small = chars[i];
if "ャュョ".contains(small) && syllable.ends_with('i') {
let base = match syllable.as_str() {
"shi" => "sh",
"chi" => "ch",
"ji" => "j",
_ => &syllable[..syllable.len() - 1],
};
syllable = format!(
"{}{}{}",
base,
if ["sh", "ch", "j"].contains(&base) {
""
} else {
"y"
},
match small {
'ャ' => "a",
'ュ' => "u",
_ => "o",
}
);
i += 1;
} else if "ァィゥェォ".contains(small)
&& !["a", "i", "u", "e", "o"].contains(&syllable.as_str())
{
let base = if syllable == "fu" {
"f"
} else if syllable == "vu" {
"v"
} else {
&syllable[..syllable.len() - 1]
};
syllable = format!(
"{}{}",
base,
match small {
'ァ' => "a",
'ィ' => "i",
'ゥ' => "u",
'ェ' => "e",
_ => "o",
}
);
i += 1;
}
}
if geminate {
if let Some(first) = syllable.chars().next().filter(|c| !"aeioun".contains(*c)) {
full.push(first);
}
geminate = false;
}
short.push(syllable.chars().next().unwrap());
full.push_str(&syllable);
}
(full, short)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn offline_multilingual_index_and_cache() {
let mut cache = SearchCache::default();
let names = vec![
"透视调色",
"さくら",
"東京",
"Half-Life: Alyx",
"Termix",
"ゲーム",
"キャット",
]
.into_iter()
.map(str::to_owned)
.collect::<Vec<_>>();
let started = std::time::Instant::now();
let v = cache
.batch(Path::new("assets/search/ipadic.dic.zst"), &names)
.unwrap();
println!("Launcher index cold: {:?}", started.elapsed());
for (name, needle) in [
("透视调色", "toushi"),
("透视调色", "tiaose"),
("透视调色", "tsts"),
("さくら", "sakura"),
("さくら", "skr"),
("東京", "toukyou"),
("Half-Life: Alyx", "hla"),
("Termix", "termix"),
("ゲーム", "geemu"),
("キャット", "kyatto"),
] {
assert!(
v[name]["terms"]
.as_array()
.unwrap()
.iter()
.any(|t| t.as_str().unwrap().contains(needle)),
"{name}: {needle}, {}",
v[name]
);
}
let cached = std::time::Instant::now();
assert_eq!(v, cache.batch(Path::new("does-not-exist"), &names).unwrap());
println!("Launcher index cached: {:?}", cached.elapsed());
}
#[test]
fn kana_and_normalization() {
assert_eq!(romanize("さくら"), ("sakura".into(), "skr".into()));
assert_eq!(romanize("トウキョウ").0, "toukyou");
assert_eq!(normalize("TOU shí-"), "toushi");
assert_ne!(normalize("ガ"), normalize("カ"));
assert_eq!(romanize("My アプリ").0, "My apuri");
}
}
+27
View File
@@ -1,8 +1,11 @@
mod auth;
mod desktop;
mod diagnostics;
mod http;
mod ipc;
mod jobs;
mod localization;
mod launcher_search;
mod model;
mod package;
mod planner;
@@ -11,6 +14,7 @@ mod recovery;
mod relations;
mod service;
mod session;
mod steam;
mod subscriptions;
#[cfg(test)]
mod tests;
@@ -31,6 +35,13 @@ struct Cli {
}
#[derive(Subcommand)]
enum Cmd {
/// Export logs even when the manager service is unavailable.
ExportLogs {
#[arg(long, default_value = "/var/lib/framely")]
state: PathBuf,
#[arg(long)]
output: PathBuf,
},
/// Disable and uninstall every plugin before removing the manager.
PrepareUninstall {
#[arg(long)]
@@ -129,6 +140,20 @@ enum Cmd {
}
fn run() -> Result<()> {
match Cli::parse().command {
Cmd::ExportLogs { state, output } => {
let archive = diagnostics::collect(&state)?;
let bytes = STANDARD.decode(archive["data"].as_str().context("Missing archive")?)?;
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&output)?;
file.write_all(&bytes)?;
println!("{}", output.display());
Ok(())
}
Cmd::PrepareUninstall { approve, socket } => {
anyhow::ensure!(unsafe { libc::geteuid() } == 0, "Uninstall requires root");
let result = ipc::call_timeout(
@@ -286,6 +311,8 @@ fn run() -> Result<()> {
documentation_url: v.manifest.documentation_url,
homepage: v.manifest.homepage,
api_version: v.manifest.api_version,
engines: v.manifest.engines,
compatible: None,
url: v.manifest.download_url.unwrap_or(format!(
"{}/{}",
base_url.trim_end_matches('/'),
+320 -2
View File
@@ -1,4 +1,4 @@
use anyhow::{bail, ensure, Result};
use anyhow::{bail, ensure, Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::{Component, Path};
@@ -116,9 +116,122 @@ fn window_width_meters() -> Option<f32> {
Some(3.0)
}
pub const LAUNCHER_VERSION: &str = "0.4.3-preview.2";
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Engines {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub framely: Option<String>,
}
impl Engines {
pub fn validate(&self) -> Result<()> {
if let Some(r) = &self.framely {
crate::relations::requirement(r)?;
}
Ok(())
}
pub fn matches(&self, version: &str) -> bool {
self.framely.as_ref().is_none_or(|r| {
crate::relations::requirement(r)
.ok()
.zip(semver::Version::parse(version).ok())
.is_some_and(|(r, v)| r.matches(&v))
})
}
pub fn check(&self) -> Result<()> {
ensure!(
self.matches(env!("CARGO_PKG_VERSION")),
"Plugin requires Framely {}; current version is {}",
self.framely.as_deref().unwrap_or("*"),
env!("CARGO_PKG_VERSION")
);
Ok(())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
pub enum LaunchTarget {
QuickPage,
Window { window: String },
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
pub enum LauncherActionTarget {
Window {
window: String,
},
Backend {
method: String,
#[serde(default)]
params: serde_json::Value,
},
Frontend {
entry: String,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LauncherAction {
pub id: String,
pub label: String,
pub target: LauncherActionTarget,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LauncherSettings {
#[serde(default)]
pub primary_trigger: bool,
#[serde(default = "yes")]
pub menu_auto_close: bool,
#[serde(default = "menu_timeout")]
pub menu_timeout_seconds: u32,
#[serde(default = "launcher_categories")]
pub all_categories: Vec<String>,
}
fn launcher_categories() -> Vec<String> {
["plugin", "steam", "lepton", "desktop"]
.into_iter()
.map(str::to_owned)
.collect()
}
fn menu_timeout() -> u32 {
10
}
impl Default for LauncherSettings {
fn default() -> Self {
Self {
primary_trigger: false,
menu_auto_close: true,
menu_timeout_seconds: 10,
all_categories: launcher_categories(),
}
}
}
impl LauncherSettings {
pub fn validate(&self) -> Result<()> {
let unique: std::collections::BTreeSet<_> = self.all_categories.iter().collect();
ensure!(
unique.len() == self.all_categories.len()
&& unique
.iter()
.all(|c| ["plugin", "steam", "lepton", "desktop"].contains(&c.as_str())),
"Invalid launcher categories"
);
ensure!(
(1..=300).contains(&self.menu_timeout_seconds),
"Menu timeout must be between 1 and 300 seconds"
);
Ok(())
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Ui {
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub launch: BTreeMap<String, LaunchTarget>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub launcher_actions: Vec<LauncherAction>,
pub quick_page: Option<String>,
#[serde(default)]
pub windows: BTreeMap<String, Window>,
@@ -138,6 +251,8 @@ pub struct Publish {
pub struct Manifest {
pub schema_version: u32,
pub api_version: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub engines: Option<Engines>,
pub id: String,
pub name: String,
pub version: String,
@@ -197,6 +312,9 @@ impl Manifest {
self.schema_version == 1 && self.api_version == API_VERSION,
"Unsupported manifest/API version"
);
if let Some(e) = &self.engines {
e.validate()?;
}
valid_id(&self.id)?;
self.relations().validate(&self.id, &self.version)?;
for link in self
@@ -318,6 +436,81 @@ impl Manifest {
if let Some(p) = &self.ui.quick_page {
check(p)?;
}
if !self.ui.launch.is_empty() || !self.ui.launcher_actions.is_empty() {
let range = self
.engines
.as_ref()
.and_then(|e| e.framely.as_ref())
.context("Launcher features require engines.framely")?;
let requirement = crate::relations::requirement(range)?;
// Require an explicit floor so older hosts cannot be included accidentally.
let floor = semver::Version::parse(LAUNCHER_VERSION)?;
ensure!(
requirement.comparators.iter().any(|c| {
matches!(
c.op,
semver::Op::Greater
| semver::Op::GreaterEq
| semver::Op::Exact
| semver::Op::Caret
| semver::Op::Tilde
) && c.minor.is_some()
&& c.patch.is_some()
&& semver::Version {
major: c.major,
minor: c.minor.unwrap(),
patch: c.patch.unwrap(),
pre: c.pre.clone(),
build: semver::BuildMetadata::EMPTY,
} >= floor
}),
"Launcher features require an explicit version floor of {} or newer",
LAUNCHER_VERSION
);
}
for (source, target) in &self.ui.launch {
ensure!(
["launcher", "quickPanel", "manager"].contains(&source.as_str()),
"Unknown launch source"
);
match target {
LaunchTarget::QuickPage => {
ensure!(self.ui.quick_page.is_some(), "No quick page declared")
}
LaunchTarget::Window { window } => ensure!(
self.ui.windows.contains_key(window),
"Launch window not declared"
),
}
}
ensure!(
self.ui.launcher_actions.len() <= 16,
"Too many launcher actions"
);
let mut action_ids = std::collections::BTreeSet::new();
for action in &self.ui.launcher_actions {
valid_id(&action.id)?;
ensure!(
action_ids.insert(&action.id)
&& !action.label.is_empty()
&& action.label.len() <= 120,
"Invalid launcher action"
);
match &action.target {
LauncherActionTarget::Window { window } => ensure!(
self.ui.windows.contains_key(window),
"Action window not declared"
),
LauncherActionTarget::Frontend { entry } => check(entry)?,
LauncherActionTarget::Backend { method, .. } => ensure!(
self.backend.is_some()
&& !method.is_empty()
&& method.len() <= 120
&& !method.starts_with("framely."),
"Invalid backend action method"
),
}
}
ensure!(self.ui.windows.len() <= 8, "Too many declared windows");
for (key, w) in &self.ui.windows {
valid_id(key)?;
@@ -583,13 +776,129 @@ pub struct Database {
pub update_source: Option<UpdateSource>,
#[serde(default, skip_serializing_if = "UpdateChannel::is_stable")]
pub update_channel: UpdateChannel,
#[serde(default)]
pub update_check: UpdateCheckSettings,
#[serde(default)]
pub update_notice: Option<UpdateNotice>,
#[serde(default)]
pub notification_inbox: BTreeMap<String, NotificationEntry>,
#[serde(default)]
pub notification_settings: NotificationSettings,
#[serde(default)]
pub launcher: LauncherSettings,
#[serde(default)]
pub steam_favorites: std::collections::BTreeSet<u32>,
#[serde(default)]
pub launcher_order: Vec<String>,
#[serde(default)]
pub launcher_favorites: std::collections::BTreeSet<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct NotificationPreference {
#[serde(default = "yes")]
pub popups: bool,
#[serde(default = "yes")]
pub badge: bool,
}
impl Default for NotificationPreference {
fn default() -> Self {
Self {
popups: true,
badge: true,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct NotificationSettings {
#[serde(default = "yes")]
pub popups: bool,
#[serde(default = "yes")]
pub badge: bool,
#[serde(default)]
pub plugins: BTreeMap<String, NotificationPreference>,
}
impl Default for NotificationSettings {
fn default() -> Self {
Self {
popups: true,
badge: true,
plugins: BTreeMap::new(),
}
}
}
impl NotificationSettings {
pub fn popups_for(&self, plugin: &str) -> bool {
self.popups && self.plugins.get(plugin).is_none_or(|p| p.popups)
}
pub fn badge_for(&self, plugin: &str) -> bool {
self.badge && self.plugins.get(plugin).is_none_or(|p| p.badge)
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct NotificationSettingsPatch {
pub plugin: Option<String>,
pub popups: Option<bool>,
pub badge: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct UpdateCheckSettings {
pub enabled: bool,
pub interval_hours: u64,
}
impl Default for UpdateCheckSettings {
fn default() -> Self {
Self {
enabled: true,
interval_hours: 6,
}
}
}
impl UpdateCheckSettings {
pub fn validate(&self) -> Result<()> {
ensure!(
(1..=168).contains(&self.interval_hours),
"自动检查间隔须为 1-168 小时"
);
Ok(())
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct UpdateNotice {
pub source: UpdateSource,
pub channel: UpdateChannel,
pub version: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct NotificationEntry {
pub plugin: String,
pub plugin_name: String,
pub created_at: u64,
pub expires_at: Option<u64>,
pub toast: bool,
pub in_inbox: bool,
#[serde(default)]
pub read: bool,
pub notification: Notification,
#[serde(default)]
pub update: Option<UpdateNotice>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Action {
pub id: String,
pub label: String,
#[serde(default)]
pub icon: String,
#[serde(default = "yes")]
pub close_on_click: bool,
#[serde(default = "yes")]
pub remove_from_inbox_on_click: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
@@ -603,6 +912,8 @@ pub struct Notification {
pub actions: Vec<Action>,
#[serde(default = "ttl")]
pub duration_ms: u64,
#[serde(default)]
pub inbox: bool,
}
fn ttl() -> u64 {
8000
@@ -615,7 +926,7 @@ impl Notification {
"Notification limit exceeded"
);
ensure!(
(1000..=60000).contains(&self.duration_ms),
self.duration_ms == 0 || (1000..=60000).contains(&self.duration_ms),
"Invalid notification duration"
);
let mut ids = std::collections::BTreeSet::new();
@@ -663,7 +974,11 @@ pub struct CatalogEntry {
pub documentation_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub homepage: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub compatible: Option<bool>,
pub api_version: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub engines: Option<Engines>,
pub url: String,
pub sha256: String,
#[serde(default)]
@@ -710,6 +1025,9 @@ impl CatalogEntry {
}
pub fn validate(&self, allow_http: bool) -> Result<()> {
if let Some(e) = &self.engines {
e.validate()?;
}
valid_id(&self.id)?;
self.relations().validate(&self.id, &self.version)?;
for link in self
+27 -9
View File
@@ -66,10 +66,13 @@ impl Resolver<'_> {
fn matching_catalog(&mut self, source: &Source, id: &str, dep: &Dependency) -> Result<Catalog> {
let mut catalog = self.catalog(source)?;
if catalog.plugins.iter().any(|p| p.id == id)
&& !catalog
.plugins
.iter()
.any(|p| p.id == id && dep.matches(&p.version).unwrap_or(false))
&& !catalog.plugins.iter().any(|p| {
p.id == id
&& p.engines
.as_ref()
.is_none_or(|e| e.matches(env!("CARGO_PKG_VERSION")))
&& dep.matches(&p.version).unwrap_or(false)
})
&& !self.histories.contains(&(source.id.clone(), id.to_owned()))
{
let history = crate::session::fetch_plugin_versions_cancel(
@@ -141,10 +144,13 @@ impl Resolver<'_> {
for source in sources.into_iter().filter(|s| s.enabled) {
match self.matching_catalog(&source, id, dep) {
Ok(c) => {
if c.plugins
.iter()
.any(|p| p.id == id && dep.matches(&p.version).unwrap_or(false))
{
if c.plugins.iter().any(|p| {
p.id == id
&& p.engines
.as_ref()
.is_none_or(|e| e.matches(env!("CARGO_PKG_VERSION")))
&& dep.matches(&p.version).unwrap_or(false)
}) {
let preferred =
selected.is_none() && Some(source.id.as_str()) == origin;
candidates.push(source);
@@ -184,7 +190,13 @@ impl Resolver<'_> {
let entry = catalog
.plugins
.iter()
.find(|p| p.id == id && dep.matches(&p.version).unwrap_or(false))
.find(|p| {
p.id == id
&& p.engines
.as_ref()
.is_none_or(|e| e.matches(env!("CARGO_PKG_VERSION")))
&& dep.matches(&p.version).unwrap_or(false)
})
.context("指定源中不存在依赖")?;
ensure!(
dep.matches(&entry.version)?,
@@ -197,6 +209,9 @@ impl Resolver<'_> {
|_, _| self.cancel.check(),
)?;
let manifest = bytes.manifest()?;
if let Some(e) = &manifest.engines {
e.check()?;
}
ensure!(
manifest.id == entry.id && manifest.version == entry.version,
"依赖包 ID 或版本与目录不一致"
@@ -299,6 +314,9 @@ pub fn prepare_staged(
) -> Result<Prepared> {
cancel.check()?;
let manifest = bytes.manifest()?;
if let Some(e) = &manifest.engines {
e.check()?;
}
let root = manifest.id.clone();
if let Some(source) = &source {
ensure!(db.sources.iter().any(|s| &s.id == source), "未知安装来源");
+1 -1
View File
@@ -29,7 +29,7 @@ pub struct ExitInfo {
}
#[cfg(test)]
thread_local! { pub static TEST_TOOLS: std::cell::RefCell<Option<std::path::PathBuf>> = const { std::cell::RefCell::new(None) }; }
fn tool(name: &str) -> Command {
pub(crate) fn tool(name: &str) -> Command {
#[cfg(test)]
if let Some(root) = TEST_TOOLS.with(|p| p.borrow().clone()) {
return Command::new(root.join(name));
+1083 -55
View File
File diff suppressed because it is too large. Load diff
+287 -16
View File
@@ -31,6 +31,7 @@ struct Agent {
commands: Mutex<VecDeque<Value>>,
events: Mutex<EventLog>,
jobs: crate::jobs::Jobs,
launcher_search: Mutex<crate::launcher_search::SearchCache>,
catalog_cache: Arc<Mutex<std::collections::BTreeMap<String, Value>>>,
}
#[derive(Default)]
@@ -358,7 +359,13 @@ impl Agent {
commands.push(queue.pop_front().unwrap());
}
drop(queue);
return send_json(r, json!({"commands":commands}));
let badge = self
.core("host.notification.badge", json!({}))
.unwrap_or(json!(0));
return send_json(
r,
json!({"commands":commands,"notificationBadge":badge,"launcher":self.core("status",json!({})).ok().map(|v|v["database"]["launcher"].clone()).unwrap_or(json!({}))}),
);
}
if let Some(rel) = path.strip_prefix("/plugin-assets/") {
let (id, file) = rel.split_once('/').context("Invalid asset path")?;
@@ -381,7 +388,10 @@ impl Agent {
.join(&m.version);
return send_file(r, &root.join(file), true);
}
if let Some(rel) = path.strip_prefix("/plugin-frame/") {
if let Some(rel) = path
.strip_prefix("/plugin-frame/")
.or_else(|| path.strip_prefix("/plugin-action-frame/"))
{
let parts: Vec<_> = rel.split('/').collect();
ensure!(parts.len() == 2, "Invalid plugin frame");
let id = parts[0];
@@ -397,7 +407,23 @@ impl Agent {
"Plugin disabled"
);
let m: Manifest = serde_json::from_value(p["manifest"].clone())?;
let entry = if parts[1] == "quick" {
if let Some(e) = &m.engines {
e.check()?;
}
let entry = if path.starts_with("/plugin-action-frame/") {
let action = parts[1];
match &m
.ui
.launcher_actions
.iter()
.find(|a| a.id == action)
.context("Unknown action")?
.target
{
LauncherActionTarget::Frontend { entry } => entry.clone(),
_ => anyhow::bail!("Not a frontend action"),
}
} else if parts[1] == "quick" {
m.ui.quick_page.clone().context("No quick page")?
} else {
m.ui.windows
@@ -524,6 +550,9 @@ impl Agent {
let mut bytes = Vec::new();
r.as_reader().read_to_end(&mut bytes)?;
let mut request: Value = serde_json::from_slice(&bytes)?;
if request["method"] == "diagnostics.export" {
request["params"] = json!({"remote":remote});
}
if remote && request["method"] == "ui.visibility.get" {
request["params"] = json!({"view":""});
}
@@ -541,9 +570,21 @@ impl Agent {
if path == "/"
|| path == "/manager"
|| path == "/notifications"
|| path == "/launcher"
|| path.starts_with("/window/")
{
let data = fs::read(self.assets.join("index.html"))?;
let data = if remote {
String::from_utf8(data)?
.replacen(
"<head>",
"<head><meta name=\"framely-remote\" content=\"true\">",
1,
)
.into_bytes()
} else {
data
};
let response=Response::from_data(data).with_header(header("Content-Type","text/html; charset=utf-8")).with_header(header("Content-Security-Policy","default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https: http:; frame-src 'self' http://localhost:*; connect-src 'self'; base-uri 'none'; form-action 'none'"));
r.respond(response)?;
return Ok(());
@@ -577,10 +618,68 @@ impl Agent {
);
}
match method {
"launcher.search.index" => {
let names: Vec<String> = serde_json::from_value(p["names"].clone())?;
ensure!(
names.len() <= 4096
&& names.iter().map(String::len).sum::<usize>() <= 262144
&& names
.iter()
.all(|n| n.len() <= 1024 && !n.chars().any(char::is_control)),
"Invalid launcher search names"
);
let parent = self
.assets
.parent()
.context("Missing search asset directory")?;
let packaged = parent.join("search/ipadic.dic.zst");
let path = if packaged.is_file() {
packaged
} else {
// Source checkout: --assets ui/dist, with data in assets/search.
parent
.parent()
.unwrap_or(Path::new("."))
.join("assets/search/ipadic.dic.zst")
};
// HTTP requests run on workers, so dictionary loading never blocks native input.
self.launcher_search.lock().unwrap().batch(&path, &names)
}
"desktop.list" => Ok(json!(crate::desktop::discover(&crate::steam::home()?))),
"desktop.launch" => {
let id = p["app"].as_str().context("Missing desktop app")?;
crate::desktop::launch(&crate::steam::home()?, id)?;
push(&self.commands, json!({"kind":"launcher.close"}));
Ok(json!(true))
}
"steam.list" => Ok(json!(crate::steam::discover(&crate::steam::home()?))),
"steam.launch" => {
let id = p["app"]
.as_u64()
.filter(|v| *v > 0 && *v <= u32::MAX as u64)
.context("Invalid Steam app")? as u32;
crate::steam::launch(id)?;
push(&self.commands, json!({"kind":"launcher.close"}));
Ok(json!(true))
}
"host.launcher.close" => {
push(&self.commands, json!({"kind":"launcher.close"}));
Ok(json!(true))
}
"host.plugin.manage" => {
let id = p["plugin"].as_str().context("Missing plugin")?;
valid_id(id)?;
push(
&self.commands,
json!({"kind":"manager.open","page":format!("plugin:{id}")}),
);
Ok(json!(true))
}
"agreement.decline" => {
let view = p["view"].as_str().context("Missing view")?;
ensure!(
view == "menu"
|| view == "launcher"
|| view == "framely.manager"
|| view.starts_with("framely.window."),
"Invalid view"
@@ -696,8 +795,13 @@ impl Agent {
_ => "menu.close",
};
let mut command = json!({"kind":kind});
if method == "host.manager.open" && p["page"] == "catalog" {
command["page"] = json!("catalog");
if method == "host.manager.open"
&& matches!(
p["page"].as_str(),
Some("catalog" | "updates" | "notification-settings" | "launcher-settings")
)
{
command["page"] = p["page"].clone();
}
push(&self.commands, command);
Ok(json!(true))
@@ -738,12 +842,50 @@ impl Agent {
Ok(json!(true))
})
}
"diagnostics.export" => {
use base64::Engine;
let mut result = self.core("diagnostics.export", json!({}))?;
if p["remote"] != true {
let name = result["name"].as_str().context("Missing archive name")?;
ensure!(
name.starts_with("framely-logs-")
&& name.ends_with(".zip")
&& !name.contains('/')
&& !name.contains('\\'),
"Invalid archive name"
);
let bytes = base64::engine::general_purpose::STANDARD
.decode(result["data"].as_str().context("Missing archive data")?)?;
let dir =
PathBuf::from(std::env::var_os("HOME").context("Missing home directory")?)
.join("Downloads");
fs::create_dir_all(&dir)?;
let file = dir.join(format!(
"{}-{}.zip",
name.trim_end_matches(".zip"),
random_key()
));
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&file)?
.write_all(&bytes)?;
result["path"] = json!(file);
result.as_object_mut().unwrap().remove("data");
}
Ok(result)
}
"host.haptic" => {
let view = p["view"].as_str().context("Missing haptic view")?;
ensure!(
view.len() <= 160
&& (matches!(view, "menu" | "framely.manager" | "notifications")
|| view.starts_with("framely.window.")),
&& (matches!(
view,
"menu" | "launcher" | "framely.manager" | "notifications"
) || view.starts_with("framely.window.")),
"Invalid haptic view"
);
let mut commands = self.commands.lock().unwrap();
@@ -784,11 +926,21 @@ impl Agent {
| "plugin.uninstall"
| "plugin.open"
| "plugin.call"
| "plugin.launch.context"
| "plugin.launch"
| "plugin.launcher.action"
| "launcher.settings.save"
| "launcher.order.save"
| "launcher.favorite"
| "steam.favorite"
| "window.open"
| "window.close"
| "notification.send"
| "notification.dismiss"
| "notification.remove"
| "notification.action"
| "notification.settings.save"
| "notification.read"
| "sources.save"
| "subscriptions.add"
| "subscriptions.change"
@@ -802,6 +954,7 @@ impl Agent {
| "safeMode"
| "system.source.save"
| "system.channel.save"
| "system.check.settings.save"
| "system.check.start"
| "system.download.start"
| "system.job.status"
@@ -844,14 +997,20 @@ pub(crate) fn fetch_catalog_proxy_cancel(
.context("插件源连接失败")?;
let bytes = crate::http::read_cancel(response, 2 * 1024 * 1024, cancel)?;
ensure!(bytes.len() <= 2 * 1024 * 1024, "插件目录超过 2 MiB");
let catalog: Catalog = serde_json::from_slice(&bytes).context("目录格式无效")?;
let mut catalog: Catalog = serde_json::from_slice(&bytes).context("目录格式无效")?;
ensure!(
catalog.schema_version == 1 && catalog.plugins.len() <= 1000,
"不支持的插件目录"
);
let mut ids = std::collections::BTreeSet::new();
for p in &catalog.plugins {
for p in &mut catalog.plugins {
p.validate(source.allow_http)?;
p.compatible = Some(
p.api_version == API_VERSION
&& p.engines
.as_ref()
.is_none_or(|e| e.matches(env!("CARGO_PKG_VERSION"))),
);
ensure!(ids.insert(&p.id), "主目录中有重复插件 ID");
}
Ok(catalog)
@@ -874,14 +1033,22 @@ pub(crate) fn fetch_plugin_versions_cancel(
cancel,
)?;
let bytes = crate::http::read_cancel(response, 2 * 1024 * 1024, cancel)?;
let document: PluginVersions = serde_json::from_slice(&bytes).context("历史版本格式无效")?;
let mut document: PluginVersions =
serde_json::from_slice(&bytes).context("历史版本格式无效")?;
ensure!(
document.schema_version == 1 && document.id == plugin_id && document.versions.len() <= 1000,
"不支持的插件历史版本目录"
);
let mut versions = std::collections::BTreeSet::new();
for entry in &document.versions {
for entry in &mut document.versions {
entry.validate(source.allow_http)?;
entry.compatible = Some(
entry.api_version == API_VERSION
&& entry
.engines
.as_ref()
.is_none_or(|e| e.matches(env!("CARGO_PKG_VERSION"))),
);
ensure!(
entry.id == plugin_id && versions.insert(&entry.version),
"历史版本 ID 不匹配或版本重复"
@@ -1074,6 +1241,7 @@ pub fn serve(
commands: Mutex::default(),
events: Mutex::default(),
jobs: crate::jobs::Jobs::default(),
launcher_search: Mutex::default(),
catalog_cache: Arc::default(),
});
let network_agent = agent.clone();
@@ -1115,6 +1283,8 @@ pub fn serve(
"window.close",
"plugin.disabled",
"notification.changed",
"manager.open",
"menu.open",
]
.contains(&e["kind"].as_str().unwrap_or(""))
{
@@ -1456,6 +1626,7 @@ mod tests {
commands: Mutex::default(),
events: Mutex::default(),
jobs: crate::jobs::Jobs::default(),
launcher_search: Mutex::default(),
catalog_cache: Arc::default(),
})
}
@@ -1473,12 +1644,98 @@ mod tests {
})
}
#[test]
fn manager_store_entry_preserves_catalog_target_and_rejects_arbitrary_pages() {
fn launcher_favorites_pass_through_real_http_session_and_persist() {
let root = tempfile::tempdir().unwrap();
let server = Server::http("127.0.0.1:0").unwrap();
let agent = agent(&server, root.path());
let manager = unsafe { libc::geteuid() };
let mut core = crate::tests::accepted_service(&agent.state, manager).unwrap();
let package = crate::tests::fixture(root.path(), "favorite.demo", "1.0.0", 1, None);
core.handle(
"install",
json!({"package":STANDARD.encode(package),"approve":true}),
)
.unwrap();
let socket = UnixListener::bind(&agent.socket).unwrap();
socket.set_nonblocking(true).unwrap();
let stop = Arc::new(AtomicBool::new(false));
let core_stop = stop.clone();
let core_worker = std::thread::spawn(move || {
while !core_stop.load(Ordering::Relaxed) {
if let Ok((mut stream, _)) = socket.accept() {
let request = ipc::read(&mut stream).unwrap();
let response = ipc::response(core.handle(
request["method"].as_str().unwrap(),
request["params"].clone(),
));
ipc::write(&mut stream, &response).unwrap();
} else {
std::thread::sleep(Duration::from_millis(5));
}
}
});
let http = http_server(server, agent.clone(), stop.clone());
let request = |method: &str, params: Value| -> Value {
ureq::post(&format!("{}/api", agent.origin))
.set("Cookie", &format!("framely={}", agent.web_key))
.set("Origin", &agent.origin)
.send_json(json!({"method":method,"params":params}))
.unwrap()
.into_json()
.unwrap()
};
let responses: Vec<_> = [
"plugin:favorite.demo",
"steam:42",
"framely",
"desktop:terminal.desktop",
"lepton:default/app",
]
.into_iter()
.map(|key| request("launcher.favorite", json!({"key":key,"favorite":true})))
.collect();
let status = request("status", json!({}));
let removed = request(
"launcher.favorite",
json!({"key":"framely","favorite":false}),
);
let denied = request("launcher.favorite.invalid", json!({}));
stop.store(true, Ordering::Relaxed);
http.join().unwrap();
core_worker.join().unwrap();
for response in responses {
assert_eq!(response["result"], true, "{response}");
}
assert_eq!(
status["result"]["database"]["plugins"]["favorite.demo"]["favorite"],
true
);
assert_eq!(status["result"]["database"]["steamFavorites"], json!([42]));
assert_eq!(removed["result"], true);
assert!(denied.get("error").is_some());
let loaded = crate::service::Service::load(&agent.state, manager).unwrap();
assert!(loaded.db.plugins["favorite.demo"].favorite);
assert!(loaded.db.steam_favorites.contains(&42));
assert_eq!(
loaded.db.launcher_favorites,
[
"desktop:terminal.desktop".to_owned(),
"lepton:default/app".to_owned()
]
.into_iter()
.collect()
);
}
#[test]
fn manager_entry_preserves_catalog_and_update_targets_and_rejects_arbitrary_pages() {
let root = tempfile::tempdir().unwrap();
let server = Server::http("127.0.0.1:0").unwrap();
let agent = agent(&server, root.path());
for params in [
json!({"page":"catalog"}),
json!({"page":"updates"}),
json!({"page":"notification-settings"}),
json!({"page":"launcher-settings"}),
json!({}),
json!({"page":"https://example.org"}),
] {
@@ -1488,8 +1745,17 @@ mod tests {
}
let commands = agent.commands.lock().unwrap();
assert_eq!(commands[0], json!({"kind":"manager.open","page":"catalog"}));
assert_eq!(commands[1], json!({"kind":"manager.open"}));
assert_eq!(commands[2], json!({"kind":"manager.open"}));
assert_eq!(commands[1], json!({"kind":"manager.open","page":"updates"}));
assert_eq!(
commands[2],
json!({"kind":"manager.open","page":"notification-settings"})
);
assert_eq!(
commands[3],
json!({"kind":"manager.open","page":"launcher-settings"})
);
assert_eq!(commands[4], json!({"kind":"manager.open"}));
assert_eq!(commands[5], json!({"kind":"manager.open"}));
}
#[test]
fn declining_agreement_only_closes_current_view() {
@@ -1871,7 +2137,12 @@ mod tests {
let listener = std::os::unix::net::UnixListener::bind(&agent.socket).unwrap();
let socket_worker = std::thread::spawn(move || {
let mut core = crate::service::Service::load(&root.path().join("state"), 1000).unwrap();
for expected in ["host.ui.visibility", "agreement.status"] {
for expected in [
"host.ui.visibility",
"host.notification.badge",
"status",
"agreement.status",
] {
let (mut stream, _) = listener.accept().unwrap();
let request = ipc::read(&mut stream).unwrap();
assert_eq!(request["method"], expected);
@@ -2244,7 +2515,7 @@ mod tests {
.unwrap();
print!("{}", String::from_utf8_lossy(&store_result.stdout));
eprint!("{}", String::from_utf8_lossy(&store_result.stderr));
agent.core("notification.send",json!({"plugin":"test.bridge","notification":{"id":"toast","title":"Toast integration","body":"Compact notification body","image":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aN1kAAAAASUVORK5CYII=","durationMs":15000,"actions":[{"id":"ok","label":"确认","icon":"✓"},{"id":"save","label":"保存","icon":"↓"},{"id":"more","label":"详情","icon":"⋯"}]}})).unwrap();
agent.core("notification.send",json!({"plugin":"test.bridge","notification":{"id":"toast","title":"Toast integration","body":"Compact notification body","image":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aN1kAAAAASUVORK5CYII=","durationMs":15000,"actions":[{"id":"ok","label":"确认","icon":"✓","closeOnClick":false,"removeFromInboxOnClick":false},{"id":"save","label":"保存","icon":"↓"},{"id":"more","label":"详情","icon":"⋯"}]}})).unwrap();
let notification_result = Command::new(std::env::var_os("FRAMELY_BROWSER_PROBE").unwrap())
.arg(format!(
"{}/boot/{}?view=notifications",
+418
View File
@@ -0,0 +1,418 @@
//! Local Steam library discovery. No account API or network access is needed.
use anyhow::{ensure, Context, Result};
use serde::Serialize;
use std::{
collections::{BTreeMap, BTreeSet},
fs,
path::{Path, PathBuf},
process::Stdio,
};
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct App {
pub id: u32,
pub name: String,
pub kind: &'static str,
pub icon: Option<String>,
pub icon_fit: &'static str,
}
#[derive(Debug)]
enum Value {
Text(String),
Object(BTreeMap<String, Value>),
}
fn tokens(input: &str) -> Result<Vec<String>> {
let mut chars = input.chars().peekable();
let mut out = Vec::new();
while let Some(c) = chars.next() {
match c {
c if c.is_whitespace() => {}
'/' if chars.peek() == Some(&'/') => {
for c in chars.by_ref() {
if c == '\n' {
break;
}
}
}
'{' | '}' => out.push(c.to_string()),
'"' => {
let mut s = String::new();
let mut closed = false;
while let Some(c) = chars.next() {
if c == '"' {
closed = true;
break;
}
if c == '\\' {
let e = chars.next().context("Truncated escape")?;
s.push(match e {
'n' => '\n',
't' => '\t',
other => other,
});
} else {
s.push(c);
}
}
ensure!(closed, "Unclosed VDF string");
out.push(s);
}
_ => {
let mut s = c.to_string();
while chars
.peek()
.is_some_and(|c| !c.is_whitespace() && *c != '{' && *c != '}')
{
s.push(chars.next().unwrap());
}
out.push(s);
}
}
}
Ok(out)
}
fn object(
tokens: &[String],
i: &mut usize,
depth: usize,
nested: bool,
) -> Result<BTreeMap<String, Value>> {
ensure!(depth < 32, "VDF too deep");
let mut out = BTreeMap::new();
while *i < tokens.len() {
if tokens[*i] == "}" {
ensure!(nested, "Unexpected brace");
*i += 1;
return Ok(out);
}
let key = tokens[*i].clone();
*i += 1;
let v = tokens.get(*i).context("Missing VDF value")?;
*i += 1;
let value = if v == "{" {
Value::Object(object(tokens, i, depth + 1, true)?)
} else {
ensure!(v != "}", "Missing VDF value");
Value::Text(v.clone())
};
out.insert(key, value);
}
ensure!(!nested, "Unclosed VDF object");
Ok(out)
}
fn read(path: &Path) -> Result<BTreeMap<String, Value>> {
let bytes = fs::read(path)?;
ensure!(bytes.len() <= 8 * 1024 * 1024, "VDF too large");
let t = tokens(std::str::from_utf8(&bytes)?)?;
object(&t, &mut 0, 0, false)
}
fn text<'a>(v: &'a BTreeMap<String, Value>, key: &str) -> Option<&'a str> {
if let Some(Value::Text(s)) = v.get(key) {
Some(s)
} else {
None
}
}
fn root<'a>(v: &'a BTreeMap<String, Value>, key: &str) -> Option<&'a BTreeMap<String, Value>> {
if let Some(Value::Object(v)) = v.get(key) {
Some(v)
} else {
None
}
}
pub fn discover(home: &Path) -> Vec<App> {
let steam = home.join(".local/share/Steam");
let steam = if steam.exists() {
steam
} else {
home.join(".steam/steam")
};
let mut libraries = BTreeSet::from([steam.clone()]);
if let Ok(v) = read(&steam.join("steamapps/libraryfolders.vdf")) {
if let Some(v) = root(&v, "libraryfolders") {
for (key, value) in v {
if key.parse::<u32>().is_err() {
continue;
}
let path = match value {
Value::Text(s) => Some(s.as_str()),
Value::Object(v) => text(v, "path"),
};
if let Some(p) = path {
let p = PathBuf::from(p);
if p.is_absolute() {
libraries.insert(p);
}
}
}
}
}
let mut apps = BTreeMap::new();
for library in libraries {
let Ok(entries) = fs::read_dir(library.join("steamapps")) else {
continue;
};
for entry in entries.flatten() {
let p = entry.path();
let Some(file) = p.file_name().and_then(|s| s.to_str()) else {
continue;
};
if !file.starts_with("appmanifest_") || !file.ends_with(".acf") {
continue;
}
let Ok(v) = read(&p) else { continue };
let Some(v) = root(&v, "AppState") else {
continue;
};
let Some(id) = text(v, "appid")
.and_then(|s| s.parse::<u32>().ok())
.filter(|v| *v > 0)
else {
continue;
};
let Some(name) = text(v, "name").filter(|n| !n.is_empty()) else {
continue;
};
let flags = text(v, "StateFlags")
.and_then(|s| s.parse::<u32>().ok())
.unwrap_or(0);
if flags & 4 == 0 {
continue;
}
let lower = name.to_lowercase();
if [
"steamvr",
"lepton",
"lepton development",
"steam linux runtime",
"proton",
"steamworks common redistributables",
]
.iter()
.any(|s| lower == *s || lower.starts_with(&format!("{s} ")))
{
continue;
}
let dir = steam.join("appcache/librarycache").join(id.to_string());
let mut candidates: Vec<_> = fs::read_dir(dir)
.ok()
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.collect();
// Newer Steam clients keep named artwork one level below a content hash.
let nested: Vec<_> = candidates
.iter()
.filter(|p| p.is_dir())
.take(16)
.cloned()
.collect();
for path in nested {
candidates.extend(
fs::read_dir(path)
.ok()
.into_iter()
.flatten()
.flatten()
.take(32)
.map(|e| e.path()),
);
}
for suffix in ["icon.jpg", "icon.png", "library_600x900.jpg", "header.jpg"] {
candidates.push(
steam
.join("appcache/librarycache")
.join(format!("{id}_{suffix}")),
);
}
let artwork_fit = |p: &Path| {
let name = p.file_name().and_then(|n| n.to_str()).unwrap_or_default();
if name.contains("600x900") || name == "library_capsule.jpg" {
(0, "cover")
} else if name.contains("header") {
(1, "cover")
} else if name == "logo.png" {
(2, "contain")
} else {
(3, "contain")
}
};
candidates.sort_by_key(|p| (artwork_fit(p).0, p.clone()));
let icon = candidates.into_iter().take(32).find_map(|p| {
if fs::metadata(&p).ok()?.len() > 1024 * 1024 {
return None;
}
let b = fs::read(&p).ok()?;
let mime = if b.starts_with(b"\x89PNG\r\n\x1a\n") {
"image/png"
} else if b.starts_with(&[0xff, 0xd8, 0xff]) {
"image/jpeg"
} else {
return None;
};
use base64::Engine;
Some((
format!(
"data:{mime};base64,{}",
base64::engine::general_purpose::STANDARD.encode(b)
),
artwork_fit(&p).1,
))
});
apps.insert(
id,
App {
id,
name: name.into(),
kind: if text(v, "installdir").is_some_and(|dir| {
fs::read_dir(library.join("steamapps/common").join(dir)).is_ok_and(
|entries| {
entries
.flatten()
.any(|e| e.path().extension().is_some_and(|ext| ext == "apk"))
},
)
}) {
"lepton"
} else {
"steam"
},
icon_fit: icon.as_ref().map(|v| v.1).unwrap_or("contain"),
icon: icon.map(|v| v.0),
},
);
}
}
apps.into_values().collect()
}
pub fn home() -> Result<PathBuf> {
ensure!(
unsafe { libc::geteuid() } != 0,
"Steam launcher must run in the user session"
);
Ok(crate::process::user_home(unsafe { libc::geteuid() })?.into())
}
pub fn launch(id: u32) -> Result<()> {
launch_installed(&home()?, id)
}
fn launch_installed(home: &Path, id: u32) -> Result<()> {
let apps = discover(home);
ensure!(
apps.iter().any(|a| a.id == id),
"Steam app is no longer installed"
);
let output = crate::process::tool("steam")
.arg(format!("steam://rungameid/{id}"))
.stdin(Stdio::null())
.output()
.context("Cannot contact Steam")?;
ensure!(
output.status.success(),
"Steam launch failed: {}",
String::from_utf8_lossy(&output.stderr)
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nested_escaped_and_invalid() {
let t = tokens("\"libraryfolders\" { \"0\" { \"path\" \"/a\\\\b\" } }").unwrap();
let v = object(&t, &mut 0, 0, false).unwrap();
assert!(root(&v, "libraryfolders").is_some());
assert!(tokens("\"oops").is_err());
assert!(object(&tokens("a { b c").unwrap(), &mut 0, 0, false).is_err());
}
#[test]
fn artwork_prefers_nested_cover_then_logo() {
let dir = tempfile::tempdir().unwrap();
let steam = dir.path().join(".local/share/Steam");
fs::create_dir_all(steam.join("steamapps")).unwrap();
fs::write(
steam.join("steamapps/appmanifest_1.acf"),
"AppState { appid 1 name Game StateFlags 4 }",
)
.unwrap();
let cache = steam.join("appcache/librarycache/1");
fs::create_dir_all(cache.join("content-hash")).unwrap();
let png = include_bytes!("../assets/branding/icons/32.png");
fs::write(cache.join("logo.png"), png).unwrap();
let cover = cache.join("content-hash/library_capsule.jpg");
fs::write(&cover, png).unwrap();
let app = discover(dir.path()).remove(0);
assert_eq!(app.icon_fit, "cover");
assert!(app.icon.unwrap().starts_with("data:image/png;base64,"));
fs::write(&cover, b"corrupt").unwrap();
assert_eq!(discover(dir.path()).remove(0).icon_fit, "contain");
}
#[test]
fn multiple_libraries_and_tools() {
let dir = tempfile::tempdir().unwrap();
let steam = dir.path().join(".local/share/Steam/steamapps");
fs::create_dir_all(&steam).unwrap();
fs::write(
steam.join("appmanifest_1.acf"),
"AppState { appid 1 name Game StateFlags 4 }",
)
.unwrap();
fs::write(
steam.join("appmanifest_2.acf"),
"AppState { appid 2 name Proton StateFlags 4 }",
)
.unwrap();
fs::write(steam.join("appmanifest_3.acf"), "broken {").unwrap();
let second = dir.path().join("second-library");
fs::create_dir_all(second.join("steamapps")).unwrap();
fs::write(
second.join("steamapps/appmanifest_4.acf"),
"AppState { appid 4 name AnotherGame StateFlags 4 }",
)
.unwrap();
fs::write(
second.join("steamapps/appmanifest_1.acf"),
"AppState { appid 1 name Duplicate StateFlags 4 }",
)
.unwrap();
fs::write(steam.join("libraryfolders.vdf"), format!("libraryfolders {{ 0 {{ path \"{}\" }} 1 {{ path \"{}\" }} 2 {{ path \"/missing-library\" }} }}", steam.parent().unwrap().display(), second.display())).unwrap();
assert_eq!(
discover(dir.path())
.iter()
.map(|a| a.id)
.collect::<Vec<_>>(),
vec![1, 4]
);
}
}
#[cfg(test)]
mod launch_tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
#[test]
fn only_installed_ids_reach_mock_steam() {
let dir = tempfile::tempdir().unwrap();
let library = dir.path().join(".local/share/Steam/steamapps");
fs::create_dir_all(&library).unwrap();
fs::write(
library.join("appmanifest_42.acf"),
"AppState { appid 42 name Test StateFlags 4 }",
)
.unwrap();
let tools = dir.path().join("tools");
fs::create_dir(&tools).unwrap();
let log = dir.path().join("args");
fs::write(
tools.join("steam"),
format!("#!/bin/sh\nprintf '%s' \"$1\" > '{}'\n", log.display()),
)
.unwrap();
fs::set_permissions(tools.join("steam"), fs::Permissions::from_mode(0o755)).unwrap();
crate::process::TEST_TOOLS.with(|p| *p.borrow_mut() = Some(tools));
assert!(launch_installed(dir.path(), 999).is_err());
assert!(!log.exists());
launch_installed(dir.path(), 42).unwrap();
assert_eq!(fs::read_to_string(log).unwrap(), "steam://rungameid/42");
crate::process::TEST_TOOLS.with(|p| *p.borrow_mut() = None);
}
}
+320 -6
View File
@@ -299,6 +299,7 @@ fn notification_limits_and_sources() {
image: None,
actions: vec![],
duration_ms: 8000,
inbox: false,
};
n.validate().unwrap();
let mut invalid = n.clone();
@@ -307,6 +308,8 @@ fn notification_limits_and_sources() {
id: i.to_string(),
label: "x".into(),
icon: "x".into(),
close_on_click: true,
remove_from_inbox_on_click: true,
})
.collect();
assert!(invalid.validate().is_err());
@@ -811,6 +814,36 @@ fn apply_prepared(core: &mut Service, prepared: crate::planner::Prepared) -> any
core.handle("install.batch",json!({"approve":true,"approveRunAs":true,"plan":prepared.plan,"packages":prepared.packages.iter().map(|(bytes,source)|{let mut request=bytes.request();request["source"]=json!(source);request}).collect::<Vec<_>>()}))
}
#[test]
fn batch_install_in_safe_mode_preserves_packages_without_starting_plugins() {
let tmp = tempfile::tempdir().unwrap();
let _tools = fake_backend_tools(tmp.path());
let mut core = accepted_service(&tmp.path().join("state"), 1000).unwrap();
core.handle("safeMode", json!({"enabled":true})).unwrap();
for version in ["1.0.0", "1.1.0"] {
let bytes = relation_package(
tmp.path(),
"test.safe",
version,
json!({"backend":{"entry":"fail.sh","autostart":true}}),
);
let prepared = crate::planner::prepare(&core.db, bytes, None, Default::default()).unwrap();
apply_prepared(&mut core, prepared).unwrap();
assert_eq!(core.db.plugins["test.safe"].manifest.version, version);
assert!(core.db.plugins["test.safe"].enabled);
assert!(core.db.safe_mode);
assert!(!core.root.join("install-transaction.json").exists());
let status = core.handle("status", json!({})).unwrap();
assert_eq!(status["runtime"]["test.safe"]["phase"], "installed");
let reloaded = Service::load(&core.root, core.manager).unwrap();
assert!(reloaded.db.safe_mode);
assert_eq!(reloaded.db.plugins["test.safe"].manifest.version, version);
}
core.handle("safeMode", json!({"enabled":false})).unwrap();
let lifecycle = fs::read_to_string(core.root.join("logs/test.safe.lifecycle.log")).unwrap();
assert!(lifecycle.contains("\"phase\":\"starting\""));
core.shutdown();
}
#[test]
fn dependency_install_conflicts_reverse_constraints_and_removal() {
let tmp = tempfile::tempdir().unwrap();
let mut core = accepted_service(&tmp.path().join("state"), unsafe { libc::geteuid() }).unwrap();
@@ -1079,17 +1112,21 @@ fn batch_hook_failure_and_interrupted_transaction_restore_state() {
disable: vec![],
affected: vec!["test.first".into(), "test.bad".into()],
};
assert!(apply_prepared(
let error = apply_prepared(
&mut core,
crate::planner::Prepared {
plan,
packages: vec![
(package::Staged::from_bytes(&first).unwrap(), None),
(package::Staged::from_bytes(&bad).unwrap(), None)
]
}
(package::Staged::from_bytes(&bad).unwrap(), None),
],
},
)
.is_err());
.unwrap_err();
let message = format!("{error:#}");
assert!(message.contains("批量安装失败,已恢复原版本和启用状态"));
assert!(message.contains("安装插件 test.bad 失败"));
assert!(message.contains("Lifecycle"));
assert_eq!(
serde_json::to_value(&core.db).unwrap(),
serde_json::to_value(&original).unwrap()
@@ -1571,13 +1608,14 @@ fn manager_uninstall_disables_all_plugins_and_removes_packages_before_body() {
.unwrap();
assert_eq!(result["uninstalled"].as_array().unwrap().len(), 2);
assert!(core.db.plugins.is_empty());
assert!(core.db.safe_mode);
assert!(!core.db.safe_mode);
assert!(!root.path().join("plugins/test.first").exists());
assert!(!root.path().join("plugins/test.second").exists());
assert!(root.path().join("data/test.first/saved").exists());
assert!(root.path().join("manager-marker").exists());
let reloaded = Service::load(root.path(), 1000).unwrap();
assert!(reloaded.db.plugins.is_empty());
assert!(!reloaded.db.safe_mode);
core.handle("system.uninstall.prepare", json!({"approve":true}))
.unwrap();
}
@@ -1609,6 +1647,7 @@ fn manager_uninstall_failure_keeps_plugin_and_persists_disabling() {
assert!(root.path().join("plugins/test.retained").exists());
let reloaded = Service::load(root.path(), 1000).unwrap();
assert!(!reloaded.db.plugins["test.retained"].enabled);
assert!(reloaded.db.safe_mode);
}
#[test]
@@ -1745,3 +1784,278 @@ for line in sys.stdin:
assert_eq!(read(&mut core, "test.legacy"), json!([]));
core.shutdown();
}
#[test]
fn launcher_manifest_validation_and_old_package_compatibility() {
let root = tempfile::tempdir().unwrap();
let bytes = fixture(root.path(), "launch.test", "1.0.0", 1, None);
let old = package::verify(&bytes).unwrap().manifest;
assert!(
old.engines.is_none() && old.ui.launch.is_empty() && old.ui.launcher_actions.is_empty()
);
let mut value = serde_json::to_value(&old).unwrap();
value["engines"] = json!({"framely":">=0.4.3-preview.2 <0.5.0"});
value["ui"]["launch"] = json!({"launcher":{"type":"quickPage"}});
let m: Manifest = serde_json::from_value(value.clone()).unwrap();
m.validate().unwrap();
value["ui"]["launch"]["manager"] = json!({"type":"window","window":"missing"});
assert!(serde_json::from_value::<Manifest>(value.clone())
.unwrap()
.validate()
.is_err());
value["ui"]["launch"] = json!({"launcher":{"type":"quickPage"}});
value["engines"] = json!({"framely":"*"});
assert!(serde_json::from_value::<Manifest>(value)
.unwrap()
.validate()
.is_err());
}
#[test]
fn engines_ranges_and_incompatible_install_are_non_mutating() {
let e = |r: &str| Engines {
framely: Some(r.into()),
};
assert!(e(">=0.4.3 <0.5.0").matches("0.4.4+build"));
assert!(!e(">=0.4.3 <0.5.0").matches("0.4.4-preview.1"));
assert!(e(">=0.4.3-preview.2 <0.5.0").matches("0.4.3-preview.3"));
assert!(e(">=0.4.3-preview.2 <0.5.0").matches("0.4.3"));
assert!(!e(">=0.4.3-preview.2 <0.5.0").matches("0.4.3-preview.1"));
assert!(e("=0.4.3").matches("0.4.3+abc"));
assert!(e("^0.4.3").matches("0.4.9"));
assert!(!e("^0.4.3").matches("0.5.0"));
assert!(e("~0.4.3").matches("0.4.4"));
assert!(e("0.4.*").matches("0.4.4"));
assert!(e("nonsense").validate().is_err());
assert!(e("0.4.3 || 0.5.0").validate().is_err());
let root = tempfile::tempdir().unwrap();
let mut core =
accepted_service(&root.path().join("state"), unsafe { libc::geteuid() }).unwrap();
install(
&mut core,
&fixture(root.path(), "launch.compat", "1.0.0", 1, None),
json!({}),
)
.unwrap();
let old = serde_json::to_value(&core.db).unwrap();
let future = rewrite(
&fixture(root.path(), "launch.compat", "2.0.0", 2, None),
|name, data| {
if name == "manifest.json" {
let mut m: Value = serde_json::from_slice(data).unwrap();
m["engines"] = json!({"framely":">=999.0.0"});
*data = serde_json::to_vec(&m).unwrap();
}
},
);
assert!(install(&mut core, &future, json!({}))
.unwrap_err()
.to_string()
.contains("requires Framely"));
assert_eq!(serde_json::to_value(&core.db).unwrap(), old);
assert!(!root
.path()
.join("state/plugins/launch.compat/versions/2.0.0")
.exists());
core.db
.plugins
.get_mut("launch.compat")
.unwrap()
.manifest
.engines = Some(e(">=999.0.0"));
assert!(core
.handle("plugin.open", json!({"plugin":"launch.compat"}))
.is_err());
}
#[test]
fn launcher_dispatch_preserves_old_open_semantics_and_window_context() {
let root = tempfile::tempdir().unwrap();
let mut core =
accepted_service(&root.path().join("state"), unsafe { libc::geteuid() }).unwrap();
install(
&mut core,
&fixture(root.path(), "launch.routes", "1.0.0", 1, None),
json!({}),
)
.unwrap();
core.events.lock().unwrap().clear();
core.handle("plugin.open", json!({"plugin":"launch.routes"}))
.unwrap();
assert!(!core
.handle("events", json!({}))
.unwrap()
.as_array()
.unwrap()
.iter()
.any(|v| v["kind"] == "menu.open"));
for source in ["launcher", "quickPanel", "manager"] {
core.handle(
"plugin.launch",
json!({"plugin":"launch.routes","source":source}),
)
.unwrap();
let events = core.handle("events", json!({})).unwrap();
assert!(events
.as_array()
.unwrap()
.iter()
.any(|v| v["kind"] == "menu.open" && v["context"]["source"] == source));
assert_eq!(
core.handle(
"plugin.launch.context",
json!({"plugin":"launch.routes","entry":"quick"})
)
.unwrap()["source"],
source
);
}
assert!(core
.handle(
"plugin.launch",
json!({"plugin":"launch.routes","source":"unknown"})
)
.is_err());
let plugin = core.db.plugins.get_mut("launch.routes").unwrap();
plugin.manifest.ui.windows.insert(
"main".into(),
serde_json::from_value(json!({"entry":"page.js","title":"Main"})).unwrap(),
);
plugin.manifest.ui.launch.insert(
"launcher".into(),
LaunchTarget::Window {
window: "main".into(),
},
);
plugin.manifest.ui.launcher_actions = serde_json::from_value(json!([
{"id":"window","label":"Open","target":{"type":"window","window":"main"}},
{"id":"front","label":"Front","target":{"type":"frontend","entry":"page.js"}}
]))
.unwrap();
core.handle(
"plugin.launch",
json!({"plugin":"launch.routes","source":"launcher"}),
)
.unwrap();
assert_eq!(
core.handle(
"plugin.launch.context",
json!({"plugin":"launch.routes","entry":"main"})
)
.unwrap()["source"],
"launcher"
);
core.handle(
"plugin.launcher.action",
json!({"plugin":"launch.routes","action":"window"}),
)
.unwrap();
assert_eq!(
core.handle(
"plugin.launch.context",
json!({"plugin":"launch.routes","entry":"main"})
)
.unwrap()["actionId"],
"window"
);
let frontend = core
.handle(
"plugin.launcher.action",
json!({"plugin":"launch.routes","action":"front"}),
)
.unwrap();
assert_eq!(frontend["frontend"], "page.js");
assert_eq!(frontend["context"]["actionId"], "front");
assert!(core
.handle(
"plugin.launcher.action",
json!({"plugin":"launch.routes","action":"unknown"})
)
.is_err());
core.handle(
"launcher.settings.save",
json!({"primaryTrigger":true,"menuAutoClose":false,"menuTimeoutSeconds":25}),
)
.unwrap();
let loaded = Service::load(&root.path().join("state"), unsafe { libc::geteuid() }).unwrap();
assert!(loaded.db.launcher.primary_trigger);
assert!(!loaded.db.launcher.menu_auto_close);
assert_eq!(loaded.db.launcher.menu_timeout_seconds, 25);
let order = vec![
"framely",
"plugin:launch.routes",
"desktop:terminal.desktop",
"lepton:test/com.example.app",
];
core.handle("launcher.order.save", json!({"order":order}))
.unwrap();
for invalid in [
json!(["framely", "framely"]),
json!(["unknown:app"]),
json!(["plugin:"]),
json!(["desktop:bad\nentry"]),
] {
assert!(core
.handle("launcher.order.save", json!({"order":invalid}))
.is_err());
}
let loaded = Service::load(&root.path().join("state"), unsafe { libc::geteuid() }).unwrap();
assert_eq!(loaded.db.launcher_order, order);
}
#[test]
fn launcher_categories_migrate_validate_and_favorites_survive_reload() {
let root = tempfile::tempdir().unwrap();
let state = root.path().join("state");
let mut core = accepted_service(&state, unsafe { libc::geteuid() }).unwrap();
assert_eq!(
core.db.launcher.all_categories,
vec!["plugin", "steam", "lepton", "desktop"]
);
core.handle("launcher.settings.save",json!({"primaryTrigger":true,"menuAutoClose":true,"menuTimeoutSeconds":10,"allCategories":[]})).unwrap();
for key in [
"framely",
"desktop:terminal.desktop",
"lepton:default/app",
"steam:42",
] {
core.handle("launcher.favorite", json!({"key":key,"favorite":true}))
.unwrap();
}
for invalid in [
json!(["all"]),
json!(["plugin", "plugin"]),
json!(["favorites"]),
] {
assert!(core.handle("launcher.settings.save",json!({"primaryTrigger":true,"menuAutoClose":true,"menuTimeoutSeconds":10,"allCategories":invalid})).is_err());
}
for invalid in [
"",
"plugin:missing",
"steam:0",
"steam:-1",
"steam:4294967296",
"desktop:",
"invalid:app",
"lepton:\napp",
] {
assert!(core
.handle("launcher.favorite", json!({"key":invalid,"favorite":true}))
.is_err());
}
let mut loaded = Service::load(&state, unsafe { libc::geteuid() }).unwrap();
assert!(loaded.db.launcher.all_categories.is_empty());
assert!(loaded.db.launcher.primary_trigger);
assert_eq!(loaded.db.launcher_favorites.len(), 3);
assert!(loaded.db.steam_favorites.contains(&42));
loaded
.handle(
"launcher.favorite",
json!({"key":"framely","favorite":false}),
)
.unwrap();
assert!(!loaded.db.launcher_favorites.contains("framely"));
loaded
.handle("launcher.settings.save", json!({"menuTimeoutSeconds":25}))
.unwrap();
assert_eq!(loaded.db.launcher.all_categories.len(), 4);
}
+1 -1
View File
@@ -150,7 +150,7 @@ struct GitHubRelease {
draft: bool,
assets: Vec<GitHubAsset>,
}
fn descriptor_version(version: &str) -> Result<semver::Version> {
pub(crate) fn descriptor_version(version: &str) -> Result<semver::Version> {
// Runtime VERSION appends a twelve-digit content hash to the Cargo version.
let version = version
.rsplit_once('-')
+4 -1
View File
@@ -33,7 +33,10 @@ impl Tracker {
ensure!(
views.len() <= 64
&& views.keys().all(|k| k.len() <= 256
&& (k == "menu" || k == "framely.manager" || k.starts_with("framely.window."))),
&& (k == "menu"
|| k == "launcher"
|| k == "framely.manager"
|| k.starts_with("framely.window."))),
"Invalid native visibility views"
);
self.seen = Some(now);
+4
View File
@@ -33,3 +33,7 @@ To edit this template inside the Framely repository, run `npm install`, `npm run
The template and bundled SDK use `AGPL-3.0-only`. See Framely's `docs/developer-guide/README.md` for the full development and publishing workflow. The template lifecycle callbacks preserve user data.
For community GitHub registration, source may omit `downloadUrl`; default assets use `<id>-<version>.framely`. Release packages need a temporary Manifest with the derived URL. See Framely's `docs/developer-guide/publishing.md` for commands, Release digests, custom URLs and database window-dimension validation. The direct packaging command above is for core testing and does not establish community registration acceptance.
Launcher support requires Framely 0.4.3-preview.2+. `actions.ts` is built separately; edit `engines.framely`, `ui.launch` and `ui.launcherActions` in the manifest. See the bilingual launcher developer guide.
启动台功能要求 Framely 0.4.3-preview.2 或更新版本。`actions.ts` 单独构建;在清单中调整 `engines.framely`、`ui.launch` 和 `ui.launcherActions`,详见中英双语启动台开发文档。
+12
View File
@@ -0,0 +1,12 @@
import {registerLauncherActions, framely} from '@framely/sdk';
// This bundle runs in a sandbox without mounting QuickPage.
// 此入口运行在沙箱内,不会挂载 QuickPage。
registerLauncherActions({
notify: async context => {
await framely.notifications.send({
id: 'launcher-action', title: 'Launcher action / 启动台操作',
body: `Opened from ${context.source} / 来自 ${context.source}`, inbox: true,
});
},
});
+63 -10
View File
@@ -7,23 +7,76 @@
"author": "Your name",
"description": "一个可保存文字、打开窗口和发送通知的插件。",
"details": "使用 React 编写界面,使用 Python 后端保存插件数据。",
"tags": ["工具"],
"tags": [
"工具"
],
"changelog": "首次发布。",
"backend": {
"entry": "backend.py", "runAs": "steamos", "autostart": false,
"restart": "on-failure", "restartLimit": 3
"entry": "backend.py",
"runAs": "steamos",
"autostart": false,
"restart": "on-failure",
"restartLimit": 3
},
"lifecycle": {
"onInstall": {"entry": "backend.py"},
"onUpdate": {"entry": "backend.py"},
"onStart": true, "onStop": true,
"onUninstall": {"entry": "backend.py"},
"onInstall": {
"entry": "backend.py"
},
"onUpdate": {
"entry": "backend.py"
},
"onStart": true,
"onStop": true,
"onUninstall": {
"entry": "backend.py"
},
"timeoutSeconds": 10
},
"ui": {
"quickPage": "page.js",
"windows": {"main": {"entry": "page.js", "title": "我的插件", "dockIcon": true}}
"windows": {
"main": {
"entry": "page.js",
"title": "我的插件",
"dockIcon": true
}
},
"launch": {
"launcher": {
"type": "quickPage"
},
"quickPanel": {
"type": "quickPage"
},
"manager": {
"type": "quickPage"
}
},
"launcherActions": [
{
"id": "open-window",
"label": "Open window",
"target": {
"type": "window",
"window": "main"
}
},
{
"id": "notify",
"label": "Send a notification",
"target": {
"type": "frontend",
"entry": "actions.js"
}
}
]
},
"dependencies": {}, "optionalDependencies": {}, "conflicts": {},
"exclusiveResources": [], "files": {}
"dependencies": {},
"optionalDependencies": {},
"conflicts": {},
"exclusiveResources": [],
"files": {},
"engines": {
"framely": ">=0.4.3-preview.2 <0.5.0"
}
}
+11 -5
View File
@@ -1,3 +1,5 @@
#include "../native/paint_buffer.h"
#include "../native/launcher_pointer.h"
// Integration test only: render the real manager and exercise its iframe bridge.
#include "include/capi/cef_app_capi.h"
#include "include/capi/cef_client_capi.h"
@@ -23,7 +25,9 @@ static Handler<cef_life_span_handler_t> life;
static std::vector<unsigned char> pixels;static int pixel_width=0,pixel_height=0;
static void snapshot(const std::string& name){const char* dir=std::getenv("FRAMELY_PREVIEW_DIR");if(!dir||pixels.empty())return;std::ofstream out(std::string(dir)+"/"+name+".ppm",std::ios::binary);out<<"P6\n"<<pixel_width<<" "<<pixel_height<<"\n255\n";for(size_t i=0;i<pixels.size();i+=4){unsigned char rgb[]={pixels[i+2],pixels[i+1],pixels[i]};out.write(reinterpret_cast<char*>(rgb),3);}}
static bool install_review_mode=std::getenv("FRAMELY_INSTALL_REVIEW_TEST")!=nullptr;
static bool launcher_mode=std::getenv("FRAMELY_LAUNCHER_TEST")!=nullptr;
static bool notification_mode=std::getenv("FRAMELY_NOTIFICATION_TEST")!=nullptr;
static LauncherPointer test_pointer;static bool press_pending=false;static int press_dx=0,press_dy=0,press_duration=0;
static bool ready=false,passed=false,failed=false,closed=false;static int paints=0;static bool scaled_paint=false,dpi_click=false,rounded_paint=false;
static void str(cef_string_t& s,const std::string& v){cef_string_utf8_to_utf16(v.data(),v.size(),&s);}
static std::string text(const cef_string_t* s){cef_string_utf8_t o{};cef_string_utf16_to_utf8(s->str,s->length,&o);std::string r(o.str,o.length);cef_string_utf8_clear(&o);return r;}
@@ -32,11 +36,13 @@ int main(int argc,char** argv){
cef_main_args_t args{argc,argv};if(std::strcmp(cef_api_hash(CEF_API_VERSION,0),CEF_API_HASH_PLATFORM))return 2;int child=cef_execute_process(&args,nullptr,nullptr);if(child>=0)return child;if(url.empty()||runtime.empty()||cef.empty())return 2;
cef_settings_t settings{};settings.size=sizeof(settings);settings.windowless_rendering_enabled=1;str(settings.root_cache_path,runtime+"/cache");str(settings.log_file,runtime+"/cef.log");str(settings.resources_dir_path,cef+"/Resources");str(settings.locales_dir_path,cef+"/Resources/locales");
if(!cef_initialize(&args,&settings,nullptr,nullptr))return 3;
render.api.get_view_rect=[](cef_render_handler_t*,cef_browser_t*,cef_rect_t* r){*r=std::getenv("FRAMELY_STORE_TEST")?cef_rect_t{0,0,1440,810}:cef_rect_t{0,0,600,notification_mode?360:840};};render.api.get_screen_info=[](cef_render_handler_t*,cef_browser_t*,cef_screen_info_t* info){return render_screen_info(info,std::getenv("FRAMELY_STORE_TEST")?1440:600,std::getenv("FRAMELY_STORE_TEST")?810:(notification_mode?360:840),std::getenv("FRAMELY_STORE_TEST")?4:2);};render.api.on_paint=[](cef_render_handler_t*,cef_browser_t*,cef_paint_element_type_t,size_t,const cef_rect_t*,const void* data,int w,int h){++paints;if(w==(std::getenv("FRAMELY_STORE_TEST")?5760:1200)&&h==(std::getenv("FRAMELY_STORE_TEST")?3240:(notification_mode?720:1680)))scaled_paint=true;pixel_width=w;pixel_height=h;pixels.assign(static_cast<const unsigned char*>(data),static_cast<const unsigned char*>(data)+w*h*4);if(!notification_mode&&w>0&&h>0){auto alpha=[&](int x,int y){return pixels[(y*w+x)*4+3];};if(alpha(0,0)==0&&alpha(w-1,0)==0&&alpha(0,h-1)==0&&alpha(w-1,h-1)==0&&alpha(w/2,40)>240)rounded_paint=true;}};
display.api.on_console_message=[](cef_display_handler_t*,cef_browser_t* b,cef_log_severity_t,const cef_string_t* m,const cef_string_t*,int){auto s=text(m);std::cout<<s<<"\n";if(s.rfind("FRAMELY_NATIVE_KEYBOARD_",0)==0){auto* frame=b->get_focused_frame(b);auto command=s.substr(24);if(command=="TEXT")keyboard_edit(frame,"汉😃");else if(command=="BACKSPACE")keyboard_edit(frame,"\b");else if(command=="ENTER")keyboard_edit(frame,"\n");else if(command=="X")keyboard_edit(frame,"x");else if(command=="Y")keyboard_edit(frame,"y");else if(command=="LEFT")keyboard_edit(frame,"\x1b[D");else if(command=="RIGHT")keyboard_edit(frame,"\x1b[C");frame->base.release(&frame->base);}if(s=="FRAMELY_DPI_CLICK_REQUEST"){auto* host=b->get_host(b);cef_mouse_event_t mouse{};mouse.x=50;mouse.y=45;host->set_focus(host,1);host->send_mouse_move_event(host,&mouse,0);host->send_mouse_click_event(host,&mouse,MBT_LEFT,0,1);host->send_mouse_click_event(host,&mouse,MBT_LEFT,1,1);host->base.release(&host->base);}if(s=="FRAMELY_DPI_CLICK_PASS")dpi_click=true;if(s.rfind("FRAMELY_PREVIEW_INSTALL_",0)==0)snapshot(s.substr(16));if(s=="FRAMELY_PREVIEW_STORE")snapshot("store");if(s=="FRAMELY_PREVIEW_FAVORITES")snapshot("favorites");if(s=="FRAMELY_PREVIEW_INSTALLED")snapshot("installed");if(s=="FRAMELY_PREVIEW_SETTINGS")snapshot("settings");if(s=="FRAMELY_VIEW_READY")ready=true;if(s=="FRAMELY_BRIDGE_PASS")passed=true;if(s.rfind("FRAMELY_BRIDGE_FAIL",0)==0)failed=true;return 1;};life.api.on_before_close=[](cef_life_span_handler_t*,cef_browser_t*){closed=true;};
render.api.get_view_rect=[](cef_render_handler_t*,cef_browser_t*,cef_rect_t* r){*r=launcher_mode?cef_rect_t{0,0,1200,800}:std::getenv("FRAMELY_STORE_TEST")?cef_rect_t{0,0,1440,810}:cef_rect_t{0,0,600,notification_mode?360:840};};render.api.get_screen_info=[](cef_render_handler_t*,cef_browser_t*,cef_screen_info_t* info){if(launcher_mode)return render_screen_info(info,1200,800,4);return render_screen_info(info,std::getenv("FRAMELY_STORE_TEST")?1440:600,std::getenv("FRAMELY_STORE_TEST")?810:(notification_mode?360:840),std::getenv("FRAMELY_STORE_TEST")?4:2);};render.api.on_paint=[](cef_render_handler_t*,cef_browser_t*,cef_paint_element_type_t type,size_t dirty_count,const cef_rect_t* dirty,const void* data,int w,int h){if(type!=PET_VIEW)return;++paints;if(w==(launcher_mode?4800:std::getenv("FRAMELY_STORE_TEST")?5760:1200)&&h==(launcher_mode?3200:std::getenv("FRAMELY_STORE_TEST")?3240:(notification_mode?720:1680)))scaled_paint=true;pixel_width=w;pixel_height=h;merge_paint(pixels,data,w,h,dirty_count,dirty);if(!notification_mode&&w>0&&h>0){auto alpha=[&](int x,int y){return pixels[(y*w+x)*4+3];};if(alpha(0,0)==0&&alpha(w-1,0)==0&&alpha(0,h-1)==0&&alpha(w-1,h-1)==0&&alpha(w/2,40)>240)rounded_paint=true;}};
display.api.on_console_message=[](cef_display_handler_t*,cef_browser_t* b,cef_log_severity_t,const cef_string_t* m,const cef_string_t*,int){auto s=text(m);std::cout<<s<<"\n";if(s.rfind("FRAMELY_NATIVE_KEYBOARD_",0)==0){auto* frame=b->get_focused_frame(b);auto command=s.substr(24);if(command=="TEXT")keyboard_edit(frame,"汉😃");else if(command=="BACKSPACE")keyboard_edit(frame,"\b");else if(command=="ENTER")keyboard_edit(frame,"\n");else if(command=="X")keyboard_edit(frame,"x");else if(command=="Y")keyboard_edit(frame,"y");else if(command=="LEFT")keyboard_edit(frame,"\x1b[D");else if(command=="RIGHT")keyboard_edit(frame,"\x1b[C");frame->base.release(&frame->base);}if(s=="FRAMELY_LAUNCHER_CANCEL_PRESS"){auto* pointer_host=b->get_host(b);cef_mouse_event_t outside{};outside.modifiers=EVENTFLAG_LEFT_MOUSE_BUTTON;pointer_host->send_mouse_move_event(pointer_host,&outside,0);outside.modifiers=0;pointer_host->send_mouse_click_event(pointer_host,&outside,MBT_LEFT,1,1);test_pointer.clear();press_pending=false;auto* frame=b->get_main_frame(b);cef_string_t code{},source{};str(code,"window.dispatchEvent(new Event('framely.launcher.cancelInput'))");frame->execute_java_script(frame,&code,&source,1);cef_string_utf16_clear(&code);frame->base.release(&frame->base);pointer_host->base.release(&pointer_host->base);}if(s.rfind("FRAMELY_LAUNCHER_DRAG_",0)==0){int x=0,y=0;if(press_pending&&std::sscanf(s.c_str(),"FRAMELY_LAUNCHER_DRAG_%d_%d",&x,&y)==2){press_dx=x-test_pointer.x;press_dy=y-test_pointer.y;}}if(s.rfind("FRAMELY_LAUNCHER_PRESS_",0)==0){int x=0,y=0;if(std::sscanf(s.c_str(),"FRAMELY_LAUNCHER_PRESS_%d_%d_%d_%d_%d",&x,&y,&press_dx,&press_dy,&press_duration)==5){auto* pointer_host=b->get_host(b);test_pointer.begin(x,y,std::chrono::steady_clock::now());press_pending=true;cef_mouse_event_t mouse{};mouse.x=x;mouse.y=y;pointer_host->set_focus(pointer_host,1);pointer_host->send_mouse_move_event(pointer_host,&mouse,0);mouse.modifiers=EVENTFLAG_LEFT_MOUSE_BUTTON;pointer_host->send_mouse_click_event(pointer_host,&mouse,MBT_LEFT,0,1);pointer_host->base.release(&pointer_host->base);}}if(s.rfind("FRAMELY_LAUNCHER_HOVER_",0)==0){int x=0,y=0;if(std::sscanf(s.c_str(),"FRAMELY_LAUNCHER_HOVER_%d_%d",&x,&y)==2){auto* hover_host=b->get_host(b);cef_mouse_event_t mouse{};mouse.x=x;mouse.y=y;hover_host->send_mouse_move_event(hover_host,&mouse,0);hover_host->base.release(&hover_host->base);}}if(s.rfind("FRAMELY_LAUNCHER_REGION_",0)==0){int x=0,y=0,w=0,h=0;if(std::sscanf(s.c_str(),"FRAMELY_LAUNCHER_REGION_%d_%d_%d_%d",&x,&y,&w,&h)==4){int ink=0;for(int py=std::max(0,y*4);py<std::min(pixel_height,(y+h)*4);py++)for(int px=std::max(0,x*4);px<std::min(pixel_width,(x+w)*4);px++)if(pixels[(size_t(py)*pixel_width+px)*4+3]>128)ink++;if(ink<30){failed=true;std::cerr<<"FRAMELY_BRIDGE_FAIL missing painted control "<<x<<","<<y<<"\n";}}}if(s.rfind("FRAMELY_LAUNCHER_INK_",0)==0){int x=0,y=0,w=0,h=0;if(std::sscanf(s.c_str(),"FRAMELY_LAUNCHER_INK_%d_%d_%d_%d",&x,&y,&w,&h)==4){int ink=0;for(int py=std::max(0,y*4);py<std::min(pixel_height,(y+h)*4);py++)for(int px=std::max(0,x*4);px<std::min(pixel_width,(x+w)*4);px++){size_t i=(size_t(py)*pixel_width+px)*4;if(pixels[i+3]>128&&pixels[i]>180&&pixels[i+1]>180&&pixels[i+2]>180)ink++;}if(ink<30){failed=true;std::cerr<<"FRAMELY_BRIDGE_FAIL missing painted label "<<x<<","<<y<<" ink="<<ink<<"\n";}}}
if(s=="FRAMELY_DPI_CLICK_REQUEST"){auto* host=b->get_host(b);cef_mouse_event_t mouse{};mouse.x=50;mouse.y=45;host->set_focus(host,1);host->send_mouse_move_event(host,&mouse,0);host->send_mouse_click_event(host,&mouse,MBT_LEFT,0,1);host->send_mouse_click_event(host,&mouse,MBT_LEFT,1,1);host->base.release(&host->base);}if(s=="FRAMELY_DPI_CLICK_PASS")dpi_click=true;if(s.rfind("FRAMELY_PREVIEW_INSTALL_",0)==0)snapshot(s.substr(16));if(s=="FRAMELY_PREVIEW_STORE")snapshot("store");if(s=="FRAMELY_PREVIEW_FAVORITES")snapshot("favorites");if(s=="FRAMELY_PREVIEW_INSTALLED")snapshot("installed");if(s=="FRAMELY_PREVIEW_SETTINGS")snapshot("settings");if(s=="FRAMELY_VIEW_READY")ready=true;if(s=="FRAMELY_BRIDGE_PASS")passed=true;if(s.rfind("FRAMELY_BRIDGE_FAIL",0)==0)failed=true;return 1;};life.api.on_before_close=[](cef_life_span_handler_t*,cef_browser_t*){closed=true;};
client.api.get_render_handler=[](cef_client_t*){return render.acquire();};client.api.get_display_handler=[](cef_client_t*){return display.acquire();};client.api.get_life_span_handler=[](cef_client_t*){return life.acquire();};
cef_window_info_t win{};win.size=sizeof(win);win.windowless_rendering_enabled=1;cef_browser_settings_t bs{};bs.size=sizeof(bs);bs.windowless_frame_rate=30;cef_string_t uri{};str(uri,url);auto* browser=cef_browser_host_create_browser_sync(&win,&client.api,&uri,&bs,nullptr,nullptr);cef_string_utf16_clear(&uri);if(!browser)return 4;auto* host=browser->get_host(browser);
auto end=std::chrono::steady_clock::now()+std::chrono::seconds(20);bool injected=false;
while(std::chrono::steady_clock::now()<end&&!passed&&!failed){cef_do_message_loop_work();if(ready&&!injected){auto* f=browser->get_main_frame(browser);cef_string_t code{},source{};str(code,install_review_mode?"window.runInstallReviewChecks()":notification_mode?R"JS((async()=>{const wait=ms=>new Promise(r=>setTimeout(r,ms));for(let i=0;i<100&&!document.querySelector('.toast');i++)await wait(30);if(innerWidth!==600||innerHeight!==360||devicePixelRatio!==2)throw Error('notification dimensions');const toast=document.querySelector('.toast');if(!toast?.textContent.includes('Toast integration'))throw Error('notification missing');if(toast.getBoundingClientRect().height>240)throw Error('notification too large');if(toast.querySelectorAll('.toast-actions button').length!==3)throw Error('actions missing');toast.querySelector('[aria-label="确认"]').click();await wait(150);document.querySelector('[aria-label="关闭通知"]').click();await wait(150);const status=await fetch('/api',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({method:'status',params:{}})}).then(r=>r.json());if(status.result.notifications.length)throw Error('notification not withdrawn');console.log('FRAMELY_BRIDGE_PASS');})().catch(e=>console.error('FRAMELY_BRIDGE_FAIL '+e)))JS":std::getenv("FRAMELY_REMOTE_TEST")?R"JS((async()=>{const wait=ms=>new Promise(r=>setTimeout(r,ms));await wait(300);const button=document.createElement('button');button.style.cssText='position:fixed;left:20px;top:20px;width:100px;height:50px;z-index:9999';button.onclick=()=>console.log('FRAMELY_DPI_CLICK_PASS');document.body.append(button);console.log('FRAMELY_DPI_CLICK_REQUEST');await wait(200);button.remove();for(let i=0;i<100;i++){const plugin=document.querySelector('.plugin-main');if(plugin){plugin.click();return;}await wait(50);}throw Error('remote plugin list timeout');})().catch(e=>console.error('FRAMELY_BRIDGE_FAIL '+e)))JS":std::getenv("FRAMELY_STORE_TEST")?R"JS((async()=>{const wait=ms=>new Promise(r=>setTimeout(r,ms));const until=async find=>{for(let i=0;i<160;i++){const value=find();if(value)return value;await wait(50);}throw Error("store timeout "+document.body.innerText);};await wait(300);if(innerWidth!==1440||innerHeight!==810||devicePixelRatio!==4)throw Error("manager layout or DPI mismatch");[...document.querySelectorAll("nav button")].find(b=>b.textContent==="插件源").click();await wait(200);if(!document.body.textContent.includes("Subscription fixture"))throw Error("subscription settings missing");const autoRefresh=[...document.querySelectorAll("button")].find(b=>b.textContent==="关闭自动刷新");if(!autoRefresh)throw Error("subscription automatic refresh missing");autoRefresh.click();await until(()=>[...document.querySelectorAll("button")].find(b=>b.textContent==="开启自动刷新"));[...document.querySelectorAll("nav button")].find(b=>b.textContent==="关于").click();await wait(150);const updates=document.querySelector(".system-updates");if(!updates||updates.querySelector("input"))throw Error("release configuration leaked into user settings");if(!updates.textContent.includes("尚未配置更新服务"))throw Error("missing unconfigured update service message");const check=[...updates.querySelectorAll("button")].find(b=>b.textContent==="检查更新");if(!check?.disabled)throw Error("unconfigured check enabled");[...document.querySelectorAll("button")].find(b=>b.textContent==="查看协议与隐私声明").click();await until(()=>[...document.querySelectorAll("button")].find(b=>b.textContent==="拒绝协议"));document.querySelector('.language-picker button').click();const english=await until(()=>[...document.querySelectorAll('[role=option]')].find(b=>b.textContent==='English'));english.click();await until(()=>document.querySelector('h1')?.textContent==='Before using Framely');document.querySelector('.language-picker button').click();const chinese=await until(()=>[...document.querySelectorAll('[role=option]')].find(b=>b.textContent==='简体中文'));chinese.click();await until(()=>[...document.querySelectorAll('button')].find(b=>b.textContent==='拒绝协议'));[...document.querySelectorAll("button")].find(b=>b.textContent==="拒绝协议").click();await until(()=>document.body.textContent.includes("拒绝协议将停用全部插件"));[...document.querySelectorAll("button")].find(b=>b.textContent==="取消").click();await until(()=>[...document.querySelectorAll("button")].find(b=>b.textContent==="返回关于"));[...document.querySelectorAll("button")].find(b=>b.textContent==="返回关于").click();await until(()=>document.querySelector(".system-updates"));[...document.querySelectorAll("nav button")].find(b=>b.textContent.includes("插件库")).click();const card=await until(()=>document.querySelector(".store-card"));if(!card.textContent.includes("可更新"))throw Error("update not detected");if(card.querySelector(".plugin-avatar").getBoundingClientRect().width<64)throw Error("store icon not enlarged");if(documeLine truncated
cef_window_info_t win{};win.size=sizeof(win);win.windowless_rendering_enabled=1;cef_browser_settings_t bs{};bs.size=sizeof(bs);bs.windowless_frame_rate=60;cef_string_t uri{};str(uri,url);auto* browser=cef_browser_host_create_browser_sync(&win,&client.api,&uri,&bs,nullptr,nullptr);cef_string_utf16_clear(&uri);if(!browser)return 4;auto* host=browser->get_host(browser);
auto end=std::chrono::steady_clock::now()+std::chrono::seconds(45);bool injected=false;
while(std::chrono::steady_clock::now()<end&&!passed&&!failed){cef_do_message_loop_work();if(press_pending){auto now=std::chrono::steady_clock::now();cef_mouse_event_t mouse{};mouse.x=test_pointer.x+press_dx;mouse.y=test_pointer.y+press_dy;test_pointer.constrain(mouse.x,mouse.y,now);mouse.modifiers=EVENTFLAG_LEFT_MOUSE_BUTTON;host->send_mouse_move_event(host,&mouse,0);if(now-test_pointer.pressed>=std::chrono::milliseconds(press_duration)){mouse.modifiers=0;host->send_mouse_click_event(host,&mouse,MBT_LEFT,1,1);test_pointer.clear();press_pending=false;}}if(ready&&!injected){auto* f=browser->get_main_frame(browser);cef_string_t code{},source{};str(code,install_review_mode?"window.runInstallReviewChecks()":notification_mode?R"JS((async()=>{const wait=ms=>new Promise(r=>setTimeout(r,ms));for(let i=0;i<100&&!document.querySelector('.toast');i++)await wait(30);if(innerWidth!==600||innerHeight!==360||devicePixelRatio!==2)throw Error('notification dimensions');const toast=document.querySelector('.toast');if(!toast?.textContent.includes('Toast integration'))throw Error('notification missing');if(toast.getBoundingClientRect().height>240)throw Error('notification too large');if(toast.querySelectorAll('.toast-actions button').length!==3)throw Error('actions missing');toast.querySelector('[aria-label="确认"]').click();await wait(150);document.querySelector('[aria-label="关闭通知"]').click();await wait(150);const status=await fetch('/api',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({method:'status',params:{}})}).then(r=>r.json());if(status.result.notifications.length)throw Error('notification not withdrawn');console.log('FRAMELY_BRIDGE_PASS');})().catch(e=>console.error('FRAMELY_BRIDGE_FAIL '+e)))JS":std::getenv("FRAMELY_REMOTE_TEST")?R"JS((async()=>{const wait=ms=>new Promise(r=>setTimeout(r,ms));await wait(300);const button=document.createElement('button');button.style.cssText='position:fixed;left:20px;top:20px;width:100px;height:50px;z-index:9999';button.onclick=()=>console.log('FRAMELY_DPI_CLICK_PASS');document.body.append(button);console.log('FRAMELY_DPI_CLICK_REQUEST');await wait(200);button.remove();for(let i=0;i<100;i++){const plugin=document.querySelector('.plugin-main');if(plugin){plugin.click();return;}await wait(50);}throw Error('remote plugin list timeout');})().catch(e=>console.error('FRAMELY_BRIDGE_FAIL '+e)))JS":std::getenv("FRAMELY_STORE_TEST")?R"JS((async()=>{const wait=ms=>new Promise(r=>setTimeout(r,ms));const until=async find=>{for(let i=0;i<160;i++){const value=find();if(value)return value;await wait(50);}throw Error("store timeout "+document.body.innerText);};await wait(300);if(innerWidth!==1440||innerHeight!==810||devicePixelRatio!==4)throw Error("manager layout or DPI mismatch");[...document.querySelectorAll("nav button")].find(b=>b.textContent==="插件源").click();await wait(200);if(!document.body.textContent.includes("Subscription fixture"))throw Error("subscription settings missing");const autoRefresh=[...document.querySelectorAll("button")].find(b=>b.textContent==="关闭自动刷新");if(!autoRefresh)throw Error("subscription automatic refresh missing");autoRefresh.click();await until(()=>[...document.querySelectorAll("button")].find(b=>b.textContent==="开启自动刷新"));[...document.querySelectorAll("nav button")].find(b=>b.textContent==="关于").click();await wait(150);const updates=document.querySelector(".system-updates");if(!updates||updates.querySelector("input:not([type=checkbox]),textarea"))throw Error("release configuration leaked into user settings");if(!updates.querySelector(".automatic-update-settings input[type=checkbox]")?.disabled)throw Error("automatic check controls enabled without source");if(!updates.textContent.includes("尚未配置更新服务"))throw Error("missing unconfigured update service message");const check=[...updates.querySelectorAll("button")].find(b=>b.textContent==="检查更新");if(!check?.disabled)throw Error("unconfigured check enabled");[...document.querySelectorAll("button")].find(b=>b.textContent==="查看协议与隐私声明").click();await until(()=>[...document.querySelectorAll("button")].find(b=>b.textContent==="拒绝协议"));document.querySelector('.language-picker button').click();const english=await until(()=>[...document.querySelectorAll('[role=option]')].find(b=>b.textContent==='English'));english.click();await until(()=>document.querySelector('h1')?.textContent==='Before using Framely');document.querySelector('.language-picker button').click();const chinese=await until(()=>[...document.querySelectorAll('[role=option]')].find(b=>b.textContent==='简体中文'));chinese.click();await until(()=>[...document.querySelectorAll('button')].find(b=>b.textContent==='拒绝协议'));[...document.querySelectorAll("button")].find(b=>b.textContent==="拒绝协议").click();await until(()=>document.body.textContent.includes("拒绝协议将停用全部插件"));[...document.querySelectorAll("button")].fiLine truncated
if(!passed&&!failed){auto* f=browser->get_main_frame(browser);cef_string_t diagnostic{},source{};str(diagnostic,"console.error('FRAMELY_TIMEOUT '+location.pathname.replace(/\\/boot\\/[^/]+/,'/boot/token')+' '+document.body.innerText.slice(0,400))");f->execute_java_script(f,&diagnostic,&source,1);cef_string_utf16_clear(&diagnostic);f->base.release(&f->base);for(int i=0;i<40;i++){cef_do_message_loop_work();std::this_thread::sleep_for(std::chrono::milliseconds(5));}snapshot("FAILURE");}
host->close_browser(host,1);for(int i=0;i<400&&!closed;i++){cef_do_message_loop_work();std::this_thread::sleep_for(std::chrono::milliseconds(5));}bool ok=passed&&!failed&&paints>0&&closed&&scaled_paint&&(notification_mode||rounded_paint)&&(notification_mode||install_review_mode||std::getenv("FRAMELY_STORE_TEST")||dpi_click);std::cout<<"BROWSER_RESULT pass="<<ok<<" paints="<<paints<<" closed="<<closed<<"\n";if(!closed)_Exit(5);host->base.release(&host->base);browser->base.release(&browser->base);cef_shutdown();return ok?0:5;
}
+1
View File
@@ -0,0 +1 @@
import{registerLauncherActions,framely}from'../sdk/src/index';registerLauncherActions({connect:async context=>{if(context.source!=='launcher')throw Error('Missing launch context');await framely.call('connect',{from:context.source});}});
+91
View File
@@ -0,0 +1,91 @@
import React,{useState} from 'react';import{createRoot}from'react-dom/client';
import{Launcher,LauncherSettings,type LauncherConfig}from'../ui/src/launcher';import{configureLanguage}from'../ui/src/i18n';import type{Plugin}from'../ui/src/main';import'../ui/src/style.css';
const wait=(ms=80)=>new Promise(r=>setTimeout(r,ms));const until=async(f:()=>any)=>{for(let i=0;i<120;i++){if(f())return;await wait(30);}throw Error('Timed out '+document.body.innerText.slice(0,240)+' '+JSON.stringify(calls.slice(-4))+' edit='+!!document.querySelector('.launcher-editing'));};
let config:LauncherConfig={primaryTrigger:false,menuAutoClose:true,menuTimeoutSeconds:1};let order:string[]=[];let localApps:any[]=[];let redraw:()=>void;let settings=false;const calls:{method:string;params:any}[]=[];
const plugins:Record<string,Plugin>={
'demo.alpha':{manifest:{id:'demo.alpha',icon:'icon.png',name:'Termix',description:'Terminal',author:'Framely',version:'1.0.0',ui:{quickPage:'page.js',windows:{main:{}},launcherActions:[{id:'connect',label:'Connect terminal',target:{type:'frontend',entry:'actions.js'}}]}},enabled:true,favorite:true,order:0},
'demo.beta':{manifest:{id:'demo.beta',icon:'icon.png',name:'Passthrough color',description:'Color',author:'Framely',version:'1.0.0',ui:{quickPage:'page.js',windows:{}}},enabled:true,favorite:false,order:1},
'demo.off':{manifest:{id:'demo.off',name:'Disabled app',description:'',author:'Framely',version:'1.0.0',ui:{windows:{}}},enabled:false,favorite:false,order:2},
};
window.fetch=async(url,init)=>{if(String(url)!=='/api')throw Error('Unexpected fetch');const{method,params}=JSON.parse(String(init?.body));calls.push({method,params});let result:any=true;
if(method==='steam.list')result=[{id:620980,name:'Beat Saber'},{id:546560,name:'Half-Life: Alyx'},{id:413150,name:'Stardew Valley'},{id:1245620,name:'Elden Ring'},{id:367520,name:'Hollow Knight'},{id:570,name:'Dota 2'},{id:440,name:'Team Fortress 2'}].map(a=>({...a,icon:`/preview-icons/${a.id}.jpg`,iconFit:'cover'}));
else if(method==='desktop.list')result=localApps;
else if(method==='status')result={database:{plugins,safeMode:false}};
else if(method==='plugin.disable.preview')result={dependents:[],fingerprint:'test'};
else if(method==='launcher.order.save'){order=params.order;}
else if(method==='launcher.settings.save'){config=params;}
else if(method==='plugin.launcher.action')result={frontend:'actions.js',context:{source:'launcher',trigger:'menuAction',actionId:params.action}};
return new Response(JSON.stringify({result}));};
function Fixture(){const[,render]=useState(0);redraw=()=>render(n=>n+1);return settings?<div className="app manager"><LauncherSettings config={config} refresh={async()=>redraw()}/></div>:<Launcher plugins={plugins} safeMode={false} config={config} favorites={[]} order={order} refresh={async()=>redraw()}/>;}
function button(text:string){return [...document.querySelectorAll<HTMLButtonElement>('button')].find(b=>b.textContent===text)!;}
function openMenu(){const b=document.querySelector<HTMLButtonElement>('.launch-icon[aria-label=Termix]')!;b.dispatchEvent(new MouseEvent('contextmenu',{bubbles:true}));}
(window as any).runInstallReviewChecks=async()=>{try{
configureLanguage('en-US',[]);redraw();await until(()=>document.querySelectorAll('.launch-icon').length===1);document.querySelector<HTMLButtonElement>('.launcher-filters button[aria-label=All]')!.click();await until(()=>document.querySelectorAll('.launch-icon').length===10);
if(document.body.textContent?.includes('Disabled app'))throw Error('Disabled plugin displayed');
if(document.querySelector('.launcher-header')||!document.querySelector('.launcher-search input'))throw Error('Launcher contains panel controls');
if(getComputedStyle(document.querySelector('.launcher-shell')!).backgroundColor!=='rgba(0, 0, 0, 0)')throw Error('Launcher is not transparent');
const grid=document.querySelector('.launcher-grid')!,filters=document.querySelector('.launcher-filters')!;const gridBefore=grid.getBoundingClientRect(),filterBefore=filters.getBoundingClientRect();if(gridBefore.width<1110)throw Error('Icon spacing was not widened');if(document.querySelector('.launcher-filters button')!.getBoundingClientRect().width<56)throw Error('Category hit target is too small');
const shellRect=document.querySelector('.launcher-shell')!.getBoundingClientRect();if(Math.abs(gridBefore.x+gridBefore.width/2-shellRect.x-shellRect.width/2)>1)throw Error('Icon area is not independently centered');const categoryRight=filterBefore.right;
const discs=[...document.querySelectorAll<HTMLElement>('.launch-disc')].map(n=>n.getBoundingClientRect());const middle=discs.filter(r=>Math.abs(r.y-discs[4].y)<1);const betweenIcons=middle[1].left-middle[0].right,gapToCategories=middle[0].left-categoryRight;if(betweenIcons<90||gapToCategories<=betweenIcons)throw Error('Category gap must exceed horizontal artwork gap');
const firstSlotY=document.querySelector<HTMLElement>('.launch-item')!.offsetTop;
const sameLayout=()=>{const g=document.querySelector('.launcher-grid')!.getBoundingClientRect(),f=filters.getBoundingClientRect();if(g.width!==gridBefore.width||g.height!==gridBefore.height||g.x!==gridBefore.x||g.y!==gridBefore.y||f.x!==filterBefore.x||f.y!==filterBefore.y)throw Error('App count moved the fixed grid or categories '+JSON.stringify({before:gridBefore.toJSON(),after:g.toJSON(),filterBefore:filterBefore.toJSON(),filterAfter:f.toJSON()}));};
const assertRows=(expected:number[])=>{const groups=new Map<string,DOMRect[]>();for(const item of document.querySelectorAll<HTMLElement>('.launch-item')){const r=item.querySelector('.launch-icon')!.getBoundingClientRect();if(item.style.gridRow.startsWith('1 /')&&Math.abs(item.offsetTop-firstSlotY)>1)throw Error('Partial rows moved the first icon row');const key=item.style.gridRow;groups.set(key,[...(groups.get(key)??[]),r]);}const rows=[...groups.values()];if(rows.map(row=>row.length).join(',')!==expected.join(','))throw Error('Unexpected row counts '+rows.map(row=>row.length));const center=(r:DOMRect)=>r.x+r.width/2;if(rows.length===1){const mean=rows[0].reduce((sum,r)=>sum+center(r),0)/rows[0].length;if(Math.abs(mean-gridBefore.x-gridBefore.width/2)>1)throw Error('Single row is not centered');}else{const step=center(rows[0][1])-center(rows[0][0]);if(Math.abs(center(rows[1][0])-center(rows[0][0])+step/2)>1)throw Error('Second row did not start half a slot left');if(rows[2]&&Math.abs(center(rows[2][0])-center(rows[0][0]))>1)throw Error('Third row is not aligned with the first');}};
assertRows([4,5,1]);
plugins['demo.ten']={...plugins['demo.beta'],manifest:{...plugins['demo.beta'].manifest,id:'demo.ten',name:'Tenth app'}};redraw();await until(()=>document.querySelectorAll('.launch-icon').length===11);sameLayout();assertRows([4,5,2]);await wait(300);console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_TEN_EN');delete plugins['demo.ten'];redraw();await until(()=>document.querySelectorAll('.launch-icon').length===10);
for(let n=0;n<3;n++)plugins[`demo.extra${n}`]={...plugins['demo.beta'],manifest:{...plugins['demo.beta'].manifest,id:`demo.extra${n}`,name:`Extra ${n}`}};redraw();await until(()=>document.querySelectorAll('.launch-icon').length===13);sameLayout();assertRows([4,5,4]);for(let n=3;n<7;n++)plugins[`demo.extra${n}`]={...plugins['demo.beta'],manifest:{...plugins['demo.beta'].manifest,id:`demo.extra${n}`,name:`Extra ${n}`}};redraw();await until(()=>document.querySelectorAll('.launcher-pages button').length===2);sameLayout();if(document.querySelectorAll('.launch-icon').length!==13)throw Error('AVP page capacity changed');document.querySelectorAll<HTMLButtonElement>('.launcher-pages button')[1].click();await until(()=>document.querySelectorAll('.launch-icon').length===4);sameLayout();document.querySelectorAll<HTMLButtonElement>('.launcher-pages button')[0].click();await until(()=>document.querySelectorAll('.launch-icon').length===13);if(!document.querySelector('.launcher-page')!.getAnimations().length)throw Error('Page change has no animation');await wait(340);for(let n=0;n<7;n++)delete plugins[`demo.extra${n}`];redraw();await until(()=>document.querySelectorAll('.launch-icon').length===10);
if(Math.abs(document.querySelector('.launch-disc')!.getBoundingClientRect().width-96)>.1)throw Error('Launcher artwork is too large');
document.querySelector<HTMLButtonElement>('.launcher-filters button[aria-label=Plugin]')!.click();await until(()=>document.querySelectorAll('.launch-icon').length===3);sameLayout();if(!document.querySelector('.launcher-page')!.getAnimations().length)throw Error('Category change has no animation');const categoryMotion=document.querySelector('.launcher-page')!.getAnimations()[0].effect as KeyframeEffect;if(!String(categoryMotion.getKeyframes()[0].translate).includes('110px'))throw Error('Category motion is too subtle');const activeSurface=document.querySelector<HTMLElement>('.launcher-category-active')!;await wait(60);const surfaceY=activeSurface.getBoundingClientRect().top,selectedY=document.querySelector('.launcher-filters button.active')!.getBoundingClientRect().top;if(surfaceY<=filterBefore.top+7||surfaceY>=selectedY)throw Error('Category active surface did not slide through intermediate positions');await wait(360);if(Math.abs(activeSurface.getBoundingClientRect().top-selectedY)>1)throw Error('Category surface did not settle under active item');
const arrangements=[[1],[2],[3],[4],[4,1],[4,2],[4,3],[4,4],[4,5],[4,5,1],[4,5,2],[4,5,3],[4,5,4]];
plugins['demo.alpha'].enabled=false;plugins['demo.beta'].enabled=false;
redraw();await until(()=>document.querySelectorAll('.launch-icon').length===1);sameLayout();assertRows([1]);
for(let n=1;n<13;n++){plugins[`layout.${n}`]={...plugins['demo.beta'],enabled:true,manifest:{...plugins['demo.beta'].manifest,id:`layout.${n}`,name:`Layout ${String(n).padStart(2,'0')}`}};redraw();await until(()=>document.querySelectorAll('.launch-icon').length===n+1);sameLayout();assertRows(arrangements[n]);}
for(let n=1;n<=13;n++)delete plugins[`layout.${n}`];plugins['demo.alpha'].enabled=true;plugins['demo.beta'].enabled=true;redraw();await until(()=>document.querySelectorAll('.launch-icon').length===3);
document.querySelector<HTMLButtonElement>('.launcher-filters button[aria-label=All]')!.click();await until(()=>document.querySelectorAll('.launch-icon').length===10);
const category=document.querySelector<HTMLButtonElement>('.launcher-filters button[aria-label=Steam]')!;const categoryRect=category.getBoundingClientRect();console.log(`FRAMELY_LAUNCHER_PRESS_${Math.round(categoryRect.x+categoryRect.width/2)}_${Math.round(categoryRect.y+categoryRect.height/2)}_28_15_150`);await until(()=>document.querySelectorAll('.launch-icon').length===7);sameLayout();assertRows([4,3]);document.querySelector<HTMLButtonElement>('.launcher-filters button[aria-label=All]')!.click();await until(()=>document.querySelectorAll('.launch-icon').length===10);
const assertControlsPainted=()=>{for(const node of document.querySelectorAll('.launcher-filters button svg,.launcher-pages button span')){const r=node.getBoundingClientRect();console.log(`FRAMELY_LAUNCHER_REGION_${Math.floor(r.x)}_${Math.floor(r.y)}_${Math.ceil(r.width)}_${Math.ceil(r.height)}`);}};
await wait(500);assertControlsPainted();for(const label of document.querySelectorAll('.launch-name')){const r=label.getBoundingClientRect();console.log(`FRAMELY_LAUNCHER_INK_${Math.floor(r.x)}_${Math.floor(r.y)}_${Math.ceil(r.width)}_${Math.ceil(r.height)}`);}console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_EN');
const icon=document.querySelector<HTMLButtonElement>('.launch-icon[aria-label=Termix]')!;
const rect=icon.getBoundingClientRect();console.log(`FRAMELY_LAUNCHER_HOVER_${Math.round(rect.x+rect.width/2)}_${Math.round(rect.y+rect.height/2)}`);await wait(350);if(icon.getBoundingClientRect().width!==rect.width)throw Error('Hover moved the input target');console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_HOVER_EN');console.log('FRAMELY_LAUNCHER_HOVER_0_0');await wait(250);
const beforeClick=calls.filter(c=>c.method==='plugin.launch').length;console.log(`FRAMELY_LAUNCHER_PRESS_${Math.round(rect.x+10)}_${Math.round(rect.y+rect.height/2)}_-28_15_150`);await until(()=>calls.filter(c=>c.method==='plugin.launch').length===beforeClick+1);if(calls.filter(c=>c.method==='plugin.launch').at(-1)?.params.plugin!=='demo.alpha')throw Error('Jitter click launched a different app');
const beforeDrag=calls.filter(c=>c.method==='plugin.launch').length;console.log(`FRAMELY_LAUNCHER_PRESS_${Math.round(rect.x+rect.width/2)}_${Math.round(rect.y+rect.height/2)}_80_0_300`);await wait(550);if(calls.filter(c=>c.method==='plugin.launch').length!==beforeDrag||document.querySelector('[role=menu]'))throw Error('Deliberate movement activated an app');
console.log(`FRAMELY_LAUNCHER_PRESS_${Math.round(rect.x+rect.width/2)}_${Math.round(rect.y+rect.height/2)}_28_18_1000`);await wait(200);console.log('FRAMELY_LAUNCHER_CANCEL_PRESS');await wait(800);if(calls.filter(c=>c.method==='plugin.launch').length!==beforeDrag||document.querySelector('[role=menu]'))throw Error('Hidden launcher retained a pending gesture');
const initial=calls.filter(c=>c.method==='plugin.launch').length;console.log(`FRAMELY_LAUNCHER_PRESS_${Math.round(rect.x+rect.width/2)}_${Math.round(rect.y+rect.height/2)}_28_18_650`);await wait(850);
if(!document.querySelector('[role=menu]')||calls.filter(c=>c.method==='plugin.launch').length!==initial)throw Error('Long press triggered a launch');
if(document.querySelectorAll('[role=menuitem]').length!==4)throw Error('Built-in/custom menu actions missing');
await wait(180);console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_MENU_EN');
button('Connect terminal').click();await until(()=>calls.some(c=>c.method==='plugin.call'&&c.params.method==='connect'));await until(()=>!document.querySelector('.launcher-action-frame'));
if(!calls.some(c=>c.method==='plugin.call'&&c.params.method==='connect'))throw Error('Frontend action did not run');
document.querySelector('.launcher-shell')!.dispatchEvent(new MouseEvent('click',{bubbles:true}));await wait();if(document.querySelector('[role=menu]'))throw Error('Outside click did not close');
openMenu();await wait();const item=document.querySelector('.launch-item-expanded')!;item.dispatchEvent(new PointerEvent('pointerout',{bubbles:true,relatedTarget:document.body}));await wait(500);item.dispatchEvent(new PointerEvent('pointerover',{bubbles:true,relatedTarget:document.body}));await wait(700);if(!document.querySelector('[role=menu]'))throw Error('Reentry failed to cancel timer');item.dispatchEvent(new PointerEvent('pointerout',{bubbles:true,relatedTarget:document.body}));await wait(1150);if(document.querySelector('[role=menu]'))throw Error('Leave timer did not close');
openMenu();await wait();button('Uninstall plugin').click();await wait();if(!document.querySelector('[role=dialog]')||calls.some(c=>c.method==='plugin.uninstall'))throw Error('Uninstall bypassed confirmation');button('Cancel').click();await wait();
configureLanguage('zh-CN',[]);config={...config,menuTimeoutSeconds:10};redraw();await wait(650);console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_MENU_ZH');document.querySelector('.launcher-shell')!.dispatchEvent(new MouseEvent('click',{bubbles:true}));await wait(650);assertControlsPainted();for(const label of document.querySelectorAll('.launch-name')){const r=label.getBoundingClientRect();console.log(`FRAMELY_LAUNCHER_INK_${Math.floor(r.x)}_${Math.floor(r.y)}_${Math.ceil(r.width)}_${Math.ceil(r.height)}`);}console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_ZH');
// Exercise real CEF pointer capture across the 400 / 800 ms transition,
// then reorder and persist. No app may launch when a long hold is released.
configureLanguage('en-US',[]);redraw();await wait(120);
const orderedBefore=[...document.querySelectorAll<HTMLElement>('.launch-item')].map(n=>n.dataset.launchKey!);
const first=document.querySelector<HTMLButtonElement>('.launch-icon')!,firstRect=first.getBoundingClientRect();const last=document.querySelectorAll<HTMLButtonElement>('.launch-icon')[3].getBoundingClientRect();
const launchesBefore=calls.filter(c=>c.method==='plugin.launch'||c.method==='steam.launch').length;
console.log(`FRAMELY_LAUNCHER_PRESS_${Math.round(firstRect.x+firstRect.width/2)}_${Math.round(firstRect.y+firstRect.height/2)}_0_0_1500`);
await until(()=>!!document.querySelector('[role=menu]'));await until(()=>document.querySelector('.launcher-editing'));if(document.querySelector('[role=menu]'))throw Error('800 ms left the menu open');
console.log(`FRAMELY_LAUNCHER_DRAG_${Math.round(last.x+last.width/2)}_${Math.round(last.y+last.height/2)}`);await until(()=>calls.some(c=>c.method==='launcher.order.save'));
await until(()=>!document.querySelector('.launcher-drag-ghost'));const reordered=[...document.querySelectorAll<HTMLElement>('.launch-item')].map(n=>n.dataset.launchKey!);if(reordered[3]!==orderedBefore[0]||order[3]!==orderedBefore[0])throw Error('Drag did not insert and persist order');if(calls.filter(c=>c.method==='plugin.launch'||c.method==='steam.launch').length!==launchesBefore)throw Error('Arrange gesture launched an app');const doneStyle=getComputedStyle(button('Done')),railStyle=getComputedStyle(document.querySelector('.launcher-tools')!);if(doneStyle.backgroundColor!==railStyle.backgroundColor||doneStyle.borderTopColor!==railStyle.borderTopColor||doneStyle.boxShadow!==railStyle.boxShadow)throw Error('Done button does not match category rail material');console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_EDIT_EN');await until(()=>!button('Done').disabled);button('Done').click();await until(()=>!document.querySelector('.launcher-editing'));await wait(100);
const selfIcon=document.querySelector<HTMLButtonElement>('.launch-icon[aria-label=Framely]')!;selfIcon.dispatchEvent(new MouseEvent('contextmenu',{bubbles:true}));await wait(80);button('Arrange icons').click();await until(()=>!!document.querySelector('.launcher-editing'));const closeCount=calls.filter(c=>c.method==='host.launcher.close').length;window.dispatchEvent(new Event('framely.back'));await until(()=>!document.querySelector('.launcher-editing'));if(calls.filter(c=>c.method==='host.launcher.close').length!==closeCount)throw Error('B closed the launcher instead of exiting arrangement');selfIcon.dispatchEvent(new MouseEvent('contextmenu',{bubbles:true}));await wait(80);button('Arrange icons').click();await until(()=>!!document.querySelector('.launcher-editing'));document.querySelector('.launcher-shell')!.dispatchEvent(new MouseEvent('click',{bubbles:true}));await until(()=>!document.querySelector('.launcher-editing'));if(calls.filter(c=>c.method==='host.launcher.close').length!==closeCount)throw Error('Blank click closed launcher during arrangement');
// Add enough icons for edge paging and swipe navigation.
for(let n=0;n<9;n++)plugins[`edge.${n}`]={...plugins['demo.beta'],manifest:{...plugins['demo.beta'].manifest,id:`edge.${n}`,name:`Edge ${n}`}};redraw();await until(()=>document.querySelectorAll('.launcher-pages button').length===2);
console.log('FRAMELY_LAUNCHER_PRESS_700_90_-180_0_550');await until(()=>!!document.querySelector('.launcher-adjacent-page'));const activePage=document.querySelector<HTMLElement>('.launcher-page')!,adjacent=document.querySelector<HTMLElement>('.launcher-adjacent-page')!;if(!document.querySelector('.launcher-grid')!.classList.contains('launcher-panning')||!getComputedStyle(activePage).translate.startsWith('-180px'))throw Error('Canvas did not follow the held trigger');if(getComputedStyle(adjacent).translate==='none')throw Error('Neighbor did not slide alongside canvas');if(document.querySelectorAll('.launcher-pages button')[0].getAttribute('aria-current')!=='page')throw Error('Swipe committed before release');await until(()=>document.querySelectorAll('.launcher-pages button')[1].getAttribute('aria-current')==='page');
window.dispatchEvent(new CustomEvent('framely.launcher.navigate',{detail:-1}));await until(()=>document.querySelectorAll('.launcher-pages button')[0].getAttribute('aria-current')==='page');
await wait(340);const edgeFirst=document.querySelector<HTMLButtonElement>('.launch-icon')!.getBoundingClientRect();const saves=calls.filter(c=>c.method==='launcher.order.save').length;
console.log(`FRAMELY_LAUNCHER_PRESS_${Math.round(edgeFirst.x+edgeFirst.width/2)}_${Math.round(edgeFirst.y+edgeFirst.height/2)}_0_0_2600`);await until(()=>document.querySelector('.launcher-editing'));const edgeBox=document.querySelector('.launcher-grid')!.getBoundingClientRect();console.log(`FRAMELY_LAUNCHER_DRAG_${Math.round(edgeBox.right-25)}_400`);await until(()=>document.querySelectorAll('.launcher-pages button')[1].getAttribute('aria-current')==='page');console.log('FRAMELY_EDGE_PAGE_OK');await wait(340);const leftEdge=Math.max(edgeBox.left,categoryRight+24)+25;if(leftEdge<=categoryRight)throw Error('Left drag edge overlaps category rail');console.log(`FRAMELY_LAUNCHER_DRAG_${Math.round(leftEdge)}_400`);await until(()=>!!document.querySelector('.launcher-drag-edge.left'));const indicator=document.querySelector('.launcher-drag-edge.left')!.getBoundingClientRect();if(indicator.left<=categoryRight)throw Error('Left edge feedback is behind the category rail');await until(()=>calls.filter(c=>c.method==='launcher.order.save').length>saves);console.log('FRAMELY_EDGE_SAVE_OK');await until(()=>!button('Done').disabled);button('Done').click();await until(()=>!document.querySelector('.launcher-editing'));
for(let n=0;n<9;n++)delete plugins[`edge.${n}`];redraw();window.dispatchEvent(new CustomEvent('framely.launcher.navigate',{detail:-1}));await wait(100);
console.log('FRAMELY_EDGE_DONE_OK');
// Framely and new app kinds use their own safe launch APIs.
document.querySelector<HTMLButtonElement>('.launch-icon[aria-label=Framely]')!.click();await until(()=>calls.some(c=>c.method==='host.manager.open'));
console.log('FRAMELY_SELF_LAUNCH_OK');localApps=[{id:'terminal.desktop',name:'Desktop terminal',kind:'desktop'},{id:'test/com.example.browser',name:'Android browser',kind:'lepton'}];await until(()=>!document.querySelector('.launch-icon:disabled'));window.dispatchEvent(new Event('framely.launcher.open'));await wait(120);await until(()=>!document.querySelector('.launcher-initializing'));document.querySelector<HTMLButtonElement>('.launcher-filters button[aria-label=All]')!.click();await until(()=>document.querySelector('.launch-icon[aria-label="Desktop terminal"]'));
document.querySelector<HTMLButtonElement>('.launcher-filters button[aria-label="Desktop apps"]')!.click();await until(()=>document.querySelectorAll('.launch-icon').length===1);document.querySelector<HTMLButtonElement>('.launch-icon')!.click();await until(()=>calls.some(c=>c.method==='desktop.launch'&&c.params.app==='desktop:terminal.desktop'));
await until(()=>!document.querySelector<HTMLButtonElement>('.launch-icon')!.disabled);window.dispatchEvent(new CustomEvent('framely.launcher.navigate',{detail:2}));await until(()=>document.querySelector('.launcher-filters button[aria-label=Lepton]')!.getAttribute('aria-pressed')==='true');document.querySelector<HTMLButtonElement>('.launch-icon')!.click();await until(()=>calls.some(c=>c.method==='desktop.launch'&&c.params.app==='lepton:test/com.example.browser'));
const closes=calls.filter(c=>c.method==='host.launcher.close').length;document.querySelector('.launcher-shell')!.dispatchEvent(new MouseEvent('click',{bubbles:true}));window.dispatchEvent(new Event('framely.back'));await until(()=>calls.filter(c=>c.method==='host.launcher.close').length===closes+2);
settings=true;redraw();await wait();const switches=document.querySelectorAll<HTMLInputElement>('[role=switch]');switches[0].click();await wait();if(!config.primaryTrigger)throw Error('Trigger setting not saved');await wait(180);console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_SETTINGS_ZH');configureLanguage('en-US',[]);redraw();await wait(180);console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_SETTINGS_EN');console.log('FRAMELY_BRIDGE_PASS');
}catch(e){console.error('FRAMELY_BRIDGE_FAIL '+e);}};
createRoot(document.getElementById('root')!).render(<Fixture/>);wait(150).then(()=>console.log('FRAMELY_VIEW_READY'));
+47
View File
@@ -0,0 +1,47 @@
#include "launcher_input.h"
#include <cassert>
#include <cmath>
int main(){
LauncherStick stick;assert(!stick.update(1,0,true));assert(!stick.update(0,0,true));assert(stick.update(.8f,.75f,true)==1);assert(!stick.update(.4f,.9f,true));assert(!stick.update(0,0,true));assert(stick.update(-.7f,-.95f,true)==-2);assert(!stick.update(0,0,false));assert(!stick.update(0,1,true));assert(!stick.update(0,.2f,true));assert(stick.update(0,1,true)==2);assert(!stick.update(NAN,0,true));
vr::RenderModel_ComponentState_t joystick_rest{},joystick_x{},joystick_y{},joystick_current{};
joystick_rest.mTrackingToComponentRenderModel={{{1,0,0,0},{0,1,0,0},{0,0,1,0}}};joystick_x=joystick_y=joystick_current=joystick_rest;
auto turn=[](vr::RenderModel_ComponentState_t& value,float x,float y){auto& m=value.mTrackingToComponentRenderModel;float cx=std::cos(x),sx=std::sin(x),cy=std::cos(y),sy=std::sin(y);m={{{cy,sy*sx,sy*cx,0},{0,cx,-sx,0},{-sy,cy*sx,cy*cx,0}}};};
turn(joystick_x,0,.35f);turn(joystick_y,.35f,0);turn(joystick_current,-.28f,.14f);float joystick_dx=0,joystick_dy=0;assert(launcher_stick_axes(joystick_rest,joystick_x,joystick_y,joystick_current,joystick_dx,joystick_dy));assert(std::abs(joystick_dx-.4f)<.03f);assert(std::abs(joystick_dy+.8f)<.03f);assert(!launcher_stick_axes(joystick_rest,joystick_rest,joystick_rest,joystick_current,joystick_dx,joystick_dy));
auto now=std::chrono::steady_clock::now();EntryTrigger t;EntryPointer pointer;
pointer.move(1,320,64);assert(pointer.hit(1));assert(!pointer.hit(2));pointer.move(2,20,64);assert(!pointer.hit(2));pointer.move(2,320,64);assert(pointer.hit(2));pointer.leave();assert(!pointer.hit(2));
vr::HmdMatrix34_t tracked{{{0,0,1,1},{0,1,0,2},{-1,0,0,3}}},tip{{{1,0,0,.1f},{0,1,0,.2f},{0,0,1,.3f}}};auto composed=entry_tip_pose(tracked,tip);assert(std::abs(composed.m[0][3]-1.3f)<1e-6f);assert(std::abs(composed.m[1][3]-2.2f)<1e-6f);assert(std::abs(composed.m[2][3]-2.9f)<1e-6f);assert(composed.m[2][0]==-1);
vr::RenderModel_ComponentState_t rest{},full{},partial{};rest.mTrackingToComponentRenderModel={{{1,0,0,0},{0,1,0,0},{0,0,1,0}}};full=partial=rest;
auto rotate=[](vr::RenderModel_ComponentState_t& state,float angle){auto& m=state.mTrackingToComponentRenderModel;m.m[0][0]=m.m[2][2]=std::cos(angle);m.m[0][2]=std::sin(angle);m.m[2][0]=-std::sin(angle);};
rotate(full,.22f);rotate(partial,.121f);float pull=0;assert(entry_trigger_pull(rest,full,partial,pull));assert(std::abs(pull-.55f)<.001f);assert(!(partial.uProperties&vr::VRComponentProperty_IsPressed));EntryAnalogTrigger analog;assert(analog.update(pull));assert(analog.update(.47f));assert(!analog.update(.44f));assert(!analog.update(.49f));assert(analog.update(.51f));assert(!entry_trigger_pull(rest,rest,partial,pull));assert(!analog.update(NAN));
EntryAnalogTrigger sampledPull;EntryTrigger sampledClick;int activations=0,frame=0;
for(float sample:{0.f,.213733f,.378395f,.513260f,.718133f,.501608f,.345020f,.188268f,.0107336f,0.f}){bool opened=sampledClick.update(true,sampledPull.update(sample),true,now+std::chrono::milliseconds(25*frame));activations+=opened;if(frame==3)assert(opened);if(frame!=3)assert(!opened);frame++;}assert(activations==1);
EntryTrigger left,upper;assert(!left.update(true,false,true,now));assert(!upper.update(true,false,true,now));assert(left.update(true,true,true,now));assert(!left.update(true,true,true,now));assert(!left.update(true,false,true,now));assert(upper.update(true,true,true,now));assert(!upper.update(true,false,true,now));
// Dragging a held trigger into the target does not count as a new press.
assert(!t.update(true,false,false,now));assert(!t.update(true,true,false,now));assert(!t.update(true,true,true,now));assert(!t.update(true,false,true,now));
assert(t.update(true,true,true,now));assert(!t.update(true,true,true,now));assert(!t.update(true,false,true,now));
// Disconnect/reconnect while held cannot produce a stale activation.
now+=std::chrono::milliseconds(200);assert(!t.update(false,false,true,now));assert(!t.update(true,true,true,now));assert(!t.update(true,false,true,now));assert(t.update(true,true,true,now));assert(!t.update(true,false,true,now));
assert(!t.update(true,true,true,now));assert(!t.update(true,false,true,now));now+=std::chrono::milliseconds(200);assert(t.update(true,true,true,now));
// Reopening after a plugin quick page must rearm the modal guard each time.
LauncherDismissGuard guard;guard.opened(now);
assert(!guard.allows(now,true));assert(!guard.allows(now+std::chrono::milliseconds(400),true));
assert(guard.allows(now+std::chrono::milliseconds(400),false));assert(guard.allows(now+std::chrono::milliseconds(500),true));
now+=std::chrono::seconds(2);guard.opened(now);
assert(!guard.allows(now+std::chrono::milliseconds(20),false));
assert(!guard.allows(now+std::chrono::milliseconds(500),false,1.f));
assert(guard.allows(now+std::chrono::milliseconds(500),false,.1f));
// Releasing the opening trigger rearms input once, even without mouse events.
guard.opened(now);guard.observe(true);guard.observe(false);
assert(guard.allows(now+std::chrono::milliseconds(700),true));
// Dock dragging and delayed cancel keep the launcher; later background
// clicks become dismissible again, and reopening clears the prior gesture.
LauncherDockGuard dock;assert(!dock.holds(now));dock.observe(true,true,now);
assert(dock.holds(now+std::chrono::milliseconds(60)));
dock.observe(false,true,now+std::chrono::seconds(2));
assert(dock.holds(now+std::chrono::seconds(2)));
dock.observe(false,false,now+std::chrono::seconds(3));
assert(dock.holds(now+std::chrono::milliseconds(3200)));
assert(!dock.holds(now+std::chrono::milliseconds(3250)));
dock.clear();assert(!dock.holds(now+std::chrono::seconds(3)));
}
+18
View File
@@ -0,0 +1,18 @@
// Check routing and migrated settings in the actual manager, not a reproduced page.
import {configureLanguage} from '../ui/src/i18n';
const wait=(ms=80)=>new Promise(r=>setTimeout(r,ms));const until=async(f:()=>any)=>{for(let i=0;i<150;i++){if(f())return;await wait(30);}throw Error('Timed out '+document.body.innerText.slice(0,350));};
history.replaceState(null,'','/manager#launcher-settings');let language='en-US';let launcher:any={primaryTrigger:false,menuAutoClose:true,menuTimeoutSeconds:10,allCategories:['plugin','steam','lepton','desktop']};
window.fetch=async(_url,init)=>{const {method,params}=JSON.parse(String(init?.body));let result:any=true;
if(method==='status')result={version:'0.4.3-preview.2',build:'0.4.3-preview.2',agreement:{version:1,accepted:true},database:{plugins:{},sources:[],safeMode:false,language,launcher,networkPanel:{enabled:true,port:15915},proxy:{http:'',github:''}},running:[],notifications:[],inbox:[]};
else if(method==='language.list')result={packs:[],invalidFiles:[]};else if(method==='ui.events')result={cursor:0,events:[]};else if(method==='network.status')result={passwordConfigured:true,localOrigin:'http://localhost:15915',ips:[],listener:{}};else if(method==='launcher.settings.save')launcher=params;else if(method==='language.save')language=params.language;
return new Response(JSON.stringify({result}));};
const nav=(label:string)=>[...document.querySelectorAll<HTMLButtonElement>('.workspace>nav button')].find(b=>b.textContent===label)!;
(window as any).runInstallReviewChecks=async()=>{try{
await until(()=>!!document.querySelector('.launcher-settings'));if(nav('Launcher').getAttribute('aria-current')!=='page')throw Error('Hash did not select Launcher');if(document.querySelectorAll('.launcher-settings [role=switch]').length!==6)throw Error('Missing launcher controls');
nav('Settings').click();await until(()=>!document.querySelector('.launcher-settings'));nav('Launcher').click();await until(()=>!!document.querySelector('.launcher-settings'));
const switcher=document.querySelector<HTMLInputElement>('.launcher-settings [role=switch]')!;switcher.click();await until(()=>launcher.primaryTrigger);await until(()=>!switcher.disabled);
const categories=document.querySelectorAll<HTMLInputElement>('.launcher-settings [role=switch]');categories[3].click();await until(()=>!launcher.allCategories.includes('steam'));await until(()=>!categories[3].disabled);
await wait(450);console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_MANAGER_EN');const content=document.querySelector<HTMLElement>('.content')!;content.scrollTop=content.scrollHeight;await wait(300);console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_CATEGORIES_EN');content.scrollTop=0;language='zh-CN';configureLanguage(language,[]);location.hash='#launcher-settings';window.dispatchEvent(new Event('hashchange'));await until(()=>document.documentElement.lang==='zh-CN'&&!!nav('启动台'));await wait(450);console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_MANAGER_ZH');content.scrollTop=content.scrollHeight;await wait(300);console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_CATEGORIES_ZH');
const first=document.querySelector('.launcher-settings .switch-row')!.getBoundingClientRect();const second=document.querySelectorAll('.launcher-settings')[1].querySelector('.switch-row')!.getBoundingClientRect();if(Math.abs(first.width-second.width)>1)throw Error('Settings widths differ');console.log('FRAMELY_BRIDGE_PASS');
}catch(e){console.error('FRAMELY_BRIDGE_FAIL '+e);}};
void import('../ui/src/main');
+24
View File
@@ -0,0 +1,24 @@
#include "../native/launcher_input.h"
#include <chrono>
#include <iostream>
#include <thread>
int main(int argc,char** argv){if(argc!=2)return 2;vr::EVRInitError error;auto* system=vr::VR_Init(&error,vr::VRApplication_Overlay);if(error){std::cerr<<"VR_Init: "<<error<<"\n";return 3;}auto* input=vr::VRInput();auto result=input->SetActionManifestPath(argv[1]);std::cout<<"manifest="<<result<<"\n";vr::VRActionSetHandle_t set=0;vr::VRActionHandle_t primary=0,upper=0,aim=0;bool ok=result==vr::VRInputError_None&&input->GetActionSetHandle("/actions/entry",&set)==vr::VRInputError_None&&input->GetActionHandle("/actions/entry/in/primary",&primary)==vr::VRInputError_None&&input->GetActionHandle("/actions/entry/in/upper",&upper)==vr::VRInputError_None&&input->GetActionHandle("/actions/entry/in/aim",&aim)==vr::VRInputError_None;
for(int i=0;i<20&&ok;i++){vr::VRActiveActionSet_t active{};active.ulActionSet=set;result=input->UpdateActionState(&active,sizeof(active),1);if(result!=vr::VRInputError_None){std::cerr<<"update="<<result<<"\n";ok=false;break;}std::this_thread::sleep_for(std::chrono::milliseconds(100));}
for(auto path:{"/user/hand/left","/user/hand/right"}){vr::VRInputValueHandle_t hand=0;input->GetInputSourceHandle(path,&hand);vr::InputDigitalActionData_t a{},b{};vr::InputPoseActionData_t pose{};auto e1=input->GetDigitalActionData(primary,&a,sizeof(a),hand),e2=input->GetDigitalActionData(upper,&b,sizeof(b),hand),e3=input->GetPoseActionDataRelativeToNow(aim,vr::TrackingUniverseStanding,0,&pose,sizeof(pose),hand);std::cout<<path<<" primary="<<e1<<"/"<<a.bActive<<" upper="<<e2<<"/"<<b.bActive<<" pose="<<e3<<"/"<<pose.bActive<<"/"<<pose.pose.bPoseIsValid<<" state="<<a.bState<<"/"<<b.bState<<"\n";
vr::VROverlayHandle_t button=0;auto* overlays=vr::VROverlay();if(!overlays->FindOverlay("framely.dock.button",&button)){
vr::VROverlayIntersectionParams_t ray{};ray.eOrigin=vr::TrackingUniverseStanding;for(int r=0;r<3;r++){ray.vSource.v[r]=pose.pose.mDeviceToAbsoluteTracking.m[r][3];ray.vDirection.v[r]=-pose.pose.mDeviceToAbsoluteTracking.m[r][2];}vr::VROverlayIntersectionResults_t hit{};bool intersects=overlays->ComputeOverlayIntersection(button,&ray,&hit);std::cout<<"dock visible="<<overlays->IsOverlayVisible(button)<<" hover="<<overlays->IsHoverTargetOverlay(button)<<" intersection="<<intersects<<" uv="<<hit.vUVs.v[0]<<","<<hit.vUVs.v[1]<<"\n";
}}
for(unsigned i=0;i<vr::k_unMaxTrackedDeviceCount;i++){if(system->GetTrackedDeviceClass(i)!=vr::TrackedDeviceClass_Controller)continue;char type[256]{};system->GetStringTrackedDeviceProperty(i,vr::Prop_ControllerType_String,type,sizeof(type));std::cout<<"controller="<<i<<" type="<<type<<"\n";}
float previousPull[2]{-1,-1};
for(int tick=0;tick<2400&&ok;tick++){
vr::VRActiveActionSet_t active{};active.ulActionSet=set;input->UpdateActionState(&active,sizeof(active),1);
if(tick%80==0){vr::TrackedDevicePose_t poses[vr::k_unMaxTrackedDeviceCount]{};system->GetDeviceToAbsoluteTrackingPose(vr::TrackingUniverseStanding,0,poses,vr::k_unMaxTrackedDeviceCount);std::cout<<"tracking";for(unsigned d=0;d<3;d++)std::cout<<" "<<d<<":"<<poses[d].bDeviceIsConnected<<"/"<<poses[d].bPoseIsValid;std::cout<<std::endl;}
for(auto path:{"/user/hand/left","/user/hand/right"}){vr::VRInputValueHandle_t hand=0;input->GetInputSourceHandle(path,&hand);vr::InputDigitalActionData_t a{},b{};input->GetDigitalActionData(primary,&a,sizeof(a),hand);input->GetDigitalActionData(upper,&b,sizeof(b),hand);
auto device=system->GetTrackedDeviceIndexForControllerRole(std::string(path).find("right")!=std::string::npos?vr::TrackedControllerRole_RightHand:vr::TrackedControllerRole_LeftHand);char model[256]{};system->GetStringTrackedDeviceProperty(device,vr::Prop_RenderModelName_String,model,sizeof(model));vr::RenderModel_ControllerMode_State_t mode{};vr::RenderModel_ComponentState_t primaryState{},upperState{};bool c1=vr::VRRenderModels()->GetComponentStateForDevicePath(model,"trigger",hand,&mode,&primaryState),c2=vr::VRRenderModels()->GetComponentStateForDevicePath(model,"bumper",hand,&mode,&upperState);vr::VRControllerState_t restInput{},fullInput{};fullInput.rAxis[1].x=1;vr::RenderModel_ComponentState_t rest{},full{};float pull=-1;bool calibrated=c1&&vr::VRRenderModels()->GetComponentState(model,"trigger",&restInput,&mode,&rest)&&vr::VRRenderModels()->GetComponentState(model,"trigger",&fullInput,&mode,&full)&&entry_trigger_pull(rest,full,primaryState,pull);int side=std::string(path).find("right")!=std::string::npos?1:0;bool changed=std::abs(pull-previousPull[side])>.05f;previousPull[side]=pull;
if(tick%80==0||changed)std::cout<<path<<" components="<<c1<<"/"<<c2<<" pressed="<<bool(primaryState.uProperties&vr::VRComponentProperty_IsPressed)<<"/"<<bool(upperState.uProperties&vr::VRComponentProperty_IsPressed)<<" calibrated="<<calibrated<<" pull="<<pull<<" actions="<<a.bActive<<"/"<<b.bActive<<"\n";
if(a.bChanged||b.bChanged){vr::InputPoseActionData_t pose{};input->GetPoseActionDataRelativeToNow(aim,vr::TrackingUniverseStanding,0,&pose,sizeof(pose),hand);std::cout<<path<<" primary="<<a.bState<<" upper="<<b.bState<<" pose="<<pose.pose.bPoseIsValid;
vr::VROverlayHandle_t overlay=0;auto* overlays=vr::VROverlay();if(!overlays->FindOverlay("framely.dock.button",&overlay)){vr::VROverlayIntersectionParams_t ray{};ray.eOrigin=vr::TrackingUniverseStanding;for(int r=0;r<3;r++){ray.vSource.v[r]=pose.pose.mDeviceToAbsoluteTracking.m[r][3];ray.vDirection.v[r]=-pose.pose.mDeviceToAbsoluteTracking.m[r][2];}vr::VROverlayIntersectionResults_t hit{};bool intersects=overlays->ComputeOverlayIntersection(overlay,&ray,&hit);std::cout<<" hover="<<overlays->IsHoverTargetOverlay(overlay)<<" intersection="<<intersects<<" uv="<<hit.vUVs.v[0]<<","<<hit.vUVs.v[1];}std::cout<<std::endl;}}
std::this_thread::sleep_for(std::chrono::milliseconds(25));
}
vr::VR_Shutdown();return ok?0:4;}
+10
View File
@@ -0,0 +1,10 @@
#include "launcher_pointer.h"
#include <cassert>
int main(){auto now=std::chrono::steady_clock::now();LauncherPointer pointer;int x=0,y=0;
pointer.begin(100,200,now);x=122;y=211;assert(pointer.constrain(x,y,now+std::chrono::milliseconds(180)));assert(x==100&&y==200);
// A 600 ms long press remains stable across many different jitter samples.
for(int ms=100;ms<=900;ms+=100){x=100+(ms%35);y=190;assert(pointer.constrain(x,y,now+std::chrono::milliseconds(ms)));assert(x==100&&y==200);}
x=126;y=215;assert(pointer.constrain(x,y,now+std::chrono::milliseconds(1100)));pointer.clear();assert(!pointer.holding(now));
pointer.begin(100,200,now);x=160;y=200;assert(!pointer.constrain(x,y,now+std::chrono::milliseconds(100)));assert(x==160);x=100;assert(!pointer.constrain(x,y,now+std::chrono::milliseconds(200)));
pointer.begin(100,200,now);x=100;y=200;assert(!pointer.constrain(x,y,now+std::chrono::seconds(3)));pointer.clear();assert(!pointer.constrain(x,y,now));
}
+69
View File
@@ -0,0 +1,69 @@
import React,{useState} from 'react';import{createRoot}from'react-dom/client';
import{Launcher,LauncherSettings,type LauncherConfig}from'../ui/src/launcher';import{configureLanguage}from'../ui/src/i18n';import type{Plugin}from'../ui/src/main';import{matchesSearch}from'../ui/src/launcher-search';import'../ui/src/style.css';
const wait=(ms=80)=>new Promise(r=>setTimeout(r,ms));const until=async(f:()=>any)=>{for(let i=0;i<160;i++){if(f())return;await wait(30);}throw Error('Timed out '+document.body.innerText.slice(0,300));};
let config:LauncherConfig={primaryTrigger:false,menuAutoClose:true,menuTimeoutSeconds:10};let saved:string[]=[];let order:string[]=[];let steamFavorites:number[]=[42];let settings=false;let redraw:()=>void;let delay=80;const calls:{method:string;params:any}[]=[];
const plugins:Record<string,Plugin>={
'demo.alpha':{manifest:{id:'demo.alpha',icon:'icon.png',name:'Termix',description:'Terminal',author:'Framely',version:'1.0.0',ui:{quickPage:'page.js',windows:{}}},enabled:true,favorite:true,order:0},
'demo.beta':{manifest:{id:'demo.beta',icon:'icon.png',name:'透视调色',description:'Color',author:'Framely',version:'1.0.0',ui:{quickPage:'page.js',windows:{}}},enabled:true,favorite:false,order:1},
'demo.off':{manifest:{id:'demo.off',name:'Disabled app',description:'',author:'Framely',version:'1.0.0',ui:{windows:{}}},enabled:false,favorite:true,order:2},
};
const local=[{id:'terminal.desktop',name:'Desktop terminal',kind:'desktop'},{id:'default/sakura',name:'さくら',kind:'lepton'},{id:'default/tokyo',name:'東京',kind:'lepton'}];
window.fetch=async(url,init)=>{if(String(url)!=='/api')throw Error('Unexpected fetch');const{method,params}=JSON.parse(String(init?.body));calls.push({method,params});let result:any=true;
if(method==='steam.list'){await wait(delay);result=[{id:42,name:'Half-Life: Alyx',icon:'/preview-icons/546560.jpg',iconFit:'cover'}];}
else if(method==='desktop.list'){await wait(delay);result=local;}
else if(method==='launcher.search.index'){await wait(150);result=Object.fromEntries(params.names.map((name:string)=>[name,{terms:name==='透视调色'?['toushitiaose','tsts']:name==='さくら'?['sakura','skr']:name==='東京'?['toukyou','tuku']:name==='Half-Life: Alyx'?['halflifealyx','hla']:[name.toLowerCase().replace(/\s/g,'')]}]));}
else if(method==='launcher.favorite'){const{key,favorite}=params;if(key.startsWith('plugin:'))plugins[key.slice(7)].favorite=favorite;else if(key.startsWith('steam:'))steamFavorites=favorite?[...steamFavorites,+key.slice(6)]:steamFavorites.filter(id=>id!==+key.slice(6));else saved=favorite?[...saved,key]:saved.filter(k=>k!==key);}
else if(method==='launcher.settings.save')config=params;
return new Response(JSON.stringify({result}));};
function Fixture(){const[,render]=useState(0);redraw=()=>render(n=>n+1);return settings?<div className="app manager"><main className="content"><div className="list-heading"><div><h1>{document.documentElement.lang==='zh-CN'?'启动台':'Launcher'}</h1><p>{document.documentElement.lang==='zh-CN'?'启动方式、菜单与分类。':'Launch controls, menus and categories.'}</p></div></div><LauncherSettings config={config} refresh={async()=>redraw()}/></main></div>:<Launcher plugins={plugins} safeMode={false} config={config} favorites={steamFavorites} localFavorites={saved} order={order} refresh={async()=>redraw()}/>;}
const category=(name:string)=>document.querySelector<HTMLButtonElement>(`.launcher-filters button[aria-label="${name}"]`)!;
const labels=()=>[...document.querySelectorAll('.launch-name')].map(n=>n.textContent);
const input=()=>document.querySelector<HTMLInputElement>('.launcher-search input')!;
function query(value:string){Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value')!.set!.call(input(),value);input().dispatchEvent(new Event('input',{bubbles:true}));}
const favorite=(name:string)=>document.querySelector<HTMLButtonElement>(`.launch-icon[aria-label="${name}"]`)!.parentElement!.querySelector<HTMLButtonElement>('.launch-favorite')!;
(window as any).runInstallReviewChecks=async()=>{try{
configureLanguage('en-US',[]);redraw();await until(()=>!document.querySelector('.launcher-initializing'));
if(category('Favorites').getAttribute('aria-pressed')!=='true'||labels().sort().join('|')!=='Half-Life: Alyx|Termix')throw Error('Default favorites / disabled filtering incorrect '+labels().join('|'));
const keys=[...document.querySelectorAll('.launcher-filters button')].map(n=>n.getAttribute('aria-label'));if(keys.join('|')!=='Favorites|All|Plugin|Steam|Lepton|Desktop apps')throw Error('Category order '+keys);
category('All').click();await until(()=>labels().length===7);const initialGrid=document.querySelector('.launcher-grid')!.getBoundingClientRect();const initialFilters=document.querySelector('.launcher-filters')!.getBoundingClientRect();
const stable=()=>{const g=document.querySelector('.launcher-grid')!.getBoundingClientRect(),f=document.querySelector('.launcher-filters')!.getBoundingClientRect();if(g.x!==initialGrid.x||g.y!==initialGrid.y||g.height!==570||f.y!==initialFilters.y)throw Error('Search / category changed fixed layout');};
await wait(400);const searchBottom=document.querySelector('.launcher-search')!.getBoundingClientRect().bottom;const artworkTop=document.querySelector('.launch-disc')!.getBoundingClientRect().top;if(artworkTop-searchBottom<72)throw Error('Search is too close to the icon artwork');
// Every app kind keeps its position when favorited or unfavorited.
const initialOrder=labels().join('|');
for(const name of ['Termix','Half-Life: Alyx','透视调色','Framely','Desktop terminal','さくら','東京']){
const was=favorite(name).getAttribute('aria-pressed')==='true';
for(const checked of [!was,was]){
favorite(name).click();await until(()=>favorite(name).getAttribute('aria-pressed')===String(checked));await until(()=>!favorite(name).disabled);
if(labels().join('|')!==initialOrder)throw Error('Favorite reordered '+name);
if(checked){await until(()=>getComputedStyle(favorite(name)).opacity==='1');if(!favorite(name).classList.contains('selected')||getComputedStyle(favorite(name)).opacity!=='1'||favorite(name).querySelector('svg')!.getAttribute('fill')!=='currentColor')throw Error('Favorite state is not visible '+name);}
}
}
// Explicit manual ordering survives favorite changes, refresh and reopening.
order=[...document.querySelectorAll<HTMLElement>('[data-launch-key]')].map(n=>n.dataset.launchKey!).reverse();redraw();await until(()=>labels().join('|')!==initialOrder);const manualOrder=labels().join('|');
favorite('Framely').click();await until(()=>saved.includes('framely'));await until(()=>!favorite('Framely').disabled);if(labels().join('|')!==manualOrder)throw Error('Manual order changed after favorite');
window.dispatchEvent(new Event('framely.launcher.open'));await until(()=>category('Favorites').getAttribute('aria-pressed')==='true');category('All').click();await until(()=>labels().length===7);if(labels().join('|')!==manualOrder)throw Error('Reopening lost manual order');
favorite('Framely').click();await until(()=>!saved.includes('framely'));await until(()=>!favorite('Framely').disabled);if(labels().join('|')!==manualOrder)throw Error('Manual order changed after removing favorite');order=[];redraw();await until(()=>labels().join('|')===initialOrder);
favorite('Framely').click();await until(()=>saved.includes('framely'));await until(()=>!document.querySelector('.launch-favorite:disabled'));favorite('Desktop terminal').click();await until(()=>saved.includes('desktop:terminal.desktop'));await until(()=>!document.querySelector('.launch-favorite:disabled'));favorite('さくら').click();await until(()=>saved.includes('lepton:default/sakura'));await until(()=>!document.querySelector('.launch-favorite:disabled'));
category('Favorites').click();await until(()=>labels().length===5);if(!labels().includes('Framely')||!labels().includes('Desktop terminal')||!labels().includes('さくら'))throw Error('New types absent from Favorites');
await wait(500);console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_FAVORITES_EN');
configureLanguage('zh-CN',[]);redraw();await wait(500);console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_FAVORITES_ZH');configureLanguage('en-US',[]);redraw();await wait();
// Search remains in the selected category, and key strokes reuse an index.
category('Plugin').click();await until(()=>labels().length===3);await until(()=>calls.some(c=>c.method==='launcher.search.index'));await wait(250);const indexCount=calls.filter(c=>c.method==='launcher.search.index').length;
for(const q of ['toushi','tiaose','tsts','TSTS']){query(q);await until(()=>labels().length===1);if(labels()[0]!=='透视调色')throw Error('Pinyin search '+q);stable();}
query('sakura');await until(()=>labels().length===0);if(!document.body.innerText.includes('No matching apps'))throw Error('Missing no results');query('');await until(()=>labels().length===3);
category('Lepton').click();for(const q of ['sakura','skr','SKR']){query(q);await until(()=>labels().length===1);if(labels()[0]!=='さくら')throw Error('Kana search '+q);}query('toukyou');await until(()=>labels().length===1);if(labels()[0]!=='東京')throw Error('Japanese kanji search');query('');
category('Steam').click();query('HLA');await until(()=>labels().length===1);if(labels()[0]!=='Half-Life: Alyx')throw Error('English initials');query('');
if(calls.filter(c=>c.method==='launcher.search.index').length!==indexCount)throw Error('Typing rebuilt indexes');
input().focus();if(getComputedStyle(input()).outlineStyle!=='none'&&getComputedStyle(input()).outlineWidth!=='0px')throw Error('Search focus still has an outline');await until(()=>calls.some(c=>c.method==='host.keyboard'));window.dispatchEvent(new CustomEvent('framely.keyboard',{detail:true}));(window as any).__framelyCommitKeyboard('HLA');await until(()=>input().value==='HLA');const closeCount=calls.filter(c=>c.method==='host.launcher.close').length;window.dispatchEvent(new CustomEvent('framely.launcher.navigate',{detail:2}));window.dispatchEvent(new Event('framely.back'));document.querySelector('.launcher-shell')!.dispatchEvent(new MouseEvent('click',{bubbles:true}));await wait();if(category('Steam').getAttribute('aria-pressed')!=='true'||calls.filter(c=>c.method==='host.launcher.close').length!==closeCount)throw Error('Keyboard allowed launcher dismissal/navigation');window.dispatchEvent(new CustomEvent('framely.keyboard',{detail:false}));input().blur();query('');
category('Plugin').click();query('tsts');await wait(450);console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_SEARCH_EN');configureLanguage('zh-CN',[]);redraw();await wait(450);console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_SEARCH_ZH');configureLanguage('en-US',[]);redraw();query('');
config={...config,allCategories:[]};redraw();category('All').click();await until(()=>labels().length===0);category('Favorites').click();await until(()=>labels().length===5);category('Plugin').click();await until(()=>labels().length===3);
config={...config,allCategories:['desktop']};redraw();category('All').click();await until(()=>labels().join('|')==='Desktop terminal');query('termix');await until(()=>labels().length===0);query('');stable();
window.dispatchEvent(new Event('framely.launcher.open'));await until(()=>category('Favorites').getAttribute('aria-pressed')==='true');if(input().value!=='')throw Error('Opening did not clear query');
// Late refresh must not override an explicit category selection.
delay=350;window.dispatchEvent(new Event('framely.launcher.open'));await wait(30);category('Steam').click();await wait(450);if(category('Steam').getAttribute('aria-pressed')!=='true')throw Error('Refresh overwrote category selection');delay=80;
saved=[];steamFavorites=[];plugins['demo.alpha'].favorite=false;redraw();window.dispatchEvent(new Event('framely.launcher.open'));await until(()=>category('All').getAttribute('aria-pressed')==='true');await until(()=>!document.querySelector('.launcher-initializing'));if(labels().join('|')!=='Desktop terminal')throw Error('No favorites fallback ignored All membership');
favorite('Desktop terminal').click();await until(()=>saved.length===1);window.dispatchEvent(new Event('framely.launcher.open'));await until(()=>category('Favorites').getAttribute('aria-pressed')==='true');favorite('Desktop terminal').click();await until(()=>labels().length===0);if(category('Favorites').getAttribute('aria-pressed')!=='true'||!document.body.innerText.includes('No favorites yet'))throw Error('Removing final favorite navigated away');window.dispatchEvent(new Event('framely.launcher.open'));await until(()=>category('All').getAttribute('aria-pressed')==='true');
if(!matchesSearch('Termix','termix')||!matchesSearch('École','ecole')||matchesSearch('Alpha','beta')||matchesSearch('ガ','カ'))throw Error('Search normalization');
settings=true;redraw();await until(()=>document.querySelectorAll('[role=switch]').length===6);const switches=document.querySelectorAll<HTMLInputElement>('[role=switch]');switches[0].click();await until(()=>config.primaryTrigger);await until(()=>!document.querySelector('[role=switch]:disabled'));switches[2].click();await until(()=>(config.allCategories??[]).includes('plugin'));await wait(350);console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_SETTINGS_EN');configureLanguage('zh-CN',[]);redraw();await wait(350);console.log('FRAMELY_PREVIEW_INSTALL_LAUNCHER_SETTINGS_ZH');console.log('FRAMELY_BRIDGE_PASS');
}catch(e){console.error('FRAMELY_BRIDGE_FAIL '+e+' '+(e as Error).stack);}};
createRoot(document.getElementById('root')!).render(<Fixture/>);wait(150).then(()=>console.log('FRAMELY_VIEW_READY'));
+35
View File
@@ -0,0 +1,35 @@
import {configureLanguage} from '../ui/src/i18n';
const wait=(ms=80)=>new Promise(r=>setTimeout(r,ms));
const until=async(f:()=>any)=>{for(let i=0;i<160;i++){if(f())return;await wait(25);}throw Error('Timeout '+document.body.innerText.slice(0,300));};
history.replaceState(null,'','/manager');
const plugin={manifest:{id:'demo',name:'Demo plugin',version:'1.0.0',description:'A demo plugin',author:'Community',ui:{windows:{}}},enabled:true,favorite:false,order:0};
const source={id:'community',name:'Community',url:'https://example.org/catalog.json',enabled:true,allowHttp:false};
const sub={id:'daily',name:'Daily sources',url:'https://example.org/subscription.json',enabled:true,autoRefresh:true,entries:[],pending:[],nextRefresh:0};
const database:any={plugins:{demo:plugin},sources:[source],subscriptions:[sub],safeMode:false,language:'en-US',launcher:{primaryTrigger:false,menuAutoClose:true,menuTimeoutSeconds:10,allCategories:['plugin','steam','lepton','desktop']},networkPanel:{enabled:true,port:15915,passwordEnabled:true},proxy:{http:'',github:''},updateSource:{url:'https://example.org/update.json'},updateCheck:{enabled:true,intervalHours:6}};
const calls:any[]=[];
window.fetch=async(_url,init)=>{const{method,params}=JSON.parse(String(init?.body));calls.push({method,params});let result:any=true;
if(method==='status')result={version:'0.4.3-preview.2',agreement:{version:1,accepted:true},database,running:[],notifications:[],inbox:[]};
else if(method==='language.list')result={packs:[],invalidFiles:[]};else if(method==='ui.events')result={cursor:0,events:[]};else if(method==='network.status')result={passwordConfigured:true,localOrigin:'http://localhost:15915',ips:[],listener:{}};
else if(method==='catalog.start')result={job:'catalog'};else if(method==='job.status')result={id:'catalog',phase:'done',result:[{source,catalog:{name:'Community',plugins:[{...plugin.manifest,apiVersion:1,url:'https://example.org/demo.framely',sha256:'a'.repeat(64)}]}}]};
else if(method==='network.save')Object.assign(database.networkPanel,params);else if(method==='safeMode')database.safeMode=params.enabled;else if(method==='sources.save')database.sources=params.sources;else if(method==='subscriptions.change')Object.assign(sub,params);else if(method==='system.check.settings.save')database.updateCheck=params.settings;
return new Response(JSON.stringify({result}));};
const nav=(label:string)=>[...document.querySelectorAll<HTMLButtonElement>('.workspace>nav button')].find(b=>b.textContent===label)!;
const width=(selector:string)=>{const node=document.querySelector<HTMLElement>(selector)!;if(!node)throw Error('Missing '+selector);const parent=node.parentElement!;const style=getComputedStyle(parent);const available=parent.clientWidth-parseFloat(style.paddingLeft)-parseFloat(style.paddingRight);if(Math.abs(node.getBoundingClientRect().width-available)>2)throw Error('Unused width '+selector+' '+node.getBoundingClientRect().width+'/'+available);};
const switcher=(label:string)=>document.querySelector<HTMLButtonElement>(`[role=switch][aria-label="${label}"]`)!;
(window as any).runInstallReviewChecks=async()=>{try{
await until(()=>!!document.querySelector('.plugin-row'));if(!switcher('Enable Demo plugin').classList.contains('ui-switch'))throw Error('Plugin switch is not shared');width('.plugin-row');
nav('Settings').click();await until(()=>!!document.querySelector('.network-password'));for(const selector of ['.language-picker','.network-password','.network-port label','.proxy-fields','.switch-row'])width(selector);
if(document.querySelector('.content input[type=checkbox]'))throw Error('Checkbox left in settings');
switcher('Safe mode').click();await until(()=>database.safeMode);await until(()=>!switcher('Safe mode').disabled);
switcher('Use an access password').click();await until(()=>!document.querySelector('.network-password'));switcher('Use an access password').click();await until(()=>!!document.querySelector('.network-password'));
await wait(450);console.log('FRAMELY_PREVIEW_INSTALL_MANAGER_SETTINGS_EN');
nav('Sources').click();await until(()=>document.querySelectorAll('.source-row').length===2);width('.source-row');switcher('Refresh daily').click();await until(()=>!sub.autoRefresh);await until(()=>!switcher('Refresh daily').disabled);
const add=[...document.querySelectorAll<HTMLButtonElement>('.content button')].find(b=>b.textContent==='Add plugin source')!;add.click();await until(()=>!!document.querySelector('.source-form'));width('.source-form');if(document.querySelector('.content input[type=checkbox]'))throw Error('Source still has a checkbox');
nav('Plugin library').click();await until(()=>!!document.querySelector('.store-card'));width('.store-card');document.querySelector<HTMLButtonElement>('.store-title')!.click();await until(()=>!!document.querySelector('.store-detail'));width('.store-detail');width('.detail-summary');
nav('Launcher').click();await until(()=>!!document.querySelector('.launcher-settings'));width('.launcher-settings .switch-row');width('.launcher-settings label');
nav('Notifications').click();await until(()=>!!document.querySelector('.notification-global-options'));width('.notification-global-options');width('.notification-plugin-list');
nav('About').click();await until(()=>!!document.querySelector('.automatic-update-settings'));width('.automatic-update-settings .framely-select');if(!switcher('Check for updates automatically').classList.contains('ui-switch'))throw Error('Update switch is not shared');
database.language='zh-CN';configureLanguage('zh-CN',[]);nav('Settings').click();await until(()=>document.documentElement.lang==='zh-CN');nav('设置').click();await until(()=>!!document.querySelector('.network-password'));width('.network-password');await wait(450);console.log('FRAMELY_PREVIEW_INSTALL_MANAGER_SETTINGS_ZH');
console.log('FRAMELY_BRIDGE_PASS');
}catch(e){console.error('FRAMELY_BRIDGE_FAIL '+e+' '+(e as Error).stack);}};
void import('../ui/src/main');
+15
View File
@@ -0,0 +1,15 @@
#include "notification_badge.h"
#include <cassert>
int main(){
std::vector<uint8_t> original(128*128*4,40),pixels=original;
notification_badge(pixels,0);assert(pixels==original);
notification_badge(pixels,1);assert(pixels!=original);
auto one=pixels;pixels=original;notification_badge(pixels,12);assert(pixels!=one);
pixels=original;notification_badge(pixels,99);auto ninety_nine=pixels;
pixels=original;notification_badge(pixels,100);assert(pixels!=ninety_nine);
auto maximum=pixels;pixels=original;notification_badge(pixels,256);assert(pixels==maximum);
for(int y=0;y<128;y++)for(int x=0;x<128;x++)if(y>=33||x<74)
for(int c=0;c<4;c++)assert(pixels[(y*128+x)*4+c]==40);
std::vector<uint8_t> invalid(12,0);notification_badge(invalid,1);assert(invalid==std::vector<uint8_t>(12,0));
}
+43 -2
View File
@@ -2,6 +2,47 @@
#include <cassert>
int main(){
// A side-offset toast must face the eye, including tilted/rotated tracking frames.
for(float yaw:{-.7f,0.f,.8f})for(float tilt:{-.6f,0.f,.5f})for(float radius:{.6f,1.3f,2.f}){
float cy=std::cos(yaw),sy=std::sin(yaw),ct=std::cos(tilt),st=std::sin(tilt);
vr::HmdMatrix34_t head{{{cy,sy*st,sy*ct,.6f},{0,ct,-st,.8f},{-sy,cy*st,cy*ct,-.7f}}};
NotificationPlacement toast{};assert(notification_placement(head,radius,toast));
auto& m=toast.transform;
vr::HmdVector3_t eye{},right{{m.m[0][0],m.m[1][0],m.m[2][0]}},up{{m.m[0][1],m.m[1][1],m.m[2][1]}};
float distance=0;
for(int r=0;r<3;r++){
eye.v[r]=head.m[r][3]-m.m[r][3];distance+=eye.v[r]*eye.v[r];
float expected=head.m[r][3]+head.m[r][0]*.24f+head.m[r][1]*.12f-head.m[r][2]*1.f;
assert(std::abs(expected-m.m[r][3])<1e-6f);
}
assert(normalize_dock_vector(eye));auto normal=cross_dock_vector(right,up);
for(int r=0;r<3;r++){assert(std::abs(eye.v[r]-m.m[r][2])<1e-6f);assert(std::abs(normal.v[r]-m.m[r][2])<1e-6f);}
assert(toast.radius==radius&&toast.width==.32f);
// Both ends of the compact cylindrical surface remain front-facing to the eye.
for(float side:{-1.f,1.f}){
float angle=side*toast.width*.5f/radius,dot=0;
for(int r=0;r<3;r++){
float point=m.m[r][3]+right.v[r]*radius*std::sin(angle)+normal.v[r]*radius*(1-std::cos(angle));
float front=normal.v[r]*std::cos(angle)-right.v[r]*std::sin(angle);
dot+=front*(head.m[r][3]-point);
}
assert(dot>0);
}
}
NotificationPlacement invalid{};vr::HmdMatrix34_t zero{};assert(!notification_placement(zero,1.3f,invalid));
vr::HmdMatrix34_t identity{{{1,0,0,0},{0,1,0,0},{0,0,1,0}}};
assert(!notification_placement(identity,0,invalid));assert(!notification_placement(identity,NAN,invalid));
// A card painted at the top of the UI must hit at the top, not below it.
std::vector<uint8_t> card(600*360*4,0);
for(int y=360-8-150;y<360-8;y++)for(int x=8;x<592;x++)card[(y*600+x)*4+3]=255;
auto top=notification_bounds(card,600,360,1);
assert(top.x==8&&top.y==8&&top.width==584&&top.height==150);
NotificationClick click;auto now=std::chrono::steady_clock::now();int x=110,y=106;
click.begin(100,100,now);assert(click.hold(x,y,now+std::chrono::milliseconds(80)));
assert(click.release(x,y,now+std::chrono::milliseconds(180)));assert(x==100&&y==100&&!click.active);
click.begin(100,100,now);assert(!click.hold(140,100,now));x=101;y=100;assert(!click.release(x,y,now));assert(x==101);
click.begin(100,100,now);x=y=100;assert(!click.release(x,y,now+std::chrono::seconds(1)));
click.begin(100,100,now);click.clear();assert(!click.release(x,y,now));
std::vector<uint8_t> pixels(12*8*4,0);
assert(!notification_bounds(pixels,12,8,2).visible());
// RGB left over in a transparent frame must not capture input.
@@ -11,13 +52,13 @@ int main(){
pixels[(4*12+9)*4+3]=1;
auto bounds=notification_bounds(pixels,12,8,2);
assert(bounds.visible());
assert(bounds.x==1&&bounds.y==.5f&&bounds.width==4&&bounds.height==2);
assert(bounds.x==1&&bounds.y==1.5f&&bounds.width==4&&bounds.height==2);
// Dismissing/expiring the final toast yields an empty frame again.
pixels[(1*12+2)*4+3]=0;pixels[(4*12+9)*4+3]=0;
assert(!notification_bounds(pixels,12,8,2).visible());
pixels.back()=255;
bounds=notification_bounds(pixels,12,8,2);
assert(bounds.x==5.5f&&bounds.y==3.5f&&bounds.width==.5f&&bounds.height==.5f);
assert(bounds.x==5.5f&&bounds.y==0&&bounds.width==.5f&&bounds.height==.5f);
assert(!notification_bounds(pixels,12,8,0).visible());
assert(!notification_bounds({},12,8,2).visible());
}
+92
View File
@@ -0,0 +1,92 @@
// Exercise the real notification controls, including failures and hidden headset views.
import React,{useState} from 'react';
import {createRoot} from 'react-dom/client';
import {NotificationSettings,PopupPermission,useReadInbox,type NotificationConfig} from '../ui/src/notification-settings';
import {NotificationCenter,type NotificationEntry} from '../ui/src/notifications';
import {configureLanguage} from '../ui/src/i18n';
import '../ui/src/style.css';
const root=createRoot(document.getElementById('root')!);
const wait=(ms=80)=>new Promise(r=>setTimeout(r,ms));
const plugins={
'capture.clip':{manifest:{id:'capture.clip',name:'Clip capture',description:'Capture your session',version:'1.0.0'},enabled:true,order:0},
'capture.off':{manifest:{id:'capture.off',name:'Frame diagnostics',description:'Device diagnostics',version:'1.0.0'},enabled:false,order:1},
};
let config:NotificationConfig={popups:true,badge:true,plugins:{}},fail=false,visible=false,readCalls=0;
const messages:NotificationEntry[]=[{plugin:'capture.clip',pluginName:'Clip capture',createdAt:Date.now(),expiresAt:null,toast:false,inInbox:true,notification:{id:'saved',title:'录像已保存',body:'录像已经保存,可以稍后打开。',inbox:true}}];
const calls:any[]=[];
window.fetch=async(_url,init)=>{
const{method,params}=JSON.parse(String(init?.body));calls.push({method,params});let result:any=true;
if(method==='status')result={version:'0.4.2-preview.12',agreement:{accepted:true,version:'fixture'},database:{plugins,sources:[],safeMode:false,language:'en-US',notificationSettings:config},notifications:[],inbox:messages,notificationBadge:0,running:[]};
else if(method==='language.list')result={packs:[]};
else if(method==='ui.events')result={events:[],cursor:0};
else if(method==='notification.settings.save'){
if(fail)return new Response(JSON.stringify({error:'Fixture settings failed'}));
config={...config,plugins:{...config.plugins}};
const preference=typeof params.plugin==='string'?(config.plugins[params.plugin]={...(config.plugins[params.plugin]??{popups:true,badge:true})}):config;
for(const key of ['popups','badge'] as const)if(typeof params[key]==='boolean')preference[key]=params[key];
}else if(method==='ui.visibility.get')result={known:true,pageVisible:visible};
else if(method==='notification.read'){
readCalls++;
for(const item of params.entries){const n=messages.find(n=>n.plugin===item.plugin&&n.notification.id===item.id&&n.createdAt===item.createdAt);if(n)n.read=true;}
}else if(!['host.manager.open','host.haptic'].includes(method))throw Error('Unexpected API '+method);
return new Response(JSON.stringify({result}));
};
let switchMode:(value:'settings'|'quick')=>void,refresh:()=>Promise<void>;
function Fixture(){
const[mode,setMode]=useState<'settings'|'quick'>('settings'),[,update]=useState(0);
switchMode=setMode;refresh=async()=>update(v=>v+1);
useReadInbox(mode==='quick',messages,refresh);
return <div className={`app ${mode==='settings'?'manager':'quick'}`}><main className="content" style={mode==='quick'?{maxWidth:600,margin:'0 auto',width:'100%'}:undefined}>{mode==='settings'?<NotificationSettings config={config} plugins={plugins} refresh={refresh}/>:<NotificationCenter inbox items={messages} plugins={plugins} refresh={refresh} controls={<PopupPermission config={config} refresh={refresh}/>}/>}</main></div>;
}
function control(label:string){const node=document.querySelector(`[role=switch][aria-label="${label}"]`);if(!node)throw Error('Missing switch '+label);return node as HTMLButtonElement;}
async function until(check:()=>boolean){for(let i=0;i<60;i++){if(check())return;await wait();}throw Error('UI timeout');}
(window as any).runInstallReviewChecks=async()=>{try{
configureLanguage('zh-CN',[]);await refresh();await wait(150);
if(document.querySelectorAll('.notification-plugin-row').length!==3||document.querySelectorAll('[role=switch]').length!==8)throw Error('Installed plugins or notification controls missing');
if(!document.body.textContent!.includes('已停用'))throw Error('Disabled plugin omitted');
if(!document.body.textContent!.includes('本体通知,包括检查更新提醒。'))throw Error('Framely notification source missing');
const globals=document.querySelector('.notification-global-options') as HTMLElement,list=document.querySelector('.notification-plugin-list') as HTMLElement;
if(Math.abs(globals.getBoundingClientRect().width-list.getBoundingClientRect().width)>1)throw Error('Global options and app list widths differ');
const globalSwitch=control('悬浮通知').getBoundingClientRect(),popupSwitch=control('Framely:悬浮').getBoundingClientRect();
if(Math.abs(globalSwitch.left-popupSwitch.left)>1)throw Error('Global and app popup switch columns are misaligned');
control('Framely:悬浮').click();await until(()=>control('Framely:悬浮').getAttribute('aria-checked')==='false');
control('Framely:角标').click();await until(()=>control('Framely:角标').getAttribute('aria-checked')==='false');
if(!config.popups||!config.badge||config.plugins[''].popups||config.plugins[''].badge)throw Error('Core preferences changed global policy');
if(!calls.some(c=>c.method==='notification.settings.save'&&c.params.plugin===''&&c.params.popups===false))throw Error('Framely popup preference was saved as global');
console.log('FRAMELY_PREVIEW_INSTALL_NOTIFICATION_SETTINGS_ZH');
fail=true;control('悬浮通知').click();await until(()=>!!document.querySelector('[role=alert]'));
if(!config.popups||control('悬浮通知').getAttribute('aria-checked')!=='true')throw Error('Failed save changed switch');
fail=false;control('悬浮通知').click();await until(()=>control('悬浮通知').getAttribute('aria-checked')==='false');
if(!config.badge)throw Error('Popup switch changed badge policy');
control('Clip capture:角标').click();await until(()=>control('Clip capture:角标').getAttribute('aria-checked')==='false');
if(config.plugins['capture.clip'].popups!==true)throw Error('Plugin badge switch changed popup policy');
control('Frame diagnostics:悬浮').click();await until(()=>control('Frame diagnostics:悬浮').getAttribute('aria-checked')==='false');
control('启动图标角标').click();await until(()=>control('启动图标角标').getAttribute('aria-checked')==='false');
if(config.plugins['capture.clip'].badge!==false||config.plugins['capture.off'].popups!==false)throw Error('Global switch erased plugin preferences');
const search=document.querySelector('[aria-label="搜索通知应用"]') as HTMLInputElement;
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value')!.set!.call(search,'Frame diagnostics');search.dispatchEvent(new Event('input',{bubbles:true}));await wait();
if(document.querySelectorAll('.notification-plugin-row').length!==1)throw Error('Plugin search failed');
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value')!.set!.call(search,'');search.dispatchEvent(new Event('input',{bubbles:true}));await wait();
configureLanguage('en-US',[]);await refresh();await wait(180);
if(!document.body.textContent!.includes('Launcher badge')||!document.body.textContent!.includes('App notifications'))throw Error('English settings copy missing');
console.log('FRAMELY_PREVIEW_INSTALL_NOTIFICATION_SETTINGS_EN');
for(const row of document.querySelectorAll('.notification-plugin-row'))if(row.scrollWidth>row.clientWidth)throw Error('Plugin switches overflow the settings row');
switchMode('quick');configureLanguage('zh-CN',[]);await wait(180);
if(control('允许通知').getAttribute('aria-checked')!=='false'||!document.body.textContent!.includes('悬浮已关闭'))throw Error('Quick popup switch out of sync');
if(readCalls)throw Error('Hidden headset view marked notifications as read');
console.log('FRAMELY_PREVIEW_INSTALL_NOTIFICATION_PERMISSION_ZH');
control('允许通知').click();await until(()=>control('允许通知').getAttribute('aria-checked')==='true');
if(!config.popups||config.badge)throw Error('Quick switch changed unrelated setting');
(document.querySelector('[aria-label="通知设置"]') as HTMLButtonElement).click();await wait();
if(!calls.some(c=>c.method==='host.manager.open'&&c.params.page==='notification-settings'))throw Error('Notification settings entry target missing');
visible=true;await until(()=>readCalls>0);
if(!messages[0].read||!document.querySelector('.inbox-message'))throw Error('Reading inbox removed message');
root.unmount();history.replaceState(null,'','/manager#notification-settings');await import('../ui/src/main');
await until(()=>!!document.querySelector('.notification-settings'));
const nav=[...document.querySelectorAll('nav button')].find(b=>b.textContent==='Notifications');
if(!nav||nav.getAttribute('aria-current')!=='page')throw Error('Manager notification settings navigation missing');
if(document.querySelectorAll('.notification-plugin-row').length!==3)throw Error('Manager notification settings omitted notification source');
await wait(180);console.log('FRAMELY_PREVIEW_INSTALL_NOTIFICATION_MANAGER_EN');
console.log('FRAMELY_BRIDGE_PASS');
}catch(e){console.error('FRAMELY_BRIDGE_FAIL '+e);}};
root.render(<Fixture/>);wait(150).then(()=>console.log('FRAMELY_VIEW_READY'));
+104
View File
@@ -0,0 +1,104 @@
// Exercise the actual notification views and quick menu in CEF, including saved messages and expiry.
import React,{useState} from 'react';
import {createRoot} from 'react-dom/client';
import {NotificationCenter,type NotificationEntry} from '../ui/src/notifications';
import {configureLanguage} from '../ui/src/i18n';
import '../ui/src/style.css';
const root=createRoot(document.getElementById('root')!);
const wait=(ms=80)=>new Promise(r=>setTimeout(r,ms));
const plugin={manifest:{id:'capture.clip',name:'Clip capture',description:'Capture your session',version:'1.0.0',author:'Framely',ui:{windows:{}}},enabled:true,favorite:false,order:0};
const plugins:Record<string,typeof plugin>={'capture.clip':plugin,'capture.off':{...plugin,enabled:false,order:1,manifest:{...plugin.manifest,id:'capture.off',name:'Disabled capture'}}};
const entry=(id:string,extra:Partial<NotificationEntry>={}):NotificationEntry=>({plugin:'capture.clip',pluginName:'Clip capture',createdAt:Date.now(),expiresAt:Date.now()+8000,toast:true,inInbox:true,notification:{id,title:'录像已保存',body:'录像已经保存,可以打开文件或继续录制。',inbox:true,actions:[{id:'open',label:'打开录像'}]},...extra});
let entries=[entry('saved'),entry('transient',{inInbox:false,notification:{id:'transient',title:'临时消息',body:'只显示浮动通知'}}),entry('update',{plugin:'',pluginName:'Framely',update:{version:'0.4.3-preview.1'},notification:{id:'update',title:'Update',body:'New release',actions:[{id:'ignore',label:'Ignore'},{id:'open',label:'Open updates'}]}})];
let language='zh-CN',fail=false,calls:any[]=[],render:(inbox:boolean)=>void;
const status=()=>({version:'0.4.2-preview.12',agreement:{accepted:true,version:'fixture'},database:{plugins,sources:[],safeMode:false,language},notifications:entries.filter(n=>n.toast),inbox:entries.filter(n=>n.inInbox),notificationsCount:entries.length,running:[]});
window.fetch=async(_url,init)=>{
const{method,params}=JSON.parse(String(init?.body));let result:any=true;
if(method==='status')result=status();
else if(method==='language.list')result={packs:[]};
else if(method==='language.save'){language=params.language;calls.push({method,params});}
else if(method==='host.manager.open'){calls.push({method,params});}
else if(method==='ui.events')result={events:[],cursor:0};
else if(method==='ui.visibility.get')result={known:false,pageVisible:false};
else if(method==='notification.read'){
for(const item of params.entries){const n=entries.find(n=>n.plugin===item.plugin&&n.notification.id===item.id&&n.createdAt===item.createdAt);if(n)n.read=true;}
}
else if(method.startsWith('notification.')){
calls.push({method,params});
const n=entries.find(n=>n.plugin===params.plugin&&n.notification.id===params.id);
if(!n)throw Error('unknown notification');
if(params.createdAt!==n.createdAt)throw Error('stale notification');
if(fail)return new Response(JSON.stringify({error:'Fixture action failed'}));
if(method==='notification.action'){
const a=n.notification.actions!.find(a=>a.id===params.action)!;
n.toast=a.closeOnClick===false?n.toast:false;n.inInbox=a.removeFromInboxOnClick===false?n.inInbox:false;
if(n.update&&a.id==='open')result={openUpdates:true};
}else if(method==='notification.dismiss')n.toast=false;
else if(method==='notification.remove'){n.toast=false;n.inInbox=false;}
}else if(!['host.haptic','host.keyboard','host.manager.open','host.menu.close'].includes(method))throw Error('unexpected API '+method);
return new Response(JSON.stringify({result}));
};
function Fixture(){const[value,setValue]=useState(entries),[inbox,setInbox]=useState(true);render=inbox=>{setValue([...entries]);setInbox(inbox);};return <div className="app quick" style={{maxWidth:600,margin:'0 auto'}}><main className="content"><NotificationCenter items={value} inbox={inbox} plugins={plugins} refresh={async()=>setValue([...entries])}/></main></div>;}
function button(label:string){const b=document.querySelector(`button[aria-label="${label}"]`);if(!b)throw Error('missing button '+label);return b as HTMLButtonElement;}
async function until(check:()=>boolean){for(let i=0;i<60;i++){if(check())return;await wait();}throw Error('UI timeout');}
(window as any).runInstallReviewChecks=async()=>{try{
configureLanguage('zh-CN',[]);render(true);await wait();
if(document.querySelectorAll('.inbox-message').length!==2||document.body.textContent!.includes('临时消息'))throw Error('non-inbox notification leaked into inbox');
if(!document.body.textContent!.includes('录像已保存')||!document.body.textContent!.includes('打开更新'))throw Error('Chinese notification content missing');
await wait(150);console.log('FRAMELY_PREVIEW_INSTALL_INBOX_ZH');
fail=true;button('打开录像').click();await until(()=>!!document.querySelector('[role=alert]'));
if(!entries[0].inInbox||!entries[0].toast)throw Error('failed action removed message');
fail=false;button('打开录像').click();await until(()=>document.querySelectorAll('.inbox-message').length===1);
if(entries[0].inInbox||entries[0].toast)throw Error('default action did not remove message');
entries=[entry('keep',{notification:{id:'keep',title:'录制进行中',body:'查看状态不会关闭这条通知。',actions:[{id:'open',label:'查看状态',closeOnClick:false,removeFromInboxOnClick:false}]} })];
render(false);await wait();button('查看状态').click();await wait();
if(!entries[0].toast||!entries[0].inInbox||!document.querySelector('.toast'))throw Error('opt-out action dismissed message');
if(!document.querySelector('[role=timer]')?.textContent?.includes('秒后关闭'))throw Error('countdown not shown');
button('关闭通知').click();await until(()=>!document.querySelector('.toast'));
if(!entries[0].inInbox)throw Error('floating close removed saved message');
render(true);await wait();button('移除通知').click();await until(()=>!!document.querySelector('.inbox-empty'));
entries=[entry('expiry',{expiresAt:Date.now()+350})];render(false);await wait(700);
if(document.querySelector('.toast')||!entries[0].inInbox)throw Error('automatic close removed inbox copy');
entries=[entry('persistent',{expiresAt:null,notification:{id:'persistent',title:'Persistent status',body:'Stays visible until dismissed',durationMs:0}})];render(false);await wait();
if(!document.querySelector('.toast')||document.querySelector('[role=timer]'))throw Error('persistent notification has a countdown');
entries=[entry('long',{notification:{id:'long',title:'A recording with a long title is ready to review',body:'Recording details. '.repeat(80),actions:[{id:'open',label:'Open recording'},{id:'copy',label:'Copy path'},{id:'continue',label:'Continue recording'}]}})];render(false);await wait();
const compact=document.querySelector('.toast') as HTMLElement,message=compact.querySelector('.notification-message') as HTMLElement;
if(compact.getBoundingClientRect().height>185||message.scrollHeight<=message.clientHeight)throw Error('long notification expanded instead of scrolling inside compact popup');
for(const action of compact.querySelectorAll('.toast-actions button')){const bounds=action.getBoundingClientRect();if(bounds.height<44||bounds.bottom>compact.getBoundingClientRect().bottom)throw Error('compact notification action is clipped or too small');}
entries=[entry('saved',{notification:{id:'saved',title:'Recording saved',body:'Your recording is ready. Open it whenever you are ready.',actions:[{id:'open',label:'Open recording'}]}}),entry('update',{plugin:'',pluginName:'Framely',update:{version:'0.4.3-preview.1'},notification:{id:'update',title:'Update',body:'New release',actions:[{id:'ignore',label:'Ignore'},{id:'open',label:'Open updates'}]}})];
configureLanguage('en-US',[]);render(true);await wait(180);
if(!document.body.textContent!.includes('Inbox')||!document.body.textContent!.includes('Open updates'))throw Error('English translation missing');
console.log('FRAMELY_PREVIEW_INSTALL_INBOX_EN');
render(false);await wait(180);console.log('FRAMELY_PREVIEW_INSTALL_TOAST_EN');
if([...document.querySelectorAll('.toast')].some(card=>card.getBoundingClientRect().height>185))throw Error('floating notification exceeds compact height');
if([...document.querySelectorAll('.toast-actions button')].some(b=>b.scrollWidth>b.clientWidth))throw Error('notification action overflowed');
// Mount the real quick menu and assert the navigation actually reaches the inbox.
root.unmount();await import('../ui/src/main');
await until(()=>!!document.querySelector('nav button'));
const installed=[...document.querySelectorAll('nav button')].find(b=>b.textContent==='已安装') as HTMLButtonElement;
installed.click();await wait();
if(document.querySelectorAll('.plugin-row').length!==1)throw Error('quick installed list includes disabled plugins');
const notifications=[...document.querySelectorAll('nav button')].find(b=>b.textContent?.startsWith('通知')) as HTMLButtonElement;
if(!notifications)throw Error('quick inbox tab missing');notifications.click();await wait(180);
if(document.querySelectorAll('.inbox-message').length!==2||document.querySelectorAll('nav button').length!==4)throw Error('quick inbox navigation broken');
if(!document.querySelector('[role=switch][aria-label="允许通知"]')||!document.querySelector('[aria-label="通知设置"]'))throw Error('quick notification controls missing');
console.log('FRAMELY_PREVIEW_INSTALL_QUICK_INBOX');
button('打开更新').click();await until(()=>!document.querySelector('.inbox-message')?.textContent?.includes('可更新'));
if(!calls.some(c=>c.method==='notification.action'&&c.params.action==='open'&&c.params.plugin===''))throw Error('update action not dispatched');
const settings=[...document.querySelectorAll('nav button')].find(b=>b.textContent==='设置') as HTMLButtonElement;
settings.click();await until(()=>!!document.querySelector('.quick-settings'));
if(document.querySelector('.quick-settings input[type=file]')||document.querySelector('.quick-settings [download]'))throw Error('Quick settings exposes language installation or template download');
const safe=document.querySelector('.setting-toggle') as HTMLElement,languageCard=document.querySelector('.language-settings') as HTMLElement;
if(languageCard.getBoundingClientRect().top-safe.getBoundingClientRect().bottom<24)throw Error('Safe mode is too close to language divider');
button('界面语言').click();await wait();
const english=[...document.querySelectorAll('[role=option]')].find(b=>b.textContent==='English') as HTMLButtonElement;
if(!english)throw Error('Language picker has no English option');english.click();
await until(()=>!!document.querySelector('[aria-label="Interface language"]'));
if(!calls.some(c=>c.method==='language.save'&&c.params.language==='en-US'))throw Error('Quick language selection did not save');
const update=document.querySelector('.quick-update-entry') as HTMLButtonElement;
if(!update?.textContent?.includes('Check for updates'))throw Error('Quick update entry missing');update.click();await wait();
if(!calls.some(c=>c.method==='host.manager.open'&&c.params.page==='updates'))throw Error('Quick update entry did not open update settings');
console.log('FRAMELY_PREVIEW_INSTALL_QUICK_SETTINGS_EN');
console.log('FRAMELY_BRIDGE_PASS');
}catch(e){console.error('FRAMELY_BRIDGE_FAIL '+e);}};
root.render(<Fixture/>);wait(150).then(()=>console.log('FRAMELY_VIEW_READY'));
+25
View File
@@ -0,0 +1,25 @@
#include "paint_buffer.h"
#include <cassert>
struct Rect{int x,y,width,height;};
int main(){
std::vector<uint8_t> source(4*3*4,80),normal,flipped;Rect full{0,0,4,3};
merge_paint(normal,source.data(),4,3,1,&full);merge_paint(flipped,source.data(),4,3,1,&full,true);
// A partial repaint may contain unrelated pixels outside the dirty area.
std::fill(source.begin(),source.end(),0);source[(1*4+2)*4]=200;Rect dirty{2,1,1,1};
merge_paint(normal,source.data(),4,3,1,&dirty);merge_paint(flipped,source.data(),4,3,1,&dirty,true);
assert(normal[0]==80&&normal[(1*4+2)*4]==200);assert(flipped[0]==80&&flipped[(1*4+2)*4]==200);
source[(0*4+1)*4]=150;Rect top{1,0,1,1};merge_paint(flipped,source.data(),4,3,1,&top,true);assert(flipped[(2*4+1)*4]==150);assert(flipped[1*4]==80);
Rect clipped{-1,-1,2,2};merge_paint(normal,source.data(),4,3,1,&clipped);assert(normal[0]==0&&normal[4]==80);
// Simulate alternating GPU textures: a texture must catch up on all paints
// since its last upload, including damage already sent to the other texture.
PaintDamage pending[2];std::vector<uint8_t> gpu[2];
source.assign(4*3*4,80);flipped.clear();
auto paint=[&](Rect r){merge_paint(flipped,source.data(),4,3,1,&r,true);for(auto& d:pending)d.add(4,3,1,&r);};
auto upload=[&](int slot){auto& d=pending[slot];if(gpu[slot].empty()){gpu[slot].resize(flipped.size());d.include(0,0,4,3);}for(int y=d.y;y<d.y+d.height;y++)std::copy_n(flipped.data()+(y*4+d.x)*4,d.width*4,gpu[slot].data()+(y*4+d.x)*4);d.clear();assert(gpu[slot]==flipped);};
paint(full);upload(0);upload(1);
source[(0*4+1)*4]=150;paint(top);assert(pending[0].x==1&&pending[0].y==2&&pending[0].width==1&&pending[0].height==1);upload(0);
source[(1*4+2)*4]=200;paint(dirty);upload(1);upload(0);
// Multiple CEF callbacks before a submission, clipping and missing dirty lists.
source[0]=25;paint(clipped);source[(2*4+3)*4]=35;paint(Rect{3,2,1,1});upload(0);upload(1);
PaintDamage bounds;bounds.add(4,3,0,static_cast<Rect*>(nullptr));assert(bounds.width==4&&bounds.height==3);bounds.clear();Rect outside{9,9,3,3};bounds.add(4,3,1,&outside);assert(bounds.empty());
}
+13
View File
@@ -0,0 +1,13 @@
#include "plugin_navigation.h"
#include <cassert>
int main() {
const std::string origin="http://localhost:19626";
assert(allow_plugin_navigation(origin+"/window",origin,true,true));
assert(allow_plugin_navigation("about:blank",origin,false,false));
assert(allow_plugin_navigation("http://localhost:19629/framely-window/main",origin,false,true));
assert(allow_plugin_navigation("http://localhost:19629/framely-window/login?ticket=test",origin,false,true));
assert(!allow_plugin_navigation("http://localhost:19629/",origin,true,true));
assert(!allow_plugin_navigation("http://localhost:19629/",origin,false,false));
for (const auto& url : {"https://example.com/", "http://192.168.5.67:19629/", "http://localhost.evil:19629/", "http://localhost:19629@evil/", "http://localhost:19629\\@evil/", "http://localhost:0/", "http://localhost:65536/", "http://localhost:/", "http://localhost:999999999999999999999/"})
assert(!allow_plugin_navigation(url,origin,false,true));
}
+32
View File
@@ -0,0 +1,32 @@
// Exercise the real quick panel across status polling and repeated host launches.
const wait=(ms=80)=>new Promise(r=>setTimeout(r,ms));
const until=async(f:()=>any)=>{for(let i=0;i<150;i++){if(f())return;await wait(30);}throw Error('Timed out '+document.body.innerText.slice(0,350));};
history.replaceState(null,'','/?fixture=1#plugin:test.quick');
let polls=0,opens=0;
window.fetch=async(_url,init)=>{
const {method}=JSON.parse(String(init?.body));let result:any=true;
if(method==='status'){polls++;result={version:'0.4.3-preview.2',agreement:{version:1,accepted:true},database:{language:'en-US',plugins:{'test.quick':{manifest:{id:'test.quick',name:'Quick fixture',version:'1',author:'Test',description:'',ui:{quickPage:'page.js',windows:{}}},enabled:true,favorite:true,order:0}},sources:[],safeMode:false},running:[],notifications:[],inbox:[]};}
else if(method==='language.list')result={packs:[],invalidFiles:[]};
else if(method==='ui.events')result={cursor:0,events:[]};
else if(method==='plugin.open')opens++;
return new Response(JSON.stringify({result}));
};
const back=()=>document.querySelector<HTMLButtonElement>('.page-title button')!;
(window as any).runInstallReviewChecks=async()=>{try{
await until(()=>!!back()&&!!document.querySelector('iframe'));
if(location.hash||location.search!=='?fixture=1')throw Error('Plugin hash was not consumed correctly');
back().click();await until(()=>!!document.querySelector('.workspace'));
const before=polls;await until(()=>polls>=before+2);
if(back()||document.querySelector('iframe')||opens!==1)throw Error('Status polling reopened plugin');
location.hash='#plugin:test.quick';await until(()=>!!back()&&opens===2);
window.dispatchEvent(new Event('framely.back'));await until(()=>!!document.querySelector('.workspace'));
const second=polls;await until(()=>polls>=second+2);
if(back()||location.hash||opens!==2)throw Error('Back event reopened plugin');
location.hash='#plugin:test.quick';await until(()=>!!back()&&opens===3);
window.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape'}));await until(()=>!!document.querySelector('.workspace'));
const third=polls;await until(()=>polls>=third+2);
if(back()||location.hash||opens!==3)throw Error('Escape reopened plugin');
console.log('FRAMELY_BRIDGE_PASS');
}catch(e){console.error('FRAMELY_BRIDGE_FAIL '+e);}
};
void import('../ui/src/main');
+8
View File
@@ -0,0 +1,8 @@
#include "render_timing.h"
#include <cassert>
#include <limits>
int main(){
assert(browser_frame_rate(72)==60);assert(browser_frame_rate(90)==60);assert(browser_frame_rate(120)==60);
assert(browser_frame_rate(0)==60);assert(browser_frame_rate(-1)==60);assert(browser_frame_rate(std::numeric_limits<float>::quiet_NaN())==60);
assert(browser_frame_rate(30)==60);assert(browser_frame_rate(1000)==60);
}
+35 -9
View File
@@ -10,12 +10,13 @@ const wait=(ms=70)=>new Promise(resolve=>setTimeout(resolve,ms));
let status:any={version:'0.4.3-preview.1',build:'0.4.3-preview.1-012345abcdef',database:{updateSource:{url:'https://github.com/example/framely/releases/latest/download/framely-release.json'}},previousRelease:'releases/old'};
let updateStatus:React.Dispatch<React.SetStateAction<any>>,remount:()=>void;
let kind='',empty=false,hold=false,verifying=false,failCheck=false,failDownload=false,failApply=false;
let checks=0,downloads=0,attempts=0,installs=0,rollbacks=0;
let checks=0,downloads=0,attempts=0,installs=0,rollbacks=0,automaticSaves=0;
const release=()=>({version:(status.database.updateChannel==='testing'?'0.4.3-preview.2':'0.4.2')+'-abcdef012345',size:1024*1024,changelog:'Fixture release notes'});
window.fetch=async(_url,init)=>{
const {method,params}=JSON.parse(String(init?.body));
let result:any=true;
if(method==='system.channel.save')status={...status,database:{...status.database,updateChannel:params.channel}};
if(method==='system.check.settings.save'){automaticSaves++;status={...status,database:{...status.database,updateCheck:params.settings}};}
else if(method==='system.channel.save')status={...status,database:{...status.database,updateChannel:params.channel}};
else if(method==='system.check.start'){kind='system.check';checks++;result={job:'fixture'};}
else if(method==='system.download.start'){kind='system.download';downloads++;result={job:'fixture'};}
else if(method==='system.job.status'){
@@ -42,12 +43,34 @@ async function choose(label:string){(document.querySelector('.framely-select but
try{
configureLanguage('zh-CN',[]);updateStatus({...status});await wait();
if(!document.querySelector('.framely-select button')?.textContent?.includes('正式版'))throw Error('legacy source did not default to stable');
const automaticSwitch=()=>document.querySelector('.automatic-update-settings [role=switch]') as HTMLButtonElement;
if(automaticSwitch().getAttribute('aria-checked')!=='true')throw Error('automatic checks did not default to enabled');
automaticSwitch().click();await until(()=>automaticSaves===1);await wait();
if(status.database.updateCheck.enabled||(document.querySelector('.automatic-update-settings .framely-select button') as HTMLButtonElement).disabled===false)throw Error('disabled automatic check settings not reflected');
automaticSwitch().click();await until(()=>automaticSaves===2);await wait();
(document.querySelector('.automatic-update-settings .framely-select button') as HTMLButtonElement).click();await wait();
([...document.querySelectorAll('[role=option]')].find(o=>o.textContent==='每 12 小时') as HTMLButtonElement).click();await until(()=>automaticSaves===3);await wait();
if(status.database.updateCheck.intervalHours!==12)throw Error('automatic interval not saved');
button('检查更新').click();await until(()=>!!document.querySelector('.release-card'));
const releaseDialog=document.querySelector('.update-release-dialog') as HTMLDialogElement;
if(!releaseDialog?.open||!releaseDialog.matches(':modal')||document.activeElement!==button('稍后'))throw Error('Available release was not announced in a modal');
if(!releaseDialog.contains(document.querySelector('.release-card')))throw Error('Release details remained inline');
if(!document.querySelector('.release-card')?.textContent?.includes('较旧版本'))throw Error('channel downgrade not identified');
button('下载并安装').click();await wait();
if(downloads!==0||attempts!==0||!document.querySelector('.confirm-box'))throw Error('update bypassed confirmation');
window.dispatchEvent(new Event('framely.back'));await wait();if(document.querySelector('.release-card')||downloads!==0||attempts!==0)throw Error('Later left inline release content or started update');
button('检查更新').click();await until(()=>!!document.querySelector('.update-release-dialog'));
button('下载并安装').focus();button('下载并安装').click();await wait();
const dialog=document.querySelector('.update-confirmation') as HTMLDialogElement|null;
if(downloads!==0||attempts!==0||!dialog?.open||!dialog.matches(':modal'))throw Error('update bypassed modal confirmation');
if(!dialog.getAttribute('aria-labelledby')||!dialog.getAttribute('aria-describedby')||document.activeElement!==button('取消'))throw Error('confirmation lacked accessible focus or description');
const bounds=dialog.getBoundingClientRect();
if(bounds.width<=0||bounds.height<=0||bounds.left<0||bounds.top<0||bounds.right>innerWidth||bounds.bottom>innerHeight)throw Error('confirmation outside viewport');
button('检查更新').focus();
if(!dialog.contains(document.activeElement))throw Error('background took focus during confirmation');
button('取消').click();await wait();
if(downloads!==0||attempts!==0)throw Error('cancelled update performed work');
if(downloads!==0||attempts!==0||document.querySelector('.update-confirmation')||document.activeElement!==button('下载并安装'))throw Error('cancelled update performed work or did not restore focus');
button('下载并安装').click();await wait();
document.querySelector('.update-confirmation')!.dispatchEvent(new Event('cancel',{cancelable:true}));await wait();
if(document.querySelector('.update-confirmation')||downloads!==0||attempts!==0)throw Error('dialog cancellation performed work');
failDownload=true;button('下载并安装').click();await wait();button('确认下载并安装').click();
await until(()=>!!document.querySelector('[role=alert]'));
if(attempts!==0||!document.querySelector('[role=alert]')?.textContent?.includes('checksum failed'))throw Error('failed verification did not stop installation');
@@ -57,13 +80,15 @@ async function choose(label:string){(document.querySelector('.framely-select but
console.log('FRAMELY_PREVIEW_INSTALL_UPDATE_STABLE');
button('安装已校验版本').click();await wait();button('确认安装').click();await until(()=>attempts===2);await wait();
if(downloads!==2)throw Error('installation retry downloaded again');
button('稍后').click();await wait();
await choose('测试版');
if(status.database.updateChannel!=='testing'||document.querySelector('.release-card'))throw Error('channel not saved or stale release retained');
button('检查更新').click();await until(()=>!!document.querySelector('.release-card'));
if(document.querySelector('.release-card')?.textContent?.includes('较旧版本'))throw Error('new preview reported as downgrade');
if([...document.querySelectorAll('button')].some(b=>b.textContent==='安装已校验版本'))throw Error('download reused across channels');
await wait(150);console.log('FRAMELY_PREVIEW_INSTALL_UPDATE_AVAILABLE_ZH');await wait(100);
hold=true;failApply=false;button('下载并安装').click();await wait();button('确认下载并安装').click();await until(()=>downloads===3);await wait();
if(!(document.querySelector('.framely-select button') as HTMLButtonElement).disabled||!button('处理中…').disabled)throw Error('settings mutable during download');
if(!(document.querySelector('.framely-select button') as HTMLButtonElement).disabled||!automaticSwitch().disabled||!button('处理中…').disabled)throw Error('settings mutable during download');
if(attempts!==2)throw Error('installation started before verification');
await until(()=>!!document.querySelector('progress[aria-label="下载进度"]'));
verifying=true;
@@ -73,7 +98,7 @@ async function choose(label:string){(document.querySelector('.framely-select but
if(verification.value!==512*1024||verification.max!==1024*1024||attempts!==2)throw Error('verification byte progress or installation gate incorrect');
console.log('FRAMELY_PREVIEW_INSTALL_UPDATE_TESTING');
hold=false;await until(()=>installs===1);
if(attempts!==3||document.querySelector('.confirm-box'))throw Error('verified download required a second confirmation');
if(attempts!==3||document.querySelector('.update-confirmation'))throw Error('verified download required a second confirmation');
remount();await wait();
failCheck=true;button('检查更新').click();await until(()=>!!document.querySelector('[role=alert]'));
if(document.querySelector('.release-card'))throw Error('failed recheck retained stale install');
@@ -82,13 +107,14 @@ async function choose(label:string){(document.querySelector('.framely-select but
empty=false;configureLanguage('en-US',[]);updateStatus({...status});await wait();
if(!document.querySelector('.framely-select button')?.textContent?.includes('Stable'))throw Error('English channel untranslated');
await choose('Testing');button('Check for updates').click();await until(()=>!!document.querySelector('.release-card'));
await wait(150);console.log('FRAMELY_PREVIEW_INSTALL_UPDATE_AVAILABLE_EN');await wait(100);
button('Download and install').click();await wait();
if(!document.querySelector('.confirm-box')?.textContent?.includes('installed automatically'))throw Error('English update flow untranslated');
if(!document.querySelector('.update-confirmation')?.textContent?.includes('installed automatically'))throw Error('English update flow untranslated');
hold=true;button('Confirm download and installation').click();
await until(()=>!!document.querySelector('progress[aria-label="Verification progress"]'));
if(!document.body.textContent?.includes('Download complete. Verifying')||!document.body.textContent?.includes('Verified 0.5 / 1.0 MiB'))throw Error('English verification progress untranslated');
hold=false;await until(()=>installs===2);
if(checks!==5||downloads!==4||attempts!==4)throw Error(`unexpected workflow counts ${checks}/${downloads}/${attempts}`);
if(checks!==6||downloads!==4||attempts!==4)throw Error(`unexpected workflow counts ${checks}/${downloads}/${attempts}`);
console.log('FRAMELY_PREVIEW_INSTALL_UPDATE_ENGLISH');
remount();await wait();button('Roll back to previous release').click();await wait();
if(rollbacks!==0)throw Error('rollback bypassed confirmation');
+7
View File
@@ -31,6 +31,7 @@ class CEFRuntimeTests(unittest.TestCase):
'lib/cef/libcef.so': 'browser', 'lib/cef/icudtl.dat': 'icu',
'lib/cef/locales/en-US.pak': 'locale', 'share/licenses/cef.txt': 'license',
'share/licenses/cef-credits.html': 'credits', 'share/licenses/openvr.txt': 'openvr',
'share/search/ipadic.dic.zst': 'dictionary', 'share/search/COPYING': 'dictionary license',
'install.sh': 'install', 'uninstall.sh': 'uninstall'}
for name, data in files.items():
p = stage / name
@@ -62,6 +63,12 @@ class CEFRuntimeTests(unittest.TestCase):
extracted = bootstrap.extract_archive(archive, folder / archive.name.replace('.tar.gz', ''),
runtime=archive.name.startswith('framely-cef-'))
subprocess.run(['sha256sum', '--quiet', '-c', 'SHA256SUMS'], cwd=extracted, check=True)
if not archive.name.startswith('framely-cef-'):
self.assertEqual((extracted / 'share/search/ipadic.dic.zst').read_text(), 'dictionary')
self.assertEqual((extracted / 'share/search/COPYING').read_text(), 'dictionary license')
self.assertIn('share/search/ipadic.dic.zst', (extracted / 'SHA256SUMS').read_text())
else:
self.assertFalse((extracted / 'share/search').exists())
if archive.name == stage.name + '-linux-arm64.tar.gz':
self.assertFalse((extracted / 'lib/cef/libcef.so').exists())
self.assertFalse((extracted / 'share/licenses/cef-credits.html').exists())
+60
View File
@@ -0,0 +1,60 @@
import base64
import importlib.util
import io
import json
import pathlib
import tempfile
import unittest
import zipfile
spec = importlib.util.spec_from_file_location('diagnostics', pathlib.Path(__file__).parents[1] / 'tools/export-diagnostics.py')
diag = importlib.util.module_from_spec(spec)
spec.loader.exec_module(diag)
class DiagnosticsTests(unittest.TestCase):
def archive(self, root):
result = diag.collect(root, commands=False, runtime=root / 'runtime')
self.assertTrue(result['name'].endswith('.zip'))
return zipfile.ZipFile(io.BytesIO(base64.b64decode(result['data'])))
def test_stopped_service_partial_logs_and_credentials(self):
with tempfile.TemporaryDirectory() as temp:
root = pathlib.Path(temp)
(root / 'logs').mkdir()
(root / 'current').mkdir()
(root / 'current/VERSION').write_text('0.4.3-preview.2-test')
(root / 'logs/demo.log').write_text('password=private token=secret\nAuthorization: Bearer abc.def\n{"password":"hidden"}\nhttps://user:pass@example.org\nUseful error\n')
(root / 'network-password.json').write_text('do-not-export')
(root / 'state.json').write_text(json.dumps({'plugins': {'demo': {'manifest': {'name':'Demo', 'version':'1.0.0'}, 'enabled': True, 'config': {'secret':'do-not-export'}}}, 'proxy': {'http': 'do-not-export'}}))
archive = self.archive(root)
text = '\n'.join(archive.read(n).decode() for n in archive.namelist())
for value in ('private', 'abc.def', 'hidden', 'user:pass', 'do-not-export'):
self.assertNotIn(value, text)
self.assertIn('Useful error', text)
self.assertIn('0.4.3-preview.2-test', text)
self.assertIn('Demo', text)
self.assertNotIn('network-password.json', archive.namelist())
def test_corrupt_state_and_missing_logs_still_export(self):
with tempfile.TemporaryDirectory() as temp:
root = pathlib.Path(temp)
(root / 'state.json').write_text('invalid')
archive = self.archive(root)
self.assertTrue(json.loads(archive.read('report.json'))['warnings'])
self.assertIn('system.json', archive.namelist())
def test_large_logs_and_symlinks(self):
with tempfile.TemporaryDirectory() as temp:
root = pathlib.Path(temp)
(root / 'logs').mkdir()
(root / 'secret').write_text('DO_NOT_FOLLOW')
(root / 'logs/link.log').symlink_to(root / 'secret')
(root / 'logs/large.log').write_text('X' * (diag.MAX_FILE * 2) + '\nLAST ERROR')
archive = self.archive(root)
self.assertNotIn('logs/link.log', archive.namelist())
data = archive.read('logs/large.log')
self.assertLessEqual(len(data), diag.MAX_FILE)
self.assertTrue(data.endswith(b'LAST ERROR'))
if __name__ == '__main__':
unittest.main()
+34
View File
@@ -0,0 +1,34 @@
"""Run the production reinstall block against retained uninstall state."""
import json
import pathlib
import subprocess
import tempfile
import unittest
class ReinstallStateTests(unittest.TestCase):
def test_only_clean_reinstall_clears_uninstall_guard(self):
source = (pathlib.Path(__file__).parents[1] / 'packaging/install.sh').read_text()
block = source.split('# Clear the uninstall guard retained by older releases', 1)[1].split('ln -s "releases/$version"', 1)[0]
block = '# Clear the uninstall guard retained by older releases' + block
for repair, old, plugins, expected in [
('false', '', {}, False),
('true', '', {}, True),
('false', 'releases/current', {}, True),
('false', '', {'demo': {'enabled': False}}, True),
]:
with self.subTest(repair=repair, old=old, plugins=plugins), tempfile.TemporaryDirectory() as temp:
root = pathlib.Path(temp)
path = root / 'state.json'
original = {'safeMode': True, 'plugins': plugins, 'language': 'en-US', 'sources': [{'url': 'https://example.org'}]}
path.write_text(json.dumps(original))
result = subprocess.run(['bash', '-e', '-c', 'root=$1; repair=$2; old=$3\n' + block, 'reinstall', str(root), repair, old], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
expected_state = dict(original, safeMode=expected)
self.assertEqual(json.loads(path.read_text()), expected_state)
if expected:
self.assertEqual(path.read_text(), json.dumps(original))
else:
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
if __name__ == '__main__':
unittest.main()
+144
View File
@@ -0,0 +1,144 @@
#!/usr/bin/env python3
"""Collect a bounded diagnostic ZIP without requiring a running Framely service."""
import argparse
import base64
import datetime
import io
import json
import os
import pathlib
import platform
import re
import subprocess
import zipfile
MAX_FILE = 256 * 1024
MAX_TOTAL = 8 * 1024 * 1024
SECRET = re.compile(r'(?i)((?:password|passwd|token|secret|authorization|api[_-]?key)[\"\']?\s*[=:]\s*)(?:"[^"]*"|\'[^\']*\'|[^\s,;]+)')
URL_CREDENTIALS = re.compile(r'(https?://)[^/\s:@]+:[^/\s@]+@')
def redact(text):
text = re.sub(r'(?i)\bBearer\s+[A-Za-z0-9._~+/=-]+', 'Bearer [redacted]', text)
text = SECRET.sub(r'\1[redacted]', text)
text = re.sub(r'(/boot/)[a-f0-9]{32,}', r'\1[redacted]', text)
return URL_CREDENTIALS.sub(r'\1[redacted]@', text)
def collect(state, commands=True, runtime=pathlib.Path('/run/user'), installer_log=None):
report = {'format': 1, 'createdAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'warnings': []}
entries = {}
budget = MAX_TOTAL
def add(name, data):
nonlocal budget
data = redact(data).encode('utf-8', errors='replace')
if len(data) > MAX_FILE:
report['warnings'].append(name + ': truncated to recent output')
data = data[-MAX_FILE:]
if len(data) > budget:
report['warnings'].append(name + ': omitted (archive budget)')
return
entries[name] = data
budget -= len(data)
def tail(path, name):
try:
if path.is_symlink() or not path.is_file():
return
with path.open('rb') as source:
source.seek(max(0, os.fstat(source.fileno()).st_size - MAX_FILE))
add(name, source.read(MAX_FILE).decode('utf-8', errors='replace'))
except (OSError, ValueError) as error:
report['warnings'].append(name + ': ' + str(error))
def command(name, args):
try:
# Temporary files avoid buffering unbounded journal output in memory.
import tempfile
with tempfile.TemporaryFile() as output:
result = subprocess.run(args, stdout=output, stderr=subprocess.STDOUT, timeout=8, check=False)
output.seek(0, 2)
output.seek(max(0, output.tell() - MAX_FILE))
add(name, output.read(MAX_FILE).decode('utf-8', errors='replace'))
if result.returncode:
report['warnings'].append(name + ': command exited ' + str(result.returncode))
except (OSError, subprocess.TimeoutExpired) as error:
report['warnings'].append(name + ': ' + str(error))
if installer_log is not None:
add('installer.log', installer_log)
add('system.json', json.dumps({'system': platform.system(), 'release': platform.release(), 'machine': platform.machine()}, indent=2))
for name in ('current', 'previous'):
tail(state / name / 'VERSION', 'versions/' + name + '.txt')
tail(state / 'previous-release', 'versions/previous-release.txt')
# Only a summary is included; plugin configuration, proxy credentials,
# inbox contents and authentication files must never enter the archive.
try:
database = json.loads((state / 'state.json').read_text())
plugins = database.get('plugins', {})
add('plugins.json', json.dumps({'safeMode': database.get('safeMode'), 'plugins': [
{'id': key, 'name': value.get('manifest', {}).get('name'), 'version': value.get('manifest', {}).get('version'), 'enabled': value.get('enabled'), 'error': value.get('error')}
for key, value in plugins.items()
]}, ensure_ascii=False, indent=2))
except (OSError, ValueError, TypeError, AttributeError) as error:
report['warnings'].append('plugins.json: ' + str(error))
try:
for path in sorted((state / 'logs').glob('*.log'))[:64]:
tail(path, 'logs/' + path.name)
for path in sorted(runtime.glob('*/framely-session-*/cef.log'))[-8:]:
tail(path, 'renderer/' + path.parent.parent.name + '-' + path.parent.name + '-cef.log')
except OSError as error:
report['warnings'].append('logs: ' + str(error))
# Record GPU evidence without copying command lines or authentication tokens.
gpu = []
if commands:
for process in pathlib.Path('/proc').glob('[0-9]*'):
try:
if pathlib.Path(os.readlink(process / 'exe')).name != 'framely-vr':
continue
arguments = (process / 'cmdline').read_bytes()
match = re.search(rb'--type=([a-z-]+)', arguments)
kind = match.group(1).decode() if match else 'browser'
info = {'pid': int(process.name), 'type': kind, 'gpuDisabled': b'--disable-gpu' in arguments.replace(b'\0', b' ').split()}
if kind == 'gpu-process':
maps = (process / 'maps').read_text(errors='replace')
info['drivers'] = sorted(set(line.split()[-1] for line in maps.splitlines() if any(word in line.lower() for word in ('freedreno', 'adreno', 'swiftshader', 'llvmpipe', 'vulkan', 'libegl', 'libgles'))))
devices = []
for fd in (process / 'fd').iterdir():
try:
target = os.readlink(fd)
if target.startswith('/dev/dri/') or target == '/dev/kgsl-3d0':
devices.append(target)
except OSError:
pass
info['devices'] = sorted(set(devices))
gpu.append(info)
except (OSError, ValueError):
continue
add('renderer/gpu.json', json.dumps(gpu, indent=2))
if commands:
command('services.txt', ['systemctl', 'status', 'framely.service', 'framely-session.service', '--no-pager', '--full'])
command('journal.txt', ['journalctl', '-u', 'framely.service', '-u', 'framely-session.service', '-u', 'framely-plugin-*', '-u', 'framely-backend-*', '-u', 'framely-hook-*', '--since=-24h', '-n', '3000', '--no-pager', '-o', 'short-iso'])
add('README.txt', 'Framely diagnostics. Recent log tails, service state and installed version summary only. Missing sources are listed in report.json. Logs may contain application data; inspect before sharing.\n')
entries['report.json'] = json.dumps(report, ensure_ascii=False, indent=2).encode()
memory = io.BytesIO()
with zipfile.ZipFile(memory, 'w', zipfile.ZIP_DEFLATED) as archive:
for name, data in entries.items():
archive.writestr(name, data)
name = 'framely-logs-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%d-%H%M%S') + '.zip'
return {'name': name, 'data': base64.b64encode(memory.getvalue()).decode('ascii')}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--state', type=pathlib.Path)
parser.add_argument('--output', type=pathlib.Path)
parser.add_argument('--installer-log-base64')
args = parser.parse_args()
state = args.state or (pathlib.Path('/home/.framely/state') if pathlib.Path('/home/.framely/state').is_dir() else pathlib.Path('/var/lib/framely'))
extra = base64.b64decode(args.installer_log_base64).decode('utf-8', errors='replace') if args.installer_log_base64 else None
result = collect(state, installer_log=extra)
if args.output:
with args.output.open('xb') as output:
os.chmod(args.output, 0o600)
output.write(base64.b64decode(result['data']))
print(args.output)
else:
print(json.dumps(result))
if __name__ == '__main__':
main()
+7 -2
View File
@@ -11,7 +11,7 @@ npm run build
bash tools/build-native.sh "$cef"
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 ui/dist sdk templates/plugin examples/showcase packaging tools docs assets/branding README.md README.zh-CN.md LICENSE -type f ! -path '*/__pycache__/*' -print0 | sort -z | xargs -0 sha256sum | sha256sum | cut -c1-12)"
build_id="$version-$(find "$binary" target/native 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)"
stage="$base/release/framely-$build_id"
[[ ! -e $stage ]] || { echo 'Release already exists.' >&2; exit 1; }
mkdir -p "$stage"/{bin,lib/cef,lib/openvr,share/ui,share/licenses,tools}
@@ -24,8 +24,13 @@ rm -f "$stage/lib/cef/framely-probe" "$stage/lib/cef/framely-browser-probe"
strip --strip-debug "$stage/lib/cef/libcef.so"
cp native/vendor/openvr/lib/linuxarm64/libopenvr_api.so "$stage/lib/openvr/"
cp -a ui/dist/. "$stage/share/ui/"
cp -a assets/search "$stage/share/"
cp assets/search/COPYING "$stage/share/licenses/ipadic.txt"
cp assets/search/NOTICE "$stage/share/licenses/ipadic-notice.txt"
cp -a native/input "$stage/share/"
cp "$cef/LICENSE.txt" "$stage/share/licenses/cef.txt"
cp native/vendor/openvr/LICENSE "$stage/share/licenses/openvr.txt"
cp node_modules/@tabler/icons-react/LICENSE "$stage/share/licenses/tabler-icons.txt"
[[ ! -f $cef/CREDITS.html ]] || cp "$cef/CREDITS.html" "$stage/share/licenses/cef-credits.html"
cp native/vendor/json.hpp "$stage/share/licenses/nlohmann-json.hpp"
cp packaging/*.sh "$stage/"
@@ -43,7 +48,7 @@ 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 "$stage/tools/"
cp tools/extract-release.py tools/bootstrap.py tools/cef-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"
+2 -2
View File
@@ -22,13 +22,13 @@ if(command==='init'){
}else if(command==='build'||command==='dev'){
const {build,context}=await import('esbuild');const root=process.cwd();await mkdir(path.join(root,'payload'),{recursive:true});
let revision=0;const clients=new Set();
const options={entryPoints:[path.join(root,'page.tsx')],bundle:true,outfile:path.join(root,'payload/page.js'),minify:command==='build',sourcemap:command==='dev',define:{'process.env.NODE_ENV':JSON.stringify(command==='dev'?'development':'production')},plugins:[{name:'framely-preview',setup(builder){builder.onEnd(async result=>{if(!result.errors.length){await cp(path.join(root,'backend.py'),path.join(root,'payload/backend.py'));await cp(fileURLToPath(import.meta.resolve('@framely/sdk/python')),path.join(root,'payload/framely.py'));if(revision++)for(const client of clients)client.write('data: reload\n\n');}})}}]};
const options={entryPoints:{page:path.join(root,'page.tsx'),...(existsSync(path.join(root,'actions.ts'))?{actions:path.join(root,'actions.ts')}:{})},bundle:true,outdir:path.join(root,'payload'),minify:command==='build',sourcemap:command==='dev',define:{'process.env.NODE_ENV':JSON.stringify(command==='dev'?'development':'production')},plugins:[{name:'framely-preview',setup(builder){builder.onEnd(async result=>{if(!result.errors.length){await cp(path.join(root,'backend.py'),path.join(root,'payload/backend.py'));await cp(fileURLToPath(import.meta.resolve('@framely/sdk/python')),path.join(root,'payload/framely.py'));if(revision++)for(const client of clients)client.write('data: reload\n\n');}})}}]};
if(command==='build'){await build(options);console.log('Built payload. Package using framely pack.');}
else{
const ctx=await context(options);await ctx.watch();
const server=http.createServer(async(req,res)=>{try{
if(req.url==='/__framely/events'){res.writeHead(200,{'Content-Type':'text/event-stream','Cache-Control':'no-cache'});res.write('data: connected\n\n');clients.add(res);req.on('close',()=>clients.delete(res));return;}
if(req.url==='/'||req.url==='/quick'||req.url?.startsWith('/window/')||req.url?.startsWith('/?')){res.setHeader('Content-Type','text/html');res.end(`<!doctype html><meta charset="utf-8"><div id="root"></div><script>window.__framelyBridge={request:async(op,p)=>{if(op==='window.open'){window.open('/?window='+encodeURIComponent(p.window),'_blank');return true;}if(op==='window.close'){window.close();return true;}if(op==='notification.send'){alert(p.notification.title+'\\n'+p.notification.body);return true;}if(op==='dependencies')return [];if(op==='notification.remove'||op==='haptic'||op==='keyboard')return true;throw Error('浏览器预览不启动后端,请安装到 Frame 测试此调用。');},subscribe:()=>()=>{}};new EventSource('/__framely/events').onmessage=e=>{if(e.data==='reload')location.reload()};history.replaceState(null,'',location.pathname.startsWith('/window/')?location.pathname:location.search.includes('window=')?'/window/'+new URLSearchParams(location.search).get('window'):'/quick');</script><script src="/page.js"></script>`);return;}
if(req.url==='/'||req.url==='/quick'||req.url?.startsWith('/window/')||req.url?.startsWith('/?')){res.setHeader('Content-Type','text/html');res.end(`<!doctype html><meta charset="utf-8"><div id="root"></div><script>window.__framelyBridge={request:async(op,p)=>{if(op==='window.open'){window.open('/?window='+encodeURIComponent(p.window),'_blank');return true;}if(op==='window.close'){window.close();return true;}if(op==='notification.send'){alert(p.notification.title+'\\n'+p.notification.body);return true;}if(op==='ui.launchContext')return {source:'quickPanel',trigger:'shortPress'};if(op==='dependencies')return [];if(op==='notification.remove'||op==='notification.dismiss'||op==='haptic'||op==='keyboard')return true;throw Error('浏览器预览不启动后端,请安装到 Frame 测试此调用。');},subscribe:()=>()=>{}};new EventSource('/__framely/events').onmessage=e=>{if(e.data==='reload')location.reload()};history.replaceState(null,'',location.pathname.startsWith('/window/')?location.pathname:location.search.includes('window=')?'/window/'+new URLSearchParams(location.search).get('window'):'/quick');</script><script src="/page.js"></script>`);return;}
const name=req.url?.split('?')[0];if(name!=='/page.js'&&name!=='/page.js.map'){res.writeHead(404);res.end();return;}res.setHeader('Content-Type',name.endsWith('.map')?'application/json':'application/javascript');res.end(await readFile(path.join(root,'payload',name.slice(1))));
}catch(e){res.writeHead(500);res.end(String(e));}});
server.listen(Number(process.env.FRAMELY_DEV_PORT??5173),'127.0.0.1',()=>console.log(`Preview: http://127.0.0.1:${server.address().port} (no device privileges)`));
+17
View File
@@ -0,0 +1,17 @@
//! Diagnostic: enumerate local Steam libraries using the same code as the session agent.
#[path = "../src/steam.rs"] mod steam;
mod process {
pub fn tool(name:&str)->std::process::Command {std::process::Command::new(name)}
pub fn user_home(uid: u32) -> anyhow::Result<String> {
for line in std::fs::read_to_string("/etc/passwd")?.lines() {
let fields: Vec<_> = line.split(':').collect();
if fields.len() >= 7 && fields[2] == uid.to_string() { return Ok(fields[5].into()); }
}
anyhow::bail!("User home not found")
}
}
fn main() -> anyhow::Result<()> {
let apps=steam::discover(&steam::home()?);
for app in &apps { println!("{}\t{}\ticon={}",app.id,app.name,app.icon.is_some()); }
println!("apps={}",apps.len());Ok(())
}
+2
View File
@@ -16,6 +16,8 @@ const out=process.env.FRAMELY_INSTALL_REVIEW_OUTPUT;
await build({entryPoints:[process.env.FRAMELY_INSTALL_REVIEW_FIXTURE],bundle:true,outfile:`${out}/fixture.js`,define:{'process.env.NODE_ENV':'"production"'}});
await writeFile(`${out}/index.html`,'<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="fixture.css"><div id="root"></div><script src="fixture.js"></script></html>');
JS
mkdir -p "$out/assets"
cp -a assets/branding "$out/assets/branding"
python3 - "$out" > "$out/server.log" 2>&1 <<'PY' &
import functools,http.server,pathlib,sys
root=pathlib.Path(sys.argv[1])
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env bash
set -euo pipefail
base=$(cd -- "$(dirname -- "$0")/.." && pwd)
cef=$(realpath "$1")
cd "$base"
out=$(mktemp -d "${TMPDIR:-/tmp}/framely-launcher.XXXXXX")
server_pid=''
cleanup() { if [[ -n $server_pid ]]; then kill "$server_pid" 2>/dev/null || true; wait "$server_pid" 2>/dev/null || true; fi; }
trap cleanup EXIT
export FRAMELY_INSTALL_REVIEW_OUTPUT="$out"
export FRAMELY_INSTALL_REVIEW_FIXTURE="${2:-tests/launcher_fixture.tsx}"
node --input-type=module - <<'JS'
import {build} from 'esbuild';
import {writeFile} from 'node:fs/promises';
const out=process.env.FRAMELY_INSTALL_REVIEW_OUTPUT;
await build({entryPoints:[process.env.FRAMELY_INSTALL_REVIEW_FIXTURE],bundle:true,outfile:`${out}/fixture.js`,define:{'process.env.NODE_ENV':'"production"'}});
await build({entryPoints:['tests/launcher_action_fixture.ts'],bundle:true,outfile:`${out}/action.js`,define:{'process.env.NODE_ENV':'"production"'}});
await build({entryPoints:['sdk/src/bootstrap.ts'],bundle:true,outfile:`${out}/bootstrap.js`});
await writeFile(`${out}/index.html`,'<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="fixture.css"><div id="root"></div><script src="fixture.js"></script></html>');
JS
mkdir -p "$out/assets"
cp -a assets/branding "$out/assets/branding"
if [[ -n ${FRAMELY_LAUNCHER_PREVIEW_ASSETS:-} ]]; then cp -a "$FRAMELY_LAUNCHER_PREVIEW_ASSETS" "$out/preview-icons"; fi
python3 - "$out" > "$out/server.log" 2>&1 <<'PY' &
import functools,http.server,pathlib,sys
root=pathlib.Path(sys.argv[1])
class Handler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path.startswith('/plugin-assets/'):
icon='termix' if '/demo.alpha/' in self.path else 'passthrough'
self.path='/preview-icons/'+icon+'.png'
return super().do_GET()
if self.path.startswith('/plugin-action-frame/'):
data=b"<!doctype html><div id=root></div><script src='/bootstrap.js'></script><script src='/action.js'></script>"
self.send_response(200);self.send_header('Content-Type','text/html');self.end_headers();self.wfile.write(data)
else:super().do_GET()
server=http.server.ThreadingHTTPServer(('127.0.0.1',0),functools.partial(Handler,directory=str(root)))
(root/'port').write_text(str(server.server_port))
server.serve_forever()
PY
server_pid=$!
for _ in {1..100}; do [[ ! -f $out/port ]] || break; sleep 0.05; done
port=$(cat "$out/port")
cp -a "$cef/Resources/." "$cef/Release/"
g++ -std=c++17 -O2 -I"$cef" tests/browser_probe.cpp -L"$cef/Release" -lcef -pthread '-Wl,-rpath,$ORIGIN' -o "$cef/Release/framely-browser-probe"
for mode in desktop; do
mkdir "$out/$mode"
export FRAMELY_CEF_ROOT="$cef" FRAMELY_LAUNCHER_TEST=1 FRAMELY_INSTALL_REVIEW_TEST=1 FRAMELY_PREVIEW_DIR="$out/$mode" GSETTINGS_BACKEND=memory
if [[ $mode == desktop ]]; then export FRAMELY_STORE_TEST=1; else unset FRAMELY_STORE_TEST; fi
if ! "$cef/Release/framely-browser-probe" "http://127.0.0.1:$port" "$out/$mode-runtime" --ozone-platform=headless --disable-gpu > "$out/$mode.log" 2>&1; then
cat "$out/$mode.log"; exit 1
fi
tail -n 1 "$out/$mode.log"
done
printf 'Launcher previews: %s\n' "$out"
+1 -1
View File
@@ -3,7 +3,7 @@ set -euo pipefail
base=$(cd -- "$(dirname -- "$0")/.." && pwd)
cd "$base"
mkdir -p target/tests
for test in menu_geometry keyboard_state notification_geometry ui_visibility; do
for test in menu_geometry keyboard_state notification_geometry notification_badge ui_visibility plugin_navigation launcher_input launcher_pointer paint_buffer render_timing; do
"${CXX:-g++}" -std=c++17 -O2 -Inative -Inative/vendor/openvr "tests/$test.cpp" -o "target/tests/$test"
"target/tests/$test"
done
+97 -1
View File
@@ -83,6 +83,8 @@
"管理 {0}": "Manage {0}",
"未找到插件": "No plugins found",
"没有收藏的插件": "No favorite plugins",
"没有已启用的插件": "No enabled plugins",
"打开插件管理以启用插件。": "Open the manager to enable plugins.",
"还没有安装插件": "No plugins installed yet",
"换一个关键词再试。": "Try another search term.",
"点击插件旁的星标,将它加入常用。": "Click a plugin's star to add it to your favorites.",
@@ -384,6 +386,100 @@
"仅检查正式版。": "Check stable releases only.",
"仅检查测试版(Preview、Beta、RC 等)。": "Check testing releases only (Preview, Beta, RC, etc.).",
"所选渠道暂无可用发行版本。": "No release is available in the selected channel.",
"所选版本早于当前版本,安装将切换到较旧版本。": "The selected release is older than your current version. Installing will switch to that older version."
"所选版本早于当前版本,安装将切换到较旧版本。": "The selected release is older than your current version. Installing will switch to that older version.",
"通知": "Notifications",
"收件箱": "Inbox",
"收件箱为空": "Your inbox is empty",
"需要保留的通知会出现在这里。": "Notifications saved for later will appear here.",
"移除通知": "Remove notification",
"{0} 秒后关闭": "Closes in {0}s",
"启用此插件后可使用通知操作。": "Enable this plugin to use notification actions.",
"Framely {0} 可更新": "Framely {0} is available",
"查看新版本并选择安装,或忽略本次提醒。": "Review and install the new version, or ignore this reminder.",
"忽略": "Ignore",
"打开更新": "Open updates",
"自动检查更新": "Check for updates automatically",
"检查间隔": "Check interval",
"每 {0} 小时": "Every {0} hours",
"发现新版本时发送通知,您可以忽略提醒或打开更新页面。": "New versions send a notification. Ignore it or open Updates when you are ready.",
"正在自动检查更新…": "Checking for updates automatically…",
"自动检查未完成,将在下次检查时重试。": "Automatic check failed. It will retry at the next interval.",
"Notification has changed": "This notification has changed. Please try again.",
"Notification inbox full": "The notification inbox is full. Remove older notifications first.",
"自动检查间隔须为 1-168 小时": "Automatic check interval must be 1-168 hours.",
"Update source or channel has changed": "The update source or channel has changed.",
"Notification queue full": "The notification popup queue is full.",
"每小时": "Every hour",
"允许通知": "Allow notifications",
"允许在视野中显示悬浮通知。": "Show floating notifications in your view.",
"悬浮已关闭,新通知仅在此处查看。": "Popups are off. View new notifications here.",
"通知设置": "Notification settings",
"选择通知如何提醒你。": "Choose how notifications reach you.",
"悬浮通知": "Floating notifications",
"关闭后,新通知将保存在通知收件箱,不显示浮窗。": "When off, new notifications go to your inbox without showing a popup.",
"启动图标角标": "Launcher badge",
"在 Framely 启动图标上显示未读收件箱消息数。": "Show the unread inbox count on the Framely launcher icon.",
"插件通知": "Plugin notifications",
"搜索通知插件": "Search notification plugins",
"全局开关优先;关闭全局开关不会改变插件偏好。": "Global switches take priority. Plugin preferences are kept when a global switch is off.",
"角标": "Badge",
"悬浮": "Popup",
"{0}:角标": "{0}: badge",
"{0}:悬浮": "{0}: popup",
"通知设置导航": "Notifications",
"应用通知": "App notifications",
"搜索通知应用": "Search notification apps",
"搜索应用": "Search apps",
"全局开关优先;关闭全局开关不会改变应用偏好。": "Global switches take priority. App preferences are kept when a global switch is off.",
"应用": "App",
"未找到应用": "No matching apps",
"本体通知,包括检查更新提醒。": "Framely notifications, including update reminders.",
"启动台": "Launcher",
"主扳机打开启动台": "Open launcher with the primary trigger",
"开启后,上扳机打开快捷面板。": "When enabled, the upper trigger opens the quick panel.",
"长按菜单自动关闭": "Automatically close the action menu",
"指针离开后开始计时,移入后取消。": "Start the timer when the pointer leaves; cancel it when the pointer returns.",
"自动关闭时间(秒)": "Close delay (seconds)",
"Steam": "Steam",
"快捷面板": "Quick panel",
"卸载插件": "Uninstall plugin",
"正在执行…": "Running…",
"插件没有快捷页面": "This plugin has no quick page",
"没有可启动的应用": "No apps available",
"正在读取 Steam 应用…": "Reading Steam apps…",
"长按插件图标查看操作": "Hold a plugin icon to see actions",
"卸载 {0}?": "Uninstall {0}?",
"依赖此插件的应用也会停用;插件数据会保留。": "Dependent plugins will also be disabled. Plugin data will be kept.",
"确认卸载": "Confirm uninstall",
"收藏": "Favorite",
"取消收藏": "Remove favorite",
"要求 Framely:{0}": "Requires Framely: {0}",
" · 不兼容": " · Incompatible",
"分页": "Pages",
"第 {0} 页": "Page {0}",
"桌面程序": "Desktop apps",
"拖动图标排列,移到两侧翻页": "Drag icons to rearrange; move to either edge to turn pages",
"完成": "Done",
"整理图标": "Arrange icons",
"正在读取本机应用…": "Reading installed apps…",
"Lepton": "Lepton",
"打开": "Open",
"导出日志": "Export logs",
"正在导出日志…": "Exporting logs…",
"日志已保存到:{0}": "Logs saved to: {0}",
"日志包已生成,请查看浏览器下载。": "Log archive created. Check your browser downloads.",
"日志包缺少数据": "Log archive data is missing",
"导出本体、插件和渲染日志及服务状态,不包含插件配置和访问密码文件。": "Export Framely, plugin and renderer logs with service status. Plugin settings and access password files are excluded.",
"发现可用发行版本": "Release available",
"稍后": "Later",
"全部包含的分类": "Categories included in All",
"只影响全部分类,其他分类和收藏仍可访问。": "Only affects All. Other categories and Favorites remain available.",
"包含 Framely": "Includes Framely",
"启动方式、菜单与分类。": "Launch controls, menus and categories.",
"没有匹配的应用": "No matching apps",
"还没有收藏的应用": "No favorites yet",
"收藏分类": "Favorites",
"读音搜索暂不可用,仍可使用原文搜索。": "Phonetic search is unavailable. You can still search original names.",
"启动方式与菜单": "Launch controls and menus"
}
}
+97 -1
View File
@@ -83,6 +83,8 @@
"管理 {0}": "管理 {0}",
"未找到插件": "未找到插件",
"没有收藏的插件": "没有收藏的插件",
"没有已启用的插件": "没有已启用的插件",
"打开插件管理以启用插件。": "打开插件管理以启用插件。",
"还没有安装插件": "还没有安装插件",
"换一个关键词再试。": "换一个关键词再试。",
"点击插件旁的星标,将它加入常用。": "点击插件旁的星标,将它加入常用。",
@@ -384,6 +386,100 @@
"仅检查正式版。": "仅检查正式版。",
"仅检查测试版(Preview、Beta、RC 等)。": "仅检查测试版(Preview、Beta、RC 等)。",
"所选渠道暂无可用发行版本。": "所选渠道暂无可用发行版本。",
"所选版本早于当前版本,安装将切换到较旧版本。": "所选版本早于当前版本,安装将切换到较旧版本。"
"所选版本早于当前版本,安装将切换到较旧版本。": "所选版本早于当前版本,安装将切换到较旧版本。",
"通知": "通知",
"收件箱": "收件箱",
"收件箱为空": "收件箱为空",
"需要保留的通知会出现在这里。": "需要保留的通知会出现在这里。",
"移除通知": "移除通知",
"{0} 秒后关闭": "{0} 秒后关闭",
"启用此插件后可使用通知操作。": "启用此插件后可使用通知操作。",
"Framely {0} 可更新": "Framely {0} 可更新",
"查看新版本并选择安装,或忽略本次提醒。": "查看新版本并选择安装,或忽略本次提醒。",
"忽略": "忽略",
"打开更新": "打开更新",
"自动检查更新": "自动检查更新",
"检查间隔": "检查间隔",
"每 {0} 小时": "每 {0} 小时",
"发现新版本时发送通知,您可以忽略提醒或打开更新页面。": "发现新版本时发送通知,您可以忽略提醒或打开更新页面。",
"正在自动检查更新…": "正在自动检查更新…",
"自动检查未完成,将在下次检查时重试。": "自动检查未完成,将在下次检查时重试。",
"Notification has changed": "通知已更新,请重试。",
"Notification inbox full": "通知收件箱已满,请先移除旧通知。",
"自动检查间隔须为 1-168 小时": "自动检查间隔须为 1-168 小时",
"Update source or channel has changed": "更新源或渠道已变更。",
"Notification queue full": "浮动通知队列已满。",
"每小时": "每小时",
"允许通知": "允许通知",
"允许在视野中显示悬浮通知。": "允许在视野中显示悬浮通知。",
"悬浮已关闭,新通知仅在此处查看。": "悬浮已关闭,新通知仅在此处查看。",
"通知设置": "通知设置",
"选择通知如何提醒你。": "选择通知如何提醒你。",
"悬浮通知": "悬浮通知",
"关闭后,新通知将保存在通知收件箱,不显示浮窗。": "关闭后,新通知将保存在通知收件箱,不显示浮窗。",
"启动图标角标": "启动图标角标",
"在 Framely 启动图标上显示未读收件箱消息数。": "在 Framely 启动图标上显示未读收件箱消息数。",
"插件通知": "插件通知",
"搜索通知插件": "搜索通知插件",
"全局开关优先;关闭全局开关不会改变插件偏好。": "全局开关优先;关闭全局开关不会改变插件偏好。",
"角标": "角标",
"悬浮": "悬浮",
"{0}:角标": "{0}:角标",
"{0}:悬浮": "{0}:悬浮",
"通知设置导航": "通知设置",
"应用通知": "应用通知",
"搜索通知应用": "搜索通知应用",
"搜索应用": "搜索应用",
"全局开关优先;关闭全局开关不会改变应用偏好。": "全局开关优先;关闭全局开关不会改变应用偏好。",
"应用": "应用",
"未找到应用": "未找到应用",
"本体通知,包括检查更新提醒。": "本体通知,包括检查更新提醒。",
"启动台": "启动台",
"主扳机打开启动台": "主扳机打开启动台",
"开启后,上扳机打开快捷面板。": "开启后,上扳机打开快捷面板。",
"长按菜单自动关闭": "长按菜单自动关闭",
"指针离开后开始计时,移入后取消。": "指针离开后开始计时,移入后取消。",
"自动关闭时间(秒)": "自动关闭时间(秒)",
"Steam": "Steam",
"快捷面板": "快捷面板",
"卸载插件": "卸载插件",
"正在执行…": "正在执行…",
"插件没有快捷页面": "插件没有快捷页面",
"没有可启动的应用": "没有可启动的应用",
"正在读取 Steam 应用…": "正在读取 Steam 应用…",
"长按插件图标查看操作": "长按插件图标查看操作",
"卸载 {0}?": "卸载 {0}?",
"依赖此插件的应用也会停用;插件数据会保留。": "依赖此插件的应用也会停用;插件数据会保留。",
"确认卸载": "确认卸载",
"收藏": "收藏",
"取消收藏": "取消收藏",
"要求 Framely:{0}": "要求 Framely:{0}",
" · 不兼容": " · 不兼容",
"分页": "分页",
"第 {0} 页": "第 {0} 页",
"桌面程序": "桌面程序",
"拖动图标排列,移到两侧翻页": "拖动图标排列,移到两侧翻页",
"完成": "完成",
"整理图标": "整理图标",
"正在读取本机应用…": "正在读取本机应用…",
"Lepton": "Lepton",
"打开": "打开",
"导出日志": "导出日志",
"正在导出日志…": "正在导出日志…",
"日志已保存到:{0}": "日志已保存到:{0}",
"日志包已生成,请查看浏览器下载。": "日志包已生成,请查看浏览器下载。",
"日志包缺少数据": "日志包缺少数据",
"导出本体、插件和渲染日志及服务状态,不包含插件配置和访问密码文件。": "导出本体、插件和渲染日志及服务状态,不包含插件配置和访问密码文件。",
"发现可用发行版本": "发现可用发行版本",
"稍后": "稍后",
"全部包含的分类": "全部包含的分类",
"只影响全部分类,其他分类和收藏仍可访问。": "只影响全部分类,其他分类和收藏仍可访问。",
"包含 Framely": "包含 Framely",
"启动方式、菜单与分类。": "启动方式、菜单与分类。",
"没有匹配的应用": "没有匹配的应用",
"还没有收藏的应用": "还没有收藏的应用",
"收藏分类": "收藏",
"读音搜索暂不可用,仍可使用原文搜索。": "读音搜索暂不可用,仍可使用原文搜索。",
"启动方式与菜单": "启动方式与菜单"
}
}
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more