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.

3056 lines
119KB

  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Carla host code
  4. # Copyright (C) 2011-2019 Filipe Coelho <falktx@falktx.com>
  5. #
  6. # This program is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU General Public License as
  8. # published by the Free Software Foundation; either version 2 of
  9. # the License, or any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # For a full copy of the GNU General Public License see the doc/GPL.txt file.
  17. # ------------------------------------------------------------------------------------------------------------
  18. # Imports (Global)
  19. import json
  20. from PyQt5.Qt import PYQT_VERSION
  21. from PyQt5.QtCore import qCritical, QEventLoop, QFileInfo, QModelIndex, QPointF, QTimer, QEvent
  22. from PyQt5.QtGui import QImage, QPalette, QBrush
  23. from PyQt5.QtWidgets import QAction, QApplication, QInputDialog, QFileSystemModel, QListWidgetItem, QMainWindow
  24. # ------------------------------------------------------------------------------------------------------------
  25. # Imports (Custom)
  26. import ui_carla_host
  27. from carla_app import *
  28. from carla_database import *
  29. from carla_settings import *
  30. from carla_utils import *
  31. from carla_widgets import *
  32. from patchcanvas import patchcanvas
  33. from widgets.digitalpeakmeter import DigitalPeakMeter
  34. from widgets.pixmapkeyboard import PixmapKeyboardHArea
  35. # ------------------------------------------------------------------------------------------------------------
  36. # Try Import OpenGL
  37. try:
  38. from PyQt5.QtOpenGL import QGLWidget
  39. hasGL = True
  40. except:
  41. hasGL = False
  42. # ------------------------------------------------------------------------------------------------------------
  43. # Safe exception hook, needed for PyQt5
  44. def sys_excepthook(typ, value, tback):
  45. return sys.__excepthook__(typ, value, tback)
  46. # ------------------------------------------------------------------------------------------------------------
  47. # Session Management support
  48. CARLA_CLIENT_NAME = os.getenv("CARLA_CLIENT_NAME")
  49. LADISH_APP_NAME = os.getenv("LADISH_APP_NAME")
  50. NSM_URL = os.getenv("NSM_URL")
  51. # ------------------------------------------------------------------------------------------------------------
  52. # Small print helper
  53. def processMode2Str(processMode):
  54. if processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT:
  55. return "Single client"
  56. if processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS:
  57. return "Multi client"
  58. if processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK:
  59. return "Continuous Rack"
  60. if processMode == ENGINE_PROCESS_MODE_PATCHBAY:
  61. return "Patchbay"
  62. if processMode == ENGINE_PROCESS_MODE_BRIDGE:
  63. return "Bridge"
  64. return "Unknown"
  65. # ------------------------------------------------------------------------------------------------------------
  66. # Carla Print class
  67. class CarlaPrint:
  68. def __init__(self, err):
  69. self.err = err
  70. def flush(self):
  71. gCarla.utils.fflush(self.err)
  72. def write(self, string):
  73. gCarla.utils.fputs(self.err, string)
  74. # ------------------------------------------------------------------------------------------------------------
  75. # Host Window
  76. class HostWindow(QMainWindow):
  77. #class HostWindow(QMainWindow, PluginEditParentMeta, metaclass=PyQtMetaClass):
  78. # signals
  79. SIGTERM = pyqtSignal()
  80. SIGUSR1 = pyqtSignal()
  81. # CustomActions
  82. CUSTOM_ACTION_NONE = 0
  83. CUSTOM_ACTION_APP_CLOSE = 1
  84. CUSTOM_ACTION_PROJECT_LOAD = 2
  85. # --------------------------------------------------------------------------------------------------------
  86. def __init__(self, host, withCanvas, parent=None):
  87. QMainWindow.__init__(self, parent)
  88. self.host = host
  89. self.ui = ui_carla_host.Ui_CarlaHostW()
  90. self.ui.setupUi(self)
  91. gCarla.gui = self
  92. if False:
  93. # kdevelop likes this :)
  94. host = CarlaHostNull()
  95. self.host = host
  96. self._true = c_char_p("true".encode("utf-8"))
  97. self.fParentOrSelf = parent or self
  98. # ----------------------------------------------------------------------------------------------------
  99. # Internal stuff
  100. self.fIdleTimerFast = 0
  101. self.fIdleTimerSlow = 0
  102. self.fLadspaRdfNeedsUpdate = True
  103. self.fLadspaRdfList = []
  104. self.fPluginCount = 0
  105. self.fPluginList = []
  106. self.fProjectFilename = ""
  107. self.fIsProjectLoading = False
  108. self.fCurrentlyRemovingAllPlugins = False
  109. self.fLastTransportBPM = 0.0
  110. self.fLastTransportFrame = 0
  111. self.fLastTransportState = False
  112. self.fSampleRate = 0.0
  113. if MACOS:
  114. self.fMacClosingHelper = True
  115. # CancelableActionCallback Box
  116. self.fCancelableActionBox = None
  117. # run a custom action after engine is properly closed
  118. self.fCustomStopAction = self.CUSTOM_ACTION_NONE
  119. # first attempt of auto-start engine doesn't show an error
  120. self.fFirstEngineInit = True
  121. # to be filled with key-value pairs of current settings
  122. self.fSavedSettings = {}
  123. if host.isControl:
  124. self.fClientName = "Carla-Control"
  125. self.fSessionManagerName = "Control"
  126. elif host.isPlugin:
  127. self.fClientName = "Carla-Plugin"
  128. self.fSessionManagerName = "Plugin"
  129. elif LADISH_APP_NAME:
  130. self.fClientName = LADISH_APP_NAME
  131. self.fSessionManagerName = "LADISH"
  132. elif NSM_URL and host.nsmOK:
  133. self.fClientName = "Carla.tmp"
  134. self.fSessionManagerName = "Non Session Manager TMP"
  135. else:
  136. self.fClientName = CARLA_CLIENT_NAME or "Carla"
  137. self.fSessionManagerName = ""
  138. # ----------------------------------------------------------------------------------------------------
  139. # Internal stuff (patchbay)
  140. self.fExportImage = QImage()
  141. self.fPeaksCleared = True
  142. self.fExternalPatchbay = False
  143. self.fSelectedPlugins = []
  144. self.fCanvasWidth = 0
  145. self.fCanvasHeight = 0
  146. self.fMiniCanvasUpdateTimeout = 0
  147. self.fWithCanvas = withCanvas
  148. # ----------------------------------------------------------------------------------------------------
  149. # Set up GUI (engine stopped)
  150. if self.host.isPlugin or self.host.isControl:
  151. self.ui.act_file_save.setVisible(False)
  152. self.ui.act_engine_start.setEnabled(False)
  153. self.ui.act_engine_start.setVisible(False)
  154. self.ui.act_engine_stop.setEnabled(False)
  155. self.ui.act_engine_stop.setVisible(False)
  156. self.ui.menu_Engine.setEnabled(False)
  157. self.ui.menu_Engine.setVisible(False)
  158. self.ui.menu_Engine.menuAction().setVisible(False)
  159. self.ui.tabWidget.removeTab(2)
  160. if self.host.isControl:
  161. self.ui.act_file_new.setVisible(False)
  162. self.ui.act_file_open.setVisible(False)
  163. self.ui.act_file_save.setVisible(False)
  164. self.ui.act_file_save_as.setVisible(False)
  165. self.ui.act_plugin_add.setVisible(False)
  166. self.ui.act_plugin_add2.setVisible(False)
  167. self.ui.act_plugin_add_jack.setVisible(False)
  168. self.ui.act_plugin_remove_all.setVisible(False)
  169. self.ui.act_add_jack.setVisible(False)
  170. self.ui.menu_Plugin.setEnabled(False)
  171. self.ui.menu_Plugin.setVisible(False)
  172. self.ui.menu_Plugin.menuAction().setVisible(False)
  173. else:
  174. self.ui.act_file_save_as.setText(self.tr("Export as..."))
  175. else:
  176. self.ui.act_engine_start.setEnabled(True)
  177. if WINDOWS:
  178. self.ui.tabWidget.removeTab(2)
  179. if not self.host.isControl:
  180. self.ui.act_file_connect.setEnabled(False)
  181. self.ui.act_file_connect.setVisible(False)
  182. self.ui.act_file_refresh.setEnabled(False)
  183. self.ui.act_file_refresh.setVisible(False)
  184. if self.fSessionManagerName and not self.host.isPlugin:
  185. self.ui.act_file_new.setEnabled(False)
  186. self.ui.act_file_open.setEnabled(False)
  187. self.ui.act_file_save.setEnabled(False)
  188. self.ui.act_file_save_as.setEnabled(False)
  189. self.ui.act_engine_stop.setEnabled(False)
  190. self.ui.act_plugin_remove_all.setEnabled(False)
  191. self.ui.act_canvas_show_internal.setChecked(False)
  192. self.ui.act_canvas_show_internal.setVisible(False)
  193. self.ui.act_canvas_show_external.setChecked(False)
  194. self.ui.act_canvas_show_external.setVisible(False)
  195. self.ui.menu_PluginMacros.setEnabled(False)
  196. self.ui.menu_Canvas.setEnabled(False)
  197. self.ui.dockWidgetTitleBar = QWidget(self)
  198. self.ui.dockWidget.setTitleBarWidget(self.ui.dockWidgetTitleBar)
  199. if not withCanvas:
  200. self.ui.act_canvas_show_internal.setVisible(False)
  201. self.ui.act_canvas_show_external.setVisible(False)
  202. self.ui.act_canvas_arrange.setVisible(False)
  203. self.ui.act_canvas_refresh.setVisible(False)
  204. self.ui.act_canvas_save_image.setVisible(False)
  205. self.ui.act_canvas_zoom_100.setVisible(False)
  206. self.ui.act_canvas_zoom_fit.setVisible(False)
  207. self.ui.act_canvas_zoom_in.setVisible(False)
  208. self.ui.act_canvas_zoom_out.setVisible(False)
  209. self.ui.act_settings_show_meters.setVisible(False)
  210. self.ui.act_settings_show_keyboard.setVisible(False)
  211. self.ui.menu_Canvas_Zoom.setEnabled(False)
  212. self.ui.menu_Canvas_Zoom.setVisible(False)
  213. self.ui.menu_Canvas_Zoom.menuAction().setVisible(False)
  214. self.ui.menu_Canvas.setEnabled(False)
  215. self.ui.menu_Canvas.setVisible(False)
  216. self.ui.menu_Canvas.menuAction().setVisible(False)
  217. self.ui.miniCanvasPreview.hide()
  218. self.ui.tabWidget.removeTab(1)
  219. if WINDOWS:
  220. self.ui.tabWidget.tabBar().hide()
  221. if host.isControl:
  222. self.ui.dockWidget.hide()
  223. # ----------------------------------------------------------------------------------------------------
  224. # Set up GUI (disk)
  225. exts = gCarla.utils.get_supported_file_extensions()
  226. self.fDirModel = QFileSystemModel(self)
  227. self.fDirModel.setRootPath(HOME)
  228. self.fDirModel.setNameFilters(tuple(("*." + i) for i in exts))
  229. self.ui.fileTreeView.setModel(self.fDirModel)
  230. self.ui.fileTreeView.setRootIndex(self.fDirModel.index(HOME))
  231. self.ui.fileTreeView.setColumnHidden(1, True)
  232. self.ui.fileTreeView.setColumnHidden(2, True)
  233. self.ui.fileTreeView.setColumnHidden(3, True)
  234. self.ui.fileTreeView.setHeaderHidden(True)
  235. # ----------------------------------------------------------------------------------------------------
  236. # Set up GUI (transport)
  237. fontMetrics = QFontMetrics(self.ui.l_transport_bbt.font())
  238. minValueWidth = fontMetrics.width("000|00|0000")
  239. minLabelWidth = fontMetrics.width(self.ui.label_transport_frame.text())
  240. labelTimeWidth = fontMetrics.width(self.ui.label_transport_time.text())
  241. labelBBTWidth = fontMetrics.width(self.ui.label_transport_bbt.text())
  242. if minLabelWidth < labelTimeWidth:
  243. minLabelWidth = labelTimeWidth
  244. if minLabelWidth < labelBBTWidth:
  245. minLabelWidth = labelBBTWidth
  246. self.ui.label_transport_frame.setMinimumWidth(minLabelWidth + 3)
  247. self.ui.label_transport_time.setMinimumWidth(minLabelWidth + 3)
  248. self.ui.label_transport_bbt.setMinimumWidth(minLabelWidth + 3)
  249. self.ui.l_transport_bbt.setMinimumWidth(minValueWidth + 3)
  250. self.ui.l_transport_frame.setMinimumWidth(minValueWidth + 3)
  251. self.ui.l_transport_time.setMinimumWidth(minValueWidth + 3)
  252. if host.isControl or host.isPlugin:
  253. self.ui.b_transport_play.setEnabled(False)
  254. self.ui.b_transport_stop.setEnabled(False)
  255. self.ui.b_transport_backwards.setEnabled(False)
  256. self.ui.b_transport_forwards.setEnabled(False)
  257. self.ui.group_transport_controls.setEnabled(False)
  258. self.ui.group_transport_controls.setVisible(False)
  259. self.ui.cb_transport_link.setEnabled(False)
  260. self.ui.cb_transport_link.setVisible(False)
  261. self.ui.cb_transport_jack.setEnabled(False)
  262. self.ui.cb_transport_jack.setVisible(False)
  263. self.ui.dsb_transport_bpm.setEnabled(False)
  264. self.ui.dsb_transport_bpm.setReadOnly(True)
  265. self.ui.w_transport.setEnabled(False)
  266. # ----------------------------------------------------------------------------------------------------
  267. # Set up GUI (rack)
  268. self.ui.listWidget.setHostAndParent(self.host, self)
  269. sb = self.ui.listWidget.verticalScrollBar()
  270. self.ui.rackScrollBar.setMinimum(sb.minimum())
  271. self.ui.rackScrollBar.setMaximum(sb.maximum())
  272. self.ui.rackScrollBar.setValue(sb.value())
  273. sb.rangeChanged.connect(self.ui.rackScrollBar.setRange)
  274. sb.valueChanged.connect(self.ui.rackScrollBar.setValue)
  275. self.ui.rackScrollBar.rangeChanged.connect(sb.setRange)
  276. self.ui.rackScrollBar.valueChanged.connect(sb.setValue)
  277. self.updateStyle()
  278. self.ui.rack.setStyleSheet("""
  279. CarlaRackList#CarlaRackList {
  280. background-color: black;
  281. }
  282. """)
  283. # ----------------------------------------------------------------------------------------------------
  284. # Set up GUI (patchbay)
  285. self.ui.peak_in.setChannelCount(2)
  286. self.ui.peak_in.setMeterColor(DigitalPeakMeter.COLOR_BLUE)
  287. self.ui.peak_in.setMeterOrientation(DigitalPeakMeter.VERTICAL)
  288. self.ui.peak_in.setFixedWidth(25)
  289. self.ui.peak_out.setChannelCount(2)
  290. self.ui.peak_out.setMeterColor(DigitalPeakMeter.COLOR_GREEN)
  291. self.ui.peak_out.setMeterOrientation(DigitalPeakMeter.VERTICAL)
  292. self.ui.peak_out.setFixedWidth(25)
  293. self.ui.scrollArea = PixmapKeyboardHArea(self.ui.patchbay)
  294. self.ui.keyboard = self.ui.scrollArea.keyboard
  295. self.ui.patchbay.layout().addWidget(self.ui.scrollArea, 1, 0, 1, 0)
  296. self.ui.scrollArea.setEnabled(False)
  297. self.ui.miniCanvasPreview.setRealParent(self)
  298. self.ui.tw_miniCanvas.tabBar().hide()
  299. # ----------------------------------------------------------------------------------------------------
  300. # Set up GUI (special stuff for Mac OS)
  301. if MACOS:
  302. self.ui.act_file_quit.setMenuRole(QAction.QuitRole)
  303. self.ui.act_settings_configure.setMenuRole(QAction.PreferencesRole)
  304. self.ui.act_help_about.setMenuRole(QAction.AboutRole)
  305. self.ui.act_help_about_qt.setMenuRole(QAction.AboutQtRole)
  306. self.ui.menu_Settings.setTitle("Panels")
  307. self.ui.menu_Help.menuAction().setVisible(False)
  308. # ----------------------------------------------------------------------------------------------------
  309. # Load Settings
  310. self.loadSettings(True)
  311. # ----------------------------------------------------------------------------------------------------
  312. # Set-up Canvas
  313. if withCanvas:
  314. self.scene = patchcanvas.PatchScene(self, self.ui.graphicsView)
  315. self.ui.graphicsView.setScene(self.scene)
  316. self.ui.graphicsView.setRenderHint(QPainter.Antialiasing, bool(self.fSavedSettings[CARLA_KEY_CANVAS_ANTIALIASING] == patchcanvas.ANTIALIASING_FULL))
  317. if self.fSavedSettings[CARLA_KEY_CANVAS_USE_OPENGL] and hasGL:
  318. self.ui.glView = QGLWidget(self)
  319. self.ui.graphicsView.setViewport(self.ui.glView)
  320. self.ui.graphicsView.setRenderHint(QPainter.HighQualityAntialiasing, self.fSavedSettings[CARLA_KEY_CANVAS_HQ_ANTIALIASING])
  321. self.setupCanvas()
  322. # ----------------------------------------------------------------------------------------------------
  323. # Connect actions to functions
  324. self.ui.act_file_new.triggered.connect(self.slot_fileNew)
  325. self.ui.act_file_open.triggered.connect(self.slot_fileOpen)
  326. self.ui.act_file_save.triggered.connect(self.slot_fileSave)
  327. self.ui.act_file_save_as.triggered.connect(self.slot_fileSaveAs)
  328. self.ui.act_engine_start.triggered.connect(self.slot_engineStart)
  329. self.ui.act_engine_stop.triggered.connect(self.slot_engineStop)
  330. self.ui.act_plugin_add.triggered.connect(self.slot_pluginAdd)
  331. self.ui.act_plugin_add2.triggered.connect(self.slot_pluginAdd)
  332. self.ui.act_plugin_remove_all.triggered.connect(self.slot_confirmRemoveAll)
  333. self.ui.act_add_jack.triggered.connect(self.slot_jackAppAdd)
  334. self.ui.act_plugin_add_jack.triggered.connect(self.slot_jackAppAdd)
  335. self.ui.act_plugins_enable.triggered.connect(self.slot_pluginsEnable)
  336. self.ui.act_plugins_disable.triggered.connect(self.slot_pluginsDisable)
  337. self.ui.act_plugins_volume100.triggered.connect(self.slot_pluginsVolume100)
  338. self.ui.act_plugins_mute.triggered.connect(self.slot_pluginsMute)
  339. self.ui.act_plugins_wet100.triggered.connect(self.slot_pluginsWet100)
  340. self.ui.act_plugins_bypass.triggered.connect(self.slot_pluginsBypass)
  341. self.ui.act_plugins_center.triggered.connect(self.slot_pluginsCenter)
  342. self.ui.act_plugins_compact.triggered.connect(self.slot_pluginsCompact)
  343. self.ui.act_plugins_expand.triggered.connect(self.slot_pluginsExpand)
  344. self.ui.act_plugins_panic.triggered.connect(self.slot_pluginsDisable)
  345. self.ui.act_settings_show_toolbar.toggled.connect(self.slot_showToolbar)
  346. self.ui.act_settings_show_meters.toggled.connect(self.slot_showCanvasMeters)
  347. self.ui.act_settings_show_keyboard.toggled.connect(self.slot_showCanvasKeyboard)
  348. self.ui.act_settings_show_side_panel.toggled.connect(self.slot_showSidePanel)
  349. self.ui.act_settings_configure.triggered.connect(self.slot_configureCarla)
  350. self.ui.act_help_about.triggered.connect(self.slot_aboutCarla)
  351. self.ui.act_help_about_juce.triggered.connect(self.slot_aboutJuce)
  352. self.ui.act_help_about_qt.triggered.connect(self.slot_aboutQt)
  353. self.ui.cb_disk.currentIndexChanged.connect(self.slot_diskFolderChanged)
  354. self.ui.b_disk_add.clicked.connect(self.slot_diskFolderAdd)
  355. self.ui.b_disk_remove.clicked.connect(self.slot_diskFolderRemove)
  356. self.ui.fileTreeView.doubleClicked.connect(self.slot_fileTreeDoubleClicked)
  357. self.ui.b_transport_play.clicked.connect(self.slot_transportPlayPause)
  358. self.ui.b_transport_stop.clicked.connect(self.slot_transportStop)
  359. self.ui.b_transport_backwards.clicked.connect(self.slot_transportBackwards)
  360. self.ui.b_transport_forwards.clicked.connect(self.slot_transportForwards)
  361. self.ui.dsb_transport_bpm.valueChanged.connect(self.slot_transportBpmChanged)
  362. self.ui.cb_transport_jack.clicked.connect(self.slot_transportJackEnabled)
  363. self.ui.cb_transport_link.clicked.connect(self.slot_transportLinkEnabled)
  364. self.ui.listWidget.customContextMenuRequested.connect(self.showPluginActionsMenu)
  365. self.ui.keyboard.noteOn.connect(self.slot_noteOn)
  366. self.ui.keyboard.noteOff.connect(self.slot_noteOff)
  367. self.ui.tabWidget.currentChanged.connect(self.slot_tabChanged)
  368. if withCanvas:
  369. self.ui.act_canvas_show_internal.triggered.connect(self.slot_canvasShowInternal)
  370. self.ui.act_canvas_show_external.triggered.connect(self.slot_canvasShowExternal)
  371. self.ui.act_canvas_arrange.triggered.connect(self.slot_canvasArrange)
  372. self.ui.act_canvas_refresh.triggered.connect(self.slot_canvasRefresh)
  373. self.ui.act_canvas_zoom_fit.triggered.connect(self.slot_canvasZoomFit)
  374. self.ui.act_canvas_zoom_in.triggered.connect(self.slot_canvasZoomIn)
  375. self.ui.act_canvas_zoom_out.triggered.connect(self.slot_canvasZoomOut)
  376. self.ui.act_canvas_zoom_100.triggered.connect(self.slot_canvasZoomReset)
  377. self.ui.act_canvas_save_image.triggered.connect(self.slot_canvasSaveImage)
  378. self.ui.act_canvas_arrange.setEnabled(False) # TODO, later
  379. self.ui.graphicsView.horizontalScrollBar().valueChanged.connect(self.slot_horizontalScrollBarChanged)
  380. self.ui.graphicsView.verticalScrollBar().valueChanged.connect(self.slot_verticalScrollBarChanged)
  381. self.ui.miniCanvasPreview.miniCanvasMoved.connect(self.slot_miniCanvasMoved)
  382. self.scene.scaleChanged.connect(self.slot_canvasScaleChanged)
  383. self.scene.sceneGroupMoved.connect(self.slot_canvasItemMoved)
  384. self.scene.pluginSelected.connect(self.slot_canvasPluginSelected)
  385. self.scene.selectionChanged.connect(self.slot_canvasSelectionChanged)
  386. self.SIGUSR1.connect(self.slot_handleSIGUSR1)
  387. self.SIGTERM.connect(self.slot_handleSIGTERM)
  388. host.EngineStartedCallback.connect(self.slot_handleEngineStartedCallback)
  389. host.EngineStoppedCallback.connect(self.slot_handleEngineStoppedCallback)
  390. host.TransportModeChangedCallback.connect(self.slot_handleTransportModeChangedCallback)
  391. host.SampleRateChangedCallback.connect(self.slot_handleSampleRateChangedCallback)
  392. host.CancelableActionCallback.connect(self.slot_handleCancelableActionCallback)
  393. host.ProjectLoadFinishedCallback.connect(self.slot_handleProjectLoadFinishedCallback)
  394. host.PluginAddedCallback.connect(self.slot_handlePluginAddedCallback)
  395. host.PluginRemovedCallback.connect(self.slot_handlePluginRemovedCallback)
  396. host.ReloadAllCallback.connect(self.slot_handleReloadAllCallback)
  397. host.NoteOnCallback.connect(self.slot_handleNoteOnCallback)
  398. host.NoteOffCallback.connect(self.slot_handleNoteOffCallback)
  399. host.UpdateCallback.connect(self.slot_handleUpdateCallback)
  400. host.PatchbayClientAddedCallback.connect(self.slot_handlePatchbayClientAddedCallback)
  401. host.PatchbayClientRemovedCallback.connect(self.slot_handlePatchbayClientRemovedCallback)
  402. host.PatchbayClientRenamedCallback.connect(self.slot_handlePatchbayClientRenamedCallback)
  403. host.PatchbayClientDataChangedCallback.connect(self.slot_handlePatchbayClientDataChangedCallback)
  404. host.PatchbayPortAddedCallback.connect(self.slot_handlePatchbayPortAddedCallback)
  405. host.PatchbayPortRemovedCallback.connect(self.slot_handlePatchbayPortRemovedCallback)
  406. host.PatchbayPortRenamedCallback.connect(self.slot_handlePatchbayPortRenamedCallback)
  407. host.PatchbayConnectionAddedCallback.connect(self.slot_handlePatchbayConnectionAddedCallback)
  408. host.PatchbayConnectionRemovedCallback.connect(self.slot_handlePatchbayConnectionRemovedCallback)
  409. host.NSMCallback.connect(self.slot_handleNSMCallback)
  410. host.DebugCallback.connect(self.slot_handleDebugCallback)
  411. host.InfoCallback.connect(self.slot_handleInfoCallback)
  412. host.ErrorCallback.connect(self.slot_handleErrorCallback)
  413. host.QuitCallback.connect(self.slot_handleQuitCallback)
  414. # ----------------------------------------------------------------------------------------------------
  415. # Final setup
  416. self.ui.text_logs.clear()
  417. self.setProperWindowTitle()
  418. # Disable non-supported features
  419. features = gCarla.utils.get_supported_features()
  420. if "link" not in features:
  421. self.ui.cb_transport_link.setEnabled(False)
  422. self.ui.cb_transport_link.setVisible(False)
  423. if "juce" not in features:
  424. self.ui.act_help_about_juce.setEnabled(False)
  425. self.ui.act_help_about_juce.setVisible(False)
  426. # Plugin needs to have timers always running so it receives messages
  427. if self.host.isPlugin or self.host.isRemote:
  428. self.startTimers()
  429. # Qt needs this so it properly creates & resizes the canvas
  430. self.ui.tabWidget.blockSignals(True)
  431. self.ui.tabWidget.setCurrentIndex(1)
  432. self.ui.tabWidget.setCurrentIndex(0)
  433. self.ui.tabWidget.blockSignals(False)
  434. # Start in patchbay tab if using forced patchbay mode
  435. if host.processModeForced and host.processMode == ENGINE_PROCESS_MODE_PATCHBAY and not host.isControl:
  436. self.ui.tabWidget.setCurrentIndex(1)
  437. # Load initial project file if set
  438. if not (self.host.isControl or self.host.isPlugin):
  439. projectFile = getInitialProjectFile(QApplication.instance())
  440. if projectFile:
  441. self.loadProjectLater(projectFile)
  442. # For NSM we wait for the open message
  443. if NSM_URL and host.nsmOK:
  444. host.nsm_ready(-1)
  445. return
  446. QTimer.singleShot(0, self.slot_engineStart)
  447. # --------------------------------------------------------------------------------------------------------
  448. # Setup
  449. def compactPlugin(self, pluginId):
  450. if pluginId > self.fPluginCount:
  451. return
  452. pitem = self.fPluginList[pluginId]
  453. if pitem is None:
  454. return
  455. pitem.recreateWidget(True)
  456. def changePluginColor(self, pluginId, color, colorStr):
  457. if pluginId > self.fPluginCount:
  458. return
  459. pitem = self.fPluginList[pluginId]
  460. if pitem is None:
  461. return
  462. self.host.set_custom_data(pluginId, CUSTOM_DATA_TYPE_PROPERTY, "CarlaColor", colorStr)
  463. pitem.recreateWidget(newColor = color)
  464. def changePluginSkin(self, pluginId, skin):
  465. if pluginId > self.fPluginCount:
  466. return
  467. pitem = self.fPluginList[pluginId]
  468. if pitem is None:
  469. return
  470. self.host.set_custom_data(pluginId, CUSTOM_DATA_TYPE_PROPERTY, "CarlaSkin", skin)
  471. if skin not in ("default","rncbc","presets","mpresets"):
  472. pitem.recreateWidget(newSkin = skin, newColor = (255,255,255))
  473. else:
  474. pitem.recreateWidget(newSkin = skin)
  475. def switchPlugins(self, pluginIdA, pluginIdB):
  476. if pluginIdA == pluginIdB:
  477. return
  478. if pluginIdA < 0 or pluginIdB < 0:
  479. return
  480. if pluginIdA >= self.fPluginCount or pluginIdB >= self.fPluginCount:
  481. return
  482. self.host.switch_plugins(pluginIdA, pluginIdB)
  483. itemA = self.fPluginList[pluginIdA]
  484. compactA = itemA.isCompacted()
  485. guiShownA = itemA.isGuiShown()
  486. itemB = self.fPluginList[pluginIdB]
  487. compactB = itemB.isCompacted()
  488. guiShownB = itemB.isGuiShown()
  489. itemA.setPluginId(pluginIdA)
  490. itemA.recreateWidget2(compactB, guiShownB)
  491. itemB.setPluginId(pluginIdB)
  492. itemB.recreateWidget2(compactA, guiShownA)
  493. self.slot_canvasRefresh()
  494. def setLoadRDFsNeeded(self):
  495. self.fLadspaRdfNeedsUpdate = True
  496. def setProperWindowTitle(self):
  497. title = self.fClientName
  498. if self.fProjectFilename and not self.host.nsmOK:
  499. title += " - %s" % os.path.basename(self.fProjectFilename)
  500. if self.fSessionManagerName:
  501. title += " (%s)" % self.fSessionManagerName
  502. self.setWindowTitle(title)
  503. # --------------------------------------------------------------------------------------------------------
  504. # Files
  505. def makeExtraFilename(self):
  506. return self.fProjectFilename.rsplit(".",1)[0]+".json"
  507. def loadProjectNow(self):
  508. if not self.fProjectFilename:
  509. return qCritical("ERROR: loading project without filename set")
  510. if self.host.nsmOK and not os.path.exists(self.fProjectFilename):
  511. return
  512. self.projectLoadingStarted()
  513. self.fIsProjectLoading = True
  514. if not self.host.load_project(self.fProjectFilename):
  515. self.fIsProjectLoading = False
  516. self.projectLoadingFinished()
  517. CustomMessageBox(self, QMessageBox.Critical, self.tr("Error"), self.tr("Failed to load project"),
  518. self.host.get_last_error(),
  519. QMessageBox.Ok, QMessageBox.Ok)
  520. def loadProjectLater(self, filename):
  521. self.fProjectFilename = QFileInfo(filename).absoluteFilePath()
  522. self.setProperWindowTitle()
  523. QTimer.singleShot(1, self.slot_loadProjectNow)
  524. def saveProjectNow(self):
  525. if not self.fProjectFilename:
  526. return qCritical("ERROR: saving project without filename set")
  527. if not self.host.save_project(self.fProjectFilename):
  528. CustomMessageBox(self, QMessageBox.Critical, self.tr("Error"), self.tr("Failed to save project"),
  529. self.host.get_last_error(),
  530. QMessageBox.Ok, QMessageBox.Ok)
  531. return
  532. if not self.fWithCanvas:
  533. return
  534. with open(self.makeExtraFilename(), 'w') as fh:
  535. json.dump({
  536. 'canvas': patchcanvas.saveGroupPositions(),
  537. }, fh)
  538. def projectLoadingStarted(self):
  539. self.ui.rack.setEnabled(False)
  540. self.ui.graphicsView.setEnabled(False)
  541. def projectLoadingFinished(self):
  542. self.ui.rack.setEnabled(True)
  543. self.ui.graphicsView.setEnabled(True)
  544. if not self.fWithCanvas:
  545. return
  546. QTimer.singleShot(1000, self.slot_canvasRefresh)
  547. extrafile = self.makeExtraFilename()
  548. if not os.path.exists(extrafile):
  549. return
  550. try:
  551. with open(extrafile, "r") as fh:
  552. canvasdata = json.load(fh)['canvas']
  553. except:
  554. return
  555. patchcanvas.restoreGroupPositions(canvasdata)
  556. # --------------------------------------------------------------------------------------------------------
  557. # Files (menu actions)
  558. @pyqtSlot()
  559. def slot_fileNew(self):
  560. if self.fPluginCount > 0 and QMessageBox.question(self, self.tr("New File"),
  561. self.tr("Plugins that are currently loaded will be removed. Are you sure?"),
  562. QMessageBox.Yes|QMessageBox.No) == QMessageBox.No:
  563. return
  564. self.pluginRemoveAll()
  565. self.fProjectFilename = ""
  566. self.setProperWindowTitle()
  567. self.host.clear_project_filename()
  568. @pyqtSlot()
  569. def slot_fileOpen(self):
  570. fileFilter = self.tr("Carla Project File (*.carxp);;Carla Preset File (*.carxs)")
  571. filename, ok = QFileDialog.getOpenFileName(self, self.tr("Open Carla Project File"), self.fSavedSettings[CARLA_KEY_MAIN_PROJECT_FOLDER], filter=fileFilter)
  572. # FIXME use ok value, test if it works as expected
  573. if not filename:
  574. return
  575. newFile = True
  576. if self.fPluginCount > 0:
  577. ask = QMessageBox.question(self, self.tr("Question"), self.tr("There are some plugins loaded, do you want to remove them now?"),
  578. QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
  579. newFile = (ask == QMessageBox.Yes)
  580. if newFile:
  581. self.pluginRemoveAll()
  582. self.fProjectFilename = filename
  583. self.setProperWindowTitle()
  584. self.loadProjectNow()
  585. else:
  586. filenameOld = self.fProjectFilename
  587. self.fProjectFilename = filename
  588. self.loadProjectNow()
  589. self.fProjectFilename = filenameOld
  590. @pyqtSlot()
  591. def slot_fileSave(self, saveAs=False):
  592. if self.fProjectFilename and not saveAs:
  593. return self.saveProjectNow()
  594. fileFilter = self.tr("Carla Project File (*.carxp)")
  595. filename, ok = QFileDialog.getSaveFileName(self, self.tr("Save Carla Project File"), self.fSavedSettings[CARLA_KEY_MAIN_PROJECT_FOLDER], filter=fileFilter)
  596. # FIXME use ok value, test if it works as expected
  597. if not filename:
  598. return
  599. if not filename.lower().endswith(".carxp"):
  600. filename += ".carxp"
  601. if self.fProjectFilename != filename:
  602. self.fProjectFilename = filename
  603. self.setProperWindowTitle()
  604. self.saveProjectNow()
  605. @pyqtSlot()
  606. def slot_fileSaveAs(self):
  607. self.slot_fileSave(True)
  608. @pyqtSlot()
  609. def slot_loadProjectNow(self):
  610. self.loadProjectNow()
  611. # --------------------------------------------------------------------------------------------------------
  612. # Engine (menu actions)
  613. @pyqtSlot()
  614. def slot_engineStart(self):
  615. audioDriver = setEngineSettings(self.host)
  616. firstInit = self.fFirstEngineInit
  617. self.fFirstEngineInit = False
  618. self.ui.text_logs.appendPlainText("======= Starting engine =======")
  619. if self.host.engine_init(audioDriver, self.fClientName):
  620. if firstInit and not (self.host.isControl or self.host.isPlugin):
  621. settings = QSettings()
  622. lastBpm = settings.value("LastBPM", 120.0, type=float)
  623. del settings
  624. self.host.transport_bpm(lastBpm)
  625. return
  626. elif firstInit:
  627. self.ui.text_logs.appendPlainText("Failed to start engine on first try, ignored")
  628. return
  629. audioError = self.host.get_last_error()
  630. if audioError:
  631. QMessageBox.critical(self, self.tr("Error"), self.tr("Could not connect to Audio backend '%s', possible reasons:\n%s" % (audioDriver, audioError)))
  632. else:
  633. QMessageBox.critical(self, self.tr("Error"), self.tr("Could not connect to Audio backend '%s'" % audioDriver))
  634. @pyqtSlot()
  635. def slot_engineStop(self, forced = False):
  636. self.ui.text_logs.appendPlainText("======= Stopping engine =======")
  637. if self.fPluginCount == 0:
  638. self.engineStopFinal()
  639. return True
  640. if not forced:
  641. 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"
  642. "Do you want to do this now?"),
  643. QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
  644. if ask != QMessageBox.Yes:
  645. return False
  646. return self.slot_engineStopTryAgain()
  647. @pyqtSlot()
  648. def slot_engineStopTryAgain(self):
  649. if self.host.is_engine_running() and not self.host.set_engine_about_to_close():
  650. QTimer.singleShot(0, self.slot_engineStopTryAgain)
  651. return False
  652. self.engineStopFinal()
  653. return True
  654. def engineStopFinal(self):
  655. self.killTimers()
  656. if self.host.is_engine_running():
  657. if self.fCustomStopAction == self.CUSTOM_ACTION_PROJECT_LOAD:
  658. self.removeAllPlugins()
  659. else:
  660. self.fCurrentlyRemovingAllPlugins = True
  661. self.projectLoadingStarted()
  662. if not self.host.remove_all_plugins():
  663. self.ui.text_logs.appendPlainText("Failed to remove all plugins, error was:")
  664. self.ui.text_logs.appendPlainText(self.host.get_last_error())
  665. if not self.host.engine_close():
  666. self.ui.text_logs.appendPlainText("Failed to stop engine, error was:")
  667. self.ui.text_logs.appendPlainText(self.host.get_last_error())
  668. if self.fCustomStopAction == self.CUSTOM_ACTION_APP_CLOSE:
  669. self.close()
  670. elif self.fCustomStopAction == self.CUSTOM_ACTION_PROJECT_LOAD:
  671. self.slot_engineStart()
  672. self.loadProjectNow()
  673. self.host.nsm_ready(2) # open
  674. self.fCustomStopAction = self.CUSTOM_ACTION_NONE
  675. # --------------------------------------------------------------------------------------------------------
  676. # Engine (host callbacks)
  677. @pyqtSlot(int, int, float, str)
  678. def slot_handleEngineStartedCallback(self, processMode, transportMode, sampleRate, driverName):
  679. self.fSampleRate = sampleRate
  680. self.ui.menu_PluginMacros.setEnabled(True)
  681. self.ui.menu_Canvas.setEnabled(True)
  682. self.ui.w_transport.setEnabled(True)
  683. self.ui.act_canvas_show_internal.blockSignals(True)
  684. self.ui.act_canvas_show_external.blockSignals(True)
  685. if processMode == ENGINE_PROCESS_MODE_PATCHBAY and not (self.host.isControl or self.host.isPlugin):
  686. self.ui.act_canvas_show_internal.setChecked(True)
  687. self.ui.act_canvas_show_internal.setVisible(True)
  688. self.ui.act_canvas_show_external.setChecked(False)
  689. self.ui.act_canvas_show_external.setVisible(True)
  690. else:
  691. self.ui.act_canvas_show_internal.setChecked(False)
  692. self.ui.act_canvas_show_internal.setVisible(False)
  693. self.ui.act_canvas_show_external.setChecked(False)
  694. self.ui.act_canvas_show_external.setVisible(False)
  695. self.ui.act_canvas_show_internal.blockSignals(False)
  696. self.ui.act_canvas_show_external.blockSignals(False)
  697. if not (self.host.isControl or self.host.isPlugin):
  698. canSave = (self.fProjectFilename and os.path.exists(self.fProjectFilename)) or not self.fSessionManagerName
  699. self.ui.act_file_save.setEnabled(canSave)
  700. self.ui.act_engine_start.setEnabled(False)
  701. self.ui.act_engine_stop.setEnabled(True)
  702. self.enableTransport(transportMode != ENGINE_TRANSPORT_MODE_DISABLED)
  703. if self.host.isPlugin or not self.fSessionManagerName:
  704. self.ui.act_file_open.setEnabled(True)
  705. self.ui.act_file_save_as.setEnabled(True)
  706. self.refreshTransport(True)
  707. self.ui.cb_transport_jack.setChecked(transportMode == ENGINE_TRANSPORT_MODE_JACK)
  708. self.ui.cb_transport_jack.setEnabled(driverName == "JACK" and processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  709. if self.ui.cb_transport_link.isEnabled():
  710. self.ui.cb_transport_link.setChecked(":link:" in self.host.transportExtra)
  711. self.startTimers()
  712. self.ui.text_logs.appendPlainText("======= Engine started ========")
  713. self.ui.text_logs.appendPlainText("Carla engine started, details:")
  714. self.ui.text_logs.appendPlainText(" Driver name: %s" % driverName)
  715. self.ui.text_logs.appendPlainText(" Sample rate: %.1f" % sampleRate)
  716. self.ui.text_logs.appendPlainText(" Process mode: %s" % processMode2Str(processMode))
  717. @pyqtSlot()
  718. def slot_handleEngineStoppedCallback(self):
  719. self.ui.text_logs.appendPlainText("======= Engine stopped ========")
  720. patchcanvas.clear()
  721. self.killTimers()
  722. # just in case
  723. self.removeAllPlugins()
  724. self.ui.menu_PluginMacros.setEnabled(False)
  725. self.ui.menu_Canvas.setEnabled(False)
  726. self.ui.w_transport.setEnabled(False)
  727. if not (self.host.isControl or self.host.isPlugin):
  728. self.ui.act_file_save.setEnabled(False)
  729. self.ui.act_engine_start.setEnabled(True)
  730. self.ui.act_engine_stop.setEnabled(False)
  731. if self.host.isPlugin or not self.fSessionManagerName:
  732. self.ui.act_file_open.setEnabled(False)
  733. self.ui.act_file_save_as.setEnabled(False)
  734. @pyqtSlot(int, str)
  735. def slot_handleTransportModeChangedCallback(self, transportMode, transportExtra):
  736. self.enableTransport(transportMode != ENGINE_TRANSPORT_MODE_DISABLED)
  737. self.ui.cb_transport_jack.setChecked(transportMode == ENGINE_TRANSPORT_MODE_JACK)
  738. self.ui.cb_transport_link.setChecked(":link:" in transportExtra)
  739. @pyqtSlot(float)
  740. def slot_handleSampleRateChangedCallback(self, newSampleRate):
  741. self.fSampleRate = newSampleRate
  742. self.refreshTransport(True)
  743. @pyqtSlot(int, bool, str)
  744. def slot_handleCancelableActionCallback(self, pluginId, started, action):
  745. if self.fCancelableActionBox is not None:
  746. self.fCancelableActionBox.close()
  747. if started:
  748. self.fCancelableActionBox = QMessageBox(self)
  749. self.fCancelableActionBox.setIcon(QMessageBox.Critical)
  750. self.fCancelableActionBox.setWindowTitle(self.tr("Action in progress"))
  751. self.fCancelableActionBox.setText(action)
  752. self.fCancelableActionBox.setInformativeText(self.tr("An action is in progress, please wait..."))
  753. self.fCancelableActionBox.setStandardButtons(QMessageBox.Cancel)
  754. self.fCancelableActionBox.setDefaultButton(QMessageBox.Cancel)
  755. self.fCancelableActionBox.buttonClicked.connect(self.slot_canlableActionBoxClicked)
  756. self.fCancelableActionBox.show()
  757. else:
  758. self.fCancelableActionBox = None
  759. @pyqtSlot()
  760. def slot_canlableActionBoxClicked(self):
  761. self.host.cancel_engine_action()
  762. @pyqtSlot()
  763. def slot_handleProjectLoadFinishedCallback(self):
  764. self.fIsProjectLoading = False
  765. self.projectLoadingFinished()
  766. # --------------------------------------------------------------------------------------------------------
  767. # Plugins
  768. def removeAllPlugins(self):
  769. self.ui.act_plugin_remove_all.setEnabled(False)
  770. patchcanvas.handleAllPluginsRemoved()
  771. while self.ui.listWidget.takeItem(0):
  772. pass
  773. self.clearSideStuff()
  774. for pitem in self.fPluginList:
  775. if pitem is None:
  776. continue
  777. pitem.close()
  778. del pitem
  779. self.fPluginCount = 0
  780. self.fPluginList = []
  781. # --------------------------------------------------------------------------------------------------------
  782. # Plugins (menu actions)
  783. def showAddPluginDialog(self):
  784. dialog = PluginDatabaseW(self.fParentOrSelf, self.host)
  785. if not dialog.exec_():
  786. return
  787. if not self.host.is_engine_running():
  788. QMessageBox.warning(self, self.tr("Warning"), self.tr("Cannot add new plugins while engine is stopped"))
  789. return
  790. btype = dialog.fRetPlugin['build']
  791. ptype = dialog.fRetPlugin['type']
  792. filename = dialog.fRetPlugin['filename']
  793. label = dialog.fRetPlugin['label']
  794. uniqueId = dialog.fRetPlugin['uniqueId']
  795. extraPtr = self.getExtraPtr(dialog.fRetPlugin)
  796. return (btype, ptype, filename, label, uniqueId, extraPtr)
  797. def showAddJackAppDialog(self):
  798. dialog = JackApplicationW(self.fParentOrSelf, self.host)
  799. if not dialog.exec_():
  800. return
  801. if not self.host.is_engine_running():
  802. QMessageBox.warning(self, self.tr("Warning"), self.tr("Cannot add new plugins while engine is stopped"))
  803. return
  804. return dialog.getCommandAndFlags()
  805. @pyqtSlot()
  806. def showPluginActionsMenu(self):
  807. menu = QMenu(self)
  808. menu.addSection("Plugins")
  809. menu.addAction(self.ui.act_plugin_add)
  810. menu.addAction(self.ui.act_plugin_remove_all)
  811. menu.addSection("All plugins (macros)")
  812. menu.addAction(self.ui.act_plugins_enable)
  813. menu.addAction(self.ui.act_plugins_disable)
  814. menu.addSeparator()
  815. menu.addAction(self.ui.act_plugins_volume100)
  816. menu.addAction(self.ui.act_plugins_mute)
  817. menu.addSeparator()
  818. menu.addAction(self.ui.act_plugins_wet100)
  819. menu.addAction(self.ui.act_plugins_bypass)
  820. menu.addSeparator()
  821. menu.addAction(self.ui.act_plugins_center)
  822. menu.addSeparator()
  823. menu.addAction(self.ui.act_plugins_compact)
  824. menu.addAction(self.ui.act_plugins_expand)
  825. menu.exec_(QCursor.pos())
  826. @pyqtSlot()
  827. def slot_pluginAdd(self):
  828. data = self.showAddPluginDialog()
  829. if data is None:
  830. return
  831. btype, ptype, filename, label, uniqueId, extraPtr = data
  832. if not self.host.add_plugin(btype, ptype, filename, None, label, uniqueId, extraPtr, 0x0):
  833. CustomMessageBox(self, QMessageBox.Critical, self.tr("Error"), self.tr("Failed to load plugin"), self.host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  834. @pyqtSlot()
  835. def slot_confirmRemoveAll(self):
  836. if self.fPluginCount == 0:
  837. return
  838. if QMessageBox.question(self, self.tr("Remove All"),
  839. self.tr("Are you sure you want to remove all plugins?"),
  840. QMessageBox.Yes|QMessageBox.No) == QMessageBox.No:
  841. return
  842. self.pluginRemoveAll()
  843. def pluginRemoveAll(self):
  844. if self.fPluginCount == 0:
  845. return
  846. self.fCurrentlyRemovingAllPlugins = True
  847. self.projectLoadingStarted()
  848. if not self.host.remove_all_plugins():
  849. self.projectLoadingFinished()
  850. self.fCurrentlyRemovingAllPlugins = False
  851. CustomMessageBox(self, QMessageBox.Warning, self.tr("Error"), self.tr("Operation failed"),
  852. self.host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  853. @pyqtSlot()
  854. def slot_jackAppAdd(self):
  855. data = self.showAddJackAppDialog()
  856. if data is None:
  857. return
  858. filename, name, label = data
  859. if not filename:
  860. CustomMessageBox(self, QMessageBox.Critical, self.tr("Error"), self.tr("Cannot add jack application"),
  861. self.tr("command is empty"), QMessageBox.Ok, QMessageBox.Ok)
  862. return
  863. if not self.host.add_plugin(BINARY_NATIVE, PLUGIN_JACK, filename, name, label, 0, None, 0x0):
  864. CustomMessageBox(self, QMessageBox.Critical, self.tr("Error"), self.tr("Failed to load plugin"),
  865. self.host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  866. # --------------------------------------------------------------------------------------------------------
  867. # Plugins (macros)
  868. @pyqtSlot()
  869. def slot_pluginsEnable(self):
  870. if not self.host.is_engine_running():
  871. return
  872. for pitem in self.fPluginList:
  873. if pitem is None:
  874. break
  875. pitem.getWidget().setActive(True, True, True)
  876. @pyqtSlot()
  877. def slot_pluginsDisable(self):
  878. if not self.host.is_engine_running():
  879. return
  880. for pitem in self.fPluginList:
  881. if pitem is None:
  882. break
  883. pitem.getWidget().setActive(False, True, True)
  884. @pyqtSlot()
  885. def slot_pluginsVolume100(self):
  886. if not self.host.is_engine_running():
  887. return
  888. for pitem in self.fPluginList:
  889. if pitem is None:
  890. break
  891. pitem.getWidget().setInternalParameter(PLUGIN_CAN_VOLUME, 1.0)
  892. @pyqtSlot()
  893. def slot_pluginsMute(self):
  894. if not self.host.is_engine_running():
  895. return
  896. for pitem in self.fPluginList:
  897. if pitem is None:
  898. break
  899. pitem.getWidget().setInternalParameter(PLUGIN_CAN_VOLUME, 0.0)
  900. @pyqtSlot()
  901. def slot_pluginsWet100(self):
  902. if not self.host.is_engine_running():
  903. return
  904. for pitem in self.fPluginList:
  905. if pitem is None:
  906. break
  907. pitem.getWidget().setInternalParameter(PLUGIN_CAN_DRYWET, 1.0)
  908. @pyqtSlot()
  909. def slot_pluginsBypass(self):
  910. if not self.host.is_engine_running():
  911. return
  912. for pitem in self.fPluginList:
  913. if pitem is None:
  914. break
  915. pitem.getWidget().setInternalParameter(PLUGIN_CAN_DRYWET, 0.0)
  916. @pyqtSlot()
  917. def slot_pluginsCenter(self):
  918. if not self.host.is_engine_running():
  919. return
  920. for pitem in self.fPluginList:
  921. if pitem is None:
  922. break
  923. pitem.getWidget().setInternalParameter(PARAMETER_BALANCE_LEFT, -1.0)
  924. pitem.getWidget().setInternalParameter(PARAMETER_BALANCE_RIGHT, 1.0)
  925. pitem.getWidget().setInternalParameter(PARAMETER_PANNING, 0.0)
  926. @pyqtSlot()
  927. def slot_pluginsCompact(self):
  928. for pitem in self.fPluginList:
  929. if pitem is None:
  930. break
  931. pitem.compact()
  932. @pyqtSlot()
  933. def slot_pluginsExpand(self):
  934. for pitem in self.fPluginList:
  935. if pitem is None:
  936. break
  937. pitem.expand()
  938. # --------------------------------------------------------------------------------------------------------
  939. # Plugins (host callbacks)
  940. @pyqtSlot(int, str)
  941. def slot_handlePluginAddedCallback(self, pluginId, pluginName):
  942. pitem = self.ui.listWidget.createItem(pluginId)
  943. self.fPluginList.append(pitem)
  944. self.fPluginCount += 1
  945. self.ui.act_plugin_remove_all.setEnabled(self.fPluginCount > 0)
  946. @pyqtSlot(int)
  947. def slot_handlePluginRemovedCallback(self, pluginId):
  948. patchcanvas.handlePluginRemoved(pluginId)
  949. if pluginId in self.fSelectedPlugins:
  950. self.clearSideStuff()
  951. pitem = self.getPluginItem(pluginId)
  952. self.fPluginCount -= 1
  953. self.fPluginList.pop(pluginId)
  954. self.ui.listWidget.takeItem(pluginId)
  955. if pitem is not None:
  956. pitem.close()
  957. del pitem
  958. if self.fPluginCount == 0:
  959. self.ui.act_plugin_remove_all.setEnabled(False)
  960. if self.fCurrentlyRemovingAllPlugins:
  961. self.fCurrentlyRemovingAllPlugins = False
  962. self.projectLoadingFinished()
  963. return
  964. # push all plugins 1 slot back
  965. for i in range(pluginId, self.fPluginCount):
  966. pitem = self.fPluginList[i]
  967. pitem.setPluginId(i)
  968. self.ui.act_plugin_remove_all.setEnabled(True)
  969. # --------------------------------------------------------------------------------------------------------
  970. # Canvas
  971. def clearSideStuff(self):
  972. if self.fWithCanvas:
  973. self.scene.clearSelection()
  974. self.fSelectedPlugins = []
  975. self.ui.keyboard.allNotesOff(False)
  976. self.ui.scrollArea.setEnabled(False)
  977. self.fPeaksCleared = True
  978. self.ui.peak_in.displayMeter(1, 0.0, True)
  979. self.ui.peak_in.displayMeter(2, 0.0, True)
  980. self.ui.peak_out.displayMeter(1, 0.0, True)
  981. self.ui.peak_out.displayMeter(2, 0.0, True)
  982. def setupCanvas(self):
  983. pOptions = patchcanvas.options_t()
  984. pOptions.theme_name = self.fSavedSettings[CARLA_KEY_CANVAS_THEME]
  985. pOptions.auto_hide_groups = self.fSavedSettings[CARLA_KEY_CANVAS_AUTO_HIDE_GROUPS]
  986. pOptions.auto_select_items = self.fSavedSettings[CARLA_KEY_CANVAS_AUTO_SELECT_ITEMS]
  987. pOptions.use_bezier_lines = self.fSavedSettings[CARLA_KEY_CANVAS_USE_BEZIER_LINES]
  988. pOptions.antialiasing = self.fSavedSettings[CARLA_KEY_CANVAS_ANTIALIASING]
  989. if self.fSavedSettings[CARLA_KEY_CANVAS_FANCY_EYE_CANDY]:
  990. pOptions.eyecandy = patchcanvas.EYECANDY_FULL
  991. elif self.fSavedSettings[CARLA_KEY_CANVAS_EYE_CANDY]:
  992. pOptions.eyecandy = patchcanvas.EYECANDY_SMALL
  993. else:
  994. pOptions.eyecandy = patchcanvas.EYECANDY_NONE
  995. pFeatures = patchcanvas.features_t()
  996. pFeatures.group_info = False
  997. pFeatures.group_rename = False
  998. pFeatures.port_info = False
  999. pFeatures.port_rename = False
  1000. pFeatures.handle_group_pos = True
  1001. patchcanvas.setOptions(pOptions)
  1002. patchcanvas.setFeatures(pFeatures)
  1003. patchcanvas.init("Carla2", self.scene, canvasCallback, False)
  1004. tryCanvasSize = self.fSavedSettings[CARLA_KEY_CANVAS_SIZE].split("x")
  1005. if len(tryCanvasSize) == 2 and tryCanvasSize[0].isdigit() and tryCanvasSize[1].isdigit():
  1006. self.fCanvasWidth = int(tryCanvasSize[0])
  1007. self.fCanvasHeight = int(tryCanvasSize[1])
  1008. else:
  1009. self.fCanvasWidth = CARLA_DEFAULT_CANVAS_SIZE_WIDTH
  1010. self.fCanvasHeight = CARLA_DEFAULT_CANVAS_SIZE_HEIGHT
  1011. patchcanvas.setCanvasSize(0, 0, self.fCanvasWidth, self.fCanvasHeight)
  1012. patchcanvas.setInitialPos(self.fCanvasWidth / 2, self.fCanvasHeight / 2)
  1013. self.ui.graphicsView.setSceneRect(0, 0, self.fCanvasWidth, self.fCanvasHeight)
  1014. self.ui.miniCanvasPreview.setViewTheme(patchcanvas.canvas.theme.canvas_bg, patchcanvas.canvas.theme.rubberband_brush, patchcanvas.canvas.theme.rubberband_pen.color())
  1015. self.ui.miniCanvasPreview.init(self.scene, self.fCanvasWidth, self.fCanvasHeight, self.fSavedSettings[CARLA_KEY_CUSTOM_PAINTING])
  1016. def updateCanvasInitialPos(self):
  1017. x = self.ui.graphicsView.horizontalScrollBar().value() + self.width()/4
  1018. y = self.ui.graphicsView.verticalScrollBar().value() + self.height()/4
  1019. patchcanvas.setInitialPos(x, y)
  1020. def updateMiniCanvasLater(self):
  1021. QTimer.singleShot(self.fMiniCanvasUpdateTimeout, self.ui.miniCanvasPreview.update)
  1022. # --------------------------------------------------------------------------------------------------------
  1023. # Canvas (menu actions)
  1024. @pyqtSlot()
  1025. def slot_canvasShowInternal(self):
  1026. self.fExternalPatchbay = False
  1027. self.ui.act_canvas_show_internal.blockSignals(True)
  1028. self.ui.act_canvas_show_external.blockSignals(True)
  1029. self.ui.act_canvas_show_internal.setChecked(True)
  1030. self.ui.act_canvas_show_external.setChecked(False)
  1031. self.ui.act_canvas_show_internal.blockSignals(False)
  1032. self.ui.act_canvas_show_external.blockSignals(False)
  1033. self.slot_canvasRefresh()
  1034. @pyqtSlot()
  1035. def slot_canvasShowExternal(self):
  1036. self.fExternalPatchbay = True
  1037. self.ui.act_canvas_show_internal.blockSignals(True)
  1038. self.ui.act_canvas_show_external.blockSignals(True)
  1039. self.ui.act_canvas_show_internal.setChecked(False)
  1040. self.ui.act_canvas_show_external.setChecked(True)
  1041. self.ui.act_canvas_show_internal.blockSignals(False)
  1042. self.ui.act_canvas_show_external.blockSignals(False)
  1043. self.slot_canvasRefresh()
  1044. @pyqtSlot()
  1045. def slot_canvasArrange(self):
  1046. patchcanvas.arrange()
  1047. @pyqtSlot()
  1048. def slot_canvasRefresh(self):
  1049. patchcanvas.clear()
  1050. if self.host.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK and (self.host.isControl or self.host.isPlugin):
  1051. return
  1052. if self.host.is_engine_running():
  1053. self.host.patchbay_refresh(self.fExternalPatchbay)
  1054. self.updateMiniCanvasLater()
  1055. @pyqtSlot()
  1056. def slot_canvasZoomFit(self):
  1057. self.scene.zoom_fit()
  1058. @pyqtSlot()
  1059. def slot_canvasZoomIn(self):
  1060. self.scene.zoom_in()
  1061. @pyqtSlot()
  1062. def slot_canvasZoomOut(self):
  1063. self.scene.zoom_out()
  1064. @pyqtSlot()
  1065. def slot_canvasZoomReset(self):
  1066. self.scene.zoom_reset()
  1067. @pyqtSlot()
  1068. def slot_canvasSaveImage(self):
  1069. newPath, ok = QFileDialog.getSaveFileName(self, self.tr("Save Image"), filter=self.tr("PNG Image (*.png);;JPEG Image (*.jpg)"))
  1070. # FIXME use ok value, test if it works as expected
  1071. if not newPath:
  1072. return
  1073. self.scene.clearSelection()
  1074. if newPath.lower().endswith((".jpg", ".jpeg")):
  1075. imgFormat = "JPG"
  1076. elif newPath.lower().endswith((".png",)):
  1077. imgFormat = "PNG"
  1078. else:
  1079. # File-dialog may not auto-add the extension
  1080. imgFormat = "PNG"
  1081. newPath += ".png"
  1082. self.fExportImage = QImage(self.scene.sceneRect().width(), self.scene.sceneRect().height(), QImage.Format_RGB32)
  1083. painter = QPainter(self.fExportImage)
  1084. painter.save()
  1085. painter.setRenderHint(QPainter.Antialiasing) # TODO - set true, cleanup this
  1086. painter.setRenderHint(QPainter.TextAntialiasing)
  1087. self.scene.render(painter)
  1088. self.fExportImage.save(newPath, imgFormat, 100)
  1089. painter.restore()
  1090. # --------------------------------------------------------------------------------------------------------
  1091. # Canvas (canvas callbacks)
  1092. @pyqtSlot(int, int, QPointF)
  1093. def slot_canvasItemMoved(self, group_id, split_mode, pos):
  1094. self.updateMiniCanvasLater()
  1095. @pyqtSlot()
  1096. def slot_canvasSelectionChanged(self):
  1097. self.updateMiniCanvasLater()
  1098. @pyqtSlot(float)
  1099. def slot_canvasScaleChanged(self, scale):
  1100. self.ui.miniCanvasPreview.setViewScale(scale)
  1101. @pyqtSlot(list)
  1102. def slot_canvasPluginSelected(self, pluginList):
  1103. self.ui.keyboard.allNotesOff(False)
  1104. self.ui.scrollArea.setEnabled(len(pluginList) != 0) # and self.fPluginCount > 0
  1105. self.fSelectedPlugins = pluginList
  1106. # --------------------------------------------------------------------------------------------------------
  1107. # Canvas (host callbacks)
  1108. @pyqtSlot(int, int, int, str)
  1109. def slot_handlePatchbayClientAddedCallback(self, clientId, clientIcon, pluginId, clientName):
  1110. pcSplit = patchcanvas.SPLIT_UNDEF
  1111. pcIcon = patchcanvas.ICON_APPLICATION
  1112. if clientIcon == PATCHBAY_ICON_PLUGIN:
  1113. pcIcon = patchcanvas.ICON_PLUGIN
  1114. if clientIcon == PATCHBAY_ICON_HARDWARE:
  1115. pcIcon = patchcanvas.ICON_HARDWARE
  1116. elif clientIcon == PATCHBAY_ICON_CARLA:
  1117. pass
  1118. elif clientIcon == PATCHBAY_ICON_DISTRHO:
  1119. pcIcon = patchcanvas.ICON_DISTRHO
  1120. elif clientIcon == PATCHBAY_ICON_FILE:
  1121. pcIcon = patchcanvas.ICON_FILE
  1122. patchcanvas.addGroup(clientId, clientName, pcSplit, pcIcon)
  1123. self.updateMiniCanvasLater()
  1124. if pluginId < 0:
  1125. return
  1126. if pluginId >= self.fPluginCount and pluginId != MAIN_CARLA_PLUGIN_ID:
  1127. print("sorry, can't map this plugin to canvas client", pluginId, self.fPluginCount)
  1128. return
  1129. if pluginId == MAIN_CARLA_PLUGIN_ID:
  1130. hasCustomUI = False
  1131. else:
  1132. hasCustomUI = bool(self.host.get_plugin_info(pluginId)['hints'] & PLUGIN_HAS_CUSTOM_UI)
  1133. patchcanvas.setGroupAsPlugin(clientId, pluginId, hasCustomUI)
  1134. @pyqtSlot(int)
  1135. def slot_handlePatchbayClientRemovedCallback(self, clientId):
  1136. patchcanvas.removeGroup(clientId)
  1137. self.updateMiniCanvasLater()
  1138. @pyqtSlot(int, str)
  1139. def slot_handlePatchbayClientRenamedCallback(self, clientId, newClientName):
  1140. patchcanvas.renameGroup(clientId, newClientName)
  1141. self.updateMiniCanvasLater()
  1142. @pyqtSlot(int, int, int)
  1143. def slot_handlePatchbayClientDataChangedCallback(self, clientId, clientIcon, pluginId):
  1144. pcIcon = patchcanvas.ICON_APPLICATION
  1145. if clientIcon == PATCHBAY_ICON_PLUGIN:
  1146. pcIcon = patchcanvas.ICON_PLUGIN
  1147. if clientIcon == PATCHBAY_ICON_HARDWARE:
  1148. pcIcon = patchcanvas.ICON_HARDWARE
  1149. elif clientIcon == PATCHBAY_ICON_CARLA:
  1150. pass
  1151. elif clientIcon == PATCHBAY_ICON_DISTRHO:
  1152. pcIcon = patchcanvas.ICON_DISTRHO
  1153. elif clientIcon == PATCHBAY_ICON_FILE:
  1154. pcIcon = patchcanvas.ICON_FILE
  1155. patchcanvas.setGroupIcon(clientId, pcIcon)
  1156. self.updateMiniCanvasLater()
  1157. if pluginId < 0:
  1158. return
  1159. if pluginId >= self.fPluginCount and pluginId != MAIN_CARLA_PLUGIN_ID:
  1160. print("sorry, can't map this plugin to canvas client", pluginId, self.fPluginCount)
  1161. return
  1162. if pluginId == MAIN_CARLA_PLUGIN_ID:
  1163. hasCustomUI = False
  1164. else:
  1165. hasCustomUI = bool(self.host.get_plugin_info(pluginId)['hints'] & PLUGIN_HAS_CUSTOM_UI)
  1166. patchcanvas.setGroupAsPlugin(clientId, pluginId, hasCustomUI)
  1167. @pyqtSlot(int, int, int, str)
  1168. def slot_handlePatchbayPortAddedCallback(self, clientId, portId, portFlags, portName):
  1169. if portFlags & PATCHBAY_PORT_IS_INPUT:
  1170. portMode = patchcanvas.PORT_MODE_INPUT
  1171. else:
  1172. portMode = patchcanvas.PORT_MODE_OUTPUT
  1173. if portFlags & PATCHBAY_PORT_TYPE_AUDIO:
  1174. portType = patchcanvas.PORT_TYPE_AUDIO_JACK
  1175. isAlternate = False
  1176. elif portFlags & PATCHBAY_PORT_TYPE_CV:
  1177. portType = patchcanvas.PORT_TYPE_AUDIO_JACK
  1178. isAlternate = True
  1179. elif portFlags & PATCHBAY_PORT_TYPE_MIDI:
  1180. portType = patchcanvas.PORT_TYPE_MIDI_JACK
  1181. isAlternate = False
  1182. else:
  1183. portType = patchcanvas.PORT_TYPE_NULL
  1184. isAlternate = False
  1185. patchcanvas.addPort(clientId, portId, portName, portMode, portType, isAlternate)
  1186. self.updateMiniCanvasLater()
  1187. @pyqtSlot(int, int)
  1188. def slot_handlePatchbayPortRemovedCallback(self, groupId, portId):
  1189. patchcanvas.removePort(groupId, portId)
  1190. self.updateMiniCanvasLater()
  1191. @pyqtSlot(int, int, str)
  1192. def slot_handlePatchbayPortRenamedCallback(self, groupId, portId, newPortName):
  1193. patchcanvas.renamePort(groupId, portId, newPortName)
  1194. self.updateMiniCanvasLater()
  1195. @pyqtSlot(int, int, int, int, int)
  1196. def slot_handlePatchbayConnectionAddedCallback(self, connectionId, groupOutId, portOutId, groupInId, portInId):
  1197. patchcanvas.connectPorts(connectionId, groupOutId, portOutId, groupInId, portInId)
  1198. self.updateMiniCanvasLater()
  1199. @pyqtSlot(int, int, int)
  1200. def slot_handlePatchbayConnectionRemovedCallback(self, connectionId, portOutId, portInId):
  1201. patchcanvas.disconnectPorts(connectionId)
  1202. self.updateMiniCanvasLater()
  1203. # --------------------------------------------------------------------------------------------------------
  1204. # Settings
  1205. def saveSettings(self):
  1206. settings = QSettings()
  1207. settings.setValue("Geometry", self.saveGeometry())
  1208. settings.setValue("ShowToolbar", self.ui.toolBar.isEnabled())
  1209. settings.setValue("ShowSidePanel", self.ui.dockWidget.isEnabled())
  1210. diskFolders = []
  1211. for i in range(self.ui.cb_disk.count()):
  1212. diskFolders.append(self.ui.cb_disk.itemData(i))
  1213. settings.setValue("DiskFolders", diskFolders)
  1214. settings.setValue("LastBPM", self.fLastTransportBPM)
  1215. settings.setValue("ShowMeters", self.ui.act_settings_show_meters.isChecked())
  1216. settings.setValue("ShowKeyboard", self.ui.act_settings_show_keyboard.isChecked())
  1217. settings.setValue("HorizontalScrollBarValue", self.ui.graphicsView.horizontalScrollBar().value())
  1218. settings.setValue("VerticalScrollBarValue", self.ui.graphicsView.verticalScrollBar().value())
  1219. settings.setValue(CARLA_KEY_ENGINE_TRANSPORT_MODE, self.host.transportMode)
  1220. settings.setValue(CARLA_KEY_ENGINE_TRANSPORT_EXTRA, self.host.transportExtra)
  1221. def loadSettings(self, firstTime):
  1222. settings = QSettings()
  1223. if firstTime:
  1224. self.restoreGeometry(settings.value("Geometry", b""))
  1225. showToolbar = settings.value("ShowToolbar", True, type=bool)
  1226. self.ui.act_settings_show_toolbar.setChecked(showToolbar)
  1227. self.ui.toolBar.setEnabled(showToolbar)
  1228. self.ui.toolBar.setVisible(showToolbar)
  1229. #if settings.contains("SplitterState"):
  1230. #self.ui.splitter.restoreState(settings.value("SplitterState", b""))
  1231. #else:
  1232. #self.ui.splitter.setSizes([210, 99999])
  1233. showSidePanel = settings.value("ShowSidePanel", True, type=bool)
  1234. self.ui.act_settings_show_side_panel.setChecked(showSidePanel)
  1235. self.slot_showSidePanel(showSidePanel)
  1236. diskFolders = toList(settings.value("DiskFolders", [HOME]))
  1237. self.ui.cb_disk.setItemData(0, HOME)
  1238. for i in range(len(diskFolders)):
  1239. if i == 0: continue
  1240. folder = diskFolders[i]
  1241. self.ui.cb_disk.addItem(os.path.basename(folder), folder)
  1242. #if MACOS and not settings.value(CARLA_KEY_MAIN_USE_PRO_THEME, True, type=bool):
  1243. # self.setUnifiedTitleAndToolBarOnMac(True)
  1244. showMeters = settings.value("ShowMeters", True, type=bool)
  1245. self.ui.act_settings_show_meters.setChecked(showMeters)
  1246. self.ui.peak_in.setVisible(showMeters)
  1247. self.ui.peak_out.setVisible(showMeters)
  1248. showKeyboard = settings.value("ShowKeyboard", True, type=bool)
  1249. self.ui.act_settings_show_keyboard.setChecked(showKeyboard)
  1250. self.ui.scrollArea.setVisible(showKeyboard)
  1251. QTimer.singleShot(100, self.slot_restoreCanvasScrollbarValues)
  1252. # TODO - complete this
  1253. self.fSavedSettings = {
  1254. CARLA_KEY_MAIN_PROJECT_FOLDER: settings.value(CARLA_KEY_MAIN_PROJECT_FOLDER, CARLA_DEFAULT_MAIN_PROJECT_FOLDER, type=str),
  1255. CARLA_KEY_MAIN_CONFIRM_EXIT: settings.value(CARLA_KEY_MAIN_CONFIRM_EXIT, CARLA_DEFAULT_MAIN_CONFIRM_EXIT, type=bool),
  1256. CARLA_KEY_MAIN_REFRESH_INTERVAL: settings.value(CARLA_KEY_MAIN_REFRESH_INTERVAL, CARLA_DEFAULT_MAIN_REFRESH_INTERVAL, type=int),
  1257. CARLA_KEY_MAIN_EXPERIMENTAL: settings.value(CARLA_KEY_MAIN_EXPERIMENTAL, CARLA_DEFAULT_MAIN_EXPERIMENTAL, type=bool),
  1258. CARLA_KEY_CANVAS_THEME: settings.value(CARLA_KEY_CANVAS_THEME, CARLA_DEFAULT_CANVAS_THEME, type=str),
  1259. CARLA_KEY_CANVAS_SIZE: settings.value(CARLA_KEY_CANVAS_SIZE, CARLA_DEFAULT_CANVAS_SIZE, type=str),
  1260. CARLA_KEY_CANVAS_AUTO_HIDE_GROUPS: settings.value(CARLA_KEY_CANVAS_AUTO_HIDE_GROUPS, CARLA_DEFAULT_CANVAS_AUTO_HIDE_GROUPS, type=bool),
  1261. CARLA_KEY_CANVAS_AUTO_SELECT_ITEMS: settings.value(CARLA_KEY_CANVAS_AUTO_SELECT_ITEMS, CARLA_DEFAULT_CANVAS_AUTO_SELECT_ITEMS, type=bool),
  1262. CARLA_KEY_CANVAS_USE_BEZIER_LINES: settings.value(CARLA_KEY_CANVAS_USE_BEZIER_LINES, CARLA_DEFAULT_CANVAS_USE_BEZIER_LINES, type=bool),
  1263. CARLA_KEY_CANVAS_EYE_CANDY: settings.value(CARLA_KEY_CANVAS_EYE_CANDY, CARLA_DEFAULT_CANVAS_EYE_CANDY, type=bool),
  1264. CARLA_KEY_CANVAS_FANCY_EYE_CANDY: settings.value(CARLA_KEY_CANVAS_FANCY_EYE_CANDY, CARLA_DEFAULT_CANVAS_FANCY_EYE_CANDY, type=bool),
  1265. CARLA_KEY_CANVAS_USE_OPENGL: settings.value(CARLA_KEY_CANVAS_USE_OPENGL, CARLA_DEFAULT_CANVAS_USE_OPENGL, type=bool),
  1266. CARLA_KEY_CANVAS_ANTIALIASING: settings.value(CARLA_KEY_CANVAS_ANTIALIASING, CARLA_DEFAULT_CANVAS_ANTIALIASING, type=int),
  1267. CARLA_KEY_CANVAS_HQ_ANTIALIASING: settings.value(CARLA_KEY_CANVAS_HQ_ANTIALIASING, CARLA_DEFAULT_CANVAS_HQ_ANTIALIASING, type=bool),
  1268. CARLA_KEY_CUSTOM_PAINTING: (settings.value(CARLA_KEY_MAIN_USE_PRO_THEME, True, type=bool) and
  1269. settings.value(CARLA_KEY_MAIN_PRO_THEME_COLOR, "Black", type=str).lower() == "black"),
  1270. }
  1271. settings = QSettings("falkTX", "Carla2")
  1272. if self.host.experimental and not self.host.isControl:
  1273. visible = settings.value(CARLA_KEY_EXPERIMENTAL_JACK_APPS, CARLA_DEFAULT_EXPERIMENTAL_JACK_APPS, type=bool)
  1274. self.ui.act_add_jack.setVisible(visible)
  1275. self.ui.act_plugin_add_jack.setVisible(visible)
  1276. else:
  1277. self.ui.act_add_jack.setVisible(False)
  1278. self.ui.act_plugin_add_jack.setVisible(False)
  1279. self.fMiniCanvasUpdateTimeout = 1000 if self.fSavedSettings[CARLA_KEY_CANVAS_FANCY_EYE_CANDY] else 0
  1280. setEngineSettings(self.host)
  1281. self.restartTimersIfNeeded()
  1282. # --------------------------------------------------------------------------------------------------------
  1283. # Settings (helpers)
  1284. def enableTransport(self, enabled):
  1285. self.ui.group_transport_controls.setEnabled(enabled)
  1286. self.ui.group_transport_settings.setEnabled(enabled)
  1287. @pyqtSlot()
  1288. def slot_restoreCanvasScrollbarValues(self):
  1289. settings = QSettings()
  1290. self.ui.graphicsView.horizontalScrollBar().setValue(settings.value("HorizontalScrollBarValue", self.ui.graphicsView.horizontalScrollBar().maximum()/2, type=int))
  1291. self.ui.graphicsView.verticalScrollBar().setValue(settings.value("VerticalScrollBarValue", self.ui.graphicsView.verticalScrollBar().maximum()/2, type=int))
  1292. # --------------------------------------------------------------------------------------------------------
  1293. # Settings (menu actions)
  1294. @pyqtSlot(bool)
  1295. def slot_showSidePanel(self, yesNo):
  1296. self.ui.dockWidget.setEnabled(yesNo)
  1297. self.ui.dockWidget.setVisible(yesNo)
  1298. @pyqtSlot(bool)
  1299. def slot_showToolbar(self, yesNo):
  1300. self.ui.toolBar.setEnabled(yesNo)
  1301. self.ui.toolBar.setVisible(yesNo)
  1302. @pyqtSlot(bool)
  1303. def slot_showCanvasMeters(self, yesNo):
  1304. self.ui.peak_in.setVisible(yesNo)
  1305. self.ui.peak_out.setVisible(yesNo)
  1306. QTimer.singleShot(0, self.slot_miniCanvasCheckAll)
  1307. @pyqtSlot(bool)
  1308. def slot_showCanvasKeyboard(self, yesNo):
  1309. self.ui.scrollArea.setVisible(yesNo)
  1310. QTimer.singleShot(0, self.slot_miniCanvasCheckAll)
  1311. @pyqtSlot()
  1312. def slot_configureCarla(self):
  1313. dialog = CarlaSettingsW(self.fParentOrSelf, self.host, True, hasGL)
  1314. if not dialog.exec_():
  1315. return
  1316. self.loadSettings(False)
  1317. patchcanvas.clear()
  1318. self.setupCanvas()
  1319. self.slot_miniCanvasCheckAll()
  1320. if self.host.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK and self.host.isPlugin:
  1321. pass
  1322. elif self.host.is_engine_running():
  1323. self.host.patchbay_refresh(self.fExternalPatchbay)
  1324. # --------------------------------------------------------------------------------------------------------
  1325. # About (menu actions)
  1326. @pyqtSlot()
  1327. def slot_aboutCarla(self):
  1328. CarlaAboutW(self.fParentOrSelf, self.host).exec_()
  1329. @pyqtSlot()
  1330. def slot_aboutJuce(self):
  1331. JuceAboutW(self.fParentOrSelf).exec_()
  1332. @pyqtSlot()
  1333. def slot_aboutQt(self):
  1334. QApplication.instance().aboutQt()
  1335. # --------------------------------------------------------------------------------------------------------
  1336. # Disk (menu actions)
  1337. @pyqtSlot(int)
  1338. def slot_diskFolderChanged(self, index):
  1339. if index < 0:
  1340. return
  1341. elif index == 0:
  1342. filename = HOME
  1343. self.ui.b_disk_remove.setEnabled(False)
  1344. else:
  1345. filename = self.ui.cb_disk.itemData(index)
  1346. self.ui.b_disk_remove.setEnabled(True)
  1347. self.fDirModel.setRootPath(filename)
  1348. self.ui.fileTreeView.setRootIndex(self.fDirModel.index(filename))
  1349. @pyqtSlot()
  1350. def slot_diskFolderAdd(self):
  1351. newPath = QFileDialog.getExistingDirectory(self, self.tr("New Folder"), "", QFileDialog.ShowDirsOnly)
  1352. if newPath:
  1353. if newPath[-1] == os.sep:
  1354. newPath = newPath[:-1]
  1355. self.ui.cb_disk.addItem(os.path.basename(newPath), newPath)
  1356. self.ui.cb_disk.setCurrentIndex(self.ui.cb_disk.count()-1)
  1357. self.ui.b_disk_remove.setEnabled(True)
  1358. @pyqtSlot()
  1359. def slot_diskFolderRemove(self):
  1360. index = self.ui.cb_disk.currentIndex()
  1361. if index <= 0:
  1362. return
  1363. self.ui.cb_disk.removeItem(index)
  1364. if self.ui.cb_disk.currentIndex() == 0:
  1365. self.ui.b_disk_remove.setEnabled(False)
  1366. @pyqtSlot(QModelIndex)
  1367. def slot_fileTreeDoubleClicked(self, modelIndex):
  1368. filename = self.fDirModel.filePath(modelIndex)
  1369. if not self.ui.listWidget.isDragUrlValid(filename):
  1370. return
  1371. if not self.host.load_file(filename):
  1372. CustomMessageBox(self, QMessageBox.Critical, self.tr("Error"),
  1373. self.tr("Failed to load file"),
  1374. self.host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  1375. # --------------------------------------------------------------------------------------------------------
  1376. # Transport
  1377. def refreshTransport(self, forced = False):
  1378. if not self.isVisible():
  1379. return
  1380. if self.fSampleRate == 0.0 or not self.host.is_engine_running():
  1381. return
  1382. timeInfo = self.host.get_transport_info()
  1383. playing = timeInfo['playing']
  1384. frame = timeInfo['frame']
  1385. bpm = timeInfo['bpm']
  1386. if playing != self.fLastTransportState or forced:
  1387. if playing:
  1388. icon = getIcon("media-playback-pause")
  1389. self.ui.b_transport_play.setChecked(True)
  1390. self.ui.b_transport_play.setIcon(icon)
  1391. #self.ui.b_transport_play.setText(self.tr("&Pause"))
  1392. else:
  1393. icon = getIcon("media-playback-start")
  1394. self.ui.b_transport_play.setChecked(False)
  1395. self.ui.b_transport_play.setIcon(icon)
  1396. #self.ui.b_play.setText(self.tr("&Play"))
  1397. self.fLastTransportState = playing
  1398. if frame != self.fLastTransportFrame or forced:
  1399. self.fLastTransportFrame = frame
  1400. time = frame / self.fSampleRate
  1401. secs = time % 60
  1402. mins = (time / 60) % 60
  1403. hrs = (time / 3600) % 60
  1404. self.ui.l_transport_time.setText("%02i:%02i:%02i" % (hrs, mins, secs))
  1405. frame1 = frame % 1000
  1406. frame2 = (frame / 1000) % 1000
  1407. frame3 = (frame / 1000000) % 1000
  1408. self.ui.l_transport_frame.setText("%03i'%03i'%03i" % (frame3, frame2, frame1))
  1409. bar = timeInfo['bar']
  1410. beat = timeInfo['beat']
  1411. tick = timeInfo['tick']
  1412. self.ui.l_transport_bbt.setText("%03i|%02i|%04i" % (bar, beat, tick))
  1413. if bpm != self.fLastTransportBPM or forced:
  1414. self.fLastTransportBPM = bpm
  1415. if bpm > 0.0:
  1416. self.ui.dsb_transport_bpm.blockSignals(True)
  1417. self.ui.dsb_transport_bpm.setValue(bpm)
  1418. self.ui.dsb_transport_bpm.blockSignals(False)
  1419. self.ui.dsb_transport_bpm.setStyleSheet("")
  1420. else:
  1421. self.ui.dsb_transport_bpm.setStyleSheet("QDoubleSpinBox { color: palette(mid); }")
  1422. # --------------------------------------------------------------------------------------------------------
  1423. # Transport (menu actions)
  1424. @pyqtSlot(bool)
  1425. def slot_transportPlayPause(self, toggled):
  1426. if self.host.isPlugin or not self.host.is_engine_running():
  1427. return
  1428. if toggled:
  1429. self.host.transport_play()
  1430. else:
  1431. self.host.transport_pause()
  1432. self.refreshTransport()
  1433. @pyqtSlot()
  1434. def slot_transportStop(self):
  1435. if self.host.isPlugin or not self.host.is_engine_running():
  1436. return
  1437. self.host.transport_pause()
  1438. self.host.transport_relocate(0)
  1439. self.refreshTransport()
  1440. @pyqtSlot()
  1441. def slot_transportBackwards(self):
  1442. if self.host.isPlugin or not self.host.is_engine_running():
  1443. return
  1444. newFrame = self.host.get_current_transport_frame() - 100000
  1445. if newFrame < 0:
  1446. newFrame = 0
  1447. self.host.transport_relocate(newFrame)
  1448. @pyqtSlot(float)
  1449. def slot_transportBpmChanged(self, newValue):
  1450. self.host.transport_bpm(newValue)
  1451. @pyqtSlot()
  1452. def slot_transportForwards(self):
  1453. if self.fSampleRate == 0.0 or self.host.isPlugin or not self.host.is_engine_running():
  1454. return
  1455. newFrame = self.host.get_current_transport_frame() + int(self.fSampleRate*2.5)
  1456. self.host.transport_relocate(newFrame)
  1457. @pyqtSlot(bool)
  1458. def slot_transportJackEnabled(self, clicked):
  1459. if not self.host.is_engine_running():
  1460. return
  1461. self.host.transportMode = ENGINE_TRANSPORT_MODE_JACK if clicked else ENGINE_TRANSPORT_MODE_INTERNAL
  1462. self.host.set_engine_option(ENGINE_OPTION_TRANSPORT_MODE,
  1463. self.host.transportMode,
  1464. self.host.transportExtra)
  1465. @pyqtSlot(bool)
  1466. def slot_transportLinkEnabled(self, clicked):
  1467. if not self.host.is_engine_running():
  1468. return
  1469. extra = ":link:" if clicked else ""
  1470. self.host.transportExtra = extra
  1471. self.host.set_engine_option(ENGINE_OPTION_TRANSPORT_MODE,
  1472. self.host.transportMode,
  1473. self.host.transportExtra)
  1474. # --------------------------------------------------------------------------------------------------------
  1475. # Canvas scrollbars
  1476. @pyqtSlot(int)
  1477. def slot_horizontalScrollBarChanged(self, value):
  1478. maximum = self.ui.graphicsView.horizontalScrollBar().maximum()
  1479. if maximum == 0:
  1480. xp = 0
  1481. else:
  1482. xp = float(value) / maximum
  1483. self.ui.miniCanvasPreview.setViewPosX(xp)
  1484. self.updateCanvasInitialPos()
  1485. @pyqtSlot(int)
  1486. def slot_verticalScrollBarChanged(self, value):
  1487. maximum = self.ui.graphicsView.verticalScrollBar().maximum()
  1488. if maximum == 0:
  1489. yp = 0
  1490. else:
  1491. yp = float(value) / maximum
  1492. self.ui.miniCanvasPreview.setViewPosY(yp)
  1493. self.updateCanvasInitialPos()
  1494. # --------------------------------------------------------------------------------------------------------
  1495. # Canvas keyboard
  1496. @pyqtSlot(int)
  1497. def slot_noteOn(self, note):
  1498. for pluginId in self.fSelectedPlugins:
  1499. self.host.send_midi_note(pluginId, 0, note, 100)
  1500. pedit = self.getPluginEditDialog(pluginId)
  1501. pedit.noteOn(0, note, 100)
  1502. @pyqtSlot(int)
  1503. def slot_noteOff(self, note):
  1504. for pluginId in self.fSelectedPlugins:
  1505. self.host.send_midi_note(pluginId, 0, note, 0)
  1506. pedit = self.getPluginEditDialog(pluginId)
  1507. pedit.noteOff(0, note)
  1508. # --------------------------------------------------------------------------------------------------------
  1509. # Canvas keyboard (host callbacks)
  1510. @pyqtSlot(int, int, int, int)
  1511. def slot_handleNoteOnCallback(self, pluginId, channel, note, velocity):
  1512. if pluginId in self.fSelectedPlugins:
  1513. self.ui.keyboard.sendNoteOn(note, False)
  1514. @pyqtSlot(int, int, int)
  1515. def slot_handleNoteOffCallback(self, pluginId, channel, note):
  1516. if pluginId in self.fSelectedPlugins:
  1517. self.ui.keyboard.sendNoteOff(note, False)
  1518. # --------------------------------------------------------------------------------------------------------
  1519. @pyqtSlot(int)
  1520. def slot_handleUpdateCallback(self, pluginId):
  1521. pitem = self.getPluginItem(pluginId)
  1522. if pitem is None:
  1523. return
  1524. wasCompacted = pitem.isCompacted()
  1525. isCompacted = wasCompacted
  1526. check = self.host.get_custom_data_value(pluginId, CUSTOM_DATA_TYPE_PROPERTY, "CarlaSkinIsCompacted")
  1527. if not check:
  1528. return
  1529. isCompacted = bool(check == "true")
  1530. if wasCompacted == isCompacted:
  1531. return
  1532. pitem.recreateWidget(True)
  1533. # --------------------------------------------------------------------------------------------------------
  1534. # MiniCanvas stuff
  1535. @pyqtSlot()
  1536. def slot_miniCanvasCheckAll(self):
  1537. self.slot_miniCanvasCheckSize()
  1538. self.slot_horizontalScrollBarChanged(self.ui.graphicsView.horizontalScrollBar().value())
  1539. self.slot_verticalScrollBarChanged(self.ui.graphicsView.verticalScrollBar().value())
  1540. @pyqtSlot()
  1541. def slot_miniCanvasCheckSize(self):
  1542. if self.fCanvasWidth == 0 or self.fCanvasHeight == 0:
  1543. return
  1544. currentIndex = self.ui.tabWidget.currentIndex()
  1545. if currentIndex == 1:
  1546. width = self.ui.graphicsView.width()
  1547. height = self.ui.graphicsView.height()
  1548. else:
  1549. self.ui.tabWidget.blockSignals(True)
  1550. self.ui.tabWidget.setCurrentIndex(1)
  1551. width = self.ui.graphicsView.width()
  1552. height = self.ui.graphicsView.height()
  1553. self.ui.tabWidget.setCurrentIndex(currentIndex)
  1554. self.ui.tabWidget.blockSignals(False)
  1555. self.scene.updateLimits()
  1556. self.ui.miniCanvasPreview.setViewSize(float(width)/self.fCanvasWidth, float(height)/self.fCanvasHeight)
  1557. @pyqtSlot(float, float)
  1558. def slot_miniCanvasMoved(self, xp, yp):
  1559. hsb = self.ui.graphicsView.horizontalScrollBar()
  1560. vsb = self.ui.graphicsView.verticalScrollBar()
  1561. hsb.setValue(xp * hsb.maximum())
  1562. vsb.setValue(yp * vsb.maximum())
  1563. self.updateCanvasInitialPos()
  1564. # --------------------------------------------------------------------------------------------------------
  1565. # Timers
  1566. def startTimers(self):
  1567. if self.fIdleTimerFast == 0:
  1568. self.fIdleTimerFast = self.startTimer(self.fSavedSettings[CARLA_KEY_MAIN_REFRESH_INTERVAL])
  1569. if self.fIdleTimerSlow == 0:
  1570. self.fIdleTimerSlow = self.startTimer(self.fSavedSettings[CARLA_KEY_MAIN_REFRESH_INTERVAL]*4)
  1571. def restartTimersIfNeeded(self):
  1572. if self.fIdleTimerFast != 0:
  1573. self.killTimer(self.fIdleTimerFast)
  1574. self.fIdleTimerFast = self.startTimer(self.fSavedSettings[CARLA_KEY_MAIN_REFRESH_INTERVAL])
  1575. if self.fIdleTimerSlow != 0:
  1576. self.killTimer(self.fIdleTimerSlow)
  1577. self.fIdleTimerSlow = self.startTimer(self.fSavedSettings[CARLA_KEY_MAIN_REFRESH_INTERVAL]*4)
  1578. def killTimers(self):
  1579. if self.fIdleTimerFast != 0:
  1580. self.killTimer(self.fIdleTimerFast)
  1581. self.fIdleTimerFast = 0
  1582. if self.fIdleTimerSlow != 0:
  1583. self.killTimer(self.fIdleTimerSlow)
  1584. self.fIdleTimerSlow = 0
  1585. # --------------------------------------------------------------------------------------------------------
  1586. # Misc
  1587. @pyqtSlot(int)
  1588. def slot_tabChanged(self, index):
  1589. if index != 1:
  1590. return
  1591. self.ui.graphicsView.setFocus()
  1592. @pyqtSlot(int)
  1593. def slot_handleReloadAllCallback(self, pluginId):
  1594. if pluginId >= self.fPluginCount:
  1595. return
  1596. pitem = self.fPluginList[pluginId]
  1597. if pitem is None:
  1598. return
  1599. pitem.recreateWidget()
  1600. # --------------------------------------------------------------------------------------------------------
  1601. @pyqtSlot(int, int, str)
  1602. def slot_handleNSMCallback(self, value1, value2, valueStr):
  1603. # Error
  1604. if value1 == 0:
  1605. pass
  1606. # Reply
  1607. elif value1 == 1:
  1608. self.fFirstEngineInit = False
  1609. self.fSessionManagerName = valueStr
  1610. self.setProperWindowTitle()
  1611. # Open
  1612. elif value1 == 2:
  1613. self.fClientName = os.path.basename(valueStr)
  1614. self.fProjectFilename = QFileInfo(valueStr+".carxp").absoluteFilePath()
  1615. self.setProperWindowTitle()
  1616. self.fCustomStopAction = self.CUSTOM_ACTION_PROJECT_LOAD
  1617. self.slot_engineStop(True)
  1618. return
  1619. # Save
  1620. elif value1 == 3:
  1621. self.saveProjectNow()
  1622. # Session is Loaded
  1623. elif value1 == 4:
  1624. pass
  1625. # Show Optional Gui
  1626. elif value1 == 5:
  1627. self.show()
  1628. # Hide Optional Gui
  1629. elif value1 == 6:
  1630. self.hide()
  1631. self.host.nsm_ready(value1)
  1632. # --------------------------------------------------------------------------------------------------------
  1633. def fixLogText(self, text):
  1634. return text.replace("\x1b[30;1m", "").replace("\x1b[31m", "").replace("\x1b[0m", "")
  1635. @pyqtSlot(int, int, int, float, str)
  1636. def slot_handleDebugCallback(self, pluginId, value1, value2, value3, valueStr):
  1637. self.ui.text_logs.appendPlainText(self.fixLogText(valueStr))
  1638. @pyqtSlot(str)
  1639. def slot_handleInfoCallback(self, info):
  1640. QMessageBox.information(self, "Information", info)
  1641. @pyqtSlot(str)
  1642. def slot_handleErrorCallback(self, error):
  1643. QMessageBox.critical(self, "Error", error)
  1644. @pyqtSlot()
  1645. def slot_handleQuitCallback(self):
  1646. pass # TODO
  1647. # --------------------------------------------------------------------------------------------------------
  1648. @pyqtSlot()
  1649. def slot_handleSIGUSR1(self):
  1650. print("Got SIGUSR1 -> Saving project now")
  1651. self.slot_fileSave()
  1652. @pyqtSlot()
  1653. def slot_handleSIGTERM(self):
  1654. print("Got SIGTERM -> Closing now")
  1655. self.fCustomStopAction = self.CUSTOM_ACTION_APP_CLOSE
  1656. self.slot_engineStop(True)
  1657. # --------------------------------------------------------------------------------------------------------
  1658. # Internal stuff
  1659. def getExtraPtr(self, plugin):
  1660. ptype = plugin['type']
  1661. if ptype == PLUGIN_LADSPA:
  1662. uniqueId = plugin['uniqueId']
  1663. self.maybeLoadRDFs()
  1664. for rdfItem in self.fLadspaRdfList:
  1665. if rdfItem.UniqueID == uniqueId:
  1666. return pointer(rdfItem)
  1667. elif ptype == PLUGIN_SF2:
  1668. if plugin['name'].lower().endswith(" (16 outputs)"):
  1669. return self._true
  1670. return None
  1671. def maybeLoadRDFs(self):
  1672. if not self.fLadspaRdfNeedsUpdate:
  1673. return
  1674. self.fLadspaRdfNeedsUpdate = False
  1675. self.fLadspaRdfList = []
  1676. if not haveLRDF:
  1677. return
  1678. settingsDir = os.path.join(HOME, ".config", "falkTX")
  1679. frLadspaFile = os.path.join(settingsDir, "ladspa_rdf.db")
  1680. if os.path.exists(frLadspaFile):
  1681. frLadspa = open(frLadspaFile, 'r')
  1682. try:
  1683. self.fLadspaRdfList = ladspa_rdf.get_c_ladspa_rdfs(json.load(frLadspa))
  1684. except:
  1685. pass
  1686. frLadspa.close()
  1687. # --------------------------------------------------------------------------------------------------------
  1688. def getPluginCount(self):
  1689. return self.fPluginCount
  1690. def getPluginItem(self, pluginId):
  1691. if pluginId >= self.fPluginCount:
  1692. return None
  1693. pitem = self.fPluginList[pluginId]
  1694. if pitem is None:
  1695. return None
  1696. #if False:
  1697. #return CarlaRackItem(self, 0, False)
  1698. return pitem
  1699. def getPluginEditDialog(self, pluginId):
  1700. if pluginId >= self.fPluginCount:
  1701. return None
  1702. pitem = self.fPluginList[pluginId]
  1703. if pitem is None:
  1704. return None
  1705. if False:
  1706. return PluginEdit(self, self.host, 0)
  1707. return pitem.getEditDialog()
  1708. def getPluginSlotWidget(self, pluginId):
  1709. if pluginId >= self.fPluginCount:
  1710. return None
  1711. pitem = self.fPluginList[pluginId]
  1712. if pitem is None:
  1713. return None
  1714. #if False:
  1715. #return AbstractPluginSlot()
  1716. return pitem.getWidget()
  1717. # --------------------------------------------------------------------------------------------------------
  1718. def waitForPendingEvents(self):
  1719. pass
  1720. # --------------------------------------------------------------------------------------------------------
  1721. # show/hide event
  1722. def showEvent(self, event):
  1723. self.refreshTransport(True)
  1724. QMainWindow.showEvent(self, event)
  1725. # set our gui as parent for all plugins UIs
  1726. if self.host.manageUIs and not (self.host.isControl or self.host.isPlugin):
  1727. if MACOS:
  1728. nsViewPtr = int(self.winId())
  1729. winIdStr = "%x" % gCarla.utils.cocoa_get_window(nsViewPtr)
  1730. else:
  1731. winIdStr = "%x" % int(self.winId())
  1732. self.host.set_engine_option(ENGINE_OPTION_FRONTEND_WIN_ID, 0, winIdStr)
  1733. def hideEvent(self, event):
  1734. # disable parent
  1735. if not (self.host.isControl or self.host.isPlugin):
  1736. self.host.set_engine_option(ENGINE_OPTION_FRONTEND_WIN_ID, 0, "0")
  1737. QMainWindow.hideEvent(self, event)
  1738. # --------------------------------------------------------------------------------------------------------
  1739. # resize event
  1740. def resizeEvent(self, event):
  1741. QMainWindow.resizeEvent(self, event)
  1742. if self.fWithCanvas:
  1743. self.slot_miniCanvasCheckSize()
  1744. # --------------------------------------------------------------------------------------------------------
  1745. # timer event
  1746. def idleFast(self):
  1747. self.host.engine_idle()
  1748. self.refreshTransport()
  1749. if self.fPluginCount == 0 or self.fCurrentlyRemovingAllPlugins:
  1750. return
  1751. for pitem in self.fPluginList:
  1752. if pitem is None:
  1753. break
  1754. pitem.getWidget().idleFast()
  1755. for pluginId in self.fSelectedPlugins:
  1756. self.fPeaksCleared = False
  1757. if self.ui.peak_in.isVisible():
  1758. self.ui.peak_in.displayMeter(1, self.host.get_input_peak_value(pluginId, True))
  1759. self.ui.peak_in.displayMeter(2, self.host.get_input_peak_value(pluginId, False))
  1760. if self.ui.peak_out.isVisible():
  1761. self.ui.peak_out.displayMeter(1, self.host.get_output_peak_value(pluginId, True))
  1762. self.ui.peak_out.displayMeter(2, self.host.get_output_peak_value(pluginId, False))
  1763. return
  1764. if self.fPeaksCleared:
  1765. return
  1766. self.fPeaksCleared = True
  1767. self.ui.peak_in.displayMeter(1, 0.0, True)
  1768. self.ui.peak_in.displayMeter(2, 0.0, True)
  1769. self.ui.peak_out.displayMeter(1, 0.0, True)
  1770. self.ui.peak_out.displayMeter(2, 0.0, True)
  1771. def idleSlow(self):
  1772. if self.fPluginCount == 0 or self.fCurrentlyRemovingAllPlugins:
  1773. return
  1774. for pitem in self.fPluginList:
  1775. if pitem is None:
  1776. break
  1777. pitem.getWidget().idleSlow()
  1778. def timerEvent(self, event):
  1779. if event.timerId() == self.fIdleTimerFast:
  1780. self.idleFast()
  1781. elif event.timerId() == self.fIdleTimerSlow:
  1782. self.idleSlow()
  1783. QMainWindow.timerEvent(self, event)
  1784. # --------------------------------------------------------------------------------------------------------
  1785. # color/style change event
  1786. def changeEvent(self, event):
  1787. if event.type() in (QEvent.PaletteChange, QEvent.StyleChange):
  1788. self.updateStyle()
  1789. QWidget.changeEvent(self, event)
  1790. def updateStyle(self):
  1791. # Rack padding images setup
  1792. rack_imgL = QImage(":/bitmaps/rack_padding_left.png")
  1793. rack_imgR = QImage(":/bitmaps/rack_padding_right.png")
  1794. min_value = 0.07
  1795. if PYQT_VERSION >= 0x50600:
  1796. value_fix = 1.0/(1.0-rack_imgL.scaled(1, 1, Qt.IgnoreAspectRatio, Qt.SmoothTransformation).pixelColor(0,0).blackF())
  1797. else:
  1798. value_fix = 1.5
  1799. bg_color = self.ui.rack.palette().window().color()
  1800. bg_value = 1.0 - bg_color.blackF()
  1801. if bg_value != 0.0 and bg_value < min_value:
  1802. pad_color = bg_color.lighter(100*min_value/bg_value*value_fix)
  1803. else:
  1804. pad_color = QColor.fromHsvF(0.0, 0.0, min_value*value_fix)
  1805. painter = QPainter()
  1806. fillRect = rack_imgL.rect().adjusted(-1,-1,1,1)
  1807. painter.begin(rack_imgL)
  1808. painter.setCompositionMode(QPainter.CompositionMode_Multiply)
  1809. painter.setBrush(pad_color)
  1810. painter.drawRect(fillRect)
  1811. painter.end()
  1812. rack_pixmapL = QPixmap(rack_imgL)
  1813. self.imgL_palette = QPalette()
  1814. self.imgL_palette.setBrush(QPalette.Window, QBrush(rack_pixmapL))
  1815. self.ui.pad_left.setPalette(self.imgL_palette)
  1816. self.ui.pad_left.setAutoFillBackground(True)
  1817. painter.begin(rack_imgR)
  1818. painter.setCompositionMode(QPainter.CompositionMode_Multiply)
  1819. painter.setBrush(pad_color)
  1820. painter.drawRect(fillRect)
  1821. painter.end()
  1822. rack_pixmapR = QPixmap(rack_imgR)
  1823. self.imgR_palette = QPalette()
  1824. self.imgR_palette.setBrush(QPalette.Window, QBrush(rack_pixmapR))
  1825. self.ui.pad_right.setPalette(self.imgR_palette)
  1826. self.ui.pad_right.setAutoFillBackground(True)
  1827. # --------------------------------------------------------------------------------------------------------
  1828. # paint event
  1829. #def paintEvent(self, event):
  1830. #QMainWindow.paintEvent(self, event)
  1831. #if MACOS or not self.fSavedSettings[CARLA_KEY_CUSTOM_PAINTING]:
  1832. #return
  1833. #painter = QPainter(self)
  1834. #painter.setBrush(QColor(36, 36, 36))
  1835. #painter.setPen(QColor(62, 62, 62))
  1836. #painter.drawRect(1, self.height()/2, self.width()-3, self.height()-self.height()/2-1)
  1837. # --------------------------------------------------------------------------------------------------------
  1838. # close event
  1839. def shouldIgnoreClose(self):
  1840. if self.host.isControl or self.host.isPlugin:
  1841. return False
  1842. if self.fCustomStopAction == self.CUSTOM_ACTION_APP_CLOSE:
  1843. return False
  1844. if self.fSavedSettings[CARLA_KEY_MAIN_CONFIRM_EXIT]:
  1845. return QMessageBox.question(self, self.tr("Quit"),
  1846. self.tr("Are you sure you want to quit Carla?"),
  1847. QMessageBox.Yes|QMessageBox.No) == QMessageBox.No
  1848. return False
  1849. def closeEvent(self, event):
  1850. if self.shouldIgnoreClose():
  1851. event.ignore()
  1852. return
  1853. if MACOS and self.fMacClosingHelper and not (self.host.isControl or self.host.isPlugin):
  1854. self.fCustomStopAction = self.CUSTOM_ACTION_APP_CLOSE
  1855. self.fMacClosingHelper = False
  1856. event.ignore()
  1857. for i in reversed(range(self.fPluginCount)):
  1858. self.host.show_custom_ui(i, False)
  1859. QTimer.singleShot(100, self.close)
  1860. return
  1861. self.killTimers()
  1862. self.saveSettings()
  1863. if self.host.is_engine_running() and not (self.host.isControl or self.host.isPlugin):
  1864. if not self.slot_engineStop(True):
  1865. self.fCustomStopAction = self.CUSTOM_ACTION_APP_CLOSE
  1866. event.ignore()
  1867. return
  1868. QMainWindow.closeEvent(self, event)
  1869. # ------------------------------------------------------------------------------------------------
  1870. # Canvas callback
  1871. def canvasCallback(action, value1, value2, valueStr):
  1872. host = gCarla.gui.host
  1873. if action == patchcanvas.ACTION_GROUP_INFO:
  1874. pass
  1875. elif action == patchcanvas.ACTION_GROUP_RENAME:
  1876. pass
  1877. elif action == patchcanvas.ACTION_GROUP_SPLIT:
  1878. groupId = value1
  1879. patchcanvas.splitGroup(groupId)
  1880. gCarla.gui.updateMiniCanvasLater()
  1881. elif action == patchcanvas.ACTION_GROUP_JOIN:
  1882. groupId = value1
  1883. patchcanvas.joinGroup(groupId)
  1884. gCarla.gui.updateMiniCanvasLater()
  1885. elif action == patchcanvas.ACTION_PORT_INFO:
  1886. pass
  1887. elif action == patchcanvas.ACTION_PORT_RENAME:
  1888. pass
  1889. elif action == patchcanvas.ACTION_PORTS_CONNECT:
  1890. gOut, pOut, gIn, pIn = [int(i) for i in valueStr.split(":")]
  1891. if not host.patchbay_connect(gOut, pOut, gIn, pIn):
  1892. print("Connection failed:", host.get_last_error())
  1893. elif action == patchcanvas.ACTION_PORTS_DISCONNECT:
  1894. connectionId = value1
  1895. if not host.patchbay_disconnect(connectionId):
  1896. print("Disconnect failed:", host.get_last_error())
  1897. elif action == patchcanvas.ACTION_PLUGIN_CLONE:
  1898. pluginId = value1
  1899. if not host.clone_plugin(pluginId):
  1900. CustomMessageBox(gCarla.gui, QMessageBox.Warning, gCarla.gui.tr("Error"), gCarla.gui.tr("Operation failed"),
  1901. host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  1902. elif action == patchcanvas.ACTION_PLUGIN_EDIT:
  1903. pluginId = value1
  1904. pwidget = gCarla.gui.getPluginSlotWidget(pluginId)
  1905. if pwidget is not None:
  1906. pwidget.showEditDialog()
  1907. elif action == patchcanvas.ACTION_PLUGIN_RENAME:
  1908. pluginId = value1
  1909. pwidget = gCarla.gui.getPluginSlotWidget(pluginId)
  1910. if pwidget is not None:
  1911. pwidget.showRenameDialog()
  1912. elif action == patchcanvas.ACTION_PLUGIN_REPLACE:
  1913. pluginId = value1
  1914. pwidget = gCarla.gui.getPluginSlotWidget(pluginId)
  1915. if pwidget is not None:
  1916. pwidget.showReplaceDialog()
  1917. elif action == patchcanvas.ACTION_PLUGIN_REMOVE:
  1918. pluginId = value1
  1919. if not host.remove_plugin(pluginId):
  1920. CustomMessageBox(gCarla.gui, QMessageBox.Warning, gCarla.gui.tr("Error"), gCarla.gui.tr("Operation failed"),
  1921. host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  1922. elif action == patchcanvas.ACTION_PLUGIN_SHOW_UI:
  1923. pluginId = value1
  1924. pwidget = gCarla.gui.getPluginSlotWidget(pluginId)
  1925. if pwidget is not None:
  1926. pwidget.showCustomUI()
  1927. elif action == patchcanvas.ACTION_BG_RIGHT_CLICK:
  1928. gCarla.gui.showPluginActionsMenu()
  1929. # ------------------------------------------------------------------------------------------------------------
  1930. # Engine callback
  1931. def engineCallback(host, action, pluginId, value1, value2, value3, valueStr):
  1932. # kdevelop likes this :)
  1933. if False: host = CarlaHostNull()
  1934. valueStr = charPtrToString(valueStr)
  1935. if action == ENGINE_CALLBACK_ENGINE_STARTED:
  1936. host.processMode = value1
  1937. host.transportMode = value2
  1938. elif action == ENGINE_CALLBACK_PROCESS_MODE_CHANGED:
  1939. host.processMode = value1
  1940. elif action == ENGINE_CALLBACK_TRANSPORT_MODE_CHANGED:
  1941. host.transportMode = value1
  1942. host.transportExtra = valueStr
  1943. if action == ENGINE_CALLBACK_DEBUG:
  1944. host.DebugCallback.emit(pluginId, value1, value2, value3, valueStr)
  1945. elif action == ENGINE_CALLBACK_PLUGIN_ADDED:
  1946. host.PluginAddedCallback.emit(pluginId, valueStr)
  1947. elif action == ENGINE_CALLBACK_PLUGIN_REMOVED:
  1948. host.PluginRemovedCallback.emit(pluginId)
  1949. elif action == ENGINE_CALLBACK_PLUGIN_RENAMED:
  1950. host.PluginRenamedCallback.emit(pluginId, valueStr)
  1951. elif action == ENGINE_CALLBACK_PLUGIN_UNAVAILABLE:
  1952. host.PluginUnavailableCallback.emit(pluginId, valueStr)
  1953. elif action == ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED:
  1954. host.ParameterValueChangedCallback.emit(pluginId, value1, value3)
  1955. elif action == ENGINE_CALLBACK_PARAMETER_DEFAULT_CHANGED:
  1956. host.ParameterDefaultChangedCallback.emit(pluginId, value1, value3)
  1957. elif action == ENGINE_CALLBACK_PARAMETER_MIDI_CC_CHANGED:
  1958. host.ParameterMidiCcChangedCallback.emit(pluginId, value1, value2)
  1959. elif action == ENGINE_CALLBACK_PARAMETER_MIDI_CHANNEL_CHANGED:
  1960. host.ParameterMidiChannelChangedCallback.emit(pluginId, value1, value2)
  1961. elif action == ENGINE_CALLBACK_PROGRAM_CHANGED:
  1962. host.ProgramChangedCallback.emit(pluginId, value1)
  1963. elif action == ENGINE_CALLBACK_MIDI_PROGRAM_CHANGED:
  1964. host.MidiProgramChangedCallback.emit(pluginId, value1)
  1965. elif action == ENGINE_CALLBACK_OPTION_CHANGED:
  1966. host.OptionChangedCallback.emit(pluginId, value1, bool(value2))
  1967. elif action == ENGINE_CALLBACK_UI_STATE_CHANGED:
  1968. host.UiStateChangedCallback.emit(pluginId, value1)
  1969. elif action == ENGINE_CALLBACK_NOTE_ON:
  1970. host.NoteOnCallback.emit(pluginId, value1, value2, round(value3))
  1971. elif action == ENGINE_CALLBACK_NOTE_OFF:
  1972. host.NoteOffCallback.emit(pluginId, value1, value2)
  1973. elif action == ENGINE_CALLBACK_UPDATE:
  1974. host.UpdateCallback.emit(pluginId)
  1975. elif action == ENGINE_CALLBACK_RELOAD_INFO:
  1976. host.ReloadInfoCallback.emit(pluginId)
  1977. elif action == ENGINE_CALLBACK_RELOAD_PARAMETERS:
  1978. host.ReloadParametersCallback.emit(pluginId)
  1979. elif action == ENGINE_CALLBACK_RELOAD_PROGRAMS:
  1980. host.ReloadProgramsCallback.emit(pluginId)
  1981. elif action == ENGINE_CALLBACK_RELOAD_ALL:
  1982. host.ReloadAllCallback.emit(pluginId)
  1983. elif action == ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED:
  1984. host.PatchbayClientAddedCallback.emit(pluginId, value1, value2, valueStr)
  1985. elif action == ENGINE_CALLBACK_PATCHBAY_CLIENT_REMOVED:
  1986. host.PatchbayClientRemovedCallback.emit(pluginId)
  1987. elif action == ENGINE_CALLBACK_PATCHBAY_CLIENT_RENAMED:
  1988. host.PatchbayClientRenamedCallback.emit(pluginId, valueStr)
  1989. elif action == ENGINE_CALLBACK_PATCHBAY_CLIENT_DATA_CHANGED:
  1990. host.PatchbayClientDataChangedCallback.emit(pluginId, value1, value2)
  1991. elif action == ENGINE_CALLBACK_PATCHBAY_PORT_ADDED:
  1992. host.PatchbayPortAddedCallback.emit(pluginId, value1, value2, valueStr)
  1993. elif action == ENGINE_CALLBACK_PATCHBAY_PORT_REMOVED:
  1994. host.PatchbayPortRemovedCallback.emit(pluginId, value1)
  1995. elif action == ENGINE_CALLBACK_PATCHBAY_PORT_RENAMED:
  1996. host.PatchbayPortRenamedCallback.emit(pluginId, value1, valueStr)
  1997. elif action == ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED:
  1998. gOut, pOut, gIn, pIn = [int(i) for i in valueStr.split(":")] # FIXME
  1999. host.PatchbayConnectionAddedCallback.emit(pluginId, gOut, pOut, gIn, pIn)
  2000. elif action == ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED:
  2001. host.PatchbayConnectionRemovedCallback.emit(pluginId, value1, value2)
  2002. elif action == ENGINE_CALLBACK_ENGINE_STARTED:
  2003. host.EngineStartedCallback.emit(value1, value2, value3, valueStr)
  2004. elif action == ENGINE_CALLBACK_ENGINE_STOPPED:
  2005. host.EngineStoppedCallback.emit()
  2006. elif action == ENGINE_CALLBACK_PROCESS_MODE_CHANGED:
  2007. host.ProcessModeChangedCallback.emit(value1)
  2008. elif action == ENGINE_CALLBACK_TRANSPORT_MODE_CHANGED:
  2009. host.TransportModeChangedCallback.emit(value1, valueStr)
  2010. elif action == ENGINE_CALLBACK_BUFFER_SIZE_CHANGED:
  2011. host.BufferSizeChangedCallback.emit(value1)
  2012. elif action == ENGINE_CALLBACK_SAMPLE_RATE_CHANGED:
  2013. host.SampleRateChangedCallback.emit(value3)
  2014. elif action == ENGINE_CALLBACK_CANCELABLE_ACTION:
  2015. host.CancelableActionCallback.emit(pluginId, bool(value1 != 0), valueStr)
  2016. elif action == ENGINE_CALLBACK_PROJECT_LOAD_FINISHED:
  2017. host.ProjectLoadFinishedCallback.emit()
  2018. elif action == ENGINE_CALLBACK_NSM:
  2019. host.NSMCallback.emit(value1, value2, valueStr)
  2020. elif action == ENGINE_CALLBACK_IDLE:
  2021. QApplication.processEvents()
  2022. elif action == ENGINE_CALLBACK_INFO:
  2023. host.InfoCallback.emit(valueStr)
  2024. elif action == ENGINE_CALLBACK_ERROR:
  2025. host.ErrorCallback.emit(valueStr)
  2026. elif action == ENGINE_CALLBACK_QUIT:
  2027. host.QuitCallback.emit()
  2028. # ------------------------------------------------------------------------------------------------------------
  2029. # File callback
  2030. def fileCallback(ptr, action, isDir, title, filter):
  2031. title = charPtrToString(title)
  2032. filter = charPtrToString(filter)
  2033. if action == FILE_CALLBACK_OPEN:
  2034. ret, ok = QFileDialog.getOpenFileName(gCarla.gui, title, "", filter) #, QFileDialog.ShowDirsOnly if isDir else 0x0)
  2035. elif action == FILE_CALLBACK_SAVE:
  2036. ret, ok = QFileDialog.getSaveFileName(gCarla.gui, title, "", filter, QFileDialog.ShowDirsOnly if isDir else 0x0)
  2037. else:
  2038. ret, ok = ("", "")
  2039. # FIXME use ok value, test if it works as expected
  2040. if not ret:
  2041. return None
  2042. # FIXME
  2043. global fileRet
  2044. fileRet = c_char_p(ret.encode("utf-8"))
  2045. retval = cast(byref(fileRet), POINTER(c_uintptr))
  2046. return retval.contents.value
  2047. # ------------------------------------------------------------------------------------------------------------
  2048. # Init host
  2049. def initHost(initName, libPrefix, isControl, isPlugin, failError, HostClass = None):
  2050. pathBinaries, pathResources = getPaths(libPrefix)
  2051. # --------------------------------------------------------------------------------------------------------
  2052. # Check if we should open main lib as local or global
  2053. settings = QSettings("falkTX", "Carla2")
  2054. try:
  2055. loadGlobal = settings.value(CARLA_KEY_EXPERIMENTAL_LOAD_LIB_GLOBAL, CARLA_DEFAULT_EXPERIMENTAL_LOAD_LIB_GLOBAL, type=bool)
  2056. except:
  2057. loadGlobal = CARLA_DEFAULT_EXPERIMENTAL_LOAD_LIB_GLOBAL
  2058. # --------------------------------------------------------------------------------------------------------
  2059. # Fail if binary dir is not found
  2060. if not os.path.exists(pathBinaries):
  2061. if failError:
  2062. QMessageBox.critical(None, "Error", "Failed to find the carla binaries, cannot continue")
  2063. sys.exit(1)
  2064. return
  2065. # --------------------------------------------------------------------------------------------------------
  2066. # Set Carla library name
  2067. libname = "libcarla_%s2.%s" % ("control" if isControl else "standalone", DLL_EXTENSION)
  2068. libname = os.path.join(pathBinaries, libname)
  2069. utilsname = os.path.join(pathBinaries, "libcarla_utils.%s" % (DLL_EXTENSION))
  2070. # --------------------------------------------------------------------------------------------------------
  2071. # Print info
  2072. print("Carla %s started, status:" % VERSION)
  2073. print(" Python version: %s" % sys.version.split(" ",1)[0])
  2074. print(" Qt version: %s" % qVersion())
  2075. print(" PyQt version: %s" % PYQT_VERSION_STR)
  2076. print(" Binary dir: %s" % pathBinaries)
  2077. print(" Resources dir: %s" % pathResources)
  2078. # --------------------------------------------------------------------------------------------------------
  2079. # Init host
  2080. if failError:
  2081. # no try
  2082. host = HostClass() if HostClass is not None else CarlaHostQtDLL(libname, loadGlobal)
  2083. else:
  2084. try:
  2085. host = HostClass() if HostClass is not None else CarlaHostQtDLL(libname, loadGlobal)
  2086. except:
  2087. host = CarlaHostQtNull()
  2088. host.isControl = isControl
  2089. host.isPlugin = isPlugin
  2090. host.set_engine_callback(lambda h,a,p,v1,v2,v3,vs: engineCallback(host,a,p,v1,v2,v3,vs))
  2091. host.set_file_callback(fileCallback)
  2092. # If it's a plugin the paths are already set
  2093. if not isPlugin:
  2094. host.pathBinaries = pathBinaries
  2095. host.pathResources = pathResources
  2096. host.set_engine_option(ENGINE_OPTION_PATH_BINARIES, 0, pathBinaries)
  2097. host.set_engine_option(ENGINE_OPTION_PATH_RESOURCES, 0, pathResources)
  2098. if not isControl:
  2099. host.nsmOK = host.nsm_init(os.getpid(), initName)
  2100. # --------------------------------------------------------------------------------------------------------
  2101. # Init utils
  2102. gCarla.utils = CarlaUtils(utilsname)
  2103. gCarla.utils.set_process_name(os.path.basename(initName))
  2104. try:
  2105. sys.stdout.flush()
  2106. except:
  2107. pass
  2108. sys.stdout = CarlaPrint(False)
  2109. sys.stderr = CarlaPrint(True)
  2110. sys.excepthook = sys_excepthook
  2111. # --------------------------------------------------------------------------------------------------------
  2112. # Done
  2113. return host
  2114. # ------------------------------------------------------------------------------------------------------------
  2115. # Load host settings
  2116. def loadHostSettings(host):
  2117. # kdevelop likes this :)
  2118. if False: host = CarlaHostNull()
  2119. settings = QSettings("falkTX", "Carla2")
  2120. try:
  2121. host.experimental = settings.value(CARLA_KEY_MAIN_EXPERIMENTAL, CARLA_DEFAULT_MAIN_EXPERIMENTAL, type=bool)
  2122. except:
  2123. host.experimental = CARLA_DEFAULT_MAIN_EXPERIMENTAL
  2124. try:
  2125. host.exportLV2 = settings.value(CARLA_KEY_EXPERIMENTAL_EXPORT_LV2, CARLA_DEFAULT_EXPERIMENTAL_LV2_EXPORT, type=bool)
  2126. except:
  2127. host.exportLV2 = CARLA_DEFAULT_EXPERIMENTAL_LV2_EXPORT
  2128. try:
  2129. host.manageUIs = settings.value(CARLA_KEY_ENGINE_MANAGE_UIS, CARLA_DEFAULT_MANAGE_UIS, type=bool)
  2130. except:
  2131. host.manageUIs = CARLA_DEFAULT_MANAGE_UIS
  2132. try:
  2133. host.maxParameters = settings.value(CARLA_KEY_ENGINE_MAX_PARAMETERS, CARLA_DEFAULT_MAX_PARAMETERS, type=int)
  2134. except:
  2135. host.maxParameters = CARLA_DEFAULT_MAX_PARAMETERS
  2136. try:
  2137. host.forceStereo = settings.value(CARLA_KEY_ENGINE_FORCE_STEREO, CARLA_DEFAULT_FORCE_STEREO, type=bool)
  2138. except:
  2139. host.forceStereo = CARLA_DEFAULT_FORCE_STEREO
  2140. try:
  2141. host.preferPluginBridges = settings.value(CARLA_KEY_ENGINE_PREFER_PLUGIN_BRIDGES, CARLA_DEFAULT_PREFER_PLUGIN_BRIDGES, type=bool)
  2142. except:
  2143. host.preferPluginBridges = CARLA_DEFAULT_PREFER_PLUGIN_BRIDGES
  2144. try:
  2145. host.preferUIBridges = settings.value(CARLA_KEY_ENGINE_PREFER_UI_BRIDGES, CARLA_DEFAULT_PREFER_UI_BRIDGES, type=bool)
  2146. except:
  2147. host.preferUIBridges = CARLA_DEFAULT_PREFER_UI_BRIDGES
  2148. try:
  2149. host.preventBadBehaviour = settings.value(CARLA_KEY_EXPERIMENTAL_PREVENT_BAD_BEHAVIOUR, CARLA_DEFAULT_EXPERIMENTAL_PREVENT_BAD_BEHAVIOUR, type=bool)
  2150. except:
  2151. host.preventBadBehaviour = CARLA_DEFAULT_EXPERIMENTAL_PREVENT_BAD_BEHAVIOUR
  2152. try:
  2153. host.showLogs = settings.value(CARLA_KEY_MAIN_SHOW_LOGS, CARLA_DEFAULT_MAIN_SHOW_LOGS, type=bool)
  2154. except:
  2155. host.showLogs = CARLA_DEFAULT_MAIN_SHOW_LOGS
  2156. try:
  2157. host.showPluginBridges = settings.value(CARLA_KEY_EXPERIMENTAL_PLUGIN_BRIDGES, CARLA_DEFAULT_EXPERIMENTAL_PLUGIN_BRIDGES, type=bool)
  2158. except:
  2159. host.showPluginBridges = CARLA_DEFAULT_EXPERIMENTAL_PLUGIN_BRIDGES
  2160. try:
  2161. host.showWineBridges = settings.value(CARLA_KEY_EXPERIMENTAL_WINE_BRIDGES, CARLA_DEFAULT_EXPERIMENTAL_WINE_BRIDGES, type=bool)
  2162. except:
  2163. host.showWineBridges = CARLA_DEFAULT_EXPERIMENTAL_WINE_BRIDGES
  2164. try:
  2165. host.uiBridgesTimeout = settings.value(CARLA_KEY_ENGINE_UI_BRIDGES_TIMEOUT, CARLA_DEFAULT_UI_BRIDGES_TIMEOUT, type=int)
  2166. except:
  2167. host.uiBridgesTimeout = CARLA_DEFAULT_UI_BRIDGES_TIMEOUT
  2168. try:
  2169. host.uisAlwaysOnTop = settings.value(CARLA_KEY_ENGINE_UIS_ALWAYS_ON_TOP, CARLA_DEFAULT_UIS_ALWAYS_ON_TOP, type=bool)
  2170. except:
  2171. host.uisAlwaysOnTop = CARLA_DEFAULT_UIS_ALWAYS_ON_TOP
  2172. if host.isPlugin:
  2173. return
  2174. try:
  2175. host.transportExtra = settings.value(CARLA_KEY_ENGINE_TRANSPORT_EXTRA, "", type=str)
  2176. except:
  2177. host.transportExtra = ""
  2178. # enums
  2179. if host.audioDriverForced is None:
  2180. try:
  2181. host.transportMode = settings.value(CARLA_KEY_ENGINE_TRANSPORT_MODE, CARLA_DEFAULT_TRANSPORT_MODE, type=int)
  2182. except:
  2183. host.transportMode = CARLA_DEFAULT_TRANSPORT_MODE
  2184. if not host.processModeForced:
  2185. try:
  2186. host.processMode = settings.value(CARLA_KEY_ENGINE_PROCESS_MODE, CARLA_DEFAULT_PROCESS_MODE, type=int)
  2187. except:
  2188. host.processMode = CARLA_DEFAULT_PROCESS_MODE
  2189. host.nextProcessMode = host.processMode
  2190. # --------------------------------------------------------------------------------------------------------
  2191. # fix things if needed
  2192. if host.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS:
  2193. if LADISH_APP_NAME:
  2194. print("LADISH detected but using multiple clients (not allowed), forcing single client now")
  2195. host.nextProcessMode = host.processMode = ENGINE_PROCESS_MODE_SINGLE_CLIENT
  2196. else:
  2197. host.transportMode = ENGINE_TRANSPORT_MODE_JACK
  2198. if gCarla.nogui:
  2199. host.showLogs = False
  2200. # --------------------------------------------------------------------------------------------------------
  2201. # run headless host now if nogui option enabled
  2202. if gCarla.nogui:
  2203. runHostWithoutUI(host)
  2204. # ------------------------------------------------------------------------------------------------------------
  2205. # Set host settings
  2206. def setHostSettings(host):
  2207. # kdevelop likes this :)
  2208. if False: host = CarlaHostNull()
  2209. host.set_engine_option(ENGINE_OPTION_FORCE_STEREO, host.forceStereo, "")
  2210. host.set_engine_option(ENGINE_OPTION_MAX_PARAMETERS, host.maxParameters, "")
  2211. host.set_engine_option(ENGINE_OPTION_PREFER_PLUGIN_BRIDGES, host.preferPluginBridges, "")
  2212. host.set_engine_option(ENGINE_OPTION_PREFER_UI_BRIDGES, host.preferUIBridges, "")
  2213. host.set_engine_option(ENGINE_OPTION_PREVENT_BAD_BEHAVIOUR, host.preventBadBehaviour, "")
  2214. host.set_engine_option(ENGINE_OPTION_UI_BRIDGES_TIMEOUT, host.uiBridgesTimeout, "")
  2215. host.set_engine_option(ENGINE_OPTION_UIS_ALWAYS_ON_TOP, host.uisAlwaysOnTop, "")
  2216. if host.isPlugin or host.isRemote or host.is_engine_running():
  2217. return
  2218. host.set_engine_option(ENGINE_OPTION_PROCESS_MODE, host.nextProcessMode, "")
  2219. host.set_engine_option(ENGINE_OPTION_TRANSPORT_MODE, host.transportMode, host.transportExtra)
  2220. host.set_engine_option(ENGINE_OPTION_DEBUG_CONSOLE_OUTPUT, host.showLogs, "")
  2221. # ------------------------------------------------------------------------------------------------------------
  2222. # Set Engine settings according to carla preferences. Returns selected audio driver.
  2223. def setEngineSettings(host):
  2224. # kdevelop likes this :)
  2225. if False: host = CarlaHostNull()
  2226. # --------------------------------------------------------------------------------------------------------
  2227. # do nothing if control
  2228. if host.isControl:
  2229. return "Control"
  2230. # --------------------------------------------------------------------------------------------------------
  2231. settings = QSettings("falkTX", "Carla2")
  2232. # --------------------------------------------------------------------------------------------------------
  2233. # main settings
  2234. setHostSettings(host)
  2235. # --------------------------------------------------------------------------------------------------------
  2236. # plugin paths
  2237. LADSPA_PATH = toList(settings.value(CARLA_KEY_PATHS_LADSPA, CARLA_DEFAULT_LADSPA_PATH))
  2238. DSSI_PATH = toList(settings.value(CARLA_KEY_PATHS_DSSI, CARLA_DEFAULT_DSSI_PATH))
  2239. LV2_PATH = toList(settings.value(CARLA_KEY_PATHS_LV2, CARLA_DEFAULT_LV2_PATH))
  2240. VST2_PATH = toList(settings.value(CARLA_KEY_PATHS_VST2, CARLA_DEFAULT_VST2_PATH))
  2241. VST3_PATH = toList(settings.value(CARLA_KEY_PATHS_VST3, CARLA_DEFAULT_VST3_PATH))
  2242. SF2_PATH = toList(settings.value(CARLA_KEY_PATHS_SF2, CARLA_DEFAULT_SF2_PATH))
  2243. SFZ_PATH = toList(settings.value(CARLA_KEY_PATHS_SFZ, CARLA_DEFAULT_SFZ_PATH))
  2244. host.set_engine_option(ENGINE_OPTION_PLUGIN_PATH, PLUGIN_LADSPA, splitter.join(LADSPA_PATH))
  2245. host.set_engine_option(ENGINE_OPTION_PLUGIN_PATH, PLUGIN_DSSI, splitter.join(DSSI_PATH))
  2246. host.set_engine_option(ENGINE_OPTION_PLUGIN_PATH, PLUGIN_LV2, splitter.join(LV2_PATH))
  2247. host.set_engine_option(ENGINE_OPTION_PLUGIN_PATH, PLUGIN_VST2, splitter.join(VST2_PATH))
  2248. host.set_engine_option(ENGINE_OPTION_PLUGIN_PATH, PLUGIN_VST3, splitter.join(VST3_PATH))
  2249. host.set_engine_option(ENGINE_OPTION_PLUGIN_PATH, PLUGIN_SF2, splitter.join(SF2_PATH))
  2250. host.set_engine_option(ENGINE_OPTION_PLUGIN_PATH, PLUGIN_SFZ, splitter.join(SFZ_PATH))
  2251. # --------------------------------------------------------------------------------------------------------
  2252. # don't continue if plugin
  2253. if host.isPlugin:
  2254. return "Plugin"
  2255. # --------------------------------------------------------------------------------------------------------
  2256. # wine settings
  2257. optWineExecutable = settings.value(CARLA_KEY_WINE_EXECUTABLE, CARLA_DEFAULT_WINE_EXECUTABLE, type=str)
  2258. optWineAutoPrefix = settings.value(CARLA_KEY_WINE_AUTO_PREFIX, CARLA_DEFAULT_WINE_AUTO_PREFIX, type=bool)
  2259. optWineFallbackPrefix = settings.value(CARLA_KEY_WINE_FALLBACK_PREFIX, CARLA_DEFAULT_WINE_FALLBACK_PREFIX, type=str)
  2260. optWineRtPrioEnabled = settings.value(CARLA_KEY_WINE_RT_PRIO_ENABLED, CARLA_DEFAULT_WINE_RT_PRIO_ENABLED, type=bool)
  2261. optWineBaseRtPrio = settings.value(CARLA_KEY_WINE_BASE_RT_PRIO, CARLA_DEFAULT_WINE_BASE_RT_PRIO, type=int)
  2262. optWineServerRtPrio = settings.value(CARLA_KEY_WINE_SERVER_RT_PRIO, CARLA_DEFAULT_WINE_SERVER_RT_PRIO, type=int)
  2263. host.set_engine_option(ENGINE_OPTION_WINE_EXECUTABLE, 0, optWineExecutable)
  2264. host.set_engine_option(ENGINE_OPTION_WINE_AUTO_PREFIX, 1 if optWineAutoPrefix else 0, "")
  2265. host.set_engine_option(ENGINE_OPTION_WINE_FALLBACK_PREFIX, 0, os.path.expanduser(optWineFallbackPrefix))
  2266. host.set_engine_option(ENGINE_OPTION_WINE_RT_PRIO_ENABLED, 1 if optWineRtPrioEnabled else 0, "")
  2267. host.set_engine_option(ENGINE_OPTION_WINE_BASE_RT_PRIO, optWineBaseRtPrio, "")
  2268. host.set_engine_option(ENGINE_OPTION_WINE_SERVER_RT_PRIO, optWineServerRtPrio, "")
  2269. # --------------------------------------------------------------------------------------------------------
  2270. # driver and device settings
  2271. # driver name
  2272. if host.audioDriverForced is not None:
  2273. audioDriver = host.audioDriverForced
  2274. else:
  2275. try:
  2276. audioDriver = settings.value(CARLA_KEY_ENGINE_AUDIO_DRIVER, CARLA_DEFAULT_AUDIO_DRIVER, type=str)
  2277. except:
  2278. audioDriver = CARLA_DEFAULT_AUDIO_DRIVER
  2279. # driver options
  2280. try:
  2281. audioDevice = settings.value("%s%s/Device" % (CARLA_KEY_ENGINE_DRIVER_PREFIX, audioDriver), "", type=str)
  2282. except:
  2283. audioDevice = ""
  2284. try:
  2285. audioBufferSize = settings.value("%s%s/BufferSize" % (CARLA_KEY_ENGINE_DRIVER_PREFIX, audioDriver), CARLA_DEFAULT_AUDIO_BUFFER_SIZE, type=int)
  2286. except:
  2287. audioBufferSize = CARLA_DEFAULT_AUDIO_BUFFER_SIZE
  2288. try:
  2289. audioSampleRate = settings.value("%s%s/SampleRate" % (CARLA_KEY_ENGINE_DRIVER_PREFIX, audioDriver), CARLA_DEFAULT_AUDIO_SAMPLE_RATE, type=int)
  2290. except:
  2291. audioSampleRate = CARLA_DEFAULT_AUDIO_SAMPLE_RATE
  2292. try:
  2293. audioTripleBuffer = settings.value("%s%s/TripleBuffer" % (CARLA_KEY_ENGINE_DRIVER_PREFIX, audioDriver), CARLA_DEFAULT_AUDIO_TRIPLE_BUFFER, type=int)
  2294. except:
  2295. audioTripleBuffer = CARLA_DEFAULT_AUDIO_TRIPLE_BUFFER
  2296. # Only setup audio things if engine is not running
  2297. if not host.is_engine_running():
  2298. host.set_engine_option(ENGINE_OPTION_AUDIO_DEVICE, 0, audioDevice)
  2299. if not audioDriver.startswith("JACK"):
  2300. host.set_engine_option(ENGINE_OPTION_AUDIO_BUFFER_SIZE, audioBufferSize, "")
  2301. host.set_engine_option(ENGINE_OPTION_AUDIO_SAMPLE_RATE, audioSampleRate, "")
  2302. host.set_engine_option(ENGINE_OPTION_AUDIO_TRIPLE_BUFFER, audioTripleBuffer, "")
  2303. # --------------------------------------------------------------------------------------------------------
  2304. # fix things if needed
  2305. if audioDriver != "JACK" and host.transportMode == ENGINE_TRANSPORT_MODE_JACK:
  2306. host.transportMode = ENGINE_TRANSPORT_MODE_INTERNAL
  2307. host.set_engine_option(ENGINE_OPTION_TRANSPORT_MODE, ENGINE_TRANSPORT_MODE_INTERNAL, host.transportExtra)
  2308. # --------------------------------------------------------------------------------------------------------
  2309. # return selected driver name
  2310. return audioDriver
  2311. # ------------------------------------------------------------------------------------------------------------
  2312. # Run Carla without showing UI
  2313. def runHostWithoutUI(host):
  2314. # kdevelop likes this :)
  2315. if False: host = CarlaHostNull()
  2316. # --------------------------------------------------------------------------------------------------------
  2317. # Some initial checks
  2318. if not gCarla.nogui:
  2319. return
  2320. projectFile = getInitialProjectFile(QCoreApplication.instance(), True)
  2321. if not projectFile:
  2322. print("Carla no-gui mode can only be used together with a project file.")
  2323. sys.exit(1)
  2324. # --------------------------------------------------------------------------------------------------------
  2325. # Additional imports
  2326. from time import sleep
  2327. # --------------------------------------------------------------------------------------------------------
  2328. # Init engine
  2329. audioDriver = setEngineSettings(host)
  2330. if not host.engine_init(audioDriver, "Carla"):
  2331. print("Engine failed to initialize, possible reasons:\n%s" % host.get_last_error())
  2332. sys.exit(1)
  2333. if not host.load_project(projectFile):
  2334. print("Failed to load selected project file, possible reasons:\n%s" % host.get_last_error())
  2335. host.engine_close()
  2336. sys.exit(1)
  2337. # --------------------------------------------------------------------------------------------------------
  2338. # Idle
  2339. print("Carla ready!")
  2340. while host.is_engine_running() and not gCarla.term:
  2341. host.engine_idle()
  2342. sleep(0.0333) # 30 Hz
  2343. # --------------------------------------------------------------------------------------------------------
  2344. # Stop
  2345. host.engine_close()
  2346. sys.exit(0)
  2347. # ------------------------------------------------------------------------------------------------------------