def testRemoveTo(self): #canvas = vcs.init() nto = vcs.listelements("textorientation") nt = vcs.listelements("template") t = vcs.createtemplate() t.scalefont(.6) # canvas.removeobect(t) vcs.removeobject(t) nto2 = vcs.listelements("textorientation") nt2 = vcs.listelements("template") self.assertEqual(len(nto2), len(nto)) self.assertEqual(len(nt2), len(nt))
def testVCSreset1only(self): for gtype in vcs.listelements(): b0 = vcs.listelements(gtype) if gtype == 'colormap': b = vcs.createcolormap() xtra = vcs.createisofill() untouched = vcs.listelements("isofill") elif gtype == "template": b = vcs.createtemplate() elif gtype == "textcombined": b = vcs.createtextcombined() elif gtype == "textorientation": b = vcs.createtextorientation() elif gtype == "texttable": b = vcs.createtexttable() elif gtype == "fillarea": b = vcs.createfillarea() elif gtype == "projection": b = vcs.createprojection() elif gtype == "marker": b = vcs.createmarker() elif gtype == "line": b = vcs.createline() elif gtype in ["display", "font", "fontNumber", "list", "format"]: vcs.manageElements.reset() continue else: b = vcs.creategraphicsmethod(gtype) if gtype != "colormap": xtra = vcs.createcolormap() untouched = vcs.listelements("colormap") b1 = vcs.listelements(gtype) self.assertNotEqual(b0, b1) vcs.manageElements.reset(gtype) b2 = vcs.listelements(gtype) self.assertEqual(b0, b2) if gtype == "colormap": self.assertEqual(untouched, vcs.listelements("isofill")) else: self.assertEqual(untouched, vcs.listelements("colormap")) vcs.manageElements.reset() if gtype == "colormap": self.assertNotEqual(untouched, vcs.listelements("isofill")) else: self.assertNotEqual(untouched, vcs.listelements("colormap")) # case for 1d weirdness sc = vcs.createscatter() vcs.manageElements.reset()
def testLoadJson(self): pth = os.path.dirname(__file__) json = os.path.join(pth, "share", "test_vcs_json.json") for tp in [ "boxfill", "meshfill", "isofill", "isoline", "template", "1d" ]: b4 = vcs.listelements(tp) self.assertFalse("Charles.Doutriaux" in b4) vcs.scriptrun(json) for tp in [ "boxfill", "meshfill", "isofill", "isoline", "template", "1d" ]: after = vcs.listelements(tp) self.assertTrue("Charles.Doutriaux" in after) gm = vcs.elements[tp]["Charles.Doutriaux"]
def setgui(self): ## First sets everuthing to "normal" so we can update the gui! self.Line.configure(menubutton_state="normal") self.type.configure(menubutton_state="normal") self.width.configure(state="normal") self.Color.configure(state="normal") self.type.setvalue(self.line.type[0]) self.width.set(self.line.width[0]) self.Color.set(self.line.color[0]) lines = vcs.listelements("line") lines.sort() self.Line.setitems(lines) if self.line.name == "default": self.type.configure(menubutton_state="disabled") self.width.configure(state="disabled") self.Color.configure(state="disabled") self.parent.properties_line.component("scrolledlist").setlist(lines) self.parent.properties_line.selectitem(self.line.name) self.Line.setvalue(self.line.name) attribute = "%s.line" % self.parent_Name self.parent.set_value(attribute, self.line.name) self.setline() return
def setgui(self): ## First sets everuthing to "normal" so we can update the gui! self.Line.configure(menubutton_state='normal') self.type.configure(menubutton_state='normal') self.width.configure(state='normal') self.Color.configure(state='normal') self.type.setvalue(self.line.type[0]) self.width.set(self.line.width[0]) self.Color.set(self.line.color[0]) lines = vcs.listelements('line') lines.sort() self.Line.setitems(lines) if self.line.name == 'default': self.type.configure(menubutton_state='disabled') self.width.configure(state='disabled') self.Color.configure(state='disabled') self.parent.properties_line.component('scrolledlist').setlist(lines) self.parent.properties_line.selectitem(self.line.name) self.Line.setvalue(self.line.name) attribute = '%s.line' % self.parent_Name self.parent.set_value(attribute, self.line.name) self.setline() return
def matplotlib2vcs(cmap, vcs_name=None): """Convert a matplotlib colormap to a vcs colormap Input can be either the actual matplotlib colormap or its name Optional second argument: vcs_name, name of the resulting vcs colormap """ import vcs import matplotlib.cm import warnings if isinstance(cmap, (str, unicode)): try: cmap = matplotlib.cm.get_cmap(cmap) except: raise RuntimeError("Could not retrieve matplotlib colormap: %s" % cmap) if vcs_name is None: vcs_name = cmap.name i = 0 vcs_name_final = vcs_name while vcs_name_final in vcs.listelements("colormap"): vcs_name_final = vcs_name + "_mpl_%.3i" % i i += 1 if vcs_name_final != vcs_name: warnings.warn( "%s colormap name was already existing, your colormap name will be: %s" % (vcs_name, vcs_name_final)) vcs_cmap = vcs.createcolormap(vcs_name_final) cmap_rgbs = cmap(range(0, cmap.N)) for i in range(0, min(cmap.N, 256)): vcs_cmap.setcolorcell(i, *([int(x * 100) for x in cmap_rgbs[i][:4]])) return vcs_cmap
def testNoXtra(self): s = self.clt("clt", time=(45, 45, 'cob'), longitude=(46., 46., 'cob'), squeeze=1) print(s.shape) self.x.portrait() N = 20 elements = vcs.listelements() cpy = {} for e in elements: cpy[e] = vcs.elements[e].copy() mn = 10000 times = [] for i in range(N): start = time.time() self.x.plot(s) self.x.png("blah", width=1200, height=1600, units="pixels") self.x.clear() end = time.time() elapsed = end - start if mn > elapsed: mn = elapsed print(i, elapsed, elapsed / mn) times.append(elapsed) for e in elements: # print "\t",e,len(vcs.elements[e]),len(cpy[e]) if len(vcs.elements[e]) != len(cpy[e]): print("\tMore elements in:", e, len(vcs.elements[e]), len(cpy[e]), len(vcs.elements[e]) - len(cpy[e])) self.assertEqual(len(vcs.elements[e]), len(cpy[e]))
def get_cmaps(): cmaps = {} for cmap in vcs.listelements('colormap'): index = vcs.getcolormap(cmap).index cmaps[cmap] = [ vcs.getcolormap(cmap).getcolorcell(i) for i in range(256) ] return cmaps
def setGraphicsMethod(self, gm): if (isinstance(gm, list)): self._plot.graphics_method = vcs.getgraphicsmethod(gm[0], gm[1]) return for t in vcs.listelements(): if len(vcs.listelements(t)): o = vcs.elements[t].values()[0] if hasattr(o, "g_name"): if o.g_name == gm["g_name"]: break else: return False my_gm = vcs.creategraphicsmethod(t) for k in gm: if k == "name": continue if gm[k] == 100000000000000000000: gm[k] = 1e20 if gm[k] == -100000000000000000000: gm[k] = -1e20 if isinstance(gm[k], list): conv = [] for v in gm[k]: if v == 100000000000000000000: conv.append(1e20) elif v == -100000000000000000000: conv.append(-1e20) else: conv.append(v) gm[k] = conv if hasattr(my_gm, k): try: setattr(my_gm, k, gm[k]) except: print "Could not set attribute %s on graphics method of type %s" % ( k, t) if "ext_1" in gm: my_gm.ext_1 = gm["ext_1"] if "ext_2" in gm: my_gm.ext_2 = gm["ext_2"] self._plot.graphics_method = my_gm
def get_el(self, name): tt = vcs.gettexttable(name) to = vcs.gettextorientation(name) for tc in vcs.listelements("textcombined"): tc = vcs.gettextcombined(tc) if tc.To_name == name and tc.Tt_name == name: return tc tc = vcs.createtextcombined() tc.Tt = tt tc.To = to return tc
def checkLine(self,name,value): checkName(self,name,value) if isinstance(value,unicode): value = str(value) if not isinstance(value,(str,vcs.line.Tl)): raise ValueError, name+' must be an line primitive or the name of an exiting one.' if isinstance(value,str): if not value in vcs.listelements('line'): raise ValueError, name+' is not an existing line primitive' return value else: return value.name
def checkTextOrientation(self,name,value): checkName(self,name,value) if isinstance(value,unicode): value = str(value) if isinstance(value,str): if not value in vcs.listelements("textorientation"): raise ValueError,"Error : not a valid textorientation" elif not isinstance(value,vcs.textorientation.To): raise ValueError,"Error you must pass a textorientation objector a textorientation name" else: return value.name return value
def setGraphicsMethod(self, gm): if (isinstance(gm, list)): self._plot.graphics_method = vcs.getgraphicsmethod(gm[0], gm[1]) return for t in vcs.listelements(): if len(vcs.listelements(t)): o = list(vcs.elements[t].values())[0] if hasattr(o, "g_name"): if o.g_name == gm["g_name"]: break else: return False my_gm = vcs.creategraphicsmethod(t) updateGraphicsMethodProps(gm, my_gm) if "ext_1" in gm: my_gm.ext_1 = gm["ext_1"] if "ext_2" in gm: my_gm.ext_2 = gm["ext_2"] self._plot.graphics_method = my_gm
def checkTextTable(self,name,value): checkName(self,name,value) if isinstance(value,unicode): value = str(value) if isinstance(value,str): if not value in vcs.listelements("texttable"): raise ValueError,"Error : not a valid texttable" elif not isinstance(value,vcs.texttable.Tt): raise ValueError,"Error you must pass a texttable objector a texttable name" else: return value.name return value
def checkFont(self,name,value): if (value == None): pass elif isNumber(value,min=1): value=int(value) # try to see if font exists nm = vcs.getfontname(value) elif isinstance(value,str): value = vcs.getfontnumber(value) else: nms = vcs.listelements("font") raise ValueError, 'Error for attribute %s: The font attribute values must be a valid font number or a valid font name. valid names are: %s' % (name,', '.join(nms)) return value
def diagnostics_template(): """creates and returns a VCS template suitable for diagnostics plots""" if 'diagnostic' in vcs.listelements('template'): tm = vcs.gettemplate('diagnostic') else: tm = vcs.createtemplate( 'diagnostic', 'default' ) # ...creates a template named 'diagnostic', as a copy of the one named 'default'. tm.title.x = 0.5 to = vcs.createtextorientation() to.halign = 'center' tm.title.textorientation = to tm.dataname.priority = 0 tm.units.priority = 0 return tm
def checkLine(self, name, value): checkName(self, name, value) if isinstance(value, unicode): value = str(value) if not isinstance(value, (str, vcs.line.Tl)): checkedRaise( self, value, ValueError, name + ' must be an line primitive or the name of an exiting one.') if isinstance(value, str): if not value in vcs.listelements('line'): checkedRaise(self, value, ValueError, name + ' is not an existing line primitive') return value else: return value.name
def checkTextTable(self, name, value): checkName(self, name, value) if isinstance(value, unicode): value = str(value) if isinstance(value, str): if not value in vcs.listelements("texttable"): checkedRaise(self, value, ValueError, "Error : not a valid texttable") elif not isinstance(value, vcs.texttable.Tt): checkedRaise( self, value, ValueError, "Error you must pass a texttable objector a texttable name") else: return value.name return value
def checkFont(self, name, value): if (value == None): pass elif isNumber(value, min=1): value = int(value) # try to see if font exists nm = vcs.getfontname(value) elif isinstance(value, str): value = vcs.getfontnumber(value) else: nms = vcs.listelements("font") checkedRaise( self, value, ValueError, 'Error for attribute %s: The font attribute values must be a valid font number or a valid font name. valid names are: %s' % (name, ', '.join(nms))) return value
def set_colormap_of_graphics_method( canvas, parameter_colormap, method, parameters): if parameter_colormap is not '': cmap = get_colormap(parameter_colormap, parameters) if isinstance(cmap, str): if cmap in vcs.listelements('colormap'): method.colormap = vcs.getcolormap(cmap) else: method.colormap = vcs.matplotlib2vcs(cmap) cmap_range = get_color_range(method) else: # cmap is of type vcs.colormap.Cp cmap, cmap_range = cmap method.colormap = cmap colors = vcs.getcolors(method.levels, colors=cmap_range, white=[ 100, 100, 100], split=0) method.fillareacolors = colors
def test_vcs_remove_object(self): for t in [ "boxfill", "isofill", "meshfill", "vector", "yxvsx", "xyvsy", "xvsy", "scatter", "1d", "isoline", "line", "fillarea", "marker", "texttable", "textorientation", "projection", "colormap", "textcombined" ]: print "Testing removal of", t, "objects" print "\tfrom canvas" exec("o = self.x.create%s()" % t) nm = o.name self.x.removeobject(o) self.assertTrue(nm not in self.x.listelements(t)) print "\tfrom vcs module" exec("o = vcs.create%s()" % t) nm = o.name vcs.removeobject(o) self.assertTrue(nm not in vcs.listelements(t))
def matplotlib2vcs(cmap, vcs_name=None): """ Convert a matplotlib colormap to a vcs colormap Input can be either the actual matplotlib colormap or its name Optional second argument: vcs_name, name of the resulting vcs colormap :param cmap: A matplotlib colormap or string name of a matplotlib colormap :type cmap: :py:class:`str` , matplotlib.cm :param vcs_name: String to set the name of the generated VCS colormap :type vcs_name: :py:class:`str` :returns: A VCS colormap object :rtype: vcs.colormap.Cp """ import vcs import matplotlib.cm import warnings if isinstance(cmap, (str, unicode)): try: cmap = matplotlib.cm.get_cmap(cmap) except: raise RuntimeError("Could not retrieve matplotlib colormap: %s" % cmap) if vcs_name is None: vcs_name = cmap.name i = 0 vcs_name_final = vcs_name while vcs_name_final in vcs.listelements("colormap"): vcs_name_final = vcs_name + "_mpl_%.3i" % i i += 1 if vcs_name_final != vcs_name: warnings.warn( "%s colormap name was already existing, your colormap name will be: %s" % (vcs_name, vcs_name_final)) vcs_cmap = vcs.createcolormap(vcs_name_final) cmap_rgbs = cmap(range(0, cmap.N)) for i in range(0, min(cmap.N, 256)): vcs_cmap.setcolorcell(i, *([int(x * 100) for x in cmap_rgbs[i][:4]])) return vcs_cmap
def test_vcs_read_yx_scr(self): testfile = os.path.join(os.path.dirname(__file__), "share", "read_yxvsx.scr") vcs.scriptrun(testfile) self.assertTrue("testyx" in vcs.listelements("yxvsx")) y = vcs.getyxvsx("testyx") self.assertEqual(y.datawc_x1, -50.) self.assertEqual(y.datawc_x2, 20.) self.assertEqual(y.datawc_y1, 50.) self.assertEqual(y.datawc_timeunits, "days since 2100") self.assertEqual(y.datawc_calendar, 135441) self.assertEqual(y.xaxisconvert, "log10") self.assertEqual(y.yaxisconvert, "area_wt") self.assertEqual(y.linetype, "dash") self.assertEqual(y.linecolor, [0.0, 0.0, 0.0, 100.0]) self.assertEqual(y.linewidth, 1) self.assertEqual(y.marker, "circle") self.assertEqual(y.markercolor, [0.0, 0.0, 0.0, 100.0]) self.assertEqual(y.markersize, 1) self.assertEqual(y.flip, False)
def testApplyFormat(self): class Data(object): def __repr__(self): return 'räpr' fmts = vcs.listelements("format") print("Formats:", fmts) results = [ "02", "002", "0002", "02", "002", "0002", " 2", "0.17", " 2", "0.167", " 2", "1.66667E-06", "r\\xe4pr", "0.16666666666666666", "0.16666666666666666", "0.17", "0.167", "1.66667e-06", "räpr", "0.16666666666666666", " 2", " 2", " 2" ] if sys.version_info.major == 2: # different on py2 precision.... results = [ "02", "002", "0002", "02", "002", "0002", " 2", "0.17", " 2", "0.167", " 2", "1.66667E-06", "r\\xe4pr", "0.166666666667", "0.166666666667", "0.17", "0.167", "1.66667e-06", "räpr", "0.166666666667", " 2", " 2", " 2" ] for fmt, res in zip(fmts, results): if "d" in vcs.elements["format"][fmt]: value = 2 elif fmt in ["g", "G"]: value = 1. / 600000. elif fmt in ["a", "r"]: if sys.version_info.major == 2: # different on py2 precision.... continue else: value = Data() else: value = 1. / 6. print("Testing formatting {} with format {}, expected: {}".format( value, fmt, res)) self.assertEqual(vcs.template.applyFormat(value, fmt), res)
def testSortedErrorAlpha(self): elts = str(vcs.listelements()) with self.assertRaisesRegexp(Exception, elts): vcs.show("bad")
import vcs x=vcs.init() for t in ["boxfill","isofill","meshfill", "vector","yxvsx","xyvsy","xvsy","scatter", "1d","isoline","line","fillarea","marker", "texttable","textorientation","projection", "colormap","textcombined"]: print "Testing removal of",t,"objects" print "\tfrom canvas" exec("o = x.create%s()" % t) nm = o.name x.removeobject(o) assert(nm not in x.listelements(t)) print "\tfrom vcs module" exec("o = vcs.create%s()" % t) nm = o.name vcs.removeobject(o) assert(nm not in vcs.listelements(t))
import vcs, sys vcs.scriptrun(sys.argv[1]) assert ("testyx" in vcs.listelements("yxvsx")) y = vcs.getyxvsx("testyx") assert (y.datawc_x1 == -50.) assert (y.datawc_x2 == 20.) assert (y.datawc_y1 == 50.) assert (y.datawc_timeunits == "days since 2100") assert (y.datawc_calendar == 135441) assert (y.xaxisconvert == "log10") assert (y.yaxisconvert == "area_wt") assert (y.line == "dash") assert (y.linecolor == 241) assert (y.linewidth == 1) assert (y.marker == "circle") assert (y.markercolor == 241) assert (y.markersize == 1) assert (y.flip == False)
def setgui(self,*crap): Proj_color=gui_support.gui_color.Proj_color projs=vcs.listelements('projection') projs.sort() a=self.projection.name self.projections.setitems(projs) self.projections.setvalue(a) self.parent.projection.setitems(projs) self.parent.projection.invoke(a) self.parent.button.configure(command=gui_control.Command(ProjGUI,canvas=self.canvas,gui_parent=self.gui_parent,dialog_parent=self.dialog_parent,master=self.master,name=a,Parent=self.parent)) self.projtype.configure(menubutton_state='normal') self.projtype.setvalue(self.projtypes[self.projection._type+3]) self.fproperties.destroy() inter=self.fprop.interior() inter.configure(bg=Proj_color) self.fproperties=Tkinter.Frame(inter,bg=Proj_color,relief='sunken') self.fproperties.pack(expand='yes',fill='both') self.fields=[] p=[] balloons={ 'smajor':'Semi-major axis of ellipsoid.\nIf zero, Clarke 1866 in meters is assumed.', 'sminor':'Eccentricity squared of the ellipsoid if less than zero\nIf zero, a spherical form is assumed\nIf greater than zero, the semi-minor axis of ellipsoid.', 'sphere':'Radius of reference sphere.\nIf zero, 6370997 meters is used.', 'standardparallel':'Latitude of the standard parallel', 'standardparallel1':'Latitude of the first standard parallel', 'standardparallel2':'Latitude of the second standard parallel', 'centralmeridian':' Longitude of the central meridian', 'originlatitude':'Latitude of the projection origin', 'falseeasting':'False easting in the same units as the semi-major axis', 'falsenorthing':'False northing in the same units as the semi-major axis', 'truescale':'Latitude of true scale', 'LongPol':'Longitude down below pole of map', 'factor':'Scale factor at central meridian (Transverse Mercator)\nor\nCenter of projection (Hotine Oblique Mercator)', 'centerlongitude':'Longitude of center of projection', 'centerlatitude':'Latitude of center of projection', 'height':'Height of perspective point', 'longitude1':'Longitude of first point on center line', 'longitude2':'Longitude of second point on center line', 'latitude1':'Latitude of first point on center line', 'latitude2':'Latitude of second point on center line', 'azimuthalangle':'Azimuth angle east of north of center line', 'azimuthallongitude':' Longitude of point on central meridian where azimuth occurs', 'orbitinclination':'Inclination of orbit at ascending node\ncounter-clockwise from equator', 'orbitlongitude':' Longitude of ascending orbit at equator', 'satelliterevolutionperiod':'Period of satellite revolution in minutes', 'landsatcompensationratio':'Landsat ratio to compensate for confusion at northern end of orbit\n(use 0.5201613)', 'pathflag':'End of path flag for Landsat\n0 = start of path, 1 = end of path', 'satellite':'Landsat Satellite Number', 'path':'Landsat Path Number\nUse WRS-1 for Landsat 1, 2 and 3\nUse WRS-2 for Landsat 4, 5 and 6.', 'shapem':'Oblated Equal Area oval shape parameter m', 'shapen':'Oblated Equal Area oval shape parameter n', 'angle':'Oblated Equal Area oval rotation angle', 'subtype':'Subtype of the projection (0 or 1)', } if self.projection._type in [3,4]: p.append('smajor') p.append('sminor') p.append('standardparallel1') p.append('standardparallel2') p.append('centralmeridian') p.append('originlatitude') p.append('falseeasting') p.append('falsenorthing') elif self.projection._type==5: p.append('smajor') p.append('sminor') p.append('centralmeridian') p.append('truescale') p.append('falseeasting') p.append('falsenorthing') elif self.projection._type==6: p.append('smajor') p.append('sminor') p.append('centerlongitude') p.append('truescale') p.append('falseeasting') p.append('falsenorthing') elif self.projection._type==7: p.append('smajor') p.append('sminor') p.append('centralmeridian') p.append('originlatitude') p.append('falseeasting') p.append('falsenorthing') elif self.projection._type==8: p.append('subtype') p.append('smajor') p.append('sminor') p.append('centralmeridian') p.append('originlatitude') p.append('falseeasting') p.append('falsenorthing') if self.projection.subtype==0: p.append('standardparallel') else: p.append('standardparallel1') p.append('standardparallel2') elif self.projection._type==9: p.append('smajor') p.append('sminor') p.append('factor') p.append('centralmeridian') p.append('originlatitude') p.append('falseeasting') p.append('falsenorthing') elif self.projection._type in [10,11,12,13,14]: p.append('sphere') p.append('centerlongitude') p.append('centerlatitude') p.append('falseeasting') p.append('falsenorthing') elif self.projection._type==15: p.append('sphere') p.append('height') p.append('centerlongitude') p.append('centerlatitude') p.append('falseeasting') p.append('falsenorthing') elif self.projection._type in [16,18,21,25,27,28,29]: p.append('sphere') p.append('centralmeridian') p.append('falseeasting') p.append('falsenorthing') elif self.projection._type==17: p.append('sphere') p.append('centralmeridian') p.append('truescale') p.append('falseeasting') p.append('falsenorthing') elif self.projection._type==19: p.append('sphere') p.append('centralmeridian') p.append('originlatitude') p.append('falseeasting') p.append('falsenorthing') elif self.projection._type==20: p.append('subtype') p.append('smajor') p.append('sminor') p.append('factor') p.append('originlatitude') p.append('falseeasting') p.append('falsenorthing') if self.projection.subtype==0: p.append('longitude1') p.append('latitude1') p.append('longitude2') p.append('latitude2') else: p.append('azimuthalangle') p.append('azimuthallongitude') elif self.projection._type==22: p.append('subtype') p.append('smajor') p.append('sminor') p.append('falseeasting') p.append('falsenorthing') if self.projection.subtype==0: p.append('orbitinclination') p.append('orbitlongitude') p.append('satelliterevolutionperiod') p.append('landsatcompensationratio') p.append('pathflag') else: p.append('satellite') p.append('path') elif self.projection._type==23: p.append('smajor') p.append('sminor') p.append('falseeasting') p.append('falsenorthing') elif self.projection._type in [24,26]: p.append('sphere') elif self.projection._type==30: p.append('sphere') p.append('shapem') p.append('shapen') p.append('centerlongitude') p.append('centerlatitude') p.append('falseeasting') p.append('falsenorthing') self.properties_names=p for p in self.properties_names: f=Tkinter.Frame(self.fproperties) f.pack(expand='yes',fill='both') a=Pmw.EntryField(self.fproperties, label_width=20,labelpos='w', label_justify='left', label_text=p, label_bg=Proj_color, hull_bg=Proj_color, entry_relief='sunken', entry_background='white', command=self.setprojection, value=getattr(self.projection,p), ## balloon=gui_support.balloon, ) a.pack(expand=1,fill='both') b=gui_support.balloon.bind( a, balloons[p] ) self.fields.append(a) if self.projection.name in ['default','robinson','polar','mollweide','linear']: self.projtype.configure(menubutton_state='disabled') for a in self.fields: a.configure(entry_state='disabled') self.setprojection() return
def init_elements(self): self.elements = sorted( (el for el in vcs.listelements(self.el_type) if el[:2] != "__"))
def _plotInternal(self): """Overrides baseclass implementation.""" tmpLevels = [] tmpColors = [] tmpLineWidths = [] tmpLineTypes = [] linewidth = self._gm.linewidths self.extendAttribute(linewidth, default=1.0) linetype = self._gm.linetypes self.extendAttribute(linetype, default='solid') plotting_dataset_bounds = self.getPlottingBounds() x1, x2, y1, y2 = plotting_dataset_bounds for i, lv_tmp in enumerate(self._contourLevels): if i == 0: W = linewidth[i] S = linetype[i] C = [self._contourColors[i]] if lv_tmp == 1.e20: L = [-1.e20] else: L = [lv_tmp] else: if W == linewidth[i] and S == linetype[i]: # Ok same style and width, lets keep going L.append(lv_tmp) C.append(self._contourColors[i]) else: tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineTypes.append(S) L = [lv_tmp] C = [self._contourColors[i]] W = linewidth[i] S = linetype[i] tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineTypes.append(S) cots = [] textprops = [] luts = [] actors = [] mappers = [] if self._gm.label and (self._gm.text or self._gm.textcolors): # Text objects: if self._gm.text: texts = self._gm.text while len(texts) < len(self._contourLevels): texts.append(texts[-1]) else: texts = [None] * len(self._contourLevels) # Custom colors: if self._gm.textcolors: colorOverrides = self._gm.textcolors while len(colorOverrides) < len(self._contourLevels): colorOverrides.append(colorOverrides[-1]) else: colorOverrides = [None] * len(self._gm.text) # Custom background colors and opacities: backgroundColors = self._gm.labelbackgroundcolors if backgroundColors: while len(backgroundColors) < len(self._contourLevels): backgroundColors.append(backgroundColors[-1]) backgroundOpacities = self._gm.labelbackgroundopacities if backgroundOpacities: while len(backgroundOpacities) < len(self._contourLevels): backgroundOpacities.append(backgroundOpacities[-1]) else: backgroundOpacities = [100.0 for lev in self._contourLevels] countLevels = 0 vp = self._resultDict.get( 'ratio_autot_viewport', [self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2]) # view and interactive area view = self._context().contextView area = vtk.vtkInteractiveArea() view.GetScene().AddItem(area) adjusted_plotting_bounds = vcs2vtk.getProjectedBoundsForWorldCoords( plotting_dataset_bounds, self._gm.projection) drawAreaBounds = vcs2vtk.computeDrawAreaBounds(adjusted_plotting_bounds) [renWinWidth, renWinHeight] = self._context().renWin.GetSize() geom = vtk.vtkRecti(int(round(vp[0] * renWinWidth)), int(round(vp[2] * renWinHeight)), int(round((vp[1] - vp[0]) * renWinWidth)), int(round((vp[3] - vp[2]) * renWinHeight))) vcs2vtk.configureContextArea(area, drawAreaBounds, geom) # FIXME: This render call is needed to work around a bug somewhere in the # FIXME: vtkContextTransform code, where the transformation represented by # FIXME: Map[To|From]Scene() isn't set up properly until after a render call. self._context().renWin.Render() for i, l in enumerate(tmpLevels): numLevels = len(l) cot = vtk.vtkContourFilter() cot.SetInputData(self._vtkDataSetFittedToViewport) cot.SetNumberOfContours(numLevels) for n in range(numLevels): cot.SetValue(n, l[n]) # TODO remove update cot.Update() lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(len(tmpColors[i])) cmap = self.getColorMap() for n, col in enumerate(tmpColors[i]): r, g, b, a = self.getColorIndexOrRGBA(cmap, col) lut.SetTableValue(n, r / 100., g / 100., b / 100., a / 100.) # Setup isoline labels if self._gm.label: # Setup label mapping array: tpropMap = vtk.vtkDoubleArray() tpropMap.SetNumberOfComponents(1) tpropMap.SetNumberOfTuples(numLevels) for n, val in enumerate(l): tpropMap.SetTuple(n, [val]) # Prep text properties: tprops = vtk.vtkTextPropertyCollection() if self._gm.text or self._gm.textcolors: ttexts = texts[countLevels:(countLevels + len(l))] for idx, tc in enumerate(ttexts): if vcs.queries.istextcombined(tc): tt, to = tuple(tc.name.split(":::")) elif tc is None: tt = "default" to = "default" elif vcs.queries.istexttable(tc): tt = tc.name to = "default" elif vcs.queries.istextorientation(tc): to = tc.name tt = "default" elif isinstance(tc, str): sp = tc.split(":::") if len(sp) == 2: tt = sp[0] to = sp[1] else: # Hum don't know what do do with this if sp[0] in vcs.listelements("textcombined"): tc = vcs.gettextcombined(tc) tt, to = tuple(tc.name.split(":::")) elif sp[0] in vcs.listelements("textorientation"): to = sp[0] tt = "default" elif sp[0] in vcs.listelements("texttable"): tt = sp[0] to = "default" tt = vcs.createtexttable(None, tt) colorOverride = colorOverrides[countLevels + idx] if colorOverride is not None: tt.color = colorOverride tt = tt.name if backgroundColors is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundcolor = backgroundColors[countLevels + idx] if backgroundOpacities is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundopacity = backgroundOpacities[countLevels + idx] tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), to, tt, cmap=cmap) tprops.AddItem(tprop) if colorOverride is not None: del(vcs.elements["texttable"][tt]) else: # No text properties specified. Use the default: tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), cmap=cmap) tprop.SetBackgroundOpacity(1.0) tprops.AddItem(tprop) textprops.append(tprops) item = vtk.vtkLabeledContourPolyDataItem() item.SetTextProperties(tprops) item.SetTextPropertyMapping(tpropMap) item.SetLabelVisibility(1) item.SetSkipDistance(self._gm.labelskipdistance) mapper = vtk.vtkLabeledContourMapper() pdMapper = mapper.GetPolyDataMapper() luts.append([lut, [l[0], l[-1], False]]) else: # No isoline labels: item = vtk.vtkPolyDataItem() mapper = vtk.vtkPolyDataMapper() pdMapper = mapper luts.append([lut, [l[0], l[-1], False]]) pdMapper.SetLookupTable(lut) lut.SetRange(l[0], l[-1]) pdMapper.SetScalarRange(l[0], l[-1]) pdMapper.SetScalarModeToUsePointData() stripper = vtk.vtkStripper() stripper.SetInputConnection(cot.GetOutputPort()) mapper.SetInputConnection(stripper.GetOutputPort()) # TODO remove update, make pipeline stripper.Update() poly = stripper.GetOutput() mappers.append(mapper) cots.append(cot) if self._needsCellData: attrs = poly.GetCellData() scalarMode = vtk.VTK_SCALAR_MODE_USE_CELL_DATA else: attrs = poly.GetPointData() scalarMode = vtk.VTK_SCALAR_MODE_USE_POINT_DATA data = attrs.GetScalars() mappedColors = lut.MapScalars(data, vtk.VTK_COLOR_MODE_DEFAULT, 0) intValue = vtk.vtkIntArray() intValue.SetNumberOfComponents(1) intValue.SetName("StippleType") intValue.InsertNextValue(vcs2vtk.getStipple(tmpLineTypes[i])) poly.GetFieldData().AddArray(intValue) floatValue = vtk.vtkFloatArray() floatValue.SetNumberOfComponents(1) floatValue.SetName("LineWidth") floatValue.InsertNextValue(tmpLineWidths[i]) poly.GetFieldData().AddArray(floatValue) item.SetPolyData(poly) item.SetScalarMode(scalarMode) item.SetMappedColors(mappedColors) mappedColors.FastDelete() area.GetDrawAreaItem().AddItem(item) actors.append([item, plotting_dataset_bounds]) countLevels += len(l) if len(textprops) > 0: self._resultDict["vtk_backend_contours_labels_text_properties"] = \ textprops if len(luts) > 0: if self._gm.label: self._resultDict["vtk_backend_labeled_luts"] = luts else: self._resultDict["vtk_backend_luts"] = luts if len(cots) > 0: self._resultDict["vtk_backend_contours"] = cots if self._maskedDataMapper is not None: mappers.insert(0, self._maskedDataMapper) self._maskedDataMapper.Update() maskedData = self._maskedDataMapper.GetInput() maskedColors = vtk.vtkUnsignedCharArray() maskedColors.SetNumberOfComponents(4) for i in range(poly.GetNumberOfCells()): maskedColors.InsertNextTypedTuple([0, 0, 0, 255]) maskItem = vtk.vtkPolyDataItem() maskItem.SetPolyData(maskedData) maskItem.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_CELL_DATA) maskItem.SetMappedColors(maskedColors) area.GetDrawAreaItem().AddItem(maskItem) actors.append([maskItem, self._maskedDataMapper, plotting_dataset_bounds]) self._resultDict["vtk_backend_actors"] = actors z, t = self.getZandT() kwargs = { "vtk_backend_grid": self._vtkDataSet, "dataset_bounds": self._vtkDataSetBounds, "plotting_dataset_bounds": plotting_dataset_bounds, "vtk_dataset_bounds_no_mask": self._vtkDataSetBoundsNoMask, "vtk_backend_geo": self._vtkGeoTransform, "vtk_backend_draw_area_bounds": drawAreaBounds, "vtk_backend_viewport_scale": [ self._context_xScale, self._context_yScale ] } if ("ratio_autot_viewport" in self._resultDict): kwargs["ratio_autot_viewport"] = vp self._resultDict.update(self._context().renderTemplate( self._template, self._data1, self._gm, t, z, **kwargs)) projection = vcs.elements["projection"][self._gm.projection] kwargs['xaxisconvert'] = self._gm.xaxisconvert kwargs['yaxisconvert'] = self._gm.yaxisconvert if self._data1.getAxis(-1).isLongitude() and self._data1.getAxis(-2).isLatitude(): self._context().plotContinents(self._plot_kargs.get("continents", self._useContinents), plotting_dataset_bounds, projection, self._dataWrapModulo, vp, self._template.data.priority, **kwargs)
def __init__(self, mode=COLORMAP_MODE, parent=None): QtGui.QColorDialog.__init__(self, parent) self.parent = parent self.setOption(QtGui.QColorDialog.DontUseNativeDialog, True) self.setOption(QtGui.QColorDialog.NoButtons) self.setOption(QtGui.QColorDialog.ShowAlphaChannel, True) l = self.layout() # Colormap selection Area f = QtGui.QFrame() h = QtGui.QHBoxLayout() self.colormap = QtGui.QComboBox(self) colormaps = sorted(vcs.listelements("colormap")) for i in colormaps: self.colormap.addItem(i) h.addWidget(self.colormap) self.newname = QtGui.QLineEdit() h.addWidget(self.newname) b = QtGui.QPushButton("Rename") b.clicked.connect(self.renamed) h.addWidget(b) f.setLayout(h) l.addWidget(f) self.mode = mode # Apply/Cancel/Save/Reset/Blend buttons buttons = QtGui.QDialogButtonBox() buttons.layout().addSpacing(30) self.accept = buttons.addButton(u"Accept", QtGui.QDialogButtonBox.AcceptRole) self.accept.setDefault(True) self.accept.setAutoDefault(True) if mode == COLORMAP_MODE: self.setWindowTitle("Choose Colormap") self.accept.setToolTip("Use Colormap") else: self.setWindowTitle("Choose Color") self.accept.setEnabled(False) self.accept.setToolTip("Use Color") export = QtGui.QPushButton("Export") export.setToolTip("Save Colormap To File") buttons.addButton(export, QtGui.QDialogButtonBox.AcceptRole) buttons.addButton( QtGui.QDialogButtonBox.Open).setToolTip("Open existing colormap") buttons.addButton("Blend", QtGui.QDialogButtonBox.HelpRole) \ .setToolTip("Blend From First To Last Highlighted Colors") buttons.addButton( QtGui.QDialogButtonBox.Reset).setToolTip("Reset Changes") buttons.addButton( QtGui.QDialogButtonBox.Apply).setToolTip("Apply Changes") buttons.addButton( QtGui.QDialogButtonBox.Cancel).setToolTip("Close Colormap") self.accept.clicked.connect(self.acceptClicked) buttons.button(QtGui.QDialogButtonBox.Apply).clicked.connect( self.applyChanges) buttons.button(QtGui.QDialogButtonBox.Open).clicked.connect( self.openColormap) buttons.button(QtGui.QDialogButtonBox.Cancel).clicked.connect( self.rejectChanges) export.clicked.connect(self.save) buttons.button(QtGui.QDialogButtonBox.Reset).clicked.connect( self.resetChanges) buttons.helpRequested.connect(self.blend) self.buttons = buttons self.colors = color_table.ColormapTable(16) self.scrollArea = QtGui.QScrollArea() self.scrollArea.setWidget(self.colors) self.scrollArea.setWidgetResizable(True) l.addWidget(self.scrollArea) l.addWidget(self.buttons) # SIGNALS self.colormap.currentIndexChanged.connect(self.colorMapComboChanged) self.currentColorChanged.connect(self.colorChanged) self.colors.singleColorSelected.connect(self.selectedCell) self.colors.cmap = str(self.colormap.currentText()) self.cell = None
def listelements(self, typeName): """Returns a list of element names""" return vcs.listelements(typeName)
import vcs,sys vcs.scriptrun(sys.argv[1]) assert("testyx" in vcs.listelements("yxvsx")) y = vcs.getyxvsx("testyx") assert(y.datawc_x1 == -50.) assert(y.datawc_x2 == 20.) assert(y.datawc_y1 == 50.) assert(y.datawc_timeunits == "days since 2100") assert(y.datawc_calendar == 135441) assert(y.xaxisconvert == "log10") assert(y.yaxisconvert == "area_wt") assert(y.line == "dash") assert(y.linecolor == 241) assert(y.linewidth == 1) assert(y.marker == "circle") assert(y.markercolor == 241) assert(y.markersize == 1) assert(y.flip == False)
def __init__(self, canvas=None, gui_parent=None, dialog_parent=None, master=None, name='default',Parent=None): self.gui_parent=gui_parent self.dialog_parent=dialog_parent self.master=master # print 'PASSED INSIDE:',gui_parent if canvas is None: ## import Canvas ## self.canvas = Canvas.Canvas() self.canvas=vcs.init() else: self.canvas=canvas self.projection=self.canvas.getprojection(name) if self.projection is None: raise 'Erro invalid projection name' self.parent=Parent ## Saves original values self.orig=[] self.save_vals() Proj_color = gui_support.gui_color.Proj_color ################################################################################################# # At the moment, this will never happen. When we need to pop this editor up on its own, then we # will revist this case. ## if self.gui_parent is None: ## self.gui_parent=Tkinter.Toplevel() ## #self.gui_parent=Tkinter.Tk(":0.0") # Use the localhost:0.0 for the DISPLAY and screen ## self.gui_parent.withdraw() ################################################################################################# title='Projection Editor - '+self.projection.name self.dialog = Pmw.Dialog(master, title=title, buttons=(), ) self.dialog.withdraw() if gui_support.root_exists(): root = gui_support.root() self.top_parent = root else: root = gui_support.root() self.top_parent = None self.root = root parent=self.dialog.interior() parent.configure(bg=Proj_color) self.cmain_menu = Pmw.MenuBar(parent, hull_relief = 'raised', hull_borderwidth = 2, balloon = gui_support.balloon ) self.cmain_menu.pack(side='top', fill='both') self.cmain_menu.addmenu('File', 'Open/Save VCS Projections', tearoff = 1) self.cmain_menu.addmenuitem('File', 'command', 'Open projection file', label = 'Open Projection File', command = self.evt_open_file, ) self.cmain_menu.addmenuitem('File', 'separator') # # Create the cascade "Save Colormap" menu and its items ## self.cmain_menu.addmenuitem('File', 'command', 'Select projection', ## label = 'Select', ## command = self.evt_loadproj, ## ) self.cmain_menu.addmenuitem('File', 'command', 'Save projection', label = 'Save (i.e Apply changes)', command = self.setprojection, ) self.cmain_menu.addmenuitem('File', 'command', 'Copy projection', label = 'Copy Projection', command = self.evt_save_as, ) self.cmain_menu.addmenuitem('File', 'command', 'Save as file', label = 'Save To File', command = self.evt_save_to_file, ) # Create the cascade "Exit" menu self.cmain_menu.addmenuitem('File', 'separator') self.cmain_menu.addmenuitem('File', 'command', statusHelp='Close Projection Editor', label = "Exit Projection Editor", command = self.dialog.destroy, ) ## self.ftype=Tkinter.Frame(parent) ## self.ftype.pack(side='top') projs=vcs.listelements('projection') projs.sort() self.projections=Pmw.OptionMenu(parent, items=projs, labelpos='w', label_text='Name: ', command=self.loadproj, initialitem=self.projection.name, label_bg=Proj_color, hull_bg=Proj_color, menu_bg=Proj_color, menu_activebackground=Proj_color, menubutton_bg=Proj_color, menubutton_activebackground=Proj_color, ) self.projections.pack() self.fprop=Pmw.Group(parent,tag_text='Properties', tagindent=10, tag_bg=Proj_color, ring_bg=Proj_color, hull_bg=Proj_color) self.fprop.pack(expand='yes',fill='both') inter=self.fprop.interior() inter.configure(bg=Proj_color) self.fproperties=Tkinter.Frame(inter,bg=Proj_color) self.fbuttons=Tkinter.Frame(parent,bg=Proj_color) self.fbuttons.pack() self.projtypes=["polar (non gctp)", "mollweide (non gctp)", "robinson (non gctp)", "linear", "utm", "state plane", "albers equal area", "lambert", "mercator", "polar stereographic", "polyconic", "equid conic", "transverse mercator", "stereographic", "lambert azimuthal", "azimuthal", "gnomonic", "orthographic", "gen. vert. near per", "sinusoidal", "equirectangular", "miller cylindrical", "van der grinten", "hotin oblique", "robinson", "space oblique", "alaska conformal", "interrupted goode", "mollweide", "interrupted mollweide", "hammer", "wagner iv", "wagner vii", "oblated equal area", ] self.projtype = Pmw.OptionMenu (inter, labelpos='w', label_text='Projection Type', label_bg=Proj_color, hull_bg=Proj_color, menu_bg=Proj_color, menu_activebackground=Proj_color, menubutton_bg=Proj_color, menubutton_activebackground=Proj_color, items= self.projtypes, command=self.settype, ) self.projtype.pack() b1=Tkinter.Button(self.fbuttons, text='Cancel', command=self.cancel) b1.pack(side='left') b2=Tkinter.Button(self.fbuttons, text='Apply', command=self.exit) b2.pack(side='left') b3=Tkinter.Button(self.fbuttons, text='Revert', command=self.reset) b3.pack(side='left') self.setgui() # Position dialog popup if dialog_parent is not None: parent_geom = dialog_parent.geometry() geom = string.split(parent_geom, '+') d1 = string.atoi( geom[1] ) d2 = string.atoi( geom[2] ) self.dialog.activate( geometry="+%d+%d" % (d1, d2) ) else: self.dialog.activate(geometry = 'centerscreenalways') return
def init_elements(self): self.elements = sorted((el for el in vcs.listelements(self.el_type) if el[:2] != "__"))
def __init__(self, canvas=None, gui_parent=None, dialog_parent=None, master=None, name='default', Parent=None): self.gui_parent = gui_parent if canvas is None: self.canvas = vcs.init() else: self.canvas = canvas self.line = self.canvas.getline(name) if self.line is None: if not name in vcs.listelements('line'): raise 'Error ' + t_name + ' is not a valid line name' else: raise 'Weird unkwnown error but no line object returned....' self.parent = Parent self.parent_Name = self.parent.parent_Name ## Saves original values self.orig = [] self.save_vals() L_color = gui_support.gui_color.L_color if self.gui_parent is None: self.gui_parent = Tkinter.Toplevel() #self.gui_parent=Tkinter.Tk(":0.0") # Use the localhost:0.0 for the DISPLAY and screen self.gui_parent.withdraw() title = 'Line Editor - table: ' + self.line.name self.dialog = Pmw.Dialog( master, title=title, buttons=(), ) self.dialog.withdraw() if gui_support.root_exists(): root = gui_support.root() self.top_parent = root else: root = gui_support.root() self.top_parent = None self.root = root parent = self.dialog.interior() parent.configure(bg=L_color) self.cmain_menu = Pmw.MenuBar(parent, hull_relief='raised', hull_borderwidth=2, balloon=gui_support.balloon) self.cmain_menu.pack(side='top', fill='both') self.cmain_menu.addmenu('File', 'Open/Save VCS Line Objects', tearoff=1) self.cmain_menu.addmenuitem( 'File', 'command', 'Open line object file', label='Open LineObject File', command=self.evt_open_file, ) self.cmain_menu.addmenuitem('File', 'separator') # # Create the cascade "Save Colormap" menu and its items self.cmain_menu.addmenuitem( 'File', 'command', 'Save Line', label='Save (i.e Apply changes)', command=self.setline, ) self.cmain_menu.addmenuitem( 'File', 'command', 'Copy Line', label='Copy Line', command=self.evt_save_line_as, ) self.cmain_menu.addmenuitem( 'File', 'command', 'Save to file', label='Save To File', command=self.evt_save_to_file, ) # Create the cascade "Exit" menu self.cmain_menu.addmenuitem('File', 'separator') self.cmain_menu.addmenuitem( 'File', 'command', statusHelp='Close Line Editor', label="Exit Line Editor", command=self.dialog.destroy, ) ## self.ftype=Tkinter.Frame(parent) ## self.ftype.pack(side='top') self.tprop = Pmw.Group( parent, tag_text='Line', tag_bg=L_color, tagindent=10, hull_bg=L_color, hull_highlightbackground=L_color, hull_highlightcolor=L_color, ring_bg=L_color, ) self.tprop.pack(expand='yes', fill='both') self.tproperties = self.tprop.interior() self.tproperties.configure(bg=L_color) lines = vcs.listelements('line') lines.sort() labels = [] self.Line = Pmw.OptionMenu( self.tproperties, items=lines, labelpos='w', label_text='Name:', command=self.loadline, initialitem=self.line.name, label_bg=L_color, hull_bg=L_color, menu_bg=L_color, menu_activebackground=L_color, menubutton_bg=L_color, menubutton_activebackground=L_color, ) self.Line.pack() labels.append(self.Line) items = ["solid", "dash", "dot", "dash-dot", "long-dash"] self.type = Pmw.OptionMenu( self.tproperties, items=items, labelpos='w', label_text='Type:', label_bg=L_color, hull_bg=L_color, menu_bg=L_color, menu_activebackground=L_color, menubutton_bg=L_color, menubutton_activebackground=L_color, command=self.setline, ) self.type.pack() labels.append(self.type) f = Tkinter.Frame(self.tproperties, bg=L_color) l = Tkinter.Label( f, text='Width:', bg=L_color, ) l.pack(side='left') self.width = Tkinter.Scale( f, bigincrement=10, from_=1, to=300, orient='horizontal', tickinterval=50, length=200, bg=L_color, activebackground=L_color, highlightbackground=L_color, command=self.setline, ) self.width.pack() labels.append(l) f.pack() f = Tkinter.Frame(self.tproperties, bg=L_color) l = Tkinter.Label( f, text='Color:', bg=L_color, ) l.pack(side='left') self.Color = Tkinter.Scale( f, bigincrement=50, from_=0, to=255, orient='horizontal', tickinterval=50, length=200, bg=L_color, activebackground=L_color, highlightbackground=L_color, command=self.setline, ) self.Color.pack() labels.append(l) f.pack() Pmw.alignlabels(labels) self.fbuttons = Tkinter.Frame(parent) self.fbuttons.pack() ## b0=Tkinter.Button(self.fbuttons, ## text='Preview', ## command=self.setfont) ## b0.pack(side='left') b1 = Tkinter.Button(self.fbuttons, text='Cancel', command=self.cancel) b1.pack(side='left') b2 = Tkinter.Button(self.fbuttons, text='Apply', command=self.exit) b2.pack(side='left') b3 = Tkinter.Button(self.fbuttons, text='Revert', command=self.reset) b3.pack(side='left') self.setgui() # Position dialog popup if dialog_parent is not None: parent_geom = dialog_parent.geometry() geom = string.split(parent_geom, '+') d1 = string.atoi(geom[1]) d2 = string.atoi(geom[2]) self.dialog.activate(geometry="+%d+%d" % (d1, d2)) else: self.dialog.activate(geometry='centerscreenalways') return
import vcs import sys json = sys.argv[1] for tp in ["boxfill","meshfill","isofill","isoline","template","1d"]: b4 = vcs.listelements(tp) assert (not "Charles.Doutriaux" in b4) vcs.scriptrun(json) for tp in ["boxfill","meshfill","isofill","isoline","template","1d"]: after = vcs.listelements(tp) assert ("Charles.Doutriaux" in after) gm = vcs.elements[tp]["Charles.Doutriaux"]
def setgui(self): ## First sets everuthing to "normal" so we can update the gui! self.font.configure(menubutton_state='normal') self.spacing.configure(state='normal') self.expansion.configure(state='normal') self.Color.configure(state='normal') self.height.configure(entry_state='normal') self.angle.configure(state='normal') self.path.configure(menubutton_state='normal') self.halign.configure(menubutton_state='normal') self.valign.configure(menubutton_state='normal') self.font.setvalue(self.canvas.getfont(self.text.font)) self.spacing.set(self.text.spacing) self.expansion.set(self.text.expansion) self.Color.set(self.text.color) self.height.setentry(str(self.text.height)) self.angle.set(self.text.angle) self.path.invoke(self.text.path) self.halign.invoke(self.text.halign) self.valign.invoke(self.text.valign) tables=vcs.listelements('texttable') tables.sort() self.table.setitems(tables) if self.text.Tt_name=='default': self.font.configure(menubutton_state='disabled') self.spacing.configure(state='disabled') self.expansion.configure(state='disabled') self.Color.configure(state='disabled') if self.text.To_name in ['default','defcentup','defcentdown','defright','defcenter']: self.height.configure(entry_state='disabled') self.angle.configure(state='disabled') self.path.configure(menubutton_state='disabled') self.halign.configure(menubutton_state='disabled') self.valign.configure(menubutton_state='disabled') self.parent.properties_font.component('scrolledlist').setlist(tables) self.parent.properties_font.selectitem(self.text.Tt_name) self.table.setvalue(self.text.Tt_name) try: attribute = '%s.texttable'%self.parent_Name self.parent.set_value(attribute,self.text.Tt_name) except: ## self.parent.dialog.invoke('Apply') pass orientations=vcs.listelements('textorientation') ## self.parent.properties_orientation.configure(scrolledlist_items=tables) self.parent.properties_orientation.component('scrolledlist').setlist(orientations) self.parent.properties_orientation.selectitem(self.text.To_name) orientations.sort() self.orientation.setitems(orientations) self.orientation.setvalue(self.text.To_name) try: attribute = '%s.textorientation'%self.parent_Name self.parent.set_value(attribute,self.text.To_name) except: self.parent.dialog.invoke('Apply') pass self.setfont() return
def get_cmaps(): cmaps = {} for cmap in vcs.listelements('colormap'): index = vcs.getcolormap(cmap).index cmaps[cmap] = [vcs.getcolormap(cmap).getcolorcell(i) for i in range(256)] return cmaps
def __init__(self): super(TextStyleEditorWidget, self).__init__() self.setPreview(text_style_preview.TextStylePreviewWidget()) # Set up vertical align self.va_group = QtGui.QButtonGroup() va_layout = QtGui.QHBoxLayout() for alignment in ["Top", "Mid", "Bot"]: button = QtGui.QPushButton() button.setText(alignment) button.setCheckable(True) va_layout.addWidget(button) self.va_group.addButton(button) self.va_group.buttonClicked.connect(self.updateButton) va_box = QtGui.QGroupBox() va_box.setLayout(va_layout) va_box.setTitle("Vertical Align") # Set up horizontal group self.ha_group = QtGui.QButtonGroup() ha_layout = QtGui.QHBoxLayout() for alignment in ["Left", "Center", "Right"]: button = QtGui.QPushButton() button.setText(alignment) button.setCheckable(True) ha_layout.addWidget(button) self.ha_group.addButton(button) self.ha_group.buttonClicked.connect(self.updateButton) ha_box = QtGui.QGroupBox() ha_box.setLayout(ha_layout) ha_box.setTitle("Horizontal Align") # First row align_angle_row = QtGui.QHBoxLayout() align_angle_row.addWidget(va_box) align_angle_row.addWidget(ha_box) align_angle_row.insertStretch(2, 1) # Create labels angle_label = QtGui.QLabel() angle_label.setText("Angle:") font_label = QtGui.QLabel() font_label.setText("Font:") size_label = QtGui.QLabel() size_label.setText("Size:") # angle dial setup self.angle_slider = QtGui.QDial() self.angle_slider.setRange( 90, 450) # set rotate values so dial orientation matches initial text self.angle_slider.setWrapping(True) self.angle_slider.setNotchesVisible(True) self.angle_slider.valueChanged.connect(self.updateAngle) align_angle_row.addWidget(angle_label) align_angle_row.addWidget(self.angle_slider) # Font combobox self.font_box = QtGui.QComboBox() for item in vcs.listelements("font"): self.font_box.addItem(item) self.font_box.currentIndexChanged[str].connect(self.updateFont) # size spin box self.size_box = QtGui.QSpinBox() self.size_box.setRange(1, 128) self.size_box.valueChanged.connect(self.updateSize) font_size_row = QtGui.QHBoxLayout() font_size_row.addWidget(font_label) font_size_row.addWidget(self.font_box) font_size_row.addWidget(size_label) font_size_row.addWidget(self.size_box) font_size_row.insertStretch(2, 3) # Set up wrap self.vertical_layout.insertLayout(1, align_angle_row) self.vertical_layout.insertLayout(2, font_size_row)
def init_elements(self): to = vcs.listelements("textorientation") tt = vcs.listelements("texttable") self.elements = sorted((el for el in tt if el in to))
def __init__(self, canvas=None, gui_parent=None, dialog_parent=None, master=None, t_name='default',o_name='default',Parent=None): self.gui_parent=gui_parent if canvas is None: ## import Canvas ## self.canvas = Canvas.Canvas() self.canvas=vcs.init() else: self.canvas=canvas self.text=self.canvas.gettext(t_name,o_name) if self.text is None: if not t_name in vcs.listelements('texttable'): raise 'Error '+t_name+' is not a valid texttable name' elif not o_name in vcs.listelements('textorientation'): raise 'Error '+o_name+' is not a valid textorientation name' else: raise 'Weird unkwnown error but no text object returned....' self.parent=Parent try: self.parent_Name=self.parent.parent_Name except: pass ## Saves original values self.orig=[] self.save_vals() Tt_color = gui_support.gui_color.Tt_color To_color = gui_support.gui_color.To_color ################################################################################################# # At the moment, this will never happen. When we need to pop this editor up on its own, then we # will revist this case. # if self.gui_parent is None: # self.gui_parent=Tkinter.Toplevel() # #self.gui_parent=Tkinter.Tk(":0.0") # Use the localhost:0.0 for the DISPLAY and screen # self.gui_parent.withdraw() ################################################################################################# title='Text Editor - table: '+self.text.Tt_name+', orientation: '+self.text.To_name self.dialog = Pmw.Dialog(master, title=title, buttons=(), ) self.dialog.withdraw() if gui_support.root_exists(): root = gui_support.root() self.top_parent = root else: root = gui_support.root() self.top_parent = None self.root = root parent=self.dialog.interior() parent.configure(bg=Tt_color) self.cmain_menu = Pmw.MenuBar(parent, hull_relief = 'raised', hull_borderwidth = 2, balloon = gui_support.balloon ) self.cmain_menu.pack(side='top', fill='both') self.cmain_menu.addmenu('File', 'Open/Save VCS Text Objects', tearoff = 1) self.cmain_menu.addmenuitem('File', 'command', 'Open textobject file', label = 'Open TextObject File', command = gui_control.Command( self.evt_open_file, master ), ) self.cmain_menu.addmenuitem('File', 'separator') # # Create the cascade "Save Colormap" menu and its items ## self.cmain_menu.addmenuitem('File', 'command', 'Select Table', ## label = 'Select Table', ## command = self.evt_loadtable, ## ) ## self.cmain_menu.addmenuitem('File', 'command', 'Select Orientation', ## label = 'Select Orientation', ## command = self.evt_loadorientation, ## ) self.cmain_menu.addmenuitem('File', 'command', 'Save TextObject', label = 'Save (i.e Apply changes)', command = self.setfont, ) self.cmain_menu.addmenuitem('File', 'command', 'Copy Table', label = 'Copy Table', command = gui_control.Command( self.evt_save_table_as, self.dialog ), ) self.cmain_menu.addmenuitem('File', 'command', 'Copy Orientation', label = 'Copy Orientation', command = gui_control.Command( self.evt_save_orientation_as, self.dialog ), ) self.cmain_menu.addmenuitem('File', 'command', 'Save to file', label = 'Save To File', command = gui_control.Command( self.evt_save_to_file, master ), ) # Create the cascade "Exit" menu self.cmain_menu.addmenuitem('File', 'separator') self.cmain_menu.addmenuitem('File', 'command', statusHelp='Close TextObject Editor', label = "Exit TextObject Editor", command = self.dialog.destroy, ) ## self.ftype=Tkinter.Frame(parent) ## self.ftype.pack(side='top') self.tprop=Pmw.Group(parent, tag_text='Table', tag_bg=Tt_color, tagindent=10, hull_bg=Tt_color, hull_highlightbackground=Tt_color, hull_highlightcolor=Tt_color, ring_bg=Tt_color, ) self.tprop.pack(expand='yes',fill='both') self.tproperties=self.tprop.interior() self.tproperties.configure(bg=Tt_color) tables=vcs.listelements('texttable') tables.sort() labels=[] self.table=Pmw.OptionMenu(self.tproperties, items=tables, labelpos='w', label_text='Name:', command=self.loadtable, initialitem=self.text.Tt_name, label_bg=Tt_color, hull_bg=Tt_color, menu_bg=Tt_color, menu_activebackground=Tt_color, menubutton_bg=Tt_color, menubutton_activebackground=Tt_color, ) self.table.pack() labels.append(self.table) fonts=vcs.listelements("font") self.font=Pmw.OptionMenu(self.tproperties, items=fonts, labelpos='w', label_text='Font:', label_bg=Tt_color, hull_bg=Tt_color, menu_bg=Tt_color, menu_activebackground=Tt_color, menubutton_bg=Tt_color, menubutton_activebackground=Tt_color, command=self.setfont, ) self.font.pack() labels.append(self.font) f=Tkinter.Frame(self.tproperties,bg=Tt_color) l=Tkinter.Label(f, text='Spacing:', bg=Tt_color, ) l.pack(side='left') self.spacing=Tkinter.Scale(f, bigincrement=10, from_=-50, to=50, orient='horizontal', tickinterval=25, length=200, bg=Tt_color, activebackground=Tt_color, highlightbackground=Tt_color, command=self.setfont, ) self.spacing.pack() labels.append(l) f.pack() f=Tkinter.Frame(self.tproperties,bg=Tt_color) l=Tkinter.Label(f, text='Width:', bg=Tt_color, ) l.pack(side='left') self.expansion=Tkinter.Scale(f, bigincrement=10, from_=50, to=150, orient='horizontal', tickinterval=25, length=200, bg=Tt_color, activebackground=Tt_color, highlightbackground=Tt_color, command=self.setfont, ) self.expansion.pack() labels.append(l) f.pack() f=Tkinter.Frame(self.tproperties,bg=Tt_color) l=Tkinter.Label(f, text='Color:', bg=Tt_color, ) l.pack(side='left') self.Color=Tkinter.Scale(f, bigincrement=50, from_=0, to=255, orient='horizontal', tickinterval=50, length=200, bg=Tt_color, activebackground=Tt_color, highlightbackground=Tt_color, command=self.setfont, ) self.Color.pack() labels.append(l) f.pack() Pmw.alignlabels(labels) labels=[] self.oprop=Pmw.Group(parent,tag_text='Orientation',tagindent=10,tag_bg=To_color,ring_bg=To_color,hull_bg=To_color) self.oprop.pack(expand='yes',fill='both') self.oproperties=self.oprop.interior() self.oproperties.configure(bg=To_color) orientations=vcs.listelements('textorientation') orientations.sort() self.orientation=Pmw.OptionMenu(self.oproperties, items=orientations, labelpos='w', label_text='Name:', label_bg=To_color, hull_bg=To_color, menu_bg=To_color, menu_activebackground=To_color, menubutton_bg=To_color, menubutton_activebackground=To_color, command=self.loadorientation, initialitem=self.text.To_name, ) self.orientation.pack() labels.append(self.orientation) self.height=Pmw.EntryField(self.oproperties, label_text='Size:', labelpos='w', label_justify='left', label_bg=To_color, hull_bg=To_color, validate={'min':0,'validator':'real'}, command=self.setfont, ) self.height.pack() labels.append(self.height) f=Tkinter.Frame(self.oproperties,bg=To_color) l=Tkinter.Label(f, text='Angle:', bg=To_color, ) l.pack(side='left') labels.append(l) self.angle=Tkinter.Scale(f, bigincrement=30, from_=-180, to=180, orient='horizontal', tickinterval=90, length=200, bg=To_color, activebackground=To_color, highlightbackground=To_color, command=self.setfont, ) self.angle.pack() f.pack() paths=["right","left","up","down"] self.path=Pmw.OptionMenu(self.oproperties, items=paths, labelpos='w', label_text='Path:', label_bg=To_color, hull_bg=To_color, menu_bg=To_color, menu_activebackground=To_color, menubutton_bg=To_color, menubutton_activebackground=To_color, command=self.setfont, ) self.path.pack() labels.append(self.path) haligns=["left","center","right"] self.halign=Pmw.OptionMenu(self.oproperties, items=haligns, labelpos='w', label_text='Halign:', label_bg=To_color, hull_bg=To_color, menu_bg=To_color, menu_activebackground=To_color, menubutton_bg=To_color, menubutton_activebackground=To_color, command=self.setfont, ) self.halign.pack() labels.append(self.halign) valigns=["top","cap","half","base","bottom"] self.valign=Pmw.OptionMenu(self.oproperties, items=valigns, labelpos='w', label_text='Valign:', label_bg=To_color, hull_bg=To_color, menu_bg=To_color, menu_activebackground=To_color, menubutton_bg=To_color, menubutton_activebackground=To_color, command=self.setfont, ) self.valign.pack() labels.append(self.valign) Pmw.alignlabels(labels) self.fbuttons=Tkinter.Frame(parent) self.fbuttons.pack() ## b0=Tkinter.Button(self.fbuttons, ## text='Preview', ## command=self.setfont) ## b0.pack(side='left') b1=Tkinter.Button(self.fbuttons, text='Cancel', command=self.cancel) b1.pack(side='left') b2=Tkinter.Button(self.fbuttons, text='Apply', command=self.exit) b2.pack(side='left') b3=Tkinter.Button(self.fbuttons, text='Revert', command=self.reset) b3.pack(side='left') self.setgui() # Position dialog popup if dialog_parent is not None: parent_geom = dialog_parent.geometry() geom = string.split(parent_geom, '+') d1 = string.atoi( geom[1] ) d2 = string.atoi( geom[2] ) self.dialog.activate( geometry="+%d+%d" % (d1, d2) ) else: self.dialog.activate(geometry = 'centerscreenalways') return
def _plotInternal(self): """Overrides baseclass implementation.""" tmpLevels = [] tmpColors = [] tmpLineWidths = [] tmpLineStyles = [] linewidth = self._gm.linewidths self.extendAttribute(linewidth, default=1.0) linestyle = self._gm.line self.extendAttribute(linestyle, default='solid') plotting_dataset_bounds = self.getPlottingBounds() x1, x2, y1, y2 = plotting_dataset_bounds for i, l in enumerate(self._contourLevels): if i == 0: W = linewidth[i] S = linestyle[i] C = [self._contourColors[i]] if l == 1.e20: L = [-1.e20] else: L = [l] else: if W == linewidth[i] and S == linestyle[i]: # Ok same style and width, lets keep going L.append(l) C.append(self._contourColors[i]) else: tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineStyles.append(S) L = [l] C = [self._contourColors[i]] W = linewidth[i] S = linestyle[i] tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineStyles.append(S) cots = [] textprops = [] luts = [] actors = [] mappers = [] if self._gm.label and (self._gm.text or self._gm.textcolors): # Text objects: if self._gm.text: texts = self._gm.text while len(texts) < len(self._contourLevels): texts.append(texts[-1]) else: texts = [None] * len(self._contourLevels) # Custom colors: if self._gm.textcolors: colorOverrides = self._gm.textcolors while len(colorOverrides) < len(self._contourLevels): colorOverrides.append(colorOverrides[-1]) else: colorOverrides = [None] * len(self._gm.text) # Custom background colors and opacities: backgroundColors = self._gm.labelbackgroundcolors if backgroundColors: while len(backgroundColors) < len(self._contourLevels): backgroundColors.append(backgroundColors[-1]) backgroundOpacities = self._gm.labelbackgroundopacities if backgroundOpacities: while len(backgroundOpacities) < len(self._contourLevels): backgroundOpacities.append(backgroundOpacities[-1]) countLevels = 0 vp = self._resultDict.get( 'ratio_autot_viewport', [self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2]) dataset_renderer = None xScale, yScale = (1, 1) for i, l in enumerate(tmpLevels): numLevels = len(l) cot = vtk.vtkContourFilter() if self._hasCellData: cot.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) else: cot.SetInputData(self._vtkDataSet) cot.SetNumberOfContours(numLevels) for n in range(numLevels): cot.SetValue(n, l[n]) # TODO remove update cot.Update() lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(len(tmpColors[i])) cmap = self.getColorMap() for n, col in enumerate(tmpColors[i]): r, g, b, a = self.getColorIndexOrRGBA(cmap, col) lut.SetTableValue(n, r / 100., g / 100., b / 100., a / 100.) # Setup isoline labels if self._gm.label: # Setup label mapping array: tpropMap = vtk.vtkDoubleArray() tpropMap.SetNumberOfComponents(1) tpropMap.SetNumberOfTuples(numLevels) for n, val in enumerate(l): tpropMap.SetTuple(n, [val]) # Prep text properties: tprops = vtk.vtkTextPropertyCollection() if self._gm.text or self._gm.textcolors: ttexts = texts[countLevels:(countLevels + len(l))] for idx, tc in enumerate(ttexts): if vcs.queries.istextcombined(tc): tt, to = tuple(tc.name.split(":::")) elif tc is None: tt = "default" to = "default" elif vcs.queries.istexttable(tc): tt = tc.name to = "default" elif vcs.queries.istextorientation(tc): to = tc.name tt = "default" elif isinstance(tc, (str, unicode)): sp = tc.split(":::") if len(sp) == 2: tt = sp[0] to = sp[1] else: # Hum don't know what do do with this if sp[0] in vcs.listelements("textcombined"): tc = vcs.gettextcombined(tc) tt, to = tuple(tc.name.split(":::")) elif sp[0] in vcs.listelements("textorientation"): to = sp[0] tt = "default" elif sp[0] in vcs.listelements("texttable"): tt = sp[0] to = "default" colorOverride = colorOverrides[countLevels + idx] if colorOverride is not None: tt = vcs.createtexttable(None, tt) tt.color = colorOverride tt = tt.name if backgroundColors is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundcolor = backgroundColors[countLevels + idx] if backgroundOpacities is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundopacity = backgroundOpacities[countLevels + idx] tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), to, tt, cmap=cmap) tprops.AddItem(tprop) if colorOverride is not None: del(vcs.elements["texttable"][tt]) else: # No text properties specified. Use the default: tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), cmap=cmap) tprops.AddItem(tprop) textprops.append(tprops) mapper = vtk.vtkLabeledContourMapper() mapper.SetTextProperties(tprops) mapper.SetTextPropertyMapping(tpropMap) mapper.SetLabelVisibility(1) mapper.SetSkipDistance(self._gm.labelskipdistance) pdMapper = mapper.GetPolyDataMapper() luts.append([lut, [l[0], l[-1], False]]) else: # No isoline labels: mapper = vtk.vtkPolyDataMapper() pdMapper = mapper luts.append([lut, [l[0], l[-1], False]]) pdMapper.SetLookupTable(lut) pdMapper.SetScalarRange(l[0], l[-1]) pdMapper.SetScalarModeToUsePointData() stripper = vtk.vtkStripper() stripper.SetInputConnection(cot.GetOutputPort()) mapper.SetInputConnection(stripper.GetOutputPort()) # TODO remove update, make pipeline stripper.Update() mappers.append(mapper) cots.append(cot) # Create actor to add to scene act = vtk.vtkActor() act.SetMapper(mapper) # Set line properties here p = act.GetProperty() p.SetLineWidth(tmpLineWidths[i]) vcs2vtk.stippleLine(p, tmpLineStyles[i]) if self._vtkGeoTransform is None: # If using geofilter on wireframed does not get wrppaed not # sure why so sticking to many mappers act = vcs2vtk.doWrap(act, plotting_dataset_bounds, self._dataWrapModulo) actors.append([act, plotting_dataset_bounds]) # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) dataset_renderer, xScale, yScale = self._context().fitToViewport( act, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSet.GetBounds(), geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=(dataset_renderer is None)) countLevels += len(l) if len(textprops) > 0: self._resultDict["vtk_backend_contours_labels_text_properties"] = \ textprops if len(luts) > 0: if self._gm.label: self._resultDict["vtk_backend_labeled_luts"] = luts else: self._resultDict["vtk_backend_luts"] = luts if len(cots) > 0: self._resultDict["vtk_backend_contours"] = cots if self._maskedDataMapper is not None: mappers.insert(0, self._maskedDataMapper) act = vtk.vtkActor() act.SetMapper(self._maskedDataMapper) if self._vtkGeoTransform is None: # If using geofilter on wireframed does not get wrppaed not # sure why so sticking to many mappers act = vcs2vtk.doWrap(act, plotting_dataset_bounds, self._dataWrapModulo) actors.append([act, self._maskedDataMapper, plotting_dataset_bounds]) # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) self._context().fitToViewport( act, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSet.GetBounds(), geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=True) self._resultDict["vtk_backend_actors"] = actors t = self._originalData1.getTime() if self._originalData1.ndim > 2: z = self._originalData1.getAxis(-3) else: z = None kwargs = {"vtk_backend_grid": self._vtkDataSet, "dataset_bounds": self._vtkDataSetBounds, "plotting_dataset_bounds": plotting_dataset_bounds, "vtk_backend_geo": self._vtkGeoTransform} if ("ratio_autot_viewport" in self._resultDict): kwargs["ratio_autot_viewport"] = vp self._resultDict.update(self._context().renderTemplate( self._template, self._data1, self._gm, t, z, **kwargs)) if self._context().canvas._continents is None: self._useContinents = False if self._useContinents: projection = vcs.elements["projection"][self._gm.projection] continents_renderer, xScale, yScale = self._context().plotContinents( plotting_dataset_bounds, projection, self._dataWrapModulo, vp, self._template.data.priority, vtk_backend_grid=self._vtkDataSet, dataset_bounds=self._vtkDataSetBounds)
def __init__(self, axis, parent=None): super(AxisEditorWidget, self).__init__() self.axis = axis self.state = None # create layout so you can set the preview self.horizontal_layout = QtGui.QHBoxLayout() # create labels tickmarks_label = QtGui.QLabel("Tickmarks:") negative_label = QtGui.QLabel("Negative:") ticks_label = QtGui.QLabel("Ticks:") step_label = QtGui.QLabel("Tick Step:") show_mini_label = QtGui.QLabel("Show Mini Ticks:") mini_per_tick_label = QtGui.QLabel("Mini-Ticks Per Tick:") preset_label = QtGui.QLabel("Preset:") # create rows tickmarks_row = QtGui.QHBoxLayout() preset_row = QtGui.QHBoxLayout() ticks_row = QtGui.QHBoxLayout() mini_ticks_row = QtGui.QHBoxLayout() # create widgets self.ticks_widget = QtGui.QWidget() self.ticks_widget.setLayout(ticks_row) self.preset_widget = QtGui.QWidget() self.preset_widget.setLayout(preset_row) self.dict_widget = DictEditorWidget() self.dict_widget.dictEdited.connect(self.updateAxisWithDict) # set up scrollable for dict editor self.scroll_area = QtGui.QScrollArea() self.scroll_area.setWidget(self.dict_widget) self.scroll_area.setWidgetResizable(True) # Create radio buttons and group them self.tickmark_button_group = QtGui.QButtonGroup() tickmarks_row.addWidget(tickmarks_label) for name in ["Auto", "Even", "Manual"]: button = QtGui.QRadioButton(name) tickmarks_row.addWidget(button) if name == "Auto": button.setChecked(True) self.tickmark_button_group.addButton(button) self.tickmark_button_group.buttonClicked.connect(self.updateTickmark) # create preset combo box # This in only being tracked for debugging preset_box = QtGui.QComboBox() preset_box.addItem("default") preset_box.addItems(vcs.listelements("list")) preset_box.currentIndexChanged[str].connect(self.updatePreset) preset_row.addWidget(preset_label) preset_row.addWidget(preset_box) # create slider for Ticks self.ticks_slider = QtGui.QSlider() self.ticks_slider.setRange(1, 100) self.ticks_slider.setOrientation(QtCore.Qt.Horizontal) self.ticks_slider.sliderMoved.connect(self.updateTicks) # create step edit box step_validator = QtGui.QDoubleValidator() self.step_edit = QtGui.QLineEdit() self.step_edit.setValidator(step_validator) self.step_edit.textEdited.connect(lambda: QtCore.QTimer.singleShot(1000, self.updateStep)) self.step_edit.editingFinished.connect(self.updateStep) # create negative check box self.negative_check = QtGui.QCheckBox() self.negative_check.clicked.connect(self.updateTickSign) ticks_row.addWidget(negative_label) ticks_row.addWidget(self.negative_check) ticks_row.addWidget(ticks_label) ticks_row.addWidget(self.ticks_slider) ticks_row.addWidget(step_label) ticks_row.addWidget(self.step_edit) # create show mini ticks check box show_mini_check_box = QtGui.QCheckBox() show_mini_check_box.stateChanged.connect(self.updateShowMiniTicks) # create mini tick spin box mini_tick_box = QtGui.QSpinBox() mini_tick_box.setRange(0, 255) mini_tick_box.valueChanged.connect(self.updateMiniTicks) mini_ticks_row.addWidget(show_mini_label) mini_ticks_row.addWidget(show_mini_check_box) mini_ticks_row.addWidget(mini_per_tick_label) mini_ticks_row.addWidget(mini_tick_box) self.adjuster_layout = QtGui.QVBoxLayout() self.adjuster_layout.insertLayout(0, tickmarks_row) self.adjuster_layout.insertWidget(1, self.preset_widget) self.adjuster_layout.insertLayout(2, mini_ticks_row) self.horizontal_layout.addLayout(self.adjuster_layout) self.vertical_layout.insertLayout(0, self.horizontal_layout) self.setPreview(AxisPreviewWidget())
def __init__(self, canvas=None, gui_parent=None, dialog_parent=None, master=None, name="default", Parent=None): self.gui_parent = gui_parent if canvas is None: self.canvas = vcs.init() else: self.canvas = canvas self.line = self.canvas.getline(name) if self.line is None: if not name in vcs.listelements("line"): raise "Error " + t_name + " is not a valid line name" else: raise "Weird unkwnown error but no line object returned...." self.parent = Parent self.parent_Name = self.parent.parent_Name ## Saves original values self.orig = [] self.save_vals() L_color = gui_support.gui_color.L_color if self.gui_parent is None: self.gui_parent = Tkinter.Toplevel() # self.gui_parent=Tkinter.Tk(":0.0") # Use the localhost:0.0 for the DISPLAY and screen self.gui_parent.withdraw() title = "Line Editor - table: " + self.line.name self.dialog = Pmw.Dialog(master, title=title, buttons=()) self.dialog.withdraw() if gui_support.root_exists(): root = gui_support.root() self.top_parent = root else: root = gui_support.root() self.top_parent = None self.root = root parent = self.dialog.interior() parent.configure(bg=L_color) self.cmain_menu = Pmw.MenuBar(parent, hull_relief="raised", hull_borderwidth=2, balloon=gui_support.balloon) self.cmain_menu.pack(side="top", fill="both") self.cmain_menu.addmenu("File", "Open/Save VCS Line Objects", tearoff=1) self.cmain_menu.addmenuitem( "File", "command", "Open line object file", label="Open LineObject File", command=self.evt_open_file ) self.cmain_menu.addmenuitem("File", "separator") # # Create the cascade "Save Colormap" menu and its items self.cmain_menu.addmenuitem( "File", "command", "Save Line", label="Save (i.e Apply changes)", command=self.setline ) self.cmain_menu.addmenuitem("File", "command", "Copy Line", label="Copy Line", command=self.evt_save_line_as) self.cmain_menu.addmenuitem( "File", "command", "Save to file", label="Save To File", command=self.evt_save_to_file ) # Create the cascade "Exit" menu self.cmain_menu.addmenuitem("File", "separator") self.cmain_menu.addmenuitem( "File", "command", statusHelp="Close Line Editor", label="Exit Line Editor", command=self.dialog.destroy ) ## self.ftype=Tkinter.Frame(parent) ## self.ftype.pack(side='top') self.tprop = Pmw.Group( parent, tag_text="Line", tag_bg=L_color, tagindent=10, hull_bg=L_color, hull_highlightbackground=L_color, hull_highlightcolor=L_color, ring_bg=L_color, ) self.tprop.pack(expand="yes", fill="both") self.tproperties = self.tprop.interior() self.tproperties.configure(bg=L_color) lines = vcs.listelements("line") lines.sort() labels = [] self.Line = Pmw.OptionMenu( self.tproperties, items=lines, labelpos="w", label_text="Name:", command=self.loadline, initialitem=self.line.name, label_bg=L_color, hull_bg=L_color, menu_bg=L_color, menu_activebackground=L_color, menubutton_bg=L_color, menubutton_activebackground=L_color, ) self.Line.pack() labels.append(self.Line) items = ["solid", "dash", "dot", "dash-dot", "long-dash"] self.type = Pmw.OptionMenu( self.tproperties, items=items, labelpos="w", label_text="Type:", label_bg=L_color, hull_bg=L_color, menu_bg=L_color, menu_activebackground=L_color, menubutton_bg=L_color, menubutton_activebackground=L_color, command=self.setline, ) self.type.pack() labels.append(self.type) f = Tkinter.Frame(self.tproperties, bg=L_color) l = Tkinter.Label(f, text="Width:", bg=L_color) l.pack(side="left") self.width = Tkinter.Scale( f, bigincrement=10, from_=1, to=300, orient="horizontal", tickinterval=50, length=200, bg=L_color, activebackground=L_color, highlightbackground=L_color, command=self.setline, ) self.width.pack() labels.append(l) f.pack() f = Tkinter.Frame(self.tproperties, bg=L_color) l = Tkinter.Label(f, text="Color:", bg=L_color) l.pack(side="left") self.Color = Tkinter.Scale( f, bigincrement=50, from_=0, to=255, orient="horizontal", tickinterval=50, length=200, bg=L_color, activebackground=L_color, highlightbackground=L_color, command=self.setline, ) self.Color.pack() labels.append(l) f.pack() Pmw.alignlabels(labels) self.fbuttons = Tkinter.Frame(parent) self.fbuttons.pack() ## b0=Tkinter.Button(self.fbuttons, ## text='Preview', ## command=self.setfont) ## b0.pack(side='left') b1 = Tkinter.Button(self.fbuttons, text="Cancel", command=self.cancel) b1.pack(side="left") b2 = Tkinter.Button(self.fbuttons, text="Apply", command=self.exit) b2.pack(side="left") b3 = Tkinter.Button(self.fbuttons, text="Revert", command=self.reset) b3.pack(side="left") self.setgui() # Position dialog popup if dialog_parent is not None: parent_geom = dialog_parent.geometry() geom = string.split(parent_geom, "+") d1 = string.atoi(geom[1]) d2 = string.atoi(geom[2]) self.dialog.activate(geometry="+%d+%d" % (d1, d2)) else: self.dialog.activate(geometry="centerscreenalways") return
def test_vcs_read_old_2(self): testfile = os.path.join("uvcdat-testdata", "data", "vcs", "old_2.scr") Ns = {} Es = {} for k in list(vcs.elements.keys()): Ns[k] = len(list(vcs.elements[k].keys())) Es[k] = vcs.listelements(k) vcs.scriptrun(testfile) Ns2 = {} for k in list(vcs.elements.keys()): Ns2[k] = len(list(vcs.elements[k].keys())) diffs = { 'projection': 0, 'colormap': 4, 'isofill': 102, 'marker': 15, '3d_dual_scalar': 0, 'texttable': 1, '3d_scalar': 0, 'fillarea': 404, 'font': 0, '3d_vector': 0, '1d': 19, 'template': 128, 'textcombined': 0, 'textorientation': 0, 'xvsy': 0, 'xyvsy': 15, 'isoline': 3, 'boxfill': 3, 'fontNumber': 0, 'line': 16, 'meshfill': 0, 'yxvsx': 17, 'taylordiagram': 1, 'list': 68, 'display': 0, 'vector': 5, 'scatter': 2, "streamline": 0 } for k in list(vcs.elements.keys()): print("Cheking number of new elements for", k) self.assertEqual(diffs[k], Ns2[k] - Ns[k]) gm = vcs.getmarker("navy") self.assertEqual(gm.type, ['dot']) self.assertEqual(gm.size, [2]) self.assertEqual(gm.color, [250]) gm = vcs.getisofill("AMIP2_psl") self.assertEqual( gm.levels, [[-1e+20, 97000.0], [97000.0, 97500.0], [97500.0, 98000.0], [98000.0, 98500.0], [98500.0, 99000.0], [99000.0, 99500.0], [99500.0, 100000.0], [100000.0, 100500.0], [100500.0, 101000.0], [101000.0, 101500.0], [101500.0, 102000.0], [102000.0, 102500.0], [102500.0, 103000.0], [103000.0, 103500.0], [103500.0, 104000.0], [104000.0, 1e+20]]) self.assertTrue(gm.ext_2) self.assertEqual(gm.ymtics1, "lat5") self.assertEqual(gm.fillareastyle, "solid") self.assertEqual( gm.fillareacolors, [30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 35, 36])
def _plotInternal(self): """Overrides baseclass implementation.""" tmpLevels = [] tmpColors = [] tmpLineWidths = [] tmpLineTypes = [] linewidth = self._gm.linewidths self.extendAttribute(linewidth, default=1.0) linetype = self._gm.linetypes self.extendAttribute(linetype, default='solid') plotting_dataset_bounds = self.getPlottingBounds() x1, x2, y1, y2 = plotting_dataset_bounds for i, lv_tmp in enumerate(self._contourLevels): if i == 0: W = linewidth[i] S = linetype[i] C = [self._contourColors[i]] if lv_tmp == 1.e20: L = [-1.e20] else: L = [lv_tmp] else: if W == linewidth[i] and S == linetype[i]: # Ok same style and width, lets keep going L.append(lv_tmp) C.append(self._contourColors[i]) else: tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineTypes.append(S) L = [lv_tmp] C = [self._contourColors[i]] W = linewidth[i] S = linetype[i] tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineTypes.append(S) cots = [] textprops = [] luts = [] actors = [] mappers = [] if self._gm.label and (self._gm.text or self._gm.textcolors): # Text objects: if self._gm.text: texts = self._gm.text while len(texts) < len(self._contourLevels): texts.append(texts[-1]) else: texts = [None] * len(self._contourLevels) # Custom colors: if self._gm.textcolors: colorOverrides = self._gm.textcolors while len(colorOverrides) < len(self._contourLevels): colorOverrides.append(colorOverrides[-1]) else: colorOverrides = [None] * len(self._gm.text) # Custom background colors and opacities: backgroundColors = self._gm.labelbackgroundcolors if backgroundColors: while len(backgroundColors) < len(self._contourLevels): backgroundColors.append(backgroundColors[-1]) backgroundOpacities = self._gm.labelbackgroundopacities if backgroundOpacities: while len(backgroundOpacities) < len(self._contourLevels): backgroundOpacities.append(backgroundOpacities[-1]) countLevels = 0 vp = self._resultDict.get('ratio_autot_viewport', [ self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2 ]) dataset_renderer = None xScale, yScale = (1, 1) for i, l in enumerate(tmpLevels): numLevels = len(l) cot = vtk.vtkContourFilter() if self._hasCellData: cot.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) else: cot.SetInputData(self._vtkDataSet) cot.SetNumberOfContours(numLevels) for n in range(numLevels): cot.SetValue(n, l[n]) # TODO remove update cot.Update() lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(len(tmpColors[i])) cmap = self.getColorMap() for n, col in enumerate(tmpColors[i]): r, g, b, a = self.getColorIndexOrRGBA(cmap, col) lut.SetTableValue(n, r / 100., g / 100., b / 100., a / 100.) # Setup isoline labels if self._gm.label: # Setup label mapping array: tpropMap = vtk.vtkDoubleArray() tpropMap.SetNumberOfComponents(1) tpropMap.SetNumberOfTuples(numLevels) for n, val in enumerate(l): tpropMap.SetTuple(n, [val]) # Prep text properties: tprops = vtk.vtkTextPropertyCollection() if self._gm.text or self._gm.textcolors: ttexts = texts[countLevels:(countLevels + len(l))] for idx, tc in enumerate(ttexts): if vcs.queries.istextcombined(tc): tt, to = tuple(tc.name.split(":::")) elif tc is None: tt = "default" to = "default" elif vcs.queries.istexttable(tc): tt = tc.name to = "default" elif vcs.queries.istextorientation(tc): to = tc.name tt = "default" elif isinstance(tc, str): sp = tc.split(":::") if len(sp) == 2: tt = sp[0] to = sp[1] else: # Hum don't know what do do with this if sp[0] in vcs.listelements("textcombined"): tc = vcs.gettextcombined(tc) tt, to = tuple(tc.name.split(":::")) elif sp[0] in vcs.listelements( "textorientation"): to = sp[0] tt = "default" elif sp[0] in vcs.listelements("texttable"): tt = sp[0] to = "default" colorOverride = colorOverrides[countLevels + idx] if colorOverride is not None: tt = vcs.createtexttable(None, tt) tt.color = colorOverride tt = tt.name if backgroundColors is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundcolor = backgroundColors[ countLevels + idx] if backgroundOpacities is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundopacity = backgroundOpacities[ countLevels + idx] tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty( tprop, self._context().renWin.GetSize(), to, tt, cmap=cmap) tprops.AddItem(tprop) if colorOverride is not None: del (vcs.elements["texttable"][tt]) else: # No text properties specified. Use the default: tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), cmap=cmap) tprops.AddItem(tprop) textprops.append(tprops) mapper = vtk.vtkLabeledContourMapper() mapper.SetTextProperties(tprops) mapper.SetTextPropertyMapping(tpropMap) mapper.SetLabelVisibility(1) mapper.SetSkipDistance(self._gm.labelskipdistance) pdMapper = mapper.GetPolyDataMapper() luts.append([lut, [l[0], l[-1], False]]) else: # No isoline labels: mapper = vtk.vtkPolyDataMapper() pdMapper = mapper luts.append([lut, [l[0], l[-1], False]]) pdMapper.SetLookupTable(lut) pdMapper.SetScalarRange(l[0], l[-1]) pdMapper.SetScalarModeToUsePointData() stripper = vtk.vtkStripper() stripper.SetInputConnection(cot.GetOutputPort()) mapper.SetInputConnection(stripper.GetOutputPort()) # TODO remove update, make pipeline stripper.Update() mappers.append(mapper) cots.append(cot) # Create actor to add to scene act = vtk.vtkActor() act.SetMapper(mapper) # Set line properties here p = act.GetProperty() p.SetLineWidth(tmpLineWidths[i]) vcs2vtk.stippleLine(p, tmpLineTypes[i]) actors.append([act, plotting_dataset_bounds]) # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) dataset_renderer, xScale, yScale = self._context().fitToViewport( act, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSetBoundsNoMask, geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=(dataset_renderer is None)) countLevels += len(l) if len(textprops) > 0: self._resultDict["vtk_backend_contours_labels_text_properties"] = \ textprops if len(luts) > 0: if self._gm.label: self._resultDict["vtk_backend_labeled_luts"] = luts else: self._resultDict["vtk_backend_luts"] = luts if len(cots) > 0: self._resultDict["vtk_backend_contours"] = cots if self._maskedDataMapper is not None: mappers.insert(0, self._maskedDataMapper) act = vtk.vtkActor() act.SetMapper(self._maskedDataMapper) actors.append( [act, self._maskedDataMapper, plotting_dataset_bounds]) # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) self._context().fitToViewport( act, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSetBoundsNoMask, geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=True) self._resultDict["vtk_backend_actors"] = actors t = self._originalData1.getTime() if self._originalData1.ndim > 2: z = self._originalData1.getAxis(-3) else: z = None kwargs = { "vtk_backend_grid": self._vtkDataSet, "dataset_bounds": self._vtkDataSetBounds, "plotting_dataset_bounds": plotting_dataset_bounds, "vtk_dataset_bounds_no_mask": self._vtkDataSetBoundsNoMask, "vtk_backend_geo": self._vtkGeoTransform } if ("ratio_autot_viewport" in self._resultDict): kwargs["ratio_autot_viewport"] = vp self._resultDict.update(self._context().renderTemplate( self._template, self._data1, self._gm, t, z, **kwargs)) if self._context().canvas._continents is None: self._useContinents = False if self._useContinents: projection = vcs.elements["projection"][self._gm.projection] continents_renderer, xScale, yScale = self._context( ).plotContinents(plotting_dataset_bounds, projection, self._dataWrapModulo, vp, self._template.data.priority, **kwargs)
def testLoadMPLCmaps(self): import vcs original = vcs.listelements("colormap") vcs.utils.loadmatplotlibcolormaps() mpl = vcs.listelements("colormap") self.assertGreater(len(mpl), len(original))
def __init__(self): super(TextStyleEditorWidget, self).__init__() self.setPreview(text_style_preview.TextStylePreviewWidget()) # Set up vertical align self.va_group = QtGui.QButtonGroup() va_layout = QtGui.QHBoxLayout() for alignment in ["Top", "Mid", "Bot"]: button = QtGui.QPushButton() button.setText(alignment) button.setCheckable(True) va_layout.addWidget(button) self.va_group.addButton(button) self.va_group.buttonClicked.connect(self.updateButton) va_box = QtGui.QGroupBox() va_box.setLayout(va_layout) va_box.setTitle("Vertical Align") # Set up horizontal group self.ha_group = QtGui.QButtonGroup() ha_layout = QtGui.QHBoxLayout() for alignment in ["Left", "Center", "Right"]: button = QtGui.QPushButton() button.setText(alignment) button.setCheckable(True) ha_layout.addWidget(button) self.ha_group.addButton(button) self.ha_group.buttonClicked.connect(self.updateButton) ha_box = QtGui.QGroupBox() ha_box.setLayout(ha_layout) ha_box.setTitle("Horizontal Align") # First row align_angle_row = QtGui.QHBoxLayout() align_angle_row.addWidget(va_box) align_angle_row.addWidget(ha_box) align_angle_row.insertStretch(2, 1) # Create labels angle_label = QtGui.QLabel() angle_label.setText("Angle:") font_label = QtGui.QLabel() font_label.setText("Font:") size_label = QtGui.QLabel() size_label.setText("Size:") # angle dial setup self.angle_slider = QtGui.QDial() self.angle_slider.setRange(90, 450) # set rotate values so dial orientation matches initial text self.angle_slider.setWrapping(True) self.angle_slider.setNotchesVisible(True) self.angle_slider.valueChanged.connect(self.updateAngle) align_angle_row.addWidget(angle_label) align_angle_row.addWidget(self.angle_slider) # Font combobox self.font_box = QtGui.QComboBox() for item in vcs.listelements("font"): self.font_box.addItem(item) self.font_box.currentIndexChanged[str].connect(self.updateFont) # size spin box self.size_box = QtGui.QSpinBox() self.size_box.setRange(1, 128) self.size_box.valueChanged.connect(self.updateSize) font_size_row = QtGui.QHBoxLayout() font_size_row.addWidget(font_label) font_size_row.addWidget(self.font_box) font_size_row.addWidget(size_label) font_size_row.addWidget(self.size_box) font_size_row.insertStretch(2, 3) # Set up wrap self.vertical_layout.insertLayout(1, align_angle_row) self.vertical_layout.insertLayout(2, font_size_row)
def __init__(self, mode=COLORMAP_MODE, parent=None): QtGui.QColorDialog.__init__(self, parent) self.parent = parent self.setOption(QtGui.QColorDialog.DontUseNativeDialog, True) self.setOption(QtGui.QColorDialog.NoButtons) self.setOption(QtGui.QColorDialog.ShowAlphaChannel, True) l = self.layout() # Colormap selection Area f = QtGui.QFrame() h = QtGui.QHBoxLayout() self.colormap = QtGui.QComboBox(self) colormaps = sorted(vcs.listelements("colormap")) for i in colormaps: self.colormap.addItem(i) h.addWidget(self.colormap) self.newname = QtGui.QLineEdit() h.addWidget(self.newname) b = QtGui.QPushButton("Rename") b.clicked.connect(self.renamed) h.addWidget(b) f.setLayout(h) l.addWidget(f) self.mode = mode # Apply/Cancel/Save/Reset/Blend buttons buttons = QtGui.QDialogButtonBox() buttons.layout().addSpacing(30) self.accept = buttons.addButton(u"Accept", QtGui.QDialogButtonBox.AcceptRole) self.accept.setDefault(True) self.accept.setAutoDefault(True) if mode == COLORMAP_MODE: self.setWindowTitle("Choose Colormap") self.accept.setToolTip("Use Colormap") else: self.setWindowTitle("Choose Color") self.accept.setEnabled(False) self.accept.setToolTip("Use Color") export = QtGui.QPushButton("Export") export.setToolTip("Save Colormap To File") buttons.addButton(export, QtGui.QDialogButtonBox.AcceptRole) buttons.addButton(QtGui.QDialogButtonBox.Open).setToolTip( "Open existing colormap") buttons.addButton("Blend", QtGui.QDialogButtonBox.HelpRole) \ .setToolTip("Blend From First To Last Highlighted Colors") buttons.addButton(QtGui.QDialogButtonBox.Reset).setToolTip( "Reset Changes") buttons.addButton(QtGui.QDialogButtonBox.Apply).setToolTip( "Apply Changes") buttons.addButton(QtGui.QDialogButtonBox.Cancel).setToolTip( "Close Colormap") self.accept.clicked.connect(self.acceptClicked) buttons.button(QtGui.QDialogButtonBox.Apply).clicked.connect(self.applyChanges) buttons.button(QtGui.QDialogButtonBox.Open).clicked.connect(self.openColormap) buttons.button(QtGui.QDialogButtonBox.Cancel).clicked.connect(self.rejectChanges) export.clicked.connect(self.save) buttons.button(QtGui.QDialogButtonBox.Reset).clicked.connect(self.resetChanges) buttons.helpRequested.connect(self.blend) self.buttons = buttons self.colors = color_table.ColormapTable(16) self.scrollArea = QtGui.QScrollArea() self.scrollArea.setWidget(self.colors) self.scrollArea.setWidgetResizable(True) l.addWidget(self.scrollArea) l.addWidget(self.buttons) # SIGNALS self.colormap.currentIndexChanged.connect(self.colorMapComboChanged) self.currentColorChanged.connect(self.colorChanged) self.colors.singleColorSelected.connect(self.selectedCell) self.colors.cmap = str(self.colormap.currentText()) self.cell = None