PluginAssistantEric.py

Tue, 10 Dec 2024 15:48:50 +0100

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Tue, 10 Dec 2024 15:48:50 +0100
branch
eric7
changeset 216
42ded9008f96
parent 214
24bfb512ce15
permissions
-rw-r--r--

Updated copyright for 2025.

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

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

"""
Module implementing the Eric assistant plugin.
"""

import os

from PyQt6.QtCore import QCoreApplication, QObject, QTranslator

from AssistantEric.Assistant import AcsAPIs, AcsProject, Assistant
from eric7 import Preferences
from eric7.EricWidgets.EricApplication import ericApp

# Start-Of-Header
name = "Assistant Eric Plugin"
author = "Detlev Offenbach <detlev@die-offenbachs.de>"
autoactivate = True
deactivateable = True
version = "10.4.1"
className = "AssistantEricPlugin"
packageName = "AssistantEric"
shortDescription = "Alternative autocompletion and calltips provider."
longDescription = (
    """This plugin implements an alternative autocompletion and"""
    """ calltips provider."""
)
needsRestart = True
pyqtApi = 2
# End-Of-Header

error = ""

assistantEricPluginObject = None


def createAutoCompletionPage(
    configDlg,  # noqa: U100
):
    """
    Module function to create the autocompletion configuration page.

    @param configDlg reference to the configuration dialog
    @type ConfigurationWidget
    @return reference to the configuration page
    @rtype QWidget
    """
    global assistantEricPluginObject
    from AssistantEric.ConfigurationPages.AutoCompletionEricPage import (  # noqa: I101
        AutoCompletionEricPage,
    )

    return AutoCompletionEricPage(assistantEricPluginObject)


def createCallTipsPage(
    configDlg,  # noqa: U100
):
    """
    Module function to create the calltips configuration page.

    @param configDlg reference to the configuration dialog
    @type ConfigurationWidget
    @return reference to the configuration page
    @rtype QWidget
    """
    global assistantEricPluginObject
    from AssistantEric.ConfigurationPages.CallTipsEricPage import (  # noqa: I101
        CallTipsEricPage,
    )

    return CallTipsEricPage(assistantEricPluginObject)


def getConfigData():
    """
    Module function returning data as required by the configuration dialog.

    @return dictionary containing the relevant data
    @rtype dict
    """
    try:
        usesDarkPalette = ericApp().usesDarkPalette()
    except AttributeError:
        from PyQt6.QtGui import QPalette  # noqa: I101, I102

        palette = ericApp().palette()
        lightness = palette.color(QPalette.ColorRole.Window).lightness()
        usesDarkPalette = lightness <= 128
    iconSuffix = "dark" if usesDarkPalette else "light"

    return {
        "ericAutoCompletionPage": [
            QCoreApplication.translate("AssistantEricPlugin", "Eric"),
            os.path.join(
                "AssistantEric", "ConfigurationPages", "eric-{0}".format(iconSuffix)
            ),
            createAutoCompletionPage,
            "1editorAutocompletionPage",
            None,
        ],
        "ericCallTipsPage": [
            QCoreApplication.translate("AssistantEricPlugin", "Eric"),
            os.path.join(
                "AssistantEric", "ConfigurationPages", "eric-{0}".format(iconSuffix)
            ),
            createCallTipsPage,
            "1editorCalltipsPage",
            None,
        ],
    }


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


class AssistantEricPlugin(QObject):
    """
    Class implementing the Eric assistant plugin.
    """

    PreferencesKey = "AssistantEric"

    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.__defaults = {
            "AutoCompletionEnabled": False,
            "AutoCompletionSource": AcsAPIs | AcsProject,
            "AutoCompletionFollowHierarchy": False,
            "CalltipsEnabled": False,
            "CallTipsContextShown": True,
            "CallTipsFollowHierarchy": False,
        }

        self.__translator = None
        self.__loadTranslator()

    def __initialize(self):
        """
        Private slot to (re)initialize the plugin.
        """
        self.__object = None

    def __checkQSql(self):
        """
        Private method to perform some checks on QSql.

        @return flag indicating QSql is ok
        @rtype bool
        """
        global error

        try:
            from PyQt6.QtSql import QSqlDatabase  # noqa: I101, I102
        except ImportError:
            error = self.tr("PyQt6.QtSql is not available.")
            return False

        drivers = QSqlDatabase.drivers()
        if "QSQLITE" not in drivers:
            error = self.tr("The SQLite database driver is not available.")
            return False

        return True

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

        @return tuple of None and activation status
        @rtype bool
        """
        global error
        error = ""  # clear previous error

        if not self.__checkQSql():
            return None, False

        global assistantEricPluginObject
        assistantEricPluginObject = self

        self.__object = Assistant(self, self.__ui)
        ericApp().registerPluginObject("AssistantEric", self.__object)

        self.__object.activate()

        return None, True

    def deactivate(self):
        """
        Public method to deactivate this plugin.
        """
        ericApp().unregisterPluginObject("AssistantEric")

        self.__object.deactivate()

        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__), "AssistantEric", "i18n"
                )
                translation = "assistant_{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 getPreferences(self, key):
        """
        Public method to retrieve the various settings.

        @param key the key of the value to get
        @type str
        @return value of the requested setting
        @rtype Any
        """
        if key in [
            "AutoCompletionEnabled",
            "AutoCompletionFollowHierarchy",
            "CalltipsEnabled",
            "CallTipsContextShown",
            "CallTipsFollowHierarchy",
        ]:
            return Preferences.toBool(
                Preferences.Prefs.settings.value(
                    self.PreferencesKey + "/" + key, self.__defaults[key]
                )
            )
        else:
            return int(
                Preferences.Prefs.settings.value(
                    self.PreferencesKey + "/" + key, self.__defaults[key]
                )
            )

    def setPreferences(self, key, value):
        """
        Public method to store the various 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(self.PreferencesKey + "/" + key, value)

        if key in ["AutoCompletionEnabled", "CalltipsEnabled"]:
            self.__object.setEnabled(key, value)


#
# eflag: noqa = M801

eric ide

mercurial