def set_network_port(self, port):
     """Sets a new value for client network port"""
     # port is saved as string due to pychan limitations
     try:
         # 0 is not a valid port, but a valid value here (used for default)
         parse_port(port, allow_zero=True)
     except ValueError:
         headline = _("Invalid network port")
         descr = _("The port you specified is not valid. It must be a number between 1 and 65535.")
         advice = _("Please check the port you entered and make sure it is in the specified range.")
         horizons.main._modules.gui.show_error_popup(headline, descr, advice)
         # reset value and reshow settings dlg
         self.engine.set_uh_setting("NetworkPort", u"0")
         ExtScheduler().add_new_object(self._setting.onOptionsPress, self.engine, 0)
     else:
         # port is valid
         try:
             if NetworkInterface() is None:
                 NetworkInterface.create_instance()
             NetworkInterface().network_data_changed(connect=False)
         except Exception as e:
             headline = _(u"Failed to apply new network settings.")
             descr = _("Network features could not be initialized with the current configuration.")
             advice = _("Check the settings you specified in the network section.")
             if 0 < parse_port(port, allow_zero=True) < 1024:
                 # i18n This is advice for players seeing a network error with the current config
                 advice += u" " + _(
                     "Low port numbers sometimes require special access privileges, try 0 or a number greater than 1024."
                 )
             details = unicode(e)
             horizons.main._modules.gui.show_error_popup(headline, descr, advice, details)
             ExtScheduler().add_new_object(self._setting.onOptionsPress, self.engine, 0)
	def __setup_client(self):
		name = horizons.main.fife.get_uh_setting("Nickname")
		serveraddress = [NETWORK.SERVER_ADDRESS, NETWORK.SERVER_PORT]
		clientaddress = None
		client_port = parse_port(horizons.main.fife.get_uh_setting("NetworkPort"), allow_zero=True)
		if NETWORK.CLIENT_ADDRESS is not None or client_port > 0:
			clientaddress = [NETWORK.CLIENT_ADDRESS, client_port]
		try:
			self._client = Client(name, VERSION.RELEASE_VERSION, serveraddress, clientaddress)
		except NetworkException, e:
			raise RuntimeError(e)
	def __setup_client(self):
		name = horizons.main.fife.get_uh_setting("Nickname")
		serveraddress = [NETWORK.SERVER_ADDRESS, NETWORK.SERVER_PORT]
		clientaddress = None
		client_port = parse_port(horizons.main.fife.get_uh_setting("NetworkPort"), allow_zero=True)
		if NETWORK.CLIENT_ADDRESS is not None or client_port > 0:
			clientaddress = [NETWORK.CLIENT_ADDRESS, client_port]
		try:
			self._client = Client(name, VERSION.RELEASE_VERSION, serveraddress, clientaddress)
		except NetworkException, e:
			raise RuntimeError(e)
Esempio n. 4
0
 def set_network_port(self, port):
     """Sets a new value for client network port"""
     # port is saved as string due to pychan limitations
     try:
         # 0 is not a valid port, but a valid value here (used for default)
         parse_port(port, allow_zero=True)
     except ValueError:
         headline = _("Invalid network port")
         descr = _(
             "The port you specified is not valid. It must be a number between 1 and 65535."
         )
         advice = _(
             "Please check the port you entered and make sure it's in the specified range."
         )
         horizons.main._modules.gui.show_error_popup(
             headline, descr, advice)
         # reset value and reshow settings dlg
         self.set_uh_setting("NetworkPort", u"0")
         ExtScheduler().add_new_object(self._setting.onOptionsPress, self,
                                       0)
     else:
         # port is valid
         try:
             if NetworkInterface() is None:
                 NetworkInterface.create_instance()
             NetworkInterface().network_data_changed(connect=False)
         except Exception, e:
             headline = _(u"Failed to apply new network data.")
             descr = _(
                 u"Networking couldn't be initialised with the current configuration."
             )
             advice = _(
                 u"Check the data you entered in the Network section.")
             if 0 < parse_port(port, allow_zero=True) < 1024:
                 advice += u" " + \
                        _("Low port numbers sometimes require special privileges, try one greater than 1024 or 0.")
             details = unicode(e)
             horizons.main._modules.gui.show_error_popup(
                 headline, descr, advice, details)
             ExtScheduler().add_new_object(self._setting.onOptionsPress,
                                           self, 0)
Esempio n. 5
0
def start(_command_line_arguments):
	"""Starts the horizons. Will drop you to the main menu.
	@param _command_line_arguments: options object from optparse.OptionParser. see run_uh.py.
	"""
	global fife, db, debug, preloading, command_line_arguments
	command_line_arguments = _command_line_arguments
	# NOTE: globals are designwise the same thing as singletons. they don't look pretty.
	#       here, we only have globals that are either trivial, or only one instance may ever exist.

	from engine import Fife

	# handle commandline globals
	debug = command_line_arguments.debug

	if command_line_arguments.restore_settings:
		# just delete the file, Settings ctor will create a new one
		os.remove( PATHS.USER_CONFIG_FILE )

	if command_line_arguments.mp_master:
		try:
			mpieces = command_line_arguments.mp_master.partition(':')
			NETWORK.SERVER_ADDRESS = mpieces[0]
			# only change port if port is specified
			if len(mpieces[2]) > 0:
				NETWORK.SERVER_PORT = parse_port(mpieces[2], allow_zero=True)
		except ValueError:
			print "Error: Invalid syntax in --mp-master commandline option. Port must be a number between 1 and 65535."
			return False

	if command_line_arguments.generate_minimap: # we've been called as subprocess to generate a map preview
		from horizons.gui.modules.singleplayermenu import MapPreview
		MapPreview.generate_minimap( * json.loads(
		  command_line_arguments.generate_minimap
		  ) )
		sys.exit(0)

	# init fife before mp_bind is parsed, since it's needed there
	fife = Fife()

	if command_line_arguments.mp_bind:
		try:
			mpieces = command_line_arguments.mp_bind.partition(':')
			NETWORK.CLIENT_ADDRESS = mpieces[0]
			fife.set_uh_setting("NetworkPort", parse_port(mpieces[2], allow_zero=True))
		except ValueError:
			print "Error: Invalid syntax in --mp-bind commandline option. Port must be a number between 1 and 65535."
			return False

	if command_line_arguments.ai_highlights:
		AI.HIGHLIGHT_PLANS = True
	if command_line_arguments.human_ai:
		AI.HUMAN_AI = True

	# set singleplayer natural resource seed
	if command_line_arguments.nature_seed:
		SINGLEPLAYER.SEED = command_line_arguments.nature_seed

	# set MAX_TICKS
	if command_line_arguments.max_ticks:
		GAME.MAX_TICKS = command_line_arguments.max_ticks

	db = _create_main_db()

	# init game parts

	_init_gettext(fife)

	client_id = fife.get_uh_setting("ClientID")
	if client_id is None or len(client_id) == 0:
		# We need a new client id
		client_id = "".join("-" if c in (8, 13, 18, 23) else \
		                    random.choice("0123456789abcdef") for c in xrange(0, 36))
		fife.set_uh_setting("ClientID", client_id)
		fife.save_settings()

	# Install gui logger, needs to be done before instanciating Gui, otherwise we miss
	# the events of the main menu buttons
	if command_line_arguments.log_gui:
		if command_line_arguments.gui_test:
			raise Exception("Logging gui interactions doesn't work when running tests.")
		try:
			from tests.gui.logger import setup_gui_logger
			setup_gui_logger()
		except ImportError:
			import traceback
			traceback.print_exc()
			print
			print "Gui logging requires code that is only present in the repository and is not being installed."
			return False

	# GUI tests always run with sound disabled and SDL (so they can run under xvfb).
	# Needs to be done before engine is initialized.
	if command_line_arguments.gui_test:
		fife.engine.getSettings().setRenderBackend('SDL')
		fife.set_fife_setting('PlaySounds', False)

	ExtScheduler.create_instance(fife.pump)
	fife.init()
	_modules.gui = Gui()
	SavegameManager.init()

	from horizons.entities import Entities
	Entities.load(db, load_now=False) # create all references

	# for preloading game data while in main screen
	preload_lock = threading.Lock()
	preload_thread = threading.Thread(target=preload_game_data, args=(preload_lock,))
	preloading = (preload_thread, preload_lock)

	# initalize update checker
	from horizons.util.checkupdates import UpdateInfo, check_for_updates, show_new_version_hint
	update_info = UpdateInfo()
	update_check_thread = threading.Thread(target=check_for_updates, args=(update_info,))
	update_check_thread.start()
	def update_info_handler(info):
		if info.status == UpdateInfo.UNINITIALISED:
			ExtScheduler().add_new_object(Callback(update_info_handler, info), info)
		elif info.status == UpdateInfo.READY:
			show_new_version_hint(_modules.gui, info)
		elif info.status == UpdateInfo.INVALID:
			pass # couldn't retrieve file or nothing relevant in there

	update_info_handler(update_info) # schedules checks by itself

	# Singleplayer seed needs to be changed before startup.
	if command_line_arguments.sp_seed:
		SINGLEPLAYER.SEED = command_line_arguments.sp_seed

	# start something according to commandline parameters
	startup_worked = True
	if command_line_arguments.start_dev_map:
		startup_worked = _start_dev_map(command_line_arguments.ai_players, command_line_arguments.human_ai, command_line_arguments.force_player_id)
	elif command_line_arguments.start_random_map:
		startup_worked = _start_random_map(command_line_arguments.ai_players, command_line_arguments.human_ai, force_player_id=command_line_arguments.force_player_id)
	elif command_line_arguments.start_specific_random_map is not None:
		startup_worked = _start_random_map(command_line_arguments.ai_players, command_line_arguments.human_ai, \
			seed=command_line_arguments.start_specific_random_map, force_player_id=command_line_arguments.force_player_id)
	elif command_line_arguments.start_map is not None:
		startup_worked = _start_map(command_line_arguments.start_map, command_line_arguments.ai_players, \
			command_line_arguments.human_ai, force_player_id=command_line_arguments.force_player_id)
	elif command_line_arguments.start_scenario is not None:
		startup_worked = _start_map(command_line_arguments.start_scenario, 0, False, True, force_player_id=command_line_arguments.force_player_id)
	elif command_line_arguments.start_campaign is not None:
		startup_worked = _start_campaign(command_line_arguments.start_campaign, force_player_id=command_line_arguments.force_player_id)
	elif command_line_arguments.load_map is not None:
		startup_worked = _load_map(command_line_arguments.load_map, command_line_arguments.ai_players, \
			command_line_arguments.human_ai, command_line_arguments.force_player_id)
	elif command_line_arguments.load_quicksave is not None:
		startup_worked = _load_last_quicksave()
	elif command_line_arguments.stringpreview:
		tiny = [ i for i in SavegameManager.get_maps()[0] if 'tiny' in i ]
		if not tiny:
			tiny = SavegameManager.get_map()[0]
		startup_worked = _start_map(tiny[0], ai_players=0, human_ai=False, trader_enabled=False, pirate_enabled=False, \
			force_player_id=command_line_arguments.force_player_id)
		from development.stringpreviewwidget import StringPreviewWidget
		__string_previewer = StringPreviewWidget(_modules.session)
		__string_previewer.show()
	elif command_line_arguments.create_mp_game:
		_modules.gui.show_main()
		_modules.gui.show_multi()
		_modules.gui.create_default_mp_game()
	elif command_line_arguments.join_mp_game:
		_modules.gui.show_main()
		_modules.gui.show_multi()
		_modules.gui.join_mp_game()
	else: # no commandline parameter, show main screen
		_modules.gui.show_main()
		if not command_line_arguments.nopreload:
			preloading[0].start()

	if not startup_worked:
		# don't start main loop if startup failed
		return False

	if command_line_arguments.gamespeed is not None:
		_modules.session.speed_set(GAME_SPEED.TICKS_PER_SECOND*command_line_arguments.gamespeed)

	if command_line_arguments.gui_test:
		from tests.gui import TestRunner
		TestRunner(fife, command_line_arguments.gui_test)

	if command_line_arguments.interactive_shell:
		from horizons.util import interactive_shell
		interactive_shell.start(fife)

	fife.run()
Esempio n. 6
0
def start(command_line_arguments):
    """Starts the horizons.
	@param command_line_arguments: options object from optparse.OptionParser. see run_uh.py.
	"""
    global fife, db, debug, preloading
    # NOTE: globals are designwise the same thing as singletons. they don't look pretty.
    #       here, we only have globals that are either trivial, or only one instance may ever exist.

    from engine import Fife

    # handle commandline globals
    debug = command_line_arguments.debug

    if command_line_arguments.restore_settings:
        # just delete the file, Settings ctor will create a new one
        os.remove(PATHS.USER_CONFIG_FILE)

    if command_line_arguments.mp_master:
        try:
            mpieces = command_line_arguments.mp_master.partition(':')
            NETWORK.SERVER_ADDRESS = mpieces[0]
            # only change port if port is specified
            if len(mpieces[2]) > 0:
                NETWORK.SERVER_PORT = parse_port(mpieces[2], allow_zero=True)
        except ValueError:
            print _(
                "Error: Invalid syntax in --mp-master commandline option. Port must be a number between 1 and 65535."
            )
            return False

    # init fife before mp_bind is parsed, since it's needed there
    fife = Fife()

    if command_line_arguments.mp_bind:
        try:
            mpieces = command_line_arguments.mp_bind.partition(':')
            NETWORK.CLIENT_ADDRESS = mpieces[0]
            fife.set_uh_setting("NetworkPort",
                                parse_port(mpieces[2], allow_zero=True))
            print 'asdf', fife.get_uh_setting("NetworkPort2")
        except ValueError:
            print _(
                "Error: Invalid syntax in --mp-bind commandline option. Port must be a number between 1 and 65535."
            )
            return False

    db = _create_db()

    # init game parts

    _init_gettext(fife)

    client_id = fife.get_uh_setting("ClientID")
    if client_id is None or len(client_id) == 0:
        # We need a new client id
        client_id = "".join("-" if c in (8, 13, 18, 23) else \
                            random.choice("0123456789abcdef") for c in xrange(0, 36))
        from engine import UH_MODULE
        fife.settings.set(UH_MODULE, "ClientID", client_id)
        fife.settings.saveSettings()

    ExtScheduler.create_instance(fife.pump)
    fife.init()
    _modules.gui = Gui()
    SavegameManager.init()
    try:
        NetworkInterface.create_instance()
    except RuntimeError, e:
        headline = _(u"Failed to initialize networking.")
        descr = _(
            u"Networking couldn't be initialised with the current configuration."
        )
        advice = _(
            u"Check the data you entered in the Network section in the settings dialogue."
        )
        _modules.gui.show_error_popup(headline, descr, advice, unicode(e))
Esempio n. 7
0
def start(command_line_arguments):
	"""Starts the horizons.
	@param command_line_arguments: options object from optparse.OptionParser. see run_uh.py.
	"""
	global fife, db, debug, preloading
	# NOTE: globals are designwise the same thing as singletons. they don't look pretty.
	#       here, we only have globals that are either trivial, or only one instance may ever exist.

	from engine import Fife

	# handle commandline globals
	debug = command_line_arguments.debug

	if command_line_arguments.restore_settings:
		# just delete the file, Settings ctor will create a new one
		os.remove( PATHS.USER_CONFIG_FILE )

	if command_line_arguments.mp_master:
		try:
			mpieces = command_line_arguments.mp_master.partition(':')
			NETWORK.SERVER_ADDRESS = mpieces[0]
			# only change port if port is specified
			if len(mpieces[2]) > 0:
				NETWORK.SERVER_PORT = parse_port(mpieces[2], allow_zero=True)
		except ValueError:
			print _("Error: Invalid syntax in --mp-master commandline option. Port must be a number between 1 and 65535.")
			return False

	# init fife before mp_bind is parsed, since it's needed there
	fife = Fife()

	if command_line_arguments.mp_bind:
		try:
			mpieces = command_line_arguments.mp_bind.partition(':')
			NETWORK.CLIENT_ADDRESS = mpieces[0]
			fife.set_uh_setting("NetworkPort", parse_port(mpieces[2], allow_zero=True))
		except ValueError:
			print _("Error: Invalid syntax in --mp-bind commandline option. Port must be a number between 1 and 65535.")
			return False

	AI.AI_PLAYERS = command_line_arguments.ai_players
	if command_line_arguments.ai_highlights:
		AI.HIGHLIGHT_PLANS = True
	if command_line_arguments.human_ai:
		AI.HUMAN_AI = True

	# set singleplayer natural resource seed
	if command_line_arguments.nature_seed:
		SINGLEPLAYER.SEED = command_line_arguments.nature_seed

	# set MAX_TICKS
	if command_line_arguments.max_ticks:
		GAME.MAX_TICKS = command_line_arguments.max_ticks

	db = _create_db()

	# init game parts

	_init_gettext(fife)

	client_id = fife.get_uh_setting("ClientID")
	if client_id is None or len(client_id) == 0:
		# We need a new client id
		client_id = "".join("-" if c in (8, 13, 18, 23) else \
		                    random.choice("0123456789abcdef") for c in xrange(0, 36))
		from engine import UH_MODULE
		fife.settings.set(UH_MODULE, "ClientID", client_id)
		fife.settings.saveSettings()

	ExtScheduler.create_instance(fife.pump)
	fife.init()
	_modules.gui = Gui()
	SavegameManager.init()

	# for preloading game data while in main screen
	preload_lock = threading.Lock()
	preload_thread = threading.Thread(target=preload_game_data, args=(preload_lock,))
	preloading = (preload_thread, preload_lock)

	# start something according to commandline parameters
	startup_worked = True
	if command_line_arguments.start_dev_map:
		startup_worked = _start_dev_map(command_line_arguments.ai_players, command_line_arguments.human_ai)
	elif command_line_arguments.start_random_map:
		startup_worked = _start_random_map(command_line_arguments.ai_players, command_line_arguments.human_ai)
	elif command_line_arguments.start_specific_random_map is not None:
		startup_worked = _start_random_map(command_line_arguments.ai_players, command_line_arguments.human_ai, \
			seed=command_line_arguments.start_specific_random_map)
	elif command_line_arguments.start_map is not None:
		startup_worked = _start_map(command_line_arguments.start_map, command_line_arguments.ai_players, \
			command_line_arguments.human_ai)
	elif command_line_arguments.start_scenario is not None:
		startup_worked = _start_map(command_line_arguments.start_scenario, 0, False, True)
	elif command_line_arguments.start_campaign is not None:
		startup_worked = _start_campaign(command_line_arguments.start_campaign)
	elif command_line_arguments.load_map is not None:
		startup_worked = _load_map(command_line_arguments.load_map, command_line_arguments.ai_players, \
			command_line_arguments.human_ai)
	elif command_line_arguments.load_quicksave is not None:
		startup_worked = _load_last_quicksave()
	elif command_line_arguments.stringpreview:
		startup_worked = _start_map("development_no_trees", 0, False)
		from development.stringpreviewwidget import StringPreviewWidget
		StringPreviewWidget().show()
	else: # no commandline parameter, show main screen
		_modules.gui.show_main()
		preloading[0].start()

	if not startup_worked:
		# don't start main loop if startup failed
		return False

	fife.run()
Esempio n. 8
0
def start(command_line_arguments):
	"""Starts the horizons.
	@param command_line_arguments: options object from optparse.OptionParser. see run_uh.py.
	"""
	global fife, db, debug, preloading
	# NOTE: globals are designwise the same thing as singletons. they don't look pretty.
	#       here, we only have globals that are either trivial, or only one instance may ever exist.

	from engine import Fife

	# handle commandline globals
	debug = command_line_arguments.debug

	if command_line_arguments.restore_settings:
		# just delete the file, Settings ctor will create a new one
		os.remove( PATHS.USER_CONFIG_FILE )

	if command_line_arguments.mp_master:
		try:
			mpieces = command_line_arguments.mp_master.partition(':')
			NETWORK.SERVER_ADDRESS = mpieces[0]
			# only change port if port is specified
			if len(mpieces[2]) > 0:
				NETWORK.SERVER_PORT = parse_port(mpieces[2], allow_zero=True)
		except ValueError:
			print _("Error: Invalid syntax in --mp-master commandline option. Port must be a number between 1 and 65535.")
			return False

	# init fife before mp_bind is parsed, since it's needed there
	fife = Fife()

	if command_line_arguments.mp_bind:
		try:
			mpieces = command_line_arguments.mp_bind.partition(':')
			NETWORK.CLIENT_ADDRESS = mpieces[0]
			fife.set_uh_setting("NetworkPort", parse_port(mpieces[2], allow_zero=True))
			print 'asdf', fife.get_uh_setting("NetworkPort2")
		except ValueError:
			print _("Error: Invalid syntax in --mp-bind commandline option. Port must be a number between 1 and 65535.")
			return False

	db = _create_db()

	# init game parts

	_init_gettext(fife)

	client_id = fife.get_uh_setting("ClientID")
	if client_id is None or len(client_id) == 0:
		# We need a new client id
		client_id = "".join("-" if c in (8, 13, 18, 23) else \
		                    random.choice("0123456789abcdef") for c in xrange(0, 36))
		from engine import UH_MODULE
		fife.settings.set(UH_MODULE, "ClientID", client_id)
		fife.settings.saveSettings()

	ExtScheduler.create_instance(fife.pump)
	fife.init()
	_modules.gui = Gui()
	SavegameManager.init()
	try:
		NetworkInterface.create_instance()
	except RuntimeError, e:
		headline = _(u"Failed to initialize networking.")
		descr = _(u"Networking couldn't be initialised with the current configuration.")
		advice = _(u"Check the data you entered in the Network section in the settings dialogue.")
		_modules.gui.show_error_popup(headline, descr, advice, unicode(e))