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.

1349 lines
52KB

  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Carla host code
  4. # Copyright (C) 2011-2014 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 doc/GPL.txt file.
  17. # ------------------------------------------------------------------------------------------------------------
  18. # Imports (Config)
  19. from carla_config import *
  20. # ------------------------------------------------------------------------------------------------------------
  21. # Imports (Global)
  22. if config_UseQt5:
  23. from PyQt5.QtCore import qCritical, QModelIndex, QTimer
  24. from PyQt5.QtGui import QPalette
  25. from PyQt5.QtWidgets import QApplication, QFileSystemModel, QListWidgetItem, QMainWindow
  26. else:
  27. from PyQt4.QtCore import qCritical, QModelIndex, QTimer
  28. from PyQt4.QtGui import QApplication, QFileSystemModel, QListWidgetItem, QMainWindow, QPalette
  29. # ------------------------------------------------------------------------------------------------------------
  30. # Imports (Custom)
  31. import ui_carla_host
  32. from carla_database import *
  33. from carla_settings import *
  34. from carla_style import *
  35. from carla_widgets import *
  36. # ------------------------------------------------------------------------------------------------------------
  37. # PatchCanvas defines
  38. CANVAS_ANTIALIASING_SMALL = 1
  39. CANVAS_EYECANDY_SMALL = 1
  40. # ------------------------------------------------------------------------------------------------------------
  41. # Session Management support
  42. LADISH_APP_NAME = os.getenv("LADISH_APP_NAME")
  43. NSM_URL = os.getenv("NSM_URL")
  44. # ------------------------------------------------------------------------------------------------------------
  45. # Dummy widget
  46. class CarlaDummyW(object):
  47. def __init__(self, parent):
  48. object.__init__(self)
  49. # -----------------------------------------------------------------
  50. def getPluginCount(self):
  51. return 0
  52. # -----------------------------------------------------------------
  53. def addPlugin(self, pluginId, isProjectLoading):
  54. pass
  55. def removePlugin(self, pluginId):
  56. pass
  57. def renamePlugin(self, pluginId, newName):
  58. pass
  59. def disablePlugin(self, pluginId, errorMsg):
  60. pass
  61. def removeAllPlugins(self):
  62. pass
  63. # -----------------------------------------------------------------
  64. def engineStarted(self):
  65. pass
  66. def engineStopped(self):
  67. pass
  68. def engineChanged(self):
  69. pass
  70. # -----------------------------------------------------------------
  71. def idleFast(self):
  72. pass
  73. def idleSlow(self):
  74. pass
  75. # -----------------------------------------------------------------
  76. def projectLoadingStarted(self):
  77. pass
  78. def projectLoadingFinished(self):
  79. pass
  80. # -----------------------------------------------------------------
  81. def saveSettings(self, settings):
  82. pass
  83. def showEditDialog(self, pluginId):
  84. pass
  85. # ------------------------------------------------------------------------------------------------------------
  86. # Host Window
  87. class HostWindow(QMainWindow):
  88. # signals
  89. DebugCallback = pyqtSignal(int, int, int, float, str)
  90. PluginAddedCallback = pyqtSignal(int, str)
  91. PluginRemovedCallback = pyqtSignal(int)
  92. PluginRenamedCallback = pyqtSignal(int, str)
  93. PluginUnavailableCallback = pyqtSignal(int, str)
  94. ParameterValueChangedCallback = pyqtSignal(int, int, float)
  95. ParameterDefaultChangedCallback = pyqtSignal(int, int, float)
  96. ParameterMidiCcChangedCallback = pyqtSignal(int, int, int)
  97. ParameterMidiChannelChangedCallback = pyqtSignal(int, int, int)
  98. ProgramChangedCallback = pyqtSignal(int, int)
  99. MidiProgramChangedCallback = pyqtSignal(int, int)
  100. UiStateChangedCallback = pyqtSignal(int, int)
  101. NoteOnCallback = pyqtSignal(int, int, int, int)
  102. NoteOffCallback = pyqtSignal(int, int, int)
  103. UpdateCallback = pyqtSignal(int)
  104. ReloadInfoCallback = pyqtSignal(int)
  105. ReloadParametersCallback = pyqtSignal(int)
  106. ReloadProgramsCallback = pyqtSignal(int)
  107. ReloadAllCallback = pyqtSignal(int)
  108. PatchbayClientAddedCallback = pyqtSignal(int, int, int, str)
  109. PatchbayClientRemovedCallback = pyqtSignal(int)
  110. PatchbayClientRenamedCallback = pyqtSignal(int, str)
  111. PatchbayClientDataChangedCallback = pyqtSignal(int, int, int)
  112. PatchbayPortAddedCallback = pyqtSignal(int, int, int, str)
  113. PatchbayPortRemovedCallback = pyqtSignal(int, int)
  114. PatchbayPortRenamedCallback = pyqtSignal(int, int, str)
  115. PatchbayPortValueChangedCallback = pyqtSignal(int, int, float)
  116. PatchbayConnectionAddedCallback = pyqtSignal(int, int, int, int, int)
  117. PatchbayConnectionRemovedCallback = pyqtSignal(int, int, int)
  118. EngineStartedCallback = pyqtSignal(int, int, str)
  119. EngineStoppedCallback = pyqtSignal()
  120. ProcessModeChangedCallback = pyqtSignal(int)
  121. TransportModeChangedCallback = pyqtSignal(int)
  122. BufferSizeChangedCallback = pyqtSignal(int)
  123. SampleRateChangedCallback = pyqtSignal(float)
  124. InfoCallback = pyqtSignal(str)
  125. ErrorCallback = pyqtSignal(str)
  126. QuitCallback = pyqtSignal()
  127. SIGTERM = pyqtSignal()
  128. SIGUSR1 = pyqtSignal()
  129. def __init__(self, parent):
  130. QMainWindow.__init__(self, parent)
  131. self.ui = ui_carla_host.Ui_CarlaHostW()
  132. self.ui.setupUi(self)
  133. if False:
  134. # kdevelop likes this :)
  135. gCarla.gui = self
  136. gCarla.host = Host("")
  137. self.fContainer = CarlaDummyW(self)
  138. # -------------------------------------------------------------
  139. # Set callback, TODO put somewhere else
  140. if gCarla.host is not None:
  141. gCarla.host.set_engine_callback(engineCallback)
  142. gCarla.host.set_file_callback(fileCallback)
  143. # -------------------------------------------------------------
  144. # Internal stuff
  145. self.fIdleTimerFast = 0
  146. self.fIdleTimerSlow = 0
  147. self.fIsProjectLoading = False
  148. self.fProjectFilename = ""
  149. self.fLadspaRdfNeedsUpdate = True
  150. self.fLadspaRdfList = []
  151. self.fLastTransportFrame = 0
  152. self.fLastTransportState = False
  153. self.fTransportText = ""
  154. # when true, call engineChanged() asap
  155. self.fEngineChanged = False
  156. # first attempt of auto-start engine doesn't show an error
  157. self.fFirstEngineInit = True
  158. self.fSavedSettings = {}
  159. if gCarla.isPlugin:
  160. self.fClientName = "Carla-Plugin"
  161. self.fSessionManagerName = "Plugin"
  162. elif LADISH_APP_NAME:
  163. self.fClientName = LADISH_APP_NAME
  164. self.fSessionManagerName = "LADISH"
  165. elif NSM_URL:
  166. self.fClientName = "Carla" # "Carla.tmp"
  167. self.fSessionManagerName = "Non Session Manager"
  168. else:
  169. self.fClientName = "Carla"
  170. self.fSessionManagerName = ""
  171. # -------------------------------------------------------------
  172. # Load Settings
  173. self.loadSettings(True)
  174. # -------------------------------------------------------------
  175. # Set up GUI (engine stopped)
  176. if gCarla.isPlugin:
  177. self.ui.act_engine_start.setEnabled(False)
  178. self.ui.menu_Engine.setEnabled(False)
  179. else:
  180. self.ui.act_engine_start.setEnabled(True)
  181. if self.fSessionManagerName:
  182. self.ui.act_file_new.setEnabled(False)
  183. self.ui.act_file_open.setEnabled(False)
  184. self.ui.act_file_save.setEnabled(False)
  185. self.ui.act_file_save_as.setEnabled(False)
  186. self.ui.act_engine_stop.setEnabled(False)
  187. self.ui.act_plugin_remove_all.setEnabled(False)
  188. self.ui.menu_PluginMacros.setEnabled(False)
  189. self.ui.menu_Canvas.setEnabled(False)
  190. self.setTransportMenuEnabled(False)
  191. # -------------------------------------------------------------
  192. # Set up GUI (disk)
  193. self.fDirModel = QFileSystemModel(self)
  194. self.fDirModel.setRootPath(HOME)
  195. if gCarla.host is not None:
  196. self.fDirModel.setNameFilters(gCarla.host.get_supported_file_extensions().split(";"))
  197. self.ui.fileTreeView.setModel(self.fDirModel)
  198. self.ui.fileTreeView.setRootIndex(self.fDirModel.index(HOME))
  199. self.ui.fileTreeView.setColumnHidden(1, True)
  200. self.ui.fileTreeView.setColumnHidden(2, True)
  201. self.ui.fileTreeView.setColumnHidden(3, True)
  202. self.ui.fileTreeView.setHeaderHidden(True)
  203. # -------------------------------------------------------------
  204. # Set up GUI (disk)
  205. #self.item1 = QListWidgetItem(self.ui.lw_plugins)
  206. #self.item1.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled|Qt.ItemIsDragEnabled)
  207. #self.item1.setIcon(QIcon(":/bitmaps/thumbs/zita-rev1.png"))
  208. #self.item1.setText("zita-rev1")
  209. #item1.setTextAlignment(Qt.ali)
  210. #self.ui.lw_plugins.()
  211. # -------------------------------------------------------------
  212. self.setProperWindowTitle()
  213. # -------------------------------------------------------------
  214. # Connect actions to functions
  215. self.ui.act_file_new.triggered.connect(self.slot_fileNew)
  216. self.ui.act_file_open.triggered.connect(self.slot_fileOpen)
  217. self.ui.act_file_save.triggered.connect(self.slot_fileSave)
  218. self.ui.act_file_save_as.triggered.connect(self.slot_fileSaveAs)
  219. self.ui.act_engine_start.triggered.connect(self.slot_engineStart)
  220. self.ui.act_engine_stop.triggered.connect(self.slot_engineStop)
  221. self.ui.act_plugin_add.triggered.connect(self.slot_pluginAdd)
  222. self.ui.act_plugin_add2.triggered.connect(self.slot_pluginAdd)
  223. self.ui.act_plugin_remove_all.triggered.connect(self.slot_pluginRemoveAll)
  224. self.ui.act_transport_play.triggered.connect(self.slot_transportPlayPause)
  225. self.ui.act_transport_stop.triggered.connect(self.slot_transportStop)
  226. self.ui.act_transport_backwards.triggered.connect(self.slot_transportBackwards)
  227. self.ui.act_transport_forwards.triggered.connect(self.slot_transportForwards)
  228. self.ui.act_help_about.triggered.connect(self.slot_aboutCarla)
  229. self.ui.act_help_about_qt.triggered.connect(self.slot_aboutQt)
  230. self.ui.cb_disk.currentIndexChanged.connect(self.slot_diskFolderChanged)
  231. self.ui.b_disk_add.clicked.connect(self.slot_diskFolderAdd)
  232. self.ui.b_disk_remove.clicked.connect(self.slot_diskFolderRemove)
  233. self.ui.fileTreeView.doubleClicked.connect(self.slot_fileTreeDoubleClicked)
  234. self.DebugCallback.connect(self.slot_handleDebugCallback)
  235. self.PluginAddedCallback.connect(self.slot_handlePluginAddedCallback)
  236. self.PluginRemovedCallback.connect(self.slot_handlePluginRemovedCallback)
  237. self.PluginRenamedCallback.connect(self.slot_handlePluginRenamedCallback)
  238. self.PluginUnavailableCallback.connect(self.slot_handlePluginUnavailableCallback)
  239. # parameter (rack, patchbay)
  240. # program, midi-program, ui-state (rack, patchbay)
  241. # note on, off (rack, patchbay)
  242. # update, reload (rack, patchbay)
  243. # patchbay
  244. self.EngineStartedCallback.connect(self.slot_handleEngineStartedCallback)
  245. self.EngineStoppedCallback.connect(self.slot_handleEngineStoppedCallback)
  246. self.ProcessModeChangedCallback.connect(self.slot_handleProcessModeChangedCallback)
  247. self.TransportModeChangedCallback.connect(self.slot_handleTransportModeChangedCallback)
  248. self.BufferSizeChangedCallback.connect(self.slot_handleBufferSizeChangedCallback)
  249. self.SampleRateChangedCallback.connect(self.slot_handleSampleRateChangedCallback)
  250. self.InfoCallback.connect(self.slot_handleInfoCallback)
  251. self.ErrorCallback.connect(self.slot_handleErrorCallback)
  252. self.QuitCallback.connect(self.slot_handleQuitCallback)
  253. self.SIGUSR1.connect(self.slot_handleSIGUSR1)
  254. self.SIGTERM.connect(self.slot_handleSIGTERM)
  255. # -------------------------------------------------------------
  256. # Final setup
  257. QTimer.singleShot(0, self.slot_engineStart)
  258. #QTimer.singleShot(2000, self.slot_test)
  259. #@pyqtSlot()
  260. #def slot_test(self):
  261. #print("test started")
  262. #if not gCarla.host.add_plugin(BINARY_NATIVE, PLUGIN_JACK, "/usr/bin/zita-rev1", "name of client", "label of client", None):
  263. #print(gCarla.host.get_last_error())
  264. #print("test ended")
  265. # -----------------------------------------------------------------
  266. # Called by containers
  267. def openSettingsWindow(self, hasCanvas, hasCanvasGL):
  268. hasEngine = bool(self.fSessionManagerName != "Non Session Manager")
  269. dialog = CarlaSettingsW(self, hasCanvas, hasCanvasGL, hasEngine)
  270. return dialog.exec_()
  271. def setupContainer(self, showCanvas, canvasThemeData = []):
  272. if showCanvas:
  273. canvasWidth, canvasHeight, canvasBg, canvasBrush, canvasPen = canvasThemeData
  274. self.ui.miniCanvasPreview.setViewTheme(canvasBg, canvasBrush, canvasPen)
  275. self.ui.miniCanvasPreview.init(self.fContainer.scene, canvasWidth, canvasHeight, self.fSavedSettings[CARLA_KEY_CUSTOM_PAINTING])
  276. else:
  277. self.ui.act_canvas_arrange.setVisible(False)
  278. self.ui.act_canvas_print.setVisible(False)
  279. self.ui.act_canvas_refresh.setVisible(False)
  280. self.ui.act_canvas_save_image.setVisible(False)
  281. self.ui.act_canvas_zoom_100.setVisible(False)
  282. self.ui.act_canvas_zoom_fit.setVisible(False)
  283. self.ui.act_canvas_zoom_in.setVisible(False)
  284. self.ui.act_canvas_zoom_out.setVisible(False)
  285. self.ui.act_settings_show_meters.setVisible(False)
  286. self.ui.act_settings_show_keyboard.setVisible(False)
  287. self.ui.menu_Canvas.setEnabled(False)
  288. self.ui.menu_Canvas.setVisible(False)
  289. self.ui.menu_Canvas_Zoom.setEnabled(False)
  290. self.ui.menu_Canvas_Zoom.setVisible(False)
  291. self.ui.miniCanvasPreview.hide()
  292. self.ui.splitter.insertWidget(1, self.fContainer)
  293. def updateContainer(self, canvasThemeData):
  294. canvasWidth, canvasHeight, canvasBg, canvasBrush, canvasPen = canvasThemeData
  295. self.ui.miniCanvasPreview.setViewTheme(canvasBg, canvasBrush, canvasPen)
  296. self.ui.miniCanvasPreview.init(self.fContainer.scene, canvasWidth, canvasHeight, self.fSavedSettings[CARLA_KEY_CUSTOM_PAINTING])
  297. # -----------------------------------------------------------------
  298. # Internal stuff (files)
  299. def loadProjectNow(self):
  300. if not self.fProjectFilename:
  301. return qCritical("ERROR: loading project without filename set")
  302. self.fContainer.projectLoadingStarted()
  303. self.fIsProjectLoading = True
  304. if gCarla.host is not None:
  305. gCarla.host.load_project(self.fProjectFilename)
  306. self.fIsProjectLoading = False
  307. self.fContainer.projectLoadingFinished()
  308. @pyqtSlot()
  309. def slot_loadProjectNow(self):
  310. self.loadProjectNow()
  311. def loadProjectLater(self, filename):
  312. self.fProjectFilename = filename
  313. self.setProperWindowTitle()
  314. QTimer.singleShot(0, self.slot_loadProjectNow)
  315. def saveProjectNow(self):
  316. if not self.fProjectFilename:
  317. return qCritical("ERROR: saving project without filename set")
  318. gCarla.host.save_project(self.fProjectFilename)
  319. # -----------------------------------------------------------------
  320. # Internal stuff (engine)
  321. def setEngineSettings(self, settings = None):
  322. if gCarla.isPlugin:
  323. return "Plugin"
  324. if self.fSessionManagerName == "Non Session Manager":
  325. return "JACK"
  326. if settings is None: settings = QSettings()
  327. # -------------------------------------------------------------
  328. # read settings
  329. # bool values
  330. try:
  331. forceStereo = settings.value(CARLA_KEY_ENGINE_FORCE_STEREO, CARLA_DEFAULT_FORCE_STEREO, type=bool)
  332. except:
  333. forceStereo = CARLA_DEFAULT_FORCE_STEREO
  334. try:
  335. preferPluginBridges = settings.value(CARLA_KEY_ENGINE_PREFER_PLUGIN_BRIDGES, CARLA_DEFAULT_PREFER_PLUGIN_BRIDGES, type=bool)
  336. except:
  337. preferPluginBridges = CARLA_DEFAULT_PREFER_PLUGIN_BRIDGES
  338. try:
  339. preferUiBridges = settings.value(CARLA_KEY_ENGINE_PREFER_UI_BRIDGES, CARLA_DEFAULT_PREFER_UI_BRIDGES, type=bool)
  340. except:
  341. preferUiBridges = CARLA_DEFAULT_PREFER_UI_BRIDGES
  342. try:
  343. uisAlwaysOnTop = settings.value(CARLA_KEY_ENGINE_UIS_ALWAYS_ON_TOP, CARLA_DEFAULT_UIS_ALWAYS_ON_TOP, type=bool)
  344. except:
  345. uisAlwaysOnTop = CARLA_DEFAULT_UIS_ALWAYS_ON_TOP
  346. # int values
  347. try:
  348. maxParameters = settings.value(CARLA_KEY_ENGINE_MAX_PARAMETERS, CARLA_DEFAULT_MAX_PARAMETERS, type=int)
  349. except:
  350. maxParameters = CARLA_DEFAULT_MAX_PARAMETERS
  351. try:
  352. uiBridgesTimeout = settings.value(CARLA_KEY_ENGINE_UI_BRIDGES_TIMEOUT, CARLA_DEFAULT_UI_BRIDGES_TIMEOUT, type=int)
  353. except:
  354. uiBridgesTimeout = CARLA_DEFAULT_UI_BRIDGES_TIMEOUT
  355. # enums
  356. try:
  357. processMode = settings.value(CARLA_KEY_ENGINE_PROCESS_MODE, CARLA_DEFAULT_PROCESS_MODE, type=int)
  358. except:
  359. processMode = CARLA_DEFAULT_PROCESS_MODE
  360. try:
  361. transportMode = settings.value(CARLA_KEY_ENGINE_TRANSPORT_MODE, CARLA_DEFAULT_TRANSPORT_MODE, type=int)
  362. except:
  363. transportMode = CARLA_DEFAULT_TRANSPORT_MODE
  364. # driver name
  365. try:
  366. audioDriver = settings.value(CARLA_KEY_ENGINE_AUDIO_DRIVER, CARLA_DEFAULT_AUDIO_DRIVER, type=str)
  367. except:
  368. audioDriver = CARLA_DEFAULT_AUDIO_DRIVER
  369. # driver options
  370. try:
  371. audioDevice = settings.value("%s%s/Device" % (CARLA_KEY_ENGINE_DRIVER_PREFIX, audioDriver), "", type=str)
  372. except:
  373. audioDevice = ""
  374. try:
  375. audioNumPeriods = settings.value("%s%s/NumPeriods" % (CARLA_KEY_ENGINE_DRIVER_PREFIX, audioDriver), CARLA_DEFAULT_AUDIO_NUM_PERIODS, type=int)
  376. except:
  377. audioNumPeriods = CARLA_DEFAULT_AUDIO_NUM_PERIODS
  378. try:
  379. audioBufferSize = settings.value("%s%s/BufferSize" % (CARLA_KEY_ENGINE_DRIVER_PREFIX, audioDriver), CARLA_DEFAULT_AUDIO_BUFFER_SIZE, type=int)
  380. except:
  381. audioBufferSize = CARLA_DEFAULT_AUDIO_BUFFER_SIZE
  382. try:
  383. audioSampleRate = settings.value("%s%s/SampleRate" % (CARLA_KEY_ENGINE_DRIVER_PREFIX, audioDriver), CARLA_DEFAULT_AUDIO_SAMPLE_RATE, type=int)
  384. except:
  385. audioSampleRate = CARLA_DEFAULT_AUDIO_SAMPLE_RATE
  386. if gCarla.processModeForced:
  387. processMode = gCarla.processMode
  388. # -------------------------------------------------------------
  389. # fix things if needed
  390. if processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK:
  391. forceStereo = True
  392. elif processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS and LADISH_APP_NAME:
  393. print("LADISH detected but using multiple clients (not allowed), forcing single client now")
  394. processMode = ENGINE_PROCESS_MODE_SINGLE_CLIENT
  395. if audioDriver != "JACK" and transportMode == ENGINE_TRANSPORT_MODE_JACK:
  396. transportMode = ENGINE_TRANSPORT_MODE_INTERNAL
  397. if gCarla.host is None:
  398. return audioDriver
  399. # -------------------------------------------------------------
  400. # apply to engine
  401. gCarla.host.set_engine_option(ENGINE_OPTION_FORCE_STEREO, forceStereo, "")
  402. gCarla.host.set_engine_option(ENGINE_OPTION_UIS_ALWAYS_ON_TOP, uisAlwaysOnTop, "")
  403. if not gCarla.isPlugin:
  404. gCarla.host.set_engine_option(ENGINE_OPTION_PREFER_PLUGIN_BRIDGES, preferPluginBridges, "")
  405. gCarla.host.set_engine_option(ENGINE_OPTION_PREFER_UI_BRIDGES, preferUiBridges, "")
  406. gCarla.host.set_engine_option(ENGINE_OPTION_MAX_PARAMETERS, maxParameters, "")
  407. gCarla.host.set_engine_option(ENGINE_OPTION_UI_BRIDGES_TIMEOUT, uiBridgesTimeout, "")
  408. gCarla.host.set_engine_option(ENGINE_OPTION_PROCESS_MODE, processMode, "")
  409. gCarla.host.set_engine_option(ENGINE_OPTION_TRANSPORT_MODE, transportMode, "")
  410. gCarla.host.set_engine_option(ENGINE_OPTION_AUDIO_NUM_PERIODS, audioNumPeriods, "")
  411. gCarla.host.set_engine_option(ENGINE_OPTION_AUDIO_BUFFER_SIZE, audioBufferSize, "")
  412. gCarla.host.set_engine_option(ENGINE_OPTION_AUDIO_SAMPLE_RATE, audioSampleRate, "")
  413. gCarla.host.set_engine_option(ENGINE_OPTION_AUDIO_DEVICE, 0, audioDevice)
  414. # save this for later
  415. gCarla.maxParameters = maxParameters
  416. # return selected driver name
  417. return audioDriver
  418. def startEngine(self):
  419. audioDriver = self.setEngineSettings()
  420. if gCarla.host is not None and not gCarla.host.engine_init(audioDriver, self.fClientName):
  421. if self.fFirstEngineInit:
  422. self.fFirstEngineInit = False
  423. return
  424. audioError = gCarla.host.get_last_error()
  425. if audioError:
  426. QMessageBox.critical(self, self.tr("Error"), self.tr("Could not connect to Audio backend '%s', possible reasons:\n%s" % (audioDriver, audioError)))
  427. else:
  428. QMessageBox.critical(self, self.tr("Error"), self.tr("Could not connect to Audio backend '%s'" % audioDriver))
  429. return
  430. self.fFirstEngineInit = False
  431. def stopEngine(self):
  432. if self.fContainer.getPluginCount() > 0:
  433. ask = QMessageBox.question(self, self.tr("Warning"), self.tr("There are still some plugins loaded, you need to remove them to stop the engine.\n"
  434. "Do you want to do this now?"),
  435. QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
  436. if ask != QMessageBox.Yes:
  437. return
  438. self.ui.act_plugin_remove_all.setEnabled(False)
  439. self.fContainer.removeAllPlugins()
  440. if gCarla.host.is_engine_running() and not gCarla.host.engine_close():
  441. print(gCarla.host.get_last_error())
  442. # -----------------------------------------------------------------
  443. # Internal stuff (plugins)
  444. def getExtraPtr(self, plugin):
  445. ptype = plugin['type']
  446. if ptype == PLUGIN_LADSPA:
  447. uniqueId = plugin['uniqueId']
  448. self.maybeLoadRDFs()
  449. for rdfItem in self.fLadspaRdfList:
  450. if rdfItem.UniqueID == uniqueId:
  451. return pointer(rdfItem)
  452. elif ptype in (PLUGIN_FILE_GIG, PLUGIN_FILE_SF2):
  453. if plugin['name'].lower().endswith(" (16 outputs)"):
  454. return c_char_p("true".encode("utf-8"))
  455. return None
  456. def maybeLoadRDFs(self):
  457. if not self.fLadspaRdfNeedsUpdate:
  458. return
  459. self.fLadspaRdfNeedsUpdate = False
  460. self.fLadspaRdfList = []
  461. if not haveLRDF:
  462. return
  463. settingsDir = os.path.join(HOME, ".config", "falkTX")
  464. frLadspaFile = os.path.join(settingsDir, "ladspa_rdf.db")
  465. if os.path.exists(frLadspaFile):
  466. frLadspa = open(frLadspaFile, 'r')
  467. try:
  468. self.fLadspaRdfList = ladspa_rdf.get_c_ladspa_rdfs(json.load(frLadspa))
  469. except:
  470. pass
  471. frLadspa.close()
  472. def setLoadRDFsNeeded(self):
  473. self.fLadspaRdfNeedsUpdate = True
  474. # -----------------------------------------------------------------
  475. # Internal stuff (transport)
  476. def refreshTransport(self, forced = False):
  477. if gCarla.sampleRate == 0.0 or not gCarla.host.is_engine_running():
  478. return
  479. timeInfo = gCarla.host.get_transport_info()
  480. playing = bool(timeInfo['playing'])
  481. frame = int(timeInfo['frame'])
  482. if playing != self.fLastTransportState or forced:
  483. if playing:
  484. icon = getIcon("media-playback-pause")
  485. self.ui.act_transport_play.setChecked(True)
  486. self.ui.act_transport_play.setIcon(icon)
  487. self.ui.act_transport_play.setText(self.tr("&Pause"))
  488. else:
  489. icon = getIcon("media-playback-start")
  490. self.ui.act_transport_play.setChecked(False)
  491. self.ui.act_transport_play.setIcon(icon)
  492. self.ui.act_transport_play.setText(self.tr("&Play"))
  493. self.fLastTransportState = playing
  494. if frame != self.fLastTransportFrame or forced:
  495. time = frame / gCarla.sampleRate
  496. secs = time % 60
  497. mins = (time / 60) % 60
  498. hrs = (time / 3600) % 60
  499. self.fTextTransport = "Transport %s, at %02i:%02i:%02i" % ("playing" if playing else "stopped", hrs, mins, secs)
  500. self.fLastTransportFrame = frame
  501. def setTransportMenuEnabled(self, enabled):
  502. self.ui.act_transport_play.setEnabled(enabled)
  503. self.ui.act_transport_stop.setEnabled(enabled)
  504. self.ui.act_transport_backwards.setEnabled(enabled)
  505. self.ui.act_transport_forwards.setEnabled(enabled)
  506. self.ui.menu_Transport.setEnabled(enabled)
  507. # -----------------------------------------------------------------
  508. # Internal stuff (settings)
  509. def loadSettings(self, firstTime):
  510. settings = QSettings()
  511. if firstTime:
  512. self.restoreGeometry(settings.value("Geometry", ""))
  513. showToolbar = settings.value("ShowToolbar", True, type=bool)
  514. self.ui.act_settings_show_toolbar.setChecked(showToolbar)
  515. self.ui.toolBar.setVisible(showToolbar)
  516. if settings.contains("SplitterState"):
  517. self.ui.splitter.restoreState(settings.value("SplitterState", ""))
  518. else:
  519. self.ui.splitter.setSizes([210, 99999])
  520. diskFolders = toList(settings.value("DiskFolders", [HOME]))
  521. self.ui.cb_disk.setItemData(0, HOME)
  522. for i in range(len(diskFolders)):
  523. if i == 0: continue
  524. folder = diskFolders[i]
  525. self.ui.cb_disk.addItem(os.path.basename(folder), folder)
  526. #if MACOS and not settings.value(CARLA_KEY_MAIN_USE_PRO_THEME, True, type=bool):
  527. # self.setUnifiedTitleAndToolBarOnMac(True)
  528. # ---------------------------------------------
  529. if not gCarla.isPlugin:
  530. # engine
  531. self.setEngineSettings(settings)
  532. # plugin paths
  533. LADSPA_PATH = toList(settings.value("Paths/LADSPA", gCarla.DEFAULT_LADSPA_PATH))
  534. DSSI_PATH = toList(settings.value("Paths/DSSI", gCarla.DEFAULT_DSSI_PATH))
  535. LV2_PATH = toList(settings.value("Paths/LV2", gCarla.DEFAULT_LV2_PATH))
  536. VST_PATH = toList(settings.value("Paths/VST", gCarla.DEFAULT_VST_PATH))
  537. AU_PATH = toList(settings.value("Paths/AU", gCarla.DEFAULT_AU_PATH))
  538. CSOUND_PATH = toList(settings.value("Paths/CSOUND", gCarla.DEFAULT_CSOUND_PATH))
  539. GIG_PATH = toList(settings.value("Paths/GIG", gCarla.DEFAULT_GIG_PATH))
  540. SF2_PATH = toList(settings.value("Paths/SF2", gCarla.DEFAULT_SF2_PATH))
  541. SFZ_PATH = toList(settings.value("Paths/SFZ", gCarla.DEFAULT_SFZ_PATH))
  542. os.environ["LADSPA_PATH"] = splitter.join(LADSPA_PATH)
  543. os.environ["DSSI_PATH"] = splitter.join(DSSI_PATH)
  544. os.environ["LV2_PATH"] = splitter.join(LV2_PATH)
  545. os.environ["VST_PATH"] = splitter.join(VST_PATH)
  546. os.environ["AU_PATH"] = splitter.join(AU_PATH)
  547. os.environ["CSOUND_PATH"] = splitter.join(CSOUND_PATH)
  548. os.environ["GIG_PATH"] = splitter.join(GIG_PATH)
  549. os.environ["SF2_PATH"] = splitter.join(SF2_PATH)
  550. os.environ["SFZ_PATH"] = splitter.join(SFZ_PATH)
  551. # ---------------------------------------------
  552. # TODO
  553. self.fSavedSettings = {
  554. CARLA_KEY_MAIN_PROJECT_FOLDER: settings.value(CARLA_KEY_MAIN_PROJECT_FOLDER, CARLA_DEFAULT_MAIN_PROJECT_FOLDER, type=str),
  555. CARLA_KEY_MAIN_REFRESH_INTERVAL: settings.value(CARLA_KEY_MAIN_REFRESH_INTERVAL, CARLA_DEFAULT_MAIN_REFRESH_INTERVAL, type=int),
  556. CARLA_KEY_CANVAS_THEME: settings.value(CARLA_KEY_CANVAS_THEME, CARLA_DEFAULT_CANVAS_THEME, type=str),
  557. CARLA_KEY_CANVAS_SIZE: settings.value(CARLA_KEY_CANVAS_SIZE, CARLA_DEFAULT_CANVAS_SIZE, type=str),
  558. CARLA_KEY_CANVAS_AUTO_HIDE_GROUPS: settings.value(CARLA_KEY_CANVAS_AUTO_HIDE_GROUPS, CARLA_DEFAULT_CANVAS_AUTO_HIDE_GROUPS, type=bool),
  559. CARLA_KEY_CANVAS_USE_BEZIER_LINES: settings.value(CARLA_KEY_CANVAS_USE_BEZIER_LINES, CARLA_DEFAULT_CANVAS_USE_BEZIER_LINES, type=bool),
  560. CARLA_KEY_CANVAS_EYE_CANDY: settings.value(CARLA_KEY_CANVAS_EYE_CANDY, CARLA_DEFAULT_CANVAS_EYE_CANDY, type=int),
  561. CARLA_KEY_CANVAS_USE_OPENGL: settings.value(CARLA_KEY_CANVAS_USE_OPENGL, CARLA_DEFAULT_CANVAS_USE_OPENGL, type=bool),
  562. CARLA_KEY_CANVAS_ANTIALIASING: settings.value(CARLA_KEY_CANVAS_ANTIALIASING, CARLA_DEFAULT_CANVAS_ANTIALIASING, type=int),
  563. CARLA_KEY_CANVAS_HQ_ANTIALIASING: settings.value(CARLA_KEY_CANVAS_HQ_ANTIALIASING, CARLA_DEFAULT_CANVAS_HQ_ANTIALIASING, type=bool),
  564. CARLA_KEY_CUSTOM_PAINTING: (settings.value(CARLA_KEY_MAIN_USE_PRO_THEME, True, type=bool) and
  565. settings.value(CARLA_KEY_MAIN_PRO_THEME_COLOR, "Black", type=str).lower() == "black")
  566. }
  567. # ---------------------------------------------
  568. if self.fIdleTimerFast != 0:
  569. self.killTimer(self.fIdleTimerFast)
  570. self.fIdleTimerFast = self.startTimer(self.fSavedSettings[CARLA_KEY_MAIN_REFRESH_INTERVAL])
  571. if self.fIdleTimerSlow != 0:
  572. self.killTimer(self.fIdleTimerSlow)
  573. self.fIdleTimerSlow = self.startTimer(self.fSavedSettings[CARLA_KEY_MAIN_REFRESH_INTERVAL]*4)
  574. def saveSettings(self):
  575. settings = QSettings()
  576. settings.setValue("Geometry", self.saveGeometry())
  577. settings.setValue("SplitterState", self.ui.splitter.saveState())
  578. settings.setValue("ShowToolbar", self.ui.toolBar.isVisible())
  579. diskFolders = []
  580. for i in range(self.ui.cb_disk.count()):
  581. diskFolders.append(self.ui.cb_disk.itemData(i))
  582. settings.setValue("DiskFolders", diskFolders)
  583. self.fContainer.saveSettings(settings)
  584. # -----------------------------------------------------------------
  585. # Internal stuff (gui)
  586. def killTimers(self):
  587. if self.fIdleTimerFast != 0:
  588. self.killTimer(self.fIdleTimerFast)
  589. self.fIdleTimerFast = 0
  590. if self.fIdleTimerSlow != 0:
  591. self.killTimer(self.fIdleTimerSlow)
  592. self.fIdleTimerSlow = 0
  593. def setProperWindowTitle(self):
  594. title = self.fClientName
  595. if self.fProjectFilename:
  596. title += " - %s" % os.path.basename(self.fProjectFilename)
  597. if self.fSessionManagerName:
  598. title += " (%s)" % self.fSessionManagerName
  599. self.setWindowTitle(title)
  600. # -----------------------------------------------------------------
  601. @pyqtSlot()
  602. def slot_fileNew(self):
  603. self.fContainer.removeAllPlugins()
  604. self.fProjectFilename = ""
  605. self.setProperWindowTitle()
  606. @pyqtSlot()
  607. def slot_fileOpen(self):
  608. fileFilter = self.tr("Carla Project File (*.carxp)")
  609. filenameTry = QFileDialog.getOpenFileName(self, self.tr("Open Carla Project File"), self.fSavedSettings[CARLA_KEY_MAIN_PROJECT_FOLDER], filter=fileFilter)
  610. if not filenameTry:
  611. return
  612. filename = filenameTry if isinstance(filenameTry, str) else filenameTry[0]
  613. newFile = True
  614. if self.fContainer.getPluginCount() > 0:
  615. ask = QMessageBox.question(self, self.tr("Question"), self.tr("There are some plugins loaded, do you want to remove them now?"),
  616. QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
  617. newFile = (ask == QMessageBox.Yes)
  618. if newFile:
  619. self.fContainer.removeAllPlugins()
  620. self.fProjectFilename = filename
  621. self.setProperWindowTitle()
  622. self.loadProjectNow()
  623. else:
  624. filenameOld = self.fProjectFilename
  625. self.fProjectFilename = filename
  626. self.loadProjectNow()
  627. self.fProjectFilename = filenameOld
  628. @pyqtSlot()
  629. def slot_fileSave(self, saveAs=False):
  630. if self.fProjectFilename and not saveAs:
  631. return self.saveProjectNow()
  632. fileFilter = self.tr("Carla Project File (*.carxp)")
  633. filenameTry = QFileDialog.getSaveFileName(self, self.tr("Save Carla Project File"), self.fSavedSettings[CARLA_KEY_MAIN_PROJECT_FOLDER], filter=fileFilter)
  634. if not filenameTry:
  635. return
  636. filename = filenameTry if isinstance(filenameTry, str) else filenameTry[0]
  637. if not filename.endswith(".carxp"):
  638. filename += ".carxp"
  639. if self.fProjectFilename != filename:
  640. self.fProjectFilename = filename
  641. self.setProperWindowTitle()
  642. self.saveProjectNow()
  643. @pyqtSlot()
  644. def slot_fileSaveAs(self):
  645. self.slot_fileSave(True)
  646. # -----------------------------------------------------------------
  647. @pyqtSlot()
  648. def slot_engineStart(self, doStart = True):
  649. if doStart: self.startEngine()
  650. check = gCarla.host is not None and gCarla.host.is_engine_running()
  651. self.ui.menu_PluginMacros.setEnabled(check)
  652. self.ui.menu_Canvas.setEnabled(check)
  653. if not gCarla.isPlugin:
  654. self.ui.act_engine_start.setEnabled(not check)
  655. self.ui.act_engine_stop.setEnabled(check)
  656. if not self.fSessionManagerName:
  657. self.ui.act_file_open.setEnabled(check)
  658. self.ui.act_file_save.setEnabled(check)
  659. self.ui.act_file_save_as.setEnabled(check)
  660. self.setTransportMenuEnabled(check)
  661. if check:
  662. if not gCarla.isPlugin:
  663. self.refreshTransport(True)
  664. self.fContainer.engineStarted()
  665. @pyqtSlot()
  666. def slot_engineStop(self, doStop = True):
  667. if doStop: self.stopEngine()
  668. # FIXME?
  669. if self.fContainer.getPluginCount() > 0:
  670. self.ui.act_plugin_remove_all.setEnabled(False)
  671. self.fContainer.removeAllPlugins()
  672. check = gCarla.host.is_engine_running()
  673. self.ui.menu_PluginMacros.setEnabled(check)
  674. self.ui.menu_Canvas.setEnabled(check)
  675. if not gCarla.isPlugin:
  676. self.ui.act_engine_start.setEnabled(not check)
  677. self.ui.act_engine_stop.setEnabled(check)
  678. if not self.fSessionManagerName:
  679. self.ui.act_file_open.setEnabled(check)
  680. self.ui.act_file_save.setEnabled(check)
  681. self.ui.act_file_save_as.setEnabled(check)
  682. self.setTransportMenuEnabled(check)
  683. if not check:
  684. self.fTextTransport = ""
  685. self.fContainer.engineStopped()
  686. # -----------------------------------------------------------------
  687. @pyqtSlot()
  688. def slot_pluginAdd(self, pluginToReplace = -1):
  689. dialog = PluginDatabaseW(self)
  690. if not dialog.exec_():
  691. return
  692. if gCarla.host is not None and not gCarla.host.is_engine_running():
  693. QMessageBox.warning(self, self.tr("Warning"), self.tr("Cannot add new plugins while engine is stopped"))
  694. return
  695. btype = dialog.fRetPlugin['build']
  696. ptype = dialog.fRetPlugin['type']
  697. filename = dialog.fRetPlugin['filename']
  698. label = dialog.fRetPlugin['label']
  699. uniqueId = dialog.fRetPlugin['uniqueId']
  700. extraPtr = self.getExtraPtr(dialog.fRetPlugin)
  701. if pluginToReplace >= 0:
  702. if not gCarla.host.replace_plugin(pluginToReplace):
  703. CustomMessageBox(self, QMessageBox.Critical, self.tr("Error"), self.tr("Failed to replace plugin"), gCarla.host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  704. return
  705. ok = gCarla.host.add_plugin(btype, ptype, filename, None, label, uniqueId, extraPtr)
  706. if pluginToReplace >= 0:
  707. gCarla.host.replace_plugin(self.fContainer.getPluginCount())
  708. if not ok:
  709. CustomMessageBox(self, QMessageBox.Critical, self.tr("Error"), self.tr("Failed to load plugin"), gCarla.host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  710. @pyqtSlot()
  711. def slot_pluginRemoveAll(self):
  712. self.ui.act_plugin_remove_all.setEnabled(False)
  713. count = self.fContainer.getPluginCount()
  714. if count == 0:
  715. return
  716. self.fContainer.projectLoadingStarted()
  717. app = QApplication.instance()
  718. for i in range(count):
  719. app.processEvents()
  720. gCarla.host.remove_plugin(count-i-1)
  721. self.fContainer.projectLoadingFinished()
  722. #self.fContainer.removeAllPlugins()
  723. #gCarla.host.remove_all_plugins()
  724. # -----------------------------------------------------------------
  725. @pyqtSlot(bool)
  726. def slot_transportPlayPause(self, toggled):
  727. if not gCarla.host.is_engine_running():
  728. return
  729. if toggled:
  730. gCarla.host.transport_play()
  731. else:
  732. gCarla.host.transport_pause()
  733. self.refreshTransport()
  734. @pyqtSlot()
  735. def slot_transportStop(self):
  736. if not gCarla.host.is_engine_running():
  737. return
  738. gCarla.host.transport_pause()
  739. gCarla.host.transport_relocate(0)
  740. self.refreshTransport()
  741. @pyqtSlot()
  742. def slot_transportBackwards(self):
  743. if not gCarla.host.is_engine_running():
  744. return
  745. newFrame = gCarla.host.get_current_transport_frame() - 100000
  746. if newFrame < 0:
  747. newFrame = 0
  748. gCarla.host.transport_relocate(newFrame)
  749. @pyqtSlot()
  750. def slot_transportForwards(self):
  751. if not gCarla.host.is_engine_running():
  752. return
  753. newFrame = gCarla.host.get_current_transport_frame() + 100000
  754. gCarla.host.transport_relocate(newFrame)
  755. # -----------------------------------------------------------------
  756. @pyqtSlot()
  757. def slot_aboutCarla(self):
  758. CarlaAboutW(self).exec_()
  759. @pyqtSlot()
  760. def slot_aboutQt(self):
  761. QApplication.instance().aboutQt()
  762. # -----------------------------------------------------------------
  763. @pyqtSlot(int)
  764. def slot_diskFolderChanged(self, index):
  765. if index < 0:
  766. return
  767. elif index == 0:
  768. filename = HOME
  769. self.ui.b_disk_remove.setEnabled(False)
  770. else:
  771. filename = self.ui.cb_disk.itemData(index)
  772. self.ui.b_disk_remove.setEnabled(True)
  773. self.fDirModel.setRootPath(filename)
  774. self.ui.fileTreeView.setRootIndex(self.fDirModel.index(filename))
  775. @pyqtSlot()
  776. def slot_diskFolderAdd(self):
  777. newPath = QFileDialog.getExistingDirectory(self, self.tr("New Folder"), "", QFileDialog.ShowDirsOnly)
  778. if newPath:
  779. if newPath[-1] == os.sep:
  780. newPath = newPath[:-1]
  781. self.ui.cb_disk.addItem(os.path.basename(newPath), newPath)
  782. self.ui.cb_disk.setCurrentIndex(self.ui.cb_disk.count()-1)
  783. self.ui.b_disk_remove.setEnabled(True)
  784. @pyqtSlot()
  785. def slot_diskFolderRemove(self):
  786. index = self.ui.cb_disk.currentIndex()
  787. if index <= 0:
  788. return
  789. self.ui.cb_disk.removeItem(index)
  790. if self.ui.cb_disk.currentIndex() == 0:
  791. self.ui.b_disk_remove.setEnabled(False)
  792. @pyqtSlot(QModelIndex)
  793. def slot_fileTreeDoubleClicked(self, modelIndex):
  794. filename = self.fDirModel.filePath(modelIndex)
  795. if not gCarla.host.load_file(filename):
  796. CustomMessageBox(self, QMessageBox.Critical, self.tr("Error"),
  797. self.tr("Failed to load file"),
  798. gCarla.host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  799. # -----------------------------------------------------------------
  800. @pyqtSlot(int, int, int, float, str)
  801. def slot_handleDebugCallback(self, pluginId, value1, value2, value3, valueStr):
  802. print("DEBUG:", pluginId, value1, value2, value3, valueStr)
  803. #self.ui.pte_log.appendPlainText(valueStr.replace("", "DEBUG: ").replace("", "ERROR: ").replace("", "").replace("\n", ""))
  804. # -----------------------------------------------------------------
  805. @pyqtSlot(int, str)
  806. def slot_handlePluginAddedCallback(self, pluginId, pluginName):
  807. self.fContainer.addPlugin(pluginId, self.fIsProjectLoading)
  808. if self.fContainer.getPluginCount() == 1:
  809. self.ui.act_plugin_remove_all.setEnabled(True)
  810. @pyqtSlot(int)
  811. def slot_handlePluginRemovedCallback(self, pluginId):
  812. self.fContainer.removePlugin(pluginId)
  813. if self.fContainer.getPluginCount() == 0:
  814. self.ui.act_plugin_remove_all.setEnabled(False)
  815. @pyqtSlot(int, str)
  816. def slot_handlePluginRenamedCallback(self, pluginId, newName):
  817. self.fContainer.renamePlugin(pluginId, newName)
  818. @pyqtSlot(int, str)
  819. def slot_handlePluginUnavailableCallback(self, pluginId, errorMsg):
  820. self.fContainer.disablePlugin(pluginId, errorMsg)
  821. # -----------------------------------------------------------------
  822. @pyqtSlot(str)
  823. def slot_handleEngineStartedCallback(self, processMode, transportMode, driverName):
  824. gCarla.processMode = processMode
  825. gCarla.transportMode = transportMode
  826. gCarla.bufferSize = gCarla.host.get_buffer_size()
  827. gCarla.sampleRate = gCarla.host.get_sample_rate()
  828. self.slot_engineStart(False)
  829. if self.fIdleTimerFast == 0:
  830. self.fIdleTimerFast = self.startTimer(self.fSavedSettings[CARLA_KEY_MAIN_REFRESH_INTERVAL])
  831. if self.fIdleTimerSlow == 0:
  832. self.fIdleTimerSlow = self.startTimer(self.fSavedSettings[CARLA_KEY_MAIN_REFRESH_INTERVAL]*4)
  833. @pyqtSlot()
  834. def slot_handleEngineStoppedCallback(self):
  835. self.killTimers()
  836. self.slot_engineStop(False)
  837. gCarla.bufferSize = 0
  838. gCarla.sampleRate = 0.0
  839. # -----------------------------------------------------------------
  840. @pyqtSlot(int)
  841. def slot_handleProcessModeChangedCallback(self, newProcessMode):
  842. self.fEngineChanged = True
  843. @pyqtSlot(int)
  844. def slot_handleTransportModeChangedCallback(self, newTransportMode):
  845. self.fEngineChanged = True
  846. # -----------------------------------------------------------------
  847. @pyqtSlot(int)
  848. def slot_handleBufferSizeChangedCallback(self, newBufferSize):
  849. self.fEngineChanged = True
  850. @pyqtSlot(float)
  851. def slot_handleSampleRateChangedCallback(self, newSampleRate):
  852. self.fEngineChanged = True
  853. # -----------------------------------------------------------------
  854. @pyqtSlot(str)
  855. def slot_handleInfoCallback(self, info):
  856. QMessageBox.information(self, "Information", info)
  857. @pyqtSlot(str)
  858. def slot_handleErrorCallback(self, error):
  859. QMessageBox.critical(self, "Error", error)
  860. @pyqtSlot()
  861. def slot_handleQuitCallback(self):
  862. pass
  863. # -----------------------------------------------------------------
  864. @pyqtSlot()
  865. def slot_handleSIGUSR1(self):
  866. print("Got SIGUSR1 -> Saving project now")
  867. QTimer.singleShot(0, self.slot_fileSave)
  868. @pyqtSlot()
  869. def slot_handleSIGTERM(self):
  870. print("Got SIGTERM -> Closing now")
  871. self.close()
  872. # -----------------------------------------------------------------
  873. def showEvent(self, event):
  874. QMainWindow.showEvent(self, event)
  875. # set our gui as parent for all plugins UIs
  876. if gCarla.host is not None:
  877. gCarla.host.set_engine_option(ENGINE_OPTION_FRONTEND_WIN_ID, 0, "%x" % self.winId())
  878. def timerEvent(self, event):
  879. if event.timerId() == self.fIdleTimerFast:
  880. #if not gCarla.isPlugin:
  881. gCarla.host.engine_idle()
  882. self.refreshTransport()
  883. self.fContainer.idleFast()
  884. elif event.timerId() == self.fIdleTimerSlow:
  885. if self.fEngineChanged:
  886. self.fContainer.engineChanged()
  887. self.fEngineChanged = False
  888. self.fContainer.idleSlow()
  889. QMainWindow.timerEvent(self, event)
  890. def closeEvent(self, event):
  891. self.killTimers()
  892. self.saveSettings()
  893. if gCarla.host is None or gCarla.isPlugin:
  894. pass
  895. elif gCarla.host.is_engine_running():
  896. gCarla.host.set_engine_about_to_close()
  897. count = self.fContainer.getPluginCount()
  898. if count > 0:
  899. # simulate project loading, to disable container
  900. self.ui.act_plugin_remove_all.setEnabled(False)
  901. self.fContainer.projectLoadingStarted()
  902. app = QApplication.instance()
  903. for i in range(count):
  904. app.processEvents()
  905. gCarla.host.remove_plugin(count-i-1)
  906. app.processEvents()
  907. #self.fContainer.removeAllPlugins()
  908. #gCarla.host.remove_all_plugins()
  909. self.stopEngine()
  910. QMainWindow.closeEvent(self, event)
  911. # ------------------------------------------------------------------------------------------------------------
  912. # Engine callback
  913. def engineCallback(ptr, action, pluginId, value1, value2, value3, valueStr):
  914. if action == ENGINE_CALLBACK_PROCESS_MODE_CHANGED:
  915. gCarla.processMode = value1
  916. if gCarla.gui is not None:
  917. gCarla.gui.ProcessModeChangedCallback.emit(value1)
  918. return
  919. if action == ENGINE_CALLBACK_TRANSPORT_MODE_CHANGED:
  920. gCarla.transportMode = value1
  921. if gCarla.gui is not None:
  922. gCarla.gui.TransportModeChangedCallback.emit(value1)
  923. return
  924. if action == ENGINE_CALLBACK_BUFFER_SIZE_CHANGED:
  925. gCarla.bufferSize = value1
  926. if gCarla.gui is not None:
  927. gCarla.gui.BufferSizeChangedCallback.emit(value1)
  928. return
  929. if action == ENGINE_CALLBACK_SAMPLE_RATE_CHANGED:
  930. gCarla.sampleRate = value1
  931. if gCarla.gui is not None:
  932. gCarla.gui.SampleRateChangedCallback.emit(value3)
  933. return
  934. if gCarla.gui is None:
  935. print("WARNING: Got engine callback but UI is not ready : ", pluginId, value1, value2, value3, valueStr)
  936. return
  937. valueStr = charPtrToString(valueStr)
  938. if action == ENGINE_CALLBACK_DEBUG:
  939. gCarla.gui.DebugCallback.emit(pluginId, value1, value2, value3, valueStr)
  940. elif action == ENGINE_CALLBACK_PLUGIN_ADDED:
  941. gCarla.gui.PluginAddedCallback.emit(pluginId, valueStr)
  942. elif action == ENGINE_CALLBACK_PLUGIN_REMOVED:
  943. gCarla.gui.PluginRemovedCallback.emit(pluginId)
  944. elif action == ENGINE_CALLBACK_PLUGIN_RENAMED:
  945. gCarla.gui.PluginRenamedCallback.emit(pluginId, valueStr)
  946. elif action == ENGINE_CALLBACK_PLUGIN_UNAVAILABLE:
  947. gCarla.gui.PluginUnavailableCallback.emit(pluginId, valueStr)
  948. elif action == ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED:
  949. gCarla.gui.ParameterValueChangedCallback.emit(pluginId, value1, value3)
  950. elif action == ENGINE_CALLBACK_PARAMETER_DEFAULT_CHANGED:
  951. gCarla.gui.ParameterDefaultChangedCallback.emit(pluginId, value1, value3)
  952. elif action == ENGINE_CALLBACK_PARAMETER_MIDI_CC_CHANGED:
  953. gCarla.gui.ParameterMidiCcChangedCallback.emit(pluginId, value1, value2)
  954. elif action == ENGINE_CALLBACK_PARAMETER_MIDI_CHANNEL_CHANGED:
  955. gCarla.gui.ParameterMidiChannelChangedCallback.emit(pluginId, value1, value2)
  956. elif action == ENGINE_CALLBACK_PROGRAM_CHANGED:
  957. gCarla.gui.ProgramChangedCallback.emit(pluginId, value1)
  958. elif action == ENGINE_CALLBACK_MIDI_PROGRAM_CHANGED:
  959. gCarla.gui.MidiProgramChangedCallback.emit(pluginId, value1)
  960. elif action == ENGINE_CALLBACK_UI_STATE_CHANGED:
  961. gCarla.gui.UiStateChangedCallback.emit(pluginId, value1)
  962. elif action == ENGINE_CALLBACK_NOTE_ON:
  963. gCarla.gui.NoteOnCallback.emit(pluginId, value1, value2, int(value3))
  964. elif action == ENGINE_CALLBACK_NOTE_OFF:
  965. gCarla.gui.NoteOffCallback.emit(pluginId, value1, value2)
  966. elif action == ENGINE_CALLBACK_UPDATE:
  967. gCarla.gui.UpdateCallback.emit(pluginId)
  968. elif action == ENGINE_CALLBACK_RELOAD_INFO:
  969. gCarla.gui.ReloadInfoCallback.emit(pluginId)
  970. elif action == ENGINE_CALLBACK_RELOAD_PARAMETERS:
  971. gCarla.gui.ReloadParametersCallback.emit(pluginId)
  972. elif action == ENGINE_CALLBACK_RELOAD_PROGRAMS:
  973. gCarla.gui.ReloadProgramsCallback.emit(pluginId)
  974. elif action == ENGINE_CALLBACK_RELOAD_ALL:
  975. gCarla.gui.ReloadAllCallback.emit(pluginId)
  976. elif action == ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED:
  977. gCarla.gui.PatchbayClientAddedCallback.emit(pluginId, value1, value2, valueStr)
  978. elif action == ENGINE_CALLBACK_PATCHBAY_CLIENT_REMOVED:
  979. gCarla.gui.PatchbayClientRemovedCallback.emit(pluginId)
  980. elif action == ENGINE_CALLBACK_PATCHBAY_CLIENT_RENAMED:
  981. gCarla.gui.PatchbayClientRenamedCallback.emit(pluginId, valueStr)
  982. elif action == ENGINE_CALLBACK_PATCHBAY_CLIENT_DATA_CHANGED:
  983. gCarla.gui.PatchbayClientDataChangedCallback.emit(pluginId, value1, value2)
  984. elif action == ENGINE_CALLBACK_PATCHBAY_PORT_ADDED:
  985. gCarla.gui.PatchbayPortAddedCallback.emit(pluginId, value1, value2, valueStr)
  986. elif action == ENGINE_CALLBACK_PATCHBAY_PORT_REMOVED:
  987. gCarla.gui.PatchbayPortRemovedCallback.emit(pluginId, value1)
  988. elif action == ENGINE_CALLBACK_PATCHBAY_PORT_RENAMED:
  989. gCarla.gui.PatchbayPortRenamedCallback.emit(pluginId, value1, valueStr)
  990. elif action == ENGINE_CALLBACK_PATCHBAY_PORT_VALUE_CHANGED:
  991. gCarla.gui.PatchbayPortValueChangedCallback.emit(pluginId, value1, value3)
  992. elif action == ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED:
  993. gOut, pOut, gIn, pIn = [int(i) for i in valueStr.split(":")]
  994. gCarla.gui.PatchbayConnectionAddedCallback.emit(pluginId, gOut, pOut, gIn, pIn)
  995. elif action == ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED:
  996. gCarla.gui.PatchbayConnectionRemovedCallback.emit(pluginId, value1, value2)
  997. elif action == ENGINE_CALLBACK_ENGINE_STARTED:
  998. gCarla.gui.EngineStartedCallback.emit(value1, value2, valueStr)
  999. elif action == ENGINE_CALLBACK_ENGINE_STOPPED:
  1000. gCarla.gui.killTimers()
  1001. gCarla.gui.EngineStoppedCallback.emit()
  1002. elif action == ENGINE_CALLBACK_IDLE:
  1003. QApplication.instance().processEvents()
  1004. elif action == ENGINE_CALLBACK_INFO:
  1005. gCarla.gui.InfoCallback.emit(valueStr)
  1006. elif action == ENGINE_CALLBACK_ERROR:
  1007. gCarla.gui.ErrorCallback.emit(valueStr)
  1008. elif action == ENGINE_CALLBACK_QUIT:
  1009. gCarla.gui.QuitCallback.emit()
  1010. # ------------------------------------------------------------------------------------------------------------
  1011. # File callback
  1012. def fileCallback(ptr, action, isDir, title, filter):
  1013. if gCarla.gui is None:
  1014. return None
  1015. ret = ""
  1016. if action == FILE_CALLBACK_DEBUG:
  1017. pass
  1018. elif action == FILE_CALLBACK_OPEN:
  1019. ret = QFileDialog.getOpenFileName(gCarla.gui, charPtrToString(title), "", charPtrToString(filter) ) #, QFileDialog.ShowDirsOnly if isDir else 0x0)
  1020. elif action == FILE_CALLBACK_SAVE:
  1021. ret = QFileDialog.getSaveFileName(gCarla.gui, charPtrToString(title), "", charPtrToString(filter), QFileDialog.ShowDirsOnly if isDir else 0x0)
  1022. if not ret:
  1023. return None
  1024. gCarla.gui._fileRet = c_char_p(ret.encode("utf-8"))
  1025. retval = cast(byref(gCarla.gui._fileRet), POINTER(c_uintptr))
  1026. return retval.contents.value