コード例 #1
0
ファイル: CanvasTab.py プロジェクト: anandology/pyjamas
    def __init__(self):
        Sink.__init__(self)
        colour_grid = ColourGridCanvas()
        rotated = RotatedCanvas()       
        spheres = SpheresCanvas()
        #pattern = PatternCanvas()
        spiro = SpiroCanvas()
        self.solar = SolarCanvas()
        
        row0 = HorizontalPanel()
        row0.setSpacing(8)
        row0.add(colour_grid)
        row0.add(rotated)
        row0.add(spheres)
        #row0.add(pattern)
        
        row1 = HorizontalPanel()
        row1.setSpacing(8)
        row1.add(self.solar)
        row1.add(spiro)

        panel = VerticalPanel()
        panel.add(row0)
        panel.add(row1)

        self.setWidget(panel)
コード例 #2
0
ファイル: SinkList.py プロジェクト: anandology/pyjamas
class SinkList(Composite):
    def __init__(self):
        Composite.__init__(self)
        self.vp_list=VerticalPanel()
        self.sinks=[]
        self.selectedSink=-1
        
        self.initWidget(self.vp_list)
        self.setStyleName("ks-List")

    def addSink(self, info):
        name = info.getName()
        link = Hyperlink(name, False, TargetHistoryToken=name)
        link.setStyleName("ks-SinkItem")
        self.vp_list.add(link)
        self.sinks.append(info)

    def find(self, sinkName):
        for info in self.sinks:
            if info.getName()==sinkName:
                return info
        return None

    def setSinkSelection(self, name):
        if self.selectedSink <> -1:
            self.vp_list.getWidget(self.selectedSink).removeStyleName("ks-SinkItem-selected")

        for i in range(len(self.sinks)):
            info = self.sinks[i]
            if (info.getName()==name):
                self.selectedSink = i
                widget=self.vp_list.getWidget(self.selectedSink)
                widget.addStyleName("ks-SinkItem-selected")
                return
コード例 #3
0
ファイル: pypddemo.py プロジェクト: mlockett42/pypddemo
 def InitialiseScreen(self):
     hpanel = HorizontalPanel()
     self.add(hpanel)
     vpanelMenu = VerticalPanel()
     hpanel.add(vpanelMenu)
     self.addbutton = Button("Add Triangle")
     vpanelMenu.add(self.addbutton)
     self.addbutton.addClickListener(getattr(self, "addtriangle"))
     self.canvas = GWTCanvas(self.CANVAS_WIDTH, self.CANVAS_HEIGHT)
     vpanelCanvas = VerticalPanel()
     self.canvas.setWidth(self.CANVAS_WIDTH)
     self.canvas.setHeight(self.CANVAS_HEIGHT)
     hpanel.add(vpanelCanvas)
     vpanelCanvas.add(self.canvas)
     self.canvas.addMouseListener(self)
     self.selecteditem = None
     self.selectedhandle = None
     self.mouseisdown = False
     dc = DocumentCollection.documentcollection
     DocumentCollection.documentcollection.edgelistener = self.EdgeListener
     if len(dc.documentsbyclass[model.Drawing.__name__]) == 0:
         drawing = model.Drawing(None)
         dc.AddDocumentObject(drawing)
         EdgePoster([a.asDict() for a in drawing.history.GetAllEdges()])
     else:
         for k,v in dc.documentsbyclass[model.Drawing.__name__].iteritems():
             drawing = v
     self.drawingid = drawing.id
     self.Draw()
コード例 #4
0
ファイル: Contacts.py プロジェクト: Ludovic-Condette/pyjs
class Contacts(Composite):
    def __init__(self):
        Composite.__init__(self)

        self.contacts = []
        self.contacts.append(Contact("Benoit Mandelbrot", "*****@*****.**"))
        self.contacts.append(Contact("Albert Einstein", "*****@*****.**"))
        self.contacts.append(Contact("Rene Descartes", "*****@*****.**"))
        self.contacts.append(Contact("Bob Saget", "*****@*****.**"))
        self.contacts.append(Contact("Ludwig von Beethoven", "*****@*****.**"))
        self.contacts.append(Contact("Richard Feynman", "*****@*****.**"))
        self.contacts.append(Contact("Alan Turing", "*****@*****.**"))
        self.contacts.append(Contact("John von Neumann", "*****@*****.**"))

        self.panel = VerticalPanel()

        # Add all the contacts to the list.
        i = 0
        while (i < len(self.contacts)):
            self.addContact(self.contacts[i])
            i =  i + 1

        self.initWidget(self.panel)
        self.setStyleName("mail-Contacts")

    def addContact(self, contact):
        link = HTML("<a href='javascript:;'>" + contact.name + "</a>")
        self.panel.add(link)

        # Add a click listener that displays a ContactPopup when it is clicked.
        listener = ContactListener(contact, link)
        link.addClickListener(listener)
コード例 #5
0
    def __init__(self, tabBar=None, **kwargs):
        self.children = [] # TODO: can self.children be used instead?
        self.tab_names = {} 
        self.deck = kwargs.pop('Deck', None)
        floatingtab = kwargs.pop('FloatingTab', False)
        if self.deck is None:
            self.deck = DeckPanel(StyleName="gwt-TabPanelBottom")
        if tabBar is None:
            self.tabBar = TabBar()
        else:
            self.tabBar = tabBar
        self.tabListeners = []

        # this is awkward: VerticalPanel is the composite,
        # so we get the element here, and pass it in to VerticalPanel.
        element = kwargs.pop('Element', None)

        panel = VerticalPanel(Element=element)
        if not floatingtab:
            panel.add(self.tabBar)
        if self.deck.getParent() is None:
            panel.add(self.deck)
            panel.setCellHeight(self.deck, "100%")
        self.tabBar.setWidth("100%")
        self.tabBar.addTabListener(self)

        kwargs['StyleName'] = kwargs.get('StyleName', "gwt-TabPanel")

        PanelBase.__init__(self)
        Composite.__init__(self, panel, **kwargs)
コード例 #6
0
ファイル: ajax.py プロジェクト: tDeranek117/CSE-Notre-Dame
class Site:
    def __init__(self):
        # Record the image url for easy access
        self.IMAGES_URL = "http://www.cse.nd.edu/~cmc/teaching/cse30332_sp15/images"
        # The title label is intially empty but will be filled with the top
        # recommended movie by the time the page is viewed
        self.title_l = Label("", StyleName="teststyle")
        self.up_b = Button("UP", post_vote)
        self.down_b = Button("DOWN", post_vote)
        self.rating_l = Label("", StyleName="teststyle")
        self.img = Image("")
        # Construct three vertical panels to make he display slightly columnar
        self.leftVertPanel = VerticalPanel()
        self.midlVertPanel = VerticalPanel()
        self.riteVertPanel = VerticalPanel()
        self.horizontalizer = HorizontalPanel()
        # Add the buttons to the correct vertical panels!!!
        self.midlVertPanel.add(self.title_l)
        self.midlVertPanel.add(self.img)
        self.midlVertPanel.add(self.rating_l)
        self.riteVertPanel.add(self.down_b)
        self.leftVertPanel.add(self.up_b)
        # Add all the panels to the horizontal panel
        self.horizontalizer.add(self.leftVertPanel)
        self.horizontalizer.add(self.midlVertPanel)
        self.horizontalizer.add(self.riteVertPanel)
        # Add the horizontal panel to the vertical one
        RootPanel().add(self.horizontalizer)
        # Get the first recommendation
        get_recommendation()
コード例 #7
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)
コード例 #8
0
ファイル: pylon_client.py プロジェクト: Waqquas/pylon
 def get_case_panel(self):
     panel = VerticalPanel()
     title = HTML("""Case""")
     panel.add(title)
     tree = self.get_case_tree()
     panel.add(tree)
     return panel
コード例 #9
0
ファイル: FlowPanel.py プロジェクト: certik/pyjamas
class FlowPanelDemo:
    """Demos the flow panel. Because of how the Flow Panel works, all elements have to be inline elements.
        Divs, tables, etc. can't be used, unless specified with CSS that they are inline or inline-block.

        Because of how Vertical Panels work (with tables), we use CSS to display tables as inline-blocks.
        IE, excluding IE8, doesn't support inline-blocks, so we have to use a CSS hack
        (see http://blog.mozilla.com/webdev/2009/02/20/cross-browser-inline-block/ for more on the hack)
        However, we use spans instead of divs for the Label by providing an 'element' argument."""
       
    def __init__(self):
        self.root = RootPanel()
        #Flow panel taking up 70% of the page.  CSS centers it.
        self.flow = FlowPanel(Width="70%", StyleName='flow-panel')
       
       
        for x in range(0, 10):
            self.panel = VerticalPanel()
            #Label each image with its number in the sequence
            title = Label("Item %s" % x, element=DOM.createElement('span'), StyleName="title item")
            #Add a neat-o image.
            image = Image('images/pyjamas.png', Width="200px", Height="200px", StyleName="cat-image cat-item")
            #Add to the Vertical Panel the image title
            self.panel.add(title)
            self.panel.add(image)

            self.flow.add(self.panel)

        self.root.add(self.flow)
コード例 #10
0
ファイル: fileUpload.py プロジェクト: Afey/pyjs
    def __init__(self):
        SimplePanel.__init__(self)

        self.form = FormPanel()
        self.form.setEncoding(FormPanel.ENCODING_MULTIPART)
        self.form.setMethod(FormPanel.METHOD_POST)
        self.form.setAction("http://nonexistent.com")
        self.form.setTarget("results")

        vPanel = VerticalPanel()

        hPanel = HorizontalPanel()
        hPanel.setSpacing(5)
        hPanel.add(Label("Upload file:"))

        self.field = FileUpload()
        self.field.setName("file")
        hPanel.add(self.field)

        hPanel.add(Button("Submit", getattr(self, "onBtnClick")))

        vPanel.add(hPanel)

        results = NamedFrame("results")
        vPanel.add(results)

        self.form.add(vPanel)
        self.add(self.form)
コード例 #11
0
ファイル: verticalPanel.py プロジェクト: Afey/pyjs
    def __init__(self):
        SimplePanel.__init__(self)

        panel = VerticalPanel(BorderWidth=1,
                              HorizontalAlignment=HasAlignment.ALIGN_CENTER,
                              VerticalAlignment=HasAlignment.ALIGN_MIDDLE,
                              Width="50%",
                              Height="300px")

        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)

        self.add(panel)
コード例 #12
0
ファイル: oldExample.py プロジェクト: Afey/pyjs
    def onModuleLoad(self):
        self.remote = DataService()
        vPanel = VerticalPanel()


        # create div to hold map
        mapPanel = SimplePanel()
        mapPanel.setSize('700px','400px')

        # initiate getting gps data from web2py
        self.remote.getPoints(self)

        # create slider div
        slider = SimplePanel()
        self.slider = slider

        # add map and slide to main panel
        vPanel.add(mapPanel)
        vPanel.add(slider)

        # add everything to page's GreedyPyJs div
        root = RootPanelCls(DOM.getElementById("GreedPyJs"))
        root.add(vPanel)

        # Create initial google map
        self.map = GMap2(mapPanel.getElement())
        self.map.setCenter(GLatLng(37.4419, -122.1419), 13)


        # create place to hold gps positions
        # these will be in tuples: (date, latitude, longitude)
        self.positions=[]
コード例 #13
0
ファイル: Index0.py プロジェクト: molhokwai/libraries
	def themesPanel(self, themes=None):
		Window.alert('line:111')
		themes = None
		if not themes: themes=['0','1', 'cms', 'pypress']

		vPanel = VerticalPanel()
		for i in range(len(themes)):
			"""
			a_n = location.getPathName().split('/')[1]
			lambda1 = lambda x: w_l.pathname.replace('/'+a_n+'/', '/'+x+'/')+'?theme='+x
        	lambda2 = lambda x: w_l.pathname.replace('/'+a_n+'/', '/a/')+'?theme='+x
			href = {
				'cms' : lambda1, 
				'pypress' : lambda1,
				'o' : lambda2, 
				'1' : lambda2 
			}.get(themes[i], lambda2)(themes[i])
			"""

			a=Button('theme '+themes[i], 
					lambda x: location.setSearchDict({'theme': x.getID()}), 
					StyleName='link')
			a.setID(themes[i])
			vPanel.add(a)
	
		return vPanel
コード例 #14
0
ファイル: Calendar.py プロジェクト: jwashin/pyjs
    def drawFull(self, month, year):
        # should be called only once when we draw the calendar for
        # the first time
        self.vp = VerticalPanel()
        self.vp.setSpacing(2)
        self.vp.addStyleName("calendarbox calendar-module calendar")
        self.setWidget(self.vp)
        self.setVisible(False)
        #
        mth = int(month)
        yr = int(year)

        tp = HorizontalPanel()
        tp.addStyleName("calendar-top-panel")
        tp.setSpacing(5)

        h1 = Hyperlink('<<')
        h1.addClickListener(getattr(self, 'onPreviousYear'))
        h2 = Hyperlink('<')
        h2.addClickListener(getattr(self, 'onPreviousMonth'))
        h4 = Hyperlink('>')
        h4.addClickListener(getattr(self, 'onNextMonth'))
        h5 = Hyperlink('>>')
        h5.addClickListener(getattr(self, 'onNextYear'))

        tp.add(h1)
        tp.add(h2)

        # titlePanel can be changed, whenever we draw, so keep the reference
        txt = "<b>"
        txt += self.getMonthsOfYear()[mth-1] + " " + str(yr)
        txt += "</b>"
        self.titlePanel = SimplePanel()
        self.titlePanel.setWidget(HTML(txt))
        self.titlePanel.setStyleName("calendar-center")

        tp.add(self.titlePanel)
        tp.add(h4)
        tp.add(h5)
        tvp = VerticalPanel()
        tvp.setSpacing(10)
        tvp.add(tp)

        self.vp.add(tvp)

        # done with top panel

        self.middlePanel = SimplePanel()
        grid = self.drawGrid(mth, yr)
        self.middlePanel.setWidget(grid)
        self.vp.add(self.middlePanel)
        self.defaultGrid = grid

        self._gridShortcutsLinks()
        self._gridCancelLink()
        #
        # add code to test another way of doing the layout
        #
        self.setVisible(True)
        return
コード例 #15
0
    def onModuleLoad(self):
        self.TEXT_WAITING = "Waiting for response..."
        self.TEXT_ERROR = "Server Error"
        self.METHOD_ECHO = "Echo"
        self.METHOD_REVERSE = "Reverse"
        self.METHOD_UPPERCASE = "UPPERCASE"
        self.METHOD_LOWERCASE = "lowercase"
        self.methods = [self.METHOD_ECHO, self.METHOD_REVERSE, self.METHOD_UPPERCASE, self.METHOD_LOWERCASE]

        self.remote_php = EchoServicePHP()
        self.remote_py = EchoServicePython()

        self.status=Label()
        self.text_area = TextArea()
        self.text_area.setText("""{'Test'} [\"String\"]
\tTest Tab
Test Newline\n
after newline
""" + r"""Literal String:
{'Test'} [\"String\"]
""")
        self.text_area.setCharacterWidth(80)
        self.text_area.setVisibleLines(8)
        
        self.method_list = ListBox()
        self.method_list.setName("hello")
        self.method_list.setVisibleItemCount(1)
        for method in self.methods:
            self.method_list.addItem(method)
        self.method_list.setSelectedIndex(0)

        method_panel = HorizontalPanel()
        method_panel.add(HTML("Remote string method to call: "))
        method_panel.add(self.method_list)
        method_panel.setSpacing(8)

        self.button_php = Button("Send to PHP Service", self)
        self.button_py = Button("Send to Python Service", self)

        buttons = HorizontalPanel()
        buttons.add(self.button_php)
        buttons.add(self.button_py)
        buttons.setSpacing(8)
        
        info = """<h2>JSON-RPC Example</h2>
        <p>This example demonstrates the calling of server services with
           <a href="http://json-rpc.org/">JSON-RPC</a>.
        </p>
        <p>Enter some text below, and press a button to send the text
           to an Echo service on your server. An echo service simply sends the exact same text back that it receives.
           </p>"""
        
        panel = VerticalPanel()
        panel.add(HTML(info))
        panel.add(self.text_area)
        panel.add(method_panel)
        panel.add(buttons)
        panel.add(self.status)
        
        RootPanel().add(panel)
コード例 #16
0
ファイル: components.py プロジェクト: Afey/pyjs
    def __init__(self,parent):
        AbsolutePanel.__init__(self)

        self.roleList = ListBox()
        self.roleList.setWidth('300px')
        self.roleList.setVisibleItemCount(6)
        self.roleList.addChangeListener(self.onListChange)
        #self.roleList.addKeyboardListener(self)
        self.roleCombo = ListBox()
        self.roleCombo.addKeyboardListener(self)
        self.roleCombo.addChangeListener(self.onComboChange)
        self.addBtn = Button("Add")
        self.addBtn.setEnabled(False)
        self.removeBtn = Button("Remove")
        self.removeBtn.setEnabled(False)

        vpanel = VerticalPanel()
        vpanel.add(self.roleList)
        hpanel = HorizontalPanel()
        hpanel.add(self.roleCombo)
        hpanel.add(self.addBtn)
        hpanel.add(self.removeBtn)
        vpanel.add(hpanel)

        self.add(vpanel)
        self.clearForm()
        return
コード例 #17
0
class AlgorithmList(Composite):
    def __init__(self):
        Composite.__init__(self)

        self.vp_list=VerticalPanel()
        self.Algorithms=[]
        self.selectedAlgorithm=-1
        
        self.initWidget(self.vp_list)
        self.setStyleName("ks-List")

    def addAlgorithm(self, info):
        name = info.getName()
        link = Hyperlink(name, False, TargetHistoryToken=name)
        link.setStyleName("ks-AlgorithmItem")
        self.vp_list.add(link)
        self.Algorithms.append(info)

    def find(self, AlgorithmName):
        for info in self.Algorithms:
            if info.getName()==AlgorithmName:
                return info
        return None

    def setAlgorithmSelection(self, name):
        if self.selectedAlgorithm <> -1:
            self.vp_list.getWidget(self.selectedAlgorithm).removeStyleName("ks-AlgorithmItem-selected")

        for i in range(len(self.Algorithms)):
            info = self.Algorithms[i]
            if (info.getName()==name):
                self.selectedAlgorithm = i
                widget=self.vp_list.getWidget(self.selectedAlgorithm)
                widget.addStyleName("ks-AlgorithmItem-selected")
                return
コード例 #18
0
ファイル: KitchenSink.py プロジェクト: pyrrho314/recipesystem
    def onModuleLoad(self):
        self.curInfo=''
        self.curSink=None
        self.description=HTML()
        self.sink_list=SinkList()
        self.panel=DockPanel()
        
        self.loadSinks()
        self.sinkContainer = DockPanel()
        self.sinkContainer.setStyleName("ks-Sink")

        vp=VerticalPanel()
        vp.setWidth("100%")
        vp.add(self.description)
        vp.add(self.sinkContainer)

        self.description.setStyleName("ks-Info")

        self.panel.add(self.sink_list, DockPanel.WEST)
        self.panel.add(vp, DockPanel.CENTER)

        self.panel.setCellVerticalAlignment(self.sink_list, HasAlignment.ALIGN_TOP)
        self.panel.setCellWidth(vp, "100%")

        History.addHistoryListener(self)
        RootPanel().add(self.panel)
        RootPanel().add(Logger())

        #Show the initial screen.
        initToken = History.getToken()
        if len(initToken):
            self.onHistoryChanged(initToken)
        else:
            self.showInfo()
コード例 #19
0
ファイル: TopPanel.py プロジェクト: Afey/pyjs
    def __init__(self):

        Composite.__init__(self)

        self.signOutLink = HTML("<a href='javascript:;'>Sign Out</a>")
        self.aboutLink = HTML("<a href='javascript:;'>About</a>")

        outer = HorizontalPanel()
        inner = VerticalPanel()

        outer.setHorizontalAlignment(HasAlignment.ALIGN_RIGHT)
        inner.setHorizontalAlignment(HasAlignment.ALIGN_RIGHT)

        links = HorizontalPanel()
        links.setSpacing(4)
        links.add(self.signOutLink)
        links.add(self.aboutLink)

        outer.add(inner)
        inner.add(HTML("<b>Welcome back, [email protected]</b>"))
        inner.add(links)

        self.signOutLink.addClickListener(self)
        self.aboutLink.addClickListener(self)

        self.initWidget(outer)
        inner.setStyleName("mail-TopPanel")
        links.setStyleName("mail-TopPanelLinks")
コード例 #20
0
	def __init__(self):
		self.form = FormPanel()
		self.form.setAction("/Accession/searchByName/")
		
		# Because we're going to add a FileUpload widget, we'll need to set the
		# form to use the POST method, and multipart MIME encoding.
		self.form.setEncoding(FormPanel.ENCODING_MULTIPART)
		self.form.setMethod(FormPanel.METHOD_POST)
		
		# Create a panel to hold all of the form widgets.
		vpanel = VerticalPanel()
		self.form.setWidget(vpanel)
		
		self.colour_input = AutoCompleteByURLTextBox('/Accession/autoComplete')
		
		hpanel = HorizontalPanel()
		hpanel.add(HTML("Enter an ecotype name: "))
		hpanel.add(self.colour_input)

		hpanel.setSpacing(8)
		# Add a 'submit' button.
		hpanel.add(Button("Submit", self))

		vpanel.add(hpanel)
		
		# Add an event handler to the form.
		self.form.addFormHandler(self)
		
		self.setWidget(self.form)
コード例 #21
0
ファイル: absolutePanel.py プロジェクト: Afey/pyjs
    def makeBox(self, label):
        wrapper = VerticalPanel(BorderWidth=1)
        wrapper.add(HTML(label))
        DOM.setAttribute(wrapper.getTable(), "cellPadding", "10")
        DOM.setAttribute(wrapper.getTable(), "bgColor", "#C3D9FF")

        return wrapper
コード例 #22
0
ファイル: form.py プロジェクト: mcsquaredjr/Reports
class Form_Row(SimplePanel):
    '''
    Create row that will be put in the Form
    '''
    def __init__(self, name, widget, help=''):
        SimplePanel.__init__(self)
        # Container
        self.mainpanel = VerticalPanel()

        self.lbl = Label(name)
        self.hlp = Label(help)
        self.lbl.setStyleName('h3')
        self.hlp.setStyleName('text-muted')
        
        self.wdg = widget
        self.mainpanel.add(self.lbl)
        self.mainpanel.add(self.wdg)
        self.mainpanel.add(self.hlp)
        
    def panel(self):
        return self.mainpanel

    def widget(self):
        return self.wdg

    def help(self):
        return self.hlp
コード例 #23
0
ファイル: TheoremPanel.py プロジェクト: vizafogo123/pokpok
class TheoremPanel(ScrollPanel):
    def __init__(self, after):
        ScrollPanel.__init__(self, Size=("630px", "500px"))
        self.after = after
        self.pok = VerticalPanel()
        self.add(self.pok)
        self.images = list()

        def onItemSelected():
            item = self.list2.getItemText(self.list2.getSelectedIndex())
            self.refresh_theorems(item)

        self.list2 = ListBox()
        self.list2.setVisibleItemCount(1)
        for f in Theorem.get_all_folders():
            self.list2.addItem(f)
        self.pok.add(self.list2)
        self.list2.addChangeListener(onItemSelected)

        self.refresh_theorems(self.list2.getItemText(self.list2.getSelectedIndex()))

    def remove_images(self):
        for im in self.images:
            self.pok.remove(im)
        self.images = list()

    def refresh_theorems(self, folder):
        self.remove_images()

        def onClick(theorem):
            def name(n):
                return "var" + str(n + 1)

            def print_scheme(n):
                return ["\\alpha", "\\beta", "\\gamma", "\\delta", "\\epsilon"][n]

            def poas(sender):
                if len(theorem.operations) == 1:
                    constants = [Operation("const" + str(i + 1), 0, print_scheme(i), name(i), Operation.EXPRESSION)
                                 for i in range(theorem.operations[0].no_of_args)]

                    def after1(f):
                        self.after(
                            theorem.formula.substitute_definition(Formula([theorem.operations[0]] + constants), f),
                            predecessors=[], rule_name="insert")

                    request_formula([op for op in proof.get_operations()] + constants,
                                    after1, type=('rel' if theorem.operations[0].type == Operation.RELATION else 'exp'))
                else:
                    self.after(theorem.formula, predecessors=[], rule_name="insert")

            return poas

        for ax in [x for x in Theorem.theorems if x.folder == folder]:
            im = Image()
            im.addClickListener(onClick(ax))
            im.setUrl(latex_to_url(ax.formula.to_latex()))
            self.pok.add(im)
            self.images.append(im)
コード例 #24
0
ファイル: pjBallot.py プロジェクト: kurifu/Old-CMUSV-Voting
class pjBallot:
    
    def __init__(self):
        self.mainPanel = VerticalPanel()
        self.contest = HorizontalPanel()
        self.contest.setStyleName('words')
        self.selection = HorizontalPanel()
        self.selection.setStyleName('words')
        self.button = Button('test', self.test)
        self.x = 1
    
    def test(self):
        self.button.setText("No, really click me!")
#        Window.alert("Hello, AJAAAX!")
        self.contest.add(HTML('yay'))

    def nextContest(self):
        self.x += 1
        self.contest.clear()
        self.contest.add(HTML('<b /> Contest: %d' % self.x))

    def nextSelection(self):
        self.x += 1
        self.selection.clear()
        self.selection.add(HTML('<b /> Selection: %d' % self.x))
    
    def onKeyDown(self, sender, keycode, modifiers):
        pass

    def onKeyUp(self, sender, keycode, modifiers):
        pass

    def onKeyPress(self, sender, keycode, modifiers):
        DOM.eventPreventDefault(DOM.eventGetCurrentEvent()) #not needed
        if keycode == KeyboardListener.KEY_UP:
            self.nextContest()
        if keycode == KeyboardListener.KEY_DOWN:
            self.nextContest()
        if keycode == KeyboardListener.KEY_LEFT:
            self.nextSelection()
        if keycode == KeyboardListener.KEY_RIGHT:
            self.nextSelection()

    def onModuleLoad(self):
        h = HTML("<b />Contest: ")
        self.contest.add(h)
        l = HTML("<b />Selection: ")
        self.selection.add(l)
#        self.mainPanel.add(self.button)
        self.mainPanel.add(self.contest)
        self.mainPanel.add(self.selection)
        
        panel = FocusPanel(Widget=self.mainPanel)
        gp = RootPanelListener(panel)
        manageRootPanel(gp)
        RootPanel().add(panel)
        panel.setFocus(True)
コード例 #25
0
ファイル: Tabs.py プロジェクト: Afey/pyjs
    def createImage(self, imageUrl):
        image = Image(imageUrl)
        image.setStyleName("ks-images-Image")

        p = VerticalPanel()
        p.setHorizontalAlignment(HasAlignment.ALIGN_CENTER)
        p.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE)
        p.add(image)
        return p
コード例 #26
0
ファイル: Sidebar.py プロジェクト: rjw57/foldbeam
    def __init__(self, *args, **kwargs):
        super(Sidebar, self).__init__(*args, **kwargs)

        if self.getStylePrimaryName() is None:
            self.addStyleName("sidebar")

        vp = VerticalPanel(Size=("100%", "100%"))
        self._layers_panel = LayersPanel(Width="100%")
        vp.add(self._layers_panel)
        self.setWidget(vp)
コード例 #27
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
コード例 #28
0
    def get_home_panel(self):
        panel = VerticalPanel()

        title = HTML("""OpenPowerSystem""")
        panel.add(title)

        subtitle = HTML("""The Open Power System data repository.""")
        panel.add(subtitle)

        return panel
コード例 #29
0
 def __init__(self, message, messageTitle="Error"):
     self.dialog = DialogBox(glass=True)
     self.dialog.setHTML("<b>" + messageTitle + "</b>")
     dialogContents = VerticalPanel(StyleName="Contents", Spacing=4)
     dialogContents.add(HTML(message))
     dialogContents.add(Button("Close", getattr(self, "onClose")))
     self.dialog.setWidget(dialogContents)
     left = (Window.getClientWidth() - 200) / 2 + Window.getScrollLeft()
     top = (Window.getClientHeight() - 100) / 2 + Window.getScrollTop()
     self.dialog.setPopupPosition(left, top)
     self.dialog.show()
コード例 #30
0
ファイル: popupPanel.py プロジェクト: Afey/pyjs
    def __init__(self):
        SimplePanel.__init__(self)

        vPanel = VerticalPanel(Spacing=4)

        self._btn = Button("Click Me", getattr(self, "showPopup"))

        vPanel.add(HTML("Click on the button below to display the popup."))
        vPanel.add(self._btn)

        self.add(vPanel)
コード例 #31
0
    def __init__(self, categoryChangeListener):
        HorizontalPanel.__init__(self,
                                 StyleName="category_block select_block",
                                 Width='100%')
        self.categoryChangeListener = categoryChangeListener

        self.add(Label('Categoria:'))
        verticalPanel = VerticalPanel(Width='100%')
        self.add(verticalPanel)
        horizontalPanel = HorizontalPanel(Width='100%')
        verticalPanel.add(horizontalPanel)

        fake = Element(Element=DOM.createDiv())

        self.control = getattr(ArduinoBlocks, 'alphaNumericType')('Controle',
                                                                  'orange',
                                                                  off=True)
        fake.append(self.control)
        self.controlType = RadioButton("groupCategory",
                                       fake.getElement().innerHTML, True)
        self.controlType.setChecked(True)
        self.controlType.addClickListener(getattr(self, "onClickControlType"))
        horizontalPanel.add(self.controlType)
        fake.removeAll()

        self.operators = getattr(ArduinoBlocks,
                                 'alphaNumericType')('Operadores',
                                                     'green',
                                                     off=True)
        fake.append(self.operators)
        self.operatorsType = RadioButton("groupCategory",
                                         fake.getElement().innerHTML, True)
        self.operatorsType.addClickListener(
            getattr(self, "onClickOperatorsType"))
        horizontalPanel.add(self.operatorsType)
        horizontalPanel = HorizontalPanel(Width='100%')
        verticalPanel.add(horizontalPanel)
        fake.removeAll()

        self.input = getattr(ArduinoBlocks, 'alphaNumericType')('Entrada',
                                                                'purple',
                                                                off=True)
        fake.append(self.input)
        self.inputType = RadioButton("groupCategory",
                                     fake.getElement().innerHTML, True)
        self.inputType.addClickListener(getattr(self, "onClickInputType"))
        horizontalPanel.add(self.inputType)
        fake.removeAll()

        self.output = getattr(ArduinoBlocks, 'alphaNumericType')('Saida',
                                                                 'blue',
                                                                 off=True)
        fake.append(self.output)
        self.outputType = RadioButton("groupCategory",
                                      fake.getElement().innerHTML, True)
        self.outputType.addClickListener(getattr(self, "onClickOutputType"))
        horizontalPanel.add(self.outputType)
        horizontalPanel = HorizontalPanel(Width='100%')
        verticalPanel.add(horizontalPanel)
        fake.removeAll()

        self.utilities = getattr(ArduinoBlocks,
                                 'alphaNumericType')('Utilitarios',
                                                     'darkblue',
                                                     off=True)
        fake.append(self.utilities)
        self.utilitiesType = RadioButton("groupCategory",
                                         fake.getElement().innerHTML, True)
        self.utilitiesType.addClickListener(
            getattr(self, "onClickUtilitiesType"))
        horizontalPanel.add(self.utilitiesType)
        fake.removeAll()

        self.variables = getattr(ArduinoBlocks,
                                 'alphaNumericType')('Variaveis',
                                                     'red',
                                                     off=True)
        fake.append(self.variables)
        self.variablesType = RadioButton("groupCategory",
                                         fake.getElement().innerHTML, True)
        self.variablesType.addClickListener(
            getattr(self, "onClickVariablesType"))
        horizontalPanel.add(self.variablesType)

        self.onClickControlType()
コード例 #32
0
    def __init__(self, chart):
        """ DialogBox CSS Style self.settings used with this example for reference:

        Note: These simplified CSS styles make the dialog's title bar behave a
        little quirkily in IE6 when dragging. For more sophisticated CSS that
        fixes this problem (and also provides a more professional look) see the
        CSS tab of the DialogBox example in the GWT <a href="xxx"> Showcase of
        Features</a> (I just didn't want to copy 5 pages of obscure DialogBox
        CSS into what is after all a Client-side GChart example).

        .gwt-DialogBox .Caption {
            font-size: 18
            color: #eef
            background: #00f repeat-x 0px -2003px
            padding: 4px 4px 4px 8px
            cursor: default
            border-bottom: 2px solid #008
            border-top: 3px solid #448


        .gwt-DialogBox .dialogContent {
            border: 1px solid #008
            background: #ddd
            padding: 3px


        """
        DialogBox.__init__(self, autoHide=True, modal=True)
        self.chart = chart
        self.isFirstTime = True
        mainPanel = VerticalPanel()
        propertyForm = FlexTable()
        commandBar = DockPanel()
        sliceSwitcher = HorizontalPanel()
        self.prevSlice = Button("&lt;Prev Slice", self)
        self.nextSlice = Button("Next Slice&gt;", self)
        self.closeButton = Button("Close", self)

        self.chart.colorSelector.addChangeListener(self)
        self.chart.sliceSizeSelector.addChangeListener(self)
        self.chart.shadingSelector.addChangeListener(self)

        #self.prevSlice.addClickListener(self)
        #self.nextSlice.addClickListener(self)
        #self.closeButton.addClickListener(self)

        # slice properties table (slice color, shading and size)
        propertyForm.setSize(3, 2)
        propertyForm.setText(0, 0, "Color:")
        propertyForm.setWidget(0, 1, self.chart.colorSelector)
        propertyForm.setText(1, 0, "Shading Pattern:")
        propertyForm.setWidget(1, 1, self.chart.shadingSelector)
        propertyForm.setText(2, 0, "Slice Size:")
        propertyForm.setWidget(2, 1, self.chart.sliceSizeSelector)
        # add additional properties here, if desired

        # buttons for changing the selected slice from the form
        sliceSwitcher.add(self.prevSlice)
        sliceSwitcher.add(self.nextSlice)

        commandBar.add(sliceSwitcher, DockPanel.WEST)
        commandBar.add(self.closeButton, DockPanel.EAST)
        commandBar.setCellHorizontalAlignment(
            self.closeButton, HasHorizontalAlignment.ALIGN_RIGHT)
        commandBar.setWidth("100%")
        # pushes close button to right edge

        # create main form and place it in DialogBox
        mainPanel.add(propertyForm)
        mainPanel.add(commandBar)
        self.setWidget(mainPanel)
コード例 #33
0
class RichTextToolbar(Composite, ClickHandler, ChangeHandler):

    fontSizesConstants = [
        RichTextAreaConsts.XX_SMALL, RichTextAreaConsts.X_SMALL,
        RichTextAreaConsts.SMALL, RichTextAreaConsts.MEDIUM,
        RichTextAreaConsts.LARGE, RichTextAreaConsts.X_LARGE,
        RichTextAreaConsts.XX_LARGE
    ]
    """*
    * Creates a toolbar that drives the given rich text area.
    *
    * @param richText the rich text area to be controlled
    """
    def __init__(self, richText, _parent, **kwargs):

        self.isInText = False
        self.lastText = ""
        self.trigger = False
        self.lastRange = None
        self._parent = _parent

        # Timer for trying real time selection change stuff
        self.timerRange = None
        self.selTimer = Timer(notify=self.run)

        self.outer = VerticalPanel()
        self.topPanel = HorizontalPanel(BorderWidth=1)
        self.bottomPanel = HorizontalPanel()

        self.richText = richText
        self.basic = richText.getBasicFormatter()
        self.extended = richText.getExtendedFormatter()

        self.outer.add(self.topPanel)
        self.outer.add(self.bottomPanel)
        self.topPanel.setWidth("100%")
        self.topPanel.setHeight("20px")
        self.bottomPanel.setWidth("100%")

        kwargs['StyleName'] = kwargs.get('StyleName', "gwt-RichTextToolbar")

        Composite.__init__(self, self.outer, **kwargs)
        ClickHandler.__init__(self)
        ChangeHandler.__init__(self)

        if self.basic is not None:
            self.bold = self.createToggleButton(Images.bold, "bold")
            self.italic = self.createToggleButton(Images.italic, "italic")
            self.underline = self.createToggleButton(Images.underline,
                                                     "underline")
            self.subscript = self.createToggleButton(Images.subscript,
                                                     "subscript")
            self.superscript = self.createToggleButton(Images.superscript,
                                                       "superscript")
            self.justifyLeft = self.createPushButton(Images.justifyLeft,
                                                     "justify left")
            self.justifyCenter = self.createPushButton(Images.justifyCenter,
                                                       "justify centre")
            self.justifyRight = self.createPushButton(Images.justifyRight,
                                                      "justify right")
            self.topPanel.add(self.bold)
            self.topPanel.add(self.italic)
            self.topPanel.add(self.underline)
            self.topPanel.add(self.subscript)
            self.topPanel.add(self.superscript)
            self.topPanel.add(self.justifyLeft)
            self.topPanel.add(self.justifyCenter)
            self.topPanel.add(self.justifyRight)

        if self.extended is not None:
            self.strikethrough = self.createToggleButton(
                Images.strikeThrough, "strikethrough")
            self.indent = self.createPushButton(Images.indent, "indent")
            self.outdent = self.createPushButton(Images.outdent, "outdent")
            self.hr = self.createPushButton(Images.hr, "hr")
            self.ol = self.createPushButton(Images.ol, "ordered list")
            self.ul = self.createPushButton(Images.ul, "unordered list")
            self.insertImage = self.createPushButton(Images.insertImage,
                                                     "insert image")
            self.createLink = self.createPushButton(Images.createLink,
                                                    "create link")
            self.removeLink = self.createPushButton(Images.removeLink,
                                                    "remove link")
            self.removeFormat = self.createPushButton(Images.removeFormat,
                                                      "remove formatting")

            self.topPanel.add(self.strikethrough)
            self.topPanel.add(self.indent)
            self.topPanel.add(self.outdent)
            self.topPanel.add(self.hr)
            self.topPanel.add(self.ol)
            self.topPanel.add(self.ul)
            self.topPanel.add(self.insertImage)
            self.topPanel.add(self.createLink)
            self.topPanel.add(self.removeLink)
            self.topPanel.add(self.removeFormat)

        if self.basic is not None:
            self.hstyles = self.createHeadingStyleList("Headings")
            self.backColors = self.createColorList("Background")
            self.foreColors = self.createColorList("Foreground")
            self.fonts = self.createFontList()
            self.fontSizes = self.createFontSizes()
            self.bottomPanel.add(self.hstyles)
            self.bottomPanel.add(self.backColors)
            self.bottomPanel.add(self.foreColors)
            self.bottomPanel.add(self.fonts)
            self.bottomPanel.add(self.fontSizes)

        self.richText.addKeyboardListener(self)
        self.richText.addClickListener(self)
        self.richText.addFocusListener(self)
        self.richText.addMouseListener(self)

    def createHeadingStyleList(self, caption):
        lb = ListBox()
        lb.addChangeListener(self)
        lb.setVisibleItemCount(1)

        lb.addItem(caption)
        lb.addItem("Heading1", "h1")
        lb.addItem("Heading2", "h2")
        lb.addItem("Heading3", "h3")
        lb.addItem("Heading4", "h4")
        lb.addItem("Heading5", "h5")

        return lb

    def createColorList(self, caption):
        lb = ListBox()
        lb.addChangeListener(self)
        lb.setVisibleItemCount(1)

        lb.addItem(caption)
        lb.addItem("White", "white")
        lb.addItem("Black", "black")
        lb.addItem("Red", "red")
        lb.addItem("Green", "green")
        lb.addItem("Yellow", "yellow")
        lb.addItem("Blue", "blue")
        return lb

    def createFontList(self):
        lb = ListBox()
        lb.addChangeListener(self)
        lb.setVisibleItemCount(1)

        lb.addItem("Font", "")
        lb.addItem("Normal", "")
        lb.addItem("Times New Roman", "Times New Roman")
        lb.addItem("Arial", "Arial")
        lb.addItem("Aramanth", "Aramanth")
        lb.addItem("Calibri", "Calibri")
        lb.addItem("Courier New", "Courier New")
        lb.addItem("Georgia", "Georgia")
        lb.addItem("Helvetica", "Helvetica")
        lb.addItem("Symbol", "Symbol")
        lb.addItem("Trebuchet", "Trebuchet")
        lb.addItem("Verdana", "Verdana")
        return lb

    def createFontSizes(self):
        lb = ListBox()
        lb.addChangeListener(self)
        lb.setVisibleItemCount(1)

        lb.addItem("Size")
        lb.addItem("XXsmall")
        lb.addItem("Xsmall")
        lb.addItem("small")
        lb.addItem("medium")
        lb.addItem("large")
        lb.addItem("Xlarge")
        lb.addItem("XXlarge")
        return lb

    def createPushButton(self, img, tip):
        img = Image(img)
        pb = PushButton(img, img, self)
        pb.setTitle(tip)
        return pb

    def createToggleButton(self, img, tip):
        img = Image(img)
        tb = ToggleButton(img, img, self)
        tb.setTitle(tip)
        return tb

    def updateStatus(self):
        """* Updates the status of all the stateful buttons.
        """
        if self.basic is not None:
            self.bold.setDown(self.basic.isBold())
            self.italic.setDown(self.basic.isItalic())
            self.underline.setDown(self.basic.isUnderlined())
            self.subscript.setDown(self.basic.isSubscript())
            self.superscript.setDown(self.basic.isSuperscript())

        if self.extended is not None:
            self.strikethrough.setDown(self.extended.isStrikethrough())

    def onChange(self, sender):
        if sender == self.hstyles:
            bc = self.hstyles.getValue(self.hstyles.getSelectedIndex())
            self._surround(HeadingStyleManager, bc)
            self.backColors.setSelectedIndex(0)
        if sender == self.backColors:
            bc = self.backColors.getValue(self.backColors.getSelectedIndex())
            self.basic.setBackColor(bc)
            self.backColors.setSelectedIndex(0)
        elif sender == self.foreColors:
            fc = self.foreColors.getValue(self.foreColors.getSelectedIndex())
            self.basic.setForeColor(fc)
            self.foreColors.setSelectedIndex(0)
        elif sender == self.fonts:
            fname = self.fonts.getValue(self.fonts.getSelectedIndex())
            self.basic.setFontName(fname)
            self.fonts.setSelectedIndex(0)
        elif sender == self.fontSizes:
            fs = self.fontSizesConstants[self.fontSizes.getSelectedIndex() - 1]
            self.basic.setFontSize(fs)
            self.fontSizes.setSelectedIndex(0)

    def onClick(self, sender):

        if sender == self.bold:
            self.basic.toggleBold()
        elif sender == self.italic:
            self.basic.toggleItalic()
        elif sender == self.underline:
            self.basic.toggleUnderline()
        elif sender == self.subscript:
            self.basic.toggleSubscript()
        elif sender == self.superscript:
            self.basic.toggleSuperscript()
        elif sender == self.strikethrough:
            self.extended.toggleStrikethrough()
        elif sender == self.indent:
            self.extended.rightIndent()
        elif sender == self.outdent:
            self.extended.leftIndent()
        elif sender == self.justifyLeft:
            self.basic.setJustification(RichTextAreaConsts.LEFT)
        elif sender == self.justifyCenter:
            self.basic.setJustification(RichTextAreaConsts.CENTER)
        elif sender == self.justifyRight:
            self.basic.setJustification(RichTextAreaConsts.RIGHT)
        elif sender == self.insertImage:
            url = Window.prompt("Enter an image URL:", "http:#")
            if url is not None:
                self.extended.insertImage(url)

        elif sender == self.createLink:
            EventLinkPopup_open(self)

        elif sender == self.removeLink:
            self.extended.removeLink()
        elif sender == self.hr:
            self.extended.insertHorizontalRule()
        elif sender == self.ol:
            self.extended.insertOrderedList()
        elif sender == self.ul:
            self.extended.insertUnorderedList()
        elif sender == self.removeFormat:
            self.extended.removeFormat()
        elif sender == self.richText:
            # We use the RichTextArea's onKeyUp event to update the
            # toolbar status.  This will catch any cases where the
            # user moves the cursor using the keyboard, or uses one of
            # the browser's built-in keyboard shortcuts.
            self.updateStatus()

        self.checkForChange()

    def onKeyDown(self, sender, keyCode, modifiers):
        pass

    def onKeyPress(self, sender, keyCode, modifiers):
        pass

    def onKeyUp(self, sender, keyCode, modifiers):
        if sender == self.richText:
            # We use the RichTextArea's onKeyUp event to update the
            # toolbar status.  This will catch any cases where the user
            # moves the cursor using the keyboard, or uses one of
            # the browser's built-in keyboard shortcuts.
            self.updateStatus()
            self.checkForChange()

    def onMouseLeave(self, event):
        pass

    def onMouseEnter(self, event):
        pass

    def onMouseUp(self, event, x, y):
        pass

    def onMouseMove(self, event, x, y):
        pass

    def onMouseDown(self, event, x, y):
        self.trigger = True

    def onFocus(self, event):
        print "focus"
        pass

    def onLostFocus(self, event):
        "lost focus"
        self.checkForChange()

    def onMouseOut(self, sender):
        print "mouse out"
        if self.isInText and self.isOnTextBorder(sender):
            self.isInText = False
            self.captureSelection()
            self.endSelTimer()

    def onMouseOver(self, sender):
        print "mouse over"
        if not self.isInText:
            self.isInText = True
            self.richText.setFocus(True)
            self.lastRange = None
            self.startSelTimer()

    def setFocus(self, wid):
        self._wid = wid  # hack
        DeferredCommand.add(getattr(self, "execute_set_focus"))

    def execute_set_focus(self):
        self._wid.setFocus(True)

    def findNodeByNumber(self, num):

        doc = self.getDocument()
        res = getAdjacentTextElement(doc, True)
        while (res is not None) and (num > 0):
            num -= 1
            res = getAdjacentTextElement(res, True)

        return res

    def selectNodes(self,
                    startNode,
                    startOffset,
                    endNode=None,
                    endOffset=None):

        startText = self.findNodeByNumber(startNode)
        if endNode is not None:
            endText = self.findNodeByNumber(endNode)
        else:
            endText = startText
            endOffset = startOffset

        rng = Range(RangeEndPoint(startText, startOffset),
                    RangeEndPoint(endText, endOffset))

        self.getSelection()
        Selection.setRange(rng)

        self.refresh()

    def font1(self):
        self._surround(FontFamilyManager, "Times New Roman")

    def font2(self):
        self._surround(FontFamilyManager, "Arial")

    def surround1(self):
        self._surround(CustomStyleManager, "editor-cls1")

    def surround2(self):
        self._surround(CustomStyleManager, "editor-cls2")

    def _surround(self, kls, cls):
        """ this is possibly one of the most truly dreadful bits of code
            for manipulating DOM ever written.  its purpose is to add only
            the editor class required, and no more.  unfortunately, DOM gets
            chopped up by the range thing, and a bit more besides.  so we
            have to:

            * extract the range contents
            * clean up removing any blank text nodes that got created above
            * slap a span round it
            * clean up removing any blank text nodes that got created above
            * remove any prior editor styles on the range contents
            * go hunting through the entire document for stacked editor styles

            this latter is funfunfun because only "spans with editor styles
            which themselves have no child elements but a single span with
            an editor style" must be removed.  e.g. if an outer editor span
            has another editor span and also some text, the outer span must
            be left alone.
        """
        rng = self.getRange()
        if (rng is None) or rng.isCursor():
            return

        csm = kls(rng.m_document, cls)

        rng.ensureRange()
        dfrag = rng.m_range.extractContents()
        remove_editor_styles(rng.m_document, csm, dfrag)
        element = csm.create()
        DOM.appendChild(element, dfrag)
        rng.m_range.insertNode(element)

        it = DOM.IterWalkChildren(element, True)
        while True:
            try:
                node = it.next()
            except StopIteration:
                break
            if node.nodeType == 3 and unicode(node.data) == u'':
                DOM.removeChild(node.parentNode, node)

        rng.setRange(element)

        it = DOM.IterWalkChildren(rng.m_document, True)
        while True:
            try:
                node = it.next()
            except StopIteration:
                break
            if node.nodeType == 3 and unicode(node.data) == u'':
                DOM.removeChild(node.parentNode, node)

        # clears out all nodes with no children.
        it = DOM.IterWalkChildren(rng.m_document)
        while True:
            try:
                node = it.next()
            except StopIteration:
                break
            if node.firstChild or not csm.identify(node):
                continue
            DOM.removeChild(node.parentNode, node)

        it = DOM.IterWalkChildren(rng.m_document, True)
        while True:
            try:
                node = it.next()
            except StopIteration:
                break
            if not csm.identify(node):
                continue
            if node.firstChild is None:
                continue
            if not csm.identify(node.firstChild):
                continue
            if node.firstChild.nextSibling:
                continue
            # remove the *outer* one because the range was added to
            # the inner, and the inner one overrides anyway

            remove_node(rng.m_document, node)

        doc = self.getDocument()

        self.getSelection()
        Selection.setRange(rng)
        self.refresh()

    def refresh(self):
        self._parent.refresh()

    def delete(self):
        rng = self.getRange()
        if rng is None or rng.isCursor():
            return
        rng.deleteContents()
        refresh()

    def toCursor(self, start):
        rng = self.getRange()
        if rng is None or rng.isCursor():
            return
        rng.collapse(start)
        self.getSelection()
        Selection.setRange(rng)
        self.refresh()

    def run(self):
        try:
            self.getSelection()
            rng = Selection.getRange()
            if (self.timerRange is None) or (not self.timerRange.equals(rng)):
                self.onSelectionChange(rng)
                self.timerRange = rng

        except:
            GWT.log("Error in timer selection", ex)

    def getSelection(self):
        res = None
        try:
            window = self.getWindow()
            Selection.getSelection(window)

        except:
            print "Error getting the selection"
            traceback.print_exc()

    def getWindow(self, iFrame=None):
        if iFrame is None:
            iFrame = self.richText.getElement()
        iFrameWin = iFrame.contentWindow or iFrame.contentDocument

        if not iFrameWin.document:
            iFrameWin = iFrameWin.parentNode  # FBJS version of parentNode

        #print "getWindow", iFrameWin, dir(iFrameWin)

        return iFrameWin

    def captureSelection(self):
        """ This captures the selection when the mouse leaves the RTE,
            because in IE the selection indicating the cursor position
            is lost once another widget gains focus.
            Could be implemented for IE only.
        """
        try:
            self.getSelection()
            self.lastRange = Selection.getRange()

        except:
            GWT.log("Error capturing selection for IE", ex)

    # Gets run every time the selection is changed
    def onSelectionChange(self, sel):
        pass

    def isOnTextBorder(self, sender):
        twX = self.richText.getAbsoluteLeft()
        twY = self.richText.getAbsoluteTop()
        x = event.getClientX() - twX
        y = event.getClientY() - twY
        width = self.richText.getOffsetWidth()
        height = self.richText.getOffsetHeight()
        return ((sender == self.richText)
                and ((x <= 0) or (x >= width) or (y <= 0) or (y >= height)))

    def startSelTimer(self):
        self.selTimer.scheduleRepeating(250)

    def endSelTimer(self):
        self.selTimer.cancel()

    def getRange(self):
        if self.lastRange is None:
            self.getSelection()
            return Selection.getRange()
        else:
            return self.lastRange

    def checkForChange(self):
        text = self.richText.getHTML()
        if text == self.lastText:
            return
        nEvt = doc().createEvent("HTMLEvents")
        nEvt.initEvent("change", False, True)
        self.getElement().dispatchEvent(nEvt)
        self.lastText = text

    def setHtml(self, text):
        self.richText.setHTML(text)
        self.lastText = text

    def getHtml(self):
        return self.richText.getHTML()

    def getDocument(self):
        return Selection.getDocument(self.getWindow())

    def getFormatter(self):
        return self.richText.getExtendedFormatter()
コード例 #34
0
ファイル: Layouts.py プロジェクト: ygyangguang/pyjs
    def __init__(self):
        Sink.__init__(self)

        text="""This is a <code>ScrollPanel</code> contained at
        the center of a <code>DockPanel</code>.
        By putting some fairly large contents
        in the middle and setting its size explicitly, it becomes a
        scrollable area within the page, but without requiring the use of
        an IFRAME.
        Here's quite a bit more meaningless text that will serve primarily
        to make this thing scroll off the bottom of its visible area.
        Otherwise, you might have to make it really, really small in order
        to see the nifty scroll bars!"""

        contents = HTML(text)
        scroller = ScrollPanel(contents, StyleName="ks-layouts-Scroller")

        dock = DockPanel(HorizontalAlignment=HasAlignment.ALIGN_CENTER,
                         Spacing=10)
        north0 = HTML("This is the <i>first</i> north component", True)
        east = HTML("<center>This<br>is<br>the<br>east<br>component</center>", True)
        south = HTML("This is the south component")
        west = HTML("<center>This<br>is<br>the<br>west<br>component</center>", True)
        north1 = HTML("This is the <b>second</b> north component", True)
        dock.add(north0, DockPanel.NORTH)
        dock.add(east, DockPanel.EAST)
        dock.add(south, DockPanel.SOUTH)
        dock.add(west, DockPanel.WEST)
        dock.add(north1, DockPanel.NORTH)
        dock.add(scroller, DockPanel.CENTER)

        #Logger.write("Layouts", "TODO: flowpanel")
        flow = FlowPanel()
        for i in range(8):
            flow.add(CheckBox("Flow %d" % i))

        horz = HorizontalPanel(VerticalAlignment=HasAlignment.ALIGN_MIDDLE)
        horz.add(Button("Button"))
        horz.add(HTML("<center>This is a<br>very<br>tall thing</center>", True))
        horz.add(Button("Button"))

        vert = VerticalPanel(HorizontalAlignment=HasAlignment.ALIGN_CENTER)
        vert.add(Button("Small"))
        vert.add(Button("--- BigBigBigBig ---"))
        vert.add(Button("tiny"))

        menu = MenuBar()
        menu0 = MenuBar(True)
        menu1 = MenuBar(True)
        menu.addItem("menu0", menu0)
        menu.addItem("menu1", menu1)
        menu0.addItem("child00")
        menu0.addItem("child01")
        menu0.addItem("child02")
        menu1.addItem("child10")
        menu1.addItem("child11")
        menu1.addItem("child12")

        #Logger.write("Layouts", "TODO: htmlpanel")
        id = HTMLPanel.createUniqueId()
        text="""This is an <code>HTMLPanel</code>.  It allows you to add
            components inside existing HTML, like this: <span id='%s' />
            Notice how the menu just fits snugly in there?  Cute.""" % id
        html = HTMLPanel(text)

        DOM.setStyleAttribute(menu.getElement(), "display", "inline")
        html.add(menu, id)

        disclose = DisclosurePanel("Click to disclose")
        disclose.add(HTML("""<b>Ta-daaaaa!</b><br />Ok - it could have
                             been<br />more of a surprise."""))

        panel = VerticalPanel(Spacing=8,
                              HorizontalAlignment=HasAlignment.ALIGN_CENTER)

        panel.add(self.makeLabel("Dock Panel"))
        panel.add(dock)
        panel.add(self.makeLabel("Flow Panel"))
        panel.add(flow)
        panel.add(self.makeLabel("Horizontal Panel"))
        panel.add(horz)
        panel.add(self.makeLabel("Vertical Panel"))
        panel.add(vert)
        panel.add(self.makeLabel("HTML Panel"))
        panel.add(html)
        panel.add(self.makeLabel("Disclosure Panel"))
        panel.add(disclose)

        self.initWidget(panel)
        self.setStyleName("ks-layouts")
コード例 #35
0
class HangManWidget(Composite):
    def __init__(self):
        Composite.__init__(self)
        self.guesses = 0
        self.score = 0
        self.level = 5
        self.answer = ''
        self.blanks = ''

        self.vp_main = VerticalPanel()
        self.vp_main.setSpacing(4)
        self.hangdude = HangDude()
        self.cmdNew = Button("Start", self)

        self.radLevel5 = RadioButton("group0", "5-10 letters")
        self.radLevel5.setChecked(True)
        self.radLevel10 = RadioButton("group0", "10-15 letters")
        self.radLevel15 = RadioButton("group0", "15-20 letters")
        self.radLevel20 = RadioButton("group0", "20+ letters")

        self.radLevel5.addClickListener(self.onRadioSelect)
        self.radLevel10.addClickListener(self.onRadioSelect)
        self.radLevel15.addClickListener(self.onRadioSelect)
        self.radLevel20.addClickListener(self.onRadioSelect)

        self.rad_hp = HorizontalPanel()
        self.rad_hp.setSpacing(4)
        self.rad_hp.add(self.radLevel5)
        self.rad_hp.add(self.radLevel10)
        self.rad_hp.add(self.radLevel15)
        self.rad_hp.add(self.radLevel20)
        self.rad_hp.add(self.cmdNew)

        self.puzzlestring = HTML()

        self.key_widgets = []
        for i in range (len(string.uppercase)):
            self.key_widgets.append(Button(string.uppercase[i:i+1], self))

        self.toprow = HorizontalPanel()
        self.midrow = HorizontalPanel()
        self.botrow = HorizontalPanel()

        for i in range(len(self.key_widgets)):
            if i <= 7:
                 self.toprow.add(self.key_widgets[i])
            elif i <= 16:
                 self.midrow.add(self.key_widgets[i])
            else:
                 self.botrow.add(self.key_widgets[i])

        self.vp_main.add(self.hangdude)
        self.vp_main.add(self.puzzlestring)
        self.vp_main.add(self.toprow)
        self.vp_main.add(self.midrow)
        self.vp_main.add(self.botrow)
        self.vp_main.add(self.rad_hp)

        for i in range(1,12):
            self.hangdude.draw(i)

        self.setWidget(self.vp_main)

    def onClick(self, sender):
        found = False
        if sender == self.cmdNew:
            self.blanks = ''
            self.hangdude.clear()
            self.guesses = 0
            self.score = 0
            for i in range(len(self.key_widgets)):
                self.key_widgets[i].setEnabled(True)
            if self.level == 5:
                words = Wordlist_5.words
            elif self.level == 10:
                words = Wordlist_10.words
            elif self.level == 15:
                words = Wordlist_15.words
            elif self.level == 20:
                words = Wordlist_20.words
            #pick a random word
            g = random.Random()
            r = int( g.random() * len(words))
            self.answer = words[r].upper()
            for i in range(len(self.answer)):
                if self.answer[i] == ' ':
                    self.blanks += '  '
                else:
                    self.blanks += '_ '
            self.puzzlestring.setHTML(self.blanks)
        else:
            guess_letter = sender.getText()
            sender.setEnabled(False)
            for i in range(len(self.answer)):
                if self.answer[i:i+1] == guess_letter:
                    j=i+1
                    self.blanks = self.blanks[0:(j*2)-2] + guess_letter + ' ' + self.blanks[j*2:]
                    found = True
                    self.score += 1
            self.puzzlestring.setHTML(self.blanks)
            if not found:
                self.guesses += 1
                self.hangdude.draw(self.guesses)
                if self.guesses >= 11:
                    Window.alert("You lose! Answer: " + self.answer)
            else:
                if self.score >= len(self.answer):
                    Window.alert("You win!")

    def onRadioSelect(self, sender, keyCode=None, modifiers=None):
        if sender == self.radLevel5:
            self.level = 5
        elif sender == self.radLevel10:
            self.level = 10
        elif sender == self.radLevel15:
            self.level = 15
        elif sender == self.radLevel20:
            self.level = 20
コード例 #36
0
ファイル: Photos.py プロジェクト: minghuascode/pyj
class Photos(Composite):
    def __init__(self):
        Composite.__init__(self)

        self.albums = []
        self.photos = []
        self.grid = Grid(4, 4, CellPadding=4, CellSpacing=4)
        self.grid.addTableListener(self)
        self.drill = 0
        self.pos = 0
        self.up = Button("Up", self)
        self.next = Button("Next", self)
        self.prev = Button("Prev", self)
        self.timer = Timer(notify=self)
        self.userid = "jameskhedley"
        self.album_url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "?alt=json-in-script&kind=album&hl=en_US&callback=restCb"
        self.doRESTQuery(self.album_url, self.timer)

        self.vp = VerticalPanel()
        self.disclosure = DisclosurePanel(
            "Click for boring technical details.")
        self.disclosure.add(
            HTML(
                '''<p>OK so you want to write client JS to do a RESTful HTTP query from picasa right?
				 Well you can't because of the Same Origin Policy. Basically this means that
				 because the domain of the query and the domain of the hosted site are different,
				 then that could well be a cross-site scripting (XSS) attack. So, the workaround is to
				 do the call from a script tag so the JSON we get back is part of the document. 
				 But since we don't know what URL to hit yet, once we find out then we have to inject
				 a new script tag dynamically which the browser will run as soon as we append it.
				 To be honest I'm not 100% why Google use RESTful services and not JSON-RPC or somesuch,
				 which would be easier. Well, easier for me.'''))

        self.IDPanel = HorizontalPanel()
        self.IDPanel.add(Label("Enter google account:"))
        self.IDButton = Button("Go", self)

        self.IDBox = TextBox()
        self.IDBox.setText(self.userid)
        self.IDPanel.add(self.IDBox)
        self.IDPanel.add(self.IDButton)
        self.vp.add(self.IDPanel)
        self.vp.add(self.disclosure)
        self.vp.add(self.grid)

        self.initWidget(self.vp)

    def doRESTQuery(self, url, timer):
        """this is a totally different from an RPC call in that we have to
           dynamically add script tags to the DOM when we want to query the 
           REST API. These rely on callbacks in the DOM so we can either add 
           them dynamically or pre-define them in public/Main.html. 
           Once we've done that have to wait for the response.
           Which means we need to provide a listener for the timer"""

        new_script = DOM.createElement("script")
        DOM.setElemAttribute(new_script, "src", url)
        DOM.setElemAttribute(new_script, "type", "text/javascript")
        doc().body.appendChild(new_script)
        self.timer.schedule(100)

    def onCellClicked(self, sender, row, col):
        if self.drill == 0:
            self.drill += 1
            self.vp.clear()
            self.grid.clear()
            self.vp.add(self.up)
            self.vp.add(self.grid)
            gridcols = self.grid.getColumnCount()
            album = self.albums[row + col + (row * (gridcols - 1))]
            url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "/albumid/" + album[
                "id"] + "?alt=json-in-script&kind=photo&hl=en_US&callback=restCb"
            self.doRESTQuery(url, self.timer)
        elif self.drill == 1:
            self.drill += 1
            gridcols = self.grid.getColumnCount()
            self.pos = row + col + (row * (gridcols - 1))
            photo = self.photos[self.pos]
            self.vp.clear()
            self.fullsize = HTML('<img src="' + photo["full"] + '"/>')
            hp = HorizontalPanel()
            hp.add(self.up)
            hp.add(self.prev)
            hp.add(self.next)
            hp.setSpacing(8)
            self.vp.add(hp)
            self.vp.add(self.fullsize)

    def onClick(self, sender):
        if sender == self.IDButton:
            self.userid = self.IDBox.getText()
            if self.userid == "" or self.userid.isdigit():
                return
            self.drill = 0
            self.album_url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "?alt=json-in-script&kind=album&hl=en_US&callback=restCb"
            self.grid.clear()
            self.doRESTQuery(self.album_url, self.timer)
        else:
            if self.drill == 2:
                if sender == self.up:
                    self.drill = 1
                    self.vp.clear()
                    self.vp.add(self.up)
                    self.vp.add(self.grid)
                    self.fillGrid(self.photos, "photos")
                else:
                    if sender == self.next:
                        if self.pos >= len(self.photos):
                            return
                        self.pos += 1
                    elif sender == self.prev:
                        if self.pos < 1:
                            return
                        self.pos -= 1
                    photo = self.photos[self.pos]
                    self.fullsize.setHTML('<img src="' + photo["full"] + '"/>')
            elif self.drill == 1:
                self.drill = 0
                self.vp.clear()
                self.vp.add(self.IDPanel)
                self.vp.add(self.disclosure)
                self.vp.add(self.grid)
                self.fillGrid(self.albums, "albums")

    def onTimer(self, timer):
        fd = doc().getElementById("__pygwt_hiddenData")
        receiver = fd.innerHTML

        if receiver == 'wait':
            self.timer.schedule(1000)
            return

        fd.innerHTML = 'wait'

        if self.drill == 0:
            self.parseAlbums(receiver)
            self.fillGrid(self.albums, "albums")
        elif self.drill == 1:
            self.parsePhotos(receiver)
            self.fillGrid(self.photos, "photos")

    def fillGrid(self, items, type):
        self.grid.clear()
        cols = self.grid.getColumnCount()
        self.grid.resizeRows((len(items) / cols) + 1)
        rows = self.grid.getRowCount()
        for i in range(len(items)):
            vp = VerticalPanel()
            if type == 'photos':
                vp.add(items[i]['thumb'])
            else:
                vp.add(items[i]['thumb'])
                vp.add(items[i]['title'])
            self.grid.setWidget(int(i / cols), i % cols, vp)

    def parsePhotos(self, items):
        photo_list = json.loads(items)
        self.photos = []
        for ph in photo_list:
            aphoto = {}
            aphoto['thumb'] = HTML(
                '<img src="' +
                ph[u"media$group"][u"media$thumbnail"][1][u"url"] + '"/>')
            aphoto['full'] = ph[u"media$group"][u"media$content"][0][u"url"]
            self.photos.append(aphoto)

    def parseAlbums(self, items):
        album_list = json.loads(items)
        self.albums = []
        for al in album_list:
            analbum = {}
            analbum['title'] = HTML(al[u"title"][u"$t"])
            analbum['thumb'] = HTML(
                '<img src="' +
                al[u"media$group"][u"media$thumbnail"][0][u"url"] + '"/>')
            url = al[u"id"][u"$t"]
            analbum['id'] = url.split(u'albumid/')[1].split(u'?alt')[0]
            self.albums.append(analbum)
コード例 #37
0
ファイル: home.py プロジェクト: sivapy/MyBlog
    def onModuleLoad(self):

        loggedInUser = getCookie("LoggedInUser")
        self.loggedInUserJsonData = json.loads(loggedInUser)

        self.remote_py = MyBlogService()

        dockPanel = DockPanel(BorderWidth=0,
                              Padding=0,
                              HorizontalAlignment=HasAlignment.ALIGN_LEFT,
                              VerticalAlignment=HasAlignment.ALIGN_TOP)

        dockPanel.setSize('100%', '100%')

        headerDockPanel = DockPanel(
            BorderWidth=0,
            Padding=0,
            HorizontalAlignment=HasAlignment.ALIGN_LEFT,
            VerticalAlignment=HasAlignment.ALIGN_CENTER)
        headerDockPanel.setStyleName('header')
        headerDockPanel.setWidth('100%')

        dockPanel.add(headerDockPanel, DockPanel.NORTH)
        dockPanel.setCellHeight(headerDockPanel, '60px')

        self.siteImage = Image("/images/Testware_logo.png")
        self.siteImage.setStyleName('logo-image')
        headerDockPanel.add(self.siteImage, DockPanel.WEST)
        headerDockPanel.setCellWidth(self.siteImage, '30%')

        self.pageTitle = Label('All Blogs')
        self.pageTitle.setStyleName('center-header')
        headerDockPanel.add(self.pageTitle, DockPanel.CENTER)
        headerDockPanel.setCellWidth(self.pageTitle, '40%')

        rightHeaderPanel = VerticalPanel(StyleName='right-header')
        headerDockPanel.add(rightHeaderPanel, DockPanel.EAST)
        headerDockPanel.setCellWidth(rightHeaderPanel, '30%')

        welcomeNoteLabel = Label('Hi %s %s!' %
                                 (self.loggedInUserJsonData["first_name"],
                                  self.loggedInUserJsonData["last_name"]))
        rightHeaderPanel.add(welcomeNoteLabel)

        logoutAnchor = Anchor(Widget=HTML('Logout'), Href='/', Title='Logout')
        logoutAnchor.setStyleName('logout')
        rightHeaderPanel.add(logoutAnchor)

        newBlogAnchor = Anchor(Widget=HTML('Create New Blog'),
                               Href='/newblog.html',
                               Title='NewBlog')
        newBlogAnchor.setStyleName('logout')
        rightHeaderPanel.add(newBlogAnchor)

        tree = Tree()
        tree.addTreeListener(self)
        tree.setStyleName('side-menu')
        dockPanel.add(tree, DockPanel.WEST)
        dockPanel.setCellWidth(tree, '60px')

        s1 = self.createItem("Blogs")
        allItem = self.createItem("All", value=0)
        self.selectedItem = allItem
        s1.addItem(allItem)
        s1.addItem(self.createItem("Published", value=1))
        s1.addItem(self.createItem("Unpublished", value=2))

        s2 = self.createItem("Other's Blog")

        s1.setState(True, fireEvents=False)

        tree.addItem(s1)
        tree.addItem(s2)

        self.absolultutePanel = AbsolutePanel(StyleName='detail-style')
        dockPanel.add(self.absolultutePanel, DockPanel.CENTER)

        self.blogs = []
        self.g = Grid()

        RootPanel().add(dockPanel)

        self.remote_py.callMethod('getBlogs',
                                  [self.loggedInUserJsonData["username"]],
                                  self)
コード例 #38
0
    def drawFull(self, month, year):
        # should be called only once when we draw the calendar for
        # the first time
        self.vp = VerticalPanel()
        self.vp.setSpacing(2)
        self.vp.addStyleName("calendarbox calendar-module calendar")
        self.setWidget(self.vp)
        self.setVisible(False)
        #
        mth = int(month)
        yr = int(year)

        tp = HorizontalPanel()
        tp.addStyleName("calendar-top-panel")
        tp.setSpacing(5)

        h1 = Hyperlink('<<')
        h1.addClickListener(getattr(self, 'onPreviousYear'))
        h2 = Hyperlink('<')
        h2.addClickListener(getattr(self, 'onPreviousMonth'))
        h4 = Hyperlink('>')
        h4.addClickListener(getattr(self, 'onNextMonth'))
        h5 = Hyperlink('>>')
        h5.addClickListener(getattr(self, 'onNextYear'))

        tp.add(h1)
        tp.add(h2)

        # titlePanel can be changed, whenever we draw, so keep the reference
        txt = "<b>"
        txt += self.getMonthsOfYear()[mth - 1] + " " + str(yr)
        txt += "</b>"
        self.titlePanel = SimplePanel()
        self.titlePanel.setWidget(HTML(txt))
        self.titlePanel.setStyleName("calendar-center")

        tp.add(self.titlePanel)
        tp.add(h4)
        tp.add(h5)
        tvp = VerticalPanel()
        tvp.setSpacing(10)
        tvp.add(tp)

        self.vp.add(tvp)

        # done with top panel

        self.middlePanel = SimplePanel()
        grid = self.drawGrid(mth, yr)
        self.middlePanel.setWidget(grid)
        self.vp.add(self.middlePanel)
        self.defaultGrid = grid
        #
        # some links & handlers
        #
        bh1 = Hyperlink(self.yesterday)
        bh1.addClickListener(getattr(self, 'onYesterday'))
        bh2 = Hyperlink(self.today)
        bh2.addClickListener(getattr(self, 'onToday'))
        bh3 = Hyperlink(self.tomorrow)
        bh3.addClickListener(getattr(self, 'onTomorrow'))
        bh4 = Hyperlink(self.cancel)
        bh4.addClickListener(getattr(self, 'onCancel'))
        #
        # add code to test another way of doing the layout
        #
        b = HorizontalPanel()
        b.add(bh1)
        b.add(bh2)
        b.add(bh3)
        b.addStyleName("calendar-shortcuts")
        self.vp.add(b)
        b2 = SimplePanel()
        b2.add(bh4)
        b2.addStyleName("calendar-cancel")
        self.vp.add(b2)

        self.setVisible(True)
        return
コード例 #39
0
ファイル: WebPageEdit.py プロジェクト: wkornewald/pyjs
    def __init__(self, sink):
        Composite.__init__(self)

        self.remote = sink.remote

        panel = VerticalPanel(Width="100%", Spacing=8)

        self.view = Button("View", self)
        self.newpage = Button("New", self)
        self.todoId = None
        self.todoTextName = TextBox()
        self.todoTextName.addKeyboardListener(self)

        self.todoTextArea = RichTextEditor(basePath="/fckeditor/")
        self.todoTextArea.setWidth("100%")
        self.todoTextArea.addSaveListener(self)

        self.todoList = ListBox()
        self.todoList.setVisibleItemCount(7)
        self.todoList.setWidth("200px")
        self.todoList.addClickListener(self)

        self.fDialogButton = Button("Upload Files", self)

        self.status = HTML()

        panel.add(HTML("Status:"))
        panel.add(self.status)
        panel.add(self.fDialogButton)
        panel.add(Label("Create New Page (doesn't save current one!):"))
        panel.add(self.newpage)
        panel.add(Label("Add/Edit New Page:"))
        panel.add(self.todoTextName)
        panel.add(Label("Click to Load and Edit (doesn't save current one!):"))
        panel.add(self.todoList)
        panel.add(self.view)
        panel.add(
            Label(
                "New Page HTML.  Click 'save' icon to save.  (pagename is editable as well)"
            ))
        panel.add(self.todoTextArea)

        self.setWidget(panel)

        self.remote.getPages(self)
コード例 #40
0
class Calendar(FocusPanel):
    monthsOfYear = [
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
        'Nov', 'Dec'
    ]
    daysOfWeek = ['S', 'M', 'T', 'W', 'T', 'F', 'S']
    today = 'Today'
    tomorrow = 'Tomorrow'
    yesterday = 'Yesterday'
    cancel = 'Cancel'

    def __init__(self, **kwargs):
        FocusPanel.__init__(self, **kwargs)
        yr, mth, day = time.strftime("%Y-%m-%d").split("-")
        self.todayYear = int(yr)
        self.todayMonth = int(mth)  # change to offset 0 as per javascript
        self.todayDay = int(day)

        self.currentMonth = self.todayMonth
        self.currentYear = self.todayYear
        self.currentDay = self.todayDay

        self.selectedDateListeners = []

        self.defaultGrid = None  # used later

        return

    def setDate(self, _date):
        """ _date - object of datetime.date class """
        self.currentMonth = _date.month
        self.currentYear = _date.year
        self.currentDay = _date.day

    def getMonthsOfYear(self):
        return self.monthsOfYear

    def getDaysOfWeek(self):
        return self.daysOfWeek

    def addSelectedDateListener(self, listener):
        self.selectedDateListeners.append(listener)

    def removeSelectedDateListener(self, listener):
        self.selectedDateListeners.remove(listener)

    def isLeapYear(self, year):
        if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
            return True
        else:
            return False

    def getDaysInMonth(self, mth, year):
        days = 0
        if mth in [1, 3, 5, 7, 8, 10, 12]:
            days = 31
        elif mth in [4, 6, 9, 11]:
            days = 30
        elif (mth == 2 and self.isLeapYear(year)):
            days = 29
        else:
            days = 28
        return days

    def setPosition(self, left, top):
        element = self.getElement()
        DOM.setStyleAttribute(element, "left", "%dpx" % left)
        DOM.setStyleAttribute(element, "top", "%dpx" % top)

    def show(self, left, top):
        if left < 0:
            left = 0
        if top < 0:
            top = 0
        self.setPosition(left, top)
        self.drawCurrent()
        self.setVisible(True)

    def drawCurrent(self):
        yr, mth, day = self.currentYear, self.currentMonth, self.currentDay
        self.draw(int(mth), int(yr))

    def draw(self, month, year):
        tod = time.localtime()
        mm = tod.tm_mon
        yy = tod.tm_year
        # has today changed and thus changed month? cater to rare case
        # where widget in created on last day of month and
        # page left till next day
        hasChangeMonth = False
        if yy <> self.todayYear or mm <> self.todayMonth:
            hasChangeMonth = True
            self.todayYear = yy
            self.todayMonth = mm

        # check to see if we have drawn the full widget before
        if self.defaultGrid is None:
            self.drawFull(month, year)
        else:
            # ok means we are re-drawing, but first check if it is the same
            # as the defaultGrid, if yes, just use it
            if not hasChangeMonth and month == self.todayMonth and \
                   year == self.todayYear:
                self.middlePanel.setWidget(self.defaultGrid)
                self.currentMonth = self.todayMonth
                self.currentYear = self.todayYear
            else:
                # we have to redraw the grid -- bah
                g = self.drawGrid(month, year)

                if hasChangeMonth:
                    # reset the default grid as we have changed months
                    self.defaultGrid = grid

            #
            # what about the title panel?
            #
            txt = "<b>"
            txt += self.getMonthsOfYear()[month - 1] + " " + str(year)
            txt += "</b>"
            self.titlePanel.setWidget(HTML(txt))
            self.setVisible(True)

        return

    def drawFull(self, month, year):
        # should be called only once when we draw the calendar for
        # the first time
        self.vp = VerticalPanel()
        self.vp.setSpacing(2)
        self.vp.addStyleName("calendarbox calendar-module calendar")
        self.setWidget(self.vp)
        self.setVisible(False)
        #
        mth = int(month)
        yr = int(year)

        tp = HorizontalPanel()
        tp.addStyleName("calendar-top-panel")
        tp.setSpacing(5)

        h1 = Hyperlink('<<')
        h1.addClickListener(getattr(self, 'onPreviousYear'))
        h2 = Hyperlink('<')
        h2.addClickListener(getattr(self, 'onPreviousMonth'))
        h4 = Hyperlink('>')
        h4.addClickListener(getattr(self, 'onNextMonth'))
        h5 = Hyperlink('>>')
        h5.addClickListener(getattr(self, 'onNextYear'))

        tp.add(h1)
        tp.add(h2)

        # titlePanel can be changed, whenever we draw, so keep the reference
        txt = "<b>"
        txt += self.getMonthsOfYear()[mth - 1] + " " + str(yr)
        txt += "</b>"
        self.titlePanel = SimplePanel()
        self.titlePanel.setWidget(HTML(txt))
        self.titlePanel.setStyleName("calendar-center")

        tp.add(self.titlePanel)
        tp.add(h4)
        tp.add(h5)
        tvp = VerticalPanel()
        tvp.setSpacing(10)
        tvp.add(tp)

        self.vp.add(tvp)

        # done with top panel

        self.middlePanel = SimplePanel()
        grid = self.drawGrid(mth, yr)
        self.middlePanel.setWidget(grid)
        self.vp.add(self.middlePanel)
        self.defaultGrid = grid
        #
        # some links & handlers
        #
        bh1 = Hyperlink(self.yesterday)
        bh1.addClickListener(getattr(self, 'onYesterday'))
        bh2 = Hyperlink(self.today)
        bh2.addClickListener(getattr(self, 'onToday'))
        bh3 = Hyperlink(self.tomorrow)
        bh3.addClickListener(getattr(self, 'onTomorrow'))
        bh4 = Hyperlink(self.cancel)
        bh4.addClickListener(getattr(self, 'onCancel'))
        #
        # add code to test another way of doing the layout
        #
        b = HorizontalPanel()
        b.add(bh1)
        b.add(bh2)
        b.add(bh3)
        b.addStyleName("calendar-shortcuts")
        self.vp.add(b)
        b2 = SimplePanel()
        b2.add(bh4)
        b2.addStyleName("calendar-cancel")
        self.vp.add(b2)

        self.setVisible(True)
        return

    def drawGrid(self, month, year):
        # draw the grid in the middle of the calendar

        daysInMonth = self.getDaysInMonth(month, year)
        # first day of the month & year
        secs = time.mktime((year, month, 1, 0, 0, 0, 0, 0, -1))
        struct = time.localtime(secs)
        # 0 - sunday for our needs instead 0 = monday in tm_wday
        startPos = (struct.tm_wday + 1) % 7
        slots = startPos + daysInMonth - 1
        rows = int(slots / 7) + 1
        grid = Grid(rows + 1, 7)  # extra row for the days in the week
        grid.setWidth("100%")
        grid.addTableListener(self)
        self.middlePanel.setWidget(grid)
        #
        # put some content into the grid cells
        #
        for i in range(7):
            grid.setText(0, i, self.getDaysOfWeek()[i])
            grid.cellFormatter.addStyleName(0, i, "calendar-header")
        #
        # draw cells which are empty first
        #
        day = 0
        pos = 0
        while pos < startPos:
            grid.setText(1, pos, " ")
            grid.cellFormatter.setStyleAttr(1, pos, "background", "#f3f3f3")
            grid.cellFormatter.addStyleName(1, pos, "calendar-blank-cell")
            pos += 1
        # now for days of the month
        row = 1
        day = 1
        col = startPos
        while day <= daysInMonth:
            if pos % 7 == 0 and day <> 1:
                row += 1
            col = pos % 7
            grid.setText(row, col, str(day))
            if self.currentYear == self.todayYear and \
               self.currentMonth == self.todayMonth and day == self.todayDay:
                grid.cellFormatter.addStyleName(row, col,
                                                "calendar-cell-today")
            else:
                grid.cellFormatter.addStyleName(row, col, "calendar-day-cell")
            day += 1
            pos += 1
        #
        # now blank lines on the last row
        #
        col += 1
        while col < 7:
            grid.setText(row, col, " ")
            grid.cellFormatter.setStyleAttr(row, col, "background", "#f3f3f3")
            grid.cellFormatter.addStyleName(row, col, "calendar-blank-cell")
            col += 1

        return grid

    def onCellClicked(self, grid, row, col):
        if row == 0:
            return
        text = grid.getText(row, col).strip()
        if text == "":
            return
        try:
            selectedDay = int(text)
        except ValueError, e:
            return
        # well if anyone is listening to the listener, fire that event
        for listener in self.selectedDateListeners:
            if hasattr(listener, "onDateSelected"):
                listener.onDateSelected(self.currentYear, self.currentMonth,
                                        selectedDay)
            else:
                listener(self.currentYear, self.currentMonth, selectedDay)
        self.setVisible(False)
コード例 #41
0
ファイル: Showcase.py プロジェクト: minghuascode/pyj
class Showcase:
    """ Our main application object.
    """
    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)

    def loadDemos(self):
        """ Load our various demos, in preparation for showing them.

            We insert the demos into self._demos.
        """
        self._demos = demoInfo.getDemos()

    def buildTree(self):
        """ Build the contents of our tree.

            Note that, for now, we highlight the demos which haven't been
            written yet.
        """
        sections = {}  # Maps section name to TreeItem object.

        for demo in self._demos:
            if demo['section'] not in sections:
                section = TreeItem('<b>' + demo['section'] + '</b>')
                DOM.setStyleAttribute(section.getElement(), "cursor",
                                      "pointer")
                DOM.setAttribute(section.itemTable, "cellPadding", "0")
                DOM.setAttribute(section.itemTable, "cellSpacing", "1")
                self._tree.addItem(section)
                sections[demo['section']] = section

            section = sections[demo['section']]

            if demo['doc'][:26] == "Documentation goes here...":
                item = TreeItem('<font style="color:#808080">' +
                                demo['title'] + '</font>')
            else:
                item = TreeItem(demo['title'])
            DOM.setStyleAttribute(item.getElement(), "cursor", "pointer")
            DOM.setAttribute(item.itemTable, "cellPadding", "0")
            DOM.setAttribute(item.itemTable, "cellSpacing", "1")
            item.setUserObject(demo)
            section.addItem(item)

        # Open the branches of the tree.

        for section in sections.keys():
            sections[section].setState(True, fireEvents=False)

    def onTreeItemSelected(self, item):
        """ Respond to the user selecting an item in our tree.
        """
        demo = item.getUserObject()
        if demo is None:
            self.showDemo(None)
        else:
            self.showDemo(demo['name'])

    def onTreeItemStateChanged(self, item):
        """ Respond to the user opening or closing a branch of the tree.
        """
        pass  # Nothing to do.

    def showDemo(self, name):
        """ Show the demonstration with the given name.
        """
        if self._curContents is not None:
            self._rightPanel.remove(self._curContents)
            self._curContents = None

        demo = None
        for d in self._demos:
            if d['name'] == name:
                demo = d
                break

        if demo is not None:
            exampleID = HTMLPanel.createUniqueId()

            html = []
            html.append('<div style="padding:20px">')
            html.append('<b>' + demo['title'] + '</b>')
            html.append('<p/>')
            html.append(self.docToHTML(demo['doc']))
            html.append('<p/>')
            html.append('<hr/>')
            html.append('<b>Working Example</b>')
            html.append('<p/>')
            html.append('<div style="padding-left:20px">')
            html.append('<span id="' + exampleID + '"></span>')
            html.append('</div>')
            html.append('<p/>')
            html.append('<hr/>')
            html.append('<b>Source Code</b>')
            html.append('<p/>')
            html.append(self.srcToHTML(demo['src']))
            html.append('</div>')

            panel = HTMLPanel("\n".join(html))
            panel.add(demo['example'], exampleID)

            self._rightPanel.add(panel)
            self._curContents = panel
        else:
            self._rightPanel.add(self._introPanel)
            self._curContents = self._introPanel

    def docToHTML(self, doc):
        """ Convert the given documentation string to HTML.
        """
        doc = doc.replace('\n\n', '<p/>')

        isBold = False
        while True:
            i = doc.find("``")
            if i == -1: break
            if isBold:
                doc = doc[:i] + '</b></font>' + doc[i + 2:]
            else:
                doc = doc[:i] + '<font face="monospace"><b>' + doc[i + 2:]
            isBold = not isBold

        return doc

    def srcToHTML(self, src):
        """ Convert the given source code to HTML.

            The source code is already in HTML format, but has extra tags to
            make it a complete HTML file.  We extract and return just the text
            between the <body> tags.
        """
        i = src.find('<body')
        i = src.find('>', i)
        j = src.find('</body>')
        return src[i + 1:j]
コード例 #42
0
ファイル: Slide.py プロジェクト: ygyangguang/pyjs
class Slide(Sink):
    def __init__(self):

        Sink.__init__(self)

        text="<div class='infoProse'>This is the Kitchen Sink sample.  "

        self.vp = VerticalPanel()
        self.initWidget(self.vp)
        self.loaded = False

    def onShow(self):

        if self.loaded:
            return

        name = self.name.replace(" ", "_")
        name = name.lower()
        HTTPRequest().asyncGet("%s.txt" % name, SlideLoader(self))

    def setSlide(self, text):
        self.loaded = True
        ul_stack1 = 0
        ul_stack2 = 0
        doing_code = 0
        txt = ''
        text += '\n'
        for line in text.split("\n"):
            if doing_code:
                if line == "}}":
                    doing_code = 0
                    line = "</pre>"
                    txt += line
                    self.vp.add(HTML(txt))
                    txt = ''
                    continue
                if line:
                    txt += line
                txt += "\n"
                continue

            line = line.strip()
            ul_line = False
            ul_line2 = False
            add = False
            if not line:
                line = "&nbsp;"
            elif line[:2] == "{{":
                doing_code = 1
                if len(line) > 2:
                    line = "<pre class='slide_code'>%s" % line[2:]
                else:
                    line = "<pre class='slide_code'>"
            elif line[:2] == '= ' and line[-2:] == ' =':
                line = "<h1 class='slide_heading1'>%s</h1>" % line[2:-2]
            elif line[:3] == '== ' and line[-3:] == ' ==':
                line = "<h2 class='slide_heading2>%s</h2>" % line[3:-3]
            elif line[:2] == '* ':
                if not ul_stack1:
                    txt += "<ul class='slide_list1'>\n"
                line = "<li class='slide_listitem1'/>%s\n" % ts(line[2:])
                ul_stack1 = True
                ul_line = True
            elif line[:3] == '** ':
                if not ul_stack2:
                    txt += "<ul class='slide_list2'>\n"
                line = "<li class='slide_listitem2'/>%s\n" % ts(line[2:])
                ul_stack2 = True
                ul_line2 = True
                ul_line = True
            else:
                if not doing_code:
                    line = "<p class='slide_para'>%s</p>" % line
            if ul_stack2 and not ul_line2:
                ul_stack2 = False
                txt += "</ul>\n"
            if ul_stack1 and not ul_line:
                ul_stack1 = False
                txt += "</ul>\n"
            if not ul_stack2 and not ul_stack1 and not doing_code:
                add = True
            txt += line
            if add:
                self.vp.add(HTML(txt))
                txt = ''

    def onError(self, text, code):
        self.vp.clear()
        self.vp.add(HTML("TODO: Slide '%s' not loaded" % self.name))
        self.vp.add(HTML(text))
        self.vp.add(HTML(code))

    def onProgress(self, event):
        self.vp.clear()
        self.vp.add(HTML("Progress: %s" % self.name))
        self.vp.add(HTML("%s" % str(event.loaded)))
        self.vp.add(HTML("%s" % str(event.total)))
コード例 #43
0
class DisclosurePanel(Composite):
    def __init__(self, *args, **kwargs):

        self.handlers = []
        self.content = None
        self.images = False

        # this is awkward: VerticalPanel is the composite,
        # so we get the element here, and pass it in to VerticalPanel.
        element = kwargs.pop('Element', None)

        # process the passed arguments
        headerText = headerWidget = None
        isOpen = False
        if len(args) == 1:
            header = args[0]
        if len(args) == 2:
            header, isOpen = args[:2]
        # apparently "basestring" is not understood
        if isinstance(header, basestring):
            headerText = header
        else:
            headerWidget = header
        isOpen = kwargs.pop('isOpen', isOpen)
        headerText = kwargs.pop('header', headerText)
        headerWidget = kwargs.pop('header', headerWidget)
        # TODO: add ImageBundle
        # images = kwargs.pop('images', None)

        # If both headerText and headerWidget are arguments, headerText will
        # be used to preserve API compatibility.
        headerContent = headerWidget
        if headerText is not None or headerContent is None:
            if headerText is None:
                headerText = ""
            headerContent = DefaultHeader(headerText)

        self.mainPanel = VerticalPanel(Element=element)

        self._init_header(headerContent)

        self.contentWrapper = SimplePanel()
        self.mainPanel.add(self.header)
        self.mainPanel.add(self.contentWrapper)
        DOM.setStyleAttribute(self.contentWrapper.getElement(), "padding",
                              "0px")
        DOM.setStyleAttribute(self.contentWrapper.getElement(), "overflow",
                              "hidden")

        kwargs['StyleName'] = kwargs.get('StyleName', "gwt-DisclosurePanel")
        Composite.__init__(self, self.mainPanel, **kwargs)

        # Must call setOpen after creating the initializing the object
        self.isOpen = None
        self.setOpen(isOpen)

        self.setContentDisplay()

    def _init_header(self, headerContent):
        self.header = ClickableHeader(self)
        self.headerObj = headerContent
        self.addEventHandler(self.headerObj)
        self.setHeader(self.headerObj)

    def add(self, widget):
        if self.getContent() is None:
            self.setContent(widget)

    def addEventHandler(self, handler):
        self.handlers.append(handler)

    def removeEventHandler(self, handler):
        self.handlers.remove(handler)

    def clear(self):
        self.setContent(None)

    def getContent(self):
        return self.content

    def getHeader(self):
        return self.header.getWidget()

    def getOpen(self):
        return self.isOpen

    def getImages(self):
        return self.images

    def remove(self, widget):
        if widget == self.getContent():
            self.setContent(None)
            return True
        return False

    def setContent(self, widget):
        if self.content is not None:
            self.contentWrapper.setWidget(None)
            self.content.removeStyleName("content")

        self.content = widget
        if self.content is not None:
            self.contentWrapper.setWidget(self.content)
            self.content.addStyleName("content")
            self.setContentDisplay()

    def setHeader(self, widget):
        self.header.setWidget(widget)

    def setOpen(self, isOpen):
        if self.isOpen == isOpen:
            return
        self.isOpen = isOpen
        self.setContentDisplay()
        self.fireEvent()

    def setImages(self, images):
        if self.images == images:
            return
        self.images = images
        header = self.getHeader()
        if header is not None and isinstance(header, DefaultHeader):
            header.setImageBase(images)
            header.updateState(self.getOpen())

    def fireEvent(self):
        for handler in self.handlers:
            if self.isOpen:
                handler.onOpen(self)
            else:
                handler.onClose(self)

    def setContentDisplay(self):
        if self.isOpen:
            self.addStyleName("open")
            self.removeStyleName("closed")
        else:
            self.addStyleName("closed")
            self.removeStyleName("open")
        self.contentWrapper.setVisible(self.isOpen)
コード例 #44
0
ファイル: AMSSnoopObjects.py プロジェクト: Tech-XCorp/petsc
class AMSSnoopObjects:
    def onModuleLoad(self):
        global statusbar
        statusbar = Label()
        self.button = Button(
            "Display list of all published memories and fields", self)
        self.buttonupdate = Button("Update data from AMS publisher", self)

        buttons = HorizontalPanel()
        buttons.add(self.button)
        buttons.add(self.buttonupdate)
        buttons.setSpacing(8)

        info = """<p>This example demonstrates the calling of the Memory Snooper in PETSc with Pyjamas and <a href="http://json-rpc.org/">JSON-RPC</a>.</p>"""

        self.panel = VerticalPanel()
        self.panel.add(HTML(info))
        self.panel.add(buttons)
        self.panel.add(statusbar)
        RootPanel().add(self.panel)
        self.commobj = AMS.AMS_Comm()
        self.tree = None

    def textboxlistener(self, arg):
        global boxes, statusbar
        statusbar.setText('User changed value in text box to ' +
                          str(arg.getText()) + " " + str(boxes[arg]))
        # the user has changed this value we should send it back to the AMS program
        boxes[arg][2].set_field_info(boxes[arg][1], arg.getText())

    def onClick(self, sender):
        global statusbar, boxes
        statusbar.setText('Button pressed')
        pass
        if sender == self.buttonupdate:
            self.commobj = AMS.AMS_Comm()
            statusbar.setText(
                'Updating data: Press Display list button to refesh')
        if sender == self.button:
            if AMS.sent > AMS.recv:
                statusbar.setText('Press button again: sent ' + str(AMS.sent) +
                                  ' recv ' + str(AMS.recv))
            if self.commobj.commname == 'No AMS publisher running' or not self.commobj.commname or self.commobj.comm == -1:
                if self.tree: self.panel.remove(self.tree)
            else:
                statusbar.setText('Memories for AMS Comm: ' +
                                  self.commobj.commname)
                result = self.commobj.get_memory_list()
                if self.tree: self.panel.remove(self.tree)
                self.tree = Tree()
                for i in result:
                    if i == "Stack": continue
                    subtree = TreeItem(i)
                    memory = self.commobj.memory_attach(i)
                    fields = memory.get_field_list()
                    if not isinstance(fields, list): fields = [fields]
                    block = false
                    for j in fields:
                        field = memory.get_field_info(j)
                        if str(field[1]) == 'AMS_READ':
                            if j == "Publish Block":
                                if field[4] == "true": block = true
                            else:
                                subtree.addItem(j + ' = ' + str(field[4]))
                        else:
                            if j == "Block" and not block: continue
                            PN = HorizontalPanel()
                            PN.add(Label(Text=j + ' ='))
                            tb = TextBox(Text=str(field[4]))
                            boxes[tb] = [i, j, memory]
                            tb.addChangeListener(self.textboxlistener)
                            PN.add(tb)
                            subtree.addItem(PN)
                    self.tree.addItem(subtree)
                    self.panel.add(self.tree)