pyqtgraph, .exporters, and .opengl now use static imports

This commit is contained in:
Luke Campagnola 2013-11-22 19:52:40 -05:00
parent 63f3b0ab6e
commit b50b94908f
9 changed files with 163 additions and 135 deletions

View File

@ -130,56 +130,119 @@ if __version__ is None and not hasattr(sys, 'frozen') and sys.version_info[0] ==
## Import almost everything to make it available from a single namespace ## Import almost everything to make it available from a single namespace
## don't import the more complex systems--canvas, parametertree, flowchart, dockarea ## don't import the more complex systems--canvas, parametertree, flowchart, dockarea
## these must be imported separately. ## these must be imported separately.
from . import frozenSupport #from . import frozenSupport
def importModules(path, globals, locals, excludes=()): #def importModules(path, globals, locals, excludes=()):
"""Import all modules residing within *path*, return a dict of name: module pairs. #"""Import all modules residing within *path*, return a dict of name: module pairs.
Note that *path* MUST be relative to the module doing the import. #Note that *path* MUST be relative to the module doing the import.
""" #"""
d = os.path.join(os.path.split(globals['__file__'])[0], path) #d = os.path.join(os.path.split(globals['__file__'])[0], path)
files = set() #files = set()
for f in frozenSupport.listdir(d): #for f in frozenSupport.listdir(d):
if frozenSupport.isdir(os.path.join(d, f)) and f not in ['__pycache__', 'tests']: #if frozenSupport.isdir(os.path.join(d, f)) and f not in ['__pycache__', 'tests']:
files.add(f) #files.add(f)
elif f[-3:] == '.py' and f != '__init__.py': #elif f[-3:] == '.py' and f != '__init__.py':
files.add(f[:-3]) #files.add(f[:-3])
elif f[-4:] == '.pyc' and f != '__init__.pyc': #elif f[-4:] == '.pyc' and f != '__init__.pyc':
files.add(f[:-4]) #files.add(f[:-4])
mods = {} #mods = {}
path = path.replace(os.sep, '.') #path = path.replace(os.sep, '.')
for modName in files: #for modName in files:
if modName in excludes: #if modName in excludes:
continue #continue
try: #try:
if len(path) > 0: #if len(path) > 0:
modName = path + '.' + modName #modName = path + '.' + modName
#mod = __import__(modName, globals, locals, fromlist=['*']) #print( "from .%s import * " % modName)
mod = __import__(modName, globals, locals, ['*'], 1) #mod = __import__(modName, globals, locals, ['*'], 1)
mods[modName] = mod #mods[modName] = mod
except: #except:
import traceback #import traceback
traceback.print_stack() #traceback.print_stack()
sys.excepthook(*sys.exc_info()) #sys.excepthook(*sys.exc_info())
print("[Error importing module: %s]" % modName) #print("[Error importing module: %s]" % modName)
return mods #return mods
def importAll(path, globals, locals, excludes=()): #def importAll(path, globals, locals, excludes=()):
"""Given a list of modules, import all names from each module into the global namespace.""" #"""Given a list of modules, import all names from each module into the global namespace."""
mods = importModules(path, globals, locals, excludes) #mods = importModules(path, globals, locals, excludes)
for mod in mods.values(): #for mod in mods.values():
if hasattr(mod, '__all__'): #if hasattr(mod, '__all__'):
names = mod.__all__ #names = mod.__all__
else: #else:
names = [n for n in dir(mod) if n[0] != '_'] #names = [n for n in dir(mod) if n[0] != '_']
for k in names: #for k in names:
if hasattr(mod, k): #if hasattr(mod, k):
globals[k] = getattr(mod, k) #globals[k] = getattr(mod, k)
importAll('graphicsItems', globals(), locals()) # Dynamic imports are disabled. This causes too many problems.
importAll('widgets', globals(), locals(), #importAll('graphicsItems', globals(), locals())
excludes=['MatplotlibWidget', 'RawImageWidget', 'RemoteGraphicsView']) #importAll('widgets', globals(), locals(),
#excludes=['MatplotlibWidget', 'RawImageWidget', 'RemoteGraphicsView'])
from .graphicsItems.VTickGroup import *
from .graphicsItems.GraphicsWidget import *
from .graphicsItems.ScaleBar import *
from .graphicsItems.PlotDataItem import *
from .graphicsItems.GraphItem import *
from .graphicsItems.TextItem import *
from .graphicsItems.GraphicsLayout import *
from .graphicsItems.UIGraphicsItem import *
from .graphicsItems.GraphicsObject import *
from .graphicsItems.PlotItem import *
from .graphicsItems.ROI import *
from .graphicsItems.InfiniteLine import *
from .graphicsItems.HistogramLUTItem import *
from .graphicsItems.GridItem import *
from .graphicsItems.GradientLegend import *
from .graphicsItems.GraphicsItem import *
from .graphicsItems.BarGraphItem import *
from .graphicsItems.ViewBox import *
from .graphicsItems.ArrowItem import *
from .graphicsItems.ImageItem import *
from .graphicsItems.AxisItem import *
from .graphicsItems.LabelItem import *
from .graphicsItems.CurvePoint import *
from .graphicsItems.GraphicsWidgetAnchor import *
from .graphicsItems.PlotCurveItem import *
from .graphicsItems.ButtonItem import *
from .graphicsItems.GradientEditorItem import *
from .graphicsItems.MultiPlotItem import *
from .graphicsItems.ErrorBarItem import *
from .graphicsItems.IsocurveItem import *
from .graphicsItems.LinearRegionItem import *
from .graphicsItems.FillBetweenItem import *
from .graphicsItems.LegendItem import *
from .graphicsItems.ScatterPlotItem import *
from .graphicsItems.ItemGroup import *
from .widgets.MultiPlotWidget import *
from .widgets.ScatterPlotWidget import *
from .widgets.ColorMapWidget import *
from .widgets.FileDialog import *
from .widgets.ValueLabel import *
from .widgets.HistogramLUTWidget import *
from .widgets.CheckTable import *
from .widgets.BusyCursor import *
from .widgets.PlotWidget import *
from .widgets.ComboBox import *
from .widgets.GradientWidget import *
from .widgets.DataFilterWidget import *
from .widgets.SpinBox import *
from .widgets.JoystickButton import *
from .widgets.GraphicsLayoutWidget import *
from .widgets.TreeWidget import *
from .widgets.PathButton import *
from .widgets.VerticalLabel import *
from .widgets.FeedbackButton import *
from .widgets.ColorButton import *
from .widgets.DataTreeWidget import *
from .widgets.GraphicsView import *
from .widgets.LayoutWidget import *
from .widgets.TableWidget import *
from .widgets.ProgressDialog import *
from .imageview import * from .imageview import *
from .WidgetGroup import * from .WidgetGroup import *
@ -194,6 +257,7 @@ from .SignalProxy import *
from .colormap import * from .colormap import *
from .ptime import time from .ptime import time
############################################################## ##############################################################
## PyQt and PySide both are prone to crashing on exit. ## PyQt and PySide both are prone to crashing on exit.
## There are two general approaches to dealing with this: ## There are two general approaches to dealing with this:

View File

@ -60,6 +60,6 @@ class CSVExporter(Exporter):
fd.write('\n') fd.write('\n')
fd.close() fd.close()
CSVExporter.register()

View File

@ -11,6 +11,14 @@ class Exporter(object):
Abstract class used for exporting graphics to file / printer / whatever. Abstract class used for exporting graphics to file / printer / whatever.
""" """
allowCopy = False # subclasses set this to True if they can use the copy buffer allowCopy = False # subclasses set this to True if they can use the copy buffer
Exporters = []
@classmethod
def register(cls):
"""
Used to register Exporter classes to appear in the export dialog.
"""
Exporter.Exporters.append(cls)
def __init__(self, item): def __init__(self, item):
""" """
@ -20,9 +28,6 @@ class Exporter(object):
object.__init__(self) object.__init__(self)
self.item = item self.item = item
#def item(self):
#return self.item
def parameters(self): def parameters(self):
"""Return the parameters used to configure this exporter.""" """Return the parameters used to configure this exporter."""
raise Exception("Abstract method must be overridden in subclass.") raise Exception("Abstract method must be overridden in subclass.")
@ -131,45 +136,4 @@ class Exporter(object):
return preItems + rootItem + postItems return preItems + rootItem + postItems
def render(self, painter, targetRect, sourceRect, item=None): def render(self, painter, targetRect, sourceRect, item=None):
#if item is None:
#item = self.item
#preItems = []
#postItems = []
#if isinstance(item, QtGui.QGraphicsScene):
#childs = [i for i in item.items() if i.parentItem() is None]
#rootItem = []
#else:
#childs = item.childItems()
#rootItem = [item]
#childs.sort(lambda a,b: cmp(a.zValue(), b.zValue()))
#while len(childs) > 0:
#ch = childs.pop(0)
#if int(ch.flags() & ch.ItemStacksBehindParent) > 0 or (ch.zValue() < 0 and int(ch.flags() & ch.ItemNegativeZStacksBehindParent) > 0):
#preItems.extend(tree)
#else:
#postItems.extend(tree)
#for ch in preItems:
#self.render(painter, sourceRect, targetRect, item=ch)
### paint root here
#for ch in postItems:
#self.render(painter, sourceRect, targetRect, item=ch)
self.getScene().render(painter, QtCore.QRectF(targetRect), QtCore.QRectF(sourceRect)) self.getScene().render(painter, QtCore.QRectF(targetRect), QtCore.QRectF(sourceRect))
#def writePs(self, fileName=None, item=None):
#if fileName is None:
#self.fileSaveDialog(self.writeSvg, filter="PostScript (*.ps)")
#return
#if item is None:
#item = self
#printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution)
#printer.setOutputFileName(fileName)
#painter = QtGui.QPainter(printer)
#self.render(painter)
#painter.end()
#def writeToPrinter(self):
#pass

View File

@ -98,4 +98,5 @@ class ImageExporter(Exporter):
else: else:
self.png.save(fileName) self.png.save(fileName)
ImageExporter.register()

View File

@ -57,6 +57,7 @@ class MatplotlibExporter(Exporter):
else: else:
raise Exception("Matplotlib export currently only works with plot items") raise Exception("Matplotlib export currently only works with plot items")
MatplotlibExporter.register()
class MatplotlibWindow(QtGui.QMainWindow): class MatplotlibWindow(QtGui.QMainWindow):
@ -72,3 +73,5 @@ class MatplotlibWindow(QtGui.QMainWindow):
def closeEvent(self, ev): def closeEvent(self, ev):
MatplotlibExporter.windows.remove(self) MatplotlibExporter.windows.remove(self)

View File

@ -63,3 +63,6 @@ class PrintExporter(Exporter):
finally: finally:
self.setExportMode(False) self.setExportMode(False)
painter.end() painter.end()
#PrintExporter.register()

View File

@ -404,6 +404,10 @@ def correctCoordinates(node, item):
if removeTransform: if removeTransform:
grp.removeAttribute('transform') grp.removeAttribute('transform')
SVGExporter.register()
def itemTransform(item, root): def itemTransform(item, root):
## Return the transformation mapping item to root ## Return the transformation mapping item to root
## (actually to parent coordinate system of root) ## (actually to parent coordinate system of root)

View File

@ -1,27 +1,24 @@
Exporters = [] #Exporters = []
from pyqtgraph import importModules #from pyqtgraph import importModules
#from .. import frozenSupport #import os
import os #d = os.path.split(__file__)[0]
d = os.path.split(__file__)[0] #for mod in importModules('', globals(), locals(), excludes=['Exporter']).values():
#files = [] #if hasattr(mod, '__all__'):
#for f in frozenSupport.listdir(d): #names = mod.__all__
#if frozenSupport.isdir(os.path.join(d, f)) and f != '__pycache__': #else:
#files.append(f) #names = [n for n in dir(mod) if n[0] != '_']
#elif f[-3:] == '.py' and f not in ['__init__.py', 'Exporter.py']: #for k in names:
#files.append(f[:-3]) #if hasattr(mod, k):
#Exporters.append(getattr(mod, k))
#for modName in files:
#mod = __import__(modName, globals(), locals(), fromlist=['*']) import Exporter
for mod in importModules('', globals(), locals(), excludes=['Exporter']).values(): from .ImageExporter import *
if hasattr(mod, '__all__'): from .SVGExporter import *
names = mod.__all__ from .Matplotlib import *
else: from .CSVExporter import *
names = [n for n in dir(mod) if n[0] != '_'] from .PrintExporter import *
for k in names:
if hasattr(mod, k):
Exporters.append(getattr(mod, k))
def listExporters(): def listExporters():
return Exporters[:] return Exporter.Exporter.Exporters[:]

View File

@ -1,28 +1,20 @@
from .GLViewWidget import GLViewWidget from .GLViewWidget import GLViewWidget
from pyqtgraph import importAll ## dynamic imports cause too many problems.
#import os #from pyqtgraph import importAll
#def importAll(path): #importAll('items', globals(), locals())
#d = os.path.join(os.path.split(__file__)[0], path)
#files = [] from .items.GLGridItem import *
#for f in os.listdir(d): from .items.GLBarGraphItem import *
#if os.path.isdir(os.path.join(d, f)) and f != '__pycache__': from .items.GLScatterPlotItem import *
#files.append(f) from .items.GLMeshItem import *
#elif f[-3:] == '.py' and f != '__init__.py': from .items.GLLinePlotItem import *
#files.append(f[:-3]) from .items.GLAxisItem import *
from .items.GLImageItem import *
#for modName in files: from .items.GLSurfacePlotItem import *
#mod = __import__(path+"."+modName, globals(), locals(), fromlist=['*']) from .items.GLBoxItem import *
#if hasattr(mod, '__all__'): from .items.GLVolumeItem import *
#names = mod.__all__
#else:
#names = [n for n in dir(mod) if n[0] != '_']
#for k in names:
#if hasattr(mod, k):
#globals()[k] = getattr(mod, k)
importAll('items', globals(), locals())
\
from .MeshData import MeshData from .MeshData import MeshData
## for backward compatibility: ## for backward compatibility:
#MeshData.MeshData = MeshData ## breaks autodoc. #MeshData.MeshData = MeshData ## breaks autodoc.