diff --git a/src/app/career_session.cpp b/src/app/career_session.cpp index f0c91cb..408f0b7 100644 --- a/src/app/career_session.cpp +++ b/src/app/career_session.cpp @@ -64,6 +64,8 @@ namespace bmh::app { namespace { +// Process-wide counter that hands every CareerSession a unique id (see session_id_ in the +// constructor); the turn driver stores that id to recognise which session it belongs to. std::atomic next_session_id{1}; constexpr uint32_t kSavedCalendar = ::bmh::layout::CompetitionCalendar; @@ -72,6 +74,8 @@ constexpr uint8_t kBlockSeat = 1; constexpr uint8_t kBlockRoof = 2; constexpr uint8_t kBlockFeatures = kBlockSeat | kBlockRoof; +// True for the stadium requests that belong to the block-expansion dialog (select, total, +// feature toggle, cancel, confirm, answer tip). bool is_block_expansion_action(ui::StadiumRequestKind kind) { return kind == ui::StadiumRequestKind::expansion_select || kind == ui::StadiumRequestKind::expansion_set_total || @@ -81,6 +85,9 @@ bool is_block_expansion_action(ui::StadiumRequestKind kind) { kind == ui::StadiumRequestKind::expansion_answer_tip; } +// Fills every rank with 1 and returns 0 unless the first league's round counter is in the +// range [2, matchdays of league 0); inside that range it returns 9 for team ids >= 138 and 0 +// for all other teams. int national_opportunities_rank(const GameState& game,int team,std::array& ranks) { ranks.fill(1); const int rounds=game.league_rounds.empty()?0:int8_t(game.league_rounds.at(0)); @@ -88,17 +95,22 @@ int national_opportunities_rank(const GameState& game,int team,std::array=138?9:0; } +// Reads one byte of the executable's data at 'address': from the game's memory image when the +// address is mapped there, else from the runtime override map, else from the loaded EXE. uint8_t source_runtime_byte(const GameState& state,const std::map& runtime, const LeImage& exe,uint32_t address) { if(state.memory.has(address))return state.memory.u8(address); const auto found=runtime.find(address);return found==runtime.end()?exe.u8(address):found->second; } +// Writes one byte to the memory image when the address is mapped there, otherwise into the +// runtime override map (the EXE image itself is never modified). void source_runtime_set_byte(GameState& state,std::map& runtime, uint32_t address,uint8_t value) { if(state.memory.has(address))state.memory.set8(address,value); else runtime[address]=value; } +// Little-endian 32-bit read built from four source_runtime_byte reads. uint32_t source_runtime_u32(const GameState& state,const std::map& runtime, const LeImage& exe,uint32_t address) { return uint32_t(source_runtime_byte(state,runtime,exe,address)) | @@ -107,6 +119,8 @@ uint32_t source_runtime_u32(const GameState& state,const std::map& runtime,const LeImage& exe) { page.decorated=source_runtime_byte(state,runtime,exe,::bmh::layout::PlainBackground)==0; @@ -116,11 +130,19 @@ void apply_balance_source_style(ui::BalanceState& page,const GameState& state, page.cached_backdrop=source_runtime_u32(state,runtime,exe,::bmh::layout::CareerSession_ApplyBalanceSourceStyle_ExecutableField)!=0; } +// Little-endian 32-bit read from a saved match-group descriptor (throws via at() when short). uint32_t saved_group_u32(const Bytes& bytes, size_t offset) { return uint32_t(bytes.at(offset)) | (uint32_t(bytes.at(offset + 1)) << 8) | (uint32_t(bytes.at(offset + 2)) << 16) | (uint32_t(bytes.at(offset + 3)) << 24); } +// Turn-cursor restore helpers (this and the next three functions plus restore_saved_turn_cursor). +// They rebuild the in-memory MatchGroup of a day that was saved in the middle of the desk loop, +// from the saved descriptors, fixtures and results. They never draw random numbers and never +// replay event preparation; any inconsistency throws std::runtime_error, which the caller turns +// into an "unsupported continuation" message or a load failure. +// League group: validates the descriptor (size, type 0, league id, fixture count) and copies +// the round's fixtures and results; per-match runtime arrays start empty. void initialize_saved_match_group(MatchGroup& group, const GameState& state, size_t index, int league) { group.desc = group_descriptor(state, index); @@ -152,6 +174,9 @@ void initialize_saved_match_group(MatchGroup& group, const GameState& state, siz group.spectators.assign(fixtures.size(), 0); } +// Cup group: checks the saved descriptor against the cup stage entry (stage, team count, +// match count), then rebuilds the fixture list (group stage: verified against regenerated +// fixtures; knockout: taken from the stage team list) and binds the result arrays of both legs. void initialize_saved_cup_group(MatchGroup& group, const GameState& state, size_t index, int cup_id, int entry_index) { const StaticMemory& mem = state.memory; @@ -284,6 +309,8 @@ void initialize_saved_cup_group(MatchGroup& group, const GameState& state, size_ group.spectators.assign(size_t(group.matches()), 0); } +// Follows the chain of stage entries of a cup and returns the first stage whose round counter +// has not reached its round count; -1 when the cup is unknown or finished. int current_cup_stage(const StaticMemory& mem, int cup_id) { int entry = find_cup(mem, cup_id); if (entry < 0) return -1; @@ -297,6 +324,9 @@ int current_cup_stage(const StaticMemory& mem, int cup_id) { return -1; } +// Replay group (cup type 9): rebuilds the replay day from the postponed-match records of 'day', +// checks each against the league schedule and result marker, and recreates the two transient +// replay buffers that are not part of a save. void initialize_saved_replay_group(MatchGroup& group, GameState& state, size_t index, int entry_index, int day) { constexpr uint32_t kPostponed = ::bmh::layout::Postponed; @@ -375,6 +405,11 @@ void initialize_saved_replay_group(MatchGroup& group, GameState& state, size_t i group.spectators.assign(replay_fixtures.size(), 0); } +// Re-establishes the turn driver after loading a save that was written mid-day: validates the +// saved desk position / active manager / manager order, handles the season-end desk, compares +// the calendar entry with the saved competition flags, rebuilds the league and cup groups and +// starts the driver. Competitions that cannot be resumed safely set 'unsupported_continuation' +// (a player-visible text) instead of throwing; broken save data throws. void restore_saved_turn_cursor(TurnDriver& driver, GameState& state, const Database& db, uint64_t session_id, uint64_t revision, std::string& unsupported_continuation) { @@ -542,6 +577,9 @@ void restore_saved_turn_cursor(TurnDriver& driver, GameState& state, const Datab // The league structure of the loaded game (schedule.hpp): sizes LeagueSizes (German // 18 18 18 18 18 12 12 12 12, English 20 20 20 20 10 12 12 12 12) and calendar groups. +// Installs the league structure and text/rule tables of the loaded game version from the +// executable image into the global schedule, message, career, environment, badge and calendar +// tables, so the same engine runs German and English data. static void install_league_sizes(const LeImage& exe) { uint8_t sizes[kLeagueCount]; for (int l = 0; l < kLeagueCount; ++l) sizes[l] = exe.u8(::bmh::layout::LeagueSizes + uint32_t(l)); @@ -569,6 +607,10 @@ static void install_league_sizes(const LeImage& exe) { install_calendar_rules(exe); } +// Constructor for a new career: loads the executable, database, texts and start data from the +// data directory, installs the league tables and rule data, sets up the turn driver flags from +// the executable, builds the start state and runs the career start up to the first dialog. +// Throws std::runtime_error when the start state is rejected. CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_seed) : data_directory_(data), exe_(load_le(ui::asset_path(data, "BMH.exe"))), db_(load_database(ui::asset_path(data, "M3D.MAN"))), @@ -595,6 +637,10 @@ CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_ throw std::runtime_error("career start: " + report.reason); } +// Constructor for a loaded career: same data/engine setup as the new-career constructor, then +// reads the native .FBM save, rebuilds the GameState, rebinds the competition pointers, lets a +// national coach take the national team over again, restores the random seed and the saved turn +// cursor (a mid-day save). A non-native save or inconsistent data throws. CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_seed, const std::filesystem::path& save_path) : data_directory_(data), exe_(load_le(ui::asset_path(data, "BMH.exe"))), db_(load_database(ui::asset_path(data, "M3D.MAN"))), @@ -632,8 +678,12 @@ CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_ capture_source_desk_callargs(); } +// Maps a master-database club index to the runtime team slot, or -1 when it is not found. +// The overload below does the lookup in a given state: clubs travel with their name offset when +// the league tables reshuffle, so the slot is found by matching that offset. int CareerSession::runtime_club(int master) const { return runtime_club(g_, master); } +// Same lookup inside the given state (see above); -1 when no club carries the master entry name offset. int CareerSession::runtime_club(const GameState& state, int master) const { // ClubsChangePlaces moves a club together with its name: the club whose name offset is the // master entry's is the one the manager chose @@ -643,8 +693,11 @@ int CareerSession::runtime_club(const GameState& state, int master) const { return -1; } +// Club-selection context (runtime slot to master club order) of the live state at 'revision'. ui::SelectionContext CareerSession::selection_context(uint64_t revision) const { return selection_context_for(g_, revision); } +// Same for an arbitrary state (e.g. the join draft); a club whose name offset matches no master +// entry keeps its own index. ui::SelectionContext CareerSession::selection_context_for(const GameState& state, uint64_t revision) const { ui::SelectionContext c; c.revision = revision; @@ -661,6 +714,8 @@ ui::SelectionContext CareerSession::selection_context_for(const GameState& state return c; } +// Lists the managers already in the game (slot, club, name, start league, portrait) as the +// choices a joining player has to avoid; throws FormatError when a manager team is invalid. std::vector CareerSession::manager_choices(uint64_t revision) const { const auto context = selection_context(revision); std::vector choices; @@ -680,6 +735,16 @@ std::vector CareerSession::manager_choices(uint64_t revision) return choices; } +// Manager join (add a human manager to a running career) follows a draft pattern: begin copies +// the state/random generators into manager_join_, confirm_manager_join adds one manager to the +// draft (restoring the draft on failure) and commit_manager_join swaps the draft into the live +// state only if the live career is byte-identical to what the draft started from. +// The members of the setup/club-information family below refuse to run while another modal +// owner is open (balance draft, strengths, top scorers, stadium block expansion, other games) +// and then report the error text "strengths_active". +// Begin: needs the menu-29 desk request of the current revision on the current manager's desk +// (not the national team), options that only grow the manager count (max 4) and keep all other +// options; returns false with 'error' set on any mismatch. bool CareerSession::begin_manager_join(const ui::DeskRequest& origin, const ui::SetupOptions& options, uint64_t revision, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || @@ -718,15 +783,20 @@ bool CareerSession::begin_manager_join(const ui::DeskRequest& origin, const ui:: } catch (const std::exception& e) { error = e.what(); return false; } } +// Selection context of the join draft; throws FormatError when no join is in progress. ui::SelectionContext CareerSession::manager_join_context() const { if (!manager_join_) throw FormatError("join: no draft"); return selection_context_for(manager_join_->state, manager_join_->context_revision); } +// True when the draft holds one choice per requested manager. bool CareerSession::manager_join_complete() const { return manager_join_ && manager_join_->choices.size() == size_t(manager_join_->options.managers); } +// Validates one choice (next slot, current roster revision, name, league, strength, portrait, +// club known and not already taken) and adds it to the draft. On failure the draft is rolled +// back to its copy from before the call and false is returned with 'error'. bool CareerSession::confirm_manager_join(const ui::ManagerChoice& choice, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } @@ -759,6 +829,10 @@ bool CareerSession::confirm_manager_join(const ui::ManagerChoice& choice, std::s } catch (const std::exception& e) { manager_join_ = std::move(before); error = e.what(); return false; } } +// Commit: requires a complete draft whose origin revision is the current one and whose live +// state and random counters are unchanged since begin. On success the draft replaces the live +// state, the revision advances by one and the new desktop/preparation projections are returned; +// on any failure the checkpoint is restored, the revision is left unchanged and false is returned. bool CareerSession::commit_manager_join(ui::CareerInitializationResult& result, uint64_t& revision, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || @@ -795,6 +869,8 @@ bool CareerSession::commit_manager_join(ui::CareerInitializationResult& result, } } +// Writes the setup-dialog options into the game memory and prunes the calendar (no league game / +// no World Cup game) as the original setup screen does at the start of a new game. void CareerSession::apply_options(const ui::SetupOptions& o) { // SetupScreen2 takes the four numbers over when the options dialog is left StaticMemory& mem = g_.memory; @@ -830,6 +906,9 @@ void CareerSession::apply_options(const ui::SetupOptions& o) { options_applied_ = true; } +// New-career manager entry: refuses while a modal owner is open, checks the chosen league is +// visible for human management, applies the options on the first call and adds the manager in +// the next free slot. Returns false with 'error' on failure. bool CareerSession::confirm_manager(const ui::SetupOptions& options, const ui::ManagerChoice& choice, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } @@ -864,6 +943,11 @@ bool CareerSession::confirm_manager(const ui::SetupOptions& options, const ui::M return true; } +// Club-information modal family (enter, change category, player redraw, national action, +// pending offers): each member refuses to run while another modal owner is open and clears +// 'error' first. The ones that change state work on copies and assign them back only after +// success. +// Enter: opens the club info entry for 'team'; nullopt plus 'error' on an invalid team. std::optional CareerSession::enter_club_information(int team, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; } @@ -872,6 +956,7 @@ std::optional CareerSession::enter_club_information(int team, std catch (const std::invalid_argument& e) { error = e.what(); return std::nullopt; } } +// Switches the club info category for 'team'; nullopt plus 'error' when it is invalid. std::optional CareerSession::change_club_information_category(int team, int requested, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || @@ -881,6 +966,7 @@ std::optional CareerSession::change_club_information_category(int team, catch (const std::invalid_argument& e) { error = e.what(); return std::nullopt; } } +// Redraws a player detail card; random generators advance only if the redraw succeeded. std::optional CareerSession::redraw_club_player_detail( const ClubPlayerDetailSelection& selection, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || @@ -899,6 +985,8 @@ std::optional CareerSession::redraw_club_player_detail( } } +// Applies the national-team add/remove action of a player card on a staged copy; the copy is +// committed only when the engine reports no reason. Returns whether the action was applied. std::optional CareerSession::dispatch_club_player_national_action( const ClubPlayerDetailSelection& selection, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || @@ -919,6 +1007,10 @@ std::optional CareerSession::dispatch_club_player_national_action( } } +// Processes the pending transfer offers of a player card. Rejects a stale revision or a nested +// pending-offer/market dispatch, works on copies and commits them when at least one offer was +// processed. The revision is bumped here unless a calendar advance is active: then the outer +// driver publishes the revision when it returns. std::optional CareerSession::dispatch_club_player_pending_offers( const ClubPlayerDetailSelection& selection, uint64_t expected_revision, const PendingOfferHooks& hooks, uint64_t& revision, std::string& error) { @@ -958,6 +1050,8 @@ std::optional CareerSession::dispatch_club_player_pending_of } } +// Seeds the process-only byte map used by the club modals with their start values from the +// executable; these values are never written to a save. void CareerSession::initialize_club_modal_runtime() { // Setup clears the boot-only dialog mode before either creating or loading // a career. This process flag is deliberately absent from native saves. @@ -969,12 +1063,15 @@ void CareerSession::initialize_club_modal_runtime() { club_modal_runtime_.emplace(address,exe_.u8(address)); } +// Collects the executable bytes and rating tables the Sportschau screen reads. SportschauSourceOptions CareerSession::sportschau_source_options() const { return {source_runtime_byte(g_, club_modal_runtime_, exe_, ::bmh::layout::CareerSession_SportschauSourceOptions_ExecutableField), source_runtime_byte(g_, club_modal_runtime_, exe_, ::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableField2), exe_.u16(::bmh::layout::TeamsWithSquads), sportschau_rating_tables(exe_)}; } +// Builds the service callbacks of the club modal on a given (staged) state, generators and +// runtime byte map, so the modal can run on a copy and be committed or dropped by the caller. ClubModalServices CareerSession::staged_club_modal_services(GameState& state, GameRandom& game,WatcomRandom& rand,std::map& runtime) { ClubModalServices services; @@ -1015,6 +1112,8 @@ ClubModalServices CareerSession::staged_club_modal_services(GameState& state, return services; } +// Same services bound to the live state (non-transactional); pending offers go through +// dispatch_club_player_pending_offers. Throws when another modal owner is open. ClubModalServices CareerSession::live_club_modal_services(uint64_t& revision) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) throw FormatError("strengths_active"); @@ -1031,6 +1130,9 @@ ClubModalServices CareerSession::live_club_modal_services(uint64_t& revision) { } namespace { +// Writes the process scratch bytes (league, group, date pieces, strength sums) that the +// original leaves behind after drawing the pairings page, so later reads see the same values. +// Bytes go to the memory image when mapped there, else to the runtime map. void pairings_runtime_draw(GameState& g,std::map& runtime, const ui::LeaguePairingsState& page,const LeImage& exe) { const auto put=[&](uint32_t at,uint8_t v) { @@ -1071,6 +1173,8 @@ void pairings_runtime_draw(GameState& g,std::map& runtime, if(computer_tip)put(tip_preference,uint8_t(g.memory.u8(tip_preference)&0xef)); } +// True when 'team' belongs to one of the human managers or to the national team record of a +// national coach; throws FormatError when the manager count is missing or invalid. bool other_games_source_manager_owned(const GameState& g,int team) { if(team<0||!g.memory.has(::bmh::layout::ManagerCount)) throw FormatError("other games: missing Source manager count for club detail redraw"); @@ -1087,6 +1191,9 @@ bool other_games_source_manager_owned(const GameState& g,int team) { return false; } +// Replays the side effects of drawing the other-games page: five ordered team-average +// calculations per displayed club (some of which draw random numbers) and the scratch bytes +// they leave. void other_games_source_redraw_effects(GameState& g,WatcomRandom& rand, std::map& runtime,const OtherGamesProjection& projection, const LeImage& exe) { @@ -1115,6 +1222,8 @@ void other_games_source_redraw_effects(GameState& g,WatcomRandom& rand, } } +// True when two other-games checkpoints agree on state, random generators, runtime bytes, +// selection and owner identity, i.e. nothing observable changed in between. bool same_other_games_live_baseline(const CareerSession::OtherGamesCheckpoint& before, const CareerSession::OtherGamesCheckpoint& after) { if(save_stream(before.state)!=save_stream(after.state)|| @@ -1140,6 +1249,8 @@ bool same_other_games_live_baseline(const CareerSession::OtherGamesCheckpoint& b a.page.projection.display_mode==b.page.projection.display_mode; } +// Compares the runtime-only fields of two states (callbacks by target type); used to check the +// strengths view left the game unchanged. bool same_strengths_runtime_state(const GameState& a,const GameState& b) { const auto same_callback=[](const auto& lhs,const auto& rhs) { return bool(lhs)==bool(rhs)&&(!lhs||lhs.target_type()==rhs.target_type()); @@ -1160,8 +1271,11 @@ bool same_strengths_runtime_state(const GameState& a,const GameState& b) { same_callback(a.transfer_decision_observer,b.transfer_decision_observer); } +// Reinterprets the low byte of 'value' as a signed byte. int8_t source_byte(int value) { return static_cast(uint8_t(value)); } +// Builds the "first-end" round range label of the league table from a text template, patching +// the two two-digit numbers in the German or English layout. std::string source_table_range_label(const TextDb& texts,int first,int end) { // DE50860 patches offsets 4/7 of its nine-byte TEXTD82 buffer. EN1e83f // patches 0/3 of the full " 0-34 only" string instead (the final y is live). @@ -1178,6 +1292,8 @@ std::string source_table_range_label(const TextDb& texts,int first,int end) { return raw; } +// Clamps the table end round to the played round when it is out of range, ensures end > first +// and refreshes the retained range label; throws FormatError when the league is unknown. void source_table_normalize_range(CareerSession::LeagueFamilyOwner::TableOwner& table, const GameState& game,int league,const TextDb& texts) { if(league<0||league>=int(game.league_rounds.size())) @@ -1194,6 +1310,8 @@ void source_table_normalize_range(CareerSession::LeagueFamilyOwner::TableOwner& texts,source_byte(table.first_round),source_byte(table.end_round)); } +// True when a league-family identity still describes the live game: same active manager, club, +// club identity, date, default league and the stored settings/display-mode words. bool source_table_identity_is_live(const GameState& game,const ui::StrengthsIdentity& id) { if(id.manager<0||id.manager>3||id.league<0||id.league>=bmh::kLeagueCount|| !game.memory.has(::bmh::layout::ActiveManager)||game.memory.u8(::bmh::layout::ActiveManager)!=id.manager|| @@ -1211,6 +1329,8 @@ bool source_table_identity_is_live(const GameState& game,const ui::StrengthsIden game.memory.u16(family)==id.expected_family_word; } +// True when a table request carries no stray fields (no target child, team, row or dialog reply; +// league id only if the selector variant is allowed) and the expected control index. bool canonical_table_envelope(const ui::LeagueFamilyRequest& request,int control_index=-1, bool allow_selector_league=false) { return request.target_child==0&&request.runtime_team==-1&&request.expected_club_identity==-1&& @@ -1219,11 +1339,14 @@ bool canonical_table_envelope(const ui::LeagueFamilyRequest& request,int control !request.table_dialog_reply; } +// Sets the table aggregation flag bits from the clear bits 4 and 2 of the display-mode word. void source_table_apply_entry_flags(CareerSession::LeagueFamilyOwner::TableOwner& table,uint16_t word) { if((word&4)==0)table.aggregation_flags=uint8_t(table.aggregation_flags|1); if((word&2)==0)table.aggregation_flags=uint8_t(table.aggregation_flags|2); } +// Packs a table owner's round range, flags, display word and optional accepted engine table +// (or forecast marker) into the projection context used to render the league table page. ui::LeagueTableProjectionContext source_table_context( const CareerSession::LeagueFamilyOwner::TableOwner& table,uint16_t display_word, std::optional accepted={},bool forecast=false) { @@ -1237,6 +1360,15 @@ ui::LeagueTableProjectionContext source_table_context( } } +// League family (table / pairings / strengths and the friendly opponent table): these three +// child screens are linked under one LeagueFamilyOwner carrying a family id. Pattern: each +// entry or transition validates the identity (revision, active manager slot, club, date) and +// the neighbouring child owners, snapshots the native save stream, random seeds and runtime +// bytes into the owner, and every close/suspend compares the live state with that snapshot so +// a stale or tampered request is rejected with an error text and nothing is changed. +// Child numbers: 1 = Table, 2 = Pairings, 3 = Strengths. +// Builds the identity (manager, club, date, default league, settings words) needed to open the +// strengths screen for the active manager; returns an empty optional when anything is missing. std::optional CareerSession::strengths_open_request(uint64_t revision) const { if(!g_.memory.has(::bmh::layout::ActiveManager))return {}; const int manager=g_.memory.u8(::bmh::layout::ActiveManager); @@ -1255,6 +1387,11 @@ std::optional CareerSession::strengths_open_request(uint64 return request; } +// Opens the family at 'child' for the identity: checks no family/TeamInfo is active, the +// revision matches, the identity belongs to the active manager and club of today (or to the +// live overview owner), and that Pairings/Strengths entries have a matching child owner. +// Allocates a family id, snapshots the state into a LeagueFamilyOwner and, for the table, builds +// the page. Returns the bound identity, or an empty optional with 'error'. std::optional CareerSession::begin_league_family( ui::StrengthsIdentity identity,uint8_t child,uint64_t revision,std::string& error) { error.clear(); @@ -1310,6 +1447,9 @@ std::optional CareerSession::begin_league_family( return identity; } +// Opens the table used to pick a friendly-match opponent (child 1 with friendly_opponent set). +// Needs the strengths request of the active manager and no other child owner; the table +// display word is initialised for that picker. Any failure restores the family checkpoint. std::optional CareerSession::begin_friendly_opponent_table( uint64_t revision,std::string& error) { error.clear(); @@ -1341,6 +1481,9 @@ std::optional CareerSession::begin_friendly_opponent_tabl } } +// Checks a select_opponent request against the owned table (identity, revision, row, club +// identity key) and returns the runtime team of the chosen row, or an empty optional with 'error'. +// Does not change state. std::optional CareerSession::resolve_friendly_table_opponent( const ui::LeagueFamilyRequest& request,uint64_t revision,std::string& error) const { error.clear(); @@ -1371,6 +1514,9 @@ std::optional CareerSession::resolve_friendly_table_opponent( return normal.runtime_team_id; } +// The player picked their own club in the opponent table: restores the normal-mode bit of the +// display word, advances the family sequence and keeps the picker open. Empty optional on a +// stale or different-club request. std::optional CareerSession::acknowledge_friendly_own_club( const ui::LeagueFamilyRequest& request,uint64_t revision,std::string& error) { const auto team=resolve_friendly_table_opponent(request,revision,error); @@ -1388,6 +1534,9 @@ std::optional CareerSession::acknowledge_friendly_own_clu return next; } +// Leaves the opponent table: validates a select_opponent (not the own club) or close request, +// restores the display word, validates the new preparation projection and drops the family +// owner while advancing the revision. Failure restores the checkpoint and returns empty. std::optional CareerSession::finish_friendly_opponent_table( const ui::LeagueFamilyRequest& request,uint64_t& revision,std::string& error) { error.clear(); @@ -1424,6 +1573,10 @@ std::optional CareerSession::finish_friendly_opponent_tabl } } +// Moves the family from one child screen to another: the request, owner and 'next' identity must +// agree (same family id, manager, club, day; sequence increased by one; revision at most one +// ahead). Replaces the owner with a fresh snapshot, building the table page when the target is +// the table. Returns false with 'error' when the transition is stale or mismatched. bool CareerSession::advance_league_family(const ui::LeagueFamilyRequest& request, ui::StrengthsIdentity next,uint8_t target,uint64_t revision,std::string& error) { error.clear(); @@ -1464,6 +1617,9 @@ bool CareerSession::advance_league_family(const ui::LeagueFamilyRequest& request league_family_owner_=std::move(owner);return true; } +// True when the identity (its source_param2 holds the match minute) belongs to the currently +// open live overview: same manager, team, minute and day, and for a phase-result viewer the +// same match group. bool CareerSession::live_source_identity(const ui::StrengthsIdentity& id) const { return live_overview_owner_ && live_overview_owner_->kind != LiveOverviewKind::cup_other_games && @@ -1477,6 +1633,11 @@ bool CareerSession::live_source_identity(const ui::StrengthsIdentity& id) const live_overview_owner_->request.group_index == int(phase_result_request_->group_index))); } +// Final close of the family: the long condition re-verifies identity, child owner and that the +// live state, random generators and runtime bytes still equal the owner's snapshot. On success +// it commits staged Pairings changes (if any), draws the random stir unless a phase-result +// viewer owns that draw, resets the child owners and bumps the revision. Returns the new +// preparation projection, or an empty optional with 'error' and no change. std::optional CareerSession::close_league_family( const ui::LeagueFamilyRequest& request,uint64_t& revision,std::string& error) { error.clear();const auto& id=request.identity; @@ -1535,6 +1696,8 @@ std::optional CareerSession::close_league_family( } catch(const std::exception& e) {error=e.what();return {};} } +// Leaves the Strengths child towards Table or Pairings without a full close: checks the owner +// snapshot is unchanged, then drops the strengths owner. False with 'error' when stale. bool CareerSession::suspend_strengths_for_family(const ui::LeagueFamilyRequest& request, uint64_t revision,std::string& error) { error.clear();const auto& id=request.identity; @@ -1550,6 +1713,9 @@ bool CareerSession::suspend_strengths_for_family(const ui::LeagueFamilyRequest& strengths_owner_.reset();return true; } +// Leaves the Pairings child towards Table or Strengths: after the same snapshot checks it +// commits only the staged page/redraw changes of the draft and drops the draft. False with +// 'error' when stale or the return word is missing. bool CareerSession::suspend_pairings_for_family(const ui::LeagueFamilyRequest& request, uint64_t revision,std::string& error) { error.clear();const auto& id=request.identity; @@ -1578,6 +1744,9 @@ bool CareerSession::suspend_pairings_for_family(const ui::LeagueFamilyRequest& r league_pairings_draft_.reset();return true; } +// Prepares the manager mode word and runtime bytes before a child screen is entered, after +// validating the identity and that no other child owner or dispatch is active. False with +// 'error' otherwise. bool CareerSession::prepare_league_family_child(const ui::StrengthsIdentity& id,uint8_t child, uint64_t revision,std::string& error) { error.clear(); @@ -1616,6 +1785,10 @@ bool CareerSession::prepare_league_family_child(const ui::StrengthsIdentity& id, return true; } +// Installs (or clears) the turn driver hook that fires at the end of a match phase. The wrapper +// records the current request in phase_result_request_ for the duration of the call, only +// accepts the driver's own groups and state, and requires that any viewer is closed again before +// the engine continues. void CareerSession::set_phase_results(decltype(TurnDriver::phase_results) hook) { if (!hook) { turn_driver_.phase_results = {}; return; } turn_driver_.phase_results = [this, hook=std::move(hook)](const PhaseResultRequest& request, @@ -1624,6 +1797,7 @@ void CareerSession::set_phase_results(decltype(TurnDriver::phase_results) hook) request.group_index >= groups.size()) throw FormatError("phase results: invalid synchronous Source boundary"); phase_result_request_ = &request; + // Clears the borrowed request pointer when the hook returns or throws. struct Reset { const PhaseResultRequest*& request; ~Reset() { request = nullptr; } } reset{phase_result_request_}; hook(request, groups, state); if (live_overview_owner_ && live_overview_owner_->phase_result) @@ -1631,6 +1805,13 @@ void CareerSession::set_phase_results(decltype(TurnDriver::phase_results) hook) }; } +// Live overview group (phase-result viewer, live league table / pairings opened from a running +// match): only valid inside a calendar advance (calendar_advance_active_) with the driver +// waiting at a phase boundary. Pattern: open -> dispatch -> acknowledge; the owner snapshots the +// state and random counters when it opens and the close must find them unchanged. +// Opens the viewer at a phase boundary: copies the current group results into a staged state +// (no simulation, no random draws) and opens the overview on it; on failure the previous state +// is kept. Returns an empty optional with 'error' when no request is pending or a viewer is open. std::optional CareerSession::open_phase_results( uint64_t& revision, const Image& underlay, std::string& error) { error.clear(); @@ -1669,6 +1850,8 @@ std::optional CareerSession::open_phase_r } catch (const std::exception& e) { error = e.what(); return {}; } } +// Forwards a viewer action while the phase-result owner of the pending request is open; empty +// optional with 'error' if the viewer is missing or belongs to another group. std::optional CareerSession::dispatch_phase_results( const LiveOverviewAction& action, uint64_t& revision, std::string& error, const TransferOfferTeamInfoPresenter& team_info) { @@ -1680,12 +1863,18 @@ std::optional CareerSession::dispatch_phase return dispatch_live_overview(action, context, revision, error, team_info); } +// Opens the overview from a key press during a running match (not a phase-result viewer). std::optional CareerSession::open_live_overview( const LiveOverviewRequest& request, MatchEngine& engine, uint64_t& revision, const Image& underlay, std::string& error) { return open_running_overview(request, engine, revision, underlay, error, false); } +// Shared opener. The long guard requires an active calendar advance, no other modal owner or +// dispatch, a request that matches the driver's groups, the live state objects and the active +// manager (revision and scope included). key_slot 0 opens the league table, 1 the league +// pairings. Returns an empty optional with 'error' when the request is stale, nested or +// unauthenticated. std::optional CareerSession::open_running_overview( const LiveOverviewRequest& request, MatchEngine& engine, uint64_t& revision, const Image& underlay, std::string& error, bool phase_result) { @@ -1724,6 +1913,8 @@ std::optional CareerSession::open_running } + // Scope guard: turns calendar_advance_active_ off while the family screens run and restores the + // previous value on exit, so nested family code does not treat itself as inside the advance. struct LiveBoundaryFamilyScope { bool& active; bool previous; @@ -1799,6 +1990,9 @@ std::optional CareerSession::open_running result.pairings = std::move(page); } } else { + // Cup descriptor (not a league): the overview becomes an other-games detail page bound to the + // active cup entry, found by trying linked-page ordinals until the cup entry and competition + // id match. Anything else throws and is rolled back by the catch block below. if (request.key_slot != 0 && request.key_slot != 1) throw FormatError("live overview: invalid cup overview key slot"); const int entry_index = cup_entry_index(competition); @@ -1862,6 +2056,8 @@ std::optional CareerSession::open_running live.kind=result.kind; live.original_native=save_stream(g_); live.original_rand_seed=rand_.seed(); live.original_game_seed=game_.seed(); live.original_rand_calls=rand_.calls(); live.original_game_calls=game_.calls(); + // Commit point: the owner now holds its final kind, family identity and revision; the scope + // counter and the revision are advanced only here, after every child owner was opened. live_overview_owner_->kind=live.kind; live_overview_owner_->family_identity=live.family_identity; live_overview_owner_->request.revision=next_revision; @@ -1869,6 +2065,8 @@ std::optional CareerSession::open_running revision=next_revision; return result; } catch(const std::exception& e) { + // Failure path: restore the family, pairings and other-games checkpoints, drop the overview + // owner and put the scope counter back, so a failed open leaves no trace. restore_league_family_checkpoint(family_checkpoint); restore_league_pairings_checkpoint(pairings_checkpoint); restore_other_games_checkpoint(other_checkpoint); @@ -1879,6 +2077,13 @@ std::optional CareerSession::open_running } } +// League table dispatch group (controls, range dialog, forecast acknowledgement, league +// selector, team info). Pattern: validate the request envelope, identity, owner and that the +// live state still equals the owner snapshot; take a checkpoint; apply the change to the +// table owner; refresh the snapshot and identity (sequence + 1, revision + 1); on any failure +// restore the checkpoint and the old revision and return an empty optional with 'error'. +// Projects the table page (or the pending range dialog profile) of the owned table child; +// read-only. Empty optional with 'error' when no table owner exists or the state drifted. std::optional CareerSession::current_league_table_dispatch( std::string& error) const { error.clear(); @@ -1922,6 +2127,8 @@ std::optional CareerSession::current_league_ } catch(const std::exception& e) {error=e.what();return {};} } +// Applies one of the table's ten controls (index 0-9) to the owned table. Requires a ready +// table, a canonical request envelope and an unchanged snapshot; revision advances by one. std::optional CareerSession::dispatch_league_table_control( const ui::LeagueFamilyRequest& request,uint64_t& revision,std::string& error) { error.clear();const auto& id=request.identity; @@ -1952,6 +2159,10 @@ std::optional CareerSession::dispatch_league const auto context=source_table_context(table,word,std::move(engine),forecast); table.page=ui::league_table_from_game(g_,id.manager,league,context); }; + // Controls 0-2 set the aggregation flags and mode bits, 3 computes a forecast table (shown + // after the present acknowledgement), 4-6 toggle display bits (at least one stays set), 7 + // toggles the normal mode, 8 resets the round range to the whole season and 9 starts the + // two-step range dialog. switch(request.control_index) { case 0: table.aggregation_flags=7;word=uint16_t((word&0x0ff0)|1);break; case 1: table.aggregation_flags=1;word=uint16_t((word&0x0ff0)|2);break; @@ -2022,6 +2233,9 @@ std::optional CareerSession::dispatch_league } +// Handles the answer of the range dialog (control 9): start value first, then end value. +// Accept stores the value, cancel restores the previous range; positions and bounds of the +// reply are validated. The table returns to ready after the second step or a cancel. std::optional CareerSession::dispatch_league_table_range_reply( const ui::LeagueFamilyRequest& request,uint64_t& revision,std::string& error) { error.clear();const auto& id=request.identity; @@ -2090,6 +2304,8 @@ std::optional CareerSession::dispatch_league } catch(const std::exception& e) {restore_league_family_checkpoint(checkpoint);revision=old_revision;error=e.what();return {};} } +// The forecast page has been shown: adopts the random generator state computed with the +// forecast, returns the table to ready and rebuilds the normal page. std::optional CareerSession::acknowledge_league_forecast_present( const ui::LeagueFamilyRequest& request,uint64_t& revision,std::string& error) { error.clear();const auto& id=request.identity; @@ -2134,6 +2350,9 @@ std::optional CareerSession::acknowledge_lea } catch(const std::exception& e) {restore_league_family_checkpoint(checkpoint);revision=old_revision;error=e.what();return {};} } +// Switches the table to another league (map click) or toggles the league group, after +// checking the target is listed in the bound league map. Works on staged copies of the state, +// runtime bytes and owner and commits them only on success; returns false with 'error' otherwise. bool CareerSession::select_league_family_page(const ui::LeagueFamilyRequest& request, uint64_t revision,std::string& error) { error.clear();const auto& id=request.identity; @@ -2209,6 +2428,10 @@ bool CareerSession::select_league_family_page(const ui::LeagueFamilyRequest& req } } +// Opens the club information of a table row through the injected presenter, on a staged copy. +// Checks the visible row identity and that the presenter left the live family untouched; +// then either keeps the poach selection (card returned) or redraws the table and publishes the +// copy. Returns the refreshed identity, or an empty optional with 'error' (state restored). std::optional CareerSession::dispatch_family_table_team_info( const ui::LeagueFamilyRequest& request,uint64_t& revision,std::string& error, const TransferOfferTeamInfoPresenter& presenter, @@ -2269,6 +2492,7 @@ std::optional CareerSession::dispatch_family_table_team_i ++entry_calls;return enter(team); }; league_family_teaminfo_active_=true; + // Marks the family as inside TeamInfo while the presenter runs; cleared on every exit. struct Reset { bool& active;~Reset(){active=false;} } reset{league_family_teaminfo_active_}; const bool accepted=presenter(services,selected_team,backdrop); const auto after=league_family_checkpoint(); @@ -2335,6 +2559,9 @@ std::optional CareerSession::dispatch_family_table_team_i } catch(const std::exception& e) {restore_league_family_checkpoint(checkpoint);revision=old_revision;error=e.what();return {};} } +// After a child screen acknowledged its page, re-binds the family owner to the child's new +// identity (same family id and sequence, revision at most one ahead) and refreshes its snapshot. +// False with 'error' when the identity or child owner is stale. bool CareerSession::refresh_family_after_child(const ui::StrengthsIdentity& prior,uint8_t child, ui::StrengthsIdentity next,uint64_t revision,std::string& error) { error.clear(); @@ -2366,6 +2593,17 @@ bool CareerSession::refresh_family_after_child(const ui::StrengthsIdentity& prio league_family_owner_->runtime=club_modal_runtime_;return true; } +// Strengths / top scorers / opportunities / other games group: modal desk pages that follow +// open -> dispatch -> acknowledge. Each open_* validates the desk request (menu kind, revision, +// active manager slot, desk stage, no other modal owner) and stores an owner that snapshots the +// native stream and the random counters; each dispatch_* refuses a stale identity or a changed +// snapshot, applies one action on a copy, bumps revision and sequence and returns the new page +// plus the desktop projection. Failures return an empty optional with 'error' and change nothing. +// National-coach desk identity: while a national coach manages the national team the manager's +// team is the national slot (kNoTeam or 0x165); the club identity key is then taken from the +// spare manager record 4 (offset 0x290) instead of the club table. +// Strengths dispatch: one entry point for open, control, league select, group toggle, team info +// and close of the strengths page (also used as a child of the league family). std::optional CareerSession::dispatch_strengths( const ui::StrengthsRequest& request,uint64_t& revision,std::string& error, const TransferOfferTeamInfoPresenter& team_info,bool family_transition) { @@ -2424,6 +2662,7 @@ std::optional CareerSession::dispatch_strength error="strengths: TeamInfo presenter unavailable";return {}; } strengths_dispatch_active_=true; + // Re-entrancy flag: set while this dispatch runs (callbacks may re-enter), cleared on every exit. struct Reset { bool& active; ~Reset(){active=false;} } reset{strengths_dispatch_active_}; try { StrengthsDispatch result; @@ -2572,6 +2811,9 @@ std::optional CareerSession::dispatch_strength } catch(const std::exception& e) {error=e.what();return {};} } +// Opens the top scorers page (desk menu 20) for the active manager; refuses while the process +// timer context is active. For a national coach the club identity comes from the spare record. +// Returns the first page (goals, league scope) or an empty optional with 'error'. std::optional CareerSession::open_top_scorers( const ui::DeskRequest& request, uint64_t revision, const Image& underlay, std::string& error) { error.clear(); @@ -2653,6 +2895,8 @@ std::optional CareerSession::open_top_scorers( } } +// Applies one top scorers action: close, metric cycle (goals -> assists -> scorer -> goals) or +// scope toggle. Rejects a stale, replayed or modified owner; commits the new page on success. std::optional CareerSession::dispatch_top_scorers( const ui::TopScorersRequest& request, uint64_t& revision, std::string& error) { error.clear(); @@ -2742,6 +2986,9 @@ std::optional CareerSession::dispatch_top_sco } } +// Statistics menu (desk menu 23): flips the manager's statistics preference flags. Needs the open +// menu owner request of the current revision and the expected current flag byte; allows exactly +// one metric bit (below 0x40) or the pair 0xc0 to change. Returns false with 'error' otherwise. bool CareerSession::apply_statistics_preference(const ui::DeskRequest& owner, int manager_slot, uint8_t expected_flags, uint8_t target_flags, uint64_t& revision, std::string& error) { @@ -2773,6 +3020,9 @@ bool CareerSession::apply_statistics_preference(const ui::DeskRequest& owner, in return true; } +// Opens the opportunities page (desk menu 23) for the active manager. 'national_source_case' +// selects the national-team variant (team 0x165, league 0, identity supplied by the caller as +// 'stable_identity'). Needs the 320x240 desktop underlay. Empty optional with 'error' on failure. std::optional CareerSession::open_opportunities( const ui::DeskRequest& request,uint64_t revision,const Image& underlay,std::string& error, bool national_source_case,int stable_identity) { @@ -2809,6 +3059,8 @@ std::optional CareerSession::open_opportunities( } catch(const std::exception& e){error=e.what();return {};} } +// Closes the opportunities page or selects one of its modes (1, 2, 4 or 8) and recomputes the +// rank table; stale or modified owners are rejected. std::optional CareerSession::dispatch_opportunities( const ui::OpportunitiesRequest& request,uint64_t& revision,std::string& error) { error.clear(); @@ -2856,6 +3108,10 @@ std::optional CareerSession::dispatch_oppo } catch(const std::exception& e){error=e.what();return {};} } +// Opens the other-games overview (desk menu 5): validates the desk request and runs the entry +// changes on a staged copy (season-dependent selector byte, selector 12 insertion or removal), +// then builds the page for the remembered competition. The copy replaces the live state only +// once the page and owner exist. Empty optional with 'error' on failure. std::optional CareerSession::open_other_games( const ui::DeskRequest& request, uint64_t& revision, const Image& underlay, std::string& error) { error.clear(); @@ -2971,6 +3227,8 @@ std::optional CareerSession::open_other_games( } } +// Applies one action of the other-games overview against the owner snapshot (a team info +// presenter may be supplied); empty optional with 'error' when the request or owner is stale. std::optional CareerSession::dispatch_other_games( const ui::OtherGamesRequest& request, uint64_t& revision, std::string& error, const TransferOfferTeamInfoPresenter& team_info) { @@ -3017,6 +3275,9 @@ std::optional CareerSession::dispatch_other_g if (stable_team < 0 || stable_team >= 138 || size_t(stable_team) >= g_.club_ids.size() || int(g_.club_ids[size_t(stable_team)]) != id.club_identity) throw FormatError("other games: stable club identity changed"); + // Team info branch: the presenter runs against a staged copy (state, both random generators, + // runtime bytes) and the live session must come back unchanged; only then is the staged copy + // committed together with the redrawn page and the owner snapshot is refreshed. if (request.action == ui::OtherGamesAction::team_info) { if (request.value < 0 || current.projection.unfinished_predecessor || !current.projection.fixtures_available) @@ -3143,6 +3404,8 @@ std::optional CareerSession::dispatch_other_g int local_cursor = other_games_owner_->participant_offset; auto mode = other_games_owner_->display_mode; bool source_new_selection = false; + // Page navigation actions (selector, linked page, previous/next round, display toggle): each is + // validated against what the current page offers, then the page is rebuilt on a staged copy. switch (request.action) { case ui::OtherGamesAction::select_competition: { if (current.projection.display_mode != OtherGamesDisplayMode::detail || request.value < 0 || @@ -3253,6 +3516,12 @@ std::optional CareerSession::dispatch_other_g } } +// Balance plan group (desk menu 28): the plan is edited in a draft (BalanceDraft) that holds a +// copy of the state, random generators and runtime bytes. Pattern: open -> edit actions on the +// draft -> close; closing may stage a warning that needs a confirmation, and only the final +// close or confirmation moves the draft into the live state and bumps the revision. +// Opens the balance plan for the active manager's club; empty optional with 'error' on a stale, +// nested or unsupported opening (any other modal owner or dispatch counts as nested). std::optional CareerSession::open_balance_plan( const ui::DeskRequest& request,uint64_t revision,const Image& underlay,std::string& error) { error.clear(); @@ -3298,6 +3567,10 @@ std::optional CareerSession::open_balance_plan( } catch(const std::exception& e) {error=e.what();return {};} } +// Applies one balance action to a copy of the draft: edit a row, cycle the view, take actual +// values, close, or confirm a staged warning close. Rejects a stale identity or a live state +// that differs from the draft's origin. Only a closing action commits the draft and bumps the +// revision; a staged warning keeps the draft open. Empty optional with 'error' on failure. std::optional CareerSession::dispatch_balance_plan( const ui::BalanceRequest& request,uint64_t& revision,std::string& error) { error.clear(); @@ -3415,6 +3688,11 @@ std::optional CareerSession::dispatch_balance_pl } catch(const std::exception& e) {error=e.what();return {};} } +// League pairings group (desk menu 1): like the balance plan it works on a draft copy +// (LeaguePairingsDraft) that remembers the active match groups and referee profiles of the turn +// driver, so a draft is only valid while those are unchanged. +// Opens the pairings page for the manager; empty optional with 'error' on a stale, nested or +// unsupported opening. std::optional CareerSession::open_league_pairings( const ui::DeskRequest& request,uint64_t revision,std::string& error) { error.clear(); @@ -3443,6 +3721,9 @@ std::optional CareerSession::open_league_pairings( } catch(const std::exception& e) {error=e.what();return std::nullopt;} } +// Refuses to continue while the original's process timer is running (not implemented), then asks +// the pairings source for the active-match packet of the running groups and records the active +// group and phase in the owner. Returns the packet, or nothing when no match group is active. std::optional CareerSession::validate_normal_pairings_group( const GameState& state,LeaguePairingsOwner& owner, const std::map& runtime) const { @@ -3462,12 +3743,18 @@ std::optional CareerSession::validate_normal_pairing return packet; } +// Applies one pairings event (page change, computer tip, team info, close) to a copy of the +// draft. The live state must still equal the draft's origin (live_matches below). On close the +// draft is committed and the revision advances; otherwise a new page is returned and the draft +// refreshed. Empty optional with 'error' when stale, nested or a presenter stops. std::optional CareerSession::dispatch_league_pairings( const ui::LeaguePairingsRequest& request,uint64_t& revision,std::string& error, const TransferOfferTeamInfoPresenter& team_info) { if (league_family_teaminfo_active_ || balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; } error.clear(); + // True while the live state, random counters, runtime bytes, match groups and referee profiles + // still equal what the draft started from. const auto live_matches=[&] { if(!league_pairings_draft_)return false; const auto& d=*league_pairings_draft_; @@ -3545,6 +3832,9 @@ std::optional CareerSession::dispatch_lea } namespace { +// Transfer editor / market group (helpers first). Projects the engine's transfer offer editor +// owner into the UI state: the quote fields, calculator profiles and, unless the editor is +// closed, the incoming-offer decision panel read from the four offer rows of the market list. ui::OutgoingTransferEditorState transfer_offer_projection(const GameState& game, const TransferOfferEditorState& owner, uint64_t revision, bool gradient) { ui::OutgoingTransferEditorState out; @@ -3593,11 +3883,13 @@ ui::OutgoingTransferEditorState transfer_offer_projection(const GameState& game, } } +// Public wrapper so other code (loan return offers) can reuse the editor projection. ui::OutgoingTransferEditorState loan_return_offer_editor_projection( const GameState& game, const TransferOfferEditorState& owner, uint64_t revision, bool gradient) { return transfer_offer_projection(game, owner, revision, gradient); } +// Maps a UI field edit onto the engine's transfer offer editor edit and returns the new owner. TransferOfferEditorState edit_transfer_offer_from_ui(GameState& game, const TransferOfferEditorState& owner, const ui::OutgoingTransferRequest& request, GameRandom& game_random, WatcomRandom& watcom_random) { @@ -3606,6 +3898,14 @@ TransferOfferEditorState edit_transfer_offer_from_ui(GameState& game, game_random, watcom_random); } +// Transfer market request family (open offer, poach, editor events, quote preview, market +// actions): each entry validates the request revision, the active manager slot and the manager's +// club, refuses nested modals (market_dispatch_active_ and the other owners), works on copies of +// the state and both random generators and commits them only on success. The revision is +// advanced only where something observable changed. Failures return an empty optional and an +// error text. +// Opens the buyer's offer editor for a marked market row after checking the row identity +// against the market list in memory; the editor owner and its revision are stored on success. std::optional CareerSession::open_transfer_offer( const ui::TransferMarketRequest& request, uint64_t& revision, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || @@ -3661,6 +3961,9 @@ std::optional CareerSession::open_tr } catch (const std::exception& e) { error = e.what(); return std::nullopt; } } +// Starts a poaching attempt for a squad slot: the attempt draws random numbers, so the revision +// advances whenever the result is not invalid; a ready attempt also opens the offer editor on +// the special poach row and remembers the attempt in poach_. std::optional CareerSession::open_poach( int manager_slot, int squad_slot, uint64_t& revision, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || @@ -3702,6 +4005,9 @@ std::optional CareerSession::open_poach( } catch (const std::exception& e) { error = e.what(); return std::nullopt; } } +// Closes the table opened only to choose a poach target: needs an unchanged table owner, then +// restores the display word and drops the family owner without a family close. False with +// 'error' if stale. bool CareerSession::close_poach_table_selection(const ui::LeagueFamilyRequest& request,std::string& error) { error.clear(); if(!poach_table_selection_ || request.kind!=ui::LeagueFamilyRequestKind::close || request.from_child!=1 || @@ -3722,6 +4028,11 @@ bool CareerSession::close_poach_table_selection(const ui::LeagueFamilyRequest& r league_family_owner_.reset();return true; } +// Poach flow driven by UI callbacks: checks the request is a pristine open_poach request of the +// current revision (320x240 backdrop, nothing else open), then reports attempts-used or +// transfer-ban notices, or lets the player pick a squad player in a table on a cloned session +// and opens the poach from that choice. The UI acknowledges through 'accept'; any failure, +// including a session changed by the acknowledgement, restores the checkpoint and revision. bool CareerSession::dispatch_poach_ui(const ui::TransferMarketRequest& request, const Image& backdrop, const PoachPlayerSelector& select, const PoachUiAccept& accept, uint64_t& revision, std::string& error) { @@ -3829,6 +4140,10 @@ bool CareerSession::dispatch_poach_ui(const ui::TransferMarketRequest& request, } } +// Applies one editor event (field quote change, submit, cancel, team info, player info) to the +// open offer editor: identity and quote must match the owner and the posted row must equal the +// single field change. Runs on copies; the revision rises only if state, runtime bytes or a +// random generator actually changed. A closing editor ends a poach attempt and clears the owner. std::optional CareerSession::dispatch_transfer_offer( const ui::OutgoingTransferRequest& request, const HumanBuyerSaleHooks& presenters, uint64_t& revision, std::string& error, @@ -3950,6 +4265,9 @@ std::optional CareerSession::dispatc } catch (const std::exception& e) { error = e.what(); return std::nullopt; } } +// Quotes a purchase, lender snapshot or squad row preview (the listing identity is re-checked) +// using a copy of the W random stream; the stream and revision are updated only if the quote +// and its projection both succeed. std::optional CareerSession::preview_transfer_market( const ui::TransferMarketRequest& request, uint64_t& revision, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || @@ -4023,6 +4341,10 @@ std::optional CareerSession::previ } } +// Direct market actions of a human manager: review offers, submit a bid, list a player. Needs +// a request of the current revision for the active manager's club; loans and marked batches are +// not accepted here. The allocator gate comes from the turn driver, never from the presenter. +// The staged copy is committed (revision plus one) only if something changed. std::optional CareerSession::dispatch_transfer_market( const ui::TransferMarketRequest& request, const HumanBuyerSaleHooks& presenters, uint64_t& revision, std::string& error, @@ -4157,9 +4479,14 @@ std::optional CareerSession::dispatch_transfer_market( } } +// Finishes the career setup after all managers are chosen: refuses while a modal owner is open +// and runs the season setup and first steps with calendar_advance_active_ set (restored by +// AdvanceReset). Returns false with 'error' (the engine's reason) on failure. bool CareerSession::finish(ui::CareerInitializationResult& result, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + // calendar_advance_active_ marks the span in which the calendar is being advanced; it is set for + // the whole setup/turn and restored by the scope guard below, so nested entries are safe. const bool previous_advance = calendar_advance_active_; calendar_advance_active_ = true; struct AdvanceReset { bool& active; bool previous; ~AdvanceReset() { active = previous; } } @@ -4202,6 +4529,13 @@ bool CareerSession::finish(ui::CareerInitializationResult& result, std::string& return true; } +// Turn driver entry (advance_turn): the player presses "Weiter" at a desk. Stages of the driver +// that count as a desk are MatchdayDesks and SeasonEndDesk; while the day is played the claimed +// turn is marked Failed until it completes. Every refusal below (open modal owner, completed +// career, saved turn that cannot be continued, stale revision or manager slot, exhausted +// cursor) returns a Failed result with the reason and leaves the state untouched. +// Order of work: resolve the manager's pending offers on staged copies (all or nothing), then +// advance the driver to the next desk, then publish the new revision and the results view. TurnAdvanceResult CareerSession::dispatch_kickoff(const ui::DeskRequest& request, uint64_t& revision, std::string& error) { error.clear(); @@ -4256,6 +4590,7 @@ TurnAdvanceResult CareerSession::dispatch_kickoff(const ui::DeskRequest& request result.reason = error; return result; } + // Builds the result that keeps the player at the current desk (revision unchanged) with 'reason'. const auto remain_at_desk = [&](TurnDeskKind kind, std::string reason) { if (reason.empty()) reason = "post-desk pending presenter stopped"; error = std::move(reason); @@ -4275,6 +4610,8 @@ TurnAdvanceResult CareerSession::dispatch_kickoff(const ui::DeskRequest& request // Pending decisions and their cursor checks must complete together or // restore the previous desk. Once simulation starts, its terminal failure // cursor must stay claimed: external presentation cannot be rolled back. + // Transaction around the pending-offer decisions: if the function returns before the driver + // claims the turn, the destructor restores the checkpoint taken at entry (state, revision). struct KickoffTransaction { CareerSession& session; uint64_t& revision; @@ -4288,10 +4625,14 @@ TurnAdvanceResult CareerSession::dispatch_kickoff(const ui::DeskRequest& request } ~KickoffTransaction() { restore(); } } transaction{*this, revision, advertising_session_checkpoint(revision)}; + // Rolls the transaction back, then stays at the desk with 'reason'. const auto stop_at_desk = [&](TurnDeskKind kind, std::string reason) { transaction.restore(); return remain_at_desk(kind, std::move(reason)); }; + // calendar_advance_active_ marks the span in which the turn driver plays the day; live overviews + // and live settings need it, desk modals refuse to open while it is set. The scope guard + // (AdvanceReset) restores the previous value on every exit. const bool previous_advance = calendar_advance_active_; calendar_advance_active_ = true; struct AdvanceReset { bool& active; bool previous; ~AdvanceReset() { active = previous; } } @@ -4371,6 +4712,8 @@ TurnAdvanceResult CareerSession::dispatch_kickoff(const ui::DeskRequest& request // Keep the checkpoint from before the complete pending decision batch so a // missing decision owner cannot commit its Native cursor cleanup or leave // an expired player partially advanced. + // Kept so a contract-expiry or loan stop during the month change can still undo the already + // resolved pending decisions; the transaction itself is released just below. std::optional contract_expiry_checkpoint = transaction.before; transaction.before.reset(); // claim the completed decision batch before simulation callbacks turn_driver_.reality_rules = &exe_; @@ -4409,6 +4752,10 @@ TurnAdvanceResult CareerSession::dispatch_kickoff(const ui::DeskRequest& request } +// Mailbox actions on one of the 40 entries for the active manager: keep toggle or delete. The +// request must carry the current revision, the active manager slot and the expected entry bytes +// (stale entries are refused); the manager's bit in the recipient or kept word is flipped and the +// revision advances. Returns false with a player-visible German text in 'error' otherwise. bool CareerSession::dispatch_mailbox(const ui::MailboxActionRequest& request, uint64_t& revision, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || @@ -4470,6 +4817,8 @@ bool CareerSession::dispatch_mailbox(const ui::MailboxActionRequest& request, ui return true; } +// Returns the mailbox page when the active human manager still has the notification bit set, +// nothing otherwise (no change of state). std::optional CareerSession::pending_mailbox_notification(uint64_t revision) const { if (!g_.memory.has(::bmh::layout::ActiveManager)) return std::nullopt; const int manager = int(g_.memory.u8(::bmh::layout::ActiveManager)); @@ -4480,6 +4829,8 @@ std::optional CareerSession::pending_mailbox_notification(uint return ui::mailbox_state_from_game(g_, manager, revision); } +// Acknowledges closing the mailbox for the active manager: clears only that manager's +// notification bit (kept outside the saved data, so the revision is not advanced). bool CareerSession::acknowledge_mailbox_close(const ui::MailboxCloseRequest& request, uint64_t revision, std::string& error) { if (!g_.memory.has(::bmh::layout::ActiveManager) || request.manager_slot < 0 || request.manager_slot >= 4 || @@ -4499,6 +4850,12 @@ bool CareerSession::acknowledge_mailbox_close(const ui::MailboxCloseRequest& req return true; } +// Settings group (desk settings, live settings, settings files). The options grid has 20 rows x 9 +// columns stored as 180 bytes: columns 0-6 are two-state switches, 7 and 8 numeric steppers. +// Write of one cell: refuses while a scoped settings owner is open unless called by it, checks +// the active manager, revision and that the posted raw block still equals the saved one, then +// applies the allowed edit (locks and original limits respected) and bumps the revision. +// Returns false with a player-visible German text in 'error' otherwise. bool CareerSession::dispatch_settings(const ui::SettingsWriteRequest& request, uint64_t& revision, std::string& error) { if ((live_settings_owner_ && !live_settings_dispatch_active_) || @@ -4625,6 +4982,10 @@ bool CareerSession::dispatch_settings(const ui::SettingsWriteRequest& request, u return true; } +// Opens the settings page from a running match (the 'S' request): only inside a calendar advance +// with the engine bound to this session, the manager at the active desk and no other modal +// owner. Works on a staged copy of the state and runtime bytes, commits it together with the new +// owner and revision on success; empty optional with 'error' on failure. std::optional CareerSession::open_live_settings( const LiveSettingsRequest& request,MatchEngine& engine,uint64_t& revision,std::string& error) { error.clear(); @@ -4692,6 +5053,9 @@ std::optional CareerSession::open_live_se } } +// Applies one action of the open live settings page (cell write or settings file request). The +// owner snapshot, engine view, match groups and random counters must be unchanged since the +// last page; failures return an empty optional with 'error' and roll the write back. std::optional CareerSession::dispatch_live_settings( const LiveSettingsAction& action,MatchEngine& engine,uint64_t& revision,std::string& error) { error.clear(); @@ -4715,6 +5079,8 @@ std::optional CareerSession::dispatch_live_ error="live settings: active Source match list changed";return {}; } const auto current=*live_settings_owner_; + // Scope guard: calendar_advance_active_ is off while the nested settings code runs and is + // restored on exit. struct LiveSettingsBoundaryScope { bool& active;bool previous; explicit LiveSettingsBoundaryScope(bool& value):active(value),previous(value){active=false;} @@ -4780,6 +5146,9 @@ std::optional CareerSession::dispatch_live_ live_settings_owner_=std::move(updated);++revision; return result; } + // Close: the owner, sequence and revision must match. The live-scene flag and a few runtime + // latches are derived from the settings switches, then the owner is dropped and the revision + // advances. const auto& close=std::get(action); if(close.owner!=current.request||close.owner.sequence!=current.request.sequence||close.owner.revision!=revision) throw FormatError("live settings: stale or mismatched Source close"); @@ -4812,6 +5181,10 @@ std::optional CareerSession::dispatch_live_ } } +// Desk settings group (menu 19) shares the cell write and file code with the live settings but +// keeps its own owner (desk_settings_owner_). Pattern: open on a staged copy -> write / file / +// close actions that must find the owner snapshot unchanged -> close. +// Captures state, runtime bytes, owner and scope counter so the UI flow can roll back. CareerSession::DeskSettingsCheckpoint CareerSession::desk_settings_checkpoint(uint64_t revision) const { return {g_,club_modal_runtime_,desk_settings_owner_ ? std::optional(desk_settings_owner_->owner) : std::nullopt, @@ -4819,6 +5192,10 @@ CareerSession::DeskSettingsCheckpoint CareerSession::desk_settings_checkpoint(ui next_desk_settings_scope_,revision}; } +// Loads or saves the 180-byte settings block as a .ein file on a staged state (const: it never +// touches the live state). Validates owner fields, extension, symlink and size; save refuses an +// existing file without the overwrite flag. Returns false with a short error code in 'error'; +// 'loaded' tells whether a load changed the staged state. bool CareerSession::apply_settings_file(const ui::SaveLoadRequest& request,int manager_slot,int origin_item_id, GameState& staged,bool& loaded,std::string& error) const { constexpr size_t kBytes=180; @@ -4869,6 +5246,8 @@ bool CareerSession::apply_settings_file(const ui::SaveLoadRequest& request,int m error.clear();return true; } +// Restores a desk settings checkpoint: state, runtime bytes, owner (with a fresh snapshot), +// scope counter and revision. void CareerSession::restore_desk_settings_checkpoint(DeskSettingsCheckpoint checkpoint,uint64_t& revision) { g_=std::move(checkpoint.state);club_modal_runtime_=std::move(checkpoint.runtime); desk_settings_owner_.reset(); @@ -4882,6 +5261,10 @@ void CareerSession::restore_desk_settings_checkpoint(DeskSettingsCheckpoint chec next_desk_settings_scope_=checkpoint.next_scope;revision=checkpoint.revision; } +// Opens the desk settings page from menu item 19: the request must name an enabled menu-19 item +// of the current revision for the active manager and no other owner, dispatch or calendar advance +// may be active. Works on a staged copy that is committed with the owner on success; empty +// optional with 'error' otherwise. std::optional CareerSession::open_desk_settings( const ui::DeskRequest& request,uint64_t& revision,std::string& error) { error.clear(); @@ -4936,6 +5319,9 @@ std::optional CareerSession::open_desk_se } catch(const std::exception& e) {error=e.what();return {};} } +// Applies a cell write, a settings file request or the close of the desk settings page. The +// owner snapshot, random counters and active manager must be unchanged. A failed write is rolled +// back and the revision restored. std::optional CareerSession::dispatch_desk_settings( const DeskSettingsAction& action,uint64_t& revision,std::string& error) { error.clear(); @@ -4994,6 +5380,9 @@ std::optional CareerSession::dispatch_desk_ g_=std::move(staged);desk_settings_owner_=std::move(updated);++revision; return result; } + // Close: validates owner and revision. When the stepper at row 7 column 7 changed, the 32-bit + // runtime counter after it is reset (new value 0) or shifted by 60 per step; the live-scene + // flag and other latches are derived from the switches and the owner is dropped. const auto& close=std::get(action); if(close.owner!=current.owner||close.owner.revision!=revision) throw FormatError("desk settings: stale close request"); @@ -5029,6 +5418,13 @@ std::optional CareerSession::dispatch_desk_ } } +// Advertising group: renewal check/answer, offers and spending. Pattern: the UI sends an +// AdvertisingRequest with request id (must increase), revision, manager slot and club; the +// session validates against the active manager, applies the change on the live state inside a +// checkpoint (apply_advertising rolls everything back if validation, the action or the +// acknowledgement fails) and bumps the revision. +// Simple renewal check for the active manager; the revision is bumped unless the contract has +// not expired. Returns nothing with a German 'error' text if stale or invalid. std::optional CareerSession::check_advertising_renewal(int manager_slot, int display_slot, uint64_t& revision, std::string& error) { error.clear(); @@ -5050,6 +5446,8 @@ std::optional CareerSession::check_advertising_renewal(int m return renewal; } +// Answers an offered renewal (renew or decline) for the active manager and bumps the revision; +// false with a German 'error' text if the request is stale. bool CareerSession::answer_advertising_renewal(int manager_slot, int contract_slot, bool renew, uint64_t& revision, std::string& error) { error.clear(); @@ -5069,6 +5467,9 @@ bool CareerSession::answer_advertising_renewal(int manager_slot, int contract_sl +// Copies nearly the whole session (state, random generators, turn driver, every modal owner, +// dispatch flags, scope counters, runtime bytes and the given revision) for rollback and for the +// "nothing changed" comparison below. Also used outside advertising, e.g. around the kickoff. CareerSession::AdvertisingSessionCheckpoint CareerSession::advertising_session_checkpoint(uint64_t revision) const { AdvertisingSessionCheckpoint c; c.state=g_; c.game=game_; c.rand=rand_; c.driver=turn_driver_; @@ -5098,6 +5499,8 @@ CareerSession::AdvertisingSessionCheckpoint CareerSession::advertising_session_c return c; } +// Puts back everything advertising_session_checkpoint captured (the caller restores the +// revision itself). void CareerSession::restore_advertising_session_checkpoint(AdvertisingSessionCheckpoint c) { g_=std::move(c.state); game_=c.game; rand_=c.rand; turn_driver_=std::move(c.driver); source_desk_callargs_=std::move(c.desk_callargs); saved_turn_error_=std::move(c.saved_turn_error); @@ -5124,6 +5527,9 @@ void CareerSession::restore_advertising_session_checkpoint(AdvertisingSessionChe last_advertising_request_id_=c.last_request_id; manager_join_=std::move(c.manager_join); } +// True when the live session equals the checkpoint in saved state, random counters, turn driver +// stage, owners, flags, scope counters and revision; used to detect a callback that changed the +// session behind the engine's back. bool CareerSession::advertising_session_unchanged(const AdvertisingSessionCheckpoint& c, uint64_t revision) const { const auto byte_same=[&](uint32_t at) { @@ -5160,6 +5566,11 @@ bool CareerSession::advertising_session_unchanged(const AdvertisingSessionCheckp last_contract_request_id_==c.last_contract_request_id && transfer_offer_revision_==c.transfer_offer_revision; } +// Renewal question with a UI presenter. Refuses a competing owner or dispatch (competing_owner) +// and a stale request (increasing request id, active manager, club, revision, contract bytes). +// The presenter runs on a staged copy; the session is always restored after it, and only the +// staged result of the confirmed answer becomes live (revision plus one). Returns nothing with a +// German 'error' text on failure. std::optional CareerSession::dispatch_advertising_renewal( const ui::AdvertisingRequest& request, uint64_t& revision, std::string& error, const AdvertisingRenewalPresenter& presenter) { @@ -5259,6 +5670,9 @@ std::optional CareerSession::dispatch_advertising_renewal( } } +// Entry point for advertising requests: runs the renewal or the offer/spending dispatch and then +// the acknowledgement callback; any failure or exception restores the advertising checkpoint and +// the old revision (exceptions are rethrown). bool CareerSession::apply_advertising(const ui::AdvertisingRequest& request, uint64_t& revision, std::string& error, const AdvertisingAcknowledge& acknowledge, const AdvertisingRenewalPresenter& presenter) { @@ -5288,6 +5702,8 @@ bool CareerSession::apply_advertising(const ui::AdvertisingRequest& request, uin } } +// Builds an accept_offer request from the page the player saw and applies it; false with 'error' +// if the displayed offer no longer exists. bool CareerSession::accept_advertising_selection(const ui::AdvertisingState& observed, int display_slot, int raw_offer, uint64_t request_id, uint64_t& revision, std::string& error) { if (display_slot < 0 || display_slot >= int(observed.offers.size())) { @@ -5314,6 +5730,8 @@ bool CareerSession::accept_advertising_selection(const ui::AdvertisingState& obs return apply_advertising(request, revision, error); } +// Builds a set_spending request for budget slots 16-18 from the observed page and applies it; +// the observed amount and delivery weeks are sent as the expected values. bool CareerSession::set_advertising_budget(const ui::AdvertisingState& observed, int target_slot, uint32_t amount, uint64_t request_id, uint64_t& revision, std::string& error, AdvertisingSpendingResult& result) { @@ -5336,6 +5754,10 @@ bool CareerSession::set_advertising_budget(const ui::AdvertisingState& observed, [&](const AdvertisingActionResult& applied) { result = applied.spending; }); } +// Validates an offer or spending request (no modal owner open, active manager and club, current +// revision, a request id greater than the last one) and applies it to the live state. The +// renewal kind is refused here; it goes through dispatch_advertising_renewal. False with a +// German 'error' text otherwise. bool CareerSession::dispatch_advertising(const ui::AdvertisingRequest& request, uint64_t& revision, std::string& error, AdvertisingSpendingResult* spending_result) { if (advertising_renewal_dispatch_active_) { error = "advertising_renewal_active"; return false; } @@ -5391,10 +5813,18 @@ bool CareerSession::dispatch_advertising(const ui::AdvertisingRequest& request, return true; } +// Contract group (negotiation at the desk). Flow: request_demands creates a quote (contract_quote_) +// that binds the follow-up requests (offer, bonuses, insurance) by quote id, row and player; +// each follow-up must carry a higher request id and the quote's revision. State changes happen on +// staged copies and are committed together with the revision bump. +// Validates request id (must increase), revision, active manager and club (not the national team) +// and the squad row against the player id; rejects with a German 'error' text and returns false. +// On success it fills 'result' (quote id, demands, accepted flag and original feedback text). bool CareerSession::dispatch_contract(const ui::ContractRequest& request, uint64_t& revision, ui::ContractActionResult& result, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + // Sets the player-visible error text and returns false. const auto reject = [&](std::string message) { error = std::move(message); return false; }; const auto original_text = [&](uint32_t address) { return ui::original_to_utf8(texts_[(address - ::bmh::layout::TextPointerTable) / 4]); @@ -5526,6 +5956,10 @@ bool CareerSession::dispatch_contract(const ui::ContractRequest& request, uint64 return true; } +// Common check for desk setting changes (ticket price, automation): no modal owner open, career +// not complete, optionally the desk phase (no calendar advance or pending dispatch), and the +// identity must match the active manager, revision, club and stable club identity. Sets a short +// error code and returns false otherwise. bool CareerSession::validate_desk_setting_owner(const DeskSettingIdentity& identity, uint64_t revision, std::string& error, bool require_desk_phase) const { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || @@ -5557,6 +5991,10 @@ bool CareerSession::validate_desk_setting_owner(const DeskSettingIdentity& ident return true; } +// Writes one desk setting for 'manager': the ticket price (admission 8-25, not for the national +// team) or automation option 'index' (0 = saved formation 0-8 limited to the saved formation +// mask, 1-3 flags, 4 training automation not for the national team). Sets 'error' on a rejected +// value; does not bump the revision (the caller does). bool CareerSession::apply_desk_setting(int manager, bool price, int index, int value, std::string& error) { const size_t rec = size_t(manager) * 0xb0c; const bool national = g_.manager_teams[size_t(manager)] == kNoTeam; @@ -5588,6 +6026,7 @@ bool CareerSession::apply_desk_setting(int manager, bool price, int index, int v return true; } +// Validates the owner and the price range (8-25) and applies the ticket price; revision plus one. bool CareerSession::dispatch_ticket_price(const TicketPriceRequest& request, uint64_t& revision, std::string& error) { if (!validate_desk_setting_owner(request.identity, revision, error)) return false; @@ -5597,6 +6036,8 @@ bool CareerSession::dispatch_ticket_price(const TicketPriceRequest& request, uin return true; } +// Validates the owner and applies one automation switch (formation automation needs a formation +// 1-8 exactly when enabled); revision plus one. bool CareerSession::dispatch_automation(const AutomationRequest& request, uint64_t& revision, std::string& error) { if (!validate_desk_setting_owner(request.identity, revision, error)) return false; @@ -5615,6 +6056,9 @@ bool CareerSession::dispatch_automation(const AutomationRequest& request, uint64 return true; } +// Desk widget click (ticket price or automation option): the request must belong to a visible, +// enabled desk item of the matching kind; the new value is derived here (formation automation +// cycles to the next available formation, flags toggle) and applied; revision plus one. bool CareerSession::dispatch_desk_widget(const ui::DeskRequest& request, uint64_t& revision, std::string& error) { const int active = g_.memory.has(::bmh::layout::ActiveManager) ? int(g_.memory.u8(::bmh::layout::ActiveManager)) : -1; @@ -5659,6 +6103,12 @@ bool CareerSession::dispatch_desk_widget(const ui::DeskRequest& request, uint64_ return true; } +// Desk layout editing (move an item, open or close a quick-bar drawer, send items to or +// restore them from a folder or bin). The desk is 54 item records of 16 bytes per manager. The +// request carries the layout before and after; this function checks that "before" equals the live +// bytes, recomputes the expected "after" for the operation itself, requires an exact match, and +// verifies the resulting desktop projection before committing (revision plus one). Any +// mismatch returns false with a short error code and changes nothing. bool CareerSession::dispatch_desktop_layout(const ui::DeskRequest& request, uint64_t& revision, std::string& error) { constexpr size_t kItems=54, kStride=16, kBytes=kItems*kStride; @@ -5696,6 +6146,9 @@ bool CareerSession::dispatch_desktop_layout(const ui::DeskRequest& request, uint request.layout_operation==ui::DeskLayoutOperation::restore_folder_child)&&!source_drag_enabled) { error="source_desk_drag_disabled";return false; } + // Each case rebuilds 'expected' (the layout bytes after the operation) from the live layout: + // bounds and optional grid snapping for moves, linked list chain edits (offsets +5/+6) for + // drawers, folders and the bin. switch(request.layout_operation) { case ui::DeskLayoutOperation::move_item: { if(request.layout_target_item!=-1 || expected[at+12]==72) { error="invalid_desk_layout_move_target"; return false; } @@ -5867,6 +6320,9 @@ bool CareerSession::dispatch_desktop_layout(const ui::DeskRequest& request, uint g_=std::move(staged); ++revision; error.clear(); return true; } +// Sets one tactic option (index 0-7, value within the executable's limit) for the active +// manager; touches only the manager record option bytes, never the tactics board or random +// generators. False with a German 'error' text when stale or invalid; revision plus one. bool CareerSession::dispatch_tactics(const ui::TacticsRequest& request, uint64_t& revision, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || @@ -5904,6 +6360,9 @@ bool CareerSession::dispatch_tactics(const ui::TacticsRequest& request, uint64_t return true; } +// Lineup requests of the active manager (refused during a calendar advance or pending offer +// dispatch). prepare_lineup builds the lineup entry on a staged copy and accepts it only when +// the first eleven squad rows form a valid authoritative lineup. bool CareerSession::dispatch_lineup(const ui::LineupRequest& request, uint64_t& revision, std::string& error) { if (calendar_advance_active_ || pending_offer_dispatch_active_) { @@ -5967,6 +6426,11 @@ bool CareerSession::dispatch_lineup(const ui::LineupRequest& request, uint64_t& ++revision; return true; } + // Swap path: only allowed after prepare_lineup for the same manager and club. The two rows must + // still hold the slots and players the UI saw; injured players and the foreign-player rule are + // refused until their dialogs exist. The swap exchanges squad slots (keeping the role bits with + // the row) and tactic board entries, re-syncs the card row ids and switches the manager's + // formation automation off. if (request.kind != ui::LineupRequestKind::swap_players || lineup_entry_manager_ != active || lineup_entry_club_ != request.runtime_club || request.first_row < 0 || request.second_row < 0 || request.first_row == request.second_row || @@ -6021,6 +6485,12 @@ bool CareerSession::dispatch_lineup(const ui::LineupRequest& request, uint64_t& return true; } +// Live overview dispatch (pattern open -> dispatch -> acknowledge): applies one action of the +// overview opened by open_running_overview. Requires an active calendar advance, the owner of the +// current revision and an engine that is still bound to this session with unchanged match groups +// and referees. The action variant selects the child: league family navigation or control, +// strengths, pairings or the cup other-games page. Close actions end the owner and return a +// preparation projection; a failure returns an empty optional with 'error'. std::optional CareerSession::dispatch_live_overview( const LiveOverviewAction& action, MatchEngine& engine, uint64_t& revision, std::string& error, const TransferOfferTeamInfoPresenter& team_info) { @@ -6044,6 +6514,7 @@ std::optional CareerSession::dispatch_live_ error="live overview: active Source match group changed";return {}; } const auto live= *live_overview_owner_; + // Scope guard: calendar_advance_active_ is off while the family code runs and is restored on exit. struct LiveBoundaryFamilyScope { bool& active; bool previous; explicit LiveBoundaryFamilyScope(bool& value) : active(value), previous(value) { active=false; } @@ -6181,6 +6652,8 @@ std::optional CareerSession::dispatch_live_ navigation.kind=ui::LeagueFamilyRequestKind::navigate; navigation.from_child=3; navigation.target_child=strengths->kind==ui::StrengthsAction::table?1:2; + // The opposite guard: sets calendar_advance_active_ for the nested table/pairings navigation, + // which expects to run inside the advance, and restores the value afterwards. struct RestoreObserverScope { bool& flag; bool previous; explicit RestoreObserverScope(bool& f):flag(f),previous(f){flag=true;} ~RestoreObserverScope(){flag=previous;} } observer_scope(calendar_advance_active_); return dispatch_live_overview(LiveOverviewAction{navigation},engine,revision,error,team_info); } @@ -6243,6 +6716,13 @@ std::optional CareerSession::dispatch_live_ } } +// Live intervention group (lineup changes during a running match). Pattern: begin stores a +// LiveInterventionCheckpoint (state, match groups, both random generators, revision), the +// substitution requests work against it, finish rerates the team and bumps the revision, abort +// puts everything back. +// Begin: only after minute 2, source mode 2 or 8, for a human manager whose team plays in the +// current match. Mode 2 also runs the lineup entry preparation. Returns false with a German +// 'error' text and no open intervention otherwise. bool CareerSession::begin_live_intervention(int minute, int source_mode, int manager, int team, MatchEngine& engine, uint64_t& revision, std::string& error) { error.clear(); @@ -6290,6 +6770,10 @@ bool CareerSession::begin_live_intervention(int minute, int source_mode, int man return true; } +// Begin for an automatic intervention caused by a match event (kind 1 or 2): the event must match +// the engine's current group, match, side and teams, the manager must have the automatic +// option on, and the affected player must show the expected status. Opens the lineup entry like +// mode 2; false with 'error' otherwise. bool CareerSession::begin_live_event_intervention(const LiveMatchEvent& event, MatchEngine& engine, uint64_t& revision, std::string& error) { error.clear(); @@ -6351,6 +6835,9 @@ bool CareerSession::begin_live_event_intervention(const LiveMatchEvent& event, M return true; } +// Ends an event intervention: the open checkpoint must belong to exactly this event and the +// engine groups must be unchanged. Only consumes the owner and bumps the revision (the rerate +// belongs to the event itself). bool CareerSession::finish_live_event_intervention(const LiveMatchEvent& event, MatchEngine& engine, uint64_t& revision, std::string& error) { error.clear(); @@ -6391,6 +6878,9 @@ bool CareerSession::finish_live_event_intervention(const LiveMatchEvent& event, return true; } +// Ends a normal intervention: rerates the team on a staged engine copy; on success the staged +// state, groups and generators replace the live ones and the revision advances, on a rerate +// failure or exhausted revision the checkpoint is restored. False with a German 'error' text. bool CareerSession::finish_live_intervention(int minute, int source_mode, int manager, int team, MatchEngine& engine, uint64_t& revision, std::string& error) { error.clear(); @@ -6448,6 +6938,8 @@ bool CareerSession::finish_live_intervention(int minute, int source_mode, int ma return true; } +// Abandons the matching open intervention and restores state, groups, random generators and the +// revision from its checkpoint. Does nothing if no matching intervention is open. void CareerSession::abort_live_intervention(int minute, int source_mode, int manager, int team, MatchEngine& engine, uint64_t& revision) { if (!live_intervention_ || live_intervention_->minute != minute || @@ -6469,6 +6961,10 @@ void CareerSession::abort_live_intervention(int minute, int source_mode, int man live_intervention_.reset(); } +// Applies one swap of the open live intervention (mode 2 only): checks owner, revision, manager, +// team and that the rows still hold the shown slots and players, whether it is a same-zone +// exchange or a field/bench substitution, and the injury status of both players (some notices +// are reported as "source_notice" codes in 'error'). False with 'error' on any failure. bool CareerSession::dispatch_live_substitution(const ui::LineupRequest& request, int minute, int source_mode, MatchEngine& engine, uint64_t& revision, std::string& error) { error.clear(); @@ -6653,6 +7149,8 @@ bool CareerSession::dispatch_live_substitution(const ui::LineupRequest& request, return true; } +// Wraps dispatch_live_substitution: applied, a "source_notice" status carrying the original +// notice address parsed from the error text, or rejected with the error text. LiveSubstitutionResult CareerSession::dispatch_live_substitution_result( const ui::LineupRequest& request, int minute, int source_mode, MatchEngine& engine, uint64_t& revision) { @@ -6670,6 +7168,10 @@ LiveSubstitutionResult CareerSession::dispatch_live_substitution_result( return {LiveSubstitutionStatus::rejected, 0, request.manager_slot, std::move(error)}; } +// Sets one tactic option during the open live intervention (source mode 8, after minute 2): the +// intervention owner, revision, manager, team and current match must match, the value must be in +// range and available. Only the manager record bytes change; revision plus one and the open +// intervention's current revision follows. False with a German 'error' text otherwise. bool CareerSession::dispatch_live_tactic(const ui::TacticsRequest& request, int minute, int source_mode, MatchEngine& engine, uint64_t& revision, std::string& error) { error.clear(); @@ -6734,6 +7236,11 @@ bool CareerSession::dispatch_live_tactic(const ui::TacticsRequest& request, int return true; } +// Pitch (lineup screen) group: all pitch actions (swap, move player, weights, formations, +// set piece editor and takers, player orders, marking, page switches). A swap is forwarded to +// dispatch_lineup. Everything else is checked against the display word, the saved set piece +// signature and the expected old values in the request, applied on a staged copy of the state +// and committed with a revision bump. False with a German 'error' text or a short code otherwise. bool CareerSession::dispatch_pitch(const ui::PitchRequest& request, uint64_t& revision, std::string& error) { if (request.kind == ui::PitchRequestKind::swap_players) { @@ -6783,12 +7290,15 @@ bool CareerSession::dispatch_pitch(const ui::PitchRequest& request, uint64_t& re // is sufficient authority there; ordinary automation/ticket settings remain // desk-only. Keep all nested desk mutations blocked while allowing this Source // line-up window before the first desk has been created. + // True when the request belongs to the open live lineup intervention (same manager, team and + // revision); such requests are authorised by that owner instead of by the desk phase. const bool live_context = live_intervention_ && live_intervention_->source_mode == 2 && request.manager_slot == live_intervention_->manager && request.runtime_club == live_intervention_->team && request.revision == live_intervention_->current_revision && request.revision == revision; const bool desk_phase = turn_driver_.stage == TurnDriver::Stage::MatchdayDesks || turn_driver_.stage == TurnDriver::Stage::SeasonEndDesk; + // True during the very first lineup window before the first desk exists (driver stage Empty). const bool initial_lineup_phase = turn_driver_.stage == TurnDriver::Stage::Empty && lineup_entry_manager_ == request.manager_slot && lineup_entry_club_ == request.runtime_club; if (!desk_phase && !initial_lineup_phase && !live_context) { error = "desk_setting_unavailable"; return false; } @@ -7055,6 +7565,9 @@ bool CareerSession::dispatch_pitch(const ui::PitchRequest& request, uint64_t& re return true; } +// Pitch request during a live intervention: needs the matching open intervention (mode 2) and +// current revision. Formation and weight controls exist only in the initial preparation and are +// refused here; the rest goes to dispatch_pitch. bool CareerSession::dispatch_live_pitch(const ui::PitchRequest& request, int minute, int source_mode, MatchEngine& engine, uint64_t& revision, std::string& error) { if (!live_intervention_ || live_intervention_->minute != minute || @@ -7087,6 +7600,8 @@ bool CareerSession::dispatch_live_pitch(const ui::PitchRequest& request, int min return dispatch_pitch(request, revision, error); } +// Result-style wrapper: swaps return the substitution result (with source notices), other pitch +// actions return applied or rejected with the error text. LiveSubstitutionResult CareerSession::dispatch_live_pitch_result(const ui::PitchRequest& request, int minute, int source_mode, MatchEngine& engine, uint64_t& revision) { if (request.kind == ui::PitchRequestKind::swap_players) { @@ -7105,6 +7620,7 @@ LiveSubstitutionResult CareerSession::dispatch_live_pitch_result(const ui::Pitch 0, request.manager_slot, std::move(error)}; } +// Desk-time swap only; any other pitch kind is refused. bool CareerSession::dispatch_pitch_swap(const ui::PitchRequest& request, uint64_t& revision, std::string& error) { if (request.kind != ui::PitchRequestKind::swap_players) { @@ -7114,10 +7630,14 @@ bool CareerSession::dispatch_pitch_swap(const ui::PitchRequest& request, uint64_ return dispatch_pitch(request, revision, error); } +// Preparation (match day) projection of the live state at 'revision'; read-only. ui::PreparationState CareerSession::preparation_projection(uint64_t revision) const { return preparation_projection(g_, revision); } +// Returns the opponent team of the manager's prepared lineup entry (from the captured desk call +// arguments, confirmed against the desk projection), or nothing when the manager is not the +// active prepared one, the day has no ordinary opponent or any check fails. Read-only. std::optional CareerSession::prepared_lineup_opponent(int manager_slot, int runtime_club, uint64_t revision) const { if (turn_driver_.stage != TurnDriver::Stage::MatchdayDesks || g_.indoor || @@ -7200,6 +7720,11 @@ std::optional CareerSession::prepared_lineup_opponent(int manager_slot, int return current_pair ? std::optional(opponent) : std::nullopt; } +// Builds the preparation projection of 'state' and layers the session-owned extras on top: the +// desktop, the lineup "entry prepared" flag and pitch extras, the bank notices and the stadium +// page including its open dialogs (construction tip, periphery quote, block expansion editor) +// when the stadium owner belongs to this exact manager, club and revision. Read-only. +// Throws FormatError when the manager's league cannot be found. ui::PreparationState CareerSession::preparation_projection(const GameState& state, uint64_t revision) const { auto result = ui::preparation_from_game(state, exe_, revision); result.desktop = desktop_projection(state, revision); @@ -7318,6 +7843,12 @@ ui::PreparationState CareerSession::preparation_projection(const GameState& stat return result; } +// Training group: one request changes the types, areas, automation byte or one player's +// intensity or focus of the active manager. The request carries the desired result; it is +// validated against the current projection (stale manager, plan limits, expected values), applied +// on a staged copy and committed with revision plus one. Manual edits clear the matching +// assistant flag and never draw random numbers; initialize and enabling automation run the +// automatic training. Returns false with a short error code in 'error' otherwise. bool CareerSession::dispatch_training(const ui::TrainingRequest& request, uint64_t& revision, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || @@ -7487,6 +8018,10 @@ bool CareerSession::dispatch_training(const ui::TrainingRequest& request, uint64 } } +// Captures, for every manager slot, the competition id and opponent shown at the desk today +// (defaults 33/34, or 32 at season end; no opponent). Only done while the driver is at a desk +// stage; the values are kept in source_desk_callargs_ and later used to authenticate lineup +// and pitch requests. void CareerSession::capture_source_desk_callargs() { source_desk_callargs_.clear(); const auto stage = turn_driver_.stage; @@ -7520,10 +8055,14 @@ void CareerSession::capture_source_desk_callargs() { } } +// Desk projection of the live state at 'revision'; read-only. ui::DeskState CareerSession::desktop_projection(uint64_t revision) const { return desktop_projection(g_, revision); } +// Desk projection of 'state'. Only at a desk stage (matchday or season end) are the next +// competition and opponent filled in from the captured call arguments; otherwise they stay +// unknown. ui::DeskState CareerSession::desktop_projection(const GameState& state, uint64_t revision) const { std::optional source_default; if (turn_driver_.stage == TurnDriver::Stage::SeasonEndDesk) { @@ -7545,6 +8084,10 @@ ui::DeskState CareerSession::desktop_projection(const GameState& state, uint64_t return ui::desk_from_game(state, exe_, revision, &turn_driver_.groups, source_default, callargs); } +// Saving group. Autosave: set once the directory is known; the driver then calls +// write_desk_autosave at each desk. Manual save (save_game) validates the target and writes on a +// staged copy of the random generator. Both go through make_savegame / write_savegame (.FBM +// container). Changing the autosave directory during an active turn throws FormatError. void CareerSession::configure_autosave_directory(const std::filesystem::path& directory) { if (autosave_directory_ && *autosave_directory_ == directory) return; if (calendar_advance_active_) throw FormatError("autosave directory change during active turn"); @@ -7554,10 +8097,14 @@ void CareerSession::configure_autosave_directory(const std::filesystem::path& di }; } +// Returns and clears the last autosave error text. std::string CareerSession::take_autosave_error() { return std::exchange(autosave_error_, {}); } +// Writes the desk autosave under the original file name to a temporary file in the autosave +// directory and renames it over the target; the random generator advances only on success. +// Failures are stored in autosave_error_ (never thrown) and the temporary file is removed. void CareerSession::write_desk_autosave(const GameState& state, WatcomRandom& random) { std::filesystem::path temporary; try { @@ -7593,6 +8140,10 @@ void CareerSession::write_desk_autosave(const GameState& state, WatcomRandom& ra } } +// Manual save of the active manager's game to a .fbm path. Refused while a modal owner, editor +// or pending decision is open or the career is complete; rejects symlink targets, a missing +// directory and an existing file without 'overwrite'. The random generator advances only if the +// write succeeded. Returns false with a short error code in 'error' otherwise. bool CareerSession::save_game(const std::filesystem::path& path, int manager_slot, bool overwrite, std::string& error) { if (advertising_renewal_dispatch_active_) { error="save_blocked_during_advertising_renewal"; return false; } if(balance_draft_||balance_dispatch_active_||strengths_owner_||strengths_dispatch_active_|| @@ -7629,6 +8180,10 @@ bool CareerSession::save_game(const std::filesystem::path& path, int manager_slo } } +// Loads or saves the 0x360-byte menu layout (.men file) of the active manager. Needs the desk +// item handle (record 53), no active flow and a payload whose link chain is valid. A load is +// checked by projecting the desktop on a staged copy before it is committed (revision plus one); +// a save refuses symlinks and existing files without overwrite. Short error codes in 'error'. bool CareerSession::dispatch_menu_layout(const ui::SaveLoadRequest& request, uint64_t& revision, std::string& error) { constexpr uint32_t kLayouts = ::bmh::layout::Desktops; @@ -7752,6 +8307,11 @@ bool CareerSession::dispatch_menu_layout(const ui::SaveLoadRequest& request, uin return true; } +// Training camp group: set_focus changes the four focus bytes of the active manager (an unchanged +// or invalid focus is refused); book books a resort for the week after checking the focus the UI +// saw, the weekly/visit limits and the funds (the booking draws random numbers). Refused while a +// modal owner is open or when the manager slot, club or revision is stale; revision plus one on +// success, short error codes in 'error' otherwise. bool CareerSession::dispatch_training_camp(const ui::TrainingCampRequest& request, uint64_t& revision, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || @@ -7807,6 +8367,11 @@ bool CareerSession::dispatch_training_camp(const ui::TrainingCampRequest& reques return false; } +// Bank group: deposit moves, share and fund trades, stock tips and bank credit. Needs the active +// manager, club and current revision and no modal owner open. Every branch validates amounts and +// counts against the manager record and the stock/fund blocks, then applies the change to the +// live state and bumps the revision once. The notices of the last property purchase or credit +// refund are kept for the next projection. Returns false with a short error code otherwise. bool CareerSession::dispatch_bank(const ui::BankRequest& request, uint64_t& revision, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } @@ -7940,6 +8505,8 @@ bool CareerSession::dispatch_bank(const ui::BankRequest& request, uint64_t& revi return true; } +// True when a construction tip dialog is open and the process timer (when running) has no time +// left; read-only. bool CareerSession::stadium_tip_deadline_expired() const { if (!stadium_.opened || (!stadium_.tip && (!stadium_.block_expansion || !stadium_.block_expansion->tip))) return false; @@ -7956,6 +8523,14 @@ bool CareerSession::stadium_tip_deadline_expired() const { return word(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField2) != 0 && int32_t(word(::bmh::layout::CareerSession_FormatError_ExecutableField2)) < 1; } +// Stadium group: an owner (stadium_) is opened with a scope id and every later request must echo +// scope and sequence, the manager, club, stable club identity, game mode and revision. All +// actions (data page, periphery quote/build, block expansion editor with its tip, investments) +// run inside the apply lambda below; on failure the stadium checkpoint is restored, on success +// revision, sequence and the owner's revision advance. Exceptions restore the checkpoint and +// the revision and are rethrown. Short error codes in 'error' otherwise. +// Older periphery callers send no scope envelope; a compatibility step fills it in for their four +// original operations only. bool CareerSession::dispatch_stadium(const ui::StadiumRequest& supplied_request, uint64_t& revision, std::string& error, const ConstructionNoticeHook& notice_presenter, const SeasonTicketCompensationNoticeHook& compensation_presenter) { @@ -8012,6 +8587,8 @@ bool CareerSession::dispatch_stadium(const ui::StadiumRequest& supplied_request, auto before = stadium_checkpoint(); const uint64_t before_revision = revision; try { + // Performs the validated stadium action and returns true on success; 'invalid' records the + // reason and returns false. const auto apply = [&]() -> bool { const auto invalid = [&error](const char* reason) { error = reason; return false; }; const auto plain = [&request](int object = -1) { @@ -8311,6 +8888,8 @@ bool CareerSession::dispatch_stadium(const ui::StadiumRequest& supplied_request, } } +// Submits a pools coupon for the active manager; only valid when the coupon has eleven matches. +// Revision plus one; false with a short error code otherwise. bool CareerSession::dispatch_toto(const ui::TotoRequest& request, uint64_t& revision, std::string& error) { if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } @@ -8332,12 +8911,17 @@ bool CareerSession::dispatch_toto(const ui::TotoRequest& request, uint64_t& revi namespace bmh::app { +// Group: presenter hooks. Returns the hooks with the allocator gate taken from the turn driver, +// so presenters can never decide it. PendingOfferHooks CareerSession::pending_hooks_for_dispatch(PendingOfferHooks hooks) const { // Presenters own answers and notice delivery, never allocator provenance. hooks.human_buyer_allocator_gate = turn_driver_.transfer_allocator_context; return hooks; } +// Resets the three screen hooks (contract expiry, loan return, loan return offer) to empty. An +// expiring contract without an installed presenter then stops the month change instead of being +// decided automatically. void CareerSession::install_default_hooks() { // InstallDefaultHooks pauses at the Original contracts screen when a term expires. // Never synthesize a two-year renewal here: callers must install the real @@ -8347,6 +8931,8 @@ void CareerSession::install_default_hooks() { g_.loan_return_offer_screen = {}; } +// Installs (or with an empty presenter removes) the contract expiry hook, keeping the other two +// screen hooks. void CareerSession::set_contract_expiry_presenter(ContractExpiryPresenter presenter) { // Clear any previously installed presenter before replacing it. The only // fallback is an explicit unsupported expiry, never a synthesized decision. @@ -8362,6 +8948,7 @@ void CareerSession::set_contract_expiry_presenter(ContractExpiryPresenter presen }; } +// Installs (or removes) the loan return question hook, keeping the other two screen hooks. void CareerSession::set_loan_return_presenter(LoanReturnPresenter presenter) { auto contract_hook = std::move(g_.contract_screen); auto loan_offer_hook = std::move(g_.loan_return_offer_screen); @@ -8376,6 +8963,9 @@ void CareerSession::set_loan_return_presenter(LoanReturnPresenter presenter) { }; } +// Installs (or removes) the loan return offer hook; the hook runs the presenter against staged +// club modal services with the allocator gate taken from the turn driver, and the staged runtime +// bytes are kept only when the presenter's result is not negative. void CareerSession::set_loan_return_offer_presenter(LoanReturnOfferPresenter presenter, HumanBuyerSaleHooks sale_hooks) { auto contract_hook = std::move(g_.contract_screen); diff --git a/src/app/controller.cpp b/src/app/controller.cpp index 65ed8cc..83175a9 100644 --- a/src/app/controller.cpp +++ b/src/app/controller.cpp @@ -40,12 +40,16 @@ namespace bmh::app { namespace fs = std::filesystem; namespace { +// True when the request that came back from the UI is exactly the friendly action the flow +// is still waiting for; a replayed or altered request fails this test. bool same_pending_friendly_request(const ui::StartupFlow& flow, const ui::FriendlyMatchRequest& request) { const auto* pending = flow.pending_friendly_action(); return pending && *pending == request; } +// Maps a failed club friendly-match booking status to the German notice shown to the player. +// Called when the booking action reports that nothing was applied. std::string friendly_status_message(FriendlyBookingStatus status) { switch (status) { case FriendlyBookingStatus::declined: return "Die Kosten wurden abgelehnt."; @@ -63,6 +67,9 @@ std::string friendly_status_message(FriendlyBookingStatus status) { return "Der Termin konnte nicht gebucht werden."; } +// Builds the manager name, portrait, slot and club badge shown in the national friendly dialogs +// from the manager record and club table of the game state. Throws FormatError when the +// manager slot or its record is missing. ui::NationalFriendlyIdentity national_friendly_identity(const GameState& game,int manager,int team) { if(manager<0||manager>=5||size_t(manager+1)*0xb0c>game.manager_records.size()) throw FormatError("national friendly: missing Source manager identity"); @@ -79,6 +86,8 @@ ui::NationalFriendlyIdentity national_friendly_identity(const GameState& game,in return out; } +// Builds one question dialog (venue, cost or payer) of the friendly-match flow: the identity of +// the asking manager plus the body text. Reused by both the club and the national variant. ui::TaxDialogProjection friendly_question(const GameState& game,int manager,uint16_t flags,std::string body) { const auto identity=national_friendly_identity(game,manager,game.manager_teams.at(size_t(manager))); ui::TaxDialogProjection p; @@ -89,6 +98,8 @@ ui::TaxDialogProjection friendly_question(const GameState& game,int manager,uint p.body=std::move(body);return p; } +// Collects everything the club friendly-match calendar screen needs for the manager at the desk +// (leagues, calendar, planner count, venue question). Called when the opponent table is finished. ui::FriendlyMatchState club_friendly_state(const CareerSession& session,const ui::DeskState& desk, const fs::path& data,uint64_t revision) { const auto& game=session.state();const int manager=desk.manager_slot; @@ -105,6 +116,7 @@ ui::FriendlyMatchState club_friendly_state(const CareerSession& session,const ui return friendly; } +// Same as friendly_status_message, but with the wording for national teams as opponents. std::string national_friendly_status_message(FriendlyBookingStatus status) { switch(status) { case FriendlyBookingStatus::declined:return "Die Kosten wurden abgelehnt."; @@ -122,6 +134,8 @@ std::string national_friendly_status_message(FriendlyBookingStatus status) { return "Der Termin konnte nicht gebucht werden."; } +// Reads the manager's transfer-history entry count from the manager record (at most 25). +// Throws FormatError for an invalid slot, a missing record or an out-of-range count. int source_transfer_history_count(const GameState& game, int manager_slot) { if (manager_slot < 0 || manager_slot >= 4) throw FormatError("statistics: invalid manager slot"); const size_t at=size_t(manager_slot)*0xb0c+0x21d; @@ -130,12 +144,18 @@ int source_transfer_history_count(const GameState& game, int manager_slot) { if(count>25)throw FormatError("statistics: Original transfer-history count exceeds 25"); return count; } +// Computes the vertical start of the transfer-history list from its entry count; a count of 0 +// is treated like 1. int source_transfer_history_origin(int count) { if(count<0||count>25)throw FormatError("statistics: invalid transfer-history count"); const int source_count=count==0?1:count; return 0x0d+(0x1c-source_count)*3; } +// Serves a friendly-match request from the UI (quote or booking, club or national team). +// It verifies the request is current, asks FriendlyActions for the quote or the booking and +// answers the flow with an acknowledgement or a rejection text. Silently returns when no desk +// is shown or the request is not the one the flow is waiting for. void serve_friendly_action(ui::StartupFlow& flow, CareerSession& session, const ui::FriendlyMatchRequest& request, uint64_t& revision, const std::filesystem::path& data) { @@ -143,6 +163,12 @@ void serve_friendly_action(ui::StartupFlow& flow, CareerSession& session, auto& game = session.state(); const auto& state = flow.desktop()->state(); const int manager = request.manager_slot; + // Identity and revision check before anything is booked: the request must carry the current + // shared revision and the desk's revision, the manager slot of the desk, and that manager must + // be the active manager in the game memory with a matching manager count. The club (runtime + // team) and planner count in the request must equal the session's values and the desk's club. + // Any mismatch means the UI built the request from an outdated screen, so it is rejected + // instead of touching the session. const bool identity_ok = request.revision == revision && request.revision == state.revision && manager == state.manager_slot && manager >= 0 && manager < 4 && size_t(manager) < game.manager_teams.size() && game.memory.has(::bmh::layout::ActiveManager) && @@ -151,11 +177,16 @@ void serve_friendly_action(ui::StartupFlow& flow, CareerSession& session, request.runtime_team == game.manager_teams[size_t(manager)] && request.runtime_team == state.runtime_club && request.planner_count == game.memory.u8(::bmh::layout::FriendlyPlanCount); + // Also rejected when the revision counter is already at its maximum and cannot advance. if (!identity_ok || revision == std::numeric_limits::max()) { flow.reject_friendly_action("Der Spielstand hat sich geändert. Bitte öffne das Menü erneut."); return; } + // National friendly booking (national-coach desk, team slot 0x165): every field of the request + // is compared with the quote and owner the UI kept, so a stale quote or a changed date, cost or + // team is refused. The date is re-checked, then book_national is called; on rejection the flow + // gets a German notice and the screen stays usable. if(request.national_booking) { const auto& national=*request.national_booking; const auto expected=FriendlyActions::national_owner(request); @@ -184,6 +215,9 @@ void serve_friendly_action(ui::StartupFlow& flow, CareerSession& session, return; } try { + // Acknowledgement callback of the booking action: projects desk and preparation at the new + // revision and gives them to the flow. A mismatch with the active screen throws, which the + // catch below turns into a rejection. const auto applied=FriendlyActions(session).book_national(request,revision,[&](const ui::FriendlyBookingAck& ack) { auto desk=session.desktop_projection(ack.revision); auto preparation=session.preparation_projection(ack.revision); @@ -199,6 +233,9 @@ void serve_friendly_action(ui::StartupFlow& flow, CareerSession& session, return; } + // Quote request (club friendly): asks for the opponent's terms, then builds the cost and payer + // questions and a 366-day calendar marking which days are free, flagged or the current day. + // If no quote is possible, or the flow no longer accepts it, the request is rejected. if (request.kind == ui::FriendlyRequestKind::quote) { const auto quote = FriendlyActions(session).quote(manager, request.opponent, request.manager_home); if (quote.status != FriendlyQuoteStatus::quoted || quote.manager_team != request.runtime_team) { @@ -245,6 +282,9 @@ void serve_friendly_action(ui::StartupFlow& flow, CareerSession& session, return; } + // Club friendly booking: the request is first range-checked (quote id, day, opponent, cost, + // planner count); invalid values are rejected, otherwise book_club is called and its status is + // mapped to a German notice if it was not applied. if (request.kind != ui::FriendlyRequestKind::book || request.quote_id == 0 || request.season_day < 0 || request.season_day > 365 || request.opponent < 0 || request.opponent >= 168 || request.cost < 0 || request.planner_count > 253) { @@ -252,6 +292,7 @@ void serve_friendly_action(ui::StartupFlow& flow, CareerSession& session, return; } try { + // Acknowledgement callback of the booking action (see the national variant above). const auto applied=FriendlyActions(session).book_club(request,revision,[&](const ui::FriendlyBookingAck& ack) { auto desk=session.desktop_projection(ack.revision); auto preparation=session.preparation_projection(ack.revision); @@ -266,6 +307,9 @@ void serve_friendly_action(ui::StartupFlow& flow, CareerSession& session, } } +// Checks that the national friendly screens (picker, statistics menu, desk) still belong to one +// owner: all carry the current revision and the same manager, that manager is on team slot +// 0x165 and is the active manager. Returns true when the family is not active at all. bool valid_national_friendly_family(const ui::StartupFlow& flow,const GameState& game,uint64_t revision) { if(!flow.national_friendly_family_active())return true; const auto* owner=flow.national_friendly_owner(); @@ -283,6 +327,9 @@ bool valid_national_friendly_family(const ui::StartupFlow& flow,const GameState& return true; } +// Runs the national friendly opponent dialogs after a nation was picked: venue question, quote, +// cost and payer questions (answered through the presenter hook), then opens the calendar. +// Any failed check or declined question closes the picker without booking anything. void serve_national_friendly_selection(ui::StartupFlow& flow,CareerSession& session, int selected_team,uint64_t& revision,const std::filesystem::path& data, const NationalFriendlyQuestionPresenter& presenter) { @@ -293,6 +340,8 @@ void serve_national_friendly_selection(ui::StartupFlow& flow,CareerSession& sess const auto& game=session.state(); const auto& desk=flow.desktop()->state(); const int manager=owner->manager; + // Identity check: owner and desk request must be the national-coach friendly menu at the current + // revision for the same manager, who must still be on team slot 0x165 and be the active manager. if(owner->desk_menu!=6||owner->runtime_team!=0x165||owner->revision!=revision|| desk_request->kind!=ui::DeskRequestKind::open_menu||desk_request->menu_kind!=6|| desk_request->revision!=revision||desk_request->manager_slot!=manager|| @@ -362,11 +411,15 @@ void serve_national_friendly_selection(ui::StartupFlow& flow,CareerSession& sess (void)data; } +// Applies the original sound options and resumes the desk song; called after load, new career +// and every turn. void start_original_desk_audio(openbmh::audio::Playback& playback, const GameState& state, bool enabled) { playback.set_original_options(original_audio_options(state, enabled)); original_audio_command(playback, 1); // SavePathInDirectory / CareerFirstSteps2, resume the same song. } +// True when the path has the expected extension and lies directly in the given save +// directory; keeps UI-supplied file names inside the save folder. bool save_path_in_directory(const fs::path& path, const fs::path& directory, std::string_view expected_extension = ".fbm") { if (path.filename().empty()) return false; @@ -380,6 +433,7 @@ bool save_path_in_directory(const fs::path& path, const fs::path& directory, return !ec && expected == actual; } +// Maps a transfer action status to the German notice shown after a transfer market action. std::string transfer_status_message(TransferActionStatus status, ui::TransferMarketRequestKind kind) { switch (status) { case TransferActionStatus::accepted: @@ -397,6 +451,9 @@ std::string transfer_status_message(TransferActionStatus status, ui::TransferMar } } +// Serves a transfer market request from the UI (list, bid, review offers, poach, offer dialog, +// preview). Dispatches by request kind to TransferActions and acknowledges or rejects through +// the flow. void serve_transfer_action(ui::StartupFlow& flow, CareerSession& session, const ui::TransferMarketRequest& request, uint64_t& revision, const HumanBuyerSaleHooks& presenters, @@ -408,11 +465,15 @@ void serve_transfer_action(ui::StartupFlow& flow, CareerSession& session, // Check that identity too, before an engine helper can consume a random draw. if (!pending || request.bid.manager != pending->bid.manager || ui::transfer_market_request_json(request) != ui::transfer_market_request_json(*pending)) return; + // The action facade checks the request against the current revision and entry policy; a + // non-empty text means it is refused and shown to the player. const auto rejection = TransferActions(session).rejection(request, revision, entry_policy); if (!rejection.empty()) { flow.reject_preparation_action(rejection); return; } + // Poach request: opens the original player selector through the session; the callback either + // shows the offer editor or presents the notice, and a failure is rejected with a message. if(request.kind==ui::TransferMarketRequestKind::open_poach) { if(entry_policy!=HumanBuyerMarketEntryPolicy::normal_interactive) { flow.reject_preparation_action("Die Original-Spielerauswahl ist in diesem Einstieg nicht verfügbar."); @@ -421,6 +482,8 @@ void serve_transfer_action(ui::StartupFlow& flow, CareerSession& session, std::string error; const auto backdrop=flow.render(); const bool accepted=session.dispatch_poach_ui(request,backdrop,poach_selector, + // Callback of the poach dispatch: shows the offer editor, or reports the start messages + // (through the notice presenter if set, otherwise as plain text). [&](const CareerSession::PoachDispatch& result,ui::PreparationState preparation) { if(result.editor) { flow.show_transfer_offer(result.editor->preparation,result.editor->editor); @@ -443,6 +506,7 @@ void serve_transfer_action(ui::StartupFlow& flow, CareerSession& session, } return; } + // Open-offer request: opens the offer dialog; only allowed in the normal interactive entry. if (request.kind == ui::TransferMarketRequestKind::open_offer) { if (entry_policy != HumanBuyerMarketEntryPolicy::normal_interactive) { flow.reject_preparation_action("Der Original-Angebotsdialog ist in diesem Einstieg nicht verfügbar."); @@ -460,6 +524,7 @@ void serve_transfer_action(ui::StartupFlow& flow, CareerSession& session, } return; } + // Preview request: asks for a quote and acknowledges it without changing the market. if (request.kind == ui::TransferMarketRequestKind::preview_quote) { if (entry_policy != HumanBuyerMarketEntryPolicy::normal_interactive) { flow.reject_preparation_action("Die Original-Transfervorschau ist in diesem Einstieg nicht verfügbar."); @@ -477,11 +542,15 @@ void serve_transfer_action(ui::StartupFlow& flow, CareerSession& session, } return; } + // All other kinds (bid, list, review offers): run through TransferActions::market with the + // sale hooks. The notice presenter is wrapped to remember whether a notice was shown, so the + // callback can keep the original notice/acknowledge order. try { auto hooks = presenters; bool source_notice_presented = false; if (hooks.notice) { const auto present = hooks.notice; + // Wrapper that forwards to the real notice presenter and records that it ran. hooks.notice = [present, &source_notice_presented](const GameState& staged, const HumanBuyerSaleNotice& notice) { present(staged, notice); source_notice_presented = true; @@ -489,6 +558,8 @@ void serve_transfer_action(ui::StartupFlow& flow, CareerSession& session, } std::string error; const auto outcome = TransferActions(session).market(request, hooks, revision, error, entry_policy, + // Callback after the market action: picks the notice, then acknowledges the new preparation + // state if something changed, or rejects/acknowledges unchanged otherwise. [&](const TransferActions::MarketDispatch& applied) { // Preserve the Source caller's existing notice/ACK sequence. const bool source_finished = request.kind != ui::TransferMarketRequestKind::review_offers && @@ -513,6 +584,8 @@ void serve_transfer_action(ui::StartupFlow& flow, CareerSession& session, } } +// Serves an outgoing transfer offer request from the UI. Ignored unless it equals the pending +// offer; refused outside the normal interactive entry; otherwise runs TransferActions::offer. void serve_transfer_offer(ui::StartupFlow& flow, CareerSession& session, const ui::OutgoingTransferRequest& request, uint64_t& revision, const HumanBuyerSaleHooks& presenters, HumanBuyerMarketEntryPolicy policy, @@ -527,6 +600,7 @@ void serve_transfer_offer(ui::StartupFlow& flow, CareerSession& session, try { std::string error; auto result = TransferActions(session).offer(request, presenters, revision, error, + // Callback after the offer action: gives the updated preparation and editor to the flow. team_info_presenter, player_info_presenter, [&](CareerSession::TransferOfferEditorDispatch& applied) { flow.acknowledge_transfer_offer(std::move(applied.preparation), std::move(applied.editor)); }); @@ -538,6 +612,10 @@ void serve_transfer_offer(ui::StartupFlow& flow, CareerSession& session, } // namespace +// Main entry: handles one FlowResult. Each branch below serves one request kind: it checks that +// the request is still the pending one and current, calls the session (through an Actions +// facade) and then acknowledges or rejects through the flow. A non-empty return is an error +// text for the console. The long parameter list is the optional presenter hooks. // Hands the flow's engine requests to the career session. Returns a message for the // console when something went wrong. std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& result, std::unique_ptr& session, @@ -574,12 +652,18 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu LiveRealityPresenter live_reality_presenter, PhaseResultPresenter phase_result_presenter, bool enable_autosave) { std::string error; + // Autosave is configured on the existing session before any request is served. if (enable_autosave && session) session->configure_autosave_directory(save_directory); + // While the opportunities owner is open in the session only its own screens (and the + // statistics menu and pages above it) may send requests; anything else is blocked. if(session&&session->opportunities_active()&&result.request!=ui::FlowRequest::none&& result.request!=ui::FlowRequest::opportunities_action&& result.request!=ui::FlowRequest::statistics_menu_action&& result.request!=ui::FlowRequest::statistics_page_action) return "opportunities: another session action is blocked while the Source owner is open"; + // Desk menu 5 (other games): the request must still be the desk's pending action at the current + // revision, otherwise it is dropped silently. OtherGamesActions opens the page; on rejection the + // desk action is rejected with the error text. if(result.request==ui::FlowRequest::desk_action&&session&& result.desk_action.kind==ui::DeskRequestKind::open_menu&&result.desk_action.menu_kind==5) { if(!flow.desktop()||!flow.desktop()->pending()||*flow.desktop()->pending()!=result.desk_action|| @@ -588,6 +672,9 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu const auto underlay=flow.desktop()->render(); auto page=OtherGamesActions(*session).open(result.desk_action,revision,underlay,error, [&](ui::OtherGamesState& opened) { + // Callback with the projected page. Identity check: manager slot, runtime club and day counter + // must equal the desk on screen and the club identity must equal the one stored for that manager + // on the desk; otherwise it throws and the page is not shown. const auto& desk=flow.desktop()->state(); if(opened.identity.manager_slot!=desk.manager_slot|| opened.identity.runtime_team!=desk.runtime_club|| @@ -606,6 +693,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return error; } + // Other-games page action: only the flow's pending action is accepted; the session dispatches it + // and the page is either closed or updated. Rejections go back to the page with the error. if(result.request==ui::FlowRequest::other_games_action&&session) { const auto* pending=flow.pending_other_games_action(); if(!pending||*pending!=result.other_games_action)return {}; @@ -624,8 +713,11 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return error; } + // While the other-games owner is open in the session, every other request is blocked. if(session&&session->other_games_active()&&result.request!=ui::FlowRequest::none) return "other games: another session action is blocked while the Source owner is open"; + // Desk menu 23 (statistics menu): shows the menu and its first page (rankings, category 0) + // built from the session. If building the page fails the menu is closed and the error returned. if(result.request==ui::FlowRequest::desk_action&&session&& result.desk_action.kind==ui::DeskRequestKind::open_menu&&result.desk_action.menu_kind==23) { if(!flow.desktop()||!flow.desktop()->pending()||*flow.desktop()->pending()!=result.desk_action|| @@ -646,6 +738,10 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return {}; } + // Statistics menu selection (indices 0 to 8 choose the page: 0 opportunities, 1 transfer history, + // 2 analytics, 3 all-time table, 4 world cup, 5 finance totals, 6 series records, 7 rankings, + // 8 minute statistics). Only the pending action is accepted; a failed national-friendly family + // check closes the menu; the page is built from the session state and shown through the flow. if(result.request==ui::FlowRequest::statistics_menu_action&&session) { const auto* pending=flow.pending_statistics_menu(); if(!pending||*pending!=result.statistics_menu_action)return {}; @@ -657,6 +753,9 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu // Parent selector actions remain live above either implemented child. // Closing A-D uses the same typed Source close transaction as its right-click path. const auto menu_request=*pending; + // Switching page while the opportunities owner (A-D) is open: the new page is built and test + // rendered first, then the opportunities owner is closed in the session and the new page shown. + // If the staging fails nothing is closed and the statistics menu is rejected. if((menu_request.selected_index==1||menu_request.selected_index==2||(menu_request.selected_index>=3&&menu_request.selected_index<=8))&&session->opportunities_active()) { if(!flow.opportunities()||flow.opportunities()->pending()||!flow.statistics_menu()|| menu_request.owner!=flow.statistics_menu()->state().owner|| @@ -664,6 +763,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu flow.reject_statistics_menu("Der Statistikwechsel ist veraltet.");return {}; } try { + // Transaction body: builds exactly one target page, closes the opportunities child and + // switches the flow to the staged page. OpportunitiesActions(*session).apply(revision, [&] { std::optional history; std::optional minutes; @@ -740,6 +841,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return error; } + // The request's owner must still be the desk action that opened the menu (pending, or already + // shown) at the current revision; otherwise the request cannot be assigned to this desk. const bool opening_owner=flow.desktop()&&pending->owner.revision==revision&& ((flow.desktop()->pending()&&*flow.desktop()->pending()==pending->owner)|| (!flow.desktop()->pending()&&flow.desktop()->state().revision==revision)); @@ -835,11 +938,16 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu try { const auto owner=pending->owner; const auto underlay=flow.statistics_menu()->render_page(0); + // Opportunities page (index 0). In the national friendly case the desk's stable session identity + // key is passed to the session so the national-coach desk is identified by its home club. const bool national_source_case=flow.national_friendly_family_active(); const int stable_identity=national_source_case&&flow.desktop()&& owner.manager_slot>=0&&size_t(owner.manager_slot)state().managers.size()? flow.desktop()->state().session_identity_key(size_t(owner.manager_slot)):-1; auto page=OpportunitiesActions(*session).open(owner,revision,underlay,error, + // Callback with the projected opportunities page. Identity check: manager slot, runtime club and + // day counter must equal the desk on screen, and the stable club identity must equal the desk's + // session identity key for that manager; otherwise it throws and nothing is shown. national_source_case,stable_identity,[&](ui::OpportunitiesState& opened) { const auto& desk=flow.desktop()->state(); if(opened.identity.manager_slot!=desk.manager_slot||opened.identity.runtime_team!=desk.runtime_club|| @@ -856,6 +964,9 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return error; } + // Statistics page action: close, or re-query the all-time table. The request must be the + // pending one and match the menu owner and the desk (revision, manager slot); otherwise it is + // dropped. A failing rebuild closes the page. if(result.request==ui::FlowRequest::statistics_page_action&&session) { const auto* pending=flow.pending_statistics_page_action(); if(!pending||*pending!=result.statistics_page_action||!flow.in_statistics_page()|| @@ -881,6 +992,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return {}; } + // Rankings category selection: rebuilds the rankings from the session for the chosen category + // and acknowledges it; any failure is reported as a rejection. if(result.request==ui::FlowRequest::statistics_rankings_action&&session) { const auto* pending=flow.pending_statistics_rankings(); if(!pending||*pending!=result.statistics_rankings_action|| @@ -894,6 +1007,9 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } catch(const std::exception&) { flow.reject_statistics_rankings(); } return {}; } + // Analytics screen action: close, or store a preference through OpportunitiesActions and + // acknowledge the rebuilt page at the new revision. Rejection resets the pending state and + // returns the error. if(result.request==ui::FlowRequest::analytics_action&&session) { const auto* pending=flow.pending_analytics(); if(!pending||*pending!=result.analytics_action||!flow.analytics()||!flow.statistics_menu()|| @@ -917,6 +1033,9 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return error; } + // Opportunities (A-D) screen action: dispatched to the session; on close the parent screen is + // restored (world cup picker for the national friendly case, closing the statistics menu + // otherwise), else the page is acknowledged. Rejections go back to the screen. if(result.request==ui::FlowRequest::opportunities_action&&session) { const auto* pending=flow.pending_opportunities(); if(!pending||*pending!=result.opportunities_action)return {}; @@ -941,6 +1060,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return error; } + // Desk menu 20 (top scorers): opens the read-only top scorers page; same pending-request and + // revision rules as the other menus, rejection goes back to the desk. if(result.request==ui::FlowRequest::desk_action&&session&& result.desk_action.kind==ui::DeskRequestKind::open_menu&&result.desk_action.menu_kind==20) { if(!flow.desktop()||!flow.desktop()->pending()||*flow.desktop()->pending()!=result.desk_action|| @@ -948,6 +1069,9 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu try { const auto underlay=flow.desktop()->render(); auto page=TopScorersActions(*session).open(result.desk_action,revision,underlay,error, + // Callback with the projected page. Identity check as for the other pages: manager slot, runtime + // club and day counter must equal the desk; the club identity is the home club identity that + // the session also builds for the national desk. [&](ui::TopScorersState& opened) { const auto& desk=flow.desktop()->state(); if(opened.identity.manager_slot!=desk.manager_slot|| @@ -967,6 +1091,9 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return error; } + // Desk menus 25 (fair play) and 26 (highscore): builds the read-only records page from the + // session for the active manager. The highscore page also loads, updates and saves the ranked + // highscore file in the save directory. Any error rejects the desk action. if(result.request==ui::FlowRequest::desk_action&&session&& result.desk_action.kind==ui::DeskRequestKind::open_menu&& (result.desk_action.menu_kind==25||result.desk_action.menu_kind==26)) { @@ -1039,6 +1166,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return {}; } + // Top scorers page action: dispatched to the session; the page is closed or acknowledged, + // rejections go back to the page. if(result.request==ui::FlowRequest::top_scorers_action&&session) { const auto* pending=flow.pending_top_scorers(); if(!pending||*pending!=result.top_scorers_action)return {}; @@ -1057,8 +1186,10 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return error; } + // While the read-only top scorers owner is open, every other request is blocked. if(session&&session->top_scorers_active()&&result.request!=ui::FlowRequest::none) return "top scorers: another session action is blocked while the read-only owner is open"; + // Desk menu 28 (balance sheet): opens the balance page through BalanceActions. if(result.request==ui::FlowRequest::desk_action&&session&& result.desk_action.kind==ui::DeskRequestKind::open_menu&&result.desk_action.menu_kind==28) { if(!flow.desktop()||!flow.desktop()->pending()||*flow.desktop()->pending()!=result.desk_action|| @@ -1074,6 +1205,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return error; } + // Balance page action: dispatched to the session; closed or acknowledged, rejections go back + // to the page. if(result.request==ui::FlowRequest::balance_action&&session) { const auto* pending=flow.pending_balance(); if(!pending||*pending!=result.balance_action)return {}; @@ -1092,8 +1225,13 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return error; } + // While the balance owner is open in the session, every other request is blocked. if(session&&session->balance_active()&&result.request!=ui::FlowRequest::none) return "balance: another session action is blocked while the Bilanz owner is open"; + // Shows a league table result from the session. It first validates the dispatch (manager slot, + // league, revision, controls, dialog phase) and throws FormatError if it is inconsistent, then + // replaces the current league's page in the table set and hands it to the flow. Used by every + // branch that enters or changes a league table. const auto show_table_dispatch = [&](const CareerSession::LeagueTableDispatch& applied, std::optional preparation = {},bool friendly_entry=false) { const auto& id = applied.identity; @@ -1116,15 +1254,22 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu flow.show_family_table_dispatch(std::move(tables), id.league, id, applied.dialog, dialog_stage, applied.phase == Phase::forecast_pending_present, std::move(preparation),friendly_entry); }; + // League family action (table, pairings and strengths screens share one owner in the session). + // The request must carry the identity of the owner held by both the flow and the session, at + // the current revision and from the child screen that is really open; otherwise it is stale. if(result.request==ui::FlowRequest::league_family_action&&session) { const auto& action=result.league_family_action; const auto& owner=flow.league_family_identity(); const auto session_family=session->league_family_owner(); + // Identity check: the action's identity must equal the flow's owner and the session's family + // owner, with the same child and the current revision. if(!flow.desktop()||!owner||action.from_child<1||action.from_child>3|| !session_family||session_family->child!=action.from_child||session_family->identity!=action.identity|| action.identity!=*owner||flow.league_family_child()!=action.from_child|| action.identity.revision!=revision) return "league family: stale child request"; + // The friendly opponent table is a restricted purpose of the same owner: the flow and the + // session must agree on it, and only table controls, selection and close are allowed there. if(session_family->friendly_opponent!=flow.friendly_table_active()|| (session_family->friendly_opponent&&action.kind!=ui::LeagueFamilyRequestKind::control&& action.kind!=ui::LeagueFamilyRequestKind::table_range_result&& @@ -1134,11 +1279,15 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu action.kind!=ui::LeagueFamilyRequestKind::select_opponent&& action.kind!=ui::LeagueFamilyRequestKind::close)) return "friendly table: invalid owner purpose or action"; + // Opponent chosen in the friendly table: the session resolves it; picking the own club returns + // to the previous state, otherwise the club friendly calendar state is built and the table + // finished. Errors reject the family screen. if(action.kind==ui::LeagueFamilyRequestKind::select_opponent) { const auto* pending=flow.pending_league_family_action(); if(!session_family->friendly_opponent||!pending||*pending!=action) return "friendly table: opponent is not the pending UI row"; try { + // Transaction body for this branch; an exception ends in the catch below. LeagueFamilyActions(*session).apply(revision, [&]() -> bool { const auto opponent=session->resolve_friendly_table_opponent(action,revision,error); if(!opponent)throw FormatError(error.empty()?"friendly table: opponent rejected":error); @@ -1163,6 +1312,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return {}; } + // Table child: controls, range replies and the forecast acknowledgement. The request must be + // the pending UI action; the session applies it and the new table is shown. if (action.from_child == 1 && (action.kind == ui::LeagueFamilyRequestKind::control || action.kind == ui::LeagueFamilyRequestKind::table_range_result || action.kind == ui::LeagueFamilyRequestKind::table_forecast_presented)) { @@ -1188,6 +1339,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return {}; } + // Team info opened from the table: the presenter runs in the session, then the same table is + // shown again and must match the identity the session returned. if(action.kind==ui::LeagueFamilyRequestKind::team_info&&action.from_child==1) { try { LeagueFamilyActions(*session).apply(revision, [&]() -> bool { @@ -1205,6 +1358,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return {}; } + // Close: leaves the family (or finishes the friendly table) and gives back the desk + // preparation state. A refused close rejects the family screen. if(action.kind==ui::LeagueFamilyRequestKind::close) { try { LeagueFamilyActions(*session).apply(revision, [&]() -> bool { @@ -1225,6 +1380,10 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return error; } + // League selection or group toggle in the table: the session selects the page, then the + // resulting table identity is compared with the request (same manager, club, day counter, + // revision and so on, and the family sequence advanced by one) so a result belonging to a + // different operation is refused. if((action.kind==ui::LeagueFamilyRequestKind::select_league|| action.kind==ui::LeagueFamilyRequestKind::toggle_league_group)&&action.from_child==1) { const auto* pending=flow.pending_league_family_action(); @@ -1262,6 +1421,10 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu return {}; } + // Navigation between table, pairings and strengths: the current child is suspended, a fresh + // manager projection supplies the new identity (family id and league settings are carried + // over) and the target child is prepared, entered and shown. Any step refused rejects the + // family screen. if(action.kind==ui::LeagueFamilyRequestKind::navigate&&flow.league_family_child()==action.from_child&& (action.target_child==1||action.target_child==2||action.target_child==3)) { try { @@ -1325,9 +1488,13 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return error; } + // Anything else is not supported by this owner. flow.reject_league_family("league family action is not yet supported by this owner"); return "league family action is not yet supported by this owner"; } + // Desk menu 2 (strengths): opens the strengths page and starts a league family owner for it. + // The session's projection must match the desk on screen (manager slot, runtime club, day + // counter and the desk's session identity key); otherwise the open is refused. if(result.request==ui::FlowRequest::desk_action&&session&& result.desk_action.kind==ui::DeskRequestKind::open_menu&&result.desk_action.menu_kind==2) { if(!flow.desktop()||!flow.desktop()->pending()||*flow.desktop()->pending()!=result.desk_action|| @@ -1356,6 +1523,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return error; } + // Desk menu 0 (league table): checks manager slot, runtime club and day counter against the + // desk, prepares and begins the league family owner for the table and shows the table. if(result.request==ui::FlowRequest::desk_action&&session&& result.desk_action.kind==ui::DeskRequestKind::open_menu&&result.desk_action.menu_kind==0) { if(!flow.desktop()||!flow.desktop()->pending()||*flow.desktop()->pending()!=result.desk_action|| @@ -1385,6 +1554,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return error; } + // Strengths page action: dispatched to the session; closed or acknowledged. When a league + // family is open its identity is refreshed after the child changed. if(result.request==ui::FlowRequest::strengths_action&&session) { const auto* pending=flow.pending_strengths(); if(!pending||*pending!=result.strengths_action)return {}; @@ -1411,6 +1582,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return error; } + // Desk menu 1 (pairings): checks manager slot, runtime club and day counter against the desk, + // then opens the pairings page and begins the league family owner for it. if(result.request==ui::FlowRequest::desk_action&&session&& result.desk_action.kind==ui::DeskRequestKind::open_menu&&result.desk_action.menu_kind==1) { if(!flow.desktop()||!flow.desktop()->pending()||*flow.desktop()->pending()!=result.desk_action|| @@ -1442,6 +1615,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } return error; } + // Pairings page action: dispatched to the session; closed or acknowledged. With a league family + // open, the family identity is refreshed from the new page state. if(result.request==ui::FlowRequest::league_pairings_action&&session) { const auto* pending=flow.pending_league_pairings(); if(!pending||*pending!=result.league_pairings_action)return {}; @@ -1475,14 +1650,20 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } if (result.request == ui::FlowRequest::desk_action && session && result.desk_action.kind == ui::DeskRequestKind::open_menu && result.desk_action.menu_kind == 29) { + // Desk menu 29: opens the dialog for adding a further manager to the running game. if (!flow.desktop() || !flow.desktop()->pending() || *flow.desktop()->pending() != result.desk_action || result.desk_action.revision != revision) return {}; try { flow.show_manager_join(session->manager_choices(revision),session->selection_context(revision)); } catch (const std::exception&) { flow.reject_desk_action("Der neue Manager kann hier nicht angelegt werden."); } } else if (result.request == ui::FlowRequest::join_cancel && session) { + // Join cancelled: the session drops the half finished join and the flow returns to the desk. if (!flow.join_origin() || *flow.join_origin() != result.desk_action) return {}; session->cancel_manager_join(); flow.reject_manager_join({}); } else if ((result.request == ui::FlowRequest::join_options || result.request == ui::FlowRequest::join_manager) && session) { + // Manager join steps (options, then manager choice): the origin desk action and revision must + // still match. Until the join is complete the team selection resumes; once complete the new + // manager is committed to the session and the flow shows the result. Any failure cancels the + // join and returns an error text. if (!flow.join_origin() || *flow.join_origin() != result.desk_action || result.desk_action.revision != revision) return {}; bool accepted=false; @@ -1521,12 +1702,17 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } } else if (result.request == ui::FlowRequest::manager_confirmed) { + // New-career setup: a manager was confirmed. The session is created on demand, the choice is + // stored and the selection screen resumes with a new revision. if (!session) session = std::make_unique(data, seed); if (enable_autosave) session->configure_autosave_directory(save_directory); const ui::ManagerChoice* choice = flow.pending_manager(); if (!choice || !session->confirm_manager(flow.options(), *choice, error)) return "manager: " + error; flow.resume_manager_selection(session->selection_context(++revision)); } else if (result.request == ui::FlowRequest::new_career) { + // New career: confirms the managers not yet confirmed, then finishes the initialization in the + // session, takes over the first revision and hands the desk to the flow. Season pause and cup + // draw presenters are installed only for this request (see the reset guard). if (!session) session = std::make_unique(data, seed); if (enable_autosave) session->configure_autosave_directory(save_directory); const ui::NewCareerRequest* request = flow.pending_career(); @@ -1536,6 +1722,7 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu ui::CareerInitializationResult init; // Initial setup reaches the same native draw boundaries as annual turns. // Scope presentation hooks to this request, including failure paths. + // Scope guard: removes the presenters again when the request ends, on success or failure. struct InitialHookReset { CareerSession* session; ~InitialHookReset() { @@ -1556,23 +1743,31 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu playback.original_ready() && playback.available()); start_original_desk_audio(playback, session->state(), music_enabled); } else if(result.request==ui::FlowRequest::national_friendly_selected&&session) { + // National friendly: a nation was selected in the picker; the dialog sequence is served by + // serve_national_friendly_selection. serve_national_friendly_selection(flow,*session,result.national_friendly_opponent,revision,data, national_friendly_question_presenter); } else if (result.request == ui::FlowRequest::friendly_action && session) { + // Friendly match request (club or national); served by serve_friendly_action. serve_friendly_action(flow, *session, result.friendly_action, revision,data); } else if (result.request == ui::FlowRequest::submenu_action && session && std::holds_alternative(result.submenu_action)) { + // Transfer market request; served by serve_transfer_action. serve_transfer_action(flow, *session, std::get(result.submenu_action), revision, market_sale_presenter, market_entry_policy, poach_player_selector, poach_notice_presenter, transfer_presenter); } else if (result.request == ui::FlowRequest::submenu_action && session && std::holds_alternative(result.submenu_action)) { + // Outgoing transfer offer; served by serve_transfer_offer. serve_transfer_offer(flow, *session, std::get(result.submenu_action), revision, market_sale_presenter, market_entry_policy, team_info_presenter, player_info_presenter); } else if (result.request == ui::FlowRequest::submenu_action && session && std::holds_alternative(result.submenu_action)) { + // Lineup change: must equal the flow's pending lineup request, otherwise it is dropped. The + // session applies it and the preparation state is acknowledged; a refusal is shown as notice. const auto& request = std::get(result.submenu_action); if (!flow.matches_pending_lineup(request)) return {}; try { + // Callback after the lineup was applied: acknowledges the new preparation projection. if (!LineupActions(*session).lineup(request, revision, error, [&] { flow.acknowledge_preparation(session->preparation_projection(revision)); })) { @@ -1584,6 +1779,7 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } } else if (result.request == ui::FlowRequest::submenu_action && session && std::holds_alternative(result.submenu_action)) { + // Pitch (field position) change: same pattern as the lineup request, through LineupActions. const auto& request = std::get(result.submenu_action); if (!flow.matches_pending_pitch(request)) return {}; try { @@ -1598,6 +1794,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } } else if (result.request == ui::FlowRequest::submenu_action && session && std::holds_alternative(result.submenu_action)) { + // Training change: dispatched to the session; the preparation state is acknowledged or the + // request rejected with the session's error. const auto& request = std::get(result.submenu_action); if (!session->dispatch_training(request, revision, error)) { flow.reject_preparation_action(error); @@ -1606,6 +1804,7 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu flow.acknowledge_preparation(session->preparation_projection(revision)); } else if (result.request == ui::FlowRequest::submenu_action && session && std::holds_alternative(result.submenu_action)) { + // Tactics change: dispatched to the session; acknowledged or rejected with the error. const auto& request = std::get(result.submenu_action); if (!session->dispatch_tactics(request, revision, error)) { flow.reject_preparation_action(error); @@ -1614,6 +1813,7 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu flow.acknowledge_preparation(session->preparation_projection(revision)); } else if (result.request == ui::FlowRequest::submenu_action && session && std::holds_alternative(result.submenu_action)) { + // Training camp request: dispatched to the session; acknowledged or rejected. const auto& request = std::get(result.submenu_action); if (!session->dispatch_training_camp(request, revision, error)) { flow.reject_preparation_action(error); @@ -1622,6 +1822,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu flow.acknowledge_preparation(session->preparation_projection(revision)); } else if (result.request == ui::FlowRequest::submenu_action && session && std::holds_alternative(result.submenu_action)) { + // Bank action: the supplied request must equal the pending one, otherwise it is rejected as + // stale. BankActions applies it and the preparation state is acknowledged. const auto* pending = flow.pending_bank_action(); if (!pending) return {}; const auto request = *pending; @@ -1642,6 +1844,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } } else if (result.request == ui::FlowRequest::submenu_action && session && std::holds_alternative(result.submenu_action)) { + // Stadium action: must equal the pending stadium request; StadiumActions applies it (with the + // construction and compensation notice hooks) and the preparation state is acknowledged. const auto& request = std::get(result.submenu_action); if (!flow.matches_pending_stadium(request)) return {}; try { @@ -1657,6 +1861,7 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } } else if (result.request == ui::FlowRequest::submenu_action && session && std::holds_alternative(result.submenu_action)) { + // Toto (betting) action: dispatched to the session; acknowledged or rejected. const auto& request = std::get(result.submenu_action); if (!session->dispatch_toto(request, revision, error)) { flow.reject_preparation_action(error); @@ -1664,6 +1869,11 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } flow.acknowledge_preparation(session->preparation_projection(revision)); } else if (result.request == ui::FlowRequest::kickoff) { + // Kickoff: plays the next match day. The request must still be the desk's pending action at + // the current revision (a replayed one is ignored). All presenter hooks are installed on the + // session for the duration of the turn and removed again by the reset guard below, then + // dispatch_kickoff runs the whole turn synchronously. A failed or waiting turn rejects the + // desk action, a finished career returns "career_complete", otherwise the new desk is shown. // A consumed/replayed request no longer owns a pending desk action. Ignore // it before installing borrowed presenters or trying to reject that desk. if (!flow.desktop() || !flow.desktop()->pending() || @@ -1672,6 +1882,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu flow.reject_desk_action("turn_driver_unavailable"); return "turn: no active career session"; } + // Scope guard: when the kickoff request ends (normally or by exception) all live match, + // season and presentation hooks are cleared and the previously installed ones restored. struct LiveHookReset { CareerSession* session; TransferOfferPresenter previous_transfer; @@ -1731,6 +1943,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu transfer_decision_presenter(active->state(), event); }); } + // Revision used by live interventions during the turn; the live dispatch lambdas below share it + // by reference. uint64_t live_revision = revision; session->set_live_ball(std::move(live_ball_presenter)); session->set_live_reality(std::move(live_reality_presenter)); @@ -1740,12 +1954,18 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu session->set_live_set_piece(std::move(live_set_piece_presenter)); session->set_live_booking(std::move(live_booking_presenter)); session->set_live_shootout(std::move(live_shootout_presenter)); + // Live minute hook: called by the session every match minute. It forwards the minute to the + // plain presenter and, if set, to the intervention presenter together with callbacks that let + // the UI change the lineup, tactics or pitch of the human team while the match runs. if (live_presenter || live_intervention_presenter) { + // Hook installed on the session; called once per live minute with the engine, groups and state. session->set_live_minute([&live_presenter, &live_intervention_presenter, active = session.get(), &live_revision] (int minute, MatchEngine& engine, std::vector& groups, GameState& state) mutable { if (live_presenter) live_presenter(minute, groups, state); if (live_intervention_presenter) { + // Substitution callback: asks the session to apply a live lineup change for this minute; + // rejected when the session is gone. const auto dispatch = [active, minute, &engine, &live_revision] (const ui::LineupRequest& request) { if (!active) return LiveSubstitutionResult{LiveSubstitutionStatus::rejected, 0, -1, @@ -1753,11 +1973,15 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu return active->dispatch_live_substitution_result(request, minute, 2, engine, live_revision); }; + // Tactics callback: applies a live tactics change through the session; returns false on failure + // and fills the error text. const auto dispatch_tactic = [active, minute, &engine, &live_revision] (const ui::TacticsRequest& request, std::string& error) { return active && active->dispatch_live_tactic(request, minute, 8, engine, live_revision, error); }; + // Pitch callback: applies a live pitch change through the session; rejected when the session is + // gone. const auto dispatch_pitch = [active, minute, &engine, &live_revision] (const ui::PitchRequest& request) { if (!active) return LiveSubstitutionResult{LiveSubstitutionStatus::rejected, 0, -1, @@ -1765,6 +1989,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu return active->dispatch_live_pitch_result(request, minute, 2, engine, live_revision); }; + // Scope callback: opens (begin), commits (finish) or cancels (abort) a live intervention in the + // session for this minute, mode, manager and team. const auto dispatch_scope = [active, minute, &engine, &live_revision] (LiveInterventionBoundary boundary, int mode, int manager, int team, std::string& error) { @@ -1788,25 +2014,33 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } }); } + // Live event hook: called by the session for match events that allow an intervention. The same + // kinds of callbacks as for the minute hook are offered, bound to the event instead of a minute. if (live_match_event_presenter) { session->set_live_event([&live_match_event_presenter, active = session.get(), &live_revision] (const LiveMatchEvent& event, MatchEngine& engine, std::vector& groups, GameState& state) { if (!active) return; + // Substitution callback bound to the event's minute. const auto dispatch = [active, &event, &engine, &live_revision](const ui::LineupRequest& request) { return active->dispatch_live_substitution_result(request, event.minute, 2, engine, live_revision); }; + // Tactics callback bound to the event's minute. const auto dispatch_tactic = [active, &event, &engine, &live_revision] (const ui::TacticsRequest& request, std::string& error) { return active && active->dispatch_live_tactic(request, event.minute, 8, engine, live_revision, error); }; + // Pitch callback bound to the event's minute. const auto dispatch_pitch = [active, &event, &engine, &live_revision] (const ui::PitchRequest& request) { if (!active) return LiveSubstitutionResult{LiveSubstitutionStatus::rejected, 0, -1, "Die Karrieresitzung ist nicht verfügbar."}; return active->dispatch_live_pitch_result(request, event.minute, 2, engine, live_revision); }; + // Scope callback for event interventions. Identity check: the scope must be mode 2 and carry + // the manager slot and team of the event itself; anything else is refused with an error text, + // so a presenter cannot start an intervention for a different manager or team. const auto scope = [active, &event, &engine, &live_revision] (LiveInterventionBoundary boundary, int mode, int manager, int team, std::string& error) { if (!active || mode != 2 || manager != event.manager_slot || team != event.team) { @@ -1829,6 +2063,9 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu dispatch, dispatch_tactic, dispatch_pitch, scope); }); } + // Sportschau (results show) hooks are gated by the game's own options before being installed: + // most parts only run when the intro-after-matchday option is set; intro and fixture views also + // check per-competition settings stored in the game memory. if (sportschau_presenter.kickoff || sportschau_presenter.intro || sportschau_presenter.fixture || sportschau_presenter.replay.step || sportschau_presenter.replay.scene || sportschau_presenter.awards || sportschau_presenter.team_info || sportschau_presenter.winner) { @@ -1840,6 +2077,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu if (source_options.intro_after_matchday != 0) gated.awards = sportschau_presenter.awards; if (source_options.intro_after_matchday != 0) gated.team_info = sportschau_presenter.team_info; if (sportschau_presenter.intro) { + // Intro wrapper: shows the intro once per matchday or once per group as the options demand, and + // only if the memory flags allow it and at least one shown competition has its setting enabled. gated.intro = [source_options, &sportschau_presenter](const GameState& state, const SportschauIntroView& view) { const bool once = view.group_index < 0 && source_options.intro_after_matchday != 0; @@ -1859,6 +2098,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu }; } if (sportschau_presenter.fixture) { + // Fixture wrapper: forwards only when the option and the competition's setting in the game + // memory allow it. gated.fixture = [source_options, &sportschau_presenter](const GameState& state, const SportschauFixtureView& fixture) { if (source_options.intro_after_matchday == 0 || fixture.source_setting_index < 0 || @@ -1879,11 +2120,16 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu session->set_season_promotion(std::move(promotion_presenter)); session->set_season_cup_draw(std::move(cup_draw_presenter)); playback.set_original_options(original_audio_options(session->state(), music_enabled)); + // Sound hook: plays the original match sound cue the session asks for. session->set_original_sound([&playback](uint8_t id, const GameState& state) { original_match_audio_command(playback, state, id); }); + // Runs the turn; the result tells whether it failed, is waiting at the desk, finished the + // career or arrived at the next desk. const auto advanced = session->dispatch_kickoff(result.desk_action, revision, error); start_original_desk_audio(playback, session->state(), music_enabled); + // Debug mode only: logs the outcome and, if the turn did not fail, writes one debug savegame in + // the debug folder after every match day. if (app::debug::enabled()) { // -debug: one savegame after every match day, in the debug folder (DBG00001.FBM, ...). app::debug::log("kickoff handled: " + std::string(advanced.kind == TurnDeskKind::Failed ? "failed" : "ok") + @@ -1913,6 +2159,10 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu // Keep the completed snapshot for queries; an extra generic result modal // has no Original caller and blocks the following desk (UI #69). } else if (result.request == ui::FlowRequest::settings_file_action) { + // Settings file (load or save of the settings file in the save directory): the request must be + // the pending one, belong to the current settings owner (sequence, desk item and manager slot), + // carry the current revision and point into the save directory with the .ein extension; + // otherwise it is rejected as stale. const auto* pending = flow.pending_file(); const auto& request = result.file_action; const auto& desk_owner = flow.settings_desk_owner(); @@ -1926,6 +2176,7 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu return {}; } try { + // Callback after the settings file was handled: acknowledges settings, desk and preparation. const auto dispatched = DeskSettingsActions(*session).file(result.settings_owner_sequence, request, revision, error, [&](CareerSession::DeskSettingsDispatch& applied) { auto desk = session->desktop_projection(revision); @@ -1941,6 +2192,9 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } } else if (result.request == ui::FlowRequest::file_action && result.file_action.file_kind == ui::SaveLoadFileKind::menu_layout) { + // Menu layout file (.men): the request must equal the pending file action field by field; if + // it does not, it is ignored (and rejected if one is pending). Revision and path (inside the + // save directory) are checked before MenuLayoutActions applies it. const auto& request = result.file_action; const auto* pending = flow.pending_file(); const bool same_pending = pending && pending->action == request.action && @@ -1969,6 +2223,10 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu flow.reject_file_action("menu_layout_projection_or_ack_failed"); } } else if (result.request == ui::FlowRequest::file_action) { + // Savegame file action. Revision and path (inside the save directory) are checked first. + // Load: for a running game the request's manager must be the active manager; a new session + // is built from the file and replaces the old one with the next revision. Save: only the + // active manager can save; the revision grows by one after a successful write. const auto& request = result.file_action; if (request.revision != revision || !save_path_in_directory(request.path, save_directory)) { flow.reject_file_action("stale_request_or_invalid_save_path"); @@ -1981,6 +2239,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu return {}; } try { + // Load: the new session is built and projected completely before it replaces the current one, + // so a failed load leaves the running game untouched. auto loaded = std::make_unique(data, seed, request.path); if (enable_autosave) loaded->configure_autosave_directory(save_directory); const uint64_t loaded_revision = revision + 1; @@ -2016,6 +2276,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu flow.reject_file_action("save_written_but_projection_failed"); } } else if (result.request == ui::FlowRequest::mailbox_closed) { + // Mailbox closed: only the pending close request is accepted; MailboxActions applies it and + // the desk is acknowledged. const auto* pending = flow.pending_mailbox_close(); if (!session || !pending || *pending != result.mailbox_close) return {}; try { @@ -2031,6 +2293,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu flow.reject_mailbox_close("Die Nachrichtenansicht konnte nicht geschlossen werden."); } } else if (result.request == ui::FlowRequest::mailbox_action) { + // Mailbox action (read, delete and so on): must equal the pending mailbox request; the session + // applies it and the rebuilt mailbox state is acknowledged. // A consumed/replayed or forged event cannot write through a new modal request. if (!session || !flow.pending_mailbox() || *flow.pending_mailbox() != result.mailbox_action) return {}; @@ -2047,6 +2311,9 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu flow.reject_mailbox("Diese Postfachaktion konnte nicht übernommen werden."); } } else if (result.request == ui::FlowRequest::settings_action) { + // Settings change: must equal the pending request and belong to the current settings owner + // sequence. If the session refuses and the refusal has an original notice text, that notice is + // shown through the presenter before the request is rejected. if (!session || !flow.pending_settings() || *flow.pending_settings() != result.settings_action || result.settings_owner_sequence != flow.settings_owner_sequence()) return {}; @@ -2076,6 +2343,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu return {}; } } else if (result.request == ui::FlowRequest::settings_close) { + // Settings closed: the owner sequence must still match; DeskSettingsActions closes the owner + // and the desk is acknowledged. if (!session || result.settings_owner_sequence != flow.settings_owner_sequence()) return {}; const auto& desk_request = flow.settings_desk_owner(); try { @@ -2093,6 +2362,11 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } else if (result.request == ui::FlowRequest::desk_action && session && result.desk_action.kind == ui::DeskRequestKind::open_menu && (result.desk_action.menu_kind == 4 || result.desk_action.menu_kind == 6 || result.desk_action.menu_kind == 7 || result.desk_action.menu_kind == 8 || result.desk_action.menu_kind == 9 || result.desk_action.menu_kind == 24 || result.desk_action.menu_kind == 27 || result.desk_action.menu_kind == 63 || result.desk_action.menu_kind == 19 || result.desk_action.menu_kind == 21)) { + // Read-only desk menus (4 achievements, 6 friendly matches, 7 and 8 calendars, 9 indoor + // standings, 19 settings, 21 advertising, 24 environment, 27 contracts, 63 mailbox, others + // settings): the request must equal the desk's pending action at the current revision for the + // active manager, otherwise it is rejected as stale. The page is built from the session and + // shown; a failure rejects the desk action and writes the reason to stderr. const auto& request = result.desk_action; if (!flow.desktop() || !flow.desktop()->pending() || request.revision != revision || request.manager_slot != int(session->state().memory.u8(::bmh::layout::ActiveManager)) || @@ -2121,6 +2395,9 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu const int manager = request.manager_slot; const size_t record = size_t(manager) * 0xb0c; const auto live = session->desktop_projection(revision); + // Calendar identity check: the manager's record must point to the manager's current team and a + // fresh desk projection must equal the desk on screen (manager, club, day counter, season, + // options and so on); otherwise the calendar is refused as stale. if (session->career_complete() || manager < 0 || manager > 3 || size_t(manager) >= game.manager_teams.size() || record + 0x291 >= game.manager_records.size() || (uint16_t(game.manager_records[record + 0x290]) | @@ -2152,6 +2429,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } else if (request.menu_kind == 6) { const auto& game = session->state(); const auto& desk = flow.desktop()->state(); + // Friendly menu: for the national-coach desk (team slot 0x165) the nation picker is shown; + // for club managers the friendly opponent table is started in the session. const int manager=request.manager_slot; if(manager>=0&&size_t(manager)state(),revision); view.owner=request.owner; @@ -2270,6 +2560,9 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu return e.what(); } } else if (result.request == ui::FlowRequest::advertising_action && session) { + // Advertising action: must equal the pending request, otherwise it is rejected as outdated. + // The session applies it (for a renewal check the question is shown through the presenter) and + // the advertising view, desk and preparation are acknowledged. const auto* pending = flow.pending_advertising_action(); if (!pending) return {}; if (*pending != result.advertising_action) { @@ -2282,10 +2575,13 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu CareerSession::AdvertisingRenewalPresenter presenter; if (request.kind == ui::AdvertisingActionKind::check_renewal && advertising_renewal_presenter) { const Image backdrop = flow.render(); + // Renewal presenter: shows the renewal question over the current screen. presenter = [&, backdrop](const GameState& staged, const AdvertisingRenewal& question) { return advertising_renewal_presenter(staged, question, backdrop); }; } + // Acknowledge callback: rebuilds the advertising view and adds the original notification text + // when a spending change produced one. const auto acknowledge = [&](const CareerSession::AdvertisingActionResult& applied) { auto state = ui::advertising_from_game(session->state(), request.manager_slot, revision); if (request.kind == ui::AdvertisingActionKind::set_spending && applied.spending.message_address != 0) { @@ -2308,8 +2604,12 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu flow.reject_advertising_action("Die Werbeänderung konnte nicht bestätigt werden."); } } else if (result.request == ui::FlowRequest::contracts_closed && session) { + // Contracts screen closed: drops the stored contract quote. session->clear_contract_quote(); } else if (result.request == ui::FlowRequest::contract_action && session) { + // Contract action (demands, offer, bonuses, insurance): must equal the pending request. The + // session applies it; the callback then rebuilds the contracts view and acknowledges it in the + // form that matches the action kind. const auto* pending = flow.pending_contract_action(); if (!pending) return {}; if (*pending != result.contract_action) { @@ -2355,6 +2655,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu } else if (result.request == ui::FlowRequest::desk_action && session && (result.desk_action.kind == ui::DeskRequestKind::change_ticket_price || result.desk_action.kind == ui::DeskRequestKind::change_option)) { + // Desk widgets (ticket price and options): dispatched to the session; the desk is acknowledged + // with a fresh projection or the action rejected. if (!session->dispatch_desk_widget(result.desk_action, revision, error)) { flow.reject_desk_action(error); return {}; @@ -2362,10 +2664,13 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu flow.acknowledge_desk(session->desktop_projection(revision)); flow.attach_preparation_context(session->preparation_projection(revision)); } else if (result.request == ui::FlowRequest::submenu_action) { + // Fallback for sub-menu requests without an engine adapter. // Every pending request needs an ACK or a rejection. Until its engine // adapter exists, the screen must remain usable after this action. flow.reject_preparation_action("Diese Aktion ist noch nicht verfügbar."); } else if (result.request == ui::FlowRequest::desk_action) { + // Remaining desk actions: a layout change is dispatched to the session; every other desk menu + // is rejected as not available. if (result.desk_action.kind == ui::DeskRequestKind::change_layout) { std::string error; if (!session->dispatch_desktop_layout(result.desk_action, revision, error)) { @@ -2381,6 +2686,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu return {}; } +// Convenience overload without presenters: forwards to the full version with empty hooks and the +// legacy (unpresented) policies; only the national friendly question presenter is passed on. std::string serve_flow_request(ui::StartupFlow& flow,const ui::FlowResult& result, std::unique_ptr& session,const fs::path& data,const fs::path& save_directory, uint32_t seed,uint64_t& revision,openbmh::audio::Playback& playback, diff --git a/src/ui/flow.cpp b/src/ui/flow.cpp index 11b0449..7575ee0 100644 --- a/src/ui/flow.cpp +++ b/src/ui/flow.cpp @@ -10,15 +10,21 @@ #include namespace bmh::ui { +// Pointer motion without a button. Returns changed=true when a screen needs a redraw; only the +// transfer market can raise a request from a plain move. The chain below runs from the screens that sit on +// top of the others down to the setup screens, and the first screen that exists owns the pointer. FlowResult StartupFlow::move_action(int x, int y) { + // The indoor standings page (and its pending release barrier) ignores motion completely. if (indoor_standings_ || indoor_standings_release_barrier_) return {}; if(world_cup_statistics_)return {world_cup_statistics_->move(x,y)}; if(achievements_)return {achievements_->move(x,y)}; + // A league-family request is waiting for the session: input stays blocked until it is acknowledged or rejected. if(family_table_dispatch_pending_)return {}; if(family_table_range_dialog_) { const bool changed=family_table_range_dialog_->move(x,y); return {changed}; } + // Screens below either forward motion to their own hover handling or ignore it (return {}, no redraw). if(other_games_)return {other_games_->move(x,y)}; if(balance_)return {balance_->move(x,y)}; if(top_scorers_)return {top_scorers_->move(x,y)}; @@ -43,7 +49,10 @@ FlowResult StartupFlow::move_action(int x, int y) { return finish_preparation_input(request, true); return {before != transfer_market_->state_json()}; } + // The desktop only reacts when it is the visible screen, i.e. no submenu is open above it. if (desktop_ && screen_name() == "desktop") return {desktop_->pointer_move(x,y)}; + // Remaining screens as one conditional chain: manager join, contracts (unless a player card covers them), + // read-only views and results (no hover), preparation sub-menus, and finally the setup / manager screens. const bool changed = joining_ ? manager_ && !join_options_pending_ && !join_choice_pending_ && manager_->move(x, y) : contracts_ && !player_card_ ? contracts_->move(x, y) @@ -57,7 +66,10 @@ FlowResult StartupFlow::move_action(int x, int y) { } +// File-local validators: they throw FormatError when an engine projection does not match what the flow confirmed. namespace { +// Checks the initial manager list from the engine against the confirmed choices: count, unique club and +// portrait, slot mapping, identity of every slot and of the active manager. void validate_confirmed_manager_projection(const std::vector& choices, const std::vector& managers, const DeskState& desk) { @@ -90,6 +102,9 @@ void validate_confirmed_manager_projection(const std::vector& cho desk.league != active.start_league) throw FormatError("career attachment: active manager identity does not match confirmed choice"); } +// Checks a DeskState returned by the engine against the confirmed roster and the runtime team mapping. +// allow_turn_handoff is true for the advance_turn handoff, where the national-team coach takeover and +// handback may legitimately swap the visible manager roster. void validate_confirmed_desk(const std::vector& choices, const std::vector& runtime_teams, const std::vector& previous, @@ -169,6 +184,8 @@ void validate_confirmed_desk(const std::vector& choices, } } +// Opens the join-manager dialog of a running career. Valid only at the idle desktop whose pending request is +// the open_menu request for menu 29, with a roster that matches the engine; otherwise it throws. void StartupFlow::show_manager_join(std::vector existing, SelectionContext context) { if (!desktop_ || !engine_attached_ || joining_ || in_preparation_menu() || in_readonly_view() || matchday_results_ || !desktop_->pending() || desktop_->pending()->kind != DeskRequestKind::open_menu || @@ -189,6 +206,8 @@ void StartupFlow::show_manager_join(std::vector existing, Selecti manager_.reset(); joining_=true; join_options_pending_=join_choice_pending_=false; } +// Called by the session after it accepted a join_options or join_manager request: builds the next manager +// screen from a newer engine context. A stale or unexpected context throws. void StartupFlow::resume_manager_join(SelectionContext context) { if (!joining_ || (!join_options_pending_ && !join_choice_pending_) || context.revision < join_context_revision_ || @@ -200,6 +219,8 @@ void StartupFlow::resume_manager_join(SelectionContext context) { join_options_pending_=join_choice_pending_=false; } +// Session accepts the join: the new desk projection must belong to the pending origin request (revision + 1, +// same options, same existing managers). On success the desktop is replaced and the join state is cleared. void StartupFlow::acknowledge_manager_join(CareerInitializationResult result) { if (!joining_ || (!join_options_pending_ && !join_choice_pending_) || !desktop_ || !desktop_->pending() || *desktop_->pending() != join_origin_ || @@ -227,6 +248,8 @@ void StartupFlow::acknowledge_manager_join(CareerInitializationResult result) { joining_=join_options_pending_=join_choice_pending_=false; } +// Session rejects or cancels the join. An empty reason only closes the local menu; otherwise the desktop +// shows the rejection. The join state is always cleared. void StartupFlow::reject_manager_join(std::string reason) { if (!joining_) return; if (reason.empty()) desktop_->resolve_local_menu(); @@ -235,13 +258,17 @@ void StartupFlow::reject_manager_join(std::string reason) { joining_=join_options_pending_=join_choice_pending_=false; } +// Feedback image of the pitch screen after a formation save; empty when no pitch screen is open. std::optional StartupFlow::pitch_formation_save_feedback(bool restored)const{ return pitch_?pitch_->formation_save_feedback(restored):std::nullopt; } +// Left button held on the pitch screen: saves the formation template when the hold is long enough and the +// pointer is inside the template area. Ignored while a release barrier or the player card is active. FlowResult StartupFlow::pitch_held_left(int x,int y,uint64_t source_ticks){ if(!pointer_source_hold_ready(source_ticks)||!pitch_||player_card_|| pitch_release_barrier_||pitch_hold_release_barrier_|| + // Only the area x 240..319, y 112..207 reacts to a hold. x<240||x>=320||y<112||y>=208)return {}; const auto before=pitch_->state_json();const auto request=pitch_->save_formation(x,y); PreparationRequest action; @@ -254,11 +281,16 @@ FlowResult StartupFlow::pitch_held_left(int x,int y,uint64_t source_ticks){ return finish_preparation_input(std::move(action),before!=pitch_->state_json()); } +// Button release after a hold of the given length (0..60000 ms). One-shot barriers swallow the release first; +// the screens that act on the release position get it next; a short hold, or one outside the pitch template +// area, is an ordinary click(); a hold of 2000 ms or more there saves the formation. FlowResult StartupFlow::hold(int x,int y,int milliseconds){ if(milliseconds<0||milliseconds>60000)throw FormatError("hold duration must be 0..60000 ms"); + // Release barriers: an earlier action already consumed this button, so its release is dropped once. if(pitch_hold_release_barrier_){pitch_hold_release_barrier_=false;return {};} if(pitch_release_barrier_){pitch_release_barrier_=false;return {};} if(balance_release_barrier_){balance_release_barrier_=false;return {};} + // These screens decide on the release position, so a hold is delivered as their release. if(other_games_)return finish_other_games_input(other_games_->release(x,y)); if(balance_)return finish_balance_input(balance_->release(x,y)); if(top_scorers_)return finish_top_scorers_input(top_scorers_->release(x,y)); @@ -271,34 +303,53 @@ FlowResult StartupFlow::hold(int x,int y,int milliseconds){ return finish_preparation_input(std::move(action),before!=state_json()); } +// Mouse button release (UP), optionally right button or double click. The chain below is ordered as follows: +// 1. one-shot release barriers, which swallow the UP that belongs to an action already handled on DOWN; +// 2. overlays and modal pages (indoor standings, records, achievements, readme, range dialog), which own the +// pointer while they exist; +// 3. statistics pages, checked before their parent statistics menu and falling through to it on release; +// 4. per-screen controllers (stadium, environment, join, contracts, friendly, calendar, tables, ...); +// 5. preparation sub-menus, then the desktop, then the setup and manager screens. +// Ownership rule: each screen holds at most one pending request. While one is pending the screen receives no +// further input; the session must call the matching acknowledge or reject method to unblock it. FlowResult StartupFlow::click(int x, int y, bool right, bool double_click) { + // The UP of a hold-saved formation is dropped once; the right button is not affected by the barrier. if(pitch_hold_release_barrier_&&!right){pitch_hold_release_barrier_=false;return {};} + // Same for the UP that closed a friendly-match question. if(friendly_question_release_barrier_&&!right) { friendly_question_release_barrier_=false;return {}; } + // Barrier eats the UP that opened the indoor standings; afterwards the page ignores release (next line). if (indoor_standings_release_barrier_) { indoor_standings_release_barrier_ = false; return {}; } if (indoor_standings_) return {}; + // Records page: the opening UP is consumed first, later releases go to the page itself. if(desk_records_release_barrier_){desk_records_release_barrier_=false;return {};} if(desk_records_)return {desk_records_->pointer_up(x,y,right)}; + // Request pending for the league-family table: blocked until acknowledge or reject. if(family_table_dispatch_pending_)return {}; if (reschedule_release_barrier_) { reschedule_release_barrier_ = false; return {}; } if(achievements_release_barrier_){achievements_release_barrier_=false;return {};} + // The achievements page does nothing on release. if(achievements_)return {}; if (settings_readme_release_barrier_) { settings_readme_release_barrier_ = false; return {}; } + // Original-wait viewer: the readme screen closes on a mouse DOWN, so a release does nothing here. if (settings_readme_) return {}; // Mouse UP is consumed by the viewer's wait. + // Barrier for the UP that follows a settings action; also tells the settings screen it was consumed. if (settings_release_barrier_) { settings_release_barrier_ = false; if (settings_) settings_->consume_release(); return {}; } + // The modal nation question already consumed the original click UP (see acknowledge_national_friendly_modal_release). if(national_friendly_release_barrier_){national_friendly_release_barrier_=false;return {};} if(pitch_release_barrier_){pitch_release_barrier_=false;return {};} + // Range dialog of the family table owns the pointer; a right release is passed to it as well. if(family_table_range_dialog_) { const bool changed=family_table_range_dialog_->pointer_up(x,y,right); // A consumed release ends drag ownership; it does not start a new @@ -307,9 +358,12 @@ FlowResult StartupFlow::click(int x, int y, bool right, bool double_click) { } if(family_table_release_barrier_){family_table_release_barrier_=false;return {};} if(balance_release_barrier_){balance_release_barrier_=false;return {};} + // Pages that act on release; most of them ignore the right button. if(other_games_)return right?FlowResult{}:finish_other_games_input(other_games_->release(x,y)); + // The national friendly picker reuses the world-cup page; releases go to the parent statistics menu if present. if(world_cup_statistics_&&national_friendly_picker_) return statistics_menu_&&!right ? finish_statistics_menu_input(statistics_menu_->release(x,y)) : FlowResult{}; + // All-time table: a close or table request becomes a statistics-page action; otherwise the release falls through to the parent menu. if(alltime_table_) { const bool changed=alltime_table_->release(x,y); if(const auto& request=alltime_table_->pending();request) { @@ -325,11 +379,13 @@ FlowResult StartupFlow::click(int x, int y, bool right, bool double_click) { return statistics_menu_ && !right ? finish_statistics_menu_input(statistics_menu_->release(x,y)) : FlowResult{}; if(balance_)return right?FlowResult{}:finish_balance_input(balance_->release(x,y)); if(top_scorers_)return right?FlowResult{}:finish_top_scorers_input(top_scorers_->release(x,y)); + // Analytics: with a pending request input is blocked; otherwise releases go to the parent statistics menu. if(analytics_) { if(analytics_->pending())return {}; if(statistics_menu_)return right?FlowResult{}:finish_statistics_menu_input(statistics_menu_->release(x,y)); return {}; } + // Statistics sub-pages below: each handles its own release first and falls back to the parent statistics menu. if(statistics_rankings_) { if(statistics_rankings_->release(x,y))return finish_statistics_rankings_input(true); if(statistics_menu_)return right?FlowResult{}:finish_statistics_menu_input(statistics_menu_->release(x,y)); @@ -350,6 +406,7 @@ FlowResult StartupFlow::click(int x, int y, bool right, bool double_click) { } if(statistics_menu_)return right?FlowResult{}:finish_statistics_menu_input(statistics_menu_->release(x,y)); if(strengths_)return right?FlowResult{}:finish_strengths_input(strengths_->release(x,y)); + // Stadium is checked here as well as in the preparation chain, because its release must restore pressed buttons. if (stadium_) { const auto request = stadium_->release(x,y,right); PreparationRequest action; @@ -368,6 +425,8 @@ FlowResult StartupFlow::click(int x, int y, bool right, bool double_click) { } // Familyclose is Source event8 on DOWN; an orphan UP has no action. if(league_pairings_)return right?FlowResult{}:finish_league_pairings_input(league_pairings_->release(x,y)); + // Join dialog: setup screen first, then the manager screen. While a join_options or join_manager request is + // pending all input is blocked until acknowledge_manager_join or reject_manager_join. if (joining_) { if (join_options_pending_ || join_choice_pending_) return {}; if (!manager_) { @@ -387,6 +446,8 @@ FlowResult StartupFlow::click(int x, int y, bool right, bool double_click) { result.desk_action = join_origin_; result.join_manager = join_choices_.back(); return result; } + // Contracts get input only when no player card covers them. close, pending contract request and a + // player-info request (opens the card over the contracts picture) are checked in this order. if (contracts_ && !player_card_) { const bool changed = contracts_->click(x, y, right); if (contracts_->close_requested()) { contracts_.reset(); return {true, FlowRequest::contracts_closed}; } @@ -404,6 +465,7 @@ FlowResult StartupFlow::click(int x, int y, bool right, bool double_click) { } return {changed}; } + // Friendly match: a request is stored in pending_friendly_action_ and sent out as friendly_action; the session answers with acknowledge_friendly_* or reject_friendly_action. if (friendly_match_) { const auto before = state_json(); auto request = friendly_match_->click(x, y, right); @@ -420,6 +482,7 @@ FlowResult StartupFlow::click(int x, int y, bool right, bool double_click) { } return {before != state_json()}; } + // Calendar: a pending reschedule is returned as reschedule_action, otherwise it is a read-only view. if (calendar_) { const bool changed = calendar_->click(x,y,right); if (calendar_->pending_reschedule()) { @@ -429,6 +492,7 @@ FlowResult StartupFlow::click(int x, int y, bool right, bool double_click) { } return finish_readonly_input(changed); } + // League table: right button acts as ESC; a pending family request is returned before the generic read-only handling. if (league_table_) { const bool changed = right ? league_table_->key("ESC") : league_table_->click(x, y); if(const auto* family=pending_league_family_action()) { @@ -438,6 +502,7 @@ FlowResult StartupFlow::click(int x, int y, bool right, bool double_click) { return finish_readonly_input(changed); } if (mailbox_) return finish_readonly_input(mailbox_->click(x, y, right)); + // A file dialog opened from settings takes the input below instead of the settings parent. if (settings_ && !save_load_) return finish_settings_input(settings_->click(x, y, right)); if (advertising_) return finish_readonly_input(right ? advertising_->key("ESC") : advertising_->click(x, y)); if (matchday_results_) { @@ -453,8 +518,11 @@ FlowResult StartupFlow::click(int x, int y, bool right, bool double_click) { const bool changed = save_load_->click(x, y, right, double_click); return finish_file_input(changed || before != state_json()); } + // Preparation sub-menus: at most one is the active screen; the first existing one receives the click and any + // request it returns is converted by finish_preparation_input. A player card is checked first because it covers its parent. if (in_preparation_menu()) { const auto before = state_json(); + // The player card can switch to its statistics page; that is reported as submenu_opened or submenu_closed. const bool statistics_before = player_card_ && player_card_->in_statistics(); PreparationRequest action; if (player_card_) player_card_->click(x, y, right); @@ -474,6 +542,7 @@ FlowResult StartupFlow::click(int x, int y, bool right, bool double_click) { result.request = player_card_->in_statistics() ? FlowRequest::submenu_opened : FlowRequest::submenu_closed; return result; } + // Idle desktop: its pending request is routed through route_desk. if (desktop_) { const auto before = desktop_->state_json(); auto result = route_desk(desktop_->pointer_up(x, y, right)); @@ -481,6 +550,7 @@ FlowResult StartupFlow::click(int x, int y, bool right, bool double_click) { return result; } if (pending_ || awaiting_context_) return {}; // One request, then wait for an engine adapter. + // Setup screen: load game opens the file dialog, new game starts the manager selection. if (!manager_) { auto r = setup_.click(x, y, right); if (r.request == SetupRequest::load_game) { @@ -493,6 +563,7 @@ FlowResult StartupFlow::click(int x, int y, bool right, bool double_click) { } return {r.changed, FlowRequest::none}; } + // Manager selection: when a manager is accepted, the last one raises new_career, earlier ones wait for the next club context. bool changed = manager_->click(x, y, right); if (manager_->view() != ManagerView::accepted) return {changed, FlowRequest::none}; confirmed_.push_back(manager_->choice()); @@ -504,6 +575,7 @@ FlowResult StartupFlow::click(int x, int y, bool right, bool double_click) { return {true, FlowRequest::manager_confirmed}; } +// Key input (ESC and other key names). Same top-down order as click(); several pages deliberately ignore the keyboard because the original has no key mapping for them. FlowResult StartupFlow::send_key(std::string_view value) { if (indoor_standings_ || indoor_standings_release_barrier_) return {}; if(achievements_)return {}; // AchievementsFromGame waits for its Source mouse event. @@ -601,6 +673,7 @@ FlowResult StartupFlow::send_key(std::string_view value) { return {manager_ && !pending_ && !awaiting_context_ && manager_->key(value)}; } +// Text input for the screens with an editable field. Returns true when something changed. Order is the same as in click(). bool StartupFlow::text(std::string_view value) { if(desk_records_)return desk_records_->text_input(value); if(family_table_dispatch_pending_)return false; @@ -616,11 +689,13 @@ bool StartupFlow::text(std::string_view value) { if (advertising_) return advertising_->text(value); // A retained Settings parent must not block its active file dialog. if (save_load_) return save_load_->text(value); + // Read-only pages, results and the friendly-match screen have no text field. if (matchday_results_ || in_readonly_view() || friendly_match_) return false; return bank_ ? bank_->text(value) : toto_ ? toto_->text(value) : outgoing_transfer_ ? outgoing_transfer_->text(value) : transfer_market_ ? transfer_market_->text(value) : stadium_ ? stadium_->text(value) : !desktop_ && manager_ && !pending_ && !awaiting_context_ && manager_->text(value); } +// Turns the state of the save/load dialog into a FlowResult: close, a pending file request (settings file or game file), or just a redraw. FlowResult StartupFlow::finish_file_input(bool changed) { if (save_load_->close_requested()) { const bool settings_file = save_load_->file_kind() == SaveLoadFileKind::settings; @@ -638,6 +713,8 @@ FlowResult StartupFlow::finish_file_input(bool changed) { return {changed}; } +// Turns the state of the settings screen into a FlowResult. Order: readme request, close request, file request +// (opens the file dialog locally), then a pending settings write for the session. FlowResult StartupFlow::finish_settings_input(bool changed) { if (!settings_) return {changed}; if (settings_->readme_requested()) { @@ -669,6 +746,7 @@ FlowResult StartupFlow::finish_settings_input(bool changed) { return {changed}; } +// Loads a reference save directly into a fresh flow (no engine attached); throws if any screen already exists. void StartupFlow::load_reference(const std::filesystem::path& save, std::optional indoor) { if (manager_ || desktop_) throw FormatError("reference load requires a fresh startup flow"); auto state = std::make_unique(load_preparation_reference(save, load_le(asset_path(data_, "BMH.exe")))); @@ -677,6 +755,7 @@ void StartupFlow::load_reference(const std::filesystem::path& save, std::optiona desktop_ = std::move(desktop); preparation_ = std::move(state); } +// Session accepts the pending new_career request with the engine's first desk projection; validates it against the confirmed setup and shows the desktop. void StartupFlow::attach_initialized_career(CareerInitializationResult result) { if (!pending_ || desktop_) throw FormatError("career attachment requires a pending new-career request"); validate_desk_profile(pending_->options); @@ -690,6 +769,8 @@ void StartupFlow::attach_initialized_career(CareerInitializationResult result) { confirmed_runtime_teams_ = runtime_teams; } +// Session accepts a desk request with the new engine projection. Only valid at the desktop without submenus; +// the preparation context is dropped so a fresh one must be attached. void StartupFlow::acknowledge_desk(DeskState state) { if (!desktop_ || !engine_attached_ || in_preparation_menu() || in_readonly_view() || state.source != "engine_projection") throw FormatError("desk acknowledgement requires an attached engine projection"); @@ -702,6 +783,7 @@ void StartupFlow::acknowledge_desk(DeskState state) { preparation_.reset(); // Require a fresh same-revision context after any desk command. } +// Opens the mailbox automatically when the desk has a mailbox notification pending; requires the idle active club desk. void StartupFlow::show_notified_mailbox(MailboxState state) { if (!desktop_ || !engine_attached_ || desktop_->pending() || in_preparation_menu() || in_readonly_view() || matchday_results_ || !desktop_->state().mailbox_notification_pending || @@ -712,6 +794,7 @@ void StartupFlow::show_notified_mailbox(MailboxState state) { original_to_utf8(desktop_->state().manager_name), desktop_->render()); } +// Session accepts the pending mailbox close: the desk may only lose its notification flag, everything else must be unchanged. void StartupFlow::acknowledge_mailbox_close(const MailboxCloseRequest& request, DeskState desk, PreparationState preparation) { if (!mailbox_ || !pending_mailbox_close_ || *pending_mailbox_close_ != request || !desktop_ || @@ -734,6 +817,7 @@ void StartupFlow::acknowledge_mailbox_close(const MailboxCloseRequest& request, pending_mailbox_close_.reset(); } +// Session rejects the pending mailbox close; the mailbox stays open and shows the reason. void StartupFlow::reject_mailbox_close(std::string reason) { if (!pending_mailbox_close_ || !mailbox_) throw FormatError("mailbox: no pending close to reject"); pending_mailbox_close_.reset(); @@ -741,6 +825,7 @@ void StartupFlow::reject_mailbox_close(std::string reason) { mailbox_->reject(std::move(reason)); } +// Resolves the local achievements menu request of the desk (menu 4), which has no engine side effect. void StartupFlow::acknowledge_desk_notice(const DeskRequest& owner) { if(!desktop_||!desktop_->pending()||*desktop_->pending()!=owner|| owner.kind!=DeskRequestKind::open_menu||owner.menu_kind!=4) @@ -748,11 +833,13 @@ void StartupFlow::acknowledge_desk_notice(const DeskRequest& owner) { desktop_->resolve_local_menu(); } +// Session rejects the pending desk request; the desktop shows the reason. void StartupFlow::reject_desk_action(std::string reason) { if (!desktop_) throw FormatError("no desktop action context"); desktop_->reject_action(std::move(reason)); } +// Session answers a pending quote request; returns false if none is pending or the screen refuses it. bool StartupFlow::acknowledge_friendly_quote(FriendlyQuoteProjection quote) { if (!friendly_match_ || !pending_friendly_action_ || pending_friendly_action_->kind != FriendlyRequestKind::quote || @@ -761,6 +848,7 @@ bool StartupFlow::acknowledge_friendly_quote(FriendlyQuoteProjection quote) { return true; } +// Answers a pending booking request that was not accepted; the dialog stays open. bool StartupFlow::acknowledge_friendly_booking(FriendlyBookingAck ack) { if (!friendly_match_ || !pending_friendly_action_ || pending_friendly_action_->kind != FriendlyRequestKind::book || ack.accepted || @@ -769,6 +857,7 @@ bool StartupFlow::acknowledge_friendly_booking(FriendlyBookingAck ack) { return true; } +// Answers an accepted booking: validates the new desk and preparation (revision + 1) and leaves the friendly screen. Returns false without changes on a mismatch. bool StartupFlow::acknowledge_friendly_booking(FriendlyBookingAck ack, DeskState desk, PreparationState preparation) { if (!friendly_match_ || !pending_friendly_action_ || @@ -798,6 +887,7 @@ bool StartupFlow::acknowledge_friendly_booking(FriendlyBookingAck ack, DeskState return true; } +// Session rejects the pending friendly request; the screen shows the reason and the request is cleared. void StartupFlow::reject_friendly_action(std::string reason) { if (!friendly_match_ || !pending_friendly_action_ || reason.empty()) throw FormatError("friendly match rejection requires a pending request"); @@ -805,6 +895,7 @@ void StartupFlow::reject_friendly_action(std::string reason) { pending_friendly_action_.reset(); } +// Session confirms a game save requested through the file dialog; the new desk must be a later revision of the same manager slot. void StartupFlow::acknowledge_saved_game(DeskState desk, PreparationState preparation) { if (!save_load_ || !save_load_->pending() || save_load_->pending()->file_kind != SaveLoadFileKind::game || save_load_->pending()->action != SaveLoadAction::save || @@ -830,11 +921,13 @@ void StartupFlow::acknowledge_saved_game(DeskState desk, PreparationState prepar desktop_ = std::move(next_desktop); preparation_ = std::move(next_preparation); } +// Session rejects the pending file request; the dialog shows the reason. void StartupFlow::reject_file_action(std::string reason) { if (!save_load_) throw FormatError("save/load: no file dialog"); save_load_->reject(std::move(reason)); } +// Session confirms a menu-layout file operation. Only the menu items and shortcuts may differ from the old desk. void StartupFlow::acknowledge_menu_layout(DeskState desk, PreparationState preparation) { if (!save_load_ || !save_load_->pending() || save_load_->pending()->file_kind != SaveLoadFileKind::menu_layout || @@ -884,6 +977,7 @@ void StartupFlow::acknowledge_menu_layout(DeskState desk, PreparationState prepa desktop_ = std::move(next_desktop); preparation_ = std::move(next_preparation); } +// Session confirms a loaded game: replaces desktop and preparation, and clears any setup or manager-selection state. void StartupFlow::attach_loaded_game(DeskState desk, PreparationState preparation) { if (!save_load_ || !save_load_->pending() || save_load_->pending()->action != SaveLoadAction::load || save_load_->pending()->file_kind != SaveLoadFileKind::game || @@ -904,6 +998,7 @@ void StartupFlow::attach_loaded_game(DeskState desk, PreparationState preparatio engine_attached_ = true; } +// Session answers a manager_confirmed request with a newer club-order context so the next manager can be chosen. bool StartupFlow::resume_manager_selection(SelectionContext context) { if (!awaiting_context_ || context.revision <= roster_revision_ || context.club_order.empty()) throw FormatError("manager selection: expected a newer engine/reference club-order context"); @@ -914,6 +1009,7 @@ bool StartupFlow::resume_manager_selection(SelectionContext context) { return true; } +// Name of the visible screen. The order mirrors the input chains: overlays and pages first, then submenus, desktop, setup. std::string StartupFlow::screen_name() const { if (indoor_standings_) return "indoor_standings"; if(achievements_)return "achievements"; @@ -940,6 +1036,8 @@ std::string StartupFlow::screen_name() const { if (friendly_table_active_) return "friendly_match"; return player_card_ ? (player_card_->in_statistics() ? "player_statistics" : "player_card") : contracts_ ? "contracts" : friendly_match_ ? "friendly_match" : league_table_ ? "league_table" : mailbox_ ? "mailbox" : save_load_ ? "save_load" : settings_ ? "settings" : advertising_ ? "advertising" : environment_ ? "environment" : matchday_results_ ? "matchday_results" : player_card_ ? (player_card_->in_statistics() ? "player_statistics" : "player_card") : pitch_ ? "pitch" : lineup_ ? "lineup" : training_ ? "training" : training_camp_ ? "training_camp" : bank_ ? "bank" : stadium_ ? "stadium" : toto_ ? "toto" : transfer_market_ ? "transfer_market" : tactics_ ? "tactics" : desktop_ ? "desktop" : pending_ ? "career_pending" : awaiting_context_ ? "manager_pending" : manager_ ? manager_->screen_name() : "setup"; } +// JSON description of the visible screen for tests and tools. Same screen priority as screen_name(); many +// screens append the engine_attached flag and the desktop context. std::string StartupFlow::state_json() const { if (indoor_standings_) return indoor_standings_->state_json(); if(achievements_)return "{\"screen\":\"achievements\",\"manager\":"+ diff --git a/src/ui/flow.hpp b/src/ui/flow.hpp index b8690a5..f44f6ab 100644 --- a/src/ui/flow.hpp +++ b/src/ui/flow.hpp @@ -59,9 +59,15 @@ struct CareerInitializationResult { std::vector managers; PreparationState preparation; }; +// Kind of request a FlowResult carries. none means nothing for the session to do; every other value names +// the FlowResult field that holds the typed payload (desk_action, file_action, contract_action, ...). enum class FlowRequest { none, load_game, manager_confirmed, new_career, kickoff, desk_action, end_session, submenu_opened, submenu_closed, contracts_closed, submenu_action, file_action, results_closed, mailbox_action, mailbox_closed, settings_action, settings_close, settings_file_action, friendly_action, national_friendly_selected, contract_action, advertising_action, environment_action, join_options, join_manager, join_cancel, league_pairings_action, strengths_action, top_scorers_action, balance_action, other_games_action, league_family_action, opportunities_action, statistics_menu_action, statistics_rankings_action, analytics_action, statistics_page_action, reschedule_action }; +// What a statistics sub-page asked for: close it, change the all-time table, or change the world-cup page. enum class StatisticsPageActionKind : uint8_t { close, alltime, world_cup }; +// Request raised by a statistics sub-page: the desk request that owns it, the page number and the selection. struct StatisticsPageAction { DeskRequest owner{}; int page=-1; StatisticsPageActionKind kind=StatisticsPageActionKind::close; int nation=-1; bool relative=false; bool operator==(const StatisticsPageAction&) const = default; }; +// Outcome of one input event. changed means the screen needs a redraw; request tells the session which payload +// field is valid. The session performs the action and then calls the matching acknowledge or reject method. struct FlowResult { bool changed = false; FlowRequest request = FlowRequest::none; @@ -93,18 +99,25 @@ struct FlowResult { RescheduleAction reschedule_action{}; }; +// Screen controller. Each open screen is owned by one unique_ptr member below; input goes to the topmost one. +// Ownership rule: a screen holds at most one pending request and takes no more input until the session calls +// the matching acknowledge or reject method. class StartupFlow { public: explicit StartupFlow(const std::filesystem::path& data, std::filesystem::path save_directory = {}) : data_(data), save_directory_(save_directory.empty() ? data : std::move(save_directory)), setup_(data) {} + // Mouse button release (UP) with optional right button and double click; the main dispatch chain, see flow.cpp. FlowResult click(int x, int y, bool right = false, bool double_click = false); + // Mouse button press (DOWN) entry point; click() handles the matching release. FlowResult pointer_down(int x,int y,bool right=false); + // Timer expiry event together with the current pointer position. FlowResult process_timer_expired(int pointer_x = 0, int pointer_y = 0); bool timed_notice_open() const; FlowResult expire_timed_notice(); // The synchronous SDL question presenter consumes the original nation-click UP. // Call only after that modal has returned; right-DOWN close keeps its barrier. void acknowledge_national_friendly_modal_release() { national_friendly_release_barrier_=false; } + // Ends the stadium tip display after its time ran out. FlowResult expire_stadium_tip(); bool in_stadium() const { return bool(stadium_); } bool in_pitch() const { return bool(pitch_); } @@ -112,17 +125,25 @@ public: return pitch_ && screen_name() == "pitch" ? pitch_->pointer_cursor(palette) : std::nullopt; } std::optional pitch_formation_save_feedback(bool restored) const; + // Left button held on the pitch screen (formation template save); source_ticks is the source-clock hold time. FlowResult pitch_held_left(int x, int y, uint64_t source_ticks); + // Drops the pitch release barrier when the matching release will never arrive. void consume_orphaned_pitch_release(){pitch_release_barrier_=false;} const StadiumScreen* stadium() const { return stadium_.get(); } const TotoScreen* toto() const { return toto_.get(); } + // Button release after a hold of the given length in milliseconds. FlowResult hold(int x, int y, int milliseconds); + // Pointer motion; the bool move() below only reports whether a redraw is needed. FlowResult move_action(int x, int y); bool move(int x, int y) { return move_action(x, y).changed; } + // Text input for screens with an editable field; returns true when something changed. bool text(std::string_view value); bool key(std::string_view value) { return send_key(value).changed; } + // Key input; the bool key() above only reports whether a redraw is needed. FlowResult send_key(std::string_view value); + // Session answers manager_confirmed with a newer club-order context so the next manager can be chosen. bool resume_manager_selection(SelectionContext context); + // Join-manager dialog of a running career: show, resume, acknowledge or reject (join_* requests). void show_manager_join(std::vector existing, SelectionContext context); void resume_manager_join(SelectionContext context); void acknowledge_manager_join(CareerInitializationResult result); @@ -130,20 +151,27 @@ public: const DeskRequest* join_origin() const { return joining_ ? &join_origin_ : nullptr; } const SetupOptions* pending_join_options() const { return join_options_pending_ ? &join_setup_->options() : nullptr; } const ManagerChoice* pending_join_manager() const { return join_choice_pending_ ? &join_choices_.back() : nullptr; } + // Draws the currently visible screen. Image render() const; + // Loads a reference save into a fresh flow without an engine. void load_reference(const std::filesystem::path& save, std::optional indoor = std::nullopt); + // Session accepts the pending new_career request with the engine's first desk projection. void attach_initialized_career(CareerInitializationResult result); + // Session accepts or rejects a desk request (desk_action) with the new engine projection or a reason. void acknowledge_desk(DeskState state); void reject_desk_action(std::string reason); void acknowledge_desk_notice(const DeskRequest& owner); void acknowledge_saved_game(DeskState desk, PreparationState preparation); // Complete an authenticated menu-layout operation while preserving the active career. void acknowledge_menu_layout(DeskState desk, PreparationState preparation); + // Session answers or rejects a file dialog request (file_action). void reject_file_action(std::string reason); + // Session confirms a loaded game and replaces desktop and preparation state. void attach_loaded_game(DeskState desk, PreparationState preparation); const SaveLoadRequest* pending_file() const { return save_load_ && save_load_->pending() ? &*save_load_->pending() : nullptr; } + // Stores the context the preparation sub-menus (lineup, training, bank, ...) are opened from. void attach_preparation_context(PreparationState state); void show_matchday_results(MatchdayResults results); bool in_results_view() const { return bool(matchday_results_); } @@ -197,6 +225,8 @@ public: const LeagueFamilyRequest* pending_pairings_family_action() const { return league_pairings_&&league_pairings_->pending_family_action()?&*league_pairings_->pending_family_action():nullptr; } + // From here on the screens follow one naming pattern: show_X opens a screen, pending_X exposes its single pending + // request, acknowledge_X applies the session's accepted result, reject_X shows the reason, close_X leaves it. void show_mailbox(MailboxState state); // Source's MailboxRecipientMask popup is consumed after the native desk draw, without a // synthetic DeskRequest. The app polls the Session latch only at an idle desk. @@ -350,6 +380,7 @@ public: void acknowledge_reschedule(CalendarState state, DeskRequest owner, DeskState desktop, PreparationState preparation); void reject_reschedule(); + // True while a screen that waits for a mouse event in the original still holds a release barrier. bool source_mouse_wait_release_pending() const { return indoor_standings_release_barrier_ || reschedule_release_barrier_ || achievements_release_barrier_ || desk_records_release_barrier_; } @@ -399,6 +430,7 @@ public: void acknowledge_contract_bonuses(ContractsState state, DeskState desk, PreparationState preparation); void acknowledge_contract_insurance(ContractsState state, DeskState desk, PreparationState preparation); void reject_contract_action(std::string reason); + // True while any read-only or list page is open; text() ignores them. bool in_readonly_view() const { return bool(desk_records_ || achievements_ || indoor_standings_ || other_games_ || strengths_ || top_scorers_ || opportunities_ || statistics_menu_ || statistics_rankings_ || analytics_ || minute_statistics_ || transfer_history_ || league_pairings_ || calendar_ || league_table_ || mailbox_ || settings_ || advertising_ || alltime_table_ || world_cup_statistics_ || finance_totals_ || series_records_); } void acknowledge_preparation(PreparationState state, std::string transfer_notice = {}); void reject_preparation_action(std::string reason); @@ -407,15 +439,19 @@ public: bool matches_pending_lineup(const LineupRequest&) const; bool matches_pending_pitch(const PitchRequest&) const; bool matches_pending_stadium(const StadiumRequest&) const; + // True while any preparation sub-menu is open; they are dispatched together in click and send_key. bool in_preparation_menu() const { return bool(other_games_ || balance_ || player_card_ || pitch_ || lineup_ || training_ || training_camp_ || bank_ || stadium_ || environment_ || toto_ || transfer_market_ || tactics_ || save_load_ || friendly_match_ || contracts_); } bool file_info_press(int x, int y) { return save_load_ && save_load_->info_press(x, y); } const DesktopScreen* desktop() const { return desktop_.get(); } + // Name of the visible screen. std::string screen_name() const; + // JSON description of the visible screen for tests and tools. std::string state_json() const; const SetupOptions& options() const { return setup_.options(); } const NewCareerRequest* pending_career() const { return pending_.get(); } const ManagerChoice* pending_manager() const { return awaiting_context_ ? &confirmed_.back() : nullptr; } private: + // The finish_*_input helpers turn the state of one screen after an input into a FlowResult (close, pending request or redraw). FlowResult finish_statistics_rankings_input(bool changed); FlowResult finish_analytics_input(bool changed); bool joining_ = false, join_options_pending_ = false, join_choice_pending_ = false; @@ -434,6 +470,8 @@ private: std::unique_ptr matchday_results_; std::unique_ptr calendar_; std::unique_ptr indoor_standings_; + // Release barriers, here and further below: a one-shot flag set when an action already consumed the button, + // so the matching release is swallowed once by click() or hold(). bool indoor_standings_release_barrier_ = false; std::unique_ptr strengths_; std::unique_ptr top_scorers_; @@ -505,6 +543,7 @@ private: std::unique_ptr pitch_; bool pitch_entry_pending_ = false; std::unique_ptr player_card_; + // Converts a desk request raised by the desktop into a FlowResult for the session. FlowResult route_desk(DeskRequest); FlowResult finish_preparation_input(PreparationRequest, bool changed); FlowResult finish_file_input(bool changed); @@ -517,6 +556,7 @@ private: FlowResult finish_statistics_menu_input(bool changed); FlowResult finish_balance_input(bool changed); FlowResult finish_other_games_input(bool changed); + // True once an engine projection has been accepted; reported in state_json. bool engine_attached_ = false; bool balance_release_barrier_ = false; bool achievements_release_barrier_ = false;