-
Notifications
You must be signed in to change notification settings - Fork 2
/
tracker.pyw
1612 lines (1506 loc) · 99.5 KB
/
tracker.pyw
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
import tkinter as Tk
import tkinter.font as tkFont
from tkinter import ttk, PhotoImage, messagebox, filedialog, simpledialog
import json
import urllib.request
import webbrowser
from contextlib import contextmanager
import subprocess
import sys
from zipfile import ZipFile
from io import BytesIO
import os
import platform
import shutil
import copy
from typing import Callable, Optional
from datetime import datetime
import calendar
import traceback
if os.name == 'nt': # windows only
import ctypes
class Tracker(Tk.Tk):
CHESTS = ["wood", "silver", "gold", "red", "blue", "purple", "green"] # chest list
RARES = ["bar", "sand", "evolite", "sunlight", "shard"] # rare item
FORBIDDEN = ["version", "last", "settings", "history", "favorites"] # forbidden raid name list
THEME = ["light", "dark", "forest-light", "forest-dark"] # existing themes
DEFAULT_LAYOUT = "[{'tab_image': 'bar', 'text': 'Bars', 'raids': [{'raid_image': 'bhl', 'text': 'BHL', 'loot': ['blue', 'ring3', 'bar']}, {'raid_image': 'akasha', 'text': 'Akasha', 'loot': ['blue', 'ring3', 'bar']}, {'raid_image': 'gohl', 'text': 'Grande', 'loot': ['blue', 'ring3', 'bar']}]}, {'tab_image': 'sand', 'text': 'Sands', 'raids': [{'raid_image': 'ennead', 'text': 'Enneads', 'loot': ['sand']}, {'text': 'M3', 'raid_image': 'm3', 'loot': ['sand']}, {'raid_image': '6d', 'text': '6D', 'loot': ['fireearring', 'sand']}, {'text': 'World', 'raid_image': 'world', 'loot': ['blue', 'world_idean', 'sand']}, {'text': 'Paragon', 'raid_image': 'paragon', 'loot': ['blue', 'sand']}]}, {'tab_image': 'siete', 'text': 'Revans', 'raids': [{'raid_image': 'mugen', 'text': 'Mugen', 'loot': ['blue', 'wpn_mugen', 'wpn_mugen2', 'sand']}, {'raid_image': 'diaspora', 'text': 'Diaspora', 'loot': ['blue', 'wpn_diaspora', 'wpn_diaspora2', 'sand']}, {'raid_image': 'siegfried', 'text': 'Siegfried', 'loot': ['blue', 'wpn_siegfried', 'wpn_siegfried2', 'sand']}, {'raid_image': 'siete', 'text': 'Siete', 'loot': ['blue', 'wpn_siete', 'wpn_siete2', 'sand']}, {'raid_image': 'cosmos', 'text': 'Cosmos', 'loot': ['blue', 'wpn_cosmos', 'wpn_cosmos2', 'sand']}, {'raid_image': 'agastia', 'text': 'Agastia', 'loot': ['blue', 'wpn_agastia', 'wpn_agastia2', 'sand']}]}, {'text': 'End', 'tab_image': 'subaha', 'raids': [{'raid_image': 'subaha', 'text': 'SuBaha', 'loot': ['sand']}, {'raid_image': 'hexa', 'text': 'Hexa', 'loot': ['sand']}, {'text': 'LuciZero', 'raid_image': 'lucizero', 'loot': ['sand']}]}, {'text': 'Others', 'tab_image': 'unknown', 'raids': [{'text': 'GW NM', 'raid_image': 'nm', 'loot': ['wpn_celestial', 'wpn_revenant', 'summon_gw']}]}]"
RAID_TAB_LIMIT = 6
MIN_WIDTH = 240
MIN_HEIGHT = 150
SMALL_THUMB = (20, 20)
BIG_THUMB = (50, 50)
GITHUB = "https://github.com/MizaGBF/GBFLT"
def __init__(self, parent : Optional[Tk.Tk] = None, tracker_directory : Optional[str] = "") -> None: # set the directory to tracker.pyw directory if imported as an external module
Tk.Tk.__init__(self,parent)
self.parent = parent
self.tracker_directory = tracker_directory # to use if the tracker is imported as a module
if __name__ == "__main__" and self.tracker_directory == "":
self.tracker_directory = os.path.dirname(os.path.abspath(sys.argv[0]))
if self.tracker_directory != "" and not self.tracker_directory.endswith('/') and not self.tracker_directory.endswith('\\'):
self.tracker_directory += "/"
self.version = "0.0"
self.python = "3.10"
self.og_raidlayout = True # set to False if the user has modified raids.json
self.stats_window = None # reference to the current stat window
self.import_window = None # reference to the current import window
self.editor_window = None # reference to the current editor window
self.history_window = None # reference to the current history window
errors = self.load_manifest()
savedata, rerrors = self.load_savedata()
errors += rerrors
self.favorites = [] if savedata is None else savedata.get("favorites", [])
self.history = {} if savedata is None else savedata.get("history", {})
self.settings = {} if savedata is None else savedata.get("settings", {})
self.call('source', self.tracker_directory+'assets/themes/main.tcl')
self.call("set_theme", self.settings.get("theme", self.THEME[0]))
self.title("GBF Loot Tracker v" + self.version)
if os.name == 'nt': ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('mizagbf.gbflt.v'+self.version) # for the icon to display on the task bar (Windows)
self.iconbitmap(self.tracker_directory+'assets/icon.ico')
self.resizable(width=False, height=False) # not resizable
self.minsize(self.MIN_WIDTH, self.MIN_HEIGHT)
self.protocol("WM_DELETE_WINDOW", self.close) # call close() if we close the window
self.assets = {} # contains loaded images
self.raid_data = {} # contains the layout
self.got_chest = {} # dict of raid with a chest button, and their chest button name
self.got_rare = {} # set of raid with a bar or sand button
self.last_tab = None # track the last tab used
self.modified = False # if True, need to save
layout, rerrors = self.load_raids()
errors += rerrors
errors += self.verify_layout(layout)
# calculate windows position offset
try:
try: n = "/".join(platform.uname()) # use platform info as an unique identifier (sort of)
except: n = platform.system()+"/"+platform.platform()
if n != self.settings.get('machine', '') or 'offset' not in self.settings: # this way, we recalculate the offset if the user changed machine (as it might differ between windows/linux/etc... versions/themes)
self.settings['machine'] = n
self.settings['offset'] = OffsetTester(self).get_offset() # create a windows at position 100x100, update it, get its new position and retrieve the difference
except:
pass
self.tab_tree = {} # used to memorize the tab structure, to set the active tab after loading
self.top_tab = ttk.Notebook(self, takefocus=False)
for ti, t in enumerate(layout): # top tabs
tab = ttk.Frame(self.top_tab)
self.top_tab.add(tab, text=t.get("text", ""))
self.top_tab.tab(tab, image=self.load_asset("assets/tabs/" + t.get("tab_image", "").replace(".png", "") + ".png", self.SMALL_THUMB), compound=Tk.LEFT)
raid_tabs = ttk.Notebook(tab, takefocus=False)
tab_count = len(t.get("raids", []))
for c, r in enumerate(t.get("raids", [])): # raid tabs
if "text" not in r or r["text"] in self.raid_data:
continue
else:
rn = r["text"]
if rn in self.FORBIDDEN:
continue
else:
self.tab_tree[rn] = (ti, c, raid_tabs)
self.raid_data[rn] = {}
sub = ttk.Frame(raid_tabs)
if tab_count <= self.RAID_TAB_LIMIT: raid_tabs.add(sub, text=rn)
else: raid_tabs.add(sub)
raid_tabs.tab(sub, image=self.load_asset("assets/tabs/" + r.get("raid_image", "").replace(".png", "") + ".png", self.SMALL_THUMB), compound=Tk.LEFT)
self.set_tab_content(sub, r, self.raid_data[rn], True)
raid_tabs.pack(expand=1, fill="both")
# settings
tab = ttk.Frame(self.top_tab)
self.top_tab.add(tab, text="Settings")
self.top_tab.tab(tab, image=self.load_asset("assets/others/settings.png", self.SMALL_THUMB), compound=Tk.LEFT)
self.make_button(tab, "Toggle Theme", self.toggle_theme, 0, 0, 3, "we", ("others", "theme", self.SMALL_THUMB))
self.make_button(tab, "Layout Editor ", self.open_layout_editor, 1, 0, 3, "we", ("others", "layout", self.SMALL_THUMB))
b = self.make_button(tab, "Restart the App", self.restart, 2, 0, 3, "we", ("others", "restart", self.SMALL_THUMB))
if __name__ != "__main__": b.configure(state='disabled')
self.make_button(tab, "Open Statistics", self.stats, 3, 0, 3, "we", ("others", "stats", self.SMALL_THUMB))
self.make_button(tab, "Export to Text", self.export_to_text, 4, 0, 3, "we", ("others", "export", self.SMALL_THUMB))
self.make_button(tab, "What's New? ", self.show_changelog, 5, 0, 3, "we", ("others", "new", self.SMALL_THUMB))
self.make_button(tab, "Credits ", self.show_credits, 6, 0, 3, "we", ("others", "credits", self.SMALL_THUMB))
self.make_button(tab, "Github Repository", self.github_repo, 0, 3, 3, "we", ("others", "github", self.SMALL_THUMB))
self.make_button(tab, "Bug Report ", self.github_issue, 1, 3, 3, "we", ("others", "bug", self.SMALL_THUMB))
b = self.make_button(tab, "Check Updates ", lambda : self.check_new_update(False), 2, 3, 3, "we", ("others", "update", self.SMALL_THUMB))
if __name__ != "__main__": b.configure(state='disabled')
self.make_button(tab, "Shortcut List ", self.show_shortcut, 3, 3, 3, "we", ("others", "shortcut", self.SMALL_THUMB))
self.make_button(tab, "Favorited ", self.show_favorite, 4, 3, 3, "we", ("others", "favorite", self.SMALL_THUMB))
self.make_button(tab, "Import from ", self.import_data, 5, 3, 3, "we", ("others", "import", self.SMALL_THUMB))
# check boxes
self.show_notif = Tk.IntVar()
ttk.Checkbutton(tab, text='Show notifications', variable=self.show_notif, command=self.toggle_notif).grid(row=0, column=6, columnspan=5, sticky="we")
self.show_notif.set(self.settings.get("show_notif", 0))
self.top_most = Tk.IntVar()
ttk.Checkbutton(tab, text='Always on top', variable=self.top_most, command=self.toggle_topmost).grid(row=1, column=6, columnspan=5, sticky="we")
self.top_most.set(self.settings.get("top_most", 0))
if self.settings.get("top_most", 0) == 1:
self.attributes('-topmost', True)
self.check_update = Tk.IntVar()
ttk.Checkbutton(tab, text='Auto Check Updates', variable=self.check_update, command=self.toggle_checkupdate).grid(row=2, column=6, columnspan=5, sticky="we")
self.check_update.set(self.settings.get("check_update", 0))
self.backup_save = Tk.IntVar()
ttk.Checkbutton(tab, text='Backup Save on startup', variable=self.backup_save, command=self.toggle_backup).grid(row=3, column=6, columnspan=5, sticky="we")
self.backup_save.set(self.settings.get("backup_save", 0))
# shortcut
self.set_general_binding(self)
# notification
self.notification = Tk.Label(self, text="")
self.notification_after = None # after callback
if self.settings.get("show_notif", 1) == 1: self.notification.grid(row=1, column=0, sticky="w")
# welcome notification and easter eggs
now = datetime.now()
if now.day == calendar.monthrange(now.year, now.month)[1]: self.push_notif(["Immunity Lily blesses your rolls.", "GOLEM GET YE GONE!"][now.month%2]) # legfest (alternate the messages depending on the month)
elif now.day == 31 and now.month == 10: self.push_notif("Happy Halloween!")
elif now.day == 25 and now.month == 12: self.push_notif("Happy Christmas!")
elif now.day == 1 and now.month == 1: self.push_notif("Happy New Year!")
elif now.day == 14 and now.month == 2: self.push_notif("Happy Valentine!")
elif now.day == 10 and now.month == 3: self.push_notif("Another year on Granblue Fantasy...")
elif now.day == 1 and now.month == 4: self.push_notif("???")
elif now.day == 29 and now.month == 4: self.push_notif("Golden Week is starting!")
elif savedata is None: self.push_notif("First time user? Take a look at the readme!")
else: self.push_notif("May luck be with you.") # random welcome message
# end
if self.check_python(self.python) is False:
errors.append("Your Python version is outdated ({}.{}). Consider uninstalling it for a recent version.".format(sys.version_info.major, sys.version_info.minor))
self.top_tab.grid(row=0, column=0, columnspan=10, sticky="wnes")
if savedata is not None: errors += self.apply_savedata(savedata)
if self.last_tab in self.tab_tree:
t = self.tab_tree[self.last_tab]
self.top_tab.select(t[0]) # select top tab
t[2].select(t[1]) # select sub tab on stored notebook
for rn, v in self.settings.get("detached", {}).items():
self.detach(rn, v)
if len(errors) > 0:
if len(errors) > 6:
tmp = ["And {} more errors...".format(len(errors)-6)]
errors = errors[:6] + tmp
messagebox.showerror("Important", "The following warnings/errors occured during startup:\n- " + "\n- ".join(errors) + "\n\nIt's recommended to close the app and fix those issues, if possible.")
elif self.settings.get("check_update", 0) == 1:
self.check_new_update()
self.last_savedata_string = str(self.get_save_data()) # get current state of the save as a string
self.after(60000, self.save_task)
def set_general_binding(self, widget : Tk.Tk, limit_to : Optional[list] = None) -> None: # set shortcut keys to given widget/window
key_bindings = [
('t', self.key_toggle_topmost),
('s', self.key_toggle_stat),
('l', self.key_toggle_theme),
('n', self.key_toggle_notif),
('e', self.key_open_editor),
('r', self.key_restart),
('u', self.key_update),
('m', self.key_memorize),
('o', self.key_open_memorized),
('c', self.key_close_popups),
]
for k in key_bindings:
if limit_to is None or k[0] in limit_to:
widget.bind('<{}>'.format(k[0]), k[1])
widget.bind('<{}>'.format(k[0].upper()), k[1])
if limit_to is None:
for k in ['<Prior>', '<Next>', '<Left>', '<Right>', '<Up>', '<Down>']: widget.bind(k, self.key_page)
for i in range(1, 13): widget.bind('<Shift-F{}>'.format(i), self.key_set_fav)
for i in range(1, 13): widget.bind('<F{}>'.format(i), self.key_select_fav)
def set_tab_content(self, parent : Tk.Tk, layout : dict, container : dict, is_main_window : bool) -> None: # contruct a tab content (used by popup windows too)
rn = layout["text"]
frame = ttk.Frame(parent)
frame.grid(row=0, column=0)
button = self.make_button(frame, "", None, 0, 0, 1, "w", ("buttons", layout.get("raid_image", ""), self.BIG_THUMB))
button.bind('<Button-1>', lambda ev, btn=button, rn=rn: self.count(btn, rn, "", add=True))
button.bind('<Button-3>', lambda ev, btn=button, rn=rn: self.count(btn, rn, "", add=False))
label = Tk.Label(frame, text="0") # Total label
label.grid(row=1, column=0)
hist = Tk.Label(frame, text="") # History label
hist.grid(row=4, column=3 if is_main_window else 1, columnspan=100, sticky="w")
container[""] = [0, label, hist, frame, layout, None] # the "" key is used for the total. this value contains: total counter, its label, the history label, the tab frame, the container frame, the detach button and the window if open
# check for chest in the list
if is_main_window:
chest = None
for l in layout.get("loot", []):
if l.replace(".png", "") in self.CHESTS:
chest = l
self.got_chest[rn] = chest
break
else:
chest = self.got_chest.get(rn, None)
# texts
Tk.Label(frame, text="Total").grid(row=2, column=0)
Tk.Label(frame, text="Chest" if chest is not None else "").grid(row=3, column=0)
# build button and label list
for i, l in enumerate(layout.get("loot", [])):
if l.endswith(".png"): l = l[:-3] # strip extension to avoid possible weird behaviors
if l in container or l == "" or (l in self.CHESTS and l != chest):
continue
if is_main_window and l in self.RARES:
if rn not in self.got_rare: self.got_rare[rn] = []
self.got_rare[rn].append(l)
button = self.make_button(frame, "", None, 0, i+1, 1, "w", ("buttons", l, self.BIG_THUMB))
button.bind('<Button-1>', lambda ev, btn=button, rn=rn, l=l: self.count(btn, rn, l, add=True))
button.bind('<Button-3>', lambda ev, btn=button, rn=rn, l=l: self.count(btn, rn, l, add=False))
d = [0, None, None] # other buttons got two labels (count and percent)
d[1] = Tk.Label(frame, text="0")
d[1].grid(row=1, column=i+1)
d[2] = Tk.Label(frame, text="0%")
d[2].grid(row=2, column=i+1)
if chest is not None and l != chest:
d.append(Tk.Label(frame, text="0%"))
d[3].grid(row=3, column=i+1)
container[l] = d
if is_main_window:
self.make_button(frame, "0", lambda rn=rn: self.reset(rn), 4, 0, 1, "we", ("others", "reset", self.SMALL_THUMB))
self.make_button(frame, "P", lambda rn=rn: self.detach(rn), 4, 1, 1, "we", ("others", "detach", self.SMALL_THUMB), width=50)
self.make_button(frame, "H", lambda rn=rn: self.show_history(rn), 4, 2, 1, "we", ("others", "history", self.SMALL_THUMB), width=50)
def make_button(self, parent : Tk.Tk, text : str, command : Optional[Callable], row : int, column : int, columnspan : int, sticky : str, asset_tuple : Optional[tuple] = None, width : Optional[int] = None, height : Optional[int] = None) -> Tk.Button: # function to make our buttons. Asset tuple is composed of 3 elements: folder, asset name and a size tuple (in pixels)
if asset_tuple is not None:
asset = self.load_asset("assets/" + asset_tuple[0] + "/" + asset_tuple[1].replace(".png", "") + ".png", asset_tuple[2])
else:
asset = None
button = Tk.Button(parent, image=asset, text=text, compound=Tk.LEFT, command=command, width=width, height=height)
button.grid(row=row, column=column, columnspan=columnspan, sticky=sticky)
return button
def load_asset(self, path : str, size : tuple = None) -> Optional[PhotoImage]: # load an image file (if not loaded) and return it. If error/not found, return None or an empty image of specified size
try:
if path not in self.assets:
self.assets[path] = PhotoImage(file=self.tracker_directory+path)
return self.assets[path]
except:
if size is None:
return None
else:
try:
if '__dummy_photo_image__'+str(size) not in self.assets: # keep a reference or it won't work
self.assets['__dummy_photo_image__'+str(size)] = Tk.PhotoImage(width=size[0], height=size[1])
return self.assets['__dummy_photo_image__'+str(size)]
except Exception as e:
print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
def check_python(self, string) -> Optional[bool]: # check the python version against a version string. Return True if valid, False if outdated, None if error
try:
pver = string.split('.')
if sys.version_info.major != int(pver[0]) or sys.version_info.minor < int(pver[1]):
return False
else:
return True
except:
return None
def verify_layout(self, layout : dict) -> list: # verify the layout for errors
errors = []
raid_data = {}
got_chest = {}
for ti, t in enumerate(layout):
for c, r in enumerate(t.get("raids", [])): # raid tabs
if "text" not in r:
errors.append("Raid '{}' doesn't have a 'Text' value in Tab '{}'".format(c, ti+1))
continue
elif r["text"] in raid_data:
errors.append("Duplicate raid name '{}' in Tab '{}'".format(r["text"], ti+1))
continue
else:
rn = r["text"]
if rn in self.FORBIDDEN:
errors.append("Raid name '{}' is forbidde in Tab '{}'".format(rn, ti+1))
continue
else:
raid_data[rn] = {}
# check for chest in the list
chest = None
for l in r.get("loot", []):
if l.replace(".png", "") in self.CHESTS:
chest = l
got_chest[rn] = chest
break
for i, l in enumerate(r.get("loot", [])):
if l.endswith(".png"): l = l[:-3] # strip extension to avoid possible weird behaviors
if l in raid_data[rn]:
errors.append("Raid {} '{}' in Tab '{}': '{}' is present twice in the loot list".format(c+1, rn, ti+1, l))
continue
elif l == "":
errors.append("Raid {} '{}' in Tab '{}': There is an empty string or an extra slash '/'".format(c+1, rn, ti+1))
continue
elif l in self.CHESTS and l != chest:
errors.append("Raid {} '{}' in Tab '{}': Only one chest button supported per raid".format(c+1, rn, ti+1))
continue
raid_data[rn][l] = None
if len(errors) > 8: errors = errors[:8] + ["And more..."] # limit to 8 error messages
return errors
def key_toggle_topmost(self, ev : Tk.Event) -> None: # shortcut to toggle top most option
self.top_most.set(not self.top_most.get())
self.toggle_topmost()
def key_toggle_stat(self, ev : Tk.Event) -> None: # shortcut to toggle stat window
if self.stats_window is None: self.stats()
else: self.stats_window.close()
def key_toggle_theme(self, ev : Tk.Event) -> None: # shortcut to toggle theme
self.toggle_theme()
def key_toggle_notif(self, ev : Tk.Event) -> None: # shortcut to toggle the notification bar
self.show_notif.set(not self.show_notif.get())
self.toggle_notif()
def key_open_editor(self, ev : Tk.Event) -> None: # shortcut to open the layout editor
self.open_layout_editor()
def key_restart(self, ev : Tk.Event) -> None: # shortcut to restart the app
self.restart()
def key_update(self, ev : Tk.Event) -> None: # shortcut to check for update
self.check_new_update(False)
def key_memorize(self, ev : Tk.Event) -> None: # shortcut to memorize popup positions
memorized = {}
for rname in self.raid_data: # check opened windows and save their positions
if self.raid_data[rname][""][5] is not None:
memorized[rname] = [self.raid_data[rname][""][5].winfo_rootx()-self.settings.get('offset', [0, 0])[0], self.raid_data[rname][""][5].winfo_rooty()-self.settings.get('offset', [0, 0])[1]] # save the positions
if len(memorized) > 0 and messagebox.askquestion(title="Memorize", message="Do you want to save the positions of currently opened Raid popups?\nYou'll then be able to open them anytime using the 'O' key.") == "yes":
self.settings['memorized'] = memorized
self.modified = True
self.push_notif("Popup Layout has been saved.")
def key_open_memorized(self, ev : Tk.Event) -> None: # shortcut to load memorized popup positions
opened = False
for rname, p in self.settings.get('memorized', {}).items():
if rname in self.raid_data:
self.detach(rname, p)
opened = True
if opened:
self.push_notif("Popups have been opened to their saved positions.")
else:
self.push_notif("No Popup Layout saved. Use the 'M' key to save one.")
def key_close_popups(self, ev : Tk.Event) -> None: # shortcut to close opened raid popups
closed = False
for rname in self.raid_data: # check opened windows and save their positions
if self.raid_data[rname][""][5] is not None:
self.raid_data[rname][""][5].close()
closed = True
if closed:
self.push_notif("Popups have been closed.")
def key_page(self, ev : Tk.Event) -> None: # key shortcut to change tabs
top_pos = self.top_tab.index("current")
top_len = len(self.top_tab.winfo_children())
current_tab = self.top_tab.nametowidget(self.top_tab.select()).winfo_children()[0]
if ev.keycode in [33, 38]:
self.top_tab.select((top_pos - 1 + top_len) % top_len)
elif ev.keycode in [34, 40]:
self.top_tab.select((top_pos + 1) % top_len)
if ev.keycode == 37:
if isinstance(current_tab, ttk.Notebook):
sub_pos = current_tab.index("current")
sub_len = len(current_tab.winfo_children())
current_tab.select((sub_pos - 1 + sub_len) % sub_len)
elif ev.keycode == 39:
if isinstance(current_tab, ttk.Notebook):
sub_pos = current_tab.index("current")
sub_len = len(current_tab.winfo_children())
current_tab.select((sub_pos +1) % sub_len)
def key_set_fav(self, ev : Tk.Event) -> None: # set a favorite
while len(self.favorites) < 12: self.favorites.append(None) # set
index = ev.keycode-112
top_pos = self.top_tab.index("current")
current_tab = self.top_tab.nametowidget(self.top_tab.select()).winfo_children()[0]
if isinstance(current_tab, ttk.Notebook):
sub_pos = current_tab.index("current")
for k, v in self.tab_tree.items():
if v[0] == top_pos and v[1] == sub_pos:
self.favorites[index] = k
self.modified = True
self.push_notif("'F{}' key set to '{}'.".format(index+1, k))
return
def key_select_fav(self, ev : Tk.Event) -> None: # load a favorite
index = ev.keycode-112
try:
t = self.tab_tree[self.favorites[index]]
self.top_tab.select(t[0]) # select top tab
t[2].select(t[1]) # select sub tab on stored notebook
except:
pass
def save_task(self) -> None: # run alongside the loop : save and then run again in 60s
self.save()
self.after(60000, self.save_task)
def clean_notif_task(self) -> None: # run alongside the loop: clean the notification bar
try: self.notification.config(text="")
except: pass
def close(self) -> None: # called when we close the window
if "detached" not in self.settings: self.settings['detached'] = {}
for rname in self.raid_data: # check opened windows and save their positions
if self.raid_data[rname][""][5] is not None:
self.settings["detached"][rname] = [self.raid_data[rname][""][5].winfo_rootx()-self.settings.get('offset', [0, 0])[0], self.raid_data[rname][""][5].winfo_rooty()-self.settings.get('offset', [0, 0])[1]] # save their positions
self.raid_data[rname][""][5].close()
self.modified = True
elif rname in self.settings['detached']:
del self.settings['detached'][rname]
self.save() # last save attempt
if self.stats_window is not None: self.stats_window.close()
if self.import_window is not None: self.import_window.close()
if self.editor_window is not None: self.editor_window.close()
if self.history_window is not None: self.history_window.close()
for rname in self.raid_data:
if self.raid_data[rname][""][5] is not None:
self.raid_data[rname][""][5].close()
self.destroy()
def load_raids(self) -> tuple: # load raids.json
errors = []
try:
with open(self.tracker_directory + 'assets/raids.json', mode='r', encoding='utf-8') as f:
data = json.load(f)
if '-debug_raid' in sys.argv: # used to update DEFAULT_LAYOUT
with open(self.tracker_directory + 'debug_raid.txt', mode='w', encoding='utf-8') as g:
g.write(str(data))
print('debug_raid.txt created')
self.og_raidlayout = (str(data) == self.DEFAULT_LAYOUT)
except Exception as e:
data = []
errors = ["Error in raids.json: " + str(e)]
return data, errors
def toggle_checkupdate(self) -> None: # toggle check for update option
self.modified = True
self.settings["check_update"] = self.check_update.get()
def toggle_topmost(self) -> None: # toggle always on top option
self.modified = True
self.settings["top_most"] = self.top_most.get()
if self.settings["top_most"] == 1:
self.attributes('-topmost', True)
if self.stats_window is not None: self.stats_window.attributes('-topmost', True)
if self.import_window is not None: self.import_window.attributes('-topmost', True)
if self.editor_window is not None:
self.editor_window.attributes('-topmost', True)
if self.editor_window.preview is not None: self.editor_window.preview.attributes('-topmost', True)
if self.history_window is not None: self.history_window.attributes('-topmost', True)
for rname in self.raid_data:
if self.raid_data[rname][""][5] is not None:
self.raid_data[rname][""][5].attributes('-topmost', True)
self.push_notif("Windows will always be on top.")
else:
self.attributes('-topmost', False)
if self.stats_window is not None: self.stats_window.attributes('-topmost', False)
if self.import_window is not None: self.import_window.attributes('-topmost', False)
if self.editor_window is not None:
self.editor_window.attributes('-topmost', False)
if self.editor_window.preview is not None: self.editor_window.preview.attributes('-topmost', False)
if self.history_window is not None: self.history_window.attributes('-topmost', False)
for rname in self.raid_data:
if self.raid_data[rname][""][5] is not None:
self.raid_data[rname][""][5].attributes('-topmost', False)
self.push_notif("Windows won't be on top.")
def toggle_notif(self) -> None: # toggle for notifications
self.modified = True
self.settings["show_notif"] = self.show_notif.get()
if self.settings["show_notif"] == 1:
self.notification.grid(row=1, column=0, sticky="w")
self.push_notif("Notifications will appear here.")
else:
self.notification.grid_forget()
def toggle_backup(self) -> None: # toggle save backup
self.modified = True
self.settings["backup_save"] = self.backup_save.get()
def push_notif(self, text : str) -> None: # edit the notification label and reset the counter
self.notification.config(text=text)
if self.notification_after is not None: self.after_cancel(self.notification_after)
self.notification_after = self.after(4000, self.clean_notif_task) # delete after 4s
def toggle_theme(self) -> None: # toggle the theme
try:
for i in range(len(self.THEME)): # search the theme
if self.THEME[i] == self.settings.get("theme", self.THEME[0]):
self.settings["theme"]= self.THEME[(i+1)%len(self.THEME)] # switch to the next one
self.call("set_theme", self.settings["theme"])
self.push_notif("Theme set to '{}'.".format(self.settings["theme"]))
self.modified = True
return
# not found
self.settings["theme"] = self.THEME[-1]
self.toggle_theme()
except Exception as e:
print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
@contextmanager
def button_press(self, button : Tk.Button) -> None: # context used for count(), to activate the button animation when right clicking
button.config(relief=Tk.SUNKEN, state=Tk.ACTIVE)
try:
yield button
finally:
button.after(100, lambda: button.config(relief=Tk.RAISED, state=Tk.NORMAL))
def count(self, button : Tk.Button, rname : str, target : str, add : bool) -> None: # add/substract a value. Parameters: button pressed, raid name, button target (will be empty string if it's the total button) and a boolean to control the addition/substraction
with self.button_press(button):
if rname in self.raid_data:
self.last_tab = rname
cname = self.got_chest.get(rname, None) # chest name
if not add: # only for substraction: take note of total normal item
total_item = 0
for k in self.raid_data[rname]:
if k == "" or k.replace(".png", "") == cname:
pass
else:
total_item += self.raid_data[rname][k][0]
if target != "" and target in self.raid_data[rname]:
# add/sub to item value
if add:
self.raid_data[rname][target][0] += 1
if target in self.RARES: # add new point to history if rare item
self.add_to_history(rname, target, self.raid_data[rname][target][0], self.raid_data[rname][""][0]+1 if rname not in self.got_chest else self.raid_data[rname][self.got_chest[rname]][0]+1)
else:
if (target.replace(".png", "") == cname and self.raid_data[rname][target][0] <= total_item) or self.raid_data[rname][target][0] == 0: return # can't decrease if it's a chest button and its value is equal to total of other items OR if its value is simply ZERO
self.raid_data[rname][target][0] = self.raid_data[rname][target][0] - 1
# chest button editing
if cname is not None and target.replace(".png", "") != cname: # if we haven't pressed the chest button or the total button, we increase the chest value
if cname in self.raid_data[rname]: # check again
if add:
self.raid_data[rname][cname][0] += 1
else:
self.raid_data[rname][cname][0] = max(0, self.raid_data[rname][cname][0] - 1)
# total button editing
if add:
self.raid_data[rname][""][0] += 1
else:
if target == "" and self.raid_data[rname][""][0] <= total_item: return
self.raid_data[rname][""][0] = max(0, self.raid_data[rname][""][0] - 1)
# done
self.modified = True
self.update_raid_ui(rname)
def reset(self, rname : str) -> None: # raid name
if messagebox.askquestion(title="Reset", message="Do you want to reset this tab?") == "yes": #ask for confirmation to avoid accidental data reset
if rname in self.raid_data:
self.last_tab = rname
for k in self.raid_data[rname]:
self.raid_data[rname][k][0] = 0
self.modified = True
self.update_raid_ui(rname)
self.push_notif("Raid '{}' has been reset.".format(rname))
def update_raid_ui(self, rname : str) -> None: # called by count() and reset()
if self.raid_data[rname][""][5] is not None: # update detached window if it exists
for k in self.raid_data[rname]:
self.raid_data[rname][""][5].data[k][0] = self.raid_data[rname][k][0]
self.update_label(rname) # update the labels for this raid
if self.stats_window is not None: self.stats_window.update_data() # update stats window if open
if self.history_window is not None and rname == self.history_window.rname: # update history window is open
self.history_window.update_history()
def detach(self, rname : str, position : Optional[list] = None) -> None: # open popup for specified raid name
if rname in self.raid_data:
if self.raid_data[rname][""][5] is not None:
self.raid_data[rname][""][5].lift()
if position is not None:
self.raid_data[rname][""][5].setPosition(position[0], position[1])
else:
self.raid_data[rname][""][5] = DetachedRaid(self, rname, position)
def show_history(self, rname : str) -> None: # open popup to show the history of the raid
if rname in self.raid_data:
if self.history_window is None:
self.history_window = History(self, rname)
else:
self.history_window.destroy()
self.history_window = History(self, rname)
else:
messagebox.showerror("Error", "History not available for this raid")
def update_label(self, rname : str) -> None: # update the labels of the tab content
if rname in self.raid_data:
self.update_label_sub(rname, self.raid_data[rname])
if self.raid_data[rname][""][5] is not None:
self.update_label_sub(rname, self.raid_data[rname][""][5].data)
def update_label_sub(self, rname : str, data : dict) -> None: # sub routine of update_label: can specify the target raid data
total = data[""][0]
chest_count = 0
if rname in self.got_chest: # get total of chest
chest_count = data[self.got_chest[rname]][0]
data[""][1].config(text="{:,}".format(total))
# update "since the last" label
if rname in self.got_rare:
k = self.got_rare[rname][0]
v = chest_count if rname in self.got_chest else total
r = (self.got_chest[rname] + " chests" if rname in self.got_chest else "battles").capitalize()
if data[k][0] > 0:
try:
h = self.history[rname][k][data[k][0]-1]
if h > 0 and h <= v:
data[""][2].config(text="{} {} since the last {}".format(v-h, r, k.capitalize()))
else:
data[""][2].config(text="")
except:
data[""][2].config(text="")
else:
data[""][2].config(text="")
else:
data[""][2].config(text="")
# update each button values and percentage
for k, v in data.items():
if k == "": continue
i = v[0]
v[1].config(text="{:,}".format(i))
if total > 0:
v[2].config(text="{:.2f}%".format(min(100, 100*float(i)/total)).replace('0%', '%').replace('.0%', '%'))
else:
v[2].config(text="0%")
# chest percentage
if rname in self.got_chest and len(v) == 4:
if chest_count > 0:
v[3].config(text="{:.2f}%".format(min(100, 100*float(v[0])/chest_count)).replace('0%', '%').replace('.0%', '%'))
else:
v[3].config(text="0%")
def cmpVer(self, mver : str, tver : str) -> bool: # compare version strings, True if mver greater or equal, else False
me = mver.split('.')
te = tver.split('.')
for i in range(0, min(len(me), len(te))):
if int(me[i]) < int(te[i]):
return False
elif int(me[i]) > int(te[i]):
return True
return True
def check_new_update(self, silent : bool = True) -> None: # request the manifest file on github and compare the versions
if __name__ != "__main__": return
try:
with urllib.request.urlopen("https://raw.githubusercontent.com/MizaGBF/GBFLT/main/assets/manifest.json") as url:
data = json.loads(url.read().decode("utf-8"))
if "version" in data and self.version != "0.0" and not self.cmpVer(self.version, data["version"]):
if messagebox.askquestion(title="Update", message="An update is available.\nCurrent version: {}\nNew Version: {}\nDo you want to download and install?\n- 'save.json' and 'assets/raids.json' (if modified) will be kept intact and be backed up.\n- Other files will be overwritten.".format(self.version, data["version"])) == "yes":
if self.check_python(data.get("python", "3.10")) is False:
if messagebox.askquestion("Outdated Python", "Your python version is v{}.{}.\nAt least Python v{} is recommended.\nUninstall python and install a more recent version.\nOpen the download page?".format(sys.version_info.major, sys.version_info.minor, data.get("python", "3.10"))) == "yes":
webbrowser.open("https://www.python.org/downloads/", new=2, autoraise=True)
else:
self.auto_update()
elif not silent:
messagebox.showinfo("Update", "GBF Loot Tracker is up-to-date.")
except Exception as e:
print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
if not silent:
messagebox.showerror("Error", "An error occured while checking for new updates.\nCheck your Firewall, Try again later or go to Github and update manually.")
def auto_update(self) -> None:
try:
# backup
try: shutil.copyfile(self.tracker_directory+"assets/raids.json", self.tracker_directory+"assets/raids-backup.json")
except: pass
try: shutil.copyfile(self.tracker_directory+"save.json", self.tracker_directory+"save-backup.json")
except: pass
# download latest
with urllib.request.urlopen(self.GITHUB+"/archive/refs/heads/main.zip") as url:
data = url.read()
# read
with BytesIO(data) as zip_content:
with ZipFile(zip_content, 'r') as zip_ref:
# list files
folders = set()
file_list = zip_ref.namelist()
for file in file_list:
if ".git" in file: continue
folders.add("/".join(file.split('/')[1:-1]))
# make folders (if missing)
for path in folders:
if path == "": continue
os.makedirs(os.path.dirname(self.tracker_directory+(path if path.endswith("/") else path+"/")), exist_ok=True)
# write files
for file in file_list:
if ".git" in file: continue
if file.split("/")[-1] in ["raids.json", "save.json"] or file.endswith("/"): continue
path = "/".join(file.split('/')[1:])
with open(self.tracker_directory+path, mode="wb") as f:
f.write(zip_ref.read(file))
# update raids.json
if self.og_raidlayout: # if unmodified
for file in file_list:
if file.endswith("raids.json"):
path = "/".join(file.split('/')[1:])
with open(self.tracker_directory+path, mode="wb") as f:
f.write(zip_ref.read(file))
break
else:
try:
with open(self.tracker_directory+'assets/raids.json', mode='r', encoding='utf-8') as f:
old = json.load(f)
# list known raids
changes = ""
for file in file_list:
if file.endswith("raids.json"):
# load new json
try:
new = json.loads(zip_ref.read(file).decode('utf-8'))
except:
new = None
if new is not None:
# tab check
for tn in new:
found = False
for i in range(len(old)):
if old[i]["text"] == tn["text"]:
found = True
break
if found: # tab exists
for rn in tn["raids"]:
if rn["text"] not in self.raid_data:
old[i]["raids"].append(copy.deepcopy(rn))
changes += "Adding Raid '{}' to Tab '{}'\n".format(rn["text"], tn["text"])
else: # tab doesn't exist
new_tab = copy.deepcopy(tn)
new_tab["raids"] = []
for rn in tn["raids"]:
if rn["text"] not in self.raid_data:
new_tab["raids"].append(copy.deepcopy(rn))
if len(new_tab["raids"]) > 0:
old.append(new_tab)
changes += "Adding Tab '{}'\n".format(tn["text"])
if changes != "" and messagebox.askquestion(title="Update", message="Some differences have been detected between your 'assets/raids.json' and the one from the latest version:\n" + changes + "\nDo you want to apply those differences to your 'assets/raids.json'?") == "yes":
try:
json.dumps(str(old)) # check for validity
with open(self.tracker_directory+'assets/raids.json', mode='w', encoding='utf-8') as f:
json.dump(old, f, indent=4, ensure_ascii=False)
messagebox.showinfo("Update", "'assets/raids.json' updated.\nUse the Layout Editor to make further modifications.")
except Exception as ee:
print("".join(traceback.format_exception(type(ee), ee, ee.__traceback__)))
messagebox.showerror("Error", "Couldn't update 'assets/raids.json', it has been left untouched:\n" + str(ee))
break
except:
if messagebox.askquestion(title="Update", message="An error occured while attempting to detect differences between your 'assets/raids.json' and the one from the latest version.\nDo you want to replace your 'assets/raids.json' with the new one?") == "yes":
for file in file_list:
if file.endswith("raids.json"):
new = json.loads(zip_ref.read(file).decode('utf-8'))
with open(self.tracker_directory+'assets/raids.json', mode='w', encoding='utf-8') as f:
json.dump(new, f, indent=4, ensure_ascii=False)
break
messagebox.showinfo("Update", "Update successful.\nThe application will now restart.\nIf you need to, you'll find backups of 'save.json' and 'assets/raids.json' near them.")
self.restart()
except Exception as e:
print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
messagebox.showerror("Error", "An error occured while downloading or installing the update:\n" + str(e))
def load_manifest(self) -> list: # load data from manifest.json (only the version number for now)
try:
with open(self.tracker_directory+"assets/manifest.json", mode="r", encoding="utf-8") as f:
data = json.load(f)
self.version = data["version"]
self.python = data["python"]
return []
except Exception as e:
print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
return ["Couldn't read 'assets/manifest.json'"]
def load_savedata(self) -> tuple: # load save.data, return a tuple of the savedata (None if error) and an error list
errors = []
try:
with open(self.tracker_directory+"save.json", mode="r", encoding="utf-8") as f:
savedata = json.load(f)
savedata = self.check_history(savedata)
if not self.cmpVer(self.version, savedata["version"]):
errors.append("Your save data comes from a more recent version. It might causses issues")
if len(errors) == 0 and savedata.get("settings", {}).get("backup_save", 0):
try: shutil.copyfile(self.tracker_directory+"save.json", self.tracker_directory+"save-backup.json")
except Exception as x: errors.append("Error while makine a save.json backup: " + str(x))
return savedata, errors
except Exception as e:
print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
if "No such file or directory" not in str(e):
errors.append("Error while opening save.json: " + str(e))
return None, errors
def check_history(self, savedata : dict) -> dict: # check the history in the savedata and updates it if needed
if 'history' not in savedata:
savedata["history"] = {}
for k, v in savedata.items():
if k in self.FORBIDDEN: continue
for x, y in v.items():
if x in self.RARES:
if k not in savedata["history"]: savedata["history"][k] = {}
if x not in savedata["history"][k]: savedata["history"][k][x] = []
while len(savedata["history"][k][x]) < y: # add data if missing (for prior versions)
savedata["history"][k][x].insert(0, 0)
if len(savedata["history"][k][x]) > y: # remove extra data
savedata["history"][k][x] = savedata["history"][k][x][:y]
return savedata
def add_to_history(self, rname : str, iname : str, val : int, total : int): # add a new point in time to a raid history
if rname not in self.history: self.history[rname] = {}
if iname not in self.history[rname]: self.history[rname][iname] = []
while len(self.history[rname][iname]) < val: self.history[rname][iname].append(0)
self.history[rname][iname][val-1] = total
def apply_savedata(self, savedata : dict) -> list: # set raid labels, etc...
errors = []
missing = False
self.last_tab = savedata.get("last", None)
for k, v in savedata.items(): # set each raid
if k in self.FORBIDDEN: continue
if k in self.raid_data:
for x, y in v.items():
if x in self.raid_data[k]:
self.raid_data[k][x][0] = y
else:
errors.append("Loot '{}' from raid '{}' isn't in use anymore and will be discarded in the next save data.".format(x, k)) # warning
else:
self.history.pop(k, None)
if not missing:
missing = True
errors.append("Raid '{}' isn't in use anymore and will be discarded in the next save data.".format(k)) # warning
self.update_label(k)
return errors
def save(self) -> None: # update save.json
if self.modified:
self.modified = False
savedata = self.get_save_data()
savedata_string = str(savedata)
if savedata_string != self.last_savedata_string:
self.last_savedata_string = savedata_string
try:
with open(self.tracker_directory+"save.json", mode="w", encoding="utf-8") as f:
json.dump(savedata, f)
self.push_notif("Changes have been saved.")
except Exception as e:
print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
messagebox.showerror("Error", "An error occured while saving:\n"+str(e))
def get_save_data(self) -> dict: # build the save data (as seen in save.json) and return it
savedata = {"version":self.version, "last":self.last_tab, "settings":self.settings, "history":self.history, "favorites":self.favorites}
for k, v in self.raid_data.items():
savedata[k] = {}
for x, y in v.items():
savedata[k][x] = y[0]
return savedata
def open_layout_editor(self) -> None: # open assets/layout_editor.pyw
if self.editor_window is not None: self.editor_window.lift()
else: self.editor_window = Editor(self)
def restart(self) -> None: # retsart the app (used to check layout changes)
if __name__ != "__main__": return
try:
self.save()
subprocess.Popen([sys.executable, sys.argv[0]])
self.close()
except Exception as e:
messagebox.showerror("Error", "An error occured while attempting to restart the application:\n"+str(e))
def stats(self) -> None: # open the stats window
if self.stats_window is not None: self.stats_window.lift()
else: self.stats_window = StatScreen(self)
def github_repo(self) -> None: # open the github repo
webbrowser.open(self.GITHUB, new=2, autoraise=True)
self.push_notif("Link opened in your broswer.")
def github_issue(self) -> None: # open the github repo on the issues page
webbrowser.open(self.GITHUB+"/issues", new=2, autoraise=True)
self.push_notif("Link opened in your broswer.")
def show_shortcut(self) -> None: # open shortcut list
messagebox.showinfo("Keyboard Shortcuts", "- T: Toggle the Always on top settings.\n- S: Toggle the Statistics window.\n- L: Toggle the Light and Dark themes.\n- N: Toggle the Notification Bar.\n- E: Open the Layout Editor.\n- R: Restart the application.\n- U: Check for updates.\n- M: Memorize the currently opened Raid Popups positions.\n- O: Open the memorized Raid popups to their saved positions.\n- C: Close all opened Raid popups.\n- Page Up or Up: Go to the top tab on the left.\n- Page Down or Down: Go to the top tab on the right.\n- Left: Go to the raid on the left.\n- Right: Go to the raid on the right.\n- Shit+F1~F12: Set the current raid to the Function Key pressed.\n- F1~F12: Go to the raid associated to this Function key.")
def show_favorite(self) -> None: # favorite list
msg = ""
for i in range(12):
if len(self.favorites) < i+1: self.favorites.append(None)
msg += "F{}: {}\n".format(i+1, self.favorites[i])
msg += "\nUse Shift+F1~F12 on a raid tab to set.\nAnd then the F1~F12 key itself to go quickly to that raid."
messagebox.showinfo("Favorited Raids", msg)
def show_changelog(self) -> None: # display the changelog
changelog = [
"1.66 - Added Venerable Paragon raid in the sand tab.",
"1.65 - (Windows) Fixed application icon not displaying on the task bar.",
"1.64 - Added a new tab for people to put whatever, along with a generic NM raid for Unite and Fight.",
"1.63 - Renamed Celestial Chests to Green chests, for ease of use. Sorry for the inconvenience if you're using it.",
"1.62 - Added Celestial Chests, you can set them via the Layout Editor.",
"1.61 - Added M3 raids.",
"1.60 - Added Lucilius Zero.",
"1.59 - Fixed a possible bug in the auto update process.",
"1.58 - Modified the base layout for future end game raids. Fixed some bugs in the layout editor.",
"1.57 - The World added to the default raid layout."
]
messagebox.showinfo("Changelog - Last Ten versions", "\n".join(changelog))
def show_credits(self) -> None: # show credits
messagebox.showinfo("Credits", "https://github.com/MizaGBF/GBFLT\nAuthor:\n- Mizako\n\nContributors:\n- Zell (v1.6)\n\nTesting:\n- Slugi\n\nVisual Themes:\nhttps://github.com/rdbende/Azure-ttk-theme\nhttps://github.com/rdbende/Forest-ttk-theme")
def export_to_text(self) -> None: # export data to text
today = datetime.now()
report = "GBFLT {} - Loot Data Export\r\n{}\r\n\r\n".format(self.version, today.strftime("%d/%m/%Y %H:%M:%S"))
for k, v in self.raid_data.items():
if v[""][0] == 0: continue
report += "### Raid {:} - {:,} times\r\n".format(k, v[""][0])
cname = self.got_chest.get(k, "")
total = v[cname][0]
for x, y in v.items():
if x == "": continue
report += "- {:} - {:,} times".format(x, y[0])
if x != cname: report += " ({:.2f}%)".format(100*y[0]/total).replace('0%', '%').replace('.0%', '%')
report += "\r\n"
if k in self.history:
add = ""
for x, y in self.history[k].items():
if len(y) == 0: continue
add += "- {} at: ".format(x)
for e in y:
if e <= 0: add += "?, "
else: add += "{}, ".format(e)
add = add[:-2]
add += "\r\n"
if add != "":
report += "Drop History:\r\n" + add
report += "\r\n"
with open(self.tracker_directory+"drop_export_{}.txt".format(today.strftime("%m-%d-%Y_%H-%M-%S.%f")), mode="w", encoding="utf-8") as f:
f.write(report)
messagebox.showinfo("Info", "Data exported to: drop_export_{}.txt".format(today.strftime("%m-%d-%Y_%H-%M-%S.%f")))
def import_data(self) -> None: # import data from other trackers
if self.import_window is not None: self.import_window.lift()
else: self.import_window = ImportDial(self)
class ImportDial(Tk.Toplevel):
def __init__(self, parent : Tracker) -> None:
# window
self.parent = parent
Tk.Toplevel.__init__(self,parent)
self.title("GBF Loot Tracker - Data Import")
self.resizable(width=False, height=False) # not resizable
self.minsize(self.parent.MIN_WIDTH, self.parent.MIN_HEIGHT)
self.iconbitmap(self.parent.tracker_directory+'assets/icon.ico')
if self.parent.settings.get("top_most", 0) == 1:
self.attributes('-topmost', True)
Tk.Label(self, text="You can import some raid data from other similar trackers.").grid(row=0, column=0, columnspan=10, sticky="w")
Tk.Button(self, text="'Gold-Bar-Tracker'", command=lambda : self.import_data(0)).grid(row=1, column=0, columnspan=10, sticky="we") # only this one so far
Tk.Label(self, text="Your tracker missing? Please notify us.").grid(row=10, column=0, columnspan=10, sticky="w")
def import_data(self, sid : int) -> None: # importer
if sid == 0: # DYDK GBTracker
messagebox.showinfo("Info", "Please select 'data.json' to import the data.\nIts content will be added to your existing data.\nCancel or Backup your 'save.json' if you're uncertain.")
path = filedialog.askopenfilename()
if path != "":
try:
with open(path, mode="r", encoding="utf-8") as f:
data = json.load(f)
matching_table = {
"pbhl": "BHL",