def makeFileChooser(): l = ListBox() for i, tup in enumerate(files): name, content = tup l.addItem(name, i) l.addChangeListener(loadFile) return l
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)
def makeFileChooser(): l = ListBox() for i, tup in enumerate(files): name, content = tup l.addItem(name, i) l.addChangeListener(loadFile) return l
class TheoremPanel(ScrollPanel): def __init__(self, after): ScrollPanel.__init__(self, Size=("630px", "500px")) self.after = after self.pok = VerticalPanel() self.add(self.pok) self.images = list() def onItemSelected(): item = self.list2.getItemText(self.list2.getSelectedIndex()) self.refresh_theorems(item) self.list2 = ListBox() self.list2.setVisibleItemCount(1) for f in Theorem.get_all_folders(): self.list2.addItem(f) self.pok.add(self.list2) self.list2.addChangeListener(onItemSelected) self.refresh_theorems(self.list2.getItemText(self.list2.getSelectedIndex())) def remove_images(self): for im in self.images: self.pok.remove(im) self.images = list() def refresh_theorems(self, folder): self.remove_images() def onClick(theorem): def name(n): return "var" + str(n + 1) def print_scheme(n): return ["\\alpha", "\\beta", "\\gamma", "\\delta", "\\epsilon"][n] def poas(sender): if len(theorem.operations) == 1: constants = [Operation("const" + str(i + 1), 0, print_scheme(i), name(i), Operation.EXPRESSION) for i in range(theorem.operations[0].no_of_args)] def after1(f): self.after( theorem.formula.substitute_definition(Formula([theorem.operations[0]] + constants), f), predecessors=[], rule_name="insert") request_formula([op for op in proof.get_operations()] + constants, after1, type=('rel' if theorem.operations[0].type == Operation.RELATION else 'exp')) else: self.after(theorem.formula, predecessors=[], rule_name="insert") return poas for ax in [x for x in Theorem.theorems if x.folder == folder]: im = Image() im.addClickListener(onClick(ax)) im.setUrl(latex_to_url(ax.formula.to_latex())) self.pok.add(im) self.images.append(im)
class ListBoxDemo(SimplePanel): def __init__(self): SimplePanel.__init__(self) hPanel = HorizontalPanel() hPanel.setSpacing(10) self.list1 = ListBox() self.list1.setVisibleItemCount(10) self.list1.addItem("Item 1") self.list1.addItem("Item 2") self.list1.addItem("Item 3") self.list1.addChangeListener(getattr(self, "onList1ItemSelected")) self.list2 = ListBox() self.list2.setVisibleItemCount(1) self.list2.addItem("Item A") self.list2.addItem("Item B") self.list2.addItem("Item C") self.list2.addChangeListener(getattr(self, "onList2ItemSelected")) hPanel.add(self.list1) hPanel.add(self.list2) self.add(hPanel) def onList1ItemSelected(self, event): item = self.list1.getItemText(self.list1.getSelectedIndex()) Window.alert("You selected " + item + " from list 1") def onList2ItemSelected(self, event): item = self.list2.getItemText(self.list2.getSelectedIndex()) Window.alert("You selected " + item + " from list 2")
class SelectionBox(HorizontalPanel): """ This is a text box with the corresponding word that is to be normalized """ def __init__(self, token_index, target_word, options): HorizontalPanel.__init__(self) self.token_index = token_index self.table = FlexTable() self.label = Label(target_word + ":\t") self.dropdown = ListBox() for option in options: self.dropdown.addItem(option) self.add(self.label) self.add(self.dropdown)
def _create_add_dialog(self): contents = VerticalPanel(StyleName="Contents", Spacing=4) wtype = ListBox(Width="14em") wtype.addChangeListener(self) for wclass in self.WEIGHT_TYPES: wtype.addItem(wclass.NAME, value=wclass) panel = HorizontalPanel(Spacing=8) panel.add(HTML("Weight type: ", **captionstyle)) panel.add(wtype) contents.add(panel) contents.add(Button("OK", getattr(self, '_close_add_dialog'))) dialog = DialogBox(glass=True) dialog.setHTML('<b>Add a new type of weights</b>') dialog.setWidget(contents) return dialog, wtype
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()
def onModuleLoad(self): '''Create initial view of the panel. ''' # Container that keeps everything self.panel = VerticalPanel() self.panel.setSpacing(10) # Create list of projects proj_list = ListBox(Height='34px') proj_list.addItem('') proj_list.setVisibleItemCount(0) proj_list.addChangeListener(getattr(self, 'on_project_changed')) proj_list.setStyleName('form-control input-lg') self.proj_row = Form_Row('Select project', proj_list, help='project, status of which you want to report') # Project-specific container self.project_panel = VerticalPanel() # Submit report button self.submit_btn = Button('Submit report', getattr(self, 'send_data')) self.submit_btn.setStyleName('btn btn-primary btn-lg') self.submit_btn.setEnabled(False) self.msg_lbl = HTMLPanel('', Width='475px') # Add controls here self.panel.add(self.proj_row.panel()) self.panel.add(self.project_panel) self.panel.add(Label(Height='20px')) self.panel.add(self.msg_lbl) btn_holder = HorizontalPanel() btn_holder.add(self.submit_btn) help_btn = HTMLPanel('') help_btn.setHTML(MODAL_PNL) btn_holder.add(Label(Width='10px')) btn_holder.add(help_btn) self.panel.add(btn_holder) self.root = RootPanel('report') self.root.add(self.panel)
def make_panel(self): duration = ListBox() duration.setVisibleItemCount(1) choices = [ 1, 2, 3, 4, 5, 7, 10, 15, 20, 25, 30, 40, 50, 60 ] for seconds in choices: duration.addItem( '%ds' % seconds if seconds < 60 else '%dm' % (seconds / 60), seconds) duration.setSelectedIndex(2) button = Button('test') handler = TestHandler(duration) button.addClickListener(handler.func) panel = HorizontalPanel() panel.add(duration) panel.add(button) return panel
def __init__(self): Sink.__init__(self) self.fDialogButton = Button("Show Dialog", self) self.fPopupButton = Button("Show Popup", self) panel = VerticalPanel() panel.add(self.fPopupButton) panel.add(self.fDialogButton) list = ListBox() list.setVisibleItemCount(5) for i in range(10): list.addItem("list item %d" % i) panel.add(list) panel.setSpacing(8) self.initWidget(panel)
def __init__(self): Sink.__init__(self) self.fDialogButton = Button("Show Dialog", self) self.fPopupButton = Button("Show Popup", self) panel = VerticalPanel() panel.add(self.fPopupButton) panel.add(self.fDialogButton) list = ListBox() list.setVisibleItemCount(5) for i in range(10): list.addItem("list item %d" % i) panel.add(list) panel.setSpacing(8) self.initWidget(panel)
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())
def createHeadingStyleList(self, caption): lb = ListBox() lb.addChangeListener(self) lb.setVisibleItemCount(1) lb.addItem(caption) lb.addItem("Heading1", "h1") lb.addItem("Heading2", "h2") lb.addItem("Heading3", "h3") lb.addItem("Heading4", "h4") lb.addItem("Heading5", "h5") return lb
def createHeadingStyleList(self, caption): lb = ListBox() lb.addChangeListener(self) lb.setVisibleItemCount(1) lb.addItem(caption) lb.addItem("Heading1", "h1") lb.addItem("Heading2", "h2") lb.addItem("Heading3", "h3") lb.addItem("Heading4", "h4") lb.addItem("Heading5", "h5") return lb
def onModuleLoad(self): self.layout = HorizontalPanel() # Each demo will set their own dimensions, so it doesn't matter # what we initialize the canvas to. canvas = GWTCanvas(400,400) canvas.addStyleName("gwt-canvas") self.demos = [] # Create demos self.demos.append(StaticDemo(canvas)) self.demos.append(LogoDemo(canvas)) self.demos.append(ParticleDemo(canvas)) self.demos.append(GradientDemo(canvas)) self.demos.append(SuiteDemo(canvas)) # Add them to the selection list box lb = ListBox() lb.setStyleName("listBox") for i in range(len(self.demos)): lb.addItem(self.demos[i].getName()) lb.addChangeListener(self) # start off with the first demo self.currentDemo = self.demos[0] # Add widgets to self.layout and RootPanel vp = VerticalPanel() vp.add(lb) vp.add(canvas) self.layout.add(vp) if self.currentDemo.getControls() is not None: self.layout.add(self.currentDemo.getControls()) RootPanel().add(self.layout) self.currentDemo.drawDemo()
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 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)
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 RolePanel(AbsolutePanel): user = None selectedRole = None roleList = None roleCombo = None addBtn = None removeBtn = None def __init__(self,parent): AbsolutePanel.__init__(self) self.roleList = ListBox() self.roleList.setWidth('300px') self.roleList.setVisibleItemCount(6) self.roleList.addChangeListener(self.onListChange) #self.roleList.addKeyboardListener(self) self.roleCombo = ListBox() self.roleCombo.addKeyboardListener(self) self.roleCombo.addChangeListener(self.onComboChange) self.addBtn = Button("Add") self.addBtn.setEnabled(False) self.removeBtn = Button("Remove") self.removeBtn.setEnabled(False) vpanel = VerticalPanel() vpanel.add(self.roleList) hpanel = HorizontalPanel() hpanel.add(self.roleCombo) hpanel.add(self.addBtn) hpanel.add(self.removeBtn) vpanel.add(hpanel) self.add(vpanel) self.clearForm() return def clearForm(self): self.user = None self.updateRoleList([]) self.roleCombo.setItemTextSelection(None) def updateRoleList(self,items): self.roleList.clear() for item in items: self.roleList.addItem(item) #self.roleList.addItem(' ') #self.roleList.addItem('- - - - - - - -') def updateRoleCombo(self,choices, default_): self.roleCombo.clear() for choice in choices: self.roleCombo.addItem(choice) self.roleCombo.selectValue(default_) def onComboChange(self, sender, keyCode=None, modifiers=None): selected = self.roleCombo.getSelectedItemText() if not selected \ or selected[0] == ApplicationConstants.ROLE_NONE_SELECTED \ or not self.user: self.addBtn.setEnabled(False) self.selectedRole=None else: self.addBtn.setEnabled(True) self.selectedRole=selected[0] self.removeBtn.setEnabled(False) self.roleList.setItemTextSelection(None) def onListChange(self, sender): selected = self.roleList.getSelectedItemText() if selected: self.removeBtn.setEnabled(True) self.selectedRole=selected[0] else: self.removeBtn.setEnabled(False) self.selectedRole=None self.addBtn.setEnabled(False) self.roleCombo.setItemTextSelection(None) def onClick(self, sender): pass def onKeyUp(self, sender, keyCode, modifiers): if sender == self.roleCombo: self.onComboChange(sender) elif sender == self.roleList: self.onListChange(sender) def onKeyDown(self, sender, keyCode, modifiers): pass def onKeyPress(self, sender, keyCode, modifiers): 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 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 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 UserListPanel(VerticalPanel): def __init__(self, tabPanel, topPanel, **kwargs): VerticalPanel.__init__(self, StyleName='user-list-panel', **kwargs) self.tabPanel = tabPanel self.topPanel = topPanel self.iconAdder = None self.iconPanel = None self.nSelected = 0 self.leftPanelWidth = 340 self.widthFudgeFactor = 25 def clear(self): VerticalPanel.clear(self) self.nSelected = 0 def updateResultLink(self): self.resultLink.setHTML('Results: <a href="%s">link</a>' % self.tabPanel.resultsLink()) def setUsers(self, title, users, kwargs): self.users = users self.nUsers = len(users) self.title = title self.resultPanel = HorizontalPanel(StyleName='result-panel') self.add(self.resultPanel) self.leftPanel = VerticalPanel(StyleName='results-left-panel', Width=self.leftPanelWidth) self.resultPanel.add(self.leftPanel) if not users: self.iconPanel = None self.leftPanel.add(HTML(title, StyleName='result-title')) else: # Set a display order that will show everything for now. self.displayOrder = range(self.nUsers) self.largeAvatar = LargeAvatar(self, self.tabPanel, self.topPanel) self.leftPanel.add(self.largeAvatar) resultPanelBottomLeft = VerticalPanel( StyleName='results-left-panel-bottom-left') self.resultLink = HTML(StyleName='result-detail') self.updateResultLink() resultPanelBottomLeft.add(self.resultLink) self.iconSizePanel = HorizontalPanel() self.iconSizePanel.add( HTML('Icons: ', StyleName='result-detail')) self.iconSizeLb = lb = ListBox() i = 0 for text, key in _iconData: lb.addItem(text, key) if key == _iconSize: lb.setSelectedIndex(i) i += 1 lb.addChangeListener(IconSizeChanger(self)) self.iconSizePanel.add(lb) resultPanelBottomLeft.add(self.iconSizePanel) if self.nUsers > 1: self.sortPanel = HorizontalPanel() self.sortPanel.add( HTML('Sort: ', StyleName='result-detail')) self.lb = lb = ListBox() i = 0 for text, key in _sortKeyData: lb.addItem(text, key) if key == _sortKey: lb.setSelectedIndex(i) i += 1 lb.addChangeListener(self) self.sortPanel.add(lb) resultPanelBottomLeft.add(self.sortPanel) self.filterPanel = HorizontalPanel() resultPanelBottomLeft.add(self.filterPanel) self.addFilterWidgets() if self.topPanel.loggedIn(): if 'screennames' in kwargs: resultPanelBottomLeft.add(tweet.SimpleTweetPanel( kwargs['screennames'], len(self.users), self.topPanel)) elif 'query' in kwargs: resultPanelBottomLeft.add(tweet.PrepareTweetButton( kwargs['query'], len(self.users), self.tabPanel.tabName, self.topPanel)) self.leftPanel.add(resultPanelBottomLeft) self.iconPanel = VerticalPanel(StyleName='icon-outer-panel') self.resultPanel.add(self.iconPanel) self.images = [] for u in users: url = u['profile_image_url'] i = Image(url, StyleName='avatar-' + _iconSize) # Does calling prefetch actually help? i.prefetch(url) i._user = u i._selected = False i.addMouseListener(self) self.images.append(i) self.showUsers() def addFilterWidgets(self): """If we're logged in (and hence the friends list is available), create a filter listbox. If not, tell the loginPanel that we exist so it can call us when the login is complete.""" if self.topPanel.loggedIn(): # Window.alert('Logged in') self.filterPanel.add( HTML('Filter: ', StyleName='result-detail')) self.filterChanger = FilterChanger(self, self.topPanel) self.filterBox = ListBox() self.filterBox.addItem('None', 0) self.filterBox.addItem( 'Following (%d of %d)' % (self.filterChanger.nFriends, self.nUsers), 1) self.filterBox.addItem( "Not following (%d of %d)" % (self.nUsers - self.filterChanger.nFriends, self.nUsers), 2) self.filterBox.addChangeListener(self.filterChanger) self.filterPanel.add(self.filterBox) else: # Not yet logged in. Add ourselves to the list of UserListPanels # that the loginPanel will call when it's ready. self.topPanel.loginPanel.addUserListPanel(self) def onChange(self, sender): global _sortKey _sortKey = self.lb.getValue(self.lb.getSelectedIndex()) self.updateResultLink() self.showUsers() def showUsers(self): # Cancel any existing timed icon additions before changing # self.displayOrder. if self.iconAdder is not None: self.iconAdder.cancel() self.iconAdder = None self.iconPanel.clear() # Set a title above the icons. if hasattr(self, 'filterChanger'): order = self.filterChanger.currentOrder if order == 0: title = self.title else: if order == 1: n = self.filterChanger.nFriends detail = 'follow' else: n = self.nUsers - self.filterChanger.nFriends detail = "don't follow" if n == 0: if detail == 'follow': title = "You don't follow any of them!" else: title = "You already follow them all!" else: if n > 1: plural = 's' else: plural = '' title = 'The %d user%s you %s:' % (n, plural, detail) else: title = self.title self.iconPanel.add(HTML(title, StyleName='result-title')) if not self.displayOrder: # There are no users to show. return decreasing = _sortKey in ( 'friends_count', 'followers_count', 'statuses_count') alpha = _sortKey in ('screen_name', 'name', 'location') def _keyFunc(n): value = self.users[n][_sortKey] if decreasing: return -1 * value elif alpha: if value: return value.lower().strip() else: # Uh, put this towards the end (of ASCII at least) return '~~~' else: return value # Don't use sorted here, as it replaces the display order list # (which is actually being maintained for us by our FilterChanger # instance). self.displayOrder.sort(key=_keyFunc) self.icons = FlowPanel(StyleName='icon-panel') self.adjustWidths() self.iconPanel.add(self.icons) self.iconAdder = IconAdder(self) Timer.Timer(1, self.iconAdder) if self.nSelected == 0: self.largeAvatar.setUser(self.users[self.displayOrder[0]]) def onMouseEnter(self, img): if not self.nSelected: self.largeAvatar.setUser(img._user) def onMouseMove(self, img, x, y): pass def onMouseLeave(self, img): pass def onMouseDown(self, img, x, y): self.largeAvatar.setUser(img._user) if not img._selected and self.nSelected: self._unselectAll() self._toggleSelect(img) def onMouseUp(self, img, x, y): pass def _toggleSelect(self, img): if img._selected: self._unselect(img) else: self._select(img) def _unselect(self, img): if img._selected: img.removeStyleDependentName('selected') self.nSelected -= 1 img._selected = False def _select(self, img): if not img._selected: img.addStyleDependentName('selected') self.nSelected += 1 img._selected = True def _unselectAll(self): for img in self.images: self._unselect(img) def unselectNotFollowed(self): for img in self.images: if not img._user['following'] and img._selected: self._unselect(img) def unselectFollowed(self): for img in self.images: if img._user['following'] and img._selected: self._unselect(img) def setIconSizes(self): for img in self.images: selected = img._selected if selected: self._unselect(img) img.setStyleName('avatar-' + _iconSize) if selected: self._select(img) def adjustWidths(self, windowWidth=None): if windowWidth is None: windowWidth = Window.getClientWidth() width = windowWidth - self.leftPanelWidth - self.widthFudgeFactor if self.iconPanel is not None: self.icons.setWidth(width) def adjustSize(self, width, height): self.adjustWidths(width)
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))
def createFontList(self): lb = ListBox() lb.addChangeListener(self) lb.setVisibleItemCount(1) lb.addItem("Font", "") lb.addItem("Normal", "") lb.addItem("Times New Roman", "Times New Roman") lb.addItem("Arial", "Arial") lb.addItem("Aramanth", "Aramanth") lb.addItem("Calibri", "Calibri") lb.addItem("Courier New", "Courier New") lb.addItem("Georgia", "Georgia") lb.addItem("Helvetica", "Helvetica") lb.addItem("Symbol", "Symbol") lb.addItem("Trebuchet", "Trebuchet") lb.addItem("Verdana", "Verdana") return lb
def createFontSizes(self): lb = ListBox() lb.addChangeListener(self) lb.setVisibleItemCount(1) lb.addItem("Size") lb.addItem("XXsmall") lb.addItem("Xsmall") lb.addItem("small") lb.addItem("medium") lb.addItem("large") lb.addItem("Xlarge") lb.addItem("XXlarge") return lb
def createColorList(self, caption): lb = ListBox() lb.addChangeListener(self) lb.setVisibleItemCount(1) lb.addItem(caption) lb.addItem("White", "white") lb.addItem("Black", "black") lb.addItem("Red", "red") lb.addItem("Green", "green") lb.addItem("Yellow", "yellow") lb.addItem("Blue", "blue") return lb
class Milestones_Row(SimplePanel): ''' Create and edit projects ''' def __init__(self, milestone_names, milestone_dates): # We need to use old form of inheritance because of pyjamas SimplePanel.__init__(self) self.milestone_dates = milestone_dates self.hpanel = HorizontalPanel() self.hpanel.setVerticalAlignment(HasAlignment.ALIGN_TOP) self.name = ListBox(Height='34px', Width='208px') self.name.setStyleName('form-control input-lg') self.name.addChangeListener(getattr(self, 'on_milestone_changed')) for m in milestone_names: self.name.addItem(m) if len(self.milestone_dates) > 0: self.planned_completion = Label(self.milestone_dates[0]) else: self.planned_completion = Label('Undefined') self.planned_completion.setStyleName('form-control text-normal') self.expected_completion = Report_Date_Field(cal_ID='end') self.expected_completion.getTextBox().setStyleName('form-control') self.expected_completion.setRegex(DATE_MATCHER) self.expected_completion.appendValidListener(self._display_ok) self.expected_completion.appendInvalidListener(self._display_error) self.expected_completion.validate(None) self.hpanel.add(self.name) self.hpanel.add(Label(Width='10px')) self.hpanel.add(self.planned_completion) self.hpanel.add(Label(Width='10px')) self.hpanel.add(self.expected_completion) def get_name_txt(self): '''Return project name. ''' return self.name.getText() def get_milestone_data(self): '''Get milestone data and return in the form suitable for passing to the model. ''' name = self.name.getItemText(self.name.getSelectedIndex()) planned_completion = self.planned_completion.getText() expected_completion = self.expected_completion.getTextBox().getText() return (name, planned_completion, expected_completion) 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') def on_milestone_changed(self, event): ''' Change completion date if milestone changed ''' ind = self.name.getSelectedIndex() self.planned_completion.setText(self.milestone_dates[ind])
class RolePanel(AbsolutePanel): user = None selectedRole = None roleList = None roleCombo = None addBtn = None removeBtn = None def __init__(self, parent): AbsolutePanel.__init__(self) self.roleList = ListBox() self.roleList.setWidth('300px') self.roleList.setVisibleItemCount(6) self.roleList.addChangeListener(self.onListChange) #self.roleList.addKeyboardListener(self) self.roleCombo = ListBox() self.roleCombo.addKeyboardListener(self) self.roleCombo.addChangeListener(self.onComboChange) self.addBtn = Button("Add") self.addBtn.setEnabled(False) self.removeBtn = Button("Remove") self.removeBtn.setEnabled(False) vpanel = VerticalPanel() vpanel.add(self.roleList) hpanel = HorizontalPanel() hpanel.add(self.roleCombo) hpanel.add(self.addBtn) hpanel.add(self.removeBtn) vpanel.add(hpanel) self.add(vpanel) self.clearForm() return def clearForm(self): self.user = None self.updateRoleList([]) self.roleCombo.setItemTextSelection(None) def updateRoleList(self, items): self.roleList.clear() for item in items: self.roleList.addItem(item) #self.roleList.addItem(' ') #self.roleList.addItem('- - - - - - - -') def updateRoleCombo(self, choices, default_): self.roleCombo.clear() for choice in choices: self.roleCombo.addItem(choice) self.roleCombo.selectValue(default_) def onComboChange(self, sender, keyCode=None, modifiers=None): selected = self.roleCombo.getSelectedItemText() if not selected \ or selected[0] == ApplicationConstants.ROLE_NONE_SELECTED \ or not self.user: self.addBtn.setEnabled(False) self.selectedRole = None else: self.addBtn.setEnabled(True) self.selectedRole = selected[0] self.removeBtn.setEnabled(False) self.roleList.setItemTextSelection(None) def onListChange(self, sender): selected = self.roleList.getSelectedItemText() if selected: self.removeBtn.setEnabled(True) self.selectedRole = selected[0] else: self.removeBtn.setEnabled(False) self.selectedRole = None self.addBtn.setEnabled(False) self.roleCombo.setItemTextSelection(None) def onClick(self, sender): pass def onKeyUp(self, sender, keyCode, modifiers): if sender == self.roleCombo: self.onComboChange(sender) elif sender == self.roleList: self.onListChange(sender) def onKeyDown(self, sender, keyCode, modifiers): pass def onKeyPress(self, sender, keyCode, modifiers): pass
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 AutoCompleteByURLTextBox(AutoCompleteTextBox): def __init__(self, url): self.choicesPopup = PopupPanel(True) self.choices = ListBox() self.items = AutoCompleteURL(url) self.popupAdded = False self.visible = False TextBox.__init__(self) self.addKeyboardListener(self) self.choices.addChangeListener(self) self.setStyleName("AutoCompleteTextBox") self.choicesPopup.add(self.choices) self.choicesPopup.addStyleName("AutoCompleteChoices") self.choices.setStyleName("list") self.url = url """ def setCompletionItems(self, items): if not items.getCompletionItems: items = AutoCompletionURL(self.url) self.items = items def getCompletionItems(self): return self.items """ def onKeyUp(self, arg0, arg1, arg2): if arg1 == KeyboardListener.KEY_DOWN: selectedIndex = self.choices.getSelectedIndex() selectedIndex += 1 if selectedIndex > self.choices.getItemCount(): selectedIndex = 0 self.choices.setSelectedIndex(selectedIndex) return if arg1 == KeyboardListener.KEY_UP: selectedIndex = self.choices.getSelectedIndex() selectedIndex -= 1 if selectedIndex < 0: selectedIndex = self.choices.getItemCount() self.choices.setSelectedIndex(selectedIndex) return if arg1 == KeyboardListener.KEY_ENTER: if self.visible: self.complete() return if arg1 == KeyboardListener.KEY_ESCAPE: self.choices.clear() self.choicesPopup.hide() self.visible = False return text = self.getText() matches = [] if len(text) > 0: matches = self.items.getCompletionItems(text) if len(matches) > 0: self.choices.clear() for i in range(len(matches)): self.choices.addItem(matches[i]) if len(matches) == 1 and matches[0] == text: self.choicesPopup.hide() else: self.choices.setSelectedIndex(0) self.choices.setVisibleItemCount(len(matches) + 1) if not self.popupAdded: RootPanel().add(self.choicesPopup) self.popupAdded = True self.choicesPopup.show() self.visible = True self.choicesPopup.setPopupPosition(self.getAbsoluteLeft(), self.getAbsoluteTop() + self.getOffsetHeight()) self.choices.setWidth(self.getOffsetWidth() + "px") else: self.visible = False self.choicesPopup.hide()
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 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 TodoApp: def onModuleLoad(self): self.remote = DataService() panel = VerticalPanel() self.todoTextBox = TextBox() self.todoTextBox.addKeyboardListener(self) self.todoList = ListBox() self.todoList.setVisibleItemCount(7) self.todoList.setWidth("200px") self.todoList.addClickListener(self) panel.add(Label("Add New Todo:")) panel.add(self.todoTextBox) panel.add(Label("Click to Remove:")) panel.add(self.todoList) self.status = Label() panel.add(self.status) RootPanel().add(panel) 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, and will add the item in the text box to the list when the user presses the enter key. In the future, this method will also handle the auto complete feature. """ if keyCode == KeyboardListener.KEY_ENTER and sender == self.todoTextBox: id = self.remote.addTask(sender.getText(), self) sender.setText("") if id < 0: self.status.setText("Server Error or Invalid Response") def onClick(self, sender): id = self.remote.deleteTask(sender.getValue(sender.getSelectedIndex()), self) if id < 0: self.status.setText("Server Error or Invalid Response") def onRemoteResponse(self, response, request_info): self.status.setText("response received") if request_info.method == 'getTasks' or request_info.method == 'addTask' or request_info.method == 'deleteTask': self.status.setText(self.status.getText() + "HERE!") self.todoList.clear() for task in response: self.todoList.addItem(task[0]) self.todoList.setValue(self.todoList.getItemCount() - 1, task[1]) else: 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 JSONRPCExample: def onModuleLoad(self): self.TEXT_WAITING = "Waiting for response..." self.TEXT_ERROR = "Server Error" self.METHOD_ECHO = "Echo" self.METHOD_REVERSE = "Reverse" self.METHOD_UPPERCASE = "UPPERCASE" self.METHOD_LOWERCASE = "lowercase" self.METHOD_NONEXISTANT = "Non existant" self.methods = [self.METHOD_ECHO, self.METHOD_REVERSE, self.METHOD_UPPERCASE, self.METHOD_LOWERCASE, self.METHOD_NONEXISTANT] self.remote_php = EchoServicePHP() self.remote_py = EchoServicePython() self.status=Label() self.text_area = TextArea() self.text_area.setText("""{'Test'} [\"String\"] \tTest Tab Test Newline\n after newline """ + r"""Literal String: {'Test'} [\"String\"] """) self.text_area.setCharacterWidth(80) self.text_area.setVisibleLines(8) 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_php = Button("Send to PHP Service", self) self.button_py = Button("Send to Python Service", self) buttons = HorizontalPanel() buttons.add(self.button_php) buttons.add(self.button_py) 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 some text below, and press a button to send the text to an Echo service on your server. An echo service simply sends the exact same text back that it receives. </p>""" panel = VerticalPanel() panel.add(HTML(info)) panel.add(self.text_area) panel.add(method_panel) panel.add(buttons) panel.add(self.status) RootPanel().add(panel) def onClick(self, sender): self.status.setText(self.TEXT_WAITING) method = self.methods[self.method_list.getSelectedIndex()] text = self.text_area.getText() # demonstrate proxy & callMethod() if sender == self.button_php: if method == self.METHOD_ECHO: id = self.remote_php.echo(text, self) elif method == self.METHOD_REVERSE: id = self.remote_php.callMethod("reverse", [text], self) elif method == self.METHOD_UPPERCASE: id = self.remote_php.uppercase(text, self) elif method == self.METHOD_LOWERCASE: id = self.remote_php.lowercase(self, msg=text) elif method == self.METHOD_NONEXISTANT: id = self.remote_php.nonexistant(text, self) else: if method == self.METHOD_ECHO: id = self.remote_py.echo(text, self) elif method == self.METHOD_REVERSE: id = self.remote_py.reverse(text, self) elif method == self.METHOD_UPPERCASE: id = self.remote_py.uppercase(text, self) elif method == self.METHOD_LOWERCASE: id = self.remote_py.lowercase(text, self) elif method == self.METHOD_NONEXISTANT: id = self.remote_py.nonexistant(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 TheoremPanel(ScrollPanel): def __init__(self, after): ScrollPanel.__init__(self, Size=("630px", "500px")) self.after = after self.pok = VerticalPanel() self.add(self.pok) self.images = list() def onItemSelected(): item = self.list2.getItemText(self.list2.getSelectedIndex()) self.refresh_theorems(item) self.list2 = ListBox() self.list2.setVisibleItemCount(1) for f in Theorem.get_all_folders(): self.list2.addItem(f) self.pok.add(self.list2) self.list2.addChangeListener(onItemSelected) self.refresh_theorems( self.list2.getItemText(self.list2.getSelectedIndex())) def remove_images(self): for im in self.images: self.pok.remove(im) self.images = list() def refresh_theorems(self, folder): self.remove_images() def onClick(theorem): def name(n): return "var" + str(n + 1) def print_scheme(n): return [ "\\alpha", "\\beta", "\\gamma", "\\delta", "\\epsilon" ][n] def poas(sender): if len(theorem.operations) == 1: constants = [ Operation("const" + str(i + 1), 0, print_scheme(i), name(i), Operation.EXPRESSION) for i in range(theorem.operations[0].no_of_args) ] def after1(f): self.after(theorem.formula.substitute_definition( Formula([theorem.operations[0]] + constants), f), predecessors=[], rule_name="insert") request_formula([op for op in proof.get_operations()] + constants, after1, type=('rel' if theorem.operations[0].type == Operation.RELATION else 'exp')) else: self.after(theorem.formula, predecessors=[], rule_name="insert") return poas for ax in [x for x in Theorem.theorems if x.folder == folder]: im = Image() im.addClickListener(onClick(ax)) im.setUrl(latex_to_url(ax.formula.to_latex())) self.pok.add(im) self.images.append(im)
class PopupPagina(PopupPanel): def __init__(self, autoHide=None, modal=True, **kwargs): PopupPanel.__init__(self, autoHide, modal, **kwargs) datasource = None id = None if kwargs.has_key("datasrc"): datasource = kwargs["datasrc"] if kwargs.has_key("id"): id = kwargs["id"] self.setSize(Window.getClientWidth() - 50, Window.getClientHeight() - 50) self.setPopupPosition(20, 0) DOM.setAttribute(self, "align", "center") # self.dbProxInstrucao = DialogBox() # self.dbProxInstrucao.setHTML("Alow") # botton = Button("Ok") # botton.addClickListener(self.onCloseDialog) # self.dbProxInstrucao.setWidget(botton) self.caption = HTML() self.child = None self.setHTML("<b>Soma de Matrizes.</b>") self.dragging = False self.dragStartX = 0 self.dragStartY = 0 self.imageFechar = Image("images/fechar.gif", Size=("32px", "32px"), StyleName="gwt-ImageButton") self.imgbtnDesfazer = Image("images/previous-arrow.png", Size=("32px", "20px"), StyleName="gwt-ImageButton") self.imgbtnFazer = Image("images/next-arrow.png", Size=("32px", "20px"), StyleName="gwt-ImageButton") # self.imgbtnDesfazer.addClickListener(desfazerProxOperacao) # self.imgbtnFazer.addClickListener(fazerProxOperacao) self.btnAutomatic = Button("Automático", self.onIniciarAnimacaoAutomatica) self.btnInterativo = Button("Interativo") if id == "escalar": self.btnStepByStep = Button("Passo a passo", IniciarAnimacaoPassoAPasso) else: self.btnStepByStep = Button("Passo a passo", self.onIniciarAnimacaoPassoAPasso) self.btnFazer = Button("fazer >>", fazerProxOperacao) # self.btnFazer.setEnabled(False); self.btnDesfazer = Button("<< desfazer", desfazerProxOperacao) # self.btnDesfazer.setEnabled(False); self.btnFechar = PushButton(imageFechar, imageFechar) self.btnTestarResposta = Button("Testar Solução") self.lbVelocidade = ListBox() self.lbVelocidade.setID("lbseg") self.lbVelocidade.addItem("0.5 segundo", value=2) self.lbVelocidade.addItem("1 segundo", value=1) self.lbVelocidade.addItem("2 segundos", value=0.5) self.lbVelocidade.addItem("3 segundos", value=1 / 3) self.lbVelocidade.addItem("4 segundos", value=0.25) self.lbVelocidade.addItem("5 segundos", value=0.20) self.lbVelocidade.addItem("6 segundos", value=0.167) self.lbVelocidade.addItem("7 segundos", value=0.143) self.lbVelocidade.addItem("8 segundos", value=0.125) self.lbVelocidade.addItem("10 segundos", value=0.1) lblinha1 = ListBox() lblinha1.setID("lm1") lblinha1.addItem("1", value=1) lblinha1.addItem("2", value=2) lblinha1.addItem("3", value=3) lblinha1.addItem("4", value=4) lblinha1.addItem("5", value=5) lblinha2 = ListBox() lblinha2.setID("lm2") lblinha2.addItem("1", value=1) lblinha2.addItem("2", value=2) lblinha2.addItem("3", value=3) lblinha2.addItem("4", value=4) lblinha2.addItem("5", value=5) lbcoluna1 = ListBox() lbcoluna1.setID("cm1") lbcoluna1.addItem("1", value=1) lbcoluna1.addItem("2", value=2) lbcoluna1.addItem("3", value=3) lbcoluna1.addItem("4", value=4) lbcoluna1.addItem("5", value=5) lbcoluna1.addItem("6", value=6) lbcoluna1.addItem("7", value=7) lbcoluna2 = ListBox() lbcoluna2.setID("cm2") lbcoluna2.addItem("1", value=1) lbcoluna2.addItem("2", value=2) lbcoluna2.addItem("3", value=3) lbcoluna2.addItem("4", value=4) lbcoluna2.addItem("5", value=5) lbcoluna2.addItem("6", value=6) lbcoluna2.addItem("7", value=7) self.lblStatus = Label("Label para Status") # Eventos self.imageFechar.addClickListener(self.onFecharPopup) # Cabeçalho da poupPanel self.grid = Grid(1, 16) self.grid.setWidth(self.getWidth()) self.grid.setHTML(0, 0, "<b>Matriz 1:</b> Nº Linhas:") self.grid.setWidget(0, 1, lblinha1) self.grid.setText(0, 2, "Nº Colunas:") self.grid.setWidget(0, 3, lbcoluna1) self.grid.setHTML(0, 4, "<b>Matriz 2:</b> Nº Linhas:") self.grid.setWidget(0, 5, lblinha2) self.grid.setText(0, 6, "Nº Colunas:") self.grid.setWidget(0, 7, lbcoluna2) # self.grid.setWidget(0, 3, self.txtColunas) self.grid.setWidget(0, 8, self.btnStepByStep) self.grid.setWidget(0, 9, self.btnDesfazer) self.grid.setWidget(0, 10, self.btnFazer) self.grid.setHTML(0, 11, "<b>Velocidade:</b>") self.grid.setWidget(0, 12, self.lbVelocidade) self.grid.setWidget(0, 13, self.btnAutomatic) # self.grid.setWidget(0, 14, self.btnInterativo) self.grid.setWidget(0, 15, self.imageFechar) # self.grid.setWidget(0, 7, self.btnFechar) self.grid.getCellFormatter().setAlignment( 0, 15, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_TOP ) self.panel = FlexTable(Height="100%", width="100%", BorderWidth="0", CellPadding="0", CellSpacing="0") self.panel.setWidget(0, 0, self.caption) self.panel.setWidget(1, 0, self.grid) self.panel.getCellFormatter().setHeight(2, 0, "100%") self.panel.getCellFormatter().setWidth(2, 0, "100%") self.panel.getCellFormatter().setAlignment( 2, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_TOP ) self.panel.setID("contetepopup") painelhorizontal = HorizontalPanel() gridinterativa = FlexTable() painelhorizontal.add( HTML( "<canvas id='%s' datasrc='%s' width='%s' height='%s' style='image-rendering: optimizespeed !important; '></canvas>" % ("soma", datasource, "1000px", "500px") ) ) ftInterativo = FlexTable(Height="100%", width="100%", BorderWidth="0", CellPadding="0", CellSpacing="0") gridinterativa = Grid(4, 4) gridinterativa.setWidget( 0, 0, HTML( "<b>M1(</b><input type='text' class='gwt-TextBox' id='linha1' style='width: 25px; height:20px;' maxLength='1'><b> , </b>" ), ) gridinterativa.setWidget( 0, 1, HTML( "<input type='text' class='gwt-TextBox' id='coluna1' style='width: 25px;height:20px;' maxLength='1'><b>) +</b>" ), ) gridinterativa.setWidget( 0, 2, HTML( "<b>M2(</b> <input type='text' class='gwt-TextBox' id='linha2' style='width: 25px; height:20px;' maxLength='1'><b> , </b>" ), ) gridinterativa.setWidget( 0, 3, HTML( "<input type='text' class='gwt-TextBox' id='coluna2' style='width: 25px; height:20px;' maxLength='1'><b>) =</b>" ), ) gridinterativa.setWidget( 2, 0, HTML( " <b>(</b><input type='text' class='gwt-TextBox' id='n1' style='width: 25px; height:20px;' maxLength='1'><b>) +</b>" ), ) gridinterativa.setWidget( 2, 1, HTML( "<b>(</b><input type='text' class='gwt-TextBox' id='n2' style='width: 25px; height:20px;' maxLength='1'><b>)</b>" ), ) gridinterativa.setWidget( 2, 2, HTML( "<b>= </b> <input type='text' class='gwt-TextBox' id='solucao' style='width: 25px; height:20px;' maxLength='1'>" ), ) ftInterativo.setHTML(0, 0, "</br>") ftInterativo.setHTML(1, 0, "<b><h3>Painel Interativo<h3></b>") # ftInterativo.setWidget(2, 0, self.btnInterativo) ftInterativo.setWidget(3, 0, gridinterativa) ftInterativo.setWidget(4, 0, self.btnTestarResposta) ftInterativo.setHTML(5, 0, "</br>") ftInterativo.setHTML(6, 0, "Use a tecla tab para agilizar.") ftInterativo.getCellFormatter().setAlignment( 4, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_TOP ) ftInterativo.getCellFormatter().setAlignment( 1, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_TOP ) # painelhorizontal.add(ftInterativo) self.panel.setWidget(2, 0, painelhorizontal) self.panel.setWidget(3, 0, self.lblStatus) self.panel.setStyleName("dialogContent") PopupPanel.setWidget(self, self.panel) self.setStyleName("gwt-DialogBox") self.caption.setStyleName("Caption") self.caption.addMouseListener(self) # self.txtlm1.setFocus(True); def onFecharPopup(self, event): self.hide() PararAnimacao() def onIniciarAnimacaoPassoAPasso(self, event): self.btnFazer.setEnabled(True) self.btnDesfazer.setEnabled(True) if self.validarParametrosMatriz(): IniciarAnimacaoPassoAPasso() def onIniciarAnimacaoAutomatica(self, event): if self.validarParametrosMatriz(): IniciarAnimacaoAutomatica() def onTestarSolucao(self, event): pass # if self.validarParametrosMatriz(): # def onCloseDialog(self, event): # self.dbProxInstrucao.hide() # def onOpenDialog(self, event): # self.dbProxInstrucao.show() def validarParametrosTestarSolucao(): lm1 = DOM.getElementById("linha1") lm1 = lm1.value cm1 = DOM.getElementById("coluna1") cm1 = cm1.value lm2 = DOM.getElementById("linha2") lm2 = lm2.value cm2 = DOM.getElementById("coluna2") cm2 = cm2.value def validarParametrosMatriz(): lm1 = DOM.getElementById("lm1") lm1 = lm1.value cm1 = DOM.getElementById("cm1") cm1 = cm1.value lm2 = DOM.getElementById("lm2") lm2 = lm2.value cm2 = DOM.getElementById("cm2") cm2 = cm2.value if not lm1 or not lm2: Window.alert("Informe o numero de linhas da matriz M1 e M2.") return False if lm1 != lm2: Window.alert("A quantidade de linhas da matriz M1 deve ser igual a da matriz M2 para operação de soma.") return False if lm1 > "5" or lm2 > "5" or len(lm1) != 1 or len(lm2) != 1: Window.alert("A quantidade de linhas da matriz M1 e da matriz M2, deve ser menor ou igual a 5.") return False if not cm1 or not cm2: Window.alert("Informe o numero de colunas da matriz M1 e M2.") return False if cm1 != cm2: Window.alert("A quantidade de colunas da matriz M1 deve ser igual a da matriz M2 para operação de soma.") return False if cm1 > "7" or cm2 > "7" or len(cm1) != 1 or len(cm2) != 1: Window.alert("A quantidade de colunas da matriz M1 e da matriz M2, deve ser menor ou igual a 7.") return False return True def getHTML(self): return self.caption.getHTML() def getText(self): return self.caption.getText() def onEventPreview(self, event): # preventDefault on mousedown events, outside of the # dialog, to stop text-selection on dragging type = DOM.eventGetType(event) if type == "mousedown": target = DOM.eventGetTarget(event) elem = self.caption.getElement() event_targets_popup = target and DOM.isOrHasChild(elem, target) if event_targets_popup: DOM.eventPreventDefault(event) return PopupPanel.onEventPreview(self, event) def onMouseDown(self, sender, x, y): self.dragging = True DOM.setCapture(self.caption.getElement()) self.dragStartX = x self.dragStartY = y def onMouseMove(self, sender, x, y): if self.dragging: absX = x + self.getAbsoluteLeft() absY = y + self.getAbsoluteTop() self.setPopupPosition(absX - self.dragStartX, absY - self.dragStartY) def onMouseUp(self, sender, x, y): self.dragging = False DOM.releaseCapture(self.caption.getElement()) def onMouseLeave(self, self, x, y): pass def onMouseEnter(self, self, x, y): pass def remove(self, widget): if self.child != widget: return False self.panel.remove(widget) self.child = None return True def setHTML(self, html): self.caption.setHTML(html) def setText(self, text): self.caption.setText(text) def doAttachChildren(self): PopupPanel.doAttachChildren(self) self.caption.onAttach() def doDetachChildren(self): PopupPanel.doDetachChildren(self) self.caption.onDetach() def setWidget(self, widget): if self.child is not None: self.panel.remove(self.child) if widget is not None: self.panel.setWidget(1, 0, widget) self.child = widget
class WebPageEdit(Composite): def __init__(self, sink): Composite.__init__(self) self.remote = sink.remote panel = VerticalPanel(Width="100%", Spacing=8) self.view = Button("View", self) self.newpage = Button("New", self) self.todoId = None self.todoTextName = TextBox() self.todoTextName.addKeyboardListener(self) self.todoTextArea = RichTextEditor(basePath="/fckeditor/") self.todoTextArea.setWidth("100%") self.todoTextArea.addSaveListener(self) self.todoList = ListBox() self.todoList.setVisibleItemCount(7) self.todoList.setWidth("200px") self.todoList.addClickListener(self) self.fDialogButton = Button("Upload Files", self) self.status = HTML() panel.add(HTML("Status:")) panel.add(self.status) panel.add(self.fDialogButton) panel.add(Label("Create New Page (doesn't save current one!):")) panel.add(self.newpage) panel.add(Label("Add/Edit New Page:")) panel.add(self.todoTextName) panel.add(Label("Click to Load and Edit (doesn't save current one!):")) panel.add(self.todoList) panel.add(self.view) panel.add(Label("New Page HTML. Click 'save' icon to save. (pagename is editable as well)")) panel.add(self.todoTextArea) self.setWidget(panel) self.remote.getPages(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, and will add the item in the text box to the list when the user presses the enter key. In the future, this method will also handle the auto complete feature. """ pass def onSave(self, editor): self.status.setText("") name = self.todoTextName.getText() if not name: self.status.setText("Please enter a name for the page") return item = { 'name': name, 'text': self.todoTextArea.getHTML() } if self.todoId is None: rid = self.remote.addPage(item, self) else: item['id'] = self.todoId rid = self.remote.updatePage(item, self) if rid<0: self.status.setHTML("Server Error or Invalid Response") return def onClick(self, sender): if sender == self.newpage: self.todoId = None self.todoTextName.setText('') self.todoTextArea.setHTML('') return elif sender == self.view: name = self.todoTextName.getText() html = self.todoTextArea.getHTML() if not html: return p = HTMLDialog(name, html) p.setPopupPosition(10, 10) p.setWidth(Window.getClientWidth()-40) p.setHeight(Window.getClientHeight()-40) p.show() return elif sender == self.fDialogButton: Window.open(fileedit_url, "fileupload", "width=800,height=600") return dlg = FileDialog(fileedit_url) left = self.fDialogButton.getAbsoluteLeft() + 10 top = self.fDialogButton.getAbsoluteTop() + 10 dlg.setPopupPosition(left, top) dlg.show() id = self.remote.getPage(sender.getValue(sender.getSelectedIndex()),self) if id<0: self.status.setHTML("Server Error or Invalid Response") def onRemoteResponse(self, response, request_info): self.status.setHTML("response received") if request_info.method == 'getPage': self.status.setHTML(self.status.getText() + "HERE!") item = response[0] self.todoId = item['pk'] self.todoTextName.setText(item['fields']['name']) self.todoTextArea.setHTML(item['fields']['text']) elif (request_info.method == 'getPages' or request_info.method == 'addPage' or request_info.method == 'deletePage'): self.status.setHTML(self.status.getText() + "HERE!") self.todoList.clear() for task in response: self.todoList.addItem(task['fields']['name']) self.todoList.setValue(self.todoList.getItemCount()-1, str(task['pk'])) else: self.status.setHTML(self.status.getText() + "none!") def onRemoteError(self, code, message, request_info): self.status.setHTML("Server Error or Invalid Response: ERROR " + str(code) + " - " + str(message))
class I2CPanel : class saveStateListener : def __init__(self, panel) : self._saveStatePanel=panel def onRemoteResponse(self, response, request_info): self._saveStatePanel.returnStatement.setText("File saved:" + response) def onRemoteError(self, code, message, request_info): ErrorMessage( "Unable to contact server" ) class loadStateListener : def __init__(self, panel) : self._saveStatePanel=panel def onRemoteResponse(self, response, request_info): self._saveStatePanel.returnStatement.setText("File loaded:" + response) self._saveStatePanel.rpcService.I2CRegisterValues( self._saveStatePanel.getTotalCBCs(), I2CPanel.ReadRegisterValueListener(self._saveStatePanel) ) #refresh of text boxes def onRemoteError(self, code, message, request_info): ErrorMessage( "Unable to contact server" ) class ConnectedCBCListener : """ A class to listen for the response to the connectedCBCNames call """ def __init__(self, listBox) : self.listBox=listBox def onRemoteResponse(self, response, request_info): self.listBox.clear() if response == None: self.listBox.addItem("<none>") self.listBox.setEnabled( False ) else : for name in response : self.listBox.addItem(name) #e.g FE0CBC0 self.listBox.setEnabled(True) def onRemoteError(self, code, message, request_info): ErrorMessage( "Unable to contact server" ) class ReadRegisterValueListener : """ A class to listen for the response to the call to get the register values """ def __init__(self, panel) : self._I2Cpanel=panel self.textBoxes=self._I2Cpanel.i2cValueEntries def onRemoteResponse(self, response, request_info): #Call is now made for all connected CBCs for better stability of status box- fb for cbcName in self._I2Cpanel.getActiveCBCs(): if cbcName=='FE0CBC0': valuesTuple = response[response.keys()[0]] elif cbcName=='FE0CBC1': valuesTuple = response[response.keys()[1]] # For this chip loop over all the register and set the text box values for registerName in valuesTuple : box=self.textBoxes[registerName] status=self._I2Cpanel.statusValueEntries[registerName] box.setText( "0x%02x"%valuesTuple[registerName] ) box.setStyleAttribute( "background-color", "#FFFFFF" ) box.setEnabled( True ) #for some reason pyjas likes these separated - fb for registerName in valuesTuple: if response['FE0CBC0'][registerName]==response['FE0CBC1'][registerName]: self._I2Cpanel.statusValueEntries[registerName].setText("==") else: self._I2Cpanel.statusValueEntries[registerName].setText(" //") def onRemoteError(self, code, message, request_info): ErrorMessage( "Unable to contact server" ) class RefreshListener : """ A class that will wait for a response before refreshing the status box """ def __init__(self, panel) : self._Refresh = panel def onRemoteResponse(self, response, request_info): self._Refresh.rpcService.I2CRegisterValues( self._Refresh.getTotalCBCs(), I2CPanel.ReadRegisterValueListener(self._Refresh) ) #Live refresh of the status box def onRemoteError(self, code, message, request_info): ErrorMessage( "Unable to contact server" ) def __init__( self ) : # This is the service that will be used to communicate with the DAQ software self.rpcService = GlibRPCService.instance() # The main panel that everythings will be insided self.mainPanel = HorizontalPanel() self.mainPanel.setSpacing(10) self.i2cValueEntries = {} # The input boxes for all the registers self.statusValueEntries = {} # Displays the status of the i2cValueEntries self.stateValueEntries = {} # For load/save state self.fileName = {} # File name of the i2c registers # This is the list of available CBC chips. It will be populated by a call to the # server later. self.cbcList=ListBox(MultipleSelect=True, VisibleItemCount=10) self.cbcList.addItem( "waiting..." ) # Default text until I hear from the server what's connected self.cbcList.setEnabled( False ) self.cbcList.addChangeListener(self) self.rpcService.connectedCBCNames( None, I2CPanel.ConnectedCBCListener(self.cbcList) ) # Ask the server what's connected # This is the panel that will have the list of I2C registers. I'll split up the # registers into subjects to make them more manageable. self.mainSettings = DisclosurePanel("Main Control Registers") self.channelMasks = DisclosurePanel("Channel Masks") self.channelTrims = DisclosurePanel("Channel Trims") self.callSettings = VerticalPanel("Load/Save States") self.callSettings.setBorderWidth(1) self.callSettings.add(HTML("<center>Load/Save State</center>")) cbcListAndCallSettings=VerticalPanel() cbcListAndCallSettings.add(self.cbcList) cbcListAndCallSettings.add(self.callSettings) self.mainPanel.add(cbcListAndCallSettings) self.mainPanel.add(self.mainSettings) self.mainPanel.add(self.channelMasks) self.mainPanel.add(self.channelTrims) self.callSettings.add( self.createStatesPanel()) self.mainSettings.add( self.createRegisterPanel(["FrontEndControl","TriggerLatency","HitDetectSLVS","Ipre1","Ipre2","Ipsf","Ipa","Ipaos","Vpafb","Icomp","Vpc","Vplus","VCth","TestPulsePot","SelTestPulseDel&ChanGroup","MiscTestPulseCtrl&AnalogMux","TestPulseChargePumpCurrent","TestPulseChargeMirrCascodeVolt","CwdWindow&Coincid","MiscStubLogic"]) ) self.channelMasks.add( self.createRegisterPanel(["MaskChannelFrom008downto001","MaskChannelFrom016downto009","MaskChannelFrom024downto017","MaskChannelFrom032downto025","MaskChannelFrom040downto033","MaskChannelFrom048downto041","MaskChannelFrom056downto049","MaskChannelFrom064downto057","MaskChannelFrom072downto065","MaskChannelFrom080downto073","MaskChannelFrom088downto081","MaskChannelFrom096downto089","MaskChannelFrom104downto097","MaskChannelFrom112downto105","MaskChannelFrom120downto113","MaskChannelFrom128downto121","MaskChannelFrom136downto129","MaskChannelFrom144downto137","MaskChannelFrom152downto145","MaskChannelFrom160downto153","MaskChannelFrom168downto161","MaskChannelFrom176downto169","MaskChannelFrom184downto177","MaskChannelFrom192downto185","MaskChannelFrom200downto193","MaskChannelFrom208downto201","MaskChannelFrom216downto209","MaskChannelFrom224downto217","MaskChannelFrom232downto225","MaskChannelFrom240downto233","MaskChannelFrom248downto241","MaskChannelFrom254downto249"]) ) self.channelTrims.add( self.createRegisterPanel(["Channel001","Channel002","Channel003","Channel004","Channel005","Channel006","Channel007","Channel008","Channel009","Channel010","Channel011","Channel012","Channel013","Channel014","Channel015","Channel016","Channel017","Channel018","Channel019","Channel020","Channel021","Channel022","Channel023","Channel024","Channel025","Channel026","Channel027","Channel028","Channel029","Channel030","Channel031","Channel032","Channel033","Channel034","Channel035","Channel036","Channel037","Channel038","Channel039","Channel040","Channel041","Channel042","Channel043","Channel044","Channel045","Channel046","Channel047","Channel048","Channel049","Channel050","Channel051","Channel052","Channel053","Channel054","Channel055","Channel056","Channel057","Channel058","Channel059","Channel060","Channel061","Channel062","Channel063","Channel064","Channel065","Channel066","Channel067","Channel068","Channel069","Channel070","Channel071","Channel072","Channel073","Channel074","Channel075","Channel076","Channel077","Channel078","Channel079","Channel080","Channel081","Channel082","Channel083","Channel084","Channel085","Channel086","Channel087","Channel088","Channel089","Channel090","Channel091","Channel092","Channel093","Channel094","Channel095","Channel096","Channel097","Channel098","Channel099","Channel100","Channel101","Channel102","Channel103","Channel104","Channel105","Channel106","Channel107","Channel108","Channel109","Channel110","Channel111","Channel112","Channel113","Channel114","Channel115","Channel116","Channel117","Channel118","Channel119","Channel120","Channel121","Channel122","Channel123","Channel124","Channel125","Channel126","Channel127","Channel128","Channel129","Channel130","Channel131","Channel132","Channel133","Channel134","Channel135","Channel136","Channel137","Channel138","Channel139","Channel140","Channel141","Channel142","Channel143","Channel144","Channel145","Channel146","Channel147","Channel148","Channel149","Channel150","Channel151","Channel152","Channel153","Channel154","Channel155","Channel156","Channel157","Channel158","Channel159","Channel160","Channel161","Channel162","Channel163","Channel164","Channel165","Channel166","Channel167","Channel168","Channel169","Channel170","Channel171","Channel172","Channel173","Channel174","Channel175","Channel176","Channel177","Channel178","Channel179","Channel180","Channel181","Channel182","Channel183","Channel184","Channel185","Channel186","Channel187","Channel188","Channel189","Channel190","Channel191","Channel192","Channel193","Channel194","Channel195","Channel196","Channel197","Channel198","Channel199","Channel200","Channel201","Channel202","Channel203","Channel204","Channel205","Channel206","Channel207","Channel208","Channel209","Channel210","Channel211","Channel212","Channel213","Channel214","Channel215","Channel216","Channel217","Channel218","Channel219","Channel220","Channel221","Channel222","Channel223","Channel224","Channel225","Channel226","Channel227","Channel228","Channel229","Channel230","Channel231","Channel232","Channel233","Channel234","Channel235","Channel236","Channel237","Channel238","Channel239","Channel240","Channel241","Channel242","Channel243","Channel244","Channel245","Channel246","Channel247","Channel248","Channel249","Channel250","Channel251","Channel252","Channel253","Channel254","ChannelDummy"]) ) self.mainSettings.add() self.echo=Label() self.mainPanel.add(self.echo) def getPanel( self ) : return self.mainPanel def onChange( self, sender ) : if sender == self.cbcList : # Make a call to the RPC service to get the register values self.rpcService.I2CRegisterValues( self.getTotalCBCs(), I2CPanel.ReadRegisterValueListener(self) )#fb - sends all CBCs self.load.setEnabled(True) self.save.setEnabled(True) elif sender == self.save: msg = self.saveFileName.getText() self.rpcService.saveI2cRegisterValues(msg, I2CPanel.saveStateListener(self) ) elif sender == self.load: msg = self.loadFileName.getText() self.rpcService.loadI2cRegisterValues(msg, I2CPanel.loadStateListener(self) ) self.rpcService.I2CRegisterValues( self.getTotalCBCs(), I2CPanel.ReadRegisterValueListener(self) )# # Sender must be a text box. Need to format the input. else : try: # For some reason the '0x' at the start of the string is causing exceptions, # even though it works fine with interactive python. I'll take it off anyway. string=sender.getText() if( len(string)>=2 ) : if string[0]=='0' and string[1]=='x' : string=string[2:] value=int( string, 16 ) # convert as hex # Cap values at 255 if value<0 : value=0 if value>255 : value=255 sender.setStyleAttribute( "background-color", "#FFFFFF" ) # Convert to the same format as everything else sender.setText( "0x%02x"%value ) # Send the change to the RPC service messageParameters = {} for cbcName in self.getActiveCBCs() : messageParameters[cbcName]={ sender.getTitle():value } self.rpcService.setI2CRegisterValues( messageParameters, I2CPanel.RefreshListener(self) ) except ValueError: sender.setStyleAttribute( "background-color", "#FF3333" ) #self.echoSelection() def echoSelection(self): #fb - a good "print screen" method msg = " File saved: " for names in self.getCheckedStates(): msg += names self.echo.setText(msg) def getList(self): selectCBCs = [] for i in range(self.cbcList.getItemCount()) : if self.cbcList.isItemSelected(i): selectedCBCs.append(self.cbcList.getItemText(i)) def getTotalCBCs(self) : #fb totalCBCs = [] for i in range(self.cbcList.getItemCount()) : totalCBCs.append(self.cbcList.getItemText(i)) return totalCBCs def getSpecificCBC(self, i): #fb specificCBC = [] specificCBC.append(self.cbcList.getItemText(i)) return specificCBC def getActiveCBCs(self) : selectedCBCs = [] for i in range(self.cbcList.getItemCount()) : if self.cbcList.isItemSelected(i): selectedCBCs.append(self.cbcList.getItemText(i)) return selectedCBCs def getCheckedStates(self): # returns the checked boxes + filename selectedStates = [] #for names in self.stateValueEntries: #if str(self.stateValueEntries[names].isChecked())=="True": # selectedStates.append(names) selectedStates.append(self.saveFileName.getText()) return selectedStates def createRegisterPanel( self, registerNames ) : """ Creates panels and buttons for everything given in registerNames, and returns the main panel. """ flowPanel=FlowPanel() for buttonName in registerNames : newPanel=HorizontalPanel() label=Label(buttonName) newPanel.add( label ) newTextBox=TextBox() newTextBox.setEnabled(False) newTextBox.setWidth(80) statusBox=TextBox() statusBox.setEnabled(False) statusBox.setWidth(30) newPanel.add(newTextBox) newPanel.add(statusBox) newPanel.setCellHorizontalAlignment( newTextBox, HasHorizontalAlignment.ALIGN_RIGHT ) newPanel.setCellHorizontalAlignment( statusBox, HasHorizontalAlignment.ALIGN_RIGHT ) newPanel.setCellWidth( statusBox, "20px" ) newPanel.setWidth("100%") #newPanel.setStyleName("areaStyle"); #newPanel.setBorderWidth(5); newTextBox.setText("select chip...") newTextBox.addChangeListener(self) newTextBox.setTitle(buttonName) # This isn't displayed, but it's useful to have stored self.i2cValueEntries[buttonName]=newTextBox self.statusValueEntries[buttonName]=statusBox statusBox.setTitle(buttonName) statusBox.setText("...") flowPanel.add(newPanel) return flowPanel def createStatesPanel(self): vertPanel=VerticalPanel() vertPanel.setSpacing(10) selectionNames = (["Main Control", "Masks", "Trims"]) registerSelection = VerticalPanel() for name in selectionNames : checkBox = CheckBox(name) checkBox.setTitle(name) self.stateValueEntries[name]=checkBox registerSelection.add(checkBox) #Tidy up loadPanel = HorizontalPanel() loadFileTextBox = TextBox() loadFileTextBox.setText("MyI2cCfg") loadFileTextBox.setWidth(80) self.loadFileName = loadFileTextBox loadPanel.add(loadFileTextBox) self.load = Button("Load",getattr(self,"onChange")) #overrides default and sends it to onChange loadPanel.add(self.load) self.load.setEnabled(False) savePanel = HorizontalPanel() saveFileTextBox = TextBox() saveFileTextBox.setText("MyI2cCfg") saveFileTextBox.setWidth(80) self.saveFileName = saveFileTextBox savePanel.add(saveFileTextBox) self.save = Button("Save", getattr(self,"onChange")) savePanel.add(self.save) self.save.setEnabled(False) self.returnStatement = Label() vertPanel.add(registerSelection) vertPanel.add(loadPanel) vertPanel.add(savePanel) vertPanel.add(self.returnStatement) return vertPanel
class Lists(Sink): def __init__(self): Sink.__init__(self) self.sStrings=[["foo0", "bar0", "baz0", "toto0", "tintin0"], ["foo1", "bar1", "baz1", "toto1", "tintin1"], ["foo2", "bar2", "baz2", "toto2", "tintin2"], ["foo3", "bar3", "baz3", "toto3", "tintin3"], ["foo4", "bar4", "baz4", "toto4", "tintin4"]] self.combo=ListBox(VisibleItemCount=1) self.list=ListBox(MultipleSelect=True, VisibleItemCount=10) self.echo=Label() self.combo.addChangeListener(self) for i in range(len(self.sStrings)): txt = "List %d" % i self.combo.addItem(txt) # test setItemText self.combo.setItemText(i, txt + " using set text") self.combo.setSelectedIndex(0) self.fillList(0) self.list.addChangeListener(self) horz = HorizontalPanel(VerticalAlignment=HasAlignment.ALIGN_TOP, Spacing=8) horz.add(self.combo) horz.add(self.list) panel = VerticalPanel(HorizontalAlignment=HasAlignment.ALIGN_LEFT) panel.add(horz) panel.add(self.echo) self.initWidget(panel) self.echoSelection() def onChange(self, sender): if sender == self.combo: self.fillList(self.combo.getSelectedIndex()) elif sender == self.list: self.echoSelection() def onShow(self): pass def fillList(self, idx): self.list.clear() strings = self.sStrings[idx] for i in range(len(strings)): self.list.addItem(strings[i]) self.echoSelection() def echoSelection(self): msg = "Selected items: " for i in range(self.list.getItemCount()): if self.list.isItemSelected(i): msg += self.list.getItemText(i) + " " self.echo.setText(msg)
class OpenPowerSystem: """ Defines the main panel for OpenPowerSystem. """ def __init__(self): """ Constructs a new OpenPowerSystem instance. """ self.TEXT_WAITING = "Waiting for response..." self.TEXT_ERROR = "Server Error" self.base_panel = HorizontalPanel() self.tab_panel = TabPanel() self.tab_panel.add(self.get_upload_panel(), "Upload") # self.tab_panel.add(self.get_home_panel(), "OpenPowerSystem") # self.tab_panel.add(self.get_map_panel(), "Map") # self.tab_panel.add(self.get_edit_panel(), "Edit") self.tab_panel.selectTab(0) self.base_panel.add(self.tab_panel) RootPanel().add(self.base_panel) def get_home_panel(self): panel = VerticalPanel() title = HTML("""OpenPowerSystem""") panel.add(title) subtitle = HTML("""The Open Power System data repository.""") panel.add(subtitle) return panel # def get_map_panel(self): # panel = VerticalPanel() # # self.map = OpenMap(Width="900px", Height="900px") # panel.add(self.map) # # self.wms = OpenWMSLayer("OpenLayers WMS", # "http://labs.metacarta.com/wms/vmap0", layers="basic") # self.map.addLayer(self.wms) # # return panel # def get_edit_panel(self): # edit_page = edit_panel.EditPanel() # return edit_page.panel def get_upload_panel(self): # Create a FormPanel and point it at a service. self.form = FormPanel() self.form.setAction("/upload") # Add an event handler to the form. handler = UploadFormHandler() handler.form = self.form self.form.addFormHandler(handler) # 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) panel = VerticalPanel() panel.setSpacing(8) panel.setStyleName("panel") # same name as in OpenPowerSystem.css. self.form.setWidget(panel) info = HTML(r'Upload CIM RDF/XML instance file.') panel.add(info) # Create a list box for choice of profile. self.profiles = [("UCTE (CIM 14)", "ucte"), ("CPSM (CIM13)", "cpsm"), ("CDPSM (CIM 14)", "cdpsm"), ("Dynamics (CIM 14)", "dynamics")] self.profile = ListBox(VisibleItemCount=1) self.profile.setName("profileType") for n, v in self.profiles: self.profile.addItem(n, v) panel.add(self.profile) # Create a FileUpload widget. rdfxml_file = FileUpload() rdfxml_file.setName("uploadFormElement") panel.add(rdfxml_file) # Add a 'submit' button. upload = Button("Upload", handler) panel.add(upload) return self.form
class Lists(Sink): def __init__(self): Sink.__init__(self) self.sStrings=[["foo0", "bar0", "baz0", "toto0", "tintin0"], ["foo1", "bar1", "baz1", "toto1", "tintin1"], ["foo2", "bar2", "baz2", "toto2", "tintin2"], ["foo3", "bar3", "baz3", "toto3", "tintin3"], ["foo4", "bar4", "baz4", "toto4", "tintin4"]] self.combo=ListBox(VisibleItemCount=1) self.list=ListBox(MultipleSelect=True, VisibleItemCount=10) self.echo=Label() self.combo.addChangeListener(self) for i in range(len(self.sStrings)): txt = "List %d" % i self.combo.addItem(txt) # test setItemText self.combo.setItemText(i, txt + " using set text") self.combo.setSelectedIndex(0) self.fillList(0) self.list.setItemSelected(0, False) self.list.setItemSelected(1, True) self.list.addChangeListener(self) horz = HorizontalPanel(VerticalAlignment=HasAlignment.ALIGN_TOP, Spacing=8) horz.add(self.combo) horz.add(self.list) panel = VerticalPanel(HorizontalAlignment=HasAlignment.ALIGN_LEFT) panel.add(horz) panel.add(self.echo) self.initWidget(panel) self.echoSelection() def onChange(self, sender): if sender == self.combo: self.fillList(self.combo.getSelectedIndex()) elif sender == self.list: self.echoSelection() def onShow(self): pass def fillList(self, idx): self.list.clear() strings = self.sStrings[idx] for i in range(len(strings)): self.list.addItem(strings[i]) self.echoSelection() def echoSelection(self): msg = "Selected items: " for i in range(self.list.getItemCount()): if self.list.isItemSelected(i): msg += self.list.getItemText(i) + " " self.echo.setText(msg)
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
def __init__(self, autoHide=None, modal=True, **kwargs): PopupPanel.__init__(self, autoHide, modal, **kwargs) datasource = None id = None if kwargs.has_key("datasrc"): datasource = kwargs["datasrc"] if kwargs.has_key("id"): id = kwargs["id"] self.setSize(Window.getClientWidth() - 50, Window.getClientHeight() - 50) self.setPopupPosition(20, 0) DOM.setAttribute(self, "align", "center") # self.dbProxInstrucao = DialogBox() # self.dbProxInstrucao.setHTML("Alow") # botton = Button("Ok") # botton.addClickListener(self.onCloseDialog) # self.dbProxInstrucao.setWidget(botton) self.caption = HTML() self.child = None self.setHTML("<b>Soma de Matrizes.</b>") self.dragging = False self.dragStartX = 0 self.dragStartY = 0 self.imageFechar = Image("images/fechar.gif", Size=("32px", "32px"), StyleName="gwt-ImageButton") self.imgbtnDesfazer = Image("images/previous-arrow.png", Size=("32px", "20px"), StyleName="gwt-ImageButton") self.imgbtnFazer = Image("images/next-arrow.png", Size=("32px", "20px"), StyleName="gwt-ImageButton") # self.imgbtnDesfazer.addClickListener(desfazerProxOperacao) # self.imgbtnFazer.addClickListener(fazerProxOperacao) self.btnAutomatic = Button("Automático", self.onIniciarAnimacaoAutomatica) self.btnInterativo = Button("Interativo") if id == "escalar": self.btnStepByStep = Button("Passo a passo", IniciarAnimacaoPassoAPasso) else: self.btnStepByStep = Button("Passo a passo", self.onIniciarAnimacaoPassoAPasso) self.btnFazer = Button("fazer >>", fazerProxOperacao) # self.btnFazer.setEnabled(False); self.btnDesfazer = Button("<< desfazer", desfazerProxOperacao) # self.btnDesfazer.setEnabled(False); self.btnFechar = PushButton(imageFechar, imageFechar) self.btnTestarResposta = Button("Testar Solução") self.lbVelocidade = ListBox() self.lbVelocidade.setID("lbseg") self.lbVelocidade.addItem("0.5 segundo", value=2) self.lbVelocidade.addItem("1 segundo", value=1) self.lbVelocidade.addItem("2 segundos", value=0.5) self.lbVelocidade.addItem("3 segundos", value=1 / 3) self.lbVelocidade.addItem("4 segundos", value=0.25) self.lbVelocidade.addItem("5 segundos", value=0.20) self.lbVelocidade.addItem("6 segundos", value=0.167) self.lbVelocidade.addItem("7 segundos", value=0.143) self.lbVelocidade.addItem("8 segundos", value=0.125) self.lbVelocidade.addItem("10 segundos", value=0.1) lblinha1 = ListBox() lblinha1.setID("lm1") lblinha1.addItem("1", value=1) lblinha1.addItem("2", value=2) lblinha1.addItem("3", value=3) lblinha1.addItem("4", value=4) lblinha1.addItem("5", value=5) lblinha2 = ListBox() lblinha2.setID("lm2") lblinha2.addItem("1", value=1) lblinha2.addItem("2", value=2) lblinha2.addItem("3", value=3) lblinha2.addItem("4", value=4) lblinha2.addItem("5", value=5) lbcoluna1 = ListBox() lbcoluna1.setID("cm1") lbcoluna1.addItem("1", value=1) lbcoluna1.addItem("2", value=2) lbcoluna1.addItem("3", value=3) lbcoluna1.addItem("4", value=4) lbcoluna1.addItem("5", value=5) lbcoluna1.addItem("6", value=6) lbcoluna1.addItem("7", value=7) lbcoluna2 = ListBox() lbcoluna2.setID("cm2") lbcoluna2.addItem("1", value=1) lbcoluna2.addItem("2", value=2) lbcoluna2.addItem("3", value=3) lbcoluna2.addItem("4", value=4) lbcoluna2.addItem("5", value=5) lbcoluna2.addItem("6", value=6) lbcoluna2.addItem("7", value=7) self.lblStatus = Label("Label para Status") # Eventos self.imageFechar.addClickListener(self.onFecharPopup) # Cabeçalho da poupPanel self.grid = Grid(1, 16) self.grid.setWidth(self.getWidth()) self.grid.setHTML(0, 0, "<b>Matriz 1:</b> Nº Linhas:") self.grid.setWidget(0, 1, lblinha1) self.grid.setText(0, 2, "Nº Colunas:") self.grid.setWidget(0, 3, lbcoluna1) self.grid.setHTML(0, 4, "<b>Matriz 2:</b> Nº Linhas:") self.grid.setWidget(0, 5, lblinha2) self.grid.setText(0, 6, "Nº Colunas:") self.grid.setWidget(0, 7, lbcoluna2) # self.grid.setWidget(0, 3, self.txtColunas) self.grid.setWidget(0, 8, self.btnStepByStep) self.grid.setWidget(0, 9, self.btnDesfazer) self.grid.setWidget(0, 10, self.btnFazer) self.grid.setHTML(0, 11, "<b>Velocidade:</b>") self.grid.setWidget(0, 12, self.lbVelocidade) self.grid.setWidget(0, 13, self.btnAutomatic) # self.grid.setWidget(0, 14, self.btnInterativo) self.grid.setWidget(0, 15, self.imageFechar) # self.grid.setWidget(0, 7, self.btnFechar) self.grid.getCellFormatter().setAlignment( 0, 15, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_TOP ) self.panel = FlexTable(Height="100%", width="100%", BorderWidth="0", CellPadding="0", CellSpacing="0") self.panel.setWidget(0, 0, self.caption) self.panel.setWidget(1, 0, self.grid) self.panel.getCellFormatter().setHeight(2, 0, "100%") self.panel.getCellFormatter().setWidth(2, 0, "100%") self.panel.getCellFormatter().setAlignment( 2, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_TOP ) self.panel.setID("contetepopup") painelhorizontal = HorizontalPanel() gridinterativa = FlexTable() painelhorizontal.add( HTML( "<canvas id='%s' datasrc='%s' width='%s' height='%s' style='image-rendering: optimizespeed !important; '></canvas>" % ("soma", datasource, "1000px", "500px") ) ) ftInterativo = FlexTable(Height="100%", width="100%", BorderWidth="0", CellPadding="0", CellSpacing="0") gridinterativa = Grid(4, 4) gridinterativa.setWidget( 0, 0, HTML( "<b>M1(</b><input type='text' class='gwt-TextBox' id='linha1' style='width: 25px; height:20px;' maxLength='1'><b> , </b>" ), ) gridinterativa.setWidget( 0, 1, HTML( "<input type='text' class='gwt-TextBox' id='coluna1' style='width: 25px;height:20px;' maxLength='1'><b>) +</b>" ), ) gridinterativa.setWidget( 0, 2, HTML( "<b>M2(</b> <input type='text' class='gwt-TextBox' id='linha2' style='width: 25px; height:20px;' maxLength='1'><b> , </b>" ), ) gridinterativa.setWidget( 0, 3, HTML( "<input type='text' class='gwt-TextBox' id='coluna2' style='width: 25px; height:20px;' maxLength='1'><b>) =</b>" ), ) gridinterativa.setWidget( 2, 0, HTML( " <b>(</b><input type='text' class='gwt-TextBox' id='n1' style='width: 25px; height:20px;' maxLength='1'><b>) +</b>" ), ) gridinterativa.setWidget( 2, 1, HTML( "<b>(</b><input type='text' class='gwt-TextBox' id='n2' style='width: 25px; height:20px;' maxLength='1'><b>)</b>" ), ) gridinterativa.setWidget( 2, 2, HTML( "<b>= </b> <input type='text' class='gwt-TextBox' id='solucao' style='width: 25px; height:20px;' maxLength='1'>" ), ) ftInterativo.setHTML(0, 0, "</br>") ftInterativo.setHTML(1, 0, "<b><h3>Painel Interativo<h3></b>") # ftInterativo.setWidget(2, 0, self.btnInterativo) ftInterativo.setWidget(3, 0, gridinterativa) ftInterativo.setWidget(4, 0, self.btnTestarResposta) ftInterativo.setHTML(5, 0, "</br>") ftInterativo.setHTML(6, 0, "Use a tecla tab para agilizar.") ftInterativo.getCellFormatter().setAlignment( 4, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_TOP ) ftInterativo.getCellFormatter().setAlignment( 1, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_TOP ) # painelhorizontal.add(ftInterativo) self.panel.setWidget(2, 0, painelhorizontal) self.panel.setWidget(3, 0, self.lblStatus) self.panel.setStyleName("dialogContent") PopupPanel.setWidget(self, self.panel) self.setStyleName("gwt-DialogBox") self.caption.setStyleName("Caption") self.caption.addMouseListener(self)
class AutoCompleteTextBox(TextBox): def __init__(self, **kwargs): self.choicesPopup = PopupPanel(True, False) self.choices = ListBox() self.items = SimpleAutoCompletionItems() self.popupAdded = False self.visible = False self.choices.addClickListener(self) self.choices.addChangeListener(self) self.choicesPopup.add(self.choices) self.choicesPopup.addStyleName("AutoCompleteChoices") self.choices.setStyleName("list") if not kwargs.has_key('StyleName'): kwargs['StyleName'] = "gwt-AutoCompleteTextBox" TextBox.__init__(self, **kwargs) self.addKeyboardListener(self) def setCompletionItems(self, items): if not hasattr(items, 'getCompletionItems'): items = SimpleAutoCompletionItems(items) self.items = items def getCompletionItems(self): return self.items def onKeyDown(self, arg0, arg1, arg2): pass def onKeyPress(self, arg0, arg1, arg2): pass def onKeyUp(self, arg0, arg1, arg2): if arg1 == KeyboardListener.KEY_DOWN: selectedIndex = self.choices.getSelectedIndex() selectedIndex += 1 if selectedIndex >= self.choices.getItemCount(): selectedIndex = 0 self.choices.setSelectedIndex(selectedIndex) return if arg1 == KeyboardListener.KEY_UP: selectedIndex = self.choices.getSelectedIndex() selectedIndex -= 1 if selectedIndex < 0: selectedIndex = self.choices.getItemCount() - 1 self.choices.setSelectedIndex(selectedIndex) return if arg1 == KeyboardListener.KEY_ENTER: if self.visible: self.complete() return if arg1 == KeyboardListener.KEY_ESCAPE: self.choices.clear() self.choicesPopup.hide() self.visible = False return text = self.getText() matches = [] if len(text) > 0: matches = self.items.getCompletionItems(text) if len(matches) > 0: self.choices.clear() for i in range(len(matches)): self.choices.addItem(matches[i]) if len(matches) == 1 and matches[0] == text: self.choicesPopup.hide() else: self.choices.setSelectedIndex(0) self.choices.setVisibleItemCount(len(matches) + 1) if not self.popupAdded: RootPanel().add(self.choicesPopup) self.popupAdded = True self.choicesPopup.show() self.visible = True self.choicesPopup.setPopupPosition( self.getAbsoluteLeft(), self.getAbsoluteTop() + self.getOffsetHeight()) self.choices.setWidth("%dpx" % self.getOffsetWidth()) else: self.visible = False self.choicesPopup.hide() def onChange(self, arg0): self.complete() def onClick(self, arg0): self.complete() def complete(self): if self.choices.getItemCount() > 0: self.setText( self.choices.getItemText(self.choices.getSelectedIndex())) self.choices.clear() self.choicesPopup.hide() self.setFocus(True) self.visible = False
class DirectionsSimple(DockPanel): def __init__(self): DockPanel.__init__(self) self.setSize('100%', '100%') # widgets topPanel = HorizontalPanel() self.add(topPanel, DockPanel.NORTH) places = { "chicago, il": "Chicago", "st louis, mo": "St Louis", "joplin, mo": "Joplin, MO", "oklahoma city, ok": "Oklahoma City", "amarillo, tx": "Amarillo", "gallup, nm": "Gallup, NM", "flagstaff, az": "Flagstaff, AZ", "winona, az": "Winona", "kingman, az": "Kingman", "barstow, ca": "Barstow", "san bernardino, ca": "San Bernardino", "los angeles, ca": "Los Angeles"} self.start = ListBox() self.end = ListBox() for value in places: self.start.addItem(places[value], value) self.end.addItem(places[value], value) self.start.addChangeListener(self.calcRoute) self.end.addChangeListener(self.calcRoute) topPanel.add(self.start) topPanel.add(self.end) # now, the map mapPanel = SimplePanel() mapPanel.setSize('800', '500') self.add(mapPanel, DockPanel.CENTER) chigado = LatLng(41.850033, -87.6500523) options = MapOptions(zoom=7, center=chigado, mapTypeId=MapTypeId.ROADMAP) self.map = Map(mapPanel.getElement(), options) # initialize the renderer self.directionsDisplay = DirectionsRenderer() self.directionsDisplay.setMap(self.map) self.directionsService = DirectionsService() def calcRoute(self): start = self.start.getValue(self.start.getSelectedIndex()) end = self.end.getValue(self.end.getSelectedIndex()) print "calcRoute start:", start, "end:", end request = DirectionsRequest(origin=start, destination=end, \ travelMode=DirectionsTravelMode.DRIVING) self.directionsService.route(request, self.directionsResult) def directionsResult(self, response, status): print "directionsResult:" if status == DirectionsStatus.OK: for trip in response.trips: print "copyrights:", trip.copyrights for route in trip.routes: print route.start_geocode.formatted_address print route.end_geocode.formatted_address print route.steps[0].start_point print route.steps[0].end_point print "\n" self.directionsDisplay.setDirections(response)
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 AutoCompleteTextBox(TextBox): def __init__(self, **kwargs): self.choicesPopup = PopupPanel(True, False) self.choices = ListBox() self.items = SimpleAutoCompletionItems() self.popupAdded = False self.visible = False self.choices.addClickListener(self) self.choices.addChangeListener(self) self.choicesPopup.add(self.choices) self.choicesPopup.addStyleName("AutoCompleteChoices") self.choices.setStyleName("list") if not kwargs.has_key('StyleName'): kwargs['StyleName']="gwt-AutoCompleteTextBox" TextBox.__init__(self, **kwargs) self.addKeyboardListener(self) def setCompletionItems(self, items): if not hasattr(items, 'getCompletionItems'): items = SimpleAutoCompletionItems(items) self.items = items def getCompletionItems(self): return self.items def onKeyDown(self, arg0, arg1, arg2): pass def onKeyPress(self, arg0, arg1, arg2): pass def onKeyUp(self, arg0, arg1, arg2): if arg1 == KeyboardListener.KEY_DOWN: selectedIndex = self.choices.getSelectedIndex() selectedIndex += 1 if selectedIndex >= self.choices.getItemCount(): selectedIndex = 0 self.choices.setSelectedIndex(selectedIndex) return if arg1 == KeyboardListener.KEY_UP: selectedIndex = self.choices.getSelectedIndex() selectedIndex -= 1 if selectedIndex < 0: selectedIndex = self.choices.getItemCount() - 1 self.choices.setSelectedIndex(selectedIndex) return if arg1 == KeyboardListener.KEY_ENTER: if self.visible: self.complete() return if arg1 == KeyboardListener.KEY_ESCAPE: self.choices.clear() self.choicesPopup.hide() self.visible = False return text = self.getText() matches = [] if len(text) > 0: matches = self.items.getCompletionItems(text) if len(matches) > 0: self.choices.clear() for i in range(len(matches)): self.choices.addItem(matches[i]) if len(matches) == 1 and matches[0] == text: self.choicesPopup.hide() else: self.choices.setSelectedIndex(0) self.choices.setVisibleItemCount(len(matches) + 1) if not self.popupAdded: RootPanel().add(self.choicesPopup) self.popupAdded = True self.choicesPopup.show() self.visible = True self.choicesPopup.setPopupPosition(self.getAbsoluteLeft(), self.getAbsoluteTop() + self.getOffsetHeight()) self.choices.setWidth("%dpx" % self.getOffsetWidth()) else: self.visible = False self.choicesPopup.hide() def onChange(self, arg0): self.complete() def onClick(self, arg0): self.complete() def complete(self): if self.choices.getItemCount() > 0: self.setText(self.choices.getItemText(self.choices.getSelectedIndex())) self.choices.clear() self.choicesPopup.hide() self.setFocus(True) self.visible = False
class DirectionsSimple(DockPanel): def __init__(self): DockPanel.__init__(self) self.setSize('100%', '100%') # widgets topPanel = HorizontalPanel() self.add(topPanel, DockPanel.NORTH) places = { "chicago, il": "Chicago", "st louis, mo": "St Louis", "joplin, mo": "Joplin, MO", "oklahoma city, ok": "Oklahoma City", "amarillo, tx": "Amarillo", "gallup, nm": "Gallup, NM", "flagstaff, az": "Flagstaff, AZ", "winona, az": "Winona", "kingman, az": "Kingman", "barstow, ca": "Barstow", "san bernardino, ca": "San Bernardino", "los angeles, ca": "Los Angeles" } self.start = ListBox() self.end = ListBox() for value in places: self.start.addItem(places[value], value) self.end.addItem(places[value], value) self.start.addChangeListener(self.calcRoute) self.end.addChangeListener(self.calcRoute) topPanel.add(self.start) topPanel.add(self.end) # now, the map mapPanel = SimplePanel() mapPanel.setSize('800', '500') self.add(mapPanel, DockPanel.CENTER) chigado = LatLng(41.850033, -87.6500523) options = MapOptions(zoom=7, center=chigado, mapTypeId=MapTypeId.ROADMAP) self.map = Map(mapPanel.getElement(), options) # initialize the renderer self.directionsDisplay = DirectionsRenderer() self.directionsDisplay.setMap(self.map) self.directionsService = DirectionsService() def calcRoute(self): start = self.start.getValue(self.start.getSelectedIndex()) end = self.end.getValue(self.end.getSelectedIndex()) print "calcRoute start:", start, "end:", end request = DirectionsRequest(origin=start, destination=end, \ travelMode=DirectionsTravelMode.DRIVING) self.directionsService.route(request, self.directionsResult) def directionsResult(self, response, status): print "directionsResult:" if status == DirectionsStatus.OK: for trip in response.trips: print "copyrights:", trip.copyrights for route in trip.routes: print route.start_geocode.formatted_address print route.end_geocode.formatted_address print route.steps[0].start_point print route.steps[0].end_point print "\n" self.directionsDisplay.setDirections(response)
class JSONRPCExample: def onModuleLoad(self): self.TEXT_WAITING = "Waiting for response..." self.TEXT_ERROR = "Server Error" self.METHOD_ECHO = "Echo" self.METHOD_REVERSE = "Reverse" self.METHOD_UPPERCASE = "UPPERCASE" self.METHOD_LOWERCASE = "lowercase" self.METHOD_NONEXISTANT = "Non existant" self.methods = [ self.METHOD_ECHO, self.METHOD_REVERSE, self.METHOD_UPPERCASE, self.METHOD_LOWERCASE, self.METHOD_NONEXISTANT ] self.remote_php = EchoServicePHP() self.remote_py = EchoServicePython() self.status = Label() self.text_area = TextArea() self.text_area.setText("""{'Test'} [\"String\"] \tTest Tab Test Newline\n after newline """ + r"""Literal String: {'Test'} [\"String\"] """) self.text_area.setCharacterWidth(80) self.text_area.setVisibleLines(8) 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_php = Button("Send to PHP Service", self) self.button_py = Button("Send to Python Service", self) buttons = HorizontalPanel() buttons.add(self.button_php) buttons.add(self.button_py) 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 some text below, and press a button to send the text to an Echo service on your server. An echo service simply sends the exact same text back that it receives. </p>""" panel = VerticalPanel() panel.add(HTML(info)) panel.add(self.text_area) panel.add(method_panel) panel.add(buttons) panel.add(self.status) RootPanel().add(panel) def onClick(self, sender): self.status.setText(self.TEXT_WAITING) method = self.methods[self.method_list.getSelectedIndex()] text = self.text_area.getText() # demonstrate proxy & callMethod() if sender == self.button_php: if method == self.METHOD_ECHO: id = self.remote_php.echo(text, self) elif method == self.METHOD_REVERSE: id = self.remote_php.callMethod("reverse", [text], self) elif method == self.METHOD_UPPERCASE: id = self.remote_php.uppercase(text, self) elif method == self.METHOD_LOWERCASE: id = self.remote_php.lowercase(self, msg=text) elif method == self.METHOD_NONEXISTANT: id = self.remote_php.nonexistant(text, self) else: if method == self.METHOD_ECHO: id = self.remote_py.echo(text, self) elif method == self.METHOD_REVERSE: id = self.remote_py.reverse(text, self) elif method == self.METHOD_UPPERCASE: id = self.remote_py.uppercase(text, self) elif method == self.METHOD_LOWERCASE: id = self.remote_py.lowercase(text, self) elif method == self.METHOD_NONEXISTANT: id = self.remote_py.nonexistant(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))
def onRemoteResponse(self, response, request_info): mname = request_info.method if mname == "customize_message": showCustomizationResult(self, response, request_info) return if mname == "get_messagesdata_for_cust": locations_data = response["locations"] selectionbox = VerticalPanel(Padding=3) locations = ListBox() for (loc_name, loc_id) in locations_data: locations.addItem(loc_id, loc_name) messages = ListBox() messages.setName("locations") messages.addItem(location_select_label) for (name, d) in response["messages"].items(): messages.addItem(d['label'], name) locations.addChangeListener(self) messages.addChangeListener(self) self.locations = locations self.messages = messages locationbox = HorizontalPanel() locationbox.add(Label("Location: ", StyleName="text", Width=80)) locationbox.add(locations) msgnamebox = HorizontalPanel() msgnamebox.add(Label("Message: ", StyleName="text", Width=80)) msgnamebox.add(messages) selectionbox.add(locationbox) selectionbox.add(msgnamebox) mainpanel = VerticalPanel(StyleName="dataBoxContent") mainpanel.add(selectionbox) self.mainpanel = mainpanel root = RootPanel() root.add(mainpanel) if mname == "get_messagecustdata": self.messages_data = response buttonspanel = FlowPanel(Spacing=1, Padding=1, Width=600) #buttonspanel.add(Label("Macros:", StyleName="text")) for macro_d in self.messages_data['macros']: macrobutton = Button(macro_d['label'], self, StyleName="buttonlikelink")#"nicebutton small") macrobutton.name = macro_d['name'] buttonspanel.add(macrobutton) msgpanel = VerticalPanel(Padding=1, Spacing=1) messagebox = TextArea() messagebox.setCharacterWidth(70) height = len(self.messages_data["text"].split('\n')) + 1 messagebox.setVisibleLines(height) messagebox.setText(self.messages_data["text"]) messagebox.setName("textBoxFormElement") self.messagebox = messagebox msgpanel.add(messagebox) self.statusbar = Label(StyleName="errorMessage") msgpanel.add(self.statusbar) actionbuttons = HorizontalPanel(Spacing=2) updatebutton = Button("Update", self, StyleName="nicebutton small yellow") updatebutton.name = "update" actionbuttons.add(updatebutton) #actionbuttons.add(Button("Send me a preview mail")) msgpanel.add(actionbuttons) editorbox = VerticalPanel(Padding=1) editorbox.add(buttonspanel) editorbox.add(msgpanel) editorpanel = CaptionPanel("Message editor", editorbox, Padding=1, StyleName="text") editorpanel.name = "editorpanel" self.editorpanel = editorpanel self.mainpanel.add(editorpanel)