PluginToolGenerateHash.py

branch
eric7
changeset 54
b43a0eccfc61
parent 51
b5a1a986b800
child 56
65b407bb4e24
diff -r a64adc8090ef -r b43a0eccfc61 PluginToolGenerateHash.py
--- a/PluginToolGenerateHash.py	Fri May 28 19:40:05 2021 +0200
+++ b/PluginToolGenerateHash.py	Fri May 28 19:48:54 2021 +0200
@@ -11,18 +11,19 @@
 import os
 import hashlib
 
-from PyQt5.QtCore import QObject, QTranslator
-from PyQt5.QtWidgets import QMenu
+from PyQt6.QtCore import pyqtSlot, QObject, QTranslator
+from PyQt6.QtGui import QAction
+from PyQt6.QtWidgets import QMenu
 
-from E5Gui.E5Application import e5App
-from E5Gui import E5FileDialog, E5MessageBox
+from EricWidgets.EricApplication import ericApp
+from EricWidgets import EricFileDialog, EricMessageBox
 
 # Start-Of-Header
 name = "Generate Hash Tool Plug-in"
 author = "Detlev Offenbach <detlev@die-offenbachs.de>"
 autoactivate = True
 deactivateable = True
-version = "3.2.0"
+version = "1.0.0"
 className = "ToolGenerateHashPlugin"
 packageName = "ToolGenerateHash"
 shortDescription = "Generate a hash for a selectable file or directory"
@@ -42,14 +43,11 @@
     """
     Class implementing the 'Generate Hash' tool plug-in.
     """
-    Hashes = {
-        "MD5": hashlib.md5,
-        "SHA1": hashlib.sha1,
-        "SHA224": hashlib.sha224,
-        "SHA256": hashlib.sha256,
-        "SHA384": hashlib.sha384,
-        "SHA512": hashlib.sha512,
-    }
+    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):
         """
@@ -72,7 +70,8 @@
         """
         Public method to activate this plugin.
         
-        @return tuple of None and activation status (boolean)
+        @return tuple of None and activation status
+        @rtype bool
         """
         global error
         error = ""     # clear previous error
@@ -89,12 +88,12 @@
             act = menu.addMenu(self.__dirMenu)
             self.__mainActions.append(act)
         
-        e5App().getObject("ViewManager").editorOpenedEd.connect(
+        ericApp().getObject("ViewManager").editorOpenedEd.connect(
             self.__editorOpened)
-        e5App().getObject("ViewManager").editorClosedEd.connect(
+        ericApp().getObject("ViewManager").editorClosedEd.connect(
             self.__editorClosed)
         
-        for editor in e5App().getObject("ViewManager").getOpenEditors():
+        for editor in ericApp().getObject("ViewManager").getOpenEditors():
             self.__editorOpened(editor)
         
         return None, True
@@ -111,9 +110,9 @@
                 menu.removeAction(act)
         self.__mainActions = []
 
-        e5App().getObject("ViewManager").editorOpenedEd.disconnect(
+        ericApp().getObject("ViewManager").editorOpenedEd.disconnect(
             self.__editorOpened)
-        e5App().getObject("ViewManager").editorClosedEd.disconnect(
+        ericApp().getObject("ViewManager").editorClosedEd.disconnect(
             self.__editorClosed)
         
         for editor, acts in self.__editors.items():
@@ -138,7 +137,7 @@
                 loaded = translator.load(translation, locale_dir)
                 if loaded:
                     self.__translator = translator
-                    e5App().installTranslator(self.__translator)
+                    ericApp().installTranslator(self.__translator)
                 else:
                     print("Warning: translation file '{0}' could not be"
                           " loaded.".format(translation))
@@ -149,40 +148,32 @@
         Private method to initialize the hash generation menus.
         """
         self.__fileMenu = QMenu(self.tr("Generate File Hash"))
-        self.__fileMenu.addAction("MD5", self.__hashFile).setData("MD5")
-        self.__fileMenu.addAction("SHA1", self.__hashFile).setData("SHA1")
-        self.__fileMenu.addAction("SHA224", self.__hashFile).setData("SHA224")
-        self.__fileMenu.addAction("SHA256", self.__hashFile).setData("SHA256")
-        self.__fileMenu.addAction("SHA384", self.__hashFile).setData("SHA384")
-        self.__fileMenu.addAction("SHA512", self.__hashFile).setData("SHA512")
+        for hash in self.Hashes:
+            self.__fileMenu.addAction(
+                hash.upper().replace("_", ":")).setData(hash)
         self.__fileMenu.setEnabled(False)
+        self.__fileMenu.triggered.connect(self.__hashFile)
         
         self.__dirMenu = QMenu(self.tr("Generate Directory Hash"))
-        self.__dirMenu.addAction(
-            "MD5", self.__hashDirectory).setData("MD5")
-        self.__dirMenu.addAction(
-            "SHA1", self.__hashDirectory).setData("SHA1")
-        self.__dirMenu.addAction(
-            "SHA224", self.__hashDirectory).setData("SHA224")
-        self.__dirMenu.addAction(
-            "SHA256", self.__hashDirectory).setData("SHA256")
-        self.__dirMenu.addAction(
-            "SHA384", self.__hashDirectory).setData("SHA384")
-        self.__dirMenu.addAction(
-            "SHA512", self.__hashDirectory).setData("SHA512")
+        for hash in self.Hashes:
+            self.__dirMenu.addAction(
+                hash.upper().replace("_", ":")).setData(hash)
         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 (string)
-        @param menu reference to the menu to be populated (QMenu)
+        @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 = e5App().getObject("ViewManager").activeWindow()
+        editor = ericApp().getObject("ViewManager").activeWindow()
         
         if name == "Tools":
             if not menu.isEmpty():
@@ -200,7 +191,8 @@
         """
         Private slot called, when a new editor was opened.
         
-        @param editor reference to the new editor (QScintilla.Editor)
+        @param editor reference to the new editor
+        @type Editor
         """
         menu = editor.getMenu("Tools")
         if menu is not None:
@@ -221,7 +213,8 @@
         """
         Private slot called, when an editor was closed.
         
-        @param editor reference to the editor (QScintilla.Editor)
+        @param editor reference to the editor
+        @type Editor
         """
         with contextlib.suppress(KeyError):
             del self.__editors[editor]
@@ -234,9 +227,12 @@
         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 (string)
-        @param menu reference to the menu (QMenu)
+        @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
@@ -259,33 +255,37 @@
         """
         Private method to insert the generated hash string.
         
-        @param hashStr hash string (string)
+        @param hashStr hash string
+        @type str
         """
         if hashStr:
-            editor = e5App().getObject("ViewManager").activeWindow()
+            editor = ericApp().getObject("ViewManager").activeWindow()
             line, index = editor.getCursorPosition()
-            # It should be done on this way to allow undo
+            # It should be done this way to allow undo
             editor.beginUndoAction()
             editor.insertAt(hashStr, line, index)
             editor.endUndoAction()
     
-    def __hashFile(self):
+    @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
         """
-        act = self.sender()
         if act is None:
             return
         
-        name = E5FileDialog.getOpenFileName(
+        name = EricFileDialog.getOpenFileName(
             self.__ui,
             self.tr("Generate File Hash"))
         if name:
             try:
                 with open(name, "rb") as f:
-                    hashStr = self.Hashes[act.data()](f.read()).hexdigest()
+                    hashStr = hashlib.new(act.data(), f.read()).hexdigest()
             except OSError as err:
-                E5MessageBox.critical(
+                EricMessageBox.critical(
                     self.__ui,
                     self.tr("Generate File Hash"),
                     self.tr("""<p>The hash for <b>{0}</b> could not"""
@@ -296,19 +296,22 @@
             
             self.__insertHash(hashStr)
     
-    def __hashDirectory(self):
+    @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
         """
-        act = self.sender()
         if act is None:
             return
         
-        folder = E5FileDialog.getExistingDirectory(
+        folder = EricFileDialog.getExistingDirectory(
             self.__ui,
             self.tr("Generate Directory Hash"),
             "",
-            E5FileDialog.Options(E5FileDialog.Option(0)))
+            EricFileDialog.Option(0))
         if folder and os.path.isdir(folder):
             fails = 0
             hashes = []
@@ -319,20 +322,20 @@
                 ):
                     try:
                         with open(os.path.join(folder, name), "rb") as f:
-                            hashStr = self.Hashes[act.data()](
-                                f.read()).hexdigest()
+                            hashStr = hashlib.new(
+                                act.data(), f.read()).hexdigest()
                         hashes.append((name, hashStr))
                     except OSError:
                         fails += 1
             if fails:
-                E5MessageBox.critical(
+                EricMessageBox.critical(
                     self.__ui,
                     self.tr("Generate Directory Hash"),
                     self.tr("""<p>The hash for some files could not"""
                             """ be generated.</p>""")
                 )
             else:
-                editor = e5App().getObject("ViewManager").activeWindow()
+                editor = ericApp().getObject("ViewManager").activeWindow()
                 line, index = editor.getCursorPosition()
                 indLevel = (editor.indentation(line) //
                             editor.indentationWidth())

eric ide

mercurial