drag'n'drop componentList, move component code to core.py

FIXME: finish implementing drag'n'drop, Down button
This commit is contained in:
tassaron 2017-06-08 09:56:57 -04:00
parent 292d21c203
commit 6079c4fd24
4 changed files with 121 additions and 90 deletions

32
core.py
View File

@ -12,6 +12,7 @@ import atexit
import time import time
from collections import OrderedDict from collections import OrderedDict
import json import json
from importlib import import_module
class Core(): class Core():
@ -26,6 +27,37 @@ class Core():
self.wd = os.path.dirname(os.path.realpath(__file__)) self.wd = os.path.dirname(os.path.realpath(__file__))
self.loadEncoderOptions() self.loadEncoderOptions()
self.modules = self.findComponents()
self.selectedComponents = []
def findComponents(self):
def findComponents():
srcPath = os.path.join(self.wd, 'components')
if os.path.exists(srcPath):
for f in sorted(os.listdir(srcPath)):
name, ext = os.path.splitext(f)
if name.startswith("__"):
continue
elif ext == '.py':
yield name
return [
import_module('components.%s' % name)
for name in findComponents()]
def insertComponent(self, compPos, moduleIndex):
self.selectedComponents.insert(
compPos,
self.modules[moduleIndex].Component())
return compPos #if compPos > -1 else len(self.selectedComponents)-1
def moveComponent(self, startI, endI):
comp = self.selectedComponents.pop(startI)
i = self.selectedComponents.insert(endI, comp)
return i
def updateComponent(self, i):
self.selectedComponents[i].update()
def loadEncoderOptions(self): def loadEncoderOptions(self):
file_path = os.path.join(self.wd, 'encoder-options.json') file_path = os.path.join(self.wd, 'encoder-options.json')
with open(file_path) as json_file: with open(file_path) as json_file:

View File

@ -1,6 +1,5 @@
from os.path import expanduser from os.path import expanduser
from queue import Queue from queue import Queue
from importlib import import_module
from collections import OrderedDict from collections import OrderedDict
from PyQt4 import QtCore, QtGui, uic from PyQt4 import QtCore, QtGui, uic
from PyQt4.QtCore import QSettings, Qt from PyQt4.QtCore import QSettings, Qt
@ -54,8 +53,9 @@ class MainWindow(QtCore.QObject):
# print('main thread id: {}'.format(QtCore.QThread.currentThreadId())) # print('main thread id: {}'.format(QtCore.QThread.currentThreadId()))
self.window = window self.window = window
self.core = core.Core() self.core = core.Core()
self.pages = []
self.selectedComponents = [] self.pages = [] # widgets of component settings
self.componentRows = {} # QListWidgetItems
self.lastAutosave = time.time() self.lastAutosave = time.time()
# Create data directory, load/create settings # Create data directory, load/create settings
@ -149,16 +149,16 @@ class MainWindow(QtCore.QObject):
window.verticalLayout_previewWrapper.addWidget(self.previewWindow) window.verticalLayout_previewWrapper.addWidget(self.previewWindow)
# Make component buttons # Make component buttons
self.modules = self.findComponents()
self.compMenu = QMenu() self.compMenu = QMenu()
for i, comp in enumerate(self.modules): for i, comp in enumerate(self.core.modules):
action = self.compMenu.addAction(comp.Component.__doc__) action = self.compMenu.addAction(comp.Component.__doc__)
action.triggered[()].connect( action.triggered[()].connect(
lambda item=i: self.insertComponent(item)) lambda item=i: self.insertComponent(item))
self.window.pushButton_addComponent.setMenu(self.compMenu) self.window.pushButton_addComponent.setMenu(self.compMenu)
window.listWidget_componentList.clicked.connect( self.window.listWidget_componentList.dropEvent = self.componentMoved
self.window.listWidget_componentList.clicked.connect(
lambda _: self.changeComponentWidget()) lambda _: self.changeComponentWidget())
self.window.pushButton_removeComponent.clicked.connect( self.window.pushButton_removeComponent.clicked.connect(
@ -183,8 +183,8 @@ class MainWindow(QtCore.QObject):
self.window.pushButton_listMoveUp.clicked.connect( self.window.pushButton_listMoveUp.clicked.connect(
self.moveComponentUp) self.moveComponentUp)
self.window.pushButton_listMoveDown.clicked.connect( #self.window.pushButton_listMoveDown.clicked.connect(
self.moveComponentDown) # self.moveComponentDown)
# Configure the Projects Menu # Configure the Projects Menu
self.projectMenu = QMenu() self.projectMenu = QMenu()
@ -323,7 +323,7 @@ class MainWindow(QtCore.QObject):
self.videoTask.emit( self.videoTask.emit(
self.window.lineEdit_audioFile.text(), self.window.lineEdit_audioFile.text(),
self.window.lineEdit_outputFile.text(), self.window.lineEdit_outputFile.text(),
self.selectedComponents) self.core.selectedComponents)
else: else:
self.showMessage( self.showMessage(
msg="You must select an audio file and output filename.") msg="You must select an audio file and output filename.")
@ -384,56 +384,35 @@ class MainWindow(QtCore.QObject):
self.drawPreview() self.drawPreview()
def drawPreview(self): def drawPreview(self):
self.newTask.emit(self.selectedComponents) self.newTask.emit(self.core.selectedComponents)
# self.processTask.emit() # self.processTask.emit()
self.autosave() self.autosave()
def showPreviewImage(self, image): def showPreviewImage(self, image):
self.previewWindow.changePixmap(image) self.previewWindow.changePixmap(image)
def findComponents(self): def insertComponent(self, moduleIndex, compPos=0):
def findComponents(): componentList = self.window.listWidget_componentList
srcPath = os.path.join(
os.path.dirname(os.path.realpath(__file__)), 'components')
if os.path.exists(srcPath):
for f in sorted(os.listdir(srcPath)):
name, ext = os.path.splitext(f)
if name.startswith("__"):
continue
elif ext == '.py':
yield name
return [
import_module('components.%s' % name)
for name in findComponents()]
def addComponent(self, moduleIndex): index = self.core.insertComponent(
index = len(self.pages) compPos, moduleIndex)
self.selectedComponents.append(self.modules[moduleIndex].Component()) row = componentList.insertItem(
self.window.listWidget_componentList.addItem( index,
self.selectedComponents[-1].__doc__) self.core.selectedComponents[index].__doc__)
self.pages.append(self.selectedComponents[-1].widget(self)) self.componentRows[index] = componentList.row(row)
self.window.listWidget_componentList.setCurrentRow(index) componentList.setCurrentRow(index)
self.window.stackedWidget.addWidget(self.pages[-1])
self.pages.insert(index, self.core.selectedComponents[index].widget(self))
self.window.stackedWidget.insertWidget(index, self.pages[index])
self.window.stackedWidget.setCurrentIndex(index) self.window.stackedWidget.setCurrentIndex(index)
self.selectedComponents[-1].update() self.core.updateComponent(index)
def insertComponent(self, moduleIndex):
self.selectedComponents.insert(
0, self.modules[moduleIndex].Component())
self.window.listWidget_componentList.insertItem(
0, self.selectedComponents[0].__doc__)
self.pages.insert(0, self.selectedComponents[0].widget(self))
self.window.listWidget_componentList.setCurrentRow(0)
self.window.stackedWidget.insertWidget(0, self.pages[0])
self.window.stackedWidget.setCurrentIndex(0)
self.selectedComponents[0].update()
def removeComponent(self): def removeComponent(self):
for selected in self.window.listWidget_componentList.selectedItems(): for selected in self.window.listWidget_componentList.selectedItems():
index = self.window.listWidget_componentList.row(selected) index = self.window.listWidget_componentList.row(selected)
self.window.stackedWidget.removeWidget(self.pages[index]) self.window.stackedWidget.removeWidget(self.pages[index])
self.window.listWidget_componentList.takeItem(index) self.window.listWidget_componentList.takeItem(index)
self.selectedComponents.pop(index) self.core.selectedComponents.pop(index)
self.pages.pop(index) self.pages.pop(index)
self.changeComponentWidget() self.changeComponentWidget()
self.drawPreview() self.drawPreview()
@ -447,20 +426,21 @@ class MainWindow(QtCore.QObject):
def moveComponentUp(self): def moveComponentUp(self):
row = self.window.listWidget_componentList.currentRow() row = self.window.listWidget_componentList.currentRow()
if row > 0: if row > 0:
module = self.selectedComponents[row] self.core.moveComponent(row, row - 1)
self.selectedComponents.pop(row) page = self.pages.pop(row)
self.selectedComponents.insert(row - 1, module)
page = self.pages[row]
self.pages.pop(row)
self.pages.insert(row - 1, page) self.pages.insert(row - 1, page)
item = self.window.listWidget_componentList.takeItem(row)
self.window.listWidget_componentList.insertItem(row - 1, item)
widget = self.window.stackedWidget.removeWidget(page)
self.window.stackedWidget.insertWidget(row - 1, page)
self.window.listWidget_componentList.setCurrentRow(row - 1)
self.window.stackedWidget.setCurrentIndex(row - 1)
self.drawPreview()
# update widgets
componentList = self.window.listWidget_componentList
stackedWidget = self.window.stackedWidget
item = componentList.takeItem(row)
componentList.insertItem(row - 1, item)
widget = stackedWidget.removeWidget(page)
stackedWidget.insertWidget(row - 1, page)
componentList.setCurrentRow(row - 1)
stackedWidget.setCurrentIndex(row - 1)
self.drawPreview()
'''
def moveComponentDown(self): def moveComponentDown(self):
row = self.window.listWidget_componentList.currentRow() row = self.window.listWidget_componentList.currentRow()
if row != -1 and row < len(self.pages)+1: if row != -1 and row < len(self.pages)+1:
@ -477,6 +457,12 @@ class MainWindow(QtCore.QObject):
self.window.listWidget_componentList.setCurrentRow(row + 1) self.window.listWidget_componentList.setCurrentRow(row + 1)
self.window.stackedWidget.setCurrentIndex(row + 1) self.window.stackedWidget.setCurrentIndex(row + 1)
self.drawPreview() self.drawPreview()
'''
def componentMoved(self, event):
widget = self.window.listWidget_componentList
for i in range(widget.count()):
pass
#print(widget.item(i) == self.componentRows[i])
def openPresetManager(self): def openPresetManager(self):
'''Preset manager for importing, exporting, renaming, deleting''' '''Preset manager for importing, exporting, renaming, deleting'''
@ -484,7 +470,7 @@ class MainWindow(QtCore.QObject):
def createNewProject(self): def createNewProject(self):
self.currentProject = None self.currentProject = None
self.selectedComponents = [] self.core.selectedComponents = []
self.window.listWidget_componentList.clear() self.window.listWidget_componentList.clear()
for widget in self.pages: for widget in self.pages:
self.window.stackedWidget.removeWidget(widget) self.window.stackedWidget.removeWidget(widget)
@ -513,7 +499,7 @@ class MainWindow(QtCore.QObject):
with open(filepath, 'w') as f: with open(filepath, 'w') as f:
print('creating %s' % filepath) print('creating %s' % filepath)
f.write('[Components]\n') f.write('[Components]\n')
for comp in self.selectedComponents: for comp in self.core.selectedComponents:
saveValueStore = comp.savePreset() saveValueStore = comp.savePreset()
f.write('%s\n' % str(comp)) f.write('%s\n' % str(comp))
f.write('%s\n' % str(comp.version())) f.write('%s\n' % str(comp.version()))
@ -538,7 +524,7 @@ class MainWindow(QtCore.QObject):
self.currentProject = filepath self.currentProject = filepath
self.settings.setValue("currentProject", filepath) self.settings.setValue("currentProject", filepath)
self.settings.setValue("projectDir", os.path.dirname(filepath)) self.settings.setValue("projectDir", os.path.dirname(filepath))
compNames = [mod.Component.__doc__ for mod in self.modules] compNames = [mod.Component.__doc__ for mod in self.core.modules]
try: try:
with open(filepath, 'r') as f: with open(filepath, 'r') as f:
validSections = ('Components') validSections = ('Components')
@ -563,14 +549,14 @@ class MainWindow(QtCore.QObject):
if line and section == 'Components': if line and section == 'Components':
if i == 0: if i == 0:
compIndex = compNames.index(line) compIndex = compNames.index(line)
self.addComponent(compIndex) self.insertComponent(compIndex, -1)
i += 1 i += 1
elif i == 1: elif i == 1:
# version, not used yet # version, not used yet
i += 1 i += 1
elif i == 2: elif i == 2:
saveValueStore = dict(eval(line)) saveValueStore = dict(eval(line))
self.selectedComponents[-1].loadPreset( self.core.selectedComponents[-1].loadPreset(
saveValueStore) saveValueStore)
i = 0 i = 0
except (IndexError, ValueError, NameError, SyntaxError, except (IndexError, ValueError, NameError, SyntaxError,
@ -620,7 +606,7 @@ class MainWindow(QtCore.QObject):
# submenu for opening presets # submenu for opening presets
index = self.window.listWidget_componentList.currentRow() index = self.window.listWidget_componentList.currentRow()
try: try:
presets = self.presetManager.presets[str(self.selectedComponents[index])] presets = self.presetManager.presets[str(self.core.selectedComponents[index])]
self.submenu = QtGui.QMenu("Open Preset") self.submenu = QtGui.QMenu("Open Preset")
self.menu.addMenu(self.submenu) self.menu.addMenu(self.submenu)

View File

@ -184,17 +184,20 @@
<property name="lineWidth"> <property name="lineWidth">
<number>1</number> <number>1</number>
</property> </property>
<property name="showDropIndicator" stdset="0"> <property name="tabKeyNavigation">
<bool>false</bool> <bool>true</bool>
</property> </property>
<property name="dragEnabled"> <property name="dragEnabled">
<bool>false</bool> <bool>true</bool>
</property> </property>
<property name="dragDropOverwriteMode"> <property name="dragDropOverwriteMode">
<bool>false</bool> <bool>false</bool>
</property> </property>
<property name="dragDropMode"> <property name="dragDropMode">
<enum>QAbstractItemView::NoDragDrop</enum> <enum>QAbstractItemView::InternalMove</enum>
</property>
<property name="defaultDropAction">
<enum>Qt::MoveAction</enum>
</property> </property>
</widget> </widget>
</item> </item>

View File

@ -86,21 +86,27 @@ class PresetManager(QtGui.QDialog):
if window.listWidget_componentList.currentRow() == -1: if window.listWidget_componentList.currentRow() == -1:
return return
while True: while True:
dialog = QtGui.QInputDialog( index = window.listWidget_componentList.currentRow()
QtGui.QWidget(), 'Audio Visualizer', 'New Preset Name:') currentPreset = self.parent.selectedComponents[index].currentPreset
dialog.setTextValue() newName, OK = QtGui.QInputDialog.getText(
newName, OK = dialog.getText() self.parent.window,
'Audio Visualizer',
'New Preset Name:',
QtGui.QLineEdit.Normal,
currentPreset
)
if OK:
badName = False badName = False
for letter in newName: for letter in newName:
if letter in string.punctuation: if letter in string.punctuation:
badName = True badName = True
if badName: if badName:
# some filesystems don't like bizarre characters # some filesystems don't like bizarre characters
self.parent.showMessage(msg=\ self.parent.showMessage(
'''Preset names must contain only letters, numbers, and spaces.''') msg='Preset names must contain only letters,'
'numbers, and spaces.')
continue continue
if OK and newName: if newName:
index = window.listWidget_componentList.currentRow()
if index != -1: if index != -1:
saveValueStore = \ saveValueStore = \
self.parent.selectedComponents[index].savePreset() self.parent.selectedComponents[index].savePreset()
@ -108,6 +114,7 @@ class PresetManager(QtGui.QDialog):
vers = self.parent.selectedComponents[index].version() vers = self.parent.selectedComponents[index].version()
self.createPresetFile( self.createPresetFile(
componentName, vers, saveValueStore, newName) componentName, vers, saveValueStore, newName)
self.parent.selectedComponents[index].currentPreset = newName
break break
def createPresetFile(self, compName, vers, saveValueStore, filename): def createPresetFile(self, compName, vers, saveValueStore, filename):
@ -139,6 +146,9 @@ class PresetManager(QtGui.QDialog):
for line in f: for line in f:
saveValueStore = dict(eval(line.strip())) saveValueStore = dict(eval(line.strip()))
break break
self.parent.selectedComponents[index].loadPreset(saveValueStore) self.parent.selectedComponents[index].loadPreset(
saveValueStore,
presetName
)
self.parent.drawPreview() self.parent.drawPreview()