class Feed: def __init__(self, url, callback): global frameId frame = DOM.createElement("iframe") frameid = "__pygwt_feedFrame%d" % frameId frameId += 1 DOM.setAttribute(frame, "id", frameid) DOM.setAttribute(frame, "src", url) #DOM.setStyleAttribute(frame, 'width', '0') #DOM.setStyleAttribute(frame, 'height', '0') #DOM.setStyleAttribute(frame, 'border', '0') #DOM.setStyleAttribute(frame, 'position', 'absolute') self.frameId = frameId self.frame = frame self.timer = Timer(notify=self) doc().parent.body.appendChild(frame) self.callback = callback self.timer.scheduleRepeating(100) def getFrameTxt(self): return str(self.frame.contentWindow.document.body.innerHTML) def onTimer(self, *args): txt = self.getFrameTxt() if txt == '': return self.callback(self, txt) self.timer.cancel()
class Animate(object): def __init__(self, widget, action, fps=50): self.widget = widget self.action = action self.fps = fps self.timer = Timer(0, self) self.timer.scheduleRepeating(int(1000.0 / fps)) def onTimer(self, sender): params = self.action(self.widget) if not params: self.timer.cancel() return
class Animate(object): def __init__(self, widget, action, fps=50): self.widget = widget self.action = action self.fps = fps self.timer = Timer(0, self) self.timer.scheduleRepeating(int(1000.0/fps)) def onTimer(self, sender): params = self.action(self.widget) if not params: self.timer.cancel() return
class Clock: # pyjamas doesn't generate __doc__ __doc__ = '''This demonstrates using Timer instantiated with the notify keyword, as in:<pre> timer = Timer(notify=func) </pre>When the timer fires it will call func() with no arguments (or <code>self</code> if it is a bound method as in this example). This timer is scheduled with the <code>scheduleRepeating()</code> method, so after func() is called, it is automatically rescheduled to fire again after the specified period. The timer can be cancelled by calling the <code>cancel()</code> method; this happens when you click on the button. ''' start_txt = 'Click to start the clock' stop_txt = 'Click to stop the clock' def __init__(self): # the button self.button = Button(listener=self) # set an attr on the button to keep track of its state self.button.stop = False # date label self.datelabel = Label(StyleName='clock') # the timer self.timer = Timer(notify=self.updateclock) # kick start self.onClick(self.button) def onClick(self, button): if self.button.stop: # we're stopping the clock self.button.stop = False self.timer.cancel() self.button.setText(self.start_txt) else: # we're starting the clock self.button.stop = True self.timer.scheduleRepeating(1000) self.button.setText(self.stop_txt) def updateclock(self, timer): # the callable attached to the timer with notify dt = datetime.now().replace(microsecond=0) self.datelabel.setText(dt.isoformat(' '))
class Tooltip(PopupPanel): def __init__(self, sender, offsetX, offsetY, contents, show_delay, hide_delay, styleName, **kwargs): """ contents may be a text string or it may be a widget """ PopupPanel.__init__(self, True, **kwargs) self.show_delay = show_delay self.hide_delay = hide_delay if isinstance(contents, basestring): contents = HTML(contents) self.add(contents) left = sender.getAbsoluteLeft() + offsetX top = sender.getAbsoluteTop() + offsetY self.setPopupPosition(left, top) self.setStyleName(styleName) if tooltip_hide_timer: self.tooltip_show_timer = Timer(1, self) else: self.tooltip_show_timer = Timer(self.show_delay, self) def show(self): global tooltip_hide_timer # activate fast tooltips tooltip_hide_timer = Timer(self.hide_delay, self) PopupPanel.show(self) def hide(self, autoClosed=False): self.tooltip_show_timer.cancel() PopupPanel.hide(self, autoClosed) def onTimer(self, timer): global tooltip_hide_timer # deactivate fast tooltips on last timer if timer is tooltip_hide_timer: tooltip_hide_timer = None if timer is self.tooltip_show_timer: self.show() else: self.hide()
class RichTextToolbar(Composite, ClickHandler, ChangeHandler): fontSizesConstants = [ RichTextAreaConsts.XX_SMALL, RichTextAreaConsts.X_SMALL, RichTextAreaConsts.SMALL, RichTextAreaConsts.MEDIUM, RichTextAreaConsts.LARGE, RichTextAreaConsts.X_LARGE, RichTextAreaConsts.XX_LARGE ] """* * Creates a toolbar that drives the given rich text area. * * @param richText the rich text area to be controlled """ def __init__(self, richText, _parent, **kwargs): self.isInText = False self.lastText = "" self.trigger = False self.lastRange = None self._parent = _parent # Timer for trying real time selection change stuff self.timerRange = None self.selTimer = Timer(notify=self.run) self.outer = VerticalPanel() self.topPanel = HorizontalPanel(BorderWidth=1) self.bottomPanel = HorizontalPanel() self.richText = richText self.basic = richText.getBasicFormatter() self.extended = richText.getExtendedFormatter() self.outer.add(self.topPanel) self.outer.add(self.bottomPanel) self.topPanel.setWidth("100%") self.topPanel.setHeight("20px") self.bottomPanel.setWidth("100%") kwargs['StyleName'] = kwargs.get('StyleName', "gwt-RichTextToolbar") Composite.__init__(self, self.outer, **kwargs) ClickHandler.__init__(self) ChangeHandler.__init__(self) if self.basic is not None: self.bold = self.createToggleButton(Images.bold, "bold") self.italic = self.createToggleButton(Images.italic, "italic") self.underline = self.createToggleButton(Images.underline, "underline") self.subscript = self.createToggleButton(Images.subscript, "subscript") self.superscript = self.createToggleButton(Images.superscript, "superscript") self.justifyLeft = self.createPushButton(Images.justifyLeft, "justify left") self.justifyCenter = self.createPushButton(Images.justifyCenter, "justify centre") self.justifyRight = self.createPushButton(Images.justifyRight, "justify right") self.topPanel.add(self.bold) self.topPanel.add(self.italic) self.topPanel.add(self.underline) self.topPanel.add(self.subscript) self.topPanel.add(self.superscript) self.topPanel.add(self.justifyLeft) self.topPanel.add(self.justifyCenter) self.topPanel.add(self.justifyRight) if self.extended is not None: self.strikethrough = self.createToggleButton(Images.strikeThrough, "strikethrough") self.indent = self.createPushButton(Images.indent, "indent") self.outdent = self.createPushButton(Images.outdent, "outdent") self.hr = self.createPushButton(Images.hr, "hr") self.ol = self.createPushButton(Images.ol, "ordered list") self.ul = self.createPushButton(Images.ul, "unordered list") self.insertImage = self.createPushButton(Images.insertImage, "insert image") self.createLink = self.createPushButton(Images.createLink, "create link") self.removeLink = self.createPushButton(Images.removeLink, "remove link") self.removeFormat = self.createPushButton(Images.removeFormat, "remove formatting") self.topPanel.add(self.strikethrough) self.topPanel.add(self.indent) self.topPanel.add(self.outdent) self.topPanel.add(self.hr) self.topPanel.add(self.ol) self.topPanel.add(self.ul) self.topPanel.add(self.insertImage) self.topPanel.add(self.createLink) self.topPanel.add(self.removeLink) self.topPanel.add(self.removeFormat) if self.basic is not None: self.hstyles = self.createHeadingStyleList("Headings") self.backColors = self.createColorList("Background") self.foreColors = self.createColorList("Foreground") self.fonts = self.createFontList() self.fontSizes = self.createFontSizes() self.bottomPanel.add(self.hstyles) self.bottomPanel.add(self.backColors) self.bottomPanel.add(self.foreColors) self.bottomPanel.add(self.fonts) self.bottomPanel.add(self.fontSizes) self.richText.addKeyboardListener(self) self.richText.addClickListener(self) self.richText.addFocusListener(self) self.richText.addMouseListener(self) 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 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 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 createPushButton(self, img, tip): img = Image(img) pb = PushButton(img, img, self) pb.setTitle(tip) return pb def createToggleButton(self, img, tip): img = Image(img) tb = ToggleButton(img, img, self) tb.setTitle(tip) return tb def updateStatus(self): """* Updates the status of all the stateful buttons. """ if self.basic is not None: self.bold.setDown(self.basic.isBold()) self.italic.setDown(self.basic.isItalic()) self.underline.setDown(self.basic.isUnderlined()) self.subscript.setDown(self.basic.isSubscript()) self.superscript.setDown(self.basic.isSuperscript()) if self.extended is not None: self.strikethrough.setDown(self.extended.isStrikethrough()) def onChange(self, sender): if sender == self.hstyles: bc = self.hstyles.getValue(self.hstyles.getSelectedIndex()) self._surround(HeadingStyleManager, bc) self.backColors.setSelectedIndex(0) if sender == self.backColors: bc = self.backColors.getValue(self.backColors.getSelectedIndex()) self.basic.setBackColor(bc) self.backColors.setSelectedIndex(0) elif sender == self.foreColors: fc = self.foreColors.getValue(self.foreColors.getSelectedIndex()) self.basic.setForeColor(fc) self.foreColors.setSelectedIndex(0) elif sender == self.fonts: fname = self.fonts.getValue(self.fonts.getSelectedIndex()) self.basic.setFontName(fname) self.fonts.setSelectedIndex(0) elif sender == self.fontSizes: fs = self.fontSizesConstants[self.fontSizes.getSelectedIndex() - 1] self.basic.setFontSize(fs) self.fontSizes.setSelectedIndex(0) def onClick(self, sender): if sender == self.bold: self.basic.toggleBold() elif sender == self.italic: self.basic.toggleItalic() elif sender == self.underline: self.basic.toggleUnderline() elif sender == self.subscript: self.basic.toggleSubscript() elif sender == self.superscript: self.basic.toggleSuperscript() elif sender == self.strikethrough: self.extended.toggleStrikethrough() elif sender == self.indent: self.extended.rightIndent() elif sender == self.outdent: self.extended.leftIndent() elif sender == self.justifyLeft: self.basic.setJustification(RichTextAreaConsts.LEFT) elif sender == self.justifyCenter: self.basic.setJustification(RichTextAreaConsts.CENTER) elif sender == self.justifyRight: self.basic.setJustification(RichTextAreaConsts.RIGHT) elif sender == self.insertImage: url = Window.prompt("Enter an image URL:", "http:#") if url is not None: self.extended.insertImage(url) elif sender == self.createLink: EventLinkPopup_open(self) elif sender == self.removeLink: self.extended.removeLink() elif sender == self.hr: self.extended.insertHorizontalRule() elif sender == self.ol: self.extended.insertOrderedList() elif sender == self.ul: self.extended.insertUnorderedList() elif sender == self.removeFormat: self.extended.removeFormat() elif sender == self.richText: # We use the RichTextArea's onKeyUp event to update the # toolbar status. This will catch any cases where the # user moves the cursor using the keyboard, or uses one of # the browser's built-in keyboard shortcuts. self.updateStatus() self.checkForChange() def onKeyDown(self, sender, keyCode, modifiers): pass def onKeyPress(self, sender, keyCode, modifiers): pass def onKeyUp(self, sender, keyCode, modifiers): if sender == self.richText: # We use the RichTextArea's onKeyUp event to update the # toolbar status. This will catch any cases where the user # moves the cursor using the keyboard, or uses one of # the browser's built-in keyboard shortcuts. self.updateStatus() self.checkForChange() def onMouseLeave(self, event): pass def onMouseEnter(self, event): pass def onMouseUp(self, event, x, y): pass def onMouseMove(self, event, x, y): pass def onMouseDown(self, event, x, y): self.trigger = True def onFocus(self, event): print "focus" pass def onLostFocus(self, event): "lost focus" self.checkForChange() def onMouseOut(self, sender): print "mouse out" if self.isInText and self.isOnTextBorder(sender): self.isInText = False self.captureSelection() self.endSelTimer() def onMouseOver(self, sender): print "mouse over" if not self.isInText: self.isInText = True self.richText.setFocus(True) self.lastRange = None self.startSelTimer() def setFocus(self, wid): self._wid = wid # hack DeferredCommand.add(getattr(self, "execute_set_focus")) def execute_set_focus(self): self._wid.setFocus(True) def findNodeByNumber(self, num): doc = self.getDocument() res = getAdjacentTextElement(doc, True) while (res is not None) and (num > 0): num -= 1 res = getAdjacentTextElement(res, True) return res def selectNodes(self, startNode, startOffset, endNode=None, endOffset=None): startText = self.findNodeByNumber(startNode) if endNode is not None: endText = self.findNodeByNumber(endNode) else: endText = startText endOffset = startOffset rng = Range(RangeEndPoint(startText, startOffset), RangeEndPoint(endText, endOffset)) self.getSelection() Selection.setRange(rng) self.refresh() def font1(self): self._surround(FontFamilyManager, "Times New Roman") def font2(self): self._surround(FontFamilyManager, "Arial") def surround1(self): self._surround(CustomStyleManager, "editor-cls1") def surround2(self): self._surround(CustomStyleManager, "editor-cls2") def _surround(self, kls, cls): """ this is possibly one of the most truly dreadful bits of code for manipulating DOM ever written. its purpose is to add only the editor class required, and no more. unfortunately, DOM gets chopped up by the range thing, and a bit more besides. so we have to: * extract the range contents * clean up removing any blank text nodes that got created above * slap a span round it * clean up removing any blank text nodes that got created above * remove any prior editor styles on the range contents * go hunting through the entire document for stacked editor styles this latter is funfunfun because only "spans with editor styles which themselves have no child elements but a single span with an editor style" must be removed. e.g. if an outer editor span has another editor span and also some text, the outer span must be left alone. """ rng = self.getRange() if (rng is None) or rng.isCursor(): return csm = kls(rng.m_document, cls) rng.ensureRange() dfrag = rng.m_range.extractContents() remove_editor_styles(rng.m_document, csm, dfrag) element = csm.create() DOM.appendChild(element, dfrag) rng.m_range.insertNode(element) it = DOM.IterWalkChildren(element, True) while True: try: node = it.next() except StopIteration: break if node.nodeType == 3 and unicode(node.data) == u'': DOM.removeChild(node.parentNode, node) rng.setRange(element) it = DOM.IterWalkChildren(rng.m_document, True) while True: try: node = it.next() except StopIteration: break if node.nodeType == 3 and unicode(node.data) == u'': DOM.removeChild(node.parentNode, node) # clears out all nodes with no children. it = DOM.IterWalkChildren(rng.m_document) while True: try: node = it.next() except StopIteration: break if node.firstChild or not csm.identify(node): continue DOM.removeChild(node.parentNode, node) it = DOM.IterWalkChildren(rng.m_document, True) while True: try: node = it.next() except StopIteration: break if not csm.identify(node): continue if node.firstChild is None: continue if not csm.identify(node.firstChild): continue if node.firstChild.nextSibling: continue # remove the *outer* one because the range was added to # the inner, and the inner one overrides anyway remove_node(rng.m_document, node) doc = self.getDocument() self.getSelection() Selection.setRange(rng) self.refresh() def refresh(self): self._parent.refresh() def delete(self): rng = self.getRange() if rng is None or rng.isCursor(): return rng.deleteContents() refresh() def toCursor(self, start): rng = self.getRange() if rng is None or rng.isCursor(): return rng.collapse(start) self.getSelection() Selection.setRange(rng) self.refresh() def run(self): try: self.getSelection() rng = Selection.getRange() if (self.timerRange is None) or (not self.timerRange.equals(rng)): self.onSelectionChange(rng) self.timerRange = rng except: GWT.log("Error in timer selection", ex) def getSelection(self): res = None try: window = self.getWindow() Selection.getSelection(window) except: print "Error getting the selection" traceback.print_exc() def getWindow(self, iFrame=None): if iFrame is None: iFrame = self.richText.getElement() iFrameWin = iFrame.contentWindow or iFrame.contentDocument if not iFrameWin.document: iFrameWin = iFrameWin.parentNode # FBJS version of parentNode #print "getWindow", iFrameWin, dir(iFrameWin) return iFrameWin def captureSelection(self): """ This captures the selection when the mouse leaves the RTE, because in IE the selection indicating the cursor position is lost once another widget gains focus. Could be implemented for IE only. """ try: self.getSelection() self.lastRange = Selection.getRange() except: GWT.log("Error capturing selection for IE", ex) # Gets run every time the selection is changed def onSelectionChange(self, sel): pass def isOnTextBorder(self, sender): twX = self.richText.getAbsoluteLeft() twY = self.richText.getAbsoluteTop() x = event.getClientX() - twX y = event.getClientY() - twY width = self.richText.getOffsetWidth() height = self.richText.getOffsetHeight() return ((sender == self.richText) and ((x <= 0) or (x >= width) or (y <= 0) or (y >= height))) def startSelTimer(self): self.selTimer.scheduleRepeating(250) def endSelTimer(self): self.selTimer.cancel() def getRange(self): if self.lastRange is None: self.getSelection() return Selection.getRange() else: return self.lastRange def checkForChange(self): text = self.richText.getHTML() if text == self.lastText: return nEvt = doc().createEvent("HTMLEvents") nEvt.initEvent("change", False, True) self.getElement().dispatchEvent(nEvt) self.lastText = text def setHtml(self, text): self.richText.setHTML(text) self.lastText = text def getHtml(self): return self.richText.getHTML() def getDocument(self): return Selection.getDocument(self.getWindow()) def getFormatter(self): return self.richText.getExtendedFormatter()
class RichTextEditor(Composite): def run(self): try: self.getSelection() rng = Selection.getRange() if (self.m_timerRange is None) or (not self.m_timerRange.equals(rng)): self.onSelectionChange(rng) self.m_timerRange = rng except: GWT.log("Error in timer selection", ex) def __init__(self): Composite.__init__(self) self.m_isInText = False self.m_lastText = "" self.trigger = False self.m_lastRange = None # Timer for trying real time selection change stuff self.m_timerRange = None self.m_selTimer = Timer() self.m_mainPanel = DockPanel() self.m_toolbarPanel = HorizontalPanel() self.m_toolbarPanel.setWidth("100%") self.m_toolbarPanel.setHeight("25px") self.m_toolbarPanel.setBorderWidth(1) self.m_toolbarPanel.addStyleName("timeline-RichTextToolbar") self.m_textW = RichTextArea() self.m_textW.addClickListener(self) self.m_textW.addKeyboardListener(self) self.m_textW.addFocusListener(self) self.m_textW.addMouseListener(self) # According to gwt doc, these do need to be set because this is a frame self.m_textW.setHeight("100%") self.m_textW.setWidth("100%") # Add buttons self.m_formatter = self.getFormatter() self.m_boldW = self.addToggleButton(self.m_toolbarPanel, Icons.bold_icon, "Bold") self.m_italicW = self.addToggleButton(self.m_toolbarPanel, Icons.italics_icon, "Italic") self.m_underlineW = self.addToggleButton(self.m_toolbarPanel, Icons.underline_icon, "Underline") self.m_subscriptW = self.addToggleButton(self.m_toolbarPanel, Icons.subscript_icon, "Subscript") self.m_superscriptW = self.addToggleButton(self.m_toolbarPanel, Icons.superscript_icon, "Superscript") self.m_strikethroughW = self.addToggleButton(self.m_toolbarPanel, Icons.strikethrough_icon, "Strikethrough") self.m_indentW = self.addPushButton(self.m_toolbarPanel, Icons.indentmore_icon, "Indent Right") self.m_outdentW = self.addPushButton(self.m_toolbarPanel, Icons.indentless_icon, "Indent Left") self.m_justifyLeftW = self.addPushButton(self.m_toolbarPanel, Icons.justifyleft_icon, "Justify Left") self.m_justifyCenterW = self.addPushButton(self.m_toolbarPanel, Icons.justifycenter_icon, "Justify Center") self.m_justifyRightW = self.addPushButton(self.m_toolbarPanel, Icons.justifyright_icon, "Justify Right") self.m_hrW = self.addPushButton(self.m_toolbarPanel, Icons.horizontalrule_icon, "Horizontal Rule") self.m_olW = self.addPushButton(self.m_toolbarPanel, Icons.numberedlist_icon, "Numbered List") self.m_ulW = self.addPushButton(self.m_toolbarPanel, Icons.list_icon, "List") self.m_newLinkW = self.addPushButton(self.m_toolbarPanel, Icons.link_icon, "Link Document") self.m_removeFormatW = self.addPushButton(self.m_toolbarPanel, Icons.noformat_icon, "No Format") self.m_mainPanel.add(self.m_toolbarPanel, DockPanel.NORTH) self.m_mainPanel.add(self.m_textW, DockPanel.CENTER) self.initWidget(self.m_mainPanel) self.sinkEvents(Event.ONCLICK) def getFormatter(self): return self.m_textW.getExtendedFormatter() def getRichTextArea(self): return self.m_textW def addPushButton(self, panel, imagep, tip): img = Image(imagep) img.setWidth("20px") img.setHeight("20px") pb = PushButton(img) self.addAnyButton(panel, pb, tip) return pb def addToggleButton(self, panel, imagep, tip): img = Image(imagep) img.setWidth("20px") img.setHeight("20px") tb = ToggleButton(img) self.addAnyButton(panel, tb, tip) return tb def addAnyButton(self, panel, button, tip): button.addStyleName("richText-button") button.setTitle(tip) button.setWidth(BUTTON_WIDTH) button.setHeight("100%") panel.add(button) panel.setCellWidth(button, BUTTON_WIDTH) button.addClickListener(self) def onClick(self, sender): if sender == self.m_boldW: self.m_formatter.toggleBold() elif sender == self.m_italicW: self.m_formatter.toggleItalic() elif sender == self.m_underlineW: self.m_formatter.toggleUnderline() elif sender == self.m_subscriptW: self.m_formatter.toggleSubscript() elif sender == self.m_superscriptW: self.m_formatter.toggleSuperscript() elif sender == self.m_strikethroughW: self.m_formatter.toggleStrikethrough() elif sender == self.m_indentW: self.m_formatter.rightIndent() elif sender == self.m_outdentW: self.m_formatter.leftIndent() elif sender == self.m_justifyLeftW: self.m_formatter.setJustification(RichTextArea.Justification.LEFT) elif sender == self.m_justifyCenterW: self.m_formatter.setJustification( RichTextArea.Justification.CENTER) elif sender == self.m_justifyRightW: self.m_formatter.setJustification(RichTextArea.Justification.RIGHT) elif sender == self.m_hrW: self.m_formatter.insertHorizontalRule() elif sender == self.m_olW: self.m_formatter.insertOrderedList() elif sender == self.m_ulW: self.m_formatter.insertUnorderedList() elif sender == self.m_removeFormatW: self.m_formatter.removeFormat() elif sender == self.m_newLinkW: EventLinkPopup.open(self) elif sender == self.m_textW: self.updateStatus() self.checkForChange() def onKeyDown(self, sender, keycode, modifiers): pass def onKeyUp(self, sender, keycode, modifiers): if sender == self.m_textW: self.updateStatus() self.checkForChange() def onMouseLeave(self, event): pass def onMouseEnter(self, event): pass def onMouseUp(self, event, x, y): pass def onMouseMove(self, event, x, y): pass def onMouseDown(self, event, x, y): self.trigger = True def onFocus(self, event): pass def onLostFocus(self, event): self.checkForChange() def onMouseOut(self, event): if self.m_isInText and self.isOnTextBorder(event): self.m_isInText = False self.captureSelection() self.endSelTimer() def onMouseOver(self, event): if not self.m_isInText: self.m_isInText = True self.m_textW.setFocus(True) self.m_lastRange = None self.startSelTimer() """* * This captures the selection when the mouse leaves the RTE, because in IE * the selection indicating the cursor position is lost once another widget * gains focus. Could be implemented for IE only. """ def captureSelection(self): try: self.getSelection() self.m_lastRange = Selection.getRange() except: GWT.log("Error capturing selection for IE", ex) # Gets run every time the selection is changed def onSelectionChange(self, sel): pass def isOnTextBorder(self, event): sender = event.getSource() twX = self.m_textW.getAbsoluteLeft() twY = self.m_textW.getAbsoluteTop() x = event.getClientX() - twX y = event.getClientY() - twY width = self.m_textW.getOffsetWidth() height = self.m_textW.getOffsetHeight() return ((sender == self.m_textW) and ((x <= 0) or (x >= width) or (y <= 0) or (y >= height))) def startSelTimer(self): self.m_selTimer.scheduleRepeating(250) def endSelTimer(self): self.m_selTimer.cancel() def getRange(self): if self.m_lastRange is None: self.getSelection() return Selection.getRange() else: return self.m_lastRange def getSelection(self): res = None try: window = self.getWindow() Selection.getSelection(window) except: print "Error getting the selection" traceback.print_exc() def getWindow(self, iFrame=None): if iFrame is None: iFrame = self.m_textW.getElement() iFrameWin = iFrame.contentWindow or iFrame.contentDocument if not iFrameWin.document: iFrameWin = iFrameWin.parentNode # FBJS version of parentNode #print "getWindow", iFrameWin, dir(iFrameWin) return iFrameWin def getDocument(self): return Selection.getDocument(self.getWindow()) def setHtml(self, text): self.m_textW.setHTML(text) self.m_lastText = text def getHtml(self): return self.m_textW.getHTML() def checkForChange(self): text = self.m_textW.getHTML() if text != self.m_lastText: nEvt = doc().createEvent("HTMLEvents") nEvt.initEvent("change", False, True) self.getElement().dispatchEvent(nEvt) self.m_lastText = text # Update edit buttons based on current cursor location def updateStatus(self): if self.m_formatter is None: return self.m_boldW.setDown(self.m_formatter.isBold()) self.m_italicW.setDown(self.m_formatter.isItalic()) self.m_underlineW.setDown(self.m_formatter.isUnderlined()) self.m_subscriptW.setDown(self.m_formatter.isSubscript()) self.m_superscriptW.setDown(self.m_formatter.isSuperscript()) self.m_strikethroughW.setDown(self.m_formatter.isStrikethrough()) def addChangeHandler(self, handler): return addDomHandler(handler, ChangeEvent.getType())
class RandomColor: __doc__ = '''This last example demonstrates what most pyjamas programmers currently do with timers: create a Timer instance specifying <code>notify</code> with an object that has an <code>onTimer</code> attribute that is callable. The slider on the left will adjust how often the middle panel changes color; it is either OFF or a value of seconds from 1 to 5. Changing the slider immediately cancels the current timer and starts a new timer to change the color in the newly specified time. Like the previous example, this timer reschedules itself (if it wasn't turned off) at the end of the call to <code>onTimer()</code>. ''' def __init__(self): # create the label and slider self.__label = Label('OFF') self.slider = slider = HorizontalSlider(0, 5, step=1, StyleName="slider") slider.setDragable(True) slider.addControlValueListener(self) # put them in a hpanel self.hpanel = hpanel = HorizontalPanel(Spacing=10) hpanel.add(slider) hpanel.add(self.__label) # create the color panel and give it color self.colorpanel = CaptionPanel('Color:', SimplePanel(StyleName='colorpanel')) self.randomcolor() # we're initially off self.value = 0 # create our timer self.timer = Timer(notify=self) def initialize(self): # this method solves an apparent bug with the slider: the # slider doesn't draw its handle if the position is set before # showing, so instead of doing this in __init__ (where I # originally had it), this method gets called after it is # shown on the root panel. See below when it gets called. self.slider.setValue(self.value) self.slider.setControlPos(self.value) def onTimer(self, timer): # when the timer fires we randomize the color and (maybe) # reschedule ourselves. self.randomcolor() v = self.value * 1000 if v: self.timer.schedule(v) def onControlValueChanged(self, sender, old, new): # event handler for when the slider is moved. if new == self.value: return self.value = new # is it being turned off? if new == 0: self.__label.setText('OFF') self.timer.cancel() else: # no it's being reset self.__label.setText(str(new) + ' sec') self.onTimer(self.timer) def randomcolor(self): # randomize the color and set the panel accordingly r = random()*256 g = random()*256 b = random()*256 e = self.colorpanel.getWidget().getElement() color = '#%02x%02x%02x' % (r, g, b) self.colorpanel.setCaption('Color: %s' % color) DOM.setStyleAttribute(e, "background", color)
class RandomColor: __doc__ = '''This last example demonstrates what most pyjamas programmers currently do with timers: create a Timer instance specifying <code>notify</code> with an object that has an <code>onTimer</code> attribute that is callable. The slider on the left will adjust how often the middle panel changes color; it is either OFF or a value of seconds from 1 to 5. Changing the slider immediately cancels the current timer and starts a new timer to change the color in the newly specified time. Like the previous example, this timer reschedules itself (if it wasn't turned off) at the end of the call to <code>onTimer()</code>. ''' def __init__(self): # create the label and slider self.__label = Label('OFF') self.slider = slider = HorizontalSlider(0, 5, step=1, StyleName="slider") slider.setDragable(True) slider.addControlValueListener(self) # put them in a hpanel self.hpanel = hpanel = HorizontalPanel(Spacing=10) hpanel.add(slider) hpanel.add(self.__label) # create the color panel and give it color self.colorpanel = CaptionPanel('Color:', SimplePanel(StyleName='colorpanel')) self.randomcolor() # we're initially off self.value = 0 # create our timer self.timer = Timer(notify=self) def initialize(self): # this method solves an apparent bug with the slider: the # slider doesn't draw its handle if the position is set before # showing, so instead of doing this in __init__ (where I # originally had it), this method gets called after it is # shown on the root panel. See below when it gets called. self.slider.setValue(self.value) self.slider.setControlPos(self.value) def onTimer(self, timer): # when the timer fires we randomize the color and (maybe) # reschedule ourselves. self.randomcolor() v = self.value * 1000 if v: self.timer.schedule(v) def onControlValueChanged(self, sender, old, new): # event handler for when the slider is moved. if new == self.value: return self.value = new # is it being turned off? if new == 0: self.__label.setText('OFF') self.timer.cancel() else: # no it's being reset self.__label.setText(str(new) + ' sec') self.onTimer(self.timer) def randomcolor(self): # randomize the color and set the panel accordingly r = random() * 256 g = random() * 256 b = random() * 256 e = self.colorpanel.getWidget().getElement() color = '#%02x%02x%02x' % (r, g, b) self.colorpanel.setCaption('Color: %s' % color) DOM.setStyleAttribute(e, "background", color)
class RichTextEditor(Composite): def run(self): try: self.getSelection() rng = Selection.getRange() if (self.m_timerRange is None) or (not self.m_timerRange.equals(rng)): self.onSelectionChange(rng) self.m_timerRange = rng except: GWT.log("Error in timer selection", ex) def __init__(self): Composite.__init__(self) self.m_isInText = False self.m_lastText = "" self.trigger = False self.m_lastRange = None # Timer for trying real time selection change stuff self.m_timerRange = None self.m_selTimer = Timer() self.m_mainPanel = DockPanel() self.m_toolbarPanel = HorizontalPanel() self.m_toolbarPanel.setWidth("100%") self.m_toolbarPanel.setHeight("25px") self.m_toolbarPanel.setBorderWidth(1) self.m_toolbarPanel.addStyleName("timeline-RichTextToolbar") self.m_textW = RichTextArea() self.m_textW.addClickListener(self) self.m_textW.addKeyboardListener(self) self.m_textW.addFocusListener(self) self.m_textW.addMouseListener(self) # According to gwt doc, these do need to be set because this is a frame self.m_textW.setHeight("100%") self.m_textW.setWidth("100%") # Add buttons self.m_formatter = self.getFormatter() self.m_boldW = self.addToggleButton(self.m_toolbarPanel, Icons.bold_icon, "Bold") self.m_italicW = self.addToggleButton(self.m_toolbarPanel, Icons.italics_icon, "Italic") self.m_underlineW = self.addToggleButton(self.m_toolbarPanel, Icons.underline_icon, "Underline") self.m_subscriptW = self.addToggleButton(self.m_toolbarPanel, Icons.subscript_icon, "Subscript") self.m_superscriptW = self.addToggleButton(self.m_toolbarPanel, Icons.superscript_icon, "Superscript") self.m_strikethroughW = self.addToggleButton(self.m_toolbarPanel, Icons.strikethrough_icon, "Strikethrough") self.m_indentW = self.addPushButton(self.m_toolbarPanel, Icons.indentmore_icon, "Indent Right") self.m_outdentW = self.addPushButton(self.m_toolbarPanel, Icons.indentless_icon, "Indent Left") self.m_justifyLeftW = self.addPushButton(self.m_toolbarPanel, Icons.justifyleft_icon, "Justify Left") self.m_justifyCenterW = self.addPushButton(self.m_toolbarPanel, Icons.justifycenter_icon, "Justify Center") self.m_justifyRightW = self.addPushButton(self.m_toolbarPanel, Icons.justifyright_icon, "Justify Right") self.m_hrW = self.addPushButton(self.m_toolbarPanel, Icons.horizontalrule_icon, "Horizontal Rule") self.m_olW = self.addPushButton(self.m_toolbarPanel, Icons.numberedlist_icon, "Numbered List") self.m_ulW = self.addPushButton(self.m_toolbarPanel, Icons.list_icon, "List") self.m_newLinkW = self.addPushButton(self.m_toolbarPanel, Icons.link_icon, "Link Document") self.m_removeFormatW = self.addPushButton(self.m_toolbarPanel, Icons.noformat_icon, "No Format") self.m_mainPanel.add(self.m_toolbarPanel, DockPanel.NORTH) self.m_mainPanel.add(self.m_textW, DockPanel.CENTER) self.initWidget(self.m_mainPanel) self.sinkEvents(Event.ONCLICK) def getFormatter(self): return self.m_textW.getExtendedFormatter() def getRichTextArea(self): return self.m_textW def addPushButton(self, panel, imagep, tip): img = Image(imagep) img.setWidth("20px") img.setHeight("20px") pb = PushButton(img) self.addAnyButton(panel, pb, tip) return pb def addToggleButton(self, panel, imagep, tip): img = Image(imagep) img.setWidth("20px") img.setHeight("20px") tb = ToggleButton(img) self.addAnyButton(panel, tb, tip) return tb def addAnyButton(self, panel, button, tip): button.addStyleName("richText-button") button.setTitle(tip) button.setWidth(BUTTON_WIDTH) button.setHeight("100%") panel.add(button) panel.setCellWidth(button, BUTTON_WIDTH) button.addClickListener(self) def onClick(self, sender): if sender == self.m_boldW: self.m_formatter.toggleBold() elif sender == self.m_italicW: self.m_formatter.toggleItalic() elif sender == self.m_underlineW: self.m_formatter.toggleUnderline() elif sender == self.m_subscriptW: self.m_formatter.toggleSubscript() elif sender == self.m_superscriptW: self.m_formatter.toggleSuperscript() elif sender == self.m_strikethroughW: self.m_formatter.toggleStrikethrough() elif sender == self.m_indentW: self.m_formatter.rightIndent() elif sender == self.m_outdentW: self.m_formatter.leftIndent() elif sender == self.m_justifyLeftW: self.m_formatter.setJustification(RichTextArea.Justification.LEFT) elif sender == self.m_justifyCenterW: self.m_formatter.setJustification(RichTextArea.Justification.CENTER) elif sender == self.m_justifyRightW: self.m_formatter.setJustification(RichTextArea.Justification.RIGHT) elif sender == self.m_hrW: self.m_formatter.insertHorizontalRule() elif sender == self.m_olW: self.m_formatter.insertOrderedList() elif sender == self.m_ulW: self.m_formatter.insertUnorderedList() elif sender == self.m_removeFormatW: self.m_formatter.removeFormat() elif sender == self.m_newLinkW: EventLinkPopup.open(self) elif sender == self.m_textW: self.updateStatus() self.checkForChange() def onKeyDown(self, sender, keycode, modifiers): pass def onKeyUp(self, sender, keycode, modifiers): if sender == self.m_textW: self.updateStatus() self.checkForChange() def onMouseLeave(self, event): pass def onMouseEnter(self, event): pass def onMouseUp(self, event, x, y): pass def onMouseMove(self, event, x, y): pass def onMouseDown(self, event, x, y): self.trigger = True def onFocus(self, event): pass def onLostFocus(self, event): self.checkForChange() def onMouseOut(self, event): if self.m_isInText and self.isOnTextBorder(event): self.m_isInText = False self.captureSelection() self.endSelTimer() def onMouseOver(self, event): if not self.m_isInText: self.m_isInText = True self.m_textW.setFocus(True) self.m_lastRange = None self.startSelTimer() """* * This captures the selection when the mouse leaves the RTE, because in IE * the selection indicating the cursor position is lost once another widget * gains focus. Could be implemented for IE only. """ def captureSelection(self): try: self.getSelection() self.m_lastRange = Selection.getRange() except: GWT.log("Error capturing selection for IE", ex) # Gets run every time the selection is changed def onSelectionChange(self, sel): pass def isOnTextBorder(self, event): sender = event.getSource() twX = self.m_textW.getAbsoluteLeft() twY = self.m_textW.getAbsoluteTop() x = event.getClientX() - twX y = event.getClientY() - twY width = self.m_textW.getOffsetWidth() height = self.m_textW.getOffsetHeight() return ((sender == self.m_textW) and ((x <= 0) or (x >= width) or (y <= 0) or (y >= height))) def startSelTimer(self): self.m_selTimer.scheduleRepeating(250) def endSelTimer(self): self.m_selTimer.cancel() def getRange(self): if self.m_lastRange is None: self.getSelection() return Selection.getRange() else: return self.m_lastRange def getSelection(self): res = None try: window = self.getWindow() Selection.getSelection(window) except: print "Error getting the selection" traceback.print_exc() def getWindow(self, iFrame=None): if iFrame is None: iFrame = self.m_textW.getElement() iFrameWin = iFrame.contentWindow or iFrame.contentDocument if not iFrameWin.document: iFrameWin = iFrameWin.parentNode # FBJS version of parentNode #print "getWindow", iFrameWin, dir(iFrameWin) return iFrameWin def getDocument(self): return Selection.getDocument(self.getWindow()) def setHtml(self, text): self.m_textW.setHTML(text) self.m_lastText = text def getHtml(self): return self.m_textW.getHTML() def checkForChange(self): text = self.m_textW.getHTML() if text != self.m_lastText: nEvt = doc().createEvent("HTMLEvents") nEvt.initEvent("change", False, True) self.getElement().dispatchEvent(nEvt) self.m_lastText = text # Update edit buttons based on current cursor location def updateStatus(self): if self.m_formatter is None: return self.m_boldW.setDown(self.m_formatter.isBold()) self.m_italicW.setDown(self.m_formatter.isItalic()) self.m_underlineW.setDown(self.m_formatter.isUnderlined()) self.m_subscriptW.setDown(self.m_formatter.isSubscript()) self.m_superscriptW.setDown(self.m_formatter.isSuperscript()) self.m_strikethroughW.setDown(self.m_formatter.isStrikethrough()) def addChangeHandler(self, handler): return addDomHandler(handler, ChangeEvent.getType())
class Tooltip(PopupPanel): def __init__(self, sender, offsetX, offsetY, contents, show_delay, hide_delay, styleName, **kwargs): """ contents may be a text string or it may be a widget """ PopupPanel.__init__(self, True, **kwargs) self.show_delay = show_delay self.hide_delay = hide_delay if isinstance(contents, basestring): contents = HTML(contents) self.add(contents) left = sender.getAbsoluteLeft() + offsetX top = sender.getAbsoluteTop() + offsetY self.setPopupPosition(left, top) self.setStyleName(styleName) if tooltip_hide_timer: self.tooltip_show_timer = Timer(1, self) else: self.tooltip_show_timer = Timer(self.show_delay, self) def onShowImpl(self, popup): width = self.getOffsetWidth() heigth = self.getOffsetHeight() w_width = Window.getClientWidth() w_heigth = Window.getClientHeight() if w_width > width and w_heigth > heigth: offset_x = self.getAbsoluteLeft() offset_y = self.getAbsoluteTop() element = self.getElement() if (offset_x + width) > w_width: offset_x = w_width - width DOM.setStyleAttribute(element, "left", "%dpx" % offset_x) if (offset_y + heigth) > w_heigth: offset_y = w_heigth - heigth DOM.setStyleAttribute(element, "top", "%dpx" % offset_y) def show(self): global tooltip_hide_timer # activate fast tooltips tooltip_hide_timer = Timer(self.hide_delay, self) PopupPanel.show(self) def hide(self, autoClosed=False): self.tooltip_show_timer.cancel() PopupPanel.hide(self, autoClosed) def onTimer(self, timer): global tooltip_hide_timer # deactivate fast tooltips on last timer if timer is tooltip_hide_timer: tooltip_hide_timer = None if timer is self.tooltip_show_timer: self.show() else: self.hide()
class IntroPage: DiceInstance = 0 VarTempScore = 0 #Temporary Score Variable VarTotScore = [] #Total Score Variable CountTurn = 1 #Count to display player number in Temporary Score Board def __init__(self): self.DPanel = DockPanel(HorizontalAlignment = HasAlignment.ALIGN_CENTER, Spacing=10) # Creates the Docker Panel Instance self.VPanel = VerticalPanel() # Creates the Vertical Panel Instance self.VPanel1 = VerticalPanel() # Creates the Vertical Panel Instance self.HPanel = HorizontalPanel() # Creates a Horizontal Panel Instance self.HPanel1 = HorizontalPanel()# Creates a Horizontal Panel Instance self.image=Image()#Creates the Image instance to embed the images of dice self.DummyUrl = self.image.getUrl() self.timer = Timer(notify=self.StillImage)#Timer for display of gif animation self.timerRButton = Timer(notify=self.OneAlert)#Timer for controlling states of Roll button #whenever the output of the dice is 1 self.RollButton = Button("Roll", getattr(self, "RollButtonPressed")) #Initially Disabled self.RollButton.setEnabled(False) self.BankButton = Button("Bank", getattr(self, "BankButtonPressed")) #Initially Disabled self.BankButton.setEnabled(False) #The start button controls both the number players as well the winning score self.StartButton = Button("Start", getattr(self, "StartButtonPressed")) #Intially Enabled self.StartButton.setEnabled(True) self.PlayerNum = TextBox() #Enter the Number of Players self.WinScore = TextBox() #Enter the Target Score self.PlayerNum.setText("0") self.WinScore.setText("0") # self.OK = Button("OK", getattr(self, "okButtonPressed")) self.NameScore = FlexTable() #main score board self.NameScore.setStyleName("NameScore") self.TempBoard = FlexTable() #Temporary score board self.TempBoard.setStyleName("TempBoard") self.TxtInstructions = HTML() def StartButtonPressed(self): self.CountTurn = 1 if int(self.PlayerNum.getText()) >= 2 and int(self.PlayerNum.getText()) <= 6 and int(self.WinScore.getText()) >= 10 and int(self.WinScore.getText()) <= 100: self.DPanel.remove(self.TxtInstructions, DockPanel.CENTER) self.BankButton.setVisible(True) self.RollButton.setVisible(True) # self.image.setVisible(True) self.TempBoard.setVisible(True) self.NameScore.setVisible(True) self.image = Image( self.DummyUrl + "images/0.png") self.image.setSize("200px", "300px") self.DPanel.add(self.image, DockPanel.CENTER) RootPanel().add(self.DPanel) self.StartButton.setEnabled(False) self.PlayerNum.setEnabled(False) self.WinScore.setEnabled(False) self.RollButton.setEnabled(True) self.TempBoard.setText(1,0,"Player"+str(1)) self.TempBoard.setText(1, 1, "0") self.NameScore.getRowFormatter().addStyleName(self.CountTurn,"Rows") else: Window.alert("Please Enter Correct Parameters " ) #Command for alert window return 0 VarPlayer = ["Player" + str(i) for i in xrange(1,int(self.PlayerNum.getText())+1)] i = 0 while i < int(self.PlayerNum.getText()): self.NameScore.setText(i+1, 0, VarPlayer[i]) self.NameScore.setText(i+1, 1, "0") self.VarTotScore.append(0) #m*1 vector of zeros indicating the initial scores i += 1 def OneAlert(self): AlrtTxt = " Sorry, your turn is over" Window.alert(AlrtTxt) self.timerRButton.cancel() self.RollButton.setEnabled(True) def StillImage(self): self.DPanel.remove(self.image, DockPanel.CENTER) self.image = Image( self.DummyUrl + "images/" +str(self.DiceInstance)+".png") self.image.setSize("300px", "300px") self.DPanel.add(self.image, DockPanel.CENTER) self.DPanel.setCellHeight(self.image, "300px") self.DPanel.setCellWidth(self.image, "600px") RootPanel().add(self.DPanel) self.timer.cancel() if self.DiceInstance != 1: self.TempBoard.setText(1, 1, self.DiceInstance + int(self.TempBoard.getText(1, 1))) self.BankButton.setEnabled(True) self.RollButton.setEnabled(True) else: self.NameScore.getRowFormatter().removeStyleName(self.CountTurn,"Rows") self.RollButton.setEnabled(False) self.timerRButton.schedule(1500) self.CountTurn += 1 if self.CountTurn % int(self.PlayerNum.getText()) == 1: self.CountTurn = 1 self.TempBoard.setText(1,0,"Player"+str(self.CountTurn)) self.TempBoard.setText(1, 1, "0") self.NameScore.getRowFormatter().addStyleName(self.CountTurn,"Rows"); else: self.TempBoard.setText(1,0,"Player"+str(self.CountTurn)) self.TempBoard.setText(1, 1, "0") self.NameScore.getRowFormatter().addStyleName(self.CountTurn,"Rows"); def RollButtonPressed(self): self.DiceInstance = random.randint(1, 6) # value turned after rolling the dice self.DPanel.remove(self.image, DockPanel.CENTER) self.image = Image("http://www.animatedimages.org/data/media/710/animated-dice-image-0064.gif") self.image.setSize("100px", "200px") self.DPanel.add(self.image, DockPanel.CENTER) self.DPanel.setCellHeight(self.image, "300px") self.DPanel.setCellWidth(self.image, "600px") RootPanel().add(self.DPanel) self.BankButton.setEnabled(False) self.RollButton.setEnabled(False) self.timer.schedule(3000) def BankButtonPressed(self): self.BankButton.setEnabled(False) self.NameScore.setText(self.CountTurn, 1, int(self.NameScore.getText(self.CountTurn, 1)) + int(self.TempBoard.getText(1,1))) if int(self.NameScore.getText(self.CountTurn, 1)) >= int(self.WinScore.getText()): AlrtTxt = "Congratulation!!! Player"+ str(self.CountTurn) + " wins !!!!" Window.alert(AlrtTxt) self.DPanel.remove(self.image, DockPanel.CENTER) self.DPanel.add(self.TxtInstructions, DockPanel.CENTER) self.BankButton.setVisible(False) self.RollButton.setVisible(False) # self.image.setVisible(False) self.TempBoard.setVisible(False) self.NameScore.setVisible(False) i = int(self.PlayerNum.getText()) while i > 0: self.NameScore. removeRow(i) i -= 1 self.TempBoard.setText(1,0,"X") self.TempBoard.setText(1, 1, "0") self.StartButton.setEnabled(True) # self.OK.setEnabled(True) self.PlayerNum.setEnabled(True) self.WinScore.setEnabled(True) self.RollButton.setEnabled(False) self.BankButton.setEnabled(False) self.NameScore.getRowFormatter().removeStyleName(self.CountTurn,"Rows"); self.DPanel.remove(self.image, DockPanel.CENTER) self.image = Image( self.DummyUrl + "images/0.png") self.image.setSize("200px", "300px") self.DPanel.add(self.image, DockPanel.CENTER) self.DPanel.setCellHeight(self.image, "200px") self.DPanel.setCellWidth(self.image, "400px") RootPanel().add(self.DPanel) else: self.NameScore.getRowFormatter().removeStyleName(self.CountTurn,"Rows"); self.CountTurn += 1 if self.CountTurn % int(self.PlayerNum.getText()) == 1: self.CountTurn = 1 self.TempBoard.setText(1,0,"Player"+str(self.CountTurn)) self.TempBoard.setText(1, 1, "0") self.NameScore.getRowFormatter().addStyleName(self.CountTurn,"Rows"); else: self.TempBoard.setText(1,0,"Player"+str(self.CountTurn)) self.TempBoard.setText(1, 1, "0") self.NameScore.getRowFormatter().addStyleName(self.CountTurn,"Rows"); def OnGameLoad(self): self.NameScore.setText(0, 0, "Player ID") self.NameScore.setText(0, 1, "Score") self.NameScore.setCellSpacing(10) self.NameScore.setCellPadding(10) self.NameScore.setBorderWidth(2) self.NameScore.setVisible(False) self.TempBoard.setText(0, 0, "Player's Turn") self.TempBoard.setText(0, 1, "Temporary Score") self.TempBoard.setText(1, 0, "X") self.TempBoard.setText(1, 1, "0") self.TempBoard.setCellSpacing(10) self.TempBoard.setCellPadding(10) self.TempBoard.setBorderWidth(2) self.TempBoard.setVisible(False) #Adding StartButton to Dock panel self.DPanel.add(self.StartButton, DockPanel.EAST) self.DPanel.setCellHeight(self.StartButton, "200px") self.DPanel.setCellWidth(self.StartButton, "20px") Txt = HTML("<center><b>Enter Number of Players (between 2 & 6)</b><center>")#Adding playernumber and winscore textbox to Horizontal Panel Txt1 = HTML("<left><b>Enter Target Score (between 10 & 100)</b><left>") self.HPanel1.add(Txt) self.HPanel1.add(self.PlayerNum) self.HPanel1.add(Txt1) self.HPanel1.add(self.WinScore) self.HPanel1.add(self.StartButton) self.HPanel1.setSpacing(20) #Adding Horizontal panel containing playernumber and winscore textbox to Dock Panel self.DPanel.add(self.HPanel1, DockPanel.NORTH) self.DPanel.setCellHeight(self.HPanel1, "30px") self.DPanel.setCellWidth(self.HPanel1, "2000px") self.TxtInstructions = HTML("<b><u><center>Instructions</center></u><ul><li>Pig is game for 2 to 6 Players.</li><li>Players take turns rolling a dice as many times as they like. </li><li>If a roll is 2, 3, 4, 5 or 6, the player adds that many points to their score for the turn. </li><li>A player may choose to end their turn at any time and 'bank' their points.</li><li>If a player rolls a 1, they lose all their unbanked points and their turn is over.</li><li>The first player to score the target or more wins.</li></ul></b>") self.TxtInstructions.setStyleName("TxtInstructions") self.DPanel.add(self.TxtInstructions, DockPanel.CENTER) self.DPanel.add(self.NameScore, DockPanel.WEST) #Adding main scoreboard to Dock Panel self.DPanel.setCellHeight(self.NameScore, "300px") self.DPanel.setCellWidth(self.NameScore, "100px") self.DPanel.setSpacing(10) self.DPanel.setPadding(2) #Adding Tempboard and BankButton to Horizontal Panel self.HPanel.add(self.TempBoard) #Adding BankButton and RollButton to vertical panel self.VPanel.add(self.RollButton) self.RollButton.setVisible(False) self.VPanel.add(self.BankButton) self.BankButton.setVisible(False) self.VPanel.setSpacing(10) #Adding Vertical panel containing BankButton and RollButton to Horizontal Panel self.HPanel.add(self.VPanel) self.HPanel.setSpacing(40) #Adding Horizontal panel containing Tempboard and vertical panel containing BankButton and RollButton to Dock Panel self.DPanel.add(self.HPanel, DockPanel.SOUTH) self.DPanel.setCellHeight(self.HPanel, "20px") self.DPanel.setCellWidth(self.HPanel, "2000px") RootPanel().add(self.DPanel)
class 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)))