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.

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