Ejemplo n.º 1
0
	def update_data(self):
		field_comp = self.instance.get_component(FieldBuilder)
		icon = self.widget.child_finder('build_all_bg')
		button = self.widget.child_finder('build_all_button')

		(enough_res, missing_res) = field_comp.check_resources()
		# Disable "build menu" button if nothing would be built or construction
		# cannot be afforded by the player right now.
		if enough_res and field_comp.how_many > 0:
			icon.image = "content/gui/images/buttons/buildmenu_button_bg.png"
			button.path = 'icons/tabwidget/lumberjackcamp/tree_area_build'
		else:
			icon.image = "content/gui/images/buttons/buildmenu_button_bg_bw.png"
			button.path = 'icons/tabwidget/lumberjackcamp/no_area_build'
		button.min_size = button.max_size = button.size = (46, 46)
		button.helptext = T('Fill range with {how_many} trees').format(
			how_many=field_comp.how_many)

		res_bar = self.instance.session.ingame_gui.resource_overview

		click_cb = Callback.ChainedCallbacks(field_comp.fill_range, self.update_data)
		enter_cb = Callback(res_bar.set_construction_mode, self.instance, field_comp.total_cost)
		#TODO the tooltip should actually hide on its own. Ticket #1096
		exit_cb = Callback.ChainedCallbacks(res_bar.close_construction_mode, button.hide_tooltip)
		self.widget.mapEvents({
			button.name: click_cb,
			button.name + '/mouseEntered': enter_cb,
			button.name + '/mouseExited': exit_cb,
		})
Ejemplo n.º 2
0
    def __init__(self, session):
        self.session = session

        self.which = None
        self.cursor = None
        self.coordinates_tooltip = None
        self.keylistener = IngameKeyListener(self.session)
        # used by NavigationTool
        LastActivePlayerSettlementManager.create_instance(self.session)

        # Mocks needed to act like the real IngameGui
        self.show_menu = mock.Mock()
        self.hide_menu = mock.Mock()
        # this is necessary for message_widget to work
        self.logbook = mock.Mock()

        self.mainhud = load_uh_widget('minimap.xml')
        self.mainhud.position_technique = "right+0:top+0"

        icon = self.mainhud.findChild(name="minimap")
        self.minimap = Minimap(
            icon,
            targetrenderer=horizons.globals.fife.targetrenderer,
            imagemanager=horizons.globals.fife.imagemanager,
            session=self.session,
            view=self.session.view)

        self.mainhud.mapEvents({
            'zoomIn':
            self.session.view.zoom_in,
            'zoomOut':
            self.session.view.zoom_out,
            'rotateRight':
            Callback.ChainedCallbacks(self.session.view.rotate_right,
                                      self.minimap.update_rotation),
            'rotateLeft':
            Callback.ChainedCallbacks(self.session.view.rotate_left,
                                      self.minimap.update_rotation),
            'gameMenuButton':
            self.toggle_pause,
        })

        self.mainhud.show()
        ZoomChanged.subscribe(self._update_zoom)

        # Hide unnecessary buttons in hud
        for widget in ("build", "speedUp", "speedDown", "destroy_tool",
                       "diplomacyButton", "logbook"):
            self.mainhud.findChild(name=widget).hide()

        self.windows = WindowManager()
        self.message_widget = MessageWidget(self.session)
        self.pausemenu = PauseMenu(self.session,
                                   self,
                                   self.windows,
                                   in_editor_mode=True)
        self.help_dialog = HelpDialog(self.windows)
Ejemplo n.º 3
0
	def _refresh_found_settlement_button(self, events):
		island_without_player_settlement_found = False
		helptext = T("The ship needs to be close to an island to found a settlement.")
		for island in self.instance.session.world.get_islands_in_radius(self.instance.position, self.instance.radius):
			if not any(settlement.owner.is_local_player for settlement in island.settlements):
				island_without_player_settlement_found = True
			else:
				helptext = T("You already have a settlement on this island.")

		if island_without_player_settlement_found:
			events['found_settlement'] = Callback(self.instance.session.ingame_gui._build,
			                                      BUILDINGS.WAREHOUSE,
			                                      weakref.ref(self.instance) )
			self.widget.child_finder('found_settlement_bg').set_active()
			self.widget.child_finder('found_settlement').set_active()
			self.widget.child_finder('found_settlement').helptext = T("Build settlement")
		else:
			events['found_settlement'] = None
			self.widget.child_finder('found_settlement_bg').set_inactive()
			self.widget.child_finder('found_settlement').set_inactive()
			self.widget.child_finder('found_settlement').helptext = helptext

		cb = Callback( self.instance.session.ingame_gui.resource_overview.set_construction_mode,
		               self.instance,
		               Entities.buildings[BUILDINGS.WAREHOUSE].costs)
		events['found_settlement/mouseEntered'] = cb

		cb1 = Callback(self.instance.session.ingame_gui.resource_overview.close_construction_mode)
		cb2 = Callback(self.widget.child_finder('found_settlement').hide_tooltip)
		#TODO the tooltip should actually hide on its own. Ticket #1096
		cb = Callback.ChainedCallbacks(cb1, cb2)
		events['found_settlement/mouseExited'] = cb
Ejemplo n.º 4
0
	def load(self, db, worldid):
		super(Collector, self).load(db, worldid)

		# load collector properties
		state_id, remaining_ticks, start_hidden = \
		        db("SELECT state, remaining_ticks, start_hidden FROM collector \
		            WHERE rowid = ?", worldid)[0]
		self.__init(self.states[state_id], start_hidden)

		# load job
		job_db = db("SELECT object, resource, amount FROM collector_job WHERE collector = ?", worldid)
		if job_db:
			reslist = []
			for obj, res, amount in job_db:
				reslist.append( Job.ResListEntry(res, amount, False) )
			# create job with worldid of object as object. This is used to defer the target resolution,
			# which might not have been loaded
			self.job = Job(obj, reslist)

		def fix_job_object():
			# resolve worldid to object later
			if self.job:
				if self.job.object == -1:
					self.job.object = None   # e.g. when hunters have killed their prey
				else:
					self.job.object = WorldObject.get_object_by_id(self.job.object)

		# apply state when job object is loaded for sure
		Scheduler().add_new_object(
			Callback.ChainedCallbacks(
				fix_job_object,
				Callback(self.apply_state, self.state, remaining_ticks)),
			self, run_in=0
		)
Ejemplo n.º 5
0
	def _show_resource_selection_dialog(self, slot_num):
		"""Shows gui for selecting a resource for slot slot_num"""
		if isinstance(self.session.ingame_gui.cursor, BuildingTool):
			return

		self._hide_resource_selection_dialog()
		inv = self._get_current_inventory()
		if inv is None:
			return

		self._show_dummy_slot()

		# set mousetool to get notified on clicks outside the resbar area
		if not isinstance(self.session.ingame_gui.cursor, ResBarMouseTool):
			self.session.ingame_gui.cursor = ResBarMouseTool(self.session, self.session.ingame_gui.cursor,
			                                      self.close_resource_selection_mode)


		on_click = functools.partial(self._set_resource_slot, slot_num)
		cur_res = self._get_current_resources()
		res_filter = lambda res_id : res_id not in cur_res
		dlg = create_resource_selection_dialog(on_click, inv, self.session.db,
		                                       widget='resbar_resource_selection.xml',
		                                       res_filter=res_filter)

		# position dlg below slot
		cur_gui = self.gui[slot_num]
		background_icon = cur_gui.findChild(name="background_icon")
		dlg.position = (cur_gui.position[0] + background_icon.position[0],
		                cur_gui.position[1] + background_icon.position[1] + background_icon.size[1] )
		dlg.findChild(name="make_default_btn").capture(self._make_configuration_default)
		reset_default_btn = dlg.findChild(name="reset_default_btn")
		# this is a quadruple-use button.
		# If there is no user set default, restore to factory default
		# If the current config is different from user default, set to default
		# If this is the current user set config, remove user set config and fall back to factory default
		# If there is no user set config and the current config is the system default,
		# the button should be disabled, but the first case below is shown because
		# we can't disable it
		if self._custom_default_resources is None:
			reset_default_btn.helptext = _("Reset this configuration to the factory default.")
			reset_default_btn.capture(Callback(self._drop_settlement_resource_configuration))

		elif self._custom_default_resources != self._get_current_resources():
			reset_default_btn.helptext = _("Reset this settlement's displayed resources to the default configuration you have saved.")
			reset_default_btn.capture(Callback(self._drop_settlement_resource_configuration))

		else:
			reset_default_btn.helptext = _("Reset the default configuration (which you see here) to the factory default for all settlements.")
			cb = Callback.ChainedCallbacks(
			  self._drop_settlement_resource_configuration, # remove specific config
			  Callback(self._make_configuration_default, reset=True) # remove global config
			)
			reset_default_btn.capture( cb )

		dlg.show()
		self._res_selection_dialog = dlg
Ejemplo n.º 6
0
	def make_ruin(self):
		""" Replaces itself with a ruin.
		"""
		command = Build(BUILDINGS.SETTLER_RUIN, self.position.origin.x,
		                self.position.origin.y, island=self.island, settlement=self.settlement)

		# Remove the building and then place the Ruin
		Scheduler().add_new_object(Callback.ChainedCallbacks(
			self.remove, Callback(command, self.owner)), self, run_in=0)
Ejemplo n.º 7
0
def set_var(session, variable, value):
	"""Assigns values to scenario variables. Overwrites previous assignments to the same variable."""
	session.scenario_eventhandler._scenario_variables[variable] = value
	check_callbacks = Callback.ChainedCallbacks(
	  Callback(session.scenario_eventhandler.check_events, CONDITIONS.var_eq),
	  Callback(session.scenario_eventhandler.check_events, CONDITIONS.var_lt),
	  Callback(session.scenario_eventhandler.check_events, CONDITIONS.var_gt)
	)
	Scheduler().add_new_object(check_callbacks, session.scenario_eventhandler, run_in=0)
Ejemplo n.º 8
0
    def draw_widget(self):
        """
		Updates whole messagewidget (all messages): draw icons.
		Inactive messages need their icon hovered to display their text again
		"""
        button_space = self.widget.findChild(name="button_space")
        button_space.removeAllChildren()  # Remove old buttons
        for index, message in enumerate(self.active_messages):
            if (self.item + index) >= len(self.active_messages):
                # Only display most recent notifications
                continue
            button = ImageButton()
            button.name = str(index)
            button.up_image = message.up_image
            button.hover_image = message.hover_image
            button.down_image = message.down_image
            button.is_focusable = False
            # show text on hover
            events = {
                button.name + "/mouseEntered": Callback(self.show_text, index),
                button.name + "/mouseExited": self.hide_text,
            }
            # init callback to something callable to improve robustness
            callback = Callback(lambda: None)
            if message.x is not None and message.y is not None:
                # move camera to source of event on click, if there is a source
                callback = Callback.ChainedCallbacks(
                    callback,  # this makes it so the order of callback assignment doesn't matter
                    Callback(self.session.view.center, message.x, message.y),
                    Callback(self.session.ingame_gui.minimap.highlight,
                             (message.x, message.y)))
            if message.type == "logbook":
                # open logbook to relevant page
                callback = Callback.ChainedCallbacks(
                    callback,  # this makes it so the order of callback assignment doesn't matter
                    Callback(self.session.ingame_gui.logbook.show,
                             message.created))
            if callback:
                events[button.name] = callback

            button.mapEvents(events)
            button_space.addChild(button)
        button_space.resizeToContent()
        self.widget.size = button_space.size
Ejemplo n.º 9
0
	def _schedule_refresh(self):
		"""Schedule a refresh soon, dropping all other refresh request, that appear until then.
		This saves a lot of CPU time, if you have a huge island, or play on high speed."""
		if not self._refresh_scheduled:
			self._refresh_scheduled = True
			def unset_flag():
				# set the flag here and not in refresh() since we can't be sure whether
				# refresh() of this class will be reached or a subclass will not call super()
				self._refresh_scheduled = False
			ExtScheduler().add_new_object(Callback.ChainedCallbacks(unset_flag, self.refresh),
			                              self, run_in=self.__class__.scheduled_update_delay)
Ejemplo n.º 10
0
    def prepare(self):
        if self._mode == 'load':
            self._map_files, self._map_file_display = SavegameManager.get_saves(
            )
            if not self._map_files:
                self._windows.open_popup(
                    T("No saved games"),
                    T("There are no saved games to load."))
                return False
        elif self._mode == 'save':
            self._map_files, self._map_file_display = SavegameManager.get_regular_saves(
            )
        elif self._mode == 'editor-save':
            self._map_files, self._map_file_display = SavegameManager.get_maps(
            )

        self._gui.distributeInitialData(
            {'savegamelist': self._map_file_display})
        if self._mode == 'load':
            self._gui.distributeData({'savegamelist': 0})

        self._cb = self._create_show_savegame_details(self._gui,
                                                      self._map_files,
                                                      'savegamelist')
        if self._mode in ('save', 'editor-save'):

            def selected_changed():
                """Fills in the name of the savegame in the textbox when selected in the list"""
                if self._gui.collectData(
                        'savegamelist'
                ) == -1:  # set blank if nothing is selected
                    self._gui.findChild(name="savegamefile").text = u""
                else:
                    savegamefile = self._map_file_display[
                        self._gui.collectData('savegamelist')]
                    self._gui.distributeData({'savegamefile': savegamefile})

            self._cb = Callback.ChainedCallbacks(self._cb, selected_changed)

        self._cb()  # Refresh data on start
        self._gui.mapEvents({'savegamelist/action': self._cb})
        self._gui.findChild(name="savegamelist").capture(
            self._cb, event_name="keyPressed")
        self._gui.findChild(name="savegamelist").capture(
            self.check_double_click, event_name="mousePressed")

        self.return_events = {
            OkButton.DEFAULT_NAME: True,
            CancelButton.DEFAULT_NAME: False,
            DeleteButton.DEFAULT_NAME: 'delete'
        }
        if self._mode in ('save', 'editor-save'):
            self.return_events['savegamefile'] = True
Ejemplo n.º 11
0
    def __init__(self, session):
        super(IngameGui, self).__init__()
        self.session = session
        assert isinstance(self.session, horizons.session.Session)
        self.settlement = None
        self._old_menu = None

        self.cursor = None
        self.coordinates_tooltip = None

        self.keylistener = IngameKeyListener(self.session)

        self.cityinfo = CityInfo(self)
        LastActivePlayerSettlementManager.create_instance(self.session)

        self.message_widget = MessageWidget(self.session)

        # Windows
        self.windows = WindowManager()
        self.show_popup = self.windows.show_popup
        self.show_error_popup = self.windows.show_error_popup

        self.logbook = LogBook(self.session, self.windows)
        self.players_overview = PlayersOverview(self.session)
        self.players_settlements = PlayersSettlements(self.session)
        self.players_ships = PlayersShips(self.session)

        self.chat_dialog = ChatDialog(self.windows, self.session)
        self.change_name_dialog = ChangeNameDialog(self.windows, self.session)
        self.pausemenu = PauseMenu(self.session,
                                   self,
                                   self.windows,
                                   in_editor_mode=False)
        self.help_dialog = HelpDialog(self.windows, session=self.session)

        # Icon manager
        self.status_icon_manager = StatusIconManager(
            renderer=self.session.view.renderer['GenericRenderer'],
            layer=self.session.view.layers[LAYERS.OBJECTS])
        self.production_finished_icon_manager = ProductionFinishedIconManager(
            renderer=self.session.view.renderer['GenericRenderer'],
            layer=self.session.view.layers[LAYERS.OBJECTS])

        # 'minimap' is the guichan gui around the actual minimap, which is saved
        # in self.minimap
        self.mainhud = load_uh_widget('minimap.xml')
        self.mainhud.position_technique = "right:top"

        icon = self.mainhud.findChild(name="minimap")
        self.minimap = Minimap(
            icon,
            targetrenderer=horizons.globals.fife.targetrenderer,
            imagemanager=horizons.globals.fife.imagemanager,
            session=self.session,
            view=self.session.view)

        def speed_up():
            SpeedUpCommand().execute(self.session)

        def speed_down():
            SpeedDownCommand().execute(self.session)

        self.mainhud.mapEvents({
            'zoomIn':
            self.session.view.zoom_in,
            'zoomOut':
            self.session.view.zoom_out,
            'rotateRight':
            Callback.ChainedCallbacks(self.session.view.rotate_right,
                                      self.minimap.rotate_right),
            'rotateLeft':
            Callback.ChainedCallbacks(self.session.view.rotate_left,
                                      self.minimap.rotate_left),
            'speedUp':
            speed_up,
            'speedDown':
            speed_down,
            'destroy_tool':
            self.toggle_destroy_tool,
            'build':
            self.show_build_menu,
            'diplomacyButton':
            self.show_diplomacy_menu,
            'gameMenuButton':
            self.toggle_pause,
            'logbook':
            lambda: self.windows.toggle(self.logbook)
        })
        self.mainhud.show()

        self.resource_overview = ResourceOverviewBar(self.session)

        # Register for messages
        SpeedChanged.subscribe(self._on_speed_changed)
        NewDisaster.subscribe(self._on_new_disaster)
        NewSettlement.subscribe(self._on_new_settlement)
        PlayerLevelUpgrade.subscribe(self._on_player_level_upgrade)
        MineEmpty.subscribe(self._on_mine_empty)
        self.session.view.add_change_listener(self._update_zoom)

        self._display_speed(self.session.timer.ticks_per_second)
Ejemplo n.º 12
0
    def __init__(self, session, gui):
        super(IngameGui, self).__init__()
        self.session = session
        assert isinstance(self.session, horizons.session.Session)
        self.main_gui = gui
        self.main_widget = None
        self.tabwidgets = {}
        self.settlement = None
        self.resource_source = None
        self.resources_needed, self.resources_usable = {}, {}
        self._old_menu = None

        self.widgets = LazyWidgetsDict(self.styles, center_widgets=False)

        self.cityinfo = self.widgets['city_info']
        self.cityinfo.child_finder = PychanChildFinder(self.cityinfo)

        self.logbook = LogBook(self.session)
        self.message_widget = MessageWidget(self.session)
        self.players_overview = PlayersOverview(self.session)
        self.players_settlements = PlayersSettlements(self.session)
        self.players_ships = PlayersShips(self.session)

        # self.widgets['minimap'] is the guichan gui around the actual minimap,
        # which is saved in self.minimap
        minimap = self.widgets['minimap']
        minimap.position_technique = "right+0:top+0"

        icon = minimap.findChild(name="minimap")
        self.minimap = Minimap(
            icon,
            targetrenderer=horizons.globals.fife.targetrenderer,
            imagemanager=horizons.globals.fife.imagemanager,
            session=self.session,
            view=self.session.view)

        def speed_up():
            SpeedUpCommand().execute(self.session)

        def speed_down():
            SpeedDownCommand().execute(self.session)

        minimap.mapEvents({
            'zoomIn':
            self.session.view.zoom_in,
            'zoomOut':
            self.session.view.zoom_out,
            'rotateRight':
            Callback.ChainedCallbacks(self.session.view.rotate_right,
                                      self.minimap.rotate_right),
            'rotateLeft':
            Callback.ChainedCallbacks(self.session.view.rotate_left,
                                      self.minimap.rotate_left),
            'speedUp':
            speed_up,
            'speedDown':
            speed_down,
            'destroy_tool':
            self.session.toggle_destroy_tool,
            'build':
            self.show_build_menu,
            'diplomacyButton':
            self.show_diplomacy_menu,
            'gameMenuButton':
            self.main_gui.toggle_pause,
            'logbook':
            self.logbook.toggle_visibility
        })
        minimap.show()
        #minimap.position_technique = "right+15:top+153"

        self.widgets['tooltip'].hide()

        self.resource_overview = ResourceOverviewBar(self.session)
        ResourceBarResize.subscribe(self._on_resourcebar_resize)

        # Register for messages
        SettlerUpdate.subscribe(self._on_settler_level_change)
        SettlerInhabitantsChanged.subscribe(self._on_settler_inhabitant_change)
        HoverSettlementChanged.subscribe(self._cityinfo_set)
    def _select_single(self, show):
        assert show in ('random', 'scenario', 'free_maps')
        self.hide()
        event_map = {
            'cancel':
            Callback.ChainedCallbacks(self._save_player_name, self.show_main),
            'okay':
            self.start_single,
            'scenario':
            Callback(self._select_single, show='scenario'),
            'random':
            Callback(self._select_single, show='random'),
            'free_maps':
            Callback(self._select_single, show='free_maps')
        }
        self.current.mapEvents(event_map)

        # init gui for subcategory
        right_side = self.widgets['sp_%s' % show]
        self.current.findChild(name=show).marked = True
        self.current.aidata.hide()

        # hide previous widget, unhide new right side widget
        if self.active_right_side is not None:
            self.active_right_side.parent.hideChild(self.active_right_side)
        right_side.parent.showChild(right_side)
        self.active_right_side = right_side

        if show == 'random':
            self._setup_random_map_selection(right_side)
            self._setup_game_settings_selection()
            self._on_random_map_parameter_changed()
            self.active_right_side.findChild(
                name="open_random_map_archive").capture(
                    self._open_random_map_archive)
            self.current.aidata.show()

        elif show == 'free_maps':
            self.current.files, maps_display = SavegameManager.get_maps()

            self.active_right_side.distributeInitialData({
                'maplist':
                maps_display,
            })
            # update preview whenever something is selected in the list
            self.active_right_side.mapEvents({
                'maplist/action':
                self._update_free_map_infos,
            })
            self._setup_game_settings_selection()
            if maps_display:  # select first entry
                self.active_right_side.distributeData({'maplist': 0})
            self.current.aidata.show()
            self._update_free_map_infos()

        elif show == 'scenario':
            self.current.files, maps_display = SavegameManager.get_available_scenarios(
                hide_test_scenarios=True)
            # get the map files and their display names. display tutorials on top.
            prefer_tutorial = lambda x: ('tutorial' not in x, x)
            maps_display.sort(key=prefer_tutorial)
            self.current.files.sort(key=prefer_tutorial)
            #add all locales to lang list, select current locale as default and sort
            lang_list = self.current.findChild(name="uni_langlist")
            self.active_right_side.distributeInitialData({
                'maplist':
                maps_display,
            })
            if maps_display:  # select first entry
                self.active_right_side.distributeData({'maplist': 0})
            lang_list.items = self._get_available_languages()
            cur_locale = horizons.globals.fife.get_locale()
            if LANGUAGENAMES[cur_locale] in lang_list.items:
                lang_list.selected = lang_list.items.index(
                    LANGUAGENAMES[cur_locale])
            else:
                lang_list.selected = 0
            self.active_right_side.mapEvents({
                'maplist/action':
                self._update_scenario_infos,
                'uni_langlist/action':
                self._update_scenario_infos,
            })
            self._update_scenario_infos()

        self.current.show()
        self.on_escape = self.show_main
Ejemplo n.º 14
0
	def show_select_savegame(self, mode, sanity_checker=None, sanity_criteria=None):
		"""Shows menu to select a savegame.
		@param mode: Valid options are 'save', 'load', 'mp_load', 'mp_save'
		@param sanity_checker: only allow manually entered names that pass this test
		@param sanity_criteria: explain which names are allowed to the user
		@return: Path to savegamefile or None"""
		assert mode in ('save', 'load', 'mp_load', 'mp_save')
		map_files, map_file_display = None, None
		args = mode, sanity_checker, sanity_criteria # for reshow
		mp = mode.startswith('mp_')
		if mp:
			mode = mode[3:]
		# below this line, mp_load == load, mp_save == save
		if mode == 'load':
			if not mp:
				map_files, map_file_display = SavegameManager.get_saves()
			else:
				map_files, map_file_display = SavegameManager.get_multiplayersaves()
			if not map_files:
				self.show_popup(_("No saved games"), _("There are no saved games to load."))
				return
		else: # don't show autosave and quicksave on save
			if not mp:
				map_files, map_file_display = SavegameManager.get_regular_saves()
			else:
				map_files, map_file_display = SavegameManager.get_multiplayersaves()

		# Prepare widget
		old_current = self._switch_current_widget('select_savegame')
		if mode == 'save':
			helptext = _('Save game')
		elif mode == 'load':
			helptext = _('Load game')
		# else: not a valid mode, so we can as well crash on the following
		self.current.findChild(name='headline').text = helptext
		self.current.findChild(name=OkButton.DEFAULT_NAME).helptext = helptext

		name_box = self.current.findChild(name="gamename_box")
		password_box = self.current.findChild(name="gamepassword_box")
		if mp and mode == 'load': # have gamename
			name_box.parent.showChild(name_box)
			password_box.parent.showChild(password_box)
			gamename_textfield = self.current.findChild(name="gamename")
			gamepassword_textfield = self.current.findChild(name="gamepassword")
			gamepassword_textfield.text = u""
			def clear_gamedetails_textfields():
				gamename_textfield.text = u""
				gamepassword_textfield.text = u""
			gamename_textfield.capture(clear_gamedetails_textfields, 'mouseReleased', 'default')
		else:
			if name_box not in name_box.parent.hidden_children:
				name_box.parent.hideChild(name_box)
			if password_box not in name_box.parent.hidden_children:
				password_box.parent.hideChild(password_box)

		self.current.show()

		if not hasattr(self, 'filename_hbox'):
			self.filename_hbox = self.current.findChild(name='enter_filename')
			self.filename_hbox_parent = self.filename_hbox.parent

		if mode == 'save': # only show enter_filename on save
			self.filename_hbox_parent.showChild(self.filename_hbox)
		elif self.filename_hbox not in self.filename_hbox_parent.hidden_children:
			self.filename_hbox_parent.hideChild(self.filename_hbox)

		def tmp_selected_changed():
			"""Fills in the name of the savegame in the textbox when selected in the list"""
			if mode != 'save': # set textbox only if we are in save mode
				return
			if self.current.collectData('savegamelist') == -1: # set blank if nothing is selected
				self.current.findChild(name="savegamefile").text = u""
			else:
				savegamefile = map_file_display[self.current.collectData('savegamelist')]
				self.current.distributeData({'savegamefile': savegamefile})

		self.current.distributeInitialData({'savegamelist': map_file_display})
		# Select first item when loading, nothing when saving
		selected_item = -1 if mode == 'save' else 0
		self.current.distributeData({'savegamelist': selected_item})
		cb_details = Gui._create_show_savegame_details(self.current, map_files, 'savegamelist')
		cb = Callback.ChainedCallbacks(cb_details, tmp_selected_changed)
		cb() # Refresh data on start
		self.current.mapEvents({'savegamelist/action': cb})
		self.current.findChild(name="savegamelist").capture(cb, event_name="keyPressed")

		bind = {
			OkButton.DEFAULT_NAME     : True,
			CancelButton.DEFAULT_NAME : False,
			DeleteButton.DEFAULT_NAME : 'delete'
		}

		if mode == 'save':
			bind['savegamefile'] = True

		retval = self.show_dialog(self.current, bind)
		if not retval: # cancelled
			self.current = old_current
			return

		if retval == 'delete':
			# delete button was pressed. Apply delete and reshow dialog, delegating the return value
			delete_retval = self._delete_savegame(map_files)
			if delete_retval:
				self.current.distributeData({'savegamelist' : -1})
				cb()
			self.current = old_current
			return self.show_select_savegame(*args)

		selected_savegame = None
		if mode == 'save': # return from textfield
			selected_savegame = self.current.collectData('savegamefile')
			if selected_savegame == "":
				self.show_error_popup(windowtitle=_("No filename given"),
				                      description=_("Please enter a valid filename."))
				self.current = old_current
				return self.show_select_savegame(*args) # reshow dialog
			elif selected_savegame in map_file_display: # savegamename already exists
				#xgettext:python-format
				message = _("A savegame with the name '{name}' already exists.").format(
				             name=selected_savegame) + u"\n" + _('Overwrite it?')
				# keep the pop-up non-modal because otherwise it is double-modal (#1876)
				if not self.show_popup(_("Confirmation for overwriting"), message, show_cancel_button=True, modal=False):
					self.current = old_current
					return self.show_select_savegame(*args) # reshow dialog
			elif sanity_checker and sanity_criteria:
				if not sanity_checker(selected_savegame):
					self.show_error_popup(windowtitle=_("Invalid filename given"),
					                      description=sanity_criteria)
					self.current = old_current
					return self.show_select_savegame(*args) # reshow dialog
		else: # return selected item from list
			selected_savegame = self.current.collectData('savegamelist')
			assert selected_savegame != -1, "No savegame selected in savegamelist"
			selected_savegame = map_files[selected_savegame]

		if mp and mode == 'load': # also name
			gamename_textfield = self.current.findChild(name="gamename")
			ret = selected_savegame, self.current.collectData('gamename'), self.current.collectData('gamepassword')
		else:
			ret = selected_savegame
		self.current = old_current # reuse old widget
		return ret
Ejemplo n.º 15
0
    def __init__(self, session):
        super(IngameGui, self).__init__()
        self.session = session
        assert isinstance(self.session, horizons.session.Session)
        self.settlement = None
        self._old_menu = None

        self.cursor = None
        self.coordinates_tooltip = None

        self.keylistener = IngameKeyListener(self.session)

        self.cityinfo = CityInfo(self)
        LastActivePlayerSettlementManager.create_instance(self.session)

        self.message_widget = MessageWidget(self.session)

        # Windows
        self.windows = WindowManager()
        self.open_popup = self.windows.open_popup
        self.open_error_popup = self.windows.open_error_popup

        self.logbook = LogBook(self.session, self.windows)
        self.players_overview = PlayersOverview(self.session)
        self.players_settlements = PlayersSettlements(self.session)
        self.players_ships = PlayersShips(self.session)

        self.chat_dialog = ChatDialog(self.windows, self.session)
        self.change_name_dialog = ChangeNameDialog(self.windows, self.session)
        self.pausemenu = PauseMenu(self.session,
                                   self,
                                   self.windows,
                                   in_editor_mode=False)
        self.help_dialog = HelpDialog(self.windows)

        # Icon manager
        self.status_icon_manager = StatusIconManager(
            renderer=self.session.view.renderer['GenericRenderer'],
            layer=self.session.view.layers[LAYERS.OBJECTS])
        self.production_finished_icon_manager = ProductionFinishedIconManager(
            renderer=self.session.view.renderer['GenericRenderer'],
            layer=self.session.view.layers[LAYERS.OBJECTS])

        # 'minimap' is the guichan gui around the actual minimap, which is saved
        # in self.minimap
        self.mainhud = load_uh_widget('minimap.xml')
        self.mainhud.position_technique = "right:top"

        icon = self.mainhud.findChild(name="minimap")
        self.minimap = Minimap(
            icon,
            targetrenderer=horizons.globals.fife.targetrenderer,
            imagemanager=horizons.globals.fife.imagemanager,
            session=self.session,
            view=self.session.view)

        def speed_up():
            SpeedUpCommand().execute(self.session)

        def speed_down():
            SpeedDownCommand().execute(self.session)

        self.mainhud.mapEvents({
            'zoomIn':
            self.session.view.zoom_in,
            'zoomOut':
            self.session.view.zoom_out,
            'rotateRight':
            Callback.ChainedCallbacks(self.session.view.rotate_right,
                                      self.minimap.rotate_right),
            'rotateLeft':
            Callback.ChainedCallbacks(self.session.view.rotate_left,
                                      self.minimap.rotate_left),
            'speedUp':
            speed_up,
            'speedDown':
            speed_down,
            'destroy_tool':
            self.toggle_destroy_tool,
            'build':
            self.show_build_menu,
            'diplomacyButton':
            self.show_diplomacy_menu,
            'gameMenuButton':
            self.toggle_pause,
            'logbook':
            lambda: self.windows.toggle(self.logbook)
        })
        self.mainhud.show()

        hotkey_replacements = {
            'rotateRight': 'ROTATE_RIGHT',
            'rotateLeft': 'ROTATE_LEFT',
            'speedUp': 'SPEED_UP',
            'speedDown': 'SPEED_DOWN',
            'destroy_tool': 'DESTROY_TOOL',
            'build': 'BUILD_TOOL',
            'gameMenuButton': 'ESCAPE',
            'logbook': 'LOGBOOK',
        }
        for (widgetname, action) in hotkey_replacements.iteritems():
            widget = self.mainhud.findChild(name=widgetname)
            keys = horizons.globals.fife.get_keys_for_action(action)
            # No `.upper()` here: "Pause" looks better than "PAUSE".
            keyname = HOTKEYS.DISPLAY_KEY.get(keys[0], keys[0].capitalize())
            widget.helptext = widget.helptext.format(key=keyname)

        self.resource_overview = ResourceOverviewBar(self.session)

        # Register for messages
        SpeedChanged.subscribe(self._on_speed_changed)
        NewDisaster.subscribe(self._on_new_disaster)
        NewSettlement.subscribe(self._on_new_settlement)
        PlayerLevelUpgrade.subscribe(self._on_player_level_upgrade)
        MineEmpty.subscribe(self._on_mine_empty)
        ZoomChanged.subscribe(self._update_zoom)

        self._display_speed(self.session.timer.ticks_per_second)