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.

2531 lines
97KB

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