-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sa_node_code.go
executable file
·1438 lines (1203 loc) · 31.4 KB
/
sa_node_code.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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2023 Milan Suk
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this db except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
"encoding/json"
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"strconv"
"strings"
_ "embed"
)
//go:embed sa_node_const_go.goo
var g_code_const_go string
var g_str_imports = []string{"\"bytes\"", "\"encoding/json\"", "\"fmt\"", "\"io\"", "\"net/http\"", "\"os\"", "\"strconv\""}
type SANodeCodeChat struct {
User string
Assistent string
err error
}
type SANodeCodeImport struct {
Name string
Path string
}
type SANodeCodeArg struct {
Node string
Write bool
}
type SANodeCodeFn struct {
node *SANode
updated bool
write bool
}
type SANodeCodeExePrm struct {
Node string
ListPos int
ListNode string
Attr string
Value interface{}
}
type SANodeCodeExe struct {
prms []SANodeCodeExePrm
}
type SANodeCode struct {
node *SANode
Messages []SANodeCodeChat
Code string
func_depends []*SANodeCodeFn
cmd_output string //terminal
file_err error
exe_err error
//ans_err error
exes []SANodeCodeExe
job_exe *SAJobExe
job_oai *SAJobOpenAI //answer is generated
job_oai_index int
}
func InitSANodeCode(node *SANode) SANodeCode {
ls := SANodeCode{}
ls.node = node
return ls
}
func (ls *SANodeCode) AddExe(exe_prms []SANodeCodeExePrm) {
if !ls.node.app.EnableExecution || !ls.node.IsTypeCode() || ls.node.IsBypassed() {
return
}
if len(exe_prms) == 0 && len(ls.exes) > 0 && len(ls.exes[len(ls.exes)-1].prms) == 0 {
return //already added
}
ls.exes = append(ls.exes, SANodeCodeExe{prms: exe_prms})
}
func (ls *SANodeCode) findFuncDepend(node *SANode) *SANodeCodeFn {
for _, fn := range ls.func_depends {
if fn.node == node {
return fn
}
}
return nil
}
func (ls *SANodeCode) addFuncDepend(nm string) error {
node, err := ls.findNodeAndCheck(nm)
if err != nil {
return err
}
//find
for _, fn := range ls.func_depends {
if fn.node == node {
return nil //already added
}
}
//add
ls.func_depends = append(ls.func_depends, &SANodeCodeFn{node: node})
return nil
}
func (ls *SANodeCode) UpdateLinks(node *SANode) {
ls.node = node
if !node.IsTypeCode() {
return
}
for i := 0; i < len(node.Code.Messages); i++ {
ls.Messages[i].err = ls.buildArgs(node.Code.Messages[i].User, nil)
}
ls.UpdateFile() //create/update file + (re)compile
}
func (ls *SANodeCode) buildSqlInfos(msgs_depends []*SANodeCodeFn) (string, error) {
str := ""
for _, fn := range msgs_depends {
if fn.node.IsTypeDbFile() {
str += fmt.Sprintf("`%s` is SQLite database which includes these tables(columns): ", fn.node.Name)
tablesStr := ""
db, _, err := ls.node.app.base.ui.win.disk.OpenDb(fn.node.GetAttrString("path", ""))
if err == nil {
info, err := db.GetTableInfo()
if err == nil {
for _, tb := range info {
columnsStr := ""
for _, col := range tb.Columns {
columnsStr += col.Name
columnsStr += "("
columnsStr += col.Type
if col.NotNull {
columnsStr += ", NOT NULL"
}
columnsStr += "), "
}
columnsStr, _ = strings.CutSuffix(columnsStr, ", ")
tablesStr += fmt.Sprintf("%s(%s), ", tb.Name, columnsStr)
}
} else {
return "", fmt.Errorf("GetTableInfo() failed: %w", err)
}
} else {
return "", fmt.Errorf("OpenDb() failed: %w", err)
}
tablesStr, _ = strings.CutSuffix(tablesStr, ", ")
str += tablesStr
str += "\n"
str += "If column is marked as NOT NULL, you have to use it when INSERT INTO.\n"
}
}
return str, nil
}
func (node *SANode) getStructName() string {
if node.IsTypeList() {
return /*"List" +*/ OsGetStringStartsWithUpper(node.Name) //Menu<name>
}
if node.IsTypeMenu() {
return /*"Menu" +*/ OsGetStringStartsWithUpper(node.Name) //List<name>
}
if node.IsTypeLayout() {
return /*"Layout" +*/ OsGetStringStartsWithUpper(node.Name) //Layout<name>
}
exe := node.Exe
if node.IsAttrDBValue() {
exe += "DB" //Editbox -> EditboxDB
}
return OsGetStringStartsWithUpper(exe) //1st letter must be upper
}
func (ls *SANodeCode) buildListSt(node *SANode, addExtraAttrs bool) string {
str := ""
if !node.IsTypeList() {
return str
}
StructName := node.getStructName()
//List<name>Row
str += fmt.Sprintf("type %sItem struct {\n", StructName)
for _, it := range node.Subs {
itVarName := OsGetStringStartsWithUpper(it.Name) //1st letter must be upper
itStructName := it.getStructName() //list inside list? .........
if addExtraAttrs {
str += fmt.Sprintf("\t%s %s `json:\"%s\"`\n", itVarName, itStructName, it.Name)
} else {
str += fmt.Sprintf("\t%s %s\n", itVarName, itStructName)
}
}
str += "}\n"
//List<name>
var extraAttrs string
if addExtraAttrs {
extraAttrs = "\tGrid_x int `json:\"grid_x\"`\n" +
"\tGrid_y int `json:\"grid_y\"`\n" +
"\tGrid_w int `json:\"grid_w\"`\n" +
"\tGrid_h int `json:\"grid_h\"`\n" +
"\tShow bool `json:\"show\"`\n" +
"\tEnable bool `json:\"enable\"`\n" +
"\tChanged bool `json:\"changed\"`\n" +
"\tDirection int `json:\"direction\"`\n" +
"\tMax_width float64 `json:\"max_width\"`\n" +
"\tMax_height float64 `json:\"max_height\"`\n" +
"\tShow_border bool `json:\"show_border\"`\n"
} else {
extraAttrs = "\tShow bool\n"
}
if addExtraAttrs {
str += fmt.Sprintf("type %s struct {\n%s\tDefItem %sItem `json:\"defItem\"`\n\tItems []*%sItem `json:\"items\"`\n\tSelected_button string `json:\"selected_button\"`\n\tSelected_index int `json:\"selected_index\"`\n}\n", StructName, extraAttrs, StructName, StructName)
} else {
str += fmt.Sprintf("type %s struct {\n%s\tDefItem %sItem\n\tItems []*%sItem\n\tSelected_button string\n\tSelected_index int\n}\n", StructName, extraAttrs, StructName, StructName)
}
//Funcs
str += fmt.Sprintf("func (tb *%s) GetSelectedItem() * %sItem {\t//Can return nil\n\tif tb.Selected_index >= 0 && tb.Selected_index < len(tb.Items) {\n\t\treturn tb.Items[tb.Selected_index]\n\t}\n\treturn nil\n}\n", StructName, StructName)
str += fmt.Sprintf("func (tb *%s) AddItem() * %sItem {\t//Use this instead of Items = append()\n\tr := &%sItem{}\n\t*r = tb.DefItem\n\ttb.Items = append(tb.Items, r)\n\treturn r\n}\n", StructName, StructName, StructName)
return str
}
func (ls *SANodeCode) buildMenuSt(node *SANode, addExtraAttrs bool) string {
str := ""
if !node.IsTypeMenu() {
return str
}
StructName := node.getStructName()
//Menu<name>
var extraAttrs string
if addExtraAttrs {
extraAttrs = "\tGrid_x int `json:\"grid_x\"`\n" +
"\tGrid_y int `json:\"grid_y\"`\n" +
"\tGrid_w int `json:\"grid_w\"`\n" +
"\tGrid_h int `json:\"grid_h\"`\n" +
"\tShow bool `json:\"show\"`\n" +
"\tBackground int `json:\"background\"`\n" +
"\tAlign int `json:\"align\"`\n" +
"\tLabel string `json:\"label\"`\n" +
"\tIcon string `json:\"icon\"`\n" +
"\tIcon_margin float64 `json:\"icon_margin\"`\n" +
"\tTooltip string `json:\"tooltip\"`\n" +
"\tEnable bool `json:\"enable\"`\n"
} else {
extraAttrs = "\tShow bool\n"
}
//Subs list
subStructLns := ""
for _, it := range node.Subs {
itVarName := OsGetStringStartsWithUpper(it.Name) //1st letter must be upper
itStructName := it.getStructName() //list inside list? .........
if addExtraAttrs {
subStructLns += fmt.Sprintf("\t%s %s `json:\"%s\"`\n", itVarName, itStructName, it.Name)
} else {
subStructLns += fmt.Sprintf("\t%s %s\n", itVarName, itStructName)
}
}
str += fmt.Sprintf("type %s struct {\n%s\n%s}\n", StructName, extraAttrs, subStructLns)
return str
}
func (ls *SANodeCode) buildLayoutSt(node *SANode, addExtraAttrs bool) string {
str := ""
if !node.IsTypeLayout() {
return str
}
StructName := node.getStructName()
//Menu<name>
var extraAttrs string
if addExtraAttrs {
extraAttrs = "\tGrid_x int `json:\"grid_x\"`\n" +
"\tGrid_y int `json:\"grid_y\"`\n" +
"\tGrid_w int `json:\"grid_w\"`\n" +
"\tGrid_h int `json:\"grid_h\"`\n" +
"\tShow bool `json:\"show\"`\n" +
"\tEnable bool `json:\"enable\"`\n"
} else {
extraAttrs = "\tShow bool\n"
}
//Subs list
subStructLns := ""
for _, it := range node.Subs {
itVarName := OsGetStringStartsWithUpper(it.Name) //1st letter must be upper
itStructName := it.getStructName() //list inside list? .........
if addExtraAttrs {
subStructLns += fmt.Sprintf("\t%s %s `json:\"%s\"`\n", itVarName, itStructName, it.Name)
} else {
subStructLns += fmt.Sprintf("\t%s %s\n", itVarName, itStructName)
}
}
str += fmt.Sprintf("type %s struct {\n%s\n%s}\n", StructName, extraAttrs, subStructLns)
return str
}
func (ls *SANodeCode) getStructCode(st string) string {
switch st {
case "Text":
return `
type Text struct {
Label string
}`
case "Editbox":
return `
type Editbox struct {
Value string
Enable bool
}`
case "EditboxDB":
return `
type EditboxDB struct {
Value string //never set directly, always use SetValue()
Enable bool
}
func (db *EditboxDB) SetValue(db_path, table, column string, rowid int) {
db.Value = fmt.Sprintf("%s:%s:%s:%d", db_path, table, column, rowid)
}`
case "Button":
return `
type Button struct {
Label string
Icon string //path to image file
Enable bool
Background int //0=transparent, 1=full, 2=light
Align int //0=left, 1=center, 2=right
Confirmation string
Triggered bool //true, when button is clicked
}`
case "Menu":
return `
type Menu struct {
Label string
Icon string //path to image file
Enable bool
Background int //0=transparent, 1=full, 2=light
}`
case "Checkbox":
return `
type Checkbox struct {
Value bool
Label string
Enable bool
}`
case "CheckboxDB":
return `
type CheckboxDB struct {
Value string //never set directly, always use SetValue()
Label string
Enable bool
func (db *EditboxDB) SetValue(db_path, table, column string, rowid int) {
db.Value = fmt.Sprintf("%s:%s:%s:%d", db_path, table, column, rowid)
}`
case "Switch":
return `
type Switch struct {
Value bool
Label string
Enable bool
}`
case "SwitchDB":
return `
type SwitchDB struct {
Value string //never set directly, always use SetValue()
Label string
Enable bool
func (db *EditboxDB) SetValue(db_path, table, column string, rowid int) {
db.Value = fmt.Sprintf("%s:%s:%s:%d", db_path, table, column, rowid)
}`
case "Slider":
return `
type Slider struct {
Value float64
Min float64
Max float64
Step float64
Enable bool
}`
case "SliderDB":
return `
type SliderDB struct {
Value string //never set directly, always use SetValue()
Min float64
Max float64
Step float64
Enable bool
func (db *EditboxDB) SetValue(db_path, table, column string, rowid int) {
db.Value = fmt.Sprintf("%s:%s:%s:%d", db_path, table, column, rowid)
}`
case "Combo":
return `
type Combo struct {
Value string
Options_names string //separated by ';'
Options_values string //separated by ';'
Enable bool
}`
case "ComboDB":
return `
type ComboDB struct {
Value string //never set directly, always use SetValue()
Options_names string //separated by ';'
Options_values string //separated by ';'
Enable bool
func (db *EditboxDB) SetValue(db_path, table, column string, rowid int) {
db.Value = fmt.Sprintf("%s:%s:%s:%d", db_path, table, column, rowid)
}`
case "Date":
return `
type Date struct {
Value int //Unix time
Enable bool
}`
case "DateDB":
return `
type DateDB struct {
Value string //never set directly, always use SetValue()
Enable bool
func (db *EditboxDB) SetValue(db_path, table, column string, rowid int) {
db.Value = fmt.Sprintf("%s:%s:%s:%d", db_path, table, column, rowid)
}`
case "Color":
return `
type Color struct {
Value_r int //<0-255>
Value_g int //<0-255>
Value_b int //<0-255>
Value_a int //<0-255>
Enable bool
}`
case "Disk_dir":
return `
type Disk_dir struct {
Path string
Write bool
}`
case "Disk_file":
return `
type Disk_file struct {
Path string
Write bool
}`
case "Db_file":
return `
type Db_file struct {
Path string //path to the database file
Write bool
}`
case "Microphone":
return `
type Microphone struct {
Path string //path to the file with recorded audio
Triggered bool //true, when recording is done
Enable bool
}`
case "Map":
return `
type MapLocator struct {
Lon, Lat float64
Label string
}
type MapSegmentTrk struct {
Lon, Lat, Ele float64
Time string
}
type MapSegment struct {
Trkpts []MapSegmentTrk
Label string
}
type Map struct {
Locators string //JSON: []MapLocator
Segments string //JSON: []MapSegment
Enable bool
}`
case "Chart":
return `
type ChartItem struct {
X, Y float64
Label string
}
type Chart struct {
Values string //JSON: []ChartItem
Enable bool
}`
case "Net":
return `
type Net struct {
}
func (net *Net) DownloadFile(dst_file string, src_addr string) error {
//TODO
return nil
}`
case "Whispercpp":
return `
type Whispercpp struct {
Model string
}
func (w *Whispercpp) TranscribeBlob(data []byte) (string, error) {
//TODO
return text
}
func (w *Whispercpp) TranscribeFile(filePath string) (string, error) {
//TODO
return text
}`
case "LlamaMessage":
return `
type LlamaMessage struct {
Role string //"system", "user", "assistant"
Content string
}
type Llamacpp struct {
Model string
}
func (ll *Llamacpp) GetAnswer(messages []LlamaMessage) (string, error) {
//TODO
return answer
}`
case "Openai":
return `
type OpenaiMessage struct {
Role string //"system", "user", "assistant"
Content string
}
type Openai struct {
Model string
}
func (oai *Openai) GetAnswer(messages []OpenaiMessage) (string, error) {
//TODO
return answer
}`
}
fmt.Println("Warning: struct", st, "not found")
return ""
}
func (ls *SANodeCode) addDependStruct(depends_structs *[]string, node *SANode, extraStructs *string, addExtraAttrs bool) {
stName := node.getStructName()
//find
for _, st := range *depends_structs {
if st == stName {
return
}
}
//add
*depends_structs = append(*depends_structs, stName)
//subs
addDepepend := false
if node.IsTypeList() {
*extraStructs += ls.buildListSt(node, addExtraAttrs)
addDepepend = true
}
if node.IsTypeMenu() {
*extraStructs += ls.buildMenuSt(node, addExtraAttrs)
addDepepend = true
}
if node.IsTypeLayout() {
*extraStructs += ls.buildLayoutSt(node, addExtraAttrs)
addDepepend = true
}
if addDepepend {
for _, nd := range node.Subs {
ls.addDependStruct(depends_structs, nd, extraStructs, addExtraAttrs)
}
}
}
func (ls *SANodeCode) buildPrompt(userCommand string) (string, error) {
msgs_depends, err := ls.buildAllPromptsArgs()
if err != nil {
return "", err
}
str := "I have this golang code:\n\n"
extraAttrs := ""
var depends_structs []string
for _, fn := range msgs_depends {
ls.addDependStruct(&depends_structs, fn.node, &extraAttrs, false)
}
//add structs
for _, st := range depends_structs {
str += ls.getStructCode(st)
}
str += "\n"
//add list, menu structs
str += extraAttrs
params := ""
for _, fn := range msgs_depends {
StructName := fn.node.getStructName()
params += fmt.Sprintf("%s *%s, ", fn.node.Name, StructName)
}
params, _ = strings.CutSuffix(params, ", ")
str += fmt.Sprintf("\nfunc %s(%s) error {\n\n}\n\n", ls.node.Name, params)
str += fmt.Sprintf("You can change the code only inside '%s' function and output only import(s) and '%s' function code. Don't explain the code.\n", ls.node.Name, ls.node.Name)
str += "\n"
strSQL, err := ls.buildSqlInfos(msgs_depends)
if err != nil {
return "", err
}
str += strSQL
str += "\n"
str += "Your job: " + userCommand
//remove this ............
fmt.Println(str)
fmt.Println("Size:", len(str))
return str, nil
}
func (ls *SANodeCode) CheckLastChatEmpty() {
n := len(ls.Messages)
if n == 0 || ls.Messages[n-1].Assistent != "" {
ls.Messages = append(ls.Messages, SANodeCodeChat{})
}
}
func (ls *SANodeCode) GetAnswer(index int) {
ls.CheckLastChatEmpty()
if len(ls.Messages) == 1 && ls.Messages[0].User == "" {
return
}
//build message array
messages := []SAServiceMsg{
{Role: "system", Content: "You are ChatGPT, an AI assistant. Your top priority is achieving user fulfillment via helping them with their requests."},
}
for i := 0; i < len(ls.Messages) && i <= index; i++ {
msg := ls.Messages[i]
//user
user := msg.User
if i == 0 {
//1st user message is prompt
user, _ = ls.buildPrompt(user)
}
messages = append(messages, SAServiceMsg{Role: "user", Content: user})
//assistant
if msg.Assistent != "" && i < index { //avoid empty(last one) assistents
messages = append(messages, SAServiceMsg{Role: "assistant", Content: msg.Assistent})
}
}
props := &SAServiceOpenAIProps{Model: ls.node.app.base.ui.win.io.ini.ChatModel, Messages: messages}
ls.job_oai = ls.node.app.base.jobs.AddOpenAI(ls.node.app, NewSANodePath(ls.node), props)
ls.job_oai_index = index
}
func (ls *SANodeCode) GetFileName() string {
return ls.node.app.Name + "_" + ls.node.Name
}
func (node *SANode) getAttributes(exe_prms []SANodeCodeExePrm) map[string]interface{} {
attrs := make(map[string]interface{})
if node.HasAttrNode() {
attrs["node"] = node.Name
} else {
for k, v := range node.Attrs {
attrs[k] = v
}
}
// add params(triggered=true, etc.)
listNode, listPos := node.FindSubListInfo()
for _, prm := range exe_prms {
if node.Name == prm.Node {
if (listNode == nil && prm.ListNode == "") || (listNode != nil && listNode.Name == prm.ListNode && listPos == prm.ListPos) {
attrs[prm.Attr] = prm.Value
}
}
}
if node.parent != nil && node.parent.IsTypeList() {
for _, it := range node.Subs {
attrs[it.Name] = it.getAttributes(exe_prms)
}
}
if node.IsTypeMenu() {
for _, it := range node.Subs {
attrs[it.Name] = it.getAttributes(exe_prms)
}
}
if node.IsTypeLayout() {
for _, it := range node.Subs {
attrs[it.Name] = it.getAttributes(exe_prms)
}
}
if node.IsTypeList() {
//defaults
defItem := make(map[string]interface{})
for _, it := range node.Subs {
defItem[it.Name] = it.Attrs
}
attrs["defItem"] = defItem
//items
items := make([]map[string]interface{}, len(node.listSubs))
for i, it := range node.listSubs {
items[i] = it.getAttributes(exe_prms)
}
attrs["items"] = items
}
return attrs
}
func (ls *SANodeCode) Execute(exe_prms []SANodeCodeExePrm) {
if ls.node.IsBypassed() {
return
}
ls.exe_err = nil
//reset
//if ls.node.IsTypeList() {
// ls.node.listSubs = nil
//}
//input
vars := make(map[string]interface{})
for _, fn := range ls.func_depends {
vars[fn.node.Name] = fn.node.getAttributes(exe_prms)
}
inputJs, err := json.Marshal(vars)
if err != nil {
ls.exe_err = err
return
}
//run
ls.job_exe = ls.node.app.base.jobs.AddExe(ls.node.app, NewSANodePath(ls.node), "/temp/go/", ls.GetFileName(), inputJs)
}
func (ls *SANodeCode) setAttributes(node *SANode, attrs map[string]interface{}) {
if node.HasAttrNode() {
return
}
delete(attrs, "triggered")
if node.IsTypeLayout() || node.IsTypeMenu() {
for _, nd := range node.Subs {
attr, found := attrs[nd.Name]
if found {
vv, ok := attr.(map[string]interface{})
if ok {
ls.setAttributes(nd, vv)
} else {
fmt.Println("cast failed 1")
}
delete(attrs, nd.Name)
}
}
}
if node.IsTypeList() {
rw := attrs["items"]
delete(attrs, "items")
delete(attrs, "defItem")
items, ok := rw.([]interface{})
if ok {
//alloc
listSubs := make([]*SANode, len(items))
//set
for i, r := range items {
vars, ok := r.(map[string]interface{})
if ok {
var err error
listSubs[i], err = node.Copy(false)
listSubs[i].DeselectAll()
listSubs[i].Name = strconv.Itoa(i)
listSubs[i].Exe = "layout" //list -> layout
//listSubs[i].parent = prmNode
listSubs[i].updateLinks(node, node.app) //set parent
if err == nil {
for key, attrs2 := range vars {
prmNode2 := listSubs[i].FindNode(key)
if prmNode2 != nil {
vv, ok := attrs2.(map[string]interface{})
if ok {
ls.setAttributes(prmNode2, vv)
} else {
fmt.Println("cast failed 3")
}
} else {
fmt.Println("Error: Node not found", key)
}
}
//prmNode.copySubs[i].Attrs = vars
}
} else {
fmt.Println("cast failed 2")
}
}
selected_button := node.GetAttrString("selected_button", "")
selected_index := node.GetAttrInt("selected_index", -1)
if selected_button != "" && selected_index >= 0 && selected_index < len(listSubs) {
selBut := listSubs[selected_index].FindNode(selected_button)
if selBut != nil {
selBut.Attrs["background"] = 1 //full
}
}
node.listSubs = listSubs
}
}
fn := ls.findFuncDepend(node)
if fn != nil {
fn.updated = true
fn.write = !node.CmpAttrs(attrs)
}
node.Attrs = attrs
}
func (ls *SANodeCode) IsJobRunning() (bool, float64, string) {
if ls.node.IsTypeCode() && ls.job_exe != nil {
if !ls.job_exe.done.Load() {
return true, 0.5, "" //description ....
}
}
return false, -1, ""
}
func (ls *SANodeCode) SetOutput(outputJs []byte) {
var vars map[string]interface{}
err := json.Unmarshal(outputJs, &vars)
if err != nil {
ls.exe_err = err
return
}
for key, attrs := range vars {
prmNode := ls.node.GetRoot().FindNode(key)
if prmNode != nil {
vv, ok := attrs.(map[string]interface{})
if ok {
ls.setAttributes(prmNode, vv)
}
} else {
fmt.Println("Error: Node not found", key)
}
}
}
func (ls *SANodeCode) UseCodeFromAnswer(answer string) error {
var err error
ls.Code, err = ls.extractCode(answer)
if err != nil {
return err
}
ls.Code = strings.ReplaceAll(ls.Code, "package main", "")
ls.UpdateFile()
return nil
}
func (ls *SANodeCode) CopyCodeToClipboard(answer string) error {
var err error
ls.Code, err = ls.extractCode(answer)
if err != nil {
return err
}
ls.node.app.base.ui.win.io.keys.clipboard = strings.ReplaceAll(ls.Code, "package main", "")
return nil
}
func (ls *SANodeCode) extractCode(answer string) (string, error) {
d := strings.Index(answer, "```go")
if d >= 0 {
answer = answer[d+5:]
d = strings.Index(answer, "```")
if d >= 0 {
answer = answer[:d]
} else {
return "", fmt.Errorf("code_end not found")
}
} else {
return "", fmt.Errorf("no code in answer")
}
return answer, nil
}