Commit 64188779 authored by Victor Wåhlström's avatar Victor Wåhlström

Ran "autopep8 --ignore=E501,E241" on all Python files.

This normalizes tabs/spaces to 4-space indent, replaces usage of deprecated global variables, removes superfluous characters, etc.

Ref T6588
parent 08cecbe0
......@@ -32,6 +32,7 @@ builtins.Scripter = Krita.instance()
builtins.Application = Krita.instance()
builtins.Krita = Krita.instance()
def qDebug(text):
'''Use KDE way to show debug info
......@@ -69,4 +70,3 @@ def on_pykrita_loaded():
def on_pykrita_unloading():
qDebug('UNLOADING PYKRITA')
return True
......@@ -29,14 +29,15 @@ from PyKrita.krita import *
import pykrita
def objectIsAlive(obj):
''' Test whether an object is alive; that is, whether the pointer
to the object still exists. '''
import sip
try:
sip.unwrapinstance(obj)
sip.unwrapinstance(obj)
except RuntimeError:
return False
return False
return True
......@@ -47,4 +48,3 @@ def qDebug(text):
'''
plugin = sys._getframe(1).f_globals['__name__']
pykrita.qDebug('{}: {}'.format(plugin, text))
......@@ -34,7 +34,7 @@ from PyQt5.QtWidgets import qApp
variant_converter = {
"QVariantList": lambda v: v.toList(v),
"QVariantList": lambda v: v.toList(v),
"QVariantMap": lambda v: toPyObject(v),
"QPoint": lambda v: v.toPoint(),
"str": lambda v: v.toString(),
......@@ -64,6 +64,7 @@ variant_converter = {
"ActionMap": lambda v: int(v.count())
}
def wrap_variant_object(variant):
"""
convert a QObject or a QWidget to its wrapped superclass
......@@ -71,6 +72,7 @@ def wrap_variant_object(variant):
o = Krita.fromVariant(variant)
return wrap(o, True)
def from_variant(variant):
"""
convert a QVariant to a Python value
......@@ -88,6 +90,7 @@ def from_variant(variant):
# Give up and return
return variant
def convert_value(value):
"""
Convert a given value, upcasting to the highest QObject-based class if possible,
......@@ -114,13 +117,14 @@ def convert_value(value):
if hasattr(value, '__class__') and issubclass(value.__class__, QObject):
return wrap(value, True)
if hasattr(value, '__type__') and not (value is None or value.type() is None) :
return from_variant(value);
if hasattr(value, '__type__') and not (value is None or value.type() is None):
return from_variant(value)
return value
qtclasses = {}
def wrap(obj, force=False):
"""
If a class is not known by PyQt it will be automatically
......@@ -143,6 +147,7 @@ def wrap(obj, force=False):
obj = create_pyqt_object(obj)
return obj
def unwrap(obj):
"""
if wrapped returns the wrapped object
......@@ -152,7 +157,6 @@ def unwrap(obj):
return obj
def is_qobject(obj):
"""
checks if class or wrapped class is a subclass of QObject
......@@ -178,15 +182,15 @@ def is_scripter_child(qobj):
return found
class Error(Exception):
"""
Base error classed. Catch this to handle exceptions comming from C++
"""
class PyQtClass(object):
"""
Base class
"""
......@@ -194,7 +198,6 @@ class PyQtClass(object):
def __init__(self, instance):
self._instance = instance
def __del__(self):
"""
If this object is deleted it should also delete the wrapped object
......@@ -206,48 +209,37 @@ class PyQtClass(object):
print("Cannot delete", qobj, "because it has child objects")
sip.delete(qobj)
def setProperty(self, name, value):
self._instance.setProperty(name, value)
def getProperty(self, name):
return wrap(self._instance.property(name))
def propertyNames(self):
return list(self.__class__.__properties__.keys())
def dynamicPropertyNames(self):
return self._instance.dynamicPropertyNames()
def metaObject(self):
return self._instance.metaObject()
def connect(self, signal, slot):
getattr(self._instance, signal).connect(slot)
def disconnect(self, signal, slot):
getattr(self._instance, signal).disconnect(slot)
def parent(self):
return wrap(self._instance.parent())
def children(self):
return [wrap(c) for c in self._instance.children()]
@property
def qt(self):
return self._instance
def __getitem__(self, key):
if isinstance(key, int):
length = getattr(self, "length", None)
......@@ -262,7 +254,6 @@ class PyQtClass(object):
else:
return getattr(self, key)
def __getattr__(self, name):
# Make named child objects available as attributes like QtQml
# Check whether the object is in the QObject hierarchy
......@@ -293,48 +284,38 @@ class PyQtClass(object):
names.append(str(pn))
return names
def __enter__(self):
print("__enter__", self)
def __exit__(self, exc_type, exc_value, traceback):
print("__exit__", self, exc_type, exc_value, traceback)
class PyQtProperty(object):
# slots for more speed
__slots__ = ["meta_property", "name", "__doc__", "read_only"]
def __init__(self, meta_property):
self.meta_property = meta_property
self.name = meta_property.name()
self.read_only = not meta_property.isWritable()
self.__doc__ = "%s is a %s%s" % (
self.name, meta_property.typeName(),
self.name, meta_property.typeName(),
self.read_only and " (read-only)" or ""
)
)
def get(self, obj):
return convert_value(self.meta_property.read(obj._instance))
def set(self, obj, value):
self.meta_property.write(obj._instance, value)
class PyQtMethod(object):
__slots__ = ["meta_method", "name", "args", "returnType", "__doc__"]
def __init__(self, meta_method):
self.meta_method = meta_method
self.name, args = str(meta_method.methodSignature(), encoding="utf-8").split("(", 1)
......@@ -342,12 +323,12 @@ class PyQtMethod(object):
self.returnType = str(meta_method.typeName())
types = [str(t, encoding="utf-8") for t in meta_method.parameterTypes()]
names = [str(n, encoding="utf-8") or "arg%i" % (i+1) \
for i, n in enumerate(meta_method.parameterNames())]
names = [str(n, encoding="utf-8") or "arg%i" % (i + 1)
for i, n in enumerate(meta_method.parameterNames())]
params = ", ".join("%s %s" % (t, n) for n, t in zip(types, names))
self.__doc__ = "%s(%s)%s" % (
self.name, params,
self.name, params,
self.returnType and (" -> %s" % self.returnType) or ""
)
......@@ -370,11 +351,10 @@ class PyQtMethod(object):
return wrapper
# Cache on-the-fly-created classes for better speed
pyqt_classes = {}
def create_pyqt_class(metaobject):
class_name = str(metaobject.className())
cls = pyqt_classes.get(class_name)
......@@ -390,13 +370,13 @@ def create_pyqt_class(metaobject):
properties[prop_name] = attrs[prop_name] = property(prop.get, doc=prop.__doc__)
else:
properties[prop_name] = attrs[prop_name] = property(
prop.get, prop.set, doc=prop.__doc__)
prop.get, prop.set, doc=prop.__doc__)
methods = attrs["__methods__"] = {}
signals = attrs["__signals__"] = {}
for i in range(metaobject.methodCount()):
meta_method = metaobject.method(i)
if meta_method.methodType() != QMetaMethod.Signal :
if meta_method.methodType() != QMetaMethod.Signal:
method = PyQtMethod(meta_method)
method_name = method.name
if method_name in attrs:
......@@ -406,7 +386,7 @@ def create_pyqt_class(metaobject):
instance_method = method.instancemethod()
instance_method.__doc__ = method.__doc__
methods[method_name] = attrs[method_name] = instance_method
else :
else:
method_name = meta_method.name()
signal_attrs = []
properties[bytes(method_name).decode('ascii')] = pyqtSignal(meta_method.parameterTypes())
......@@ -417,7 +397,6 @@ def create_pyqt_class(metaobject):
return cls
def create_pyqt_object(obj):
"""
Wrap a QObject and make all slots and properties dynamically available.
......@@ -431,8 +410,3 @@ def create_pyqt_object(obj):
"""
cls = create_pyqt_class(obj.metaObject())
return cls(obj)
# -*- coding: utf-8 -*-
"""
This module will be a collection of functions to hook into the GUI of Scribus.
This module will be a collection of functions to hook into the GUI of Scribus.
Currently it only provides functions to add items to a menubar.
Support for the toolbar, statusbar and dockarea have still to be implemented.
......@@ -13,37 +13,34 @@ import mikro
class MenuHooks(object):
"""
This class lets extension-scripts hook into the main menu of Scribus.
This class lets extension-scripts hook into the main menu of Scribus.
"""
def __init__(self, window=None):
self.window = window or Scripter.dialogs.mainWindow.qt
self.menubar = self.window.menuBar()
self.menus = []
def createMenu(self, title):
m = QMenu(title)
self.menus.append(m)
self.menubar.addMenu(m)
return m
def iter_menus(self):
for action in self.menubar.actions():
menu = action.menu()
if menu:
yield menu
def iter_inner_menus(self, menu):
for action in menu.actions():
menu = action.menu()
if menu:
yield menu
def findMenu(self, title):
"""
find a menu with a given title
......@@ -54,7 +51,7 @@ class MenuHooks(object):
@return: None if no menu was found, else the menu with title
"""
# See also http://pyqt.sourceforge.net/Docs/PyQt5/i18n.html#differences-between-pyqt5-and-qt
title = QApplication.translate(mikro.classname(self.window), title)
title = QApplication.translate(mikro.classname(self.window), title)
for menu in self.iter_menus():
if menu.title() == title:
return menu
......@@ -62,13 +59,11 @@ class MenuHooks(object):
if innerMenu.title() == title:
return innerMenu
def actionForMenu(self, menu):
for action in self.menubar.actions():
if action.menu() == menu:
return action
def insertMenuBefore(self, before_menu, new_menu):
"""
Insert a menu after another menu in the menubar
......@@ -86,26 +81,23 @@ class MenuHooks(object):
new_action = self.menubar.insertMenu(before_action, new_menu)
return new_action
def menuAfter(self, menu):
# This method is needed for insertMenuAfter because
# QMenuBar.insertMenu can only insert before another menu
# QMenuBar.insertMenu can only insert before another menu
previous = None
for m in self.iter_menus():
if previous and previous == menu:
return m
previous = m
def appendMenu(self, menu):
"""
Probably not that usefull
Probably not that usefull
because it will add a menu after the help menu
"""
action = self.menubar.addMenu(menu)
return action
def insertMenuAfter(self, after_menu, new_menu):
"""
Insert a menu before another menu in the menubar
......@@ -118,20 +110,18 @@ class MenuHooks(object):
else:
return self.appendMenu(new_menu)
def appendItem(self, menu, item, *extra_args):
if isinstance(menu, basestring):
title = menu
menu = self.findMenu(title)
if not menu:
raise ValueError("Menu %r not found" % title)
if isinstance(item, QMenu):
if isinstance(item, QMenu):
action = menu.addMenu(item)
else:
action = menu.addAction(item, *extra_args)
return action
def appendSeparator(self, menu):
if isinstance(menu, basestring):
menu = self.findMenu(menu)
......
......@@ -36,6 +36,7 @@ from .api import *
# initialization related stuff
#
def pykritaEventHandler(event):
def _decorator(func):
setattr(pykrita, event, func)
......@@ -96,6 +97,7 @@ def unload(func):
'''
plugin = sys._getframe(1).f_globals['__name__']
qDebug('@unload: {}/{}'.format(plugin, func.__name__))
def _module_cleaner():
qDebug('@unload/cleaner: {}/{}'.format(plugin, func.__name__))
if plugin in init.functions:
......@@ -105,5 +107,3 @@ def unload(func):
func()
return _registerCallback(plugin, unload, _module_cleaner)
......@@ -3,11 +3,12 @@ from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyKrita.krita import *
class DockWidgetFactory(DockWidgetFactoryBase):
def __init__(self, _id, _dockPosition, _klass):
super().__init__(_id, _dockPosition)
self.klass = _klass
def __init__(self, _id, _dockPosition, _klass):
super().__init__(_id, _dockPosition)
self.klass = _klass
def createDockWidget(self):
return self.klass()
def createDockWidget(self):
return self.klass()
......@@ -16,7 +16,6 @@ from PyQt5.QtWidgets import QApplication, QDialog
from excepthook_ui import Ui_ExceptHookDialog
def on_error(exc_type, exc_obj, exc_tb):
"""
This is the callback function for sys.excepthook
......@@ -26,13 +25,12 @@ def on_error(exc_type, exc_obj, exc_tb):
dlg.exec_()
def show_current_error(title=None):
"""
Call this function to show the current error.
It can be used inside an except-block.
"""
dlg = ExceptHookDialog(sys.exc_type, sys.exc_value, sys.exc_traceback, title)
dlg = ExceptHookDialog(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], title)
dlg.show()
dlg.exec_()
......@@ -42,7 +40,6 @@ def install():
sys.excepthook = on_error
def uninstall():
"removes the error handler"
sys.excepthook = sys.__excepthook__
......@@ -52,7 +49,6 @@ atexit.register(uninstall)
class ExceptHookDialog(QDialog):
def __init__(self, exc_type, exc_obj, exc_tb, title=None):
QDialog.__init__(self)
self.ui = Ui_ExceptHookDialog()
......@@ -63,7 +59,7 @@ class ExceptHookDialog(QDialog):
self.ui.exceptionLabel.setText(msg)
html = cgitb.text((exc_type, exc_obj, exc_tb))
self.ui.tracebackBrowser.setText(html)
self.resize(650, 350) # give enough space to see the backtrace better
self.resize(650, 350) # give enough space to see the backtrace better
@pyqtSlot()
def on_closeButton_clicked(self):
......
......@@ -8,7 +8,9 @@
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_ExceptHookDialog(object):
def setupUi(self, ExceptHookDialog):
ExceptHookDialog.setObjectName("ExceptHookDialog")
ExceptHookDialog.resize(542, 290)
......@@ -45,4 +47,3 @@ class Ui_ExceptHookDialog(object):
self.label.setText(_translate("ExceptHookDialog", "An exception occurred while running the script."))
self.exceptionLabel.setText(_translate("ExceptHookDialog", "Exception"))
self.closeButton.setText(_translate("ExceptHookDialog", "&Close"))
......@@ -9,6 +9,5 @@ def launch(parent=None):
if not editor_main_window:
from sceditor.mainwindow import EditorMainWindow
editor_main_window = EditorMainWindow(parent)
editor_main_window.resize(640,480)
editor_main_window.resize(640, 480)
editor_main_window.show()
......@@ -5,11 +5,10 @@ from PyQt5.QtWidgets import (qApp, QListWidget, QListWidgetItem, QTextBrowser,
class PopupWidget(QWidget):
def __init__(self, textedit):
flags = Qt.ToolTip
flags = Qt.Window | Qt.FramelessWindowHint | \
Qt.CustomizeWindowHint | Qt.X11BypassWindowManagerHint
Qt.CustomizeWindowHint | Qt.X11BypassWindowManagerHint
QWidget.__init__(self, None, flags)
self.textedit = textedit
self.vlayout = QVBoxLayout(self)
......@@ -19,7 +18,6 @@ class PopupWidget(QWidget):
self.hide()
self.active = False
def show(self, timeout=0, above=False):
self.cursor_start_col = self.textedit.textCursor().columnNumber()
desktop = qApp.desktop()
......@@ -48,26 +46,18 @@ class PopupWidget(QWidget):
if timeout:
QTimer.singleShot(timeout * 1000, self.hide)
def hide(self):
self.active = False
QWidget.hide(self)
class CallTip(PopupWidget):
def init_popup(self):
self.browser = QTextBrowser(self)
self.layout().addWidget(self.browser)
class AutoCompleteItem(QListWidgetItem):
def __init__(self, item):
......@@ -78,21 +68,17 @@ class AutoCompleteItem(QListWidgetItem):
self.kind = item.kind
class AutoComplete(PopupWidget):
def init_popup(self):
self.list = QListWidget(self)
self.list.itemClicked.connect(self.insertItem)
self.layout().addWidget(self.list)
self.items = []
def insertItem(self, item):
self.insert()
def insert(self):
completition = self.items[self.list.currentRow()].value
cursor = self.textedit.textCursor()
......@@ -100,18 +86,17 @@ class AutoComplete(PopupWidget):
line = unicode(cursor.block().text())
i = self.cursor_start_col
while i > 0:
#print(`line[i:col]`)
# print(`line[i:col]`)
if completition.startswith(line[i:col]):
#print("break")
# print("break")
break
i -= 1
#print(col,i)
cursor.insertText(completition[col-i:])
# print(col,i)
cursor.insertText(completition[col - i:])
self.hide()
def setItems(self, proposals):
proposals = sorted(proposals, cmp=lambda p1,p2:cmp(p1.name,p2.name))
proposals = sorted(proposals, cmp=lambda p1, p2: cmp(p1.name, p2.name))
del self.items[:]