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.

3528 lines
140KB

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