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.

364 lines
13KB

  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Carla plugin host
  4. # Copyright (C) 2011-2013 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 GPL.txt file
  17. # ------------------------------------------------------------------------------------------------------------
  18. # Imports (Global)
  19. from time import sleep
  20. from PyQt5.QtCore import Qt, QModelIndex, QPointF, QSize
  21. from PyQt5.QtGui import QImage, QPalette, QResizeEvent, QSyntaxHighlighter
  22. from PyQt5.QtPrintSupport import QPrinter, QPrintDialog
  23. from PyQt5.QtWidgets import QApplication, QDialogButtonBox, QFileSystemModel, QLabel, QMainWindow
  24. # ------------------------------------------------------------------------------------------------------------
  25. # Imports (Custom Stuff)
  26. import ui_carla
  27. from carla_shared import *
  28. # ------------------------------------------------------------------------------------------------------------
  29. # Global Variables
  30. libPrefix = None
  31. projectFilename = None
  32. # ------------------------------------------------------------------------------------------------------------
  33. # Log Syntax Highlighter
  34. class LogSyntaxHighlighter(QSyntaxHighlighter):
  35. def __init__(self, parent):
  36. QSyntaxHighlighter.__init__(self, parent)
  37. palette = parent.palette()
  38. self.fColorDebug = palette.color(QPalette.Disabled, QPalette.WindowText)
  39. self.fColorError = Qt.red
  40. # -------------------------------------------------------------
  41. def highlightBlock(self, text):
  42. if text.startswith("DEBUG:"):
  43. self.setFormat(0, len(text), self.fColorDebug)
  44. elif text.startswith("ERROR:"):
  45. self.setFormat(0, len(text), self.fColorError)
  46. # ------------------------------------------------------------------------------------------------------------
  47. # Main Window
  48. class CarlaMainW(QMainWindow):
  49. def __init__(self, parent=None):
  50. QMainWindow.__init__(self, parent)
  51. self.ui = ui_carla.Ui_CarlaMainW()
  52. self.ui.setupUi(self)
  53. # -------------------------------------------------------------
  54. # Internal stuff
  55. self.fFirstEngineInit = True
  56. # -------------------------------------------------------------
  57. # Set-up GUI stuff
  58. self.fInfoLabel = QLabel(self)
  59. self.fInfoLabel.setText("")
  60. self.fInfoText = ""
  61. self.fDirModel = QFileSystemModel(self)
  62. self.fDirModel.setNameFilters(cString(Carla.host.get_supported_file_types()).split(";"))
  63. self.fDirModel.setRootPath(HOME)
  64. if not WINDOWS:
  65. self.fSyntaxLog = LogSyntaxHighlighter(self.ui.pte_log)
  66. self.fSyntaxLog.setDocument(self.ui.pte_log.document())
  67. if LADISH_APP_NAME:
  68. self.ui.miniCanvasPreview.setVisible(False)
  69. self.ui.tabMain.removeTab(1)
  70. else:
  71. self.ui.tabMain.removeTab(2)
  72. self.ui.fileTreeView.setModel(self.fDirModel)
  73. self.ui.fileTreeView.setRootIndex(self.fDirModel.index(HOME))
  74. self.ui.fileTreeView.setColumnHidden(1, True)
  75. self.ui.fileTreeView.setColumnHidden(2, True)
  76. self.ui.fileTreeView.setColumnHidden(3, True)
  77. self.ui.fileTreeView.setHeaderHidden(True)
  78. self.ui.act_engine_start.setEnabled(False)
  79. self.ui.act_engine_stop.setEnabled(False)
  80. self.ui.act_plugin_remove_all.setEnabled(False)
  81. # FIXME: Qt4 needs this so it properly creates & resizes the canvas
  82. self.ui.tabMain.setCurrentIndex(1)
  83. self.ui.tabMain.setCurrentIndex(0)
  84. # -------------------------------------------------------------
  85. # Set-up Canvas Preview
  86. self.ui.miniCanvasPreview.setRealParent(self)
  87. self.ui.miniCanvasPreview.setViewTheme(patchcanvas.canvas.theme.canvas_bg, patchcanvas.canvas.theme.rubberband_brush, patchcanvas.canvas.theme.rubberband_pen.color())
  88. self.ui.miniCanvasPreview.init(self.scene, DEFAULT_CANVAS_WIDTH, DEFAULT_CANVAS_HEIGHT, self.fSavedSettings["UseCustomMiniCanvasPaint"])
  89. QTimer.singleShot(100, self, SLOT("slot_miniCanvasInit()"))
  90. def updateInfoLabelPos(self):
  91. tabBar = self.ui.tabMain.tabBar()
  92. y = tabBar.mapFromParent(self.ui.centralwidget.pos()).y()+tabBar.height()/4
  93. if not self.ui.toolBar.isVisible():
  94. y -= self.ui.toolBar.height()
  95. self.fInfoLabel.move(self.fInfoLabel.x(), y)
  96. def updateInfoLabelSize(self):
  97. tabBar = self.ui.tabMain.tabBar()
  98. self.fInfoLabel.resize(self.ui.tabMain.width()-tabBar.width()-20, self.fInfoLabel.height())
  99. @pyqtSlot()
  100. def slot_fileExportLv2Preset(self):
  101. fileFilter = self.tr("LV2 Preset (*.lv2)")
  102. filenameTry = QFileDialog.getSaveFileName(self, self.tr("Save Carla Project File"), self.fSavedSettings["Main/DefaultProjectFolder"], filter=fileFilter)
  103. if not filenameTry:
  104. return
  105. if not filenameTry.endswith(".lv2"):
  106. filenameTry += ".lv2"
  107. if os.path.exists(filenameTry) and not os.path.isdir(filenameTry):
  108. # TODO - error
  109. return
  110. # Save current project to a tmp file, and read it
  111. tmpFile = os.path.join(TMP, "carla-plugin-export.carxp")
  112. if not Carla.host.save_project(tmpFile):
  113. # TODO - error
  114. return
  115. tmpFileFd = open(tmpFile, "r")
  116. presetContents = tmpFileFd.read()
  117. tmpFileFd.close()
  118. os.remove(tmpFile)
  119. # Create LV2 Preset
  120. os.mkdir(filenameTry)
  121. manifestPath = os.path.join(filenameTry, "manifest.ttl")
  122. manifestFd = open(manifestPath, "w")
  123. manifestFd.write("""# LV2 Preset for the Carla LV2 Plugin
  124. @prefix lv2: <http://lv2plug.in/ns/lv2core#> .
  125. @prefix pset: <http://lv2plug.in/ns/ext/presets#> .
  126. @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
  127. @prefix state: <http://lv2plug.in/ns/ext/state#> .
  128. <file://%s>
  129. a pset:Preset ;
  130. lv2:appliesTo <http://kxstudio.sf.net/carla> ;
  131. rdfs:label "%s" ;
  132. state:state [
  133. <http://kxstudio.sf.net/ns/carla/string>
  134. \"\"\"
  135. %s
  136. \"\"\"
  137. ] .
  138. """ % (manifestPath, os.path.basename(filenameTry), presetContents))
  139. manifestFd.close()
  140. @pyqtSlot()
  141. def slot_toolbarShown(self):
  142. self.updateInfoLabelPos()
  143. @pyqtSlot()
  144. def slot_splitterMoved(self):
  145. self.updateInfoLabelSize()
  146. @pyqtSlot(int)
  147. def slot_diskFolderChanged(self, index):
  148. if index < 0:
  149. return
  150. elif index == 0:
  151. filename = HOME
  152. self.ui.b_disk_remove.setEnabled(False)
  153. else:
  154. filename = self.ui.cb_disk.itemData(index)
  155. self.ui.b_disk_remove.setEnabled(True)
  156. self.fDirModel.setRootPath(filename)
  157. self.ui.fileTreeView.setRootIndex(self.fDirModel.index(filename))
  158. @pyqtSlot()
  159. def slot_diskFolderAdd(self):
  160. newPath = QFileDialog.getExistingDirectory(self, self.tr("New Folder"), "", QFileDialog.ShowDirsOnly)
  161. if newPath:
  162. if newPath[-1] == os.sep:
  163. newPath = newPath[:-1]
  164. self.ui.cb_disk.addItem(os.path.basename(newPath), newPath)
  165. self.ui.cb_disk.setCurrentIndex(self.ui.cb_disk.count()-1)
  166. self.ui.b_disk_remove.setEnabled(True)
  167. @pyqtSlot()
  168. def slot_diskFolderRemove(self):
  169. index = self.ui.cb_disk.currentIndex()
  170. if index <= 0:
  171. return
  172. self.ui.cb_disk.removeItem(index)
  173. if self.ui.cb_disk.currentIndex() == 0:
  174. self.ui.b_disk_remove.setEnabled(False)
  175. @pyqtSlot(QModelIndex)
  176. def slot_fileTreeDoubleClicked(self, modelIndex):
  177. filename = self.fDirModel.filePath(modelIndex)
  178. if not Carla.host.load_filename(filename):
  179. CustomMessageBox(self, QMessageBox.Critical, self.tr("Error"),
  180. self.tr("Failed to load file"),
  181. cString(Carla.host.get_last_error()), QMessageBox.Ok, QMessageBox.Ok)
  182. @pyqtSlot(float, float)
  183. def slot_miniCanvasMoved(self, xp, yp):
  184. self.ui.graphicsView.horizontalScrollBar().setValue(xp * DEFAULT_CANVAS_WIDTH)
  185. self.ui.graphicsView.verticalScrollBar().setValue(yp * DEFAULT_CANVAS_HEIGHT)
  186. @pyqtSlot(int)
  187. def slot_horizontalScrollBarChanged(self, value):
  188. maximum = self.ui.graphicsView.horizontalScrollBar().maximum()
  189. if maximum == 0:
  190. xp = 0
  191. else:
  192. xp = float(value) / maximum
  193. self.ui.miniCanvasPreview.setViewPosX(xp)
  194. @pyqtSlot(int)
  195. def slot_verticalScrollBarChanged(self, value):
  196. maximum = self.ui.graphicsView.verticalScrollBar().maximum()
  197. if maximum == 0:
  198. yp = 0
  199. else:
  200. yp = float(value) / maximum
  201. self.ui.miniCanvasPreview.setViewPosY(yp)
  202. @pyqtSlot(int, int, QPointF)
  203. def slot_canvasItemMoved(self, group_id, split_mode, pos):
  204. self.ui.miniCanvasPreview.update()
  205. @pyqtSlot(float)
  206. def slot_canvasScaleChanged(self, scale):
  207. self.ui.miniCanvasPreview.setViewScale(scale)
  208. @pyqtSlot()
  209. def slot_miniCanvasInit(self):
  210. settings = QSettings()
  211. self.ui.graphicsView.horizontalScrollBar().setValue(settings.value("HorizontalScrollBarValue", DEFAULT_CANVAS_WIDTH / 3, type=int))
  212. self.ui.graphicsView.verticalScrollBar().setValue(settings.value("VerticalScrollBarValue", DEFAULT_CANVAS_HEIGHT * 3 / 8, type=int))
  213. tabBar = self.ui.tabMain.tabBar()
  214. x = tabBar.width()+20
  215. y = tabBar.mapFromParent(self.ui.centralwidget.pos()).y()+tabBar.height()/4
  216. self.fInfoLabel.move(x, y)
  217. self.fInfoLabel.resize(self.ui.tabMain.width()-x, tabBar.height())
  218. @pyqtSlot()
  219. def slot_miniCanvasCheckAll(self):
  220. self.slot_miniCanvasCheckSize()
  221. self.slot_horizontalScrollBarChanged(self.ui.graphicsView.horizontalScrollBar().value())
  222. self.slot_verticalScrollBarChanged(self.ui.graphicsView.verticalScrollBar().value())
  223. @pyqtSlot()
  224. def slot_miniCanvasCheckSize(self):
  225. self.ui.miniCanvasPreview.setViewSize(float(self.ui.graphicsView.width()) / DEFAULT_CANVAS_WIDTH, float(self.ui.graphicsView.height()) / DEFAULT_CANVAS_HEIGHT)
  226. @pyqtSlot(str)
  227. def slot_handleNSM_AnnounceCallback(self, smName):
  228. self.fSessionManagerName = smName
  229. self.ui.act_file_new.setEnabled(False)
  230. self.ui.act_file_open.setEnabled(False)
  231. self.ui.act_file_save_as.setEnabled(False)
  232. self.ui.act_engine_start.setEnabled(True)
  233. self.ui.act_engine_stop.setEnabled(False)
  234. @pyqtSlot(str)
  235. def slot_handleNSM_OpenCallback(self, data):
  236. projectPath, clientId = data.rsplit(":", 1)
  237. self.fClientName = clientId
  238. # restart engine
  239. if self.fEngineStarted:
  240. self.stopEngine()
  241. self.slot_engineStart()
  242. if self.fEngineStarted:
  243. self.loadProject(projectPath)
  244. Carla.host.nsm_reply_open()
  245. @pyqtSlot()
  246. def slot_handleNSM_SaveCallback(self):
  247. self.saveProject(self.fProjectFilename)
  248. Carla.host.nsm_reply_save()
  249. @pyqtSlot(str)
  250. def slot_handleErrorCallback(self, error):
  251. QMessageBox.critical(self, self.tr("Error"), error)
  252. @pyqtSlot()
  253. def slot_handleQuitCallback(self):
  254. CustomMessageBox(self, QMessageBox.Warning, self.tr("Warning"),
  255. self.tr("Engine has been stopped or crashed.\nPlease restart Carla"),
  256. self.tr("You may want to save your session now..."), QMessageBox.Ok, QMessageBox.Ok)
  257. def dragEnterEvent(self, event):
  258. if event.source() == self.ui.fileTreeView:
  259. event.accept()
  260. elif self.ui.tabMain.contentsRect().contains(event.pos()):
  261. event.accept()
  262. else:
  263. QMainWindow.dragEnterEvent(self, event)
  264. def dropEvent(self, event):
  265. event.accept()
  266. urls = event.mimeData().urls()
  267. for url in urls:
  268. filename = url.toLocalFile()
  269. if not Carla.host.load_filename(filename):
  270. CustomMessageBox(self, QMessageBox.Critical, self.tr("Error"),
  271. self.tr("Failed to load file"),
  272. cString(Carla.host.get_last_error()), QMessageBox.Ok, QMessageBox.Ok)
  273. def resizeEvent(self, event):
  274. if self.ui.tabMain.currentIndex() == 0:
  275. # Force update of 2nd tab
  276. width = self.ui.tab_plugins.width()-4
  277. height = self.ui.tab_plugins.height()-4
  278. self.ui.miniCanvasPreview.setViewSize(float(width) / DEFAULT_CANVAS_WIDTH, float(height) / DEFAULT_CANVAS_HEIGHT)
  279. else:
  280. QTimer.singleShot(0, self, SLOT("slot_miniCanvasCheckSize()"))
  281. self.updateInfoLabelSize()
  282. QMainWindow.resizeEvent(self, event)