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.

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