class GridEdit: def onModuleLoad(self): self.input = TextBox() self.input.setEnabled(False) self.input.addKeyboardListener(self) self.g=Grid() self.g.resize(5, 5) self.g.setHTML(0, 0, "<b>Grid Edit</b>") self.g.setBorderWidth(2) self.g.setCellPadding(4) self.g.setCellSpacing(1) self.g.setWidth("500px") self.g.setHeight("120px") self.g.addTableListener(self) self.initGrid() RootPanel().add(self.input) RootPanel().add(self.g) def onKeyDown(self, sender, keycode, modifiers): pass def onKeyUp(self, sender, keycode, modifiers): pass def onKeyPress(self, sender, keycode, modifiers): if keycode == KeyboardListener.KEY_ESCAPE: self.input.setEnabled(False) elif keycode == KeyboardListener.KEY_ENTER: self.input.setEnabled(False) val = self.input.getText() self.set_grid_value(self.row, self.col, val) def onCellClicked(self, sender, row, col): self.row = row self.col = col val = self.values[row][col] self.input.setText(val) self.input.setEnabled(True) self.input.setFocus(True) def set_grid_value(self, row, col, val): self.values[row][col] = val if val == "": val = " " self.g.setHTML(row, col, val) def initGrid(self): self.values = {} for y in range(5): self.values[y] = {} for x in range(5): self.values[y][x] = "" for y in range(5): for x in range(5): val = self.values[y][x] self.set_grid_value(y, x, val)
class GridWidget(AbsolutePanel): def __init__(self): AbsolutePanel.__init__(self) self.page=0 self.min_page=1 self.max_page=10 self.addb=Button("Next >", self) self.subb=Button("< Prev", self) self.clearb=Button("Clear", self) self.g=Grid() self.g.resize(5, 5) self.g.setWidget(0, 0, HTML("<b>Grid Test</b>")) self.g.setBorderWidth(2) self.g.setCellPadding(4) self.g.setCellSpacing(1) self.updatePageDisplay() self.add(self.subb) self.add(self.addb) self.add(self.clearb) self.add(self.g) def onClick(self, sender): if sender == self.clearb: print "clear" self.g.clear() return elif sender==self.addb: self.page+=1 elif sender==self.subb: self.page-=1 self.updatePageDisplay() def updatePageDisplay(self): if self.page<self.min_page: self.page=self.min_page elif self.page>self.max_page: self.page=self.max_page total_pages=(self.max_page-self.min_page) + 1 self.g.setHTML(0, 4, "<b>page %d of %d</b>" % (self.page, total_pages)) if self.page>=self.max_page: self.addb.setEnabled(False) else: self.addb.setEnabled(True) if self.page<=self.min_page: self.subb.setEnabled(False) else: self.subb.setEnabled(True) for y in range(1, 5): for x in range(5): self.g.setText(y, x, "%d (%d,%d)" % (self.page, x, y))
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()
def __init__(self): SimplePanel.__init__(self) grid = Grid(5, 5, BorderWidth=2, CellPadding=4, CellSpacing=1) grid.setHTML(0, 0, '<b>Hello, World!</b>') for row in range(1, 5): for col in range(1, 5): grid.setText( row, col, str(row) + "*" + str(col) + " = " + str(row * col)) self.add(grid)
def __init__(self): SimplePanel.__init__(self) grid = Grid(5, 5, BorderWidth=2, CellPadding=4, CellSpacing=1) grid.setHTML(0, 0, '<b>Hello, World!</b>') for row in range(1, 5): for col in range(1, 5): grid.setText(row, col, str(row) + "*" + str(col) + " = " + str(row*col)) self.add(grid)
class DbTest(): def __init__(self): self.tb = TextBox() self.b = Button("add") self.g = Grid() self.g.resize(4, 2) RootPanel().add(HTML("Add Phrase. Press Button.")) RootPanel().add(self.tb) RootPanel().add(self.b) RootPanel().add(self.g) self.b.addClickListener(self) try: self.db = Factory.createDatabase() self.db.open('database-demo') self.db.execute('create table if not exists Demo' + ' (Phrase varchar(255), Timestamp int)') except: alert( "Could not create database.\nDo you have the google gears extension installed?" ) def onClick(self, sender): phrase = self.tb.getText() currTime = time() self.db.execute('insert into Demo values (?, ?)', phrase, currTime) rs = self.db.execute('select * from Demo order by Timestamp desc') index = 0 while rs.isValidRow(): if index < 4: self.g.setHTML(index, 0, rs.field(0)) self.g.setHTML(index, 1, rs.field(1)) else: self.db.execute('delete from Demo where Timestamp=?', rs.field(1)) index += 1 rs.next() rs.close()
class DbTest(): def __init__(self): self.tb = TextBox() self.b = Button("add") self.g = Grid() self.g.resize(4, 2) RootPanel().add(HTML("Add Phrase. Press Button.")) RootPanel().add(self.tb) RootPanel().add(self.b) RootPanel().add(self.g) self.b.addClickListener(self) try: self.db = Factory.createDatabase() self.db.open('database-demo') self.db.execute('create table if not exists Demo' + ' (Phrase varchar(255), Timestamp int)') except ex: log("could not create database" + str(ex)) def onClick(self, sender): phrase = self.tb.getText() currTime = time() self.db.execute('insert into Demo values (?, ?)', phrase, currTime); rs = self.db.execute('select * from Demo order by Timestamp desc'); index = 0 while rs.isValidRow(): if index <4: self.g.setHTML(index, 0, rs.field(0)) self.g.setHTML(index, 1, rs.field(1)) else: self.db.execute('delete from Demo where Timestamp=?', rs.field(1)); index += 1 rs.next() rs.close()
def onRemoteResponse(self, response, request_info): method = request_info.method if method == 'get_documents': grid = Grid() grid.resize(len(response) + 1, 8) grid.setHTML(0, 0, "Comment") grid.setHTML(0, 1, "Episode") grid.setHTML(0, 2, "When") for (row, item) in enumerate(response): grid.setHTML(row + 1, 0, item.comment) grid.setHTML(row + 1, 1, item.episode) grid.setHTML(row + 1, 2, str(item.clin_when)) #RootPanel().add(grid) self.add(grid) else: self.status.setText(str(response))
def onRemoteResponse(self, response, request_info): method = request_info.method if method == 'get_documents': grid = Grid() grid.resize(len(response)+1, 8) grid.setHTML(0, 0, "Comment") grid.setHTML(0, 1, "Episode") grid.setHTML(0, 2, "When") for (row, item) in enumerate(response): grid.setHTML(row+1, 0, item.comment) grid.setHTML(row+1, 1, item.episode) grid.setHTML(row+1, 2, str(item.clin_when)) #RootPanel().add(grid) self.add(grid) else: self.status.setText(str(response))
def htmlElements(self, addList = None): if not self._htmlElements: h = HTML("<h1>Hello from %s</h1>" % location.getHref(), StyleName='font-s07em') p = HorizontalPanel(HTML('Valid/tested combinations')) grid = Grid(2,2) grid.setHTML(0, 0, "app") grid.setHTML(0, 1, "themes") grid.setHTML(1, 0, "a") grid.setHTML(1, 1, "0 - 1 - ff0000 - cms - pypress - wordpress") self._htmlElements = [['h', h], ['p', p], ['grid', grid]] for i in range(len(self._htmlElements)): RootPanel().add(self._htmlElements[i][1]) if addList: self._htmlElements+=addList for i in range(len(self._htmlElements)): RootPanel().add(addList[i][1]) return self._htmlElements
class Form(FormPanel): def __init__(self, svc, **kwargs): self.describe_listeners = [] if kwargs.has_key('listener'): listener = kwargs.pop('listener') self.addDescribeListener(listener) if kwargs.has_key('data'): data = kwargs.pop('data') else: data = None writebr(repr(data)) FormPanel.__init__(self, **kwargs) self.svc = svc self.grid = Grid() self.grid.resize(0, 3) self.add(self.grid) self.describer = FormDescribeGrid(self) self.saver = FormSaveGrid(self) self.getter = FormGetGrid(self) self.formsetup(data) def addDescribeListener(self, l): self.describe_listeners.append(l) def add_widget(self, description, widget): """ adds a widget, with error rows interspersed """ num_rows = self.grid.getRowCount() self.grid.resize((num_rows + 1), 3) self.grid.setHTML(num_rows, 0, description) self.grid.setWidget(num_rows, 1, widget) def get(self, **kwargs): writebr(repr(kwargs)) self.svc({}, {'get': kwargs}, self.getter) def save(self, data=None): self.clear_errors() if data is None: data = self.getValue() self.data = data writebr(repr(self.data)) self.svc(data, {'save': None}, self.saver) def save_respond(self, response): if not response['success']: errors = response['errors'] self.set_errors(errors) for l in self.describe_listeners: l.onErrors(self, errors) return for l in self.describe_listeners: l.onSaveDone(self, response) def formsetup(self, data=None): if data is None: data = {} self.data = data writebr(repr(self.data)) self.svc(data, {'describe': None}, self.describer) def clear_errors(self): for idx, fname in enumerate(self.fields): self.grid.setHTML(idx, 2, None) def set_errors(self, errors): offsets = {} for idx, fname in enumerate(self.fields): offsets[fname] = idx for k, err in errors.items(): err = "<br />".join(err) idx = offsets[k] self.grid.setHTML(idx, 2, err) def update_values(self, data=None): if data is not None: self.data = data for idx, fname in enumerate(self.fields): val = None if self.data.has_key(fname): val = self.data[fname] w = self.grid.getWidget(idx, 1) w.setValue(val) def do_get(self, response): fields = response.get('instance', None) if fields: self.update_values(fields) for l in self.describe_listeners: l.onRetrieveDone(self, fields) def do_describe(self, fields): self.fields = fields.keys() for idx, fname in enumerate(self.fields): field = fields[fname] if self.data and self.data.has_key(fname): field['initial'] = self.data[fname] writebr("%s %s %d" % (fname, field['label'], idx)) field_type = field['type'] widget_kls = widget_factory.get(field_type, CharField) fv = {} for (k, v) in field.items(): fv[str(k)] = v w = widget_kls(**fv) self.add_widget(field['label'], w) for l in self.describe_listeners: l.onDescribeDone(self) def getValue(self): res = {} for idx, fname in enumerate(self.fields): w = self.grid.getWidget(idx, 1) val = w.getValue() res[fname] = val self.data[fname] = val return res
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 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
class Form(FormPanel): def __init__(self, svc, **kwargs): self.describe_listeners = [] if kwargs.has_key('listener'): listener = kwargs.pop('listener') self.addDescribeListener(listener) if kwargs.has_key('data'): data = kwargs.pop('data') else: data = None FormPanel.__init__(self, **kwargs) self.svc = svc self.grid = Grid() self.grid.resize(0, 3) self.add(self.grid) self.describer = FormDescribeGrid(self) self.saver = FormSaveGrid(self) self.getter = FormGetGrid(self) self.formsetup(data) def addDescribeListener(self, l): self.describe_listeners.append(l) def add_widget(self, description, widget): """ adds a widget, with error rows interspersed """ num_rows = self.grid.getRowCount() self.grid.resize((num_rows+1), 3) self.grid.setHTML(num_rows, 0, description) self.grid.setWidget(num_rows, 1, widget) def get(self, **kwargs): writebr(repr(kwargs)) self.svc({}, {'get': kwargs}, self.getter) def save(self, data=None): self.clear_errors() if data is None: data = self.getValue() self.data = data writebr(repr(self.data)) self.svc(data, {'save': None}, self.saver) def save_respond(self, response): if not response['success']: errors = response['errors'] self.set_errors(errors) for l in self.describe_listeners: l.onErrors(self, errors) return for l in self.describe_listeners: l.onSaveDone(self, response) def formsetup(self, data=None): if data is None: data = {} self.data = data self.svc(data, {'describe': None}, self.describer) def clear_errors(self): for idx, fname in enumerate(self.fields): self.grid.setHTML(idx, 2, None) def set_errors(self, errors): offsets = {} for idx, fname in enumerate(self.fields): offsets[fname] = idx for k, err in errors.items(): err = "<br />".join(err) idx = offsets[k] self.grid.setHTML(idx, 2, err) def update_values(self, data = None): if data is not None: self.data = data for idx, fname in enumerate(self.fields): val = None if self.data.has_key(fname): val = self.data[fname] w = self.grid.getWidget(idx, 1) w.setValue(val) def do_get(self, response): fields = response.get('instance', None) if fields: self.update_values(fields) for l in self.describe_listeners: l.onRetrieveDone(self, fields) def do_describe(self, fields): self.fields = fields.keys() for idx, fname in enumerate(self.fields): field = fields[fname] if self.data and self.data.has_key(fname): field['initial'] = self.data[fname] field_type = field['type'] widget_kls = widget_factory.get(field_type, CharField) fv = {} for (k, v) in field.items(): fv[str(k)] = v w = widget_kls(**fv) self.add_widget(field['label'], w) for l in self.describe_listeners: l.onDescribeDone(self) def getValue(self): res = {} for idx, fname in enumerate(self.fields): w = self.grid.getWidget(idx, 1) val = w.getValue() res[fname] = val self.data[fname] = val return res
class Viewer: def __init__(self, db_url, parent_panel, doc_callback=None, page_size=5): self.db_url = db_url self.parent_panel = parent_panel self.doc_callback = doc_callback self.page_size = page_size def onModuleLoad(self): ## Grid setup self.grid = Grid() # Note: The resize method args are Rows,Cols (Curses style) self.grid.resize(1,4) self.grid.setBorderWidth(1) self.grid.setHTML(0,0,'#') self.grid.setHTML(0,1,'ID') self.grid.setHTML(0,2,'Revision') self.grid.setHTML(0,3,'Delete') self.grid.addTableListener(self) self.parent_panel.add(self.grid) ## Buttons self.button_panel = HorizontalPanel() # Prev self.first_button = Button("<-", self.firstPage) self.first_button.setEnabled(False) self.button_panel.add(self.first_button) self.prev_button = Button("Previous", self.prevPage) self.prev_button.setEnabled(False) self.button_panel.add(self.prev_button) self.next_button = Button("Next", self.nextPage) self.next_button.setEnabled(False) self.button_panel.add(self.next_button) self.parent_panel.add(self.button_panel) def populate(self, json): view_obj = JSONParser().decode(json) view_rows = view_obj['rows'] offset = view_obj['offset'] num_rows = len(view_rows) self.first_key = view_rows[0]['key'] if offset != 0: self.first_button.setEnabled(True) if num_rows > self.page_size: self.next_key = view_rows[-1:][0]['key'] self.next_button.setEnabled(True) self.grid.resize(self.page_size+1,4) else: self.grid.resize(num_rows+1,4) for row_num in range(num_rows): if row_num < self.page_size: self.grid.setHTML(row_num+1, 0, 1+offset+row_num) self.grid.setHTML(row_num+1, 1, view_rows[row_num]['key']) self.grid.setHTML(row_num+1, 2, view_rows[row_num]['value']['rev']) self.grid.setHTML(row_num+1, 3, '<b>X O X</b>') if len(self.prev_keys)>0: self.prev_button.setEnabled(True) def onCellClicked(self, sender, row, col): doc_id = self.grid.getHTML(row, 1) if col == 3: doc_rev = self.grid.getHTML(row, 2) url = self.db_url+doc_id+'?rev='+doc_rev HTTPRequest().asyncDelete(None, None, url=url, handler=DeleteHandler(self)) else: if self.doc_callback is not None: self.doc_callback(doc_id) def firstPage(self): self.loadPage(None) def nextPage(self): self.prev_keys.append(self.first_key) self.loadPage(self.next_key) def prevPage(self): self.loadPage(self.prev_keys.pop()) def setView(self, view_path, first_key = None): self.view_path = view_path #self.prev_keys = [] #self.next_key = None self.loadPage(first_key) def loadPage(self, startkey=None): limit = int(self.page_size)+1 view_url = self.db_url+self.view_path+'?limit=%d'%limit if startkey is not None: view_url += '&startkey="%s"'%startkey else: self.prev_keys = [] self.first_button.setEnabled(False) self.next_button.setEnabled(False) self.prev_button.setEnabled(False) HTTPRequest().asyncGet(None, None, url=view_url, handler=ViewLoader(self))