From a1d7cbb984f2a6c2ea976daa8914a2c9845ee21c Mon Sep 17 00:00:00 2001 From: tassaron Date: Tue, 15 Aug 2017 22:20:25 -0400 Subject: undoable edits for normal component settings; TODO: merge small edits --- src/toolkit/common.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'src/toolkit/common.py') diff --git a/src/toolkit/common.py b/src/toolkit/common.py index eba57d9..51ad023 100644 --- a/src/toolkit/common.py +++ b/src/toolkit/common.py @@ -9,6 +9,18 @@ import subprocess from collections import OrderedDict +class blockSignals: + '''A context manager to temporarily block a Qt widget from updating''' + def __init__(self, widget): + self.widget = widget + + def __enter__(self): + self.widget.blockSignals(True) + + def __exit__(self, *args): + self.widget.blockSignals(False) + + def badName(name): '''Returns whether a name contains non-alphanumeric chars''' return any([letter in string.punctuation for letter in name]) -- cgit v1.2.3 From c07f2426ceeada205fdacbfba66329179a74a1dc Mon Sep 17 00:00:00 2001 From: tassaron Date: Sat, 19 Aug 2017 18:32:12 -0400 Subject: fixed issues with undoing relative widgets --- src/component.py | 198 +++++++++++++++++++++++++++++++++------------ src/components/color.py | 2 - src/components/image.py | 2 - src/components/life.py | 1 - src/components/sound.py | 1 - src/components/spectrum.py | 4 +- src/components/text.py | 1 - src/components/video.py | 2 - src/components/waveform.py | 2 +- src/core.py | 11 +-- src/gui/actions.py | 11 ++- src/gui/mainwindow.py | 4 +- src/gui/presetmanager.py | 4 + src/gui/preview_thread.py | 2 +- src/gui/preview_win.py | 2 +- src/main.py | 2 +- src/toolkit/common.py | 47 +++++++++-- 17 files changed, 215 insertions(+), 81 deletions(-) (limited to 'src/toolkit/common.py') diff --git a/src/component.py b/src/component.py index 1fe9237..ba86422 100644 --- a/src/component.py +++ b/src/component.py @@ -9,6 +9,7 @@ import sys import math import time import logging +from copy import copy from toolkit.frame import BlankFrame from toolkit import ( @@ -113,14 +114,20 @@ class ComponentMetaclass(type(QtCore.QObject)): def presetWrapper(self, *args): with openingPreset(self): - return func(self, *args) + try: + return func(self, *args) + except Exception: + try: + raise ComponentError(self, 'preset loader') + except ComponentError: + return return presetWrapper def updateWrapper(func): ''' - For undoable updates triggered by the user, - call _userUpdate() after the subclass's update() method. - For non-user updates, call _autoUpdate() + Calls _preUpdate before every subclass update(). + Afterwards, for non-user updates, calls _autoUpdate(). + For undoable updates triggered by the user, calls _userUpdate() ''' class wrap: def __init__(self, comp, auto): @@ -128,24 +135,57 @@ class ComponentMetaclass(type(QtCore.QObject)): self.auto = auto def __enter__(self): - pass + self.comp._preUpdate() def __exit__(self, *args): if self.auto or self.comp.openingPreset \ or not hasattr(self.comp.parent, 'undoStack'): + log.verbose('Automatic update') self.comp._autoUpdate() else: + log.verbose('User update') self.comp._userUpdate() def updateWrapper(self, **kwargs): - auto = False - if 'auto' in kwargs: - auto = kwargs['auto'] - + auto = kwargs['auto'] if 'auto' in kwargs else False with wrap(self, auto): - return func(self) + try: + return func(self) + except Exception: + try: + raise ComponentError(self, 'update method') + except ComponentError: + return return updateWrapper + def widgetWrapper(func): + '''Connects all widgets to update method after the subclass's method''' + class wrap: + def __init__(self, comp): + self.comp = comp + + def __enter__(self): + pass + + def __exit__(self, *args): + for widgetList in self.comp._allWidgets.values(): + for widget in widgetList: + log.verbose('Connecting %s' % str( + widget.__class__.__name__)) + connectWidget(widget, self.comp.update) + + def widgetWrapper(self, *args, **kwargs): + auto = kwargs['auto'] if 'auto' in kwargs else False + with wrap(self): + try: + return func(self, *args, **kwargs) + except Exception: + try: + raise ComponentError(self, 'widget creation') + except ComponentError: + return + return widgetWrapper + def __new__(cls, name, parents, attrs): if 'ui' not in attrs: # Use module name as ui filename by default @@ -153,13 +193,12 @@ class ComponentMetaclass(type(QtCore.QObject)): attrs['__module__'].split('.')[-1] )[0] - # if parents[0] == QtCore.QObject: else: decorate = ( 'names', # Class methods 'error', 'audio', 'properties', # Properties 'preFrameRender', 'previewRender', 'frameRender', 'command', - 'loadPreset', 'update' + 'loadPreset', 'update', 'widget', ) # Auto-decorate methods @@ -184,6 +223,8 @@ class ComponentMetaclass(type(QtCore.QObject)): attrs[key] = cls.loadPresetWrapper(attrs[key]) elif key == 'update': attrs[key] = cls.updateWrapper(attrs[key]) + elif key == 'widget' and parents[0] != QtCore.QObject: + attrs[key] = cls.widgetWrapper(attrs[key]) # Turn version string into a number try: @@ -224,23 +265,28 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): self.moduleIndex = moduleIndex self.compPos = compPos self.core = core - self.currentPreset = None - self.openingPreset = False + # STATUS VARIABLES + self.currentPreset = None + self._allWidgets = {} self._trackedWidgets = {} self._presetNames = {} self._commandArgs = {} self._colorWidgets = {} self._colorFuncs = {} self._relativeWidgets = {} - # pixel values stored as floats + # Pixel values stored as floats self._relativeValues = {} - # maximum values of spinBoxes at 1080p (Core.resolutions[0]) + # Maximum values of spinBoxes at 1080p (Core.resolutions[0]) self._relativeMaximums = {} + # LOCKING VARIABLES + self.openingPreset = False self._lockedProperties = None self._lockedError = None self._lockedSize = None + # If set to a dict, values are used as basis to update relative widgets + self.oldAttrs = None # Stop lengthy processes in response to this variable self.canceled = False @@ -338,21 +384,21 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): ''' self.parent = parent self.settings = parent.settings + log.verbose('Creating UI for %s #%s\'s widget' % ( + self.name, self.compPos + )) self.page = self.loadUi(self.__class__.ui) - # Connect widget signals - widgets = { + # Find all normal widgets which will be connected after subclass method + self._allWidgets = { 'lineEdit': self.page.findChildren(QtWidgets.QLineEdit), 'checkBox': self.page.findChildren(QtWidgets.QCheckBox), 'spinBox': self.page.findChildren(QtWidgets.QSpinBox), 'comboBox': self.page.findChildren(QtWidgets.QComboBox), } - widgets['spinBox'].extend( + self._allWidgets['spinBox'].extend( self.page.findChildren(QtWidgets.QDoubleSpinBox) ) - for widgetList in widgets.values(): - for widget in widgetList: - connectWidget(widget, self.update) def update(self): ''' @@ -427,10 +473,15 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): # =~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~==~=~=~=~=~=~=~=~=~=~=~=~=~=~ # "Private" Methods # =~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~==~=~=~=~=~=~=~=~=~=~=~=~=~=~ + def _preUpdate(self): + '''Happens before subclass update()''' + for attr in self._relativeWidgets: + self.updateRelativeWidget(attr) + def _userUpdate(self): - '''An undoable component update triggered by the user''' + '''Happens after subclass update() for an undoable update by user.''' oldWidgetVals = { - attr: getattr(self, attr) + attr: copy(getattr(self, attr)) for attr in self._trackedWidgets } newWidgetVals = { @@ -443,13 +494,12 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): for attr, val in newWidgetVals.items() if val != oldWidgetVals[attr] } - if modifiedWidgets: action = ComponentUpdate(self, oldWidgetVals, modifiedWidgets) self.parent.undoStack.push(action) def _autoUpdate(self): - '''An internal component update that is not undoable''' + '''Happens after subclass update() for an internal component update.''' newWidgetVals = { attr: getWidgetValue(widget) for attr, widget in self._trackedWidgets.items() @@ -459,12 +509,12 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): def setAttrs(self, attrDict): ''' - Sets attrs (linked to trackedWidgets) in this preset to + Sets attrs (linked to trackedWidgets) in this component to the values in the attrDict. Mutates certain widget values if needed ''' for attr, val in attrDict.items(): if attr in self._colorWidgets: - # Color Widgets: text stored as tuple & update the button color + # Color Widgets must have a tuple & have a button to update if type(val) is tuple: rgbTuple = val else: @@ -475,15 +525,25 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): self._colorWidgets[attr].setStyleSheet(btnStyle) setattr(self, attr, rgbTuple) - elif attr in self._relativeWidgets: - # Relative widgets: number scales to fit export resolution - self.updateRelativeWidget(attr) - setattr(self, attr, val) - else: # Normal tracked widget setattr(self, attr, val) + def setWidgetValues(self, attrDict): + ''' + Sets widgets defined by keys in trackedWidgets in this preset to + the values in the attrDict. + ''' + affectedWidgets = [ + self._trackedWidgets[attr] for attr in attrDict + ] + with blockSignals(affectedWidgets): + for attr, val in attrDict.items(): + widget = self._trackedWidgets[attr] + if attr in self._colorWidgets: + val = '%s,%s,%s' % val + setWidgetValue(widget, val) + def _sendUpdateSignal(self): if not self.core.openingProject: self.parent.drawPreview() @@ -499,6 +559,8 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): Optional args: 'presetNames': preset variable names to replace attr names 'commandArgs': arg keywords that differ from attr names + 'colorWidgets': identify attr as RGB tuple & update button CSS + 'relativeWidgets': change value proportionally to resolution NOTE: Any kwarg key set to None will selectively disable tracking. ''' @@ -542,6 +604,8 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): self._relativeMaximums[attr] = \ self._trackedWidgets[attr].maximum() self.updateRelativeWidgetMaximum(attr) + self._preUpdate() + self._autoUpdate() def pickColor(self, textWidget, button): '''Use color picker to get color input from the user.''' @@ -627,12 +691,28 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): def setRelativeWidget(self, attr, floatVal): '''Set a relative widget using a float''' pixelVal = self.pixelValForAttr(attr, floatVal) - self._trackedWidgets[attr].setValue(pixelVal) + with blockSignals(self._allWidgets): + self._trackedWidgets[attr].setValue(pixelVal) + self.update(auto=True) + + def getOldAttr(self, attr): + ''' + Returns previous state of this attr. Used to determine whether + a relative widget must be updated. Required because undoing/redoing + can make determining the 'previous' value tricky. + ''' + if self.oldAttrs is not None: + log.verbose('Using nonstandard oldAttr for %s' % attr) + return self.oldAttrs[attr] + else: + return getattr(self, attr) def updateRelativeWidget(self, attr): + '''Called by _preUpdate() for each relativeWidget before each update''' try: - oldUserValue = getattr(self, attr) - except AttributeError: + oldUserValue = self.getOldAttr(attr) + except (AttributeError, KeyError): + log.info('Using visible values as basis for relative widgets') oldUserValue = self._trackedWidgets[attr].value() newUserValue = self._trackedWidgets[attr].value() newRelativeVal = self.floatValForAttr(attr, newUserValue) @@ -645,11 +725,10 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): # means the pixel value needs to be updated log.debug('Updating %s #%s\'s relative widget: %s' % ( self.name, self.compPos, attr)) - self._trackedWidgets[attr].blockSignals(True) - self.updateRelativeWidgetMaximum(attr) - pixelVal = self.pixelValForAttr(attr, oldRelativeVal) - self._trackedWidgets[attr].setValue(pixelVal) - self._trackedWidgets[attr].blockSignals(False) + with blockSignals(self._trackedWidgets[attr]): + self.updateRelativeWidgetMaximum(attr) + pixelVal = self.pixelValForAttr(attr, oldRelativeVal) + self._trackedWidgets[attr].setValue(pixelVal) if attr not in self._relativeValues \ or oldUserValue != newUserValue: @@ -725,14 +804,22 @@ class ComponentUpdate(QtWidgets.QUndoCommand): parent.name, parent.compPos ) ) + self.undone = False self.parent = parent self.oldWidgetVals = { - attr: val + attr: copy(val) for attr, val in oldWidgetVals.items() if attr in modifiedVals } self.modifiedVals = modifiedVals + # Because relative widgets change themselves every update based on + # their previous value, we must store ALL their values in case of undo + self.redoRelativeWidgetVals = { + attr: copy(getattr(self.parent, attr)) + for attr in self.parent._relativeWidgets + } + # Determine if this update is mergeable self.id_ = -1 if len(self.modifiedVals) == 1: @@ -755,15 +842,26 @@ class ComponentUpdate(QtWidgets.QUndoCommand): return True def redo(self): + if self.undone: + log.debug('Redoing component update') + self.parent.setWidgetValues(self.modifiedVals) self.parent.setAttrs(self.modifiedVals) - self.parent._sendUpdateSignal() + if self.undone: + self.parent.oldAttrs = self.redoRelativeWidgetVals + self.parent.update(auto=True) + self.parent.oldAttrs = None + else: + self.undoRelativeWidgetVals = { + attr: copy(getattr(self.parent, attr)) + for attr in self.parent._relativeWidgets + } + self.parent._sendUpdateSignal() def undo(self): + log.debug('Undoing component update') + self.undone = True + self.parent.oldAttrs = self.undoRelativeWidgetVals + self.parent.setWidgetValues(self.oldWidgetVals) self.parent.setAttrs(self.oldWidgetVals) - with blockSignals(self.parent): - for attr, val in self.oldWidgetVals.items(): - widget = self.parent._trackedWidgets[attr] - if attr in self.parent._colorWidgets: - val = '%s,%s,%s' % val - setWidgetValue(widget, val) - self.parent._sendUpdateSignal() + self.parent.update(auto=True) + self.parent.oldAttrs = None diff --git a/src/components/color.py b/src/components/color.py index d09cee8..a55aa10 100644 --- a/src/components/color.py +++ b/src/components/color.py @@ -82,8 +82,6 @@ class Component(Component): self.page.pushButton_color2.setEnabled(False) self.page.fillWidget.setCurrentIndex(fillType) - super().update() - def previewRender(self): return self.drawFrame(self.width, self.height) diff --git a/src/components/image.py b/src/components/image.py index 63bee1a..c57b69c 100644 --- a/src/components/image.py +++ b/src/components/image.py @@ -84,7 +84,6 @@ class Component(Component): if filename: self.settings.setValue("componentDir", os.path.dirname(filename)) self.page.lineEdit_image.setText(filename) - self.update() def command(self, arg): if '=' in arg: @@ -123,4 +122,3 @@ class Component(Component): else: scaleBox.setVisible(True) stretchScaleBox.setVisible(False) - super().update() diff --git a/src/components/life.py b/src/components/life.py index 2383d30..76d2c5f 100644 --- a/src/components/life.py +++ b/src/components/life.py @@ -53,7 +53,6 @@ class Component(Component): if filename: self.settings.setValue("componentDir", os.path.dirname(filename)) self.page.lineEdit_image.setText(filename) - self.update() def shiftGrid(self, d): def newGrid(Xchange, Ychange): diff --git a/src/components/sound.py b/src/components/sound.py index 26ecf93..b86f40c 100644 --- a/src/components/sound.py +++ b/src/components/sound.py @@ -53,7 +53,6 @@ class Component(Component): if filename: self.settings.setValue("componentDir", os.path.dirname(filename)) self.page.lineEdit_sound.setText(filename) - self.update() def commandHelp(self): print('Path to audio file:\n path=/filepath/to/sound.ogg') diff --git a/src/components/spectrum.py b/src/components/spectrum.py index 89130a2..2b98dc2 100644 --- a/src/components/spectrum.py +++ b/src/components/spectrum.py @@ -76,8 +76,6 @@ class Component(Component): else: self.page.checkBox_mono.setEnabled(True) - super().update() - def previewRender(self): changedSize = self.updateChunksize() if not changedSize \ @@ -138,7 +136,7 @@ class Component(Component): '-r', self.settings.value("outputFrameRate"), '-ss', "{0:.3f}".format(startPt), '-i', - os.path.join(self.core.wd, 'background.png') + self.core.junkStream if genericPreview else inputFile, '-f', 'image2pipe', '-pix_fmt', 'rgba', diff --git a/src/components/text.py b/src/components/text.py index d3afd5c..92f0599 100644 --- a/src/components/text.py +++ b/src/components/text.py @@ -68,7 +68,6 @@ class Component(Component): self.page.spinBox_shadY.setHidden(True) self.page.label_shadBlur.setHidden(True) self.page.spinBox_shadBlur.setHidden(True) - super().update() def centerXY(self): self.setRelativeWidget('xPosition', 0.5) diff --git a/src/components/video.py b/src/components/video.py index a189f60..9c0d608 100644 --- a/src/components/video.py +++ b/src/components/video.py @@ -52,7 +52,6 @@ class Component(Component): else: self.page.label_volume.setEnabled(False) self.page.spinBox_volume.setEnabled(False) - super().update() def previewRender(self): self.updateChunksize() @@ -119,7 +118,6 @@ class Component(Component): if filename: self.settings.setValue("componentDir", os.path.dirname(filename)) self.page.lineEdit_video.setText(filename) - self.update() def getPreviewFrame(self, width, height): if not self.videoPath or not os.path.exists(self.videoPath): diff --git a/src/components/waveform.py b/src/components/waveform.py index 0743e55..5c02bbf 100644 --- a/src/components/waveform.py +++ b/src/components/waveform.py @@ -98,7 +98,7 @@ class Component(Component): '-r', self.settings.value("outputFrameRate"), '-ss', "{0:.3f}".format(startPt), '-i', - os.path.join(self.core.wd, 'background.png') + self.core.junkStream if genericPreview else inputFile, '-f', 'image2pipe', '-pix_fmt', 'rgba', diff --git a/src/core.py b/src/core.py index d9499f7..169716c 100644 --- a/src/core.py +++ b/src/core.py @@ -13,7 +13,7 @@ import toolkit log = logging.getLogger('AVP.Core') -STDOUT_LOGLVL = logging.WARNING +STDOUT_LOGLVL = logging.VERBOSE FILE_LOGLVL = logging.DEBUG @@ -81,10 +81,7 @@ class Core: component = self.modules[moduleIndex].Component( moduleIndex, compPos, self ) - # init component's widget for loading/saving presets component.widget(loader) - # use autoUpdate() method before update() this 1 time to set attrs - component._autoUpdate() else: moduleIndex = -1 log.debug( @@ -186,9 +183,8 @@ class Core: if hasattr(loader, 'window'): for widget, value in data['WindowFields']: widget = eval('loader.window.%s' % widget) - widget.blockSignals(True) - toolkit.setWidgetValue(widget, value) - widget.blockSignals(False) + with toolkit.blockSignals(widget): + toolkit.setWidgetValue(widget, value) for key, value in data['Settings']: Core.settings.setValue(key, value) @@ -474,6 +470,7 @@ class Core: 'logDir': os.path.join(dataDir, 'log'), 'presetDir': os.path.join(dataDir, 'presets'), 'componentsPath': os.path.join(wd, 'components'), + 'junkStream': os.path.join(wd, 'gui', 'background.png'), 'encoderOptions': encoderOptions, 'resolutions': [ '1920x1080', diff --git a/src/gui/actions.py b/src/gui/actions.py index 0fe97f2..1444569 100644 --- a/src/gui/actions.py +++ b/src/gui/actions.py @@ -20,11 +20,20 @@ class AddComponent(QUndoCommand): self.parent = parent self.moduleI = moduleI self.compI = compI + self.comp = None def redo(self): - self.parent.core.insertComponent(self.compI, self.moduleI, self.parent) + if self.comp is None: + self.parent.core.insertComponent( + self.compI, self.moduleI, self.parent) + else: + # inserting previously-created component + self.parent.core.insertComponent( + self.compI, self.comp, self.parent) + def undo(self): + self.comp = self.parent.core.selectedComponents[self.compI] self.parent._removeComponent(self.compI) diff --git a/src/gui/mainwindow.py b/src/gui/mainwindow.py index 8000b3b..76c53af 100644 --- a/src/gui/mainwindow.py +++ b/src/gui/mainwindow.py @@ -25,7 +25,7 @@ from toolkit import ( ) -log = logging.getLogger('AVP.MainWindow') +log = logging.getLogger('AVP.Gui.MainWindow') class MainWindow(QtWidgets.QMainWindow): @@ -76,7 +76,7 @@ class MainWindow(QtWidgets.QMainWindow): # Create the preview window and its thread, queues, and timers log.debug('Creating preview window') self.previewWindow = PreviewWindow(self, os.path.join( - Core.wd, "background.png")) + Core.wd, 'gui', "background.png")) window.verticalLayout_previewWrapper.addWidget(self.previewWindow) log.debug('Starting preview thread') diff --git a/src/gui/presetmanager.py b/src/gui/presetmanager.py index dce5333..befa7cd 100644 --- a/src/gui/presetmanager.py +++ b/src/gui/presetmanager.py @@ -5,12 +5,16 @@ from PyQt5 import QtCore, QtWidgets import string import os +import logging from toolkit import badName from core import Core from gui.actions import * +log = logging.getLogger('AVP.Gui.PresetManager') + + class PresetManager(QtWidgets.QDialog): def __init__(self, window, parent): super().__init__(parent.window) diff --git a/src/gui/preview_thread.py b/src/gui/preview_thread.py index 9615884..33a9e7a 100644 --- a/src/gui/preview_thread.py +++ b/src/gui/preview_thread.py @@ -14,7 +14,7 @@ from toolkit.frame import Checkerboard from toolkit import disableWhenOpeningProject -log = logging.getLogger("AVP.PreviewThread") +log = logging.getLogger("AVP.Gui.PreviewThread") class Worker(QtCore.QObject): diff --git a/src/gui/preview_win.py b/src/gui/preview_win.py index 40c19c6..c6b9a32 100644 --- a/src/gui/preview_win.py +++ b/src/gui/preview_win.py @@ -7,7 +7,7 @@ class PreviewWindow(QtWidgets.QLabel): Paints the preview QLabel in MainWindow and maintains the aspect ratio when the window is resized. ''' - log = logging.getLogger('AVP.PreviewWindow') + log = logging.getLogger('AVP.Gui.PreviewWindow') def __init__(self, parent, img): super(PreviewWindow, self).__init__() diff --git a/src/main.py b/src/main.py index c1278da..6d18af3 100644 --- a/src/main.py +++ b/src/main.py @@ -6,7 +6,7 @@ import logging from __init__ import wd -log = logging.getLogger('AVP.Entrypoint') +log = logging.getLogger('AVP.Main') def main(): diff --git a/src/toolkit/common.py b/src/toolkit/common.py index 51ad023..74143e8 100644 --- a/src/toolkit/common.py +++ b/src/toolkit/common.py @@ -6,19 +6,53 @@ import string import os import sys import subprocess +import logging +from copy import copy from collections import OrderedDict +log = logging.getLogger('AVP.Toolkit.Common') + + class blockSignals: - '''A context manager to temporarily block a Qt widget from updating''' - def __init__(self, widget): - self.widget = widget + ''' + Context manager to temporarily block list of QtWidgets from updating, + and guarantee restoring the previous state afterwards. + ''' + def __init__(self, widgets): + if type(widgets) is dict: + self.widgets = concatDictVals(widgets) + else: + self.widgets = ( + widgets if hasattr(widgets, '__iter__') + else [widgets] + ) def __enter__(self): - self.widget.blockSignals(True) + log.verbose('Blocking signals for %s' % ", ".join([ + str(w.__class__.__name__) for w in self.widgets + ])) + self.oldStates = [w.signalsBlocked() for w in self.widgets] + for w in self.widgets: + w.blockSignals(True) def __exit__(self, *args): - self.widget.blockSignals(False) + log.verbose('Resetting blockSignals to %s' % sum(self.oldStates)) + for w, state in zip(self.widgets, self.oldStates): + w.blockSignals(state) + + +def concatDictVals(d): + '''Concatenates all values in given dict into one list.''' + key, value = d.popitem() + d[key] = value + final = copy(value) + if type(final) is not list: + final = [final] + final.extend([val for val in d.values()]) + else: + value.extend([item for val in d.values() for item in val]) + return final def badName(name): @@ -119,12 +153,14 @@ def connectWidget(widget, func): elif type(widget) == QtWidgets.QComboBox: widget.currentIndexChanged.connect(func) else: + log.warning('Failed to connect %s ' % str(widget.__class__.__name__)) return False return True def setWidgetValue(widget, val): '''Generic setValue method for use with any typical QtWidget''' + log.verbose('Setting %s to %s' % (str(widget.__class__.__name__), val)) if type(widget) == QtWidgets.QLineEdit: widget.setText(val) elif type(widget) == QtWidgets.QSpinBox \ @@ -135,6 +171,7 @@ def setWidgetValue(widget, val): elif type(widget) == QtWidgets.QComboBox: widget.setCurrentIndex(val) else: + log.warning('Failed to set %s ' % str(widget.__class__.__name__)) return False return True -- cgit v1.2.3 From d4b63e4d4612db262424fe10c83f8eaa4f741f24 Mon Sep 17 00:00:00 2001 From: tassaron Date: Sat, 19 Aug 2017 20:45:44 -0400 Subject: remove % from log calls --- src/component.py | 32 +++++++++++++++++--------------- src/core.py | 19 ++++++++++--------- src/gui/actions.py | 3 ++- src/gui/mainwindow.py | 26 +++++++++++++++++++++----- src/gui/presetmanager.py | 2 +- src/toolkit/common.py | 16 ++++++++++------ src/toolkit/ffmpeg.py | 2 +- src/video_thread.py | 7 ++++--- 8 files changed, 66 insertions(+), 41 deletions(-) (limited to 'src/toolkit/common.py') diff --git a/src/component.py b/src/component.py index ba86422..992a82e 100644 --- a/src/component.py +++ b/src/component.py @@ -40,11 +40,11 @@ class ComponentMetaclass(type(QtCore.QObject)): def renderWrapper(func): def renderWrapper(self, *args, **kwargs): try: - log.verbose('### %s #%s renders%s frame %s###' % ( + log.verbose('### %s #%s renders%s frame %s###', self.__class__.name, str(self.compPos), '' if args else ' a preview', '' if not args else '%s ' % args[0], - )) + ) return func(self, *args, **kwargs) except Exception as e: try: @@ -170,7 +170,7 @@ class ComponentMetaclass(type(QtCore.QObject)): def __exit__(self, *args): for widgetList in self.comp._allWidgets.values(): for widget in widgetList: - log.verbose('Connecting %s' % str( + log.verbose('Connecting %s', str( widget.__class__.__name__)) connectWidget(widget, self.comp.update) @@ -230,16 +230,18 @@ class ComponentMetaclass(type(QtCore.QObject)): try: if 'version' not in attrs: log.error( - 'No version attribute in %s. Defaulting to 1' % + 'No version attribute in %s. Defaulting to 1', attrs['name']) attrs['version'] = 1 else: attrs['version'] = int(attrs['version'].split('.')[0]) except ValueError: - log.critical('%s component has an invalid version string:\n%s' % ( - attrs['name'], str(attrs['version']))) + log.critical( + '%s component has an invalid version string:\n%s', + attrs['name'], str(attrs['version']) + ) except KeyError: - log.critical('%s component has no version string.' % attrs['name']) + log.critical('%s component has no version string.', attrs['name']) else: return super().__new__(cls, name, parents, attrs) quit(1) @@ -384,9 +386,9 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): ''' self.parent = parent self.settings = parent.settings - log.verbose('Creating UI for %s #%s\'s widget' % ( + log.verbose('Creating UI for %s #%s\'s widget', self.name, self.compPos - )) + ) self.page = self.loadUi(self.__class__.ui) # Find all normal widgets which will be connected after subclass method @@ -702,7 +704,7 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): can make determining the 'previous' value tricky. ''' if self.oldAttrs is not None: - log.verbose('Using nonstandard oldAttr for %s' % attr) + log.verbose('Using nonstandard oldAttr for %s', attr) return self.oldAttrs[attr] else: return getattr(self, attr) @@ -723,8 +725,9 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): and oldRelativeVal != newRelativeVal: # Float changed without pixel value changing, which # means the pixel value needs to be updated - log.debug('Updating %s #%s\'s relative widget: %s' % ( - self.name, self.compPos, attr)) + log.debug( + 'Updating %s #%s\'s relative widget: %s', + self.name, self.compPos, attr) with blockSignals(self._trackedWidgets[attr]): self.updateRelativeWidgetMaximum(attr) pixelVal = self.pixelValForAttr(attr, oldRelativeVal) @@ -828,9 +831,8 @@ class ComponentUpdate(QtWidgets.QUndoCommand): self.modifiedVals[attr] = val else: log.warning( - '%s component settings changed at once. (%s)' % ( - len(self.modifiedVals), repr(self.modifiedVals) - ) + '%s component settings changed at once. (%s)', + len(self.modifiedVals), repr(self.modifiedVals) ) def id(self): diff --git a/src/core.py b/src/core.py index 169716c..bfb8272 100644 --- a/src/core.py +++ b/src/core.py @@ -77,7 +77,8 @@ class Core: if type(component) is int: # create component using module index in self.modules moduleIndex = int(component) - log.debug('Creating new component from module #%s' % moduleIndex) + log.debug( + 'Creating new component from module #%s', str(moduleIndex)) component = self.modules[moduleIndex].Component( moduleIndex, compPos, self ) @@ -85,7 +86,7 @@ class Core: else: moduleIndex = -1 log.debug( - 'Inserting previously-created %s component' % component.name) + 'Inserting previously-created %s component', component.name) component._error.connect( loader.videoThreadError @@ -117,8 +118,9 @@ class Core: self.componentListChanged() def updateComponent(self, i): - log.debug('Auto-updating %s #%s' % ( - self.selectedComponents[i], str(i))) + log.debug( + 'Auto-updating %s #%s', + self.selectedComponents[i], str(i)) self.selectedComponents[i].update(auto=True) def moduleIndexFor(self, compName): @@ -146,9 +148,8 @@ class Core: ) except KeyError as e: log.warning( - '%s #%s\'s preset is missing value: %s' % ( - comp.name, str(compIndex), str(e) - ) + '%s #%s\'s preset is missing value: %s', + comp.name, str(compIndex), str(e) ) self.savedPresets[presetName] = dict(saveValueStore) @@ -266,7 +267,7 @@ class Core: Returns dictionary with section names as the keys, each one contains a list of tuples: (compName, version, compPresetDict) ''' - log.debug('Parsing av file: %s' % filepath) + log.debug('Parsing av file: %s', filepath) validSections = ( 'Components', 'Settings', @@ -385,7 +386,7 @@ class Core: def createProjectFile(self, filepath, window=None): '''Create a project file (.avp) using the current program state''' - log.info('Creating %s' % filepath) + log.info('Creating %s', filepath) settingsKeys = [ 'componentDir', 'inputDir', diff --git a/src/gui/actions.py b/src/gui/actions.py index 1444569..f101bd7 100644 --- a/src/gui/actions.py +++ b/src/gui/actions.py @@ -3,6 +3,7 @@ ''' from PyQt5.QtWidgets import QUndoCommand import os +from copy import copy from core import Core @@ -132,7 +133,7 @@ class OpenPreset(QUndoCommand): comp = self.parent.core.selectedComponents[compI] self.store = comp.savePreset() - self.store['preset'] = str(comp.currentPreset) + self.store['preset'] = copy(comp.currentPreset) def redo(self): self.parent._openPreset(self.presetName, self.compI) diff --git a/src/gui/mainwindow.py b/src/gui/mainwindow.py index 76c53af..833d2d1 100644 --- a/src/gui/mainwindow.py +++ b/src/gui/mainwindow.py @@ -387,30 +387,46 @@ class MainWindow(QtWidgets.QMainWindow): @QtCore.pyqtSlot(int, dict) def updateComponentTitle(self, pos, presetStore=False): + ''' + Sets component title to modified or unmodified when given boolean. + If given a preset dict, compares it against the component to + determine if it is modified. + A component with no preset is always unmodified. + ''' if type(presetStore) is dict: name = presetStore['preset'] if name is None or name not in self.core.savedPresets: modified = False else: modified = (presetStore != self.core.savedPresets[name]) + if modified: + log.verbose( + 'Differing values between presets: %s', + ", ".join([ + '%s: %s' % item for item in presetStore.items() + if val != self.core.savedPresets[name][key] + ]) + ) else: modified = bool(presetStore) if pos < 0: pos = len(self.core.selectedComponents)-1 - name = str(self.core.selectedComponents[pos]) + name = self.core.selectedComponents[pos].name title = str(name) if self.core.selectedComponents[pos].currentPreset: title += ' - %s' % self.core.selectedComponents[pos].currentPreset if modified: title += '*' if type(presetStore) is bool: - log.debug('Forcing %s #%s\'s modified status to %s: %s' % ( + log.debug( + 'Forcing %s #%s\'s modified status to %s: %s', name, pos, modified, title - )) + ) else: - log.debug('Setting %s #%s\'s title: %s' % ( + log.debug( + 'Setting %s #%s\'s title: %s', name, pos, title - )) + ) self.window.listWidget_componentList.item(pos).setText(title) def updateCodecs(self): diff --git a/src/gui/presetmanager.py b/src/gui/presetmanager.py index befa7cd..2445760 100644 --- a/src/gui/presetmanager.py +++ b/src/gui/presetmanager.py @@ -210,7 +210,7 @@ class PresetManager(QtWidgets.QDialog): def _openPreset(self, presetName, index): selectedComponents = self.core.selectedComponents - componentName = str(selectedComponents[index]).strip() + componentName = selectedComponents[index].name.strip() version = selectedComponents[index].version dirname = os.path.join(self.presetDir, componentName, str(version)) filepath = os.path.join(dirname, presetName) diff --git a/src/toolkit/common.py b/src/toolkit/common.py index 74143e8..95aeab3 100644 --- a/src/toolkit/common.py +++ b/src/toolkit/common.py @@ -29,15 +29,19 @@ class blockSignals: ) def __enter__(self): - log.verbose('Blocking signals for %s' % ", ".join([ - str(w.__class__.__name__) for w in self.widgets - ])) + log.verbose( + 'Blocking signals for %s', + ", ".join([ + str(w.__class__.__name__) for w in self.widgets + ]) + ) self.oldStates = [w.signalsBlocked() for w in self.widgets] for w in self.widgets: w.blockSignals(True) def __exit__(self, *args): - log.verbose('Resetting blockSignals to %s' % sum(self.oldStates)) + log.verbose( + 'Resetting blockSignals to %s', str(bool(sum(self.oldStates)))) for w, state in zip(self.widgets, self.oldStates): w.blockSignals(state) @@ -153,7 +157,7 @@ def connectWidget(widget, func): elif type(widget) == QtWidgets.QComboBox: widget.currentIndexChanged.connect(func) else: - log.warning('Failed to connect %s ' % str(widget.__class__.__name__)) + log.warning('Failed to connect %s ', str(widget.__class__.__name__)) return False return True @@ -171,7 +175,7 @@ def setWidgetValue(widget, val): elif type(widget) == QtWidgets.QComboBox: widget.setCurrentIndex(val) else: - log.warning('Failed to set %s ' % str(widget.__class__.__name__)) + log.warning('Failed to set %s ', str(widget.__class__.__name__)) return False return True diff --git a/src/toolkit/ffmpeg.py b/src/toolkit/ffmpeg.py index 8fe9148..f007f90 100644 --- a/src/toolkit/ffmpeg.py +++ b/src/toolkit/ffmpeg.py @@ -93,7 +93,7 @@ class FfmpegVideo: from component import ComponentError logFilename = os.path.join( core.Core.logDir, 'render_%s.log' % str(self.component.compPos)) - log.debug('Creating ffmpeg process (log at %s)' % logFilename) + log.debug('Creating ffmpeg process (log at %s)', logFilename) with open(logFilename, 'w') as logf: logf.write(" ".join(self.command) + '\n\n') with open(logFilename, 'a') as logf: diff --git a/src/video_thread.py b/src/video_thread.py index 87fb9bd..823ac73 100644 --- a/src/video_thread.py +++ b/src/video_thread.py @@ -179,7 +179,7 @@ class Worker(QtCore.QObject): for num, component in enumerate(reversed(self.components)) ]) print('Loaded Components:', initText) - log.info('Calling preFrameRender for %s' % initText) + log.info('Calling preFrameRender for %s', initText) self.staticComponents = {} for compNo, comp in enumerate(reversed(self.components)): try: @@ -221,12 +221,13 @@ class Worker(QtCore.QObject): if self.canceled: if canceledByComponent: - log.error('Export cancelled by component #%s (%s): %s' % ( + log.error( + 'Export cancelled by component #%s (%s): %s', compNo, comp.name, 'No message.' if comp.error() is None else ( comp.error() if type(comp.error()) is str - else comp.error()[0]) + else comp.error()[0] ) ) self.cancelExport() -- cgit v1.2.3 From be9eb9077b2234e6d91c78d70bb8e1d8347b03aa Mon Sep 17 00:00:00 2001 From: tassaron Date: Sun, 20 Aug 2017 17:47:00 -0400 Subject: relative widgets scale properly when undoing at different resolutions --- src/component.py | 81 +++++++++++++++++++++++++++++++++-------------- src/components/life.py | 2 +- src/gui/mainwindow.py | 7 ++-- src/gui/preview_thread.py | 6 ++-- src/toolkit/common.py | 1 + 5 files changed, 68 insertions(+), 29 deletions(-) (limited to 'src/toolkit/common.py') diff --git a/src/component.py b/src/component.py index 992a82e..0ff2fbd 100644 --- a/src/component.py +++ b/src/component.py @@ -40,7 +40,8 @@ class ComponentMetaclass(type(QtCore.QObject)): def renderWrapper(func): def renderWrapper(self, *args, **kwargs): try: - log.verbose('### %s #%s renders%s frame %s###', + log.verbose( + '### %s #%s renders%s frame %s###', self.__class__.name, str(self.compPos), '' if args else ' a preview', '' if not args else '%s ' % args[0], @@ -289,7 +290,6 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): self._lockedSize = None # If set to a dict, values are used as basis to update relative widgets self.oldAttrs = None - # Stop lengthy processes in response to this variable self.canceled = False @@ -386,7 +386,8 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): ''' self.parent = parent self.settings = parent.settings - log.verbose('Creating UI for %s #%s\'s widget', + log.verbose( + 'Creating UI for %s #%s\'s widget', self.name, self.compPos ) self.page = self.loadUi(self.__class__.ui) @@ -530,6 +531,7 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): else: # Normal tracked widget setattr(self, attr, val) + log.verbose('Setting %s self.%s to %s' % (self.name, attr, val)) def setWidgetValues(self, attrDict): ''' @@ -669,12 +671,22 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): def relativeWidgetAxis(func): def relativeWidgetAxis(self, attr, *args, **kwargs): + hasVerticalWords = ( + lambda attr: + 'height' in attr.lower() or + 'ypos' in attr.lower() or + attr == 'y' + ) if 'axis' not in kwargs: axis = self.width - if 'height' in attr.lower() \ - or 'ypos' in attr.lower() or attr == 'y': + if hasVerticalWords(attr): axis = self.height kwargs['axis'] = axis + if 'axis' in kwargs and type(kwargs['axis']) is tuple: + axis = kwargs['axis'][0] + if hasVerticalWords(attr): + axis = kwargs['axis'][1] + kwargs['axis'] = axis return func(self, attr, *args, **kwargs) return relativeWidgetAxis @@ -682,7 +694,12 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): def pixelValForAttr(self, attr, val=None, **kwargs): if val is None: val = self._relativeValues[attr] - return math.ceil(kwargs['axis'] * val) + result = math.ceil(kwargs['axis'] * val) + log.verbose( + 'Converting %s: f%s to px%s using axis %s', + attr, val, result, kwargs['axis'] + ) + return result @relativeWidgetAxis def floatValForAttr(self, attr, val=None, **kwargs): @@ -693,7 +710,7 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): def setRelativeWidget(self, attr, floatVal): '''Set a relative widget using a float''' pixelVal = self.pixelValForAttr(attr, floatVal) - with blockSignals(self._allWidgets): + with blockSignals(self._trackedWidgets[attr]): self._trackedWidgets[attr].setValue(pixelVal) self.update(auto=True) @@ -707,15 +724,15 @@ class Component(QtCore.QObject, metaclass=ComponentMetaclass): log.verbose('Using nonstandard oldAttr for %s', attr) return self.oldAttrs[attr] else: - return getattr(self, attr) + try: + return getattr(self, attr) + except AttributeError: + log.info('Using visible values instead of attrs') + return self._trackedWidgets[attr].value() def updateRelativeWidget(self, attr): '''Called by _preUpdate() for each relativeWidget before each update''' - try: - oldUserValue = self.getOldAttr(attr) - except (AttributeError, KeyError): - log.info('Using visible values as basis for relative widgets') - oldUserValue = self._trackedWidgets[attr].value() + oldUserValue = self.getOldAttr(attr) newUserValue = self._trackedWidgets[attr].value() newRelativeVal = self.floatValForAttr(attr, newUserValue) @@ -808,17 +825,25 @@ class ComponentUpdate(QtWidgets.QUndoCommand): ) ) self.undone = False + self.res = (int(parent.width), int(parent.height)) self.parent = parent self.oldWidgetVals = { attr: copy(val) + if attr not in self.parent._relativeWidgets + else self.parent.floatValForAttr(attr, val, axis=self.res) for attr, val in oldWidgetVals.items() if attr in modifiedVals } - self.modifiedVals = modifiedVals + self.modifiedVals = { + attr: val + if attr not in self.parent._relativeWidgets + else self.parent.floatValForAttr(attr, val, axis=self.res) + for attr, val in modifiedVals.items() + } # Because relative widgets change themselves every update based on # their previous value, we must store ALL their values in case of undo - self.redoRelativeWidgetVals = { + self.relativeWidgetValsAfterUndo = { attr: copy(getattr(self.parent, attr)) for attr in self.parent._relativeWidgets } @@ -843,17 +868,28 @@ class ComponentUpdate(QtWidgets.QUndoCommand): self.modifiedVals.update(other.modifiedVals) return True + def setWidgetValues(self, attrDict): + ''' + Mask the component's usual method to handle our + relative widgets in case the resolution has changed. + ''' + newAttrDict = { + attr: val if attr not in self.parent._relativeWidgets + else self.parent.pixelValForAttr(attr, val) + for attr, val in attrDict.items() + } + self.parent.setWidgetValues(newAttrDict) + def redo(self): if self.undone: log.debug('Redoing component update') - self.parent.setWidgetValues(self.modifiedVals) - self.parent.setAttrs(self.modifiedVals) - if self.undone: - self.parent.oldAttrs = self.redoRelativeWidgetVals + self.parent.oldAttrs = self.relativeWidgetValsAfterUndo + self.setWidgetValues(self.modifiedVals) self.parent.update(auto=True) self.parent.oldAttrs = None else: - self.undoRelativeWidgetVals = { + self.parent.setAttrs(self.modifiedVals) + self.relativeWidgetValsAfterRedo = { attr: copy(getattr(self.parent, attr)) for attr in self.parent._relativeWidgets } @@ -862,8 +898,7 @@ class ComponentUpdate(QtWidgets.QUndoCommand): def undo(self): log.debug('Undoing component update') self.undone = True - self.parent.oldAttrs = self.undoRelativeWidgetVals - self.parent.setWidgetValues(self.oldWidgetVals) - self.parent.setAttrs(self.oldWidgetVals) + self.parent.oldAttrs = self.relativeWidgetValsAfterRedo + self.setWidgetValues(self.oldWidgetVals) self.parent.update(auto=True) self.parent.oldAttrs = None diff --git a/src/components/life.py b/src/components/life.py index 76d2c5f..5d00987 100644 --- a/src/components/life.py +++ b/src/components/life.py @@ -70,7 +70,7 @@ class Component(Component): elif d == 3: newGrid = newGrid(1, 0) self.startingGrid = newGrid - self.sendUpdateSignal() + self._sendUpdateSignal() def update(self): self.updateGridSize() diff --git a/src/gui/mainwindow.py b/src/gui/mainwindow.py index 833d2d1..2841896 100644 --- a/src/gui/mainwindow.py +++ b/src/gui/mainwindow.py @@ -88,10 +88,13 @@ class MainWindow(QtWidgets.QMainWindow): self.previewWorker.imageCreated.connect(self.showPreviewImage) self.previewThread.start() - log.debug('Starting preview timer') + timeout = 500 + log.debug( + 'Preview timer set to trigger when idle for %sms' % str(timeout) + ) self.timer = QtCore.QTimer(self) self.timer.timeout.connect(self.processTask.emit) - self.timer.start(500) + self.timer.start(timeout) # Begin decorating the window and connecting events self.window.installEventFilter(self) diff --git a/src/gui/preview_thread.py b/src/gui/preview_thread.py index 33a9e7a..d3e0581 100644 --- a/src/gui/preview_thread.py +++ b/src/gui/preview_thread.py @@ -45,8 +45,6 @@ class Worker(QtCore.QObject): @pyqtSlot() def process(self): - width = int(self.settings.value('outputWidth')) - height = int(self.settings.value('outputHeight')) try: nextPreviewInformation = self.queue.get(block=False) while self.queue.qsize() >= 2: @@ -54,12 +52,14 @@ class Worker(QtCore.QObject): self.queue.get(block=False) except Empty: continue + width = int(self.settings.value('outputWidth')) + height = int(self.settings.value('outputHeight')) if self.background.width != width \ or self.background.height != height: self.background = Checkerboard(width, height) frame = self.background.copy() - log.debug('Creating new preview frame') + log.info('Creating new preview frame') components = nextPreviewInformation["components"] for component in reversed(components): try: diff --git a/src/toolkit/common.py b/src/toolkit/common.py index 95aeab3..2e800eb 100644 --- a/src/toolkit/common.py +++ b/src/toolkit/common.py @@ -84,6 +84,7 @@ def appendUppercase(lst): lst.append(form.upper()) return lst + def pipeWrapper(func): '''A decorator to insert proper kwargs into Popen objects.''' def pipeWrapper(commandList, **kwargs): -- cgit v1.2.3