PluginProjectKivy.py

Sat, 23 Dec 2023 15:48:53 +0100

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Sat, 23 Dec 2023 15:48:53 +0100
branch
eric7
changeset 68
20cdd6e03807
parent 66
978b7b8eee65
child 70
2c0a54bf5b4c
permissions
-rw-r--r--

Updated copyright for 2024.

# -*- coding: utf-8 -*-

# Copyright (c) 2013 - 2024 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Module implementing the Kivy project plug-in.
"""

import contextlib
import fnmatch
import glob
import os

from pygments.lexers._mapping import LEXERS
from PyQt6.QtCore import QObject, QTranslator

from eric7 import Preferences
from eric7.EricWidgets.EricApplication import ericApp
from eric7.QScintilla import Lexers, TypingCompleters

# Start-of-Header
name = "Kivy Project Plugin"
author = "Detlev Offenbach <detlev@die-offenbachs.de>"
autoactivate = True
deactivateable = True
version = "10.3.1"
className = "ProjectKivyPlugin"
packageName = "ProjectKivy"
shortDescription = "Project support for Kivy projects."
longDescription = """This plugin implements project support for Kivy projects."""
needsRestart = False
pyqtApi = 2
# End-of-Header

error = ""


def apiFiles(language):
    """
    Module function to return the API files made available by this plugin.

    @param language language to get API file for
    @type str
    @return list of API filenames
    @rtype list of str
    """
    if language in ["Python3"]:
        apisDir = os.path.join(os.path.dirname(__file__), "ProjectKivy", "APIs")
        return glob.glob(os.path.join(apisDir, "*.api"))
    else:
        return []


def prepareUninstall():
    """
    Module function to prepare for an uninstallation.
    """
    Preferences.Prefs.settings.remove(ProjectKivyPlugin.PreferencesKey)


class ProjectKivyPlugin(QObject):
    """
    Class implementing the Kivy project plugin.
    """

    PreferencesKey = "Kivy"

    lexerAssociations = {
        "*.kv": "Pygments|Kivy",
        "*.kivy": "Pygments|Kivy",
    }

    KivyLexerKey = "KivyLexer"
    KivyLexerEntry = (
        "ProjectKivy.KivyLexer",
        "Kivy",
        ("kivy", "kv"),
        ("*.kv", "*.kivy"),
        ("application/x-kivy",),
    )

    def __init__(self, ui):
        """
        Constructor

        @param ui reference to the user interface object
        @type UserInterface
        """
        QObject.__init__(self, ui)
        self.__ui = ui
        self.__initialize()

        self.__typingDefaults = {
            "EnabledTypingAids": True,
            "InsertClosingBrace": True,
            "SkipBrace": True,
            "InsertQuote": True,
            "AutoIndentation": True,
            "ColonDetection": True,
            "InsertBlankColon": True,
            "InsertBlankComma": True,
        }

        self.__translator = None
        self.__loadTranslator()

    def __initialize(self):
        """
        Private slot to (re)initialize the plugin.
        """
        self.__ericProject = ericApp().getObject("Project")

    def activate(self):
        """
        Public method to activate this plugin.

        @return tuple of None and activation status
        @rtype bool
        """
        self.__ericProject.registerProjectType(
            "Kivy",
            self.tr("Kivy"),
            self.fileTypesCallback,
            lexerAssociationCallback=self.lexerAssociationCallback,
            progLanguages=["Python3"],
        )

        try:
            # backward compatibility for eric7 < 22.12
            from eric7.Project.ProjectBrowser import (  # noqa: I101
                FormsBrowserFlag,
                OthersBrowserFlag,
                SourcesBrowserFlag,
                TranslationsBrowserFlag,
            )

            Preferences.setProjectBrowserFlagsDefault(
                "Kivy",
                SourcesBrowserFlag
                | FormsBrowserFlag
                | TranslationsBrowserFlag
                | OthersBrowserFlag,
            )
        except ImportError:
            Preferences.setProjectBrowsersDefault(
                "Kivy",
                ("sources", "forms", "translations", "others"),
            )

        LEXERS[self.KivyLexerKey] = self.KivyLexerEntry
        Lexers.registerLexer(
            "Pygments|Kivy",
            self.tr("Kivy"),
            "dummy.kv",
            self.getLexer,
            [self.tr("Kivy Files (*.kv *.kivy)")],
            [self.tr("Kivy Files (*.kv)")],
            ["*.kv", "*.kivy"],
        )

        with contextlib.suppress(AttributeError):
            # Typing Completer (eric7 > 23.9)
            TypingCompleters.registerCompleter(
                language="Pygments|Kivy",
                createCompleterFunction=self.createTypingCompleter,
                createConfigPageFunction=self.createTypingCompleterConfigWidget,
            )

        return None, True

    def deactivate(self):
        """
        Public method to deactivate this plugin.
        """
        self.__ericProject.unregisterProjectType("Kivy")

        with contextlib.suppress(AttributeError):
            # Typing Completer (eric7 > 23.9)
            TypingCompleters.unregisterTypingCompleter("Pygments|Kivy")

        Lexers.unregisterLexer("Pygments|Kivy")
        if self.KivyLexerKey in LEXERS:
            del LEXERS[self.KivyLexerKey]

        self.__initialize()

    def __loadTranslator(self):
        """
        Private method to load the translation file.
        """
        if self.__ui is not None:
            loc = self.__ui.getLocale()
            if loc and loc != "C":
                locale_dir = os.path.join(
                    os.path.dirname(__file__), "ProjectKivy", "i18n"
                )
                translation = "kivy_{0}".format(loc)
                translator = QTranslator(None)
                loaded = translator.load(translation, locale_dir)
                if loaded:
                    self.__translator = translator
                    ericApp().installTranslator(self.__translator)
                else:
                    print(
                        "Warning: translation file '{0}' could not be"
                        " loaded.".format(translation)
                    )
                    print("Using default.")

    def fileTypesCallback(self):
        """
        Public method get the filetype associations of the Kivy project type.

        @return dictionary with file type associations
        @rtype dict
        """
        if self.__ericProject.getProjectType() == "Kivy":
            return {
                "*.kv": "SOURCES",
                "*.kivy": "SOURCES",
                "*.py": "SOURCES",
            }
        else:
            return {}

    def lexerAssociationCallback(self, filename):
        """
        Public method to get the lexer association of the Kivy project type for
        a file.

        @param filename name of the file
        @type str
        @return name of the lexer (Pygments lexers are prefixed with
            'Pygments|')
        @rtype str
        """
        for pattern, language in self.lexerAssociations.items():
            if fnmatch.fnmatch(filename, pattern):
                return language

        return ""

    def getLexer(self, parent=None):
        """
        Public method to instantiate a Pygments Kivy lexer object.

        @param parent reference to the parent object
        @type QObject
        @return reference to the instanciated lexer object
        @rtype QsciLexer
        """
        from eric7.QScintilla.Lexers.LexerPygments import LexerPygments

        lexer = LexerPygments(parent, name="Kivy")
        if lexer.canStyle():
            return lexer
        else:
            return None

    def getTypingPreferences(self, key):
        """
        Public method to retrieve the typing completer settings.

        @param key the key of the value to get
        @type str
        @return value of the requested setting
        @rtype Any
        """
        return Preferences.toBool(
            Preferences.Prefs.settings.value(
                f"{self.PreferencesKey}/Typing/{key}", self.__typingDefaults[key]
            )
        )

    def setTypingPreferences(self, key, value):
        """
        Public method to store the typing completer settings.

        @param key the key of the setting to be set
        @type str
        @param value value to be set
        @type Any
        """
        Preferences.Prefs.settings.setValue(
            f"{self.PreferencesKey}/Typing/{key}", value
        )

    def createTypingCompleter(self, editor, parent=None):
        """
        Public method to create a typing completer object for the given editor.

        @param editor reference to the editor object
        @type Editor
        @param parent reference to the parent object (defaults to None)
        @type QObject (optional)
        @return reference to the instantiated typing completer object
        @rtype CompleterKivy
        """
        from ProjectKivy.CompleterKivy import CompleterKivy

        return CompleterKivy(self, editor, parent)

    def createTypingCompleterConfigWidget(self):
        """
        Public method to create and populate the typing completer configuration widget.

        @return instantiated and populated configuration widget
        @rtype CompleterKivyConfigWidget
        """
        from ProjectKivy.CompleterKivyConfigWidget import CompleterKivyConfigWidget

        widget = CompleterKivyConfigWidget(self)
        return widget


#
# eflag: noqa = M801, M811, U200

eric ide

mercurial