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.

362 lines
15 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 PyQt5.QtWidgets import QApplication, QAction, QLabel, QDialogButtonBox, QDialog, QFileDialog, QMessageBox, QPushButton, QLineEdit, QCheckBox, QSpinBox, QDoubleSpinBox, QTableWidget, QTableWidgetItem, QTabWidget, QComboBox, QWidget, QScrollArea
  9. from PyQt5.QtCore import QFile, QObject, Qt
  10. from PyQt5.QtGui import QPixmap, QImage
  11. from PyQt5 import uic
  12. from chordsheet.tableView import ChordTableView, BlockTableView , MItemModel, MProxyStyle
  13. from reportlab.lib.units import mm, cm, inch, pica
  14. from reportlab.lib.pagesizes import A4, A5, LETTER, LEGAL
  15. from reportlab.pdfbase import pdfmetrics
  16. from reportlab.pdfbase.ttfonts import TTFont
  17. from chordsheet.document import Document, Style, Chord, Block
  18. from chordsheet.render import savePDF
  19. from chordsheet.parsers import parseFingering, parseName
  20. if getattr(sys, 'frozen', False):
  21. scriptDir = sys._MEIPASS
  22. else:
  23. scriptDir = os.path.abspath(os.path.dirname(os.path.abspath(__file__)))
  24. QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
  25. pdfmetrics.registerFont(TTFont('FreeSans', os.path.join(scriptDir, 'fonts', 'FreeSans.ttf')))
  26. if sys.platform == "darwin":
  27. pdfmetrics.registerFont(TTFont('HelveticaNeue', 'HelveticaNeue.ttc', subfontIndex=0))
  28. pageSizeDict = {'A4':A4, 'A5':A5, 'Letter':LETTER, 'Legal':LEGAL}
  29. unitDict = {'mm':mm, 'cm':cm, 'inch':inch, 'point':1, 'pica':pica} # point is 1 because reportlab's native unit is points.
  30. class DocumentWindow(QWidget):
  31. def __init__(self, doc, style, parent=None):
  32. super().__init__(parent)
  33. self.doc = doc
  34. self.style = style
  35. self.UIFileLoader(str(os.path.join(scriptDir, 'ui','mainwindow.ui')))
  36. self.UIInitStyle()
  37. # self.UIInitDocument()
  38. def UIFileLoader(self, ui_file):
  39. ui_file = QFile(ui_file)
  40. ui_file.open(QFile.ReadOnly)
  41. self.window = uic.loadUi(ui_file)
  42. ui_file.close()
  43. self.window.actionNew.triggered.connect(self.menuFileNewAction)
  44. self.window.actionOpen.triggered.connect(self.menuFileOpenAction)
  45. self.window.actionSave.triggered.connect(self.menuFileSaveAction)
  46. self.window.actionSave_as.triggered.connect(self.menuFileSaveAsAction)
  47. self.window.actionSave_PDF.triggered.connect(self.menuFileSavePDFAction)
  48. self.window.actionPrint.triggered.connect(self.menuFilePrintAction)
  49. self.window.actionClose.triggered.connect(self.menuFileCloseAction)
  50. self.window.pageSizeComboBox.currentIndexChanged.connect(self.pageSizeAction)
  51. self.window.documentUnitsComboBox.currentIndexChanged.connect(self.unitAction)
  52. self.window.includedFontCheckBox.stateChanged.connect(self.includedFontAction)
  53. self.window.generateButton.clicked.connect(self.generateAction)
  54. self.window.guitarVoicingButton.clicked.connect(self.guitarVoicingAction)
  55. self.window.addChordButton.clicked.connect(self.addChordAction)
  56. self.window.removeChordButton.clicked.connect(self.removeChordAction)
  57. self.window.updateChordButton.clicked.connect(self.updateChordAction)
  58. self.window.addBlockButton.clicked.connect(self.addBlockAction)
  59. self.window.removeBlockButton.clicked.connect(self.removeBlockAction)
  60. self.window.updateBlockButton.clicked.connect(self.updateBlockAction)
  61. self.window.chordTableView.clicked.connect(self.chordClickedAction)
  62. self.window.blockTableView.clicked.connect(self.blockClickedAction)
  63. def UIInitDocument(self):
  64. self.window.titleLineEdit.setText(self.doc.title)
  65. self.window.composerLineEdit.setText(self.doc.composer)
  66. self.window.arrangerLineEdit.setText(self.doc.arranger)
  67. self.window.timeSignatureSpinBox.setValue(self.doc.timeSignature)
  68. # chord and block table lists here
  69. self.window.chordTableView.populate(self.doc.chordList)
  70. self.window.blockTableView.populate(self.doc.blockList)
  71. self.updateChordDict()
  72. self.window.tabWidget.setCurrentWidget(self.window.tabWidget.findChild(QWidget, 'Overview'))
  73. # self.updatePreview()
  74. def UIInitStyle(self):
  75. self.window.pageSizeComboBox.addItems(list(pageSizeDict.keys()))
  76. self.window.pageSizeComboBox.setCurrentText(list(pageSizeDict.keys())[0])
  77. self.window.documentUnitsComboBox.addItems(list(unitDict.keys()))
  78. self.window.documentUnitsComboBox.setCurrentText(list(unitDict.keys())[0])
  79. self.window.lineSpacingDoubleSpinBox.setValue(self.style.lineSpacing)
  80. self.window.leftMarginLineEdit.setText(str(self.style.leftMargin))
  81. self.window.topMarginLineEdit.setText(str(self.style.topMargin))
  82. self.window.fontComboBox.setDisabled(True)
  83. self.window.includedFontCheckBox.setChecked(True)
  84. def pageSizeAction(self, index):
  85. self.pageSizeSelected = self.window.pageSizeComboBox.itemText(index)
  86. def unitAction(self, index):
  87. self.unitSelected = self.window.documentUnitsComboBox.itemText(index)
  88. def includedFontAction(self):
  89. if self.window.includedFontCheckBox.isChecked():
  90. self.style.useIncludedFont = True
  91. else:
  92. self.style.useIncludedFont = False
  93. def chordClickedAction(self, index):
  94. self.window.chordNameLineEdit.setText(self.window.chordTableView.model.item(index.row(), 0).text())
  95. self.window.guitarVoicingLineEdit.setText(self.window.chordTableView.model.item(index.row(), 1).text())
  96. def blockClickedAction(self, index):
  97. self.window.blockChordComboBox.setCurrentText(self.window.blockTableView.model.item(index.row(), 0).text())
  98. self.window.blockLengthLineEdit.setText(self.window.blockTableView.model.item(index.row(), 1).text())
  99. self.window.blockNotesLineEdit.setText(self.window.blockTableView.model.item(index.row(), 2).text())
  100. def menuFileNewAction(self):
  101. self.doc = Document()
  102. def menuFileOpenAction(self):
  103. filePath = QFileDialog.getOpenFileName(self.window.tabWidget, 'Open file', str(os.path.expanduser("~")), "Chordsheet ML files (*.xml *.cml)")
  104. if filePath[0]:
  105. self.currentFilePath = filePath[0]
  106. self.doc.loadXML(filePath[0])
  107. self.UIInitDocument()
  108. self.updatePreview()
  109. def menuFileSaveAction(self):
  110. self.updateDocument()
  111. if not (hasattr(self, 'currentFilePath') and self.currentFilePath):
  112. filePath = QFileDialog.getSaveFileName(self.window.tabWidget, 'Save file', str(os.path.expanduser("~")), "Chordsheet ML files (*.xml *.cml)")
  113. self.currentFilePath = filePath[0]
  114. self.doc.saveXML(self.currentFilePath)
  115. def menuFileSaveAsAction(self):
  116. self.updateDocument()
  117. filePath = QFileDialog.getSaveFileName(self.window.tabWidget, 'Save file', str(os.path.expanduser("~")), "Chordsheet ML files (*.xml *.cml)")
  118. if filePath[0]:
  119. self.currentFilePath = filePath[0]
  120. self.doc.saveXML(self.currentFilePath)
  121. def menuFileSavePDFAction(self):
  122. self.updateDocument()
  123. self.updatePreview()
  124. filePath = QFileDialog.getSaveFileName(self.window.tabWidget, 'Save file', str(os.path.expanduser("~")), "PDF files (*.pdf)")
  125. if filePath[0]:
  126. savePDF(d, s, filePath[0])
  127. def menuFilePrintAction(self):
  128. if sys.platform == "darwin":
  129. pass
  130. # subprocess.call()
  131. else:
  132. pass
  133. def menuFileCloseAction(self):
  134. pass
  135. def guitarVoicingAction(self):
  136. gdialog = GuitarDialog()
  137. voicing = gdialog.getVoicing()
  138. if voicing:
  139. self.window.guitarVoicingLineEdit.setText(voicing)
  140. def clearChordLineEdits(self):
  141. self.window.chordNameLineEdit.clear()
  142. self.window.guitarVoicingLineEdit.clear()
  143. self.window.chordNameLineEdit.repaint() # necessary on Mojave with PyInstaller (or previous contents will be shown)
  144. self.window.guitarVoicingLineEdit.clear()
  145. def updateChordDict(self):
  146. self.chordDict = {c.name:c for c in self.doc.chordList}
  147. self.window.blockChordComboBox.clear()
  148. self.window.blockChordComboBox.addItems(list(self.chordDict.keys()))
  149. def removeChordAction(self):
  150. self.updateChords()
  151. row = self.window.chordTableView.selectionModel().currentIndex().row()
  152. self.doc.chordList.pop(row)
  153. self.window.chordTableView.populate(self.doc.chordList)
  154. self.clearChordLineEdits()
  155. self.updateChordDict()
  156. def addChordAction(self):
  157. self.updateChords()
  158. self.doc.chordList.append(Chord(parseName(self.window.chordNameLineEdit.text())))
  159. if self.window.guitarVoicingLineEdit.text():
  160. setattr(self.doc.chordList[-1], 'guitar', parseFingering(self.window.guitarVoicingLineEdit.text(), 'guitar'))
  161. self.window.chordTableView.populate(self.doc.chordList)
  162. self.clearChordLineEdits()
  163. self.updateChordDict()
  164. def updateChordAction(self):
  165. if self.window.chordTableView.selectionModel().hasSelection():
  166. self.updateChords()
  167. row = self.window.chordTableView.selectionModel().currentIndex().row()
  168. self.doc.chordList[row] = Chord(parseName(self.window.chordNameLineEdit.text()))
  169. if self.window.guitarVoicingLineEdit.text():
  170. setattr(self.doc.chordList[row], 'guitar', parseFingering(self.window.guitarVoicingLineEdit.text(), 'guitar'))
  171. self.window.chordTableView.populate(self.doc.chordList)
  172. self.clearChordLineEdits()
  173. self.updateChordDict()
  174. def clearBlockLineEdits(self):
  175. self.window.blockLengthLineEdit.clear()
  176. self.window.blockNotesLineEdit.clear()
  177. self.window.blockLengthLineEdit.repaint() # necessary on Mojave with PyInstaller (or previous contents will be shown)
  178. self.window.blockNotesLineEdit.repaint()
  179. def removeBlockAction(self):
  180. self.updateBlocks()
  181. row = self.window.blockTableView.selectionModel().currentIndex().row()
  182. self.doc.blockList.pop(row)
  183. self.window.blockTableView.populate(self.doc.blockList)
  184. def addBlockAction(self):
  185. self.updateBlocks()
  186. self.doc.blockList.append(Block(self.window.blockLengthLineEdit.text(),
  187. chord = self.chordDict[self.window.blockChordComboBox.currentText()],
  188. notes = (self.window.blockNotesLineEdit.text() if not "" else None)))
  189. self.window.blockTableView.populate(self.doc.blockList)
  190. self.clearBlockLineEdits()
  191. def updateBlockAction(self):
  192. if self.window.blockTableView.selectionModel().hasSelection():
  193. self.updateBlocks()
  194. row = self.window.blockTableView.selectionModel().currentIndex().row()
  195. self.doc.blockList[row] = (Block(self.window.blockLengthLineEdit.text(),
  196. chord = self.chordDict[self.window.blockChordComboBox.currentText()],
  197. notes = (self.window.blockNotesLineEdit.text() if not "" else None)))
  198. self.window.blockTableView.populate(self.doc.blockList)
  199. self.clearBlockLineEdits()
  200. def generateAction(self):
  201. self.updateDocument()
  202. self.updatePreview()
  203. def updatePreview(self):
  204. self.currentPreview = io.BytesIO()
  205. savePDF(self.doc, self.style, self.currentPreview)
  206. pdfView = fitz.Document(stream=self.currentPreview, filetype='pdf')
  207. pix = pdfView[0].getPixmap(alpha = False)
  208. fmt = QImage.Format_RGB888
  209. qtimg = QImage(pix.samples, pix.width, pix.height, pix.stride, fmt)
  210. self.window.imageLabel.setPixmap(QPixmap.fromImage(qtimg))
  211. self.window.imageLabel.repaint() # necessary on Mojave with PyInstaller (or previous contents will be shown)
  212. def updateChords(self):
  213. chordTableList = []
  214. for i in range(self.window.chordTableView.model.rowCount()):
  215. chordTableList.append(Chord(parseName(self.window.chordTableView.model.item(i, 0).text()))),
  216. if self.window.chordTableView.model.item(i, 1).text():
  217. chordTableList[-1].guitar = parseFingering(self.window.chordTableView.model.item(i, 1).text(), 'guitar')
  218. self.doc.chordList = chordTableList
  219. def updateBlocks(self):
  220. blockTableList = []
  221. for i in range(self.window.blockTableView.model.rowCount()):
  222. blockLength = int(self.window.blockTableView.model.item(i, 1).text())
  223. blockChordName = parseName(self.window.blockTableView.model.item(i, 0).text())
  224. if blockChordName:
  225. blockChord = None
  226. for c in self.doc.chordList:
  227. if c.name == blockChordName:
  228. blockChord = c
  229. break
  230. if blockChord is None:
  231. exit("Chord {c} does not match any chord in {l}.".format(c=blockChordName, l=self.doc.chordList))
  232. else:
  233. blockChord = None
  234. blockNotes = self.window.blockTableView.model.item(i, 2).text() if self.window.blockTableView.model.item(i, 2).text() else None
  235. blockTableList.append(Block(blockLength, chord=blockChord, notes=blockNotes))
  236. self.doc.blockList = blockTableList
  237. def updateDocument(self):
  238. self.doc.title = self.window.titleLineEdit.text() # Title can be empty string but not None
  239. self.doc.composer = (self.window.composerLineEdit.text() if self.window.composerLineEdit.text() else None)
  240. self.doc.arranger = (self.window.arrangerLineEdit.text() if self.window.arrangerLineEdit.text() else None)
  241. self.doc.timeSignature = int(self.window.timeSignatureSpinBox.value())
  242. self.style.pageSize = pageSizeDict[self.pageSizeSelected]
  243. self.style.unit = unitDict[self.unitSelected]
  244. self.style.leftMargin = int(self.window.leftMarginLineEdit.text())
  245. self.style.topMargin = int(self.window.topMarginLineEdit.text())
  246. self.style.lineSpacing = float(self.window.lineSpacingDoubleSpinBox.value())
  247. self.updateChords()
  248. self.updateBlocks()
  249. self.style.font = ('FreeSans' if self.style.useIncludedFont else 'HelveticaNeue')
  250. # something for the font box here
  251. class GuitarDialog(QDialog):
  252. def __init__(self):
  253. super().__init__()
  254. self.UIFileLoader(str(os.path.join(scriptDir, 'ui','guitardialog.ui')))
  255. def UIFileLoader(self, ui_file):
  256. ui_file = QFile(ui_file)
  257. ui_file.open(QFile.ReadOnly)
  258. self.dialog = uic.loadUi(ui_file)
  259. ui_file.close()
  260. def getVoicing(self):
  261. if self.dialog.exec_() == QDialog.Accepted:
  262. result = [self.dialog.ELineEdit.text(),
  263. self.dialog.ALineEdit.text(),
  264. self.dialog.DLineEdit.text(),
  265. self.dialog.GLineEdit.text(),
  266. self.dialog.BLineEdit.text(),
  267. self.dialog.eLineEdit.text()]
  268. resultJoined = ",".join(result)
  269. return resultJoined
  270. else:
  271. return None
  272. if __name__ == '__main__':
  273. app = QApplication(sys.argv)
  274. d = Document()
  275. s = Style()
  276. w = DocumentWindow(d, s)
  277. w.window.show()
  278. sys.exit(app.exec_())