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.

938 lines
36 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
  8. import fitz
  9. import io
  10. import subprocess
  11. import os
  12. import time
  13. from copy import copy
  14. from PyQt5.QtWidgets import QApplication, QAction, QLabel, QDialogButtonBox, QDialog, QFileDialog, QMessageBox, QPushButton, QLineEdit, QCheckBox, QSpinBox, QDoubleSpinBox, QTableWidgetItem, QTabWidget, QComboBox, QWidget, QScrollArea, QMainWindow, QShortcut
  15. from PyQt5.QtCore import QFile, QObject, Qt, pyqtSlot, QSettings
  16. from PyQt5.QtGui import QPixmap, QImage, QKeySequence
  17. from PyQt5 import uic
  18. from chordsheet.tableView import ChordTableView, BlockTableView
  19. from chordsheet.comboBox import MComboBox
  20. from chordsheet.pdfViewer import PDFViewer
  21. from reportlab.lib.units import mm, cm, inch, pica
  22. from reportlab.lib.pagesizes import A4, A5, LETTER, LEGAL
  23. from reportlab.pdfbase import pdfmetrics
  24. from reportlab.pdfbase.ttfonts import TTFont
  25. from chordsheet.document import Document, Style, Chord, Block, Section
  26. from chordsheet.render import Renderer
  27. from chordsheet.parsers import parseFingering, parseName
  28. import _version
  29. # set the directory where our files are depending on whether we're running a pyinstaller binary or not
  30. if getattr(sys, 'frozen', False):
  31. scriptDir = sys._MEIPASS
  32. else:
  33. scriptDir = os.path.abspath(os.path.dirname(os.path.abspath(__file__)))
  34. # enable automatic high DPI scaling on Windows
  35. QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
  36. QApplication.setOrganizationName("Ivan Holmes")
  37. QApplication.setOrganizationDomain("ivanholmes.co.uk")
  38. QApplication.setApplicationName("Chordsheet")
  39. settings = QSettings()
  40. pdfmetrics.registerFont(
  41. TTFont('FreeSans', os.path.join(scriptDir, 'fonts', 'FreeSans.ttf')))
  42. if sys.platform == "darwin":
  43. pdfmetrics.registerFont(
  44. TTFont('HelveticaNeue', 'HelveticaNeue.ttc', subfontIndex=0))
  45. # dictionaries for combo boxes
  46. pageSizeDict = {'A4': A4, 'A5': A5, 'Letter': LETTER, 'Legal': LEGAL}
  47. # point is 1 because reportlab's native unit is points.
  48. unitDict = {'mm': mm, 'cm': cm, 'inch': inch, 'point': 1, 'pica': pica}
  49. class DocumentWindow(QMainWindow):
  50. """
  51. Class for the main window of the application.
  52. """
  53. def __init__(self, doc, style, filename=None):
  54. """
  55. Initialisation function for the main window of the application.
  56. Arguments:
  57. doc -- the Document object for the window to use
  58. style -- the Style object for the window to use
  59. """
  60. super().__init__()
  61. self.doc = doc
  62. self.style = style
  63. self.renderer = Renderer(self.doc, self.style)
  64. self.lastDoc = copy(self.doc)
  65. self.currentFilePath = filename
  66. self.UIFileLoader(str(os.path.join(scriptDir, 'ui', 'mainwindow.ui')))
  67. self.UIInitStyle()
  68. self.updateChordDict()
  69. self.updateSectionDict()
  70. self.currentSection = None
  71. self.setCentralWidget(self.window.centralWidget)
  72. self.setMenuBar(self.window.menuBar)
  73. self.setWindowTitle("Chordsheet")
  74. if filename:
  75. try:
  76. self.openFile(filename)
  77. except Exception:
  78. UnreadableMessageBox().exec()
  79. def closeEvent(self, event):
  80. """
  81. Reimplement the built in closeEvent to allow asking the user to save.
  82. """
  83. self.saveWarning()
  84. def UIFileLoader(self, ui_file):
  85. """
  86. Loads the .ui file for this window and connects the UI elements to their actions.
  87. """
  88. ui_file = QFile(ui_file)
  89. ui_file.open(QFile.ReadOnly)
  90. self.window = uic.loadUi(ui_file)
  91. ui_file.close()
  92. # link all the UI elements
  93. self.window.actionAbout.triggered.connect(self.menuFileAboutAction)
  94. self.window.actionNew.triggered.connect(self.menuFileNewAction)
  95. self.window.actionOpen.triggered.connect(self.menuFileOpenAction)
  96. self.window.actionSave.triggered.connect(self.menuFileSaveAction)
  97. self.window.actionSave_as.triggered.connect(self.menuFileSaveAsAction)
  98. self.window.actionSave_PDF.triggered.connect(
  99. self.menuFileSavePDFAction)
  100. self.window.actionPrint.triggered.connect(self.menuFilePrintAction)
  101. self.window.actionClose.triggered.connect(self.menuFileCloseAction)
  102. self.window.actionUndo.triggered.connect(self.menuEditUndoAction)
  103. self.window.actionRedo.triggered.connect(self.menuEditRedoAction)
  104. self.window.actionCut.triggered.connect(self.menuEditCutAction)
  105. self.window.actionCopy.triggered.connect(self.menuEditCopyAction)
  106. self.window.actionPaste.triggered.connect(self.menuEditPasteAction)
  107. self.window.actionNew.setShortcut(QKeySequence.New)
  108. self.window.actionOpen.setShortcut(QKeySequence.Open)
  109. self.window.actionSave.setShortcut(QKeySequence.Save)
  110. self.window.actionSave_as.setShortcut(QKeySequence.SaveAs)
  111. self.window.actionSave_PDF.setShortcut(QKeySequence("Ctrl+E"))
  112. self.window.actionPrint.setShortcut(QKeySequence.Print)
  113. self.window.actionClose.setShortcut(QKeySequence.Close)
  114. self.window.actionUndo.setShortcut(QKeySequence.Undo)
  115. self.window.actionRedo.setShortcut(QKeySequence.Redo)
  116. self.window.actionCut.setShortcut(QKeySequence.Cut)
  117. self.window.actionCopy.setShortcut(QKeySequence.Copy)
  118. self.window.actionPaste.setShortcut(QKeySequence.Paste)
  119. self.window.pageSizeComboBox.currentIndexChanged.connect(
  120. self.pageSizeAction)
  121. self.window.documentUnitsComboBox.currentIndexChanged.connect(
  122. self.unitAction)
  123. self.window.includedFontCheckBox.stateChanged.connect(
  124. self.includedFontAction)
  125. self.window.generateButton.clicked.connect(self.generateAction)
  126. # update whole document when any tab is selected
  127. self.window.tabWidget.tabBarClicked.connect(self.tabBarUpdateAction)
  128. self.window.guitarVoicingButton.clicked.connect(
  129. self.guitarVoicingAction)
  130. self.window.addChordButton.clicked.connect(self.addChordAction)
  131. self.window.removeChordButton.clicked.connect(self.removeChordAction)
  132. self.window.updateChordButton.clicked.connect(self.updateChordAction)
  133. # connecting clicked only works for this combo box because it's my own modified version (MComboBox)
  134. self.window.blockSectionComboBox.clicked.connect(
  135. self.blockSectionClickedAction)
  136. self.window.blockSectionComboBox.currentIndexChanged.connect(
  137. self.blockSectionChangedAction)
  138. self.window.addBlockButton.clicked.connect(self.addBlockAction)
  139. self.window.removeBlockButton.clicked.connect(self.removeBlockAction)
  140. self.window.updateBlockButton.clicked.connect(self.updateBlockAction)
  141. self.window.addSectionButton.clicked.connect(self.addSectionAction)
  142. self.window.removeSectionButton.clicked.connect(
  143. self.removeSectionAction)
  144. self.window.updateSectionButton.clicked.connect(
  145. self.updateSectionAction)
  146. self.window.chordTableView.clicked.connect(self.chordClickedAction)
  147. self.window.sectionTableView.clicked.connect(self.sectionClickedAction)
  148. self.window.blockTableView.clicked.connect(self.blockClickedAction)
  149. def UIInitDocument(self):
  150. """
  151. Fills the window's fields with the values from its document.
  152. """
  153. self.updateTitleBar()
  154. # set all fields to appropriate values from document
  155. self.window.titleLineEdit.setText(self.doc.title)
  156. self.window.subtitleLineEdit.setText(self.doc.subtitle)
  157. self.window.composerLineEdit.setText(self.doc.composer)
  158. self.window.arrangerLineEdit.setText(self.doc.arranger)
  159. self.window.timeSignatureSpinBox.setValue(self.doc.timeSignature)
  160. self.window.tempoLineEdit.setText(self.doc.tempo)
  161. self.window.chordTableView.populate(self.doc.chordList)
  162. self.window.sectionTableView.populate(self.doc.sectionList)
  163. # populate the block table with the first section, account for a document with no sections
  164. self.currentSection = self.doc.sectionList[0] if len(
  165. self.doc.sectionList) else None
  166. self.window.blockTableView.populate(
  167. self.currentSection.blockList if self.currentSection else [])
  168. self.updateSectionDict()
  169. self.updateChordDict()
  170. def UIInitStyle(self):
  171. """
  172. Fills the window's fields with the values from its style.
  173. """
  174. self.window.pageSizeComboBox.addItems(list(pageSizeDict.keys()))
  175. self.window.pageSizeComboBox.setCurrentText(
  176. list(pageSizeDict.keys())[0])
  177. self.window.documentUnitsComboBox.addItems(list(unitDict.keys()))
  178. self.window.documentUnitsComboBox.setCurrentText(
  179. list(unitDict.keys())[0])
  180. self.window.lineSpacingDoubleSpinBox.setValue(self.style.lineSpacing)
  181. self.window.leftMarginLineEdit.setText(str(self.style.leftMargin))
  182. self.window.rightMarginLineEdit.setText(str(self.style.rightMargin))
  183. self.window.topMarginLineEdit.setText(str(self.style.topMargin))
  184. self.window.bottomMarginLineEdit.setText(str(self.style.bottomMargin))
  185. self.window.fontComboBox.setDisabled(True)
  186. self.window.includedFontCheckBox.setChecked(True)
  187. self.window.beatWidthLineEdit.setText(str(self.style.unitWidth))
  188. def tabBarUpdateAction(self, index):
  189. self.updateDocument()
  190. def pageSizeAction(self, index):
  191. self.pageSizeSelected = self.window.pageSizeComboBox.itemText(index)
  192. def unitAction(self, index):
  193. self.unitSelected = self.window.documentUnitsComboBox.itemText(index)
  194. def includedFontAction(self):
  195. if self.window.includedFontCheckBox.isChecked():
  196. self.style.useIncludedFont = True
  197. else:
  198. self.style.useIncludedFont = False
  199. def chordClickedAction(self, index):
  200. # set the controls to the values from the selected chord
  201. self.window.chordNameLineEdit.setText(
  202. self.window.chordTableView.model.item(index.row(), 0).text())
  203. self.window.guitarVoicingLineEdit.setText(
  204. self.window.chordTableView.model.item(index.row(), 1).text())
  205. def sectionClickedAction(self, index):
  206. # set the controls to the values from the selected section
  207. self.window.sectionNameLineEdit.setText(
  208. self.window.sectionTableView.model.item(index.row(), 0).text())
  209. # also set the combo box on the block page to make it flow well
  210. curSecName = self.window.sectionTableView.model.item(
  211. index.row(), 0).text()
  212. if curSecName:
  213. self.window.blockSectionComboBox.setCurrentText(
  214. curSecName)
  215. def blockSectionClickedAction(self, text):
  216. if text:
  217. self.updateBlocks(self.sectionDict[text])
  218. def blockSectionChangedAction(self, index):
  219. sName = self.window.blockSectionComboBox.currentText()
  220. if sName:
  221. self.currentSection = self.sectionDict[sName]
  222. self.window.blockTableView.populate(self.currentSection.blockList)
  223. else:
  224. self.currentSection = None
  225. def blockClickedAction(self, index):
  226. # set the controls to the values from the selected block
  227. bChord = self.window.blockTableView.model.item(index.row(), 0).text()
  228. self.window.blockChordComboBox.setCurrentText(
  229. bChord if bChord else "None")
  230. self.window.blockLengthLineEdit.setText(
  231. self.window.blockTableView.model.item(index.row(), 1).text())
  232. self.window.blockNotesLineEdit.setText(
  233. self.window.blockTableView.model.item(index.row(), 2).text())
  234. def getPath(self, value):
  235. """
  236. Wrapper for Qt settings to return home directory if no setting exists.
  237. """
  238. return str((settings.value(value) if settings.value(value) else os.path.expanduser("~")))
  239. def setPath(self, value, fullpath):
  240. """
  241. Wrapper for Qt settings to set path to open/save from next time from current file location.
  242. """
  243. return settings.setValue(value, os.path.dirname(fullpath))
  244. def menuFileNewAction(self):
  245. self.doc = Document() #  new document object
  246. # copy this object as reference to check against on quitting
  247. self.lastDoc = copy(self.doc)
  248. #  reset file path (this document hasn't been saved yet)
  249. self.currentFilePath = None
  250. # new renderer
  251. self.renderer = Renderer(self.doc, self.style)
  252. self.UIInitDocument()
  253. self.updatePreview()
  254. def menuFileOpenAction(self):
  255. filePath = QFileDialog.getOpenFileName(self.window.tabWidget, 'Open file', self.getPath(
  256. "workingPath"), "Chordsheet ML files (*.xml *.cml)")[0]
  257. if filePath:
  258. self.openFile(filePath)
  259. def openFile(self, filePath):
  260. """
  261. Opens a file from a file path and sets up the window accordingly.
  262. """
  263. self.currentFilePath = filePath
  264. self.doc.loadXML(self.currentFilePath)
  265. self.lastDoc = copy(self.doc)
  266. self.setPath("workingPath", self.currentFilePath)
  267. self.UIInitDocument()
  268. self.updatePreview()
  269. def menuFileSaveAction(self):
  270. self.updateDocument()
  271. if not self.currentFilePath:
  272. filePath = QFileDialog.getSaveFileName(self.window.tabWidget, 'Save file', self.getPath(
  273. "workingPath"), "Chordsheet ML files (*.xml *.cml)")[0]
  274. else:
  275. filePath = self.currentFilePath
  276. self.saveFile(filePath)
  277. def menuFileSaveAsAction(self):
  278. self.updateDocument()
  279. filePath = QFileDialog.getSaveFileName(self.window.tabWidget, 'Save file', self.getPath(
  280. "workingPath"), "Chordsheet ML files (*.xml *.cml)")[0]
  281. if filePath:
  282. self.saveFile(filePath)
  283. def saveFile(self, filePath):
  284. """
  285. Saves a file to given file path and sets up environment.
  286. """
  287. self.currentFilePath = filePath
  288. self.doc.saveXML(self.currentFilePath)
  289. self.lastDoc = copy(self.doc)
  290. self.setPath("workingPath", self.currentFilePath)
  291. self.updateTitleBar() # as we may have a new filename
  292. def menuFileSavePDFAction(self):
  293. self.updateDocument()
  294. self.updatePreview()
  295. filePath = QFileDialog.getSaveFileName(self.window.tabWidget, 'Save file', self.getPath(
  296. "lastExportPath"), "PDF files (*.pdf)")[0]
  297. if filePath:
  298. self.renderer.savePDF(filePath)
  299. self.setPath("lastExportPath", filePath)
  300. def menuFilePrintAction(self):
  301. if sys.platform == "darwin":
  302. pass
  303. # subprocess.call()
  304. else:
  305. pass
  306. @pyqtSlot()
  307. def menuFileCloseAction(self):
  308. self.saveWarning()
  309. def menuFileAboutAction(self):
  310. AboutDialog()
  311. def menuEditUndoAction(self):
  312. try:
  313. QApplication.focusWidget().undo() # see if the built in widget supports it
  314. except Exception:
  315. pass #  if not just fail silently
  316. def menuEditRedoAction(self):
  317. try:
  318. QApplication.focusWidget().redo()
  319. except Exception:
  320. pass
  321. def menuEditCutAction(self):
  322. try:
  323. QApplication.focusWidget().cut()
  324. except Exception:
  325. pass
  326. def menuEditCopyAction(self):
  327. try:
  328. QApplication.focusWidget().copy()
  329. except Exception:
  330. pass
  331. def menuEditPasteAction(self):
  332. try:
  333. QApplication.focusWidget().paste()
  334. except Exception:
  335. pass
  336. def saveWarning(self):
  337. """
  338. Function to check if the document has unsaved data in it and offer to save it.
  339. """
  340. self.updateDocument() # update the document to catch all changes
  341. if self.lastDoc == self.doc:
  342. self.close()
  343. else:
  344. wantToSave = UnsavedMessageBox().exec()
  345. if wantToSave == QMessageBox.Save:
  346. if not self.currentFilePath:
  347. filePath = QFileDialog.getSaveFileName(self.window.tabWidget, 'Save file', str(
  348. os.path.expanduser("~")), "Chordsheet ML files (*.xml *.cml)")
  349. self.currentFilePath = filePath[0]
  350. self.doc.saveXML(self.currentFilePath)
  351. self.close()
  352. elif wantToSave == QMessageBox.Discard:
  353. self.close()
  354. # if cancel or anything else do nothing at all
  355. def guitarVoicingAction(self):
  356. gdialog = GuitarDialog()
  357. voicing = gdialog.getVoicing()
  358. if voicing:
  359. self.window.guitarVoicingLineEdit.setText(voicing)
  360. def clearChordLineEdits(self):
  361. self.window.chordNameLineEdit.clear()
  362. self.window.guitarVoicingLineEdit.clear()
  363. # necessary on Mojave with PyInstaller (or previous contents will be shown)
  364. self.window.chordNameLineEdit.repaint()
  365. self.window.guitarVoicingLineEdit.repaint()
  366. def clearSectionLineEdits(self):
  367. self.window.sectionNameLineEdit.clear()
  368. # necessary on Mojave with PyInstaller (or previous contents will be shown)
  369. self.window.sectionNameLineEdit.repaint()
  370. def clearBlockLineEdits(self):
  371. self.window.blockLengthLineEdit.clear()
  372. self.window.blockNotesLineEdit.clear()
  373. # necessary on Mojave with PyInstaller (or previous contents will be shown)
  374. self.window.blockLengthLineEdit.repaint()
  375. self.window.blockNotesLineEdit.repaint()
  376. def updateChordDict(self):
  377. """
  378. Updates the dictionary used to generate the Chord menu (on the block tab)
  379. """
  380. self.chordDict = {'None': None}
  381. self.chordDict.update({c.name: c for c in self.doc.chordList})
  382. self.window.blockChordComboBox.clear()
  383. self.window.blockChordComboBox.addItems(list(self.chordDict.keys()))
  384. def updateSectionDict(self):
  385. """
  386. Updates the dictionary used to generate the Section menu (on the block tab)
  387. """
  388. self.sectionDict = {s.name: s for s in self.doc.sectionList}
  389. self.window.blockSectionComboBox.clear()
  390. self.window.blockSectionComboBox.addItems(
  391. list(self.sectionDict.keys()))
  392. def removeChordAction(self):
  393. if self.window.chordTableView.selectionModel().hasSelection(): #  check for selection
  394. self.updateChords()
  395. row = self.window.chordTableView.selectionModel().currentIndex().row()
  396. self.doc.chordList.pop(row)
  397. self.window.chordTableView.populate(self.doc.chordList)
  398. self.clearChordLineEdits()
  399. self.updateChordDict()
  400. def addChordAction(self):
  401. success = False # initialise
  402. self.updateChords()
  403. cName = parseName(self.window.chordNameLineEdit.text())
  404. if cName:
  405. self.doc.chordList.append(Chord(cName))
  406. if self.window.guitarVoicingLineEdit.text():
  407. try:
  408. self.doc.chordList[-1].voicings['guitar'] = parseFingering(
  409. self.window.guitarVoicingLineEdit.text(), 'guitar')
  410. success = True #  chord successfully parsed
  411. except Exception:
  412. VoicingWarningMessageBox().exec() # Voicing is malformed, warn user
  413. else:
  414. success = True #  chord successfully parsed
  415. else:
  416. ChordNameWarningMessageBox().exec() # Chord has no name, warn user
  417. if success == True: # if chord was parsed properly
  418. self.window.chordTableView.populate(self.doc.chordList)
  419. self.clearChordLineEdits()
  420. self.updateChordDict()
  421. def updateChordAction(self):
  422. success = False # see comments above
  423. if self.window.chordTableView.selectionModel().hasSelection(): #  check for selection
  424. self.updateChords()
  425. row = self.window.chordTableView.selectionModel().currentIndex().row()
  426. oldName = self.window.chordTableView.model.item(row, 0).text()
  427. cName = parseName(self.window.chordNameLineEdit.text())
  428. if cName:
  429. self.doc.chordList[row].name = cName
  430. if self.window.guitarVoicingLineEdit.text():
  431. try:
  432. self.doc.chordList[row].voicings['guitar'] = parseFingering(
  433. self.window.guitarVoicingLineEdit.text(), 'guitar')
  434. success = True
  435. except Exception:
  436. VoicingWarningMessageBox().exec()
  437. else:
  438. success = True
  439. else:
  440. ChordNameWarningMessageBox().exec()
  441. if success == True:
  442. self.updateChordDict()
  443. self.window.chordTableView.populate(self.doc.chordList)
  444. # update the names of chords in all blocklists in case they've already been used
  445. for s in self.doc.sectionList:
  446. for b in s.blockList:
  447. if b.chord:
  448. if b.chord.name == oldName:
  449. b.chord.name = cName
  450. self.window.blockTableView.populate(self.currentSection.blockList)
  451. self.clearChordLineEdits()
  452. def removeSectionAction(self):
  453. if self.window.sectionTableView.selectionModel().hasSelection(): #  check for selection
  454. self.updateSections()
  455. row = self.window.sectionTableView.selectionModel().currentIndex().row()
  456. self.doc.sectionList.pop(row)
  457. self.window.sectionTableView.populate(self.doc.sectionList)
  458. self.clearSectionLineEdits()
  459. self.updateSectionDict()
  460. def addSectionAction(self):
  461. self.updateSections()
  462. sName = self.window.sectionNameLineEdit.text()
  463. if sName and sName not in [s.name for s in self.doc.sectionList]:
  464. self.doc.sectionList.append(Section(name=sName))
  465. self.window.sectionTableView.populate(self.doc.sectionList)
  466. self.clearSectionLineEdits()
  467. self.updateSectionDict()
  468. else:
  469. # Section has no name or non unique, warn user
  470. SectionNameWarningMessageBox().exec()
  471. def updateSectionAction(self):
  472. if self.window.sectionTableView.selectionModel().hasSelection(): #  check for selection
  473. self.updateSections()
  474. row = self.window.sectionTableView.selectionModel().currentIndex().row()
  475. sName = self.window.sectionNameLineEdit.text()
  476. if sName and sName not in [s.name for s in self.doc.sectionList]:
  477. self.doc.sectionList[row].name = sName
  478. self.window.sectionTableView.populate(self.doc.sectionList)
  479. self.clearSectionLineEdits()
  480. self.updateSectionDict()
  481. else:
  482. # Section has no name or non unique, warn user
  483. SectionNameWarningMessageBox().exec()
  484. def removeBlockAction(self):
  485. if self.window.blockTableView.selectionModel().hasSelection(): #  check for selection
  486. self.updateBlocks(self.currentSection)
  487. row = self.window.blockTableView.selectionModel().currentIndex().row()
  488. self.currentSection.blockList.pop(row)
  489. self.window.blockTableView.populate(self.currentSection.blockList)
  490. def addBlockAction(self):
  491. self.updateBlocks(self.currentSection)
  492. try:
  493. #  can the value entered for block length be cast as a float
  494. bLength = float(self.window.blockLengthLineEdit.text())
  495. except Exception:
  496. bLength = False
  497. if bLength: # create the block
  498. self.currentSection.blockList.append(Block(bLength,
  499. chord=self.chordDict[self.window.blockChordComboBox.currentText(
  500. )],
  501. notes=(self.window.blockNotesLineEdit.text() if not "" else None)))
  502. self.window.blockTableView.populate(self.currentSection.blockList)
  503. self.clearBlockLineEdits()
  504. else:
  505. # show warning that length was not entered or in wrong format
  506. LengthWarningMessageBox().exec()
  507. def updateBlockAction(self):
  508. if self.window.blockTableView.selectionModel().hasSelection(): #  check for selection
  509. self.updateBlocks(self.currentSection)
  510. try:
  511. #  can the value entered for block length be cast as a float
  512. bLength = float(self.window.blockLengthLineEdit.text())
  513. except Exception:
  514. bLength = False
  515. row = self.window.blockTableView.selectionModel().currentIndex().row()
  516. if bLength:
  517. self.currentSection.blockList[row] = (Block(bLength,
  518. chord=self.chordDict[self.window.blockChordComboBox.currentText(
  519. )],
  520. notes=(self.window.blockNotesLineEdit.text() if not "" else None)))
  521. self.window.blockTableView.populate(
  522. self.currentSection.blockList)
  523. self.clearBlockLineEdits()
  524. else:
  525. LengthWarningMessageBox().exec()
  526. def generateAction(self):
  527. self.updateDocument()
  528. self.updatePreview()
  529. def updatePreview(self):
  530. """
  531. Update the preview shown by rendering a new PDF and drawing it to the scroll area.
  532. """
  533. try:
  534. self.currentPreview = self.renderer.stream()
  535. except Exception:
  536. QMessageBox.warning(self, "Preview failed", "Could not update the preview.",
  537. buttons=QMessageBox.Ok, defaultButton=QMessageBox.Ok)
  538. self.window.pdfArea.update(self.currentPreview)
  539. def updateTitleBar(self):
  540. """
  541. Update the application's title bar to reflect the current document.
  542. """
  543. if self.currentFilePath:
  544. self.setWindowTitle(_version.appName + " – " +
  545. os.path.basename(self.currentFilePath))
  546. else:
  547. self.setWindowTitle(_version.appName)
  548. def updateChords(self):
  549. """
  550. Update the chord list by reading the table.
  551. """
  552. chordTableList = []
  553. for i in range(self.window.chordTableView.model.rowCount()):
  554. chordTableList.append(
  555. Chord(parseName(self.window.chordTableView.model.item(i, 0).text()))),
  556. if self.window.chordTableView.model.item(i, 1).text():
  557. chordTableList[-1].voicings['guitar'] = parseFingering(
  558. self.window.chordTableView.model.item(i, 1).text(), 'guitar')
  559. self.doc.chordList = chordTableList
  560. def matchSection(self, nameToMatch):
  561. """
  562. Given the name of a section, this function checks if it is already present in the document.
  563. If it is, it's returned. If not, a new section with the given name is returned.
  564. """
  565. section = None
  566. for s in self.doc.sectionList:
  567. if s.name == nameToMatch:
  568. section = s
  569. break
  570. if section is None:
  571. section = Section(name=nameToMatch)
  572. return section
  573. def updateSections(self):
  574. """
  575. Update the section list by reading the table
  576. """
  577. sectionTableList = []
  578. for i in range(self.window.sectionTableView.model.rowCount()):
  579. sectionTableList.append(self.matchSection(
  580. self.window.sectionTableView.model.item(i, 0).text()))
  581. self.doc.sectionList = sectionTableList
  582. def updateBlocks(self, section):
  583. """
  584. Update the block list by reading the table.
  585. """
  586. blockTableList = []
  587. for i in range(self.window.blockTableView.model.rowCount()):
  588. blockLength = float(
  589. self.window.blockTableView.model.item(i, 1).text())
  590. blockChord = self.chordDict[(self.window.blockTableView.model.item(
  591. i, 0).text() if self.window.blockTableView.model.item(i, 0).text() else "None")]
  592. blockNotes = self.window.blockTableView.model.item(i, 2).text(
  593. ) if self.window.blockTableView.model.item(i, 2).text() else None
  594. blockTableList.append(
  595. Block(blockLength, chord=blockChord, notes=blockNotes))
  596. section.blockList = blockTableList
  597. def updateDocument(self):
  598. """
  599. Update the Document object by reading values from the UI.
  600. """
  601. self.doc.title = self.window.titleLineEdit.text(
  602. ) # Title can be empty string but not None
  603. self.doc.subtitle = (self.window.subtitleLineEdit.text(
  604. ) if self.window.subtitleLineEdit.text() else None)
  605. self.doc.composer = (self.window.composerLineEdit.text(
  606. ) if self.window.composerLineEdit.text() else None)
  607. self.doc.arranger = (self.window.arrangerLineEdit.text(
  608. ) if self.window.arrangerLineEdit.text() else None)
  609. self.doc.tempo = (self.window.tempoLineEdit.text()
  610. if self.window.tempoLineEdit.text() else None)
  611. self.doc.timeSignature = int(self.window.timeSignatureSpinBox.value(
  612. )) if self.window.timeSignatureSpinBox.value() else self.doc.timeSignature
  613. self.style.pageSize = pageSizeDict[self.pageSizeSelected]
  614. self.style.unit = unitDict[self.unitSelected]
  615. self.style.leftMargin = float(self.window.leftMarginLineEdit.text(
  616. )) if self.window.leftMarginLineEdit.text() else self.style.leftMargin
  617. self.style.rightMargin = float(self.window.rightMarginLineEdit.text(
  618. )) if self.window.rightMarginLineEdit.text() else self.style.rightMargin
  619. self.style.topMargin = float(self.window.topMarginLineEdit.text(
  620. )) if self.window.topMarginLineEdit.text() else self.style.topMargin
  621. self.style.bottomMargin = float(self.window.bottomMarginLineEdit.text(
  622. )) if self.window.bottomMarginLineEdit.text() else self.style.bottomMargin
  623. self.style.lineSpacing = float(self.window.lineSpacingDoubleSpinBox.value(
  624. )) if self.window.lineSpacingDoubleSpinBox.value() else self.style.lineSpacing
  625. # make sure the unit width isn't too wide to draw!
  626. if self.window.beatWidthLineEdit.text():
  627. if (self.style.pageSize[0] - 2 * self.style.leftMargin * mm) >= (float(self.window.beatWidthLineEdit.text()) * 2 * self.doc.timeSignature * mm):
  628. self.style.unitWidth = float(
  629. self.window.beatWidthLineEdit.text())
  630. else:
  631. maxBeatWidth = (
  632. self.style.pageSize[0] - 2 * self.style.leftMargin * mm) / (2 * self.doc.timeSignature * mm)
  633. QMessageBox.warning(self, "Out of range", "Beat width is out of range. It can be a maximum of {}.".format(
  634. maxBeatWidth), buttons=QMessageBox.Ok, defaultButton=QMessageBox.Ok)
  635. # update chords, sections, blocks
  636. self.updateChords()
  637. self.updateSections()
  638. if self.currentSection:
  639. self.updateBlocks(self.currentSection)
  640. self.style.font = (
  641. 'FreeSans' if self.style.useIncludedFont else 'HelveticaNeue')
  642. # something for the font box here
  643. class GuitarDialog(QDialog):
  644. """
  645. Dialogue to allow the user to enter a guitar chord voicing. Not particularly advanced at present!
  646. May be extended in future.
  647. """
  648. def __init__(self):
  649. super().__init__()
  650. self.UIFileLoader(
  651. str(os.path.join(scriptDir, 'ui', 'guitardialog.ui')))
  652. def UIFileLoader(self, ui_file):
  653. ui_file = QFile(ui_file)
  654. ui_file.open(QFile.ReadOnly)
  655. self.dialog = uic.loadUi(ui_file)
  656. ui_file.close()
  657. def getVoicing(self):
  658. """
  659. Show the dialogue and return the voicing that has been entered.
  660. """
  661. if self.dialog.exec_() == QDialog.Accepted:
  662. result = [self.dialog.ELineEdit.text(),
  663. self.dialog.ALineEdit.text(),
  664. self.dialog.DLineEdit.text(),
  665. self.dialog.GLineEdit.text(),
  666. self.dialog.BLineEdit.text(),
  667. self.dialog.eLineEdit.text()]
  668. resultJoined = ",".join(result)
  669. return resultJoined
  670. else:
  671. return None
  672. class AboutDialog(QDialog):
  673. """
  674. Dialogue showing information about the program.
  675. """
  676. def __init__(self):
  677. super().__init__()
  678. self.UIFileLoader(str(os.path.join(scriptDir, 'ui', 'aboutdialog.ui')))
  679. icon = QImage(str(os.path.join(scriptDir, 'ui', 'icon.png')))
  680. self.dialog.iconLabel.setPixmap(QPixmap.fromImage(icon).scaled(self.dialog.iconLabel.width(
  681. ), self.dialog.iconLabel.height(), Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation))
  682. self.dialog.versionLabel.setText("Version " + _version.version)
  683. self.dialog.exec()
  684. def UIFileLoader(self, ui_file):
  685. ui_file = QFile(ui_file)
  686. ui_file.open(QFile.ReadOnly)
  687. self.dialog = uic.loadUi(ui_file)
  688. ui_file.close()
  689. class UnsavedMessageBox(QMessageBox):
  690. """
  691. Message box to alert the user of unsaved changes and allow them to choose how to act.
  692. """
  693. def __init__(self):
  694. super().__init__()
  695. self.setIcon(QMessageBox.Question)
  696. self.setWindowTitle("Unsaved changes")
  697. self.setText("The document has been modified.")
  698. self.setInformativeText("Do you want to save your changes?")
  699. self.setStandardButtons(
  700. QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
  701. self.setDefaultButton(QMessageBox.Save)
  702. class UnreadableMessageBox(QMessageBox):
  703. """
  704. Message box to warn the user that the chosen file cannot be opened.
  705. """
  706. def __init__(self):
  707. super().__init__()
  708. self.setIcon(QMessageBox.Warning)
  709. self.setWindowTitle("File cannot be opened")
  710. self.setText("The file you have selected cannot be opened.")
  711. self.setInformativeText("Please make sure it is in the right format.")
  712. self.setStandardButtons(QMessageBox.Ok)
  713. self.setDefaultButton(QMessageBox.Ok)
  714. class ChordNameWarningMessageBox(QMessageBox):
  715. """
  716. Message box to warn the user that a chord must have a name
  717. """
  718. def __init__(self):
  719. super().__init__()
  720. self.setIcon(QMessageBox.Warning)
  721. self.setWindowTitle("Unnamed chord")
  722. self.setText("Chords must have a name.")
  723. self.setInformativeText("Please give your chord a name and try again.")
  724. self.setStandardButtons(QMessageBox.Ok)
  725. self.setDefaultButton(QMessageBox.Ok)
  726. class SectionNameWarningMessageBox(QMessageBox):
  727. """
  728. Message box to warn the user that a section must have a name
  729. """
  730. def __init__(self):
  731. super().__init__()
  732. self.setIcon(QMessageBox.Warning)
  733. self.setWindowTitle("Unnamed section")
  734. self.setText("Sections must have a unique name.")
  735. self.setInformativeText(
  736. "Please give your section a unique name and try again.")
  737. self.setStandardButtons(QMessageBox.Ok)
  738. self.setDefaultButton(QMessageBox.Ok)
  739. class VoicingWarningMessageBox(QMessageBox):
  740. """
  741. Message box to warn the user that the voicing entered could not be parsed
  742. """
  743. def __init__(self):
  744. super().__init__()
  745. self.setIcon(QMessageBox.Warning)
  746. self.setWindowTitle("Malformed voicing")
  747. self.setText(
  748. "The voicing you entered was not understood and has not been applied.")
  749. self.setInformativeText(
  750. "Please try re-entering it in the correct format.")
  751. self.setStandardButtons(QMessageBox.Ok)
  752. self.setDefaultButton(QMessageBox.Ok)
  753. class LengthWarningMessageBox(QMessageBox):
  754. """
  755. Message box to warn the user that a block must have a length
  756. """
  757. def __init__(self):
  758. super().__init__()
  759. self.setIcon(QMessageBox.Warning)
  760. self.setWindowTitle("Block without valid length")
  761. self.setText("Blocks must have a whole number length.")
  762. self.setInformativeText(
  763. "Please enter a valid length for your block and try again.")
  764. self.setStandardButtons(QMessageBox.Ok)
  765. self.setDefaultButton(QMessageBox.Ok)
  766. if __name__ == '__main__':
  767. app = QApplication(sys.argv)
  768. d = Document()
  769. s = Style()
  770. # pass first argument as filename
  771. w = DocumentWindow(d, s, filename=(
  772. sys.argv[1] if len(sys.argv) > 1 else None))
  773. w.show()
  774. sys.exit(app.exec_())