-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathMain.go
959 lines (842 loc) · 24.9 KB
/
Main.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
// program to match persons with group preferences to their groups
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"html/template"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"os/signal"
"runtime"
"sort"
"strconv"
"strings"
"time"
"path"
"github.com/asticode/go-astikit"
"github.com/asticode/go-astilectron"
assetfs "github.com/elazarl/go-bindata-assetfs"
"github.com/veecue/GroupMatcher/matching"
"github.com/veecue/GroupMatcher/parseInput"
"golang.org/x/text/language"
)
type Message struct {
Cmd string
Body string
}
//go:generate go-bindata static/... locales templates
//DISABLED: go:generate go-astilectron-bindata -c
// map of all supported languages
var langs map[language.Tag]map[string]string
// current language
var l map[string]string
// set language per param
var langFlag = flag.String("lang", "", "The language of the UI")
// current project
var persons []*matching.Person
var groups []*matching.Group
var filename string
// buffer to save messages to be sent to astilectron
var messages []Message
var darktheme bool
// last path the project was saved to
var projectPath string
var w *astilectron.Window
// scan language files from the locales directory and import them into the program
func initLangs() {
langFiles, err := AssetDir("locales")
if err != nil {
log.Fatal(err)
}
langs = make(map[language.Tag]map[string]string, len(langFiles))
for _, filename := range langFiles {
if strings.HasSuffix(filename, ".json") {
langname := strings.TrimSuffix(filename, ".json")
lang := make(map[string]string)
langData, err := Asset("locales/" + filename)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(langData, &lang)
if err != nil {
log.Fatal(err)
}
langs[language.MustParse(langname)] = lang
}
}
tags := make([]language.Tag, 0, len(langs))
for t := range langs {
tags = append(tags, t)
}
langMatcher := language.NewMatcher(tags)
userTags := make([]language.Tag, 0)
if *langFlag != "" {
userTags = append(userTags, language.Make(*langFlag))
} else if os.Getenv("LANG") != "" {
userTags = append(userTags, language.Make(os.Getenv("LANG")))
} else {
userTags = append(userTags, language.Make("en"))
}
tag, _, _ := langMatcher.Match(userTags...)
l = langs[tag]
}
func init() {
rand.Seed(int64(time.Now().Nanosecond()))
}
// create a user-readable and localized error message for input parsing
func separateError(err string) (text string, with bool, line int) {
b := []byte(err)
for i := range b {
n, err := strconv.Atoi(string(b[i]))
if err != nil {
text = text + string(b[i])
} else {
with = true
line = line*10 + n
}
}
return
}
// store current project to autosafe location on program exit
func autosafe() {
if projectPath != "" {
gm, err := parseInput.FormatGroupsAndPersons(groups, persons)
if err != nil {
log.Fatal(err)
}
ioutil.WriteFile(projectPath, []byte(gm), 0600)
}
}
// autosafe and exit program
func exit() {
autosafe()
os.Exit(0)
}
// sorte the persons by alphabet for better UI
func sortPersons() {
matching.Sort(persons)
for _, g := range groups {
matching.Sort(g.Members)
}
}
func setDarkTheme(dark bool) {
if darktheme == dark {
return
}
darktheme = dark
w.SendMessage(struct {
Cmd string
}{
"reload",
})
}
//opens documentation in current language
func openDoc() {
switch runtime.GOOS {
case "linux":
exec.Command("xdg-open", "https://github.com/veecue/GroupMatcher/tree/master/documentation/"+l["#name"]+".pdf").Start()
case "windows":
exec.Command("cmd", "/c", "start", "https://github.com/veecue/GroupMatcher/tree/master/documentation/"+l["#name"]+".pdf").Start()
}
}
// http handler function for the about GUI
func handleAbout(res http.ResponseWriter, req *http.Request) {
if req.URL.Query()["open"] != nil {
url := req.URL.Query()["open"][0]
switch runtime.GOOS { //open browser on localhost in different environments
case "linux":
exec.Command("xdg-open", url).Start()
case "windows":
exec.Command("cmd", "/c", "start", url).Start()
}
}
tData, err := Asset("templates/about.tmpl")
if err != nil {
log.Fatal(err)
}
t, err := template.New("about").Parse(string(tData))
if err != nil {
log.Fatal(err)
}
body := bytes.Buffer{}
body.WriteString(`<div class="about"><h1>GroupMatcher</h1><p>` + l["thanks"] + `</p><h2>` + l["about"] + `</h2><p>` + l["abouttext"] + `</p><h2>` + l["project"] + `</h2><p>` + l["github"] + ` - <a href="/about?open=https://github.com/veecue/GroupMatcher">` + l["visit"] + `</a></p><h2>` + l["license"] + `</h2><p>` + l["licensetext"] + `</p></div>`)
var bodyHTML template.HTML
bodyHTML = template.HTML(body.String())
t.Execute(res, struct {
Body template.HTML
Theme string
}{
bodyHTML,
func() string {
if darktheme {
return "dark"
} else {
return "bright"
}
}(),
})
}
// http handler function for the main GUI
func handleRoot(res http.ResponseWriter, req *http.Request) {
tData, err := Asset("templates/workspace.tmpl")
if err != nil {
log.Fatal(err)
}
t, err := template.New("workspace").Parse(string(tData))
if err != nil {
log.Fatal(err)
}
body := handleChanges(req.URL.Query(), req.PostFormValue("data"), true)
var bodyHTML template.HTML
bodyHTML = template.HTML(body)
t.Execute(res, struct {
Body template.HTML
Theme string
}{
bodyHTML,
func() string {
if darktheme {
return "dark"
} else {
return "bright"
}
}(),
})
}
//handle changes
func handleChanges(form url.Values, data string, calledByForm bool) string {
res := bytes.Buffer{}
var errors bytes.Buffer
var notifications bytes.Buffer
var err error
// handle internal links
if form["internalLink"] != nil {
messages = append(messages, Message{"internalLink", form["internalLink"][0]})
}
// remove all persons from their groups
if form["reset"] != nil {
for i := range groups {
groups[i].Members = make([]*matching.Person, 0)
}
notifications.WriteString(l["reseted"] + "<br>")
}
var importError string
var errorLine int
errorLine = 0
if form["import"] != nil {
p := form.Get("import")
if p != "undefined" { // user pressed cancel, do nothing
err := handleImport(p)
// display any error messages from import
if err == nil {
projectPath = p
importError = "success"
} else {
importError = err.Error()
}
}
}
if form["save"] != nil {
notifications.WriteString(l["save_success"])
}
if form["save_as"] != nil {
p := form.Get("save_as")
if p != "undefined" { // user pressed cancel, do nothing
err := handleSaveAs(p)
// display any error messages from export
if err == nil {
projectPath = p
notifications.WriteString(l["save_success"])
} else {
errors.WriteString(l["save_error"])
}
}
}
if form["export_limited"] != nil {
p := form.Get("export_limited")
if p != "undefined" { // user pressed cancel, do nothing
err := handleExport(p, false)
// display any error messages from export
if err == nil {
notifications.WriteString(l["save_success"])
} else {
errors.WriteString(l["save_error"])
}
}
}
if form["export_total"] != nil {
p := form.Get("export_total")
if p != "undefined" { // user pressed cancel, do nothing
err := handleExport(p, true)
// display any error messages from export
if err == nil {
notifications.WriteString(l["save_success"])
} else {
errors.WriteString(l["save_error"])
}
}
}
// find all selected persons that should be affected by any action
listedPersons := make([]*matching.Person, 0)
for formName := range form {
if strings.HasPrefix(formName, "person") {
i, err := strconv.Atoi(strings.TrimPrefix(formName, "person"))
if err != nil {
log.Fatal(err)
}
listedPersons = append(listedPersons, persons[i])
}
}
// match selected persons if requested
if form["match"] != nil {
var qPersons []*matching.Person
if len(listedPersons) > 0 {
qPersons = listedPersons
} else {
qPersons = persons
}
m := matching.NewMatcher(matching.GetGrouplessPersons(qPersons, groups), groups)
err, errGroups := m.CheckMatcher()
if err == nil || err.Error() == "group_deleted" {
if err != nil {
errors.WriteString(l["group_deleted"] + errGroups + "<br>")
}
err = m.MatchManyAndTakeBest(50, time.Minute, 10*time.Second)
if err != nil {
errors.WriteString(l[err.Error()] + "<br>")
}
groups, persons = m.Groups, m.Persons
} else {
if err.Error() == "combination_overfilled" {
errors.WriteString(l["combination_overfilled"] + errGroups + "<br>")
} else {
errors.WriteString(l[err.Error()] + "<br>")
}
}
}
// delete the selected persons from the given groups
if form["delfrom"] != nil {
j, err := strconv.Atoi(form.Get("delfrom"))
if err != nil {
log.Fatal(err)
}
for _, p := range listedPersons {
i := p.IndexIn(groups[j].Members)
if i != -1 {
groups[j].Members = groups[j].Members[:i+copy(groups[j].Members[i:], groups[j].Members[i+1:])]
}
}
}
// add the selected persons to a given groups
if form["addto"] != nil {
j, err := strconv.Atoi(form.Get("addto"))
if err != nil {
log.Fatal(err)
}
for _, p := range listedPersons {
var hasThisPreference bool
for k := range p.Preferences {
if p.Preferences[k] == groups[j] {
hasThisPreference = true
}
}
//check if person has the wanted preference and is not assigned in case someone messes around with the links (DAU-safety) safety
if hasThisPreference && matching.FindPerson(p.Name, matching.GetGrouplessPersons(persons, groups)) != nil {
groups[j].Members = append(groups[j].Members, p)
hasThisPreference = false
}
}
}
// handle editmode and import from editmode
editmode := false
editmodeContent := ""
if form["edit"] != nil {
if data != "" {
groupStore, personStore, err := parseInput.ParseGroupsAndPersons(strings.NewReader(data))
if err != nil {
editmode = true
importError = err.Error()
editmodeContent = data
} else {
importError = "success"
groups = groupStore
persons = personStore
// avoid loosing data on sudden exit with no path being provided
if projectPath == "" {
w.SendMessage(struct {
Cmd string
}{"save_as"})
}
}
} else {
editmode = true
editmodeContent, err = parseInput.FormatGroupsAndPersons(groups, persons)
if err != nil {
errors.WriteString(l[err.Error()] + "<br>")
}
}
}
if importError == "success" {
notifications.WriteString(l["import_success"] + "<br>")
} else if importError != "" {
text, withLine, line := separateError(importError)
errString := l["import_error"] + l[text]
if withLine {
errorLine = line
errString = errString + l["line"] + strconv.Itoa(line)
}
errors.WriteString(errString)
}
// clear if in invalid state or requested
if (groups == nil || persons == nil) && errors.Len() == 0 {
projectPath = ""
groups = make([]*matching.Group, 0)
persons = make([]*matching.Person, 0)
}
if form["clear"] != nil {
projectPath = ""
groups = make([]*matching.Group, 0)
persons = make([]*matching.Person, 0)
notifications.WriteString(l["cleared"] + "<br>")
}
// calculate matching quote for display
quote_value, quoteInPercent := matching.NewMatcher(persons, groups).CalcQuote()
// sort persons before display
sortPersons()
// create menu:
if editmode {
// provide hidden iframe for post forms to avoid reload via server handler
res.WriteString(`<iframe name="form" style="display:none"></iframe>`)
res.WriteString(`<form action="/?edit" method="POST" target="form">`)
res.WriteString(`<div class="header"><div class="switch"><button type="submit">` + l["assign"] + `</button><a onclick="astilectron.sendMessage('?edit')">` + l["edit"] + `</a></div></div>`)
} else {
res.WriteString(`<div class="header"><ul><li><a onclick="astilectron.sendMessage('/?reset')">` + l["reset"] + `</a></li><li><a onclick="astilectron.sendMessage('/?match')">` + l["match_selected"] + `</a></li></ul><div class="switch"><a onclick="astilectron.sendMessage('/')">` + l["assign"] + `</a><a class="inactive" onclick="astilectron.sendMessage('?edit')">` + l["edit"] + `</a></div></div>`)
}
// sidebar
res.WriteString(`<div class="sidebar">`)
res.WriteString(`<div id="scale_container"><div id="scale" style="height: ` + strconv.FormatFloat(quoteInPercent, 'f', 2, 64) + `%;"><p>` + strconv.FormatFloat(quote_value, 'f', 2, 64) + `</p></div></div>`)
for i, group := range groups {
htmlid := fmt.Sprint("g", i)
var disliked bool
for _, m := range group.Members {
for j := int(len(m.Preferences)/2) + 1; j < len(m.Preferences); j++ {
if m.Preferences[j].Name == group.Name {
disliked = true
}
break
}
if disliked {
break
}
}
if (len(group.Members) < group.MinSize || len(group.Members) > group.Capacity) && !matching.AllEmpty(groups) {
res.WriteString(`<a class="unfitting group" href="#` + htmlid + `">` + group.StringWithSize() + `</a>`)
} else if disliked {
res.WriteString(`<a class="disliked group" href="#` + htmlid + `">` + group.StringWithSize() + `</a>`)
} else {
res.WriteString(`<a href="#` + htmlid + `" class="group">` + group.StringWithSize() + `</a>`)
}
}
fmt.Fprintf(&res, `</div>`)
res.WriteString(`</ul></div>`)
res.WriteString(`<div id="content">`)
// print notifications and errors:
if errors.Len() > 0 {
res.WriteString(`<div class="errors">` + errors.String() + `</div>`)
}
if notifications.Len() > 0 {
res.WriteString(`<div class="notifications">` + notifications.String() + `</div>`)
}
res.WriteString(`<div id="panels">`)
// list unassigned persons:
if !editmode {
grouplessPersons := matching.GetGrouplessPersons(persons, groups)
if !editmode && len(grouplessPersons) > 0 {
res.WriteString(`<table class="left panel">`)
res.WriteString(`<tr class="heading-big unassigned"><td colspan="5"><h3>` + l["unassigned"] + `</h3></td></tr>`)
res.WriteString(`<tr class="headings-middle unassigned"><th><span class="spacer"></span></th><th>` + l["name"] + `</th><th>` + l["1stchoice"] + `</th><th>` + l["2ndchoice"] + `</th><th>` + l["3rdchoice"] + `</th></tr>`)
for i, person := range grouplessPersons {
res.WriteString(`<tr class="person unassigned"><td><!--input type="checkbox" name="person` + strconv.Itoa(i) + `"--></td><td>` + person.Name + `</td>`)
for i := 0; i < 3; i++ {
if i >= len(person.Preferences) {
res.WriteString(`<td>--------</td>`)
} else {
prefID := person.Preferences[i].IndexIn(groups)
res.WriteString(`<td><a onclick="astilectron.sendMessage('?person` + strconv.Itoa(person.IndexIn(persons)) + `&addto=` + strconv.Itoa(prefID) + `')" title="` + l["add_to_group"] + `">` + person.Preferences[i].StringWithSize() + `</a></td>`)
}
}
res.WriteString("</tr>")
}
res.Write([]byte(`</table>`))
}
// list group and their members
if !editmode && len(groups) > 0 {
res.WriteString("<table class=\"right panel\">")
for i, group := range groups {
htmlid := fmt.Sprint("g", i)
res.Write([]byte(``))
res.WriteString(`<tr class="heading-big assigned"><td colspan="5"><h3 id="` + htmlid + `">` + group.StringWithSize() + `</h3></td></tr>`)
res.WriteString(`<tr class="headings-middle assigned"><th><span class="spacer"></span></th><th>` + l["name"] + `</th><th>` + l["1stchoice"] + `</th><th>` + l["2ndchoice"] + `</th><th>` + l["3rdchoice"] + `</th></tr>`)
for _, person := range group.Members {
res.WriteString(`<tr class="person assigned"><td><!--input type="checkbox" name="person` + strconv.Itoa(i) + `"--></td><td>` + person.Name + `</td>`)
for j := 0; j < 3; j++ {
if j >= len(person.Preferences) {
res.WriteString(`<td>--------</td>`)
} else {
pref := person.Preferences[j]
prefID := pref.IndexIn(groups)
personID := person.IndexIn(persons)
if pref == group {
res.WriteString(`<td><a onclick="astilectron.sendMessage('/?person` + strconv.Itoa(personID) + `&delfrom=` + strconv.Itoa(i) + `&internalLink=#` + htmlid + `')" class="blue" title="` + l["rem_from_group"] + `">` + pref.StringWithSize() + `</a></td>`)
} else {
res.WriteString(`<td><a onclick="astilectron.sendMessage('/?person` + strconv.Itoa(personID) + `&delfrom=` + strconv.Itoa(i) + `&addto=` + strconv.Itoa(prefID) + `&internalLink=#` + htmlid + `')" title="` + l["add_to_group"] + `">` + pref.StringWithSize() + `</a></td>`)
}
}
}
res.WriteString("</tr>")
}
}
res.WriteString("</table>")
}
}
// display editmode panel with texbox
if editmode {
res.WriteString(`<div class="panel">`)
res.WriteString(`<textarea id="edit" name="data" line="` + strconv.Itoa(errorLine) + `">` + editmodeContent + `</textarea>`)
res.WriteString(`</div></form>`)
}
// end document
res.WriteString("</div>")
res.WriteString(`</div>`)
// do refresh on real body (not hidden iframe)
if calledByForm {
sendBody(res.String())
for _, message := range messages {
w.SendMessage(message)
}
}
return res.String()
}
// handle file-uploads for import
func handleImport(filepath string) (err error) {
file, err := os.Open(filepath)
if err != nil {
return
}
defer file.Close()
groups, persons, err = parseInput.ParseGroupsAndPersons(file)
filename = filepath
return
}
//handle save_as action
func handleSaveAs(filepath string) (err error) {
defer updateBody()
file, err := os.Create(filepath)
if err != nil {
return err
}
defer file.Close()
text, err := parseInput.FormatGroupsAndPersons(groups, persons)
if err != nil {
if err.Error() != "groups_empty" {
return err
}
}
_, err = file.WriteString(text)
return err
}
//handle export as excel-file actions
func handleExport(filepath string, total bool) (err error) {
file, err := parseInput.FormatGroupsAndPersonsToExcel(groups, persons, l, total)
if err != nil {
return err
}
return file.Save(filepath)
}
//update body with no changes
func updateBody() {
form, err := url.ParseQuery(" ")
if err != nil {
log.Fatal(err)
}
body := handleChanges(form, "", false)
// Send message to webserver
sendBody(body)
}
func sendBody(body string) {
w.SendMessage(Message{
"body",
body,
})
}
// main function
func main() {
flag.Parse()
initLangs()
// properly exit on receiving exit signal
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
exit()
}()
// parse project opened with the program
if flag.NArg() >= 1 {
projectPath = flag.Arg(0)
}
// setup http listeners
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(&assetfs.AssetFS{
Asset: Asset,
AssetDir: AssetDir,
AssetInfo: AssetInfo,
Prefix: "static",
})))
http.HandleFunc("/", handleRoot)
http.HandleFunc("/about", handleAbout)
// listen on random free port
listener, err := net.Listen("tcp", "localhost:0")
if err != nil {
log.Fatal(err)
}
// Build splasher
/*var s *astisplash.Splasher
if s, err = astisplash.New(); err != nil {
log.Fatal(err)
}
defer s.Close()
// Splash
var sp *astisplash.Splash
if sp, err = s.Splash("static/loadscreen.png"); err != nil {
log.Fatal(err)
}*/
go func() {
log.Fatal(http.Serve(listener, nil))
}()
time.Sleep(time.Millisecond * 10)
// Extract icons
tempPath := path.Join(os.TempDir(), "astilectron")
err = os.Mkdir(tempPath, 0755)
if err != nil && !os.IsExist(err) {
log.Fatal(err)
}
iconPng, err := Asset("static/icon.png")
if err != nil {
log.Fatal(err)
}
iconPngPath := path.Join(tempPath, "icon.png")
err = ioutil.WriteFile(iconPngPath, iconPng, 0644)
if err != nil {
log.Fatal(err)
}
iconIco, err := Asset("static/icon.ico")
if err != nil {
log.Fatal(err)
}
iconIcoPath := path.Join(tempPath, "icon.ico")
err = ioutil.WriteFile(iconIcoPath, iconIco, 0644)
if err != nil {
log.Fatal(err)
}
// Initialize astilectron
var a, _ = astilectron.New(log.New(os.Stderr, "", 0), astilectron.Options{
AppName: "GroupMatcher",
AppIconDefaultPath: iconPngPath,
AppIconDarwinPath: iconIcoPath,
BaseDirectoryPath: os.TempDir(),
})
defer a.Close()
//a.SetProvisioner(astilectron_bindata.NewProvisioner(Disembed))
a.HandleSignals()
err = a.Start()
if err != nil {
log.Fatal(err)
}
/*
// Close splash
if err = sp.Close(); err != nil {
log.Fatal(err)
}
*/
urlString := "http://" + listener.Addr().String()
if projectPath != "" {
urlString += "?import=" + projectPath
}
// Create a new window
w, err = a.NewWindow(urlString, &astilectron.WindowOptions{
Center: astikit.BoolPtr(true),
Height: astikit.IntPtr(800),
Width: astikit.IntPtr(1200),
})
if err != nil {
log.Fatal(err)
}
err = w.Create()
if err != nil {
log.Fatal(err)
}
var m *astilectron.Menu
var createMenu func()
createMenu = func() {
m = w.NewMenu([]*astilectron.MenuItemOptions{
{
Label: astikit.StrPtr(l["file"]),
SubMenu: []*astilectron.MenuItemOptions{
{Label: astikit.StrPtr(l["open"]), OnClick: func(e astilectron.Event) bool {
w.SendMessage(struct {
Cmd string
}{"openFile"})
return false
}},
{Label: astikit.StrPtr(l["clear"]), OnClick: func(e astilectron.Event) bool {
form, err := url.ParseQuery("clear")
if err != nil {
log.Fatal(err)
}
body := handleChanges(form, "", false)
sendBody(body)
return false
}},
{Label: astikit.StrPtr(l["save"]), OnClick: func(e astilectron.Event) bool {
if projectPath != "" {
err := handleSaveAs(projectPath)
if err == nil {
form, err := url.ParseQuery("save")
if err != nil {
log.Fatal(err)
}
body := handleChanges(form, "", false)
sendBody(body)
return false
}
}
w.SendMessage(struct {
Cmd string
}{"save_as"})
return false
}},
{Label: astikit.StrPtr(l["save_as"]), OnClick: func(e astilectron.Event) bool {
w.SendMessage(struct {
Cmd string
}{"save_as"})
return false
}},
{Label: astikit.StrPtr(l["export"]), SubMenu: []*astilectron.MenuItemOptions{
{Label: astikit.StrPtr(l["exlimited"]), OnClick: func(e astilectron.Event) bool {
w.SendMessage(struct {
Cmd string
}{"export_limited"})
return false
}},
{Label: astikit.StrPtr(l["extotal"]), OnClick: func(e astilectron.Event) bool {
w.SendMessage(struct {
Cmd string
}{"export_total"})
return false
}},
}},
{Label: astikit.StrPtr(l["exit"]), Role: astilectron.MenuItemRoleQuit},
},
},
{
Label: astikit.StrPtr(l["language"]),
SubMenu: func() []*astilectron.MenuItemOptions {
o := make([]*astilectron.MenuItemOptions, 0, len(langs))
for n, lang := range langs {
name := n
o = append(o, &astilectron.MenuItemOptions{
Label: astikit.StrPtr(lang["#name"]),
Type: astilectron.MenuItemTypeRadio,
Checked: astikit.BoolPtr(lang["#name"] == l["#name"]),
OnClick: func(e astilectron.Event) bool {
l = langs[name]
go func() {
m.Destroy()
createMenu()
updateBody()
}()
return false
},
})
}
sort.Slice(o, func(i, j int) bool {
return strings.Compare(*o[i].Label, *o[j].Label) < 0
})
return o
}(),
},
{
Label: astikit.StrPtr(l["theme"]),
SubMenu: []*astilectron.MenuItemOptions{
{Label: astikit.StrPtr(l["bright"]), Type: astilectron.MenuItemTypeRadio, Checked: astikit.BoolPtr(!darktheme), OnClick: func(e astilectron.Event) bool {
setDarkTheme(false)
return false
}},
{Label: astikit.StrPtr(l["dark"]), Type: astilectron.MenuItemTypeRadio, Checked: astikit.BoolPtr(darktheme), OnClick: func(e astilectron.Event) bool {
setDarkTheme(true)
return false
}},
},
},
{
Label: astikit.StrPtr(l["help"]),
SubMenu: []*astilectron.MenuItemOptions{
{Label: astikit.StrPtr(l["help"]), Role: astilectron.MenuItemRoleHelp, OnClick: func(e astilectron.Event) bool {
openDoc()
return false
}},
{Label: astikit.StrPtr(l["about"]), Role: astilectron.MenuItemRoleAbout, OnClick: func(e astilectron.Event) bool {
go func() {
aboutWindow, err := a.NewWindow(urlString+"/about", &astilectron.WindowOptions{
Center: astikit.BoolPtr(true),
Width: astikit.IntPtr(900),
Height: astikit.IntPtr(450),
Resizable: astikit.BoolPtr(false),
})
if err != nil {
log.Fatal(err)
}
err = aboutWindow.Create()
if err != nil {
log.Fatal(err)
}
}()
return false
}},
},
},
})
m.Create()
}
createMenu()
// Listen to messages sent by webserver
w.OnMessage(func(e *astilectron.EventMessage) interface{} {
var msg string
err := e.Unmarshal(&msg)
if err != nil {
log.Println(err)
}
msg = strings.Trim(strings.Trim(msg, "/"), "?")
form, err := url.ParseQuery(msg)
if err != nil {
log.Fatal(err)
}
body := handleChanges(form, "", false)
// Send body to webserver
sendBody(body)
// send other messages
for _, message := range messages {
w.SendMessage(message)
}
return nil
})
a.Wait()
exit()
}