Exemple #1
0
 def addGroup(self, sender):
     self.listPanel.setVisible(True)
     op = Label(self.operator, Title='Invert group operator', StyleName='aur-search-advanced-group-op', Visible=False)
     op.addClickListener(getattr(self, 'invertOperator'))
     if len(self.children) > 0 or len(self.parameters) > 0: op.setVisible(True)
     self.childPanel.add(op)
     self.childPanel.setCellHorizontalAlignment(op, 'right')
     g = ParamGroup(self.childPanel, self.kind, self, self.level+1)
     g.op = op
     self.children.append(g)
 def addBlock(self, block, classHelp='help_default', beforeIndex=None):
     panel = HorizontalPanel()
     panel.add(block)
     info = Label('i', StyleName='info_btn')
     info.block = block
     info.classHelp = classHelp
     info.addClickListener(self.showInfo)
     panel.add(info)
     if beforeIndex is not None: self.list.insert(panel, self.list.getBody(), 0)#deprecated
     else: self.list.add(panel)
     self.list.setStyleName(self.list.getWidgetTd(panel), 'block_info')
     self.blocks.append(block)
Exemple #3
0
 def addParam(self, sender):
     self.listPanel.setVisible(True)
     op = Label(self.operator, Title='Invert group operator', StyleName='aur-search-advanced-param-op', Visible=False)
     op.addClickListener(getattr(self, 'invertOperator'))
     if len(self.parameters) > 0: op.setVisible(True)
     self.paramPanel.add(op)
     self.paramPanel.setCellHorizontalAlignment(op, 'right')
     k = self.kind[self.paramChooser.getSelectedValues()[0]]
     p = Param(self.paramPanel, k, self)
     p.op = op
     self.parameters.append(p)
     if len(self.children) > 0:
         self.children[0].op.setVisible(True)
Exemple #4
0
    def addBlock(self, block, classHelp='help_default', beforeIndex=None):
        panel = HorizontalPanel()
        panel.add(block)
        info = Label('i', StyleName='info_btn')
        info.block = block
        info.classHelp = classHelp
        info.addClickListener(self.showInfo)
        panel.add(info)
        if beforeIndex is not None:
            self.list.insert(panel, self.list.getBody(), 0)  #deprecated
        else:
            self.list.add(panel)
        self.list.setStyleName(self.list.getWidgetTd(panel), 'block_info')
        self.blocks.append(block)

        if block.name in [
                'commandType', 'numericType', 'logicType', 'alphaNumericType'
        ]:
            panel.add(self.getRemoveCustomBlock(block))
            info.addMouseListener(TooltipListener("Editar"))
        else:
            info.addMouseListener(TooltipListener("Ajuda"))
Exemple #5
0
 def getRemoveCustomBlock(self, block):
     remove = Label('x', StyleName='remove_btn')
     remove.addMouseListener(TooltipListener("Remover"))
     remove.block = block
     remove.addClickListener(self.RemoveCustomBlock)
     return remove
Exemple #6
0
class Game(VerticalPanel):
    def __init__(self, row, column=0):
        super(Game, self).__init__(StyleName='game')
        self.sinkEvents(Event.ONCONTEXTMENU)  # to disable right click

        self.row = row
        self.column = column or row
        self.level = 1
        self.toppers = [[], [], []]  # storage for top scorers for 3 levels.
        self.remote = DataService()
        self.remote_handler = RemoteHandler(self)
        self.remote.get_scores(self.remote_handler)

        # contents of Game
        menubar = MineMenuBar(self)
        score_board = HorizontalPanel(StyleName='score-board')
        self.grid_panel = SimplePanel(StyleName='grid-panel')

        self.add(menubar)
        self.add(score_board)
        self.add(self.grid_panel)

        # contents of score_board
        self.counter = Label('000', StyleName='digit counter')
        self.face = Smiley(self)
        self.timer = Label('000', StyleName='digit timer')

        for one in (self.counter, self.face, self.timer):
            score_board.add(one)
        score_board.setCellWidth(self.face, '100%')

        self.create_grid()
        self.start()

    def onBrowserEvent(self, event):
        # prevent right click context menu as well as all the other events.
        DOM.eventPreventDefault(event)

    def create_grid(self):
        # contents of self.grid_panel
        self.grid = CustomGrid(self, self.row, self.column)
        self.grid_panel.add(self.grid)

    def start(self, no_of_bomb=0):
        self.time = -1
        self.started = True
        self.first_click = True

        self.bombed_cells = []
        self.flagged_cells = []
        self.to_be_released = []  # cells to be released after being pressed
        self.count_opened_cells = 0
        self.no_of_click = 0

        self.squares = self.row * self.column
        self.no_of_bomb = no_of_bomb or int((self.squares * 10) / 64)
        self.no_of_safe_zones = self.squares - self.no_of_bomb

        self.set_counter()
        self.timer.setText('000')

        self.generate_bombs()
        self.face.setStyleName('facesmile')

    def get_all_cells(self):
        for i in xrange(self.row):
            for j in xrange(self.column):
                one = self.grid.getCell(i, j)
                yield one

    def get_neighbors(self, cell):
        x = cell.x
        y = cell.y
        row, column = self.row, self.column
        for i in xrange(x - 1, x + 2):
            if 0 <= i < row:
                for j in xrange(y - 1, y + 2):
                    if 0 <= j < column:
                        if (i, j) != (x, y):
                            one = self.grid.getCell(i, j)
                            yield one

    def set_counter(self):
        next_value = self.no_of_bomb - len(self.flagged_cells)

        if next_value == 0 and self.started:
            self.counter.setStyleName('digit counter-blue')
            self.counter.addClickListener(RemainingMineHandler(self))
        else:
            self.counter.setStyleName('digit counter')
            self.counter._clickListeners = []

        if next_value < 0:
            template = '-00'
            next_value = abs(next_value)
        else:
            template = '000'
        value = str(next_value)
        value = template[:-len(value)] + value
        self.counter.setText(value)

    def onTimer(self, target):
        if not self.started or self.first_click:
            return
        Timer(1000, self)
        self.time += 1
        if self.time <= 999:
            str_time = str(self.time)
            str_time = '000'[:-len(str_time)] + str_time
            self.timer.setText(str_time)
        else:
            self.started = False
            self.face.setStyleName('faceclock')

    def sample(self, population, k):
        # pyjamas doesn't support random.sample but random.choice
        seq = list(population)
        s = []
        for i in xrange(k):
            pick = random.choice(seq)
            seq.remove(pick)
            s.append(pick)
        return s

    def generate_bombs(self):
        # generate 1 extra mine so that if user's first click is bomb, move that
        bombs = self.sample(xrange(self.squares), self.no_of_bomb + 1)
        row, column = self.row, self.column
        for i, bomb in enumerate(bombs):
            x = bomb // column
            y = bomb % column
            mine = self.grid.getCell(x, y)
            if i == 0:
                self.extra_mine = mine
                continue
            #DOM.setInnerHTML(mine.getElement(),'b');mine.addStyleName('debug')
            self.bombed_cells.append(mine)
            mine.count = -1
            for one in self.get_neighbors(mine):
                if one.count != -1:
                    one.count += 1

    def move_to_extra_mine(self, to_be_moved):
        to_be_moved.count = 0
        self.bombed_cells.remove(to_be_moved)
        for one in self.get_neighbors(to_be_moved):
            if one.count == -1:
                to_be_moved.count += 1
            else:
                one.count -= 1

        self.extra_mine.count = -1
        self.bombed_cells.append(self.extra_mine)
        for one in self.get_neighbors(self.extra_mine):
            if one.count != -1:
                one.count += 1

    def press_neighbor_cells(self, cell):
        self.count_flags = 0
        self.bomb_explodes_on = []
        self.to_be_released = []
        for one in self.get_neighbors(cell):
            if one.state == 3:
                continue
            one.addStyleName('pressed')
            self.to_be_released.append(one)
            if one.state == 1:
                self.count_flags += 1
            else:
                if one.count == -1:
                    self.bomb_explodes_on.append(one)

    def open_if_satisfies(self, cell):
        if self.count_flags == cell.count:
            if self.bomb_explodes_on:
                self.show_all_bombs(self.bomb_explodes_on)
            else:
                self.open_neighboring_cells(cell)

    def open_neighboring_cells(self, cell):
        if not self.started:
            return
        for one in self.get_neighbors(cell):
            if one.state in (0, 2) and one.count != -1:
                one.setStyleName('opened')
                one.state = 3
                self.count_opened_cells += 1
                if one.count == 0:
                    self.open_neighboring_cells(one)
                else:
                    setColorfulHTML(one.getElement(), one.count)
        self.check_win()

    def check_win(self):
        if not self.started:
            return
        if self.count_opened_cells == self.no_of_safe_zones:
            for one in self.bombed_cells:
                if one.state != 1:
                    one.setStyleName('cell bombflagged')
                    self.flagged_cells.append(one)
            self.started = False
            self.set_counter()
            self.face.setStyleName('facewin')
            name = Window.prompt("You've done it !\n\
                                Game Time: %s seconds\n\
                                Number of Clicks: %s\n"
                                 "What's ur name ?" %
                                 (self.time, self.no_of_click))
            if name and self.level in (1, 2, 3):
                self.remote.add_score(name, self.level, self.time, \
                                      self.no_of_click, self.remote_handler)
                self.add_player_to_toppers(name)

    def add_player_to_toppers(self, name):
        current_level = self.level - 1
        toppers_in_this_level = self.toppers[current_level]
        toppers_in_this_level.append(('<b>%s</b>' % name, self.time))
        self.toppers[current_level] = sorted(toppers_in_this_level, \
                                             key=lambda score: score[1])
        self.remote_handler.load_top_scores()

    def show_all_bombs(self, bomb_explodes_on=[]):
        self.started = False
        self.face.setStyleName('facedead')

        for one in self.bombed_cells:
            if one.state != 1:
                one.setStyleName('cell bombrevealed')
        for one in self.flagged_cells:
            if one.count != -1:
                one.setStyleName('cell bombmisflagged')

        for one in bomb_explodes_on:
            one.setStyleName('cell bombdeath')

    def next_game(self, level=None, no_of_bomb=0):
        current_level = (self.row, self.column)
        if not level or level == (0, 0) or level == current_level:
            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)
class Client:
    def onModuleLoad(self):
        # Window.setTitle("CBC Test Stand")
        StyleSheetCssFile("styleSheet.css")

        self.TEXT_WAITING = "Waiting for response..."
        self.TEXT_ERROR = "Server Error"

        self.status = Label()

        # This is the remote service
        self.I2CPanel = I2CPanel()
        self.SCurveRunPanel = SCurveRunPanel()
        self.OccupancyCheckPanel = OccupancyCheckPanel()
        self.CalibrateChannelTrimsPanel = CalibrateChannelTrimsPanel()

        # mainPanel will have all of the working stuff in it
        self.mainPanel = DockPanel()
        # self.mainPanel.setSpacing(10)
        titleBar = HorizontalPanel()
        titleBar.add(HTML(r"CBC Test Stand (v1.1)", StyleName="titleStyle"))
        self.stopTakingDataButton = Button("Stop taking data")
        self.stopTakingDataButton.addClickListener(self)
        self.dataTakingPercentage = HTML("0%")
        self.dataTakingStatus = HTML("Initiating...")
        titleBar.add(self.dataTakingPercentage)
        titleBar.add(self.dataTakingStatus)
        titleBar.add(self.stopTakingDataButton)
        titleBar.setCellHorizontalAlignment(self.dataTakingStatus, HasHorizontalAlignment.ALIGN_RIGHT)
        titleBar.setCellHorizontalAlignment(self.dataTakingPercentage, HasHorizontalAlignment.ALIGN_RIGHT)
        titleBar.setCellHorizontalAlignment(self.stopTakingDataButton, HasHorizontalAlignment.ALIGN_RIGHT)
        titleBar.setWidth("100%")
        self.mainPanel.add(titleBar, DockPanel.NORTH)
        selectionPanel = VerticalPanel()

        # Register to get updates about the status of data taking, so that
        # I can update the information in the title bar
        self.dataRunManager = DataRunManager.instance()
        self.dataRunManager.registerEventHandler(self)

        self.activePanelButton = None
        self.activePanel = None

        self.registersButton = Label("I2C Registers", StyleName="areaStyle")
        self.occupanciesButton = Label("Test Occupancies", StyleName="areaStyle")
        self.scurveButton = Label("S-Curve Run", StyleName="areaStyle")
        self.calibrateTrimsButton = Label("Calibrate Trims", StyleName="areaStyle")

        self.registersButton.addClickListener(self)
        self.occupanciesButton.addClickListener(self)
        self.scurveButton.addClickListener(self)
        self.calibrateTrimsButton.addClickListener(self)

        selectionPanel.add(self.registersButton)
        selectionPanel.add(self.occupanciesButton)
        selectionPanel.add(self.scurveButton)
        selectionPanel.add(self.calibrateTrimsButton)

        self.mainPanel.add(selectionPanel, DockPanel.WEST)

        self.mainPanel.add(self.status, DockPanel.SOUTH)
        RootPanel().add(self.mainPanel)

        self.setNewMainPanel(self.registersButton)

    def onDataTakingEvent(self, eventCode, details):
        """
		Method that receives updates from DataRunManager
		"""
        if eventCode == DataRunManager.DataTakingStartedEvent:
            self.stopTakingDataButton.setEnabled(True)
            self.dataTakingPercentage.setText("0%")
            self.dataTakingStatus.setText("Starting run...")
        elif eventCode == DataRunManager.DataTakingFinishedEvent:
            self.stopTakingDataButton.setEnabled(False)
            self.dataTakingPercentage.setText("")
            self.dataTakingStatus.setText("Not taking data")
        elif eventCode == DataRunManager.DataTakingStatusEvent:
            self.stopTakingDataButton.setEnabled(True)
            self.dataTakingPercentage.setText("%3d%%" % int(details["fractionComplete"] * 100 + 0.5))
            self.dataTakingStatus.setText(details["statusString"])

    def onClick(self, sender):
        # (data, response_class): if the latter is 'self', then
        # the response is handled by the self.onRemoteResponse() method
        try:
            if sender == self.stopTakingDataButton:
                self.dataRunManager.stopTakingData()
            else:
                # I don't have any other buttons so it must be a panel change
                self.setNewMainPanel(sender)

        except Exception as error:
            self.status.setText("Client exception was thrown: '" + str(error.__class__) + "'='" + str(error) + "'")

    def setNewMainPanel(self, panelButton):
        if panelButton == self.activePanelButton:
            return  # already the active panel so no need to do anything

        # Remove the "selected" style from the current button
        if self.activePanelButton != None:
            self.activePanelButton.setStyleName("areaStyle")

        # Set the "selected" style on the new one
        self.activePanelButton = panelButton
        self.activePanelButton.setStyleName("selectedAreaStyle")

        # Clear the main panel
        if self.activePanel != None:
            self.mainPanel.remove(self.activePanel.getPanel())

            # Figure out what the new main panel should be
        if panelButton == self.registersButton:
            self.activePanel = self.I2CPanel
        elif panelButton == self.scurveButton:
            self.activePanel = self.SCurveRunPanel
        elif panelButton == self.occupanciesButton:
            self.activePanel = self.OccupancyCheckPanel
        elif panelButton == self.calibrateTrimsButton:
            self.activePanel = self.CalibrateChannelTrimsPanel

        # Set the new main panel
        self.activePanel.getPanel().setStyleName("selectedAreaStyle")
        self.activePanel.getPanel().setWidth("100%")
        self.mainPanel.add(self.activePanel.getPanel(), DockPanel.CENTER)

    def onRemoteResponse(self, response, request_info):
        self.status.setText(response)

    def onRemoteError(self, code, message, request_info):
        ErrorMessage("Unable to contact server")
Exemple #8
0
class Game(VerticalPanel):
    def __init__(self, row, column=0):
        super(Game, self).__init__(StyleName='game')
        self.sinkEvents(Event.ONCONTEXTMENU)  # to disable right click
        
        self.row = row
        self.column = column or row
        self.level = 1
        self.toppers = [[], [], []]  # storage for top scorers for 3 levels.
        self.remote = DataService()
        self.remote_handler = RemoteHandler(self)
        self.remote.get_scores(self.remote_handler)
        
        # contents of Game
        menubar = MineMenuBar(self)
        score_board = HorizontalPanel(StyleName='score-board')
        self.grid_panel = SimplePanel(StyleName='grid-panel')
        
        self.add(menubar)
        self.add(score_board)
        self.add(self.grid_panel)
        
        # contents of score_board
        self.counter = Label('000', StyleName='digit counter')
        self.face = Smiley(self)
        self.timer = Label('000', StyleName='digit timer')
        
        for one in (self.counter, self.face, self.timer):
            score_board.add(one)
        score_board.setCellWidth(self.face, '100%')
        
        self.create_grid()
        self.start()
    
    def onBrowserEvent(self, event):
        # prevent right click context menu as well as all the other events.
        DOM.eventPreventDefault(event)
    
    def create_grid(self):
        # contents of self.grid_panel
        self.grid = CustomGrid(self, self.row, self.column)
        self.grid_panel.add(self.grid)
    
    def start(self, no_of_bomb=0):
        self.time = -1
        self.started = True
        self.first_click = True
        
        self.bombed_cells = []
        self.flagged_cells = []
        self.to_be_released = []  # cells to be released after being pressed
        self.count_opened_cells = 0
        self.no_of_click = 0
        
        self.squares = self.row * self.column
        self.no_of_bomb = no_of_bomb or int((self.squares * 10) / 64)
        self.no_of_safe_zones = self.squares - self.no_of_bomb
        
        self.set_counter()
        self.timer.setText('000')
        
        self.generate_bombs()
        self.face.setStyleName('facesmile')
    
    def get_all_cells(self):
        for i in xrange(self.row):
            for j in xrange(self.column):
                one = self.grid.getCell(i, j)
                yield one
    
    def get_neighbors(self, cell):
        x = cell.x
        y = cell.y
        row, column = self.row, self.column
        for i in xrange(x-1, x+2):
            if 0 <= i < row:
                for j in xrange(y-1, y+2):
                    if 0 <= j < column:
                        if (i,j) != (x, y):
                            one = self.grid.getCell(i, j)
                            yield one
    
    def set_counter(self):
        next_value = self.no_of_bomb - len(self.flagged_cells)
        
        if next_value == 0 and self.started:
            self.counter.setStyleName('digit counter-blue')
            self.counter.addClickListener(RemainingMineHandler(self))
        else:
            self.counter.setStyleName('digit counter')
            self.counter._clickListeners = []
        
        if next_value < 0:
            template = '-00'
            next_value = abs(next_value)
        else:
            template = '000'
        value = str(next_value)
        value = template[:-len(value)] + value
        self.counter.setText(value)
    
    def onTimer(self, target):
        if not self.started or self.first_click:
            return
        Timer(1000, self)
        self.time += 1
        if self.time <= 999:
            str_time = str(self.time)
            str_time = '000'[:-len(str_time)] + str_time
            self.timer.setText(str_time)
        else:
            self.started = False
            self.face.setStyleName('faceclock')
    
    def sample(self, population, k):
        # pyjamas doesn't support random.sample but random.choice
        seq = list(population)
        s = []
        for i in xrange(k):
            pick = random.choice(seq)
            seq.remove(pick)
            s.append(pick)
        return s
    
    def generate_bombs(self):
        # generate 1 extra mine so that if user's first click is bomb, move that
        bombs = self.sample(xrange(self.squares), self.no_of_bomb+1)
        row, column = self.row, self.column
        for i,bomb in enumerate(bombs):
            x = bomb // column
            y = bomb % column
            mine = self.grid.getCell(x, y)
            if i == 0:
                self.extra_mine = mine
                continue
            #DOM.setInnerHTML(mine.getElement(),'b');mine.addStyleName('debug')
            self.bombed_cells.append(mine)
            mine.count = -1
            for one in self.get_neighbors(mine):
                if one.count != -1:
                    one.count += 1
    
    def move_to_extra_mine(self, to_be_moved):
        to_be_moved.count = 0
        self.bombed_cells.remove(to_be_moved)
        for one in self.get_neighbors(to_be_moved):
            if one.count == -1:
                to_be_moved.count += 1
            else:
                one.count -= 1
        
        self.extra_mine.count = -1
        self.bombed_cells.append(self.extra_mine)
        for one in self.get_neighbors(self.extra_mine):
            if one.count != -1:
                one.count += 1
    
    def press_neighbor_cells(self, cell):
        self.count_flags = 0
        self.bomb_explodes_on = []
        self.to_be_released = []
        for one in self.get_neighbors(cell):
            if one.state == 3:
                continue
            one.addStyleName('pressed')
            self.to_be_released.append(one)
            if one.state == 1:
                self.count_flags += 1
            else:
                if one.count == -1:
                    self.bomb_explodes_on.append(one)
    
    def open_if_satisfies(self, cell):
        if self.count_flags == cell.count:
            if self.bomb_explodes_on:
                self.show_all_bombs(self.bomb_explodes_on)
            else:
                self.open_neighboring_cells(cell)
    
    def open_neighboring_cells(self, cell):
        if not self.started:
            return
        for one in self.get_neighbors(cell):
            if one.state in (0, 2) and one.count != -1:
                one.setStyleName('opened')
                one.state = 3
                self.count_opened_cells += 1
                if one.count == 0:
                    self.open_neighboring_cells(one)
                else:
                    setColorfulHTML(one.getElement(), one.count)
        self.check_win()
    
    def check_win(self):
        if not self.started:
            return
        if self.count_opened_cells == self.no_of_safe_zones:
            for one in self.bombed_cells:
                if one.state != 1:
                    one.setStyleName('cell bombflagged')
                    self.flagged_cells.append(one)
            self.started = False
            self.set_counter()
            self.face.setStyleName('facewin')
            name = Window.prompt("You've done it !\n\
                                Game Time: %s seconds\n\
                                Number of Clicks: %s\n"
                                "What's ur name ?" % (self.time, self.no_of_click))
            if name and self.level in (1, 2, 3):
                self.remote.add_score(name, self.level, self.time, \
                                      self.no_of_click, self.remote_handler)
                self.add_player_to_toppers(name)
    
    def add_player_to_toppers(self, name):
        current_level = self.level - 1
        toppers_in_this_level = self.toppers[current_level]
        toppers_in_this_level.append(('<b>%s</b>' % name, self.time))
        self.toppers[current_level] = sorted(toppers_in_this_level, \
                                             key=lambda score: score[1])
        self.remote_handler.load_top_scores()
        
    def show_all_bombs(self, bomb_explodes_on=[]):
        self.started = False
        self.face.setStyleName('facedead')
        
        for one in self.bombed_cells:
            if one.state != 1:
                one.setStyleName('cell bombrevealed')
        for one in self.flagged_cells:
            if one.count != -1:
                one.setStyleName('cell bombmisflagged')
        
        for one in bomb_explodes_on:
            one.setStyleName('cell bombdeath')
    
    def next_game(self, level=None, no_of_bomb=0):
        current_level = (self.row, self.column)
        if not level or level == (0,0) or level == current_level:
            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)
class TemplatePanel(ComplexPanel):
    """
    Panel which allows you to attach or insert widgets into a
    pre-defined template.

    We don't do any caching of our own, since the browser will do
    caching for us, and probably more efficiently.
    """
    templateRoot = ""
    # XXX What is this text expression supposed to do? It won't be
    # added to the docstring as it is.
    """Set staticRoot to change the base path of all the templates
    that are loaded; templateRoot should have a trailing slash"""

    def __init__(self, templateName, allowEdit=False):
        ComplexPanel.__init__(self)
        self.loaded = False # Set after widgets are attached
        self.widgetsAttached = False
        self.id = None
        self.templateName = None
        self.title = None
        self.elementsById = {}
        self.metaTags = {}
        self.body = None
        self.links = []
        self.forms = []
        self.metaTagList = []
        self.loadListeners = []
        self.toAttach = []
        self.toInsert = []
        self.setElement(DOM.createDiv())
        self.editor = None
        self.allowEdit = allowEdit
        if templateName:
            self.loadTemplate(templateName)

    def getTemplatePath(self, templateName):
        return self.templateRoot+'tpl/'+templateName+'.html'

    def loadTemplate(self, templateName):
        self.templateName = templateName
        self.id = templateName + str(hash(self))
        self.httpReq = HTTPRequest()
        self.httpReq.asyncGet(self.getTemplatePath(templateName),
                              TemplateLoader(self))

    def getCurrentTemplate(self):
        """Return the template that is currently loaded, or is loading."""
        return self.templateName

    def isLoaded(self):
        """Return True if the template is finished loading."""
        return self.loaded

    def areWidgetsAttached(self):
        """Return True if the template is loaded and attachWidgets()
        has been called."""
        return self.widgetsAttached

    def setTemplateText(self, text):
        """
        Set the template text; if the template is not HTML, a subclass
        could override this to pre-process the text into HTML before
        passing it to the default implementation.
        """
        if self.allowEdit:
            self.originalText = text
        # If we have children, remove them all first since we are
        # trashing their DOM
        for child in List(self.children):
            self.remove(child)

        DOM.setInnerHTML(self.getElement(), text)
        self.elementsById = {}
        self.links = []
        self.metaTags = {}
        self.forms = []
        self.metaTagList = []

        # Make the ids unique and store a pointer to each named element
        for node in DOM.walkChildren(self.getElement()):
            #console.log("Passing node with name %s", node.nodeName)
            if node.nodeName == "META":
                name = node.getAttribute("name")
                content = node.getAttribute("content")
                console.log("Found meta %o name %s content %s",
                            node, name, content)
                self.metaTags[name] = content
                self.metaTagList.append(node)
            elif node.nodeName == "BODY":
                self.body = node
            elif node.nodeName == "TITLE":
                self.title = DOM.getInnerText(node)
            elif node.nodeName == "FORM":
                self.forms.append(node)

            nodeId = DOM.getAttribute(node, "id")
            if nodeId:
                self.elementsById[nodeId] = node
                DOM.setAttribute(node, "id", self.id + ":" + node.id)
            nodeHref = DOM.getAttribute(node, "href")
            if nodeHref:
                self.links.append(node)

        self.loaded = True
        if self.attached:
            self.attachWidgets()
            self.widgetsAttached = True

        if self.allowEdit:
            self.editor = None
            self.editButton = Label("edit "+unescape(self.templateName))
            self.editButton.addStyleName("link")
            self.editButton.addStyleName("ContentPanelEditLink")
            self.editButton.addClickListener(EventDelegate("onClick", self,
                                             self.onEditContentClick))
            ComplexPanel.insert(self, self.editButton, self.getElement(),
                                len(self.children))

        self.notifyLoadListeners()

    def onError(self, html, statusCode):
        if statusCode == 404 and self.allowEdit:
            self.editor = None
            self.originalText = ""
            DOM.setInnerHTML(self.getElement(), '')
            self.editButton = Label("create "+unescape(self.templateName))
            self.editButton.addStyleName("link")
            self.editButton.addStyleName("ContentPanelEditLink")
            self.editButton.addClickListener(EventDelegate("onClick", self,
                                             self.onEditContentClick))
            ComplexPanel.insert(self, self.editButton, self.getElement(),
                                len(self.children))
            return

        # Show the page we got in an iframe, which will hopefully show
        # the error better than we can.
        # DOM.setInnerHTML(self.getElement(), '<iframe src="'+self.getTemplatePath(self.templateName)+'"/>')

    def onTimeout(self, text):
        self.onError("Page loading timed out: "+text)

    def getElementsById(self):
        """Return a dict mapping an id to an element with that id
        inside the template; useful for post-processing."""
        return self.elementsById

    def getLinks(self):
        """Return a list of all the A HREF= elements found in the template."""
        return self.links

    def getForms(self):
        """Return a list of all the FORM elements found in the template."""
        return self.forms

    def onAttach(self):
        if not self.attached:
            SimplePanel.onAttach(self)
            if self.loaded and not self.widgetsAttached:
                self.attachWidgets()
                self.widgetsAttached = True

    def attachWidgets(self):
        """
        Attach and insert widgets into the DOM now that it has been
        loaded.  If any widgets were attached before loading, they
        will have been queued and the default implementation will
        attach them.

        Override this in subclasses to attach your own widgets after
        loading.
        """
        for attach in self.toAttach:
            self.attach(attach.name, attach.widget)
        for insert in self.toInsert:
            self.insert(insert.name, insert.widget)

    def getElementById(self, id):
        return self.elementsById[id]

    def insert(self, id, widget):
        """
        Insert a widget into the element with the given id, at the end
        of its children.
        """
        if not self.loaded:
            self.toInsert.append(PendingAttachOrInsert(id, widget))
        else:
            element = self.getElementById(id)
            if element:
                self.adopt(widget, element)
                self.children.append(widget)
            else:
                console.error("Page error: No such element " + id)
            return widget

    def attachToElement(self, element, widget):
        events = DOM.getEventsSunk(widget.getElement())
        widget.unsinkEvents(events)
        widget.setElement(element)
        widget.sinkEvents(events)
        self.adopt(widget, None)
        self.children.append(widget)

    def replaceElement(self, element, widget):
        """Replace an existing element with the given widget."""
        DOM.getParent(element).replaceChild(widget.getElement(), element)
        self.adopt(widget, None)
        self.children.append(widget)

    def attach(self, id, widget):
        """
        Attach a widget onto the element with the given id; the element
        currently associated with the widget is discarded.
        """
        if not self.loaded:
            self.toAttach.append(PendingAttachOrInsert(id, widget))
        else:
            element = self.getElementById(id)
            if element:
                self.attachToElement(element, widget)
            else:
                console.error("Page error: No such element " + id)
            return widget

    def getMeta(self, name):
        """
        Get the value of a meta-variable found in the template, or None if
        no meta tags were found with the given name.
        """
        return self.metaTags.get(name)

    def getTitle(self):
        """Return a user-friendly title for the page."""
        if self.title:
            return self.title
        else:
            return self.templateName

    def addLoadListener(self, listener):
        """
        The listener should be a function or an object implementing
        onTemplateLoaded. It will be called this TemplatePanel
        instance after the template has been loaded and after
        attachWidgets() is called.
        """
        self.loadListeners.append(listener)

    def removeLoadListener(self, listener):
        self.loadListeners.remove(listener)

    def notifyLoadListeners(self):
        for listener in self.loadListeners:
            if listener.onTemplateLoaded:
                listener.onTemplateLoaded(self)
            else:
                listener(self)

    def onEditContentClick(self, sender):
        if self.editor:
            editor = self.editor
            self.editor = None
            ComplexPanel.remove(self, editor)
            self.editButton.setText("edit " + unescape(self.templateName))
        else:
            self.editor = RichTextEditor(self.originalText)
            self.editor.addSaveListener(self)
            ComplexPanel.insert(self, self.editor, self.getElement(),
                                len(self.children))
            self.editButton.setText("close editor")

    def getTemplateSaveUrl(self, templateName):
        """
        Get the URL to post a template to when it is saved in the editor.
        """
        return self.getTemplatePath(templateName)

    def saveTemplateText(self, html):
        """
        Save the text. This method can be overridden to use a
        different save method. The default is to POST to the template
        save URL, passing a single parameter "content" with the html
        string.

        To change the target of the POST, override getTemplateSaveUrl().

        To preprocess the html, override this method in a subclass and
        perform processing there.
        """
        HTTPRequest().asyncPost(self.getTemplateSaveUrl(self.templateName),
                                "content=" + encodeURIComponent(html),
                                ContentSaveHandler(self))

    def onSave(self, sender):
        """Called when the user clicks save in the content editor."""
        html = self.editor.getHTML()
        self.saveTemplateText(html)

    def onSaveComplete(self):
        """
        Called when the template was successfully POSTed to the
        server; it reloads the template.

        Subclasses which don't use the default method of saving may
        want to call this after they successfully save the template.
        """
        self.loadTemplate(self.templateName)
Exemple #10
0
def onClick(sender):
    Window.alert('Make service request using %s' % sender.getID())


if __name__ == '__main__':
    pyjd.setup("public/Anchor.html")
    # EXAMPLE 1
    a1 = Anchor(
        Widget=HTML('Test 1: Anchor to external site using HTML widget.'),
        Href='http://pyjs.org',
        Title='Test1')
    RootPanel().add(a1)
    # EXAMPLE 2
    label = Label(text='Test 2: Click listener added to a label.')
    label.addClickListener(onClick)
    RootPanel().add(label)
    # EXAMPLE 3
    a2 = Hyperlink(text='Hyperlink', Element=DOM.createSpan())
    a2.setID('param1')
    a2.addClickListener(onClick)
    html2 = HTMLPanel(
        "Test 3: <span id ='t3'></span> added to HTMLPanel with click listener."
    )
    html2.add(a2, "t3")
    RootPanel().add(html2)
    # EXAMPLE 4
    hpanel = HorizontalPanel()
    hpanel.append(HTML('Test 4:  Anchor to external site using Image widget'))
    a3 = Anchor(Widget=Image('http://pyjs.org/assets/images/pyjs.128x128.png'),
                Href='http://pyjs.org',
def labelbutton(x,y):
    z = Label(x)
    z.addClickListener(y)
    return z
Exemple #12
0
from pyjamas.ui.Label import Label
from pyjamas.ui.Image import Image
from pyjamas.ui.HorizontalPanel import HorizontalPanel


def onClick(sender):
    Window.alert('Make service request using %s'%sender.getID())
    
if __name__ == '__main__':
    pyjd.setup("public/Anchor.html")
    # EXAMPLE 1
    a1 = Anchor(Widget = HTML('Test 1: Anchor to external site using HTML widget.'), Href='http://pyjs.org', Title = 'Test1')
    RootPanel().add(a1) 
    # EXAMPLE 2
    label = Label(text = 'Test 2: Click listener added to a label.')
    label.addClickListener(onClick)
    RootPanel().add(label) 
    # EXAMPLE 3
    a2 = Hyperlink(text = 'Hyperlink', Element = DOM.createSpan())
    a2.setID('param1')
    a2.addClickListener(onClick)
    html2=HTMLPanel("Test 3: <span id ='t3'></span> added to HTMLPanel with click listener.")
    html2.add(a2, "t3")
    RootPanel().add(html2)
    # EXAMPLE 4
    hpanel = HorizontalPanel()
    hpanel.append(HTML('Test 4:  Anchor to external site using Image widget'))
    a3 = Anchor(Widget = Image('http://pyjs.org/assets/images/pyjs.128x128.png'), Href='http://pyjs.org', Title = 'Test4')
    hpanel.append(a3)
    RootPanel().add(hpanel) 
    # EXAMPLE 5