package action import ( "context" "fmt" "sync" "time" pwin "zerorigin/internal/platform/windows" ) func init() { // 单例:alternate 模式的往返方向状态必须跨执行保持 //(引擎每次执行都通过工厂获取实例,非单例会丢失状态)。 Register("switch_virtual_desktop", func() Action { return switchDesktopShared }) } // switchDesktopShared 为共享的切换桌面动作实例。 var switchDesktopShared = &switchDesktopAction{} // switchDesktopAction 切换虚拟桌面。 // mode: alternate(往返)/ left / right。 // method: com(默认,COM 直调,无快捷键依赖)/ taskview(Win+Tab 导航)/ hotkey(Win+Ctrl+方向键, // 仅当系统快捷键未被占用时可用)。com 失败时自动回退 taskview。 type switchDesktopAction struct { mu sync.Mutex next int32 // alternate 模式下上次切换方向,用于往返 } func (a *switchDesktopAction) ID() string { return "switch_virtual_desktop" } func (a *switchDesktopAction) Name() string { return "切换虚拟桌面" } func (a *switchDesktopAction) Schema() ActionSchema { return ActionSchema{Params: []ParamSpec{ {Name: "mode", Type: "string", Required: true, Default: "alternate"}, {Name: "method", Type: "string", Required: false, Default: "com"}, {Name: "taskview_delay_ms", Type: "int", Required: false, Default: 400}, }} } func (a *switchDesktopAction) Validate(params map[string]any) error { mode := GetString(params, "mode") switch mode { case "alternate", "left", "right": default: return fmt.Errorf("switch_virtual_desktop: invalid mode %q (want alternate|left|right)", mode) } method := GetString(params, "method") switch method { case "", "com", "taskview", "hotkey": default: return fmt.Errorf("switch_virtual_desktop: invalid method %q (want com|taskview|hotkey)", method) } if d := GetInt(params, "taskview_delay_ms"); d < 0 { return fmt.Errorf("switch_virtual_desktop: taskview_delay_ms must be >= 0") } return nil } func (a *switchDesktopAction) Execute(ctx context.Context, params map[string]any) error { mode := GetString(params, "mode") var dir int32 switch mode { case "left": dir = -1 case "right": dir = 1 default: // alternate a.mu.Lock() dir = a.next if dir == 0 { dir = 1 // 首次默认向右 } a.next = -dir a.mu.Unlock() } switch GetString(params, "method") { case "hotkey": return pwin.SwitchVirtualDesktop(dir) case "taskview": return pwin.SwitchDesktopViaTaskView(dir, time.Duration(GetInt(params, "taskview_delay_ms"))*time.Millisecond) default: // com:COM 直调,失败回退 taskview if err := pwin.SwitchDesktopCOM(dir); err == nil { return nil } return pwin.SwitchDesktopViaTaskView(dir, time.Duration(GetInt(params, "taskview_delay_ms"))*time.Millisecond) } }