PluginToolGenerateHash.py

Mon, 24 Oct 2022 16:42:16 +0200

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Mon, 24 Oct 2022 16:42:16 +0200
branch
eric7
changeset 62
3d0bb45398c6
parent 61
6fc29f5292d3
child 64
72d9f6d21a41
permissions
-rw-r--r--

Adapted the import statements to the new structure.

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

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

"""
Module implementing the 'Generate Hash' tool plug-in.
"""

import contextlib
import os
import hashlib

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

from eric7.EricWidgets import EricFileDialog, EricMessageBox
from eric7.EricWidgets.EricApplication import ericApp

# Start-Of-Header
name = "Generate Hash Tool Plug-in"
author = "Detlev Offenbach <detlev@die-offenbachs.de>"
autoactivate = True
deactivateable = True
version = "10.1.0"
className = "ToolGenerateHashPlugin"
packageName = "ToolGenerateHash"
shortDescription = "Generate a hash for a selectable file or directory"
longDescription = (
    """Plug-in to generate a hash for a selectable file or directory. The"""
    """ hash string will be inserted at the cursor position of the current"""
    """ editor. The menu will be disabled, if no editor is open."""
)
needsRestart = False
pyqtApi = 2
# End-Of-Header

error = ""


class ToolGenerateHashPlugin(QObject):
    """
    Class implementing the 'Generate Hash' tool plug-in.
    """

    Hashes = [
        h
        for h in (
            "md5",
            "sha1",
            "sha224",
            "sha256",
            "sha384",
            "sha512",
            "sha3_224",
            "sha3_256",
            "sha3_384",
            "sha3_512",
        )
        if h in hashlib.algorithms_guaranteed
    ]

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

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

        self.__translator = None
        self.__loadTranslator()

        self.__initMenus()

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

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

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

        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.__fileMenu)
            self.__mainActions.append(act)
            act = menu.addMenu(self.__dirMenu)
            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__), "ToolGenerateHash", "i18n"
                )
                translation = "generatehash_{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 __initMenus(self):
        """
        Private method to initialize the hash generation menus.
        """
        self.__fileMenu = QMenu(self.tr("Generate File Hash"))
        for hashName in self.Hashes:
            self.__fileMenu.addAction(hashName.upper().replace("_", ":")).setData(
                hashName
            )
        self.__fileMenu.setEnabled(False)
        self.__fileMenu.triggered.connect(self.__hashFile)

        self.__dirMenu = QMenu(self.tr("Generate Directory Hash"))
        for hashName in self.Hashes:
            self.__dirMenu.addAction(hashName.upper().replace("_", ":")).setData(
                hashName
            )
        self.__dirMenu.setEnabled(False)
        self.__dirMenu.triggered.connect(self.__hashDirectory)

    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.__fileMenu)
            act.setEnabled(editor is not None)
            act = menu.addMenu(self.__dirMenu)
            act.setEnabled(editor is not None)
        elif name == "PluginTools" and self.__mainActions:
            self.__mainActions[-2].setEnabled(editor is not None)
            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.__fileMenu)
            self.__editors[editor].append(act)
            act = menu.addMenu(self.__dirMenu)
            self.__editors[editor].append(act)
            editor.showMenu.connect(self.__editorShowMenu)

            self.__fileMenu.setEnabled(True)
            self.__dirMenu.setEnabled(True)

    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.__fileMenu.setEnabled(False)
                self.__dirMenu.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.__fileMenu.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.__fileMenu)
            self.__editors[editor].append(act)
            act = menu.addMenu(self.__dirMenu)
            self.__editors[editor].append(act)

            self.__fileMenu.setEnabled(True)
            self.__dirMenu.setEnabled(True)

    def __insertHash(self, hashStr):
        """
        Private method to insert the generated hash string.

        @param hashStr hash string
        @type str
        """
        if hashStr:
            editor = ericApp().getObject("ViewManager").activeWindow()
            line, index = editor.getCursorPosition()
            # It should be done this way to allow undo
            editor.beginUndoAction()
            editor.insertAt(hashStr, line, index)
            editor.endUndoAction()

    @pyqtSlot(QAction)
    def __hashFile(self, act):
        """
        Private slot to generate the hash for a file.

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

        name = EricFileDialog.getOpenFileName(self.__ui, self.tr("Generate File Hash"))
        if name:
            try:
                with open(name, "rb") as f:
                    hashStr = hashlib.new(act.data(), f.read()).hexdigest()
            except OSError as err:
                EricMessageBox.critical(
                    self.__ui,
                    self.tr("Generate File Hash"),
                    self.tr(
                        """<p>The hash for <b>{0}</b> could not"""
                        """ be generated.</p><p>Reason: {1}</p>"""
                    ).format(name, str(err)),
                )
                return

            self.__insertHash(hashStr)

    @pyqtSlot(QAction)
    def __hashDirectory(self, act):
        """
        Private slot to generate the hash for a directory.

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

        folder = EricFileDialog.getExistingDirectory(
            self.__ui, self.tr("Generate Directory Hash"), "", EricFileDialog.Option(0)
        )
        if folder and os.path.isdir(folder):
            fails = 0
            hashes = []
            for name in os.listdir(folder):
                if not name.startswith(".") and os.path.isfile(
                    os.path.join(folder, name)
                ):
                    try:
                        with open(os.path.join(folder, name), "rb") as f:
                            hashStr = hashlib.new(act.data(), f.read()).hexdigest()
                        hashes.append((name, hashStr))
                    except OSError:
                        fails += 1
            if fails:
                EricMessageBox.critical(
                    self.__ui,
                    self.tr("Generate Directory Hash"),
                    self.tr(
                        """<p>The hash for some files could not"""
                        """ be generated.</p>"""
                    ),
                )
            else:
                editor = ericApp().getObject("ViewManager").activeWindow()
                line, index = editor.getCursorPosition()
                indLevel = editor.indentation(line) // editor.indentationWidth()
                if editor.indentationsUseTabs():
                    indString = "\t"
                else:
                    indString = editor.indentationWidth() * " "
                indent = (indLevel + 1) * indString
                code = ["["]
                for name, hashStr in hashes:
                    code.append("{0}('{1}', '{2}'),".format(indent, name, hashStr))
                code.append("{0}]".format(indLevel * indString))

                self.__insertHash(os.linesep.join(code))


#
# eflag: noqa = M801

eric ide

mercurial