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.

1339 lines
51KB

  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. OptionChangedCallback = pyqtSignal(int, int, bool)
  101. UiStateChangedCallback = pyqtSignal(int, int)
  102. NoteOnCallback = pyqtSignal(int, int, int, int)
  103. NoteOffCallback = pyqtSignal(int, int, int)
  104. UpdateCallback = pyqtSignal(int)
  105. ReloadInfoCallback = pyqtSignal(int)
  106. ReloadParametersCallback = pyqtSignal(int)
  107. ReloadProgramsCallback = pyqtSignal(int)
  108. ReloadAllCallback = pyqtSignal(int)
  109. PatchbayClientAddedCallback = pyqtSignal(int, int, int, str)
  110. PatchbayClientRemovedCallback = pyqtSignal(int)
  111. PatchbayClientRenamedCallback = pyqtSignal(int, str)
  112. PatchbayClientDataChangedCallback = pyqtSignal(int, int, int)
  113. PatchbayPortAddedCallback = pyqtSignal(int, int, int, str)
  114. PatchbayPortRemovedCallback = pyqtSignal(int, int)
  115. PatchbayPortRenamedCallback = pyqtSignal(int, int, str)
  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. # -----------------------------------------------------------------
  259. # Called by containers
  260. def openSettingsWindow(self, hasCanvas, hasCanvasGL):
  261. hasEngine = bool(self.fSessionManagerName != "Non Session Manager")
  262. dialog = CarlaSettingsW(self, hasCanvas, hasCanvasGL, hasEngine)
  263. return dialog.exec_()
  264. def setupContainer(self, showCanvas, canvasThemeData = []):
  265. if showCanvas:
  266. canvasWidth, canvasHeight, canvasBg, canvasBrush, canvasPen = canvasThemeData
  267. self.ui.miniCanvasPreview.setViewTheme(canvasBg, canvasBrush, canvasPen)
  268. self.ui.miniCanvasPreview.init(self.fContainer.scene, canvasWidth, canvasHeight, self.fSavedSettings[CARLA_KEY_CUSTOM_PAINTING])
  269. else:
  270. self.ui.act_canvas_arrange.setVisible(False)
  271. self.ui.act_canvas_print.setVisible(False)
  272. self.ui.act_canvas_refresh.setVisible(False)
  273. self.ui.act_canvas_save_image.setVisible(False)
  274. self.ui.act_canvas_zoom_100.setVisible(False)
  275. self.ui.act_canvas_zoom_fit.setVisible(False)
  276. self.ui.act_canvas_zoom_in.setVisible(False)
  277. self.ui.act_canvas_zoom_out.setVisible(False)
  278. self.ui.act_settings_show_meters.setVisible(False)
  279. self.ui.act_settings_show_keyboard.setVisible(False)
  280. self.ui.menu_Canvas.setEnabled(False)
  281. self.ui.menu_Canvas.setVisible(False)
  282. self.ui.menu_Canvas_Zoom.setEnabled(False)
  283. self.ui.menu_Canvas_Zoom.setVisible(False)
  284. self.ui.miniCanvasPreview.hide()
  285. self.ui.splitter.insertWidget(1, self.fContainer)
  286. def updateContainer(self, canvasThemeData):
  287. canvasWidth, canvasHeight, canvasBg, canvasBrush, canvasPen = canvasThemeData
  288. self.ui.miniCanvasPreview.setViewTheme(canvasBg, canvasBrush, canvasPen)
  289. self.ui.miniCanvasPreview.init(self.fContainer.scene, canvasWidth, canvasHeight, self.fSavedSettings[CARLA_KEY_CUSTOM_PAINTING])
  290. # -----------------------------------------------------------------
  291. # Internal stuff (files)
  292. def loadProjectNow(self):
  293. if not self.fProjectFilename:
  294. return qCritical("ERROR: loading project without filename set")
  295. self.fContainer.projectLoadingStarted()
  296. self.fIsProjectLoading = True
  297. if gCarla.host is not None:
  298. gCarla.host.load_project(self.fProjectFilename)
  299. self.fIsProjectLoading = False
  300. self.fContainer.projectLoadingFinished()
  301. @pyqtSlot()
  302. def slot_loadProjectNow(self):
  303. self.loadProjectNow()
  304. def loadProjectLater(self, filename):
  305. self.fProjectFilename = filename
  306. self.setProperWindowTitle()
  307. QTimer.singleShot(0, self.slot_loadProjectNow)
  308. def saveProjectNow(self):
  309. if not self.fProjectFilename:
  310. return qCritical("ERROR: saving project without filename set")
  311. gCarla.host.save_project(self.fProjectFilename)
  312. # -----------------------------------------------------------------
  313. # Internal stuff (engine)
  314. def setEngineSettings(self, settings = None):
  315. if gCarla.isPlugin:
  316. return "Plugin"
  317. if self.fSessionManagerName == "Non Session Manager":
  318. return "JACK"
  319. if settings is None: settings = QSettings()
  320. # -------------------------------------------------------------
  321. # read settings
  322. # bool values
  323. try:
  324. forceStereo = settings.value(CARLA_KEY_ENGINE_FORCE_STEREO, CARLA_DEFAULT_FORCE_STEREO, type=bool)
  325. except:
  326. forceStereo = CARLA_DEFAULT_FORCE_STEREO
  327. try:
  328. preferPluginBridges = settings.value(CARLA_KEY_ENGINE_PREFER_PLUGIN_BRIDGES, CARLA_DEFAULT_PREFER_PLUGIN_BRIDGES, type=bool)
  329. except:
  330. preferPluginBridges = CARLA_DEFAULT_PREFER_PLUGIN_BRIDGES
  331. try:
  332. preferUiBridges = settings.value(CARLA_KEY_ENGINE_PREFER_UI_BRIDGES, CARLA_DEFAULT_PREFER_UI_BRIDGES, type=bool)
  333. except:
  334. preferUiBridges = CARLA_DEFAULT_PREFER_UI_BRIDGES
  335. try:
  336. uisAlwaysOnTop = settings.value(CARLA_KEY_ENGINE_UIS_ALWAYS_ON_TOP, CARLA_DEFAULT_UIS_ALWAYS_ON_TOP, type=bool)
  337. except:
  338. uisAlwaysOnTop = CARLA_DEFAULT_UIS_ALWAYS_ON_TOP
  339. # int values
  340. try:
  341. maxParameters = settings.value(CARLA_KEY_ENGINE_MAX_PARAMETERS, CARLA_DEFAULT_MAX_PARAMETERS, type=int)
  342. except:
  343. maxParameters = CARLA_DEFAULT_MAX_PARAMETERS
  344. try:
  345. uiBridgesTimeout = settings.value(CARLA_KEY_ENGINE_UI_BRIDGES_TIMEOUT, CARLA_DEFAULT_UI_BRIDGES_TIMEOUT, type=int)
  346. except:
  347. uiBridgesTimeout = CARLA_DEFAULT_UI_BRIDGES_TIMEOUT
  348. # enums
  349. try:
  350. processMode = settings.value(CARLA_KEY_ENGINE_PROCESS_MODE, CARLA_DEFAULT_PROCESS_MODE, type=int)
  351. except:
  352. processMode = CARLA_DEFAULT_PROCESS_MODE
  353. try:
  354. transportMode = settings.value(CARLA_KEY_ENGINE_TRANSPORT_MODE, CARLA_DEFAULT_TRANSPORT_MODE, type=int)
  355. except:
  356. transportMode = CARLA_DEFAULT_TRANSPORT_MODE
  357. # driver name
  358. try:
  359. audioDriver = settings.value(CARLA_KEY_ENGINE_AUDIO_DRIVER, CARLA_DEFAULT_AUDIO_DRIVER, type=str)
  360. except:
  361. audioDriver = CARLA_DEFAULT_AUDIO_DRIVER
  362. # driver options
  363. try:
  364. audioDevice = settings.value("%s%s/Device" % (CARLA_KEY_ENGINE_DRIVER_PREFIX, audioDriver), "", type=str)
  365. except:
  366. audioDevice = ""
  367. try:
  368. audioNumPeriods = settings.value("%s%s/NumPeriods" % (CARLA_KEY_ENGINE_DRIVER_PREFIX, audioDriver), CARLA_DEFAULT_AUDIO_NUM_PERIODS, type=int)
  369. except:
  370. audioNumPeriods = CARLA_DEFAULT_AUDIO_NUM_PERIODS
  371. try:
  372. audioBufferSize = settings.value("%s%s/BufferSize" % (CARLA_KEY_ENGINE_DRIVER_PREFIX, audioDriver), CARLA_DEFAULT_AUDIO_BUFFER_SIZE, type=int)
  373. except:
  374. audioBufferSize = CARLA_DEFAULT_AUDIO_BUFFER_SIZE
  375. try:
  376. audioSampleRate = settings.value("%s%s/SampleRate" % (CARLA_KEY_ENGINE_DRIVER_PREFIX, audioDriver), CARLA_DEFAULT_AUDIO_SAMPLE_RATE, type=int)
  377. except:
  378. audioSampleRate = CARLA_DEFAULT_AUDIO_SAMPLE_RATE
  379. if gCarla.processModeForced:
  380. processMode = gCarla.processMode
  381. # -------------------------------------------------------------
  382. # fix things if needed
  383. if processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK:
  384. forceStereo = True
  385. elif processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS and LADISH_APP_NAME:
  386. print("LADISH detected but using multiple clients (not allowed), forcing single client now")
  387. processMode = ENGINE_PROCESS_MODE_SINGLE_CLIENT
  388. if audioDriver != "JACK" and transportMode == ENGINE_TRANSPORT_MODE_JACK:
  389. transportMode = ENGINE_TRANSPORT_MODE_INTERNAL
  390. if gCarla.host is None:
  391. return audioDriver
  392. # -------------------------------------------------------------
  393. # apply to engine
  394. gCarla.host.set_engine_option(ENGINE_OPTION_FORCE_STEREO, forceStereo, "")
  395. gCarla.host.set_engine_option(ENGINE_OPTION_UIS_ALWAYS_ON_TOP, uisAlwaysOnTop, "")
  396. if not gCarla.isPlugin:
  397. gCarla.host.set_engine_option(ENGINE_OPTION_PREFER_PLUGIN_BRIDGES, preferPluginBridges, "")
  398. gCarla.host.set_engine_option(ENGINE_OPTION_PREFER_UI_BRIDGES, preferUiBridges, "")
  399. gCarla.host.set_engine_option(ENGINE_OPTION_MAX_PARAMETERS, maxParameters, "")
  400. gCarla.host.set_engine_option(ENGINE_OPTION_UI_BRIDGES_TIMEOUT, uiBridgesTimeout, "")
  401. gCarla.host.set_engine_option(ENGINE_OPTION_PROCESS_MODE, processMode, "")
  402. gCarla.host.set_engine_option(ENGINE_OPTION_TRANSPORT_MODE, transportMode, "")
  403. gCarla.host.set_engine_option(ENGINE_OPTION_AUDIO_NUM_PERIODS, audioNumPeriods, "")
  404. gCarla.host.set_engine_option(ENGINE_OPTION_AUDIO_BUFFER_SIZE, audioBufferSize, "")
  405. gCarla.host.set_engine_option(ENGINE_OPTION_AUDIO_SAMPLE_RATE, audioSampleRate, "")
  406. gCarla.host.set_engine_option(ENGINE_OPTION_AUDIO_DEVICE, 0, audioDevice)
  407. # save this for later
  408. gCarla.maxParameters = maxParameters
  409. # return selected driver name
  410. return audioDriver
  411. def startEngine(self):
  412. audioDriver = self.setEngineSettings()
  413. if gCarla.host is not None and not gCarla.host.engine_init(audioDriver, self.fClientName):
  414. if self.fFirstEngineInit:
  415. self.fFirstEngineInit = False
  416. return
  417. audioError = gCarla.host.get_last_error()
  418. if audioError:
  419. QMessageBox.critical(self, self.tr("Error"), self.tr("Could not connect to Audio backend '%s', possible reasons:\n%s" % (audioDriver, audioError)))
  420. else:
  421. QMessageBox.critical(self, self.tr("Error"), self.tr("Could not connect to Audio backend '%s'" % audioDriver))
  422. return
  423. self.fFirstEngineInit = False
  424. def stopEngine(self):
  425. if self.fContainer.getPluginCount() > 0:
  426. 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"
  427. "Do you want to do this now?"),
  428. QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
  429. if ask != QMessageBox.Yes:
  430. return
  431. self.ui.act_plugin_remove_all.setEnabled(False)
  432. self.fContainer.removeAllPlugins()
  433. if gCarla.host.is_engine_running() and not gCarla.host.engine_close():
  434. print(gCarla.host.get_last_error())
  435. # -----------------------------------------------------------------
  436. # Internal stuff (plugins)
  437. def getExtraPtr(self, plugin):
  438. ptype = plugin['type']
  439. if ptype == PLUGIN_LADSPA:
  440. uniqueId = plugin['uniqueId']
  441. self.maybeLoadRDFs()
  442. for rdfItem in self.fLadspaRdfList:
  443. if rdfItem.UniqueID == uniqueId:
  444. return pointer(rdfItem)
  445. elif ptype in (PLUGIN_GIG, PLUGIN_SF2):
  446. if plugin['name'].lower().endswith(" (16 outputs)"):
  447. return c_char_p("true".encode("utf-8"))
  448. return None
  449. def maybeLoadRDFs(self):
  450. if not self.fLadspaRdfNeedsUpdate:
  451. return
  452. self.fLadspaRdfNeedsUpdate = False
  453. self.fLadspaRdfList = []
  454. if not haveLRDF:
  455. return
  456. settingsDir = os.path.join(HOME, ".config", "falkTX")
  457. frLadspaFile = os.path.join(settingsDir, "ladspa_rdf.db")
  458. if os.path.exists(frLadspaFile):
  459. frLadspa = open(frLadspaFile, 'r')
  460. try:
  461. self.fLadspaRdfList = ladspa_rdf.get_c_ladspa_rdfs(json.load(frLadspa))
  462. except:
  463. pass
  464. frLadspa.close()
  465. def setLoadRDFsNeeded(self):
  466. self.fLadspaRdfNeedsUpdate = True
  467. # -----------------------------------------------------------------
  468. # Internal stuff (transport)
  469. def refreshTransport(self, forced = False):
  470. if gCarla.sampleRate == 0.0 or not gCarla.host.is_engine_running():
  471. return
  472. timeInfo = gCarla.host.get_transport_info()
  473. playing = bool(timeInfo['playing'])
  474. frame = int(timeInfo['frame'])
  475. if playing != self.fLastTransportState or forced:
  476. if playing:
  477. icon = getIcon("media-playback-pause")
  478. self.ui.act_transport_play.setChecked(True)
  479. self.ui.act_transport_play.setIcon(icon)
  480. self.ui.act_transport_play.setText(self.tr("&Pause"))
  481. else:
  482. icon = getIcon("media-playback-start")
  483. self.ui.act_transport_play.setChecked(False)
  484. self.ui.act_transport_play.setIcon(icon)
  485. self.ui.act_transport_play.setText(self.tr("&Play"))
  486. self.fLastTransportState = playing
  487. if frame != self.fLastTransportFrame or forced:
  488. time = frame / gCarla.sampleRate
  489. secs = time % 60
  490. mins = (time / 60) % 60
  491. hrs = (time / 3600) % 60
  492. self.fTextTransport = "Transport %s, at %02i:%02i:%02i" % ("playing" if playing else "stopped", hrs, mins, secs)
  493. self.fLastTransportFrame = frame
  494. def setTransportMenuEnabled(self, enabled):
  495. self.ui.act_transport_play.setEnabled(enabled)
  496. self.ui.act_transport_stop.setEnabled(enabled)
  497. self.ui.act_transport_backwards.setEnabled(enabled)
  498. self.ui.act_transport_forwards.setEnabled(enabled)
  499. self.ui.menu_Transport.setEnabled(enabled)
  500. # -----------------------------------------------------------------
  501. # Internal stuff (settings)
  502. def loadSettings(self, firstTime):
  503. settings = QSettings()
  504. if firstTime:
  505. self.restoreGeometry(settings.value("Geometry", ""))
  506. showToolbar = settings.value("ShowToolbar", True, type=bool)
  507. self.ui.act_settings_show_toolbar.setChecked(showToolbar)
  508. self.ui.toolBar.setVisible(showToolbar)
  509. if settings.contains("SplitterState"):
  510. self.ui.splitter.restoreState(settings.value("SplitterState", ""))
  511. else:
  512. self.ui.splitter.setSizes([210, 99999])
  513. diskFolders = toList(settings.value("DiskFolders", [HOME]))
  514. self.ui.cb_disk.setItemData(0, HOME)
  515. for i in range(len(diskFolders)):
  516. if i == 0: continue
  517. folder = diskFolders[i]
  518. self.ui.cb_disk.addItem(os.path.basename(folder), folder)
  519. #if MACOS and not settings.value(CARLA_KEY_MAIN_USE_PRO_THEME, True, type=bool):
  520. # self.setUnifiedTitleAndToolBarOnMac(True)
  521. # ---------------------------------------------
  522. if not gCarla.isPlugin:
  523. # engine
  524. self.setEngineSettings(settings)
  525. # plugin paths
  526. LADSPA_PATH = toList(settings.value("Paths/LADSPA", gCarla.DEFAULT_LADSPA_PATH))
  527. DSSI_PATH = toList(settings.value("Paths/DSSI", gCarla.DEFAULT_DSSI_PATH))
  528. LV2_PATH = toList(settings.value("Paths/LV2", gCarla.DEFAULT_LV2_PATH))
  529. VST_PATH = toList(settings.value("Paths/VST", gCarla.DEFAULT_VST_PATH))
  530. AU_PATH = toList(settings.value("Paths/AU", gCarla.DEFAULT_AU_PATH))
  531. GIG_PATH = toList(settings.value("Paths/GIG", gCarla.DEFAULT_GIG_PATH))
  532. SF2_PATH = toList(settings.value("Paths/SF2", gCarla.DEFAULT_SF2_PATH))
  533. SFZ_PATH = toList(settings.value("Paths/SFZ", gCarla.DEFAULT_SFZ_PATH))
  534. os.environ["LADSPA_PATH"] = splitter.join(LADSPA_PATH)
  535. os.environ["DSSI_PATH"] = splitter.join(DSSI_PATH)
  536. os.environ["LV2_PATH"] = splitter.join(LV2_PATH)
  537. os.environ["VST_PATH"] = splitter.join(VST_PATH)
  538. os.environ["AU_PATH"] = splitter.join(AU_PATH)
  539. os.environ["GIG_PATH"] = splitter.join(GIG_PATH)
  540. os.environ["SF2_PATH"] = splitter.join(SF2_PATH)
  541. os.environ["SFZ_PATH"] = splitter.join(SFZ_PATH)
  542. # ---------------------------------------------
  543. # TODO
  544. self.fSavedSettings = {
  545. CARLA_KEY_MAIN_PROJECT_FOLDER: settings.value(CARLA_KEY_MAIN_PROJECT_FOLDER, CARLA_DEFAULT_MAIN_PROJECT_FOLDER, type=str),
  546. CARLA_KEY_MAIN_REFRESH_INTERVAL: settings.value(CARLA_KEY_MAIN_REFRESH_INTERVAL, CARLA_DEFAULT_MAIN_REFRESH_INTERVAL, type=int),
  547. CARLA_KEY_CANVAS_THEME: settings.value(CARLA_KEY_CANVAS_THEME, CARLA_DEFAULT_CANVAS_THEME, type=str),
  548. CARLA_KEY_CANVAS_SIZE: settings.value(CARLA_KEY_CANVAS_SIZE, CARLA_DEFAULT_CANVAS_SIZE, type=str),
  549. CARLA_KEY_CANVAS_AUTO_HIDE_GROUPS: settings.value(CARLA_KEY_CANVAS_AUTO_HIDE_GROUPS, CARLA_DEFAULT_CANVAS_AUTO_HIDE_GROUPS, type=bool),
  550. CARLA_KEY_CANVAS_USE_BEZIER_LINES: settings.value(CARLA_KEY_CANVAS_USE_BEZIER_LINES, CARLA_DEFAULT_CANVAS_USE_BEZIER_LINES, type=bool),
  551. CARLA_KEY_CANVAS_EYE_CANDY: settings.value(CARLA_KEY_CANVAS_EYE_CANDY, CARLA_DEFAULT_CANVAS_EYE_CANDY, type=int),
  552. CARLA_KEY_CANVAS_USE_OPENGL: settings.value(CARLA_KEY_CANVAS_USE_OPENGL, CARLA_DEFAULT_CANVAS_USE_OPENGL, type=bool),
  553. CARLA_KEY_CANVAS_ANTIALIASING: settings.value(CARLA_KEY_CANVAS_ANTIALIASING, CARLA_DEFAULT_CANVAS_ANTIALIASING, type=int),
  554. CARLA_KEY_CANVAS_HQ_ANTIALIASING: settings.value(CARLA_KEY_CANVAS_HQ_ANTIALIASING, CARLA_DEFAULT_CANVAS_HQ_ANTIALIASING, type=bool),
  555. CARLA_KEY_CUSTOM_PAINTING: (settings.value(CARLA_KEY_MAIN_USE_PRO_THEME, True, type=bool) and
  556. settings.value(CARLA_KEY_MAIN_PRO_THEME_COLOR, "Black", type=str).lower() == "black")
  557. }
  558. # ---------------------------------------------
  559. if self.fIdleTimerFast != 0:
  560. self.killTimer(self.fIdleTimerFast)
  561. self.fIdleTimerFast = self.startTimer(self.fSavedSettings[CARLA_KEY_MAIN_REFRESH_INTERVAL])
  562. if self.fIdleTimerSlow != 0:
  563. self.killTimer(self.fIdleTimerSlow)
  564. self.fIdleTimerSlow = self.startTimer(self.fSavedSettings[CARLA_KEY_MAIN_REFRESH_INTERVAL]*4)
  565. def saveSettings(self):
  566. settings = QSettings()
  567. settings.setValue("Geometry", self.saveGeometry())
  568. settings.setValue("SplitterState", self.ui.splitter.saveState())
  569. settings.setValue("ShowToolbar", self.ui.toolBar.isVisible())
  570. diskFolders = []
  571. for i in range(self.ui.cb_disk.count()):
  572. diskFolders.append(self.ui.cb_disk.itemData(i))
  573. settings.setValue("DiskFolders", diskFolders)
  574. self.fContainer.saveSettings(settings)
  575. # -----------------------------------------------------------------
  576. # Internal stuff (gui)
  577. def killTimers(self):
  578. if self.fIdleTimerFast != 0:
  579. self.killTimer(self.fIdleTimerFast)
  580. self.fIdleTimerFast = 0
  581. if self.fIdleTimerSlow != 0:
  582. self.killTimer(self.fIdleTimerSlow)
  583. self.fIdleTimerSlow = 0
  584. def setProperWindowTitle(self):
  585. title = self.fClientName
  586. if self.fProjectFilename:
  587. title += " - %s" % os.path.basename(self.fProjectFilename)
  588. if self.fSessionManagerName:
  589. title += " (%s)" % self.fSessionManagerName
  590. self.setWindowTitle(title)
  591. # -----------------------------------------------------------------
  592. @pyqtSlot()
  593. def slot_fileNew(self):
  594. self.fContainer.removeAllPlugins()
  595. self.fProjectFilename = ""
  596. self.setProperWindowTitle()
  597. @pyqtSlot()
  598. def slot_fileOpen(self):
  599. fileFilter = self.tr("Carla Project File (*.carxp)")
  600. filenameTry = QFileDialog.getOpenFileName(self, self.tr("Open Carla Project File"), self.fSavedSettings[CARLA_KEY_MAIN_PROJECT_FOLDER], filter=fileFilter)
  601. if not filenameTry:
  602. return
  603. filename = filenameTry if isinstance(filenameTry, str) else filenameTry[0]
  604. newFile = True
  605. if self.fContainer.getPluginCount() > 0:
  606. ask = QMessageBox.question(self, self.tr("Question"), self.tr("There are some plugins loaded, do you want to remove them now?"),
  607. QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
  608. newFile = (ask == QMessageBox.Yes)
  609. if newFile:
  610. self.fContainer.removeAllPlugins()
  611. self.fProjectFilename = filename
  612. self.setProperWindowTitle()
  613. self.loadProjectNow()
  614. else:
  615. filenameOld = self.fProjectFilename
  616. self.fProjectFilename = filename
  617. self.loadProjectNow()
  618. self.fProjectFilename = filenameOld
  619. @pyqtSlot()
  620. def slot_fileSave(self, saveAs=False):
  621. if self.fProjectFilename and not saveAs:
  622. return self.saveProjectNow()
  623. fileFilter = self.tr("Carla Project File (*.carxp)")
  624. filenameTry = QFileDialog.getSaveFileName(self, self.tr("Save Carla Project File"), self.fSavedSettings[CARLA_KEY_MAIN_PROJECT_FOLDER], filter=fileFilter)
  625. if not filenameTry:
  626. return
  627. filename = filenameTry if isinstance(filenameTry, str) else filenameTry[0]
  628. if not filename.endswith(".carxp"):
  629. filename += ".carxp"
  630. if self.fProjectFilename != filename:
  631. self.fProjectFilename = filename
  632. self.setProperWindowTitle()
  633. self.saveProjectNow()
  634. @pyqtSlot()
  635. def slot_fileSaveAs(self):
  636. self.slot_fileSave(True)
  637. # -----------------------------------------------------------------
  638. @pyqtSlot()
  639. def slot_engineStart(self, doStart = True):
  640. if doStart: self.startEngine()
  641. check = gCarla.host is not None and gCarla.host.is_engine_running()
  642. self.ui.menu_PluginMacros.setEnabled(check)
  643. self.ui.menu_Canvas.setEnabled(check)
  644. if not gCarla.isPlugin:
  645. self.ui.act_engine_start.setEnabled(not check)
  646. self.ui.act_engine_stop.setEnabled(check)
  647. if not self.fSessionManagerName:
  648. self.ui.act_file_open.setEnabled(check)
  649. self.ui.act_file_save.setEnabled(check)
  650. self.ui.act_file_save_as.setEnabled(check)
  651. self.setTransportMenuEnabled(check)
  652. if check:
  653. if not gCarla.isPlugin:
  654. self.refreshTransport(True)
  655. self.fContainer.engineStarted()
  656. @pyqtSlot()
  657. def slot_engineStop(self, doStop = True):
  658. if doStop: self.stopEngine()
  659. # FIXME?
  660. if self.fContainer.getPluginCount() > 0:
  661. self.ui.act_plugin_remove_all.setEnabled(False)
  662. self.fContainer.removeAllPlugins()
  663. check = gCarla.host.is_engine_running()
  664. self.ui.menu_PluginMacros.setEnabled(check)
  665. self.ui.menu_Canvas.setEnabled(check)
  666. if not gCarla.isPlugin:
  667. self.ui.act_engine_start.setEnabled(not check)
  668. self.ui.act_engine_stop.setEnabled(check)
  669. if not self.fSessionManagerName:
  670. self.ui.act_file_open.setEnabled(check)
  671. self.ui.act_file_save.setEnabled(check)
  672. self.ui.act_file_save_as.setEnabled(check)
  673. self.setTransportMenuEnabled(check)
  674. if not check:
  675. self.fTextTransport = ""
  676. self.fContainer.engineStopped()
  677. # -----------------------------------------------------------------
  678. @pyqtSlot()
  679. def slot_pluginAdd(self, pluginToReplace = -1):
  680. dialog = PluginDatabaseW(self)
  681. if not dialog.exec_():
  682. return
  683. if gCarla.host is not None and not gCarla.host.is_engine_running():
  684. QMessageBox.warning(self, self.tr("Warning"), self.tr("Cannot add new plugins while engine is stopped"))
  685. return
  686. btype = dialog.fRetPlugin['build']
  687. ptype = dialog.fRetPlugin['type']
  688. filename = dialog.fRetPlugin['filename']
  689. label = dialog.fRetPlugin['label']
  690. uniqueId = dialog.fRetPlugin['uniqueId']
  691. extraPtr = self.getExtraPtr(dialog.fRetPlugin)
  692. if pluginToReplace >= 0:
  693. if not gCarla.host.replace_plugin(pluginToReplace):
  694. CustomMessageBox(self, QMessageBox.Critical, self.tr("Error"), self.tr("Failed to replace plugin"), gCarla.host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  695. return
  696. ok = gCarla.host.add_plugin(btype, ptype, filename, None, label, uniqueId, extraPtr)
  697. if pluginToReplace >= 0:
  698. gCarla.host.replace_plugin(self.fContainer.getPluginCount())
  699. if not ok:
  700. CustomMessageBox(self, QMessageBox.Critical, self.tr("Error"), self.tr("Failed to load plugin"), gCarla.host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  701. @pyqtSlot()
  702. def slot_pluginRemoveAll(self):
  703. self.ui.act_plugin_remove_all.setEnabled(False)
  704. count = self.fContainer.getPluginCount()
  705. if count == 0:
  706. return
  707. self.fContainer.projectLoadingStarted()
  708. app = QApplication.instance()
  709. for i in range(count):
  710. app.processEvents()
  711. gCarla.host.remove_plugin(count-i-1)
  712. self.fContainer.projectLoadingFinished()
  713. #self.fContainer.removeAllPlugins()
  714. #gCarla.host.remove_all_plugins()
  715. # -----------------------------------------------------------------
  716. @pyqtSlot(bool)
  717. def slot_transportPlayPause(self, toggled):
  718. if not gCarla.host.is_engine_running():
  719. return
  720. if toggled:
  721. gCarla.host.transport_play()
  722. else:
  723. gCarla.host.transport_pause()
  724. self.refreshTransport()
  725. @pyqtSlot()
  726. def slot_transportStop(self):
  727. if not gCarla.host.is_engine_running():
  728. return
  729. gCarla.host.transport_pause()
  730. gCarla.host.transport_relocate(0)
  731. self.refreshTransport()
  732. @pyqtSlot()
  733. def slot_transportBackwards(self):
  734. if not gCarla.host.is_engine_running():
  735. return
  736. newFrame = gCarla.host.get_current_transport_frame() - 100000
  737. if newFrame < 0:
  738. newFrame = 0
  739. gCarla.host.transport_relocate(newFrame)
  740. @pyqtSlot()
  741. def slot_transportForwards(self):
  742. if not gCarla.host.is_engine_running():
  743. return
  744. newFrame = gCarla.host.get_current_transport_frame() + 100000
  745. gCarla.host.transport_relocate(newFrame)
  746. # -----------------------------------------------------------------
  747. @pyqtSlot()
  748. def slot_aboutCarla(self):
  749. CarlaAboutW(self).exec_()
  750. @pyqtSlot()
  751. def slot_aboutQt(self):
  752. QApplication.instance().aboutQt()
  753. # -----------------------------------------------------------------
  754. @pyqtSlot(int)
  755. def slot_diskFolderChanged(self, index):
  756. if index < 0:
  757. return
  758. elif index == 0:
  759. filename = HOME
  760. self.ui.b_disk_remove.setEnabled(False)
  761. else:
  762. filename = self.ui.cb_disk.itemData(index)
  763. self.ui.b_disk_remove.setEnabled(True)
  764. self.fDirModel.setRootPath(filename)
  765. self.ui.fileTreeView.setRootIndex(self.fDirModel.index(filename))
  766. @pyqtSlot()
  767. def slot_diskFolderAdd(self):
  768. newPath = QFileDialog.getExistingDirectory(self, self.tr("New Folder"), "", QFileDialog.ShowDirsOnly)
  769. if newPath:
  770. if newPath[-1] == os.sep:
  771. newPath = newPath[:-1]
  772. self.ui.cb_disk.addItem(os.path.basename(newPath), newPath)
  773. self.ui.cb_disk.setCurrentIndex(self.ui.cb_disk.count()-1)
  774. self.ui.b_disk_remove.setEnabled(True)
  775. @pyqtSlot()
  776. def slot_diskFolderRemove(self):
  777. index = self.ui.cb_disk.currentIndex()
  778. if index <= 0:
  779. return
  780. self.ui.cb_disk.removeItem(index)
  781. if self.ui.cb_disk.currentIndex() == 0:
  782. self.ui.b_disk_remove.setEnabled(False)
  783. @pyqtSlot(QModelIndex)
  784. def slot_fileTreeDoubleClicked(self, modelIndex):
  785. filename = self.fDirModel.filePath(modelIndex)
  786. if not gCarla.host.load_file(filename):
  787. CustomMessageBox(self, QMessageBox.Critical, self.tr("Error"),
  788. self.tr("Failed to load file"),
  789. gCarla.host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  790. # -----------------------------------------------------------------
  791. @pyqtSlot(int, int, int, float, str)
  792. def slot_handleDebugCallback(self, pluginId, value1, value2, value3, valueStr):
  793. print("DEBUG:", pluginId, value1, value2, value3, valueStr)
  794. #self.ui.pte_log.appendPlainText(valueStr.replace("", "DEBUG: ").replace("", "ERROR: ").replace("", "").replace("\n", ""))
  795. # -----------------------------------------------------------------
  796. @pyqtSlot(int, str)
  797. def slot_handlePluginAddedCallback(self, pluginId, pluginName):
  798. self.fContainer.addPlugin(pluginId, self.fIsProjectLoading)
  799. if self.fContainer.getPluginCount() == 1:
  800. self.ui.act_plugin_remove_all.setEnabled(True)
  801. @pyqtSlot(int)
  802. def slot_handlePluginRemovedCallback(self, pluginId):
  803. self.fContainer.removePlugin(pluginId)
  804. if self.fContainer.getPluginCount() == 0:
  805. self.ui.act_plugin_remove_all.setEnabled(False)
  806. @pyqtSlot(int, str)
  807. def slot_handlePluginRenamedCallback(self, pluginId, newName):
  808. self.fContainer.renamePlugin(pluginId, newName)
  809. @pyqtSlot(int, str)
  810. def slot_handlePluginUnavailableCallback(self, pluginId, errorMsg):
  811. self.fContainer.disablePlugin(pluginId, errorMsg)
  812. # -----------------------------------------------------------------
  813. @pyqtSlot(str)
  814. def slot_handleEngineStartedCallback(self, processMode, transportMode, driverName):
  815. gCarla.processMode = processMode
  816. gCarla.transportMode = transportMode
  817. gCarla.bufferSize = gCarla.host.get_buffer_size()
  818. gCarla.sampleRate = gCarla.host.get_sample_rate()
  819. self.slot_engineStart(False)
  820. if self.fIdleTimerFast == 0:
  821. self.fIdleTimerFast = self.startTimer(self.fSavedSettings[CARLA_KEY_MAIN_REFRESH_INTERVAL])
  822. if self.fIdleTimerSlow == 0:
  823. self.fIdleTimerSlow = self.startTimer(self.fSavedSettings[CARLA_KEY_MAIN_REFRESH_INTERVAL]*4)
  824. @pyqtSlot()
  825. def slot_handleEngineStoppedCallback(self):
  826. self.killTimers()
  827. self.slot_engineStop(False)
  828. gCarla.bufferSize = 0
  829. gCarla.sampleRate = 0.0
  830. # -----------------------------------------------------------------
  831. @pyqtSlot(int)
  832. def slot_handleProcessModeChangedCallback(self, newProcessMode):
  833. self.fEngineChanged = True
  834. @pyqtSlot(int)
  835. def slot_handleTransportModeChangedCallback(self, newTransportMode):
  836. self.fEngineChanged = True
  837. # -----------------------------------------------------------------
  838. @pyqtSlot(int)
  839. def slot_handleBufferSizeChangedCallback(self, newBufferSize):
  840. self.fEngineChanged = True
  841. @pyqtSlot(float)
  842. def slot_handleSampleRateChangedCallback(self, newSampleRate):
  843. self.fEngineChanged = True
  844. # -----------------------------------------------------------------
  845. @pyqtSlot(str)
  846. def slot_handleInfoCallback(self, info):
  847. QMessageBox.information(self, "Information", info)
  848. @pyqtSlot(str)
  849. def slot_handleErrorCallback(self, error):
  850. QMessageBox.critical(self, "Error", error)
  851. @pyqtSlot()
  852. def slot_handleQuitCallback(self):
  853. pass
  854. # -----------------------------------------------------------------
  855. @pyqtSlot()
  856. def slot_handleSIGUSR1(self):
  857. print("Got SIGUSR1 -> Saving project now")
  858. QTimer.singleShot(0, self.slot_fileSave)
  859. @pyqtSlot()
  860. def slot_handleSIGTERM(self):
  861. print("Got SIGTERM -> Closing now")
  862. self.close()
  863. # -----------------------------------------------------------------
  864. def showEvent(self, event):
  865. QMainWindow.showEvent(self, event)
  866. # set our gui as parent for all plugins UIs
  867. if gCarla.host is not None:
  868. gCarla.host.set_engine_option(ENGINE_OPTION_FRONTEND_WIN_ID, 0, "%x" % self.winId())
  869. def timerEvent(self, event):
  870. if event.timerId() == self.fIdleTimerFast:
  871. #if not gCarla.isPlugin:
  872. gCarla.host.engine_idle()
  873. self.refreshTransport()
  874. self.fContainer.idleFast()
  875. elif event.timerId() == self.fIdleTimerSlow:
  876. if self.fEngineChanged:
  877. self.fContainer.engineChanged()
  878. self.fEngineChanged = False
  879. self.fContainer.idleSlow()
  880. QMainWindow.timerEvent(self, event)
  881. def closeEvent(self, event):
  882. self.killTimers()
  883. self.saveSettings()
  884. if gCarla.host is None or gCarla.isPlugin:
  885. pass
  886. elif gCarla.host.is_engine_running():
  887. gCarla.host.set_engine_about_to_close()
  888. count = self.fContainer.getPluginCount()
  889. if count > 0:
  890. # simulate project loading, to disable container
  891. self.ui.act_plugin_remove_all.setEnabled(False)
  892. self.fContainer.projectLoadingStarted()
  893. app = QApplication.instance()
  894. for i in range(count):
  895. app.processEvents()
  896. gCarla.host.remove_plugin(count-i-1)
  897. app.processEvents()
  898. #self.fContainer.removeAllPlugins()
  899. #gCarla.host.remove_all_plugins()
  900. self.stopEngine()
  901. QMainWindow.closeEvent(self, event)
  902. # ------------------------------------------------------------------------------------------------------------
  903. # Engine callback
  904. def engineCallback(ptr, action, pluginId, value1, value2, value3, valueStr):
  905. if action == ENGINE_CALLBACK_PROCESS_MODE_CHANGED:
  906. gCarla.processMode = value1
  907. if gCarla.gui is not None:
  908. gCarla.gui.ProcessModeChangedCallback.emit(value1)
  909. return
  910. if action == ENGINE_CALLBACK_TRANSPORT_MODE_CHANGED:
  911. gCarla.transportMode = value1
  912. if gCarla.gui is not None:
  913. gCarla.gui.TransportModeChangedCallback.emit(value1)
  914. return
  915. if action == ENGINE_CALLBACK_BUFFER_SIZE_CHANGED:
  916. gCarla.bufferSize = value1
  917. if gCarla.gui is not None:
  918. gCarla.gui.BufferSizeChangedCallback.emit(value1)
  919. return
  920. if action == ENGINE_CALLBACK_SAMPLE_RATE_CHANGED:
  921. gCarla.sampleRate = value1
  922. if gCarla.gui is not None:
  923. gCarla.gui.SampleRateChangedCallback.emit(value3)
  924. return
  925. if gCarla.gui is None:
  926. print("WARNING: Got engine callback but UI is not ready : ", pluginId, value1, value2, value3, valueStr)
  927. return
  928. valueStr = charPtrToString(valueStr)
  929. if action == ENGINE_CALLBACK_DEBUG:
  930. gCarla.gui.DebugCallback.emit(pluginId, value1, value2, value3, valueStr)
  931. elif action == ENGINE_CALLBACK_PLUGIN_ADDED:
  932. gCarla.gui.PluginAddedCallback.emit(pluginId, valueStr)
  933. elif action == ENGINE_CALLBACK_PLUGIN_REMOVED:
  934. gCarla.gui.PluginRemovedCallback.emit(pluginId)
  935. elif action == ENGINE_CALLBACK_PLUGIN_RENAMED:
  936. gCarla.gui.PluginRenamedCallback.emit(pluginId, valueStr)
  937. elif action == ENGINE_CALLBACK_PLUGIN_UNAVAILABLE:
  938. gCarla.gui.PluginUnavailableCallback.emit(pluginId, valueStr)
  939. elif action == ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED:
  940. gCarla.gui.ParameterValueChangedCallback.emit(pluginId, value1, value3)
  941. elif action == ENGINE_CALLBACK_PARAMETER_DEFAULT_CHANGED:
  942. gCarla.gui.ParameterDefaultChangedCallback.emit(pluginId, value1, value3)
  943. elif action == ENGINE_CALLBACK_PARAMETER_MIDI_CC_CHANGED:
  944. gCarla.gui.ParameterMidiCcChangedCallback.emit(pluginId, value1, value2)
  945. elif action == ENGINE_CALLBACK_PARAMETER_MIDI_CHANNEL_CHANGED:
  946. gCarla.gui.ParameterMidiChannelChangedCallback.emit(pluginId, value1, value2)
  947. elif action == ENGINE_CALLBACK_PROGRAM_CHANGED:
  948. gCarla.gui.ProgramChangedCallback.emit(pluginId, value1)
  949. elif action == ENGINE_CALLBACK_MIDI_PROGRAM_CHANGED:
  950. gCarla.gui.MidiProgramChangedCallback.emit(pluginId, value1)
  951. elif action == ENGINE_CALLBACK_OPTION_CHANGED:
  952. gCarla.gui.OptionChangedCallback.emit(pluginId, value1, bool(value2))
  953. elif action == ENGINE_CALLBACK_UI_STATE_CHANGED:
  954. gCarla.gui.UiStateChangedCallback.emit(pluginId, value1)
  955. elif action == ENGINE_CALLBACK_NOTE_ON:
  956. gCarla.gui.NoteOnCallback.emit(pluginId, value1, value2, int(value3))
  957. elif action == ENGINE_CALLBACK_NOTE_OFF:
  958. gCarla.gui.NoteOffCallback.emit(pluginId, value1, value2)
  959. elif action == ENGINE_CALLBACK_UPDATE:
  960. gCarla.gui.UpdateCallback.emit(pluginId)
  961. elif action == ENGINE_CALLBACK_RELOAD_INFO:
  962. gCarla.gui.ReloadInfoCallback.emit(pluginId)
  963. elif action == ENGINE_CALLBACK_RELOAD_PARAMETERS:
  964. gCarla.gui.ReloadParametersCallback.emit(pluginId)
  965. elif action == ENGINE_CALLBACK_RELOAD_PROGRAMS:
  966. gCarla.gui.ReloadProgramsCallback.emit(pluginId)
  967. elif action == ENGINE_CALLBACK_RELOAD_ALL:
  968. gCarla.gui.ReloadAllCallback.emit(pluginId)
  969. elif action == ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED:
  970. gCarla.gui.PatchbayClientAddedCallback.emit(pluginId, value1, value2, valueStr)
  971. elif action == ENGINE_CALLBACK_PATCHBAY_CLIENT_REMOVED:
  972. gCarla.gui.PatchbayClientRemovedCallback.emit(pluginId)
  973. elif action == ENGINE_CALLBACK_PATCHBAY_CLIENT_RENAMED:
  974. gCarla.gui.PatchbayClientRenamedCallback.emit(pluginId, valueStr)
  975. elif action == ENGINE_CALLBACK_PATCHBAY_CLIENT_DATA_CHANGED:
  976. gCarla.gui.PatchbayClientDataChangedCallback.emit(pluginId, value1, value2)
  977. elif action == ENGINE_CALLBACK_PATCHBAY_PORT_ADDED:
  978. gCarla.gui.PatchbayPortAddedCallback.emit(pluginId, value1, value2, valueStr)
  979. elif action == ENGINE_CALLBACK_PATCHBAY_PORT_REMOVED:
  980. gCarla.gui.PatchbayPortRemovedCallback.emit(pluginId, value1)
  981. elif action == ENGINE_CALLBACK_PATCHBAY_PORT_RENAMED:
  982. gCarla.gui.PatchbayPortRenamedCallback.emit(pluginId, value1, valueStr)
  983. elif action == ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED:
  984. gOut, pOut, gIn, pIn = [int(i) for i in valueStr.split(":")]
  985. gCarla.gui.PatchbayConnectionAddedCallback.emit(pluginId, gOut, pOut, gIn, pIn)
  986. elif action == ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED:
  987. gCarla.gui.PatchbayConnectionRemovedCallback.emit(pluginId, value1, value2)
  988. elif action == ENGINE_CALLBACK_ENGINE_STARTED:
  989. gCarla.gui.EngineStartedCallback.emit(value1, value2, valueStr)
  990. elif action == ENGINE_CALLBACK_ENGINE_STOPPED:
  991. gCarla.gui.killTimers()
  992. gCarla.gui.EngineStoppedCallback.emit()
  993. elif action == ENGINE_CALLBACK_IDLE:
  994. QApplication.instance().processEvents()
  995. elif action == ENGINE_CALLBACK_INFO:
  996. gCarla.gui.InfoCallback.emit(valueStr)
  997. elif action == ENGINE_CALLBACK_ERROR:
  998. gCarla.gui.ErrorCallback.emit(valueStr)
  999. elif action == ENGINE_CALLBACK_QUIT:
  1000. gCarla.gui.QuitCallback.emit()
  1001. # ------------------------------------------------------------------------------------------------------------
  1002. # File callback
  1003. def fileCallback(ptr, action, isDir, title, filter):
  1004. if gCarla.gui is None:
  1005. return None
  1006. ret = ""
  1007. if action == FILE_CALLBACK_DEBUG:
  1008. pass
  1009. elif action == FILE_CALLBACK_OPEN:
  1010. ret = QFileDialog.getOpenFileName(gCarla.gui, charPtrToString(title), "", charPtrToString(filter) ) #, QFileDialog.ShowDirsOnly if isDir else 0x0)
  1011. elif action == FILE_CALLBACK_SAVE:
  1012. ret = QFileDialog.getSaveFileName(gCarla.gui, charPtrToString(title), "", charPtrToString(filter), QFileDialog.ShowDirsOnly if isDir else 0x0)
  1013. if not ret:
  1014. return None
  1015. gCarla.gui._fileRet = c_char_p(ret.encode("utf-8"))
  1016. retval = cast(byref(gCarla.gui._fileRet), POINTER(c_uintptr))
  1017. return retval.contents.value