src/eric7/Toolbox/Startup.py

branch
eric7
changeset 9209
b99e7fd55fd3
parent 8881
54e42bc2437a
child 9221
bf71ee032bb4
equal deleted inserted replaced
9208:3fc8dfeb6ebe 9209:b99e7fd55fd3
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2002 - 2022 Detlev Offenbach <detlev@die-offenbachs.de>
4 #
5
6 """
7 Module implementing some startup helper funcions.
8 """
9
10 import os
11 import sys
12
13 from PyQt6.QtCore import QTranslator, QLocale, QLibraryInfo, QDir
14 from PyQt6.QtWidgets import QApplication
15
16 from EricWidgets.EricApplication import EricApplication
17
18 import Globals
19
20 import UI.PixmapCache
21
22 from eric7config import getConfig
23
24 application = None
25
26
27 def usage(appinfo, optlen=12):
28 """
29 Module function to show the usage information.
30
31 @param appinfo dictionary describing the application
32 @param optlen length of the field for the commandline option (integer)
33 """
34 options = [
35 ("--version", "show the program's version number and exit"),
36 ("-h, --help", "show this help message and exit")
37 ]
38 options.extend(appinfo["options"])
39
40 print("""\n"""
41 """Usage: {bin} [OPTIONS] {arg}\n"""
42 """\n"""
43 """{name} - {description}\n"""
44 """\n"""
45 """Options:""".format(**appinfo))
46 for opt in options:
47 print(" {0} {1}".format(opt[0].ljust(optlen), opt[1]))
48 sys.exit(0)
49
50
51 def version(appinfo):
52 """
53 Module function to show the version information.
54
55 @param appinfo dictionary describing the application
56 """
57 print("""\n"""
58 """{name} {version}\n"""
59 """\n"""
60 """{description}\n"""
61 """\n"""
62 """Copyright (c) 2002 - 2022 Detlev Offenbach"""
63 """ <detlev@die-offenbachs.de>\n"""
64 """This is free software; see LICENSE.GPL3 for copying"""
65 """ conditions.\n"""
66 """There is NO warranty; not even for MERCHANTABILITY or FITNESS"""
67 """ FOR A\n"""
68 """PARTICULAR PURPOSE.""".format(**appinfo))
69 sys.exit(0)
70
71
72 def handleArgs(argv, appinfo):
73 """
74 Module function to handle the always present commandline options.
75
76 @param argv list of commandline parameters (list of strings)
77 @param appinfo dictionary describing the application
78 @return index of the '--' option (integer). This is used to tell
79 the application, that all additional options don't belong to
80 the application.
81 """
82 ddindex = 30000 # arbitrarily large number
83 args = {
84 "--version": version,
85 "--help": usage,
86 "-h": usage
87 }
88 if '--' in argv:
89 ddindex = argv.index("--")
90 for a in args:
91 if a in argv and argv.index(a) < ddindex:
92 args[a](appinfo)
93 return ddindex
94
95
96 def loadTranslatorForLocale(dirs, tn):
97 """
98 Module function to find and load a specific translation.
99
100 @param dirs Searchpath for the translations. (list of strings)
101 @param tn The translation to be loaded. (string)
102 @return Tuple of a status flag and the loaded translator
103 (int, QTranslator)
104 """
105 trans = QTranslator(None)
106 for directory in dirs:
107 loaded = trans.load(tn, directory)
108 if loaded:
109 return (trans, True)
110
111 print("Warning: translation file '" + tn + "'could not be loaded.")
112 print("Using default.")
113 return (None, False)
114
115
116 def initializeResourceSearchPath(application):
117 """
118 Module function to initialize the default mime source factory.
119
120 @param application reference to the application object
121 @type EricApplication
122 """
123 import Preferences
124
125 defaultIconPaths = getDefaultIconPaths(application)
126 iconPaths = Preferences.getIcons("Path")
127 for iconPath in iconPaths:
128 if iconPath:
129 UI.PixmapCache.addSearchPath(iconPath)
130 for defaultIconPath in defaultIconPaths:
131 if defaultIconPath not in iconPaths:
132 UI.PixmapCache.addSearchPath(defaultIconPath)
133
134
135 def getDefaultIconPaths(application):
136 """
137 Module function to determine the default icon paths.
138
139 @param application reference to the application object
140 @type EricApplication
141 @return list of default icon paths
142 @rtype list of str
143 """
144 import Preferences
145
146 defaultIconsPath = Preferences.getIcons("DefaultIconsPath")
147 if defaultIconsPath == "automatic":
148 if application.usesDarkPalette():
149 # dark desktop
150 defaultIconsPath = "breeze-dark"
151 else:
152 # light desktop
153 defaultIconsPath = "breeze-light"
154
155 return [
156 os.path.join(getConfig('ericIconDir'), defaultIconsPath),
157 os.path.join(getConfig('ericIconDir'), defaultIconsPath, "languages"),
158 ]
159
160
161 def setLibraryPaths():
162 """
163 Module function to set the Qt library paths correctly.
164 """
165 libPaths = (
166 os.path.join(Globals.getPyQt6ModulesDirectory(), "plugins"),
167 os.path.join(Globals.getPyQt6ModulesDirectory(), "Qt6", "plugins"),
168 )
169
170 libraryPaths = QApplication.libraryPaths()
171 for libPath in libPaths:
172 if os.path.exists(libPath):
173 libPath = QDir.fromNativeSeparators(libPath)
174 if libPath not in libraryPaths:
175 libraryPaths.insert(0, libPath)
176 QApplication.setLibraryPaths(libraryPaths)
177
178 # the translator must not be deleted, therefore we save them here
179 loaded_translators = {}
180
181
182 def loadTranslators(qtTransDir, app, translationFiles=()):
183 """
184 Module function to load all required translations.
185
186 @param qtTransDir directory of the Qt translations files (string)
187 @param app reference to the application object (QApplication)
188 @param translationFiles tuple of additional translations to
189 be loaded (tuple of strings)
190 @return the requested locale (string)
191 """
192 import Preferences
193
194 global loaded_translators
195
196 translations = (
197 "qt", "qt_help", "qtbase", "qtmultimedia", "qtserialport",
198 "qtwebengine", "qtwebsockets", "eric7"
199 ) + translationFiles
200 loc = Preferences.getUILanguage()
201 if loc is None:
202 return ""
203
204 if loc == "System":
205 loc = QLocale.system().name()
206 if loc != "C":
207 dirs = [getConfig('ericTranslationsDir'), Globals.getConfigDir()]
208 if qtTransDir is not None:
209 dirs.append(qtTransDir)
210
211 loca = loc
212 for tf in ["{0}_{1}".format(tr, loc) for tr in translations]:
213 translator, ok = loadTranslatorForLocale(dirs, tf)
214 loaded_translators[tf] = translator
215 if ok:
216 app.installTranslator(translator)
217 else:
218 if tf.startswith("eric7"):
219 loca = None
220 loc = loca
221 else:
222 loc = None
223 return loc
224
225
226 def simpleAppStartup(argv, appinfo, mwFactory, quitOnLastWindowClosed=True,
227 app=None, raiseIt=True, installErrorHandler=False):
228 """
229 Module function to start up an application that doesn't need a specialized
230 start up.
231
232 This function is used by all of eric's helper programs.
233
234 @param argv list of commandline parameters (list of strings)
235 @param appinfo dictionary describing the application
236 @param mwFactory factory function generating the main widget. This
237 function must accept the following parameter.
238 <dl>
239 <dt>argv</dt>
240 <dd>list of commandline parameters (list of strings)</dd>
241 </dl>
242 @param quitOnLastWindowClosed flag indicating to quit the application,
243 if the last window was closed (boolean)
244 @param app reference to the application object (QApplication or None)
245 @param raiseIt flag indicating to raise the generated application
246 window (boolean)
247 @param installErrorHandler flag indicating to install an error
248 handler dialog (boolean)
249 @return exit result (integer)
250 """
251 global application
252
253 if "__PYVENV_LAUNCHER__" in os.environ:
254 del os.environ["__PYVENV_LAUNCHER__"]
255
256 handleArgs(argv, appinfo)
257 if app is None:
258 # set the library paths for plugins
259 setLibraryPaths()
260 app = EricApplication(argv)
261 application = app
262 app.setQuitOnLastWindowClosed(quitOnLastWindowClosed)
263
264 # the following code depends upon a valid application object
265 import Preferences
266
267 # set the application style sheet
268 app.setStyleSheetFile(Preferences.getUI("StyleSheet"))
269
270 initializeResourceSearchPath(app)
271 QApplication.setWindowIcon(UI.PixmapCache.getIcon("eric"))
272
273 qtTransDir = Preferences.getQtTranslationsDir()
274 if not qtTransDir:
275 qtTransDir = QLibraryInfo.path(
276 QLibraryInfo.LibraryPath.TranslationsPath)
277 loadTranslators(qtTransDir, app, ("qscintilla",))
278 # qscintilla needed for web browser
279
280 w = mwFactory(argv)
281 if w is None:
282 return 100
283
284 if quitOnLastWindowClosed:
285 app.lastWindowClosed.connect(app.quit)
286 w.show()
287 if raiseIt:
288 w.raise_()
289
290 if installErrorHandler:
291 # generate a graphical error handler
292 from EricWidgets import EricErrorMessage
293 eMsg = EricErrorMessage.qtHandler()
294 eMsg.setMinimumSize(600, 400)
295
296 return app.exec()
297
298 #
299 # eflag: noqa = M801

eric ide

mercurial