eric6/UI/UserInterface.py

branch
maintenance
changeset 8273
698ae46f40a4
parent 8177
5688d73cc3ae
parent 8268
6b8128e0c9d1
child 8400
b3eefd7e58d1
diff -r fb0ef164f536 -r 698ae46f40a4 eric6/UI/UserInterface.py
--- a/eric6/UI/UserInterface.py	Fri Apr 02 11:59:41 2021 +0200
+++ b/eric6/UI/UserInterface.py	Sat May 01 14:27:20 2021 +0200
@@ -15,6 +15,7 @@
 import datetime
 import getpass
 import functools
+import contextlib
 
 from PyQt5.QtCore import (
     pyqtSlot, QTimer, QFile, QFileInfo, pyqtSignal, PYQT_VERSION_STR, QDate,
@@ -59,7 +60,7 @@
     E5NetworkProxyFactory, proxyAuthenticationRequired
 )
 try:
-    from E5Network.E5SslErrorHandler import E5SslErrorHandler
+    from E5Network.E5SslErrorHandler import E5SslErrorHandler, E5SslErrorState
     SSL_AVAILABLE = True
 except ImportError:
     SSL_AVAILABLE = False
@@ -86,7 +87,7 @@
         @param parent reference to the parent object
         @type QObject
         """
-        super(Redirector, self).__init__(parent)
+        super().__init__(parent)
         self.stderr = stderr
         self.buffer = ''
         
@@ -191,7 +192,7 @@
         @param originalPathString original PATH environment variable
         @type str
         """
-        super(UserInterface, self).__init__()
+        super().__init__()
         
         self.__restartArgs = restartArguments[:]
         
@@ -200,7 +201,7 @@
         
         self.maxEditorPathLen = Preferences.getUI("CaptionFilenameLength")
         self.locale = locale
-        self.__noOpenAtStartup = noOpenAtStartup
+        self.__openAtStartup = not noOpenAtStartup
         self.__noCrashOpenAtStartup = noCrashOpenAtStartup
         self.__disableCrashSession = disableCrashSession
         self.__disabledPlugins = disabledPlugins[:]
@@ -1027,19 +1028,19 @@
         
         @param debugServer reference to the debug server object
         """
-        from E5Gui.E5SideBar import E5SideBar
+        from E5Gui.E5SideBar import E5SideBar, E5SideBarSide
         
         logging.debug("Creating Sidebars Layout...")
         
         delay = Preferences.getUI("SidebarDelay")
         # Create the left sidebar
-        self.leftSidebar = E5SideBar(E5SideBar.West, delay)
+        self.leftSidebar = E5SideBar(E5SideBarSide.WEST, delay)
         
         # Create the bottom sidebar
-        self.bottomSidebar = E5SideBar(E5SideBar.South, delay)
+        self.bottomSidebar = E5SideBar(E5SideBarSide.SOUTH, delay)
         
         # Create the right sidebar
-        self.rightSidebar = E5SideBar(E5SideBar.East, delay)
+        self.rightSidebar = E5SideBar(E5SideBarSide.EAST, delay)
         
         ####################################################
         ## Populate the left side bar
@@ -1392,7 +1393,7 @@
         
         # no args, return
         if args is None:
-            if not self.__noOpenAtStartup:
+            if self.__openAtStartup:
                 self.__openOnStartup()
             return
         
@@ -1403,10 +1404,7 @@
         # flag indicating '--' options was found
         ddseen = False
         
-        if Utilities.isWindowsPlatform():
-            argChars = ['-', '/']
-        else:
-            argChars = ['-']
+        argChars = ['-', '/'] if Utilities.isWindowsPlatform() else ['-']
 
         for arg in args:
             # handle a request to start with last session
@@ -1458,10 +1456,9 @@
         if argsStr is not None:
             self.debuggerUI.setArgvHistory(argsStr)
         
-        if opens == 0:
+        if opens == 0 and self.__openAtStartup:
             # no files, project or multiproject was given
-            if not self.__noOpenAtStartup:
-                self.__openOnStartup()
+            self.__openOnStartup()
     
     def processInstallInfoFile(self):
         """
@@ -1480,7 +1477,7 @@
                                         "eric6installpip.json")
                 if os.path.exists(filename):
                     # eric was installed via pip (i.e. eric-ide)
-                    try:
+                    with contextlib.suppress(OSError):
                         installDateTime = datetime.datetime.now(tz=None)
                         with open(filename, "r") as infoFile:
                             installInfo = json.load(infoFile)
@@ -1500,9 +1497,6 @@
                             installInfo["eric"], os.W_OK)
                         with open(installInfoFile, "w") as infoFile:
                             json.dump(installInfo, infoFile, indent=2)
-                    except OSError:
-                        # ignore this
-                        pass
         else:
             changed = False
             with open(installInfoFile, "r") as infoFile:
@@ -3747,10 +3741,7 @@
         except (ImportError, AttributeError):
             sip_version_str = "sip version not available"
         
-        if sys.maxsize > 2**32:
-            sizeStr = "64-Bit"
-        else:
-            sizeStr = "32-Bit"
+        sizeStr = "64-Bit" if sys.maxsize > 2**32 else "32-Bit"
         
         versionText = self.tr(
             """<h2>Version Numbers</h2>"""
@@ -3764,34 +3755,28 @@
         versionText += (
             """<tr><td><b>PyQt</b></td><td>{0}</td></tr>"""
         ).format(PYQT_VERSION_STR)
-        try:
+        with contextlib.suppress(ImportError, AttributeError):
             from PyQt5 import QtChart
             versionText += (
                 """<tr><td><b>PyQtChart</b></td><td>{0}</td></tr>"""
             ).format(QtChart.PYQT_CHART_VERSION_STR)
-        except (ImportError, AttributeError):
-            pass
-        try:
+        with contextlib.suppress(ImportError, AttributeError):
             from PyQt5 import QtWebEngine
             versionText += (
                 """<tr><td><b>PyQtWebEngine</b></td><td>{0}</td></tr>"""
             ).format(QtWebEngine.PYQT_WEBENGINE_VERSION_STR)
-        except (ImportError, AttributeError):
-            pass
         versionText += (
             """<tr><td><b>QScintilla</b></td><td>{0}</td></tr>"""
         ).format(QSCINTILLA_VERSION_STR)
         versionText += (
             """<tr><td><b>sip</b></td><td>{0}</td></tr>"""
         ).format(sip_version_str)
-        try:
+        with contextlib.suppress(ImportError):
             from WebBrowser.Tools import WebBrowserTools
             chromeVersion = WebBrowserTools.getWebEngineVersions()[0]
             versionText += (
                 """<tr><td><b>WebEngine</b></td><td>{0}</td></tr>"""
             ).format(chromeVersion)
-        except ImportError:
-            pass
         versionText += ("""<tr><td><b>{0}</b></td><td>{1}</td></tr>"""
                         ).format(Program, Version)
         versionText += self.tr("""</table>""")
@@ -3852,10 +3837,7 @@
         @param deleteAttachFile flag indicating to delete the file after
             it has been read (boolean)
         """
-        if mode == "feature":
-            address = FeatureAddress
-        else:
-            address = BugAddress
+        address = FeatureAddress if mode == "feature" else BugAddress
         subject = "[eric] "
         if attachFile is not None:
             with open(attachFile, "r", encoding="utf-8") as f:
@@ -3971,13 +3953,11 @@
             It must be one of "ui" or "wizards".
         """
         for act in actions:
-            try:
+            with contextlib.suppress(ValueError):
                 if actionType == 'ui':
                     self.actions.remove(act)
                 elif actionType == 'wizards':
                     self.wizardsActions.remove(act)
-            except ValueError:
-                pass
         
     def getActions(self, actionType):
         """
@@ -4112,12 +4092,9 @@
         """
         toolbars = []
         for tbName in self.__toolbars:
-            try:
+            with contextlib.suppress(IndexError):
                 if self.__toolbars[tbName][2] == category:
                     toolbars.append(self.__toolbars[tbName][1])
-            except IndexError:
-                # backward compatibility; category is not yet supported
-                pass
         
         return toolbars
     
@@ -4144,15 +4121,16 @@
         @param ask flag indicating to ask the user for permission
         @type bool
         """
-        if ask:
-            res = E5MessageBox.yesNo(
+        res = (
+            E5MessageBox.yesNo(
                 self,
                 self.tr("Restart application"),
                 self.tr(
                     """The application needs to be restarted. Do it now?"""),
                 yesDefault=True)
-        else:
-            res = True
+            if ask else
+            True
+        )
         
         if res and self.__shutdown():
             e5App().closeAllWindows()
@@ -4238,9 +4216,10 @@
         self.__menus["user_tools"].addSeparator()
         
         # add the configurable entries
-        idx = 0
         try:
-            for tool in self.toolGroups[self.currentToolGroup][1]:
+            for idx, tool in enumerate(
+                self.toolGroups[self.currentToolGroup][1]
+            ):
                 if tool['menutext'] == '--':
                     self.__menus["user_tools"].addSeparator()
                 else:
@@ -4248,7 +4227,6 @@
                         UI.PixmapCache.getIcon(tool['icon']),
                         tool['menutext'])
                     act.setData(idx)
-                idx += 1
         except IndexError:
             # the current tool group might have been deleted
             act = self.__menus["user_tools"].addAction(
@@ -4263,15 +4241,13 @@
         
         # add the configurable tool groups
         if self.toolGroups:
-            idx = 0
-            for toolGroup in self.toolGroups:
+            for idx, toolGroup in enumerate(self.toolGroups):
                 act = self.toolGroupsMenu.addAction(toolGroup[0])
                 act.setData(idx)
                 if self.currentToolGroup == idx:
                     font = act.font()
                     font.setBold(True)
                     act.setFont(font)
-                idx += 1
         else:
             act = self.toolGroupsMenu.addAction(
                 self.tr("No User Tools Configured"))
@@ -6329,14 +6305,15 @@
             if ex:
                 fn += ex
         
-        if os.path.exists(fn):
-            ok = E5MessageBox.yesNo(
+        ok = (
+            E5MessageBox.yesNo(
                 self,
                 self.tr("Export Keyboard Shortcuts"),
                 self.tr("""<p>The keyboard shortcuts file <b>{0}</b> exists"""
                         """ already. Overwrite it?</p>""").format(fn))
-        else:
-            ok = True
+            if os.path.exists(fn) else
+            True
+        )
         
         if ok:
             from Preferences import Shortcuts
@@ -6486,11 +6463,8 @@
         
         @param editor editor window
         """
-        if editor:
-            fn = editor.getFileName()
-        else:
-            fn = None
-            
+        fn = editor.getFileName() if editor else None
+        
         if fn:
             dbs = e5App().getObject("DebugServer")
             for language in dbs.getSupportedLanguages():
@@ -6687,11 +6661,8 @@
             fn = os.path.join(Utilities.getConfigDir(),
                               f"eric6_crash_session{ext}")
             if os.path.exists(fn):
-                try:
+                with contextlib.suppress(OSError):
                     os.remove(fn)
-                except OSError:
-                    # ignore it silently
-                    pass
     
     def __writeCrashSession(self):
         """
@@ -6954,9 +6925,8 @@
         if self.__webBrowserProcess is not None:
             self.__webBrowserShutdown()
         
-        if self.irc is not None:
-            if not self.irc.shutdown():
-                return False
+        if self.irc is not None and not self.irc.shutdown():
+            return False
         
         sessionCreated = self.__writeSession()
         
@@ -7060,15 +7030,13 @@
                         "Updates/LastCheckDate", QDate(1970, 1, 1))
                     if lastCheck.isValid():
                         now = QDate.currentDate()
-                        if period == 2 and lastCheck.day() == now.day():
-                            # daily
-                            return
-                        elif period == 3 and lastCheck.daysTo(now) < 7:
-                            # weekly
-                            return
-                        elif period == 4 and (lastCheck.daysTo(now) <
-                                              lastCheck.daysInMonth()):
-                            # monthly
+                        if (
+                            (period == 2 and lastCheck.day() == now.day()) or
+                            (period == 3 and lastCheck.daysTo(now) < 7) or
+                            (period == 4 and (lastCheck.daysTo(now) <
+                                              lastCheck.daysInMonth()))
+                        ):
+                            # daily, weekly, monthly
                             return
         
         self.__inVersionCheck = True
@@ -7319,7 +7287,7 @@
         @param errors list of SSL errors (list of QSslError)
         """
         ignored = self.__sslErrorHandler.sslErrorsReply(reply, errors)[0]
-        if ignored == E5SslErrorHandler.NotIgnored:
+        if ignored == E5SslErrorState.NOT_IGNORED:
             self.__downloadCancelled = True
     
     #######################################
@@ -7463,7 +7431,7 @@
     ##########################################
     
     def showNotification(self, icon, heading, text,
-                         kind=NotificationTypes.Information, timeout=None):
+                         kind=NotificationTypes.INFORMATION, timeout=None):
         """
         Public method to show a desktop notification.
         

eric ide

mercurial