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.

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