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)
def drawGrid(self, month, year): # draw the grid in the middle of the calendar daysInMonth = self.getDaysInMonth(month, year) # first day of the month & year secs = time.mktime((year, month, 1, 0, 0, 0, 0, 0, -1)) struct = time.localtime(secs) # 0 - sunday for our needs instead 0 = monday in tm_wday startPos = (struct.tm_wday + 1) % 7 slots = startPos + daysInMonth - 1 rows = int(slots / 7) + 1 grid = Grid(rows + 1, 7) # extra row for the days in the week grid.setWidth("100%") grid.addTableListener(self) self.middlePanel.setWidget(grid) # # put some content into the grid cells # for i in range(7): grid.setText(0, i, self.getDaysOfWeek()[i]) grid.cellFormatter.addStyleName(0, i, "calendar-header") # # draw cells which are empty first # day = 0 pos = 0 while pos < startPos: grid.setText(1, pos, " ") grid.cellFormatter.setStyleAttr(1, pos, "background", "#f3f3f3") grid.cellFormatter.addStyleName(1, pos, "calendar-blank-cell") pos += 1 # now for days of the month row = 1 day = 1 col = startPos while day <= daysInMonth: if pos % 7 == 0 and day <> 1: row += 1 col = pos % 7 grid.setText(row, col, str(day)) if self.currentYear == self.todayYear and \ self.currentMonth == self.todayMonth and day == self.todayDay: grid.cellFormatter.addStyleName(row, col, "calendar-cell-today") else: grid.cellFormatter.addStyleName(row, col, "calendar-day-cell") day += 1 pos += 1 # # now blank lines on the last row # col += 1 while col < 7: grid.setText(row, col, " ") grid.cellFormatter.setStyleAttr(row, col, "background", "#f3f3f3") grid.cellFormatter.addStyleName(row, col, "calendar-blank-cell") col += 1 return grid
def drawGrid(self, month, year): # draw the grid in the middle of the calendar daysInMonth = self.getDaysInMonth(month, year) # first day of the month & year secs = time.mktime((year, month, 1, 0, 0, 0, 0, 0, -1)) struct = time.localtime(secs) # 0 - sunday for our needs instead 0 = monday in tm_wday startPos = (struct.tm_wday + 1) % 7 slots = startPos + daysInMonth - 1 rows = int(slots/7) + 1 grid = Grid(rows+1, 7) # extra row for the days in the week grid.setWidth("100%") grid.addTableListener(self) self.middlePanel.setWidget(grid) # # put some content into the grid cells # for i in range(7): grid.setText(0, i, self.getDaysOfWeek()[i]) grid.cellFormatter.addStyleName(0, i, "calendar-header") # # draw cells which are empty first # day =0 pos = 0 while pos < startPos: grid.setText(1, pos , " ") grid.cellFormatter.setStyleAttr(1, pos, "background", "#f3f3f3") grid.cellFormatter.addStyleName(1, pos, "calendar-blank-cell") pos += 1 # now for days of the month row = 1 day = 1 col = startPos while day <= daysInMonth: if pos % 7 == 0 and day <> 1: row += 1 col = pos % 7 grid.setText(row, col, str(day)) if self.currentYear == self.todayYear and \ self.currentMonth == self.todayMonth and day == self.todayDay: grid.cellFormatter.addStyleName(row, col, "calendar-cell-today") else: grid.cellFormatter.addStyleName(row, col, "calendar-day-cell") day += 1 pos += 1 # # now blank lines on the last row # col += 1 while col < 7: grid.setText(row, col, " ") grid.cellFormatter.setStyleAttr(row, col, "background", "#f3f3f3") grid.cellFormatter.addStyleName(row, col, "calendar-blank-cell") col += 1 return grid
class Photos(Composite): def __init__(self): Composite.__init__(self) self.albums = [] self.photos = [] self.grid = Grid(4, 4, CellPadding=4, CellSpacing=4) self.grid.addTableListener(self) self.drill = 0 self.pos = 0 self.up = Button("Up", self) self.next = Button("Next", self) self.prev = Button("Prev", self) self.timer = Timer(notify=self) self.userid = "jameskhedley" self.album_url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "?alt=json-in-script&kind=album&hl=en_US&callback=restCb" self.doRESTQuery(self.album_url, self.timer) self.vp = VerticalPanel() self.disclosure = DisclosurePanel( "Click for boring technical details.") self.disclosure.add( HTML( '''<p>OK so you want to write client JS to do a RESTful HTTP query from picasa right? Well you can't because of the Same Origin Policy. Basically this means that because the domain of the query and the domain of the hosted site are different, then that could well be a cross-site scripting (XSS) attack. So, the workaround is to do the call from a script tag so the JSON we get back is part of the document. But since we don't know what URL to hit yet, once we find out then we have to inject a new script tag dynamically which the browser will run as soon as we append it. To be honest I'm not 100% why Google use RESTful services and not JSON-RPC or somesuch, which would be easier. Well, easier for me.''')) self.IDPanel = HorizontalPanel() self.IDPanel.add(Label("Enter google account:")) self.IDButton = Button("Go", self) self.IDBox = TextBox() self.IDBox.setText(self.userid) self.IDPanel.add(self.IDBox) self.IDPanel.add(self.IDButton) self.vp.add(self.IDPanel) self.vp.add(self.disclosure) self.vp.add(self.grid) self.initWidget(self.vp) def doRESTQuery(self, url, timer): """this is a totally different from an RPC call in that we have to dynamically add script tags to the DOM when we want to query the REST API. These rely on callbacks in the DOM so we can either add them dynamically or pre-define them in public/Main.html. Once we've done that have to wait for the response. Which means we need to provide a listener for the timer""" new_script = DOM.createElement("script") DOM.setElemAttribute(new_script, "src", url) DOM.setElemAttribute(new_script, "type", "text/javascript") doc().body.appendChild(new_script) self.timer.schedule(100) def onCellClicked(self, sender, row, col): if self.drill == 0: self.drill += 1 self.vp.clear() self.grid.clear() self.vp.add(self.up) self.vp.add(self.grid) gridcols = self.grid.getColumnCount() album = self.albums[row + col + (row * (gridcols - 1))] url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "/albumid/" + album[ "id"] + "?alt=json-in-script&kind=photo&hl=en_US&callback=restCb" self.doRESTQuery(url, self.timer) elif self.drill == 1: self.drill += 1 gridcols = self.grid.getColumnCount() self.pos = row + col + (row * (gridcols - 1)) photo = self.photos[self.pos] self.vp.clear() self.fullsize = HTML('<img src="' + photo["full"] + '"/>') hp = HorizontalPanel() hp.add(self.up) hp.add(self.prev) hp.add(self.next) hp.setSpacing(8) self.vp.add(hp) self.vp.add(self.fullsize) def onClick(self, sender): if sender == self.IDButton: self.userid = self.IDBox.getText() if self.userid == "" or self.userid.isdigit(): return self.drill = 0 self.album_url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "?alt=json-in-script&kind=album&hl=en_US&callback=restCb" self.grid.clear() self.doRESTQuery(self.album_url, self.timer) else: if self.drill == 2: if sender == self.up: self.drill = 1 self.vp.clear() self.vp.add(self.up) self.vp.add(self.grid) self.fillGrid(self.photos, "photos") else: if sender == self.next: if self.pos >= len(self.photos): return self.pos += 1 elif sender == self.prev: if self.pos < 1: return self.pos -= 1 photo = self.photos[self.pos] self.fullsize.setHTML('<img src="' + photo["full"] + '"/>') elif self.drill == 1: self.drill = 0 self.vp.clear() self.vp.add(self.IDPanel) self.vp.add(self.disclosure) self.vp.add(self.grid) self.fillGrid(self.albums, "albums") def onTimer(self, timer): fd = doc().getElementById("__pygwt_hiddenData") receiver = fd.innerHTML if receiver == 'wait': self.timer.schedule(1000) return fd.innerHTML = 'wait' if self.drill == 0: self.parseAlbums(receiver) self.fillGrid(self.albums, "albums") elif self.drill == 1: self.parsePhotos(receiver) self.fillGrid(self.photos, "photos") def fillGrid(self, items, type): self.grid.clear() cols = self.grid.getColumnCount() self.grid.resizeRows((len(items) / cols) + 1) rows = self.grid.getRowCount() for i in range(len(items)): vp = VerticalPanel() if type == 'photos': vp.add(items[i]['thumb']) else: vp.add(items[i]['thumb']) vp.add(items[i]['title']) self.grid.setWidget(int(i / cols), i % cols, vp) def parsePhotos(self, items): photo_list = json.loads(items) self.photos = [] for ph in photo_list: aphoto = {} aphoto['thumb'] = HTML( '<img src="' + ph[u"media$group"][u"media$thumbnail"][1][u"url"] + '"/>') aphoto['full'] = ph[u"media$group"][u"media$content"][0][u"url"] self.photos.append(aphoto) def parseAlbums(self, items): album_list = json.loads(items) self.albums = [] for al in album_list: analbum = {} analbum['title'] = HTML(al[u"title"][u"$t"]) analbum['thumb'] = HTML( '<img src="' + al[u"media$group"][u"media$thumbnail"][0][u"url"] + '"/>') url = al[u"id"][u"$t"] analbum['id'] = url.split(u'albumid/')[1].split(u'?alt')[0] self.albums.append(analbum)
class Viewer: def __init__(self, db_url, parent_panel, doc_callback=None, page_size=5): self.db_url = db_url self.parent_panel = parent_panel self.doc_callback = doc_callback self.page_size = page_size def onModuleLoad(self): ## Grid setup self.grid = Grid() # Note: The resize method args are Rows,Cols (Curses style) self.grid.resize(1,4) self.grid.setBorderWidth(1) self.grid.setHTML(0,0,'#') self.grid.setHTML(0,1,'ID') self.grid.setHTML(0,2,'Revision') self.grid.setHTML(0,3,'Delete') self.grid.addTableListener(self) self.parent_panel.add(self.grid) ## Buttons self.button_panel = HorizontalPanel() # Prev self.first_button = Button("<-", self.firstPage) self.first_button.setEnabled(False) self.button_panel.add(self.first_button) self.prev_button = Button("Previous", self.prevPage) self.prev_button.setEnabled(False) self.button_panel.add(self.prev_button) self.next_button = Button("Next", self.nextPage) self.next_button.setEnabled(False) self.button_panel.add(self.next_button) self.parent_panel.add(self.button_panel) def populate(self, json): view_obj = JSONParser().decode(json) view_rows = view_obj['rows'] offset = view_obj['offset'] num_rows = len(view_rows) self.first_key = view_rows[0]['key'] if offset != 0: self.first_button.setEnabled(True) if num_rows > self.page_size: self.next_key = view_rows[-1:][0]['key'] self.next_button.setEnabled(True) self.grid.resize(self.page_size+1,4) else: self.grid.resize(num_rows+1,4) for row_num in range(num_rows): if row_num < self.page_size: self.grid.setHTML(row_num+1, 0, 1+offset+row_num) self.grid.setHTML(row_num+1, 1, view_rows[row_num]['key']) self.grid.setHTML(row_num+1, 2, view_rows[row_num]['value']['rev']) self.grid.setHTML(row_num+1, 3, '<b>X O X</b>') if len(self.prev_keys)>0: self.prev_button.setEnabled(True) def onCellClicked(self, sender, row, col): doc_id = self.grid.getHTML(row, 1) if col == 3: doc_rev = self.grid.getHTML(row, 2) url = self.db_url+doc_id+'?rev='+doc_rev HTTPRequest().asyncDelete(None, None, url=url, handler=DeleteHandler(self)) else: if self.doc_callback is not None: self.doc_callback(doc_id) def firstPage(self): self.loadPage(None) def nextPage(self): self.prev_keys.append(self.first_key) self.loadPage(self.next_key) def prevPage(self): self.loadPage(self.prev_keys.pop()) def setView(self, view_path, first_key = None): self.view_path = view_path #self.prev_keys = [] #self.next_key = None self.loadPage(first_key) def loadPage(self, startkey=None): limit = int(self.page_size)+1 view_url = self.db_url+self.view_path+'?limit=%d'%limit if startkey is not None: view_url += '&startkey="%s"'%startkey else: self.prev_keys = [] self.first_button.setEnabled(False) self.next_button.setEnabled(False) self.prev_button.setEnabled(False) HTTPRequest().asyncGet(None, None, url=view_url, handler=ViewLoader(self))
class Photos(Composite): def __init__(self): Composite.__init__(self) self.albums = [] self.photos = [] self.grid = Grid(4, 4, CellPadding=4, CellSpacing=4) self.grid.addTableListener(self) self.drill = 0 self.pos = 0 self.up = Button("Up", self) self.next = Button("Next", self) self.prev = Button("Prev", self) self.timer = Timer(notify=self) self.userid = "jameskhedley" self.album_url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "?alt=json-in-script&kind=album&hl=en_US&callback=restCb" self.doRESTQuery(self.album_url, self.timer) self.vp = VerticalPanel() self.disclosure = DisclosurePanel("Click for boring technical details.") self.disclosure.add(HTML('''<p>OK so you want to write client JS to do a RESTful HTTP query from picasa right? Well you can't because of the Same Origin Policy. Basically this means that because the domain of the query and the domain of the hosted site are different, then that could well be a cross-site scripting (XSS) attack. So, the workaround is to do the call from a script tag so the JSON we get back is part of the document. But since we don't know what URL to hit yet, once we find out then we have to inject a new script tag dynamically which the browser will run as soon as we append it. To be honest I'm not 100% why Google use RESTful services and not JSON-RPC or somesuch, which would be easier. Well, easier for me.''')) self.IDPanel = HorizontalPanel() self.IDPanel.add(Label("Enter google account:")) self.IDButton = Button("Go", self) self.IDBox = TextBox() self.IDBox.setText(self.userid) self.IDPanel.add(self.IDBox) self.IDPanel.add(self.IDButton) self.vp.add(self.IDPanel) self.vp.add(self.disclosure) self.vp.add(self.grid) self.initWidget(self.vp) def doRESTQuery(self, url, timer): """this is a totally different from an RPC call in that we have to dynamically add script tags to the DOM when we want to query the REST API. These rely on callbacks in the DOM so we can either add them dynamically or pre-define them in public/Main.html. Once we've done that have to wait for the response. Which means we need to provide a listener for the timer""" JS("$wnd.receiver = 'wait'") new_script = DOM.createElement("script") DOM.setElemAttribute(new_script, "src", url) DOM.setElemAttribute(new_script, "type","text/javascript") JS("$wnd.document.body.appendChild(@{{new_script}})") self.timer.schedule(100) def onCellClicked(self, sender, row, col): if self.drill==0: self.drill += 1 self.vp.clear() self.grid.clear() self.vp.add(self.up) self.vp.add(self.grid) gridcols = self.grid.getColumnCount() album = self.albums[row+col+(row*(gridcols-1))] url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "/albumid/" + album["id"] + "?alt=json-in-script&kind=photo&hl=en_US&callback=restCb" self.doRESTQuery(url, self.timer) elif self.drill==1: self.drill += 1 gridcols = self.grid.getColumnCount() self.pos =row+col+(row*(gridcols-1)) photo = self.photos[self.pos] self.vp.clear() self.fullsize = HTML('<img src="' + photo["full"] + '"/>') hp = HorizontalPanel() hp.add(self.up) hp.add(self.prev) hp.add(self.next) hp.setSpacing(8) self.vp.add(hp) self.vp.add(self.fullsize) def onClick(self, sender): if sender == self.IDButton: self.userid = self.IDBox.getText() if self.userid == "" or self.userid.isdigit(): return self.drill = 0 self.album_url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "?alt=json-in-script&kind=album&hl=en_US&callback=restCb" self.grid.clear() self.doRESTQuery(self.album_url, self.timer) else: if self.drill == 2: if sender == self.up: self.drill=1 self.vp.clear() self.vp.add(self.up) self.vp.add(self.grid) self.fillGrid(self.photos, "photos") else: if sender == self.next: if self.pos >= len(self.photos): return self.pos +=1 elif sender == self.prev: if self.pos < 1: return self.pos -=1 photo = self.photos[self.pos] self.fullsize.setHTML('<img src="' + photo["full"] + '"/>') elif self.drill == 1: self.drill=0 self.vp.clear() self.vp.add(self.IDPanel) self.vp.add(self.disclosure) self.vp.add(self.grid) self.fillGrid(self.albums, "albums") def onTimer(self, timer): receiver = JS("$wnd.receiver") if receiver == 'wait': self.timer.schedule(1000) return JS("$wnd.receiver = 'wait'") if self.drill == 0: self.parseAlbums(receiver) self.fillGrid(self.albums, "albums") elif self.drill == 1: self.parsePhotos(receiver) self.fillGrid(self.photos, "photos") def fillGrid(self, items, type): self.grid.clear() cols = self.grid.getColumnCount() self.grid.resizeRows((len(items)/cols)+1) rows = self.grid.getRowCount() for i in range(len(items)): vp = VerticalPanel() if type == 'photos': vp.add(items[i]['thumb']) else: vp.add(items[i]['thumb']) vp.add(items[i]['title']) self.grid.setWidget(int(i/cols), i%cols, vp) def parsePhotos(self, items): photo_list = JSONParser().jsObjectToPyObject(items) self.photos = [] for i in range(len(photo_list)): index = "%s" % i aphoto = {} aphoto['thumb'] = HTML('<img src="' + photo_list[index]["media$group"]["media$thumbnail"]["1"]["url"] + '"/>') aphoto['full'] = photo_list[index]["media$group"]["media$content"]["0"]["url"] self.photos.append(aphoto) def parseAlbums(self, items): album_list = JSONParser().jsObjectToPyObject(items) self.albums = [] for i in range(len(album_list)): index = "%s" % i analbum = {} analbum['title'] = HTML(album_list[index]["title"]["$t"]) analbum['thumb'] = HTML('<img src="' + album_list[index]["media$group"]["media$thumbnail"]["0"]["url"] + '"/>') url = album_list[index]["id"]["$t"] analbum['id'] = url.split('albumid/')[1].split('?alt')[0] self.albums.append(analbum)
def drawGrid(self, month, year): # draw the grid in the middle of the calendar self.checkLinks(month, year) daysInMonth = self.getDaysInMonth(month, year) # first day of the month & year secs = time.mktime((year, month, 1, 0, 0, 0, 0, 0, -1)) struct = time.localtime(secs) startPos = (struct.tm_wday + self.dayoffset) % 7 slots = startPos + daysInMonth - 1 rows = int(slots/7) + 1 grid = Grid(rows+1, 7, # extra row for the days in the week StyleName="calendar-grid") grid.setWidth("100%") grid.addTableListener(self) self.middlePanel.setWidget(grid) cf = grid.getCellFormatter() # # put some content into the grid cells # for i in range(7): grid.setText(0, i, self.getDaysOfWeek()[i]) cf.addStyleName(0, i, "calendar-header") # # draw cells which are empty first # day = 0 pos = 0 while pos < startPos: self._setCell(grid, 1, pos, BLANKCELL, "calendar-blank-cell") pos += 1 # now for days of the month row = 1 day = 1 col = startPos while day <= daysInMonth: if pos % 7 == 0 and day != 1: row += 1 col = pos % 7 if not self._indaterange(self.currentYear, self.currentMonth, day): self._setCell(grid, row, col, BLANKCELL, "calendar-blank-cell") day += 1 pos += 1 continue if self.currentYear == self.todayYear and \ self.currentMonth == self.todayMonth and day == self.todayDay: style = "calendar-cell-today" else: style = "calendar-day-cell" self._setCell(grid, row, col, str(day), style) day += 1 pos += 1 # # now blank lines on the last row # col += 1 while col < 7: self._setCell(grid, row, col, BLANKCELL, "calendar-blank-cell") col += 1 return grid
class InputBox(FocusPanel): _props = [ ("maxLength", "Max Length", "MaxLength", int), ("text", "Text", "Text", None), ("matchPattern", "Match Pattern", "MatchPattern", None), ("cursorStyle", "Cursor Style", "CursorStyle", None), ] @classmethod def _getProps(self): return FocusPanel._getProps() + self._props def __init__(self, **kwargs): """ setMatchPattern - defaults to '' to match everything match pattern examples: '^[0-9]*$' is for digits only '^[0-9,A-Z]*$' is for digits and uppercase setMaxLength setText OB """ kwargs['MatchPattern'] = kwargs.pop('MatchPattern', '') cs = kwargs.pop('CursorStyle', "inputbox-cursor") gs = kwargs.pop('StyleName', 'gwt-inputbox') ap = AbsolutePanel(StyleName="inputbox") self.tp = Grid(StyleName=gs, Width="100%", Height="100%", CellPadding=0, CellSpacing=0) self.cursor = HTML(StyleName=cs) ap.add(self.tp) ap.add(self.cursor, 0, 0) self.cf = self.tp.getCellFormatter() FocusPanel.__init__(self, Widget=ap, **kwargs) self.addTableListener(self) self.addKeyboardListener(self) self.addFocusListener(self) self.word_selected_pos = 0 self.ctimer = Timer(notify=self.cursorFlash) self.focusset = False self.cstate = False self._keypressListeners = [] def addKeypressListener(self, listener): self._keypressListeners.append(listener) def removeKeypressListener(self, listener): self._keypressListeners.remove(listener) def getMatchPattern(self): return self.mp def setMatchPattern(self, mp): self.mp = mp self.rexp = re.compile(self.mp) def addDblTableListener(self, listener): self.tp.addDblTableListener(listener) def addTableListener(self, listener): self.tp.addTableListener(listener) def _move_cursor(self, col): """ moves the css-styled cursor """ #old style (useful for insert mode - don't delete this line for now!) #self.cf.setStyleName(0, col, "inputbox-square-word-cursor", highlight) el = self.cf.getRawElement(0, col+1) w = self.getWidget() px = self.tp.getAbsoluteLeft() py = self.tp.getAbsoluteTop() width = DOM.getOffsetWidth(el) px = DOM.getAbsoluteLeft(el) - px py = DOM.getAbsoluteTop(el) - py w.setWidgetPosition(self.cursor, px, py) def _highlight_cursor(self, col, highlight): """ highlights (or dehighlights) the currently selected cell """ #old style (useful for insert mode - don't delete this line for now!) #self.cf.setStyleName(0, col, "inputbox-square-word-cursor", highlight) print "_highlight", col, highlight self._move_cursor(col) self.cursor.setStyleName("inputbox-square-word-cursor", highlight) def set_grid_value(self, v, y, x): if v: w = "" else: w = "0px" v = v or EMPTY s = HTML(v, StyleName="inputbox-square") self.tp.setWidget(y, x, s) self.cf.setAlignment(y, x, HasAlignment.ALIGN_LEFT, HasAlignment.ALIGN_MIDDLE) self.cf.setWidth(y, x, w) s.setWidth(w) def onKeyDown(self, sender, keycode, modifiers): evt = DOM.eventGetCurrentEvent() DOM.eventPreventDefault(evt) if self.word_selected_pos is None: return val = chr(keycode) done = False if keycode == KeyboardListener.KEY_DELETE: self.shift_letters_back() done = True elif keycode == KeyboardListener.KEY_BACKSPACE: if not self.nasty_hack(): if self.moveCursor(-1): self.shift_letters_back() done = True elif keycode == KeyboardListener.KEY_LEFT: self.moveCursor(-1) done = True elif keycode == KeyboardListener.KEY_RIGHT: self.moveCursor(1) done = True print "onKeyDown", keycode, val, self.rexp.match(val) if not done: if self.rexp.match(val): self.press_letter(val) for listener in self._keypressListeners: listener.onKeyPressed(sender, keycode, modifiers) def press_letter(self, val): print "press letter", val # check the key is a letter, and there's a grid position highlighted if self.word_selected_pos is None: return row = 0 col = self.word_selected_pos self.highlight_cursor(False) self.set_grid_value(val, row, col) self.moveCursor(1) def nasty_hack(self): """ breaking of backspace/delete rules for the final character """ row = 0 col = self.word_selected_pos txt = self.get_char(col) if txt is None or txt == EMPTY: return False self.set_grid_value(EMPTY, row, col) return True def shift_letters_back(self): """ this function is used by del and backspace, to move the letters backwards from after the cursor. the only difference between backspace and delete is that backspace moves the cursor and _then_ does letter-moving. """ self.highlight_cursor(False) row = 0 col = self.word_selected_pos x2 = self.tp.getColumnCount()-2 while (x2 != col): txt = self.get_char(col+1) self.set_grid_value(txt, row, col) col += 1 self.set_grid_value(EMPTY, row, col) def setCursorPos(self, col): x2 = self.tp.getColumnCount()-1 col = min(x2, col) col = max(col, 0) if self.get_char(0) is None or self.get_char(0) == EMPTY: col = 0 while (self.get_char(col-1) is None or \ self.get_char(col-1) == EMPTY) and col > 1: col -= 1 self._move_cursor(col) self.highlight_cursor(False) self.word_selected_pos = col self.highlight_cursor(self.focusset) return True def getCursorPos(self): return self.word_selected_pos def moveCursor(self, dirn): x2 = self.tp.getColumnCount()-1 row = 0 col = self.word_selected_pos if dirn == 1 and x2 == col+1: return False if dirn == -1 and 0 == col+1: return False return self.setCursorPos(col+dirn) def onKeyUp(self, sender, keycode, modifiers): evt = DOM.eventGetCurrentEvent() DOM.eventCancelBubble(evt, True) DOM.eventPreventDefault(evt) def onKeyPress(self, sender, keycode, modifiers): evt = DOM.eventGetCurrentEvent() DOM.eventPreventDefault(evt) def highlight_cursor(self, highlight): """ highlights (or dehighlights) the currently selected cell """ if self.word_selected_pos is None: return col = self.word_selected_pos self._highlight_cursor(col, highlight) def getMaxLength(self): return self.tp.getColumnCount()-1 def setMaxLength(self, x): l = max(0, self.tp.getColumnCount()-1) self.tp.resize(1, x+1) self.clear(l) def clear(self, fromrange=0): for i in range(fromrange, self.tp.getColumnCount()): self.set_grid_value(EMPTY, 0, i) self.cf.setWidth(0, self.tp.getColumnCount()-1, "100%") def onCellClicked(self, listener, row, col, direction=None): self.setCursorPos(col) def cursorFlash(self, timr): if not self.focusset: return self.highlight_cursor(self.cstate) self.cstate = not self.cstate def onFocus(self, sender): print "onFocus", sender self.focusset = True self.ctimer.scheduleRepeating(800) def onLostFocus(self, sender): print "onLostFocus", sender self.focusset = False self.ctimer.cancel() self.highlight_cursor(False) def get_char(self, x): w = self.tp.getWidget(0, x) return w and w.getHTML() def getText(self): txt = '' for i in range(self.tp.getColumnCount()-1): c = self.get_char(i) if c is None or c == EMPTY: break txt += c return txt def setText(self, txt): self.highlight_cursor(False) self.clear() txt = txt[:self.getMaxLength()] for (i, c) in enumerate(txt): self.set_grid_value(c, 0, i) self.setCursorPos(min(self.getMaxLength()-1, len(txt)))
class Home: def onModuleLoad(self): loggedInUser = getCookie("LoggedInUser") self.loggedInUserJsonData = json.loads(loggedInUser) self.remote_py = MyBlogService() dockPanel = DockPanel(BorderWidth=0, Padding=0, HorizontalAlignment=HasAlignment.ALIGN_LEFT, VerticalAlignment=HasAlignment.ALIGN_TOP) dockPanel.setSize('100%', '100%') headerDockPanel = DockPanel( BorderWidth=0, Padding=0, HorizontalAlignment=HasAlignment.ALIGN_LEFT, VerticalAlignment=HasAlignment.ALIGN_CENTER) headerDockPanel.setStyleName('header') headerDockPanel.setWidth('100%') dockPanel.add(headerDockPanel, DockPanel.NORTH) dockPanel.setCellHeight(headerDockPanel, '60px') self.siteImage = Image("/images/Testware_logo.png") self.siteImage.setStyleName('logo-image') headerDockPanel.add(self.siteImage, DockPanel.WEST) headerDockPanel.setCellWidth(self.siteImage, '30%') self.pageTitle = Label('All Blogs') self.pageTitle.setStyleName('center-header') headerDockPanel.add(self.pageTitle, DockPanel.CENTER) headerDockPanel.setCellWidth(self.pageTitle, '40%') rightHeaderPanel = VerticalPanel(StyleName='right-header') headerDockPanel.add(rightHeaderPanel, DockPanel.EAST) headerDockPanel.setCellWidth(rightHeaderPanel, '30%') welcomeNoteLabel = Label('Hi %s %s!' % (self.loggedInUserJsonData["first_name"], self.loggedInUserJsonData["last_name"])) rightHeaderPanel.add(welcomeNoteLabel) logoutAnchor = Anchor(Widget=HTML('Logout'), Href='/', Title='Logout') logoutAnchor.setStyleName('logout') rightHeaderPanel.add(logoutAnchor) newBlogAnchor = Anchor(Widget=HTML('Create New Blog'), Href='/newblog.html', Title='NewBlog') newBlogAnchor.setStyleName('logout') rightHeaderPanel.add(newBlogAnchor) tree = Tree() tree.addTreeListener(self) tree.setStyleName('side-menu') dockPanel.add(tree, DockPanel.WEST) dockPanel.setCellWidth(tree, '60px') s1 = self.createItem("Blogs") allItem = self.createItem("All", value=0) self.selectedItem = allItem s1.addItem(allItem) s1.addItem(self.createItem("Published", value=1)) s1.addItem(self.createItem("Unpublished", value=2)) s2 = self.createItem("Other's Blog") s1.setState(True, fireEvents=False) tree.addItem(s1) tree.addItem(s2) self.absolultutePanel = AbsolutePanel(StyleName='detail-style') dockPanel.add(self.absolultutePanel, DockPanel.CENTER) self.blogs = [] self.g = Grid() RootPanel().add(dockPanel) self.remote_py.callMethod('getBlogs', [self.loggedInUserJsonData["username"]], self) def updatePageDisplay(self): self.g.removeFromParent() self.g = Grid() self.g.setStyleName('content-style') self.g.addTableListener(self) for y in range(len(self.blogs)): for x in range(1): json_data = json.loads(self.blogs[y]) blogPanel = VerticalPanel() blogTitleAnchor = Anchor(Widget=HTML('%s' % json_data["blog_name"]), Href='/blogdetail.html') blogTitleAnchor.setStyleName('blog-search-title') blogPanel.add(blogTitleAnchor) blogDetails = Label() blogDetails.setStyleName('blog-details') blogContent = json_data["blog_content"] if len(blogContent) > 200: blogContent = blogContent[0:200] + '......' blogDetails.setText('%s' % (blogContent)) blogPanel.add(blogDetails) value = self.selectedItem.getUserObject() if self.selectedItem.getText() == "All" and value == 0: blogStatus = Label() blogStatus.setStyleName('blog-details') if json_data["is_published"] == True: blogStatus.setText('Published') else: blogStatus.setText('Unpublished') blogPanel.add(blogStatus) self.g.add(blogPanel, y, x) self.absolultutePanel.add(self.g) def createItem(self, label, value=None): item = TreeItem(label) DOM.setStyleAttribute(item.getElement(), "cursor", "pointer") if value is not None: item.setUserObject(value) return item def onTreeItemSelected(self, item): self.selectedItem = item if item.getText() == "Other's Blog": self.remote_py.callMethod('getOthersPublishedBlogs', [self.loggedInUserJsonData["username"]], self) else: value = item.getUserObject() if value == 0: self.remote_py.callMethod( 'getBlogs', [self.loggedInUserJsonData["username"]], self) elif value == 1: self.remote_py.callMethod( 'getPublishedBlogs', [self.loggedInUserJsonData["username"]], self) elif value == 2: self.remote_py.callMethod( 'getUnPublishedBlogs', [self.loggedInUserJsonData["username"]], self) def onTreeItemStateChanged(self, item): pass # We ignore this. def onRemoteResponse(self, response, requestInfo): self.blogs = response self.updatePageDisplay() if self.selectedItem.getText() == "Other's Blog": self.pageTitle.setText("Other's Blog") else: value = self.selectedItem.getUserObject() if value == 0: self.pageTitle.setText('All Blogs') elif value == 1: self.pageTitle.setText('Published Blogs') elif value == 2: self.pageTitle.setText('Unpublished Blogs') def onRemoteError(self, code, error_dict, requestInfo): pass def onCellClicked(self, sender, row, col): setCookie("SelectedBlog", self.blogs[row], 10000, path='/') setCookie("ShowPublishButton", 'False', 10000, path='/')