コード例 #1
0
    def __init__(self):
        SimplePanel.__init__(self)

        panel = VerticalPanel()
        panel.setBorderWidth(1)

        panel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER)
        panel.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE)

        part1 = Label("Part 1")
        part2 = Label("Part 2")
        part3 = Label("Part 3")
        part4 = Label("Part 4")

        panel.add(part1)
        panel.add(part2)
        panel.add(part3)
        panel.add(part4)

        panel.setCellHeight(part1, "10%")
        panel.setCellHeight(part2, "70%")
        panel.setCellHeight(part3, "10%")
        panel.setCellHeight(part4, "10%")

        panel.setCellHorizontalAlignment(part3, HasAlignment.ALIGN_RIGHT)

        panel.setWidth("50%")
        panel.setHeight("300px")

        self.add(panel)
コード例 #2
0
ファイル: verticalPanel.py プロジェクト: pombredanne/pyjamas
    def __init__(self):
        SimplePanel.__init__(self)

        panel = VerticalPanel()
        panel.setBorderWidth(1)

        panel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER)
        panel.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE)

        part1 = Label("Part 1")
        part2 = Label("Part 2")
        part3 = Label("Part 3")
        part4 = Label("Part 4")

        panel.add(part1)
        panel.add(part2)
        panel.add(part3)
        panel.add(part4)

        panel.setCellHeight(part1, "10%")
        panel.setCellHeight(part2, "70%")
        panel.setCellHeight(part3, "10%")
        panel.setCellHeight(part4, "10%")

        panel.setCellHorizontalAlignment(part3, HasAlignment.ALIGN_RIGHT)

        panel.setWidth("50%")
        panel.setHeight("300px")

        self.add(panel)
コード例 #3
0
    def makeBox(self, label):
        wrapper = VerticalPanel()
        wrapper.setBorderWidth(1)
        wrapper.add(HTML(label))
        DOM.setAttribute(wrapper.getTable(), "cellPadding", "10")
        DOM.setAttribute(wrapper.getTable(), "bgColor", "#C3D9FF")

        return wrapper
コード例 #4
0
    def makeBox(self, label):
        wrapper = VerticalPanel()
        wrapper.setBorderWidth(1)
        wrapper.add(HTML(label))
        DOM.setAttribute(wrapper.getTable(), "cellPadding", "10")
        DOM.setAttribute(wrapper.getTable(), "bgColor", "#C3D9FF")

        return wrapper
コード例 #5
0
ファイル: uiHelpers.py プロジェクト: FreakTheMighty/pyjamas
def border(contents):
    """ Draw a border around the given contents.

        We return a Panel which wraps up the given contents and draws a border
        around it.
    """
    wrapper = VerticalPanel()
    wrapper.add(contents)
    wrapper.setBorderWidth(1)
    return wrapper
コード例 #6
0
ファイル: uiHelpers.py プロジェクト: ygyangguang/pyjs
def border(contents):
    """ Draw a border around the given contents.

        We return a Panel which wraps up the given contents and draws a border
        around it.
    """
    wrapper = VerticalPanel()
    wrapper.add(contents)
    wrapper.setBorderWidth(1)
    return wrapper
コード例 #7
0
ファイル: ui_panel.py プロジェクト: rwl/traitsbackendpyjamas
def _fill_panel(panel, content, ui, item_handler=None):
    """ Fill a page based container panel with content.
    """
    active = 0

    for index, item in enumerate(content):
        page_name = item.get_label(ui)
        if page_name == "":
            page_name = "Page %d" % index

        if isinstance(item, Group):
            if item.selected:
                active = index

            gp = _GroupPanel(item, ui, suppress_label=True)
            page = gp.control
            sub_page = gp.sub_control

            # If the result is the same type with only one page, collapse it
            # down into just the page.
            if type(sub_page) is type(panel) and sub_page.count() == 1:
                new = sub_page.getWidget(0)
                if isinstance(panel, TabPanel):
                    sub_page.remove(sub_page.getWidget(0))
                else:
                    sub_page.remove(sub_page.getWidget(0))
            elif isinstance(page, Widget):
                new = page
            else:
                new = Widget()
                new.setLayoutData(page)

            layout = new.getLayoutData()
#            if layout is not None:
#                layout.setAlignment(QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)

        else:
            new = Widget()
            layout = VerticalPanel()
            layout.setBorderWidth(0)
            item_handler(item, layout)

        # Add the content.
        if isinstance(panel, TabPanel):
            panel.add(new, page_name)
        else:
            panel.add(new)

    panel.selectTab( active )
コード例 #8
0
ファイル: Showcase.py プロジェクト: Afey/pyjs
    def onModuleLoad(self):
        """ Dynamically build our user interface when the web page is loaded.
        """
        self._root        = RootPanel()
        self._tree        = Tree()
        self._rightPanel  = SimplePanel()
        self._curContents = None

        intro = HTML('<h3>Welcome to the Pyjamas User Interface Showcase</h3>'+
                     '<p/>Please click on an item to start.')

        self._introPanel = VerticalPanel()
        self._introPanel.add(uiHelpers.indent(intro, left=20))

        self._demos = [] # List of all installed demos.  Each item in this list
                         # is a dictionary with the following entries:
                         #
                         #     'name'
                         #
                         #         The name for this demo.
                         #
                         #     'section'
                         #
                         #         The name of the section of the demo tree
                         #         this demo should be part of.
                         #
                         #     'doc'
                         #
                         #         The documentation for this demo.
                         #
                         #     'src'
                         #
                         #         The source code for this demo.
                         #
                         #     'example'
                         #
                         #         The Panel which holds the example output for
                         #         this demo.

        self.loadDemos()
        self.buildTree()

        self._tree.setSize("0%", "100%")

        divider = VerticalPanel()
        divider.setSize("1px", "100%")
        divider.setBorderWidth(1)

        scroller = ScrollPanel(self._rightPanel)
        scroller.setSize("100%", "100%")

        hPanel = HorizontalPanel()
        hPanel.setSpacing(4)

        hPanel.add(self._tree)
        hPanel.add(divider)
        hPanel.add(scroller)

        hPanel.setHeight("100%")
        self._root.add(hPanel)

        self._tree.addTreeListener(self)
        self.showDemo(None)
コード例 #9
0
class I2CPanel :
	
	class saveStateListener :
		def __init__(self, panel) :
			self._saveStatePanel=panel	
			
		def onRemoteResponse(self, response, request_info):
			self._saveStatePanel.returnStatement.setText("File saved:" + response)
			
		def onRemoteError(self, code, message, request_info):
			ErrorMessage( "Unable to contact server" )
			
	
	class loadStateListener :
		def __init__(self, panel) :
			self._saveStatePanel=panel	
			
		def onRemoteResponse(self, response, request_info):
			self._saveStatePanel.returnStatement.setText("File loaded:" + response)
			self._saveStatePanel.rpcService.I2CRegisterValues( self._saveStatePanel.getTotalCBCs(), I2CPanel.ReadRegisterValueListener(self._saveStatePanel) ) #refresh of text boxes

		def onRemoteError(self, code, message, request_info):
			ErrorMessage( "Unable to contact server" )
	
	class ConnectedCBCListener :
		"""
		A class to listen for the response to the connectedCBCNames call
		"""
		def __init__(self, listBox) :
			self.listBox=listBox
			
		def onRemoteResponse(self, response, request_info):
			self.listBox.clear()
			if response == None:
				self.listBox.addItem("<none>")
				self.listBox.setEnabled( False )
			else :
				for name in response :
					self.listBox.addItem(name) #e.g FE0CBC0
				self.listBox.setEnabled(True)

		def onRemoteError(self, code, message, request_info):
			ErrorMessage( "Unable to contact server" )

	class ReadRegisterValueListener :
		"""
		A class to listen for the response to the call to get the register values
		"""
		def __init__(self, panel) :
			self._I2Cpanel=panel
			self.textBoxes=self._I2Cpanel.i2cValueEntries
			
		def onRemoteResponse(self, response, request_info):
			#Call is now made for all connected CBCs for better stability of status box- fb
			for cbcName in self._I2Cpanel.getActiveCBCs():
				if cbcName=='FE0CBC0':
					valuesTuple = response[response.keys()[0]]
				elif cbcName=='FE0CBC1':
					valuesTuple = response[response.keys()[1]]
			# For this chip loop over all the register and set the text box values
			for registerName in valuesTuple :
				box=self.textBoxes[registerName]
				status=self._I2Cpanel.statusValueEntries[registerName]
				box.setText( "0x%02x"%valuesTuple[registerName] )
				box.setStyleAttribute( "background-color", "#FFFFFF" )
				box.setEnabled( True )
			#for some reason pyjas likes these separated - fb	
			for registerName in valuesTuple:
				if response['FE0CBC0'][registerName]==response['FE0CBC1'][registerName]:
					self._I2Cpanel.statusValueEntries[registerName].setText("==")
				else:
					self._I2Cpanel.statusValueEntries[registerName].setText(" //")
		def onRemoteError(self, code, message, request_info):
			ErrorMessage( "Unable to contact server" )

	class RefreshListener :
		"""
		A class that will wait for a response before refreshing the status box
		"""
		def __init__(self, panel) :
			self._Refresh = panel
		
		def onRemoteResponse(self, response, request_info):
			self._Refresh.rpcService.I2CRegisterValues( self._Refresh.getTotalCBCs(), I2CPanel.ReadRegisterValueListener(self._Refresh) )	 #Live refresh of the status box
			

		def onRemoteError(self, code, message, request_info):
			ErrorMessage( "Unable to contact server" )

	def __init__( self ) :
		# This is the service that will be used to communicate with the DAQ software
		self.rpcService = GlibRPCService.instance()
		# The main panel that everythings will be insided
		self.mainPanel = HorizontalPanel()
		self.mainPanel.setSpacing(10)
		self.i2cValueEntries = {} # The input boxes for all the registers
		self.statusValueEntries = {} # Displays the status of the i2cValueEntries
		
		self.stateValueEntries = {} # For load/save state
		self.fileName = {} # File name of the i2c registers
		
		# This is the list of available CBC chips. It will be populated by a call to the
		# server later.
		self.cbcList=ListBox(MultipleSelect=True, VisibleItemCount=10)
		self.cbcList.addItem( "waiting..." ) # Default text until I hear from the server what's connected
		self.cbcList.setEnabled( False )
		self.cbcList.addChangeListener(self)
		self.rpcService.connectedCBCNames( None, I2CPanel.ConnectedCBCListener(self.cbcList) ) # Ask the server what's connected
		
		
		# This is the panel that will have the list of I2C registers. I'll split up the
		# registers into subjects to make them more manageable.
		self.mainSettings = DisclosurePanel("Main Control Registers")
		self.channelMasks = DisclosurePanel("Channel Masks")
		self.channelTrims = DisclosurePanel("Channel Trims")
		self.callSettings = VerticalPanel("Load/Save States")
		self.callSettings.setBorderWidth(1)

		self.callSettings.add(HTML("<center>Load/Save State</center>"))
		
		cbcListAndCallSettings=VerticalPanel()
		cbcListAndCallSettings.add(self.cbcList)
		cbcListAndCallSettings.add(self.callSettings)
		self.mainPanel.add(cbcListAndCallSettings)
		self.mainPanel.add(self.mainSettings)
		self.mainPanel.add(self.channelMasks)
		self.mainPanel.add(self.channelTrims)
		
		self.callSettings.add( self.createStatesPanel())
		self.mainSettings.add( self.createRegisterPanel(["FrontEndControl","TriggerLatency","HitDetectSLVS","Ipre1","Ipre2","Ipsf","Ipa","Ipaos","Vpafb","Icomp","Vpc","Vplus","VCth","TestPulsePot","SelTestPulseDel&ChanGroup","MiscTestPulseCtrl&AnalogMux","TestPulseChargePumpCurrent","TestPulseChargeMirrCascodeVolt","CwdWindow&Coincid","MiscStubLogic"]) )
		self.channelMasks.add( self.createRegisterPanel(["MaskChannelFrom008downto001","MaskChannelFrom016downto009","MaskChannelFrom024downto017","MaskChannelFrom032downto025","MaskChannelFrom040downto033","MaskChannelFrom048downto041","MaskChannelFrom056downto049","MaskChannelFrom064downto057","MaskChannelFrom072downto065","MaskChannelFrom080downto073","MaskChannelFrom088downto081","MaskChannelFrom096downto089","MaskChannelFrom104downto097","MaskChannelFrom112downto105","MaskChannelFrom120downto113","MaskChannelFrom128downto121","MaskChannelFrom136downto129","MaskChannelFrom144downto137","MaskChannelFrom152downto145","MaskChannelFrom160downto153","MaskChannelFrom168downto161","MaskChannelFrom176downto169","MaskChannelFrom184downto177","MaskChannelFrom192downto185","MaskChannelFrom200downto193","MaskChannelFrom208downto201","MaskChannelFrom216downto209","MaskChannelFrom224downto217","MaskChannelFrom232downto225","MaskChannelFrom240downto233","MaskChannelFrom248downto241","MaskChannelFrom254downto249"]) )
		self.channelTrims.add( self.createRegisterPanel(["Channel001","Channel002","Channel003","Channel004","Channel005","Channel006","Channel007","Channel008","Channel009","Channel010","Channel011","Channel012","Channel013","Channel014","Channel015","Channel016","Channel017","Channel018","Channel019","Channel020","Channel021","Channel022","Channel023","Channel024","Channel025","Channel026","Channel027","Channel028","Channel029","Channel030","Channel031","Channel032","Channel033","Channel034","Channel035","Channel036","Channel037","Channel038","Channel039","Channel040","Channel041","Channel042","Channel043","Channel044","Channel045","Channel046","Channel047","Channel048","Channel049","Channel050","Channel051","Channel052","Channel053","Channel054","Channel055","Channel056","Channel057","Channel058","Channel059","Channel060","Channel061","Channel062","Channel063","Channel064","Channel065","Channel066","Channel067","Channel068","Channel069","Channel070","Channel071","Channel072","Channel073","Channel074","Channel075","Channel076","Channel077","Channel078","Channel079","Channel080","Channel081","Channel082","Channel083","Channel084","Channel085","Channel086","Channel087","Channel088","Channel089","Channel090","Channel091","Channel092","Channel093","Channel094","Channel095","Channel096","Channel097","Channel098","Channel099","Channel100","Channel101","Channel102","Channel103","Channel104","Channel105","Channel106","Channel107","Channel108","Channel109","Channel110","Channel111","Channel112","Channel113","Channel114","Channel115","Channel116","Channel117","Channel118","Channel119","Channel120","Channel121","Channel122","Channel123","Channel124","Channel125","Channel126","Channel127","Channel128","Channel129","Channel130","Channel131","Channel132","Channel133","Channel134","Channel135","Channel136","Channel137","Channel138","Channel139","Channel140","Channel141","Channel142","Channel143","Channel144","Channel145","Channel146","Channel147","Channel148","Channel149","Channel150","Channel151","Channel152","Channel153","Channel154","Channel155","Channel156","Channel157","Channel158","Channel159","Channel160","Channel161","Channel162","Channel163","Channel164","Channel165","Channel166","Channel167","Channel168","Channel169","Channel170","Channel171","Channel172","Channel173","Channel174","Channel175","Channel176","Channel177","Channel178","Channel179","Channel180","Channel181","Channel182","Channel183","Channel184","Channel185","Channel186","Channel187","Channel188","Channel189","Channel190","Channel191","Channel192","Channel193","Channel194","Channel195","Channel196","Channel197","Channel198","Channel199","Channel200","Channel201","Channel202","Channel203","Channel204","Channel205","Channel206","Channel207","Channel208","Channel209","Channel210","Channel211","Channel212","Channel213","Channel214","Channel215","Channel216","Channel217","Channel218","Channel219","Channel220","Channel221","Channel222","Channel223","Channel224","Channel225","Channel226","Channel227","Channel228","Channel229","Channel230","Channel231","Channel232","Channel233","Channel234","Channel235","Channel236","Channel237","Channel238","Channel239","Channel240","Channel241","Channel242","Channel243","Channel244","Channel245","Channel246","Channel247","Channel248","Channel249","Channel250","Channel251","Channel252","Channel253","Channel254","ChannelDummy"]) )
		
		self.mainSettings.add()
		self.echo=Label()
		self.mainPanel.add(self.echo)

	def getPanel( self ) :
		return self.mainPanel
	
	def onChange( self, sender ) :
		
		if sender == self.cbcList :
			# Make a call to the RPC service to get the register values
			self.rpcService.I2CRegisterValues( self.getTotalCBCs(), I2CPanel.ReadRegisterValueListener(self) )#fb - sends all CBCs
			self.load.setEnabled(True)
			self.save.setEnabled(True)
		elif sender == self.save:
			msg = self.saveFileName.getText()
			self.rpcService.saveI2cRegisterValues(msg, I2CPanel.saveStateListener(self) )
		elif sender == self.load:
			msg = self.loadFileName.getText()
			self.rpcService.loadI2cRegisterValues(msg, I2CPanel.loadStateListener(self) )	
			self.rpcService.I2CRegisterValues( self.getTotalCBCs(), I2CPanel.ReadRegisterValueListener(self) )#
				
		# Sender must be a text box. Need to format the input.
		else : 
			try:
			# For some reason the '0x' at the start of the string is causing exceptions,
			# even though it works fine with interactive python. I'll take it off anyway.
				string=sender.getText()
				if( len(string)>=2 ) :
					if string[0]=='0' and string[1]=='x' : string=string[2:]
					value=int( string, 16 ) # convert as hex
					# Cap values at 255
					if value<0 : value=0
					if value>255 : value=255
					sender.setStyleAttribute( "background-color", "#FFFFFF" )
			# Convert to the same format as everything else
				sender.setText( "0x%02x"%value )
			# Send the change to the RPC service
				messageParameters = {}
				for cbcName in self.getActiveCBCs() :
					messageParameters[cbcName]={ sender.getTitle():value }
					self.rpcService.setI2CRegisterValues( messageParameters, I2CPanel.RefreshListener(self) )
			
			except ValueError:
				sender.setStyleAttribute( "background-color", "#FF3333" )		
		
		#self.echoSelection()
	
	def echoSelection(self): #fb - a good "print screen" method
		msg = " File saved: "
		for names in self.getCheckedStates():
			msg += names
		self.echo.setText(msg)	
			
	def getList(self):
		selectCBCs = []
		for i in range(self.cbcList.getItemCount()) :
			if self.cbcList.isItemSelected(i):
				selectedCBCs.append(self.cbcList.getItemText(i))
				
	def getTotalCBCs(self) : #fb
		totalCBCs = []
		for i in range(self.cbcList.getItemCount()) :
			totalCBCs.append(self.cbcList.getItemText(i))
		return totalCBCs
	
	def getSpecificCBC(self, i): #fb
		specificCBC = []
		specificCBC.append(self.cbcList.getItemText(i))
		return specificCBC
		

	def getActiveCBCs(self) :
		selectedCBCs = []
		for i in range(self.cbcList.getItemCount()) :
			if self.cbcList.isItemSelected(i):
				selectedCBCs.append(self.cbcList.getItemText(i))
		return selectedCBCs
	
	def getCheckedStates(self): # returns the checked boxes + filename
		selectedStates = []
		#for names in self.stateValueEntries:
			#if str(self.stateValueEntries[names].isChecked())=="True":
			#	selectedStates.append(names)
		selectedStates.append(self.saveFileName.getText())
		return selectedStates
		
	def createRegisterPanel( self, registerNames ) :
		"""
		Creates panels and buttons for everything given in registerNames, and returns the main panel.
		"""
		flowPanel=FlowPanel()
		for buttonName in registerNames :
			newPanel=HorizontalPanel()
			label=Label(buttonName)
			newPanel.add( label )
			newTextBox=TextBox()
			newTextBox.setEnabled(False)
			newTextBox.setWidth(80)
			statusBox=TextBox()
			statusBox.setEnabled(False)
			statusBox.setWidth(30)
			newPanel.add(newTextBox)
			newPanel.add(statusBox)
			newPanel.setCellHorizontalAlignment( newTextBox, HasHorizontalAlignment.ALIGN_RIGHT )
			newPanel.setCellHorizontalAlignment( statusBox, HasHorizontalAlignment.ALIGN_RIGHT )
			newPanel.setCellWidth( statusBox, "20px" )
			newPanel.setWidth("100%")
			#newPanel.setStyleName("areaStyle");
			#newPanel.setBorderWidth(5);
			
			newTextBox.setText("select chip...")
			newTextBox.addChangeListener(self)
			newTextBox.setTitle(buttonName) # This isn't displayed, but it's useful to have stored
			
			self.i2cValueEntries[buttonName]=newTextBox	
			
			self.statusValueEntries[buttonName]=statusBox
			statusBox.setTitle(buttonName)
			statusBox.setText("...")
			
			flowPanel.add(newPanel)


		return flowPanel
	
	def createStatesPanel(self):
		vertPanel=VerticalPanel()
		vertPanel.setSpacing(10)
		
		selectionNames = (["Main Control", "Masks", "Trims"])	
		registerSelection = VerticalPanel()
		
		for name in selectionNames :
			checkBox = CheckBox(name)
			checkBox.setTitle(name)
			self.stateValueEntries[name]=checkBox
			registerSelection.add(checkBox)
		
		#Tidy up 
		loadPanel = HorizontalPanel()
		loadFileTextBox = TextBox()
		loadFileTextBox.setText("MyI2cCfg")
		loadFileTextBox.setWidth(80)
		self.loadFileName = loadFileTextBox
		loadPanel.add(loadFileTextBox)
		self.load = Button("Load",getattr(self,"onChange")) #overrides default and sends it to onChange
		loadPanel.add(self.load)
		self.load.setEnabled(False)
		
		savePanel = HorizontalPanel()
		saveFileTextBox = TextBox()
		saveFileTextBox.setText("MyI2cCfg")
		saveFileTextBox.setWidth(80)
		self.saveFileName = saveFileTextBox
		savePanel.add(saveFileTextBox)
		self.save = Button("Save", getattr(self,"onChange"))
		savePanel.add(self.save)
		self.save.setEnabled(False)
		
		self.returnStatement = Label()
		
		vertPanel.add(registerSelection)
		vertPanel.add(loadPanel)
		vertPanel.add(savePanel)
		vertPanel.add(self.returnStatement)
		
		return vertPanel
コード例 #10
0
class ReducePanelIFACE(PanelIFACE):
    def __init__(self, parent = None):
        
        PanelIFACE.__init__(self, parent)
        self.panel = VerticalPanel()
        self.panel.setBorderWidth(1)
        self.panel.setWidth("100%")
        # prepare panel
        self.prepareReduce = HTML("<tt> .. none yet .. </tt>", True, )

        self.recipeList = ListBox()
        self.recipeList.addChangeListener(getattr(self, "onRecipeSelected"))
        self.recipeList.addItem("None")
        HTTPRequest().asyncGet("recipes.xml",
                                RecipeListLoader(self))

        #EO prepare panel
        self.reduceCLPanel = DockPanel(Spacing = 5)
        self.reduceCLPanel.add(HTML("<i>Reduce Command Line</i>:"), DockPanel.NORTH)                        
        self.reduceCLPanel.add(self.prepareReduce, DockPanel.NORTH)

        self.reduceFilesPanel = DockPanel(Spacing = 5)
        self.reduceFilesPanel.add(HTML("<b>Datasets</b>:"), DockPanel.WEST)

        self.reduceFiles = ListBox()
        self.reduceFiles.setVisibleItemCount(5)
        self.reduceFilesPanel.add(self.reduceFiles, DockPanel.WEST)
        self.clearReduceFilesButton = Button("<b>Clear List</b>", listener = getattr(self, "onClearReduceFiles"))
        self.reduceFilesPanel.add(self.clearReduceFilesButton, DockPanel.SOUTH)

        self.recipeListPanel = DockPanel(Spacing = 5)
        self.recipeListPanel.add(HTML("<b>Recipes List</b>:"),DockPanel.WEST)
        self.recipeListPanel.add(self.recipeList, DockPanel.WEST)

        self.runReduceButton = Button("<b>RUN REDUCE</b>", listener = getattr(self, "onRunReduce"))

        self.adInfo = HTML("file info...")
        # major sub panels
        self.panel.add(self.reduceCLPanel)
        self.panel.add(self.reduceFilesPanel)
        self.panel.add(self.recipeListPanel)
        self.panel.add(self.runReduceButton)
        self.panel.add(self.adInfo)
    def onRecipeSelected(self, event):
        self.updateReduceCL()
    
    def onClearReduceFiles(self, event):
        self.reduceFiles.clear() 
        self.adInfo.setHTML("file info...") 
        self.updateReduceCL()
        
    def updateReduceCL(self):
        recipe = self.recipeList.getItemText(self.recipeList.getSelectedIndex())
        
        if recipe=="None":
            rstr = ""
        else:
            rstr = "-r "+recipe

        rfiles = []            
        for i in range(0, self.reduceFiles.getItemCount()):
            fname = self.reduceFiles.getItemText(i)
            rfiles.append(fname)
        filesstr = " ".join(rfiles)
        
                
        self.prepareReduce.setHTML('<b>reduce</b> %(recipe)s %(files)s' % 
                                        { "recipe":rstr, 
                                          "files":filesstr})
    def onRunReduce(self):
        recipe = self.recipeList.getItemText(self.recipeList.getSelectedIndex())
        
        if recipe=="None":
            rstr = ""
        else:
            rstr = "p=-r"+recipe

        rfiles = []            
        for i in range(0, self.reduceFiles.getItemCount()):
            fname = self.reduceFiles.getItemText(i)
            rfiles.append(quote(self.pathdict[fname]["path"]))
        filesstr = "&p=".join(rfiles)
                
        cl = "/runreduce?%s&p=%s" % (rstr, filesstr)
        # @@TEST
        # cl = "/recipes.xml"
        if False:
            msg = repr(self.parent)+repr(dir(self.parent))
            JS("alert(msg)")
        if hasattr(self.parent, "roFrame"):
            self.parent.roFrame.setUrl(cl)
            self.parent.tabPanel.selectTab(self.parent.tabIFACEdict["rogui"])
        else:
            JS("window.open(cl)")

    def onTreeItemSelected(self, item):
        pathdict = self.pathdict
        
        tfile = item.getText()
        #check if already in

        self.reduceFiles.addItem(tfile)
        self.updateReduceCL()
        
        filename = tfile
        if filename in pathdict:
            if pathdict[filename]["filetype"] == "fileEntry":
                url = "adinfo?filename=%s" % self.pathdict[item.getText()]["path"]
                HTTPRequest().asyncGet(url, 
                               ADInfoLoader(self),
                              )
            else:
                self.adInfo.setHTML("""
                    <b style="font-size:200%%">%s</b>""" % pathdict[filename]["filetype"])
        else:
            self.adInfo.setHTML("unknown node")
        return
コード例 #11
0
class Trees(Sink):
    pathdict = {}
    reduceFiles = None
    def __init__(self, parent = None):
        Sink.__init__(self, parent)
        self.reduceFiles = []
        if True:
            HTTPRequest().asyncGet("datadir.xml", 
                                    DirDictLoader(self),
                                )
        dock = DockPanel(HorizontalAlignment=HasAlignment.ALIGN_LEFT, 
                            Spacing=10,
                             Size=("100%","100%"))
        self.dock = dock
        self.fProto = []

        self.fTree = Tree()
        self.prPanel = VerticalPanel(Size=("50%", ""))
        self.treePanel = HorizontalPanel(Size=("50%", "100%"))
        self.treePanel.add(self.fTree)
        dock.add(self.treePanel, DockPanel.WEST)
        
        self.treePanel.setBorderWidth(1)
        self.treePanel.setWidth("100%")
        self.prPanel.setBorderWidth(1)
        self.prPanel.setWidth("100%")
        # prepare panel
        self.prepareReduce = HTML("<tt> .. none yet .. </tt>", True, )
        
        self.recipeList = ListBox()
        self.recipeList.addChangeListener(getattr(self, "onRecipeSelected"))
        self.recipeList.addItem("None")
        HTTPRequest().asyncGet("recipes.xml",
                                RecipeListLoader(self))

        #EO prepare panel
        self.reduceCLPanel = DockPanel(Spacing = 5)
        self.reduceCLPanel.add(HTML("<i>Reduce Command Line</i>:"), DockPanel.NORTH)                        
        self.reduceCLPanel.add(self.prepareReduce, DockPanel.NORTH)

        self.reduceFilesPanel = DockPanel(Spacing = 5)
        self.reduceFilesPanel.add(HTML("<b>Datasets</b>:"), DockPanel.WEST)
        
        self.reduceFiles = ListBox()
        self.reduceFiles.setVisibleItemCount(5)
        self.reduceFilesPanel.add(self.reduceFiles, DockPanel.WEST)
        self.clearReduceFilesButton = Button("<b>Clear List</b>", listener = getattr(self, "onClearReduceFiles"))
        self.reduceFilesPanel.add(self.clearReduceFilesButton, DockPanel.SOUTH)

        self.recipeListPanel = DockPanel(Spacing = 5)
        self.recipeListPanel.add(HTML("<b>Recipes List</b>:"),DockPanel.WEST)
        self.recipeListPanel.add(self.recipeList, DockPanel.WEST)
        
        self.runReduceButton = Button("<b>RUN REDUCE</b>", listener = getattr(self, "onRunReduce"))
        
        self.adInfo = HTML("file info...")
        # major sub panels
        self.prPanel.add(self.reduceCLPanel)
        self.prPanel.add(self.reduceFilesPanel)
        self.prPanel.add(self.recipeListPanel)
        self.prPanel.add(self.runReduceButton)
        self.prPanel.add(self.adInfo)
       
        
        dock.add(self.prPanel,DockPanel.EAST)
        
        dock.setCellWidth(self.treePanel, "50%")
        dock.setCellWidth(self.prPanel, "50%")
        for i in range(len(self.fProto)):
            self.createItem(self.fProto[i])
            self.fTree.addItem(self.fProto[i].item)

        self.fTree.addTreeListener(self)
        self.initWidget(self.dock)
        
        if False: #self.parent.filexml != None:
            DirDictLoader(self).onCompletion(self.parent.filexml)

    def onTreeItemSelected(self, item):
        pathdict = self.pathdict
        
        tfile = item.getText()
        #check if already in

        for i in range(0, self.reduceFiles.getItemCount()):
            fname = self.reduceFiles.getItemText(i)
            if fname == tfile:
                return
        self.reduceFiles.addItem(tfile)
        self.updateReduceCL()
        
        filename = tfile
        if filename in pathdict:
            if pathdict[filename]["filetype"] == "fileEntry":
                HTTPRequest().asyncGet("adinfo?filename=%s" % self.pathdict[item.getText()]["path"], 
                               ADInfoLoader(self),
                              )
            else:
                self.adInfo.setHTML("""
                    <b style="font-size:200%%">%s</b>""" % pathdict[filename]["filetype"])
        else:
            self.adInfo.setHTML("unknown node")
        return
        
        # self.prepareReduce.setHTML('<a href="runreduce?p=-r&p=callen&p=%(fname)s">reduce -r callen %(fname)s</a>' %
        #                            {"fname":item.getText()})
        pass
 
    def onRecipeSelected(self, event):
        self.updateReduceCL()
    
    def onClearReduceFiles(self, event):
        self.reduceFiles.clear() 
        self.adInfo.setHTML("file info...") 
        self.updateReduceCL()
        
    def updateReduceCL(self):
        recipe = self.recipeList.getItemText(self.recipeList.getSelectedIndex())
        
        if recipe=="None":
            rstr = ""
        else:
            rstr = "-r "+recipe

        rfiles = []            
        for i in range(0, self.reduceFiles.getItemCount()):
            fname = self.reduceFiles.getItemText(i)
            rfiles.append(fname)
        filesstr = " ".join(rfiles)
        
                
        self.prepareReduce.setHTML('<b>reduce</b> %(recipe)s %(files)s' % 
                                        { "recipe":rstr, 
                                          "files":filesstr})
    def onRunReduce(self):
        recipe = self.recipeList.getItemText(self.recipeList.getSelectedIndex())
        
        if recipe=="None":
            rstr = ""
        else:
            rstr = "p=-r"+recipe

        rfiles = []            
        for i in range(0, self.reduceFiles.getItemCount()):
            fname = self.reduceFiles.getItemText(i)
            rfiles.append(quote(self.pathdict[fname]["path"]))
        filesstr = "&p=".join(rfiles)
                
        cl = "/runreduce?%s&p=%s" % (rstr, filesstr)
        JS("window.open(cl)")

        
    def onTreeItemSelected(self, item):
        pathdict = self.pathdict
        
        tfile = item.getText()
        #check if already in
        if tfile in pathdict:
            ftype = pathdict[tfile]["filetype"]
            if ftype != "fileEntry":
                item.setState(True)
                return
        else:
            return
        for i in range(0, self.reduceFiles.getItemCount()):
            fname = self.reduceFiles.getItemText(i)
            if fname == tfile:
                return
        self.reduceFiles.addItem(tfile)
        self.updateReduceCL()
        
        filename = tfile
        if filename in pathdict:
            if pathdict[filename]["filetype"] == "fileEntry":
                HTTPRequest().asyncGet("adinfo?filename=%s" % self.pathdict[item.getText()]["path"], 
                               ADInfoLoader(self),
                              )
            else:
                self.adInfo.setHTML("""
                    <b style="font-size:200%%">%s</b>""" % pathdict[filename]["filetype"])
        else:
            self.adInfo.setHTML("unknown node")
        return
        
        # self.prepareReduce.setHTML('<a href="runreduce?p=-r&p=callen&p=%(fname)s">reduce -r callen %(fname)s</a>' %
        #                            {"fname":item.getText()})
        pass
    
    def onTreeItemStateChanged(self, item):
        child = item.getChild(0)
        if hasattr(child, "isPendingItem"):
            item.removeItem(child)
        
            proto = item.getUserObject()
            for i in range(len(proto.children)):
                self.createItem(proto.children[i])
                index = self.getSortIndex(item, proto.children[i].text)
                # demonstrate insertItem.  addItem is easy.
                item.insertItem(proto.children[i].item, index)
                item.setState(True)

    def getSortIndex(self, parent, text):
        nodes = parent.getChildCount()
        node = 0
        text = text.lower()

        while node < nodes:
            item = parent.getChild(node)
            if cmp(text, item.getText().lower()) < 0:
                break;
            else:
                node += 1
        
        return node
    
    def createProto(self, node):
            #if node.nodeType != node.ELEMENT_NODE:
            #    return
            pathdict = self.pathdict
            if not node.hasChildNodes():
                if node.nodeType != 1:
                    return None
                newproto = Proto(str(node.getAttribute("name")))
                if node.tagName == "fileEntry":
                    pathdict.update({node.getAttribute("name"):
                                        { "path":node.getAttribute("fullpath"),
                                          "filetype": node.tagName }})
                elif node.tagName == "dirEntry":
                    pathdict.update({node.getAttribute("name"):
                                        { "path":node.getAttribute("name"),
                                          "filetype": node.tagName}})
                else:
                    pathdict.update({node.getAttribute("name"):
                                        { "path": "NOPATH",
                                          "filetype": node.tagName}})
                self.createItem(newproto)
                return newproto
            else:
                cprotos = []
                for i in range(0, node.childNodes.length):
                    childnode = node.childNodes.item(i)
                    ncproto = self.createProto(childnode)
                    if ncproto != None:
                        ncitem  = self.createItem(ncproto)
                        cprotos.append(ncproto)
                if len(cprotos)>0:
                    newproto = Proto(str(node.getAttribute("name")),cprotos)
                else:
                    newproto = Proto(str(node.getAttribute("name")))
                if node.tagName == "fileEntry":
                    pathdict.update({node.getAttribute("name"):
                                        { "path":node.getAttribute("fullpath"),
                                          "filetype": node.tagName }})
                elif node.tagName == "dirEntry":
                    pathdict.update({node.getAttribute("name"):
                                        { "path":node.getAttribute("name"),
                                          "filetype": node.tagName}})
                else:
                    pathdict.update({node.getAttribute("name"):
                                        { "path": "NOPATH",
                                          "filetype": node.tagName}})

                self.createItem(newproto)
            return newproto
    
    def fromXML(self,text):
        doc = create_xml_doc(text)
        #node = doc.firstChild
        
        #node = doc.getElementById("topDirectory")
        nodes = doc.getElementsByTagName("dirEntry")
        node = nodes.item(0)
        s = repr(node)
        
        newproto = self.createProto(node)    
        plist = [newproto]
        #plist = [Proto(node.tagName)]

        for i in range(len(plist)):
            num = str(len(plist))
            # self.createItem(plist[i])
            self.fTree.addItem(plist[i].item)
            plist[i].item.setState(True)

        
    def onShow(self):
        if False:
            for item in self.fTree.treeItemIterator():
                key = repr(item.tree)
                if key != "null":
                    item.setState(True)
                else:
                    JS("alert(item.getText())")

        pass

    def createItem(self, proto):
        proto.item = TreeItem(proto.text)
        proto.item.setUserObject(proto)
        if len(proto.children) > 0:
            proto.item.addItem(PendingItem())
コード例 #12
0
ファイル: Showcase.py プロジェクト: minghuascode/pyj
    def onModuleLoad(self):
        """ Dynamically build our user interface when the web page is loaded.
        """
        self._root = RootPanel()
        self._tree = Tree()
        self._rightPanel = SimplePanel()
        self._curContents = None

        intro = HTML(
            '<h3>Welcome to the Pyjamas User Interface Showcase</h3>' +
            '<p/>Please click on an item to start.')

        self._introPanel = VerticalPanel()
        self._introPanel.add(uiHelpers.indent(intro, left=20))

        self._demos = [
        ]  # List of all installed demos.  Each item in this list
        # is a dictionary with the following entries:
        #
        #     'name'
        #
        #         The name for this demo.
        #
        #     'section'
        #
        #         The name of the section of the demo tree
        #         this demo should be part of.
        #
        #     'doc'
        #
        #         The documentation for this demo.
        #
        #     'src'
        #
        #         The source code for this demo.
        #
        #     'example'
        #
        #         The Panel which holds the example output for
        #         this demo.

        self.loadDemos()
        self.buildTree()

        self._tree.setSize("0%", "100%")

        divider = VerticalPanel()
        divider.setSize("1px", "100%")
        divider.setBorderWidth(1)

        scroller = ScrollPanel(self._rightPanel)
        scroller.setSize("100%", "100%")

        hPanel = HorizontalPanel()
        hPanel.setSpacing(4)

        hPanel.add(self._tree)
        hPanel.add(divider)
        hPanel.add(scroller)

        hPanel.setHeight("100%")
        self._root.add(hPanel)

        self._tree.addTreeListener(self)
        self.showDemo(None)