-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathDraft.pyw
469 lines (367 loc) · 17.3 KB
/
Draft.pyw
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
459
460
461
462
463
464
465
466
467
468
469
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sip
sip.setapi('QString', 2)
import sys, os
from PyQt4 import QtCore, QtGui
iconPath="none"
class Draft(QtGui.QMainWindow):
def __init__(self, fileName=None, parent=None):
super(Draft, self).__init__(parent)
self.setWindowIcon(QtGui.QIcon.fromTheme("applications-office"))
tb = QtGui.QToolBar("File Actions")
self.addToolBar(tb)
self.actionNew = QtGui.QAction(QtGui.QIcon.fromTheme('document-new'), 'New', self)
self.actionNew.setShortcut('Ctrl+N')
self.actionNew.triggered.connect(self.fileNew)
self.actionOpen = QtGui.QAction(QtGui.QIcon.fromTheme('document-open'), 'Open...', self)
self.actionOpen.setShortcut('Ctrl+O')
self.actionOpen.triggered.connect(self.fileOpen)
self.actionSave = QtGui.QAction(QtGui.QIcon.fromTheme('document-save'), 'Save', self, enabled=False)
self.actionSave.setShortcut('Ctrl+S')
self.actionSave.triggered.connect(self.fileSave)
self.actionSaveAs = QtGui.QAction(QtGui.QIcon.fromTheme('document-save-as'), 'Save As...', self)
self.actionSaveAs.triggered.connect(self.fileSaveAs)
self.actionPrintPreview = QtGui.QAction(QtGui.QIcon.fromTheme('fileprint'), 'Preview...', self)
self.actionPrintPreview.setShortcut('Ctrl+P')
self.actionPrintPreview.triggered.connect(self.filePrintPreview)
self.actionSavePdf = QtGui.QAction(QtGui.QIcon.fromTheme('document-export'), 'Export PDF...', self)
self.actionSavePdf.setShortcut('Ctrl+D')
self.actionSavePdf.triggered.connect(self.filePrint)
tb.setMovable(False)
tb.addAction(self.actionNew)
tb.addAction(self.actionOpen)
tb.addAction(self.actionSave)
tb.addAction(self.actionSaveAs)
tb.addAction(self.actionPrintPreview)
tb.addAction(self.actionSavePdf)
self.setupTextActions()
self.textEdit = QtGui.QTextEdit(self)
self.textEdit.currentCharFormatChanged.connect(self.currentCharFormatChanged)
self.textEdit.cursorPositionChanged.connect(self.cursorPositionChanged)
self.setCentralWidget(self.textEdit)
self.textEdit.setFocus()
self.setCurrentFileName()
self.fontChanged(self.textEdit.font())
self.colorChanged(self.textEdit.textColor())
self.alignmentChanged(self.textEdit.alignment())
self.textEdit.document().modificationChanged.connect(self.actionSave.setEnabled)
self.textEdit.document().modificationChanged.connect(self.setWindowModified)
self.setWindowModified(self.textEdit.document().isModified())
self.actionSave.setEnabled(self.textEdit.document().isModified())
if fileName is None:
fileName = os.path.join("example.html")
if not self.load(fileName):
self.fileNew()
def closeEvent(self, e):
if self.maybeSave():
e.accept()
else:
e.ignore()
def setupTextActions(self):
tb = QtGui.QToolBar(self)
tb.setWindowTitle("Format Actions")
self.addToolBar(tb)
tb.setMovable(False)
self.actionTextBold = QtGui.QAction(QtGui.QIcon.fromTheme('format-text-bold'), 'Bold', self, checkable=True)
self.actionTextBold.setShortcut('Ctrl+B')
self.actionTextBold.triggered.connect(self.textBold)
"""self.actionTextBold = QtGui.QAction(
QtGui.QIcon.fromTheme('format-text-bold',
QtGui.QIcon(iconPath + '/textbold.png')),
"&Bold", self, priority=QtGui.QAction.LowPriority,
shortcut=QtCore.Qt.CTRL + QtCore.Qt.Key_B,
triggered=self.textBold, checkable=True)"""
bold = QtGui.QFont()
bold.setBold(True)
self.actionTextBold.setFont(bold)
tb.addAction(self.actionTextBold)
self.actionTextItalic = QtGui.QAction(
QtGui.QIcon.fromTheme('format-text-italic',
QtGui.QIcon(iconPath + '/textitalic.png')),
"&Italic", self, priority=QtGui.QAction.LowPriority,
shortcut=QtCore.Qt.CTRL + QtCore.Qt.Key_I,
triggered=self.textItalic, checkable=True)
italic = QtGui.QFont()
italic.setItalic(True)
self.actionTextItalic.setFont(italic)
tb.addAction(self.actionTextItalic)
self.actionTextUnderline = QtGui.QAction(
QtGui.QIcon.fromTheme('format-text-underline',
QtGui.QIcon(iconPath + '/textunder.png')),
"&Underline", self, priority=QtGui.QAction.LowPriority,
shortcut=QtCore.Qt.CTRL + QtCore.Qt.Key_U,
triggered=self.textUnderline, checkable=True)
underline = QtGui.QFont()
underline.setUnderline(True)
self.actionTextUnderline.setFont(underline)
tb.addAction(self.actionTextUnderline)
grp = QtGui.QActionGroup(self, triggered=self.textAlign)
tbc = QtGui.QToolBar(self)
tbc.setWindowTitle("Menu")
self.addToolBar(tbc)
tbc.setMovable(False)
left_spacer = QtGui.QWidget()
left_spacer.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
self.actionMenu = QtGui.QAction(QtGui.QIcon.fromTheme('document-properties'), 'Menu', self)
self.actionMenu.triggered.connect(self.on_mouse_menu)
tbc.addWidget(left_spacer)
tbc.addAction(self.actionMenu)
# create context menu
self.popMenuMouse = QtGui.QMenu(self)
self.popMenuMouse.addAction(QtGui.QAction('Create Document', self, triggered=self.fileNew))
self.popMenuMouse.addAction(QtGui.QAction('Close Document', self, triggered=self.close))
self.popMenuMouse.addSeparator()
self.popMenuMouse.addAction(QtGui.QAction('Preferences', self))
self.popMenuMouse.addSeparator()
self.popMenuMouse.addAction(QtGui.QAction('About', self, triggered=self.about))
# Make sure the alignLeft is always left of the alignRight.
if QtGui.QApplication.isLeftToRight():
self.actionAlignLeft = QtGui.QAction(
QtGui.QIcon.fromTheme('format-justify-left',
QtGui.QIcon(iconPath + '/textleft.png')),
"&Left", grp)
self.actionAlignCenter = QtGui.QAction(
QtGui.QIcon.fromTheme('format-justify-center',
QtGui.QIcon(iconPath + '/textcenter.png')),
"C&enter", grp)
self.actionAlignRight = QtGui.QAction(
QtGui.QIcon.fromTheme('format-justify-right',
QtGui.QIcon(iconPath + '/textright.png')),
"&Right", grp)
else:
self.actionAlignRight = QtGui.QAction(
QtGui.QIcon.fromTheme('format-justify-right',
QtGui.QIcon(iconPath + '/textright.png')),
"&Right", grp)
self.actionAlignCenter = QtGui.QAction(
QtGui.QIcon.fromTheme('format-justify-center',
QtGui.QIcon(iconPath + '/textcenter.png')),
"C&enter", grp)
self.actionAlignLeft = QtGui.QAction(
QtGui.QIcon.fromTheme('format-justify-left',
QtGui.QIcon(iconPath + '/textleft.png')),
"&Left", grp)
self.actionAlignJustify = QtGui.QAction(
QtGui.QIcon.fromTheme('format-justify-fill',
QtGui.QIcon(iconPath + '/textjustify.png')),
"&Justify", grp)
self.actionAlignLeft.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_L)
self.actionAlignLeft.setCheckable(True)
self.actionAlignLeft.setPriority(QtGui.QAction.LowPriority)
self.actionAlignCenter.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_E)
self.actionAlignCenter.setCheckable(True)
self.actionAlignCenter.setPriority(QtGui.QAction.LowPriority)
self.actionAlignRight.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_R)
self.actionAlignRight.setCheckable(True)
self.actionAlignRight.setPriority(QtGui.QAction.LowPriority)
self.actionAlignJustify.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_J)
self.actionAlignJustify.setCheckable(True)
self.actionAlignJustify.setPriority(QtGui.QAction.LowPriority)
tb.addActions(grp.actions())
pix = QtGui.QPixmap(16, 16)
pix.fill(QtCore.Qt.black)
self.actionTextColor = QtGui.QAction(QtGui.QIcon(pix), "&Color...",
self, triggered=self.textColor)
tb.addAction(self.actionTextColor)
tb = QtGui.QToolBar(self)
tb.setWindowTitle("Fonts and Size")
self.addToolBarBreak(QtCore.Qt.TopToolBarArea)
self.addToolBar(tb)
tb.setMovable(False)
self.comboFont = QtGui.QFontComboBox(tb)
tb.addWidget(self.comboFont)
self.comboFont.activated[str].connect(self.textFamily)
self.comboSize = QtGui.QComboBox(tb)
self.comboSize.setObjectName("comboSize")
tb.addWidget(self.comboSize)
self.comboSize.setEditable(True)
db = QtGui.QFontDatabase()
for size in db.standardSizes():
self.comboSize.addItem("%s" % (size))
self.comboSize.activated[str].connect(self.textSize)
self.comboSize.setCurrentIndex(
self.comboSize.findText(
"%s" % (QtGui.QApplication.font().pointSize())))
def on_mouse_menu(self):
# show context menu
self.pos = QtGui.QCursor.pos()
self.popMenuMouse.exec_(self.pos)
def load(self, f):
if not QtCore.QFile.exists(f):
return False
fh = QtCore.QFile(f)
if not fh.open(QtCore.QFile.ReadOnly):
return False
data = fh.readAll()
codec = QtCore.QTextCodec.codecForHtml(data)
unistr = codec.toUnicode(data)
if QtCore.Qt.mightBeRichText(unistr):
self.textEdit.setHtml(unistr)
else:
self.textEdit.setPlainText(unistr)
self.setCurrentFileName(f)
return True
def maybeSave(self):
if not self.textEdit.document().isModified():
return True
if self.fileName.startswith(':/'):
return True
ret = QtGui.QMessageBox.warning(self, "Draft",
"The document has been modified.\n"
"Do you want to save your changes?",
QtGui.QMessageBox.Save | QtGui.QMessageBox.Discard |
QtGui.QMessageBox.Cancel)
if ret == QtGui.QMessageBox.Save:
return self.fileSave()
if ret == QtGui.QMessageBox.Cancel:
return False
return True
def setCurrentFileName(self, fileName=''):
self.fileName = fileName
self.textEdit.document().setModified(False)
if not fileName:
shownName = 'New document'
else:
shownName = QtCore.QFileInfo(fileName).fileName()
self.setWindowTitle(self.tr("%s[*] - %s" % (shownName, "Draft")))
self.setWindowModified(False)
def fileNew(self):
if self.maybeSave():
self.textEdit.clear()
self.setCurrentFileName()
def fileOpen(self):
fn = QtGui.QFileDialog.getOpenFileName(self, "Open File...", None,
"Supported formats (*htm *.html *.txt);;HTML-Files (*.htm *.html);;All Files (*)")
if fn:
self.load(fn)
def fileSave(self):
if not self.fileName:
return self.fileSaveAs()
writer = QtGui.QTextDocumentWriter(self.fileName)
success = writer.write(self.textEdit.document())
if success:
self.textEdit.document().setModified(False)
return success
def fileSaveAs(self):
fn = QtGui.QFileDialog.getSaveFileName(self, "Save as...", None,
"ODF files (*.odt);;HTML-Files (*.htm *.html);;All Files (*)")
if not fn:
return False
lfn = fn.lower()
if not lfn.endswith(('.odt', '.htm', '.html')):
# The default.
fn += '.odt'
self.setCurrentFileName(fn)
return self.fileSave()
def filePrint(self):
printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution)
dlg = QtGui.QPrintDialog(printer, self)
if self.textEdit.textCursor().hasSelection():
dlg.addEnabledOption(QtGui.QAbstractPrintDialog.PrintSelection)
dlg.setWindowTitle("Print Document")
if dlg.exec_() == QtGui.QDialog.Accepted:
self.textEdit.print_(printer)
del dlg
def filePrintPreview(self):
printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution)
preview = QtGui.QPrintPreviewDialog(printer, self)
preview.paintRequested.connect(self.printPreview)
preview.exec_()
def printPreview(self, printer):
self.textEdit.print_(printer)
def filePrintPdf(self):
fn = QtGui.QFileDialog.getSaveFileName(self, "Export as PDF", None,
"PDF files (*.pdf);;All Files (*)")
if fn:
if QtCore.QFileInfo(fn).suffix():
fn += '.pdf'
printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution)
printer.setOutputFormat(QtGui.QPrinter.PdfFormat)
printer.setOutputFileName(fn)
self.textEdit.document().print_(printer)
def textBold(self):
fmt = QtGui.QTextCharFormat()
fmt.setFontWeight(self.actionTextBold.isChecked() and QtGui.QFont.Bold or QtGui.QFont.Normal)
self.mergeFormatOnWordOrSelection(fmt)
def textUnderline(self):
fmt = QtGui.QTextCharFormat()
fmt.setFontUnderline(self.actionTextUnderline.isChecked())
self.mergeFormatOnWordOrSelection(fmt)
def textItalic(self):
fmt = QtGui.QTextCharFormat()
fmt.setFontItalic(self.actionTextItalic.isChecked())
self.mergeFormatOnWordOrSelection(fmt)
def textFamily(self, family):
fmt = QtGui.QTextCharFormat()
fmt.setFontFamily(family)
self.mergeFormatOnWordOrSelection(fmt)
def textSize(self, pointSize):
pointSize = float(pointSize)
if pointSize > 0:
fmt = QtGui.QTextCharFormat()
fmt.setFontPointSize(pointSize)
self.mergeFormatOnWordOrSelection(fmt)
def textColor(self):
col = QtGui.QColorDialog.getColor(self.textEdit.textColor(), self)
if not col.isValid():
return
fmt = QtGui.QTextCharFormat()
fmt.setForeground(col)
self.mergeFormatOnWordOrSelection(fmt)
self.colorChanged(col)
def textAlign(self, action):
if action == self.actionAlignLeft:
self.textEdit.setAlignment(
QtCore.Qt.AlignLeft | QtCore.Qt.AlignAbsolute)
elif action == self.actionAlignCenter:
self.textEdit.setAlignment(QtCore.Qt.AlignHCenter)
elif action == self.actionAlignRight:
self.textEdit.setAlignment(
QtCore.Qt.AlignRight | QtCore.Qt.AlignAbsolute)
elif action == self.actionAlignJustify:
self.textEdit.setAlignment(QtCore.Qt.AlignJustify)
def currentCharFormatChanged(self, format):
self.fontChanged(format.font())
self.colorChanged(format.foreground().color())
def cursorPositionChanged(self):
self.alignmentChanged(self.textEdit.alignment())
def about(self):
QtGui.QMessageBox.about(self, "About",
"Draft"
"This program is published under the terms of the gpl license, it comes with ABSOLUTELY NO WARRANTY; for details, visit http://www.gnu.org/licenses/gpl.html"
"\n\nBy: Emilio Coppola ")
def mergeFormatOnWordOrSelection(self, format):
cursor = self.textEdit.textCursor()
if not cursor.hasSelection():
cursor.select(QtGui.QTextCursor.WordUnderCursor)
cursor.mergeCharFormat(format)
self.textEdit.mergeCurrentCharFormat(format)
def fontChanged(self, font):
self.comboFont.setCurrentIndex(self.comboFont.findText(QtGui.QFontInfo(font).family()))
self.comboSize.setCurrentIndex(self.comboSize.findText("%s" % font.pointSize()))
self.actionTextBold.setChecked(font.bold())
self.actionTextItalic.setChecked(font.italic())
self.actionTextUnderline.setChecked(font.underline())
def colorChanged(self, color):
pix = QtGui.QPixmap(20, 20)
pix.fill(color)
self.actionTextColor.setIcon(QtGui.QIcon(pix))
def alignmentChanged(self, alignment):
if alignment & QtCore.Qt.AlignLeft:
self.actionAlignLeft.setChecked(True)
elif alignment & QtCore.Qt.AlignHCenter:
self.actionAlignCenter.setChecked(True)
elif alignment & QtCore.Qt.AlignRight:
self.actionAlignRight.setChecked(True)
elif alignment & QtCore.Qt.AlignJustify:
self.actionAlignJustify.setChecked(True)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
mainWindows = []
for fn in sys.argv[1:] or [None]:
textEdit = Draft(fn)
textEdit.resize(700, 450)
textEdit.show()
mainWindows.append(textEdit)
sys.exit(app.exec_())