forked from BeAglES-ftWare/editor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbeagleeditor.py
415 lines (360 loc) · 18.6 KB
/
beagleeditor.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
# Form implementation generated from reading ui file 'main.ui'
#
# Created by: PyQt6 UI code generator 6.7.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic6 is
# run again. Do not edit this file unless you know what you are doing.
import platform
import subprocess
from PyQt6 import QtCore, QtGui, QtWidgets
from markdown import markdown
import sys
import os
import importlib
from syntax import *
from autocomplete import *
import subprocess
import requests
from bs4 import BeautifulSoup
from splash import show_splash_screen
from PyQt6 import QtWidgets, QtCore
class CustomPlainTextEdit(QtWidgets.QPlainTextEdit):
def __init__(self, completer, parent=None, filename=None):
super().__init__(parent)
self.completer = completer
self.indentation = " " * 4
self.filename = filename
def keyPressEvent(self, event):
cursor = self.textCursor()
current_line = cursor.block().text()
current_position = cursor.positionInBlock()
if event.key() in (QtCore.Qt.Key.Key_Return, QtCore.Qt.Key.Key_Enter):
cursor.insertText("\n")
indent_level = self.calculate_indent_level(current_line)
cursor.insertText(self.indentation * indent_level)
return
if event.key() == QtCore.Qt.Key.Key_Backspace:
if current_line[:current_position].endswith(self.indentation):
for _ in range(len(self.indentation)):
cursor.deletePreviousChar()
return
if event.key() == QtCore.Qt.Key.Key_Tab:
cursor.insertText(self.indentation)
return
if self.completer.popup().isVisible():
if event.key() in (QtCore.Qt.Key.Key_Enter, QtCore.Qt.Key.Key_Return, QtCore.Qt.Key.Key_Escape, QtCore.Qt.Key.Key_Tab, QtCore.Qt.Key.Key_Backtab):
event.ignore()
return
super().keyPressEvent(event)
self.handle_autocomplete(event)
def handle_autocomplete(self, event):
isShortcut = (event.modifiers() & QtCore.Qt.KeyboardModifier.ControlModifier) and event.key() == QtCore.Qt.Key.Key_Space
if not self.completer or not isShortcut:
return
completionPrefix = self.textUnderCursor()
if completionPrefix != self.completer.completionPrefix():
self.completer.setCompletionPrefix(completionPrefix)
self.completer.popup().setCurrentIndex(self.completer.completionModel().index(0, 0))
cr = self.cursorRect()
cr.setWidth(self.completer.popup().sizeHintForColumn(0) + self.completer.popup().verticalScrollBar().sizeHint().width())
self.completer.complete(cr)
def textUnderCursor(self):
cursor = self.textCursor()
cursor.select(QtGui.QTextCursor.SelectionType.WordUnderCursor)
return cursor.selectedText()
def calculate_indent_level(self, current_line):
cursor = self.textCursor()
block_number = cursor.blockNumber()
indent_level = 0
for i in range(block_number):
block = self.document().findBlockByNumber(i)
line = block.text().strip()
if line.endswith(":") or line.endswith("{"):
indent_level += 1
elif line == "" or not line.endswith((":", "{")):
indent_level = max(indent_level - 1, 0)
return indent_level
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1264, 630)
self.centralwidget = QtWidgets.QWidget(parent=MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayoutWidget = QtWidgets.QWidget(parent=self.centralwidget)
self.gridLayoutWidget.setGeometry(QtCore.QRect(10, 10, 1251, 581))
self.gridLayoutWidget.setObjectName("gridLayoutWidget")
self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.plainTextEdit = CustomPlainTextEdit(None, parent=self.gridLayoutWidget)
self.plainTextEdit.setObjectName("plainTextEdit")
self.plainTextEdit.setFont(QtGui.QFont("Cascadia Code", 11))
self.gridLayout.addWidget(self.plainTextEdit, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(parent=MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1264, 18))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(parent=self.menubar)
self.menuFile.setObjectName("menuFile")
self.menuActions = QtWidgets.QMenu(parent=self.menubar)
self.menuActions.setObjectName("menuActions")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(parent=MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionSave = QtGui.QAction(parent=MainWindow)
self.actionSave.setObjectName("actionSave")
self.actionOpen = QtGui.QAction(parent=MainWindow)
self.actionOpen.setObjectName("actionOpen")
self.actionNew = QtGui.QAction(parent=MainWindow)
self.actionNew.setObjectName("actionOpen")
self.menuFile.addAction(self.actionSave)
self.menuFile.addAction(self.actionOpen)
self.menuFile.addAction(self.actionNew)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addAction(self.menuActions.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.actionSave.triggered.connect(self.save_file)
self.actionOpen.triggered.connect(self.open_file)
self.actionNew.triggered.connect(self.new_file)
self.filename_to_editor = {}
# Add Autocompletion
self.completer = QtWidgets.QCompleter()
self.completer.setWidget(self.plainTextEdit)
self.model = QtGui.QStandardItemModel(self.completer)
self.completer.setModel(self.model)
self.completer.setCompletionMode(QtWidgets.QCompleter.CompletionMode.PopupCompletion)
self.completer.setCaseSensitivity(QtCore.Qt.CaseSensitivity.CaseInsensitive)
self.completer.activated.connect(self.insert_completion)
self.plainTextEdit.completer = self.completer
self.plainTextEdit.textChanged.connect(self.update_completions)
self.filename = None
self.version = "2024.4.0.1"
self.current_highlighter = None
self.is_file_opened = False
self.is_pyfile_opened = False
self.is_cfile_opened = False
self.is_cppfile_opened = False
self.is_csfile_opened = False
self.dark_mode = False
self.plugin = None
self.startup()
def startup(self):
self.load_plugins()
self.check_for_updates()
def check_for_updates(self):
try:
response = requests.get("https://beaglesoftware.github.io/beagleeditor")
soup = BeautifulSoup(response.content, 'html.parser')
div = soup.find("div", class_="Version")
if div:
vers = div.find('p')
if vers:
ver = vers.text.replace("Current Version: ", "")
if ver != self.version and ver > self.version:
QtWidgets.QMessageBox.warning(None, "Update", f"New version avaliable\nLocal app version: {self.version}\nLatest version: {ver}")
except Exception as e:
QtWidgets.QMessageBox.critical(None, "Error", f"An error occurred when checking for update: Error: {e}")
def load_plugins(self):
plugin_dir = "plugins"
plugin_modules = [] # List to store loaded plugin modules
if os.path.exists(plugin_dir):
self.menuPlugins = QtWidgets.QMenu(parent=self.menubar)
self.menuPlugins.setObjectName("menuPlugins")
self.menuPlugins.setTitle("Plugins")
for filename in os.listdir(plugin_dir):
if filename.endswith(".py"):
module_name = filename[:-3] # Remove ".py" extension
try:
plugin_module = importlib.import_module(f"{plugin_dir}.{module_name}")
plugin_modules.append(plugin_module) # Add the loaded module to the list
except ImportError:
print(f"Error importing plugin: {module_name}")
# Add actions to the plugins menu
for module in plugin_modules:
# Use module filename as action name
action_name = module.__name__.split('.')[-1]
action = QtGui.QAction(action_name, MainWindow)
action.triggered.connect(lambda checked, m=module: self.run_plugin(m))
self.menuPlugins.addAction(action)
self.menubar.addAction(self.menuPlugins.menuAction())
def run_plugin(self, module):
# Call a specific function from the plugin module, e.g., `run`
if hasattr(module, 'run_from_beagleeditor'):
module.run_from_beagleeditor()
else:
QtWidgets.QMessageBox.critical(None, "Error", f"Module {module.__name__} does not have a run_from_beagleeditor() function", QtWidgets.QMessageBox.StandardButton.Ok)
def save_file(self):
if self.is_file_opened:
with open(self.filename, 'w') as f:
f.write(self.plainTextEdit.toPlainText())
else:
self.filename, _ = QtWidgets.QFileDialog.getSaveFileName(None, "Save File", "", "All Files (*)")
if self.filename:
with open(self.filename, 'w') as f:
f.write(self.plainTextEdit.toPlainText())
self.is_file_opened = True
self.update_completions()
self.apply_highlighter()
self.add_run_action()
if self.filename.endswith('.md'):
self.mdpreTextEdit = QtWidgets.QTextEdit(parent=self.gridLayoutWidget)
self.mdpreTextEdit.setObjectName("mdpreTextEdit")
self.gridLayout.addWidget(self.mdpreTextEdit, 1, 0, 1, 1)
self.plainTextEdit.textChanged.connect(self.markdown_preview)
else:
try:
self.mdpreTextEdit.clear()
self.mdpreTextEdit.setVisible(False)
except Exception:
pass
def open_file(self):
filename, _ = QtWidgets.QFileDialog.getOpenFileName(None, "Open File", "", "All Files (*)")
if filename:
with open(filename, 'r') as f:
file_content = f.read()
self.plainTextEdit.setPlainText(file_content)
self.is_file_opened = True
self.filename = filename
self.update_completions()
self.apply_highlighter()
self.add_run_action()
if self.filename.endswith('.md'):
self.mdpreTextEdit = QtWidgets.QTextEdit(parent=self.gridLayoutWidget)
self.mdpreTextEdit.setObjectName("mdpreTextEdit")
self.gridLayout.addWidget(self.mdpreTextEdit, 1, 0, 1, 1)
self.plainTextEdit.textChanged.connect(self.markdown_preview)
else:
try:
self.mdpreTextEdit.clear()
self.mdpreTextEdit.setVisible(False)
except Exception:
pass
def markdown_preview(self):
markdown_content = self.plainTextEdit.toPlainText()
html_content = markdown(markdown_content)
self.mdpreTextEdit.setHtml(html_content)
def add_run_action(self):
if self.is_file_opened and not self.is_pyfile_opened and self.filename.endswith('.py'):
self.actionRunPythonFile = QtGui.QAction("Run Python File", parent=MainWindow)
self.actionRunPythonFile.setObjectName("actionRunPythonFile")
self.menuActions.addAction(self.actionRunPythonFile)
self.actionRunPythonFile.triggered.connect(self.start_python_file)
self.is_pyfile_opened = True
elif self.is_file_opened and not self.is_cfile_opened and self.filename.endswith('.c'):
self.actionOneClickCompile = QtGui.QAction("One-Click Compile", parent=MainWindow)
self.actionOneClickCompile.setObjectName("actionOneClickCompile")
self.menuActions.addAction(self.actionOneClickCompile)
self.actionOneClickCompile.triggered.connect(self.compile_c_file)
self.is_cfile_opened = True
elif self.is_file_opened and not self.is_cppfile_opened and self.filename.endswith('.c'):
self.actionOneClickCompile = QtGui.QAction("One-Click Compile", parent=MainWindow)
self.actionOneClickCompile.setObjectName("actionOneClickCompile")
self.menuActions.addAction(self.actionOneClickCompile)
self.actionOneClickCompile.triggered.connect(self.compile_c_file)
self.is_cppfile_opened = True
elif self.is_file_opened and not self.is_csfile_opened and self.filename.endswith('.c'):
self.actionOneClickCompile = QtGui.QAction("One-Click Compile", parent=MainWindow)
self.actionOneClickCompile.setObjectName("actionOneClickCompile")
self.menuActions.addAction(self.actionOneClickCompile)
self.actionOneClickCompile.triggered.connect(self.compile_c_file)
self.is_csfile_opened = True
def start_python_file(self):
if self.filename:
subprocess.run([sys.executable, self.filename])
def compile_c_file(self):
if self.filename:
if platform.system() == "Windows":
subprocess.run(["cmd.exe", "/c", "compile_c_cpp.bat", self.filename, os.path.dirname(self.filename) + '//'])
elif platform.system() == "darwin" or platform.system() == "Linux":
subprocess.run(["./compile_c.sh", self.filename])
def compile_cpp_file(self):
if self.filename:
if platform.system() == "Windows":
subprocess.run(["cmd.exe", "/c", "compile_c_cpp.bat", self.filename])
elif platform.system() == "darwin" or platform.system() == "Linux":
subprocess.run(["./compile_cpp.sh", self.filename])
def compile_cs_file(self):
if self.filename:
if platform.system() == "Windows":
subprocess.run(["cmd.exe", "/c", "compile_cs.bat", self.filename])
elif platform.system() == "darwin" or platform.system() == "Linux":
QtWidgets.QMessageBox.critical(None, "Error", "Can't compile C# file on Mac or Linux. Windows needed")
def new_file(self):
if self.filename:
self.filename = None
self.is_file_opened = False
self.plainTextEdit.clear()
def apply_highlighter(self):
if self.current_highlighter:
self.current_highlighter.setDocument(None)
if self.filename.endswith('.py'):
self.current_highlighter = PythonHighlighter(self.plainTextEdit.document())
elif self.filename.endswith('.html'):
self.current_highlighter = HTMLHighlighter(self.plainTextEdit.document())
elif self.filename.endswith('.cpp') or self.filename.endswith('.h'):
self.current_highlighter = CppHighlighter(self.plainTextEdit.document())
elif self.filename.endswith('.css'):
self.current_highlighter = CSSHighlighter(self.plainTextEdit.document())
elif self.filename.endswith('.cs'):
self.current_highlighter = CSharpHighlighter(self.plainTextEdit.document())
elif self.filename.endswith('.c'):
self.current_highlighter = CHighlighter(self.plainTextEdit.document())
elif self.filename.endswith('.js'):
self.current_highlighter = JavaScriptHighlighter(self.plainTextEdit.document())
elif self.filename.endswith('.md'):
self.current_highlighter = MarkdownHighlighter(self.plainTextEdit.document())
def update_completions(self):
cursor = self.plainTextEdit.textCursor()
cursor.select(QtGui.QTextCursor.SelectionType.WordUnderCursor)
word_fragment = cursor.selectedText()
if not word_fragment:
return
if self.filename and self.filename.endswith('.py'):
suggestions = PythonSuggestions.get_suggestions
elif self.filename and self.filename.endswith('.html'):
suggestions = HTMLSuggestions.get_suggestions
elif self.filename and (self.filename.endswith('.cpp') or self.filename.endswith('.h')):
suggestions = CppSuggestions.get_suggestions
elif self.filename and self.filename.endswith('.css'):
suggestions = CSSSuggestions.get_suggestions
elif self.filename and self.filename.endswith('.cs'):
suggestions = CSharpSuggestions.get_suggestions
elif self.filename and self.filename.endswith('.c'):
suggestions = CSuggestions.get_suggestions
elif self.filename and self.filename.endswith('.js'):
suggestions = JavaScriptSuggestions.get_suggestions
else:
suggestions = lambda word_fragment: []
suggestions_list = suggestions(word_fragment)
self.model = QtGui.QStandardItemModel(self.completer)
for suggestion in suggestions_list:
item = QtGui.QStandardItem(suggestion)
self.model.appendRow(item)
self.completer.setModel(self.model)
self.completer.setCompletionPrefix(word_fragment)
cursor_rect = self.plainTextEdit.cursorRect()
cursor_rect.setWidth(self.completer.popup().sizeHintForColumn(0) +
self.completer.popup().verticalScrollBar().sizeHint().width())
self.completer.complete(cursor_rect)
def insert_completion(self, completion):
cursor = self.plainTextEdit.textCursor()
cursor.select(QtGui.QTextCursor.SelectionType.WordUnderCursor)
cursor.insertText(completion)
self.plainTextEdit.setTextCursor(cursor)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "BeagleEditor"))
self.menuActions.setTitle(_translate("MainWindow", "Actions"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.actionSave.setText(_translate("MainWindow", "Save"))
self.actionOpen.setText(_translate("MainWindow", "Open"))
self.actionNew.setText(_translate("MainWindow", "New"))
if __name__ == "__main__":
app, splash = show_splash_screen()
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
QtCore.QTimer.singleShot(1500, lambda: MainWindow.show())
sys.exit(app.exec())