Exemplo n.º 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)
Exemplo n.º 2
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)
Exemplo n.º 3
0
def main(init):
    root = RootPanel()
    container = FocusPanel()
    DeferredCommand.add(Focus(container))
    root.add(container)
    container.setSize(21*15,21*15)
    init(container)
Exemplo n.º 4
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)
Exemplo n.º 5
0
    def onModuleLoad(self):
        slot = RootPanel("calendar")
        if slot:
            calendar = SchoolCalendarWidget(15)
            slot.add(calendar)

            slot = RootPanel("days")
            if slot:
                filterWidget = DayFilterWidget(calendar)
                slot.add(filterWidget)
Exemplo n.º 6
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)
Exemplo n.º 7
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)
Exemplo n.º 8
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()
Exemplo n.º 9
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.")
Exemplo n.º 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.")
Exemplo n.º 11
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())
Exemplo n.º 12
0
from pyjamas.Timer import Timer

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


class ControlSimple(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.navigationControl = False
        #options.scaleControl = True

        options = MapOptions(zoom=4, center=LatLng(-33, 151),
                           mapTypeId=MapTypeId.ROADMAP,
                           navigationControl=False, scaleControl=True)

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


if __name__ == '__main__':

    root = RootPanel()
    root.add(ControlSimple())
Exemplo n.º 13
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())
Exemplo n.º 14
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]
Exemplo n.º 15
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())
Exemplo n.º 16
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()
Exemplo n.º 17
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()
Exemplo n.º 18
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)
Exemplo n.º 19
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())
Exemplo n.º 20
0
from pyjamas.gmaps.Map import Map, MapTypeId, MapOptions
from pyjamas.gmaps.Base import LatLng


class ControlSimple(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.navigationControl = False
        #options.scaleControl = True

        options = MapOptions(zoom=4,
                             center=LatLng(-33, 151),
                             mapTypeId=MapTypeId.ROADMAP,
                             navigationControl=False,
                             scaleControl=True)

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


if __name__ == '__main__':

    root = RootPanel()
    root.add(ControlSimple())
Exemplo n.º 21
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)
Exemplo n.º 22
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()

Exemplo n.º 23
0
    def geocodeResult(self, results, status):
        print "geocodeResult"

        if status == GeocoderStatus.OK:

            for res in results:
                print res.formatted_address
                print res.geometry.location.lat()
                print res.geometry.location.lng()
                for compo in res.address_components:
                    print "- " + compo.short_name
                print ""

            self.map.setCenter(results[0].geometry.location)

            marker = Marker(
                MarkerOptions(map=self.map,
                              position=results[0].geometry.location))

        else:
            Window.alert(
                "Geocode was not successful for the following reason: " +
                status)


if __name__ == '__main__':

    root = RootPanel()
    root.add(GeocodingSimple())
Exemplo n.º 24
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())
Exemplo n.º 25
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())
Exemplo n.º 26
0
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from pyjamas.ui.RootPanel import RootPanel, RootPanelCls
from pyjamas.ui.SimplePanel import SimplePanel
from pyjamas import DOM

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


if __name__ == '__main__':

    mapPanel = SimplePanel()
    mapPanel.setSize('100%', '100%')

    options = MapOptions(zoom=8, center=LatLng(-34.397, 150.644),
                         mapTypeId=MapTypeId.ROADMAP)

    #options = MapOptions()
    #options.zoom = 8
    #options.center = LatLng(-34.397, 150.644)
    #options.mapTypeId = MapTypeId.ROADMAP

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

    #root = RootPanelCls(DOM.getElementById("here"))
    root = RootPanel()
    root.add(mapPanel)
Exemplo n.º 27
0
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from pyjamas.ui.RootPanel import RootPanel, RootPanelCls
from pyjamas.ui.SimplePanel import SimplePanel
from pyjamas import DOM

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

if __name__ == '__main__':

    mapPanel = SimplePanel()
    mapPanel.setSize('100%', '100%')

    options = MapOptions(zoom=8,
                         center=LatLng(-34.397, 150.644),
                         mapTypeId=MapTypeId.ROADMAP)

    #options = MapOptions()
    #options.zoom = 8
    #options.center = LatLng(-34.397, 150.644)
    #options.mapTypeId = MapTypeId.ROADMAP

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

    #root = RootPanelCls(DOM.getElementById("here"))
    root = RootPanel()
    root.add(mapPanel)
Exemplo n.º 28
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())
Exemplo n.º 29
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())
Exemplo n.º 30
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())
Exemplo n.º 31
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())
Exemplo n.º 32
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]
Exemplo n.º 33
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()
Exemplo n.º 34
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)
Exemplo n.º 35
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())
Exemplo n.º 36
0
            self.geocoder.geocode(request, self.geocodeResult)

    def geocodeResult(self, results, status):
        print "geocodeResult"

        if status == GeocoderStatus.OK:

            for res in results:
                print res.formatted_address
                print res.geometry.location.lat()
                print res.geometry.location.lng()
                for compo in res.address_components:
                    print "- " + compo.short_name
                print ""

            self.map.setCenter(results[0].geometry.location)

            marker = Marker(MarkerOptions(map=self.map,
                position=results[0].geometry.location))

        else:
            Window.alert(
                "Geocode was not successful for the following reason: " +
                status)


if __name__ == '__main__':

    root = RootPanel()
    root.add(GeocodingSimple())