AssistantEric/APIsManager.py

changeset 84
67197c1f11eb
parent 77
e96c89dd66a7
child 86
11088ce2312f
diff -r b447f89da620 -r 67197c1f11eb AssistantEric/APIsManager.py
--- a/AssistantEric/APIsManager.py	Sun Oct 13 18:32:15 2013 +0200
+++ b/AssistantEric/APIsManager.py	Thu Oct 24 19:04:41 2013 +0200
@@ -11,7 +11,8 @@
 
 import os
 
-from PyQt4.QtCore import QTimer, QThread, QFileInfo, pyqtSignal, QDateTime, QObject, Qt
+from PyQt4.QtCore import QTimer, QThread, QFileInfo, pyqtSignal, QDateTime, \
+    QObject, Qt
 try:
     from PyQt4.QtSql import QSqlDatabase, QSqlQuery
 except ImportError:
@@ -44,8 +45,10 @@
     processing = pyqtSignal(int, str)
     
     populate_api_stmt = """
-        INSERT INTO api (acWord, context, fullContext, signature, fileId, pictureId)
-        VALUES (:acWord, :context, :fullContext, :signature, :fileId, :pictureId)
+        INSERT INTO api (
+        acWord, context, fullContext, signature, fileId, pictureId)
+        VALUES (
+        :acWord, :context, :fullContext, :signature, :fileId, :pictureId)
     """
     populate_del_api_stmt = """
         DELETE FROM api WHERE fileId = :fileId
@@ -74,7 +77,8 @@
         DELETE FROM file WHERE id = :id
     """
     
-    def __init__(self, proxy, language, apiFiles, projectPath="", refresh=False):
+    def __init__(self, proxy, language, apiFiles, projectPath="",
+                 refresh=False):
         """
         Constructor
         
@@ -83,15 +87,16 @@
         @param apiFiles list of API files to process (list of strings)
         @param projectPath path of the project. Only needed, if the APIs
             are extracted out of the sources of a project. (string)
-        @param refresh flag indicating a refresh of the APIs of one file (boolean)
+        @param refresh flag indicating a refresh of the APIs of one file
+            (boolean)
         """
         QThread.__init__(self)
         
         self.setTerminationEnabled(True)
         
-        # Get the AC word separators for all of the languages that the editor supports.
-        # This has to be before we create a new thread, because access to GUI elements
-        # is not allowed from non-gui threads.
+        # Get the AC word separators for all of the languages that the editor
+        # supports. This has to be before we create a new thread, because
+        # access to GUI elements is not allowed from non-GUI threads.
         self.__wseps = {}
         for lang in QScintilla.Lexers.getSupportedLanguages():
             lexer = QScintilla.Lexers.getLexer(lang)
@@ -142,7 +147,8 @@
         finally:
             db.commit()
         if self.__projectPath:
-            modTime = QFileInfo(os.path.join(self.__projectPath, apiFile)).lastModified()
+            modTime = QFileInfo(os.path.join(self.__projectPath, apiFile))\
+                .lastModified()
         else:
             modTime = QFileInfo(apiFile).lastModified()
             basesFile = os.path.splitext(apiFile)[0] + ".bas"
@@ -177,7 +183,8 @@
                         id = Editor.AttributeProtectedID
                     else:
                         id = Editor.AttributePrivateID
-                    api.append('{0}{1}?{2:d}'.format(classNameStr, variable, id))
+                    api.append('{0}{1}?{2:d}'.format(classNameStr, variable,
+                                                     id))
         return api
     
     def __loadApiFile(self, apiFile):
@@ -201,14 +208,16 @@
                     apiGenerator = APIGenerator(module)
                     apis = apiGenerator.genAPI(True, "", True)
                     if os.path.basename(apiFile).startswith("Ui_"):
-                        # it is a forms source file, extract public attributes as well
+                        # it is a forms source file, extract public attributes
+                        # as well
                         apis.extend(self.__classesAttributesApi(module))
                     try:
                         basesDict = apiGenerator.genBases(True)
                         for baseEntry in basesDict:
                             if basesDict[baseEntry]:
                                 bases.append("{0} {1}\n".format(
-                                    baseEntry, " ".join(sorted(basesDict[baseEntry]))))
+                                    baseEntry, " ".join(
+                                        sorted(basesDict[baseEntry]))))
                     except AttributeError:
                         # eric 5.1 doesn't have this method
                         pass
@@ -222,7 +231,8 @@
             try:
                 basesFile = os.path.splitext(apiFile)[0] + ".bas"
                 if os.path.exists(basesFile):
-                    bases = Utilities.readEncodedFile(basesFile)[0].splitlines(True)
+                    bases = Utilities.readEncodedFile(basesFile)[0]\
+                        .splitlines(True)
             except (IOError, UnicodeError):
                 pass
             language = None
@@ -237,8 +247,10 @@
         """
         Private method to store file info only.
         
-        Doing this avoids rereading the file whenever the API is initialized in case
-        the given file doesn't contain API data.
+        Doing this avoids rereading the file whenever the API is initialized
+        in case the given file doesn't contain API data.
+        
+        @param apiFile file name of the API file (string)
         """
         db = QSqlDatabase.database(self.__language)
         db.transaction()
@@ -458,8 +470,8 @@
     """
     Class implementing an API storage entity.
     
-    @signal apiPreparationStatus(language, status, file) emitted to indicate the
-            API preparation status for a language
+    @signal apiPreparationStatus(language, status, file) emitted to indicate
+        the API preparation status for a language
     """
     apiPreparationStatus = pyqtSignal(str, int, str)
     
@@ -508,7 +520,8 @@
     create_context_idx = """CREATE INDEX context_idx on api (context)"""
     drop_context_idx = """DROP INDEX IF EXISTS context_idx"""
     
-    create_fullContext_idx = """CREATE INDEX fullContext_idx on api (fullContext)"""
+    create_fullContext_idx = \
+        """CREATE INDEX fullContext_idx on api (fullContext)"""
     drop_fullContext_idx = """DROP INDEX IF EXISTS fullContext_idx"""
     
     create_bases_idx = """CREATE INDEX base_idx on bases (class)"""
@@ -559,7 +572,7 @@
     """
     mgmt_insert_stmt = """
         INSERT INTO mgmt (format) VALUES ({0:d})
-    """.format(DB_VERSION)
+        """.format(DB_VERSION)
     
     def __init__(self, language, parent=None):
         """
@@ -592,7 +605,8 @@
         self.__project.newProject.connect(self.__projectOpened)
         self.__project.projectClosed.connect(self.__projectClosed)
         try:
-            self.__project.projectFormCompiled.connect(self.__projectFormCompiled)
+            self.__project.projectFormCompiled.connect(
+                self.__projectFormCompiled)
         except AttributeError:
             # older eric5 versions don't have this signal
             pass
@@ -753,10 +767,10 @@
             to be completed (string)
         @keyparam followHierarchy flag indicating to follow the hierarchy of
             base classes (boolean)
-        @return list of dictionaries with possible completions (key 'completion'
-            contains the completion (string), key 'context'
-            contains the context (string) and key 'pictureId'
-            contains the ID of the icon to be shown (string))
+        @return list of dictionaries with possible completions
+            (key 'completion' contains the completion (string),
+            key 'context' contains the context (string) and
+            key 'pictureId' contains the ID of the icon to be shown (string))
         """
         completions = []
         
@@ -811,10 +825,12 @@
         Public method to determine the calltips.
         
         @param acWord function to get calltips for (string)
-        @param commas minimum number of commas contained in the calltip (integer)
+        @param commas minimum number of commas contained in the calltip
+            (integer)
         @param context string giving the context (e.g. classname) (string)
         @param fullContext string giving the full context (string)
-        @param showContext flag indicating to show the calltip context (boolean)
+        @param showContext flag indicating to show the calltip context
+            (boolean)
         @keyparam followHierarchy flag indicating to follow the hierarchy of
             base classes (boolean)
         @return list of calltips (list of string)
@@ -870,19 +886,21 @@
                 else:
                     bases = []
                 for base in bases:
-                    calltips.extend(self.getCalltips(acWord, commas, context=base,
-                                                     showContext=showContext,
-                                                     followHierarchy=True))
+                    calltips.extend(self.getCalltips(
+                        acWord, commas, context=base, showContext=showContext,
+                        followHierarchy=True))
             
             if context and len(calltips) == 0 and not followHierarchy:
                 # nothing found, try without a context
-                calltips = self.getCalltips(acWord, commas, showContext=showContext)
+                calltips = self.getCalltips(
+                    acWord, commas, showContext=showContext)
         
         return calltips
     
     def __enoughCommas(self, s, commas):
         """
-        Private method to determine, if the given string contains enough commas.
+        Private method to determine, if the given string contains enough
+        commas.
         
         @param s string to check (string)
         @param commas number of commas to check for (integer)
@@ -911,10 +929,12 @@
         """
         Private method to get the source files for the project forms.
         
-        @keyparam normalized flag indicating a normalized filename is wanted (boolean)
+        @keyparam normalized flag indicating a normalized filename is wanted
+            (boolean)
         @return list of project form sources (list of strings)
         """
-        if self.__project.pdata["PROGLANGUAGE"][0] in ["Python", "Python2", "Python3"]:
+        if self.__project.pdata["PROGLANGUAGE"][0] in ["Python", "Python2",
+                                                       "Python3"]:
             sourceExt = ".py"
         elif self.project.pdata["PROGLANGUAGE"][0] == "Ruby":
             sourceExt = ".rb"
@@ -927,7 +947,8 @@
             dirname, filename = os.path.split(ofn)
             formSource = os.path.join(dirname, "Ui_" + filename + sourceExt)
             if normalized:
-                formSource = os.path.join(self.__project.getProjectPath(), formSource)
+                formSource = os.path.join(
+                    self.__project.getProjectPath(), formSource)
             formsSources.append(formSource)
         return formsSources
     
@@ -946,12 +967,15 @@
         elif self.__language == ApisNameProject:
             apiFiles = self.__project.getSources()[:]
             apiFiles.extend(
-                [f for f in self.__getProjectFormSources() if f not in apiFiles])
+                [f for f in self.__getProjectFormSources() if
+                 f not in apiFiles])
             projectPath = self.__project.getProjectPath()
         else:
             apiFiles = Preferences.getEditorAPI(self.__language)
-        self.__worker = DbAPIsWorker(self, self.__language, apiFiles, projectPath)
-        self.__worker.processing.connect(self.__processingStatus, Qt.QueuedConnection)
+        self.__worker = DbAPIsWorker(self, self.__language, apiFiles,
+                                     projectPath)
+        self.__worker.processing.connect(
+            self.__processingStatus, Qt.QueuedConnection)
         self.__worker.start()
     
     def __processQueue(self):
@@ -969,9 +993,10 @@
                 apiFiles = [apiFiles[0].replace(projectPath + os.sep, "")]
             else:
                 projectPath = ""
-            self.__worker = DbAPIsWorker(self, self.__language, apiFiles, projectPath,
-                                         refresh=True)
-            self.__worker.processing.connect(self.__processingStatus, Qt.QueuedConnection)
+            self.__worker = DbAPIsWorker(self, self.__language, apiFiles,
+                                         projectPath, refresh=True)
+            self.__worker.processing.connect(
+                self.__processingStatus, Qt.QueuedConnection)
             self.__worker.start()
     
     def getLexer(self):
@@ -1002,17 +1027,21 @@
         """
         if status == WorkerStatusStarted:
             self.__inPreparation = True
-            self.apiPreparationStatus.emit(self.__language, WorkerStatusStarted, "")
+            self.apiPreparationStatus.emit(
+                self.__language, WorkerStatusStarted, "")
         elif status == WorkerStatusFinished:
             self.__inPreparation = False
-            self.apiPreparationStatus.emit(self.__language, WorkerStatusFinished, "")
+            self.apiPreparationStatus.emit(
+                self.__language, WorkerStatusFinished, "")
             QTimer.singleShot(0, self.__processQueue)
         elif status == WorkerStatusAborted:
             self.__inPreparation = False
-            self.apiPreparationStatus.emit(self.__language, WorkerStatusAborted, "")
+            self.apiPreparationStatus.emit(
+                self.__language, WorkerStatusAborted, "")
             QTimer.singleShot(0, self.__processQueue)
         elif status == WorkerStatusFile:
-            self.apiPreparationStatus.emit(self.__language, WorkerStatusFile, filename)
+            self.apiPreparationStatus.emit(
+                self.__language, WorkerStatusFile, filename)
     
     ########################################################
     ## project related stuff below
@@ -1022,11 +1051,13 @@
         """
         Private slot to perform actions after a project has been opened.
         """
-        if self.__project.getProjectLanguage() in ["Python", "Python2", "Python3"]:
+        if self.__project.getProjectLanguage() in ["Python", "Python2",
+                                                   "Python3"]:
             self.__discardFirst = ["self", "cls"]
         else:
             self.__discardFirst = []
-        self.__lexer = QScintilla.Lexers.getLexer(self.__project.getProjectLanguage())
+        self.__lexer = QScintilla.Lexers.getLexer(
+            self.__project.getProjectLanguage())
         self.__openAPIs()
     
     def __projectClosed(self):
@@ -1094,7 +1125,8 @@
         Public method to get an apis object for autocompletion/calltips.
         
         This method creates and loads an APIs object dynamically upon request.
-        This saves memory for languages, that might not be needed at the moment.
+        This saves memory for languages, that might not be needed at the
+        moment.
         
         @param language the language of the requested api object (string)
         @return the apis object (APIs)
@@ -1154,7 +1186,8 @@
     
     def __apiPreparationCancelled(self, language):
         """
-        Private slot handling the preparation cancelled signal of an API object.
+        Private slot handling the preparation cancelled signal of an API
+        object.
         
         @param language language of the API (string)
         """
@@ -1175,14 +1208,15 @@
             language = self.trUtf8("Project")
         
         if status == WorkerStatusStarted:
-            self.__showMessage(self.trUtf8("Preparation of '{0}' APIs started.").format(
-                language))
+            self.__showMessage(self.trUtf8(
+                "Preparation of '{0}' APIs started.").format(language))
         elif status == WorkerStatusFile:
-            self.__showMessage(self.trUtf8("'{0}' APIs: Processing '{1}'").format(
+            self.__showMessage(self.trUtf8(
+                "'{0}' APIs: Processing '{1}'").format(
                 language, os.path.basename(filename)))
         elif status == WorkerStatusFinished:
-            self.__showMessage(self.trUtf8("Preparation of '{0}' APIs finished.").format(
-                language))
+            self.__showMessage(self.trUtf8(
+                "Preparation of '{0}' APIs finished.").format(language))
         elif status == WorkerStatusAborted:
-            self.__showMessage(self.trUtf8("Preparation of '{0}' APIs cancelled.").format(
-                language))
+            self.__showMessage(self.trUtf8(
+                "Preparation of '{0}' APIs cancelled.").format(language))

eric ide

mercurial