forked from SolarLune/masterplan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproject.go
2307 lines (1764 loc) · 64 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 (
"fmt"
"image/gif"
"io"
"io/ioutil"
"log"
"math"
"net/http"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
"github.com/pkg/browser"
"github.com/tanema/gween"
"github.com/tanema/gween/ease"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"github.com/faiface/beep"
"github.com/faiface/beep/speaker"
"github.com/gen2brain/raylib-go/raymath"
"github.com/ncruces/zenity"
"github.com/gabriel-vasile/mimetype"
rl "github.com/gen2brain/raylib-go/raylib"
)
const (
NUMBERING_SEQUENCE_NUMBER = iota
NUMBERING_SEQUENCE_NUMBER_DASH
NUMBERING_SEQUENCE_ROMAN
NUMBERING_SEQUENCE_BULLET
NUMBERING_SEQUENCE_OFF
)
const (
// Task messages
MessageNeighbors = "neighbors"
MessageNumbering = "numbering"
MessageDelete = "delete"
MessageSelect = "select"
MessageDropped = "dropped"
MessageDoubleClick = "double click"
MessageDragging = "dragging"
MessageTaskClose = "task close"
// Project actions
ActionNewProject = "new"
ActionLoadProject = "load"
ActionSaveAsProject = "save as"
BackupDelineator = "_bak_"
)
var firstFreeTaskID = 0
type Project struct {
// Project Settings
TaskShadowSpinner *Spinner
GridVisible *Checkbox
SampleRate *Spinner
SetSampleRate int
SampleBuffer int
ShowIcons *Checkbox
PulsingTaskSelection *Checkbox
AutoSave *Checkbox
AutoReloadThemes *Checkbox
AutoLoadLastProject *Checkbox
DisableSplashscreen *Checkbox
SaveSoundsPlaying *Checkbox
OutlineTasks *Checkbox
ColorThemeSpinner *Spinner
BracketSubtasks *Checkbox
LockProject *Checkbox
NumberingSequence *Spinner
NumberTopLevel *Checkbox
AutomaticBackupInterval *NumberSpinner
AutomaticBackupKeepCount *NumberSpinner
MaxUndoSteps *NumberSpinner
// Internal data to make stuff work
FilePath string
GridSize int32
Boards []*Board
BoardIndex int
BoardPanel rl.Rectangle
ZoomLevel int
CameraPan rl.Vector2
CameraOffset rl.Vector2
FullyInitialized bool
GridTexture rl.Texture2D
ContextMenuOpen bool
ContextMenuPosition rl.Vector2
ProjectSettingsOpen bool
Selecting bool
SelectionStart rl.Vector2
DoubleClickTimer int
DoubleClickTaskID int
CopyBuffer []*Task
Cutting bool // If cutting, then this boolean is set
TaskOpen bool
ThemeReloadTimer int
JustLoaded bool
ResizingImage bool
LogOn bool
LoadRecentDropdown *DropdownMenu
SearchedTasks []*Task
FocusedSearchTask int
Searchbar *Textbox
StatusBar rl.Rectangle
GUI_Icons rl.Texture2D
Patterns rl.Texture2D
ShortcutKeyTimer int
PreviousTaskType string
Resources map[string]*Resource
Modified bool
Locked bool
RenameBoardPopup *TextboxPopup
AbandonPlanPopup *ButtonChoicePopup
ActivePopup Popup
PopupAction string
PopupArgument string
SettingsColumns []*SettingsColumn
BackupTimer time.Time
UndoFade *gween.Sequence
Undoing int
//UndoBuffer // This is going to be difficult, because it needs to store a set of changes to execute for each change;
// There's two ways to go about this I suppose. 1) Store the changes to disk whenever a change happens, then restore it when you undo, and vice-versa when redoing.
// This would be simple, but could be prohibitive if the size becomes large. Upside is that since we're storing the buffer to disk, you can undo
// things even between program sessions which is pretty insane.
// 2) Make actual functions, I guess, for each user-controllable change that can happen to the project, and then store references to these functions
// in a buffer; then walk backwards through them to change them, I suppose?
}
func NewProject() *Project {
searchBar := NewTextbox(float32(rl.GetScreenWidth())-128, float32(float32(rl.GetScreenHeight()))-23, 128, 23)
searchBar.AllowNewlines = false
project := &Project{
FilePath: "",
GridSize: 16,
ZoomLevel: -99,
CameraPan: rl.Vector2{0, 0},
Searchbar: searchBar,
StatusBar: rl.Rectangle{0, float32(rl.GetScreenHeight()) - 32, float32(rl.GetScreenWidth()), 32},
GUI_Icons: rl.LoadTexture(GetPath("assets", "gui_icons.png")),
SampleBuffer: 512,
Patterns: rl.LoadTexture(GetPath("assets", "patterns.png")),
Resources: map[string]*Resource{},
LoadRecentDropdown: NewDropdown(0, 0, 0, 0, "Load Recent..."), // Position and size is set below in the context menu handling
RenameBoardPopup: NewTextboxPopup("New Board name:", "Accept", "Cancel"),
AbandonPlanPopup: NewButtonChoicePopup("This plan has been modified; Abandon plan?", "Yes", "No"),
SettingsColumns: []*SettingsColumn{},
UndoFade: gween.NewSequence(gween.New(0, 192, 0.25, ease.InOutExpo), gween.New(192, 0, 0.25, ease.InOutExpo)),
ColorThemeSpinner: NewSpinner(0, 0, 256, 24),
TaskShadowSpinner: NewSpinner(0, 0, 128, 24, "Off", "Flat", "Smooth", "3D"),
OutlineTasks: NewCheckbox(0, 0, 32, 32),
GridVisible: NewCheckbox(0, 0, 32, 32),
ShowIcons: NewCheckbox(0, 0, 32, 32),
NumberingSequence: NewSpinner(0, 0, 128, 24, "1.1.", "1-1)", "I.I.", "Bullets", "Off"),
NumberTopLevel: NewCheckbox(0, 0, 32, 32),
PulsingTaskSelection: NewCheckbox(0, 0, 32, 32),
AutoSave: NewCheckbox(0, 0, 32, 32),
SaveSoundsPlaying: NewCheckbox(0, 0, 32, 32),
SampleRate: NewSpinner(0, 0, 128, 24, "22050", "44100", "48000", "88200", "96000"),
BracketSubtasks: NewCheckbox(0, 0, 32, 32),
LockProject: NewCheckbox(0, 0, 32, 32),
AutomaticBackupInterval: NewNumberSpinner(0, 0, 128, 40),
AutomaticBackupKeepCount: NewNumberSpinner(0, 0, 128, 40),
MaxUndoSteps: NewNumberSpinner(0, 0, 160, 32),
// Program settings GUI elements
AutoLoadLastProject: NewCheckbox(0, 0, 32, 32),
AutoReloadThemes: NewCheckbox(0, 0, 32, 32),
DisableSplashscreen: NewCheckbox(0, 0, 32, 32),
}
column := project.AddSettingsColumn()
column.Add("Color Theme:", project.ColorThemeSpinner)
column.Add("Task Depth:", project.TaskShadowSpinner)
column.Add("Outline Tasks:", project.OutlineTasks)
column.Add("Grid Visible:", project.GridVisible)
column.Add("Show Icons:", project.ShowIcons)
column.Add("Bracket Sub-Tasks:", project.BracketSubtasks)
column.Add("Lock Project:", project.LockProject)
column.Add("Numbering Style:", project.NumberingSequence)
column.Add("Backup every X minutes:", project.AutomaticBackupInterval)
column.Add("Keep X backups max:", project.AutomaticBackupKeepCount)
column = project.AddSettingsColumn()
column.Add("Number Top-level Tasks:", project.NumberTopLevel)
column.Add("Pulse Selected Tasks:", project.PulsingTaskSelection)
column.Add("Auto-save Project:", project.AutoSave)
column.Add("Project Samplerate:", project.SampleRate)
column.Add("Save Sound Playback:", project.SaveSoundsPlaying)
column.Add("Maximum Undo Steps:", project.MaxUndoSteps)
column.Add("--Program Settings--", nil)
column.Add("Auto-reload Themes:", project.AutoReloadThemes)
column.Add("Auto-load Last Project:", project.AutoLoadLastProject)
column.Add("Disable Splashscreen:", project.DisableSplashscreen)
project.Boards = []*Board{NewBoard(project)}
project.OutlineTasks.Checked = true
project.BracketSubtasks.Checked = true
project.LogOn = true
project.PulsingTaskSelection.Checked = true
project.TaskShadowSpinner.CurrentChoice = 2
project.GridVisible.Checked = true
project.ShowIcons.Checked = true
project.DoubleClickTimer = -1
project.PreviousTaskType = "Check Box"
project.NumberTopLevel.Checked = true
project.AutomaticBackupInterval.SetNumber(15) // Seems sensible to make new projects have this as a default.
project.AutomaticBackupInterval.Minimum = 0
project.AutomaticBackupInterval.Maximum = 60
project.AutomaticBackupKeepCount.SetNumber(3)
project.AutomaticBackupKeepCount.Minimum = 1
project.MaxUndoSteps.Minimum = 0
currentTheme = "Sunlight" // Default theme for new projects and new sessions is the Sunlight theme
project.ReloadThemes()
project.ChangeTheme(currentTheme)
if strings.Contains(runtime.GOOS, "darwin") {
project.SampleRate.SetChoice("22050") // For some reason, sound on Mac is choppy unless the project's sample rate is 22050.
} else {
project.SampleRate.SetChoice("44100")
}
speaker.Init(beep.SampleRate(project.SampleRate.ChoiceAsInt()), project.SampleBuffer)
project.SetSampleRate = project.SampleRate.ChoiceAsInt()
return project
}
func (project *Project) CurrentBoard() *Board {
return project.Boards[project.BoardIndex]
}
func (project *Project) GetAllTasks() []*Task {
tasks := []*Task{}
for _, b := range project.Boards {
tasks = append(tasks, b.Tasks...)
}
return tasks
}
func (project *Project) SaveAs() {
if savePath, err := zenity.SelectFileSave(
zenity.Title("Select a location and name to save the Project."),
zenity.ConfirmOverwrite(),
zenity.FileFilters{{Name: ".plan", Patterns: []string{"*.plan"}}}); err == nil && savePath != "" {
if filepath.Ext(savePath) != ".plan" {
savePath += ".plan"
}
project.ExecuteDestructiveAction(ActionSaveAsProject, savePath)
}
}
func (project *Project) Save(backup bool) {
success := true
if !backup && project.LockProject.Checked && project.Locked {
success = false
project.Log("Project cannot be manually saved, as it is locked.")
} else {
if project.FilePath != "" {
// Sort the Tasks by their ID, then loop through them using that slice. This way,
// They store data according to their creation ID, not according to their position
// in the world.
tasksByID := append([]*Task{}, project.GetAllTasks()...)
sort.Slice(tasksByID, func(i, j int) bool { return tasksByID[i].ID < tasksByID[j].ID })
// We're passing in actual JSON strings for task serlizations, so we have to actually construct the
// string containing our JSON array of tasks ourselves.
taskData := "["
firstTask := true
for _, task := range tasksByID {
if firstTask {
firstTask = false
} else {
taskData += ","
}
if task.Serializable() {
taskData += task.Serialize()
}
}
taskData += "]"
data := `{}`
// Not handling any of these errors because uuuuuuuuuh idkkkkkk should there ever really be errors
// with a blank JSON {} object????
data, _ = sjson.Set(data, `Version`, softwareVersion.String())
data, _ = sjson.Set(data, `LockProject`, project.LockProject.Checked)
data, _ = sjson.Set(data, `BoardIndex`, project.BoardIndex)
data, _ = sjson.Set(data, `BoardCount`, len(project.Boards))
data, _ = sjson.Set(data, `AutoSave`, project.AutoSave.Checked)
data, _ = sjson.Set(data, `Pan\.X`, project.CameraPan.X)
data, _ = sjson.Set(data, `Pan\.Y`, project.CameraPan.Y)
data, _ = sjson.Set(data, `ZoomLevel`, project.ZoomLevel)
data, _ = sjson.Set(data, `ColorTheme`, currentTheme)
data, _ = sjson.Set(data, `OutlineTasks`, project.OutlineTasks.Checked)
data, _ = sjson.Set(data, `BracketSubtasks`, project.BracketSubtasks.Checked)
data, _ = sjson.Set(data, `TaskShadow`, project.TaskShadowSpinner.CurrentChoice)
data, _ = sjson.Set(data, `ShowIcons`, project.ShowIcons.Checked)
data, _ = sjson.Set(data, `NumberTopLevel`, project.NumberTopLevel.Checked)
data, _ = sjson.Set(data, `NumberingSequence`, project.NumberingSequence.CurrentChoice)
data, _ = sjson.Set(data, `PulsingTaskSelection`, project.PulsingTaskSelection.Checked)
data, _ = sjson.Set(data, `GridVisible`, project.GridVisible.Checked)
data, _ = sjson.Set(data, `GridSize`, project.GridSize)
data, _ = sjson.Set(data, `SampleRate`, project.SampleRate.ChoiceAsInt())
data, _ = sjson.Set(data, `SampleBuffer`, project.SampleBuffer)
data, _ = sjson.Set(data, `SaveSoundsPlaying`, project.SaveSoundsPlaying.Checked)
data, _ = sjson.Set(data, `BackupInterval`, project.AutomaticBackupInterval.GetNumber())
data, _ = sjson.Set(data, `BackupKeepCount`, project.AutomaticBackupKeepCount.GetNumber())
data, _ = sjson.Set(data, `UndoMaxSteps`, project.MaxUndoSteps.GetNumber())
data, _ = sjson.SetRaw(data, `Tasks`, taskData) // taskData is already properly encoded and formatted JSON
if !backup && project.LockProject.Checked {
project.Log("Project lock engaged.")
project.Locked = true
}
boardNames := []string{}
for _, board := range project.Boards {
boardNames = append(boardNames, board.Name)
}
sjson.Set(data, `BoardNames`, boardNames)
f, err := os.Create(project.FilePath)
if err != nil {
log.Println(err)
} else {
defer f.Close()
data = gjson.Parse(data).Get("@pretty").String() // Pretty print it so it's visually nice in the .plan file.
f.Write([]byte(data))
programSettings.Save()
err = f.Sync() // Want to make sure the file is written
if err != nil {
log.Println("ERROR: Can't write file to system: ", err)
success = false
}
}
} else {
success = false
}
if success {
if !backup {
project.Log("Save successful.")
// Modified flag only gets cleared on manual saves, not automatic backups
project.Modified = false
} else {
project.Log("Backup successful.")
}
} else {
project.Log("ERROR: Save / backup unsuccessful.")
}
}
}
func LoadProjectFrom() *Project {
// I used to have the extension for this file selector set to "*.plan", but Mac doesn't seem to recognize
// MasterPlan's .plan files as having that extension, using both dlgs and zenity. Not sure why; filters work when loading
// files. Maybe because .plan files don't have some kind of metadata that identifies them on Mac? Maybe I should just make them
// JSON files; that's what they are, anyway...
if file, err := zenity.SelectFile(zenity.Title("Select MasterPlan Project File")); err == nil && file != "" {
if loadedProject := LoadProject(file); loadedProject != nil {
return loadedProject
}
}
return nil
}
func LoadProject(filepath string) *Project {
project := NewProject()
if fileData, err := ioutil.ReadFile(filepath); err == nil {
data := gjson.Parse(string(fileData))
if data.Get("Tasks").Exists() {
project.JustLoaded = true
if strings.Contains(filepath, BackupDelineator) {
project.FilePath = strings.Split(filepath, BackupDelineator)[0]
} else {
project.FilePath = filepath
}
getFloat := func(name string) float32 {
return float32(data.Get(name).Float())
}
getInt := func(name string) int {
return int(data.Get(name).Int())
}
getString := func(name string) string {
return data.Get(name).String()
}
getBool := func(name string) bool {
return data.Get(name).Bool()
}
project.GridSize = int32(getInt(`GridSize`))
project.CameraPan.X = getFloat(`Pan\.X`)
project.CameraPan.Y = getFloat(`Pan\.Y`)
project.ZoomLevel = getInt(`ZoomLevel`)
project.SampleRate.SetChoice(getString(`SampleRate`))
project.SampleBuffer = getInt(`SampleBuffer`)
project.TaskShadowSpinner.CurrentChoice = getInt(`TaskShadow`)
project.OutlineTasks.Checked = getBool(`OutlineTasks`)
project.BracketSubtasks.Checked = getBool(`BracketSubtasks`)
project.GridVisible.Checked = getBool(`GridVisible`)
project.ShowIcons.Checked = getBool(`ShowIcons`)
project.NumberingSequence.CurrentChoice = getInt(`NumberingSequence`)
project.NumberTopLevel.Checked = getBool(`NumberTopLevel`)
project.PulsingTaskSelection.Checked = getBool(`PulsingTaskSelection`)
project.AutoSave.Checked = getBool(`AutoSave`)
project.SaveSoundsPlaying.Checked = getBool(`SaveSoundsPlaying`)
project.BoardIndex = getInt(`BoardIndex`)
project.LockProject.Checked = getBool(`LockProject`)
project.AutomaticBackupInterval.SetNumber(getInt(`BackupInterval`))
project.AutomaticBackupKeepCount.SetNumber(getInt(`BackupKeepCount`))
project.MaxUndoSteps.SetNumber(getInt(`UndoMaxSteps`))
if project.LockProject.Checked {
project.Locked = true
}
speaker.Init(beep.SampleRate(project.SampleRate.ChoiceAsInt()), project.SampleBuffer)
project.SetSampleRate = project.SampleRate.ChoiceAsInt()
project.LogOn = false
boardNames := []string{}
for _, name := range data.Get(`BoardNames`).Array() {
boardNames = append(boardNames, name.String())
}
for i := 0; i < getInt(`BoardCount`)-1; i++ {
project.AddBoard()
}
for i := range project.Boards {
project.Boards[i].UndoBuffer.On = false // No undoing for the loading process
if i < len(boardNames) {
project.Boards[i].Name = boardNames[i]
}
}
for _, taskData := range data.Get(`Tasks`).Array() {
boardIndex := 0
if taskData.Get(`BoardIndex`).Exists() {
boardIndex = int(taskData.Get(`BoardIndex`).Int())
}
task := project.Boards[boardIndex].CreateNewTask()
task.Deserialize(taskData.String())
}
project.LogOn = true
colorTheme := getString(`ColorTheme`)
if colorTheme != "" {
project.ChangeTheme(colorTheme) // Changing theme regenerates the grid; we don't have to do it elsewhere
}
list := []string{}
existsInList := func(value string) bool {
for _, item := range list {
if value == item {
return true
}
}
return false
}
lastOpenedIndex := -1
i := 0
for _, s := range programSettings.RecentPlanList {
_, err := os.Stat(s)
if err == nil && !existsInList(s) {
// If err != nil, the file must not exist, so we'll skip it
list = append(list, s)
if s == filepath {
lastOpenedIndex = i
}
i++
}
}
if lastOpenedIndex > 0 {
// If the project to be opened is already in the recent files list, then we can just bump it up to the front.
// ABC <- Say we want to move B to the front.
// list = ABC_
list = append(list, "")
// list = AABC
copy(list[1:], list[0:])
// list = BABC
list[0] = list[lastOpenedIndex+1] // Index needs to be +1 here because we made the list 1 larger above
// list = BAC
list = append(list[:lastOpenedIndex+1], list[lastOpenedIndex+2:]...)
} else if lastOpenedIndex < 0 {
list = append([]string{filepath}, list...)
}
programSettings.RecentPlanList = list
programSettings.Save()
project.Log("Load successful.")
for _, b := range project.Boards {
b.UndoBuffer.On = true
}
return project
}
}
// It's possible for the file to be mangled and unable to be loaded; I should actually handle this
// with a backup system or something.
log.Println(fmt.Sprintf("Error: Could not load plan: [ %s ].", filepath))
// We log on the current project because this project didn't load correctly
currentProject.Log("Error: Could not load plan:\n[ %s ].", filepath)
currentProject.Log("Are you sure it's a valid MasterPlan project?")
return nil
}
func (project *Project) Log(text string, variables ...interface{}) {
if project.LogOn {
if len(variables) > 0 {
text = fmt.Sprintf(text, variables...)
}
eventLogBuffer = append(eventLogBuffer, EventLog{time.Now(), text, gween.New(255, 0, 7, ease.InExpo)})
}
}
func (project *Project) HandleCamera() {
wheel := rl.GetMouseWheelMove()
if !project.ContextMenuOpen && !project.ProjectSettingsOpen && !project.TaskOpen {
if wheel > 0 {
project.ZoomLevel += 1
} else if wheel < 0 {
project.ZoomLevel -= 1
}
}
zoomLevels := []float32{0.5, 1, 2, 3, 4}
if project.ZoomLevel == -99 {
project.ZoomLevel = 1
}
if project.ZoomLevel >= len(zoomLevels) {
project.ZoomLevel = len(zoomLevels) - 1
}
if project.ZoomLevel < 0 {
project.ZoomLevel = 0
}
targetZoom := zoomLevels[project.ZoomLevel]
camera.Zoom += (targetZoom - camera.Zoom) * 0.2
if math.Abs(float64(targetZoom-camera.Zoom)) < 0.001 {
camera.Zoom = targetZoom
}
if rl.IsMouseButtonDown(rl.MouseMiddleButton) {
diff := GetMouseDelta()
project.CameraPan.X += diff.X
project.CameraPan.Y += diff.Y
}
project.CameraOffset.X += float32(project.CameraPan.X-project.CameraOffset.X) * 0.2
project.CameraOffset.Y += float32(project.CameraPan.Y-project.CameraOffset.Y) * 0.2
camera.Target.X = float32(-project.CameraOffset.X)
camera.Target.Y = float32(-project.CameraOffset.Y)
camera.Offset.X = float32(rl.GetScreenWidth() / 2)
camera.Offset.Y = float32(rl.GetScreenHeight() / 2)
}
func (project *Project) MousingOver() string {
if rl.CheckCollisionPointRec(GetMousePosition(), project.StatusBar) {
return "StatusBar"
} else if rl.CheckCollisionPointRec(GetMousePosition(), project.BoardPanel) {
return "Boards"
} else if project.TaskOpen {
return "TaskOpen"
} else {
return "Project"
}
}
func (project *Project) Update() {
project.AutoBackup()
if project.ActivePopup == nil {
if project.AutoReloadThemes.Checked && project.ThemeReloadTimer > 30 {
project.ReloadThemes()
project.ThemeReloadTimer = 0
}
project.ThemeReloadTimer++
holdingShift := rl.IsKeyDown(rl.KeyLeftShift) || rl.IsKeyDown(rl.KeyRightShift)
holdingAlt := rl.IsKeyDown(rl.KeyLeftAlt) || rl.IsKeyDown(rl.KeyRightAlt)
src := rl.Rectangle{-100000, -100000, 200000, 200000}
dst := src
rl.DrawTexturePro(project.GridTexture, src, dst, rl.Vector2{}, 0, rl.White)
// Board name on background of project
boardName := project.CurrentBoard().Name
boardNameWidth := GUITextWidth(boardName) + 16
boardNameHeight, _ := TextHeight(boardName, true)
rl.DrawRectangle(1, 1, int32(boardNameWidth), int32(boardNameHeight), getThemeColor(GUI_INSIDE))
DrawGUITextColored(rl.Vector2{8, 0}, getThemeColor(GUI_INSIDE_DISABLED), boardName)
// This is the origin crosshair
rl.DrawLineEx(rl.Vector2{0, -100000}, rl.Vector2{0, 100000}, 2, getThemeColor(GUI_INSIDE))
rl.DrawLineEx(rl.Vector2{-100000, 0}, rl.Vector2{100000, 0}, 2, getThemeColor(GUI_INSIDE))
selectionRect := rl.Rectangle{}
if !project.TaskOpen && !project.ProjectSettingsOpen {
project.CurrentBoard().HandleDroppedFiles()
project.HandleCamera()
var clickedTask *Task
clicked := false
// We update the tasks from top (last) down, because if you click on one, you click on the top-most one.
if rl.IsMouseButtonPressed(rl.MouseLeftButton) && !project.ContextMenuOpen && !project.ProjectSettingsOpen {
clicked = true
}
if project.ResizingImage {
project.Selecting = false
}
if project.MousingOver() == "Project" {
for i := len(project.CurrentBoard().Tasks) - 1; i >= 0; i-- {
task := project.CurrentBoard().Tasks[i]
if rl.CheckCollisionPointRec(GetWorldMousePosition(), task.Rect) && clickedTask == nil {
clickedTask = task
}
}
if project.DoubleClickTimer >= 0 {
project.DoubleClickTimer++
}
if project.DoubleClickTimer >= 20 {
project.DoubleClickTimer = -1
}
if clicked {
if clickedTask == nil {
project.SelectionStart = GetWorldMousePosition()
project.Selecting = true
} else {
project.Selecting = false
if holdingAlt && clickedTask.Selected {
project.Log("Deselected 1 Task.")
} else if !holdingAlt && !clickedTask.Selected {
project.Log("Selected 1 Task.")
}
if holdingShift {
if holdingAlt {
clickedTask.ReceiveMessage(MessageSelect, map[string]interface{}{})
} else {
clickedTask.ReceiveMessage(MessageSelect, map[string]interface{}{
"task": clickedTask,
})
}
} else {
if !clickedTask.Selected { // This makes it so you don't have to shift+drag to move already selected Tasks
project.SendMessage(MessageSelect, map[string]interface{}{
"task": clickedTask,
})
} else {
clickedTask.ReceiveMessage(MessageSelect, map[string]interface{}{
"task": clickedTask,
})
}
}
}
if clickedTask == nil {
if project.DoubleClickTimer > 0 && project.DoubleClickTaskID == -1 {
task := project.CurrentBoard().CreateNewTask()
task.ReceiveMessage(MessageDoubleClick, nil)
project.Selecting = false
}
project.DoubleClickTaskID = -1
project.DoubleClickTimer = 0
} else {
if clickedTask.ID == project.DoubleClickTaskID && project.DoubleClickTimer > 0 && clickedTask.Selected {
clickedTask.ReceiveMessage(MessageDoubleClick, nil)
} else {
project.SendMessage(MessageDragging, nil)
}
project.DoubleClickTimer = 0
project.DoubleClickTaskID = clickedTask.ID
}
}
if project.Selecting {
diff := raymath.Vector2Subtract(GetWorldMousePosition(), project.SelectionStart)
x1, y1 := project.SelectionStart.X, project.SelectionStart.Y
x2, y2 := diff.X, diff.Y
if x2 < 0 {
x2 *= -1
x1 = GetWorldMousePosition().X
}
if y2 < 0 {
y2 *= -1
y1 = GetWorldMousePosition().Y
}
selectionRect = rl.Rectangle{x1, y1, x2, y2}
if rl.IsMouseButtonReleased(rl.MouseLeftButton) && !project.ResizingImage {
project.Selecting = false // We're done with the selection process
count := 0
for _, task := range project.CurrentBoard().Tasks {
inSelectionRect := false
var t *Task
if rl.CheckCollisionRecs(selectionRect, task.Rect) {
inSelectionRect = true
t = task
}
if holdingAlt {
if inSelectionRect {
if task.Selected {
count++
}
task.ReceiveMessage(MessageSelect, map[string]interface{}{"task": t, "invert": true})
}
} else {
if !holdingShift || inSelectionRect {
if (!task.Selected && inSelectionRect) || (!holdingShift && inSelectionRect) {
count++
}
task.ReceiveMessage(MessageSelect, map[string]interface{}{
"task": t,
})
}
}
}
if holdingAlt {
project.Log("Deselected %d Task(s).", count)
} else {
project.Log("Selected %d Task(s).", count)
}
}
}
} else {
if rl.IsMouseButtonReleased(rl.MouseLeftButton) {
project.Selecting = false
}
}
project.CurrentBoard().UndoBuffer.Update()
}
for _, task := range project.GetAllTasks() {
task.Update()
}
// Additive blending should be out here to avoid state changes mid-task drawing.
shadowColor := getThemeColor(GUI_SHADOW_COLOR)
if shadowColor.R > 254 || shadowColor.G > 254 || shadowColor.B > 254 {
rl.BeginBlendMode(rl.BlendAdditive)
}
for _, task := range project.CurrentBoard().Tasks {
task.DrawShadow()
}
if shadowColor.R > 254 || shadowColor.G > 254 || shadowColor.B > 254 {
rl.EndBlendMode()
}
for _, task := range project.CurrentBoard().Tasks {
task.Draw()
}
// This is true once at least one loop has happened
project.FullyInitialized = true
rl.DrawRectangleLinesEx(selectionRect, 1, getThemeColor(GUI_OUTLINE_HIGHLIGHTED))
project.Shortcuts()
if project.JustLoaded {
for _, t := range project.GetAllTasks() {
t.Draw() // We need to draw the task at least once to ensure the rects are updated by the Task's contents.
// This makes it so that neighbors can be correct.
}
project.ReorderTasks()
project.Modified = false
project.JustLoaded = false
}
}
for _, board := range project.Boards {
board.HandleDeletedTasks()
}
if project.Modified && project.AutoSave.Checked {
project.LogOn = false
project.Save(false)
project.LogOn = true
}
}
func (project *Project) AutoBackup() {
if project.AutomaticBackupInterval.GetNumber() == 0 {
if !project.AutomaticBackupInterval.Textbox.Focused {
project.AutomaticBackupInterval.Textbox.SetText("OFF")
}
} else {
if project.BackupTimer.IsZero() {
project.BackupTimer = time.Now()
} else if time.Now().Sub(project.BackupTimer).Minutes() >= float64(project.AutomaticBackupInterval.GetNumber()) && project.FilePath != "" {
dir, _ := filepath.Split(project.FilePath)
existingBackups := []string{}
// Walk the home directory to find
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if path != project.FilePath && strings.Contains(path, project.FilePath) {
existingBackups = append(existingBackups, path)
}
return nil
})
timeFormat := "Jan 2 2006 15:04:05"
if len(existingBackups) > 0 {
sort.Slice(existingBackups, func(i, j int) bool {
dti := strings.Split(existingBackups[i], BackupDelineator)
dateTextI := dti[len(dti)-1]
timeI, _ := time.Parse(timeFormat, dateTextI)
dtj := strings.Split(existingBackups[j], BackupDelineator)
dateTextJ := dtj[len(dtj)-1]
timeJ, _ := time.Parse(timeFormat, dateTextJ)
return timeI.Before(timeJ)
})
}
for i := 0; i < len(existingBackups)-project.AutomaticBackupKeepCount.GetNumber()+1; i++ {
oldest := existingBackups[0]
os.Remove(oldest)
existingBackups = existingBackups[1:]
}
fp := strings.Split(project.FilePath, BackupDelineator)[0]
project.FilePath += BackupDelineator + time.Now().Format(timeFormat)
project.Save(true)
project.BackupTimer = time.Now()
project.FilePath = fp
}
}
}
func (project *Project) SendMessage(message string, data map[string]interface{}) {
taskList := project.GetAllTasks()
for _, task := range taskList {
task.ReceiveMessage(message, data)
}