-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathPcode.py
More file actions
458 lines (385 loc) · 17.9 KB
/
Copy pathPcode.py
File metadata and controls
458 lines (385 loc) · 17.9 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
import Extensions.qscintilla_compat # noqa: F401 — before any Qsci editor import
from PyQt6.QtCore import QSettings, Qt
from PyQt6.QtGui import QAction, QIcon, QKeySequence, QPixmap, QShortcut
from PyQt6.QtWidgets import (
QApplication, QComboBox, QFileDialog, QHBoxLayout, QLabel, QMessageBox,
QSplashScreen, QStackedWidget, QStyledItemDelegate, QToolButton,
QVBoxLayout, QWidget,
)
import sys
import os
import logging
from Extensions.screen_utils import primary_screen_geometry
from Extensions.UseData import UseData
from Extensions.Library.Library import Library
from Extensions.About import About
from Extensions.Settings.SettingsWidget import SettingsWidget
from Extensions.Projects.Projects import Projects
from Extensions.BusyWidget import BusyWidget
from Extensions import StyleSheet
from Extensions.Start import Start
from Extensions.StackSwitcher import StackSwitcher
from Extensions.CommandPalette import CommandPalette
class Pcode(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
app = QApplication.instance()
if app is None:
app = QApplication(sys.argv)
self.app = app
self.setWindowIcon(
QIcon(os.path.join("Resources", "images", "Icon")))
self.setWindowTitle("Pcode - Loading...")
screen = primary_screen_geometry()
self.resize(screen.width() - 200, screen.height() - 200)
size = self.geometry()
self.move(int((screen.width() - size.width()) / 2),
int((screen.height() - size.height()) / 2))
self.lastWindowGeometry = self.geometry()
mainLayout = QVBoxLayout()
mainLayout.setSpacing(0)
mainLayout.setContentsMargins(0, 0, 0, 0)
self.setLayout(mainLayout)
self.useData = UseData()
# Re-point logging from the early startup log (configured in main())
# to the workspace log now that the workspace path is known.
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',
filename=self.useData.appPathDict["logfile"],
level=logging.DEBUG, force=True)
if sys.version_info.major < 3:
logging.error("This application requires Python 3")
sys.exit(1)
self.library = Library(self.useData)
self.busyWidget = BusyWidget(app, self.useData, self)
if self.useData.SETTINGS["UI"] == "Custom":
StyleSheet.apply_theme(app, self.useData.SETTINGS.get("Theme", "Light"))
self.projectWindowStack = QStackedWidget()
self.projectTitleBox = QComboBox()
self.projectTitleBox.setMinimumWidth(180)
self.projectTitleBox.setStyleSheet(StyleSheet.projectTitleBoxStyle)
self.projectTitleBox.setItemDelegate(QStyledItemDelegate())
self.projectTitleBox.currentIndexChanged.connect(self.projectChanged)
self.projectTitleBox.activated.connect(self.projectChanged)
self.settingsWidget = SettingsWidget(self.useData, app,
self.projectWindowStack, self.library.codeViewer, self)
self.settingsWidget.colorScheme.styleEditor(self.library.codeViewer)
startWindow = Start(self.useData, self)
self.addProject(startWindow, "Start",
"Start", os.path.join("Resources", "images", "flag-green"))
self.projects = Projects(self.useData, self.busyWidget,
self.library, self.settingsWidget, app,
self.projectWindowStack, self.projectTitleBox, self)
self.createActions()
hbox = QHBoxLayout()
hbox.setContentsMargins(5, 3, 5, 3)
mainLayout.addLayout(hbox)
self.logoLabel = QLabel()
logoPix = QPixmap(os.path.join("Resources", "images", "Icon"))
if not logoPix.isNull():
self.logoLabel.setPixmap(logoPix.scaled(
22, 22,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation))
hbox.addWidget(self.logoLabel)
self.titleLabel = QLabel("Pcode")
titleFont = self.titleLabel.font()
titleFont.setBold(True)
self.titleLabel.setFont(titleFont)
self.titleLabel.setContentsMargins(4, 0, 8, 0)
hbox.addWidget(self.titleLabel)
hbox.addStretch(1)
self.pagesStack = QStackedWidget()
mainLayout.addWidget(self.pagesStack)
self.projectSwitcher = StackSwitcher(self.pagesStack)
self.projectSwitcher.setStyleSheet(StyleSheet.mainMenuStyle)
hbox.addWidget(self.projectSwitcher)
self.addPage(self.projectWindowStack, "EDITOR", QIcon(
os.path.join("Resources", "images", "hire-me")))
self.addPage(self.library, "LIBRARY", QIcon(
os.path.join("Resources", "images", "library")))
self.projectSwitcher.setDefault()
hbox.addWidget(self.projectTitleBox)
hbox.setSpacing(5)
self.settingsButton = QToolButton()
self.settingsButton.setAutoRaise(True)
self.settingsButton.setDefaultAction(self.settingsAct)
self.settingsButton.setToolTip("Settings")
hbox.addWidget(self.settingsButton)
self.fullScreenButton = QToolButton()
self.fullScreenButton.setAutoRaise(True)
self.fullScreenButton.setDefaultAction(self.showFullScreenAct)
self.fullScreenButton.setToolTip("Toggle fullscreen")
hbox.addWidget(self.fullScreenButton)
self.aboutButton = QToolButton()
self.aboutButton.setAutoRaise(True)
self.aboutButton.setDefaultAction(self.aboutAct)
self.aboutButton.setToolTip("About Pcode")
hbox.addWidget(self.aboutButton)
self.commandPalette = CommandPalette(self)
self.setKeymap()
if self.useData.bootstrap_bool("firstRun", True):
self.showMaximized()
else:
self.restoreUiState()
self.useData.settings["running"] = 'True'
self.useData.settings["firstRun"] = 'False'
self.useData.saveSettings()
def createActions(self):
self.aboutAct = QAction(
QIcon(os.path.join("Resources", "images", "properties")),
"About Pcode", self, statusTip="About Pcode",
triggered=self.showAbout)
self.showFullScreenAct = \
QAction(
QIcon(os.path.join("Resources", "images", "fullscreen")),
"Fullscreen", self,
statusTip="Fullscreen",
triggered=self.showFullScreenMode)
self.settingsAct = QAction(
QIcon(os.path.join("Resources", "images", "config")),
"Settings", self,
statusTip="Settings", triggered=self.showSettings)
def addPage(self, pageWidget, name, iconPath):
self.projectSwitcher.addButton(name=name, icon=iconPath)
self.pagesStack.addWidget(pageWidget)
def loadProject(self, path, show=False, new=False):
self.projects.loadProject(path, show, new)
def newProject(self):
self.projects.newProjectDialog.exec()
def showProject(self, path):
if not os.path.exists(path):
QMessageBox.warning(
self, "Open Project", "Project cannot be be found!")
else:
if path in self.useData.OPENED_PROJECTS:
for i in range(self.projectWindowStack.count() - 1):
window = self.projectWindowStack.widget(i)
p_path = window.projectPathDict["root"]
if os.path.samefile(path, p_path):
self.projectTitleBox.setCurrentIndex(i)
return True
return False
def addProject(self, window, name, type='Project', iconPath=None):
self.projectWindowStack.insertWidget(0, window)
if type == 'Project':
self.projectTitleBox.insertItem(0, QIcon(
os.path.join("Resources", "images", "project")), name, [window, type])
else:
self.projectTitleBox.insertItem(0, QIcon(
iconPath), name, [window, type])
def projectChanged(self, index):
data = self.projectTitleBox.itemData(index)
window = data[0]
windowType = data[1]
if windowType == "Start":
self.setWindowTitle("Pcode - Start")
elif windowType == "Project":
title = window.editorTabWidget.getEditorData("filePath")
self.updateWindowTitle(title)
self.projectWindowStack.setCurrentWidget(window)
def removeProject(self, window):
for index in range(self.projectTitleBox.count() - 1):
data = self.projectTitleBox.itemData(index)
windowWidget = data[0]
if windowWidget == window:
self.projectWindowStack.removeWidget(window)
self.projectTitleBox.removeItem(index)
def updateWindowTitle(self, title):
if title is None:
title = "Pcode - " + "Unsaved"
else:
window = self.projectTitleBox.itemData(
self.projectTitleBox.currentIndex())[0]
if title.startswith(window.projectPathDict["sourcedir"]):
src_dir = window.projectPathDict["sourcedir"]
n = title.partition(src_dir)[-1]
title = 'Pcode - ' + n
else:
title = "Pcode - " + title
self.setWindowTitle(title)
def showAbout(self):
aboutPane = About(self)
aboutPane.exec()
def showSettings(self):
self.settingsWidget.show()
def showFullScreenMode(self):
if self.isFullScreen():
self.showNormal()
self.setGeometry(self.lastWindowGeometry)
else:
# get current size ahd show Fullscreen
# so we can later restore to proper position
self.lastWindowGeometry = self.geometry()
self.showFullScreen()
def saveUiState(self):
settings = QSettings("Clean Code Inc.", "Pcode")
settings.beginGroup("MainWindow")
settings.setValue("geometry", self.geometry())
settings.setValue("lsplitter", self.library.mainSplitter.saveState())
settings.setValue("snippetsMainsplitter",
self.settingsWidget.snippetEditor.mainSplitter.saveState())
settings.setValue("windowMaximized", self.isMaximized())
settings.endGroup()
def restoreUiState(self):
settings = QSettings("Clean Code Inc.", "Pcode")
settings.beginGroup("MainWindow")
if settings.value("windowMaximized", True, type=bool):
self.showMaximized()
else:
self.setGeometry(settings.value("geometry"))
self.show()
self.library.mainSplitter.restoreState(settings.value("lsplitter"))
self.settingsWidget.snippetEditor.mainSplitter.restoreState(
settings.value("snippetsMainsplitter"))
settings.endGroup()
def closeEvent(self, event):
for i in range(self.projectWindowStack.count() - 1):
window = self.projectWindowStack.widget(i)
closed = window.closeWindow()
if not closed:
self.projectTitleBox.setCurrentIndex(i)
event.ignore()
return
else:
pass
self.saveUiState()
self.useData.saveUseData()
self.app.closeAllWindows()
event.accept()
def setKeymap(self):
shortcuts = self.useData.CUSTOM_SHORTCUTS
self.shortFullscreen = QShortcut(
shortcuts["Ide"]["Fullscreen"], self)
self.shortFullscreen.activated.connect(self.showFullScreenMode)
self.shortCommandPalette = QShortcut(
QKeySequence("Ctrl+Shift+P"), self)
self.shortCommandPalette.activated.connect(self.showCommandPalette)
def showCommandPalette(self):
self.commandPalette.setCommands(self.buildCommands())
self.commandPalette.launch()
def _activeProjectWindow(self):
window = self.projectWindowStack.currentWidget()
if window is not None and hasattr(window, "editorTabWidget"):
return window
return None
def buildCommands(self):
commands = [
("New Project", self.newProject),
("Open Project\u2026", self.openProjectDialog),
("Settings", self.showSettings),
("Toggle Fullscreen", self.showFullScreenMode),
("Go to Editor", lambda: self.projectSwitcher.setButton("EDITOR")),
("Go to Library", lambda: self.projectSwitcher.setButton("LIBRARY")),
("Theme: Light", lambda: self.applyTheme("Light")),
("Theme: Dark", lambda: self.applyTheme("Dark")),
("Theme: System", lambda: self.applyTheme("System")),
("About Pcode", self.showAbout),
]
window = self._activeProjectWindow()
if window is not None:
etw = window.editorTabWidget
sw = window.bottomStackSwitcher
commands.extend([
("Save All", window.saveAll),
("Save File", etw.save),
("Run Project", window.runProject),
("Run File", window.runFile),
("Find", window.showFinderWidget),
("Replace", window.showReplaceWidget),
("Find in Files", window.showFindInFilesWidget),
("Go to Line", lambda: window.gotoLineAct.trigger()),
("Configure Project", lambda: window.configureAct.trigger()),
("Panel: Output",
lambda: sw.setCurrentWidget(window.runWidget)),
("Panel: Alerts",
lambda: sw.setCurrentWidget(window.assistantWidget)),
("Panel: Messages",
lambda: sw.setCurrentWidget(window.messagesWidget)),
("Panel: Bookmarks",
lambda: sw.setCurrentWidget(window.bookmarkWidget)),
("Panel: Tasks",
lambda: sw.setCurrentWidget(window.tasksWidget)),
("Git: Refresh", lambda: window.gitPanel.refresh()),
("Git: Stage File", lambda: window.gitPanel.stage_selected()),
("Git: Commit", lambda: window.gitPanel.commit()),
("Git: Diff at Cursor", lambda: window.gitPanel.diff_at_cursor()),
])
keymap_dispatch = {
"Find": window.showFinderWidget,
"Replace": window.showReplaceWidget,
"Go-to-Line": lambda: window.gotoLineAct.trigger(),
"Save-File": etw.save,
"Save-All": window.saveAll,
"Run-Project": window.runProject,
"Run-File": window.runFile,
}
for name, shortcut in self.useData.CUSTOM_SHORTCUTS.get("Ide", {}).items():
handler = keymap_dispatch.get(name)
if shortcut and handler is not None:
label = "Keymap: {0} ({1})".format(
name.replace("-", " "), shortcut)
commands.append((label, handler))
editor_dispatch = {
"Comment": etw.comment,
"Uncomment": etw.unComment,
}
for name, value in self.useData.CUSTOM_SHORTCUTS.get(
"Editor", {}).items():
shortcut = value[0] if isinstance(value, (list, tuple)) else value
handler = editor_dispatch.get(name)
if shortcut and handler is not None:
label = "Keymap (Editor): {0} ({1})".format(
name.replace("-", " "), shortcut)
commands.append((label, handler))
for i in range(self.projectWindowStack.count() - 1):
proj_window = self.projectWindowStack.widget(i)
if not hasattr(proj_window, "projectPathDict"):
continue
root = proj_window.projectPathDict["root"]
pname = proj_window.projectPathDict.get(
"name", os.path.basename(root))
commands.append(
("Switch Project: {0}".format(pname),
lambda idx=i: self.projectTitleBox.setCurrentIndex(idx)))
for path in self.useData.OPENED_PROJECTS[:5]:
name = os.path.basename(path)
commands.append(
("Recent: {0}".format(name),
lambda p=path: self.loadProject(p, True)))
return commands
def applyTheme(self, name):
self.useData.SETTINGS["Theme"] = name
if self.useData.SETTINGS["UI"] == "Custom":
StyleSheet.apply_theme(self.app, name)
def openProjectDialog(self):
directory = QFileDialog.getExistingDirectory(
self, "Project Folder", self.useData.getLastOpenedDir(),
QFileDialog.Option.ShowDirsOnly
| QFileDialog.Option.DontResolveSymlinks)
if directory:
directory = os.path.normpath(directory)
self.useData.saveLastOpenedDir(directory)
self.loadProject(directory, True)
def main():
# Resources are resolved relative to the working directory, so anchor it to
# this file's location regardless of where the entry point is launched from.
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# Configure logging before anything else so errors during early startup
# (before the workspace log path is known) are still captured. Pcode
# re-points this to the workspace LOG.txt once UseData has loaded.
import tempfile
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(message)s',
filename=os.path.join(tempfile.gettempdir(), "pcode-startup.log"),
level=logging.DEBUG)
app = QApplication(sys.argv)
from Extensions import ErrorHandler
ErrorHandler.install()
splash = QSplashScreen(
QPixmap(os.path.join("Resources", "images", "splash")))
splash.show()
window = Pcode()
splash.finish(window)
return app.exec()
if __name__ == '__main__':
sys.exit(main())