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.

3347 lines
132KB

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