-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathWriterClassic.py
5032 lines (3568 loc) · 166 KB
/
WriterClassic.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
# WriterClassic.py
'''
WriterClassic
Powered by: Python 3.11.8
Official Website:
https://mf366-coding.github.io/writerclassic.html
Official Repo:
https://github.com/MF366-Coding/WriterClassic
Find me in this spots:
https://github.com/MF366-Coding
https://www.buymeacoffee.com/mf366 (Support me please!)
Original idea and development by: MF366
Small but lovely contributions by:
Norb (norbcodes at GitHub)
Zeca70 (Zeca70 at GitHub)
'''
# [*] Sorting the imports
import os
import shutil
import sys
import json
import subprocess
import random
import datetime
import base64
import gzip
import platform
import math
import cmath
import tracemalloc
from typing import Literal, SupportsFloat, Any, Callable # [i] Making things nicer, I guess
from getpass import getuser # [i] Used in order to obtain the username of the current user, which is used for the Auto Signature
import zipfile as zipper # [i] Used to extract the zip files used by plugins
# [i] tkinter is used for the UI, duh?!
from tkinter import Listbox, Event, DISABLED, NORMAL, SINGLE, Tk, Toplevel, TclError, StringVar, END, Menu, IntVar, INSERT, Frame, WORD, CHAR, NONE, Variable
from tkinter.ttk import Button, Checkbutton, Label, Entry, OptionMenu, Radiobutton, Style # [i] Used because of the auto styling in tkinter.ttk
from tkinter import SEL_FIRST, SEL_LAST
from tkinter.scrolledtext import ScrolledText # [!?] Only here so pyinstaller compiles it - not needed and gets removed later on
import tkinter.messagebox as mb # [i] Used for the message boxes
import tkinter.filedialog as dlg # [i] Used for the "save", "open" dialogues
from tkinter import simpledialog as sdg # [i] Used for dialogues that ask you for an input
from tkinter.font import Font # [i] Used for controlling the fonts in the Text widget
from tkinter import colorchooser # [!?] Same reason why ScrolledText was imported, see above
import smtplib # [i] Used for the Send E-mail option - server management
# [i] The next 4 are all used for the Send E-mail option - encodings and e-mail parts
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
# [i] Custom widgets for WriterClassic specifically (a custom ScrolledText widget and a custom Toplevel for Search & Replace)
from editor import WriterClassicEditor, SearchReplace, CustomThemeMaker, deprecated
from plugin_system import load_module_from_source # [i] For WriterClassic's Plugin "API"
from setting_loader import get_settings, dump_settings # [i] Used to load and dump WriterClassic's settings
from pygame import mixer # [i] Playing the sucessful sound => Only in this file so it gets compiled
from icecream import ic # [i] Used for debugging
from PIL import Image, ImageTk # [i] Used for placing the WriterClassic logo on the screen
import tkfontchooser # [i] used for the new Font picker
import pyperclip as pyclip # [i] used for the clipboard options
import markdown2 # [i] Used to make HTML files from Markdown
import simple_webbrowser # [i] My own Python module (used for the Search with... options)
from requests import get, exceptions # [i] Used for regular interactions with the Internet
from PyLocalizer import EntryFormatting
from PyLocalizer.internal import JSONLocalization
# /-/ import chlorophyl # [i] Code view for Snippets
del ScrolledText, colorchooser
current_file = False # [*] current file, otherwise False
cur_data: str = ""
grp: None = None # [i] Redefined later on...
save_status: bool = True
TOOLBAR_LEN: int = 11
LAST_THEME_CALL = datetime.datetime.now()
CREDITS = """WriterClassic by: MF366
Powered by: Python 3.11+
- Thank you, Norb and Zeca70, best GitHub contributors (and friends) ever! :)
- Thank you, j4321 for your tkFontChooser module, which really helped me a LOT when implementing the improved version of the Font Picker.
- And thank you, dear user, for using WriterClassic! <3"""
# [!?] Disabling annoying Pylint stuff (specially stupid conventions)
# [*] Everything related to general exceptions (catching them and raising them)
# pylint: disable=W0718
# pylint: disable=W0719
# [*] Module 'PIL.Image' has no 'LANCZOS' member (hint: it does)
# pylint: disable=E1101
# [*] Redefining from outer scope
# pylint: disable=W0621
# [*] Global statement, exec and eval
# pylint: disable=W0603
# pylint: disable=W0122
# pylint: disable=W0123
# [*] Bad indentation nonsense
# pylint: disable=W0311
# [*] String statement doesn't have any effect
# pylint: disable=W0105
# [*] Consider explicitly re-raising...
# pylint: disable=W0707
# [*] Get the absolute path of the script
script_path: str = os.path.abspath(__file__)
# [*] Get the directory containing the script
script_dir: str = os.path.dirname(script_path)
config: str = os.path.join(script_dir, 'config')
user_data: str = os.path.join(script_dir, 'user_data')
nix_assets: str = os.path.join(script_dir, 'nix_assets')
plugin_dir: str = os.path.join(script_dir, 'plugins')
data_dir: str = os.path.join(script_dir, 'data')
locale: str = os.path.join(script_dir, 'locale')
temp_dir: str = os.path.join(script_dir, 'temp')
scripts_dir: str = os.path.join(script_dir, "scripts")
now = datetime.datetime.now
EFORMATTER = EntryFormatting.EntryFormatter(False, False, False)
LOCALIZER = JSONLocalization.JSONLocalization(EFORMATTER, f"{locale}/en")
LOCALIZER.get_entry_value()
def check_paths(var: str) -> str:
"""
check_paths checks if the directories exist
This function checks if the directories related to WriterClassic exist or should be created.
Args:
var (str, absolute filepath): the path that must be checked
Returns:
str: either 'Created' or 'Was there', depending on if it existed before or not
"""
if not os.path.exists(var):
os.mkdir(var)
return "Created."
return "Was there."
debug_a: list[str] = [config, user_data, nix_assets, plugin_dir, data_dir, locale, temp_dir, scripts_dir]
for i in debug_a:
check_paths(i)
class Logger:
def __init__(self, logger_path: str, encoding: str = 'utf-8') -> None:
"""
__init__ is the initializer for the Logger class
Args:
logger_path (str): the path to the log file
encoding (str, optional): the encoding to use when opening the file. Defaults to 'utf-8'.
Raises:
ValueError: empty string as path or invalid path
"""
if logger_path.strip() == '':
raise ValueError('emptry string as a path value')
if not os.path.exists(logger_path) or not os.path.isfile(logger_path):
raise ValueError('invalid path - must be existing file')
self.logger = open(logger_path, 'a', encoding=encoding)
self.__newline()
def write(self, text: str) -> None:
"""
write writes text to the log file
Args:
text (str)
"""
self.logger.write(text)
def error(self, text: str, error_details: str | None = None) -> None:
"""
error writes an error information to the log file
Syntax is:
Current Time - text argument: error_details argument
Args:
text (str)
error_details (str | None, optional): extra details such as NO INETERNET CONNECTION. Defaults to ERROR.
"""
if error_details is None:
error_details = 'ERROR'
self.logger.write(f"{str(now())} - {text}: {error_details}\n")
def warning(self, text: str, details: str | None = None) -> None:
"""
warning writes a warning to the log file
Syntax used:
Current Time - text arg - details arg
Args:
text (str)
details (str | None, optional): extra details such as AN INSECURE ACTION HAS BEEN EXECUTED. Defaults to WARNING.
"""
if details is None:
details = 'WARNING'
self.logger.write(f"{str(now())} - {text}: {details}\n")
def action(self, text: str, extra: str | None = None) -> None:
"""
action writes a simple action in the syntax:
Current Time - text arg - extra arg
Args:
text (str)
extra (str | None, optional): extra details on what was done. Defaults to nothing.
"""
if extra is None:
extra = ''
self.logger.write(f"{str(now())} - {text}: OK {extra}".rstrip() + "\n")
def close(self) -> None:
"""
close closes the log file
"""
self.logger.close()
def __newline(self) -> None:
"""
Internal function.
"""
self.logger.write('\n')
def __repr__(self) -> str:
"""
String representation of the logger
Returns:
str: same as str(filelike object)
"""
return str(self.logger)
LOG = Logger(os.path.join(user_data, "log.wclassic"))
LOG.action("WriterClassic was executed")
tracemalloc.start()
ic.configureOutput(prefix="ic debug statement | -> ")
def showerror(title: str | None = None, message: str | None = None, **options) -> str:
"""
showerror works just like tkinter.messagebox.showerror() but saves the information to the WriterClassic log file
Args:
title (str | None, optional): the title of the messagebox. Defaults to None.
message (str | None, optional): the contents of the messagebox. Defaults to None.
Returns:
str: value returned by `tkinter.messagebox.showerror(title, message, **options)`
"""
s: str = mb.showerror(title, message, **options)
if title is not None and message is not None:
LOG.error(message.split('\n')[-1], title.strip())
return s
def showwarning(title: str | None = None, message: str | None = None, **options) -> str:
"""
showwarning works just like tkinter.messagebox.showwarning() but saves the information to the WriterClassic log file
Args:
title (str | None, optional): the title of the messagebox. Defaults to None.
message (str | None, optional): the contents of the messagebox. Defaults to None.
Returns:
str: value returned by `tkinter.messagebox.showwarning(title, message, **options)`
"""
s = mb.showwarning(title, message, **options)
if title is not None and message is not None:
LOG.warning(message.split('\n')[-1], title.strip())
return s
def showinfo(title: str | None = None, message: str | None = None, **options) -> str:
"""
showinfo works just like tkinter.messagebox.showinfo() but saves the information to the WriterClassic log file
Args:
title (str | None, optional): the title of the messagebox. Defaults to None.
message (str | None, optional): the contents of the messagebox. Defaults to None.
Returns:
str: value returned by `tkinter.messagebox.showinfo(title, message, **options)`
"""
s = mb.showinfo(title, message, **options)
if title is not None and message is not None:
LOG.action(message.split('\n')[-1], f"- MESSAGEBOX => {title.strip()}")
return s
def asklink(title: str, prompt: str, encoding: str | None = 'utf-8', require_https: bool = False, initialvalue: str | None = None, show: str | None = None, warning_message: str | None = None):
link: str = sdg.askstring(title, prompt, initialvalue=initialvalue, show=show)
if not warning_message:
warning_message = f"{lang[133]}\n{lang[359]}"
if require_https:
while not link.lstrip().startswith('https://'):
showwarning(title, warning_message)
link: str = sdg.askstring(title, prompt, initialvalue=link, show=show)
return simple_webbrowser.LinkString(link.rstrip(), encoding)
def clamp(val: float | int, _min: float | int, _max: float | int) -> object:
"""
clamp clamps and returns a value
Clamping a value is setting it between the max value and min value in case it exceeds those
Args:
val (Any): the value to clamp
_min (Any): the min value allowed
_max (Any): the max value allowed
Returns:
type(val): the clamped value of val
"""
if val < _min:
return _min
if val > _max:
return _max
return val
def open_in_file_explorer(path: str):
if sys.platform == "win32":
os.startfile(path)
elif sys.platform == "darwin":
subprocess.Popen(["open", path])
else:
subprocess.Popen(["xdg-open", path])
desktop_win = Tk()
LOG.action("The window has been created")
text_widget = WriterClassicEditor(desktop_win, font=("Calibri", 13), borderwidth=5, undo=True)
LOG.action("The editor has been created sucessfully")
class WrongClipboardAction(Exception): ...
class InvalidSnippet(Exception): ...
class InvalidEngine(Exception): ...
class ScriptError(Exception): ...
class VersionError(Exception): ...
class PluginNotFoundError(Exception): ...
class CircularListenning(Exception): ...
class CallHistory:
def __init__(self, function_limit: int = 60):
self._history: list[int] = []
self._LIMIT = function_limit
def register_call(self, function_or_func_id: Callable | int):
if isinstance(function_or_func_id, int):
what_to_add = function_or_func_id
else:
what_to_add = id(function_or_func_id)
if what_to_add in self._history:
return
if len(self._history) == self._LIMIT:
self._history.pop(0)
self._history.append(what_to_add)
def has_been_registered(self, what_to_check: Callable | int):
if isinstance(what_to_check, int):
value = what_to_check
else:
value = id(what_to_check)
if value in self._history:
return True
return False
def clear_history(self):
self._history: list[int] = []
@property
def entry_limit(self):
return self._LIMIT
@property
def call_history(self):
return self._history.copy()
writerclassic_call_history = CallHistory(32)
class Listener:
def __init__(self, _id: bytes, target: Callable, output: Callable, condition: str = "True") -> None:
if self.target == self.output:
raise CircularListenning('cannot target the output function')
self._id: str = str(base64.b64encode(gzip.compress(_id)), 'utf-8')
self._target: Callable = target
self._output: Callable = output
self._condition: str = condition # [i] is evaluated later on
def run_output(self) -> Any | str:
if eval(self._condition, globals().copy()) is True:
return self._output()
return f"False condition; aborted listener with ID: {self._id}"
@property
def target(self):
return self._target
@property
def output(self):
return self._output
@property
def listener_id(self) -> str:
return self._id
class FunctionListeners:
def __init__(self):
self._stop_group = 'StoppedInactive'
self._listeners = {
self._stop_group: set()
}
def _create_subgroup(self, subgroup_function: Callable, listener: Listener, *other_listeners: Listener) -> int:
if subgroup_function in self._listeners.keys():
return 9 # [!?] Subgroup already exists
if self.edit_listener(listener.listener_id, 4) == 2:
self._listeners[subgroup_function] = {listener}
else:
return 10 # [!?] ID already exists
for other_listener in other_listeners:
if self.edit_listener(other_listener.listener_id, 4) == 2:
self._listeners[subgroup_function].add(other_listener)
else:
return 10 # [i] see above
return 0 # [*] Success!
def add_listeners(self, listeners: set[Listener]) -> int:
for listener in listeners:
if listener.target in self._listeners:
if self.edit_listener(listener.listener_id, 4) == 2:
self._listeners[listener.target] = listener
else:
return 10 # [!?] ID already exists
else:
self._create_subgroup(listener.target, listener)
return 0 # [*] Success!
def edit_listener(self, listener_id: str, operation_type: int) -> int:
correct_group = None
correct_listener = None
for listener_group in self._listeners.values():
for listener in listener_group:
if listener.listener_id == listener_id:
correct_group = listener_group
correct_listener = listener
break
if not correct_listener:
return 2 # [!?] Invalid ID
match operation_type:
case 1:
if correct_group == self._stop_group:
return 4 # [!?] Operation 1 failed since the listener was stopped already
self._listeners[self._stop_group].add(correct_listener)
self._listeners[correct_group].remove(correct_listener)
case 2:
if correct_group != self._stop_group:
return 3 # [!?] Operation 2 failed since the listener wasn't stopped
self._listeners[self._stop_group].remove(correct_listener)
self.add_listeners({correct_listener})
case 3:
self._listeners[correct_group].remove(correct_listener)
return correct_listener
case _:
return 5 # [!?] Invalid operation type (must be 1, 2 or 3)
return 0 # [*] Success!
def run_group(self, group: Callable, auto_purge: bool = True) -> int:
exception_occured = False
if group == self._stop_group:
return 6 # [!?] You cannot run the inactive group as a whole
if group not in self._listeners.keys():
return 7 # [!?] The group does not exist
for listener in self._listeners[group]:
try:
listener.run_output()
except Exception as e:
print(f"Listener {listener.listener_id} failed - {e}")
exception_occured = True
self.edit_listener(listener.listener_id, 3)
continue
if exception_occured:
if auto_purge:
return 8 # [!?] Successful with certain listeners being purged
return 1 # [!?] Successful with certain listeners giving errors but not being purged
return 0 # [*] Succesful with no errors or purges
def remove_group(self, group: Callable):
if group == self._stop_group:
return 12 # [!?] the disabled group cannot be removed
return self._listeners.pop(group, 11) # [!?] 11 if the group does not exist
def remove_all_groups(self):
for group in self._listeners:
if group == self._stop_group:
continue
self.remove_group(group)
return 0 # [*] Sucess!
@property
def listeners(self) -> dict[Callable | str, set[Listener]]:
return self._listeners.copy()
before_listeners = FunctionListeners()
after_listeners = FunctionListeners()
def is_being_listened(target: Callable, *groups: FunctionListeners):
if len(groups) == 0:
groups = (before_listeners, after_listeners)
for group in groups:
for possible_target in group.listeners:
if possible_target == target:
return True
return False
def has_been_called(function_or_function_id: Callable | int, call_history: CallHistory = writerclassic_call_history) -> bool:
return call_history.has_been_registered(function_or_function_id)
def clip_actions(__id: Literal['copy', 'paste'], __s: str = '') -> str:
"""
clip_actions sends an instruction to the clipboard
It could be either a copy or a paste instruction.
Args:
__id ('copy' or 'paste'): the action to run
__s (str): the text to copy (when using the 'copy' action). Defaults to ''.
Returns:
str: the value of __s when copying; the last item to be copied when pasting.
Raises:
WrongClipboardAction: if an action different from 'copy' or 'paste' is given.
"""
match __id:
case 'copy':
LOG.action(f"Copied '{__s}' to the clipboard")
pyclip.copy(__s)
return __s
case 'paste':
LOG.action("Pasted the contents")
return pyclip.paste()
case _:
LOG.error('Wrong clipboard action', 'ONLY COPY & PASTE ALLOWED')
raise WrongClipboardAction('Can only copy or paste.')
settings: dict[str, dict[str, str | int | bool] | bool | str | list[str] | int] = get_settings(f"{config}/settings.json")
LOG.action("Got the settings")
if not settings["debugging"]:
ic.disable()
LOG.action("Debugging is disabled")
ic(settings)
if ic.enabled:
for debug_b in debug_a:
ic(debug_a)
ic(script_dir)
ic(script_path)
ic(f"{data_dir}/logo.png")
ic(now())
ic(settings['language'])
with open(os.path.join(locale, f"{settings['language'][:2]}.wclassic"), 'r', encoding='utf-8') as usedLangFile:
usedLang = usedLangFile.read()
lang = usedLang.split('\n')
LOG.write(f"{str(now())} - Language has been configured correctly: OK\n")
# [*] Windowing
LOG.write(f"{str(now())} - WriterClassic launched: OK\n")
if sys.platform == "win32":
desktop_win.iconbitmap(f"{data_dir}/app_icon.ico")
LOG.write(f"{str(now())} - Icon has been changed to WriterClassic's icon [WINDOWS ONLY]: OK\n")
LATEST = None
ic(LATEST)
# [!] Very Important: Keeping track of versions and commits
APP_VERSION = "v12.0.0"
ADVANCED_VERSION ="v11.0.0.372"
# [i] the fourth number up here, is the commit where this changes have been made
ABOUT_WRITER = f"""App name: WriterClassic
Developer: MF366 (at GitHub: MF366-Coding)
Version number: {APP_VERSION[1:]}
Powered by: Python 3.11.8 (x64)
Tested on: Windows, Linux
https://mf366-coding.github.io/writerclassic.html
https://github.com/MF366-Coding/WriterClassic
Thank you for using Writer Classic! <3
"""
def advanced_clipping(__action: Literal['copy', 'paste', 'cut'], text_widget: WriterClassicEditor = text_widget) -> str:
"""
advanced_clipping sends something to the clipboard based on the GUI
Args:
__action ('copy', 'paste', 'cut'): the clipboard action to perform
text_widget (WriterClassicEditor, optional): the WriterClassicEditor widget that gets affected by the 'paste' and 'cut' operations. Defaults to text_widget.
Returns:
str: either the value of a copy/paste operation or an empty string
"""
before_listeners.run_group(advanced_clipping)
writerclassic_call_history.register_call(id(advanced_clipping))
selection: str = ''
try:
# [*] Get the current selection
selection = text_widget.get(SEL_FIRST, SEL_LAST)
except TclError:
selection = INSERT
if __action in ('copy', 'cut'):
return ''
__action = 'paste'
if __action in ('copy', 'cut'):
clip_actions('copy', selection)
if __action == 'cut':
text_widget.replace(SEL_FIRST, SEL_LAST, '')
return selection
__s: str = clip_actions('paste')
if selection == INSERT:
text_widget.insert(INSERT, __s)
else:
text_widget.replace(SEL_FIRST, SEL_LAST, __s)
after_listeners.run_group(advanced_clipping)
return __s
copy, paste, cut = lambda: advanced_clipping('copy'), lambda: advanced_clipping('paste'), lambda: advanced_clipping('cut')
# [i] Config files
ic(APP_VERSION)
ic(ADVANCED_VERSION)
ic(settings['theme'])
LOG.write(f"{str(now())} - Got the current theme: OK\n")
LOG.write(f"{str(now())} - Got the current font family/type: OK\n")
LOG.write(f"{str(now())} - Got the current font size: OK\n")
temp_files = os.listdir(temp_dir)
for temp_file in temp_files:
file_to_delete = os.path.join(temp_dir, temp_file)
if os.path.isfile(file_to_delete):
os.remove(file_to_delete)
class Stack:
def __init__(self):
"""
NOTE: Not a regular Stack data type!!!
This is a Stack that doesn't allow repeated values.
When a repeated value appears it instead of repeating gets moved to the last index.
The stack is initialized with an empty list.
"""
self.items = []
def fromlist(self, seq: list):
"""
Load all elements from a list (`seq`), except for items that can't be added such as booleans.
"""
if isinstance(seq, list):
old_items = self.content
self.items = []
for i in seq:
if not i:
continue
if not isinstance(i, str):
continue
if i not in self.items:
self.push(i)
else:
self.items.remove(i)
self.push(i)
return old_items
raise TypeError('cannot use anything other than a list')
# [i] VSCode marks this code as unreachable but it can actually be reached since type annotations are not strict in Python
loadlist = fromlist
def copy(self):
"""
Return a shallow copy of the whole stack
"""
s = Stack()
s.fromlist(self.content)
return s
def __len__(self) -> int:
"""
Lenght of the list
"""
return len(self.items)
def push(self, data) -> Any:
"""
push appends `data` to the stack
As explained above, if the item already exists, it gets moved to the last position.
Alias:
append
Args:
data (Any): the value to append
Returns:
Any: `data` or an empty string if the data can't be added
"""
if not data:
return ''
if not isinstance(data, str):
return ''
if data not in self.items:
self.items.append(data)
return data
self.items.remove(data)
self.items.append(data)
return data
append = push
def pop(self) -> Any:
"""
pop removes the last item
Alias:
remove
Returns:
Any: the last item
"""
return self.items.pop()
remove = pop
def peek(self):
"""
peek returns the last item
Alias:
top
Returns:
Any: last item in the stack
"""
return self.items[-1]
top = peek
@property
def is_empty(self) -> bool:
"""
Is the lenght 0?
"""
return len(self) == 0
@property
def content(self) -> list:
"""
Shallow copy of the items only
"""
return self.items.copy()
last_file: str | None = None
recent_stack = Stack()
for i in settings['recent']:
if not i:
settings['recent'].remove(i)
continue
if not isinstance(i, str):
settings['recent'].remove(i)
continue
if os.path.exists(i):
continue
settings['recent'].remove(i)
recent_files: list[str] = settings['recent'].copy()
if len(recent_files) > 0:
recent_stack.fromlist(recent_files)
last_file = recent_stack.top()
def fast_dump(*_):
"""
fast_dump dumps the settings of WriterClassic
Why use this instead of dump_settings from the settings_loader?
- This only dumps the 10 most recent files from recent_stack
- No arguments needed (hence the use of *_)
"""
before_listeners.run_group(fast_dump)
writerclassic_call_history.register_call(id(fast_dump))
if len(recent_stack) > 10:
settings['recent'] = recent_stack.content[-10:]
else:
settings['recent'] = recent_stack.content
after_listeners.run_group(advanced_clipping)
dump_settings(os.path.join(config, 'settings.json'), settings)
fast_dump()
# [i] Windowing... again
if current_file is False:
desktop_win.title(lang[1])
LOG.write(f"{str(now())} - Window's title was set to WriterClassic: OK\n")
config_font = Font(family="Segoe UI", size=12, slant='roman', weight='normal', underline=False, overstrike=False)