brightness_service.go 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. // BrightnessConfig 显示器亮度配置:记住各显示器亮度(按显示器名称),供启动时恢复
  7. type BrightnessConfig struct {
  8. RestoreOnStart bool `json:"restoreOnStart"` // 启动应用时恢复上次亮度
  9. Levels map[string]int `json:"levels"` // 显示器名称 -> 亮度百分比(0-100)
  10. }
  11. // MonitorBrightnessInfo 单个显示器的亮度状态(返回给前端渲染滑块)
  12. type MonitorBrightnessInfo struct {
  13. Index int `json:"index"` // 显示器序号(与 SetBrightness 的 index 一致)
  14. Name string `json:"name"` // 显示器名称(物理监视器描述,取不到时用设备名)
  15. Percent int `json:"percent"` // 当前亮度百分比 0-100
  16. Hardware bool `json:"hardware"` // true=DDC/CI 硬件调光;false=Gamma 软件调光
  17. }
  18. // BrightnessService 显示器亮度控制:Windows 下优先 DDC/CI 硬件调光,
  19. // 显示器不支持时回退 Gamma 软件调光;其他平台不提供(Available 返回 false)。
  20. type BrightnessService struct{}
  21. // NewBrightnessService 创建亮度服务实例
  22. func NewBrightnessService() *BrightnessService { return &BrightnessService{} }
  23. // Available 当前平台是否支持亮度调节
  24. func (s *BrightnessService) Available() bool { return brightnessAvailable() }
  25. // GetMonitors 列出所有显示器及当前亮度;软件调光的显示器取设置里保存的亮度(默认 100)
  26. func (s *BrightnessService) GetMonitors() []MonitorBrightnessInfo {
  27. list := listMonitorBrightness()
  28. levels := loadSettings().Brightness.Levels
  29. for i := range list {
  30. if !list[i].Hardware {
  31. if v, ok := levels[strings.TrimSpace(list[i].Name)]; ok {
  32. list[i].Percent = v
  33. }
  34. }
  35. if list[i].Percent < 0 {
  36. list[i].Percent = 0
  37. } else if list[i].Percent > 100 {
  38. list[i].Percent = 100
  39. }
  40. }
  41. return list
  42. }
  43. // SetBrightness 设置指定显示器亮度(0-100),硬件不可用时自动回退 Gamma
  44. func (s *BrightnessService) SetBrightness(index, percent int) error {
  45. if percent < 0 {
  46. percent = 0
  47. } else if percent > 100 {
  48. percent = 100
  49. }
  50. return setMonitorBrightness(index, percent)
  51. }
  52. // TurnOff 立即关闭所有显示器(息屏),移动鼠标或按键即恢复
  53. func (s *BrightnessService) TurnOff() error {
  54. return turnOffDisplay()
  55. }
  56. // SaveLevel 记住某个显示器当前亮度(按名称保存,供启动时恢复)
  57. func (s *BrightnessService) SaveLevel(name string, percent int) error {
  58. name = strings.TrimSpace(name)
  59. if name == "" {
  60. return fmt.Errorf("显示器名称不能为空")
  61. }
  62. if percent < 0 {
  63. percent = 0
  64. } else if percent > 100 {
  65. percent = 100
  66. }
  67. settings := loadSettings()
  68. if settings.Brightness.Levels == nil {
  69. settings.Brightness.Levels = map[string]int{}
  70. }
  71. settings.Brightness.Levels[name] = percent
  72. return saveSettings(settings)
  73. }