Commit fc9b3dee authored by Luke Campagnola's avatar Luke Campagnola
Browse files

Started Python3 compatibility changes

parent 13b201be
from pyqtgraph.Qt import QtCore, QtGui, QtOpenGL, QtSvg
from pyqtgraph.Qt import QtCore, QtGui
#try:
#from PyQt4 import QtOpenGL
#HAVE_OPENGL = True
#except ImportError:
#HAVE_OPENGL = False
import weakref
from pyqtgraph.Point import Point
import pyqtgraph.functions as fn
import pyqtgraph.ptime as ptime
from mouseEvents import *
from .mouseEvents import *
import pyqtgraph.debug as debug
import exportDialog
from . import exportDialog
try:
import sip
......@@ -216,7 +222,7 @@ class GraphicsScene(QtGui.QGraphicsScene):
items = self.itemsNearEvent(event)
self.sigMouseHover.emit(items)
prevItems = self.hoverItems.keys()
prevItems = list(self.hoverItems.keys())
for item in items:
if hasattr(item, 'hoverEvent'):
......@@ -352,7 +358,7 @@ class GraphicsScene(QtGui.QGraphicsScene):
items = QtGui.QGraphicsScene.items(self, *args)
## PyQt bug: items() returns a list of QGraphicsItem instances. If the item is subclassed from QGraphicsObject,
## then the object returned will be different than the actual item that was originally added to the scene
items2 = map(self.translateGraphicsItem, items)
items2 = list(map(self.translateGraphicsItem, items))
#if HAVE_SIP and isinstance(self, sip.wrapper):
#items2 = []
#for i in items:
......@@ -374,7 +380,7 @@ class GraphicsScene(QtGui.QGraphicsScene):
#i2 = GraphicsScene._addressCache.get(addr, i)
##print i, "==>", i2
#items2.append(i2)
items2 = map(self.translateGraphicsItem, items)
items2 = list(map(self.translateGraphicsItem, items))
#print 'items:', items
return items2
......@@ -430,7 +436,7 @@ class GraphicsScene(QtGui.QGraphicsScene):
return 0
return item.zValue() + absZValue(item.parentItem())
items2.sort(lambda a,b: cmp(absZValue(b), absZValue(a)))
sortList(items2, lambda a,b: cmp(absZValue(b), absZValue(a)))
return items2
......@@ -543,7 +549,7 @@ class GraphicsScene(QtGui.QGraphicsScene):
@staticmethod
def translateGraphicsItems(items):
return map(GraphicsScene.translateGraphicsItem, items)
return list(map(GraphicsScene.translateGraphicsItem, items))
from GraphicsScene import *
from .GraphicsScene import *
import exportDialogTemplate
from . import exportDialogTemplate
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
import pyqtgraph.exporters as exporters
......
......@@ -5,7 +5,7 @@ Copyright 2010 Luke Campagnola
Distributed under MIT/X11 license. See license.txt for more infomation.
"""
from Qt import QtCore
from .Qt import QtCore
import numpy as np
def clip(x, mn, mx):
......
## Do all Qt imports from here to allow easier PyQt / PySide compatibility
#from PySide import QtGui, QtCore, QtOpenGL, QtSvg
from PyQt4 import QtGui, QtCore, QtOpenGL, QtSvg
from PyQt4 import QtGui, QtCore
try:
from PyQt4 import QtSvg
except ImportError:
pass
try:
from PyQt4 import QtOpenGL
except ImportError:
pass
if not hasattr(QtCore, 'Signal'):
QtCore.Signal = QtCore.pyqtSignal
# -*- coding: utf-8 -*-
from Qt import QtCore
from ptime import time
import ThreadsafeTimer
from .Qt import QtCore
from .ptime import time
from . import ThreadsafeTimer
__all__ = ['SignalProxy']
......@@ -99,7 +99,7 @@ class SignalProxy(QtCore.QObject):
if __name__ == '__main__':
from Qt import QtGui
from .Qt import QtGui
app = QtGui.QApplication([])
win = QtGui.QMainWindow()
spin = QtGui.QSpinBox()
......@@ -107,9 +107,9 @@ if __name__ == '__main__':
win.show()
def fn(*args):
print "Raw signal:", args
print("Raw signal:", args)
def fn2(*args):
print "Delayed signal:", args
print("Delayed signal:", args)
spin.valueChanged.connect(fn)
......
# -*- coding: utf-8 -*-
from Qt import QtCore, QtGui
from Point import Point
from .Qt import QtCore, QtGui
from .Point import Point
import numpy as np
class Transform(QtGui.QTransform):
......@@ -141,9 +141,9 @@ class Transform(QtGui.QTransform):
return np.array([[self.m11(), self.m12(), self.m13()],[self.m21(), self.m22(), self.m23()],[self.m31(), self.m32(), self.m33()]])
if __name__ == '__main__':
import widgets
from . import widgets
import GraphicsView
from functions import *
from .functions import *
app = QtGui.QApplication([])
win = QtGui.QMainWindow()
win.show()
......@@ -189,23 +189,23 @@ if __name__ == '__main__':
tr3 = QtGui.QTransform()
tr3.translate(20, 0)
tr3.rotate(45)
print "QTransform -> Transform:", Transform(tr3)
print("QTransform -> Transform:", Transform(tr3))
print "tr1:", tr1
print("tr1:", tr1)
tr2.translate(20, 0)
tr2.rotate(45)
print "tr2:", tr2
print("tr2:", tr2)
dt = tr2/tr1
print "tr2 / tr1 = ", dt
print("tr2 / tr1 = ", dt)
print "tr2 * tr1 = ", tr2*tr1
print("tr2 * tr1 = ", tr2*tr1)
tr4 = Transform()
tr4.scale(-1, 1)
tr4.rotate(30)
print "tr1 * tr4 = ", tr1*tr4
print("tr1 * tr4 = ", tr1*tr4)
w1 = widgets.TestROI((19,19), (22, 22), invertible=True)
#w2 = widgets.TestROI((0,0), (150, 150))
......
......@@ -8,7 +8,7 @@ This class addresses the problem of having to save and restore the state
of a large group of widgets.
"""
from Qt import QtCore, QtGui
from .Qt import QtCore, QtGui
import weakref, inspect
......@@ -24,7 +24,7 @@ def restoreSplitter(w, s):
elif type(s) is str:
w.restoreState(QtCore.QByteArray.fromPercentEncoding(s))
else:
print "Can't configure QSplitter using object of type", type(s)
print("Can't configure QSplitter using object of type", type(s))
if w.count() > 0: ## make sure at least one item is not collapsed
for i in w.sizes():
if i > 0:
......@@ -44,7 +44,7 @@ def comboState(w):
except AttributeError:
pass
if data is None:
return unicode(w.itemText(ind))
return asUnicode(w.itemText(ind))
else:
return data
......@@ -133,7 +133,7 @@ class WidgetGroup(QtCore.QObject):
for w in widgetList:
self.addWidget(*w)
elif isinstance(widgetList, dict):
for name, w in widgetList.iteritems():
for name, w in widgetList.items():
self.addWidget(w, name)
elif widgetList is None:
return
......@@ -258,7 +258,7 @@ class WidgetGroup(QtCore.QObject):
## if the getter function provided in the interface is a bound method,
## then just call the method directly. Otherwise, pass in the widget as the first arg
## to the function.
if inspect.ismethod(getFunc) and getFunc.im_self is not None:
if inspect.ismethod(getFunc) and getFunc.__self__ is not None:
val = getFunc()
else:
val = getFunc(w)
......@@ -284,7 +284,7 @@ class WidgetGroup(QtCore.QObject):
## if the setter function provided in the interface is a bound method,
## then just call the method directly. Otherwise, pass in the widget as the first arg
## to the function.
if inspect.ismethod(setFunc) and setFunc.im_self is not None:
if inspect.ismethod(setFunc) and setFunc.__self__ is not None:
setFunc(v)
else:
setFunc(w, v)
......
......@@ -3,21 +3,25 @@
## 'Qt' is a local module; it is intended mainly to cover up the differences
## between PyQt4 and PySide.
from Qt import QtGui
from .Qt import QtGui
## not really safe.
## not really safe--If we accidentally create another QApplication, the process hangs (and it is very difficult to trace the cause)
#if QtGui.QApplication.instance() is None:
#app = QtGui.QApplication([])
## in general openGL is poorly supported in Qt.
## we only enable it where the performance benefit is critical.
## Note this only applies to 2D graphics; 3D graphics always use OpenGL.
import sys
## check python version
if sys.version_info[0] != 2 or sys.version_info[1] != 7:
if sys.version_info[0] < 2 or (sys.version_info[0] == 2 and sys.version_info[1] != 7):
raise Exception("Pyqtgraph requires Python version 2.7 (this is %d.%d)" % (sys.version_info[0], sys.version_info[1]))
## helpers for 2/3 compatibility
from . import python2_3
## in general openGL is poorly supported in Qt.
## we only enable it where the performance benefit is critical.
## Note this only applies to 2D graphics; 3D graphics always use OpenGL.
if 'linux' in sys.platform: ## linux has numerous bugs in opengl implementation
useOpenGL = False
elif 'darwin' in sys.platform: ## openGL greatly speeds up display on mac
......@@ -27,8 +31,11 @@ else:
CONFIG_OPTIONS = {
'useOpenGL': useOpenGL, ## by default, this is platform-dependent (see widgets/GraphicsView). Set to True or False to explicitly enable/disable opengl.
'leftButtonPan': True ## if false, left button drags a rubber band for zooming in viewbox
}
'leftButtonPan': True, ## if false, left button drags a rubber band for zooming in viewbox
'foregroundColor': (200,200,200),
'backgroundColor': (0,0,0),
'antialias': False,
}
def setConfigOption(opt, value):
CONFIG_OPTIONS[opt] = value
......@@ -47,13 +54,15 @@ def renamePyc(startDir):
printed = False
startDir = os.path.abspath(startDir)
for path, dirs, files in os.walk(startDir):
if '__pycache__' in path:
continue
for f in files:
fileName = os.path.join(path, f)
base, ext = os.path.splitext(fileName)
py = base + ".py"
if ext == '.pyc' and not os.path.isfile(py):
if not printed:
print "NOTE: Renaming orphaned .pyc files:"
print("NOTE: Renaming orphaned .pyc files:")
printed = True
n = 1
while True:
......@@ -61,8 +70,8 @@ def renamePyc(startDir):
if not os.path.exists(name2):
break
n += 1
print " " + fileName + " ==>"
print " " + name2
print(" " + fileName + " ==>")
print(" " + name2)
os.rename(fileName, name2)
import os
......@@ -78,7 +87,7 @@ def importAll(path, excludes=()):
d = os.path.join(os.path.split(__file__)[0], path)
files = []
for f in os.listdir(d):
if os.path.isdir(os.path.join(d, f)):
if os.path.isdir(os.path.join(d, f)) and f != '__pycache__':
files.append(f)
elif f[-3:] == '.py' and f != '__init__.py':
files.append(f[:-3])
......@@ -98,14 +107,14 @@ def importAll(path, excludes=()):
importAll('graphicsItems')
importAll('widgets', excludes=['MatplotlibWidget'])
from imageview import *
from WidgetGroup import *
from Point import Point
from Transform import Transform
from functions import *
from graphicsWindows import *
from SignalProxy import *
from ptime import time
from .imageview import *
from .WidgetGroup import *
from .Point import Point
from .Transform import Transform
from .functions import *
from .graphicsWindows import *
from .SignalProxy import *
from .ptime import time
......
......@@ -5,7 +5,7 @@ if __name__ == '__main__':
sys.path = [os.path.dirname(md), os.path.join(md, '..', '..', '..')] + sys.path
#print md
from CanvasTemplate import *
from .CanvasTemplate import *
#from pyqtgraph.GraphicsView import GraphicsView
#import pyqtgraph.graphicsItems as graphicsItems
#from pyqtgraph.PlotWidget import PlotWidget
......@@ -18,9 +18,9 @@ import numpy as np
from pyqtgraph import debug
#import pyqtgraph as pg
import weakref
from CanvasManager import CanvasManager
from .CanvasManager import CanvasManager
#import items
from CanvasItem import CanvasItem, GroupCanvasItem
from .CanvasItem import CanvasItem, GroupCanvasItem
class Canvas(QtGui.QWidget):
......@@ -154,7 +154,7 @@ class Canvas(QtGui.QWidget):
if parent is None:
tree = li.treeWidget()
if tree is None:
print "Skipping item", i, i.name
print("Skipping item", i, i.name)
continue
tree.removeTopLevelItem(li)
else:
......@@ -365,7 +365,7 @@ class Canvas(QtGui.QWidget):
parent = parent.listItem
## set Z value above all other siblings if none was specified
siblings = [parent.child(i).canvasItem for i in xrange(parent.childCount())]
siblings = [parent.child(i).canvasItem for i in range(parent.childCount())]
z = citem.zValue()
if z is None:
zvals = [i.zValue() for i in siblings]
......@@ -462,7 +462,7 @@ class Canvas(QtGui.QWidget):
item.canvasItem.setParentItem(self.view.childGroup)
else:
item.canvasItem.setParentItem(parent.canvasItem)
siblings = [parent.child(i).canvasItem for i in xrange(parent.childCount())]
siblings = [parent.child(i).canvasItem for i in range(parent.childCount())]
zvals = [i.zValue() for i in siblings]
zvals.sort(reverse=True)
......
......@@ -2,7 +2,7 @@
from pyqtgraph.Qt import QtGui, QtCore, QtSvg
from pyqtgraph.graphicsItems.ROI import ROI
import pyqtgraph as pg
import TransformGuiTemplate
from . import TransformGuiTemplate
from pyqtgraph import debug
class SelectBox(ROI):
......
......@@ -36,7 +36,7 @@ class CanvasManager(QtCore.QObject):
self.sigCanvasListChanged.emit()
def listCanvases(self):
return self.canvases.keys()
return list(self.canvases.keys())
def getCanvas(self, name):
return self.canvases[name]
......
......@@ -96,5 +96,5 @@ class Ui_Form(object):
self.reflectSelectionBtn.setText(QtGui.QApplication.translate("Form", "MirrorXY", None, QtGui.QApplication.UnicodeUTF8))
from pyqtgraph.widgets.GraphicsView import GraphicsView
from CanvasManager import CanvasCombo
from .CanvasManager import CanvasCombo
from pyqtgraph.widgets.TreeWidget import TreeWidget
# -*- coding: utf-8 -*-
from Canvas import *
from CanvasItem import *
\ No newline at end of file
from .Canvas import *
from .CanvasItem import *
\ No newline at end of file
......@@ -12,7 +12,7 @@ as it can be converted to/from a string using repr and eval.
import re, os, sys
from collections import OrderedDict
GLOBAL_PATH = None # so not thread safe.
import units
from . import units
class ParseError(Exception):
def __init__(self, message, lineNum, line, fileName=None):
......@@ -51,7 +51,7 @@ def readConfigFile(fname):
try:
#os.chdir(newDir) ## bad.
fd = open(fname)
s = unicode(fd.read(), 'UTF-8')
s = asUnicode(fd.read(), 'UTF-8')
fd.close()
s = s.replace("\r\n", "\n")
s = s.replace("\r", "\n")
......@@ -60,7 +60,7 @@ def readConfigFile(fname):
sys.exc_info()[1].fileName = fname
raise
except:
print "Error while reading config file %s:"% fname
print("Error while reading config file %s:"% fname)
raise
#finally:
#os.chdir(cwd)
......@@ -78,10 +78,10 @@ def genString(data, indent=''):
for k in data:
sk = str(k)
if len(sk) == 0:
print data
print(data)
raise Exception('blank dict keys not allowed (see data above)')
if sk[0] == ' ' or ':' in sk:
print data
print(data)
raise Exception('dict keys must not contain ":" or start with spaces [offending key is "%s"]' % sk)
if isinstance(data[k], dict):
s += indent + sk + ':\n'
......@@ -95,7 +95,7 @@ def parseString(lines, start=0):
data = OrderedDict()
if isinstance(lines, basestring):
lines = lines.split('\n')
lines = filter(lambda l: re.search(r'\S', l) and not re.match(r'\s*#', l), lines) ## remove empty lines
lines = [l for l in lines if re.search(r'\S', l) and not re.match(r'\s*#', l)] ## remove empty lines
indent = measureIndent(lines[start])
ln = start - 1
......@@ -189,13 +189,13 @@ key2: ##comment
"""
tf.write(cf)
tf.close()
print "=== Test:==="
print("=== Test:===")
num = 1
for line in cf.split('\n'):
print "%02d %s" % (num, line)
print("%02d %s" % (num, line))
num += 1
print cf
print "============"
print(cf)
print("============")
data = readConfigFile(fn)
print data
print(data)
os.remove(fn)
\ No newline at end of file
......@@ -6,9 +6,9 @@ Distributed under MIT/X11 license. See license.txt for more infomation.
"""
import sys, traceback, time, gc, re, types, weakref, inspect, os, cProfile
import ptime
from . import ptime
from numpy import ndarray
from Qt import QtCore, QtGui
from .Qt import QtCore, QtGui
__ftraceDepth = 0
def ftrace(func):
......@@ -18,13 +18,13 @@ def ftrace(func):
def w(*args, **kargs):
global __ftraceDepth
pfx = " " * __ftraceDepth
print pfx + func.__name__ + " start"
print(pfx + func.__name__ + " start")
__ftraceDepth += 1
try:
rv = func(*args, **kargs)
finally:
__ftraceDepth -= 1
print pfx + func.__name__ + " done"
print(pfx + func.__name__ + " done")
return rv
return w
......@@ -39,20 +39,20 @@ def printExc(msg='', indent=4, prefix='|'):
"""Print an error message followed by an indented exception backtrace
(This function is intended to be called within except: blocks)"""
exc = getExc(indent, prefix + ' ')
print "[%s] %s\n" % (time.strftime("%H:%M:%S"), msg)
print " "*indent + prefix + '='*30 + '>>'
print exc
print " "*indent + prefix + '='*30 + '<<'
print("[%s] %s\n" % (time.strftime("%H:%M:%S"), msg))
print(" "*indent + prefix + '='*30 + '>>')
print(exc)
print(" "*indent + prefix + '='*30 + '<<')
def printTrace(msg='', indent=4, prefix='|'):
"""Print an error message followed by an indented stack trace"""
trace = backtrace(1)
#exc = getExc(indent, prefix + ' ')
print "[%s] %s\n" % (time.strftime("%H:%M:%S"), msg)
print " "*indent + prefix + '='*30 + '>>'
print("[%s] %s\n" % (time.strftime("%H:%M:%S"), msg))
print(" "*indent + prefix + '='*30 + '>>')
for line in trace.split('\n'):
print " "*indent + prefix + " " + line
print " "*indent + prefix + '='*30 + '<<'
print(" "*indent + prefix + " " + line)
print(" "*indent + prefix + '='*30 + '<<')
def backtrace(skip=0):
......@@ -107,12 +107,12 @@ def findRefPath(startObj, endObj, maxLen=8, restart=True, seen={}, path=None, ig
#print prefix+" LOOP", objChainString([r]+path)
continue
except:
print r
print path
print(r)
print(path)
raise
if r is startObj:
refs.append([r])
print refPathString([startObj]+path)
print(refPathString([startObj]+path))
continue
if maxLen == 0:
#print prefix+" END:", objChainString([r]+path)
......@@ -125,7 +125,7 @@ def findRefPath(startObj, endObj, maxLen=8, restart=True, seen={}, path=None, ig
if cache[0] >= maxLen:
tree = cache[1]
for p in tree:
print refPathString(p+path)
print(refPathString(p+path))
except KeyError:
pass
......@@ -147,14 +147,14 @@ def findRefPath(startObj, endObj, maxLen=8, restart=True, seen={}, path=None, ig
def objString(obj):
"""Return a short but descriptive string for any object"""
try:
if type(obj) in [int, long, float]:
if type(obj) in [int, float]:
return str(obj)
elif isinstance(obj, dict):
if len(obj) > 5:
return "<dict {%s,...}>" % (",".join(obj.keys()[:5]))
return "<dict {%s,...}>" % (",".join(list(obj.keys())[:5]))
else:
return "<dict {%s}>" % (",".join(obj.keys()))
elif isinstance(obj, basestring):
return "<dict {%s}>" % (",".join(list(obj.keys())))
elif isinstance(obj, str):
if len(obj) > 50:
return '"%s..."' % obj[:50]
else:
......@@ -261,19 +261,19 @@ def objectSize(obj, ignore=None, verbose=False, depth=0, recursive=False):
if recursive:
if type(obj) in [list, tuple]:
if verbose:
print indent+"list:"
print(indent+"list:")
for o in obj:
s = objectSize(o, ignore=ignore, verbose=verbose, depth=depth+1)
if verbose:
print indent+' +', s
print(indent+' +', s)
size += s
elif isinstance(obj, dict):
if verbose:
print indent+"list:"
print(indent+"list:")
for k in obj:
s = objectSize(obj[k], ignore=ignore, verbose=verbose, depth=depth+1)
if verbose:
print indent+' +', k, s
print(indent+' +', k, s)
size += s
#elif isinstance(obj, QtCore.QObject):
#try:
......@@ -291,7 +291,7 @@ def objectSize(obj, ignore=None, verbose=False, depth=0, recursive=False):
#if isinstance(obj, types.InstanceType):
gc.collect()
if verbose:
print indent+'attrs:'
print(indent+'attrs:')
for k in dir(obj):
if k in ['__dict__']:
continue
......@@ -311,7 +311,7 @@ def objectSize(obj, ignore=None, verbose=False, depth=0, recursive=False):
s = objectSize(o, ignore=ignore, verbose=verbose, depth=depth+1)
size += s
if verbose:
print indent + " +", k, s