From 3b27a72472bfcabbaf8d65a2b44bedb781cc7aac Mon Sep 17 00:00:00 2001 From: Ivy233 Date: Tue, 1 Dec 2026 19:38:31 +0800 Subject: [PATCH] fix(display): keep identical-EDID monitors distinct and migrate old layouts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Generate display UUIDs from a per-refresh view of the current topology. All connected X outputs are resolved against a freshly read DRM connector list, so identical-EDID monitors no longer share a UUID and the result cannot depend on hotplug or daemon-restart history. Only outputs that really share a (stdName, EDID fingerprint) pair fall back to their X output name, exact port-name matches keep the legacy UUID, and a single monitor keeps its @connector UUID even when several connectors report the same EDID. Migrate legacy screens configs that were saved with duplicate UUIDs instead of resetting the user's layout. The migration matches the old UUIDs to the current monitors by the EDID fingerprint embedded in each UUID and by the saved output names; it rewrites the screen key, per-monitor UUIDs, OnlyOne entries and fill-mode keys, and refuses to migrate when counts or names are ambiguous. Add regression tests for hotplug/restart stability, monitor replacement, single-monitor multi-connector and duplicate-connector-name cases, randomized topology properties, and legacy duplicate-UUID config migration. Log: Identical-EDID monitors keep independent layouts across hotplug and daemon restart, and existing layouts are migrated instead of reset. Influence: 1. Identical-EDID monitors receive unique UUIDs; a given topology keeps the same UUIDs across hotplug and daemon restarts. 2. A single monitor keeps its legacy UUID even when several DRM connectors report the same EDID. 3. Screens configs saved with duplicate UUIDs are migrated to the new UUIDs when the monitor set and names are unambiguous. fix(display): 保证同 EDID 显示器身份稳定并迁移旧布局 每轮刷新基于当前拓扑重新解析所有 X 输出的标准 connector 名,相同 EDID 的 显示器不再共享 UUID,判定结果也不再依赖热插或 daemon 重启历史。仅当多个 输出确实共享 (标准名, EDID 指纹) 时才回退到 X output 名;端口名精确匹配的 输出保留旧 UUID;只有一台显示器时,即使多个 connector 报告同一 EDID 也保留 @connector 形式的旧 UUID。 新增旧配置迁移:对历史上因重复 UUID 而无法命中的 Screens 配置,按 UUID 中 携带的 EDID 指纹和配置里的输出名映射到当前显示器,重写屏幕 key、各显示器 UUID、OnlyOne 条目和填充模式 key;数量或名称无法唯一确定时放弃迁移,避免 把布局写到错误的显示器,也避免升级后布局被整体重置。 补充热插/重启稳定性、换接显示器、单屏多 connector、跨卡同名 connector、 随机拓扑属性以及旧重复 UUID 配置迁移的回归测试。 Influence: 1. 相同 EDID 显示器获得唯一 UUID,同一拓扑在热插和重启后 UUID 不变。 2. 单屏在多个 connector 报告同一 EDID 时保留旧 UUID。 3. 重复 UUID 的旧屏幕配置在显示器集合与名称可唯一确定时迁移到新 UUID。 Log: 相同 EDID 显示器在热插和重启后保持独立布局,旧布局会迁移而不是重置。 PMS: BUG-382483 --- display1/config.go | 15 +- display1/displayconf.go | 569 +++++++++++++++++++++- display1/duplicate_uuid_test.go | 781 ++++++++++++++++++++++++++++++ display1/manager.go | 100 ++-- display1/manager_test.go | 90 ++++ display1/migration_test.go | 703 +++++++++++++++++++++++++++ display1/monitor.go | 12 + display1/stdname_property_test.go | 83 ++++ display1/util.go | 82 +++- display1/xorg.go | 104 +++- 10 files changed, 2453 insertions(+), 86 deletions(-) create mode 100644 display1/duplicate_uuid_test.go create mode 100644 display1/migration_test.go create mode 100644 display1/stdname_property_test.go diff --git a/display1/config.go b/display1/config.go index 29ec6ff40..6404ecbf5 100644 --- a/display1/config.go +++ b/display1/config.go @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2022-2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later @@ -40,7 +40,20 @@ func getCfgDir() string { } func updateSysMonitorConfigsName(configs SysMonitorConfigs, monitorMap map[uint32]*Monitor) { + // 同 EDID 的历史配置可能让多条记录共享同一个 UUID。 + // 此时不能再按 UUID 覆盖 Name,否则多条记录的 Name 会被写成同一个输出名, + // 后续按 (UUID, Name) 区分显示器的能力就会被破坏。 + uuidCount := make(map[string]int, len(configs)) for _, mc := range configs { + uuidCount[mc.UUID]++ + } + + for _, mc := range configs { + if uuidCount[mc.UUID] > 1 { + // UUID 有歧义时保留原 Name(包括空值),不能猜测并覆盖, + // 否则多条记录可能被写成同一个输出名。 + continue + } for _, m := range monitorMap { if mc.UUID == m.uuid { mc.Name = m.Name diff --git a/display1/displayconf.go b/display1/displayconf.go index 146aea685..7ad94fa77 100644 --- a/display1/displayconf.go +++ b/display1/displayconf.go @@ -147,15 +147,20 @@ func (m *Manager) getSysScreenConfig(monitorsId monitorsId) *SysScreenConfig { } func (m *Manager) updateConfigUuid(monitors Monitors) { - m.updateSysConfigUuid(monitors) - m.updateUserConfigUuid(monitors) + // 先迁移 SysConfig 并记录它为每个新 key 选中的旧 key, + // 再让 UserConfig 在多个历史 key 竞争同一新 key 时跟随同样的选择。 + preferred := m.updateSysConfigUuid(monitors) + m.updateUserConfigUuid(monitors, preferred) } -func (m *Manager) updateUserConfigUuid(monitors Monitors) { +func (m *Manager) updateUserConfigUuid(monitors Monitors, preferred map[string]string) { m.userCfgMu.Lock() defer m.userCfgMu.Unlock() - needSave := m.userConfig.updateUuid(monitors) + needSave := m.userConfig.migrateDuplicateUuidScreens(monitors, preferred) + if m.userConfig.updateUuid(monitors) { + needSave = true + } if needSave { err := m.saveUserConfigNoLock() if err != nil { @@ -202,17 +207,22 @@ func (cfg *UserConfig) updateUuid(monitors Monitors) (changed bool) { return } -func (m *Manager) updateSysConfigUuid(monitors Monitors) { +func (m *Manager) updateSysConfigUuid(monitors Monitors) map[string]string { m.sysConfig.mu.Lock() defer m.sysConfig.mu.Unlock() - needSave := m.sysConfig.Config.updateUuid(monitors) + changed, preferred := m.sysConfig.Config.migrateDuplicateUuidScreens(monitors) + needSave := changed + if m.sysConfig.Config.updateUuid(monitors) { + needSave = true + } if needSave { err := m.saveSysConfigNoLock("update uuid") if err != nil { logger.Warning("save sys config failed:", err) } } + return preferred } func (m *Manager) setSysScreenConfig(monitorsId monitorsId, screenCfg *SysScreenConfig) { @@ -441,6 +451,448 @@ func updateUuid(uuid string, monitors Monitors) (newUuid string, change bool) { return uuid, false } +// uuidEdidFingerprint 从 v1 UUID(形如 name|md5|v1)中取出 EDID 指纹。 +func uuidEdidFingerprint(uuid string) string { + parts := strings.Split(uuid, "|") + if len(parts) != 3 || parts[2] != "v1" || parts[1] == "" { + return "" + } + return parts[1] +} + +// duplicateUuidMigration 描述旧「重复 UUID」配置到当前显示器的映射。 +// +// 旧版本给相同 EDID 的显示器生成相同 UUID,屏幕配置 key 里会出现重复 UUID, +// 升级后这些 key 无法再被匹配。迁移只依赖 UUID 中的 EDID 指纹和配置条目的 +// Name:数量对不上或名称无法唯一确定时放弃迁移,避免把布局写到错误的显示器。 +type duplicateUuidMigration struct { + groups map[string]Monitors // 旧 UUID -> 当前显示器 + monitors Monitors // 该 key 涉及的全部当前显示器 +} + +func planDuplicateUuidMigration(monitorUuids []string, monitors Monitors) (*duplicateUuidMigration, bool) { + if len(monitorUuids) < 2 || len(monitors) < 2 { + return nil, false + } + + uuidCount := make(map[string]int, len(monitorUuids)) + hasDuplicate := false + for _, uuid := range monitorUuids { + uuidCount[uuid]++ + if uuidCount[uuid] > 1 { + hasDuplicate = true + } + } + if !hasDuplicate { + return nil, false + } + key := strings.Join(monitorUuids, monitorsIdDelimiter) + + // 必须用 realConnected(物理连接)而不是 Connected(有 CRTC 才算), + // 与调用方 getConnectedMonitors 保持一致:物理插着但被禁用的同型号屏 + // 也要计入,否则数量对不上会白白放弃迁移。 + monitorsByFingerprint := make(map[string]Monitors) + for _, monitor := range monitors { + if !monitor.realConnected || len(monitor.edid) < 128 { + continue + } + fingerprint := edidFingerprint(monitor.edid) + if fingerprint == "" { + continue + } + monitorsByFingerprint[fingerprint] = append(monitorsByFingerprint[fingerprint], monitor) + } + + migration := &duplicateUuidMigration{groups: make(map[string]Monitors, len(uuidCount))} + claimed := make(map[*Monitor]struct{}, len(monitors)) + for uuid, count := range uuidCount { + fingerprint := uuidEdidFingerprint(uuid) + if fingerprint == "" { + logger.Warningf("skip duplicate uuid migration for key %q: cannot parse EDID fingerprint from uuid %q", key, uuid) + return nil, false + } + candidates := monitorsByFingerprint[fingerprint] + if len(candidates) != count { + logger.Warningf("skip duplicate uuid migration for key %q: %d current monitors match fingerprint %q, but old key uses uuid %d times", + key, len(candidates), fingerprint, count) + return nil, false + } + for _, monitor := range candidates { + if _, ok := claimed[monitor]; ok { + logger.Warningf("skip duplicate uuid migration for key %q: monitor %q matched more than once", key, monitor.Name) + return nil, false + } + claimed[monitor] = struct{}{} + } + migration.groups[uuid] = candidates + migration.monitors = append(migration.monitors, candidates...) + } + if len(migration.monitors) != len(monitorUuids) { + logger.Warningf("skip duplicate uuid migration for key %q: %d current monitors match %d old uuids", + key, len(migration.monitors), len(monitorUuids)) + return nil, false + } + return migration, true +} + +// matchMonitorByGeometry 在剩余显示器中按位置和分辨率寻找唯一匹配。 +// 旧配置的 Name 可能被历史逻辑写成空或错误值,几何信息是最后可用的线索; +// 只有唯一匹配时才采用,镜像等无法区分的场景仍然放弃迁移。 +func (m *duplicateUuidMigration) matchMonitorByGeometry(monitorCfg *SysMonitorConfig, assigned map[*Monitor]struct{}) *Monitor { + fingerprint := uuidEdidFingerprint(monitorCfg.UUID) + var matched *Monitor + for _, monitor := range m.monitors { + if _, ok := assigned[monitor]; ok { + continue + } + if fingerprint != edidFingerprint(monitor.edid) { + continue + } + if monitorCfg.X != monitor.X || monitorCfg.Y != monitor.Y { + continue + } + if monitorCfg.Width != 0 && (monitorCfg.Width != monitor.Width || monitorCfg.Height != monitor.Height) { + continue + } + if matched != nil { + return nil + } + matched = monitor + } + return matched +} + +// remapMonitorUuids 按 Name 把配置条目对应到当前显示器,并写入新 UUID。 +// Name 无法确定时退回几何匹配,仍不唯一则放弃整条配置的迁移。 +func (m *duplicateUuidMigration) remapMonitorUuids(config *SysMonitorModeConfig, byName map[string]*Monitor) bool { + if config == nil { + return true + } + assigned := make(map[*Monitor]struct{}, len(config.Monitors)) + for _, monitorCfg := range config.Monitors { + monitor := byName[monitorCfg.Name] + if monitor != nil { + if _, ok := assigned[monitor]; ok { + monitor = nil + } + } + if monitor == nil || uuidEdidFingerprint(monitorCfg.UUID) != edidFingerprint(monitor.edid) { + monitor = m.matchMonitorByGeometry(monitorCfg, assigned) + } + if monitor == nil { + return false + } + assigned[monitor] = struct{}{} + monitorCfg.UUID = monitor.uuid + monitorCfg.Name = monitor.Name + } + return true +} + +// migrateDuplicateUuid 尝试把一条旧屏幕配置迁移到当前显示器。 +// 返回迁移后的配置;false 表示无法安全迁移,调用方应保留原配置。 +func (c *SysScreenConfig) migrateDuplicateUuid(migration *duplicateUuidMigration) (*SysScreenConfig, bool) { + byName := make(map[string]*Monitor, len(migration.monitors)) + for _, monitor := range migration.monitors { + if monitor.Name == "" { + return nil, false + } + if _, ok := byName[monitor.Name]; ok { + return nil, false + } + byName[monitor.Name] = monitor + } + + result := c.clone() + for _, config := range []*SysMonitorModeConfig{result.Mirror, result.Extend, result.Single} { + if !migration.remapMonitorUuids(config, byName) { + return nil, false + } + } + + migratedOnlyOne := make(map[string]string, len(result.OnlyOneMap)) + if len(result.OnlyOneMap) > 0 { + onlyOneMap := make(map[string]*SysMonitorModeConfig, len(result.OnlyOneMap)) + for oldUuid, config := range result.OnlyOneMap { + if config == nil || len(config.Monitors) != 1 { + onlyOneMap[oldUuid] = config + continue + } + monitorCfg := config.Monitors[0] + monitor := byName[monitorCfg.Name] + if monitor == nil { + monitor = migration.matchMonitorByGeometry(monitorCfg, nil) + } + if monitor == nil || uuidEdidFingerprint(oldUuid) != edidFingerprint(monitor.edid) { + onlyOneMap[oldUuid] = config + continue + } + monitorCfg.UUID = monitor.uuid + monitorCfg.Name = monitor.Name + onlyOneMap[monitor.uuid] = config + migratedOnlyOne[oldUuid] = monitor.uuid + if oldUuid == c.OnlyOneUuid { + result.OnlyOneUuid = monitor.uuid + } + } + result.OnlyOneMap = onlyOneMap + } + if c.OnlyOneUuid != "" { + // OnlyOneUuid 指向的条目不存在或无法映射时放弃整条配置的迁移, + // 否则迁移后 OnlyOne 选择会静默丢失并回退到默认主屏。 + newUuid, ok := migratedOnlyOne[c.OnlyOneUuid] + if !ok { + logger.Warningf("skip duplicate uuid migration: OnlyOneUuid %q cannot be mapped to a current monitor", c.OnlyOneUuid) + return nil, false + } + result.OnlyOneUuid = newUuid + } + return result, true +} + +// migrateDuplicateUuidFillModes 把旧重复 UUID 对应的填充模式复制到新 UUID。 +func (cfg *SysConfig) migrateDuplicateUuidFillModes(migration *duplicateUuidMigration) { + if len(cfg.FillModes) == 0 { + return + } + // 旧 key 不删除:同一 EDID 组的显示器可能只接入了子集,旧 key 还要服务 + // 尚未接入的同类显示器;删除会让它们以后拿不到填充模式。 + for oldUuid, group := range migration.groups { + prefix := oldUuid + fillModeKeyDelimiter + for key, value := range cfg.FillModes { + if !strings.HasPrefix(key, prefix) { + continue + } + suffix := key[len(oldUuid):] + for _, monitor := range group { + if monitor.uuid == oldUuid { + continue + } + newKey := monitor.uuid + suffix + if _, ok := cfg.FillModes[newKey]; !ok { + cfg.FillModes[newKey] = value + } + } + } + } +} + +// scoreDuplicateUuidCandidate 用当前实际布局给候选旧配置打分:多个历史 key +// 可能映射到同一个新 key(例如不同时期探测到的不同端口名),应选择与用户 +// 当前所见布局最接近的那条,而不是依赖 map 遍历顺序。 +func scoreDuplicateUuidCandidate(screenCfg *SysScreenConfig, byName map[string]*Monitor, displayMode byte) int { + var modeCfg *SysMonitorModeConfig + switch displayMode { + case DisplayModeMirror: + modeCfg = screenCfg.Mirror + case DisplayModeExtend: + modeCfg = screenCfg.Extend + case DisplayModeOnlyOne: + modeCfg = screenCfg.OnlyOneMap[screenCfg.OnlyOneUuid] + if modeCfg == nil { + // OnlyOneUuid 未记录或已失效时按排序后第一个有效条目, + // 避免依赖 map 的随机遍历顺序。 + keys := make([]string, 0, len(screenCfg.OnlyOneMap)) + for key := range screenCfg.OnlyOneMap { + keys = append(keys, key) + } + sort.Strings(keys) + for _, key := range keys { + if config := screenCfg.OnlyOneMap[key]; config != nil { + modeCfg = config + break + } + } + } + default: + modeCfg = screenCfg.Single + } + if modeCfg == nil { + return 0 + } + + score := 0 + for _, monitorCfg := range modeCfg.Monitors { + monitor := byName[monitorCfg.Name] + if monitor == nil { + continue + } + if monitorCfg.X == monitor.X && monitorCfg.Y == monitor.Y { + score += 2 + } + if monitorCfg.Width == monitor.Width && monitorCfg.Height == monitor.Height { + score++ + } + if monitorCfg.Enabled == monitor.Enabled { + score++ + } + if diff := monitorCfg.RefreshRate - monitor.RefreshRate; diff > -0.01 && diff < 0.01 { + score++ + } + } + return score +} + +// migrateDuplicateUuidScreens 迁移旧版本因 EDID 相同而生成重复 UUID 的屏幕配置。 +// 只有 UUID 数量与当前显示器一一对应、且每个配置条目的 Name 都能唯一确定时才迁移。 +func (cfg *SysConfig) migrateDuplicateUuidScreens(monitors Monitors) (changed bool, preferred map[string]string) { + if len(cfg.Screens) == 0 { + return false, nil + } + + byName := make(map[string]*Monitor, len(monitors)) + for _, monitor := range monitors { + byName[monitor.Name] = monitor + } + + keys := make([]string, 0, len(cfg.Screens)) + for key := range cfg.Screens { + keys = append(keys, key) + } + sort.Strings(keys) + + type candidate struct { + screenCfg *SysScreenConfig + migration *duplicateUuidMigration + oldKey string + score int + } + chosen := make(map[string]*candidate) + for _, key := range keys { + uuids := strings.Split(key, monitorsIdDelimiter) + migration, ok := planDuplicateUuidMigration(uuids, monitors) + if !ok { + continue + } + screenCfg := cfg.Screens[key] + if screenCfg == nil { + continue + } + newScreenCfg, ok := screenCfg.migrateDuplicateUuid(migration) + if !ok { + logger.Warningf("skip duplicate uuid migration for key %q: cannot map every monitor config to a current monitor", key) + continue + } + newKey := migration.monitors.getMonitorsId().v1 + if newKey == "" || newKey == key { + continue + } + item := &candidate{ + screenCfg: newScreenCfg, + migration: migration, + oldKey: key, + score: scoreDuplicateUuidCandidate(newScreenCfg, byName, cfg.DisplayMode), + } + if old, ok := chosen[newKey]; !ok || item.score > old.score { + chosen[newKey] = item + } + } + if len(chosen) == 0 { + return false, nil + } + + // 记录每个新 key 由 SysConfig 选中的旧 key,供 UserConfig 在多个历史 + // key 竞争同一新 key 时保持同样的选择;即使新 key 已存在未被采用, + // 这个选择仍然是当前布局下最可信的历史来源。 + preferred = make(map[string]string, len(chosen)) + for newKey, item := range chosen { + preferred[item.oldKey] = newKey + } + + // 只有真正写入 cfg.Screens[newKey] 的旧 key 才删除;未被采用的旧 key + // (例如第一次迁移失败后默认布局已经写进新 key)必须保留,供后续重试 + // 和回滚,否则旧布局会永久丢失。 + deletedKeys := make(map[string]struct{}, len(chosen)) + for newKey, item := range chosen { + if _, ok := cfg.Screens[newKey]; ok { + logger.Debugf("duplicate uuid screen config %q already exists, keep legacy key %q for retry", newKey, item.oldKey) + continue + } + cfg.Screens[newKey] = item.screenCfg + deletedKeys[item.oldKey] = struct{}{} + logger.Infof("migrate duplicate uuid screen config to %q", newKey) + cfg.migrateDuplicateUuidFillModes(item.migration) + } + if len(deletedKeys) == 0 { + return false, preferred + } + for key := range deletedKeys { + delete(cfg.Screens, key) + } + return true, preferred +} + +// migrateDuplicateUuidScreens 迁移用户配置中旧重复 UUID 的 key。 +// preferred 是 SysConfig 迁移时为每个新 key 选中的旧 key(oldKey -> newKey), +// 多个历史 key 竞争同一新 key 时优先跟随它;为空时退回按键名排序的第一条。 +func (cfg *UserConfig) migrateDuplicateUuidScreens(monitors Monitors, preferred map[string]string) (changed bool) { + keys := make([]string, 0, len(cfg.Screens)) + for key := range cfg.Screens { + keys = append(keys, key) + } + sort.Strings(keys) + + preferredOldKey := make(map[string]string, len(preferred)) + for oldKey, newKey := range preferred { + if oldKey != "" && newKey != "" { + preferredOldKey[newKey] = oldKey + } + } + + type candidate struct { + oldKey string + result UserScreenConfig + } + chosen := make(map[string]*candidate) + for _, key := range keys { + screenCfg := cfg.Screens[key] + uuids := strings.Split(key, monitorsIdDelimiter) + migration, ok := planDuplicateUuidMigration(uuids, monitors) + if !ok { + continue + } + newKey := migration.monitors.getMonitorsId().v1 + if newKey == "" || newKey == key { + continue + } + result := make(UserScreenConfig, len(screenCfg)) + for modeKey, modeCfg := range screenCfg { + if strings.HasPrefix(modeKey, KeyModeOnlyOnePrefix) { + oldUuid := strings.TrimPrefix(modeKey, KeyModeOnlyOnePrefix) + group, ok := migration.groups[oldUuid] + if !ok || len(group) == 0 { + // uuid 无法映射时保留原条目,避免用户 OnlyOne 设置静默丢失。 + result[modeKey] = modeCfg + continue + } + for _, monitor := range group { + result[KeyModeOnlyOnePrefix+monitor.uuid] = modeCfg + } + continue + } + result[modeKey] = modeCfg + } + item := &candidate{oldKey: key, result: result} + old, exists := chosen[newKey] + if !exists || (preferredOldKey[newKey] == key && old.oldKey != key) { + chosen[newKey] = item + } + } + + for newKey, item := range chosen { + if _, ok := cfg.Screens[newKey]; ok { + // 新 key 已存在时不覆盖用户当前配置,也保留旧 key 供后续重试/回滚。 + logger.Debugf("duplicate uuid user config %q already exists, keep legacy key %q for retry", newKey, item.oldKey) + continue + } + cfg.Screens[newKey] = item.result + logger.Infof("migrate duplicate uuid user config to %q", newKey) + delete(cfg.Screens, item.oldKey) + changed = true + } + return changed +} + // 更新配置中的所有 uuid 的版本 func (c *SysMonitorModeConfig) updateUuid(monitors Monitors) (*SysMonitorModeConfig, bool) { if c == nil { @@ -706,14 +1158,111 @@ func (cfgs SysMonitorConfigs) getByUuid(uuid string) *SysMonitorConfig { return nil } -func (cfgs SysMonitorConfigs) setPrimary(uuid string) { +// getByUuidAndName 优先用 UUID + Name 精确匹配配置。 +// 多台同型号显示器的 EDID 可能完全相同,从而产生相同的 UUID; +// 此时仅靠 UUID 只能命中第一条配置,必须用 Name 区分。 +func (cfgs SysMonitorConfigs) getByUuidAndName(uuid, name string) *SysMonitorConfig { + return cfgs.getByUuidAndNameWithMonitor(uuid, name, nil) +} + +// getByUuidAndNameWithMonitor 是 getByUuidAndName 的完整版本,额外利用当前 +// 显示器的几何信息消除重复 UUID 的歧义。UUID 唯一时行为与旧实现完全一致: +// Name 不匹配仍回退到该 UUID 的唯一配置,避免旧配置导致显示器被禁用。 +// UUID 重复且 Name 不匹配时,只有与当前显示器 X/Y/Width/Height 完全一致 +// 且唯一的配置才会被采用;否则返回 nil,避免多台显示器被写入相同坐标。 +func (cfgs SysMonitorConfigs) getByUuidAndNameWithMonitor(uuid, name string, monitor *Monitor) *SysMonitorConfig { + if name != "" { + for _, mc := range cfgs { + if uuid == mc.UUID && name == mc.Name { + return mc + } + } + } + + var matches SysMonitorConfigs + for _, mc := range cfgs { + if uuid == mc.UUID { + matches = append(matches, mc) + } + } + if len(matches) <= 1 { + if len(matches) == 1 { + return matches[0] + } + return nil + } + + if monitor == nil { + logger.Warningf("duplicate uuid %q has %d configs and no monitor information to disambiguate", uuid, len(matches)) + return nil + } + + var matched *SysMonitorConfig + for _, mc := range matches { + if mc.X != monitor.X || mc.Y != monitor.Y || + mc.Width != monitor.Width || mc.Height != monitor.Height { + continue + } + if matched != nil { + logger.Warningf("duplicate uuid %q has multiple configs matching monitor %s geometry, skip", uuid, monitor.Name) + return nil + } + matched = mc + } + if matched == nil { + logger.Warningf("duplicate uuid %q has no config matching monitor %s geometry, skip", uuid, monitor.Name) + } + return matched +} + +// countByUuid 返回配置中同一 UUID 出现的次数。 +func (cfgs SysMonitorConfigs) countByUuid(uuid string) int { + count := 0 for _, mc := range cfgs { if mc.UUID == uuid { - mc.Primary = true - } else { - mc.Primary = false + count++ } } + return count +} + +func (cfgs SysMonitorConfigs) setPrimary(uuid string) { + cfgs.setPrimaryByUuidAndName(uuid, "") +} + +func (cfgs SysMonitorConfigs) setPrimaryByUuidAndName(uuid, name string) { + if name != "" { + matched := false + for _, mc := range cfgs { + if mc.UUID == uuid && mc.Name == name { + matched = true + break + } + } + if !matched { + // 与 getByUuidAndName 的兼容兜底一致:Name 过期时按 UUID 设置, + // 不能把所有配置的 Primary 都清掉。 + name = "" + } + } + + for _, mc := range cfgs { + mc.Primary = mc.UUID == uuid && (name == "" || mc.Name == name) + } +} + +// setPrimaryConfig 把已经通过 UUID+Name/几何消歧唯一匹配到的 target 配置设为 +// 主屏,其余配置一律清除非主屏标记。 +// 重复 UUID 时不能再按 UUID+Name 二次查找:Name 过期会退化成只按 UUID 匹配, +// 从而把同一 UUID 的多条配置全部置为 Primary。 +func (cfgs SysMonitorConfigs) setPrimaryConfig(target *SysMonitorConfig) { + if target == nil { + return + } + + for _, mc := range cfgs { + mc.Primary = mc == target + } } // cfgs 和 otherCfgs 之间是否仅亮度不同 diff --git a/display1/duplicate_uuid_test.go b/display1/duplicate_uuid_test.go new file mode 100644 index 000000000..7673be491 --- /dev/null +++ b/display1/duplicate_uuid_test.go @@ -0,0 +1,781 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +package display1 + +import ( + "bytes" + "os" + "path/filepath" + "testing" + + "github.com/linuxdeepin/go-lib/utils" +) + +// writeTestEdid 在伪 /sys/class/drm 目录下构造一个 connector 及其 edid 文件。 +// card 用于模拟跨显卡场景(card0 / card1)。 +func writeTestEdid(t *testing.T, dir, card, connector string, edid []byte) { + t.Helper() + + path := filepath.Join(dir, card+"-"+connector) + if err := os.MkdirAll(path, 0755); err != nil { + t.Fatalf("mkdir %s failed: %v", path, err) + } + if err := os.WriteFile(filepath.Join(path, "edid"), edid, 0644); err != nil { + t.Fatalf("write edid failed: %v", err) + } +} + +type testOutput struct { + name string + edid []byte +} + +// testOutputUuids 走与 refreshMonitorsCache 相同的两步逻辑: +// 先读取本轮 connector 列表,再由 assignStdNames 决定标准名, +// 最后用 getOutputUuid 生成最终 UUID。返回 map[X 输出名]UUID。 +func testOutputUuids(t *testing.T, dir string, outputs []testOutput) map[string]string { + t.Helper() + + owners := make([]edidOwner, 0, len(outputs)) + for _, output := range outputs { + owners = append(owners, edidOwner{ + Name: output.name, + Connected: true, + EDID: output.edid, + }) + } + + stdNames := assignStdNames(owners, listSysDrmConnectors(dir)) + + uuids := make(map[string]string, len(owners)) + for _, owner := range owners { + uuids[owner.Name] = getOutputUuid(owner.Name, stdNames[owner.Name], owner.EDID) + } + return uuids +} + +func assertDistinctUuids(t *testing.T, uuids map[string]string) { + t.Helper() + + seen := make(map[string]string, len(uuids)) + for name, uuid := range uuids { + if other, ok := seen[uuid]; ok { + t.Fatalf("outputs %s and %s share UUID %s", other, name, uuid) + } + seen[uuid] = name + } +} + +func assertXFallbackUuid(t *testing.T, name, uuid string, edid []byte) { + t.Helper() + + want := name + "|" + edidFingerprint(edid) + "|v1" + if uuid != want { + t.Fatalf("output %s UUID = %q, want X-name fallback %q", name, uuid, want) + } +} + +// 场景 A:本机形态。X 侧是 nvidia 的 DP-0/DP-2,sysfs 只有 card1-DP-3/DP-4 +// 报告同一 EDID。旧实现会认领 card1-DP-3 并让两台显示器共享 UUID。 +func TestUuidsIdenticalEdidSharedOnOtherCard(t *testing.T) { + dir := t.TempDir() + edidX := bytes.Repeat([]byte{0x11}, 128) + edidSys := bytes.Repeat([]byte{0x11}, 256) + writeTestEdid(t, dir, "card1", "DP-3", edidSys) + writeTestEdid(t, dir, "card1", "DP-4", edidSys) + + uuids := testOutputUuids(t, dir, []testOutput{ + {name: "DP-0", edid: edidX}, + {name: "DP-2", edid: edidX}, + }) + + assertDistinctUuids(t, uuids) + for name, uuid := range uuids { + assertXFallbackUuid(t, name, uuid, edidX) + } +} + +// 场景 B:四屏同源,X 输出与 DRM connector 名字一一对应但 EDID 相同。 +func TestUuidsFourIdenticalEdidMonitors(t *testing.T) { + dir := t.TempDir() + edidX := bytes.Repeat([]byte{0x22}, 128) + edidSys := bytes.Repeat([]byte{0x22}, 256) + connectors := []string{"DP-1", "DP-2", "DP-3", "DP-4"} + for _, connector := range connectors { + writeTestEdid(t, dir, "card0", connector, edidSys) + } + + outputs := make([]testOutput, 0, len(connectors)) + for _, connector := range connectors { + outputs = append(outputs, testOutput{name: connector, edid: edidX}) + } + uuids := testOutputUuids(t, dir, outputs) + + assertDistinctUuids(t, uuids) + if len(uuids) != 4 { + t.Fatalf("got %d UUIDs, want 4", len(uuids)) + } + for name, uuid := range uuids { + // 四台输出共享同一 EDID 指纹,无法判断端口归属,一律回退到 X 名。 + // 即使 X 名与 connector 一一对应,也不能沿用 @connector 形态,否则 + // connector 探测进度变化时 UUID 会漂移。 + assertXFallbackUuid(t, name, uuid, edidX) + } +} + +// 场景 D:部分探测。sysfs 只有 card1-DP-3 已探测出 EDID,card1-DP-4 的 +// edid 为空。候选修复 4c853bd7 在此会误判为唯一匹配,从而让两台屏共享 UUID。 +func TestUuidsIdenticalEdidPartiallyProbed(t *testing.T) { + dir := t.TempDir() + edidX := bytes.Repeat([]byte{0x33}, 128) + edidSys := bytes.Repeat([]byte{0x33}, 256) + writeTestEdid(t, dir, "card1", "DP-3", edidSys) + writeTestEdid(t, dir, "card1", "DP-4", nil) + + uuids := testOutputUuids(t, dir, []testOutput{ + {name: "DP-0", edid: edidX}, + {name: "DP-2", edid: edidX}, + }) + + assertDistinctUuids(t, uuids) + for name, uuid := range uuids { + assertXFallbackUuid(t, name, uuid, edidX) + } +} + +func TestUuidsSameEdidPrefixDifferentLengths(t *testing.T) { + dir := t.TempDir() + prefix := bytes.Repeat([]byte{0x3c}, 128) + edid256 := append(append([]byte{}, prefix...), bytes.Repeat([]byte{0x5a}, 128)...) + // 只有一个 sysfs connector 完成探测时,两个不同长度的 X EDID + // 都会按前缀命中同一 connector,最终必须一起回退。 + writeTestEdid(t, dir, "card1", "DP-3", edid256) + + uuids := testOutputUuids(t, dir, []testOutput{ + {name: "DP-0", edid: prefix}, + {name: "DP-2", edid: edid256}, + }) + assertDistinctUuids(t, uuids) + assertXFallbackUuid(t, "DP-0", uuids["DP-0"], prefix) + assertXFallbackUuid(t, "DP-2", uuids["DP-2"], edid256) +} + +// 场景 C:跨卡同名。两台 X 输出共享同一 EDID 时,即使其中一台与 +// card0-DP-2 同名,也不能据此猜测物理端口归属,全部回退到 X output 名。 +// 跨 GPU 的物理端口归属需要 RandR provider 信息,属于独立问题。 +func TestUuidsCrossCardSameName(t *testing.T) { + dir := t.TempDir() + edidX := bytes.Repeat([]byte{0x44}, 128) + edidSys := bytes.Repeat([]byte{0x44}, 256) + writeTestEdid(t, dir, "card0", "DP-2", edidSys) + writeTestEdid(t, dir, "card1", "DP-3", edidSys) + writeTestEdid(t, dir, "card1", "DP-4", edidSys) + + uuids := testOutputUuids(t, dir, []testOutput{ + {name: "DP-0", edid: edidX}, + {name: "DP-2", edid: edidX}, + }) + + assertDistinctUuids(t, uuids) + for name, uuid := range uuids { + assertXFallbackUuid(t, name, uuid, edidX) + } +} + +// 场景 E:EDID 唯一,兼容性回归。每台显示器各有一个 connector 时, +// UUID 必须与旧版逐字符一致,不能让存量配置失效。 +func TestUuidsUniqueEdidKeepsLegacyFormat(t *testing.T) { + dir := t.TempDir() + edidA := bytes.Repeat([]byte{0x55}, 128) + edidB := bytes.Repeat([]byte{0x66}, 128) + writeTestEdid(t, dir, "card1", "DP-3", bytes.Repeat([]byte{0x55}, 256)) + writeTestEdid(t, dir, "card1", "DP-4", bytes.Repeat([]byte{0x66}, 256)) + + uuids := testOutputUuids(t, dir, []testOutput{ + {name: "DP-0", edid: edidA}, + {name: "DP-2", edid: edidB}, + }) + + wantDP0 := "@DP-3|" + edidFingerprint(edidA) + "|v1" + if got := uuids["DP-0"]; got != wantDP0 { + t.Fatalf("DP-0 UUID = %q, want %q", got, wantDP0) + } + wantDP2 := "@DP-4|" + edidFingerprint(edidB) + "|v1" + if got := uuids["DP-2"]; got != wantDP2 { + t.Fatalf("DP-2 UUID = %q, want %q", got, wantDP2) + } +} + +func TestEdidFingerprint(t *testing.T) { + if got := edidFingerprint(nil); got != "" { + t.Fatalf("edidFingerprint(nil) = %q, want empty", got) + } + if got := edidFingerprint(bytes.Repeat([]byte{0x01}, 127)); got != "" { + t.Fatalf("edidFingerprint(127 bytes) = %q, want empty", got) + } + + edid128 := bytes.Repeat([]byte{0x77}, 128) + edid256 := append(append([]byte{}, edid128...), bytes.Repeat([]byte{0x88}, 128)...) + if got, want := edidFingerprint(edid128), edidFingerprint(edid256); got != want { + t.Fatalf("prefix-identical EDIDs got different fingerprints: %q != %q", got, want) + } + + want, _ := utils.SumStrMd5(string(edid128)) + if got := edidFingerprint(edid128); got != want { + t.Fatalf("edidFingerprint = %q, want %q", got, want) + } +} + +// 跨显卡同名 connector 不应被当成两个候选:只有一台显示器时保留旧 UUID。 +func TestUuidsCrossCardDuplicateConnectorSingleMonitor(t *testing.T) { + dir := t.TempDir() + edidX := bytes.Repeat([]byte{0x44}, 128) + writeTestEdid(t, dir, "card0", "DP-2", bytes.Repeat([]byte{0x44}, 256)) + writeTestEdid(t, dir, "card1", "DP-2", bytes.Repeat([]byte{0x44}, 256)) + + uuids := testOutputUuids(t, dir, []testOutput{{name: "DP-2", edid: edidX}}) + want := "@DP-2|" + edidFingerprint(edidX) + "|v1" + if uuids["DP-2"] != want { + t.Fatalf("single monitor UUID = %q, want unchanged legacy UUID %q", uuids["DP-2"], want) + } +} + +// 只有一台 X 显示器、多个 connector 报同一 EDID(MST/扩展坞形态)时不存在 +// UUID 冲突,必须保留旧实现的 @connector UUID,不能让存量配置失效。 +func TestUuidsSingleMonitorMultipleConnectors(t *testing.T) { + dir := t.TempDir() + edidX := bytes.Repeat([]byte{0x9a}, 128) + writeTestEdid(t, dir, "card0", "DP-3", bytes.Repeat([]byte{0x9a}, 256)) + writeTestEdid(t, dir, "card0", "DP-4", bytes.Repeat([]byte{0x9a}, 256)) + + uuids := testOutputUuids(t, dir, []testOutput{{name: "DP-0", edid: edidX}}) + want := "@DP-3|" + edidFingerprint(edidX) + "|v1" + if uuids["DP-0"] != want { + t.Fatalf("single monitor UUID = %q, want unchanged legacy UUID %q", uuids["DP-0"], want) + } +} + +// A1 回归:只有一台 X 输出时,即使 X 输出名与某个 connector 精确匹配, +// 也必须保持旧实现的“取第一个候选”,否则健康机器升级后 UUID 会从 +// @DP-2|... 变成 @DP-3|...,存量布局丢失。 +func TestUuidsSingleMonitorExactConnectorNotFirstKeepsLegacyUuid(t *testing.T) { + edid := bytes.Repeat([]byte{0x5a}, 128) + connectors := []drmConnector{ + {name: "DP-2", edid: edid}, + {name: "DP-3", edid: edid}, + } + legacyCandidates := matchConnectorNames(connectors, edid) + if len(legacyCandidates) < 2 { + t.Fatalf("got %d connector candidates, want at least 2", len(legacyCandidates)) + } + legacyUuid := getOutputUuid("DP-3", legacyCandidates[0], edid) + + stdNames := assignStdNames([]edidOwner{ + {Name: "DP-3", Connected: true, EDID: edid}, + }, connectors) + got := getOutputUuid("DP-3", stdNames["DP-3"], edid) + + if got != legacyUuid { + t.Fatalf("single monitor UUID changed: got %q, legacy %q", got, legacyUuid) + } + want := "@DP-2|" + edidFingerprint(edid) + "|v1" + if got != want { + t.Fatalf("single monitor UUID = %q, want legacy first-candidate UUID %q", got, want) + } +} + +// 多个输出共享同一 EDID 指纹时无法判断端口归属,直接全部回退(空 stdName)。 +func TestAssignStdNamesSharedStdNameFallsBack(t *testing.T) { + edid := bytes.Repeat([]byte{0xcc}, 128) + connectors := []drmConnector{ + {name: "DP-3", edid: bytes.Repeat([]byte{0xcc}, 256)}, + {name: "DP-4", edid: bytes.Repeat([]byte{0xcc}, 256)}, + } + + got := assignStdNames([]edidOwner{ + {Name: "DP-0", Connected: true, EDID: edid}, + {Name: "DP-2", Connected: true, EDID: edid}, + }, connectors) + + for _, name := range []string{"DP-0", "DP-2"} { + if stdName, ok := got[name]; ok && stdName != "" { + t.Fatalf("assignStdNames[%q] = %q, want empty fallback", name, stdName) + } + } +} + +func TestAssignStdNamesSkipsDisconnectedAndShortEdid(t *testing.T) { + connectors := []drmConnector{ + {name: "std-DP-0", edid: bytes.Repeat([]byte{0x01}, 128)}, + {name: "std-DP-2", edid: bytes.Repeat([]byte{0x02}, 128)}, + {name: "std-DP-3", edid: bytes.Repeat([]byte{0x03}, 128)}, + {name: "std-DP-4", edid: bytes.Repeat([]byte{0x04}, 128)}, + } + + got := assignStdNames([]edidOwner{ + {Name: "DP-0", Connected: true, EDID: bytes.Repeat([]byte{0x01}, 128)}, + {Name: "DP-2", Connected: true, EDID: bytes.Repeat([]byte{0x02}, 128)}, + {Name: "DP-3", Connected: false, EDID: bytes.Repeat([]byte{0x03}, 128)}, + {Name: "DP-4", Connected: true, EDID: bytes.Repeat([]byte{0x04}, 100)}, + }, connectors) + + if got["DP-0"] != "std-DP-0" || got["DP-2"] != "std-DP-2" { + t.Fatalf("unique EDID stdNames = %+v, want std-DP-0 / std-DP-2", got) + } + if _, ok := got["DP-3"]; ok { + t.Fatalf("disconnected output got stdName %q", got["DP-3"]) + } + if _, ok := got["DP-4"]; ok { + t.Fatalf("short-EDID output got stdName %q", got["DP-4"]) + } +} + +func TestGetOutputUuidIdenticalEdidUsesDistinctStdNames(t *testing.T) { + edid := bytes.Repeat([]byte{0x78}, 128) + // 固定 X 输出名,只改变 stdName:若 getOutputUuid 忽略 stdName, + // 所有结果都会相同,该用例必然失败。 + const xName = "DP-0" + seen := make(map[string]string) + for _, stdName := range []string{"DP-1", "DP-2", "DP-3", "DP-4"} { + uuid := getOutputUuid(xName, stdName, edid) + want := "@" + stdName + "|" + edidFingerprint(edid) + "|v1" + if uuid != want { + t.Fatalf("stdName %s UUID = %q, want %q", stdName, uuid, want) + } + if other, ok := seen[uuid]; ok { + t.Fatalf("stdName %s and %s got the same UUID %s", other, stdName, uuid) + } + seen[uuid] = stdName + } +} + +func TestSysMonitorConfigsGetByUuidAndName(t *testing.T) { + const uuid = "@DP-1|hash|v1" + cfgs := SysMonitorConfigs{ + {UUID: uuid, Name: "DP-4", X: 0}, + {UUID: uuid, Name: "DP-1", X: 3840}, + {UUID: uuid, Name: "DP-2", X: 7680}, + {UUID: uuid, Name: "DP-3", X: 11520}, + } + + want := map[string]int16{ + "DP-1": 3840, + "DP-2": 7680, + "DP-3": 11520, + "DP-4": 0, + } + for name, wantX := range want { + cfg := cfgs.getByUuidAndName(uuid, name) + if cfg == nil { + t.Fatalf("getByUuidAndName(%q) returned nil", name) + } + if cfg.X != wantX { + t.Fatalf("getByUuidAndName(%q).X = %d, want %d", name, cfg.X, wantX) + } + } + + if cfg := cfgs.getByUuidAndName(uuid, "DP-9"); cfg != nil { + t.Fatalf("getByUuidAndName should not pick the first of an ambiguous duplicate UUID, got %+v", cfg) + } + + // 有当前显示器信息时,只有位置和分辨率完全一致的唯一配置才会被采用。 + monitor := &Monitor{Name: "DP-9", uuid: uuid, X: 7680, Y: 0} + if cfg := cfgs.getByUuidAndNameWithMonitor(uuid, "DP-9", monitor); cfg == nil || cfg.Name != "DP-2" { + t.Fatalf("geometry fallback returned %+v, want DP-2", cfg) + } + + cfgs[0].Primary = true + cfgs.setPrimaryByUuidAndName(uuid, "DP-2") + primaryCount := 0 + for _, cfg := range cfgs { + if cfg.Primary { + primaryCount++ + if cfg.Name != "DP-2" { + t.Fatalf("unexpected primary config: %+v", cfg) + } + } + } + if primaryCount != 1 { + t.Fatalf("primary count = %d, want 1", primaryCount) + } +} + +func TestSysMonitorConfigsGetByUuidAndNameUniqueFallback(t *testing.T) { + cfgs := SysMonitorConfigs{ + {UUID: "unique-uuid", Name: "DP-1", X: 3840}, + } + + cfg := cfgs.getByUuidAndName("unique-uuid", "DP-9") + if cfg == nil { + t.Fatal("getByUuidAndName should fall back to unique UUID") + } + if cfg.X != 3840 { + t.Fatalf("unexpected config: %+v", cfg) + } +} + +func TestMonitorsGetByUuidAndNameOrUuid(t *testing.T) { + monitors := Monitors{ + &Monitor{Name: "DP-1", uuid: "duplicate-uuid"}, + &Monitor{Name: "DP-2", uuid: "duplicate-uuid"}, + } + + if got := monitors.GetByUuidAndNameOrUuid("duplicate-uuid", "DP-2"); got == nil || got.Name != "DP-2" { + t.Fatalf("GetByUuidAndNameOrUuid returned %+v, want DP-2", got) + } + if got := monitors.GetByUuidAndNameOrUuid("duplicate-uuid", "DP-9"); got != monitors.GetByUuid("duplicate-uuid") { + t.Fatalf("GetByUuidAndNameOrUuid unknown-name fallback returned %+v, want same monitor as GetByUuid", got) + } + + unique := Monitors{&Monitor{Name: "DP-1", uuid: "unique-uuid"}} + if got := unique.GetByUuidAndNameOrUuid("unique-uuid", "DP-9"); got == nil || got.Name != "DP-1" { + t.Fatalf("GetByUuidAndNameOrUuid unique fallback returned %+v, want DP-1", got) + } +} + +// updateSysMonitorConfigsName 不能在 UUID 有歧义时用同一个输出名覆盖多条 +// 配置的 Name,否则 (UUID, Name) 这第二道防线会被破坏。 +func TestUpdateSysMonitorConfigsNameKeepsDuplicateUuidNames(t *testing.T) { + const uuid = "@DP-3|hash|v1" + configs := SysMonitorConfigs{ + {UUID: uuid, Name: "DP-0", X: 0}, + {UUID: uuid, Name: "DP-2", X: 3840}, + } + monitorMap := map[uint32]*Monitor{ + 1: {Name: "DP-2", uuid: uuid}, + 2: {Name: "DP-2", uuid: uuid}, + } + + updateSysMonitorConfigsName(configs, monitorMap) + + if configs[0].Name != "DP-0" || configs[1].Name != "DP-2" { + t.Fatalf("duplicate UUID configs were collapsed to %q / %q, want DP-0 / DP-2", + configs[0].Name, configs[1].Name) + } +} + +// 没有歧义时仍按 UUID 回填 Name,保持原有行为。 +func TestUpdateSysMonitorConfigsNameFillsUniqueUuid(t *testing.T) { + configs := SysMonitorConfigs{ + {UUID: "uuid-1", Name: "", X: 0}, + {UUID: "uuid-2", Name: "", X: 3840}, + } + monitorMap := map[uint32]*Monitor{ + 1: {Name: "DP-0", uuid: "uuid-1"}, + 2: {Name: "DP-2", uuid: "uuid-2"}, + } + + updateSysMonitorConfigsName(configs, monitorMap) + + if configs[0].Name != "DP-0" || configs[1].Name != "DP-2" { + t.Fatalf("unique UUID names = %q / %q, want DP-0 / DP-2", + configs[0].Name, configs[1].Name) + } +} + +func TestUpdateSysMonitorConfigsNameDoesNotGuessDuplicateEmptyName(t *testing.T) { + const uuid = "@DP-3|hash|v1" + configs := SysMonitorConfigs{ + {UUID: uuid, Name: "DP-0"}, + {UUID: uuid, Name: ""}, + } + monitorMap := map[uint32]*Monitor{ + 1: {Name: "DP-2", uuid: uuid}, + 2: {Name: "DP-0", uuid: uuid}, + } + + updateSysMonitorConfigsName(configs, monitorMap) + if configs[0].Name != "DP-0" || configs[1].Name != "" { + t.Fatalf("duplicate UUID names were guessed: %q / %q", configs[0].Name, configs[1].Name) + } +} + +func TestAssignStdNamesOnlyDuplicateResolutionFallsBack(t *testing.T) { + got := assignStdNames([]edidOwner{ + {Name: "DP-0", Connected: true, EDID: bytes.Repeat([]byte{0x01}, 128)}, + {Name: "DP-2", Connected: true, EDID: bytes.Repeat([]byte{0x01}, 128)}, + {Name: "DP-4", Connected: true, EDID: bytes.Repeat([]byte{0x02}, 128)}, + }, []drmConnector{ + {name: "DP-3", edid: bytes.Repeat([]byte{0x01}, 128)}, + {name: "DP-4", edid: bytes.Repeat([]byte{0x02}, 128)}, + }) + + if _, ok := got["DP-0"]; ok { + t.Fatalf("duplicate stdName was retained for DP-0: %+v", got) + } + if _, ok := got["DP-2"]; ok { + t.Fatalf("duplicate stdName was retained for DP-2: %+v", got) + } + if got["DP-4"] != "DP-4" { + t.Fatalf("unique resolved stdName changed: %+v", got) + } +} + +// 标准名判定不得依赖历史:先单屏后热插第二台,与直接双屏冷启动(daemon +// 重启)必须得到完全相同的 UUID,否则热插时保存的布局会在重启后失效。 +func TestUuidsStableAcrossHotplugAndRestart(t *testing.T) { + dir := t.TempDir() + edidX := bytes.Repeat([]byte{0x11}, 128) + edidSys := bytes.Repeat([]byte{0x11}, 256) + writeTestEdid(t, dir, "card1", "DP-3", edidSys) + + // 阶段 1:只接 A,sysfs 只有 DP-3 完成探测,此时 A 独占候选,保留旧 UUID。 + single := testOutputUuids(t, dir, []testOutput{{name: "DP-0", edid: edidX}}) + wantSingle := "@DP-3|" + edidFingerprint(edidX) + "|v1" + if single["DP-0"] != wantSingle { + t.Fatalf("single monitor UUID = %q, want %q", single["DP-0"], wantSingle) + } + + // 阶段 2:热插同型号 B,DP-4 也探测完成。 + writeTestEdid(t, dir, "card1", "DP-4", edidSys) + outputs := []testOutput{{name: "DP-0", edid: edidX}, {name: "DP-2", edid: edidX}} + hot := testOutputUuids(t, dir, outputs) + assertDistinctUuids(t, hot) + + // 阶段 3:daemon 重启后冷启动,同一拓扑必须得到同一组 UUID。 + cold := testOutputUuids(t, dir, outputs) + for name, uuid := range hot { + if cold[name] != uuid { + t.Fatalf("output %s UUID drifted across restart: %q -> %q", name, uuid, cold[name]) + } + } +} + +// 两台同 EDID 输出时,connector EDID 是逐步探测出来的。旧算法会在 +// 同名端口稍后才可读时,把该输出从回退 UUID 改成 @connector UUID,导致同一 +// 拓扑的 UUID 漂移。多输出直接回退后,探测进度不应再影响结果。 +func TestUuidsStableWhileConnectorEdidProbeCompletes(t *testing.T) { + dir := t.TempDir() + edidX := bytes.Repeat([]byte{0x6b}, 128) + edidSys := bytes.Repeat([]byte{0x6b}, 256) + // 先只有 DP-3 的 EDID 可读,DP-4 尚未探测完成。 + writeTestEdid(t, dir, "card0", "DP-3", edidSys) + writeTestEdid(t, dir, "card0", "DP-4", nil) + + outputs := []testOutput{ + {name: "DP-3", edid: edidX}, + {name: "DP-4", edid: edidX}, + } + partial := testOutputUuids(t, dir, outputs) + assertDistinctUuids(t, partial) + + // 探测完成,DP-4 也能读到同一 EDID。 + writeTestEdid(t, dir, "card0", "DP-4", edidSys) + complete := testOutputUuids(t, dir, outputs) + assertDistinctUuids(t, complete) + + for name, uuid := range partial { + if complete[name] != uuid { + t.Fatalf("output %s UUID drifted while connector EDID probe completed: %q -> %q", + name, uuid, complete[name]) + } + } + for name, uuid := range partial { + // 多输出同 EDID 一律回退到 X output 名。 + assertXFallbackUuid(t, name, uuid, edidX) + } +} + +// 多输出同 EDID 时端口归属无法判定,结果不应依赖 connector 的枚举顺序。 +func TestAssignStdNamesMultiOutputIndependentOfConnectorOrder(t *testing.T) { + edid := bytes.Repeat([]byte{0x6c}, 128) + connectors := []drmConnector{ + {name: "DP-1", edid: edid}, + {name: "DP-2", edid: edid}, + {name: "DP-3", edid: edid}, + {name: "DP-4", edid: edid}, + } + reversed := make([]drmConnector, len(connectors)) + for i, connector := range connectors { + reversed[len(connectors)-1-i] = connector + } + + owners := []edidOwner{ + {Name: "DP-0", Connected: true, EDID: edid}, + {Name: "DP-2", Connected: true, EDID: edid}, + } + forward := assignStdNames(owners, connectors) + backward := assignStdNames(owners, reversed) + + if len(forward) != 0 || len(backward) != 0 { + t.Fatalf("multi-output stdNames depend on connector order: %+v vs %+v", forward, backward) + } + for _, owner := range owners { + forwardUuid := getOutputUuid(owner.Name, forward[owner.Name], edid) + backwardUuid := getOutputUuid(owner.Name, backward[owner.Name], edid) + if forwardUuid != backwardUuid { + t.Fatalf("output %s UUID depends on connector order: %q vs %q", + owner.Name, forwardUuid, backwardUuid) + } + } +} + +// 换接不同 EDID 的显示器后,同一 X 输出必须得到新 UUID,不能复用旧标准名。 +func TestUuidsChangeWhenMonitorReplaced(t *testing.T) { + dir := t.TempDir() + edidA := bytes.Repeat([]byte{0xa1}, 128) + edidB := bytes.Repeat([]byte{0xb2}, 128) + writeTestEdid(t, dir, "card1", "DP-3", bytes.Repeat([]byte{0xa1}, 256)) + + before := testOutputUuids(t, dir, []testOutput{{name: "DP-0", edid: edidA}}) + + writeTestEdid(t, dir, "card1", "DP-3", bytes.Repeat([]byte{0xb2}, 256)) + after := testOutputUuids(t, dir, []testOutput{{name: "DP-0", edid: edidB}}) + + if before["DP-0"] == after["DP-0"] { + t.Fatalf("UUID did not change after replacing the monitor: %q", before["DP-0"]) + } + if after["DP-0"] != "@DP-3|"+edidFingerprint(edidB)+"|v1" { + t.Fatalf("unexpected UUID after replacement: %q", after["DP-0"]) + } +} + +func TestAssignStdNamesSameNameDifferentEdidKeepsLegacyUuid(t *testing.T) { + // card0-DP-2 与 card2-DP-2 可以让不同 EDID 的输出都解析为 DP-2。 + // 由于最终 UUID 还含有不同的 EDID 指纹,它们本来就不冲突,不能回退。 + got := assignStdNames([]edidOwner{ + {Name: "DP-0", Connected: true, EDID: bytes.Repeat([]byte{0x01}, 128)}, + {Name: "DP-1", Connected: true, EDID: bytes.Repeat([]byte{0x02}, 128)}, + }, []drmConnector{ + {name: "DP-2", edid: bytes.Repeat([]byte{0x01}, 128)}, + {name: "DP-2", edid: bytes.Repeat([]byte{0x02}, 128)}, + }) + if got["DP-0"] != "DP-2" || got["DP-1"] != "DP-2" { + t.Fatalf("non-conflicting UUID inputs were changed: %+v", got) + } +} + +func TestSetPrimaryByUuidAndNameFallsBackToUuid(t *testing.T) { + cfgs := SysMonitorConfigs{ + {UUID: "uuid-1", Name: "old-name"}, + {UUID: "uuid-2", Name: "other", Primary: true}, + } + cfgs.setPrimaryByUuidAndName("uuid-1", "new-name") + if !cfgs[0].Primary || cfgs[1].Primary { + t.Fatalf("UUID fallback did not preserve exactly one primary: %+v", cfgs) + } +} + +// B1:重复 UUID 且 Name 完全不匹配时,不能无脑取第一条配置。 +func TestGetByUuidAndNameDuplicateUuidAmbiguousReturnsNil(t *testing.T) { + const uuid = "@DP-1|hash|v1" + cfgs := SysMonitorConfigs{ + {UUID: uuid, Name: "DP-0", X: 0}, + {UUID: uuid, Name: "DP-2", X: 3840}, + } + + if cfg := cfgs.getByUuidAndName(uuid, "DP-9"); cfg != nil { + t.Fatalf("getByUuidAndName returned the first duplicate config: %+v", cfg) + } + + // 几何信息本身有歧义时也必须放弃,不能返回任意一条。 + sameGeometry := SysMonitorConfigs{ + {UUID: uuid, Name: "DP-0", X: 0, Y: 0}, + {UUID: uuid, Name: "DP-2", X: 0, Y: 0}, + } + ambiguous := &Monitor{Name: "DP-9", uuid: uuid, X: 0, Y: 0} + if cfg := sameGeometry.getByUuidAndNameWithMonitor(uuid, "DP-9", ambiguous); cfg != nil { + t.Fatalf("ambiguous geometry fallback returned %+v", cfg) + } + + // 几何唯一时可以用作兜底。 + unique := &Monitor{Name: "DP-9", uuid: uuid, X: 3840, Y: 0} + if cfg := cfgs.getByUuidAndNameWithMonitor(uuid, "DP-9", unique); cfg == nil || cfg.Name != "DP-2" { + t.Fatalf("unique geometry fallback returned %+v, want DP-2", cfg) + } +} + +// B1:旧重复 UUID 配置无法唯一匹配时,applySysMonitorConfigs 不得禁用显示器, +// 也不能把同一条配置的坐标写到多台显示器上。 +func TestConfigureMonitorsKeepsAmbiguousDuplicateUuidMonitors(t *testing.T) { + const uuid = "@DP-1|hash|v1" + monitorMap := map[uint32]*Monitor{ + 1: {ID: 1, Name: "DP-0", uuid: uuid, Enabled: true, X: 100, Y: 0, Width: 1920, Height: 1080}, + 2: {ID: 2, Name: "DP-2", uuid: uuid, Enabled: true, X: 2020, Y: 0, Width: 1920, Height: 1080}, + } + configs := SysMonitorConfigs{ + {UUID: uuid, Name: "DP-8", Enabled: true, X: 0, Y: 0, Width: 1920, Height: 1080}, + {UUID: uuid, Name: "DP-9", Enabled: true, X: 1920, Y: 0, Width: 1920, Height: 1080}, + } + + m := &Manager{} + _, enabled := m.configureMonitorsFromConfigs(monitorMap, configs) + if len(enabled) != 2 { + t.Fatalf("enabled monitors = %d, want both retained", len(enabled)) + } + if !monitorMap[1].Enabled || !monitorMap[2].Enabled { + t.Fatalf("ambiguous duplicate uuid config disabled a monitor: %+v", monitorMap) + } + if monitorMap[1].X != 100 || monitorMap[2].X != 2020 { + t.Fatalf("ambiguous duplicate uuid config rewrote coordinates: %d / %d", + monitorMap[1].X, monitorMap[2].X) + } + if monitorMap[1].X == monitorMap[2].X { + t.Fatalf("monitors ended up with identical coordinates: %+v", monitorMap) + } +} + +// B1 兼容性:UUID 唯一时 Name 不匹配仍回退到该 UUID 的唯一配置并正常应用。 +func TestConfigureMonitorsUniqueUuidFallbackStillApplies(t *testing.T) { + monitorMap := map[uint32]*Monitor{ + 1: {ID: 1, Name: "DP-0", uuid: "unique-uuid", Enabled: true, X: 50, Y: 0}, + } + configs := SysMonitorConfigs{ + {UUID: "unique-uuid", Name: "stale-name", Enabled: true, X: 1920, Y: 0}, + } + + m := &Manager{} + _, enabled := m.configureMonitorsFromConfigs(monitorMap, configs) + if len(enabled) != 1 { + t.Fatalf("enabled monitors = %d, want 1", len(enabled)) + } + if got := monitorMap[1].X; got != 1920 { + t.Fatalf("unique UUID fallback was not applied: X = %d, want 1920", got) + } +} + +// 重复 UUID 且 Name 全部过期时,setPrimaryConfig 只能把几何唯一命中的那条 +// 配置设为主屏,不能退化成按 UUID 匹配导致多条 Primary。 +func TestSetPrimaryConfigUsesMatchedPointerOnly(t *testing.T) { + const uuid = "@DP-1|hash|v1" + cfgs := SysMonitorConfigs{ + {UUID: uuid, Name: "DP-8", X: 0, Y: 0, Width: 1920, Height: 1080}, + {UUID: uuid, Name: "DP-9", X: 1920, Y: 0, Width: 1920, Height: 1080}, + } + // 原有主屏是错误的那一条,验证会被清理。 + cfgs[0].Primary = true + + monitor := &Monitor{Name: "DP-2", uuid: uuid, X: 1920, Y: 0, Width: 1920, Height: 1080} + target := cfgs.getByUuidAndNameWithMonitor(uuid, monitor.Name, monitor) + if target == nil { + t.Fatal("geometry disambiguation did not match any config") + } + if target.Name != "DP-9" { + t.Fatalf("matched config = %q, want DP-9", target.Name) + } + + cfgs.setPrimaryConfig(target) + + primaryCount := 0 + var primary *SysMonitorConfig + for _, cfg := range cfgs { + if cfg.Primary { + primaryCount++ + primary = cfg + } + } + if primaryCount != 1 { + t.Fatalf("primary count = %d, want exactly 1: %+v", primaryCount, cfgs) + } + if primary != target { + t.Fatalf("primary config = %+v, want matched %+v", primary, target) + } + + // nil target 不能 panic,也不能改变现有 Primary 状态。 + cfgs.setPrimaryConfig(nil) + if !cfgs[1].Primary || cfgs[0].Primary { + t.Fatalf("setPrimaryConfig(nil) changed primary state: %+v", cfgs) + } +} diff --git a/display1/manager.go b/display1/manager.go index 4e7c98abd..57f665009 100644 --- a/display1/manager.go +++ b/display1/manager.go @@ -848,12 +848,9 @@ func (m *Manager) handleSysConfigUpdated(newSysConfig *SysRootConfig) { // applySysMonitorConfigs 会在内部设置 fillMode logger.Debug("fillModes changed, set fill mode for monitors") monitors := m.getConnectedMonitors() - var primaryScreenFillMode = fillModeDefault - for _, config := range newMonitorCfgs { - if config.Primary { - primaryScreenFillMode = newCfg.FillModes[monitors.GetByName(config.Name).generateFillModeKey()] - break - } + primaryScreenFillMode := fillModeDefault + if key := primaryFillModeKey(monitors, newMonitorCfgs); key != "" { + primaryScreenFillMode = newCfg.FillModes[key] } go func() { @@ -876,6 +873,26 @@ func (m *Manager) handleSysConfigUpdated(newSysConfig *SysRootConfig) { } } +// primaryFillModeKey 返回主显示器对应的填充模式 key。 +// 配置里的 Name 可能为空或已过期,先按 Name 查找,再用 UUID 兜底; +// 两种方式都找不到时跳过该条目,避免解引用 nil monitor。 +func primaryFillModeKey(monitors Monitors, configs SysMonitorConfigs) string { + for _, config := range configs { + if !config.Primary { + continue + } + monitor := monitors.GetByName(config.Name) + if monitor == nil { + monitor = monitors.GetByUuidAndNameOrUuid(config.UUID, config.Name) + } + if monitor == nil { + continue + } + return monitor.generateFillModeKey() + } + return "" +} + // initBuiltinMonitor 初始化内置显示器。 func (m *Manager) initBuiltinMonitor() { if !m.hasBuiltinMonitor { @@ -1710,8 +1727,8 @@ func (m *Manager) getMirrorConfigs(monitorsId monitorsId, monitors Monitors) (co return configs, false, nil } - if config := configs.getByUuid(primaryMonitor.uuid); config != nil && config.Enabled && !config.Primary { - configs.setPrimary(primaryMonitor.uuid) + if config := configs.getByUuidAndNameWithMonitor(primaryMonitor.uuid, primaryMonitor.Name, primaryMonitor); config != nil && config.Enabled && !config.Primary { + configs.setPrimaryConfig(config) return configs, true, nil } return configs, false, nil @@ -1919,7 +1936,12 @@ func (m *Manager) setPrimary(name string) error { // modify configs // TODO 这里为什么需要更新 Name? updateSysMonitorConfigsName(configs, m.monitorMap) - configs.setPrimary(primaryMonitor.uuid) + if config := configs.getByUuidAndNameWithMonitor(primaryMonitor.uuid, primaryMonitor.Name, primaryMonitor); config != nil { + configs.setPrimaryConfig(config) + } else { + // 兼容旧配置:唯一 UUID 的既有行为保持不变。 + configs.setPrimaryByUuidAndName(primaryMonitor.uuid, primaryMonitor.Name) + } } err := m.mm.setMonitorPrimary(primaryMonitor.ID) @@ -2361,7 +2383,7 @@ func (m *Manager) applyChanges() error { configs := m.getSuitableSysMonitorConfigs(m.DisplayMode, monitorsId, monitors) for _, config := range configs { - monitor := monitors.GetByUuid(config.UUID) + monitor := monitors.GetByUuidAndNameOrUuid(config.UUID, config.Name) if monitor == nil { continue } @@ -2425,27 +2447,23 @@ func (m *Manager) cloneMonitorMapNoLock() map[uint32]*Monitor { return result } -func (m *Manager) applySysMonitorConfigs(mode byte, monitorsId monitorsId, monitorMap map[uint32]*Monitor, configs SysMonitorConfigs, options applyOptions) error { - if logger.GetLogLevel() == log.LevelDebug { - logger.Debugf("applySysMonitorConfigs configs: %s, options: %v", spew.Sdump(configs), options) - } - - // 验证配置 - enabledCount := 0 - for _, config := range configs { - if config.Enabled { - enabledCount++ - } - } - if enabledCount == 0 { - return errors.New("invalid configs: no enabled monitor") - } - - var primaryMonitorID uint32 - var enabledMonitors []*Monitor +// configureMonitorsFromConfigs 把屏幕配置写入 monitorMap 中的显示器,返回主屏 +// ID 和使能的显示器列表。重复 UUID 且无法唯一匹配时保留显示器当前状态, +// 避免把同一条配置的坐标套到多台显示器上,也避免禁用物理插着的显示器。 +func (m *Manager) configureMonitorsFromConfigs(monitorMap map[uint32]*Monitor, configs SysMonitorConfigs) (primaryMonitorID uint32, enabledMonitors []*Monitor) { for _, monitor := range monitorMap { - monitorCfg := configs.getByUuid(monitor.uuid) + monitorCfg := configs.getByUuidAndNameWithMonitor(monitor.uuid, monitor.Name, monitor) if monitorCfg == nil { + if configs.countByUuid(monitor.uuid) > 1 { + // 旧配置对同一 UUID 有多条,且 Name/几何都无法唯一确定。 + // 不能把第一条配置的坐标套到多台显示器上,也不能因此禁用 + // 物理插着的显示器:保留当前启用状态和坐标/模式,仅记录警告。 + logger.Warningf("ambiguous duplicate uuid config for monitor %s (%s), keep current state", monitor.Name, monitor.uuid) + if monitor.Enabled { + enabledMonitors = append(enabledMonitors, monitor) + } + continue + } logger.Debug("disable monitor", monitor) monitor.Enabled = false } else { @@ -2474,6 +2492,26 @@ func (m *Manager) applySysMonitorConfigs(mode byte, monitorsId monitorsId, monit } } } + return +} + +func (m *Manager) applySysMonitorConfigs(mode byte, monitorsId monitorsId, monitorMap map[uint32]*Monitor, configs SysMonitorConfigs, options applyOptions) error { + if logger.GetLogLevel() == log.LevelDebug { + logger.Debugf("applySysMonitorConfigs configs: %s, options: %v", spew.Sdump(configs), options) + } + + // 验证配置 + enabledCount := 0 + for _, config := range configs { + if config.Enabled { + enabledCount++ + } + } + if enabledCount == 0 { + return errors.New("invalid configs: no enabled monitor") + } + + primaryMonitorID, enabledMonitors := m.configureMonitorsFromConfigs(monitorMap, configs) if primaryMonitorID == 0 { primaryMonitor := m.getDefaultPrimaryMonitor(enabledMonitors) @@ -2534,7 +2572,7 @@ func (m *Manager) applySysMonitorConfigs(mode byte, monitorsId monitorsId, monit if err != nil { logger.Warningf("call setBrightness err: %v, config.Name: %s", err, config.Name) monitors := m.getConnectedMonitors() - monitor := monitors.GetByUuid(config.UUID) + monitor := monitors.GetByUuidAndNameOrUuid(config.UUID, config.Name) // 插拔过程中存在异常monitor空 if monitor == nil { logger.Warning("call GetByUuid failed: ", config.UUID) @@ -2582,7 +2620,7 @@ func (m *Manager) getInheritedPrimaryMonitor(monitorsId monitorsId, monitors Mon if !config.Primary { continue } - if monitor := monitors.GetByUuid(config.UUID); monitor != nil { + if monitor := monitors.GetByUuidAndNameOrUuid(config.UUID, config.Name); monitor != nil { return monitor } break diff --git a/display1/manager_test.go b/display1/manager_test.go index d9ff08c14..aa4e5da74 100644 --- a/display1/manager_test.go +++ b/display1/manager_test.go @@ -194,6 +194,96 @@ func Test_getMirrorConfigs(t *testing.T) { assert.True(t, configs.getByUuid("uuid-edp").Primary) } +// 重复 UUID 且复制配置 Name 过期时,getMirrorConfigs 必须只把几何命中的 +// 唯一配置设为主屏,不能出现多条 Primary。 +func Test_getMirrorConfigsDuplicateUuidKeepsSinglePrimary(t *testing.T) { + const uuid = "@DP-1|hash|v1" + + dp0 := newMirrorTestMonitor(1, "DP-1", uuid) + dp0.X, dp0.Y, dp0.Width, dp0.Height = 0, 0, 1920, 1080 + dp1 := newMirrorTestMonitor(2, "DP-2", uuid) + dp1.X, dp1.Y, dp1.Width, dp1.Height = 1920, 0, 1920, 1080 + monitors := Monitors{dp0, dp1} + id := monitorsId{v1: uuid + "," + uuid} + + m := newMirrorTestManager() + m.DisplayMode = DisplayModeExtend + m.Primary = "DP-2" + m.sysConfig.Config.Screens[id.v1] = &SysScreenConfig{ + Mirror: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {UUID: uuid, Name: "DP-8", Enabled: true, X: 0, Y: 0, Width: 1920, Height: 1080, Primary: true}, + {UUID: uuid, Name: "DP-9", Enabled: true, X: 1920, Y: 0, Width: 1920, Height: 1080}, + }}, + } + + configs, needSaveCfg, err := m.getMirrorConfigs(id, monitors) + assert.NoError(t, err) + assert.True(t, needSaveCfg) + + primaryCount := 0 + var primary *SysMonitorConfig + for _, cfg := range configs { + if cfg.Primary { + primaryCount++ + primary = cfg + } + } + assert.Equal(t, 1, primaryCount, "duplicate UUID configs produced multiple primaries: %+v", configs) + if assert.NotNil(t, primary) { + assert.Equal(t, "DP-9", primary.Name) + assert.Equal(t, int16(1920), primary.X) + } +} + +// primaryFillModeKey 不能在 Name 为空或过期时解引用 nil monitor。 +func TestPrimaryFillModeKey(t *testing.T) { + monitor := &Monitor{Name: "DP-2", uuid: "uuid-2", Width: 1920, Height: 1080} + monitors := Monitors{monitor} + want := "uuid-2:1920x1080" + + tests := []struct { + name string + configs SysMonitorConfigs + want string + }{ + { + name: "empty name falls back to uuid", + configs: SysMonitorConfigs{{UUID: "uuid-2", Name: "", Primary: true}}, + want: want, + }, + { + name: "stale name falls back to uuid", + configs: SysMonitorConfigs{{UUID: "uuid-2", Name: "DP-9", Primary: true}}, + want: want, + }, + { + name: "stale name and uuid are skipped", + configs: SysMonitorConfigs{{UUID: "stale-uuid", Name: "", Primary: true}}, + want: "", + }, + { + name: "non primary entry is ignored", + configs: SysMonitorConfigs{{UUID: "uuid-2", Name: "DP-2"}}, + want: "", + }, + { + name: "unresolvable primary is skipped", + configs: SysMonitorConfigs{ + {UUID: "stale-uuid", Name: "DP-9", Primary: true}, + {UUID: "uuid-2", Name: "DP-2", Primary: true}, + }, + want: want, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := primaryFillModeKey(monitors, tt.configs); got != tt.want { + t.Fatalf("primaryFillModeKey() = %q, want %q", got, tt.want) + } + }) + } +} + // saveExtendPrimary 模拟"扩展模式主屏":把扩展模式配置里的主屏写成 primaryUuid。 func saveExtendPrimary(m *Manager, id monitorsId, primaryUuid string) { m.sysConfig.Config.Screens[id.v1] = &SysScreenConfig{ diff --git a/display1/migration_test.go b/display1/migration_test.go new file mode 100644 index 000000000..9e2a10587 --- /dev/null +++ b/display1/migration_test.go @@ -0,0 +1,703 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +package display1 + +import ( + "bytes" + "reflect" + "testing" +) + +func newMigrationTestMonitor(name string, edid []byte) *Monitor { + return &Monitor{ + Name: name, + Connected: true, + realConnected: true, + edid: edid, + uuid: getOutputUuid(name, "", edid), + } +} + +func newDuplicateUuidTestConfig() (oldUuid string, monitors Monitors) { + edid := bytes.Repeat([]byte{0x5c}, 128) + monitors = Monitors{ + newMigrationTestMonitor("DP-0", edid), + newMigrationTestMonitor("DP-2", edid), + } + return "@DP-1|" + edidFingerprint(edid) + "|v1", monitors +} + +func TestMigrateDuplicateUuidScreens(t *testing.T) { + oldUuid, monitors := newDuplicateUuidTestConfig() + oldKey := oldUuid + monitorsIdDelimiter + oldUuid + edid := monitors[0].edid + + cfg := &SysConfig{ + DisplayMode: DisplayModeExtend, + Screens: map[string]*SysScreenConfig{ + oldKey: { + Extend: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {UUID: oldUuid, Name: "DP-0", Enabled: true, X: 0, Y: 0, Width: 3840, Height: 2160, RefreshRate: 60, Primary: true}, + {UUID: oldUuid, Name: "DP-2", Enabled: true, X: 3840, Y: 0, Width: 3840, Height: 2160, RefreshRate: 59.94}, + }}, + }, + }, + FillModes: map[string]string{ + oldUuid + fillModeKeyDelimiter + "3840x2160": "16:9", + }, + } + + if changed, _ := cfg.migrateDuplicateUuidScreens(monitors); !changed { + t.Fatal("duplicate uuid screens were not migrated") + } + + wantKey := monitors.getMonitorsId().v1 + screen := cfg.Screens[wantKey] + if screen == nil { + t.Fatalf("config key = %v, want %q", keysOfSysScreens(cfg.Screens), wantKey) + } + if _, ok := cfg.Screens[oldKey]; ok { + t.Fatal("old duplicate uuid key was not removed") + } + monitorsCfgs := screen.Extend.Monitors + if len(monitorsCfgs) != 2 { + t.Fatalf("got %d monitor configs, want 2", len(monitorsCfgs)) + } + wantUUIDs := map[string]string{ + "DP-0": getOutputUuid("DP-0", "", edid), + "DP-2": getOutputUuid("DP-2", "", edid), + } + for _, mc := range monitorsCfgs { + if got := wantUUIDs[mc.Name]; mc.UUID != got { + t.Fatalf("monitor %s UUID = %q, want %q", mc.Name, mc.UUID, got) + } + } + if monitorsCfgs[0].X != 0 || monitorsCfgs[1].X != 3840 { + t.Fatalf("layout was not preserved: %+v", monitorsCfgs) + } + for _, mon := range monitors { + key := mon.uuid + fillModeKeyDelimiter + "3840x2160" + if cfg.FillModes[key] != "16:9" { + t.Fatalf("fill mode %q = %q, want 16:9", key, cfg.FillModes[key]) + } + } + // 旧 key 保留给同 EDID 但当前未接入的显示器,避免以后拿不到填充模式。 + if cfg.FillModes[oldUuid+fillModeKeyDelimiter+"3840x2160"] != "16:9" { + t.Fatalf("legacy fill mode was removed: %v", cfg.FillModes) + } + if len(cfg.FillModes) != 3 { + t.Fatalf("fill modes = %v, want legacy + 2 new entries", cfg.FillModes) + } +} + +func keysOfSysScreens(screens map[string]*SysScreenConfig) []string { + keys := make([]string, 0, len(screens)) + for key := range screens { + keys = append(keys, key) + } + return keys +} + +func TestMigrateDuplicateUuidScreensSkipsAmbiguousGeometry(t *testing.T) { + oldUuid, monitors := newDuplicateUuidTestConfig() + oldKey := oldUuid + monitorsIdDelimiter + oldUuid + cfg := &SysConfig{Screens: map[string]*SysScreenConfig{ + oldKey: {Extend: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {UUID: oldUuid, Name: "DP-9"}, + {UUID: oldUuid, Name: "DP-8"}, + }}}, + }} + + if changed, _ := cfg.migrateDuplicateUuidScreens(monitors); changed { + t.Fatal("screen with ambiguous name and geometry should not be migrated") + } + if cfg.Screens[oldKey] == nil { + t.Fatal("original config was removed after a rejected migration") + } +} + +// Name 被旧逻辑写空/写错时,仍可用唯一的位置和分辨率恢复布局。 +func TestMigrateDuplicateUuidScreensByGeometry(t *testing.T) { + oldUuid, monitors := newDuplicateUuidTestConfig() + monitors[0].X, monitors[0].Y = 0, 0 + monitors[1].X, monitors[1].Y = 3840, 0 + monitors[0].Width, monitors[0].Height = 3840, 2160 + monitors[1].Width, monitors[1].Height = 3840, 2160 + oldKey := oldUuid + monitorsIdDelimiter + oldUuid + cfg := &SysConfig{Screens: map[string]*SysScreenConfig{ + oldKey: {Extend: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {UUID: oldUuid, Name: "", Width: 3840, Height: 2160, X: 0, Y: 0, Primary: true}, + {UUID: oldUuid, Name: "DP-9", Width: 3840, Height: 2160, X: 3840, Y: 0}, + }}}, + }} + + if changed, _ := cfg.migrateDuplicateUuidScreens(monitors); !changed { + t.Fatal("screen with recoverable geometry was not migrated") + } + screen := cfg.Screens[monitors.getMonitorsId().v1] + if screen == nil { + t.Fatal("migrated screen config not found") + } + for _, mc := range screen.Extend.Monitors { + want := monitors[0].uuid + if mc.X == 3840 { + want = monitors[1].uuid + } + if mc.UUID != want { + t.Fatalf("monitor at X=%d got UUID %q, want %q", mc.X, mc.UUID, want) + } + if mc.Name == "" || mc.Name == "DP-9" { + t.Fatalf("monitor at X=%d kept stale name %q", mc.X, mc.Name) + } + } +} + +func TestMigrateDuplicateUuidScreensSkipsCountMismatch(t *testing.T) { + oldUuid, monitors := newDuplicateUuidTestConfig() + // 旧 key 是四屏配置,当前只接了两台:数量不一致,不能猜。 + oldKey := oldUuid + monitorsIdDelimiter + oldUuid + monitorsIdDelimiter + oldUuid + monitorsIdDelimiter + oldUuid + cfg := &SysConfig{Screens: map[string]*SysScreenConfig{ + oldKey: {Extend: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {UUID: oldUuid, Name: "DP-0"}, + {UUID: oldUuid, Name: "DP-2"}, + }}}, + }} + + if changed, _ := cfg.migrateDuplicateUuidScreens(monitors); changed { + t.Fatal("screen with 4 old uuids and 2 current monitors should not be migrated") + } +} + +func TestMigrateDuplicateUuidScreensSkipsUniqueUuids(t *testing.T) { + _, monitors := newDuplicateUuidTestConfig() + edidB := bytes.Repeat([]byte{0x6d}, 128) + other := newMigrationTestMonitor("DP-4", edidB) + cfg := &SysConfig{Screens: map[string]*SysScreenConfig{ + monitors[0].uuid: {Single: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {UUID: monitors[0].uuid, Name: "DP-0"}, + }}}, + other.uuid + monitorsIdDelimiter + monitors[0].uuid: {Extend: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {UUID: other.uuid, Name: "DP-4"}, + {UUID: monitors[0].uuid, Name: "DP-0"}, + }}}, + }} + + if changed, _ := cfg.migrateDuplicateUuidScreens(monitors); changed { + t.Fatal("unique uuid configs must not be migrated") + } +} + +func TestMigrateDuplicateUuidScreensOnlyOne(t *testing.T) { + oldUuid, monitors := newDuplicateUuidTestConfig() + oldKey := oldUuid + monitorsIdDelimiter + oldUuid + primary := &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {UUID: oldUuid, Name: "DP-2", Primary: true}, + }} + cfg := &SysConfig{Screens: map[string]*SysScreenConfig{ + oldKey: { + OnlyOneMap: map[string]*SysMonitorModeConfig{oldUuid: primary}, + OnlyOneUuid: oldUuid, + }, + }} + + if changed, _ := cfg.migrateDuplicateUuidScreens(monitors); !changed { + t.Fatal("OnlyOne config was not migrated") + } + screen := cfg.Screens[monitors.getMonitorsId().v1] + if screen == nil { + t.Fatal("migrated screen config not found") + } + dp2UUID := getOutputUuid("DP-2", "", monitors[0].edid) + if screen.OnlyOneMap[dp2UUID] == nil { + t.Fatalf("OnlyOneMap keys = %v, want %q", keysOfModeConfigs(screen.OnlyOneMap), dp2UUID) + } + if got := screen.OnlyOneMap[dp2UUID].Monitors[0].UUID; got != dp2UUID { + t.Fatalf("OnlyOneMap embedded monitor UUID = %q, want %q", got, dp2UUID) + } + if screen.OnlyOneUuid != dp2UUID { + t.Fatalf("OnlyOneUuid = %q, want %q", screen.OnlyOneUuid, dp2UUID) + } +} + +func keysOfModeConfigs(m map[string]*SysMonitorModeConfig) []string { + keys := make([]string, 0, len(m)) + for key := range m { + keys = append(keys, key) + } + return keys +} + +func TestMigrateDuplicateUuidUserConfig(t *testing.T) { + oldUuid, monitors := newDuplicateUuidTestConfig() + oldKey := oldUuid + monitorsIdDelimiter + oldUuid + userCfg := &UserConfig{Screens: map[string]UserScreenConfig{ + oldKey: { + KeyModeExtend: {ColorTemperatureMode: 1}, + KeyModeOnlyOnePrefix + oldUuid: {ColorTemperatureMode: 2}, + }, + }} + + if changed := userCfg.migrateDuplicateUuidScreens(monitors, nil); !changed { + t.Fatal("user config was not migrated") + } + newKey := monitors.getMonitorsId().v1 + screenCfg := userCfg.Screens[newKey] + if screenCfg == nil { + t.Fatalf("user config key = %v, want %q", keysOfUserScreens(userCfg.Screens), newKey) + } + if _, ok := userCfg.Screens[oldKey]; ok { + t.Fatal("old user config key was not removed") + } + if screenCfg[KeyModeExtend] == nil || screenCfg[KeyModeExtend].ColorTemperatureMode != 1 { + t.Fatalf("Extend color temp config lost: %+v", screenCfg[KeyModeExtend]) + } + // 重复 UUID 无法区分 OnlyOne 的用户设置,复制到该 EDID 组的每台显示器。 + for _, mon := range monitors { + if got := screenCfg[KeyModeOnlyOnePrefix+mon.uuid]; got == nil || got.ColorTemperatureMode != 2 { + t.Fatalf("OnlyOne config for %s lost: %+v", mon.Name, got) + } + } +} + +func keysOfUserScreens(screens map[string]UserScreenConfig) []string { + keys := make([]string, 0, len(screens)) + for key := range screens { + keys = append(keys, key) + } + return keys +} + +// 多个历史 key 映射到同一个新 key 时,应选择与当前实际布局最接近的那条, +// 而不是依赖 map 遍历顺序。 +func TestMigrateDuplicateUuidScreensPicksCurrentLayout(t *testing.T) { + _, monitors := newDuplicateUuidTestConfig() + monitors[0].X, monitors[0].Y = 3840, 0 + monitors[1].X, monitors[1].Y = 0, 0 + fp := edidFingerprint(monitors[0].edid) + currentUuid := "@DP-3|" + fp + "|v1" + historyUuid := "@DP-1|" + fp + "|v1" + + makeScreen := func(uuid string, dp0X, dp2X int16) *SysScreenConfig { + return &SysScreenConfig{Extend: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {UUID: uuid, Name: "DP-0", Enabled: true, X: dp0X, Y: 0}, + {UUID: uuid, Name: "DP-2", Enabled: true, X: dp2X, Y: 0}, + }}} + } + currentKey := currentUuid + monitorsIdDelimiter + currentUuid + historyKey := historyUuid + monitorsIdDelimiter + historyUuid + cfg := &SysConfig{ + DisplayMode: DisplayModeExtend, + Screens: map[string]*SysScreenConfig{ + historyKey: makeScreen(historyUuid, 0, 3840), + currentKey: makeScreen(currentUuid, 3840, 0), + }, + } + + if changed, _ := cfg.migrateDuplicateUuidScreens(monitors); !changed { + t.Fatal("screens were not migrated") + } + newKey := monitors.getMonitorsId().v1 + screen := cfg.Screens[newKey] + if screen == nil { + t.Fatalf("config key = %v, want %q", keysOfSysScreens(cfg.Screens), newKey) + } + // 只有被采用(写入新 key)的 currentKey 才删除;历史 key 未被采用, + // 必须保留以便后续重试/回滚。 + if _, ok := cfg.Screens[currentKey]; ok { + t.Fatal("adopted key with duplicate uuids was not removed") + } + if _, ok := cfg.Screens[historyKey]; !ok { + t.Fatal("historical key was removed even though it was not adopted") + } + byName := map[string]int16{} + for _, mc := range screen.Extend.Monitors { + byName[mc.Name] = mc.X + } + if byName["DP-0"] != 3840 || byName["DP-2"] != 0 { + t.Fatalf("migration did not pick the current layout: %+v", byName) + } +} + +// 当前 key 已存在时,迁移不能覆盖用户正在使用的布局;此时旧 key 也未被采用, +// 必须保留,供迁移重试和回滚,不能删除。 +func TestMigrateDuplicateUuidScreensKeepsExistingKey(t *testing.T) { + oldUuid, monitors := newDuplicateUuidTestConfig() + oldKey := oldUuid + monitorsIdDelimiter + oldUuid + newKey := monitors.getMonitorsId().v1 + existing := &SysScreenConfig{Extend: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {UUID: monitors[0].uuid, Name: "DP-0", X: 100}, + {UUID: monitors[1].uuid, Name: "DP-2", X: 200}, + }}} + cfg := &SysConfig{Screens: map[string]*SysScreenConfig{ + oldKey: {Extend: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {UUID: oldUuid, Name: "DP-0", X: 0}, + {UUID: oldUuid, Name: "DP-2", X: 3840}, + }}}, + newKey: existing, + }} + + // 没有写入任何新 key,迁移不算发生变更。 + if changed, _ := cfg.migrateDuplicateUuidScreens(monitors); changed { + t.Fatal("migration reported a change although nothing was adopted") + } + if got := cfg.Screens[newKey].Extend.Monitors[0].X; got != 100 { + t.Fatalf("existing layout was overwritten: X = %d, want 100", got) + } + if _, ok := cfg.Screens[oldKey]; !ok { + t.Fatal("old duplicate key was removed even though its config was not adopted") + } +} + +// 物理插着但被禁用的显示器(Connected=false,realConnected=true)必须计入 +// 迁移,过滤条件要与调用方 getConnectedMonitors 使用的 realConnected 一致。 +func TestMigrateDuplicateUuidScreensCountsPhysicallyConnected(t *testing.T) { + oldUuid, monitors := newDuplicateUuidTestConfig() + monitors[1].Connected = false // 物理连接,但没有 CRTC(被禁用) + oldKey := oldUuid + monitorsIdDelimiter + oldUuid + cfg := &SysConfig{DisplayMode: DisplayModeExtend, Screens: map[string]*SysScreenConfig{ + oldKey: {Extend: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {UUID: oldUuid, Name: "DP-0", Enabled: true, X: 0}, + {UUID: oldUuid, Name: "DP-2", Enabled: false, X: 3840}, + }}}, + }} + + if changed, _ := cfg.migrateDuplicateUuidScreens(monitors); !changed { + t.Fatal("migration should count physically connected but disabled monitors") + } + newKey := monitors.getMonitorsId().v1 + screen := cfg.Screens[newKey] + if screen == nil { + t.Fatalf("config key = %v, want %q", keysOfSysScreens(cfg.Screens), newKey) + } + if len(screen.Extend.Monitors) != 2 { + t.Fatalf("got %d monitor configs, want 2", len(screen.Extend.Monitors)) + } + if _, ok := cfg.Screens[oldKey]; ok { + t.Fatal("adopted old key was not removed") + } +} + +// 时序回归:第一次迁移因数量不匹配失败,随后 applyModeExtend 把默认布局写进 +// 新 key;第二次迁移虽然成功,但不能覆盖新 key,并且旧 key 必须保留。 +func TestMigrateDuplicateUuidScreensKeepsOldKeyAfterFailedThenDefault(t *testing.T) { + oldUuid, monitors := newDuplicateUuidTestConfig() + oldKey := oldUuid + monitorsIdDelimiter + oldUuid + cfg := &SysConfig{DisplayMode: DisplayModeExtend, Screens: map[string]*SysScreenConfig{ + oldKey: {Extend: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {UUID: oldUuid, Name: "DP-0", X: 0}, + {UUID: oldUuid, Name: "DP-2", X: 3840}, + }}}, + }} + + // 第一次只有一台显示器在线,数量不匹配,迁移被放弃。 + if changed, _ := cfg.migrateDuplicateUuidScreens(monitors[:1]); changed { + t.Fatal("migration with a single monitor should be rejected") + } + if cfg.Screens[oldKey] == nil { + t.Fatal("old key was removed after a rejected migration") + } + + // 模拟 applyModeExtend 把默认布局写到新 key。 + newKey := monitors.getMonitorsId().v1 + cfg.Screens[newKey] = &SysScreenConfig{Extend: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {UUID: monitors[0].uuid, Name: "DP-0", X: 100}, + {UUID: monitors[1].uuid, Name: "DP-2", X: 200}, + }}} + + // 第二次两台都就绪,迁移可以成功,但新 key 已存在,不能采用。 + if changed, _ := cfg.migrateDuplicateUuidScreens(monitors); changed { + t.Fatal("migration reported a change although the new key already existed") + } + if cfg.Screens[oldKey] == nil { + t.Fatal("old key was removed although the migration result was not adopted") + } + if got := cfg.Screens[newKey].Extend.Monitors[0].X; got != 100 { + t.Fatalf("default layout was overwritten: X = %d, want 100", got) + } +} + +// UserConfig 版本:新 key 已存在时同样不能删旧 key。 +func TestMigrateDuplicateUuidUserConfigKeepsExistingKey(t *testing.T) { + oldUuid, monitors := newDuplicateUuidTestConfig() + oldKey := oldUuid + monitorsIdDelimiter + oldUuid + newKey := monitors.getMonitorsId().v1 + userCfg := &UserConfig{Screens: map[string]UserScreenConfig{ + oldKey: { + KeyModeExtend: {ColorTemperatureMode: 1}, + }, + newKey: { + KeyModeExtend: {ColorTemperatureMode: 5}, + }, + }} + + if changed := userCfg.migrateDuplicateUuidScreens(monitors, nil); changed { + t.Fatal("migration reported a change although the new key already existed") + } + if userCfg.Screens[oldKey] == nil { + t.Fatal("old user config key was removed although it was not adopted") + } + if got := userCfg.Screens[newKey][KeyModeExtend].ColorTemperatureMode; got != 5 { + t.Fatalf("existing user config was overwritten: ColorTemperatureMode = %d, want 5", got) + } +} + +// 打分只看当前显示模式:历史 key 即使多带一个 Mirror 快照,也不能因此 +// 压过与当前 Extend 布局一致的那条。 +func TestScoreDuplicateUuidCandidateUsesCurrentMode(t *testing.T) { + _, monitors := newDuplicateUuidTestConfig() + monitors[0].X, monitors[0].Y = 0, 0 + monitors[1].X, monitors[1].Y = 3840, 0 + byName := map[string]*Monitor{"DP-0": monitors[0], "DP-2": monitors[1]} + + current := &SysScreenConfig{Extend: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {Name: "DP-0", X: 0, Y: 0}, + {Name: "DP-2", X: 3840, Y: 0}, + }}} + historical := &SysScreenConfig{ + Extend: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {Name: "DP-0", X: 0, Y: 2160}, + {Name: "DP-2", X: 0, Y: 0}, + }}, + Mirror: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {Name: "DP-0", X: 0, Y: 0}, + {Name: "DP-2", X: 3840, Y: 0}, + }}, + } + if got, want := scoreDuplicateUuidCandidate(current, byName, DisplayModeExtend), + scoreDuplicateUuidCandidate(historical, byName, DisplayModeExtend); got <= want { + t.Fatalf("current Extend score %d should beat historical %d", got, want) + } +} + +// OnlyOne 的 Name 为空时也应能通过唯一几何位置恢复,并写回 Name。 +func TestMigrateDuplicateUuidScreensOnlyOneByGeometry(t *testing.T) { + oldUuid, monitors := newDuplicateUuidTestConfig() + monitors[0].X, monitors[0].Y = 0, 0 + monitors[1].X, monitors[1].Y = 3840, 0 + oldKey := oldUuid + monitorsIdDelimiter + oldUuid + cfg := &SysConfig{Screens: map[string]*SysScreenConfig{ + oldKey: { + OnlyOneMap: map[string]*SysMonitorModeConfig{oldUuid: {Monitors: SysMonitorConfigs{ + {UUID: oldUuid, Name: "", X: 3840, Y: 0}, + }}}, + OnlyOneUuid: oldUuid, + }, + }} + + if changed, _ := cfg.migrateDuplicateUuidScreens(monitors); !changed { + t.Fatal("OnlyOne config was not migrated") + } + screen := cfg.Screens[monitors.getMonitorsId().v1] + if screen == nil { + t.Fatal("migrated screen not found") + } + dp2Uuid := monitors[1].uuid + entry := screen.OnlyOneMap[dp2Uuid] + if entry == nil { + t.Fatalf("OnlyOneMap keys = %v, want %q", keysOfModeConfigs(screen.OnlyOneMap), dp2Uuid) + } + if entry.Monitors[0].Name != "DP-2" { + t.Fatalf("OnlyOne entry name = %q, want DP-2", entry.Monitors[0].Name) + } + if screen.OnlyOneUuid != dp2Uuid { + t.Fatalf("OnlyOneUuid = %q, want %q", screen.OnlyOneUuid, dp2Uuid) + } +} + +// B2:OnlyOneUuid 指向的 OnlyOneMap 条目不存在时,不能迁移整条 screen key, +// 否则 OnlyOne 选择会静默丢失并回退到默认主屏。 +func TestMigrateDuplicateUuidScreensRejectsMissingOnlyOneEntry(t *testing.T) { + oldUuid, monitors := newDuplicateUuidTestConfig() + oldKey := oldUuid + monitorsIdDelimiter + oldUuid + cfg := &SysConfig{Screens: map[string]*SysScreenConfig{ + oldKey: { + OnlyOneMap: map[string]*SysMonitorModeConfig{ + oldUuid: {Monitors: SysMonitorConfigs{ + {UUID: oldUuid, Name: "DP-2", Primary: true}, + }}, + }, + OnlyOneUuid: "@DP-9|" + edidFingerprint(monitors[0].edid) + "|v1", + }, + }} + + if changed, _ := cfg.migrateDuplicateUuidScreens(monitors); changed { + t.Fatal("screen with an OnlyOneUuid missing from OnlyOneMap should not be migrated") + } + if cfg.Screens[oldKey] == nil { + t.Fatal("original config was removed after a rejected migration") + } +} + +// B2:OnlyOneUuid 对应的条目无法映射到当前显示器时同样不能迁移。 +func TestMigrateDuplicateUuidScreensRejectsUnmappableOnlyOneEntry(t *testing.T) { + oldUuid, monitors := newDuplicateUuidTestConfig() + oldKey := oldUuid + monitorsIdDelimiter + oldUuid + cfg := &SysConfig{Screens: map[string]*SysScreenConfig{ + oldKey: { + OnlyOneMap: map[string]*SysMonitorModeConfig{ + oldUuid: {Monitors: SysMonitorConfigs{ + {UUID: oldUuid, Name: "DP-9", X: 1234, Y: 5678}, + }}, + }, + OnlyOneUuid: oldUuid, + }, + }} + + if changed, _ := cfg.migrateDuplicateUuidScreens(monitors); changed { + t.Fatal("screen with an unmappable OnlyOneUuid should not be migrated") + } + if cfg.Screens[oldKey] == nil { + t.Fatal("original config was removed after a rejected migration") + } +} + +// B2:打分必须使用 OnlyOneUuid 选中的条目,而不是 map 的随机第一条; +// OnlyOneUuid 失效时才按排序后的第一个有效条目兜底。 +func TestScoreDuplicateUuidCandidateOnlyOneUsesSelectedEntry(t *testing.T) { + _, monitors := newDuplicateUuidTestConfig() + monitors[0].X = 100 + byName := map[string]*Monitor{"DP-0": monitors[0], "DP-2": monitors[1]} + + screenCfg := &SysScreenConfig{OnlyOneMap: map[string]*SysMonitorModeConfig{ + "uuid-a": {Monitors: SysMonitorConfigs{{UUID: "uuid-a", Name: "DP-0", X: 999}}}, + "uuid-z": {Monitors: SysMonitorConfigs{{UUID: "uuid-z", Name: "DP-0", X: 100}}}, + }, OnlyOneUuid: "uuid-z"} + + selected := scoreDuplicateUuidCandidate(screenCfg, byName, DisplayModeOnlyOne) + if want := scoreDuplicateUuidCandidate(&SysScreenConfig{OnlyOneMap: map[string]*SysMonitorModeConfig{ + "uuid-z": screenCfg.OnlyOneMap["uuid-z"], + }}, byName, DisplayModeOnlyOne); selected != want { + t.Fatalf("OnlyOne score = %d, want selected entry score %d", selected, want) + } + if got := scoreDuplicateUuidCandidate(&SysScreenConfig{OnlyOneMap: screenCfg.OnlyOneMap}, byName, DisplayModeOnlyOne); got != scoreDuplicateUuidCandidate(&SysScreenConfig{OnlyOneMap: map[string]*SysMonitorModeConfig{ + "uuid-a": screenCfg.OnlyOneMap["uuid-a"], + }}, byName, DisplayModeOnlyOne) { + t.Fatal("missing OnlyOneUuid should fall back to the sorted first entry") + } + if selected <= scoreDuplicateUuidCandidate(&SysScreenConfig{OnlyOneMap: map[string]*SysMonitorModeConfig{ + "uuid-a": screenCfg.OnlyOneMap["uuid-a"], + }}, byName, DisplayModeOnlyOne) { + t.Fatal("selected OnlyOne entry was not scored as the expected one") + } +} + +// B2:UserConfig 中 OnlyOne- 的 uuid 无法映射时必须保留原条目。 +func TestMigrateDuplicateUuidUserConfigKeepsUnmappableOnlyOne(t *testing.T) { + oldUuid, monitors := newDuplicateUuidTestConfig() + oldKey := oldUuid + monitorsIdDelimiter + oldUuid + const missingUuid = "@DP-9|missing|v1" + userCfg := &UserConfig{Screens: map[string]UserScreenConfig{ + oldKey: { + KeyModeExtend: {ColorTemperatureMode: 1}, + KeyModeOnlyOnePrefix + missingUuid: {ColorTemperatureMode: 2}, + }, + }} + + if changed := userCfg.migrateDuplicateUuidScreens(monitors, nil); !changed { + t.Fatal("user config was not migrated") + } + newKey := monitors.getMonitorsId().v1 + screenCfg := userCfg.Screens[newKey] + if screenCfg == nil { + t.Fatalf("user config key = %v, want %q", keysOfUserScreens(userCfg.Screens), newKey) + } + if got := screenCfg[KeyModeOnlyOnePrefix+missingUuid]; got == nil || got.ColorTemperatureMode != 2 { + t.Fatalf("unmappable OnlyOne user config was dropped: %+v", screenCfg) + } +} + +// B3:多个历史 key 竞争同一新 key 时,UserConfig 应跟随 SysConfig 选中的 +// 旧 key,而不是按字典序取第一条。 +func TestMigrateDuplicateUuidUserConfigFollowsSysConfigWinner(t *testing.T) { + _, monitors := newDuplicateUuidTestConfig() + monitors[0].X, monitors[0].Y = 0, 0 + monitors[1].X, monitors[1].Y = 3840, 0 + fp := edidFingerprint(monitors[0].edid) + firstUuid := "@DP-0|" + fp + "|v1" // 字典序在前 + secondUuid := "@DP-3|" + fp + "|v1" // 字典序在后 + firstKey := firstUuid + monitorsIdDelimiter + firstUuid + secondKey := secondUuid + monitorsIdDelimiter + secondUuid + newKey := monitors.getMonitorsId().v1 + + makeScreen := func(uuid string, dp0X, dp2X int16) *SysScreenConfig { + return &SysScreenConfig{Extend: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {UUID: uuid, Name: "DP-0", Enabled: true, X: dp0X, Y: 0}, + {UUID: uuid, Name: "DP-2", Enabled: true, X: dp2X, Y: 0}, + }}} + } + sysCfg := &SysConfig{ + DisplayMode: DisplayModeExtend, + Screens: map[string]*SysScreenConfig{ + firstKey: makeScreen(firstUuid, 999, 999), + secondKey: makeScreen(secondUuid, 0, 3840), + }, + } + changed, preferred := sysCfg.migrateDuplicateUuidScreens(monitors) + if !changed { + t.Fatal("sys config was not migrated") + } + if preferred[secondKey] != newKey { + t.Fatalf("sys preferred mapping = %v, want %q -> %q", preferred, secondKey, newKey) + } + if _, ok := preferred[firstKey]; ok { + t.Fatalf("sys config should not prefer the lexicographically first key: %v", preferred) + } + + userCfg := &UserConfig{Screens: map[string]UserScreenConfig{ + firstKey: {KeyModeExtend: {ColorTemperatureMode: 1}}, + secondKey: {KeyModeExtend: {ColorTemperatureMode: 2}}, + }} + if changed := userCfg.migrateDuplicateUuidScreens(monitors, preferred); !changed { + t.Fatal("user config was not migrated") + } + if got := userCfg.Screens[newKey][KeyModeExtend].ColorTemperatureMode; got != 2 { + t.Fatalf("user config followed the wrong historical key: ColorTemperatureMode = %d, want 2", got) + } + if _, ok := userCfg.Screens[firstKey]; !ok { + t.Fatal("non-preferred historical key should be kept for retry") + } +} + +// B5:旧重复 UUID key 需要两台同指纹显示器,但当前只接一台且该显示器仍保留 +// 这个 UUID 时,migrateDuplicateUuidScreens + updateUuid 都不能删除旧 key、 +// 生成含重复 UUID 的新 key 或改写配置内容。 +func TestUpdateUuidKeepsLegacyDuplicateKeyWithSingleMonitor(t *testing.T) { + edid := bytes.Repeat([]byte{0x5c}, 128) + oldUuid := "@DP-1|" + edidFingerprint(edid) + "|v1" + monitor := newMigrationTestMonitor("DP-1", edid) + monitor.uuid = oldUuid + monitor.uuidV0 = "v0-" + oldUuid + monitors := Monitors{monitor} + + oldKey := oldUuid + monitorsIdDelimiter + oldUuid + cfg := &SysConfig{DisplayMode: DisplayModeExtend, Screens: map[string]*SysScreenConfig{ + oldKey: {Extend: &SysMonitorModeConfig{Monitors: SysMonitorConfigs{ + {UUID: oldUuid, Name: "DP-1", Enabled: true, X: 0, Y: 0, Width: 1920, Height: 1080, Primary: true}, + {UUID: oldUuid, Name: "DP-2", Enabled: true, X: 1920, Y: 0, Width: 1920, Height: 1080}, + }}}, + }} + before := cfg.Screens[oldKey].clone() + + if changed, _ := cfg.migrateDuplicateUuidScreens(monitors); changed { + t.Fatal("migration should be rejected when only one of the two monitors is connected") + } + if changed := cfg.updateUuid(monitors); changed { + t.Fatal("updateUuid should not rewrite a legacy duplicate key that still matches the single monitor") + } + if cfg.Screens[oldKey] == nil { + t.Fatal("old duplicate uuid key was removed") + } + if len(cfg.Screens) != 1 { + t.Fatalf("a new screen key was generated: %v", keysOfSysScreens(cfg.Screens)) + } + for key := range cfg.Screens { + if key != oldKey { + t.Fatalf("unexpected screen key %q, want only %q", key, oldKey) + } + } + if !reflect.DeepEqual(before, cfg.Screens[oldKey]) { + t.Fatalf("config content was rewritten:\nbefore: %+v\nafter: %+v", before, cfg.Screens[oldKey]) + } +} diff --git a/display1/monitor.go b/display1/monitor.go index 5636f6958..9c1ef8ad6 100644 --- a/display1/monitor.go +++ b/display1/monitor.go @@ -557,6 +557,18 @@ func (monitors Monitors) GetByUuidAndName(uuid, name string) *Monitor { return nil } +// GetByUuidAndNameOrUuid 优先用 UUID + Name 查找显示器。 +// 多台同型号显示器的 EDID 可能完全相同而共享 UUID,此时必须用 Name 区分; +// Name 不匹配时回退到 UUID,保留旧配置的兼容行为。 +func (monitors Monitors) GetByUuidAndNameOrUuid(uuid, name string) *Monitor { + if name != "" { + if monitor := monitors.GetByUuidAndName(uuid, name); monitor != nil { + return monitor + } + } + return monitors.GetByUuid(uuid) +} + const fillModeKeyDelimiter = ":" func (m *Monitor) generateFillModeKey() string { diff --git a/display1/stdname_property_test.go b/display1/stdname_property_test.go new file mode 100644 index 000000000..29dba4b94 --- /dev/null +++ b/display1/stdname_property_test.go @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +package display1 + +import ( + "bytes" + "fmt" + "math/rand" + "testing" +) + +// 随机属性检查:任意拓扑下(1)同 EDID 输出不得共享 UUID;(2)判定结果与 +// X 输出枚举顺序、sysfs 目录枚举顺序无关;(3)只有一台显示器时不得因多个 +// connector 报同一 EDID 而丢掉 @connector 形态的旧 UUID。 +// +// 注意:这里刻意不加入 connector 乱序维度。listSysDrmConnectors 使用 +// os.ReadDir,生产前提是返回有序结果;单屏且同指纹只有一台输出时仍取第一个 +// 候选,是刻意保留的旧行为兼容(见 +// TestUuidsSingleMonitorExactConnectorNotFirstKeepsLegacyUuid),打乱 connector +// 顺序会让这个兼容行为本身失去意义。多输出同指纹场景的直接回退与顺序无关, +// 另见 TestAssignStdNamesMultiOutputIndependentOfConnectorOrder。 +func TestAssignStdNamesRandomizedTopologyProperties(t *testing.T) { + rng := rand.New(rand.NewSource(20261201)) + for iter := 0; iter < 400; iter++ { + // EDID 组:同组 = 同型号显示器 + groups := rng.Intn(4) + var edids [][]byte + for g := 0; g <= groups; g++ { + b := byte(g + 1) + edids = append(edids, bytes.Repeat([]byte{b}, 128)) + } + + nOutputs := 1 + rng.Intn(5) + outputs := make([]testOutput, 0, nOutputs) + for i := 0; i < nOutputs; i++ { + outputs = append(outputs, testOutput{ + name: fmt.Sprintf("DP-%d", i), + edid: edids[rng.Intn(len(edids))], + }) + } + + dir := t.TempDir() + nConn := 1 + rng.Intn(6) + for i := 0; i < nConn; i++ { + ed := edids[rng.Intn(len(edids))] + // 一半 connector 用与 X 输出同名的端口,模拟本形态 + name := fmt.Sprintf("DP-%d", rng.Intn(8)) + writeTestEdid(t, dir, fmt.Sprintf("card%d", rng.Intn(2)), name, append(append([]byte{}, ed...), ed...)) + } + + uuids := testOutputUuids(t, dir, outputs) + seen := map[string]string{} + for name, uuid := range uuids { + if other, ok := seen[uuid]; ok { + t.Fatalf("iter %d: outputs %s and %s share UUID %s", iter, other, name, uuid) + } + seen[uuid] = name + } + + // 顺序无关:打乱 owners 顺序后 UUID 必须一致。 + shuffled := make([]testOutput, len(outputs)) + copy(shuffled, outputs) + rng.Shuffle(len(shuffled), func(i, j int) { shuffled[i], shuffled[j] = shuffled[j], shuffled[i] }) + for name, uuid := range testOutputUuids(t, dir, shuffled) { + if uuids[name] != uuid { + t.Fatalf("iter %d: output %s UUID depends on enumeration order: %s vs %s", + iter, name, uuids[name], uuid) + } + } + + // 单屏:只要有 connector 匹配其 EDID,就必须保留 @connector UUID。 + if len(outputs) == 1 { + single := outputs[0] + matched := matchConnectorNames(listSysDrmConnectors(dir), single.edid) + if len(matched) > 0 && !bytes.HasPrefix([]byte(uuids[single.name]), []byte("@")) { + t.Fatalf("iter %d: single monitor lost legacy @ UUID: %s (candidates %v)", + iter, uuids[single.name], matched) + } + } + } +} diff --git a/display1/util.go b/display1/util.go index c08ee3e91..ddbe979a0 100644 --- a/display1/util.go +++ b/display1/util.go @@ -7,7 +7,6 @@ package display1 import ( "bytes" "encoding/json" - "errors" "math" "os" "path/filepath" @@ -216,12 +215,18 @@ func parseEdid(edid []byte) (string, string) { return string(maInf), string(moInf) } -func getOutputUuid(name, stdName string, edid []byte) string { +// edidFingerprint 返回用于识别显示器的 EDID 指纹,与 getOutputUuid 中的哈希保持一致。 +// 只有前 128 字节参与计算:既兼容既有配置,也避免扩展块差异改变已有 UUID。 +func edidFingerprint(edid []byte) string { if len(edid) < 128 { - return name + "||v1" + return "" } - id, _ := utils.SumStrMd5(string(edid[:128])) + return id +} + +func getOutputUuid(name, stdName string, edid []byte) string { + id := edidFingerprint(edid) if id == "" { return name + "||v1" } @@ -400,26 +405,65 @@ func hasRate(rates []float64, rate float64) bool { var regCardOutput = regexp.MustCompile(`^card\d+-.+`) -func getStdMonitorName(edid []byte) (string, error) { +const sysDrmDir = "/sys/class/drm" + +// drmConnector 是 /sys/class/drm 下一个已经报告 EDID 的 connector。 +type drmConnector struct { + // name 是 connector 名,例如 card1-DP-3 中的 DP-3。 + name string + edid []byte +} + +// listSysDrmConnectors 读取 dir 下所有 connector 的 EDID,目录参数便于测试。 +// +// 每轮显示器刷新只调用一次:标准名的歧义判定依赖当前所有 connector 的状态, +// 不能跨轮缓存判定结论,否则同一拓扑在热插和 daemon 重启后会得到不同 UUID。 +func listSysDrmConnectors(dir string) []drmConnector { // /sys/class/drm/card0-HDMI-A-1 - fileInfos, err := os.ReadDir("/sys/class/drm") + fileInfos, err := os.ReadDir(dir) if err != nil { - return "", err + logger.Warningf("read %s failed: %v", dir, err) + return nil } + + var connectors []drmConnector for _, info := range fileInfos { name := info.Name() - if regCardOutput.MatchString(name) { - nameParts := strings.SplitN(name, "-", 2) - if len(nameParts) == 2 { - outputName := nameParts[1] - sysEdid, _ := readSysDrmEdid(name) - if outputName != "" && len(sysEdid) > 0 && edidEqual(edid, sysEdid) { - return outputName, nil - } - } + if !regCardOutput.MatchString(name) { + continue + } + + nameParts := strings.SplitN(name, "-", 2) + if len(nameParts) != 2 || nameParts[1] == "" { + continue + } + + sysEdid, err := readSysDrmEdid(dir, name) + if err != nil || len(sysEdid) == 0 { + continue + } + connectors = append(connectors, drmConnector{name: nameParts[1], edid: sysEdid}) + } + return connectors +} + +// matchConnectorNames 返回 EDID 匹配的 connector 名,保持目录枚举顺序, +// 与旧实现“取第一个匹配项”的偏好一致。跨显卡的同名 connector 只保留一次: +// 它们对应的标准名相同,不应被当成两个不同的候选。 +func matchConnectorNames(connectors []drmConnector, edid []byte) []string { + var names []string + seen := make(map[string]struct{}) + for _, connector := range connectors { + if _, ok := seen[connector.name]; ok { + continue + } + if !edidEqual(edid, connector.edid) { + continue } + seen[connector.name] = struct{}{} + names = append(names, connector.name) } - return "", errors.New("can not get std name") + return names } func edidEqual(edid1, edid2 []byte) bool { @@ -434,7 +478,7 @@ func edidEqual(edid1, edid2 []byte) bool { return false } -func readSysDrmEdid(name string) ([]byte, error) { - content, err := os.ReadFile(filepath.Join("/sys/class/drm", name, "edid")) +func readSysDrmEdid(dir, name string) ([]byte, error) { + content, err := os.ReadFile(filepath.Join(dir, name, "edid")) return content, err } diff --git a/display1/xorg.go b/display1/xorg.go index ebcb37a77..1c7b37233 100644 --- a/display1/xorg.go +++ b/display1/xorg.go @@ -159,8 +159,6 @@ type xMonitorManager struct { outputs map[randr.Output]*OutputInfo primary randr.Output monitorChangedCbEnabled bool - // 键是 x 的 output 名称,值是标准名。 - stdNamesCache map[string]string } func newXMonitorManager(xConn *x.Conn, hasRandr1d2 bool) *xMonitorManager { @@ -169,7 +167,6 @@ func newXMonitorManager(xConn *x.Conn, hasRandr1d2 bool) *xMonitorManager { hasRandr1d2: hasRandr1d2, crtcs: make(map[randr.Crtc]*CrtcInfo), outputs: make(map[randr.Output]*OutputInfo), - stdNamesCache: make(map[string]string), monitorChangedCbEnabled: true, } err := xmm.init() @@ -428,24 +425,73 @@ func toMonitorInfoMap(monitors []*MonitorInfo) map[uint32]*MonitorInfo { return result } -func (mm *xMonitorManager) getStdMonitorName(name string, edid []byte) (string, error) { - // NOTE:不要加锁 - stdName := mm.stdNamesCache[name] - if stdName != "" { - return stdName, nil +// edidOwner 是 assignStdNames 的输入,只保留判定标准名歧义所需的字段。 +type edidOwner struct { + Name string + Connected bool + EDID []byte +} + +// assignStdNames 为一批已连接的显示器决定 stdName。 +// +// 判定只依赖本轮传入的 X 输出和 DRM connector 列表,不缓存结论:connector 的 +// EDID 是逐步探测出来的,缓存上一轮的判定会让同一拓扑在热插和 daemon 重启后 +// 得到不同的 UUID,从而使已保存的布局失效。 +// +// 选择规则: +// 1. 同一 EDID 指纹只有一台已连接 X 输出时,直接取第一个匹配的 connector, +// 与旧实现完全一致,避免健康机器升级后 UUID 改变、存量布局丢失;没有 +// 匹配的 connector 时 stdName 为空,回退到 X output 名。 +// 2. 同一 EDID 指纹有多台输出时,无法判断每台显示器物理上接在哪个 connector, +// 全部直接回退到 X output 名,不分配 stdName。 +// +// 第 2 条之所以整体回退,而不是逐个做候选匹配:同一指纹组的 X 输出前 128 字节 +// EDID 相同,各输出匹配到的 connector 候选列表因此相同;旧算法即便偏好与 X +// output 同名的 connector,最终也必然让这些输出共享 (stdName, EDID 指纹) 而全部 +// 落到回退分支。提前直接回退与原结果等价,却不再依赖 connector 的探测进度和 +// 枚举顺序,同一拓扑的 UUID 因而保持稳定。组大小变化来自真实热插,属于固有行为。 +// +// 返回 map[X 输出名]标准名;值为空表示回退到 X 输出名。 +func assignStdNames(infos []edidOwner, connectors []drmConnector) map[string]string { + fingerprintOwners := make(map[string]int, len(infos)) + for _, info := range infos { + if !info.Connected || len(info.EDID) < 128 { + continue + } + fingerprintOwners[edidFingerprint(info.EDID)]++ } - stdName, err := getStdMonitorName(edid) - if err != nil { - return "", err + stdNames := make(map[string]string, len(infos)) + for _, info := range infos { + if !info.Connected || len(info.EDID) < 128 { + continue + } + + fingerprint := edidFingerprint(info.EDID) + if fingerprintOwners[fingerprint] > 1 { + logger.Debugf("monitor %v: EDID shared by %d X outputs, use X output name", + info.Name, fingerprintOwners[fingerprint]) + continue + } + + candidates := matchConnectorNames(connectors, info.EDID) + if len(candidates) == 0 { + logger.Debugf("monitor %v: no drm connector matches its EDID, use X output name", info.Name) + continue + } + // 同指纹只有一台 X 输出时不存在 UUID 冲突,保持旧实现取首候选, + // 否则健康机器升级后 UUID 会改变、存量布局丢失。 + stdNames[info.Name] = candidates[0] } - mm.stdNamesCache[name] = stdName - return stdName, nil + return stdNames } func (mm *xMonitorManager) refreshMonitorsCache() { // NOTE: 不要加锁 monitors := make([]*MonitorInfo, 0, len(mm.outputs)) + + // 第一遍:读取所有输出的 EDID。标准名的歧义判定必须等 EDID 全部读完 + // 后再统一进行,见 assignStdNames。 for outputId, outputInfo := range mm.outputs { monitor := &MonitorInfo{ crtc: outputInfo.Crtc, @@ -463,21 +509,31 @@ func (mm *xMonitorManager) refreshMonitorsCache() { logger.Warningf("get output %d edid failed: %v", outputId, err) } - stdName := "" - if monitor.Connected { - stdName, err = mm.getStdMonitorName(monitor.Name, monitor.EDID) - if err != nil { - logger.Warningf("get monitor %v std name failed: %v", monitor.Name, err) - } - } + monitors = append(monitors, monitor) + } + + // 多个输出被解析到同一个标准名时,相关输出回退到 X 输出名, + // 保证每台显示器的 UUID 各不相同。connector 列表每轮重新读取, + // 保证判定只取决于当前拓扑。 + owners := make([]edidOwner, 0, len(monitors)) + for _, monitor := range monitors { + owners = append(owners, edidOwner{ + Name: monitor.Name, + Connected: monitor.Connected, + EDID: monitor.EDID, + }) + } + stdNames := assignStdNames(owners, listSysDrmConnectors(sysDrmDir)) - monitor.UUID = getOutputUuid(monitor.Name, stdName, monitor.EDID) + // 第二遍:填充 UUID 及其他依赖 EDID 的字段。 + for _, monitor := range monitors { + monitor.UUID = getOutputUuid(monitor.Name, stdNames[monitor.Name], monitor.EDID) monitor.UuidV0 = getOutputUuidV0(monitor.Name, monitor.EDID) monitor.Manufacturer, monitor.Model = parseEdid(monitor.EDID) - availFillModes, err := mm.getOutputAvailableFillModes(outputId) + availFillModes, err := mm.getOutputAvailableFillModes(monitor.outputId()) if err != nil { - logger.Warningf("get output %d available fill modes failed: %v", outputId, err) + logger.Warningf("get output %d available fill modes failed: %v", monitor.outputId(), err) } monitor.AvailableFillModes = availFillModes @@ -503,8 +559,6 @@ func (mm *xMonitorManager) refreshMonitorsCache() { monitor.VirtualConnected = false monitor.Enabled = false } - - monitors = append(monitors, monitor) } mm.monitorsCache = monitors