Пример #1
0
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)
 def newPositioner(self, context):
     
     # Use two widgets so that setPixelSize() consistently affects dimensions
     outer = SimplePanel() 
     outer.addStyleName(CSS_DRAGDROP_POSITIONER)
     
     # place off screen for border calculation
     RootPanel.get().add(outer, -500, -500) 
     
     # Ensure IE quirks mode returns valid outer.offsetHeight, and thus valid
     outer.setWidget(self.DUMMY_LABEL_IE_QUIRKS_MODE_OFFSET_HEIGHT)
     width = 0
     height = 0
     if isinstance(self.dropTarget,HorizontalPanel):
         for widget in context.selectedWidgets:
             width += widget.getOffsetWidth()
             height = Math.max(height, widget.getOffsetHeight())
     else:
         for widget in context.selectedWidgets:
             width = Math.max(width, widget.getOffsetWidth())
             height += widget.getOffsetHeight()
     inner = SimplePanel()
     inner.setPixelSize(
         width - DOMUtil.getHorizontalBorders(outer), height - DOMUtil.getVerticalBorders(outer))
     outer.setWidget(inner)
     return outer
Пример #3
0
def main(init):
    root = RootPanel()
    container = FocusPanel()
    DeferredCommand.add(Focus(container))
    root.add(container)
    container.setSize(21*15,21*15)
    init(container)
Пример #4
0
def main():
    root = RootPanel()
    tree = Tree()
    cb1 = CheckBox('test 1')
    cb1.addClickListener(onCb1)
    root.add(cb1)
    cb2 = CheckBox('test 2')
    cb2.addClickListener(onCb2)
    item = TreeItem(cb2)
    tree.addItem(item)
    root.add(tree)
 def makePositioner(self, reference):
     outer = SimplePanel() # Use two widgets so that setPixelSize() consistently affects dimensions
     outer.addStyleName(CSS_DRAGDROP_POSITIONER)
     outer.getElement().getStyle().setProperty("margin", "0px")
     RootPanel.get().add(outer, -500, -500) # place off screen for border calculation
     outer.setWidget(DUMMY_LABEL_IE_QUIRKS_MODE_OFFSET_HEIGHT) # Ensure IE quirks mode returns valid outer.offsetHeight, and thus valid
     inner = SimplePanel()
     inner.getElement().getStyle().setProperty("margin", "0px")
     inner.getElement().getStyle().setProperty("border", "none")
     offsetWidth = reference.getOffsetWidth() - DOMUtil.getHorizontalBorders(outer)
     offsetHeight = reference.getOffsetHeight() - DOMUtil.getVerticalBorders(outer)
     inner.setPixelSize(offsetWidth, offsetHeight)
     outer.setWidget(inner)
     return outer
Пример #6
0
class MapProgram:
    def onModuleLoad( self ):
        self.setUpInstanceVariables()
        self.assemblePanels()
        self.setUpListeners()
        self.service.usernames( self.userNameReceiver )
        self.controlPanel.numPointsListBox.setSelectedIndex( 1 )
        self.service.shakeevents( 'Last Week', self.controlPanel.nameListBox.getValue( self.controlPanel.nameListBox.getSelectedIndex() ), self.shakeEventPointReceiver )


    def setUpInstanceVariables( self ):
        self.service = MapService()
        self.root = RootPanel()
        self.controlPanel = TopPanel()
        self.mapPanel = MapPanel()
        self.userNameReceiver = UserNameReceiver( self )
        #self.usgsPointReceiver = USGSPointReceiver(self)
        self.shakeEventPointReceiver = ShakeEventPointReceiver( self )
        self.markers = []

    def assemblePanels( self ):
        vp = VerticalPanel()
        vp.add( self.controlPanel )
        vp.add( self.mapPanel )
        self.root.add( vp )

    def setUpListeners( self ):
        npBox = self.controlPanel.numPointsListBox
        unBox = self.controlPanel.nameListBox
        def npFn():
            #self.service.points(npBox.getValue(npBox.getSelectedIndex()),self.usgsPointReceiver)
            self.controlPanel.statusHTML.setHTML( 'Fetching Points...' )
            self.service.shakeevents( npBox.getValue( npBox.getSelectedIndex() ), unBox.getValue( unBox.getSelectedIndex() ), self.shakeEventPointReceiver )
        npBox.addChangeListener( npFn )
        unBox.addChangeListener( npFn )

    def mouseOverMarker( self,ind ):
        Window.alert('test1')
        marker = self.markers[ind]
        iwo = InfoWindowOptions()
        iwo.position = marker['latlng']
        iwo.content = marker['title']
        Window.alert('test2')
        self.iw = InfoWindow( iwo )
        self.iw.open( self.mapPanel.map )

    def mouseOutMarker( self ):
        self.iw.close()
Пример #7
0
 def newPositioner(self, context):
     # Use two widgets so that setPixelSize() consistently affects dimensions
     # excluding positioner border in quirks and strict modes
     SimplePanel outer = SimplePanel()
     outer.addStyleName(CSS_DRAGDROP_POSITIONER)
     
     # place off screen for border calculation
     RootPanel.get().add(outer, -500, -500)
     
     # Ensure IE quirks mode returns valid outer.offsetHeight, and thus valid
     # DOMUtil.getVerticalBorders(outer)
     outer.setWidget(DUMMY_LABEL_IE_QUIRKS_MODE_OFFSET_HEIGHT)
     
     int width = 0
     int height = 0
     if dropTarget instanceof HorizontalPanel:
         for Iterator iterator = context.selectedWidgets.iterator(); iterator.hasNext();:
Пример #8
0
 def internalSetWidget(self, widget):
     # this.widget = widget;
     if widget == None or widget == RootPanel.get():
         self.widgetLeft = 0
         self.widgetTop = 0
     else:
         self.widgetLeft = widget.getAbsoluteLeft() - widget.getElement().getScrollLeft()
         self.widgetTop = widget.getAbsoluteTop() - widget.getElement().getScrollTop()
Пример #9
0
    def onModuleLoad(self):
        """ Dynamically build our user interface when the web page is loaded.
        """
        self._curPanelID = None # ID of currently-shown panel.
        self._root       = RootPanel()

        self._panels = self.createPanels()
        self.showPanel(self.getDefaultPanel())
Пример #10
0
class PanelApp:
    """ A generic multiple-panel web application.

        This class makes it easy to handle multiple panels within a web
        application.  Panels are shown as they are required.
    """
    def onModuleLoad(self):
        """ Dynamically build our user interface when the web page is loaded.
        """
        self._curPanelID = None # ID of currently-shown panel.
        self._root       = RootPanel()

        self._panels = self.createPanels()
        self.showPanel(self.getDefaultPanel())


    def showPanel(self, panelID):
        """ Show the panel with the given ID.
        """
        if panelID == self._curPanelID: return

        if self._curPanelID is not None:
            self._root.remove(self._panels[self._curPanelID])

        self._root.add(self._panels[panelID])
        self._curPanelID = panelID

    # ==============================
    # == METHODS TO BE OVERRIDDEN ==
    # ==============================

    def createPanels(self):
        """ Create the various panels to be used by this application.

            This should be overridden by the subclass to create the various
            panels the application will use.  Upon completion, the subclass
            should return a dictionary mapping the ID to use for each panel to
            the panel to be displayed.
        """
        Window.alert("Must be overridden.")


    def getDefaultPanel(self):
        """ Return the ID of the panel to show on system startup.
        """
        Window.alert("Must be overridden.")
Пример #11
0
 def setUpInstanceVariables( self ):
     self.service = MapService()
     self.root = RootPanel()
     self.controlPanel = TopPanel()
     self.mapPanel = MapPanel()
     self.userNameReceiver = UserNameReceiver( self )
     #self.usgsPointReceiver = USGSPointReceiver(self)
     self.shakeEventPointReceiver = ShakeEventPointReceiver( self )
     self.markers = []
Пример #12
0
 def internalSetReference(self, reference):
     # this.reference = reference;
     if reference == None or reference == RootPanel.get():
         self.referenceAdjustLeft = 0
         self.referenceAdjustTop = 0
     else:
         self.referenceAdjustLeft = \
             reference.getAbsoluteLeft() + DOMUtil.getBorderLeft(reference.getElement())
         self.referenceAdjustTop = \
             reference.getAbsoluteTop() + DOMUtil.getBorderTop(reference.getElement())
Пример #13
0
 def onModuleLoad(self):
     slot = RootPanel("calendar")
     if slot is not None:
         calendar = SchoolCalendarWidget(15)
         slot.add(calendar)
         
         slot = RootPanel("days")
         if slot is not None:
             filterWidget = DayFilterWidget(calendar)
             slot.add(filterWidget)
Пример #14
0
    def onModuleLoad(self):
        '''Create initial view of the panel.
        '''
        # Container that keeps everything
        self.panel = VerticalPanel()
        self.panel.setSpacing(10)

        # Create list of projects 
        proj_list = ListBox(Height='34px')
       
        proj_list.addItem('')
       
        proj_list.setVisibleItemCount(0)
        proj_list.addChangeListener(getattr(self, 'on_project_changed'))
        proj_list.setStyleName('form-control input-lg')
        
        self.proj_row = Form_Row('Select project',
                            proj_list,
                            help='project, status of which you want to report')
        
        # Project-specific container
        self.project_panel = VerticalPanel()

        # Submit report button
        self.submit_btn = Button('Submit report', getattr(self, 'send_data'))
        self.submit_btn.setStyleName('btn btn-primary btn-lg')
        self.submit_btn.setEnabled(False)

        self.msg_lbl = HTMLPanel('', Width='475px')

        # Add controls here
        self.panel.add(self.proj_row.panel())
        self.panel.add(self.project_panel)
        self.panel.add(Label(Height='20px'))
        self.panel.add(self.msg_lbl)
        btn_holder = HorizontalPanel()
        btn_holder.add(self.submit_btn)
        help_btn = HTMLPanel('')

        help_btn.setHTML(MODAL_PNL)
        btn_holder.add(Label(Width='10px'))
        btn_holder.add(help_btn)
        self.panel.add(btn_holder)
        
        self.root = RootPanel('report')
        self.root.add(self.panel)
Пример #15
0
    def onModuleLoad(self):
        '''Create initial view of the panel.
        '''
        # Container that keeps everything
        self.panel = VerticalPanel()
        self.panel.setSpacing(10)

        spacer1 = Label()
        spacer1.setHeight('10px')
        spacer2 = Label()
        spacer2.setHeight('10px')
        
        self.tbl_panel = VerticalPanel(Width='755px')
        # First is a row count
        self.grid = Reports_Grid()
        self.grid.create_grid(1, 4, ['Milestone Name', 'Milestone State', 'Start Date', 'End Date'])
        self.tbl_panel.add(self.grid)

        self.editor = Milestones_Editor()
        self.submit_btn = Button('Submit', getattr(self, 'send_data'))
        self.submit_btn.setStyleName('btn btn-primary btn-lg')

        hpanel = HorizontalPanel()
        hpanel.setHorizontalAlignment(HasAlignment.ALIGN_RIGHT)
        hpanel.add(self.submit_btn)

        self.msg_lbl = HTMLPanel('', Width='755px')

        self.root = RootPanel('projects_')
        self.root.add(spacer1)
        self.root.add(self.editor.hpanel)
        self.root.add(spacer2)
        self.root.add(self.tbl_panel)

        spacer3 = Label()
        spacer3.setHeight('20px')

        self.root.add(self.msg_lbl)
        self.root.add(spacer3)
        self.root.add(hpanel)
        self.root.add(Label(Height='20px'))
        

        # Add listeners and initialize components
        self._add_listeners()
        self._iniate_states()
Пример #16
0
    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)
Пример #17
0
        HorizontalPanel.__init__(self)
        #self.setSpacing('10px')

        pool = StudentContainer(1, 20, 'pool_1')
        for item in [['Fred', 12], ['Jane', 10], ['Sam', 18],
                     ['Ginger', 8], ['Mary', 4]]:
            pool.addStudent(name=item[0], age=item[1])
        self.append(pool)
        self.append(StudentContainer(6, 13, 'pool_2'))
        self.append(StudentContainer(11, 20, 'pool_3'))
        self.setSpacing('10px')

    def containerFromId(self, id):
        for item in self.children:
            if item.getID() == id:
                return item


class MultiTargetDemo(DNDDemo):
    def __init__(self):
        self.drop_widget = ClassContainer()
        self.title = 'Drop with Validation'
        self.id = 'multi'
        DNDDemo.__init__(self)

if __name__ == '__main__':
    pyjd.setup("./public/DNDTest.html")
    j = RootPanel()
    j.add(DNDDemos())
    pyjd.run()
Пример #18
0
def greet(fred):
    global sc
    txt = fred.getText()
    if txt == "Click me lots":
        sc = StyleSheetCssChanger(newcolours)
        fred.setText("Did it work?")
    elif txt == "Did it work?":
        sc.remove()
        fred.setText("It did!")
    elif txt == "It did!":
        sc = StyleSheetCssChanger(morenewcolours)
        fred.setText("Play again!")
    elif txt != "Ok enough now":
        fred.setText("Ok enough now")
        sc.remove()


if __name__ == '__main__':
    pyjd.setup("public/CSSMess.html?fred=foo#me")
    b = Button("Click me lots", greet, StyleName='teststyle')
    h = HTML("<b>CSSMess World</b> (html)", StyleName='teststyle')
    l = Label("CSSMess World (label)", StyleName='teststyle')
    base = HTML("CSSMess from %s" % pygwt.getModuleBaseURL(),
                StyleName='teststyle')
    RootPanel().add(b)
    RootPanel().add(h)
    RootPanel().add(l)
    RootPanel().add(base)
    StyleSheetCssFileChanger("./CSSMess.css")
    pyjd.run()
Пример #19
0
class Input_Form(Abstract_View):
    '''Input form that modifies itself depending on the proejct.
    '''
    def __init__(self):
        Abstract_View.__init__(self)
        self.dev_fields = Dev_Fields()
        

    def register(self, controller):
        '''Register controller for view and its subviews'''
        self.controller = controller
        self.dev_fields.register(controller)
        
    def onModuleLoad(self):
        '''Create initial view of the panel.
        '''
        # Container that keeps everything
        self.panel = VerticalPanel()
        self.panel.setSpacing(10)

        # Create list of projects 
        proj_list = ListBox(Height='34px')
       
        proj_list.addItem('')
       
        proj_list.setVisibleItemCount(0)
        proj_list.addChangeListener(getattr(self, 'on_project_changed'))
        proj_list.setStyleName('form-control input-lg')
        
        self.proj_row = Form_Row('Select project',
                            proj_list,
                            help='project, status of which you want to report')
        
        # Project-specific container
        self.project_panel = VerticalPanel()

        # Submit report button
        self.submit_btn = Button('Submit report', getattr(self, 'send_data'))
        self.submit_btn.setStyleName('btn btn-primary btn-lg')
        self.submit_btn.setEnabled(False)

        self.msg_lbl = HTMLPanel('', Width='475px')

        # Add controls here
        self.panel.add(self.proj_row.panel())
        self.panel.add(self.project_panel)
        self.panel.add(Label(Height='20px'))
        self.panel.add(self.msg_lbl)
        btn_holder = HorizontalPanel()
        btn_holder.add(self.submit_btn)
        help_btn = HTMLPanel('')

        help_btn.setHTML(MODAL_PNL)
        btn_holder.add(Label(Width='10px'))
        btn_holder.add(help_btn)
        self.panel.add(btn_holder)
        
        self.root = RootPanel('report')
        self.root.add(self.panel)

    def _load_project(self, project):
        '''Load project specific fields in the panel
        '''
        if self.dev_fields is not None:
            self.project_panel.remove(self.dev_fields)
        # Remove the old one and add brand new
        self.dev_fields = Dev_Fields()
        self.project_panel.add(self.dev_fields)

    def send_data(self):
        '''Retrieve data for the active project fields and send to flask.
        '''
        #data = self.dev_fields.prep_data()
        self.controller.process_msg(SEND_DATA_MSG)
        
    def on_project_changed(self, event):
        '''Change form fields depending on the proejct.
        '''
        proj_list = self.proj_row.widget()
        project = proj_list.getItemText(proj_list.getSelectedIndex())
        if project != '':
            self.controller.process_msg(PROJ_CHANGED_MSG, project)
Пример #20
0
class Milestones_View(Abstract_View):
    def __init__(self):
        '''Project editor view.
        '''
        Abstract_View.__init__(self)
    
    def onModuleLoad(self):
        '''Create initial view of the panel.
        '''
        # Container that keeps everything
        self.panel = VerticalPanel()
        self.panel.setSpacing(10)

        spacer1 = Label()
        spacer1.setHeight('10px')
        spacer2 = Label()
        spacer2.setHeight('10px')
        
        self.tbl_panel = VerticalPanel(Width='755px')
        # First is a row count
        self.grid = Reports_Grid()
        self.grid.create_grid(1, 4, ['Milestone Name', 'Milestone State', 'Start Date', 'End Date'])
        self.tbl_panel.add(self.grid)

        self.editor = Milestones_Editor()
        self.submit_btn = Button('Submit', getattr(self, 'send_data'))
        self.submit_btn.setStyleName('btn btn-primary btn-lg')

        hpanel = HorizontalPanel()
        hpanel.setHorizontalAlignment(HasAlignment.ALIGN_RIGHT)
        hpanel.add(self.submit_btn)

        self.msg_lbl = HTMLPanel('', Width='755px')

        self.root = RootPanel('projects_')
        self.root.add(spacer1)
        self.root.add(self.editor.hpanel)
        self.root.add(spacer2)
        self.root.add(self.tbl_panel)

        spacer3 = Label()
        spacer3.setHeight('20px')

        self.root.add(self.msg_lbl)
        self.root.add(spacer3)
        self.root.add(hpanel)
        self.root.add(Label(Height='20px'))
        

        # Add listeners and initialize components
        self._add_listeners()
        self._iniate_states()
        
    def _add_listeners(self):
        '''Register listeners here.
        '''
        self.editor.add_btn.addClickListener(getattr(self, 'on_add_btn_click'))
        self.editor.del_btn.addClickListener(getattr(self, 'on_del_btn_click'))
        self.editor.name.addKeyboardListener(self)
        

    def _iniate_states(self):
         self.editor.add_btn.setEnabled(False)
         self.editor.del_btn.setEnabled(False)
         self.editor.name.setFocus(True)   
        

    def register(self, controller):
        '''Register controller for a view and related controls.
        '''
        self.controller = controller
        self.grid.register(controller)
        self.editor.start.register(controller)
        self.editor.end.register(controller)
        

    def on_add_btn_click(self, event):
        '''Process click on Add button.
        '''
        (valid, data) = self.editor.get_milestone_data()
        if self.editor.add_btn.getText() == 'Add':
            self.controller.process_msg(ADD_ROW_MSG, data)
        else:
            self.controller.process_msg(EDT_ROW_MSG, self.grid.selected_row, data)


    def on_del_btn_click(self, event):
        '''Process click on Add button.
        '''
        if self.grid.selected_row > 0:
            self.controller.process_msg(DEL_ROW_MSG, self.grid.selected_row)

    def send_data(self):
        '''Notify controller that we need to send data to db and let it
        do the work'''
        self.controller.process_msg(COMMIT_MLS_MSG)

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


    def onKeyUp(self, sender, keycode, modifiers):
        # We are managing view control states here, though might send
        # a message to controller as well, but since we are not passing any data,
        # we do not bother about controller
        (valid, data) = self.editor.get_milestone_data()
        #Window.alert('Valid is {0}, data is {1}'.format(valid, data))
        if valid:
            self.editor.add_btn.setEnabled(True)
        else:
            self.editor.add_btn.setEnabled(False)
        

    def onKeyPress(self, sender, keycode, modifiers):
        '''Let users input using keyboard.
        '''
        (valid, data) = self.editor.get_milestone_data()
       
        if keycode == KeyboardListener.KEY_ESCAPE:
            pass   # TODO: should we do something useful here?
        elif keycode == KeyboardListener.KEY_ENTER:
            if self.editor.add_btn.getText() == 'Add' and self.editor.add_btn.isEnabled():
                self.controller.process_msg(ADD_ROW_MSG, data)
            elif self.editor.add_btn.getText() == 'Change' and self.editor.add_btn.isEnabled():
                self.controller.process_msg(EDT_ROW_MSG, self.grid.selected_row, data)
Пример #21
0
        options = MapOptions()
        options.zoom = 4
        options.center = self.myLatLng
        options.mapTypeId = MapTypeId.ROADMAP

        self.map = Map(self.getElement(), options)
        self.map.addListener("zoom_changed", self.zoomChanged)

        options = InfoWindowOptions()
        options.content = "Zoom Level Test"
        options.position = self.myLatLng

        self.infoWindow = InfoWindow(options)
        self.infoWindow.open(self.map)

        self.map.addListener("zoom_changed", self.zoomChanged)

    def zoomChanged(self):
        zoomLevel = self.map.get_zoom()
        self.map.setCenter(self.myLatLng)
        self.infoWindow.setContent("Zoom: " + str(zoomLevel))

        if zoomLevel == 0:
            self.map.setZoom(10)


if __name__ == '__main__':

    root = RootPanel()
    root.add(EventProperties())
Пример #22
0
        for obj in self.objects:
            obj.update(2)
        ctx = self.context
        ctx.clearRect(0, 0, self.width, self.height)
        for obj in self.objects:
            obj.draw(ctx)

    def add(self, obj):
        self.objects.append(obj)

    def onLoad(self, img=None):
        if self.img == img:
            self.onTimer()

    def onError(self, img=None):
        #console.log('load img error')
        pass


if __name__ == '__main__':
    canvas = LlkCanvas(int(Window.getClientWidth()),
                       int(Window.getClientHeight()))
    RootPanel().add(canvas)
    img = canvas.img
    for i in range(100):
        canvas.add(
            BasicBox(img, (randint(0, 20), randint(0, 20)),
                     (randint(0, 10), randint(0, 10)), canvas))
    Timer(object=canvas).scheduleRepeating(100)
    #load_image('output.png', Listener( (lambda img:canvas.draw(img)) ))
Пример #23
0
 def onKeyPress(self, sender, keyCode, modifiers):
     RootPanel().add(HTML("keypressed: %s" % keyCode))
Пример #24
0
 def onClick(self, sender):
     RootPanel().add(HTML("click"))
Пример #25
0
 def onKeyDown(self, sender, keyCode, modifiers):
     RootPanel().add(HTML("keydown: %s" % keyCode))
Пример #26
0
 def onKeyUp(self, sender, keyCode, modifiers):
     RootPanel().add(HTML("keyup: %s" % keyCode))
Пример #27
0
            self.restart(no_of_bomb)
        else:
            self.row, self.column = level
            if level[0] <= current_level[0] and level[1] <= current_level[1]:
                self.grid.resize(*level)
                self.restart(no_of_bomb)
            else:
                self.grid_panel.remove(self.grid)
                self.create_grid()
                self.start(no_of_bomb)
    
    def restart(self, no_of_bomb=0):
        for one in self.get_all_cells():
            one.count = 0
            one.state = 0
            one.setStyleName('blank')
            DOM.setInnerHTML(one.getElement(), '')
        self.start(no_of_bomb)

if __name__ == '__main__':
    pyjd.setup("./public/minesweeper.html")
    LOG = HTMLPanel('', StyleName='log')
    SCORES = HTMLPanel('', StyleName='scores')
    game = Game(8, 8)
    
    RootPanel('content').add(game)
    RootPanel('content').add(SCORES)
    RootPanel('content').add(LOG)

    pyjd.run()
Пример #28
0
    This function is used to make buttons for allowing more computation time,
    step by step, in reduceterm().    
    """

    orders = 0
    while prevmaxlines >= 10:
        orders += 1
        prevmaxlines /= 10
    if prevmaxlines >= 3:
        maxlines = 10
    else:
        maxlines = 3
    for _ in range(orders):
        maxlines *= 10
    return maxlines


if __name__ == '__main__':
    b = Button("Reduce", queuereduce)
    RootPanel("buttons").add(b)
    fileChooser = makeFileChooser()
    RootPanel("file-chooser").add(fileChooser)
    RootPanel("loading-notify").setVisible(False)
    inputArea = TextArea(VisibleLines=5, CharacterWidth=80)
    RootPanel("input").add(inputArea)
    outputPanel = RootPanel("output")
    loadFile('called from main')
    showOutputMeta(BEGINMESSAGES, iswidgetlist=True)
    b.setFocus(True)
Пример #29
0
    p.ellipse(X, Y, radius, radius )

def mouseMoved():
    global p,nX,nY
    nX = p.mouseX
    nY = p.mouseY

class ProcessingCanvas(GWTCanvas):
    def __init__(self):
        GWTCanvas.__init__(self, 150, 150, 150, 150)
        self.c = self.getCanvasElement()
        self.p = Processing (self.c)
        global p
        p = self.p

if __name__ == '__main__':
    note = HTML("""
Note that this is an example of using processing.js.<br>
See <a href=http://ejohn.org/blog/processingjs/>http://ejohn.org/blog/processingjs/</a> for more info.<br>
Since processing.js is built for state-of-the-art browser<br>
that properly implement canvas, IE is not supported.<br>
<br>
""")
    RootPanel().add(note)
    PC = ProcessingCanvas()
    PC.p.setup = setup
    PC.p.draw = draw
    PC.p.mouseMoved = mouseMoved
    PC.p.init()
    RootPanel().add(PC)
Пример #30
0
    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)
Пример #31
0
# Crossword Puzzle Loader Demo
# Copyright (C) 2011 Camille Dalmeras
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU Affero General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU Affero General Public License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.

import pyjd

from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.InputBox import InputBox

if __name__ == '__main__':
    pyjd.setup("./public/inputbox.html")
    app = InputBox(MatchPattern="^[0-9,A-Z,:]*$")
    app.setMaxLength(20)
    app.setText("hello")
    RootPanel("keypad").add(app)

    pyjd.run()
Пример #32
0
 def onMouseEnter(self, sender):
     RootPanel().add(
         HTML("mouseenter: setting focus (keyboard input accepted)"))
     self.setFocus(True)
Пример #33
0
        SimplePanel.__init__(self)
        self.setSize("100%", "100%")

        options = MapOptions()
        options.zoom = 4
        options.center = LatLng(-25.363882, 131.044922)
        options.mapTypeId = MapTypeId.ROADMAP

        self.map = Map(self.getElement(), options)

        self.map.addListener("zoom_changed", self.zoomChanged)

        self.map.addListener("click", self.clicked)

    def zoomChanged(self):
        print "zoom to " + str(self.map.getZoom())
        Timer(1500, self.moveToDarwin)

    def moveToDarwin(self, timer):
        darwin = LatLng(-12.461334, 130.841904)
        self.map.setCenter(darwin)

    def clicked(self):
        self.map.setZoom(8)


if __name__ == "__main__":

    root = RootPanel()
    root.add(EventSimple())
Пример #34
0
                style=MapTypeControlStyle.DROPDOWN_MENU),

            navigationControl=True,
            navigationControlOptions=NavigationControlOptions(
                style=NavigationControlStyle.SMALL))
        # the same, in a extensive way:

        #options = MapOptions()

        #options.zoom = 4
        #options.center = LatLng(-25.363882, 131.044922)
        #options.mapTypeId = MapTypeId.ROADMAP

        #options.mapTypeControl = True
        #options.mapTypeControlOptions = MapTypeControlOptions()
        #options.mapTypeControlOptions.style =
        #   MapTypeControlStyle.DROPDOWN_MENU

        #options.navigationControl = True
        #options.navigationControlOptions = NavigationControlOptions()
        #options.navigationControlOptions.style = \
        #    NavigationControlStyle.SMALL

        self.map = Map(self.getElement(), options)


if __name__ == '__main__':

    root = RootPanel()
    root.add(ControlOptions())
Пример #35
0
 def onRemoteError(self, code, message, request_info):
     RootPanel().add(HTML("Server Error or Invalid Response: ERROR " + code))
     RootPanel().add(HTML(message))
Пример #36
0
    def onRemoteResponse(self, response, request_info):
        mname = request_info.method
        if mname == "customize_message":
            showCustomizationResult(self, response, request_info)
            return

        if mname == "get_messagesdata_for_cust":
            locations_data = response["locations"]
            selectionbox = VerticalPanel(Padding=3)
            locations = ListBox()
            for (loc_name, loc_id) in locations_data:
                locations.addItem(loc_id, loc_name)
            messages = ListBox()
            messages.setName("locations")
            messages.addItem(location_select_label)
            for (name, d) in response["messages"].items():
                messages.addItem(d['label'], name)

            locations.addChangeListener(self)
            messages.addChangeListener(self)
            self.locations = locations
            self.messages = messages

            locationbox = HorizontalPanel()
            locationbox.add(Label("Location: ", StyleName="text", Width=80))
            locationbox.add(locations)

            msgnamebox = HorizontalPanel()
            msgnamebox.add(Label("Message: ", StyleName="text", Width=80))
            msgnamebox.add(messages)

            selectionbox.add(locationbox)
            selectionbox.add(msgnamebox)

            mainpanel = VerticalPanel(StyleName="dataBoxContent")
            mainpanel.add(selectionbox)
            self.mainpanel = mainpanel
            root = RootPanel()
            root.add(mainpanel)

        if mname == "get_messagecustdata":
            self.messages_data = response
            buttonspanel = FlowPanel(Spacing=1, Padding=1, Width=600)
            #buttonspanel.add(Label("Macros:", StyleName="text"))
            for macro_d in self.messages_data['macros']:
                macrobutton = Button(macro_d['label'], self, StyleName="buttonlikelink")#"nicebutton small")
                macrobutton.name = macro_d['name']
                buttonspanel.add(macrobutton)

            msgpanel = VerticalPanel(Padding=1, Spacing=1)
            messagebox = TextArea()
            messagebox.setCharacterWidth(70)
            height = len(self.messages_data["text"].split('\n')) + 1
            messagebox.setVisibleLines(height)
            messagebox.setText(self.messages_data["text"])
            messagebox.setName("textBoxFormElement")
            self.messagebox = messagebox
            msgpanel.add(messagebox)
            self.statusbar = Label(StyleName="errorMessage")
            msgpanel.add(self.statusbar)
            actionbuttons = HorizontalPanel(Spacing=2)
            updatebutton = Button("Update", self, StyleName="nicebutton small yellow")
            updatebutton.name = "update"
            actionbuttons.add(updatebutton)
            #actionbuttons.add(Button("Send me a preview mail"))
            msgpanel.add(actionbuttons)

            editorbox = VerticalPanel(Padding=1)
            editorbox.add(buttonspanel)
            editorbox.add(msgpanel)
            editorpanel = CaptionPanel("Message editor", editorbox, Padding=1, StyleName="text")
            editorpanel.name = "editorpanel"
            self.editorpanel = editorpanel

            self.mainpanel.add(editorpanel)
Пример #37
0
import pyjd
from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.Image import Image
from pyjamas.ui.Anchor import Anchor

if __name__ == '__main__':
    pyjd.setup("Anchor.html")

    root = RootPanel()
    image_url = "http://www.dcuktec.com/static/images/logo.png"
    image = Image(image_url)
    anchor = Anchor(Widget=image)
    anchor.href.set('http://www.dcuktec.com')
    root.add(anchor)

    pyjd.run()

Пример #38
0
    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)
Пример #39
0
        if self.page < self.min_page: self.page = self.min_page
        elif self.page > self.max_page: self.page = self.max_page
        total_pages = (self.max_page - self.min_page) + 1

        self.g.setHTML(0, 4, "<b>page %d of %d</b>" % (self.page, total_pages))

        if self.page >= self.max_page:
            self.addb.setEnabled(False)
        else:
            self.addb.setEnabled(True)

        if self.page <= self.min_page:
            self.subb.setEnabled(False)
        else:
            self.subb.setEnabled(True)

        for y in range(1, 5):
            for x in range(5):
                self.g.setText(y, x, "%d (%d,%d)" % (self.page, x, y))


def AppInit():
    return GridWidget()


if __name__ == '__main__':
    pyjd.setup("./GridTest.html")
    g = GridWidget()
    RootPanel().add(g)
    pyjd.run()
Пример #40
0
        SimplePanel.__init__(self)
        self.setSize('100%', '100%')

        options = MapOptions()
        options.zoom = 4
        options.center = LatLng(-25.363882, 131.044922)
        options.mapTypeId = MapTypeId.ROADMAP

        self.map = Map(self.getElement(), options)

        self.map.addListener("click", self.clicked)

    def clicked(self, event):
        print "clicked on " + str(event.latLng)
        self.placeMarker(event.latLng)

    def placeMarker(self, location):
        options = MarkerOptions()
        options.position = location
        options.map = self.map

        marker = Marker(options)

        self.map.setCenter(location)


if __name__ == '__main__':

    root = RootPanel()
    root.add(EventArguments())
Пример #41
0
 def onMouseLeave(self, sender):
     RootPanel().add(
         HTML("mouseleave: clearing focus (keyboard input not accepted)"))
     self.setFocus(False)
Пример #42
0
 def failed(self, message):
     msg = "Failed to access data"
     if message:
         msg = "%s: %s" % (msg, message)
     RootPanel().add(HTML(msg))
Пример #43
0
            token = item['fields']['name']
            self.createPage(token, html, token)
            self.setPage(token)

    def onRemoteError(self, code, message, request_info):
        RootPanel().add(
            HTML("Server Error or Invalid Response: ERROR " + str(code) +
                 " - " + str(message)))


class DataService(JSONProxy):
    def __init__(self):
        JSONProxy.__init__(self, "/services/pages/", [
            "getPage", "updatePage", "getPages", "addPage", "getPageByName",
            "deletePage"
        ])


if __name__ == "__main__":
    pyjd.setup("http://127.0.0.8/site_media/public/index.html")

    el = DOM.createElement("div")
    el.innerHTML = "test"
    DOM.setAttribute(el, "id", "pyjamas.apps.Email(Text='hello')")
    label = Factory.createWidgetOnElement(el)
    RootPanel().add(label)

    app = WebApp()
    app.onModuleLoad()
    pyjd.run()
Пример #44
0
 def onMouseMove(self, sender, x, y):
     RootPanel().add(HTML("move: x %d " % x + "y %d" % y))
Пример #45
0
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]
Пример #46
0
        for i in range(self.numSectors):
            alpha = beta * i - math.pi / 2
            cos = math.cos(alpha)
            sin = math.sin(alpha)
            path = self.canvas.path(pathParams)
            path.moveTo(cx + r1 * cos, cy + r1 * sin)
            path.lineTo(cx + r2 * cos, cy + r2 * sin)
            self.opacity.append(1 / self.numSectors * i)
            self.sectors.append(path)

        period = 1000 / self.numSectors

        self._timer = Timer(listener=self)
        self._timer.scheduleRepeating(period)

        self.add(self.canvas)

    def onTimer(self, timerID):
        """ Respond to our timer firing.
        """
        self.opacity.insert(0, self.opacity.pop())
        for i in range(self.numSectors):
            self.sectors[i].setAttr("opacity", self.opacity[i])


#############################################################################

if __name__ == "__main__":
    panel = TestPanel()
    RootPanel().add(panel)
Пример #47
0
            return self.left_nibble * 16 + self.right_nibble
        else:
            return self.right_nibble * 16 + self.left_nibble

    @property
    def center(self):
        return bool(self.leds[4].value)

    @property
    def left_nibble(self):
        return self.leds[0].value + self.leds[1].value * 2 + self.leds[
            2].value * 4 + self.leds[3].value * 8

    @property
    def right_nibble(self):
        return self.leds[8].value + self.leds[7].value * 2 + self.leds[
            6].value * 4 + self.leds[5].value * 8


if __name__ == '__main__':
    pyjd.setup("public/Temp.html")
    gauge = Gauge("")
    RootPanel().add(gauge)
    leds = HorizontalPanel()
    RootPanel().add(leds)
    for x in range(2, 11):
        leds.add(LED(x, gauge))
    gauge.compute()

    pyjd.run()
Пример #48
0
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]
Пример #49
0
from pyjamas.ui.RootPanel import RootPanel, RootPanelCls
from pyjamas.ui.SimplePanel import SimplePanel
from pyjamas import DOM
from pyjamas.Timer import Timer

from pyjamas.gmaps.Map import Map, MapTypeId, MapOptions
from pyjamas.gmaps.Base import LatLng


class ControlDisableUI(SimplePanel):

    def __init__(self):
        SimplePanel.__init__(self)
        self.setSize('100%', '100%')

        options = MapOptions()

        options.zoom = 4
        options.center = LatLng(-33, 151)
        options.mapTypeId = MapTypeId.ROADMAP

        options.disableDefaultUI = True

        self.map = Map(self.getElement(), options)


if __name__ == '__main__':

    root = RootPanel()
    root.add(ControlDisableUI())
Пример #50
0
    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)
Пример #51
0
        self.add(g)
        self.g.setWidget(y_board, x_board, g)

  def grid_to_state(self, point):
    board = self.state.boards
    for y_board in range(3):
      for x_board in range(3):
        g = self.g.getWidget(y_board, x_board)
        for y_cell in range(3):
          for x_cell in range(3):
            if isinstance(g.getWidget(y_cell, x_cell), Button):
              assert board[y_board][x_board][y_cell][x_cell]['cell'] == 0
            elif (g.getText(y_cell, x_cell) == '1') or (g.getText(y_cell, x_cell) == '2'):
              if self.state.boards[y_board][x_board][y_cell][x_cell]['cell'] == 0:
                self.state.boards[y_board][x_board][y_cell][x_cell]['cell'] = int(g.getText(y_cell, x_cell))
                piece = self.state.next_piece
                piece[0] = y_cell
                piece[1] = x_cell
            else:
              assert (g.getText(y_cell, x_cell) == '-')
    if is_win(self.state.boards[point['y_board']][point['x_board']]):
      self.state.score[str(self.min_player)] += 1


if __name__ == '__main__':
  pyjd.setup("./GridTest.html")
  g = GridWidget()
  r = RootPanel()
  r.add(g)
  pyjd.run()
Пример #52
0
        print "calcRoute start:", start, "end:", end

        request = DirectionsRequest(origin=start, destination=end, \
            travelMode=DirectionsTravelMode.DRIVING)

        self.directionsService.route(request, self.directionsResult)

    def directionsResult(self, response, status):
        print "directionsResult:"

        if status == DirectionsStatus.OK:

            for trip in response.trips:
                print "copyrights:", trip.copyrights

                for route in trip.routes:
                    print route.start_geocode.formatted_address
                    print route.end_geocode.formatted_address
                    print route.steps[0].start_point
                    print route.steps[0].end_point

                print "\n"

            self.directionsDisplay.setDirections(response)


if __name__ == '__main__':

    root = RootPanel()
    root.add(DirectionsSimple())
Пример #53
0
    def onClick(self, sender):
        log.writebr('Text' + str(sender))

    def _event_targets_title(self, event):
        target = DOM.eventGetTarget(event)
        return target and DOM.isOrHasChild(self.title.getElement(), target)

    def onBrowserEvent(self, event):
        etype = DOM.eventGetType(event)
        if etype == "click":
            if self._event_targets_title(event):
                return
        ClickHandler.onBrowserEvent(self, event)


class Text(HTML, ClickHandler):
    def __init__(self, text):
        HTML.__init__(self, text)
        ClickHandler.__init__(self, preventDefault=True)
        self.addClickListener(self)

    def onClick(self, sender):
        log.writebr('Text' + str(sender))


if __name__ == "__main__":
    pyjd.setup("./Override.html")
    board = Board()
    RootPanel().add(board)
    pyjd.run()
Пример #54
0
        latSpan = northEast.lat() - southWest.lat()

        for i in range(0, 5):
            location = LatLng(southWest.lat() + latSpan * random(),
                              southWest.lng() + lngSpan * random())

            options = MarkerOptions()
            options.position = location
            options.map = self.map

            marker = Marker(options)
            marker.setTitle(str(i + 1))

            self.attachSecretMessage(marker, i)

    def attachSecretMessage(self, marker, number):
        message = ["This", "is", "the", "secret", "message"]

        options = InfoWindowOptions()
        options.content = message[number]

        infoWindow = InfoWindow(options)

        marker.addListener('click', lambda: infoWindow.open(self.map, marker))


if __name__ == '__main__':

    root = RootPanel()
    root.add(EventClosure())
Пример #55
0
import pyjd
from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.Image import Image
from pyjamas.ui.Anchor import Anchor

if __name__ == '__main__':
    pyjd.setup("public/Anchor.html")

    root = RootPanel()
    image = Image('http://pyj.be/img/pyjamas.128x128.png')
    anchor = Anchor(Widget=image, Href='http://pyj.be', Title='Pyjs website')
    root.add(anchor)

    pyjd.run()

Пример #56
0
        mainpage.mid = result['movie_id']


class Site:
    def __init__(self):
        self.mid = None
        HTTPRequest().asyncGet(
            "http://student02.cse.nd.edu:40001/recommendations/156",
            getRec(self))


if __name__ == '__main__':
    pyjd.setup("public/primer.html")
    mainpage = Site()
    l = Label("Enter movie ID:")
    movie = Label("Movie Title Displayed Here if Found")
    movieRating = Label("Movie Rating Displayed Here if Found")
    poster = Image()
    b1 = Button("Up", upvote)
    b2 = Button("Down", downvote)
    absolute = AbsolutePanel()
    absolute.add(poster, 50, 25)
    absolute.add(b1, 0, 100)
    absolute.add(b2, 250, 100)
    absolute.add(movie, 50, 0)
    absolute.add(movieRating, 50, 315)
    absolute.setWidth("100%")
    absolute.setHeight("100%")
    RootPanel().add(absolute)
    pyjd.run()
Пример #57
0
 def onModuleLoad(self):
     self.photos = Photos()
     RootPanel().add(self.photos)
Пример #58
0
        self.focussed = False
        RootPanelCls.__init__(self, *args, **kwargs)
        ClickHandler.__init__(self)
        KeyboardHandler.__init__(self)

        self.addClickListener(self)

    def onClick(self, Sender):
        self.focussed = not self.focussed
        self.Parent.setFocus(self.focussed)


if __name__ == '__main__':
    pyjd.setup("public/Space.html")
    c = GameCanvas(800, 600)
    panel = FocusPanel(Widget=c)
    RootPanel().add(panel)
    panel.addKeyboardListener(c)
    panel.setFocus(True)
    RootPanel().add(
        HTML("""
<hr/>
Left/Right arrows turn, Up key thrusts, Space bar fires<br/>
<a href="http://rumsey.org/blog/?p=215">About Space Game</a> by <a href="http://rumsey.org/blog/">Ogre</a><br/>
Written entirely in Python, using <a href="http://pyjs.org/">Pyjamas</a></br>
Copyright &copy; 2009 Joe Rumsey
"""))

    #c.getElement().focus()
    pyjd.run()
Пример #59
0
        #self.setSpacing('10px')

        pool = StudentContainer(1, 20, 'pool_1')
        for item in [['Fred', 12], ['Jane', 10], ['Sam', 18], ['Ginger', 8],
                     ['Mary', 4]]:
            pool.addStudent(name=item[0], age=item[1])
        self.append(pool)
        self.append(StudentContainer(6, 13, 'pool_2'))
        self.append(StudentContainer(11, 20, 'pool_3'))
        self.setSpacing('10px')

    def containerFromId(self, id):
        for item in self.children:
            if item.getID() == id:
                return item


class MultiTargetDemo(DNDDemo):
    def __init__(self):
        self.drop_widget = ClassContainer()
        self.title = 'Drop with Validation'
        self.id = 'multi'
        DNDDemo.__init__(self)


if __name__ == '__main__':
    pyjd.setup("./public/DNDTest.html")
    j = RootPanel()
    j.add(DNDDemos())
    pyjd.run()
Пример #60
0
 def onModuleLoad(self):
     self.b = Button("function callback", onButtonClick)
     self.b2 = Button("object callback", self)
     RootPanel().add(self.b)
     RootPanel().add(self.b2)