Documentation
¶
Overview ¶
Package maa provides Go bindings for the MaaFramework.
Pipeline model ¶
Typed pipeline builders use pipeline v2 JSON with nested action and recognition objects. Decoding also accepts the legacy flat pipeline format and normalizes it into the v2 model; encoding always emits v2. For pipeline protocol details, see: https://github.com/MaaXYZ/MaaFramework/blob/main/docs/en_us/3.1-PipelineProtocol.md
Object lifetime ¶
Constructors such as NewTasker, NewResource, and the controller constructors return objects that own their native handles. Getters and callbacks — Tasker.GetResource, Tasker.GetController, Context.GetTasker, and the views passed to event callbacks — return borrowed views that do not own the native object; destroying one returns ErrBorrowed.
Repeated successful Destroy calls on an owner are safe. Destroy returns ErrInUse while a call or asynchronous job is active, even if the returned Job was discarded; retry after it finishes. Call Wait on a job before destroying its owner if you need the job's outcome. A successful Destroy returns after native cleanup and prevents subsequent user callbacks; destroying an owner from one of its own callbacks returns ErrInCallback. After closing, methods that return an error report ErrClosed, and jobs expose it through Job.Error.
Keep every resource and controller bound to a tasker alive until the tasker is destroyed, including bindings replaced by a later rebind; closing one before then returns ErrBound. Rebinding a running tasker returns ErrTaskerRunning. An AgentClient likewise retains its bound resource and registered event sources until the client is destroyed. A Context received in a callback, including a Clone, expires when the callback returns.
Concurrency ¶
Job and TaskJob support concurrent Wait, status queries and predicates, and Error. Multiple waiters share the completed result, and status queries remain available while a wait is in progress. Do not copy these objects.
Most other operations require caller coordination: serialize option changes, resource and pipeline changes, calls through a single Context, and AgentClient and AgentServer lifecycle operations. Mutable configuration values such as Pipeline and Node also require caller synchronization. Handle lifetime checks do not make all native operations thread-safe.
Callbacks ¶
Callbacks execute synchronously on native calling threads and may overlap. Synchronize shared state in handlers, and never wait for work that needs the current callback to return. Do not call AgentServer lifecycle methods from its callbacks.
Registrations ¶
Change event sinks and custom recognition and action registrations only while the instance and all associated taskers are idle: stop new submissions and let their work and callbacks finish before adding, replacing, removing, or clearing registrations, and never change registrations from a callback. Configuration transactions on one instance are serialized with each other, including through borrowed views, but they must not overlap native execution.
Index ¶
- Constants
- Variables
- func AgentServerAddContextSink(sink ContextEventSink) int64
- func AgentServerAddControllerSink(sink ControllerEventSink) int64
- func AgentServerAddResourceSink(sink ResourceEventSink) int64
- func AgentServerAddTaskerSink(sink TaskerEventSink) int64
- func AgentServerDetach()
- func AgentServerJoin()
- func AgentServerRegisterCustomAction(name string, action CustomActionRunner) error
- func AgentServerRegisterCustomRecognition(name string, recognition CustomRecognitionRunner) error
- func AgentServerShutDown()
- func AgentServerStartUp(identifier string) error
- func ConfigInitOption(userPath, defaultJson string) error
- func Init(opts ...InitOption) (err error)
- func IsInited() bool
- func LoadPlugin(path string) error
- func MacOSCheckPermission(perm MacOSPermission) bool
- func MacOSRequestPermission(perm MacOSPermission) bool
- func MacOSRevealPermissionSettings(perm MacOSPermission) bool
- func Release() error
- func ResetJSONCodec()
- func SetDebugMode(enabled bool) error
- func SetDrawQuality(quality int32) error
- func SetJSONDecoder(decoder JSONDecoder)
- func SetJSONEncoder(encoder JSONEncoder)
- func SetLogDir(path string) error
- func SetRecoImageCacheLimit(limit uint64) error
- func SetSaveDraw(enabled bool) error
- func SetSaveOnError(enabled bool) error
- func SetStdoutLevel(level LoggingLevel) error
- func Version() string
- type Action
- func ActClick(p ClickParam) *Action
- func ActClickKey(keys []int) *Action
- func ActCommand(p CommandParam) *Action
- func ActCustom(p CustomActionParam) *Action
- func ActDoNothing() *Action
- func ActInputText(input string) *Action
- func ActKeyDown(key int) *Action
- func ActKeyUp(key int) *Action
- func ActLongPress(p LongPressParam) *Action
- func ActLongPressKey(p LongPressKeyParam) *Action
- func ActMultiSwipe(swipes ...MultiSwipeItem) *Action
- func ActScreencap(p ScreencapParam) *Action
- func ActScroll(p ScrollParam) *Action
- func ActShell(cmd string) *Action
- func ActStartApp(pkg string) *Action
- func ActStopApp(pkg string) *Action
- func ActStopTask() *Action
- func ActSwipe(p SwipeParam) *Action
- func ActTouchDown(p TouchDownParam) *Action
- func ActTouchMove(p TouchMoveParam) *Action
- func ActTouchUp(contact int) *Action
- type ActionDetail
- type ActionParam
- type ActionResult
- func (r *ActionResult) AsApp() (*AppActionResult, bool)
- func (r *ActionResult) AsClick() (*ClickActionResult, bool)
- func (r *ActionResult) AsClickKey() (*ClickKeyActionResult, bool)
- func (r *ActionResult) AsInputText() (*InputTextActionResult, bool)
- func (r *ActionResult) AsLongPress() (*LongPressActionResult, bool)
- func (r *ActionResult) AsLongPressKey() (*LongPressKeyActionResult, bool)
- func (r *ActionResult) AsMultiSwipe() (*MultiSwipeActionResult, bool)
- func (r *ActionResult) AsScreencap() (*ScreencapActionResult, bool)
- func (r *ActionResult) AsScroll() (*ScrollActionResult, bool)
- func (r *ActionResult) AsShell() (*ShellActionResult, bool)
- func (r *ActionResult) AsSwipe() (*SwipeActionResult, bool)
- func (r *ActionResult) AsTouch() (*TouchActionResult, bool)
- func (r *ActionResult) Type() ActionType
- func (r *ActionResult) Value() any
- type ActionType
- type AdbDevice
- type AgentClient
- func (ac *AgentClient) Alive() bool
- func (ac *AgentClient) BindResource(res *Resource) error
- func (ac *AgentClient) Connect() error
- func (ac *AgentClient) Connected() bool
- func (ac *AgentClient) Destroy() error
- func (ac *AgentClient) Disconnect() error
- func (ac *AgentClient) GetCustomActionList() ([]string, error)
- func (ac *AgentClient) GetCustomRecognitionList() ([]string, error)
- func (ac *AgentClient) Identifier() (string, error)
- func (ac *AgentClient) RegisterControllerSink(ctrl Controller) error
- func (ac *AgentClient) RegisterResourceSink(res *Resource) error
- func (ac *AgentClient) RegisterTaskerSink(tasker Tasker) error
- func (ac *AgentClient) SetTimeout(duration time.Duration) error
- type AgentClientOption
- type AndRecognitionParam
- type AppActionResult
- type BlankController
- func (c *BlankController) Click(x int32, y int32) bool
- func (c *BlankController) ClickKey(keycode int32) bool
- func (c *BlankController) Connect() bool
- func (c *BlankController) Connected() bool
- func (c *BlankController) GetFeature() ControllerFeature
- func (c *BlankController) GetInfo() (string, bool)
- func (c *BlankController) Inactive() bool
- func (c *BlankController) InputText(text string) bool
- func (c *BlankController) KeyDown(keycode int32) bool
- func (c *BlankController) KeyUp(keycode int32) bool
- func (c *BlankController) RelativeMove(dx int32, dy int32) bool
- func (c *BlankController) RequestUUID() (string, bool)
- func (c *BlankController) Screencap() (image.Image, bool)
- func (c *BlankController) Scroll(dx int32, dy int32) bool
- func (c *BlankController) Shell(cmd string, timeout int64) (string, bool)
- func (c *BlankController) StartApp(intent string) bool
- func (c *BlankController) StopApp(intent string) bool
- func (c *BlankController) Swipe(x1 int32, y1 int32, x2 int32, y2 int32, duration int32) bool
- func (c *BlankController) TouchDown(contact int32, x int32, y int32, pressure int32) bool
- func (c *BlankController) TouchMove(contact int32, x int32, y int32, pressure int32) bool
- func (c *BlankController) TouchUp(contact int32) bool
- type ClassSelector
- type ClassSelectors
- type ClickActionResult
- type ClickKeyActionResult
- type ClickKeyParam
- type ClickParam
- type ColorMatchMethod
- type ColorMatchOrderBy
- type ColorMatchParam
- type ColorMatchResult
- type CommandParam
- type Context
- func (ctx *Context) ClearHitCount(nodeName string) error
- func (ctx *Context) Clone() *Context
- func (ctx *Context) GetAnchor(anchorName string) (string, error)
- func (ctx *Context) GetHitCount(nodeName string) (uint64, error)
- func (ctx *Context) GetNode(name string) (*Node, error)
- func (ctx *Context) GetNodeJSON(name string) (string, error)
- func (ctx *Context) GetTaskJob() *TaskJob
- func (ctx *Context) GetTasker() *Tasker
- func (ctx *Context) OverrideImage(imageName string, image image.Image) error
- func (ctx *Context) OverrideNext(name string, nextList []NextItem) error
- func (ctx *Context) OverridePipeline(override any) error
- func (ctx *Context) RunAction(entry string, box Rect, recognitionDetail string, override ...any) (*ActionDetail, error)
- func (ctx *Context) RunActionDirect(actionType ActionType, actionParam ActionParam, box Rect, ...) (*ActionDetail, error)
- func (ctx *Context) RunRecognition(entry string, img image.Image, override ...any) (*RecognitionDetail, error)
- func (ctx *Context) RunRecognitionDirect(recoType RecognitionType, recoParam RecognitionParam, img image.Image) (*RecognitionDetail, error)
- func (ctx *Context) RunTask(entry string, override ...any) (*TaskDetail, error)
- func (ctx *Context) SetAnchor(anchorName, nodeName string) error
- func (ctx *Context) WaitFreezes(duration time.Duration, box *Rect, waitFreezesParam *WaitFreezesParam) error
- type ContextEventSink
- type ContextWaitFreezesEventSink
- type Controller
- func NewAdbController(adbPath, address string, screencapMethod adb.ScreencapMethod, ...) (*Controller, error)
- func NewAndroidNativeController(configJson string) (*Controller, error)
- func NewBlankController() (*Controller, error)
- func NewCustomController(ctrl CustomController) (*Controller, error)
- func NewGamepadController(hWnd unsafe.Pointer, gamepadType GamepadType, ...) (*Controller, error)
- func NewLinuxController(configJson string) (*Controller, error)
- func NewMacOSController(windowID uint32, screencapMethod macos.ScreencapMethod, ...) (*Controller, error)
- func NewPlayCoverController(address, uuid string) (*Controller, error)
- func NewRecordController(inner *Controller, recordingPath string) (*Controller, error)
- func NewReplayController(recordingPath string) (*Controller, error)
- func NewWin32Controller(hWnd unsafe.Pointer, screencapMethod win32.ScreencapMethod, ...) (*Controller, error)
- func (c *Controller) AddSink(sink ControllerEventSink) int64
- func (c *Controller) CacheImage() (image.Image, error)
- func (c *Controller) CacheImageInto(dst *image.RGBA) (*image.RGBA, error)
- func (c *Controller) ClearSinks()
- func (c *Controller) Connected() bool
- func (c *Controller) Destroy() error
- func (c *Controller) GetInfo() (string, error)
- func (c *Controller) GetResolution() (width, height int32, err error)
- func (c *Controller) GetShellOutput() (string, error)
- func (c *Controller) GetUUID() (string, error)
- func (c *Controller) OnControllerAction(fn func(EventStatus, ControllerActionDetail)) int64
- func (c *Controller) PostClick(x, y int32) (*Job, error)
- func (c *Controller) PostClickKey(keycode int32) (*Job, error)
- func (c *Controller) PostClickV2(x, y, contact, pressure int32) (*Job, error)
- func (c *Controller) PostConnect() (*Job, error)
- func (c *Controller) PostInactive() (*Job, error)
- func (c *Controller) PostInputText(text string) (*Job, error)
- func (c *Controller) PostKeyDown(keycode int32) (*Job, error)
- func (c *Controller) PostKeyUp(keycode int32) (*Job, error)
- func (c *Controller) PostRelativeMove(dx, dy int32) (*Job, error)
- func (c *Controller) PostScreencap() (*Job, error)
- func (c *Controller) PostScroll(dx, dy int32) (*Job, error)
- func (c *Controller) PostShell(cmd string, timeout time.Duration) (*Job, error)
- func (c *Controller) PostStartApp(intent string) (*Job, error)
- func (c *Controller) PostStopApp(intent string) (*Job, error)
- func (c *Controller) PostSwipe(x1, y1, x2, y2 int32, duration time.Duration) (*Job, error)
- func (c *Controller) PostSwipeV2(x1, y1, x2, y2 int32, duration time.Duration, contact, pressure int32) (*Job, error)
- func (c *Controller) PostTouchDown(contact, x, y, pressure int32) (*Job, error)
- func (c *Controller) PostTouchMove(contact, x, y, pressure int32) (*Job, error)
- func (c *Controller) PostTouchUp(contact int32) (*Job, error)
- func (c *Controller) RemoveSink(sinkId int64)
- func (c *Controller) SetBackgroundManagedKeys(keys []int32) error
- func (c *Controller) SetMouseLockFollow(enabled bool) error
- func (c *Controller) SetScreenshot(opts ...ScreenshotOption) error
- type ControllerActionDetail
- type ControllerEventSink
- type ControllerFeature
- type CustomActionArg
- type CustomActionFunc
- type CustomActionParam
- type CustomActionRunner
- type CustomController
- type CustomRecognitionArg
- type CustomRecognitionFunc
- type CustomRecognitionParam
- type CustomRecognitionResult
- type CustomRecognitionRunner
- type DesktopWindow
- type DirectHitParam
- type DoNothingParam
- type Event
- type EventStatus
- type FeatureMatchDetector
- type FeatureMatchOrderBy
- type FeatureMatchParam
- type FeatureMatchResult
- type GamepadType
- type GamescopeInstance
- type InferenceDevice
- type InitOption
- func WithDebugMode(enabled bool) InitOption
- func WithJSONDecoder(decoder JSONDecoder) InitOption
- func WithJSONEncoder(encoder JSONEncoder) InitOption
- func WithLibDir(libDir string) InitOption
- func WithLogDir(logDir string) InitOption
- func WithPluginPaths(path ...string) InitOption
- func WithSaveDraw(enabled bool) InitOption
- func WithStdoutLevel(level LoggingLevel) InitOption
- type InlineSubRecognition
- type InputTextActionResult
- type InputTextParam
- type JSONDecoder
- type JSONEncoder
- type Job
- type KeyDownParam
- type KeyUpParam
- type LibraryLoadError
- type LoggingLevel
- type LongPressActionResult
- type LongPressKeyActionResult
- type LongPressKeyParam
- type LongPressParam
- type MaaCustomControllerCallbacks
- type MacOSPermission
- type MultiSwipeActionResult
- type MultiSwipeItem
- type MultiSwipeParam
- type NeuralNetworkClassifyOrderBy
- type NeuralNetworkClassifyParam
- type NeuralNetworkClassifyResult
- type NeuralNetworkDetectOrderBy
- type NeuralNetworkDetectParam
- type NeuralNetworkDetectResult
- type NextItem
- type Node
- func (n *Node) AddAnchor(anchor string) *Node
- func (n *Node) AddNext(name string, opts ...NodeAttributeOption) *Node
- func (n *Node) AddOnError(name string, opts ...NodeAttributeOption) *Node
- func (n *Node) ClearAnchor(anchor string) *Node
- func (n *Node) RemoveAnchor(anchor string) *Node
- func (n *Node) RemoveNext(name string) *Node
- func (n *Node) RemoveOnError(name string) *Node
- func (n *Node) SetAction(act *Action) *Node
- func (n *Node) SetAnchor(anchor map[string]string) *Node
- func (n *Node) SetAnchorTarget(anchor, nodeName string) *Node
- func (n *Node) SetAttach(attach map[string]any) *Node
- func (n *Node) SetEnabled(enabled bool) *Node
- func (n *Node) SetFocus(focus any) *Node
- func (n *Node) SetInverse(inverse bool) *Node
- func (n *Node) SetMaxHit(maxHit uint64) *Node
- func (n *Node) SetNext(next []NextItem) *Node
- func (n *Node) SetOnError(onError []NextItem) *Node
- func (n *Node) SetPostDelay(postDelay time.Duration) *Node
- func (n *Node) SetPostWaitFreezes(postWaitFreezes *WaitFreezesParam) *Node
- func (n *Node) SetPreDelay(preDelay time.Duration) *Node
- func (n *Node) SetPreWaitFreezes(preWaitFreezes *WaitFreezesParam) *Node
- func (n *Node) SetRateLimit(rateLimit time.Duration) *Node
- func (n *Node) SetRecognition(rec *Recognition) *Node
- func (n *Node) SetRepeat(repeat uint64) *Node
- func (n *Node) SetRepeatDelay(repeatDelay time.Duration) *Node
- func (n *Node) SetRepeatWaitFreezes(repeatWaitFreezes *WaitFreezesParam) *Node
- func (n *Node) SetTimeout(timeout time.Duration) *Node
- func (n *Node) UnmarshalJSON(data []byte) error
- type NodeActionDetail
- type NodeActionNodeDetail
- type NodeAttributeOption
- type NodeDetail
- type NodeNextListDetail
- type NodePipelineNodeDetail
- type NodeRecognitionDetail
- type NodeRecognitionNodeDetail
- type NodeRef
- type NodeWaitFreezesDetail
- type OCROrderBy
- type OCRParam
- type OCRResult
- type OrRecognitionParam
- type OrderBy
- type Pipeline
- func (p *Pipeline) AddNode(node *Node) *Pipeline
- func (p *Pipeline) Clear() *Pipeline
- func (p *Pipeline) GetNode(name string) (*Node, bool)
- func (p *Pipeline) HasNode(name string) bool
- func (p *Pipeline) Len() int
- func (p *Pipeline) MarshalJSON() ([]byte, error)
- func (p *Pipeline) RemoveNode(name string) *Pipeline
- func (p *Pipeline) UnmarshalJSON(data []byte) error
- type Point
- type PortalHelper
- func (p *PortalHelper) Destroy()
- func (p *PortalHelper) OpenStream() error
- func (p *PortalHelper) Persist() bool
- func (p *PortalHelper) PipeWireFD() int
- func (p *PortalHelper) PipeWireNodeID() uint32
- func (p *PortalHelper) RestoreToken() string
- func (p *PortalHelper) SetPersist(enable bool)
- func (p *PortalHelper) SetRestoreToken(token string)
- type RawActionParam
- type RawRecognitionParam
- type Recognition
- func RecAnd(items ...SubRecognitionItem) *Recognition
- func RecColorMatch(p ColorMatchParam) *Recognition
- func RecCustom(p CustomRecognitionParam) *Recognition
- func RecDirectHit() *Recognition
- func RecFeatureMatch(p FeatureMatchParam) *Recognition
- func RecNeuralNetworkClassify(p NeuralNetworkClassifyParam) *Recognition
- func RecNeuralNetworkDetect(p NeuralNetworkDetectParam) *Recognition
- func RecOCR(p OCRParam) *Recognition
- func RecOr(anyOf ...SubRecognitionItem) *Recognition
- func RecTemplateMatch(p TemplateMatchParam) *Recognition
- type RecognitionDetail
- type RecognitionParam
- type RecognitionResult
- func (r *RecognitionResult) AsColorMatch() (*ColorMatchResult, bool)
- func (r *RecognitionResult) AsCustom() (*CustomRecognitionResult, bool)
- func (r *RecognitionResult) AsFeatureMatch() (*FeatureMatchResult, bool)
- func (r *RecognitionResult) AsNeuralNetworkClassify() (*NeuralNetworkClassifyResult, bool)
- func (r *RecognitionResult) AsNeuralNetworkDetect() (*NeuralNetworkDetectResult, bool)
- func (r *RecognitionResult) AsOCR() (*OCRResult, bool)
- func (r *RecognitionResult) AsTemplateMatch() (*TemplateMatchResult, bool)
- func (r *RecognitionResult) Type() RecognitionType
- func (r *RecognitionResult) Value() any
- type RecognitionResults
- type RecognitionType
- type Rect
- type Resource
- func (r *Resource) AddSink(sink ResourceEventSink) int64
- func (r *Resource) Clear() error
- func (r *Resource) ClearCustomAction() error
- func (r *Resource) ClearCustomRecognition() error
- func (r *Resource) ClearSinks()
- func (r *Resource) Destroy() error
- func (r *Resource) GetCustomActionList() ([]string, error)
- func (r *Resource) GetCustomRecognitionList() ([]string, error)
- func (r *Resource) GetDefaultActionParam(actionType ActionType) (ActionParam, error)
- func (r *Resource) GetDefaultRecognitionParam(recoType RecognitionType) (RecognitionParam, error)
- func (r *Resource) GetHash() (string, error)
- func (r *Resource) GetNode(name string) (*Node, error)
- func (r *Resource) GetNodeJSON(name string) (string, error)
- func (r *Resource) GetNodeList() ([]string, error)
- func (r *Resource) Loaded() bool
- func (r *Resource) OnResourceLoading(fn func(EventStatus, ResourceLoadingDetail)) int64
- func (r *Resource) OverrideImage(imageName string, image image.Image) error
- func (r *Resource) OverrideNext(name string, nextList []NextItem) error
- func (r *Resource) OverridePipeline(override any) error
- func (r *Resource) PostBundle(path string) (*Job, error)
- func (r *Resource) PostImage(path string) (*Job, error)
- func (r *Resource) PostOcrModel(path string) (*Job, error)
- func (r *Resource) PostPipeline(path string) (*Job, error)
- func (r *Resource) RegisterCustomAction(name string, action CustomActionRunner) error
- func (r *Resource) RegisterCustomRecognition(name string, recognition CustomRecognitionRunner) error
- func (r *Resource) RemoveSink(sinkId int64)
- func (r *Resource) UnregisterCustomAction(name string) error
- func (r *Resource) UnregisterCustomRecognition(name string) error
- func (r *Resource) UseAutoExecutionProvider() error
- func (r *Resource) UseCPU() error
- func (r *Resource) UseDirectml(deviceID InferenceDevice) error
- func (r *Resource) UseWebgpu(deviceID InferenceDevice) error
- type ResourceEventSink
- type ResourceLoadingDetail
- type ScreencapActionResult
- type ScreencapParam
- type ScreenshotOption
- func WithScreenshotResizeMethod(method ScreenshotResizeMethod) ScreenshotOption
- func WithScreenshotTargetExpand(width, height int32) ScreenshotOption
- func WithScreenshotTargetLongSide(targetLongSide int32) ScreenshotOption
- func WithScreenshotTargetShortSide(targetShortSide int32) ScreenshotOption
- func WithScreenshotUseRawSize(enabled bool) ScreenshotOption
- type ScreenshotResizeMethod
- type ScrollActionResult
- type ScrollParam
- type ShellActionResult
- type ShellParam
- type StartAppParam
- type Status
- type StopAppParam
- type StopTaskParam
- type StringList
- type SubRecognitionItem
- type SwipeActionResult
- type SwipeParam
- type SymbolLookupError
- type Target
- type TaskDetail
- type TaskJob
- func (j *TaskJob) Done() bool
- func (j *TaskJob) Error() error
- func (j *TaskJob) Failure() bool
- func (j *TaskJob) GetDetail() (*TaskDetail, error)
- func (j *TaskJob) Invalid() bool
- func (j *TaskJob) OverridePipeline(override any) error
- func (j *TaskJob) Pending() bool
- func (j *TaskJob) Running() bool
- func (j *TaskJob) Status() Status
- func (j *TaskJob) Success() bool
- func (j *TaskJob) Wait() *TaskJob
- type Tasker
- func (t *Tasker) AddContextSink(sink ContextEventSink) int64
- func (t *Tasker) AddSink(sink TaskerEventSink) int64
- func (t *Tasker) BindController(ctrl *Controller) error
- func (t *Tasker) BindResource(res *Resource) error
- func (t *Tasker) ClearCache() error
- func (t *Tasker) ClearContextSinks()
- func (t *Tasker) ClearSinks()
- func (t *Tasker) Destroy() error
- func (t *Tasker) GetActionDetail(actionId int64) (*ActionDetail, error)
- func (t *Tasker) GetController() *Controller
- func (t *Tasker) GetLatestNode(taskName string) (*NodeDetail, error)
- func (t *Tasker) GetNodeDetail(nodeId int64) (*NodeDetail, error)
- func (t *Tasker) GetRecognitionDetail(recId int64) (*RecognitionDetail, error)
- func (t *Tasker) GetResource() *Resource
- func (t *Tasker) GetTaskDetail(taskId int64) (*TaskDetail, error)
- func (t *Tasker) GetWaitFreezesDetail(wfId int64) (*WaitFreezesDetail, error)
- func (t *Tasker) Initialized() bool
- func (t *Tasker) OnNodeActionInContext(fn func(*Context, EventStatus, NodeActionDetail)) int64
- func (t *Tasker) OnNodeActionNodeInContext(fn func(*Context, EventStatus, NodeActionNodeDetail)) int64
- func (t *Tasker) OnNodeNextListInContext(fn func(*Context, EventStatus, NodeNextListDetail)) int64
- func (t *Tasker) OnNodePipelineNodeInContext(fn func(*Context, EventStatus, NodePipelineNodeDetail)) int64
- func (t *Tasker) OnNodeRecognitionInContext(fn func(*Context, EventStatus, NodeRecognitionDetail)) int64
- func (t *Tasker) OnNodeRecognitionNodeInContext(fn func(*Context, EventStatus, NodeRecognitionNodeDetail)) int64
- func (t *Tasker) OnNodeWaitFreezesInContext(fn func(*Context, EventStatus, NodeWaitFreezesDetail)) int64
- func (t *Tasker) OnTaskerTask(fn func(EventStatus, TaskerTaskDetail)) int64
- func (t *Tasker) PostAction(actionType ActionType, actionParam ActionParam, box Rect, ...) (*TaskJob, error)
- func (t *Tasker) PostRecognition(recType RecognitionType, recParam RecognitionParam, img image.Image) (*TaskJob, error)
- func (t *Tasker) PostStop() (*TaskJob, error)
- func (t *Tasker) PostTask(entry string, override ...any) (*TaskJob, error)
- func (t *Tasker) RemoveContextSink(sinkId int64)
- func (t *Tasker) RemoveSink(sinkId int64)
- func (t *Tasker) Running() bool
- func (t *Tasker) Stopping() bool
- type TaskerEventSink
- type TaskerTaskDetail
- type TemplateMatchMethod
- type TemplateMatchOrderBy
- type TemplateMatchParam
- type TemplateMatchResult
- type TouchActionResult
- type TouchDownParam
- type TouchMoveParam
- type TouchUpParam
- type WaitFreezesDetail
- type WaitFreezesParam
Examples ¶
Constants ¶
const ( EventResourceLoading = Event("Resource.Loading") EventControllerAction = Event("Controller.Action") EventTaskerTask = Event("Tasker.Task") EventNodePipelineNode = Event("Node.PipelineNode") EventNodeRecognitionNode = Event("Node.RecognitionNode") EventNodeActionNode = Event("Node.ActionNode") EventNodeNextList = Event("Node.NextList") EventNodeRecognition = Event("Node.Recognition") EventNodeAction = Event("Node.Action") // EventNodeWaitFreezes identifies wait-freezes lifecycle events: a single // Starting when the wait loop is entered and a Succeeded or Failed on // completion. There are no per-iteration progress events. EventNodeWaitFreezes = Event("Node.WaitFreezes") )
MaaFramework notification event families, matching the MaaMsg_* defines in the upstream MaaMsg.h one-to-one:
- EventResourceLoading: loading resource content; details decode as ResourceLoadingDetail.
- EventControllerAction: running a controller action; ControllerActionDetail.
- EventTaskerTask: running a pipeline task; TaskerTaskDetail.
- EventNodePipelineNode: a node of a running pipeline task; NodePipelineNodeDetail.
- EventNodeRecognitionNode, EventNodeActionNode: the dedicated recognition-only and action-only task types posted via Tasker.PostRecognition and Tasker.PostAction; NodeRecognitionNodeDetail and NodeActionNodeDetail.
- EventNodeNextList: scanning a node's next list; NodeNextListDetail.
- EventNodeRecognition, EventNodeAction: a recognition or action step within a node; NodeRecognitionDetail and NodeActionDetail.
- EventNodeWaitFreezes: see its own comment below.
Most families report Starting when the operation begins and Succeeded or Failed when it ends, with two upstream edge cases: a Controller.Action reports Starting and Succeeded only for focused actions (actions posted through the public Post methods are auto-focused upstream), while Failed is reported for every failed action; and a Node.Action may end without a terminal event when its task is stopped. Events with an unknown family name are ignored, and an event whose details fail to decode is dropped without invoking the sink. Detail payloads are decoded leniently: keys upstream adds beyond the documented detail fields are ignored.
const ( TemplateMatchOrderByHorizontal = TemplateMatchOrderBy(OrderByHorizontal) TemplateMatchOrderByVertical = TemplateMatchOrderBy(OrderByVertical) TemplateMatchOrderByScore = TemplateMatchOrderBy(OrderByScore) TemplateMatchOrderByRandom = TemplateMatchOrderBy(OrderByRandom) )
Template match result ordering options the native parser accepts: Horizontal, Vertical, Score, and Random.
const ( FeatureMatchOrderByHorizontal = FeatureMatchOrderBy(OrderByHorizontal) FeatureMatchOrderByVertical = FeatureMatchOrderBy(OrderByVertical) FeatureMatchOrderByScore = FeatureMatchOrderBy(OrderByScore) FeatureMatchOrderByArea = FeatureMatchOrderBy(OrderByArea) FeatureMatchOrderByRandom = FeatureMatchOrderBy(OrderByRandom) )
Feature match result ordering options the native parser accepts: Horizontal, Vertical, Score, Area, and Random.
const ( ColorMatchOrderByHorizontal = ColorMatchOrderBy(OrderByHorizontal) ColorMatchOrderByVertical = ColorMatchOrderBy(OrderByVertical) ColorMatchOrderByScore = ColorMatchOrderBy(OrderByScore) ColorMatchOrderByArea = ColorMatchOrderBy(OrderByArea) ColorMatchOrderByRandom = ColorMatchOrderBy(OrderByRandom) )
Color match result ordering options the native parser accepts: Horizontal, Vertical, Score, Area, and Random.
const ( OCROrderByHorizontal = OCROrderBy(OrderByHorizontal) OCROrderByVertical = OCROrderBy(OrderByVertical) OCROrderByArea = OCROrderBy(OrderByArea) OCROrderByLength = OCROrderBy(OrderByLength) OCROrderByRandom = OCROrderBy(OrderByRandom) OCROrderByExpected = OCROrderBy(OrderByExpected) )
OCR result ordering options the native parser accepts: Horizontal, Vertical, Area, Length, Random, and Expected. Expected orders results by their position in the Expected list, Length by matched text length.
const ( NeuralNetworkClassifyOrderByHorizontal = NeuralNetworkClassifyOrderBy(OrderByHorizontal) NeuralNetworkClassifyOrderByVertical = NeuralNetworkClassifyOrderBy(OrderByVertical) NeuralNetworkClassifyOrderByScore = NeuralNetworkClassifyOrderBy(OrderByScore) NeuralNetworkClassifyOrderByRandom = NeuralNetworkClassifyOrderBy(OrderByRandom) NeuralNetworkClassifyOrderByExpected = NeuralNetworkClassifyOrderBy(OrderByExpected) )
Neural network classification result ordering options the native parser accepts: Horizontal, Vertical, Score, Random, and Expected.
const ( NeuralNetworkDetectOrderByHorizontal = NeuralNetworkDetectOrderBy(OrderByHorizontal) NeuralNetworkDetectOrderByVertical = NeuralNetworkDetectOrderBy(OrderByVertical) NeuralNetworkDetectOrderByScore = NeuralNetworkDetectOrderBy(OrderByScore) NeuralNetworkDetectOrderByArea = NeuralNetworkDetectOrderBy(OrderByArea) NeuralNetworkDetectOrderByRandom = NeuralNetworkDetectOrderBy(OrderByRandom) NeuralNetworkDetectOrderByExpected = NeuralNetworkDetectOrderBy(OrderByExpected) )
Neural network detection result ordering options the native parser accepts: Horizontal, Vertical, Score, Area, Random, and Expected.
Variables ¶
var ( // ErrInvalidAgentClient reports an AgentClient method called on a nil // receiver. Destroy is exempt: calling it on nil returns nil. ErrInvalidAgentClient = errors.New("invalid agent client") // ErrInvalidResource reports BindResource or RegisterResourceSink // called with a nil *Resource. ErrInvalidResource = errors.New("invalid resource") // ErrInvalidController reports RegisterControllerSink called with a // zero-value Controller. ErrInvalidController = errors.New("invalid controller") // ErrInvalidTasker reports RegisterTaskerSink called with a zero-value // Tasker. ErrInvalidTasker = errors.New("invalid tasker") // ErrInvalidTimeout reports SetTimeout called with a negative duration. ErrInvalidTimeout = errors.New("timeout must be non-negative") )
var ( // ErrSetLogDir is returned when SetLogDir fails at the native layer. ErrSetLogDir = errors.New("failed to set log directory") // ErrSetSaveDraw is returned when SetSaveDraw fails at the native layer. ErrSetSaveDraw = errors.New("failed to set save draw option") // ErrSetStdoutLevel is returned when SetStdoutLevel fails at the native layer. ErrSetStdoutLevel = errors.New("failed to set stdout level") // ErrSetDebugMode is returned when SetDebugMode fails at the native layer. ErrSetDebugMode = errors.New("failed to set debug mode") // ErrSetSaveOnError is returned when SetSaveOnError fails at the native layer. ErrSetSaveOnError = errors.New("failed to set save on error option") // ErrSetDrawQuality is returned when SetDrawQuality fails at the native layer. ErrSetDrawQuality = errors.New("failed to set draw quality") // ErrSetRecoImageCacheLimit is returned when SetRecoImageCacheLimit fails at the native layer. ErrSetRecoImageCacheLimit = errors.New("failed to set recognition image cache limit") // ErrLoadPlugin is returned when LoadPlugin cannot load any plugin for the given path. ErrLoadPlugin = errors.New("failed to load plugin") // ErrEmptyLogDir is returned by SetLogDir when the path is empty. ErrEmptyLogDir = errors.New("log directory path is empty") )
var ErrBorrowed = errors.New("maa: borrowed object cannot be destroyed")
ErrBorrowed reports an attempt to destroy, bind, or register or unregister callbacks on a handle obtained from a getter or callback; such a view does not own the native object.
var ErrBound = errors.New("maa: object is bound to a tasker")
ErrBound reports an attempt to destroy an object another object still retains: a resource or controller bound to a tasker or retained by an AgentClient, or a tasker with an AgentClient registered as a sink.
var ErrClosed = errors.New("maa: object is closed")
ErrClosed reports an operation on a destroyed native object.
var ErrInCallback = errors.New("maa: object cannot be destroyed during a callback")
ErrInCallback reports an attempt to destroy an object from one of its callbacks.
var ErrInUse = errors.New("maa: object has an active call")
ErrInUse reports an attempt to destroy an object while a call or job is active, or to configure or start up an agent server that is active, joined, or detached. Destroy can be retried once the active work finishes; the agent server states cannot be retried into success.
var ErrLibraryInUse = errors.New("maa: cannot release libraries while native objects or the agent server are active")
ErrLibraryInUse reports an attempt to release the libraries while native objects remain alive, the Agent Server has not been shut down, or its service thread has been detached.
var ErrTaskerRunning = errors.New("maa: tasker is running")
ErrTaskerRunning reports an attempt to rebind a running tasker.
Functions ¶
func AgentServerAddContextSink ¶
func AgentServerAddContextSink(sink ContextEventSink) int64
AgentServerAddContextSink adds a context event callback sink and returns the sink ID. Configure before StartUp. It returns 0 on failure, including after ShutDown.
func AgentServerAddControllerSink ¶
func AgentServerAddControllerSink(sink ControllerEventSink) int64
AgentServerAddControllerSink adds a controller event callback sink and returns the sink ID. Configure before StartUp. It returns 0 on failure, including after ShutDown.
func AgentServerAddResourceSink ¶
func AgentServerAddResourceSink(sink ResourceEventSink) int64
AgentServerAddResourceSink adds a resource event callback sink and returns the sink ID. Configure before StartUp. It returns 0 on failure, including after ShutDown.
func AgentServerAddTaskerSink ¶
func AgentServerAddTaskerSink(sink TaskerEventSink) int64
AgentServerAddTaskerSink adds a tasker event callback sink and returns the sink ID. Configure before StartUp. It returns 0 on failure, including after ShutDown.
func AgentServerDetach ¶
func AgentServerDetach()
AgentServerDetach detaches the service thread started by AgentServerStartUp. StartUp already runs the service in a separate thread; Detach gives up the ability to wait for that thread to exit. Use it only when the service is intended to last for the lifetime of the process and Release is not needed. After Detach, AgentServerJoin cannot wait for the thread, and AgentServerShutDown cannot confirm its exit. Release returns ErrLibraryInUse for the rest of the process, even after Join or ShutDown. Detach waits for a concurrent AgentServerJoin; see that method.
func AgentServerJoin ¶
func AgentServerJoin()
AgentServerJoin waits for the attached service thread to end without requesting a stop. After AgentServerDetach, it returns without waiting.
Join holds the lifecycle lock, so concurrent AgentServerShutDown and AgentServerDetach calls wait until it returns. For client-controlled shutdown, let the paired client Disconnect, wait for Join to return, then call AgentServerShutDown to close the sockets before Release. For server-controlled shutdown, call AgentServerShutDown without entering a blocking Join.
func AgentServerRegisterCustomAction ¶
func AgentServerRegisterCustomAction(name string, action CustomActionRunner) error
AgentServerRegisterCustomAction registers a custom action runner. The name should match the custom_action field in Pipeline. Configure before StartUp. It returns ErrInUse while the server is active, joined, or detached, and ErrClosed after AgentServerShutDown of an attached or never-started server; a detached server keeps returning ErrInUse even after ShutDown. The native layer also rejects a name that is already registered, as a recognition or an action, surfaced as a generic error.
func AgentServerRegisterCustomRecognition ¶
func AgentServerRegisterCustomRecognition(name string, recognition CustomRecognitionRunner) error
AgentServerRegisterCustomRecognition registers a custom recognition runner. The name should match the custom_recognition field in Pipeline. Configure before StartUp. It returns ErrInUse while the server is active, joined, or detached, and ErrClosed after AgentServerShutDown of an attached or never-started server; a detached server keeps returning ErrInUse even after ShutDown. The native layer also rejects a name that is already registered, as a recognition or an action, surfaced as a generic error.
func AgentServerShutDown ¶
func AgentServerShutDown()
AgentServerShutDown requests that the MAA Agent Server stop. If its service thread is still attached, the native call waits for the thread to exit before closing its sockets. After AgentServerDetach, it cannot wait for the thread and closing the sockets may race with their use. It does not make Release safe after Detach. Without prior Detach, ShutDown permanently prevents startup and configuration, even if called before StartUp; repeated calls are no-ops.
ShutDown cannot interrupt a blocking AgentServerJoin; see that method for shutdown ordering.
func AgentServerStartUp ¶
AgentServerStartUp starts the MAA Agent Server in a separate native thread. It returns after starting the thread; call AgentServerJoin only when the caller needs to wait for the service to end.
The identifier is the rendezvous name used to match with AgentClient: the server connects to an IPC socket whose filename embeds the identifier, which the AgentClient binds. A purely numeric identifier in 1-65535 makes it connect to 127.0.0.1 on that port instead; an AgentClient must be listening there, see WithTcpPort. An empty identifier makes startup fail.
Lifecycle operations are serialized. Configuration functions (custom registration and the sink functions) are serialized with each other and with StartUp. See AgentServerJoin for shutdown ordering. Do not call lifecycle operations from server callbacks. After an attached server's ShutDown, StartUp returns ErrClosed for the rest of the process, including after Release and Init. It returns ErrInUse while the server is running, joined, or detached.
func ConfigInitOption ¶
ConfigInitOption initializes the toolkit option file under userPath. If <userPath>/config/maa_option.json does not exist, it is created from defaultJson; when the file already exists, defaultJson is ignored. defaultJson must be a valid JSON object whose keys are all optional: logging, save_draw, save_on_error, stdout_level, and draw_quality. The loaded options are applied to the global framework configuration, including the log directory <userPath>/debug when logging is enabled. An error is returned when defaultJson is not valid JSON or does not match the option schema, or when the file cannot be written or loaded.
func Init ¶
func Init(opts ...InitOption) (err error)
Init loads MaaFramework, MaaToolkit, MaaAgentServer, and MaaAgentClient and registers their functions. All four libraries must come from the same MaaFramework release compatible with this binding.
It must be called before invoking any other MAA-related functions. Once Init has succeeded, later calls to Init are no-ops and any options passed to them are discarded.
A missing library is reported by LibraryLoadError, and a missing required symbol by SymbolLookupError. Use errors.As to inspect these errors. On failure, Init attempts to unload the libraries it opened. If cleanup fails, its error is included in the returned error, and handles for libraries that could not be unloaded are retained. Call Release to retry cleanup before calling Init again.
Calls to Init and Release are serialized. Other MAA-related functions must not run concurrently with Init or Release.
On Windows, DLL search configuration changed through WithLibDir is not restored if initialization fails; see WithLibDir for its process-wide scope.
Note: If this function is not called before other MAA functions, it will trigger a null pointer panic.
func IsInited ¶
func IsInited() bool
IsInited checks if the MAA framework has been initialized. It is safe to call concurrently with Init and Release.
func LoadPlugin ¶
LoadPlugin loads a plugin specified by path. The path may be a full filesystem path or just a plugin name. A bare name is resolved against the directory of the loaded MaaFramework library first, then through the platform's dynamic-library search. If the path refers to a directory, plugins inside it are searched recursively, and the load fails with ErrLoadPlugin unless at least one plugin loads. Plugins in the "plugins" directory next to the MaaFramework library are loaded automatically when the library itself is loaded.
func MacOSCheckPermission ¶
func MacOSCheckPermission(perm MacOSPermission) bool
MacOSCheckPermission checks whether the given macOS permission has been granted.
func MacOSRequestPermission ¶
func MacOSRequestPermission(perm MacOSPermission) bool
MacOSRequestPermission requests the given macOS permission by showing the system prompt, and reports whether the permission is currently granted. It does not wait for the user's response, so it may return false even though the prompt was just shown.
func MacOSRevealPermissionSettings ¶
func MacOSRevealPermissionSettings(perm MacOSPermission) bool
MacOSRevealPermissionSettings opens the System Settings page for the given macOS permission. Returns true on success.
func Release ¶
func Release() error
Release releases the dynamic library resources of the MAA framework and unregisters its related functions. It returns ErrLibraryInUse while native objects remain alive or the Agent Server has not been shut down. After AgentServerDetach, Release remains blocked for the rest of the process, even after AgentServerJoin or AgentServerShutDown, because native thread exit cannot be confirmed. Calls to Init and Release are serialized. Other MAA-related functions must not run concurrently with Init or Release. If unloading fails, IsInited becomes false; call Release again to retry cleanup before calling Init. On Windows, Release does not restore the DLL search configuration changed during Init. A later Init with an empty library directory uses the process's current configuration; see WithLibDir.
func ResetJSONCodec ¶
func ResetJSONCodec()
ResetJSONCodec resets the global JSON encoder and decoder to encoding/json defaults.
func SetDebugMode ¶
SetDebugMode sets whether to enable debug mode.
func SetDrawQuality ¶
SetDrawQuality sets image quality for draw images. Default value is 85, range: [0, 100]. Values outside the range fail with ErrSetDrawQuality instead of being clamped.
func SetJSONDecoder ¶
func SetJSONDecoder(decoder JSONDecoder)
SetJSONDecoder sets the global JSON decoder used by this package.
The decoder must satisfy the compatibility requirements documented by JSONDecoder, including ignoring unknown fields.
func SetJSONEncoder ¶
func SetJSONEncoder(encoder JSONEncoder)
SetJSONEncoder sets the global JSON encoder used by this package.
The encoder must satisfy the compatibility requirements documented by JSONEncoder, including support for "omitzero" and IsZero() methods.
func SetRecoImageCacheLimit ¶
SetRecoImageCacheLimit sets recognition image cache limit. Default value is 4096.
func SetSaveOnError ¶
SetSaveOnError sets whether to save screenshot on error.
func SetStdoutLevel ¶
func SetStdoutLevel(level LoggingLevel) error
SetStdoutLevel sets the level of log output to stdout.
Types ¶
type Action ¶
type Action struct {
// Type specifies the action type.
Type ActionType `json:"type,omitempty"`
// Param specifies the action parameters.
// A nil Param omits param when encoding. For unknown types, an explicit JSON null is retained.
Param ActionParam `json:"param,omitempty"`
}
Action defines a node's action using the pipeline v2 type/param object format. Known types decode to their typed parameters. Unrecognized type names retain their parameter JSON as *RawActionParam; this does not establish native support. Unknown fields outside param, and unmodeled fields of known parameters, are not retained. Known parameter fields accept their canonical JSON forms plus the protocol's shorthand forms the native parser tolerates (single values in place of lists); all of them normalize to the canonical list shapes this package emits.
func ActClick ¶
func ActClick(p ClickParam) *Action
ActClick creates a Click action. Pass a zero value for defaults.
func ActClickKey ¶
ActClickKey creates a ClickKey action with the given virtual key codes.
func ActCommand ¶
func ActCommand(p CommandParam) *Action
ActCommand creates a Command action with the given parameters.
func ActCustom ¶
func ActCustom(p CustomActionParam) *Action
ActCustom creates a Custom action with the given parameters.
func ActDoNothing ¶
func ActDoNothing() *Action
ActDoNothing creates a DoNothing action that performs no operation.
func ActInputText ¶
ActInputText creates an InputText action with the given text.
func ActKeyDown ¶
ActKeyDown creates a KeyDown action that presses the key without releasing.
func ActLongPress ¶
func ActLongPress(p LongPressParam) *Action
ActLongPress creates a LongPress action. Pass a zero value for defaults.
func ActLongPressKey ¶
func ActLongPressKey(p LongPressKeyParam) *Action
ActLongPressKey creates a LongPressKey action with the given parameters.
func ActMultiSwipe ¶
func ActMultiSwipe(swipes ...MultiSwipeItem) *Action
ActMultiSwipe creates a MultiSwipe action for multi-finger swipe gestures.
func ActScreencap ¶
func ActScreencap(p ScreencapParam) *Action
ActScreencap creates a Screencap action. Pass a zero value for defaults.
func ActScroll ¶
func ActScroll(p ScrollParam) *Action
ActScroll creates a Scroll action. Pass a zero value for defaults.
func ActShell ¶
ActShell creates a Shell action with the given command. To specify a timeout, set the returned action's Param to a ShellParam with ShellTimeout. Only controllers that support shell commands (in practice, ADB controllers) can run it; other controller types fail. The output of the command can be obtained in the action detail by MaaTaskerGetActionDetail.
func ActStartApp ¶
ActStartApp creates a StartApp action with the given package name or activity.
func ActStopApp ¶
ActStopApp creates a StopApp action with the given package name.
func ActStopTask ¶
func ActStopTask() *Action
ActStopTask creates a StopTask action that stops the current task chain.
func ActSwipe ¶
func ActSwipe(p SwipeParam) *Action
ActSwipe creates a Swipe action. Pass a zero value for defaults.
func ActTouchDown ¶
func ActTouchDown(p TouchDownParam) *Action
ActTouchDown creates a TouchDown action. Pass a zero value for defaults.
func ActTouchMove ¶
func ActTouchMove(p TouchMoveParam) *Action
ActTouchMove creates a TouchMove action. Pass a zero value for defaults.
func ActTouchUp ¶
ActTouchUp creates a TouchUp action. contact is the touch point identifier (0 for default).
func (*Action) UnmarshalJSON ¶
UnmarshalJSON decodes a pipeline v2 action. Errors in known parameter types are returned without falling back to raw JSON. On error the action is unchanged. When "param" is absent, parameters are decoded from the whole action object, matching the native parser, so flat fields such as {"type":"Click","contact":1} are preserved instead of silently lost.
type ActionDetail ¶
type ActionDetail struct {
ID int64
Name string
Action string
Box Rect
Success bool
DetailJson string
Result *ActionResult
}
ActionDetail contains the detail returned for an executed action.
type ActionParam ¶
type ActionParam interface {
// contains filtered or unexported methods
}
ActionParam is the interface for typed action parameters and RawActionParam. Omitted fields inherit the existing node's values when its action type is unchanged; otherwise they use the action's defaults from default_pipeline.json, falling back to the framework defaults documented on each field. Nil optional pointers omit the field; non-nil pointers send their value, including zero or false. Field-specific exceptions are documented separately.
type ActionResult ¶
type ActionResult struct {
// contains filtered or unexported fields
}
ActionResult wraps parsed action detail.
func (*ActionResult) AsApp ¶
func (r *ActionResult) AsApp() (*AppActionResult, bool)
AsApp returns the app detail and true if the action type is StartApp or StopApp.
func (*ActionResult) AsClick ¶
func (r *ActionResult) AsClick() (*ClickActionResult, bool)
AsClick returns the click detail and true if the action type is Click.
func (*ActionResult) AsClickKey ¶
func (r *ActionResult) AsClickKey() (*ClickKeyActionResult, bool)
AsClickKey returns the key detail and true if the action type is ClickKey, KeyDown, or KeyUp.
func (*ActionResult) AsInputText ¶
func (r *ActionResult) AsInputText() (*InputTextActionResult, bool)
AsInputText returns the input text detail and true if the action type is InputText.
func (*ActionResult) AsLongPress ¶
func (r *ActionResult) AsLongPress() (*LongPressActionResult, bool)
AsLongPress returns the long press detail and true if the action type is LongPress.
func (*ActionResult) AsLongPressKey ¶
func (r *ActionResult) AsLongPressKey() (*LongPressKeyActionResult, bool)
AsLongPressKey returns the long press key detail and true if the action type is LongPressKey.
func (*ActionResult) AsMultiSwipe ¶
func (r *ActionResult) AsMultiSwipe() (*MultiSwipeActionResult, bool)
AsMultiSwipe returns the multi-swipe detail and true if the action type is MultiSwipe.
func (*ActionResult) AsScreencap ¶
func (r *ActionResult) AsScreencap() (*ScreencapActionResult, bool)
AsScreencap returns the screencap detail and true if the action type is Screencap.
func (*ActionResult) AsScroll ¶
func (r *ActionResult) AsScroll() (*ScrollActionResult, bool)
AsScroll returns the scroll detail and true if the action type is Scroll.
func (*ActionResult) AsShell ¶
func (r *ActionResult) AsShell() (*ShellActionResult, bool)
AsShell returns the shell detail and true if the action type is Shell.
func (*ActionResult) AsSwipe ¶
func (r *ActionResult) AsSwipe() (*SwipeActionResult, bool)
AsSwipe returns the swipe detail and true if the action type is Swipe.
func (*ActionResult) AsTouch ¶
func (r *ActionResult) AsTouch() (*TouchActionResult, bool)
AsTouch returns the touch detail and true if the action type is TouchDown, TouchMove, or TouchUp.
func (*ActionResult) Type ¶
func (r *ActionResult) Type() ActionType
Type returns the action type of the result.
func (*ActionResult) Value ¶
func (r *ActionResult) Value() any
Value returns the underlying value of the result.
type ActionType ¶
type ActionType string
ActionType names a pipeline v2 action. Constants identify the types modeled by this package; other names may be used with RawActionParam if the native library supports them.
const ( ActionTypeDoNothing ActionType = "DoNothing" ActionTypeClick ActionType = "Click" ActionTypeLongPress ActionType = "LongPress" ActionTypeSwipe ActionType = "Swipe" ActionTypeMultiSwipe ActionType = "MultiSwipe" ActionTypeTouchDown ActionType = "TouchDown" ActionTypeTouchMove ActionType = "TouchMove" ActionTypeTouchUp ActionType = "TouchUp" ActionTypeClickKey ActionType = "ClickKey" ActionTypeLongPressKey ActionType = "LongPressKey" ActionTypeKeyDown ActionType = "KeyDown" ActionTypeKeyUp ActionType = "KeyUp" ActionTypeInputText ActionType = "InputText" ActionTypeStartApp ActionType = "StartApp" ActionTypeStopApp ActionType = "StopApp" ActionTypeStopTask ActionType = "StopTask" ActionTypeScroll ActionType = "Scroll" ActionTypeCommand ActionType = "Command" ActionTypeShell ActionType = "Shell" ActionTypeScreencap ActionType = "Screencap" ActionTypeCustom ActionType = "Custom" )
Pipeline v2 action types.
type AdbDevice ¶
type AdbDevice struct {
// Name is a human-readable device label, typically in the form
// "<serial>-<emulator name or adb path>". Some Windows emulator
// finders use the emulator instance name in place of the serial.
Name string
// AdbPath is the path of the ADB executable used to query the device.
AdbPath string
// Address is the ADB serial of the device.
Address string
// ScreencapMethod is the bitmask of screencap methods the device
// supports. See the controller/adb package for the bit definitions.
ScreencapMethod adb.ScreencapMethod
// InputMethod is the bitmask of input methods the device supports.
// See the controller/adb package for the bit definitions.
InputMethod adb.InputMethod
// Config is a JSON object string generated by the discovery process.
// It carries emulator-specific parameters such as extras.mumu,
// extras.ld, extras.avd, extras.androws, command.StartApp, and
// command.Orientation. Pass it as the config argument of
// NewAdbController when creating a controller for this device.
Config string
}
AdbDevice represents a single ADB device discovered by the toolkit.
func FindAdbDevices ¶
FindAdbDevices finds ADB devices. If specifiedAdb is given, only the first value is used and discovery is restricted to that ADB executable; extra values are ignored. Without it, all known emulators and the adb executable from the PATH are queried. An empty slice with a nil error means no devices were found; the device order is unspecified.
type AgentClient ¶
type AgentClient struct {
// contains filtered or unexported fields
}
AgentClient is used to connect to AgentServer, delegating custom recognition and action execution to a separate process. This allows separating MaaFW core from custom logic into independent processes.
The client retains its bound resource and registered event sources until Destroy. Client lifecycle operations — binding, sink registration, connection, and Destroy — are not serialized by this wrapper; callers must serialize them.
func NewAgentClient ¶
func NewAgentClient(opts ...AgentClientOption) (*AgentClient, error)
NewAgentClient creates an Agent client instance with specified options. At least one creation option (WithIdentifier or WithTcpPort) should be provided. If none is provided, it defaults to identifier mode with an empty identifier.
See WithIdentifier and WithTcpPort for priority rules when both are specified.
func (*AgentClient) Alive ¶
func (ac *AgentClient) Alive() bool
Alive reports whether the communication channel to the Agent server is still ready. It probes the local channel, not a heartbeat, so it may keep returning true briefly for a server that has exited.
func (*AgentClient) BindResource ¶
func (ac *AgentClient) BindResource(res *Resource) error
BindResource links the Agent client to the specified resource.
func (*AgentClient) Connect ¶
func (ac *AgentClient) Connect() error
Connect connects to the Agent server.
A resource must be bound with BindResource first; the native layer fails the connection otherwise. On success Connect performs the protocol handshake and registers the Agent server's custom recognition and action list on the bound resource. Communication waits use the timeout set by AgentClient.SetTimeout; each wait has its own timeout, so the whole connection attempt can take longer. The default timeout is effectively unlimited.
func (*AgentClient) Connected ¶
func (ac *AgentClient) Connected() bool
Connected checks if the client is connected to the Agent server.
func (*AgentClient) Destroy ¶
func (ac *AgentClient) Destroy() error
Destroy releases the client and its references to native objects once; repeated successful calls are safe. It returns ErrInUse while a client call is active; retry after the call ends.
func (*AgentClient) Disconnect ¶
func (ac *AgentClient) Disconnect() error
Disconnect disconnects from the Agent server.
func (*AgentClient) GetCustomActionList ¶
func (ac *AgentClient) GetCustomActionList() ([]string, error)
GetCustomActionList returns the custom action name list of the agent client. The list is empty until Connect has succeeded.
func (*AgentClient) GetCustomRecognitionList ¶
func (ac *AgentClient) GetCustomRecognitionList() ([]string, error)
GetCustomRecognitionList returns the custom recognition name list of the agent client. The list is empty until Connect has succeeded.
func (*AgentClient) Identifier ¶
func (ac *AgentClient) Identifier() (string, error)
Identifier returns the identifier of the current agent client. In TCP mode it returns the bound port as a string; see WithTcpPort.
func (*AgentClient) RegisterControllerSink ¶
func (ac *AgentClient) RegisterControllerSink(ctrl Controller) error
RegisterControllerSink registers a sink on the controller so that its lifecycle events are forwarded to the connected Agent server. Each call replaces the sink previously registered by this client for the controller, and Disconnect clears the sinks registered on the client.
Passing an object borrowed inside an AgentClient callback fails with ErrBorrowed, a deliberate lifetime restriction: the client cannot keep callback-scoped handles alive.
func (*AgentClient) RegisterResourceSink ¶
func (ac *AgentClient) RegisterResourceSink(res *Resource) error
RegisterResourceSink registers a sink on the resource so that its lifecycle events are forwarded to the connected Agent server. Each call replaces the sink previously registered by this client for the resource, and Disconnect clears the sinks registered on the client.
Passing an object borrowed inside an AgentClient callback fails with ErrBorrowed, a deliberate lifetime restriction: the client cannot keep callback-scoped handles alive.
func (*AgentClient) RegisterTaskerSink ¶
func (ac *AgentClient) RegisterTaskerSink(tasker Tasker) error
RegisterTaskerSink registers a sink on the tasker so that its lifecycle events are forwarded to the connected Agent server. It also forwards context events: the native layer registers a context sink on the same tasker. Each call replaces the sink previously registered by this client for the tasker, and Disconnect clears the sinks registered on the client.
Passing an object borrowed inside an AgentClient callback fails with ErrBorrowed, a deliberate lifetime restriction: the client cannot keep callback-scoped handles alive.
func (*AgentClient) SetTimeout ¶
func (ac *AgentClient) SetTimeout(duration time.Duration) error
SetTimeout sets this client's timeout for each native communication wait with the Agent server. Connect, Disconnect, and other remote calls can perform multiple waits and process requests or callbacks between them, so an operation's total duration can exceed this timeout.
Durations are converted to whole milliseconds; a positive sub-millisecond duration is rounded up to one millisecond. A negative duration is rejected with ErrInvalidTimeout. The native layer would instead treat a negative timeout as unlimited; pass a very large duration to approximate that.
type AgentClientOption ¶
type AgentClientOption func(*agentClientConfig)
AgentClientOption configures how an Agent client is created.
func WithIdentifier ¶
func WithIdentifier(identifier string) AgentClientOption
WithIdentifier sets the client identifier for creating an agent client. The identifier is used to identify this specific client instance. In identifier mode the rendezvous is an IPC socket whose filename embeds the identifier, except that a purely numeric identifier in 1-65535 is treated as a TCP port number that the client binds, instead of an IPC socket name. The identifier creation mode will fall back to TCP on older Windows versions that do not support AF_UNIX (builds prior to 17063); in that fallback the client binds an auto-selected port and Identifier returns that port string rather than the passed identifier. If empty, an identifier will be automatically generated.
Priority: This option takes precedence for creation mode if specified after WithTcpPort. If specified before WithTcpPort, WithTcpPort will override it.
func WithTcpPort ¶
func WithTcpPort(port uint16) AgentClientOption
WithTcpPort sets the TCP port for creating a TCP-based agent client. The client listens on 127.0.0.1:port and the Agent server connects to it, so the server must be started with the same port number as its identifier, e.g. AgentServerStartUp("5555"). A port of 0 lets the system auto-select a port; Identifier then returns the bound port as a string.
Priority: This option takes precedence for creation mode if specified after WithIdentifier. If specified before WithIdentifier, WithIdentifier will override it.
type AndRecognitionParam ¶
type AndRecognitionParam struct {
// AllOf lists the sub-recognitions that must all succeed. Elements are
// node name references or inline recognitions (SubRecognitionItem).
AllOf []SubRecognitionItem `json:"all_of,omitempty"`
// BoxIndex selects which all_of result's box to use as the final box.
// The native parser requires 0 <= box_index < len(all_of); the default 0
// uses the first result.
BoxIndex int `json:"box_index,omitempty"`
}
AndRecognitionParam defines parameters for AND recognition. AllOf elements are either node name strings or inline recognitions.
type AppActionResult ¶
type AppActionResult struct {
Package string `json:"package"`
}
AppActionResult holds the parsed detail of StartApp and StopApp actions.
type BlankController ¶
type BlankController struct{}
BlankController is a no-op CustomController for testing: every method reports success without performing any action. It is designed to be embedded in test controller types that override only the methods under test. Observable behavior worth knowing:
- Screencap returns a 1280x720 image; after the native round-trip it is opaque black (alpha is dropped on the RGBA-to-BGR conversion and forced back to 255 on decoding).
- RequestUUID returns "blank-controller" for every instance, so controllers are not distinguishable by UUID.
- Connected reports true unconditionally, even before Connect.
- GetInfo returns {"type":"blank"}, but the framework overwrites the "type" key with "custom" for every custom controller, so Controller.GetInfo always reports type "custom".
func (*BlankController) Click ¶
func (c *BlankController) Click(x int32, y int32) bool
Click implements CustomController.
func (*BlankController) ClickKey ¶
func (c *BlankController) ClickKey(keycode int32) bool
ClickKey implements CustomController.
func (*BlankController) Connect ¶
func (c *BlankController) Connect() bool
Connect implements CustomController.
func (*BlankController) Connected ¶
func (c *BlankController) Connected() bool
Connected implements CustomController.
func (*BlankController) GetFeature ¶
func (c *BlankController) GetFeature() ControllerFeature
GetFeature implements CustomController.
func (*BlankController) GetInfo ¶
func (c *BlankController) GetInfo() (string, bool)
GetInfo implements CustomController.
func (*BlankController) Inactive ¶
func (c *BlankController) Inactive() bool
Inactive implements CustomController.
func (*BlankController) InputText ¶
func (c *BlankController) InputText(text string) bool
InputText implements CustomController.
func (*BlankController) KeyDown ¶
func (c *BlankController) KeyDown(keycode int32) bool
KeyDown implements CustomController.
func (*BlankController) KeyUp ¶
func (c *BlankController) KeyUp(keycode int32) bool
KeyUp implements CustomController.
func (*BlankController) RelativeMove ¶
func (c *BlankController) RelativeMove(dx int32, dy int32) bool
RelativeMove implements CustomController.
func (*BlankController) RequestUUID ¶
func (c *BlankController) RequestUUID() (string, bool)
RequestUUID implements CustomController.
func (*BlankController) Screencap ¶
func (c *BlankController) Screencap() (image.Image, bool)
Screencap implements CustomController. It returns a blank 1280x720 image, opaque black after the native round-trip.
func (*BlankController) Scroll ¶
func (c *BlankController) Scroll(dx int32, dy int32) bool
Scroll implements CustomController.
func (*BlankController) Shell ¶
func (c *BlankController) Shell(cmd string, timeout int64) (string, bool)
Shell implements CustomController.
func (*BlankController) StartApp ¶
func (c *BlankController) StartApp(intent string) bool
StartApp implements CustomController.
func (*BlankController) StopApp ¶
func (c *BlankController) StopApp(intent string) bool
StopApp implements CustomController.
func (*BlankController) TouchUp ¶
func (c *BlankController) TouchUp(contact int32) bool
TouchUp implements CustomController.
type ClassSelector ¶
type ClassSelector struct {
// contains filtered or unexported fields
}
ClassSelector selects a neural network class by index or label. Its zero value selects class index 0.
func ClassIndex ¶
func ClassIndex(index int) ClassSelector
ClassIndex selects a class by its numeric index.
func ClassLabel ¶
func ClassLabel(label string) ClassSelector
ClassLabel selects a class by its label.
func (ClassSelector) AsIndex ¶
func (c ClassSelector) AsIndex() (int, error)
AsIndex returns the index, or an error if the selector holds a label.
func (ClassSelector) AsLabel ¶
func (c ClassSelector) AsLabel() (string, error)
AsLabel returns the label, or an error if the selector holds an index.
func (ClassSelector) IsIndex ¶
func (c ClassSelector) IsIndex() bool
IsIndex reports whether the selector selects by class index.
func (ClassSelector) IsLabel ¶
func (c ClassSelector) IsLabel() bool
IsLabel reports whether the selector selects by class label.
func (ClassSelector) MarshalJSON ¶
func (c ClassSelector) MarshalJSON() ([]byte, error)
MarshalJSON encodes a selector as an integer or string. It returns an error for an index outside the int32 range, which the pipeline parser rejects.
func (*ClassSelector) UnmarshalJSON ¶
func (c *ClassSelector) UnmarshalJSON(data []byte) error
UnmarshalJSON accepts only an integer or string and leaves c unchanged on error. Indexes are limited to the int32 range the pipeline parser accepts.
type ClassSelectors ¶
type ClassSelectors []ClassSelector
ClassSelectors is an ordered list of class indices and labels. JSON input may be a single integer or string, or an array of either. Non-nil lists marshal as arrays. In neural network parameters, nil is omitted to inherit the existing/default selection; an empty non-nil list clears the selection, matching all classes (detection results are still threshold-filtered).
func (*ClassSelectors) UnmarshalJSON ¶
func (c *ClassSelectors) UnmarshalJSON(data []byte) error
UnmarshalJSON normalizes a scalar to a one-element list. Invalid input, including null, leaves the receiver unchanged.
type ClickActionResult ¶
type ClickActionResult struct {
Point Point `json:"point"`
Contact int `json:"contact"`
// Pressure is kept to match MaaFramework raw detail JSON.
Pressure int `json:"pressure"`
}
ClickActionResult holds the parsed detail of a Click action.
type ClickKeyActionResult ¶
ClickKeyActionResult holds the parsed detail of ClickKey, KeyDown, and KeyUp actions.
type ClickKeyParam ¶
type ClickKeyParam struct {
// Key specifies the virtual key codes to click. Required.
// JSON input may be a single key code or an array; a single value
// normalizes to a one-element array.
Key []int `json:"key,omitempty"`
}
ClickKeyParam defines parameters for key click action.
func (*ClickKeyParam) UnmarshalJSON ¶
func (p *ClickKeyParam) UnmarshalJSON(data []byte) error
UnmarshalJSON normalizes a single key code to a one-element array. An omitted key retains its existing value. On error the param is unchanged.
type ClickParam ¶
type ClickParam struct {
// Target specifies the click target position.
Target Target `json:"target,omitzero"`
// TargetOffset specifies additional offset applied to target.
// JSON accepts [x, y], which expands to a 1x1 offset at (x, y), or [x, y, w, h];
// the zero value omits the field, so the pipeline default or parent-node inheritance applies.
TargetOffset Rect `json:"target_offset,omitzero"`
// Contact specifies the touch point identifier. Adb: finger index (0=first finger). Win32: mouse button (0=left, 1=right, 2=middle).
Contact int `json:"contact,omitempty"`
// Pressure specifies touch pressure; its range depends on the controller.
// Framework default: 1. Nil inherits as described in [ActionParam];
// a pointer to 0 sends zero explicitly.
Pressure *int `json:"pressure,omitempty"`
}
ClickParam defines parameters for click action.
type ColorMatchMethod ¶
type ColorMatchMethod int
ColorMatchMethod defines the color space for color matching (cv::ColorConversionCodes).
const ( ColorMatchMethodRGB ColorMatchMethod = 4 // RGB color space, 3 channels (default) ColorMatchMethodHSV ColorMatchMethod = 40 // HSV color space, 3 channels ColorMatchMethodGRAY ColorMatchMethod = 6 // Grayscale, 1 channel )
Color spaces with the channel count each implies for the lower/upper bounds. Default: 4 (RGB).
type ColorMatchOrderBy ¶
type ColorMatchOrderBy OrderBy
ColorMatchOrderBy defines the ordering options for color matching results.
type ColorMatchParam ¶
type ColorMatchParam struct {
// ROI specifies the region of interest for recognition.
ROI Target `json:"roi,omitzero"`
// ROIOffset specifies an offset applied to ROI. The zero value is omitted
// to inherit the existing/default offset; an explicit zero offset cannot
// be expressed with this value-type field.
ROIOffset Rect `json:"roi_offset,omitzero"`
// Method specifies the color space. 4: RGB (default), 40: HSV, 6: GRAY.
Method ColorMatchMethod `json:"method,omitempty"`
// Lower specifies the color lower bounds. Required. Inner array length must match method channels.
// JSON input may be a single flat row of channel values; a flat row
// normalizes to one row.
Lower [][]int `json:"lower,omitempty"`
// Upper specifies the color upper bounds. Required. Inner array length must match method channels.
// JSON input may be a single flat row of channel values; a flat row
// normalizes to one row.
Upper [][]int `json:"upper,omitempty"`
// Count specifies the minimum pixel count required (threshold). Default: 1.
Count int `json:"count,omitempty"`
// OrderBy specifies how results are sorted. Default: Horizontal. Options: Horizontal | Vertical | Score | Area | Random.
OrderBy ColorMatchOrderBy `json:"order_by,omitempty"`
// Index specifies which match to select from results.
Index int `json:"index,omitempty"`
// Connected enables connected component analysis. Default: false.
Connected bool `json:"connected,omitempty"`
}
ColorMatchParam defines parameters for color matching recognition.
func (*ColorMatchParam) UnmarshalJSON ¶
func (p *ColorMatchParam) UnmarshalJSON(data []byte) error
UnmarshalJSON normalizes the flat single-row lower/upper form to one row, matching the native parser. Omitted fields retain their existing values. On error the param is unchanged.
type ColorMatchResult ¶
ColorMatchResult is the decoded ColorMatch result from a recognition detail JSON, with keys box and count.
type CommandParam ¶
type CommandParam struct {
// Exec specifies the program path to execute. Required.
Exec string `json:"exec,omitempty"`
// Args specifies the command arguments. Supports runtime placeholders:
// {ENTRY}: task entry name, {NODE}: current node name,
// {IMAGE}: screenshot file path, {BOX}: recognition target [x,y,w,h],
// {RESOURCE_DIR}: last loaded resource directory, {LIBRARY_DIR}: MaaFW library directory.
// JSON input may be a single argument or an array; a single value
// normalizes to a one-element array.
Args []string `json:"args,omitempty"`
// Detach enables detached mode to run without waiting for completion. Default: false.
Detach bool `json:"detach,omitempty"`
}
CommandParam defines parameters for command execution action.
func (*CommandParam) UnmarshalJSON ¶
func (p *CommandParam) UnmarshalJSON(data []byte) error
UnmarshalJSON normalizes a single argument to a one-element array. Omitted fields retain their existing values. On error the param is unchanged.
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context provides the runtime context for custom actions/recognitions and exposes task, recognition, action, and pipeline operations. A Context received in a callback, including a Clone, is valid only until that callback returns. Keep results rather than retaining the Context. Operations on the same Context are not serialized by this wrapper — the underlying native context is unsynchronized, so callers must serialize them themselves. Once the callback has returned, operations fail with ErrClosed.
func (*Context) ClearHitCount ¶
ClearHitCount clears the hit count of a node by name. An unknown node name is not an error.
func (*Context) Clone ¶
Clone clones the current Context. The clone has the same callback lifetime. It returns nil if the context is no longer usable or the native clone fails.
func (*Context) GetAnchor ¶
GetAnchor gets an anchor by name. It returns an error if the anchor is not set.
func (*Context) GetHitCount ¶
GetHitCount gets the hit count of a node by name. An unknown node reports a count of zero without error.
func (*Context) GetNode ¶
GetNode returns the node definition by name. It fetches the node JSON from the current pipeline and unmarshals it into a Node struct. The node dump does not carry the node name, so Name is set to name; a node without attach data gets an empty, non-nil Attach map.
func (*Context) GetNodeJSON ¶
GetNodeJSON gets the node JSON by name.
func (*Context) GetTaskJob ¶
GetTaskJob returns the job of the current task. If the context is no longer usable, it returns a failed job carrying the error rather than nil.
func (*Context) GetTasker ¶
GetTasker returns a borrowed view of the current Tasker. Destroy must not be called on the returned value. It returns nil if the context is no longer usable.
func (*Context) OverrideImage ¶
OverrideImage overrides an image by name.
func (*Context) OverrideNext ¶
OverrideNext overrides the next list of a node by name. An empty or nil nextList clears the node's next list. If the underlying call fails (e.g., node not found or list invalid), it returns an error.
func (*Context) OverridePipeline ¶
OverridePipeline overrides the current pipeline definition. The override parameter can be a JSON string, raw JSON bytes, a Pipeline, or any data type that can be marshaled to JSON. The resulting JSON must be a JSON object keyed by node names; arrays are rejected by the native side. If override is nil, an empty JSON object will be used, which leaves the current pipeline definition unchanged.
Example 1:
pipeline := NewPipeline()
node := NewNode("Task").SetAction(ActDoNothing())
pipeline.AddNode(node)
ctx.OverridePipeline(pipeline)
Example 2:
ctx.OverridePipeline(map[string]any{
"Task": map[string]any{
"action": "Click",
"target": []int{100, 200, 100, 100},
},
})
Example 3:
ctx.OverridePipeline(`{"Task":{"action":"Click","target":[100,200,100,100]}}`)
func (*Context) RunAction ¶
func (ctx *Context) RunAction( entry string, box Rect, recognitionDetail string, override ...any, ) (*ActionDetail, error)
RunAction runs an action by entry name and returns its detail. It accepts an entry string and an optional override parameter which can be a JSON string, raw JSON bytes, or any data type that can be marshaled to JSON. The override must be a JSON object (map); this is enforced by the native side, so a non-object override fails with a generic run error. If the override value is nil, an empty JSON object will be used. If multiple overrides are provided, only the first one will be used. If the override value cannot be marshaled to JSON, an error is returned and the action is not run. recognitionDetail should be a JSON string for the previous recognition detail (e.g., RecognitionDetail.DetailJson). Pass "" if not available.
Example 1:
pipeline := NewPipeline()
node := NewNode("Task").
SetAction(ActClick(ClickParam{Target: NewTargetRect(Rect{100, 200, 100, 100})}))
pipeline.AddNode(node)
ctx.RunAction(node.Name, box, recognitionDetail, pipeline)
Example 2:
ctx.RunAction("Task", box, recognitionDetail, map[string]any{
"Task": map[string]any{
"action": "Click",
"target": []int{100, 200, 100, 100},
}
})
Example 3:
ctx.RunAction("Task", box, recognitionDetail, `{"Task":{"action":"Click","target":[100, 200, 100, 100]}}`)
func (*Context) RunActionDirect ¶
func (ctx *Context) RunActionDirect( actionType ActionType, actionParam ActionParam, box Rect, recoDetail *RecognitionDetail, ) (*ActionDetail, error)
RunActionDirect runs action directly by type and parameters, without a pipeline entry. It accepts an action type string (e.g., "Click", "Swipe"), an action parameter that will be marshaled to JSON, a box for the action position, and recognition details. If action parameters or recognition details are nil, they will be marshaled to JSON null: a null action parameter means the action's default parameters are used, and a null recognition detail is treated as absent. A non-nil recognition detail is marshaled as an opaque JSON payload (see RecognitionDetail).
Example:
actParam := &ClickParam{Target: NewTargetRect(Rect{100, 200, 100, 100})}
box := Rect{100, 200, 100, 100}
ctx.RunActionDirect(ActionTypeClick, actParam, box, nil)
func (*Context) RunRecognition ¶
func (ctx *Context) RunRecognition( entry string, img image.Image, override ...any, ) (*RecognitionDetail, error)
RunRecognition runs a recognition by entry name and returns its detail. It accepts an entry string and an optional override parameter which can be a JSON string, raw JSON bytes, or any data type that can be marshaled to JSON. The override must be a JSON object (map); this is enforced by the native side, so a non-object override fails with a generic run error. If the override value is nil, an empty JSON object will be used. If multiple overrides are provided, only the first one will be used. If the override value cannot be marshaled to JSON, an error is returned and the recognition is not run. The image must not be empty; an empty image is rejected by the native side.
Example 1:
pipeline := NewPipeline()
node := NewNode("Task").
SetRecognition(RecOCR(OCRParam{Expected: []string{"Hello"}}))
pipeline.AddNode(node)
ctx.RunRecognition(node.Name, img, pipeline)
Example 2:
ctx.RunRecognition("Task", img, map[string]any{
"Task": map[string]any{
"recognition": "OCR",
"expected": "Hello",
}
})
Example 3:
ctx.RunRecognition("Task", img, `{"Task":{"recognition":"OCR","expected":"Hello"}}`)
func (*Context) RunRecognitionDirect ¶
func (ctx *Context) RunRecognitionDirect( recoType RecognitionType, recoParam RecognitionParam, img image.Image, ) (*RecognitionDetail, error)
RunRecognitionDirect runs recognition directly by type and parameters, without a pipeline entry. It accepts a recognition type (e.g., RecognitionTypeOCR, RecognitionTypeTemplateMatch), a recognition parameter implementing RecognitionParam (marshaled to JSON), and an image. recoParam may be nil; it is then marshaled as JSON null, which the native side treats as an unspecified parameter, so the recognition's default parameters are used.
Example:
recParam := &OCRParam{Expected: []string{"Hello"}}
detail, err := ctx.RunRecognitionDirect(RecognitionTypeOCR, recParam, img)
func (*Context) RunTask ¶
func (ctx *Context) RunTask(entry string, override ...any) (*TaskDetail, error)
RunTask runs a pipeline task by entry name and returns its detail. It accepts an entry string and an optional override parameter which can be a JSON string, raw JSON bytes, or any data type that can be marshaled to JSON. The override must be a JSON object (map); this is enforced by the native side, so a non-object override fails with a generic run error. If the override value is nil, an empty JSON object will be used. If multiple overrides are provided, only the first one will be used. If the override value cannot be marshaled to JSON, an error is returned and the task is not run.
Example 1:
pipeline := NewPipeline()
node := NewNode("Task").
SetAction(ActClick(ClickParam{Target: NewTargetRect(Rect{100, 200, 100, 100})}))
pipeline.AddNode(node)
ctx.RunTask(node.Name, pipeline)
Example 2:
ctx.RunTask("Task", map[string]any{
"Task": map[string]any{
"action": "Click",
"target": []int{100, 200, 100, 100},
}
})
Example 3:
ctx.RunTask("Task", `{"Task":{"action":"Click","target":[100, 200, 100, 100]}}`)
func (*Context) SetAnchor ¶
SetAnchor sets an anchor by name. An empty nodeName erases the anchor; the native side does not report an error for unknown names.
func (*Context) WaitFreezes ¶
func (ctx *Context) WaitFreezes( duration time.Duration, box *Rect, waitFreezesParam *WaitFreezesParam, ) error
WaitFreezes waits until the screen stabilizes (no significant changes). duration is the duration that the screen must remain stable, truncated to whole milliseconds. Negative durations are never honored: the value wraps on its way to the native side and ends up non-positive there, so it is silently ignored when waitFreezesParam.Time is set and reported as a missing duration otherwise. box is the recognition hit box, used when the waitFreezesParam target is "Self" to calculate the ROI. A nil box yields an empty ROI, so the default "Self" target fails; to monitor the entire screen, pass a rect covering it, in box or in a region target. A boolean true target still means "Self" here and does not widen a nil box. waitFreezesParam is optional; nil uses default params. duration and waitFreezesParam.Time are mutually exclusive; one of them must be non-zero. Returns nil if the screen stabilized within the timeout; returns an error on timeout or failure. If waitFreezesParam cannot be marshaled to JSON, an error is returned and nothing is waited.
type ContextEventSink ¶
type ContextEventSink interface {
OnNodePipelineNode(ctx *Context, event EventStatus, detail NodePipelineNodeDetail)
OnNodeRecognitionNode(ctx *Context, event EventStatus, detail NodeRecognitionNodeDetail)
OnNodeActionNode(ctx *Context, event EventStatus, detail NodeActionNodeDetail)
OnNodeNextList(ctx *Context, event EventStatus, detail NodeNextListDetail)
OnNodeRecognition(ctx *Context, event EventStatus, detail NodeRecognitionDetail)
OnNodeAction(ctx *Context, event EventStatus, detail NodeActionDetail)
}
ContextEventSink is the interface for receiving context-level events. Handler methods run synchronously on native calling threads, may overlap with other callbacks, and must not wait for work that requires them to return.
type ContextWaitFreezesEventSink ¶
type ContextWaitFreezesEventSink interface {
OnNodeWaitFreezes(ctx *Context, event EventStatus, detail NodeWaitFreezesDetail)
}
ContextWaitFreezesEventSink optionally adds Node.WaitFreezes handling to a ContextEventSink. Existing sinks do not need to implement this interface.
type Controller ¶
type Controller struct {
// contains filtered or unexported fields
}
Controller is an owned or borrowed native controller: controllers returned by the controller constructors own their native handles, while views obtained from getters and callbacks do not. Handle lifetime is guarded across calls; callers must coordinate configuration and execution.
func NewAdbController ¶
func NewAdbController( adbPath, address string, screencapMethod adb.ScreencapMethod, inputMethod adb.InputMethod, config, agentPath string, ) (*Controller, error)
NewAdbController creates a new ADB controller. config must be a valid JSON object; use "{}" for defaults. It is normally obtained from AdbDevice.Config (see FindAdbDevices). Its "command.<Name>" arrays override the built-in adb command templates. agentPath is the directory holding the agent binaries; the minitouch and maatouch input methods require their binaries to exist there.
func NewAndroidNativeController ¶
func NewAndroidNativeController(configJson string) (*Controller, error)
NewAndroidNativeController creates an Android native controller backed by MaaAndroidNativeControlUnit. configJson is the JSON config for the control unit. Required fields:
- library_path: path to the Android native control unit library
- screen_resolution.width / screen_resolution.height: raw screenshot and touch resolution
Optional fields:
- display_id: target display id, defaults to 0
- force_stop: whether to force stop before start_app, defaults to false
Note: This controller is only available on Android. The configured screen_resolution must match the control unit's raw screenshot/touch coordinate space. Multi-touch is supported: contact is the finger id (0 for the first finger). The external library's TouchArgs must carry contact.
func NewBlankController ¶
func NewBlankController() (*Controller, error)
NewBlankController creates a controller whose operations all succeed as no-ops. Use it to test framework features (resource binding, tasker initialization, etc.) without any real controller behavior. It returns an error only when native controller creation fails.
func NewCustomController ¶
func NewCustomController( ctrl CustomController, ) (*Controller, error)
NewCustomController creates a custom controller instance.
func NewGamepadController ¶
func NewGamepadController( hWnd unsafe.Pointer, gamepadType GamepadType, screencapMethod win32.ScreencapMethod, ) (*Controller, error)
NewGamepadController creates a virtual gamepad controller for Windows.
hWnd: Window handle for screencap (optional, can be nil if screencap not needed). gamepadType: Type of virtual gamepad (Xbox360 or DualShock4). screencapMethod: Win32 screencap method to use. Ignored if hWnd is nil.
Note: Requires ViGEm Bus Driver to be installed on the system. click and swipe are not directly supported; input_text, start_app, stop_app, and scroll are not supported. For gamepad button and touch constants, import "github.com/MaaXYZ/maa-framework-go/v4/controller/gamepad".
func NewLinuxController ¶
func NewLinuxController(configJson string) (*Controller, error)
NewLinuxController creates a Linux controller from a JSON configuration. configJson must specify screencap_method and input_method, plus the fields required by the selected methods (such as wlr_socket_path for wlroots, pw_node_id for PipeWire, or eis_socket_path for libei). The PipeWire portal screencap method requires both pw_socket_fd and pw_node_id. See the MaaFramework MaaLinuxControllerCreate documentation for the complete configuration format. This controller is only available on Linux.
func NewMacOSController ¶
func NewMacOSController( windowID uint32, screencapMethod macos.ScreencapMethod, inputMethod macos.InputMethod, ) (*Controller, error)
NewMacOSController creates a macOS controller for native macOS applications. windowID is the CGWindowID of the target window (0 for desktop). screencapMethod is the macOS screencap method to use. inputMethod is the macOS input method to use.
Note: Requires Screen Recording permission for screencap. Input simulation requires Accessibility permission. Some features are not supported: start_app, stop_app, scroll. Only single touch is supported (contact must be 0).
func NewPlayCoverController ¶
func NewPlayCoverController( address, uuid string, ) (*Controller, error)
NewPlayCoverController creates a new PlayCover controller. address is the PlayTools service address in "host:port" format. uuid is the bundle identifier of the target application (e.g. "com.hypergryph.arknights"). start_app, input_text, click_key, key_down, key_up, and scroll are not supported.
func NewRecordController ¶
func NewRecordController(inner *Controller, recordingPath string) (*Controller, error)
NewRecordController creates a record controller that wraps an existing controller and records all operations. inner is the inner controller to forward all operations to; it must not be nil. The record controller does NOT take ownership of the inner controller. recordingPath is the path to the recording JSONL file to write. Screenshot images will be saved to a "{stem}-Screenshot" folder in the same directory as this file. The recorded file can be replayed using NewReplayController.
func NewReplayController ¶
func NewReplayController(recordingPath string) (*Controller, error)
NewReplayController creates a replay controller that replays recorded operations. recordingPath is the path to the recording JSONL file written by a record controller. Screenshot image paths in the file are resolved relative to this file's parent directory.
func NewWin32Controller ¶
func NewWin32Controller( hWnd unsafe.Pointer, screencapMethod win32.ScreencapMethod, mouseMethod win32.InputMethod, keyboardMethod win32.InputMethod, ) (*Controller, error)
NewWin32Controller creates a win32 controller instance.
func (*Controller) AddSink ¶
func (c *Controller) AddSink(sink ControllerEventSink) int64
AddSink adds an event callback sink and returns the sink ID. The sink ID can be used to remove the sink later. The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback. It returns 0 if registration fails or the object is closed.
func (*Controller) CacheImage ¶
func (c *Controller) CacheImage() (image.Image, error)
CacheImage gets the image buffer of the last screencap request. The cached image is scaled to the configured screenshot target size, so its dimensions may differ from the raw device resolution (see GetResolution).
func (*Controller) CacheImageInto ¶
CacheImageInto gets the image buffer of the last screencap request and writes into dst when possible. If dst is nil or size mismatched, a new *image.RGBA is allocated and returned.
func (*Controller) ClearSinks ¶
func (c *Controller) ClearSinks()
ClearSinks clears all event callback sinks. The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback.
func (*Controller) Connected ¶
func (c *Controller) Connected() bool
Connected checks if the controller is connected.
func (*Controller) Destroy ¶
func (c *Controller) Destroy() error
Destroy closes the controller once; repeated successful calls are safe. It returns ErrBound while a tasker uses it or an AgentClient retains it, ErrInUse while a call or job is active — even if the returned Job was discarded — ErrBorrowed when called on a getter or callback view, and ErrInCallback when called from inside one of the controller's own callbacks. After a stop invalidates action IDs, Destroy may post an inactive action, invoking a custom controller's Inactive handler, and return ErrInUse until it completes; retry afterward. Native destruction may call custom KeyUp/TouchUp methods before Destroy returns successfully. A successful Destroy returns after native cleanup and prevents subsequent user callbacks.
func (*Controller) GetInfo ¶
func (c *Controller) GetInfo() (string, error)
GetInfo gets controller information as a JSON string. Returns controller-specific information including type, constructor parameters and current state. The returned JSON always contains a "type" key identifying the controller kind; for custom controllers it is always "custom".
func (*Controller) GetResolution ¶
func (c *Controller) GetResolution() (width, height int32, err error)
GetResolution gets the raw (unscaled) device resolution. Returns the width and height. Returns an error if the resolution is not available yet, for example before connecting or before the first screencap. Note: This returns the actual device screen resolution before any scaling. The screenshot obtained via CacheImage is scaled according to the screenshot target size settings.
func (*Controller) GetShellOutput ¶
func (c *Controller) GetShellOutput() (string, error)
GetShellOutput gets the output of the last shell command, including embedded NUL bytes.
func (*Controller) GetUUID ¶
func (c *Controller) GetUUID() (string, error)
GetUUID gets the UUID of the controller.
func (*Controller) OnControllerAction ¶
func (c *Controller) OnControllerAction( fn func(EventStatus, ControllerActionDetail), ) int64
OnControllerAction registers a callback sink that only handles Controller.Action events and returns the sink ID. The sink ID can be used to remove the sink later.
func (*Controller) PostClick ¶
func (c *Controller) PostClick(x, y int32) (*Job, error)
PostClick posts a click. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostClickKey ¶
func (c *Controller) PostClickKey(keycode int32) (*Job, error)
PostClickKey posts a click key. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostClickV2 ¶
func (c *Controller) PostClickV2(x, y, contact, pressure int32) (*Job, error)
PostClickV2 posts a click with contact and pressure. For adb controller, contact means finger id (0 for first finger, 1 for second finger, etc). For win32 controller, contact means mouse button id (0 for left, 1 for right, 2 for middle). It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostConnect ¶
func (c *Controller) PostConnect() (*Job, error)
PostConnect posts a connection. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostInactive ¶
func (c *Controller) PostInactive() (*Job, error)
PostInactive posts an inactive request to restore controller/window state. For Win32 controllers this restores window position (removes topmost) and unblocks user input. For other controllers this is a no-op that typically succeeds. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostInputText ¶
func (c *Controller) PostInputText(text string) (*Job, error)
PostInputText posts an input text. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostKeyDown ¶
func (c *Controller) PostKeyDown(keycode int32) (*Job, error)
PostKeyDown posts a key-down. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostKeyUp ¶
func (c *Controller) PostKeyUp(keycode int32) (*Job, error)
PostKeyUp posts a key-up. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostRelativeMove ¶
func (c *Controller) PostRelativeMove(dx, dy int32) (*Job, error)
PostRelativeMove posts a relative cursor move. dx and dy are the horizontal and vertical move offsets. Supported by Win32 controllers using Seize or message-based mouse input, by Linux controllers (uinput/wlroots/libei input), and by custom controllers implementing RelativeMove; macOS controllers do not support it. Win32 message-based mouse input requires mouse-lock-follow mode to be active when the action executes; enable it with Controller.SetMouseLockFollow. Seize mouse input does not require this mode. Relative move failures are reported by the submitted job's final status; use Job.Wait or Job.Status to check the result. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostScreencap ¶
func (c *Controller) PostScreencap() (*Job, error)
PostScreencap posts a screencap. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostScroll ¶
func (c *Controller) PostScroll(dx, dy int32) (*Job, error)
PostScroll posts a scroll. dx and dy are the horizontal and vertical scroll deltas: positive dx scrolls right, positive dy scrolls up. Scroll is supported by Win32, macOS, and Linux controllers when their input method supports scrolling, and by custom controllers implementing Scroll. Scroll failures are reported by the submitted job's final status; use Job.Wait or Job.Status to check the result. On Win32 the amounts are wheel-delta units, so multiples of 120 are recommended. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostShell ¶
PostShell posts a shell command. Supported by ADB controllers and by custom controllers that implement the Shell method; for other controller types the action fails. The timeout is passed to the native API in milliseconds: a negative timeout waits indefinitely, and zero returns immediately. No default applies, as the Go wrapper always passes an explicit value. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostStartApp ¶
func (c *Controller) PostStartApp(intent string) (*Job, error)
PostStartApp posts a start app. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostStopApp ¶
func (c *Controller) PostStopApp(intent string) (*Job, error)
PostStopApp posts a stop app. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostSwipe ¶
PostSwipe posts a swipe. The duration is converted to int32 milliseconds for the native API, so durations beyond the int32 millisecond range (about 24.8 days) wrap around, matching the C API's own limit. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostSwipeV2 ¶
func (c *Controller) PostSwipeV2(x1, y1, x2, y2 int32, duration time.Duration, contact, pressure int32) (*Job, error)
PostSwipeV2 posts a swipe with contact and pressure. For adb controller, contact means finger id (0 for first finger, 1 for second finger, etc). For win32 controller, contact means mouse button id (0 for left, 1 for right, 2 for middle). The duration is converted to int32 milliseconds for the native API, so durations beyond the int32 millisecond range (about 24.8 days) wrap around, matching the C API's own limit. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostTouchDown ¶
func (c *Controller) PostTouchDown(contact, x, y, pressure int32) (*Job, error)
PostTouchDown posts a touch-down. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostTouchMove ¶
func (c *Controller) PostTouchMove(contact, x, y, pressure int32) (*Job, error)
PostTouchMove posts a touch-move. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) PostTouchUp ¶
func (c *Controller) PostTouchUp(contact int32) (*Job, error)
PostTouchUp posts a touch-up. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed.
func (*Controller) RemoveSink ¶
func (c *Controller) RemoveSink(sinkId int64)
RemoveSink removes an event callback sink by sink ID. Removing an unknown or already-removed sink ID is a no-op. The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback.
func (*Controller) SetBackgroundManagedKeys ¶
func (c *Controller) SetBackgroundManagedKeys(keys []int32) error
SetBackgroundManagedKeys sets the Win32 virtual-key codes managed during background input. Call it before connecting a Win32 controller. An empty slice clears the managed key list.
func (*Controller) SetMouseLockFollow ¶
func (c *Controller) SetMouseLockFollow(enabled bool) error
SetMouseLockFollow enables or disables mouse-lock-follow mode. This is designed for TPS/FPS games that lock the mouse to their window in the background. Only valid for Win32 controllers using message-based input methods.
func (*Controller) SetScreenshot ¶
func (c *Controller) SetScreenshot(opts ...ScreenshotOption) error
SetScreenshot updates the supplied screenshot settings on the controller. A target, interpolation method, and WithScreenshotUseRawSize(false) can be combined in any order. Long-side, short-side, and expand targets are mutually exclusive within one call, as are a target and WithScreenshotUseRawSize(true). Target dimensions must be positive, and the interpolation method must be one of the five ScreenshotResizeMethod constants (0 through 4). The native API treats a target value of 0 as clearing the target; this Go wrapper deliberately rejects non-positive values instead. Repeated settings are rejected even when their values are identical. Nil options are ignored; an empty call leaves the settings unchanged.
Omitted settings are retained. Across separate calls, a new target replaces the previous target without disabling raw-size mode. Disabling raw-size mode resumes resizing with the retained target and interpolation method. If no target has ever been set, the native default target scales the short side to 720.
Rejecting raw-size true with a target is a Go API guard against ambiguous screenshot-size intent: the target would be inactive in raw-size mode. The native API can retain a target while raw-size mode is enabled; set it in a separate call to prepare for later resizing, or combine it with WithScreenshotUseRawSize(false) to resume resizing with it. Interpolation is an independent preference and can accompany either raw-size value.
All options are validated before any native setting is changed. Valid options are applied in the order target, interpolation method, then raw-size mode. If a native setter fails, earlier changes remain applied and later setters are skipped. Callers must serialize configuration with other controller operations.
For example, to resume resizing with a 1280-pixel long side and linear interpolation:
if err := ctrl.SetScreenshot(
WithScreenshotUseRawSize(false),
WithScreenshotTargetLongSide(1280),
WithScreenshotResizeMethod(ScreenshotResizeMethodLinear),
); err != nil {
return err
}
type ControllerActionDetail ¶
type ControllerActionDetail struct {
CtrlID uint64 `json:"ctrl_id"`
UUID string `json:"uuid"`
Action string `json:"action"`
Param map[string]any `json:"param"`
Info map[string]any `json:"info"`
}
ControllerActionDetail contains information about controller action events
type ControllerEventSink ¶
type ControllerEventSink interface {
OnControllerAction(ctrl *Controller, event EventStatus, detail ControllerActionDetail)
}
ControllerEventSink is the sink for controller action events (Controller.Action.* messages), delivered with a borrowed *Controller view of the controller that posted the event. Handler methods run synchronously on native calling threads, may overlap with other callbacks, and must not wait for work that requires them to return. See Controller.OnControllerAction for a single-event convenience wrapper.
type ControllerFeature ¶
type ControllerFeature uint64
ControllerFeature is the feature bitmask returned by CustomController.GetFeature. The flags indicate which input methods the controller supports or prefers.
const ( // ControllerFeatureNone reports no special features: the controller // supports Click, Swipe, and ClickKey directly. ControllerFeatureNone ControllerFeature = 0 // ControllerFeatureUseMouseDownAndUpInsteadOfClick makes the framework // route clicks and swipes through TouchDown/TouchMove/TouchUp instead of // Click and Swipe, so contact and pressure are forwarded. ControllerFeatureUseMouseDownAndUpInsteadOfClick ControllerFeature = 1 // ControllerFeatureUseKeyboardDownAndUpInsteadOfClick makes the framework // route ClickKey through KeyDown plus KeyUp instead of ClickKey. ControllerFeatureUseKeyboardDownAndUpInsteadOfClick ControllerFeature = 1 << 1 // ControllerFeatureNoScalingTouchPoints disables automatic touch coordinate scaling. ControllerFeatureNoScalingTouchPoints ControllerFeature = 1 << 2 )
type CustomActionArg ¶
type CustomActionArg struct {
TaskID int64 // Task ID. Task details can be retrieved via Tasker.GetTaskDetail.
// CurrentTaskName is the name of the node currently executing. Entries
// run via Context.RunActionDirect use a synthesized name
// ("action/<type>/<uuid>") instead of a pipeline node name.
CurrentTaskName string
// CustomActionName is the registered name of this custom action.
CustomActionName string
// CustomActionParam is the node's custom_action_param, serialized as a
// JSON string.
CustomActionParam string
// RecognitionDetail may be nil when the custom action runs on an action-only
// node (e.g. invoked via Context.RunAction), where reco_id is invalid.
RecognitionDetail *RecognitionDetail
// Box is the action's resolved target rect. It equals the preceding
// recognition's hit box when the target is Self (the default).
Box Rect
}
CustomActionArg is the argument passed to CustomActionRunner.Run when the framework executes a node with a Custom action.
type CustomActionFunc ¶
type CustomActionFunc func(ctx *Context, arg *CustomActionArg) bool
CustomActionFunc is an adapter to allow use of ordinary functions as CustomActionRunner. If f is a function with the appropriate signature, CustomActionFunc(f) is a CustomActionRunner that calls f.
func (CustomActionFunc) Run ¶
func (f CustomActionFunc) Run(ctx *Context, arg *CustomActionArg) bool
Run calls f(ctx, arg).
type CustomActionParam ¶
type CustomActionParam struct {
// Target specifies the action target position.
Target Target `json:"target,omitzero"`
// TargetOffset specifies additional offset applied to target.
// JSON accepts [x, y], which expands to a 1x1 offset at (x, y), or [x, y, w, h];
// the zero value omits the field, so the pipeline default or parent-node inheritance applies.
TargetOffset Rect `json:"target_offset,omitzero"`
// CustomAction specifies the action name registered via MaaResourceRegisterCustomAction. Required.
CustomAction string `json:"custom_action,omitempty"`
// CustomActionParam specifies custom parameters passed to the action callback.
// The value is passed through verbatim by the framework, so decoding keeps
// numbers as json.Number to preserve integers beyond float64 precision.
CustomActionParam any `json:"custom_action_param,omitempty"`
}
CustomActionParam defines parameters for custom action handlers.
func (*CustomActionParam) UnmarshalJSON ¶
func (p *CustomActionParam) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the custom action param, keeping the numeric fidelity of custom_action_param by decoding its numbers as json.Number, exactly as the upstream parser passes the sub-JSON through. Omitted fields retain their existing values; a provided custom_action_param replaces the previous value. On error the param is unchanged.
type CustomActionRunner ¶
type CustomActionRunner interface {
// Run reports whether the action succeeded. Returning false marks the
// node's action as failed; for a pipeline node the task then continues
// from the node's on_error list, while action-only runs (e.g. via
// Context.RunAction) only report the failure in their ActionDetail.
Run(ctx *Context, arg *CustomActionArg) bool
}
CustomActionRunner performs the action for nodes registered under a name via Resource.RegisterCustomAction.
type CustomController ¶
type CustomController interface {
Connect() bool
// Connected reports whether the controller is ready. Return true when
// no connection check is needed.
Connected() bool
RequestUUID() (string, bool)
GetFeature() ControllerFeature
StartApp(intent string) bool
StopApp(intent string) bool
Screencap() (image.Image, bool)
Click(x, y int32) bool
Swipe(x1, y1, x2, y2, duration int32) bool
TouchDown(contact, x, y, pressure int32) bool
TouchMove(contact, x, y, pressure int32) bool
TouchUp(contact int32) bool
ClickKey(keycode int32) bool
InputText(text string) bool
KeyDown(keycode int32) bool
KeyUp(keycode int32) bool
Scroll(dx, dy int32) bool
RelativeMove(dx, dy int32) bool
// Shell runs a controller-side shell command and returns its textual output.
// timeout is measured in milliseconds.
// Embedded NUL bytes in the output are preserved.
// Return ("", true) if the command succeeded but produced no output.
Shell(cmd string, timeout int64) (string, bool)
// Inactive is called when the framework requests restoring controller/window state (e.g. after tasks finish).
// Return true for success or when no action is needed.
Inactive() bool
// GetInfo returns custom controller information as a JSON string.
// Return ("{}", true) if no extra info is needed; an empty string is not
// valid JSON and logs a framework warning on every controller action.
GetInfo() (string, bool)
}
CustomController defines the operations of a custom controller. Methods can be called concurrently from native threads; implementations must synchronize shared state. KeyUp and TouchUp can be called during destruction.
type CustomRecognitionArg ¶
type CustomRecognitionArg struct {
TaskID int64 // Task ID. Task details can be retrieved via Tasker.GetTaskDetail.
// CurrentTaskName is the name of the node currently executing. Entries
// run via Context.RunRecognitionDirect use a synthesized name
// ("recognition/<type>/<uuid>") instead of a pipeline node name.
CurrentTaskName string
// CustomRecognitionName is the registered name of this custom recognizer.
CustomRecognitionName string
// CustomRecognitionParam is the node's custom_recognition_param,
// serialized as a JSON string.
CustomRecognitionParam string
// Img is the current frame to recognize, decoded into a copy that stays
// valid after Run returns.
Img image.Image
// Roi is the region of interest the recognizer should search, resolved
// from the node's roi.
Roi Rect
}
CustomRecognitionArg is the argument passed to CustomRecognitionRunner.Run when the framework executes a node with a Custom recognition.
type CustomRecognitionFunc ¶
type CustomRecognitionFunc func(ctx *Context, arg *CustomRecognitionArg) (*CustomRecognitionResult, bool)
CustomRecognitionFunc is an adapter to allow use of ordinary functions as CustomRecognitionRunner. If f is a function with the appropriate signature, CustomRecognitionFunc(f) is a CustomRecognitionRunner that calls f.
func (CustomRecognitionFunc) Run ¶
func (f CustomRecognitionFunc) Run(ctx *Context, arg *CustomRecognitionArg) (*CustomRecognitionResult, bool)
Run calls f(ctx, arg).
type CustomRecognitionParam ¶
type CustomRecognitionParam struct {
// ROI specifies the region of interest for recognition.
ROI Target `json:"roi,omitzero"`
// ROIOffset specifies an offset applied to ROI. The zero value is omitted
// to inherit the existing/default offset; an explicit zero offset cannot
// be expressed with this value-type field.
ROIOffset Rect `json:"roi_offset,omitzero"`
// CustomRecognition specifies the recognizer name registered via MaaResourceRegisterCustomRecognition. Required.
CustomRecognition string `json:"custom_recognition,omitempty"`
// CustomRecognitionParam specifies custom parameters passed to the recognition callback.
CustomRecognitionParam any `json:"custom_recognition_param,omitempty"`
}
CustomRecognitionParam defines parameters for custom recognition handlers.
type CustomRecognitionResult ¶
CustomRecognitionResult contains the box and detail returned by a custom recognizer. The result can include diagnostic information even when recognition does not match.
type CustomRecognitionRunner ¶
type CustomRecognitionRunner interface {
// Run returns a result and whether recognition matched. A non-nil result is
// passed to MaaFramework even when matched is false. A nil result is always
// treated as no match.
Run(ctx *Context, arg *CustomRecognitionArg) (*CustomRecognitionResult, bool)
}
CustomRecognitionRunner performs recognition for a registered custom recognizer.
type DesktopWindow ¶
type DesktopWindow struct {
// Handle is the platform window handle cast to unsafe.Pointer: a Win32
// HWND, a macOS CGWindowID (an SCWindow windowID, not an NSWindow
// pointer), or on Linux a Wayland display number. It is a handle
// value, not a Go pointer, and must not be dereferenced.
Handle unsafe.Pointer
// ClassName is the Win32 window class name, the macOS bundle
// identifier, or on Linux the Wayland socket path.
ClassName string
// WindowName is the window title on Win32 and macOS, or on Linux the
// Wayland socket file name.
WindowName string
}
DesktopWindow represents a single desktop window found on the system.
func FindDesktopWindows ¶
func FindDesktopWindows() ([]*DesktopWindow, error)
FindDesktopWindows finds desktop windows. An empty slice with a nil error means no windows were found.
type DirectHitParam ¶
type DirectHitParam struct {
// ROI specifies the region to return. The zero value inherits the existing ROI or defaults to the whole image.
ROI Target `json:"roi,omitzero"`
// ROIOffset specifies an offset applied to the ROI.
// Nil inherits the existing/default offset; a pointer to a zero Rect clears it explicitly.
ROIOffset *Rect `json:"roi_offset,omitempty"`
}
DirectHitParam defines parameters for direct hit recognition. It performs no image matching and uses the first resolved ROI as its result box. Recognition fails if the ROI cannot be resolved, for example an unavailable node reference.
type DoNothingParam ¶
type DoNothingParam struct{}
DoNothingParam defines parameters for do-nothing action.
type Event ¶
type Event string
Event is the family name of a MaaFramework notification, such as "Resource.Loading". The families match the MaaMsg_* defines in the upstream MaaMsg.h one-to-one and carry no status: the full notification name is built by appending a status suffix with Starting, Succeeded, or Failed. Incoming notification names are split the same way, and a name without a recognized suffix reports EventStatusUnknown.
func (Event) Failed ¶
Failed returns the notification name reported when the operation fails: the family name plus ".Failed".
func (Event) Starting ¶
Starting returns the notification name reported when the operation starts: the family name plus ".Starting".
type EventStatus ¶
type EventStatus int
EventStatus represents the current state of an event
const ( EventStatusUnknown EventStatus = iota EventStatusStarting EventStatusSucceeded EventStatusFailed )
Event status constants
type FeatureMatchDetector ¶
type FeatureMatchDetector string
FeatureMatchDetector defines the feature detection algorithms.
const ( FeatureMatchMethodSIFT FeatureMatchDetector = "SIFT" // Scale-Invariant Feature Transform (default, most accurate) FeatureMatchMethodKAZE FeatureMatchDetector = "KAZE" // KAZE features FeatureMatchMethodAKAZE FeatureMatchDetector = "AKAZE" // Accelerated KAZE FeatureMatchMethodBRISK FeatureMatchDetector = "BRISK" // Binary Robust Invariant Scalable Keypoints (fast) FeatureMatchMethodORB FeatureMatchDetector = "ORB" // Oriented FAST and Rotated BRIEF (fast) FeatureMatchMethodSURF FeatureMatchDetector = "SURF" // Speeded-Up Robust Features; requires OpenCV xfeatures2d )
Feature detection algorithms. The native parser accepts the CamelCase and all-lowercase spellings of these names, plus "Default" (keep the existing detector) and "SURF", which fails node load on builds without OpenCV xfeatures2d. Default: SIFT.
type FeatureMatchOrderBy ¶
type FeatureMatchOrderBy OrderBy
FeatureMatchOrderBy defines the ordering options for feature matching results.
type FeatureMatchParam ¶
type FeatureMatchParam struct {
// ROI specifies the region of interest for recognition.
ROI Target `json:"roi,omitzero"`
// ROIOffset specifies an offset applied to ROI. The zero value is omitted
// to inherit the existing/default offset; an explicit zero offset cannot
// be expressed with this value-type field.
ROIOffset Rect `json:"roi_offset,omitzero"`
// Template specifies the template image paths. Required.
// JSON input may be a single string or an array of strings; a scalar
// normalizes to a one-element list. Nil is omitted to inherit the
// existing/default templates; an empty non-nil list clears them.
Template StringList `json:"template,omitzero"`
// Count specifies the minimum number of feature points required (threshold). Default: 4.
Count int `json:"count,omitempty"`
// OrderBy specifies how results are sorted. Default: Horizontal. Options: Horizontal | Vertical | Score | Area | Random.
OrderBy FeatureMatchOrderBy `json:"order_by,omitempty"`
// Index specifies which match to select from results.
Index int `json:"index,omitempty"`
// GreenMask enables green color masking for transparent areas.
GreenMask bool `json:"green_mask,omitempty"`
// Detector specifies the feature detector algorithm. Options: SIFT, KAZE,
// AKAZE, BRISK, ORB, and SURF (requires an OpenCV build with xfeatures2d).
// Default: SIFT.
Detector FeatureMatchDetector `json:"detector,omitempty"`
// Ratio specifies the matching ratio threshold [0-1.0]. Default: 0.6.
Ratio float64 `json:"ratio,omitempty"`
}
FeatureMatchParam defines parameters for feature matching recognition.
type FeatureMatchResult ¶
FeatureMatchResult is the decoded FeatureMatch result from a recognition detail JSON, with keys box and count.
type GamepadType ¶
type GamepadType = native.MaaGamepadType
GamepadType defines the type of virtual gamepad.
const ( GamepadTypeXbox360 GamepadType = native.MaaGamepadType_Xbox360 GamepadTypeDualShock4 GamepadType = native.MaaGamepadType_DualShock4 )
Gamepad type constants.
type GamescopeInstance ¶
GamescopeInstance describes a running gamescope instance.
func FindGamescopeInstances ¶
func FindGamescopeInstances() ([]*GamescopeInstance, error)
FindGamescopeInstances finds running gamescope instances, ordered by display number. An empty slice means no instances were found. A zero PipeWireNodeID or empty EisSocketPath means the corresponding capture or input endpoint is unavailable.
type InferenceDevice ¶
type InferenceDevice = native.MaaInferenceDevice
InferenceDevice identifies the device used for inference: a GPU index or provider-specific id, or one of the InferenceDevice constants below. It is an alias of the native MaaInferenceDevice (int32 in MaaDef.h).
const ( InferenceDeviceAuto InferenceDevice = -1 InferenceDevice0 InferenceDevice = 0 InferenceDevice1 InferenceDevice = 1 )
Inference device values accepted by UseDirectml and UseWebgpu, mirroring MaaInferenceDeviceEnum in MaaDef.h. InferenceDeviceAuto asks the provider to select a device; UseDirectml interprets the other values as the DirectML adapter id from Win32 EnumAdapters1, and UseWebgpu as the WebGPU device id (ep.webgpuexecutionprovider.deviceId). GPU ids beyond 1 are expressed as plain integers. The upstream CPU value is not exported here; UseCPU selects that combination.
type InitOption ¶
type InitOption func(*initConfig)
InitOption defines a function type for configuring initialization through functional options. Use package-provided WithXxx helpers to construct options.
func WithDebugMode ¶
func WithDebugMode(enabled bool) InitOption
WithDebugMode returns an InitOption that enables or disables debug mode. When enabled is true, additional debug information will be collected and logged.
func WithJSONDecoder ¶
func WithJSONDecoder(decoder JSONDecoder) InitOption
WithJSONDecoder returns an InitOption that sets a custom JSON decoder.
func WithJSONEncoder ¶
func WithJSONEncoder(encoder JSONEncoder) InitOption
WithJSONEncoder returns an InitOption that sets a custom JSON encoder. The encoder must satisfy the compatibility requirements documented by JSONEncoder.
func WithLibDir ¶
func WithLibDir(libDir string) InitOption
WithLibDir returns an InitOption that sets the library directory path for the MAA framework. The libDir parameter specifies the directory where the MAA dynamic library is located. An empty directory uses the platform loader's current search configuration.
On Windows, when Init applies a nonempty directory, it calls SetDllDirectoryW to change the DLL search directory for the whole process. Once that call succeeds, neither Release nor initialization failure rollback restores the previous configuration. It remains in effect until the process exits or another DLL search configuration change replaces it. Later Init calls with an empty directory leave the current configuration unchanged. For unpackaged, unprotected Win32 processes, the change can also affect the DLL search order of subsequently started child processes.
func WithLogDir ¶
func WithLogDir(logDir string) InitOption
WithLogDir returns an InitOption that sets the directory path for log files. The logDir parameter specifies where the MAA framework should write its log files.
func WithPluginPaths ¶
func WithPluginPaths(path ...string) InitOption
WithPluginPaths returns an InitOption that sets the plugin paths loaded during Init. Init copies the paths when applying the option; changes to the argument slice before Init affect the paths used. Each path follows the LoadPlugin resolution rules; passing no paths yields an empty list that loads nothing.
func WithSaveDraw ¶
func WithSaveDraw(enabled bool) InitOption
WithSaveDraw returns an InitOption that configures whether to save drawing information. When enabled is true, recognition results will be saved to LogDir/vision directory and RecoDetail will be able to retrieve draws for debugging.
func WithStdoutLevel ¶
func WithStdoutLevel(level LoggingLevel) InitOption
WithStdoutLevel returns an InitOption that sets the logging level for standard output. The level parameter determines the verbosity of logs written to stdout.
type InlineSubRecognition ¶
type InlineSubRecognition struct {
// SubName names the inline sub-recognition. Only And uses it, to resolve
// the ROIs of later sub-recognitions.
SubName string `json:"sub_name,omitempty"`
Recognition
}
InlineSubRecognition is a v2 inline sub-recognition in all_of/any_of. Input accepts the protocol envelope {"sub_name": "...", "recognition": {type, param}}, the v1 form with "recognition" holding a bare type name (parameters flat on the sub item), and the flat native dump {"sub_name", "type", "param"}; all of them normalize into this v2 model, and encoding always emits the envelope. SubName is retained by both And and Or; only And uses it to resolve later sub-recognition ROIs.
func (InlineSubRecognition) MarshalJSON ¶
func (n InlineSubRecognition) MarshalJSON() ([]byte, error)
MarshalJSON encodes the v2 recognition envelope used by MaaFramework.
func (*InlineSubRecognition) UnmarshalJSON ¶
func (n *InlineSubRecognition) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the protocol envelope, the v1 form where "recognition" holds a bare type name (parameters flat on the sub item, as the native parser reads them), and the flat native dump form when the recognition key is absent. On error the receiver is unchanged.
type InputTextActionResult ¶
type InputTextActionResult struct {
Text string `json:"text"`
}
InputTextActionResult holds the parsed detail of an InputText action.
type InputTextParam ¶
type InputTextParam struct {
// InputText specifies the text to input. Some controllers only support ASCII. Required.
InputText string `json:"input_text,omitempty"`
}
InputTextParam defines parameters for text input action.
type JSONDecoder ¶
JSONDecoder defines how JSON is deserialized into values. Custom decoders must validate the input and honor json.Unmarshaler and json.RawMessage so pipeline v2 parameters retain their JSON representation. They must also ignore unknown fields, as encoding/json does by default: JSON produced by MaaFramework can carry keys this package's structs do not model. Node recognition and action completion events, for example, always attach reco_details, node_details, or action_details, and recognition events carry anchor as well when the node was reached through an anchor. Event callbacks run only after the event details decode successfully, so a decoder that rejects unknown fields silently drops those events.
func GetJSONDecoder ¶
func GetJSONDecoder() JSONDecoder
GetJSONDecoder returns the currently configured global JSON decoder.
type JSONEncoder ¶
JSONEncoder defines how values are serialized into JSON.
Custom encoders must honor the encoding/json semantics used by this package, including json.Marshaler, "omitempty", and the "omitzero" option added in Go 1.24. json.RawMessage and the raw parameter types must encode as JSON values, preserving numbers without conversion through floating-point Go values. Support for "omitzero" includes calling IsZero() methods. For this package's slice fields tagged "omitzero", nil must be omitted while non-nil empty slices must be encoded as [].
These rules preserve pipeline defaults and inheritance. Emitting null instead of omitting a zero field may cause MaaFramework to reject the configuration.
func GetJSONEncoder ¶
func GetJSONEncoder() JSONEncoder
GetJSONEncoder returns the currently configured global JSON encoder.
type Job ¶
type Job struct {
// contains filtered or unexported fields
}
Job represents an asynchronous job with status tracking capabilities. It provides methods to check the job status and wait for completion. Wait, status queries and predicates, and Error may be called concurrently. Multiple waiters share the completed result, and status queries remain available while a wait is in progress. A Job must not be copied.
func (*Job) Status ¶
Status returns the current status of the job. It reports StatusFailure when the job carries an error and no terminal status has been cached yet, for example after a failed submission or after the owning handle has been closed.
func (*Job) Wait ¶
Wait blocks until the job completes and returns the job instance. It returns immediately without waiting for native work when the job carries an error, such as a failed submission or a closed owning handle. The terminal status reported by Wait is cached: later Status calls return it instead of querying the native layer again.
type KeyDownParam ¶
type KeyDownParam struct {
// AutoUp releases still-held keys when the task stops, finishes, or the controller is destroyed.
// Framework default: false. Nil inherits as described in [ActionParam].
AutoUp *bool `json:"auto_up,omitempty"`
// Key specifies the virtual key code to press down. Required.
// Decoding also accepts the legacy key_code alias; when both fields are
// present, key wins. Encoding always writes key.
Key int `json:"key,omitempty"`
}
KeyDownParam defines parameters for key down action.
func (*KeyDownParam) UnmarshalJSON ¶
func (p *KeyDownParam) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the key down param, accepting the legacy key_code alias for key. When both fields are present, key wins, matching the upstream parser. Omitted fields retain their existing values. On error the param is unchanged.
type KeyUpParam ¶
type KeyUpParam struct {
// AutoUp retains the framework's shared key parameter for JSON round trips.
// It only affects KeyDown; KeyUp does not use it. Nil leaves it unspecified.
AutoUp *bool `json:"auto_up,omitempty"`
// Key specifies the virtual key code to release. Required.
// Decoding also accepts the legacy key_code alias; when both fields are
// present, key wins. Encoding always writes key.
Key int `json:"key,omitempty"`
}
KeyUpParam defines parameters for key up action.
func (*KeyUpParam) UnmarshalJSON ¶
func (p *KeyUpParam) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the key up param, accepting the legacy key_code alias for key. When both fields are present, key wins, matching the upstream parser. Omitted fields retain their existing values. On error the param is unchanged.
type LibraryLoadError ¶
type LibraryLoadError = native.LibraryLoadError
LibraryLoadError represents an error that occurs when loading a MAA dynamic library. This error type provides detailed information about which library failed to load, including the library name, the full path attempted, and the underlying system error.
type LoggingLevel ¶
type LoggingLevel int32
LoggingLevel defines the logging verbosity levels, mirroring the MaaLoggingLevelEnum values of MaaDef.h (Off = 0 through All = 7).
const ( LoggingLevelOff LoggingLevel = iota LoggingLevelFatal LoggingLevelError LoggingLevelWarn LoggingLevelInfo LoggingLevelDebug LoggingLevelTrace LoggingLevelAll )
LoggingLevel values accepted by SetStdoutLevel, ordered by increasing verbosity.
type LongPressActionResult ¶
type LongPressActionResult struct {
Point Point `json:"point"`
Duration int64 `json:"duration"`
Contact int `json:"contact"`
// Pressure is kept to match MaaFramework raw detail JSON.
Pressure int `json:"pressure"`
}
LongPressActionResult holds the parsed detail of a LongPress action.
type LongPressKeyActionResult ¶
type LongPressKeyActionResult struct {
Keycode []int `json:"keycode"`
Duration int64 `json:"duration"`
}
LongPressKeyActionResult holds the parsed detail of a LongPressKey action.
type LongPressKeyParam ¶
type LongPressKeyParam struct {
// Key specifies the virtual key codes to press. Required.
// JSON input may be a single key code or an array; a single value
// normalizes to a one-element array.
Key []int `json:"key,omitempty"`
// Duration specifies the long press duration, serialized as integer milliseconds.
// Framework default: 1000ms. Nil inherits as described in [ActionParam];
// a pointer to 0 sends zero explicitly.
Duration *time.Duration `json:"-"`
}
LongPressKeyParam defines parameters for long press key action.
func (LongPressKeyParam) MarshalJSON ¶
func (p LongPressKeyParam) MarshalJSON() ([]byte, error)
MarshalJSON encodes the long press key param, with the duration as integer milliseconds. A nil duration omits the field; a pointer to zero is emitted.
func (*LongPressKeyParam) UnmarshalJSON ¶
func (p *LongPressKeyParam) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the long press key param, reading the duration as integer milliseconds and normalizing a single key code to a one-element array. An absent duration stays nil; zero decodes to a pointer to zero. It rejects durations outside the range of time.Duration.
type LongPressParam ¶
type LongPressParam struct {
// Target specifies the long press target position.
Target Target `json:"target,omitzero"`
// TargetOffset specifies additional offset applied to target.
// JSON accepts [x, y], which expands to a 1x1 offset at (x, y), or [x, y, w, h];
// the zero value omits the field, so the pipeline default or parent-node inheritance applies.
TargetOffset Rect `json:"target_offset,omitzero"`
// Duration specifies the long press duration, serialized as integer milliseconds.
// Framework default: 1000ms. Nil inherits as described in [ActionParam];
// a pointer to 0 sends zero explicitly.
Duration *time.Duration `json:"-"`
// Contact specifies the touch point identifier. Adb: finger index (0=first finger). Win32: mouse button (0=left, 1=right, 2=middle).
Contact int `json:"contact,omitempty"`
// Pressure specifies touch pressure; its range depends on the controller.
// Framework default: 1. Nil inherits as described in [ActionParam];
// a pointer to 0 sends zero explicitly.
Pressure *int `json:"pressure,omitempty"`
}
LongPressParam defines parameters for long press action.
func (LongPressParam) MarshalJSON ¶
func (p LongPressParam) MarshalJSON() ([]byte, error)
MarshalJSON encodes the long press param, with the duration as integer milliseconds. A nil duration omits the field; a pointer to zero is emitted.
func (*LongPressParam) UnmarshalJSON ¶
func (p *LongPressParam) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the long press param, reading the duration as integer milliseconds. An absent duration stays nil; zero decodes to a pointer to zero. It rejects durations outside the range of time.Duration.
type MaaCustomControllerCallbacks ¶
type MaaCustomControllerCallbacks struct {
Connect uintptr
Connected uintptr
RequestUUID uintptr
GetFeature uintptr
StartApp uintptr
StopApp uintptr
Screencap uintptr
Click uintptr
Swipe uintptr
TouchDown uintptr
TouchMove uintptr
TouchUp uintptr
ClickKey uintptr
InputText uintptr
KeyDown uintptr
KeyUp uintptr
Scroll uintptr
RelativeMove uintptr
Shell uintptr
Inactive uintptr
GetInfo uintptr
}
MaaCustomControllerCallbacks is the purego mirror of the C MaaCustomControllerCallbacks struct. Its field order and signatures must match MaaCustomController.h exactly: the struct layout is the ABI that the native MaaCustomControllerCreate reads.
type MacOSPermission ¶
type MacOSPermission = native.MaaMacOSPermission
MacOSPermission defines a macOS permission type.
const ( MacOSPermissionScreenCapture MacOSPermission = native.MaaMacOSPermissionScreenCapture MacOSPermissionAccessibility MacOSPermission = native.MaaMacOSPermissionAccessibility )
MacOS permission constants. The permission functions below are only effective on macOS; on other platforms they log and return false.
type MultiSwipeActionResult ¶
type MultiSwipeActionResult struct {
Swipes []SwipeActionResult `json:"swipes"`
}
MultiSwipeActionResult holds the parsed detail of a MultiSwipe action.
type MultiSwipeItem ¶
type MultiSwipeItem struct {
// Starting specifies when this swipe starts within the action. Default: 0.
// JSON: serialized as integer milliseconds.
Starting time.Duration `json:"-"`
// Begin specifies the swipe start position.
Begin Target `json:"begin,omitzero"`
// BeginOffset specifies additional offset applied to begin position.
// JSON accepts [x, y], which expands to a 1x1 offset at (x, y), or [x, y, w, h];
// the zero value omits the field, so the pipeline default or parent-node inheritance applies.
BeginOffset Rect `json:"begin_offset,omitzero"`
// End specifies the swipe end positions. JSON input may be a single
// target in place of the list (a bare true or node name, or a flat
// [x, y] point or [x, y, w, h] rectangle array); a single target
// normalizes to a one-element list. A zero Target element fails JSON
// encoding.
End []Target `json:"end,omitzero"`
// EndOffset specifies additional offset applied to end position. JSON
// input may be a single flat [x, y, w, h] rectangle in place of the
// list; a single offset normalizes to a one-element list.
EndOffset []Rect `json:"end_offset,omitempty"`
// Duration specifies the swipe duration. Default: 200ms.
// JSON input may be a single number or an array; a single value
// normalizes to a one-element array.
// JSON: serialized as array of integer milliseconds.
Duration []time.Duration `json:"-"`
// EndHold specifies extra wait time at end position before releasing. Default: 0.
// JSON input may be a single number or an array; a single value
// normalizes to a one-element array.
// JSON: serialized as array of integer milliseconds.
EndHold []time.Duration `json:"-"`
// OnlyHover enables hover-only mode without press/release actions. Default: false.
OnlyHover bool `json:"only_hover,omitempty"`
// Contact specifies the touch point identifier. Adb: finger index. Win32: mouse button. Default uses array index if 0.
Contact int `json:"contact,omitempty"`
// Pressure specifies touch pressure; nil uses the default Swipe pressure, initially 1.
// A pointer to 0 sends zero explicitly.
Pressure *int `json:"pressure,omitempty"`
}
MultiSwipeItem defines a single swipe within a multi-swipe action.
func (MultiSwipeItem) MarshalJSON ¶
func (p MultiSwipeItem) MarshalJSON() ([]byte, error)
MarshalJSON encodes the multi-swipe item, with the starting time, durations, and end holds as integer milliseconds.
func (*MultiSwipeItem) UnmarshalJSON ¶
func (p *MultiSwipeItem) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the multi-swipe item, reading the starting time, durations, and end holds as integer milliseconds, normalizing single end targets and offsets to one-element lists and single timing values to one-element arrays.
type MultiSwipeParam ¶
type MultiSwipeParam struct {
// Swipes specifies the list of swipe items. Required.
Swipes []MultiSwipeItem `json:"swipes,omitempty"`
}
MultiSwipeParam defines parameters for multi-finger swipe action.
type NeuralNetworkClassifyOrderBy ¶
type NeuralNetworkClassifyOrderBy OrderBy
NeuralNetworkClassifyOrderBy defines the ordering options for neural network classification results.
type NeuralNetworkClassifyParam ¶
type NeuralNetworkClassifyParam struct {
// ROI specifies the region of interest for recognition.
ROI Target `json:"roi,omitzero"`
// ROIOffset specifies an offset applied to ROI. The zero value is omitted
// to inherit the existing/default offset; an explicit zero offset cannot
// be expressed with this value-type field.
ROIOffset Rect `json:"roi_offset,omitzero"`
// Labels specifies class names for label selection, debugging, and logging. Fills "Unknown" if not provided.
// JSON input may be a single string or an array of strings.
// Nil is omitted to inherit the existing/default labels; an empty
// non-nil list clears them.
Labels StringList `json:"labels,omitzero"`
// Model specifies the model folder path relative to model/classify directory. Required. Only ONNX models supported.
Model string `json:"model,omitempty"`
// Expected selects class indices or labels, preserving their order.
// Nil inherits the existing/default selection; an empty list matches all classes.
Expected ClassSelectors `json:"expected,omitzero"`
// OrderBy specifies how results are sorted. Default: Horizontal. Options: Horizontal | Vertical | Score | Random | Expected.
OrderBy NeuralNetworkClassifyOrderBy `json:"order_by,omitempty"`
// Index specifies which match to select from results.
Index int `json:"index,omitempty"`
}
NeuralNetworkClassifyParam defines parameters for neural network classification.
type NeuralNetworkClassifyResult ¶
type NeuralNetworkClassifyResult struct {
Box Rect `json:"box"`
ClsIndex uint64 `json:"cls_index"`
Label string `json:"label"`
Score float64 `json:"score"`
}
NeuralNetworkClassifyResult is the decoded NeuralNetworkClassify result from a recognition detail JSON, with keys cls_index, label, box, and score.
type NeuralNetworkDetectOrderBy ¶
type NeuralNetworkDetectOrderBy OrderBy
NeuralNetworkDetectOrderBy defines the ordering options for neural network detection results.
type NeuralNetworkDetectParam ¶
type NeuralNetworkDetectParam struct {
// ROI specifies the region of interest for recognition.
ROI Target `json:"roi,omitzero"`
// ROIOffset specifies an offset applied to ROI. The zero value is omitted
// to inherit the existing/default offset; an explicit zero offset cannot
// be expressed with this value-type field.
ROIOffset Rect `json:"roi_offset,omitzero"`
// Labels specifies class names for label selection, debugging, and logging. Auto-reads from model metadata if not provided.
// JSON input may be a single string or an array of strings.
// Nil is omitted to inherit the existing/default labels; an empty
// non-nil list clears them.
Labels StringList `json:"labels,omitzero"`
// Model specifies the model folder path relative to model/detect directory. Required. Supports YOLOv8/YOLOv11 ONNX models.
Model string `json:"model,omitempty"`
// Expected selects class indices or labels, preserving their order.
// Nil inherits the existing/default selection; an empty list matches all
// classes, subject to Threshold.
Expected ClassSelectors `json:"expected,omitzero"`
// Threshold specifies confidence thresholds in [0, 1], in Expected order.
// Nil or an empty list inherits the existing thresholds or defaults to 0.3.
// A single threshold applies to all expected classes; otherwise lengths must match.
// A nonempty list containing 0 sends zero explicitly.
// JSON input may be a number or an array; encoding always uses an array.
Threshold []float64 `json:"threshold,omitempty"`
// OrderBy specifies how results are sorted. Default: Horizontal. Options: Horizontal | Vertical | Score | Area | Random | Expected
OrderBy NeuralNetworkDetectOrderBy `json:"order_by,omitempty"`
// Index specifies which match to select from results.
Index int `json:"index,omitempty"`
}
NeuralNetworkDetectParam defines parameters for neural network object detection.
func (*NeuralNetworkDetectParam) UnmarshalJSON ¶
func (p *NeuralNetworkDetectParam) UnmarshalJSON(data []byte) error
UnmarshalJSON normalizes a scalar threshold to a one-element list. Invalid parameter values leave the receiver unchanged.
type NeuralNetworkDetectResult ¶
type NeuralNetworkDetectResult struct {
Box Rect `json:"box"`
ClsIndex uint64 `json:"cls_index"`
Label string `json:"label"`
Score float64 `json:"score"`
}
NeuralNetworkDetectResult is the decoded NeuralNetworkDetect result from a recognition detail JSON, with keys cls_index, label, box, and score.
type NextItem ¶
type NextItem struct {
// Name is the name of the target node.
Name string `json:"name"`
// JumpBack indicates whether to jump back to the parent node after this node's chain completes.
JumpBack bool `json:"jump_back"`
// Anchor resolves Name as an anchor name rather than a literal node name.
Anchor bool `json:"anchor"`
}
NextItem is one item in the list of nodes to run next. It is used in Node.Next (on success) and Node.OnError (on failure). Node.UnmarshalJSON accepts bare node-name strings in these fields; direct decoding into NextItem does not support this shorthand. A string may carry [JumpBack] and [Anchor] prefixes, and unrecognized prefixes are ignored, matching the native parser. Shorthand entries re-encode as objects, matching native output.
func (NextItem) FormatName ¶
FormatName returns the name with attribute prefixes, e.g. [JumpBack]NodeA.
type Node ¶
type Node struct {
Name string `json:"-"`
// Anchor maps anchor names to target node names, matching GetNodeData output.
// Target names are retained without checking whether they exist.
// A nil map is omitted to inherit the existing configuration or defaults.
// A non-nil empty map encodes as an empty object and clears the node's
// configuration, leaving runtime anchors intact.
// An empty target name clears that runtime anchor after the node is hit and
// its action returns. Direct Node decoding accepts only the object form;
// see [Pipeline.UnmarshalJSON] for shorthand input.
Anchor map[string]string `json:"anchor,omitzero"`
// Recognition defines how this node recognizes targets on screen.
Recognition *Recognition `json:"recognition,omitempty"`
// Action defines what action to perform when recognition succeeds.
Action *Action `json:"action,omitempty"`
// Next specifies the list of possible next nodes to execute.
// Decoding also accepts the protocol's shorthand: a single node value in
// place of the list, and bare node-name strings in place of objects.
Next []NextItem `json:"next,omitempty"`
// RateLimit sets the minimum interval between recognition attempts in milliseconds. Default: 1000.
RateLimit *int64 `json:"rate_limit,omitempty"`
// Timeout sets the maximum time to wait for recognition in milliseconds. Default: 20000; -1 waits indefinitely.
Timeout *int64 `json:"timeout,omitempty"`
// OnError specifies nodes to execute when recognition times out or action execution fails.
// Decoding accepts the same shorthand forms as Next.
OnError []NextItem `json:"on_error,omitempty"`
// Inverse inverts the recognition result. Default: false.
Inverse bool `json:"inverse,omitempty"`
// Enabled determines whether this node is active. Default: true.
// The native parser also accepts the legacy "enable" alias; this model
// only decodes "enabled".
Enabled *bool `json:"enabled,omitempty"`
// MaxHit sets the maximum hit count of the node. Default: unlimited.
// The native parser stores this as a 32-bit unsigned int.
MaxHit *uint64 `json:"max_hit,omitempty"`
// PreDelay sets the delay before action execution in milliseconds. Default: 200.
PreDelay *int64 `json:"pre_delay,omitempty"`
// PostDelay sets the delay after action execution in milliseconds. Default: 200.
PostDelay *int64 `json:"post_delay,omitempty"`
// PreWaitFreezes waits for screen to stabilize before action execution.
PreWaitFreezes *WaitFreezesParam `json:"pre_wait_freezes,omitempty"`
// PostWaitFreezes waits for screen to stabilize after action.
PostWaitFreezes *WaitFreezesParam `json:"post_wait_freezes,omitempty"`
// Repeat specifies the number of times to repeat the node. Default: 1.
// The native parser stores this as a 32-bit unsigned int.
Repeat *uint64 `json:"repeat,omitempty"`
// RepeatDelay sets the delay between repetitions in milliseconds. Default: 0.
RepeatDelay *int64 `json:"repeat_delay,omitempty"`
// RepeatWaitFreezes waits for screen to stabilize between repetitions.
RepeatWaitFreezes *WaitFreezesParam `json:"repeat_wait_freezes,omitempty"`
// Focus specifies custom focus data.
Focus any `json:"focus,omitempty"`
// Attach provides additional custom data for the node.
Attach map[string]any `json:"attach,omitempty"`
}
Node represents a single task node using pipeline v2 JSON. Action and Recognition use nested type/param objects; a recognition or action object without "param" decodes its parameters from the whole object, and the v1 flat form (string recognition/action with parameters flat on the node) normalizes into this v2 model, matching the native parser. Encoding always emits v2. Omitted fields are resolved by MaaFramework using the existing node or its defaults. Node values shared across goroutines require caller synchronization.
func (*Node) AddAnchor ¶
AddAnchor sets an anchor to the current node and returns the node for chaining.
func (*Node) AddNext ¶
func (n *Node) AddNext(name string, opts ...NodeAttributeOption) *Node
AddNext appends a node to the next list and returns the node for chaining.
func (*Node) AddOnError ¶
func (n *Node) AddOnError(name string, opts ...NodeAttributeOption) *Node
AddOnError appends a node to the on_error list and returns the node for chaining.
func (*Node) ClearAnchor ¶
ClearAnchor marks an anchor as cleared and returns the node for chaining.
func (*Node) RemoveAnchor ¶
RemoveAnchor removes an anchor from the node and returns the node for chaining.
func (*Node) RemoveNext ¶
RemoveNext removes a node from the next list and returns the node for chaining.
func (*Node) RemoveOnError ¶
RemoveOnError removes a node from the on_error list and returns the node for chaining.
func (*Node) SetAnchorTarget ¶
SetAnchorTarget sets an anchor to a specific target node and returns the node for chaining.
func (*Node) SetAttach ¶
SetAttach sets the attached custom data for the node and returns the node for chaining. The map is copied so the node does not share state with the caller. A nil attach is stored as an empty map so that Attach is never nil.
func (*Node) SetEnabled ¶
SetEnabled sets whether the node is enabled and returns the node for chaining.
func (*Node) SetFocus ¶
SetFocus sets the focus data for the node and returns the node for chaining.
func (*Node) SetInverse ¶
SetInverse sets whether to invert the recognition result and returns the node for chaining.
func (*Node) SetMaxHit ¶
SetMaxHit sets the maximum hit count of the node and returns the node for chaining.
func (*Node) SetNext ¶
SetNext sets the next nodes list for the node and returns the node for chaining.
func (*Node) SetOnError ¶
SetOnError sets the error handling nodes for the node and returns the node for chaining.
func (*Node) SetPostDelay ¶
SetPostDelay sets the delay after action execution and returns the node for chaining.
func (*Node) SetPostWaitFreezes ¶
func (n *Node) SetPostWaitFreezes(postWaitFreezes *WaitFreezesParam) *Node
SetPostWaitFreezes sets the post-action wait freezes configuration and returns the node for chaining.
func (*Node) SetPreDelay ¶
SetPreDelay sets the delay before action execution and returns the node for chaining.
func (*Node) SetPreWaitFreezes ¶
func (n *Node) SetPreWaitFreezes(preWaitFreezes *WaitFreezesParam) *Node
SetPreWaitFreezes sets the pre-action wait freezes configuration and returns the node for chaining.
func (*Node) SetRateLimit ¶
SetRateLimit sets the rate limit for the node and returns the node for chaining.
func (*Node) SetRecognition ¶
func (n *Node) SetRecognition(rec *Recognition) *Node
SetRecognition sets the recognition for the node and returns the node for chaining.
func (*Node) SetRepeat ¶
SetRepeat sets the number of times to repeat the node and returns the node for chaining.
func (*Node) SetRepeatDelay ¶
SetRepeatDelay sets the delay between repetitions and returns the node for chaining.
func (*Node) SetRepeatWaitFreezes ¶
func (n *Node) SetRepeatWaitFreezes(repeatWaitFreezes *WaitFreezesParam) *Node
SetRepeatWaitFreezes sets the wait freezes configuration between repetitions and returns the node for chaining.
func (*Node) SetTimeout ¶
SetTimeout sets the timeout for the node and returns the node for chaining.
func (*Node) UnmarshalJSON ¶
UnmarshalJSON decodes the formats described by Node and its fields. Fields absent from the input, including Name, are reset to their zero values; decoding replaces the node rather than merging into it. On error the node is unchanged.
type NodeActionDetail ¶
type NodeActionDetail struct {
TaskID uint64 `json:"task_id"`
ActionID uint64 `json:"action_id"`
Name string `json:"name"`
Focus any `json:"focus"`
}
NodeActionDetail contains information about node action events
type NodeActionNodeDetail ¶
type NodeActionNodeDetail struct {
TaskID uint64 `json:"task_id"`
NodeID uint64 `json:"node_id"`
Name string `json:"name"`
Focus any `json:"focus"`
}
NodeActionNodeDetail contains information about action node events
type NodeAttributeOption ¶
type NodeAttributeOption func(*NextItem)
NodeAttributeOption is a functional option for configuring NextItem attributes.
func WithAnchor ¶
func WithAnchor() NodeAttributeOption
WithAnchor enables anchor reference. The name field will be treated as an anchor name and resolved to the last node that set this anchor at runtime.
func WithJumpBack ¶
func WithJumpBack() NodeAttributeOption
WithJumpBack enables the jump-back mechanism. When this node matches, the system returns to the parent node after completing this node's chain, and continues recognizing from the start of next list. Jump-back is not performed while running the on_error chain.
type NodeDetail ¶
type NodeDetail struct {
ID int64
Name string
Recognition *RecognitionDetail
Action *ActionDetail
RunCompleted bool
}
NodeDetail contains node information.
type NodeNextListDetail ¶
type NodeNextListDetail struct {
TaskID uint64 `json:"task_id"`
Name string `json:"name"`
List []NextItem `json:"list"`
Focus any `json:"focus"`
}
NodeNextListDetail contains information about node next list events
type NodePipelineNodeDetail ¶
type NodePipelineNodeDetail struct {
TaskID uint64 `json:"task_id"`
NodeID uint64 `json:"node_id"`
Name string `json:"name"`
Focus any `json:"focus"`
}
NodePipelineNodeDetail contains information about pipeline node events
type NodeRecognitionDetail ¶
type NodeRecognitionDetail struct {
TaskID uint64 `json:"task_id"`
RecognitionID uint64 `json:"reco_id"`
Name string `json:"name"`
Focus any `json:"focus"`
}
NodeRecognitionDetail contains information about node recognition events
type NodeRecognitionNodeDetail ¶
type NodeRecognitionNodeDetail struct {
TaskID uint64 `json:"task_id"`
NodeID uint64 `json:"node_id"`
Name string `json:"name"`
Focus any `json:"focus"`
}
NodeRecognitionNodeDetail contains information about recognition node events
type NodeRef ¶
type NodeRef struct {
// contains filtered or unexported fields
}
NodeRef is a lightweight reference to a node detail that can be queried on demand.
func (NodeRef) GetDetail ¶
func (n NodeRef) GetDetail() (*NodeDetail, error)
GetDetail queries the referenced node detail on demand.
type NodeWaitFreezesDetail ¶
type NodeWaitFreezesDetail struct {
TaskID uint64 `json:"task_id"`
WfID int64 `json:"wf_id"`
Name string `json:"name"`
Phase string `json:"phase"`
ROI Rect `json:"roi"`
Param map[string]any `json:"param"`
RecoIDs []int64 `json:"reco_ids,omitempty"`
Elapsed uint64 `json:"elapsed,omitempty"`
Focus any `json:"focus"`
}
NodeWaitFreezesDetail contains wait-freezes lifecycle data. Param retains native JSON values. RecoIDs and Elapsed are supplied on completion: the Starting payload carries neither key, and both the Succeeded and Failed payloads attach them. Phase reports which wait-freezes stage fired: "pre", "repeat", or "post" for a pipeline node's stages, or "context" for a wait started via Context.WaitFreezes. Elapsed is measured in milliseconds.
type OCRParam ¶
type OCRParam struct {
// ROI specifies the region of interest for recognition.
ROI Target `json:"roi,omitzero"`
// ROIOffset specifies an offset applied to ROI. The zero value is omitted
// to inherit the existing/default offset; an explicit zero offset cannot
// be expressed with this value-type field.
ROIOffset Rect `json:"roi_offset,omitzero"`
// Expected specifies the expected text results, supports regex.
// JSON input may be a single string or an array of strings.
// Nil is omitted to inherit the existing/default value; an empty
// non-nil list clears it.
// The deprecated upstream "text" alias decodes into Expected when
// "expected" is absent; encoding always uses "expected".
Expected StringList `json:"expected,omitzero"`
// Threshold specifies the model confidence threshold [0-1.0]. Default: 0.3.
Threshold float64 `json:"threshold,omitempty"`
// Replace specifies text replacement rules for correcting OCR errors,
// applied as regex replacements. JSON input may be a single
// ["pattern","replacement"] pair; a single pair normalizes to a
// one-pair list.
Replace [][2]string `json:"replace,omitempty"`
// OrderBy specifies how results are sorted. Default: Horizontal. Options: Horizontal | Vertical | Area | Length | Random | Expected.
OrderBy OCROrderBy `json:"order_by,omitempty"`
// Index specifies which match to select from results.
Index int `json:"index,omitempty"`
// OnlyRec enables recognition-only mode without detection (requires precise ROI). Default: false.
OnlyRec bool `json:"only_rec,omitempty"`
// Model specifies the model folder path relative to model/ocr directory.
Model string `json:"model,omitempty"`
// ColorFilter specifies a ColorMatch node name whose color parameters (method, lower, upper)
// are used to binarize the image before OCR. Nodes with this field set will not participate in batch optimization.
// Recognition fails at run time if the referenced node does not exist or is not a ColorMatch node.
ColorFilter string `json:"color_filter,omitempty"`
}
OCRParam defines parameters for OCR text recognition.
func (*OCRParam) UnmarshalJSON ¶
UnmarshalJSON maps the deprecated "text" alias to Expected when "expected" is absent and normalizes a single replace pair to a one-pair list, matching the native parser. A single pair must contain exactly two non-null strings. Omitted fields retain their existing values. On error the param is unchanged.
type OCRResult ¶
type OCRResult struct {
Box Rect `json:"box"`
Text string `json:"text"`
Score float64 `json:"score"`
}
OCRResult is the decoded OCR result from a recognition detail JSON, with keys text, box, and score.
type OrRecognitionParam ¶
type OrRecognitionParam struct {
// AnyOf lists the sub-recognitions, one of which must succeed. Elements
// are node name references or inline recognitions (SubRecognitionItem).
AnyOf []SubRecognitionItem `json:"any_of,omitempty"`
}
OrRecognitionParam defines parameters for OR recognition. AnyOf elements are either node name strings or inline recognitions.
type OrderBy ¶
type OrderBy string
OrderBy defines the ordering options for recognition results. Different recognition types support different subsets of these values; the per-type OrderBy constants declare the values each parser accepts. The native parser also reads the "order" key as an alias for "order_by" and accepts all-lowercase spellings and "Default" (the default ordering); this model only uses the canonical key, and values pass through unchanged.
const ( OrderByHorizontal OrderBy = "Horizontal" OrderByVertical OrderBy = "Vertical" OrderByScore OrderBy = "Score" OrderByArea OrderBy = "Area" OrderByLength OrderBy = "Length" OrderByRandom OrderBy = "Random" OrderByExpected OrderBy = "Expected" )
Result ordering options shared across recognition types.
type Pipeline ¶
type Pipeline struct {
// contains filtered or unexported fields
}
Pipeline represents a collection of nodes that define a task flow. A task is a logical sequential structure of nodes connected in a specific order, representing the entire process from start to finish; its first node is the entry. A Pipeline is not safe for concurrent modification; callers must synchronize access.
func (*Pipeline) AddNode ¶
AddNode adds a node to the pipeline and returns the pipeline for chaining.
func (*Pipeline) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface.
func (*Pipeline) RemoveNode ¶
RemoveNode removes a node by name and returns the pipeline for chaining.
func (*Pipeline) UnmarshalJSON ¶
UnmarshalJSON replaces the pipeline with a JSON object keyed by node name. Keys starting with "$" are ignored, matching the native parser. Each node decodes via Node.UnmarshalJSON and takes its Name from the map key. Anchor strings and string lists normalize to maps pointing to the containing node. An omitted anchor remains nil; an empty list or object becomes a non-nil empty map. See Node for anchor encoding and runtime semantics. JSON null decodes to an empty pipeline. On error the pipeline is unchanged.
type Point ¶
type Point [2]int
Point represents a 2D point [x, y].
func (*Point) UnmarshalJSON ¶
UnmarshalJSON decodes a point from a two-element array [x, y]. A JSON string containing the same array, e.g. `"[1, 2]"`, is also accepted.
type PortalHelper ¶
type PortalHelper struct {
// contains filtered or unexported fields
}
PortalHelper manages an xdg-desktop-portal ScreenCast session. Call Destroy when the session is no longer needed; the session is released, but the PipeWire file descriptor is not closed. Do not use the helper after Destroy. A PortalHelper must not be copied after creation. A nil or zero-value helper behaves like a destroyed helper: OpenStream reports an error, PipeWireFD returns -1, and the other getters return zero values.
func NewPortalHelper ¶
func NewPortalHelper() (*PortalHelper, error)
NewPortalHelper creates a ScreenCast portal helper.
func (*PortalHelper) Destroy ¶
func (p *PortalHelper) Destroy()
Destroy closes the portal session and frees the helper. It is safe to call more than once, including from concurrent goroutines.
func (*PortalHelper) OpenStream ¶
func (p *PortalHelper) OpenStream() error
OpenStream opens a ScreenCast stream through xdg-desktop-portal.
func (*PortalHelper) Persist ¶
func (p *PortalHelper) Persist() bool
Persist reports whether the portal session is configured to persist.
func (*PortalHelper) PipeWireFD ¶
func (p *PortalHelper) PipeWireFD() int
PipeWireFD returns the portal's PipeWire socket FD for pw_socket_fd. The helper owns the FD; keep it alive while a controller uses the stream.
func (*PortalHelper) PipeWireNodeID ¶
func (p *PortalHelper) PipeWireNodeID() uint32
PipeWireNodeID returns the stream node ID for pw_node_id.
func (*PortalHelper) RestoreToken ¶
func (p *PortalHelper) RestoreToken() string
RestoreToken returns the token that can restore a persistent session.
func (*PortalHelper) SetPersist ¶
func (p *PortalHelper) SetPersist(enable bool)
SetPersist configures whether the portal session should persist.
func (*PortalHelper) SetRestoreToken ¶
func (p *PortalHelper) SetRestoreToken(token string)
SetRestoreToken sets a token from a previous persistent session before OpenStream.
type RawActionParam ¶
type RawActionParam json.RawMessage
RawActionParam holds an uninterpreted JSON action parameter value. Action.UnmarshalJSON uses *RawActionParam for unrecognized action types. It preserves parameter content, including large JSON integers, without converting it to Go values. JSON encoding may normalize whitespace and escape sequences.
It can also be supplied wherever ActionParam is accepted, for example:
action := &Action{
Type: ActionType("FutureAction"),
Param: RawActionParam(`{"new_option":true}`),
}
The native library must support the type and parameters. RawActionParam does not add typed result parsing or validate the parameters against the protocol. A nil value encodes as null. Converting a byte slice to RawActionParam shares its backing array; UnmarshalJSON copies its input.
Example ¶
package main
import (
"encoding/json"
"fmt"
maa "github.com/MaaXYZ/maa-framework-go/v4"
)
func main() {
action := &maa.Action{
Type: maa.ActionType("FutureAction"),
Param: maa.RawActionParam(`{"value":9007199254740993}`),
}
encoded, err := json.Marshal(action)
if err != nil {
panic(err)
}
fmt.Println(string(encoded))
}
Output: {"type":"FutureAction","param":{"value":9007199254740993}}
func (RawActionParam) MarshalJSON ¶
func (p RawActionParam) MarshalJSON() ([]byte, error)
MarshalJSON encodes the parameter as a JSON value, rejecting invalid JSON.
func (*RawActionParam) UnmarshalJSON ¶
func (p *RawActionParam) UnmarshalJSON(data []byte) error
UnmarshalJSON validates and copies the parameter JSON without interpreting its fields.
type RawRecognitionParam ¶
type RawRecognitionParam json.RawMessage
RawRecognitionParam holds an uninterpreted JSON recognition parameter value. Recognition.UnmarshalJSON uses *RawRecognitionParam for unrecognized recognition types. It preserves parameter content, including large JSON integers, without converting it to Go values. JSON encoding may normalize whitespace and escape sequences.
It can also be supplied wherever RecognitionParam is accepted. The native library must support the type and parameters; this does not add typed result parsing or validate parameters against the protocol. A nil value encodes as null. Converting a byte slice shares its backing array; UnmarshalJSON copies its input.
Example ¶
package main
import (
"encoding/json"
"fmt"
maa "github.com/MaaXYZ/maa-framework-go/v4"
)
func main() {
var recognition maa.Recognition
err := json.Unmarshal([]byte(`{"type":"FutureMatcher","param":{"new_option":true}}`), &recognition)
if err != nil {
panic(err)
}
param := recognition.Param.(*maa.RawRecognitionParam)
fmt.Println(recognition.Type)
fmt.Println(string(*param))
}
Output: FutureMatcher {"new_option":true}
func (RawRecognitionParam) MarshalJSON ¶
func (p RawRecognitionParam) MarshalJSON() ([]byte, error)
MarshalJSON encodes the parameter as a JSON value, rejecting invalid JSON.
func (*RawRecognitionParam) UnmarshalJSON ¶
func (p *RawRecognitionParam) UnmarshalJSON(data []byte) error
UnmarshalJSON validates and copies the parameter JSON without interpreting its fields.
type Recognition ¶
type Recognition struct {
// Type specifies the recognition algorithm type.
Type RecognitionType `json:"type,omitempty"`
// Param specifies the recognition parameters.
// A nil Param omits param when encoding. For unknown types, an explicit JSON null is retained.
// When decoding, an absent "param" reads parameters from the whole
// recognition object, so flat fields are preserved instead of lost.
Param RecognitionParam `json:"param,omitempty"`
}
Recognition defines a node's recognition using the pipeline v2 type/param object format. Known types decode to their typed parameters. Unrecognized type names — including the lowercase aliases the native parser accepts, such as "ocr" — retain their parameter JSON as *RawRecognitionParam; this does not establish native support. Unknown fields outside param, and unmodeled fields of known parameters, are not retained. Like the native parser, a recognition object without a param key reads its parameters from the whole object.
func RecAnd ¶
func RecAnd(items ...SubRecognitionItem) *Recognition
RecAnd creates an AND recognition that requires all sub-recognitions to succeed. Use SetBoxIndex to set which result's box to use. Example: RecAnd(Ref("NodeA"), Inline(RecDirectHit(), "sub1")).SetBoxIndex(1)
func RecColorMatch ¶
func RecColorMatch(p ColorMatchParam) *Recognition
RecColorMatch creates a ColorMatch recognition with the given parameters.
func RecCustom ¶
func RecCustom(p CustomRecognitionParam) *Recognition
RecCustom creates a Custom recognition with the given parameters.
func RecDirectHit ¶
func RecDirectHit() *Recognition
RecDirectHit creates a DirectHit recognition with the default ROI, without image matching. To choose an ROI, set the returned recognition's Param to a DirectHitParam.
func RecFeatureMatch ¶
func RecFeatureMatch(p FeatureMatchParam) *Recognition
RecFeatureMatch creates a FeatureMatch recognition with the given parameters. Feature matching provides better generalization with perspective and scale invariance.
func RecNeuralNetworkClassify ¶
func RecNeuralNetworkClassify(p NeuralNetworkClassifyParam) *Recognition
RecNeuralNetworkClassify creates a NeuralNetworkClassify recognition with the given parameters. This classifies images at fixed positions into predefined categories.
func RecNeuralNetworkDetect ¶
func RecNeuralNetworkDetect(p NeuralNetworkDetectParam) *Recognition
RecNeuralNetworkDetect creates a NeuralNetworkDetect recognition with the given parameters. This detects objects at arbitrary positions using deep learning models like YOLO.
func RecOCR ¶
func RecOCR(p OCRParam) *Recognition
RecOCR creates an OCR recognition with the given parameters. All fields are optional; pass OCRParam{} for defaults.
func RecOr ¶
func RecOr(anyOf ...SubRecognitionItem) *Recognition
RecOr creates an OR recognition that succeeds if any sub-recognition succeeds.
func RecTemplateMatch ¶
func RecTemplateMatch(p TemplateMatchParam) *Recognition
RecTemplateMatch creates a TemplateMatch recognition with the given parameters.
func (*Recognition) SetBoxIndex ¶
func (nr *Recognition) SetBoxIndex(idx int) *Recognition
SetBoxIndex sets which sub-recognition result's box to use as the final box. Only effective when the recognition type is And. The native parser requires 0 <= idx < len(all_of) and fails to load the node otherwise.
func (*Recognition) UnmarshalJSON ¶
func (nr *Recognition) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes a pipeline v2 recognition. Errors in known parameter types are returned without falling back to raw JSON. On error the recognition is unchanged. When "param" is absent, parameters are decoded from the whole recognition object, matching the native parser, so flat fields such as {"type":"ColorMatch","lower":...} are preserved instead of silently lost.
type RecognitionDetail ¶
type RecognitionDetail struct {
ID int64
Name string
Algorithm string
Hit bool
Box Rect
DetailJson string
Results *RecognitionResults // nil if algorithm is DirectHit, And or Or.
CombinedResult []*RecognitionDetail // for And/Or algorithms only.
Raw image.Image // available only in debug mode.
Draws []image.Image // available when debug mode or save_draw is enabled.
}
RecognitionDetail contains recognition information.
PostAction and Context.RunActionDirect marshal the recognition detail as an opaque JSON payload for the native layer: with the default JSON codec the keys are the Go field names, and Raw and Draws embed internal image data rather than usable image content. The native layer does not parse the payload keys, but the shape differs from the RecoResult JSON (keys reco_id, name, algorithm, box, detail) the C API emits for recognition details.
Raw and Draws come from the recognition image cache and are subject to its size limit (see SetRecoImageCacheLimit).
type RecognitionParam ¶
type RecognitionParam interface {
// contains filtered or unexported methods
}
RecognitionParam is the interface for typed recognition parameters and RawRecognitionParam. Builders and decoders do not validate protocol constraints such as threshold ranges, list-length agreements, or required fields; the native parser rejects invalid combinations when the pipeline is posted.
type RecognitionResult ¶
type RecognitionResult struct {
// contains filtered or unexported fields
}
RecognitionResult is the decoded view of a single recognition result from a recognition detail JSON. The underlying value is discriminated by the algorithm string reported by the framework; use Type, Value, and the As methods to access it. An unrecognized algorithm string is a decode error, so only the algorithm set currently produced by the framework decodes.
func (*RecognitionResult) AsColorMatch ¶
func (r *RecognitionResult) AsColorMatch() (*ColorMatchResult, bool)
AsColorMatch returns the result as ColorMatchResult if the type matches.
func (*RecognitionResult) AsCustom ¶
func (r *RecognitionResult) AsCustom() (*CustomRecognitionResult, bool)
AsCustom returns the result as CustomRecognitionResult if the type matches.
func (*RecognitionResult) AsFeatureMatch ¶
func (r *RecognitionResult) AsFeatureMatch() (*FeatureMatchResult, bool)
AsFeatureMatch returns the result as FeatureMatchResult if the type matches.
func (*RecognitionResult) AsNeuralNetworkClassify ¶
func (r *RecognitionResult) AsNeuralNetworkClassify() (*NeuralNetworkClassifyResult, bool)
AsNeuralNetworkClassify returns the result as NeuralNetworkClassifyResult if the type matches.
func (*RecognitionResult) AsNeuralNetworkDetect ¶
func (r *RecognitionResult) AsNeuralNetworkDetect() (*NeuralNetworkDetectResult, bool)
AsNeuralNetworkDetect returns the result as NeuralNetworkDetectResult if the type matches.
func (*RecognitionResult) AsOCR ¶
func (r *RecognitionResult) AsOCR() (*OCRResult, bool)
AsOCR returns the result as OCRResult if the type matches.
func (*RecognitionResult) AsTemplateMatch ¶
func (r *RecognitionResult) AsTemplateMatch() (*TemplateMatchResult, bool)
AsTemplateMatch returns the result as TemplateMatchResult if the type matches.
func (*RecognitionResult) Type ¶
func (r *RecognitionResult) Type() RecognitionType
Type returns the recognition type of the result.
func (*RecognitionResult) Value ¶
func (r *RecognitionResult) Value() any
Value returns the underlying value of the result.
type RecognitionResults ¶
type RecognitionResults struct {
All []*RecognitionResult `json:"all"`
Best *RecognitionResult `json:"best"`
Filtered []*RecognitionResult `json:"filtered"`
}
RecognitionResults contains all, best, and filtered recognition results. Detail JSON format: {"all": [Result...], "best": Result | null, "filtered": [Result...]} if algorithm is direct hit, Results is nil
type RecognitionType ¶
type RecognitionType string
RecognitionType names a pipeline v2 recognition. Constants identify the types modeled by this package; other names may be used with RawRecognitionParam if the native library supports them.
const ( RecognitionTypeDirectHit RecognitionType = "DirectHit" RecognitionTypeTemplateMatch RecognitionType = "TemplateMatch" RecognitionTypeFeatureMatch RecognitionType = "FeatureMatch" RecognitionTypeColorMatch RecognitionType = "ColorMatch" RecognitionTypeOCR RecognitionType = "OCR" RecognitionTypeNeuralNetworkClassify RecognitionType = "NeuralNetworkClassify" RecognitionTypeNeuralNetworkDetect RecognitionType = "NeuralNetworkDetect" RecognitionTypeAnd RecognitionType = "And" RecognitionTypeOr RecognitionType = "Or" RecognitionTypeCustom RecognitionType = "Custom" )
Recognition algorithm type names used by the pipeline v2 protocol.
type Rect ¶
Rect is a [4]int rectangle: x, y, width, height. It is the Go type for pipeline ROI offsets, action target offsets, and result boxes.
JSON decodes [x, y] as a 1x1 rectangle at (x, y) and [x, y, w, h] as-is, mirroring the upstream pipeline parser; null, any other length, or a non-integer element is an error and leaves the rectangle unchanged. The zero value is omitted by the encoding/json "omitzero" option, so pipeline defaults and parent-node inheritance apply.
type Resource ¶
type Resource struct {
// contains filtered or unexported fields
}
Resource manages the loading and configuration of resources required by Tasker. It handles pipeline definitions, OCR models, images, and inference device settings. Resource also provides registration of custom recognitions and actions.
A Resource created with NewResource owns its native handle and should be destroyed with Destroy when no longer needed. Resource changes such as option changes and PostBundle, PostPipeline, PostOcrModel, and PostImage loads are not serialized by this wrapper; callers must serialize them.
func (*Resource) AddSink ¶
func (r *Resource) AddSink(sink ResourceEventSink) int64
AddSink adds an event callback sink and returns the sink ID. The sink ID can be used to remove the sink later. The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback. It returns 0 if registration fails or the object is closed.
func (*Resource) Clear ¶
Clear clears loaded content. This method fails if resources are currently loading.
func (*Resource) ClearCustomAction ¶
ClearCustomAction clears all custom action runners registered on the resource. The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback.
func (*Resource) ClearCustomRecognition ¶
ClearCustomRecognition clears all custom recognition runners registered on the resource. The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback.
func (*Resource) ClearSinks ¶
func (r *Resource) ClearSinks()
ClearSinks clears all event callback sinks. The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback.
func (*Resource) Destroy ¶
Destroy closes the resource once; repeated successful calls are safe. It returns ErrBound while a tasker uses it or an AgentClient retains it, ErrInUse while a call or job is active — even if the returned Job was discarded — ErrInCallback when called from one of its callbacks, and ErrBorrowed when called on a getter or callback view. A successful Destroy returns after native cleanup and prevents subsequent user callbacks.
func (*Resource) GetCustomActionList ¶
GetCustomActionList returns the custom action list of the resource.
func (*Resource) GetCustomRecognitionList ¶
GetCustomRecognitionList returns the custom recognition list of the resource.
func (*Resource) GetDefaultActionParam ¶
func (r *Resource) GetDefaultActionParam(actionType ActionType) (ActionParam, error)
GetDefaultActionParam returns the default action parameters for the specified type from DefaultPipelineMgr. actionType is an action type (e.g., ActionTypeClick, ActionTypeSwipe). Known types return typed parameters; other types supported by the native library return *RawActionParam. Native lookup failures and known-type decode errors are returned.
func (*Resource) GetDefaultRecognitionParam ¶
func (r *Resource) GetDefaultRecognitionParam(recoType RecognitionType) (RecognitionParam, error)
GetDefaultRecognitionParam returns the default recognition parameters for the specified type from DefaultPipelineMgr. recoType is a recognition type (e.g., RecognitionTypeOCR, RecognitionTypeTemplateMatch). Known types return typed parameters; other types supported by the native library return *RawRecognitionParam. Native lookup failures and known-type decode errors are returned.
func (*Resource) GetHash ¶
GetHash returns the hash of the loaded resource content. It fails while the hash is empty, for example on a newly created resource that has never posted a load.
func (*Resource) GetNode ¶
GetNode returns the node definition by name. It fetches the node JSON via GetNodeJSON and unmarshals it into a Node struct. The returned node has Name set to the requested name and Attach non-nil, an empty map when the definition has no attach fields.
func (*Resource) GetNodeJSON ¶
GetNodeJSON gets the task definition JSON of a node by name. It returns an error when the name is unknown.
func (*Resource) GetNodeList ¶
GetNodeList returns the node list of the resource.
func (*Resource) Loaded ¶
Loaded reports the validity flag of the loaded resource content. A newly created resource reports true; submitting a load flips the flag to false until the load completes.
func (*Resource) OnResourceLoading ¶
func (r *Resource) OnResourceLoading(fn func(EventStatus, ResourceLoadingDetail)) int64
OnResourceLoading registers a callback sink that only handles Resource.Loading events and returns the sink ID. The sink ID can be used to remove the sink later.
func (*Resource) OverrideImage ¶
OverrideImage overrides the image data for the specified image name.
func (*Resource) OverrideNext ¶
OverrideNext overrides the next list of a task by name. It sets the list directly and will create the node if it doesn't exist.
func (*Resource) OverridePipeline ¶
OverridePipeline overrides pipeline nodes. override can be a JSON string or any value that can be marshaled to JSON. The top level must be a JSON object keyed by node name; each value is a node definition object whose unspecified fields inherit the node's currently loaded definition. Keys starting with "$" are skipped, and defining the same node twice in one call is rejected. Invalid input returns an error.
func (*Resource) PostBundle ¶
PostBundle asynchronously loads resource paths and returns a Job. This is an async operation that immediately returns a Job, which can be queried via status/wait. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed. Submitting a load clears the loaded state and the resource hash until the load completes.
func (*Resource) PostImage ¶
PostImage asynchronously loads image resources and returns a Job. Supports loading a directory or a single image file. This is an async operation that immediately returns a Job, which can be queried via status/wait. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed. Submitting a load clears the loaded state and the resource hash until the load completes.
func (*Resource) PostOcrModel ¶
PostOcrModel asynchronously loads an OCR model directory and returns a Job. This is an async operation that immediately returns a Job, which can be queried via status/wait. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed. Submitting a load clears the loaded state and the resource hash until the load completes.
func (*Resource) PostPipeline ¶
PostPipeline asynchronously loads a pipeline and returns a Job. Supports loading a directory or a single json/jsonc file. This is an async operation that immediately returns a Job, which can be queried via status/wait. It returns an error and a terminal-failed job when the request cannot be submitted, for example when the underlying object is closed. Submitting a load clears the loaded state and the resource hash until the load completes.
func (*Resource) RegisterCustomAction ¶
func (r *Resource) RegisterCustomAction(name string, action CustomActionRunner) error
RegisterCustomAction registers a custom action runner to the resource. The registered name is referenced by pipeline nodes via CustomActionParam{CustomAction: name}.
Common registration forms are:
1. A type that implements CustomActionRunner.
type closeDialogAction struct{}
func (closeDialogAction) Run(ctx *Context, arg *CustomActionArg) bool {
...
}
err := res.RegisterCustomAction("CloseDialog", closeDialogAction{})
2. A named function adapted with CustomActionFunc.
func runCloseDialog(ctx *Context, arg *CustomActionArg) bool {
...
}
err := res.RegisterCustomAction("CloseDialog", CustomActionFunc(runCloseDialog))
3. An inline function adapted with CustomActionFunc.
err := res.RegisterCustomAction("CloseDialog", CustomActionFunc(
func(ctx *Context, arg *CustomActionArg) bool {
...
},
))
Use UnregisterCustomAction or ClearCustomAction to remove registrations. Use GetCustomActionList to inspect the currently registered names.
Registering a name that is already taken — by either a recognition or an action — is rejected by the native library and reported as an error. A nil runner, including a typed-nil CustomActionFunc, is rejected before reaching the native library.
The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback.
func (*Resource) RegisterCustomRecognition ¶
func (r *Resource) RegisterCustomRecognition(name string, recognition CustomRecognitionRunner) error
RegisterCustomRecognition registers a custom recognition runner to the resource. The registered name is referenced by pipeline nodes via CustomRecognitionParam{CustomRecognition: name}.
Common registration forms are:
1. A type that implements CustomRecognitionRunner.
type screenTextRecognition struct{}
func (screenTextRecognition) Run(ctx *Context, arg *CustomRecognitionArg) (*CustomRecognitionResult, bool) {
...
}
err := res.RegisterCustomRecognition("ScreenText", screenTextRecognition{})
2. A named function adapted with CustomRecognitionFunc.
func runScreenText(ctx *Context, arg *CustomRecognitionArg) (*CustomRecognitionResult, bool) {
...
}
err := res.RegisterCustomRecognition("ScreenText", CustomRecognitionFunc(runScreenText))
3. An inline function adapted with CustomRecognitionFunc.
err := res.RegisterCustomRecognition("ScreenText", CustomRecognitionFunc(
func(ctx *Context, arg *CustomRecognitionArg) (*CustomRecognitionResult, bool) {
...
},
))
Use UnregisterCustomRecognition or ClearCustomRecognition to remove registrations. Use GetCustomRecognitionList to inspect the currently registered names.
Registering a name that is already taken — by either a recognition or an action — is rejected by the native library and reported as an error. A nil runner, including a typed-nil CustomRecognitionFunc, is rejected before reaching the native library.
The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback.
func (*Resource) RemoveSink ¶
RemoveSink removes an event callback sink by sink ID. Removing an unknown or already-removed sink ID is a no-op. The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback.
func (*Resource) UnregisterCustomAction ¶
UnregisterCustomAction unregisters a runner added with RegisterCustomAction. A name absent from both the Go registry and the native resource is a no-op and returns nil. A name registered outside this wrapper returns an error and remains registered. In particular, registrations added by AgentClient.Connect are managed by the client and removed by AgentClient.Disconnect. The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback.
func (*Resource) UnregisterCustomRecognition ¶
UnregisterCustomRecognition unregisters a runner added with RegisterCustomRecognition. A name absent from both the Go registry and the native resource is a no-op and returns nil. A name registered outside this wrapper returns an error and remains registered. In particular, registrations added by AgentClient.Connect are managed by the client and removed by AgentClient.Disconnect. The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback.
func (*Resource) UseAutoExecutionProvider ¶
UseAutoExecutionProvider lets the native library select the execution provider from the available hardware providers, falling back to CPU when none can be initialized. See UseCPU for when the option takes effect.
func (*Resource) UseCPU ¶
UseCPU selects the CPU execution provider for inference.
Inference options are applied when a Post* load runs, so set them before loading a model. A later change takes effect at the next load for model sessions created afterwards; already created sessions keep their provider. When the selected provider cannot be initialized, loading falls back to CPU.
func (*Resource) UseDirectml ¶
func (r *Resource) UseDirectml(deviceID InferenceDevice) error
UseDirectml selects the DirectML execution provider. deviceID is the DirectML adapter id from Win32 EnumAdapters1; use InferenceDeviceAuto for auto selection. See UseCPU for when the option takes effect.
func (*Resource) UseWebgpu ¶
func (r *Resource) UseWebgpu(deviceID InferenceDevice) error
UseWebgpu selects the WebGPU execution provider. deviceID is the WebGPU device id (ep.webgpuexecutionprovider.deviceId); use InferenceDeviceAuto to let the framework choose, which selects device 0. The provider ships on Windows, Linux, and macOS and needs MaaFramework v5.14.3 or later. See UseCPU for when the option takes effect.
With an earlier native library the value is not a known provider: loading logs an invalid provider and falls back to CPU instead of failing the set, matching how the other provider setters behave.
type ResourceEventSink ¶
type ResourceEventSink interface {
// OnResourceLoading receives Resource.Loading events: status is
// EventStatusStarting before the load runs, then EventStatusSucceeded or
// EventStatusFailed with the outcome, and detail describes the submitted
// path.
OnResourceLoading(res *Resource, event EventStatus, detail ResourceLoadingDetail)
}
ResourceEventSink is the interface for receiving resource-level events. Handler methods run synchronously on native calling threads, may overlap with other callbacks, and must not wait for work that requires them to return.
type ResourceLoadingDetail ¶
type ResourceLoadingDetail struct {
ResID uint64 `json:"res_id"`
Hash string `json:"hash"`
Path string `json:"path"`
// Type is the kind of load the event reports: the upstream PostPathType
// serialized as its value name, one of "Bundle", "OcrModel", "Pipeline",
// or "Image".
Type string `json:"type"`
}
ResourceLoadingDetail contains information about resource loading events
type ScreencapActionResult ¶
type ScreencapActionResult struct {
Filepath string `json:"filepath"`
Format string `json:"format"`
Quality int `json:"quality"`
Success bool `json:"success"`
}
ScreencapActionResult holds the parsed detail of a Screencap action.
type ScreencapParam ¶
type ScreencapParam struct {
// Filename specifies screencap filename without extension. Empty means auto-generated by MaaFramework.
Filename string `json:"filename,omitempty"`
// Format specifies image format. Optional values: "png", "jpg", "jpeg". Default: "png".
Format string `json:"format,omitempty"`
// Quality specifies image quality (0-100), only effective for jpg/jpeg. Default: 100.
Quality int `json:"quality,omitempty"`
}
ScreencapParam defines parameters for screencap action.
type ScreenshotOption ¶
type ScreenshotOption func(*screenshotOptionConfig)
ScreenshotOption configures how the screenshot is resized. Options for different settings can be combined; see Controller.SetScreenshot for validation and conflict rules.
func WithScreenshotResizeMethod ¶
func WithScreenshotResizeMethod(method ScreenshotResizeMethod) ScreenshotOption
WithScreenshotResizeMethod sets the interpolation method used when resizing screenshots. Defaults to ScreenshotResizeMethodArea (cv::INTER_AREA). Only values from ScreenshotResizeMethodNearestNeighbor through ScreenshotResizeMethodLanczos4 are supported (0 through 4).
func WithScreenshotTargetExpand ¶
func WithScreenshotTargetExpand(width, height int32) ScreenshotOption
WithScreenshotTargetExpand scales screenshots uniformly to cover the reference width and height. The scale is max(width/rawWidth, height/rawHeight), preserving the source aspect ratio without cropping or stretching. Both output dimensions are at least the reference size. Width and height must be positive. Setting this replaces long-side and short-side targets. It does not disable raw-size mode; the target is retained for later use while raw-size mode is active.
func WithScreenshotTargetLongSide ¶
func WithScreenshotTargetLongSide(targetLongSide int32) ScreenshotOption
WithScreenshotTargetLongSide sets screenshot target long side. The short side is scaled proportionally. Setting this replaces short-side and expand targets. The target must be positive. It does not disable raw-size mode.
eg: 1280
func WithScreenshotTargetShortSide ¶
func WithScreenshotTargetShortSide(targetShortSide int32) ScreenshotOption
WithScreenshotTargetShortSide sets screenshot target short side. The long side is scaled proportionally. Setting this replaces long-side and expand targets. The target must be positive. It does not disable raw-size mode.
eg: 720
func WithScreenshotUseRawSize ¶
func WithScreenshotUseRawSize(enabled bool) ScreenshotOption
WithScreenshotUseRawSize sets whether the screenshot uses the raw size without scaling. Enabling raw-size mode retains the target and interpolation method; disabling it resumes scaling with those settings. Combine false with a target option to set a new target and resume scaling in one call.
type ScreenshotResizeMethod ¶
type ScreenshotResizeMethod int32
ScreenshotResizeMethod is the interpolation method used when resizing screenshots. Values correspond to cv::InterpolationFlags.
const ( // ScreenshotResizeMethodNearestNeighbor selects nearest-neighbor interpolation (cv::INTER_NEAREST). ScreenshotResizeMethodNearestNeighbor ScreenshotResizeMethod = 0 // ScreenshotResizeMethodLinear selects bilinear interpolation (cv::INTER_LINEAR). ScreenshotResizeMethodLinear ScreenshotResizeMethod = 1 // ScreenshotResizeMethodCubic selects bicubic interpolation (cv::INTER_CUBIC). ScreenshotResizeMethodCubic ScreenshotResizeMethod = 2 // ScreenshotResizeMethodArea selects pixel-area interpolation (cv::INTER_AREA). // This is the default method. ScreenshotResizeMethodArea ScreenshotResizeMethod = 3 // ScreenshotResizeMethodLanczos4 selects 8x8 Lanczos interpolation (cv::INTER_LANCZOS4). ScreenshotResizeMethodLanczos4 ScreenshotResizeMethod = 4 )
type ScrollActionResult ¶
type ScrollActionResult struct {
// Point is kept to match MaaFramework raw detail JSON.
Point Point `json:"point"`
Dx int `json:"dx"`
Dy int `json:"dy"`
}
ScrollActionResult holds the parsed detail of a Scroll action.
type ScrollParam ¶
type ScrollParam struct {
// Target specifies the scroll target position.
Target Target `json:"target,omitzero"`
// TargetOffset specifies additional offset applied to target.
// JSON accepts [x, y], which expands to a 1x1 offset at (x, y), or [x, y, w, h];
// the zero value omits the field, so the pipeline default or parent-node inheritance applies.
TargetOffset Rect `json:"target_offset,omitzero"`
// Dx specifies the horizontal scroll amount.
Dx int `json:"dx,omitempty"`
// Dy specifies the vertical scroll amount.
Dy int `json:"dy,omitempty"`
}
ScrollParam defines parameters for scroll action.
type ShellActionResult ¶
type ShellActionResult struct {
Cmd string `json:"cmd"`
ShellTimeout int `json:"shell_timeout"`
Success bool `json:"success"`
Output string `json:"output"`
}
ShellActionResult holds the parsed detail of a Shell action.
type ShellParam ¶
type ShellParam struct {
// Cmd specifies the command to run in the controller's shell.
Cmd string `json:"cmd,omitempty"`
// ShellTimeout limits command execution, serialized as integer milliseconds.
// Framework default: 20 seconds. Nil inherits as described in [ActionParam].
// A pointer to zero sends zero explicitly; -time.Millisecond means wait indefinitely.
ShellTimeout *time.Duration `json:"-"`
}
ShellParam defines parameters for shell command execution action.
func (ShellParam) MarshalJSON ¶
func (p ShellParam) MarshalJSON() ([]byte, error)
MarshalJSON encodes the shell timeout in milliseconds, preserving an explicit zero.
func (*ShellParam) UnmarshalJSON ¶
func (p *ShellParam) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the shell timeout from integer milliseconds. It rejects timeout values outside the range of time.Duration.
type StartAppParam ¶
type StartAppParam struct {
// Package specifies the package name or activity to start. Required.
Package string `json:"package,omitempty"`
}
StartAppParam defines parameters for start app action.
type Status ¶
type Status int32
Status represents the lifecycle state of a task or item.
const ( // StatusInvalid is the unknown or uninitialized state, matching // MaaStatus_Invalid in the native API. It is the zero value. StatusInvalid Status = 0 // StatusPending means the item is queued but not yet started, matching // MaaStatus_Pending. StatusPending Status = 1000 // StatusRunning means work is in progress, matching MaaStatus_Running. StatusRunning Status = 2000 // StatusSuccess means the item completed successfully, matching // MaaStatus_Succeeded. StatusSuccess Status = 3000 // StatusFailure means the item completed with failure, matching // MaaStatus_Failed. StatusFailure Status = 4000 )
type StopAppParam ¶
type StopAppParam struct {
// Package specifies the package name to stop. Required.
Package string `json:"package,omitempty"`
}
StopAppParam defines parameters for stop app action.
type StopTaskParam ¶
type StopTaskParam struct{}
StopTaskParam defines parameters for stop task action. This action stops the current task chain.
type StringList ¶
type StringList []string
StringList is an ordered list of strings. JSON input may be a single string or an array of strings; a scalar normalizes to a one-element list. Non-nil lists marshal as arrays. In pipeline parameters, nil is omitted to inherit the existing/default value; an empty non-nil list clears it.
func (*StringList) UnmarshalJSON ¶
func (s *StringList) UnmarshalJSON(data []byte) error
UnmarshalJSON normalizes a scalar string to a one-element list. Invalid input, including null, leaves the receiver unchanged.
type SubRecognitionItem ¶
type SubRecognitionItem struct {
// NodeName is set when the JSON value is a string (reference to another node by name).
NodeName string
// Inline is set when the JSON value is an object (inline recognition with type, param, sub_name).
// The v2 JSON envelope nests type and param under recognition.
Inline *InlineSubRecognition
}
SubRecognitionItem is one element of And all_of / Or any_of. It is either a node name (string reference) or a v2 inline recognition with a recognition object and optional sub_name. GetNodeData from C++ outputs: all_of/any_of as array of string | object; this type supports both.
func Inline ¶
func Inline(rec *Recognition, name ...string) SubRecognitionItem
Inline builds a SubRecognitionItem from a recognition; optional name is the sub_name. Example: RecOr(Inline(RecTemplateMatch(...)), Inline(RecColorMatch(...))) Example: RecAnd(Ref("A"), Inline(RecDirectHit(), "sub1")).SetBoxIndex(1)
func Ref ¶
func Ref(nodeName string) SubRecognitionItem
Ref returns a SubRecognitionItem that references another node by name.
func (SubRecognitionItem) MarshalJSON ¶
func (s SubRecognitionItem) MarshalJSON() ([]byte, error)
MarshalJSON outputs a string when NodeName is set, the inline object when Inline is set, and null when both are zero values.
func (*SubRecognitionItem) UnmarshalJSON ¶
func (s *SubRecognitionItem) UnmarshalJSON(data []byte) error
UnmarshalJSON supports both string (node name) and object (inline recognition).
type SwipeActionResult ¶
type SwipeActionResult struct {
Begin Point `json:"begin"`
End []Point `json:"end"`
EndHold []int `json:"end_hold"`
Duration []int `json:"duration"`
OnlyHover bool `json:"only_hover"`
Starting int `json:"starting"`
Contact int `json:"contact"`
// Pressure is kept to match MaaFramework raw detail JSON.
Pressure int `json:"pressure"`
// contains filtered or unexported fields
}
SwipeActionResult holds the parsed detail of a Swipe action.
func (SwipeActionResult) MarshalJSON ¶
func (s SwipeActionResult) MarshalJSON() ([]byte, error)
MarshalJSON encodes the swipe detail, preferring the retained raw end JSON over re-encoding End.
func (*SwipeActionResult) UnmarshalJSON ¶
func (s *SwipeActionResult) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the swipe detail, retaining the raw end JSON so it can be re-encoded verbatim. On error the detail is unchanged.
type SwipeParam ¶
type SwipeParam struct {
// Begin specifies the swipe start position.
Begin Target `json:"begin,omitzero"`
// BeginOffset specifies additional offset applied to begin position.
// JSON accepts [x, y], which expands to a 1x1 offset at (x, y), or [x, y, w, h];
// the zero value omits the field, so the pipeline default or parent-node inheritance applies.
BeginOffset Rect `json:"begin_offset,omitzero"`
// End specifies the swipe end positions. JSON input may be a single
// target in place of the list (a bare true or node name, or a flat
// [x, y] point or [x, y, w, h] rectangle array); a single target
// normalizes to a one-element list. A zero Target element fails JSON
// encoding.
End []Target `json:"end,omitzero"`
// EndOffset specifies additional offset applied to end position. JSON
// input may be a single flat [x, y, w, h] rectangle in place of the
// list; a single offset normalizes to a one-element list.
EndOffset []Rect `json:"end_offset,omitempty"`
// Duration specifies the swipe duration. Default: 200ms.
// JSON input may be a single number or an array; a single value
// normalizes to a one-element array.
// JSON: serialized as array of integer milliseconds.
Duration []time.Duration `json:"-"`
// EndHold specifies extra wait time at end position before releasing. Default: 0.
// JSON input may be a single number or an array; a single value
// normalizes to a one-element array.
// JSON: serialized as array of integer milliseconds.
EndHold []time.Duration `json:"-"`
// OnlyHover enables hover-only mode without press/release actions. Default: false.
OnlyHover bool `json:"only_hover,omitempty"`
// Contact specifies the touch point identifier. Adb: finger index (0=first finger). Win32: mouse button (0=left, 1=right, 2=middle).
Contact int `json:"contact,omitempty"`
// Pressure specifies touch pressure; its range depends on the controller.
// Framework default: 1. Nil inherits as described in [ActionParam];
// a pointer to 0 sends zero explicitly.
Pressure *int `json:"pressure,omitempty"`
}
SwipeParam defines parameters for swipe action.
func (SwipeParam) MarshalJSON ¶
func (p SwipeParam) MarshalJSON() ([]byte, error)
MarshalJSON encodes the swipe param, with the durations and end holds as integer milliseconds.
func (*SwipeParam) UnmarshalJSON ¶
func (p *SwipeParam) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the swipe param, reading the durations and end holds as integer milliseconds, normalizing single end targets and offsets to one-element lists and single timing values to one-element arrays.
type SymbolLookupError ¶
type SymbolLookupError = native.SymbolLookupError
SymbolLookupError reports a MaaFramework library that lacks a symbol required by this binding. Use errors.As to inspect the library, symbol, and version expectation after Init fails.
type Target ¶
Target identifies a pipeline v2 ROI or action position: true for the current recognition box (or the full image for an ROI), a node or [Anchor] name, or a rectangle. JSON points [x, y] are normalized to [x, y, 1, 1]. Names are passed through unvalidated: an empty name or a malformed [Anchor] prefix fails when the pipeline is parsed. A zero Target is unspecified and cannot be encoded; decoding an explicit JSON null target is an error.
func NewTargetBool ¶
NewTargetBool creates the current-result/full-image target when val is true. False is not a valid pipeline target and fails JSON encoding.
func NewTargetRect ¶
NewTargetRect creates a target for an explicit [x, y, width, height] rectangle.
func NewTargetString ¶
NewTargetString creates a target that refers to a node name or [Anchor] name.
type TaskDetail ¶
TaskDetail contains task information. Nodes lists nodes in execution order and supports querying details on demand.
type TaskJob ¶
type TaskJob struct {
// contains filtered or unexported fields
}
TaskJob extends Job with task-specific functionality. It provides additional methods to retrieve task details. Wait, status queries and predicates, and Error may be called concurrently. Multiple waiters share the completed result, and status queries remain available while a wait is in progress. A TaskJob must not be copied.
func (*TaskJob) GetDetail ¶
func (j *TaskJob) GetDetail() (*TaskDetail, error)
GetDetail retrieves the detailed information of the task.
func (*TaskJob) OverridePipeline ¶
OverridePipeline overrides the pipeline of a queued or running task; it fails once the task has completed. The override parameter can be a JSON string, []byte, or any JSON-marshalable value; nil marshals to an empty override object, which the native layer treats as a no-op success.
func (*TaskJob) Status ¶
Status returns the current status of the task job. If the task job has an error, it returns StatusFailure.
type Tasker ¶
type Tasker struct {
// contains filtered or unexported fields
}
Tasker is the main task executor that coordinates resources and controllers to perform automated tasks. A Tasker created with NewTasker owns its native handle; taskers obtained from getters and callbacks are borrowed views.
func (*Tasker) AddContextSink ¶
func (t *Tasker) AddContextSink(sink ContextEventSink) int64
AddContextSink adds a context event listener and returns the sink ID for later removal. The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback. It returns 0 if registration fails or the object is closed.
func (*Tasker) AddSink ¶
func (t *Tasker) AddSink(sink TaskerEventSink) int64
AddSink adds an event listener and returns the sink ID for later removal. The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback. It returns 0 if registration fails or the object is closed.
func (*Tasker) BindController ¶
func (t *Tasker) BindController(ctrl *Controller) error
BindController binds an initialized controller to the tasker. It returns ErrTaskerRunning while tasks are pending or running. The C API accepts rebinding and a null handle (unbind) in any state; the Go wrapper is stricter and also rejects a nil controller. A previously bound controller remains retained until the tasker is destroyed.
func (*Tasker) BindResource ¶
BindResource binds an initialized resource to the tasker. It returns ErrTaskerRunning while tasks are pending or running. The C API accepts rebinding and a null handle (unbind) in any state; the Go wrapper is stricter and also rejects a nil resource. A previously bound resource remains retained until the tasker is destroyed.
func (*Tasker) ClearCache ¶
ClearCache clears all queryable runtime cache.
func (*Tasker) ClearContextSinks ¶
func (t *Tasker) ClearContextSinks()
ClearContextSinks clears all context event listeners. The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback.
func (*Tasker) ClearSinks ¶
func (t *Tasker) ClearSinks()
ClearSinks clears all instance event listeners. The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback.
func (*Tasker) Destroy ¶
Destroy closes the tasker once; repeated successful calls are safe. Borrowed taskers cannot be destroyed. Destroy returns ErrBound while an AgentClient is registered as a sink, ErrInUse while a method or asynchronous job is active — even if the returned Job was discarded — and ErrInCallback when called from inside one of the tasker's own callbacks. After PostStop invalidated job IDs, Destroy keeps returning ErrInUse until the native workers are idle. A successful Destroy returns after native cleanup and prevents subsequent user callbacks. Destroy the tasker before destroying its bound resource and controller.
func (*Tasker) GetActionDetail ¶
func (t *Tasker) GetActionDetail(actionId int64) (*ActionDetail, error)
GetActionDetail returns the detail recorded for actionId. The returned detail mirrors MaaTaskerGetActionDetail in the C++ API: Box is the recognition box passed to the action, Success is the controller return value, and Result is the action-specific decoding of DetailJson. It returns an error when no detail is available for actionId.
func (*Tasker) GetController ¶
func (t *Tasker) GetController() *Controller
GetController returns the bound controller of the tasker. It may run concurrently with binding changes and returns a borrowed view of the binding observed during this call.
func (*Tasker) GetLatestNode ¶
func (t *Tasker) GetLatestNode(taskName string) (*NodeDetail, error)
GetLatestNode returns the latest node detail for a given task name.
func (*Tasker) GetNodeDetail ¶
func (t *Tasker) GetNodeDetail(nodeId int64) (*NodeDetail, error)
GetNodeDetail queries node detail by node ID. Recognition and Action are nil when the node has no recognition or action.
func (*Tasker) GetRecognitionDetail ¶
func (t *Tasker) GetRecognitionDetail(recId int64) (*RecognitionDetail, error)
GetRecognitionDetail queries recognition detail. It returns an error when no detail is available for recId or the detail cannot be decoded. Only the algorithm strings the framework currently produces decode successfully; an unrecognized algorithm string fails the whole query.
func (*Tasker) GetResource ¶
GetResource returns the bound resource of the tasker. It may run concurrently with binding changes and returns a borrowed view of the binding observed during this call.
func (*Tasker) GetTaskDetail ¶
func (t *Tasker) GetTaskDetail(taskId int64) (*TaskDetail, error)
GetTaskDetail queries task detail by task ID. Entry and Status are available even when the task has no recorded nodes.
func (*Tasker) GetWaitFreezesDetail ¶
func (t *Tasker) GetWaitFreezesDetail(wfId int64) (*WaitFreezesDetail, error)
GetWaitFreezesDetail queries wait-freezes detail by wait-freezes ID. It returns an error when no detail is available for wfId.
func (*Tasker) Initialized ¶
Initialized checks if the tasker is correctly initialized. A tasker needs a valid resource. A bound controller must be connected.
func (*Tasker) OnNodeActionInContext ¶
func (t *Tasker) OnNodeActionInContext(fn func(*Context, EventStatus, NodeActionDetail)) int64
OnNodeActionInContext registers a callback for Node.Action events and returns the sink ID.
func (*Tasker) OnNodeActionNodeInContext ¶
func (t *Tasker) OnNodeActionNodeInContext(fn func(*Context, EventStatus, NodeActionNodeDetail)) int64
OnNodeActionNodeInContext registers a callback for Node.ActionNode events and returns the sink ID.
func (*Tasker) OnNodeNextListInContext ¶
func (t *Tasker) OnNodeNextListInContext(fn func(*Context, EventStatus, NodeNextListDetail)) int64
OnNodeNextListInContext registers a callback for Node.NextList events and returns the sink ID.
func (*Tasker) OnNodePipelineNodeInContext ¶
func (t *Tasker) OnNodePipelineNodeInContext(fn func(*Context, EventStatus, NodePipelineNodeDetail)) int64
OnNodePipelineNodeInContext registers a callback for Node.PipelineNode events and returns the sink ID.
func (*Tasker) OnNodeRecognitionInContext ¶
func (t *Tasker) OnNodeRecognitionInContext(fn func(*Context, EventStatus, NodeRecognitionDetail)) int64
OnNodeRecognitionInContext registers a callback for Node.Recognition events and returns the sink ID.
func (*Tasker) OnNodeRecognitionNodeInContext ¶
func (t *Tasker) OnNodeRecognitionNodeInContext(fn func(*Context, EventStatus, NodeRecognitionNodeDetail)) int64
OnNodeRecognitionNodeInContext registers a callback for Node.RecognitionNode events and returns the sink ID.
func (*Tasker) OnNodeWaitFreezesInContext ¶
func (t *Tasker) OnNodeWaitFreezesInContext(fn func(*Context, EventStatus, NodeWaitFreezesDetail)) int64
OnNodeWaitFreezesInContext registers a callback for Node.WaitFreezes events and returns its sink ID. Remove it with RemoveContextSink when no longer needed.
func (*Tasker) OnTaskerTask ¶
func (t *Tasker) OnTaskerTask(fn func(EventStatus, TaskerTaskDetail)) int64
OnTaskerTask registers a callback for Tasker.Task events and returns the sink ID.
func (*Tasker) PostAction ¶
func (t *Tasker) PostAction(actionType ActionType, actionParam ActionParam, box Rect, recoDetail *RecognitionDetail) (*TaskJob, error)
PostAction posts an action to the tasker asynchronously. The box and recoDetail are from the previous recognition; recoDetail is marshaled as an opaque JSON payload (see RecognitionDetail). It returns an error and a terminal-failed job when the action cannot be submitted, for example when the action or recognition detail parameter cannot be marshaled or the tasker is closed; the action is not posted to the native layer in that case.
func (*Tasker) PostRecognition ¶
func (t *Tasker) PostRecognition(recType RecognitionType, recParam RecognitionParam, img image.Image) (*TaskJob, error)
PostRecognition posts a recognition to the tasker asynchronously. It returns an error and a terminal-failed job when the recognition cannot be submitted, for example when the image or recognition parameter is invalid or the tasker is closed; the recognition is not posted to the native layer in that case.
func (*Tasker) PostStop ¶
PostStop posts a stop signal to the tasker asynchronously. It interrupts the currently running task and stops resource loading and controller operations. It returns an error and a terminal-failed job when the stop signal cannot be submitted, for example when the tasker is closed. A stop can invalidate earlier job IDs before their native calls finish. Do not treat an earlier Job.Wait return as proof that all callbacks ended.
func (*Tasker) PostTask ¶
PostTask posts a task to the tasker asynchronously. The optional override can be a JSON string, []byte, or any JSON-marshalable value. It returns an error and a terminal-failed job when the task cannot be submitted, for example when the override cannot be marshaled or the tasker is closed; the task is not posted to the native layer in that case.
func (*Tasker) RemoveContextSink ¶
RemoveContextSink removes a context event listener by sink ID. Removing an unknown or already-removed sink ID is a no-op. The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback.
func (*Tasker) RemoveSink ¶
RemoveSink removes an event listener by sink ID. Removing an unknown or already-removed sink ID is a no-op. The instance and associated taskers must be idle: stop new submissions and let their work and callbacks finish. Do not call this from a callback.
type TaskerEventSink ¶
type TaskerEventSink interface {
OnTaskerTask(tasker *Tasker, event EventStatus, detail TaskerTaskDetail)
}
TaskerEventSink is the interface for receiving tasker-level events. Handler methods run synchronously on native calling threads, may overlap with other callbacks, and must not wait for work that requires them to return.
type TaskerTaskDetail ¶
type TaskerTaskDetail struct {
TaskID uint64 `json:"task_id"`
Entry string `json:"entry"`
UUID string `json:"uuid"`
Hash string `json:"hash"`
}
TaskerTaskDetail contains information about tasker task events
type TemplateMatchMethod ¶
type TemplateMatchMethod int
TemplateMatchMethod defines the template matching algorithm (cv::TemplateMatchModes).
const ( TemplateMatchMethodSQDIFF_NORMED TemplateMatchMethod = 1 // Normalized squared difference TemplateMatchMethodSQDIFF_NORMED_Inverted TemplateMatchMethod = 10001 // Normalized squared difference (Inverted) TemplateMatchMethodCCORR_NORMED TemplateMatchMethod = 3 // Normalized cross correlation TemplateMatchMethodCCOEFF_NORMED TemplateMatchMethod = 5 // Normalized correlation coefficient (default, most accurate) )
Template matching algorithms. The native parser forwards any integer to OpenCV; adding 10000 to a method inverts its score, so the inverted SQDIFF_NORMED is 10001. Default: 5 (CCOEFF_NORMED).
type TemplateMatchOrderBy ¶
type TemplateMatchOrderBy OrderBy
TemplateMatchOrderBy defines the ordering options for template matching results.
type TemplateMatchParam ¶
type TemplateMatchParam struct {
// ROI specifies the region of interest for recognition.
ROI Target `json:"roi,omitzero"`
// ROIOffset specifies an offset applied to ROI. The zero value is omitted
// to inherit the existing/default offset; an explicit zero offset cannot
// be expressed with this value-type field.
ROIOffset Rect `json:"roi_offset,omitzero"`
// Template specifies the template image paths. Required.
// JSON input may be a single string or an array of strings; a scalar
// normalizes to a one-element list. Nil is omitted to inherit the
// existing/default templates; an empty non-nil list clears them.
Template StringList `json:"template,omitzero"`
// Threshold specifies the matching threshold [0-1.0]. Default: 0.7.
// JSON input may be a number or an array of numbers; a scalar normalizes
// to a one-element list. Nil is omitted to inherit the existing/default
// thresholds; an empty non-nil list clears them (matching fails at run
// time when templates or thresholds are empty).
Threshold []float64 `json:"threshold,omitzero"`
// OrderBy specifies how results are sorted. Default: Horizontal. Options: Horizontal | Vertical | Score | Random.
OrderBy TemplateMatchOrderBy `json:"order_by,omitempty"`
// Index specifies which match to select from results.
Index int `json:"index,omitempty"`
// Method specifies the matching algorithm: 1 (SQDIFF_NORMED), 3 (CCORR_NORMED),
// 5 (CCOEFF_NORMED, default), or 10001 (inverted SQDIFF_NORMED).
Method TemplateMatchMethod `json:"method,omitempty"`
// GreenMask enables green color masking for transparent areas.
GreenMask bool `json:"green_mask,omitempty"`
}
TemplateMatchParam defines parameters for template matching recognition.
func (*TemplateMatchParam) UnmarshalJSON ¶
func (p *TemplateMatchParam) UnmarshalJSON(data []byte) error
UnmarshalJSON normalizes a scalar template and a scalar threshold to one-element lists. Invalid parameter values leave the receiver unchanged.
type TemplateMatchResult ¶
TemplateMatchResult is the decoded TemplateMatch result from a recognition detail JSON, with keys box and score.
type TouchActionResult ¶
type TouchActionResult struct {
Contact int `json:"contact"`
Point Point `json:"point"`
Pressure int `json:"pressure"`
AutoUp bool `json:"auto_up"`
}
TouchActionResult holds the parsed detail of TouchDown, TouchMove, and TouchUp actions.
type TouchDownParam ¶
type TouchDownParam struct {
// AutoUp releases still-held contacts when the task stops, finishes, or the controller is destroyed.
// Framework default: false. Nil inherits as described in [ActionParam].
AutoUp *bool `json:"auto_up,omitempty"`
// Target specifies the touch target position.
Target Target `json:"target,omitzero"`
// TargetOffset specifies additional offset applied to target.
// JSON accepts [x, y], which expands to a 1x1 offset at (x, y), or [x, y, w, h];
// the zero value omits the field, so the pipeline default or parent-node inheritance applies.
TargetOffset Rect `json:"target_offset,omitzero"`
// Pressure specifies the touch pressure, range depends on controller implementation. Default: 0.
Pressure int `json:"pressure,omitempty"`
// Contact specifies the touch point identifier. Adb: finger index (0=first finger). Win32: mouse button (0=left, 1=right, 2=middle).
Contact int `json:"contact,omitempty"`
}
TouchDownParam defines parameters for touch down action.
type TouchMoveParam ¶
type TouchMoveParam struct {
// AutoUp retains the framework's shared touch parameter for JSON round trips.
// It only affects TouchDown; TouchMove does not use it. Nil leaves it unspecified.
AutoUp *bool `json:"auto_up,omitempty"`
// Target specifies the touch target position.
Target Target `json:"target,omitzero"`
// TargetOffset specifies additional offset applied to target.
// JSON accepts [x, y], which expands to a 1x1 offset at (x, y), or [x, y, w, h];
// the zero value omits the field, so the pipeline default or parent-node inheritance applies.
TargetOffset Rect `json:"target_offset,omitzero"`
// Pressure specifies the touch pressure, range depends on controller implementation. Default: 0.
Pressure int `json:"pressure,omitempty"`
// Contact specifies the touch point identifier. Adb: finger index (0=first finger). Win32: mouse button (0=left, 1=right, 2=middle).
Contact int `json:"contact,omitempty"`
}
TouchMoveParam defines parameters for touch move action.
type TouchUpParam ¶
type TouchUpParam struct {
// Contact specifies the touch point identifier. Adb: finger index (0=first finger). Win32: mouse button (0=left, 1=right, 2=middle).
Contact int `json:"contact,omitempty"`
}
TouchUpParam defines parameters for touch up action.
type WaitFreezesDetail ¶
type WaitFreezesDetail struct {
ID int64
NodeName string
Phase string
Success bool
ElapsedMs uint64
RecoIDs []int64
ROI Rect
}
WaitFreezesDetail contains the detail for a wait-freezes action.
type WaitFreezesParam ¶
type WaitFreezesParam struct {
// Time specifies the duration that the screen must remain stable.
// Zero is omitted, inheriting the existing value; the framework's built-in default is zero (no wait).
// JSON: serialized as integer milliseconds.
Time time.Duration `json:"-"`
// Target specifies the region to monitor for changes.
// The built-in default is the current recognition box.
Target Target `json:"target,omitzero"`
// TargetOffset specifies additional offset applied to target.
// JSON accepts [x, y], which expands to a 1x1 offset at (x, y), or [x, y, w, h];
// the zero value omits the field, so the pipeline default or parent-node inheritance applies.
TargetOffset Rect `json:"target_offset,omitzero"`
// Threshold specifies the template matching threshold for detecting changes. Default: 0.95.
Threshold float64 `json:"threshold,omitempty"`
// Method specifies the template matching algorithm (cv::TemplateMatchModes). Default: 5.
Method int `json:"method,omitempty"`
// RateLimit specifies the minimum interval between checks. Default: 1000ms.
// JSON: serialized as integer milliseconds.
RateLimit time.Duration `json:"-"`
// Timeout specifies the maximum wait time. Default: 20000ms.
// JSON: serialized as integer milliseconds.
Timeout time.Duration `json:"-"`
}
WaitFreezesParam defines parameters for waiting until screen stabilizes. The screen is considered stable when there are no significant changes for a continuous period. JSON input may be a bare number, shorthand for the time in milliseconds.
func (WaitFreezesParam) MarshalJSON ¶
func (w WaitFreezesParam) MarshalJSON() ([]byte, error)
MarshalJSON encodes time, rate_limit, and timeout as integer milliseconds. Zero durations are omitted so pipeline defaults and parent-node inheritance apply.
func (*WaitFreezesParam) UnmarshalJSON ¶
func (w *WaitFreezesParam) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes integer milliseconds for time, rate_limit, and timeout into durations, accepting a bare number as the time in milliseconds, matching the native parser. An explicit JSON null is rejected, matching the native parser. Invalid input leaves the receiver unchanged. A bare millisecond value outside the range of time.Duration is rejected.
Source Files
¶
- action.go
- action_result.go
- agent_client.go
- agent_server.go
- blank_controller.go
- class_selector.go
- context.go
- context_state.go
- controller.go
- custom_action.go
- custom_controller.go
- custom_recognition.go
- doc.go
- event.go
- handle_state.go
- job.go
- json_codec.go
- maa.go
- millis.go
- node.go
- pipeline.go
- raw_param.go
- recognition.go
- recognition_result.go
- rect.go
- resource.go
- status.go
- string_list.go
- target.go
- tasker.go
- toolkit.go
- version.go
- wait_freezes.go
Directories
¶
| Path | Synopsis |
|---|---|
|
controller
|
|
|
adb
Package adb defines the screencap and input method flags for ADB controllers, with name parsing helpers.
|
Package adb defines the screencap and input method flags for ADB controllers, with name parsing helpers. |
|
gamepad
Package gamepad defines the button and analog-input codes for gamepad controllers.
|
Package gamepad defines the button and analog-input codes for gamepad controllers. |
|
macos
Package macos defines the screencap and input method flags for macOS controllers.
|
Package macos defines the screencap and input method flags for macOS controllers. |
|
win32
Package win32 defines the screencap and input method flags for Win32 controllers, with name parsing helpers.
|
Package win32 defines the screencap and input method flags for Win32 controllers, with name parsing helpers. |
|
examples
|
|
|
agent-client
command
|
|
|
agent-server
command
|
|
|
custom-action
command
|
|
|
custom-recognition
command
|
|
|
quick-start
command
|
|
|
internal
|
|
|
buffer
Package buffer wraps MaaFramework image, string, rect, and list buffers.
|
Package buffer wraps MaaFramework image, string, rect, and list buffers. |
|
jsoncodec
Package jsoncodec provides the process-wide JSON codec used to serialize and deserialize the JSON that crosses the MaaFramework native boundary.
|
Package jsoncodec provides the process-wide JSON codec used to serialize and deserialize the JSON that crosses the MaaFramework native boundary. |
|
native
Package native binds the MaaFramework C API for Go through purego.
|
Package native binds the MaaFramework C API for Go through purego. |
|
rect
Package rect provides the rectangle type shared by pipeline parameters and result views.
|
Package rect provides the rectangle type shared by pipeline parameters and result views. |
|
store
Package store provides registries keyed by native handle for the callback registrations of taskers, controllers, and resources.
|
Package store provides registries keyed by native handle for the callback registrations of taskers, controllers, and resources. |
|
target
Package target implements the pipeline v2 target wire type: a variant that is either the boolean true, a node or [Anchor] name, or a rectangle.
|
Package target implements the pipeline v2 target wire type: a variant that is either the boolean true, a node or [Anchor] name, or a rectangle. |