-
Notifications
You must be signed in to change notification settings - Fork 433
/
ProperTree.py
executable file
·2031 lines (1879 loc) · 100 KB
/
ProperTree.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
#!/usr/bin/env python
import sys, os, binascii, base64, json, re, subprocess, webbrowser, multiprocessing, signal, ctypes
from collections import OrderedDict
try:
import Tkinter as tk
import ttk
import tkFileDialog as fd
import tkMessageBox as mb
from tkFont import Font, families
from tkColorChooser import askcolor as ac
except:
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import filedialog as fd
from tkinter import messagebox as mb
from tkinter.font import Font, families
from tkinter.colorchooser import askcolor as ac
try:
unicode
except NameError: # Python 3
unicode = str
# Add this script's dir to the local PATH var - may improve import consistency
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
from Scripts import plist, plistwindow, downloader
def _check_for_update(queue, version_url = None, user_initiated = False):
args = [sys.executable]
file_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),"Scripts","update_check.py")
if os.path.exists(file_path):
args.append(file_path)
else:
return queue.put({
"exception":"Could not locate update_check.py.",
"error":"Missing Required Files",
"user_initiated":user_initiated
})
if version_url: args.extend(["-u",version_url])
proc = subprocess.Popen(args,stdout=subprocess.PIPE)
o,e = proc.communicate()
if sys.version_info >= (3,0): o = o.decode("utf-8")
try:
json_data = json.loads(o)
# Append/update our user_initiated value
json_data["user_initiated"] = user_initiated
except:
return queue.put({
"exception":"Could not serialize returned JSON data.",
"error":"An Error Occurred Checking For Updates",
"user_initiated":user_initiated
})
queue.put(json_data)
def _update_tex(queue, tex_url = None, tex_path = None):
args = [sys.executable]
file_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),"Scripts","update_check.py")
if os.path.exists(file_path):
args.extend([file_path,"-m","tex","-t",tex_path])
else:
return queue.put({
"exception":"Could not locate update_check.py.",
"error":"Missing Required Files"
})
if tex_url: args.extend(["-u",tex_url])
proc = subprocess.Popen(args,stdout=subprocess.PIPE)
o,e = proc.communicate()
if sys.version_info >= (3,0): o = o.decode("utf-8")
try:
json_data = json.loads(o)
except:
return queue.put({
"exception":"Could not serialize returned JSON data.",
"error":"An Error Occurred Downloading Configuration.tex"
})
queue.put(json_data)
class ProperTree:
def __init__(self, plists = []):
# Create new queues for multiprocessing
self.queue = multiprocessing.Queue()
self.tex_queue = multiprocessing.Queue()
self.creating_window = False
# Create the new tk object
self.tk = tk.Tk()
self.tk.withdraw() # Try to remove before it's drawn
self.tk.title("Convert Values")
self.tk.minsize(width=640,height=130)
self.tk.resizable(True, False)
self.tk.columnconfigure(2,weight=1)
self.tk.columnconfigure(3,weight=1)
# Build the Hex <--> Base64 converter
f_label = tk.Label(self.tk, text="From:")
f_label.grid(row=0,column=0,sticky="e",padx=10,pady=10)
t_label = tk.Label(self.tk, text="To:")
t_label.grid(row=1,column=0,sticky="e",padx=10,pady=10)
# Create the settings window
self.settings_window = tk.Toplevel(self.tk)
self.settings_window.withdraw() # Try to remove before it's drawn
self.settings_window.title("ProperTree Settings")
self.settings_window.resizable(False, False)
self.settings_window.columnconfigure(0,weight=1)
self.settings_window.columnconfigure(2,weight=1)
self.settings_window.columnconfigure(4,weight=1)
self.settings_window.columnconfigure(6,weight=1)
# Set the default max undo/redo steps to retain
self.max_undo = 200
# Set up our defaults for our option lists
self.allowed_types = ("XML","Binary")
self.allowed_data = ("Hex","Base64")
self.allowed_int = ("Decimal","Hex")
self.allowed_bool = ("True/False","YES/NO","On/Off","1/0",u"\u2714/\u274c")
self.allowed_conv = ("Ascii","Base64","Decimal","Hex","Binary")
# If should_set_header_text() returns None, we're running in macOS
# with a window that does not support native dark mode. The result
# of which is that some ttk widget backgrounds do not match the
# window background. We'll try to work around that by using tk in
# those cases.
tk_or_ttk = tk if self.should_set_header_text() is None else ttk
# Left side - functional elements:
# Let's add some checkboxes and stuffs
sep_func = ttk.Separator(self.settings_window,orient="horizontal")
sep_func.grid(row=0,column=1,columnspan=2,sticky="we",padx=10,pady=10)
func_label = tk.Label(self.settings_window,text="Functionality Options:")
func_label.grid(row=0,column=0,sticky="w",padx=10,pady=10)
self.expand_on_open = tk.IntVar()
self.use_xcode_data = tk.IntVar()
self.sort_dict_keys = tk.IntVar()
self.comment_ignore_case = tk.IntVar()
self.comment_check_string = tk.IntVar()
self.force_schema = tk.IntVar()
self.expand_check = tk_or_ttk.Checkbutton(self.settings_window,text="Expand Children When Opening Plist",variable=self.expand_on_open,command=self.expand_command)
self.xcode_check = tk_or_ttk.Checkbutton(self.settings_window,text="Use Xcode-Style <data> Tags (Inline) in XML Plists",variable=self.use_xcode_data,command=self.xcode_command)
self.sort_check = tk_or_ttk.Checkbutton(self.settings_window,text="Ignore Dictionary Key Order",variable=self.sort_dict_keys,command=self.sort_command)
self.ignore_case_check = tk_or_ttk.Checkbutton(self.settings_window,text="Ignore Case When Stripping Comments",variable=self.comment_ignore_case,command=self.ignore_case_command)
self.check_string_check = tk_or_ttk.Checkbutton(self.settings_window,text="Check String Values When Stripping Comments",variable=self.comment_check_string,command=self.check_string_command)
self.expand_check.grid(row=1,column=0,columnspan=3,sticky="w",padx=10)
self.xcode_check.grid(row=2,column=0,columnspan=3,sticky="w",padx=10)
self.sort_check.grid(row=3,column=0,columnspan=3,sticky="w",padx=10)
self.ignore_case_check.grid(row=4,column=0,columnspan=3,sticky="w",padx=10)
self.check_string_check.grid(row=5,column=0,columnspan=3,sticky="w",padx=10)
comment_prefix_label = tk.Label(self.settings_window,text="Comment Prefix (default is #):")
comment_prefix_label.grid(row=6,column=0,sticky="w",padx=10)
self.comment_prefix_text = plistwindow.EntryPlus(self.settings_window,self.tk,self)
self.comment_prefix_text.grid(row=6,column=1,columnspan=2,sticky="we",padx=10)
self.plist_type_string = tk.StringVar(self.settings_window)
self.plist_type_menu = tk_or_ttk.OptionMenu(self.settings_window, self.plist_type_string, *self.get_option_menu_list(self.allowed_types), command=self.change_plist_type)
plist_label = tk.Label(self.settings_window,text="Default New Plist Type:")
plist_label.grid(row=7,column=0,sticky="w",padx=10)
self.plist_type_menu.grid(row=7,column=1,columnspan=2,sticky="we",padx=10)
self.data_type_string = tk.StringVar(self.settings_window)
self.data_type_menu = tk_or_ttk.OptionMenu(self.settings_window, self.data_type_string, *self.get_option_menu_list(self.allowed_data), command=self.change_data_type)
data_label = tk.Label(self.settings_window,text="Data Display Default:")
data_label.grid(row=8,column=0,sticky="w",padx=10)
self.data_type_menu.grid(row=8,column=1,columnspan=2,sticky="we",padx=10)
self.int_type_string = tk.StringVar(self.settings_window)
self.int_type_menu = tk_or_ttk.OptionMenu(self.settings_window, self.int_type_string, *self.get_option_menu_list(self.allowed_int), command=self.change_int_type)
int_label = tk.Label(self.settings_window,text="Integer Display Default:")
int_label.grid(row=9,column=0,sticky="w",padx=10)
self.int_type_menu.grid(row=9,column=1,columnspan=2,sticky="we",padx=10)
self.bool_type_string = tk.StringVar(self.settings_window)
self.bool_type_menu = tk_or_ttk.OptionMenu(self.settings_window, self.bool_type_string, *self.get_option_menu_list(self.allowed_bool), command=self.change_bool_type)
bool_label = tk.Label(self.settings_window,text="Boolean Display Default:")
bool_label.grid(row=10,column=0,sticky="w",padx=10)
self.bool_type_menu.grid(row=10,column=1,columnspan=2,sticky="we",padx=10)
self.snapshot_string = tk.StringVar(self.settings_window)
self.snapshot_menu = tk_or_ttk.OptionMenu(self.settings_window, self.snapshot_string, "Auto-detect", command=self.change_snapshot_version)
snapshot_label = tk.Label(self.settings_window,text="OC Snapshot Target Version:")
snapshot_label.grid(row=11,column=0,sticky="w",padx=10)
self.snapshot_menu.grid(row=11,column=1,columnspan=2,sticky="we",padx=10)
self.schema_check = tk_or_ttk.Checkbutton(self.settings_window,text="Force Update Snapshot Schema",variable=self.force_schema,command=self.schema_command)
self.schema_check.grid(row=12,column=0,columnspan=3,sticky="w",padx=10)
self.mod_check = tk.IntVar()
self.enable_mod_check = tk_or_ttk.Checkbutton(self.settings_window,text="Warn If Files Are Externally Modified",variable=self.mod_check,command=self.mod_check_command)
self.enable_mod_check.grid(row=13,column=0,columnspan=3,stick="w",padx=10)
self.first_check = tk.IntVar()
self.enable_first_check = tk_or_ttk.Checkbutton(self.settings_window,text="Enter Edits Values Before Keys Where Possible",variable=self.first_check,command=self.first_check_command)
self.enable_first_check.grid(row=14,column=0,columnspan=3,stick="w",padx=10)
self.enable_drag_and_drop = tk.BooleanVar()
self.toggle_drag_drop = tk_or_ttk.Checkbutton(self.settings_window,text="Enable Row Drag & Drop", variable=self.enable_drag_and_drop,command=self.drag_drop_command)
self.toggle_drag_drop.grid(row=15,column=0,columnspan=3,sticky="w",padx=10)
self.drag_label = tk.Label(self.settings_window,text="Drag Dead Zone (1-100 pixels):")
self.drag_label.grid(row=16,column=0,sticky="w",padx=10)
self.drag_pixels = tk.Label(self.settings_window,text="20")
self.drag_pixels.grid(row=16,column=1,sticky="w",padx=(10,0))
self.drag_scale = tk_or_ttk.Scale(self.settings_window,from_=1,to=100,orient=tk.HORIZONTAL,command=self.scale_command)
# Try to hide the value if using tk - will throw an exception in ttk
try: self.drag_scale.configure(showvalue=False)
except tk.TclError: pass
self.drag_scale.grid(row=16,column=2,sticky="we",padx=(0,10))
self.drag_disabled = tk.Label(self.settings_window,text="[ Drag & Drop Disabled ]")
self.drag_disabled.configure(state="disabled")
self.drag_disabled.grid(row=16,column=1,columnspan=2,sticky="we",padx=10)
undo_max_label = tk.Label(self.settings_window,text="Max Undo (0=unlim, {}=default):".format(self.max_undo))
undo_max_label.grid(row=17,column=0,sticky="w",padx=10)
self.undo_max_text = plistwindow.EntryPlus(self.settings_window,self.tk,self)
self.undo_max_text.grid(row=17,column=1,columnspan=2,sticky="we",padx=10)
# Left/right separator:
sep = ttk.Separator(self.settings_window,orient="vertical")
sep.grid(row=1,column=3,rowspan=17,sticky="ns",padx=10)
# Right side - theme elements:
t_func = ttk.Separator(self.settings_window,orient="horizontal")
t_func.grid(row=0,column=5,columnspan=2,sticky="we",padx=10,pady=10)
tfunc_label = tk.Label(self.settings_window,text="Appearance Options:")
tfunc_label.grid(row=0,column=4,sticky="w",padx=10,pady=10)
self.op_label = tk.Label(self.settings_window,text="Window Opacity (25-100%):")
self.op_label.grid(row=1,column=4,sticky="w",padx=10)
self.op_perc = tk.Label(self.settings_window,text="100")
self.op_perc.grid(row=1,column=5,sticky="w",padx=(10,0))
self.op_scale = tk_or_ttk.Scale(self.settings_window,from_=25,to=100,orient=tk.HORIZONTAL,command=self.update_opacity)
# Try to hide the value if using tk - will throw an exception in ttk
try: self.op_scale.configure(showvalue=False)
except tk.TclError: pass
self.op_scale.grid(row=1,column=6,sticky="we",padx=10)
r4_label = tk.Label(self.settings_window,text="Highlight Color:")
r4_label.grid(row=2,column=4,sticky="w",padx=10)
self.hl_canvas = tk.Canvas(self.settings_window, height=20, width=30, background="black", relief="groove", bd=2)
self.hl_canvas.grid(row=2,column=5,columnspan=2,sticky="we",padx=10)
r1_label = tk.Label(self.settings_window,text="Alternating Row Color #1:")
r1_label.grid(row=3,column=4,sticky="w",padx=10)
self.r1_canvas = tk.Canvas(self.settings_window, height=20, width=30, background="black", relief="groove", bd=2)
self.r1_canvas.grid(row=3,column=5,columnspan=2,sticky="we",padx=10)
r2_label = tk.Label(self.settings_window,text="Alternating Row Color #2:")
r2_label.grid(row=4,column=4,sticky="w",padx=10)
self.r2_canvas = tk.Canvas(self.settings_window, height=20, width=30, background="black", relief="groove", bd=2)
self.r2_canvas.grid(row=4,column=5,columnspan=2,sticky="we",padx=10)
r3_label = tk.Label(self.settings_window,text="Column Header/BG Color:")
r3_label.grid(row=5,column=4,sticky="w",padx=10)
self.bg_canvas = tk.Canvas(self.settings_window, height=20, width=30, background="black", relief="groove", bd=2)
self.bg_canvas.grid(row=5,column=5,columnspan=2,sticky="we",padx=10)
self.ig_bg_check = tk.IntVar()
self.ig_bg = tk_or_ttk.Checkbutton(self.settings_window,text="Header Text Ignores BG Color",variable=self.ig_bg_check,command=self.check_ig_bg_command)
self.ig_bg.grid(row=6,column=4,sticky="w",padx=10)
self.bg_inv_check = tk.IntVar()
self.bg_inv = tk_or_ttk.Checkbutton(self.settings_window,text="Invert Header Text Color",variable=self.bg_inv_check,command=self.check_bg_invert_command)
self.bg_inv.grid(row=6,column=5,columnspan=2,sticky="w",padx=10)
self.r1_inv_check = tk.IntVar()
self.r1_inv = tk_or_ttk.Checkbutton(self.settings_window,text="Invert Row #1 Text Color",variable=self.r1_inv_check,command=self.check_r1_invert_command)
self.r1_inv.grid(row=7,column=5,columnspan=2,sticky="w",padx=10)
self.r2_inv_check = tk.IntVar()
self.r2_inv = tk_or_ttk.Checkbutton(self.settings_window,text="Invert Row #2 Text Color",variable=self.r2_inv_check,command=self.check_r2_invert_command)
self.r2_inv.grid(row=8,column=5,columnspan=2,sticky="w",padx=10)
self.hl_inv_check = tk.IntVar()
self.hl_inv = tk_or_ttk.Checkbutton(self.settings_window,text="Invert Highlight Text Color",variable=self.hl_inv_check,command=self.check_hl_invert_command)
self.hl_inv.grid(row=9,column=5,columnspan=2,sticky="w",padx=10)
self.default_font = Font(font='TkTextFont')
self.custom_font = tk.IntVar()
self.font_check = tk_or_ttk.Checkbutton(self.settings_window,text="Use Custom Font Size",variable=self.custom_font,command=self.font_command)
self.font_string = tk.StringVar()
self.font_spinbox = tk.Spinbox(self.settings_window,from_=1,to=128,textvariable=self.font_string)
try:
self.font_string.trace_add("write",self.update_font)
except AttributeError:
self.font_string.trace("w",self.update_font)
self.font_check.grid(row=10,column=4,sticky="w",padx=10)
self.font_spinbox.grid(row=10,column=5,columnspan=2,sticky="we",padx=10)
# Custom font picker - wacky implementation.
self.font_var = tk.IntVar()
self.font_family = tk.StringVar()
self.font_custom_check = tk_or_ttk.Checkbutton(self.settings_window,text="Use Custom Font",variable=self.font_var,command=self.font_select)
self.font_custom = ttk.Combobox(self.settings_window,state="readonly",textvariable=self.font_family,values=sorted(families()))
self.font_custom.bind('<<ComboboxSelected>>',self.font_pick)
try:
self.font_family.trace_add("write",self.update_font_family)
except AttributeError:
self.font_family.trace("w",self.update_font_family)
self.font_custom_check.grid(row=11,column=4,stick="w",padx=10)
self.font_custom.grid(row=11,column=5,columnspan=2,sticky="we",padx=10)
r5_label = tk.Label(self.settings_window,text="Restore Appearance Defaults:")
r5_label.grid(row=12,column=4,sticky="w",padx=10)
dt_func = ttk.Separator(self.settings_window,orient="horizontal")
dt_func.grid(row=12,column=5,columnspan=2,sticky="we",padx=10)
default_font = tk_or_ttk.Button(self.settings_window,text="Font Defaults",command=self.font_defaults)
default_font.grid(row=13,column=4,sticky="we",padx=10)
default_high = tk_or_ttk.Button(self.settings_window,text="Highlight Color",command=lambda:self.swap_colors("highlight"))
default_high.grid(row=14,column=4,sticky="we",padx=10)
default_light = tk_or_ttk.Button(self.settings_window,text="Light Mode Colors",command=lambda:self.swap_colors("light"))
default_light.grid(row=13,column=5,columnspan=2,sticky="we",padx=10)
default_dark = tk_or_ttk.Button(self.settings_window,text="Dark Mode Colors",command=lambda:self.swap_colors("dark"))
default_dark.grid(row=14,column=5,columnspan=2,sticky="we",padx=10)
sep_theme = ttk.Separator(self.settings_window,orient="horizontal")
sep_theme.grid(row=18,column=0,columnspan=7,sticky="we",padx=10,pady=(10,0))
# Add the check for updates checkbox and button
self.update_int = tk.IntVar()
self.update_check = tk_or_ttk.Checkbutton(self.settings_window,text="Check For Updates At Start",variable=self.update_int,command=self.update_command)
self.update_check.grid(row=19,column=0,sticky="w",padx=10,pady=(5,0))
self.notify_once_int = tk.IntVar()
self.notify_once_check = tk_or_ttk.Checkbutton(self.settings_window,text="Only Notify Once Per Version",variable=self.notify_once_int,command=self.notify_once)
self.notify_once_check.grid(row=20,column=0,sticky="w",padx=10,pady=(0,10))
self.update_button = tk_or_ttk.Button(self.settings_window,text="Check Now",command=lambda:self.check_for_updates(user_initiated=True))
self.update_button.grid(row=20,column=1,columnspan=2,sticky="w",padx=10,pady=(0,10))
self.tex_button = tk_or_ttk.Button(self.settings_window,text="Get Configuration.tex",command=self.get_latest_tex)
self.tex_button.grid(row=20,column=4,sticky="we",padx=10,pady=(0,10))
reset_settings = tk_or_ttk.Button(self.settings_window,text="Restore All Defaults",command=self.reset_settings)
reset_settings.grid(row=20,column=5,columnspan=2,sticky="we",padx=10,pady=(0,10))
# Setup the color picker click methods
self.r1_canvas.bind("<ButtonRelease-1>",lambda x:self.pick_color("alternating_color_1",self.r1_canvas))
self.r2_canvas.bind("<ButtonRelease-1>",lambda x:self.pick_color("alternating_color_2",self.r2_canvas))
self.hl_canvas.bind("<ButtonRelease-1>",lambda x:self.pick_color("highlight_color",self.hl_canvas))
self.bg_canvas.bind("<ButtonRelease-1>",lambda x:self.pick_color("background_color",self.bg_canvas))
# Setup some canvas connections
self.canvas_connect = {
self.bg_canvas: {"invert":self.bg_inv_check},
self.r1_canvas: {"invert":self.r1_inv_check},
self.r2_canvas: {"invert":self.r2_inv_check},
self.hl_canvas: {"invert":self.hl_inv_check}
}
self.default_dark = {
"alternating_color_1":"#161616",
"alternating_color_2":"#202020",
"highlight_color":"#1E90FF",
"background_color":"#161616",
"invert_background_text_color":False,
"invert_row1_text_color":False,
"invert_row2_text_color":False
}
self.default_light = {
"alternating_color_1":"#F0F1F1",
"alternating_color_2":"#FEFEFE",
"highlight_color":"#1E90FF",
"background_color":"#FEFEFE",
"invert_background_text_color":False,
"invert_row1_text_color":False,
"invert_row2_text_color":False
}
# Setup the from/to option menus
self.f_title = tk.StringVar(self.tk)
self.t_title = tk.StringVar(self.tk)
f_option = tk_or_ttk.OptionMenu(self.tk, self.f_title, *self.get_option_menu_list(self.allowed_conv), command=self.change_from_type)
t_option = tk_or_ttk.OptionMenu(self.tk, self.t_title, *self.get_option_menu_list(self.allowed_conv), command=self.change_to_type)
f_option.grid(row=0,column=1,sticky="we")
t_option.grid(row=1,column=1,sticky="we")
self.f_text = plistwindow.EntryPlus(self.tk,self.tk,self)
self.f_text.delete(0,tk.END)
self.f_text.insert(0,"")
self.f_text.grid(row=0,column=2,columnspan=3,sticky="we",padx=10,pady=10)
self.t_text = plistwindow.EntryPlus(self.tk,self.tk,self)
self.t_text.configure(state='normal')
self.t_text.delete(0,tk.END)
self.t_text.insert(0,"")
self.t_text.configure(state='readonly')
self.t_text.grid(row=1,column=2,columnspan=3,sticky="we",padx=10,pady=10)
self.c_button = tk_or_ttk.Button(self.tk, text="Convert", command=self.convert_values)
self.c_button.grid(row=2,column=4,sticky="e",padx=10,pady=10)
self.s_button = tk_or_ttk.Button(self.tk, text="To <--> From", command=self.swap_convert)
self.s_button.grid(row=2,column=0,columnspan=2,sticky="w",padx=10,pady=10)
self.f_text.bind("<Return>", self.convert_values)
self.f_text.bind("<KP_Enter>", self.convert_values)
self.start_window = None
# Regex to find the processor serial numbers when
# opened from the Finder
self.regexp = re.compile(r"^-psn_[0-9]+_[0-9]+$")
# Setup the menu-related keybinds - and change the app name if needed
key="Control"
sign = "Ctrl+"
self.use_dark = self.get_dark()
if str(sys.platform) == "darwin":
# Remap the quit function to our own
self.tk.createcommand('::tk::mac::Quit', self.quit)
self.tk.createcommand("::tk::mac::OpenDocument", self.open_plist_from_app)
self.tk.createcommand("::tk::mac::ShowPreferences", lambda:self.show_window(self.settings_window))
# Import the needed modules to change the bundle name and force focus
try:
from Foundation import NSBundle
from Cocoa import NSRunningApplication, NSApplicationActivateIgnoringOtherApps
app = NSRunningApplication.runningApplicationWithProcessIdentifier_(os.getpid())
app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)
bundle = NSBundle.mainBundle()
if bundle:
info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
if info and info['CFBundleName'] == 'Python':
info['CFBundleName'] = "ProperTree"
except:
pass
key="Command"
sign=key+"+"
self.tk.protocol("WM_DELETE_WINDOW", lambda x=self.tk: self.close_window(window=x))
self.settings_window.protocol("WM_DELETE_WINDOW", lambda x=self.settings_window: self.close_window(window=x))
self.default_windows = (self.tk,self.settings_window)
self.recent_menu = None
if str(sys.platform) == "darwin":
# Setup the top level menu
file_menu = tk.Menu(self.tk)
main_menu = tk.Menu(self.tk)
self.recent_menu = tk.Menu(self.tk)
main_menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="New (Cmd+N)", command=self.new_plist)
file_menu.add_command(label="Open (Cmd+O)", command=self.open_plist)
file_menu.add_cascade(label="Open Recent", menu=self.recent_menu, command=self.open_recent)
file_menu.add_command(label="Save (Cmd+S)", command=self.save_plist)
file_menu.add_command(label="Save As... (Cmd+Shift+S)", command=self.save_plist_as)
file_menu.add_command(label="Duplicate (Cmd+D)", command=self.duplicate_plist)
file_menu.add_command(label="Reload From Disk (Cmd+L)", command=self.reload_from_disk)
file_menu.add_separator()
file_menu.add_command(label="OC Snapshot (Cmd+R)", command=self.oc_snapshot)
file_menu.add_command(label="OC Clean Snapshot (Cmd+Shift+R)", command=self.oc_clean_snapshot)
file_menu.add_separator()
file_menu.add_command(label="Convert Window (Cmd+T)", command=lambda:self.show_window(self.tk))
file_menu.add_command(label="Strip Comments (Cmd+M)", command=self.strip_comments)
file_menu.add_command(label="Strip Disabled Entries (Cmd+E)", command=self.strip_disabled)
file_menu.add_separator()
file_menu.add_command(label="Settings (Cmd+,)",command=lambda:self.show_window(self.settings_window))
file_menu.add_separator()
file_menu.add_command(label="Toggle Find/Replace Pane (Cmd+F)",command=self.hide_show_find)
file_menu.add_command(label="Toggle Plist/Data/Int Type Pane (Cmd+P)",command=self.hide_show_type)
file_menu.add_separator()
file_menu.add_command(label="Quit (Cmd+Q)", command=self.quit)
self.tk.config(menu=main_menu)
# Set bindings
# on at least macOS, tk 8.5 works with <Command-Z>, but 8.6 requires <Shift-Command-z>
# Can be bypassed by including both Shift and the capital letter
self.tk.bind("<{}-w>".format(key), self.close_window)
self.settings_window.bind("<{}-w>".format(key), self.close_window)
self.tk.bind_all("<{}-n>".format(key), self.new_plist)
self.tk.bind_all("<{}-o>".format(key), self.open_plist)
self.tk.bind_all("<{}-s>".format(key), self.save_plist)
self.tk.bind_all("<{}-Shift-S>".format(key), self.save_plist_as)
self.tk.bind_all("<{}-d>".format(key), self.duplicate_plist)
self.tk.bind_all("<{}-t>".format(key), lambda event, x=self.tk: self.show_window(x))
self.tk.bind_all("<{}-z>".format(key), self.undo)
self.tk.bind_all("<{}-Shift-Z>".format(key), self.redo)
self.tk.bind_all("<{}-m>".format(key), self.strip_comments)
self.tk.bind_all("<{}-e>".format(key), self.strip_disabled)
self.tk.bind_all("<{}-r>".format(key), self.oc_snapshot)
self.tk.bind_all("<{}-Shift-R>".format(key), self.oc_clean_snapshot)
self.tk.bind_all("<{}-l>".format(key), self.reload_from_disk)
if not str(sys.platform) == "darwin":
# Rewrite the default Command-Q command
self.tk.bind_all("<{}-q>".format(key), self.quit)
self.tk.bind_all("<{}-comma>".format(key), lambda event, x=self.settings_window:self.show_window(x))
self.tk.bind("<KeyPress>", self.handle_keypress)
self.settings_window.bind("<KeyPress>", self.handle_keypress)
cwd = os.getcwd()
os.chdir(os.path.abspath(os.path.dirname(__file__)))
#
# Load the settings - current available settings are:
#
# last_window_width: width value (default is 640)
# last_window_height: height value (default is 480)
# expand_all_items_on_open: bool
# sort_dict: bool, false = OrderedDict
# xcode_data: bool, true = <data>XXXX</data>, false = different lines
# comment_strip_prefix: string, defaults to #
# comment_strip_ignore_case: bool, true = ignore case when stripping comments
# comment_strip_check_string: bool, true = consider string values as well as keys
# new_plist_default_type: string, XML/Binary
# display_data_as: string, Hex/Base64
# display_int_as: string, Decimal/Hex
# snapshot_version: string, X.X.X version number, or Latest
# force_snapshot_schema: bool
# alternating_color_1: string, Dark: #161616 - Light: #F0F1F1
# alternating_color_2: string, Dark: #202020 - Light: #FEFEFE
# highlight_color: string, Dark: #1E90FF - Light: #1E90FF
# background_color: string, Dark: #161616 - Light: #FEFEFE
# header_text_ignore_bg_color: bool
# invert_background_text_color: bool
# invert_row1_text_color: bool
# invert_row2_text_color: bool
# invert_hl_text_color: bool
# warn_if_modified: bool
# edit_values_before_keys: bool
# enable_drag_and_drop: bool
# drag_dead_zone: pixel distance before drag starts (default is 20)
# open_recent: list, paths recently opened
# recent_max: int, max number of recent items
# max_undo: int, max undo history - 0 = unlimited
# check_for_updates_at_startup: bool
# notify_once_per_version: bool
# last_version_checked: str
# opacity int, 10-100 (default is 100)
#
self.settings = {}
if os.path.exists("Scripts/settings.json"):
try:
self.settings = json.load(open("Scripts/settings.json"))
except:
pass
# Also load the snapshot defaults
self.snapshot_data = {}
if os.path.exists("Scripts/snapshot.plist"):
try:
with open("Scripts/snapshot.plist","rb") as f:
self.snapshot_data = plist.load(f)
except:
pass
# And finally, load the version.json if it exists
self.version = {}
if os.path.exists("Scripts/version.json"):
try: self.version = json.load(open("Scripts/version.json"))
except: pass
os.chdir(cwd)
# Apply the version to the update and tex buttons
self.reset_update_button()
self.reset_tex_button()
# Setup the settings page to reflect our settings.json file
self.update_settings()
self.case_insensitive = self.get_case_insensitive()
# Normalize the pathing for Open Recents
self.normpath_recents()
if str(sys.platform) == "darwin": self.update_recents()
self.check_dark_mode()
self.version_url = "https://raw.githubusercontent.com/corpnewt/ProperTree/master/Scripts/version.json"
self.tex_url = "https://raw.githubusercontent.com/acidanthera/OpenCorePkg/master/Docs/Configuration.tex"
self.repo_url = "https://github.com/corpnewt/ProperTree"
# Windows running python 2 seems to have issues with multiprocessing
# if the case of the main script's name is incorrect:
# e.g. Downloader.py vs downloader.py
#
# To work around this, we try to scrape for the correct case if
# possible.
try:
path = os.path.abspath(sys.modules["__main__"].__file__)
if os.path.isfile(path):
name = os.path.basename(path).lower()
fldr = os.path.dirname(path)
for f in os.listdir(fldr):
if f.lower() == name:
sys.modules["__main__"].__file__ = os.path.join(fldr,f)
break
except AttributeError as e:
# This likely means we're running from the interpreter directly
pass
# Implement a simple boolean lock, and check for updates if needed
self.is_checking_for_updates = False
if self.settings.get("check_for_updates_at_startup",True):
self.tk.after(0, lambda:self.check_for_updates(user_initiated=False))
# Prior implementations tried to wait 250ms to give open_plist_from_app()
# enough time to parse anything double-clicked. The issue was that both
# check_open() and open_plist_from_app() would fire at roughly the same
# time - resulting in one opening a blank doc, and the other opening the
# double-clicked plist(s). We now use the is_opening lock to determine
# if one function is currently working - and the other will check in 5ms
# intervals until the lock is lifted before processing. This allows us
# to overtake a blank doc opened by one with the other - hopefully fixing
# the issue of multiple documents spawning on double-click in macOS.
self.is_opening = False
self.is_quitting = False
self.check_open(plists)
# Set up a signal handler for SIGINT that pipes to our quit() function
signal.signal(signal.SIGINT,self.quit)
# Set up our event loop "poker" to keep the event loop processing
self.tk.after(200,self.sigint_check)
# Set our titlebar colors
for w in (self.tk, self.settings_window):
self.set_win_titlebar(windows=w)
# Start our run loop
tk.mainloop()
def _clipboard_append(self, clipboard_string = None):
# Tkinter has issues copying to the system clipboard as evident in this bug report:
# https://bugs.python.org/issue40452
#
# There are some workarounds that require compiling a new tk binary - but we can
# ensure the system clipboard is updated by calling either clip or pbcopy depending
# on the current OS.
#
# First we clear the tkinter clipboard
self.tk.clipboard_clear()
# Only write to the tkinter clipboard if we have a value
if clipboard_string: self.tk.clipboard_append(clipboard_string)
else: clipboard_string = "" # Ensure we have at least an empty string
# Gather our args for the potential clipboard commands Windows -> macOS -> Linux
for args in (["clip"],) if os.name=="nt" else (["pbcopy"],) if sys.platform=="darwin" else (["xclip","-sel","c"],["xsel","-ib"],):
# Try to start a subprocess to mirror the tkinter clipboard contents
try:
clipboard = subprocess.Popen(
args,
stdin=subprocess.PIPE,
stderr=getattr(subprocess,"DEVNULL",open(os.devnull,"w")),
stdout=getattr(subprocess,"DEVNULL",open(os.devnull,"w"))
)
except:
continue
# Dirty py2 check to see if we need to encode the data or not
clipboard.stdin.write(clipboard_string if 2/3==0 else clipboard_string.encode())
clipboard.stdin.flush() # Flush the buffer
clipboard.stdin.close() # Close the pipe
break # Break out of the loop as needed
def sigint_check(self):
# Helper to keep the event loop moving in order to ensure we can catch
# KeyboardInterrupts as needed
self.tk.after(200,self.sigint_check)
def get_case_insensitive(self):
# Helper function to check our file path, change case, and see if os.path.exists() still works
our_path = os.path.abspath(__file__)
# Walk our chars and find the first alpha character
# then reverse it's case - and see if the path still exists
for i,x in enumerate(our_path):
if x.isalpha():
x = x.upper() if x.islower() else x.lower()
return os.path.exists(our_path[:i]+x+our_path[i+1:])
# If we got here - there were no alpha chars in the path - we'll just uh... return False to be safe
return False
def check_dark_mode(self):
check_dark = self.get_dark()
if check_dark != self.use_dark and any((x not in self.settings for x in ("alternating_color_1","alternating_color_2","background_color"))):
# Mode changed
# Update colors as needed
color_check = [x for x in self.default_dark if not x in self.settings]
if color_check: # We have something to animate
color_list = []
from_dict,to_dict = (self.default_dark,self.default_light) if self.use_dark \
else (self.default_light,self.default_dark)
for name in color_check:
if name.startswith("invert_"):
continue # Skip boolean checks
color_list.append((
name,
from_dict[name],
to_dict[name]
))
# Queue up the animations
self.color_animate(color_list)
self.use_dark = check_dark
if os.name == "nt":
# Iterate all the windows
self.set_win_titlebar()
# Continue the loop every 3 seconds
self.tk.after(1500, lambda:self.check_dark_mode())
def set_win_titlebar(self, windows=None, mode=None):
if not os.name == "nt":
return # Only change on Windows
if windows is None:
windows = self.stackorder(self.tk, include_defaults=True)
elif not isinstance(windows,(list,tuple)):
windows = [windows]
try:
# Set up the values
if mode is None:
mode = int(self.use_dark)
value = ctypes.c_int(mode) # Mode is 0 for light, 1 for dark
# Configure the window attributes
DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 = 19
DWMWA_USE_IMMERSIVE_DARK_MODE = 20
set_window_attribute = ctypes.windll.dwmapi.DwmSetWindowAttribute
get_parent = ctypes.windll.user32.GetParent
except:
# Something went wrong - bail
return
for window in windows:
try:
# Update the window
window.update()
hwnd_inst = get_parent(window.winfo_id())
set_window_attribute(hwnd_inst, DWMWA_USE_IMMERSIVE_DARK_MODE, ctypes.byref(value),
ctypes.sizeof(value))
set_window_attribute(hwnd_inst, DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1, ctypes.byref(value),
ctypes.sizeof(value))
# Update the Window size to ensure the changes happen
for x in (1,-1):
window.geometry("{}x{}".format(
window.winfo_width()+x,
window.winfo_height()+x
))
window.update()
except:
# Something went wrong - but this is cosmetic only,
# so we just continue on as normal
continue
def color_animate(self, colors, step=1, steps=5, delay=35):
for name,start,end in colors:
# Get the start and end as ints #rrggbb
start_r = int(start[1:3],16)
start_g = int(start[3:5],16)
start_b = int(start[5:7],16)
end_r = int(end[1:3],16)
end_g = int(end[3:5],16)
end_b = int(end[5:7],16)
# Get and apply the steps
r_now = int((((end_r-start_r)/steps)*step)+start_r)
g_now = int((((end_g-start_g)/steps)*step)+start_g)
b_now = int((((end_b-start_b)/steps)*step)+start_b)
# Set our target color
result = "#{}{}{}".format(
hex(r_now)[2:].upper(),
hex(g_now)[2:].upper(),
hex(b_now)[2:].upper()
)
self.settings[name] = result
# Update the windows
if step < steps:
self.update_canvases()
self.tk.after(delay, lambda:self.color_animate(
colors, step=step+1, steps=steps, delay=delay
))
else:
# Remove the adjusted colors from the settings
for c in colors:
self.settings.pop(c[0],None)
self.update_settings()
def get_option_menu_list(self, option_list):
# Helper to return OptionMenu lists depending on whether
# we're using tk or ttk. The latter requires the default
# element listed - for which we'll just pick the first
# element in the option_list
if self.should_set_header_text() is None:
# This should only happen on macOS when the window
# doesn't support native dark mode - this results in
# the background of some ttk widgets not matching the
# window background
return option_list
# We should be using ttk, which requires the default element
# before the options
return [option_list[0]]+list(option_list)
def should_set_header_text(self):
# In macOS, the header colors are only affected by the background
# when in dark mode on specific python build
# We'll try to get the system's actual dark mode here
if str(sys.platform) != "darwin": return True # Don't make changes on Windows/Linux
try:
# Ask the window if it's in dark mode - only works when supported
return bool(self.tk.call("tk::unsupported::MacWindowStyle","isdark",self.tk))
except Exception as e:
return None # If this fails, window doesn't support dark mode
def get_dark(self):
if os.name=="nt":
# Get the registry entry to tell us if we're in dark/light mode
p = subprocess.Popen(["reg","query","HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize","/v","AppsUseLightTheme"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
c = p.communicate()
return c[0].decode("utf-8", "ignore").strip().lower().split(" ")[-1] in ("","0x0")
elif str(sys.platform) != "darwin":
return True # Default to dark mode on Linux platforms
# Get the macOS version - and see if dark mode is a thing
p = subprocess.Popen(["sw_vers","-productVersion"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
c = p.communicate()
p_vers = c[0].decode("utf-8", "ignore").strip().lower()
if p_vers < "10.14.0": return True # Default to dark on anything prior to
# At this point - we have an OS that supports dark mode, let's check our value
p = subprocess.Popen(["defaults","read","-g","AppleInterfaceStyle"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
c = p.communicate()
return c[0].decode("utf-8", "ignore").strip().lower() == "dark"
def compare_version(self, v1, v2):
# Splits the version numbers by periods and compare each value
# Allows 0.0.10 > 0.0.9 where normal string comparison would return false
# Also strips out any non-numeric values from each segment to avoid conflicts
#
# Returns True if v1 > v2, None if v1 == v2, and False if v1 < v2
if not all((isinstance(x,str) for x in (v1,v2))):
# Wrong types
return False
v1_seg = v1.split(".")
v2_seg = v2.split(".")
# Pad with 0s to ensure common length
v1_seg += ["0"]*(len(v2_seg)-len(v1_seg))
v2_seg += ["0"]*(len(v1_seg)-len(v2_seg))
# Compare each segment - stripping non-numbers as needed
for i in range(len(v1_seg)):
a,b = v1_seg[i],v2_seg[i]
try: a = int("".join([x for x in a if x.isdigit()]))
except: a = 0
try: b = int("".join([x for x in b if x.isdigit()]))
except: b = 0
if a > b: return True
if a < b: return False
# If we're here, both versions are the same
return None
def check_for_updates(self, user_initiated = False):
if self.is_checking_for_updates: # Already checking
if user_initiated:
# We pressed the button - but another check is in progress
self.tk.bell()
mb.showerror("Already Checking For Updates","An update check is already in progress. If you consistently get this error when manually checking for updates - it may indicate a netowrk issue.")
self.lift_window()
return
self.is_checking_for_updates = True # Lock out other update checks
self.update_button.configure(
state="disabled",
text="Checking... ({})".format(self.version.get("version","?.?.?"))
)
# We'll leverage multiprocessing to avoid UI locks if the update checks take too long
p = multiprocessing.Process(target=_check_for_update,args=(self.queue,self.version_url,user_initiated))
p.daemon = True
p.start()
self.check_update_process(p)
def reset_update_button(self):
self.update_button.configure(
state="normal",
text="Check Now ({})".format(self.version.get("version","?.?.?"))
)
def check_update_process(self, p):
# Helper to watch until an update is done
if p.is_alive():
self.tk.after(100,self.check_update_process,p)
return
# Join the process to ensure resources are returned
p.join()
# We've returned - reset our bool lock
self.is_checking_for_updates = False
# Check if we got anything from the queue
if self.queue.empty(): # Nothing in the queue, bail
return self.reset_update_button()
# Retrieve any returned value and parse
output_dict = self.queue.get()
user_initiated = output_dict.get("user_initiated",False)
# Check if we got an error or exception
if "exception" in output_dict or "error" in output_dict:
error = output_dict.get("error","An Error Occurred Checking For Updates")
excep = output_dict.get("exception","Something went wrong when checking for updates.")
if user_initiated:
self.tk.bell()
mb.showerror(error,excep)
self.lift_window()
return self.reset_update_button()
# Parse the output returned
version_dict = output_dict.get("json",{})
if not version_dict.get("version"):
if user_initiated:
self.tk.bell()
mb.showerror("An Error Occurred Checking For Updates","Data returned was malformed or nonexistent.")
self.lift_window()
return self.reset_update_button()
# At this point - we should have json data containing the version key/value
check_version = str(version_dict["version"]).lower()
our_version = str(self.version.get("version","0.0.0")).lower()
notify_once = self.settings.get("notify_once_per_version",True)
last_version = str(self.settings.get("last_version_checked","0.0.0")).lower()
if self.compare_version(check_version,our_version) is True:
if notify_once and last_version == check_version and not user_initiated:
# Already notified about this version - ignore
return self.reset_update_button()
# Save the last version checked
self.settings["last_version_checked"] = check_version
# We got an update we're not ignoring - let's prompt
self.tk.bell()
result = mb.askyesno(
title="New ProperTree Version Available",
message="Version {} is available (currently on {}).\n\nWhat's new in {}:\n{}\n\nVisit ProperTree's github repo now?".format(
check_version,
our_version,
check_version,
version_dict.get("changes","No changes listed.")
)
)
if result: # Open the url in the default browser
webbrowser.open(self.repo_url)
elif user_initiated:
# No new updates - but we need to tell the user
mb.showinfo(
title="No Updates Available",
message="You are currently running the latest version of ProperTree ({}).".format(our_version)
)
else:
# Nothing to notify about - and not user initiated
return self.reset_update_button()
# Reset the update button after notifying
self.reset_update_button()
# If we got here - we displayed some message, let's lift our window to the top
self.lift_window()
def get_best_tex_path(self):
pt_path = os.path.abspath(os.path.dirname(__file__))
# Add a check for next to the script
config_tex_paths = [os.path.join(pt_path,"Configuration.tex")]
pt_path_parts = pt_path.split(os.sep)
if len(pt_path_parts) >= 3 and pt_path_parts[-2:] == ["Contents","MacOS"] \
and pt_path_parts[-3].lower().endswith(".app"):
for x in range(3):
# Remove the last 3 path components as we're in a .app bundle
pt_path = os.path.dirname(pt_path)
# Add a check for next to the .app bundle
config_tex_paths.append(os.path.join(pt_path,"Configuration.tex"))
# Iterate any paths we need to check and return the first match
for path in config_tex_paths:
if os.path.isfile(path):
return path
# If none were found - return the first entry
if config_tex_paths:
return config_tex_paths[0]
def get_tex_version(self, file_path = None):
file_path = file_path or self.get_best_tex_path()
if not file_path or not os.path.isfile(file_path):
return None
try:
with open(file_path,"r") as f:
t = f.read()
for line in t.split("\n"):
line = line.strip().lower()
if line.startswith("reference manual (") and line.endswith(")"):
return line.split("(")[-1].split(")")[0]
except: pass
return None
def reset_tex_button(self, version = None):
tex_version = version or self.get_tex_version()
self.tex_button.configure(
state="normal",
text="Get Configuration.tex{}".format(
" ({})".format(tex_version) if tex_version else ""
)
)
def get_latest_tex(self):
tex_version = self.get_tex_version()
self.tex_button.configure(
state="disabled",
text="Downloading...{}".format(
" ({})".format(tex_version) if tex_version else ""
)
)
# We'll leverage multiprocessing to avoid UI locks if the update checks take too long
p = multiprocessing.Process(target=_update_tex,args=(self.tex_queue,self.tex_url,self.get_best_tex_path()))
p.daemon = True
p.start()
self.check_tex_process(p)
def check_tex_process(self, p):
# Helper to watch until an update is done
if p.is_alive():
self.tk.after(100,self.check_tex_process,p)
return
# Join the process to ensure resources are returned
p.join()
# Check if we got anything from the queue
if self.tex_queue.empty(): # Nothing in the queue, bail
return self.reset_tex_button()
output_dict = self.tex_queue.get()
# Check if we got an error or exception
if "exception" in output_dict or "error" in output_dict:
error = output_dict.get("error","An Error Occurred Downloading Configuration.tex")
excep = output_dict.get("exception","Something went wrong when getting the latest Configuration.tex.")
self.tk.bell()
mb.showerror(error,excep)
else:
tex_path = self.get_best_tex_path()
if os.path.isfile(tex_path):
version = self.get_tex_version(file_path=tex_path)
if not version:
self.tk.bell()
mb.showerror(
title="An Error Occurred Downloading Configuration.tex",
message="Something went wrong when getting the latest Configuration.tex."
)
else:
mb.showinfo(
title="Updated Configuration.tex",
message="Configuration.tex ({}) saved to:\n\n{}".format(version,tex_path)
)
self.reset_tex_button()
# If we got here - we displayed some message, let's lift our window to the top
self.lift_window()
def handle_keypress(self, event, generate=True):