-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncryptext.pyw
More file actions
1715 lines (1387 loc) · 70.5 KB
/
Encryptext.pyw
File metadata and controls
1715 lines (1387 loc) · 70.5 KB
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/python'
# Created by Sooraj S
# https://encryptext.sooraj.dev
# Free for everyone. Forever.
"""
Imports
"""
# Main imports
# This allows the update to happen at least even if the other imports don't work
import sys
from os.path import abspath, join, expanduser
# from os import getenv #! DOESN'T SEEM TO WORK IN EXE MODE
from random import choice, randint
from string import ascii_letters, digits
# Used for getting files when using one-file mode .exe format
def getTrueFilename(filename: str) -> str:
try:
base = sys._MEIPASS
except Exception:
base = abspath(".")
return join(base, filename)
debug = True
version = "VERSION NUMBER HERE"
hash_str = "HASH STRING HERE"
encrypt_key = b"ENCRYPTION KEY HERE"
# Uses random random-length strings of characters to determine where formatting starts and stops
format_item_separator = "FORMAT ITEM SEPARATOR HERE"
format_separator = "FORMAT SEPARATOR HERE"
format_string = "FORMAT STRING HERE"
def updateMode() -> 'tuple[str, str, str, str]':
return (format_item_separator, format_separator, format_string, encrypt_key)
arguments = sys.argv
if len(arguments) == 2 and arguments[1] == hash_str:
print(updateMode())
sys.exit(0)
elif len(arguments) == 2:
possible_characters = ascii_letters + digits
print(("".join([choice(possible_characters) for i in range(randint(15, 45))]), "".join([choice(possible_characters) for i in range(randint(15, 45))]), "".join([choice(possible_characters) for i in range(randint(15, 45))]), Fernet.generate_key().decode()))
sys.exit(0)
# Other imports
import json
import tkinter as tk
from tkinter import font
from tkinter import filedialog
from tkinter import messagebox
from tkinter import colorchooser
from traceback import format_exc, print_exc # For the error messages when in exe form
from webbrowser import open_new # For opening the help page
from cryptography.fernet import Fernet # For encryption features
# Weird import method for ttkbootstrap and tkinterweb
if not debug:
sys.path.append(getTrueFilename("ttkbootstrap"))
import ttkbootstrap as ttk
# For Markdown preview features
from markdown import markdown
if not debug:
sys.path.pop()
sys.path.append(getTrueFilename("tkinterweb"))
import tkinterweb
if not debug:
sys.path.pop()
settings_file_location = r"SETTINGS FILE LOCATION HERE"
try:
try:
with open(settings_file_location, "r", encoding="utf-8") as file:
settings = json.load(file)
except:
# Try simply opening the file as a string and then parse it
with open(settings_file_location, "r", encoding="utf-8") as file:
settings = file.readline()
settings = json.loads(" ".join(settings.split(" ")[:-1]))
# Replace the "true" and "false" strings with the boolean version
for key, value in settings.items():
if isinstance(value, dict):
for sub_key, sub_value in value.items():
if sub_value == "false":
settings[key][sub_key] = False
elif sub_value == "true":
settings[key][sub_key] = True
else:
if value == "false":
settings[key] = False
elif value == "true":
settings[key] = True
version = f"{'.'.join(version.split('.')[:-1])} (build {version.split('.')[-1]})"
except FileNotFoundError as e:
messagebox.showerror("Error Opening File", format_exc())
print_exc()
settings = {
"recentFilePaths": [],
"maxRecentFiles": 0,
"otherSettings": {
"theme": "light",
"fontStyle": "Arial",
"fontScaleFactor": 1,
"language": "en_US",
"autoSave": True,
"autoSaveInterval": 15,
"showLineNumbers": False,
"wrapLines": True,
"highlightActiveLine": False,
"closeAllTabs": False
}
}
version = "'Encryptext Travel Mode'"
font_scale_factor = settings["otherSettings"]["fontScaleFactor"]
theme = settings["otherSettings"]["theme"]
"""
Custom Classes
"""
if theme == "light":
bg = "white"
text = "black"
code_bg = "#f8f8f8"
else:
bg = "black"
text = "white"
code_bg = "#080808"
css_styles = """body { background-color:""" + bg + """; color:""" + text + """;}
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.codehilite .hll { background-color: #ffffcc }
.codehilite { background: """ + code_bg + """; }
.codehilite .c { color: #3D7B7B; font-style: italic } /* Comment */
.codehilite .err { border: 1px solid #FF0000 } /* Error */
.codehilite .k { color: #008000; font-weight: bold } /* Keyword */
.codehilite .o { color: #666666 } /* Operator */
.codehilite .ch { color: #3D7B7B; font-style: italic } /* Comment.Hashbang */
.codehilite .cm { color: #3D7B7B; font-style: italic } /* Comment.Multiline */
.codehilite .cp { color: #9C6500 } /* Comment.Preproc */
.codehilite .cpf { color: #3D7B7B; font-style: italic } /* Comment.PreprocFile */
.codehilite .c1 { color: #3D7B7B; font-style: italic } /* Comment.Single */
.codehilite .cs { color: #3D7B7B; font-style: italic } /* Comment.Special */
.codehilite .gd { color: #A00000 } /* Generic.Deleted */
.codehilite .ge { font-style: italic } /* Generic.Emph */
.codehilite .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.codehilite .gr { color: #E40000 } /* Generic.Error */
.codehilite .gh { color: #000080; font-weight: bold } /* Generic.Heading */
.codehilite .gi { color: #008400 } /* Generic.Inserted */
.codehilite .go { color: #717171 } /* Generic.Output */
.codehilite .gp { color: #000080; font-weight: bold } /* Generic.Prompt */
.codehilite .gs { font-weight: bold } /* Generic.Strong */
.codehilite .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
.codehilite .gt { color: #0044DD } /* Generic.Traceback */
.codehilite .kc { color: #008000; font-weight: bold } /* Keyword.Constant */
.codehilite .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */
.codehilite .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */
.codehilite .kp { color: #008000 } /* Keyword.Pseudo */
.codehilite .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */
.codehilite .kt { color: #B00040 } /* Keyword.Type */
.codehilite .m { color: #666666 } /* Literal.Number */
.codehilite .s { color: #BA2121 } /* Literal.String */
.codehilite .na { color: #687822 } /* Name.Attribute */
.codehilite .nb { color: #008000 } /* Name.Builtin */
.codehilite .nc { color: #0000FF; font-weight: bold } /* Name.Class */
.codehilite .no { color: #880000 } /* Name.Constant */
.codehilite .nd { color: #AA22FF } /* Name.Decorator */
.codehilite .ni { color: #717171; font-weight: bold } /* Name.Entity */
.codehilite .ne { color: #CB3F38; font-weight: bold } /* Name.Exception */
.codehilite .nf { color: #0000FF } /* Name.Function */
.codehilite .nl { color: #767600 } /* Name.Label */
.codehilite .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */
.codehilite .nt { color: #008000; font-weight: bold } /* Name.Tag */
.codehilite .nv { color: #19177C } /* Name.Variable */
.codehilite .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */
.codehilite .w { color: #bbbbbb } /* Text.Whitespace */
.codehilite .mb { color: #666666 } /* Literal.Number.Bin */
.codehilite .mf { color: #666666 } /* Literal.Number.Float */
.codehilite .mh { color: #666666 } /* Literal.Number.Hex */
.codehilite .mi { color: #666666 } /* Literal.Number.Integer */
.codehilite .mo { color: #666666 } /* Literal.Number.Oct */
.codehilite .sa { color: #BA2121 } /* Literal.String.Affix */
.codehilite .sb { color: #BA2121 } /* Literal.String.Backtick */
.codehilite .sc { color: #BA2121 } /* Literal.String.Char */
.codehilite .dl { color: #BA2121 } /* Literal.String.Delimiter */
.codehilite .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */
.codehilite .s2 { color: #BA2121 } /* Literal.String.Double */
.codehilite .se { color: #AA5D1F; font-weight: bold } /* Literal.String.Escape */
.codehilite .sh { color: #BA2121 } /* Literal.String.Heredoc */
.codehilite .si { color: #A45A77; font-weight: bold } /* Literal.String.Interpol */
.codehilite .sx { color: #008000 } /* Literal.String.Other */
.codehilite .sr { color: #A45A77 } /* Literal.String.Regex */
.codehilite .s1 { color: #BA2121 } /* Literal.String.Single */
.codehilite .ss { color: #19177C } /* Literal.String.Symbol */
.codehilite .bp { color: #008000 } /* Name.Builtin.Pseudo */
.codehilite .fm { color: #0000FF } /* Name.Function.Magic */
.codehilite .vc { color: #19177C } /* Name.Variable.Class */
.codehilite .vg { color: #19177C } /* Name.Variable.Global */
.codehilite .vi { color: #19177C } /* Name.Variable.Instance */
.codehilite .vm { color: #19177C } /* Name.Variable.Magic */
.codehilite .il { color: #666666 } /* Literal.Number.Integer.Long */"""
# https://stackoverflow.com/a/16375233
class TextLineNumbers(tk.Canvas):
def __init__(self, *args, **kwargs):
tk.Canvas.__init__(self, *args, **kwargs)
self.textwidget = None
if theme == "light":
self.configure(bg="#f7f7f7")
else:
self.configure(bg="#1c1c1c")
def attach(self, text_widget):
self.textwidget = text_widget
def redraw(self, *args):
self.delete("all")
i = self.textwidget.index("@0,0")
while True :
dline= self.textwidget.dlineinfo(i)
if dline is None: break
y = dline[1]
linenum = str(i).split(".")[0]
if theme == "light":
self.create_text(2,y,anchor="nw", text=linenum, fill="#000000")
else:
self.create_text(2,y,anchor="nw", text=linenum, fill="#ffffff")
i = self.textwidget.index("%s+1line" % i)
# https://stackoverflow.com/a/16375233
class CustomText(tk.Text):
def __init__(self, *args, **kwargs):
tk.Text.__init__(self, *args, **kwargs)
# create a proxy for the underlying widget
self._orig = self._w + "_orig"
self.tk.call("rename", self._w, self._orig)
self.tk.createcommand(self._w, self._proxy)
def _proxy(self, *args):
# let the actual widget perform the requested action
try:
cmd = (self._orig,) + args
result = self.tk.call(cmd)
except tk._tkinter.TclError:
result = "break"
# generate an event if something was added or deleted,
# or the cursor position changed
if (args[0] in ("insert", "replace", "delete") or
args[0:3] == ("mark", "set", "insert") or
args[0:2] == ("xview", "moveto") or
args[0:2] == ("xview", "scroll") or
args[0:2] == ("yview", "moveto") or
args[0:2] == ("yview", "scroll")
):
self.event_generate("<<Change>>", when="tail")
# return what the actual widget returned
return result
# https://www.reddit.com/r/learnpython/comments/6dndqz/comment/di42keo/
class WrappedLabel(ttk.Label):
def __init__(self, master=None, **kwargs):
ttk.Label.__init__(self, master, **kwargs)
self.bind("<Configure>", lambda e: self.config(wraplength=self.winfo_width()))
class PreferenceWindow(tk.Toplevel):
win_open = False
def __init__(self, close: bool = False) -> None:
if not self.win_open and not close:
self.pref_window = tk.Toplevel()
self.pref_window.title("Preferences")
self.pref_window.geometry("450x600")
self.pref_window.iconbitmap(getTrueFilename("app_icon.ico"))
self.pref_window.protocol("WM_DELETE_WINDOW", self.closeWindow)
self.win_open = True
self.option_pady = 3
# Title label
self.title = WrappedLabel(self.pref_window, text="Preferences", font=(settings["otherSettings"]["fontStyle"], int(round(18*font_scale_factor))))
self.title.pack(side="top", fill="x", anchor="nw", padx=5, pady=10)
ttk.Separator(self.pref_window, orient="horizontal").pack(side="top", fill="x", padx=5, pady=5)
# Recent file number
self.selected_recent_files = tk.IntVar(value=settings["maxRecentFiles"])
self.recent_file_label = WrappedLabel(self.pref_window, text="Number of recent files to store: ", anchor="nw", font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))))
self.recent_file_val = ttk.Spinbox(self.recent_file_label, textvariable=self.selected_recent_files, from_=0, to=20, width=5, font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))))
self.recent_file_label.pack(side="top", anchor="w", fill="x", padx=5)
self.recent_file_val.pack(side="right", padx=20, pady=self.option_pady)
ttk.Separator(self.pref_window, orient="horizontal").pack(side="top", fill="x", padx=100, pady=10)
# Font style picker
self.selected_font_style = tk.StringVar(value=settings["otherSettings"]["fontStyle"])
self.font_style_label = WrappedLabel(self.pref_window, text="Display font style: ", font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))))
font_options = sorted(list(font.families()))
self.font_style_val = ttk.Combobox(self.font_style_label, textvariable=self.selected_font_style, values=font_options, state="readonly", font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))))
self.font_style_label.pack(side="top", fill="x", padx=5, anchor="nw")
self.font_style_val.pack(side="right", padx=20, pady=self.option_pady)
# Font size number
self.selected_font_sf = tk.DoubleVar(value=settings["otherSettings"]["fontScaleFactor"])
self.font_sf_label = WrappedLabel(self.pref_window, text="Display font size scale factor: ", font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))))
self.font_sf_val = ttk.Spinbox(self.font_sf_label, textvariable=self.selected_font_sf, from_=0.5, to=2, increment=0.05, width=5, font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))))
self.font_sf_label.pack(side="top", fill="x", padx=5, anchor="nw")
self.font_sf_val.pack(side="right", padx=20, pady=self.option_pady)
ttk.Separator(self.pref_window, orient="horizontal").pack(side="top", fill="x", padx=100, pady=10)
# Theme selector
self.selected_theme = tk.StringVar(value=theme)
self.theme_label = WrappedLabel(self.pref_window, text="Theme: ", font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))))
self.light_theme_val = ttk.Radiobutton(self.theme_label, text="Light", value="light", variable=self.selected_theme)
self.dark_theme_val = ttk.Radiobutton(self.theme_label, text="Dark", value="dark", variable=self.selected_theme)
self.theme_label.pack(side="top", fill="x", padx=5, anchor="n")
self.dark_theme_val.pack(side="right", padx=20, pady=self.option_pady)
self.light_theme_val.pack(side="right", padx=20, pady=self.option_pady)
ttk.Separator(self.pref_window, orient="horizontal").pack(side="top", fill="x", padx=100, pady=10)
# Auto-save selector
self.selected_auto_save = tk.StringVar(value=str(settings["otherSettings"]["autoSave"]).lower())
self.auto_save_val = ttk.Checkbutton(self.pref_window, text="Auto-save", variable=self.selected_auto_save, onvalue="true", offvalue="false")
self.auto_save_val.pack(side="top", anchor="nw", padx=5, pady=self.option_pady)
# Auto-save interval number
self.selected_auto_save_interval_val = tk.IntVar(value=settings["otherSettings"]["autoSaveInterval"])
self.auto_save_interval_label = WrappedLabel(self.pref_window, text="Auto-save interval (seconds): ", font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))))
self.auto_save_interval_val = ttk.Spinbox(self.auto_save_interval_label, textvariable=self.selected_auto_save_interval_val, from_=1, to=600, increment=5, width=5, font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))))
self.auto_save_interval_label.pack(side="top", fill="x", padx=5, anchor="nw")
self.auto_save_interval_val.pack(side="right", padx=20, pady=self.option_pady)
ttk.Separator(self.pref_window, orient="horizontal").pack(side="top", fill="x", padx=100, pady=10)
# Language picker
self.selected_language = tk.StringVar(value=settings["otherSettings"]["language"])
self.language_label = WrappedLabel(self.pref_window, text="Display language: ", font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))))
# Get the user's default language and also display that in the list
# It doesn't change anything right now, but maybe it will in the future.
#! DOESN'T SEEM TO WORK IN EXE MODE
# getenv("LANG").split(".")[0]
lang_options = ["en_US"]
self.language_val = ttk.Combobox(self.language_label, textvariable=self.selected_language, values=lang_options, state="readonly", font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))))
self.language_label.pack(side="top", fill="x", padx=5, anchor="nw")
self.language_val.pack(side="right", padx=20, pady=self.option_pady)
ttk.Separator(self.pref_window, orient="horizontal").pack(side="top", fill="x", padx=100, pady=10)
# show checkboxes for other true/false options
self.selected_show_line_no = tk.StringVar(value=str(settings["otherSettings"]["showLineNumbers"]).lower())
self.show_line_no_val = ttk.Checkbutton(self.pref_window, text="Show line numbers", variable=self.selected_show_line_no, onvalue="true", offvalue="false")
self.show_line_no_val.pack(side="top", anchor="nw", padx=5, pady=self.option_pady)
self.selected_wrap_line = tk.StringVar(value=str(settings["otherSettings"]["wrapLines"]).lower())
self.wrap_line_val = ttk.Checkbutton(self.pref_window, text="Wrap text", variable=self.selected_wrap_line, onvalue="true", offvalue="false")
self.wrap_line_val.pack(side="top", anchor="nw", padx=5, pady=self.option_pady)
self.selected_show_active_line = tk.StringVar(value=str(settings["otherSettings"]["highlightActiveLine"]).lower())
self.show_active_line_val = ttk.Checkbutton(self.pref_window, text="Highlight active line", variable=self.selected_show_active_line, onvalue="true", offvalue="false")
self.show_active_line_val.pack(side="top", anchor="nw", padx=5, pady=self.option_pady)
self.selected_close_all_tabs = tk.StringVar(value=str(settings["otherSettings"]["closeAllTabs"]).lower())
self.close_all_tabs_val = ttk.Checkbutton(self.pref_window, text="Close all tabs", variable=self.selected_close_all_tabs, onvalue="true", offvalue="false")
self.close_all_tabs_val.pack(side="top", anchor="nw", padx=5, pady=self.option_pady)
# Save button
self.save_button = ttk.Button(self.pref_window, text="Save Preferences", command=self.savePreferences)
self.save_button.pack(side="bottom", anchor="e", pady=10, padx=10)
# Info text
self.info_text = WrappedLabel(self.pref_window, text="Reopen Encryptext to see changes after saving.", anchor="sw", font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))))
self.info_text.pack(side="bottom", anchor="n", padx=5, pady=self.option_pady, fill="x")
elif self.win_open:
self.pref_window.focus()
def savePreferences(self) -> None:
global settings
# Save preferences that have been selected
settings["maxRecentFiles"] = max(0, min(20, self.selected_recent_files.get()))
settings["otherSettings"]["fontStyle"] = self.selected_font_style.get()
settings["otherSettings"]["fontScaleFactor"] = max(0.5, min(2, self.selected_font_sf.get()))
settings["otherSettings"]["theme"] = self.selected_theme.get()
settings["otherSettings"]["autoSave"] = self.selected_auto_save.get()
settings["otherSettings"]["autoSaveInterval"] = max(1, min(600, self.selected_auto_save_interval_val.get()))
settings["otherSettings"]["language"] = self.language_val.get()
settings["otherSettings"]["showLineNumbers"] = self.selected_show_line_no.get()
settings["otherSettings"]["wrapLines"] = self.selected_wrap_line.get()
settings["otherSettings"]["highlightActiveLine"] = self.selected_show_active_line.get()
settings["otherSettings"]["closeAllTabs"] = self.selected_close_all_tabs.get()
# Close the preferences window automatically
self.closeWindow()
def closeWindow(self) -> None:
self.pref_window.destroy()
self.win_open = False
class PreviewWindow(tk.Toplevel):
win_open = False
def __init__(self, close: bool = False) -> None:
if not self.win_open and not close:
self.preview_window = tk.Toplevel()
self.preview_window.title("Preview")
self.preview_window.geometry("800x500")
self.preview_window.iconbitmap(getTrueFilename("app_icon.ico"))
self.preview_window.protocol("WM_DELETE_WINDOW", self.closeWindow)
self.win_open = True
self.preview_window.bind("<Control-w>", self.closeWindow)
self.preview_window.bind_all("<Control-P>", preview_window.closeWindow)
self.preview_window.bind_all("<Control-e>", updatePreview)
self.addFrame()
elif self.win_open:
self.preview_window.focus()
def closeWindow(self, other_args = None) -> None:
self.preview_window.destroy()
self.win_open = False
def addFrame(self) -> None:
self.frame = tkinterweb.HtmlFrame(self.preview_window, messages_enabled=False)
current_tab = getCurrentTab()
if current_tab == -1:
return None
text = textboxes[current_tab].get("1.0", tk.END)
self.updateFrame(text)
self.frame.pack(fill="both", expand=True)
def updateFrame(self, text: str) -> None:
html_page = f"<html><head><style>{css_styles}</style></head><body>{markdown(text, extensions=['fenced_code', 'codehilite'])}</body></html>"
self.frame.load_html(html_page)
def key_bind(self, keys: str, func) -> None:
self.preview_window.bind(keys, func)
"""
Window Settings
"""
# Create the window and configure the background for theme changes
if theme == "light":
styles = ttk.Style(theme="cosmo")
else:
styles = ttk.Style(theme="darkly")
root = styles.master
pref_window = PreferenceWindow(close=True)
preview_window = PreviewWindow(close=True)
# Rename the window
root.title("Encryptext")
# Resize the window (manually resizable too)
root.geometry("800x500")
# Change the icon
root.iconbitmap(getTrueFilename("app_icon.ico"))
"""
Variables
"""
file_save_locations = []
file_extensions = []
default_font_size = 11
default_font_type = "Arial"
max_font_size = 96
min_font_size = 8
font_sizes = []
font_type = []
# These are just general font styles for all text items
other_styles = ttk.Style()
other_styles.configure("TButton", font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))))
other_styles.configure("TNotebook", tabposition="nw", padding=2)
other_styles.configure("TNotebook.Tab", font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))), expand=-1)
other_styles.configure("TRadiobutton", font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))))
other_styles.configure("TCheckbutton", font=(settings["otherSettings"]["fontStyle"], int(round(11*font_scale_factor))))
recent_files = settings["recentFilePaths"]
supported_file_types = [
("Accepted Files", "*.etx *.md *.txt *.py *.html *.css *.js *.json *.csv *.ini *.log"),
("Encrypted File", "*.etx"),
("Markdown File", "*.md"),
("Plain Text File", "*.txt"),
("Python File", "*.py"),
("HTML File", "*.html"),
("CSS File", "*.css"),
("JavaScript File", "*.js"),
("JSON File", "*.json"),
("Comma-Separated Values File", "*.csv"),
("Windows Initialization File", "*.ini"),
("Log File", "*.log"),
("All Files", "*.*")
]
# For debug purposes, set static key and separators
if debug:
encrypt_key = b'4P7ySeLwmoC61q8Nsm7SiEpGW_Y9eISDlg07f699uAo='
format_item_separator = "@@@"
format_separator = "^^^"
format_string = "&&&"
fernet = Fernet(encrypt_key)
# Have atleast 3 versions of history
file_histories = []
# Set the current history version to 1 (centered)
current_versions = []
max_history = 50
file_format_tags = []
file_format_tag_nums = []
frames = []
textboxes = []
line_number_areas = []
saved = []
prev_key = ""
"""
Functions
"""
def updateTags() -> str:
global file_format_tags
current_tab = getCurrentTab()
if current_tab == -1:
return ""
tags_used = textboxes[current_tab].tag_names()
i = 0
# Convert the tuple into a list to remove the "sel" and "current_line" tag
# These tags caused issues when saving
tags_used = list(tags_used)
try:
tags_used.remove("sel")
finally:
try:
# Throws an error if highlightActiveLine setting isn't on
tags_used.remove("current_line")
except ValueError: pass
for tag in tags_used:
indices = textboxes[current_tab].tag_ranges(tag)
for start, end in zip(indices[::2], indices[1::2]):
file_format_tags[current_tab][i][1] = str(start)
file_format_tags[current_tab][i][2] = str(end)
i += 1
formatted_tags = [format_item_separator.join(tag) for tag in file_format_tags[current_tab]]
formatted_tags = format_separator.join(formatted_tags)
return formatted_tags
def quitApp(Event = None, force: bool = False) -> None:
def closeWindows() -> None:
try:
preview_window.destroy()
pref_window.closeWindow()
finally:
root.destroy()
sys.exit()
def savePreferences() -> bool:
global settings
settings["recentFilePaths"] = recent_files
try:
with open(settings_file_location, "r+", encoding="utf-8") as file:
settings = str(settings).replace("'", '"').replace("False", "false").replace("True", "true")
file.write(str(settings))
except Exception as e:
return messagebox.askokcancel("Error", f"Error: {e}\n\nUnknown error. If this problem persists, please contact the developer at 'https://github.com/WhenLifeHandsYouLemons/Encryptext'.")
return True
current_tab = getCurrentTab()
if current_tab == -1:
# Save any settings changes
if savePreferences():
closeWindows()
# Check if any of the tabs are not saved yet
quit_confirm = True
if not force:
for save_status in saved:
if save_status == False:
quit_confirm = False
# If there's one that's not empty, then show warning
if not quit_confirm:
quit_confirm = messagebox.askyesno("Quit", "Quit Encryptext?\n\nAny unsaved changes will be lost.")
if quit_confirm:
# Save any settings changes
if savePreferences():
closeWindows()
def openFile(Event = None, current: bool = False, file_path: str = None) -> None:
# Make save_location global to change it for the whole program
global file_save_locations, file_format_tags, file_histories, current_versions, file_format_tag_nums, file_extensions
current_tab = getCurrentTab()
if current_tab == -1:
addNewTab()
# Check if the current textbox is empty
if len(textboxes[current_tab].get("1.0", tk.END)) > 2 and textboxes[current_tab].get("1.0", tk.END) != "\n\n" and not current and saved[current_tab] == False:
open_file_confirm = messagebox.askyesno("Open File", "Open a file?\n\nAny unsaved changes will be lost.")
else:
open_file_confirm = True
if open_file_confirm:
# Show a file selector and let user choose file
save_location = file_save_locations[current_tab]
if file_path != None:
save_location = file_path
elif not current:
save_location = filedialog.askopenfilename(title="Select file", filetypes=supported_file_types)
if save_location != "":
# Open the file and read its contents into an array
try:
file = open(save_location, "r")
except FileNotFoundError:
messagebox.showerror("Error Opening File", f"File not found.\nThe file that you tried to open doesn't exist!")
return None
# Don't change the file save location before confirming
file_save_locations[current_tab] = save_location
# Reset tag number
file_format_tag_nums[current_tab] = 0
# Get the file exntension
file_extensions[current_tab] = file_save_locations[current_tab].split(".")[-1]
# Get file name
file_name = file_save_locations[current_tab].split("/")[-1]
# Set the title of the window to the file name
tab_panes.tab(tab_panes.tabs()[getCurrentTab()], text=f"{file_name} ")
# Set the current textbox to be writable
textboxes[current_tab].config(state=tk.NORMAL)
# Clear the current textbox
textboxes[current_tab].delete("1.0", tk.END)
# Clear the history
file_histories[current_tab] = ["", "", ""]
current_versions[current_tab] = 1
# If the file is a .etx file, decrypt it
if file_extensions[current_tab] == "etx":
try:
# Convert the text to bytes
file = bytes(file.read(), "utf-8")
# Convert to string and remove the b'' from the string
if not debug:
# Decrypt the file
file = fernet.decrypt(file).decode()
else:
file = file.decode()
# Split the formatting and the visible text
file = file.split(format_string)
# Go through the formats and remove duplicates
formattings = file[0].split(format_separator)
formats = []
if formattings != [""]:
formattings.reverse()
for format_style in formattings:
format_style = format_style.split(format_item_separator)
add = True
if formats == []:
format_style[0] = f"{''.join(i for i in format_style[0] if not i.isdigit())}{file_format_tag_nums[current_tab]}"
formats.append(format_style)
file_format_tag_nums[current_tab] += 1
else:
format_type = "".join(i for i in format_style[0] if not i.isdigit())
for f in formats:
if format_type == "".join(i for i in f[0] if not i.isdigit()) and format_style[1] == f[1] and format_style[2] == f[2]:
add = False
break
if add:
format_style[0] = f"{''.join(i for i in format_style[0] if not i.isdigit())}{file_format_tag_nums[current_tab]}"
formats.append(format_style)
file_format_tag_nums[current_tab] += 1
# Need to sort the formats list to have the bold at the end
# The bold has to be the last formatting to be applied otherwise it won't show up
new_formats = []
i = len(formats) - 1
while i >= 0:
if formats[i][0].startswith("bold"):
new_formats.append(formats[i])
else:
new_formats.insert(0, formats[i])
i -= 1
formats = new_formats.copy()
# Saves memory
new_formats.clear()
# Format the visible text properly
text = file[1]
text = text.replace("\\n", "\n")
# Write the file contents to the current textbox
# Removes the extra newline that tkinter adds
textboxes[current_tab].insert(tk.END, text[:-1])
# Add all the formatting to the text and add it to the tags list
file_format_tags[current_tab] = []
if formats != []:
for i in range(len(formats)):
format = formats[i]
textboxes[current_tab].tag_add(format[0], format[1], format[2])
if "colour" in format[0]:
textboxes[current_tab].tag_config(format[0], foreground=format[3])
elif "size" in format[0]:
textboxes[current_tab].tag_config(format[0], font=(format[3], int(format[4])))
else:
# Get format type
if "bold" in format[0]:
textboxes[current_tab].tag_config(format[0], font=(format[3], int(format[4]), "bold"))
elif "italic" in format[0]:
textboxes[current_tab].tag_config(format[0], font=(format[3], int(format[4]), "italic"))
elif "normal" in format[0]:
textboxes[current_tab].tag_config(format[0], font=(format[3], int(format[4]), "normal"))
file_format_tags[current_tab].append(format)
# Set save status to True
setSaveStatus(True, current_tab)
# Change recent files list
if save_location in recent_files:
recent_files.pop(recent_files.index(save_location))
recent_files.insert(0, save_location)
else:
recent_files.insert(0, save_location)
# Check that there's only the set number of file paths stored
if len(recent_files) > settings["maxRecentFiles"]:
recent_files.pop()
createMenuBar()
except Exception as e:
if debug:
messagebox.showerror("Error Opening File", format_exc())
print_exc()
else:
messagebox.showerror("Error Opening File", f"Access denied.\nPlease use the Encryptext program that you used to write this file to open it correctly.")
else:
# Write the file contents to the current textbox
textboxes[current_tab].insert(tk.END, file.read()[:-1])
# Close the file
file.close()
# Set save status to True
setSaveStatus(True, current_tab)
# Change recent files list
if save_location in recent_files:
recent_files.pop(recent_files.index(save_location))
recent_files.insert(0, save_location)
else:
recent_files.insert(0, save_location)
# Check that there's only the set number of file paths stored
if len(recent_files) > settings["maxRecentFiles"]:
recent_files.pop()
createMenuBar()
# Open the preview window if a markdown file is opened
if file_extensions[current_tab] == "md":
global preview_window
try:
preview_window.deiconify()
updatePreview()
except:
preview_window.__init__()
else:
text = textboxes[current_tab].get("1.0", tk.END)
textboxes[current_tab].delete("1.0", tk.END)
textboxes[current_tab].insert(tk.END, text[:-2])
for i in range(len(file_format_tags[current_tab])):
format = file_format_tags[current_tab][i]
textboxes[current_tab].tag_add(format[0], format[1], format[2])
if "colour" in format[0]:
textboxes[current_tab].tag_config(format[0], foreground=format[3])
elif "size" in format[0]:
textboxes[current_tab].tag_config(format[0], font=(format[3], int(format[4])))
else:
# Get format type
if "bold" in format[0]:
textboxes[current_tab].tag_config(format[0], font=(format[3], int(format[4]), "bold"))
elif "italic" in format[0]:
textboxes[current_tab].tag_config(format[0], font=(format[3], int(format[4]), "italic"))
elif "normal" in format[0]:
textboxes[current_tab].tag_config(format[0], font=(format[3], int(format[4]), "normal"))
def newFile(Event = None) -> None:
global file_save_locations, file_histories, current_versions
current_tab = getCurrentTab()
if current_tab == -1:
addNewTab()
# Check if the current textbox is empty
confirmed = False
if saved[current_tab] == False:
new_file_confirm = messagebox.askyesno("New File", "Create new file?\n\nAny unsaved changes will be lost.")
if new_file_confirm:
confirmed = True
else:
confirmed = True
if confirmed:
file_save_locations[current_tab] = ""
textboxes[current_tab].config(state=tk.NORMAL)
textboxes[current_tab].delete("1.0", tk.END)
file_histories[current_tab] = ["", "", ""]
current_versions[current_tab] = 1
setSaveStatus(True, current_tab)
tab_panes.tab(tab_panes.tabs()[getCurrentTab()], text="Untitled ")
updatePreview()
def autoSaveFile() -> None:
# Save the file if there is a tab open
current_tab = getCurrentTab()
if current_tab != -1:
saveFile(auto_save=True)
# Recursively run autoSaveFile until program is closed (sys.exit kills all processes)
# Delay time is in milliseconds
root.after(settings["otherSettings"]["autoSaveInterval"]*1000, autoSaveFile)
def saveFile(Event = None, auto_save: bool = False) -> None:
current_tab = getCurrentTab()
if current_tab == -1:
return None
# If it's a new file
if file_save_locations[current_tab] == "":
# If it's being saved manually, then try save as
if not auto_save:
saveFileAs()
else:
# Get the text from the current textbox
text = textboxes[current_tab].get("1.0", tk.END)
# If the file is a .etx file, encrypt it
if file_save_locations[current_tab].split(".")[-1] == "etx":
full_text = format_string.join([updateTags(), text])
if not debug:
text = fernet.encrypt(full_text.encode())
else:
text = full_text.encode()
# Convert the text to a string
text = str(text)
# Remove the b'' from the string
text = text[2:-1]
# Write the text to the file and close it
file = open(file_save_locations[current_tab], "w")
file.write(text)
file.close()
# Set save status to True
setSaveStatus(True, current_tab)
trackChanges(override=True)
def saveFileAs(Event = None) -> None:
global file_save_locations
current_tab = getCurrentTab()
if current_tab == -1:
return None
# Get the text from the current textbox
text = textboxes[current_tab].get("1.0", tk.END)
# Show a file selector and let user choose file
file_save_locations[current_tab] = filedialog.asksaveasfilename(title="Save file as", filetypes=supported_file_types, defaultextension=supported_file_types)
if file_save_locations[current_tab] != "":
# If the file is a .etx file, encrypt it
if file_save_locations[current_tab].split(".")[-1] == "etx":
full_text = format_string.join([updateTags(), text])
if not debug:
text = fernet.encrypt(full_text.encode())
else:
text = full_text.encode()
# Convert the text to a string
text = str(text)
# Remove the b'' from the string
text = text[2:-1]
# Write the text to the file and close it
file = open(file_save_locations[current_tab], "w")
file.write(text)
file.close()
# Open the new file
openFile(current=True)
def undo(Event = None) -> None:
global file_histories
current_tab = getCurrentTab()
if current_tab == -1:
return None
# Check if the previous version is the same as the current version
if file_histories[current_tab][current_versions[current_tab] - 1] != textboxes[current_tab].get("1.0", tk.END):
# Update the current version
file_histories[current_tab][current_versions[current_tab]] = textboxes[current_tab].get("1.0", tk.END)
# Remove the last newline character
file_histories[current_tab][current_versions[current_tab]] = file_histories[current_tab][current_versions[current_tab]][:-1]
# Check if the final version is blank
if file_histories[current_tab][-1] != "":
if len(file_histories[current_tab]) - current_versions[current_tab] < max_history:
# Add a new version
file_histories[current_tab].append("")
# Shift every version up one
for i in range(len(file_histories[current_tab]) - 1, 0, -1):
file_histories[current_tab][i] = file_histories[current_tab][i - 1]
# Clear the first version
file_histories[current_tab][0] = ""
# Update the current textbox
textboxes[current_tab].delete("1.0", tk.END)
textboxes[current_tab].insert(tk.END, file_histories[current_tab][current_versions[current_tab]])
setSaveStatus(False, current_tab)
def redo(Event = None) -> None:
global file_histories, current_versions
current_tab = getCurrentTab()
if current_tab == -1:
return None
# Check if the next version is the same as the current version
if file_histories[current_tab][current_versions[current_tab] + 1] != textboxes[current_tab].get("1.0", tk.END):