Continued implementing pybabel translations support.

Thu, 19 Nov 2020 18:34:05 +0100

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Thu, 19 Nov 2020 18:34:05 +0100
changeset 14
d2da14b2a233
parent 13
ed33cdfca13d
child 15
3f5c05eb2d5f

Continued implementing pybabel translations support.

ProjectFlask/Project.py file | annotate | diff | comparison | revisions
ProjectFlask/PyBabelConfigDialog.py file | annotate | diff | comparison | revisions
diff -r ed33cdfca13d -r d2da14b2a233 ProjectFlask/Project.py
--- a/ProjectFlask/Project.py	Wed Nov 18 20:16:06 2020 +0100
+++ b/ProjectFlask/Project.py	Thu Nov 19 18:34:05 2020 +0100
@@ -554,6 +554,22 @@
             environment object to be used with QProcess
         @rtype tuple of (str, QProcessEnvironment)
         """
+        workdir, app = self.getApplication()
+        env = QProcessEnvironment.systemEnvironment()
+        env.insert("FLASK_APP", app)
+        if development:
+            env.insert("FLASK_ENV", "development")
+        
+        return workdir, env
+    
+    def getApplication(self):
+        """
+        Public method to determine the application name and the respective
+        working directory.
+        
+        @return tuple containing the working directory and the application name
+        @rtype tuple of (str, str)
+        """
         mainScript = self.__e5project.getMainScript(normalized=True)
         if not mainScript:
             E5MessageBox.critical(
@@ -568,13 +584,7 @@
             workdir, app = os.path.split(scriptPath)
         else:
             workdir, app = scriptPath, scriptName
-        
-        env = QProcessEnvironment.systemEnvironment()
-        env.insert("FLASK_APP", app)
-        if development:
-            env.insert("FLASK_ENV", "development")
-        
-        return workdir, env
+        return workdir, app
     
     def getData(self, category, key):
         """
@@ -798,19 +808,75 @@
             config = dlg.getConfiguration()
             self.setData("pybabel", "", config)
             
-            if not os.path.exists(config["configFile"]):
-                self.__createBabelCfg(config["configFile"])
+            cfgFileName = self.__e5project.getAbsoluteUniversalPath(
+                config["configFile"])
+            if not os.path.exists(cfgFileName):
+                self.__createBabelCfg(cfgFileName)
+    
+    def __ensurePybabelConfigured(self):
+        """
+        Private method to ensure, that PyBabel has been configured.
+        
+        @return flag indicating successful configuration
+        @rtype bool
+        """
+        config = self.getData("pybabel", "")
+        if not config:
+            self.__configurePybabel()
+            return True
+        
+        configFileName = self.getData("pybabel", "configFile")
+        if configFileName:
+            cfgFileName = self.__e5project.getAbsoluteUniversalPath(
+                configFileName)
+            if os.path.exists(cfgFileName):
+                return True
+            else:
+                return self.__createBabelCfg(cfgFileName)
+        
+        return False
     
     def __createBabelCfg(self, configFile):
         """
         Private method to create a template pybabel configuration file.
+        
+        @return flag indicating successful configuration file creation
+        @rtype bool
         """
-        template = (
-            "[python: {0}/**.py]\n"
-            "[jinja2: {0}/templates/**.html]\n"
-            "extensions=jinja2.ext.autoescape,jinja2.ext.with_\n"
-        )
-        # TODO: determine app name and write file
+        _, app = self.getApplication()
+        if app.endswith(".py"):
+            template = (
+                "[python: {0}]\n"
+                "[jinja2: templates/**.html]\n"
+                "extensions=jinja2.ext.autoescape,jinja2.ext.with_\n"
+            )
+        else:
+            template = (
+                "[python: {0}/**.py]\n"
+                "[jinja2: {0}/templates/**.html]\n"
+                "extensions=jinja2.ext.autoescape,jinja2.ext.with_\n"
+            )
+        try:
+            with open(configFile, "w") as f:
+                f.write(template.format(app))
+            self.__e5project.appendFile(configFile)
+            E5MessageBox.information(
+                None,
+                self.tr("Generate PyBabel Configuration File"),
+                self.tr("""The PyBabel configuration file was created."""
+                        """ Please edit it to adjust the entries as"""
+                        """ required.""")
+            )
+            return True
+        except EnvironmentError as err:
+            E5MessageBox.warning(
+                None,
+                self.tr("Generate PyBabel Configuration File"),
+                self.tr("""<p>The PyBabel Configuration File could not be"""
+                        """ generated.</p><p>Reason: {0}</p>""")
+                .format(str(err))
+            )
+            return False
     
     def __projectLanguageAdded(self, code):
         # TODO: implement this with pybabel ...
diff -r ed33cdfca13d -r d2da14b2a233 ProjectFlask/PyBabelConfigDialog.py
--- a/ProjectFlask/PyBabelConfigDialog.py	Wed Nov 18 20:16:06 2020 +0100
+++ b/ProjectFlask/PyBabelConfigDialog.py	Thu Nov 19 18:34:05 2020 +0100
@@ -32,32 +32,43 @@
         super(PyBabelConfigDialog, self).__init__(parent)
         self.setupUi(self)
         
-        e5project = e5App().getObject("Project")
+        self.__e5project = e5App().getObject("Project")
         
-        self.configFilePicker.setMode(E5PathPickerModes.OpenFileMode)
+        self.configFilePicker.setMode(
+            E5PathPickerModes.SaveFileEnsureExtensionMode)
         self.configFilePicker.setFilters(self.tr(
             "Configuration Files (*.cfg);;"
             "All Files (*)"
         ))
-        self.configFilePicker.setDefaultDirectory(e5project.getProjectPath())
+        self.configFilePicker.setDefaultDirectory(
+            self.__e5project.getProjectPath())
         
-        self.catalogFilePicker.setMode(E5PathPickerModes.OpenFileMode)
+        self.catalogFilePicker.setMode(
+            E5PathPickerModes.SaveFileEnsureExtensionMode)
         self.catalogFilePicker.setFilters(self.tr(
             "Message Catalog Files (*.pot);;"
             "All Files (*)"
         ))
-        self.catalogFilePicker.setDefaultDirectory(e5project.getProjectPath())
+        self.catalogFilePicker.setDefaultDirectory(
+            self.__e5project.getProjectPath())
         
         self.configFilePicker.setFocus(Qt.OtherFocusReason)
         
         self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
         
         if "configFile" in configuration:
-            self.configFilePicker.setText(configuration["configFile"])
+            self.configFilePicker.setText(
+                self.__e5project.getAbsoluteUniversalPath(
+                    configuration["configFile"]))
         if "catalogFile" in configuration:
-            self.catalogFilePicker.setText(configuration["catalogFile"])
+            self.catalogFilePicker.setText(
+                self.__e5project.getAbsoluteUniversalPath(
+                    configuration["catalogFile"]))
         if "markersList" in configuration:
             self.markersEdit.setText(" ".join(configuration["markersList"]))
+        
+        msh = self.minimumSizeHint()
+        self.resize(max(self.width(), msh.width()), msh.height())
     
     def getConfiguration(self):
         """
@@ -67,8 +78,10 @@
         @rtype dict
         """
         configuration = {
-            "configFile": self.configFilePicker.text(),
-            "catalogFile": self.catalogFilePicker.text(),
+            "configFile": self.__e5project.getRelativeUniversalPath(
+                self.configFilePicker.text()),
+            "catalogFile": self.__e5project.getRelativeUniversalPath(
+                self.catalogFilePicker.text()),
         }
         if self.markersEdit.text():
             configuration["markersList"] = self.markersEdit.text().split()

eric ide

mercurial