-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
277 lines (229 loc) · 9.05 KB
/
main.py
File metadata and controls
277 lines (229 loc) · 9.05 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
import sys
import os
import time
import datetime as dt
import threading
import traceback
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtWidgets import QLabel, QTextEdit, QShortcut
from PyQt5.QtWidgets import QWidget, QDesktopWidget
from PyQt5.QtWidgets import QStatusBar, QToolBar
from PyQt5.QtWidgets import QFileDialog, QFontDialog
from PyQt5.QtWidgets import QMessageBox, QInputDialog
from PyQt5.QtGui import QColor, QKeySequence
from PyQt5 import QtCore, QtGui
import json
class Window(QMainWindow):
def __init__(self, w, h, parent=None, fn=None):
# Inheritance
super().__init__(parent)
# Basic parameters
self.name = ''
# Style parameters
self.font_size = conf['default-font-size']
self.font = 'font-size: ' + str(conf['default-font-size'])
self.background_color = 'background-color: ' + conf['background-color']
self.font_color = 'color: ' + conf['font-color']
self.font_family = ''
self.style = ''
self._autosaveText = 'Enable autosave'
self._autosave = False
self.encoding = 'utf-8'
# Main widgets
self._editBox = QTextEdit()
self.about_window = About(w*0.5, h*0.5)
self._fileDialog = QFileDialog()
self._encodingDialog = encodingDialog(self)
self.closing_with_text = QMessageBox(QMessageBox.Warning,
'Unsaved text. Still close?',
'There is text not saved in the editor.\n' +
'Do you still want to close the editor?')
self.closing_with_text.setStandardButtons(
QMessageBox.Ok | QMessageBox.Cancel)
# Setting edit box main properties
self.setCentralWidget(self._editBox)
self.resize(int(w), int(h))
self.setFocusPolicy(QtCore.Qt.StrongFocus)
self._editBox.setFocusPolicy(QtCore.Qt.StrongFocus)
self._editBox.setAcceptRichText(False) # Erase format when pasting
# Timer for the autosave
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.save)
# Shortcuts (https://zetcode.com/pyqt/qshortcut/)
self.ctrlsave = QShortcut(QKeySequence('Ctrl+S'), self)
self.ctrlsave.activated.connect(self.save)
self.quitSc = QShortcut(QKeySequence('Ctrl+Q'), self)
self.quitSc.activated.connect(QApplication.instance().quit)
# Initial functions
if fn != None:
self.openGiven(fn)
self.updateStyle()
self.setWindowTitle('Dark Theme Text Editor')
self._createMenu()
self._createToolBar()
self._createStatusBar()
def _createMenu(self):
self.menu = self.menuBar().addMenu("&Menu")
self.menu.addAction('&Open file', self.openFile)
self.menu.addAction('&Save copy as', self.save_as)
self.menu.addAction('&Change encoding', self.changeEncoding)
self.menu.addAction('&About', self.about)
self.menu.addAction('&Exit', self.close)
self.options = self.menuBar().addMenu("&Options")
self.options.addAction('&Font', self.fontMenu)
def _createToolBar(self):
tools = QToolBar()
self.addToolBar(tools)
tools.addAction('Save', self.save)
tools.addAction('Exit', self.close)
self.saveAction = tools.addAction(self._autosaveText, self.autosave)
def _createStatusBar(self):
self.status = QStatusBar()
self.status.showMessage(
'New file {:>}'.format('Encoding: ' + self.encoding))
self.setStatusBar(self.status)
def about(self):
self.about_window.show()
def updateStatusBar(self, text):
self.status.showMessage(text)
self.setStatusBar(self.status)
# SAVE METHODS
def saveFile(self):
file = open(self.name, 'wb')
text = (self._editBox.toPlainText()).encode(self.encoding)
file.write(text)
file.close()
def save(self, bypass=False):
if self.name != '':
self.save_update()
else:
self.name = self._fileDialog.getSaveFileName(self)[0]
if self.name != '':
self.save_update()
else:
self.updateStatusBar('Unsaved file')
def save_update(self):
self.saveFile()
self.updateStatusBar(
"{:50}{:^9}Last saved: {}".format(self.name, '|', dt.datetime.today()))
def save_as(self):
self.save(bypass=True)
def autosave(self):
if self._autosave:
self._autosaveText = 'Enable autosave'
self._autosave = True
self.timer.stop()
else:
self._autosaveText = 'Disable autosave'
self._autosave = False
self.timer.start(1000)
self.saveAction.setText(self._autosaveText)
# STYLE METHODS
def changeFontSize(self, size):
self.font = 'font-size:{}px'.format(int(size))
self.updateStyle()
def fontMenu(self):
font, valid = QFontDialog.getFont()
if valid:
self.font_family = 'font-family:"{}";'.format(font)
self.updateStyle()
def updateStyle(self):
self.style = ''
self.style += self.font + ';'
self.style += self.background_color + ';'
self.style += self.font_color + ';'
self.style += self.font_family + ';'
self.setStyleSheet(self.style)
# OTHER METHODS
def openGiven(self, given):
self.name = given
with open(self.name, 'rb') as fn:
self._editBox.setText(fn.read().decode(self.encoding))
def openFile(self):
try:
self.openGiven(QFileDialog.getOpenFileName(self, 'Open file')[0])
except:
QMessageBox.information(self,
'Wrong encoding',
('In case you see a weird behaivour' +
'with the text displayed.\n' +
'Please check what is the' +
'encoding of you file and set it on ' +
'the application correspondinly.'))
with open(self.name, 'r') as fn:
self._editBox.setText(fn.read())
self.save()
def changeEncoding(self):
retval = self._encodingDialog.getItem()
self.encoding = retval
self.updateStatusBar("{} | {:>}".format(
self.status.currentMessage(), 'Encoding: ' + self.encoding))
print(retval)
def wheelEvent(self, event):
self.font_size += event.angleDelta().y()/280
self.changeFontSize(self.font_size)
# Handling close event
def closeEvent(self, event):
print("User has clicked the red x on the main window")
if self._editBox.toPlainText() == '':
retval = self.closing_with_text.exec_()
if retval == QMessageBox.Ok:
print('Ok pressed')
event.accept()
else:
print('Cancel pressed')
event.ignore()
class About(QMainWindow):
def __init__(self, w, h, parent=None):
super().__init__(parent)
self.setWindowTitle('About page')
with open(about_file, "r") as f:
self.about_text = f.read()
f.close()
self.setCentralWidget(QLabel(self.about_text))
self.setStyleSheet(style)
self.resize(int(w), int(h))
class encodingDialog(QWidget):
def __init__(self, parent=None):
super(encodingDialog, self).__init__(parent)
def getItem(self):
items = ('utf-8', 'utf-16', 'utf-32', 'ascii', 'ansi', 'cp775')
item, ok = QInputDialog.getItem(self, "Select encoding",
"List of encodings", items, 0, False)
if ok and item:
return item
def app_path(fn):
return '\\'.join(cd[:-1]) + '\\' + fn
if __name__ == "__main__":
cd = sys.argv[0].split('\\')
with open(app_path('conf.json'), 'r') as conf_file:
conf = json.load(conf_file)
whiteColor = QColor(255, 255, 255)
blackColor = QColor(0, 0, 0)
about_file = app_path(conf['about_file'])
style_file = app_path(conf['style_file'])
style = ''.join(open(style_file, 'r').read().split('\n'))
try:
# If the os is Windows there is need to do some
# trick for the icon to appear in the taskbar.
if os.name == 'nt':
import ctypes
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
"myappid")
app = QApplication(sys.argv)
app.setWindowIcon(QtGui.QIcon('blackicon.svg'))
screen = app.primaryScreen()
size = screen.size()
rect = screen.availableGeometry()
# Proportion of the windows size the application takes on launch
p = 0.7
try:
fn = sys.argv[1]
except:
fn = None
win = Window(int(rect.width()*p), int(rect.height()*p), fn=fn)
win.show()
sys.exit(app.exec_())
except:
traceback.print_exc()
time.sleep(5)