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.

3450 lines
136KB

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