class PreferencesDlg(DialogBox): fileLocation = None def __init__(self, left = 50, top = 50): DialogBox.__init__(self, modal = False) self.setPopupPosition(left, top) self.setText("Preferences") ftable = FlexTable() ftableFormatter = ftable.getFlexCellFormatter() row = 0 self.fileLocation = getCookie("fileLocation") row += 1 ftable.setWidget(row, 0, Label("Sheet loaded on startup", wordWrap=False)) self.fileLocationInput = TextBox() self.fileLocationInput.addChangeListener(self.checkValid) self.fileLocationInput.addKeyboardListener(self) self.fileLocationInput.setVisibleLength(30) self.fileLocationInput.setText(self.fileLocation) ftable.setWidget(row, 1, self.fileLocationInput) row += 1 hpanel = HorizontalPanel() self.saveBtn = Button("Save", self.onSave) self.saveBtn.setEnabled(False) hpanel.add(self.saveBtn) self.cancelBtn = Button("Cancel", self.onCancel) hpanel.add(self.cancelBtn) ftable.setWidget(row, 0, hpanel) ftableFormatter.setColSpan(row, 0, 2) self.setWidget(ftable) def onCancel(self, sender): self.hide() def onSave(self, sender): setCookie("fileLocation", self.fileLocationInput.getText(), 1000000000) self.hide() def checkValid(self, evt=None): if self.fileLocation != self.fileLocationInput.getText(): self.saveBtn.setEnabled(True) else: self.saveBtn.setEnabled(False) def onClick(self, sender): pass def onKeyUp(self, sender, keyCode, modifiers): self.checkValid() def onKeyDown(self, sender, keyCode, modifiers): pass def onKeyPress(self, sender, keyCode, modifiers): pass
class TestRect: def onModuleLoad(self): self.r = Rect(0.0, 0.0) self.xbox = TextBox() self.ybox = TextBox() self.addbutton = Button("Click to add x and y to Rectangle") self.addbutton.addClickListener(self) self.xbox.setText("2") self.ybox.setText("5") RootPanel().add(HTML("X Value:")) RootPanel().add(self.xbox) RootPanel().add(HTML("Y Value:")) RootPanel().add(self.ybox) RootPanel().add(self.addbutton) RootPanel().add(HTML("Current value: %d %d" % ( self.r.get_x(), self.r.get_y()))) def onClick(self, sender): x = int(self.xbox.getText()) y = int(self.ybox.getText()) r = Rect(x, y) self.r.add(r) RootPanel().add(HTML("New value: %d" % ( self.r.get_x()))) RootPanel().add(HTML("New value: %d" % ( self.r.get_y()))) RootPanel().add(HTML("New value: %d %d" % ( self.r.get_x(), self.r.get_y()))) RootPanel().add(HTML("New Area: %d" % self.r.area()))
class Email(Composite): def __init__(self, **kwargs): element = None if kwargs.has_key('Element'): element = kwargs.pop('Element') panel = VerticalPanel(Element=element) Composite.__init__(self, panel, **kwargs) self.TEXT_WAITING = "Please wait..." self.TEXT_ERROR = "Server Error" self.remote_py = EchoServicePython() self.status = Label() self.subject = TextBox() self.subject.setVisibleLength(60) self.sender = TextBox() self.sender.setVisibleLength(40) self.message = TextArea() self.message.setCharacterWidth(60) self.message.setVisibleLines(15) self.button_py = Button("Send", self) buttons = HorizontalPanel() buttons.add(self.button_py) buttons.setSpacing(8) panel.add(HTML("Subject:")) panel.add(self.subject) panel.add(HTML("From:")) panel.add(self.sender) panel.add( HTML("Your Message - please keep it to under 1,000 characters")) panel.add(self.message) panel.add(buttons) panel.add(self.status) def onClick(self, sender): self.status.setText(self.TEXT_WAITING) text = self.message.getText() msg_sender = self.sender.getText() msg_subject = self.subject.getText() # demonstrate proxy & callMethod() if sender == self.button_py: id = self.remote_py.send(msg_sender, msg_subject, text, self) if id < 0: self.status.setText(self.TEXT_ERROR) def onRemoteResponse(self, response, request_info): self.status.setText(response) def onRemoteError(self, code, message, request_info): self.status.setText("Server Error or Invalid Response: ERROR " + \ str(code) + " - " + str(message))
class LoginDialgoBox(DialogBox,RPCBase): def __init__(self, app): DialogBox.__init__(self) self.app = app self.table=FlexTable() self.table.setText(0, 0, "Please enter username and password") self.table.getFlexCellFormatter().setColSpan(0, 0, 2) self.table.setText(1, 0, "Username") self.handle = TextBox() h = getCookie('handle') self.handle.setText(h) self.table.setWidget(1, 1, self.handle) self.table.setText(2, 0, "Password") self.pwd = PasswordTextBox() self.table.setWidget(2, 1, self.pwd) self.table.setHTML(3,0,"") self.table.getFlexCellFormatter().setColSpan(3, 0, 2) h = HorizontalPanel() self.table.setWidget(4,0, h) self.table.getFlexCellFormatter().setColSpan(4, 0, 2) h.add(Button("Ok", getattr(self, "onOk"))) h.add(Button("Cancel", getattr(self, "onClose"))) h.setSpacing(4) self.setHTML("<b>Login</b>") self.setWidget(self.table) left = (Window.getClientWidth() - 200) / 2 top = (Window.getClientHeight() - 100) / 2 self.setPopupPosition(left,top) def onRemoteResponse(self, response, request_info): if response == "invalid_cookie": self.show() elif response == None or len(response) < 3: self.table.setHTML(3,0,"<b>Invalid username or password</b>") else: self.app.cookie = response[0] setCookie('cookie',response[0],1000*60*60*24) self.hide() self.app.logininit(response[1],response[2]) def onClose(self,env): Window.getLocation().setHref("http://www.google.com") def onOk(self, env): global gw setCookie('handle',self.handle.getText(),24*60*60*1000) x = self.pwd.getText() x = pwhash(x) gw.login(self.handle.getText(), x, self) def login(self): global gw if not self.app.cookie: self.show() else: gw.validateCookie(self.app.cookie, self)
class Email(Composite): def __init__(self, **kwargs): element = None if kwargs.has_key('Element'): element = kwargs.pop('Element') panel = VerticalPanel(Element=element) Composite.__init__(self, panel, **kwargs) self.TEXT_WAITING = "Please wait..." self.TEXT_ERROR = "Server Error" self.remote_py = EchoServicePython() self.status=Label() self.subject = TextBox() self.subject.setVisibleLength(60) self.sender = TextBox() self.sender.setVisibleLength(40) self.message = TextArea() self.message.setCharacterWidth(60) self.message.setVisibleLines(15) self.button_py = Button("Send", self) buttons = HorizontalPanel() buttons.add(self.button_py) buttons.setSpacing(8) panel.add(HTML("Subject:")) panel.add(self.subject) panel.add(HTML("From:")) panel.add(self.sender) panel.add(HTML("Your Message - please keep it to under 1,000 characters")) panel.add(self.message) panel.add(buttons) panel.add(self.status) def onClick(self, sender): self.status.setText(self.TEXT_WAITING) text = self.message.getText() msg_sender = self.sender.getText() msg_subject = self.subject.getText() # demonstrate proxy & callMethod() if sender == self.button_py: id = self.remote_py.send(msg_sender, msg_subject, text, self) if id<0: self.status.setText(self.TEXT_ERROR) def onRemoteResponse(self, response, request_info): self.status.setText(response) def onRemoteError(self, code, message, request_info): self.status.setText("Server Error or Invalid Response: ERROR " + \ str(code) + " - " + str(message))
class BooleanArgument(Argument): def __init__(self): Argument.__init__(self, [Block.BOOLEAN_BLOCK]) self.height = 20 self.width = 15 drawBooleanArgument(self) self.addInput() self.resize() def addInput(self): self.input = TextBox() self.input.setWidth(20) self.input.addInputListener(self) self.append(self.input) DOM.setBooleanAttribute(self.input.getElement(), "readOnly", True) self.input.addChangeListener(self) def onChange(self, sender): from edu.uca.util.Serializable import stateChange stateChange() def onInput(self, sender): if len(self.input.getText()) == 0: self.input.setWidth( 20) # nao esta usando pois nao pode digitar no input bool else: self.input.setWidth(20 + ((len(self.input.getText()) - 1) * 7)) self.width = self.input.getWidth() self.resize() def resize(self): c = math.ceil(self.height / 2 + 1) self.tr.setStyleAttribute({ 'right': -c - 2, 'width': c + 3, 'height': c }) self.br.setStyleAttribute({ 'right': -c - 2, 'width': c + 3, 'height': c }) self.tl.setStyleAttribute({ 'left': -c - 2, 'width': c + 3, 'height': c }) self.bl.setStyleAttribute({ 'left': -c - 2, 'width': c + 3, 'height': c }) self.setStyleAttribute({'width': self.width}) self.t.setWidth(self.width) self.b.setWidth(self.width)
class PopupNewVar(Popup): def __init__(self, okClick, cancelClick): Popup.__init__(self, '<b>Nova Variável</b>', okClick, cancelClick, CONFIRM_CANCEL) def draw(self): Popup.draw(self) namePanel = HorizontalPanel() namePanel.add(Label(_('Name') + ':')) self.textBox = TextBox() self.textBox.setMaxLength(15) self.textBox.setStyleAttribute('marginLeft', 10) namePanel.add(self.textBox) self.center.add(namePanel) self.choose = ChooseTypeVarPanel() self.center.add(self.choose) self.textBox.addInputListener(self) self.message = Element(Element=DOM.createDiv()) self.message.add(Widget(Element=DOM.createDiv(), StyleName='not_image')) self.message.add( Label(text=_('Name already used'), wordWrap=False, StyleName='not_message')) self.onInput() def onInput(self, sender): if self.textBox.getText().count(' ') == len(self.textBox.getText()): self.okButton.addStyleName('disabled') self.south.remove(self.message) elif self.textBox.getText() in vars or self.textBox.getText( ) in createdBlocks: self.okButton.addStyleName('disabled') self.south.add(self.message) else: self.okButton.removeStyleName('disabled') self.south.remove(self.message) def myOkClick(self): if 'disabled' not in self.okButton.getStyleName(): Popup.myOkClick(self) self.okClick(self.textBox.getText(), self.choose.selectedType) def myCancelClick(self): Popup.myCancelClick(self) if self.cancelClick is not None: self.cancelClick() def show(self): Popup.show(self) self.textBox.setFocus(True)
class CalibrateChannelTrimsView(object) : """ Class that takes care of the purely UI parts of the trim calibration """ def __init__( self ) : numberOfLoopsPanel=HorizontalPanel() numberOfLoopsPanel.add( HTML("Maximum number of loops") ) self.maximumNumberOfLoops=TextBox() self.maximumNumberOfLoops.setText(10) numberOfLoopsPanel.add( self.maximumNumberOfLoops ) numberOfLoopsPanel.setCellHorizontalAlignment( self.maximumNumberOfLoops, HasHorizontalAlignment.ALIGN_RIGHT ) numberOfLoopsPanel.setWidth("100%") aimPointPanel=HorizontalPanel() aimPointPanel.add( HTML("Aim point") ) self.aimPoint=TextBox() self.aimPoint.setText(127) aimPointPanel.add( self.aimPoint ) aimPointPanel.setCellHorizontalAlignment( self.aimPoint, HasHorizontalAlignment.ALIGN_RIGHT ) aimPointPanel.setWidth("100%") self.start=Button("Start") self.echo=HTML("Initiating...") self.mainPanel = VerticalPanel() self.mainPanel.add( numberOfLoopsPanel ) self.mainPanel.add( aimPointPanel ) self.mainPanel.add( self.start ) self.mainPanel.add( self.echo ) def getMaxNumberOfLoops( self ) : return int(self.maximumNumberOfLoops.getText()) def getAimPoint( self ) : return int(self.aimPoint.getText()) def getStartButton( self ) : return self.start def setEchoText( self, text ) : self.echo.setText( text ) def enable( self ) : self.start.setEnabled(True) def disable( self ) : self.start.setEnabled(False) def getPanel( self ) : return self.mainPanel
class TestDict: def onModuleLoad(self): self.r = WrapperDict() self.kbox = TextBox() self.addbutton = Button( "Click to look up key value (hello or goodbye)") self.addbutton.addClickListener(self) self.kbox.setText("hello") # default to make life easier RootPanel().add(HTML("Key:")) RootPanel().add(self.kbox) RootPanel().add(self.addbutton) def display_value(self): key = self.kbox.getText() RootPanel().add(HTML("Value using python:")) RootPanel().add(HTML(self.r.python_get_value(key))) RootPanel().add(HTML("Value using javascript:")) RootPanel().add(HTML(self.r.javascript_get_value(key))) def onClick(self, sender): self.display_value()
class TestDict: def onModuleLoad(self): self.r = WrapperDict() self.kbox = TextBox() self.addbutton = Button("Click to look up key value (hello or goodbye)") self.addbutton.addClickListener(self) self.kbox.setText("hello") # default to make life easier RootPanel().add(HTML("Key:")) RootPanel().add(self.kbox) RootPanel().add(self.addbutton) def display_value(self): key = self.kbox.getText() RootPanel().add(HTML("Value using python:" )) RootPanel().add(HTML(self.r.python_get_value(key))) RootPanel().add(HTML("Value using javascript:" )) RootPanel().add(HTML(self.r.javascript_get_value(key))) def onClick(self, sender): self.display_value()
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 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 Cancel(HorizontalPanel): def __init__(self): HorizontalPanel.__init__(self, Spacing=4) self.add(Label('Cancel:', StyleName='section')) self.name = TextBox() self.name.setMaxLength(18) self.name.setVisibleLength(18) self.add(self.name) self.cancel = Button('Do it', self) self.add(self.cancel) self.err = Label() self.add(self.err) def onClick(self, sender): self.err.setText('') name = self.name.getText().strip() if name == '': return else: self.cancel.setEnabled(False) remote = server.AdminService() id = remote.cancel(name, self) if id < 0: self.err.setText('oops: could not cancel') def onRemoteResponse(self, result, request_info): self.cancel.setEnabled(True) self.name.setText('') def onRemoteError(self, code, message, request_info): self.cancel.setEnabled(True) self.err.setText('Could not cancel: ' + message['data']['message'])
class TextEditor(Editor): """ Base class for text style editors, which displays an editable text field, containing a text representation of the object trait value. """ # --------------------------------------------------------------------------- # Finishes initializing the editor by creating the underlying toolkit # widget: # --------------------------------------------------------------------------- def init(self, parent): """ Finishes initializing the editor by creating the underlying toolkit widget. """ self.control = TextBox() self.control.setText(self.str_value) self.control.addChangeListener(getattr(self, "update_object")) self.set_tooltip() # --------------------------------------------------------------------------- # Handles the user changing the contents of the edit control: # --------------------------------------------------------------------------- def update_object(self, sender): """ Handles the user changing the contents of the edit control. """ try: self.value = unicode(self.control.getText()) except TraitError, excp: pass
class DefinitionDialog(DialogWindow): def __init__(self, **kwargs): DialogWindow.__init__(self, modal=True, close=True) v = VerticalPanel() v.setWidth(300) # v.setHeight(500) self.setText("definition") self.setPopupPosition(100, 100) self.setStyleAttribute("background-color", "#ffffff") self.setStyleAttribute("color", "#9847a2") self.setStyleAttribute("border-width", "5px") self.setStyleAttribute("border-style", "solid") h = HorizontalPanel() self.textbox_name = TextBox() h.add(Label("name")) h.add(self.textbox_name) v.add(h) h = HorizontalPanel() self.textbox_scheme = TextBox() h.add(Label("print scheme")) h.add(self.textbox_scheme) v.add(h) self.add(v) self.theorems = list() self.radios = list() for t in Theorem.theorems: if t.formula.is_in_unique_form(): self.theorems.append(t) self.radios.append(RadioButton("group1", "")) h = HorizontalPanel() h.add(self.radios[-1]) im = Image() im.setUrl(latex_to_url(t.formula.to_latex())) h.add(im) v.add(h) v.add(Button("Done", self.done_click)) def done_click(self): for i in range(len(self.radios)): if self.radios[i].getChecked(): op = Operation(Operation.get_new_id(), self.theorems[i].formula.get_no_of_args_for_unique_form(), self.textbox_scheme.getText(), self.textbox_name.getText(), Operation.EXPRESSION) Operation.global_operations.append(op) Theorem.theorems.append(Theorem(self.theorems[i].formula.get_def_theorem(op),18,"iojo",[])) IO.save() self.hide()
class FormPanelExample: def onModuleLoad(self): # Create a FormPanel and point it at a service. self.form = FormPanel() self.form.setAction("/chat-service/test/") # Because we're going to add a FileUpload widget, we'll need to set the # form to use the POST method, and multipart MIME encoding. self.form.setEncoding(FormPanel.ENCODING_MULTIPART) self.form.setMethod(FormPanel.METHOD_POST) # Create a panel to hold all of the form widgets. panel = VerticalPanel() self.form.setWidget(panel) # Create a TextBox, giving it a name so that it will be submitted. self.tb = TextBox() self.tb.setName("textBoxFormElement") panel.add(self.tb) # Create a ListBox, giving it a name and some values to be associated with # its options. lb = ListBox() lb.setName("listBoxFormElement") lb.addItem("foo", "fooValue") lb.addItem("bar", "barValue") lb.addItem("baz", "bazValue") panel.add(lb) # Create a FileUpload widget. upload = FileUpload() upload.setName("uploadFormElement") panel.add(upload) # Add a 'submit' button. panel.add(Button("Submit", self)) # Add an event handler to the form. self.form.addFormHandler(self) RootPanel().add(self.form) def onClick(self, sender): self.form.submit() def onSubmitComplete(self, event): # When the form submission is successfully completed, this event is # fired. Assuming the service returned a response of type text/plain, # we can get the result text here (see the FormPanel documentation for # further explanation). Window.alert(event.getResults()) def onSubmit(self, event): # This event is fired just before the form is submitted. We can take # this opportunity to perform validation. if (len(self.tb.getText()) == 0): Window.alert("The text box must not be empty") event.setCancelled(True)
class FormPanelExample: def onModuleLoad(self): # Create a FormPanel and point it at a service. self.form = FormPanel() self.form.setAction("/chat-service/test/") # Because we're going to add a FileUpload widget, we'll need to set the # form to use the POST method, and multipart MIME encoding. self.form.setEncoding(FormPanel.ENCODING_MULTIPART) self.form.setMethod(FormPanel.METHOD_POST) # Create a panel to hold all of the form widgets. panel = VerticalPanel() self.form.setWidget(panel) # Create a TextBox, giving it a name so that it will be submitted. self.tb = TextBox() self.tb.setName("textBoxFormElement") panel.add(self.tb) # Create a ListBox, giving it a name and some values to be associated with # its options. lb = ListBox() lb.setName("listBoxFormElement") lb.addItem("foo", "fooValue") lb.addItem("bar", "barValue") lb.addItem("baz", "bazValue") panel.add(lb) # Create a FileUpload widget. upload = FileUpload() upload.setName("uploadFormElement") panel.add(upload) # Add a 'submit' button. panel.add(Button("Submit", self)) # Add an event handler to the form. self.form.addFormHandler(self) RootPanel().add(self.form) def onClick(self, sender): self.form.submit() def onSubmitComplete(self, event): # When the form submission is successfully completed, this event is # fired. Assuming the service returned a response of type text/plain, # we can get the result text here (see the FormPanel documentation for # further explanation). Window.alert(event.getResults()) def onSubmit(self, event): # This event is fired just before the form is submitted. We can take # this opportunity to perform validation. if self.tb.getText().length == 0: Window.alert("The text box must not be empty") event.setCancelled(True)
class AuthPanel(VerticalPanel): def __init__(self, beginVerifyAuth, onClose, baseStyleName='gwt-authdlgbox'): """Initialize a new instance. beginVerifyAuth: callable that takes (string username, string password).Should call 'endVerifyAuth' when finished. onClose: callable that takes (AuthDlgBox sender, bool wasAuthorized, string username, string password). Called when Cancel is pressed, or OK is pressed and verification is successful. baseStyleName: base css name for type. baseStyleName + -label, -textbox, and -warninglabel should also be defined. """ VerticalPanel.__init__(self, StyleName=baseStyleName) self.onClose = onClose self.wasAuthorized = False self._beginVerifyAuth = beginVerifyAuth self.baseStyleName = baseStyleName self._createContent() def _createContent(self): self.add(self._createUsernamePanel()) self.add(self._createPasswordPanel()) self.add(self._createButtonPanel()) self.warningLabel = Label('', StyleName='-warninglabel') self.add(self.warningLabel) def _createUsernamePanel(self): hp = HorizontalPanel() hp.add(Label('Username: '******'-label')) self.usernameTB = TextBox(StyleName=self.baseStyleName + '-textbox') hp.add(self.usernameTB) return hp def _createPasswordPanel(self): hp = HorizontalPanel() hp.add(Label('Password: '******'-label')) self.passTB = PasswordTextBox(StyleName=self.baseStyleName + '-textbox') hp.add(self.passTB) return hp def _createButtonPanel(self): hp = HorizontalPanel() self.okBtn = Button('OK', self.onOk, StyleName=self.baseStyleName + '-button') self.cancelBtn = Button('Cancel', self.onCancel, StyleName=self.baseStyleName + '-button') hp.add(self.okBtn) hp.add(self.cancelBtn) return hp def getUserAndPass(self): return self.usernameTB.getText(), self.passTB.getText() def onOk(self, sender): self._beginVerifyAuth(*self.getUserAndPass()) return def onCancel(self, sender): self.onClose(self, False, None, None) return def endVerifyAuth(self, result, username, password, msg='Username/password invalid.'): if result: self.onClose(self, True, username, password) else: self.warningLabel.setText(msg)
class JSONRPCExample: def onModuleLoad(self): self.TEXT_WAITING = "Waiting for response..." self.TEXT_ERROR = "Server Error" self.remote = JSONProxy("../api", ["hello"]) self.status = Label() self.text_box = TextBox() self.button_send = Button("Send", self) buttons = HorizontalPanel() buttons.add(self.button_send) buttons.setSpacing(8) info = """<h2>JSON-RPC Example</h2> <p>This example demonstrates the calling of server services with <a href="http://json-rpc.org/">JSON-RPC</a>. </p> <p>Enter your name below.</p>""" panel = VerticalPanel() panel.add(HTML(info)) panel.add(self.text_box) #panel.add(method_panel) panel.add(buttons) panel.add(self.status) RootPanel().add(panel) def onClick(self, sender): self.status.setText(self.TEXT_WAITING) text = self.text_box.getText() id = self.remote.hello(text, self) def onRemoteResponse(self, response, request_info): self.status.setText(response) def onRemoteError(self, code, errobj, request_info): # onRemoteError gets the HTTP error code or 0 and # errobj is an jsonrpc 2.0 error dict: # { # 'code': jsonrpc-error-code (integer) , # 'message': jsonrpc-error-message (string) , # 'data' : extra-error-data # } message = errobj['message'] if code != 0: self.status.setText("HTTP error %d: %s" % (code, message)) else: code = errobj['code'] self.status.setText("JSONRPC Error %s: %s" % (code, message))
class TestRect: def onModuleLoad(self): self.r = Rect(0.0, 0.0) self.xbox = TextBox() self.ybox = TextBox() self.addbutton = Button("Click to add x and y to Rectangle") self.addbutton.addClickListener(self) self.xbox.setText("2") self.ybox.setText("5") RootPanel().add(HTML("X Value:")) RootPanel().add(self.xbox) RootPanel().add(HTML("Y Value:")) RootPanel().add(self.ybox) RootPanel().add(self.addbutton) RootPanel().add( HTML("Current value: %d %d" % (self.r.get_x(), self.r.get_y()))) def onClick(self, sender): x = int(self.xbox.getText()) y = int(self.ybox.getText()) r = Rect(x, y) self.r.add(r) RootPanel().add(HTML("New value: %d" % (self.r.get_x()))) RootPanel().add(HTML("New value: %d" % (self.r.get_y()))) RootPanel().add( HTML("New value: %d %d" % (self.r.get_x(), self.r.get_y()))) RootPanel().add(HTML("New Area: %d" % self.r.area()))
class InputControl(Control): def __init__(self, min_value, max_value, start_value=None, step=None, **kwargs): if not kwargs.has_key("StyleName"): kwargs['StyleName'] = "gwt-InputControl" self.input = TextBox() self.input.addKeyboardListener(self) #element = DOM.createDiv() if kwargs.has_key('Element'): # XXX FIXME: unlikely to work! element = kwargs.pop('Element') else: element = self.input.getElement() # YUK!!! Control.__init__(self, element, min_value, max_value, start_value, step, **kwargs) self.addClickListener(self) self.addFocusListener(self) self.addKeyboardListener(self) def onFocus(self, sender): self.addStyleName("gwt-InputControl-focussed") def onLostFocus(self, sender): self.removeStyleName("gwt-InputControl-focussed") def setControlPos(self, value): self.input.setText(value) def onKeyPress(self, sender, keycode, modifiers): if keycode == KeyboardListener.KEY_ENTER: DOM.eventPreventDefault(DOM.eventGetCurrentEvent()) txt = self.input.getText() if not txt: return new_value = float(txt) new_value = self.processValue(new_value) self.setControlPos(new_value) self.setValue(new_value) else: Control.onKeyPress(self, sender, keycode, modifiers)
class SaveDialog(DialogWindow): def __init__(self, theorem, **kwargs): DialogWindow.__init__(self, modal=True, close=True) self.theorem=theorem v = VerticalPanel() v.setWidth(300) # v.setHeight(500) self.setText("save") self.setPopupPosition(100, 100) self.setStyleAttribute("background-color", "#ffffff") self.setStyleAttribute("color", "red") self.setStyleAttribute("border-width", "5px") self.setStyleAttribute("border-style", "solid") self.im=Image() self.im.setUrl(latex_to_url(self.theorem.formula.to_latex())) v.add(self.im) h=HorizontalPanel() self.radio=RadioButton("group1", "Existing folder:") h.add(self.radio) self.list = ListBox() self.list.setVisibleItemCount(1) for f in Theorem.get_all_folders(): self.list.addItem(f) h.add(self.list) v.add(h) h=HorizontalPanel() h.add(RadioButton("group1", "New folder:")) self.radio.setChecked(True) self.textbox=TextBox() h.add(self.textbox) v.add(h) v.add(Button("Done",self.done_click)) self.add(v) def get_folder_name(self): if self.radio.getChecked(): return self.list.getItemText(self.list.getSelectedIndex()) else: return self.textbox.getText() def done_click(self): self.theorem.folder=self.get_folder_name() Theorem.theorems.append(self.theorem) IO.save() self.hide()
class SaveDialog(DialogWindow): def __init__(self, theorem, **kwargs): DialogWindow.__init__(self, modal=True, close=True) self.theorem = theorem v = VerticalPanel() v.setWidth(300) # v.setHeight(500) self.setText("save") self.setPopupPosition(100, 100) self.setStyleAttribute("background-color", "#ffffff") self.setStyleAttribute("color", "red") self.setStyleAttribute("border-width", "5px") self.setStyleAttribute("border-style", "solid") self.im = Image() self.im.setUrl(latex_to_url(self.theorem.formula.to_latex())) v.add(self.im) h = HorizontalPanel() self.radio = RadioButton("group1", "Existing folder:") h.add(self.radio) self.list = ListBox() self.list.setVisibleItemCount(1) for f in Theorem.get_all_folders(): self.list.addItem(f) h.add(self.list) v.add(h) h = HorizontalPanel() h.add(RadioButton("group1", "New folder:")) self.radio.setChecked(True) self.textbox = TextBox() h.add(self.textbox) v.add(h) v.add(Button("Done", self.done_click)) self.add(v) def get_folder_name(self): if self.radio.getChecked(): return self.list.getItemText(self.list.getSelectedIndex()) else: return self.textbox.getText() def done_click(self): self.theorem.folder = self.get_folder_name() Theorem.theorems.append(self.theorem) IO.save() self.hide()
class InputControl(Control): def __init__(self, min_value, max_value, start_value=None, step=None, **kwargs): if not kwargs.has_key("StyleName"): kwargs['StyleName'] = "gwt-InputControl" self.input = TextBox() self.input.addKeyboardListener(self) #element = DOM.createDiv() if kwargs.has_key('Element'): # XXX FIXME: unlikely to work! element = kwargs.pop('Element') else: element = self.input.getElement() # YUK!!! Control.__init__(self, element, min_value, max_value, start_value, step, **kwargs) self.addClickListener(self) self.addFocusListener(self) self.addKeyboardListener(self) def onFocus(self, sender): self.addStyleName("gwt-InputControl-focussed") def onLostFocus(self, sender): self.removeStyleName("gwt-InputControl-focussed") def setControlPos(self, value): self.input.setText(value) def onKeyPress(self, sender, keycode, modifiers): if keycode == KeyboardListener.KEY_ENTER: DOM.eventPreventDefault(DOM.eventGetCurrentEvent()) txt = self.input.getText() if not txt: return new_value = float(txt) new_value = self.processValue(new_value) self.setControlPos(new_value) self.setValue(new_value) else: Control.onKeyPress(self, sender, keycode, modifiers)
class Projects_Editor(SimplePanel): ''' Create and edit projects ''' def __init__(self): # We need to use old form of inheritance because of pyjamas SimplePanel.__init__(self) self.hpanel = HorizontalPanel(Width='475px') self.hpanel.setVerticalAlignment(HasAlignment.ALIGN_BOTTOM) self.name = TextBox() self.name.setStyleName('form-control') self.status = ListBox() self.status.addItem('Active') self.status.addItem('Inactive') self.status.setVisibleItemCount(0) self.status.setStyleName('form-control input-lg') self.status.setSize('100px', '34px') lbl = Label('', Width='10px') self.add_btn = Button('Add') self.add_btn.setStyleName('btn btn-primary') self.del_btn = Button('Delete') self.del_btn.setStyleName('btn btn-danger') self.hpanel.add(self.name) self.hpanel.add(lbl) self.hpanel.add(self.status) self.hpanel.add(self.add_btn) self.hpanel.add(self.del_btn) def get_name_txt(self): '''Return project name. ''' return self.name.getText() def get_status(self): '''Return project status. ''' return self.status.getItemText(self.status.getSelectedIndex())
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()
class WebApp: def onFormLoad(self): self.fetch = Button("Retrieve", self) self.search = TextBox() self.submit = Button("Submit", self) self.formsvc = FormService() self.wanted = WantedService() d = {'price': 20, 'name': 'a good car'} self.form = Form(getattr(self.formsvc, "itemform"), data=d, listener=self) #self.describe(['name', 'description']) RootPanel().add(self.form) RootPanel().add(self.search) RootPanel().add(self.fetch) def onRetrieveDone(self, form): log.debug("onRetrieveDone: %s" % repr(form)) def onDescribeDone(self, form): form.add_widget("Submit", self.submit) def onClick(self, sender): if sender == self.fetch: key = self.search.getText() if not key: log.debug("Please enter id") return key = int(key) log.debug("id %d" % key) #self.wanted.getItem(key, self) self.form.get(id=key) if sender == self.submit: v = self.form.getValue() log.debug("onClick %s" % repr(v)) if v.get('id', None): self.form.update(v) else: self.form.save(v) def onErrors(self, form, response): log.debug("onErrors %s" % repr(response)) def onSaveDone(self, form, response): log.debug("onSave %s" % repr(response)) def onModuleLoad(self): self.pages = DataService() #Show the initial screen. initToken = History().getToken() if initToken and len(initToken): if initToken == 'admin': RootPanel().add(WebPageEdit(self)) return else: initToken = 'index' self.dock = DockPanel() self.dock.setWidth("100%") self.pages = {} self.current_page = None RootPanel().add(self.dock) History.addHistoryListener(self) self.onHistoryChanged(initToken) def createPage(self, ref, html, title): htp = HTMLLinkPanel(self, html, title) htp.replaceLinks() htp.setWidth("100%") self.pages[ref] = htp def onHistoryChanged(self, token): #log.debug("onHistoryChanged %s" % token) if self.pages.has_key(token): self.setPage(token) return self.pages.getPageByName(token, self) def setPage(self, ref): htp = self.pages[ref] if htp == self.current_page: return Window.setTitle(htp.title) if self.current_page: self.dock.remove(self.current_page) self.dock.add(htp, DockPanel.CENTER) self.current_page = htp def onRemoteResponse(self, response, request_info): #if (request_info.method == 'getItem'): # data = {'id': response['pk']} # log.debug(repr(response)) # self.form.update_values(response) if (request_info.method == 'getPageByName' or request_info.method == 'getPage'): item = response[0] html = item['fields']['text'] token = item['fields']['name'] self.createPage(token, html, token) self.setPage(token) def onRemoteError(self, code, message, request_info): RootPanel().add( HTML("Server Error or Invalid Response: ERROR " + str(code) + " - " + str(message)))
class DateField(Composite, DateSelectedHandler): img_base = None icon_img = None icon_style = "calendar-img" today_text = "Today" today_style = "calendar-today-link" def __init__(self, format='%d-%m-%Y'): DateSelectedHandler.__init__(self) if self.img_base is None: self.img_base = pygwt.getImageBaseURL(True) if self.icon_img is None: self.icon_img = self.img_base + 'icon_calendar.gif' self.format = format self.tbox = TextBox() self.tbox.setVisibleLength(10) # assume valid sep is - / . or nothing if format.find('-') >= 0: self.sep = '-' elif format.find('/') >= 0: self.sep = '/' elif format.find('.') >= 0: self.sep = '.' else: self.sep = '' # self.sep = format[2] # is this too presumptious? self.calendar = Calendar() self.img = Image(self.icon_img) self.img.addStyleName(self.icon_style) self.calendarLink = HyperlinkImage(self.img) self.todayLink = Hyperlink(self.today_text) self.todayLink.addStyleName(self.today_style) # # lay it out # hp = HorizontalPanel() hp.setSpacing(2) vp = VerticalPanel() hp.add(self.tbox) vp.add(self.calendarLink) vp.add(self.todayLink) #vp.add(self.calendar) hp.add(vp) Composite.__init__(self) self.initWidget(hp) # # done with layout, so now set up some listeners # self.tbox.addFocusListener(self) # hook to onLostFocus self.calendar.addSelectedDateListener(getattr(self, "onDateSelected")) self.todayLink.addClickListener(getattr(self, "onTodayClicked")) self.calendarLink.addClickListener(getattr(self, "onShowCalendar")) self.tbox.addChangeListener(getattr(self, "onFieldChanged")) self.tbox.addInputListener(getattr(self, "onFieldChanged")) self._last_date = None def emitSelectedDate(self): _d = self.getDate() if _d == self._last_date: return self._last_date = _d self.fireDateSelectedEvent(_d) def onFieldChanged(self, event): self.emitSelectedDate() def getTextBox(self): return self.tbox def getCalendar(self): return self.calendar def getDate(self): """ returns datetime.date object or None if empty/unparsable by current format""" _sdate = self.tbox.getText() try: return datetime.strptime(_sdate, self.format).date() except ValueError: return None def setID(self, id): self.tbox.setID(id) def onDateSelected(self, yyyy, mm, dd): secs = time.mktime((int(yyyy), int(mm), int(dd), 0, 0, 0, 0, 0, -1)) d = time.strftime(self.format, time.localtime(secs)) self.tbox.setText(d) self.emitSelectedDate() def onLostFocus(self, sender): # text = self.tbox.getText().strip() # if blank - leave it alone if text and len(text) == 8: # ok what format do we have? assume ddmmyyyy --> dd-mm-yyyy txt = text[0:2] + self.sep + text[2:4] + self.sep + text[4:8] self.tbox.setText(txt) self.emitSelectedDate() def onFocus(self, sender): pass def onTodayClicked(self, event): today = time.strftime(self.format) self.tbox.setText(today) self.emitSelectedDate() def onShowCalendar(self, sender): txt = self.tbox.getText().strip() try: if txt: _d = datetime.strptime(txt, self.format).date() self.calendar.setDate(_d) except ValueError: pass p = CalendarPopup(self.calendar) x = self.tbox.getAbsoluteLeft() + 10 y = self.tbox.getAbsoluteTop() + 10 p.setPopupPosition(x, y) p.show()
class Photos(Composite): def __init__(self): Composite.__init__(self) self.albums = [] self.photos = [] self.grid = Grid(4, 4, CellPadding=4, CellSpacing=4) self.grid.addTableListener(self) self.drill = 0 self.pos = 0 self.up = Button("Up", self) self.next = Button("Next", self) self.prev = Button("Prev", self) self.timer = Timer(notify=self) self.userid = "jameskhedley" self.album_url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "?alt=json-in-script&kind=album&hl=en_US&callback=restCb" self.doRESTQuery(self.album_url, self.timer) self.vp = VerticalPanel() self.disclosure = DisclosurePanel("Click for boring technical details.") self.disclosure.add(HTML('''<p>OK so you want to write client JS to do a RESTful HTTP query from picasa right? Well you can't because of the Same Origin Policy. Basically this means that because the domain of the query and the domain of the hosted site are different, then that could well be a cross-site scripting (XSS) attack. So, the workaround is to do the call from a script tag so the JSON we get back is part of the document. But since we don't know what URL to hit yet, once we find out then we have to inject a new script tag dynamically which the browser will run as soon as we append it. To be honest I'm not 100% why Google use RESTful services and not JSON-RPC or somesuch, which would be easier. Well, easier for me.''')) self.IDPanel = HorizontalPanel() self.IDPanel.add(Label("Enter google account:")) self.IDButton = Button("Go", self) self.IDBox = TextBox() self.IDBox.setText(self.userid) self.IDPanel.add(self.IDBox) self.IDPanel.add(self.IDButton) self.vp.add(self.IDPanel) self.vp.add(self.disclosure) self.vp.add(self.grid) self.initWidget(self.vp) def doRESTQuery(self, url, timer): """this is a totally different from an RPC call in that we have to dynamically add script tags to the DOM when we want to query the REST API. These rely on callbacks in the DOM so we can either add them dynamically or pre-define them in public/Main.html. Once we've done that have to wait for the response. Which means we need to provide a listener for the timer""" JS("$wnd.receiver = 'wait'") new_script = DOM.createElement("script") DOM.setElemAttribute(new_script, "src", url) DOM.setElemAttribute(new_script, "type","text/javascript") JS("$wnd.document.body.appendChild(@{{new_script}})") self.timer.schedule(100) def onCellClicked(self, sender, row, col): if self.drill==0: self.drill += 1 self.vp.clear() self.grid.clear() self.vp.add(self.up) self.vp.add(self.grid) gridcols = self.grid.getColumnCount() album = self.albums[row+col+(row*(gridcols-1))] url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "/albumid/" + album["id"] + "?alt=json-in-script&kind=photo&hl=en_US&callback=restCb" self.doRESTQuery(url, self.timer) elif self.drill==1: self.drill += 1 gridcols = self.grid.getColumnCount() self.pos =row+col+(row*(gridcols-1)) photo = self.photos[self.pos] self.vp.clear() self.fullsize = HTML('<img src="' + photo["full"] + '"/>') hp = HorizontalPanel() hp.add(self.up) hp.add(self.prev) hp.add(self.next) hp.setSpacing(8) self.vp.add(hp) self.vp.add(self.fullsize) def onClick(self, sender): if sender == self.IDButton: self.userid = self.IDBox.getText() if self.userid == "" or self.userid.isdigit(): return self.drill = 0 self.album_url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "?alt=json-in-script&kind=album&hl=en_US&callback=restCb" self.grid.clear() self.doRESTQuery(self.album_url, self.timer) else: if self.drill == 2: if sender == self.up: self.drill=1 self.vp.clear() self.vp.add(self.up) self.vp.add(self.grid) self.fillGrid(self.photos, "photos") else: if sender == self.next: if self.pos >= len(self.photos): return self.pos +=1 elif sender == self.prev: if self.pos < 1: return self.pos -=1 photo = self.photos[self.pos] self.fullsize.setHTML('<img src="' + photo["full"] + '"/>') elif self.drill == 1: self.drill=0 self.vp.clear() self.vp.add(self.IDPanel) self.vp.add(self.disclosure) self.vp.add(self.grid) self.fillGrid(self.albums, "albums") def onTimer(self, timer): receiver = JS("$wnd.receiver") if receiver == 'wait': self.timer.schedule(1000) return JS("$wnd.receiver = 'wait'") if self.drill == 0: self.parseAlbums(receiver) self.fillGrid(self.albums, "albums") elif self.drill == 1: self.parsePhotos(receiver) self.fillGrid(self.photos, "photos") def fillGrid(self, items, type): self.grid.clear() cols = self.grid.getColumnCount() self.grid.resizeRows((len(items)/cols)+1) rows = self.grid.getRowCount() for i in range(len(items)): vp = VerticalPanel() if type == 'photos': vp.add(items[i]['thumb']) else: vp.add(items[i]['thumb']) vp.add(items[i]['title']) self.grid.setWidget(int(i/cols), i%cols, vp) def parsePhotos(self, items): photo_list = JSONParser().jsObjectToPyObject(items) self.photos = [] for i in range(len(photo_list)): index = "%s" % i aphoto = {} aphoto['thumb'] = HTML('<img src="' + photo_list[index]["media$group"]["media$thumbnail"]["1"]["url"] + '"/>') aphoto['full'] = photo_list[index]["media$group"]["media$content"]["0"]["url"] self.photos.append(aphoto) def parseAlbums(self, items): album_list = JSONParser().jsObjectToPyObject(items) self.albums = [] for i in range(len(album_list)): index = "%s" % i analbum = {} analbum['title'] = HTML(album_list[index]["title"]["$t"]) analbum['thumb'] = HTML('<img src="' + album_list[index]["media$group"]["media$thumbnail"]["0"]["url"] + '"/>') url = album_list[index]["id"]["$t"] analbum['id'] = url.split('albumid/')[1].split('?alt')[0] self.albums.append(analbum)
class PreferencesDlg(DialogBox): fileLocation = None def __init__(self, left=50, top=50): DialogBox.__init__(self, modal=False) self.setPopupPosition(left, top) self.setText("Preferences") ftable = FlexTable() ftableFormatter = ftable.getFlexCellFormatter() row = 0 try: self.fileLocation = getCookie("fileLocation") except: self.fileLocation = None row += 1 ftable.setWidget(row, 0, Label("Sheet loaded on startup", wordWrap=False)) self.fileLocationInput = TextBox() self.fileLocationInput.addChangeListener(self.checkValid) self.fileLocationInput.addKeyboardListener(self) self.fileLocationInput.setVisibleLength(30) self.fileLocationInput.setText(self.fileLocation) ftable.setWidget(row, 1, self.fileLocationInput) row += 1 hpanel = HorizontalPanel() self.saveBtn = Button("Save", self.onSave) self.saveBtn.setEnabled(False) hpanel.add(self.saveBtn) self.cancelBtn = Button("Cancel", self.onCancel) hpanel.add(self.cancelBtn) ftable.setWidget(row, 0, hpanel) ftableFormatter.setColSpan(row, 0, 2) self.setWidget(ftable) def onCancel(self, sender): self.hide() def onSave(self, sender): try: setCookie("fileLocation", self.fileLocationInput.getText(), 1000000000) except: pass self.hide() def checkValid(self, evt=None): if self.fileLocation != self.fileLocationInput.getText(): self.saveBtn.setEnabled(True) else: self.saveBtn.setEnabled(False) def onClick(self, sender): pass def onKeyUp(self, sender, keyCode, modifiers): self.checkValid() def onKeyDown(self, sender, keyCode, modifiers): pass def onKeyPress(self, sender, keyCode, modifiers): pass
class cTestPanel(VerticalPanel): def __init__(self, **kwargs): VerticalPanel.__init__(self, **kwargs) info = """<h2>JSON-RPC Example</h2> #<p>This example demonstrates the calling of server services with # <a href="http://json-rpc.org/">JSON-RPC</a>. #</p> #<p>Choose a service below, and press a the "call service" button to initiate it. An echo service simply sends the exact same text back that it receives. # </p>""" self.status = Label() self.dockey = TextBox(Text="12") self.TEXT_WAITING = "Waiting for response..." self.METHOD_ECHO = "Echo" self.METHOD_DOCTYPES = "get doc types" self.METHOD_UPPERCASE = "get schema" self.METHOD_GETINBOX = "get inbox" self.METHOD_GETDOCS = "get documents" self.methods = [ self.METHOD_ECHO, self.METHOD_DOCTYPES, self.METHOD_UPPERCASE, self.METHOD_GETINBOX, self.METHOD_GETDOCS ] self.method_list = ListBox() self.method_list.setName("hello") self.method_list.setVisibleItemCount(1) for method in self.methods: self.method_list.addItem(method) self.method_list.setSelectedIndex(0) method_panel = HorizontalPanel() method_panel.add(HTML("Remote string method to call: ")) method_panel.add(self.method_list) method_panel.setSpacing(8) self.button_action = Button("Call Service", self) buttons = HorizontalPanel() buttons.add(self.button_action) buttons.setSpacing(8) panel = VerticalPanel() panel.add(HTML(info)) panel.add(HTML("Primary key of the patient in the database:")) panel.add(self.dockey) panel.add(method_panel) panel.add(buttons) panel.add(self.status) self.add(panel) #-------------------------------------------------- def onClick(self, sender): self.status.setText(self.TEXT_WAITING) method = self.methods[self.method_list.getSelectedIndex()] # demonstrate proxy & callMethod() if sender == self.button_action: if method == self.METHOD_ECHO: id = Remote.svc.echo("Hello", self) elif method == self.METHOD_DOCTYPES: id = Remote.svc.get_doc_types(self) elif method == self.METHOD_UPPERCASE: id = Remote.svc.get_schema_version(self) elif method == self.METHOD_GETINBOX: id = Remote.svc.get_provider_inbox_data(self) elif method == self.METHOD_GETDOCS: key = int(self.dockey.getText()) # TODO: check it! id = Remote.svc.get_documents(key, self) #-------------------------------------------------- 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 onRemoteError(self, code, errobj, request_info): # onRemoteError gets the HTTP error code or 0 and # errobj is an jsonrpc 2.0 error dict: # { # 'code': jsonrpc-error-code (integer) , # 'message': jsonrpc-error-message (string) , # 'data' : extra-error-data # } message = errobj['message'] if code != 0: self.status.setText("HTTP error %d: %s" % (code, message)) else: code = errobj['code'] if message == 'Cannot request login parameters.': self.status.setText("You need to log in first") else: self.status.setText("JSONRPC Error %s: %s" % (code, message))
class IntroPage: DiceInstance = 0 VarTempScore = 0 #Temporary Score Variable VarTotScore = [] #Total Score Variable CountTurn = 1 #Count to display player number in Temporary Score Board def __init__(self): self.DPanel = DockPanel(HorizontalAlignment = HasAlignment.ALIGN_CENTER, Spacing=10) # Creates the Docker Panel Instance self.VPanel = VerticalPanel() # Creates the Vertical Panel Instance self.VPanel1 = VerticalPanel() # Creates the Vertical Panel Instance self.HPanel = HorizontalPanel() # Creates a Horizontal Panel Instance self.HPanel1 = HorizontalPanel()# Creates a Horizontal Panel Instance self.image=Image()#Creates the Image instance to embed the images of dice self.DummyUrl = self.image.getUrl() self.timer = Timer(notify=self.StillImage)#Timer for display of gif animation self.timerRButton = Timer(notify=self.OneAlert)#Timer for controlling states of Roll button #whenever the output of the dice is 1 self.RollButton = Button("Roll", getattr(self, "RollButtonPressed")) #Initially Disabled self.RollButton.setEnabled(False) self.BankButton = Button("Bank", getattr(self, "BankButtonPressed")) #Initially Disabled self.BankButton.setEnabled(False) #The start button controls both the number players as well the winning score self.StartButton = Button("Start", getattr(self, "StartButtonPressed")) #Intially Enabled self.StartButton.setEnabled(True) self.PlayerNum = TextBox() #Enter the Number of Players self.WinScore = TextBox() #Enter the Target Score self.PlayerNum.setText("0") self.WinScore.setText("0") # self.OK = Button("OK", getattr(self, "okButtonPressed")) self.NameScore = FlexTable() #main score board self.NameScore.setStyleName("NameScore") self.TempBoard = FlexTable() #Temporary score board self.TempBoard.setStyleName("TempBoard") self.TxtInstructions = HTML() def StartButtonPressed(self): self.CountTurn = 1 if int(self.PlayerNum.getText()) >= 2 and int(self.PlayerNum.getText()) <= 6 and int(self.WinScore.getText()) >= 10 and int(self.WinScore.getText()) <= 100: self.DPanel.remove(self.TxtInstructions, DockPanel.CENTER) self.BankButton.setVisible(True) self.RollButton.setVisible(True) # self.image.setVisible(True) self.TempBoard.setVisible(True) self.NameScore.setVisible(True) self.image = Image( self.DummyUrl + "images/0.png") self.image.setSize("200px", "300px") self.DPanel.add(self.image, DockPanel.CENTER) RootPanel().add(self.DPanel) self.StartButton.setEnabled(False) self.PlayerNum.setEnabled(False) self.WinScore.setEnabled(False) self.RollButton.setEnabled(True) self.TempBoard.setText(1,0,"Player"+str(1)) self.TempBoard.setText(1, 1, "0") self.NameScore.getRowFormatter().addStyleName(self.CountTurn,"Rows") else: Window.alert("Please Enter Correct Parameters " ) #Command for alert window return 0 VarPlayer = ["Player" + str(i) for i in xrange(1,int(self.PlayerNum.getText())+1)] i = 0 while i < int(self.PlayerNum.getText()): self.NameScore.setText(i+1, 0, VarPlayer[i]) self.NameScore.setText(i+1, 1, "0") self.VarTotScore.append(0) #m*1 vector of zeros indicating the initial scores i += 1 def OneAlert(self): AlrtTxt = " Sorry, your turn is over" Window.alert(AlrtTxt) self.timerRButton.cancel() self.RollButton.setEnabled(True) def StillImage(self): self.DPanel.remove(self.image, DockPanel.CENTER) self.image = Image( self.DummyUrl + "images/" +str(self.DiceInstance)+".png") self.image.setSize("300px", "300px") self.DPanel.add(self.image, DockPanel.CENTER) self.DPanel.setCellHeight(self.image, "300px") self.DPanel.setCellWidth(self.image, "600px") RootPanel().add(self.DPanel) self.timer.cancel() if self.DiceInstance != 1: self.TempBoard.setText(1, 1, self.DiceInstance + int(self.TempBoard.getText(1, 1))) self.BankButton.setEnabled(True) self.RollButton.setEnabled(True) else: self.NameScore.getRowFormatter().removeStyleName(self.CountTurn,"Rows") self.RollButton.setEnabled(False) self.timerRButton.schedule(1500) self.CountTurn += 1 if self.CountTurn % int(self.PlayerNum.getText()) == 1: self.CountTurn = 1 self.TempBoard.setText(1,0,"Player"+str(self.CountTurn)) self.TempBoard.setText(1, 1, "0") self.NameScore.getRowFormatter().addStyleName(self.CountTurn,"Rows"); else: self.TempBoard.setText(1,0,"Player"+str(self.CountTurn)) self.TempBoard.setText(1, 1, "0") self.NameScore.getRowFormatter().addStyleName(self.CountTurn,"Rows"); def RollButtonPressed(self): self.DiceInstance = random.randint(1, 6) # value turned after rolling the dice self.DPanel.remove(self.image, DockPanel.CENTER) self.image = Image("http://www.animatedimages.org/data/media/710/animated-dice-image-0064.gif") self.image.setSize("100px", "200px") self.DPanel.add(self.image, DockPanel.CENTER) self.DPanel.setCellHeight(self.image, "300px") self.DPanel.setCellWidth(self.image, "600px") RootPanel().add(self.DPanel) self.BankButton.setEnabled(False) self.RollButton.setEnabled(False) self.timer.schedule(3000) def BankButtonPressed(self): self.BankButton.setEnabled(False) self.NameScore.setText(self.CountTurn, 1, int(self.NameScore.getText(self.CountTurn, 1)) + int(self.TempBoard.getText(1,1))) if int(self.NameScore.getText(self.CountTurn, 1)) >= int(self.WinScore.getText()): AlrtTxt = "Congratulation!!! Player"+ str(self.CountTurn) + " wins !!!!" Window.alert(AlrtTxt) self.DPanel.remove(self.image, DockPanel.CENTER) self.DPanel.add(self.TxtInstructions, DockPanel.CENTER) self.BankButton.setVisible(False) self.RollButton.setVisible(False) # self.image.setVisible(False) self.TempBoard.setVisible(False) self.NameScore.setVisible(False) i = int(self.PlayerNum.getText()) while i > 0: self.NameScore. removeRow(i) i -= 1 self.TempBoard.setText(1,0,"X") self.TempBoard.setText(1, 1, "0") self.StartButton.setEnabled(True) # self.OK.setEnabled(True) self.PlayerNum.setEnabled(True) self.WinScore.setEnabled(True) self.RollButton.setEnabled(False) self.BankButton.setEnabled(False) self.NameScore.getRowFormatter().removeStyleName(self.CountTurn,"Rows"); self.DPanel.remove(self.image, DockPanel.CENTER) self.image = Image( self.DummyUrl + "images/0.png") self.image.setSize("200px", "300px") self.DPanel.add(self.image, DockPanel.CENTER) self.DPanel.setCellHeight(self.image, "200px") self.DPanel.setCellWidth(self.image, "400px") RootPanel().add(self.DPanel) else: self.NameScore.getRowFormatter().removeStyleName(self.CountTurn,"Rows"); self.CountTurn += 1 if self.CountTurn % int(self.PlayerNum.getText()) == 1: self.CountTurn = 1 self.TempBoard.setText(1,0,"Player"+str(self.CountTurn)) self.TempBoard.setText(1, 1, "0") self.NameScore.getRowFormatter().addStyleName(self.CountTurn,"Rows"); else: self.TempBoard.setText(1,0,"Player"+str(self.CountTurn)) self.TempBoard.setText(1, 1, "0") self.NameScore.getRowFormatter().addStyleName(self.CountTurn,"Rows"); def OnGameLoad(self): self.NameScore.setText(0, 0, "Player ID") self.NameScore.setText(0, 1, "Score") self.NameScore.setCellSpacing(10) self.NameScore.setCellPadding(10) self.NameScore.setBorderWidth(2) self.NameScore.setVisible(False) self.TempBoard.setText(0, 0, "Player's Turn") self.TempBoard.setText(0, 1, "Temporary Score") self.TempBoard.setText(1, 0, "X") self.TempBoard.setText(1, 1, "0") self.TempBoard.setCellSpacing(10) self.TempBoard.setCellPadding(10) self.TempBoard.setBorderWidth(2) self.TempBoard.setVisible(False) #Adding StartButton to Dock panel self.DPanel.add(self.StartButton, DockPanel.EAST) self.DPanel.setCellHeight(self.StartButton, "200px") self.DPanel.setCellWidth(self.StartButton, "20px") Txt = HTML("<center><b>Enter Number of Players (between 2 & 6)</b><center>")#Adding playernumber and winscore textbox to Horizontal Panel Txt1 = HTML("<left><b>Enter Target Score (between 10 & 100)</b><left>") self.HPanel1.add(Txt) self.HPanel1.add(self.PlayerNum) self.HPanel1.add(Txt1) self.HPanel1.add(self.WinScore) self.HPanel1.add(self.StartButton) self.HPanel1.setSpacing(20) #Adding Horizontal panel containing playernumber and winscore textbox to Dock Panel self.DPanel.add(self.HPanel1, DockPanel.NORTH) self.DPanel.setCellHeight(self.HPanel1, "30px") self.DPanel.setCellWidth(self.HPanel1, "2000px") self.TxtInstructions = HTML("<b><u><center>Instructions</center></u><ul><li>Pig is game for 2 to 6 Players.</li><li>Players take turns rolling a dice as many times as they like. </li><li>If a roll is 2, 3, 4, 5 or 6, the player adds that many points to their score for the turn. </li><li>A player may choose to end their turn at any time and 'bank' their points.</li><li>If a player rolls a 1, they lose all their unbanked points and their turn is over.</li><li>The first player to score the target or more wins.</li></ul></b>") self.TxtInstructions.setStyleName("TxtInstructions") self.DPanel.add(self.TxtInstructions, DockPanel.CENTER) self.DPanel.add(self.NameScore, DockPanel.WEST) #Adding main scoreboard to Dock Panel self.DPanel.setCellHeight(self.NameScore, "300px") self.DPanel.setCellWidth(self.NameScore, "100px") self.DPanel.setSpacing(10) self.DPanel.setPadding(2) #Adding Tempboard and BankButton to Horizontal Panel self.HPanel.add(self.TempBoard) #Adding BankButton and RollButton to vertical panel self.VPanel.add(self.RollButton) self.RollButton.setVisible(False) self.VPanel.add(self.BankButton) self.BankButton.setVisible(False) self.VPanel.setSpacing(10) #Adding Vertical panel containing BankButton and RollButton to Horizontal Panel self.HPanel.add(self.VPanel) self.HPanel.setSpacing(40) #Adding Horizontal panel containing Tempboard and vertical panel containing BankButton and RollButton to Dock Panel self.DPanel.add(self.HPanel, DockPanel.SOUTH) self.DPanel.setCellHeight(self.HPanel, "20px") self.DPanel.setCellWidth(self.HPanel, "2000px") RootPanel().add(self.DPanel)
class DateField(Composite): icon_img = "icon_calendar.gif" icon_style = "calendar-img" today_text = "Today" today_style = "calendar-today-link" def __init__(self, format='%d-%m-%Y'): self.format = format self.tbox = TextBox() self.tbox.setVisibleLength(10) # assume valid sep is - / . or nothing if format.find('-') >= 0: self.sep = '-' elif format.find('/') >= 0: self.sep = '/' elif format.find('.') >= 0: self.sep = '.' else: self.sep = '' # self.sep = format[2] # is this too presumptious? self.calendar = Calendar() self.img = Image(self.icon_img) self.img.addStyleName(self.icon_style) self.calendarLink = HyperlinkImage(self.img) self.todayLink = Hyperlink(self.today_text) self.todayLink.addStyleName(self.today_style) # # lay it out # hp = HorizontalPanel() hp.setSpacing(2) vp = VerticalPanel() hp.add(self.tbox) vp.add(self.calendarLink) vp.add(self.todayLink) #vp.add(self.calendar) hp.add(vp) Composite.__init__(self) self.initWidget(hp) # # done with layout, so now set up some listeners # self.tbox.addFocusListener(self) # hook to onLostFocus self.calendar.addSelectedDateListener(getattr(self, "onDateSelected")) self.todayLink.addClickListener(getattr(self, "onTodayClicked")) self.calendarLink.addClickListener(getattr(self, "onShowCalendar")) def getTextBox(self): return self.tbox def getCalendar(self): return self.calendar def getDate(self): """ returns datetime.date object or None if empty/unparsable by current format""" _sdate = self.tbox.getText() try: return datetime.strptime(_sdate, self.format).date() except ValueError: return None def setID(self, id): self.tbox.setID(id) def onDateSelected(self, yyyy, mm, dd): secs = time.mktime((int(yyyy), int(mm), int(dd), 0, 0, 0, 0, 0, -1)) d = time.strftime(self.format, time.localtime(secs)) self.tbox.setText(d) def onLostFocus(self, sender): # text = self.tbox.getText().strip() # if blank - leave it alone if text and len(text) == 8: # ok what format do we have? assume ddmmyyyy --> dd-mm-yyyy txt = text[0:2] + self.sep + text[2:4] + self.sep + text[4:8] self.tbox.setText(txt) def onFocus(self, sender): pass def onTodayClicked(self, event): today = time.strftime(self.format) self.tbox.setText(today) def onShowCalendar(self, sender): txt = self.tbox.getText().strip() try: if txt: _d = datetime.strptime(txt,self.format).date() self.calendar.setDate(_d) except ValueError: pass p = CalendarPopup(self.calendar) x = self.tbox.getAbsoluteLeft() + 10 y = self.tbox.getAbsoluteTop() + 10 p.setPopupPosition(x, y) p.show()
class PageVerify: # setup JSON RPC facebook_user = {} users = [] new_user = {} get_data = {} app_info = {} verification_key = None verification_status = False def onModuleLoad(self): self.remote = DataService() # do JSON RPC calls self.remote.get_facebook_user(self) self.remote.get_app_info(self, "verify") # labels and banners self.html_verify_banner = HTML("<h1>Verify your NetID</h1>") self.html_confirm_banner = HTML("<h1>Confirming your NetID...</h1>") self.lbl_verify_text = Label("Please verify your account.") self.lbl_confirm_text = Label("Confirming Acount...") self.lbl_confirm_result = Label() # textboxes self.tb_verify_netid = TextBox() # hook up keyboard events send_confirmation_email = self.send_confirmation_email class Add_KeyboardHandler(): def onKeyPress(self, sender, keycode, modifiers): if keycode == KEY_ENTER: send_confirmation_email() def onKeyDown(self, sender, keycode, modifiers): return def onKeyUp(self, sender, keycode, modifiers): return self.kbh = Add_KeyboardHandler() self.tb_verify_netid.addKeyboardListener(self.kbh) # buttons self.btn_verify = Button("Verify!", self.send_confirmation_email) # NetID information form self.table_verify_netid = FlexTable() self.table_verify_netid.setText(0, 0, "NetID:") self.table_verify_netid.setWidget(0, 1, self.tb_verify_netid) self.table_verify_netid.setWidget(1, 1, self.btn_verify) # panels self.main_panel = VerticalPanel() # check get information, if present, verify, if not request form self.location = Window.getLocation().getHref() self.tmp = self.location.split('?') self.tmp = self.tmp[len(self.tmp) - 1].split("&") for e in self.tmp: get_var = e.split("=") if len(get_var) == 2: PageVerify.get_data[get_var[0]] = get_var[1] if "vk" in PageVerify.get_data: # we have request from verification email self.main_panel.add(self.html_confirm_banner) self.main_panel.add(self.lbl_confirm_text) self.main_panel.add(self.lbl_confirm_result) self.verify_user() else: self.main_panel.add(self.html_verify_banner) self.main_panel.add(self.lbl_verify_text) self.main_panel.add(self.table_verify_netid) self.main_panel.addStyleName("verify_panel") # add everything to root panel RootPanel("page_verify").add(self.main_panel) def send_confirmation_email(self, sender, netid = None): """ given a valid NetID, send a confirmation email with a link (using encrypted key) to validate the user's NetID """ if netid == None: netid = self.tb_verify_netid.getText() # create a new user with netid and facebook id self.remote.create_user(self, PageVerify.facebook_user['facebook_id'], netid, PageVerify.facebook_user['full_name']) # create cryptogram based on email name self.remote.encrypt(self, netid) # subject line subject = "Hello from Textbook Connect!" class EmailTimer(Timer): def __init__(self, context): Timer.__init__(self) self.max_tries = 10 self.tries = 0 self.context = context def run(self): self.context.btn_verify.setEnabled(False) self.context.tb_verify_netid.setFocus(False) self.tries += 1 # stop timer after a certain time if self.tries >= self.max_tries: Window.alert("It looks like there's a connection problem. We're sorry about the inconvenience. Please try again later.") self.context.btn_verify.setEnabled(True) self.cancel() return False if "error" in PageVerify.new_user: Window.alert(PageVerify.new_user["error"]) return False if len(PageVerify.new_user) == 0 or PageVerify.verification_key == None: return False # message body link = "%sverify?vk=%s" % (PageVerify.app_info['url'], PageVerify.verification_key) body = "Hello, %s.<br /><br />Thank you for verifying your netid with us! " % PageVerify.new_user['name'] body += "Please click the link below or copy and paste the link into a web browser.<br /><br />" body += "<a href=\"%s\">%s</a><br /><br />" % (link, link) body += "Thanks,<br /> Textbook Connect Team" self.context.remote.send_email(self.context, netid + "@cornell.edu", subject, body) Window.alert("Thank you! An email from Textbook Connect should arrive shortly.") self.cancel() return True et = EmailTimer(self) et.scheduleRepeating(500) def verify_user(self): """ take get data input with verification key and attempt to verify a user in the database """ class VerifyTimer(Timer): def __init__(self, context): Timer.__init__(self) self.max_tries = 10 self.tries = 0 self.context = context def run(self): self.tries += 1 if self.context.facebook_user == None or "vk" not in self.context.get_data: return False # stop timer after a certain time if self.tries >= self.max_tries: Window.alert("It looks like there's a connection problem. We're sorry about the inconvenience. Please try again later.") self.context.lbl_confirm_result.setText("User verification unsuccessful...") self.cancel() return False self.context.remote.verify_email(self.context, self.context.facebook_user['facebook_id'], self.context.get_data['vk']) if self.context.verification_status: self.context.lbl_confirm_result.setText("User verification successful!") self.cancel() Window.open(self.context.app_info['url'], "_top", "") return True vt = VerifyTimer(self) vt.scheduleRepeating(500) def onRemoteResponse(self, response, request_info): """ Called when a response is received from an RPC """ if not request_info.method in DataService.methods: Window.alert('Unrecognized JSONRPC method.') return if request_info.method == "get_facebook_user": PageVerify.facebook_user = {} for k, v in response.items(): PageVerify.facebook_user[k] = v elif request_info.method == "get_app_info": for k, v in response.items(): PageVerify.app_info[k] = v elif request_info.method == "encrypt": PageVerify.verification_key = response['c'] elif request_info.method == "verify_email": PageVerify.verification_status = response['result'] elif request_info.method == "create_user": PageVerify.new_user = {} for k, v in response.items(): PageVerify.new_user[k] = v def onRemoteError(self, code, message, request_info): """ Called when a returned response is invalid or Server Error """ code = str(code) message = str(message) if len(code) > 200: code = code[0:200] + "..." if len(message) > 200: message = message[0:200] + "..." err_msg = Label("Server Error or invalid response: ERROR " + str(code) + " - " + str(message)) err_msg.addStyleName("status") Window.alert(err_msg.getText())
class MenuCmd: def __init__(self, menu, command): self.menu = menu self.command = command def execute(self): if self.command in ('Beginner', 'Intermediate', 'Expert', 'Custom'): body = doc().getElementsByTagName('body').item(0) body.setAttribute('id', self.command) modes = { 'New': [(0, 0), 0], 'Beginner': [(8, 8), 1], 'Intermediate': [(16, 16), 2], 'Expert': [(16, 32), 3] } level = modes.get(self.command) if level: if level[1]: self.menu.game.level = level[1] self.menu.game.next_game(level[0]) elif self.command == 'Custom': self.menu.game.level = 4 self.show_custom() elif self.command == 'Instructions': pass elif self.command == 'About': self.show_about() def show_custom(self): self.dialog = DialogBox(StyleName='custom-dialog') self.dialog.setHTML('Custom Settings') contents = VerticalPanel(StyleName='contents') self.dialog.setWidget(contents) # contents of contents rows = HorizontalPanel() columns = HorizontalPanel() bombs = HorizontalPanel() buttons = HorizontalPanel() for each in (rows, columns, bombs, buttons): contents.add(each) rows.add(Label('Rows:')) self.row = TextBox() rows.add(self.row) columns.add(Label('Columns:')) self.column = TextBox() columns.add(self.column) bombs.add(Label('Bombs:')) self.bomb = TextBox() bombs.add(self.bomb) buttons.add(Button("OK", getattr(self, 'new_game'))) buttons.add(Button("Cancel", getattr(self, 'close_dialog'))) left = (Window.getClientWidth() - 201) / 2 top = (Window.getClientHeight() - 190) / 2 self.dialog.setPopupPosition(left, top) self.dialog.show() def new_game(self, event): try: row = int(self.row.getText()) except: Window.alert('Invalid number in rows') return try: column = int(self.column.getText()) except: Window.alert('Invalid number in columns') return try: bomb = int(self.bomb.getText()) except: bomb = 0 if bomb >= (row * column): Window.alert("Number of bombs should not be greater than " \ "rows x columns.") else: self.menu.game.next_game((row, column), bomb) self.close_dialog() def close_dialog(self, event): self.dialog.hide() def show_about(self): self.dialog = PopupPanel(StyleName='about', autoHide=True) contents = HTMLPanel('', StyleName='contents') self.dialog.setWidget(contents) html = '<p class="pyjamas">MineSweeper written in Python with ' \ '<a href="http://pyjs.org" target="_blank">Pyjamas</a><p>' \ '<p class="comments">Send comments to ' \ '<a href="mailto:[email protected]">' \ '[email protected]</a>.<p>' contents.setHTML(html) left = (Window.getClientWidth() - 294) / 2 top = (Window.getClientHeight() - 112) / 2 self.dialog.setPopupPosition(left, top) self.dialog.show()
class Milestones_Editor(SimplePanel): ''' Create and edit projects ''' def __init__(self): # We need to use old form of inheritance because of pyjamas SimplePanel.__init__(self) self.hpanel = HorizontalPanel(Width='755px') self.hpanel.setVerticalAlignment(HasAlignment.ALIGN_TOP) self.name = TextBox() self.name.setStyleName('form-control') self.start = Report_Date_Field(cal_ID='start') self.start.getTextBox().setStyleName('form-control') self.start.setRegex(DATE_MATCHER) self.start.appendValidListener(self._display_ok) self.start.appendInvalidListener(self._display_error) self.start.validate(None) self.end = Report_Date_Field(cal_ID='end') self.end.getTextBox().setStyleName('form-control') self.end.setRegex(DATE_MATCHER) self.end.appendValidListener(self._display_ok) self.end.appendInvalidListener(self._display_error) self.end.validate(None) self.status = ListBox() self.status.addItem('Active') self.status.addItem('Inactive') self.status.setVisibleItemCount(0) self.status.setStyleName('form-control input-lg') self.status.setSize('100px', '34px') spacer1 = Label(Width='10px') spacer2 = Label(Width='10px') spacer3 = Label(Width='10px') self.add_btn = Button('Add') self.add_btn.setStyleName('btn btn-primary') self.del_btn = Button('Delete') self.del_btn.setStyleName('btn btn-danger') self.hpanel.add(self.name) self.hpanel.add(spacer1) self.hpanel.add(self.status) self.hpanel.add(spacer2) self.hpanel.add(self.start) #self.hpanel.add(spacer3) self.hpanel.add(self.end) self.hpanel.add(self.add_btn) self.hpanel.add(Label(Width='10px')) self.hpanel.add(self.del_btn) def get_name_txt(self): '''Return project name. ''' return self.name.getText() def get_status(self): '''Return project status. ''' return self.status.getItemText(self.status.getSelectedIndex()) def get_milestone_data(self): '''Return all data for a milestone and validation result. ''' valid = False name_txt = self.get_name_txt() status_txt = self.get_status() start_txt = self.start.getTextBox().getText() end_txt = self.end.getTextBox().getText() data = [name_txt, status_txt, start_txt, end_txt] # We are only valid if these conditions are met if len(name_txt.strip()) > 0 and self.start.valid == True and self.end.valid == True: valid = True return (valid, data) def _display_ok(self, obj): obj.setStyleName('form-input') def _display_error(self, obj): if len(obj.getTextBox().getText()) > 0: obj.setStyleName('form-group has-error')
class CompaniesAppGUI(AbsolutePanel): def __init__(self): AbsolutePanel.__init__(self) self.app = CompaniesApp() self.history = [] self.save = Button("save", self) self.selectDepartment = Button("select", self) self.selectEmployee = Button("select", self) self.edit = Button("edit", self) self.cut = Button("cut", self) self.back = Button("back", self) self.name = TextBox() self.address = TextBox() self.manager = TextBox() self.departments = ListBox(Size=("100%"), VisibleItemCount="5") self.employees = ListBox(Size=("100%"), VisibleItemCount="5") self.total = TextBox() self.errors = VerticalPanel() self.grid = Grid() self.allPanels = VerticalPanel() self.allPanels.add(self.grid) self.allPanels.add(self.errors) self.add(self.allPanels) self.initCompanyGUI() def onClick(self, sender): self.errors.clear() if sender == self.cut: self.current.cut() self.total.setText(self.current.total()) if sender == self.save: if self.current.__class__.__name__ == "Employee": if self.validateEmployee(self.current.id, self.name.getText(), self.address.getText(), self.total.getText()) == True: self.current.save(self.name.getText(), self.address.getText(), float(self.total.getText())) else: if self.validateDepartment(self.current.id, self.name.getText()) == True: self.current.save(self.name.getText()) if sender == self.selectDepartment: if (self.departments.getSelectedIndex() > -1): self.history.append(self.current) self.current = self.app.getDepartment(self.departments.getValue(self.departments.getSelectedIndex())) self.initDepartmentGUI() if sender == self.selectEmployee: if (self.employees.getSelectedIndex() > -1): self.history.append(self.current) self.current = self.app.getEmployee(self.employees.getValue(self.employees.getSelectedIndex())) self.initEmployeeGUI() if sender == self.edit: self.history.append(self.current) self.current = self.current.getManager() self.initEmployeeGUI() if sender == self.back: if len(self.history) > 0: self.current = self.history.pop() if self.current.__class__.__name__ == "Company": self.initCompanyGUI() else: self.initDepartmentGUI() def validateDepartment(self, index, name): valid = True if name == "": self.errors.add(Label("- Enter a valid name, please.")) valid = False for item in self.app.departments: if item.id != index and name == item.name: self.errors.add(Label("- There is already a department with the same name. Enter a valid name, please.")) valid = False return valid def validateEmployee(self, index, name, address, salary): valid = True if name == "": self.errors.add(Label("- Enter a valid name, please.")) valid = False if address == "": self.errors.add(Label("- Enter a valid address, please.")) valid = False if salary == "": self.errors.add(Label("- Enter a valid salary, please.")) valid = False try: float(salary) except ValueError: self.errors.add(Label("- The salary must be a number. Enter a valid salary, please.")) valid = False for item in self.app.employees: if item.id != index and name == item.name and item.address == address: self.errors.add(Label("- There is already an employee with the same name and address combination. Enter a valid name and address, please.")) valid = False return valid def initCompanyGUI(self): self.current = self.app.company self.grid.clear() self.grid.resize(4, 3) # row 1 self.grid.setWidget(0, 0, Label("Name:")) self.grid.setWidget(1, 0, Label("Department:")) self.grid.setWidget(2, 0, Label("Total:")) # row 2 self.grid.setWidget(0, 1, self.name) self.grid.setWidget(1, 1, self.departments) self.grid.setWidget(2, 1, self.total) # row 3 self.grid.setWidget(0, 2, self.save) self.grid.setWidget(1, 2, self.selectDepartment) self.grid.setWidget(2, 2, self.cut) self.name.setText(self.current.name) self.departments.clear() for item in self.current.departments: self.departments.addItem(item.name, item.id) if self.departments.getItemCount() > 0: self.departments.setSelectedIndex(0) self.total.setText(self.current.total()) def initDepartmentGUI(self): self.grid.clear() self.grid.resize(6, 3) # row 1 self.grid.setWidget(0, 0, Label("Name:")) self.grid.setWidget(1, 0, Label("Manager:")) self.grid.setWidget(2, 0, Label("Department:")) self.grid.setWidget(3, 0, Label("Employee:")) self.grid.setWidget(4, 0, Label("Total:")) # row 2 self.grid.setWidget(0, 1, self.name) self.grid.setWidget(1, 1, self.manager) self.grid.setWidget(2, 1, self.departments) self.grid.setWidget(3, 1, self.employees) self.grid.setWidget(4, 1, self.total) # row 3 self.grid.setWidget(0, 2, self.save) self.grid.setWidget(1, 2, self.edit) self.grid.setWidget(2, 2, self.selectDepartment) self.grid.setWidget(3, 2, self.selectEmployee) self.grid.setWidget(4, 2, self.cut) # back self.grid.setWidget(5, 2, self.back) self.name.setText(self.current.name) self.departments.clear() self.employees.clear() for item in self.current.departments: self.departments.addItem(item.name, item.id) if self.departments.getItemCount() > 0: self.departments.setSelectedIndex(0) for item in self.current.employees: if item.manager == 0: self.employees.addItem(item.name, item.id) else: self.manager.setText(item.name) if self.employees.getItemCount() > 0: self.employees.setSelectedIndex(0) self.total.setText(self.current.total()) def initEmployeeGUI(self): self.grid.clear() self.grid.resize(4, 3) # row 1 self.grid.setWidget(0, 0, Label("Name:")) self.grid.setWidget(1, 0, Label("Address:")) self.grid.setWidget(2, 0, Label("Salary:")) # row 2 self.grid.setWidget(0, 1, self.name) self.grid.setWidget(1, 1, self.address) self.grid.setWidget(2, 1, self.total) # row 3 self.grid.setWidget(0, 2, self.save) self.grid.setWidget(2, 2, self.cut) self.grid.setWidget(3, 2, self.back) self.name.setText(self.current.name) self.address.setText(self.current.address) self.total.setText(self.current.salary)
class MenuCmd: def __init__(self, menu, command): self.menu = menu self.command = command def execute(self): if self.command in ('Beginner', 'Intermediate', 'Expert', 'Custom'): body = doc().getElementsByTagName('body').item(0) body.setAttribute('id', self.command) modes = {'New': [(0, 0), 0], 'Beginner': [(8, 8), 1], 'Intermediate': [(16, 16), 2], 'Expert': [(16, 32), 3]} level = modes.get(self.command) if level: if level[1]: self.menu.game.level = level[1] self.menu.game.next_game(level[0]) elif self.command == 'Custom': self.menu.game.level = 4 self.show_custom() elif self.command == 'Instructions': pass elif self.command == 'About': self.show_about() def show_custom(self): self.dialog = DialogBox(StyleName='custom-dialog') self.dialog.setHTML('Custom Settings') contents = VerticalPanel(StyleName='contents') self.dialog.setWidget(contents) # contents of contents rows = HorizontalPanel() columns = HorizontalPanel() bombs = HorizontalPanel() buttons = HorizontalPanel() for each in (rows, columns, bombs, buttons): contents.add(each) rows.add(Label('Rows:')) self.row = TextBox() rows.add(self.row) columns.add(Label('Columns:')) self.column = TextBox() columns.add(self.column) bombs.add(Label('Bombs:')) self.bomb = TextBox() bombs.add(self.bomb) buttons.add(Button("OK", getattr(self, 'new_game'))) buttons.add(Button("Cancel", getattr(self, 'close_dialog'))) left = (Window.getClientWidth() - 201) / 2 top = (Window.getClientHeight() - 190) / 2 self.dialog.setPopupPosition(left, top) self.dialog.show() def new_game(self, event): try: row = int(self.row.getText()) except: Window.alert('Invalid number in rows') return try: column = int(self.column.getText()) except: Window.alert('Invalid number in columns') return try: bomb = int(self.bomb.getText()) except: bomb = 0 if bomb >= (row * column): Window.alert("Number of bombs should not be greater than " \ "rows x columns.") else: self.menu.game.next_game((row, column), bomb) self.close_dialog() def close_dialog(self, event): self.dialog.hide() def show_about(self): self.dialog = PopupPanel(StyleName='about', autoHide=True) contents = HTMLPanel('', StyleName='contents') self.dialog.setWidget(contents) html = '<p class="pyjamas">MineSweeper written in Python with ' \ '<a href="http://pyjs.org" target="_blank">Pyjamas</a><p>' \ '<p class="comments">Send comments to ' \ '<a href="mailto:[email protected]">' \ '[email protected]</a>.<p>' contents.setHTML(html) left = (Window.getClientWidth() - 294) / 2 top = (Window.getClientHeight() - 112) / 2 self.dialog.setPopupPosition(left, top) self.dialog.show()
class Index: def onModuleLoad(self): self.remote_py = MyBlogService() # Create a FormPanel and point it at a service. self.form = FormPanel() # Create a panel to hold all of the form widgets. vp=VerticalPanel(BorderWidth=0,HorizontalAlignment=HasAlignment.ALIGN_CENTER,VerticalAlignment=HasAlignment.ALIGN_MIDDLE,Width="100%",Height="150px") self.form.setWidget(vp) header=HTML("<h2>LOGIN TO YOUR ACCOUNT</h2>") part1=header # Create a TextBox, giving it a name so that it will be submitted. self.userName = TextBox() self.userName.setName("userNameFormElement") self.userName.setPlaceholder("User Name") part2=self.userName self.password = PasswordTextBox() self.password.setName("passwordFormElement") self.password.setPlaceholder("Password") part3=self.password self.errorInfoLabel = Label() self.errorInfoLabel.setStyleName('error-info') part4=self.errorInfoLabel part4.setStyleName("errorlabel") # Add a 'submit' button. hpanel = HorizontalPanel(BorderWidth=0,HorizontalAlignment=HasAlignment.ALIGN_CENTER,VerticalAlignment=HasAlignment.ALIGN_MIDDLE,Width="100%",Height="50px") partb=Button("Login", self) partb.setStyleName('btn') image=Label("Don''t have account? Sign up") anchor = Anchor(Widget=image, Href='/signup.html') parta=anchor hpanel.add(partb) hpanel.add(parta) part5=hpanel part5.setStyleName("hpanel") vp.add(part1) vp.add(part2) vp.add(part3) vp.add(part4) vp.add(part5) vp.setStyleName("signup") # Add an event handler to the form. self.form.addFormHandler(self) RootPanel().add(self.form) def onClick(self, sender): if (len(self.userName.getText()) == 0 or len(self.password.getText()) == 0): self.errorInfoLabel.setText("Username or Password required") else: self.errorInfoLabel.setText('') self.authenticateUser() def authenticateUser(self): self.remote_py.callMethod('authenticateUser', [self.userName.getText(), self.password.getText()], self) def onRemoteResponse(self, response, requestInfo): self.errorInfoLabel.setText('') d = datetime.date.today() + datetime.timedelta(days=1) setCookie("LoggedInUser", response, d, path='/') loggedInUser = json.loads(response) if loggedInUser["is_superuser"] == True: Window.setLocation("/admin.html") else: Window.setLocation("/home.html") def onRemoteError(self, code, error_dict, requestInfo): if code == 401: self.errorInfoLabel.setText("Invalid Credentials. Please try again.")
class StockWatcher: def onModuleLoad(self): ''' This is the main entry point method. ''' # Setup JSON RPC self.remote = DataService() # Initialize member variables self.mainPanel = VerticalPanel() self.stocksFlexTable = FlexTable() self.addPanel = HorizontalPanel() self.newSymbolTextBox = TextBox() self.lastUpdatedLabel = Label() self.addStockButton = Button('Add', self.addStock) self.stocks = [] self.stocksTableColumns = ['Symbol', 'Price', 'Change', 'Remove'] # Add styles to elements in the stock list table self.stocksFlexTable.getRowFormatter().addStyleName(0, 'watchListHeader') self.stocksFlexTable.addStyleName('watchList') self.stocksFlexTable.getCellFormatter().addStyleName(0, 1, 'watchListNumericColumn') self.stocksFlexTable.getCellFormatter().addStyleName(0, 2, 'watchListNumericColumn') self.stocksFlexTable.getCellFormatter().addStyleName(0, 3, 'watchListRemoveColumn') # Create table for stock data for i in range(len(self.stocksTableColumns)): self.stocksFlexTable.setText(0, i, self.stocksTableColumns[i]) # Assemble Add Stock panel self.addPanel.add(self.newSymbolTextBox) self.addPanel.add(self.addStockButton) self.addPanel.addStyleName('addPanel') # Assemble Main panel self.mainPanel.add(self.stocksFlexTable) self.mainPanel.add(self.addPanel) self.mainPanel.add(self.lastUpdatedLabel) # Associate the Main panel with the HTML host page RootPanel().add(self.mainPanel) # Move cursor focus to the input box self.newSymbolTextBox.setFocus(True) # Setup timer to refresh list automatically refresh = self.refreshWatchlist class MyTimer(Timer): def run(self): refresh() refreshTimer = MyTimer() refreshTimer.scheduleRepeating(5000) # Listen for keyboard events in the input box self_addStock = self.addStock class StockTextBox_KeyboardHandler(): def onKeyPress(self, sender, keycode, modifiers): if keycode == KEY_ENTER: self_addStock() def onKeyDown(self, sender, keycode, modifiers): return def onKeyUp(self, sender, keycode, modifiers): return self.newSymbolTextBox.addKeyboardListener(StockTextBox_KeyboardHandler()) # Load the stocks self.remote.getStocks(self) def addStock(self, sender, symbol=None): ''' Add stock to FlexTable. Executed when the user clicks the addStockButton or presses enter in the newSymbolTextBox ''' if symbol is None: # Get the symbol symbol = self.newSymbolTextBox.getText().upper().trim() self.newSymbolTextBox.setText('') # Don't add the stock if it's already in the table if symbol in self.stocks: return # Tell the server that we're adding this stock self.remote.addStock(symbol, self) self.newSymbolTextBox.setFocus(True) # Stocks code must be between 1 and 10 chars that are numbers/letters/dots p = re.compile('^[0-9A-Z\\.]{1,10}$') if p.match(symbol) == None: Window.alert('"%s" is not a valid symbol.' % symbol) self.newSymbolTextBox.selectAll() return # Add the stock to the table row = self.stocksFlexTable.getRowCount() self.stocks.append(symbol) self.stocksFlexTable.setText(row, 0, symbol) self.stocksFlexTable.setWidget(row, 2, Label()) self.stocksFlexTable.getCellFormatter().addStyleName(row, 1, 'watchListNumericColumn') self.stocksFlexTable.getCellFormatter().addStyleName(row, 2, 'watchListNumericColumn') self.stocksFlexTable.getCellFormatter().addStyleName(row, 3, 'watchListRemoveColumn') # Add a button to remove this stock from the table def _removeStockButton_Click(event): if symbol not in self.stocks: return removedIndex = self.stocks.index(symbol) self.remote.deleteStock(symbol, self) self.stocks.remove(symbol) self.stocksFlexTable.removeRow(removedIndex + 1) removeStockButton = Button('x', _removeStockButton_Click) removeStockButton.addStyleDependentName('remove') self.stocksFlexTable.setWidget(row, 3, removeStockButton) # Get the stock price self.refreshWatchlist() def refreshWatchlist(self): ''' Update the price change for each stock ''' MAX_PRICE = 100.0 MAX_PRICE_CHANGE = 0.02 prices = [] for i in range(len(self.stocks)): price = random.random() * MAX_PRICE change = price * MAX_PRICE_CHANGE * (random.random() * 2.0 - 1.0) prices.append(StockPrice(self.stocks[i], price, change)) self.updateTable(prices) def updateTable(self, prices): ''' Update the price and change fields of all the rows in the stock table prices -- List of StockPrice objects for all rows ''' # Type checking assert isinstance(prices, list) for price in prices: assert isinstance(price, StockPrice) # Nothing to do... if len(prices) == 0: return # Update each individual row for i in range(len(prices)): self.updateRow(prices[i]) # Display timestamp showing last refresh self.lastUpdatedLabel.setText("Last update: %s" % datetime.datetime.now().strftime("%m/%d/%Y %I:%M:%S %p")) def updateRow(self, price): ''' Update a single row in the stock table price -- StockPrice object for a single row ''' # Type checking assert isinstance(price, StockPrice) # Make sure the stock is still in the stock table if price.symbol not in self.stocks: return # Find the index of row = self.stocks.index(price.symbol) + 1 # Populate the price and change fields with new data self.stocksFlexTable.setText(row, 1, '%.2f' % price.price) changeWidget = self.stocksFlexTable.getWidget(row, 2) changeWidget.setText('%.2f (%.2f%%)' % (price.change, price.getChangePercent())) # Change the color of the text in the Change field based on its value changeStyleName = 'noChange' if price.getChangePercent() < -0.1: changeStyleName = 'negativeChange' else: changeStyleName = 'positiveChange' changeWidget.setStyleName(changeStyleName) def onRemoteResponse(self, response, request_info): ''' Called when a response is received from a RPC. ''' if request_info.method in DataService.methods: # Compare self.stocks and the stocks in response stocks_set = set(self.stocks) response_set = set(response) # Add the differences for symbol in list(response_set.difference(stocks_set)): self.addStock(None, symbol) else: Window.alert('Unrecognized JSONRPC method.') def onRemoteError(self, code, message, request_info): Window.alert(message)
class UserForm(AbsolutePanel): MODE_ADD = "modeAdd" MODE_EDIT = "modeEdit" user = None mode = None usernameInput = None firstInput = None lastInput = None emailInput = None passwordInput = None confirmInput = None departmentCombo = None addBtn = None cancelBtn = None def __init__(self, parent): AbsolutePanel.__init__(self) ftable = FlexTable() ftable.setWidget(0, 0, Label("First Name", wordWrap=False)) ftableFormatter = ftable.getFlexCellFormatter() self.firstInput = TextBox() self.firstInput.addChangeListener(self.checkValid) self.firstInput.addKeyboardListener(self) ftable.setWidget(0, 1, self.firstInput) ftable.setWidget(1, 0, Label("Last Name", wordWrap=False)) self.lastInput = TextBox() self.lastInput.addChangeListener(self.checkValid) self.lastInput.addKeyboardListener(self) ftable.setWidget(1, 1, self.lastInput) ftable.setWidget(2, 0, Label("Email", wordWrap=False)) self.emailInput = TextBox() self.emailInput.addChangeListener(self.checkValid) self.emailInput.addKeyboardListener(self) ftable.setWidget(2, 1, self.emailInput) w = Label("* Username", wordWrap=False) w.addMouseListener(TooltipListener("Required, not changable")) ftable.setWidget(3, 0, w) self.usernameInput = TextBox() self.usernameInput.addChangeListener(self.checkValid) self.usernameInput.addKeyboardListener(self) ftable.setWidget(3, 1, self.usernameInput) w = Label("* Password", wordWrap=False) w.addMouseListener(TooltipListener("Required")) ftable.setWidget(4, 0, w) self.passwordInput = PasswordTextBox() self.passwordInput.addChangeListener(self.checkValid) self.passwordInput.addKeyboardListener(self) ftable.setWidget(4, 1, self.passwordInput) w = Label("* Confirm", wordWrap=False) w.addMouseListener(TooltipListener("Required")) ftable.setWidget(5, 0, w) self.confirmInput = PasswordTextBox() self.confirmInput.addChangeListener(self.checkValid) self.confirmInput.addKeyboardListener(self) ftable.setWidget(5, 1, self.confirmInput) w = Label("* Department", wordWrap=False) w.addMouseListener(TooltipListener("Required")) ftable.setWidget(6, 0, w) self.departmentCombo = ListBox() self.departmentCombo.addChangeListener(self.checkValid) self.departmentCombo.addKeyboardListener(self) ftable.setWidget(6, 1, self.departmentCombo) hpanel = HorizontalPanel() self.addBtn = Button("Add User") self.addBtn.setEnabled(False) hpanel.add(self.addBtn) self.cancelBtn = Button("Cancel") hpanel.add(self.cancelBtn) ftable.setWidget(7, 0, hpanel) ftableFormatter.setColSpan(7, 0, 2) self.add(ftable) self.clearForm() return def clearForm(self): self.user = None self.usernameInput.setText('') self.firstInput.setText('') self.lastInput.setText('') self.emailInput.setText('') self.passwordInput.setText('') self.confirmInput.setText('') self.departmentCombo.setItemTextSelection(None) self.updateMode(self.MODE_ADD) self.checkValid() def updateUser(self, user): def setText(elem, value): if value: elem.setText(value) else: elem.setText("") self.user = user setText(self.usernameInput, self.user.username) setText(self.firstInput, self.user.fname) setText(self.lastInput, self.user.lname) setText(self.emailInput, self.user.email) setText(self.passwordInput, self.user.password) setText(self.confirmInput, self.user.password) self.departmentCombo.setItemTextSelection([self.user.department]) self.checkValid() def updateDepartmentCombo(self, choices, default_): self.departmentCombo.clear() for choice in choices: self.departmentCombo.addItem(choice) self.departmentCombo.selectValue(default_) def updateMode(self, mode): self.mode = mode if self.mode == self.MODE_ADD: self.addBtn.setText("Add User") else: self.addBtn.setText("Update User") def checkValid(self, evt=None): if self.enableSubmit(self.usernameInput.getText(), self.passwordInput.getText(), self.confirmInput.getText(), self.departmentCombo.getSelectedItemText(True)): self.addBtn.setEnabled(True) else: self.addBtn.setEnabled(False) def enableSubmit(self, u, p, c, d): return (len(u) > 0 and len(p) > 0 and p == c and len(d) > 0) def onClick(self, sender): pass def onKeyUp(self, sender, keyCode, modifiers): self.checkValid() def onKeyDown(self, sender, keyCode, modifiers): pass def onKeyPress(self, sender, keyCode, modifiers): pass
class PopupOpenState(Popup): def __init__(self, okClick, cancelClick, title='Abrir', options=CONFIRM_CANCEL): Popup.__init__(self, title, okClick, cancelClick, options) def draw(self): Popup.draw(self) namePanel = HorizontalPanel() #namePanel.add(Label('Crie um arquivo')) if self.title == 'Abrir': self.enableOkButton(False) namePanel.add(HTML("""<div class=""gwt-Label"" style=""white-space: normal;""> Abra o arquivo salvo, copie<br>e cole aqui o conteudo:</div>""")) self.field = FileUpload() self.field.setName('file') self.field.setID('files') self.center.add(self.field) element = self.field.getElement() JS("""function handleFileSelect(evt) {@{{self}}.enableOkButton(evt.target.files[0]!=null);} @{{element}}.addEventListener('change', handleFileSelect, false);""") #http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml else: namePanel.add(HTML("""<div class=""gwt-Label"" style=""white-space: normal;""> Crie um arquivo txt e copie<br>e cole o conteudo a seguir:</div>""")) self.textBox = TextBox() self.textBox.setStyleAttribute('marginLeft', 10) namePanel.add(self.textBox) self.center.add(namePanel) self.textBox.addInputListener(self) self.onInput() def enableOkButton(self, enable): if enable: self.okButton.removeStyleName('disabled') else: self.okButton.addStyleName('disabled') def onInput(self, sender): self.enableOkButton(self.textBox.getText().count(' ') != len(self.textBox.getText())) def myOkClick(self): if 'disabled' not in self.okButton.getStyleName(): Popup.myOkClick(self) if self.okClick is not None: if self.title == 'Abrir': files = getattr(self.field.getElement(), 'files') file = JS("@{{files}}[0]") if file: JS("""var reader = new FileReader(); reader.onload = function(e) {@{{self}}.okClick(e.target.result);} reader.readAsBinaryString(@{{file}});""") #self.okClick(str) else: self.okClick(self.textBox.getText()) def myCancelClick(self): Popup.myCancelClick(self) if self.cancelClick is not None: self.cancelClick() def show(self): Popup.show(self) if self.title != 'Abrir': self.textBox.setFocus(True) else: pass
class Impediments(SimplePanel): ''' Create and edit projects ''' def __init__(self, start_date, can_delete=True): # We need to use old form of inheritance because of pyjamas SimplePanel.__init__(self) self.vpanel = VerticalPanel() desc_panel = VerticalPanel() self.desc_box = TextBox() self.desc_box.setVisibleLength(44) self.desc_box.setStyleName('form-control') desc_lbl = Label('impediment description') desc_lbl.setStyleName('text-muted') desc_panel.add(self.desc_box) desc_panel.add(desc_lbl) # Set to False if loaded from database self.can_delete = can_delete status_panel = VerticalPanel() self.status_lst = ListBox(Height='34px') self.status_lst.setStyleName('form-control input-lg') self.status_lst.addItem('Open') self.status_lst.addItem('Closed') # we put date here self.status_lbl = Label('') self.set_start_date(start_date) self.status_lbl.setStyleName('text-muted') status_panel = VerticalPanel() status_panel.add(self.status_lst) status_panel.add(self.status_lbl) self.comment = Text_Area_Row('', 'why it exists or is being closed') hpanel = HorizontalPanel() hpanel.add(desc_panel) hpanel.add(Label(Width='10px')) hpanel.add(status_panel) self.vpanel.add(hpanel) self.vpanel.add(self.comment.panel()) def set_start_date(self, start_date): date_str = 'added on: ' + start_date self.status_lbl.setText(date_str) def get_impediment_data(self): '''Get impediment data as a list suitable to passing to model. ''' desc = self.desc_box.getText() comment = self.comment.widget().getText() state = self.status_lst.getItemText(self.status_lst.getSelectedIndex()) lbl_text = self.status_lbl.getText() # ind = lbl_text.find(':') + 1 # We need just date start_date = lbl_text[ind:].strip() if state == 'Open': end_date = None else: end_date = datetime.date.today().strftime('%d/%m/%Y') return (desc, comment, start_date, end_date, state)
class Photos(Composite): def __init__(self): Composite.__init__(self) self.albums = [] self.photos = [] self.grid = Grid(4, 4, CellPadding=4, CellSpacing=4) self.grid.addTableListener(self) self.drill = 0 self.pos = 0 self.up = Button("Up", self) self.next = Button("Next", self) self.prev = Button("Prev", self) self.timer = Timer(notify=self) self.userid = "jameskhedley" self.album_url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "?alt=json-in-script&kind=album&hl=en_US&callback=restCb" self.doRESTQuery(self.album_url, self.timer) self.vp = VerticalPanel() self.disclosure = DisclosurePanel( "Click for boring technical details.") self.disclosure.add( HTML( '''<p>OK so you want to write client JS to do a RESTful HTTP query from picasa right? Well you can't because of the Same Origin Policy. Basically this means that because the domain of the query and the domain of the hosted site are different, then that could well be a cross-site scripting (XSS) attack. So, the workaround is to do the call from a script tag so the JSON we get back is part of the document. But since we don't know what URL to hit yet, once we find out then we have to inject a new script tag dynamically which the browser will run as soon as we append it. To be honest I'm not 100% why Google use RESTful services and not JSON-RPC or somesuch, which would be easier. Well, easier for me.''')) self.IDPanel = HorizontalPanel() self.IDPanel.add(Label("Enter google account:")) self.IDButton = Button("Go", self) self.IDBox = TextBox() self.IDBox.setText(self.userid) self.IDPanel.add(self.IDBox) self.IDPanel.add(self.IDButton) self.vp.add(self.IDPanel) self.vp.add(self.disclosure) self.vp.add(self.grid) self.initWidget(self.vp) def doRESTQuery(self, url, timer): """this is a totally different from an RPC call in that we have to dynamically add script tags to the DOM when we want to query the REST API. These rely on callbacks in the DOM so we can either add them dynamically or pre-define them in public/Main.html. Once we've done that have to wait for the response. Which means we need to provide a listener for the timer""" new_script = DOM.createElement("script") DOM.setElemAttribute(new_script, "src", url) DOM.setElemAttribute(new_script, "type", "text/javascript") doc().body.appendChild(new_script) self.timer.schedule(100) def onCellClicked(self, sender, row, col): if self.drill == 0: self.drill += 1 self.vp.clear() self.grid.clear() self.vp.add(self.up) self.vp.add(self.grid) gridcols = self.grid.getColumnCount() album = self.albums[row + col + (row * (gridcols - 1))] url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "/albumid/" + album[ "id"] + "?alt=json-in-script&kind=photo&hl=en_US&callback=restCb" self.doRESTQuery(url, self.timer) elif self.drill == 1: self.drill += 1 gridcols = self.grid.getColumnCount() self.pos = row + col + (row * (gridcols - 1)) photo = self.photos[self.pos] self.vp.clear() self.fullsize = HTML('<img src="' + photo["full"] + '"/>') hp = HorizontalPanel() hp.add(self.up) hp.add(self.prev) hp.add(self.next) hp.setSpacing(8) self.vp.add(hp) self.vp.add(self.fullsize) def onClick(self, sender): if sender == self.IDButton: self.userid = self.IDBox.getText() if self.userid == "" or self.userid.isdigit(): return self.drill = 0 self.album_url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "?alt=json-in-script&kind=album&hl=en_US&callback=restCb" self.grid.clear() self.doRESTQuery(self.album_url, self.timer) else: if self.drill == 2: if sender == self.up: self.drill = 1 self.vp.clear() self.vp.add(self.up) self.vp.add(self.grid) self.fillGrid(self.photos, "photos") else: if sender == self.next: if self.pos >= len(self.photos): return self.pos += 1 elif sender == self.prev: if self.pos < 1: return self.pos -= 1 photo = self.photos[self.pos] self.fullsize.setHTML('<img src="' + photo["full"] + '"/>') elif self.drill == 1: self.drill = 0 self.vp.clear() self.vp.add(self.IDPanel) self.vp.add(self.disclosure) self.vp.add(self.grid) self.fillGrid(self.albums, "albums") def onTimer(self, timer): fd = doc().getElementById("__pygwt_hiddenData") receiver = fd.innerHTML if receiver == 'wait': self.timer.schedule(1000) return fd.innerHTML = 'wait' if self.drill == 0: self.parseAlbums(receiver) self.fillGrid(self.albums, "albums") elif self.drill == 1: self.parsePhotos(receiver) self.fillGrid(self.photos, "photos") def fillGrid(self, items, type): self.grid.clear() cols = self.grid.getColumnCount() self.grid.resizeRows((len(items) / cols) + 1) rows = self.grid.getRowCount() for i in range(len(items)): vp = VerticalPanel() if type == 'photos': vp.add(items[i]['thumb']) else: vp.add(items[i]['thumb']) vp.add(items[i]['title']) self.grid.setWidget(int(i / cols), i % cols, vp) def parsePhotos(self, items): photo_list = json.loads(items) self.photos = [] for ph in photo_list: aphoto = {} aphoto['thumb'] = HTML( '<img src="' + ph[u"media$group"][u"media$thumbnail"][1][u"url"] + '"/>') aphoto['full'] = ph[u"media$group"][u"media$content"][0][u"url"] self.photos.append(aphoto) def parseAlbums(self, items): album_list = json.loads(items) self.albums = [] for al in album_list: analbum = {} analbum['title'] = HTML(al[u"title"][u"$t"]) analbum['thumb'] = HTML( '<img src="' + al[u"media$group"][u"media$thumbnail"][0][u"url"] + '"/>') url = al[u"id"][u"$t"] analbum['id'] = url.split(u'albumid/')[1].split(u'?alt')[0] self.albums.append(analbum)
class MovieRatings: def onModuleLoad(self): # Setup JSON RPC self.remote = DataService() ### Initialize member variables self.mainPanel = HorizontalPanel() self.rightPanel = VerticalPanel() self.moviesPanel = VerticalPanel() self.topRatedPanel = VerticalPanel() self.categoriesPanel = VerticalPanel() self.moviesFlexTable = FlexTable() self.topRatedMoviesFlexTable = FlexTable() self.topCategoryMoviesFlexTable = FlexTable() self.lessThanFiveLabel = Label('There are less than 5 movies. Add more movies!') self.moviesListLabel = Label('Movies List') self.addPanel = VerticalPanel() self.newMovieCategoryTextBox = TextBox() self.newMovieNameTextBox = TextBox() self.newMovieRatingListBox = ListBox(False) self.addMovieButton = Button('Add', self.addMovieButton_Click) self.movies = [] self.topRatedMovies = [] self.categories = {} self.MAX_RATING = 10 ### Add Movie Panel # Add ratings to list box for i in range(self.MAX_RATING + 1): self.newMovieRatingListBox.addItem(str(i)) # Add label and textbox to horizontal panel self.labelPanel = HorizontalPanel() self.labelPanel.add(Label("Add a movie:")) self.categoryPanel = HorizontalPanel() self.categoryPanel.add(Label("Category: ")) self.categoryPanel.add(self.newMovieCategoryTextBox) self.namePanel = HorizontalPanel() self.namePanel.add(Label("Movie Name: ")) self.namePanel.add(self.newMovieNameTextBox) self.ratingPanel = HorizontalPanel() self.ratingPanel.add(Label("Movie Rating: ")) self.ratingPanel.add(self.newMovieRatingListBox) self.labelPanel.addStyleName("addLabel") self.labelPanel.setSpacing(5) self.categoryPanel.addStyleName("addPanel") self.categoryPanel.setSpacing(5) self.namePanel.addStyleName("addPanel") self.namePanel.setSpacing(5) self.ratingPanel.addStyleName("addPanel") self.ratingPanel.setSpacing(5) self.newMovieCategoryTextBox.addStyleName("addPanel-input") self.newMovieNameTextBox.addStyleName("addPanel-input") self.newMovieRatingListBox.addStyleName("addPanel-input") self.addPanel.add(self.labelPanel) self.addPanel.add(self.categoryPanel) self.addPanel.add(self.namePanel) self.addPanel.add(self.ratingPanel) self.addPanel.add(self.addMovieButton) self.addPanel.addStyleName("addPanel") self.addMovieButton.addStyleName('addButton') self.addPanel.add(self.addMovieButton) self.addPanel.addStyleName('addPanel') ### Movies table self.moviesFlexTable.setText(0, 1, "Category") self.moviesFlexTable.setText(0, 2, "Title") self.moviesFlexTable.setText(0, 3, "Rating") self.moviesFlexTable.addStyleName("movieList") self.moviesFlexTable.getRowFormatter().addStyleName(0, "listHeader") self.moviesFlexTable.setCellPadding(6) self.moviesFlexTable.getCellFormatter().setStyleName(0, 1, "listHeaderColumn") self.moviesFlexTable.getCellFormatter().setStyleName(0, 2, "listHeaderColumn") self.moviesListLabel.addStyleName("listLabel") self.moviesPanel.add(self.moviesListLabel) self.moviesPanel.add(self.moviesFlexTable) self.moviesPanel.setStyleName("moviesPanel") ### Top rated movies table self.topRatedMoviesFlexTable.setText(0, 0, "Category") self.topRatedMoviesFlexTable.setText(0, 1, "Title") self.topRatedMoviesFlexTable.setText(0, 2, "Rating") self.topRatedMoviesFlexTable.addStyleName("topMoviesList") self.topRatedMoviesFlexTable.getRowFormatter().addStyleName(0, "listHeader") self.topRatedMoviesFlexTable.setCellPadding(6) self.topRatedMoviesFlexTable.getCellFormatter().setStyleName(0, 0, "listHeaderColumn") self.topRatedMoviesFlexTable.getCellFormatter().setStyleName(0, 1, "listHeaderColumn") self.topRatedLabel = Label("Top 5 Rated Movies") self.topRatedLabel.addStyleName("listLabel") self.lessThanFiveLabel.addStyleName("noticeLabel") self.topRatedPanel.add(self.topRatedLabel) self.topRatedPanel.add(self.topRatedMoviesFlexTable) self.topRatedPanel.add(self.lessThanFiveLabel) self.topRatedPanel.setStyleName("topRatedPanel") ### Categories table self.topCategoryMoviesFlexTable.setText(0, 0, "Category") self.topCategoryMoviesFlexTable.setText(0, 1, "Top Movie") self.topCategoryMoviesFlexTable.setText(0, 2, "Average Rating") self.topCategoryMoviesFlexTable.addStyleName("topCategoryMoviesList") self.topCategoryMoviesFlexTable.getRowFormatter().addStyleName(0, "listHeader") self.topCategoryMoviesFlexTable.setCellPadding(6) self.topCategoryMoviesFlexTable.getCellFormatter().setStyleName(0, 0, "listHeaderColumn") self.topCategoryMoviesFlexTable.getCellFormatter().setStyleName(0, 1, "listHeaderColumn") self.categoriesLabel = Label("Movie Categories") self.categoriesLabel.addStyleName("listLabel") self.categoriesPanel.add(self.categoriesLabel) self.categoriesPanel.add(self.topCategoryMoviesFlexTable) self.categoriesPanel.setStyleName("categoriesPanel") ### Assemble Main panel self.rightPanel.add(self.topRatedPanel) self.rightPanel.add(self.categoriesPanel) self.mainPanel.add(self.moviesPanel) self.mainPanel.add(self.rightPanel) self.mainPanel.setStyleName("mainPanel") self.mainPanel.setSpacing(25) # Associate panels with the HTML host page RootPanel('addPanel').add(self.addPanel) RootPanel('main').add(self.mainPanel) # Move cursor focus to the input box self.newMovieNameTextBox.setFocus(True) # Load the movies self.remote.getMovies(self) def verifyInputs(self, name, category): if len(name) == 0: Window.alert("Movie name cannot be empty.") return False if len(name) > 100: Window.alert("Movie name is too long. Maximum length is 100 characters.") return False if len(category) == 0: Window.alert("Category cannot be empty.") return False p = re.compile('^[0-9A-Za-z\\.\\-\\(\\) ]{1,100}$') if p.match(category) == None: Window.alert('"%s" is not a valid category.' % category) return False return True def addMovieButton_Click(self, event): name = self.newMovieNameTextBox.getText().trim() cat = self.newMovieCategoryTextBox.getText().trim().lower() category = cat[0].upper() + cat[1:] rating = self.newMovieRatingListBox.getSelectedIndex() if not self.verifyInputs(name, category): return movie = Movie(name, category, rating) if movie in self.movies: Window.alert("'" + name + "' is already in table.") self.newMovieNameTextBox.selectAll() return self.remote.addMovie((name, category, rating), self) self.newMovieNameTextBox.setText('') def addMovie(self, sender, movie): self.movies.append(movie) row = self.moviesFlexTable.getRowCount() self.moviesFlexTable.setText(row, 1, movie.category) self.moviesFlexTable.setText(row, 2, movie.name) self.moviesFlexTable.setText(row, 3, movie.rating) # Adds buttons for remove, edit, save and cancel removeMovieButton = Button("x") editMovieButton = Button("Edit") saveButton = Button("Save") cancelButton = Button("Cancel") # Save and cancel are hidden by default saveButton.setVisible(False) cancelButton.setVisible(False) # Add buttons to row buttons = HorizontalPanel() buttons.add(removeMovieButton) buttons.add(editMovieButton) buttons.add(cancelButton) buttons.add(saveButton) self.moviesFlexTable.setWidget(row, 0, buttons) def removeMovieButton_Click(sender): self.remote.deleteMovie((movie.name, movie.category), self) removeMovieButton.addClickListener(removeMovieButton_Click) def editMovieButton_Click(sender): # Add textboxes and listbox editMovieButton.setVisible(False) cancelButton.setVisible(True) saveButton.setVisible(True) editCategory = TextBox() editName = TextBox() editRating = ListBox(False) for i in range(self.MAX_RATING + 1): editRating.addItem(str(i)) # Variable width textboxes catlen = len(movie.category) namelen = len(movie.name) if (catlen > 8): editCategory.setWidth(str(catlen*10) + "px") else: editCategory.setWidth("80px") if (namelen > 8): editName.setWidth(str(namelen*10) + "px") else: editName.setWidth("80px") self.moviesFlexTable.setWidget(row, 1, editCategory) self.moviesFlexTable.setWidget(row, 2, editName) self.moviesFlexTable.setWidget(row, 3, editRating) editCategory.setText(movie.category) editName.setText(movie.name) editRating.setSelectedIndex(movie.rating) editMovieButton.addClickListener(editMovieButton_Click) def saveButton_Click(sender): catText = self.moviesFlexTable.getWidget(row, 1) nameText = self.moviesFlexTable.getWidget(row, 2) ratingList = self.moviesFlexTable.getWidget(row, 3) newCategory = catText.getText().trim().lower() newCategory = newCategory[0].upper() + newCategory[1:] newName = nameText.getText().trim() newRating = ratingList.getSelectedIndex() if not self.verifyInputs(newName, newCategory): return # Removes temporarily to check for duplicates self.movies.remove(movie) newMovie = Movie(newName, newCategory, newRating) if newMovie in self.movies: Window.alert("'" + newName + "' is already in table.") nameText.selectAll() return self.remote.editMovie((movie.name, movie.category), (newMovie.name, newMovie.category, newMovie.rating), self) saveButton.addClickListener(saveButton_Click) def cancelButton_Click(sender): self.moviesFlexTable.remove(self.moviesFlexTable.getWidget(row, 1)) self.moviesFlexTable.remove(self.moviesFlexTable.getWidget(row, 2)) self.moviesFlexTable.remove(self.moviesFlexTable.getWidget(row, 3)) # Reverts fields to old movie info self.moviesFlexTable.setText(row, 1, movie.category) self.moviesFlexTable.setText(row, 2, movie.name) self.moviesFlexTable.setText(row, 3, movie.rating) cancelButton.setVisible(False) saveButton.setVisible(False) editMovieButton.setVisible(True) cancelButton.addClickListener(cancelButton_Click) def updateTopRatedMovies(self): numTopRated = len(self.topRatedMovies) self.clearTable(self.topRatedMoviesFlexTable) for row in range(numTopRated): self.topRatedMoviesFlexTable.setText(row+1, 0, self.topRatedMovies[row].category) self.topRatedMoviesFlexTable.setText(row+1, 1, self.topRatedMovies[row].name) self.topRatedMoviesFlexTable.setText(row+1, 2, self.topRatedMovies[row].rating) # Label should only be visible if less than 5 movies self.lessThanFiveLabel.setVisible(numTopRated < 5) def updateCategories(self): self.clearTable(self.topCategoryMoviesFlexTable) for row, cat in enumerate(self.categories): self.topCategoryMoviesFlexTable.setText(row+1, 0, cat + " (" + str(self.categories[cat][2]) + ")") self.topCategoryMoviesFlexTable.setText(row+1, 1, self.categories[cat][0]) self.topCategoryMoviesFlexTable.setText(row+1, 2, "%.1f" % float(self.categories[cat][1])) def clearTable(self, table): try: for i in range(table.getRowCount()): table.removeRow(1) except: pass # Called when a response is received from a RPC. def onRemoteResponse(self, response, request_info): if request_info.method in ['getMovies', 'addMovie', 'deleteMovie', 'editMovie']: # Clear current and add all self.movies = [] self.clearTable(self.moviesFlexTable) for m in response: movie = Movie(m[0], m[1], m[2]) self.addMovie(None, movie) self.moviesListLabel.setText("Movies List (" + str(len(self.movies)) + ")") self.remote.getTopRated(self) self.remote.getCategories(self) if request_info.method == 'getTopRated': # Update top rated self.topRatedMovies = [] for m in response: movie = Movie(m[0], m[1], m[2]) self.topRatedMovies.append(movie) self.updateTopRatedMovies() if request_info.method == 'getCategories': # Update categories self.categories = response self.updateCategories()
class MechOptionPanel(HorizontalPanel): def __init__(self, handle, idx, checkOptions = [False, True]): HorizontalPanel.__init__(self) self.log = logging.getConsoleLogger(type(self).__name__, lev) self.log.disabled = False self.log.debug('__init__: Instantiation') self.idx = idx self._handle = handle self._checkOptions = checkOptions self.setStyleName('os-mech-checkbox-options') #checkbox = CheckBox('symbol') #checkbox.setChecked(checkOptions[0]) #checkbox.addClickListener(self.onClickOption) #checkbox.setID('CBSY%d'%idx) #self.append(checkbox) #checkbox = CheckBox('value') #checkbox.setChecked(checkOptions[1]) #checkbox.addClickListener(self.onClickOption) #checkbox.setID('CBVA%d'%idx) #self.append(checkbox) self._textBoxRatio = TextBox('1:1') self._ratioCache = self._textBoxRatio.getText() self._textBoxRatio.setTitle('Ratio') self._ratioCache = self._textBoxRatio.getText() self._textBoxRatio.addChangeListener(self.onRatioChange) self._textBoxRatio.setID('TXRT%d'%idx) self._textBoxRatio.setStyleName('os-mech-textbox-ratio') self._listBoxSize = ListBox() self._listBoxSize.addChangeListener(self.onSizeSet) self._listBoxSize.setVisibleItemCount(1) self._listBoxSize.setStyleName('os-mech-listbox-size') self._listBoxUnit = ListBox() self._listBoxUnit.addChangeListener(self.onUnitSet) self._listBoxUnit.setVisibleItemCount(1) self._listBoxUnit.setStyleName('os-mech-listbox-unit') self.append(Label('Ratio')) self.append(self._textBoxRatio) self.append(Label('Size')) self.append(self._listBoxSize) self.append(Label('Unit')) self.append(self._listBoxUnit) def onSizeSet(self, sender, event): value = sender.getSelectedItemText()[0] self.log.debug('Change size to %s'%value) self._handle.remoteService.mech_options_set(self._handle._handle, self.idx, 'size', value) def onUnitSet(self, sender, event): value = sender.getSelectedValues()[0] self._handle.remoteService.mech_options_set(self._handle._handle, self.idx, 'unit',int(value)) def onRatioChange(self, sender, event): #validate ratio change matches = re.findall(r'^\d{1,4}:\d{1,4}$', self._textBoxRatio.getText()) if len(matches) == 1: # correct self._ratioCache = self._textBoxRatio.getText() self._handle.remoteService.mech_options_set(self._handle._handle, self.idx, 'ratio', self._ratioCache) else: # invalid self._textBoxRatio.setText(self._ratioCache) def actSizeFill(self, options, value = 0): for idx, option in enumerate(options, idx): self._listBoxSize.addItem(option, idx) self._listBoxSize.setSelectedIndex(value) def actUnitFill(self, options, value = 0): for number, name in options.items(): self._listBoxUnit.addItem(name, number) if value < 100000: self._listBoxUnit.setSelectedIndex(value) else: self._listBoxUnit.selectValue(value) def actSizeSet(self, value): self.log.debug('actSizeSet, setting value %s'%value) self._listBoxSize.selectValue(value) def actRatioChange(self, ratio): self._textBoxRatio.setText(ratio) self._ratioCache = ratio def onClickOption(self, sender, event): sendId = int(sender.getID()[4:]) if sendId == 0: self._checkOptions[0] = sender.isChecked() self._checkOptions[1] = not(sender.isChecked()) else: self._checkOptions[0] = not(sender.isChecked()) self._checkOptions[1] = sender.isChecked() checkbox = self.getWidget(0) checkbox.setChecked(self._checkOptions[0]) checkbox = self.getWidget(1) checkbox.setChecked(self._checkOptions[1]) self._handle.remoteService.mech_options_set(self._handle._handle, self.idx, 'checkOptions', self._checkOptions)
class SoftChordApp: def onModuleLoad(self): """ Gets run when the page is first loaded. Creates the widgets. """ self.remote = DataService() main_layout = VerticalPanel() h_layout = HorizontalPanel() h_layout.setPadding(10) songlist_layout = VerticalPanel() songlist_layout.add(Label("Add New Song:")) self.newSongTextBox = TextBox() self.newSongTextBox.addKeyboardListener(self) songlist_layout.add(self.newSongTextBox) self.addSongButton = Button("Add Song") self.addSongButton.addClickListener(self) songlist_layout.add(self.addSongButton) #songlist_layout.add(Label("Click to Remove:")) self.songListBox = ListBox() self.songListBox.setVisibleItemCount(7) self.songListBox.setWidth("300px") self.songListBox.setHeight("400px") self.songListBox.addClickListener(self) songlist_layout.add(self.songListBox) self.deleteSongButton = Button("Delete") self.deleteSongButton.addClickListener(self) songlist_layout.add(self.deleteSongButton) h_layout.add(songlist_layout) #self.textArea = TextArea() #self.textArea.setCharacterWidth(30) #self.textArea.setVisibleLines(50) #h_layout.add(self.textArea) #self.scrollPanel = ScrollPanel(Size=("400px", "500px")) self.songHtml = HTML("<b>Please select a song in the left table</b>") #self.scrollPanel.add(self.songHtml) #h_layout.add(self.scrollPanel) h_layout.add(self.songHtml) main_layout.add(h_layout) self.status = Label() main_layout.add(self.status) RootPanel().add(main_layout) # Populate the song table: self.remote.getAllSongs(self) def onKeyUp(self, sender, keyCode, modifiers): pass def onKeyDown(self, sender, keyCode, modifiers): pass def onKeyPress(self, sender, keyCode, modifiers): """ This functon handles the onKeyPress event """ if keyCode == KeyboardListener.KEY_ENTER and sender == self.newSongTextBox: id = self.remote.addSong(self.newSongTextBox.getText(), self) self.newSongTextBox.setText("") if id<0: self.status.setText("Server Error or Invalid Response") def onClick(self, sender): """ Gets called when a user clicked in the <sender> widget. Currently deletes the song on which the user clicked. """ if sender == self.songListBox: song_id = self.songListBox.getValue(self.songListBox.getSelectedIndex()) self.status.setText("selected song_id: %s" % song_id) id = self.remote.getSong(song_id, self) if id<0: self.status.setText("Server Error or Invalid Response") elif sender == self.addSongButton: id = self.remote.addSong(self.newSongTextBox.getText(), self) self.newSongTextBox.setText("") if id<0: self.status.setText("Server Error or Invalid Response") elif sender == self.deleteSongButton: # Figure out what song is selected in the table: song_id = self.songListBox.getValue(self.songListBox.getSelectedIndex()) self.status.setText("delete song_id: %s" % song_id) id = self.remote.deleteSong(song_id, self) if id<0: self.status.setText("Server Error or Invalid Response") def onRemoteResponse(self, response, request_info): """ Gets called when the backend (django) sends a packet to us. Populates the song table with all songs in the database. """ self.status.setText("response received") if request_info.method == 'getAllSongs' or request_info.method == 'addSong' or request_info.method == 'deleteSong': self.status.setText(self.status.getText() + " - song list received") self.songListBox.clear() for item in response: song_id, song_num, song_title = item if song_num: song_title = "%i %s" % (song_num, song_title) self.songListBox.addItem(song_title) self.songListBox.setValue(self.songListBox.getItemCount()-1, song_id) elif request_info.method == 'getSong': self.status.setText(self.status.getText() + " - song received") song_obj = songs.Song(response) self.status.setText(self.status.getText() + "; id: %i; num-chords: %i" % (song_obj.id, len(song_obj.chords) ) ) self.songHtml.setHTML(song_obj.getHtml()) #self.textArea.setText(song_obj.text) else: # Unknown response received form the server self.status.setText(self.status.getText() + "none!") def onRemoteError(self, code, errobj, request_info): message = errobj['message'] self.status.setText("Server Error or Invalid Response: ERROR %s - %s" % (code, message))
class LoginPanel(VerticalPanel): def __init__(self, listener): VerticalPanel.__init__(self, StyleName = "login") self.listener = listener self.remote = DataService(['login']) form_panel = VerticalPanel(ID = "container", StyleName = "form") self.error_message = Label(StyleName = "error-message") grid = Grid(2, 2, CellPadding=0, CellSpacing=0, StyleName = "form-grid") grid.setWidget(0, 0, Label(JS('gettext("Username:"******"label")) self.tb = TextBox(Name="username") grid.setWidget(0, 1, self.tb) grid.setWidget(1, 0, Label(JS('gettext("Password:"******"label")) self.ptb = PasswordTextBox(Name="password") grid.setWidget(1, 1, self.ptb) form_panel.add(Label(JS('gettext("User Login")'), StyleName = "form-title")) form_panel.add(self.error_message) form_panel.add(grid) button_box = HorizontalPanel(Width="100%") register_button = PseudoLink(JS('gettext("Create an account")'), self.onRegisterButtonClick) submit_button = Button(JS('gettext("Login")'), self.onSubmitButtonClick) button_box.add(register_button) button_box.add(submit_button) button_box.setCellHorizontalAlignment(submit_button, HasAlignment.ALIGN_RIGHT) form_panel.add(button_box) self.add(form_panel) def onShow(self, sender): self.error_message.setText("") def onRegisterButtonClick(self, sender): self.listener.onRegister(self) def onSubmitButtonClick(self, sender): self.remote.login(self.tb.getText(), self.ptb.getText(), self) def onRemoteResponse(self, response, request_info): ''' Called when a response is received from a RPC. ''' if request_info.method == 'login': if response['success']: self.listener.onLogin(self) else: self.error_message.setText(response['error_message']) else: Window.alert('Unrecognized JSONRPC method.') def onRemoteError(self, code, message, request_info): Window.alert(message)
class LatBuilderWeb: def setStyleSheet(self, sheet): e = DOM.createElement('link') e.setAttribute('rel', 'stylesheet') e.setAttribute('type', 'text/css') e.setAttribute('href', sheet) html = Window.getDocumentRoot().parentElement head = html.getElementsByTagName('head').item(0) head.appendChild(e) def includeMathJax(self, config): html = Window.getDocumentRoot().parentElement head = html.getElementsByTagName('head').item(0) e = DOM.createElement('script') e.setAttribute('type', 'text/javascript') e.setAttribute( 'src', 'http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=' + config) head.appendChild(e) e = DOM.createElement('script') e.setAttribute('type', 'text/javascript') e.textContent = 'function Typeset() { MathJax.Hub.Queue(["Typeset",MathJax.Hub]); }' head.appendChild(e) def onModuleLoad(self): self.current_request = None Window.setTitle("Lattice Builder Web Interface") self.setStyleSheet("./LatBuilderWeb.css") self.includeMathJax('TeX-AMS-MML_HTMLorMML') self.TEXT_WAITING = "Lattice Builder is working..." self.TEXT_ERROR = "Server Error" self.FIGURES_OF_MERIT = [ # (key, name) ('{cs}P2', 'P2'), ('{cs}P4', 'P4'), ('{cs}P6', 'P6'), ('{cs}R{alpha}', 'R_alpha'), ('spectral', 'spectral'), ] self.CONSTRUCTION_METHODS = [ ('explicit:{genvec}', "Explicit (Evaluation)", "Evaluates the figure of merit for a given generating vector.<br/>" "<strong>Please specify the generating vector in the Lattice " "Properties panel above.</strong>"), ('exhaustive', "Exhaustive", "Examines all generating vectors and retains the best one."), ('random:{samples}', "Random", "Examines a number of randomly selected generating vectors and " "retains the best one."), ('Korobov', "Korobov", "Examines all generating vectors of the form (1, a, a^2 mod n, " "..., a^s mod n) and retains the best one."), ('random-Korobov:{samples}', "Random Korobov", "Examines a number of randomly selected generating vectors of " "the form (1, a, a^2 mod n, ..., a^s mod n) and retains the " "best one."), ('CBC', "Component-by-Component", "Examines all possible values of the components of the " "generating vector and selects the best ones, one coordinate " "at a time."), ('random-CBC:{samples}', "Random Component-by-Component", "Examines a number of randomly selected values of the " "components of the generating vector and selects the best " "ones, one coordinate at a time."), ('fast-CBC', "Fast Component-by-Component", "Examines all possible values of the components of the " "generating vector and selects the best ones, one coordinate " "at a time. Computation is accelerated by using fast " "Fourier transforms."), ] self.COMBINER_TYPES = [ ('level:max', 'highest level'), ('sum', 'weighted sum'), ('max', 'maximum weighted value'), ] self.NORMALIZATION_TYPES = [ ('norm:P{alpha}-SL10', 'SL10 P-alpha'), ('norm:P{alpha}-DPW08', 'DPW08 P-alpha'), ] captionstyle = { 'Width': '10em', 'HorizontalAlignment': 'right', } self.remote = LatBuilderService() WeightValuesArray.REMOTE = self.remote main_panel = VerticalPanel(Spacing=30) # information info = """<h2>Lattice Builder Web Interface</h2> <p>This Web interface allows <a href="https://github.com/mungerd/latbuilder#readme">Lattice Builder</a> users to call the executable program without having to construct the command line explicitly. </p> <p>Enter the construction parameters below, and press the <em>Search for Good Lattices</em> button. The results will show at the bottom. </p>""" main_panel.add(HTML(info)) self.version_label = HTML() main_panel.add(self.version_label) self.remote.backend_version(self) params_panel = VerticalPanel(Spacing=15) main_panel.add(params_panel) # lattice type and size and dimension lat_panel = VerticalPanel() params_panel.add(CaptionPanel("Lattice Properties", lat_panel)) lat_panel.add( HTML( r'\[ P_n = \left\{ (i \boldsymbol a \bmod n) / n \::\: i = 0, \dots, n \right\} \qquad (\boldsymbol a \in \mathbb Z^s) \]', StyleName='DisplayMath')) self.size = TextBox(Text="2^10") self.size.addChangeListener(self) self.embedded = CheckBox("embedded") self.embedded.addClickListener(self) panel = HorizontalPanel(Spacing=8) panel.add(HTML(r"Size (\(n\)): ", StyleName="CaptionLabel")) panel.add(self.size) panel.add(self.embedded) lat_panel.add(panel) self.dimension = TextBox(Text="3") self.dimension.addChangeListener(self) panel = HorizontalPanel(Spacing=8) panel.add(HTML(r"Dimension (\(s\)): ", StyleName="CaptionLabel")) panel.add(self.dimension) lat_panel.add(panel) self.generating_vector = GeneratingVector(self.size) self.generating_vector.panel.setVisible(False) lat_panel.add(self.generating_vector.panel) # figure of merit merit_panel = VerticalPanel() params_panel.add(CaptionPanel("Figure of Merit", merit_panel)) merit_panel.add( HTML( r"\[ \left[ \mathcal D_q(P_n) \right]^q = " r"\sum_{\emptyset \neq u \subseteq \{1,\dots,s\}}" r"\gamma_u^q \, \left[\mathcal D_u(P_n)\right]^q" r"\qquad (q > 0) \]", StyleName='DisplayMath')) self.norm_type = TextBox(Text="2") self.norm_type.addChangeListener(self) panel = HorizontalPanel(Spacing=8) panel.add( HTML(r"Norm type (\(q\) or <b>inf</b>): ", StyleName="CaptionLabel")) panel.add(self.norm_type) merit_panel.add(panel) self.merit = ListBox() self.merit.addChangeListener(self) for key, name in self.FIGURES_OF_MERIT: self.merit.addItem(name) self.merit_cs = CheckBox("Use coordinate-symmetric implementation", Checked=True) panel = HorizontalPanel(Spacing=8) panel.add(HTML("Figure of merit: ", StyleName="CaptionLabel")) panel.add(self.merit) panel.add(self.merit_cs) merit_panel.add(panel) self.merit_alpha_panel = HorizontalPanel(Spacing=8) self.merit_alpha = TextBox(Text="2") self.merit_alpha_panel.add( HTML("Value of alpha: ", StyleName="CaptionLabel")) self.merit_alpha_panel.add(self.merit_alpha) merit_panel.add(self.merit_alpha_panel) # filters and combiner multilevel_panel = VerticalPanel(Spacing=8) self.multilevel_panel = CaptionPanel("Multilevel Filters and Combiner", multilevel_panel, Visible=False) params_panel.add(self.multilevel_panel) self.ml_normalization_enable = CheckBox("Normalization") self.ml_normalization_enable.addClickListener(self) multilevel_panel.add(self.ml_normalization_enable) self.ml_normalization_panel = VerticalPanel(Spacing=4, Visible=False, StyleName='SubPanel') multilevel_panel.add(self.ml_normalization_panel) panel = HorizontalPanel(Spacing=8) panel.add(HTML("Normalization type: ", StyleName="CaptionLabel")) self.ml_normalization_type = ListBox() for key, name in self.NORMALIZATION_TYPES: self.ml_normalization_type.addItem(name, value=key) panel.add(self.ml_normalization_type) self.ml_normalization_panel.add(panel) panel = HorizontalPanel(Spacing=8) panel.add(HTML("Minimum level: ", StyleName="CaptionLabel")) self.ml_min_level = TextBox(Text="1") panel.add(self.ml_min_level) self.ml_normalization_panel.add(panel) panel = HorizontalPanel(Spacing=8) panel.add(HTML("Maximum level: ", StyleName="CaptionLabel")) self.ml_max_level = TextBox(Text="1") panel.add(self.ml_max_level) self.ml_normalization_panel.add(panel) self.ml_lowpass_enable = CheckBox("Low-pass filter") self.ml_lowpass_enable.addClickListener(self) multilevel_panel.add(self.ml_lowpass_enable) self.ml_lowpass_panel = VerticalPanel(Spacing=4, Visible=False, StyleName='SubPanel') multilevel_panel.add(self.ml_lowpass_panel) self.ml_lowpass = TextBox(Text="1.0") panel = HorizontalPanel(Spacing=8) panel.add(HTML("Low-pass threshold: ", StyleName="CaptionLabel")) panel.add(self.ml_lowpass) self.ml_lowpass_panel.add(panel) self.combiner_type = ListBox() for key, name in self.COMBINER_TYPES: self.combiner_type.addItem(name, value=key) panel = HorizontalPanel(Spacing=8) panel.add(HTML("Combiner: ", StyleName="CaptionLabel")) panel.add(self.combiner_type) multilevel_panel.add(panel) # weights self.weights = CompoundWeights() weights_panel = VerticalPanel() params_panel.add(CaptionPanel("Weights", weights_panel)) weights_panel.add( HTML(r"\[ \gamma_u^p \qquad (u \subseteq \{1, \dots, s\}) \]", StyleName='DisplayMath')) self.weights_power = TextBox(Text="2") panel = HorizontalPanel(Spacing=8) panel.add(HTML(r"Weights power (\(p\)): ", StyleName="CaptionLabel")) panel.add(self.weights_power) weights_panel.add(panel) weights_panel.add(self.weights.panel) self.weights.add_weights(ProductWeights) # construction method cons_panel = VerticalPanel() params_panel.add(CaptionPanel("Construction Method", cons_panel)) self.construction = ListBox() self.construction.addChangeListener(self) for key, name, desc in self.CONSTRUCTION_METHODS: self.construction.addItem(name, value=key) self.construction_desc = HTML() panel = HorizontalPanel(Spacing=8) panel.add(self.construction) panel.add(self.construction_desc) cons_panel.add(panel) self.construction_samples_panel = HorizontalPanel(Spacing=8) self.construction_samples = TextBox(Text="30") self.construction_samples_panel.add( HTML("Random samples: ", StyleName="CaptionLabel")) self.construction_samples_panel.add(self.construction_samples) cons_panel.add(self.construction_samples_panel) # execute button panel = VerticalPanel(Spacing=8, Width="100%", HorizontalAlignment='center') main_panel.add(panel) button_panel = HorizontalPanel() panel.add(button_panel) self.button_search = Button("Search", self) button_panel.add(self.button_search) self.button_abort = Button("Abort", self, Visible=False) button_panel.add(self.button_abort) self.status = Label() panel.add(self.status) # results results_panel = VerticalPanel() self.results_panel = CaptionPanel("Results", results_panel, Visible=False) main_panel.add(self.results_panel) self.results_size = Label() panel = HorizontalPanel(Spacing=8) panel.add(HTML("Lattice size: ", StyleName="ResultsCaptionLabel")) panel.add(self.results_size) results_panel.add(panel) self.results_gen = Label() panel = HorizontalPanel(Spacing=8) panel.add(HTML("Generating vector: ", StyleName="ResultsCaptionLabel")) panel.add(self.results_gen) results_panel.add(panel) self.results_merit = Label() panel = HorizontalPanel(Spacing=8) panel.add(HTML("Merit value: ", StyleName="ResultsCaptionLabel")) panel.add(self.results_merit) results_panel.add(panel) self.results_cpu_time = Label() panel = HorizontalPanel(Spacing=8) panel.add(HTML("CPU time: ", StyleName="ResultsCaptionLabel")) panel.add(self.results_cpu_time) results_panel.add(panel) self.results_cmd = Label(StyleName='Command', Visible=False) panel = HorizontalPanel(Spacing=8) self.results_cmd_link = Hyperlink("Command line: ", StyleName="ResultsCaptionLabel") self.results_cmd_link.addClickListener(self) panel.add(self.results_cmd_link) panel.add(self.results_cmd) results_panel.add(panel) # update selections self.construction.selectValue('CBC') self.onChange(self.size) self.onChange(self.construction) self.onChange(self.merit) self.onChange(self.dimension) self.onClick(self.embedded) self.onChange(self.ml_normalization_enable) self.onChange(self.ml_lowpass_enable) RootPanel().add(main_panel) def onChange(self, sender): if sender == self.construction: key, name, desc = \ self.CONSTRUCTION_METHODS[self.construction.getSelectedIndex()] self.construction_desc.setHTML(desc) self.construction_samples_panel.setVisible('{samples}' in key) if key.startswith('explicit'): self.generating_vector.panel.setVisible(True) self.button_search.setText("Evaluate Figure of Merit") else: self.generating_vector.panel.setVisible(False) self.button_search.setText("Search for Good Lattices") elif sender == self.merit: key, name = \ self.FIGURES_OF_MERIT[self.merit.getSelectedIndex()] self.merit_alpha_panel.setVisible('{alpha}' in key) self.merit_cs.setVisible('{cs}' in key) elif sender == self.size: max_level = LatSize(self.size.getText()).max_level if int(self.ml_min_level.getText()) > max_level: self.ml_min_level.setText(max_level) self.ml_max_level.setText(max_level) elif sender == self.dimension: # resize weights dimension = int(self.dimension.getText()) self.generating_vector.dimension = dimension self.weights.dimension = dimension elif sender == self.norm_type: q = self.norm_type.getText().strip() self.merit_cs.setVisible(q == '2') if q == 'inf': self.weights_power.setText('1') else: self.weights_power.setText(q) def onClick(self, sender): if sender == self.embedded: self.multilevel_panel.setVisible(self.embedded.getChecked()) elif sender == self.ml_normalization_enable: self.ml_normalization_panel.setVisible( self.ml_normalization_enable.getChecked()) elif sender == self.ml_lowpass_enable: self.ml_lowpass_panel.setVisible( self.ml_lowpass_enable.getChecked()) elif sender == self.results_cmd_link: self.results_cmd.setVisible(not self.results_cmd.getVisible()) elif sender == self.button_search: self.results_panel.setVisible(False) self.button_search.setVisible(False) self.button_abort.setVisible(True) lattype = self.embedded.getChecked() and 'embedded' or 'ordinary' size = self.size.getText() dimension = self.dimension.getText() norm_type = self.norm_type.getText() merit, merit_name = \ self.FIGURES_OF_MERIT[self.merit.getSelectedIndex()] alpha = self.merit_alpha.getText() cs = norm_type == 2 and self.merit_cs.getChecked() and 'CS:' or '' weights_power = self.weights_power.getText() weights = [w.as_arg() for w in self.weights.weights] construction, construction_name, desc = \ self.CONSTRUCTION_METHODS[self.construction.getSelectedIndex()] samples = self.construction_samples.getText() genvec = ','.join(self.generating_vector.values) mlfilters = [] combiner_type = None if self.embedded.getChecked(): if self.ml_normalization_enable.getChecked(): ml_normalization_type, ml_normalization_name = \ self.NORMALIZATION_TYPES[self.ml_normalization_type.getSelectedIndex()] ml_normalization_type += ':even:{},{}'.format( self.ml_min_level.getText(), self.ml_max_level.getText()) mlfilters.append(ml_normalization_type.format(alpha=alpha)) if self.ml_lowpass_enable.getChecked(): mlfilters.append('low-pass:{}'.format( self.ml_lowpass.getText())) combiner_type, combiner_name = \ self.COMBINER_TYPES[self.combiner_type.getSelectedIndex()] self.status.setText(self.TEXT_WAITING) self.current_request = self.remote.latbuilder_exec( lattype, size, dimension, norm_type, merit.format(alpha=alpha, cs=cs), construction.format(samples=samples, genvec=genvec), weights, weights_power, None, mlfilters, combiner_type, self) elif sender == self.button_abort: # Need to patch JSONService.sendRequest(): # # return HTTPRequest().asyncPost(self.url, msg_data, # JSONResponseTextHandler(request_info) # False, self.content_type, # self.headers) if self.current_request: self.current_request.abort() self.current_request = None self.button_abort.setVisible(False) self.button_search.setVisible(True) elif sender == self.product_weights_expr_link: self.showDialog(self._product_weights_expr_dialog) elif sender == self.order_weights_expr_link: self.showDialog(self._order_weights_expr_dialog) def onRemoteResponse(self, response, request_info): try: if request_info.method == 'latbuilder_exec': self.button_search.setVisible(True) self.button_abort.setVisible(False) cmd, points, gen, merit, seconds = eval(response) self.results_size.setText(points) self.results_gen.setText(', '.join(gen)) self.results_merit.setText(merit) self.results_cpu_time.setText(format_time(seconds=seconds)) self.results_cmd.setText(cmd) self.results_panel.setVisible(True) self.status.setText("") elif request_info.method == 'backend_version': version = response self.version_label.setHTML( "<b>Backend:</b> {}".format(version)) except: self.status.setText(response.replace('\n', ' | ')) def onRemoteError(self, code, errobj, request_info): if request_info.method == 'latbuilder_exec': self.button_search.setVisible(True) self.button_abort.setVisible(False) message = errobj['message'] if code != 0: self.status.setText("HTTP error %d: %s" % (code, message['name'])) else: code = errobj['code'] if code == -32603: self.status.setText("Aborted.") else: self.status.setText("JSONRPC Error %s: %s" % (code, message))
class EventLinkPopup(PopupPanel): def __init__(self, editor): PopupPanel.__init__(self, glass=True) self.m_origAnchorStart = None self.m_origAnchorEnd = None self.m_origTargetText = "" self.m_editor = editor vpanel = VerticalPanel() vpanel.setWidth("350px") self.m_webPageText = TextBox() self.m_webPageText.setText("http:#") self.m_webPageText.setWidth("320px") vpanel.add(self.m_webPageText) lbl = Label("Display:") self.m_targetText = TextBox() self.m_targetText.setWidth("100%") lpanel = HorizontalPanel() lpanel.add(lbl) lpanel.add(self.m_targetText) vpanel.add(lpanel) self.m_fillOutCB = CheckBox("Change entire link") self.m_fillOutCB.setVisible(False) self.m_fillOutCB.addClickListener(self) vpanel.add(self.m_fillOutCB) self.m_okBut = Button("Ok", self) self.m_okBut.addStyleName("float-left") self.m_cancelBut = Button("Cancel", self) self.m_cancelBut.addStyleName("float-left") hpanel = HorizontalPanel() hpanel.add(self.m_okBut) hpanel.add(self.m_cancelBut) vpanel.add(hpanel) self.add(vpanel) self.setStyleName("gwt-DialogBox") def refresh(self): try: self.m_editor.getSelection() self.m_range = self.m_editor.getRange() if self.m_range is None: return False else: self.m_selTexts = self.m_range.getSelectedTextElements() if self.m_selTexts is None: return False else: self.m_origTargetText = self.m_range.getText() self.m_targetText.setText(self.m_origTargetText) anchor = self.getAnchor(self.m_selTexts) if anchor is not None: href = anchor.getHref().strip() if href: self.m_webPageText.setText(href) self.m_origAnchorStart = self.getAnchorLimit( self.m_range.getStartPoint().getTextNode(), anchor, False) self.m_origAnchorEnd = self.getAnchorLimit( self.m_range.getStartPoint().getTextNode(), anchor, True) if self.m_range.getStartPoint().equals(self.m_origAnchorStart) and self.m_range.getStartPoint().equals(self.m_origAnchorEnd): self.m_origAnchorStart = None self.m_origAnchorEnd = None else: self.m_fillOutCB.setVisible(True) self.m_fillOutCB.setValue(True) self.m_origTargetText = self.fetchStringFromTexts( self.m_origAnchorStart, self.m_origAnchorEnd) self.m_targetText.setText(self.m_origTargetText) except: print "exception" traceback.print_exc() return False return True def _apply(self): formatter = self.m_editor.getFormatter() link = self.m_webPageText.getText().strip() if not link: return False print self.m_origAnchorStart, self.m_origAnchorEnd if (self.m_origAnchorStart is not None) and self.m_fillOutCB.getValue(): # Expand selection to these bounds self.m_range.setRange(self.m_origAnchorStart, self.m_origAnchorEnd) # Ensure the selection hasn't changed, or at least changes to the # expanded bounds we want Selection.setRange(self.m_range) targetText = self.m_targetText.getText() if self.m_range.isCursor(): # Insert into a single cursor location newEle = DOM.createAnchor() newEle.href = link newEle.innerText = targetText sp = self.m_range.getStartPoint() startNode = sp.getTextNode() offset = sp.getOffset() print "sp", sp, startNode, offset parentEle = startNode.parentElement text = startNode.data if offset == 0: parentEle.insertBefore(newEle, startNode) else: if offset < len(text): # Split this in two and insert the node between startNode.splitText(offset) DOM.insertAfter(startNode, newEle) Selection.setRange(Range(newEle)) elif targetText != self.m_origTargetText: # Replace whatever was selected with this text ele = self.m_range.surroundContents() newEle = DOM.createAnchor() newEle.href = link newEle.innerText = targetText ele.parentElement.replaceChild(newEle, ele) Selection.setRange(Range(newEle)) else: formatter.createLink(link) return True def getAnchor(self, node): res = None if isinstance(node, list): nodes = node for node in nodes: res = self.getAnchor(node) if res is not None: break return res ele = node.parentElement while ele is not None: tag = ele.tagName if tag.lower == "a": res = ele break ele = ele.parentElement return res def getAnchorLimit(self, node, anchor, forward): href = anchor.href while True: prevNode = node node = Range.getAdjacentTextElement(prevNode, forward) if node is not None: cmpAnchor = self.getAnchor(node) if (cmpAnchor is None) or not href == cmpAnchor.href: break if node is None: break res = RangeEndPoint() res.setTextNode(prevNode) res.setOffset(forward and prevNode.getData().length() or 0) return res def parseEventLink(self, href): res = 0 idx = href.index("#event=") if idx > 0: try: res = href[idx+7:] except: pass return res def createEventLink(self, id): return "#event=" + id def fetchStringFromTexts(self, startPoint, endPoint): res = None texts = Range.getSelectedTextElements( startPoint.getTextNode(), endPoint.getTextNode()) if texts is not None: res = self.fetchStringFromTexts(texts, startPoint, endPoint) return res def fetchStringFromTexts(self, allTexts, startPoint, endPoint): selText = "" for node in allTexts: val = node.getData() if node == startPoint.getTextNode(): if node == endPoint.getTextNode(): val = val.substring[startPoint.getOffset(): endPoint.getOffset()] else: val = val[startPoint.getOffset():] elif node == endPoint.getTextNode(): val = val[:endPoint.getOffset()] selText += val return selText def onClick(self, sender): if sender == self.m_cancelBut: self.hide() elif sender == self.m_okBut: if self._apply(): self.hide() elif sender == self.m_fillOutCB: if self.m_fillOutCB.getValue(): self.m_origTargetText = fetchStringFromTexts(self.m_origAnchorStart, self.m_origAnchorEnd) self.m_targetText.setValue(self.m_origTargetText) else: self.m_origTargetText = self.m_range.getText() self.m_targetText.setValue(self.m_origTargetText) def checkSuggestValid(self): self.m_okBut.setEnabled(True) def execute(self): self.checkSuggestValid() def deferredCheckValid(self): DeferredCommand.addCommand(self)
class WebApp: def onFormLoad(self): self.fetch = Button("Retrieve", self) self.search = TextBox() self.submit = Button("Submit", self) self.formsvc = FormService() self.wanted = WantedService() d = {'price': 20, 'name': 'a good car'} self.form = Form(getattr(self.formsvc, "itemform"), data=d, listener=self) #self.describe(['name', 'description']) RootPanel().add(self.form) RootPanel().add(self.search) RootPanel().add(self.fetch) def onRetrieveDone(self, form): log.debug("onRetrieveDone: %s" % repr(form)) def onDescribeDone(self, form): form.add_widget("Submit", self.submit) def onClick(self, sender): if sender == self.fetch: key = self.search.getText() if not key: log.debug("Please enter id") return key = int(key) log.debug("id %d" % key) #self.wanted.getItem(key, self) self.form.get(id=key) if sender == self.submit: v = self.form.getValue() log.debug("onClick %s" % repr(v)) if v.get('id', None): self.form.update(v) else: self.form.save(v) def onErrors(self, form, response): log.debug("onErrors %s" % repr(response)) def onSaveDone(self, form, response): log.debug("onSave %s" % repr(response)) def onModuleLoad(self): self.pages = DataService() #Show the initial screen. initToken = History().getToken() if initToken and len(initToken): if initToken == 'admin': RootPanel().add(WebPageEdit(self)) return else: initToken = 'index' self.dock = DockPanel() self.dock.setWidth("100%") self.pages = {} self.current_page = None RootPanel().add(self.dock) History.addHistoryListener(self) self.onHistoryChanged(initToken) def createPage(self, ref, html, title): htp = HTMLLinkPanel(self, html, title) htp.replaceLinks() htp.setWidth("100%") self.pages[ref] = htp def onHistoryChanged(self, token): #log.debug("onHistoryChanged %s" % token) if self.pages.has_key(token): self.setPage(token) return self.pages.getPageByName(token, self) def setPage(self, ref): htp = self.pages[ref] if htp == self.current_page: return Window.setTitle(htp.title) if self.current_page: self.dock.remove(self.current_page) self.dock.add(htp, DockPanel.CENTER) self.current_page = htp def onRemoteResponse(self, response, request_info): #if (request_info.method == 'getItem'): # data = {'id': response['pk']} # log.debug(repr(response)) # self.form.update_values(response) if (request_info.method == 'getPageByName' or request_info.method == 'getPage'): item = response[0] html = item['fields']['text'] token = item['fields']['name'] self.createPage(token, html, token) self.setPage(token) def onRemoteError(self, code, message, request_info): RootPanel().add(HTML("Server Error or Invalid Response: ERROR " + str(code) + " - " + str(message)))
class DateField(Composite): icon_img = "icon_calendar.gif" icon_style = "calendar-img" today_text = "Today" today_style = "calendar-today-link" def __init__(self, format='%d-%m-%Y'): self.format = format self.tbox = TextBox() self.tbox.setVisibleLength(10) # assume valid sep is - / . or nothing if format.find('-') >= 0: self.sep = '-' elif format.find('/') >= 0: self.sep = '/' elif format.find('.') >= 0: self.sep = '.' else: self.sep = '' # self.sep = format[2] # is this too presumptious? self.calendar = Calendar() self.img = Image(self.icon_img) self.img.addStyleName(self.icon_style) self.calendarLink = HyperlinkImage(self.img) self.todayLink = Hyperlink(self.today_text) self.todayLink.addStyleName(self.today_style) # # lay it out # hp = HorizontalPanel() hp.setSpacing(2) vp = VerticalPanel() hp.add(self.tbox) vp.add(self.calendarLink) vp.add(self.todayLink) #vp.add(self.calendar) hp.add(vp) Composite.__init__(self) self.initWidget(hp) # # done with layout, so now set up some listeners # self.tbox.addFocusListener(self) # hook to onLostFocus self.calendar.addSelectedDateListener(getattr(self, "onDateSelected")) self.todayLink.addClickListener(getattr(self, "onTodayClicked")) self.calendarLink.addClickListener(getattr(self, "onShowCalendar")) def getTextBox(self): return self.tbox def getCalendar(self): return self.calendar def setID(self, id): self.tbox.setID(id) def onDateSelected(self, yyyy, mm, dd): secs = time.mktime((int(yyyy), int(mm), int(dd), 0, 0, 0, 0, 0, -1)) d = time.strftime(self.format, time.localtime(secs)) self.tbox.setText(d) def onLostFocus(self, sender): # text = self.tbox.getText().strip() # if blank - leave it alone if text and len(text) == 8: # ok what format do we have? assume ddmmyyyy --> dd-mm-yyyy txt = text[0:2] + self.sep + text[2:4] + self.sep + text[4:8] self.tbox.setText(txt) def onFocus(self, sender): pass def onTodayClicked(self, event): today = time.strftime(self.format) self.tbox.setText(today) def onShowCalendar(self, sender): p = CalendarPopup(self.calendar) x = self.tbox.getAbsoluteLeft() + 10 y = self.tbox.getAbsoluteTop() + 10 p.setPopupPosition(x, y) p.show()
class NewBlog: def onModuleLoad(self): loggedInUser = getCookie("LoggedInUser") loggedInUserJsonData = json.loads(loggedInUser) self.username = loggedInUserJsonData["username"] self.remote_py = MyBlogService() dockPanel = DockPanel(BorderWidth=0, Padding=0, HorizontalAlignment=HasAlignment.ALIGN_CENTER, VerticalAlignment=HasAlignment.ALIGN_MIDDLE) dockPanel.setSize('100%', '100%') headerDockPanel = DockPanel( BorderWidth=0, Padding=0, HorizontalAlignment=HasAlignment.ALIGN_LEFT, VerticalAlignment=HasAlignment.ALIGN_CENTER) headerDockPanel.setStyleName('header') headerDockPanel.setWidth('100%') dockPanel.add(headerDockPanel, DockPanel.NORTH) dockPanel.setCellHeight(headerDockPanel, '60px') self.siteImage = Image("/images/Testware_logo.png") self.siteImage.setStyleName('logo-image') headerDockPanel.add(self.siteImage, DockPanel.WEST) headerDockPanel.setCellWidth(self.siteImage, '30%') self.pageTitle = Label('New Blog') self.pageTitle.setStyleName('center-header') headerDockPanel.add(self.pageTitle, DockPanel.CENTER) headerDockPanel.setCellWidth(self.pageTitle, '40%') rightHeaderPanel = VerticalPanel(StyleName='right-header') headerDockPanel.add(rightHeaderPanel, DockPanel.EAST) headerDockPanel.setCellWidth(rightHeaderPanel, '30%') welcomeNoteLabel = Label('Hi %s %s!' % (loggedInUserJsonData["first_name"], loggedInUserJsonData["last_name"])) rightHeaderPanel.add(welcomeNoteLabel) logoutAnchor = Anchor(Widget=HTML('Logout'), Href='/', Title='Logout') logoutAnchor.setStyleName('logout') rightHeaderPanel.add(logoutAnchor) panel = HorizontalPanel(StyleName="header2") dockPanel.add(panel, DockPanel.NORTH) dockPanel.setCellHeight(panel, '50px') self.blogTitle = TextBox() self.blogTitle.setStyleName('blog-title') self.blogTitle.setPlaceholder("Blog Title") panel.add(self.blogTitle) self.blogContent = TextArea() self.blogContent.setStyleName('blog-content') dockPanel.add(self.blogContent, DockPanel.CENTER) createBlogButton = Button("Create Blog", self) createBlogButton.setStyleName('btn') panel.add(createBlogButton) RootPanel().add(dockPanel) def onClick(self, sender): self.createBlog() def createBlog(self): self.remote_py.callMethod('createBlog', [ self.blogTitle.getText(), self.blogContent.getText(), self.username ], self) def onRemoteResponse(self, response, requestInfo): Window.setLocation("/home.html") def onRemoteError(self, code, error_dict, requestInfo): if code == 401: self.errorlabel.setText("Invalid Credentials. Please try again.")
class UserForm(AbsolutePanel): MODE_ADD = "modeAdd"; MODE_EDIT = "modeEdit"; user = None mode = None usernameInput = None firstInput = None lastInput = None emailInput = None passwordInput = None confirmInput = None departmentCombo = None addBtn = None cancelBtn = None def __init__(self,parent): AbsolutePanel.__init__(self) ftable = FlexTable() ftable.setWidget(0, 0, Label("First Name", wordWrap=False)) ftableFormatter = ftable.getFlexCellFormatter() self.firstInput = TextBox() self.firstInput.addChangeListener(self.checkValid) self.firstInput.addKeyboardListener(self) ftable.setWidget(0, 1, self.firstInput) ftable.setWidget(1, 0, Label("Last Name", wordWrap=False)) self.lastInput = TextBox() self.lastInput.addChangeListener(self.checkValid) self.lastInput.addKeyboardListener(self) ftable.setWidget(1, 1, self.lastInput) ftable.setWidget(2, 0, Label("Email", wordWrap=False)) self.emailInput = TextBox() self.emailInput.addChangeListener(self.checkValid) self.emailInput.addKeyboardListener(self) ftable.setWidget(2, 1, self.emailInput) w = Label("* Username", wordWrap=False) w.addMouseListener(TooltipListener("Required, not changable")) ftable.setWidget(3, 0, w) self.usernameInput = TextBox() self.usernameInput.addChangeListener(self.checkValid) self.usernameInput.addKeyboardListener(self) ftable.setWidget(3, 1, self.usernameInput) w = Label("* Password", wordWrap=False) w.addMouseListener(TooltipListener("Required")) ftable.setWidget(4, 0, w) self.passwordInput = PasswordTextBox() self.passwordInput.addChangeListener(self.checkValid) self.passwordInput.addKeyboardListener(self) ftable.setWidget(4, 1, self.passwordInput) w = Label("* Confirm", wordWrap=False) w.addMouseListener(TooltipListener("Required")) ftable.setWidget(5, 0, w) self.confirmInput = PasswordTextBox() self.confirmInput.addChangeListener(self.checkValid) self.confirmInput.addKeyboardListener(self) ftable.setWidget(5, 1, self.confirmInput) w = Label("* Department", wordWrap=False) w.addMouseListener(TooltipListener("Required")) ftable.setWidget(6, 0, w) self.departmentCombo = ListBox() self.departmentCombo.addChangeListener(self.checkValid) self.departmentCombo.addKeyboardListener(self) ftable.setWidget(6, 1, self.departmentCombo) hpanel = HorizontalPanel() self.addBtn = Button("Add User") self.addBtn.setEnabled(False) hpanel.add(self.addBtn) self.cancelBtn = Button("Cancel") hpanel.add(self.cancelBtn) ftable.setWidget(7, 0, hpanel) ftableFormatter.setColSpan(7, 0, 2) self.add(ftable) self.clearForm() return def clearForm(self): self.user = None self.usernameInput.setText('') self.firstInput.setText('') self.lastInput.setText('') self.emailInput.setText('') self.passwordInput.setText('') self.confirmInput.setText('') self.departmentCombo.setItemTextSelection(None) self.updateMode(self.MODE_ADD) self.checkValid() def updateUser(self, user): def setText(elem, value): if value: elem.setText(value) else: elem.setText("") self.user = user setText(self.usernameInput, self.user.username) setText(self.firstInput, self.user.fname) setText(self.lastInput, self.user.lname) setText(self.emailInput, self.user.email) setText(self.passwordInput, self.user.password) setText(self.confirmInput, self.user.password) self.departmentCombo.setItemTextSelection([self.user.department]) self.checkValid() def updateDepartmentCombo(self,choices, default_): self.departmentCombo.clear() for choice in choices: self.departmentCombo.addItem(choice) self.departmentCombo.selectValue(default_) def updateMode(self, mode): self.mode = mode if self.mode == self.MODE_ADD: self.addBtn.setText("Add User") else: self.addBtn.setText("Update User") def checkValid(self, evt=None): if self.enableSubmit(self.usernameInput.getText(),self.passwordInput.getText(),self.confirmInput.getText(), self.departmentCombo.getSelectedItemText(True)): self.addBtn.setEnabled(True) else: self.addBtn.setEnabled(False) def enableSubmit(self, u, p, c, d): return (len(u) > 0 and len(p) >0 and p == c and len(d) > 0) def onClick(self, sender): pass def onKeyUp(self, sender, keyCode, modifiers): self.checkValid() def onKeyDown(self, sender, keyCode, modifiers): pass def onKeyPress(self, sender, keyCode, modifiers): pass