Beispiel #1
0
	def init(self):
		"""Second initialization stage of engine"""
		self.engine.init()

		# Init stuff.
		self.eventmanager = self.engine.getEventManager()
		self.sound = Sound(self)
		self.imagemanager = self.engine.getImageManager()
		self.animationmanager = self.engine.getAnimationManager()
		self.targetrenderer = self.engine.getTargetRenderer()
		self.animationloader = None

		# Set game cursor.
		self.cursor = self.engine.getCursor()
		cursor_images = {
			'default':   'content/gui/images/cursors/cursor.png',
			'tearing':   'content/gui/images/cursors/cursor_tear.png',
			'attacking': 'content/gui/images/cursors/cursor_attack.png',
			'pipette':   'content/gui/images/cursors/cursor_pipette.png',
			'rename':    'content/gui/images/cursors/cursor_rename.png',
		}
		self.cursor_images = dict((k, self.imagemanager.load(v)) for k, v in  cursor_images.iteritems())
		self.cursor.set(self.cursor_images['default'])

		# Init pychan.
		# Enabling pychan's debug mode may have performance impacts.
		# Because of this, the default PychanDebug value is False.
		debug_pychan = self.get_fife_setting('PychanDebug')
		self.pychan.init(self.engine, debug_pychan)

		init_pychan()
		self._setting.apply()

		self._got_inited = True
	def init(self):
		"""Second initialization stage of engine"""
		self.engine.init()

		# Init stuff.
		self.eventmanager = self.engine.getEventManager()
		self.sound = Sound(self)
		self.imagemanager = self.engine.getImageManager()
		self.animationmanager = self.engine.getAnimationManager()
		self.targetrenderer = self.engine.getTargetRenderer()
		self.animationloader = None

		# Set game cursor.
		self.cursor = self.engine.getCursor()
		cursor_images = {
			'default':   'content/gui/images/cursors/cursor.png',
			'tearing':   'content/gui/images/cursors/cursor_tear.png',
			'attacking': 'content/gui/images/cursors/cursor_attack.png',
			'pipette':   'content/gui/images/cursors/cursor_pipette.png',
			'rename':    'content/gui/images/cursors/cursor_rename.png',
		}
		self.cursor_images = {k: self.imagemanager.load(v) for k, v in cursor_images.items()}
		self.cursor.set(self.cursor_images['default'])

		# Init pychan.
		# Enabling pychan's debug mode may have performance impacts.
		# Because of this, the default PychanDebug value is False.
		debug_pychan = self.get_fife_setting('PychanDebug')
		self.pychan.init(self.engine, debug_pychan)

		init_pychan()
		self._setting.apply()

		self._got_inited = True
	def init(self):
		"""Second initialization stage of engine"""
		self.engine.init()

		#init stuff
		self.eventmanager = self.engine.getEventManager()
		self.sound = Sound(self)
		self.imagemanager = self.engine.getImageManager()
		self.targetrenderer = self.engine.getTargetRenderer()
		self.animationloader = None

		#Set game cursor
		self.cursor = self.engine.getCursor()
		cursor_images = {
			'default':   'content/gui/images/cursors/cursor.png',
			'tearing':   'content/gui/images/cursors/cursor_tear.png',
			'attacking': 'content/gui/images/cursors/cursor_attack.png',
			'pipette':   'content/gui/images/cursors/cursor_pipette.png',
			'rename':    'content/gui/images/cursors/cursor_rename.png',
		}
		self.cursor_images = dict( (k, self.imagemanager.load(v)) for k, v in  cursor_images.iteritems() )
		self.cursor.set(self.cursor_images['default'])

		#init pychan
		debug_pychan = self.get_fife_setting('PychanDebug') # default is False
		self.pychan.init(self.engine, debug_pychan) # pychan debug mode may have performance impacts

		init_pychan()
		self._setting.apply()

		self._got_inited = True
Beispiel #4
0
    def init(self):
        """Second initialisation stage of engine
		"""
        self.engine.init()

        #init stuff
        self.eventmanager = self.engine.getEventManager()
        #self.eventmanager.setNonConsumableKeys([fife.Key.ESCAPE, fife.Key.F10])
        self.sound = Sound(self)
        self.imagemanager = self.engine.getImageManager()
        self.targetrenderer = self.engine.getTargetRenderer()
        self.animationloader = None

        #Set game cursor
        self.cursor = self.engine.getCursor()
        cursor_images = {
            'default': 'content/gui/images/cursors/cursor.png',
            'tearing': 'content/gui/images/cursors/cursor_tear.png',
            'attacking': 'content/gui/images/cursors/cursor_attack.png',
            'pipette': 'content/gui/images/cursors/cursor_pipette.png',
            'rename': 'content/gui/images/cursors/cursor_rename.png',
        }
        self.cursor_images = dict((k, self.imagemanager.load(v))
                                  for k, v in cursor_images.iteritems())
        self.cursor.set(self.cursor_images['default'])

        #init pychan
        debug_pychan = self.get_fife_setting('PychanDebug')  # default is False
        self.pychan.init(
            self.engine,
            debug_pychan)  # pychan debug mode may have performance impacts
        self.pychan.setupModalExecution(self.loop, self.breakLoop)
        self.console = self.pychan.manager.hook.guimanager.getConsole()

        init_pychan()
        self.pychanmanager = pychan.internal.get_manager()

        self._setting_handler.apply_settings()

        self._gotInited = True
Beispiel #5
0
	def init(self):
		"""Second initialisation stage of engine
		"""
		logToPrompt, logToFile, debugPychan = True, True, False
		if self._gotInited:
			return
		#start modules
		self.log = fifelog.LogManager(self.engine, 1 if logToPrompt else 0, 1 if logToFile else 0)
		#self.log.setVisibleModules('all')

		self.engine.init()

		#init stuff
		self.eventmanager = self.engine.getEventManager()
		#self.eventmanager.setNonConsumableKeys([fife.Key.ESCAPE, fife.Key.F10])
		self.sound = Sound(self)
		self.imagemanager = self.engine.getImageManager()
		self.targetrenderer = self.engine.getTargetRenderer()
		self.use_atlases = GFX.USE_ATLASES
		if self.use_atlases:
			self.animationloader = SQLiteAtlasLoader()
		else:
			self.animationloader = SQLiteAnimationLoader()

		#Set game cursor
		self.cursor = self.engine.getCursor()
		cursor_images = {
			'default':   'content/gui/images/cursors/cursor.png',
			'tearing':   'content/gui/images/cursors/cursor_tear.png',
			'attacking': 'content/gui/images/cursors/cursor_attack.png',
			'pipette':   'content/gui/images/cursors/cursor_pipette.png',
		  'rename':    'content/gui/images/cursors/cursor_rename.png',
		}
		self.cursor_images = dict( (k, self.imagemanager.load(v)) for k, v in  cursor_images.iteritems() )
		self.cursor.set( self.cursor_images['default'] )

		#init pychan
		self.pychan.init(self.engine, debugPychan)
		self.pychan.setupModalExecution(self.loop, self.breakLoop)
		self.console = self.pychan.manager.hook.guimanager.getConsole()

		init_pychan()

		self._setting_handler.apply_settings()

		self._gotInited = True
Beispiel #6
0
	def init(self):
		"""Second initialisation stage of engine
		"""
		self.engine.init()

		#init stuff
		self.eventmanager = self.engine.getEventManager()
		#self.eventmanager.setNonConsumableKeys([fife.Key.ESCAPE, fife.Key.F10])
		self.sound = Sound(self)
		self.imagemanager = self.engine.getImageManager()
		self.targetrenderer = self.engine.getTargetRenderer()
		self.use_atlases = GFX.USE_ATLASES
		if self.use_atlases:
			self.animationloader = SQLiteAtlasLoader()
		else:
			self.animationloader = SQLiteAnimationLoader()

		#Set game cursor
		self.cursor = self.engine.getCursor()
		cursor_images = {
			'default':   'content/gui/images/cursors/cursor.png',
			'tearing':   'content/gui/images/cursors/cursor_tear.png',
			'attacking': 'content/gui/images/cursors/cursor_attack.png',
			'pipette':   'content/gui/images/cursors/cursor_pipette.png',
			'rename':    'content/gui/images/cursors/cursor_rename.png',
		}
		self.cursor_images = dict( (k, self.imagemanager.load(v)) for k, v in  cursor_images.iteritems() )
		self.cursor.set( self.cursor_images['default'] )

		#init pychan
		debug_pychan = self.get_fife_setting('PychanDebug') # default is False
		self.pychan.init(self.engine, debug_pychan) # pychan debug mode may have performance impacts
		self.pychan.setupModalExecution(self.loop, self.breakLoop)
		self.console = self.pychan.manager.hook.guimanager.getConsole()

		init_pychan()
		self.pychanmanager = pychan.internal.get_manager()

		self._setting_handler.apply_settings()

		self._gotInited = True
class Fife(ApplicationBase):
	"""
	Basic initiation of engine. Followed later by init().
	"""
	def __init__(self):
		self.pump = []

		self._setting_handler = SettingsHandler(self)
		self._setup_settings()

		self.engine = fife.Engine()
		self.engine_settings = self.engine.getSettings()

		super(Fife, self).initLogging()

		self.loadSettings()

		self.pychan = pychan

		self.quit_requested = False
		self.break_requested = False
		self.return_values = None
		self._got_inited = False


	# existing settings not part of this gui or the fife defaults
	# (required for preserving values when upgrading settings file)
	UNREFERENCED_SETTINGS = {UH_MODULE: ["Nickname", "AIPlayers", "ClientID"] }

	def _setup_settings(self, check_file_version=True):
		_user_config_file = os.path.join( os.getcwd(), PATHS.USER_CONFIG_FILE )
		if check_file_version and os.path.exists(_user_config_file):
			# check if user settings file is the current one

			# NOTE: SimpleXMLSerializer can't handle relative paths, it fails silently
			# (although the doc states otherwise) - thus translate paths to absolute ones
			user_config_parser = SimpleXMLSerializer( _user_config_file )
			user_settings_version = user_config_parser.get("meta", "SettingsVersion", -1)
			_template_config_file = os.path.join( os.getcwd(), PATHS.CONFIG_TEMPLATE_FILE )
			template_config_parser = SimpleXMLSerializer( _template_config_file )
			template_settings_version = template_config_parser.get("meta", "SettingsVersion")

			if template_settings_version > user_settings_version: # we have to update the file
				print 'Discovered old settings file, auto-upgrading: %s -> %s' % \
				      (user_settings_version, template_settings_version)
				# create settings so we have a list of all settings
				self._setup_settings(check_file_version=False)

				# save settings here
				entries = []

				# need safe default value
				default_value = object()

				def update_value(modulename, entryname):
					# retrieve values from loaded settings file
					try:
						value = self._setting.get(modulename, entryname, default_value)
					except UnicodeEncodeError: # this can happen when unicode data is saved as str
						value = "default"
					if value is not default_value:
						entries.append( (modulename, entryname, value ) )

				# collect values from known settings and unreferenced settings
				for modulename, module in self._setting.entries.iteritems():
					for entryname in module.iterkeys():
						update_value(modulename, entryname)
				for modulename, entry_list in self.UNREFERENCED_SETTINGS.iteritems():
					for entryname in entry_list:
						update_value(modulename, entryname)

				# patch old values
				if user_settings_version <= 10:
					old_entries = entries
					entries = []
					for i in old_entries:
						if i[0] == UH_MODULE and i[1] == "Language":
							entries.append( (i[0], i[1], LANGUAGENAMES.get_by_value(i[2])) )
						else:
							entries.append(i)

				# write actual new file
				shutil.copy( PATHS.CONFIG_TEMPLATE_FILE, PATHS.USER_CONFIG_FILE )
				user_config_parser = SimpleXMLSerializer( _user_config_file )
				for modulename, entryname, value in entries:
					user_config_parser.set(modulename, entryname, value)
				user_config_parser.save()

		self._setting = SettingsDialog(app_name=UH_MODULE,
				                         settings_file=PATHS.USER_CONFIG_FILE,
				                         settings_gui_xml="settings.xml",
				                         changes_gui_xml="requirerestart.xml",
				                         default_settings_file=PATHS.CONFIG_TEMPLATE_FILE)

		self._setting_handler.add_settings()

	def init(self):
		"""Second initialisation stage of engine
		"""
		self.engine.init()

		#init stuff
		self.eventmanager = self.engine.getEventManager()
		#self.eventmanager.setNonConsumableKeys([fife.Key.ESCAPE, fife.Key.F10])
		self.sound = Sound(self)
		self.imagemanager = self.engine.getImageManager()
		self.targetrenderer = self.engine.getTargetRenderer()
		self.use_atlases = GFX.USE_ATLASES
		if self.use_atlases:
			self.animationloader = SQLiteAtlasLoader()
		else:
			self.animationloader = SQLiteAnimationLoader()

		#Set game cursor
		self.cursor = self.engine.getCursor()
		cursor_images = {
			'default':   'content/gui/images/cursors/cursor.png',
			'tearing':   'content/gui/images/cursors/cursor_tear.png',
			'attacking': 'content/gui/images/cursors/cursor_attack.png',
			'pipette':   'content/gui/images/cursors/cursor_pipette.png',
			'rename':    'content/gui/images/cursors/cursor_rename.png',
		}
		self.cursor_images = dict( (k, self.imagemanager.load(v)) for k, v in  cursor_images.iteritems() )
		self.cursor.set( self.cursor_images['default'] )

		#init pychan
		debug_pychan = self.get_fife_setting('PychanDebug') # default is False
		self.pychan.init(self.engine, debug_pychan) # pychan debug mode may have performance impacts
		self.pychan.setupModalExecution(self.loop, self.breakLoop)
		self.console = self.pychan.manager.hook.guimanager.getConsole()

		init_pychan()

		self._setting_handler.apply_settings()

		self._gotInited = True

	def show_settings(self):
		"""Show fife settings gui"""
		if not hasattr(self, "_settings_extra_inited "):
			self._setting_handler.setup_setting_extras()
			self._settings_extra_inited = True
		self._setting.onOptionsPress()

	def set_cursor_image(self, which="default"):
		"""Sets a certain cursor image.
		See definition of cursor_images for reference."""
		self.cursor.set( self.cursor_images[which] )

	def get_fife_setting(self, settingname):
		return self._setting.get(FIFE_MODULE, settingname)

	def set_fife_setting(self, settingname, value):
		"""Probably saves setting in memory. Call save_settings() later"""
		return self._setting.set(FIFE_MODULE, settingname, value)

	def get_uh_setting(self, settingname):
		return self._setting.get(UH_MODULE, settingname)

	def set_uh_setting(self, settingname, value):
		"""Probably saves setting in memory. Call save_settings() later"""
		self._setting.set(UH_MODULE, settingname, value)

	def save_settings(self):
		self._setting.saveSettings()

	def play_sound(self, emitter, soundfile):
		"""Plays a soundfile on the given emitter.
		@param emitter: string with the emitters name in horizons.main.fife.sound.emitter that is to play the  sound
		@param soundfile: string containing the path to the soundfile"""
		self.sound.play_sound(emitter, soundfile)

	def get_locale(self):
		for locale_code, langname in LANGUAGENAMES.items():
			if langname == self.get_uh_setting('Language'):
				if not langname == 'System default':
					return locale_code
		try:
			default_locale, default_encoding = locale.getdefaultlocale()
			return default_locale.split('_')[0]
		except (ValueError, AttributeError):
			# OS X sometimes returns 'UTF-8' as locale, which is a ValueError.
			# If no locale is set at all, the split will fail, which is an AttributeError.
			# Use 'EN' as fallback in both cases since we cannot reasonably detect the locale.
			return "en"

	def run(self):
		"""
		"""
		assert self._gotInited

		self._setting.setAvailableScreenResolutions(get_screen_resolutions())

		self.engine.initializePumping()
		self.loop()
		self.engine.finalizePumping()
		self.__kill_engine()

	def loop(self):
		"""
		"""
		while not self.quit_requested:
			try:
				self.engine.pump()
			except fife.Exception as e:
				print e.getMessage()
				break
			for f in self.pump:
				f()
			if self.break_requested:
				self.break_requested = False
				return self.return_values

	def __kill_engine(self):
		"""Called when the engine is quit"""
		self.cursor.set(fife.CURSOR_NATIVE) #hack to get system cursor back
		self.engine.destroy()

	def breakLoop(self, returnValue=None):
		"""
		@param returnValue:
		"""
		self.return_values = returnValue
		self.break_requested = True

	def quit(self):
		""" Quits the engine.
		"""
		self.quit_requested = True
class Fife:
	"""
	Basic initiation of engine. Followed later by init().
	"""
	log = logging.getLogger('engine.engine')

	def __init__(self):
		self.pump = []

		self._setting = Settings(PATHS.USER_CONFIG_FILE, PATHS.SETTINGS_TEMPLATE_FILE)
		self.engine = fife.Engine()
		self.engine_settings = self.engine.getSettings()

		self.init_logging()
		self.load_settings()

		self.pychan = pychan

		self.quit_requested = False
		self.break_requested = False
		self.return_values = None
		self._got_inited = False

	def load_settings(self):
		"""
		Load the settings from a python file and load them into the engine.
		Called in the ApplicationBase constructor.
		"""
		# get finalSetting (from the xml file, or if absent the default value)
		self._finalSetting = self._setting.get_module_settings("FIFE")

		self.engine_settings = self.engine.getSettings()

		self.engine_settings.setDefaultFontPath(self._finalSetting['Font'])
		self.engine_settings.setBitsPerPixel(self._finalSetting['BitsPerPixel'])
		self.engine_settings.setInitialVolume(self._finalSetting['InitialVolume'])
		self.engine_settings.setSDLRemoveFakeAlpha(self._finalSetting['SDLRemoveFakeAlpha'])
		self.engine_settings.setGLCompressImages(self._finalSetting['GLCompressImages'])
		self.engine_settings.setGLUseFramebuffer(self._finalSetting['GLUseFramebuffer'])
		self.engine_settings.setGLUseNPOT(self._finalSetting['GLUseNPOT'])

		# introduced in fife 0.4.0
		self.engine_settings.setGLUseMonochrome(self._finalSetting['GLUseMonochrome'])
		self.engine_settings.setGLUseMipmapping(self._finalSetting['GLUseMipmapping'])
		if self._finalSetting['GLTextureFiltering'] == 'None':
			self.engine_settings.setGLTextureFiltering(fife.TEXTURE_FILTER_NONE)
		elif self._finalSetting['GLTextureFiltering'] == 'Bilinear':
			self.engine_settings.setGLTextureFiltering(fife.TEXTURE_FILTER_BILINEAR)
		elif self._finalSetting['GLTextureFiltering'] == 'Trilinear':
			self.engine_settings.setGLTextureFiltering(fife.TEXTURE_FILTER_TRILINEAR)
		elif self._finalSetting['GLTextureFiltering'] == 'Anisotropic':
			self.engine_settings.setGLTextureFiltering(fife.TEXTURE_FILTER_ANISOTROPIC)
		self.engine_settings.setGLUseDepthBuffer(self._finalSetting['GLUseDepthBuffer'])
		self.engine_settings.setGLAlphaTestValue(self._finalSetting['GLAlphaTestValue'])

		(width, height) = self._finalSetting['ScreenResolution'].split('x')
		self.engine_settings.setScreenWidth(int(width))
		self.engine_settings.setScreenHeight(int(height))
		self.engine_settings.setRenderBackend(self._finalSetting['RenderBackend'])
		self.engine_settings.setFullScreen(self._finalSetting['FullScreen'])
		self.engine_settings.setLightingModel(self._finalSetting['Lighting'])

		try:
			self.engine_settings.setColorKeyEnabled(self._finalSetting['ColorKeyEnabled'])
		except:
			pass

		try:
			self.engine_settings.setColorKey(
				self._finalSetting['ColorKey'][0],
				self._finalSetting['ColorKey'][1],
				self._finalSetting['ColorKey'][2])
		except:
			pass

		try:
			self.engine_settings.setWindowTitle(self._finalSetting['WindowTitle'])
			self.engine_settings.setWindowIcon(self._finalSetting['WindowIcon'])
		except:
			pass

		try:
			self.engine_settings.setFrameLimitEnabled(self._finalSetting['FrameLimitEnabled'])
			self.engine_settings.setFrameLimit(self._finalSetting['FrameLimit'])
		except:
			pass

		try:
			self.engine_settings.setMouseSensitivity(self._finalSetting['MouseSensitivity'])
		except:
			pass

		try:
			self.engine_settings.setMouseAccelerationEnabled(self._finalSetting['MouseAcceleration'])
		except:
			pass

	def init_logging(self):
		"""Initialize the LogManager."""

		# If desired, log to the console and/or the log file.
		log_to_prompt = self._setting.get(SETTINGS.FIFE_MODULE, "LogToPrompt", False)
		log_to_file = self._setting.get(SETTINGS.FIFE_MODULE, "LogToFile", False)
		self._log = fifelog.LogManager(self.engine, log_to_prompt, log_to_file)

		log_level = self._setting.get(SETTINGS.FIFE_MODULE, "LogLevelFilter",
		                              fife.LogManager.LEVEL_DEBUG)
		self._log.setLevelFilter(log_level)

		logmodules = self._setting.get(SETTINGS.FIFE_MODULE, "LogModules", ["controller"])
		if logmodules:
			self._log.setVisibleModules(*logmodules)

	def init(self):
		"""Second initialization stage of engine"""
		self.engine.init()

		# Init stuff.
		self.eventmanager = self.engine.getEventManager()
		self.sound = Sound(self)
		self.imagemanager = self.engine.getImageManager()
		self.animationmanager = self.engine.getAnimationManager()
		self.targetrenderer = self.engine.getTargetRenderer()
		self.animationloader = None

		# Set game cursor.
		self.cursor = self.engine.getCursor()
		cursor_images = {
			'default':   'content/gui/images/cursors/cursor.png',
			'tearing':   'content/gui/images/cursors/cursor_tear.png',
			'attacking': 'content/gui/images/cursors/cursor_attack.png',
			'pipette':   'content/gui/images/cursors/cursor_pipette.png',
			'rename':    'content/gui/images/cursors/cursor_rename.png',
		}
		self.cursor_images = {k: self.imagemanager.load(v) for k, v in cursor_images.items()}
		self.cursor.set(self.cursor_images['default'])

		# Init pychan.
		# Enabling pychan's debug mode may have performance impacts.
		# Because of this, the default PychanDebug value is False.
		debug_pychan = self.get_fife_setting('PychanDebug')
		self.pychan.init(self.engine, debug_pychan)

		init_pychan()
		self._setting.apply()

		self._got_inited = True

	def init_animation_loader(self, use_atlases):
		# this method should not be called from init to catch any bugs caused by the loader changing after it.
		self.use_atlases = use_atlases
		if self.use_atlases:
			self.animationloader = SQLiteAtlasLoader()
		else:
			self.animationloader = SQLiteAnimationLoader()

	def set_cursor_image(self, which="default"):
		"""Sets a certain cursor image.
		See definition of cursor_images for reference."""
		self.cursor.set(self.cursor_images[which])

	def get_fife_setting(self, settingname):
		return self._setting.get(SETTINGS.FIFE_MODULE, settingname)

	def set_fife_setting(self, settingname, value):
		"""Probably saves setting in memory. Call save_settings() later"""
		return self._setting.set(SETTINGS.FIFE_MODULE, settingname, value)

	def get_uh_setting(self, settingname):
		return self._setting.get(SETTINGS.UH_MODULE, settingname)

	def set_uh_setting(self, settingname, value):
		"""Probably saves setting in memory. Call save_settings() later"""
		self._setting.set(SETTINGS.UH_MODULE, settingname, value)

	def get_hotkey_settings(self):
		return self._setting.get_module_settings(SETTINGS.KEY_MODULE)

	def get_keys_for_action(self, action, default=False):
		"""Returns list of current hotkeys for *action* or its default hotkeys."""
		if default:
			keys = self._setting.get_module_template_settings(SETTINGS.KEY_MODULE).get(action)
		else:
			keys = self._setting.get(SETTINGS.KEY_MODULE, action)
		return keys

	def set_key_for_action(self, action, newkey):
		"""Replaces all existing hotkeys for *action* with *newkey*."""
		self._setting.set(SETTINGS.KEY_MODULE, action, newkey)

	def add_key_for_action(self, action, addkey):
		"""Adds hotkey *addkey* to list of hotkeys for action *action*."""
		old_keys = self._setting.get(SETTINGS.KEY_MODULE, action, [])
		new_keys = set(old_keys + [addkey])
		self.set_key_for_action(action, list(new_keys))

	def remove_key_for_action(self, action, remkey):
		"""Removes hotkey *remkey* from list of hotkeys for action *action*."""
		old_keys = self._setting.get(SETTINGS.KEY_MODULE, action, [])
		if remkey in old_keys:
				old_keys.remove(remkey)
		if not old_keys:
				print('Cannot have no binding for action')
				return
		self.set_key_for_action(action, old_keys)

	def replace_key_for_action(self, action, oldkey, newkey):
		"""Replaces key *oldkey* with key *newkey* for action *action*"""
		old_keys = self._setting.get(SETTINGS.KEY_MODULE, action, [])
		if oldkey not in old_keys:
			return
		index = old_keys.index(oldkey)
		old_keys[index] = newkey
		self.set_key_for_action(action, old_keys)

	def save_settings(self):
		self._setting.save()

	def play_sound(self, emitter, soundfile):
		"""Plays a soundfile on the given emitter.
		@param emitter: string with the emitters name in horizons.globals.fife.sound.emitter that is to play the  sound
		@param soundfile: string containing the path to the soundfile"""
		self.sound.play_sound(emitter, soundfile)

	def get_locale(self):
		langname = self.get_uh_setting('Language')
		locale_code = LANGUAGENAMES.get_by_value(langname)
		if not langname == 'System default':
				return locale_code
		try:
			default_locale, default_encoding = locale.getdefaultlocale()
			return default_locale.split('_')[0]
		except (ValueError, AttributeError):
			# OS X sometimes returns 'UTF-8' as locale, which is a ValueError.
			# If no locale is set at all, the split will fail, which is an AttributeError.
			# Use 'EN' as fallback in both cases since we cannot reasonably detect the locale.
			return "en"

	def run(self):
		assert self._got_inited

		self.engine.initializePumping()
		self.loop()
		self.engine.finalizePumping()
		self.__kill_engine()

	def loop(self):
		while not self.quit_requested:
			try:
				self.engine.pump()
			except RuntimeError:
				import sys
				print("Unknown Horizons exited uncleanly via SIGINT")
				self._log.log_warn("Unknown Horizons exited uncleanly via SIGINT")
				sys.exit(1)
			except fife.Exception as e:
				print(e.getMessage())
				break
			for f in self.pump:
				f()
			if self.break_requested:
				self.break_requested = False
				return self.return_values

	def __kill_engine(self):
		"""Called when the engine is quit"""
		# A hack to get the system cursor back:
		self.cursor.set(fife.CURSOR_NATIVE)
		self.engine.destroy()

	def breakLoop(self, returnValue=None):
		self.return_values = returnValue
		self.break_requested = True

	def quit(self):
		"""Quits the engine."""
		self.quit_requested = True

	@classmethod
	def getVersion(cls):
		"""Returns a tuple (Major, Minor, Patch) version of the current running Fife."""
		try:
			return (fife.getMajor(), fife.getMinor(), fife.getPatch())
		except AttributeError:
			return (0, 0, 0)
Beispiel #9
0
class Fife:
    """
	Basic initiation of engine. Followed later by init().
	"""
    log = logging.getLogger('engine.engine')

    def __init__(self):
        self.pump = []

        self._setting = Settings(PATHS.USER_CONFIG_FILE,
                                 PATHS.SETTINGS_TEMPLATE_FILE)
        self.engine = fife.Engine()
        self.engine_settings = self.engine.getSettings()

        self.init_logging()
        self.load_settings()

        self.pychan = pychan

        self.quit_requested = False
        self.break_requested = False
        self.return_values = None
        self._got_inited = False

    def load_settings(self):
        """
		Load the settings from a python file and load them into the engine.
		Called in the ApplicationBase constructor.
		"""
        # get finalSetting (from the xml file, or if absent the default value)
        self._finalSetting = self._setting.get_module_settings("FIFE")

        self.engine_settings = self.engine.getSettings()

        self.engine_settings.setDefaultFontPath(self._finalSetting['Font'])
        self.engine_settings.setBitsPerPixel(
            self._finalSetting['BitsPerPixel'])
        self.engine_settings.setInitialVolume(
            self._finalSetting['InitialVolume'])
        self.engine_settings.setSDLRemoveFakeAlpha(
            self._finalSetting['SDLRemoveFakeAlpha'])
        self.engine_settings.setGLCompressImages(
            self._finalSetting['GLCompressImages'])
        self.engine_settings.setGLUseFramebuffer(
            self._finalSetting['GLUseFramebuffer'])
        self.engine_settings.setGLUseNPOT(self._finalSetting['GLUseNPOT'])

        # introduced in fife 0.4.0
        if self.getVersion() >= (0, 4, 0):
            self.engine_settings.setGLUseMonochrome(
                self._finalSetting['GLUseMonochrome'])
            self.engine_settings.setGLUseMipmapping(
                self._finalSetting['GLUseMipmapping'])
            if self._finalSetting['GLTextureFiltering'] == 'None':
                self.engine_settings.setGLTextureFiltering(
                    fife.TEXTURE_FILTER_NONE)
            elif self._finalSetting['GLTextureFiltering'] == 'Bilinear':
                self.engine_settings.setGLTextureFiltering(
                    fife.TEXTURE_FILTER_BILINEAR)
            elif self._finalSetting['GLTextureFiltering'] == 'Trilinear':
                self.engine_settings.setGLTextureFiltering(
                    fife.TEXTURE_FILTER_TRILINEAR)
            elif self._finalSetting['GLTextureFiltering'] == 'Anisotropic':
                self.engine_settings.setGLTextureFiltering(
                    fife.TEXTURE_FILTER_ANISOTROPIC)
            self.engine_settings.setGLUseDepthBuffer(
                self._finalSetting['GLUseDepthBuffer'])
            self.engine_settings.setGLAlphaTestValue(
                self._finalSetting['GLAlphaTestValue'])

        (width, height) = self._finalSetting['ScreenResolution'].split('x')
        self.engine_settings.setScreenWidth(int(width))
        self.engine_settings.setScreenHeight(int(height))
        self.engine_settings.setRenderBackend(
            self._finalSetting['RenderBackend'])
        self.engine_settings.setFullScreen(self._finalSetting['FullScreen'])
        self.engine_settings.setLightingModel(self._finalSetting['Lighting'])

        try:
            self.engine_settings.setColorKeyEnabled(
                self._finalSetting['ColorKeyEnabled'])
        except:
            pass

        try:
            self.engine_settings.setColorKey(self._finalSetting['ColorKey'][0],
                                             self._finalSetting['ColorKey'][1],
                                             self._finalSetting['ColorKey'][2])
        except:
            pass

        try:
            self.engine_settings.setWindowTitle(
                self._finalSetting['WindowTitle'])
            self.engine_settings.setWindowIcon(
                self._finalSetting['WindowIcon'])
        except:
            pass

        try:
            self.engine_settings.setFrameLimitEnabled(
                self._finalSetting['FrameLimitEnabled'])
            self.engine_settings.setFrameLimit(
                self._finalSetting['FrameLimit'])
        except:
            pass

        try:
            self.engine_settings.setMouseSensitivity(
                self._finalSetting['MouseSensitivity'])
        except:
            pass

        try:
            self.engine_settings.setMouseAccelerationEnabled(
                self._finalSetting['MouseAcceleration'])
        except:
            pass

    def init_logging(self):
        """Initialize the LogManager."""

        # If desired, log to the console and/or the log file.
        log_to_prompt = self._setting.get(SETTINGS.FIFE_MODULE, "LogToPrompt",
                                          False)
        log_to_file = self._setting.get(SETTINGS.FIFE_MODULE, "LogToFile",
                                        False)
        self._log = fifelog.LogManager(self.engine, log_to_prompt, log_to_file)

        log_level = self._setting.get(SETTINGS.FIFE_MODULE, "LogLevelFilter",
                                      fife.LogManager.LEVEL_DEBUG)
        self._log.setLevelFilter(log_level)

        logmodules = self._setting.get(SETTINGS.FIFE_MODULE, "LogModules",
                                       ["controller"])
        if logmodules:
            self._log.setVisibleModules(*logmodules)

    def init(self):
        """Second initialization stage of engine"""
        self.engine.init()

        # Init stuff.
        self.eventmanager = self.engine.getEventManager()
        self.sound = Sound(self)
        self.imagemanager = self.engine.getImageManager()
        self.animationmanager = self.engine.getAnimationManager()
        self.targetrenderer = self.engine.getTargetRenderer()
        self.animationloader = None

        # Set game cursor.
        self.cursor = self.engine.getCursor()
        cursor_images = {
            'default': 'content/gui/images/cursors/cursor.png',
            'tearing': 'content/gui/images/cursors/cursor_tear.png',
            'attacking': 'content/gui/images/cursors/cursor_attack.png',
            'pipette': 'content/gui/images/cursors/cursor_pipette.png',
            'rename': 'content/gui/images/cursors/cursor_rename.png',
        }
        self.cursor_images = {
            k: self.imagemanager.load(v)
            for k, v in cursor_images.items()
        }
        self.cursor.set(self.cursor_images['default'])

        # Init pychan.
        # Enabling pychan's debug mode may have performance impacts.
        # Because of this, the default PychanDebug value is False.
        debug_pychan = self.get_fife_setting('PychanDebug')
        self.pychan.init(self.engine, debug_pychan)

        init_pychan()
        self._setting.apply()

        self._got_inited = True

    def init_animation_loader(self, use_atlases):
        # this method should not be called from init to catch any bugs caused by the loader changing after it.
        self.use_atlases = use_atlases
        if self.use_atlases:
            self.animationloader = SQLiteAtlasLoader()
        else:
            self.animationloader = SQLiteAnimationLoader()

    def set_cursor_image(self, which="default"):
        """Sets a certain cursor image.
		See definition of cursor_images for reference."""
        self.cursor.set(self.cursor_images[which])

    def get_fife_setting(self, settingname):
        return self._setting.get(SETTINGS.FIFE_MODULE, settingname)

    def set_fife_setting(self, settingname, value):
        """Probably saves setting in memory. Call save_settings() later"""
        return self._setting.set(SETTINGS.FIFE_MODULE, settingname, value)

    def get_uh_setting(self, settingname):
        return self._setting.get(SETTINGS.UH_MODULE, settingname)

    def set_uh_setting(self, settingname, value):
        """Probably saves setting in memory. Call save_settings() later"""
        self._setting.set(SETTINGS.UH_MODULE, settingname, value)

    def get_hotkey_settings(self):
        return self._setting.get_module_settings(SETTINGS.KEY_MODULE)

    def get_keys_for_action(self, action, default=False):
        """Returns list of current hotkeys for *action* or its default hotkeys."""
        if default:
            keys = self._setting.get_module_template_settings(
                SETTINGS.KEY_MODULE).get(action)
        else:
            keys = self._setting.get(SETTINGS.KEY_MODULE, action)
        return keys

    def set_key_for_action(self, action, newkey):
        """Replaces all existing hotkeys for *action* with *newkey*."""
        self._setting.set(SETTINGS.KEY_MODULE, action, newkey)

    def add_key_for_action(self, action, addkey):
        """Adds hotkey *addkey* to list of hotkeys for action *action*."""
        old_keys = self._setting.get(SETTINGS.KEY_MODULE, action, [])
        new_keys = set(old_keys + [addkey])
        self.set_key_for_action(action, list(new_keys))

    def remove_key_for_action(self, action, remkey):
        """Removes hotkey *remkey* from list of hotkeys for action *action*."""
        old_keys = self._setting.get(SETTINGS.KEY_MODULE, action, [])
        if remkey in old_keys:
            old_keys.remove(remkey)
        if not old_keys:
            print('Cannot have no binding for action')
            return
        self.set_key_for_action(action, old_keys)

    def replace_key_for_action(self, action, oldkey, newkey):
        """Replaces key *oldkey* with key *newkey* for action *action*"""
        old_keys = self._setting.get(SETTINGS.KEY_MODULE, action, [])
        if oldkey not in old_keys:
            return
        index = old_keys.index(oldkey)
        old_keys[index] = newkey
        self.set_key_for_action(action, old_keys)

    def save_settings(self):
        self._setting.save()

    def play_sound(self, emitter, soundfile):
        """Plays a soundfile on the given emitter.
		@param emitter: string with the emitters name in horizons.globals.fife.sound.emitter that is to play the  sound
		@param soundfile: string containing the path to the soundfile"""
        self.sound.play_sound(emitter, soundfile)

    def get_locale(self):
        langname = self.get_uh_setting('Language')
        locale_code = LANGUAGENAMES.get_by_value(langname)
        if not langname == 'System default':
            return locale_code
        try:
            default_locale, default_encoding = locale.getdefaultlocale()
            return default_locale.split('_')[0]
        except (ValueError, AttributeError):
            # OS X sometimes returns 'UTF-8' as locale, which is a ValueError.
            # If no locale is set at all, the split will fail, which is an AttributeError.
            # Use 'EN' as fallback in both cases since we cannot reasonably detect the locale.
            return "en"

    def run(self):
        assert self._got_inited

        self.engine.initializePumping()
        self.loop()
        self.engine.finalizePumping()
        self.__kill_engine()

    def loop(self):
        while not self.quit_requested:
            try:
                self.engine.pump()
            except RuntimeError:
                import sys
                print("Unknown Horizons exited uncleanly via SIGINT")
                self._log.log_warn(
                    "Unknown Horizons exited uncleanly via SIGINT")
                sys.exit(1)
            except fife.Exception as e:
                print(e.getMessage())
                break
            for f in self.pump:
                f()
            if self.break_requested:
                self.break_requested = False
                return self.return_values

    def __kill_engine(self):
        """Called when the engine is quit"""
        # A hack to get the system cursor back:
        self.cursor.set(fife.CURSOR_NATIVE)
        self.engine.destroy()

    def breakLoop(self, returnValue=None):
        self.return_values = returnValue
        self.break_requested = True

    def quit(self):
        """Quits the engine."""
        self.quit_requested = True

    @classmethod
    def getVersion(cls):
        """Returns a tuple (Major, Minor, Patch) version of the current running Fife."""
        try:
            return (fife.getMajor(), fife.getMinor(), fife.getPatch())
        except AttributeError:
            return (0, 0, 0)
Beispiel #10
0
class Fife(ApplicationBase):
    """
	Basic initiation of engine. Followed later by init().
	"""
    def __init__(self):
        self.pump = []

        self._setting_handler = SettingsHandler(self)
        self._setup_settings()
        self._set_properly_window_icon()

        self.engine = fife.Engine()
        self.engine_settings = self.engine.getSettings()

        super(Fife, self).initLogging()

        self.loadSettings()

        self.pychan = pychan

        self.quit_requested = False
        self.break_requested = False
        self.return_values = None
        self._got_inited = False

    # existing settings not part of this gui or the fife defaults
    # (required for preserving values when upgrading settings file)
    UNREFERENCED_SETTINGS = {UH_MODULE: ["Nickname", "AIPlayers", "ClientID"]}

    def _set_properly_window_icon(self):
        # Use other Window-Icon for Mac
        if sys.platform == 'darwin' and \
           self.get_fife_setting('WindowIcon') == PATHS.DEFAULT_WINDOW_ICON_PATH:
            self.set_fife_setting('WindowIcon', PATHS.MAC_WINDOW_ICON_PATH)

    def _setup_settings(self, check_file_version=True):
        # NOTE: SimpleXMLSerializer can't handle relative paths, it fails silently
        # (although the doc states otherwise) - thus translate paths to absolute ones
        _template_config_file = os.path.join(os.getcwd(),
                                             PATHS.CONFIG_TEMPLATE_FILE)
        template_config_parser = SimpleXMLSerializer(_template_config_file)
        template_settings_version = template_config_parser.get(
            "meta", "SettingsVersion")
        self._default_hotkeys = template_config_parser.getAllSettings(
            KEY_MODULE)

        _user_config_file = os.path.join(os.getcwd(), PATHS.USER_CONFIG_FILE)
        if check_file_version and os.path.exists(_user_config_file):
            # check if user settings file is the current one
            user_config_parser = SimpleXMLSerializer(_user_config_file)
            user_settings_version = user_config_parser.get(
                "meta", "SettingsVersion", -1)

            if template_settings_version > user_settings_version:  # we have to update the file
                print 'Discovered old settings file, auto-upgrading: %s -> %s' % \
                      (user_settings_version, template_settings_version)
                # create settings so we have a list of all settings
                self._setup_settings(check_file_version=False)

                # save settings here
                entries = []

                # need safe default value
                default_value = object()

                def update_value(modulename, entryname):
                    # retrieve values from loaded settings file
                    try:
                        value = self._setting.get(modulename, entryname,
                                                  default_value)
                    except UnicodeEncodeError:  # this can happen when unicode data is saved as str
                        value = "default"
                    if value is not default_value:
                        entries.append((modulename, entryname, value))

                # collect values from known settings and unreferenced settings
                for modulename, module in self._setting.entries.iteritems():
                    for entryname in module.iterkeys():
                        update_value(modulename, entryname)
                for modulename, entry_list in self.UNREFERENCED_SETTINGS.iteritems(
                ):
                    for entryname in entry_list:
                        update_value(modulename, entryname)

                # patch old values
                if user_settings_version <= 10:
                    old_entries = entries
                    entries = []
                    for i in old_entries:
                        if i[0] == UH_MODULE and i[1] == "Language":
                            entries.append(
                                (i[0], i[1], LANGUAGENAMES.get_by_value(i[2])))
                        else:
                            entries.append(i)

                # write actual new file
                shutil.copy(PATHS.CONFIG_TEMPLATE_FILE, PATHS.USER_CONFIG_FILE)
                user_config_parser = SimpleXMLSerializer(_user_config_file)
                for modulename, entryname, value in entries:
                    user_config_parser.set(modulename, entryname, value)
                user_config_parser.save()

        self._setting = SettingsDialog(
            app_name=UH_MODULE,
            settings_file=PATHS.USER_CONFIG_FILE,
            settings_gui_xml="settings.xml",
            changes_gui_xml="requirerestart.xml",
            default_settings_file=PATHS.CONFIG_TEMPLATE_FILE)

        self._setting_handler.add_settings()

    def init(self):
        """Second initialisation stage of engine
		"""
        self.engine.init()

        #init stuff
        self.eventmanager = self.engine.getEventManager()
        #self.eventmanager.setNonConsumableKeys([fife.Key.ESCAPE, fife.Key.F10])
        self.sound = Sound(self)
        self.imagemanager = self.engine.getImageManager()
        self.targetrenderer = self.engine.getTargetRenderer()
        self.animationloader = None

        #Set game cursor
        self.cursor = self.engine.getCursor()
        cursor_images = {
            'default': 'content/gui/images/cursors/cursor.png',
            'tearing': 'content/gui/images/cursors/cursor_tear.png',
            'attacking': 'content/gui/images/cursors/cursor_attack.png',
            'pipette': 'content/gui/images/cursors/cursor_pipette.png',
            'rename': 'content/gui/images/cursors/cursor_rename.png',
        }
        self.cursor_images = dict((k, self.imagemanager.load(v))
                                  for k, v in cursor_images.iteritems())
        self.cursor.set(self.cursor_images['default'])

        #init pychan
        debug_pychan = self.get_fife_setting('PychanDebug')  # default is False
        self.pychan.init(
            self.engine,
            debug_pychan)  # pychan debug mode may have performance impacts
        self.pychan.setupModalExecution(self.loop, self.breakLoop)
        self.console = self.pychan.manager.hook.guimanager.getConsole()

        init_pychan()
        self.pychanmanager = pychan.internal.get_manager()

        self._setting_handler.apply_settings()

        self._gotInited = True

    def init_animation_loader(self, use_atlases):
        # this method should not be called from init to catch any bugs caused by the loader changing after it.
        self.use_atlases = use_atlases
        if self.use_atlases:
            self.animationloader = SQLiteAtlasLoader()
        else:
            self.animationloader = SQLiteAnimationLoader()

    def show_settings(self):
        """Show fife settings gui"""
        if not hasattr(self, "_settings_extra_inited"):
            self._setting_handler.setup_setting_extras()
            self._settings_extra_inited = True
        self._setting.onOptionsPress()

    def set_cursor_image(self, which="default"):
        """Sets a certain cursor image.
		See definition of cursor_images for reference."""
        self.cursor.set(self.cursor_images[which])

    def get_fife_setting(self, settingname):
        return self._setting.get(FIFE_MODULE, settingname)

    def set_fife_setting(self, settingname, value):
        """Probably saves setting in memory. Call save_settings() later"""
        return self._setting.set(FIFE_MODULE, settingname, value)

    def get_uh_setting(self, settingname):
        return self._setting.get(UH_MODULE, settingname)

    def set_uh_setting(self, settingname, value):
        """Probably saves setting in memory. Call save_settings() later"""
        self._setting.set(UH_MODULE, settingname, value)

    def get_hotkey_settings(self):
        return self._setting.getSettingsFromFile(KEY_MODULE)

    def get_default_key_for_action(self, action):
        return self._default_hotkeys.get(action)

    def get_key_for_action(self, action):
        return self._setting.get(KEY_MODULE, action)

    def set_key_for_action(self, action, key):
        """Sets hotkey *key* for action *action*."""
        self._setting.set(KEY_MODULE, action, key)

    def save_settings(self):
        self._setting.saveSettings()

    def play_sound(self, emitter, soundfile):
        """Plays a soundfile on the given emitter.
		@param emitter: string with the emitters name in horizons.globals.fife.sound.emitter that is to play the  sound
		@param soundfile: string containing the path to the soundfile"""
        self.sound.play_sound(emitter, soundfile)

    def get_locale(self):
        for locale_code, langname in LANGUAGENAMES.items():
            if langname == self.get_uh_setting('Language'):
                if not langname == 'System default':
                    return locale_code
        try:
            default_locale, default_encoding = locale.getdefaultlocale()
            return default_locale.split('_')[0]
        except (ValueError, AttributeError):
            # OS X sometimes returns 'UTF-8' as locale, which is a ValueError.
            # If no locale is set at all, the split will fail, which is an AttributeError.
            # Use 'EN' as fallback in both cases since we cannot reasonably detect the locale.
            return "en"

    def run(self):
        """
		"""
        assert self._gotInited

        # Screen Resolutions can only be queried after the engine has been inited
        available_resolutions = get_screen_resolutions(
            self.get_fife_setting('ScreenResolution'))
        self._setting.entries[FIFE_MODULE][
            'ScreenResolution'].initialdata = available_resolutions

        self.engine.initializePumping()
        self.loop()
        self.engine.finalizePumping()
        self.__kill_engine()

    def loop(self):
        """
		"""
        while not self.quit_requested:
            try:
                self.engine.pump()
            except fife.Exception as e:
                print e.getMessage()
                break
            for f in self.pump:
                f()
            if self.break_requested:
                self.break_requested = False
                return self.return_values

    def __kill_engine(self):
        """Called when the engine is quit"""
        self.cursor.set(fife.CURSOR_NATIVE)  #hack to get system cursor back
        self.engine.destroy()

    def breakLoop(self, returnValue=None):
        """
		@param returnValue:
		"""
        self.return_values = returnValue
        self.break_requested = True

    def quit(self):
        """ Quits the engine.
		"""
        self.quit_requested = True
Beispiel #11
0
class Fife(ApplicationBase):
	"""
	Basic initiation of engine. Followed later by init().
	"""
	def __init__(self):
		self.pump = []

		self._setting_handler = SettingsHandler(self)
		self._setup_settings()
		self._set_window_icon()

		self.engine = fife.Engine()
		self.engine_settings = self.engine.getSettings()

		super(Fife, self).initLogging()

		self.loadSettings()

		self.pychan = pychan

		self.quit_requested = False
		self.break_requested = False
		self.return_values = None
		self._got_inited = False


	# existing settings not part of this gui or the fife defaults
	# (required for preserving values when upgrading settings file)
	UNREFERENCED_SETTINGS = {UH_MODULE: ["Nickname", "AIPlayers", "ClientID"]}

	def _set_window_icon(self):
		"""Use different window icon for Mac."""
		if sys.platform == 'darwin':
			if self.get_fife_setting('WindowIcon') == PATHS.DEFAULT_WINDOW_ICON_PATH:
				self.set_fife_setting('WindowIcon', PATHS.MAC_WINDOW_ICON_PATH)

	def _setup_settings(self, check_file_version=True):
		# NOTE: SimpleXMLSerializer can't handle relative paths, it fails silently
		# (although the doc states otherwise) - thus translate paths to absolute ones
		_template_config_file = os.path.join(os.getcwd(), PATHS.CONFIG_TEMPLATE_FILE)
		template_config_parser = SimpleXMLSerializer(_template_config_file)
		template_settings_version = template_config_parser.get("meta", "SettingsVersion")
		self._default_hotkeys = template_config_parser.getAllSettings(KEY_MODULE)

		_user_config_file = os.path.join(os.getcwd(), PATHS.USER_CONFIG_FILE)
		if check_file_version and os.path.exists(_user_config_file):
			# check if user settings file is the current one
			user_config_parser = SimpleXMLSerializer(_user_config_file)
			user_settings_version = user_config_parser.get("meta", "SettingsVersion", -1)

			if template_settings_version > user_settings_version: # we have to update the file
				print 'Discovered old settings file, auto-upgrading: %s -> %s' % \
				      (user_settings_version, template_settings_version)
				# create settings so we have a list of all settings
				self._setup_settings(check_file_version=False)

				# save settings here
				entries = []

				# need safe default value
				default_value = object()

				def update_value(modulename, entryname):
					# retrieve values from loaded settings file
					try:
						value = self._setting.get(modulename, entryname, default_value)
					except UnicodeEncodeError: # this can happen when unicode data is saved as str
						value = "default"
					if value is not default_value:
						entries.append( (modulename, entryname, value) )

				# collect values from known settings and unreferenced settings
				for modulename, module in self._setting.entries.iteritems():
					for entryname in module.iterkeys():
						update_value(modulename, entryname)
				for modulename, entry_list in self.UNREFERENCED_SETTINGS.iteritems():
					for entryname in entry_list:
						update_value(modulename, entryname)

				# patch old values
				if user_settings_version <= 10:
					old_entries = entries
					entries = []
					for i in old_entries:
						if i[0] == UH_MODULE and i[1] == "Language":
							entries.append( (i[0], i[1], LANGUAGENAMES.get_by_value(i[2])) )
						else:
							entries.append(i)

				# write actual new file
				shutil.copy(PATHS.CONFIG_TEMPLATE_FILE, PATHS.USER_CONFIG_FILE)
				user_config_parser = SimpleXMLSerializer(_user_config_file)
				for modulename, entryname, value in entries:
					user_config_parser.set(modulename, entryname, value)
				user_config_parser.save()

		self._setting = SettingsDialog(app_name=UH_MODULE,
		                               settings_file=PATHS.USER_CONFIG_FILE,
		                               settings_gui_xml="settings.xml",
		                               changes_gui_xml="requirerestart.xml",
		                               default_settings_file=PATHS.CONFIG_TEMPLATE_FILE)

		self._setting_handler.add_settings()

	def init(self):
		"""Second initialization stage of engine
		"""
		self.engine.init()

		#init stuff
		self.eventmanager = self.engine.getEventManager()
		self.sound = Sound(self)
		self.imagemanager = self.engine.getImageManager()
		self.targetrenderer = self.engine.getTargetRenderer()
		self.animationloader = None

		#Set game cursor
		self.cursor = self.engine.getCursor()
		cursor_images = {
			'default':   'content/gui/images/cursors/cursor.png',
			'tearing':   'content/gui/images/cursors/cursor_tear.png',
			'attacking': 'content/gui/images/cursors/cursor_attack.png',
			'pipette':   'content/gui/images/cursors/cursor_pipette.png',
			'rename':    'content/gui/images/cursors/cursor_rename.png',
		}
		self.cursor_images = dict( (k, self.imagemanager.load(v)) for k, v in  cursor_images.iteritems() )
		self.cursor.set(self.cursor_images['default'])

		#init pychan
		debug_pychan = self.get_fife_setting('PychanDebug') # default is False
		self.pychan.init(self.engine, debug_pychan) # pychan debug mode may have performance impacts

		init_pychan()

		self._setting_handler.apply_settings()

		self._got_inited = True

	def init_animation_loader(self, use_atlases):
		# this method should not be called from init to catch any bugs caused by the loader changing after it.
		self.use_atlases = use_atlases
		if self.use_atlases:
			self.animationloader = SQLiteAtlasLoader()
		else:
			self.animationloader = SQLiteAnimationLoader()

	def show_settings(self):
		"""Show fife settings gui"""
		if not hasattr(self, "_settings_extra_inited"):
			self._setting_handler.setup_setting_extras()
			self._settings_extra_inited = True
		if hasattr(self._setting, 'showSettingsDialog'):
			#TODO fifechan / FIFE 0.3.5+ compat
			self._setting.showSettingsDialog()
		else:
			# this is the old (0.3.4 and earlier) API
			self._setting.onOptionsPress()

	def set_cursor_image(self, which="default"):
		"""Sets a certain cursor image.
		See definition of cursor_images for reference."""
		self.cursor.set(self.cursor_images[which])

	def get_fife_setting(self, settingname):
		return self._setting.get(FIFE_MODULE, settingname)

	def set_fife_setting(self, settingname, value):
		"""Probably saves setting in memory. Call save_settings() later"""
		return self._setting.set(FIFE_MODULE, settingname, value)

	def get_uh_setting(self, settingname):
		return self._setting.get(UH_MODULE, settingname)

	def set_uh_setting(self, settingname, value):
		"""Probably saves setting in memory. Call save_settings() later"""
		self._setting.set(UH_MODULE, settingname, value)

	def get_hotkey_settings(self):
		return self._setting.getSettingsFromFile(KEY_MODULE)

	def get_keys_for_action(self, action, default=False):
		"""Returns list of current hotkeys for *action* or its default hotkeys."""
		if default:
			keys = self._default_hotkeys.get(action)
		else:
			keys = self._setting.get(KEY_MODULE, action)
		return keys

	def set_key_for_action(self, action, newkey):
		"""Replaces all existing hotkeys for *action* with *newkey*."""
		self._setting.set(KEY_MODULE, action, newkey)

	def add_key_for_action(self, action, addkey):
		"""Adds hotkey *addkey* to list of hotkeys for action *action*."""
		old_keys = self._setting.get(KEY_MODULE, action, defaultValue=[])
		new_keys = set(old_keys + [addkey])
		self.set_key_for_action(action, list(new_keys))

	def remove_key_for_action(self, action, remkey):
		"""Removes hotkey *remkey* from list of hotkeys for action *action*."""
		old_keys = self._setting.get(KEY_MODULE, action, defaultValue=[])
		if remkey in old_keys:
				old_keys.remove(remkey)
		if len(old_keys) == 0:
				print 'Cannot have no binding for action'
				return
		self.set_key_for_action(action, old_keys)

	def replace_key_for_action(self, action, oldkey, newkey):
		"""Replaces key *oldkey* with key *newkey* for action *action*"""
		old_keys = self._setting.get(KEY_MODULE, action, defaultValue=[])
		if not oldkey in old_keys:
			return
		index = old_keys.index(oldkey)
		old_keys[index] = newkey
		self.set_key_for_action(action, old_keys)

	def save_settings(self):
		self._setting.saveSettings()

	def play_sound(self, emitter, soundfile):
		"""Plays a soundfile on the given emitter.
		@param emitter: string with the emitters name in horizons.globals.fife.sound.emitter that is to play the  sound
		@param soundfile: string containing the path to the soundfile"""
		self.sound.play_sound(emitter, soundfile)

	def get_locale(self):
		for locale_code, langname in LANGUAGENAMES.items():
			if langname == self.get_uh_setting('Language'):
				if not langname == 'System default':
					return locale_code
		try:
			default_locale, default_encoding = locale.getdefaultlocale()
			return default_locale.split('_')[0]
		except (ValueError, AttributeError):
			# OS X sometimes returns 'UTF-8' as locale, which is a ValueError.
			# If no locale is set at all, the split will fail, which is an AttributeError.
			# Use 'EN' as fallback in both cases since we cannot reasonably detect the locale.
			return "en"

	def run(self):
		"""
		"""
		assert self._got_inited

		# Screen Resolutions can only be queried after the engine has been inited
		available_resolutions = get_screen_resolutions(self.get_fife_setting('ScreenResolution'))
		self._setting.entries[FIFE_MODULE]['ScreenResolution'].initialdata = available_resolutions

		self.engine.initializePumping()
		self.loop()
		self.engine.finalizePumping()
		self.__kill_engine()

	def loop(self):
		"""
		"""
		while not self.quit_requested:
			try:
				self.engine.pump()
			except fife.Exception as e:
				print e.getMessage()
				break
			for f in self.pump:
				f()
			if self.break_requested:
				self.break_requested = False
				return self.return_values

	def __kill_engine(self):
		"""Called when the engine is quit"""
		self.cursor.set(fife.CURSOR_NATIVE) #hack to get system cursor back
		self.engine.destroy()

	def breakLoop(self, returnValue=None):
		"""
		@param returnValue:
		"""
		self.return_values = returnValue
		self.break_requested = True

	def quit(self):
		""" Quits the engine.
		"""
		self.quit_requested = True
Beispiel #12
0
	def init(self):
		"""Second initialization stage of engine
		"""
		self.engine.init()
		
		# There is no default value for the LatestBackground setting inside the
		# settings-template.xml file. As this file is used to populate settings.xml
		# when the game is first run, we will examine the LatestBackground setting
		# to determine if the game has run before
		if not self.get_uh_setting('LatestBackground'):
			# The game hasn't run before (or the settings.xml file has been deleted)
			# set the game's resolution to the resolution that is closest to the
			# desktop's resolution and supported by the renderer
			
			# Get_screen_resolutions() returns all supported resolutions, sorted by width
			available_resolutions = get_screen_resolutions(self.get_fife_setting('ScreenResolution'))
			
			# Use the resolution that the game is currently set to as a baseline
			current_width = self.engine.getRenderBackend().getWidth()
			current_height = self.engine.getRenderBackend().getHeight()
			closest_width = current_width
			closest_height = current_height
			
			# Compare the desktop's resolution with the game's current resolution
			desktop_width = self.engine.getDeviceCaps().getDesktopWidth()
			desktop_height = self.engine.getDeviceCaps().getDesktopHeight()
			closest_width_difference = abs(desktop_width - current_width)
			closest_height_difference = abs(desktop_height - current_height)
			
			# Compare all available resolutions with the game's current resolution
			for available_resolution in available_resolutions:
				(width, height) = available_resolution.split('x')
				width_difference = abs(desktop_width - int(width))
				height_difference = abs(desktop_height - int(height))
				
				# If another available resolution is closer to the desktop's resolution
				if (width_difference <= closest_width_difference and
					height_difference <= closest_height_difference):
					# Update the closest resolution
					closest_width = width
					closest_width_difference = width_difference
					closest_height = height
					closest_height_difference = height_difference
			
			# We need to destroy and re-initialize the engine to force the change
			self.engine.destroy()
			self.set_fife_setting('ScreenResolution',str(closest_width)+'x'+str(closest_height))
			self.save_settings()
			self.engine_settings.setScreenWidth(int(closest_width))
			self.engine_settings.setScreenHeight(int(closest_height))
			self.engine.init()

		#init stuff
		self.eventmanager = self.engine.getEventManager()
		self.sound = Sound(self)
		self.imagemanager = self.engine.getImageManager()
		self.targetrenderer = self.engine.getTargetRenderer()
		self.animationloader = None

		#Set game cursor
		self.cursor = self.engine.getCursor()
		cursor_images = {
			'default':   'content/gui/images/cursors/cursor.png',
			'tearing':   'content/gui/images/cursors/cursor_tear.png',
			'attacking': 'content/gui/images/cursors/cursor_attack.png',
			'pipette':   'content/gui/images/cursors/cursor_pipette.png',
			'rename':    'content/gui/images/cursors/cursor_rename.png',
		}
		self.cursor_images = dict( (k, self.imagemanager.load(v)) for k, v in  cursor_images.iteritems() )
		self.cursor.set(self.cursor_images['default'])

		#init pychan
		debug_pychan = self.get_fife_setting('PychanDebug') # default is False
		self.pychan.init(self.engine, debug_pychan) # pychan debug mode may have performance impacts

		init_pychan()

		self._setting_handler.apply_settings()

		self._got_inited = True