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.

3582 lines
143KB

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