-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
220 lines (174 loc) · 7.75 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
import sys
import os
import threading
import pygame
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QFileDialog
from PyQt5.QtWidgets import QAction, QTreeWidget, QPushButton, QTreeWidgetItem, QMessageBox, QLabel
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QIcon, QDesktopServices
from PyQt5 import uic # Import the uic module
from codeEditor import PythonCodeEditor
import subprocess
class PygameApp(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
self.pygame_thread = None
self.screen = None
def initUI(self):
uic.loadUi('ui/editor.ui', self)
self.setWindowTitle("PyCon Young Learners Workshop")
self.setWindowIcon(QIcon("./ui/img/python.png"))
self.codePanelLayout:QVBoxLayout
self.runButton:QPushButton
self.terminalButton:QPushButton
self.fileDirTreeWidget:QTreeWidget
self.zoomInButton:QPushButton
self.zoomOutButton:QPushButton
self.fileNameLabel:QLabel
self.actionOpen:QAction
self.actionSave:QAction
self.actionFAQ:QAction
self.actionAbout:QAction
self.codeEditorWidget:QWidget = PythonCodeEditor()
self.codePanelLayout.addWidget(self.codeEditorWidget)
self.terminalButton.setIcon(QIcon("./ui/img/terminal.png"))
self.runButton.setIcon(QIcon("./ui/img/game.png"))
self.runButton.clicked.connect(self.runPygameCode)
self.terminalButton.clicked.connect(self.runTerminalCommand)
self.fileDirTreeWidget.itemDoubleClicked.connect(self.openTutorialFile)
self.zoomInButton.clicked.connect(self.textZoomIn)
self.zoomOutButton.clicked.connect(self.textZoomOut)
## Actions
self.actionOpen.triggered.connect(self.open_file)
self.actionSave.triggered.connect(self.save_file)
self.actionFAQ.triggered.connect(self.open_faq)
self.actionAbout.triggered.connect(self.open_about)
self.actionOpen.setShortcut("Ctrl+O")
self.actionSave.setShortcut("Ctrl+S")
self.populateTree("Tutorials", self.fileDirTreeWidget)
self.fileDirTreeWidget.sortItems(0, 0)
self.show()
def textZoomIn(self):
self.codeEditorWidget.textZoomIn()
def textZoomOut(self):
self.codeEditorWidget.textZoomOut()
def runPygameCode(self):
# Clear the Pygame screen if it's already open
if self.screen:
pygame.quit()
pygameCode = self.codeEditorWidget.text()
# Define a function to run Pygame in a separate thread
def pygame_thread_function():
# Initialize Pygame
# pygame.init()
# Create a Pygame screen (adjust dimensions as needed)
# self.screen = pygame.display.set_mode((800, 600))
running = True
# Execute the Python code (make sure to handle Pygame events)
try:
exec(pygameCode)
except Exception as e:
print(f"Error: {e}")
error_dialog = QMessageBox()
error_dialog.setIcon(QMessageBox.Critical)
error_dialog.setWindowTitle("Error")
error_dialog.setText(f"Error: {e}")
error_dialog.exec_()
# Main loop to keep the Pygame window open
# while running:
# for event in pygame.event.get():
# if event.type == pygame.QUIT:
# running = False
try:
# end_dialog = QMessageBox()
# end_dialog.setIcon(QMessageBox.Information)
# end_dialog.setWindowTitle("Information")
# end_dialog.setText(f"Code Execution Completed !!")
# end_dialog.exec_()
# pygame.display.quit()
...
except Exception as e:
print(e)
# Start the Pygame thread
self.pygame_thread = threading.Thread(target=pygame_thread_function, daemon=True)
self.pygame_thread.start()
def runTerminalCommand(self):
initText = f"import os\nimport sys\nsys.path.insert(0,'{os.path.abspath(__file__).rsplit('/', 1)[0]}/Tutorials/6_Game')\n"
# initText = f"import os\nos.environ['PATH'] += ':'+'{os.path.abspath(__file__).rsplit('/', 1)[0]}/Tutorials/6_Game'\n"
with open("temp.py", "w") as file:
file.write(initText)
file.write(self.codeEditorWidget.text())
command = f"python temp.py"
subprocess.Popen(["gnome-terminal", "--", "bash", "-c", f"{command}; read -p 'Press Enter to exit...'"])
print("Done Terminal Code")
def populateTree(self, path, parent):
for item in os.listdir(path):
itemPath = os.path.join(path, item)
itemIsDir = os.path.isdir(itemPath)
if itemIsDir and type(parent) == QTreeWidget:
parentItem = QTreeWidgetItem(parent, [item])
parent.addTopLevelItem(parentItem)
sys.path.append(itemPath)
self.populateTree(itemPath, parentItem)
else:
QTreeWidgetItem(parent, [item])
def openTutorialFile(self, item, column):
path = []
while item is not None:
path.insert(0, item.text(0))
item = item.parent()
# Join the path elements and print it
full_path = os.path.join("./Tutorials", *path) # Join with "/" as the separator
# print("Double-clicked:", full_path)
if full_path.endswith(".py"):
with open(full_path, 'r') as file:
# Read the entire file content into a string
file_content = file.read()
self.codeEditorWidget.setPlainText(file_content)
self.fileNameLabel.setText(f"{path[-2]}/{path[-1]}")
def open_file(self):
options = QFileDialog.Options()
options |= QFileDialog.ReadOnly
options |= QFileDialog.ExistingFiles
file_dialog = QFileDialog()
file_dialog.setNameFilter("Python Files (*.py)")
file_dialog.setViewMode(QFileDialog.List)
file_dialog.setOptions(options)
if file_dialog.exec_():
selected_files = file_dialog.selectedFiles()
for file_path in selected_files:
with open(file_path, 'r') as file:
file_contents = file.read()
# Now you can work with the file_contents
self.codeEditorWidget.setPlainText(file_contents)
self.fileNameLabel.setText(file_path)
return
def save_file(self):
options = QFileDialog.Options()
options |= QFileDialog.ReadOnly
options |= QFileDialog.ExistingFiles
file_dialog = QFileDialog()
file_dialog.setNameFilter("Python Files (*.py)")
file_dialog.setOptions(options)
default_file_name = "TestCode.py" # Default file name
file_path, _ = file_dialog.getSaveFileName(self, "Save File", default_file_name, "Python Files (*.py)")
if file_path:
with open(file_path, 'w') as file:
file.write(self.codeEditorWidget.text())
self.fileNameLabel.setText(file_path)
def open_faq(self):
url = QUrl("https://www.harshmittal.co.in/PyCon2023-YLW")
QDesktopServices.openUrl(url)
def open_about(self):
url = QUrl("https://github.com/harshmittal2210/PyCon2023-YLW/wiki")
QDesktopServices.openUrl(url)
def main():
try:
app = QApplication(sys.argv)
ex = PygameApp()
sys.exit(app.exec_())
except KeyboardInterrupt:
exit(0)
if __name__ == "__main__":
main()