PluginPrintRemover.py

Tue, 10 Dec 2024 15:49:04 +0100

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Tue, 10 Dec 2024 15:49:04 +0100
branch
eric7
changeset 70
40e98b382639
parent 69
ed8361e82ca1
permissions
-rw-r--r--

Updated copyright for 2025.

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

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

"""
Module implementing the Print Remover plug-in.
"""

import contextlib
import os

from PyQt6.QtCore import QCoreApplication, QObject, QTranslator, pyqtSlot
from PyQt6.QtGui import QAction
from PyQt6.QtWidgets import QMenu

from eric7 import Preferences
from eric7.EricWidgets.EricApplication import ericApp

# Start-Of-Header
name = "Print Remover Plug-in"
author = "Detlev Offenbach <detlev@die-offenbachs.de>"
autoactivate = True
deactivateable = True
version = "10.1.0"
className = "PrintRemoverPlugin"
packageName = "PrintRemover"
shortDescription = "Remove print() like debug statements."
longDescription = (
    """This plug-in implements a tool to remove lines starting with"""
    """ a configurable string. This is mostly used to remove print()"""
    """ like debug statements. The match is done after stripping all"""
    """ whitespace from the beginning of a line. Lines containing the"""
    """ string '__NO_REMOVE__' are preserved."""
)
needsRestart = False
pyqtApi = 2
# End-Of-Header

error = ""

printRemoverPluginObject = None


def createPrintRemoverPage(configDlg):  # noqa: U100
    """
    Module function to create the Print Remover configuration page.

    @param configDlg reference to the configuration dialog
    @type ConfigurationWidget
    @return reference to the configuration page
    @rtype PrintRemoverPage
    """
    from PrintRemover.ConfigurationPage.PrintRemoverPage import PrintRemoverPage

    global printRemoverPluginObject

    return PrintRemoverPage(printRemoverPluginObject)


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

    @return dictionary containing the relevant data
    @rtype dict
    """
    usesDarkPalette = ericApp().usesDarkPalette()
    iconSuffix = "dark" if usesDarkPalette else "light"

    return {
        "printRemoverPage": [
            QCoreApplication.translate("PrintRemoverPlugin", "Print Remover"),
            os.path.join(
                "PrintRemover", "icons", "printRemover-{0}".format(iconSuffix)
            ),
            createPrintRemoverPage,
            None,
            None,
        ],
    }


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


class PrintRemoverPlugin(QObject):
    """
    Class implementing the Print Remover plugin.
    """

    PreferencesKey = "PrintRemover"

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

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

        self.__defaults = {
            "StartswithStrings": ["print(", "print ", "console.log"],
        }

        self.__translator = None
        self.__loadTranslator()

        self.__initMenu()

        self.__editors = {}
        self.__mainActions = []

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

        @return tuple of None and activation statu
        @rtype tuple of (None, bool)
        """
        global error
        error = ""  # clear previous error

        global printRemoverPluginObject
        printRemoverPluginObject = self

        self.__ui.showMenu.connect(self.__populateMenu)

        menu = self.__ui.getMenu("plugin_tools")
        if menu is not None:
            if not menu.isEmpty():
                act = menu.addSeparator()
                self.__mainActions.append(act)
            act = menu.addMenu(self.__menu)
            self.__mainActions.append(act)

        ericApp().getObject("ViewManager").editorOpenedEd.connect(self.__editorOpened)
        ericApp().getObject("ViewManager").editorClosedEd.connect(self.__editorClosed)

        for editor in ericApp().getObject("ViewManager").getOpenEditors():
            self.__editorOpened(editor)

        return None, True

    def deactivate(self):
        """
        Public method to deactivate this plugin.
        """
        self.__ui.showMenu.disconnect(self.__populateMenu)

        menu = self.__ui.getMenu("plugin_tools")
        if menu is not None:
            for act in self.__mainActions:
                menu.removeAction(act)
        self.__mainActions = []

        ericApp().getObject("ViewManager").editorOpenedEd.disconnect(
            self.__editorOpened
        )
        ericApp().getObject("ViewManager").editorClosedEd.disconnect(
            self.__editorClosed
        )

        for editor, acts in self.__editors.items():
            editor.showMenu.disconnect(self.__editorShowMenu)
            menu = editor.getMenu("Tools")
            if menu is not None:
                for act in acts:
                    menu.removeAction(act)
        self.__editors = {}

    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__), "PrintRemover", "i18n"
                )
                translation = "printremover_{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 ["StartswithStrings"]:
            return Preferences.toList(
                Preferences.Prefs.settings.value(
                    self.PreferencesKey + "/" + key, self.__defaults[key]
                )
            )
        else:
            return Preferences.Prefs.settings.value(
                self.PreferencesKey + "/" + key, self.__defaults[key]
            )

    def setPreferences(self, key, value):
        """
        Public method to store the various settings.

        @param key 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)

    def __initMenu(self):
        """
        Private method to initialize the menu.
        """
        self.__menu = QMenu("Remove Outputs")
        self.__menu.setEnabled(False)
        self.__menu.aboutToShow.connect(self.__showMenu)
        self.__menu.triggered.connect(self.__removeLine)

    def __populateMenu(self, name, menu):
        """
        Private slot to populate the tools menu with our entries.

        @param name name of the menu
        @type str
        @param menu reference to the menu to be populated
        @type QMenu
        """
        if name not in ["Tools", "PluginTools"]:
            return

        editor = ericApp().getObject("ViewManager").activeWindow()

        if name == "Tools":
            if not menu.isEmpty():
                menu.addSeparator()

            act = menu.addMenu(self.__menu)
            act.setEnabled(editor is not None)
        elif name == "PluginTools" and self.__mainActions:
            self.__mainActions[-1].setEnabled(editor is not None)

    def __editorOpened(self, editor):
        """
        Private slot called, when a new editor was opened.

        @param editor reference to the new editor
        @type Editor
        """
        menu = editor.getMenu("Tools")
        if menu is not None:
            self.__editors[editor] = []
            if not menu.isEmpty():
                act = menu.addSeparator()
                self.__editors[editor].append(act)
            act = menu.addMenu(self.__menu)
            self.__menu.setEnabled(True)
            self.__editors[editor].append(act)
            editor.showMenu.connect(self.__editorShowMenu)

    def __editorClosed(self, editor):
        """
        Private slot called, when an editor was closed.

        @param editor reference to the editor
        @type Editor
        """
        with contextlib.suppress(KeyError):
            del self.__editors[editor]
            if not self.__editors:
                self.__menu.setEnabled(False)

    def __editorShowMenu(self, menuName, menu, editor):
        """
        Private slot called, when the the editor context menu or a submenu is
        about to be shown.

        @param menuName name of the menu to be shown
        @type str
        @param menu reference to the menu
        @type QMenu
        @param editor reference to the editor
        @type Editor
        """
        if menuName == "Tools" and self.__menu.menuAction() not in menu.actions():
            # Re-add our menu
            self.__editors[editor] = []
            if not menu.isEmpty():
                act = menu.addSeparator()
                self.__editors[editor].append(act)
            act = menu.addMenu(self.__menu)
            self.__editors[editor].append(act)

    def __showMenu(self):
        """
        Private slot to build the menu hierarchy.
        """
        self.__menu.clear()
        for startString in self.getPreferences("StartswithStrings"):
            if startString == "--Separator--":
                self.__menu.addSeparator()
            else:
                act = self.__menu.addAction(self.tr("Remove '{0}'").format(startString))
                act.setData(startString)

    @pyqtSlot(QAction)
    def __removeLine(self, act):
        """
        Private slot to remove lines starting with the selected pattern.

        @param act reference to the action that was triggered
        @type QAction
        """
        if act is None:
            return

        editor = ericApp().getObject("ViewManager").activeWindow()
        if editor is None:
            return

        pattern = act.data()
        if not pattern:
            return

        text = editor.text()
        newText = "".join(
            [
                line
                for line in text.splitlines(True)
                if not line.lstrip().startswith(pattern) or "__NO_REMOVE__" in line
            ]
        )
        if newText != text:
            editor.beginUndoAction()
            editor.selectAll()
            editor.replaceSelectedText(newText)
            editor.endUndoAction()


#
# eflag: noqa = M801, U200

eric ide

mercurial