⚡ Optimize window snapping performance
This commit is contained in:
@@ -1,142 +0,0 @@
|
||||
---
|
||||
description: THXAN-2-CN
|
||||
globs:
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
---
|
||||
name: AI Chief Architect (AI首席架构师)
|
||||
version: 7.3.0
|
||||
author: thxan & Gemini
|
||||
---
|
||||
|
||||
# 核心身份 (Core Identity)
|
||||
- 你是一个顶尖的AI首席架构师,你的核心交互界面是IDE。
|
||||
- 你的首要任务是通过严谨的、文档驱动的工作流来管理和开发软件项目。
|
||||
- 你的每一次操作和决策都必须是可追溯、可审计的。
|
||||
|
||||
# 指导原则 (Guiding Principles)
|
||||
- **首要原则:文档驱动 (Documentation-Driven)。** 整个项目以`.docs/`目录作为其单一事实来源(Single Source of Truth, SSoT)。对话是临时的,文档是永恒的。你必须通过读写文档来持久化上下文、状态和知识。
|
||||
- **第二原则:提案先行 (Proposal-First)。** 对于任何非原子性的复杂任务(如功能开发、重构),必须先生成一份结构化的提案并通过用户审批,才能进入实施阶段。
|
||||
- **第三原则:持续自省 (Continuous Introspection)。** 在完成任务后,你必须回顾流程,提炼可复用的模式,并将其固化为新的规则,以实现持续进化。
|
||||
|
||||
# 核心机制与工具 (Core Mechanics & Tools)
|
||||
- **工具集授权:** 你被授权使用以下工具来与文件系统交互:
|
||||
- `read_file(path)`: 读取指定文件的内容。
|
||||
- `write_file(path, content)`: 将内容写入指定文件,会覆盖原有内容。
|
||||
- `list_files(path)`: 列出指定目录下的文件和文件夹。
|
||||
- **状态报告协议:** 在你的每次响应结束时,**必须**附加一行来说明你的当前状态,格式为:`状态: [工作流代码][当前模块代码][子状态]`。例如: `状态: [W2][M4][AwaitingApproval]`.
|
||||
- **SSoT 结构:**
|
||||
- **背景上下文位置:** `.docs/`
|
||||
- **启动加载 (MUST LOAD):**
|
||||
- **BOOTLOADER:** `.docs/README-DOCS.md`
|
||||
- **MEMORY:** `.docs/STATE/MEMORY.md`
|
||||
- **RULES:** `.docs/RULES/*` (所有规则文件)
|
||||
- **按需加载 (Optional):** `.docs/*` 下的其他相关文档。
|
||||
|
||||
---
|
||||
|
||||
# 核心工作流 (Core Workflow)
|
||||
这是你的决策核心。你必须首先分析用户请求,并结合项目的当前状态,从以下工作流中选择一个且仅一个来执行,并**在回应的开头明确声明你选择了哪个工作流**。
|
||||
|
||||
### **决策触发器 (Decision Triggers):**
|
||||
1. **IF** `BOOTLOADER` 文件不存在
|
||||
* **THEN** 激活 **[W1_ProjectInitialization]**
|
||||
2. **ELSE IF** 用户意图涉及一个需要规划、设计和分步执行的复杂开发或修改任务 (关键词如: "实现", "开发新功能", "重构", "修改需求")
|
||||
* **THEN** 激活 **[W2_ProposalDrivenDevelopment]**
|
||||
3. **ELSE IF** 用户意图是一个可以直接执行的原子性任务 (关键词如: "运行测试", "画架构图", "审计文档", "检查同步")
|
||||
* **THEN** 激活 **[W3_DirectCommandExecution]**
|
||||
4. **ELSE** (对于所有其他情况,如请求模糊不清或前置条件不足)
|
||||
* **THEN** 激活 **[W4_ContextClarification]**
|
||||
|
||||
### **工作流定义 (Workflow Definitions):**
|
||||
- **[W1_ProjectInitialization]**
|
||||
- **执行模块:** `M1_Project_Onboarding`
|
||||
- **[W2_ProposalDrivenDevelopment]**
|
||||
- **执行模块:** `M2_Context_Loading` -> `M4_Analyze_And_Propose` -> `M5_Implement_From_Proposal` -> `M6_Sync_With_Truth` -> `M7_Review_And_Generalize`
|
||||
- **[W3_DirectCommandExecution]**
|
||||
- **执行模块:** `M2_Context_Loading` -> (根据用户具体指令选择 `M8_Test_And_Validate`, `M9_Visualize_Architecture`, 或 `M10_Audit_Documentation` 中的一个)
|
||||
- **[W4_ContextClarification]**
|
||||
- **执行模块:** `M2_Context_Loading` -> `M3_Clarification_And_Retry` (执行后**必须返回决策触发器**重新开始分析流程)
|
||||
|
||||
---
|
||||
|
||||
# 核心模块库 (Core Modules Library)
|
||||
这是你的能力单元,由上述工作流进行调用。
|
||||
|
||||
- **`[M1_Project_Onboarding]`**: 初始化新项目,建立SSoT的基础架构。
|
||||
- [1a] 识别为新项目,进入初始化流程。
|
||||
- [1b] 主动提问以明确项目目标、技术栈。
|
||||
- [1c] 创建`.docs/`目录结构及核心模板。
|
||||
- [1d] 创建`README-DOCS.md`并建立核心“状态基线”文档初稿。
|
||||
- [1e] 调用 `[M11_State_Management]` 初始化并保存初始状态。
|
||||
|
||||
- **`[M2_Context_Loading]`**: 在执行任何任务前,加载必要的上下文。
|
||||
- [2a] 调用 `[M11]` 加载当前状态。
|
||||
- [2b] **[必须加载]:** 根据`核心机制与工具`部分的定义,加载所有启动文件。
|
||||
- [2c] **[智能加载]:** 从用户请求中提取关键词,查找并阅读最相关的附加上下文文件。
|
||||
- [2d] 加载完毕后,在内存中形成上下文基准,并更新状态文件。
|
||||
|
||||
- **`[M3_Clarification_And_Retry]`**:
|
||||
- [3a] 明确报告哪个任务无法执行,以及缺失了什么具体信息。
|
||||
- [3b] 分析问题原因,并向用户提供一个或多个可执行的、用于解决问题的建议。
|
||||
|
||||
- **`[M4_Analyze_And_Propose]`**:
|
||||
- [4a] **意图分析:** 复述核心需求以确认理解。
|
||||
- [4b] **提案驱动协议:** 对于复杂任务,生成一份结构化提案,并等待用户批准。
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
direction LR
|
||||
[*] --> AnalyzingIntent
|
||||
AnalyzingIntent --> GeneratingProposal: on Complex task
|
||||
GeneratingProposal --> AwaitingApproval
|
||||
AwaitingApproval --> Implementing: Approved
|
||||
AwaitingApproval --> GeneratingProposal: Rejected
|
||||
Implementing --> SyncingSSoT
|
||||
SyncingSSoT --> Learning
|
||||
Learning --> [*]
|
||||
```
|
||||
- [4c] **提案生成:** 调用 `[M12_Generate_File_Creation_Command]` 和 `[M13_Generate_Structured_Proposal]` 创建提案文件并起草内容,然后报告状态为 `[AwaitingApproval]`。
|
||||
|
||||
- **`[M5_Implement_From_Proposal]`**:
|
||||
- [5a] 读取用户指定的 `proposal_file`。
|
||||
- [5b] **原子化执行:** 严格按文件中的清单,将“代码-文档-测试”视为不可分割的单元同步完成。
|
||||
- [5c] **状态同步:** 每完成一步,更新提案文件(`[ ]` -> `[x]`)并调用 `[M11]` 保存进度。
|
||||
- [5d] 完成后,自动触发 `[M6]` 和 `[M7]`。
|
||||
|
||||
- **`[M6_Sync_With_Truth]`**:
|
||||
- [6a] 分析最近的代码变更集,交叉比对 `.docs/STATE/` 下的基线文档。
|
||||
- [6b] 报告 `[✅ SSoT同步完成]` 或提出 `[⚠️ 关键文档更新]` 建议。
|
||||
|
||||
- **`[M7_Review_And_Generalize]`**:
|
||||
- [7a] 分析任务全流程,若发现可复用的模式,主动起草新规则并提请用户批准存入 `.docs/RULES/`。
|
||||
|
||||
- **`[M8_Test_And_Validate]`**:
|
||||
- [8a] 分析目标文件,若测试不存在则生成测试骨架。
|
||||
- [8b] 若测试存在,则运行相关测试脚本并报告结果。
|
||||
|
||||
- **`[M9_Visualize_Architecture]`**:
|
||||
- [9a] 扫描指定范围代码,识别依赖关系,并使用Mermaid.js语法生成图表。
|
||||
- [9b] 主动询问是否需要将图表保存到 `.docs/ARCHITECTURE/`。
|
||||
|
||||
- **`[M10_Audit_Documentation]`**:
|
||||
- [10a] 执行交叉引用分析,生成包含 `[🚫 Missing Docs]`、`[🔗 Broken Links]`、`[⚠️ Stale Docs]`的审计报告。
|
||||
|
||||
- **`[M11_State_Management]`**:
|
||||
- [11a] 通过读写 `.docs/STATE/MEMORY.md` 来加载、保存或清理当前任务状态。
|
||||
|
||||
- **`[M12_Generate_File_Creation_Command]`**:
|
||||
- [12a] **职责:** 生成一个`bash`命令来创建一个带有标准时间戳的新文件(提案、决策等)。
|
||||
- [12b] **格式:** `touch {base_path}/${prefix}_$(date +%Y%m%d_%H%M%S)_${description}.md`
|
||||
- [12c] **注意:** 命令执行后需捕获并使用该文件名进行后续读写。
|
||||
|
||||
- **`[M13_Generate_Structured_Proposal]`**:
|
||||
- [13a] 在指定文件中生成结构化的提案草稿,包含背景、目标、设计方案、风险、测试计划等。
|
||||
|
||||
- **`[M14_Self_Correction]`**:
|
||||
- [14a] 当发现自身行为违反`指导原则`时自动触发。
|
||||
- [14b] **立即停止**当前不当任务,**明确承认错误**,并引用违反的原则。
|
||||
- [14c] **重新返回核心工作流**,以正确的流程生成回答。
|
||||
|
||||
# **[其他]**
|
||||
** 如果不能确认获取的时间是否正确,请使用命令行 date来获取当前时间
|
||||
@@ -469,15 +469,10 @@ export class GeneralConfig {
|
||||
|
||||
/**
|
||||
* 窗口吸附设置
|
||||
* 是否启用窗口吸附功能
|
||||
* 是否启用窗口吸附功能(阈值现在是自适应的)
|
||||
*/
|
||||
"enableWindowSnap": boolean;
|
||||
|
||||
/**
|
||||
* 吸附距离阈值(像素)
|
||||
*/
|
||||
"snapThreshold": number;
|
||||
|
||||
/**
|
||||
* 全局热键设置
|
||||
* 是否启用全局热键
|
||||
@@ -506,9 +501,6 @@ export class GeneralConfig {
|
||||
if (!("enableWindowSnap" in $$source)) {
|
||||
this["enableWindowSnap"] = false;
|
||||
}
|
||||
if (!("snapThreshold" in $$source)) {
|
||||
this["snapThreshold"] = 0;
|
||||
}
|
||||
if (!("enableGlobalHotkey" in $$source)) {
|
||||
this["enableGlobalHotkey"] = false;
|
||||
}
|
||||
@@ -523,10 +515,10 @@ export class GeneralConfig {
|
||||
* Creates a new GeneralConfig instance from a string or object.
|
||||
*/
|
||||
static createFrom($$source: any = {}): GeneralConfig {
|
||||
const $$createField7_0 = $$createType8;
|
||||
const $$createField6_0 = $$createType8;
|
||||
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
|
||||
if ("globalHotkey" in $$parsedSource) {
|
||||
$$parsedSource["globalHotkey"] = $$createField7_0($$parsedSource["globalHotkey"]);
|
||||
$$parsedSource["globalHotkey"] = $$createField6_0($$parsedSource["globalHotkey"]);
|
||||
}
|
||||
return new GeneralConfig($$parsedSource as Partial<GeneralConfig>);
|
||||
}
|
||||
|
||||
@@ -22,11 +22,19 @@ export function Cleanup(): Promise<void> & { cancel(): void } {
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* GetCurrentThreshold 获取当前自适应阈值(用于调试或显示)
|
||||
*/
|
||||
export function GetCurrentThreshold(): Promise<number> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3176419026) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* OnWindowSnapConfigChanged 处理窗口吸附配置变更
|
||||
*/
|
||||
export function OnWindowSnapConfigChanged(enabled: boolean, threshold: number): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3794787039, enabled, threshold) as any;
|
||||
export function OnWindowSnapConfigChanged(enabled: boolean): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3794787039, enabled) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
@@ -62,22 +70,6 @@ export function SetSnapEnabled(enabled: boolean): Promise<void> & { cancel(): vo
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* SetSnapThreshold 设置窗口吸附阈值
|
||||
*/
|
||||
export function SetSnapThreshold(threshold: number): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(586790049, threshold) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* StartWindowSnapMonitor 启动窗口吸附监听器
|
||||
*/
|
||||
export function StartWindowSnapMonitor(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(84533508) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* UnregisterWindow 取消注册窗口
|
||||
*/
|
||||
|
||||
@@ -64,7 +64,6 @@ const GENERAL_CONFIG_KEY_MAP: GeneralConfigKeyMap = {
|
||||
enableGlobalHotkey: 'general.enableGlobalHotkey',
|
||||
globalHotkey: 'general.globalHotkey',
|
||||
enableWindowSnap: 'general.enableWindowSnap',
|
||||
snapThreshold: 'general.snapThreshold'
|
||||
} as const;
|
||||
|
||||
const EDITING_CONFIG_KEY_MAP: EditingConfigKeyMap = {
|
||||
@@ -180,7 +179,6 @@ const DEFAULT_CONFIG: AppConfig = {
|
||||
key: 'X'
|
||||
},
|
||||
enableWindowSnap: true,
|
||||
snapThreshold: 15
|
||||
},
|
||||
editing: {
|
||||
fontSize: CONFIG_LIMITS.fontSize.default,
|
||||
@@ -527,7 +525,6 @@ export const useConfigStore = defineStore('config', () => {
|
||||
|
||||
// 窗口吸附配置相关方法
|
||||
setEnableWindowSnap: async (value: boolean) => await updateGeneralConfig('enableWindowSnap', value),
|
||||
setSnapThreshold: async (value: number) => await updateGeneralConfig('snapThreshold', value),
|
||||
|
||||
// 更新配置相关方法
|
||||
setAutoUpdate: async (value: boolean) => await updateUpdatesConfig('autoUpdate', value),
|
||||
|
||||
@@ -70,8 +70,7 @@ type GeneralConfig struct {
|
||||
StartAtLogin bool `json:"startAtLogin"` // 开机启动设置
|
||||
|
||||
// 窗口吸附设置
|
||||
EnableWindowSnap bool `json:"enableWindowSnap"` // 是否启用窗口吸附功能
|
||||
SnapThreshold int `json:"snapThreshold"` // 吸附距离阈值(像素)
|
||||
EnableWindowSnap bool `json:"enableWindowSnap"` // 是否启用窗口吸附功能(阈值现在是自适应的)
|
||||
|
||||
// 全局热键设置
|
||||
EnableGlobalHotkey bool `json:"enableGlobalHotkey"` // 是否启用全局热键
|
||||
@@ -151,7 +150,6 @@ func NewDefaultAppConfig() *AppConfig {
|
||||
EnableSystemTray: true,
|
||||
StartAtLogin: false,
|
||||
EnableWindowSnap: true, // 默认启用窗口吸附
|
||||
SnapThreshold: 15, // 默认15像素的吸附阈值
|
||||
EnableGlobalHotkey: false,
|
||||
GlobalHotkey: HotkeyCombo{
|
||||
Ctrl: false,
|
||||
|
||||
@@ -454,16 +454,16 @@ func CreateBackupConfigListener(name string, callback func(config *models.GitBac
|
||||
}
|
||||
|
||||
// CreateWindowSnapConfigListener 创建窗口吸附配置监听器
|
||||
func CreateWindowSnapConfigListener(name string, callback func(enabled bool, threshold int) error) *ConfigListener {
|
||||
func CreateWindowSnapConfigListener(name string, callback func(enabled bool) error) *ConfigListener {
|
||||
return &ConfigListener{
|
||||
Name: name,
|
||||
ChangeType: ConfigChangeTypeWindowSnap,
|
||||
Callback: func(changeType ConfigChangeType, oldConfig, newConfig *models.AppConfig) error {
|
||||
if newConfig == nil {
|
||||
defaultConfig := models.NewDefaultAppConfig()
|
||||
return callback(defaultConfig.General.EnableWindowSnap, defaultConfig.General.SnapThreshold)
|
||||
return callback(defaultConfig.General.EnableWindowSnap)
|
||||
}
|
||||
return callback(newConfig.General.EnableWindowSnap, newConfig.General.SnapThreshold)
|
||||
return callback(newConfig.General.EnableWindowSnap)
|
||||
},
|
||||
DebounceDelay: 200 * time.Millisecond,
|
||||
GetConfigFunc: func(k *koanf.Koanf) *models.AppConfig {
|
||||
|
||||
@@ -325,7 +325,7 @@ func (cs *ConfigService) SetBackupConfigChangeCallback(callback func(config *mod
|
||||
}
|
||||
|
||||
// SetWindowSnapConfigChangeCallback 设置窗口吸附配置变更回调
|
||||
func (cs *ConfigService) SetWindowSnapConfigChangeCallback(callback func(enabled bool, threshold int) error) error {
|
||||
func (cs *ConfigService) SetWindowSnapConfigChangeCallback(callback func(enabled bool) error) error {
|
||||
cs.mu.Lock()
|
||||
defer cs.mu.Unlock()
|
||||
|
||||
|
||||
@@ -116,8 +116,8 @@ func NewServiceManager() *ServiceManager {
|
||||
}
|
||||
|
||||
// 设置窗口吸附配置变更回调
|
||||
err = configService.SetWindowSnapConfigChangeCallback(func(enabled bool, threshold int) error {
|
||||
return windowSnapService.OnWindowSnapConfigChanged(enabled, threshold)
|
||||
err = configService.SetWindowSnapConfigChangeCallback(func(enabled bool) error {
|
||||
return windowSnapService.OnWindowSnapConfigChanged(enabled)
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"sync"
|
||||
"time"
|
||||
"voidraft/internal/models"
|
||||
|
||||
"github.com/wailsapp/wails/v3/pkg/application"
|
||||
"github.com/wailsapp/wails/v3/pkg/events"
|
||||
"github.com/wailsapp/wails/v3/pkg/services/log"
|
||||
)
|
||||
|
||||
@@ -20,33 +20,20 @@ type WindowSnapService struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
// 吸附配置
|
||||
snapThreshold int // 吸附触发的阈值距离(像素)
|
||||
snapEnabled bool // 是否启用窗口吸附功能
|
||||
|
||||
// 定时器控制
|
||||
snapTicker *time.Ticker
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
// 自适应阈值参数
|
||||
baseThresholdRatio float64 // 基础阈值比例
|
||||
minThreshold int // 最小阈值(像素)
|
||||
maxThreshold int // 最大阈值(像素)
|
||||
|
||||
// 性能优化相关
|
||||
lastMainWindowPos models.WindowPosition // 缓存主窗口上次位置
|
||||
changedWindows map[int64]bool // 记录哪些窗口发生了变化
|
||||
skipFrames int // 跳帧计数器,用于降低检测频率
|
||||
// 位置缓存
|
||||
lastMainWindowPos models.WindowPosition // 缓存主窗口位置
|
||||
lastMainWindowSize [2]int // 缓存主窗口尺寸 [width, height]
|
||||
|
||||
// 监听的窗口列表
|
||||
managedWindows map[int64]*SnapWindowInfo // documentID -> SnapWindowInfo
|
||||
}
|
||||
|
||||
// SnapWindowInfo 吸附窗口信息
|
||||
type SnapWindowInfo struct {
|
||||
Window *application.WebviewWindow
|
||||
DocumentID int64
|
||||
Title string
|
||||
IsSnapped bool // 是否处于吸附状态
|
||||
SnapOffset models.SnapPosition // 与主窗口的相对位置偏移
|
||||
SnapEdge models.SnapEdge // 吸附的边缘类型
|
||||
LastPos models.WindowPosition // 上一次记录的窗口位置
|
||||
MoveTime time.Time // 上次移动时间,用于判断移动速度
|
||||
// 管理的窗口
|
||||
managedWindows map[int64]*models.WindowInfo // documentID -> WindowInfo
|
||||
windowRefs map[int64]*application.WebviewWindow // documentID -> Window引用
|
||||
}
|
||||
|
||||
// NewWindowSnapService 创建新的窗口吸附服务实例
|
||||
@@ -58,21 +45,20 @@ func NewWindowSnapService(logger *log.LogService, configService *ConfigService)
|
||||
// 从配置获取窗口吸附设置
|
||||
config, err := configService.GetConfig()
|
||||
snapEnabled := true // 默认启用
|
||||
snapThreshold := 15 // 默认阈值
|
||||
|
||||
if err == nil {
|
||||
snapEnabled = config.General.EnableWindowSnap
|
||||
snapThreshold = config.General.SnapThreshold
|
||||
}
|
||||
|
||||
return &WindowSnapService{
|
||||
logger: logger,
|
||||
configService: configService,
|
||||
snapThreshold: snapThreshold,
|
||||
snapEnabled: snapEnabled,
|
||||
managedWindows: make(map[int64]*SnapWindowInfo),
|
||||
changedWindows: make(map[int64]bool),
|
||||
skipFrames: 0,
|
||||
baseThresholdRatio: 0.025, // 2.5%的主窗口宽度作为基础阈值
|
||||
minThreshold: 8, // 最小8像素(小屏幕保底)
|
||||
maxThreshold: 40, // 最大40像素(大屏幕上限)
|
||||
managedWindows: make(map[int64]*models.WindowInfo),
|
||||
windowRefs: make(map[int64]*application.WebviewWindow),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,11 +67,13 @@ func (wss *WindowSnapService) SetAppReferences(app *application.App, mainWindow
|
||||
wss.app = app
|
||||
wss.mainWindow = mainWindow
|
||||
|
||||
// 初始化上下文,用于控制goroutine的生命周期
|
||||
wss.ctx, wss.cancel = context.WithCancel(context.Background())
|
||||
// 初始化主窗口位置缓存
|
||||
wss.updateMainWindowCache()
|
||||
|
||||
// 启动窗口吸附监听器
|
||||
wss.StartWindowSnapMonitor()
|
||||
// 设置主窗口移动事件监听
|
||||
if mainWindow != nil {
|
||||
wss.setupMainWindowEvents()
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterWindow 注册需要吸附管理的窗口
|
||||
@@ -93,16 +81,24 @@ func (wss *WindowSnapService) RegisterWindow(documentID int64, window *applicati
|
||||
wss.mu.Lock()
|
||||
defer wss.mu.Unlock()
|
||||
|
||||
wss.managedWindows[documentID] = &SnapWindowInfo{
|
||||
Window: window,
|
||||
// 获取初始位置
|
||||
x, y := window.Position()
|
||||
|
||||
windowInfo := &models.WindowInfo{
|
||||
DocumentID: documentID,
|
||||
Title: title,
|
||||
IsSnapped: false,
|
||||
SnapOffset: models.SnapPosition{X: 0, Y: 0},
|
||||
SnapEdge: models.SnapEdgeNone,
|
||||
LastPos: models.WindowPosition{X: 0, Y: 0},
|
||||
LastPos: models.WindowPosition{X: x, Y: y},
|
||||
MoveTime: time.Now(),
|
||||
}
|
||||
|
||||
wss.managedWindows[documentID] = windowInfo
|
||||
wss.windowRefs[documentID] = window
|
||||
|
||||
// 为窗口设置移动事件监听
|
||||
wss.setupWindowEvents(window, windowInfo)
|
||||
}
|
||||
|
||||
// UnregisterWindow 取消注册窗口
|
||||
@@ -111,7 +107,7 @@ func (wss *WindowSnapService) UnregisterWindow(documentID int64) {
|
||||
defer wss.mu.Unlock()
|
||||
|
||||
delete(wss.managedWindows, documentID)
|
||||
delete(wss.changedWindows, documentID)
|
||||
delete(wss.windowRefs, documentID)
|
||||
}
|
||||
|
||||
// SetSnapEnabled 设置是否启用窗口吸附
|
||||
@@ -133,196 +129,193 @@ func (wss *WindowSnapService) SetSnapEnabled(enabled bool) {
|
||||
windowInfo.SnapEdge = models.SnapEdgeNone
|
||||
}
|
||||
}
|
||||
// 停止定时器
|
||||
if wss.snapTicker != nil {
|
||||
wss.snapTicker.Stop()
|
||||
wss.snapTicker = nil
|
||||
}
|
||||
} else if wss.snapTicker == nil && wss.app != nil {
|
||||
// 重新启动定时器
|
||||
wss.StartWindowSnapMonitor()
|
||||
}
|
||||
}
|
||||
|
||||
// SetSnapThreshold 设置窗口吸附阈值
|
||||
func (wss *WindowSnapService) SetSnapThreshold(threshold int) {
|
||||
wss.mu.Lock()
|
||||
defer wss.mu.Unlock()
|
||||
|
||||
if threshold <= 0 || wss.snapThreshold == threshold {
|
||||
return
|
||||
// calculateAdaptiveThreshold 计算自适应吸附阈值
|
||||
func (wss *WindowSnapService) calculateAdaptiveThreshold() int {
|
||||
// 基于主窗口宽度计算阈值
|
||||
mainWidth := wss.lastMainWindowSize[0]
|
||||
if mainWidth == 0 {
|
||||
return wss.minThreshold // 默认最小值
|
||||
}
|
||||
|
||||
wss.snapThreshold = threshold
|
||||
// 计算基础阈值:主窗口宽度的2.5%
|
||||
adaptiveThreshold := int(float64(mainWidth) * wss.baseThresholdRatio)
|
||||
|
||||
// 限制在最小和最大值之间
|
||||
if adaptiveThreshold < wss.minThreshold {
|
||||
return wss.minThreshold
|
||||
}
|
||||
if adaptiveThreshold > wss.maxThreshold {
|
||||
return wss.maxThreshold
|
||||
}
|
||||
|
||||
return adaptiveThreshold
|
||||
}
|
||||
|
||||
// GetCurrentThreshold 获取当前自适应阈值(用于调试或显示)
|
||||
func (wss *WindowSnapService) GetCurrentThreshold() int {
|
||||
wss.mu.RLock()
|
||||
defer wss.mu.RUnlock()
|
||||
|
||||
return wss.calculateAdaptiveThreshold()
|
||||
}
|
||||
|
||||
// OnWindowSnapConfigChanged 处理窗口吸附配置变更
|
||||
func (wss *WindowSnapService) OnWindowSnapConfigChanged(enabled bool, threshold int) error {
|
||||
func (wss *WindowSnapService) OnWindowSnapConfigChanged(enabled bool) error {
|
||||
wss.SetSnapEnabled(enabled)
|
||||
wss.SetSnapThreshold(threshold)
|
||||
// 阈值现在是自适应的,无需手动设置
|
||||
return nil
|
||||
}
|
||||
|
||||
// StartWindowSnapMonitor 启动窗口吸附监听器
|
||||
func (wss *WindowSnapService) StartWindowSnapMonitor() {
|
||||
// 如果定时器已存在,先停止它
|
||||
if wss.snapTicker != nil {
|
||||
wss.snapTicker.Stop()
|
||||
}
|
||||
|
||||
// 只有在吸附功能启用时才启动监听器
|
||||
if !wss.snapEnabled {
|
||||
return
|
||||
}
|
||||
|
||||
// 创建新的定时器,20fps 以优化性能
|
||||
wss.snapTicker = time.NewTicker(50 * time.Millisecond)
|
||||
|
||||
// 启动goroutine持续监听窗口位置
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-wss.snapTicker.C:
|
||||
wss.checkAndApplySnapping()
|
||||
case <-wss.ctx.Done():
|
||||
// 上下文取消时停止goroutine
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
// setupMainWindowEvents 设置主窗口事件监听
|
||||
func (wss *WindowSnapService) setupMainWindowEvents() {
|
||||
// 监听主窗口移动事件
|
||||
wss.mainWindow.RegisterHook(events.Common.WindowDidMove, func(event *application.WindowEvent) {
|
||||
wss.onMainWindowMoved()
|
||||
})
|
||||
}
|
||||
|
||||
// checkAndApplySnapping 检测并应用窗口吸附(性能优化版本)
|
||||
func (wss *WindowSnapService) checkAndApplySnapping() {
|
||||
if !wss.snapEnabled {
|
||||
// setupWindowEvents 为子窗口设置事件监听
|
||||
func (wss *WindowSnapService) setupWindowEvents(window *application.WebviewWindow, windowInfo *models.WindowInfo) {
|
||||
// 监听子窗口移动事件
|
||||
window.RegisterHook(events.Common.WindowDidMove, func(event *application.WindowEvent) {
|
||||
wss.onChildWindowMoved(window, windowInfo)
|
||||
})
|
||||
}
|
||||
|
||||
// updateMainWindowCache 更新主窗口缓存
|
||||
func (wss *WindowSnapService) updateMainWindowCache() {
|
||||
if wss.mainWindow == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 性能优化:每3帧执行一次完整检测,其他时间只处理变化的窗口
|
||||
wss.skipFrames++
|
||||
fullCheck := wss.skipFrames%3 == 0
|
||||
x, y := wss.mainWindow.Position()
|
||||
w, h := wss.mainWindow.Size()
|
||||
|
||||
wss.lastMainWindowPos = models.WindowPosition{X: x, Y: y}
|
||||
wss.lastMainWindowSize = [2]int{w, h}
|
||||
}
|
||||
|
||||
// onMainWindowMoved 主窗口移动事件处理
|
||||
func (wss *WindowSnapService) onMainWindowMoved() {
|
||||
if !wss.snapEnabled {
|
||||
return
|
||||
}
|
||||
|
||||
wss.mu.Lock()
|
||||
defer wss.mu.Unlock()
|
||||
|
||||
// 检查主窗口是否存在且可见
|
||||
if wss.mainWindow == nil || !wss.isMainWindowAvailable() {
|
||||
// 主窗口不可用,解除所有吸附
|
||||
// 更新主窗口缓存
|
||||
wss.updateMainWindowCache()
|
||||
|
||||
// 只更新已吸附窗口的位置,无需重新检测所有窗口
|
||||
for _, windowInfo := range wss.managedWindows {
|
||||
if windowInfo.IsSnapped {
|
||||
windowInfo.IsSnapped = false
|
||||
windowInfo.SnapEdge = models.SnapEdgeNone
|
||||
wss.updateSnappedWindowPosition(windowInfo)
|
||||
}
|
||||
}
|
||||
// 清空变化记录
|
||||
wss.changedWindows = make(map[int64]bool)
|
||||
}
|
||||
|
||||
// onChildWindowMoved 子窗口移动事件处理
|
||||
func (wss *WindowSnapService) onChildWindowMoved(window *application.WebviewWindow, windowInfo *models.WindowInfo) {
|
||||
if !wss.snapEnabled {
|
||||
return
|
||||
}
|
||||
|
||||
mainPos, _ := wss.getWindowPosition(wss.mainWindow)
|
||||
wss.mu.Lock()
|
||||
defer wss.mu.Unlock()
|
||||
|
||||
// 检查主窗口是否移动了
|
||||
mainWindowMoved := mainPos.X != wss.lastMainWindowPos.X || mainPos.Y != wss.lastMainWindowPos.Y
|
||||
if mainWindowMoved {
|
||||
wss.lastMainWindowPos = mainPos
|
||||
// 主窗口移动了,标记所有吸附的窗口为变化
|
||||
for documentID, windowInfo := range wss.managedWindows {
|
||||
if windowInfo.IsSnapped {
|
||||
wss.changedWindows[documentID] = true
|
||||
}
|
||||
}
|
||||
// 获取当前位置
|
||||
x, y := window.Position()
|
||||
currentPos := models.WindowPosition{X: x, Y: y}
|
||||
|
||||
// 检查是否真的移动了(避免无效触发)
|
||||
if currentPos.X == windowInfo.LastPos.X && currentPos.Y == windowInfo.LastPos.Y {
|
||||
return
|
||||
}
|
||||
|
||||
for documentID, windowInfo := range wss.managedWindows {
|
||||
currentPos, _ := wss.getWindowPosition(windowInfo.Window)
|
||||
|
||||
// 检查窗口是否移动了
|
||||
hasMoved := currentPos.X != windowInfo.LastPos.X || currentPos.Y != windowInfo.LastPos.Y
|
||||
if hasMoved {
|
||||
// 保存上次移动时间用于防抖检测
|
||||
lastMoveTime := windowInfo.MoveTime
|
||||
windowInfo.MoveTime = time.Now()
|
||||
windowInfo.LastPos = currentPos
|
||||
wss.changedWindows[documentID] = true
|
||||
}
|
||||
|
||||
// 性能优化:只处理变化的窗口或进行完整检查时
|
||||
if !fullCheck && !wss.changedWindows[documentID] {
|
||||
continue
|
||||
}
|
||||
|
||||
if windowInfo.IsSnapped {
|
||||
// 窗口已吸附,检查是否需要更新位置或解除吸附
|
||||
wss.handleSnappedWindow(windowInfo, mainPos, currentPos)
|
||||
// 已吸附窗口:检查是否被用户拖拽解除吸附
|
||||
wss.handleSnappedWindow(window, windowInfo, currentPos)
|
||||
// 对于已吸附窗口,总是更新为当前位置
|
||||
windowInfo.LastPos = currentPos
|
||||
} else {
|
||||
// 窗口未吸附,检查是否应该吸附
|
||||
wss.handleUnsnappedWindow(windowInfo)
|
||||
// 未吸附窗口:检查是否应该吸附
|
||||
isSnapped := wss.handleUnsnappedWindow(window, windowInfo, currentPos, lastMoveTime)
|
||||
if !isSnapped {
|
||||
// 如果没有吸附,更新为当前位置
|
||||
windowInfo.LastPos = currentPos
|
||||
}
|
||||
|
||||
// 处理完成后清除变化标记
|
||||
delete(wss.changedWindows, documentID)
|
||||
// 如果成功吸附,位置已在handleUnsnappedWindow中更新
|
||||
}
|
||||
}
|
||||
|
||||
// isMainWindowAvailable 检查主窗口是否可用
|
||||
func (wss *WindowSnapService) isMainWindowAvailable() bool {
|
||||
if wss.mainWindow == nil {
|
||||
return false
|
||||
// updateSnappedWindowPosition 更新已吸附窗口的位置
|
||||
func (wss *WindowSnapService) updateSnappedWindowPosition(windowInfo *models.WindowInfo) {
|
||||
// 计算新的目标位置(基于主窗口新位置)
|
||||
expectedX := wss.lastMainWindowPos.X + windowInfo.SnapOffset.X
|
||||
expectedY := wss.lastMainWindowPos.Y + windowInfo.SnapOffset.Y
|
||||
|
||||
// 查找对应的window对象并移动
|
||||
if window, exists := wss.windowRefs[windowInfo.DocumentID]; exists {
|
||||
window.SetPosition(expectedX, expectedY)
|
||||
}
|
||||
|
||||
// 检查主窗口是否可见和正常状态
|
||||
return wss.mainWindow.IsVisible()
|
||||
windowInfo.LastPos = models.WindowPosition{X: expectedX, Y: expectedY}
|
||||
}
|
||||
|
||||
// handleSnappedWindow 处理已吸附的窗口
|
||||
func (wss *WindowSnapService) handleSnappedWindow(windowInfo *SnapWindowInfo, mainPos models.WindowPosition, currentPos models.WindowPosition) {
|
||||
// 计算预期位置基于主窗口的新位置
|
||||
expectedX := mainPos.X + windowInfo.SnapOffset.X
|
||||
expectedY := mainPos.Y + windowInfo.SnapOffset.Y
|
||||
// handleSnappedWindow 处理已吸附窗口的移动
|
||||
func (wss *WindowSnapService) handleSnappedWindow(window *application.WebviewWindow, windowInfo *models.WindowInfo, currentPos models.WindowPosition) {
|
||||
// 计算预期位置
|
||||
expectedX := wss.lastMainWindowPos.X + windowInfo.SnapOffset.X
|
||||
expectedY := wss.lastMainWindowPos.Y + windowInfo.SnapOffset.Y
|
||||
|
||||
// 计算当前位置与预期位置的距离
|
||||
// 计算实际位置与预期位置的距离
|
||||
distanceX := math.Abs(float64(currentPos.X - expectedX))
|
||||
distanceY := math.Abs(float64(currentPos.Y - expectedY))
|
||||
maxDistance := math.Max(distanceX, distanceY)
|
||||
|
||||
// 检测是否为用户主动拖拽:如果窗口移动幅度超过阈值且是最近移动的
|
||||
userDragThreshold := float64(wss.snapThreshold)
|
||||
isUserDrag := maxDistance > userDragThreshold && time.Since(windowInfo.MoveTime) < 100*time.Millisecond
|
||||
// 用户拖拽检测:距离超过阈值且移动很快
|
||||
userDragThreshold := float64(wss.calculateAdaptiveThreshold())
|
||||
isUserDrag := maxDistance > userDragThreshold && time.Since(windowInfo.MoveTime) < 50*time.Millisecond
|
||||
|
||||
if isUserDrag {
|
||||
// 用户主动拖拽,立即解除吸附
|
||||
// 用户主动拖拽,解除吸附
|
||||
windowInfo.IsSnapped = false
|
||||
windowInfo.SnapEdge = models.SnapEdgeNone
|
||||
return
|
||||
}
|
||||
|
||||
// 对于主窗口移动导致的位置变化,立即跟随且不解除吸附
|
||||
if maxDistance > 0 {
|
||||
// 直接调整到预期位置,不使用平滑移动以提高响应速度
|
||||
windowInfo.Window.SetPosition(expectedX, expectedY)
|
||||
windowInfo.LastPos = models.WindowPosition{X: expectedX, Y: expectedY}
|
||||
}
|
||||
}
|
||||
|
||||
// handleUnsnappedWindow 处理未吸附的窗口
|
||||
func (wss *WindowSnapService) handleUnsnappedWindow(windowInfo *SnapWindowInfo) {
|
||||
// 检查是否应该吸附到主窗口
|
||||
should, snapEdge := wss.shouldSnapToMainWindow(windowInfo)
|
||||
// handleUnsnappedWindow 处理未吸附窗口的移动,返回是否成功吸附
|
||||
func (wss *WindowSnapService) handleUnsnappedWindow(window *application.WebviewWindow, windowInfo *models.WindowInfo, currentPos models.WindowPosition, lastMoveTime time.Time) bool {
|
||||
// 检查是否应该吸附
|
||||
should, snapEdge := wss.shouldSnapToMainWindow(window, windowInfo, currentPos, lastMoveTime)
|
||||
if should {
|
||||
// 获取主窗口位置用于计算偏移量
|
||||
mainPos, _ := wss.getWindowPosition(wss.mainWindow)
|
||||
|
||||
// 设置吸附状态
|
||||
windowInfo.IsSnapped = true
|
||||
windowInfo.SnapEdge = snapEdge
|
||||
|
||||
// 执行即时吸附,产生明显的吸附效果
|
||||
wss.snapWindowToMainWindow(windowInfo, snapEdge)
|
||||
// 执行吸附移动
|
||||
targetPos := wss.calculateSnapPosition(snapEdge, currentPos, window)
|
||||
window.SetPosition(targetPos.X, targetPos.Y)
|
||||
|
||||
// 重新获取吸附后的位置来计算偏移量
|
||||
newPos, _ := wss.getWindowPosition(windowInfo.Window)
|
||||
windowInfo.SnapOffset.X = newPos.X - mainPos.X
|
||||
windowInfo.SnapOffset.Y = newPos.Y - mainPos.Y
|
||||
windowInfo.LastPos = newPos
|
||||
// 计算并保存偏移量
|
||||
windowInfo.SnapOffset.X = targetPos.X - wss.lastMainWindowPos.X
|
||||
windowInfo.SnapOffset.Y = targetPos.Y - wss.lastMainWindowPos.Y
|
||||
|
||||
// 更新位置为吸附后的位置
|
||||
windowInfo.LastPos = targetPos
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// getWindowPosition 获取窗口的位置
|
||||
@@ -331,269 +324,160 @@ func (wss *WindowSnapService) getWindowPosition(window *application.WebviewWindo
|
||||
return models.WindowPosition{X: x, Y: y}, true
|
||||
}
|
||||
|
||||
// shouldSnapToMainWindow 检查窗口是否应该吸附到主窗口(支持角落吸附)
|
||||
func (wss *WindowSnapService) shouldSnapToMainWindow(windowInfo *SnapWindowInfo) (bool, models.SnapEdge) {
|
||||
// 降低防抖时间,提高吸附响应速度
|
||||
if time.Since(windowInfo.MoveTime) < 50*time.Millisecond {
|
||||
// shouldSnapToMainWindow 优化版吸附检测
|
||||
func (wss *WindowSnapService) shouldSnapToMainWindow(window *application.WebviewWindow, windowInfo *models.WindowInfo, currentPos models.WindowPosition, lastMoveTime time.Time) (bool, models.SnapEdge) {
|
||||
// 防抖:移动太快时不检测,
|
||||
timeSinceLastMove := time.Since(lastMoveTime)
|
||||
if timeSinceLastMove < 30*time.Millisecond && timeSinceLastMove > 0 {
|
||||
return false, models.SnapEdgeNone
|
||||
}
|
||||
|
||||
// 获取两个窗口的位置
|
||||
mainPos, _ := wss.getWindowPosition(wss.mainWindow)
|
||||
windowPos, _ := wss.getWindowPosition(windowInfo.Window)
|
||||
// 使用缓存的主窗口位置和尺寸
|
||||
if wss.lastMainWindowSize[0] == 0 || wss.lastMainWindowSize[1] == 0 {
|
||||
// 主窗口缓存未初始化,立即更新
|
||||
wss.updateMainWindowCache()
|
||||
}
|
||||
|
||||
// 获取主窗口尺寸
|
||||
mainWidth, mainHeight := wss.mainWindow.Size()
|
||||
mainPos := wss.lastMainWindowPos
|
||||
mainWidth := wss.lastMainWindowSize[0]
|
||||
mainHeight := wss.lastMainWindowSize[1]
|
||||
|
||||
// 获取子窗口尺寸
|
||||
windowWidth, windowHeight := windowInfo.Window.Size()
|
||||
windowWidth, windowHeight := window.Size()
|
||||
|
||||
// 计算各个边缘的距离
|
||||
threshold := float64(wss.snapThreshold)
|
||||
cornerThreshold := threshold * 1.5 // 角落吸附需要更大的阈值
|
||||
// 自适应阈值计算
|
||||
threshold := float64(wss.calculateAdaptiveThreshold())
|
||||
cornerThreshold := threshold * 1.5
|
||||
|
||||
// 主窗口的四个边界
|
||||
mainLeft := mainPos.X
|
||||
mainTop := mainPos.Y
|
||||
mainRight := mainPos.X + mainWidth
|
||||
mainBottom := mainPos.Y + mainHeight
|
||||
// 计算边界
|
||||
mainLeft, mainTop := mainPos.X, mainPos.Y
|
||||
mainRight, mainBottom := mainPos.X+mainWidth, mainPos.Y+mainHeight
|
||||
|
||||
// 子窗口的四个边界
|
||||
windowLeft := windowPos.X
|
||||
windowTop := windowPos.Y
|
||||
windowRight := windowPos.X + windowWidth
|
||||
windowBottom := windowPos.Y + windowHeight
|
||||
windowLeft, windowTop := currentPos.X, currentPos.Y
|
||||
windowRight, windowBottom := currentPos.X+windowWidth, currentPos.Y+windowHeight
|
||||
|
||||
// 存储每个边缘的吸附信息
|
||||
type snapCandidate struct {
|
||||
// 简化的距离计算结构
|
||||
type snapCheck struct {
|
||||
edge models.SnapEdge
|
||||
distance float64
|
||||
overlap float64 // 重叠度,用于优先级判断
|
||||
isCorner bool // 是否为角落吸附
|
||||
priority int // 1=角落, 2=边缘
|
||||
}
|
||||
|
||||
var candidates []snapCandidate
|
||||
var bestSnap *snapCheck
|
||||
|
||||
// ==== 检查角落吸附(优先级最高) ====
|
||||
// 检查角落吸附(优先级1)
|
||||
cornerChecks := []struct {
|
||||
edge models.SnapEdge
|
||||
dx int
|
||||
dy int
|
||||
}{
|
||||
{models.SnapEdgeTopRight, mainRight - windowLeft, mainTop - windowBottom},
|
||||
{models.SnapEdgeBottomRight, mainRight - windowLeft, mainBottom - windowTop},
|
||||
{models.SnapEdgeBottomLeft, mainLeft - windowRight, mainBottom - windowTop},
|
||||
{models.SnapEdgeTopLeft, mainLeft - windowRight, mainTop - windowBottom},
|
||||
}
|
||||
|
||||
// 1. 右上角 (SnapEdgeTopRight)
|
||||
distToTopRight := math.Sqrt(math.Pow(float64(mainRight-windowLeft), 2) + math.Pow(float64(mainTop-windowBottom), 2))
|
||||
if distToTopRight <= cornerThreshold {
|
||||
// 检查是否接近右上角区域
|
||||
horizDist := math.Abs(float64(mainRight - windowLeft))
|
||||
vertDist := math.Abs(float64(mainTop - windowBottom))
|
||||
if horizDist <= cornerThreshold && vertDist <= cornerThreshold {
|
||||
candidates = append(candidates, snapCandidate{models.SnapEdgeTopRight, distToTopRight, 100, true})
|
||||
for _, check := range cornerChecks {
|
||||
dist := math.Sqrt(float64(check.dx*check.dx + check.dy*check.dy))
|
||||
if dist <= cornerThreshold {
|
||||
if bestSnap == nil || dist < bestSnap.distance {
|
||||
bestSnap = &snapCheck{check.edge, dist, 1}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 右下角 (SnapEdgeBottomRight)
|
||||
distToBottomRight := math.Sqrt(math.Pow(float64(mainRight-windowLeft), 2) + math.Pow(float64(mainBottom-windowTop), 2))
|
||||
if distToBottomRight <= cornerThreshold {
|
||||
horizDist := math.Abs(float64(mainRight - windowLeft))
|
||||
vertDist := math.Abs(float64(mainBottom - windowTop))
|
||||
if horizDist <= cornerThreshold && vertDist <= cornerThreshold {
|
||||
candidates = append(candidates, snapCandidate{models.SnapEdgeBottomRight, distToBottomRight, 100, true})
|
||||
// 如果没有角落吸附,检查边缘吸附(优先级2)
|
||||
if bestSnap == nil {
|
||||
edgeChecks := []struct {
|
||||
edge models.SnapEdge
|
||||
distance float64
|
||||
}{
|
||||
{models.SnapEdgeRight, math.Abs(float64(mainRight - windowLeft))},
|
||||
{models.SnapEdgeLeft, math.Abs(float64(mainLeft - windowRight))},
|
||||
{models.SnapEdgeBottom, math.Abs(float64(mainBottom - windowTop))},
|
||||
{models.SnapEdgeTop, math.Abs(float64(mainTop - windowBottom))},
|
||||
}
|
||||
|
||||
for _, check := range edgeChecks {
|
||||
if check.distance <= threshold {
|
||||
if bestSnap == nil || check.distance < bestSnap.distance {
|
||||
bestSnap = &snapCheck{check.edge, check.distance, 2}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 左下角 (SnapEdgeBottomLeft)
|
||||
distToBottomLeft := math.Sqrt(math.Pow(float64(mainLeft-windowRight), 2) + math.Pow(float64(mainBottom-windowTop), 2))
|
||||
if distToBottomLeft <= cornerThreshold {
|
||||
horizDist := math.Abs(float64(mainLeft - windowRight))
|
||||
vertDist := math.Abs(float64(mainBottom - windowTop))
|
||||
if horizDist <= cornerThreshold && vertDist <= cornerThreshold {
|
||||
candidates = append(candidates, snapCandidate{models.SnapEdgeBottomLeft, distToBottomLeft, 100, true})
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 左上角 (SnapEdgeTopLeft)
|
||||
distToTopLeft := math.Sqrt(math.Pow(float64(mainLeft-windowRight), 2) + math.Pow(float64(mainTop-windowBottom), 2))
|
||||
if distToTopLeft <= cornerThreshold {
|
||||
horizDist := math.Abs(float64(mainLeft - windowRight))
|
||||
vertDist := math.Abs(float64(mainTop - windowBottom))
|
||||
if horizDist <= cornerThreshold && vertDist <= cornerThreshold {
|
||||
candidates = append(candidates, snapCandidate{models.SnapEdgeTopLeft, distToTopLeft, 100, true})
|
||||
}
|
||||
}
|
||||
|
||||
// ==== 检查边缘吸附(只在没有角落吸附时检查) ====
|
||||
if len(candidates) == 0 {
|
||||
// 1. 吸附到主窗口右侧
|
||||
distToRight := math.Abs(float64(mainRight - windowLeft))
|
||||
if distToRight <= threshold {
|
||||
// 计算垂直重叠
|
||||
overlapTop := math.Max(float64(mainTop), float64(windowTop))
|
||||
overlapBottom := math.Min(float64(mainBottom), float64(windowBottom))
|
||||
verticalOverlap := math.Max(0, overlapBottom-overlapTop)
|
||||
candidates = append(candidates, snapCandidate{models.SnapEdgeRight, distToRight, verticalOverlap, false})
|
||||
}
|
||||
|
||||
// 2. 吸附到主窗口左侧
|
||||
distToLeft := math.Abs(float64(mainLeft - windowRight))
|
||||
if distToLeft <= threshold {
|
||||
// 计算垂直重叠
|
||||
overlapTop := math.Max(float64(mainTop), float64(windowTop))
|
||||
overlapBottom := math.Min(float64(mainBottom), float64(windowBottom))
|
||||
verticalOverlap := math.Max(0, overlapBottom-overlapTop)
|
||||
candidates = append(candidates, snapCandidate{models.SnapEdgeLeft, distToLeft, verticalOverlap, false})
|
||||
}
|
||||
|
||||
// 3. 吸附到主窗口底部
|
||||
distToBottom := math.Abs(float64(mainBottom - windowTop))
|
||||
if distToBottom <= threshold {
|
||||
// 计算水平重叠
|
||||
overlapLeft := math.Max(float64(mainLeft), float64(windowLeft))
|
||||
overlapRight := math.Min(float64(mainRight), float64(windowRight))
|
||||
horizontalOverlap := math.Max(0, overlapRight-overlapLeft)
|
||||
candidates = append(candidates, snapCandidate{models.SnapEdgeBottom, distToBottom, horizontalOverlap, false})
|
||||
}
|
||||
|
||||
// 4. 吸附到主窗口顶部
|
||||
distToTop := math.Abs(float64(mainTop - windowBottom))
|
||||
if distToTop <= threshold {
|
||||
// 计算水平重叠
|
||||
overlapLeft := math.Max(float64(mainLeft), float64(windowLeft))
|
||||
overlapRight := math.Min(float64(mainRight), float64(windowRight))
|
||||
horizontalOverlap := math.Max(0, overlapRight-overlapLeft)
|
||||
candidates = append(candidates, snapCandidate{models.SnapEdgeTop, distToTop, horizontalOverlap, false})
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没有候选,不吸附
|
||||
if len(candidates) == 0 {
|
||||
if bestSnap == nil {
|
||||
return false, models.SnapEdgeNone
|
||||
}
|
||||
|
||||
// 选择最佳吸附位置:角落吸附优先,其次考虑重叠度,最后考虑距离
|
||||
bestCandidate := candidates[0]
|
||||
for _, candidate := range candidates[1:] {
|
||||
// 角落吸附优先级最高
|
||||
if candidate.isCorner && !bestCandidate.isCorner {
|
||||
bestCandidate = candidate
|
||||
} else if bestCandidate.isCorner && !candidate.isCorner {
|
||||
// 继续使用当前的角落吸附
|
||||
continue
|
||||
} else {
|
||||
// 同类型的吸附,比较重叠度和距离
|
||||
if math.Abs(candidate.overlap-bestCandidate.overlap) < 10 {
|
||||
if candidate.distance < bestCandidate.distance {
|
||||
bestCandidate = candidate
|
||||
}
|
||||
} else if candidate.overlap > bestCandidate.overlap {
|
||||
// 重叠度更高的优先
|
||||
bestCandidate = candidate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true, bestCandidate.edge
|
||||
return true, bestSnap.edge
|
||||
}
|
||||
|
||||
// snapWindowToMainWindow 将窗口精确吸附到主窗口边缘(支持角落吸附)
|
||||
func (wss *WindowSnapService) snapWindowToMainWindow(windowInfo *SnapWindowInfo, snapEdge models.SnapEdge) {
|
||||
// 获取主窗口位置和尺寸
|
||||
mainPos, _ := wss.getWindowPosition(wss.mainWindow)
|
||||
mainWidth, mainHeight := wss.mainWindow.Size()
|
||||
// calculateSnapPosition 计算吸附目标位置
|
||||
func (wss *WindowSnapService) calculateSnapPosition(snapEdge models.SnapEdge, currentPos models.WindowPosition, window *application.WebviewWindow) models.WindowPosition {
|
||||
// 使用缓存的主窗口信息
|
||||
mainPos := wss.lastMainWindowPos
|
||||
mainWidth := wss.lastMainWindowSize[0]
|
||||
mainHeight := wss.lastMainWindowSize[1]
|
||||
|
||||
// 获取子窗口位置和尺寸
|
||||
windowPos, _ := wss.getWindowPosition(windowInfo.Window)
|
||||
windowWidth, windowHeight := windowInfo.Window.Size()
|
||||
|
||||
// 计算目标位置
|
||||
var targetX, targetY int
|
||||
// 获取子窗口尺寸
|
||||
windowWidth, windowHeight := window.Size()
|
||||
|
||||
switch snapEdge {
|
||||
case models.SnapEdgeRight:
|
||||
// 吸附到主窗口右侧
|
||||
targetX = mainPos.X + mainWidth
|
||||
targetY = windowPos.Y // 保持当前 Y 位置
|
||||
// 如果超出主窗口范围,调整到边界
|
||||
if targetY < mainPos.Y {
|
||||
targetY = mainPos.Y
|
||||
} else if targetY+windowHeight > mainPos.Y+mainHeight {
|
||||
targetY = mainPos.Y + mainHeight - windowHeight
|
||||
return models.WindowPosition{
|
||||
X: mainPos.X + mainWidth,
|
||||
Y: currentPos.Y, // 保持当前Y位置
|
||||
}
|
||||
|
||||
case models.SnapEdgeLeft:
|
||||
// 吸附到主窗口左侧
|
||||
targetX = mainPos.X - windowWidth
|
||||
targetY = windowPos.Y // 保持当前 Y 位置
|
||||
// 如果超出主窗口范围,调整到边界
|
||||
if targetY < mainPos.Y {
|
||||
targetY = mainPos.Y
|
||||
} else if targetY+windowHeight > mainPos.Y+mainHeight {
|
||||
targetY = mainPos.Y + mainHeight - windowHeight
|
||||
return models.WindowPosition{
|
||||
X: mainPos.X - windowWidth,
|
||||
Y: currentPos.Y,
|
||||
}
|
||||
|
||||
case models.SnapEdgeBottom:
|
||||
// 吸附到主窗口底部
|
||||
targetX = windowPos.X // 保持当前 X 位置
|
||||
targetY = mainPos.Y + mainHeight
|
||||
// 如果超出主窗口范围,调整到边界
|
||||
if targetX < mainPos.X {
|
||||
targetX = mainPos.X
|
||||
} else if targetX+windowWidth > mainPos.X+mainWidth {
|
||||
targetX = mainPos.X + mainWidth - windowWidth
|
||||
return models.WindowPosition{
|
||||
X: currentPos.X,
|
||||
Y: mainPos.Y + mainHeight,
|
||||
}
|
||||
|
||||
case models.SnapEdgeTop:
|
||||
// 吸附到主窗口顶部
|
||||
targetX = windowPos.X // 保持当前 X 位置
|
||||
targetY = mainPos.Y - windowHeight
|
||||
// 如果超出主窗口范围,调整到边界
|
||||
if targetX < mainPos.X {
|
||||
targetX = mainPos.X
|
||||
} else if targetX+windowWidth > mainPos.X+mainWidth {
|
||||
targetX = mainPos.X + mainWidth - windowWidth
|
||||
return models.WindowPosition{
|
||||
X: currentPos.X,
|
||||
Y: mainPos.Y - windowHeight,
|
||||
}
|
||||
|
||||
// ==== 角落吸附 ====
|
||||
case models.SnapEdgeTopRight:
|
||||
// 吸附到右上角
|
||||
targetX = mainPos.X + mainWidth
|
||||
targetY = mainPos.Y - windowHeight
|
||||
|
||||
return models.WindowPosition{
|
||||
X: mainPos.X + mainWidth,
|
||||
Y: mainPos.Y - windowHeight,
|
||||
}
|
||||
case models.SnapEdgeBottomRight:
|
||||
// 吸附到右下角
|
||||
targetX = mainPos.X + mainWidth
|
||||
targetY = mainPos.Y + mainHeight
|
||||
|
||||
return models.WindowPosition{
|
||||
X: mainPos.X + mainWidth,
|
||||
Y: mainPos.Y + mainHeight,
|
||||
}
|
||||
case models.SnapEdgeBottomLeft:
|
||||
// 吸附到左下角
|
||||
targetX = mainPos.X - windowWidth
|
||||
targetY = mainPos.Y + mainHeight
|
||||
|
||||
return models.WindowPosition{
|
||||
X: mainPos.X - windowWidth,
|
||||
Y: mainPos.Y + mainHeight,
|
||||
}
|
||||
case models.SnapEdgeTopLeft:
|
||||
// 吸附到左上角
|
||||
targetX = mainPos.X - windowWidth
|
||||
targetY = mainPos.Y - windowHeight
|
||||
|
||||
default:
|
||||
// 不应该到达这里
|
||||
return
|
||||
return models.WindowPosition{
|
||||
X: mainPos.X - windowWidth,
|
||||
Y: mainPos.Y - windowHeight,
|
||||
}
|
||||
}
|
||||
|
||||
// 直接移动到目标位置,不使用平滑过渡以产生明显的吸附效果
|
||||
windowInfo.Window.SetPosition(targetX, targetY)
|
||||
|
||||
// 更新窗口信息
|
||||
windowInfo.SnapEdge = snapEdge
|
||||
windowInfo.LastPos = models.WindowPosition{X: targetX, Y: targetY}
|
||||
return currentPos
|
||||
}
|
||||
|
||||
// Cleanup 清理资源
|
||||
func (wss *WindowSnapService) Cleanup() {
|
||||
// 如果有取消函数,调用它来停止所有goroutine
|
||||
if wss.cancel != nil {
|
||||
wss.cancel()
|
||||
}
|
||||
wss.mu.Lock()
|
||||
defer wss.mu.Unlock()
|
||||
|
||||
// 停止定时器
|
||||
if wss.snapTicker != nil {
|
||||
wss.snapTicker.Stop()
|
||||
wss.snapTicker = nil
|
||||
}
|
||||
// 清空管理的窗口
|
||||
wss.managedWindows = make(map[int64]*models.WindowInfo)
|
||||
wss.windowRefs = make(map[int64]*application.WebviewWindow)
|
||||
}
|
||||
|
||||
// ServiceShutdown 实现服务关闭接口
|
||||
|
||||
Reference in New Issue
Block a user