Audio plugin host https://kx.studio/carla
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.

647 lines
19KB

  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Pixmap Keyboard, a custom Qt widget
  4. # Copyright (C) 2011-2022 Filipe Coelho <falktx@falktx.com>
  5. #
  6. # This program is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU General Public License as
  8. # published by the Free Software Foundation; either version 2 of
  9. # the License, or any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # For a full copy of the GNU General Public License see the doc/GPL.txt file.
  17. # ---------------------------------------------------------------------------------------------------------------------
  18. # Imports (Global)
  19. from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QPointF, QRectF, QTimer, QSize
  20. from PyQt5.QtGui import QColor, QPainter, QPixmap
  21. from PyQt5.QtWidgets import QActionGroup, QMenu, QScrollArea, QWidget
  22. # ---------------------------------------------------------------------------------------------------------------------
  23. # Imports (Carla)
  24. from utils import QSafeSettings
  25. # ---------------------------------------------------------------------------------------------------------------------
  26. kMidiKey2RectMapHorizontal = [
  27. QRectF(0, 0, 24, 57), # C
  28. QRectF(14, 0, 15, 33), # C#
  29. QRectF(24, 0, 24, 57), # D
  30. QRectF(42, 0, 15, 33), # D#
  31. QRectF(48, 0, 24, 57), # E
  32. QRectF(72, 0, 24, 57), # F
  33. QRectF(84, 0, 15, 33), # F#
  34. QRectF(96, 0, 24, 57), # G
  35. QRectF(112, 0, 15, 33), # G#
  36. QRectF(120, 0, 24, 57), # A
  37. QRectF(140, 0, 15, 33), # A#
  38. QRectF(144, 0, 24, 57), # B
  39. ]
  40. kMidiKey2RectMapVertical = [
  41. QRectF(0, 144, 57, 24), # C
  42. QRectF(0, 139, 33, 15), # C#
  43. QRectF(0, 120, 57, 24), # D
  44. QRectF(0, 111, 33, 15), # D#
  45. QRectF(0, 96, 57, 24), # E
  46. QRectF(0, 72, 57, 24), # F
  47. QRectF(0, 69, 33, 15), # F#
  48. QRectF(0, 48, 57, 24), # G
  49. QRectF(0, 41, 33, 15), # G#
  50. QRectF(0, 24, 57, 24), # A
  51. QRectF(0, 13, 33, 15), # A#
  52. QRectF(0, 0, 57, 24), # B
  53. ]
  54. kPcKeys_qwerty = [
  55. # 1st octave
  56. str(Qt.Key_Z),
  57. str(Qt.Key_S),
  58. str(Qt.Key_X),
  59. str(Qt.Key_D),
  60. str(Qt.Key_C),
  61. str(Qt.Key_V),
  62. str(Qt.Key_G),
  63. str(Qt.Key_B),
  64. str(Qt.Key_H),
  65. str(Qt.Key_N),
  66. str(Qt.Key_J),
  67. str(Qt.Key_M),
  68. # 2nd octave
  69. str(Qt.Key_Q),
  70. str(Qt.Key_2),
  71. str(Qt.Key_W),
  72. str(Qt.Key_3),
  73. str(Qt.Key_E),
  74. str(Qt.Key_R),
  75. str(Qt.Key_5),
  76. str(Qt.Key_T),
  77. str(Qt.Key_6),
  78. str(Qt.Key_Y),
  79. str(Qt.Key_7),
  80. str(Qt.Key_U),
  81. # 3rd octave
  82. str(Qt.Key_I),
  83. str(Qt.Key_9),
  84. str(Qt.Key_O),
  85. str(Qt.Key_0),
  86. str(Qt.Key_P),
  87. ]
  88. kPcKeys_qwertz = [
  89. # 1st octave
  90. str(Qt.Key_Y),
  91. str(Qt.Key_S),
  92. str(Qt.Key_X),
  93. str(Qt.Key_D),
  94. str(Qt.Key_C),
  95. str(Qt.Key_V),
  96. str(Qt.Key_G),
  97. str(Qt.Key_B),
  98. str(Qt.Key_H),
  99. str(Qt.Key_N),
  100. str(Qt.Key_J),
  101. str(Qt.Key_M),
  102. # 2nd octave
  103. str(Qt.Key_Q),
  104. str(Qt.Key_2),
  105. str(Qt.Key_W),
  106. str(Qt.Key_3),
  107. str(Qt.Key_E),
  108. str(Qt.Key_R),
  109. str(Qt.Key_5),
  110. str(Qt.Key_T),
  111. str(Qt.Key_6),
  112. str(Qt.Key_Z),
  113. str(Qt.Key_7),
  114. str(Qt.Key_U),
  115. # 3rd octave
  116. str(Qt.Key_I),
  117. str(Qt.Key_9),
  118. str(Qt.Key_O),
  119. str(Qt.Key_0),
  120. str(Qt.Key_P),
  121. ]
  122. kPcKeys_azerty = [
  123. # 1st octave
  124. str(Qt.Key_W),
  125. str(Qt.Key_S),
  126. str(Qt.Key_X),
  127. str(Qt.Key_D),
  128. str(Qt.Key_C),
  129. str(Qt.Key_V),
  130. str(Qt.Key_G),
  131. str(Qt.Key_B),
  132. str(Qt.Key_H),
  133. str(Qt.Key_N),
  134. str(Qt.Key_J),
  135. str(Qt.Key_Comma),
  136. # 2nd octave
  137. str(Qt.Key_A),
  138. str(Qt.Key_Eacute),
  139. str(Qt.Key_Z),
  140. str(Qt.Key_QuoteDbl),
  141. str(Qt.Key_E),
  142. str(Qt.Key_R),
  143. str(Qt.Key_ParenLeft),
  144. str(Qt.Key_T),
  145. str(Qt.Key_Minus),
  146. str(Qt.Key_Y),
  147. str(Qt.Key_Egrave),
  148. str(Qt.Key_U),
  149. # 3rd octave
  150. str(Qt.Key_I),
  151. str(Qt.Key_Ccedilla),
  152. str(Qt.Key_O),
  153. str(Qt.Key_Agrave),
  154. str(Qt.Key_P),
  155. ]
  156. kPcKeysLayouts = {
  157. 'qwerty': kPcKeys_qwerty,
  158. 'qwertz': kPcKeys_qwertz,
  159. 'azerty': kPcKeys_azerty,
  160. }
  161. kValidColors = ("Blue", "Green", "Orange", "Red")
  162. kBlackNotes = (1, 3, 6, 8, 10)
  163. # ------------------------------------------------------------------------------------------------------------
  164. def _isNoteBlack(note):
  165. baseNote = note % 12
  166. return bool(baseNote in kBlackNotes)
  167. # ------------------------------------------------------------------------------------------------------------
  168. # MIDI Keyboard, using a pixmap for painting
  169. class PixmapKeyboard(QWidget):
  170. # signals
  171. noteOn = pyqtSignal(int)
  172. noteOff = pyqtSignal(int)
  173. notesOn = pyqtSignal()
  174. notesOff = pyqtSignal()
  175. def __init__(self, parent):
  176. QWidget.__init__(self, parent)
  177. self.fEnabledKeys = []
  178. self.fLastMouseNote = -1
  179. self.fStartOctave = 0
  180. self.fPcKeybOffset = 2
  181. self.fInitalizing = True
  182. self.fFont = self.font()
  183. self.fFont.setFamily("Monospace")
  184. self.fFont.setPixelSize(12)
  185. self.fFont.setBold(True)
  186. self.fPixmapNormal = QPixmap(":/bitmaps/kbd_normal.png")
  187. self.fPixmapDown = QPixmap(":/bitmaps/kbd_down-blue.png")
  188. self.fHighlightColor = kValidColors[0]
  189. self.fkPcKeyLayout = "qwerty"
  190. self.fkPcKeys = kPcKeysLayouts["qwerty"]
  191. self.fKey2RectMap = kMidiKey2RectMapHorizontal
  192. self.fWidth = self.fPixmapNormal.width()
  193. self.fHeight = self.fPixmapNormal.height()
  194. self.setCursor(Qt.PointingHandCursor)
  195. self.setStartOctave(0)
  196. self.setOctaves(6)
  197. self.loadSettings()
  198. self.fInitalizing = False
  199. def saveSettings(self):
  200. if self.fInitalizing:
  201. return
  202. settings = QSafeSettings("falkTX", "CarlaKeyboard")
  203. settings.setValue("PcKeyboardLayout", self.fkPcKeyLayout)
  204. settings.setValue("PcKeyboardOffset", self.fPcKeybOffset)
  205. settings.setValue("HighlightColor", self.fHighlightColor)
  206. del settings
  207. def loadSettings(self):
  208. settings = QSafeSettings("falkTX", "CarlaKeyboard")
  209. self.setPcKeyboardLayout(settings.value("PcKeyboardLayout", self.fkPcKeyLayout, str))
  210. self.setPcKeyboardOffset(settings.value("PcKeyboardOffset", self.fPcKeybOffset, int))
  211. self.setColor(settings.value("HighlightColor", self.fHighlightColor, str))
  212. del settings
  213. def allNotesOff(self, sendSignal=True):
  214. self.fEnabledKeys = []
  215. if sendSignal:
  216. self.notesOff.emit()
  217. self.update()
  218. def sendNoteOn(self, note, sendSignal=True):
  219. if 0 <= note <= 127 and note not in self.fEnabledKeys:
  220. self.fEnabledKeys.append(note)
  221. if sendSignal:
  222. self.noteOn.emit(note)
  223. self.update()
  224. if len(self.fEnabledKeys) == 1:
  225. self.notesOn.emit()
  226. def sendNoteOff(self, note, sendSignal=True):
  227. if 0 <= note <= 127 and note in self.fEnabledKeys:
  228. self.fEnabledKeys.remove(note)
  229. if sendSignal:
  230. self.noteOff.emit(note)
  231. self.update()
  232. if len(self.fEnabledKeys) == 0:
  233. self.notesOff.emit()
  234. def setColor(self, color):
  235. if color not in kValidColors:
  236. return
  237. if self.fHighlightColor == color:
  238. return
  239. self.fHighlightColor = color
  240. self.fPixmapDown.load(":/bitmaps/kbd_down-{}.png".format(color.lower()))
  241. self.saveSettings()
  242. def setPcKeyboardLayout(self, layout):
  243. if layout not in kPcKeysLayouts.keys():
  244. return
  245. if self.fkPcKeyLayout == layout:
  246. return
  247. self.fkPcKeyLayout = layout
  248. self.fkPcKeys = kPcKeysLayouts[layout]
  249. self.saveSettings()
  250. def setPcKeyboardOffset(self, offset):
  251. if offset < 0:
  252. offset = 0
  253. elif offset > 9:
  254. offset = 9
  255. if self.fPcKeybOffset == offset:
  256. return
  257. self.fPcKeybOffset = offset
  258. self.saveSettings()
  259. def setOctaves(self, octaves):
  260. if octaves < 1:
  261. octaves = 1
  262. elif octaves > 10:
  263. octaves = 10
  264. self.fOctaves = octaves
  265. self.setMinimumSize(self.fWidth * self.fOctaves, self.fHeight)
  266. self.setMaximumSize(self.fWidth * self.fOctaves, self.fHeight)
  267. def setStartOctave(self, octave):
  268. if octave < 0:
  269. octave = 0
  270. elif octave > 9:
  271. octave = 9
  272. if self.fStartOctave == octave:
  273. return
  274. self.fStartOctave = octave
  275. self.update()
  276. def handleMousePos(self, pos):
  277. if pos.x() < 0 or pos.x() > self.fOctaves * self.fWidth:
  278. return
  279. octave = int(pos.x() / self.fWidth)
  280. keyPos = QPointF(pos.x() % self.fWidth, pos.y())
  281. if self.fKey2RectMap[1].contains(keyPos): # C#
  282. note = 1
  283. elif self.fKey2RectMap[ 3].contains(keyPos): # D#
  284. note = 3
  285. elif self.fKey2RectMap[ 6].contains(keyPos): # F#
  286. note = 6
  287. elif self.fKey2RectMap[ 8].contains(keyPos): # G#
  288. note = 8
  289. elif self.fKey2RectMap[10].contains(keyPos): # A#
  290. note = 10
  291. elif self.fKey2RectMap[ 0].contains(keyPos): # C
  292. note = 0
  293. elif self.fKey2RectMap[ 2].contains(keyPos): # D
  294. note = 2
  295. elif self.fKey2RectMap[ 4].contains(keyPos): # E
  296. note = 4
  297. elif self.fKey2RectMap[ 5].contains(keyPos): # F
  298. note = 5
  299. elif self.fKey2RectMap[ 7].contains(keyPos): # G
  300. note = 7
  301. elif self.fKey2RectMap[ 9].contains(keyPos): # A
  302. note = 9
  303. elif self.fKey2RectMap[11].contains(keyPos): # B
  304. note = 11
  305. else:
  306. note = -1
  307. if note != -1:
  308. note += (self.fStartOctave + octave) * 12
  309. if self.fLastMouseNote != note:
  310. self.sendNoteOff(self.fLastMouseNote)
  311. self.sendNoteOn(note)
  312. elif self.fLastMouseNote != -1:
  313. self.sendNoteOff(self.fLastMouseNote)
  314. self.fLastMouseNote = note
  315. def showOptions(self, event):
  316. event.accept()
  317. menu = QMenu()
  318. menu.addAction(self.tr("Note: restart carla to apply globally")).setEnabled(False)
  319. menu.addAction(self.tr("Color")).setSeparator(True)
  320. groupColor = QActionGroup(menu)
  321. groupLayout = QActionGroup(menu)
  322. actColors = []
  323. actLayouts = []
  324. menu.addAction(self.tr("Highlight color")).setSeparator(True)
  325. for color in kValidColors:
  326. act = menu.addAction(color)
  327. act.setActionGroup(groupColor)
  328. act.setCheckable(True)
  329. if self.fHighlightColor == color:
  330. act.setChecked(True)
  331. actColors.append(act)
  332. menu.addAction(self.tr("PC Keyboard layout")).setSeparator(True)
  333. for pcKeyLayout in kPcKeysLayouts.keys():
  334. act = menu.addAction(pcKeyLayout)
  335. act.setActionGroup(groupLayout)
  336. act.setCheckable(True)
  337. if self.fkPcKeyLayout == pcKeyLayout:
  338. act.setChecked(True)
  339. actLayouts.append(act)
  340. menu.addAction(self.tr("PC Keyboard base octave (%i)" % self.fPcKeybOffset)).setSeparator(True)
  341. actOctaveUp = menu.addAction(self.tr("Octave up"))
  342. actOctaveDown = menu.addAction(self.tr("Octave down"))
  343. if self.fPcKeybOffset == 0:
  344. actOctaveDown.setEnabled(False)
  345. actSelected = menu.exec_(event.screenPos().toPoint())
  346. if not actSelected:
  347. return
  348. if actSelected in actColors:
  349. return self.setColor(actSelected.text())
  350. if actSelected in actLayouts:
  351. return self.setPcKeyboardLayout(actSelected.text())
  352. if actSelected == actOctaveUp:
  353. return self.setPcKeyboardOffset(self.fPcKeybOffset + 1)
  354. if actSelected == actOctaveDown:
  355. return self.setPcKeyboardOffset(self.fPcKeybOffset - 1)
  356. def minimumSizeHint(self):
  357. return QSize(self.fWidth, self.fHeight)
  358. def sizeHint(self):
  359. return QSize(self.fWidth * self.fOctaves, self.fHeight)
  360. def keyPressEvent(self, event):
  361. if not event.isAutoRepeat():
  362. try:
  363. qKey = str(event.key())
  364. index = self.fkPcKeys.index(qKey)
  365. except:
  366. pass
  367. else:
  368. self.sendNoteOn(index+(self.fPcKeybOffset*12))
  369. QWidget.keyPressEvent(self, event)
  370. def keyReleaseEvent(self, event):
  371. if not event.isAutoRepeat():
  372. try:
  373. qKey = str(event.key())
  374. index = self.fkPcKeys.index(qKey)
  375. except:
  376. pass
  377. else:
  378. self.sendNoteOff(index+(self.fPcKeybOffset*12))
  379. QWidget.keyReleaseEvent(self, event)
  380. def mousePressEvent(self, event):
  381. if event.button() == Qt.RightButton:
  382. self.showOptions(event)
  383. else:
  384. self.fLastMouseNote = -1
  385. self.handleMousePos(event.pos())
  386. self.setFocus()
  387. QWidget.mousePressEvent(self, event)
  388. def mouseMoveEvent(self, event):
  389. if event.button() != Qt.RightButton:
  390. self.handleMousePos(event.pos())
  391. QWidget.mouseMoveEvent(self, event)
  392. def mouseReleaseEvent(self, event):
  393. if self.fLastMouseNote != -1:
  394. self.sendNoteOff(self.fLastMouseNote)
  395. self.fLastMouseNote = -1
  396. QWidget.mouseReleaseEvent(self, event)
  397. def paintEvent(self, event):
  398. painter = QPainter(self)
  399. event.accept()
  400. # -------------------------------------------------------------
  401. # Paint clean keys (as background)
  402. for octave in range(self.fOctaves):
  403. target = QRectF(self.fWidth * octave, 0, self.fWidth, self.fHeight)
  404. source = QRectF(0, 0, self.fWidth, self.fHeight)
  405. painter.drawPixmap(target, self.fPixmapNormal, source)
  406. if not self.isEnabled():
  407. painter.setBrush(QColor(0, 0, 0, 150))
  408. painter.setPen(QColor(0, 0, 0, 150))
  409. painter.drawRect(0, 0, self.width(), self.height())
  410. return
  411. # -------------------------------------------------------------
  412. # Paint (white) pressed keys
  413. paintedWhite = False
  414. for note in self.fEnabledKeys:
  415. pos = self._getRectFromMidiNote(note)
  416. if _isNoteBlack(note):
  417. continue
  418. if note < 12:
  419. octave = 0
  420. elif note < 24:
  421. octave = 1
  422. elif note < 36:
  423. octave = 2
  424. elif note < 48:
  425. octave = 3
  426. elif note < 60:
  427. octave = 4
  428. elif note < 72:
  429. octave = 5
  430. elif note < 84:
  431. octave = 6
  432. elif note < 96:
  433. octave = 7
  434. elif note < 108:
  435. octave = 8
  436. elif note < 120:
  437. octave = 9
  438. elif note < 132:
  439. octave = 10
  440. else:
  441. # cannot paint this note
  442. continue
  443. octave -= self.fStartOctave
  444. target = QRectF(pos.x() + (self.fWidth * octave), 0, pos.width(), pos.height())
  445. source = QRectF(pos.x(), 0, pos.width(), pos.height())
  446. paintedWhite = True
  447. painter.drawPixmap(target, self.fPixmapDown, source)
  448. # -------------------------------------------------------------
  449. # Clear white keys border
  450. if paintedWhite:
  451. for octave in range(self.fOctaves):
  452. for note in kBlackNotes:
  453. pos = self._getRectFromMidiNote(note)
  454. target = QRectF(pos.x() + (self.fWidth * octave), 0, pos.width(), pos.height())
  455. source = QRectF(pos.x(), 0, pos.width(), pos.height())
  456. painter.drawPixmap(target, self.fPixmapNormal, source)
  457. # -------------------------------------------------------------
  458. # Paint (black) pressed keys
  459. for note in self.fEnabledKeys:
  460. pos = self._getRectFromMidiNote(note)
  461. if not _isNoteBlack(note):
  462. continue
  463. if note < 12:
  464. octave = 0
  465. elif note < 24:
  466. octave = 1
  467. elif note < 36:
  468. octave = 2
  469. elif note < 48:
  470. octave = 3
  471. elif note < 60:
  472. octave = 4
  473. elif note < 72:
  474. octave = 5
  475. elif note < 84:
  476. octave = 6
  477. elif note < 96:
  478. octave = 7
  479. elif note < 108:
  480. octave = 8
  481. elif note < 120:
  482. octave = 9
  483. elif note < 132:
  484. octave = 10
  485. else:
  486. # cannot paint this note
  487. continue
  488. octave -= self.fStartOctave
  489. target = QRectF(pos.x() + (self.fWidth * octave), 0, pos.width(), pos.height())
  490. source = QRectF(pos.x(), 0, pos.width(), pos.height())
  491. painter.drawPixmap(target, self.fPixmapDown, source)
  492. # Paint C-number note info
  493. painter.setFont(self.fFont)
  494. painter.setPen(Qt.black)
  495. for i in range(self.fOctaves):
  496. octave = self.fStartOctave + i - 1
  497. painter.drawText(i * 168 + (4 if octave == -1 else 3),
  498. 35, 20, 20,
  499. Qt.AlignCenter,
  500. "C{}".format(octave))
  501. def _getRectFromMidiNote(self, note):
  502. baseNote = note % 12
  503. return self.fKey2RectMap[baseNote]
  504. # ---------------------------------------------------------------------------------------------------------------------
  505. # Horizontal scroll area for keyboard
  506. class PixmapKeyboardHArea(QScrollArea):
  507. def __init__(self, parent):
  508. QScrollArea.__init__(self, parent)
  509. self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
  510. self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
  511. self.keyboard = PixmapKeyboard(self)
  512. self.keyboard.setOctaves(10)
  513. self.setWidget(self.keyboard)
  514. self.setEnabled(False)
  515. self.setFixedHeight(int(self.keyboard.height() + self.horizontalScrollBar().height()/2 + 2))
  516. QTimer.singleShot(0, self.slot_initScrollbarValue)
  517. # FIXME use change event
  518. def setEnabled(self, yesNo):
  519. self.keyboard.setEnabled(yesNo)
  520. QScrollArea.setEnabled(self, yesNo)
  521. @pyqtSlot()
  522. def slot_initScrollbarValue(self):
  523. self.horizontalScrollBar().setValue(int(self.horizontalScrollBar().maximum()/2))
  524. # ---------------------------------------------------------------------------------------------------------------------