-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
1986 lines (1701 loc) · 69.1 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import curses, _curses
import string
import sys
import traceback
import pyperclip
from functools import partial
import os
import importlib
import json
import typing_extensions
from typing import Union, Optional, Callable, Any, List
from configparser import ConfigParser
from collections import deque
from traceback import print_exception
import re
import datetime
from algorithmic_compiler import AlgorithmicCompiler
from cpp_compiler import CppCompiler
from utils import display_menu, input_text, get_screen_middle_coords, browse_files
from custom_types import CommandType, OptionType
# Constants
CRASH_FILE_NAME = ".crash"
class App:
__singleton = None
def __new__(cls, *args, **kwargs):
"""
Creates a singleton of the class.
"""
if cls.__singleton is None:
cls.__singleton = super().__new__(cls)
return cls.__singleton
def __init__(self):
# Loads the config
with open("plugins_config.json", "r", encoding="utf-8") as f:
self.plugins_config = json.load(f) # The configuration of the plugins
# Loads the translations
self.translations = {} # Contains all the translations in all the translation files
self.language = self.plugins_config["BASE_CONFIG"]["language"] # Contains the language code of the chosen language (e.g. 'en' or 'fr').
for translation_file in os.listdir("translations/"):
with open(f"translations/{translation_file}", "r", encoding="utf8") as f:
# Loads the translations as dictionaries,
# e.g. translation_file = 'translations_en.json', self.translations['en'] = {...}
self.translations[translation_file[13:15]] = json.load(f)
self.current_text = "" # The text being displayed in the window
self.stdscr: Optional[_curses.window] = None # The standard screen (see curses library)
self.rows, self.cols = 0, 0 # The number of rows and columns in the window
self.lines = 1 # The number of lines containing text in the window
self.current_index = 0 # The current index of the cursor
self.command_symbol = ":" # The symbol triggering a command
self.commands = {
"q": CommandType(self.quit, self.get_translation("commands", "q"), False),
"q!": CommandType(partial(self.quit, True), self.get_translation("commands", "q!"), True),
"qs!": CommandType(partial(self.quit, True, True), self.get_translation("commands", "qs!"), True),
"s": CommandType(self.save, self.get_translation("commands", "s"), False),
"qs": CommandType(partial(self.save, quick_save=True), self.get_translation("commands", "qs"), False),
"o": CommandType(self.open, self.get_translation("commands", "o"), False),
"c": CommandType(self.compile, self.get_translation("commands", "c"), False),
"p": CommandType(self.compile_to_cpp, self.get_translation("commands", "p"), False),
"op": CommandType(self.options, self.get_translation("commands", "op"), False),
"h": CommandType(self.display_commands, self.get_translation("commands", "h"), False),
"z": CommandType(self.undo, self.get_translation("commands", "z"), False),
"a": CommandType(self.repeat_last_command, self.get_translation("commands", "a"), False),
# "t": CommandType(self.modify_tab_char, self.get_translation("commands", "t"), True),
# "j": CommandType(self.toggle_std_use, self.get_translation("commands", "j"), True),
# "st": CommandType(self.toggle_struct_use, self.get_translation("commands", "st"), True),
"cl": CommandType(self.clear_text, self.get_translation("commands", "cl"), True),
"is": CommandType(self.insert_text, self.get_translation("commands", "is"), True),
"rlt": CommandType(self.reload_theme, self.get_translation("commands", "rlt"), True),
"m": CommandType(self.mark_line, self.get_translation("commands", "m"), True),
# To add the command symbol to the text
self.command_symbol: CommandType(
partial(self.add_char_to_text, self.command_symbol),
self.command_symbol,
True
)
} # A dictionary of all the commands, either built-in or plugin-defined.
self.command_bind_controls = {
'o': 'o',
's': 'qs',
'z': 'z',
} # Binds a CTRL+Letter keybind to a command. Key is a letter and value is a command prefix.
self.last_used_command: Optional[str] = None # The prefix of the last command used
self.instructions_list = [] # The list of instructions for compilation, is only used by the compilation functions
self.tab_char = "\t" # The tab character
self.using_namespace_std = False # Whether to use the std namespace during the C++ compilation
self.use_struct_keyword = False # Whether to use the struct keyword in the functions' return type during the C++ compilation
self.logs = True # Whether to log
self.min_display_line = 0 # The minimum line displayed on the window (scroll)
self.cur = tuple() # The cursor
self.min_display_char = 0 # Useless at the moment
self.last_save_action = "clipboard" # What the user did the last time he saved some code from the editor ; can be 'clipboard' or the pah to a file.
self.compilers = {} # A dictionary of compilers for the editor
self.undo_actions = deque([], maxlen=21) # All the actions that can be used to undo
self.is_crash_reboot = False # Whether the editor has been rebooted from a crash. Can only be used through a plugin's init() method, will always be False otherwise.
self.marked_lines = [] # Which lines are currently marked by the user
self.left_placement_shift = 0 # By how many columns the line numbers should be shifted to the right
self.top_placement_shift = 0 # By how many lines the top of the code should be shifted from the top
self.input_locked = False # If True, will disable all keyboard input except for commands and plugins
self.use_ptrs_and_malloc = False # If True, will enable the pointers and memory allocations
self.skip_welcome_page = False # If True, will skip the welcome message on startup
self.invert_vertical_slider_direction = False # If True, the keys to move the vertical slider will be inverted
# Changes the class variable of browse_files to be the config's class variable
if self.plugins_config["BASE_CONFIG"]["default_save_location"] != "":
browse_files.last_browsed_path = self.plugins_config["BASE_CONFIG"]["default_save_location"]
else:
browse_files.last_browsed_path = os.path.normpath(os.path.join(os.path.dirname(__file__), "../"))
# Changes the namespace std use based on its setting last time
if "using_namespace_std" in self.plugins_config["BASE_CONFIG"].keys():
self.using_namespace_std = self.plugins_config["BASE_CONFIG"]["using_namespace_std"]
else:
self.plugins_config["BASE_CONFIG"]["using_namespace_std"] = False
# Changes the namespace std use based on its setting last time
if "use_struct_keyword" in self.plugins_config["BASE_CONFIG"].keys():
self.use_struct_keyword = self.plugins_config["BASE_CONFIG"]["use_struct_keyword"]
else:
self.plugins_config["BASE_CONFIG"]["use_struct_keyword"] = False
# Changes the tab character based on its setting last time
if "tab_char" in self.plugins_config["BASE_CONFIG"].keys():
self.tab_char = self.plugins_config["BASE_CONFIG"]["tab_char"]
else:
self.plugins_config["BASE_CONFIG"]["tab_char"] = self.tab_char
# Creates a maximum length for the queue of the undo actions based on the config
if "max_undo_size" in self.plugins_config["BASE_CONFIG"].keys():
self.undo_actions = deque([], maxlen=self.plugins_config["BASE_CONFIG"]["max_undo_size"] + 1)
else:
self.plugins_config["BASE_CONFIG"]["max_undo_size"] = self.undo_actions.maxlen - 1
# Whether to enable pointers and memory allocations based on the config
if "use_ptrs_and_malloc" in self.plugins_config["BASE_CONFIG"].keys():
self.use_ptrs_and_malloc = self.plugins_config["BASE_CONFIG"]["use_ptrs_and_malloc"]
else:
self.plugins_config["BASE_CONFIG"]["use_ptrs_and_malloc"] = self.use_ptrs_and_malloc
# Whether to skip the welcome message
if "skip_welcome_page" in self.plugins_config["BASE_CONFIG"].keys():
self.skip_welcome_page = self.plugins_config["BASE_CONFIG"]["skip_welcome_page"]
else:
self.plugins_config["BASE_CONFIG"]["skip_welcome_page"] = self.skip_welcome_page
# Whether to skip the welcome message
if "invert_vertical_slider_direction" in self.plugins_config["BASE_CONFIG"].keys():
self.invert_vertical_slider_direction = self.plugins_config["BASE_CONFIG"]["invert_vertical_slider_direction"]
else:
self.plugins_config["BASE_CONFIG"]["invert_vertical_slider_direction"] = self.invert_vertical_slider_direction
# Generates the list of options the user has access to
self.options_list = [
OptionType(self.get_translation('commands', 'std_use'), lambda: self.using_namespace_std, self.toggle_std_use),
OptionType(self.get_translation('commands', 'struct_use'), lambda: self.use_struct_keyword, self.use_struct_keyword),
OptionType(self.get_translation('commands', 'modify_tab_char'), lambda: repr(self.tab_char), self.modify_tab_char),
OptionType(self.get_translation('commands', 'use_ptrs_and_malloc'), lambda: self.use_ptrs_and_malloc, self.toggle_use_ptrs_and_malloc),
OptionType(self.get_translation('language', 'language'), lambda: self.language, self.change_language),
OptionType(self.get_translation('skip_welcome_page'), lambda: self.skip_welcome_page, self.toggle_skip_welcome_page),
OptionType(self.get_translation('change_max_undo_size', 'max_undo'),
lambda: self.plugins_config['BASE_CONFIG']['max_undo_size'], self.change_max_undo_size),
OptionType(self.get_translation('invert_vertical_slider_direction'), lambda: self.invert_vertical_slider_direction,
self.toggle_vertical_slider_direction)
] # The list of options the user has access to ; Follows the scheme <name> <current_state> <callback_trigger>
# Getting the theme
self._theme_parser = ConfigParser()
self._theme_parser.read("theme.ini")
# Preparing the color pairs
self.color_pairs = {
pair_name: self._theme_parser["PAIRS"].getint(pair_name, fallback_value)
for pair_name, fallback_value in (
("statement", 1),
("function", 2),
("variable", 3),
("instruction", 4),
("strings", 3),
("special_string", 5)
)
} # The number of the color pairs
self.color_control_flow = {
"statement": ("if", "else", "end", "elif", "for", "while", "switch", "case", "default", "const", "delete"),
"function": ("fx", "fx_start", "return", "CODE_RETOUR", "struct"),
"variable": ('int', 'float', 'string', 'bool', 'char'),
"instruction": ("print", "input", "arr", "tab", "init")
} # What each type of statement corresponds to
self.theme_scheme = self._theme_parser["SCHEME"].get("scheme", "DARK")
self.default_bg = curses.COLOR_BLACK
self.default_fg = curses.COLOR_WHITE
# Loads all the plugins
self.authorized_plugins_list: Optional[List[str]] = None # A list of the plugins authorized to load, or None if any plugin in the plugins folder can load
if "--authorized-plugins" in sys.argv:
arg = sys.argv[sys.argv.index("--authorized-plugins") + 1]
# If it is the path to a file
if arg.startswith("f:"):
with open(arg[2:], 'r', encoding="utf-8") as f:
# Each plugin name will be on a new line
self.authorized_plugins_list = f.read().split('\n')
else:
# Each plugin name will be separated by a ':'
self.authorized_plugins_list = arg.split(':')
self.plugins = self.load_plugins() # A dict containing all the plugins as list of [module, instance]
def main(self, stdscr: _curses.window):
"""
The main function, wrapped around by curses.
"""
# Curses initialization
self.stdscr: _curses.window = stdscr
self.stdscr.clear()
self.rows, self.cols = self.stdscr.getmaxyx()
# If a .crash file exists, we show a message asking if they want their data to be recovered,
# then we set current_text to its contents and delete it
if CRASH_FILE_NAME in os.listdir(os.path.dirname(__file__)) and "--file" not in sys.argv:
self._on_crash_recover()
# Declaring the color pairs
self._declare_color_pairs()
# Initializes the compilers
self._load_compilers()
# Initializes each plugin, if they have an init function
self._init_plugins()
# Deletes the given commands
if "--delete-commands" in sys.argv:
commands_to_delete_arg = sys.argv[sys.argv.index("--delete-commands") + 1]
# If the commands to delete are stored in a file
if commands_to_delete_arg.startswith("f:"):
with open(commands_to_delete_arg[2:], 'r', encoding="utf-8") as f:
commands_to_delete_arg = f.read()
# Splits the commands into a list of commands to delete
commands_to_delete = commands_to_delete_arg.split(":")
for e in commands_to_delete:
try:
del self.commands[e]
except KeyError: pass
# If the app had not previously crashed, we display the welcome page
if self.is_crash_reboot is False and not self.skip_welcome_page:
self.show_welcome_page()
# Displays the text
self.display_text()
self.apply_stylings()
self.stdscr.refresh()
# App main loop
while True:
# Gets the current screen size
self.rows, self.cols = self.stdscr.getmaxyx()
# Key input
self.stdscr.nodelay(True)
try:
key = self.stdscr.getkey()
except _curses.error:
continue
finally:
# Calls the plugins fixed_update function
for plugin in self.plugins.values():
if hasattr(plugin[1], "fixed_update"):
plugin[1].fixed_update()
self.stdscr.nodelay(False)
# If the undo is full, dumping the earliest element of queue
if len(self.undo_actions) == self.undo_actions.maxlen:
self.undo_actions.popleft()
# If system key is pressed
if key == self.command_symbol:
self.handle_command_key()
# If it is a regular key
else:
# Screen clearing
self.stdscr.clear()
# Handles the input as regular keys
if not self.input_locked:
self.handle_regular_key(key)
# Calls the plugins update_on_keypress function
for plugin in self.plugins.values():
if hasattr(plugin[1], "update_on_keypress"):
plugin[1].update_on_keypress(key)
# Clamping the index
self.current_index = max(min(self.current_index, len(self.current_text)), 0)
# Displays the current text
# TODO Longer lines
self.display_text()
# Visual stylings, e.g. adds a full line over the input
self.apply_stylings()
# Screen refresh after input
self.stdscr.refresh()
def handle_regular_key(self, key: str):
"""
Handles the regular input.
:param key: The key pressed by the user.
"""
# If the key IS a backspace character, we remove the last character from the text
if key in ("\b", "\0") or key.startswith("KEY_") or key.startswith("CTL_") or key.startswith("ALT_") \
or len(key) != 1 or (len(key) == 1 and ord(key) <= 26):
if key in ("KEY_BACKSPACE", "\b", "\0"):
if self.current_index > 0:
# Makes the action undoable
self.undo_actions.append(
{
"action_type": "removed_char",
"char": self.current_text[self.current_index - 1],
"index": self.current_index - 1,
"adder": 0
}
)
# Removes the character from the text
self.current_text = self.current_text[:self.current_index - 1] + self.current_text[
self.current_index:]
self.current_index -= 1
elif key == "KEY_DC": # Delete key
if self.current_index < len(self.current_text):
# Makes the action undoable
self.undo_actions.append(
{
"action_type": "removed_char",
"char": self.current_text[self.current_index],
"index": self.current_index,
"adder": 0
}
)
# Removes the character from the text
self.current_text = self.current_text[:self.current_index] + self.current_text[
self.current_index + 1:]
elif key in ("KEY_UP", "KEY_DOWN"):
text = self.current_text + "\n"
indexes = tuple(index for index in range(len(text)) if text.startswith('\n', index))
closest_index = min(indexes, key=lambda x: abs(x - self.current_index))
closest_index = indexes.index(closest_index)
closest_index = closest_index + (-1) ** (key == "KEY_UP")
try:
if closest_index <= 0:
if "\n" in self.current_text:
self.current_index = self.current_text.index("\n")
else:
self.current_index = len(self.current_text)
else:
self.current_index = indexes[closest_index]
except IndexError:
pass
elif key == "KEY_LEFT":
self.current_index -= 1
elif key == "KEY_RIGHT":
self.current_index += 1
elif key == "CTL_LEFT":
self.current_index -= 1
while self.current_index >= 0 and self.current_text[self.current_index] in string.ascii_letters:
self.current_index -= 1
elif key == "CTL_RIGHT":
self.current_index += 1
while self.current_index < len(self.current_text) and self.current_text[
self.current_index] in string.ascii_letters:
self.current_index += 1
elif key in ("KEY_NPAGE", "KEY_PPAGE"): # Move vertical slider up/down
increment = 1
if key == "KEY_NPAGE":
increment *= -1
if self.invert_vertical_slider_direction:
increment *= -1
self.min_display_line += increment
if self.min_display_line < 0:
self.min_display_line = 0
if self.min_display_line > self.lines - 1:
self.min_display_line = self.lines - 1
elif key == "KEY_F(1)":
self.commands["h"].command()
elif key == "KEY_F(4)":
self.commands["q"].command()
elif key == "KEY_SEND": # The key used to type '<', for some reason
self.add_char_to_text('<')
elif key == "CTL_END": # The key used to type '>', for some reason
self.add_char_to_text('>')
elif key == "SHF_PADSLASH": # The key used to type '!', for some reason
self.add_char_to_text('!')
elif key == "PADENTER":
self.add_char_to_text('\n')
elif len(key) == 1 and ord(key) <= 26:
# Finds which letter was pressed alongside CTRL
bound_letter = chr(ord('a') + ord(key) - 1)
# Looks for the letter in the binds
bound_command = self.command_bind_controls.get(bound_letter)
# If there is a bound command for this control, runs the command
if bound_command is not None:
self.commands[bound_command].command()
# If no command is bound for this control, prints it to the user
else:
self.stdscr.addstr(
self.rows - 1, 0,
self.get_translation("errors", "no_control_bound", letter=bound_letter)
)
"""elif key == "KEY_HOME":
self.min_display_char -= 1
if self.min_display_char < 0:
self.min_display_char = 0
elif key == "KEY_END":
self.min_display_char += 1"""
else:
# If the key is NOT a backspace character, we add the new character to the text
self.add_char_to_text(key)
def handle_command_key(self):
"""
Handles a command.
"""
# Writes the command symbol to the command area row
self.stdscr.addstr(self.rows - 1, 0, self.command_symbol)
# Awaits the user's full command
full_command = input_text(self.stdscr, 1, self.rows - 1)
# Gets if multiple commands are chained together
if '+' in full_command:
command_items = full_command.split('+')
else:
command_items = [full_command]
# Executes each command one after the other
for command in command_items:
# Gets the repeat count (e.g. ":5z" will repeat ":z" 5 times)
repeat_count = 1
if command != "" and command[0].isdigit():
# Finds the number before the command
repeat_count_str = re.search(r'\d+', command).group()
repeat_count = int(repeat_count_str)
# Removes the number from the command name so we can actually find the correct command
command = command[len(repeat_count_str):]
# If the command exists
if command in self.commands.keys():
# We get the command information
key_name, (function, name, hidden) = command, self.commands[command]
# We add the full command name to the command area row
self.stdscr.addstr(self.rows - 1, 1, key_name)
# We launch the command as many times as needed
for _ in range(repeat_count):
self.execute_command(function, command)
# Add a few spaces to clear the command name
self.stdscr.addstr(self.rows - 1, 0, " " * (len(full_command) + 1))
def execute_command(self, function: Callable[[], Any], key: str):
"""
Executes the given command.
:param function: A function to call (a command).
:param key: The prefix of the command.
"""
try:
# Remembering the current state of the text so the command can be undone
# However, not doing this if this is the undo command
if key != "z":
self.undo_actions.append(
{
"action_type": "command",
"current_text": self.current_text,
"current_index": self.current_index
}
)
# Actually launching the command
function()
# Keeps in mind the key used as being the last command
if key != "a":
self.last_used_command = key
# If a curses error happens, we warn the user and log the error
except curses.error as e:
self.stdscr.addstr(self.rows - 1, 5, self.get_translation("errors", "unknown"))
self.log(e)
print_exception(e)
# We also undo the action just in case
if key != "z":
self.undo()
def _init_plugins(self):
"""
Inits once every plugin that was loaded.
"""
msg_string = self.get_translation("loaded_plugin", plugin_name="{}")
for i, (plugin_name, plugin) in enumerate(self.plugins.items()):
if hasattr(plugin[1], "init"):
if not plugin[1].was_initialized:
plugin[1].init()
plugin[1].was_initialized = True
# Writes a message to the screen showing all imported plugins
self.stdscr.addstr(
self.rows - 4 - i,
self.cols - (len(msg_string.format(plugin_name)) + 2),
msg_string.format(plugin_name)
)
# Highlights the plugin name
self.stdscr.addstr(
self.rows - 4 - i,
self.cols - (len(msg_string.format(plugin_name)) - msg_string.find("{") + 2),
plugin_name,
curses.color_pair(self.color_pairs["instruction"])
)
msg_string = self.get_translation("loaded_n_plugins")
self.stdscr.addstr(
self.rows - 4 - len(self.plugins.keys()),
self.cols - (len(msg_string.format(len(self.plugins.keys()))) + 2),
msg_string.format(len(self.plugins.keys())), curses.color_pair(3)
)
def _load_compilers(self):
"""
Loads the base compilers.
"""
self.compilers["algorithmic"] = AlgorithmicCompiler(
{
"for": "Pour",
"if": "Si",
"while": "Tant Que",
"switch": "Selon",
"arr": "Tableau",
"tab": "Tableau",
"case": "Cas",
"default": "Autrement",
"fx": "Fonction",
"proc": "Procédure",
"const": "Constante"
},
{
"int": "Entier",
"float": "Réel",
"string": "Chaîne de caractères",
"bool": "Booléen",
"char": "Caractère"
},
["print", "input", "end", "elif", "else", "fx_start", "vars", "precond", "data", "datar", "result",
"return", "desc", "CODE_RETOUR", "init", "struct", "const", "delete"],
self.stdscr,
self.translations,
self.get_translation,
self,
self.tab_char
)
self.compilers["C++"] = CppCompiler(
('for', 'if', 'while', 'switch', 'arr', 'tab', 'case', 'default', 'fx', 'proc', 'struct'),
{
"int": "int",
"float": "float",
"string": "std::string",
"bool": "bool",
"char": "char"
},
["print", "input", "end", "elif", "else", "fx_start", "vars", "precond", "data", "datar", "result",
"return", "desc", "CODE_RETOUR", "init", "const", "delete"],
self.stdscr,
self
)
def _on_crash_recover(self):
"""
If a crash file exists, asks the user if they want to recover.
"""
CRASH_FILE_PATH = os.path.join(os.path.dirname(__file__), CRASH_FILE_NAME)
def recover_crash_data():
with open(CRASH_FILE_PATH, "r", encoding="utf-8") as f:
self.current_text = f.read()
self.display_text()
self.is_crash_reboot = True
modify_time = os.path.getmtime(CRASH_FILE_PATH)
modify_date = datetime.datetime.fromtimestamp(modify_time)
dateD_H_str = modify_date.strftime("%d/%m/%Y %H:%M:%S")
display_menu(
self.stdscr,
(
("Yes", recover_crash_data),
("No", lambda: None)
),
label=self.get_translation("crash_recovery", date=dateD_H_str),
clear=False
)
try:
os.remove(CRASH_FILE_PATH)
except FileNotFoundError:
pass
@property
def color_control_flow_fused(self):
return [
*self.color_control_flow["statement"],
*self.color_control_flow["function"],
*self.color_control_flow["instruction"]
]
def _declare_color_pairs(self):
"""
Declares all the curses color pairs based on the theme.
"""
# Sets the default colors
if hasattr(curses, f"COLOR_{self._theme_parser['SCHEME'].get('default_bg', 'BLACK')}"):
self.default_bg = getattr(curses, f"COLOR_{self._theme_parser['SCHEME'].get('default_bg', 'BLACK')}")
else:
self.default_bg = curses.COLOR_BLACK
if hasattr(curses, f"COLOR_{self._theme_parser['SCHEME'].get('default_fg', 'WHITE')}"):
self.default_fg = getattr(curses, f"COLOR_{self._theme_parser['SCHEME'].get('default_fg', 'WHITE')}")
else:
self.default_fg = curses.COLOR_WHITE
curses.init_pair(255, self.default_fg, self.default_bg)
self.stdscr.attron(curses.color_pair(255))
# Fetches all the possible color pair numbers in the theme
for i in range(1, 9):
# Finds each pair of colors in the theme
current_pair = self._theme_parser["COLORS"].get(f"pair_{i}")
# If the current pair is defined in the theme
if current_pair is not None:
# We turn it into an actual pair by separating the values on the comma
current_pair = current_pair.split(",")
# We check that this is indeed a pair, otherwise raise an error
if len(current_pair) != 2:
raise KeyError(self.get_translation(
"errors", "color_pair_creation_error", i=i, current_pair=current_pair
))
# Then we sanitize the values by stripping them from whitespaces and putting them in uppercase
for j in range(2):
current_pair[j] = current_pair[j].strip().upper()
# If it is the default color, we define it as such
if current_pair[j].lower().startswith("def"):
if j == 0: # Foreground
current_pair[j] = self._theme_parser['SCHEME'].get('default_fg', 'WHITE')
if j == 1: # Background
current_pair[j] = self._theme_parser['SCHEME'].get('default_bg', 'BLACK')
# We also check if this color exists in curses, and otherwise raise an exception
elif not hasattr(curses, f"COLOR_{current_pair[j]}"):
raise KeyError(self.get_translation(
"errors", "not_curses_color",
i=i, color=j, current_pair_element=current_pair[j]
))
# We then initialize the pair by finding the corresponding curses color
curses.init_pair(
i,
getattr(curses, f"COLOR_{current_pair[0]}"),
getattr(curses, f"COLOR_{current_pair[1]}")
)
# Sets the background color
self.stdscr.bkgd(' ', curses.color_pair(255))
def get_translation(self, *keys: str, language: str = None, **format_keys) -> str:
"""
Returns the translation of the given string.
:param keys: Every key, in order, towards the translation.
:param language: The language in which to translate in. If None (by default), the value of self.language is used.
:param format_keys: Parameters that would be used in the str.format() method.
:return: The translation.
"""
# Tries to reach the correct translation
try:
# Loads the translation in the given language
string = self.translations[self.language if language is None else language]
# Loads, key by key, the contents of the translation
for key in keys:
string = string[key]
# If anything happens, we fall back to english.
except KeyError:
if language != "en":
string = self.get_translation(*keys, language="en")
else:
raise KeyError(f"Translation for {keys} not found !")
# We format the string based on the given format_keys
if format_keys:
string = string.format(**format_keys)
# We return the given string
return string
def undo(self):
"""
Undoes the last action.
"""
# Checks if there are actions that can be undone, otherwise just leaves there
if len(self.undo_actions) == 0: return None
# Looks at the last action while removing it from the queue
last_action = self.undo_actions.pop()
# Remembers if an action was undone for later
undone_action = False
# If the last action is a character addition
if last_action["action_type"] == "added_char":
self.current_text = self.current_text[:last_action["index"]] + \
self.current_text[last_action["index"] + len(last_action["char"]):]
# Also refreshes the screen
undone_action = True
# If the last action was to remove a character, we add it back
elif last_action["action_type"] == "removed_char":
# Inserting the character back into the text
current_text = list(self.current_text)
current_text.insert(
last_action["index"], last_action["char"]
)
current_text = "".join(current_text)
self.current_text = current_text
# Putting the cursor back to where the character was
self.current_index = last_action["index"] + last_action["adder"]
# Refreshes the screen
undone_action = True
# If the last action was a command launch
elif last_action["action_type"] == "command":
# Resetting the current text and current index
self.current_text = last_action["current_text"]
self.current_index = last_action["current_index"]
# Refreshes the screen
undone_action = True
# If unknown, logs the action and recursively calls the function
else:
self.log(f"Unknown action : {last_action}")
# Tries to undo another action
self.undo()
# Refreshes the screen
if undone_action:
self.stdscr.clear()
self.display_text()
def quit(self, force_quit: bool = False, auto_quicksave: bool = False) -> None:
"""
Exits the app.
:param force_quit: If set to True, will automatically quit without saving. Default is False.
:param auto_quicksave: If set to True, will automatically quicksave. Default is False.
"""
def quit():
# Saves the plugin config, after saving the base config
if self.plugins_config["BASE_CONFIG"]["default_save_location"] != "":
self.plugins_config["BASE_CONFIG"]["default_save_location"] = browse_files.last_browsed_path
with open("plugins_config.json", "w", encoding="utf-8") as f:
json.dump(self.plugins_config, f, indent=2)
# Exits the app
sys.exit(0)
def save_and_quit():
self.save()
quit()
def cancel():
pass
# If we have been asked to, we quicksave
if auto_quicksave:
self.save(quick_save=True)
# Provides the option to save and quit, quit without saving, or cancel quitting.
if force_quit is False:
display_menu(
self.stdscr,
(
(self.get_translation("quit", "quit_without_save"), quit),
(self.get_translation("quit", "save_and_quit"), save_and_quit),
(self.get_translation("quit", "cancel"), cancel)
),
1, self.get_translation("quit", "quit_message"),
space_out_last_option = True
)
# If we have been asked to force quit, we just quit without asking the user
else:
quit()
def get_lineno_length(self) -> int:
"""
Returns the space taken by the line numbers?
"""
return len(str(self.lines)) + 1 + self.left_placement_shift
def display_text(self):
"""
Displays the text in current_text.
"""
# Calculates the size of the line numbers
self.calculate_line_numbers()
# Gets the position of the cursor on the window
self.cur = (
self.current_text[:self.current_index].count('\n') - self.min_display_line + self.top_placement_shift,
self.current_index - (self.current_text[:self.current_index].rfind('\n')) + self.get_lineno_length() - 1,
self.current_text[self.current_index]
if
self.current_index < len(self.current_text) # If the current index is after the end of the text
and self.current_text[self.current_index].isprintable() # Or if the character is not printable
else
" "
)
for i, line in enumerate(
self.current_text.split("\n")[self.min_display_line:self.min_display_line + (self.rows - 3) - self.top_placement_shift]
):
line = line[self.min_display_char:]
# Getting the splitted line for syntax highlighting
splitted_line = line.split(" ")
# Writing the line to the screen
if self.get_lineno_length() + len(line) < self.cols - self.left_placement_shift - 1: # -1 is for the scrollbar
# If the line's length does not overflow off the screen, we write it entirely
self.stdscr.addstr(i + self.top_placement_shift, self.get_lineno_length(), line)
else:
# If the line's length overflows off the screen, we write only the part that stays in the screen
self.stdscr.addstr(i + self.top_placement_shift, self.get_lineno_length(), line[:self.cols - self.get_lineno_length() - self.left_placement_shift])
# Tests the beginning of the line to add a color, syntax highlighting
self.syntax_highlighting(line, splitted_line, i)
# Calls the plugins update_on_syntax_highlight function
for plugin_name, plugin in tuple(self.plugins.items()):
if len(plugin) > 1:
if hasattr(plugin[1], "update_on_syntax_highlight"):
plugin[1].update_on_syntax_highlight(line, splitted_line, i)
else:
del self.plugins[plugin_name]
# Placing cursor
if 0 <= self.cur[1] < self.cols and 0 <= self.cur[0] < self.rows - 3:
try:
self.stdscr.addstr(*self.cur, curses.A_REVERSE)
except curses.error:
pass
def apply_stylings(self) -> None:
"""
Apply all the stylings to the screen.
"""
# Applies the bar at the bottom of the screen
try:
self.stdscr.addstr(self.rows - 3, 0, "▓" * self.cols)
except curses.error: pass
# Adds the commands list at the bottom of the screen
self.display_commands_list()
# Calculates the scrollbar
self.calculate_scrollbar()
# Gets the amount of lines in the text
self.calculate_line_numbers()
# Puts the line numbers at the edge of the screen
for i in range(self.min_display_line, min(self.lines, self.min_display_line + (self.rows - 3) - self.top_placement_shift)):
style = curses.A_REVERSE
if i in self.marked_lines: # Gives the line a different color if it marked
style |= curses.color_pair(self.color_pairs["statement"])
self.stdscr.addstr(i - self.min_display_line + self.top_placement_shift, self.left_placement_shift, str(i + 1).zfill(len(str(self.lines))), style)
self.stdscr.refresh()
def calculate_scrollbar(self):
"""
Calculate and display the scrollbar.
"""
total_lines_of_code = self.current_text.count("\n")
scrollbar_max_height = self.rows - 3 - self.top_placement_shift
if total_lines_of_code > scrollbar_max_height:
scrollbar_height = int(scrollbar_max_height / total_lines_of_code * scrollbar_max_height)
scrollbar_pos = self.top_placement_shift + int(
self.min_display_line / total_lines_of_code * scrollbar_max_height)
for i in range(scrollbar_height):
if scrollbar_pos + i < self.rows - 3:
self.stdscr.addstr(
scrollbar_pos + i,
self.cols - 1,
" ",
curses.A_REVERSE
)
def display_commands_list(self):
"""
Displays the list of commands at the bottom of the window.
"""
cols = 0
for key_name, (function, name, hidden) in self.commands.items():
if key_name != self.command_symbol and hidden is False:
generated_str = f"{self.command_symbol}{key_name} - {name}"
# If printing this text would overflow off the screen, we break out of the loop
if cols + len(generated_str) >= self.cols - 4:
try:
self.stdscr.addstr(self.rows - 2, cols, "...", curses.A_REVERSE)
except curses.error:
pass
# We also display "..." beforehand.
break
try:
# Adds the generated string at the right place of the screen
self.stdscr.addstr(self.rows - 2, cols, generated_str, curses.A_REVERSE)
# Keeping in mind the x coordinates of the next generated string
cols += len(generated_str)
# Followed by a space
self.stdscr.addstr(self.rows - 2, cols, " ")
except curses.error:
self.log(f"Could not display command {self.command_symbol}{key_name} - {name}")
cols += 1
# Adds a spacing between built-in and plugin commands
elif key_name == self.command_symbol:
cols += 3
def reload_theme(self):
"""
Reloads the theme.
"""
self._theme_parser.read("theme.ini")
self.color_pairs = {
pair_name: self._theme_parser["PAIRS"].getint(pair_name, fallback_value)
for pair_name, fallback_value in self.color_pairs.items()
}
self._declare_color_pairs()
# Adds a message at the bottom to warn the theme was reloaded
self.stdscr.addstr(self.rows - 1, 4, self.get_translation("theme_reloaded"))
def load_plugins(self):
"""
Loads all the plugins.
"""
from plugin import Plugin # Note : A bit dirty to put an import here, but required for it to work
# Creating the plugins folder if it does not exist
if not os.path.exists(os.path.join(os.path.dirname(__file__), "plugins")):
os.mkdir(os.path.join(os.path.dirname(__file__), "plugins"))
# Initializing the plugins var
plugins = {}
# Lists all the plugin files inside the plugins folder
for plugin in os.listdir(os.path.join(os.path.dirname(__file__), "plugins")):
if plugin.startswith("__") or os.path.isdir(os.path.join(os.path.dirname(__file__), "plugins", plugin)) \
or not plugin.endswith(".py") or (