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.

3603 lines
144KB

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