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.

2734 lines
105KB

  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Carla host code
  4. # Copyright (C) 2011-2016 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 (Config)
  19. from carla_config import *
  20. # ------------------------------------------------------------------------------------------------------------
  21. # Imports (Global)
  22. if config_UseQt5:
  23. from PyQt5.QtCore import qCritical, QFileInfo, QModelIndex, QPointF, QTimer
  24. from PyQt5.QtGui import QImage, QPalette
  25. from PyQt5.QtWidgets import QAction, QApplication, QInputDialog, QFileSystemModel, QListWidgetItem, QMainWindow
  26. else:
  27. from PyQt4.QtCore import qCritical, QFileInfo, QModelIndex, QPointF, QTimer
  28. from PyQt4.QtGui import QImage, QPalette
  29. from PyQt4.QtGui import QAction, QApplication, QInputDialog, QFileSystemModel, QListWidgetItem, QMainWindow
  30. # ------------------------------------------------------------------------------------------------------------
  31. # Imports (Custom)
  32. import patchcanvas
  33. import ui_carla_host
  34. from carla_app import *
  35. from carla_database import *
  36. from carla_settings import *
  37. from carla_utils import *
  38. from carla_widgets import *
  39. from digitalpeakmeter import DigitalPeakMeter
  40. from pixmapkeyboard import PixmapKeyboardHArea
  41. # ------------------------------------------------------------------------------------------------------------
  42. # Try Import OpenGL
  43. try:
  44. if config_UseQt5:
  45. from PyQt5.QtOpenGL import QGLWidget
  46. else:
  47. from PyQt4.QtOpenGL import QGLWidget
  48. hasGL = True
  49. except:
  50. hasGL = False
  51. # ------------------------------------------------------------------------------------------------------------
  52. # Session Management support
  53. CARLA_CLIENT_NAME = os.getenv("CARLA_CLIENT_NAME")
  54. LADISH_APP_NAME = os.getenv("LADISH_APP_NAME")
  55. NSM_URL = os.getenv("NSM_URL")
  56. # ------------------------------------------------------------------------------------------------------------
  57. # Carla Print class
  58. class CarlaPrint:
  59. def __init__(self, err):
  60. self.err = err
  61. def flush(self):
  62. gCarla.utils.fflush(self.err)
  63. def write(self, string):
  64. gCarla.utils.fputs(self.err, string)
  65. # ------------------------------------------------------------------------------------------------------------
  66. # Host Window
  67. class HostWindow(QMainWindow):
  68. #class HostWindow(QMainWindow, PluginEditParentMeta, metaclass=PyQtMetaClass):
  69. # signals
  70. SIGTERM = pyqtSignal()
  71. SIGUSR1 = pyqtSignal()
  72. # --------------------------------------------------------------------------------------------------------
  73. def __init__(self, host, withCanvas, parent=None):
  74. QMainWindow.__init__(self, parent)
  75. self.host = host
  76. self.ui = ui_carla_host.Ui_CarlaHostW()
  77. self.ui.setupUi(self)
  78. gCarla.gui = self
  79. if False:
  80. # kdevelop likes this :)
  81. host = CarlaHostNull()
  82. self.host = host
  83. self._true = c_char_p("true".encode("utf-8"))
  84. self.fParentOrSelf = parent or self
  85. # ----------------------------------------------------------------------------------------------------
  86. # Internal stuff
  87. self.fIdleTimerFast = 0
  88. self.fIdleTimerSlow = 0
  89. self.fLadspaRdfNeedsUpdate = True
  90. self.fLadspaRdfList = []
  91. self.fPluginCount = 0
  92. self.fPluginList = []
  93. self.fProjectFilename = ""
  94. self.fIsProjectLoading = False
  95. self.fCurrentlyRemovingAllPlugins = False
  96. self.fLastTransportBPM = 0.0
  97. self.fLastTransportFrame = 0
  98. self.fLastTransportState = False
  99. self.fSampleRate = 0.0
  100. # run a custom action after engine is properly closed
  101. # 1 for close carla, 2 for load project
  102. self.fCustomStopAction = 0
  103. # first attempt of auto-start engine doesn't show an error
  104. self.fFirstEngineInit = True
  105. # to be filled with key-value pairs of current settings
  106. self.fSavedSettings = {}
  107. if host.isControl:
  108. self.fClientName = "Carla-Control"
  109. self.fSessionManagerName = "Control"
  110. elif host.isPlugin:
  111. self.fClientName = "Carla-Plugin"
  112. self.fSessionManagerName = "Plugin"
  113. elif LADISH_APP_NAME:
  114. self.fClientName = LADISH_APP_NAME
  115. self.fSessionManagerName = "LADISH"
  116. elif NSM_URL and host.nsmOK:
  117. self.fClientName = "Carla.tmp"
  118. self.fSessionManagerName = "Non Session Manager TMP"
  119. else:
  120. self.fClientName = CARLA_CLIENT_NAME or "Carla"
  121. self.fSessionManagerName = ""
  122. # ----------------------------------------------------------------------------------------------------
  123. # Internal stuff (patchbay)
  124. self.fExportImage = QImage()
  125. self.fPeaksCleared = True
  126. self.fExternalPatchbay = False
  127. self.fSelectedPlugins = []
  128. self.fCanvasWidth = 0
  129. self.fCanvasHeight = 0
  130. self.fMiniCanvasUpdateTimeout = 0
  131. self.fWithCanvas = withCanvas
  132. # ----------------------------------------------------------------------------------------------------
  133. # Set up GUI (engine stopped)
  134. if self.host.isPlugin or self.host.isControl:
  135. self.ui.act_file_save.setVisible(False)
  136. self.ui.act_engine_start.setEnabled(False)
  137. self.ui.act_engine_start.setVisible(False)
  138. self.ui.act_engine_stop.setEnabled(False)
  139. self.ui.act_engine_stop.setVisible(False)
  140. self.ui.menu_Engine.setEnabled(False)
  141. self.ui.menu_Engine.setVisible(False)
  142. self.ui.menu_Engine.menuAction().setVisible(False)
  143. self.ui.tabWidget.removeTab(2)
  144. if self.host.isControl:
  145. self.ui.act_file_new.setVisible(False)
  146. self.ui.act_file_open.setVisible(False)
  147. self.ui.act_file_save.setVisible(False)
  148. self.ui.act_file_save_as.setVisible(False)
  149. self.ui.act_plugin_add.setVisible(False)
  150. self.ui.act_plugin_add2.setVisible(False)
  151. self.ui.act_plugin_remove_all.setVisible(False)
  152. self.ui.menu_Plugin.setEnabled(False)
  153. self.ui.menu_Plugin.setVisible(False)
  154. self.ui.menu_Plugin.menuAction().setVisible(False)
  155. else:
  156. self.ui.act_file_save_as.setText(self.tr("Export as..."))
  157. else:
  158. self.ui.act_engine_start.setEnabled(True)
  159. if WINDOWS:
  160. self.ui.tabWidget.removeTab(2)
  161. if not self.host.isControl:
  162. self.ui.act_file_connect.setEnabled(False)
  163. self.ui.act_file_connect.setVisible(False)
  164. self.ui.act_file_refresh.setEnabled(False)
  165. self.ui.act_file_refresh.setVisible(False)
  166. if self.fSessionManagerName and not self.host.isPlugin:
  167. self.ui.act_file_new.setEnabled(False)
  168. self.ui.act_file_open.setEnabled(False)
  169. self.ui.act_file_save.setEnabled(False)
  170. self.ui.act_file_save_as.setEnabled(False)
  171. self.ui.act_engine_stop.setEnabled(False)
  172. self.ui.act_plugin_remove_all.setEnabled(False)
  173. self.ui.act_canvas_show_internal.setChecked(False)
  174. self.ui.act_canvas_show_internal.setVisible(False)
  175. self.ui.act_canvas_show_external.setChecked(False)
  176. self.ui.act_canvas_show_external.setVisible(False)
  177. self.ui.menu_PluginMacros.setEnabled(False)
  178. self.ui.menu_Canvas.setEnabled(False)
  179. self.ui.dockWidgetTitleBar = QWidget(self)
  180. self.ui.dockWidget.setTitleBarWidget(self.ui.dockWidgetTitleBar)
  181. if not withCanvas:
  182. self.ui.act_canvas_show_internal.setVisible(False)
  183. self.ui.act_canvas_show_external.setVisible(False)
  184. self.ui.act_canvas_arrange.setVisible(False)
  185. self.ui.act_canvas_refresh.setVisible(False)
  186. self.ui.act_canvas_save_image.setVisible(False)
  187. self.ui.act_canvas_zoom_100.setVisible(False)
  188. self.ui.act_canvas_zoom_fit.setVisible(False)
  189. self.ui.act_canvas_zoom_in.setVisible(False)
  190. self.ui.act_canvas_zoom_out.setVisible(False)
  191. self.ui.act_settings_show_meters.setVisible(False)
  192. self.ui.act_settings_show_keyboard.setVisible(False)
  193. self.ui.menu_Canvas_Zoom.setEnabled(False)
  194. self.ui.menu_Canvas_Zoom.setVisible(False)
  195. self.ui.menu_Canvas_Zoom.menuAction().setVisible(False)
  196. self.ui.menu_Canvas.setEnabled(False)
  197. self.ui.menu_Canvas.setVisible(False)
  198. self.ui.menu_Canvas.menuAction().setVisible(False)
  199. self.ui.miniCanvasPreview.hide()
  200. self.ui.tabWidget.removeTab(1)
  201. self.ui.tabWidget.tabBar().hide()
  202. if host.isControl:
  203. self.ui.dockWidget.hide()
  204. # ----------------------------------------------------------------------------------------------------
  205. # Set up GUI (disk)
  206. self.fDirModel = QFileSystemModel(self)
  207. self.fDirModel.setRootPath(HOME)
  208. self.fDirModel.setNameFilters(gCarla.utils.get_supported_file_extensions().split(";"))
  209. self.ui.fileTreeView.setModel(self.fDirModel)
  210. self.ui.fileTreeView.setRootIndex(self.fDirModel.index(HOME))
  211. self.ui.fileTreeView.setColumnHidden(1, True)
  212. self.ui.fileTreeView.setColumnHidden(2, True)
  213. self.ui.fileTreeView.setColumnHidden(3, True)
  214. self.ui.fileTreeView.setHeaderHidden(True)
  215. # ----------------------------------------------------------------------------------------------------
  216. # Set up GUI (transport)
  217. fontMetrics = QFontMetrics(self.ui.l_transport_bbt.font())
  218. minValueWidth = fontMetrics.width("000|00|0000")
  219. minLabelWidth = fontMetrics.width(self.ui.label_transport_frame.text())
  220. labelTimeWidth = fontMetrics.width(self.ui.label_transport_time.text())
  221. labelBBTWidth = fontMetrics.width(self.ui.label_transport_bbt.text())
  222. if minLabelWidth < labelTimeWidth:
  223. minLabelWidth = labelTimeWidth
  224. if minLabelWidth < labelBBTWidth:
  225. minLabelWidth = labelBBTWidth
  226. self.ui.label_transport_frame.setMinimumWidth(minLabelWidth + 3)
  227. self.ui.label_transport_time.setMinimumWidth(minLabelWidth + 3)
  228. self.ui.label_transport_bbt.setMinimumWidth(minLabelWidth + 3)
  229. self.ui.l_transport_bbt.setMinimumWidth(minValueWidth + 3)
  230. self.ui.l_transport_frame.setMinimumWidth(minValueWidth + 3)
  231. self.ui.l_transport_time.setMinimumWidth(minValueWidth + 3)
  232. if host.isPlugin:
  233. self.ui.b_transport_play.setEnabled(False)
  234. self.ui.b_transport_stop.setEnabled(False)
  235. self.ui.b_transport_backwards.setEnabled(False)
  236. self.ui.b_transport_forwards.setEnabled(False)
  237. self.ui.cb_transport_link.setEnabled(False)
  238. self.ui.dsb_transport_bpm.setEnabled(False)
  239. self.ui.w_transport.setEnabled(False)
  240. # ----------------------------------------------------------------------------------------------------
  241. # Set up GUI (rack)
  242. self.ui.listWidget.setHost(self.host)
  243. sb = self.ui.listWidget.verticalScrollBar()
  244. self.ui.rackScrollBar.setMinimum(sb.minimum())
  245. self.ui.rackScrollBar.setMaximum(sb.maximum())
  246. self.ui.rackScrollBar.setValue(sb.value())
  247. sb.rangeChanged.connect(self.ui.rackScrollBar.setRange)
  248. sb.valueChanged.connect(self.ui.rackScrollBar.setValue)
  249. self.ui.rackScrollBar.rangeChanged.connect(sb.setRange)
  250. self.ui.rackScrollBar.valueChanged.connect(sb.setValue)
  251. self.ui.rack.setStyleSheet("""
  252. QLabel#pad_left {
  253. background-image: url(:/bitmaps/rack_padding_left.png);
  254. background-repeat: repeat-y;
  255. }
  256. QLabel#pad_right {
  257. background-image: url(:/bitmaps/rack_padding_right.png);
  258. background-repeat: repeat-y;
  259. }
  260. CarlaRackList#CarlaRackList {
  261. background-color: black;
  262. }
  263. """)
  264. # ----------------------------------------------------------------------------------------------------
  265. # Set up GUI (patchbay)
  266. self.ui.peak_in.setChannelCount(2)
  267. self.ui.peak_in.setMeterColor(DigitalPeakMeter.COLOR_BLUE)
  268. self.ui.peak_in.setMeterOrientation(DigitalPeakMeter.VERTICAL)
  269. self.ui.peak_in.setFixedWidth(25)
  270. self.ui.peak_out.setChannelCount(2)
  271. self.ui.peak_out.setMeterColor(DigitalPeakMeter.COLOR_GREEN)
  272. self.ui.peak_out.setMeterOrientation(DigitalPeakMeter.VERTICAL)
  273. self.ui.peak_out.setFixedWidth(25)
  274. self.ui.scrollArea = PixmapKeyboardHArea(self.ui.patchbay)
  275. self.ui.keyboard = self.ui.scrollArea.keyboard
  276. self.ui.patchbay.layout().addWidget(self.ui.scrollArea, 1, 0, 1, 0)
  277. self.ui.scrollArea.setEnabled(False)
  278. self.ui.miniCanvasPreview.setRealParent(self)
  279. # ----------------------------------------------------------------------------------------------------
  280. # Set up GUI (special stuff for Mac OS)
  281. if MACOS:
  282. self.ui.act_file_quit.setMenuRole(QAction.QuitRole)
  283. self.ui.act_settings_configure.setMenuRole(QAction.PreferencesRole)
  284. self.ui.act_help_about.setMenuRole(QAction.AboutRole)
  285. self.ui.act_help_about_juce.setMenuRole(QAction.ApplicationSpecificRole)
  286. self.ui.act_help_about_qt.setMenuRole(QAction.AboutQtRole)
  287. self.ui.menu_Settings.setTitle("Panels")
  288. self.ui.menu_Help.menuAction().setVisible(False)
  289. # ----------------------------------------------------------------------------------------------------
  290. # Load Settings
  291. self.loadSettings(True)
  292. # ----------------------------------------------------------------------------------------------------
  293. # Set-up Canvas
  294. self.scene = patchcanvas.PatchScene(self, self.ui.graphicsView)
  295. self.ui.graphicsView.setScene(self.scene)
  296. self.ui.graphicsView.setRenderHint(QPainter.Antialiasing, bool(self.fSavedSettings[CARLA_KEY_CANVAS_ANTIALIASING] == patchcanvas.ANTIALIASING_FULL))
  297. if self.fSavedSettings[CARLA_KEY_CANVAS_USE_OPENGL] and hasGL:
  298. self.ui.glView = QGLWidget(self)
  299. self.ui.graphicsView.setViewport(self.ui.glView)
  300. self.ui.graphicsView.setRenderHint(QPainter.HighQualityAntialiasing, self.fSavedSettings[CARLA_KEY_CANVAS_HQ_ANTIALIASING])
  301. self.setupCanvas()
  302. # ----------------------------------------------------------------------------------------------------
  303. # Connect actions to functions
  304. self.ui.act_file_new.triggered.connect(self.slot_fileNew)
  305. self.ui.act_file_open.triggered.connect(self.slot_fileOpen)
  306. self.ui.act_file_save.triggered.connect(self.slot_fileSave)
  307. self.ui.act_file_save_as.triggered.connect(self.slot_fileSaveAs)
  308. self.ui.act_engine_start.triggered.connect(self.slot_engineStart)
  309. self.ui.act_engine_stop.triggered.connect(self.slot_engineStop)
  310. self.ui.act_plugin_add.triggered.connect(self.slot_pluginAdd)
  311. self.ui.act_plugin_add2.triggered.connect(self.slot_pluginAdd)
  312. self.ui.act_plugin_remove_all.triggered.connect(self.slot_pluginRemoveAll)
  313. self.ui.act_add_jack.triggered.connect(self.slot_jackAppAdd)
  314. self.ui.act_plugins_enable.triggered.connect(self.slot_pluginsEnable)
  315. self.ui.act_plugins_disable.triggered.connect(self.slot_pluginsDisable)
  316. self.ui.act_plugins_volume100.triggered.connect(self.slot_pluginsVolume100)
  317. self.ui.act_plugins_mute.triggered.connect(self.slot_pluginsMute)
  318. self.ui.act_plugins_wet100.triggered.connect(self.slot_pluginsWet100)
  319. self.ui.act_plugins_bypass.triggered.connect(self.slot_pluginsBypass)
  320. self.ui.act_plugins_center.triggered.connect(self.slot_pluginsCenter)
  321. self.ui.act_plugins_compact.triggered.connect(self.slot_pluginsCompact)
  322. self.ui.act_plugins_expand.triggered.connect(self.slot_pluginsExpand)
  323. self.ui.act_plugins_panic.triggered.connect(self.slot_pluginsDisable)
  324. self.ui.act_canvas_show_internal.triggered.connect(self.slot_canvasShowInternal)
  325. self.ui.act_canvas_show_external.triggered.connect(self.slot_canvasShowExternal)
  326. self.ui.act_canvas_arrange.triggered.connect(self.slot_canvasArrange)
  327. self.ui.act_canvas_refresh.triggered.connect(self.slot_canvasRefresh)
  328. self.ui.act_canvas_zoom_fit.triggered.connect(self.slot_canvasZoomFit)
  329. self.ui.act_canvas_zoom_in.triggered.connect(self.slot_canvasZoomIn)
  330. self.ui.act_canvas_zoom_out.triggered.connect(self.slot_canvasZoomOut)
  331. self.ui.act_canvas_zoom_100.triggered.connect(self.slot_canvasZoomReset)
  332. self.ui.act_canvas_save_image.triggered.connect(self.slot_canvasSaveImage)
  333. self.ui.act_canvas_arrange.setEnabled(False) # TODO, later
  334. self.ui.act_settings_show_toolbar.toggled.connect(self.slot_showToolbar)
  335. self.ui.act_settings_show_meters.toggled.connect(self.slot_showCanvasMeters)
  336. self.ui.act_settings_show_keyboard.toggled.connect(self.slot_showCanvasKeyboard)
  337. self.ui.act_settings_show_side_panel.toggled.connect(self.slot_showSidePanel)
  338. self.ui.act_settings_configure.triggered.connect(self.slot_configureCarla)
  339. self.ui.act_help_about.triggered.connect(self.slot_aboutCarla)
  340. self.ui.act_help_about_juce.triggered.connect(self.slot_aboutJuce)
  341. self.ui.act_help_about_qt.triggered.connect(self.slot_aboutQt)
  342. self.ui.cb_disk.currentIndexChanged.connect(self.slot_diskFolderChanged)
  343. self.ui.b_disk_add.clicked.connect(self.slot_diskFolderAdd)
  344. self.ui.b_disk_remove.clicked.connect(self.slot_diskFolderRemove)
  345. self.ui.fileTreeView.doubleClicked.connect(self.slot_fileTreeDoubleClicked)
  346. self.ui.b_transport_play.clicked.connect(self.slot_transportPlayPause)
  347. self.ui.b_transport_stop.clicked.connect(self.slot_transportStop)
  348. self.ui.b_transport_backwards.clicked.connect(self.slot_transportBackwards)
  349. self.ui.b_transport_forwards.clicked.connect(self.slot_transportForwards)
  350. self.ui.cb_transport_jack.clicked.connect(self.slot_transportJackEnabled)
  351. self.ui.cb_transport_link.clicked.connect(self.slot_transportLinkEnabled)
  352. self.ui.listWidget.customContextMenuRequested.connect(self.showPluginActionsMenu)
  353. self.ui.graphicsView.horizontalScrollBar().valueChanged.connect(self.slot_horizontalScrollBarChanged)
  354. self.ui.graphicsView.verticalScrollBar().valueChanged.connect(self.slot_verticalScrollBarChanged)
  355. self.ui.keyboard.noteOn.connect(self.slot_noteOn)
  356. self.ui.keyboard.noteOff.connect(self.slot_noteOff)
  357. self.ui.miniCanvasPreview.miniCanvasMoved.connect(self.slot_miniCanvasMoved)
  358. self.ui.tabWidget.currentChanged.connect(self.slot_tabChanged)
  359. self.scene.scaleChanged.connect(self.slot_canvasScaleChanged)
  360. self.scene.sceneGroupMoved.connect(self.slot_canvasItemMoved)
  361. self.scene.pluginSelected.connect(self.slot_canvasPluginSelected)
  362. self.SIGUSR1.connect(self.slot_handleSIGUSR1)
  363. self.SIGTERM.connect(self.slot_handleSIGTERM)
  364. host.EngineStartedCallback.connect(self.slot_handleEngineStartedCallback)
  365. host.EngineStoppedCallback.connect(self.slot_handleEngineStoppedCallback)
  366. host.SampleRateChangedCallback.connect(self.slot_handleSampleRateChangedCallback)
  367. host.PluginAddedCallback.connect(self.slot_handlePluginAddedCallback)
  368. host.PluginRemovedCallback.connect(self.slot_handlePluginRemovedCallback)
  369. host.ReloadAllCallback.connect(self.slot_handleReloadAllCallback)
  370. host.NoteOnCallback.connect(self.slot_handleNoteOnCallback)
  371. host.NoteOffCallback.connect(self.slot_handleNoteOffCallback)
  372. host.UpdateCallback.connect(self.slot_handleUpdateCallback)
  373. host.PatchbayClientAddedCallback.connect(self.slot_handlePatchbayClientAddedCallback)
  374. host.PatchbayClientRemovedCallback.connect(self.slot_handlePatchbayClientRemovedCallback)
  375. host.PatchbayClientRenamedCallback.connect(self.slot_handlePatchbayClientRenamedCallback)
  376. host.PatchbayClientDataChangedCallback.connect(self.slot_handlePatchbayClientDataChangedCallback)
  377. host.PatchbayPortAddedCallback.connect(self.slot_handlePatchbayPortAddedCallback)
  378. host.PatchbayPortRemovedCallback.connect(self.slot_handlePatchbayPortRemovedCallback)
  379. host.PatchbayPortRenamedCallback.connect(self.slot_handlePatchbayPortRenamedCallback)
  380. host.PatchbayConnectionAddedCallback.connect(self.slot_handlePatchbayConnectionAddedCallback)
  381. host.PatchbayConnectionRemovedCallback.connect(self.slot_handlePatchbayConnectionRemovedCallback)
  382. host.NSMCallback.connect(self.slot_handleNSMCallback)
  383. host.DebugCallback.connect(self.slot_handleDebugCallback)
  384. host.InfoCallback.connect(self.slot_handleInfoCallback)
  385. host.ErrorCallback.connect(self.slot_handleErrorCallback)
  386. host.QuitCallback.connect(self.slot_handleQuitCallback)
  387. # ----------------------------------------------------------------------------------------------------
  388. # Final setup
  389. self.ui.text_logs.clear()
  390. self.setProperWindowTitle()
  391. # Qt needs this so it properly creates & resizes the canvas
  392. self.ui.tabWidget.blockSignals(True)
  393. self.ui.tabWidget.setCurrentIndex(1)
  394. self.ui.tabWidget.setCurrentIndex(0)
  395. self.ui.tabWidget.blockSignals(False)
  396. # Plugin needs to have timers always running so it receives messages
  397. if self.host.isPlugin:
  398. self.startTimers()
  399. # Start in patchbay tab if using forced patchbay mode
  400. if host.processModeForced and host.processMode == ENGINE_PROCESS_MODE_PATCHBAY and not host.isControl:
  401. self.ui.tabWidget.setCurrentIndex(1)
  402. # Load initial project file if set
  403. if not (self.host.isControl or self.host.isPlugin):
  404. projectFile = getInitialProjectFile(QApplication.instance())
  405. if projectFile:
  406. self.loadProjectLater(projectFile)
  407. # For NSM we wait for the open message
  408. if NSM_URL and host.nsmOK:
  409. host.nsm_ready(-1)
  410. return
  411. QTimer.singleShot(0, self.slot_engineStart)
  412. # --------------------------------------------------------------------------------------------------------
  413. # Setup
  414. def compactPlugin(self, pluginId):
  415. if pluginId > self.fPluginCount:
  416. return
  417. pitem = self.fPluginList[pluginId]
  418. if pitem is None:
  419. return
  420. pitem.recreateWidget(True)
  421. def setLoadRDFsNeeded(self):
  422. self.fLadspaRdfNeedsUpdate = True
  423. def setProperWindowTitle(self):
  424. title = self.fClientName
  425. if self.fProjectFilename and not self.host.nsmOK:
  426. title += " - %s" % os.path.basename(self.fProjectFilename)
  427. if self.fSessionManagerName:
  428. title += " (%s)" % self.fSessionManagerName
  429. self.setWindowTitle(title)
  430. # --------------------------------------------------------------------------------------------------------
  431. # Files
  432. def loadProjectNow(self):
  433. if not self.fProjectFilename:
  434. return qCritical("ERROR: loading project without filename set")
  435. if self.host.nsmOK and not os.path.exists(self.fProjectFilename):
  436. return
  437. self.projectLoadingStarted()
  438. self.fIsProjectLoading = True
  439. self.host.load_project(self.fProjectFilename)
  440. self.fIsProjectLoading = False
  441. self.projectLoadingFinished()
  442. def loadProjectLater(self, filename):
  443. self.fProjectFilename = QFileInfo(filename).absoluteFilePath()
  444. self.setProperWindowTitle()
  445. QTimer.singleShot(1, self.slot_loadProjectNow)
  446. def saveProjectNow(self):
  447. if not self.fProjectFilename:
  448. return qCritical("ERROR: saving project without filename set")
  449. self.host.save_project(self.fProjectFilename)
  450. def projectLoadingStarted(self):
  451. self.ui.rack.setEnabled(False)
  452. self.ui.graphicsView.setEnabled(False)
  453. def projectLoadingFinished(self):
  454. self.ui.rack.setEnabled(True)
  455. self.ui.graphicsView.setEnabled(True)
  456. QTimer.singleShot(1000, self.slot_canvasRefresh)
  457. # --------------------------------------------------------------------------------------------------------
  458. # Files (menu actions)
  459. @pyqtSlot()
  460. def slot_fileNew(self):
  461. self.slot_pluginRemoveAll()
  462. self.fProjectFilename = ""
  463. self.setProperWindowTitle()
  464. @pyqtSlot()
  465. def slot_fileOpen(self):
  466. fileFilter = self.tr("Carla Project File (*.carxp);;Carla Preset File (*.carxs)")
  467. filename = QFileDialog.getOpenFileName(self, self.tr("Open Carla Project File"), self.fSavedSettings[CARLA_KEY_MAIN_PROJECT_FOLDER], filter=fileFilter)
  468. if config_UseQt5:
  469. filename = filename[0]
  470. if not filename:
  471. return
  472. newFile = True
  473. if self.fPluginCount > 0:
  474. ask = QMessageBox.question(self, self.tr("Question"), self.tr("There are some plugins loaded, do you want to remove them now?"),
  475. QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
  476. newFile = (ask == QMessageBox.Yes)
  477. if newFile:
  478. self.slot_pluginRemoveAll()
  479. self.fProjectFilename = filename
  480. self.setProperWindowTitle()
  481. self.loadProjectNow()
  482. else:
  483. filenameOld = self.fProjectFilename
  484. self.fProjectFilename = filename
  485. self.loadProjectNow()
  486. self.fProjectFilename = filenameOld
  487. @pyqtSlot()
  488. def slot_fileSave(self, saveAs=False):
  489. if self.fProjectFilename and not saveAs:
  490. return self.saveProjectNow()
  491. fileFilter = self.tr("Carla Project File (*.carxp)")
  492. filename = QFileDialog.getSaveFileName(self, self.tr("Save Carla Project File"), self.fSavedSettings[CARLA_KEY_MAIN_PROJECT_FOLDER], filter=fileFilter)
  493. if config_UseQt5:
  494. filename = filename[0]
  495. if not filename:
  496. return
  497. if not filename.lower().endswith(".carxp"):
  498. filename += ".carxp"
  499. if self.fProjectFilename != filename:
  500. self.fProjectFilename = filename
  501. self.setProperWindowTitle()
  502. self.saveProjectNow()
  503. @pyqtSlot()
  504. def slot_fileSaveAs(self):
  505. self.slot_fileSave(True)
  506. @pyqtSlot()
  507. def slot_loadProjectNow(self):
  508. self.loadProjectNow()
  509. # --------------------------------------------------------------------------------------------------------
  510. # Engine (menu actions)
  511. @pyqtSlot()
  512. def slot_engineStart(self):
  513. audioDriver = setEngineSettings(self.host)
  514. firstInit = self.fFirstEngineInit
  515. self.fFirstEngineInit = False
  516. self.ui.text_logs.appendPlainText("======= Starting engine =======")
  517. if self.host.engine_init(audioDriver, self.fClientName):
  518. self.ui.text_logs.appendPlainText("======= Engine started ========")
  519. return
  520. elif firstInit:
  521. self.ui.text_logs.appendPlainText("Failed to start engine on first try, ignored")
  522. return
  523. audioError = self.host.get_last_error()
  524. if audioError:
  525. QMessageBox.critical(self, self.tr("Error"), self.tr("Could not connect to Audio backend '%s', possible reasons:\n%s" % (audioDriver, audioError)))
  526. else:
  527. QMessageBox.critical(self, self.tr("Error"), self.tr("Could not connect to Audio backend '%s'" % audioDriver))
  528. @pyqtSlot()
  529. def slot_engineStop(self, forced = False):
  530. self.ui.text_logs.appendPlainText("======= Stopping engine =======")
  531. if self.fPluginCount == 0:
  532. self.engineStopFinal()
  533. return True
  534. if not forced:
  535. 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"
  536. "Do you want to do this now?"),
  537. QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
  538. if ask != QMessageBox.Yes:
  539. return False
  540. return self.slot_engineStopTryAgain()
  541. @pyqtSlot()
  542. def slot_engineStopTryAgain(self):
  543. if self.host.is_engine_running() and not self.host.set_engine_about_to_close():
  544. QTimer.singleShot(0, self.slot_engineStopTryAgain)
  545. return False
  546. self.engineStopFinal()
  547. return True
  548. def engineStopFinal(self):
  549. self.killTimers()
  550. self.removeAllPlugins()
  551. if self.host.is_engine_running():
  552. self.host.remove_all_plugins()
  553. if self.host.engine_close():
  554. self.ui.text_logs.appendPlainText("======= Engine stopped ========")
  555. else:
  556. self.ui.text_logs.appendPlainText("Failed to stop engine, error was:")
  557. self.ui.text_logs.appendPlainText(self.host.get_last_error())
  558. if self.fCustomStopAction == 1:
  559. self.close()
  560. elif self.fCustomStopAction == 2:
  561. self.slot_engineStart()
  562. self.loadProjectNow()
  563. self.host.nsm_ready(2) # open
  564. self.fCustomStopAction = 0
  565. # --------------------------------------------------------------------------------------------------------
  566. # Engine (host callbacks)
  567. @pyqtSlot(int, int, str)
  568. def slot_handleEngineStartedCallback(self, processMode, transportMode, driverName):
  569. self.fSampleRate = self.host.get_sample_rate()
  570. self.ui.menu_PluginMacros.setEnabled(True)
  571. self.ui.menu_Canvas.setEnabled(True)
  572. self.ui.act_canvas_show_internal.blockSignals(True)
  573. self.ui.act_canvas_show_external.blockSignals(True)
  574. if processMode == ENGINE_PROCESS_MODE_PATCHBAY and not (self.host.isControl or self.host.isPlugin):
  575. self.ui.act_canvas_show_internal.setChecked(True)
  576. self.ui.act_canvas_show_internal.setVisible(True)
  577. self.ui.act_canvas_show_external.setChecked(False)
  578. self.ui.act_canvas_show_external.setVisible(True)
  579. else:
  580. self.ui.act_canvas_show_internal.setChecked(False)
  581. self.ui.act_canvas_show_internal.setVisible(False)
  582. self.ui.act_canvas_show_external.setChecked(False)
  583. self.ui.act_canvas_show_external.setVisible(False)
  584. self.ui.act_canvas_show_internal.blockSignals(False)
  585. self.ui.act_canvas_show_external.blockSignals(False)
  586. if not (self.host.isControl or self.host.isPlugin):
  587. canSave = (self.fProjectFilename and os.path.exists(self.fProjectFilename)) or not self.fSessionManagerName
  588. self.ui.act_file_save.setEnabled(canSave)
  589. self.ui.act_engine_start.setEnabled(False)
  590. self.ui.act_engine_stop.setEnabled(True)
  591. self.ui.w_transport.setEnabled(True)
  592. if self.host.isPlugin or not self.fSessionManagerName:
  593. self.ui.act_file_open.setEnabled(True)
  594. self.ui.act_file_save_as.setEnabled(True)
  595. self.refreshTransport(True)
  596. self.ui.cb_transport_jack.setChecked(transportMode == ENGINE_TRANSPORT_MODE_JACK)
  597. self.ui.cb_transport_jack.setEnabled(driverName == "JACK")
  598. self.startTimers()
  599. @pyqtSlot()
  600. def slot_handleEngineStoppedCallback(self):
  601. patchcanvas.clear()
  602. self.killTimers()
  603. # just in case
  604. self.removeAllPlugins()
  605. self.ui.menu_PluginMacros.setEnabled(False)
  606. self.ui.menu_Canvas.setEnabled(False)
  607. if not (self.host.isControl or self.host.isPlugin):
  608. self.ui.act_file_save.setEnabled(False)
  609. self.ui.act_engine_start.setEnabled(True)
  610. self.ui.act_engine_stop.setEnabled(False)
  611. self.ui.w_transport.setEnabled(False)
  612. if self.host.isPlugin or not self.fSessionManagerName:
  613. self.ui.act_file_open.setEnabled(False)
  614. self.ui.act_file_save_as.setEnabled(False)
  615. @pyqtSlot(float)
  616. def slot_handleSampleRateChangedCallback(self, newSampleRate):
  617. self.fSampleRate = newSampleRate
  618. self.refreshTransport(True)
  619. # --------------------------------------------------------------------------------------------------------
  620. # Plugins
  621. def removeAllPlugins(self):
  622. self.ui.act_plugin_remove_all.setEnabled(False)
  623. patchcanvas.handleAllPluginsRemoved()
  624. while self.ui.listWidget.takeItem(0):
  625. pass
  626. self.clearSideStuff()
  627. for pitem in self.fPluginList:
  628. if pitem is None:
  629. continue
  630. pitem.close()
  631. del pitem
  632. self.fPluginCount = 0
  633. self.fPluginList = []
  634. # --------------------------------------------------------------------------------------------------------
  635. # Plugins (menu actions)
  636. def showAddPluginDialog(self):
  637. dialog = PluginDatabaseW(self.fParentOrSelf, self.host)
  638. if not dialog.exec_():
  639. return
  640. if not self.host.is_engine_running():
  641. QMessageBox.warning(self, self.tr("Warning"), self.tr("Cannot add new plugins while engine is stopped"))
  642. return
  643. btype = dialog.fRetPlugin['build']
  644. ptype = dialog.fRetPlugin['type']
  645. filename = dialog.fRetPlugin['filename']
  646. label = dialog.fRetPlugin['label']
  647. uniqueId = dialog.fRetPlugin['uniqueId']
  648. extraPtr = self.getExtraPtr(dialog.fRetPlugin)
  649. return (btype, ptype, filename, label, uniqueId, extraPtr)
  650. def showAddJackAppDialog(self):
  651. dialog = JackApplicationW(self.fParentOrSelf, self.host)
  652. if not dialog.exec_():
  653. return
  654. if not self.host.is_engine_running():
  655. QMessageBox.warning(self, self.tr("Warning"), self.tr("Cannot add new plugins while engine is stopped"))
  656. return
  657. return dialog.getCommandAndFlags()
  658. @pyqtSlot()
  659. def showPluginActionsMenu(self):
  660. menu = QMenu(self)
  661. if config_UseQt5:
  662. menu.addSection("Plugins")
  663. else:
  664. # fake section
  665. act = menu.addAction(" Plugins")
  666. font = act.font()
  667. font.setBold(True)
  668. act.setFont(font)
  669. act.setEnabled(False)
  670. menu.addSeparator()
  671. menu.addAction(self.ui.act_plugin_add)
  672. menu.addAction(self.ui.act_plugin_remove_all)
  673. if config_UseQt5:
  674. menu.addSection("All plugins (macros)")
  675. else:
  676. # fake space
  677. act = menu.addAction(" ")
  678. font = act.font()
  679. font.setBold(True)
  680. font.setPointSize(font.pointSize()/2)
  681. act.setEnabled(False)
  682. # fake section
  683. act = menu.addAction(" All plugins (macros)")
  684. font = act.font()
  685. font.setBold(True)
  686. act.setFont(font)
  687. act.setEnabled(False)
  688. menu.addSeparator()
  689. menu.addAction(self.ui.act_plugins_enable)
  690. menu.addAction(self.ui.act_plugins_disable)
  691. menu.addSeparator()
  692. menu.addAction(self.ui.act_plugins_volume100)
  693. menu.addAction(self.ui.act_plugins_mute)
  694. menu.addSeparator()
  695. menu.addAction(self.ui.act_plugins_wet100)
  696. menu.addAction(self.ui.act_plugins_bypass)
  697. menu.addSeparator()
  698. menu.addAction(self.ui.act_plugins_center)
  699. menu.addSeparator()
  700. menu.addAction(self.ui.act_plugins_compact)
  701. menu.addAction(self.ui.act_plugins_expand)
  702. menu.exec_(QCursor.pos())
  703. @pyqtSlot()
  704. def slot_pluginAdd(self):
  705. data = self.showAddPluginDialog()
  706. if data is None:
  707. return
  708. btype, ptype, filename, label, uniqueId, extraPtr = data
  709. if not self.host.add_plugin(btype, ptype, filename, None, label, uniqueId, extraPtr, 0x0):
  710. CustomMessageBox(self, QMessageBox.Critical, self.tr("Error"), self.tr("Failed to load plugin"), self.host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  711. @pyqtSlot()
  712. def slot_pluginRemoveAll(self):
  713. if self.fPluginCount == 0:
  714. return
  715. # FIXME - this is not working
  716. # removing a plugin causes flicker, the rack-list becomes empty for some time
  717. # this breaks the remove-all animation, so don't bother using it
  718. if False and not self.host.isPlugin:
  719. self.projectLoadingStarted()
  720. app = QApplication.instance()
  721. app.processEvents()
  722. for i in reversed(range(self.fPluginCount)):
  723. self.host.remove_plugin(i)
  724. app.processEvents()
  725. self.projectLoadingFinished()
  726. self.fCurrentlyRemovingAllPlugins = True
  727. ok = self.host.remove_all_plugins()
  728. self.fCurrentlyRemovingAllPlugins = False
  729. if ok:
  730. self.removeAllPlugins()
  731. else:
  732. CustomMessageBox(self, QMessageBox.Warning, self.tr("Error"), self.tr("Operation failed"),
  733. self.host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  734. self.fCurrentlyRemovingAllPlugins = False
  735. @pyqtSlot()
  736. def slot_jackAppAdd(self):
  737. data = self.showAddJackAppDialog()
  738. if data is None:
  739. return
  740. filename, label = data
  741. if not self.host.add_plugin(BINARY_NATIVE, PLUGIN_JACK, filename, None, label, 0, None, 0x0):
  742. CustomMessageBox(self, QMessageBox.Critical, self.tr("Error"), self.tr("Failed to load plugin"),
  743. self.host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  744. # --------------------------------------------------------------------------------------------------------
  745. # Plugins (macros)
  746. @pyqtSlot()
  747. def slot_pluginsEnable(self):
  748. if not self.host.is_engine_running():
  749. return
  750. for pitem in self.fPluginList:
  751. if pitem is None:
  752. break
  753. pitem.getWidget().setActive(True, True, True)
  754. @pyqtSlot()
  755. def slot_pluginsDisable(self):
  756. if not self.host.is_engine_running():
  757. return
  758. for pitem in self.fPluginList:
  759. if pitem is None:
  760. break
  761. pitem.getWidget().setActive(False, True, True)
  762. @pyqtSlot()
  763. def slot_pluginsVolume100(self):
  764. if not self.host.is_engine_running():
  765. return
  766. for pitem in self.fPluginList:
  767. if pitem is None:
  768. break
  769. pitem.getWidget().setInternalParameter(PLUGIN_CAN_VOLUME, 1.0)
  770. @pyqtSlot()
  771. def slot_pluginsMute(self):
  772. if not self.host.is_engine_running():
  773. return
  774. for pitem in self.fPluginList:
  775. if pitem is None:
  776. break
  777. pitem.getWidget().setInternalParameter(PLUGIN_CAN_VOLUME, 0.0)
  778. @pyqtSlot()
  779. def slot_pluginsWet100(self):
  780. if not self.host.is_engine_running():
  781. return
  782. for pitem in self.fPluginList:
  783. if pitem is None:
  784. break
  785. pitem.getWidget().setInternalParameter(PLUGIN_CAN_DRYWET, 1.0)
  786. @pyqtSlot()
  787. def slot_pluginsBypass(self):
  788. if not self.host.is_engine_running():
  789. return
  790. for pitem in self.fPluginList:
  791. if pitem is None:
  792. break
  793. pitem.getWidget().setInternalParameter(PLUGIN_CAN_DRYWET, 0.0)
  794. @pyqtSlot()
  795. def slot_pluginsCenter(self):
  796. if not self.host.is_engine_running():
  797. return
  798. for pitem in self.fPluginList:
  799. if pitem is None:
  800. break
  801. pitem.getWidget().setInternalParameter(PARAMETER_BALANCE_LEFT, -1.0)
  802. pitem.getWidget().setInternalParameter(PARAMETER_BALANCE_RIGHT, 1.0)
  803. pitem.getWidget().setInternalParameter(PARAMETER_PANNING, 0.0)
  804. @pyqtSlot()
  805. def slot_pluginsCompact(self):
  806. for pitem in self.fPluginList:
  807. if pitem is None:
  808. break
  809. pitem.compact()
  810. @pyqtSlot()
  811. def slot_pluginsExpand(self):
  812. for pitem in self.fPluginList:
  813. if pitem is None:
  814. break
  815. pitem.expand()
  816. # --------------------------------------------------------------------------------------------------------
  817. # Plugins (host callbacks)
  818. @pyqtSlot(int, str)
  819. def slot_handlePluginAddedCallback(self, pluginId, pluginName):
  820. pitem = self.ui.listWidget.createItem(pluginId, self.fSavedSettings[CARLA_KEY_MAIN_USE_CUSTOM_SKINS])
  821. self.fPluginList.append(pitem)
  822. self.fPluginCount += 1
  823. self.ui.act_plugin_remove_all.setEnabled(self.fPluginCount > 0)
  824. @pyqtSlot(int)
  825. def slot_handlePluginRemovedCallback(self, pluginId):
  826. patchcanvas.handlePluginRemoved(pluginId)
  827. if pluginId in self.fSelectedPlugins:
  828. self.clearSideStuff()
  829. pitem = self.getPluginItem(pluginId)
  830. self.fPluginCount -= 1
  831. self.fPluginList.pop(pluginId)
  832. self.ui.listWidget.takeItem(pluginId)
  833. if pitem is not None:
  834. pitem.close()
  835. del pitem
  836. # push all plugins 1 slot back
  837. for i in range(pluginId, self.fPluginCount):
  838. pitem = self.fPluginList[i]
  839. pitem.setPluginId(i)
  840. self.ui.act_plugin_remove_all.setEnabled(self.fPluginCount > 0)
  841. # --------------------------------------------------------------------------------------------------------
  842. # Canvas
  843. def clearSideStuff(self):
  844. self.scene.clearSelection()
  845. self.fSelectedPlugins = []
  846. self.ui.keyboard.allNotesOff(False)
  847. self.ui.scrollArea.setEnabled(False)
  848. self.fPeaksCleared = True
  849. self.ui.peak_in.displayMeter(1, 0.0, True)
  850. self.ui.peak_in.displayMeter(2, 0.0, True)
  851. self.ui.peak_out.displayMeter(1, 0.0, True)
  852. self.ui.peak_out.displayMeter(2, 0.0, True)
  853. def setupCanvas(self):
  854. pOptions = patchcanvas.options_t()
  855. pOptions.theme_name = self.fSavedSettings[CARLA_KEY_CANVAS_THEME]
  856. pOptions.auto_hide_groups = self.fSavedSettings[CARLA_KEY_CANVAS_AUTO_HIDE_GROUPS]
  857. pOptions.auto_select_items = self.fSavedSettings[CARLA_KEY_CANVAS_AUTO_SELECT_ITEMS]
  858. pOptions.use_bezier_lines = self.fSavedSettings[CARLA_KEY_CANVAS_USE_BEZIER_LINES]
  859. pOptions.antialiasing = self.fSavedSettings[CARLA_KEY_CANVAS_ANTIALIASING]
  860. if self.fSavedSettings[CARLA_KEY_CANVAS_FANCY_EYE_CANDY]:
  861. pOptions.eyecandy = patchcanvas.EYECANDY_FULL
  862. elif self.fSavedSettings[CARLA_KEY_CANVAS_EYE_CANDY]:
  863. pOptions.eyecandy = patchcanvas.EYECANDY_SMALL
  864. else:
  865. pOptions.eyecandy = patchcanvas.EYECANDY_NONE
  866. pFeatures = patchcanvas.features_t()
  867. pFeatures.group_info = False
  868. pFeatures.group_rename = False
  869. pFeatures.port_info = False
  870. pFeatures.port_rename = False
  871. pFeatures.handle_group_pos = True
  872. patchcanvas.setOptions(pOptions)
  873. patchcanvas.setFeatures(pFeatures)
  874. patchcanvas.init("Carla2", self.scene, canvasCallback, False)
  875. tryCanvasSize = self.fSavedSettings[CARLA_KEY_CANVAS_SIZE].split("x")
  876. if len(tryCanvasSize) == 2 and tryCanvasSize[0].isdigit() and tryCanvasSize[1].isdigit():
  877. self.fCanvasWidth = int(tryCanvasSize[0])
  878. self.fCanvasHeight = int(tryCanvasSize[1])
  879. else:
  880. self.fCanvasWidth = CARLA_DEFAULT_CANVAS_SIZE_WIDTH
  881. self.fCanvasHeight = CARLA_DEFAULT_CANVAS_SIZE_HEIGHT
  882. patchcanvas.setCanvasSize(0, 0, self.fCanvasWidth, self.fCanvasHeight)
  883. patchcanvas.setInitialPos(self.fCanvasWidth / 2, self.fCanvasHeight / 2)
  884. self.ui.graphicsView.setSceneRect(0, 0, self.fCanvasWidth, self.fCanvasHeight)
  885. self.ui.miniCanvasPreview.setViewTheme(patchcanvas.canvas.theme.canvas_bg, patchcanvas.canvas.theme.rubberband_brush, patchcanvas.canvas.theme.rubberband_pen.color())
  886. self.ui.miniCanvasPreview.init(self.scene, self.fCanvasWidth, self.fCanvasHeight, self.fSavedSettings[CARLA_KEY_CUSTOM_PAINTING])
  887. def updateCanvasInitialPos(self):
  888. x = self.ui.graphicsView.horizontalScrollBar().value() + self.width()/4
  889. y = self.ui.graphicsView.verticalScrollBar().value() + self.height()/4
  890. patchcanvas.setInitialPos(x, y)
  891. def updateMiniCanvasLater(self):
  892. QTimer.singleShot(self.fMiniCanvasUpdateTimeout, self.ui.miniCanvasPreview.update)
  893. # --------------------------------------------------------------------------------------------------------
  894. # Canvas (menu actions)
  895. @pyqtSlot()
  896. def slot_canvasShowInternal(self):
  897. self.fExternalPatchbay = False
  898. self.ui.act_canvas_show_internal.blockSignals(True)
  899. self.ui.act_canvas_show_external.blockSignals(True)
  900. self.ui.act_canvas_show_internal.setChecked(True)
  901. self.ui.act_canvas_show_external.setChecked(False)
  902. self.ui.act_canvas_show_internal.blockSignals(False)
  903. self.ui.act_canvas_show_external.blockSignals(False)
  904. self.slot_canvasRefresh()
  905. @pyqtSlot()
  906. def slot_canvasShowExternal(self):
  907. self.fExternalPatchbay = True
  908. self.ui.act_canvas_show_internal.blockSignals(True)
  909. self.ui.act_canvas_show_external.blockSignals(True)
  910. self.ui.act_canvas_show_internal.setChecked(False)
  911. self.ui.act_canvas_show_external.setChecked(True)
  912. self.ui.act_canvas_show_internal.blockSignals(False)
  913. self.ui.act_canvas_show_external.blockSignals(False)
  914. self.slot_canvasRefresh()
  915. @pyqtSlot()
  916. def slot_canvasArrange(self):
  917. patchcanvas.arrange()
  918. @pyqtSlot()
  919. def slot_canvasRefresh(self):
  920. patchcanvas.clear()
  921. if self.host.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK and (self.host.isControl or self.host.isPlugin):
  922. return
  923. if self.host.is_engine_running():
  924. self.host.patchbay_refresh(self.fExternalPatchbay)
  925. self.updateMiniCanvasLater()
  926. @pyqtSlot()
  927. def slot_canvasZoomFit(self):
  928. self.scene.zoom_fit()
  929. @pyqtSlot()
  930. def slot_canvasZoomIn(self):
  931. self.scene.zoom_in()
  932. @pyqtSlot()
  933. def slot_canvasZoomOut(self):
  934. self.scene.zoom_out()
  935. @pyqtSlot()
  936. def slot_canvasZoomReset(self):
  937. self.scene.zoom_reset()
  938. @pyqtSlot()
  939. def slot_canvasSaveImage(self):
  940. newPath = QFileDialog.getSaveFileName(self, self.tr("Save Image"), filter=self.tr("PNG Image (*.png);;JPEG Image (*.jpg)"))
  941. if config_UseQt5:
  942. newPath = newPath[0]
  943. if not newPath:
  944. return
  945. self.scene.clearSelection()
  946. if newPath.lower().endswith((".jpg", ".jpeg")):
  947. imgFormat = "JPG"
  948. elif newPath.lower().endswith((".png",)):
  949. imgFormat = "PNG"
  950. else:
  951. # File-dialog may not auto-add the extension
  952. imgFormat = "PNG"
  953. newPath += ".png"
  954. self.fExportImage = QImage(self.scene.sceneRect().width(), self.scene.sceneRect().height(), QImage.Format_RGB32)
  955. painter = QPainter(self.fExportImage)
  956. painter.save()
  957. painter.setRenderHint(QPainter.Antialiasing) # TODO - set true, cleanup this
  958. painter.setRenderHint(QPainter.TextAntialiasing)
  959. self.scene.render(painter)
  960. self.fExportImage.save(newPath, imgFormat, 100)
  961. painter.restore()
  962. # --------------------------------------------------------------------------------------------------------
  963. # Canvas (canvas callbacks)
  964. @pyqtSlot(int, int, QPointF)
  965. def slot_canvasItemMoved(self, group_id, split_mode, pos):
  966. self.updateMiniCanvasLater()
  967. @pyqtSlot(float)
  968. def slot_canvasScaleChanged(self, scale):
  969. self.ui.miniCanvasPreview.setViewScale(scale)
  970. @pyqtSlot(list)
  971. def slot_canvasPluginSelected(self, pluginList):
  972. self.ui.keyboard.allNotesOff(False)
  973. self.ui.scrollArea.setEnabled(len(pluginList) != 0) # and self.fPluginCount > 0
  974. self.fSelectedPlugins = pluginList
  975. # --------------------------------------------------------------------------------------------------------
  976. # Canvas (host callbacks)
  977. @pyqtSlot(int, int, int, str)
  978. def slot_handlePatchbayClientAddedCallback(self, clientId, clientIcon, pluginId, clientName):
  979. pcSplit = patchcanvas.SPLIT_UNDEF
  980. pcIcon = patchcanvas.ICON_APPLICATION
  981. if clientIcon == PATCHBAY_ICON_PLUGIN:
  982. pcIcon = patchcanvas.ICON_PLUGIN
  983. if clientIcon == PATCHBAY_ICON_HARDWARE:
  984. pcIcon = patchcanvas.ICON_HARDWARE
  985. elif clientIcon == PATCHBAY_ICON_CARLA:
  986. pass
  987. elif clientIcon == PATCHBAY_ICON_DISTRHO:
  988. pcIcon = patchcanvas.ICON_DISTRHO
  989. elif clientIcon == PATCHBAY_ICON_FILE:
  990. pcIcon = patchcanvas.ICON_FILE
  991. patchcanvas.addGroup(clientId, clientName, pcSplit, pcIcon)
  992. self.updateMiniCanvasLater()
  993. if pluginId < 0:
  994. return
  995. if pluginId >= self.fPluginCount:
  996. print("sorry, can't map this plugin to canvas client", pluginId, self.fPluginCount)
  997. return
  998. patchcanvas.setGroupAsPlugin(clientId, pluginId, bool(self.host.get_plugin_info(pluginId)['hints'] & PLUGIN_HAS_CUSTOM_UI))
  999. @pyqtSlot(int)
  1000. def slot_handlePatchbayClientRemovedCallback(self, clientId):
  1001. patchcanvas.removeGroup(clientId)
  1002. self.updateMiniCanvasLater()
  1003. @pyqtSlot(int, str)
  1004. def slot_handlePatchbayClientRenamedCallback(self, clientId, newClientName):
  1005. patchcanvas.renameGroup(clientId, newClientName)
  1006. self.updateMiniCanvasLater()
  1007. @pyqtSlot(int, int, int)
  1008. def slot_handlePatchbayClientDataChangedCallback(self, clientId, clientIcon, pluginId):
  1009. pcIcon = patchcanvas.ICON_APPLICATION
  1010. if clientIcon == PATCHBAY_ICON_PLUGIN:
  1011. pcIcon = patchcanvas.ICON_PLUGIN
  1012. if clientIcon == PATCHBAY_ICON_HARDWARE:
  1013. pcIcon = patchcanvas.ICON_HARDWARE
  1014. elif clientIcon == PATCHBAY_ICON_CARLA:
  1015. pass
  1016. elif clientIcon == PATCHBAY_ICON_DISTRHO:
  1017. pcIcon = patchcanvas.ICON_DISTRHO
  1018. elif clientIcon == PATCHBAY_ICON_FILE:
  1019. pcIcon = patchcanvas.ICON_FILE
  1020. patchcanvas.setGroupIcon(clientId, pcIcon)
  1021. self.updateMiniCanvasLater()
  1022. if pluginId < 0:
  1023. return
  1024. if pluginId >= self.fPluginCount:
  1025. print("sorry, can't map this plugin to canvas client", pluginId, self.fPluginCount)
  1026. return
  1027. patchcanvas.setGroupAsPlugin(clientId, pluginId, bool(self.host.get_plugin_info(pluginId)['hints'] & PLUGIN_HAS_CUSTOM_UI))
  1028. @pyqtSlot(int, int, int, str)
  1029. def slot_handlePatchbayPortAddedCallback(self, clientId, portId, portFlags, portName):
  1030. if portFlags & PATCHBAY_PORT_IS_INPUT:
  1031. portMode = patchcanvas.PORT_MODE_INPUT
  1032. else:
  1033. portMode = patchcanvas.PORT_MODE_OUTPUT
  1034. if portFlags & PATCHBAY_PORT_TYPE_AUDIO:
  1035. portType = patchcanvas.PORT_TYPE_AUDIO_JACK
  1036. isAlternate = False
  1037. elif portFlags & PATCHBAY_PORT_TYPE_CV:
  1038. portType = patchcanvas.PORT_TYPE_AUDIO_JACK
  1039. isAlternate = True
  1040. elif portFlags & PATCHBAY_PORT_TYPE_MIDI:
  1041. portType = patchcanvas.PORT_TYPE_MIDI_JACK
  1042. isAlternate = False
  1043. else:
  1044. portType = patchcanvas.PORT_TYPE_NULL
  1045. isAlternate = False
  1046. patchcanvas.addPort(clientId, portId, portName, portMode, portType, isAlternate)
  1047. self.updateMiniCanvasLater()
  1048. @pyqtSlot(int, int)
  1049. def slot_handlePatchbayPortRemovedCallback(self, groupId, portId):
  1050. patchcanvas.removePort(groupId, portId)
  1051. self.updateMiniCanvasLater()
  1052. @pyqtSlot(int, int, str)
  1053. def slot_handlePatchbayPortRenamedCallback(self, groupId, portId, newPortName):
  1054. patchcanvas.renamePort(groupId, portId, newPortName)
  1055. self.updateMiniCanvasLater()
  1056. @pyqtSlot(int, int, int, int, int)
  1057. def slot_handlePatchbayConnectionAddedCallback(self, connectionId, groupOutId, portOutId, groupInId, portInId):
  1058. patchcanvas.connectPorts(connectionId, groupOutId, portOutId, groupInId, portInId)
  1059. self.updateMiniCanvasLater()
  1060. @pyqtSlot(int, int, int)
  1061. def slot_handlePatchbayConnectionRemovedCallback(self, connectionId, portOutId, portInId):
  1062. patchcanvas.disconnectPorts(connectionId)
  1063. self.updateMiniCanvasLater()
  1064. # --------------------------------------------------------------------------------------------------------
  1065. # Settings
  1066. def saveSettings(self):
  1067. settings = QSettings()
  1068. settings.setValue("Geometry", self.saveGeometry())
  1069. #settings.setValue("SplitterState", self.ui.splitter.saveState())
  1070. settings.setValue("ShowToolbar", self.ui.toolBar.isEnabled())
  1071. settings.setValue("ShowSidePanel", self.ui.dockWidget.isEnabled())
  1072. diskFolders = []
  1073. for i in range(self.ui.cb_disk.count()):
  1074. diskFolders.append(self.ui.cb_disk.itemData(i))
  1075. settings.setValue("DiskFolders", diskFolders)
  1076. settings.setValue("ShowMeters", self.ui.act_settings_show_meters.isChecked())
  1077. settings.setValue("ShowKeyboard", self.ui.act_settings_show_keyboard.isChecked())
  1078. settings.setValue("HorizontalScrollBarValue", self.ui.graphicsView.horizontalScrollBar().value())
  1079. settings.setValue("VerticalScrollBarValue", self.ui.graphicsView.verticalScrollBar().value())
  1080. def loadSettings(self, firstTime):
  1081. settings = QSettings()
  1082. if firstTime:
  1083. self.restoreGeometry(settings.value("Geometry", b""))
  1084. showToolbar = settings.value("ShowToolbar", True, type=bool)
  1085. self.ui.act_settings_show_toolbar.setChecked(showToolbar)
  1086. self.ui.toolBar.setEnabled(showToolbar)
  1087. self.ui.toolBar.setVisible(showToolbar)
  1088. #if settings.contains("SplitterState"):
  1089. #self.ui.splitter.restoreState(settings.value("SplitterState", b""))
  1090. #else:
  1091. #self.ui.splitter.setSizes([210, 99999])
  1092. showSidePanel = settings.value("ShowSidePanel", True, type=bool)
  1093. self.ui.act_settings_show_side_panel.setChecked(showSidePanel)
  1094. self.ui.dockWidget.setEnabled(showSidePanel)
  1095. self.ui.dockWidget.setVisible(showSidePanel)
  1096. diskFolders = toList(settings.value("DiskFolders", [HOME]))
  1097. self.ui.cb_disk.setItemData(0, HOME)
  1098. for i in range(len(diskFolders)):
  1099. if i == 0: continue
  1100. folder = diskFolders[i]
  1101. self.ui.cb_disk.addItem(os.path.basename(folder), folder)
  1102. #if MACOS and not settings.value(CARLA_KEY_MAIN_USE_PRO_THEME, True, type=bool):
  1103. # self.setUnifiedTitleAndToolBarOnMac(True)
  1104. showMeters = settings.value("ShowMeters", False, type=bool)
  1105. self.ui.act_settings_show_meters.setChecked(showMeters)
  1106. self.ui.peak_in.setVisible(showMeters)
  1107. self.ui.peak_out.setVisible(showMeters)
  1108. showKeyboard = settings.value("ShowKeyboard", not(MACOS or WINDOWS), type=bool)
  1109. self.ui.act_settings_show_keyboard.setChecked(showKeyboard)
  1110. self.ui.scrollArea.setVisible(showKeyboard)
  1111. QTimer.singleShot(100, self.slot_restoreCanvasScrollbarValues)
  1112. # TODO - complete this
  1113. self.fSavedSettings = {
  1114. CARLA_KEY_MAIN_PROJECT_FOLDER: settings.value(CARLA_KEY_MAIN_PROJECT_FOLDER, CARLA_DEFAULT_MAIN_PROJECT_FOLDER, type=str),
  1115. CARLA_KEY_MAIN_REFRESH_INTERVAL: settings.value(CARLA_KEY_MAIN_REFRESH_INTERVAL, CARLA_DEFAULT_MAIN_REFRESH_INTERVAL, type=int),
  1116. CARLA_KEY_MAIN_USE_CUSTOM_SKINS: settings.value(CARLA_KEY_MAIN_USE_CUSTOM_SKINS, CARLA_DEFAULT_MAIN_USE_CUSTOM_SKINS, type=bool),
  1117. CARLA_KEY_MAIN_EXPERIMENTAL: settings.value(CARLA_KEY_MAIN_EXPERIMENTAL, CARLA_DEFAULT_MAIN_EXPERIMENTAL, type=bool),
  1118. CARLA_KEY_CANVAS_THEME: settings.value(CARLA_KEY_CANVAS_THEME, CARLA_DEFAULT_CANVAS_THEME, type=str),
  1119. CARLA_KEY_CANVAS_SIZE: settings.value(CARLA_KEY_CANVAS_SIZE, CARLA_DEFAULT_CANVAS_SIZE, type=str),
  1120. CARLA_KEY_CANVAS_AUTO_HIDE_GROUPS: settings.value(CARLA_KEY_CANVAS_AUTO_HIDE_GROUPS, CARLA_DEFAULT_CANVAS_AUTO_HIDE_GROUPS, type=bool),
  1121. CARLA_KEY_CANVAS_AUTO_SELECT_ITEMS: settings.value(CARLA_KEY_CANVAS_AUTO_SELECT_ITEMS, CARLA_DEFAULT_CANVAS_AUTO_SELECT_ITEMS, type=bool),
  1122. CARLA_KEY_CANVAS_USE_BEZIER_LINES: settings.value(CARLA_KEY_CANVAS_USE_BEZIER_LINES, CARLA_DEFAULT_CANVAS_USE_BEZIER_LINES, type=bool),
  1123. CARLA_KEY_CANVAS_EYE_CANDY: settings.value(CARLA_KEY_CANVAS_EYE_CANDY, CARLA_DEFAULT_CANVAS_EYE_CANDY, type=bool),
  1124. CARLA_KEY_CANVAS_FANCY_EYE_CANDY: settings.value(CARLA_KEY_CANVAS_FANCY_EYE_CANDY, CARLA_DEFAULT_CANVAS_FANCY_EYE_CANDY, type=bool),
  1125. CARLA_KEY_CANVAS_USE_OPENGL: settings.value(CARLA_KEY_CANVAS_USE_OPENGL, CARLA_DEFAULT_CANVAS_USE_OPENGL, type=bool),
  1126. CARLA_KEY_CANVAS_ANTIALIASING: settings.value(CARLA_KEY_CANVAS_ANTIALIASING, CARLA_DEFAULT_CANVAS_ANTIALIASING, type=int),
  1127. CARLA_KEY_CANVAS_HQ_ANTIALIASING: settings.value(CARLA_KEY_CANVAS_HQ_ANTIALIASING, CARLA_DEFAULT_CANVAS_HQ_ANTIALIASING, type=bool),
  1128. CARLA_KEY_CUSTOM_PAINTING: (settings.value(CARLA_KEY_MAIN_USE_PRO_THEME, True, type=bool) and
  1129. settings.value(CARLA_KEY_MAIN_PRO_THEME_COLOR, "Black", type=str).lower() == "black"),
  1130. }
  1131. self.ui.act_add_jack.setVisible(settings.value(CARLA_KEY_EXPERIMENTAL_JACK_APPS,
  1132. CARLA_DEFAULT_EXPERIMENTAL_JACK_APPS, type=bool))
  1133. self.fMiniCanvasUpdateTimeout = 1000 if self.fSavedSettings[CARLA_KEY_CANVAS_FANCY_EYE_CANDY] else 0
  1134. setEngineSettings(self.host)
  1135. self.restartTimersIfNeeded()
  1136. # --------------------------------------------------------------------------------------------------------
  1137. # Settings (helpers)
  1138. @pyqtSlot()
  1139. def slot_restoreCanvasScrollbarValues(self):
  1140. settings = QSettings()
  1141. self.ui.graphicsView.horizontalScrollBar().setValue(settings.value("HorizontalScrollBarValue", self.ui.graphicsView.horizontalScrollBar().maximum()/2, type=int))
  1142. self.ui.graphicsView.verticalScrollBar().setValue(settings.value("VerticalScrollBarValue", self.ui.graphicsView.verticalScrollBar().maximum()/2, type=int))
  1143. # --------------------------------------------------------------------------------------------------------
  1144. # Settings (menu actions)
  1145. @pyqtSlot(bool)
  1146. def slot_showSidePanel(self, yesNo):
  1147. self.ui.dockWidget.setEnabled(yesNo)
  1148. self.ui.dockWidget.setVisible(yesNo)
  1149. @pyqtSlot(bool)
  1150. def slot_showToolbar(self, yesNo):
  1151. self.ui.toolBar.setEnabled(yesNo)
  1152. self.ui.toolBar.setVisible(yesNo)
  1153. @pyqtSlot(bool)
  1154. def slot_showCanvasMeters(self, yesNo):
  1155. self.ui.peak_in.setVisible(yesNo)
  1156. self.ui.peak_out.setVisible(yesNo)
  1157. QTimer.singleShot(0, self.slot_miniCanvasCheckAll)
  1158. @pyqtSlot(bool)
  1159. def slot_showCanvasKeyboard(self, yesNo):
  1160. self.ui.scrollArea.setVisible(yesNo)
  1161. QTimer.singleShot(0, self.slot_miniCanvasCheckAll)
  1162. @pyqtSlot()
  1163. def slot_configureCarla(self):
  1164. dialog = CarlaSettingsW(self.fParentOrSelf, self.host, True, hasGL)
  1165. if not dialog.exec_():
  1166. return
  1167. self.loadSettings(False)
  1168. patchcanvas.clear()
  1169. self.setupCanvas()
  1170. self.slot_miniCanvasCheckAll()
  1171. if self.host.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK and self.host.isPlugin:
  1172. pass
  1173. elif self.host.is_engine_running():
  1174. self.host.patchbay_refresh(self.fExternalPatchbay)
  1175. for pitem in self.fPluginList:
  1176. if pitem is None:
  1177. break
  1178. pitem.setUsingSkins(self.fSavedSettings[CARLA_KEY_MAIN_USE_CUSTOM_SKINS])
  1179. pitem.recreateWidget()
  1180. # --------------------------------------------------------------------------------------------------------
  1181. # About (menu actions)
  1182. @pyqtSlot()
  1183. def slot_aboutCarla(self):
  1184. CarlaAboutW(self.fParentOrSelf, self.host).exec_()
  1185. @pyqtSlot()
  1186. def slot_aboutJuce(self):
  1187. JuceAboutW(self.fParentOrSelf).exec_()
  1188. @pyqtSlot()
  1189. def slot_aboutQt(self):
  1190. QApplication.instance().aboutQt()
  1191. # --------------------------------------------------------------------------------------------------------
  1192. # Disk (menu actions)
  1193. @pyqtSlot(int)
  1194. def slot_diskFolderChanged(self, index):
  1195. if index < 0:
  1196. return
  1197. elif index == 0:
  1198. filename = HOME
  1199. self.ui.b_disk_remove.setEnabled(False)
  1200. else:
  1201. filename = self.ui.cb_disk.itemData(index)
  1202. self.ui.b_disk_remove.setEnabled(True)
  1203. self.fDirModel.setRootPath(filename)
  1204. self.ui.fileTreeView.setRootIndex(self.fDirModel.index(filename))
  1205. @pyqtSlot()
  1206. def slot_diskFolderAdd(self):
  1207. newPath = QFileDialog.getExistingDirectory(self, self.tr("New Folder"), "", QFileDialog.ShowDirsOnly)
  1208. if newPath:
  1209. if newPath[-1] == os.sep:
  1210. newPath = newPath[:-1]
  1211. self.ui.cb_disk.addItem(os.path.basename(newPath), newPath)
  1212. self.ui.cb_disk.setCurrentIndex(self.ui.cb_disk.count()-1)
  1213. self.ui.b_disk_remove.setEnabled(True)
  1214. @pyqtSlot()
  1215. def slot_diskFolderRemove(self):
  1216. index = self.ui.cb_disk.currentIndex()
  1217. if index <= 0:
  1218. return
  1219. self.ui.cb_disk.removeItem(index)
  1220. if self.ui.cb_disk.currentIndex() == 0:
  1221. self.ui.b_disk_remove.setEnabled(False)
  1222. @pyqtSlot(QModelIndex)
  1223. def slot_fileTreeDoubleClicked(self, modelIndex):
  1224. filename = self.fDirModel.filePath(modelIndex)
  1225. if not self.host.load_file(filename):
  1226. CustomMessageBox(self, QMessageBox.Critical, self.tr("Error"),
  1227. self.tr("Failed to load file"),
  1228. self.host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  1229. # --------------------------------------------------------------------------------------------------------
  1230. # Transport
  1231. def refreshTransport(self, forced = False):
  1232. if not self.isVisible():
  1233. return
  1234. if self.fSampleRate == 0.0 or not self.host.is_engine_running():
  1235. return
  1236. timeInfo = self.host.get_transport_info()
  1237. playing = timeInfo['playing']
  1238. frame = timeInfo['frame']
  1239. bpm = timeInfo['bpm']
  1240. if playing != self.fLastTransportState or forced:
  1241. if playing:
  1242. icon = getIcon("media-playback-pause")
  1243. self.ui.b_transport_play.setChecked(True)
  1244. self.ui.b_transport_play.setIcon(icon)
  1245. #self.ui.b_transport_play.setText(self.tr("&Pause"))
  1246. else:
  1247. icon = getIcon("media-playback-start")
  1248. self.ui.b_transport_play.setChecked(False)
  1249. self.ui.b_transport_play.setIcon(icon)
  1250. #self.ui.b_play.setText(self.tr("&Play"))
  1251. self.fLastTransportState = playing
  1252. if frame != self.fLastTransportFrame or forced:
  1253. self.fLastTransportFrame = frame
  1254. time = frame / self.fSampleRate
  1255. secs = time % 60
  1256. mins = (time / 60) % 60
  1257. hrs = (time / 3600) % 60
  1258. self.ui.l_transport_time.setText("%02i:%02i:%02i" % (hrs, mins, secs))
  1259. frame1 = frame % 1000
  1260. frame2 = (frame / 1000) % 1000
  1261. frame3 = (frame / 1000000) % 1000
  1262. self.ui.l_transport_frame.setText("%03i'%03i'%03i" % (frame3, frame2, frame1))
  1263. bar = timeInfo['bar']
  1264. beat = timeInfo['beat']
  1265. tick = timeInfo['tick']
  1266. self.ui.l_transport_bbt.setText("%03i|%02i|%04i" % (bar, beat, tick))
  1267. if bpm != self.fLastTransportBPM or forced:
  1268. self.fLastTransportBPM = bpm
  1269. if bpm > 0.0:
  1270. self.ui.dsb_transport_bpm.setValue(bpm)
  1271. self.ui.dsb_transport_bpm.setStyleSheet("")
  1272. else:
  1273. self.ui.dsb_transport_bpm.setStyleSheet("QDoubleSpinBox { color: palette(mid); }")
  1274. # --------------------------------------------------------------------------------------------------------
  1275. # Transport (menu actions)
  1276. @pyqtSlot(bool)
  1277. def slot_transportPlayPause(self, toggled):
  1278. if self.host.isPlugin or not self.host.is_engine_running():
  1279. return
  1280. if toggled:
  1281. self.host.transport_play()
  1282. else:
  1283. self.host.transport_pause()
  1284. self.refreshTransport()
  1285. @pyqtSlot()
  1286. def slot_transportStop(self):
  1287. if self.host.isPlugin or not self.host.is_engine_running():
  1288. return
  1289. self.host.transport_pause()
  1290. self.host.transport_relocate(0)
  1291. self.refreshTransport()
  1292. @pyqtSlot()
  1293. def slot_transportBackwards(self):
  1294. if self.host.isPlugin or not self.host.is_engine_running():
  1295. return
  1296. newFrame = self.host.get_current_transport_frame() - 100000
  1297. if newFrame < 0:
  1298. newFrame = 0
  1299. self.host.transport_relocate(newFrame)
  1300. @pyqtSlot()
  1301. def slot_transportForwards(self):
  1302. if self.fSampleRate == 0.0 or self.host.isPlugin or not self.host.is_engine_running():
  1303. return
  1304. newFrame = self.host.get_current_transport_frame() + int(self.fSampleRate*2.5)
  1305. self.host.transport_relocate(newFrame)
  1306. @pyqtSlot(bool)
  1307. def slot_transportJackEnabled(self, clicked):
  1308. if not self.host.is_engine_running():
  1309. return
  1310. mode = ENGINE_TRANSPORT_MODE_JACK if clicked else ENGINE_TRANSPORT_MODE_INTERNAL
  1311. extra = ":link:" if self.ui.cb_transport_link.isChecked() else ""
  1312. self.host.set_engine_option(ENGINE_OPTION_TRANSPORT_MODE, mode, extra)
  1313. @pyqtSlot(bool)
  1314. def slot_transportLinkEnabled(self, clicked):
  1315. if not self.host.is_engine_running():
  1316. return
  1317. mode = ENGINE_TRANSPORT_MODE_JACK if self.ui.cb_transport_jack.isChecked() else ENGINE_TRANSPORT_MODE_INTERNAL
  1318. extra = ":link:" if clicked else ""
  1319. self.host.set_engine_option(ENGINE_OPTION_TRANSPORT_MODE, mode, extra)
  1320. # --------------------------------------------------------------------------------------------------------
  1321. # Canvas scrollbars
  1322. @pyqtSlot(int)
  1323. def slot_horizontalScrollBarChanged(self, value):
  1324. maximum = self.ui.graphicsView.horizontalScrollBar().maximum()
  1325. if maximum == 0:
  1326. xp = 0
  1327. else:
  1328. xp = float(value) / maximum
  1329. self.ui.miniCanvasPreview.setViewPosX(xp)
  1330. self.updateCanvasInitialPos()
  1331. @pyqtSlot(int)
  1332. def slot_verticalScrollBarChanged(self, value):
  1333. maximum = self.ui.graphicsView.verticalScrollBar().maximum()
  1334. if maximum == 0:
  1335. yp = 0
  1336. else:
  1337. yp = float(value) / maximum
  1338. self.ui.miniCanvasPreview.setViewPosY(yp)
  1339. self.updateCanvasInitialPos()
  1340. # --------------------------------------------------------------------------------------------------------
  1341. # Canvas keyboard
  1342. @pyqtSlot(int)
  1343. def slot_noteOn(self, note):
  1344. for pluginId in self.fSelectedPlugins:
  1345. self.host.send_midi_note(pluginId, 0, note, 100)
  1346. pedit = self.getPluginEditDialog(pluginId)
  1347. pedit.noteOn(0, note, 100)
  1348. @pyqtSlot(int)
  1349. def slot_noteOff(self, note):
  1350. for pluginId in self.fSelectedPlugins:
  1351. self.host.send_midi_note(pluginId, 0, note, 0)
  1352. pedit = self.getPluginEditDialog(pluginId)
  1353. pedit.noteOff(0, note)
  1354. # --------------------------------------------------------------------------------------------------------
  1355. # Canvas keyboard (host callbacks)
  1356. @pyqtSlot(int, int, int, int)
  1357. def slot_handleNoteOnCallback(self, pluginId, channel, note, velocity):
  1358. if pluginId in self.fSelectedPlugins:
  1359. self.ui.keyboard.sendNoteOn(note, False)
  1360. @pyqtSlot(int, int, int)
  1361. def slot_handleNoteOffCallback(self, pluginId, channel, note):
  1362. if pluginId in self.fSelectedPlugins:
  1363. self.ui.keyboard.sendNoteOff(note, False)
  1364. # --------------------------------------------------------------------------------------------------------
  1365. @pyqtSlot(int)
  1366. def slot_handleUpdateCallback(self, pluginId):
  1367. pitem = self.getPluginItem(pluginId)
  1368. if pitem is None:
  1369. return
  1370. wasCompacted = pitem.isCompacted()
  1371. isCompacted = wasCompacted
  1372. for i in range(self.host.get_custom_data_count(pluginId)):
  1373. cdata = self.host.get_custom_data(pluginId, i)
  1374. if cdata['type'] == CUSTOM_DATA_TYPE_PROPERTY and cdata['key'] == "CarlaSkinIsCompacted":
  1375. isCompacted = bool(cdata['value'] == "true")
  1376. break
  1377. else:
  1378. return
  1379. if wasCompacted == isCompacted:
  1380. return
  1381. pitem.recreateWidget(True)
  1382. # --------------------------------------------------------------------------------------------------------
  1383. # MiniCanvas stuff
  1384. @pyqtSlot()
  1385. def slot_miniCanvasCheckAll(self):
  1386. self.slot_miniCanvasCheckSize()
  1387. self.slot_horizontalScrollBarChanged(self.ui.graphicsView.horizontalScrollBar().value())
  1388. self.slot_verticalScrollBarChanged(self.ui.graphicsView.verticalScrollBar().value())
  1389. @pyqtSlot()
  1390. def slot_miniCanvasCheckSize(self):
  1391. if self.fCanvasWidth == 0 or self.fCanvasHeight == 0:
  1392. return
  1393. currentIndex = self.ui.tabWidget.currentIndex()
  1394. if currentIndex == 1:
  1395. width = self.ui.graphicsView.width()
  1396. height = self.ui.graphicsView.height()
  1397. else:
  1398. self.ui.tabWidget.blockSignals(True)
  1399. self.ui.tabWidget.setCurrentIndex(1)
  1400. width = self.ui.graphicsView.width()
  1401. height = self.ui.graphicsView.height()
  1402. self.ui.tabWidget.setCurrentIndex(currentIndex)
  1403. self.ui.tabWidget.blockSignals(False)
  1404. self.ui.miniCanvasPreview.setViewSize(float(width)/self.fCanvasWidth, float(height)/self.fCanvasHeight)
  1405. @pyqtSlot(float, float)
  1406. def slot_miniCanvasMoved(self, xp, yp):
  1407. hsb = self.ui.graphicsView.horizontalScrollBar()
  1408. vsb = self.ui.graphicsView.verticalScrollBar()
  1409. hsb.setValue(xp * hsb.maximum())
  1410. vsb.setValue(yp * vsb.maximum())
  1411. self.updateCanvasInitialPos()
  1412. # --------------------------------------------------------------------------------------------------------
  1413. # Timers
  1414. def startTimers(self):
  1415. if self.fIdleTimerFast == 0:
  1416. self.fIdleTimerFast = self.startTimer(self.fSavedSettings[CARLA_KEY_MAIN_REFRESH_INTERVAL])
  1417. if self.fIdleTimerSlow == 0:
  1418. self.fIdleTimerSlow = self.startTimer(self.fSavedSettings[CARLA_KEY_MAIN_REFRESH_INTERVAL]*4)
  1419. def restartTimersIfNeeded(self):
  1420. if self.fIdleTimerFast != 0:
  1421. self.killTimer(self.fIdleTimerFast)
  1422. self.fIdleTimerFast = self.startTimer(self.fSavedSettings[CARLA_KEY_MAIN_REFRESH_INTERVAL])
  1423. if self.fIdleTimerSlow != 0:
  1424. self.killTimer(self.fIdleTimerSlow)
  1425. self.fIdleTimerSlow = self.startTimer(self.fSavedSettings[CARLA_KEY_MAIN_REFRESH_INTERVAL]*4)
  1426. def killTimers(self):
  1427. if self.fIdleTimerFast != 0:
  1428. self.killTimer(self.fIdleTimerFast)
  1429. self.fIdleTimerFast = 0
  1430. if self.fIdleTimerSlow != 0:
  1431. self.killTimer(self.fIdleTimerSlow)
  1432. self.fIdleTimerSlow = 0
  1433. # --------------------------------------------------------------------------------------------------------
  1434. # Misc
  1435. @pyqtSlot(int)
  1436. def slot_tabChanged(self, index):
  1437. if index != 1:
  1438. return
  1439. self.ui.graphicsView.setFocus()
  1440. @pyqtSlot(int)
  1441. def slot_handleReloadAllCallback(self, pluginId):
  1442. if pluginId >= self.fPluginCount:
  1443. return
  1444. pitem = self.fPluginList[pluginId]
  1445. if pitem is None:
  1446. return
  1447. pitem.recreateWidget()
  1448. # --------------------------------------------------------------------------------------------------------
  1449. @pyqtSlot(int, int, str)
  1450. def slot_handleNSMCallback(self, value1, value2, valueStr):
  1451. # Error
  1452. if value1 == 0:
  1453. pass
  1454. # Reply
  1455. elif value1 == 1:
  1456. self.fFirstEngineInit = False
  1457. self.fSessionManagerName = valueStr
  1458. self.setProperWindowTitle()
  1459. # Open
  1460. elif value1 == 2:
  1461. self.fClientName = os.path.basename(valueStr)
  1462. self.fProjectFilename = QFileInfo(valueStr+".carxp").absoluteFilePath()
  1463. self.setProperWindowTitle()
  1464. self.fCustomStopAction = 2
  1465. self.slot_engineStop(True)
  1466. return
  1467. # Save
  1468. elif value1 == 3:
  1469. self.saveProjectNow()
  1470. # Session is Loaded
  1471. elif value1 == 4:
  1472. pass
  1473. # Show Optional Gui
  1474. elif value1 == 5:
  1475. self.show()
  1476. # Hide Optional Gui
  1477. elif value1 == 6:
  1478. self.hide()
  1479. self.host.nsm_ready(value1)
  1480. # --------------------------------------------------------------------------------------------------------
  1481. def fixLogText(self, text):
  1482. return text.replace("\x1b[30;1m", "").replace("\x1b[31m", "").replace("\x1b[0m", "")
  1483. @pyqtSlot(int, int, int, float, str)
  1484. def slot_handleDebugCallback(self, pluginId, value1, value2, value3, valueStr):
  1485. self.ui.text_logs.appendPlainText(self.fixLogText(valueStr))
  1486. @pyqtSlot(str)
  1487. def slot_handleInfoCallback(self, info):
  1488. QMessageBox.information(self, "Information", info)
  1489. @pyqtSlot(str)
  1490. def slot_handleErrorCallback(self, error):
  1491. QMessageBox.critical(self, "Error", error)
  1492. @pyqtSlot()
  1493. def slot_handleQuitCallback(self):
  1494. pass # TODO
  1495. # --------------------------------------------------------------------------------------------------------
  1496. @pyqtSlot()
  1497. def slot_handleSIGUSR1(self):
  1498. print("Got SIGUSR1 -> Saving project now")
  1499. self.slot_fileSave()
  1500. @pyqtSlot()
  1501. def slot_handleSIGTERM(self):
  1502. print("Got SIGTERM -> Closing now")
  1503. self.fCustomStopAction = 1
  1504. self.slot_engineStop(True)
  1505. # --------------------------------------------------------------------------------------------------------
  1506. # Internal stuff
  1507. def getExtraPtr(self, plugin):
  1508. ptype = plugin['type']
  1509. if ptype == PLUGIN_LADSPA:
  1510. uniqueId = plugin['uniqueId']
  1511. self.maybeLoadRDFs()
  1512. for rdfItem in self.fLadspaRdfList:
  1513. if rdfItem.UniqueID == uniqueId:
  1514. return pointer(rdfItem)
  1515. elif ptype in (PLUGIN_GIG, PLUGIN_SF2):
  1516. if plugin['name'].lower().endswith(" (16 outputs)"):
  1517. return self._true
  1518. return None
  1519. def maybeLoadRDFs(self):
  1520. if not self.fLadspaRdfNeedsUpdate:
  1521. return
  1522. self.fLadspaRdfNeedsUpdate = False
  1523. self.fLadspaRdfList = []
  1524. if not haveLRDF:
  1525. return
  1526. settingsDir = os.path.join(HOME, ".config", "falkTX")
  1527. frLadspaFile = os.path.join(settingsDir, "ladspa_rdf.db")
  1528. if os.path.exists(frLadspaFile):
  1529. frLadspa = open(frLadspaFile, 'r')
  1530. try:
  1531. self.fLadspaRdfList = ladspa_rdf.get_c_ladspa_rdfs(json.load(frLadspa))
  1532. except:
  1533. pass
  1534. frLadspa.close()
  1535. # --------------------------------------------------------------------------------------------------------
  1536. def getPluginItem(self, pluginId):
  1537. if pluginId >= self.fPluginCount:
  1538. return None
  1539. pitem = self.fPluginList[pluginId]
  1540. if pitem is None:
  1541. return None
  1542. #if False:
  1543. #return CarlaRackItem(self, 0, False)
  1544. return pitem
  1545. def getPluginEditDialog(self, pluginId):
  1546. if pluginId >= self.fPluginCount:
  1547. return None
  1548. pitem = self.fPluginList[pluginId]
  1549. if pitem is None:
  1550. return None
  1551. if False:
  1552. return PluginEdit(self, self.host, 0)
  1553. return pitem.getEditDialog()
  1554. def getPluginSlotWidget(self, pluginId):
  1555. if pluginId >= self.fPluginCount:
  1556. return None
  1557. pitem = self.fPluginList[pluginId]
  1558. if pitem is None:
  1559. return None
  1560. #if False:
  1561. #return AbstractPluginSlot()
  1562. return pitem.getWidget()
  1563. # --------------------------------------------------------------------------------------------------------
  1564. def waitForPendingEvents(self):
  1565. pass
  1566. # --------------------------------------------------------------------------------------------------------
  1567. # show/hide event
  1568. def showEvent(self, event):
  1569. self.refreshTransport(True)
  1570. QMainWindow.showEvent(self, event)
  1571. # set our gui as parent for all plugins UIs
  1572. if self.host.manageUIs and not (self.host.isControl or self.host.isPlugin):
  1573. winIdStr = "%x" % int(self.winId())
  1574. self.host.set_engine_option(ENGINE_OPTION_FRONTEND_WIN_ID, 0, winIdStr)
  1575. def hideEvent(self, event):
  1576. # disable parent
  1577. if not (self.host.isControl or self.host.isPlugin):
  1578. self.host.set_engine_option(ENGINE_OPTION_FRONTEND_WIN_ID, 0, "0")
  1579. QMainWindow.hideEvent(self, event)
  1580. # --------------------------------------------------------------------------------------------------------
  1581. # resize event
  1582. def fixCanvasPreviewSize(self):
  1583. self.ui.patchbay.resize(self.ui.rack.size())
  1584. self.slot_miniCanvasCheckSize()
  1585. def resizeEvent(self, event):
  1586. QMainWindow.resizeEvent(self, event)
  1587. if self.ui.tabWidget.currentIndex() != 1:
  1588. size = self.ui.rack.size()
  1589. self.ui.patchbay.resize(size)
  1590. self.slot_miniCanvasCheckSize()
  1591. # --------------------------------------------------------------------------------------------------------
  1592. # timer event
  1593. def idleFast(self):
  1594. self.host.engine_idle()
  1595. self.refreshTransport()
  1596. if self.fPluginCount == 0 or self.fCurrentlyRemovingAllPlugins:
  1597. return
  1598. for pitem in self.fPluginList:
  1599. if pitem is None:
  1600. break
  1601. pitem.getWidget().idleFast()
  1602. for pluginId in self.fSelectedPlugins:
  1603. self.fPeaksCleared = False
  1604. if self.ui.peak_in.isVisible():
  1605. self.ui.peak_in.displayMeter(1, self.host.get_input_peak_value(pluginId, True))
  1606. self.ui.peak_in.displayMeter(2, self.host.get_input_peak_value(pluginId, False))
  1607. if self.ui.peak_out.isVisible():
  1608. self.ui.peak_out.displayMeter(1, self.host.get_output_peak_value(pluginId, True))
  1609. self.ui.peak_out.displayMeter(2, self.host.get_output_peak_value(pluginId, False))
  1610. return
  1611. if self.fPeaksCleared:
  1612. return
  1613. self.fPeaksCleared = True
  1614. self.ui.peak_in.displayMeter(1, 0.0, True)
  1615. self.ui.peak_in.displayMeter(2, 0.0, True)
  1616. self.ui.peak_out.displayMeter(1, 0.0, True)
  1617. self.ui.peak_out.displayMeter(2, 0.0, True)
  1618. def idleSlow(self):
  1619. if self.fPluginCount == 0 or self.fCurrentlyRemovingAllPlugins:
  1620. return
  1621. for pitem in self.fPluginList:
  1622. if pitem is None:
  1623. break
  1624. pitem.getWidget().idleSlow()
  1625. def timerEvent(self, event):
  1626. if event.timerId() == self.fIdleTimerFast:
  1627. self.idleFast()
  1628. elif event.timerId() == self.fIdleTimerSlow:
  1629. self.idleSlow()
  1630. QMainWindow.timerEvent(self, event)
  1631. # --------------------------------------------------------------------------------------------------------
  1632. # paint event
  1633. #def paintEvent(self, event):
  1634. #QMainWindow.paintEvent(self, event)
  1635. #if MACOS or not self.fSavedSettings[CARLA_KEY_CUSTOM_PAINTING]:
  1636. #return
  1637. #painter = QPainter(self)
  1638. #painter.setBrush(QColor(36, 36, 36))
  1639. #painter.setPen(QColor(62, 62, 62))
  1640. #painter.drawRect(1, self.height()/2, self.width()-3, self.height()-self.height()/2-1)
  1641. # --------------------------------------------------------------------------------------------------------
  1642. # close event
  1643. def closeEvent(self, event):
  1644. self.killTimers()
  1645. self.saveSettings()
  1646. if self.host.is_engine_running() and not (self.host.isControl or self.host.isPlugin):
  1647. if not self.slot_engineStop(True):
  1648. self.fCustomStopAction = 1
  1649. event.ignore()
  1650. return
  1651. QMainWindow.closeEvent(self, event)
  1652. # ------------------------------------------------------------------------------------------------
  1653. # Canvas callback
  1654. def canvasCallback(action, value1, value2, valueStr):
  1655. host = gCarla.gui.host
  1656. if action == patchcanvas.ACTION_GROUP_INFO:
  1657. pass
  1658. elif action == patchcanvas.ACTION_GROUP_RENAME:
  1659. pass
  1660. elif action == patchcanvas.ACTION_GROUP_SPLIT:
  1661. groupId = value1
  1662. patchcanvas.splitGroup(groupId)
  1663. gCarla.gui.updateMiniCanvasLater()
  1664. elif action == patchcanvas.ACTION_GROUP_JOIN:
  1665. groupId = value1
  1666. patchcanvas.joinGroup(groupId)
  1667. gCarla.gui.updateMiniCanvasLater()
  1668. elif action == patchcanvas.ACTION_PORT_INFO:
  1669. pass
  1670. elif action == patchcanvas.ACTION_PORT_RENAME:
  1671. pass
  1672. elif action == patchcanvas.ACTION_PORTS_CONNECT:
  1673. gOut, pOut, gIn, pIn = [int(i) for i in valueStr.split(":")]
  1674. if not host.patchbay_connect(gOut, pOut, gIn, pIn):
  1675. print("Connection failed:", host.get_last_error())
  1676. elif action == patchcanvas.ACTION_PORTS_DISCONNECT:
  1677. connectionId = value1
  1678. if not host.patchbay_disconnect(connectionId):
  1679. print("Disconnect failed:", host.get_last_error())
  1680. elif action == patchcanvas.ACTION_PLUGIN_CLONE:
  1681. pluginId = value1
  1682. if not host.clone_plugin(pluginId):
  1683. CustomMessageBox(gCarla.gui, QMessageBox.Warning, gCarla.gui.tr("Error"), gCarla.gui.tr("Operation failed"),
  1684. host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  1685. elif action == patchcanvas.ACTION_PLUGIN_EDIT:
  1686. pluginId = value1
  1687. pwidget = gCarla.gui.getPluginSlotWidget(pluginId)
  1688. if pwidget is not None:
  1689. pwidget.showEditDialog()
  1690. elif action == patchcanvas.ACTION_PLUGIN_RENAME:
  1691. pluginId = value1
  1692. pwidget = gCarla.gui.getPluginSlotWidget(pluginId)
  1693. if pwidget is not None:
  1694. pwidget.showRenameDialog()
  1695. elif action == patchcanvas.ACTION_PLUGIN_REPLACE:
  1696. pluginId = value1
  1697. pwidget = gCarla.gui.getPluginSlotWidget(pluginId)
  1698. if pwidget is not None:
  1699. pwidget.showReplaceDialog()
  1700. elif action == patchcanvas.ACTION_PLUGIN_REMOVE:
  1701. pluginId = value1
  1702. if not host.remove_plugin(pluginId):
  1703. CustomMessageBox(gCarla.gui, QMessageBox.Warning, gCarla.gui.tr("Error"), gCarla.gui.tr("Operation failed"),
  1704. host.get_last_error(), QMessageBox.Ok, QMessageBox.Ok)
  1705. elif action == patchcanvas.ACTION_PLUGIN_SHOW_UI:
  1706. pluginId = value1
  1707. pwidget = gCarla.gui.getPluginSlotWidget(pluginId)
  1708. if pwidget is not None:
  1709. pwidget.showCustomUI()
  1710. elif action == patchcanvas.ACTION_BG_RIGHT_CLICK:
  1711. gCarla.gui.showPluginActionsMenu()
  1712. # ------------------------------------------------------------------------------------------------------------
  1713. # Engine callback
  1714. def engineCallback(host, action, pluginId, value1, value2, value3, valueStr):
  1715. # kdevelop likes this :)
  1716. if False: host = CarlaHostNull()
  1717. if action == ENGINE_CALLBACK_ENGINE_STARTED:
  1718. host.processMode = value1
  1719. host.transportMode = value2
  1720. elif action == ENGINE_CALLBACK_PROCESS_MODE_CHANGED:
  1721. host.processMode = value1
  1722. elif action == ENGINE_CALLBACK_TRANSPORT_MODE_CHANGED:
  1723. host.transportMode = value1
  1724. valueStr = charPtrToString(valueStr)
  1725. if action == ENGINE_CALLBACK_DEBUG:
  1726. host.DebugCallback.emit(pluginId, value1, value2, value3, valueStr)
  1727. elif action == ENGINE_CALLBACK_PLUGIN_ADDED:
  1728. host.PluginAddedCallback.emit(pluginId, valueStr)
  1729. elif action == ENGINE_CALLBACK_PLUGIN_REMOVED:
  1730. host.PluginRemovedCallback.emit(pluginId)
  1731. elif action == ENGINE_CALLBACK_PLUGIN_RENAMED:
  1732. host.PluginRenamedCallback.emit(pluginId, valueStr)
  1733. elif action == ENGINE_CALLBACK_PLUGIN_UNAVAILABLE:
  1734. host.PluginUnavailableCallback.emit(pluginId, valueStr)
  1735. elif action == ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED:
  1736. host.ParameterValueChangedCallback.emit(pluginId, value1, value3)
  1737. elif action == ENGINE_CALLBACK_PARAMETER_DEFAULT_CHANGED:
  1738. host.ParameterDefaultChangedCallback.emit(pluginId, value1, value3)
  1739. elif action == ENGINE_CALLBACK_PARAMETER_MIDI_CC_CHANGED:
  1740. host.ParameterMidiCcChangedCallback.emit(pluginId, value1, value2)
  1741. elif action == ENGINE_CALLBACK_PARAMETER_MIDI_CHANNEL_CHANGED:
  1742. host.ParameterMidiChannelChangedCallback.emit(pluginId, value1, value2)
  1743. elif action == ENGINE_CALLBACK_PROGRAM_CHANGED:
  1744. host.ProgramChangedCallback.emit(pluginId, value1)
  1745. elif action == ENGINE_CALLBACK_MIDI_PROGRAM_CHANGED:
  1746. host.MidiProgramChangedCallback.emit(pluginId, value1)
  1747. elif action == ENGINE_CALLBACK_OPTION_CHANGED:
  1748. host.OptionChangedCallback.emit(pluginId, value1, bool(value2))
  1749. elif action == ENGINE_CALLBACK_UI_STATE_CHANGED:
  1750. host.UiStateChangedCallback.emit(pluginId, value1)
  1751. elif action == ENGINE_CALLBACK_NOTE_ON:
  1752. host.NoteOnCallback.emit(pluginId, value1, value2, round(value3))
  1753. elif action == ENGINE_CALLBACK_NOTE_OFF:
  1754. host.NoteOffCallback.emit(pluginId, value1, value2)
  1755. elif action == ENGINE_CALLBACK_UPDATE:
  1756. host.UpdateCallback.emit(pluginId)
  1757. elif action == ENGINE_CALLBACK_RELOAD_INFO:
  1758. host.ReloadInfoCallback.emit(pluginId)
  1759. elif action == ENGINE_CALLBACK_RELOAD_PARAMETERS:
  1760. host.ReloadParametersCallback.emit(pluginId)
  1761. elif action == ENGINE_CALLBACK_RELOAD_PROGRAMS:
  1762. host.ReloadProgramsCallback.emit(pluginId)
  1763. elif action == ENGINE_CALLBACK_RELOAD_ALL:
  1764. host.ReloadAllCallback.emit(pluginId)
  1765. elif action == ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED:
  1766. host.PatchbayClientAddedCallback.emit(pluginId, value1, value2, valueStr)
  1767. elif action == ENGINE_CALLBACK_PATCHBAY_CLIENT_REMOVED:
  1768. host.PatchbayClientRemovedCallback.emit(pluginId)
  1769. elif action == ENGINE_CALLBACK_PATCHBAY_CLIENT_RENAMED:
  1770. host.PatchbayClientRenamedCallback.emit(pluginId, valueStr)
  1771. elif action == ENGINE_CALLBACK_PATCHBAY_CLIENT_DATA_CHANGED:
  1772. host.PatchbayClientDataChangedCallback.emit(pluginId, value1, value2)
  1773. elif action == ENGINE_CALLBACK_PATCHBAY_PORT_ADDED:
  1774. host.PatchbayPortAddedCallback.emit(pluginId, value1, value2, valueStr)
  1775. elif action == ENGINE_CALLBACK_PATCHBAY_PORT_REMOVED:
  1776. host.PatchbayPortRemovedCallback.emit(pluginId, value1)
  1777. elif action == ENGINE_CALLBACK_PATCHBAY_PORT_RENAMED:
  1778. host.PatchbayPortRenamedCallback.emit(pluginId, value1, valueStr)
  1779. elif action == ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED:
  1780. gOut, pOut, gIn, pIn = [int(i) for i in valueStr.split(":")] # FIXME
  1781. host.PatchbayConnectionAddedCallback.emit(pluginId, gOut, pOut, gIn, pIn)
  1782. elif action == ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED:
  1783. host.PatchbayConnectionRemovedCallback.emit(pluginId, value1, value2)
  1784. elif action == ENGINE_CALLBACK_ENGINE_STARTED:
  1785. host.EngineStartedCallback.emit(value1, value2, valueStr)
  1786. elif action == ENGINE_CALLBACK_ENGINE_STOPPED:
  1787. host.EngineStoppedCallback.emit()
  1788. elif action == ENGINE_CALLBACK_PROCESS_MODE_CHANGED:
  1789. host.ProcessModeChangedCallback.emit(value1)
  1790. elif action == ENGINE_CALLBACK_TRANSPORT_MODE_CHANGED:
  1791. host.TransportModeChangedCallback.emit(value1)
  1792. elif action == ENGINE_CALLBACK_BUFFER_SIZE_CHANGED:
  1793. host.BufferSizeChangedCallback.emit(value1)
  1794. elif action == ENGINE_CALLBACK_SAMPLE_RATE_CHANGED:
  1795. host.SampleRateChangedCallback.emit(value3)
  1796. elif action == ENGINE_CALLBACK_NSM:
  1797. host.NSMCallback.emit(value1, value2, valueStr)
  1798. elif action == ENGINE_CALLBACK_IDLE:
  1799. QApplication.instance().processEvents()
  1800. elif action == ENGINE_CALLBACK_INFO:
  1801. host.InfoCallback.emit(valueStr)
  1802. elif action == ENGINE_CALLBACK_ERROR:
  1803. host.ErrorCallback.emit(valueStr)
  1804. elif action == ENGINE_CALLBACK_QUIT:
  1805. host.QuitCallback.emit()
  1806. # ------------------------------------------------------------------------------------------------------------
  1807. # File callback
  1808. def fileCallback(ptr, action, isDir, title, filter):
  1809. ret = ("", "") if config_UseQt5 else ""
  1810. if action == FILE_CALLBACK_DEBUG:
  1811. pass
  1812. elif action == FILE_CALLBACK_OPEN:
  1813. ret = QFileDialog.getOpenFileName(gCarla.gui, charPtrToString(title), "", charPtrToString(filter) ) #, QFileDialog.ShowDirsOnly if isDir else 0x0)
  1814. elif action == FILE_CALLBACK_SAVE:
  1815. ret = QFileDialog.getSaveFileName(gCarla.gui, charPtrToString(title), "", charPtrToString(filter), QFileDialog.ShowDirsOnly if isDir else 0x0)
  1816. if config_UseQt5:
  1817. ret = ret[0]
  1818. if not ret:
  1819. return None
  1820. # FIXME
  1821. global fileRet
  1822. fileRet = c_char_p(ret.encode("utf-8"))
  1823. retval = cast(byref(fileRet), POINTER(c_uintptr))
  1824. return retval.contents.value
  1825. # ------------------------------------------------------------------------------------------------------------
  1826. # Init host
  1827. def initHost(initName, libPrefix, isControl, isPlugin, failError, HostClass = None):
  1828. pathBinaries, pathResources = getPaths(libPrefix)
  1829. # --------------------------------------------------------------------------------------------------------
  1830. # Check if we should open main lib as local or global
  1831. settings = QSettings("falkTX", "Carla2")
  1832. try:
  1833. loadGlobal = settings.value(CARLA_KEY_EXPERIMENTAL_LOAD_LIB_GLOBAL, CARLA_DEFAULT_EXPERIMENTAL_LOAD_LIB_GLOBAL, type=bool)
  1834. except:
  1835. loadGlobal = CARLA_DEFAULT_EXPERIMENTAL_LOAD_LIB_GLOBAL
  1836. # --------------------------------------------------------------------------------------------------------
  1837. # Fail if binary dir is not found
  1838. if not os.path.exists(pathBinaries):
  1839. if failError:
  1840. QMessageBox.critical(None, "Error", "Failed to find the carla binaries, cannot continue")
  1841. sys.exit(1)
  1842. return
  1843. # --------------------------------------------------------------------------------------------------------
  1844. # Set Carla library name
  1845. libname = "libcarla_%s2.%s" % ("control" if isControl else "standalone", DLL_EXTENSION)
  1846. libname = os.path.join(pathBinaries, libname)
  1847. utilsname = os.path.join(pathBinaries, "libcarla_utils.%s" % (DLL_EXTENSION))
  1848. # --------------------------------------------------------------------------------------------------------
  1849. # Print info
  1850. print("Carla %s started, status:" % VERSION)
  1851. print(" Python version: %s" % sys.version.split(" ",1)[0])
  1852. print(" Qt version: %s" % qVersion())
  1853. print(" PyQt version: %s" % PYQT_VERSION_STR)
  1854. print(" Binary dir: %s" % pathBinaries)
  1855. print(" Resources dir: %s" % pathResources)
  1856. # --------------------------------------------------------------------------------------------------------
  1857. # Init host
  1858. if failError:
  1859. # no try
  1860. host = HostClass() if HostClass is not None else CarlaHostQtDLL(libname, loadGlobal)
  1861. else:
  1862. try:
  1863. host = HostClass() if HostClass is not None else CarlaHostQtDLL(libname, loadGlobal)
  1864. except:
  1865. host = CarlaHostQtNull()
  1866. host.isControl = isControl
  1867. host.isPlugin = isPlugin
  1868. host.set_engine_callback(lambda h,a,p,v1,v2,v3,vs: engineCallback(host,a,p,v1,v2,v3,vs))
  1869. host.set_file_callback(fileCallback)
  1870. # If it's a plugin the paths are already set
  1871. if not isPlugin:
  1872. host.pathBinaries = pathBinaries
  1873. host.pathResources = pathResources
  1874. host.set_engine_option(ENGINE_OPTION_PATH_BINARIES, 0, pathBinaries)
  1875. host.set_engine_option(ENGINE_OPTION_PATH_RESOURCES, 0, pathResources)
  1876. if not isControl:
  1877. host.nsmOK = host.nsm_init(os.getpid(), initName)
  1878. # --------------------------------------------------------------------------------------------------------
  1879. # Init utils
  1880. gCarla.utils = CarlaUtils(utilsname)
  1881. gCarla.utils.set_process_name(os.path.basename(initName))
  1882. try:
  1883. sys.stdout.flush()
  1884. except:
  1885. pass
  1886. sys.stdout = CarlaPrint(False)
  1887. sys.stderr = CarlaPrint(True)
  1888. # --------------------------------------------------------------------------------------------------------
  1889. # Done
  1890. return host
  1891. # ------------------------------------------------------------------------------------------------------------
  1892. # Load host settings
  1893. def loadHostSettings(host):
  1894. # kdevelop likes this :)
  1895. if False: host = CarlaHostNull()
  1896. settings = QSettings("falkTX", "Carla2")
  1897. try:
  1898. host.experimental = settings.value(CARLA_KEY_MAIN_EXPERIMENTAL, CARLA_DEFAULT_MAIN_EXPERIMENTAL, type=bool)
  1899. except:
  1900. host.experimental = CARLA_DEFAULT_MAIN_EXPERIMENTAL
  1901. try:
  1902. host.manageUIs = settings.value(CARLA_KEY_ENGINE_MANAGE_UIS, CARLA_DEFAULT_MANAGE_UIS, type=bool)
  1903. except:
  1904. host.manageUIs = CARLA_DEFAULT_MANAGE_UIS
  1905. try:
  1906. host.maxParameters = settings.value(CARLA_KEY_ENGINE_MAX_PARAMETERS, CARLA_DEFAULT_MAX_PARAMETERS, type=int)
  1907. except:
  1908. host.maxParameters = CARLA_DEFAULT_MAX_PARAMETERS
  1909. try:
  1910. host.forceStereo = settings.value(CARLA_KEY_ENGINE_FORCE_STEREO, CARLA_DEFAULT_FORCE_STEREO, type=bool)
  1911. except:
  1912. host.forceStereo = CARLA_DEFAULT_FORCE_STEREO
  1913. try:
  1914. host.preferPluginBridges = settings.value(CARLA_KEY_ENGINE_PREFER_PLUGIN_BRIDGES, CARLA_DEFAULT_PREFER_PLUGIN_BRIDGES, type=bool)
  1915. except:
  1916. host.preferPluginBridges = CARLA_DEFAULT_PREFER_PLUGIN_BRIDGES
  1917. try:
  1918. host.preferUIBridges = settings.value(CARLA_KEY_ENGINE_PREFER_UI_BRIDGES, CARLA_DEFAULT_PREFER_UI_BRIDGES, type=bool)
  1919. except:
  1920. host.preferUIBridges = CARLA_DEFAULT_PREFER_UI_BRIDGES
  1921. try:
  1922. host.preventBadBehaviour = settings.value(CARLA_KEY_EXPERIMENTAL_PREVENT_BAD_BEHAVIOUR, CARLA_DEFAULT_EXPERIMENTAL_PREVENT_BAD_BEHAVIOUR, type=bool)
  1923. except:
  1924. host.preventBadBehaviour = CARLA_DEFAULT_EXPERIMENTAL_PREVENT_BAD_BEHAVIOUR
  1925. try:
  1926. host.showPluginBridges = settings.value(CARLA_KEY_EXPERIMENTAL_PLUGIN_BRIDGES, CARLA_DEFAULT_EXPERIMENTAL_PLUGIN_BRIDGES, type=bool)
  1927. except:
  1928. host.showPluginBridges = CARLA_DEFAULT_EXPERIMENTAL_PLUGIN_BRIDGES
  1929. try:
  1930. host.showLogs = settings.value(CARLA_KEY_MAIN_SHOW_LOGS, CARLA_DEFAULT_MAIN_SHOW_LOGS, type=bool)
  1931. except:
  1932. host.showLogs = CARLA_DEFAULT_MAIN_SHOW_LOGS
  1933. try:
  1934. host.uiBridgesTimeout = settings.value(CARLA_KEY_ENGINE_UI_BRIDGES_TIMEOUT, CARLA_DEFAULT_UI_BRIDGES_TIMEOUT, type=int)
  1935. except:
  1936. host.uiBridgesTimeout = CARLA_DEFAULT_UI_BRIDGES_TIMEOUT
  1937. try:
  1938. host.uisAlwaysOnTop = settings.value(CARLA_KEY_ENGINE_UIS_ALWAYS_ON_TOP, CARLA_DEFAULT_UIS_ALWAYS_ON_TOP, type=bool)
  1939. except:
  1940. host.uisAlwaysOnTop = CARLA_DEFAULT_UIS_ALWAYS_ON_TOP
  1941. if host.isPlugin:
  1942. return
  1943. # enums
  1944. if host.audioDriverForced is None:
  1945. try:
  1946. host.transportMode = settings.value(CARLA_KEY_ENGINE_TRANSPORT_MODE, CARLA_DEFAULT_TRANSPORT_MODE, type=int)
  1947. except:
  1948. host.transportMode = CARLA_DEFAULT_TRANSPORT_MODE
  1949. if not host.processModeForced:
  1950. try:
  1951. host.processMode = settings.value(CARLA_KEY_ENGINE_PROCESS_MODE, CARLA_DEFAULT_PROCESS_MODE, type=int)
  1952. except:
  1953. host.processMode = CARLA_DEFAULT_PROCESS_MODE
  1954. host.nextProcessMode = host.processMode
  1955. # --------------------------------------------------------------------------------------------------------
  1956. # fix things if needed
  1957. if host.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS and LADISH_APP_NAME:
  1958. print("LADISH detected but using multiple clients (not allowed), forcing single client now")
  1959. host.nextProcessMode = host.processMode = ENGINE_PROCESS_MODE_SINGLE_CLIENT
  1960. # --------------------------------------------------------------------------------------------------------
  1961. # run headless host now if nogui option enabled
  1962. if gCarla.nogui:
  1963. runHostWithoutUI(host)
  1964. # ------------------------------------------------------------------------------------------------------------
  1965. # Set host settings
  1966. def setHostSettings(host):
  1967. # kdevelop likes this :)
  1968. if False: host = CarlaHostNull()
  1969. host.set_engine_option(ENGINE_OPTION_FORCE_STEREO, host.forceStereo, "")
  1970. host.set_engine_option(ENGINE_OPTION_MAX_PARAMETERS, host.maxParameters, "")
  1971. host.set_engine_option(ENGINE_OPTION_PREFER_PLUGIN_BRIDGES, host.preferPluginBridges, "")
  1972. host.set_engine_option(ENGINE_OPTION_PREFER_UI_BRIDGES, host.preferUIBridges, "")
  1973. host.set_engine_option(ENGINE_OPTION_PREVENT_BAD_BEHAVIOUR, host.preventBadBehaviour, "")
  1974. host.set_engine_option(ENGINE_OPTION_DEBUG_CONSOLE_OUTPUT, host.showLogs, "")
  1975. host.set_engine_option(ENGINE_OPTION_UI_BRIDGES_TIMEOUT, host.uiBridgesTimeout, "")
  1976. host.set_engine_option(ENGINE_OPTION_UIS_ALWAYS_ON_TOP, host.uisAlwaysOnTop, "")
  1977. if host.isPlugin:
  1978. return
  1979. host.set_engine_option(ENGINE_OPTION_PROCESS_MODE, host.nextProcessMode, "")
  1980. host.set_engine_option(ENGINE_OPTION_TRANSPORT_MODE, host.transportMode, "")
  1981. # ------------------------------------------------------------------------------------------------------------
  1982. # Set Engine settings according to carla preferences. Returns selected audio driver.
  1983. def setEngineSettings(host):
  1984. # kdevelop likes this :)
  1985. if False: host = CarlaHostNull()
  1986. # --------------------------------------------------------------------------------------------------------
  1987. # do nothing if control
  1988. if host.isControl:
  1989. return "Control"
  1990. # --------------------------------------------------------------------------------------------------------
  1991. settings = QSettings("falkTX", "Carla2")
  1992. # --------------------------------------------------------------------------------------------------------
  1993. # main settings
  1994. setHostSettings(host)
  1995. # --------------------------------------------------------------------------------------------------------
  1996. # plugin paths
  1997. LADSPA_PATH = toList(settings.value(CARLA_KEY_PATHS_LADSPA, CARLA_DEFAULT_LADSPA_PATH))
  1998. DSSI_PATH = toList(settings.value(CARLA_KEY_PATHS_DSSI, CARLA_DEFAULT_DSSI_PATH))
  1999. LV2_PATH = toList(settings.value(CARLA_KEY_PATHS_LV2, CARLA_DEFAULT_LV2_PATH))
  2000. VST2_PATH = toList(settings.value(CARLA_KEY_PATHS_VST2, CARLA_DEFAULT_VST2_PATH))
  2001. VST3_PATH = toList(settings.value(CARLA_KEY_PATHS_VST3, CARLA_DEFAULT_VST3_PATH))
  2002. GIG_PATH = toList(settings.value(CARLA_KEY_PATHS_GIG, CARLA_DEFAULT_GIG_PATH))
  2003. SF2_PATH = toList(settings.value(CARLA_KEY_PATHS_SF2, CARLA_DEFAULT_SF2_PATH))
  2004. SFZ_PATH = toList(settings.value(CARLA_KEY_PATHS_SFZ, CARLA_DEFAULT_SFZ_PATH))
  2005. host.set_engine_option(ENGINE_OPTION_PLUGIN_PATH, PLUGIN_LADSPA, splitter.join(LADSPA_PATH))
  2006. host.set_engine_option(ENGINE_OPTION_PLUGIN_PATH, PLUGIN_DSSI, splitter.join(DSSI_PATH))
  2007. host.set_engine_option(ENGINE_OPTION_PLUGIN_PATH, PLUGIN_LV2, splitter.join(LV2_PATH))
  2008. host.set_engine_option(ENGINE_OPTION_PLUGIN_PATH, PLUGIN_VST2, splitter.join(VST2_PATH))
  2009. host.set_engine_option(ENGINE_OPTION_PLUGIN_PATH, PLUGIN_VST3, splitter.join(VST3_PATH))
  2010. host.set_engine_option(ENGINE_OPTION_PLUGIN_PATH, PLUGIN_GIG, splitter.join(GIG_PATH))
  2011. host.set_engine_option(ENGINE_OPTION_PLUGIN_PATH, PLUGIN_SF2, splitter.join(SF2_PATH))
  2012. host.set_engine_option(ENGINE_OPTION_PLUGIN_PATH, PLUGIN_SFZ, splitter.join(SFZ_PATH))
  2013. # --------------------------------------------------------------------------------------------------------
  2014. # don't continue if plugin
  2015. if host.isPlugin:
  2016. return "Plugin"
  2017. # --------------------------------------------------------------------------------------------------------
  2018. # driver and device settings
  2019. # driver name
  2020. if host.audioDriverForced is not None:
  2021. audioDriver = host.audioDriverForced
  2022. else:
  2023. try:
  2024. audioDriver = settings.value(CARLA_KEY_ENGINE_AUDIO_DRIVER, CARLA_DEFAULT_AUDIO_DRIVER, type=str)
  2025. except:
  2026. audioDriver = CARLA_DEFAULT_AUDIO_DRIVER
  2027. # driver options
  2028. try:
  2029. audioDevice = settings.value("%s%s/Device" % (CARLA_KEY_ENGINE_DRIVER_PREFIX, audioDriver), "", type=str)
  2030. except:
  2031. audioDevice = ""
  2032. try:
  2033. audioNumPeriods = settings.value("%s%s/NumPeriods" % (CARLA_KEY_ENGINE_DRIVER_PREFIX, audioDriver), CARLA_DEFAULT_AUDIO_NUM_PERIODS, type=int)
  2034. except:
  2035. audioNumPeriods = CARLA_DEFAULT_AUDIO_NUM_PERIODS
  2036. try:
  2037. audioBufferSize = settings.value("%s%s/BufferSize" % (CARLA_KEY_ENGINE_DRIVER_PREFIX, audioDriver), CARLA_DEFAULT_AUDIO_BUFFER_SIZE, type=int)
  2038. except:
  2039. audioBufferSize = CARLA_DEFAULT_AUDIO_BUFFER_SIZE
  2040. try:
  2041. audioSampleRate = settings.value("%s%s/SampleRate" % (CARLA_KEY_ENGINE_DRIVER_PREFIX, audioDriver), CARLA_DEFAULT_AUDIO_SAMPLE_RATE, type=int)
  2042. except:
  2043. audioSampleRate = CARLA_DEFAULT_AUDIO_SAMPLE_RATE
  2044. host.set_engine_option(ENGINE_OPTION_AUDIO_DEVICE, 0, audioDevice)
  2045. host.set_engine_option(ENGINE_OPTION_AUDIO_NUM_PERIODS, audioNumPeriods, "")
  2046. host.set_engine_option(ENGINE_OPTION_AUDIO_BUFFER_SIZE, audioBufferSize, "")
  2047. host.set_engine_option(ENGINE_OPTION_AUDIO_SAMPLE_RATE, audioSampleRate, "")
  2048. # --------------------------------------------------------------------------------------------------------
  2049. # fix things if needed
  2050. if audioDriver != "JACK" and host.transportMode == ENGINE_TRANSPORT_MODE_JACK:
  2051. host.transportMode = ENGINE_TRANSPORT_MODE_INTERNAL
  2052. host.set_engine_option(ENGINE_OPTION_TRANSPORT_MODE, ENGINE_TRANSPORT_MODE_INTERNAL, "")
  2053. # --------------------------------------------------------------------------------------------------------
  2054. # return selected driver name
  2055. return audioDriver
  2056. # ------------------------------------------------------------------------------------------------------------
  2057. # Run Carla without showing UI
  2058. def runHostWithoutUI(host):
  2059. # kdevelop likes this :)
  2060. if False: host = CarlaHostNull()
  2061. # --------------------------------------------------------------------------------------------------------
  2062. # Some initial checks
  2063. if not gCarla.nogui:
  2064. return
  2065. projectFile = getInitialProjectFile(QCoreApplication.instance(), True)
  2066. if not projectFile:
  2067. print("Carla no-gui mode can only be used together with a project file.")
  2068. sys.exit(1)
  2069. # --------------------------------------------------------------------------------------------------------
  2070. # Additional imports
  2071. from time import sleep
  2072. # --------------------------------------------------------------------------------------------------------
  2073. # Init engine
  2074. audioDriver = setEngineSettings(host)
  2075. if not host.engine_init(audioDriver, "Carla-nogui"):
  2076. print("Engine failed to initialize, possible reasons:\n%s" % host.get_last_error())
  2077. sys.exit(1)
  2078. if not host.load_project(projectFile):
  2079. print("Failed to load selected project file, possible reasons:\n%s" % host.get_last_error())
  2080. host.engine_close()
  2081. sys.exit(1)
  2082. # --------------------------------------------------------------------------------------------------------
  2083. # Idle
  2084. while host.is_engine_running() and not gCarla.term:
  2085. host.engine_idle()
  2086. sleep(0.5)
  2087. # --------------------------------------------------------------------------------------------------------
  2088. # Stop
  2089. host.engine_close()
  2090. sys.exit(0)
  2091. # ------------------------------------------------------------------------------------------------------------