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.

607 lines
21KB

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