-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
5239 lines (5046 loc) · 233 KB
/
main.py
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
# disable pygame startup prompt
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = 'hide'
import interaction
import config
import pygame
import debug
import SQL
import encryption
import startup
from controls import controls
from searches import GetTagMostSimilar, SplitByCharacters, FormatImportTags, StrictSearch, WeightedSearch, ExtremeSearch, Operators, FormatResultsToHTML
from vectors import Vector2D
from interface import ScalePosition, Entry, Button, Label, Container, FunctionalEntry, AdvancedLabel, CheckButton, CacheButton, Rectangle
from interface import HoverButton, UnfocusEntry, ConstantFunctionalEntry, RegulatedContainer, ScrollingRegulatedContainer, ImageElement, RatingsBar
from interface import SearchBar
from components import StaticComponent, ScrollComponent
from fnmatch import filter as WildcardMatch
from time import time as CurrentTime
from enum import Enum
class ComponentID(Enum):
LOADUP = 1
MAIN = 2
TAG_LIST = 3
TAG_FIRST_BAR = 4
TAG_SECOND_BAR = 5
TAG_THIRD_BAR = 6
TAG_FOURTH_BAR = 7
TAG_FADE_LAYER = 8
TAG_ADD = 9
TAG_EDIT = 10
TAG_CHANGE_EXIT = 11
TAG_ADD_SUGGESTIONS = 12
TAG_ADD_SYNONYMS = 13
ITEM_FIRST_BAR = 14
ITEM_SECOND_BAR = 15
ITEM_LIST = 16
ITEM_ADD = 17
ITEM_ADD_TAGS = 18
ITEM_ADD_FADE_LAYER = 19
SEARCH = 20
SEARCH_RESULT = 21
ERROR = 1000 # temp TODO change
ERROR_FADE_LAYER = 1001 # temp TODO change
ITEM_ADD_TAGS_ADD = 1002 # temp TODO change
ITEM_ADD_TAGS_ADD_EXIT = 1003 # temp TODO change
ITEM_ADD_TAGS_ADD_SUGGESTIONS = 1004 # temp TODO change
ITEM_ADD_TAGS_ADD_SYNONYMS = 1005 # temp TODO change
NOTIFICATION = 10000 # temp TODO change
def MakeElementEqualSize(text, font, target_size):
text_size = Vector2D(font.size(text))
return (target_size - text_size) / 2
def RemoveStringFromList(data, remove):
to_remove = []
for item in data:
if item == remove:
to_remove.append(item)
for item in to_remove:
data.remove(item)
def CharactersInString(characters, string):
for character in characters:
if character in string:
return True
return False
class MenuConstructor:
# a seperate class to avoid the use of mass global variables
def __init__(self):
self.font_size = 0.02 * config.settings["window_height"] / 0.6876
self.standard_ui_font = pygame.font.SysFont(config.settings["font"],
int(self.font_size))
self.medium_large_ui_font = pygame.font.SysFont(
config.settings["font"], int(self.font_size * 1.5))
self.larger_ui_font = pygame.font.SysFont(config.settings["font"],
int(self.font_size * 1.7))
self.large_ui_font = pygame.font.SysFont(config.settings["font"],
int(self.font_size * 2))
self.smaller_title_ui_font = pygame.font.SysFont(
config.settings["title_font"], int(self.font_size * 3.5))
self.title_ui_font = pygame.font.SysFont(config.settings["title_font"],
int(self.font_size * 5))
self.standard_padding = Vector2D(self.font_size // 5,
self.font_size // 5)
self.wider_padding = Vector2D(self.font_size // 5 * 2,
self.font_size // 5)
self.larger_padding = Vector2D(self.font_size // 2,
self.font_size // 2)
self.very_wide_padding = Vector2D(self.font_size, self.font_size // 5)
self.large_padding = Vector2D(self.font_size, self.font_size)
self.extremely_wide_padding = Vector2D(self.font_size * 4,
self.font_size // 2)
self.standard_outline_size = Vector2D(self.font_size // 10,
self.font_size // 10)
self.cli_commands = {
"help": self.CLIHelp,
"tag add": self.CLIAddTag,
"tag import": self.CLIImportTags,
"tag export": self.CLIExportTags,
"tag search": self.CLISearchTags,
"tag view": self.CLIViewTag,
"tag edit": self.CLIEditTag,
"tag remove": self.CLIRemoveTag,
"tag delete": self.CLIRemoveTag,
"quit": self.CLIQuit,
"font": self.CLIFontChange,
"cls": self.CLIClear,
"clear": self.CLIClear,
"yes": self.CLIConfirm,
"y": self.CLIConfirm,
"no": self.CLIDeny,
"n": self.CLIDeny,
"stop": self.CLIDeny
}
self.file_dialog_used = False
self.disallowed_characters = {
"*": "asterisks",
"&": "ampersands",
"|": "vertical pipes",
"!": "exclamations",
"~": "tildes",
"^": "carats",
"(": "brackets",
")": "brackets",
"+": "pluses"
}
self.disallowed_phrases = [
"addweight", "calcweight", "and", "not", "or", "xor"
]
def ConstructStartMenus(self, window):
self.CreateLoadupMenu(window)
debug.Log("Startup menu constructed successfully.")
def ConstructMenus(self, window):
self.ConstructFadeRectangle()
self.CreateMainMenu(window)
self.CreateTagsMenu(window)
self.CreateTagAdditionMenu(window)
self.CreateTagEditMenu(window)
self.CreateErrorMenu(window)
self.CreateNotificationMenu(window)
self.CreateItemsMenu(window)
self.CreateItemChangeMenu(window)
self.CreateSearchesMenu(window)
self.CreateSearchResultMenu(window)
debug.Log("All menus constructed successfully.")
def ChangeFade(self, new_fade):
self.fade_rectangle.colour = (0, 0, 0, new_fade)
self.fade_rectangle.UpdateImageColour()
def ConstructFadeRectangle(self):
self.fade_rectangle = Rectangle(config.settings["window_size"],
(0, 0, 0, 0))
def FinishStartup(self, window):
encryption.CreateCiphers(config.settings["key"])
SQL.LoadDatabase(config.settings["db_location"])
self.ConstructMenus(window)
self.loadup_component.AddCommands({"TYPE": "UPDATE BACKGROUND"}, {
"TYPE":
"TRANSITION",
"TRANSITIONS":
[{
"ELEMENTS": self.loadup_component.tab_list[0],
"STYLE": 25,
"TIME": 1,
"DELAY": 0,
"TYPE": "LEAVING",
"POST_ARGS": [{
"TYPE": "LEAVE",
"ID": ComponentID.LOADUP.value
}]
}, {
"ELEMENTS": self.loadup_component.tab_list[1],
"STYLE": 24,
"TIME": 1,
"DELAY": 0,
"TYPE": "LEAVING"
}, {
"ELEMENTS": self.loadup_start_button,
"STYLE": 1,
"TIME": 1,
"DELAY": 0.3,
"TYPE": "LEAVING"
}, {
"ELEMENTS": ComponentID.MAIN.value,
"STYLE": 1,
"TIME": 1,
"DELAY": 0.5,
"TYPE": "JOINING"
}]
})
def CreateLoadupMenu(self, window):
self.loadup_component = StaticComponent(
Vector2D(0, 0), config.settings["window_size"],
config.settings["background_colour"])
db_entry = Entry(self.larger_ui_font,
config.settings["window_width"] * 2 // 3,
padding=self.wider_padding,
outline_size=self.standard_outline_size,
empty_text="Enter location")
db_entry.position = ScalePosition(Vector2D(0, 0),
self.loadup_component.size,
Vector2D(0.5, 0.3), db_entry.size)
key_entry = Entry(self.larger_ui_font,
config.settings["window_width"] * 2 // 3,
padding=self.wider_padding,
outline_size=self.standard_outline_size,
empty_text="Enter key",
hide_text=True)
key_entry.position = ScalePosition(Vector2D(0, 0),
self.loadup_component.size,
Vector2D(0.5, 0.5), key_entry.size)
self.loadup_start_button = Button(
"Start",
self.large_ui_font,
target=startup.GetKey,
arguments=[self.loadup_component, self.FinishStartup, window],
padding=self.wider_padding,
outline_size=self.standard_outline_size,
background_colour=(150, 150, 150))
self.loadup_start_button.position = ScalePosition(
Vector2D(0, 0), self.loadup_component.size, Vector2D(0.5, 0.7),
self.loadup_start_button.size)
self.loadup_component.AddUIElements(db_entry, key_entry,
self.loadup_start_button)
self.loadup_component.tab_list = [db_entry, key_entry]
window.AddComponent(self.loadup_component, ComponentID.LOADUP.value,
True, True)
debug.Log("Menu #1 loaded correctly.")
def PrintToCLI(self, text):
self.command_line_output.text += '\n' + text
def CLIHelp(self, command):
for line in [
"\nHELP", "-------",
"help - Provides help list for available commands",
"tag add x - Adds a new tag to the database. See 'tag add help' for more",
"tag import x - Imports & adds multiple tags. See 'tag import help' for more",
"tag export x - Exports all existing tags. See 'tag export help' for more",
"tag search x - Search for tags. See 'tag search help' for more",
"tag view x - View a tag's information. See 'tag view help' for more",
"tag edit x - Edit and update a tag's details. See 'tag edit help' for more",
"tag remove x - Remove a tag. See 'tag remove help' for more",
"font x - Changes the command line font to the font named x",
"clear / cls - Clears the command line output",
"quit - Quit the program",
"More commands are currently under development."
]:
self.PrintToCLI(line)
def CLIAddTag(self, command):
try:
command = command.strip()
tag_data = command.split(" ")[2:]
RemoveStringFromList(tag_data, '')
if tag_data[0].lower() == "help":
self.PrintToCLI(
"\nEnter a tag in the following format:" +
'\n > tag add [name] "[description]" ([synonym1], [synonym2], ...) '
+ "\nFor example, entering" +
'\n > tag add one "The number 1." (1, number_one, the_number_one)'
+
"\nwould add a tag with the name 'one', a description 'The number 1.', and"
+ "\nthe synonyms '1', 'number_one' and 'the_number_one'.")
return
name = tag_data[0].lower()
desc = SplitByCharacters(command, ["'", '"'])
if len(desc) == 3:
desc = desc[1]
elif len(desc) == 2:
self.PrintToCLI(
"That input was not understood. Maybe you forgot to close the"
+ "\nquotation on your description?")
return
elif len(desc) == 1:
desc = ''
else:
self.PrintToCLI(
"That input was not understood. Look at 'tag add help' for more"
+ "\ninformation.")
return
synonym_text = SplitByCharacters(
command, ["(", "[", "{", "<", ")", "]", "}", ">"])
if len(synonym_text) == 3:
synonym_text = synonym_text[1]
elif len(synonym_text) == 2:
self.PrintToCLI(
"That input was not understood. Maybe you forgot to close the"
+ "\nparentheses around your synonyms?")
return
elif len(synonym_text) == 1:
synonym_text = ''
else:
self.PrintToCLI(
"That input was not understood. Look at 'tag add help' for more"
+ "\ninformation.")
return
split_text = synonym_text.split(",")
synonyms = []
for s in split_text:
s = s.strip(" ")
if len(s) > 0 and s not in synonyms:
synonyms.append(s)
self.PrintToCLI(
"Here is the information for the tag you entered:" +
"\nNAME: {}".format(name) + "\nDESCRIPTION: {}".format(desc) +
"\nSYNONYMS: {}".format(", ".join(synonyms)) +
"\nDo you wish to add a tag with this information?")
self.cli_history = [
self.AttemptAddNewTag,
[name, desc, synonyms, [self.main_menu_component, [2]], False],
self.PrintToCLI, ["Tag addition process aborted."]
]
debug.Log('Attempted to add a new tag through the CLI.')
except:
self.PrintToCLI(
"That input was not understood. Look at 'tag add help' for more"
+ "\ninformation.")
def CLIImportTags(self, command):
command = command.strip()
import_data = command.split(" ")[2:]
if len(import_data) == 0:
self.PrintToCLI(
"That input was not understood. Look at 'tag import help' for"
+ "\nmore information.")
return
if import_data[0].lower() == "help":
self.PrintToCLI(
"\nImport tag data from a given file in the following format:"
+ '\n > tag import [path to file] ' +
'\nImport tag data from a file you can manually select using:'
+ '\n > tag import file' +
'\nImport tag data from your clipboard by typing either of:' +
'\n > tag import clipboard' + '\n > tag import paste' +
'\nOr import tag data directly by directly entering the data:'
+ '\n > tag import [data]')
elif import_data[0].lower() in ["clipboard", "paste"]:
self.ImportTagsFromClipboard()
debug.Log(
"Attempted to import tags from the clipboard through the CLI.")
elif import_data[0].lower() in ["file", "choose"]:
self.ImportTagsFromFile()
debug.Log("Attempted to import tags from a file through the CLI.")
elif command.endswith(".CVAL") or command.endswith(".txt"):
file_path = "".join(import_data)
self.ImportTagsFromFile(filename=file_path)
debug.Log("Attempted to import tags from a file through the CLI.")
else:
self.AttemptTagImport("".join(import_data))
debug.Log("Attempted to import tags directly from the CLI.")
def CLIExportTags(self, command):
command = command.strip()
export_data = command.split(" ")[2:]
if len(export_data) == 0:
self.PrintToCLI(
"That input was not understood. Look at 'tag export help' for"
+ "\nmore information.")
return
if export_data[0].lower() == "help":
self.PrintToCLI(
"\nExport tag data to a given file in the following format:" +
'\n > tag export [path to file] ' +
'\nExport tag data from a file you can manually select using:'
+ '\n > tag export file' +
'\nExport tag data from your clipboard by typing either of:' +
'\n > tag export clipboard' + '\n > tag export copy')
elif export_data[0].lower() in ["clipboard", "copy"]:
self.ExportTagsToClipboard()
debug.Log(
"Attempted to export tags to the clipboard through the CLI.")
elif export_data[0].lower() in ["file", "choose"]:
self.ExportTagsToFile()
debug.Log("Attempted to export tags to a file through the CLI.")
elif command.endswith(".CVAL") or command.endswith(".txt"):
file_path = "".join(export_data)
self.ExportTagsToFile(filename=file_path)
debug.Log("Attempted to export tags to a file through the CLI.")
else:
self.PrintToCLI(
"That input was not understood. Look at 'tag export help' for"
+ "\nmore information.")
def CLISearchTags(self, command):
command = command.strip()
tag_data = command.split(" ")[2:]
if len(tag_data) == 0:
self.PrintToCLI(
"That input was not understood. Look at 'tag search help' for"
+ "\nmore information.")
return
if tag_data[0].lower() == "help":
self.PrintToCLI(
"\nSearch for a tag in the following format:" +
'\n > tag search [query] [distance] ' +
'\nWhere the query is just the term you are searching with, and distance'
+
'\nis an integer from 0 to 100 (inclusive) indicating threshold similarity.'
+
'\n0 is no similarity and 100 is high similarity. You can also leave it blank:'
+ '\n > tag search [query]' +
'\nA distance of around 60 is recommended.' +
'\nCheck \'tag view help\' if you want to see more information about a tag.'
)
return
query = tag_data[0].lower()
if len(tag_data) > 1:
try:
distance = int(tag_data[1])
except:
self.PrintToCLI(
"That input was not understood. Make sure your entered" +
"\ndistance is an integer from 0-100. See 'tag search help' for more."
)
return
else:
distance = config.settings["levenshtein_search_threshold"]
if len(query) == 0:
self.PrintToCLI("No matches found.")
return
matches = GetTagMostSimilar(query, SQL.GetTagNames())
tags = sorted(list(matches), key=lambda k: matches[k], reverse=True)
for i, tag in enumerate(tags):
if matches[tag] < distance:
tags = tags[:i]
break
debug.Log(
f'Searched for tags through the CLI. {len(tags)} matches found.')
if len(tags) == 0:
self.PrintToCLI("No matches found.")
return
to_print = f'{len(tags)} matches found:'
for i, tag in enumerate(tags):
to_print += f'\n{i+1}: {tag}'
self.PrintToCLI(to_print)
def CLIViewTag(self, command):
command = command.strip()
tag_data = command.split(" ")[2:]
RemoveStringFromList(tag_data, '')
if len(tag_data) == 0:
self.PrintToCLI(
"That input was not understood. Look at 'tag view help' for" +
"\nmore information.")
return
if tag_data[0].lower() == "help":
self.PrintToCLI(
"\nView the information about a certain tag by using the following:"
+ '\n > tag view [tag name] ' + '\nYou can also use:' +
'\n > tag view [synonym]' +
'\nwhich will then attempt to find the tag based on its synonyms.'
+ '\nYou may also find the \'tag search\' command useful.')
return
name = "_".join(tag_data)
data = SQL.GetTagData(name)
debug.Log("Attempted to view a tag through the CLI.")
if data == None:
data = SQL.GetTagDataFromSynonym(name)
if data == None:
self.PrintToCLI(
"That tag/synonym could not be found. Look at 'tag view help'"
+ "\nfor more information.")
return
self.PrintToCLI("\n NAME: {}".format(data["NAME"]) +
"\n DESCRIPTION: {}".format(data["DESCRIPTION"]) +
"\n SYNONYMS: {}".format(", ".join(data["SYNONYMS"])))
def CLIEditTag(self, command):
try:
command = command.strip()
tag_data = command.split(" ")[2:]
RemoveStringFromList(tag_data, '')
if len(tag_data) == 0:
self.PrintToCLI(
"That input was not understood. Look at 'tag edit help' for"
+ "\nmore information.")
return
if tag_data[0].lower() == "help":
self.PrintToCLI(
"\nEdit the information about a certain tag by using the following:"
+
'\n > tag edit [name] [new name] "[description]" ([synonym1], [synonym2], ...) '
+
'\nIf you don\'t know a tag\'s name but know a synonym see \'tag view help\'.'
+
'\nUse * in any field (but name) to indicate that it should stay unchanged:'
+ '\n > tag edit example * "Hello" *' +
'\nFor example will change the "example" tag\'s description to \'Hello\'.'
+
'\nYou can also put * as one of the synonyms to keep all current synonyms:'
+ '\n> tag edit example2 * * (*, syn_1, syn_2)' +
'\nFor example keeps all old synonyms and adds \'syn_1\' and \'syn_2\'.'
)
return
if len(tag_data) == 3 and tag_data[2].strip() == "*":
self.PrintToCLI(
"Sorry, inputs in the form" +
"\n > tag edit [current name] [name] *" +
"\ncannot be understood. This is because it could be interpreted"
+
"\nas either the description or synonyms being left empty. Try"
+ "\nusing either of the following formats instead:" +
"\n > tag edit [current name] [name] (*) <no description>"
+
"\n > tag edit [current name] [name] * () <no synonyms>"
)
return
name = tag_data[0].lower()
current_data = SQL.GetTagData(name)
if current_data == None:
self.PrintToCLI(
"That tag could not be found. You might want to try the 'tag view' command."
+ "\nSee 'tag edit help' for more information.")
return
new_name = tag_data[1].lower()
if "*" in new_name:
new_name = name
if "*" in tag_data[2] and not CharactersInString(
["(", "[", "{", "<", ")", "]", "}", ">"],
tag_data[2]): # if in desription
desc = current_data["DESCRIPTION"]
else:
desc = SplitByCharacters(command, ["'", '"'])
if len(desc) == 3:
desc = desc[1]
elif len(desc) == 2:
self.PrintToCLI(
"That input was not understood. Maybe you forgot to close the"
+ "\nquotation on your description?")
return
elif len(desc) == 1:
desc = ''
else:
self.PrintToCLI(
"That input was not understood. Look at 'tag edit help' for more"
+ "\ninformation.")
return
synonym_text = SplitByCharacters(
command, ["(", "[", "{", "<", ")", "]", "}", ">"])
if "*" in tag_data[-1] and len(synonym_text) == 1:
# we have to check length to avoid catching cases like 'synonyms = (1, 2, 3, *)'
synonyms = current_data["SYNONYMS"]
else:
if len(synonym_text) == 3:
synonym_text = synonym_text[1]
elif len(synonym_text) == 2:
self.PrintToCLI(
"That input was not understood. Maybe you forgot to close the"
+ "\nparentheses around your synonyms?")
return
elif len(synonym_text) == 1:
synonym_text = ''
else:
self.PrintToCLI(
"That input was not understood. Look at 'tag edit help' for more"
+ "\ninformation.")
return
split_text = synonym_text.split(",")
synonyms = []
for s in split_text:
s = s.strip(" ")
if len(s) > 0 and s not in synonyms:
if s == "*":
for synonym in current_data["SYNONYMS"]:
if synonym not in synonyms:
synonyms.append(synonym)
else:
synonyms.append(s)
debug.Log("Attempted to edit a tag through the CLI.")
self.PrintToCLI(
"Here is the current information for the tag:" +
"\n NAME: {}".format(name) +
"\n DESCRIPTION: {}".format(current_data["DESCRIPTION"]) +
"\n SYNONYMS: {}".format(", ".join(current_data["SYNONYMS"])) +
"\nHere is the edited information for the tag:" +
"\n NAME: {}".format(new_name) +
"\n DESCRIPTION: {}".format(desc) +
"\n SYNONYMS: {}".format(", ".join(synonyms)) +
"\nDo you wish to update the tag with this information?")
self.cli_history = [
self.AttemptUpdateTag,
[
name, current_data["SYNONYMS"], new_name, desc, synonyms,
[self.main_menu_component, [2]], False
], self.PrintToCLI, ["Tag editing process aborted."]
]
except:
self.PrintToCLI(
"That input was not understood. Look at 'tag edit help' for more"
+ "\ninformation.")
def CLIRemoveTag(self, command):
command = command.strip()
tag_data = command.split(" ")[2:]
if len(tag_data) == 0:
self.PrintToCLI(
"That input was not understood. Look at 'tag remove help' for"
+ "\nmore information.")
return
if tag_data[0].lower() == "help":
self.PrintToCLI(
"\nRemove a tag by issuing a command in the following format:"
+ '\n > tag remove [name]' +
'\nIf you don\'t know a tag\'s name but know a synonym see \'tag view help\'.'
+
'\nIf you are trying to find a specific tag, see \'tag search help\'.'
)
return
name = tag_data[0].lower()
tags = SQL.GetTagNames()
if name in tags:
SQL.RemoveTag(name)
self.AddNotification("Tag deleted successfully")
debug.Log("Removed a tag through the CLI.")
else:
self.AddNotification("Tag deletion failed")
debug.Log("Failed to remove a tag through the CLI.")
self.PrintToCLI(
"That tag could not be found. Look at 'tag remove help' for" +
"\nmore information")
def CLIConfirm(self, command):
if len(self.cli_history) > 0:
debug.Log(
"Decided to continue with their previous descision in the CLI."
)
self.cli_history[0](*self.cli_history[1])
else:
self.PrintToCLI(
"Unknown Command. Type 'help' to show a list of available commands."
)
def CLIDeny(self, command):
if len(self.cli_history) > 0:
debug.Log(
"(CLI) Decided to abort their previous decision in the CLI.")
self.cli_history[2](*self.cli_history[3])
else:
self.PrintToCLI(
"Unknown Command. Type 'help' to show a list of available commands."
)
def CLIQuit(self, command):
if command.lower() == "quit help":
self.PrintToCLI(
"Typing 'quit' into the interface will quit the program.")
else:
debug.Log("Typed 'quit' into the CLI.")
self.main_menu_component.AddCommand({"TYPE": "STOP"})
def CLIFontChange(self, command):
try:
font_name = "".join(command.lower().strip().split(" ")[1:])
if font_name == 'default':
font_name = config.settings["font"]
elif font_name == 'help':
self.PrintToCLI(
"Typing 'font x' (where x is the name of a font, e.g. 'font comicsansms') will\nchange the command line interface's font to the specified font."
)
return
if font_name not in pygame.font.get_fonts():
self.PrintToCLI(
"That font could not be found. Type 'font help' for more.")
return
new_font = pygame.font.SysFont(font_name, int(self.font_size))
self.command_line_entry.font = new_font
self.command_line_entry.UpdateText()
self.command_line_entry.UpdateImage()
self.command_line_output.font = new_font
self.command_line_output.UpdateImage()
self.PrintToCLI("Font applied.")
debug.Log(f'Applied new font {font_name} through the CLI.')
except:
self.PrintToCLI(
"That font could not be applied. Type 'font help' for more.")
def CLIClear(self, command):
self.command_line_output.text = ''
self.command_line_output.current_scroll = 0
self.command_line_output.UpdateImage()
debug.Log("Cleared the CLI.")
def UpdateCommandLineOutput(self, data):
if len(data) > 100:
display_data = data[:100] + "..."
else:
display_data = data
if len(self.command_line_output.text) == 0:
self.command_line_output.text += f' > {display_data}'
else:
self.PrintToCLI(f"\n > {display_data}")
input_command = data.lower().strip()
for command in self.cli_commands:
if input_command.startswith(command):
self.cli_commands[command](data)
return
# only run if no other commands matched
self.PrintToCLI(
"Unknown Command. Type 'help' to show a list of available commands."
)
def CreateMainMenu(self, window): # 2
self.main_menu_component = StaticComponent(
Vector2D(0, 0), config.settings["window_size"], (0, 0, 0, 0))
title_size = Vector2D(int(config.settings["window_width"] // 5 * 3.5),
config.settings["window_width"] // 5)
title_image = pygame.transform.scale(
pygame.image.load('gui\\images\\Title.png'), tuple(title_size))
title = ImageElement(title_image)
title.position = ScalePosition(Vector2D(0, 0),
self.main_menu_component.size,
Vector2D(0.5, 0.15), title_size)
version_label = Label(config.version,
self.standard_ui_font,
text_colour=(150, 150, 150))
version_label.position = ScalePosition(Vector2D(0, 0),
self.main_menu_component.size,
Vector2D(0,
0), version_label.size,
Vector2D(0, 0))
version_label.position.x += self.standard_padding.x
button_container = RegulatedContainer(
1, 4, Vector2D(0, 0),
Vector2D(0, self.main_menu_component.height // 30))
button_size = Vector2D(self.main_menu_component.width // 4,
self.main_menu_component.height // 10)
outline_size = Vector2D(self.main_menu_component.width // 400,
self.main_menu_component.width // 400)
self.main_tags_button = Button(
"Tags",
self.large_ui_font,
target=self.main_menu_component.AddCommands,
arguments=[{
"TYPE": "JOIN",
"ID": ComponentID.TAG_LIST.value,
}, {
"TYPE":
"MOVE",
"ID":
ComponentID.TAG_LIST.value,
"POSITION":
Vector2D(0, config.settings["window_height"] // 7)
}, {
"TYPE": "DEACTIVATE",
"ID": ComponentID.TAG_LIST.value,
"CACHE": False
}, {
"TYPE":
"TRANSITION",
"TRANSITIONS": [{
"ELEMENTS": ComponentID.MAIN.value,
"STYLE": 1,
"TIME": 1,
"DELAY": 0,
"TYPE": "LEAVING"
}, {
"ELEMENTS": ComponentID.TAG_FIRST_BAR.value,
"STYLE": 7,
"TIME": 0.5,
"DELAY": 0.9,
"TYPE": "JOINING"
}]
}],
padding=MakeElementEqualSize("Tags", self.large_ui_font,
button_size),
outline_size=outline_size,
pressed_background_colour=(200, 200, 200))
items_button = Button("Items",
self.large_ui_font,
target=self.main_menu_component.AddCommands,
arguments=[{
"TYPE":
"TRANSITION",
"TRANSITIONS": [{
"ELEMENTS":
ComponentID.MAIN.value,
"STYLE":
2,
"TIME":
1,
"DELAY":
0,
"TYPE":
"LEAVING"
}, {
"ELEMENTS":
ComponentID.ITEM_FIRST_BAR.value,
"STYLE":
2,
"TIME":
1,
"DELAY":
0,
"TYPE":
"JOINING"
}]
}],
padding=MakeElementEqualSize(
"Items", self.large_ui_font, button_size),
outline_size=outline_size,
pressed_background_colour=(200, 200, 200))
search_button = Button("Search",
self.large_ui_font,
target=self.main_menu_component.AddCommands,
arguments=[{
"TYPE":
"TRANSITION",
"TRANSITIONS": [{
"ELEMENTS":
ComponentID.MAIN.value,
"STYLE":
25,
"TIME":
1,
"DELAY":
0,
"TYPE":
"LEAVING"
}, {
"ELEMENTS":
ComponentID.SEARCH.value,
"STYLE":
25,
"TIME":
1,
"DELAY":
0,
"TYPE":
"JOINING"
}]
}],
padding=MakeElementEqualSize(
"Search", self.large_ui_font, button_size),
outline_size=outline_size,
pressed_background_colour=(200, 200, 200))
exit_button = Button("Exit",
self.large_ui_font,
target=self.main_menu_component.AddCommand,
arguments={"TYPE": "STOP"},
padding=MakeElementEqualSize(
"Exit", self.large_ui_font, button_size),
outline_size=outline_size,
background_colour=(237, 27, 36),
pressed_background_colour=(237, 27, 36),
text_colour=(255, 255, 255))
buttons = [
self.main_tags_button, items_button, search_button, exit_button
]
button_container.AddElements(*buttons)
button_container.position = ScalePosition(
Vector2D(0, 0), self.main_menu_component.size,
Vector2D(1 / 4, 0.6), button_container.size)
command_line_container = Container(
1, 2, Vector2D(0, 0), Vector2D(0, -self.standard_outline_size.y))
self.command_line_entry = FunctionalEntry(
self.standard_ui_font,
self.main_menu_component.width // 2,
self.UpdateCommandLineOutput,
padding=self.standard_padding,
outline_size=self.standard_outline_size,
empty_text="Type 'help' for help!",
text_colour=(255, 255, 255),
background_colour=(50, 50, 50))
self.command_line_output = AdvancedLabel(
'',
self.standard_ui_font,
Vector2D(self.main_menu_component.width // 2,
self.main_menu_component.height // 3 * 2),
padding=self.standard_padding,
outline_size=self.standard_outline_size,
background_colour=(50, 50, 50),
outline_colour=(0, 0, 0),
text_colour=(255, 255, 255),
line_seperation=self.main_menu_component.height // 400,
auto_scroll_position=1)
self.cli_history = []
command_line_container.AddElements(self.command_line_output,
self.command_line_entry)
command_line_container.position = ScalePosition(
Vector2D(0, 0), self.main_menu_component.size, Vector2D(1, 1),
command_line_container.size, Vector2D(1, 1))
self.main_menu_component.AddUIElements(title, version_label,
button_container,
command_line_container)
window.AddComponent(self.main_menu_component, ComponentID.MAIN.value,
False, False)
def SetupDefaultFileDialog(self):
from tkinter import Tk, PhotoImage
root = Tk()
root.withdraw() # instantly withdraw so the tk window doesn't pop up
root.tk.call('wm', 'iconphoto', root._w,
PhotoImage(file='gui\\images\\Logo32.png'))
def AttemptTagImport(self, ImportText):
from base64 import b64encode as EncodeB64
from json import loads as LoadJSON
try:
imported_text = encryption.DecryptTextWithKey(
EncodeB64(config.settings["key"]), ImportText)
tag_data = LoadJSON(imported_text)
successful = 0
failed = []
for tag in tag_data:
success = self.AttemptAddNewTag(tag[0], tag[1], tag[2], [
self.tag_first_bar,
[ComponentID.TAG_SECOND_BAR, ComponentID.TAG_LIST]
], False, False)
if success:
successful += 1
else:
failed.append(tag[0])
self.AddNotification(
"{} tags successfully added & {} failed".format(
successful, len(failed)),
display_time=8)
debug.Log(
f'Successfully imported {successful} tags and failed to import {len(failed)} tags.'
)
if successful > 0:
self.RefreshTags()
except:
self.AddNotification("Failed to import tags")
debug.Log("Failed to import tags.")
def ImportTagsFromClipboard(self):
from pyperclip import paste as PasteFromClipboard
self.AttemptTagImport(PasteFromClipboard().strip())
def ImportTagsFromFile(self, filename=None):
try:
if filename == None:
if not self.file_dialog_used:
self.SetupDefaultFileDialog()
self.file_dialog_used = True
from tkinter.filedialog import askopenfilename as AskOpenFileName
filename = AskOpenFileName(
title="Select a file to import tag data from",
filetypes=(("CVAL files", "*.CVAL"), ("Text files",
"*.txt")))
if filename != '':
debug.Log(f'Attempted to import tags from a file.')
with open(filename, "r") as f:
data = f.read()
f.close()
self.AttemptTagImport(data.strip())
except FileNotFoundError:
self.AddNotification("The specified file could not be found")
except:
self.AddNotification("An error occurred accessing the file")
def GetTagExport(self):
from base64 import b64encode as EncodeB64
from json import dumps as DumpJSON
tag_data = DumpJSON(SQL.GetAllTagData())
return encryption.EncryptTextWithKey(EncodeB64(config.settings["key"]),
tag_data)
def ExportTagsToClipboard(self):
from pyperclip import copy as CopyToClipboard
CopyToClipboard(self.GetTagExport())
self.AddNotification("Tag data copied to clipboard")
def ExportTagsToFile(self, filename=None):
try:
if filename == None:
if not self.file_dialog_used:
self.SetupDefaultFileDialog()
self.file_dialog_used = True
from tkinter.filedialog import asksaveasfile as AskSaveAsFile
file_ = AskSaveAsFile(
title="Create a file to save tag data to",
filetypes=(("CVAL files", "*.CVAL"), ("Text files",
"*.txt")),
defaultextension="CVAL")
else:
file_ = open(filename, 'w+')
if file_ != None:
debug.Log(f'Exported tag information to a file.')
file_.write(self.GetTagExport())