-
Notifications
You must be signed in to change notification settings - Fork 46
/
project.go
1653 lines (1222 loc) · 44.6 KB
/
project.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
package main
import (
"log"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/blang/semver"
"github.com/ncruces/zenity"
"github.com/pkg/browser"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"github.com/veandco/go-sdl2/sdl"
)
// const (
// SequenceNumber = iota
// SequenceNumberDash
// SequenceRoman
// SequenceBullet
// SequenceOff
// )
// const (
// SettingsGeneral = iota
// SettingsTasks
// SettingsGlobal
// SettingsKeyboard
// SettingsAbout
// )
const (
GUIFontSize100 = "100%"
GUIFontSize150 = "150%"
GUIFontSize200 = "200%"
GUIFontSize250 = "250%"
GUIFontSize300 = "300%"
GUIFontSize350 = "350%"
GUIFontSize400 = "400%"
// Project actions
BackupDelineator = "_bak_"
FileTimeFormat = "01_02_06_15_04_05"
// Per-Project Properties
ProjectCacheDirectory = "CacheDirectory"
)
type Project struct {
Pages []*Page
// CurrentPageIndex int
CurrentPage *Page
Camera *Camera
GridTexture *RenderTexture
Filepath string
Loading bool
UndoHistory *UndoHistory
LastCardType string
Modified bool
justModified bool
HasOrphanPages bool
LinkingCard *Card
LoadConfirmationTo string
BackingUp bool
LastBackup time.Time
Properties *Properties
}
func NewProject() *Project {
project := &Project{
Camera: NewCamera(),
// Pages: []*Page{},
LastCardType: ContentTypeCheckbox,
LastBackup: time.Now(),
Properties: NewProperties(),
}
if globals.Hierarchy != nil {
globals.Hierarchy.Destroy()
globals.Hierarchy = NewHierarchy(globals.Hierarchy.Container)
}
project.UndoHistory = NewUndoHistory(project)
globalPageID = 0
project.CurrentPage = project.AddPage()
project.CreateGridTexture()
project.Properties.Get(ProjectCacheDirectory).Set("")
globalCardID = 0
return project
}
func (project *Project) AddPage() *Page {
page := NewPage(project)
project.Pages = append(project.Pages, page)
return page
}
func (project *Project) RemovePage(page *Page) {
for i, p := range project.Pages {
if p == page {
project.Pages[i] = nil
project.Pages = append(project.Pages[:i], project.Pages[i+1:]...)
break
}
}
}
func (project *Project) PageIndex(page *Page) int {
for i, p := range project.Pages {
if p == page {
return i
}
}
return -1
}
func (project *Project) CreateGridTexture() {
guiTex := globals.Resources.Get(LocalRelativePath("assets/gui.png")).AsImage()
// project.GridTexture = TileTexture(guiTex, &sdl.Rect{480, 0, 32, 32}, 512, 512)
srcRect := &sdl.Rect{480, 0, 32, 32}
if project.GridTexture == nil {
project.GridTexture = NewRenderTexture()
project.GridTexture.RenderFunc = func() {
project.GridTexture.Recreate(512, 512)
gridColor := getThemeColor(GUIGridColor).Mix(getThemeColor(GUIBGColor), 0.5)
guiTex.Texture.SetColorMod(gridColor.RGB())
guiTex.Texture.SetAlphaMod(gridColor[3])
project.GridTexture.Texture.SetBlendMode(sdl.BLENDMODE_BLEND)
SetRenderTarget(project.GridTexture.Texture)
dst := &sdl.Rect{0, 0, srcRect.W, srcRect.H}
for y := int32(0); y < int32(project.GridTexture.Size.Y); y += srcRect.H {
for x := int32(0); x < int32(project.GridTexture.Size.X); x += srcRect.W {
dst.X = x
dst.Y = y
globals.Renderer.Copy(guiTex.Texture, srcRect, dst)
}
}
SetRenderTarget(nil)
}
}
project.GridTexture.RenderFunc()
}
func (project *Project) AutoBackup() {
if globals.ReleaseMode != ReleaseModeDemo && project.Filepath != "" && globals.Settings.Get(SettingsAutoBackup).AsBool() && time.Since(project.LastBackup) > time.Duration(globals.Settings.Get(SettingsAutoBackupTime).AsFloat())*time.Minute {
filename := project.Filepath
if strings.Contains(filename, ".plan"+BackupDelineator) {
filename = filename[:strings.Index(filename, ".plan")] + ".plan" + BackupDelineator + time.Now().Format(FileTimeFormat)
} else {
filename += BackupDelineator + time.Now().Format(FileTimeFormat)
}
ogFilepath := project.Filepath
project.Filepath = filename
project.BackingUp = true
project.Save()
project.BackingUp = false
project.LastBackup = time.Now()
project.Filepath = ogFilepath
head := filepath.Base(filename)
if !strings.Contains(head, ".plan"+BackupDelineator) {
head += BackupDelineator
} else {
ind := strings.Index(head, ".plan"+BackupDelineator)
head = head[:ind] + ".plan" + BackupDelineator
}
existingBackups := FilesInDirectory(filepath.Dir(project.Filepath), head)
maxBackups := int(globals.Settings.Get(SettingsMaxAutoBackups).AsFloat())
if len(existingBackups) > maxBackups {
deleteCount := len(existingBackups) - maxBackups
for i := 0; i < deleteCount; i++ {
if existingBackups[0] != ogFilepath {
if err := os.Remove(existingBackups[0]); err != nil {
log.Println("ERROR: Couldn't delete existing backups: ", err.Error())
}
}
existingBackups = existingBackups[1:]
}
}
}
}
func (project *Project) Update() {
if globals.NextProject != nil && globals.NextProject != project {
// You're the old project, so you can just chill. We do this
// because otherwise, a card may use a resource that got destroyed
// to render.
return
}
project.AutoBackup()
project.Camera.Update()
globals.Mouse.HiddenPosition = false
for _, page := range project.Pages {
if page.Valid() {
page.Update()
}
}
globals.Mouse.HiddenPosition = false
project.GlobalShortcuts()
globals.InputText = []rune{}
project.UndoHistory.Update()
// This should only be true for a total of essentially 1 or 2 frames, immediately after loading
project.Loading = false
if project.Modified && project.justModified {
globals.Dispatcher.Run()
}
project.justModified = false
}
// SetModifiedState sets the modified variable for the Project to true, but also sets justModified to true, allowing the Dispatcher to run to make things happen when the project is altered in some appreciable way.
func (project *Project) SetModifiedState() {
project.Modified = true
project.justModified = true
}
func (project *Project) DrawGrid() {
drawGridPiece := func(x, y float32) {
globals.Renderer.CopyF(project.GridTexture.Texture, nil, &sdl.FRect{x, y, project.GridTexture.Size.X, project.GridTexture.Size.Y})
}
extent := float32(10)
for y := -extent; y < extent; y++ {
for x := -extent; x < extent; x++ {
translated := project.Camera.TranslateRect(&sdl.FRect{x * project.GridTexture.Size.X, y * project.GridTexture.Size.Y, 0, 0})
drawGridPiece(translated.X, translated.Y)
}
}
// TODO: Draw pieces around the camera, rather than a solid 10 in every direction
halfW := float32(project.Camera.ViewArea().W / 2)
halfH := float32(project.Camera.ViewArea().H / 2)
ThickLine(project.Camera.TranslatePoint(Point{project.Camera.Position.X - halfW, 0}), project.Camera.TranslatePoint(Point{project.Camera.Position.X + halfW, 0}), 2, getThemeColor(GUIGridColor))
ThickLine(project.Camera.TranslatePoint(Point{0, project.Camera.Position.Y - halfH}), project.Camera.TranslatePoint(Point{0, project.Camera.Position.Y + halfH}), 2, getThemeColor(GUIGridColor))
if project.CurrentPage.UpwardPage != nil {
gridColor := getThemeColor(GUIGridColor)
text := project.CurrentPage.PointingSubpageCard.Properties.Get("description").AsString()
textSize := globals.TextRenderer.MeasureText([]rune(text), 1).CeilToGrid()
globals.Renderer.SetDrawColor(gridColor.RGBA())
globals.Renderer.FillRectF(project.Camera.TranslateRect(&sdl.FRect{0, -globals.GridSize, textSize.X, textSize.Y}))
globals.TextRenderer.QuickRenderText(text, project.Camera.TranslatePoint(Point{textSize.X / 2, -globals.GridSize}), 1, getThemeColor(GUIBGColor), nil, AlignCenter)
// globals.Renderer.DrawRectF(project.Camera.TranslateRect(&sdl.FRect{0, 0, SubpageScreenshotSize.X, SubpageScreenshotSize.Y}))
ssRect := project.Camera.TranslateRect(&sdl.FRect{0, 0, SubpageScreenshotSize.X / float32(SubpageScreenshotZoom), SubpageScreenshotSize.Y / float32(SubpageScreenshotZoom)}) // Screenshot zoom
ThickRect(int32(ssRect.X), int32(ssRect.Y), int32(ssRect.W), int32(ssRect.H), 2, gridColor)
guiTex := globals.Resources.Get(LocalRelativePath("assets/gui.png")).AsImage()
guiTex.Texture.SetColorMod(gridColor.RGB())
guiTex.Texture.SetAlphaMod(gridColor[3])
globals.Renderer.CopyF(guiTex.Texture, &sdl.Rect{80, 256, 32, 32}, &sdl.FRect{ssRect.X, ssRect.Y, 32, 32})
}
}
func (project *Project) Draw() {
if globals.NextProject != nil && globals.NextProject != project {
// You're the old project, so you can just chill. We do this
// because otherwise, a card may use a resource that got destroyed
// to render.
return
}
if (project.Camera.Zoom >= 1 || !globals.Settings.Get(SettingsHideGridOnZoomOut).AsBool()) && globals.Settings.Get(SettingsShowGrid).AsBool() {
project.DrawGrid()
}
// gridPieceToScreenW := globals.ScreenSize.X / project.GridTexture.Size.X / project.Camera.TargetZoom
// gridPieceToScreenH := globals.ScreenSize.Y / project.GridTexture.Size.Y / project.Camera.TargetZoom
// for iy := -gridPieceToScreenH; iy < gridPieceToScreenH; iy++ {
// for ix := -gridPieceToScreenW; ix < gridPieceToScreenW; ix++ {
// x := float32(ix * project.GridTexture.Size.X)
// x += float32(math.Round(float64(project.Camera.Position.X / project.GridTexture.Size.X * project.GridTexture.Size.X)))
// y := float32(iy * project.GridTexture.Size.Y)
// y += float32(math.Round(float64(project.Camera.Position.Y / project.GridTexture.Size.Y * project.GridTexture.Size.Y)))
// // x -= int32(project.Camera.Position.X)
// translated := project.Camera.Translate(&sdl.FRect{x, y, 0, 0})
// drawGridPiece(translated.X, translated.Y)
// }
// }
project.CurrentPage.Draw()
// We want this here so anything else can intercept a mouse button click (for example, a button drawn from a Card).
project.MouseActions()
}
func (project *Project) Save() {
if globals.ReleaseMode == ReleaseModeDemo {
globals.EventLog.Log("Cannot save in demo mode of MasterPlan.", true)
return
}
saveData, _ := sjson.Set("{}", "version", globals.Version.String())
saveData, _ = sjson.Set(saveData, "pan", project.Camera.TargetPosition)
saveData, _ = sjson.Set(saveData, "zoom", project.Camera.TargetZoom)
saveData, _ = sjson.Set(saveData, "currentPage", project.CurrentPage.ID)
if cache := project.Properties.Get(ProjectCacheDirectory); cache.AsString() != "" {
cache.Set(project.PathToRelative(cache.AsString(), true))
}
saveData, _ = sjson.SetRaw(saveData, "properties", project.Properties.Serialize(true))
if cache := project.Properties.Get(ProjectCacheDirectory); cache.AsString() != "" {
cache.Set(project.PathToAbsolute(cache.AsString(), true))
}
savedImages := map[string]string{}
pageData := "["
pagesToSave := []*Page{project.Pages[0]}
if len(project.Pages) > 1 {
for _, page := range project.Pages[1:] {
// If a page is an orphan, then we can just skip saving it as long as it doesn't have any cards
if page.Valid() {
pagesToSave = append(pagesToSave, page)
} else if project.HasOrphanPages {
valid := false
// Orphan
for _, card := range page.Cards {
if card.Valid {
valid = true
break
}
}
// else, page.PointingSubpageCard points to a card that has been deleted; if it hadn't been deleted, then the page would be valid
if !valid {
continue
}
pagesToSave = append(pagesToSave, page)
}
}
}
sort.SliceStable(pagesToSave, func(i, j int) bool { return pagesToSave[i].ID < pagesToSave[j].ID })
type convertedFilepath struct {
Original string
PropName string
Card *Card
}
for i, page := range pagesToSave {
// Convert all paths to relative before saving
converted := []convertedFilepath{}
for _, card := range page.Cards {
if fp := card.Properties.GetIfExists("filepath"); fp != nil && (globals.Resources.Get(fp.AsString()) == nil || !globals.Resources.Get(fp.AsString()).SaveFile) && FileExists(fp.AsString()) {
converted = append(converted, convertedFilepath{Original: fp.AsString(), PropName: "filepath", Card: card})
fp.Set(project.PathToRelative(fp.AsString(), false))
}
if run := card.Properties.GetIfExists("run"); run != nil && FileExists(run.AsString()) {
converted = append(converted, convertedFilepath{Original: run.AsString(), PropName: "run", Card: card})
run.Set(project.PathToRelative(run.AsString(), false))
}
}
pageData += page.Serialize()
if i < len(pagesToSave)-1 {
pageData += ", "
}
// Reset the filepaths after serialization
for _, conv := range converted {
conv.Card.Properties.Get(conv.PropName).Set(conv.Original)
}
}
pageData += "]"
saveData, _ = sjson.SetRaw(saveData, "pages", pageData)
for _, page := range project.Pages {
for _, card := range page.Cards {
fp := card.Properties.Get("filepath").AsString()
if res := globals.Resources.Get(fp); res != nil && res.SaveFile {
if pngFile, err := os.ReadFile(fp); err != nil {
panic(err)
} else {
out := ""
for _, b := range pngFile {
out += string(b)
}
savedImages[fp] = string(out)
}
} else {
card.Properties.Remove("saveimage")
}
}
}
saveData, _ = sjson.Set(saveData, "savedimages", savedImages)
saveData = gjson.Get(saveData, "@pretty").String()
if file, err := os.Create(project.Filepath); err != nil {
log.Println(err)
} else {
file.Write([]byte(saveData))
file.Close()
file.Sync() // Ensure the save file is written
}
if project.BackingUp {
globals.EventLog.Log("Project back-up successfully saved.", false)
} else {
globals.EventLog.Log("Project saved successfully.", false)
}
AddFileToRecentFilesList(project.Filepath)
project.Modified = false
}
func (project *Project) SaveAs() {
if filename, err := zenity.SelectFileSave(zenity.Title("Save MasterPlan Project..."), zenity.ConfirmOverwrite(), zenity.FileFilter{Name: "Project File (*.plan)", Patterns: []string{"*.plan"}}); err == nil {
if filepath.Ext(filename) != ".plan" {
filename += ".plan"
}
project.Filepath = filename
project.Save()
} else if err != zenity.ErrCanceled {
panic(err)
}
}
// Open a project to load
func (project *Project) Open() {
if filename, err := zenity.SelectFile(zenity.Title("Select MasterPlan Project to Open..."), zenity.FileFilter{Name: "Project File (*.plan / *.plan_bak_*)", Patterns: []string{"*.plan", "*.plan_bak_*"}}); err == nil {
project.LoadConfirmationTo = filename
loadConfirm := globals.MenuSystem.Get("confirm load")
loadConfirm.Center()
loadConfirm.Open()
} else if err != zenity.ErrCanceled {
panic(err)
}
}
func OpenProjectFrom(filename string) {
i := 0
for {
if i >= len(globals.RecentFiles) {
break
}
file := globals.RecentFiles[i]
if !FileExists(file) {
globals.RecentFiles = append(globals.RecentFiles[:i], globals.RecentFiles[i+1:]...)
} else {
i++
}
}
jsonData, err := os.ReadFile(filename)
if err != nil {
globals.EventLog.Log("Error: %s", true, err.Error())
} else {
json := string(jsonData)
if !gjson.Get(json, "version").Exists() && !gjson.Get(json, "Version").Exists() {
// if !gjson.Get(json, "pages").Exists() && !gjson.Get(json, "Tasks").Exists() {
globals.EventLog.Log("Warning: Cannot open project as it doesn't appear to be a valid MasterPlan project file. Please double-check to ensure it is valid.", true)
return
}
// Destroy resources before we load new ones
globals.Resources.Destroy()
log.Println("Load started.")
AddFileToRecentFilesList(filename)
log.Println("Recent files list updated...")
globals.EventLog.On = false
newProject := NewProject()
newProject.Loading = true
newProject.UndoHistory.On = false
globals.NextProject = newProject
brokenProject := false
savedImageFileNames := map[string]string{}
if ver, err := semver.Parse(gjson.Get(json, "version").String()); err != nil || ver.Minor < 8 {
globals.EventLog.Log("WARNING: Not all features from MasterPlan v0.7.2 have been re-implemented.\nPlease double-check the project to ensure it has been imported correctly, and\ncheck the roadmap under Help to see what remains to be re-implemented.\nIt would probably be best not to save over the original plan.", true)
// IMPORT v0.7!
// We don't set the filepath here because we explicity want you not to save over the project accidentally.
// newProject.Filepath = filename
boardNames := gjson.Get(json, "BoardNames").Array()
createdSubpages := make([]*Card, 0, len(boardNames)-1)
x := float32(0)
for _, b := range boardNames[1:] {
t := newProject.CurrentPage.CreateNewCard(ContentTypeSubpage)
t.Rect.X = x
t.Properties.Get("description").Set(b.String())
x += t.Rect.W + globals.GridSize
createdSubpages = append(createdSubpages, t)
}
type Line struct {
Page *Page
Start Point
Endings []Point
}
newLine := func(page *Page, x, y float32) Line {
return Line{
Page: page,
Start: Point{x, y},
Endings: []Point{},
}
}
linePositions := []Line{}
tasks := gjson.Get(json, "Tasks").Array()
for _, task := range tasks {
boardIndex := task.Get("BoardIndex").Int()
cardType := ContentTypeCheckbox
content := task.Get(`TaskType\.CurrentChoice`).Int()
switch content {
// case 0: // Checkbox
case 1: // Progression
cardType = ContentTypeNumbered
case 2:
cardType = ContentTypeNote
case 3:
cardType = ContentTypeImage
case 4:
cardType = ContentTypeSound
case 5:
cardType = ContentTypeTimer
case 6:
// Line
line := newLine(newProject.Pages[boardIndex], float32(task.Get(`Position\.X`).Float()*2), float32(task.Get(`Position\.Y`).Float()*2))
endings := task.Get(`LineEndings`).Array()
for i := 0; i < len(endings); i += 2 {
line.Endings = append(line.Endings, Point{float32(endings[i].Float() * 2), float32(endings[i+1].Float() * 2)})
}
linePositions = append(linePositions, line)
continue // Lines don't exist, so we do our best to connect cards that lines wwere connected to and move on
case 7:
cardType = ContentTypeMap
case 8:
// cardType = ContentTypeWhiteboard
continue
case 9:
cardType = ContentTypeTable
}
card := newProject.Pages[boardIndex].CreateNewCard(cardType)
card.Rect.X = float32(task.Get(`Position\.X`).Float() * 2) // Grid is 32x32 in MasterPlan v0.8 compared to 16x16 in v0.7.2
card.Rect.Y = float32(task.Get(`Position\.Y`).Float() * 2)
if card.Properties.Has("description") {
desc := ""
if d := task.Get("Description").String(); d != "" {
desc = d
} else if d := task.Get(`TimerName\.Text`).String(); d != "" {
desc = d
}
card.Properties.Get("description").Set(desc)
}
if card.Properties.Has("checked") {
card.Properties.Get("checked").Set(task.Get(`Checkbox\.Checked`).Bool())
}
if card.Properties.Has("current") {
card.Properties.Get("current").Set(task.Get(`Progression\.Current`).Float())
card.Properties.Get("maximum").Set(task.Get(`Progression\.Max`).Float())
}
if card.Completable() && task.Get(`DeadlineDaySpinner\.Number`).Exists() {
deadlineDay := int(task.Get(`DeadlineDaySpinner\.Number`).Int())
deadlineMonth := time.Month(task.Get(`DeadlineMonthSpinner\.CurrentChoice`).Int() + 1)
deadlineYear := int(task.Get(`DeadlineYearSpinner\.Number`).Int())
now := time.Now()
deadline := time.Date(deadlineYear, deadlineMonth, deadlineDay, 0, 0, 0, 0, now.Location())
card.Properties.Get("deadline").Set(deadline.Format("2006-01-02"))
}
if card.Properties.Has("filepath") {
// If it's a saved image from the clipboard, then the path is of no consequence.
if !card.Properties.Has("saveimage") {
fp := []string{}
for _, element := range task.Get(`FilePath`).Array() {
fp = append(fp, element.String())
}
relativePath := filepath.Join(fp...)
relativePath = filepath.ToSlash(relativePath)
card.Properties.Get("filepath").Set(relativePath)
}
if sound, ok := card.Contents.(*SoundContents); ok {
sound.LoadFile()
} else if image, ok := card.Contents.(*ImageContents); ok {
image.LoadFile()
}
}
if task.Get(`ImageDisplaySize\.X`).Exists() {
w := float32(task.Get(`ImageDisplaySize\.X`).Float() * 2)
h := float32(task.Get(`ImageDisplaySize\.Y`).Float() * 2)
if image, ok := card.Contents.(*ImageContents); ok {
if image.Resource != nil {
card.Rect.W = w
card.Rect.H = h
}
} else {
card.Rect.W = w
card.Rect.H = h
}
}
if task.Get(`TimerMode\.CurrentChoice`).Exists() {
timerType := task.Get(`TimerMode\.CurrentChoice`).Int()
switch timerType {
// Countdown
case 0:
card.Properties.Get("mode group").Set(TimerModeCountdown)
str := card.Contents.(*TimerContents).SetMaxTime(int(task.Get(`TimerMinuteSpinner\.Number`).Int()), int(task.Get(`TimerSecondSpinner\.Number`).Int()))
card.Properties.Get("max time").Set(str)
triggerMode := task.Get(`TimerTriggerMode\.CurrentChoice`).Int()
switch triggerMode {
case 1:
card.Properties.Get("trigger mode").Set(TriggerTypeSet)
case 2:
card.Properties.Get("trigger mode").Set(TriggerTypeClear)
default:
card.Properties.Get("trigger mode").Set(TriggerTypeToggle)
}
case 3:
card.Properties.Get("mode group").Set(TimerModeStopwatch)
}
}
if task.Get(`MapData`).Exists() {
card.Rect.H -= globals.GridSize // There's no header bar for maps in 0.8, so they're one row shorter
card.Update() // Allows the map to be set to the correct size
mc := card.Contents.(*MapContents)
mc.MapData.Clear()
for y, row := range task.Get(`MapData`).Array() {
for x, value := range row.Array() {
mc.MapData.SetI(x, y, int(value.Int()))
}
}
card.Properties.Get("contents").Set(mc.MapData.Serialize())
mc.UpdateTexture()
}
if task.Get(`TableData`).Exists() {
card.Update()
tc := card.Contents.(*TableContents)
height := len(task.Get(`TableData.Rows`).Array())
width := len(task.Get(`TableData.Columns`).Array())
card.Recreate(float32(width)*globals.GridSize, float32(height)*globals.GridSize)
tc.TableData.Resize(width, height)
for i, s := range task.Get(`TableData.Columns`).Array() {
ch := tc.TableData.ColumnHeadings[i]
ch.Label.SetTextRaw([]rune(s.String()))
ch.Label.RecreateTexture()
}
for i, s := range task.Get(`TableData.Rows`).Array() {
tc.TableData.RowHeadings[i].Label.SetTextRaw([]rune(s.String()))
}
for y, row := range task.Get(`TableData.Completion`).Array() {
for x, value := range row.Array() {
tc.TableData.SetValue(x, y, int(value.Int()))
}
}
}
card.LockPosition()
// Autoresize the card to fit the amount of text typed.
if auto, ok := card.Contents.(AutosetSizer); ok {
auto.AutosetSize()
}
if cardType != ContentTypeNote && cardType != ContentTypeImage && cardType != ContentTypeMap && cardType != ContentTypeTable {
card.Collapse() // Collapsing the cards make them align more correctly to the 0.7 "single-line" layout
}
}
// Attempt to connect relevant Cards
for _, line := range linePositions {
for _, dest := range line.Endings {
var baseCard *Card
var destination *Card
if cards := line.Page.Grid.NeighboringCards(line.Start.X, line.Start.Y); len(cards) > 0 {
for _, c := range cards {
// Skip subpages because they don't exist in 0.7
if c.ContentType == ContentTypeSubpage {
continue
}
baseCard = c
}
}
if cards := line.Page.Grid.NeighboringCards(dest.X, dest.Y); len(cards) > 0 {
for _, c := range cards {
// Skip subpages because they don't exist in 0.7
if c.ContentType == ContentTypeSubpage {
continue
}
destination = c
}
}
if baseCard != nil && destination != nil && baseCard != destination {
baseCard.Link(destination)
}
}
}
rootPageBounds := CorrectingRect{}
root := newProject.Pages[0]
if len(root.Cards) > 0 {
rootPageBounds.X1 = root.Cards[0].Rect.X
rootPageBounds.Y1 = root.Cards[0].Rect.Y
rootPageBounds.X2 = root.Cards[0].Rect.X
rootPageBounds.Y2 = root.Cards[0].Rect.Y
for _, card := range root.Cards {
if card.ContentType != ContentTypeSubpage {
rootPageBounds = rootPageBounds.AddXY(card.Rect.X, card.Rect.Y)
rootPageBounds = rootPageBounds.AddXY(card.Rect.X+card.Rect.W, card.Rect.Y+card.Rect.H)
}
}
for _, subpage := range createdSubpages {
subpage.Rect.X += rootPageBounds.Width()
subpage.LockPosition()
}
}
} else {
newProject.Filepath = filename
if props := gjson.Get(json, "properties"); props.Exists() {
newProject.Properties.Deserialize(gjson.Get(json, "properties").String())
}
if cache := newProject.Properties.Get(ProjectCacheDirectory); cache.AsString() != "" {
cache.Set(newProject.PathToAbsolute(cache.AsString(), true))
}
for fpName, imgData := range gjson.Get(json, "savedimages").Map() {
imgOut := []byte{}
for _, c := range imgData.String() {
imgOut = append(imgOut, byte(c))
}
newFName, _ := WriteImageToTemp(imgOut)
savedImageFileNames[fpName] = newFName
globals.Resources.Get(newFName).TempFile = true
globals.Resources.Get(newFName).SaveFile = true
}
log.Println("Any saved images loaded.")
log.Println("Loading pages...")
if ver.LTE(semver.MustParse("0.8.0-alpha.3")) {
page := gjson.Get(json, "root.contents").Array()[0]
newProject.Pages[0].DeserializePageData(page.String())
newProject.Pages[0].DeserializeCards(page.String())
} else {
// v0.8.0-alpha.3 and below just had one page, but organized into a folder; this is no longer done.
for i := 0; i < len(gjson.Get(json, "pages").Array())-1; i++ {
newProject.AddPage()
}
for p, pageData := range gjson.Get(json, "pages").Array() {
page := newProject.Pages[p]
page.DeserializePageData(pageData.String())
}
for p, pageData := range gjson.Get(json, "pages").Array() {
newProject.Pages[p].DeserializeCards(pageData.String())
}
}
}
newProject.SendMessage(NewMessage(MessageProjectLoadingAllCardsCreated, nil, nil))
for _, page := range newProject.Pages {
if page.PointingSubpageCard == nil && page != newProject.Pages[0] {
brokenProject = true
}
for _, card := range page.Cards {
card.DisplayRect.X = card.Rect.X
card.DisplayRect.Y = card.Rect.Y
card.DisplayRect.W = card.Rect.W
card.DisplayRect.H = card.Rect.H
if card.Properties.Has("saveimage") {
imgPath, exists := savedImageFileNames[card.Properties.Get("filepath").AsString()]
if exists {
card.Contents.(*ImageContents).LoadFileFrom(imgPath) // Reload the file
} else {
card.Properties.Remove("saveimage")
globals.EventLog.Log("Saved screenshot: %s could not be loaded.\n", true, imgPath)
}
}
}
page.UpdateLinks()
}
// newProject.Camera.Update()
// Settle the elements in - we do this a few times because it seems like things might take two steps (create card, set properties, create links, etc)
globals.Renderer.SetClipRect(nil)
for i := 0; i < 3; i++ {
for _, page := range newProject.Pages {
newProject.CurrentPage = page
page.Update()
page.Draw()
}
}
// for _, page := range newProject.Pages {
// newProject.CurrentPage = page
// for _, card := range page.Cards {