class GridEdit: def onModuleLoad(self): self.input = TextBox() self.input.setEnabled(False) self.input.addKeyboardListener(self) self.g=Grid() self.g.resize(5, 5) self.g.setHTML(0, 0, "<b>Grid Edit</b>") self.g.setBorderWidth(2) self.g.setCellPadding(4) self.g.setCellSpacing(1) self.g.setWidth("500px") self.g.setHeight("120px") self.g.addTableListener(self) self.initGrid() RootPanel().add(self.input) RootPanel().add(self.g) def onKeyDown(self, sender, keycode, modifiers): pass def onKeyUp(self, sender, keycode, modifiers): pass def onKeyPress(self, sender, keycode, modifiers): if keycode == KeyboardListener.KEY_ESCAPE: self.input.setEnabled(False) elif keycode == KeyboardListener.KEY_ENTER: self.input.setEnabled(False) val = self.input.getText() self.set_grid_value(self.row, self.col, val) def onCellClicked(self, sender, row, col): self.row = row self.col = col val = self.values[row][col] self.input.setText(val) self.input.setEnabled(True) self.input.setFocus(True) def set_grid_value(self, row, col, val): self.values[row][col] = val if val == "": val = " " self.g.setHTML(row, col, val) def initGrid(self): self.values = {} for y in range(5): self.values[y] = {} for x in range(5): self.values[y][x] = "" for y in range(5): for x in range(5): val = self.values[y][x] self.set_grid_value(y, x, val)
class PopupNewVar(Popup): def __init__(self, okClick, cancelClick): Popup.__init__(self, '<b>Nova Variável</b>', okClick, cancelClick, CONFIRM_CANCEL) def draw(self): Popup.draw(self) namePanel = HorizontalPanel() namePanel.add(Label(_('Name') + ':')) self.textBox = TextBox() self.textBox.setMaxLength(15) self.textBox.setStyleAttribute('marginLeft', 10) namePanel.add(self.textBox) self.center.add(namePanel) self.choose = ChooseTypeVarPanel() self.center.add(self.choose) self.textBox.addInputListener(self) self.message = Element(Element=DOM.createDiv()) self.message.add(Widget(Element=DOM.createDiv(), StyleName='not_image')) self.message.add( Label(text=_('Name already used'), wordWrap=False, StyleName='not_message')) self.onInput() def onInput(self, sender): if self.textBox.getText().count(' ') == len(self.textBox.getText()): self.okButton.addStyleName('disabled') self.south.remove(self.message) elif self.textBox.getText() in vars or self.textBox.getText( ) in createdBlocks: self.okButton.addStyleName('disabled') self.south.add(self.message) else: self.okButton.removeStyleName('disabled') self.south.remove(self.message) def myOkClick(self): if 'disabled' not in self.okButton.getStyleName(): Popup.myOkClick(self) self.okClick(self.textBox.getText(), self.choose.selectedType) def myCancelClick(self): Popup.myCancelClick(self) if self.cancelClick is not None: self.cancelClick() def show(self): Popup.show(self) self.textBox.setFocus(True)
class Search: def onModuleLoad(self): Window.alert('Loadingg') # Setup JSON RPC self.remote = DataService() parser = JSONParser() #initialize member variables self.mainPanel = VerticalPanel() self.searchPanel = HorizontalPanel() self.resultsPanel = VerticalPanel() self.deptLabel = Label('Department') self.deptBox = TextBox() self.courseNoLabel = Label ('Course Number') self.courseNoBox = TextBox() self.searchButton = Button('Search', self.searchCourses) self.searchPanel = VerticalPanel() # Assemble search panel self.searchPanel.add(self.deptLabel) self.searchPanel.add(self.deptBox) self.searchPanel.add(self.courseNoLabel) self.searchPanel.add(self.courseNoBox) self.searchPanel.add(self.searchButton) # Assemble results panel self.resultsLabel = Label('Results here') self.resultsPanel.add(self.resultsLabel) # Assemble main panel self.mainPanel.add(self.searchPanel) self.mainPanel.add(self.resultsPanel) # Associate mainPanel with the HTML host page RootPanel().add(self.mainPanel) # Move cursor focus to input box self.deptBox.setFocus(True) #Search courses def searchCourses(self): Window.alert('Searching')
class PopupOpenState(Popup): def __init__(self, okClick, cancelClick, title='Abrir', options=CONFIRM_CANCEL): Popup.__init__(self, title, okClick, cancelClick, options) def draw(self): Popup.draw(self) namePanel = HorizontalPanel() #namePanel.add(Label('Crie um arquivo')) if self.title == 'Abrir': self.enableOkButton(False) namePanel.add(HTML("""<div class=""gwt-Label"" style=""white-space: normal;""> Abra o arquivo salvo, copie<br>e cole aqui o conteudo:</div>""")) self.field = FileUpload() self.field.setName('file') self.field.setID('files') self.center.add(self.field) element = self.field.getElement() JS("""function handleFileSelect(evt) {@{{self}}.enableOkButton(evt.target.files[0]!=null);} @{{element}}.addEventListener('change', handleFileSelect, false);""") #http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml else: namePanel.add(HTML("""<div class=""gwt-Label"" style=""white-space: normal;""> Crie um arquivo txt e copie<br>e cole o conteudo a seguir:</div>""")) self.textBox = TextBox() self.textBox.setStyleAttribute('marginLeft', 10) namePanel.add(self.textBox) self.center.add(namePanel) self.textBox.addInputListener(self) self.onInput() def enableOkButton(self, enable): if enable: self.okButton.removeStyleName('disabled') else: self.okButton.addStyleName('disabled') def onInput(self, sender): self.enableOkButton(self.textBox.getText().count(' ') != len(self.textBox.getText())) def myOkClick(self): if 'disabled' not in self.okButton.getStyleName(): Popup.myOkClick(self) if self.okClick is not None: if self.title == 'Abrir': files = getattr(self.field.getElement(), 'files') file = JS("@{{files}}[0]") if file: JS("""var reader = new FileReader(); reader.onload = function(e) {@{{self}}.okClick(e.target.result);} reader.readAsBinaryString(@{{file}});""") #self.okClick(str) else: self.okClick(self.textBox.getText()) def myCancelClick(self): Popup.myCancelClick(self) if self.cancelClick is not None: self.cancelClick() def show(self): Popup.show(self) if self.title != 'Abrir': self.textBox.setFocus(True) else: pass
class StockWatcher: def onModuleLoad(self): ''' This is the main entry point method. ''' # Setup JSON RPC self.remote = DataService() # Initialize member variables self.mainPanel = VerticalPanel() self.stocksFlexTable = FlexTable() self.addPanel = HorizontalPanel() self.newSymbolTextBox = TextBox() self.lastUpdatedLabel = Label() self.addStockButton = Button('Add', self.addStock) self.stocks = [] self.stocksTableColumns = ['Symbol', 'Price', 'Change', 'Remove'] # Add styles to elements in the stock list table self.stocksFlexTable.getRowFormatter().addStyleName(0, 'watchListHeader') self.stocksFlexTable.addStyleName('watchList') self.stocksFlexTable.getCellFormatter().addStyleName(0, 1, 'watchListNumericColumn') self.stocksFlexTable.getCellFormatter().addStyleName(0, 2, 'watchListNumericColumn') self.stocksFlexTable.getCellFormatter().addStyleName(0, 3, 'watchListRemoveColumn') # Create table for stock data for i in range(len(self.stocksTableColumns)): self.stocksFlexTable.setText(0, i, self.stocksTableColumns[i]) # Assemble Add Stock panel self.addPanel.add(self.newSymbolTextBox) self.addPanel.add(self.addStockButton) self.addPanel.addStyleName('addPanel') # Assemble Main panel self.mainPanel.add(self.stocksFlexTable) self.mainPanel.add(self.addPanel) self.mainPanel.add(self.lastUpdatedLabel) # Associate the Main panel with the HTML host page RootPanel().add(self.mainPanel) # Move cursor focus to the input box self.newSymbolTextBox.setFocus(True) # Setup timer to refresh list automatically refresh = self.refreshWatchlist class MyTimer(Timer): def run(self): refresh() refreshTimer = MyTimer() refreshTimer.scheduleRepeating(5000) # Listen for keyboard events in the input box self_addStock = self.addStock class StockTextBox_KeyboardHandler(): def onKeyPress(self, sender, keycode, modifiers): if keycode == KEY_ENTER: self_addStock() def onKeyDown(self, sender, keycode, modifiers): return def onKeyUp(self, sender, keycode, modifiers): return self.newSymbolTextBox.addKeyboardListener(StockTextBox_KeyboardHandler()) # Load the stocks self.remote.getStocks(self) def addStock(self, sender, symbol=None): ''' Add stock to FlexTable. Executed when the user clicks the addStockButton or presses enter in the newSymbolTextBox ''' if symbol is None: # Get the symbol symbol = self.newSymbolTextBox.getText().upper().trim() self.newSymbolTextBox.setText('') # Don't add the stock if it's already in the table if symbol in self.stocks: return # Tell the server that we're adding this stock self.remote.addStock(symbol, self) self.newSymbolTextBox.setFocus(True) # Stocks code must be between 1 and 10 chars that are numbers/letters/dots p = re.compile('^[0-9A-Z\\.]{1,10}$') if p.match(symbol) == None: Window.alert('"%s" is not a valid symbol.' % symbol) self.newSymbolTextBox.selectAll() return # Add the stock to the table row = self.stocksFlexTable.getRowCount() self.stocks.append(symbol) self.stocksFlexTable.setText(row, 0, symbol) self.stocksFlexTable.setWidget(row, 2, Label()) self.stocksFlexTable.getCellFormatter().addStyleName(row, 1, 'watchListNumericColumn') self.stocksFlexTable.getCellFormatter().addStyleName(row, 2, 'watchListNumericColumn') self.stocksFlexTable.getCellFormatter().addStyleName(row, 3, 'watchListRemoveColumn') # Add a button to remove this stock from the table def _removeStockButton_Click(event): if symbol not in self.stocks: return removedIndex = self.stocks.index(symbol) self.remote.deleteStock(symbol, self) self.stocks.remove(symbol) self.stocksFlexTable.removeRow(removedIndex + 1) removeStockButton = Button('x', _removeStockButton_Click) removeStockButton.addStyleDependentName('remove') self.stocksFlexTable.setWidget(row, 3, removeStockButton) # Get the stock price self.refreshWatchlist() def refreshWatchlist(self): ''' Update the price change for each stock ''' MAX_PRICE = 100.0 MAX_PRICE_CHANGE = 0.02 prices = [] for i in range(len(self.stocks)): price = random.random() * MAX_PRICE change = price * MAX_PRICE_CHANGE * (random.random() * 2.0 - 1.0) prices.append(StockPrice(self.stocks[i], price, change)) self.updateTable(prices) def updateTable(self, prices): ''' Update the price and change fields of all the rows in the stock table prices -- List of StockPrice objects for all rows ''' # Type checking assert isinstance(prices, list) for price in prices: assert isinstance(price, StockPrice) # Nothing to do... if len(prices) == 0: return # Update each individual row for i in range(len(prices)): self.updateRow(prices[i]) # Display timestamp showing last refresh self.lastUpdatedLabel.setText("Last update: %s" % datetime.datetime.now().strftime("%m/%d/%Y %I:%M:%S %p")) def updateRow(self, price): ''' Update a single row in the stock table price -- StockPrice object for a single row ''' # Type checking assert isinstance(price, StockPrice) # Make sure the stock is still in the stock table if price.symbol not in self.stocks: return # Find the index of row = self.stocks.index(price.symbol) + 1 # Populate the price and change fields with new data self.stocksFlexTable.setText(row, 1, '%.2f' % price.price) changeWidget = self.stocksFlexTable.getWidget(row, 2) changeWidget.setText('%.2f (%.2f%%)' % (price.change, price.getChangePercent())) # Change the color of the text in the Change field based on its value changeStyleName = 'noChange' if price.getChangePercent() < -0.1: changeStyleName = 'negativeChange' else: changeStyleName = 'positiveChange' changeWidget.setStyleName(changeStyleName) def onRemoteResponse(self, response, request_info): ''' Called when a response is received from a RPC. ''' if request_info.method in DataService.methods: # Compare self.stocks and the stocks in response stocks_set = set(self.stocks) response_set = set(response) # Add the differences for symbol in list(response_set.difference(stocks_set)): self.addStock(None, symbol) else: Window.alert('Unrecognized JSONRPC method.') def onRemoteError(self, code, message, request_info): Window.alert(message)
class 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()