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.

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