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.

598 lines
21KB

  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Carla plugin host (plugin UI)
  4. # Copyright (C) 2013-2016 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 GPL.txt file
  17. # ------------------------------------------------------------------------------------------------------------
  18. # Imports (Config)
  19. from carla_config import *
  20. # ------------------------------------------------------------------------------------------------------------
  21. # Imports (Global)
  22. if config_UseQt5:
  23. from PyQt5.QtGui import QKeySequence
  24. from PyQt5.QtWidgets import QHBoxLayout
  25. else:
  26. from PyQt4.QtGui import QHBoxLayout, QKeySequence
  27. # ------------------------------------------------------------------------------------------------------------
  28. # Imports (Custom Stuff)
  29. from carla_host import *
  30. from externalui import ExternalUI
  31. # ------------------------------------------------------------------------------------------------------------
  32. # Host Plugin object
  33. class PluginHost(CarlaHostQtPlugin):
  34. def __init__(self):
  35. CarlaHostQtPlugin.__init__(self)
  36. if False:
  37. # kdevelop likes this :)
  38. self.fExternalUI = ExternalUI()
  39. # ---------------------------------------------------------------
  40. self.fExternalUI = None
  41. # -------------------------------------------------------------------
  42. def setExternalUI(self, extUI):
  43. self.fExternalUI = extUI
  44. def sendMsg(self, lines):
  45. if self.fExternalUI is None:
  46. return False
  47. self.fExternalUI.send(lines)
  48. return True
  49. # -------------------------------------------------------------------
  50. def engine_init(self, driverName, clientName):
  51. return True
  52. def engine_close(self):
  53. return True
  54. def engine_idle(self):
  55. self.fExternalUI.idleExternalUI()
  56. def is_engine_running(self):
  57. return self.fExternalUI.isRunning()
  58. def set_engine_about_to_close(self):
  59. return True
  60. # ------------------------------------------------------------------------------------------------------------
  61. # Main Window
  62. class CarlaMiniW(ExternalUI, HostWindow):
  63. def __init__(self, host, parent=None):
  64. ExternalUI.__init__(self)
  65. HostWindow.__init__(self, host, sys.argv[0].lower().endswith("/carla-plugin-patchbay"), parent)
  66. self.host = host
  67. if False:
  68. # kdevelop likes this :)
  69. host = PluginHost()
  70. self.host = host
  71. host.setExternalUI(self)
  72. self.fFirstInit = True
  73. self.setWindowTitle(self.fUiName)
  74. self.ready()
  75. # -------------------------------------------------------------------
  76. # ExternalUI Callbacks
  77. def uiShow(self):
  78. if self.parent() is not None:
  79. return
  80. self.show()
  81. def uiFocus(self):
  82. if self.parent() is not None:
  83. return
  84. self.setWindowState((self.windowState() & ~Qt.WindowMinimized) | Qt.WindowActive)
  85. self.show()
  86. self.raise_()
  87. self.activateWindow()
  88. def uiHide(self):
  89. if self.parent() is not None:
  90. return
  91. self.hide()
  92. def uiQuit(self):
  93. self.closeExternalUI()
  94. self.close()
  95. if self != gui:
  96. gui.close()
  97. app.quit()
  98. def uiTitleChanged(self, uiTitle):
  99. self.setWindowTitle(uiTitle)
  100. # -------------------------------------------------------------------
  101. # Qt events
  102. def closeEvent(self, event):
  103. self.closeExternalUI()
  104. HostWindow.closeEvent(self, event)
  105. # there might be other qt windows open which will block carla-plugin from quitting
  106. app.quit()
  107. # -------------------------------------------------------------------
  108. # Custom callback
  109. def msgCallback(self, msg):
  110. try:
  111. self.msgCallback2(msg)
  112. except:
  113. print("msgCallback error, skipped for", msg)
  114. def msgCallback2(self, msg):
  115. msg = charPtrToString(msg)
  116. #if not msg:
  117. #return
  118. if msg.startswith("PEAKS_"):
  119. pluginId = int(msg.replace("PEAKS_", ""))
  120. in1, in2, out1, out2 = [float(i) for i in self.readlineblock().split(":")]
  121. self.host._set_peaks(pluginId, in1, in2, out1, out2)
  122. elif msg.startswith("PARAMVAL_"):
  123. pluginId, paramId = [int(i) for i in msg.replace("PARAMVAL_", "").split(":")]
  124. paramValue = float(self.readlineblock())
  125. if paramId < 0:
  126. self.host._set_internalValue(pluginId, paramId, paramValue)
  127. else:
  128. self.host._set_parameterValue(pluginId, paramId, paramValue)
  129. elif msg.startswith("ENGINE_CALLBACK_"):
  130. action = int(msg.replace("ENGINE_CALLBACK_", ""))
  131. pluginId = int(self.readlineblock())
  132. value1 = int(self.readlineblock())
  133. value2 = int(self.readlineblock())
  134. value3 = float(self.readlineblock())
  135. valueStr = self.readlineblock().replace("\r", "\n")
  136. if action == ENGINE_CALLBACK_PLUGIN_RENAMED:
  137. self.host._set_pluginName(pluginId, valueStr)
  138. elif action == ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED:
  139. if value1 < 0:
  140. self.host._set_internalValue(pluginId, value1, value3)
  141. else:
  142. self.host._set_parameterValue(pluginId, value1, value3)
  143. elif action == ENGINE_CALLBACK_PARAMETER_DEFAULT_CHANGED:
  144. self.host._set_parameterDefault(pluginId, value1, value3)
  145. elif action == ENGINE_CALLBACK_PARAMETER_MIDI_CC_CHANGED:
  146. self.host._set_parameterMidiCC(pluginId, value1, value2)
  147. elif action == ENGINE_CALLBACK_PARAMETER_MIDI_CHANNEL_CHANGED:
  148. self.host._set_parameterMidiChannel(pluginId, value1, value2)
  149. elif action == ENGINE_CALLBACK_PROGRAM_CHANGED:
  150. self.host._set_currentProgram(pluginId, value1)
  151. elif action == ENGINE_CALLBACK_MIDI_PROGRAM_CHANGED:
  152. self.host._set_currentMidiProgram(pluginId, value1)
  153. engineCallback(self.host, action, pluginId, value1, value2, value3, valueStr)
  154. elif msg.startswith("ENGINE_OPTION_"):
  155. option = int(msg.replace("ENGINE_OPTION_", ""))
  156. forced = bool(self.readlineblock() == "true")
  157. value = self.readlineblock()
  158. if self.fFirstInit and not forced:
  159. return
  160. if option == ENGINE_OPTION_PROCESS_MODE:
  161. self.host.processMode = int(value)
  162. elif option == ENGINE_OPTION_TRANSPORT_MODE:
  163. self.host.transportMode = int(value)
  164. elif option == ENGINE_OPTION_FORCE_STEREO:
  165. self.host.forceStereo = bool(value == "true")
  166. elif option == ENGINE_OPTION_PREFER_PLUGIN_BRIDGES:
  167. self.host.preferPluginBridges = bool(value == "true")
  168. elif option == ENGINE_OPTION_PREFER_UI_BRIDGES:
  169. self.host.preferUIBridges = bool(value == "true")
  170. elif option == ENGINE_OPTION_UIS_ALWAYS_ON_TOP:
  171. self.host.uisAlwaysOnTop = bool(value == "true")
  172. elif option == ENGINE_OPTION_MAX_PARAMETERS:
  173. self.host.maxParameters = int(value)
  174. elif option == ENGINE_OPTION_UI_BRIDGES_TIMEOUT:
  175. self.host.uiBridgesTimeout = int(value)
  176. elif option == ENGINE_OPTION_PATH_BINARIES:
  177. self.host.pathBinaries = value
  178. elif option == ENGINE_OPTION_PATH_RESOURCES:
  179. self.host.pathResources = value
  180. elif msg.startswith("PLUGIN_INFO_"):
  181. pluginId = int(msg.replace("PLUGIN_INFO_", ""))
  182. self.host._add(pluginId)
  183. type_, category, hints, uniqueId, optsAvail, optsEnabled = [int(i) for i in self.readlineblock().split(":")]
  184. filename = self.readlineblock().replace("\r", "\n")
  185. name = self.readlineblock().replace("\r", "\n")
  186. iconName = self.readlineblock().replace("\r", "\n")
  187. realName = self.readlineblock().replace("\r", "\n")
  188. label = self.readlineblock().replace("\r", "\n")
  189. maker = self.readlineblock().replace("\r", "\n")
  190. copyright = self.readlineblock().replace("\r", "\n")
  191. pinfo = {
  192. 'type': type_,
  193. 'category': category,
  194. 'hints': hints,
  195. 'optionsAvailable': optsAvail,
  196. 'optionsEnabled': optsEnabled,
  197. 'filename': filename,
  198. 'name': name,
  199. 'label': label,
  200. 'maker': maker,
  201. 'copyright': copyright,
  202. 'iconName': iconName,
  203. 'patchbayClientId': 0,
  204. 'uniqueId': uniqueId
  205. }
  206. self.host._set_pluginInfo(pluginId, pinfo)
  207. self.host._set_pluginRealName(pluginId, realName)
  208. elif msg.startswith("AUDIO_COUNT_"):
  209. pluginId, ins, outs = [int(i) for i in msg.replace("AUDIO_COUNT_", "").split(":")]
  210. self.host._set_audioCountInfo(pluginId, {'ins': ins, 'outs': outs})
  211. elif msg.startswith("MIDI_COUNT_"):
  212. pluginId, ins, outs = [int(i) for i in msg.replace("MIDI_COUNT_", "").split(":")]
  213. self.host._set_midiCountInfo(pluginId, {'ins': ins, 'outs': outs})
  214. elif msg.startswith("PARAMETER_COUNT_"):
  215. pluginId, ins, outs, count = [int(i) for i in msg.replace("PARAMETER_COUNT_", "").split(":")]
  216. self.host._set_parameterCountInfo(pluginId, count, {'ins': ins, 'outs': outs})
  217. elif msg.startswith("PARAMETER_DATA_"):
  218. pluginId, paramId = [int(i) for i in msg.replace("PARAMETER_DATA_", "").split(":")]
  219. paramType, paramHints, midiChannel, midiCC = [int(i) for i in self.readlineblock().split(":")]
  220. paramName = self.readlineblock().replace("\r", "\n")
  221. paramUnit = self.readlineblock().replace("\r", "\n")
  222. paramInfo = {
  223. 'name': paramName,
  224. 'symbol': "",
  225. 'unit': paramUnit,
  226. 'scalePointCount': 0,
  227. }
  228. self.host._set_parameterInfo(pluginId, paramId, paramInfo)
  229. paramData = {
  230. 'type': paramType,
  231. 'hints': paramHints,
  232. 'index': paramId,
  233. 'rindex': -1,
  234. 'midiCC': midiCC,
  235. 'midiChannel': midiChannel
  236. }
  237. self.host._set_parameterData(pluginId, paramId, paramData)
  238. elif msg.startswith("PARAMETER_RANGES_"):
  239. pluginId, paramId = [int(i) for i in msg.replace("PARAMETER_RANGES_", "").split(":")]
  240. def_, min_, max_, step, stepSmall, stepLarge = [float(i) for i in self.readlineblock().split(":")]
  241. paramRanges = {
  242. 'def': def_,
  243. 'min': min_,
  244. 'max': max_,
  245. 'step': step,
  246. 'stepSmall': stepSmall,
  247. 'stepLarge': stepLarge
  248. }
  249. self.host._set_parameterRanges(pluginId, paramId, paramRanges)
  250. elif msg.startswith("PROGRAM_COUNT_"):
  251. pluginId, count, current = [int(i) for i in msg.replace("PROGRAM_COUNT_", "").split(":")]
  252. self.host._set_programCount(pluginId, count)
  253. self.host._set_currentProgram(pluginId, current)
  254. elif msg.startswith("PROGRAM_NAME_"):
  255. pluginId, progId = [int(i) for i in msg.replace("PROGRAM_NAME_", "").split(":")]
  256. progName = self.readlineblock().replace("\r", "\n")
  257. self.host._set_programName(pluginId, progId, progName)
  258. elif msg.startswith("MIDI_PROGRAM_COUNT_"):
  259. pluginId, count, current = [int(i) for i in msg.replace("MIDI_PROGRAM_COUNT_", "").split(":")]
  260. self.host._set_midiProgramCount(pluginId, count)
  261. self.host._set_currentMidiProgram(pluginId, current)
  262. elif msg.startswith("MIDI_PROGRAM_DATA_"):
  263. pluginId, midiProgId = [int(i) for i in msg.replace("MIDI_PROGRAM_DATA_", "").split(":")]
  264. bank, program = [int(i) for i in self.readlineblock().split(":")]
  265. name = self.readlineblock().replace("\r", "\n")
  266. self.host._set_midiProgramData(pluginId, midiProgId, {'bank': bank, 'program': program, 'name': name})
  267. elif msg.startswith("CUSTOM_DATA_COUNT_"):
  268. pluginId, count = [int(i) for i in msg.replace("CUSTOM_DATA_COUNT_", "").split(":")]
  269. self.host._set_customDataCount(pluginId, count)
  270. elif msg.startswith("CUSTOM_DATA_"):
  271. pluginId, customDataId = [int(i) for i in msg.replace("CUSTOM_DATA_", "").split(":")]
  272. type_ = self.readlineblock().replace("\r", "\n")
  273. key = self.readlineblock().replace("\r", "\n")
  274. value = self.readlineblock().replace("\r", "\n")
  275. self.host._set_customData(pluginId, customDataId, {'type': type_, 'key': key, 'value': value})
  276. elif msg == "osc-urls":
  277. tcp = self.readlineblock().replace("\r", "\n")
  278. udp = self.readlineblock().replace("\r", "\n")
  279. self.host.fOscTCP = tcp
  280. self.host.fOscUDP = udp
  281. elif msg == "max-plugin-number":
  282. maxnum = int(self.readlineblock())
  283. self.host.fMaxPluginNumber = maxnum
  284. elif msg == "buffer-size":
  285. bufsize = int(self.readlineblock())
  286. self.host.fBufferSize = bufsize
  287. elif msg == "sample-rate":
  288. srate = float(self.readlineblock())
  289. self.host.fSampleRate = srate
  290. elif msg == "transport":
  291. playing = bool(self.readlineblock() == "true")
  292. frame, bar, beat, tick = [int(i) for i in self.readlineblock().split(":")]
  293. bpm = float(self.readlineblock())
  294. self.host._set_transport(playing, frame, bar, beat, tick, bpm)
  295. elif msg == "error":
  296. error = self.readlineblock().replace("\r", "\n")
  297. engineCallback(self.host, ENGINE_CALLBACK_ERROR, 0, 0, 0, 0.0, error)
  298. elif msg == "show":
  299. self.fFirstInit = False
  300. self.uiShow()
  301. elif msg == "focus":
  302. self.uiFocus()
  303. elif msg == "hide":
  304. self.uiHide()
  305. elif msg == "quit":
  306. self.fQuitReceived = True
  307. self.uiQuit()
  308. elif msg == "uiTitle":
  309. uiTitle = self.readlineblock().replace("\r", "\n")
  310. self.uiTitleChanged(uiTitle)
  311. else:
  312. print("unknown message: \"" + msg + "\"")
  313. # ------------------------------------------------------------------------------------------------------------
  314. # Embed Widget
  315. if LINUX and config_UseQt5:
  316. from PyQt5.QtGui import QMouseEvent
  317. class QEmbedWidget(QWidget):
  318. def __init__(self):
  319. QWidget.__init__(self)
  320. self.setAttribute(Qt.WA_LayoutUsesWidgetRect)
  321. self.fPos = (0, 0)
  322. self.move(0, 0)
  323. self.fWinId = 0
  324. def eventFilter(self, obj, ev):
  325. if isinstance(ev, QMouseEvent):
  326. pos = gCarla.utils.x11_get_window_pos(self.fWinId)
  327. if self.fPos != pos:
  328. self.fPos = pos
  329. self.move(pos[0], pos[1])
  330. gCarla.utils.x11_move_window(self.fWinId, 0, 0)
  331. return False
  332. def finalSetup(self, gui, winId):
  333. self.fWinId = int(self.winId())
  334. gui.ui.menubar.installEventFilter(self)
  335. gCarla.utils.x11_reparent_window(self.fWinId, winId)
  336. self.show()
  337. elif LINUX and not config_UseQt5:
  338. from PyQt4.QtGui import QX11EmbedWidget
  339. class QEmbedWidget(QX11EmbedWidget):
  340. def __init__(self):
  341. QX11EmbedWidget.__init__(self)
  342. def finalSetup(self, gui, winId):
  343. self.embedInto(winId)
  344. self.show()
  345. else:
  346. class QEmbedWidget(object):
  347. def __init__(self, winId, width, height):
  348. print("Cannot use embed UI with this configuration")
  349. raise Exception
  350. # ------------------------------------------------------------------------------------------------------------
  351. # Embed plugin UI
  352. class CarlaEmbedW(QEmbedWidget):
  353. def __init__(self, host, winId):
  354. QEmbedWidget.__init__(self)
  355. self.setFixedSize(740, 512)
  356. self.host = host
  357. self.fWinId = winId
  358. self.fLayout = QVBoxLayout(self)
  359. self.fLayout.setContentsMargins(0, 0, 0, 0)
  360. self.fLayout.setSpacing(0)
  361. self.setLayout(self.fLayout)
  362. self.gui = CarlaMiniW(host, self)
  363. self.gui.hide()
  364. self.gui.ui.act_file_quit.setEnabled(False)
  365. self.gui.ui.act_file_quit.setVisible(False)
  366. self.fShortcutActions = []
  367. self.addShortcutActions(self.gui.ui.menu_File.actions())
  368. self.addShortcutActions(self.gui.ui.menu_Plugin.actions())
  369. self.addShortcutActions(self.gui.ui.menu_PluginMacros.actions())
  370. self.addShortcutActions(self.gui.ui.menu_Settings.actions())
  371. self.addShortcutActions(self.gui.ui.menu_Help.actions())
  372. if self.host.processMode == ENGINE_PROCESS_MODE_PATCHBAY:
  373. self.addShortcutActions(self.gui.ui.menu_Canvas.actions())
  374. self.addShortcutActions(self.gui.ui.menu_Canvas_Zoom.actions())
  375. self.addWidget(self.gui.ui.menubar)
  376. self.addLine()
  377. self.addWidget(self.gui.ui.toolBar)
  378. if self.host.processMode == ENGINE_PROCESS_MODE_PATCHBAY:
  379. self.addLine()
  380. self.addWidget(self.gui.centralWidget())
  381. self.finalSetup(self.gui, winId)
  382. self.gui.send(["ready", int(self.winId())])
  383. def addShortcutActions(self, actions):
  384. for action in actions:
  385. if not action.shortcut().isEmpty():
  386. self.fShortcutActions.append(action)
  387. def addWidget(self, widget):
  388. widget.setParent(self)
  389. self.fLayout.addWidget(widget)
  390. def addLine(self):
  391. line = QFrame(self)
  392. line.setFrameShadow(QFrame.Sunken)
  393. line.setFrameShape(QFrame.HLine)
  394. line.setLineWidth(0)
  395. line.setMidLineWidth(1)
  396. self.fLayout.addWidget(line)
  397. def keyPressEvent(self, event):
  398. modifiers = event.modifiers()
  399. modifiersStr = ""
  400. if modifiers & Qt.ShiftModifier:
  401. modifiersStr += "Shift+"
  402. if modifiers & Qt.ControlModifier:
  403. modifiersStr += "Ctrl+"
  404. if modifiers & Qt.AltModifier:
  405. modifiersStr += "Alt+"
  406. if modifiers & Qt.MetaModifier:
  407. modifiersStr += "Meta+"
  408. keyStr = QKeySequence(event.key()).toString()
  409. keySeq = QKeySequence(modifiersStr + keyStr)
  410. for action in self.fShortcutActions:
  411. if not action.isEnabled():
  412. continue
  413. if keySeq.matches(action.shortcut()) != QKeySequence.ExactMatch:
  414. continue
  415. event.accept()
  416. action.trigger()
  417. return
  418. QEmbedWidget.keyPressEvent(self, event)
  419. def showEvent(self, event):
  420. QEmbedWidget.showEvent(self, event)
  421. # set our gui as parent for all plugins UIs
  422. if self.host.manageUIs:
  423. winIdStr = "%x" % self.fWinId
  424. self.host.set_engine_option(ENGINE_OPTION_FRONTEND_WIN_ID, 0, winIdStr)
  425. def hideEvent(self, event):
  426. # disable parent
  427. self.host.set_engine_option(ENGINE_OPTION_FRONTEND_WIN_ID, 0, "0")
  428. QEmbedWidget.hideEvent(self, event)
  429. def closeEvent(self, event):
  430. self.gui.close()
  431. self.gui.closeExternalUI()
  432. QEmbedWidget.closeEvent(self, event)
  433. # there might be other qt windows open which will block carla-plugin from quitting
  434. app.quit()
  435. # ------------------------------------------------------------------------------------------------------------
  436. # Main
  437. if __name__ == '__main__':
  438. # -------------------------------------------------------------
  439. # App initialization
  440. app = CarlaApplication("Carla2-Plugin")
  441. # -------------------------------------------------------------
  442. # Set-up custom signal handling
  443. setUpSignals()
  444. # -------------------------------------------------------------
  445. # Init host backend
  446. host = initHost("Carla-Plugin", None, False, True, True, PluginHost)
  447. host.processMode = ENGINE_PROCESS_MODE_PATCHBAY if sys.argv[0].lower().endswith("/carla-plugin-patchbay") else ENGINE_PROCESS_MODE_CONTINUOUS_RACK
  448. host.processModeForced = True
  449. host.nextProcessMode = host.processMode
  450. loadHostSettings(host)
  451. # -------------------------------------------------------------
  452. # Create GUI
  453. try:
  454. winId = int(os.getenv("CARLA_PLUGIN_EMBED_WINID"))
  455. except:
  456. winId = 0
  457. gCarla.utils.setenv("CARLA_PLUGIN_EMBED_WINID", "0")
  458. if LINUX and winId != 0:
  459. gui = CarlaEmbedW(host, winId)
  460. else:
  461. gui = CarlaMiniW(host)
  462. # -------------------------------------------------------------
  463. # App-Loop
  464. app.exit_exec()