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.

617 lines
22KB

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