Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,14 @@ strip = "symbols"
# panic,而 abort 会让那层防护失效。
panic = "unwind"

# 系统通知走 UNUserNotificationCenter:能原地更新、撤回、点开落到对应页面(见
# `notices/macos.rs`)。版本跟着 Tauri 自己用的那一套
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = "0.6"
block2 = "0.6"
objc2-foundation = "0.3"
objc2-user-notifications = "0.3"

[dev-dependencies]
# 去抖和限流要按时间测。**暂停时钟**,不是真的等一分钟
tokio = { version = "1", features = ["test-util", "macros", "rt-multi-thread"] }
20 changes: 19 additions & 1 deletion src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1258,6 +1258,7 @@ pub fn run() {
dismiss_notice,
notice_prefs,
set_notice_pref,
take_pending_view,
chatgpt::start_chatgpt_login,
chatgpt::reopen_chatgpt_login,
chatgpt::chatgpt_login_status,
Expand Down Expand Up @@ -1323,10 +1324,21 @@ pub fn run() {
announce_update(&handle);

// 通知总线。**判定在这里,不在界面** —— 关窗即销毁 webview
// 系统通知:装好的应用用原生的(能原地更新、撤回、点开落到对应页面),
// `tauri dev` 这种不在应用包里的退回插件
#[cfg(target_os = "macos")]
let system: Box<dyn notices::Sink> = if notices::macos::available() {
notices::macos::install(handle.clone());
Box::new(notices::macos::NativeSink)
} else {
Box::new(notices::SystemSink::new(handle.clone()))
};
#[cfg(not(target_os = "macos"))]
let system: Box<dyn notices::Sink> = Box::new(notices::SystemSink::new(handle.clone()));
let notices = notices::Notices::new(
vec![
Box::new(notices::sink::AppSink::new(handle.clone())),
Box::new(notices::SystemSink::new(handle.clone())),
system,
],
Some(data_dir()),
);
Expand Down Expand Up @@ -1634,6 +1646,12 @@ fn dismiss_notice(notices: tauri::State<'_, Arc<notices::Notices>>, key: String)
notices.dismiss(&key);
}

/// 点通知新建的窗口挂上之后,来取要落的那一页
#[tauri::command]
fn take_pending_view() -> Option<String> {
notices::take_pending_view()
}

/// 设置页上的一行:一类提醒,和它现在怎么对待
#[derive(serde::Serialize)]
struct NoticePref {
Expand Down
74 changes: 74 additions & 0 deletions src-tauri/src/notices/macos/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
//! macOS 的系统通知:`UNUserNotificationCenter`。
//!
//! 换掉 `tauri-plugin-notification` 的理由只有一条:那个插件在桌面端**发出即不管** ——
//! 不能按 id 原地更新、不能撤回、点了没有回调,而总线的「同一件事只说一次、恢复时
//! 撤回、点开落到能处理它的那一页」三件事都要靠这些。
//!
//! # 2026-09-18 实测过的前提
//!
//! - **没有团队 ID 的签名也能拿到授权**(临时签名即可;发布用的自签名证书只会更好)。
//! 但应用得装在正式位置、在系统里登记过 —— 放在临时目录里的包,申请授权会被直接拒绝,
//! 连弹窗都没有
//! - 菜单栏模式(没有窗口)照样能弹;同一个 identifier 再发是**原地替换**;
//! `removeDelivered` 能撤回;点通知能收到回调
//!
//! 真正调通知中心的那几行在 [`un`],这里只是把它接到总线上。

pub mod un;

use super::{Notice, Sink};

pub use un::available;

/// 接上通知中心:点了通知就把窗口带回来,落到那一条对应的页面
pub fn install(app: tauri::AppHandle) {
un::install(Box::new(move |key| {
super::open_from_notification(&app, &key)
}));
}

/// macOS 原生的系统通知
pub struct NativeSink;

impl Sink for NativeSink {
fn show(&self, notice: &Notice) {
un::post(
notice.key.clone(),
notice.title.clone(),
notice.body.clone(),
thread_of(notice),
false,
);
}

/// **只更新弹过的那些**:没弹过的(被压下、只进应用内的)不该借更新的名义冒出来
fn update(&self, notice: &Notice) {
if !notice.notified {
return;
}
let title = if notice.count > 1 {
format!("{}({} 次)", notice.title, notice.count)
} else {
notice.title.clone()
};
un::post(
notice.key.clone(),
title,
notice.body.clone(),
thread_of(notice),
true,
);
}

fn withdraw(&self, key: &str) {
un::withdraw(key);
}
}

/// 同一类的归在一起:用类别的标识做 thread
fn thread_of(notice: &Notice) -> String {
serde_json::to_value(notice.category)
.ok()
.and_then(|v| v.as_str().map(str::to_string))
.unwrap_or_default()
}
134 changes: 134 additions & 0 deletions src-tauri/src/notices/macos/un.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
//! `UNUserNotificationCenter` 的那几个调用。
//!
//! **不依赖 Tauri,也不依赖总线** —— 这样它能被一个单独的小程序原样引用,换一个
//! bundle id 在真机上验证,而不必动正在用的那个应用(同一个 bundle id、同一个数据
//! 目录,两个一起跑会互相干扰)。

use std::sync::OnceLock;

use block2::RcBlock;
use objc2::rc::Retained;
use objc2::runtime::{Bool, ProtocolObject};
use objc2::{AnyThread, define_class, msg_send};
use objc2_foundation::{NSArray, NSBundle, NSError, NSObject, NSObjectProtocol, NSString};
use objc2_user_notifications::{
UNAuthorizationOptions, UNMutableNotificationContent, UNNotification,
UNNotificationInterruptionLevel, UNNotificationPresentationOptions, UNNotificationRequest,
UNNotificationResponse, UNUserNotificationCenter, UNUserNotificationCenterDelegate,
};

/// 点了哪一条(它的 identifier)。**delegate 的回调里拿不到别的东西**,只能放这里
type OnClick = Box<dyn Fn(String) + Send + Sync>;
static ON_CLICK: OnceLock<OnClick> = OnceLock::new();

/// 能不能用:只有装好的 `.app` 能用。`tauri dev` 那种不在应用包里的二进制,
/// 去拿通知中心会直接抛异常,进程退出
pub fn available() -> bool {
let bundle = NSBundle::mainBundle();
bundle.bundleIdentifier().is_some() && bundle.bundlePath().to_string().ends_with(".app")
}

/// 接上通知中心。**要在启动时就调** —— 点通知把应用拉起来的那一次,delegate 得已经在了
pub fn install(on_click: OnClick) {
let _ = ON_CLICK.set(on_click);
let delegate = Delegate::new();
let center = UNUserNotificationCenter::currentNotificationCenter();
center.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
// 通知中心只弱引用 delegate:**让它活到进程结束**
std::mem::forget(delegate);
}

define_class!(
// SAFETY: NSObject 对子类没有额外要求;这个类没有实现 Drop
#[unsafe(super(NSObject))]
#[name = "ThinkWatchNoticeDelegate"]
struct Delegate;

unsafe impl NSObjectProtocol for Delegate {}

unsafe impl UNUserNotificationCenterDelegate for Delegate {
/// 应用在前台时收到通知:**只进通知中心,不弹横幅** —— 用户正看着界面,
/// 工具栏的提醒列表已经说了。设了 delegate 就必须实现这一条,否则前台一律不显示
#[unsafe(method(userNotificationCenter:willPresentNotification:withCompletionHandler:))]
fn will_present(
&self,
_center: &UNUserNotificationCenter,
_notification: &UNNotification,
done: &block2::DynBlock<dyn Fn(UNNotificationPresentationOptions)>,
) {
done.call((UNNotificationPresentationOptions::List,));
}

/// 点了通知
#[unsafe(method(userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:))]
fn did_receive(
&self,
_center: &UNUserNotificationCenter,
response: &UNNotificationResponse,
done: &block2::DynBlock<dyn Fn()>,
) {
let key = response.notification().request().identifier().to_string();
if let Some(f) = ON_CLICK.get() {
f(key);
}
done.call(());
}
}
);

impl Delegate {
fn new() -> Retained<Self> {
let this = Self::alloc().set_ivars(());
// SAFETY: NSObject 的 init
unsafe { msg_send![super(this), init] }
}
}

/// 发一条,或者替换同一个 `key` 的那一条。**先问授权**:第一次会弹系统询问,之后
/// 立刻用存下的答案 —— 放在第一条要打断用户的提醒之前问,那时用户知道这是为了什么。
///
/// `quiet`:只是更新计数的那一次**不亮屏、不出声**,替换掉通知中心里那一条就好
pub fn post(key: String, title: String, body: String, thread: String, quiet: bool) {
let center = UNUserNotificationCenter::currentNotificationCenter();
let then = RcBlock::new(move |granted: Bool, _err: *mut NSError| {
if !granted.as_bool() {
// 用户没允许:提醒照样在应用里,不再追问
return;
}
let content = UNMutableNotificationContent::new();
content.setTitle(&NSString::from_str(&title));
content.setBody(&NSString::from_str(&body));
// 同一类的归在一起
content.setThreadIdentifier(&NSString::from_str(&thread));
content.setInterruptionLevel(if quiet {
UNNotificationInterruptionLevel::Passive
} else {
UNNotificationInterruptionLevel::Active
});
let request = UNNotificationRequest::requestWithIdentifier_content_trigger(
&NSString::from_str(&key),
&content,
None,
);
let center = UNUserNotificationCenter::currentNotificationCenter();
let logged = RcBlock::new(|err: *mut NSError| {
// SAFETY: 通知中心给的要么是空指针,要么是一个有效的 NSError
if let Some(e) = unsafe { err.as_ref() } {
tracing::debug!("系统通知未能发出:{}", e.localizedDescription());
}
});
center.addNotificationRequest_withCompletionHandler(&request, Some(&logged));
});
center.requestAuthorizationWithOptions_completionHandler(
UNAuthorizationOptions::Alert | UNAuthorizationOptions::Sound,
&then,
);
}

/// 撤回:通知中心里的那一条,和还没发出去的那一条
pub fn withdraw(key: &str) {
let center = UNUserNotificationCenter::currentNotificationCenter();
let ids = NSArray::from_retained_slice(&[NSString::from_str(key)]);
center.removeDeliveredNotificationsWithIdentifiers(&ids);
center.removePendingNotificationRequestsWithIdentifiers(&ids);
}
37 changes: 37 additions & 0 deletions src-tauri/src/notices/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

#[cfg(target_os = "macos")]
pub mod macos;
pub mod prefs;
pub mod rules;
pub mod sink;
Expand Down Expand Up @@ -274,6 +276,15 @@ impl Notices {
Ok(())
}

/// 这一条点开之后落在哪一页。**已经不在列表里的**(恢复了、被划掉了)按类别给
pub fn view_of(&self, key: &str) -> String {
self.state
.lock()
.ok()
.and_then(|g| g.open.get(key).and_then(|o| o.notice.view.clone()))
.unwrap_or_else(|| rules::default_view(Category::of(key)).to_string())
}

/// 界面要显示的那一份,最近的在前
pub fn list(&self) -> Vec<Notice> {
let g = self.state.lock().expect("锁未中毒");
Expand Down Expand Up @@ -548,6 +559,32 @@ fn take_token(state: &mut State, level: Level) -> bool {
true
}

/// 点通知之后要落到的那一页。**窗口这时可能根本不存在** —— 新建的界面挂上之后自己来取
static PENDING_VIEW: Mutex<Option<String>> = Mutex::new(None);

/// 点了系统通知:把窗口带回来,落到能处理这件事的那一页
pub fn open_from_notification(app: &tauri::AppHandle, key: &str) {
use tauri::{Emitter, Manager};
let view = app
.try_state::<Arc<Notices>>()
.map(|n| n.view_of(key))
.unwrap_or_else(|| rules::default_view(Category::of(key)).to_string());
if let Ok(mut g) = PENDING_VIEW.lock() {
*g = Some(view.clone());
}
// 通知的回调不在主线程上,建窗口要回到主线程
let a = app.clone();
let _ = app.run_on_main_thread(move || {
let _ = crate::show_main_window(&a);
let _ = a.emit("open-view", &view);
});
}

/// 取走待落的那一页。取一次就没了:下次开窗不该又跳过去
pub fn take_pending_view() -> Option<String> {
PENDING_VIEW.lock().ok().and_then(|mut g| g.take())
}

fn now_ms() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
Expand Down
10 changes: 10 additions & 0 deletions src-tauri/src/notices/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ const UPSTREAMS: &str = "upstreams";
const SECURITY: &str = "security";
const CONFIG: &str = "config";

/// 一类提醒默认落在哪一页(那一条已经不在列表里时用)
pub fn default_view(c: super::Category) -> &'static str {
use super::Category;
match c {
Category::Gateway | Category::Config | Category::Storage => CONFIG,
Category::Security => SECURITY,
Category::Upstream | Category::Quota | Category::Credential | Category::Proxy => UPSTREAMS,
}
}

/// 这个键开着的时候,压下哪些键(前缀匹配)。
///
/// **网关不在服务时不必再说它下面每一家怎么了** —— 那时用户要做的只有一件事。
Expand Down
10 changes: 5 additions & 5 deletions src-tauri/src/notices/sink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ impl Sink for AppSink {
}
}

/// 系统通知。
/// 系统通知的退路:`tauri-plugin-notification`。
///
/// **目前用的是 `tauri-plugin-notification`,它在桌面端只能「发出即不管」** ——
/// 不能按 id 原地更新、不能撤回、点了没有回调(2026-09-18 查过插件源码和上游
/// issue)。所以这里的 `update` 和 `withdraw` 是空的:原地更新和恢复时撤回要等
/// macOS 的原生实现(`UNUserNotificationCenter`),那时换掉这一个类型即可。
/// **装好的 macOS 应用不走这里**,走 `macos::NativeSink`。这个插件在桌面端只能「发出即
/// 不管」—— 不能按 id 原地更新、不能撤回、点了没有回调,所以 `update` 和 `withdraw`
/// 是空的。留着它是给 `tauri dev`(不在应用包里,原生通知中心拿不到)和还没有原生
/// 实现的平台用。
pub struct SystemSink {
app: tauri::AppHandle,
}
Expand Down
Loading
Loading