diff --git a/Cargo.lock b/Cargo.lock index 75795cd..871082e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -291,7 +291,7 @@ dependencies = [ [[package]] name = "framely" -version = "0.4.2-preview.12" +version = "0.4.3-preview.1" dependencies = [ "anyhow", "base64", diff --git a/Cargo.toml b/Cargo.toml index 316d2a5..4f3fe21 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "framely" -version = "0.4.2-preview.12" +version = "0.4.3-preview.1" edition = "2021" license = "AGPL-3.0-only" diff --git a/README.md b/README.md index 5850ff8..58eee17 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/README.zh-CN.md b/README.zh-CN.md index fe7525f..ec956cc 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -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 终端安装最新正式版: diff --git a/docs/developer-guide/sdk.md b/docs/developer-guide/sdk.md index c136416..4dbbac5 100644 --- a/docs/developer-guide/sdk.md +++ b/docs/developer-guide/sdk.md @@ -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` | 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 diff --git a/docs/images/plugin-library.png b/docs/images/plugin-library.png new file mode 100644 index 0000000..3628f01 Binary files /dev/null and b/docs/images/plugin-library.png differ diff --git a/docs/user-guide/basic-usage.md b/docs/user-guide/basic-usage.md index 7532207..3043284 100644 --- a/docs/user-guide/basic-usage.md +++ b/docs/user-guide/basic-usage.md @@ -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,14 @@ 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. diff --git a/docs/zh-CN/developer-guide/sdk.md b/docs/zh-CN/developer-guide/sdk.md index fbe281f..6ca052d 100644 --- a/docs/zh-CN/developer-guide/sdk.md +++ b/docs/zh-CN/developer-guide/sdk.md @@ -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` | 查询本插件声明的依赖状态 | | `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 diff --git a/docs/zh-CN/user-guide/basic-usage.md b/docs/zh-CN/user-guide/basic-usage.md index 9650696..a976ab9 100644 --- a/docs/zh-CN/user-guide/basic-usage.md +++ b/docs/zh-CN/user-guide/basic-usage.md @@ -9,10 +9,11 @@ 在 SteamVR Dashboard 点击 Framely Dock 图标打开快捷菜单。首次访问需阅读并同意协议及隐私声明;未同意时插件不会自动启动。 - **常用**:打开收藏的插件快捷页。 -- **已安装**:查看本机插件,进入插件页面。 -- **设置**:语言、安全模式和“管理插件”入口。 +- **已安装**:查看已启用的本机插件,进入插件页面。 +- **通知**:查看收件箱消息和更新提醒,并控制悬浮通知。 +- **设置**:选择已安装的语言、切换安全模式,或打开“管理插件”和“检查更新”。“检查更新”打开管理窗口的关于/更新页面;安装语言文件和下载语言模板在管理窗口的设置中进行。 -“管理插件”打开独立大窗口,左侧导航进入插件、插件库、插件源、设置和关于。安装、更新及来源管理在这里完成;电脑或手机也可使用[网络管理面板](network-panel.md)。 +“管理插件”打开独立大窗口,左侧导航进入插件、插件库、插件源、设置、通知设置和关于。安装、更新及来源管理在这里完成;电脑或手机也可使用[网络管理面板](network-panel.md)。 ## 插件启停与窗口 @@ -29,3 +30,17 @@ 在“关于”选择正式版或测试版渠道并检查更新,点击“下载并安装”并确认一次:Framely 下载、校验发行包后自动开始安装。下载和校验分别显示阶段提示与实际字节进度。下载或校验失败时停止安装并显示原因。插件和数据保留,Framely 界面会暂时关闭并重新启动。 日志排查命令见[安装指南](installation.md#修复与日志)。界面能打开不代表所有插件都正常;先逐个启用,确认运行身份与来源可信。 + +## 通知收件箱与自动更新检查 + +快捷面板的“通知”标签展示明确设置为进入收件箱的消息,浮窗启用时,普通通知默认不保存;浮窗关闭时会转存到收件箱。浮动通知显示自动关闭倒计时,关闭浮动通知会保留已保存的收件箱副本;收件箱里的删除按钮会移除消息。通知按钮默认在操作成功后关闭弹窗并移除收件箱副本,发送方可以分别修改这两个行为。 + +“通知”顶部的“允许通知”开关控制全局浮窗。关闭后,新通知即使没有声明进入收件箱也会保存到这里,正在显示的浮窗也会转存。重新开启不会重新弹出旧消息。 + +悬浮通知跟随头显,显示在视野内右上方。激光命中区域与实际卡片对齐,短按按钮可容忍小幅追踪抖动。 + +管理窗口的“通知设置”提供全局“悬浮通知”和“启动图标角标”开关,并为 Framely 本体(包括更新提醒)及所有已安装插件(包括已停用插件)提供独立的“角标”和“悬浮”开关。全局开关优先,关闭后仍保留各应用偏好。Framely Dock 启动图标的角标统计允许显示角标来源的未读收件箱消息,超过 99 显示 `99+`;实际打开通知标签后消除角标,隐藏的头显面板不会自动标记已读。查看消息不会删除消息,也不会关闭其操作按钮。设置和已读状态均会保存并在重启后恢复。 + +本体默认在启动约 30 秒后检查更新(须已接受用户协议),之后每 6 小时检查一次;面板关闭时也会继续检查。可在管理窗口“关于”的更新页关闭自动检查或修改间隔。自动检查遵循所选正式版/测试版渠道及代理配置,只检查并提醒,不会自动下载或安装。 + +发现较新版本后会将提醒保存在收件箱,通知设置允许时同时显示浮窗。“忽略”关闭并移除此版本提醒,同一版本在重启后也不会重复提醒;“打开更新”直接打开管理窗口的更新页面。更改更新源或渠道会清除旧提醒。 diff --git a/examples/showcase/page.tsx b/examples/showcase/page.tsx index 7dafc19..c20443c 100644 --- a/examples/showcase/page.tsx +++ b/examples/showcase/page.tsx @@ -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){try{setResult(JSON.stringify(await f(),null,2));}catch(e){setResult(String(e));}}return <>
每个按钮都调用正式 SDK。

setText(e.target.value)}/>
{result}
{Array.from({length:12},(_,i)=>

测试条目 {i+1}

)}
} +function Page(){const [text,setText]=useState('');const [result,setResult]=useState('');const [count,setCount]=useState(0);async function run(f:()=>Promise){try{setResult(JSON.stringify(await f(),null,2));}catch(e){setResult(String(e));}}return <>
每个按钮都调用正式 SDK。

setText(e.target.value)}/>
{result}
{Array.from({length:12},(_,i)=>

测试条目 {i+1}

)}
} registerPlugin({QuickPage:Page,WindowPage:Page}); diff --git a/native/host.cpp b/native/host.cpp index c9d7456..5ef7ce6 100644 --- a/native/host.cpp +++ b/native/host.cpp @@ -11,10 +11,12 @@ #include "overlay_placement.h" #include "render_resolution.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 #include #include @@ -40,7 +42,9 @@ static vr::IVRSystem* vr_system=nullptr; static Display* xdisplay=nullptr; static GLXContext glcontext=nullptr; static GLXPbuffer glsurface=0; +static std::atomic notification_badge_count{0}; 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,8 +63,8 @@ template 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; + OverlayPlacement placement;NotificationClick notification_click;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]{};std::vector pixels; }; static std::map> views; @@ -99,7 +103,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 dock_icon(bool hover,bool active){ - auto source=icon(hover,active);std::vector canvas(dock_canvas_width*dock_canvas_height*4,0); + auto source=icon(hover,active);notification_badge(source,notification_badge_count.load());std::vector canvas(dock_canvas_width*dock_canvas_height*4,0); for(int row=0;rowSetOverlayCursorPositionOverride(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 "<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 "<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 "<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 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")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){ @@ -144,11 +170,23 @@ 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 "<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();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; 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){ @@ -177,9 +215,9 @@ static void plugin_thumbnail(View& view,const std::string& encoded){ for(int y=0;ySetOverlayRaw(view.thumbnail,pixels.data(),128,128,4); } -static void commands(){std::deque commands;{std::lock_guard 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 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 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()+"."+c.at("window").get();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: "< commands;{std::lock_guard 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 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:""),true,1440,810);if(page=="catalog"||page=="updates"||page=="notification-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;}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 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()+"."+c.at("window").get();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");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: "<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 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"<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!="notifications"||!v.notification_click.active)v.host->send_mouse_move_event(v.host,&mouse,1);break;case vr::VREvent_MouseMove: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=="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")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+1closed=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")<<"] "<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_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: "<key<<"\n";close_view(*v);if(v->key=="menu")running=0;}}; 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< 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: "< 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: "<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,7 +256,7 @@ 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}},¢er)&&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_at0)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_atIsOverlayVisible(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; @@ -269,10 +307,20 @@ int main(int argc,char** argv){ auto error=overlays->SetOverlayIntersectionMask(v->overlay,&mask,1); if(error){std::cerr<<"Notification input mask failed "<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 lock(visibility_mutex);visible_views=std::move(snapshot);} if(keyboard_close_pending){ @@ -282,7 +330,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||icon_hover!=hovered||icon_badge!=badge){icon_badge=badge;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; 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. diff --git a/native/notification_badge.h b/native/notification_badge.h new file mode 100644 index 0000000..4e04f93 --- /dev/null +++ b/native/notification_badge.h @@ -0,0 +1,28 @@ +#pragma once +#include +#include +#include +#include + +// 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& 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;y36)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 #include #include +#include +#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& 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& pixels if(xright)right=x;if(yhigh)high=y; } if(rightstd::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;} +}; diff --git a/native/plugin_navigation.h b/native/plugin_navigation.h new file mode 100644 index 0000000..1260fa6 --- /dev/null +++ b/native/plugin_navigation.h @@ -0,0 +1,21 @@ +#pragma once +#include + +// 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; +} diff --git a/package-lock.json b/package-lock.json index eacbd8c..827cef8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index 3df39c2..3aa3036 100644 --- a/package.json +++ b/package.json @@ -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" }, diff --git a/sdk/src/index.tsx b/sdk/src/index.tsx index 3aa482c..fd7b4f1 100644 --- a/sdk/src/index.tsx +++ b/sdk/src/index.tsx @@ -4,8 +4,8 @@ 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;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={ @@ -14,7 +14,7 @@ export const framely={ call:(method:string,params:unknown={}):Promise=>bridge().request('call',{method,params}), windows:{open:(window:string)=>bridge().request('window.open',{window}),close:(window:string)=>bridge().request('window.close',{window})}, dependencies:():Promise=>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}){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();console.log('FRAMELY_PLUGIN_READY');} diff --git a/src/model.rs b/src/model.rs index 01f8d69..223466b 100644 --- a/src/model.rs +++ b/src/model.rs @@ -583,13 +583,121 @@ pub struct Database { pub update_source: Option, #[serde(default, skip_serializing_if = "UpdateChannel::is_stable")] pub update_channel: UpdateChannel, + #[serde(default)] + pub update_check: UpdateCheckSettings, + #[serde(default)] + pub update_notice: Option, + #[serde(default)] + pub notification_inbox: BTreeMap, + #[serde(default)] + pub notification_settings: NotificationSettings, +} +#[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, +} +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, + pub popups: Option, + pub badge: Option, +} +#[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, + pub toast: bool, + pub in_inbox: bool, + #[serde(default)] + pub read: bool, + pub notification: Notification, + #[serde(default)] + pub update: Option, } #[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 +711,8 @@ pub struct Notification { pub actions: Vec, #[serde(default = "ttl")] pub duration_ms: u64, + #[serde(default)] + pub inbox: bool, } fn ttl() -> u64 { 8000 @@ -615,7 +725,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(); diff --git a/src/service.rs b/src/service.rs index 54d54ea..0f9e215 100644 --- a/src/service.rs +++ b/src/service.rs @@ -31,7 +31,12 @@ pub struct Service { pub manager: u32, running: BTreeMap, pub events: Events, - notifications: BTreeMap, + notifications: BTreeMap, + automatic_updater: crate::update::Updater, + auto_update_job: Option<(String, UpdateSource, UpdateChannel)>, + next_update_check: Instant, + last_update_check: Option, + auto_update_error: Option, rates: BTreeMap>, recovery: BTreeMap, updater: crate::update::Updater, @@ -43,6 +48,7 @@ pub struct Service { } impl Service { pub fn prepare_uninstall(&mut self) -> Result { + self.cancel_automatic_check(); self.updater.ensure_idle()?; self.updater.jobs.ensure_idle()?; let roots: Vec<_> = self.db.plugins.keys().cloned().collect(); @@ -73,8 +79,10 @@ impl Service { .with_context(|| format!("插件 {id} 卸载失败,本体保留,请重试"))?; fs::remove_dir_all(self.root.join("plugins").join(id))?; self.db.plugins.remove(id); + self.db.notification_settings.plugins.remove(id); self.runtime.remove(id); - self.save()?; + self.notifications.retain(|_, n| n.plugin != *id); + self.save_notifications()?; } Ok(json!({"uninstalled": ids})) } @@ -86,6 +94,7 @@ impl Service { } else { Database::default() }; + db.update_check.validate()?; if db.update_source.is_none() { db.update_source = fs::read(root.join("update-source.json")) .ok() @@ -146,6 +155,15 @@ impl Service { } } } + let notifications = db + .notification_inbox + .iter() + .map(|(key, entry)| { + let mut entry = entry.clone(); + entry.toast = false; + (key.clone(), entry) + }) + .collect(); let service = Self { verifier: Default::default(), root: root.into(), @@ -153,7 +171,12 @@ impl Service { manager, running: BTreeMap::new(), events: Arc::default(), - notifications: BTreeMap::new(), + notifications, + automatic_updater: Default::default(), + auto_update_job: None, + next_update_check: Instant::now() + Duration::from_secs(30), + last_update_check: None, + auto_update_error: None, rates: BTreeMap::new(), recovery: BTreeMap::new(), updater: crate::update::Updater::default(), @@ -222,7 +245,10 @@ impl Service { ); } fn cleanup_resources(&mut self, id: &str) { - self.notifications.retain(|_, v| v["plugin"] != id); + for entry in self.notifications.values_mut().filter(|v| v.plugin == id) { + entry.toast = false; + } + self.notifications.retain(|_, v| v.toast || v.in_inbox); self.rates.remove(id); process::event(&self.events, json!({"kind":"plugin.disabled","plugin":id})); process::event( @@ -507,6 +533,7 @@ impl Service { Ok(()) } pub fn shutdown(&mut self) { + self.cancel_automatic_check(); let roots: Vec<_> = self.running.keys().cloned().collect(); let ids = crate::relations::order(&self.db, &roots, false).unwrap_or(roots); for id in ids.into_iter().rev() { @@ -583,6 +610,7 @@ impl Service { } } pub fn maintenance(&mut self) { + self.expire_notifications(); if self.visibility.expire(Instant::now()) { self.publish_visibility(); } @@ -590,6 +618,7 @@ impl Service { if !self.agreement_accepted() { return; } + self.automatic_update_check(); let now = Instant::now(); let exited: Vec<_> = self .running @@ -690,6 +719,7 @@ impl Service { "status" | "events" | "host.ui.visibility" + | "host.notification.badge" | "ui.visibility.get" | "language.list" | "language.save" @@ -778,6 +808,9 @@ impl Service { self.stop_one(&id, "agreement-revoked"); } self.notifications.clear(); + self.db.notification_inbox.clear(); + self.cancel_automatic_check(); + self.save()?; process::event(&self.events, json!({"kind":"agreement.revoked"})); Ok(json!(true)) } @@ -805,7 +838,7 @@ impl Service { "status" => { self.maintenance(); Ok( - json!({"agreement":{"version":AGREEMENT_VERSION,"accepted":self.agreement_accepted()},"version":env!("CARGO_PKG_VERSION"),"build":fs::read_to_string(self.root.join("current/VERSION")).unwrap_or_else(|_|env!("CARGO_PKG_VERSION").into()).trim(),"systemUpdate":fs::read(self.root.join("update-status.json")).ok().and_then(|b|serde_json::from_slice::(&b).ok()),"previousRelease":fs::read_to_string(self.root.join("previous-release")).ok().filter(|s|!s.trim().is_empty()),"apiVersion":API_VERSION,"runtime":self.runtime,"database":self.db,"running":self.running.iter_mut().filter_map(|(id,r)|if !r.exited(){Some(id.clone())}else{None}).collect::>(),"notifications":self.notifications.values().collect::>() }), + json!({"agreement":{"version":AGREEMENT_VERSION,"accepted":self.agreement_accepted()},"version":env!("CARGO_PKG_VERSION"),"build":fs::read_to_string(self.root.join("current/VERSION")).unwrap_or_else(|_|env!("CARGO_PKG_VERSION").into()).trim(),"systemUpdate":fs::read(self.root.join("update-status.json")).ok().and_then(|b|serde_json::from_slice::(&b).ok()),"previousRelease":fs::read_to_string(self.root.join("previous-release")).ok().filter(|s|!s.trim().is_empty()),"apiVersion":API_VERSION,"runtime":self.runtime,"database":self.db,"running":self.running.iter_mut().filter_map(|(id,r)|if !r.exited(){Some(id.clone())}else{None}).collect::>(),"notifications":self.notifications.values().filter(|n| n.toast).collect::>(),"inbox":self.notifications.values().filter(|n| n.in_inbox).collect::>(),"notificationBadge":self.notification_badge(),"automaticUpdate":{"checking":self.auto_update_job.is_some(),"lastCheckedAt":self.last_update_check,"error":self.auto_update_error} }), ) } "inspect" => { @@ -933,7 +966,9 @@ impl Service { } } self.db.plugins.remove(&id); - self.save()?; + self.db.notification_settings.plugins.remove(&id); + self.notifications.retain(|_, n| n.plugin != id); + self.save_notifications()?; fs::remove_dir_all(self.root.join("plugins").join(&id))?; if p["purge"].as_bool() == Some(true) { let data = self.root.join("data").join(&id); @@ -997,42 +1032,103 @@ impl Service { ); Ok(json!(true)) } - "notification.send" => self.notify(&id, p["notification"].clone()), - "notification.remove" => { - self.active(&id)?; - let key = p["id"].as_str().context("Missing notification ID")?; - valid_id(key)?; - self.notifications.remove(&format!("{id}:{key}")); - process::event(&self.events, json!({"kind":"notification.changed"})); + "host.notification.badge" => Ok(json!(self.notification_badge())), + "notification.settings.save" => { + let patch: NotificationSettingsPatch = serde_json::from_value(p)?; + ensure!( + patch.popups.is_some() || patch.badge.is_some(), + "Missing notification setting" + ); + let mut settings = self.db.notification_settings.clone(); + if let Some(id) = patch.plugin { + // Core notifications already use the empty sender identity. + if !id.is_empty() { + self.plugin(&id)?; + } + let preference = settings.plugins.entry(id).or_default(); + if let Some(value) = patch.popups { + preference.popups = value; + } + if let Some(value) = patch.badge { + preference.badge = value; + } + } else { + if let Some(value) = patch.popups { + settings.popups = value; + } + if let Some(value) = patch.badge { + settings.badge = value; + } + } + self.expire_notifications(); + let new_inbox = self + .notifications + .values() + .filter(|n| n.in_inbox || n.toast && !settings.popups_for(&n.plugin)) + .count(); + ensure!(new_inbox <= 256, "Notification inbox full"); + self.db.notification_settings = settings; + for entry in self.notifications.values_mut() { + if entry.toast && !self.db.notification_settings.popups_for(&entry.plugin) { + entry.toast = false; + entry.in_inbox = true; + } + } + self.save_notifications()?; Ok(json!(true)) } - "notification.action" => { - let key = p["id"].as_str().context("Missing ID")?; - let action = p["action"].as_str().context("Missing action")?; - let n = self - .notifications - .get(&format!("{id}:{key}")) - .context("Notification expired")?; - ensure!( - n["expiresAt"].as_u64().unwrap_or(0) > now_ms(), - "Notification expired" - ); - ensure!( - n["notification"]["actions"] - .as_array() - .is_some_and(|a| a.iter().any(|v| v["id"] == action)), - "Action not declared" - ); - process::event( - &self.events, - json!({"kind":"plugin.event","plugin":id,"event":"notification.action","data":{"id":key,"action":action}}), - ); - if self.active(&id)?.manifest.backend.is_some() { - self.handle("plugin.call",json!({"plugin":id,"method":"notification.action","params":{"id":key,"action":action}})) - } else { - Ok(json!(true)) + "notification.read" => { + #[derive(serde::Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct ReadEntry { + plugin: String, + id: String, + created_at: u64, } + let entries: Vec = serde_json::from_value(p["entries"].clone())?; + ensure!(entries.len() <= 256, "Too many notifications"); + let mut changed = false; + for item in entries { + if let Some(n) = self + .notifications + .get_mut(&format!("{}:{}", item.plugin, item.id)) + { + if n.in_inbox && !n.read && n.created_at == item.created_at { + n.read = true; + changed = true; + } + } + } + if changed { + self.save_notifications()?; + } + Ok(json!(true)) } + "notification.send" => self.notify(&id, p["notification"].clone()), + "notification.remove" | "notification.dismiss" => { + if !id.is_empty() { + self.plugin(&id)?; + } + let key = p["id"].as_str().context("Missing notification ID")?; + valid_id(key)?; + let compound = format!("{id}:{key}"); + if let Some(entry) = self.notifications.get_mut(&compound) { + ensure!( + p["createdAt"] + .as_u64() + .is_none_or(|time| time == entry.created_at), + "Notification has changed" + ); + entry.toast = false; + if method == "notification.remove" { + entry.in_inbox = false; + } + } + self.notifications.retain(|_, n| n.toast || n.in_inbox); + self.save_notifications()?; + Ok(json!(true)) + } + "notification.action" => self.notification_action(&id, &p), "events" => { let events: Vec<_> = self.events.lock().unwrap().drain(..).collect(); let mut out = Vec::new(); @@ -1055,8 +1151,7 @@ impl Service { out.push(e); } } - self.notifications - .retain(|_, v| v["expiresAt"].as_u64().unwrap_or(0) > now_ms()); + self.expire_notifications(); Ok(json!(out)) } "system.source.save" => { @@ -1072,6 +1167,7 @@ impl Service { } else { let _ = fs::remove_file(self.root.join("update-source.json")); } + self.reset_automatic_updates(); self.db.update_source = source; self.updater.clear(); self.save()?; @@ -1080,11 +1176,21 @@ impl Service { "system.channel.save" => { let channel: UpdateChannel = serde_json::from_value(p["channel"].clone())?; self.updater.ensure_idle()?; + self.reset_automatic_updates(); self.db.update_channel = channel; self.updater.clear(); self.save()?; Ok(json!(true)) } + "system.check.settings.save" => { + let settings: UpdateCheckSettings = serde_json::from_value(p["settings"].clone())?; + settings.validate()?; + self.cancel_automatic_check(); + self.db.update_check = settings; + self.next_update_check = Instant::now() + Duration::from_secs(30); + self.save()?; + Ok(json!(true)) + } "system.check.start" => self.updater.check( self.db.update_source.clone().context("请先设置更新源")?, self.db.update_channel, @@ -1305,15 +1411,269 @@ impl Service { } ensure!(rate.len() < 10, "Notification rate exceeded"); rate.push_back(now); + self.insert_notification(id, &name, n, None)?; + Ok(json!(true)) + } + fn insert_notification( + &mut self, + id: &str, + name: &str, + notification: Notification, + update: Option, + ) -> Result<()> { + self.expire_notifications(); + let key = format!("{id}:{}", notification.id); + let toast = self.db.notification_settings.popups_for(id); + let in_inbox = notification.inbox || !toast; ensure!( - self.notifications.len() < 64 - || self.notifications.contains_key(&format!("{id}:{}", n.id)), + !toast + || self.notifications.values().filter(|n| n.toast).count() < 64 + || self.notifications.get(&key).is_some_and(|n| n.toast), "Notification queue full" ); - let entry = json!({"plugin":id,"pluginName":name,"expiresAt":now_ms()+n.duration_ms,"notification":n}); - self.notifications.insert(format!("{id}:{}", n.id), entry); + ensure!( + !in_inbox + || self.notifications.values().filter(|n| n.in_inbox).count() < 256 + || self.notifications.get(&key).is_some_and(|n| n.in_inbox), + "Notification inbox full" + ); + let created_at = now_ms().max(self.notifications.get(&key).map_or(0, |n| n.created_at + 1)); + let expires_at = + (notification.duration_ms != 0).then(|| created_at + notification.duration_ms); + let entry = NotificationEntry { + plugin: id.into(), + plugin_name: name.into(), + created_at, + expires_at, + toast, + in_inbox, + read: false, + notification, + update, + }; + self.notifications.insert(key, entry); + self.save_notifications() + } + fn notification_badge(&self) -> usize { + if !self.agreement_accepted() { + return 0; + } + self.notifications + .values() + .filter(|n| n.in_inbox && !n.read && self.db.notification_settings.badge_for(&n.plugin)) + .count() + } + fn save_notifications(&mut self) -> Result<()> { + self.db.notification_inbox = self + .notifications + .iter() + .filter(|(_, n)| n.in_inbox) + .map(|(k, n)| (k.clone(), n.clone())) + .collect(); + self.save()?; process::event(&self.events, json!({"kind":"notification.changed"})); - Ok(json!(true)) + Ok(()) + } + fn expire_notifications(&mut self) { + let now = now_ms(); + let mut changed = false; + for n in self.notifications.values_mut() { + if n.toast && n.expires_at.is_some_and(|time| time <= now) { + n.toast = false; + changed = true; + } + } + self.notifications.retain(|_, n| n.toast || n.in_inbox); + if changed { + process::event(&self.events, json!({"kind":"notification.changed"})); + } + } + fn notification_action(&mut self, id: &str, p: &Value) -> Result { + self.expire_notifications(); + let key = p["id"].as_str().context("Missing ID")?; + let action = p["action"].as_str().context("Missing action")?; + let compound = format!("{id}:{key}"); + let entry = self + .notifications + .get(&compound) + .context("Notification expired")? + .clone(); + ensure!( + p["createdAt"] + .as_u64() + .is_none_or(|time| time == entry.created_at), + "Notification has changed" + ); + let policy = entry + .notification + .actions + .iter() + .find(|a| a.id == action) + .context("Action not declared")?; + let result = if let Some(update) = &entry.update { + ensure!( + self.db.update_source.as_ref() == Some(&update.source) + && self.db.update_channel == update.channel, + "Update source or channel has changed" + ); + match action { + "ignore" => json!(true), + "open" => { + process::event( + &self.events, + json!({"kind":"manager.open","page":"updates"}), + ); + json!({"openUpdates":true}) + } + _ => bail!("Action not declared"), + } + } else { + self.active(id)?; + let result = if self.plugin(id)?.manifest.backend.is_some() { + match self.handle("plugin.call", json!({"plugin":id,"method":"notification.action","params":{"id":key,"action":action}})) { + Ok(value) => value, + Err(error) => { + // Starting a failed backend may clear transient resources. Keep the + // message for retry, and never remove it as a successful action. + if self.notifications.get(&compound).is_none_or(|n| n.created_at == entry.created_at) { + self.notifications.insert(compound.clone(), entry.clone()); + self.save_notifications()?; + } + return Err(error); + } + } + } else { + json!(true) + }; + process::event( + &self.events, + json!({"kind":"plugin.event","plugin":id,"event":"notification.action","data":{"id":key,"action":action}}), + ); + result + }; + if let Some(n) = self + .notifications + .get_mut(&compound) + .filter(|n| n.created_at == entry.created_at) + { + if policy.close_on_click { + n.toast = false; + } + if policy.remove_from_inbox_on_click { + n.in_inbox = false; + } + } + self.notifications.retain(|_, n| n.toast || n.in_inbox); + self.save_notifications()?; + Ok(result) + } + fn cancel_automatic_check(&mut self) { + if let Some((job, _, _)) = self.auto_update_job.take() { + let _ = self.automatic_updater.jobs.cancel(&job); + } + self.auto_update_error = None; + } + fn reset_automatic_updates(&mut self) { + self.cancel_automatic_check(); + self.db.update_notice = None; + self.notifications.retain(|_, n| n.update.is_none()); + self.db.notification_inbox.retain(|_, n| n.update.is_none()); + self.next_update_check = Instant::now() + Duration::from_secs(30); + process::event(&self.events, json!({"kind":"notification.changed"})); + } + fn automatic_update_check(&mut self) { + if let Some((job, source, channel)) = self.auto_update_job.clone() { + if let Ok(result) = self.automatic_updater.jobs.status(&job) { + if matches!( + result["phase"].as_str(), + Some("done" | "failed" | "cancelled") + ) { + self.auto_update_job = None; + self.last_update_check = Some(now_ms()); + self.auto_update_error = result["error"].as_str().map(str::to_owned); + if result["phase"] == "done" + && self.db.update_check.enabled + && self.db.update_source.as_ref() == Some(&source) + && self.db.update_channel == channel + { + if let Err(e) = self.announce_update(&result["result"], source, channel) { + self.auto_update_error = Some(e.to_string()); + } + } + } + } else { + self.auto_update_job = None; + } + } + if !self.db.update_check.enabled + || self.auto_update_job.is_some() + || Instant::now() < self.next_update_check + || self.updater.ensure_idle().is_err() + { + return; + } + let Some(source) = self.db.update_source.clone() else { + return; + }; + let installing = fs::read(self.root.join("update-status.json")) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .is_some_and(|v| v["phase"] == "installing"); + if installing { + return; + } + self.next_update_check = + Instant::now() + Duration::from_secs(self.db.update_check.interval_hours * 3600); + match self.automatic_updater.check( + source.clone(), + self.db.update_channel, + self.db.proxy.clone(), + ) { + Ok(job) => { + self.auto_update_job = Some(( + job["job"].as_str().unwrap().into(), + source, + self.db.update_channel, + )); + self.auto_update_error = None; + } + Err(e) => { + self.auto_update_error = Some(e.to_string()); + self.last_update_check = Some(now_ms()); + } + } + } + fn announce_update( + &mut self, + result: &Value, + source: UpdateSource, + channel: UpdateChannel, + ) -> Result<()> { + let Some(version) = result["release"]["version"].as_str() else { + return Ok(()); + }; + let current = fs::read_to_string(self.root.join("current/VERSION")) + .unwrap_or_else(|_| env!("CARGO_PKG_VERSION").into()); + if crate::update::descriptor_version(version)? + .cmp_precedence(&crate::update::descriptor_version(current.trim())?) + != std::cmp::Ordering::Greater + { + return Ok(()); + } + let notice = UpdateNotice { + source, + channel, + version: version.into(), + }; + if self.db.update_notice.as_ref() == Some(¬ice) { + return Ok(()); + } + let notification: Notification = serde_json::from_value( + json!({"id":"framely.update","title":format!("Framely {version} is available"),"body":"Open Updates to review and install this version, or ignore this reminder.","inbox":true,"durationMs":15000,"actions":[{"id":"ignore","label":"Ignore"},{"id":"open","label":"Open updates"}]}), + )?; + self.insert_notification("", "Framely", notification, Some(notice.clone()))?; + self.db.update_notice = Some(notice); + self.save() } fn install(&mut self, p: Value) -> Result { ensure!( @@ -1914,3 +2274,435 @@ mod request_tests { assert_eq!(worker.join().unwrap(), json!(false)); } } + +#[cfg(test)] +mod notification_tests { + use super::*; + fn plugin(core: &mut Service) { + core.db.plugins.insert("test.notice".into(), serde_json::from_value(json!({"manifest":{"schemaVersion":1,"apiVersion":1,"id":"test.notice","name":"Notice tests","author":"Framely","version":"1.0.0","ui":{"quickPage":"page.js"},"files":{}},"enabled":true,"favorite":false,"order":0,"source":null})).unwrap()); + } + fn send(core: &mut Service, id: &str, extra: Value) { + let mut n = json!({"id":id,"title":"Download finished","body":"Ready to open","actions":[{"id":"open","label":"Open"}]}); + for (k, v) in extra.as_object().unwrap() { + n[k] = v.clone(); + } + core.handle( + "notification.send", + json!({"plugin":"test.notice","notification":n}), + ) + .unwrap(); + } + fn action(core: &mut Service, id: &str) -> Result { + core.handle( + "notification.action", + json!({"plugin":"test.notice","id":id,"action":"open"}), + ) + } + #[test] + fn popup_settings_preserve_suppressed_messages_and_survive_reload() { + let root = tempfile::tempdir().unwrap(); + let mut core = crate::tests::accepted_service(root.path(), 1000).unwrap(); + plugin(&mut core); + assert!(core.db.notification_settings.popups); + assert!(core.db.notification_settings.badge); + send(&mut core, "visible", json!({})); + core.handle("notification.settings.save", json!({"popups":false})) + .unwrap(); + assert!(!core.notifications["test.notice:visible"].toast); + assert!(core.notifications["test.notice:visible"].in_inbox); + send(&mut core, "silent", json!({})); + let status = core.handle("status", json!({})).unwrap(); + assert_eq!(status["notifications"].as_array().unwrap().len(), 0); + assert_eq!(status["inbox"].as_array().unwrap().len(), 2); + assert_eq!(status["notificationBadge"], 2); + let mut reloaded = Service::load(root.path(), 1000).unwrap(); + assert!(!reloaded.db.notification_settings.popups); + assert_eq!(reloaded.notification_badge(), 2); + reloaded + .handle("notification.settings.save", json!({"popups":true})) + .unwrap(); + assert!(reloaded.notifications.values().all(|n| !n.toast)); + send(&mut reloaded, "next", json!({})); + assert!(reloaded.notifications["test.notice:next"].toast); + assert!(!reloaded.notifications["test.notice:next"].in_inbox); + } + #[test] + fn plugin_notification_preferences_are_independent_and_global_switches_take_priority() { + let root = tempfile::tempdir().unwrap(); + let mut core = crate::tests::accepted_service(root.path(), 1000).unwrap(); + plugin(&mut core); + core.handle( + "notification.settings.save", + json!({"plugin":"test.notice","popups":false}), + ) + .unwrap(); + core.handle( + "notification.settings.save", + json!({"plugin":"test.notice","badge":false}), + ) + .unwrap(); + send(&mut core, "silent", json!({})); + assert!(!core.notifications["test.notice:silent"].toast); + assert!(core.notifications["test.notice:silent"].in_inbox); + assert_eq!(core.notification_badge(), 0); + core.handle( + "notification.settings.save", + json!({"plugin":"test.notice","badge":true}), + ) + .unwrap(); + assert_eq!(core.notification_badge(), 1); + core.handle( + "notification.settings.save", + json!({"badge":false,"popups":false}), + ) + .unwrap(); + core.handle( + "notification.settings.save", + json!({"plugin":"test.notice","popups":true}), + ) + .unwrap(); + send(&mut core, "global", json!({})); + assert!(!core.notifications["test.notice:global"].toast); + assert_eq!(core.notification_badge(), 0); + assert!(core.db.notification_settings.plugins["test.notice"].badge); + core.handle("notification.settings.save", json!({"badge":true})) + .unwrap(); + assert_eq!(core.notification_badge(), 2); + assert!(core + .handle( + "notification.settings.save", + json!({"plugin":"missing","badge":false}) + ) + .is_err()); + assert!(core + .handle("notification.settings.save", json!({"badge":"false"})) + .is_err()); + assert!(core + .handle("notification.settings.save", json!({"unknown":true})) + .is_err()); + assert_eq!(core.notification_badge(), 2); + } + #[test] + fn framely_notification_preferences_control_update_reminders_and_survive_reload() { + let root = tempfile::tempdir().unwrap(); + let mut core = crate::tests::accepted_service(root.path(), 1000).unwrap(); + plugin(&mut core); + send(&mut core, "saved", json!({"inbox":true})); + let source = UpdateSource { + url: "https://example.org/framely-release.json".into(), + }; + core.db.update_source = Some(source.clone()); + core.announce_update( + &json!({"release":{"version":"0.5.0-abcdef012345"}}), + source.clone(), + UpdateChannel::Stable, + ) + .unwrap(); + assert!(core.notifications[":framely.update"].toast); + assert_eq!(core.notification_badge(), 2); + core.handle( + "notification.settings.save", + json!({"plugin":"","popups":false,"badge":false}), + ) + .unwrap(); + assert!(core.db.notification_settings.popups && core.db.notification_settings.badge); + assert!(!core.notifications[":framely.update"].toast); + assert!(core.notifications[":framely.update"].in_inbox); + assert!(core.notifications["test.notice:saved"].toast); + assert_eq!(core.notification_badge(), 1); + core.announce_update( + &json!({"release":{"version":"0.5.1-abcdef012345"}}), + source, + UpdateChannel::Stable, + ) + .unwrap(); + assert!(!core.notifications[":framely.update"].toast); + assert!(core.notifications[":framely.update"].in_inbox); + let mut core = Service::load(root.path(), 1000).unwrap(); + assert!(!core.db.notification_settings.plugins[""].popups); + assert!(!core.db.notification_settings.plugins[""].badge); + assert_eq!(core.notification_badge(), 1); + core.handle( + "notification.settings.save", + json!({"plugin":"","badge":true}), + ) + .unwrap(); + assert_eq!(core.notification_badge(), 2); + assert!(!core.notifications[":framely.update"].toast); + core.handle("notification.settings.save", json!({"badge":false})) + .unwrap(); + assert_eq!(core.notification_badge(), 0); + assert!(core.db.notification_settings.plugins[""].badge); + } + #[test] + fn reading_inbox_clears_badge_without_removing_messages_or_reading_replacements() { + let root = tempfile::tempdir().unwrap(); + let mut core = crate::tests::accepted_service(root.path(), 1000).unwrap(); + plugin(&mut core); + send(&mut core, "saved", json!({"inbox":true})); + let old = core.notifications["test.notice:saved"].created_at; + send(&mut core, "saved", json!({"inbox":true})); + core.handle( + "notification.read", + json!({"entries":[{"plugin":"test.notice","id":"saved","createdAt":old}]}), + ) + .unwrap(); + assert_eq!(core.notification_badge(), 1); + let current = core.notifications["test.notice:saved"].created_at; + core.handle( + "notification.read", + json!({"entries":[{"plugin":"test.notice","id":"saved","createdAt":current}]}), + ) + .unwrap(); + assert_eq!(core.notification_badge(), 0); + assert!(core.notifications["test.notice:saved"].toast); + assert_eq!(core.db.notification_inbox.len(), 1); + let reloaded = Service::load(root.path(), 1000).unwrap(); + assert_eq!(reloaded.notification_badge(), 0); + assert!(reloaded.db.notification_inbox["test.notice:saved"].read); + } + #[test] + fn notifications_opt_in_to_persistent_inbox_and_default_actions_remove() { + let root = tempfile::tempdir().unwrap(); + let mut core = crate::tests::accepted_service(root.path(), 1000).unwrap(); + plugin(&mut core); + send(&mut core, "transient", json!({})); + send(&mut core, "saved", json!({"inbox":true})); + assert_eq!(core.db.notification_inbox.len(), 1); + core.notifications + .get_mut("test.notice:saved") + .unwrap() + .expires_at = Some(0); + core.notifications + .get_mut("test.notice:transient") + .unwrap() + .expires_at = Some(0); + core.expire_notifications(); + assert!(!core.notifications.contains_key("test.notice:transient")); + assert!(!core.notifications["test.notice:saved"].toast); + let mut reloaded = Service::load(root.path(), 1000).unwrap(); + assert_eq!(reloaded.notifications.len(), 1); + assert!(!reloaded.notifications["test.notice:saved"].toast); + action(&mut reloaded, "saved").unwrap(); + assert!(reloaded.notifications.is_empty()); + assert!(Service::load(root.path(), 1000) + .unwrap() + .db + .notification_inbox + .is_empty()); + } + #[test] + fn notification_action_policies_are_independent_and_stale_actions_are_rejected() { + let root = tempfile::tempdir().unwrap(); + let mut core = crate::tests::accepted_service(root.path(), 1000).unwrap(); + plugin(&mut core); + for close in [false, true] { + for remove in [false, true] { + let id = format!("policy.{close}.{remove}"); + send( + &mut core, + &id, + json!({"inbox":true,"durationMs":0,"actions":[{"id":"open","label":"Open","closeOnClick":close,"removeFromInboxOnClick":remove}]}), + ); + action(&mut core, &id).unwrap(); + let entry = core.notifications.get(&format!("test.notice:{id}")); + assert_eq!(entry.is_some(), !close || !remove); + if let Some(entry) = entry { + assert_eq!(entry.toast, !close); + assert_eq!(entry.in_inbox, !remove); + assert!(entry.expires_at.is_none()); + } + } + } + send(&mut core, "replace", json!({"inbox":true})); + let old = core.notifications["test.notice:replace"].created_at; + send(&mut core, "replace", json!({"inbox":true})); + assert!(core + .handle( + "notification.action", + json!({"plugin":"test.notice","id":"replace","action":"open","createdAt":old}) + ) + .is_err()); + assert!(core.notifications["test.notice:replace"].toast); + } + #[test] + fn dismiss_and_disable_keep_inbox_but_removal_drops_it() { + let root = tempfile::tempdir().unwrap(); + let mut core = crate::tests::accepted_service(root.path(), 1000).unwrap(); + plugin(&mut core); + send(&mut core, "saved", json!({"inbox":true})); + core.handle( + "notification.dismiss", + json!({"plugin":"test.notice","id":"saved"}), + ) + .unwrap(); + assert!(!core.notifications["test.notice:saved"].toast); + assert!(core.notifications["test.notice:saved"].in_inbox); + core.cleanup_resources("test.notice"); + core.db.plugins.get_mut("test.notice").unwrap().enabled = false; + assert!(action(&mut core, "saved").is_err()); + assert!(core.notifications.contains_key("test.notice:saved")); + core.handle( + "notification.remove", + json!({"plugin":"test.notice","id":"saved"}), + ) + .unwrap(); + assert!(core.db.notification_inbox.is_empty()); + } + #[test] + fn failed_notification_backend_keeps_message_for_retry() { + let root = tempfile::tempdir().unwrap(); + let mut core = crate::tests::accepted_service(root.path(), 1000).unwrap(); + plugin(&mut core); + crate::process::TEST_TOOLS + .with(|p| *p.borrow_mut() = Some(root.path().join("missing-tools"))); + send(&mut core, "saved", json!({"inbox":true})); + core.db + .plugins + .get_mut("test.notice") + .unwrap() + .manifest + .backend = + Some(serde_json::from_value(json!({"entry":"missing","runAs":"steamos"})).unwrap()); + assert!(action(&mut core, "saved").is_err()); + assert!(core.notifications["test.notice:saved"].toast); + assert!(core.db.notification_inbox.contains_key("test.notice:saved")); + crate::process::TEST_TOOLS.with(|p| *p.borrow_mut() = None); + } + #[test] + fn automatic_update_notifications_ignore_old_versions_and_deduplicate_after_reload() { + let root = tempfile::tempdir().unwrap(); + let mut core = crate::tests::accepted_service(root.path(), 1000).unwrap(); + let source = UpdateSource { + url: "https://example.org/framely-release.json".into(), + }; + core.db.update_source = Some(source.clone()); + for version in ["0.1.0", "0.4.2-preview.12-012345abcdef"] { + core.announce_update( + &json!({"release":{"version":version}}), + source.clone(), + UpdateChannel::Stable, + ) + .unwrap(); + assert!(core.notifications.is_empty()); + } + let result = json!({"release":{"version":"0.5.0-abcdef012345"}}); + core.announce_update(&result, source.clone(), UpdateChannel::Stable) + .unwrap(); + assert_eq!(core.notifications.len(), 1); + core.handle( + "notification.action", + json!({"id":"framely.update","action":"ignore"}), + ) + .unwrap(); + assert!(core.notifications.is_empty()); + let mut core = Service::load(root.path(), 1000).unwrap(); + core.announce_update(&result, source.clone(), UpdateChannel::Stable) + .unwrap(); + assert!(core.notifications.is_empty()); + core.announce_update( + &json!({"release":{"version":"0.5.1-abcdef012345"}}), + source, + UpdateChannel::Stable, + ) + .unwrap(); + assert_eq!( + core.handle( + "notification.action", + json!({"id":"framely.update","action":"open"}) + ) + .unwrap(), + json!({"openUpdates":true}) + ); + assert!(core + .events + .lock() + .unwrap() + .iter() + .any(|e| e["kind"] == "manager.open" && e["page"] == "updates")); + assert!(core.db.notification_inbox.is_empty()); + } + #[test] + fn automatic_update_schedule_settings_and_stale_completions() { + let root = tempfile::tempdir().unwrap(); + let mut core = crate::tests::accepted_service(root.path(), 1000).unwrap(); + let source = UpdateSource { + url: "https://example.org/framely-release.json".into(), + }; + core.db.update_source = Some(source.clone()); + assert!(core.db.update_check.enabled); + assert_eq!(core.db.update_check.interval_hours, 6); + core.handle( + "system.check.settings.save", + json!({"settings":{"enabled":false,"intervalHours":12}}), + ) + .unwrap(); + core.next_update_check = Instant::now(); + core.automatic_update_check(); + assert!(core.auto_update_job.is_none()); + assert!( + !Service::load(root.path(), 1000) + .unwrap() + .db + .update_check + .enabled + ); + for hours in [0, 169] { + assert!(core + .handle( + "system.check.settings.save", + json!({"settings":{"enabled":true,"intervalHours":hours}}) + ) + .is_err()); + } + core.db.update_check.enabled = true; + core.next_update_check = Instant::now() + Duration::from_secs(3600); + core.automatic_update_check(); + assert!(core.auto_update_job.is_none()); + // Inject a completed background job to exercise the timer's completion path + // without any external network request or UI polling. + let job = core + .automatic_updater + .jobs + .task("system.check", |_| { + Ok(json!({"release":{"version":"0.5.0-abcdef012345"}})) + }) + .unwrap(); + let id = job["job"].as_str().unwrap().to_owned(); + for _ in 0..100 { + if core.automatic_updater.jobs.status(&id).unwrap()["phase"] == "done" { + break; + } + std::thread::sleep(Duration::from_millis(5)); + } + core.auto_update_job = Some((id, source.clone(), UpdateChannel::Stable)); + core.automatic_update_check(); + assert_eq!(core.db.notification_inbox.len(), 1); + assert!(core.last_update_check.is_some()); + core.handle("system.channel.save", json!({"channel":"testing"})) + .unwrap(); + assert!(core.db.notification_inbox.is_empty()); + assert!(core.db.update_notice.is_none()); + // A result from the previous channel arriving late cannot recreate its reminder. + core.auto_update_job = Some(( + job["job"].as_str().unwrap().into(), + source, + UpdateChannel::Stable, + )); + core.automatic_update_check(); + assert!(core.db.notification_inbox.is_empty()); + // A due check advances the configured timer even if source validation fails; + // this exercises failure/retry scheduling without contacting a server. + core.db.update_source = Some(UpdateSource { + url: "file:///invalid-release.json".into(), + }); + core.next_update_check = Instant::now(); + core.automatic_update_check(); + assert!(core.auto_update_error.is_some()); + assert!(core.auto_update_job.is_none()); + assert!( + core.next_update_check.duration_since(Instant::now()) + > Duration::from_secs(12 * 3600 - 2) + ); + } +} diff --git a/src/session.rs b/src/session.rs index 4915ce1..3751804 100644 --- a/src/session.rs +++ b/src/session.rs @@ -358,7 +358,10 @@ 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})); } if let Some(rel) = path.strip_prefix("/plugin-assets/") { let (id, file) = rel.split_once('/').context("Invalid asset path")?; @@ -696,8 +699,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") + ) + { + command["page"] = p["page"].clone(); } push(&self.commands, command); Ok(json!(true)) @@ -787,8 +795,11 @@ impl Agent { | "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 +813,7 @@ impl Agent { | "safeMode" | "system.source.save" | "system.channel.save" + | "system.check.settings.save" | "system.check.start" | "system.download.start" | "system.job.status" @@ -1115,6 +1127,7 @@ pub fn serve( "window.close", "plugin.disabled", "notification.changed", + "manager.open", ] .contains(&e["kind"].as_str().unwrap_or("")) { @@ -1473,12 +1486,14 @@ mod tests { }) } #[test] - fn manager_store_entry_preserves_catalog_target_and_rejects_arbitrary_pages() { + 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!({}), json!({"page":"https://example.org"}), ] { @@ -1488,8 +1503,13 @@ 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"})); + assert_eq!(commands[4], json!({"kind":"manager.open"})); } #[test] fn declining_agreement_only_closes_current_view() { @@ -1871,7 +1891,11 @@ 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", + "agreement.status", + ] { let (mut stream, _) = listener.accept().unwrap(); let request = ipc::read(&mut stream).unwrap(); assert_eq!(request["method"], expected); @@ -2244,7 +2268,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", diff --git a/src/tests.rs b/src/tests.rs index 25fbcce..8ddf839 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -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()); diff --git a/src/update.rs b/src/update.rs index 3777ed7..14d0f78 100644 --- a/src/update.rs +++ b/src/update.rs @@ -150,7 +150,7 @@ struct GitHubRelease { draft: bool, assets: Vec, } -fn descriptor_version(version: &str) -> Result { +pub(crate) fn descriptor_version(version: &str) -> Result { // Runtime VERSION appends a twelve-digit content hash to the Cargo version. let version = version .rsplit_once('-') diff --git a/tests/browser_probe.cpp b/tests/browser_probe.cpp index 87393e5..a5fe28b 100644 --- a/tests/browser_probe.cpp +++ b/tests/browser_probe.cpp @@ -37,6 +37,7 @@ int main(int argc,char** argv){ 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()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(document.querySelectorAll(".store-card").length!==1)throw Error("versions duplicated plugin cards");document.querySelector(".framely-select button").click();const tag=await until(()=>[...document.querySelectorAll("[role=option]")].find(b=>b.textContent==="工具"));if(!tag)throw Error("tag missing");tag.click();await wait(100);if(document.querySelector(".store-card .run-user-badge")?.textContent!=="root")throw Error("store run user missing");document.querySelector(".store-card").click();await wait(100);if(!document.body.textContent.includes("Store integration details"))throw Error("detail missing");if(!document.querySelector(".store-detail .run-user-notice.is-root"))throw Error("store root warning missing");console.log("FRAMELY_PREVIEW_STORE");document.querySelector(".detail-heading button").click();const approve=await until(()=>[...document.querySelectorAll("button")].find(b=>b.textContent==="确认安装"));if(document.querySelector(".modal h2")?.textContent!=="更新 Bridge")throw Error("manual install update title missing");if(document.querySelector(".install-review .install-account")?.textContent!=="steamos")throw Error("install must use package identity");if(document.body.textContent.includes("权限变化"))throw Error("unexpected privilege change");approve.click();await until(()=>!document.querySelector(".modal"));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.database.plugins["test.bridge"].manifest.version!=="2.0.0")throw Error("install not persisted");const chooseVersion=async v=>{document.querySelector('.store-detail .framely-select button').click();const option=await until(()=>[...document.querySelectorAll('[role=option]')].find(b=>b.textContent.split(' · ')[0]===v));option.click();await wait(100);if(document.querySelector('.store-detail .install-account')?.textContent!==(v==='2.0.0'?'root':'steamos'))throw Error('selected version user incorrect');document.querySelector('.detail-heading button').click();const approveVersion=await until(()=>[...document.querySelectorAll('button')].find(b=>b.textContent==='确认安装'));approveVersion.click();await until(()=>!document.querySelector('.modal'));const result=await fetch('/api',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({method:'status',params:{}})}).then(r=>r.json());if(result.result.database.plugins['test.bridge'].manifest.version!==v)throw Error('selected version not installed '+v);};await chooseVersion('1');await chooseVersion('2.0.0');console.log('FRAMELY_VERSION_SELECTION_PASS');[...document.querySelectorAll("nav button")].find(b=>b.textContent==="插件源").click();const removeSub=await until(()=>[...document.querySelectorAll("button")].find(b=>b.textContent==="删除订阅"));removeSub.click();const confirm=await until(()=>[...document.querySelectorAll(".modal button")].find(b=>b.textContent==="确认"));confirm.click();await until(()=>!document.body.textContent.includes("Subscription fixture"));console.log("FRAMELY_BRIDGE_PASS");})().catch(e=>console.error("FRAMELY_BRIDGE_FAIL "+e)))JS":R"JS((async()=>{const wait=ms=>new Promise(r=>setTimeout(r,ms));await wait(300);if(innerWidth!==600||innerHeight!==840||devicePixelRatio!==2)throw Error('quick layout or DPI changed');const dpiButton=document.createElement('button');dpiButton.style.cssText='position:fixed;left:20px;top:20px;width:100px;height:50px;z-index:9999';dpiButton.textContent='DPI test';let clicked=false;dpiButton.onclick=()=>{clicked=true;console.log('FRAMELY_DPI_CLICK_PASS');};document.body.append(dpiButton);console.log('FRAMELY_DPI_CLICK_REQUEST');await wait(200);dpiButton.remove();if(!clicked)throw Error('logical pointer coordinates failed');const originalFetch=window.fetch;let pulses=0;window.fetch=function(url,init){if(init?.body&&JSON.parse(init.body).method==='host.haptic')pulses++;return originalFetch.call(this,url,init);};const fixture=document.createElement('div');fixture.innerHTML='';document.body.append(fixture);const children=fixture.querySelectorAll('span'),buttons=fixture.querySelectorAll('button');const over=e=>e.dispatchEvent(new PointerEvent('pointerover',{bubbles:true}));const leave=(e,target)=>e.dispatchEvent(new PointerEvent('pointerout',{bubbles:true,relatedTarget:target}));over(children[0]);leave(children[0],children[1]);over(children[1]);leave(children[1],children[2]);over(children[2]);leave(children[2],buttons[2]);over(buttons[2]);await wait(100);fixture.remove();window.fetch=originalFetch;if(pulses!==2)throw Error('hover count='+pulses);console.log('FRAMELY_HOVER_PASS');console.log('FRAMELY_PREVIEW_FAVORITES');[...document.querySelectorAll('nav button')].find(b=>b.textContent==='设置').click();await wait(200);console.log('FRAMELY_PREVIEW_SETTINGS');if(!document.querySelector('.quick-settings').firstElementChild.classList.contains('setting-entry'))throw Error('manager entry is below language settings');document.querySelector('.setting-entry').click();await wait(100);[...document.querySelectorAll('nav button')].find(b=>b.textContent==='已安装').click();await wait(200);console.log('FRAMELY_PREVIEW_INSTALLED');for(let i=0;i<100;i++){await wait(50);const b=document.querySelector('.plugin-main');if(b){b.click();return;}}console.error('FRAMELY_BRIDGE_FAIL manager plugin list timeout');})().catch(e=>console.error('FRAMELY_BRIDGE_FAIL '+e)))JS");f->execute_java_script(f,&code,&source,1);cef_string_utf16_clear(&code);f->base.release(&f->base);injected=true;}std::this_thread::sleep_for(std::chrono::milliseconds(5));} + while(std::chrono::steady_clock::now()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")].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(document.querySelectorAll(".store-card").length!==1)throw Error("versions duplicated plugin cards");document.querySelector(".framely-select button").click();const tag=await until(()=>[...document.querySelectorAll("[role=option]")].find(b=>b.textContent==="工具"));if(!tag)throw Error("tag missing");tag.click();await wait(100);if(document.querySelector(".store-card .run-user-badge")?.textContent!=="root")throw Error("store run user missing");document.querySelector(".store-card").click();await wait(100);if(!document.body.textContent.includes("Store integration details"))throw Error("detail missing");if(!document.querySelector(".store-detail .run-user-notice.is-root"))throw Error("store root warning missing");console.log("FRAMELY_PREVIEW_STORE");document.querySelector(".detail-heading button").click();const approve=await until(()=>[...document.querySelectorAll("button")].find(b=>b.textContent==="确认安装"));if(document.querySelector(".modal h2")?.textContent!=="更新 Bridge")throw Error("manual install update title missing");if(document.querySelector(".install-review .install-account")?.textContent!=="steamos")throw Error("install must use package identity");if(document.body.textContent.includes("权限变化"))throw Error("unexpected privilege change");approve.click();await until(()=>!document.querySelector(".modal"));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.database.plugins["test.bridge"].manifest.version!=="2.0.0")throw Error("install not persisted");const chooseVersion=async v=>{document.querySelector('.store-detail .framely-select button').click();const option=await until(()=>[...document.querySelectorAll('[role=option]')].find(b=>b.textContent.split(' · ')[0]===v));option.click();await wait(100);if(document.querySelector('.store-detail .install-account')?.textContent!==(v==='2.0.0'?'root':'steamos'))throw Error('selected version user incorrect');document.querySelector('.detail-heading button').click();const approveVersion=await until(()=>[...document.querySelectorAll('button')].find(b=>b.textContent==='确认安装'));approveVersion.click();await until(()=>!document.querySelector('.modal'));const result=await fetch('/api',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({method:'status',params:{}})}).then(r=>r.json());if(result.result.database.plugins['test.bridge'].manifest.version!==v)throw Error('selected version not installed '+v);};await chooseVersion('1');await chooseVersion('2.0.0');console.log('FRAMELY_VERSION_SELECTION_PASS');[...document.querySelectorAll("nav button")].find(b=>b.textContent==="插件源").click();const removeSub=await until(()=>[...document.querySelectorAll("button")].find(b=>b.textContent==="删除订阅"));removeSub.click();const confirm=await until(()=>[...document.querySelectorAll(".modal button")].find(b=>b.textContent==="确认"));confirm.click();await until(()=>!document.body.textContent.includes("Subscription fixture"));console.log("FRAMELY_BRIDGE_PASS");})().catch(e=>console.error("FRAMELY_BRIDGE_FAIL "+e)))JS":R"JS((async()=>{const wait=ms=>new Promise(r=>setTimeout(r,ms));await wait(300);if(innerWidth!==600||innerHeight!==840||devicePixelRatio!==2)throw Error('quick layout or DPI changed');const dpiButton=document.createElement('button');dpiButton.style.cssText='position:fixed;left:20px;top:20px;width:100px;height:50px;z-index:9999';dpiButton.textContent='DPI test';let clicked=false;dpiButton.onclick=()=>{clicked=true;console.log('FRAMELY_DPI_CLICK_PASS');};document.body.append(dpiButton);console.log('FRAMELY_DPI_CLICK_REQUEST');await wait(200);dpiButton.remove();if(!clicked)throw Error('logical pointer coordinates failed');const originalFetch=window.fetch;let pulses=0;window.fetch=function(url,init){if(init?.body&&JSON.parse(init.body).method==='host.haptic')pulses++;return originalFetch.call(this,url,init);};const fixture=document.createElement('div');fixture.innerHTML='';document.body.append(fixture);const children=fixture.querySelectorAll('span'),buttons=fixture.querySelectorAll('button');const over=e=>e.dispatchEvent(new PointerEvent('pointerover',{bubbles:true}));const leave=(e,target)=>e.dispatchEvent(new PointerEvent('pointerout',{bubbles:true,relatedTarget:target}));over(children[0]);leave(children[0],children[1]);over(children[1]);leave(children[1],children[2]);over(children[2]);leave(children[2],buttons[2]);over(buttons[2]);await wait(100);fixture.remove();window.fetch=originalFetch;if(pulses!==2)throw Error('hover count='+pulses);console.log('FRAMELY_HOVER_PASS');console.log('FRAMELY_PREVIEW_FAVORITES');[...document.querySelectorAll('nav button')].find(b=>b.textContent==='设置').click();await wait(200);console.log('FRAMELY_PREVIEW_SETTINGS');if(!document.querySelector('.quick-settings').firstElementChild.classList.contains('setting-entry'))throw Error('manager entry is below language settings');document.querySelector('.setting-entry').click();await wait(100);[...document.querySelectorAll('nav button')].find(b=>b.textContent==='已安装').click();await wait(200);console.log('FRAMELY_PREVIEW_INSTALLED');for(let i=0;i<100;i++){await wait(50);const b=document.querySelector('.plugin-main');if(b){b.click();return;}}console.error('FRAMELY_BRIDGE_FAIL manager plugin list timeout');})().catch(e=>console.error('FRAMELY_BRIDGE_FAIL '+e)))JS");f->execute_java_script(f,&code,&source,1);cef_string_utf16_clear(&code);f->base.release(&f->base);injected=true;}std::this_thread::sleep_for(std::chrono::milliseconds(5));} + 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="<base.release(&host->base);browser->base.release(&browser->base);cef_shutdown();return ok?0:5; } diff --git a/tests/notification_badge.cpp b/tests/notification_badge.cpp new file mode 100644 index 0000000..9ce46f4 --- /dev/null +++ b/tests/notification_badge.cpp @@ -0,0 +1,15 @@ +#include "notification_badge.h" +#include + +int main(){ + std::vector 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 invalid(12,0);notification_badge(invalid,1);assert(invalid==std::vector(12,0)); +} diff --git a/tests/notification_geometry.cpp b/tests/notification_geometry.cpp index 8da489b..89ab114 100644 --- a/tests/notification_geometry.cpp +++ b/tests/notification_geometry.cpp @@ -2,6 +2,47 @@ #include 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 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 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()); } diff --git a/tests/notification_settings_fixture.tsx b/tests/notification_settings_fixture.tsx new file mode 100644 index 0000000..e5695dc --- /dev/null +++ b/tests/notification_settings_fixture.tsx @@ -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; +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
{mode==='settings'?:}/>}
; +} +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();wait(150).then(()=>console.log('FRAMELY_VIEW_READY')); diff --git a/tests/notifications_fixture.tsx b/tests/notifications_fixture.tsx new file mode 100644 index 0000000..79632c8 --- /dev/null +++ b/tests/notifications_fixture.tsx @@ -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={'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=>({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
setValue([...entries])}/>
;} +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();wait(150).then(()=>console.log('FRAMELY_VIEW_READY')); diff --git a/tests/plugin_navigation.cpp b/tests/plugin_navigation.cpp new file mode 100644 index 0000000..0d31fc4 --- /dev/null +++ b/tests/plugin_navigation.cpp @@ -0,0 +1,13 @@ +#include "plugin_navigation.h" +#include +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)); +} diff --git a/tests/system_updates_fixture.tsx b/tests/system_updates_fixture.tsx index 1f31e00..74f60b5 100644 --- a/tests/system_updates_fixture.tsx +++ b/tests/system_updates_fixture.tsx @@ -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>,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,6 +43,14 @@ 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 input[type=checkbox]') as HTMLInputElement; + if(!automaticSwitch().checked)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')); if(!document.querySelector('.release-card')?.textContent?.includes('较旧版本'))throw Error('channel downgrade not identified'); button('下载并安装').focus();button('下载并安装').click();await wait(); @@ -72,7 +81,7 @@ async function choose(label:string){(document.querySelector('.framely-select but 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'); 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; diff --git a/tools/package-release.sh b/tools/package-release.sh index 9990fb4..654e2b9 100755 --- a/tools/package-release.sh +++ b/tools/package-release.sh @@ -26,6 +26,7 @@ cp native/vendor/openvr/lib/linuxarm64/libopenvr_api.so "$stage/lib/openvr/" cp -a ui/dist/. "$stage/share/ui/" 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/" diff --git a/tools/plugin-dev.mjs b/tools/plugin-dev.mjs index bfd155d..701b5e3 100644 --- a/tools/plugin-dev.mjs +++ b/tools/plugin-dev.mjs @@ -28,7 +28,7 @@ if(command==='init'){ 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(`
`);return;} + if(req.url==='/'||req.url==='/quick'||req.url?.startsWith('/window/')||req.url?.startsWith('/?')){res.setHeader('Content-Type','text/html');res.end(`
`);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)`)); diff --git a/tools/test-install-review.sh b/tools/test-install-review.sh index 37c8dc9..a6b3142 100755 --- a/tools/test-install-review.sh +++ b/tools/test-install-review.sh @@ -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`,'
'); 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]) diff --git a/tools/test-native.sh b/tools/test-native.sh index a64b9b3..4049617 100755 --- a/tools/test-native.sh +++ b/tools/test-native.sh @@ -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; do "${CXX:-g++}" -std=c++17 -O2 -Inative -Inative/vendor/openvr "tests/$test.cpp" -o "target/tests/$test" "target/tests/$test" done diff --git a/ui/locales/en-US.json b/ui/locales/en-US.json index 6aec176..866ce33 100644 --- a/ui/locales/en-US.json +++ b/ui/locales/en-US.json @@ -386,6 +386,53 @@ "仅检查正式版。": "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 apps found", + "本体通知,包括检查更新提醒。": "Framely notifications, including update reminders." } } diff --git a/ui/locales/zh-CN.json b/ui/locales/zh-CN.json index ad3935a..2449bde 100644 --- a/ui/locales/zh-CN.json +++ b/ui/locales/zh-CN.json @@ -386,6 +386,53 @@ "仅检查正式版。": "仅检查正式版。", "仅检查测试版(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}:悬浮", + "通知设置导航": "通知设置", + "应用通知": "应用通知", + "搜索通知应用": "搜索通知应用", + "搜索应用": "搜索应用", + "全局开关优先;关闭全局开关不会改变应用偏好。": "全局开关优先;关闭全局开关不会改变应用偏好。", + "应用": "应用", + "未找到应用": "未找到应用", + "本体通知,包括检查更新提醒。": "本体通知,包括检查更新提醒。" } } diff --git a/ui/src/language.tsx b/ui/src/language.tsx index 4e2e380..24de55e 100644 --- a/ui/src/language.tsx +++ b/ui/src/language.tsx @@ -2,12 +2,12 @@ import React,{useState} from 'react'; import {api} from './api'; import {Select} from './localized-select'; import {t,languages,resolveLanguage,LanguagePack} from './i18n'; -export function LanguageSettings({value,packs,invalidFiles,refresh}:{value:string;packs:LanguagePack[];invalidFiles:string[];refresh:()=>Promise}){ +export function LanguageSettings({value,packs,invalidFiles,refresh,selectionOnly=false}:{value:string;packs:LanguagePack[];invalidFiles:string[];refresh:()=>Promise;selectionOnly?:boolean}){ const[busy,setBusy]=useState(false),[error,setError]=useState(''); async function select(language:string){setBusy(true);setError('');try{await api('language.save',{language});await refresh();}catch(e){setError((e as Error).message);}finally{setBusy(false);}} async function install(file:File){setBusy(true);setError('');try{if(file.size>1024*1024)throw new Error(t('语言文件超过 1 MiB'));const pack=JSON.parse(await file.text());await api('language.install',{pack});await refresh();}catch(e){setError((e as Error).message);}finally{setBusy(false);}} - return

{t('语言')}

{t('下载语言文件模板')}
{invalidFiles.length>0&&

{t('无法读取语言文件:{0}',{0:invalidFiles.join(', ')})}

}{error&&

{error}

}
; + return

{t('语言')}

{!selectionOnly&&<>{t('下载语言文件模板')}}
{invalidFiles.length>0&&

{t('无法读取语言文件:{0}',{0:invalidFiles.join(', ')})}

}{error&&

{error}

}
; } export function LanguagePicker({value,packs,disabled,onChange}:{value:string;packs:LanguagePack[];disabled?:boolean;onChange:(language:string)=>void}){ diff --git a/ui/src/main.tsx b/ui/src/main.tsx index ba632b2..777baf7 100644 --- a/ui/src/main.tsx +++ b/ui/src/main.tsx @@ -1,3 +1,6 @@ +import {NotificationSettings,PopupPermission,useReadInbox,defaultNotificationConfig,type NotificationConfig} from './notification-settings'; +import {NotificationCenter,type NotificationEntry} from './notifications'; +import {IconBell} from '@tabler/icons-react'; import {t} from './i18n'; import {uploadFile} from './upload'; import {LanguageSettings} from './language'; @@ -15,7 +18,7 @@ import React,{useEffect,useRef,useState} from 'react';import{createRoot}from'rea type Manifest=Presentation&{id:string;name:string;version:string;author:string;description:string;backend?:{runAs:string;autostart:boolean;memoryLimitMiB?:number};lifecycle?:{runAs?:string};dependencies?:Record;optionalDependencies?:Record;conflicts?:Record;exclusiveResources?:string[];ui:{quickPage?:string;windows:Record}}; type Plugin={manifest:Manifest;enabled:boolean;favorite:boolean;order:number;source?:string;error?:string}; type Source={id:string;name:string;url:string;enabled:boolean;allowHttp:boolean}; -type Status={agreement?:AgreementState;version:string;build?:string;systemUpdate?:any;previousRelease?:string;database:{language?:string;proxy?:ProxyConfig;networkPanel?:NetworkPanel;plugins:Record;sources:Source[];subscriptions?:Subscription[];sourceOrigins?:Record}>;safeMode:boolean;updateSource?:{url:string}|null;updateChannel?:'stable'|'testing'};notifications:any[];runtime?:Record;running:string[]}; +type Status={agreement?:AgreementState;version:string;build?:string;systemUpdate?:any;previousRelease?:string;database:{notificationSettings?:NotificationConfig;language?:string;proxy?:ProxyConfig;networkPanel?:NetworkPanel;plugins:Record;sources:Source[];subscriptions?:Subscription[];sourceOrigins?:Record}>;safeMode:boolean;updateSource?:{url:string}|null;updateChannel?:'stable'|'testing'};notifications:NotificationEntry[];inbox?:NotificationEntry[];notificationBadge?:number;runtime?:Record;running:string[]}; const managerMode=location.pathname==='/manager'; const empty:Status={version:'0.4.0',database:{plugins:{},sources:[],safeMode:false},notifications:[],running:[]}; @@ -26,7 +29,7 @@ function PluginFrame({plugin,entry='quick'}:{plugin:string;entry?:string}){ const [attempt,setAttempt]=useState(0); useEffect(()=>{ let live=true;setError('');setSource(null); - const methods:Record={call:'plugin.call',dependencies:'plugin.dependencies','window.open':'window.open','window.close':'window.close','notification.send':'notification.send','notification.remove':'notification.remove'}; + const methods:Record={call:'plugin.call',dependencies:'plugin.dependencies','window.open':'window.open','window.close':'window.close','notification.send':'notification.send','notification.remove':'notification.remove','notification.dismiss':'notification.dismiss'}; async function message(e:MessageEvent){ if(e.source!==ref.current?.contentWindow||e.data?.channel!=='framely.plugin')return; const {id,op,params}=e.data;if(!Number.isSafeInteger(id)||typeof op!=='string')return; @@ -66,9 +69,10 @@ function PluginFrame({plugin,entry='quick'}:{plugin:string;entry?:string}){ return error?

{error}

:source?