Repository navigation
Expand file tree
/
Copy pathnode.go
More file actions
519 lines (466 loc) · 16.2 KB
/
Copy pathnode.go
File metadata and controls
519 lines (466 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
package maa
import (
"bytes"
"encoding/json"
"fmt"
"maps"
"slices"
"strings"
"time"
)
// 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.
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"`
}
// 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.
func (n *Node) UnmarshalJSON(data []byte) error {
normalized, err := normalizeNodeShorthand(data)
if err != nil {
return err
}
type Alias Node
var decoded Alias
if err := unmarshalJSON(normalized, &decoded); err != nil {
return err
}
*n = Node(decoded)
return nil
}
// normalizeNodeShorthand rewrites input forms this model does not decode
// directly into their canonical v2 shape: v1 string recognition/action and
// shorthand next/on_error values. Every other key is left untouched, except
// that an explicit null for a wait-freezes field is rejected here, because
// decoding null into the pointer fields would silently produce nil instead
// of the native parser's error.
func normalizeNodeShorthand(data []byte) ([]byte, error) {
var fields map[string]json.RawMessage
if err := unmarshalJSON(data, &fields); err != nil {
return nil, err
}
for _, key := range [...]string{"pre_wait_freezes", "post_wait_freezes", "repeat_wait_freezes"} {
if value, ok := fields[key]; ok && bytes.Equal(bytes.TrimSpace(value), []byte("null")) {
return nil, fmt.Errorf("%s must not be null", key)
}
}
changed := false
for _, key := range [...]string{"recognition", "action"} {
value, ok := fields[key]
if !ok {
continue
}
trimmed := bytes.TrimSpace(value)
if len(trimmed) == 0 || trimmed[0] != '"' {
continue
}
// v1 form: "recognition": "ColorMatch" with parameters flat on the
// node. The native parser reads parameters from the whole node in
// this case, so wrap the string into the v2 envelope with the node
// itself as the param input.
envelope, err := marshalJSON(struct {
Type json.RawMessage `json:"type"`
Param json.RawMessage `json:"param"`
}{Type: json.RawMessage(trimmed), Param: json.RawMessage(data)})
if err != nil {
return nil, err
}
fields[key] = envelope
changed = true
}
for _, key := range [...]string{"next", "on_error"} {
value, ok := fields[key]
if !ok {
continue
}
normalized, err := normalizeNextValue(value)
if err != nil {
return nil, err
}
fields[key] = normalized
changed = true
}
if !changed {
return data, nil
}
return marshalJSON(fields)
}
// normalizeNextValue converts one next/on_error value — a single node value or
// an array mixing name strings and objects — into an array of node objects.
func normalizeNextValue(data []byte) ([]byte, error) {
trimmed := bytes.TrimSpace(data)
if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {
return data, nil
}
var items []json.RawMessage
if trimmed[0] == '[' {
if err := unmarshalJSON(data, &items); err != nil {
return nil, err
}
} else {
items = []json.RawMessage{trimmed}
}
list := make([]json.RawMessage, 0, len(items))
for _, item := range items {
item = bytes.TrimSpace(item)
switch {
case len(item) == 0:
return nil, fmt.Errorf("next entry must be a string or object, got empty")
case item[0] == '"':
var name string
if err := unmarshalJSON(item, &name); err != nil {
return nil, err
}
next, err := parseNextName(name)
if err != nil {
return nil, err
}
encoded, err := marshalJSON(next)
if err != nil {
return nil, err
}
list = append(list, encoded)
case item[0] == '{':
list = append(list, item)
default:
return nil, fmt.Errorf("next entry must be a string or object, got %s", item)
}
}
return marshalJSON(list)
}
// parseNextName parses a shorthand next name with optional [JumpBack] and
// [Anchor] prefixes, mirroring the native parser: an unclosed prefix or an
// empty remaining name is an error; unrecognized prefixes are ignored.
func parseNextName(raw string) (NextItem, error) {
var item NextItem
remaining := raw
for strings.HasPrefix(remaining, "[") {
end := strings.IndexByte(remaining, ']')
if end < 0 {
return NextItem{}, fmt.Errorf("invalid node attribute format, missing ']': %q", raw)
}
switch remaining[:end+1] {
case "[JumpBack]":
item.JumpBack = true
case "[Anchor]":
item.Anchor = true
}
remaining = remaining[end+1:]
}
if remaining == "" {
return NextItem{}, fmt.Errorf("invalid node format, missing node name or anchor name: %q", raw)
}
item.Name = remaining
return item, nil
}
// NewNode creates a new Node with the given name.
func NewNode(name string) *Node {
return &Node{
Name: name,
Attach: make(map[string]any),
}
}
// SetAnchor sets the anchor for the node and returns the node for chaining.
func (n *Node) SetAnchor(anchor map[string]string) *Node {
n.Anchor = maps.Clone(anchor)
return n
}
// SetAnchorTarget sets an anchor to a specific target node and returns the node for chaining.
func (n *Node) SetAnchorTarget(anchor, nodeName string) *Node {
if anchor == "" {
return n
}
if n.Anchor == nil {
n.Anchor = make(map[string]string)
}
n.Anchor[anchor] = nodeName
return n
}
// SetRecognition sets the recognition for the node and returns the node for chaining.
func (n *Node) SetRecognition(rec *Recognition) *Node {
n.Recognition = rec
return n
}
// SetAction sets the action for the node and returns the node for chaining.
func (n *Node) SetAction(act *Action) *Node {
n.Action = act
return n
}
// SetNext sets the next nodes list for the node and returns the node for chaining.
func (n *Node) SetNext(next []NextItem) *Node {
n.Next = slices.Clone(next)
return n
}
// SetRateLimit sets the rate limit for the node and returns the node for chaining.
func (n *Node) SetRateLimit(rateLimit time.Duration) *Node {
d := rateLimit.Milliseconds()
n.RateLimit = &d
return n
}
// SetTimeout sets the timeout for the node and returns the node for chaining.
func (n *Node) SetTimeout(timeout time.Duration) *Node {
d := timeout.Milliseconds()
n.Timeout = &d
return n
}
// SetOnError sets the error handling nodes for the node and returns the node for chaining.
func (n *Node) SetOnError(onError []NextItem) *Node {
n.OnError = slices.Clone(onError)
return n
}
// SetInverse sets whether to invert the recognition result and returns the node for chaining.
func (n *Node) SetInverse(inverse bool) *Node {
n.Inverse = inverse
return n
}
// SetEnabled sets whether the node is enabled and returns the node for chaining.
func (n *Node) SetEnabled(enabled bool) *Node {
n.Enabled = &enabled
return n
}
// SetMaxHit sets the maximum hit count of the node and returns the node for chaining.
func (n *Node) SetMaxHit(maxHit uint64) *Node {
n.MaxHit = &maxHit
return n
}
// SetPreDelay sets the delay before action execution and returns the node for chaining.
func (n *Node) SetPreDelay(preDelay time.Duration) *Node {
d := preDelay.Milliseconds()
n.PreDelay = &d
return n
}
// SetPostDelay sets the delay after action execution and returns the node for chaining.
func (n *Node) SetPostDelay(postDelay time.Duration) *Node {
d := postDelay.Milliseconds()
n.PostDelay = &d
return n
}
// SetPreWaitFreezes sets the pre-action wait freezes configuration and returns the node for chaining.
func (n *Node) SetPreWaitFreezes(preWaitFreezes *WaitFreezesParam) *Node {
n.PreWaitFreezes = preWaitFreezes
return n
}
// SetPostWaitFreezes sets the post-action wait freezes configuration and returns the node for chaining.
func (n *Node) SetPostWaitFreezes(postWaitFreezes *WaitFreezesParam) *Node {
n.PostWaitFreezes = postWaitFreezes
return n
}
// SetRepeat sets the number of times to repeat the node and returns the node for chaining.
func (n *Node) SetRepeat(repeat uint64) *Node {
n.Repeat = &repeat
return n
}
// SetRepeatDelay sets the delay between repetitions and returns the node for chaining.
func (n *Node) SetRepeatDelay(repeatDelay time.Duration) *Node {
d := repeatDelay.Milliseconds()
n.RepeatDelay = &d
return n
}
// SetRepeatWaitFreezes sets the wait freezes configuration between repetitions and returns the node for chaining.
func (n *Node) SetRepeatWaitFreezes(repeatWaitFreezes *WaitFreezesParam) *Node {
n.RepeatWaitFreezes = repeatWaitFreezes
return n
}
// SetFocus sets the focus data for the node and returns the node for chaining.
func (n *Node) SetFocus(focus any) *Node {
n.Focus = focus
return n
}
// 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 (n *Node) SetAttach(attach map[string]any) *Node {
if attach == nil {
n.Attach = make(map[string]any)
} else {
n.Attach = maps.Clone(attach)
}
return n
}
// 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.
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"`
}
// FormatName returns the name with attribute prefixes, e.g. [JumpBack]NodeA.
func (i NextItem) FormatName() string {
name := i.Name
if i.JumpBack {
name = "[JumpBack]" + name
}
if i.Anchor {
name = "[Anchor]" + name
}
return name
}
// NodeAttributeOption is a functional option for configuring NextItem attributes.
type NodeAttributeOption func(*NextItem)
// 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.
func WithJumpBack() NodeAttributeOption {
return func(i *NextItem) {
i.JumpBack = true
}
}
// 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 WithAnchor() NodeAttributeOption {
return func(i *NextItem) {
i.Anchor = true
}
}
// AddAnchor sets an anchor to the current node and returns the node for chaining.
func (n *Node) AddAnchor(anchor string) *Node {
return n.SetAnchorTarget(anchor, n.Name)
}
// ClearAnchor marks an anchor as cleared and returns the node for chaining.
func (n *Node) ClearAnchor(anchor string) *Node {
return n.SetAnchorTarget(anchor, "")
}
// RemoveAnchor removes an anchor from the node and returns the node for chaining.
func (n *Node) RemoveAnchor(anchor string) *Node {
if anchor == "" {
return n
}
delete(n.Anchor, anchor)
return n
}
// AddNext appends a node to the next list and returns the node for chaining.
func (n *Node) AddNext(name string, opts ...NodeAttributeOption) *Node {
if name == "" {
return n
}
newItem := NextItem{
Name: name,
}
for _, opt := range opts {
opt(&newItem)
}
found := false
for i, item := range n.Next {
if item.Name == name {
n.Next[i] = newItem
found = true
break
}
}
if !found {
n.Next = append(n.Next, newItem)
}
return n
}
// RemoveNext removes a node from the next list and returns the node for chaining.
func (n *Node) RemoveNext(name string) *Node {
if name == "" {
return n
}
n.Next = slices.DeleteFunc(n.Next, func(item NextItem) bool {
return item.Name == name
})
return n
}
// AddOnError appends a node to the on_error list and returns the node for chaining.
func (n *Node) AddOnError(name string, opts ...NodeAttributeOption) *Node {
if name == "" {
return n
}
newItem := NextItem{
Name: name,
}
for _, opt := range opts {
opt(&newItem)
}
found := false
for i, item := range n.OnError {
if item.Name == name {
n.OnError[i] = newItem
found = true
break
}
}
if !found {
n.OnError = append(n.OnError, newItem)
}
return n
}
// RemoveOnError removes a node from the on_error list and returns the node for chaining.
func (n *Node) RemoveOnError(name string) *Node {
if name == "" {
return n
}
n.OnError = slices.DeleteFunc(n.OnError, func(item NextItem) bool {
return item.Name == name
})
return n
}