-
Notifications
You must be signed in to change notification settings - Fork 13
/
Untitled_file_61.py
325 lines (256 loc) · 11.7 KB
/
Untitled_file_61.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
import sys
from builtins import print
import os
import getpass
import socket
from pathlib import Path
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QPlainTextEdit, QDesktopWidget
from PyQt5.QtGui import QSyntaxHighlighter, QTextCharFormat, QColor, QFont, QTextCursor
from PyQt5.QtCore import Qt, pyqtSignal, QRegExp, QProcess, QThread
class PlainTextEdit(QPlainTextEdit):
commandSignal = pyqtSignal(str)
commandZPressed = pyqtSignal(str)
def __init__(self, parent=None, movable=False):
super().__init__(parent)
self.name = "[" + str(getpass.getuser()) + "@" + str(socket.gethostname()) + "]" + " ~" + str(
os.getcwd()) + " >$ "
self.appendPlainText(self.name)
self.movable = movable
self.parent = parent
self.commands = [] # This is a list to track what commands the user has used so we could display them when
# up arrow key is pressed
self.tracker = 0
self.setStyleSheet("QPlainTextEdit{background-color: #212121; color: white; padding: 8;}")
self.font = QFont()
self.font.setFamily("Iosevka")
self.font.setPointSize(12)
self.text = None
self.setFont(self.font)
self.document_file = self.document()
self.previousCommandLength = 0
self.document_file.setDocumentMargin(-1)
def center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def mousePressEvent(self, event):
if self.movable is True:
self.parent.mousePressEvent(event)
def mouseMoveEvent(self, event):
if self.movable is True:
self.parent.mouseMoveEvent(event)
def textUnderCursor(self):
textCursor = self.textCursor()
textCursor.select(QTextCursor.WordUnderCursor)
return textCursor.selectedText()
def keyPressEvent(self, e):
cursor = self.textCursor()
if self.parent:
if e.modifiers() == Qt.ControlModifier and e.key() == Qt.Key_A:
return
if e.modifiers() == Qt.ControlModifier and e.key() == Qt.Key_Z:
self.commandZPressed.emit("True")
return
if e.key() == 16777220: # This is the ENTER key
text = self.textCursor().block().text()
if text == self.name + text.replace(self.name, "") and text.replace(self.name, "") != "": # This is to prevent adding in commands that were not meant to be added in
self.commands.append(text.replace(self.name, ""))
self.commandSignal.emit(text)
self.appendPlainText(self.name)
return
if e.key() == Qt.Key_Up:
try:
if self.tracker != 0:
cursor.select(QTextCursor.BlockUnderCursor)
cursor.removeSelectedText()
self.appendPlainText(self.name)
self.insertPlainText(self.commands[self.tracker])
self.tracker += 1
except IndexError:
self.tracker = 0
return
if e.key() == Qt.Key_Down:
try:
cursor.select(QTextCursor.BlockUnderCursor)
cursor.removeSelectedText()
self.appendPlainText(self.name)
self.insertPlainText(self.commands[self.tracker])
self.tracker -= 1
except IndexError:
self.tracker = 0
if e.key() == 16777219:
if cursor.positionInBlock() <= len(self.name):
return
else:
cursor.deleteChar()
super().keyPressEvent(e)
e.accept()
class Terminal(QWidget):
errorSignal = pyqtSignal(str)
outputSignal = pyqtSignal(str)
def __init__(self, parent, movable=False):
super().__init__()
self.setWindowFlags(
Qt.Widget |
Qt.WindowCloseButtonHint |
Qt.WindowStaysOnTopHint |
Qt.FramelessWindowHint
)
self.movable = movable
self.layout = QVBoxLayout()
self.pressed = False
self.process = QProcess()
self.parent = parent
self.name = None
self.process.readyReadStandardError.connect(self.onReadyReadStandardError)
self.process.readyReadStandardOutput.connect(self.onReadyReadStandardOutput)
self.setLayout(self.layout)
self.setStyleSheet("QWidget {background-color:invisible;}")
# self.showMaximized() # comment this if you want to embed this widget
def ispressed(self):
return self.pressed
def center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def add(self):
self.added()
self.button = QPushButton("Hide terminal")
self.button.setFont(QFont("Iosevka", 11))
self.button.setStyleSheet("""
height: 20;
background-color: #212121;
""")
self.button.setFixedWidth(120)
self.editor = PlainTextEdit(self, self.movable)
self.highlighter = name_highlighter(self.editor.document(), str(getpass.getuser()), str(socket.gethostname()),
str(os.getcwd()))
self.layout.addWidget(self.button)
self.layout.addWidget(self.editor)
self.editor.commandSignal.connect(self.handle)
self.button.clicked.connect(self.remove)
self.editor.commandZPressed.connect(self.handle)
def added(self):
self.pressed = True
def remove(self):
self.editor.deleteLater()
self.button.deleteLater()
self.parent.hideConsole()
self.pressed = False
def onReadyReadStandardError(self):
self.error = self.process.readAllStandardError().data().decode()
self.editor.appendPlainText(self.error.strip('\n'))
self.errorSignal.emit(self.error)
def onReadyReadStandardOutput(self):
self.result = self.process.readAllStandardOutput().data().decode()
self.editor.appendPlainText(self.result.strip('\n'))
self.state = self.process.state()
self.outputSignal.emit(self.result)
def run(self, command):
"""Executes a system command."""
if self.process.state() != 2:
self.process.start(command)
def handle(self, command):
"""Split a command into list so command echo hi would appear as ['echo', 'hi']"""
real_command = command.replace(self.editor.name, "")
if command == "True":
if self.process.state() == 2:
self.process.kill()
self.editor.appendPlainText("Program execution killed, press enter")
if real_command.startswith("python"):
pass
if real_command != "":
command_list = real_command.split()
else:
command_list = None
"""Now we start implementing some commands"""
if real_command == "clear":
self.editor.clear()
elif command_list is not None and command_list[0] == "echo":
self.editor.appendPlainText(" ".join(command_list[1:]))
elif real_command == "exit":
self.remove()
elif command_list is not None and command_list[0] == "cd" and len(command_list) > 1:
try:
os.chdir(" ".join(command_list[1:]))
self.editor.name = "[" + str(getpass.getuser()) + "@" + str(socket.gethostname()) + "]" + " ~" + str(
os.getcwd()) + " >$ "
if self.highlighter:
del self.highlighter
self.highlighter = name_highlighter(self.editor.document(), str(getpass.getuser()),
str(socket.gethostname()), str(os.getcwd()))
except FileNotFoundError as E:
self.editor.appendPlainText(str(E))
elif command_list is not None and len(command_list) == 1 and command_list[0] == "cd":
os.chdir(str(Path.home()))
self.editor.name = "[" + str(getpass.getuser()) + "@" + str(socket.gethostname()) + "]" + " ~" + str(
os.getcwd()) + " >$ "
elif self.process.state() == 2:
self.process.write(real_command.encode())
self.process.closeWriteChannel()
elif command == self.editor.name + real_command:
self.run(real_command)
else:
pass
# When the user does a command like ls and then presses enter then it wont read the line where the cursor is on as a command
class name_highlighter(QSyntaxHighlighter):
def __init__(self, parent=None, user_name=None, host_name=None, cwd=None):
super().__init__(parent)
self.highlightingRules = []
self.name = user_name
self.name2 = host_name
self.cwd = cwd
most_used = ["cd", "clear", "history", "ls", "man", "pwd", "what", "type",
"strace", "ltrace", "gdb", "cat", "chmod", "cp", "chown", "find", "grep", "locate", "mkdir",
"rmdir", "rm", "mv", "vim", "nano", "rename",
"touch", "wget", "zip", "tar", "gzip", "apt", "bg", "fg", "df", "free", "ip", "jobs", "kill",
"killall", "mount", "umount", "ps", "sudo", "echo",
"top", "uname", "whereis", "uptime", "whereis", "whoami", "exit"
] # most used linux commands, so we will highlight them!
self.regex = {
"class": "\\bclass\\b",
"function": "[A-Za-z0-9_]+(?=\\()",
"magic": "\\__[^']*\\__",
"decorator": "@[^\n]*",
"singleLineComment": "#[^\n]*",
"quotation": "\"[^\"]*\"",
"quotation2": "'[^\']*\'",
"multiLineComment": "[-+]?[0-9]+",
"int": "[-+]?[0-9]+",
}
"""compgen -c returns all commands that you can run"""
for f in most_used:
nameFormat = QTextCharFormat()
nameFormat.setForeground(QColor("#00ff00"))
nameFormat.setFontItalic(True)
self.highlightingRules.append((QRegExp("\\b" + f + "\\b"), nameFormat))
hostnameFormat = QTextCharFormat()
hostnameFormat.setForeground(QColor("#12c2e9"))
self.highlightingRules.append((QRegExp(self.name), hostnameFormat))
self.highlightingRules.append((QRegExp(self.name2), hostnameFormat))
otherFormat = QTextCharFormat()
otherFormat.setForeground(QColor("#f7797d"))
self.highlightingRules.append((QRegExp("~\/[^\s]*"), otherFormat))
quotation1Format = QTextCharFormat()
quotation1Format.setForeground(QColor("#96c93d"))
self.highlightingRules.append((QRegExp("\"[^\"]*\""), quotation1Format))
quotation2Format = QTextCharFormat()
quotation2Format.setForeground(QColor("#96c93d"))
self.highlightingRules.append((QRegExp("'[^\']*\'"), quotation2Format))
integerFormat = QTextCharFormat()
integerFormat.setForeground(QColor("#cc5333"))
integerFormat.setFontItalic(True)
self.highlightingRules.append((QRegExp("\\b[-+]?[0-9]+\\b"), integerFormat))
def highlightBlock(self, text):
for pattern, format in self.highlightingRules:
expression = QRegExp(pattern)
index = expression.indexIn(text)
while index >= 0:
length = expression.matchedLength()
self.setFormat(index, length, format)
index = expression.indexIn(text, index + length)
class PythonThread(QThread):
def __init__(self):
super().__init__()