def make_panel(self): message = Label( 'The configuration has been changed.\n' 'You must apply the changes in order for them to take effect.') DOM.setStyleAttribute(message.getElement(), "whiteSpace", 'pre') msgbox = Grid(1, 2, StyleName='changes') msgbox.setWidget(0, 0, Image('icons/exclam.png')) msgbox.setWidget(0, 1, message) msgbox.getCellFormatter().setStyleName(0, 0, 'changes-image') msgbox.getCellFormatter().setStyleName(0, 1, 'changes-text') button = Button('apply changes') button.addClickListener(self.apply_clicked) self.changes = VerticalPanel() self.changes.setHorizontalAlignment('right') self.changes.setVisible(False) self.changes.add(msgbox) self.changes.add(button) panel = VerticalPanel() panel.setSpacing(10) panel.add(self.table) panel.add(self.status) panel.add(self.changes) return panel
class OddGridWidget(DockPanel): def __init__(self, **kwargs): DockPanel.__init__(self, **kwargs) self.grid = Grid(StyleName="datagrid") self.sp = ScrollPanel(self.grid, Width="100%", Height="100%") self.header = Grid(Height="50px") self.add(self.header, DockPanel.NORTH) self.add(self.sp, DockPanel.CENTER) cf = self.setCellHeight(self.header, "50px") cf = self.setCellHeight(self.sp, "100%") self.sortcol = 0 def setData(self, data): self.data = data self.redraw() def sortfn(self, row1, row2): return cmp(row1[self.sortcol], row2[self.sortcol]) def redraw(self): self.data.sort(self.sortfn) rows = len(self.data) cols = 0 if rows > 0: cols = len(self.data[0]) self.grid.resize(rows, cols) self.header.resize(1, cols) cf = self.grid.getCellFormatter() for (nrow, row) in enumerate(self.data): for (ncol, item) in enumerate(row): self.grid.setHTML(nrow, ncol, str(item)) cf.setWidth(nrow, ncol, "200px") cf = self.header.getCellFormatter() self.sortbuttons = [] for ncol in range(cols): sb = Button("sort col %d" % ncol) sb.addClickListener(self) self.header.setWidget(0, ncol, sb) cf.setWidth(0, ncol, "200px") self.sortbuttons.append(sb) def onClick(self, sender): for (ncol, b) in enumerate(self.sortbuttons): if sender == b: self.sortcol = ncol self.redraw()
class TickeryTab(VerticalPanel): process = None # Define in subclass. def __init__(self, topPanel, **kwargs): VerticalPanel.__init__(self, HorizontalAlignment=HasAlignment.ALIGN_LEFT, StyleName='tickery-tab', **kwargs) self.topPanel = topPanel # don't add this yet! self.topGrid = Grid(1, 2, StyleName='tickery-tab-top-grid', HorizontalAlignment=HasAlignment.ALIGN_LEFT) self.add(self.topGrid) self.autoActivate = False def addTopPanel(self): parent = self.topPanel.getParent() if parent: parent.remove(self.topPanel) self.topGrid.setWidget(0, 0, self.topPanel) formatter = self.topGrid.getCellFormatter() formatter.setAlignment(0, 0, 'left', 'top') formatter.setAlignment(0, 1, 'left', 'top') formatter.setWidth(0, 1, '100%') def onTimer(self, timerid): self.setInputFocus() if self.autoActivate: self.autoActivate = False self.process()
def __init__(self, topPanel): TickeryTab.__init__(self, topPanel) # Get the query string and wanted tab, if any, from URL args. args = Window.getLocation().getSearchDict() query = args.get('query') wantedTab = args.get('tab') if wantedTab: wantedTab = wantedTab.lower() if query and wantedTab == self.tabName.lower(): query = urllib.unquote_plus(query) self.autoActivate = True else: query = self.defaultQuery self.instructions.setHorizontalAlignment(HasAlignment.ALIGN_LEFT) self.instructions.setStyleName('instructions-popup') self.popup = InstructionBox( self.__class__.__name__, self.instructions) self.popup.setText(self.instructionsTitle) self.db = Button(HELP_TEXT, StyleName='help-button') self.db.addClickListener(self) huhId = HTMLPanel.createUniqueId() help = HTMLPanel('%s <span id="%s"></span>' % (SHORT_INSTRUCTIONS[self.tabName], huhId), StyleName='simple-instructions') help.add(self.db, huhId) self.goButton = go.GoButton(self) self.query = text.TextAreaFocusHighlight(Text=query, VisibleLines=3, StyleName='large-query-area') self.checkResult = HorizontalPanel(Spacing=4) mainGrid = Grid(2, 2, StyleName='tickery-tab-panel', HorizontalAlignment=HasAlignment.ALIGN_LEFT) formatter = mainGrid.getCellFormatter() mainGrid.setWidget(0, 0, help) mainGrid.setWidget(1, 0, self.query) mainGrid.setWidget(1, 1, self.goButton) formatter.setHorizontalAlignment(0, 0, 'left') formatter.setHorizontalAlignment(1, 0, 'left') formatter.setAlignment(1, 1, 'left', 'bottom') self.topGrid.setWidget(0, 1, mainGrid) self.add(self.checkResult) self.results = userlist.UserListPanel(self, topPanel, HorizontalAlignment=HasAlignment.ALIGN_LEFT) self.add(self.results)
class PopupPagina(PopupPanel): def __init__(self, autoHide=None, modal=True, **kwargs): PopupPanel.__init__(self, autoHide, modal, **kwargs) datasource = None id = None if kwargs.has_key("datasrc"): datasource = kwargs["datasrc"] if kwargs.has_key("id"): id = kwargs["id"] self.setSize(Window.getClientWidth() - 50, Window.getClientHeight() - 50) self.setPopupPosition(20, 0) DOM.setAttribute(self, "align", "center") # self.dbProxInstrucao = DialogBox() # self.dbProxInstrucao.setHTML("Alow") # botton = Button("Ok") # botton.addClickListener(self.onCloseDialog) # self.dbProxInstrucao.setWidget(botton) self.caption = HTML() self.child = None self.setHTML("<b>Soma de Matrizes.</b>") self.dragging = False self.dragStartX = 0 self.dragStartY = 0 self.imageFechar = Image("images/fechar.gif", Size=("32px", "32px"), StyleName="gwt-ImageButton") self.imgbtnDesfazer = Image("images/previous-arrow.png", Size=("32px", "20px"), StyleName="gwt-ImageButton") self.imgbtnFazer = Image("images/next-arrow.png", Size=("32px", "20px"), StyleName="gwt-ImageButton") # self.imgbtnDesfazer.addClickListener(desfazerProxOperacao) # self.imgbtnFazer.addClickListener(fazerProxOperacao) self.btnAutomatic = Button("Automático", self.onIniciarAnimacaoAutomatica) self.btnInterativo = Button("Interativo") if id == "escalar": self.btnStepByStep = Button("Passo a passo", IniciarAnimacaoPassoAPasso) else: self.btnStepByStep = Button("Passo a passo", self.onIniciarAnimacaoPassoAPasso) self.btnFazer = Button("fazer >>", fazerProxOperacao) # self.btnFazer.setEnabled(False); self.btnDesfazer = Button("<< desfazer", desfazerProxOperacao) # self.btnDesfazer.setEnabled(False); self.btnFechar = PushButton(imageFechar, imageFechar) self.btnTestarResposta = Button("Testar Solução") self.lbVelocidade = ListBox() self.lbVelocidade.setID("lbseg") self.lbVelocidade.addItem("0.5 segundo", value=2) self.lbVelocidade.addItem("1 segundo", value=1) self.lbVelocidade.addItem("2 segundos", value=0.5) self.lbVelocidade.addItem("3 segundos", value=1 / 3) self.lbVelocidade.addItem("4 segundos", value=0.25) self.lbVelocidade.addItem("5 segundos", value=0.20) self.lbVelocidade.addItem("6 segundos", value=0.167) self.lbVelocidade.addItem("7 segundos", value=0.143) self.lbVelocidade.addItem("8 segundos", value=0.125) self.lbVelocidade.addItem("10 segundos", value=0.1) lblinha1 = ListBox() lblinha1.setID("lm1") lblinha1.addItem("1", value=1) lblinha1.addItem("2", value=2) lblinha1.addItem("3", value=3) lblinha1.addItem("4", value=4) lblinha1.addItem("5", value=5) lblinha2 = ListBox() lblinha2.setID("lm2") lblinha2.addItem("1", value=1) lblinha2.addItem("2", value=2) lblinha2.addItem("3", value=3) lblinha2.addItem("4", value=4) lblinha2.addItem("5", value=5) lbcoluna1 = ListBox() lbcoluna1.setID("cm1") lbcoluna1.addItem("1", value=1) lbcoluna1.addItem("2", value=2) lbcoluna1.addItem("3", value=3) lbcoluna1.addItem("4", value=4) lbcoluna1.addItem("5", value=5) lbcoluna1.addItem("6", value=6) lbcoluna1.addItem("7", value=7) lbcoluna2 = ListBox() lbcoluna2.setID("cm2") lbcoluna2.addItem("1", value=1) lbcoluna2.addItem("2", value=2) lbcoluna2.addItem("3", value=3) lbcoluna2.addItem("4", value=4) lbcoluna2.addItem("5", value=5) lbcoluna2.addItem("6", value=6) lbcoluna2.addItem("7", value=7) self.lblStatus = Label("Label para Status") # Eventos self.imageFechar.addClickListener(self.onFecharPopup) # Cabeçalho da poupPanel self.grid = Grid(1, 16) self.grid.setWidth(self.getWidth()) self.grid.setHTML(0, 0, "<b>Matriz 1:</b> Nº Linhas:") self.grid.setWidget(0, 1, lblinha1) self.grid.setText(0, 2, "Nº Colunas:") self.grid.setWidget(0, 3, lbcoluna1) self.grid.setHTML(0, 4, "<b>Matriz 2:</b> Nº Linhas:") self.grid.setWidget(0, 5, lblinha2) self.grid.setText(0, 6, "Nº Colunas:") self.grid.setWidget(0, 7, lbcoluna2) # self.grid.setWidget(0, 3, self.txtColunas) self.grid.setWidget(0, 8, self.btnStepByStep) self.grid.setWidget(0, 9, self.btnDesfazer) self.grid.setWidget(0, 10, self.btnFazer) self.grid.setHTML(0, 11, "<b>Velocidade:</b>") self.grid.setWidget(0, 12, self.lbVelocidade) self.grid.setWidget(0, 13, self.btnAutomatic) # self.grid.setWidget(0, 14, self.btnInterativo) self.grid.setWidget(0, 15, self.imageFechar) # self.grid.setWidget(0, 7, self.btnFechar) self.grid.getCellFormatter().setAlignment( 0, 15, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_TOP ) self.panel = FlexTable(Height="100%", width="100%", BorderWidth="0", CellPadding="0", CellSpacing="0") self.panel.setWidget(0, 0, self.caption) self.panel.setWidget(1, 0, self.grid) self.panel.getCellFormatter().setHeight(2, 0, "100%") self.panel.getCellFormatter().setWidth(2, 0, "100%") self.panel.getCellFormatter().setAlignment( 2, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_TOP ) self.panel.setID("contetepopup") painelhorizontal = HorizontalPanel() gridinterativa = FlexTable() painelhorizontal.add( HTML( "<canvas id='%s' datasrc='%s' width='%s' height='%s' style='image-rendering: optimizespeed !important; '></canvas>" % ("soma", datasource, "1000px", "500px") ) ) ftInterativo = FlexTable(Height="100%", width="100%", BorderWidth="0", CellPadding="0", CellSpacing="0") gridinterativa = Grid(4, 4) gridinterativa.setWidget( 0, 0, HTML( "<b>M1(</b><input type='text' class='gwt-TextBox' id='linha1' style='width: 25px; height:20px;' maxLength='1'><b> , </b>" ), ) gridinterativa.setWidget( 0, 1, HTML( "<input type='text' class='gwt-TextBox' id='coluna1' style='width: 25px;height:20px;' maxLength='1'><b>) +</b>" ), ) gridinterativa.setWidget( 0, 2, HTML( "<b>M2(</b> <input type='text' class='gwt-TextBox' id='linha2' style='width: 25px; height:20px;' maxLength='1'><b> , </b>" ), ) gridinterativa.setWidget( 0, 3, HTML( "<input type='text' class='gwt-TextBox' id='coluna2' style='width: 25px; height:20px;' maxLength='1'><b>) =</b>" ), ) gridinterativa.setWidget( 2, 0, HTML( " <b>(</b><input type='text' class='gwt-TextBox' id='n1' style='width: 25px; height:20px;' maxLength='1'><b>) +</b>" ), ) gridinterativa.setWidget( 2, 1, HTML( "<b>(</b><input type='text' class='gwt-TextBox' id='n2' style='width: 25px; height:20px;' maxLength='1'><b>)</b>" ), ) gridinterativa.setWidget( 2, 2, HTML( "<b>= </b> <input type='text' class='gwt-TextBox' id='solucao' style='width: 25px; height:20px;' maxLength='1'>" ), ) ftInterativo.setHTML(0, 0, "</br>") ftInterativo.setHTML(1, 0, "<b><h3>Painel Interativo<h3></b>") # ftInterativo.setWidget(2, 0, self.btnInterativo) ftInterativo.setWidget(3, 0, gridinterativa) ftInterativo.setWidget(4, 0, self.btnTestarResposta) ftInterativo.setHTML(5, 0, "</br>") ftInterativo.setHTML(6, 0, "Use a tecla tab para agilizar.") ftInterativo.getCellFormatter().setAlignment( 4, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_TOP ) ftInterativo.getCellFormatter().setAlignment( 1, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_TOP ) # painelhorizontal.add(ftInterativo) self.panel.setWidget(2, 0, painelhorizontal) self.panel.setWidget(3, 0, self.lblStatus) self.panel.setStyleName("dialogContent") PopupPanel.setWidget(self, self.panel) self.setStyleName("gwt-DialogBox") self.caption.setStyleName("Caption") self.caption.addMouseListener(self) # self.txtlm1.setFocus(True); def onFecharPopup(self, event): self.hide() PararAnimacao() def onIniciarAnimacaoPassoAPasso(self, event): self.btnFazer.setEnabled(True) self.btnDesfazer.setEnabled(True) if self.validarParametrosMatriz(): IniciarAnimacaoPassoAPasso() def onIniciarAnimacaoAutomatica(self, event): if self.validarParametrosMatriz(): IniciarAnimacaoAutomatica() def onTestarSolucao(self, event): pass # if self.validarParametrosMatriz(): # def onCloseDialog(self, event): # self.dbProxInstrucao.hide() # def onOpenDialog(self, event): # self.dbProxInstrucao.show() def validarParametrosTestarSolucao(): lm1 = DOM.getElementById("linha1") lm1 = lm1.value cm1 = DOM.getElementById("coluna1") cm1 = cm1.value lm2 = DOM.getElementById("linha2") lm2 = lm2.value cm2 = DOM.getElementById("coluna2") cm2 = cm2.value def validarParametrosMatriz(): lm1 = DOM.getElementById("lm1") lm1 = lm1.value cm1 = DOM.getElementById("cm1") cm1 = cm1.value lm2 = DOM.getElementById("lm2") lm2 = lm2.value cm2 = DOM.getElementById("cm2") cm2 = cm2.value if not lm1 or not lm2: Window.alert("Informe o numero de linhas da matriz M1 e M2.") return False if lm1 != lm2: Window.alert("A quantidade de linhas da matriz M1 deve ser igual a da matriz M2 para operação de soma.") return False if lm1 > "5" or lm2 > "5" or len(lm1) != 1 or len(lm2) != 1: Window.alert("A quantidade de linhas da matriz M1 e da matriz M2, deve ser menor ou igual a 5.") return False if not cm1 or not cm2: Window.alert("Informe o numero de colunas da matriz M1 e M2.") return False if cm1 != cm2: Window.alert("A quantidade de colunas da matriz M1 deve ser igual a da matriz M2 para operação de soma.") return False if cm1 > "7" or cm2 > "7" or len(cm1) != 1 or len(cm2) != 1: Window.alert("A quantidade de colunas da matriz M1 e da matriz M2, deve ser menor ou igual a 7.") return False return True def getHTML(self): return self.caption.getHTML() def getText(self): return self.caption.getText() def onEventPreview(self, event): # preventDefault on mousedown events, outside of the # dialog, to stop text-selection on dragging type = DOM.eventGetType(event) if type == "mousedown": target = DOM.eventGetTarget(event) elem = self.caption.getElement() event_targets_popup = target and DOM.isOrHasChild(elem, target) if event_targets_popup: DOM.eventPreventDefault(event) return PopupPanel.onEventPreview(self, event) def onMouseDown(self, sender, x, y): self.dragging = True DOM.setCapture(self.caption.getElement()) self.dragStartX = x self.dragStartY = y def onMouseMove(self, sender, x, y): if self.dragging: absX = x + self.getAbsoluteLeft() absY = y + self.getAbsoluteTop() self.setPopupPosition(absX - self.dragStartX, absY - self.dragStartY) def onMouseUp(self, sender, x, y): self.dragging = False DOM.releaseCapture(self.caption.getElement()) def onMouseLeave(self, self, x, y): pass def onMouseEnter(self, self, x, y): pass def remove(self, widget): if self.child != widget: return False self.panel.remove(widget) self.child = None return True def setHTML(self, html): self.caption.setHTML(html) def setText(self, text): self.caption.setText(text) def doAttachChildren(self): PopupPanel.doAttachChildren(self) self.caption.onAttach() def doDetachChildren(self): PopupPanel.doDetachChildren(self) self.caption.onDetach() def setWidget(self, widget): if self.child is not None: self.panel.remove(self.child) if widget is not None: self.panel.setWidget(1, 0, widget) self.child = widget
def drawGrid(self, month, year): # draw the grid in the middle of the calendar self.checkLinks(month, year) daysInMonth = self.getDaysInMonth(month, year) # first day of the month & year secs = time.mktime((year, month, 1, 0, 0, 0, 0, 0, -1)) struct = time.localtime(secs) startPos = (struct.tm_wday + self.dayoffset) % 7 slots = startPos + daysInMonth - 1 rows = int(slots/7) + 1 grid = Grid(rows+1, 7, # extra row for the days in the week StyleName="calendar-grid") grid.setWidth("100%") grid.addTableListener(self) self.middlePanel.setWidget(grid) cf = grid.getCellFormatter() # # put some content into the grid cells # for i in range(7): grid.setText(0, i, self.getDaysOfWeek()[i]) cf.addStyleName(0, i, "calendar-header") # # draw cells which are empty first # day = 0 pos = 0 while pos < startPos: self._setCell(grid, 1, pos, BLANKCELL, "calendar-blank-cell") pos += 1 # now for days of the month row = 1 day = 1 col = startPos while day <= daysInMonth: if pos % 7 == 0 and day != 1: row += 1 col = pos % 7 if not self._indaterange(self.currentYear, self.currentMonth, day): self._setCell(grid, row, col, BLANKCELL, "calendar-blank-cell") day += 1 pos += 1 continue if self.currentYear == self.todayYear and \ self.currentMonth == self.todayMonth and day == self.todayDay: style = "calendar-cell-today" else: style = "calendar-day-cell" self._setCell(grid, row, col, str(day), style) day += 1 pos += 1 # # now blank lines on the last row # col += 1 while col < 7: self._setCell(grid, row, col, BLANKCELL, "calendar-blank-cell") col += 1 return grid
def __init__(self, statusSummary, sender): VerticalPanel.__init__(self, Spacing=10, StyleName='userlist-error-box') self.add(HTML("We're currently working on users you mentioned", StyleName='userlist-error-title')) self.add(HTML( """<p>Below is a summary of work already in progress, or queued, which must complete before we can run your query. Please note that Tickery is subject to Twitter's API rate limiting and general network latency, so you may need to be patient. We'll get there!</p> <p><a href=\"%s\">Here's a link</a> to this results page so you can come back to see how we're doing. You can also click %r again to see updated progress.</p>""" % (sender.resultsLink(), go.goButtonText), StyleName='userlist-error-text')) nRows = 0 underway = statusSummary['underway'] nUnderway = len(underway) queued = statusSummary['queued'] nQueued = len(queued) nCols = 4 width = 200 if nUnderway: nRows += nUnderway + 1 if nQueued: nRows += nQueued + 1 g = Grid(nRows, nCols, StyleName='users') g.setCellPadding(2) cellFormatter = g.getCellFormatter() row = 0 if nUnderway: g.setHTML(row, 0, 'Users currently being processed ') cellFormatter.setStyleName(row, 0, 'title-lhs') g.setText(row, 1, 'Name') cellFormatter.setStyleName(row, 1, 'title') g.setText(row, 2, 'Friends') cellFormatter.setStyleName(row, 2, 'title') g.setText(row, 3, '% done') cellFormatter.setStyleName(row, 3, 'title') cellFormatter.setWidth(row, 3, width) row += 1 for u, nFriends, done in underway: cellFormatter.setStyleName(row, 0, 'blank') n = utils.splitthousands(nFriends) g.setHTML(row, 1, utils.screennameToTwitterLink(u)) g.setHTML(row, 2, utils.screennameToTwitterFriendsLink(u, n)) cellFormatter.setHorizontalAlignment(row, 2, 'right') pct = '%d' % int(done * 100.0) left = Label(pct, StyleName='done', Width=int(done * width)) g.setWidget(row, 3, left) row += 1 if nQueued: g.setHTML(row, 0, 'Users queued for processing ') cellFormatter.setStyleName(row, 0, 'title-lhs') g.setText(row, 1, 'Name') cellFormatter.setStyleName(row, 1, 'title') g.setText(row, 2, 'Friends') cellFormatter.setStyleName(row, 2, 'title') g.setText(row, 3, 'Queue position') cellFormatter.setStyleName(row, 3, 'title') row += 1 for u, nFriends, pos in queued: cellFormatter.setStyleName(row, 0, 'blank') n = utils.splitthousands(nFriends) g.setHTML(row, 1, utils.screennameToTwitterLink(u)) g.setHTML(row, 2, utils.screennameToTwitterFriendsLink(u, n)) cellFormatter.setHorizontalAlignment(row, 2, 'right') g.setText(row, 3, pos) cellFormatter.setHorizontalAlignment(row, 3, 'right') row += 1 self.add(g)
class InputBox(FocusPanel): _props = [ ("maxLength", "Max Length", "MaxLength", int), ("text", "Text", "Text", None), ("matchPattern", "Match Pattern", "MatchPattern", None), ("cursorStyle", "Cursor Style", "CursorStyle", None), ] @classmethod def _getProps(self): return FocusPanel._getProps() + self._props def __init__(self, **kwargs): """ setMatchPattern - defaults to '' to match everything match pattern examples: '^[0-9]*$' is for digits only '^[0-9,A-Z]*$' is for digits and uppercase setMaxLength setText OB """ kwargs['MatchPattern'] = kwargs.pop('MatchPattern', '') cs = kwargs.pop('CursorStyle', "inputbox-cursor") gs = kwargs.pop('StyleName', 'gwt-inputbox') ap = AbsolutePanel(StyleName="inputbox") self.tp = Grid(StyleName=gs, Width="100%", Height="100%", CellPadding=0, CellSpacing=0) self.cursor = HTML(StyleName=cs) ap.add(self.tp) ap.add(self.cursor, 0, 0) self.cf = self.tp.getCellFormatter() FocusPanel.__init__(self, Widget=ap, **kwargs) self.addTableListener(self) self.addKeyboardListener(self) self.addFocusListener(self) self.word_selected_pos = 0 self.ctimer = Timer(notify=self.cursorFlash) self.focusset = False self.cstate = False self._keypressListeners = [] def addKeypressListener(self, listener): self._keypressListeners.append(listener) def removeKeypressListener(self, listener): self._keypressListeners.remove(listener) def getMatchPattern(self): return self.mp def setMatchPattern(self, mp): self.mp = mp self.rexp = re.compile(self.mp) def addDblTableListener(self, listener): self.tp.addDblTableListener(listener) def addTableListener(self, listener): self.tp.addTableListener(listener) def _move_cursor(self, col): """ moves the css-styled cursor """ #old style (useful for insert mode - don't delete this line for now!) #self.cf.setStyleName(0, col, "inputbox-square-word-cursor", highlight) el = self.cf.getRawElement(0, col+1) w = self.getWidget() px = self.tp.getAbsoluteLeft() py = self.tp.getAbsoluteTop() width = DOM.getOffsetWidth(el) px = DOM.getAbsoluteLeft(el) - px py = DOM.getAbsoluteTop(el) - py w.setWidgetPosition(self.cursor, px, py) def _highlight_cursor(self, col, highlight): """ highlights (or dehighlights) the currently selected cell """ #old style (useful for insert mode - don't delete this line for now!) #self.cf.setStyleName(0, col, "inputbox-square-word-cursor", highlight) print "_highlight", col, highlight self._move_cursor(col) self.cursor.setStyleName("inputbox-square-word-cursor", highlight) def set_grid_value(self, v, y, x): if v: w = "" else: w = "0px" v = v or EMPTY s = HTML(v, StyleName="inputbox-square") self.tp.setWidget(y, x, s) self.cf.setAlignment(y, x, HasAlignment.ALIGN_LEFT, HasAlignment.ALIGN_MIDDLE) self.cf.setWidth(y, x, w) s.setWidth(w) def onKeyDown(self, sender, keycode, modifiers): evt = DOM.eventGetCurrentEvent() DOM.eventPreventDefault(evt) if self.word_selected_pos is None: return val = chr(keycode) done = False if keycode == KeyboardListener.KEY_DELETE: self.shift_letters_back() done = True elif keycode == KeyboardListener.KEY_BACKSPACE: if not self.nasty_hack(): if self.moveCursor(-1): self.shift_letters_back() done = True elif keycode == KeyboardListener.KEY_LEFT: self.moveCursor(-1) done = True elif keycode == KeyboardListener.KEY_RIGHT: self.moveCursor(1) done = True print "onKeyDown", keycode, val, self.rexp.match(val) if not done: if self.rexp.match(val): self.press_letter(val) for listener in self._keypressListeners: listener.onKeyPressed(sender, keycode, modifiers) def press_letter(self, val): print "press letter", val # check the key is a letter, and there's a grid position highlighted if self.word_selected_pos is None: return row = 0 col = self.word_selected_pos self.highlight_cursor(False) self.set_grid_value(val, row, col) self.moveCursor(1) def nasty_hack(self): """ breaking of backspace/delete rules for the final character """ row = 0 col = self.word_selected_pos txt = self.get_char(col) if txt is None or txt == EMPTY: return False self.set_grid_value(EMPTY, row, col) return True def shift_letters_back(self): """ this function is used by del and backspace, to move the letters backwards from after the cursor. the only difference between backspace and delete is that backspace moves the cursor and _then_ does letter-moving. """ self.highlight_cursor(False) row = 0 col = self.word_selected_pos x2 = self.tp.getColumnCount()-2 while (x2 != col): txt = self.get_char(col+1) self.set_grid_value(txt, row, col) col += 1 self.set_grid_value(EMPTY, row, col) def setCursorPos(self, col): x2 = self.tp.getColumnCount()-1 col = min(x2, col) col = max(col, 0) if self.get_char(0) is None or self.get_char(0) == EMPTY: col = 0 while (self.get_char(col-1) is None or \ self.get_char(col-1) == EMPTY) and col > 1: col -= 1 self._move_cursor(col) self.highlight_cursor(False) self.word_selected_pos = col self.highlight_cursor(self.focusset) return True def getCursorPos(self): return self.word_selected_pos def moveCursor(self, dirn): x2 = self.tp.getColumnCount()-1 row = 0 col = self.word_selected_pos if dirn == 1 and x2 == col+1: return False if dirn == -1 and 0 == col+1: return False return self.setCursorPos(col+dirn) def onKeyUp(self, sender, keycode, modifiers): evt = DOM.eventGetCurrentEvent() DOM.eventCancelBubble(evt, True) DOM.eventPreventDefault(evt) def onKeyPress(self, sender, keycode, modifiers): evt = DOM.eventGetCurrentEvent() DOM.eventPreventDefault(evt) def highlight_cursor(self, highlight): """ highlights (or dehighlights) the currently selected cell """ if self.word_selected_pos is None: return col = self.word_selected_pos self._highlight_cursor(col, highlight) def getMaxLength(self): return self.tp.getColumnCount()-1 def setMaxLength(self, x): l = max(0, self.tp.getColumnCount()-1) self.tp.resize(1, x+1) self.clear(l) def clear(self, fromrange=0): for i in range(fromrange, self.tp.getColumnCount()): self.set_grid_value(EMPTY, 0, i) self.cf.setWidth(0, self.tp.getColumnCount()-1, "100%") def onCellClicked(self, listener, row, col, direction=None): self.setCursorPos(col) def cursorFlash(self, timr): if not self.focusset: return self.highlight_cursor(self.cstate) self.cstate = not self.cstate def onFocus(self, sender): print "onFocus", sender self.focusset = True self.ctimer.scheduleRepeating(800) def onLostFocus(self, sender): print "onLostFocus", sender self.focusset = False self.ctimer.cancel() self.highlight_cursor(False) def get_char(self, x): w = self.tp.getWidget(0, x) return w and w.getHTML() def getText(self): txt = '' for i in range(self.tp.getColumnCount()-1): c = self.get_char(i) if c is None or c == EMPTY: break txt += c return txt def setText(self, txt): self.highlight_cursor(False) self.clear() txt = txt[:self.getMaxLength()] for (i, c) in enumerate(txt): self.set_grid_value(c, 0, i) self.setCursorPos(min(self.getMaxLength()-1, len(txt)))