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.

2998 lines
116KB

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