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.

3493 lines
139KB

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