def __init__(self): SimplePanel.__init__(self) panel = HorizontalPanel() panel.setBorderWidth(1) panel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER) panel.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE) part1 = Label("Part 1") part2 = Label("Part 2") part3 = Label("Part 3") part4 = Label("Part 4") panel.add(part1) panel.add(part2) panel.add(part3) panel.add(part4) panel.setCellWidth(part1, "10%") panel.setCellWidth(part2, "70%") panel.setCellWidth(part3, "10%") panel.setCellWidth(part4, "10%") panel.setCellVerticalAlignment(part3, HasAlignment.ALIGN_BOTTOM) panel.setWidth("100%") panel.setHeight("200px") self.add(panel)
def __init__( self ) : numberOfLoopsPanel=HorizontalPanel() numberOfLoopsPanel.add( HTML("Maximum number of loops") ) self.maximumNumberOfLoops=TextBox() self.maximumNumberOfLoops.setText(10) numberOfLoopsPanel.add( self.maximumNumberOfLoops ) numberOfLoopsPanel.setCellHorizontalAlignment( self.maximumNumberOfLoops, HasHorizontalAlignment.ALIGN_RIGHT ) numberOfLoopsPanel.setWidth("100%") aimPointPanel=HorizontalPanel() aimPointPanel.add( HTML("Aim point") ) self.aimPoint=TextBox() self.aimPoint.setText(127) aimPointPanel.add( self.aimPoint ) aimPointPanel.setCellHorizontalAlignment( self.aimPoint, HasHorizontalAlignment.ALIGN_RIGHT ) aimPointPanel.setWidth("100%") self.start=Button("Start") self.echo=HTML("Initiating...") self.mainPanel = VerticalPanel() self.mainPanel.add( numberOfLoopsPanel ) self.mainPanel.add( aimPointPanel ) self.mainPanel.add( self.start ) self.mainPanel.add( self.echo )
def __init__(self): Composite.__init__(self) panel = DockPanel(HorizontalAlignment=HasAlignment.ALIGN_CENTER, VerticalAlignment=HasAlignment.ALIGN_MIDDLE) panel.setWidth("100%") vp = VerticalPanel() grid = FlexTable(CellPadding=4, CellSpacing=4) hp = HorizontalPanel() handle_n = NextHandle(self) handle_f = FinishHandle(self) handle_c = ClearHandle(self) self.next = Button("Next", handle_n, StyleName='button') self.finish = Button("Finish!", handle_f, StyleName='button') self.clear = Button("Clear", handle_c, StyleName='button') hp.add(self.clear) hp.add(self.finish) hp.add(self.next) hp.setWidth("70%") vp.add(Label("Content-Based Image Retrieval Using OPF", StyleName='label')) vp.add(grid) vp.setHorizontalAlignment(HasAlignment.ALIGN_RIGHT) vp.add(hp) cols = 4 for i in range(100): im = Image('images/cbir/%d.jpg' % random.randint(0, 1000), Size=("200px", "150px"), StyleName='image-cool') grid.setWidget(int(i/cols), i%cols, im) panel.add(vp, DockPanel.CENTER) self.initWidget(panel) self.status = Label() vp.add(self.status)
def createRegisterPanel( self, registerNames ) : """ Creates panels and buttons for everything given in registerNames, and returns the main panel. """ flowPanel=FlowPanel() for buttonName in registerNames : newPanel=HorizontalPanel() label=Label(buttonName) newPanel.add( label ) newTextBox=TextBox() newTextBox.setEnabled(False) newTextBox.setWidth(80) statusBox=TextBox() statusBox.setEnabled(False) statusBox.setWidth(30) newPanel.add(newTextBox) newPanel.add(statusBox) newPanel.setCellHorizontalAlignment( newTextBox, HasHorizontalAlignment.ALIGN_RIGHT ) newPanel.setCellHorizontalAlignment( statusBox, HasHorizontalAlignment.ALIGN_RIGHT ) newPanel.setCellWidth( statusBox, "20px" ) newPanel.setWidth("100%") #newPanel.setStyleName("areaStyle"); #newPanel.setBorderWidth(5); newTextBox.setText("select chip...") newTextBox.addChangeListener(self) newTextBox.setTitle(buttonName) # This isn't displayed, but it's useful to have stored self.i2cValueEntries[buttonName]=newTextBox self.statusValueEntries[buttonName]=statusBox statusBox.setTitle(buttonName) statusBox.setText("...") flowPanel.add(newPanel) return flowPanel
class InfoDirectory: def onModuleLoad(self): self.remote = InfoServicePython() self.tree_width = 200 self.tp = HorizontalPanel() self.tp.setWidth("%dpx" % (self.tree_width)) self.treeview = Trees() self.treeview.fTree.addTreeListener(self) self.sp = ScrollPanel() self.tp.add(self.treeview) self.sp.add(self.tp) self.sp.setHeight("100%") self.horzpanel1 = HorizontalPanel() self.horzpanel1.setSize("100%", "100%") self.horzpanel1.setBorderWidth(1) self.horzpanel1.setSpacing("10px") self.rp = RightPanel() self.rps = ScrollPanel() self.rps.add(self.rp) self.rps.setWidth("100%") self.rp.setWidth("100%") self.cp1 = CollapserPanel(self) self.cp1.setWidget(self.sp) self.cp1.setHTML(" ") self.midpanel = MidPanel(self) self.cp2 = CollapserPanel(self) self.cp2.setWidget(self.midpanel) self.cp2.setHTML(" ") self.horzpanel1.add(self.cp1) self.horzpanel1.add(self.cp2) self.horzpanel1.add(self.rps) self.cp1.setInitialWidth("%dpx" % self.tree_width) self.cp2.setInitialWidth("200px") RootPanel().add(self.horzpanel1) width = Window.getClientWidth() height = Window.getClientHeight() self.onWindowResized(width, height) Window.addWindowResizeListener(self) def setCollapserWidth(self, widget, width): self.horzpanel1.setCellWidth(widget, width) def onWindowResized(self, width, height): #self.hp.setWidth("%dpx" % (width - self.tree_width)) #self.hp.setHeight("%dpx" % (height - 20)) self.cp1.setHeight("%dpx" % (height - 30)) self.cp2.setHeight("%dpx" % (height - 30)) self.rps.setHeight("%dpx" % (height - 30)) self.horzpanel1.setHeight("%dpx" % (height - 20)) def onTreeItemStateChanged(self, item): if item.isSelected(): self.onTreeItemSelected(item) def onTreeItemSelected(self, item): obj = item.getUserObject() if len(obj.children) != 0: self.clear_mid_panel() return self.remote.get_midpanel_data(obj.root + "/" + obj.text, self) self.cp2.setHTML(obj.text) self.clear_right_panel() def clear_right_panel(self): self.horzpanel1.remove(2) self.horzpanel1.insert(HTML(""), 2) self.rp.setTitle(" ") def clear_mid_panel(self): self.clear_right_panel() #self.horzpanel2.setLeftWidget(HTML("")) def set_mid_panel(self, response): self.midpanel.set_items(response) self.cp2.setWidget(self.midpanel) def select_right_grid(self, location, name): self.horzpanel1.remove(2) self.horzpanel1.insert(self.rps, 2) self.rp.setTitle(name) self.remote.get_rightpanel_datanames(location, self) def get_rightpanel_datasets(self, datasets): self.rp.clear_items() self.rp.setup_panels(datasets) for i in range(len(datasets)): item = datasets[i] fname = item[0] self.remote.get_rightpanel_data(fname, fname, i, self) def fill_right_grid(self, data): index = data.get('index') name = data.get('name') if data.has_key('items'): self.rp.add_items(data.get('items'), name, index) elif data.has_key('html'): self.rp.add_html(data.get('html'), name, index) def onRemoteResponse(self, response, request_info): method = request_info.method if method == "get_midpanel_data": self.set_mid_panel(response) elif method == "get_rightpanel_datanames": self.get_rightpanel_datasets(response) elif method == "get_rightpanel_data": self.fill_right_grid(response) def onRemoteError(self, code, message, request_info): RootPanel().add(HTML("Server Error or Invalid Response: ERROR " + code)) RootPanel().add(HTML(message))
class MailList(Composite): VISIBLE_EMAIL_COUNT = 10 def __init__(self, mailObject): Composite.__init__(self) self.countLabel = HTML() self.newerButton = HTML("<a href='javascript:;'>< newer</a>", True) self.olderButton = HTML("<a href='javascript:;'>older ></a>", True) self.startIndex = 0 self.selectedRow = -1 self.table = FlexTable() self.navBar = HorizontalPanel() self.mailObject = mailObject # Setup the table. self.table.setCellSpacing(0) self.table.setCellPadding(2) self.table.setWidth("100%") # Hook up events. self.table.addTableListener(self) self.newerButton.addClickListener(self) self.olderButton.addClickListener(self) # Create the 'navigation' bar at the upper-right. innerNavBar = HorizontalPanel() innerNavBar.setSpacing(8) innerNavBar.add(self.newerButton) innerNavBar.add(self.countLabel) innerNavBar.add(self.olderButton) self.navBar.setStyleName("mail-ListNavBar") self.navBar.setHorizontalAlignment(HasAlignment.ALIGN_RIGHT) self.navBar.add(innerNavBar) self.navBar.setWidth("100%") self.initWidget(self.table) self.setStyleName("mail-List") self.initTable() self.update() def onCellClicked(self, sender, row, cell): # Select the row that was clicked (-1 to account for header row). if (row > 0): self.selectRow(row - 1) def onClick(self, sender): if (sender == self.olderButton): # Move forward a page. self.startIndex = self.startIndex + MailList.VISIBLE_EMAIL_COUNT if (self.startIndex >= MailItems().getMailItemCount()): self.startIndex = self.startIndex - MailList.VISIBLE_EMAIL_COUNT else: self.styleRow(self.selectedRow, False) self.selectedRow = -1 self.update() elif (sender == self.newerButton): # Move back a page. self.startIndex = self.startIndex - MailList.VISIBLE_EMAIL_COUNT if (self.startIndex < 0): self.startIndex = 0 else: self.styleRow(self.selectedRow, False) self.selectedRow = -1 self.update() def initTable(self): # Create the header row. self.table.setText(0, 0, "sender") self.table.setText(0, 1, "email") self.table.setText(0, 2, "subject") self.table.setWidget(0, 3, self.navBar) self.table.getRowFormatter().setStyleName(0, "mail-ListHeader") # Initialize the rest of the rows. i = 0 while i < MailList.VISIBLE_EMAIL_COUNT: self.table.setText(i + 1, 0, "") self.table.setText(i + 1, 1, "") self.table.setText(i + 1, 2, "") self.table.getCellFormatter().setWordWrap(i + 1, 0, False) self.table.getCellFormatter().setWordWrap(i + 1, 1, False) self.table.getCellFormatter().setWordWrap(i + 1, 2, False) self.table.getFlexCellFormatter().setColSpan(i + 1, 2, 2) i = i + 1 def selectRow(self, row): # When a row (other than the first one, which is used as a header) is # selected, display its associated MailItem. item = MailItems().getMailItem(self.startIndex + row) if item is None: return self.styleRow(self.selectedRow, False) self.styleRow(row, True) item.read = True self.selectedRow = row self.mailObject.get().displayItem(item) def styleRow(self, row, selected): if (row != -1): if (selected): self.table.getRowFormatter().addStyleName( row + 1, "mail-SelectedRow") else: self.table.getRowFormatter().removeStyleName( row + 1, "mail-SelectedRow") def update(self): # Update the older/newer buttons & label. count = MailItems().getMailItemCount() max = self.startIndex + MailList.VISIBLE_EMAIL_COUNT if (max > count): max = count self.newerButton.setVisible(self.startIndex != 0) self.olderButton.setVisible( self.startIndex + MailList.VISIBLE_EMAIL_COUNT < count) startIndexPlusOne = self.startIndex + 1 self.countLabel.setText("%d - %d of %d" % (startIndexPlusOne, max, count)) # Show the selected emails. i = 0 while (i < MailList.VISIBLE_EMAIL_COUNT): # Don't read past the end. if (self.startIndex + i >= MailItems().getMailItemCount()): break item = MailItems().getMailItem(self.startIndex + i) # Add a row to the table, then set each of its columns to the # email's sender and subject values. self.table.setText(i + 1, 0, item.sender) self.table.setText(i + 1, 1, item.email) self.table.setText(i + 1, 2, item.subject) i = i + 1 # Clear any remaining slots. while (i < MailList.VISIBLE_EMAIL_COUNT): self.table.setHTML(i + 1, 0, " ") self.table.setHTML(i + 1, 1, " ") self.table.setHTML(i + 1, 2, " ") i = i + 1 # Select the first row if none is selected. if (self.selectedRow == -1): self.selectRow(0)
def onModuleLoad(self): # Window.setTitle("CBC Test Stand") StyleSheetCssFile("styleSheet.css") self.TEXT_WAITING = "Waiting for response..." self.TEXT_ERROR = "Server Error" self.status = Label() # This is the remote service self.I2CPanel = I2CPanel() self.SCurveRunPanel = SCurveRunPanel() self.OccupancyCheckPanel = OccupancyCheckPanel() self.CalibrateChannelTrimsPanel = CalibrateChannelTrimsPanel() # mainPanel will have all of the working stuff in it self.mainPanel = DockPanel() # self.mainPanel.setSpacing(10) titleBar = HorizontalPanel() titleBar.add(HTML(r"CBC Test Stand (v1.1)", StyleName="titleStyle")) self.stopTakingDataButton = Button("Stop taking data") self.stopTakingDataButton.addClickListener(self) self.dataTakingPercentage = HTML("0%") self.dataTakingStatus = HTML("Initiating...") titleBar.add(self.dataTakingPercentage) titleBar.add(self.dataTakingStatus) titleBar.add(self.stopTakingDataButton) titleBar.setCellHorizontalAlignment(self.dataTakingStatus, HasHorizontalAlignment.ALIGN_RIGHT) titleBar.setCellHorizontalAlignment(self.dataTakingPercentage, HasHorizontalAlignment.ALIGN_RIGHT) titleBar.setCellHorizontalAlignment(self.stopTakingDataButton, HasHorizontalAlignment.ALIGN_RIGHT) titleBar.setWidth("100%") self.mainPanel.add(titleBar, DockPanel.NORTH) selectionPanel = VerticalPanel() # Register to get updates about the status of data taking, so that # I can update the information in the title bar self.dataRunManager = DataRunManager.instance() self.dataRunManager.registerEventHandler(self) self.activePanelButton = None self.activePanel = None self.registersButton = Label("I2C Registers", StyleName="areaStyle") self.occupanciesButton = Label("Test Occupancies", StyleName="areaStyle") self.scurveButton = Label("S-Curve Run", StyleName="areaStyle") self.calibrateTrimsButton = Label("Calibrate Trims", StyleName="areaStyle") self.registersButton.addClickListener(self) self.occupanciesButton.addClickListener(self) self.scurveButton.addClickListener(self) self.calibrateTrimsButton.addClickListener(self) selectionPanel.add(self.registersButton) selectionPanel.add(self.occupanciesButton) selectionPanel.add(self.scurveButton) selectionPanel.add(self.calibrateTrimsButton) self.mainPanel.add(selectionPanel, DockPanel.WEST) self.mainPanel.add(self.status, DockPanel.SOUTH) RootPanel().add(self.mainPanel) self.setNewMainPanel(self.registersButton)
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())
resdict = resgen_core.processconf(inputArea.getText()) hData = resgen_core.processhorz(resdict, hTemplate, footdict) outputArea.setText(hData) if __name__ == '__main__': b = Button("Convert", convert) p = HorizontalPanel() p.add(inputArea) p.add(outputArea) q = VerticalPanel() q.setStyleName("panel") q.add(b) q.add(p) q.setHeight("100%") q.setWidth("100%") p.setHeight("80%") p.setWidth("100%") inputArea.setHeight("100%") inputArea.setWidth("100%") outputArea.setHeight("100%") outputArea.setWidth("100%") inputArea.setText(confDefault) RootPanel().add(q)
class Trees(Sink): pathdict = {} reduceFiles = None def __init__(self, parent = None): Sink.__init__(self, parent) self.reduceFiles = [] if True: HTTPRequest().asyncGet("datadir.xml", DirDictLoader(self), ) dock = DockPanel(HorizontalAlignment=HasAlignment.ALIGN_LEFT, Spacing=10, Size=("100%","100%")) self.dock = dock self.fProto = [] self.fTree = Tree() self.prPanel = VerticalPanel(Size=("50%", "")) self.treePanel = HorizontalPanel(Size=("50%", "100%")) self.treePanel.add(self.fTree) dock.add(self.treePanel, DockPanel.WEST) self.treePanel.setBorderWidth(1) self.treePanel.setWidth("100%") self.prPanel.setBorderWidth(1) self.prPanel.setWidth("100%") # prepare panel self.prepareReduce = HTML("<tt> .. none yet .. </tt>", True, ) self.recipeList = ListBox() self.recipeList.addChangeListener(getattr(self, "onRecipeSelected")) self.recipeList.addItem("None") HTTPRequest().asyncGet("recipes.xml", RecipeListLoader(self)) #EO prepare panel self.reduceCLPanel = DockPanel(Spacing = 5) self.reduceCLPanel.add(HTML("<i>Reduce Command Line</i>:"), DockPanel.NORTH) self.reduceCLPanel.add(self.prepareReduce, DockPanel.NORTH) self.reduceFilesPanel = DockPanel(Spacing = 5) self.reduceFilesPanel.add(HTML("<b>Datasets</b>:"), DockPanel.WEST) self.reduceFiles = ListBox() self.reduceFiles.setVisibleItemCount(5) self.reduceFilesPanel.add(self.reduceFiles, DockPanel.WEST) self.clearReduceFilesButton = Button("<b>Clear List</b>", listener = getattr(self, "onClearReduceFiles")) self.reduceFilesPanel.add(self.clearReduceFilesButton, DockPanel.SOUTH) self.recipeListPanel = DockPanel(Spacing = 5) self.recipeListPanel.add(HTML("<b>Recipes List</b>:"),DockPanel.WEST) self.recipeListPanel.add(self.recipeList, DockPanel.WEST) self.runReduceButton = Button("<b>RUN REDUCE</b>", listener = getattr(self, "onRunReduce")) self.adInfo = HTML("file info...") # major sub panels self.prPanel.add(self.reduceCLPanel) self.prPanel.add(self.reduceFilesPanel) self.prPanel.add(self.recipeListPanel) self.prPanel.add(self.runReduceButton) self.prPanel.add(self.adInfo) dock.add(self.prPanel,DockPanel.EAST) dock.setCellWidth(self.treePanel, "50%") dock.setCellWidth(self.prPanel, "50%") for i in range(len(self.fProto)): self.createItem(self.fProto[i]) self.fTree.addItem(self.fProto[i].item) self.fTree.addTreeListener(self) self.initWidget(self.dock) if False: #self.parent.filexml != None: DirDictLoader(self).onCompletion(self.parent.filexml) def onTreeItemSelected(self, item): pathdict = self.pathdict tfile = item.getText() #check if already in for i in range(0, self.reduceFiles.getItemCount()): fname = self.reduceFiles.getItemText(i) if fname == tfile: return self.reduceFiles.addItem(tfile) self.updateReduceCL() filename = tfile if filename in pathdict: if pathdict[filename]["filetype"] == "fileEntry": HTTPRequest().asyncGet("adinfo?filename=%s" % self.pathdict[item.getText()]["path"], ADInfoLoader(self), ) else: self.adInfo.setHTML(""" <b style="font-size:200%%">%s</b>""" % pathdict[filename]["filetype"]) else: self.adInfo.setHTML("unknown node") return # self.prepareReduce.setHTML('<a href="runreduce?p=-r&p=callen&p=%(fname)s">reduce -r callen %(fname)s</a>' % # {"fname":item.getText()}) pass def onRecipeSelected(self, event): self.updateReduceCL() def onClearReduceFiles(self, event): self.reduceFiles.clear() self.adInfo.setHTML("file info...") self.updateReduceCL() def updateReduceCL(self): recipe = self.recipeList.getItemText(self.recipeList.getSelectedIndex()) if recipe=="None": rstr = "" else: rstr = "-r "+recipe rfiles = [] for i in range(0, self.reduceFiles.getItemCount()): fname = self.reduceFiles.getItemText(i) rfiles.append(fname) filesstr = " ".join(rfiles) self.prepareReduce.setHTML('<b>reduce</b> %(recipe)s %(files)s' % { "recipe":rstr, "files":filesstr}) def onRunReduce(self): recipe = self.recipeList.getItemText(self.recipeList.getSelectedIndex()) if recipe=="None": rstr = "" else: rstr = "p=-r"+recipe rfiles = [] for i in range(0, self.reduceFiles.getItemCount()): fname = self.reduceFiles.getItemText(i) rfiles.append(quote(self.pathdict[fname]["path"])) filesstr = "&p=".join(rfiles) cl = "/runreduce?%s&p=%s" % (rstr, filesstr) JS("window.open(cl)") def onTreeItemSelected(self, item): pathdict = self.pathdict tfile = item.getText() #check if already in if tfile in pathdict: ftype = pathdict[tfile]["filetype"] if ftype != "fileEntry": item.setState(True) return else: return for i in range(0, self.reduceFiles.getItemCount()): fname = self.reduceFiles.getItemText(i) if fname == tfile: return self.reduceFiles.addItem(tfile) self.updateReduceCL() filename = tfile if filename in pathdict: if pathdict[filename]["filetype"] == "fileEntry": HTTPRequest().asyncGet("adinfo?filename=%s" % self.pathdict[item.getText()]["path"], ADInfoLoader(self), ) else: self.adInfo.setHTML(""" <b style="font-size:200%%">%s</b>""" % pathdict[filename]["filetype"]) else: self.adInfo.setHTML("unknown node") return # self.prepareReduce.setHTML('<a href="runreduce?p=-r&p=callen&p=%(fname)s">reduce -r callen %(fname)s</a>' % # {"fname":item.getText()}) pass def onTreeItemStateChanged(self, item): child = item.getChild(0) if hasattr(child, "isPendingItem"): item.removeItem(child) proto = item.getUserObject() for i in range(len(proto.children)): self.createItem(proto.children[i]) index = self.getSortIndex(item, proto.children[i].text) # demonstrate insertItem. addItem is easy. item.insertItem(proto.children[i].item, index) item.setState(True) def getSortIndex(self, parent, text): nodes = parent.getChildCount() node = 0 text = text.lower() while node < nodes: item = parent.getChild(node) if cmp(text, item.getText().lower()) < 0: break; else: node += 1 return node def createProto(self, node): #if node.nodeType != node.ELEMENT_NODE: # return pathdict = self.pathdict if not node.hasChildNodes(): if node.nodeType != 1: return None newproto = Proto(str(node.getAttribute("name"))) if node.tagName == "fileEntry": pathdict.update({node.getAttribute("name"): { "path":node.getAttribute("fullpath"), "filetype": node.tagName }}) elif node.tagName == "dirEntry": pathdict.update({node.getAttribute("name"): { "path":node.getAttribute("name"), "filetype": node.tagName}}) else: pathdict.update({node.getAttribute("name"): { "path": "NOPATH", "filetype": node.tagName}}) self.createItem(newproto) return newproto else: cprotos = [] for i in range(0, node.childNodes.length): childnode = node.childNodes.item(i) ncproto = self.createProto(childnode) if ncproto != None: ncitem = self.createItem(ncproto) cprotos.append(ncproto) if len(cprotos)>0: newproto = Proto(str(node.getAttribute("name")),cprotos) else: newproto = Proto(str(node.getAttribute("name"))) if node.tagName == "fileEntry": pathdict.update({node.getAttribute("name"): { "path":node.getAttribute("fullpath"), "filetype": node.tagName }}) elif node.tagName == "dirEntry": pathdict.update({node.getAttribute("name"): { "path":node.getAttribute("name"), "filetype": node.tagName}}) else: pathdict.update({node.getAttribute("name"): { "path": "NOPATH", "filetype": node.tagName}}) self.createItem(newproto) return newproto def fromXML(self,text): doc = create_xml_doc(text) #node = doc.firstChild #node = doc.getElementById("topDirectory") nodes = doc.getElementsByTagName("dirEntry") node = nodes.item(0) s = repr(node) newproto = self.createProto(node) plist = [newproto] #plist = [Proto(node.tagName)] for i in range(len(plist)): num = str(len(plist)) # self.createItem(plist[i]) self.fTree.addItem(plist[i].item) plist[i].item.setState(True) def onShow(self): if False: for item in self.fTree.treeItemIterator(): key = repr(item.tree) if key != "null": item.setState(True) else: JS("alert(item.getText())") pass def createItem(self, proto): proto.item = TreeItem(proto.text) proto.item.setUserObject(proto) if len(proto.children) > 0: proto.item.addItem(PendingItem())
class PageBookComments: def onModuleLoad(self): # parse get data self.location = Window.getLocation().getHref() self.get_data = {} self.tmp = self.location.split('?') self.tmp = self.tmp[len(self.tmp) - 1].split("&") for e in self.tmp: get_var = e.split("=") if len(get_var) == 2: self.get_data[get_var[0]] = get_var[1] # JSON RPC response holders self.facebook_user = {} self.app_info = {} self.sellers = [] self.book = {} self.has_book = "none" # setup JSON RPC self.remote = DataService() self.remote.get_facebook_user(self) self.remote.get_app_info(self, "book_detail") if "asin" in self.get_data: self.remote.get_book_details(self, self.get_data["asin"]) self.remote.get_sellers(self, self.get_data["asin"]) self.remote.user_has_book(self, self.get_data["asin"]) # create panels self.main_panel = HorizontalPanel() self.info_panel = VerticalPanel() self.sell_btn_panel = VerticalPanel() self.wish_btn_panel = VerticalPanel() self.seller_panel = VerticalPanel() self.add_comment_panel = VerticalPanel() # images self.img_book_cover = Image() # html labels self.html_book_title = HTML() self.html_book_author = HTML() self.html_book_isbn10 = HTML() self.html_book_publisher = HTML() self.html_book_publish_date = HTML() self.html_book_edition = HTML() self.html_book_binding = HTML() self.html_btn_sell = HTML() self.html_btn_wish = HTML() self.html_seller_title = HTML() # check for no get data! if "asin" not in self.get_data: self.html_book_title.setHTML("<h1>Book not found!</h1>\n<p>The book you are looking for does not exist.</p>") self.info_panel.setWidth("100%") self.main_panel.setWidth("100%") self.info_panel.add(self.html_book_title) self.main_panel.add(self.info_panel) RootPanel("page_book_comments").add(self.main_panel) return # add to sellers panel self.seller_panel.add(self.html_seller_title) self.seller_panel.addStyleName("comments") self.info_panel.add(self.html_book_title) self.info_panel.add(self.html_book_author) self.info_panel.add(self.html_book_isbn10) self.info_panel.add(self.html_book_publisher) self.info_panel.add(self.html_book_publish_date) self.info_panel.add(self.html_book_edition) self.info_panel.add(self.html_book_binding) self.info_panel.add(self.add_comment_panel) self.info_panel.add(self.seller_panel) self.info_panel.addStyleName("info_panel") self.main_panel.add(self.info_panel) self.main_panel.add(self.img_book_cover) RootPanel("page_book_comments").add(self.main_panel) # spin until book info get here class SpinTimer(Timer): def __init__(self, max_tries = 10, interval = 500): Timer.__init__(self) self.interval = interval self.max_tries = max_tries self.tries = 0 self.func = func self.params = params self.scheduleRepeating(self.interval) def run(self): self.tries += 1 if self.tries >= self.max_tries: Window.alert("It looks like there's a connection problem. We're sorry about the inconvenience. Please try again later.") self.cancel() return if populate_book_details(): self.cancel() populate_book_details = self.populate_book_details st = SpinTimer() def populate_book_details(self): """ fill in book information on this page """ if len(self.facebook_user) == 0: return False if len(self.app_info) == 0: return False if len(self.book) == 0: return False if self.book['num_sellers'] != 0 and len(self.sellers) == 0: return False if 'title' not in self.book or 'binding' not in self.book: return False binding = "Hardcover" if self.book['binding'] != "Hardcover" and not self.book['binding']: binding = "Paperback" self.html_book_title.setHTML("<span class=\"title\">%s [%s]</span>" % (self.book['title'], binding)) if 'author' not in self.book: return False self.html_book_author.setHTML("<span class=\"author\">%s</span>" % self.book['author']) if 'isbn10' not in self.book: return False self.html_book_isbn10.setHTML("<span class=\"isbn\">ISBN 10: %s</span>" % self.book['isbn10']) # add these in #self.html_book_publisher.setHTML("<span class=\"info\">Publisher: %s</span>" % self.book['publisher']) #self.html_book_publish_date.setHTML("<span class=\"info\">Published: %s</span>" % self.book['publish_date']) if 'edition' not in self.book: return False self.html_book_edition.setHTML("<span class=\"info\">Edition: %s</span>" % self.book['edition']) if 'thumbnail' not in self.book: return False if self.book['thumbnail'] == "N/A": self.book['thumbnail'] = self.app_info['url'] + "static/images/default_thumbnail.png" self.img_book_cover.setUrl(self.book['thumbnail']) if 'num_sellers' not in self.book: return False amount = "amount_low" if int(self.book['num_sellers']) > 3: amount = "amount_medium" elif int(self.book['num_sellers']) > 7: amount = "amount_high" self.html_btn_sell.setHTML("<span class=\"num_sellers\">Sellers: <span class=\"%s\">%d</span></span>" % (amount, self.book['num_sellers'])) if 'num_watchers' not in self.book: return False amount = "amount_low" if int(self.book['num_watchers']) > 3: amount = "amount_medium" elif int(self.book['num_watchers']) > 7: amount = "amount_high" self.html_btn_wish.setHTML("<span class=\"num_watchers\">Watchers: <span class=\"%s\">%d</span></span>" % (amount, self.book['num_watchers'])) self.html_seller_title.setHTML("<h1>%s's Seller Activity for %s</h1>" % (self.facebook_user['first_name'], self.book['title'])) comments_url = self.app_info['url'] comments_url += "fbcommentsplugin?asin=" + self.get_data['asin'] comments_url += "&fbid=" + self.get_data['fbid'] self.frame_seller_comments = HTML('<div data-height="600px" class="fb-comments" data-num-posts="3" data-width="600"></div>') self.seller_panel.add(self.html_seller_title) self.seller_panel.add(self.frame_seller_comments) return True def onRemoteResponse(self, response, request_info): """ Called when a response is received from an RPC """ if not request_info.method in DataService.methods: Window.alert('Unrecognized JSONRPC method.') return if request_info.method == "get_facebook_user": self.facebook_user = {} for k, v in response.items(): self.facebook_user[k] = v elif request_info.method == "get_book_details": self.book = {} for k, v in response.items(): self.book[k] = v elif request_info.method == "get_app_info": self.app_info = {} for k, v in response.items(): self.app_info[k] = v elif request_info.method == "get_sellers": self.sellers = response elif request_info.method == "user_has_book": self.has_book = response["result"] def onRemoteError(self, code, message, request_info): """ Called when a returned response is invalid for Server Error """ code = str(code) message = str(message) if len(code) > 200: code = code[0:200] + "..." if len(message) > 200: message = message[0:200] + "..." err_msg = Label("Server Error or invalid response: ERROR " + str(code) + " - " + str(message)) err_msg.addStyleName("status") Window.alert(err_msg.getText())
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 MailList(Composite): VISIBLE_EMAIL_COUNT = 10 def __init__(self, mailObject): Composite.__init__(self) self.countLabel = HTML() self.newerButton = HTML("<a href='javascript:;'>< newer</a>", True) self.olderButton = HTML("<a href='javascript:;'>older ></a>", True) self.startIndex = 0 self.selectedRow = -1 self.table = FlexTable() self.navBar = HorizontalPanel() self.mailObject = mailObject # Setup the table. self.table.setCellSpacing(0) self.table.setCellPadding(2) self.table.setWidth("100%") # Hook up events. self.table.addTableListener(self) self.newerButton.addClickListener(self) self.olderButton.addClickListener(self) # Create the 'navigation' bar at the upper-right. innerNavBar = HorizontalPanel() innerNavBar.setSpacing(8) innerNavBar.add(self.newerButton) innerNavBar.add(self.countLabel) innerNavBar.add(self.olderButton) self.navBar.setStyleName("mail-ListNavBar") self.navBar.setHorizontalAlignment(HasAlignment.ALIGN_RIGHT) self.navBar.add(innerNavBar) self.navBar.setWidth("100%") self.initWidget(self.table) self.setStyleName("mail-List") self.initTable() self.update() def onCellDoubleClicked(self, sender, row, cell): pass def onCellClicked(self, sender, row, cell): # Select the row that was clicked (-1 to account for header row). if (row > 0): self.selectRow(row - 1) def onClick(self, sender): if (sender == self.olderButton): # Move forward a page. self.startIndex = self.startIndex + MailList.VISIBLE_EMAIL_COUNT if (self.startIndex >= MailItems().getMailItemCount()): self.startIndex = self.startIndex - MailList.VISIBLE_EMAIL_COUNT else: self.styleRow(self.selectedRow, False) self.selectedRow = -1 self.update() elif (sender == self.newerButton): # Move back a page. self.startIndex = self.startIndex - MailList.VISIBLE_EMAIL_COUNT if (self.startIndex < 0): self.startIndex = 0 else: self.styleRow(self.selectedRow, False) self.selectedRow = -1 self.update() def initTable(self): # Create the header row. self.table.setText(0, 0, "sender") self.table.setText(0, 1, "email") self.table.setText(0, 2, "subject") self.table.setWidget(0, 3, self.navBar) self.table.getRowFormatter().setStyleName(0, "mail-ListHeader") # Initialize the rest of the rows. i = 0 while i < MailList.VISIBLE_EMAIL_COUNT: self.table.setText(i + 1, 0, "") self.table.setText(i + 1, 1, "") self.table.setText(i + 1, 2, "") self.table.getCellFormatter().setWordWrap(i + 1, 0, False) self.table.getCellFormatter().setWordWrap(i + 1, 1, False) self.table.getCellFormatter().setWordWrap(i + 1, 2, False) self.table.getFlexCellFormatter().setColSpan(i + 1, 2, 2) i = i + 1 def selectRow(self, row): # When a row (other than the first one, which is used as a header) is # selected, display its associated MailItem. item = MailItems().getMailItem(self.startIndex + row) if item is None: return self.styleRow(self.selectedRow, False) self.styleRow(row, True) item.read = True self.selectedRow = row self.mailObject.get().displayItem(item) def styleRow(self, row, selected): if (row != -1): if (selected): self.table.getRowFormatter().addStyleName(row + 1, "mail-SelectedRow") else: self.table.getRowFormatter().removeStyleName(row + 1, "mail-SelectedRow") def update(self): # Update the older/newer buttons & label. count = MailItems().getMailItemCount() max = self.startIndex + MailList.VISIBLE_EMAIL_COUNT if (max > count): max = count self.newerButton.setVisible(self.startIndex != 0) self.olderButton.setVisible(self.startIndex + MailList.VISIBLE_EMAIL_COUNT < count) startIndexPlusOne = self.startIndex + 1 self.countLabel.setText("%d - %d of %d" % (startIndexPlusOne, max, count)) # Show the selected emails. i = 0 while (i < MailList.VISIBLE_EMAIL_COUNT): # Don't read past the end. if (self.startIndex + i >= MailItems().getMailItemCount()): break item = MailItems().getMailItem(self.startIndex + i) # Add a row to the table, then set each of its columns to the # email's sender and subject values. self.table.setText(i + 1, 0, item.sender) self.table.setText(i + 1, 1, item.email) self.table.setText(i + 1, 2, item.subject) i = i + 1 # Clear any remaining slots. while (i < MailList.VISIBLE_EMAIL_COUNT): self.table.setHTML(i + 1, 0, " ") self.table.setHTML(i + 1, 1, " ") self.table.setHTML(i + 1, 2, " ") i = i + 1 # Select the first row if none is selected. if (self.selectedRow == -1): self.selectRow(0)
class PageIndex: def onModuleLoad(self): # JSON RPC response containers self.facebook_user = {} self.app_info = {} self.wl_books = [] self.sl_books = [] self.events = [] # setup JSON RPC self.remote = DataService() # make JSON RPC calls self.remote.get_app_info(self, "index") self.remote.get_wish_list(self) self.remote.get_sell_list(self) self.remote.get_events(self, 10) # panels self.main_panel = HorizontalPanel() self.feed_panel = VerticalPanel() self.list_panel = VerticalPanel() self.feed_panel.addStyleName("feed_panel") self.list_panel.addStyleName("list_panel") # labels self.html_feed_title = HTML("<h1>Recent Activity</h1>") self.html_wish_title = HTML("<h1>Your Wishlist</h1>") self.html_sell_title = HTML("<h1>Your Selllist</h1>") # user lists self.wish_list = UserList("wish", self) self.sell_list = UserList("sell", self) self.wish_list.addStyleName("userlist") self.sell_list.addStyleName("userlist") self.feed_panel.add(self.html_feed_title) self.list_panel.add(self.html_wish_title) self.list_panel.add(self.wish_list) self.list_panel.add(HTML("<br />")) self.list_panel.add(self.html_sell_title) self.list_panel.add(self.sell_list) # add everything together self.main_panel.add(self.feed_panel) self.main_panel.add(self.list_panel) self.main_panel.setWidth("100%") RootPanel("page_index").add(self.main_panel) show_events = self.show_events class EventTimer(Timer): def run(self): show_events() et = EventTimer() self.show_events() et.scheduleRepeating(5000) def populate_book_lists(self): """ check the JSON RPC containers and fill the UserLists if it finds them to be non-empty """ for b in self.wl_books: Window.alert(str(b)) self.wish_list.add_book(b) for b in self.sl_books: self.sell_list.add_book(b) return True def show_events(self): """ create events on the recent activity feed """ for e in self.events: self.add_event(e) self.events = [] def add_event(self, event): """ add an event to the recent activity feed """ event_panel = HorizontalPanel() mid_panel = VerticalPanel() book_panel = HorizontalPanel() # profile picture pic_url = "https://graph.facebook.com/" + event['fbid'] + "/picture" pic_html = HTML("<img src=\"%s\" />" % pic_url) # event string event_html = HTML("<span style=\"font-weight: bold\">%s</span>" % event['string']) url = self.app_info['url'] + "book?asin=" + event['book']['asin'] cutoff = 40 # book thumbnail img_url = event['book']['thumbnail'] if event['book']["thumbnail"] == "N/A": img_url = self.app_info['url'] + "static/images/default_thumbnail.png" img_html = HTML("<a href=\"%s\" target=\"_top\"><img src=\"%s\" /></a>" % (url, img_url)) # handle book information title = event['book']['title'] author = event['book']['author'] isbn = event['book']['isbn10'] if len(title) > cutoff: title = title[0:cutoff] + "..." if len(author) > cutoff: author = author[0:cutoff] + "..." if len(isbn) > cutoff: isbn = isbn[0:cutoff] + "..." html = "<a href=\"%s\" target=\"_top\"><span style=\"font-weight: bold\">%s</span></a><br />" % (url, title) html += "<span style=\"font-weight: bold; color: #6C82AF;\">ISBN-10: %s</span><br />" % isbn html += "<span style=\"font-weight: bold; color: #7D7D7D;\">%s</span><br />" % author html_entry = HTML(html) book_panel.add(img_html) book_panel.add(html_entry) mid_panel.add(event_html) mid_panel.add(book_panel) event_panel.add(pic_html) event_panel.add(mid_panel) # html = "<span style=\"text-align: right; width: 100%; display: block;\">%s</span><hr />" % unicode(event['time']) # event_panel.add(HTML(html)) self.feed_panel.add(event_panel) def onRemoteResponse(self, response, request_info): """ Called when a response is received from an RPC """ if request_info.method == "get_facebook_user": for k, v in response.items(): self.facebook_user[k] = v elif request_info.method == "get_app_info": for k, v in response.items(): self.app_info[k] = v elif request_info.method == "get_wish_list": self.wl_books = response for b in self.wl_books: self.wish_list.add_book(b) elif request_info.method == "get_sell_list": self.sl_books = response for b in self.sl_books: self.sell_list.add_book(b) elif request_info.method == "add_event": self.events.append(response) elif request_info.method == "get_events": self.events = response def onRemoteError(self, code, message, request_info): """ Called when a returned response is invalid or Server Error """ code = str(code) message = str(message) if len(code) > 200: code = code[0:200] + "..." if len(message) > 200: message = message[0:200] + "..." err_msg = Label("Server Error or invalid response: ERROR " + str(code) + " - " + str(message)) err_msg.addStyleName("status") Window.alert(err_msg.getText())