Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100755 294 lines (254 sloc) 11.09 kB
4e61145 * Changed svn:eol-style native
phiker authored
1 #!/usr/bin/env python
2
935d277 Yay, the patch finally arrived!
phiker authored
3 # ###################################################
c6dd2cf Unfortunatly revision 1992 - 2000 were lost when moving the svn repos…
dauerflucher authored
4 # Copyright (C) 2009 The Unknown Horizons Team
844e05d * Renamed all accurances of OpenAnno to Unknown Horizons
nihathrael authored
5 # team@unknown-horizons.org
6 # This file is part of Unknown Horizons.
935d277 Yay, the patch finally arrived!
phiker authored
7 #
844e05d * Renamed all accurances of OpenAnno to Unknown Horizons
nihathrael authored
8 # Unknown Horizons is free software; you can redistribute it and/or modify
935d277 Yay, the patch finally arrived!
phiker authored
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the
20 # Free Software Foundation, Inc.,
21 # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22 # ###################################################
23
89db61a Fixed another load of spelling mistakes
totycro authored
24 """This is the Unknown Horizons launcher, it looks for fife and tries to start the game. If you want to dig
09b0056 Updated file paths from game/ to horizons/
totycro authored
25 into the game, continue to horizons/main.py. Read all docstrings and get familiar with the functions and
c9eb3e1 * Began with an incode tutorial
nihathrael authored
26 attributes. I will mark all tutorial instructions with 'TUTORIAL:'. Have fun :-)"""
27
6a1bbb1 distribute simplejson with openanno
spq authored
28 import sys
29 import os
bbf8feb Fixed distribution
totycro authored
30 import os.path
630f6b8 Made logging work again
totycro authored
31 import gettext
26d4356 Logging output will be written to a logfile via python logging module
totycro authored
32 import time
9f38e7c Small refactoring concerning logging and run_uh.py
totycro authored
33 import logging
34 import logging.config
26d4356 Logging output will be written to a logfile via python logging module
totycro authored
35 import logging.handlers
b38cc82 Switched to more comfortable option parse (from optparse module)
totycro authored
36 import optparse
21c8374 Made fatal exceptions being printed to logfile
totycro authored
37 import traceback
e669268 * Start adding gettext support (See #27)
christoph authored
38
9f38e7c Small refactoring concerning logging and run_uh.py
totycro authored
39 def log():
40 """Returns Logger"""
41 return logging.getLogger("run_uh")
42
60b23bd * Merge unknown-horizons and run_uh.py into one file
christoph authored
43 def find_uh_position():
9f38e7c Small refactoring concerning logging and run_uh.py
totycro authored
44 """Returns path, where uh is located"""
60b23bd * Merge unknown-horizons and run_uh.py into one file
christoph authored
45 first_guess = os.path.split( os.path.realpath( sys.argv[0]) )[0]
46 if os.path.exists('%s/content' % first_guess):
47 return first_guess
48 else:
49 positions = ['/usr/share/games',
50 '/usr/share',
51 '/usr/local/share/games',
52 '/usr/local/share',
53 ]
07c881a removed nature.py (Growing*)
totycro authored
54
60b23bd * Merge unknown-horizons and run_uh.py into one file
christoph authored
55 for i in positions:
56 if os.path.exists('%s/unknown-horizons' % i):
57 return '%s/unknown-horizons' % i
58
b38cc82 Switched to more comfortable option parse (from optparse module)
totycro authored
59 def get_option_parser():
60 """Returns inited OptionParser object"""
61 p = optparse.OptionParser()
62 p.add_option("-d", "--debug", dest="debug", action="store_true", default=False, \
63 help=_("Enable debug output"))
64 p.add_option("--fife-path", dest="fife_path", metavar="<path>", \
65 help=_("Specify the path to FIFE root directory."))
66
67 start_uh_group = optparse.OptionGroup(p, _("Starting unknown horizons"))
68 start_uh_group.add_option("--start-map", dest="start_map", metavar="<map>", \
69 help=_("Starts <map>. <map> is the mapname (filename without extension)"))
8f620ee * Merged production_rework branch into trunk
nihathrael authored
70 start_uh_group.add_option("--start-dev-map", dest="start_dev_map", action="store_true", \
71 default=False, help=_("Starts the development map without displaying the main menu."))
b38cc82 Switched to more comfortable option parse (from optparse module)
totycro authored
72 start_uh_group.add_option("--load-map", dest="load_map", metavar="<save>", \
73 help=_("Loads a saved game. <save> is the savegamename."))
8f620ee * Merged production_rework branch into trunk
nihathrael authored
74 start_uh_group.add_option("--load-last-quicksave", dest="load_quicksave", action="store_true", \
75 help=_("Loads the last quicksave."))
b38cc82 Switched to more comfortable option parse (from optparse module)
totycro authored
76 p.add_option_group(start_uh_group)
77
78 dev_group = optparse.OptionGroup(p, _("Development options"))
f2176f2 Added new option '--debug-log-only' (logging only to logfile).
totycro authored
79 dev_group.add_option("--debug-log-only", dest="debug_log_only", action="store_true", \
80 default=False, help=_("Write debug output only to logfile, not to console"))
b38cc82 Switched to more comfortable option parse (from optparse module)
totycro authored
81 dev_group.add_option("--debug-module", action="append", dest="debug_module", \
82 metavar="<module>", default=[], \
83 help=_("Enable logging for a certain logging module."))
84 dev_group.add_option("--fife-in-library-path", dest="fife_in_library_path", \
85 action="store_true", default=False, help=_("For internal use only."))
86 dev_group.add_option("--enable-unstable-features", dest="unstable_features", \
87 action="store_true", default=False, help=_("Enables unstable features"))
88 dev_group.add_option("--profile", dest="profile", action="store_true", default=False, \
89 help=_("Enable profiling"))
90 p.add_option_group(dev_group)
91
92 return p
60b23bd * Merge unknown-horizons and run_uh.py into one file
christoph authored
93
dcd772c Several random minor changes
totycro authored
94 def create_user_dirs():
95 """Creates the userdir and subdirs. Includes from horizons."""
96 from horizons.constants import PATHS
97 for directory in [PATHS.USER_DIR, PATHS.LOG_DIR]:
98 if not os.path.isdir(directory):
88d699b * Fixed a small bug
nihathrael authored
99 os.makedirs(directory)
9f38e7c Small refactoring concerning logging and run_uh.py
totycro authored
100
21c8374 Made fatal exceptions being printed to logfile
totycro authored
101 def excepthook_creator(outfilename):
102 """Returns an excepthook function to replace sys.excepthook.
103 The returned function does the same as the default, except it also prints the traceback
104 to a file.
105 @param outfilename: a filename to append traceback to"""
106 def excepthook(exception_type, value, tb):
107 f = open(outfilename, 'a')
108 traceback.print_exception(exception_type, value, tb, file=f)
109 traceback.print_exception(exception_type, value, tb)
f2176f2 Added new option '--debug-log-only' (logging only to logfile).
totycro authored
110 print
111 print _('Unknown Horizons crashed.')
112 print
113 print _('We are very sorry for this, and want to fix this error.')
114 print _('In order to do this, we need the information from the logfile:')
115 print outfilename
116 print _('Please give it to us via IRC or our forum, for both see unknown-horizons.org .')
21c8374 Made fatal exceptions being printed to logfile
totycro authored
117 return excepthook
118
bbf8feb Fixed distribution
totycro authored
119 def main():
b423553 make the /usr/bin script working again
christoph authored
120 #chdir to Unknown Horizons root
60b23bd * Merge unknown-horizons and run_uh.py into one file
christoph authored
121 os.chdir( find_uh_position() )
9554df1 * Made uh more distribution capable
nihathrael authored
122 logging.config.fileConfig('content/logging.conf')
630f6b8 Made logging work again
totycro authored
123 gettext.install("unknownhorizons", "po", unicode=1)
ce987e3 Split up run_uh.py into run_uh and envionment
totycro authored
124
dcd772c Several random minor changes
totycro authored
125 create_user_dirs()
b423553 make the /usr/bin script working again
christoph authored
126
b38cc82 Switched to more comfortable option parse (from optparse module)
totycro authored
127 parser = get_option_parser()
128 (options, args) = parser.parse_args()
129
130 # apply options
131 if options.debug:
132 logging.getLogger().setLevel(logging.DEBUG)
1270ae5 Minor changes
totycro authored
133 for module in options.debug_module:
134 if not module in logging.Logger.manager.loggerDict:
135 print 'No such logger:', module
136 sys.exit(1)
137 logging.getLogger(module).setLevel(logging.DEBUG)
f2176f2 Added new option '--debug-log-only' (logging only to logfile).
totycro authored
138 if options.debug or len(options.debug_module) > 0 or options.debug_log_only:
1270ae5 Minor changes
totycro authored
139 # also log to file
889d57e Added pause notification (thx @ Kilian)
totycro authored
140 # init a logfile handler with a dynamic filename
1270ae5 Minor changes
totycro authored
141 from horizons.constants import PATHS
f2176f2 Added new option '--debug-log-only' (logging only to logfile).
totycro authored
142 logfilename = PATHS.LOG_DIR + "/unknown-horizons-%s.log" % \
143 time.strftime("%y-%m-%d_%H-%M-%S")
144 print 'Logging to %s' % logfilename
b38cc82 Switched to more comfortable option parse (from optparse module)
totycro authored
145 file_handler = logging.FileHandler(logfilename, 'w')
146 logging.getLogger().addHandler(file_handler)
21c8374 Made fatal exceptions being printed to logfile
totycro authored
147 sys.excepthook = excepthook_creator(logfilename)
f2176f2 Added new option '--debug-log-only' (logging only to logfile).
totycro authored
148 if not options.debug_log_only:
149 # add a handler to stderr
150 logging.getLogger().addHandler( logging.StreamHandler(sys.stderr) )
b38cc82 Switched to more comfortable option parse (from optparse module)
totycro authored
151
630f6b8 Made logging work again
totycro authored
152 # NOTE: this might cause a program restart
bf84237 Put the moving code from Unit to MovingObject and cleaned it up.
totycro authored
153 init_environment()
a267636 Introduced possibility to start a game bypassing the menu via command…
totycro authored
154
f273e2a Introduced getopt argument parsing
totycro authored
155 #start unknownhorizons
4040236 Implemented reproduction and death for wild animals
totycro authored
156 import horizons.main
b38cc82 Switched to more comfortable option parse (from optparse module)
totycro authored
157 if not options.profile:
869051f Small optimisation
totycro authored
158 # start normal
b38cc82 Switched to more comfortable option parse (from optparse module)
totycro authored
159 horizons.main.start(options)
7b95703 Further optimisation/beautifying
totycro authored
160 else:
869051f Small optimisation
totycro authored
161 # start with profiling
7b95703 Further optimisation/beautifying
totycro authored
162 import profile
163 import tempfile
164 outfilename = tempfile.mkstemp(text = True)[1]
165 log().warning('Starting profile mode. Writing output to: %s', outfilename)
b38cc82 Switched to more comfortable option parse (from optparse module)
totycro authored
166 profile.runctx('horizons.main.start(options)', globals(), locals(), \
7b95703 Further optimisation/beautifying
totycro authored
167 outfilename)
168 log().warning('Program ended. Profiling output: %s', outfilename)
169
f2176f2 Added new option '--debug-log-only' (logging only to logfile).
totycro authored
170 print _('Thank you for using Unknown Horizons!')
bf84237 Put the moving code from Unit to MovingObject and cleaned it up.
totycro authored
171
172
173 """
174 Functions controlling the program environment.
175 NOTE: these are supposed to be in an extra file, but are placed here for simplifying
176 distribution
177 """
178 def init_environment():
dcd772c Several random minor changes
totycro authored
179 """Sets up everything. Use in any program that requires access to fife and uh modules.
180 It will parse sys.args, so this var has to contain only valid uh options."""
181 create_user_dirs()
bf84237 Put the moving code from Unit to MovingObject and cleaned it up.
totycro authored
182
183 gettext.install("unknownhorizons", "po", unicode=1)
184
185 (options, args) = get_option_parser().parse_args()
186
187 #find fife and setup search paths, if it can't be imported yet
188 try:
189 import fife
190 except ImportError, e:
191 if options.fife_in_library_path:
192 # fife should already be in LD_LIBRARY_PATH
193 print 'Failed to load fife:', e
194 exit(1)
195 log().debug('Searching for FIFE')
2fe1dd2 Removed a debug statement and cleaned up code
totycro authored
196 find_FIFE(options.fife_path) # this restarts or terminates the program
197 assert False
bf84237 Put the moving code from Unit to MovingObject and cleaned it up.
totycro authored
198
199 #for some external libraries distributed with unknownhorizons
200 sys.path.append('horizons/ext')
201
2fe1dd2 Removed a debug statement and cleaned up code
totycro authored
202 args_to_discard_now = ['--fife-in-library-path', '--fife-path']
203 for arg in args_to_discard_now:
204 if arg in sys.argv:
205 sys.argv.remove(arg)
206
bf84237 Put the moving code from Unit to MovingObject and cleaned it up.
totycro authored
207 def get_fife_path(fife_custom_path=None):
7d5c621 Set USER_DIR + /log as logging dir
totycro authored
208 """Returns absolute path to fife engine. Calls sys.exit() if it can't be found."""
bf84237 Put the moving code from Unit to MovingObject and cleaned it up.
totycro authored
209 # assemble a list of paths where fife could be located at
210 _paths = []
211 # check if there is a config file (has to be called config.py)
212 try:
213 import config
214 _paths.append(config.fife_path)
215 if not check_path_for_fife(config.fife_path):
216 print 'Invalid fife_path in config.py: %s' % config.fife_path
217 except (ImportError, AttributeError):
218 # no config, check for commandline arg
219 if fife_custom_path is not None:
220 _paths.append(fife_custom_path)
221 if not check_path_for_fife(fife_custom_path):
222 print 'Specified invalid fife path: %s' % fife_custom_path
223
224 else:
225 # try frequently used paths
226 _paths += [ a + '/' + b + '/' + c for \
227 a in ('.', '..', '../..') for \
228 b in ('.', 'fife', 'FIFE', 'Fife') for \
229 c in ('.', 'trunk') ]
230
231 fife_path = None
232 for p in _paths:
233 if p not in sys.path: # skip dirs where import would have found fife
ac3e089 Increased logging for finding FIFE code
totycro authored
234 p = os.path.abspath(p)
235 log().debug("Searching for FIFE in %s", p)
bf84237 Put the moving code from Unit to MovingObject and cleaned it up.
totycro authored
236 if check_path_for_fife(p):
ac3e089 Increased logging for finding FIFE code
totycro authored
237 fife_path = p
bf84237 Put the moving code from Unit to MovingObject and cleaned it up.
totycro authored
238
bbf8feb Fixed distribution
totycro authored
239 log().debug("Found FIFE in %s", fife_path)
bf84237 Put the moving code from Unit to MovingObject and cleaned it up.
totycro authored
240
241 #add python paths (<fife>/engine/extensions <fife>/engine/swigwrappers/python)
bbf8feb Fixed distribution
totycro authored
242 for pe in [ fife_path + os.path.sep + a for \
bf84237 Put the moving code from Unit to MovingObject and cleaned it up.
totycro authored
243 a in ('engine/extensions', 'engine/swigwrappers/python') ]:
244 if os.path.exists(pe):
245 sys.path.append(pe)
246 os.environ['PYTHONPATH'] = os.path.pathsep.join(\
247 os.environ.get('PYTHONPATH', '').split(os.path.pathsep) + \
bbf8feb Fixed distribution
totycro authored
248 [ fife_path + os.path.sep + a for a in \
bf84237 Put the moving code from Unit to MovingObject and cleaned it up.
totycro authored
249 ('engine/extensions', 'engine/swigwrappers/python') ])
250
251 #add windows paths (<fife>/.)
252 os.environ['PATH'] = os.path.pathsep.join( \
dcd772c Several random minor changes
totycro authored
253 os.environ.get('PATH', '').split(os.path.pathsep) + [ fife_path ] )
bbf8feb Fixed distribution
totycro authored
254 os.path.defpath += os.path.pathsep + fife_path
bf84237 Put the moving code from Unit to MovingObject and cleaned it up.
totycro authored
255 break
256 else:
257 print _('FIFE was not found.')
7d5c621 Set USER_DIR + /log as logging dir
totycro authored
258 sys.exit(1)
dcd772c Several random minor changes
totycro authored
259 return fife_path
bf84237 Put the moving code from Unit to MovingObject and cleaned it up.
totycro authored
260
261 def check_path_for_fife(path):
bbf8feb Fixed distribution
totycro authored
262 absolute_path = os.path.abspath(path)
263 for pe in [ '%s/%s' % (absolute_path, a) for a in ('.', 'engine', 'engine/extensions', \
bf84237 Put the moving code from Unit to MovingObject and cleaned it up.
totycro authored
264 'engine/swigwrappers/python') ]:
265 if not os.path.exists(pe):
266 return False
267 return True
268
269 def find_FIFE(fife_custom_path=None):
270 """Inserts path to fife engine to $LD_LIBRARY_PATH (environment variable).
271 If it's already there, the function will return, else
272 it will restart uh with correct $LD_LIBRARY_PATH. """
273 fife_path = get_fife_path(fife_custom_path) # terminates program if fife can't be found
274
275 os.environ['LD_LIBRARY_PATH'] = os.path.pathsep.join( \
276 [ os.path.abspath(fife_path + '/' + a) for \
277 a in ('ext/minizip', 'ext/install/lib') ] + \
278 (os.environ['LD_LIBRARY_PATH'].split(os.path.pathsep) if \
279 os.environ.has_key('LD_LIBRARY_PATH') else []))
280
281 log().debug("Restarting with proper LD_LIBRARY_PATH...")
282 log().debug("LD_LIBRARY_PATH: %s", os.environ['LD_LIBRARY_PATH'])
283 log().debug("PATH: %s", os.environ['PATH'])
284 log().debug("PYTHONPATH %s", os.environ['PYTHONPATH'])
285
286 # assemble args (python run_uh.py ..)
287 args = [sys.executable] + sys.argv + [ "--fife-in-library-path"]
288 log().debug("Restarting with args %s", args)
289 os.execvp(args[0], args)
290
291
bbf8feb Fixed distribution
totycro authored
292 if __name__ == '__main__':
293 main()
Something went wrong with that request. Please try again.