Exemplo n.º 1
0
    def StatusTextChange(self, status):
        if self.visible:
            if self.drivingMoz:
                internaljumpPrefix = u"file://internaljump/wikipage/"
            else:
                internaljumpPrefix = u"http://internaljump/wikipage/"

            if status.startswith(internaljumpPrefix):
                # First check for an anchor. In URLs, anchors are always
                # separated by '#' regardless which character is used
                # in the wiki syntax (normally '!')
                try:
                    wikiWord, anchor = status[len(internaljumpPrefix):].split(
                            u"#", 1)
                    anchor = flexibleUrlUnquote(anchor)
                except ValueError:
                    wikiWord = status[len(internaljumpPrefix):]
                    anchor = None
                    
                wikiWord = flexibleUrlUnquote(wikiWord)

                wikiDocument = self.presenter.getWikiDocument()
                if wikiDocument is None:
                    return
                    
                wikiWord = wikiDocument.getWikiPageNameForLinkTerm(wikiWord)

                if wikiWord is not None:
                    status = _(u"Link to page: %s") % wikiWord

            self.presenter.getMainControl().statusBar.SetStatusText(
                    uniToGui(status), 0)
Exemplo n.º 2
0
    def StatusTextChange(self, status):
        if self.visible:
            if self.drivingMoz:
                internaljumpPrefix = u"file://internaljump/wikipage/"
            else:
                internaljumpPrefix = u"http://internaljump/wikipage/"

            if status.startswith(internaljumpPrefix):
                # First check for an anchor. In URLs, anchors are always
                # separated by '#' regardless which character is used
                # in the wiki syntax (normally '!')
                try:
                    wikiWord, anchor = status[len(internaljumpPrefix):].split(
                        u"#", 1)
                    anchor = flexibleUrlUnquote(anchor)
                except ValueError:
                    wikiWord = status[len(internaljumpPrefix):]
                    anchor = None

                wikiWord = flexibleUrlUnquote(wikiWord)

                wikiDocument = self.presenter.getWikiDocument()
                if wikiDocument is None:
                    return

                wikiWord = wikiDocument.getWikiPageNameForLinkTerm(wikiWord)

                if wikiWord is not None:
                    status = _(u"Link to page: %s") % wikiWord

            self.presenter.getMainControl().statusBar.SetStatusText(
                uniToGui(status), 0)
Exemplo n.º 3
0
    def OnMouseMotion(self, evt):
        evt.Skip()

        pos = self.CalcUnscrolledPosition(evt.GetPosition())
        irep = self.GetInternalRepresentation()
        if irep is None:
            cell = None
        else:
            cell = irep.FindCellByPos(pos.x, pos.y)
        callTip = u""
        status = u""

        if cell is not None:
            linkInfo = cell.GetLink()
            if linkInfo is not None:
                href = linkInfo.GetHref()
                if href.startswith(u"internaljump:wikipage/"):
                    # Jump to another wiki page

                    # First check for an anchor. In URLs, anchors are always
                    # separated by '#' regardless which character is used
                    # in the wiki syntax (normally '!')
                    try:
                        wikiWord, anchor = href[22:].split(u"#", 1)
                        anchor = flexibleUrlUnquote(anchor)
                    except ValueError:
                        wikiWord = href[22:]
                        anchor = None

                    wikiWord = flexibleUrlUnquote(wikiWord)

                    wikiDocument = self.presenter.getWikiDocument()
                    if wikiDocument is None:
                        return
                    wikiWord = wikiDocument.getWikiPageNameForLinkTerm(
                        wikiWord)

                    if wikiWord is not None:
                        propList = wikiDocument.getAttributeTriples(
                            wikiWord, u"short_hint", None)

                        if len(propList) > 0:
                            callTip = propList[-1][2]

                        status = _(u"Link to page: %s") % wikiWord
                else:
                    status = href

        self.presenter.getMainControl().statusBar.SetStatusText(
            uniToGui(status), 0)

        self.SetToolTipString(callTip)
Exemplo n.º 4
0
    def OnMouseMotion(self, evt):
        evt.Skip()

        pos = self.CalcUnscrolledPosition(evt.GetPosition())
        irep = self.GetInternalRepresentation()
        if irep is None:
            cell = None
        else:
            cell = irep.FindCellByPos(pos.x, pos.y)
        callTip = u""
        status = u""

        if cell is not None:
            linkInfo = cell.GetLink()
            if linkInfo is not None:
                href = linkInfo.GetHref()
                if href.startswith(u"internaljump:wikipage/"):
                    # Jump to another wiki page
                    
                    # First check for an anchor. In URLs, anchors are always
                    # separated by '#' regardless which character is used
                    # in the wiki syntax (normally '!')
                    try:
                        wikiWord, anchor = href[22:].split(u"#", 1)
                        anchor = flexibleUrlUnquote(anchor)
                    except ValueError:
                        wikiWord = href[22:]
                        anchor = None

                    wikiWord = flexibleUrlUnquote(wikiWord)
                    
                    wikiDocument = self.presenter.getWikiDocument()
                    if wikiDocument is None:
                        return
                    wikiWord = wikiDocument.getWikiPageNameForLinkTerm(wikiWord)

                    if wikiWord is not None:
                        propList = wikiDocument.getAttributeTriples(wikiWord,
                                u"short_hint", None)

                        if len(propList) > 0:
                            callTip = propList[-1][2]
                        
                        status = _(u"Link to page: %s") % wikiWord
                else:
                    status = href

        self.presenter.getMainControl().statusBar.SetStatusText(
                        uniToGui(status), 0)

        self.SetToolTipString(callTip)
Exemplo n.º 5
0
 def _showInfo(self, msg):
     """
     Set dialog controls to show an info/error message
     """
     
     self.ctrls.tfToCheck.SetValue("")
     # Show message in blue
     self.ctrls.tfToCheck.SetDefaultStyle(wx.TextAttr(wx.BLUE))
     self.ctrls.tfToCheck.AppendText(uniToGui(msg))
     self.ctrls.tfToCheck.SetDefaultStyle(wx.TextAttr(wx.BLACK))
     # To scroll text to beginning
     self.ctrls.tfToCheck.SetInsertionPoint(0)
     self.ctrls.tfReplaceWith.SetValue(u"")
     self.ctrls.lbReplaceSuggestions.DeleteAllItems()
     
     self.ctrls.tfReplaceWith.SetFocus()
Exemplo n.º 6
0
class WikiHtmlView(wx.html.HtmlWindow):
    def __init__(self, presenter, parent, ID):
        wx.html.HtmlWindow.__init__(self, parent, ID)
        self.presenter = presenter

        self.presenterListener = wxKeyFunctionSink((
                ("loaded current wiki page", self.onLoadedCurrentWikiPage),
                ("reloaded current doc page", self.onReloadedCurrentPage),
                ("opened wiki", self.onOpenedWiki),
                ("closing current wiki", self.onClosingCurrentWiki)
        ), self.presenter.getMiscEvent())
        
        self.__sinkApp = wxKeyFunctionSink((
                ("options changed", self.onOptionsChanged),
        ), wx.GetApp().getMiscEvent())
        
        self.__sinkDocPage = wxKeyFunctionSink((
                ("updated wiki page", self.onUpdatedWikiPage),
                ("changed live text", self.onChangedLiveText)
        ), self.presenter.getCurrentDocPageProxyEvent())

        self.visible = False
        self.outOfSync = True   # HTML content is out of sync with live content
        self.counterResizeIgnore = 0  # How often to ignore a size event
        self.deferredScrollPos = None  # Used by scrollDeferred()

        self.currentLoadedWikiWord = None

        self.anchor = None  # Name of anchor to jump to when view gets visible
        self.contextHref = None  # Link href on which context menu was opened
        
        # TODO Should be changed to presenter as controller
        self.exporterInstance = PluginManager.getExporterTypeDict(
                self.presenter.getMainControl(), False)[u"html_single"][0]\
                (self.presenter.getMainControl())

        self._DEFAULT_FONT_SIZES = self.presenter.getMainControl().presentationExt.INTHTML_FONTSIZES
        
        # TODO More elegantly
        self.exporterInstance.exportType = u"html_previewWX"
        self.exporterInstance.styleSheet = u""
        self.exporterInstance.tempFileSet = TempFileSet()
        self._updateTempFilePrefPath()

        self.exporterInstance.setWikiDocument(
                self.presenter.getWikiDocument())
        self.exporterInstance.setLinkConverter(
                LinkConverterForPreview(self.presenter.getWikiDocument()))

        wx.EVT_KEY_DOWN(self, self.OnKeyDown)
        wx.EVT_KEY_UP(self, self.OnKeyUp)
        wx.EVT_SIZE(self, self.OnSize)

        wx.EVT_MENU(self, GUI_ID.CMD_CLIPBOARD_COPY, self.OnClipboardCopy)
        wx.EVT_MENU(self, GUI_ID.CMD_SELECT_ALL, lambda evt: self.SelectAll())
        wx.EVT_MENU(self, GUI_ID.CMD_ZOOM_IN, lambda evt: self.addZoom(1))
        wx.EVT_MENU(self, GUI_ID.CMD_ZOOM_OUT, lambda evt: self.addZoom(-1))
        wx.EVT_MENU(self, GUI_ID.CMD_ACTIVATE_THIS, self.OnActivateThis)        
        wx.EVT_MENU(self, GUI_ID.CMD_ACTIVATE_NEW_TAB_THIS,
                self.OnActivateNewTabThis)
        wx.EVT_MENU(self, GUI_ID.CMD_ACTIVATE_NEW_TAB_BACKGROUND_THIS,
                self.OnActivateNewTabBackgroundThis)
        wx.EVT_MENU(self, GUI_ID.CMD_ACTIVATE_NEW_WINDOW_THIS,
                self.OnActivateNewWindowThis)

        wx.EVT_MENU(self, GUI_ID.CMD_OPEN_CONTAINING_FOLDER_THIS,
                self.OnOpenContainingFolderThis)

        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        wx.EVT_LEFT_DCLICK(self, self.OnLeftDClick)
        wx.EVT_MIDDLE_DOWN(self, self.OnMiddleDown)
        wx.EVT_MOUSEWHEEL(self, self.OnMouseWheel)
        wx.EVT_MOTION(self, self.OnMouseMotion)


    def setLayerVisible(self, vis, scName=""):
        """
        Informs the widget if it is really visible on the screen or not
        """
        if not self.visible and vis:
            self.outOfSync = True   # Just to be sure
            self.refresh()
            
        if not vis:
            self.exporterInstance.tempFileSet.clear()

        self.visible = vis



    if isWindows():
        _RE_RIGHT_FILE_URL = re.compile(u"file:/[a-zA-Z]:")
        
        def OnOpeningURL(self, typ, url):
            if url.startswith("file:"):
                if self._RE_RIGHT_FILE_URL.match(url):
                    return wx.html.HTML_OPEN
                # At least under Windows, wxWidgets has another
                # opinion how a local file URL should look like
                # than Python.
                # The same processing is done already by the exporter
                # for WikidPad URL but not for URLs in HTML tags. 
                p = pathnameFromUrl(url)
                url = wx.FileSystem.FileNameToURL(p)
                return url
    
            return wx.html.HTML_OPEN


    def close(self):
        self.Unbind(wx.EVT_SET_FOCUS)
        self.setLayerVisible(False)
        self.presenterListener.disconnect()
        self.__sinkApp.disconnect()
        self.__sinkDocPage.disconnect()


# This doesn't work for wxPython 2.8 and newer, constants are missing
#     _DEFAULT_FONT_SIZES = (wx.html.HTML_FONT_SIZE_1, wx.html.HTML_FONT_SIZE_2, 
#             wx.html.HTML_FONT_SIZE_3, wx.html.HTML_FONT_SIZE_4,
#             wx.html.HTML_FONT_SIZE_5, wx.html.HTML_FONT_SIZE_6,
#             wx.html.HTML_FONT_SIZE_7)

    # These are the Windows sizes
#     if isWindows():
#         _DEFAULT_FONT_SIZES = (7, 8, 10, 12, 16, 22, 30)
#     elif isOSX():
#         _DEFAULT_FONT_SIZES = (9, 12, 14, 18, 24, 30, 36)
#     else:
#         _DEFAULT_FONT_SIZES = (10, 12, 14, 16, 19, 24, 32)




    # For __WXGPE__ (?)
    # _DEFAULT_FONT_SIZES = (6, 7, 8, 9, 10, 12, 14)
    # For others
    # _DEFAULT_FONT_SIZES = (10, 12, 14, 16, 19, 24, 32)


    def refresh(self):
        ## _prof.start()
        
        # Store position of currently displayed page, if any
        if self.currentLoadedWikiWord:
            try:
                prevPage = self.presenter.getWikiDocument().getWikiPage(
                        self.currentLoadedWikiWord)
                prevPage.setPresentation(self.getIntendedViewStart(), 3)
            except WikiWordNotFoundException, e:
                pass

        wikiPage = self.presenter.getDocPage()
        if isinstance(wikiPage,
                (DocPages.DataCarryingPage, DocPages.AliasWikiPage)) and \
                not wikiPage.checkFileSignatureAndMarkDirty():
            # Valid wiki page and invalid signature -> rebuild HTML page
            self.outOfSync = True

        if self.outOfSync:
            self.currentLoadedWikiWord = None
    
            if wikiPage is None:
                return  # TODO Do anything else here?
                
            word = wikiPage.getWikiWord()
            if word is None:
                return  # TODO Do anything else here?

            # Remove previously used temporary files
            self.exporterInstance.tempFileSet.clear()
            self.exporterInstance.buildStyleSheetList()

            self.currentLoadedWikiWord = word
#             content = self.presenter.getLiveText()

            html = self.exporterInstance.exportWikiPageToHtmlString(wikiPage)

            wx.GetApp().getInsertionPluginManager().taskEnd()

    
            # TODO Reset after open wiki
            zoom = self.presenter.getConfig().getint("main", "preview_zoom", 0)
            lx, ly = self.getIntendedViewStart()
            self.SetFonts("", "", [max(s + 2 * zoom, 1)
                    for s in self._DEFAULT_FONT_SIZES])
                    
#             print "-- refresh8", html.encode("mbcs", "ignore")
            self.SetPage(uniToGui(html))
            self.scrollDeferred(lx, ly)

#         traceback.print_stack()
        if self.anchor:   #  and self.HasAnchor(self.anchor):
            if self.HasAnchor(self.anchor):
                self.ScrollToAnchor(self.anchor)
                # Workaround because ScrollToAnchor scrolls too far
                # Here the real scroll position is needed so
                # getIntendedViewStart() is not called
                lx, ly = self.GetViewStart()
                self.scrollDeferred(lx, ly-1)
            else:
                self.scrollDeferred(0, 0)
        elif self.outOfSync:
            lx, ly = wikiPage.getPresentation()[3:5]
            self.scrollDeferred(lx, ly)

        self.anchor = None
        self.outOfSync = False
Exemplo n.º 7
0
    def checkNext(self, startPos=0):
        activeEditor = self.mainControl.getActiveEditor()
        startWikiWord = self.mainControl.getCurrentWikiWord()

        if startWikiWord is None:
            # No wiki loaded or no wiki word in editor
            self._showInfo(
                    _(u"No wiki open or current page is a functional page"))
            return False

        startWikiWord = self.mainControl.getWikiDocument()\
                .getWikiPageNameForLinkTermOrAsIs(startWikiWord)

        firstCheckedWikiWord = startWikiWord

        if not self.mainControl.getWikiDocument().isDefinedWikiPageName(
                firstCheckedWikiWord):

            # This can happen if startWikiWord is a newly created, not yet
            # saved page
            if not self.ctrls.cbGoToNextPage.GetValue():
                self._showInfo(_(u"Current page is not modified yet"))
                return False

            firstCheckedWikiWord = self.session.findAndLoadNextWikiPage(None,
                    firstCheckedWikiWord)
                    
            if firstCheckedWikiWord is None:
                self._showInfo(_(u"No (more) misspelled words found"))
                return False

        else:
            self.session.setCurrentDocPage(
                    self.mainControl.getWikiDocument().getWikiPage(
                    firstCheckedWikiWord))

            if not self.session.hasEnchantDict():
                if firstCheckedWikiWord == startWikiWord:
                    self._showInfo(_(u"No dictionary found for this page"))
                    return False  # No dictionary


        checkedWikiWord = firstCheckedWikiWord

        langHelper = wx.GetApp().createWikiLanguageHelper(
                self.session.getCurrentDocPage().getWikiLanguageName())

        text = activeEditor.GetText()

        self.ctrls.tfToCheck.SetValue("")

        while True:
            start, end, spWord = langHelper.findNextWordForSpellcheck(text,
                    startPos, self.session.getCurrentDocPage())

            if start is None:
                # End of page reached
                if self.ctrls.cbGoToNextPage.GetValue():
                    checkedWikiWord = self.session.findAndLoadNextWikiPage(
                            firstCheckedWikiWord, checkedWikiWord)
                    
                    if checkedWikiWord is None:
                        self._showInfo(_(u"No (more) misspelled words found"))
                        return False

                    text = self.mainControl.getWikiDocument()\
                            .getWikiPage(checkedWikiWord).getLiveText()
                    startPos = 0
                    continue
                else:
                    self._showInfo(_(u"No (more) misspelled words found"))
                    return False

            if self.session.checkWord(spWord):
                # Ignore if word is in the ignore lists or is seen as correct
                # by the spell checker

                startPos = end
                continue

            if self.session.getAutoReplaceWords().has_key(spWord):
                activeEditor.showSelectionByCharPos(start, end)
                activeEditor.ReplaceSelection(
                        self.session.getAutoReplaceWords()[spWord])
                startPos = activeEditor.GetSelectionCharPos()[1]
                continue

            break


        if startWikiWord != checkedWikiWord:
            # The search went on to another word, so load it into editor
            self.mainControl.openWikiPage(checkedWikiWord)

        self.currentCheckedWord = spWord
        self.currentStart = start
        self.currentEnd = end

        activeEditor.showSelectionByCharPos(start, end)

        conStart = max(0, start - 30)

        contextPre = text[conStart:start]
        contextPost = text[end:end+60]
        
        contextPre = contextPre.split(u"\n")[-1]
        contextPost = contextPost.split(u"\n", 1)[0]

        # Show misspelled word in context
        self.ctrls.tfToCheck.SetDefaultStyle(wx.TextAttr(wx.BLACK))
        self.ctrls.tfToCheck.AppendText(contextPre)
        self.ctrls.tfToCheck.SetDefaultStyle(wx.TextAttr(wx.RED))
        self.ctrls.tfToCheck.AppendText(spWord)
        self.ctrls.tfToCheck.SetDefaultStyle(wx.TextAttr(wx.BLACK))
        self.ctrls.tfToCheck.AppendText(contextPost)
        # To scroll text to beginning
        self.ctrls.tfToCheck.SetInsertionPoint(0)
        
        # List suggestions
        sugglist = self.session.suggest(spWord)
        
        self.ctrls.lbReplaceSuggestions.DeleteAllItems()
        for s in sugglist:
            self.ctrls.lbReplaceSuggestions.InsertStringItem(
                    self.ctrls.lbReplaceSuggestions.GetItemCount(), s)
#         self.ctrls.lbReplaceSuggestions.SetColumnWidth(0, wx.LIST_AUTOSIZE)
        autosizeColumn(self.ctrls.lbReplaceSuggestions, 0)

        if len(sugglist) > 0:
            self.ctrls.tfReplaceWith.SetValue(uniToGui(sugglist[0]))
        else:
            self.ctrls.tfReplaceWith.SetValue(uniToGui(spWord))

        self.ctrls.tfReplaceWith.SetFocus()

        return True
Exemplo n.º 8
0
 def SetStatusText(self, text, field):
     self.getStatusBar().SetStatusText(uniToGui(text), field)
Exemplo n.º 9
0
    def openWikiPage(self, wikiWord, addToHistory=True,
            forceTreeSyncFromRoot=False, forceReopen=False,
            suggNewPageTitle=None, **evtprops):
        """
        Opens a wiki page in the editor of this presenter
        """
        if not self.getMainControl().requireReadAccess():
            return

#         oldPage = self.getDocPage()

        evtprops["addToHistory"] = addToHistory
        evtprops["forceTreeSyncFromRoot"] = forceTreeSyncFromRoot

        langHelper = wx.GetApp().createWikiLanguageHelper(
                self.getWikiDocument().getWikiDefaultWikiLanguage())

        errMsg = None

        # The "if" ensures that existing pages can be opened even
        # if the syntax is (or became) incompatible
        if not self.getWikiDocument().isDefinedWikiPageName(wikiWord):
            errMsg = langHelper.checkForInvalidWikiWord(wikiWord,
                    self.getWikiDocument())

        if errMsg is not None:
            self.getMainControl().displayErrorMessage(
                    _(u"'%s' is an invalid wiki word. %s.") % (wikiWord, errMsg))
            return
            
        try:
            # don't reopen the currently open page, only send an event
            if (wikiWord == self.getWikiWord()) and not forceReopen:
                p2 = evtprops.copy()
                p2.update({"reloaded current doc page": True,
                        "reloaded current wiki page": True})
                self.fireMiscEventProps(p2)

                if forceTreeSyncFromRoot:
                    self.getMainControl().findCurrentWordInTree()
                return

            # trigger hook
            self.getMainControl().hooks.openWikiWord(self, wikiWord)

            # check if this is an alias
            wikiDoc = self.getMainControl().getWikiDocument()
            wikiWord = wikiDoc.getWikiPageNameForLinkTermOrAsIs(wikiWord)

            # fetch the page info from the database
            try:
                page = wikiDoc.getWikiPage(wikiWord)
#                 self.getStatusBar().SetStatusText(uniToGui(_(u"Opened wiki word '%s'") %
#                         wikiWord), 0)

            except (WikiWordNotFoundException, WikiFileNotFoundException), e:
                page = wikiDoc.createWikiPage(wikiWord,
                        suggNewPageTitle=suggNewPageTitle)
                # trigger hooks
                self.getMainControl().hooks.newWikiWord(self, wikiWord)
                self.showStatusMessage(
                        uniToGui(_(u"Wiki page not found, a new "
                        u"page will be created")))
#                 self.getStatusBar().SetStatusText(uniToGui(u""), 1)

            self.loadWikiPage(page, **evtprops)
            page.informVisited()

            # sync the tree
            if forceTreeSyncFromRoot:
                self.getMainControl().findCurrentWordInTree()  # TODO ?