Beispiel #1
0
def _load_map(savegamename):
	"""Load a map specified by user
	@return: bool, whether loading succeded"""
	saves = SavegameManager.get_saves()
	map_file = None
	for i in xrange(0, len(saves[1])):
		# exact match
		if saves[1][i] == savegamename:
			map_file = saves[0][i]
			break
		# check for partial match
		if saves[1][i].startswith(savegamename):
			if map_file is not None:
				# multiple matches, collect all for output
				map_file += u'\n' + saves[0][i]
			else:
				map_file = saves[0][i]
	if map_file is None:
		print _("Error: Cannot find savegame \"%s\".") % savegamename
		return False
	if len(map_file.splitlines()) > 1:
		print _("Error: Found multiple matches: ")
		for match in map_file.splitlines():
			print os.path.basename(match)
		return False
	load_game(map_file)
	return True
def _load_map(savegamename):
    """Load a map specified by user
	@return: bool, whether loading succeded"""
    saves = SavegameManager.get_saves()
    map_file = None
    for i in xrange(0, len(saves[1])):
        # exact match
        if saves[1][i] == savegamename:
            map_file = saves[0][i]
            break
        # check for partial match
        if saves[1][i].startswith(savegamename):
            if map_file is not None:
                # multiple matches, collect all for output
                map_file += u'\n' + saves[0][i]
            else:
                map_file = saves[0][i]
    if map_file is None:
        print _("Error: Cannot find savegame \"%s\".") % savegamename
        return False
    if len(map_file.splitlines()) > 1:
        print _("Error: Found multiple matches: ")
        for match in map_file.splitlines():
            print os.path.basename(match)
        return False
    load_game(map_file)
    return True
Beispiel #3
0
def _load_map(savegame, ai_players, human_ai, force_player_id=None):
	"""Load a map specified by user.
	@param savegame: eiter the displayname of a savegame or a path to a savegame
	@return: bool, whether loading succeded"""
	# first check for partial or exact matches in the normal savegame list
	saves = SavegameManager.get_saves()
	map_file = None
	for i in xrange(0, len(saves[1])):
		# exact match
		if saves[1][i] == savegame:
			map_file = saves[0][i]
			break
		# check for partial match
		if saves[1][i].startswith(savegame):
			if map_file is not None:
				# multiple matches, collect all for output
				map_file += u'\n' + saves[0][i]
			else:
				map_file = saves[0][i]
	if map_file is None:
		# not a savegame, check for path to file or fail
		if os.path.exists(savegame):
			map_file = savegame
		else:
			#xgettext:python-format
			print u"Error: Cannot find savegame '{name}'.".format(name=savegame)
			return False
	if len(map_file.splitlines()) > 1:
		print "Error: Found multiple matches:"
		for match in map_file.splitlines():
			print os.path.basename(match)
		return False
	load_game(savegame=map_file, force_player_id=force_player_id)
	return True
def _load_map(savegame, ai_players, human_ai, force_player_id=None):
	"""Load a map specified by user.
	@param savegame: either the displayname of a savegame or a path to a savegame
	@return: bool, whether loading succeded"""
	# first check for partial or exact matches in the normal savegame list
	savegames = SavegameManager.get_saves()
	map_file = _find_matching_map(savegame, savegames)
	if not map_file:
		return False
	load_game(savegame=map_file, force_player_id=force_player_id)
	return True
    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
Beispiel #6
0
def _load_cmd_map(savegame, ai_players, force_player_id=None):
	"""Load a map specified by user.
	@param savegame: either the displayname of a savegame or a path to a savegame
	@return: bool, whether loading succeeded"""
	# first check for partial or exact matches in the normal savegame list
	savegames = SavegameManager.get_saves()
	map_file = _find_map(savegame, savegames)
	if not map_file:
		return False

	options = StartGameOptions.create_load_game(map_file, force_player_id)
	start_singleplayer(options)
	return True
Beispiel #7
0
def _load_cmd_map(savegame, ai_players, force_player_id=None):
	"""Load a map specified by user.
	@param savegame: either the displayname of a savegame or a path to a savegame
	@return: bool, whether loading succeeded"""
	# first check for partial or exact matches in the normal savegame list
	savegames = SavegameManager.get_saves()
	map_file = _find_matching_map(savegame, savegames)
	if not map_file:
		return False

	options = StartGameOptions.create_load_game(map_file, force_player_id)
	start_singleplayer(options)
	return True
Beispiel #8
0
def edit_game_map(saved_game_name):
	"""
	Start editing the specified map.

	@param map_name: name of map or path to map
	@return: bool, whether loading succeeded
	"""
	saved_games = SavegameManager.get_saves()
	saved_game_path = _find_matching_map(saved_game_name, saved_games)
	if not saved_game_path:
		return False

	accessor = SavegameAccessor(saved_game_path, False)
	map_name = accessor.map_name
	accessor.close()
	if isinstance(map_name, list):
		# a random map represented by a list of island strings
		return _edit_map(map_name)
	return edit_map(map_name)
Beispiel #9
0
def edit_game_map(saved_game_name):
	"""
	Start editing the specified map.

	@param map_name: name of map or path to map
	@return: bool, whether loading succeeded
	"""
	saved_games = SavegameManager.get_saves()
	saved_game_path = _find_map(saved_game_name, saved_games)
	if not saved_game_path:
		return False

	accessor = SavegameAccessor(saved_game_path, False)
	map_name = accessor.map_name
	accessor.close()
	if isinstance(map_name, list):
		# a random map represented by a list of island strings
		return _edit_map(map_name)
	return edit_map(map_name)
	def prepare(self):
		if self._mode == 'load':
			self._map_files, self._map_file_display = SavegameManager.get_saves()
			if not self._map_files:
				self._windows.show_popup(_("No saved games"), _("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
Beispiel #11
0
	def show_select_savegame(self, mode):
		"""Shows menu to select a savegame.
		@param mode: 'save' or 'load'
		@return: Path to savegamefile or None"""
		assert mode in ('save', 'load')
		map_files, map_file_display = None, None
		if mode == 'load':
			map_files, map_file_display = SavegameManager.get_saves()
			if len(map_files) == 0:
				self.show_popup(_("No saved games"), _("There are no saved games to load"))
				return
		else: # don't show autosave and quicksave on save
			map_files, map_file_display = SavegameManager.get_regular_saves()

		# Prepare widget
		old_current = self._switch_current_widget('select_savegame')
		self.current.findChild(name='headline').text = _('Save game') if mode == 'save' else _('Load game')

		""" this doesn't work (yet), see http://fife.trac.cvsdude.com/engine/ticket/375
		if mode == 'save': # only show enter_filename on save
			self.current.findChild(name='enter_filename').show()
		else:
			self.current.findChild(name='enter_filename').hide()
		"""

		def tmp_selected_changed():
			"""Fills in the name of the savegame in the textbox when selected in the list"""
			if self.current.collectData('savegamelist') != -1: # check if we actually collect valid data
				self.current.distributeData({'savegamefile' : \
				                             map_file_display[self.current.collectData('savegamelist')]})

		self.current.distributeInitialData({'savegamelist' : map_file_display})
		cb = Callback.ChainedCallbacks(Gui._create_show_savegame_details(self.current, map_files, 'savegamelist'), \
		                               tmp_selected_changed)
		self.current.findChild(name="savegamelist").mapEvents({
		    'savegamelist/action'              : cb,
		    'savegamelist/mouseWheelMovedUp'   : cb,
		    'savegamelist/mouseWheelMovedDown' : cb
		})
		self.current.findChild(name="savegamelist").capture(cb, event_name="keyPressed")

		retval = self.show_dialog(self.current, {
		                                          'okButton'     : True,
		                                          'cancelButton' : False,
		                                          'deleteButton' : 'delete',
		                                          'savegamefile' : True
		                                        },
		                                        onPressEscape = False)
		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
			self._delete_savegame(map_files)
			self.current = old_current
			return self.show_select_savegame(mode=mode)

		selected_savegame = None
		if mode == 'save': # return from textfield
			selected_savegame = self.current.collectData('savegamefile')
			if selected_savegame in map_file_display: # savegamename already exists
				message = _("A savegame with the name \"%s\" already exists. \nShould i overwrite it?") % selected_savegame
				if not self.show_popup(_("Confirmation for overwriting"),message,show_cancel_button = True):
					self.current = old_current
					return self.show_select_savegame(mode=mode) # reshow dialog
		else: # return selected item from list
			selected_savegame = self.current.collectData('savegamelist')
			selected_savegame = None if selected_savegame == -1 else map_files[selected_savegame]
			if selected_savegame is None:
				# ok button has been pressed, but no savegame was selected
				self.show_popup(_("Select a savegame"), _("Please select a savegame or click on cancel."));
				return self.show_select_savegame(mode=mode) # reshow dialog
		self.current = old_current # reuse old widget
		return selected_savegame
Beispiel #12
0
	def show_select_savegame(self, mode, sanity_checker=None, sanity_criteria=None):
		"""Shows menu to select a savegame.
		@param mode: 'save', 'load' or 'mp_load'
		@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
		mp = False
		args = mode, sanity_checker, sanity_criteria # for reshow
		if mode.startswith('mp'):
			mode = mode[3:]
			mp = True
			# 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 len(map_files) == 0:
				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')
		self.current.findChild(name='headline').text = _('Save game') if mode == 'save' else _('Load game')
		self.current.findChild(name=OkButton.DEFAULT_NAME).helptext = _('Save game') if mode == 'save' else _('Load game')

		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._getParent()

		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
				if self.current.collectData('savegamelist') == -1: # set blank if nothing is selected
					self.current.findChild(name="savegamefile").text = u""
				else:
					self.current.distributeData({'savegamefile' : \
				                             map_file_display[self.current.collectData('savegamelist')]})

		self.current.distributeInitialData({'savegamelist' : map_file_display})
		self.current.distributeData({'savegamelist' : -1}) # Don't select anything by default
		cb = Callback.ChainedCallbacks(Gui._create_show_savegame_details(self.current, map_files, 'savegamelist'), \
		                               tmp_selected_changed)
		cb() # Refresh data on start
		self.current.findChild(name="savegamelist").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?')
				if not self.show_popup(_("Confirmation for overwriting"), message, show_cancel_button=True):
					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')
			selected_savegame = None if selected_savegame == -1 else map_files[selected_savegame]
			if selected_savegame is None:
				# ok button has been pressed, but no savegame was selected
				self.show_popup(_("Select a savegame"), _("Please select a savegame or click on cancel."))
				self.current = old_current
				return self.show_select_savegame(*args) # reshow dialog

		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
Beispiel #13
0
 def show(self):
     self._saved_game_data = SavegameManager.get_saves()
     self._gui.distributeInitialData(
         {'saved_game_list': self._saved_game_data[1]})
     self._parent_widget.removeAllChildren()
     self._parent_widget.addChild(self._gui)
Beispiel #14
0
	def show_select_savegame(self, mode):
		"""Shows menu to select a savegame.
		@param mode: 'save' or 'load'
		@return: Path to savegamefile or None"""
		assert mode in ('save', 'load')
		map_files, map_file_display = None, None
		if mode == 'load':
			map_files, map_file_display = SavegameManager.get_saves()
			if len(map_files) == 0:
				self.show_popup(_("No saved games"), _("There are no saved games to load"))
				return
		else: # don't show autosave and quicksave on save
			map_files, map_file_display = SavegameManager.get_regular_saves()

		# Prepare widget
		old_current = self._switch_current_widget('select_savegame')
		self.current.findChild(name='headline').text = _('Save game') if mode == 'save' else _('Load game')

		""" this doesn't work (yet), see http://fife.trac.cvsdude.com/engine/ticket/375
		if mode == 'save': # only show enter_filename on save
			self.current.findChild(name='enter_filename').show()
		else:
			self.current.findChild(name='enter_filename').hide()
		"""

		def tmp_selected_changed():
			"""Fills in the name of the savegame in the textbox when selected in the list"""
			if self.current.collectData('savegamelist') != -1: # Check if it actually collected valid data
				self.current.distributeData({'savegamefile' : \
				                             map_file_display[self.current.collectData('savegamelist')]})

		self.current.distributeInitialData({'savegamelist' : map_file_display})
		self.current.findChild(name="savegamelist").capture( Callback.ChainedCallbacks( \
		  Gui._create_show_savegame_details(self.current, map_files, 'savegamelist'), \
		  tmp_selected_changed))

		retval = self.show_dialog(self.current, \
		                        {'okButton': True, 'cancelButton': False, 'deleteButton': 'delete', 'savegamefile' : True},
														onPressEscape = False)

		if not retval: # canceled
			self.current = old_current
			return

		if retval == 'delete':
			# delete button was pressed. Apply delete and reshow dialog, delegating the return value
			self._delete_savegame(map_files)
			self.current = old_current
			return self.show_select_savegame(mode=mode)

		selected_savegame = None
		if mode == 'save': # return from textfield
			selected_savegame = self.current.collectData('savegamefile')
			if selected_savegame in map_file_display: # savegamename already exists
				if not self.show_popup(_("Confirmation for overwriting"), \
				      _("A savegame with the name \"%s\" already exists. \nShould i overwrite it?") % \
				      selected_savegame, show_cancel_button = True):
					self.current = old_current
					return self.show_select_savegame(mode=mode) # reshow dialog
		else: # return selected item from list
			selected_savegame = self.current.collectData('savegamelist')
			selected_savegame = None if selected_savegame == -1 else map_files[selected_savegame]
		self.current = old_current # reuse old widget
		return selected_savegame
Beispiel #15
0
    def show_select_savegame(self, mode):
        """Shows menu to select a savegame.
		@param mode: 'save' or 'load'
		@return: Path to savegamefile or None"""
        assert mode in ("save", "load")
        map_files, map_file_display = None, None
        if mode == "load":
            map_files, map_file_display = SavegameManager.get_saves()
            if len(map_files) == 0:
                self.show_popup(_("No saved games"), _("There are no saved games to load"))
                return
        else:  # don't show autosave and quicksave on save
            map_files, map_file_display = SavegameManager.get_regular_saves()

            # Prepare widget
        old_current = self._switch_current_widget("select_savegame")
        self.current.findChild(name="headline").text = _("Save game") if mode == "save" else _("Load game")

        """ this doesn't work (yet), see http://fife.trac.cvsdude.com/engine/ticket/375
		if mode == 'save': # only show enter_filename on save
			self.current.findChild(name='enter_filename').show()
		else:
			self.current.findChild(name='enter_filename').hide()
		"""

        def tmp_selected_changed():
            """Fills in the name of the savegame in the textbox when selected in the list"""
            if self.current.collectData("savegamelist") != -1:  # check if we actually collect valid data
                self.current.distributeData(
                    {"savegamefile": map_file_display[self.current.collectData("savegamelist")]}
                )

        self.current.distributeInitialData({"savegamelist": map_file_display})
        cb = Callback.ChainedCallbacks(
            Gui._create_show_savegame_details(self.current, map_files, "savegamelist"), tmp_selected_changed
        )
        self.current.findChild(name="savegamelist").mapEvents(
            {"savegamelist/action": cb, "savegamelist/mouseWheelMovedUp": cb, "savegamelist/mouseWheelMovedDown": cb}
        )
        self.current.findChild(name="savegamelist").capture(cb, event_name="keyPressed")

        retval = self.show_dialog(
            self.current,
            {"okButton": True, "cancelButton": False, "deleteButton": "delete", "savegamefile": True},
            onPressEscape=False,
        )
        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
            self._delete_savegame(map_files)
            self.current = old_current
            return self.show_select_savegame(mode=mode)

        selected_savegame = None
        if mode == "save":  # return from textfield
            selected_savegame = self.current.collectData("savegamefile")
            if selected_savegame in map_file_display:  # savegamename already exists
                message = (
                    _('A savegame with the name "%s" already exists. \nShould i overwrite it?') % selected_savegame
                )
                if not self.show_popup(_("Confirmation for overwriting"), message, show_cancel_button=True):
                    self.current = old_current
                    return self.show_select_savegame(mode=mode)  # reshow dialog
        else:  # return selected item from list
            selected_savegame = self.current.collectData("savegamelist")
            selected_savegame = None if selected_savegame == -1 else map_files[selected_savegame]
            if selected_savegame is None:
                # ok button has been pressed, but no savegame was selected
                self.show_popup(_("Select a savegame"), _("Please select a savegame or click on cancel."))
                self.current = old_current
                return self.show_select_savegame(mode=mode)  # reshow dialog
        self.current = old_current  # reuse old widget
        return selected_savegame
Beispiel #16
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
Beispiel #17
0
	def show_select_savegame(self, mode):
		"""Shows menu to select a savegame.
		@param mode: 'save' or 'load'
		@return: Path to savegamefile or None"""
		assert mode in ('save', 'load')
		map_files, map_file_display = None, None
		if mode == 'load':
			map_files, map_file_display = SavegameManager.get_saves()
			if len(map_files) == 0:
				self.show_popup(_("No saved games"), _("There are no saved games to load."))
				return
		else: # don't show autosave and quicksave on save
			map_files, map_file_display = SavegameManager.get_regular_saves()

		# Prepare widget
		old_current = self._switch_current_widget('select_savegame')
		self.current.findChild(name='headline').text = _('Save game') if mode == 'save' else _('Load game')
		self.current.findChild(name='okButton').tooltip = _('Save game') if mode == 'save' else _('Load game')

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

		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
				if self.current.collectData('savegamelist') == -1: # set blank if nothing is selected
					self.current.findChild(name="savegamefile").text = u""
				else:
					self.current.distributeData({'savegamefile' : \
				                             map_file_display[self.current.collectData('savegamelist')]})

		self.current.distributeInitialData({'savegamelist' : map_file_display})
		self.current.distributeData({'savegamelist' : -1}) # Don't select anything by default
		cb = Callback.ChainedCallbacks(Gui._create_show_savegame_details(self.current, map_files, 'savegamelist'), \
		                               tmp_selected_changed)
		cb() # Refresh data on start
		self.current.findChild(name="savegamelist").mapEvents({
		    'savegamelist/action'              : cb,
		    'savegamelist/mouseWheelMovedUp'   : cb,
		    'savegamelist/mouseWheelMovedDown' : cb
		})
		self.current.findChild(name="savegamelist").capture(cb, event_name="keyPressed")

		eventMap = {
			'okButton'     : True,
			'cancelButton' : False,
			'deleteButton' : 'delete'
		}

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

		retval = self.show_dialog(self.current, eventMap, onPressEscape = False)
		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(mode=mode)

		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(mode=mode) # 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?')
				if not self.show_popup(_("Confirmation for overwriting"), message, show_cancel_button = True):
					self.current = old_current
					return self.show_select_savegame(mode=mode) # reshow dialog
		else: # return selected item from list
			selected_savegame = self.current.collectData('savegamelist')
			selected_savegame = None if selected_savegame == -1 else map_files[selected_savegame]
			if selected_savegame is None:
				# ok button has been pressed, but no savegame was selected
				self.show_popup(_("Select a savegame"), _("Please select a savegame or click on cancel."))
				self.current = old_current
				return self.show_select_savegame(mode=mode) # reshow dialog
		self.current = old_current # reuse old widget
		return selected_savegame
	def show(self):
		self._saved_game_data = SavegameManager.get_saves()
		self._gui.distributeInitialData({'saved_game_list': self._saved_game_data[1]})
		self._parent_widget.removeAllChildren()
		self._parent_widget.addChild(self._gui)
Beispiel #19
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