-
Notifications
You must be signed in to change notification settings - Fork 8
/
scitercanvas.go
561 lines (461 loc) · 14.2 KB
/
scitercanvas.go
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
/* D3pixelbot - Custom client, recorder and bot for pixel drawing games
Copyright (C) 2019 David Vogel
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */
package main
import (
"encoding/binary"
"encoding/json"
"fmt"
"image"
"image/color"
"image/png"
"os"
"sync"
"time"
"github.com/Dadido3/go-sciter"
gorice "github.com/Dadido3/go-sciter/rice"
"github.com/Dadido3/go-sciter/window"
"github.com/nfnt/resize"
)
// A sciter window, showing a canvas
type sciterCanvas struct {
connection connection
canvas *canvas
handlerChan chan *sciter.Value // Queue of event data, so the main logic doesn't stop while sciter is processing it
ClosedMutex sync.RWMutex
Closed bool
}
// Opens a new sciter canvas and attaches itself to the given connection and canvas
//
// ONLY CALL FROM MAIN THREAD!
func sciterOpenCanvas(con connection, can *canvas) (closedChan chan struct{}) {
sca := &sciterCanvas{
connection: con,
canvas: can,
Closed: true,
}
w, err := window.New(sciter.SW_RESIZEABLE|sciter.SW_TITLEBAR|sciter.SW_CONTROLS|sciter.SW_GLASSY|sciter.SW_ENABLE_DEBUG, sciter.NewRect(50, 300, 800, 800))
if err != nil {
log.Panic(err)
}
gorice.HandleDataLoad(w.Sciter)
w.DefineFunction("subscribeCanvasEvents", func(args ...*sciter.Value) *sciter.Value {
if len(args) != 2 {
log.Errorf("Wrong number of parameters")
return sciter.NewValue("Wrong number of parameters")
}
obj, cbHandler := args[0].Clone(), args[1].Clone() // Always clone, otherwise those are just references to sciter values and will be invalid if used after return
if !obj.IsObject() || !cbHandler.IsObjectFunction() {
log.Errorf("Wrong type of parameters")
return sciter.NewValue("Wrong type of parameters")
}
sca.ClosedMutex.Lock()
defer sca.ClosedMutex.Unlock()
if sca.handlerChan != nil {
log.Errorf("Already subscribed")
return sciter.NewValue("Already subscribed")
}
err := can.subscribeListener(sca, true) // Let the canvas manage virtual chunks for us
if err != nil {
log.Errorf("Can't subscribe to canvas: %v", err)
return sciter.NewValue(fmt.Sprintf("Can't subscribe to canvas: %v", err))
}
sca.handlerChan = make(chan *sciter.Value, 300) // Can be after can.subscribeListener, as the ClosedMutex is still locked here
sca.Closed = false
go func(channel <-chan *sciter.Value) {
for {
// Batch read from channel, or return if the channel got closed
events := []*sciter.Value{}
event, ok := <-channel
if !ok {
// Channel closed, so just close goroutine
return
}
events = append(events, event)
batchLoop:
for i := 1; i < 50; i++ { // Limit batch size to 50
select {
case event, ok := <-channel:
if ok {
events = append(events, event)
}
default:
break batchLoop
}
}
val := sciter.NewValue()
for _, event := range events {
val.Append(event)
event.Release()
}
//log.Tracef("Invoke cbHandler with %v", val)
cbHandler.Invoke(obj, "[Native Script]", val)
//log.Tracef("Invoke cbHandler with %v done", val)
val.Release()
//log.Tracef("val released")
}
}(sca.handlerChan)
return nil
})
w.DefineFunction("unsubscribeCanvasEvents", func(args ...*sciter.Value) *sciter.Value {
if len(args) != 0 {
log.Errorf("Wrong number of parameters")
return sciter.NewValue("Wrong number of parameters")
}
// unsubscribeCanvasEvents is non blocking, but an Unsubscribed event is sent to the callback
go func() {
sca.ClosedMutex.Lock()
defer sca.ClosedMutex.Unlock()
if sca.handlerChan == nil {
log.Errorf("Not subscribed")
return
}
err := can.unsubscribeListener(sca)
if err != nil {
log.Errorf("Can't unsubscribe from canvas: %v", err)
return
}
val := sciter.NewValue()
val.Set("Type", "Unsubscribed")
sca.handlerChan <- val
close(sca.handlerChan)
sca.handlerChan = nil // Goroutine has its own reference to this channel
sca.Closed = true
}()
return nil
})
rectsChan := make(chan []image.Rectangle, 1)
go func() {
for rects := range rectsChan {
can.registerRects(sca, rects)
}
}()
w.DefineFunction("registerRects", func(args ...*sciter.Value) *sciter.Value {
if len(args) != 1 {
log.Errorf("Wrong number of parameters")
return sciter.NewValue("Wrong number of parameters")
}
jsonRect := args[0] // Clone if value is needed after this function returned
if !jsonRect.IsObject() {
log.Errorf("Wrong type of parameters")
return sciter.NewValue("Wrong type of parameters")
}
jsonRect.ConvertToString(sciter.CVT_JSON_LITERAL)
rects := []image.Rectangle{}
if err := json.Unmarshal([]byte(jsonRect.String()), &rects); err != nil {
log.Errorf("Error reading json: %v", err)
return sciter.NewValue(fmt.Sprintf("Error reading json: %v", err))
}
// Write rect into channel, or replace the current one if the goroutine is busy
select {
case rectsChan <- rects:
default:
select {
case <-rectsChan:
default:
}
rectsChan <- rects
}
return nil
})
w.DefineFunction("setReplayTime", func(args ...*sciter.Value) *sciter.Value {
if len(args) != 1 {
log.Errorf("Wrong number of parameters")
return sciter.NewValue("Wrong number of parameters")
}
sciterTime := args[0] // Clone if value is needed after this function returned
if !sciterTime.IsDate() {
log.Errorf("Wrong type of parameters")
return sciter.NewValue("Wrong type of parameters")
}
conR, ok := con.(connectionReplay) // Check if connection has replay time methods
if !ok {
log.Errorf("Can't set replay time on %T", con)
return sciter.NewValue(fmt.Sprintf("Can't set replay time on %T", con))
}
t, err := sciterTime.Time()
if err != nil {
log.Errorf("Error getting time: %v", err)
return sciter.NewValue(fmt.Sprintf("Error getting time: %v", err))
}
err = conR.setReplayTime(t)
if err != nil {
log.Errorf("Can't set replay time %T", err)
return sciter.NewValue(err.Error())
}
return nil
})
w.DefineFunction("hasReplayTime", func(args ...*sciter.Value) (val *sciter.Value) {
val = sciter.NewValue()
if len(args) != 0 {
log.Errorf("Wrong number of parameters")
val.Set("Error", "Wrong number of parameters")
return
}
conRep, ok := con.(connectionReplay) // Check if connection has replay time methods
if !ok {
log.Errorf("%T doesn't support setReplayTime", con)
val.Set("Error", fmt.Sprintf("%T doesn't support setReplayTime", con))
return
}
recs := conRep.getRecordings()
val.Set("HasReplayTime", sciter.NewValue(true))
sciterRecs := sciter.NewValue()
for i, rec := range recs {
sciterRec := sciter.NewValue()
sciterRec.Set("StartTime", rec.StartTime)
sciterRec.Set("EndTime", rec.EndTime)
sciterRec.Set("FileName", rec.FileName)
sciterRecs.SetIndex(i, sciterRec)
}
val.Set("Recs", sciterRecs)
return val
})
w.DefineFunction("saveImage", func(args ...*sciter.Value) *sciter.Value {
if len(args) != 4 {
log.Errorf("Wrong number of parameters")
return sciter.NewValue("Wrong number of parameters")
}
sciterRect, sciterSize, sciterPath, cbHandler := args[0], args[1], args[2], args[3].Clone() // Clone if value is needed after this function has returned
if !sciterRect.IsObject() || !sciterSize.IsObject() || !sciterPath.IsString() || !cbHandler.IsObjectFunction() {
log.Errorf("Wrong type of parameters")
return sciter.NewValue("Wrong type of parameters")
}
min, max := sciterRect.Get("Min"), sciterRect.Get("Max")
rect := image.Rectangle{
image.Point{int(int32(min.Get("X").Int())), int(int32(min.Get("Y").Int()))},
image.Point{int(int32(max.Get("X").Int())), int(int32(max.Get("Y").Int()))},
}
size := pixelSize{sciterSize.Get("X").Int(), sciterSize.Get("Y").Int()}
filename := sciterPath.String()
log.Tracef("Starting to save image %v at %v with size of %v", filename, rect, size)
file, err := os.Create(filename)
if err != nil {
log.Errorf("Can't create file %v: %v", filename, err)
return sciter.NewValue(fmt.Sprintf("Can't create file %v: %v", filename, err))
}
go func() {
defer file.Close()
img, err := can.getImageCopy(rect, false, true)
if err != nil {
log.Errorf("Can't get image at %v: %v", rect, err)
return
}
resized := resize.Resize(uint(size.X), uint(size.Y), img, resize.Lanczos3)
png.Encode(file, resized)
log.Tracef("Finished to save image %v", filename)
cbHandler.Invoke(sciter.NewValue(), "[Native Script]")
}()
return nil
})
closedChan = make(chan struct{}) // Signals that the window got closed
w.DefineFunction("signalClosed", func(args ...*sciter.Value) *sciter.Value {
if len(args) != 0 {
log.Errorf("Wrong number of parameters")
return sciter.NewValue("Wrong number of parameters")
}
close(rectsChan)
close(closedChan)
return nil
})
if err := w.LoadFile("rice://ui/canvas.htm"); err != nil {
log.Panic(err)
}
// Testing pixel events
/*go func() {
for {
can.setPixel(image.Point{rand.Intn(128), rand.Intn(128)}, color.RGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)), uint8(rand.Intn(256)), uint8(rand.Intn(256))})
time.Sleep(10 * time.Millisecond)
}
}()*/
w.Show()
return closedChan
}
func (s *sciterCanvas) handleInvalidateAll() error {
s.ClosedMutex.RLock()
defer s.ClosedMutex.RUnlock()
if s.Closed {
return fmt.Errorf("Listener is closed")
}
val := sciter.NewValue()
val.Set("Type", "InvalidateAll")
s.handlerChan <- val
return nil
}
func (s *sciterCanvas) handleInvalidateRect(rect image.Rectangle, vcIDs []int) error {
s.ClosedMutex.RLock()
defer s.ClosedMutex.RUnlock()
if s.Closed {
return fmt.Errorf("Listener is closed")
}
val := sciter.NewValue()
val.Set("Type", "InvalidateRect")
val.Set("X", rect.Min.X)
val.Set("Y", rect.Min.Y)
val.Set("Width", rect.Dx())
val.Set("Height", rect.Dy())
valArray := sciter.NewValue()
defer valArray.Release()
for k, v := range vcIDs {
valArray.SetIndex(k, v)
}
val.Set("VcIDs", valArray)
s.handlerChan <- val
return nil
}
func (s *sciterCanvas) handleRevalidateRect(rect image.Rectangle, vcIDs []int) error {
s.ClosedMutex.RLock()
defer s.ClosedMutex.RUnlock()
if s.Closed {
return fmt.Errorf("Listener is closed")
}
val := sciter.NewValue()
val.Set("Type", "RevalidateRect")
val.Set("X", rect.Min.X)
val.Set("Y", rect.Min.Y)
val.Set("Width", rect.Dx())
val.Set("Height", rect.Dy())
valArray := sciter.NewValue()
defer valArray.Release()
for k, v := range vcIDs {
valArray.SetIndex(k, v)
}
val.Set("VcIDs", valArray)
s.handlerChan <- val
return nil
}
func (s *sciterCanvas) handleSetImage(img image.Image, valid bool, vcIDs []int) error {
s.ClosedMutex.RLock()
defer s.ClosedMutex.RUnlock()
if s.Closed {
return fmt.Errorf("Listener is closed")
}
imageArray := imageToBGRAArray(img)
headerArray := [12]byte{'B', 'G', 'R', 'A'}
binary.BigEndian.PutUint32(headerArray[4:8], uint32(img.Bounds().Dx()))
binary.BigEndian.PutUint32(headerArray[8:12], uint32(img.Bounds().Dy()))
array := append(headerArray[:], imageArray...)
val := sciter.NewValue()
val.Set("Type", "SetImage")
val.Set("X", img.Bounds().Min.X)
val.Set("Y", img.Bounds().Min.Y)
val.Set("Width", img.Bounds().Dx())
val.Set("Height", img.Bounds().Dy())
valArray := sciter.NewValue()
defer valArray.Release()
valArray.SetBytes(array)
val.Set("Array", valArray)
val.Set("Valid", valid)
valArray = sciter.NewValue()
defer valArray.Release()
for k, v := range vcIDs {
valArray.SetIndex(k, v)
}
val.Set("VcIDs", valArray)
s.handlerChan <- val
return nil
}
func (s *sciterCanvas) handleSetPixel(pos image.Point, color color.Color, vcID int) error {
s.ClosedMutex.RLock()
defer s.ClosedMutex.RUnlock()
if s.Closed {
return fmt.Errorf("Listener is closed")
}
r, g, b, a := color.RGBA()
val := sciter.NewValue()
val.Set("Type", "SetPixel")
val.Set("X", pos.X)
val.Set("Y", pos.Y)
val.Set("R", r>>8)
val.Set("G", g>>8)
val.Set("B", b>>8)
val.Set("A", a>>8)
val.Set("VcID", vcID)
s.handlerChan <- val
return nil
}
func (s *sciterCanvas) handleSignalDownload(rect image.Rectangle, vcIDs []int) error {
s.ClosedMutex.RLock()
defer s.ClosedMutex.RUnlock()
if s.Closed {
return fmt.Errorf("Listener is closed")
}
val := sciter.NewValue()
val.Set("Type", "SignalDownload")
val.Set("X", rect.Min.X)
val.Set("Y", rect.Min.Y)
val.Set("Width", rect.Dx())
val.Set("Height", rect.Dy())
valArray := sciter.NewValue()
defer valArray.Release()
for k, v := range vcIDs {
valArray.SetIndex(k, v)
}
val.Set("VcIDs", valArray)
s.handlerChan <- val
return nil
}
func (s *sciterCanvas) handleChunksChange(create, remove map[image.Rectangle]int) error {
s.ClosedMutex.RLock()
defer s.ClosedMutex.RUnlock()
if s.Closed {
return fmt.Errorf("Listener is closed")
}
removeIDs := []int{}
for _, id := range remove {
removeIDs = append(removeIDs, id)
}
createIDs := []struct {
Rect image.Rectangle
VcID int
}{}
for rect, id := range create {
createIDs = append(createIDs, struct {
Rect image.Rectangle
VcID int
}{
rect, id,
})
}
jsonData := struct {
Type string
Create []struct {
Rect image.Rectangle
VcID int
}
Remove []int
}{
"ChunksChange",
createIDs, removeIDs,
}
// TODO: Don't use json as intermediary
b, err := json.Marshal(jsonData)
if err != nil {
return fmt.Errorf("Can't convert to JSON object: %v", err)
}
val := sciter.NewValue()
val.ConvertFromString(string(b), sciter.CVT_JSON_LITERAL)
s.handlerChan <- val
return nil
}
func (s *sciterCanvas) handleSetTime(t time.Time) error {
s.ClosedMutex.RLock()
defer s.ClosedMutex.RUnlock()
if s.Closed {
return fmt.Errorf("Listener is closed")
}
val := sciter.NewValue()
val.Set("Type", "SetTime")
val.Set("Time", t)
s.handlerChan <- val
return nil
}