Esempio n. 1
0
class makeSpellCheck():
    def __init__(self):
        # Nothing loaded yet
        self.altTag = QString()
        self.altDict = None
        self.mainTag = QString()
        self.mainDict = None
        # Tags of any not-found dicts so we only give one diagnostic per dict
        self.errTags = set()
        # Populate our list of available dictionaries by finding
        # all the file-pairs of the form <tag>.dic and <tag>.aff in the
        # folder whose path is saved by ppqt in IMC.dictPath.
        # Save the dict tags in the string list self.listOfDicts.
        self.listOfDicts = QStringList()
        # Get a list of all files in that folder. We don't need to sort them,
        # we use the "in" operator to find the X.dic matching an X.aff
        # Defensive programming: dict folder should exist but maybe the user
        # moved stuff.
        try :
            fnames = os.listdir(IMC.dictPath)
        except OSError :
            fnames = [] # no dict folder?!
        for fn in fnames:
            if u'.aff' == fn[-4:] :
                # this is a tag.aff file, look for a matching tag.dic
                dn = fn[:-4]
                if (dn + u'.dic') in fnames:
                    self.listOfDicts.append(QString(dn))
        # Initialize our main dictionary to the one last-chosen by the user
        # with a default of en_US. The current main dict is saved in the
        # settings during the terminate() method below.
        deftag = IMC.settings.value(u"main/spellDictTag",
                                    QString(u"en_US")).toString()
        # Try to load the main dictionary. Sets self.mainDict/.mainTag.
        self.setMainDict(deftag)
        # No alt-dict has been loaded yet, so self.altDict/.altTag are None.

    # If a main dictionary has been loaded, return True.
    def isUp(self):
        return (self.mainDict is not None)

    # Return our list of available dictionary tags, as needed to populate
    # the View > Dictionary submenu.
    def dictList(self):
        return self.listOfDicts

    # When the program is ending, pqMain calls this slot.
    # Save the user-set main dictionary tag for next time.
    def terminate(self):
        IMC.settings.setValue(u"main/spellDictTag",self.mainTag)

    # Set a new main/default dictionary if a dict of that tag exists.
    # If we have already gone to the labor of loading that dict, don't
    # repeat the work.
    def setMainDict(self,tag):
        if tag == self.mainTag :
            return True # We already loaded that one
        elif tag == self.altTag :
            # We already loaded that tag as an alt, make it Main
            self.mainTag = self.altTag
            self.mainDict = self.altDict
            # and now we don't have an alt any more.
            self.altTag = None
            self.altDict = None
            return True
        # Try to create a hunspell object for that dict/aff pair.
        dictobj = self.loadDict(tag)
        if dictobj is not None :
            # That worked, save it.
            self.mainDict = dictobj
            self.mainTag = tag
            return True
        else:
            # It didn't work. .mainDict/.mainTag are either None,
            # or else they have some earlier successful choice.
            # Leave them as-is.
            return False

    # Set up a spellcheck dictionary by way of our spellDict class.
    def loadDict(self,tag):
        p = self.listOfDicts.indexOf(tag)
        try:
            if p > -1 : # the tag is in our list of valid dicts
                fn = unicode(tag) # get qstring to python string
                aff_path = os.path.join(IMC.dictPath,fn+u'.aff')
                dic_path = os.path.join(IMC.dictPath,fn+u'.dic')
                obj = spellDict( dic_path, aff_path )
                return obj # success
            else:
                raise LookupError('dictionary tag {0} not found'.format(tag))
        except (LookupError, IOError, OSError) as err:
            if unicode(tag) not in self.errTags :
                pqMsgs.warningMsg(u'Could not open dictionary',str(err))
                self.errTags.add(unicode(tag))
            return None
        except : # some other error?
            print("unexpected error opening a spell dict")
            return None

    # Check one word, a python u-string, against the main or an alt dictionary.
    # If an alt dict is specified, it is likely the same as the last one
    # requested, but if not, then try to load a dict of the given tag.
    # We used to split up hyphenated phrases, but Hunspell handles them.
    def check(self, aword, dicTag = ''):
        if 0 == len(dicTag):
            d = self.mainDict # which is None, if we are not up
        else:
            if dicTag == self.altTag :
                d = self.altDict # same alt as the last one
            else:
                # Different alt dictionary, open it
                d = self.loadDict(dicTag)
                if d is not None :
                    self.altDict = d # that worked, save new alt dict
                    self.altTag = dicTag
        if d is not None: # one way or another we have a dict
            return d.spell(aword)
        return False # null word, or main or alt dict not available
Esempio n. 2
0
class makeSpellCheck():
    def __init__(self):
        # Nothing loaded yet
        self.altTag = QString()
        self.altDict = None
        self.mainTag = QString()
        self.mainDict = None
        # Tags of any not-found dicts so we only give one diagnostic per dict
        self.errTags = set()
        # Populate our list of available dictionaries by finding
        # all the file-pairs of the form <tag>.dic and <tag>.aff in the
        # folder whose path is saved by ppqt in IMC.dictPath.
        # Save the dict tags in the string list self.listOfDicts.
        self.listOfDicts = QStringList()
        # Get a list of all files in that folder. We don't need to sort them,
        # we use the "in" operator to find the X.dic matching an X.aff
        # Defensive programming: dict folder should exist but maybe the user
        # moved stuff.
        try:
            fnames = os.listdir(IMC.dictPath)
        except OSError:
            fnames = []  # no dict folder?!
        for fn in fnames:
            if u'.aff' == fn[-4:]:
                # this is a tag.aff file, look for a matching tag.dic
                dn = fn[:-4]
                if (dn + u'.dic') in fnames:
                    self.listOfDicts.append(QString(dn))
        # Initialize our main dictionary to the one last-chosen by the user
        # with a default of en_US. The current main dict is saved in the
        # settings during the terminate() method below.
        deftag = IMC.settings.value(u"main/spellDictTag",
                                    QString(u"en_US")).toString()
        # Try to load the main dictionary. Sets self.mainDict/.mainTag.
        self.setMainDict(deftag)
        # No alt-dict has been loaded yet, so self.altDict/.altTag are None.

    # If a main dictionary has been loaded, return True.
    def isUp(self):
        return (self.mainDict is not None)

    # Return our list of available dictionary tags, as needed to populate
    # the View > Dictionary submenu.
    def dictList(self):
        return self.listOfDicts

    # When the program is ending, pqMain calls this slot.
    # Save the user-set main dictionary tag for next time.
    def terminate(self):
        IMC.settings.setValue(u"main/spellDictTag", self.mainTag)

    # Set a new main/default dictionary if a dict of that tag exists.
    # If we have already gone to the labor of loading that dict, don't
    # repeat the work.
    def setMainDict(self, tag):
        if tag == self.mainTag:
            return True  # We already loaded that one
        elif tag == self.altTag:
            # We already loaded that tag as an alt, make it Main
            self.mainTag = self.altTag
            self.mainDict = self.altDict
            # and now we don't have an alt any more.
            self.altTag = None
            self.altDict = None
            return True
        # Try to create a hunspell object for that dict/aff pair.
        dictobj = self.loadDict(tag)
        if dictobj is not None:
            # That worked, save it.
            self.mainDict = dictobj
            self.mainTag = tag
            return True
        else:
            # It didn't work. .mainDict/.mainTag are either None,
            # or else they have some earlier successful choice.
            # Leave them as-is.
            return False

    # Set up a spellcheck dictionary by way of our spellDict class.
    def loadDict(self, tag):
        p = self.listOfDicts.indexOf(tag)
        try:
            if p > -1:  # the tag is in our list of valid dicts
                fn = unicode(tag)  # get qstring to python string
                aff_path = os.path.join(IMC.dictPath, fn + u'.aff')
                dic_path = os.path.join(IMC.dictPath, fn + u'.dic')
                obj = spellDict(dic_path, aff_path)
                return obj  # success
            else:
                raise LookupError('dictionary tag {0} not found'.format(tag))
        except (LookupError, IOError, OSError) as err:
            if unicode(tag) not in self.errTags:
                pqMsgs.warningMsg(u'Could not open dictionary', str(err))
                self.errTags.add(unicode(tag))
            return None
        except:  # some other error?
            print("unexpected error opening a spell dict")
            return None

    # Check one word, a python u-string, against the main or an alt dictionary.
    # If an alt dict is specified, it is likely the same as the last one
    # requested, but if not, then try to load a dict of the given tag.
    # We used to split up hyphenated phrases, but Hunspell handles them.
    def check(self, aword, dicTag=''):
        if 0 == len(dicTag):
            d = self.mainDict  # which is None, if we are not up
        else:
            if dicTag == self.altTag:
                d = self.altDict  # same alt as the last one
            else:
                # Different alt dictionary, open it
                d = self.loadDict(dicTag)
                if d is not None:
                    self.altDict = d  # that worked, save new alt dict
                    self.altTag = dicTag
        if d is not None:  # one way or another we have a dict
            return d.spell(aword)
        return False  # null word, or main or alt dict not available