def onClick(self, sender=None): """ Called when the user finishes clicking on this button. The default behavior is to fire the click event to listeners. Subclasses that override onClickStart() should override this method to restore the normal widget display. """ # Allow the click we're about to synthesize to pass through to the # superclass and containing elements. Element.dispatchEvent() is # synchronous, so we simply set and clear the flag within this method. self.allowClick = True # Mouse coordinates are not always available (e.g., when the click is # caused by a keyboard event). evt = None # we NEED to initialize evt, to be in the same namespace # as the evt *inside* of JS block # We disallow setting the button here, because IE doesn't provide the # button property for click events. # there is a good explanation about all the arguments of initMouseEvent # at: https://developer.mozilla.org/En/DOM:event.initMouseEvent DOM.buttonClick(self.getElement()) self.allowClick = False
def insertRow(self, beforeRow): if beforeRow != self.getRowCount(): self.checkRowBounds(beforeRow) tr = DOM.createTR() DOM.insertChild(self.bodyElem, tr, beforeRow) return beforeRow
def ensureContentPanel(self): if self.contentPanel is None: DOM.setInnerHTML(self.contentElem, "") self.contentPanel = TreeContentPanel(self.contentElem) self.contentPanel.setTreeItem(self) if self.getTree() is not None: self.tree.adopt(self.contentPanel)
def setHTML(self, html): """Set the face's contents as html.""" self.face = DOM.createDiv() UIObject.setStyleName(self.button, self.face, self.STYLENAME_HTML_FACE, True) DOM.setInnerHTML(self.face, html) self.button.updateButtonFace()
def onBrowserEvent(self, event): etype = DOM.eventGetType(event) if etype in MOUSE_EVENTS: if self._mousePreventDefault: DOM.eventPreventDefault(event) return fireMouseEvent(self._mouseListeners, self, event) return False
def setWidget(self, index, w): """ Sets one of the contained widgets. @param index the index, only 0 and 1 are valid @param w the widget """ oldWidget = self.widgets[index] if oldWidget == w: return if w is not None: w.removeFromParent() # Remove the old child. if oldWidget is not None: # Orphan old. self.disown(oldWidget) # Physical detach old. #DOM.removeChild(self.elements[index], oldWidget.getElement()) # Logical detach old / attach new. self.widgets[index] = w if w is not None: # Physical attach new. DOM.appendChild(self.elements[index], w.getElement()) # Adopt new. self.adopt(w, None)
def setWidth(self, width): self.fontsize = math.floor(width / self.cols) AbsolutePanel.setWidth(self, "%dpx" % (self.cols*self.fontsize)) ratio = self.fontsize / self.fontheight DOM.setStyleAttribute(self.getElement(), 'fontSizeAdjust', str(ratio))
def __init__(self, **kwargs): """ Creates an empty vertical split panel. """ if not kwargs.has_key('StyleName'): kwargs['StyleName']="gwt-VerticalSplitPanel" if kwargs.has_key('Element'): element = kwargs.pop('Element') else: element = DOM.createDiv() SplitPanel.__init__(self, element, DOM.createDiv(), self.preventBoxStyles(DOM.createDiv()), self.preventBoxStyles(DOM.createDiv()), **kwargs) self.container = self.preventBoxStyles(DOM.createDiv()) self.buildDOM() self.impl = ImplVerticalSplitPanel(self) self.setSplitPosition("50%") # Captures the height of the top container when drag resizing starts. self.initialTopHeight = 0 # Captures the offset of a user's mouse pointer during drag resizing. self.initialThumbPos = 0 self.lastSplitPosition = ""
def setSplitPosition(self, px): splitElem = self.panel.getSplitElement() rootElemHeight = DOM.getOffsetHeight(self.panel.container) splitElemHeight = DOM.getOffsetHeight(splitElem) # layout not settled, set height to what it _should_ be... yuk. if splitElemHeight == 0: splitElemHeight = 7 if rootElemHeight < splitElemHeight: return newBottomHeight = rootElemHeight - px - splitElemHeight if px < 0: px = 0 newBottomHeight = rootElemHeight - splitElemHeight elif newBottomHeight < 0: px = rootElemHeight - splitElemHeight newBottomHeight = 0 self.updateElements(self.panel.getWidgetElement(0), splitElem, self.panel.getWidgetElement(1), px, px + splitElemHeight, newBottomHeight)
def onImagesLoaded(self, imagesHandles): self.clock = imagesHandles[0] el = self.clock.getElement() self.width = DOM.getIntAttribute(el, "width") self.height = DOM.getIntAttribute(el, "height") self.setWidth("%d" % self.width) self.setHeight("%d" % self.height)
def onreadystatechange(): if xhtoj.readyState == 4: jsnode = 0 if xhtoj.status == 200: txt = xhtoj.responseText jsnode = None if idname: jsnode = DOM.getElementById(idname) if jsnode is None: jsnode = DOM.createElement('script') #tst = DOM.createElement('html') #tst.innerHTML = str activate_javascript(txt) if not on_load_fn is None: wnd().alert(on_load_fn) # eval(on_load_fn) test_fn() return 1 else: jsnode = DOM.getElementById(idname) if not jsnode is None: jsnode.innerHTML = xhtoj.status
def setWidth(self, width): """Set the width of the element associated with this UIObject. The value should be given as a CSS value, such as 100px, 30%, or 50pi """ if width is None: width = "" DOM.setStyleAttribute(self.element, "width", str(width))
def onDrop(self, event): dt = event.dataTransfer item = dt.getData("Text") data = json.decode(item) if 'name' in data and 'age' in data: age = data['age'] name = data['name'] self.removeStyleName('dragover') if self.age_is_ok(age): self.addStudent(name, age) dt.dropEffect = 'copy' self.addStyleName('flash') def removeFlash(timer): self.removeStyleName('flash') Timer(250, notify=removeFlash) else: dt.dropEffect = 'none' self.addMessage('student could not be added') # setting dropEffect to 'none' should be sufficient to notify # that the drop failed, but # we need to cheat a bit for now... # this is the only reason for parent id in data item_parent_id = data['parent'] item_parent = self.parent.containerFromId(item_parent_id) item_parent.addStyleName('drop_fail') # prevent default allows onDragEnd to see the dropEffect we set here DOM.eventPreventDefault(event)
def onDrop(self, event): dt = event.dataTransfer types = getTypes(event) self.addMessage("drop types received: " + ", ".join(types)) parent = self.getParent() parent.clearContent() self.addMessage('dt: ' + str(dt)) types.sort() for ctype in types: data = dt.getData(ctype) if ctype == 'Files': file_names = [] files = dt.files # files is a FileList # http://help.dottoro.com/ljuelxgf.php for idx in range(files.length): item = files.item(idx) try: name = item.name except: name = item.fileName file_names.append(name) data = '<br>'.join(file_names) parent.addContent(ctype, data) DOM.eventPreventDefault(event) # cancel bubble so first file is not opened in browser. DOM.eventCancelBubble(event, True)
def onDrop(self, event): dt = event.dataTransfer text = dt.getData('text') package = json.decode(text) x = DOM.eventGetClientX(event) y = DOM.eventGetClientY(event) scrollY = Window.getScrollTop() scrollX = Window.getScrollLeft() offsetX = int(package['offsetX']) offsetY = int(package['offsetY']) at = self.getAbsoluteTop() al = self.getAbsoluteLeft() posX, posY = x - (al - scrollX), y - (at - scrollY) w = DragWidget6(package['text']) self.add(w) makeDraggable(w) # firefox seems to be off-by-one in x. # firefox-specific code? #w.setStyleAttribute('left', posX - offsetX -1) w.setStyleAttribute('left', posX - offsetX) w.setStyleAttribute('top', posY - offsetY) w.removeStyleName('invisible') self.addMessage( "top:%s, left:%s, cy:%s cx:%s, sy:%s sx:%s dropy:%s dropx:%s" % ( at, al, y, x, scrollY, scrollX, posY, posX)) DOM.eventPreventDefault(event)
def addMessage(self, text): d = datetime.now().strftime("%x %X") li = DOM.createElement('li') DOM.setInnerHTML(li, '<dt class="time">%s</dt><dd class="txt">%s</dd>' % ( d, text)) DOM.insertChild(self.element, li, 0)
def onDragStart(self, event): dt = event.dataTransfer target = DOM.eventGetTarget(event) target = Widget(Element=target) id = target.getID() dt.setData("Text", "Dropped %s" % target.getID()) dt.effectAllowed = 'copy' if id == 'imgdrag1': parent = self.getParent() while not hasattr(parent, 'h2'): parent = parent.getParent() dt.setDragImage(parent.h2.getElement(), 10, 10) elif id == 'imgdrag2': dt.setDragImage(doc().getElementById('logo'), 10, 10) elif id == 'imgdrag3': # OK, it's a bit of a cheat, but the following works on current # Opera, IE, Firefox, Safari, Chrome. ctx = GWTCanvas(50, 50) self.makeCanvasImg(ctx) try: img = DOM.createImg() DOM.setAttribute(img, 'src', ctx.canvas.toDataURL()) dt.setDragImage(img, 25, 25) except: dt.setDragImage(ctx.canvas, 25, 25)
def onElementInitialized(self): # Issue 1897: This method is called after a timeout, during which time the # element might by detached. if not self.initializing: return print "onElementInit", DOM.getInnerHTML(self.beforeInitPlaceholder) self.initializing = False RichTextAreaImpl.onElementInitialized(self) # clone styles from main document if self.css_styling: elem = self.elem; _doc = elem.contentWindow.document fragment = _doc.createDocumentFragment() nl = doc().getElementsByTagName("style") for i in range(nl.length): n = nl.item(i) fragment.appendChild(n.cloneNode(True)) _doc.getElementsByTagName("head").item(0).appendChild(fragment) # When the iframe is ready, ensure cached content is set. if self.beforeInitPlaceholder is not None: self.setHTMLImpl(DOM.getInnerHTML(self.beforeInitPlaceholder)) self.beforeInitPlaceholder = None if self.isPendingFocus: self.isPendingFocus = False self.setFocus(True)
def set_main_frame(frame): global main_frame main_frame = frame from pyjamas import DOM # ok - now the main frame has been set we can initialise the # signal handlers etc. DOM.init()
def onBrowserEvent(self, event): # farm out the event to convenience handlers. # detect existence by checking for the listener lists of each # type of handler. there's probably a better way to do this... if hasattr(self, "_clickListeners"): ClickHandler.onBrowserEvent(self, event) if hasattr(self, "_keyboardListeners"): KeyboardHandler.onBrowserEvent(self, event) if hasattr(self, "_mouseListeners"): MouseHandler.onBrowserEvent(self, event) if hasattr(self, "_mouseWheelListeners"): MouseWheelHandler.onBrowserEvent(self, event) if hasattr(self, "_focusListeners"): FocusHandler.onBrowserEvent(self, event) if hasattr(self, "_dragListeners"): DragHandler.onBrowserEvent(self, event) if hasattr(self, "_dropListeners"): DropHandler.onBrowserEvent(self, event) if self.contextMenu is None: return True type = DOM.eventGetType(event) if type == "contextmenu": DOM.eventCancelBubble(event, True) DOM.eventPreventDefault(event) self.contextMenu.onContextMenu(self) return False return True
def setHeight(self, height): """Set the height of the element associated with this UIObject. The value should be given as a CSS value, such as 100px, 30%, or 50pi """ if height is None: height = "" DOM.setStyleAttribute(self.element, "height", str(height))
def validarParametrosMatriz(): lm1 = DOM.getElementById("lm1") lm1 = lm1.value cm1 = DOM.getElementById("cm1") cm1 = cm1.value lm2 = DOM.getElementById("lm2") lm2 = lm2.value cm2 = DOM.getElementById("cm2") cm2 = cm2.value if not lm1 or not lm2: Window.alert("Informe o numero de linhas da matriz M1 e M2.") return False if lm1 != lm2: Window.alert("A quantidade de linhas da matriz M1 deve ser igual a da matriz M2 para operação de soma.") return False if lm1 > "5" or lm2 > "5" or len(lm1) != 1 or len(lm2) != 1: Window.alert("A quantidade de linhas da matriz M1 e da matriz M2, deve ser menor ou igual a 5.") return False if not cm1 or not cm2: Window.alert("Informe o numero de colunas da matriz M1 e M2.") return False if cm1 != cm2: Window.alert("A quantidade de colunas da matriz M1 deve ser igual a da matriz M2 para operação de soma.") return False if cm1 > "7" or cm2 > "7" or len(cm1) != 1 or len(cm2) != 1: Window.alert("A quantidade de colunas da matriz M1 e da matriz M2, deve ser menor ou igual a 7.") return False return True
def findTextPoint(node, offset): """ If the found range is not on a text node, this finds the cooresponding text node to where the selection is. If it is on a text node, just directly creates the endpoint from it. @param node node returned as an endpoint of a range @param offset offset returned to the endpoint of a range @return A range end point with a proper (or None) text node """ if DOM.getNodeType(node) == DOM.TEXT_NODE: res = RangeEndPoint(node, offset) else: # search backwards unless this is after the last node dirn = offset >= DOM.getChildCount(node) child = (DOM.getChildCount(node) == 0) and node or DOM.getChild(node, dirn and (offset - 1) or offset) # Get the previous/next text node text = RangeUtil.getAdjacentTextElement(child, dirn) if text is None: # If we didn't find a text node in the preferred direction, # try the other direction dirn = not dirn text = RangeUtil.getAdjacentTextElement(child, dirn) res = RangeEndPoint(text, dirn) return res
def buildDOM(self): leftDiv = self.getWidgetElement(0) rightDiv = self.getWidgetElement(1) splitDiv = self.getSplitElement() DOM.appendChild(self.getElement(), self.container) DOM.appendChild(self.container, leftDiv) DOM.appendChild(self.container, splitDiv) DOM.appendChild(self.container, rightDiv) # Sadly, this is the only way I've found to get vertical # centering in this case. The usually CSS hacks (display: # table-cell, vertical-align: middle) don't work in an # absolute positioned DIV. thumb_html = '<img src="splitPanelThumb.png" />' DOM.setInnerHTML(splitDiv, "<table class='hsplitter' height='100%' cellpadding='0' " + "cellspacing='0'><tr><td align='center' valign='middle'>" + thumb_html + "</td></tr></table>") self.addScrolling(leftDiv) self.addScrolling(rightDiv)
def updateState(self): if self.disclosurePanel.getOpen(): DOM.setAttribute(self.imgElem, "src", self.imageBase + "disclosurePanelOpen.png") else: DOM.setAttribute(self.imgElem, "src", self.imageBase + "disclosurePanelClosed.png")
def __init__(self, **kwargs): """ Creates an empty horizontal split panel. """ if not kwargs.has_key('StyleName'): kwargs['StyleName']="gwt-HorizontalSplitPanel" if kwargs.has_key('Element'): element = kwargs.pop('Element') else: element = DOM.createDiv() SplitPanel.__init__(self, element, DOM.createDiv(), self.preventBoxStyles(DOM.createDiv()), self.preventBoxStyles(DOM.createDiv()), **kwargs) self.container = self.preventBoxStyles(DOM.createDiv()) self.buildDOM() self.impl = ImplHorizontalSplitPanel(self) # By default the panel will fill its parent vertically and horizontally. # The horizontal case is covered by the fact that the top level div is # block display. self.setHeight("100%") self.lastSplitPosition = "50%" self.initialLeftWidth = 0 self.initialThumbPos = 0
def __init__(self, headerText, isOpen=False, **kwargs): self.handlers = [] self.content = None # this is awkward: VerticalPanel is the composite, # so we get the element here, and pass it in to VerticalPanel. element = None if kwargs.has_key('Element'): element = kwargs.pop('Element') self.mainPanel = VerticalPanel(Element=element) self.header = ClickableHeader(self) self.contentWrapper = SimplePanel() self.mainPanel.add(self.header) self.mainPanel.add(self.contentWrapper) DOM.setStyleAttribute(self.contentWrapper.getElement(), "padding", "0px"); DOM.setStyleAttribute(self.contentWrapper.getElement(), "overflow", "hidden"); self.isOpen = isOpen self.headerObj = DefaultHeader(headerText, self) self.setHeader(self.headerObj) if not kwargs.has_key('StyleName'): kwargs['StyleName']="gwt-DisclosurePanel" Composite.__init__(self, self.mainPanel, **kwargs) self.setContentDisplay()
def setStyleName(element, style, add): oldStyle = DOM.getAttribute(element, "className") if oldStyle is None: oldStyle = "" idx = oldStyle.find(style) # Calculate matching index lastPos = len(oldStyle) while idx != -1: if idx == 0 or (oldStyle[idx - 1] == " "): last = idx + len(style) if (last == lastPos) or ((last < lastPos) and (oldStyle[last] == " ")): break idx = oldStyle.find(style, idx + 1) if add: if idx == -1: DOM.setAttribute(element, "className", oldStyle + " " + style) else: if idx != -1: if idx == 0: begin = '' else: begin = oldStyle[:idx-1] end = oldStyle[idx + len(style):] DOM.setAttribute(element, "className", begin + end)
def moveControl(self, mouse_x, mouse_y, first_move=False): handle_height = DOM.getIntAttribute(self.handle, "offsetHeight") widget_height = self.getOffsetHeight() height_range = widget_height - 10 # handle height is hard-coded relative_y = mouse_y - (handle_height / 2) if relative_y < 0: relative_y = 0 if relative_y >= height_range: relative_y = height_range # turn round (bottom to top) for x relative_y = height_range - relative_y handle_width = DOM.getIntAttribute(self.handle, "offsetWidth") widget_width = self.getOffsetWidth() length_range = widget_width - 10 # handle width is hard-coded relative_x = mouse_x - (handle_width / 2) if relative_x < 0: relative_x = 0 if relative_x >= length_range: relative_x = length_range val_diff_x = self.max_value_x - self.min_value_x new_value_x = ((val_diff_x * relative_x) / length_range) + \ self.min_value_x val_diff_y = self.max_value_y - self.min_value_y new_value_y = ((val_diff_y * relative_y) / height_range) + \ self.min_value_y new_value = [new_value_x, new_value_y] new_value = self.processValue(new_value) self.setControlPos(new_value) self.setValue(new_value)
def fillText(self, text, startX, startY, maxWidth=None): """ Places text, at the specified start coords, according to the current fillstyle. @param startX x coord of the top left corner in the destination space @param startY y coord of the top left corner in the destination space @param maxWidth maximum width of text """ # create an SVG text element text_elem = self._createElementSVG("text") # integerize the coordinates xy = self._integerize(startX, startY) # add the size and position DOM.setElemAttribute(text_elem, "x", str(xy[0])) DOM.setElemAttribute(text_elem, "y", str(xy[1])) if maxWidth is not None: DOM.setElemAttribute(text_elem, "textLength", str(maxWidth)) # add the fill styles style = "font:"+self.ctx["font"]+";fill:"+str(self.ctx["fill"]) DOM.setElemAttribute(text_elem, "style", style) # now add the text DOM.setInnerText(text_elem, text) # add the rect element to the canvas self._addElementSVG(text_elem)
def setAttr(self, row, column, attrName, value): elem = self.getElement(row, column) DOM.setAttribute(elem, attrName, value)
def getStyleName(self, row, column): return DOM.getAttribute(self.getElement(row, column), "className")
def ensureElement(self, row, column): self.outer.prepareCell(row, column) return DOM.getChild(self.outer.rowFormatter.ensureElement(row), column)
def getElement(self, row, column): self.outer.checkCellBounds(row, column) return DOM.getChild(self.outer.rowFormatter.getRow(self.outer.bodyElem, row), column)
def setHref(self, href): DOM.setAttribute(self.getElement(), "href", href)
def getAttr(self, row, column, attr): elem = self.getElement(row, column) return DOM.getAttribute(elem, attr)
def setShape(self, shape): DOM.setAttribute(self.getElement(), "shape", shape)
def setWordWrap(self, row, column, wrap): self.outer.prepareCell(row, column) wrap = (not wrap) and "nowrap" or "" DOM.setStyleAttribute(self.getElement(row, column), "whiteSpace", wrap)
def changeTexts(self): if self.text != '': DOM.setInnerHTML(self.title.getElement(), _(self.text))
def setCoords(self, coords): DOM.setAttribute(self.getElement(), "coords", coords)
def __init__(self, text=None, wordWrap=True, **kwargs): kwargs['StyleName'] = kwargs.get('StyleName', "gwt-InlineLabel") kwargs['Element'] = DOM.createSpan() Label.__init__(self, text, wordWrap, **kwargs)
def setName(self, name): DOM.setAttribute(self.getElement(), "name", name)
def onBrowserEvent(self, event): type = DOM.eventGetType(event) if type in MOUSE_EVENTS: if self._mousePreventDefault: DOM.eventPreventDefault(event) fireMouseEvent(self._mouseListeners, self, event)
def onLostFocus(self, sender): self.removeStyleName("gwt-VerticalSlider-focussed") self.dragging = False DOM.releaseCapture(self.getElement())