forked from STOCD/SETS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
6828 lines (5917 loc) · 361 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
# from textwrap import fill
# from asyncio import subprocess
import argparse
import ctypes
import datetime
import html
import json
import os
import platform
import re
import sys
import textwrap
import urllib.parse
import uuid
import webbrowser
import copy
# from tkinter import *
import tkinter as tk
from tkinter import Tk
from tkinter import BOTH, BOTTOM, DISABLED, END, FLAT, HORIZONTAL
from tkinter import LEFT, NORMAL, RIGHT, TOP, VERTICAL, WORD, X, Y
from tkinter import DoubleVar, IntVar, StringVar
from tkinter import Canvas, Checkbutton, Entry, Frame, Label, Menu, Menubutton #, Message
from tkinter import OptionMenu, PhotoImage, Radiobutton, Scale, Scrollbar, Text, Toplevel
from tkinter import font
from tkinter import filedialog
from tkinter import messagebox
from tkinter.ttk import Progressbar
import PIL
from PIL import Image, ImageTk, ImageGrab
from requests_html import Element, HTMLSession, HTML
import requests
import numpy as np
#import xlsxwriter
if platform.system() == 'Darwin':
from tkmacosx import Button
else:
from tkinter import Button
CLEANR = re.compile('<.*?>')
"""This section will improve display, but may require sizing adjustments to activate"""
if sys.platform.startswith('win'):
try:
ctypes.windll.shcore.SetProcessDpiAwareness(2) # windows version >= 8.1
except:
ctypes.windll.user32.SetProcessDPIAware() # windows version <= 8.0
class HoverButton(Button):
""" Updates default Button to have a hover background """
def __init__(self, master, **kw):
Button.__init__(self,master=master,**kw)
self.defaultBackground = self["background"]
self.bind("<Enter>", self.on_enter)
self.bind("<Leave>", self.on_leave)
def on_enter(self, e):
self['background'] = self['activebackground']
def on_leave(self, e):
self['background'] = self.defaultBackground
class SETS():
"""Main App Class"""
version = '20220413a_beta'
daysDelayBeforeReattempt = 7
#base URI
wikihttp = 'https://sto.fandom.com/wiki/'
wikiImages = wikihttp+'Special:Filepath/'
#query for ship cargo table on the wiki
ship_query = wikihttp+"Special:CargoExport?tables=Ships&&fields=_pageName%3DPage%2Cname%3Dname%2Cimage%3Dimage%2Cfc%3Dfc%2Ctier%3Dtier%2Ctype__full%3Dtype%2Chull%3Dhull%2Chullmod%3Dhullmod%2Cshieldmod%3Dshieldmod%2Cturnrate%3Dturnrate%2Cimpulse%3Dimpulse%2Cinertia%3Dinertia%2Cpowerall%3Dpowerall%2Cpowerweapons%3Dpowerweapons%2Cpowershields%3Dpowershields%2Cpowerengines%3Dpowerengines%2Cpowerauxiliary%3Dpowerauxiliary%2Cpowerboost%3Dpowerboost%2Cboffs__full%3Dboffs%2Cfore%3Dfore%2Caft%3Daft%2Cequipcannons%3Dequipcannons%2Cdevices%3Ddevices%2Cconsolestac%3Dconsolestac%2Cconsoleseng%3Dconsoleseng%2Cconsolessci%3Dconsolessci%2Cuniconsole%3Duniconsole%2Ct5uconsole%3Dt5uconsole%2Cexperimental%3Dexperimental%2Csecdeflector%3Dsecdeflector%2Changars%3Dhangars%2Cabilities__full%3Dabilities%2Cdisplayprefix%3Ddisplayprefix%2Cdisplayclass%3Ddisplayclass%2Cdisplaytype%3Ddisplaytype%2Cfactionlede%3Dfactionlede&&order+by=`_pageName`%2C`name`%2C`image`%2C`fc`%2C`faction__full`&limit=2500&format=json"
#query for ship equipment cargo table on the wiki
item_query = wikihttp+'Special:CargoExport?tables=Infobox&&fields=_pageName%3DPage%2Cname%3Dname%2Crarity%3Drarity%2Ctype%3Dtype%2Cboundto%3Dboundto%2Cboundwhen%3Dboundwhen%2Cwho%3Dwho%2Chead1%3Dhead1%2Chead2%3Dhead2%2Chead3%3Dhead3%2Chead4%3Dhead4%2Chead5%3Dhead5%2Chead6%3Dhead6%2Chead7%3Dhead7%2Chead8%3Dhead8%2Chead9%3Dhead9%2Csubhead1%3Dsubhead1%2Csubhead2%3Dsubhead2%2Csubhead3%3Dsubhead3%2Csubhead4%3Dsubhead4%2Csubhead5%3Dsubhead5%2Csubhead6%3Dsubhead6%2Csubhead7%3Dsubhead7%2Csubhead8%3Dsubhead8%2Csubhead9%3Dsubhead9%2Ctext1%3Dtext1%2Ctext2%3Dtext2%2Ctext3%3Dtext3%2Ctext4%3Dtext4%2Ctext5%3Dtext5%2Ctext6%3Dtext6%2Ctext7%3Dtext7%2Ctext8%3Dtext8%2Ctext9%3Dtext9&&order+by=%60_pageName%60%2C%60name%60%2C%60rarity%60%2C%60type%60%2C%60boundto%60&limit=5000&format=json'
#query for personal and reputation trait cargo table on the wiki
trait_query = wikihttp+"Special:CargoExport?tables=Traits&&fields=_pageName%3DPage%2Cname%3Dname%2Cchartype%3Dchartype%2Cenvironment%3Denvironment%2Ctype%3Dtype%2Cisunique%3Disunique%2Cmaster%3Dmaster%2Cdescription%3Ddescription%2Crequired__full%3Drequired%2Cpossible__full%3Dpossible&&order+by=%60_pageName%60%2C%60name%60%2C%60chartype%60%2C%60environment%60%2C%60type%60&limit=2500&format=json"
ship_trait_query = wikihttp+"Special:CargoExport?tables=Mastery&fields=Mastery._pageName,Mastery.trait,Mastery.traitdesc,Mastery.trait2,Mastery.traitdesc2,Mastery.trait3,Mastery.traitdesc3,Mastery.acctrait,Mastery.acctraitdesc&limit=1000&offset=0&format=json"
#query for DOFF types and specializations
doff_query = wikihttp+"Special:CargoExport?tables=Specializations&fields=Specializations.name,Specializations.shipdutytype,Specializations.department,Specializations.description,Specializations.powertype,Specializations.white,Specializations.green,Specializations.blue,Specializations.purple,Specializations.violet,Specializations.gold&order+by=Specializations.name&limit=1000&offset=0&format=json"
#query for Specializations and Reps
reputation_query = wikihttp+'Special:CargoExport?tables=Reputation&fields=Reputation.name,Reputation.environment,Reputation.boff,Reputation.color1,Reputation.color2,Reputation.description,Reputation.icon,Reputation.link,Reputation.released,Reputation.secondary&order+by=Reputation.boff&limit=1000&offset=0&format=json'
#query for Boffskills
trayskill_query = wikihttp+"Special:CargoExport?tables=TraySkill&fields=TraySkill._pageName,TraySkill.name,TraySkill.activation,TraySkill.affects,TraySkill.description,TraySkill.description_long,TraySkill.rank1rank,TraySkill.rank2rank,TraySkill.rank3rank,TraySkill.recharge_base,TraySkill.recharge_global,TraySkill.region,TraySkill.system,TraySkill.targets,TraySkill.type&order+by=TraySkill.name&limit=1000&offset=0&format=json"
faction_query = wikihttp+"Special:CargoExport?tables=Faction&fields=Faction.playability,Faction.name,Faction._pageName,Faction.allegiance,Faction.faction,Faction.imagepeople,Faction.origin,Faction.quadrant,Faction.status,Faction.traits&limit=1000&offset=0&format=json"
#to prevent Infobox from loading the same element twice in a row
displayedInfoboxItem = str()
#available specializations and their respective starship traits
specializations = {"Constable": "Arrest",
"Command Officer": "Command Frequency",
"Commando": "Demolition Teams",
"Miracle Worker": "Going the Extra Mile",
"Temporal Operative": "Non-Linear Progression",
"Pilot": "Pedal to the Metal",
"Intelligence Officer": "Predictive Algorithms",
"Strategist": "Unconventional Tactics"}
#available recruits and their respective starship traits
recruits = {"Klingon Recruit": "Hunter's Instinct",
"Delta Recruit": "Temporal Insight",
"Temporal Agent": "Critical Systems"}
#conversion from self.build['equipment'] keys to self.cache['equipment'] keys
keys = {"foreWeapons": "Ship Fore Weapon",
"aftWeapons": "Ship Aft Weapon",
"deflector": "Ship Deflector Dish",
"engines": "Impulse Engine",
"warpCore": "Warp",
"shield": "Ship Shields",
"devices": "Ship Device",
"secdef": "Ship Secondary Deflector",
"experimental": "Experimental",
"engConsoles": "Ship Engineering Console",
"sciConsoles": "Ship Science Console",
"tacConsoles": "Ship Tactical Console",
"uniConsoles": "Console",
"groundKit": "Kit Frame",
"groundArmor": "Body Armor",
"groundEV": "EV Suit",
"groundShield": "Personal Shield",
"groundWeapons": "Ground Weapon",
"groundDevices": "Ground Device",
"groundKitModules": "Kit Module",
"hangars": "Hangar Bay"
}
# Needs fonts, padx, pady, possibly others
theme = theme_default = {
'name': 'SETS_default',
'app': {
'bg': '#c59129', # self.theme['app']['bg']
'fg': '#3a3a3a', # self.theme['app']['fg']
'hover': '#a3a3a3', # self.theme['app']['hover']
'font': { # self.theme['app']['font_object']
'family': 'Helvetica',
'size': 10,
'weight': '',
},
},
'frame': {
'bg': '#3a3a3a', # self.theme['frame']['bg']
'fg': '#b3b3b3', # self.theme['frame']['fg']
},
'frame_medium': {
'bg': '#b3b3b3', # self.theme['frame_medium']['bg']
'fg': '#3a3a3a', # self.theme['frame_medium']['fg']
'hover': '#555555', # self.theme['frame_medium']['hover']
'hlbg': 'grey', # self.theme['frame_medium']['hlbg'] # highlightbackground
'hlthick': 1, # self.theme['frame_medium']['hlthick'] # highlightthickness
},
'frame_light': {
'bg': '#b3b3b3', # self.theme['frame_light']['bg']
'fg': '#3a3a3a', # self.theme['frame_light']['fg']
},
'button_heavy': {
'bg': '#6b6b6b', # self.theme['button_heavy']['bg']
'fg': '#ffffff', # self.theme['button_heavy']['fg']
'hover': '#bbbbbb', # self.theme['button_heavy']['hover']
'font': { # self.theme['button_heavy']['font_object']
'size': 12,
'weight': 'bold',
},
},
'button_medium': {
'bg': '#6b6b6b', # self.theme['button_medium']['bg']
'fg': '#dddddd', # self.theme['button_medium']['fg']
'hover': '#bbbbbb', # self.theme['button_medium']['hover']
'font': { # self.theme['button_medium']['font_object']
},
},
'button': {
'bg': '#3a3a3a', # self.theme['button']['bg']
'fg': '#b3b3b3', # self.theme['button']['fg']
'hover': '#555555', # self.theme['button']['hover']
},
'label': {
'bg': '#b3b3b3', # self.theme['label']['bg']
'fg': '#3a3a3a', # self.theme['label']['fg']
'font': { # self.theme['app']['font_object']
'size': 12,
},
},
'space': {
'bg': '#000000', # self.theme['label']['bg']
'fg': '#3a3a3a', # self.theme['label']['fg']
},
'title1': {
'font': { # self.theme['title1']['font_object']
'size': 14,
'weight': 'bold',
},
},
'title2': {
'font': { # self.theme['title2']['font_object']
'size': 12,
'weight': 'bold',
},
},
'text_highlight': {
'font': { # self.theme['text_highlight']['font_object']
'size': 10,
'weight': 'bold',
},
},
'text_contrast': {
'font': { # self.theme['text_contrast']['font_object']
'size': 10,
'weight': 'italic',
},
},
'text_medium': {
'font': { # self.theme['text_medium']['font_object']
'size': 9,
},
},
'text_small': {
'font': { # self.theme['text_small']['font_object']
'size': 8,
},
},
'text_tiny': {
'font': { # self.theme['text_tiny']['font_object']
'size': 8,
'weight': 'bold',
},
},
'text_log': {
'font': { # self.theme['text_small']['font_object']
'family': 'Courier',
'size': 10,
},
},
'entry': { # Entry and Text widgets
'bg': '#b3b3b3', # self.theme['entry']['bg']
'fg': '#3a3a3a', # self.theme['entry']['fg']
},
'entry_dark': {
'bg': '#3a3a3a', # self.theme['entry_dark']['bg']
'fg': '#ffffff', # self.theme['entry_dark']['fg']
},
'tooltip': {
'bg': '#090b0d', # self.theme['tooltip']['bg']
'fg': '#ffffff', # self.theme['tooltip']['fg']
'highlight': '#090b0d', # self.theme['tooltip']['highlight']
'relief': 'flat', # self.theme['tooltip']['relief']
# Tags
'head1': {'fg': '#42afca'}, # self.theme['tooltip']['head1']['fg']
'head': {'fg': '#42afca'}, # self.theme['tooltip']['head']['fg']
'subhead': {'fg': '#f4f400'}, # self.theme['tooltip']['subhead']['fg']
'who': {'fg': '#ff6347'}, # self.theme['tooltip']['who']['fg']
'distance': {'fg': '#000000'}, # self.theme['tooltip']['distance']['fg']
},
'tooltip_head': {
'font': { # self.theme['tooltip_head']['font_object']
'size': 12,
'weight': 'bold',
},
},
'tooltip_subhead': {
'font': { # self.theme['tooltip_subhead']['font_object']
'size': 10,
'weight': 'bold',
},
},
'tooltip_name': {
'font': { # self.theme['tooltip_name']['font_object']
'size': 15,
'weight': 'bold',
},
},
'tooltip_body': {
'font': { # self.theme['tooltip_body']['font_object']
'size': 10,
},
},
'tooltip_distance': {
'font': { # self.theme['tooltip_distance']['font_object']
'size': 4,
},
},
'icon_off': {
'bg': 'grey', # self.theme['icon_off']['bg']
'fg': '#ffffff', # self.theme['icon_off']['fg']
'hlbg': 'grey', # self.theme['icon_off']['hlbg'] # highlightbackground
'hlthick': 0, # self.theme['icon_off']['hlthick'] # highlightthickness
'relief': 'raised', # self.theme['icon_off']['relief']
},
'icon_on': {
'bg': 'yellow', # self.theme['icon_on']['bg']
'fg': '#ffffff', # self.theme['icon_on']['fg']
'relief': 'groove', # self.theme['icon_on']['relief']
},
}
def encodeBuildInImage(self, src, message, dest):
img = Image.open(src, 'r')
width, height = img.size
array = np.array(list(img.getdata()))
if img.mode == 'RGB':
n = 3
elif img.mode == 'RGBA':
n = 4
else:
return
total_pixels = array.size//n
message += "$t3g0"
b_message = ''.join([format(ord(i), "08b") for i in message])
req_pixels = len(b_message)
if req_pixels <= total_pixels:
index = 0
for p in range(total_pixels):
for q in range(0, 3):
if index < req_pixels:
array[p][q] = int(bin(array[p][q])[2:9] + b_message[index], 2)
index += 1
array = array.reshape(height, width, n)
enc_img = Image.fromarray(array.astype('uint8'), img.mode)
enc_img.save(dest)
def decodeBuildFromImage(self, src):
img = Image.open(src, 'r')
array = np.array(list(img.getdata()))
if img.mode == 'RGB':
n = 3
elif img.mode == 'RGBA':
n = 4
else:
return
total_pixels = array.size//n
hidden_bits = ""
for p in range(total_pixels):
if p % 5000 == 0:
self.progress_bar_update()
for q in range(0, 3):
hidden_bits += (bin(array[p][q])[2:][-1])
hidden_bits = [hidden_bits[i:i+8] for i in range(0, len(hidden_bits), 8)]
message = ""
for i in range(len(hidden_bits)):
if message[-5:] == "$t3g0":
break
else:
message += chr(int(hidden_bits[i], 2))
return message[:-5]
def add_to_IntVar(self, v):
self.set(self.get() + v)
IntVar.add = add_to_IntVar
def openURL(self, url):
""" Open the system-specific browser with provided url """
try:
webbrowser.open(url, new=2, autoraise=True)
except:
messagebox.showinfo(message="You'll find more information on the STO - Fandom WIKI: "+url)
def openWikiPage(self, pagename):
""" Request a browser tab with provided pagename """
self.openURL(self.getWikiURL(pagename))
def getWikiURL(self, pagename):
""" Convert provided pagename into an URL to find the page on the wiki """
return "https://sto.fandom.com/wiki/"+pagename.replace(" ", "_")
def fetchOrRequestHtml(self, url, designation):
"""Request HTML document from web or fetch from local cache"""
cache_base = self.get_folder_location('cache')
override_base = self.get_folder_location('override')
if not os.path.exists(cache_base):
return
filename = os.path.join(*filter(None, [cache_base, designation]))+".html"
filenameOverride = os.path.join(*filter(None, [override_base, designation]))+".html"
if os.path.exists(filenameOverride):
filename = filenameOverride
if os.path.exists(filename):
modDate = os.path.getmtime(filename)
interval = datetime.datetime.now() - datetime.datetime.fromtimestamp(modDate)
if interval.days < self.daysDelayBeforeReattempt:
with open(filename, 'r', encoding='utf-8') as html_file:
s = html_file.read()
return HTML(html=s, url = 'https://sto.fandom.com/')
r = self.session.get(url)
self.make_filename_path(os.path.dirname(filename))
with open(filename, 'w', encoding="utf-8") as html_file:
html_file.write(r.text)
self.logWriteTransaction('Cache File (html)', 'stored', str(os.path.getsize(filename)), designation, 1)
return r.html
def fetchOrRequestJson(self, url, designation, local=False):
"""Request HTML document from web or fetch from local cache specifically for JSON formats"""
cache_base = self.resource_path(self.settings['folder']['local']) if local else self.get_folder_location('cache')
override_base = self.get_folder_location('override')
if not os.path.exists(cache_base):
return
filenameOverride = os.path.join(*filter(None, [override_base, designation]))+".json"
if os.path.exists(filenameOverride):
filename = filenameOverride
else:
filename = os.path.join(*filter(None, [cache_base, designation])) + ".json"
if os.path.exists(filename):
modDate = os.path.getmtime(filename)
interval = datetime.datetime.now() - datetime.datetime.fromtimestamp(modDate)
if interval.days < 7 or local:
with open(filename, 'r', encoding='utf-8') as json_file:
json_data = json.load(json_file)
self.logWriteTransaction('Cache File (json)', 'read', str(os.path.getsize(filename)), designation, 1)
return json_data
if interval.days >= 7:
self.clearCacheFolder(designation+".json")
elif not local:
r = requests.get(url)
self.make_filename_path(os.path.dirname(filename))
with open(filename, 'w') as json_file:
json.dump(r.json(),json_file)
self.logWriteTransaction('Cache File (json)', 'stored', str(os.path.getsize(filename)), designation, 1)
return r.json()
def filePathSanitize(self, txt, chr_set='printable'):
"""Converts txt to a valid filename.
Args:
txt: The str to convert.
chr_set:
'printable': Any printable character except those disallowed on Windows/*nix.
'extended': 'printable' + extended ASCII character codes 128-255
'universal': For almost *any* file system. '-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
"""
FILLER = '-'
MAX_LEN = 255 # Maximum length of filename is 255 bytes in Windows and some *nix flavors.
# Step 1: Remove excluded characters.
BLACK_LIST = set(chr(127) + r'<>:"/\|?*') # 127 is unprintable, the rest are illegal in Windows.
white_lists = {
'universal': {'-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'},
'printable': {chr(x) for x in range(32, 127)} - BLACK_LIST, # 0-32, 127 are unprintable,
'extended' : {chr(x) for x in range(32, 256)} - BLACK_LIST,
}
white_list = white_lists[chr_set]
result = ''.join(x
if x in white_list else FILLER
for x in txt)
# Step 2: Device names, '.', and '..' are invalid filenames in Windows.
DEVICE_NAMES = 'CON,PRN,AUX,NUL,COM1,COM2,COM3,COM4,' \
'COM5,COM6,COM7,COM8,COM9,LPT1,LPT2,' \
'LPT3,LPT4,LPT5,LPT6,LPT7,LPT8,LPT9,' \
'CONIN$,CONOUT$,..,.'.split() # This list is an O(n) operation.
if result in DEVICE_NAMES:
result = f'-{result}-'
# Step 3: Truncate long files while preserving the file extension.
if len(result) > MAX_LEN:
if '.' in txt:
result, _, ext = result.rpartition('.')
ext = '.' + ext
else:
ext = ''
result = result[:MAX_LEN - len(ext)] + ext
# Step 4: Windows does not allow filenames to end with '.' or ' ' or begin with ' '.
result = re.sub(r"[. ]$", FILLER, result)
result = re.sub(r"^ ", FILLER, result)
return result
def titleCaseRegexpText(self, matchobj):
return matchobj.group(0).title()
def lowerCaseRegexpText(self, matchobj):
return matchobj.group(0).lower()
def iconNameCleanup(self, text):
""" Adjustments needed to convert cargo name to image URL name """
text = text.replace('Q%27s_Ornament%3A_', '')
# Much of this can be removed if the wiki templates have their lowercase forces removed
text = re.sub('_From_', '_from_', text)
text = re.sub('_For_', '_for_', text)
text = re.sub('_The_', '_the_', text)
text = re.sub('_And_', '_and_', text)
text = re.sub('/[Ss]if', '/SIF', text)
text = re.sub('nos_', 'noS_', text)
text = re.sub('rihan', 'Rihan', text)
text = re.sub('_(\w{1,2})_', self.lowerCaseRegexpText, text)
text = re.sub('-([a-z])', self.titleCaseRegexpText, text)
return text
def fetchImage(self, url, designation):
"""
Attempt to get image from <url>, saved as <designation> in local cache
- will record failure and avoid re-trying that error until a designated number of days has passed
"""
today = datetime.date.today()
if not self.args.allfetch and url in self.persistent['imagesFail'] and self.persistent['imagesFail'][url]:
daysSinceFail = today - datetime.date.fromisoformat(self.persistent['imagesFail'][url])
if daysSinceFail.days <= self.daysDelayBeforeReattempt:
# Previously failed, do not attempt download again until next reattempt days have passed
return None
self.progress_bar_update(text=designation)
img_request = requests.get(url)
self.logWriteTransaction('fetchImage', 'download', str(img_request.headers.get('Content-Length')), url, 1, [str(img_request.status_code), designation])
if not img_request.ok:
# No response on icon grab, mark for no downlaad attempt till restart
self.persistent['imagesFail'][url] = today.isoformat()
self.auto_save(quiet=True)
return None
if url in self.persistent['imagesFail'] and self.persistent['imagesFail'][url]:
self.persistent['imagesFail'][url] = ''
self.auto_save()
return img_request.content
def filepath_sanitizer(self, path):
""" Take provided path, remove characters inappropriate for saving as a filename, return as path """
(path_only, name) = os.path.split(path)
name = self.filename_sanitizer(name)
path_converted = os.path.join(path_only, name)
return path_converted
def filename_sanitizer(self, name):
""" Remove inappropriate filename characters (os agnostic rather than specific) """
name_only, chosenExtension = os.path.splitext(name)
name_only = name_only.replace('/', '_') # Missed by the path sanitizer
name_only = self.filePathSanitize(name_only) # Probably should move to pathvalidate library
name_only = name_only.replace('\\\\', '_') # Missed by the path sanitizer
name_only = name_only.replace('.', '') # Missed by the path sanitizer
name_converted = '{}{}'.format(name_only, chosenExtension)
self.logWriteSimple('sanitize', 'name', 6, [name, '=>', name_converted])
return name_converted
def fetchOrRequestImage(self, url, designation, width = None, height = None, faction = None, forceAspect = False, loop=1):
"""Request image from web or fetch from local cache"""
cache_base = self.get_folder_location('images')
if not os.path.exists(cache_base):
return
self.logWriteTransaction('Image File', 'try', '----', url, 5, [designation, faction, forceAspect])
image_data = None
designation = self.filename_sanitizer(designation)
factionCode = factionCodeDefault = '_(Federation)'
if faction is not None and self.persistent['useFactionSpecificIcons']:
if 'faction' in self.build['captain'] and self.build['captain']['faction'] != '':
factionCode = '_('+self.build['captain']['faction']+')'
extension = "jpeg" if url.endswith("jpeg") or url.endswith("jpg") else "png"
fileextension = '.'+extension
filename = filenameDefault = filenameNoFaction = os.path.join(*filter(None, [cache_base, designation]))+fileextension
override_base = self.get_folder_location('override')
internal_base = self.resource_path(self.settings['folder']['images'])
local_base = self.settings['folder']['images']
filenameOverride = os.path.join(*filter(None, [override_base, designation]))+fileextension
filenameInternal = os.path.join(*filter(None, [internal_base, designation]))+fileextension
filenameLocal = os.path.join(*filter(None, [local_base, designation]))+fileextension
filenameExisting = ''
if faction is not None and faction != False and '_icon' in url and not '_icon_(' in url:
url = re.sub('_icon', '_icon{}'.format(factionCode), url)
if factionCode != factionCodeDefault:
# Don't alter filename for default faction
filename = re.sub(fileextension, '{}{}'.format(factionCode, fileextension), filename)
filenameDefault = re.sub(fileextension, '{}{}'.format(factionCodeDefault, fileextension), filename)
if filename in self.persistent['imagesFactionAliases']:
filename = self.persistent['imagesFactionAliases'][filename]
if os.path.exists(filenameOverride):
filename = filenameOverride
elif not os.path.exists(filename):
if os.path.exists(filenameInternal):
filename = filenameInternal
elif os.path.exists(filenameLocal):
filename = filenameLocal
if os.path.exists(filename):
self.progress_bar_update()
elif not self.args.nofetch:
image_data = self.fetch_image_from_url(url, designation, factionCode, factionCodeDefault, filenameNoFaction, filenameDefault)
if os.path.exists(filenameExisting):
self.progress_bar_update(int(self.updateOnHeavyStep / 2))
self.persistent['imagesFactionAliases'][filename] = filenameExisting
self.logWriteTransaction('Image File', 'alias', '----', filename, 3, [filenameExisting])
self.auto_save(quiet=True)
filename = filenameExisting
if image_data is not None:
self.progress_bar_update(self.updateOnHeavyStep)
self.perf('file_write')
with open(filename, 'wb') as handler:
handler.write(image_data)
self.logWriteTransaction('Image File', 'write', len(str(os.path.getsize(filename))) if os.path.exists(filename) else '----', filename, 1)
self.perf('file_write', 'stop', cumulative=True)
elif not os.path.exists(filename):
self.progress_bar_update(int(self.updateOnHeavyStep / 4))
return self.emptyImage
image_result = self.fetch_image(filename, width, height, forceAspect)
if image_result is None and loop == 1:
# remove image
try:
# os.rename(filename, filename+'.bad')
os.unlink(filename)
except BaseException as err:
self.logWriteSimple('image unlink', 'fail', 1, [err])
else:
image_result = self.fetchOrRequestImage(url, designation, width, height, faction, forceAspect, loop=2)
return image_result
def fetch_image_from_url(self, url, designation, factionCode, factionCodeDefault, filenameNoFaction, filenameDefault):
image_data = self.fetchImage(url, designation)
""" Try variations of image name to download from the wiki, returns the image """
url4 = url3 = url2 = ''
if image_data is None:
url2 = self.iconNameCleanup(url)
image_data = self.fetchImage(url2, designation) if url2 != url else image_data
if image_data is None:
if factionCode in url:
url3 = re.sub(factionCode, factionCodeDefault, url)
filenameExisting = filenameNoFaction
else:
url3 = re.sub('_icon', '_icon{}'.format(factionCode), url)
filenameExisting = filenameDefault
if not os.path.exists(filenameExisting):
image_data = self.fetchImage(url3, designation) if url3 != url and url3 != url2 else image_data
if image_data is None:
url4 = self.iconNameCleanup(url3)
image_data = self.fetchImage(url4, designation) if url4 != url3 and url4 != url and url4 != url2 else image_data
return image_data
def fetch_image(self, filename, width, height, forceAspect):
""" Open local image and provide an image with provided sizing """
try:
image_load = Image.open(filename)
except PIL.UnidentifiedImageError:
self.logWriteTransaction('Image File', 'unidentified', '', filename, 4)
return None
if(width is not None):
if forceAspect:
image = image_load.resize((width, height), Image.LANCZOS)
else:
image = image_load
image.thumbnail((width, height), resample=Image.LANCZOS)
else:
image = image_load
self.logWriteTransaction('Image File', 'read', str(os.path.getsize(filename)), filename, 4, image.size)
tk_image = ImageTk.PhotoImage(image)
return tk_image
def deHTML(self, textBlock, leaveHTML=False):
""" Remove HTML escaping, and optionally remove HTML tags """
textBlock = html.unescape(html.unescape(textBlock)) # Twice because the wiki overlaps some
if not leaveHTML: textBlock = re.sub(CLEANR, '', textBlock)
return textBlock
def deWikify(self, textBlock, leaveHTML=False):
""" Remove wiki format marks """
textBlock = self.deHTML(textBlock, leaveHTML) # required first-- the below are *secondary* filters due to wiki formatting
textBlock = textBlock.replace('<',"<")
textBlock = textBlock.replace('>',">")
textBlock = textBlock.replace('"', '"')
textBlock = textBlock.replace(''', '\'')
textBlock = textBlock.replace('[', '[')
textBlock = textBlock.replace(']', ']')
textBlock = textBlock.replace('"', '\"')
# clean up wikitext
textBlock = textBlock.replace('\x7f', '')
# \u007f'"`UNIQ--nowiki-00000000-QINU`"'\u007f
textBlock = re.sub('\'"`UNIQ--nowiki-0000000.-QINU`"\'', '*', textBlock)
textBlock = re.sub('\'"`UNIQ--nowiki-0000001.-QINU`"\'', '*', textBlock)
textBlock = re.sub('\'"`UNIQ--nowiki-0000002.-QINU`"\'', '*', textBlock)
textBlock = re.sub('\'"`UNIQ--nowiki-0000003.-QINU`"\'', '*', textBlock)
textBlock = re.sub('\'"`UNIQ--nowiki-0000004.-QINU`"\'', '*', textBlock)
if "[[" and "|" in textBlock:
while "[[" and "|" in textBlock:
start = textBlock.find("[[")
end = textBlock.find("|")
textBlock = textBlock[:start] + textBlock[end+1:]
textBlock = textBlock.replace('[[', '')
textBlock = textBlock.replace(']]', '')
textBlock = textBlock.replace("{{lc: ","").replace("{{lc:","")
textBlock = textBlock.replace("{{ucfirst: ","").replace("{{ucfirst:","")
textBlock = textBlock.replace("{{","").replace("}}","")
textBlock = textBlock.replace("&", "&")
textBlock = textBlock.replace("*","*")
return textBlock
def loadLocalImage(self, filename, width = None, height = None, forceAspect=False):
"""Request image from web or fetch from local cache"""
cache_base = self.settings['folder']['local']
cache_base = self.resource_path(cache_base)
self.make_filename_path(cache_base)
filename = os.path.join(*filter(None, [cache_base, filename]))
if os.path.exists(filename):
image = Image.open(filename)
#self.logWrite('==={}x{} [{}]'.format(width, height, filename), 2)
if(width is not None):
if forceAspect: image = image.resize((width,height),Image.LANCZOS)
else: image.thumbnail((width, height), resample=Image.LANCZOS)
return ImageTk.PhotoImage(image)
return self.emptyImage
def emptyShipLayout(self, shipHtml):
"""overrides all ship components of self.build to feature the exact layout of the given ship"""
self.build['ship'] = shipHtml['Page'] # saves ship name
# Boffs
if not 'boffs' in shipHtml: return
seats = len(shipHtml['boffs'])
boffranks = [4] * seats
boffcareers = [''] * seats + [None] * (6-seats)
boffspecs = [''] * seats + [None] * (6-seats)
for i in range(len(shipHtml['boffs'])):
boffranks[i] = 3 if 'Lieutenant Commander' in shipHtml['boffs'][i] else 2 if 'Lieutenant' in shipHtml['boffs'][i] else 4 if 'Commander' in shipHtml['boffs'][i] else 1
for s in self.cache['specsPrimary']:
if '-'+s in shipHtml['boffs'][i]:
boffspecs[i] = s
break
boffcareers[i] = self.boffTitleToCareer(shipHtml['boffs'][i].replace('Lieutenant', '').replace('Commander', '').replace('Ensign', '').strip())
self.build['boffseats']['space'] = boffcareers
self.build['boffseats']['space_spec'] = boffspecs
for i in range(seats):
self.build['boffs']['spaceBoff_'+str(i)] = [None] * boffranks[i]
for i in range(seats, 6):
try: self.build['boffs'].pop('spaceBoff_'+str(i))
except KeyError: pass
# Consoles & Devices
self.build['tacConsoles'] = [None] * int(shipHtml['consolestac'])
self.build['engConsoles'] = [None] * int(shipHtml['consoleseng'])
self.build['sciConsoles'] = [None] * int(shipHtml['consolessci'])
self.build['uniConsoles'] = [None] * 1 if 'Innovation Effects' in shipHtml['abilities'] else [None] * 0
self.build['devices'] = [None] * int(shipHtml['devices'])
# Weapons
self.build['foreWeapons'] = [None] * int(shipHtml['fore'])
self.build['aftWeapons'] = [None] * int(shipHtml['aft'])
if 'experimental' in shipHtml and shipHtml['experimental'] == 1:
self.build['experimental'] = [None]
else:
self.build['experimental'] = []
# DSECS
for decs in ['deflector', 'engines', 'warpCore', 'shield']:
self.build[decs] = [None]
if 'secdeflector' in shipHtml and shipHtml['secdeflector'] == 1:
self.build['secdef'] = [None]
else:
self.build['secdef'] = []
# Hagars
if 'hangars' in shipHtml and (shipHtml['hangars'] == 1 or shipHtml['hangars'] == 2):
self.build['hagars'] = [None] * int(shipHtml['hangars'])
else:
self.build['hangars'] = []
# Misc
""" Do we need that?
self.build['playerShipName'] == ''
self.build['playerShipDesc'] == ''
"""
def alignNewShipBuild(self, shipHtml):
"""maps a space build onto a new ship and writes it into self.build. this only affects ship dependent parts of the build"""
# helper fuction to ensure that None < 0
def sortedNone(tup):
newTup = tuple()
for element in tup:
if element == None: newTup += (-float('inf'),)
else: newTup += (element,)
return newTup
if not ('boffs' in self.build and 'spaceBoff_0' in self.build['boffs'] and 'boffseats' in self.build and 'space' in self.build['boffseats']): return
oldBuild = copy.deepcopy(self.build) # saving the current build. oldBuild will be "laid over" the new layout
self.emptyShipLayout(shipHtml) # creating an empty ship layout for the given ship
# putting in the equipment
for elem in ['tacConsoles','engConsoles','sciConsoles','uniConsoles','devices','foreWeapons','aftWeapons','experimental','secdef','hangars','deflector', 'engines', 'warpCore', 'shield']:
for index in range(len(self.build[elem])):
try:
self.build[elem][index] = oldBuild[elem][index]
except IndexError:
self.build[elem][index] = [None]
# putting in the boffs
if not 'boffs' in oldBuild and not 'boffseats' in oldBuild and not 'space' in oldBuild['boffseats'] and not 'space_spec' in oldBuild['boffseats']:
self.logWriteSimple('old build invalid', 'the old build is missing critical data about Boff seating', 1, ['possibly missing keys:','["boffs"]','["boffseats"]','["boffseats"]["space"]','["boffseats"]["space_spec"]'])
return
oldSeats = []
newSeats = []
for dct in [self.build,oldBuild]: # goes over the old and the new build and creates two lists with the bridge officers
for currentSeat in range(6):
rank = len(dct['boffs']['spaceBoff_'+str(currentSeat)]) if 'spaceBoff_'+str(currentSeat) in dct['boffs'] else None
career = dct['boffseats']['space'][currentSeat]
spec = dct['boffseats']['space_spec'][currentSeat]
id = 'spaceBoff_'+str(currentSeat)
if dct == oldBuild: oldSeats.append((rank, career, spec, id))
elif dct == self.build: newSeats.append((rank, career, spec, id))
oldSeats = sorted(oldSeats, key=sortedNone, reverse=True)
newSeats = sorted(newSeats, key=sortedNone, reverse=True)
boffMapping = dict() # this dictionary will contain the information on which boff seat on the old build will be which on the new build: "<newSeatID>":"<oldSeatID>"
universalStationPurpose = ['']*6 # if a seat gets assigned to an universal seat the career that this universal seat needs to be is saved here
for oldSeat in oldSeats: # this tries to give every old seat a new seat. higher rank seats will be considered first.
if oldSeat[0] == None: continue
for withUniversalSeats in [False, True]: # ignores universal seats on the first iteration, considers them in the second
if oldSeat[3] in boffMapping.values(): break # aborts if current station has already been assigned a new station
for i in range(6):
if oldSeat[1] == newSeats[i][1] or (newSeats[i][1] == 'Universal' and withUniversalSeats): # index 1 stands for 'career'
if not newSeats[i][3] in boffMapping: # index 3 stands for 'id'
boffMapping[newSeats[i][3]] = oldSeat[3]
universalStationPurpose[i] = oldSeat[1]
break
for idx, seat in enumerate(newSeats): # executes the mapping; saves respective abilities to their new locations in self.build; filters out specialist abilities not fitting onto the new station
if seat[0] == None or not seat[3] in boffMapping: continue
self.build['boffseats']['space'][int(seat[3][-1])] = seat[1] if not seat[1] == 'Universal' else universalStationPurpose[idx]
self.build['boffseats']['space_spec'][int(seat[3][-1])] = seat[2]
for r in range(1, min( len(self.build['boffs'][seat[3]]), len(oldBuild['boffs'][boffMapping[seat[3]]] ) ) + 1 ): # iterates for the minimum rank of the old and new station
ability = oldBuild['boffs'][boffMapping[seat[3]]][r-1]
if seat[2] == '': bofflist = self.cache['boffAbilitiesWithImages']['space'][self.build['boffseats']['space'][int(seat[3][-1])]][r]
else: bofflist = self.cache['boffAbilitiesWithImages']['space'][self.build['boffseats']['space'][int(seat[3][-1])]][r] + self.cache['boffAbilitiesWithImages']['space'][seat[2]][r]
for thisisshit in bofflist:
if thisisshit[0] == ability:
self.build['boffs'][seat[3]][r-1] = ability
def getShipFromName(self, shipJson, shipName):
"""Find cargo table entry for given ship name"""
ship_list = []
for e in range(len(shipJson)):
if shipJson[e]["Page"] == shipName:
ship_list = shipJson[e]
return ship_list
def getTierOptions(self, tier):
"""Get possible tier options from ship tier string"""
return ['T5', 'T5-U', 'T5-X'] if int(tier) == 5 else ['T6', 'T6-X'] if int(tier) == 6 else ['T'+str(tier)]
def setVarAndQuit(self, e, name, image, v, win):
"""Helper function to set variables from within UI callbacks"""
v['item'] = name
v['image'] = image
win.destroy()
def makeRedditTable(self, c0, c1, c2:list = [], c3:list = [], alignment:list = [":---", ":---", ":---"]):
"""Creates Markdown formatted table from lists containing the column elements and an alignment list"""
# 4 columns
if c3 != []:
result = '**{0}** | **{1}** | **{2}** | **{3}**\n'.format(c0[0],c1[0],c2[0],c3[0])
result = result + "{0} | {1} | {2} | {3}\n".format(alignment[0], alignment[1], alignment[2], alignment[3])
for i in range(1,len(c0)):
c0[i] = c0[i] if c0[i] is not None else ' '
c1[i] = c1[i] if c1[i] is not None else ' '
c2[i] = c2[i] if c2[i] is not None else ' '
c3[i] = c3[i] if c3[i] is not None else ' '
result = result + "{0} | {1} | {2} | {3}\n".format(c0[i],c1[i],c2[i],c3[i])
return result
# 2 columns
if c2 == []:
result = '**{0}** | **{1}**\n'.format(c0[0], c1[0])
result = result + "{0} | {1}\n".format(alignment[0], alignment[1])
for i in range(1, len(c0)):
c0[i] = c0[i] if c0[i] is not None else ' '
c1[i] = c1[i] if c1[i] is not None else ' '
result = result + "{0} | {1}\n".format(c0[i], c1[i])
return result
# 3 columns
result = '**{0}** | **{1}** | **{2}**\n'.format(c0[0],c1[0],c2[0])
result = result + "{0} | {1} | {2}\n".format(alignment[0], alignment[1], alignment[2])
for i in range(1,len(c0)):
c0[i] = c0[i] if c0[i] is not None else ' '
c1[i] = c1[i] if c1[i] is not None else ' '
c2[i] = c2[i] if c2[i] is not None else ' '
result = result + "{0} | {1} | {2}\n".format(c0[i],c1[i],c2[i])
return result
def makeRedditColumn(self, c0, length):
if length == 0: return []
return c0+[' ']*(length-len(c0))+['--------------']
def preformatRedditEquipment(self, key,len): #self.cache['equipment'][key][name]
equipment = list()
for item in self.build[key]:
if item is not None:
equipment.append("[{0} {1} {2}]({3})".format(item["item"], item['mark'], ''.join(item['modifiers']), self.getWikiURL(self.cache['equipment'][self.keys[key]][item["item"]]['Page'])))
return equipment[:len]
#return ["{0} {1} {2}".format(item['item'], item['mark'], ''.join(item['modifiers'])) for item in self.build[key] if item is not None][:len]
def getEmptyItem(self):
""" Provide an 'item' dict with empty formatting """
return {"item": "", "image": self.emptyImage}
def sanitizeEquipmentName(self, name):
"""Strip irreleant bits of equipment name for easier icon matching"""
name = self.deWikify(name)
name = re.sub(r"(∞.*)|(Mk X.*)|(\[.*].*)|(MK X.*)|(-S$)", '', name).strip()
return name
def precachePreload(self, limited=False):
""" Cache all popup and tooltip lists for full app functionality """
self.logWriteBreak('precachePreload START')
self.perf('downloads');self.precache_downloads();self.perf('downloads', 'stop')
self.perf('cache-ships');self.precacheShips();self.perf('cache-ships', 'stop')
self.perf('cache-templates');self.precacheTemplates();self.perf('cache-templates', 'stop')
self.perf('cache-doffspace');self.precacheDoffs("Space");self.perf('cache-doffspace', 'stop')
self.perf('cache-doffground');self.precacheDoffs("Ground");self.perf('cache-doffground', 'stop')
self.perf('cache-mods');self.precacheModifiers();self.perf('cache-mods', 'stop')
self.perf('cache-reps');self.precacheReputations();self.perf('cache-reps', 'stop')
self.perf('cache-factions');self.precacheFactions();self.perf('cache-factions', 'stop')
self.perf('cache-skills');self.precacheSkills();self.perf('cache-skills', 'stop')
# Image list builders are slower
self.perf('cache-boffabilities');self.precacheBoffAbilities(limited=limited);self.perf('cache-boffabilities', 'stop')
self.perf('cache-traits');self.precacheTraits(limited=limited);self.perf('cache-traits', 'stop')
self.perf('cache-shiptraits');self.precacheShipTraits(limited=limited);self.perf('cache-shiptraits', 'stop')
self.perf('cache-equipment');self.precache_equipment_all(limited=limited);self.perf('cache-equipment', 'stop')
# Add the known equipment series [optional?]
self.logWriteBreak('precachePreload END')
def precache_equipment_all(self, limited=False):
""" Precache all known equipment types """
equipment_types = [
'Ship Fore Weapon', 'Ship Aft Weapon', 'Ship Device', 'Hangar Bay', 'Experimental',
'Ship Deflector Dish', 'Ship Secondary Deflector', 'Impulse Engine', 'Warp', 'Singularity', 'Ship Shields',
'Console', 'Ship Tactical Console', 'Ship Science Console', 'Ship Engineering Console',
'Kit Module', 'Kit Frame', 'Body Armor', 'EV Suit', 'Personal Shield', 'Ground Weapon', 'Ground Device',
]
if not limited:
for type in equipment_types:
self.precacheEquipment(type)
return
def precacheIconCleanup(self):
""" preliminary gathering for self-cleaning icon folder """
#equipment = self.searchJsonTable(self.infoboxes, "type", phrases)
boffIcons = self.cache['boffTooltips']['space'].keys()
boffIcons += self.cache['boffTooltips']['ground'].keys()
def precacheEquipmentSingle(self, name, keyPhrase, item):
"""Add an item to caches """
name = self.sanitizeEquipmentName(name)
if 'Hangar - Advanced' in name or 'Hangar - Elite' in name:
return
if not keyPhrase in self.cache['equipment']:
self.cache['equipment'][keyPhrase] = {}
self.cache['equipmentWithImages'][keyPhrase] = []
if not name in self.cache['equipment'][keyPhrase]:
self.cache['equipment'][keyPhrase][name] = item
self.cache['equipmentWithImages'][keyPhrase].append((name, self.imageFromInfoboxName(name)))
def precacheEquipment(self, keyPhrase):
"""Populate in-memory cache of ship equipment lists for faster loading"""
if not keyPhrase or keyPhrase in self.cache['equipment']:
return
additionalPhrases = []
if 'Weapon' in keyPhrase and 'Ship' in keyPhrase: additionalPhrases = ['Ship Weapon']
elif 'Console' in keyPhrase: additionalPhrases = ['Universal Console']
phrases = [keyPhrase] + additionalPhrases