You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

646 lines
26 KiB

  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Wed May 29 00:02:24 2019
  5. @author: ivan
  6. """
  7. import sys, fitz, io, subprocess, os
  8. from copy import copy
  9. from PyQt5.QtWidgets import QApplication, QAction, QLabel, QDialogButtonBox, QDialog, QFileDialog, QMessageBox, QPushButton, QLineEdit, QCheckBox, QSpinBox, QDoubleSpinBox, QTableWidgetItem, QTabWidget, QComboBox, QWidget, QScrollArea, QMainWindow, QShortcut
  10. from PyQt5.QtCore import QFile, QObject, Qt, pyqtSlot, QSettings
  11. from PyQt5.QtGui import QPixmap, QImage, QKeySequence
  12. from PyQt5 import uic
  13. from chordsheet.tableView import ChordTableView, BlockTableView , MItemModel, MProxyStyle
  14. from reportlab.lib.units import mm, cm, inch, pica
  15. from reportlab.lib.pagesizes import A4, A5, LETTER, LEGAL
  16. from reportlab.pdfbase import pdfmetrics
  17. from reportlab.pdfbase.ttfonts import TTFont
  18. from chordsheet.document import Document, Style, Chord, Block
  19. from chordsheet.render import savePDF
  20. from chordsheet.parsers import parseFingering, parseName
  21. from _version import version
  22. # set the directory where our files are depending on whether we're running a pyinstaller binary or not
  23. if getattr(sys, 'frozen', False):
  24. scriptDir = sys._MEIPASS
  25. else:
  26. scriptDir = os.path.abspath(os.path.dirname(os.path.abspath(__file__)))
  27. QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True) # enable automatic high DPI scaling on Windows
  28. QApplication.setOrganizationName("Ivan Holmes")
  29. QApplication.setOrganizationDomain("ivanholmes.co.uk")
  30. QApplication.setApplicationName("Chordsheet")
  31. settings = QSettings()
  32. pdfmetrics.registerFont(TTFont('FreeSans', os.path.join(scriptDir, 'fonts', 'FreeSans.ttf')))
  33. if sys.platform == "darwin":
  34. pdfmetrics.registerFont(TTFont('HelveticaNeue', 'HelveticaNeue.ttc', subfontIndex=0))
  35. # dictionaries for combo boxes
  36. pageSizeDict = {'A4':A4, 'A5':A5, 'Letter':LETTER, 'Legal':LEGAL}
  37. unitDict = {'mm':mm, 'cm':cm, 'inch':inch, 'point':1, 'pica':pica} # point is 1 because reportlab's native unit is points.
  38. class DocumentWindow(QMainWindow):
  39. """
  40. Class for the main window of the application.
  41. """
  42. def __init__(self, doc, style, filename=None):
  43. """
  44. Initialisation function for the main window of the application.
  45. Arguments:
  46. doc -- the Document object for the window to use
  47. style -- the Style object for the window to use
  48. """
  49. super().__init__()
  50. self.doc = doc
  51. self.style = style
  52. self.lastDoc = copy(self.doc)
  53. self.currentFilePath = filename
  54. self.UIFileLoader(str(os.path.join(scriptDir, 'ui','mainwindow.ui')))
  55. self.UIInitStyle()
  56. self.updateChordDict()
  57. self.setCentralWidget(self.window.centralWidget)
  58. self.setMenuBar(self.window.menuBar)
  59. self.setWindowTitle("Chordsheet")
  60. if filename:
  61. try:
  62. self.openFile(filename)
  63. except:
  64. UnreadableMessageBox().exec()
  65. def closeEvent(self, event):
  66. """
  67. Reimplement the built in closeEvent to allow asking the user to save.
  68. """
  69. self.saveWarning()
  70. def UIFileLoader(self, ui_file):
  71. """
  72. Loads the .ui file for this window and connects the UI elements to their actions.
  73. """
  74. ui_file = QFile(ui_file)
  75. ui_file.open(QFile.ReadOnly)
  76. self.window = uic.loadUi(ui_file)
  77. ui_file.close()
  78. # link all the UI elements
  79. self.window.actionAbout.triggered.connect(self.menuFileAboutAction)
  80. self.window.actionNew.triggered.connect(self.menuFileNewAction)
  81. self.window.actionOpen.triggered.connect(self.menuFileOpenAction)
  82. self.window.actionSave.triggered.connect(self.menuFileSaveAction)
  83. self.window.actionSave_as.triggered.connect(self.menuFileSaveAsAction)
  84. self.window.actionSave_PDF.triggered.connect(self.menuFileSavePDFAction)
  85. self.window.actionPrint.triggered.connect(self.menuFilePrintAction)
  86. self.window.actionClose.triggered.connect(self.menuFileCloseAction)
  87. self.window.actionUndo.triggered.connect(self.menuEditUndoAction)
  88. self.window.actionRedo.triggered.connect(self.menuEditRedoAction)
  89. self.window.actionCut.triggered.connect(self.menuEditCutAction)
  90. self.window.actionCopy.triggered.connect(self.menuEditCopyAction)
  91. self.window.actionPaste.triggered.connect(self.menuEditPasteAction)
  92. self.window.actionNew.setShortcut(QKeySequence.New)
  93. self.window.actionOpen.setShortcut(QKeySequence.Open)
  94. self.window.actionSave.setShortcut(QKeySequence.Save)
  95. self.window.actionSave_as.setShortcut(QKeySequence.SaveAs)
  96. self.window.actionSave_PDF.setShortcut(QKeySequence("Ctrl+E"))
  97. self.window.actionPrint.setShortcut(QKeySequence.Print)
  98. self.window.actionClose.setShortcut(QKeySequence.Close)
  99. self.window.actionUndo.setShortcut(QKeySequence.Undo)
  100. self.window.actionRedo.setShortcut(QKeySequence.Redo)
  101. self.window.actionCut.setShortcut(QKeySequence.Cut)
  102. self.window.actionCopy.setShortcut(QKeySequence.Copy)
  103. self.window.actionPaste.setShortcut(QKeySequence.Paste)
  104. self.window.pageSizeComboBox.currentIndexChanged.connect(self.pageSizeAction)
  105. self.window.documentUnitsComboBox.currentIndexChanged.connect(self.unitAction)
  106. self.window.includedFontCheckBox.stateChanged.connect(self.includedFontAction)
  107. self.window.generateButton.clicked.connect(self.generateAction)
  108. self.window.guitarVoicingButton.clicked.connect(self.guitarVoicingAction)
  109. self.window.addChordButton.clicked.connect(self.addChordAction)
  110. self.window.removeChordButton.clicked.connect(self.removeChordAction)
  111. self.window.updateChordButton.clicked.connect(self.updateChordAction)
  112. self.window.addBlockButton.clicked.connect(self.addBlockAction)
  113. self.window.removeBlockButton.clicked.connect(self.removeBlockAction)
  114. self.window.updateBlockButton.clicked.connect(self.updateBlockAction)
  115. self.window.chordTableView.clicked.connect(self.chordClickedAction)
  116. self.window.blockTableView.clicked.connect(self.blockClickedAction)
  117. def UIInitDocument(self):
  118. """
  119. Fills the window's fields with the values from its document.
  120. """
  121. self.updateTitleBar()
  122. # set all fields to appropriate values from document
  123. self.window.titleLineEdit.setText(self.doc.title)
  124. self.window.composerLineEdit.setText(self.doc.composer)
  125. self.window.arrangerLineEdit.setText(self.doc.arranger)
  126. self.window.timeSignatureSpinBox.setValue(self.doc.timeSignature)
  127. self.window.chordTableView.populate(self.doc.chordList)
  128. self.window.blockTableView.populate(self.doc.blockList)
  129. self.updateChordDict()
  130. def UIInitStyle(self):
  131. """
  132. Fills the window's fields with the values from its style.
  133. """
  134. self.window.pageSizeComboBox.addItems(list(pageSizeDict.keys()))
  135. self.window.pageSizeComboBox.setCurrentText(list(pageSizeDict.keys())[0])
  136. self.window.documentUnitsComboBox.addItems(list(unitDict.keys()))
  137. self.window.documentUnitsComboBox.setCurrentText(list(unitDict.keys())[0])
  138. self.window.lineSpacingDoubleSpinBox.setValue(self.style.lineSpacing)
  139. self.window.leftMarginLineEdit.setText(str(self.style.leftMargin))
  140. self.window.topMarginLineEdit.setText(str(self.style.topMargin))
  141. self.window.fontComboBox.setDisabled(True)
  142. self.window.includedFontCheckBox.setChecked(True)
  143. def pageSizeAction(self, index):
  144. self.pageSizeSelected = self.window.pageSizeComboBox.itemText(index)
  145. def unitAction(self, index):
  146. self.unitSelected = self.window.documentUnitsComboBox.itemText(index)
  147. def includedFontAction(self):
  148. if self.window.includedFontCheckBox.isChecked():
  149. self.style.useIncludedFont = True
  150. else:
  151. self.style.useIncludedFont = False
  152. def chordClickedAction(self, index):
  153. self.window.chordNameLineEdit.setText(self.window.chordTableView.model.item(index.row(), 0).text())
  154. self.window.guitarVoicingLineEdit.setText(self.window.chordTableView.model.item(index.row(), 1).text())
  155. def blockClickedAction(self, index):
  156. self.window.blockChordComboBox.setCurrentText(self.window.blockTableView.model.item(index.row(), 0).text())
  157. self.window.blockLengthLineEdit.setText(self.window.blockTableView.model.item(index.row(), 1).text())
  158. self.window.blockNotesLineEdit.setText(self.window.blockTableView.model.item(index.row(), 2).text())
  159. def getPath(self, value):
  160. """
  161. Wrapper for Qt settings to return home directory if no setting exists.
  162. """
  163. return str((settings.value(value) if settings.value(value) else os.path.expanduser("~")))
  164. def setPath(self, value, fullpath):
  165. """
  166. Wrapper for Qt settings to set path to open/save from next time from current file location.
  167. """
  168. return settings.setValue(value, os.path.dirname(fullpath))
  169. def menuFileNewAction(self):
  170. self.doc = Document()
  171. self.lastDoc = copy(self.doc)
  172. self.currentFilePath = None
  173. self.UIInitDocument()
  174. self.updatePreview()
  175. def menuFileOpenAction(self):
  176. filePath = QFileDialog.getOpenFileName(self.window.tabWidget, 'Open file', self.getPath("workingPath"), "Chordsheet ML files (*.xml *.cml)")
  177. if filePath[0]:
  178. self.openFile(filePath[0])
  179. def openFile(self, filePath):
  180. self.currentFilePath = filePath
  181. self.doc.loadXML(self.currentFilePath)
  182. self.lastDoc = copy(self.doc)
  183. self.setPath("workingPath", self.currentFilePath)
  184. self.UIInitDocument()
  185. self.updatePreview()
  186. def menuFileSaveAction(self):
  187. self.updateDocument()
  188. if not (hasattr(self, 'currentFilePath') and self.currentFilePath):
  189. filePath = QFileDialog.getSaveFileName(self.window.tabWidget, 'Save file', self.getPath("workingPath"), "Chordsheet ML files (*.xml *.cml)")
  190. self.currentFilePath = filePath[0]
  191. self.doc.saveXML(self.currentFilePath)
  192. self.lastDoc = copy(self.doc)
  193. self.setPath("workingPath", self.currentFilePath)
  194. def menuFileSaveAsAction(self):
  195. self.updateDocument()
  196. filePath = QFileDialog.getSaveFileName(self.window.tabWidget, 'Save file', self.getPath("workingPath"), "Chordsheet ML files (*.xml *.cml)")
  197. if filePath[0]:
  198. self.currentFilePath = filePath[0]
  199. self.doc.saveXML(self.currentFilePath)
  200. self.lastDoc = copy(self.doc)
  201. self.setPath("workingPath", self.currentFilePath)
  202. self.updateTitleBar() # as we now have a new filename
  203. def menuFileSavePDFAction(self):
  204. self.updateDocument()
  205. self.updatePreview()
  206. filePath = QFileDialog.getSaveFileName(self.window.tabWidget, 'Save file', self.getPath("lastExportPath"), "PDF files (*.pdf)")
  207. if filePath[0]:
  208. savePDF(d, s, filePath[0])
  209. self.setPath("lastExportPath", filePath[0])
  210. def menuFilePrintAction(self):
  211. if sys.platform == "darwin":
  212. pass
  213. # subprocess.call()
  214. else:
  215. pass
  216. @pyqtSlot()
  217. def menuFileCloseAction(self):
  218. self.saveWarning()
  219. def menuFileAboutAction(self):
  220. aDialog = AboutDialog()
  221. def menuEditUndoAction(self):
  222. try:
  223. QApplication.focusWidget().undo()
  224. except:
  225. pass
  226. def menuEditRedoAction(self):
  227. try:
  228. QApplication.focusWidget().redo()
  229. except:
  230. pass
  231. def menuEditCutAction(self):
  232. try:
  233. QApplication.focusWidget().cut()
  234. except:
  235. pass
  236. def menuEditCopyAction(self):
  237. try:
  238. QApplication.focusWidget().copy()
  239. except:
  240. pass
  241. def menuEditPasteAction(self):
  242. try:
  243. QApplication.focusWidget().paste()
  244. except:
  245. pass
  246. def saveWarning(self):
  247. """
  248. Function to check if the document has unsaved data in it and offer to save it.
  249. """
  250. self.updateDocument() # update the document to catch all changes
  251. if (self.lastDoc == self.doc):
  252. self.close()
  253. else:
  254. wantToSave = UnsavedMessageBox().exec()
  255. if wantToSave == QMessageBox.Save:
  256. if not (hasattr(self, 'currentFilePath') and self.currentFilePath):
  257. filePath = QFileDialog.getSaveFileName(self.window.tabWidget, 'Save file', str(os.path.expanduser("~")), "Chordsheet ML files (*.xml *.cml)")
  258. self.currentFilePath = filePath[0]
  259. self.doc.saveXML(self.currentFilePath)
  260. self.close()
  261. elif wantToSave == QMessageBox.Discard:
  262. self.close()
  263. # if cancel or anything else do nothing at all
  264. def guitarVoicingAction(self):
  265. gdialog = GuitarDialog()
  266. voicing = gdialog.getVoicing()
  267. if voicing:
  268. self.window.guitarVoicingLineEdit.setText(voicing)
  269. def clearChordLineEdits(self):
  270. self.window.chordNameLineEdit.clear()
  271. self.window.guitarVoicingLineEdit.clear()
  272. self.window.chordNameLineEdit.repaint() # necessary on Mojave with PyInstaller (or previous contents will be shown)
  273. self.window.guitarVoicingLineEdit.clear()
  274. def updateChordDict(self):
  275. self.chordDict = {'None':None}
  276. self.chordDict.update({c.name:c for c in self.doc.chordList})
  277. self.window.blockChordComboBox.clear()
  278. self.window.blockChordComboBox.addItems(list(self.chordDict.keys()))
  279. def removeChordAction(self):
  280. self.updateChords()
  281. row = self.window.chordTableView.selectionModel().currentIndex().row()
  282. self.doc.chordList.pop(row)
  283. self.window.chordTableView.populate(self.doc.chordList)
  284. self.clearChordLineEdits()
  285. self.updateChordDict()
  286. def addChordAction(self):
  287. success = False
  288. self.updateChords()
  289. cName = parseName(self.window.chordNameLineEdit.text())
  290. if cName:
  291. self.doc.chordList.append(Chord(cName))
  292. if self.window.guitarVoicingLineEdit.text():
  293. try:
  294. self.doc.chordList[-1].voicings['guitar'] = parseFingering(self.window.guitarVoicingLineEdit.text(), 'guitar')
  295. success = True
  296. except:
  297. VoicingWarningMessageBox().exec()
  298. else:
  299. success = True
  300. else:
  301. NameWarningMessageBox().exec()
  302. if success == True:
  303. self.window.chordTableView.populate(self.doc.chordList)
  304. self.clearChordLineEdits()
  305. self.updateChordDict()
  306. def updateChordAction(self):
  307. success = False
  308. if self.window.chordTableView.selectionModel().hasSelection():
  309. self.updateChords()
  310. row = self.window.chordTableView.selectionModel().currentIndex().row()
  311. cName = parseName(self.window.chordNameLineEdit.text())
  312. if cName:
  313. self.doc.chordList[row] = Chord(cName)
  314. if self.window.guitarVoicingLineEdit.text():
  315. try:
  316. self.doc.chordList[-1].voicings['guitar'] = parseFingering(self.window.guitarVoicingLineEdit.text(), 'guitar')
  317. success = True
  318. except:
  319. VoicingWarningMessageBox().exec()
  320. else:
  321. success = True
  322. else:
  323. NameWarningMessageBox().exec()
  324. if success == True:
  325. self.window.chordTableView.populate(self.doc.chordList)
  326. self.clearChordLineEdits()
  327. self.updateChordDict()
  328. def clearBlockLineEdits(self):
  329. self.window.blockLengthLineEdit.clear()
  330. self.window.blockNotesLineEdit.clear()
  331. self.window.blockLengthLineEdit.repaint() # necessary on Mojave with PyInstaller (or previous contents will be shown)
  332. self.window.blockNotesLineEdit.repaint()
  333. def removeBlockAction(self):
  334. self.updateBlocks()
  335. row = self.window.blockTableView.selectionModel().currentIndex().row()
  336. self.doc.blockList.pop(row)
  337. self.window.blockTableView.populate(self.doc.blockList)
  338. def addBlockAction(self):
  339. self.updateBlocks()
  340. try:
  341. bLength = int(self.window.blockLengthLineEdit.text())
  342. except:
  343. bLength = False
  344. if bLength:
  345. self.doc.blockList.append(Block(bLength,
  346. chord = self.chordDict[self.window.blockChordComboBox.currentText()],
  347. notes = (self.window.blockNotesLineEdit.text() if not "" else None)))
  348. self.window.blockTableView.populate(self.doc.blockList)
  349. self.clearBlockLineEdits()
  350. else:
  351. LengthWarningMessageBox().exec()
  352. def updateBlockAction(self):
  353. if self.window.blockTableView.selectionModel().hasSelection():
  354. self.updateBlocks()
  355. try:
  356. bLength = int(self.window.blockLengthLineEdit.text())
  357. except:
  358. bLength = False
  359. row = self.window.blockTableView.selectionModel().currentIndex().row()
  360. if bLength:
  361. self.doc.blockList[row] = (Block(bLength,
  362. chord = self.chordDict[self.window.blockChordComboBox.currentText()],
  363. notes = (self.window.blockNotesLineEdit.text() if not "" else None)))
  364. self.window.blockTableView.populate(self.doc.blockList)
  365. self.clearBlockLineEdits()
  366. else:
  367. LengthWarningMessageBox().exec()
  368. def generateAction(self):
  369. self.updateDocument()
  370. self.updatePreview()
  371. def updatePreview(self):
  372. self.currentPreview = io.BytesIO()
  373. savePDF(self.doc, self.style, self.currentPreview)
  374. pdfView = fitz.Document(stream=self.currentPreview, filetype='pdf')
  375. pix = pdfView[0].getPixmap(matrix = fitz.Matrix(4, 4), alpha = False) # render at 4x resolution and scale
  376. fmt = QImage.Format_RGB888
  377. qtimg = QImage(pix.samples, pix.width, pix.height, pix.stride, fmt)
  378. self.window.imageLabel.setPixmap(QPixmap.fromImage(qtimg).scaled(self.window.scrollArea.width()-30, self.window.scrollArea.height()-30, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation))
  379. # -30 because the scrollarea has a margin of 12 each side (extra for safety)
  380. self.window.imageLabel.repaint() # necessary on Mojave with PyInstaller (or previous contents will be shown)
  381. def updateTitleBar(self):
  382. appName = "Chordsheet"
  383. if self.currentFilePath:
  384. self.setWindowTitle(appName + " – " + os.path.basename(self.currentFilePath))
  385. else:
  386. self.setWindowTitle(appName)
  387. def updateChords(self):
  388. chordTableList = []
  389. for i in range(self.window.chordTableView.model.rowCount()):
  390. chordTableList.append(Chord(parseName(self.window.chordTableView.model.item(i, 0).text()))),
  391. if self.window.chordTableView.model.item(i, 1).text():
  392. chordTableList[-1].voicings['guitar'] = parseFingering(self.window.chordTableView.model.item(i, 1).text(), 'guitar')
  393. self.doc.chordList = chordTableList
  394. def updateBlocks(self):
  395. blockTableList = []
  396. for i in range(self.window.blockTableView.model.rowCount()):
  397. blockLength = int(self.window.blockTableView.model.item(i, 1).text())
  398. blockChord = self.chordDict[(self.window.blockTableView.model.item(i, 0).text() if self.window.blockTableView.model.item(i, 0).text() else "None")]
  399. blockNotes = self.window.blockTableView.model.item(i, 2).text() if self.window.blockTableView.model.item(i, 2).text() else None
  400. blockTableList.append(Block(blockLength, chord=blockChord, notes=blockNotes))
  401. self.doc.blockList = blockTableList
  402. def updateDocument(self):
  403. self.doc.title = self.window.titleLineEdit.text() # Title can be empty string but not None
  404. self.doc.composer = (self.window.composerLineEdit.text() if self.window.composerLineEdit.text() else None)
  405. self.doc.arranger = (self.window.arrangerLineEdit.text() if self.window.arrangerLineEdit.text() else None)
  406. self.doc.timeSignature = int(self.window.timeSignatureSpinBox.value())
  407. self.style.pageSize = pageSizeDict[self.pageSizeSelected]
  408. self.style.unit = unitDict[self.unitSelected]
  409. self.style.leftMargin = int(self.window.leftMarginLineEdit.text())
  410. self.style.topMargin = int(self.window.topMarginLineEdit.text())
  411. self.style.lineSpacing = float(self.window.lineSpacingDoubleSpinBox.value())
  412. self.updateChords()
  413. self.updateBlocks()
  414. self.style.font = ('FreeSans' if self.style.useIncludedFont else 'HelveticaNeue')
  415. # something for the font box here
  416. class GuitarDialog(QDialog):
  417. """
  418. Dialogue to allow the user to enter a guitar chord voicing. Not particularly advanced at present!
  419. May be extended in future.
  420. """
  421. def __init__(self):
  422. super().__init__()
  423. self.UIFileLoader(str(os.path.join(scriptDir, 'ui','guitardialog.ui')))
  424. def UIFileLoader(self, ui_file):
  425. ui_file = QFile(ui_file)
  426. ui_file.open(QFile.ReadOnly)
  427. self.dialog = uic.loadUi(ui_file)
  428. ui_file.close()
  429. def getVoicing(self):
  430. if self.dialog.exec_() == QDialog.Accepted:
  431. result = [self.dialog.ELineEdit.text(),
  432. self.dialog.ALineEdit.text(),
  433. self.dialog.DLineEdit.text(),
  434. self.dialog.GLineEdit.text(),
  435. self.dialog.BLineEdit.text(),
  436. self.dialog.eLineEdit.text()]
  437. resultJoined = ",".join(result)
  438. return resultJoined
  439. else:
  440. return None
  441. class AboutDialog(QDialog):
  442. """
  443. Dialogue showing information about the program.
  444. """
  445. def __init__(self):
  446. super().__init__()
  447. self.UIFileLoader(str(os.path.join(scriptDir, 'ui','aboutdialog.ui')))
  448. icon = QImage(str(os.path.join(scriptDir, 'ui','icon.png')))
  449. self.dialog.iconLabel.setPixmap(QPixmap.fromImage(icon).scaled(self.dialog.iconLabel.width(), self.dialog.iconLabel.height(), Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation))
  450. self.dialog.versionLabel.setText("Version " + version)
  451. self.dialog.exec()
  452. def UIFileLoader(self, ui_file):
  453. ui_file = QFile(ui_file)
  454. ui_file.open(QFile.ReadOnly)
  455. self.dialog = uic.loadUi(ui_file)
  456. ui_file.close()
  457. class UnsavedMessageBox(QMessageBox):
  458. """
  459. Message box to alert the user of unsaved changes and allow them to choose how to act.
  460. """
  461. def __init__(self):
  462. super().__init__()
  463. self.setIcon(QMessageBox.Question)
  464. self.setWindowTitle("Unsaved changes")
  465. self.setText("The document has been modified.")
  466. self.setInformativeText("Do you want to save your changes?")
  467. self.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
  468. self.setDefaultButton(QMessageBox.Save)
  469. class UnreadableMessageBox(QMessageBox):
  470. """
  471. Message box to warn the user that the chosen file cannot be opened.
  472. """
  473. def __init__(self):
  474. super().__init__()
  475. self.setIcon(QMessageBox.Warning)
  476. self.setWindowTitle("File cannot be opened")
  477. self.setText("The file you have selected cannot be opened.")
  478. self.setInformativeText("Please make sure it is in the right format.")
  479. self.setStandardButtons(QMessageBox.Ok)
  480. self.setDefaultButton(QMessageBox.Ok)
  481. class NameWarningMessageBox(QMessageBox):
  482. """
  483. Message box to warn the user that a chord must have a name
  484. """
  485. def __init__(self):
  486. super().__init__()
  487. self.setIcon(QMessageBox.Warning)
  488. self.setWindowTitle("Unnamed chord")
  489. self.setText("Chords must have a name.")
  490. self.setInformativeText("Please give your chord a name and try again.")
  491. self.setStandardButtons(QMessageBox.Ok)
  492. self.setDefaultButton(QMessageBox.Ok)
  493. class VoicingWarningMessageBox(QMessageBox):
  494. """
  495. Message box to warn the user that the voicing entered could not be parsed
  496. """
  497. def __init__(self):
  498. super().__init__()
  499. self.setIcon(QMessageBox.Warning)
  500. self.setWindowTitle("Malformed voicing")
  501. self.setText("The voicing you entered was not understood and has not been applied.")
  502. self.setInformativeText("Please try re-entering it in the correct format.")
  503. self.setStandardButtons(QMessageBox.Ok)
  504. self.setDefaultButton(QMessageBox.Ok)
  505. class LengthWarningMessageBox(QMessageBox):
  506. """
  507. Message box to warn the user that a block must have a length
  508. """
  509. def __init__(self):
  510. super().__init__()
  511. self.setIcon(QMessageBox.Warning)
  512. self.setWindowTitle("Block without valid length")
  513. self.setText("Blocks must have a whole number length.")
  514. self.setInformativeText("Please enter a valid length for your block and try again.")
  515. self.setStandardButtons(QMessageBox.Ok)
  516. self.setDefaultButton(QMessageBox.Ok)
  517. if __name__ == '__main__':
  518. app = QApplication(sys.argv)
  519. d = Document()
  520. s = Style()
  521. w = DocumentWindow(d, s, filename=(sys.argv[1] if len(sys.argv) > 1 else None)) # pass first argument as filename
  522. w.show()
  523. sys.exit(app.exec_())