Compare commits

..

7 Commits

Author SHA1 Message Date
57d605674e feat: 升级版本至1.0.1并添加外部显示器支持
- 更新版本号至1.0.1
- 添加外部显示器检测功能
- 更新README文档说明新特性
- 移除临时Applications链接
2025-12-27 22:46:41 +08:00
b133d8a4e9 feat(通知): 添加显示器连接状态检测和通知功能
当检测到外部显示器连接时自动启用保持亮屏功能
当外部显示器断开时发送通知询问是否关闭功能
添加通知代理处理用户响应
2025-12-27 22:42:43 +08:00
aef0f74616 refactor: 简化空闲状态检测逻辑,直接显示保护状态
移除空闲状态检测及相关UI显示,直接显示"保护中"状态
2025-12-27 22:01:35 +08:00
886b460d5e fix: 添加更多caffeinate参数以防止系统睡眠
添加-i和-s参数以全面防止系统睡眠,包括用户不活动和系统睡眠的情况
2025-12-27 21:52:39 +08:00
27e98a527f feat(assets): 添加应用图标资源文件
添加不同尺寸的Mac应用图标文件并更新Contents.json配置
2025-12-27 21:32:33 +08:00
230a2836a6 chore: 删除临时目录中的Applications符号链接 2025-12-27 20:21:17 +08:00
3514f450c9 refactor: 移除菜单内容中多余的过渡动画效果 2025-12-27 20:17:03 +08:00
16 changed files with 176 additions and 81 deletions

View File

@@ -266,7 +266,7 @@
"$(inherited)", "$(inherited)",
"@executable_path/../Frameworks", "@executable_path/../Frameworks",
); );
MARKETING_VERSION = 1.0; MARKETING_VERSION = 1.0.1;
PRODUCT_BUNDLE_IDENTIFIER = me.leo12025.PowerBar; PRODUCT_BUNDLE_IDENTIFIER = me.leo12025.PowerBar;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES; REGISTER_APP_GROUPS = YES;
@@ -300,7 +300,7 @@
"$(inherited)", "$(inherited)",
"@executable_path/../Frameworks", "@executable_path/../Frameworks",
); );
MARKETING_VERSION = 1.0; MARKETING_VERSION = 1.0.1;
PRODUCT_BUNDLE_IDENTIFIER = me.leo12025.PowerBar; PRODUCT_BUNDLE_IDENTIFIER = me.leo12025.PowerBar;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES; REGISTER_APP_GROUPS = YES;

View File

@@ -3,6 +3,7 @@ import Combine
import IOKit.pwr_mgt import IOKit.pwr_mgt
import ServiceManagement import ServiceManagement
import AppKit import AppKit
import UserNotifications
// MARK: - App State Manager // MARK: - App State Manager
class AppState: ObservableObject { class AppState: ObservableObject {
@@ -11,24 +12,25 @@ class AppState: ObservableObject {
// //
@Published var isFunctionEnabled: Bool = false @Published var isFunctionEnabled: Bool = false
//
@Published var isUserIdle: Bool = false
// //
@Published var isLaunchAtLogin: Bool = false @Published var isLaunchAtLogin: Bool = false
// //
private var monitorTimer: Timer?
private var caffeinateProcess: Process? // 使Process private var caffeinateProcess: Process? // 使Process
private var displayCountObserver: AnyCancellable? //
// private var wasAutomaticallyEnabled: Bool = false //
private let idleThreshold: TimeInterval = 300 // 5 private var currentDisplayCount: Int = NSScreen.screens.count //
private let checkInterval: TimeInterval = 10 // 10
// //
init() { init() {
// //
checkLaunchAtLoginStatus() checkLaunchAtLoginStatus()
//
requestNotificationPermission()
//
setupDisplayCountObserver()
} }
// MARK: - Public Methods // MARK: - Public Methods
@@ -37,52 +39,11 @@ class AppState: ObservableObject {
func toggleFunction() { func toggleFunction() {
isFunctionEnabled.toggle() isFunctionEnabled.toggle()
if isFunctionEnabled { if isFunctionEnabled {
// // caffeinate
performCheck() startCaffeinate()
startMonitoringTimer()
} else { } else {
// // caffeinate
stopMonitoringTimer()
stopCaffeinate() stopCaffeinate()
updateUserIdleStatus(false) //
}
}
// MARK: - Monitoring Logic
private func startMonitoringTimer() {
guard monitorTimer == nil else { return }
print("开始监控...")
// 使 weak self
monitorTimer = Timer.scheduledTimer(withTimeInterval: checkInterval, repeats: true) { [weak self] _ in
self?.performCheck()
}
}
private func stopMonitoringTimer() {
monitorTimer?.invalidate()
monitorTimer = nil
print("监控已停止。")
}
private func performCheck() {
// 1.
let idleTime = getSystemIdleTime()
// 2.
let isIdleNow = (idleTime >= idleThreshold)
// 3.
if isIdleNow != isUserIdle {
updateUserIdleStatus(isIdleNow)
if isIdleNow {
//
stopCaffeinate()
} else {
//
startCaffeinate()
}
} }
} }
@@ -125,7 +86,7 @@ class AppState: ObservableObject {
// caffeinate // caffeinate
caffeinateProcess = Process() caffeinateProcess = Process()
caffeinateProcess?.executableURL = URL(fileURLWithPath: "/usr/bin/caffeinate") caffeinateProcess?.executableURL = URL(fileURLWithPath: "/usr/bin/caffeinate")
caffeinateProcess?.arguments = ["-d"] // -d caffeinateProcess?.arguments = ["-i", "-s", "-d"] // -i -s -d
// //
let outputPipe = Pipe() let outputPipe = Pipe()
@@ -155,14 +116,7 @@ class AppState: ObservableObject {
print("已重置 caffeinate 进程引用") print("已重置 caffeinate 进程引用")
} }
// MARK: - UI State Update
/// 线
private func updateUserIdleStatus(_ isIdle: Bool) {
DispatchQueue.main.async {
self.isUserIdle = isIdle
}
}
// MARK: - Launch at Login Management // MARK: - Launch at Login Management
@@ -248,11 +202,122 @@ class AppState: ObservableObject {
} }
} }
// MARK: - Display Monitoring and Auto-enable
///
private func requestNotificationPermission() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if granted {
print("通知权限已授予")
} else if let error = error {
print("请求通知权限失败: \(error)")
}
}
}
///
private func setupDisplayCountObserver() {
// 使 Combine NSScreen.screens.count
// 使
displayCountObserver = Timer.publish(every: 5, on: .main, in: .common)
.autoconnect()
.sink { [weak self] _ in
self?.checkDisplayCount()
}
}
///
private func checkDisplayCount() {
let newDisplayCount = NSScreen.screens.count
//
if newDisplayCount != currentDisplayCount {
if newDisplayCount > 1 {
//
handleExternalDisplayConnected()
} else {
//
handleExternalDisplayDisconnected()
}
currentDisplayCount = newDisplayCount
}
}
///
private func handleExternalDisplayConnected() {
if !isFunctionEnabled {
//
wasAutomaticallyEnabled = true
toggleFunction()
//
sendNotification(title: "PowerBar", body: "检测到外部显示器,已自动打开保持亮屏功能")
}
}
///
private func handleExternalDisplayDisconnected() {
if wasAutomaticallyEnabled && isFunctionEnabled {
//
sendNotificationWithAction(title: "PowerBar", body: "外部显示器已断开,是否关闭保持亮屏功能?")
}
}
///
private func sendNotification(title: String, body: String) {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = UNNotificationSound.default
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("发送通知失败: \(error)")
}
}
}
///
private func sendNotificationWithAction(title: String, body: String) {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = UNNotificationSound.default
content.categoryIdentifier = "displayDisconnected"
//
let cancelAction = UNNotificationAction(identifier: "cancel", title: "取消", options: [])
let disableAction = UNNotificationAction(identifier: "disable", title: "关闭", options: [])
let category = UNNotificationCategory(identifier: "displayDisconnected", actions: [disableAction, cancelAction], intentIdentifiers: [])
UNUserNotificationCenter.current().setNotificationCategories([category])
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("发送通知失败: \(error)")
}
}
}
///
func handleNotificationResponse(identifier: String) {
if identifier == "disable" {
//
wasAutomaticallyEnabled = false
toggleFunction()
} else if identifier == "cancel" {
//
wasAutomaticallyEnabled = false
}
}
// MARK: - Deinitializer // MARK: - Deinitializer
deinit { deinit {
// App 退 // App 退
stopMonitoringTimer()
stopCaffeinate() stopCaffeinate()
displayCountObserver?.cancel()
} }
} }

View File

@@ -1,51 +1,61 @@
{ {
"images" : [ "images" : [
{ {
"filename" : "icon_16x16.png",
"idiom" : "mac", "idiom" : "mac",
"scale" : "1x", "scale" : "1x",
"size" : "16x16" "size" : "16x16"
}, },
{ {
"filename" : "icon_16x16@2x.png",
"idiom" : "mac", "idiom" : "mac",
"scale" : "2x", "scale" : "2x",
"size" : "16x16" "size" : "16x16"
}, },
{ {
"filename" : "icon_32x32.png",
"idiom" : "mac", "idiom" : "mac",
"scale" : "1x", "scale" : "1x",
"size" : "32x32" "size" : "32x32"
}, },
{ {
"filename" : "icon_32x32@2x.png",
"idiom" : "mac", "idiom" : "mac",
"scale" : "2x", "scale" : "2x",
"size" : "32x32" "size" : "32x32"
}, },
{ {
"filename" : "icon_128x128.png",
"idiom" : "mac", "idiom" : "mac",
"scale" : "1x", "scale" : "1x",
"size" : "128x128" "size" : "128x128"
}, },
{ {
"filename" : "icon_128x128@2x.png",
"idiom" : "mac", "idiom" : "mac",
"scale" : "2x", "scale" : "2x",
"size" : "128x128" "size" : "128x128"
}, },
{ {
"filename" : "icon_256x256.png",
"idiom" : "mac", "idiom" : "mac",
"scale" : "1x", "scale" : "1x",
"size" : "256x256" "size" : "256x256"
}, },
{ {
"filename" : "icon_256x256@2x.png",
"idiom" : "mac", "idiom" : "mac",
"scale" : "2x", "scale" : "2x",
"size" : "256x256" "size" : "256x256"
}, },
{ {
"filename" : "icon_512x512.png",
"idiom" : "mac", "idiom" : "mac",
"scale" : "1x", "scale" : "1x",
"size" : "512x512" "size" : "512x512"
}, },
{ {
"filename" : "icon_512x512@2x.png",
"idiom" : "mac", "idiom" : "mac",
"scale" : "2x", "scale" : "2x",
"size" : "512x512" "size" : "512x512"

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 465 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 159 KiB

View File

@@ -1,5 +1,6 @@
import SwiftUI import SwiftUI
import AppKit import AppKit
import UserNotifications
@main @main
struct PowerBarApp: App { struct PowerBarApp: App {
@@ -26,6 +27,30 @@ struct PowerBarApp: App {
.foregroundColor(appState.isFunctionEnabled ? .green : .gray) .foregroundColor(appState.isFunctionEnabled ? .green : .gray)
} }
} }
.onChange(of: ScenePhase.active) {
//
UNUserNotificationCenter.current().delegate = NotificationDelegate.shared
NotificationDelegate.shared.appState = appState
}
}
}
//
class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
static let shared = NotificationDelegate()
weak var appState: AppState?
private override init() { super.init() }
//
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
return [.banner, .sound]
}
//
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
let actionIdentifier = response.actionIdentifier
appState?.handleNotificationResponse(identifier: actionIdentifier)
} }
} }
@@ -83,8 +108,6 @@ struct MenuContent: View {
.buttonStyle(.plain) .buttonStyle(.plain)
Divider() Divider()
.transition(.opacity)
.animation(.easeInOut(duration: 0.3), value: appState.isFunctionEnabled)
// //
VStack(alignment: .leading, spacing: 4) { VStack(alignment: .leading, spacing: 4) {
@@ -95,18 +118,10 @@ struct MenuContent: View {
if appState.isFunctionEnabled { if appState.isFunctionEnabled {
HStack(spacing: 6) { HStack(spacing: 6) {
Circle() Circle()
.fill(appState.isUserIdle ? Color.orange : Color.green) .fill(Color.green)
.frame(width: 8, height: 8) .frame(width: 8, height: 8)
.transition(.scale(scale: 0.5, anchor: .center)) Text("保护中")
Text(appState.isUserIdle ? "空闲" : "活动中")
.font(.body) .font(.body)
// caffeinate
if !appState.isUserIdle {
Text("(保护中)")
.font(.caption2)
.foregroundColor(.secondary)
}
} }
} else { } else {
HStack(spacing: 6) { HStack(spacing: 6) {
@@ -119,8 +134,7 @@ struct MenuContent: View {
} }
Spacer() Spacer()
} }
.transition(.opacity)
.animation(.easeInOut(duration: 0.3), value: appState.isFunctionEnabled || appState.isUserIdle)
} }
.padding(8) .padding(8)
.background( .background(

View File

@@ -1,11 +1,17 @@
# PowerBar # PowerBar
一个智能的macOS菜单栏应用根据用户活动状态自动管理系统睡眠。 一个智能的macOS菜单栏应用根据用户活动状态和外部显示器连接状态自动管理系统睡眠。
## 版本
1.0.1
## 功能特性 ## 功能特性
- 📊 **智能睡眠管理**:根据用户活动状态自动控制系统睡眠 - 📊 **智能睡眠管理**:根据用户活动状态自动控制系统睡眠
- 🔍 **空闲检测**5分钟无操作自动视为空闲停止阻止睡眠 - 🖥️ **外部显示器检测**自动检测外部显示器连接状态
- 🚀 **自动控制**:外部显示器连接时自动开启保持亮屏
- 📢 **通知提醒**:外部显示器连接/断开时发送通知
- 🎯 **清晰的状态指示**:通过菜单栏图标直观显示当前状态 - 🎯 **清晰的状态指示**:通过菜单栏图标直观显示当前状态
- 🎨 **现代化UI**:简洁美观的菜单界面,易于操作 - 🎨 **现代化UI**:简洁美观的菜单界面,易于操作
-**低资源消耗**:轻量级设计,几乎不占用系统资源 -**低资源消耗**:轻量级设计,几乎不占用系统资源

View File

@@ -7,7 +7,7 @@
PROJECT_NAME="PowerBar" PROJECT_NAME="PowerBar"
SCHEME="PowerBar" SCHEME="PowerBar"
CONFIGURATION="Release" CONFIGURATION="Release"
VERSION="1.0.0" VERSION="1.0.1"
echo "=== PowerBar 打包脚本 v$VERSION ===" echo "=== PowerBar 打包脚本 v$VERSION ==="