Exception handling cleanup

This commit is contained in:
Eric Froemling 2020-06-16 20:29:03 -07:00
parent 414afe598d
commit 0fdc5f1fc4
55 changed files with 214 additions and 299 deletions

View File

@ -4135,16 +4135,16 @@
"assets/build/windows/x64/vc_redist.x64.exe": "https://files.ballistica.net/cache/ba1/ea/19/8b8787d81abcdce158ba608cd24f", "assets/build/windows/x64/vc_redist.x64.exe": "https://files.ballistica.net/cache/ba1/ea/19/8b8787d81abcdce158ba608cd24f",
"assets/build/windows/x64/vcruntime140_1d.dll": "https://files.ballistica.net/cache/ba1/11/d8/ff6344b429b00c24d9a1930d4338", "assets/build/windows/x64/vcruntime140_1d.dll": "https://files.ballistica.net/cache/ba1/11/d8/ff6344b429b00c24d9a1930d4338",
"assets/build/windows/x64/vcruntime140d.dll": "https://files.ballistica.net/cache/ba1/20/33/0825e11e6518f87ece3009309933", "assets/build/windows/x64/vcruntime140d.dll": "https://files.ballistica.net/cache/ba1/20/33/0825e11e6518f87ece3009309933",
"build/prefab/linux-server/debug/dist/ballisticacore_headless": "https://files.ballistica.net/cache/ba1/59/6a/634ef384e18384fa78b7a2a624f8", "build/prefab/linux-server/debug/dist/ballisticacore_headless": "https://files.ballistica.net/cache/ba1/29/9c/24a918c046b06f010d9948458a09",
"build/prefab/linux-server/release/dist/ballisticacore_headless": "https://files.ballistica.net/cache/ba1/d6/1b/165df7c0c0c21761cba641640d4d", "build/prefab/linux-server/release/dist/ballisticacore_headless": "https://files.ballistica.net/cache/ba1/2e/1c/2285cc92d83ce3a32b26c020cb71",
"build/prefab/linux/debug/ballisticacore": "https://files.ballistica.net/cache/ba1/e3/8b/b1770e7c2ade5a6f538260acae4d", "build/prefab/linux/debug/ballisticacore": "https://files.ballistica.net/cache/ba1/24/b6/9410d8cf8be5aaf2ffad07964950",
"build/prefab/linux/release/ballisticacore": "https://files.ballistica.net/cache/ba1/9f/c1/7ad792405a744d9f2fa4cf682d4b", "build/prefab/linux/release/ballisticacore": "https://files.ballistica.net/cache/ba1/48/c4/2bdd6802858b92c348df702c9dcd",
"build/prefab/mac-server/debug/dist/ballisticacore_headless": "https://files.ballistica.net/cache/ba1/a5/d5/d9ed741473501d1a1541d5c100df", "build/prefab/mac-server/debug/dist/ballisticacore_headless": "https://files.ballistica.net/cache/ba1/b4/ca/0a1426dabc53a9f90a6beb011423",
"build/prefab/mac-server/release/dist/ballisticacore_headless": "https://files.ballistica.net/cache/ba1/10/e5/70bde6663088d44e126ec91cfaae", "build/prefab/mac-server/release/dist/ballisticacore_headless": "https://files.ballistica.net/cache/ba1/f8/ef/4186b927c2675c3e4dfa19ba180d",
"build/prefab/mac/debug/ballisticacore": "https://files.ballistica.net/cache/ba1/88/6c/b4eb60746d994cddd19813faee85", "build/prefab/mac/debug/ballisticacore": "https://files.ballistica.net/cache/ba1/29/59/60175945534d87709dfc29d1b180",
"build/prefab/mac/release/ballisticacore": "https://files.ballistica.net/cache/ba1/17/31/dff0defb0cc64a80d5068ed97930", "build/prefab/mac/release/ballisticacore": "https://files.ballistica.net/cache/ba1/5c/b8/16b868c1bbd8b1be2ebaf4da4d31",
"build/prefab/windows-server/debug/dist/ballisticacore_headless.exe": "https://files.ballistica.net/cache/ba1/02/b0/83ec7dc92ec4e5b75a9d9a058cda", "build/prefab/windows-server/debug/dist/ballisticacore_headless.exe": "https://files.ballistica.net/cache/ba1/30/6c/33b6b194062212beeae3043515a3",
"build/prefab/windows-server/release/dist/ballisticacore_headless.exe": "https://files.ballistica.net/cache/ba1/aa/1e/bfcf2f01ae72a897333a4e4137b5", "build/prefab/windows-server/release/dist/ballisticacore_headless.exe": "https://files.ballistica.net/cache/ba1/4b/24/c54be077112185f6a3d2c67641ea",
"build/prefab/windows/debug/BallisticaCore.exe": "https://files.ballistica.net/cache/ba1/cc/ec/50508b196f190b4a4b137d4aaf9c", "build/prefab/windows/debug/BallisticaCore.exe": "https://files.ballistica.net/cache/ba1/ee/6e/a9d59e81b549b992673d20f84f11",
"build/prefab/windows/release/BallisticaCore.exe": "https://files.ballistica.net/cache/ba1/94/71/340f38cdbbcad105395733b9e556" "build/prefab/windows/release/BallisticaCore.exe": "https://files.ballistica.net/cache/ba1/5b/73/97159eb1d7dfb4018c5a1241f164"
} }

View File

@ -572,6 +572,7 @@
<w>ensurepip</w> <w>ensurepip</w>
<w>entitylist</w> <w>entitylist</w>
<w>entrynew</w> <w>entrynew</w>
<w>entrystorename</w>
<w>entrytype</w> <w>entrytype</w>
<w>entrytypeselect</w> <w>entrytypeselect</w>
<w>enumtype</w> <w>enumtype</w>
@ -1306,6 +1307,7 @@
<w>ntriple</w> <w>ntriple</w>
<w>nturl</w> <w>nturl</w>
<w>numedit</w> <w>numedit</w>
<w>numsound</w>
<w>numstr</w> <w>numstr</w>
<w>nvcompress</w> <w>nvcompress</w>
<w>nvidia</w> <w>nvidia</w>

View File

@ -422,8 +422,8 @@ def test_depset() -> None:
if dep.cls is AssetPackage: if dep.cls is AssetPackage:
print('MISSING ASSET PACKAGE', dep.config) print('MISSING ASSET PACKAGE', dep.config)
else: else:
raise Exception('unknown dependency error for ' + raise RuntimeError(
str(dep.cls)) f'Unknown dependency error for {dep.cls}') from exc
except Exception as exc: except Exception as exc:
print('DependencySet resolve failed with exc type:', type(exc)) print('DependencySet resolve failed with exc type:', type(exc))
if depset.resolved: if depset.resolved:

View File

@ -337,7 +337,7 @@ def _verify_object_death(wref: ReferenceType) -> None:
i += 1 i += 1
def storagename(basename: str) -> str: def storagename(suffix: str = None) -> str:
"""Generate a (hopefully) unique name for storing things in public places. """Generate a (hopefully) unique name for storing things in public places.
Category: General Utility Functions Category: General Utility Functions
@ -371,7 +371,9 @@ def storagename(basename: str) -> str:
qualname = fback.f_locals.get('__qualname__') qualname = fback.f_locals.get('__qualname__')
if qualname is not None: if qualname is not None:
assert isinstance(qualname, str) assert isinstance(qualname, str)
fullpath = f'_{modulepath}_{qualname.lower()}_{basename}' fullpath = f'_{modulepath}_{qualname.lower()}'
else: else:
fullpath = f'_{modulepath}_{basename}' fullpath = f'_{modulepath}'
if suffix is not None:
fullpath = f'{fullpath}_{suffix}'
return fullpath.replace('.', '_') return fullpath.replace('.', '_')

View File

@ -296,8 +296,8 @@ def _add_to_attr_dict(dst: AttrDict, src: Dict) -> None:
except Exception: except Exception:
dst_dict = dst[key] = AttrDict() dst_dict = dst[key] = AttrDict()
if not isinstance(dst_dict, AttrDict): if not isinstance(dst_dict, AttrDict):
raise Exception("language key '" + key + raise RuntimeError("language key '" + key +
"' is defined both as a dict and value") "' is defined both as a dict and value")
_add_to_attr_dict(dst_dict, value) _add_to_attr_dict(dst_dict, value)
else: else:
if not isinstance(value, (float, int, bool, str, str, type(None))): if not isinstance(value, (float, int, bool, str, str, type(None))):
@ -404,7 +404,8 @@ def get_resource(resource: str,
from ba import _error from ba import _error
if fallback_value is not None: if fallback_value is not None:
return fallback_value return fallback_value
raise _error.NotFoundError("resource not found: '" + resource + "'") raise _error.NotFoundError(
f"Resource not found: '{resource}'") from None
def translate(category: str, def translate(category: str,

View File

@ -143,9 +143,9 @@ def get_map_class(name: str) -> Type[ba.Map]:
name = get_filtered_map_name(name) name = get_filtered_map_name(name)
try: try:
return _ba.app.maps[name] return _ba.app.maps[name]
except Exception: except KeyError:
from ba import _error from ba import _error
raise _error.NotFoundError("Map not found: '" + name + "'") raise _error.NotFoundError(f"Map not found: '{name}'") from None
class Map(Actor): class Map(Actor):

View File

@ -322,7 +322,6 @@ class CoopScoreScreen(ba.Activity[ba.Player, ba.Team]):
def show_ui(self) -> None: def show_ui(self) -> None:
"""Show the UI for restarting, playing the next Level, etc.""" """Show the UI for restarting, playing the next Level, etc."""
# pylint: disable=too-many-locals # pylint: disable=too-many-locals
# pylint: disable=too-many-statements
from bastd.ui.store.button import StoreButton from bastd.ui.store.button import StoreButton
from bastd.ui.league.rankbutton import LeagueRankButton from bastd.ui.league.rankbutton import LeagueRankButton
@ -330,15 +329,7 @@ class CoopScoreScreen(ba.Activity[ba.Player, ba.Team]):
# If there's no players left in the game, lets not show the UI # If there's no players left in the game, lets not show the UI
# (that would allow restarting the game with zero players, etc). # (that would allow restarting the game with zero players, etc).
if not self.players:
# Hmmm shouldn't need this try/except here i don't think.
try:
players = self.players
except Exception as exc:
print(('EXC bs_coop_game show_ui cant get '
'self.players; shouldn\'t happen:'), exc)
players = []
if not players:
return return
rootc = self._root_ui = ba.containerwidget(size=(0, 0), rootc = self._root_ui = ba.containerwidget(size=(0, 0),
@ -513,7 +504,7 @@ class CoopScoreScreen(ba.Activity[ba.Player, ba.Team]):
self._store_button_instance.set_position((pos_x + 100, pos_y)) self._store_button_instance.set_position((pos_x + 100, pos_y))
def on_begin(self) -> None: def on_begin(self) -> None:
# FIXME: clean this up # FIXME: Clean this up.
# pylint: disable=too-many-statements # pylint: disable=too-many-statements
# pylint: disable=too-many-branches # pylint: disable=too-many-branches
# pylint: disable=too-many-locals # pylint: disable=too-many-locals
@ -661,12 +652,9 @@ class CoopScoreScreen(ba.Activity[ba.Player, ba.Team]):
# Add us to high scores, filter, and store. # Add us to high scores, filter, and store.
our_high_scores_all = self._campaign.getlevel( our_high_scores_all = self._campaign.getlevel(
self._level_name).get_high_scores() self._level_name).get_high_scores()
try:
our_high_scores = our_high_scores_all[str(len(self._playerinfos)) + our_high_scores = our_high_scores_all.setdefault(
' Player'] str(len(self._playerinfos)) + ' Player', [])
except Exception:
our_high_scores = our_high_scores_all[str(len(self._playerinfos)) +
' Player'] = []
if self._score is not None: if self._score is not None:
our_score: Optional[list] = [ our_score: Optional[list] = [
@ -685,8 +673,8 @@ class CoopScoreScreen(ba.Activity[ba.Player, ba.Team]):
our_high_scores.sort(reverse=self._score_order == 'increasing', our_high_scores.sort(reverse=self._score_order == 'increasing',
key=lambda x: x[0]) key=lambda x: x[0])
except Exception: except Exception:
ba.print_exception('Error sorting scores') ba.print_exception('Error sorting scores.')
print('our_high_scores:', our_high_scores) print(f'our_high_scores: {our_high_scores}')
del our_high_scores[10:] del our_high_scores[10:]
@ -809,6 +797,7 @@ class CoopScoreScreen(ba.Activity[ba.Player, ba.Team]):
name_str = ', '.join( name_str = ', '.join(
[p['name'] for p in display_scores[i][1]['players']]) [p['name'] for p in display_scores[i][1]['players']])
except Exception: except Exception:
ba.print_exception('Error calcing name_str')
name_str = '-' name_str = '-'
if display_scores[i] == our_score and not showed_ours: if display_scores[i] == our_score and not showed_ours:
flash = True flash = True
@ -1256,7 +1245,7 @@ class CoopScoreScreen(ba.Activity[ba.Player, ba.Team]):
transition_delay=2.0).autoretain() transition_delay=2.0).autoretain()
vval -= 35 vval -= 35
except Exception: except Exception:
ba.print_exception('error showing prize ranges') ba.print_exception('Error showing prize ranges.')
if self._do_new_rating: if self._do_new_rating:
if error: if error:

View File

@ -98,6 +98,8 @@ class PowerupBoxFactory:
that has this ba.Material applied. that has this ba.Material applied.
""" """
_STORENAME = ba.storagename()
def __init__(self) -> None: def __init__(self) -> None:
"""Instantiate a PowerupBoxFactory. """Instantiate a PowerupBoxFactory.
@ -187,21 +189,17 @@ class PowerupBoxFactory:
self._lastpoweruptype = ptype self._lastpoweruptype = ptype
return ptype return ptype
@staticmethod @classmethod
def get() -> PowerupBoxFactory: def get(cls) -> PowerupBoxFactory:
"""Return a shared ba.PowerupBoxFactory object, creating if needed.""" """Return a shared ba.PowerupBoxFactory object, creating if needed."""
activity = ba.getactivity() activity = ba.getactivity()
if activity is None: if activity is None:
raise RuntimeError('no current activity') raise ba.ContextError('No current activity.')
try: factory = activity.customdata.get(cls._STORENAME)
# FIXME: et better way to store stuff with activity if factory is None:
# pylint: disable=protected-access factory = activity.customdata[cls._STORENAME] = PowerupBoxFactory()
# noinspection PyProtectedMember assert isinstance(factory, PowerupBoxFactory)
return activity._shared_powerup_factory # type: ignore return factory
except Exception:
factory = activity._shared_powerup_factory = ( # type: ignore
PowerupBoxFactory())
return factory
class PowerupBox(ba.Actor): class PowerupBox(ba.Actor):

View File

@ -343,7 +343,7 @@ class Scoreboard:
category: Gameplay Classes category: Gameplay Classes
""" """
_STORENAME = ba.storagename('entry') _ENTRYSTORENAME = ba.storagename('entry')
def __init__(self, label: ba.Lstr = None, score_split: float = 0.7): def __init__(self, label: ba.Lstr = None, score_split: float = 0.7):
"""Instantiate a scoreboard. """Instantiate a scoreboard.
@ -384,8 +384,8 @@ class Scoreboard:
# Create a proxy in the team which will kill # Create a proxy in the team which will kill
# our entry when it dies (for convenience) # our entry when it dies (for convenience)
assert self._STORENAME not in team.customdata assert self._ENTRYSTORENAME not in team.customdata
team.customdata[self._STORENAME] = _EntryProxy(self, team) team.customdata[self._ENTRYSTORENAME] = _EntryProxy(self, team)
# Now set the entry. # Now set the entry.
self._entries[team.id].set_value(score=score, self._entries[team.id].set_value(score=score,

View File

@ -235,11 +235,7 @@ class SpazBot(Spaz):
# towards the flag and try to pick it up. # towards the flag and try to pick it up.
if self.target_flag: if self.target_flag:
if self.node.hold_node: if self.node.hold_node:
try: holding_flag = (self.node.hold_node.getnodetype() == 'flag')
holding_flag = (
self.node.hold_node.getnodetype() == 'flag')
except Exception:
holding_flag = False
else: else:
holding_flag = False holding_flag = False
@ -280,11 +276,8 @@ class SpazBot(Spaz):
# Not a flag-bearer. If we're holding anything but a bomb, drop it. # Not a flag-bearer. If we're holding anything but a bomb, drop it.
if self.node.hold_node: if self.node.hold_node:
try: holding_bomb = (self.node.hold_node.getnodetype()
holding_bomb = (self.node.hold_node.getnodetype() in ['bomb', 'prop'])
in ['bomb', 'prop'])
except Exception:
holding_bomb = False
if not holding_bomb: if not holding_bomb:
self.node.pickup_pressed = True self.node.pickup_pressed = True
self.node.pickup_pressed = False self.node.pickup_pressed = False
@ -532,8 +525,8 @@ class SpazBot(Spaz):
picked_up_by = msg.node.source_player picked_up_by = msg.node.source_player
else: else:
picked_up_by = None picked_up_by = None
except Exception as exc: except Exception:
print('EXC on SpazBot DroppedMessage:', exc) ba.print_exception('Error on SpazBot DroppedMessage.')
picked_up_by = None picked_up_by = None
if picked_up_by: if picked_up_by:
@ -969,7 +962,7 @@ class SpazBotSet:
]) ])
except Exception: except Exception:
bot_list = [] bot_list = []
ba.print_exception('error updating bot list: ' + ba.print_exception('Error updating bot list: ' +
str(self._bot_lists[self._bot_update_list])) str(self._bot_lists[self._bot_update_list]))
self._bot_update_list = (self._bot_update_list + self._bot_update_list = (self._bot_update_list +
1) % self._bot_list_count 1) % self._bot_list_count
@ -988,7 +981,7 @@ class SpazBotSet:
player_pts.append((ba.Vec3(player.actor.node.position), player_pts.append((ba.Vec3(player.actor.node.position),
ba.Vec3(player.actor.node.velocity))) ba.Vec3(player.actor.node.velocity)))
except Exception: except Exception:
ba.print_exception('error on bot-set _update') ba.print_exception('Error on bot-set _update.')
for bot in bot_list: for bot in bot_list:
bot.set_player_points(player_pts) bot.set_player_points(player_pts)

View File

@ -139,12 +139,15 @@ class EasterEggHuntGame(ba.TeamGameActivity[Player, Team]):
if self.has_ended(): if self.has_ended():
return return
collision = ba.getcollision() collision = ba.getcollision()
# Be defensive here; we could be hitting the corpse of a player
# who just left/etc.
try: try:
egg = collision.sourcenode.getdelegate(Egg, True) egg = collision.sourcenode.getdelegate(Egg, True)
player = collision.opposingnode.getdelegate(PlayerSpaz, player = collision.opposingnode.getdelegate(PlayerSpaz,
True).getplayer( True).getplayer(
Player, True) Player, True)
except Exception: except ba.NotFoundError:
return return
player.team.score += 1 player.team.score += 1

View File

@ -653,7 +653,7 @@ class FootballCoopGame(ba.CoopGameActivity[Player, Team]):
assert self._flag is not None assert self._flag is not None
self._flag.handlemessage(ba.DieMessage()) self._flag.handlemessage(ba.DieMessage())
except Exception: except Exception:
ba.print_exception('error in _kill_flag') ba.print_exception('Error in _kill_flag.')
def _handle_score(self) -> None: def _handle_score(self) -> None:
""" a point has been scored """ """ a point has been scored """

View File

@ -208,7 +208,7 @@ class KeepAwayGame(ba.TeamGameActivity[Player, Team]):
holdingflag = ( holdingflag = (
player.actor.node.hold_node.getnodetype() == 'flag') player.actor.node.hold_node.getnodetype() == 'flag')
except Exception: except Exception:
ba.print_exception('exception checking hold flag') ba.print_exception('Error checking hold flag.')
if holdingflag: if holdingflag:
self._holding_players.append(player) self._holding_players.append(player)
player.team.holdingflag = True player.team.holdingflag = True

View File

@ -216,11 +216,9 @@ class KingOfTheHillGame(ba.TeamGameActivity[Player, Team]):
self._flag.set_score_text(str(scoring_team.time_remaining)) self._flag.set_score_text(str(scoring_team.time_remaining))
# Announce numbers we have sounds for. # Announce numbers we have sounds for.
try: numsound = self._countdownsounds.get(scoring_team.time_remaining)
ba.playsound( if numsound is not None:
self._countdownsounds[scoring_team.time_remaining]) ba.playsound(numsound)
except Exception:
pass
# winner # winner
if scoring_team.time_remaining <= 0: if scoring_team.time_remaining <= 0:

View File

@ -1225,25 +1225,21 @@ class OnslaughtGame(ba.CoopGameActivity[Player, Team]):
if msg.killerplayer is not None: if msg.killerplayer is not None:
self._handle_kill_achievements(msg) self._handle_kill_achievements(msg)
target: Optional[Sequence[float]] target: Optional[Sequence[float]]
try: if msg.spazbot.node:
assert msg.spazbot.node
target = msg.spazbot.node.position target = msg.spazbot.node.position
except Exception: else:
ba.print_exception()
target = None target = None
try:
killerplayer = msg.killerplayer killerplayer = msg.killerplayer
self.stats.player_scored(killerplayer, self.stats.player_scored(killerplayer,
pts, pts,
target=target, target=target,
kill=True, kill=True,
screenmessage=False, screenmessage=False,
importance=importance) importance=importance)
ba.playsound(self._dingsound ba.playsound(self._dingsound
if importance == 1 else self._dingsoundhigh, if importance == 1 else self._dingsoundhigh,
volume=0.6) volume=0.6)
except Exception:
pass
# Normally we pull scores from the score-set, but if there's # Normally we pull scores from the score-set, but if there's
# no player lets be explicit. # no player lets be explicit.

View File

@ -361,8 +361,8 @@ class RaceGame(ba.TeamGameActivity[Player, Team]):
2.2: 0 2.2: 0
}) })
ba.timer(2.3, mathnode.delete) ba.timer(2.3, mathnode.delete)
except Exception as exc: except Exception:
print('Exception printing lap:', exc) ba.print_exception('Error printing lap.')
def on_team_join(self, team: Team) -> None: def on_team_join(self, team: Team) -> None:
self._update_scoreboard() self._update_scoreboard()
@ -392,7 +392,7 @@ class RaceGame(ba.TeamGameActivity[Player, Team]):
if otherplayer.actor is not None: if otherplayer.actor is not None:
otherplayer.actor.handlemessage(ba.DieMessage()) otherplayer.actor.handlemessage(ba.DieMessage())
except Exception: except Exception:
ba.print_exception('Error sending diemessages') ba.print_exception('Error sending DieMessage.')
# Defer so team/player lists will be updated. # Defer so team/player lists will be updated.
ba.pushcall(self._check_end_game) ba.pushcall(self._check_end_game)
@ -520,7 +520,7 @@ class RaceGame(ba.TeamGameActivity[Player, Team]):
assert isinstance(player.actor, PlayerSpaz) assert isinstance(player.actor, PlayerSpaz)
player.actor.connect_controls_to_player() player.actor.connect_controls_to_player()
except Exception: except Exception:
ba.print_exception('Error in race player connects') ba.print_exception('Error in race player connects.')
assert self._timer is not None assert self._timer is not None
self._timer.start() self._timer.start()

View File

@ -1158,7 +1158,7 @@ class RunaroundGame(ba.CoopGameActivity[Player, Team]):
self._dingsoundhigh, self._dingsoundhigh,
volume=0.6) volume=0.6)
except Exception: except Exception:
ba.print_exception('Error on SpazBotDiedMessage') ba.print_exception('Error on SpazBotDiedMessage.')
# Normally we pull scores from the score-set, but if there's no # Normally we pull scores from the score-set, but if there's no
# player lets be explicit. # player lets be explicit.

View File

@ -216,7 +216,7 @@ class TheLastStandGame(ba.CoopGameActivity[Player, Team]):
assert player.actor.node assert player.actor.node
playerpts.append(player.actor.node.position) playerpts.append(player.actor.node.position)
except Exception: except Exception:
ba.print_exception('Error updating bots') ba.print_exception('Error updating bots.')
for i in range(3): for i in range(3):
for playerpt in playerpts: for playerpt in playerpts:
dists[i] += abs(playerpt[0] - botspawnpts[i][0]) dists[i] += abs(playerpt[0] - botspawnpts[i][0])

View File

@ -2305,8 +2305,7 @@ class TutorialActivity(ba.Activity[Player, Team]):
] ]
except Exception: except Exception:
import traceback ba.print_exception()
traceback.print_exc()
# If we read some, exec them. # If we read some, exec them.
if self._entries: if self._entries:
@ -2324,8 +2323,7 @@ class TutorialActivity(ba.Activity[Player, Team]):
result = entry.run(self) result = entry.run(self)
except Exception: except Exception:
result = None result = None
import traceback ba.print_exception()
traceback.print_exc()
# If the entry returns an int value, set a timer; # If the entry returns an int value, set a timer;
# otherwise just keep going. # otherwise just keep going.

View File

@ -984,7 +984,7 @@ class AccountSettingsWindow(ba.Window):
str(int(progress * 100.0)) + '%')]) str(int(progress * 100.0)) + '%')])
except Exception: except Exception:
p_str = '?' p_str = '?'
ba.print_exception('error calculating co-op campaign progress') ba.print_exception('Error calculating co-op campaign progress.')
ba.textwidget(edit=self._campaign_progress_text, text=p_str) ba.textwidget(edit=self._campaign_progress_text, text=p_str)
def _refresh_tickets_text(self) -> None: def _refresh_tickets_text(self) -> None:
@ -1081,7 +1081,7 @@ class AccountSettingsWindow(ba.Window):
campaign = getcampaign('Challenges') campaign = getcampaign('Challenges')
campaign.reset() # also writes the config.. campaign.reset() # also writes the config..
except Exception: except Exception:
ba.print_exception('exception resetting co-op campaign progress') ba.print_exception('Error resetting co-op campaign progress.')
ba.playsound(ba.getsound('shieldDown')) ba.playsound(ba.getsound('shieldDown'))
self._refresh() self._refresh()
@ -1108,14 +1108,11 @@ class AccountSettingsWindow(ba.Window):
raise ValueError('unrecognized selection') raise ValueError('unrecognized selection')
ba.app.window_states[self.__class__.__name__] = sel_name ba.app.window_states[self.__class__.__name__] = sel_name
except Exception: except Exception:
ba.print_exception('exception saving state for', self.__class__) ba.print_exception(f'Error saving state for {self}.')
def _restore_state(self) -> None: def _restore_state(self) -> None:
try: try:
try: sel_name = ba.app.window_states.get(self.__class__.__name__)
sel_name = ba.app.window_states[self.__class__.__name__]
except Exception:
sel_name = None
if sel_name == 'Back': if sel_name == 'Back':
sel = self._back_button sel = self._back_button
elif sel_name == 'Scroll': elif sel_name == 'Scroll':
@ -1124,4 +1121,4 @@ class AccountSettingsWindow(ba.Window):
sel = self._back_button sel = self._back_button
ba.containerwidget(edit=self._root_widget, selected_child=sel) ba.containerwidget(edit=self._root_widget, selected_child=sel)
except Exception: except Exception:
ba.print_exception('error restoring state for', self.__class__) ba.print_exception(f'Error restoring state for {self}.')

View File

@ -208,7 +208,7 @@ class AccountViewerWindow(popup.PopupWindow):
if trophystr == '': if trophystr == '':
trophystr = '-' trophystr = '-'
except Exception: except Exception:
ba.print_exception('Error displaying trophies') ba.print_exception('Error displaying trophies.')
account_name_spacing = 15 account_name_spacing = 15
tscale = 0.65 tscale = 0.65
ts_height = _ba.get_string_height(trophystr, ts_height = _ba.get_string_height(trophystr,
@ -255,7 +255,7 @@ class AccountViewerWindow(popup.PopupWindow):
tint2_color=tint2_color) tint2_color=tint2_color)
v -= 95 v -= 95
except Exception: except Exception:
ba.print_exception('Error displaying character') ba.print_exception('Error displaying character.')
ba.textwidget( ba.textwidget(
parent=self._subcontainer, parent=self._subcontainer,
size=(0, 0), size=(0, 0),
@ -474,7 +474,7 @@ class AccountViewerWindow(popup.PopupWindow):
text=trophystr) text=trophystr)
except Exception: except Exception:
ba.print_exception('Error displaying account info') ba.print_exception('Error displaying account info.')
def _on_cancel_press(self) -> None: def _on_cancel_press(self) -> None:
self._transition_out() self._transition_out()

View File

@ -83,10 +83,8 @@ class CoopBrowserWindow(ba.Window):
# Try to recreate the same number of buttons we had last time so our # Try to recreate the same number of buttons we had last time so our
# re-selection code works. # re-selection code works.
try: self._tournament_button_count = app.config.get('Tournament Rows', 0)
self._tournament_button_count = app.config['Tournament Rows'] assert isinstance(self._tournament_button_count, int)
except Exception:
self._tournament_button_count = 0
self._easy_button: Optional[ba.Widget] = None self._easy_button: Optional[ba.Widget] = None
self._hard_button: Optional[ba.Widget] = None self._hard_button: Optional[ba.Widget] = None
@ -345,7 +343,7 @@ class CoopBrowserWindow(ba.Window):
ba.imagewidget(edit=self._hard_button_lock_image, ba.imagewidget(edit=self._hard_button_lock_image,
opacity=0.0 if have_pro_options() else 1.0) opacity=0.0 if have_pro_options() else 1.0)
except Exception: except Exception:
ba.print_exception('error updating campaign lock') ba.print_exception('Error updating campaign lock.')
def _update_for_data(self, data: Optional[List[Dict[str, Any]]]) -> None: def _update_for_data(self, data: Optional[List[Dict[str, Any]]]) -> None:
# pylint: disable=too-many-statements # pylint: disable=too-many-statements
@ -1006,7 +1004,7 @@ class CoopBrowserWindow(ba.Window):
up_widget=tournament_h_scroll if self._tournament_buttons up_widget=tournament_h_scroll if self._tournament_buttons
else self._tournament_info_button) else self._tournament_info_button)
except Exception: except Exception:
ba.print_exception('Error wiring up custom buttons') ba.print_exception('Error wiring up custom buttons.')
if self._back_button is not None: if self._back_button is not None:
ba.buttonwidget(edit=self._back_button, ba.buttonwidget(edit=self._back_button,
@ -1531,11 +1529,8 @@ class CoopBrowserWindow(ba.Window):
def _restore_state(self) -> None: def _restore_state(self) -> None:
try: try:
try: sel_name = ba.app.window_states.get(self.__class__.__name__,
sel_name = ba.app.window_states[ {}).get('sel_name')
self.__class__.__name__]['sel_name']
except Exception:
sel_name = None
if sel_name == 'Back': if sel_name == 'Back':
sel = self._back_button sel = self._back_button
elif sel_name == 'Scroll': elif sel_name == 'Scroll':
@ -1548,7 +1543,7 @@ class CoopBrowserWindow(ba.Window):
sel = self._scrollwidget sel = self._scrollwidget
ba.containerwidget(edit=self._root_widget, selected_child=sel) ba.containerwidget(edit=self._root_widget, selected_child=sel)
except Exception: except Exception:
ba.print_exception('error restoring state for', self.__class__) ba.print_exception(f'Error restoring state for {self}.')
def _save_state(self) -> None: def _save_state(self) -> None:
cfg = ba.app.config cfg = ba.app.config
@ -1568,7 +1563,7 @@ class CoopBrowserWindow(ba.Window):
'sel_name': sel_name 'sel_name': sel_name
} }
except Exception: except Exception:
ba.print_exception('error saving state for', self.__class__) ba.print_exception(f'Error saving state for {self}.')
cfg['Selected Coop Row'] = self._selected_row cfg['Selected Coop Row'] = self._selected_row
cfg['Selected Coop Custom Level'] = self._selected_custom_level cfg['Selected Coop Custom Level'] = self._selected_custom_level

View File

@ -173,7 +173,7 @@ class CreditsListWindow(ba.Window):
translation_contributors = (json.loads( translation_contributors = (json.loads(
infile.read())['translation_contributors']) infile.read())['translation_contributors'])
except Exception: except Exception:
ba.print_exception('error reading translation contributors') ba.print_exception('Error reading translation contributors.')
translation_contributors = [] translation_contributors = []
translation_names = _format_names(translation_contributors, 60) translation_names = _format_names(translation_contributors, 60)

View File

@ -181,7 +181,7 @@ class FileSelectorWindow(ba.Window):
test_path)) test_path))
except Exception: except Exception:
ba.print_exception( ba.print_exception(
'error on FileSelectorWindow._on_entry_activated') 'Error in FileSelectorWindow._on_entry_activated().')
if new_path is not None: if new_path is not None:
self._set_path(new_path) self._set_path(new_path)

View File

@ -828,14 +828,14 @@ class GatherWindow(ba.Window):
self._call = call self._call = call
def run(self) -> None: def run(self) -> None:
result: Optional[str]
try: try:
import socket import socket
addr2 = socket.gethostbyname(self._name) result = socket.gethostbyname(self._name)
ba.pushcall(ba.Call(self._call, addr2),
from_other_thread=True)
except Exception: except Exception:
ba.pushcall(ba.Call(self._call, None), result = None
from_other_thread=True) ba.pushcall(ba.Call(self._call, result),
from_other_thread=True)
def do_it_2(addr2: Optional[str]) -> None: def do_it_2(addr2: Optional[str]) -> None:
if addr2 is None: if addr2 is None:
@ -1969,7 +1969,7 @@ class GatherWindow(ba.Window):
'internet_tab': self._internet_tab 'internet_tab': self._internet_tab
} }
except Exception: except Exception:
ba.print_exception('error saving state for', self.__class__) ba.print_exception(f'Error saving state for {self}.')
def _restore_state(self) -> None: def _restore_state(self) -> None:
try: try:
@ -1990,7 +1990,7 @@ class GatherWindow(ba.Window):
sel = self._tab_buttons[current_tab] sel = self._tab_buttons[current_tab]
ba.containerwidget(edit=self._root_widget, selected_child=sel) ba.containerwidget(edit=self._root_widget, selected_child=sel)
except Exception: except Exception:
ba.print_exception('error restoring state for', self.__class__) ba.print_exception(f'Error restoring state for {self}.')
def _back(self) -> None: def _back(self) -> None:
from bastd.ui import mainmenu from bastd.ui import mainmenu

View File

@ -336,10 +336,7 @@ class KioskWindow(ba.Window):
repeat=True) repeat=True)
def _restore_state(self) -> None: def _restore_state(self) -> None:
try: sel_name = ba.app.window_states.get(self.__class__.__name__)
sel_name = ba.app.window_states[self.__class__.__name__]
except Exception:
sel_name = None
sel: Optional[ba.Widget] sel: Optional[ba.Widget]
if sel_name == 'b1': if sel_name == 'b1':
sel = self._b1 sel = self._b1

View File

@ -227,7 +227,7 @@ class LeagueRankButton:
ba.buttonwidget(edit=self._button, color=color_used) ba.buttonwidget(edit=self._button, color=color_used)
except Exception: except Exception:
ba.print_exception('error doing smooth update') ba.print_exception('Error doing smooth update.')
self._smooth_update_timer = None self._smooth_update_timer = None
def _update_for_league_rank_data(self, data: Optional[Dict[str, def _update_for_league_rank_data(self, data: Optional[Dict[str,
@ -285,7 +285,7 @@ class LeagueRankButton:
status_text = str(int(self._smooth_percent)) + '%' status_text = str(int(self._smooth_percent)) + '%'
except Exception: except Exception:
ba.print_exception('error updating power ranking') ba.print_exception('Error updating power ranking.')
self._percent = self._rank = None self._percent = self._rank = None
status_text = '-' status_text = '-'
@ -326,10 +326,15 @@ class LeagueRankButton:
else: else:
try: try:
assert data is not None assert data is not None
txt = ba.Lstr(resource='league.leagueFullText', txt = ba.Lstr(
subs=[('${NAME}', resource='league.leagueFullText',
ba.Lstr(translate=('leagueNames', subs=[
data['l']['n'])))]) (
'${NAME}',
ba.Lstr(translate=('leagueNames', data['l']['n'])),
),
],
)
t_color = data['l']['c'] t_color = data['l']['c']
except Exception: except Exception:
txt = ba.Lstr( txt = ba.Lstr(

View File

@ -259,7 +259,7 @@ class LeagueRankWindow(ba.Window):
ba.textwidget(edit=self._season_ends_text, text='') ba.textwidget(edit=self._season_ends_text, text='')
ba.textwidget(edit=self._trophy_counts_reset_text, text='') ba.textwidget(edit=self._trophy_counts_reset_text, text='')
except Exception: except Exception:
ba.print_exception('error showing updated rank info') ba.print_exception('Error showing updated rank info.')
self._last_power_ranking_query_time = cur_time self._last_power_ranking_query_time = cur_time
self._doing_power_ranking_query = True self._doing_power_ranking_query = True
@ -651,7 +651,7 @@ class LeagueRankWindow(ba.Window):
'${REMAINING}', str(data['scores'][-1][1]))) '${REMAINING}', str(data['scores'][-1][1])))
do_percent = True do_percent = True
except Exception: except Exception:
ba.print_exception('error updating power ranking') ba.print_exception('Error updating power ranking.')
status_text = self._rdict.powerRankingNotInTopText.replace( status_text = self._rdict.powerRankingNotInTopText.replace(
'${NUMBER}', str(data['listSize'])) '${NUMBER}', str(data['listSize']))
extra_text = '' extra_text = ''

View File

@ -109,8 +109,8 @@ class MainMenuWindow(ba.Window):
ba.timer(2.5, ba.timer(2.5,
_check_show_bs_remote_window, _check_show_bs_remote_window,
timetype=ba.TimeType.REAL) timetype=ba.TimeType.REAL)
except Exception as exc: except Exception:
print('EXC bs_remote_show', exc) ba.print_exception('Error showing get-remote-app info')
def _get_store_char_tex(self) -> str: def _get_store_char_tex(self) -> str:
return ('storeCharacterXmas' if _ba.get_account_misc_read_val( return ('storeCharacterXmas' if _ba.get_account_misc_read_val(
@ -677,8 +677,8 @@ class MainMenuWindow(ba.Window):
str(cme)) str(cme))
except Exception: except Exception:
custom_menu_entries = [] custom_menu_entries = []
ba.print_exception('exception getting custom menu entries for', ba.print_exception(
session) f'Error getting custom menu entries for {session}')
self._width = 250.0 self._width = 250.0
self._height = 250.0 if self._input_player else 180.0 self._height = 250.0 if self._input_player else 180.0
if self._is_kiosk and self._input_player: if self._is_kiosk and self._input_player:
@ -738,10 +738,7 @@ class MainMenuWindow(ba.Window):
# Ask the entry whether we should resume when we call # Ask the entry whether we should resume when we call
# it (defaults to true). # it (defaults to true).
try: resume = bool(entry.get('resume_on_call', True))
resume = entry['resume_on_call']
except Exception:
resume = True
if resume: if resume:
call = ba.Call(self._resume_and_call, entry['call']) call = ba.Call(self._resume_and_call, entry['call'])

View File

@ -284,7 +284,7 @@ class PartyWindow(ba.Window):
'displayString'] 'displayString']
except Exception: except Exception:
ba.print_exception( ba.print_exception(
'error calcing client name str') 'Error calcing client name str.')
p_str = '???' p_str = '???'
widget = ba.textwidget(parent=self._root_widget, widget = ba.textwidget(parent=self._root_widget,

View File

@ -279,7 +279,7 @@ class PartyQueueWindow(ba.Window):
}) })
_ba.run_transactions() _ba.run_transactions()
except Exception: except Exception:
ba.print_exception('err removing self from party queue') ba.print_exception('Error removing self from party queue.')
def get_line_left(self) -> float: def get_line_left(self) -> float:
"""(internal)""" """(internal)"""

View File

@ -541,14 +541,11 @@ class PlayWindow(ba.Window):
raise ValueError(f'unrecognized selection {sel}') raise ValueError(f'unrecognized selection {sel}')
ba.app.window_states[self.__class__.__name__] = sel_name ba.app.window_states[self.__class__.__name__] = sel_name
except Exception: except Exception:
ba.print_exception('error saving state for', self.__class__) ba.print_exception(f'Error saving state for {self}.')
def _restore_state(self) -> None: def _restore_state(self) -> None:
try: try:
try: sel_name = ba.app.window_states.get(self.__class__.__name__)
sel_name = ba.app.window_states[self.__class__.__name__]
except Exception:
sel_name = None
if sel_name == 'Team Games': if sel_name == 'Team Games':
sel = self._teams_button sel = self._teams_button
elif sel_name == 'Co-op Games': elif sel_name == 'Co-op Games':
@ -561,4 +558,4 @@ class PlayWindow(ba.Window):
sel = self._coop_button sel = self._coop_button
ba.containerwidget(edit=self._root_widget, selected_child=sel) ba.containerwidget(edit=self._root_widget, selected_child=sel)
except Exception: except Exception:
ba.print_exception('error restoring state for', self.__class__) ba.print_exception(f'Error restoring state for {self}.')

View File

@ -452,7 +452,7 @@ class PlaylistBrowserWindow(ba.Window):
maptype: Optional[Type[ba.Map]] maptype: Optional[Type[ba.Map]]
try: try:
maptype = get_map_class(mapname) maptype = get_map_class(mapname)
except Exception: except ba.NotFoundError:
maptype = None maptype = None
if maptype is not None: if maptype is not None:
tex_name = maptype.get_preview_texture_name() tex_name = maptype.get_preview_texture_name()

View File

@ -229,11 +229,8 @@ class PlaylistCustomizeBrowserWindow(ba.Window):
h = 145 h = 145
try: self._do_randomize_val = ba.app.config.get(
self._do_randomize_val = ba.app.config[self._pvars.config_name + self._pvars.config_name + ' Playlist Randomize', 0)
' Playlist Randomize']
except Exception:
self._do_randomize_val = 0
h += 210 h += 210
@ -300,7 +297,7 @@ class PlaylistCustomizeBrowserWindow(ba.Window):
_ba.new_host_session(self._sessiontype) _ba.new_host_session(self._sessiontype)
except Exception: except Exception:
from bastd import mainmenu from bastd import mainmenu
ba.print_exception('exception running session', self._sessiontype) ba.print_exception(f'Error running session {self._sessiontype}.')
# Drop back into a main menu session. # Drop back into a main menu session.
_ba.new_host_session(mainmenu.MainMenuSession) _ba.new_host_session(mainmenu.MainMenuSession)
@ -318,11 +315,8 @@ class PlaylistCustomizeBrowserWindow(ba.Window):
# If there was no prev selection, look in prefs. # If there was no prev selection, look in prefs.
if old_selection is None: if old_selection is None:
try: old_selection = ba.app.config.get(self._pvars.config_name +
old_selection = ba.app.config[self._pvars.config_name + ' Playlist Selection')
' Playlist Selection']
except Exception:
pass
old_selection_index = self._selected_playlist_index old_selection_index = self._selected_playlist_index

View File

@ -97,7 +97,7 @@ class PlaylistEditGameWindow(ba.Window):
if filtered_map_name in valid_maps: if filtered_map_name in valid_maps:
self._map = filtered_map_name self._map = filtered_map_name
except Exception: except Exception:
ba.print_exception('exception getting map for editor') ba.print_exception('Error getting map for editor.')
if config is not None and 'settings' in config: if config is not None and 'settings' in config:
self._settings = config['settings'] self._settings = config['settings']
@ -427,7 +427,7 @@ class PlaylistEditGameWindow(ba.Window):
prev_widgets = cwdg prev_widgets = cwdg
except Exception: except Exception:
ba.print_exception( ba.print_exception(
'error wiring up game-settings-select widget column') 'Error wiring up game-settings-select widget column.')
ba.buttonwidget(edit=add_button, on_activate_call=ba.Call(self._add)) ba.buttonwidget(edit=add_button, on_activate_call=ba.Call(self._add))
ba.containerwidget(edit=self._root_widget, ba.containerwidget(edit=self._root_widget,

View File

@ -135,8 +135,7 @@ class PlaylistMapSelectWindow(ba.Window):
map_tex = ba.gettexture(map_tex_name) map_tex = ba.gettexture(map_tex_name)
self._maps.append((mapname, map_tex)) self._maps.append((mapname, map_tex))
except Exception: except Exception:
print('invalid map preview texture: "' + map_tex_name + print(f'Invalid map preview texture: "{map_tex_name}".')
'"')
else: else:
print('Error: no map preview texture for map:', mapname) print('Error: no map preview texture for map:', mapname)

View File

@ -117,7 +117,7 @@ class PlayOptionsWindow(popup.PopupWindow):
maptype: Optional[Type[ba.Map]] maptype: Optional[Type[ba.Map]]
try: try:
maptype = get_map_class(mapname) maptype = get_map_class(mapname)
except Exception: except ba.NotFoundError:
maptype = None maptype = None
if maptype is not None: if maptype is not None:
tex_name = maptype.get_preview_texture_name() tex_name = maptype.get_preview_texture_name()
@ -141,7 +141,7 @@ class PlayOptionsWindow(popup.PopupWindow):
self._height += self._row_height * rows self._height += self._row_height * rows
except Exception: except Exception:
ba.print_exception('error listing playlist maps') ba.print_exception('Error listing playlist maps.')
show_shuffle_check_box = game_count > 1 show_shuffle_check_box = game_count > 1
@ -304,10 +304,7 @@ class PlayOptionsWindow(popup.PopupWindow):
on_value_change_call=_cb_callback) on_value_change_call=_cb_callback)
# Show tutorial. # Show tutorial.
try: show_tutorial = bool(ba.app.config.get('Show Tutorial', True))
show_tutorial = ba.app.config['Show Tutorial']
except Exception:
show_tutorial = True
def _cb_callback_2(val: bool) -> None: def _cb_callback_2(val: bool) -> None:
cfg = ba.app.config cfg = ba.app.config
@ -388,10 +385,8 @@ class PlayOptionsWindow(popup.PopupWindow):
def _does_target_playlist_exist(self) -> bool: def _does_target_playlist_exist(self) -> bool:
if self._playlist == '__default__': if self._playlist == '__default__':
return True return True
val: bool = self._playlist in ba.app.config.get( return self._playlist in ba.app.config.get(
self._pvars.config_name + ' Playlists', {}) self._pvars.config_name + ' Playlists', {})
assert isinstance(val, bool)
return val
def _update(self) -> None: def _update(self) -> None:
# All we do here is make sure our targeted playlist still exists, # All we do here is make sure our targeted playlist still exists,

View File

@ -290,10 +290,7 @@ class ProfileBrowserWindow(ba.Window):
# Delete old. # Delete old.
while self._profile_widgets: while self._profile_widgets:
self._profile_widgets.pop().delete() self._profile_widgets.pop().delete()
try: self._profiles = ba.app.config.get('Player Profiles', {})
self._profiles = ba.app.config['Player Profiles']
except Exception:
self._profiles = {}
assert self._profiles is not None assert self._profiles is not None
items = list(self._profiles.items()) items = list(self._profiles.items())
items.sort(key=lambda x: x[0].lower()) items.sort(key=lambda x: x[0].lower())
@ -365,14 +362,11 @@ class ProfileBrowserWindow(ba.Window):
sel_name = 'Back' sel_name = 'Back'
ba.app.window_states[self.__class__.__name__] = sel_name ba.app.window_states[self.__class__.__name__] = sel_name
except Exception: except Exception:
ba.print_exception('error saving state for', self.__class__) ba.print_exception(f'Error saving state for {self}.')
def _restore_state(self) -> None: def _restore_state(self) -> None:
try: try:
try: sel_name = ba.app.window_states.get(self.__class__.__name__)
sel_name = ba.app.window_states[self.__class__.__name__]
except Exception:
sel_name = None
if sel_name == 'Scroll': if sel_name == 'Scroll':
sel = self._scrollwidget sel = self._scrollwidget
elif sel_name == 'New': elif sel_name == 'New':
@ -392,4 +386,4 @@ class ProfileBrowserWindow(ba.Window):
sel = self._scrollwidget sel = self._scrollwidget
ba.containerwidget(edit=self._root_widget, selected_child=sel) ba.containerwidget(edit=self._root_widget, selected_child=sel)
except Exception: except Exception:
ba.print_exception('error restoring state for', self.__class__) ba.print_exception(f'Error restoring state for {self}.')

View File

@ -253,7 +253,7 @@ class AdvancedSettingsWindow(ba.Window):
lang_names_translated = (json.loads( lang_names_translated = (json.loads(
infile.read())['lang_names_translated']) infile.read())['lang_names_translated'])
except Exception: except Exception:
ba.print_exception('error reading lang data') ba.print_exception('Error reading lang data.')
lang_names_translated = {} lang_names_translated = {}
langs_translated = {} langs_translated = {}
@ -605,16 +605,13 @@ class AdvancedSettingsWindow(ba.Window):
'sel_name': sel_name 'sel_name': sel_name
} }
except Exception: except Exception:
ba.print_exception('error saving state for', self.__class__) ba.print_exception(f'Error saving state for {self.__class__}')
def _restore_state(self) -> None: def _restore_state(self) -> None:
# pylint: disable=too-many-branches # pylint: disable=too-many-branches
try: try:
try: sel_name = ba.app.window_states.get(self.__class__.__name__,
sel_name = ba.app.window_states[ {}).get('sel_name')
self.__class__.__name__]['sel_name']
except Exception:
sel_name = None
if sel_name == 'Back': if sel_name == 'Back':
sel = self._back_button sel = self._back_button
else: else:
@ -654,7 +651,7 @@ class AdvancedSettingsWindow(ba.Window):
selected_child=sel, selected_child=sel,
visible_child=sel) visible_child=sel)
except Exception: except Exception:
ba.print_exception('error restoring state for', self.__class__) ba.print_exception(f'Error restoring state for {self.__class__}')
def _on_menu_open(self) -> None: def _on_menu_open(self) -> None:
self._menu_open = True self._menu_open = True

View File

@ -257,15 +257,12 @@ class AllSettingsWindow(ba.Window):
'sel_name': sel_name 'sel_name': sel_name
} }
except Exception: except Exception:
ba.print_exception('error saving state for', self.__class__) ba.print_exception(f'Error saving state for {self}.')
def _restore_state(self) -> None: def _restore_state(self) -> None:
try: try:
try: sel_name = ba.app.window_states.get(self.__class__.__name__,
sel_name = ba.app.window_states[ {}).get('sel_name')
self.__class__.__name__]['sel_name']
except Exception:
sel_name = None
sel: Optional[ba.Widget] sel: Optional[ba.Widget]
if sel_name == 'Controllers': if sel_name == 'Controllers':
sel = self._controllers_button sel = self._controllers_button
@ -282,4 +279,4 @@ class AllSettingsWindow(ba.Window):
if sel is not None: if sel is not None:
ba.containerwidget(edit=self._root_widget, selected_child=sel) ba.containerwidget(edit=self._root_widget, selected_child=sel)
except Exception: except Exception:
ba.print_exception('error restoring state for', self.__class__) ba.print_exception(f'Error restoring state for {self}.')

View File

@ -210,7 +210,7 @@ class AudioSettingsWindow(ba.Window):
try: try:
ba.widget(edit=back_button, down_widget=svne.minusbutton) ba.widget(edit=back_button, down_widget=svne.minusbutton)
except Exception: except Exception:
ba.print_exception('error wiring AudioSettingsWindow') ba.print_exception('Error wiring AudioSettingsWindow.')
self._restore_state() self._restore_state()
@ -269,14 +269,11 @@ class AudioSettingsWindow(ba.Window):
raise ValueError(f'unrecognized selection \'{sel}\'') raise ValueError(f'unrecognized selection \'{sel}\'')
ba.app.window_states[self.__class__.__name__] = sel_name ba.app.window_states[self.__class__.__name__] = sel_name
except Exception: except Exception:
ba.print_exception('error saving state for', self.__class__) ba.print_exception(f'Error saving state for {self.__class__}.')
def _restore_state(self) -> None: def _restore_state(self) -> None:
try: try:
try: sel_name = ba.app.window_states.get(self.__class__.__name__)
sel_name = ba.app.window_states[self.__class__.__name__]
except Exception:
sel_name = None
sel: Optional[ba.Widget] sel: Optional[ba.Widget]
if sel_name == 'SoundMinus': if sel_name == 'SoundMinus':
sel = self._sound_volume_numedit.minusbutton sel = self._sound_volume_numedit.minusbutton
@ -297,4 +294,4 @@ class AudioSettingsWindow(ba.Window):
if sel: if sel:
ba.containerwidget(edit=self._root_widget, selected_child=sel) ba.containerwidget(edit=self._root_widget, selected_child=sel)
except Exception: except Exception:
ba.print_exception('error restoring state for', self.__class__) ba.print_exception(f'Error restoring state for {self.__class__}.')

View File

@ -474,10 +474,7 @@ class ControlsSettingsWindow(ba.Window):
ba.app.window_states[self.__class__.__name__] = sel_name ba.app.window_states[self.__class__.__name__] = sel_name
def _restore_state(self) -> None: def _restore_state(self) -> None:
try: sel_name = ba.app.window_states.get(self.__class__.__name__)
sel_name = ba.app.window_states[self.__class__.__name__]
except Exception:
sel_name = None
if sel_name == 'GamePads': if sel_name == 'GamePads':
sel = self._gamepads_button sel = self._gamepads_button
elif sel_name == 'Touch': elif sel_name == 'Touch':

View File

@ -351,7 +351,7 @@ class GamepadSettingsWindow(ba.Window):
ba.widget(edit=cancel_button, right_widget=save_button) ba.widget(edit=cancel_button, right_widget=save_button)
ba.widget(edit=save_button, left_widget=cancel_button) ba.widget(edit=save_button, left_widget=cancel_button)
except Exception: except Exception:
ba.print_exception('error wiring gamepad config window') ba.print_exception('Error wiring up gamepad config window.')
def get_r(self) -> str: def get_r(self) -> str:
"""(internal)""" """(internal)"""

View File

@ -403,10 +403,7 @@ class GamepadAdvancedSettingsWindow(ba.Window):
def _inc(self, control: str, min_val: float, max_val: float, def _inc(self, control: str, min_val: float, max_val: float,
inc: float) -> None: inc: float) -> None:
try: val = self._parent_window.get_settings().get(control, 1.0)
val = self._parent_window.get_settings()[control]
except Exception:
val = 1.0
val = min(max_val, max(min_val, val + inc)) val = min(max_val, max(min_val, val + inc))
if abs(1.0 - val) < 0.001: if abs(1.0 - val) < 0.001:
if control in self._parent_window.get_settings(): if control in self._parent_window.get_settings():

View File

@ -379,19 +379,14 @@ class SoundtrackBrowserWindow(ba.Window):
# If there was no prev selection, look in prefs. # If there was no prev selection, look in prefs.
if old_selection is None: if old_selection is None:
try: old_selection = ba.app.config.get('Soundtrack')
old_selection = ba.app.config['Soundtrack']
except Exception:
pass
old_selection_index = self._selected_soundtrack_index old_selection_index = self._selected_soundtrack_index
# Delete old. # Delete old.
while self._soundtrack_widgets: while self._soundtrack_widgets:
self._soundtrack_widgets.pop().delete() self._soundtrack_widgets.pop().delete()
try:
self._soundtracks = ba.app.config['Soundtracks'] self._soundtracks = ba.app.config.get('Soundtracks', {})
except Exception:
self._soundtracks = {}
assert self._soundtracks is not None assert self._soundtracks is not None
items = list(self._soundtracks.items()) items = list(self._soundtracks.items())
items.sort(key=lambda x: x[0].lower()) items.sort(key=lambda x: x[0].lower())
@ -488,14 +483,11 @@ class SoundtrackBrowserWindow(ba.Window):
raise ValueError(f'unrecognized selection \'{sel}\'') raise ValueError(f'unrecognized selection \'{sel}\'')
ba.app.window_states[self.__class__.__name__] = sel_name ba.app.window_states[self.__class__.__name__] = sel_name
except Exception: except Exception:
ba.print_exception('error saving state for', self.__class__) ba.print_exception(f'Error saving state for {self}.')
def _restore_state(self) -> None: def _restore_state(self) -> None:
try: try:
try: sel_name = ba.app.window_states.get(self.__class__.__name__)
sel_name = ba.app.window_states[self.__class__.__name__]
except Exception:
sel_name = None
if sel_name == 'Scroll': if sel_name == 'Scroll':
sel = self._scrollwidget sel = self._scrollwidget
elif sel_name == 'New': elif sel_name == 'New':
@ -510,4 +502,4 @@ class SoundtrackBrowserWindow(ba.Window):
sel = self._scrollwidget sel = self._scrollwidget
ba.containerwidget(edit=self._root_widget, selected_child=sel) ba.containerwidget(edit=self._root_widget, selected_child=sel)
except Exception: except Exception:
ba.print_exception('error restoring state for', self.__class__) ba.print_exception(f'Error restoring state for {self}.')

View File

@ -213,10 +213,7 @@ class SoundtrackEditWindow(ba.Window):
claims_left_right=True, claims_left_right=True,
claims_tab=True, claims_tab=True,
selection_loop_to_parent=True) selection_loop_to_parent=True)
try: type_name = type_names_translated.get(song_type, song_type)
type_name = type_names_translated[song_type]
except Exception:
type_name = song_type
ba.textwidget(parent=row, ba.textwidget(parent=row,
size=(230, 25), size=(230, 25),
always_highlight=True, always_highlight=True,

View File

@ -119,6 +119,7 @@ class SpecialOfferWindow(ba.Window):
resource='store.salePercentText').evaluate().replace( resource='store.salePercentText').evaluate().replace(
'${PERCENT}', str(percent_off)) '${PERCENT}', str(percent_off))
except Exception: except Exception:
ba.print_exception('Error setting up special-offer')
original_price_str = new_price_str = '?' original_price_str = new_price_str = '?'
percent_off_text = '' percent_off_text = ''
@ -462,6 +463,6 @@ def show_offer() -> bool:
app.special_offer = None app.special_offer = None
return True return True
except Exception: except Exception:
ba.print_exception('Error showing offer') ba.print_exception('Error showing offer.')
return False return False

View File

@ -1008,20 +1008,14 @@ class StoreBrowserWindow(ba.Window):
'tab': self._current_tab 'tab': self._current_tab
} }
except Exception: except Exception:
ba.print_exception('error saving state for', self.__class__) ba.print_exception(f'Error saving state for {self}.')
def _restore_state(self) -> None: def _restore_state(self) -> None:
try: try:
sel: Optional[ba.Widget] sel: Optional[ba.Widget]
try: sel_name = ba.app.window_states.get(self.__class__.__name__,
sel_name = ( {}).get('sel_name')
ba.app.window_states[self.__class__.__name__]['sel_name']) current_tab = ba.app.config.get('Store Tab')
except Exception:
sel_name = None
try:
current_tab = ba.app.config['Store Tab']
except Exception:
current_tab = None
if self._show_tab is not None: if self._show_tab is not None:
current_tab = self._show_tab current_tab = self._show_tab
if current_tab is None or current_tab not in self._tab_buttons: if current_tab is None or current_tab not in self._tab_buttons:
@ -1044,7 +1038,7 @@ class StoreBrowserWindow(ba.Window):
if sel is not None: if sel is not None:
ba.containerwidget(edit=self._root_widget, selected_child=sel) ba.containerwidget(edit=self._root_widget, selected_child=sel)
except Exception: except Exception:
ba.print_exception('error restoring state for', self.__class__) ba.print_exception(f'Error restoring state for {self}.')
def _on_get_more_tickets_press(self) -> None: def _on_get_more_tickets_press(self) -> None:
# pylint: disable=cyclic-import # pylint: disable=cyclic-import

View File

@ -259,7 +259,7 @@ class StoreButton:
if to_end > 0: if to_end > 0:
sale_times.append(to_end) sale_times.append(to_end)
except Exception: except Exception:
ba.print_exception('Error parsing sales') ba.print_exception('Error parsing sales.')
if sale_times: if sale_times:
sale_time = int(min(sale_times) * 1000) sale_time = int(min(sale_times) * 1000)

View File

@ -332,10 +332,7 @@ class TournamentEntryWindow(popup.PopupWindow):
cfg.commit() cfg.commit()
def _restore_state(self) -> None: def _restore_state(self) -> None:
try: sel_name = ba.app.config.get('Tournament Pay Selection', 'Tickets')
sel_name = ba.app.config['Tournament Pay Selection']
except Exception:
sel_name = 'Tickets'
if sel_name == 'Ad' and self._pay_with_ad_btn is not None: if sel_name == 'Ad' and self._pay_with_ad_btn is not None:
sel = self._pay_with_ad_btn sel = self._pay_with_ad_btn
else: else:
@ -457,13 +454,14 @@ class TournamentEntryWindow(popup.PopupWindow):
ba.screenmessage(ba.Lstr(translate=('serverResponses', ba.screenmessage(ba.Lstr(translate=('serverResponses',
'Entering tournament...')), 'Entering tournament...')),
color=(0, 1, 0)) color=(0, 1, 0))
# We can hit exceptions here if _tournament_activity ends before # We can hit exceptions here if _tournament_activity ends before
# our restart attempt happens. # our restart attempt happens.
# In this case we'll fall back to launching a new session. # In this case we'll fall back to launching a new session.
# This is not ideal since players will have to rejoin, etc., # This is not ideal since players will have to rejoin, etc.,
# but it works for now. # but it works for now.
except Exception: except Exception:
pass print('Error restarting tournament activity.')
# If we had no existing activity (or were unable to restart it) # If we had no existing activity (or were unable to restart it)
# launch a new session. # launch a new session.

View File

@ -286,16 +286,17 @@ class WatchWindow(ba.Window):
def do_it() -> None: def do_it() -> None:
try: try:
# reset to normal speed # Reset to normal speed.
_ba.set_replay_speed_exponent(0) _ba.set_replay_speed_exponent(0)
_ba.fade_screen(True) _ba.fade_screen(True)
assert self._my_replay_selected is not None assert self._my_replay_selected is not None
_ba.new_replay_session(_ba.get_replays_dir() + '/' + _ba.new_replay_session(_ba.get_replays_dir() + '/' +
self._my_replay_selected) self._my_replay_selected)
except Exception: except Exception:
ba.print_exception('exception running replay session') ba.print_exception('Error running replay session.')
# drop back into a fresh main menu session
# in case we half-launched or something.. # Drop back into a fresh main menu session
# in case we half-launched or something.
from bastd import mainmenu from bastd import mainmenu
_ba.new_host_session(mainmenu.MainMenuSession) _ba.new_host_session(mainmenu.MainMenuSession)
@ -391,11 +392,12 @@ class WatchWindow(ba.Window):
ba.playsound(ba.getsound('gunCocking')) ba.playsound(ba.getsound('gunCocking'))
except Exception: except Exception:
ba.print_exception( ba.print_exception(
f"error renaming replay '{replay}' to '{new_name}'") f"Error renaming replay '{replay}' to '{new_name}'.")
ba.playsound(ba.getsound('error')) ba.playsound(ba.getsound('error'))
ba.screenmessage(ba.Lstr(resource=self._r + ba.screenmessage(
'.replayRenameErrorText'), ba.Lstr(resource=self._r + '.replayRenameErrorText'),
color=(1, 0, 0)) color=(1, 0, 0),
)
ba.containerwidget(edit=self._my_replays_rename_window, ba.containerwidget(edit=self._my_replays_rename_window,
transition='out_scale') transition='out_scale')
@ -428,11 +430,12 @@ class WatchWindow(ba.Window):
if replay == self._my_replay_selected: if replay == self._my_replay_selected:
self._my_replay_selected = None self._my_replay_selected = None
except Exception: except Exception:
ba.print_exception("exception deleting replay '" + replay + "'") ba.print_exception(f"Error deleting replay '{replay}'.")
ba.playsound(ba.getsound('error')) ba.playsound(ba.getsound('error'))
ba.screenmessage(ba.Lstr(resource=self._r + ba.screenmessage(
'.replayDeleteErrorText'), ba.Lstr(resource=self._r + '.replayDeleteErrorText'),
color=(1, 0, 0)) color=(1, 0, 0),
)
def _on_my_replay_select(self, replay: str) -> None: def _on_my_replay_select(self, replay: str) -> None:
self._my_replay_selected = replay self._my_replay_selected = replay
@ -448,7 +451,7 @@ class WatchWindow(ba.Window):
names = [n for n in names if n.endswith('.brp')] names = [n for n in names if n.endswith('.brp')]
names.sort(key=lambda x: x.lower()) names.sort(key=lambda x: x.lower())
except Exception: except Exception:
ba.print_exception('error listing replays dir') ba.print_exception('Error listing replays dir.')
names = [] names = []
assert self._my_replays_scroll_width is not None assert self._my_replays_scroll_width is not None
@ -488,19 +491,13 @@ class WatchWindow(ba.Window):
'tab': self._current_tab 'tab': self._current_tab
} }
except Exception: except Exception:
ba.print_exception('error saving state for', self.__class__) ba.print_exception(f'Error saving state for {self}.')
def _restore_state(self) -> None: def _restore_state(self) -> None:
try: try:
try: sel_name = ba.app.window_states.get(self.__class__.__name__,
sel_name = ba.app.window_states[ {}).get('sel_name')
self.__class__.__name__]['sel_name'] current_tab = ba.app.config.get('Watch Tab')
except Exception:
sel_name = None
try:
current_tab = ba.app.config['Watch Tab']
except Exception:
current_tab = None
if current_tab is None or current_tab not in self._tab_buttons: if current_tab is None or current_tab not in self._tab_buttons:
current_tab = 'my_replays' current_tab = 'my_replays'
self._set_tab(current_tab) self._set_tab(current_tab)
@ -517,7 +514,7 @@ class WatchWindow(ba.Window):
sel = self._tab_buttons[current_tab] sel = self._tab_buttons[current_tab]
ba.containerwidget(edit=self._root_widget, selected_child=sel) ba.containerwidget(edit=self._root_widget, selected_child=sel)
except Exception: except Exception:
ba.print_exception('error restoring state for', self.__class__) ba.print_exception(f'Error restoring state for {self}.')
def _back(self) -> None: def _back(self) -> None:
from bastd.ui import mainmenu from bastd.ui import mainmenu

View File

@ -1,5 +1,5 @@
<!-- THIS FILE IS AUTO GENERATED; DO NOT EDIT BY HAND --> <!-- THIS FILE IS AUTO GENERATED; DO NOT EDIT BY HAND -->
<h4><em>last updated on 2020-06-16 for Ballistica version 1.5.5 build 20070</em></h4> <h4><em>last updated on 2020-06-16 for Ballistica version 1.5.5 build 20071</em></h4>
<p>This page documents the Python classes and functions in the 'ba' module, <p>This page documents the Python classes and functions in the 'ba' module,
which are the ones most relevant to modding in Ballistica. If you come across something you feel should be included here or could be better explained, please <a href="mailto:support@froemling.net">let me know</a>. Happy modding!</p> which are the ones most relevant to modding in Ballistica. If you come across something you feel should be included here or could be better explained, please <a href="mailto:support@froemling.net">let me know</a>. Happy modding!</p>
<hr> <hr>
@ -6620,7 +6620,7 @@ playing, the playing track will not be restarted.</p>
<hr> <hr>
<h2><strong><a name="function_ba_storagename">ba.storagename()</a></strong></h3> <h2><strong><a name="function_ba_storagename">ba.storagename()</a></strong></h3>
<p><span>storagename(basename: str) -&gt; str</span></p> <p><span>storagename(suffix: str = None) -&gt; str</span></p>
<p>Generate a (hopefully) unique name for storing things in public places.</p> <p>Generate a (hopefully) unique name for storing things in public places.</p>

View File

@ -438,7 +438,7 @@ if __name__ == '__main__':
except KeyboardInterrupt: except KeyboardInterrupt:
# Let's do a clean fail on keyboard interrupt. # Let's do a clean fail on keyboard interrupt.
# Can make this optional if a backtrace is ever useful.. # Can make this optional if a backtrace is ever useful..
sys.exit(-1) sys.exit(1)
except CleanError as exc: except CleanError as exc:
exc.pretty_print() exc.pretty_print()
sys.exit(-1) sys.exit(1)

View File

@ -369,7 +369,8 @@ class BaseEnumValue(TypedValue[T]):
except ValueError: except ValueError:
if error: if error:
raise ValueError( raise ValueError(
f'Invalid value for {self._enumtype}: {data}') f'Invalid value for {self._enumtype}: {data}'
) from None
logging.error('Ignoring invalid value for %s: %s', logging.error('Ignoring invalid value for %s: %s',
self._enumtype, data) self._enumtype, data)
data = self._default_data data = self._default_data

View File

@ -145,7 +145,7 @@ def _windows_enable_color() -> bool:
return set_conout_mode(mode, mask) return set_conout_mode(mode, mask)
except WindowsError as exc: except WindowsError as exc:
if exc.winerror == ERROR_INVALID_PARAMETER: if exc.winerror == ERROR_INVALID_PARAMETER:
raise NotImplementedError raise NotImplementedError from exc
raise raise
try: try: