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.

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