src/eric7/Project/Project.py

branch
eric7
changeset 9520
e12589f1d408
parent 9517
d73c3a1e432b
child 9525
477545eef9f4
diff -r d7ab0653bc63 -r e12589f1d408 src/eric7/Project/Project.py
--- a/src/eric7/Project/Project.py	Tue Nov 22 14:02:00 2022 +0100
+++ b/src/eric7/Project/Project.py	Tue Nov 22 16:33:30 2022 +0100
@@ -57,6 +57,7 @@
 from eric7.UI.NotificationWidget import NotificationTypes
 
 from .DebuggerPropertiesFile import DebuggerPropertiesFile
+from .FileCategoryRepositoryItem import FileCategoryRepositoryItem
 from .ProjectBrowserModel import ProjectBrowserModel
 from .ProjectFile import ProjectFile
 from .UserProjectFile import UserProjectFile
@@ -182,6 +183,11 @@
             ),
         }
 
+        self.__fileCategoriesRepository = {}
+        # This dictionary will be populated by the various project browsers with
+        # classes of type 'FileCategoryRepositoryItem' using the 'addFileCategory()
+        # and removeFileCategory() methods.
+
         self.vcsMenu = None
         self.__makeProcess = None
 
@@ -214,6 +220,50 @@
 
         self.processChangedProjectFiles.connect(self.__autoExecuteMake)
 
+    def addFileCategory(self, category, categoryItem):
+        """
+        Public method to add a file category to the categories repository.
+
+        Note: The given category must not be contained in the repository already.
+
+        @param category file category (must be unique)
+        @type str
+        @param categoryItem data class instance containing the category data
+        @type FileCategoryRepositoryItem
+        @exception TypeError raised to signal a wrong type for the category item
+        """
+        if not isinstance(categoryItem, FileCategoryRepositoryItem):
+            raise TypeError(
+                "'categoryItem' must be an instance of 'FileCategoryRepositoryItem'."
+            )
+
+        if category in self.__fileCategoriesRepository:
+            EricMessageBox.critical(
+                self.ui,
+                self.tr("Add File Category"),
+                self.tr(
+                    "<p>The file category <b>{0}</b> has already been added. This"
+                    " attempt will be ignored.</p>"
+                ),
+            )
+        else:
+            self.__fileCategoriesRepository[category] = categoryItem
+            with contextlib.suppress(AttributeError):
+                self.__pdata[category] = []
+
+    def removeFileCategory(self, category):
+        """
+        Public method to remove a category from the categories repository.
+
+        Note: If the category is not contained in the repository, the request to
+        remove it will be ignored silently.
+
+        @param category file category
+        @type str
+        """
+        with contextlib.suppress(KeyError):
+            del self.__fileCategoriesRepository[category]
+
     def __sourceExtensions(self, language):
         """
         Private method to get the source extensions of a programming language.
@@ -465,13 +515,6 @@
         self.__pdata = {
             "DESCRIPTION": "",
             "VERSION": "",
-            "SOURCES": [],
-            "FORMS": [],
-            "RESOURCES": [],
-            "INTERFACES": [],
-            "PROTOCOLS": [],
-            "OTHERS": [],
-            "TRANSLATIONS": [],
             "TRANSLATIONEXCEPTIONS": [],
             "TRANSLATIONPATTERN": "",
             "TRANSLATIONSBINPATH": "",
@@ -526,54 +569,8 @@
             "LICENSE": "",
             "EMBEDDED_VENV": False,
         }
-        # TODO: Move these to a file categories repository populated through the
-        #       project browsers
-        self.__knownFileCategories = [
-            "FORMS",
-            "OTHERS",
-            "RESOURCES",
-            "SOURCES",
-            "TRANSLATIONS",
-            "INTERFACES",
-            "PROTOCOLS",
-        ]
-        self.__fileCategoryFilterTemplates = {
-            "FORMS": self.tr("Form Files ({0})"),
-            "OTHERS": self.tr("Other Files ({0})"),
-            "RESOURCES": self.tr("Resource Files ({0})"),
-            "SOURCES": self.tr("Source Files ({0})"),
-            "TRANSLATIONS": self.tr("Translation Files ({0})"),
-            "INTERFACES": self.tr("Interface Files ({0})"),
-            "PROTOCOLS": self.tr("Protocol Files ({0})"),
-        }
-        self.__fileCategoryUserStrings = {
-            "FORMS": self.tr("Form Files"),
-            "OTHERS": self.tr("Other Files"),
-            "RESOURCES": self.tr("Resource Files"),
-            "SOURCES": self.tr("Source Files"),
-            "TRANSLATIONS": self.tr("Translation Files"),
-            "INTERFACES": self.tr("Interface Files"),
-            "PROTOCOLS": self.tr("Protocol Files"),
-        }
-        self.__fileCategoryTyeStrings = {
-            "FORMS": self.tr("Forms"),
-            "OTHERS": self.tr("Others"),
-            "RESOURCES": self.tr("Resources"),
-            "SOURCES": self.tr("Sources"),
-            "TRANSLATIONS": self.tr("Translations"),
-            "INTERFACES": self.tr("Interfaces"),
-            "PROTOCOLS": self.tr("Protocols"),
-        }
-        self.__fileCategoryExtensions = {
-            "FORMS": ["*.ui"],
-            "OTHERS": [],
-            "RESOURCES": ["*.qrc"],
-            "SOURCES": ["*.py", "*.pyw"],  # Python files as default
-            "TRANSLATIONS": ["*.ts", "*.qm"],
-            "INTERFACES": ["*.idl"],
-            "PROTOCOLS": ["*.proto"],
-        }
-        # until here
+        for category in self.__fileCategoriesRepository:
+            self.__pdata[category] = []
 
         self.__initDebugProperties()
 
@@ -705,7 +702,7 @@
         @return list of known file categories
         @rtype list of str
         """
-        return self.__knownFileCategories[:]
+        return list(self.__fileCategoriesRepository.keys())
 
     def getFileCategoryFilterString(
         self, categories=None, withOthers=False, withAll=True
@@ -726,19 +723,21 @@
         @rtype str
         """
         if categories is None:
-            categories = [c for c in self.__knownFileCategories if c != "OTHERS"]
+            categories = [c for c in self.__fileCategoriesRepository if c != "OTHERS"]
             if withOthers:
                 categories.append("OTHERS")
 
         patterns = collections.defaultdict(list)
         for pattern, filetype in self.__pdata["FILETYPES"].items():
-            if filetype in categories and filetype in self.__knownFileCategories:
+            if filetype in categories and filetype in self.__fileCategoriesRepository:
                 patterns[filetype].append(pattern)
 
         filters = []
         for filetype in patterns:
             filters.append(
-                self.__fileCategoryFilterTemplates[filetype].format(
+                self.__fileCategoriesRepository[
+                    filetype
+                ].fileCategoryFilterTemplate.format(
                     " ".join(sorted(patterns[filetype]))
                 )
             )
@@ -757,7 +756,7 @@
         @return user string for the category
         @rtype str
         """
-        return self.__fileCategoryUserStrings[category]
+        return self.__fileCategoriesRepository[category].fileCategoryUserString
 
     def getFileCategoryType(self, category):
         """
@@ -768,7 +767,7 @@
         @return user type string for the category
         @rtype str
         """
-        return self.__fileCategoryTyeStrings[category]
+        return self.__fileCategoriesRepository[category].fileCategoryTyeString
 
     def getFileCategoryExtension(self, category, reverse=False):
         """
@@ -784,12 +783,12 @@
         """
         if reverse:
             extensions = []
-            for cat, ext in self.__fileCategoryExtensions.items():
+            for cat, item in self.__fileCategoriesRepository.items():
                 if cat != category:
-                    extensions += ext
+                    extensions += item.fileCategoryExtensions[:]
             return extensions
         else:
-            return self.__fileCategoryExtensions[category][:]
+            return self.__fileCategoriesRepository[category].fileCategoryExtensions[:]
 
     def initFileTypes(self):
         """
@@ -1085,13 +1084,11 @@
 
             # check, if the files of the project still exist in the
             # project directory
-            for fileCategory in self.__knownFileCategories:
+            for fileCategory in self.getFileCategories():
                 self.__checkFilesExist(fileCategory)
 
             # get the names of subdirectories the files are stored in
-            for fileCategory in [
-                c for c in self.__knownFileCategories if c != "OTHERS"
-            ]:
+            for fileCategory in [c for c in self.getFileCategories() if c != "OTHERS"]:
                 for fn in self.__pdata[fileCategory]:
                     dn = os.path.dirname(fn)
                     if dn not in self.subdirs:
@@ -2152,7 +2149,7 @@
             )
             return False
 
-        if any(fn in self.__pdata[category] for category in self.__knownFileCategories):
+        if any(fn in self.__pdata[category] for category in self.getFileCategories()):
             self.renameFileInPdata(oldfn, newfn, isSourceFile)
 
         return True
@@ -2189,7 +2186,7 @@
         filelist = []
         start = self.getRelativePath(start)
         for fileCategory in [
-            c for c in self.__knownFileCategories if c != "TRANSLATIONS"
+            c for c in self.getFileCategories() if c != "TRANSLATIONS"
         ]:
             for entry in self.__pdata[fileCategory][:]:
                 if entry.startswith(start):
@@ -2204,11 +2201,11 @@
 
         # init data store for the reorganization
         newPdata = {}
-        for fileCategory in self.__knownFileCategories:
+        for fileCategory in self.getFileCategories():
             newPdata[fileCategory] = []
 
         # iterate over all files checking for a reassignment
-        for fileCategory in self.__knownFileCategories:
+        for fileCategory in self.getFileCategories():
             for fn in self.__pdata[fileCategory][:]:
                 filetype = fileCategory
                 bfn = os.path.basename(fn)
@@ -2233,7 +2230,7 @@
             ##"OTHERS",
             ##"TRANSLATIONS",
             ##]:
-            for fileCategory in self.__knownFileCategories:
+            for fileCategory in self.getFileCategories():
                 self.__pdata[fileCategory] = newPdata[fileCategory][:]
 
             # repopulate the model
@@ -2258,7 +2255,7 @@
         ##"OTHERS",
         ##]:
         for fileCategory in [
-            c for c in self.__knownFileCategories if c != "TRANSLATIONS"
+            c for c in self.getFileCategories() if c != "TRANSLATIONS"
         ]:
             for entry in self.__pdata[fileCategory][:]:
                 if entry.startswith(olddn):
@@ -2287,7 +2284,7 @@
         ##"OTHERS",
         ##]:
         for fileCategory in [
-            c for c in self.__knownFileCategories if c != "TRANSLATIONS"
+            c for c in self.getFileCategories() if c != "TRANSLATIONS"
         ]:
             for entry in self.__pdata[fileCategory][:]:
                 if entry.startswith(olddn):
@@ -2348,7 +2345,7 @@
                 self.__pdata["OTHERS"].remove(entry)
                 dirty = True
         dn2 = dn if dn.endswith(os.sep) else dn + os.sep
-        for fileCategory in [c for c in self.__knownFileCategories if c != "OTHERS"]:
+        for fileCategory in [c for c in self.getFileCategories() if c != "OTHERS"]:
             for entry in self.__pdata[fileCategory][:]:
                 if entry.startswith(dn2):
                     self.__pdata[fileCategory].remove(entry)
@@ -2443,7 +2440,7 @@
         fn = self.getRelativePath(fn)
         return any(
             fn in self.__pdata[category]
-            for category in self.__knownFileCategories
+            for category in self.getFileCategories()
             if category != "TRANSLATIONS"
         )
 
@@ -3592,7 +3589,7 @@
         @rtype list of str
         @exception ValueError raised when an unsupported file type is given
         """
-        if fileType not in self.__knownFileCategories:
+        if fileType not in self.getFileCategories():
             raise ValueError("Given file type has incorrect value.")
 
         if normalized:
@@ -4006,8 +4003,7 @@
         newfn = os.path.abspath(fn)
         newfn = self.getRelativePath(newfn)
         return any(
-            newfn in self.__pdata[category]
-            for category in self.__knownFileCategories
+            newfn in self.__pdata[category] for category in self.getFileCategories()
         )
 
     def isProjectFile(self, fn):
@@ -4020,7 +4016,7 @@
         """
         return any(
             self.__checkProjectFileGroup(fn, category)
-            for category in self.__knownFileCategories
+            for category in self.getFileCategories()
         )
 
     def __checkProjectFileGroup(self, fn, group):
@@ -5511,7 +5507,7 @@
                         break
 
                 if (
-                    filetype in self.__knownFileCategories
+                    filetype in self.getFileCategories()
                     and fn not in self.__pdata[filetype]
                     and (
                         filetype != "TRANSLATIONS"
@@ -6093,7 +6089,7 @@
 
         # build the list of entries
         lst_ = []
-        for key in self.__knownFileCategories:
+        for key in self.getFileCategories():
             lst_.extend(self.__pdata[key])
         lst = []
         for entry in lst_:

eric ide

mercurial