コード例 #1
0
    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)
コード例 #2
0
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())
コード例 #3
0
ファイル: InfoDirectory.py プロジェクト: pombredanne/pyjamas
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("&nbsp;")

        self.midpanel = MidPanel(self)
        self.cp2 = CollapserPanel(self)
        self.cp2.setWidget(self.midpanel)
        self.cp2.setHTML("&nbsp;")

        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("&nbsp;")

    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))
コード例 #4
0
ファイル: Showcase.py プロジェクト: Afey/pyjs
    def onModuleLoad(self):
        """ Dynamically build our user interface when the web page is loaded.
        """
        self._root        = RootPanel()
        self._tree        = Tree()
        self._rightPanel  = SimplePanel()
        self._curContents = None

        intro = HTML('<h3>Welcome to the Pyjamas User Interface Showcase</h3>'+
                     '<p/>Please click on an item to start.')

        self._introPanel = VerticalPanel()
        self._introPanel.add(uiHelpers.indent(intro, left=20))

        self._demos = [] # List of all installed demos.  Each item in this list
                         # is a dictionary with the following entries:
                         #
                         #     'name'
                         #
                         #         The name for this demo.
                         #
                         #     'section'
                         #
                         #         The name of the section of the demo tree
                         #         this demo should be part of.
                         #
                         #     'doc'
                         #
                         #         The documentation for this demo.
                         #
                         #     'src'
                         #
                         #         The source code for this demo.
                         #
                         #     'example'
                         #
                         #         The Panel which holds the example output for
                         #         this demo.

        self.loadDemos()
        self.buildTree()

        self._tree.setSize("0%", "100%")

        divider = VerticalPanel()
        divider.setSize("1px", "100%")
        divider.setBorderWidth(1)

        scroller = ScrollPanel(self._rightPanel)
        scroller.setSize("100%", "100%")

        hPanel = HorizontalPanel()
        hPanel.setSpacing(4)

        hPanel.add(self._tree)
        hPanel.add(divider)
        hPanel.add(scroller)

        hPanel.setHeight("100%")
        self._root.add(hPanel)

        self._tree.addTreeListener(self)
        self.showDemo(None)
コード例 #5
0
ファイル: RichTextToolbar.py プロジェクト: minghuascode/pyj
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()
コード例 #6
0
ファイル: resgen_web.py プロジェクト: johnpeck/resgen
    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)

コード例 #7
0
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("&nbsp;")


        self.midpanel = MidPanel(self)
        self.cp2 = CollapserPanel(self)
        self.cp2.setWidget(self.midpanel)
        self.cp2.setHTML("&nbsp;")

        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("&nbsp;")

    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))
コード例 #8
0
ファイル: RichTextToolbar.py プロジェクト: Afey/pyjs
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()
コード例 #9
0
ファイル: Showcase.py プロジェクト: minghuascode/pyj
    def onModuleLoad(self):
        """ Dynamically build our user interface when the web page is loaded.
        """
        self._root = RootPanel()
        self._tree = Tree()
        self._rightPanel = SimplePanel()
        self._curContents = None

        intro = HTML(
            '<h3>Welcome to the Pyjamas User Interface Showcase</h3>' +
            '<p/>Please click on an item to start.')

        self._introPanel = VerticalPanel()
        self._introPanel.add(uiHelpers.indent(intro, left=20))

        self._demos = [
        ]  # List of all installed demos.  Each item in this list
        # is a dictionary with the following entries:
        #
        #     'name'
        #
        #         The name for this demo.
        #
        #     'section'
        #
        #         The name of the section of the demo tree
        #         this demo should be part of.
        #
        #     'doc'
        #
        #         The documentation for this demo.
        #
        #     'src'
        #
        #         The source code for this demo.
        #
        #     'example'
        #
        #         The Panel which holds the example output for
        #         this demo.

        self.loadDemos()
        self.buildTree()

        self._tree.setSize("0%", "100%")

        divider = VerticalPanel()
        divider.setSize("1px", "100%")
        divider.setBorderWidth(1)

        scroller = ScrollPanel(self._rightPanel)
        scroller.setSize("100%", "100%")

        hPanel = HorizontalPanel()
        hPanel.setSpacing(4)

        hPanel.add(self._tree)
        hPanel.add(divider)
        hPanel.add(scroller)

        hPanel.setHeight("100%")
        self._root.add(hPanel)

        self._tree.addTreeListener(self)
        self.showDemo(None)
コード例 #10
0
ファイル: RichTextEditor.py プロジェクト: Afey/pyjs
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())