def isEnabled(self): return not DOM.getBooleanAttribute(self.inputElem, "disabled") def setEnabled(self, enabled): DOM.setBooleanAttribute(self.inputElem, "disabled", not enabled) def setFocus(self, focused): if focused: Focus.focus(self.inputElem) else: Focus.blur(self.inputElem) def setHTML(self, html): DOM.setInnerHTML(self.labelElem, html) def setName(self, name): DOM.setAttribute(self.inputElem, "name", name) def setTabIndex(self, index): Focus.setTabIndex(self.inputElem, index) def setText(self, text): DOM.setInnerText(self.labelElem, text) def onDetach(self): self.setChecked(self.isChecked()) ButtonBase.onDetach(self) Factory.registerClass('pyjamas.ui.CheckBox', CheckBox)
return True DOM.setInnerHTML(td, "") return False def prepareCell(self, row, column): pass def prepareRow(self, row): pass def removeCell(self, row, column): self.checkCellBounds(row, column) td = self.cleanCell(row, column) tr = self.rowFormatter.getRow(self.bodyElem, row) DOM.removeChild(tr, td) def removeRow(self, row): for column in range(self.getCellCount(row)): self.cleanCell(row, column) DOM.removeChild(self.bodyElem, self.rowFormatter.getRow(self.bodyElem, row)) def setCellFormatter(self, cellFormatter): self.cellFormatter = cellFormatter def setRowFormatter(self, rowFormatter): self.rowFormatter = rowFormatter Factory.registerClass('pyjamas.ui.HTMLTable', 'HTMLTable', HTMLTable)
relative_x = 0 if relative_x >= length_range: relative_x = length_range val_diff = self.max_value - self.min_value new_value = ((val_diff * relative_x) / length_range) + self.min_value new_value = self.processValue(new_value) self.setControlPos(new_value) self.setValue(new_value) def setControlPos(self, value): widget_width = self.getOffsetWidth() length_range = widget_width - 10 # handle width is hard-coded val_diff = self.max_value - self.min_value relative_x = length_range * (value - self.min_value) / val_diff # limit the position to be in the widget! if relative_x < 0: relative_x = 0 if relative_x >= length_range: relative_x = length_range # move the handle DOM.setStyleAttribute(self.handle, "left", "%dpx" % relative_x) DOM.setStyleAttribute(self.handle, "position", "absolute") Factory.registerClass('pyjamas.ui.HorizontalSlider', 'HorizontalSlider', HorizontalSlider)
DOM.setAttribute(self.imgElem, "src", src) class RootTreeItem(TreeItem): def addItem(self, item): self.insertItem(item) def insertItem(self, item, index=None): if (item.getParentItem() is not None) or (item.getTree() is not None): item.remove() item.setTree(self.getTree()) item.setParentItem(None) if index is None: self.children.append(item) else: self.children.insert(index, item) DOM.setIntStyleAttribute(item.getElement(), "marginLeft", 0) def removeItem(self, item): if item not in self.children: return item.setTree(None) item.setParentItem(None) self.children.remove(item) Factory.registerClass('pyjamas.ui.TreeItem', 'TreeItem', TreeItem)
def addLoadListener(self, listener): self.loadListeners.append(listener) def removeLoadListener(self, listener): self.loadListeners.remove(listener) def getUrl(self): return DOM.getAttribute(self.getElement(), "src") def onBrowserEvent(self, event): Widget.onBrowserEvent(self, event) type = DOM.eventGetType(event) if type == "load": for listener in self.loadListeners: listener.onImageLoad(self) elif type == "error": for listener in self.loadListeners: listener.onImageError(self) def prefetch(self, url): img = DOM.createImg() DOM.setElemAttribute(img, "src", url) prefetchImages[url] = img def setUrl(self, url): DOM.setElemAttribute(self.getElement(), "src", url) Factory.registerClass('pyjamas.ui.Image', 'Image', Image)
from pyjamas import DOM from pyjamas import Factory from PopupPanel import PopupPanel class ContextMenuPopupPanel(PopupPanel): def __init__(self, item, **kwargs): self.item = item kwargs['Widget'] = item PopupPanel.__init__(self, True, **kwargs) def showAt(self, x, y): self.setPopupPosition(x, y) self.item.onShow() self.show() def onEventPreview(self, event): type = DOM.eventGetType(event) if type == "click": target = DOM.eventGetTarget(event) parentMenuElement = self.item.getElement() if DOM.isOrHasChild(parentMenuElement, target): if self.item.onBrowserEvent(event): self.hide() return True return PopupPanel.onEventPreview(self, event) Factory.registerClass('pyjamas.ui.ContextMenuPopupPanel', ContextMenuPopupPanel)
def onMinimize(self, sender): if self._runDialogListener("onMinimize") is False: return widget = self.child if widget is not None: if widget.isVisible(): widget.setVisible(False) self.setHeight("") self.setWidth("") if self._maximized: self._minimized = self._maximized self._toggleMaximize() else: self._minimized = None else: if self._minimized is not None: self._toggleMaximize() widget.setVisible(True) def onClose(self, sender): if self._runDialogListener("onClose") is False: return self.hide() def onMouseUp(self, sender, x, y): if self.dragStartX != x or self.dragStartY != y: self.onActivate() DialogBox.endDragging(self) Factory.registerClass('pyjamas.ui.DialogWindow', 'DialogWindow', DialogWindow)
kwargs['Value'] = value Widget.__init__(self, **kwargs) def getDefaultValue(self): return DOM.getAttribute(self.getElement(), "defaultValue") def getName(self): return DOM.getAttribute(self.getElement(), "name") def getValue(self): return DOM.getAttribute(self.getElement(), "value") def setDefaultValue(self, defaultValue): DOM.setAttribute(self.getElement(), "defaultValue", defaultValue) def setName(self, name): if name is None: #throw new NullPointerException("Name cannot be null"); console.error("Name cannot be null") elif len(name) == 0: #throw new IllegalArgumentException("Name cannot be an empty string."); console.error("Name cannot be an empty string.") DOM.setAttribute(self.getElement(), "name", name) def setValue(self, value): DOM.setAttribute(self.getElement(), "value", value) Factory.registerClass('pyjamas.ui.Hidden', Hidden)
self.selectedTab = None return True self.selectedTab = self.panel.getWidget(index + 1) self.setSelectionStyle(self.selectedTab, True) for listener in self.tabListeners: listener.onTabSelected(self, index) return True def checkTabIndex(self, index): if (index < -1) or (index >= self.getTabCount()): #throw new IndexOutOfBoundsException(); pass def setSelectionStyle(self, item, selected): if item is not None: if selected: item.addStyleName("gwt-TabBarItem-selected") self.setStyleName(DOM.getParent(item.getElement()), "gwt-TabBarItem-wrapper-selected", True) else: item.removeStyleName("gwt-TabBarItem-selected") self.setStyleName(DOM.getParent(item.getElement()), "gwt-TabBarItem-wrapper-selected", False) Factory.registerClass('pyjamas.ui.TabBar', 'TabBar', TabBar)
widget_width = self.getOffsetWidth() length_range = widget_width - 10 # handle width is hard-coded val_diff_x = self.max_value_x - self.min_value_x relative_x = length_range * (value_x - self.min_value_x) / val_diff_x # limit the position to be in the widget! if relative_x < 0: relative_x = 0 if relative_x >= length_range: relative_x = length_range widget_height = self.getOffsetHeight() height_range = widget_height - 10 # handle height is hard-coded val_diff_y = self.max_value_y - self.min_value_y relative_y = height_range * (value_y - self.min_value_y) / val_diff_y # limit the position to be in the widget! if relative_y < 0: relative_y = 0 if relative_y >= height_range: relative_y = height_range relative_y = height_range - relative_y # turn round (bottom to top) # move the handle DOM.setStyleAttribute(self.handle, "top", "%dpx" % relative_y) DOM.setStyleAttribute(self.handle, "left", "%dpx" % relative_x) DOM.setStyleAttribute(self.handle, "position", "absolute") Factory.registerClass('pyjamas.ui.AreaSlider', 'AreaSlider', AreaSlider)
self.getScrollPosition()) def removeScrollListener(self, listener): self.scrollListeners.remove(listener) def setAlwaysShowScrollBars(self, alwaysShow): if alwaysShow: style = "scroll" else: style = "auto" DOM.setStyleAttribute(self.getElement(), "overflow", style) def setScrollPosition(self, position): DOM.setIntAttribute(self.getElement(), "scrollTop", position) def setHorizontalScrollPosition(self, position): DOM.setIntAttribute(self.getElement(), "scrollLeft", position) def ensureVisibleImpl(self, scroll, e): if not e: return item = e realOffset = 0 while item and (item != scroll): realOffset += item.offsetTop item = item.offsetParent scroll.scrollTop = realOffset - scroll.offsetHeight / 2 Factory.registerClass('pyjamas.ui.ScrollPanel', ScrollPanel)
self.addClickListener(self) self.addFocusListener(self) self.addKeyboardListener(self) def onFocus(self, sender): self.addStyleName("gwt-InputControl-focussed") def onLostFocus(self, sender): self.removeStyleName("gwt-InputControl-focussed") def setControlPos(self, value): self.input.setText(value) def onKeyPress(self, sender, keycode, modifiers): if keycode == KeyboardListener.KEY_ENTER: DOM.eventPreventDefault(DOM.eventGetCurrentEvent()) txt = self.input.getText() if not txt: return new_value = float(txt) new_value = self.processValue(new_value) self.setControlPos(new_value) self.setValue(new_value) else: Control.onKeyPress(self, sender, keycode, modifiers) Factory.registerClass('pyjamas.ui.InputControl', 'InputControl', InputControl)
if int(self.currentMonth) == 12: self.currentMonth = 1 self.currentYear = int(self.currentYear) + 1 else: self.currentMonth = int(self.currentMonth) + 1 self.draw(self.currentMonth, self.currentYear) def drawPreviousYear(self): self.currentYear = int(self.currentYear) - 1 self.draw(self.currentMonth, self.currentYear) def drawNextYear(self): self.currentYear = int(self.currentYear) + 1 self.draw(self.currentMonth, self.currentYear) Factory.registerClass('pyjamas.ui.Calendar', 'Calendar', Calendar) class DateField(Composite, DateSelectedHandler): img_base = None icon_img = None icon_style = "calendar-img" today_text = "Today" today_style = "calendar-today-link" def __init__(self, format='%d-%m-%Y'): DateSelectedHandler.__init__(self) if self.img_base is None: self.img_base = pygwt.getImageBaseURL(True)
else: element = DOM.createElement("map") self.setElement(element) ComplexPanel.__init__(self, **kwargs) def add(self, widget): self.insert(widget, self.getWidgetCount()) def insert(self, widget, beforeIndex): widget.removeFromParent() ComplexPanel.insert(self, widget, self.getElement(), beforeIndex) def setName(self, name): DOM.setAttribute(self.getElement(), "name", name) Factory.registerClass('pyjamas.ui.ImageMap', ImageMap) class MapArea(Widget, MouseHandler, ClickHandler): """ An area inside an imagemap """ def __init__(self, Shape, Coords, **kwargs): if not kwargs.has_key('Href'): kwargs['Href'] = "" kwargs['Shape'] = Shape kwargs['Coords'] = Coords if kwargs.has_key('Element'): element = kwargs.pop('Element') else: element = DOM.createElement("area") self.setElement(element) Widget.__init__(self, **kwargs)
row = rows[northRow] DOM.insertChild(row.tr, td, row.center) row.center += 1 self.appendAndMaybeAdopt(td, child.getElement(), beingAdded) DOM.setIntAttribute(td, "rowSpan", southRow - northRow + 1) westCol += 1 elif layout.direction == self.EAST: row = rows[northRow] DOM.insertChild(row.tr, td, row.center) self.appendAndMaybeAdopt(td, child.getElement(), beingAdded) DOM.setIntAttribute(td, "rowSpan", southRow - northRow + 1) eastCol -= 1 elif layout.direction == self.CENTER: centerTd = td if self.center is not None: row = rows[northRow] DOM.insertChild(row.tr, centerTd, row.center) self.appendAndMaybeAdopt(centerTd, self.center.getElement(), beingAdded) def appendAndMaybeAdopt(self, parent, child, beingAdded): if beingAdded is not None: if DOM.compare(child, beingAdded.getElement()): CellPanel.add(self, beingAdded, parent) return DOM.appendChild(parent, child) Factory.registerClass('pyjamas.ui.DockPanel', 'DockPanel', DockPanel)
if text: kwargs['Text'] = text self.setElement(kwargs.pop('Element', None) or DOM.createDiv()) self.horzAlign = "" Widget.__init__(self, **kwargs) MouseHandler.__init__(self) ClickHandler.__init__(self) @classmethod def _getProps(self): return Widget._getProps() + InnerText._getProps() + self._props def getHorizontalAlignment(self): return self.horzAlign def getWordWrap(self): ws = DOM.getStyleAttribute(self.getElement(), "whiteSpace") return ws != "nowrap" def setHorizontalAlignment(self, align): self.horzAlign = align DOM.setStyleAttribute(self.getElement(), "textAlign", align) def setWordWrap(self, wrap): style = wrap and "normal" or "nowrap" DOM.setStyleAttribute(self.getElement(), "whiteSpace", style) Factory.registerClass('pyjamas.ui.Label', 'Label', Label)
relative_y = height_range relative_y = height_range - relative_y # turn round (bottom to top) val_diff = self.max_value - self.min_value new_value = ((val_diff * relative_y) / height_range) + self.min_value new_value = self.processValue(new_value) self.setControlPos(new_value) self.setValue(new_value) def setControlPos(self, value): widget_height = self.getOffsetHeight() height_range = widget_height - 10 # handle height is hard-coded val_diff = self.max_value - self.min_value relative_y = height_range * (value - self.min_value) / val_diff # limit the position to be in the widget! if relative_y < 0: relative_y = 0 if relative_y >= height_range: relative_y = height_range relative_y = height_range - relative_y # turn round (bottom to top) # move the handle DOM.setStyleAttribute(self.handle, "top", "%dpx" % relative_y) DOM.setStyleAttribute(self.handle, "position", "absolute") Factory.registerClass('pyjamas.ui.VerticalSlider', 'VerticalSlider', VerticalSlider)
self.tableRow = DOM.createTR() DOM.appendChild(self.getBody(), self.tableRow) def insert(self, widget, beforeIndex): widget.removeFromParent() td = DOM.createTD() DOM.insertChild(self.tableRow, td, beforeIndex) CellPanel.insert(self, widget, td, beforeIndex) self.setCellHorizontalAlignment(widget, self.horzAlign) self.setCellVerticalAlignment(widget, self.vertAlign) def remove(self, widget): if isinstance(widget, int): widget = self.getWidget(widget) if widget.getParent() != self: return False td = DOM.getParent(widget.getElement()) DOM.removeChild(self.tableRow, td) CellPanel.remove(self, widget) return True Factory.registerClass('pyjamas.ui.HorizontalPanel', 'HorizontalPanel', HorizontalPanel)
class ToggleButton(CustomButton): """ A ToggleButton is a stylish stateful button which allows the user to toggle between UP and DOWN states. CSS: .gwt-ToggleButton- up/down/up-hovering/down-hovering/up-disabled/down-disabled {.html-face} """ STYLENAME_DEFAULT = "gwt-ToggleButton" def __init__(self, upImageText=None, downImageText=None, handler=None, **kwargs): """ Constructor for ToggleButton. """ kwargs['StyleName'] = kwargs.get('StyleName', self.STYLENAME_DEFAULT) CustomButton.__init__(self, upImageText, downImageText, handler, **kwargs) def onClick(self, sender=None): self.toggleDown() CustomButton.onClick(self) Factory.registerClass('pyjamas.ui.ToggleButton', 'ToggleButton', ToggleButton)
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pyjamas import DOM from pyjamas import Factory from FocusWidget import FocusWidget class ButtonBase(FocusWidget): def __init__(self, element, **kwargs): FocusWidget.__init__(self, element, **kwargs) def getHTML(self): return DOM.getInnerHTML(self.getElement()) def getText(self): return DOM.getInnerText(self.getElement()) def setHTML(self, html): DOM.setInnerHTML(self.getElement(), html) def setText(self, text): DOM.setInnerText(self.getElement(), text) Factory.registerClass('pyjamas.ui.ButtonBase', ButtonBase)
def getCellElement(self, row, cell): """ Get a specific Element from the panel. @param row: the row index @param cell: the cell index @return the Element at the given row and cell """ tr = DOM.getChild(self.tbody, row) td = DOM.getChild(tr, cell) return DOM.getFirstChild(td) def getContainerElement(self): return self.containerElem Factory.registerClass('pyjamas.ui.DecoratorPanel', 'DecoratorPanel', DecoratorPanel) class DecoratedTabBar(TabBar): TAB_ROW_STYLES = ["tabTop", "tabMiddle"] STYLENAME_DEFAULT = "gwt-DecoratedTabBar" def __init__(self, **kwargs): """ Creates an empty {@link DecoratedTabBar}. """ TabBar.__init__(self, **kwargs) def createTabTextWrapper(self): return DecoratorPanel(self.TAB_ROW_STYLES, 1)
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pyjamas import DOM from pyjamas import Factory from ComplexPanel import ComplexPanel class FlowPanel(ComplexPanel): def __init__(self, **kwargs): element = None if kwargs.has_key('Element'): element = kwargs.pop('Element') if element is None: element = DOM.createDiv() self.setElement(element) ComplexPanel.__init__(self, **kwargs) def add(self, w): ComplexPanel.add(self, w, self.getElement()) def remove(self, index): if isinstance(index, int): index = self.getWidget(index) return ComplexPanel.remove(self, index) Factory.registerClass('pyjamas.ui.FlowPanel', FlowPanel)
@param html: Html content (e.g. the button label); see setHTML() @param listener: A new click listener; see addClickListener() """ if not kwargs.has_key('StyleName'): kwargs['StyleName'] = "gwt-Button" if html: kwargs['HTML'] = html if kwargs.has_key('Element'): element = kwargs.pop('Element') else: element = DOM.createButton() ButtonBase.__init__(self, element, **kwargs) self.adjustType(self.getElement()) if listener: self.addClickListener(listener) def adjustType(self, button): if button.type == 'submit': try: DOM.setAttribute(button, "type", "button") except: pass def click(self): """ Simulate a button click. """ self.getElement().click() Factory.registerClass('pyjamas.ui.Button', Button)
SimplePanel.__init__(self, element) self.disclosurePanel = disclosurePanel element = self.getElement() DOM.setAttribute(element, "href", "javascript:void(0);"); DOM.setStyleAttribute(element, "display", "block") self.sinkEvents(Event.ONCLICK) self.setStyleName("header") def onBrowserEvent(self, event): type = DOM.eventGetType(event) if type == "click": DOM.eventPreventDefault(event) newstate = not self.disclosurePanel.getOpen() self.disclosurePanel.setOpen(newstate) Factory.registerClass('pyjamas.ui.ClickableHeader', ClickableHeader) class DefaultHeader(Widget): def __init__(self, text, disclosurePanel): Widget.__init__(self) self.disclosurePanel = disclosurePanel self.imageBase = pygwt.getModuleBaseURL() self.root = DOM.createTable() self.tbody = DOM.createTBody() self.tr = DOM.createTR() self.imageTD = DOM.createTD() self.labelTD = DOM.createTD() self.imgElem = DOM.createImg() self.updateState()
# Copyright 2010, Daniel Popowich <*****@*****.**> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pyjamas import DOM from pyjamas import Factory from pyjamas.ui.HTML import HTML class InlineHTML(HTML): '''An HTML, but using <span> instead of <div>''' def __init__(self, html=None, wordWrap=True, **kwargs): kwargs['StyleName'] = kwargs.get('StyleName', "gwt-InlineHTML") kwargs['Element'] = DOM.createSpan() HTML.__init__(self, html, wordWrap, **kwargs) Factory.registerClass('pyjamas.ui.InlineHTML', 'InlineHTML', InlineHTML)
self.disclosurePanel = disclosurePanel element = self.getElement() DOM.setAttribute(element, "href", "javascript:void(0);") DOM.setStyleAttribute(element, "display", "block") self.sinkEvents(Event.ONCLICK) self.setStyleName("header") def onBrowserEvent(self, event): etype = DOM.eventGetType(event) if etype == "click": DOM.eventPreventDefault(event) newstate = not self.disclosurePanel.getOpen() self.disclosurePanel.setOpen(newstate) Factory.registerClass('pyjamas.ui.DisclosurePanel', 'ClickableHeader', ClickableHeader) class DefaultHeader(Widget): def __init__(self, text): Widget.__init__(self) self.imageBase = pygwt.getModuleBaseURL() self.root = DOM.createTable() self.tbody = DOM.createTBody() self.tr = DOM.createTR() self.imageTD = DOM.createTD() self.labelTD = DOM.createTD() self.imgElem = DOM.createImg() self.setElement(self.root)
if kwargs.has_key('Element'): element = kwargs.pop('Element') else: element = DOM.createElement("fieldset") self.legend = DOM.createElement("legend") DOM.appendChild(element, self.legend) kwargs['Caption'] = caption if widget is not None: kwargs['Widget'] = widget if not 'StyleName' in kwargs: kwargs['StyleName'] = 'gwt-CaptionPanel' SimplePanel.__init__(self, element, **kwargs) @classmethod def _getProps(self): return SimplePanel._getProps() + self._props def getCaption(self): return self.caption def setCaption(self, caption): self.caption = caption if caption is not None and not caption == "": DOM.setInnerHTML(self.legend, caption) DOM.insertChild(self.getElement(), self.legend, 0) elif DOM.getParent(self.legend) is not None: DOM.removeChild(self.getElement(), self.legend) Factory.registerClass('pyjamas.ui.CaptionPanel', 'CaptionPanel', CaptionPanel)
if int(self.currentMonth) == 12: self.currentMonth = 1 self.currentYear = int(self.currentYear) + 1 else: self.currentMonth = int(self.currentMonth) + 1 self.draw(self.currentMonth, self.currentYear) def drawPreviousYear(self): self.currentYear = int(self.currentYear) - 1 self.draw(self.currentMonth, self.currentYear) def drawNextYear(self): self.currentYear = int(self.currentYear) + 1 self.draw(self.currentMonth, self.currentYear) Factory.registerClass('pyjamas.ui.Calendar', 'Calendar', Calendar) class DateField(Composite): icon_img = "icon_calendar.gif" icon_style = "calendar-img" today_text = "Today" today_style = "calendar-today-link" def __init__(self, format='%d-%m-%Y'): self.format = format self.tbox = TextBox() self.tbox.setVisibleLength(10) # assume valid sep is - / . or nothing if format.find('-') >= 0:
try: # yuk! return element.style.display != "none" except AttributeError: # not been set (yet?) return True # also callable as: setVisible(visible) def setVisible(self, element, visible=None): """Set whether this element is visible or not. If a single parameter is given, the self.element is used. This modifies the CSS property 'display', which means that an invisible element not only is not drawn, but doesn't occupy any space on the page. """ if visible is None: visible = element element = self.element if visible: DOM.setStyleAttribute(element, 'display', "") else: DOM.setStyleAttribute(element, 'display', "none") def unsinkEvents(self, eventBitsToRemove): """Reverse the operation of sinkEvents. See L{UIObject.sinkEvents}. """ DOM.sinkEvents( self.getElement(), ~eventBitsToRemove & DOM.getEventsSunk(self.getElement())) Factory.registerClass('pyjamas.ui.UIObject', 'UIObject', UIObject)
DOM.setEventListener(self.focusable, None) def onLoad(self): self.root.updateStateRecursive() def adopt(self, content): self.childWidgets.add(content) content.treeSetParent(self) def disown(self, item): self.childWidgets.remove(item) item.treeSetParent(None) def fireStateChanged(self, item): for listener in self.listeners: if hasattr(listener, "onTreeItemStateChanged"): listener.onTreeItemStateChanged(item) def getChildWidgets(self): return self.childWidgets def shouldTreeDelegateFocusToElement(self, elem): name = str(elem.nodeName) name = name.lower() return name == 'select' or \ name == 'input' or \ name == 'checkbox' Factory.registerClass('pyjamas.ui.Tree', 'Tree', Tree)
DOM.setEventListener(self.focusable, None); def onLoad(self): self.root.updateStateRecursive() def adopt(self, content): self.childWidgets.add(content) content.treeSetParent(self) def disown(self, item): self.childWidgets.remove(item) item.treeSetParent(None) def fireStateChanged(self, item): for listener in self.listeners: if hasattr(listener, "onTreeItemStateChanged"): listener.onTreeItemStateChanged(item) def getChildWidgets(self): return self.childWidgets def shouldTreeDelegateFocusToElement(self, elem): name = str(elem.nodeName) name = name.lower() return name == 'select' or \ name == 'input' or \ name == 'checkbox' Factory.registerClass('pyjamas.ui.Tree', 'Tree', Tree)
("wordwrap", "Word Wrap", "WordWrap", None), ("horzAlign", "Horizontal Alignment", "HorizontalAlignment", None), ] def __init__(self, html=None, wordWrap=True, **kwargs): kwargs['StyleName'] = kwargs.get('StyleName', "gwt-HTML") if html: kwargs['HTML'] = html Label.__init__(self, wordWrap=wordWrap, **kwargs) self.sinkEvents(Event.ONCLICK | Event.MOUSEEVENTS) @classmethod def _getProps(self): return Widget._getProps() + self._props def _setWeirdProps(self, props, builderstate): if props.has_key("label"): props['text'] = props['label'] del props['label'] if not props.has_key("text"): return txt = props["text"] if props.get("html", False): self.setHTML(txt) else: self.setText(txt) Factory.registerClass('pyjamas.ui.HTML', 'HTML', HTML)
self.initialThumbPos) def onSplitterResizeStarted(self, x, y): self.initialThumbPos = y self.initialTopHeight = DOM.getOffsetHeight(self.getWidgetElement(0)) def buildDOM(self): topDiv = self.getWidgetElement(0) bottomDiv = self.getWidgetElement(1) splitDiv = self.getSplitElement() DOM.appendChild(self.getElement(), self.container) DOM.appendChild(self.container, topDiv) DOM.appendChild(self.container, splitDiv) DOM.appendChild(self.container, bottomDiv) # The style name is placed on the table rather than splitElem # to allow the splitter to be styled without interfering # with layout. DOM.setInnerHTML(splitDiv, "<div class='vsplitter' " + "style='text-align:center'>" + self.getThumbImageHTML() + "</div>") self.addScrolling(topDiv) self.addScrolling(bottomDiv) Factory.registerClass('pyjamas.ui.VerticalSplitPanel', VerticalSplitPanel)
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 getEndOfLinePos(self): return 0 # TODO: return (LocaleInfo.getCurrentLocale().isRTL() ? 0 : 1) def getStartOfLinePos(self): return 1 # TODO: return (LocaleInfo.getCurrentLocale().isRTL() ? 1 : 0) Factory.registerClass('pyjamas.ui.HorizontalSplitPanel', HorizontalSplitPanel)
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pyjamas import DOM from pyjamas import Factory from Label import Label from pyjamas.ui import Event from pyjamas.ui import InnerHTML class HTML(Label, InnerHTML): def __init__(self, html=None, wordWrap=True, Element=None, **kwargs): if not kwargs.has_key('StyleName'): kwargs['StyleName']="gwt-HTML" if html: kwargs['HTML'] = html kwargs['WordWrap'] = wordWrap if Element is None: Element = DOM.createDiv() self.setElement(Element) Label.__init__(self, **kwargs) self.sinkEvents(Event.ONCLICK | Event.MOUSEEVENTS) Factory.registerClass('pyjamas.ui.HTML', HTML)
def getStep(self): return DOM.getAttribute(self.getElement(), "step") def getVisibleLength(self): return DOM.getIntAttribute(self.getElement(), "size") def setMaxLength(self, length): DOM.setIntAttribute(self.getElement(), "maxLength", length) def setKind(self, kind): DOM.setAttribute(self.getElement(), "type", kind) def setMin(self, min): DOM.setAttribute(self.getElement(), "min", min) def setMax(self, max): DOM.setAttribute(self.getElement(), "max", max) def setPlaceholder(self, placeholder): DOM.setIntAttribute(self.getElement(), "placeholder", placeholder) def setStep(self, step): DOM.setAttribute(self.getElement(), "step", step) def setVisibleLength(self, length): DOM.setIntAttribute(self.getElement(), "size", length) Factory.registerClass('pyjamas.ui.TextBox', 'TextBox', TextBox)
widget.setVisible(False) def remove(self, widget): if isinstance(widget, int): widget = self.getWidget(widget) if not ComplexPanel.remove(self, widget): return False if self.visibleWidget == widget: self.visibleWidget = None return True def showWidget(self, index): self.checkIndex(index) if self.visibleWidget is not None: self.visibleWidget.setVisible(False) self.visibleWidget = self.getWidget(index) self.visibleWidget.setVisible(True) def checkIndex(self, index): if (index < 0) or (index >= self.getWidgetCount()): # throw new IndexOutOfBoundsException(); pass Factory.registerClass('pyjamas.ui.DeckPanel', DeckPanel)
def addItem(comp, props, childs, parentInstance, eventTarget): klsname = comp['name'] modname = comp.get('module') if modname is None: modname = '.'.join(["pyjamas.ui", klsname]) kls = Factory.lookupClass('.'.join([modname, klsname])) args = {} wprops = {} if props.has_key("common"): wprops.update(props['common']) if props.has_key("widget"): wprops.update(props['widget']) for n in kls._getProps(): name = n[ui.PROP_NAME] if not wprops.has_key(name): continue fname = n[ui.PROP_FNAM] if wprops[name] == '': continue args[fname] = wprops[name] # create item with properties including weird ones # which can't fit into the name value structure item = kls(**args) if hasattr(item, "_setWeirdProps"): item._setWeirdProps(wprops, BuilderState(self, eventTarget)) tooltip = wprops.get('tooltip') if tooltip is not None: item.addMouseListener(TooltipListener(tooltip)) identifier = comp['id'] widget_order.append(identifier) widgets_by_name[identifier] = klsname widget_instances[identifier] = item l = widgets_by_class.get(klsname, []) l.append(identifier) widgets_by_class[klsname] = l #if parentInstance is not None: # context = parentInstance.getIndexedChild(comp['index']) # context.add(item.componentInstance) for (index, child) in enumerate(childs): if not child[0].has_key("type") or child[0]["type"] is None: continue childitem = addItem(child[0], child[1], child[2], item, eventTarget) if childitem is None: continue print "childitem", childitem item.addIndexedItem(child[0]["index"], childitem) if not "elements" in props: props["elements"] = {} if not index in props["elements"]: props["elements"][index] = {} elemprops = props['elements'][index] print "elemprops", childitem, item, elemprops item.setElementProperties(childitem, elemprops) # add child (by name) to item cname = child[0]["id"] setattr(item, cname, childitem) # make the event target the recipient of all events if eventTarget is not None and props.has_key("events"): added_already = [] #print props["events"] for listener_name, listener_fn in props["events"].items(): if listener_name in added_already or not listener_fn: continue args = {} args[listener_name] = listener_fn fname = eventListeners[listener_name][0] listener = MultiListener(eventTarget, **args) setattr(item, "_%sListener" % fname, listener) #print "add listener", listener_name, fname listen_add_fn = getattr(item, fname) listen_add_fn(listener) return item
widget.removeFromParent() tr = DOM.createTR() td = DOM.createTD() DOM.insertChild(self.getBody(), tr, beforeIndex) DOM.appendChild(tr, td) CellPanel.insert(self, widget, td, beforeIndex) self.setCellHorizontalAlignment(widget, self.horzAlign) self.setCellVerticalAlignment(widget, self.vertAlign) def remove(self, widget): if isinstance(widget, int): widget = self.getWidget(widget) if widget.getParent() != self: return False td = DOM.getParent(widget.getElement()) tr = DOM.getParent(td) DOM.removeChild(self.getBody(), tr) CellPanel.remove(self, widget) return True Factory.registerClass('pyjamas.ui.VerticalPanel', 'VerticalPanel', VerticalPanel)
elif layout.direction == self.WEST: row = rows[northRow] DOM.insertChild(row.tr, td, row.center) row.center += 1 self.appendAndMaybeAdopt(td, child.getElement(), beingAdded) DOM.setIntAttribute(td, "rowSpan", southRow - northRow + 1) westCol += 1 elif layout.direction == self.EAST: row = rows[northRow] DOM.insertChild(row.tr, td, row.center) self.appendAndMaybeAdopt(td, child.getElement(), beingAdded) DOM.setIntAttribute(td, "rowSpan", southRow - northRow + 1) eastCol -= 1 elif layout.direction == self.CENTER: centerTd = td if self.center is not None: row = rows[northRow] DOM.insertChild(row.tr, centerTd, row.center) self.appendAndMaybeAdopt(centerTd, self.center.getElement(), beingAdded) def appendAndMaybeAdopt(self, parent, child, beingAdded): if beingAdded is not None: if DOM.compare(child, beingAdded.getElement()): CellPanel.add(self, beingAdded, parent) return DOM.appendChild(parent, child) Factory.registerClass("pyjamas.ui.DockPanel", DockPanel)
return self.getDOMRowCount() def removeCells(self, row, column, num): for i in range(num): self.removeCell(row, column) def prepareCell(self, row, column): self.prepareRow(row) #if column < 0: throw new IndexOutOfBoundsException("Cannot create a column with a negative index: " + column); cellCount = self.getCellCount(row) required = column + 1 - cellCount if required > 0: self.addCells(self.getBodyElement(), row, required) def prepareRow(self, row): #if row < 0: throw new IndexOutOfBoundsException("Cannot create a row with a negative index: " + row); rowCount = self.getRowCount() for i in range(rowCount, row + 1): self.insertRow(i) def addCells(self, table, row, num): rowElem = table.rows.item(row) for i in range(num): cell = doc().createElement("td") rowElem.appendChild(cell) Factory.registerClass('pyjamas.ui.FlexTable', FlexTable)
self.value_x = new_value[0] self.value_y = new_value[1] if not notify: return for listener in self.valuechange_listeners: listener.onControlValueChanged(self, old_value, new_value) def onControlValueChanged(self, value_old_xy, value_new_xy): pass def onKeyDown(self, sender, keycode, modifiers): if keycode == KeyboardListener.KEY_UP: DOM.eventPreventDefault(DOM.eventGetCurrentEvent()) new_value = \ self.processValue((self.value_x + self.step_x, self.value_y + self.step_y)) self.setControlPos(new_value) self.setValue(new_value) elif keycode == KeyboardListener.KEY_DOWN: DOM.eventPreventDefault(DOM.eventGetCurrentEvent()) new_value = \ self.processValue((self.value_x - self.step_x, self.value_y-self.step_y)) self.setControlPos(new_value) self.setValue(new_value) Factory.registerClass('pyjamas.ui.DoubleControl', 'DoubleControl', DoubleControl)
class HyperlinkImage(Hyperlink): def __init__(self, img, **kwargs): self.mouseListeners = [] if not kwargs.has_key('StyleName'): kwargs['StyleName'] = 'gwt-HyperlinkImage' Hyperlink.__init__(self, **kwargs) DOM.appendChild(DOM.getFirstChild(self.getElement()), img.getElement()) img.unsinkEvents(Event.ONCLICK | Event.MOUSEEVENTS) self.sinkEvents(Event.ONCLICK | Event.MOUSEEVENTS) def addMouseListener(self, listener): self.mouseListeners.append(listener) def removeMouseListener(self,listener): self.mouseListeners.remove(listener) def onBrowserEvent(self, event): type = DOM.eventGetType(event) if type == 'mousedown' or type == 'mouseup' or type == 'mousemove' or type == 'mouseover' or type == 'mouseout': MouseListener.fireMouseEvent(self.mouseListeners, self, event) # stop event falling through esp. for drag on image DOM.eventPreventDefault(event) else: Hyperlink.onBrowserEvent(self, event) Factory.registerClass('pyjamas.ui.HyperlinkImage', 'HyperlinkImage', HyperlinkImage)
self.tab_names.pop(k) break index = self.getWidgetIndex(widget) if index == -1: return False self.children.remove(widget) self.tabBar.removeTab(index) self.deck.remove(widget) return True def removeTabListener(self, listener): self.tabListeners.remove(listener) def selectTab(self, index): """ manual tab selection. tab can be selected: * by index, * by tab name (matching TabPanel.insert name arg if given) * or by widget. """ if isinstance(index, basestring): index = self.tab_names[index] if not isinstance(index, int): index = self.getWidgetIndex(index) self.tabBar.selectTab(index) Factory.registerClass('pyjamas.ui.TabPanel', 'TabPanel', TabPanel)
token = item['fields']['name'] self.createPage(token, html, token) self.setPage(token) def onRemoteError(self, code, message, request_info): RootPanel().add( HTML("Server Error or Invalid Response: ERROR " + str(code) + " - " + str(message))) class DataService(JSONProxy): def __init__(self): JSONProxy.__init__(self, "/services/pages/", [ "getPage", "updatePage", "getPages", "addPage", "getPageByName", "deletePage" ]) if __name__ == "__main__": pyjd.setup("http://127.0.0.8/site_media/public/index.html") el = DOM.createElement("div") el.innerHTML = "test" DOM.setAttribute(el, "id", "pyjamas.apps.Email(Text='hello')") label = Factory.createWidgetOnElement(el) RootPanel().add(label) app = WebApp() app.onModuleLoad() pyjd.run()
# Copyright 2006 James Tauber and contributors # Copyright (C) 2009 Luke Kenneth Casson Leighton <*****@*****.**> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pyjamas import DOM from pyjamas import Factory from FocusWidget import FocusWidget from pyjamas.ui import InnerText, InnerHTML class ButtonBase(FocusWidget, InnerHTML, InnerText): def __init__(self, element, **kwargs): FocusWidget.__init__(self, element, **kwargs) Factory.registerClass('pyjamas.ui.ButtonBase', ButtonBase)
def __iter__(self): return self.getChildren().__iter__() class Panel(PanelBase, Widget): def __init__(self, **kwargs): self.children = [] PanelBase.__init__(self) Widget.__init__(self, **kwargs) def disown(self, widget): if widget.getParent() is not self: raise Exception("widget %s is not a child of this panel %s" % \ (str(widget), str(self))) element = widget.getElement() widget.setParent(None) parentElement = DOM.getParent(element) if parentElement is not None: DOM.removeChild(parentElement, element) def adopt(self, widget, container): if container is not None: widget.removeFromParent() DOM.appendChild(container, widget.getElement()) widget.setParent(self) Factory.registerClass('pyjamas.ui.Panel', 'Panel', Panel)
child.updateStateRecursive() class RootTreeItem(TreeItem): def addItem(self, item): self.insertItem(item) def insertItem(self, item, index=None): if (item.getParentItem() is not None) or (item.getTree() is not None): item.remove() item.setTree(self.getTree()) item.setParentItem(None) if index is None: self.children.append(item) else: self.children.insert(index, item) DOM.setIntStyleAttribute(item.getElement(), "marginLeft", 0) def removeItem(self, item): if item not in self.children: return item.setTree(None) item.setParentItem(None) self.children.remove(item) Factory.registerClass('pyjamas.ui.TreeItem', 'TreeItem', TreeItem)
panel.add(self.message) panel.add(buttons) panel.add(self.status) def onClick(self, sender): self.status.setText(self.TEXT_WAITING) text = self.message.getText() msg_sender = self.sender.getText() msg_subject = self.subject.getText() # demonstrate proxy & callMethod() if sender == self.button_py: id = self.remote_py.send(msg_sender, msg_subject, text, self) if id < 0: self.status.setText(self.TEXT_ERROR) def onRemoteResponse(self, response, request_info): self.status.setText(response) def onRemoteError(self, code, message, request_info): self.status.setText("Server Error or Invalid Response: ERROR " + \ str(code) + " - " + str(message)) Factory.registerClass('pyjamas.apps.Email', Email) class EchoServicePython(JSONProxy): def __init__(self): JSONProxy.__init__(self, "/services/email.py", ["send"])
console.error("widget %o is not a child of this panel %o", widget, self) else: element = widget.getElement() widget.setParent(None) parentElement = DOM.getParent(element) if parentElement: DOM.removeChild(parentElement, element) def adopt(self, widget, container): if container: widget.removeFromParent() DOM.appendChild(container, widget.getElement()) widget.setParent(self) def remove(self, widget): pass def doAttachChildren(self): for child in self: child.onAttach() def doDetachChildren(self): for child in self: child.onDetach() def __iter__(self): return self.children.__iter__() Factory.registerClass('pyjamas.ui.Panel', Panel)
element = self.element try: # yuk! return element.style.display != "none" except AttributeError: # not been set (yet?) return True # also callable as: setVisible(visible) def setVisible(self, element, visible=None): """Set whether this element is visible or not. If a single parameter is given, the self.element is used. This modifies the CSS property 'display', which means that an invisible element not only is not drawn, but doesn't occupy any space on the page. """ if visible is None: visible = element element = self.element if visible: DOM.setStyleAttribute(element, 'display', "") else: DOM.setStyleAttribute(element, 'display', "none") def unsinkEvents(self, eventBitsToRemove): """Reverse the operation of sinkEvents. See L{UIObject.sinkevents}. """ DOM.sinkEvents(self.getElement(), ~eventBitsToRemove & DOM.getEventsSunk(self.getElement())) Factory.registerClass('pyjamas.ui.UIObject', 'UIObject', UIObject)
def getCellElement(self, row, cell) : """ Get a specific Element from the panel. @param row the row index @param cell the cell index @return the Element at the given row and cell """ tr = DOM.getChild(self.tbody, row) td = DOM.getChild(tr, cell) return DOM.getFirstChild(td) def getContainerElement(self): return self.containerElem Factory.registerClass('pyjamas.ui.DecoratorPanel', 'DecoratorPanel', DecoratorPanel) class DecoratedTabBar(TabBar): TAB_ROW_STYLES = ["tabTop", "tabMiddle"] STYLENAME_DEFAULT = "gwt-DecoratedTabBar" def __init__(self, **kwargs): """ Creates an empty {@link DecoratedTabBar}. """ TabBar.__init__(self, **kwargs) def createTabTextWrapper(self): return DecoratorPanel(self.TAB_ROW_STYLES, 1)
return manageRootPanel(RootPanelCls(element), id) def manageRootPanel(panel, id=None): if len(rootPanels) < 1: panelManager = RootPanelManager() Window.addWindowCloseListener(panelManager) rootPanels[id] = panel return panel class RootPanelCls(AbsolutePanel): def __init__(self, Element=None, **kwargs): if Element: kwargs['Element'] = Element AbsolutePanel.__init__(self, **kwargs) if Element is None: # avoid having CSS styles position:relative and hidden set on body Element = self.getBodyElement() self.setElement(Element) self.onAttach() def getBodyElement(self): return doc().body Factory.registerClass('pyjamas.ui.RootPanelCls', RootPanelCls) def RootPanel(id=None): return get(id)