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.

3465 lines
137KB

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