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.

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