-
Notifications
You must be signed in to change notification settings - Fork 0
/
QTerminal.py
241 lines (194 loc) · 8.4 KB
/
QTerminal.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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import os
import getpass
import socket
from pathlib import Path
from PyQt5.QtWidgets import QWidget, QApplication, QPlainTextEdit, QMainWindow
from PyQt5.QtGui import QFont, QTextCursor
from PyQt5.QtCore import Qt, pyqtSignal, QProcess, QCoreApplication, QSettings, QEvent, QPoint, QSize
class MainWindow(QMainWindow):
def __init__(self, parent=None, movable=False):
super(MainWindow, self).__init__()
self.setAcceptDrops(True)
self.shellWin = PlainTextEdit()
self.setCentralWidget(self.shellWin)
self.setGeometry(0, 0, 600, 600)
self.setWindowTitle("QTerminal")
self.settings = QSettings("QTerminal", "QTerminal")
self.readSettings()
def closeEvent(self, e):
self.writeSettings()
def readSettings(self):
if self.settings.contains("commands"):
self.shellWin.commands = self.settings.value("commands")
if self.settings.contains("pos"):
pos = self.settings.value("pos", QPoint(200, 200))
self.move(pos)
if self.settings.contains("size"):
size = self.settings.value("size", QSize(400, 400))
self.resize(size)
def writeSettings(self):
self.settings.setValue("commands", self.shellWin.commands)
self.settings.setValue("pos", self.pos())
self.settings.setValue("size", self.size())
class PlainTextEdit(QPlainTextEdit):
commandSignal = pyqtSignal(str)
commandZPressed = pyqtSignal(str)
def __init__(self, parent=None, movable=False):
super(PlainTextEdit, self).__init__()
self.installEventFilter(self)
self.setAcceptDrops(True)
QApplication.setCursorFlashTime(1000)
self.process = QProcess()
self.process.readyReadStandardError.connect(self.onReadyReadStandardError)
self.process.readyReadStandardOutput.connect(self.onReadyReadStandardOutput)
self.name = (str(getpass.getuser()) + "@" + str(socket.gethostname())
+ ":" + str(os.getcwd()) + "$ ")
self.appendPlainText(self.name)
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: #f3f3f3; padding: 8;}")
self.verticalScrollBar().setStyleSheet("background-color: #212121;")
self.text = None
self.setFont(QFont("Noto Sans Mono", 8))
self.previousCommandLength = 0
def eventFilter(self, source, event):
if (event.type() == QEvent.DragEnter):
event.accept()
print ('DragEnter')
return True
elif (event.type() == QEvent.Drop):
print ('Drop')
self.setDropEvent(event)
return True
else:
return False ### super(QPlainTextEdit).eventFilter(event)
def setDropEvent(self, event):
if event.mimeData().hasUrls():
f = str(event.mimeData().urls()[0].toLocalFile())
self.insertPlainText(f)
event.accept()
elif event.mimeData().hasText():
ft = event.mimeData().text()
print("text:", ft)
self.insertPlainText(ft)
event.accept()
else:
event.ignore()
def keyPressEvent(self, e):
cursor = self.textCursor()
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.modifiers() == Qt.ControlModifier and e.key() == Qt.Key_C:
self.process.kill()
self.name = (str(getpass.getuser()) + "@" + str(socket.gethostname())
+ ":" + str(os.getcwd()) + "$ ")
self.appendPlainText("process cancelled")
self.appendPlainText(self.name)
self.textCursor().movePosition(QTextCursor.End)
return
if e.key() == Qt.Key_Return: ### 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, ""))
# print(self.commands)
self.handle(text)
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() == Qt.Key_Backspace: ### 16777219:
if cursor.positionInBlock() <= len(self.name):
return
else:
cursor.deleteChar()
super().keyPressEvent(e)
cursor = self.textCursor()
e.accept()
def ispressed(self):
return self.pressed
def onReadyReadStandardError(self):
self.error = self.process.readAllStandardError().data().decode()
self.appendPlainText(self.error.strip('\n'))
def onReadyReadStandardOutput(self):
self.result = self.process.readAllStandardOutput().data().decode()
self.appendPlainText(self.result.strip('\n'))
self.state = self.process.state()
# print(self.result)
def run(self, command):
"""Executes a system command."""
if self.process.state() != 2:
self.process.start(command)
self.process.waitForFinished()
self.textCursor().movePosition(QTextCursor.End)
def handle(self, command):
# print("begin handle")
"""Split a command into list so command echo hi would appear as ['echo', 'hi']"""
real_command = command.replace(self.name, "")
if command == "True":
if self.process.state() == 2:
self.process.kill()
self.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.clear()
elif command_list is not None and command_list[0] == "echo":
self.appendPlainText(" ".join(command_list[1:]))
elif real_command == "exit":
quit()
elif command_list is not None and command_list[0] == "cd" and len(command_list) > 1:
try:
os.chdir(" ".join(command_list[1:]))
self.name = (str(getpass.getuser()) + "@" + str(socket.gethostname())
+ ":" + str(os.getcwd()) + "$ ")
self.textCursor().movePosition(QTextCursor.End)
except FileNotFoundError as E:
self.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.name = (str(getpass.getuser()) + "@" + str(socket.gethostname())
+ ":" + str(os.getcwd()) + "$ ")
self.textCursor().movePosition(QTextCursor.End)
elif self.process.state() == 2:
self.process.write(real_command.encode())
self.process.closeWriteChannel()
elif command == self.name + real_command:
self.run(real_command)
else:
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())