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
24 changes: 17 additions & 7 deletions display1/displayconf.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,15 @@ type SysCache struct {

// UserConfig v1
type UserConfig struct {
Version string
Screens map[string]UserScreenConfig
Version string
Screens map[string]UserScreenConfig
LidScale *LidScaleConfig `json:",omitempty"`
}

// 缩放仍由 XSettings 生效,这里只保存开合盖切换时各显示器的配置。
type LidScaleConfig struct {
Factors map[string]map[string]float64 // 显示器 UUID -> 原有缩放映射
ExternalUUID string `json:",omitempty"` // 尚未切回内屏的外屏
Comment on lines +60 to +61

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Saved display scale is not restored

When a monitor UUID changes during UUID migration, updateUserConfigUuid migrates Screens but not the UUIDs in LidScale.Factors or ExternalUUID, so applyLidScale misses the saved factors for the new UUID and fails to restore the monitor’s previous scale.

Migrate the UUIDs in LidScale.Factors and ExternalUUID along with the screen configuration UUIDs.

Prompt for AI agents
In `display1/displayconf.go` at lines 60-61:

**Saved display scale is not restored**

When a monitor UUID changes during UUID migration, `updateUserConfigUuid` migrates `Screens` but not the UUIDs in `LidScale.Factors` or `ExternalUUID`, so `applyLidScale` misses the saved factors for the new UUID and fails to restore the monitor’s previous scale.

Migrate the UUIDs in `LidScale.Factors` and `ExternalUUID` along with the screen configuration UUIDs.

}

func (cfg *UserConfig) fix() {
Expand Down Expand Up @@ -382,6 +389,8 @@ type SysScreenConfig struct {
Single *SysMonitorModeConfig `json:",omitempty"`
OnlyOneMap map[string]*SysMonitorModeConfig `json:",omitempty"`
OnlyOneUuid string `json:",omitempty"`
// Single 已保存合盖时用户确认的配置,后续合盖应恢复而非初始化。
LidClosedConfigured bool `json:",omitempty"`
}

func isCurrentVersionUuid(uuid string) bool {
Expand All @@ -393,7 +402,7 @@ func (c *SysScreenConfig) updateUuid(monitors Monitors) (result *SysScreenConfig
return nil, false
}

result = &SysScreenConfig{}
result = &SysScreenConfig{LidClosedConfigured: c.LidClosedConfigured}

if c.Mirror != nil {
changed := false
Expand Down Expand Up @@ -478,10 +487,11 @@ func (c *SysScreenConfig) clone() *SysScreenConfig {
return nil
}
result := &SysScreenConfig{
Mirror: c.Mirror.clone(),
Extend: c.Extend.clone(),
Single: c.Single.clone(),
OnlyOneUuid: c.OnlyOneUuid,
Mirror: c.Mirror.clone(),
Extend: c.Extend.clone(),
Single: c.Single.clone(),
OnlyOneUuid: c.OnlyOneUuid,
LidClosedConfigured: c.LidClosedConfigured,
}
if len(c.OnlyOneMap) > 0 {
result.OnlyOneMap = make(map[string]*SysMonitorModeConfig, len(c.OnlyOneMap))
Expand Down
62 changes: 55 additions & 7 deletions display1/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,9 @@ type Manager struct {
builtinMonitorMu sync.Mutex
candidateBuiltinMonitors []*Monitor // 候补的

lidScaleMu sync.Mutex
lidScalePending bool

monitorMap map[uint32]*Monitor
monitorMapMu sync.Mutex
mm monitorManager
Expand Down Expand Up @@ -983,8 +986,10 @@ func monitorsRemove(monitors []*Monitor, id uint32) []*Monitor {
}

func (m *Manager) buildConfigForSingle(monitor *Monitor) SysMonitorConfigs {
if cfg := m.getLidClosedSingleConfig(monitor); cfg != nil {
return SysMonitorConfigs{cfg}
if !m.lidDisplayResetPending() {
if cfg := m.getLidClosedSingleConfig(monitor); cfg != nil {
return SysMonitorConfigs{cfg}
}
}
cfg := monitor.toBasicSysConfig()
cfg.Enabled = true
Expand Down Expand Up @@ -1071,13 +1076,30 @@ func (m *Manager) applyDisplayConfig(mode byte, monitorsId monitorsId, monitorMa
// 单屏情况
screenCfg := m.getSysScreenConfig(monitorsId)

needSaveCfg := false

monitorConfigs := screenCfg.getSingleMonitorConfigs()
if len(monitorConfigs) == 0 {
// 没有单屏配置
needSaveCfg = true
needSaveCfg := len(monitorConfigs) == 0
resetForLid := m.lidDisplayResetPending() && (needSaveCfg || !screenCfg.LidClosedConfigured)
if needSaveCfg && resetForLid {
// 显示方案已被清空时,不能继续恢复该外屏上一轮的缩放缓存。
m.userCfgMu.Lock()
if state := m.userConfig.LidScale; state != nil {
delete(state.Factors, monitors[0].uuid)
if state.ExternalUUID == monitors[0].uuid {
state.ExternalUUID = ""
}
}
m.userCfgMu.Unlock()
}
if needSaveCfg || resetForLid {
// 合盖只临时使用默认显示参数,不覆盖已有 Single 方案及亮度。
previous := monitorConfigs.getByUuid(monitors[0].uuid)
monitorConfigs = m.buildConfigForSingle(monitors[0])
if resetForLid {
monitorConfigs[0].Brightness = monitors[0].Brightness
if previous != nil {
monitorConfigs[0].Brightness = previous.Brightness
}
}
}

// 应用配置
Expand All @@ -1088,6 +1110,7 @@ func (m *Manager) applyDisplayConfig(mode byte, monitorsId monitorsId, monitorMa
}
if needSaveCfg {
screenCfg.setSingleMonitorConfigs(monitorConfigs)
screenCfg.LidClosedConfigured = false
m.setSysScreenConfig(monitorsId, screenCfg)
err = m.saveSysConfig("single")
if err != nil {
Expand Down Expand Up @@ -2372,6 +2395,14 @@ func (m *Manager) save() (err error) {
}
if len(monitors) == 1 {
screenCfg.setSingleMonitorConfigs(configs)
if builtin := m.getBuiltinMonitor(); builtin != nil && builtin.ID != monitors[0].ID {
builtin.PropsMu.RLock()
closed := builtin.lidClosed
builtin.PropsMu.RUnlock()
if closed {
screenCfg.LidClosedConfigured = true
}
}
} else {
uuid := getOnlyOneMonitorUuid(m.DisplayMode, monitors)
screenCfg.setMonitorConfigs(m.DisplayMode, uuid, configs)
Expand Down Expand Up @@ -2683,6 +2714,8 @@ func (m *Manager) applySysMonitorConfigs(mode byte, monitorsId monitorsId, monit
logger.Warning(err)
}

m.applyLidScale(monitorMap)

return nil
}

Expand Down Expand Up @@ -3854,6 +3887,21 @@ func (m *Manager) tryToChangeScaleFactor(monitorWidth, monitorHeight uint16) {
if monitorWidth == 0 || monitorHeight == 0 || !m.dsAutoChangeScaleEnabled {
return
}
// 合盖初始化期间由最终显示配置统一设置缩放,避免中间分辨率事件覆盖结果。
if m.lidDisplayResetPending() {
Comment on lines +3890 to +3891

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Late scale event overrides lid scale

When a monitor-change handler passes the pending check while a lid-close transition is concurrently applying the external scale, a monitor-change handler can pass the pending check, then the lid handler sets pending and applies the external target, after which the first handler calls SetScaleFactor using its stale dimensions. The external display ends with the automatic factor instead of its remembered or recommended target.

Serialize automatic scale changes with lid-scale transitions, or recheck the transition state immediately before writing the scale.

Prompt for AI agents
In `display1/manager.go` at lines 3890-3891:

**Late scale event overrides lid scale**

When a monitor-change handler passes the pending check while a lid-close transition is concurrently applying the external scale, a monitor-change handler can pass the pending check, then the lid handler sets pending and applies the external target, after which the first handler calls `SetScaleFactor` using its stale dimensions. The external display ends with the automatic factor instead of its remembered or recommended target.

Serialize automatic scale changes with lid-scale transitions, or recheck the transition state immediately before writing the scale.

return
}
if builtin := m.getBuiltinMonitor(); builtin != nil {
m.userCfgMu.Lock()
hasExternalScale := m.userConfig.LidScale != nil && m.userConfig.LidScale.ExternalUUID != ""
m.userCfgMu.Unlock()
builtin.PropsMu.RLock()
restoring := hasExternalScale && !builtin.lidClosed
builtin.PropsMu.RUnlock()
if restoring {
return
}
}

if m.xsManager == nil {
return
Expand Down
124 changes: 122 additions & 2 deletions display1/manager_lid.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package display1
import (
"fmt"

"github.com/linuxdeepin/dde-daemon/common/scale"
configManager "github.com/linuxdeepin/go-dbus-factory/org.desktopspec.ConfigManager"
syspower "github.com/linuxdeepin/go-dbus-factory/system/org.deepin.dde.power1"
)
Expand Down Expand Up @@ -78,12 +79,20 @@ func (m *Manager) updateLidState(closed bool) bool {
break
}
}
// 扩展模式和仅内屏模式合盖都需要初始化外屏;仅外屏模式保持原值。
initializeExternal := closed && hasExternal && m.shouldInitializeLidExternal(builtin)
m.lidScaleMu.Lock()
defer m.lidScaleMu.Unlock()
builtin.PropsMu.Lock()
defer builtin.PropsMu.Unlock()
previous := builtin.lidClosed
builtin.lidClosed = closed && hasExternal
changed := previous != builtin.lidClosed
logger.Infof("sync lid closed: %v", builtin.lidClosed)
return previous != builtin.lidClosed
builtin.PropsMu.Unlock()
if changed {
m.lidScalePending = initializeExternal
Comment on lines +92 to +93

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Replacement display inherits stale scale

When an external display is added or replaced while the lid stays closed and the lid-closed boolean does not change, updateLidState does not re-arm lidScalePending, so applyLidScale skips the new display; on lid open, the stale ExternalUUID can cause its scale to overwrite the previous display’s saved scale.

Re-arm lidScalePending when the external display configuration changes while the lid remains closed.

Also at display1/manager_lid.go:222.

Prompt for AI agents
In `display1/manager_lid.go` at lines 92-93:

**Replacement display inherits stale scale**

When an external display is added or replaced while the lid stays closed and the lid-closed boolean does not change, `updateLidState` does not re-arm `lidScalePending`, so `applyLidScale` skips the new display; on lid open, the stale `ExternalUUID` can cause its scale to overwrite the previous display’s saved scale.

Re-arm `lidScalePending` when the external display configuration changes while the lid remains closed.

Also at `display1/manager_lid.go:222`.

}
return changed
}

func (m *Manager) handleLidSwitch(sysPower syspower.Power, handleFunc func(bool)) {
Expand Down Expand Up @@ -147,3 +156,114 @@ func (m *Manager) setLidClosed(closed bool) error {
}
return nil
}

func (m *Manager) shouldInitializeLidExternal(builtin *Monitor) bool {
m.sysConfig.mu.Lock()
displayMode := m.sysConfig.Config.DisplayMode
m.sysConfig.mu.Unlock()
if displayMode == DisplayModeExtend {
return true
}
if displayMode != DisplayModeOnlyOne {
return false
}

var physicalMonitors Monitors
for _, monitor := range m.cloneMonitorMap() {
if monitor.realConnected {
physicalMonitors = append(physicalMonitors, monitor)
}
}
screenCfg := m.getSysScreenConfig(physicalMonitors.getMonitorsId())
return screenCfg.OnlyOneUuid == "" || screenCfg.OnlyOneUuid == builtin.uuid
}

func (m *Manager) lidDisplayResetPending() bool {
m.lidScaleMu.Lock()
defer m.lidScaleMu.Unlock()
return m.lidScalePending
}

// 显示配置成功应用后再调整缩放,避免失败或中间状态污染当前配置。
func (m *Manager) applyLidScale(monitorMap map[uint32]*Monitor) {
if m.xsManager == nil {
return
}
builtin := m.getBuiltinMonitor()
if builtin == nil {
return
}
builtin = monitorMap[builtin.ID]
if builtin == nil {
return
}
m.lidScaleMu.Lock()
defer m.lidScaleMu.Unlock()
m.userCfgMu.Lock()
defer m.userCfgMu.Unlock()
state := m.userConfig.LidScale
if !builtin.lidClosed && builtin.Enabled && state != nil && state.ExternalUUID != "" {
// 切回内屏前保存外屏最后使用的值,不能下次合盖又重置为默认值。
factors, err := m.xsManager.GetScreenScaleFactors(0)
if err != nil {
logger.Warning("failed to read external scale before lid open:", err)
return
}
state.Factors[state.ExternalUUID] = factors
if err := m.xsManager.SetScreenScaleFactors(0, state.Factors[builtin.uuid]); err != nil {
logger.Warning("failed to restore builtin scale after lid open:", err)
return
}
state.ExternalUUID = ""
if err := m.saveUserConfigNoLock(); err != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Saved external scale is overwritten

When saving the cleared ExternalUUID fails while restoring the builtin scale and the daemon restarts before a successful save, the disk retains the stale external marker, so after restart applyLidScale records the builtin scale under the external UUID and overwrites the remembered external scale.

Handle the save failure so a stale ExternalUUID cannot remain on disk after restoring the builtin scale.

Prompt for AI agents
In `display1/manager_lid.go` at line 218:

**Saved external scale is overwritten**

When saving the cleared `ExternalUUID` fails while restoring the builtin scale and the daemon restarts before a successful save, the disk retains the stale external marker, so after restart `applyLidScale` records the builtin scale under the external UUID and overwrites the remembered external scale.

Handle the save failure so a stale `ExternalUUID` cannot remain on disk after restoring the builtin scale.

logger.Warning("failed to save lid scale config:", err)
}
}
if !m.lidScalePending || !builtin.lidClosed || builtin.Enabled {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Scale adjustment stays disabled

When lid-close initialization is requested while the builtin monitor is enabled or multiple external monitors are active, applyLidScale returns without clearing lidScalePending, so tryToChangeScaleFactor keeps returning during the closed-lid session and the intended scale adjustment does not run.

Clear or otherwise resolve lidScalePending on these early-return paths.

Also at display1/manager_lid.go:229-230.

Prompt for AI agents
In `display1/manager_lid.go` at line 222:

**Scale adjustment stays disabled**

When lid-close initialization is requested while the builtin monitor is enabled or multiple external monitors are active, `applyLidScale` returns without clearing `lidScalePending`, so `tryToChangeScaleFactor` keeps returning during the closed-lid session and the intended scale adjustment does not run.

Clear or otherwise resolve `lidScalePending` on these early-return paths.

Also at `display1/manager_lid.go:229-230`.

return
}
var external *Monitor
for _, monitor := range monitorMap {
if monitor.ID != builtin.ID && monitor.realConnected && monitor.Enabled {
if external != nil {
return // 多外屏组合沿用原有逻辑,不擅自套用单外屏的缩放。
}
external = monitor
}
}
if external == nil {
return
}
if state != nil && state.ExternalUUID == external.uuid {
// 合盖期间重启服务时,当前值已经属于外屏,不能拿它覆盖内屏记录。
m.lidScalePending = false
return
}
factors, err := m.xsManager.GetScreenScaleFactors(0)
if err != nil {
logger.Warning("failed to read builtin scale before lid close:", err)
return
}
if state == nil {
state = &LidScaleConfig{Factors: make(map[string]map[string]float64)}
m.userConfig.LidScale = state
}
state.Factors[builtin.uuid] = factors

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Lid-close handling crashes

When the user config contains a LidScale object whose Factors map is missing or null, applyLidScale assigns to state.Factors without initializing the map, causing a nil-map panic that terminates the daemon.

Initialize state.Factors before assigning the builtin factors.

Prompt for AI agents
In `display1/manager_lid.go` at line 251:

**Lid-close handling crashes**

When the user config contains a `LidScale` object whose `Factors` map is missing or null, `applyLidScale` assigns to `state.Factors` without initializing the map, causing a nil-map panic that terminates the daemon.

Initialize `state.Factors` before assigning the builtin factors.

target := state.Factors[external.uuid]
if len(target) == 0 {
// 仅首次使用该外屏时计算默认值,之后优先恢复用户保存的值。
target = map[string]float64{"ALL": scale.GetRecommendedScaleFactor(m.xConn)}
}
state.ExternalUUID = external.uuid

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · External scale initialization is skipped

When ExternalUUID is saved but setting the external scale fails or the daemon stops before the scale is applied, applyLidScale treats the matching ExternalUUID as proof that the scale is active, clears lidScalePending, and skips the retry, so the external display keeps the wrong scale.

Save ExternalUUID only after SetScreenScaleFactors succeeds, and ensure a failed scale-setting call does not leave the marker in place.

Also at display1/manager_lid.go:237-240.

Prompt for AI agents
In `display1/manager_lid.go` at line 257:

**External scale initialization is skipped**

When `ExternalUUID` is saved but setting the external scale fails or the daemon stops before the scale is applied, `applyLidScale` treats the matching `ExternalUUID` as proof that the scale is active, clears `lidScalePending`, and skips the retry, so the external display keeps the wrong scale.

Save `ExternalUUID` only after `SetScreenScaleFactors` succeeds, and ensure a failed scale-setting call does not leave the marker in place.

Also at `display1/manager_lid.go:237-240`.

if err := m.saveUserConfigNoLock(); err != nil {
state.ExternalUUID = ""
logger.Warning("failed to save builtin scale before lid close:", err)
return
}
if err := m.xsManager.SetScreenScaleFactors(0, target); err != nil {
logger.Warning("failed to initialize external scale after lid close:", err)
return
}
m.lidScalePending = false
logger.Infof("applied external scale after lid close: %v", target)
}
Loading