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.

682 lines
28 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. 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. # set the controls to the values from the selected chord
  154. self.window.chordNameLineEdit.setText(self.window.chordTableView.model.item(index.row(), 0).text())
  155. self.window.guitarVoicingLineEdit.setText(self.window.chordTableView.model.item(index.row(), 1).text())
  156. def blockClickedAction(self, index):
  157. # set the controls to the values from the selected block
  158. bChord = self.window.blockTableView.model.item(index.row(), 0).text()
  159. self.window.blockChordComboBox.setCurrentText(bChord if bChord else "None")
  160. self.window.blockLengthLineEdit.setText(self.window.blockTableView.model.item(index.row(), 1).text())
  161. self.window.blockNotesLineEdit.setText(self.window.blockTableView.model.item(index.row(), 2).text())
  162. def getPath(self, value):
  163. """
  164. Wrapper for Qt settings to return home directory if no setting exists.
  165. """
  166. return str((settings.value(value) if settings.value(value) else os.path.expanduser("~")))
  167. def setPath(self, value, fullpath):
  168. """
  169. Wrapper for Qt settings to set path to open/save from next time from current file location.
  170. """
  171. return settings.setValue(value, os.path.dirname(fullpath))
  172. def menuFileNewAction(self):
  173. self.doc = Document() # new document object
  174. self.lastDoc = copy(self.doc) # copy this object as reference to check against on quitting
  175. self.currentFilePath = None # reset file path (this document hasn't been saved yet)
  176. self.UIInitDocument()
  177. self.updatePreview()
  178. def menuFileOpenAction(self):
  179. filePath = QFileDialog.getOpenFileName(self.window.tabWidget, 'Open file', self.getPath("workingPath"), "Chordsheet ML files (*.xml *.cml)")[0]
  180. if filePath:
  181. self.openFile(filePath)
  182. def openFile(self, filePath):
  183. """
  184. Opens a file from a file path and sets up the window accordingly.
  185. """
  186. self.currentFilePath = filePath
  187. self.doc.loadXML(self.currentFilePath)
  188. self.lastDoc = copy(self.doc)
  189. self.setPath("workingPath", self.currentFilePath)
  190. self.UIInitDocument()
  191. self.updatePreview()
  192. def menuFileSaveAction(self):
  193. self.updateDocument()
  194. if not self.currentFilePath:
  195. filePath = QFileDialog.getSaveFileName(self.window.tabWidget, 'Save file', self.getPath("workingPath"), "Chordsheet ML files (*.xml *.cml)")[0]
  196. else:
  197. filePath = self.currentFilePath
  198. self.saveFile(filePath)
  199. def menuFileSaveAsAction(self):
  200. self.updateDocument()
  201. filePath = QFileDialog.getSaveFileName(self.window.tabWidget, 'Save file', self.getPath("workingPath"), "Chordsheet ML files (*.xml *.cml)")[0]
  202. if filePath:
  203. self.saveFile(filePath)
  204. def saveFile(self, filePath):
  205. """
  206. Saves a file to given file path and sets up environment.
  207. """
  208. self.currentFilePath = filePath
  209. self.doc.saveXML(self.currentFilePath)
  210. self.lastDoc = copy(self.doc)
  211. self.setPath("workingPath", self.currentFilePath)
  212. self.updateTitleBar() # as we may have a new filename
  213. def menuFileSavePDFAction(self):
  214. self.updateDocument()
  215. self.updatePreview()
  216. filePath = QFileDialog.getSaveFileName(self.window.tabWidget, 'Save file', self.getPath("lastExportPath"), "PDF files (*.pdf)")[0]
  217. if filePath:
  218. savePDF(d, s, filePath)
  219. self.setPath("lastExportPath", filePath)
  220. def menuFilePrintAction(self):
  221. if sys.platform == "darwin":
  222. pass
  223. # subprocess.call()
  224. else:
  225. pass
  226. @pyqtSlot()
  227. def menuFileCloseAction(self):
  228. self.saveWarning()
  229. def menuFileAboutAction(self):
  230. aDialog = AboutDialog()
  231. def menuEditUndoAction(self):
  232. try:
  233. QApplication.focusWidget().undo() # see if the built in widget supports it
  234. except:
  235. pass # if not just fail silently
  236. def menuEditRedoAction(self):
  237. try:
  238. QApplication.focusWidget().redo()
  239. except:
  240. pass
  241. def menuEditCutAction(self):
  242. try:
  243. QApplication.focusWidget().cut()
  244. except:
  245. pass
  246. def menuEditCopyAction(self):
  247. try:
  248. QApplication.focusWidget().copy()
  249. except:
  250. pass
  251. def menuEditPasteAction(self):
  252. try:
  253. QApplication.focusWidget().paste()
  254. except:
  255. pass
  256. def saveWarning(self):
  257. """
  258. Function to check if the document has unsaved data in it and offer to save it.
  259. """
  260. self.updateDocument() # update the document to catch all changes
  261. if (self.lastDoc == self.doc):
  262. self.close()
  263. else:
  264. wantToSave = UnsavedMessageBox().exec()
  265. if wantToSave == QMessageBox.Save:
  266. if not (self.currentFilePath):
  267. filePath = QFileDialog.getSaveFileName(self.window.tabWidget, 'Save file', str(os.path.expanduser("~")), "Chordsheet ML files (*.xml *.cml)")
  268. self.currentFilePath = filePath[0]
  269. self.doc.saveXML(self.currentFilePath)
  270. self.close()
  271. elif wantToSave == QMessageBox.Discard:
  272. self.close()
  273. # if cancel or anything else do nothing at all
  274. def guitarVoicingAction(self):
  275. gdialog = GuitarDialog()
  276. voicing = gdialog.getVoicing()
  277. if voicing:
  278. self.window.guitarVoicingLineEdit.setText(voicing)
  279. def clearChordLineEdits(self):
  280. self.window.chordNameLineEdit.clear()
  281. self.window.guitarVoicingLineEdit.clear()
  282. self.window.chordNameLineEdit.repaint() # necessary on Mojave with PyInstaller (or previous contents will be shown)
  283. self.window.guitarVoicingLineEdit.repaint()
  284. def updateChordDict(self):
  285. """
  286. Updates the dictionary used to generate the Chord menu (on the block tab)
  287. """
  288. self.chordDict = {'None':None}
  289. self.chordDict.update({c.name:c for c in self.doc.chordList})
  290. self.window.blockChordComboBox.clear()
  291. self.window.blockChordComboBox.addItems(list(self.chordDict.keys()))
  292. def removeChordAction(self):
  293. if self.window.chordTableView.selectionModel().hasSelection(): # check for selection
  294. self.updateChords()
  295. row = self.window.chordTableView.selectionModel().currentIndex().row()
  296. self.doc.chordList.pop(row)
  297. self.window.chordTableView.populate(self.doc.chordList)
  298. self.clearChordLineEdits()
  299. self.updateChordDict()
  300. def addChordAction(self):
  301. success = False # initialise
  302. self.updateChords()
  303. cName = parseName(self.window.chordNameLineEdit.text())
  304. if cName:
  305. self.doc.chordList.append(Chord(cName))
  306. if self.window.guitarVoicingLineEdit.text():
  307. try:
  308. self.doc.chordList[-1].voicings['guitar'] = parseFingering(self.window.guitarVoicingLineEdit.text(), 'guitar')
  309. success = True # chord successfully parsed
  310. except:
  311. VoicingWarningMessageBox().exec() # Voicing is malformed, warn user
  312. else:
  313. success = True # chord successfully parsed
  314. else:
  315. NameWarningMessageBox().exec() # Chord has no name, warn user
  316. if success == True: # if chord was parsed properly
  317. self.window.chordTableView.populate(self.doc.chordList)
  318. self.clearChordLineEdits()
  319. self.updateChordDict()
  320. def updateChordAction(self):
  321. success = False # see comments above
  322. if self.window.chordTableView.selectionModel().hasSelection(): # check for selection
  323. self.updateChords()
  324. row = self.window.chordTableView.selectionModel().currentIndex().row()
  325. cName = parseName(self.window.chordNameLineEdit.text())
  326. if cName:
  327. self.doc.chordList[row] = Chord(cName)
  328. if self.window.guitarVoicingLineEdit.text():
  329. try:
  330. self.doc.chordList[row].voicings['guitar'] = parseFingering(self.window.guitarVoicingLineEdit.text(), 'guitar')
  331. success = True
  332. except:
  333. VoicingWarningMessageBox().exec()
  334. else:
  335. success = True
  336. else:
  337. NameWarningMessageBox().exec()
  338. if success == True:
  339. self.window.chordTableView.populate(self.doc.chordList)
  340. self.clearChordLineEdits()
  341. self.updateChordDict()
  342. def clearBlockLineEdits(self):
  343. self.window.blockLengthLineEdit.clear()
  344. self.window.blockNotesLineEdit.clear()
  345. self.window.blockLengthLineEdit.repaint() # necessary on Mojave with PyInstaller (or previous contents will be shown)
  346. self.window.blockNotesLineEdit.repaint()
  347. def removeBlockAction(self):
  348. if self.window.blockTableView.selectionModel().hasSelection(): # check for selection
  349. self.updateBlocks()
  350. row = self.window.blockTableView.selectionModel().currentIndex().row()
  351. self.doc.blockList.pop(row)
  352. self.window.blockTableView.populate(self.doc.blockList)
  353. def addBlockAction(self):
  354. self.updateBlocks()
  355. try:
  356. bLength = int(self.window.blockLengthLineEdit.text()) # can the value entered for block length be cast as an integer
  357. except:
  358. bLength = False
  359. if bLength: # create the block
  360. self.doc.blockList.append(Block(bLength,
  361. chord = self.chordDict[self.window.blockChordComboBox.currentText()],
  362. notes = (self.window.blockNotesLineEdit.text() if not "" else None)))
  363. self.window.blockTableView.populate(self.doc.blockList)
  364. self.clearBlockLineEdits()
  365. else:
  366. LengthWarningMessageBox().exec() # show warning that length was not entered or in wrong format
  367. def updateBlockAction(self):
  368. if self.window.blockTableView.selectionModel().hasSelection(): # check for selection
  369. self.updateBlocks()
  370. try:
  371. bLength = int(self.window.blockLengthLineEdit.text())
  372. except:
  373. bLength = False
  374. row = self.window.blockTableView.selectionModel().currentIndex().row()
  375. if bLength:
  376. self.doc.blockList[row] = (Block(bLength,
  377. chord = self.chordDict[self.window.blockChordComboBox.currentText()],
  378. notes = (self.window.blockNotesLineEdit.text() if not "" else None)))
  379. self.window.blockTableView.populate(self.doc.blockList)
  380. self.clearBlockLineEdits()
  381. else:
  382. LengthWarningMessageBox().exec()
  383. def generateAction(self):
  384. self.updateDocument()
  385. self.updatePreview()
  386. def updatePreview(self):
  387. """
  388. Update the preview shown by rendering a new PDF and drawing it to the scroll area.
  389. """
  390. try:
  391. self.currentPreview = io.BytesIO()
  392. savePDF(self.doc, self.style, self.currentPreview)
  393. pdfView = fitz.Document(stream=self.currentPreview, filetype='pdf')
  394. pix = pdfView[0].getPixmap(matrix = fitz.Matrix(4, 4), alpha = False) # render at 4x resolution and scale
  395. fmt = QImage.Format_RGB888
  396. qtimg = QImage(pix.samples, pix.width, pix.height, pix.stride, fmt)
  397. self.window.imageLabel.setPixmap(QPixmap.fromImage(qtimg).scaled(self.window.scrollArea.width()-30, self.window.scrollArea.height()-30, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation))
  398. # -30 because the scrollarea has a margin of 12 each side (extra for safety)
  399. self.window.imageLabel.repaint() # necessary on Mojave with PyInstaller (or previous contents will be shown)
  400. except:
  401. warning = QMessageBox.warning(self, "Preview failed", "Could not update the preview.", buttons=QMessageBox.Ok, defaultButton=QMessageBox.Ok)
  402. def updateTitleBar(self):
  403. """
  404. Update the application's title bar to reflect the current document.
  405. """
  406. if self.currentFilePath:
  407. self.setWindowTitle(_version.appName + " – " + os.path.basename(self.currentFilePath))
  408. else:
  409. self.setWindowTitle(_version.appName)
  410. def updateChords(self):
  411. """
  412. Update the chord list by reading the table.
  413. """
  414. chordTableList = []
  415. for i in range(self.window.chordTableView.model.rowCount()):
  416. chordTableList.append(Chord(parseName(self.window.chordTableView.model.item(i, 0).text()))),
  417. if self.window.chordTableView.model.item(i, 1).text():
  418. chordTableList[-1].voicings['guitar'] = parseFingering(self.window.chordTableView.model.item(i, 1).text(), 'guitar')
  419. self.doc.chordList = chordTableList
  420. def updateBlocks(self):
  421. """
  422. Update the block list by reading the table.
  423. """
  424. blockTableList = []
  425. for i in range(self.window.blockTableView.model.rowCount()):
  426. blockLength = int(self.window.blockTableView.model.item(i, 1).text())
  427. blockChord = self.chordDict[(self.window.blockTableView.model.item(i, 0).text() if self.window.blockTableView.model.item(i, 0).text() else "None")]
  428. blockNotes = self.window.blockTableView.model.item(i, 2).text() if self.window.blockTableView.model.item(i, 2).text() else None
  429. blockTableList.append(Block(blockLength, chord=blockChord, notes=blockNotes))
  430. self.doc.blockList = blockTableList
  431. def updateDocument(self):
  432. """
  433. Update the Document object by reading values from the UI.
  434. """
  435. self.doc.title = self.window.titleLineEdit.text() # Title can be empty string but not None
  436. self.doc.composer = (self.window.composerLineEdit.text() if self.window.composerLineEdit.text() else None)
  437. self.doc.arranger = (self.window.arrangerLineEdit.text() if self.window.arrangerLineEdit.text() else None)
  438. self.doc.timeSignature = int(self.window.timeSignatureSpinBox.value())
  439. self.style.pageSize = pageSizeDict[self.pageSizeSelected]
  440. self.style.unit = unitDict[self.unitSelected]
  441. self.style.leftMargin = int(self.window.leftMarginLineEdit.text())
  442. self.style.topMargin = int(self.window.topMarginLineEdit.text())
  443. self.style.lineSpacing = float(self.window.lineSpacingDoubleSpinBox.value())
  444. self.updateChords()
  445. self.updateBlocks()
  446. self.style.font = ('FreeSans' if self.style.useIncludedFont else 'HelveticaNeue')
  447. # something for the font box here
  448. class GuitarDialog(QDialog):
  449. """
  450. Dialogue to allow the user to enter a guitar chord voicing. Not particularly advanced at present!
  451. May be extended in future.
  452. """
  453. def __init__(self):
  454. super().__init__()
  455. self.UIFileLoader(str(os.path.join(scriptDir, 'ui','guitardialog.ui')))
  456. def UIFileLoader(self, ui_file):
  457. ui_file = QFile(ui_file)
  458. ui_file.open(QFile.ReadOnly)
  459. self.dialog = uic.loadUi(ui_file)
  460. ui_file.close()
  461. def getVoicing(self):
  462. """
  463. Show the dialogue and return the voicing that has been entered.
  464. """
  465. if self.dialog.exec_() == QDialog.Accepted:
  466. result = [self.dialog.ELineEdit.text(),
  467. self.dialog.ALineEdit.text(),
  468. self.dialog.DLineEdit.text(),
  469. self.dialog.GLineEdit.text(),
  470. self.dialog.BLineEdit.text(),
  471. self.dialog.eLineEdit.text()]
  472. resultJoined = ",".join(result)
  473. return resultJoined
  474. else:
  475. return None
  476. class AboutDialog(QDialog):
  477. """
  478. Dialogue showing information about the program.
  479. """
  480. def __init__(self):
  481. super().__init__()
  482. self.UIFileLoader(str(os.path.join(scriptDir, 'ui','aboutdialog.ui')))
  483. icon = QImage(str(os.path.join(scriptDir, 'ui','icon.png')))
  484. self.dialog.iconLabel.setPixmap(QPixmap.fromImage(icon).scaled(self.dialog.iconLabel.width(), self.dialog.iconLabel.height(), Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation))
  485. self.dialog.versionLabel.setText("Version " + _version.version)
  486. self.dialog.exec()
  487. def UIFileLoader(self, ui_file):
  488. ui_file = QFile(ui_file)
  489. ui_file.open(QFile.ReadOnly)
  490. self.dialog = uic.loadUi(ui_file)
  491. ui_file.close()
  492. class UnsavedMessageBox(QMessageBox):
  493. """
  494. Message box to alert the user of unsaved changes and allow them to choose how to act.
  495. """
  496. def __init__(self):
  497. super().__init__()
  498. self.setIcon(QMessageBox.Question)
  499. self.setWindowTitle("Unsaved changes")
  500. self.setText("The document has been modified.")
  501. self.setInformativeText("Do you want to save your changes?")
  502. self.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
  503. self.setDefaultButton(QMessageBox.Save)
  504. class UnreadableMessageBox(QMessageBox):
  505. """
  506. Message box to warn the user that the chosen file cannot be opened.
  507. """
  508. def __init__(self):
  509. super().__init__()
  510. self.setIcon(QMessageBox.Warning)
  511. self.setWindowTitle("File cannot be opened")
  512. self.setText("The file you have selected cannot be opened.")
  513. self.setInformativeText("Please make sure it is in the right format.")
  514. self.setStandardButtons(QMessageBox.Ok)
  515. self.setDefaultButton(QMessageBox.Ok)
  516. class NameWarningMessageBox(QMessageBox):
  517. """
  518. Message box to warn the user that a chord must have a name
  519. """
  520. def __init__(self):
  521. super().__init__()
  522. self.setIcon(QMessageBox.Warning)
  523. self.setWindowTitle("Unnamed chord")
  524. self.setText("Chords must have a name.")
  525. self.setInformativeText("Please give your chord a name and try again.")
  526. self.setStandardButtons(QMessageBox.Ok)
  527. self.setDefaultButton(QMessageBox.Ok)
  528. class VoicingWarningMessageBox(QMessageBox):
  529. """
  530. Message box to warn the user that the voicing entered could not be parsed
  531. """
  532. def __init__(self):
  533. super().__init__()
  534. self.setIcon(QMessageBox.Warning)
  535. self.setWindowTitle("Malformed voicing")
  536. self.setText("The voicing you entered was not understood and has not been applied.")
  537. self.setInformativeText("Please try re-entering it in the correct format.")
  538. self.setStandardButtons(QMessageBox.Ok)
  539. self.setDefaultButton(QMessageBox.Ok)
  540. class LengthWarningMessageBox(QMessageBox):
  541. """
  542. Message box to warn the user that a block must have a length
  543. """
  544. def __init__(self):
  545. super().__init__()
  546. self.setIcon(QMessageBox.Warning)
  547. self.setWindowTitle("Block without valid length")
  548. self.setText("Blocks must have a whole number length.")
  549. self.setInformativeText("Please enter a valid length for your block and try again.")
  550. self.setStandardButtons(QMessageBox.Ok)
  551. self.setDefaultButton(QMessageBox.Ok)
  552. if __name__ == '__main__':
  553. app = QApplication(sys.argv)
  554. d = Document()
  555. s = Style()
  556. w = DocumentWindow(d, s, filename=(sys.argv[1] if len(sys.argv) > 1 else None)) # pass first argument as filename
  557. w.show()
  558. sys.exit(app.exec_())