示例#1
0
	def initialize(self):
		logging.debug("PropertyManager.initialize: starting")
		self.__setUiLanguage()

		DivvunHandlePool.getInstance().setGlobalBooleanOption(PropertyManager.DIVVUN_OPT_IGNORE_DOT, True)
		DivvunHandlePool.getInstance().setGlobalBooleanOption(PropertyManager.DIVVUN_OPT_NO_UGLY_HYPHENATION, True)

		# Set these options globally until OOo bug #97945 is resolved.
		DivvunHandlePool.getInstance().setGlobalBooleanOption(PropertyManager.DIVVUN_OPT_ACCEPT_TITLES_IN_GC, True)
		DivvunHandlePool.getInstance().setGlobalBooleanOption(PropertyManager.DIVVUN_OPT_ACCEPT_BULLETED_LISTS_IN_GC, True)

		DivvunHandlePool.getInstance().setGlobalBooleanOption(PropertyManager.DIVVUN_OPT_ACCEPT_UNFINISHED_PARAGRAPHS_IN_GC, True)

		compContext = uno.getComponentContext()
		servManager = compContext.ServiceManager
		self.__linguPropSet = servManager.createInstanceWithContext("com.sun.star.linguistic2.LinguProperties", compContext)
		self.__linguPropSet.addPropertyChangeListener("IsSpellWithDigits", self)
		self.__linguPropSet.addPropertyChangeListener("IsSpellUpperCase", self)
		logging.debug("PropertyManager.initialize: property manager initalized")

		# synchronize the local settings from global preferences
		self.__setProperties(self.__linguPropSet)
		self.readDivvunSettings()
		# request that all users of linguistic services run the spellchecker and hyphenator
		# again with updated settings
		event = LinguServiceEvent()
		event.nEvent = SPELL_CORRECT_WORDS_AGAIN | SPELL_WRONG_WORDS_AGAIN | HYPHENATE_AGAIN | PROOFREAD_AGAIN
		self.__sendLinguEvent(event)
示例#2
0
def getToggleIds():		# type: () -> Dict[str, str]
	"""Return the toggleIds of currently opened checker handles.

Don't cache this – the result may change if more handles (checkers)
are loaded (and if UI locale changes, though that's not too bad)

	"""
	toggleIds = {}		# type: Dict[str, str]
	uilocale = getUILocale()
	logging.info("KBU: uilocale {}".format(uilocale))
	pool = DivvunHandlePool.getInstance()
	handles = pool.getOpenHandles()
	for checklang, checker in handles.items():
		prefs = libdivvun.prefs_bytes(checker).asdict()
		logging.info("KBU: prefs of checker for lang {} has pref l18n langs {}".format(checklang, prefs.keys()))
		# First add explanations from the other languages,
		# then those of the checker, then the UI language, so
		# the UI and checker language explanations are
		# preferred:
		p_uilang, p_notui = partition(prefs.items(), lambda lp: lp[0] == uilocale.Language)
		p_checklang, p_notcheckui = partition(p_notui, lambda lp: lp[0] == checklang)
		logging.info("KBU: prefs of checker for lang {} has p_uilang {}".format(checklang, p_uilang))
		logging.info("KBU: prefs of checker for lang {} has p_checklang {}".format(checklang, p_checklang))
		logging.info("KBU: prefs of checker for lang {} has p_notcheckui {}".format(checklang, p_notcheckui))
		for _l, p in p_notcheckui:
			toggleIds.update(p.toggleIds.asdict())
		for _l, p in p_checklang:
			toggleIds.update(p.toggleIds.asdict())
		for _l, p in p_uilang:
			toggleIds.update(p.toggleIds.asdict())
		logging.info("KBU: prefs of checker for lang {} has toggleIds {}".format(checklang, toggleIds))
	# Remove empty ones, just confusing:
	return { err:msg
		 for err,(msg, dsc) in toggleIds.items()
		 if err.strip() != "" and msg.strip() != "" }
示例#3
0
	def reloadDivvunSettings(self):
		divvun = DivvunHandlePool.getInstance()
		event = LinguServiceEvent()
		event.nEvent = 0
		try:
			hyphWordParts = self.readFromRegistry("/no.divvun.gramcheck.Config/hyphenator", "hyphWordParts")
			if hyphWordParts != self.__hyphWordParts:
				event.nEvent = event.nEvent | HYPHENATE_AGAIN
				self.__hyphWordParts = hyphWordParts

			hyphUnknownWords = self.readFromRegistry("/no.divvun.gramcheck.Config/hyphenator", "hyphUnknownWords")
			if hyphUnknownWords != self.__hyphUnknownWords:
				event.nEvent = event.nEvent | HYPHENATE_AGAIN
				self.__hyphUnknownWords = hyphUnknownWords

			dictVariant = self.readFromRegistry("/no.divvun.gramcheck.Config/dictionary", "variant")
			if dictVariant is None or dictVariant == "":
				dictVariant = divvun.getPreferredGlobalVariant()
			if dictVariant != divvun.getPreferredGlobalVariant():
				event.nEvent =  event.nEvent | SPELL_CORRECT_WORDS_AGAIN | SPELL_WRONG_WORDS_AGAIN | PROOFREAD_AGAIN
				divvun.setPreferredGlobalVariant(dictVariant)
		except UnknownPropertyException as e:
			logging.exception("PropertyManager.reloadDivvunSettings")
		self.__syncHyphenatorSettings()
		self.__sendLinguEvent(event)
示例#4
0
	def setValue(self, value):
		if value.Name == "IsSpellWithDigits":
			DivvunHandlePool.getInstance().setGlobalBooleanOption(PropertyManager.DIVVUN_OPT_IGNORE_NUMBERS, not value.Value)
		elif value.Name == "IsSpellUpperCase":
			DivvunHandlePool.getInstance().setGlobalBooleanOption(PropertyManager.DIVVUN_OPT_IGNORE_UPPERCASE, not value.Value)
		elif value.Name == "HyphMinLeading":
			if value.Value is not None:
				self.__hyphMinLeading = value.Value
				self.__syncHyphenatorSettings()
		elif value.Name == "HyphMinTrailing":
			if value.Value is not None:
				self.__hyphMinTrailing = value.Value
				self.__syncHyphenatorSettings()
		elif value.Name == "HyphMinWordLength":
			if value.Value is not None:
				self.__hyphMinWordLength = value.Value
				self.__syncHyphenatorSettings()
示例#5
0
 def isValid(self, word, locale, properties):
     DivvunHandlePool.mutex.acquire()
     try:
         divvun = DivvunHandlePool.getInstance().getHandle(locale)
         if divvun is None:
             return False
         PropertyManager.getInstance().setValues(properties)
         result = divvun.spell(word)
         PropertyManager.getInstance().resetValues(properties)
         return result
     finally:
         DivvunHandlePool.mutex.release()
示例#6
0
    def spell(self, word, locale, properties):
        # Check if diagnostic message should be returned
        if word == "DivvunGetStatusInformation":
            suggestions = [
                DivvunHandlePool.getInstance().getInitializationStatus()
            ]
            return SpellAlternatives(word, suggestions, locale)

        DivvunHandlePool.mutex.acquire()
        try:
            divvun = DivvunHandlePool.getInstance().getHandle(locale)
            if divvun is None:
                return None

            PropertyManager.getInstance().setValues(properties)
            if divvun.spell(word):
                PropertyManager.getInstance().resetValues(properties)
                return None
            suggestions = divvun.suggest(word)
            PropertyManager.getInstance().resetValues(properties)
            return SpellAlternatives(word, suggestions, locale)
        finally:
            DivvunHandlePool.mutex.release()
示例#7
0
    def hyphenate(self, word, locale, nMaxLeading, properties):
        logging.debug("Hyphenator.hyphenate")
        if len(word) > 10000:
            return None
        DivvunHandlePool.mutex.acquire()
        try:
            divvun = DivvunHandlePool.getInstance().getHandle(locale)
            if divvun is None:
                return None
            PropertyManager.getInstance().setValues(properties)

            minLeading = PropertyManager.getInstance().getHyphMinLeading()
            minTrailing = PropertyManager.getInstance().getHyphMinTrailing()
            wlen = len(word)

            # If the word is too short to be hyphenated, return no hyphenation points
            if wlen < PropertyManager.getInstance().getHyphMinWordLength(
            ) or wlen < minLeading + minTrailing:
                PropertyManager.getInstance().resetValues(properties)
                return None

            hyphenationPoints = divvun.getHyphenationPattern(word)
            if hyphenationPoints is None:
                PropertyManager.getInstance().resetValues(properties)
                return None

            # find the hyphenation point
            hyphenPos = -1
            i = wlen - minTrailing  # The last generally allowed hyphenation point
            if i > nMaxLeading:
                i = nMaxLeading  # The last allowed point on this line
            while i >= minLeading and hyphenPos == -1:
                if word[i] == '\'':
                    i = i - 1
                    continue
                if hyphenationPoints[i] == '-' or hyphenationPoints[i] == '=':
                    hyphenPos = i
                    break
                i = i - 1

            # return the result
            PropertyManager.getInstance().resetValues(properties)
            if hyphenPos != -1:
                return HyphenatedWord(word, hyphenPos - 1, locale)
            else:
                return None
        finally:
            DivvunHandlePool.mutex.release()
示例#8
0
    def createPossibleHyphens(self, word, locale, properties):
        logging.debug("Hyphenator.createPossibleHyphens")
        wlen = len(word)
        if wlen > 10000:
            return None
        DivvunHandlePool.mutex.acquire()
        try:
            divvun = DivvunHandlePool.getInstance().getHandle(locale)
            if divvun is None:
                return None
            PropertyManager.getInstance().setValues(properties)

            # If the word is too short to be hyphenated, return no hyphenation points
            minLeading = PropertyManager.getInstance().getHyphMinLeading()
            minTrailing = PropertyManager.getInstance().getHyphMinTrailing()
            if wlen < PropertyManager.getInstance().getHyphMinWordLength(
            ) or wlen < minLeading + minTrailing:
                PropertyManager.getInstance().resetValues(properties)
                return None

            hyphenationPoints = divvun.getHyphenationPattern(word)
            if hyphenationPoints is None:
                PropertyManager.getInstance().resetValues(properties)
                return None

            hyphenSeq = []
            hyphenatedWord = ""
            for i in range(0, wlen):
                hyphenatedWord = hyphenatedWord + word[i]
                if i >= minLeading - 1 and i < wlen - minTrailing and hyphenationPoints[
                        i + 1] == '-':
                    hyphenSeq.append(i)
                    hyphenatedWord = hyphenatedWord + "="

            res = PossibleHyphens(word, hyphenatedWord, hyphenSeq, locale)
            PropertyManager.getInstance().resetValues(properties)
            return res
        finally:
            DivvunHandlePool.mutex.release()
示例#9
0
	def __init__(self):
		self.__messageLanguage = "en_US"
		DivvunHandlePool.getInstance().setInstallationPath(self.__getInstallationPath())
		logging.debug("PropertyManager.__init__")
		self.__linguPropSet = None
		self.__hyphMinLeading = 2
		self.__hyphMinTrailing = 2
		self.__hyphMinWordLength = 5
		self.__hyphWordParts = False
		self.__hyphUnknownWords = True
		self.__linguEventListeners = {}	 # type: Dict[int, Any]
		try:
			dictVariant = self.readFromRegistry("/no.divvun.gramcheck.Config/dictionary", "variant")
			DivvunHandlePool.getInstance().setPreferredGlobalVariant(dictVariant)
			logging.debug("Initial dictionary variant '" + dictVariant + "'")
		except UnknownPropertyException as e:
			logging.debug("Setting initial dictionary variant to default")
			DivvunHandlePool.getInstance().setPreferredGlobalVariant("")
		self.initialize()
示例#10
0
 def hasLocale(self, aLocale):
     return DivvunHandlePool.getInstance().supportsHyphenationLocale(
         aLocale)
示例#11
0
 def hasLocale(self, aLocale):
     return DivvunHandlePool.getInstance().supportsSpellingLocale(aLocale)
示例#12
0
 def getLocales(self):
     return DivvunHandlePool.getInstance().getSupportedSpellingLocales()
示例#13
0
	def __syncHyphenatorSettings(self):
		if self.__hyphWordParts:
			DivvunHandlePool.getInstance().setGlobalIntegerOption(PropertyManager.DIVVUN_MIN_HYPHENATED_WORD_LENGTH, self.__hyphMinWordLength)
		else:
			DivvunHandlePool.getInstance().setGlobalIntegerOption(PropertyManager.DIVVUN_MIN_HYPHENATED_WORD_LENGTH, 2)
		DivvunHandlePool.getInstance().setGlobalBooleanOption(PropertyManager.DIVVUN_OPT_HYPHENATE_UNKNOWN_WORDS, self.__hyphUnknownWords)
示例#14
0
	def getLocales(self):
		return DivvunHandlePool.getInstance().getSupportedGrammarLocales()
示例#15
0
 def getLocales(self):
     return DivvunHandlePool.getInstance().getSupportedHyphenationLocales()
示例#16
0
	def doProofreading(self, aDocumentIdentifier, aText, aLocale, nStartOfSentencePos, nSuggestedBehindEndOfSentencePosition, aProperties):
		logging.debug("GrammarChecker.doProofreading")
		result = ProofreadingResult()
		result.aDocumentIdentifier = aDocumentIdentifier
		result.xFlatParagraph = None
		result.aText = aText
		result.aLocale = aLocale
		result.nStartOfSentencePosition = nStartOfSentencePos
		result.nBehindEndOfSentencePosition = nSuggestedBehindEndOfSentencePosition
		result.xProofreader = self
		# We read from registry on each check – it probably
		# doesn't change most of the time, but it *can* change
		# if user edited the plugin options, so this is at
		# least safe:
		ignoredRules = readIgnoredRules() # TODO: get from PropertyManager instead, see reloadDivvunSettings

		DivvunHandlePool.mutex.acquire()
		try:
			instance = DivvunHandlePool.getInstance()
			if instance is None:
				logging.error("GrammarChecker.doProofreading could not initialize libdivvun!")
				return result
			divvun = instance.getHandle(aLocale)
			if divvun is None:
				logging.error("GrammarChecker.doProofreading couldn't get an instance for locale %s"%(aLocale,))
				logging.error("DivvunHandlePool.initializationErrors = %s"%(instance.getInitializationStatus(),))
				return result

			gcErrors = []
			logging.info("Checking '%s', nStartOfSentencePos=%d, nSuggestedBehindEndOfSentencePosition=%d",
					aText, nStartOfSentencePos, nSuggestedBehindEndOfSentencePosition)
			for dError in libdivvun.proc_errs_bytes(divvun, aText):
				startPos = dError.beg
				errorLength = dError.end - dError.beg
				logging.info("dError on form=%s at (%d,%d) replacements: %s",
						dError.form, dError.beg, dError.end, dError.rep)
				if dError.beg < result.nStartOfSentencePosition:
					logging.info("beg %d < result.nStartOfSentencePosition %d, continue",
							dError.beg, result.nStartOfSentencePosition)
					continue
				if dError.beg >= result.nBehindEndOfSentencePosition:
					logging.info("beg %d >= result.nBehindEndOfSentencePosition %d, break",
							dError.beg, result.nBehindEndOfSentencePosition)
					break
				if dError.beg + errorLength > result.nBehindEndOfSentencePosition:
					logging.info("dError.beg %d + errorLength %d > result.nBehindEndOfSentencePosition %d, incf",
							dError.beg, errorLength, result.nBehindEndOfSentencePosition)
					result.nBehindEndOfSentencePosition = dError.beg + errorLength
				logging.info("dError on form=%s at (%d,%d) replacements: %s",
						dError.form,
						dError.beg, dError.end,
						dError.rep)
				ruleIdentifier = dError.err
				if ruleIdentifier in ignoredRules:
					logging.debug("Ignored error with rule " + ruleIdentifier)
					continue

				suggestions = dError.rep
				gcError = SingleProofreadingError()
				gcErrors.append(gcError)
				gcError.nErrorStart = startPos
				gcError.nErrorLength = errorLength
				gcError.nErrorType = PROOFREADING
				comment = dError.dsc
				gcError.aShortComment = comment
				gcError.aFullComment = comment
				gcError.aRuleIdentifier = ruleIdentifier

				if False:  # We are not web yet, TODO
				    detailUrl = PropertyValue()
				    detailUrl.Name = "FullCommentURL"
				    detailUrl.Value = "http://divvun.no/gchelp/" + aLocale.Language + "/" + ruleIdentifier + ".html"
				    gcError.aProperties = (detailUrl,)

				# add suggestions
				if len(suggestions) > 0:
					gcError.aSuggestions = tuple(suggestions)

			result.aErrors = tuple(gcErrors)
			result.nStartOfNextSentencePosition = result.nBehindEndOfSentencePosition
			logging.info("return result, errors: %d", len(result.aErrors))
			return result
		finally:
			DivvunHandlePool.mutex.release()
示例#17
0
	def hasLocale(self, aLocale):
		logging.info("haslocale %s for %s", DivvunHandlePool.getInstance().supportsGrammarLocale(aLocale), aLocale)
		return DivvunHandlePool.getInstance().supportsGrammarLocale(aLocale)