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.

629 lines
22KB

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