eric7/Toolbox/Startup.py

branch
eric7
changeset 8312
800c432b34c8
parent 8143
2c730d5fd177
child 8314
e3642a6a1e71
equal deleted inserted replaced
8311:4e8b98454baa 8312:800c432b34c8
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2002 - 2021 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 PyQt5.QtCore import QTranslator, QLocale, QLibraryInfo, QDir
14 from PyQt5.QtWidgets import QApplication
15
16 from E5Gui.E5Application import E5Application
17
18 import Globals
19
20 import UI.PixmapCache
21
22 from eric6config 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 - 2021 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 E5Application
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 E5Application
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 for windows systems.
164 """
165 if Globals.isWindowsPlatform():
166 libPath = os.path.join(Globals.getPyQt5ModulesDirectory(), "plugins")
167 if os.path.exists(libPath):
168 libPath = QDir.fromNativeSeparators(libPath)
169 libraryPaths = QApplication.libraryPaths()
170 if libPath not in libraryPaths:
171 libraryPaths.insert(0, libPath)
172 QApplication.setLibraryPaths(libraryPaths)
173
174 # the translator must not be deleted, therefore we save them here
175 loaded_translators = {}
176
177
178 def loadTranslators(qtTransDir, app, translationFiles=()):
179 """
180 Module function to load all required translations.
181
182 @param qtTransDir directory of the Qt translations files (string)
183 @param app reference to the application object (QApplication)
184 @param translationFiles tuple of additional translations to
185 be loaded (tuple of strings)
186 @return the requested locale (string)
187 """
188 import Preferences
189
190 global loaded_translators
191
192 translations = (
193 "qt", "qt_help", "qtbase", "qtmultimedia", "qtserialport",
194 "qtwebengine", "qtwebsockets", "eric6"
195 ) + translationFiles
196 loc = Preferences.getUILanguage()
197 if loc is None:
198 return ""
199
200 if loc == "System":
201 loc = QLocale.system().name()
202 if loc != "C":
203 dirs = [getConfig('ericTranslationsDir'), Globals.getConfigDir()]
204 if qtTransDir is not None:
205 dirs.append(qtTransDir)
206
207 loca = loc
208 for tf in ["{0}_{1}".format(tr, loc) for tr in translations]:
209 translator, ok = loadTranslatorForLocale(dirs, tf)
210 loaded_translators[tf] = translator
211 if ok:
212 app.installTranslator(translator)
213 else:
214 if tf.startswith("eric6"):
215 loca = None
216 loc = loca
217 else:
218 loc = None
219 return loc
220
221
222 def simpleAppStartup(argv, appinfo, mwFactory, quitOnLastWindowClosed=True,
223 app=None, raiseIt=True, installErrorHandler=False):
224 """
225 Module function to start up an application that doesn't need a specialized
226 start up.
227
228 This function is used by all of eric's helper programs.
229
230 @param argv list of commandline parameters (list of strings)
231 @param appinfo dictionary describing the application
232 @param mwFactory factory function generating the main widget. This
233 function must accept the following parameter.
234 <dl>
235 <dt>argv</dt>
236 <dd>list of commandline parameters (list of strings)</dd>
237 </dl>
238 @param quitOnLastWindowClosed flag indicating to quit the application,
239 if the last window was closed (boolean)
240 @param app reference to the application object (QApplication or None)
241 @param raiseIt flag indicating to raise the generated application
242 window (boolean)
243 @param installErrorHandler flag indicating to install an error
244 handler dialog (boolean)
245 @return exit result (integer)
246 """
247 global application
248
249 if "__PYVENV_LAUNCHER__" in os.environ:
250 del os.environ["__PYVENV_LAUNCHER__"]
251
252 handleArgs(argv, appinfo)
253 if app is None:
254 # set the library paths for plugins
255 setLibraryPaths()
256 app = E5Application(argv)
257 application = app
258 app.setQuitOnLastWindowClosed(quitOnLastWindowClosed)
259
260 # the following code depends upon a valid application object
261 import Preferences
262
263 initializeResourceSearchPath(app)
264 QApplication.setWindowIcon(UI.PixmapCache.getIcon("eric"))
265
266 qtTransDir = Preferences.getQtTranslationsDir()
267 if not qtTransDir:
268 qtTransDir = QLibraryInfo.location(
269 QLibraryInfo.LibraryLocation.TranslationsPath)
270 loadTranslators(qtTransDir, app, ("qscintilla",))
271 # qscintilla needed for web browser
272
273 w = mwFactory(argv)
274 if w is None:
275 return 100
276
277 if quitOnLastWindowClosed:
278 app.lastWindowClosed.connect(app.quit)
279 w.show()
280 if raiseIt:
281 w.raise_()
282
283 if installErrorHandler:
284 # generate a graphical error handler
285 from E5Gui import E5ErrorMessage
286 eMsg = E5ErrorMessage.qtHandler()
287 eMsg.setMinimumSize(600, 400)
288
289 return app.exec()
290
291 #
292 # eflag: noqa = M801

eric ide

mercurial