-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpyro.py
More file actions
714 lines (610 loc) · 25.6 KB
/
pyro.py
File metadata and controls
714 lines (610 loc) · 25.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
#!/usr/bin/env python
"""
UnityModderPyro, Modified to work for Unity Mod Maker By Hippolippo
Original Code https://github.com/JamesStallings/pyro/blob/master/pyro:
simple elegant text editor built on python/tkinter
by James Stallings, June 2015
Adapted from:
Pygments Tkinter example
copyleft 2014 by Jens Diemer
licensed under GNU GPL v3
and
'OONO' designed and written by Lee Fallat, 2013-2014.
Inspired by acme, sam, vi and ohmwriter.
A sincere thanks to these good people for making their source code available for myself and others
to learn from. Cheers!
Pyro currently does a very minimalist job of text editing via tcl/tk ala tkinter.
What pyro does now:
colorizes syntax for a variety of text types; to wit:
Python
PlainText
Html/Javascript
Xml
Html/Php
Perl6
Ruby
Ini/Init
Apache 'Conf'
Bash Scripts
Diffs
C#
MySql
writes out its buffer
converts tabs to 4 spaces
It does this in an austere text editor framework which is essentially a glue layer
bringing together the tk text widget with the Pygment library for styling displayed
text. Editor status line is in the window title.
Pyro comes with one serious warning: it is a user-space editor. It makes no effort
to monitor state-change events on files and so should not be used in situations
where it is possible that more than one writer will have access to the file.
Pyro's current controls are as follows:
Ctrl+q quits
Ctrl+w writes out the buffer
Selection, copy, cut and paste are all per xserver/window manager. Keyboard navigation via
arrow/control keys, per system READLINE.
Pyro's current commands are:
#(num) move view to line 'num' and highlight it, if possible.
*(text) find text in file.
/(delim)(text)(delim)(text) search and replace
Pyro requires Tkinter and Pygment external libraries.
"""
RECENT = None
import os
import io
import sys
import ChangeManager
from GraphicalInterface import *
import MenuMethods
from functools import partial
try:
# Python 3
import tkinter
from tkinter import font, ttk, scrolledtext, _tkinter
except ImportError:
# Python 2
import Tkinter as tkinter
from Tkinter import ttk
import tkFont as font
import ScrolledText as scrolledtext
from ModObject import *
from pygments.lexers.python import PythonLexer
from pygments.lexers.special import TextLexer
from pygments.lexers.html import HtmlLexer
from pygments.lexers.html import XmlLexer
from pygments.lexers.templates import HtmlPhpLexer
from pygments.lexers.perl import Perl6Lexer
from pygments.lexers.ruby import RubyLexer
from pygments.lexers.configs import IniLexer
from pygments.lexers.configs import ApacheConfLexer
from pygments.lexers.shell import BashLexer
from pygments.lexers.diff import DiffLexer
from pygments.lexers.dotnet import CSharpLexer
from pygments.lexers.sql import MySqlLexer
from pygments.styles import get_style_by_name
pyros = []
windows = []
class LineNumbers(Text): #scrolledtext.ScrolledText
def __init__(self, master, text_widget, **kwargs):
super().__init__(master, **kwargs)
self.text_widget = text_widget
self.text_widget.bind('<KeyRelease>', self.match_up)
self.num_of_lines = -1
self.insert(1.0, '1')
self.configure(state='disabled')
def match_up(self, e=None):
p, q = self.text_widget.index("@0,0").split('.')
p = int(p)
final_index = str(self.text_widget.index(tkinter.END))
temp = self.num_of_lines
self.num_of_lines = final_index.split('.')[0]
line_numbers_string = "\n".join(str(1 + no) for no in range(int(self.num_of_lines)))
width = len(str(self.num_of_lines)) + 3
self.configure(state='normal', width=width)
if self.num_of_lines != temp:
self.delete(1.0, tkinter.END)
self.insert(1.0, line_numbers_string)
self.configure(state='disabled')
self.scroll_data = self.text_widget.yview()
self.yview_moveto(self.scroll_data[0])
class CoreUI(object):
"""
CoreUI is the editor object, derived from class 'object'. It's instantiation initilizer requires the
ubiquitous declaration of the 'self' reference implied at call time, as well as a handle to
the lexer to be used for text decoration.
"""
def __init__(self, lexer, filename="Untitled", mod=None, settings={}):
global RECENT
RECENT = self
self.settings = settings
set_window_count(get_window_count() + 1)
self.filename = filename
if mod is None:
mod = ModObject("Untitled")
self.mod = mod
self.contents = mod.get_text()
self.sourcestamp = {}
self.filestamp = {}
self.uiopts = []
self.lexer = lexer
self.lastRegexp = ""
self.markedLine = 0
self.root = tkinter.Tk()
self.root.withdraw()
self.root.iconbitmap("resources/unitymodmaker.ico")
self.root.protocol("WM_DELETE_WINDOW", self.destroy_window)
self.uiconfig()
self.root.bind("<Key>", self.event_key)
self.root.bind('<Control-KeyPress-q>', self.close)
self.root.bind('<Control-KeyPress-z>', self.undo)
self.root.bind('<Control-KeyPress-y>', self.redo)
self.root.bind('<Button>', self.event_mouse)
self.root.bind('<Configure>', self.event_mouse)
self.text.bind('<Return>', self.autoindent)
self.text.bind('<Tab>', self.tab2spaces4)
self.create_tags()
self.text.edit_modified(False)
self.bootstrap = [self.recolorize]
self.loadfile(self.contents)
self.recolorize()
self.root.geometry("1200x700+10+10")
self.initialize_menubar()
self.updatetitlebar()
self.scroll_data = self.text.yview()
self.starting()
global pyros
pyros.append(self)
def undo(self, e=None):
mod = ChangeManager.undo()
if mod is not None:
self.mod = mod
self.refresh(False)
return "break"
def redo(self, e):
mod = ChangeManager.redo()
if mod is not None:
self.mod = mod
self.refresh(False)
return "break"
def initialize_menubar(self):
self.menubar = tkinter.Menu(self.root)
self.filemenu = tkinter.Menu(self.menubar, tearoff=False)
self.editmenu = tkinter.Menu(self.menubar, tearoff=False)
self.createmenu = tkinter.Menu(self.menubar, tearoff=False)
self.buildmenu = tkinter.Menu(self.menubar, tearoff=False)
self.menubar.add_cascade(label="File", menu=self.filemenu)
self.filemenu.add_command(label="New", command=partial(MenuMethods.new,self.settings))
self.filemenu.add_command(label="Open", command=partial(MenuMethods.open, self.settings))
self.filemenu.add_command(label="Save", command=partial(MenuMethods.save, self, self.filename))
self.filemenu.add_command(label="Save as Renamed Copy", command=partial(MenuMethods.copy, self))
self.menubar.add_cascade(label="Edit", menu=self.editmenu)
self.editmenu.add_command(label="Change Mod Name", command=partial(MenuMethods.change_mod_name, self))
self.editmenu.add_command(label="Change Mod Version",
command=partial(MenuMethods.change_mod_version, self))
self.menubar.add_cascade(label="Create", menu=self.createmenu)
self.createmenu.add_command(label="Create Harmony Patch",
command=partial(MenuMethods.create_harmony_patch, self))
self.createmenu.add_command(label="Create Config Item",
command=partial(MenuMethods.create_config_item, self))
self.createmenu.add_command(label="Create Keybind",
command=partial(MenuMethods.create_keybind, self))
self.menubar.add_cascade(label="Build", menu=self.buildmenu)
self.buildmenu.add_command(label="Build and Install", command=partial(MenuMethods.build_install, self))
self.buildmenu.add_command(label="Export C# File", command=partial(MenuMethods.export_cs, self), state="disabled")
self.buildmenu.add_command(label="Generate Dotnet Files", command=partial(MenuMethods.export_dotnet, self))
self.root.config(menu=self.menubar)
def refresh(self, updateMod=True):
if updateMod:
self.scroll_data = self.text.yview()
text = self.text.get("1.0", tkinter.END)[:-1]
cursor = self.text.index(tkinter.INSERT)
# print(cursor)
index = ChangeManager.update(self.mod, self.text.get("1.0", tkinter.END)[:-1])
if index == "Locked":
self.undo()
return
self.mod.index = index
else:
text = None
index = self.mod.index
self.text.delete("1.0", tkinter.END)
self.text.insert("1.0", self.mod.get_text())
self.recolorize()
if self.mod.get_text() == text and text is not None:
self.text.mark_set("insert", str(cursor))
else:
text = self.text.get("1.0", tkinter.END).split("\n")
a, i = 0, 0
while a + len(text[i]) + 1 < index and i < len(text):
a += len(text[i])
a += 1
i += 1
j = index - a
self.text.mark_set("insert", "%d.%d" % (i + 1, j))
# self.root.update()
self.text.yview_moveto(self.scroll_data[0])
def uiconfig(self):
"""
this method sets up the main window and two text widgets (the editor widget, and a
text entry widget for the commandline).
"""
self.uiopts = {"height": "1000",
"width": "1000",
"cursor": "xterm",
"bg": "#00062A",
"fg": "#FFAC00",
"insertbackground": "#FFD310",
"insertborderwidth": "1",
"insertwidth": "3",
"exportselection": True,
"undo": True,
"selectbackground": "#E0000E",
"inactiveselectbackground": "#E0E0E0",
}
self.text = Text(master=self.root, wrap="none", **self.uiopts)
self.xsb = Scrollbar(self.root, orient="horizontal", command=self.text.xview)
self.text.configure(xscrollcommand=self.xsb.set)
self.xsb.grid(row=1, column=0, columnspan=2,sticky=(E,W))
self.ysb = Scrollbar(self.root, orient="vertical", command=self.text.yview)
self.text.configure(yscrollcommand=self.ysb.set)
self.ysb.grid(row=0, column=2,sticky=(N,S), rowspan=2)
self.ysb.configure(
activebackground="#FFD310",
borderwidth="0",
background="#68606E",
highlightthickness="0",
highlightcolor="#00062A",
highlightbackground="#00062A",
troughcolor="#20264A",
relief="flat")
'''self.cli = tkinter.Text(self.root, {"height": "1",
"bg": "#191F44",
"fg": "#FFC014",
"insertbackground": "#FFD310",
"insertborderwidth": "1",
"insertwidth": "3",
"exportselection": True,
"undo": True,
"selectbackground": "#E0000E",
"inactiveselectbackground": "#E0E0E0"
})'''
self.info = tkinter.Label(self.root, {"height": "1",
"bg": "#191F44",
"fg": "#FFC014",
"anchor": "w"
})
lineNums_uiopts = {"height": "60",
"width": "8",
"cursor": "xterm",
"bg": "#2c314d",
"fg": "#FFAC00",
"insertbackground": "#FFD310",
"insertborderwidth": "1",
"insertwidth": "3",
"exportselection": True,
"undo": True,
"selectbackground": "#E0000E",
"inactiveselectbackground": "#E0E0E0"
}
if self.settings["Show Line Numbers"].lower() == "true":
self.lineNums = LineNumbers(self.root, self.text, **lineNums_uiopts)
self.lineNums.grid(column=0,row=0,sticky=('nsew'))
self.text.grid(column=1, row=0, sticky=('nsew'))
self.root.grid_columnconfigure(0, weight=0)
self.root.grid_columnconfigure(1, weight=1)
self.info.grid(column=0, row=2, pady=1, sticky=('nsew'),columnspan=3)
self.info.visible = True
#self.cli.grid(column=0, row=1, pady=1, sticky=('nsew'))
#self.cli.bind("<Return>", self.cmdlaunch)
#self.cli.bind("<KeyRelease>", self.adjust_cli)
#self.cli.visible = True
#self.root.grid_columnconfigure(0, weight=1)
self.root.grid_rowconfigure(0, weight=1)
self.root.grid_rowconfigure(1, weight=0)
def updatetitlebar(self):
self.root.title("Unity Mod Maker - " + self.filename)
#self.root.update()
def destroy_window(self):
self.close()
def search(self, regexp, currentposition):
"""
this method implements the core functionality of the search feature
arguments: the search target as a regular expression and the position
from which to search.
"""
characters = tkinter.StringVar()
index_start = ""
index_end = ""
try:
index_start = self.text.search(
regexp,
currentposition + "+1c",
regexp=True,
count=characters)
except _tkinter.TclError:
index_start = "1.0"
if index_start == "":
index_start = self.text.index("insert")
length = characters.get()
if length == "":
length = "0"
index_end = "{0}+{1}c".format(index_start, length)
return index_start, index_end
def replace(self, regexp, subst, cp):
"""
this method implements the search+replace compliment to the search functionality
"""
index_start, index_end = self.search(regexp, cp)
if index_start != index_end:
self.text.delete(index_start, index_end)
self.text.insert(index_start, subst)
return index_start, index_end
def gotoline(self, linenumber):
"""
this method implements the core functionality to locate a specific line of text by
line position
arguments: the target line number
"""
index_start = linenumber + ".0"
index_end = linenumber + ".end"
return index_start, index_end
def cmd(self, cmd, index_insert):
"""
this method parses a line of text from the command line and invokes methods on the text
as indicated for each of the implemented commands
arguments: the command, and the insert position
"""
index_start = ""
index_end = ""
regexp = ""
linenumber = ""
cmdchar = cmd[0:1] # truncate newline
cmd = cmd.strip("\n")
if len(cmdchar) == 1:
regexp = self.lastRegexp
linenumber = self.markedLine
if cmdchar == "*":
if len(cmd) > 1:
regexp = cmd[1:]
index_start, index_end = self.search(regexp, index_insert)
self.lastRegexp = regexp
elif cmdchar == "#":
if len(cmd) > 1:
linenumber = cmd[1:]
index_start, index_end = self.gotoline(linenumber)
self.markedLine = linenumber
elif cmdchar == "/":
if len(cmd) > 3: # the '/', delimter chr, 1 chr target, delimiter chr, null for minimum useful s+r
snr = cmd[1:]
token = snr[0]
regexp = snr.split(token)[1]
subst = snr.split(token)[2]
index_start, index_end = self.replace(regexp, subst, index_insert)
return index_start, index_end
def cmdcleanup(self, index_start, index_end):
"""
this method cleans up post-command and prepares the command line for re-use
arguments: index beginning and end. ** this needs an audit, as does the entire
index start/end construct **
"""
if index_start != "":
self.text.mark_set("insert", index_start)
self.text.tag_add("sel", index_start, index_end)
# self.text.focus()
self.text.see(index_start)
self.cli.delete("1.0", tkinter.END)
def cmdlaunch(self, event):
"""
this method implements the callback for the key binding (Return Key)
in the command line widget, wiring it up to the parser/dispatcher method.
arguments: the tkinter event object with which the callback is associated
"""
mods = {
0: None,
0x0001: 'Shift',
0x0002: 'Caps Lock',
0x0004: 'Control',
0x0008: 'Left-hand Alt',
0x0010: 'Num Lock',
0x0080: 'Right-hand Alt',
0x0100: 'Mouse button 1',
0x0200: 'Mouse button 2',
0x0400: 'Mouse button 3'
}
if mods[event.state] == "Shift":
self.adjust_cli(event)
return
cmd = self.cli.get("1.0", tkinter.END)
self.cli.delete("1.0", tkinter.END)
if cmd[0] == "~":
try:
if cmd.count("\n") > 1:
exec(cmd[1:])
else:
print("User Command Executed", "(" + cmd[1:-1] + ")", "Gives:", eval(cmd[1:]))
self.root.update()
except Exception as e:
print(e)
self.adjust_cli(event)
return "break"
def adjust_cli(self, event=None):
height = self.cli.cget("height")
if min(self.cli.get("1.0", tkinter.END).count("\n"), 25) != height:
self.cli.config(height=min(self.cli.get("1.0", tkinter.END).count("\n"), 25))
def autoindent(self, event):
"""
this method implements the callback for the Return Key in the editor widget.
arguments: the tkinter event object with which the callback is associated
"""
indentation = ""
lineindex = self.text.index("insert").split(".")[0]
linetext = self.text.get(lineindex + ".0", lineindex + ".end")
for character in linetext:
if character in [" ", "\t"]:
indentation += character
else:
break
self.text.insert(self.text.index("insert"), "\n" + indentation)
return "break"
def tab2spaces4(self, event):
"""
this method implements the callback for the indentation key (Tab Key) in the
editor widget.
arguments: the tkinter event object with which the callback is associated
"""
self.text.insert(self.text.index("insert"), " ")
return "break"
def loadfile(self, text):
"""
this method implements loading a file into the editor.
arguments: the scrollable text object into which the text is to be loaded
"""
if text:
self.text.insert(tkinter.INSERT, text)
self.text.tag_remove(tkinter.SEL, '1.0', tkinter.END)
self.text.see(tkinter.INSERT)
def event_key(self, event):
"""
this method traps the keyboard events. anything that needs doing when a key is pressed is done here.
arguments: the associated event object
"""
keycode = event.keycode
char = event.char
self.recolorize()
self.updatetitlebar()
def event_write(self, event):
"""
the callback method for the root window 'ctrl+w' event (write the file to disk)
arguments: the associated event object.
"""
with open(self.filename, "w") as filedescriptor:
filedescriptor.write(self.text.get("1.0", tkinter.END)[:-1])
self.text.edit_modified(False)
self.root.title("Pyro: File Written.")
def event_mouse(self, event):
"""
this method traps the mouse events. anything that needs doing when a mouse
operation occurs is done here.
arguments: the associated event object
"""
self.updatetitlebar()
# self.recolorize()
def close(self, event=None):
self.mod.autosave(False)
import GraphicalInterface
GraphicalInterface.set_window_count(GraphicalInterface.get_window_count() - 1)
self.root.destroy()
if get_window_count() <= 0:
GraphicalInterface.set_window_count(0)
InterfaceMenu()
# ---------------------------------------------------------------------------------------
def starting(self):
"""
the classical tkinter event driver loop invocation, after running through any
startup tasks
"""
for task in self.bootstrap:
task()
def create_tags(self):
"""
thmethod creates the tags associated with each distinct style element of the
source code 'dressing'
"""
bold_font = font.Font(self.text, self.text.cget("font"))
bold_font.configure(weight=font.BOLD)
italic_font = font.Font(self.text, self.text.cget("font"))
italic_font.configure(slant=font.ITALIC)
bold_italic_font = font.Font(self.text, self.text.cget("font"))
bold_italic_font.configure(weight=font.BOLD, slant=font.ITALIC)
style = get_style_by_name('default')
for ttype, ndef in style:
tag_font = None
if ndef['bold'] and ndef['italic']:
tag_font = bold_italic_font
elif ndef['bold']:
tag_font = bold_font
elif ndef['italic']:
tag_font = italic_font
if ndef['color']:
foreground = "#%s" % ndef['color']
else:
foreground = None
self.text.tag_configure(str(ttype), foreground=foreground, font=tag_font)
def recolorize(self):
"""
this method colors and styles the prepared tags
"""
code = self.text.get("1.0", "end-1c")
tokensource = self.lexer.get_tokens(code)
start_line = 1
start_index = 0
end_line = 1
end_index = 0
for ttype, value in tokensource:
if "\n" in value:
end_line += value.count("\n")
end_index = len(value.rsplit("\n", 1)[1])
else:
end_index += len(value)
if value not in (" ", "\n"):
index1 = "%s.%s" % (start_line, start_index)
index2 = "%s.%s" % (end_line, end_index)
for tagname in self.text.tag_names(index1): # FIXME
self.text.tag_remove(tagname, index1, index2)
self.text.tag_add(str(ttype), index1, index2)
start_line = end_line
start_index = end_index
def update_info(self):
cursor = self.text.index(tkinter.INSERT)
self.info['text'] = "Cursor Position: row {}, column {}".format(cursor.split(".")[0],cursor.split(".")[1])
def add_window(window):
global windows
windows.append(window)
def mainloop():
global pyros
global windows
while True:
global RECENT
if RECENT is not None:
RECENT.root.deiconify()
RECENT.root.update()
RECENT.root.lift()
RECENT.text.focus()
RECENT = None
count = 0
for pyro in pyros:
try:
pyro.root.state()
exists = True
if exists:
count += 1
if pyro.settings["Show Line Numbers"]:
try:
pyro.lineNums.match_up()
except AttributeError:
pass
pyro.update_info()
pyro.root.update()
#pyro.adjust_cli()
box = pyro.text.get("1.0", tkinter.END)[:-1]
modtext = pyro.mod.get_text()
if box != modtext:
pyro.refresh()
except Exception as e:
pass
for window in windows:
try:
window.state()
window.update()
count += 1
except Exception:
pass
for window in get_windows():
try:
window.state()
window.update()
count += 1
except Exception:
pass
if count == 0:
print("Exiting: All Windows Deleted")
return