-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1703 lines (1248 loc) · 67.2 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from tkinter import *
from tkinter import messagebox as tkinter_messagebox
from tkinter import filedialog
from tkinter import colorchooser
from tklinenums import TkLineNumbers
from threading import Thread, Event
from typing import Callable
import ttkthemes
import tkinter.ttk as ttk
import idlelib.colorizer as idlecolorizer
import idlelib.percolator as idlepercolator
import requests, webbrowser
import re
import json
import subprocess
import platform
import os
import difflib
import ast
import importlib.util as importlib_util
import keyword, builtins, pkg_resources
__version__ = 'v1.4.0'
def messagebox(content: str, type: str, title=None):
if (type == 'info'):
tkinter_messagebox.showinfo(title or 'SparklyPython - Info', content)
elif (type == 'error'):
tkinter_messagebox.showerror(title or 'SparklyPython - Error', content)
elif (type == 'warning'):
tkinter_messagebox.showwarning(title or 'SparklyPython - Warning', content)
else:
pass
def find_best_matching_keys(string, array, threshold=0.5):
similar_keys = []
for key in array:
similarity_ratio = difflib.SequenceMatcher(None, string, key).ratio()
if similarity_ratio >= threshold:
similar_keys.append((key, similarity_ratio))
similar_keys.sort(key=lambda x: x[1], reverse=True)
return similar_keys
def center(win:Toplevel|Tk):
win.update_idletasks()
width = win.winfo_width()
frm_width = win.winfo_rootx() - win.winfo_x()
win_width = width + 2 * frm_width
height = win.winfo_height()
titlebar_height = win.winfo_rooty() - win.winfo_y()
win_height = height + titlebar_height + frm_width
x = win.winfo_screenwidth() // 2 - win_width // 2
y = win.winfo_screenheight() // 2 - win_height // 2
win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
win.deiconify()
class SparklyPythonNotebookWindow(Toplevel):
def __init__(self, master:Tk, title:str, settings, on_ok: Callable[[Toplevel, list], None], geometry=None):
super().__init__()
self.result = []
self.master = master
self.geometry(geometry or '400x300')
self.resizable(False, False)
self.title(title)
self.loading = None
try:
self.iconbitmap('./icon.ico')
except: pass
self.notebook = ttk.Notebook(self)
self.notebook.pack(expand=TRUE, fill=BOTH, padx=5, pady=5)
self.results = []
self.split_notebooks(settings)
buttons_frame = ttk.Frame(self)
buttons_frame.pack(side=BOTTOM, pady=10, padx=10)
save_button = ttk.Button(buttons_frame, width=10, text='OK', command=lambda: on_ok(self, self.results))
save_button.pack(side=RIGHT, padx=5)
cancel_button = ttk.Button(buttons_frame, width=10, text='Cancel', command=self.destroy)
cancel_button.pack(side=LEFT, padx=5)
self.notebook.bind('<Button-1>', lambda _: self.notebook.focus_set())
center(self)
def split_notebooks(self, settings):
for setting in settings:
page_name = setting[0]
page_settings = setting[1]
page_frame = self.create_widgets(page_settings)
page_frame.pack(expand=TRUE, fill=BOTH)
self.notebook.add(page_frame, text=page_name, state=DISABLED if len(page_settings) <= 0 else NORMAL)
def create_widgets(self, page_settings):
main_frame = ttk.Frame(self.notebook)
for setting in page_settings:
secondary_frame = ttk.Frame(main_frame)
widget_type = setting[1]
if widget_type == 'Entry':
label, _, default_value, config_value = setting
self.create_entry(secondary_frame, label, default_value, config_value)
elif widget_type == 'Checkbutton':
label, _, default_value, config_value = setting
self.create_checkbutton(secondary_frame, label, default_value, config_value)
elif widget_type == 'Dropdown':
label, _, options, default_value, config_value = setting
self.create_dropdown(secondary_frame, label, options, default_value, config_value)
elif widget_type == 'Color':
label, _, default_value, config_value = setting
self.create_colorchooser(secondary_frame, label, default_value, config_value)
else:
label = setting
self.create_label(secondary_frame, label)
secondary_frame.pack(fill=X, side=TOP, padx=5, pady=5)
return main_frame
def create_label(self, secondary_frame, label):
label_widget = ttk.Label(secondary_frame, text=label, justify=LEFT)
label_widget.pack(side=LEFT, fill=X)
label_widget.bind('<Configure>', lambda _: label_widget.config(wraplength=self.winfo_width() - 50))
def create_entry(self, secondary_frame, label, default_value, config_value):
ttk.Label(secondary_frame, text=label).pack(side=LEFT)
entry_var = StringVar(self.notebook, value=default_value)
entry = ttk.Entry(secondary_frame, textvariable=entry_var, width=35)
entry.pack(side=RIGHT, padx=5)
self.results.append((entry_var, config_value))
def create_checkbutton(self, secondary_frame, label, default_value, config_value):
checkbutton_var = BooleanVar(self.notebook, value=default_value)
checkbutton = ttk.Checkbutton(secondary_frame, text=label, variable=checkbutton_var)
checkbutton.pack(side=LEFT)
self.results.append((checkbutton_var, config_value))
def create_dropdown(self, secondary_frame, label, options, default_value, config_value):
ttk.Label(secondary_frame, text=label).pack(side=LEFT)
dropdown_var = StringVar(self.notebook, value=default_value)
dropdown = ttk.Combobox(secondary_frame, textvariable=dropdown_var, values=options, state='readonly', width=32)
dropdown.pack(side=RIGHT, padx=5)
self.results.append((dropdown_var, config_value))
def create_colorchooser(self, secondary_frame, label, default_value, config_value):
ttk.Label(secondary_frame, text=label).pack(side=LEFT)
entry_var = StringVar(self.notebook, value=default_value)
def open_color_chooser():
res = colorchooser.askcolor(default_value)
if (res[1] == None): return
entry_var.set(res[1].upper())
def reset_color():
for key in self.master.default_settings:
if (key[0] == config_value):
entry_var.set(key[1])
reset_button = ttk.Button(secondary_frame, text='Reset', command=reset_color, width=10)
reset_button.pack(side=RIGHT, padx=5)
chooser_button = ttk.Button(secondary_frame, text='Edit', command=open_color_chooser, width=10)
chooser_button.pack(side=RIGHT, padx=5)
entry = ttk.Entry(secondary_frame, textvariable=entry_var, width=10, state=DISABLED)
entry.pack(side=RIGHT, padx=5)
self.results.append((entry_var, config_value))
class SparklyPythonTooltip:
def __init__(self, widget:Button, text:str):
self.widget = widget
self.text = text
self.tooltip_window = None
self.id = None
self.widget.bind('<Enter>', self.enter)
self.widget.bind('<Leave>', self.leave)
def show_tooltip(self):
x, y, _, _ = self.widget.bbox(INSERT)
x += self.widget.winfo_rootx() + 80
y += self.widget.winfo_rooty() + 30
self.tooltip_window = Toplevel(self.widget)
self.tooltip_window.wm_overrideredirect(True)
self.tooltip_window.wm_geometry(f"+{x}+{y}")
label = ttk.Label(self.tooltip_window, text=self.text, background='#FFFFE0', relief=SOLID, borderwidth=1)
label.pack(ipadx=1)
def hide_tooltip(self):
if self.tooltip_window:
self.tooltip_window.destroy()
def enter(self, event):
self.id = self.widget.after(1000, self.show_tooltip)
def leave(self, event):
if self.id:
self.widget.after_cancel(self.id)
self.hide_tooltip()
class SparklyPythonLoadingTopLevel(Toplevel):
def __init__(self, total:int):
super().__init__()
self.total = total
self.step = 0
self.title('Loading...')
self.geometry('250x50')
self.resizable(0, 0)
try:
self.iconbitmap('./icon.ico')
except: pass
def on_closing(): pass
self.protocol("WM_DELETE_WINDOW", on_closing)
self.label = ttk.Label(self, text='0%')
self.label.pack(side=TOP)
self.progress_bar_variable = IntVar(self)
self.progress_bar = ttk.Progressbar(self, maximum=100, mode='determinate', value=0, variable=self.progress_bar_variable, length=250)
self.progress_bar.pack(side=LEFT, fill=X, padx=5, pady=5)
center(self)
def set_values(self, total):
self.total = total
def reset(self, reset_total=False):
self.step = 0
if (reset_total): self.total = 0
def add_step(self):
self.step += 1
res = (self.step / self.total) * 100
try:
self.label.config(text=f'{round(res)}%')
self.progress_bar_variable.set(res)
except: pass
def reached_max(self):
return True if self.step >= self.total else False
class SparklyPythonAutocomplete():
def __init__(self, master:Tk, text:Text, keywords:list[str]):
self.text = text
self.default_keywords = keywords
self.keywords = keywords
self.master = master
self.extracted_variables = []
self.__version__ = '1.0.0-beta-3'
self.listbox_frame = None
self.listbox = None
self.scrollbar = None
self.details_label = None
self.cache_details_variables = []
self.cache_class_methods_details = []
self.text.bind_all('<Key>', self.key_pressed)
def extract_variables(self):
try:
code = self.text.get('1.0', END)
parsed_code = ast.parse(code)
result = []
for node in ast.walk(parsed_code):
if isinstance(node, ast.FunctionDef):
result.append(node.name)
elif isinstance(node, ast.ClassDef):
result.append(node.name)
elif isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name):
result.append(target.id)
elif isinstance(node, ast.AnnAssign):
if isinstance(node.target, ast.Name):
result.append(node.target.id)
elif isinstance(node, ast.Import) or isinstance(node, ast.ImportFrom):
for alias in node.names:
result.append(alias.asname or alias.name)
return result
except:
return []
def get_members_from_module(self, module):
try:
spec = importlib_util.find_spec(module)
if spec is None:
return []
with open(spec.origin, 'r') as f:
source_code: str = f.read()
exported_members = []
source_code_splitted = source_code.split('\n')
for line in source_code_splitted:
if (line.startswith('#')): continue
match = re.match(r"from\s+\w+(\.\w+)*\s+import\s+(\w+)", line)
if match:
imported_module_name = match.group(2)
exported_members.append(imported_module_name)
tree = ast.parse(source_code)
for node in tree.body:
if isinstance(node, ast.ClassDef):
exported_members.append(node.name)
elif isinstance(node, ast.FunctionDef):
exported_members.append(node.name)
elif isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name):
exported_members.append(target.id)
elif isinstance(node, ast.AnnAssign):
if isinstance(node.target, ast.Name):
exported_members.append(node.target.id)
elif isinstance(node, ast.Import) or isinstance(node, ast.ImportFrom):
for alias in node.names:
exported_members.append(alias.asname or alias.name)
return list(set(exported_members))
except:
return []
def get_variable_details(self):
try:
code = self.text.get('1.0', END)
parsed_code = ast.parse(code)
result = []
def extract_comments(node):
if isinstance(node, (ast.FunctionDef, ast.ClassDef)):
if node.body and isinstance(node.body[0], ast.Expr) and isinstance(node.body[0].value, ast.Str):
return node.body[0].value.s.strip()
return None
for node in ast.walk(parsed_code):
if isinstance(node, ast.FunctionDef):
args = []
for arg in node.args.args:
arg_annotation = getattr(arg, 'annotation', None)
annotation_type = ast.dump(arg_annotation) if arg_annotation else None
if (annotation_type):
match = re.search(r"id='(\w+)'", annotation_type)
args.append({ 'arg': arg.arg, 'annotation': match.group(1) if match else None })
else:
args.append({ 'arg': arg.arg, 'annotation': None })
return_type = ast.dump(node.returns) if node.returns else None
return_type_match = re.search(r"id='(\w+)'", return_type) if return_type else None
result.append({ 'name': node.name, 'type': 'function', 'args': args, 'returns': return_type_match.group(1) if return_type_match else None, 'comments': extract_comments(node) })
elif isinstance(node, ast.ClassDef):
for item in node.body:
if isinstance(item, ast.FunctionDef) and item.name == '__init__':
args = []
for arg in item.args.args:
arg_annotation = getattr(arg, 'annotation', None)
annotation_type = ast.dump(arg_annotation) if arg_annotation else None
if (annotation_type):
match = re.search(r"id='(\w+)'", annotation_type)
args.append({ 'arg': arg.arg, 'annotation': match.group(1) if match else None })
else:
args.append({ 'arg': arg.arg, 'annotation': None })
result.append({ 'name': node.name, 'type': 'class', 'args': args, 'returns': None, 'comments': extract_comments(node) })
return result
except:
return []
def get_class_methods_details(self):
try:
code = self.text.get('1.0', END)
parsed_code = ast.parse(code)
result = []
def extract_comments(node):
if isinstance(node, (ast.FunctionDef, ast.ClassDef)):
if node.body and isinstance(node.body[0], ast.Expr) and isinstance(node.body[0].value, ast.Str):
return node.body[0].value.s.strip()
return None
for node in ast.walk(parsed_code):
if isinstance(node, ast.ClassDef):
functions = []
variables = []
for item in node.body:
if isinstance(item, ast.FunctionDef):
args = []
for arg in item.args.args:
arg_annotation = getattr(arg, 'annotation', None)
annotation_type = ast.dump(arg_annotation) if arg_annotation else None
if (annotation_type):
match = re.search(r"id='(\w+)'", annotation_type)
args.append({ 'arg': arg.arg, 'annotation': match.group(1) if match else None })
else:
args.append({ 'arg': arg.arg, 'annotation': None })
return_type = ast.dump(item.returns) if item.returns else None
return_type_match = re.search(r"id='(\w+)'", return_type) if return_type else None
functions.append({ 'name': item.name, 'args': args, 'returns': return_type_match.group(1) if return_type_match else None, 'comments': extract_comments(node) })
elif isinstance(item, ast.Assign):
for target in item.targets:
if isinstance(target, ast.Name):
variables.append(target.id)
result.append({ 'name': node.name, 'functions': functions, 'variables': variables })
return result
except:
return []
def get_installed_packages(self):
try:
packages = list([i.key.replace('-', '_') for i in pkg_resources.working_set])
return packages
except:
return []
def show_popup(self, matching_keys):
if not matching_keys:
self.hide_popup()
return
cursor_index = self.text.index(INSERT)
zoom = self.master.editor_font[1]
try:
x, y = self.text.bbox(cursor_index)[:2]
x += self.text.winfo_x()
x += self.master.linenumbers_frame.winfo_width() + self.master.explorer_frame.winfo_width()
y += zoom * 2
if not self.listbox_frame:
self.listbox_frame = ttk.Frame(self.master)
self.listbox_frame.place(x=x, y=y)
self.listbox = Listbox(self.listbox_frame, background=self.master.style.lookup('TFrame', 'background'), width=30, font=(self.master.editor_font[0], self.master.editor_font[1] - 2))
self.listbox.bind('<ButtonRelease-1>', self.on_listbox_select)
self.text.bind('<Tab>', self.tab_or_enter_pressed)
self.text.bind('<Up>', self.arrow_up_pressed)
self.text.bind('<Down>', self.arrow_down_pressed)
self.text.bind('<Button-1>', lambda _: self.hide_popup())
self.listbox.pack(side=LEFT)
self.scrollbar = ttk.Scrollbar(self.listbox_frame, command=self.listbox.yview)
self.scrollbar.pack(side=RIGHT, fill=Y)
self.listbox.config(yscrollcommand=self.scrollbar.set)
else:
self.listbox_frame.place_configure(x=x, y=y)
self.listbox.delete(0, END)
for key in matching_keys:
self.listbox.insert(END, key)
self.listbox.select_set(0)
except: pass
def show_popup_details_label(self, message: str):
cursor_index = self.text.index(INSERT)
zoom = self.master.editor_font[1]
try:
x, y = self.text.bbox(cursor_index)[:2]
x += self.text.winfo_x()
y += zoom * 2
if not self.details_label:
self.details_label = ttk.Label(self.text, text=message, background='#FFFFE0', font=self.master.editor_font, relief=SOLID, borderwidth=1)
self.details_label.pack()
self.details_label.place_configure(x=x, y=y)
self.text.bind('<Tab>', lambda _: self.hide_popup_details_label())
self.text.bind('<Up>', lambda _: self.hide_popup_details_label())
self.text.bind('<Down>', lambda _: self.hide_popup_details_label())
self.text.bind('<Enter>', lambda _: self.hide_popup_details_label())
self.text.bind('<Button-1>', lambda _: self.hide_popup_details_label())
else:
self.details_label.place_configure(x=x, y=y)
except: pass
def hide_popup(self):
if self.listbox_frame:
self.listbox_frame.destroy()
self.listbox_frame = None
self.listbox = None
self.scrollbar = None
self.text.unbind('<Tab>')
self.text.unbind('<Up>')
self.text.unbind('<Down>')
def hide_popup_details_label(self):
if self.details_label:
self.details_label.destroy()
self.details_label = None
def key_pressed(self, event):
if ('autocomplete.enabled' in self.master.settings and not self.master.settings['autocomplete.enabled']): return
self.keywords = self.default_keywords
variables = self.extract_variables()
if (len(variables) > 0):
self.extracted_variables = variables
self.keywords += self.extracted_variables
self.keywords = list(set(self.keywords)) # Removing duplicates
self.master.after(10, self.get_current_text)
def get_current_text(self):
current_text = self.text.get('insert linestart', INSERT)
if (len(current_text) <= 0):
self.hide_popup()
return
splitted = current_text.split(' ')
splitted = [s.replace('\t', '') for s in splitted]
index = len(splitted) - 1
_variables_details = self.get_variable_details()
if _variables_details != []: self.cache_details_variables = _variables_details
_class_methods_details = self.get_class_methods_details()
if _class_methods_details != []: self.cache_class_methods_details = _class_methods_details
if (current_text[len(current_text) - 1] == ' ' or current_text[len(current_text) - 1] == '\t'):
self.hide_popup()
return
if index >= 0:
previous_index = index - 1
if (previous_index < 0): previous_index = 0
previous_word = splitted[previous_index]
current_word = splitted[index]
if ('.' in current_word and len(current_word.split('.')) >= 2):
if (current_word.split('.')[1] != ''):
self.hide_popup()
for detail in self.cache_class_methods_details:
if detail['name'] == current_word.split('.')[0]:
functions = detail['functions']
for function in functions:
if function['name'] == current_word.split('.')[1]:
self.hide_popup_details_label()
result = []
for arg in function['args']:
result.append(arg['arg'] + ': ' + ('any' if arg['annotation'] == None else arg['annotation']))
string = '(' + ', '.join(result) + ') -> ' + (function['returns'] if function['returns'] != None else 'any') + (('\n' + function['comments']) if function['comments'] != None else '')
self.show_popup_details_label(string)
break
return
if (current_word.endswith('.') and current_word.split('.')[0] in [v['name'] for v in self.cache_class_methods_details]):
self.hide_popup()
for detail in self.cache_class_methods_details:
if detail['name'] == current_word.split('.')[0]:
variables = detail['variables']
functions = [v['name'] for v in detail['functions']]
self.show_popup_details_label(f'Methods and variables defined in \'' + detail['name'] + '\': \n' + '\n'.join(variables + functions) + '\n')
break
return
else:
self.hide_popup_details_label()
if (current_word.endswith('(') and current_word.split('(')[0] in [v['name'] for v in self.cache_details_variables]):
self.hide_popup()
for detail in self.cache_details_variables:
if detail['name'] == current_word.split('(')[0]:
result = []
for arg in detail['args']:
result.append(arg['arg'] + ': ' + ('any' if arg['annotation'] == None else arg['annotation']))
string = '(' + ', '.join(result) + ') -> ' + (detail['returns'] if detail['returns'] != None else 'any') + (('\n' + detail['comments']) if detail['comments'] != None else '')
self.show_popup_details_label(string)
break
return
else:
self.hide_popup_details_label()
if (current_word.endswith('(') or current_word.endswith(')') or current_word.endswith('"') or current_word.endswith('\'')):
self.hide_popup()
return
packages_installed = self.get_installed_packages()
keywords = self.keywords
if (current_word.split('.')[0] in packages_installed):
keywords = self.get_members_from_module(current_word.split('.')[0])
if (previous_word == 'import' or previous_word == 'from'):
match = re.match(r"from\s+(\w+)\s+import", current_text)
if match:
module_name = match.group(1)
module_members: list[str] = self.get_members_from_module(module_name)
keywords = module_members
else:
keywords = packages_installed
if any(keyword == current_word for keyword in keywords):
self.hide_popup()
return
if (self.master.settings['autocomplete.matchcase']):
matching_keys = [key for key in keywords if key.startswith(current_word)]
else:
matching_keys = []
best_match = find_best_matching_keys(current_word, keywords, threshold=0.1)
for match in best_match:
matching_keys.append(match[0])
self.show_popup(matching_keys)
def on_listbox_select(self, event):
configured_indentation = self.master.settings['editor.indentation']
global indentation
indentation = '\t'
if (configured_indentation != 'TAB' and configured_indentation.isdigit()):
indentation = ' ' * int(configured_indentation)
if self.listbox:
selected_item: str = self.listbox.get(self.listbox.curselection())
if selected_item:
current_text = self.text.get('insert linestart', INSERT)
splitted = current_text.split(' ')
splitted = [s.replace('\t', '') for s in splitted]
index = len(splitted) - 1
insert_index = self.text.index(INSERT)
if index >= 0:
tabs_count = current_text.count(indentation)
full_text = self.text.get('insert linestart', 'insert lineend')
second_splitted = full_text.split(' ')
second_splitted = [s.replace('\t', '') for s in second_splitted]
new_text = f'{indentation * tabs_count}' + ' '.join(splitted[:index] + [selected_item] + second_splitted[index + 1:])
self.text.replace(f'{INSERT} linestart', f'{INSERT} lineend', new_text)
# The undo and then redo makes Idlelib's colorizer to apply the colors again
self.text.edit_undo()
self.text.edit_redo()
selected_item_index = self.text.search(selected_item, insert_index, 'insert lineend')
if selected_item_index:
line, column = map(int, selected_item_index.split('.'))
new_index = f'{line}.{column + len(selected_item)}'
self.text.mark_set(INSERT, new_index)
self.hide_popup()
self.text.focus_set()
return 'break'
def tab_or_enter_pressed(self, event):
self.master.after(10, self.pressed_after)
return 'break'
def pressed_after(self):
configured_indentation = self.master.settings['editor.indentation']
global indentation
indentation = '\t'
if (configured_indentation != 'TAB' and configured_indentation.isdigit()):
indentation = ' ' * int(configured_indentation)
if self.listbox:
selected_item = self.listbox.get(self.listbox.curselection())
if selected_item:
current_text = self.text.get('insert linestart', INSERT)
splitted = current_text.split(' ')
splitted = [s.replace('\t', '') for s in splitted]
index = len(splitted) - 1
insert_index = self.text.index(INSERT)
if index >= 0:
tabs_count = current_text.count(indentation)
full_text = self.text.get('insert linestart', 'insert lineend')
second_splitted = full_text.split(' ')
second_splitted = [s.replace('\t', '') for s in second_splitted]
new_text = f'{indentation * tabs_count}' + ' '.join(splitted[:index] + [selected_item] + second_splitted[index + 1:])
self.text.replace(f'{INSERT} linestart', f'{INSERT} lineend', new_text)
# The undo and then redo makes Idlelib's colorizer to apply the colors again
self.text.edit_undo()
self.text.edit_redo()
selected_item_index = self.text.search(selected_item, insert_index, 'insert lineend')
if selected_item_index:
line, column = map(int, selected_item_index.split('.'))
new_index = f'{line}.{column + len(selected_item)}'
self.text.mark_set(INSERT, new_index)
self.hide_popup()
return 'break'
def arrow_up_pressed(self, event):
if self.listbox:
current_selection = self.listbox.curselection()
if current_selection:
if current_selection[0] > 0:
self.listbox.select_clear(current_selection[0])
self.listbox.select_set(current_selection[0] - 1)
self.listbox.see(current_selection[0] - 1)
else:
self.listbox.select_clear(current_selection[0])
self.listbox.select_set(self.listbox.size() - 1)
else:
self.listbox.select_set(self.listbox.size() - 1)
return 'break'
def arrow_down_pressed(self, event):
if self.listbox:
current_selection = self.listbox.curselection()
if current_selection:
if current_selection[0] < self.listbox.size() - 1:
self.listbox.select_clear(current_selection[0])
self.listbox.select_set(current_selection[0] + 1)
self.listbox.see(current_selection[0] + 1)
else:
self.listbox.select_clear(current_selection[0])
self.listbox.select_set(0)
return 'break'
class SparklyPythonExplorer():
def __init__(self, treeview: ttk.Treeview, root: Tk):
self.treeview = treeview
self.root = root
self.treeview.bind("<<TreeviewSelect>>", self.on_select)
def populate(self, parent: str, folder: str, path_so_far=''):
if (len(folder) <= 0): return
items = os.listdir(folder)
for item in items:
item_path = os.path.join(folder, item)
full_path = os.path.join(path_so_far, item)
if os.path.isdir(item_path):
folder_icon = self.treeview.insert(parent, 'end', text=f' {item}', open=False, values=(full_path, 'dir'))
self.populate(folder_icon, item_path, path_so_far=full_path)
else:
if (str(item).endswith('.py')):
self.treeview.insert(parent, 'end', text=f' {item}', values=(full_path, 'file'))
else:
self.treeview.insert(parent, 'end', text=f' {item}', values=(full_path, 'file'))
def on_select(self, event):
selected_item = self.treeview.selection()
if (not selected_item): return
full_path: str = os.path.join(self.root.startup_explorer_dir, self.treeview.item(selected_item, 'values')[0]).replace('\\', '/')
typeof = self.treeview.item(selected_item, 'values')[1]
if (typeof == 'file'):
if (full_path.endswith('.py')):
self.root.open_file(custom_path=full_path)
else:
if (self.root.settings['filesexplorer.defaultopennonpythonfiles']):
os.startfile(full_path)
def clear(self):
for item in self.treeview.get_children():
self.treeview.delete(item)
class StoppableThread(Thread):
def __init__(self, *args, **kwargs):
super(StoppableThread, self).__init__(*args, **kwargs)
self._stop_event = Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
class SparklyPythonIDE(Tk):
def __init__(self):
super().__init__()
self.style = ttkthemes.ThemedStyle(self)
self.style.set_theme(theme_name='arc')
try:
self.iconbitmap('./icon.ico')
except: pass
self.current_file_path = ''
self.startup_explorer_dir = ''
self.current_main_dir = ''
self.text_edited = False
self.settings = {
'previous_file_path': '',
'startup_explorer_dir': ''
}
self.default_settings = [
('window.update_check', True),
('terminal.python_command', 'python'), ('terminal.pause', True), ('terminal.save_file', True),
('linenumbers.enabled', True), ('linenumbers.justify', 'Right'),
('filesexplorer.enabled', True), ('filesexplorer.defaultopennonpythonfiles', True),
('editor.indentation', 'TAB'), ('editor.indentation_on_line', True), ('editor.open_previous_file', True), ('editor.font_name', 'Courier New'), ('editor.autosave', False),
('highlighter.comment', '#808080'), ('highlighter.keyword', '#1220E6'), ('highlighter.builtin', '#FF0000'), ('highlighter.string', '#008000'), ('highlighter.def', '#7F7F00'), ('highlighter.number', '#FF6600'),
('autocomplete.enabled', True), ('autocomplete.matchcase', False),
]
self.python_process = None
self.loading = None
for setting in self.default_settings:
self.settings[setting[0]] = setting[1]
self.title('SparklyPython')
self.geometry('1200x700')
self.check_configuration_file()
# Menu bar configuration
self.menu_bar = Menu(self)
file_menu = Menu(self.menu_bar, tearoff=0)
file_menu.add_command(label='New', command=self.new_file, accelerator='Ctrl+N')
file_menu.add_separator()
file_menu.add_command(label='Open File', command=lambda: self.open_file(explorer=True), accelerator='Ctrl+O')
file_menu.add_separator()
file_menu.add_command(label='Save', command=self.save_file, accelerator='Ctrl+S')
file_menu.add_command(label='Save As...', command=self.save_as_file)
file_menu.add_separator()
file_menu.add_command(label='Exit', command=self.exit_program, accelerator='Alt+F4')
self.menu_bar.add_cascade(label='File', menu=file_menu)
edit_menu = Menu(self.menu_bar, tearoff=0)
edit_menu.add_command(label='Undo', command=self.editor_undo, accelerator='Ctrl+Z')
edit_menu.add_command(label='Redo', command=self.editor_redo, accelerator='Ctrl+Y')
edit_menu.add_separator()
edit_menu.add_command(label='Zoom In', command=self.editor_zoom_in, accelerator='Ctrl+Plus')
edit_menu.add_command(label='Zoom Out', command=self.editor_zoom_out, accelerator='Ctrl+Minus')
edit_menu.add_separator()
edit_menu.add_command(label='Format Indentation', command=self.editor_format_indentation, accelerator='Shift+Alt+F')
edit_menu.add_separator()
edit_menu.add_command(label='Copy', command=lambda: self.editor.event_generate("<<Copy>>"), accelerator='Ctrl+C')
edit_menu.add_command(label='Cut', command=lambda: self.editor.event_generate("<<Cut>>"), accelerator='Ctrl+X')
edit_menu.add_command(label='Paste', command=lambda: self.editor.event_generate("<<Paste>>"), accelerator='Ctrl+V')
self.menu_bar.add_cascade(label='Edit', menu=edit_menu)
python_menu = Menu(self.menu_bar, tearoff=0)
python_menu.add_command(label='New Prompt', command=self.python_new_prompt)
python_menu.add_separator()
python_menu.add_command(label='Run Python', command=self.python_run, accelerator='F5')
python_menu.add_command(label='Stop Python', command=self.python_stop)
self.menu_bar.add_cascade(label='Python', menu=python_menu)
self.menu_bar.add_command(label='Settings', command=self.open_settings)
self.menu_bar.add_command(label='About', command=self.open_about)
# Add menus to the menu bar
self.config(menu=self.menu_bar)
# All required frames
self.status_frame = ttk.Frame(self)
self.status_frame.pack(fill=X, pady=5, side=BOTTOM)
self.main = ttk.Frame(self)
self.main.pack(expand=TRUE, fill=BOTH)
self.editor_frame = ttk.Frame(self.main)
self.editor_frame.pack(side=RIGHT, expand=TRUE, fill=BOTH)
self.explorer_frame = ttk.Frame(self.main)
self.explorer_frame.pack(side=LEFT, fill=Y)
self.linenumbers_frame = ttk.Frame(self.main)
self.linenumbers_frame.pack(side=LEFT, fill=Y)
# Adding scroll bars
self.editor_scrollbar_yview = ttk.Scrollbar(self.editor_frame, orient=VERTICAL)
self.editor_scrollbar_yview.pack(side=RIGHT, fill=Y)
self.editor_scrollbar_xview = ttk.Scrollbar(self.editor_frame, orient=HORIZONTAL)
self.editor_scrollbar_xview.pack(side=BOTTOM, fill=X)
# Create the editor and ballon tip
self.editor_font = (self.settings['editor.font_name'], 10)