-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
1467 lines (1116 loc) · 49.6 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 editorLibrary import *
''' Note:
CLASSE CONFIG
metodi
set(variable, value)
get(variable)
'''
root = Tk()
root.geometry('900x560')
root.title('Untitled - TindyEditor')
root.resizable(width=1, height=1)
language = StringVar(root)
language.set('python3')
language.trace('w', lambda *args: Syntaxhl.extract_text(open_mode=True))
fontSize = StringVar(root)
index = ''
if config.get('font'):
fontSize.set(config.get('font'))
else:
fontSize.set('Medium')
# -------------------
'''Checking S.O.'''
if sys.platform[:5].lower() == 'linux':
isLinux = 1
else:
isLinux = 0
##################
def getEncoding(filePath=None):
encodes = ['utf-8', 'utf-16', 'iso-8859-15', 'cp437']
for test in encodes:
try:
open(filePath, 'r', encoding=test)
except:
pass
else:
encoding = test
break
if encoding:
return encoding
else:
return 0
####################
class Syntaxhl():
colors = {
'Token.Text': "#000000",
'Token.Keyword': "#3060A6",
'Token.Keyword.Constant': "#3060A6",
'Token.Keyword.Declaration': "#3060A6",
'Token.Keyword.Namespace': "#3060A6",
'Token.Keyword.Pseudo': "#3060A6",
'Token.Keyword.Reserved': "#3060A6",
'Token.Keyword.Type': "#3060A6",
'Token.Name': "#000000",
'Token.Name.Attribute': "#4E9A06",
'Token.Name.Builtin': "#4E9A06",
'Token.Name.Builtin.Pseudo': "#4E9A06",
'Token.Name.Class': "#4E9A06",
'Token.Name.Constant': "#4E9A06",
'Token.Name.Decorator': "#4E9A06",
'Token.Name.Entity': "#4E9A06",
'Token.Name.Exception': "#4E9A06",
'Token.Name.Function': "#4E9A06",
'Token.Name.Function.Magic': "#4E9A06",
'Token.Name.Label': "#4E9A06",
'Token.Name.Namespace': "#4E9A06",
'Token.Name.Other': "#4E9A06",
'Token.Name.Tag': "#4E9A06",
'Token.Name.Variable': "#4E9A06",
'Token.Name.Variable.Class': "#4E9A06",
'Token.Name.Variable.Global': "#4E9A06",
'Token.Name.Variable.Instance': "#4E9A06",
'Token.Name.Variable.Magic': "#4E9A06",
'Token.Literal': "#3CBBDD",
'Token.Literal.Date': "#3CBBDD",
'Token.Literal.String': "#3CBBDD",
'Token.Literal.String.Affix': "#3CBBDD",
'Token.Literal.String.Backtick': "#3CBBDD",
'Token.Literal.String.Char': "#3CBBDD",
'Token.Literal.String.Delimiter': "#3CBBDD",
'Token.Literal.String.Doc': "#3CBBDD",
'Token.Literal.String.Double': "#3CBBDD",
'Token.Literal.String.Escape': "#3CBBDD",
'Token.Literal.String.Heredoc': "#3CBBDD",
'Token.Literal.String.Interpol': "#3CBBDD",
'Token.Literal.String.Other': "#3CBBDD",
'Token.Literal.String.Regex': "#3CBBDD",
'Token.Literal.String.Single': "#3CBBDD",
'Token.Literal.String.Symbol': "#3CBBDD",
'Token.Operator': "#C10E18",
'Token.Operator.Word': "#C10E18",
'Token.Punctuation': "#494141",
'Token.Comment': "#AD7FA8",
'Token.Comment.Hashbang': "#AD7FA8",
'Token.Comment.Multiline': "#AD7FA8",
'Token.Comment.Preproc': "#AD7FA8",
'Token.Comment.Single': "#AD7FA8",
'Token.Comment.Special': "#AD7FA8",
'Token.Literal.Number': "#04137A",
'Token.Literal.Number.Bin': "#04137A",
'Token.Literal.Number.Float': "#04137A",
'Token.Literal.Number.Hex': "#04137A",
'Token.Literal.Number.Integer': "#04137A",
'Token.Literal.Number.Integer.Long': "#04137A",
'Token.Literal.Number.Oct': "#04137A",
'Token.Declaration': "#F53200",
}
lexers = {
'css': pygments.lexers.CssLexer(),
'html': pygments.lexers.HtmlLexer(),
'javascript': pygments.lexers.JavascriptLexer(),
'json': pygments.lexers.JsonLexer(),
'python3': pygments.lexers.Python3Lexer(),
'php': pygments.lexers.PhpLexer(startinline=True),
'mysql': pygments.lexers.MySqlLexer(),
'sql': pygments.lexers.SqlLexer(),
'XML': pygments.lexers.XmlLexer()
}
def extract_text(event=None, return_mode=False, open_mode=False):
if open_mode is False:
if return_mode is False:
linestart = textPad.index('insert linestart')
lineend = textPad.index('insert lineend')
text = textPad.get(linestart, lineend)
Syntaxhl.find_syntax(text, linestart, lineend)
else:
linestart = str(int(textPad.index('insert linestart').split('.')[0]) - 1) + '.' + textPad.index('insert linestart').split('.')[1]
lineend = str(int(textPad.index('insert lineend').split('.')[0]) - 1) + '.' + textPad.index('insert lineend-1c').split('.')[1]
text = textPad.get(linestart, lineend)
Syntaxhl.find_syntax(text, linestart, lineend)
else:
text = textPad.get('1.0', 'end')
# Syntaxhl.lexer = pygments.lexers.guess_lexer(text) # Non riconosce molto bene
for tag in textPad.tag_names():
textPad.tag_remove(tag, '1.0', 'end')
lines = text.split('\n')
for i in range(len(lines)):
linestart = f'{str(i + 1)}.0'
lineend = f'{str(i + 1)}.{len(lines[i])}'
text = textPad.get(linestart, lineend)
Syntaxhl.find_syntax(text, linestart, lineend)
for wordtype in Syntaxhl.colors.keys():
textPad.tag_config(wordtype, foreground=Syntaxhl.colors[wordtype]) # Imposta il colore del testo
def analyze_language(text):
pass
def find_syntax(text, linestart, lineend):
count = 0
lexer = Syntaxhl.lexers[language.get()] # Language.get() contiene i linguaggi
for tag in textPad.tag_names(): # Esiste un modo più veloce?
textPad.tag_remove(tag, linestart, lineend)
for pair in pygments.lex(text, lexer):
wordtype = str(pair[0])
word = pair[1]
if word == "\n":
return
#index = textPad.search(word, linestart, stopindex=lineend)
chars = len(word)
count += chars
column = int(linestart.split('.')[1])
line = int(linestart.split('.')[0])
index = f'{line}.{count}'
column = int(index.split('.')[1])
textPad.tag_add(wordtype, f'{line}.{str(column - chars)}', index)
##################
def downloadTheme():
global clrschms
result = getThemes(clrschms)
if result:
config.set('themeList', json.dumps(result))
##################
def popup(event):
cmenu.config(bg=Colors.pop_bg, fg=Colors.pop_fg, activebackground=Colors.pop_bg_active)
cmenu.tk_popup(event.x_root, event.y_root)
'''Scelta tema'''
def theme(x=None):
global bgc, fgc, clrschms
if config.get('theme') and x is None:
val = config.get('theme')
else:
val = themechoice.get()
config.set('theme', val)
clrs = clrschms[val] # 000000.FFFFFF
fgc, bgc = clrs.split('.')
fgc, bgc = '#' + fgc, '#' + bgc
textPad.config(bg=bgc, fg=fgc)
config.set('theme', val)
def setFontSize(font=None):
config.set('font', str(font))
font = font.lower()
if font == 'small':
font = 9
elif font == 'medium':
font = 11
elif font == 'large':
font = 13
lnlabel.config(font = f'Helvetica {font}')
textPad.config(font = f'Helvetica {font}')
def getFontSize():
font = fontSize.get().lower()
if font == 'small':
font = 9
elif font == 'medium':
font = 11
elif font == 'large':
font = 13
return font
class Colors:
mblack = '#171717'
black = '#171E28' #prima #515151
black2 = '#282C34'
black3 = '#31363F'
black4 = '#444447'
white = '#F0F0F0'
white2 = '#F7F7F7'
grey = '#B3B3B3'
grey2 = '#ABB2BF'
grey3 = '#9DA5B4'
blue = "#729FCF"
pop_bg = white
pop_fg = black
pop_bg_active = white2
pop_bg_list = 'white'
active_line_highlight = '#E4FFD5'
def night_mode(event=None): # Bug: creazione dei bookmark in nightmode: aggiungere colore globale per fg e bg, che venga preso sul momento dalla funzione draw - Aggiungere nightmode per tutte le finestre secondarie, menu contestuale compreso
current_theme = themechoice.get() # Potrei utilizzare il tag 'sel' per modificare il colore della selezione
objects = ((menubar, filemenu, viewmenu, editmenu, aboutmenu, themesmenu, recentFiles, settingsMenu))
if nightmodeln.get():
nightmodeln.set(0)
Colors.pop_bg = Colors.white
Colors.pop_fg = Colors.black
Colors.pop_bg_active = Colors.white2
Colors.pop_bg_list = 'white'
Colors.active_line_highlight = '#E4FFD5'
themechoice.set(current_theme)
theme(1)
textPad.config(insertbackground="#000000")
lnlabel.config(bg='#DDFFDC', fg='#650909')
infobar.config(fg=Colors.black, bg=Colors.white)
scroll_x.config(bg=Colors.white, activebackground=Colors.white, troughcolor=Colors.grey, highlightbackground=Colors.white2)
scroll_y.config(bg=Colors.white, activebackground=Colors.white, troughcolor=Colors.grey, highlightbackground=Colors.white2)
shortcutbar.config(bg=Colors.white)
bookmarkbar.config(bg=Colors.white)
root.config(bg=Colors.white)
selector.config(bg=Colors.white, fg=Colors.black, activebackground=Colors.white2, activeforeground=Colors.black)
selector["menu"].config(bg=Colors.white, fg=Colors.black, activebackground=Colors.white2, activeforeground=Colors.black)
fontSelector.config(bg=Colors.white, fg=Colors.black, activebackground=Colors.white2, activeforeground=Colors.black)
fontSelector["menu"].config(bg=Colors.white, fg=Colors.black, activebackground=Colors.white2, activeforeground=Colors.black)
fr.config(bg=Colors.white)
for i in objects:
i.config(fg=Colors.black, bg=Colors.white, activebackground=Colors.blue, activeforeground=Colors.black)
for i in bookmarkbar.winfo_children():
i.config(bg=Colors.white, fg=Colors.black, activebackground=Colors.white2, activeforeground=Colors.black)
for i in shortcutbar.winfo_children():
i.config(bg=Colors.white)
else:
nightmodeln.set(1)
Colors.pop_bg = Colors.black2
Colors.pop_fg = Colors.grey
Colors.pop_bg_active = Colors.mblack
Colors.pop_bg_list = Colors.black2
Colors.active_line_highlight = '#082E58'
textPad.config(fg=Colors.grey2, bg=Colors.black2, insertbackground="#5386E9")
lnlabel.config(fg=Colors.grey2, bg=Colors.black2)
infobar.config(fg=Colors.grey3, bg=Colors.black3)
scroll_x.config(bg=Colors.black3, activebackground=Colors.black3, troughcolor=Colors.black2, highlightbackground=Colors.black2)
scroll_y.config(bg=Colors.black3, activebackground=Colors.black3, troughcolor=Colors.black2, highlightbackground=Colors.black2)
shortcutbar.config(bg=Colors.black3)
root.config(bg=Colors.black3)
bookmarkbar.config(bg=Colors.black3)
selector.config(bg=Colors.black3, fg=Colors.grey3, activebackground=Colors.mblack, activeforeground=Colors.grey3)
selector["menu"].config(bg=Colors.black3, fg=Colors.grey3, activebackground=Colors.mblack, activeforeground=Colors.grey3)
fontSelector.config(bg=Colors.black3, fg=Colors.grey3, activebackground=Colors.mblack, activeforeground=Colors.grey3)
fontSelector["menu"].config(bg=Colors.black3, fg=Colors.grey3, activebackground=Colors.mblack, activeforeground=Colors.grey3)
fr.config(bg=Colors.black3)
for i in objects:
i.config(fg=Colors.grey3, bg=Colors.black3, activebackground=Colors.black4, activeforeground=Colors.grey3)
for i in bookmarkbar.winfo_children():
i.config(bg=Colors.black2, fg=Colors.grey3, activebackground=Colors.mblack, activeforeground=Colors.grey3)
for i in shortcutbar.winfo_children():
i.config(bg=Colors.black2)
def show_line_bar():
val = showln.get()
if val:
lnlabel.pack(side=LEFT, fill=Y, before=textPad)
else:
lnlabel.pack_forget()
def show_info_bar():
val = showinbar.get()
if val:
infobar.pack(expand=NO, fill=None, side=BOTTOM, anchor='c')
scroll_x.pack_forget()
scroll_x.pack(side=BOTTOM, fill=X)
elif not val:
infobar.pack_forget()
def update_line_number(load=False, event=None, paste=False, new=False):
global filename
update_info_bar()
if showln.get():
if load is False:
if int(lnlabel.index('end').split('.')[0]) < int(textPad.index('end').split('.')[0]):
lnlabel.config(state='normal')
line = int(textPad.index('end').split('.')[0]) - 1
lnlabel.insert('end', "\n" + str(line))
lnlabel.config(state='disabled')
if textPad.index('insert').split('.')[0] == textPad.index('end-1c').split('.')[0]:
lnlabel.see(textPad.index('end'))
else:
lnlabel.config(state='normal')
if int(lnlabel.index('end').split('.')[0]) > int(textPad.index('end').split('.')[0]):
lnlabel.delete(textPad.index('end'), 'end')
lnlabel.config(state='disabled')
lnlabel.yview_moveto(textPad.yview()[0])
else:
Syntaxhl.extract_text(open_mode=True)
lnlabel.config(state='normal')
lines = int(textPad.index('end').split('.')[0])
lnlabel.delete(2.0, 'end')
for i in range(2, lines):
lnlabel.insert('end', '\n' + str(i))
lnlabel.config(state='disabled')
if paste is False and new is False:
try:
bookmarks_list = config.get('bookmarks').split('\n')
except:
pass
else:
for i in bookmarks_list:
if i.split(';')[0] == filename:
Bookmark.bookmarks = ast.literal_eval(i.split(';')[1])
Bookmark.draw(delete=True)
return
elif bookmarks_list.index(i) == len(bookmarks_list):
Bookmark.bookmarks = {}
Bookmark.draw(delete=True)
selected_text = BooleanVar()
def highlight_line(interval=1):
textPad.tag_remove("active_line", 1.0, "end") # si può sfruttare questo meccanismo per aggiornare in tempo reale la barra mentre si seleziona
if selected_text.get() == False:
textPad.tag_add("active_line", "insert linestart", "insert lineend+1c")
textPad.tag_config("active_line", background=Colors.active_line_highlight)
textPad.after(interval, toggle_highlight)
def undo_highlight():
textPad.tag_remove("active_line", 1.0, "end")
def toggle_highlight(event=None):
val = hltln.get()
undo_highlight() if not val else highlight_line()
def fullscreen(event=None):
if fullscreenln.get():
state = 0
fullscreenln.set(0)
else:
state = 1
fullscreenln.set(1)
root.attributes('-fullscreen', state)
def anykey(event=None):
update_file()
update_line_number()
update_info_bar()
update_info_bar()
selected_text.set(False)
####################
def about(event=None):
showinfo("About", "Developed by @Luckymls & Francesco")
def help_box(event=None):
showinfo("Help", "For help email to melis.luca2014@gmail.com", icon='question')
def showCredits(event=None):
showinfo("Credits", "Created by Luca Melis and Francesco Tatti.");
def exit_editor():
if askokcancel("Quit", "Do you really want to quit?"):
root.destroy()
root.protocol('WM_DELETE_WINDOW', exit_editor)
#####################
'''Index e tags'''
def select_all(event=None):
textPad.tag_add('sel', '1.0', 'end')
def on_find(event=None):
t2 = Toplevel(root, bg=Colors.pop_bg)
t2.title('Find')
t2.geometry('350x65+200+250')
t2.resizable(width=0, height=0)
t2.transient(root)
Label(t2, text="Find All:", bg=Colors.pop_bg, fg=Colors.pop_fg).grid(row=0, column=0, pady=4, sticky='e')
v = StringVar()
e = Entry(t2, width=25, textvariable=v, bg=Colors.pop_bg, fg=Colors.pop_fg)
e.grid(row=0, column=1, padx=2, pady=4, sticky='we')
c = IntVar()
Checkbutton(t2, text='Ignore Case', variable=c, bg=Colors.pop_bg, fg=Colors.pop_fg).grid(row=1, column=1, sticky='e', padx=2, pady=2)
Button(t2, text='Find All', underline=0, bg=Colors.pop_bg, fg=Colors.pop_fg, command=lambda: search_for(v.get(), c.get(), textPad, t2, e)).grid(row=0, column=2, sticky='e' + 'w', padx=2, pady=4)
def close_search():
textPad.tag_remove('match', '1.0', END)
t2.destroy()
t2.protocol('WM_DELETE_WINDOW', close_search)
def search_for(needle, cssnstv, textPad, t2, e):
textPad.tag_remove('match', '1.0', END)
count = 0
if needle:
pos = '1.0'
while True:
pos = textPad.search(needle, pos, nocase=cssnstv, stopindex=END)
if not pos:
break
lastpos = '%s+%dc' % (pos, len(needle))
textPad.tag_add('match', pos, lastpos)
count += 1
pos = lastpos
textPad.tag_config('match', foreground='white', background='blue')
e.focus_set()
t2.title('%d matches found' % count)
#######################################################################
insertln = IntVar()
gTL = StringVar()
def goToLine(event=None):
global gTL
t4 = Toplevel(root, bg=Colors.pop_bg)
t4.focus_set()
t4.title('Go to...')
t4.geometry('300x65')
t4.resizable(width=0, height=0)
t4.transient(root)
Label(t4, text="Line:", bg=Colors.pop_bg, fg=Colors.pop_fg).grid(row=0, column=0, pady=4, sticky='e')
pos = gTL.get() + '.0'
gTL.set('')
e = Entry(t4, width=25, textvariable=gTL, takefocus='active', bg=Colors.pop_bg, fg=Colors.pop_fg)
e.grid(row=0, column=1, padx=2, pady=4, sticky='we')
e.focus_set()
b = Button(t4, text='Go!', command=lineSearch, default='active', bg=Colors.pop_bg, fg=Colors.pop_fg, activebackground=Colors.pop_bg_active)
b.grid(row=0, column=2, sticky='e' + 'w', padx=2, pady=4)
# def check_content():
# accepted_characters = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Da implementare
# if i in accepted_characters:
# return True
# else:
# return False
#
# e. config(validate='key', validatecommand=check_content)
def close_goto(event=None):
textPad.tag_remove('lineSearch', 1.0, "end")
t4.destroy()
pos = gTL.get() + '.1'
t4.protocol("WM_DELETE_WINDOW", close_goto)
t4.bind('<Return>', lineSearch)
e.bind('<FocusOut>', close_goto)
def lineSearch(event=None):
textPad.tag_remove('lineSearch', 1.0, "end")
pos = gTL.get() + '.0'
lastpos = int(gTL.get()) + 1
lastpos = str(lastpos) + '.0'
textPad.tag_add('lineSearch', pos, lastpos)
textPad.tag_config('lineSearch', foreground='white', background='blue')
textPad.see([pos])
lnlabel.yview_moveto(textPad.yview()[0])
########################################################################
'''Funzioni preesistenti di tkinter'''
def undo():
textPad.event_generate("<<Undo>>")
def redo():
textPad.event_generate("<<Redo>>")
def cut():
textPad.event_generate("<<Cut>>")
def copy():
textPad.event_generate("<<Copy>>")
def paste(event=None):
textPad.event_generate("<<Paste>>")
def on_paste(event=None):
textPad.delete('sel.first', 'sel.last') #replace?
previous_event = StringVar()
previous_event.set('Control')
def key_release(event=None):
if previous_event.get()[:-2] == 'Control':
if event.keysym.lower() == 'z' or event.keysym.lower() == "v" or event.char == '\x1a' or event.char == '\x16':
update_line_number(load=True, paste=True)
Syntaxhl.extract_text(open_mode=True)
previous_event.set(event.keysym)
def on_tab_key(event=None):
textPad.replace('insert-1c', 'insert', ' ')
# textPad.delete('insert-1c')
# textPad.insert('insert', ' ')
######################################################################
def wSetting():
t3 = Toplevel(root, bg=Colors.pop_bg)
t3.title('Settings')
t3.geometry('500x300')
t3.resizable(width=0, height=0)
t3.transient(root)
'''Menu'''
menuBar = Menu(t3)
t3.config(menu=menuBar)
nightMenu = Menu(menuBar, tearoff=0)
menuBar.add_cascade(label="Help", menu=nightMenu)
nightMenu.add_command(label="About", compound=LEFT, command=about)
nightMenu.add_command(label="Credits", compound=LEFT, command=showCredits)
menuBar.add_command(label="Close", compound=LEFT, command=t3.destroy)
############################################
def new_file(event=None):
global filename
filename = None
root.title("Untitled - Hydrogen")
textPad.delete(1.0, END)
update_line_number(load=True, new=True)
def open_file(event=None, file_name=None):
global filename
filename = file_name
if filename is None:
filename = filedialog.askopenfilename(defaultextension=".txt", filetypes=[("Text Documents", "*.txt"), ("All Files", "*.*")]) # ("All Files","*.*"), Da aggiungere dopo che aggiungiamo i vari tipi di codifica
if filename == "":
filename = None
else:
filename = str(filename)
if os.path.isfile(filename + ".backup"):
if os.path.getmtime(filename) < os.path.getmtime(filename + ".backup"):
if askokcancel("Yes", "Backup file has more recent changes, do you want to open the backup file instead?"):
root.title(os.path.basename(filename) + " - Hydrogen")
textPad.delete(1.0, END)
fh = open(filename + ".backup", "r")
textPad.insert(1.0, fh.read())
fh.close()
update_line_number(load=True)
Syntaxhl.extract_text(open_mode=True)
return
else:
pass
'''Ritorna il nome del file senza estensione'''
root.title(os.path.basename(filename) + " - Hydrogen")
textPad.delete(1.0, END)
fh = open(filename, "r")
textPad.insert(1.0, fh.read())
fh.close()
update_line_number(load=True)
Syntaxhl.extract_text(open_mode=True)
def open_recent_file(file_name=None): # Aggiungere funzione backup anche qui
global filename
nBase = os.path.basename(file_name)
filename = file_name
try:
fh = open(file_name, "r")
except:
messagebox.showerror("Error", "File not found")
checkConf = config.get('recent files').split('\n')
for file in checkConf:
exists = os.path.exists(file)
if not exists:
checkConf.remove(file)
toAdd = ''
for file in checkConf:
toAdd+= file+'\n'
config.set('recent files', toAdd)
else:
if os.path.isfile(filename + ".backup"):
if os.path.getmtime(filename) < os.path.getmtime(filename + ".backup"):
if askokcancel("Yes", "Backup file has more recent changes, do you want to open the backup file instead?"):
root.title(os.path.basename(filename) + " - Hydrogen")
textPad.delete(1.0, END)
fh = open(filename + ".backup", "r")
textPad.insert(1.0, fh.read())
fh.close()
update_line_number(load=True)
Syntaxhl.extract_text(open_mode=True)
return
else: pass
root.title(nBase + " - Hydrogen")
textPad.delete(1.0, END)
textPad.insert(1.0, fh.read())
fh.close()
update_line_number(load=True)
Syntaxhl.extract_text(open_mode=True)
def save(event=None):
global filename
try:
config.set('bookmarks', Bookmark.save(filename))
pathAlreadyExists = 0
checkConf = config.get('recent files')
if checkConf:
checkConf = checkConf.split('\n')
else:
checkConf = []
for testPath in checkConf:
if testPath == filename:
pathAlreadyExists = 1
if pathAlreadyExists is 0:
if len(checkConf) < 5:
config.set('recent files', filename + '\n', 1)
else:
config.set('recent files', filename + '\n', 1, 1)
f = open(filename, 'w')
letter = textPad.get(1.0, 'end')
f.write(letter)
f.close()
return filename
except:
return save_as()
def save_as():
global filename
'''Apro finestra wn per salvare file con nome'''
f = filedialog.asksaveasfilename(initialfile='Untitled.txt', defaultextension=".txt", filetypes=[("Text Documents", "*.txt")]) # ("All Files","*.*"),
fh = open(f, 'w')
filename = f
config.set('bookmarks', Bookmark.save(filename))
pathAlreadyExists = 0
checkConf = config.get('recent files')
if checkConf:
checkConf = checkConf.split('\n')
else:
checkConf = []
for testPath in checkConf:
if testPath == filename:
pathAlreadyExists = 1
if pathAlreadyExists is 0:
if len(checkConf) < 5:
config.set('recent files', filename + '\n', 1)
else:
config.set('recent files', filename + '\n', 1, 1)
textoutput = textPad.get(1.0, END)
fh.write(textoutput)
fh.close()
root.title(os.path.basename(f) + " - TindyEditor")
return filename
def update_file(event=None):
update_line_number()
global filename
if autoSave.get():
try:
rand = random.randint(1, 3)
if rand is 3:
baseName = os.path.basename(filename)
f = filename.replace('/'+baseName, '')+f'/.{baseName}.backup'
fh = open(f, 'w')
if not isLinux:
os.popen('attrib +S +H ' + f)
textoutput = textPad.get(1.0, END)
fh.write(textoutput)
fh.close()
except:
pass
def update_info_bar(event=None):
linecount = IntVar()
line = int(textPad.index('insert').split('.')[0])
total = int(textPad.index('end').split('.')[0]) - 1
column = int(textPad.index('insert').split('.')[1]) + 1
infobar.config(text=f'Line {line}/{total} | Column {column}')
def on_return_key(event=None):
if textPad.get('insert-2c') == ":" and (language.get() == 'python3' or language.get() == 'python2'):
textPad.insert('insert', ' ')
if textPad.get('insert-1l linestart') == ' ':
line = textPad.get('insert-1l linestart', 'insert-1l lineend')
for i in range(0, len(line), 4):
spaces = line[i:i+4]
if spaces == ' ':
textPad.insert('insert', ' ')
else:
break
Syntaxhl.extract_text(return_mode=True)
def dedent(event):
textPad.delete('insert linestart', 'insert linestart+4c')
def comment(event):
textPad.insert('insert linestart', '#')
def printSheet():
#Only work on Windows
filePath = save()
os.startfile(filePath, "print")
messagebox.showinfo("Title", 'Printing...')
######################################################################
'''Icone del menù'''
'''Spiegazione rapida: label = testo, accelerator= testo per scorciatoia combinazione tasti, compund=posizione, command=comando da richiamare se si spunta/clicca l'opzione'''
if not os.path.exists(os.getcwd()+'/icons/') or len(os.listdir(os.getcwd()+'/icons/')) < 11:
print('Icons not found, downloading...')
rDownload = downloadIcon(isLinux=isLinux)
if rDownload == 400:
input('Internet connection trouble. Please enable your internet connection and try again. Press any key to exit')
exit()
if isLinux:
completePath = os.getcwd() + '/'
else:
completePath = ''
root.iconbitmap('icons/pypad.ico')
new_fileicon = PhotoImage(file=completePath + 'icons/new_file.png')
open_fileicon = PhotoImage(file=completePath + 'icons/open_file.png')
saveicon = PhotoImage(file=completePath + 'icons/save.png')
cuticon = PhotoImage(file=completePath + 'icons/cut.png')
copyicon = PhotoImage(file=completePath + 'icons/copy.png')
pasteicon = PhotoImage(file=completePath + 'icons/paste.png')
undoicon = PhotoImage(file=completePath + 'icons/undo.png')
redoicon = PhotoImage(file=completePath + 'icons/redo.png')
on_findicon = PhotoImage(file=completePath + 'icons/on_find.png')
abouticon = PhotoImage(file=completePath + 'icons/about.png')
'''Menù'''
menubar = Menu(root, relief='ridge', bd=1, activebackground="#729FCF")
'''File menù'''
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", accelerator='Ctrl+N', compound=LEFT, image=new_fileicon, underline=0, command=new_file)
filemenu.add_separator()
filemenu.add_command(label="Open", accelerator='Ctrl+O', compound=LEFT, image=open_fileicon, underline=0, command=open_file)
recentFiles = Menu(filemenu, tearoff=0)
filemenu.add_cascade(label="Recent Files", menu=recentFiles)
themechoice = IntVar()
filemenu.config(bg=Colors.white, fg=Colors.black, activebackground="#729FCF", activeforeground="#FFFFFF")
'''Add Recent Files'''
if config.get('recent files'):
recentOpen = config.get('recent files').split('\n')
i = 0
for filePaths in recentOpen:
if len(filePaths) > 3:
i += 1
fileName = os.path.basename(filePaths)[0].upper() + os.path.basename(filePaths)[1:]
recentFiles.add_command(label=str(i) + '. ' + fileName, compound=LEFT, underline=0, command=lambda x=filePaths: open_recent_file(x))
filemenu.add_separator()
filemenu.add_command(label="Save", accelerator='Ctrl+S', compound=LEFT, image=saveicon, underline=0, command=save)
filemenu.add_command(label="Save as", accelerator='Shift+Ctrl+S', command=save_as)
autoSave = IntVar()
autoSave.set(1)
filemenu.add_checkbutton(label="Save Automatically", variable=autoSave, command=update_file)
if not isLinux: # Print Function
filemenu.add_separator()
filemenu.add_command(label="Print", command=printSheet)
filemenu.add_separator()
filemenu.add_command(label="Exit", accelerator='Alt+F4', command=exit_editor)
menubar.add_cascade(label="File", menu=filemenu)
recentFiles.config(activebackground="#729FCF", activeforeground="#FFFFFF")
'''Edit menù'''
editmenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Edit", menu=editmenu)
editmenu.add_command(label="Undo", compound=LEFT, image=undoicon, accelerator='Ctrl+Z', command=undo)
editmenu.add_command(label="Redo", compound=LEFT, image=redoicon, accelerator='Ctrl+Y', command=redo)
editmenu.add_separator()
editmenu.add_command(label="Cut", compound=LEFT, image=cuticon, accelerator='Ctrl+X', command=cut)
editmenu.add_command(label="Copy", compound=LEFT, image=copyicon, accelerator='Ctrl+C', command=copy)
editmenu.add_command(label="Paste", compound=LEFT, image=pasteicon, accelerator='Ctrl+V', command=paste)
editmenu.add_separator()
editmenu.add_command(label="Find", compound=LEFT, image=on_findicon, accelerator='Ctrl+F', command=on_find)
editmenu.add_separator()
editmenu.add_command(label="Select All", compound=LEFT, accelerator='Ctrl+A', underline=7, command=select_all)
editmenu.config(bg=Colors.white, fg=Colors.black, activebackground="#729FCF", activeforeground="#FFFFFF")
'''View menu'''
viewmenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="View", menu=viewmenu)
showln = IntVar()
showln.set(1)
viewmenu.add_checkbutton(label="Show Line Number", variable=showln, command=show_line_bar)
showinbar = IntVar()
showinbar.set(1)
viewmenu.add_checkbutton(label="Show Info Bar at Bottom", variable=showinbar, command=show_info_bar)
hltln = IntVar()
viewmenu.add_checkbutton(label="Highlight Current Line", variable=hltln, command=toggle_highlight)
viewmenu.add_command(label='Go to...', accelerator='Ctrl+G', command=goToLine)
viewmenu.add_separator()
themesmenu = Menu(viewmenu, tearoff=0)
viewmenu.add_cascade(label="Themes", menu=themesmenu)
viewmenu.add_separator()
fullscreenln = IntVar()
nightmodeln = IntVar()
viewmenu.add_checkbutton(label="Night Mode", variable=nightmodeln.get(), accelerator='F9', command=night_mode)
viewmenu.add_checkbutton(label="Full Screen", variable=fullscreenln.get(), accelerator='F11', command=fullscreen)
viewmenu.config(bg=Colors.white, fg=Colors.black, activebackground="#729FCF", activeforeground="#FFFFFF")
'''Dizionario con: nome: esadecimale carattere.esadecimale sfondo'''
####################
if config.get('themeList'):
clrschms = json.loads(config.get('themeList'))
downloadTheme()
else:
clrschms = {
'1. Default White': '000000.FFFFFF',
'2. Greygarious Grey': '83406A.D1D4D1',
'3. Lovely Lavender': '202B4B.E1E1FF',
'4. Aquamarine': '5B8340.D1E7E0',
'5. Bold Beige': '4B4620.FFF0E1',
'6. Cobalt Blue': 'ffffBB.3333aa',
'7. Olive Green': 'D1E7E0.5B8340',
}
config.set('themeList', json.dumps(clrschms))
###################
themechoice = StringVar()