Utilities/Startup.py

changeset 2087
795992a5c561
parent 2085
b4c1f0b6dac2
child 2088
73a2ca4ac409
equal deleted inserted replaced
2085:b4c1f0b6dac2 2087:795992a5c561
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2002 - 2012 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 PyQt4.QtCore import QTranslator, QLocale, QLibraryInfo
14 from PyQt4.QtGui import QApplication
15
16 from E5Gui.E5Application import E5Application
17
18 import Preferences
19 import Utilities
20 from UI.Info import Version
21
22 import UI.PixmapCache
23
24 from eric5config import getConfig
25
26
27 def makeAppInfo(argv, name, arg, description, options=[]):
28 """
29 Module function to generate a dictionary describing the application.
30
31 @param argv list of commandline parameters (list of strings)
32 @param name name of the application (string)
33 @param arg commandline arguments (string)
34 @param description text describing the application (string)
35 @param options list of additional commandline options
36 (list of tuples of two strings (commandline option, option description)).
37 The options --version, --help and -h are always present and must not
38 be repeated in this list.
39 @return dictionary describing the application
40 """
41 return {
42 "bin": argv[0],
43 "arg": arg,
44 "name": name,
45 "description": description,
46 "version": Version,
47 "options": options
48 }
49
50
51 def usage(appinfo, optlen=12):
52 """
53 Module function to show the usage information.
54
55 @param appinfo dictionary describing the application
56 @param optlen length of the field for the commandline option (integer)
57 """
58 options = [\
59 ("--version", "show the program's version number and exit"),
60 ("-h, --help", "show this help message and exit")
61 ]
62 options.extend(appinfo["options"])
63
64 print("""
65 Usage: {bin} [OPTIONS] {arg}
66
67 {name} - {description}
68
69 Options:""".format(**appinfo))
70 for opt in options:
71 print(" {0} {1}".format(opt[0].ljust(optlen), opt[1]))
72 sys.exit(0)
73
74
75 def version(appinfo):
76 """
77 Module function to show the version information.
78
79 @param appinfo dictionary describing the application
80 """
81 print("""
82 {name} {version}
83
84 {description}
85
86 Copyright (c) 2002 - 2012 Detlev Offenbach <detlev@die-offenbachs.de>
87 This is free software; see LICENSE.GPL3 for copying conditions.
88 There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
89 PARTICULAR PURPOSE.""".format(**appinfo))
90 sys.exit(0)
91
92
93 def handleArgs(argv, appinfo):
94 """
95 Module function to handle the always present commandline options.
96
97 @param argv list of commandline parameters (list of strings)
98 @param appinfo dictionary describing the application
99 @return index of the '--' option (integer). This is used to tell
100 the application, that all additional options don't belong to
101 the application.
102 """
103 ddindex = 30000 # arbitrarily large number
104 args = {
105 "--version": version,
106 "--help": usage,
107 "-h": usage
108 }
109 if '--' in argv:
110 ddindex = argv.index("--")
111 for a in args:
112 if a in argv and argv.index(a) < ddindex:
113 args[a](appinfo)
114 return ddindex
115
116
117 def loadTranslatorForLocale(dirs, tn):
118 """
119 Module function to find and load a specific translation.
120
121 @param dirs Searchpath for the translations. (list of strings)
122 @param tn The translation to be loaded. (string)
123 @return Tuple of a status flag and the loaded translator. (int, QTranslator)
124 """
125 trans = QTranslator(None)
126 for dir in dirs:
127 loaded = trans.load(tn, dir)
128 if loaded:
129 return (trans, True)
130
131 print("Warning: translation file '" + tn + "'could not be loaded.")
132 print("Using default.")
133 return (None, False)
134
135
136 def initializeResourceSearchPath():
137 """
138 Module function to initialize the default mime source factory.
139 """
140 defaultIconPath = os.path.join(getConfig('ericIconDir'), "default")
141 iconPaths = Preferences.getIcons("Path")
142 for iconPath in iconPaths:
143 if iconPath:
144 UI.PixmapCache.addSearchPath(iconPath)
145 if not defaultIconPath in iconPaths:
146 UI.PixmapCache.addSearchPath(defaultIconPath)
147
148
149 def setLibraryPaths():
150 """
151 Module function to set the Qt library paths correctly for windows systems.
152 """
153 if Utilities.isWindowsPlatform():
154 from PyQt4 import pyqtconfig
155 libPath = os.path.join(pyqtconfig._pkg_config["pyqt_mod_dir"], "plugins")
156 if os.path.exists(libPath):
157 libPath = Utilities.fromNativeSeparators(libPath)
158 libraryPaths = QApplication.libraryPaths()
159 if libPath not in libraryPaths:
160 libraryPaths.insert(0, libPath)
161 QApplication.setLibraryPaths(libraryPaths)
162
163 # the translator must not be deleted, therefore we save them here
164 loaded_translators = {}
165
166
167 def loadTranslators(qtTransDir, app, translationFiles=()):
168 """
169 Module function to load all required translations.
170
171 @param qtTransDir directory of the Qt translations files (string)
172 @param app reference to the application object (QApplication)
173 @param translationFiles tuple of additional translations to
174 be loaded (tuple of strings)
175 @return the requested locale (string)
176 """
177 global loaded_translators
178 translations = ("qt", "eric5") + translationFiles
179 loc = Preferences.getUILanguage()
180 if loc is None:
181 return
182
183 if loc == "System":
184 loc = QLocale.system().name()
185 if loc != "C":
186 dirs = [getConfig('ericTranslationsDir'), Utilities.getConfigDir()]
187 if qtTransDir is not None:
188 dirs.append(qtTransDir)
189
190 loca = loc
191 for tf in ["{0}_{1}".format(tr, loc) for tr in translations]:
192 translator, ok = loadTranslatorForLocale(dirs, tf)
193 loaded_translators[tf] = translator
194 if ok:
195 app.installTranslator(translator)
196 else:
197 if tf.startswith("eric5"):
198 loca = None
199 loc = loca
200 else:
201 loc = None
202 return loc
203
204
205 def simpleAppStartup(argv, appinfo, mwFactory, quitOnLastWindowClosed=True,
206 app=None, raiseIt=True):
207 """
208 Module function to start up an application that doesn't need a specialized start up.
209
210 This function is used by all of eric5's helper programs.
211
212 @param argv list of commandline parameters (list of strings)
213 @param appinfo dictionary describing the application
214 @param mwFactory factory function generating the main widget. This
215 function must accept the following parameter.
216 <dl>
217 <dt>argv</dt>
218 <dd>list of commandline parameters (list of strings)</dd>
219 </dl>
220 @keyparam quitOnLastWindowClosed flag indicating to quit the application,
221 if the last window was closed (boolean)
222 @keyparam app reference to the application object (QApplication or None)
223 @keyparam raiseIt flag indicating to raise the generated application window (boolean)
224 """
225 handleArgs(argv, appinfo)
226 if app is None:
227 app = E5Application(argv)
228 app.setQuitOnLastWindowClosed(quitOnLastWindowClosed)
229
230 setLibraryPaths()
231 initializeResourceSearchPath()
232 QApplication.setWindowIcon(UI.PixmapCache.getIcon("eric.png"))
233
234 qt4TransDir = Preferences.getQt4TranslationsDir()
235 if not qt4TransDir:
236 qt4TransDir = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
237 loadTranslators(qt4TransDir, app)
238
239 w = mwFactory(argv)
240 if quitOnLastWindowClosed:
241 app.lastWindowClosed.connect(app.quit)
242 w.show()
243 if raiseIt:
244 w.raise_()
245
246 return app.exec_()

eric ide

mercurial