Manage real OBS careers in native save and load dialogs (by Codex)

This commit is contained in:
Codex committed 2026-10-29 02:57:32 +01:00
1 parent 693744a961
commit e3ea03a05d
25 files changed
+539 -39

No files matched your search

+7
View File
@@ -15,6 +15,7 @@
#include "modern/content/press_journal.hpp"
#include "modern/content/statistics.hpp"
#include "modern/content/world_package.hpp"
#include "modern/content/world_save.hpp"
#include "modern/game/almanac.hpp"
#include "modern/game/desk_actions.hpp"
#include "modern/game/environment.hpp"
@@ -494,6 +495,12 @@ cli::Json ui_read(const ModernState& g, const UiContext& c, const cli::Json& req
const std::string today = *std::get<O>(m.value).at("date").string();
if (kind == "session") return snapshot(request_id, std::move(m), session_data(g, c));
if (kind == "desktop") return snapshot(request_id, std::move(m), desktop_data(g, c, today));
if (kind == "file-metadata") {
const auto* world=current_world();
if(!world)return failure(request_id,"world_unavailable","Keine aktive Modern-Welt.",c.state_revision);
try{return snapshot(request_id,std::move(m),world_career_metadata(*world,g));}
catch(const std::exception&){return failure(request_id,"metadata_unavailable","Spielstandangaben nicht verfügbar.",c.state_revision);}
}
if (kind == "camps") return snapshot(request_id, std::move(m), camps_data(g, c, std::to_string(c.state_revision)));
if (kind == "player-rankings" || kind == "fairplay") {
J data = query_rankings(g, c.manager, request);
+32
View File
@@ -3,6 +3,7 @@
#include <algorithm>
#include <bit>
#include <cstdio>
#include <utility>
#include <variant>
#include <set>
@@ -13,6 +14,7 @@
#include "formats/native_state.hpp"
#include "import/detail.hpp"
#include "modern/game/save.hpp"
#include "formats/executable_layout.hpp"
namespace bmh::modern {
@@ -266,4 +268,34 @@ SavedWorldCareer load_world_career(const std::filesystem::path& path, const Worl
return out;
}
cli::Json world_career_metadata(const World& world,const ModernState& state) {
const bool coach=state.memory.has(::bmh::layout::CoachActive)&&state.memory.u8(::bmh::layout::CoachActive)!=0;
const int count=coach?state.memory.u8(::bmh::layout::OriginalManagerCount):int(state.manager_teams.size());
if(count<1||count>4)fail("unsupported saved manager count");
const int runtime=coach?0:state.memory.has(::bmh::layout::ActiveManager)?state.memory.u8(::bmh::layout::ActiveManager):0;
const int active=state.human_manager_slot(runtime);if(active<0||active>=count)fail("invalid saved active manager");
A managers;int active_team=-1;
for(int human=0;human<count;++human) {
const int record=state.manager_record_slot(human);const size_t at=size_t(record)*0xb0c;
if(at+0x292>state.manager_records.size())fail("saved manager record missing");
const int team=record>=0&&size_t(record)<state.manager_teams.size()?state.manager_teams[size_t(record)]:int(uint16_t(state.manager_records[at+0x290])|uint16_t(state.manager_records[at+0x291])<<8);
if(team<0||size_t(team)>=state.world_club_id.size())fail("saved manager team missing");
const auto* presentation=state.manager_presentation_for_human(human);std::string name;
if(presentation)name=presentation->name;else {for(size_t n=0;n<25&&state.manager_records[at+0xa8+n];++n)name.push_back(char(state.manager_records[at+0xa8+n]));name=almanac_utf8(name);}
const auto id=size_t(human)<state.manager_ids.size()&&!state.manager_ids[size_t(human)].empty()?state.manager_ids[size_t(human)]:"manager:slot-"+std::to_string(human);
managers.push_back(O{{"id",id},{"name",name},{"club",state.world_club_id[size_t(team)]},{"team_name",coach&&record==0?std::string("Deutschland"):size_t(team)<state.world_club_name.size()?state.world_club_name[size_t(team)]:std::string()},{"portrait",int(state.manager_records[at+0x221])},{"portrait_style",presentation?presentation->portrait_style:"photo"},{"national",coach&&record==0}});
if(human==active)active_team=team;
}
const auto date=almanac_date(state.date,state.display_start_year);char iso[16];std::snprintf(iso,sizeof iso,"%04d-%02d-%02d",date.year,date.month,date.day);
const int year=state.display_start_year+state.season,next=(year+1)%100;const auto season=std::to_string(year)+"/"+(next<10?"0":"")+std::to_string(next);std::string round="—";
if(!coach) {
std::vector<const WorldLeague*> leagues;for(const auto& l:world.leagues)if(l.index>=0)leagues.push_back(&l);std::sort(leagues.begin(),leagues.end(),[](auto* a,auto* b){return a->index<b->index;});
int first=0;for(const auto* l:leagues){const int size=int(l->members.size());if(active_team>=first&&active_team<first+size&&size>1&&size_t(l->index)<state.league_rounds.size())round=std::to_string(std::min(int(state.league_rounds[size_t(l->index)])+1,(size-1)*2))+". Spieltag";first+=size;}
}
return O{{"schema","modern-career-metadata@1"},{"career_id",state.career_id},{"world_id",world.id},{"world_revision",world.data_revision},{"date",iso},{"season",season},{"matchday",round},{"role",coach?"national":"club"},{"human_count",count},{"current_manager",managers.at(size_t(active))},{"managers",std::move(managers)}};
}
cli::Json read_world_career_metadata(const std::filesystem::path& path,const World& world) {
const auto saved=load_world_career(path,world);return world_career_metadata(world,saved.state);
}
} // namespace bmh::modern
+4
View File
@@ -29,6 +29,10 @@ void save_world_career(const std::filesystem::path& path, const World& world, co
const WatcomRandom& random, const GameRandom& game, const TurnDriver& driver, bool overwrite,
const cli::Json& session = {});
// Read-only metadata, independent of the active session and global world layout.
cli::Json world_career_metadata(const World&,const ModernState&);
cli::Json read_world_career_metadata(const std::filesystem::path&,const World&);
// Throws FormatError when the save is damaged, not a Modern save or belongs to another world.
SavedWorldCareer load_world_career(const std::filesystem::path& path, const World& world);
+2 -2
View File
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: GPL-3.0-only
add_library(bmh_modern_ui_core STATIC catalog.cpp crest_contrast.cpp engine_dto.cpp model.cpp demo_career.cpp demo_national_ui.cpp gui_assets.cpp desktop.cpp demo_sports.cpp demo_calendar.cpp demo_reports.cpp demo_almanac.cpp demo_finance.cpp demo_environment.cpp demo_advertising.cpp demo_toto.cpp demo_lineup.cpp demo_live.cpp demo_post_match.cpp demo_transfer.cpp demo_career_reports.cpp demo_rankings.cpp demo_stadium.cpp demo_statistics.cpp demo_news.cpp news_catalog.cpp news_journal.cpp demo_settings.cpp ui_preferences.cpp demo_widgets.cpp demo_files.cpp demo_opening.cpp)
add_library(bmh_modern_ui_core STATIC catalog.cpp crest_contrast.cpp engine_dto.cpp model.cpp demo_career.cpp demo_national_ui.cpp gui_assets.cpp desktop.cpp demo_sports.cpp demo_calendar.cpp demo_reports.cpp demo_almanac.cpp demo_finance.cpp demo_environment.cpp demo_advertising.cpp demo_toto.cpp demo_lineup.cpp demo_live.cpp demo_post_match.cpp demo_transfer.cpp demo_career_reports.cpp demo_rankings.cpp demo_stadium.cpp demo_statistics.cpp demo_news.cpp news_catalog.cpp news_journal.cpp demo_settings.cpp ui_preferences.cpp demo_widgets.cpp demo_files.cpp career_files.cpp demo_opening.cpp)
target_include_directories(bmh_modern_ui_core PUBLIC ../..)
target_link_libraries(bmh_modern_ui_core PUBLIC bmh_asset_io)
add_library(bmh_modern_ui_mods STATIC mod_library.cpp)
@@ -49,7 +49,7 @@ foreach(asset modern.rml theme.rcss ticket.rcss sports.rcss calendar.rcss report
configure_file("${CMAKE_SOURCE_DIR}/assets/modern/${asset}" "${modern_assets}/${asset}" COPYONLY)
endforeach()
foreach(component career_reports rankings)
foreach(component career_reports rankings career_files)
add_executable(modern_${component}_tests ../../../tests/modern_${component}_tests.cpp)
target_link_libraries(modern_${component}_tests PRIVATE bmh_modern_ui_core)
if(MSVC)
+122
View File
@@ -0,0 +1,122 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "modern/ui/career_files.hpp"
#include "content/digest.hpp"
#include <algorithm>
#include <chrono>
#include <iomanip>
#include <sstream>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <fcntl.h>
#include <sys/file.h>
#include <unistd.h>
#endif
namespace bmh::modern_ui {
namespace {
constexpr uint64_t file_limit=256*1024*1024;
void safe_directory(const fs::path &path,bool create=false) {
fs::path current;
for(const auto &part:fs::absolute(path).lexically_normal()) {
current/=part;const auto status=fs::symlink_status(current);
if(fs::is_symlink(status)||(fs::exists(status)&&!fs::is_directory(status)))throw editor::Error("Die Spielstandablage ist nicht verfügbar.");
}
if(create)fs::create_directories(path);
}
std::string bytes(const fs::path &path) {
if(fs::is_symlink(fs::symlink_status(path))||!fs::is_regular_file(path))throw editor::Error("Der Spielstand ist keine reguläre Datei.");
return editor::read_file(path,file_limit);
}
std::string timestamp(const fs::path &file) {
const auto elapsed=fs::last_write_time(file)-fs::file_time_type::clock::now();const auto time=std::chrono::system_clock::now()+std::chrono::duration_cast<std::chrono::system_clock::duration>(elapsed);const auto days=std::chrono::floor<std::chrono::days>(time);const std::chrono::year_month_day date{days};const std::chrono::hh_mm_ss clock{std::chrono::floor<std::chrono::seconds>(time-days)};
std::ostringstream out;out<<std::setfill('0')<<std::setw(4)<<int(date.year())<<'-'<<std::setw(2)<<unsigned(date.month())<<'-'<<std::setw(2)<<unsigned(date.day())<<' '<<std::setw(2)<<clock.hours().count()<<':'<<std::setw(2)<<clock.minutes().count()<<" UTC";return out.str();
}
struct Lock {
#ifdef _WIN32
HANDLE handle=INVALID_HANDLE_VALUE;
#else
int handle=-1;
#endif
explicit Lock(const fs::path &directory) {
safe_directory(directory,true);const auto path=directory/".career-files.lock";
if(fs::is_symlink(fs::symlink_status(path)))throw editor::Error("Die Spielstandablage ist nicht verfügbar.");
#ifdef _WIN32
handle=CreateFileW(path.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,nullptr);
if(handle==INVALID_HANDLE_VALUE)throw editor::Error("Die Spielstandablage ist gerade belegt. Bitte erneut versuchen.");
#else
handle=::open(path.c_str(),O_CREAT|O_RDWR|O_CLOEXEC,0600);
if(handle<0)throw editor::Error("Die Spielstandablage kann nicht geöffnet werden.");
if(flock(handle,LOCK_EX|LOCK_NB)!=0){::close(handle);handle=-1;throw editor::Error("Die Spielstandablage ist gerade belegt. Bitte erneut versuchen.");}
#endif
}
~Lock(){
#ifdef _WIN32
if(handle!=INVALID_HANDLE_VALUE)CloseHandle(handle);
#else
if(handle>=0){flock(handle,LOCK_UN);::close(handle);}
#endif
}
};
struct Staging {fs::path path;~Staging(){std::error_code e;fs::remove(path,e);}};
}
std::string CareerFiles::clean_name(const std::string &raw) {
const auto name=DemoFiles::clean_name(raw);
if(name.front()=='.'||name.back()=='.'||name.find_first_of("<>:\"/\\|?*")!=std::string::npos)
throw editor::Error("Bitte eine Bezeichnung ohne Dateipfad oder Sonderzeichen eingeben.");
const auto base=DemoFiles::name_key(name.substr(0,name.find('.')));
if(base=="con"||base=="prn"||base=="aux"||base=="nul"||
(base.size()==4&&(base.starts_with("com")||base.starts_with("lpt"))&&base[3]>='1'&&base[3]<='9'))
throw editor::Error("Diese Bezeichnung ist als Dateiname reserviert.");
return name;
}
CareerFiles::CareerFiles(fs::path directory,Reader reader):directory_(fs::absolute(std::move(directory)).lexically_normal()),reader_(std::move(reader)){if(!reader_)throw editor::Error("Die Spielstandprüfung fehlt.");}
fs::path CareerFiles::file(const std::string &id) const {
const auto p=editor::path(id);if(id.empty()||id.front()=='.'||id.find_first_of("/\\")!=std::string::npos||p.filename()!=p||p.extension()!=".obs")throw editor::Error("Ungültiger Spielstandeintrag.");safe_directory(directory_);return directory_/p;
}
DemoFileEntry CareerFiles::decode(const fs::path &path) const {
DemoFileEntry e;e.id=editor::utf8(path.filename());e.name=editor::utf8(path.stem());const auto raw=bytes(path);e.token=content::sha256(raw);e.bytes=raw.size();e.modified=e.created=timestamp(path);e.data=reader_(path);return e;
}
std::vector<DemoFileEntry> CareerFiles::list() const {
safe_directory(directory_);std::vector<DemoFileEntry> result;if(!fs::exists(directory_))return result;
for(const auto &p:fs::directory_iterator(directory_)){const auto name=editor::utf8(p.path().filename());if(name.starts_with('.')||p.path().extension()!=".obs")continue;DemoFileEntry e;try{e=decode(p.path());}catch(const std::exception &error){e.id=name;e.name=editor::utf8(p.path().stem());e.error=error.what();try{const auto raw=bytes(p.path());e.token=content::sha256(raw);e.bytes=raw.size();e.modified=e.created=timestamp(p.path());}catch(...) {}}result.push_back(std::move(e));}
std::sort(result.begin(),result.end(),[](const auto &a,const auto &b){return a.name<b.name;});return result;
}
DemoFileEntry CareerFiles::read(const std::string &id,const std::string &expected) const {
const auto p=file(id);const auto token=content::sha256(bytes(p));if(!expected.empty()&&token!=expected)throw editor::Error("Dieser Spielstand wurde inzwischen geändert. Bitte erneut auswählen.");auto result=decode(p);if(!expected.empty()&&result.token!=expected)throw editor::Error("Dieser Spielstand wurde inzwischen geändert. Bitte erneut auswählen.");return result;
}
void CareerFiles::available_name(const std::string &name,const std::string &except) const {
const auto key=DemoFiles::name_key(name);
for(const auto &e:list())if(e.id!=except){bool same=false;try{same=DemoFiles::name_key(e.name)==key;}catch(...){}if(same)throw editor::Error("Diese Bezeichnung wird bereits verwendet.");}
}
std::string CareerFiles::free_name(const std::string &base) const {
const auto name=clean_name(base);const auto rows=list();
for(int n=1;n<100000;++n){auto prefix=name;const auto suffix=n==1?std::string():" ("+std::to_string(n)+")";std::string candidate;
while(!prefix.empty()){try{candidate=clean_name(prefix+suffix);break;}catch(...){size_t at=prefix.size()-1;while(at>0&&(uint8_t(prefix[at])&0xc0)==0x80)--at;prefix.erase(at);}}
if(candidate.empty())throw editor::Error("Keine freie Bezeichnung gefunden.");bool found=false;for(const auto &e:rows)try{found|=DemoFiles::name_key(e.name)==DemoFiles::name_key(candidate);}catch(...){}if(!found)return candidate;
}
throw editor::Error("Keine freie Bezeichnung gefunden.");
}
DemoFileEntry CareerFiles::put(const std::string &raw_name,const Writer &writer,const std::string &id,const std::string &expected) {
const auto name=clean_name(raw_name);Lock lock(directory_);available_name(name,id);const auto selected=id.empty()?name+".obs":id;const auto target=file(selected);
if(!id.empty()){if(expected.empty()||content::sha256(bytes(target))!=expected)throw editor::Error("Dieser Spielstand wurde inzwischen geändert. Bitte erneut auswählen.");}
Staging staging{directory_/(".pending-"+content::sha256(editor::new_id("save")).substr(0,32)+".obs")};writer(staging.path);(void)reader_(staging.path);const auto raw=bytes(staging.path);
if(!id.empty()&&content::sha256(bytes(target))!=expected)throw editor::Error("Dieser Spielstand wurde inzwischen geändert. Bitte erneut auswählen.");editor::write_atomic(target,raw,!id.empty());return decode(target);
}
DemoFileEntry CareerFiles::rename(const std::string &id,const std::string &expected,const std::string &raw_name) {
const auto name=clean_name(raw_name);Lock lock(directory_);const auto previous=read(id,expected);available_name(name,id);const auto target=file(name+".obs"),source=file(id);if(target==source)return previous;
if(fs::exists(target)&&fs::equivalent(source,target)){fs::rename(source,target);return decode(target);}
const auto raw=bytes(source);if(content::sha256(raw)!=expected)throw editor::Error("Dieser Spielstand wurde inzwischen geändert. Bitte erneut auswählen.");editor::write_atomic(target,raw,false);try{if(content::sha256(bytes(source))!=expected)throw editor::Error("Dieser Spielstand wurde inzwischen geändert.");fs::remove(source);}catch(...){if(fs::exists(target)&&content::sha256(bytes(target))==content::sha256(raw)){std::error_code e;fs::remove(target,e);}throw;}return decode(target);
}
void CareerFiles::remove(const std::string &id,const std::string &expected) {
Lock lock(directory_);const auto source=file(id);const auto raw=bytes(source);if(expected.empty()||content::sha256(raw)!=expected)throw editor::Error("Dieser Spielstand wurde inzwischen geändert. Bitte erneut auswählen.");const auto trash=directory_/(".deleted-"+content::sha256(editor::new_id("delete")));fs::rename(source,trash);std::error_code e;fs::remove(trash,e);
}
DemoFileEntry CareerFiles::import_file(const fs::path &source) {
const auto raw=bytes(source);(void)reader_(source);const auto name=free_name(clean_name(editor::utf8(source.stem())));return put(name,[&](const auto &path){editor::write_atomic(path,raw,false);});
}
void CareerFiles::export_file(const std::string &id,const std::string &expected,const fs::path &destination,bool overwrite) const {
const auto e=read(id,expected);(void)e;const auto target=fs::weakly_canonical(destination);const auto relative=target.lexically_relative(fs::weakly_canonical(directory_));if(!relative.empty()&&*relative.begin()!="..")throw editor::Error("Für den Export bitte ein anderes Verzeichnis wählen.");safe_directory(target.parent_path());const auto raw=bytes(file(id));if(content::sha256(raw)!=expected)throw editor::Error("Dieser Spielstand wurde inzwischen geändert. Bitte erneut auswählen.");editor::write_atomic(target,raw,overwrite);
}
} // namespace bmh::modern_ui
+30
View File
@@ -0,0 +1,30 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "modern/ui/demo_files.hpp"
#include <functional>
namespace bmh::modern_ui {
// Real OBS files only. Entry.data is validated display metadata, never a DemoSource checkpoint.
class CareerFiles {
public:
using Reader=std::function<Json(const fs::path&)>;
using Writer=std::function<void(const fs::path&)>;
CareerFiles(fs::path directory,Reader reader);
static std::string clean_name(const std::string&);
std::vector<DemoFileEntry> list() const;
DemoFileEntry read(const std::string&,const std::string& expected={}) const;
std::string free_name(const std::string&) const;
DemoFileEntry put(const std::string& name,const Writer&,const std::string& id={},const std::string& expected={});
DemoFileEntry rename(const std::string&,const std::string&,const std::string&);
void remove(const std::string&,const std::string&);
DemoFileEntry import_file(const fs::path&);
void export_file(const std::string&,const std::string&,const fs::path&,bool overwrite=false) const;
fs::path file(const std::string&) const;
fs::path directory() const {return directory_;}
private:
fs::path directory_;Reader reader_;
DemoFileEntry decode(const fs::path&) const;
void available_name(const std::string&,const std::string& except={}) const;
};
// Production metadata reader, implemented with the Modern content adapter.
CareerFiles make_career_files(const fs::path &directory,const fs::path &world);
} // namespace bmh::modern_ui
+3 -3
View File
@@ -901,8 +901,8 @@ void App::script() {
const auto type = command.value("type", std::string());
if (type == "engine-wait") {
const auto until = SDL_GetTicks64() + command.value("timeout_ms", uint64_t(300000));
while ((engine_busy_ || engine_creation_busy_) && SDL_GetTicks64() < until) { pump_events(); frame(); SDL_Delay(10); }
if (engine_busy_ || engine_creation_busy_) throw editor::Error("Engine-Vorgang hat das QA-Zeitlimit überschritten.");
while ((engine_busy_ || engine_creation_busy_ || engine_files_busy_) && SDL_GetTicks64() < until) { pump_events(); frame(); SDL_Delay(10); }
if (engine_busy_ || engine_creation_busy_ || engine_files_busy_) throw editor::Error("Engine-Vorgang hat das QA-Zeitlimit überschritten.");
} else if(type=="window-resize-probe"){
// QA-only synthetic event: no OS window or mouse coordinate is changed.
int w,h,pw,ph;SDL_GetWindowSize(video_.window,&w,&h);video_.drawable_size(pw,ph);
@@ -950,7 +950,7 @@ void App::script() {
{"HOME", Rml::Input::KI_HOME}, {"END", Rml::Input::KI_END},
{"LEFT", Rml::Input::KI_LEFT}, {"RIGHT", Rml::Input::KI_RIGHT},
{"UP", Rml::Input::KI_UP}, {"DOWN", Rml::Input::KI_DOWN},
{"A", Rml::Input::KI_A}, {"Z", Rml::Input::KI_Z}, {"V", Rml::Input::KI_V},
{"S", Rml::Input::KI_S}, {"O", Rml::Input::KI_O}, {"A", Rml::Input::KI_A}, {"Z", Rml::Input::KI_Z}, {"V", Rml::Input::KI_V},
{"P", Rml::Input::KI_P},
{"BACKSPACE", Rml::Input::KI_BACK}, {"DELETE", Rml::Input::KI_DELETE}, {"F4", Rml::Input::KI_F4}, {"F10", Rml::Input::KI_F10}, {"CONTEXT", Rml::Input::KI_APPS},
{"0", Rml::Input::KI_0}, {"1", Rml::Input::KI_1}, {"2", Rml::Input::KI_2}, {"3", Rml::Input::KI_3},
+36 -10
View File
@@ -3,13 +3,26 @@
#include "modern/app/modern_session.hpp"
#include "modern/content/world_package.hpp"
#include "modern/content/ui_contract.hpp"
#include "modern/content/world_save.hpp"
#include "modern/content/world_expand.hpp"
#include "modern/ui/model.hpp"
#include "modern/ui/career_files.hpp"
#include "content/digest.hpp"
#include <set>
namespace bmh::modern_ui {
namespace {
Json from_engine(const cli::Json &v) { return Json::parse(cli::dump_json(v)); }
}
namespace {
Json session_snapshot(modern::app::ModernSession &session,uint64_t revision) {
Json bundle=Json::object();
for(const auto *kind:{"session","desktop","camps","squad","lineup","tactics","training","bank","stadium","credit","environment","advertising","contracts","friendly-plan"})bundle[kind]=from_engine(session.ui_read(cli::Json::Object{{"kind",kind}},revision));
validate_engine_desk(bundle);const auto &season=bundle.at("desktop").at("meta").at("season");
bundle["calendar"]=from_engine(session.ui_read(cli::Json::Object{{"kind","calendar"},{"from",season.at("startDate").get<std::string>()},{"until",season.at("endDate").get<std::string>()}},revision));
bundle["scheduling"]=from_engine(session.ui_read(cli::Json::Object{{"kind","scheduling"}},revision));return bundle;
}
}
struct EngineBridge::Impl {
modern::WorldPackage package;
std::unique_ptr<content::Mount> mount;
@@ -63,22 +76,35 @@ std::shared_ptr<EngineBridge> EngineBridge::create(const fs::path &world,const J
if(modern::current_world())throw editor::Error("Bitte die laufende Partie beenden, bevor eine neue begonnen wird.");
return std::shared_ptr<EngineBridge>(new EngineBridge(std::make_unique<Impl>(world,setup,managers,seed)));
}
Json EngineBridge::snapshot() const {
Json bundle = Json::object();
for (const auto *kind : {"session", "desktop", "camps", "squad", "lineup", "tactics", "training", "bank", "stadium", "credit", "environment", "advertising", "contracts", "friendly-plan"})
bundle[kind] = from_engine(impl_->session->ui_read(cli::Json::Object{{"kind", kind}}, impl_->revision));
validate_engine_desk(bundle);
const auto &season = bundle.at("desktop").at("meta").at("season");
bundle["calendar"] = read({{"kind", "calendar"}, {"from", season.at("startDate")}, {"until", season.at("endDate")}});
bundle["scheduling"] = read({{"kind", "scheduling"}});
return bundle;
}
Json EngineBridge::snapshot() const {return session_snapshot(*impl_->session,impl_->revision);}
Json EngineBridge::command(const Json &request) {
return from_engine(impl_->session->ui_command(cli::parse_json(request.dump()), impl_->revision));
}
Json EngineBridge::read(const Json &request) const {
return from_engine(impl_->session->ui_read(cli::parse_json(request.dump()), impl_->revision));
}
CareerFiles make_career_files(const fs::path &directory,const fs::path &world) {
const auto model=modern::open_world_package(world).world;
return CareerFiles(directory,[model](const fs::path &file){
try{return from_engine(modern::read_world_career_metadata(file,*model));}
catch(const std::exception &e){const std::string reason=e.what();if(reason.starts_with("the save belongs to another world"))throw editor::Error("Dieser Spielstand gehört zu einer anderen Mod oder Datensatzversion.");throw editor::Error("Dieser Spielstand ist beschädigt oder wird nicht unterstützt.");}
});
}
Json EngineBridge::file_metadata() const {
const auto reply=read({{"kind","file-metadata"}});
if(reply.value("messageType","")!="snapshot")throw editor::Error("Spielstandangaben nicht verfügbar.");
return reply.at("data");
}
Json EngineBridge::load_same_world(const fs::path &path,const std::string &expected_token) {
const auto check=[&]{if(!expected_token.empty()&&content::sha256(editor::read_file(path,256*1024*1024))!=expected_token)throw editor::Error("Dieser Spielstand wurde inzwischen geändert. Bitte erneut auswählen.");};
check();(void)modern::load_world_career(path,*impl_->package.world);
try {
auto staged=std::make_unique<modern::app::ModernSession>(impl_->mount->root(),1u,path,false);
(void)session_snapshot(*staged,0);check();
impl_->session=std::move(staged);impl_->input=fs::weakly_canonical(path);impl_->revision=0;
}catch(...){modern::install_world_dimensions(*impl_->package.world);throw;}
return {{"messageType","loaded"}};
}
Json EngineBridge::save_copy(const fs::path &path) {
if (fs::weakly_canonical(path) == impl_->input || fs::exists(path))
throw editor::Error("Bitte eine neue Datei wählen. Der geladene Spielstand wird nicht überschrieben.");
+2
View File
@@ -75,6 +75,8 @@ public:
Json read(const Json &request) const;
Json command(const Json &request);
Json save_copy(const fs::path &path);
Json file_metadata() const;
Json load_same_world(const fs::path &path,const std::string &expected_token={});
private:
struct Impl;
explicit EngineBridge(std::unique_ptr<Impl>);
+17 -7
View File
@@ -87,6 +87,7 @@ void App::engine_frame() {
engine_contract_scroll_.reset();
}
if(rendered&&(menu_=="scorers"||menu_=="fairplay")){rankings_restore_scroll();context_->Update();}
if(rendered&&files_native_){files_after_render();context_->Update();}
if (center_selects(*doc_)) context_->Update();
if (menu_ == "lineup" && lineup_roster_scroll_) {
if (auto *roster = element("lineup-roster-scroll")) roster->SetScrollTop(*lineup_roster_scroll_);
@@ -114,7 +115,8 @@ void App::engine_frame() {
renderer_.Clear(); renderer_.BeginFrame(); context_->Render(); renderer_.EndFrame(); video_.present(); dirty_ = false;
}
void App::engine_save() {
if (engine_busy_ || !engine_link_) return;
if (engine_busy_ || engine_files_busy_ || !engine_link_) return;
if(config_.file_export.empty()){engine_files_begin("save");return;}
auto output = config_.file_export;
if (output.empty()) {
NFD::Guard guard; NFD::UniquePath chosen;
@@ -128,7 +130,7 @@ void App::engine_save() {
engine_start("Spielstand wird gespeichert …", [link, output] { auto response = link->save_copy(output); return EngineReply{link, link->snapshot(), response, nullptr}; });
}
void App::engine_quit() {
if (engine_busy_) { engine_notice_ = "Bitte den laufenden Vorgang abwarten."; dirty_ = true; return; }
if (engine_busy_ || engine_files_busy_) { engine_notice_ = "Bitte den laufenden Vorgang abwarten."; dirty_ = true; return; }
if (engine_dirty_) {
confirmation("Die Partie enthält ungespeicherte Änderungen. Vor dem Beenden speichern?",[this]{closed_=true;});
popup_accept_="Ohne Speichern beenden";
@@ -147,13 +149,14 @@ void App::engine_event(Rml::Event &event) {
if (!engine_busy_ && bank_event(event)) return;
if (!engine_busy_ && advertising_event(event)) return;
if (!engine_busy_ && popup_.empty() && contracts_event(event)) return;
if(engine_opening_active()&&popup_.empty()) {
if(engine_opening_active()&&menu_.empty()&&popup_.empty()) {
if(type=="keydown") {const auto key=Rml::Input::KeyIdentifier(event.GetParameter<int>("key_identifier",0));
if(key==Rml::Input::KI_TAB){Rml::ElementList nodes;doc_->QuerySelectorAll(nodes,".opening-actions button");std::erase_if(nodes,[](auto *n){return n->HasAttribute("disabled");});if(!nodes.empty()){const auto it=std::find(nodes.begin(),nodes.end(),context_->GetFocusElement());const int i=it==nodes.end()?-1:int(it-nodes.begin()),n=int(nodes.size());nodes[size_t((i+n+(event.GetParameter<int>("shift_key",0)?-1:1))%n)]->Focus(true);}event.StopImmediatePropagation();return;}
if(key==Rml::Input::KI_RETURN||key==Rml::Input::KI_SPACE){for(auto *n=target;n&&n!=doc_;n=n->GetParentNode())if(n->GetTagName()=="button"&&!n->HasAttribute("disabled")){n->DispatchEvent("click",{});break;}}}
if(type=="click")for(auto *n=target;n&&n!=doc_;n=n->GetParentNode())if(n->HasAttribute("data-action")){opening_action(n->GetAttribute<Rml::String>("data-action",""),n);break;}
event.StopImmediatePropagation();return;
}
if(files_native_&&files_event(event))return;
if (engine_reports_event(event)) return;
if(!engine_busy_&&popup_.empty()&&rankings_event(event))return;
if (!engine_busy_ && popup_.empty() && engine_friendly_event(event)) return;
@@ -183,7 +186,7 @@ void App::engine_event(Rml::Event &event) {
}
if (type == "keydown" && event.GetParameter<int>("key_identifier", 0) == Rml::Input::KI_ESCAPE) {
if (menu_ == "almanac" && engine_busy_) { event.StopImmediatePropagation(); return; }
if (!popup_.empty()) { popup_.clear(); confirm_ = {}; dirty_ = true; }
if (!popup_.empty()) { popup_.clear(); reset_popup(); engine_files_pending_load_.reset(); engine_exit_after_save_=false; dirty_ = true; }
else if (!engine_busy_ && !engine_player_.empty()) { focus_after_render_ = "lineup-detail-" + engine_player_ + "-0"; engine_player_.clear(); refresh(); }
else if (!engine_busy_ && menu_ == "almanac") engine_almanac_action("alm-back",nullptr);
else if (!engine_busy_ && !menu_.empty()) { if (menu_ == "training" || menu_ == "tactics") engine_sports_reset(); if(menu_=="scorers"||menu_=="fairplay")rankings_remember_scroll(); menu_.clear(); refresh(); }
@@ -208,6 +211,10 @@ void App::engine_event(Rml::Event &event) {
}
event.StopImmediatePropagation(); return;
}
if(type=="keydown"&&popup_.empty()&&menu_.empty()&&!engine_busy_&&!engine_files_busy_) {
const auto key=Rml::Input::KeyIdentifier(event.GetParameter<int>("key_identifier",0));
if(event.GetParameter<int>("ctrl_key",0)&&(key==Rml::Input::KI_S||key==Rml::Input::KI_O)){engine_files_begin(key==Rml::Input::KI_S?"save":"load");event.StopImmediatePropagation();return;}
}
if (engine_busy_) return;
if ((type == "input" || type == "change") && menu_ == "camp" && popup_.empty() && target->GetId().starts_with("camp-focus-")) {
const int index = target->GetAttribute<int>("data-id", -1);
@@ -233,11 +240,13 @@ void App::engine_event(Rml::Event &event) {
if (!node->HasAttribute("data-action") || node->HasAttribute("disabled")) continue;
const auto action = node->GetAttribute<Rml::String>("data-action", ""), id = node->GetAttribute<Rml::String>("data-id", "");
if (!popup_.empty()) {
if (action == "popup-close") { popup_.clear(); confirm_ = {}; dirty_ = true; }
if (action == "popup-close") { popup_.clear(); reset_popup(); engine_files_pending_load_.reset(); engine_exit_after_save_=false; dirty_ = true; }
if(action=="files-save-before-load"){const auto pending=engine_files_pending_load_;reset_popup();popup_.clear();engine_files_begin("save");engine_files_pending_load_=pending;return;}
if(action=="engine-save-exit"){reset_popup();popup_.clear();engine_exit_after_save_=true;try{engine_save();}catch(const std::exception &e){engine_exit_after_save_=false;message(e.what());}return;}
if (action == "popup-confirm") { auto callback = std::move(confirm_); popup_.clear(); dirty_ = true; if (callback) callback(); }
if (action == "popup-confirm") { auto callback=std::move(confirm_);auto text_callback=std::move(text_accept_);const auto text=field("popup-text");popup_.clear();reset_popup();dirty_=true;if(text_callback)text_callback(text);else if(callback)callback(); }
return;
}
if(files_native_&&files_action(action,node))return;
if(action.starts_with("rankings-")&&menu_=="scorers"){rankings_action(action,node);return;}
if (engine_reports_action(action,node)) return;
if (almanac_action(action,node)) return;
@@ -256,6 +265,7 @@ void App::engine_event(Rml::Event &event) {
ticket_->open(node, device_ratio_, price.at("min"), price.at("max")); dirty_ = true;
}
else if (action == "engine-open" && (id == "environment" || id == "advertising")) { menu_ = id; advertising_selected_ = -1; advertising_offer_ = 0; refresh(); }
else if(action=="engine-open"&&id=="load"){engine_files_begin("load");}
else if(action=="engine-open"&&id=="scorers"){menu_=id;engine_reports_sync();engine_rankings_load(engine_rankings_state_.at("league"),engine_rankings_state_.at("scope"));}
else if(action=="engine-open"&&id=="fairplay"){menu_=id;engine_reports_sync();engine_fairplay_load();}
else if(action=="engine-open"&&id=="other"){menu_=id;engine_reports_sync();engine_other_load(engine_other_value_.is_object()?engine_other_value_.at("viewId").get<std::string>():"",engine_other_value_.is_object()?engine_other_value_.at("round").get<int>():0);}
@@ -286,5 +296,5 @@ void App::engine_event(Rml::Event &event) {
}
Json App::engine_snapshot() const {
return {{"mode", engine_mode_}, {"creation_busy",engine_creation_busy_}, {"busy", engine_busy_}, {"dirty", engine_dirty_}, {"fresh", engine_fresh_}, {"bundle", engine_data_},
{"response", engine_response_}, {"opening_read",engine_opening_read_},{"opening_state",engine_opening_state_},{"rankings_read",engine_rankings_read_},{"rankings_state",engine_rankings_state_},{"fairplay_read",engine_fairplay_read_},{"other_index",engine_other_index_},{"other_read",engine_other_read_},{"fixtures_read",engine_fixtures_read_},{"reports_state",engine_reports_state_},{"reports_index",engine_reports_index_},{"reports_read",engine_reports_read_},{"reports_roster",engine_reports_roster_},{"almanac_cache",engine_almanac_cache_}, {"almanac_context",engine_almanac_context_}, {"friendly_quote", engine_friendly_read_}, {"friendly_league", engine_friendly_league_}, {"friendly_opponent", engine_friendly_opponent_}, {"friendly_date", engine_friendly_date_}, {"friendly_home", engine_friendly_home_}, {"friendly_stage", engine_friendly_stage_}, {"friendly_month", engine_friendly_month_}, {"calendar_day", engine_calendar_day_}, {"move_id", engine_move_id_}, {"credit_preview", engine_credit_}, {"credit_edits", engine_credit_edits_}, {"training_draft", engine_training_draft_}, {"tactics_draft", engine_tactics_draft_}, {"player_profile", engine_player_}, {"lineup_selected", lineup_selected_}, {"focus", engine_focus_}, {"selected_camp", engine_camp_}, {"notice", engine_notice_}};
{"response", engine_response_}, {"files_native",files_native_},{"files_busy",engine_files_busy_},{"files_current",engine_files_metadata_},{"opening_read",engine_opening_read_},{"opening_state",engine_opening_state_},{"rankings_read",engine_rankings_read_},{"rankings_state",engine_rankings_state_},{"fairplay_read",engine_fairplay_read_},{"other_index",engine_other_index_},{"other_read",engine_other_read_},{"fixtures_read",engine_fixtures_read_},{"reports_state",engine_reports_state_},{"reports_index",engine_reports_index_},{"reports_read",engine_reports_read_},{"reports_roster",engine_reports_roster_},{"almanac_cache",engine_almanac_cache_}, {"almanac_context",engine_almanac_context_}, {"friendly_quote", engine_friendly_read_}, {"friendly_league", engine_friendly_league_}, {"friendly_opponent", engine_friendly_opponent_}, {"friendly_date", engine_friendly_date_}, {"friendly_home", engine_friendly_home_}, {"friendly_stage", engine_friendly_stage_}, {"friendly_month", engine_friendly_month_}, {"calendar_day", engine_calendar_day_}, {"move_id", engine_move_id_}, {"credit_preview", engine_credit_}, {"credit_edits", engine_credit_edits_}, {"training_draft", engine_training_draft_}, {"tactics_draft", engine_tactics_draft_}, {"player_profile", engine_player_}, {"lineup_selected", lineup_selected_}, {"focus", engine_focus_}, {"selected_camp", engine_camp_}, {"notice", engine_notice_}};
}
+80
View File
@@ -0,0 +1,80 @@
// SPDX-License-Identifier: GPL-3.0-only
fs::path App::engine_files_directory() const {
return (config_.userdata.empty()?root_/"userdata":config_.userdata)/"careers"/content::sha256(world_->manifest().at("id").get<std::string>());
}
void App::engine_files_start(std::string label,std::function<EngineFilesReply()> work) {
if(engine_files_busy_||engine_busy_)return;engine_files_busy_=true;files_feedback_=std::move(label);engine_files_job_=std::async(std::launch::async,std::move(work));refresh();
}
void App::engine_files_begin(const std::string &mode) {
if(engine_files_busy_||engine_busy_)return;
if(!world_){const auto *active=mod(active_mod_);if(!active||active->type!="Modern"||!active->error.empty()){message("Bitte zuerst eine spielbare Modern-Mod aktivieren.");return;}load_world(active->file);}
reset_files();files_native_=true;files_mode_=mode;menu_=mode;files_world_=world_;files_name_="Spielstand 1";engine_files_metadata_=Json();
const auto directory=engine_files_directory(),file=world_->source();auto link=engine_link_;
engine_files_start("Spielstände werden geladen …",[directory,file,link,mode]{auto store=make_career_files(directory,file);EngineFilesReply result;result.rows=store.list();result.feedback="";result.operation="list";if(mode=="load"&&!result.rows.empty())result.selected=result.rows.front().id;if(link)result.metadata=link->file_metadata();return result;});
}
void App::engine_files_select(const std::string &id) {
files_selected_=id;files_entry_.reset();for(const auto &row:files_rows_)if(row.id==id){files_entry_=row;break;}files_feedback_.clear();files_reveal_selected_=true;focus_after_render_=id.empty()?"files-name":"files-confirm";refresh();
}
void App::engine_files_poll() {
if(!engine_files_busy_||engine_files_job_.wait_for(std::chrono::milliseconds(0))!=std::future_status::ready)return;
engine_files_busy_=false;
try {
auto result=engine_files_job_.get();
if(result.operation=="loaded") {
engine_reports_context_=Json();engine_almanac_context_=Json();engine_friendly_read_=Json();engine_friendly_stage_=0;engine_calendar_season_.clear();engine_calendar_day_=-1;engine_move_id_.clear();report_detail_kind_.clear();engine_player_.clear();lineup_selected_.clear();engine_opening_state_=Json();engine_opening_read_=Json();
engine_mode_=true;engine_dirty_=engine_base_dirty_=false;engine_accept(std::move(*result.engine));source_.reset();entry_catalog_.reset();engine_files_current_id_=result.selected;engine_files_pending_load_.reset();scene_="engine";menu_.clear();reset_files();refresh();return;
}
files_rows_=std::move(result.rows);if(result.metadata.is_object())engine_files_metadata_=std::move(result.metadata);
if(result.operation=="saved") {
engine_accept(std::move(*result.engine));engine_files_current_id_=result.selected;
const auto pending=engine_files_pending_load_;engine_files_pending_load_.reset();menu_.clear();reset_files();
if(pending&&!closed_)engine_files_load(*pending,true);refresh();return;
}
if(result.operation=="deleted"&&engine_files_current_id_==result.selected){engine_files_current_id_.clear();if(engine_mode_)engine_dirty_=true;result.selected.clear();}
else if(result.operation=="renamed"&&engine_files_current_id_==files_selected_)engine_files_current_id_=result.selected;
if(!result.selected.empty())engine_files_select(result.selected);else {files_selected_.clear();files_entry_.reset();}
files_feedback_=std::move(result.feedback);refresh();
}catch(const std::exception &e){files_feedback_=e.what();engine_exit_after_save_=false;engine_files_pending_load_.reset();refresh();}
}
void App::engine_files_load(DemoFileEntry row,bool confirmed) {
if(engine_files_busy_||engine_busy_)return;
if(engine_mode_&&engine_dirty_&&!confirmed) {
confirmation("Die aktuelle Partie enthält ungespeicherte Änderungen. Vor dem Laden speichern?",[this,row]{engine_files_load(row,true);});popup_accept_="Ohne Speichern laden";popup_extra_=btn("files-save-before-load","Zuerst speichern","primary");engine_files_pending_load_=row;return;
}
const auto directory=engine_files_directory(),file=world_->source();auto link=engine_link_;
engine_files_start("Spielstand wird geprüft und geladen …",[directory,file,link,row]{auto store=make_career_files(directory,file);const auto current=store.read(row.id,row.token);(void)current;auto loaded=link;if(loaded)loaded->load_same_world(store.file(row.id),row.token);else {loaded=EngineBridge::open(file,store.file(row.id));if(store.read(row.id,row.token).token!=row.token)throw editor::Error("Der Spielstand wurde inzwischen geändert.");}auto bundle=loaded->snapshot();EngineFilesReply result;result.operation="loaded";result.selected=row.id;result.engine=EngineReply{loaded,bundle,{{"messageType","loaded"}},link?nullptr:Catalog::open(file)};return result;});
}
bool App::engine_files_action(const std::string &action,Rml::Element *target) {
if(!action.starts_with("files-"))return false;
if(engine_files_busy_||engine_busy_)return true;
const auto id=target?target->GetAttribute<Rml::String>("data-id",""):std::string();
try {
if(action=="files-close"){engine_exit_after_save_=false;engine_files_pending_load_.reset();menu_.clear();reset_files();refresh();return true;}
if(action=="files-new"){engine_files_select("");return true;}
if(action=="files-select"){engine_files_select(id);return true;}
const auto directory=engine_files_directory(),file=world_->source();
if(action=="files-load"){if(files_entry_&&files_entry_->valid())engine_files_load(*files_entry_);return true;}
if(action=="files-save") {
if(!engine_mode_||!engine_fresh_||!engine_files_metadata_.is_object())return true;
const auto name=files_entry_?files_entry_->name:CareerFiles::clean_name(files_name_);auto chosen=files_entry_;
if(!chosen)for(const auto &row:files_rows_)try{if(DemoFiles::name_key(row.name)==DemoFiles::name_key(name)){chosen=row;break;}}catch(...){}
auto link=engine_link_;const auto save=[this,directory,file,name,chosen,link]{engine_files_start("Spielstand wird gespeichert …",[directory,file,name,chosen,link]{auto store=make_career_files(directory,file);const auto row=store.put(name,[link](const auto &path){(void)link->save_copy(path);},chosen?chosen->id:std::string(),chosen?chosen->token:std::string());EngineFilesReply result;result.operation="saved";result.selected=row.id;result.engine=EngineReply{link,link->snapshot(),{{"messageType","saved"}},nullptr};return result;});};
if(chosen)confirmation("Spielstand „"+chosen->name+"“ überschreiben?",save);else save();return true;
}
if(action=="files-rename"&&files_entry_&&files_entry_->valid()) {
const auto row=*files_entry_;text_dialog("Neue Bezeichnung",row.name,[this,directory,file,row](const auto &name){engine_files_start("Spielstand wird umbenannt …",[directory,file,row,name]{auto store=make_career_files(directory,file);const auto renamed=store.rename(row.id,row.token,name);EngineFilesReply r;r.operation="renamed";r.selected=renamed.id;r.rows=store.list();r.feedback="Spielstand umbenannt.";return r;});});return true;
}
if(action=="files-delete"&&files_entry_&&!files_entry_->token.empty()) {
const auto row=*files_entry_;confirmation("Spielstand „"+row.name+"“ wirklich löschen?",[this,directory,file,row]{engine_files_start("Spielstand wird gelöscht …",[directory,file,row]{auto store=make_career_files(directory,file);store.remove(row.id,row.token);EngineFilesReply r;r.operation="deleted";r.selected=row.id;r.rows=store.list();r.feedback="Spielstand gelöscht.";return r;});});return true;
}
if(action=="files-import") {
auto input=config_.file_import;if(input.empty()){NFD::Guard guard;NFD::UniquePath selected;const nfdfilteritem_t filter[]={{"OpenBMH-Spielstand","obs"}};const auto result=NFD::OpenDialog(selected,filter,1);if(result==NFD_CANCEL)return true;if(result!=NFD_OKAY)throw editor::Error("Die Dateiauswahl konnte nicht geöffnet werden.");input=editor::path(selected.get());}
engine_files_start("Spielstand wird importiert …",[directory,file,input]{auto store=make_career_files(directory,file);const auto imported=store.import_file(input);EngineFilesReply r;r.operation="imported";r.selected=imported.id;r.rows=store.list();r.feedback="Spielstand importiert. Die aktive Partie bleibt unverändert.";return r;});return true;
}
if(action=="files-export"&&files_entry_&&files_entry_->valid()) {
const auto row=*files_entry_;auto output=config_.file_export;if(output.empty()){NFD::Guard guard;NFD::UniquePath selected;const nfdfilteritem_t filter[]={{"OpenBMH-Spielstand","obs"}};const auto name=row.name+".obs";const auto result=NFD::SaveDialog(selected,filter,1,nullptr,name.c_str());if(result==NFD_CANCEL)return true;if(result!=NFD_OKAY)throw editor::Error("Die Dateiauswahl konnte nicht geöffnet werden.");output=editor::path(selected.get());}
const auto copy=[this,directory,file,row,output]{engine_files_start("Spielstand wird exportiert …",[directory,file,row,output]{auto store=make_career_files(directory,file);store.export_file(row.id,row.token,output,fs::exists(output));EngineFilesReply r;r.operation="exported";r.selected=row.id;r.rows=store.list();r.feedback="Spielstand exportiert.";return r;});};if(fs::exists(output))confirmation("Vorhandene Exportdatei ersetzen?",copy);else copy();return true;
}
}catch(const std::exception &e){files_feedback_=e.what();refresh();}
return true;
}
+19
View File
@@ -0,0 +1,19 @@
// SPDX-License-Identifier: GPL-3.0-only
struct EngineFilesReply {
std::vector<DemoFileEntry> rows;
std::string selected,feedback,operation;
Json metadata;
std::optional<EngineReply> engine;
};
bool files_native_=false,engine_files_busy_=false;
std::future<EngineFilesReply> engine_files_job_;
Json engine_files_metadata_;
std::string engine_files_current_id_;
std::optional<DemoFileEntry> engine_files_pending_load_;
fs::path engine_files_directory() const;
void engine_files_begin(const std::string &);
void engine_files_start(std::string,std::function<EngineFilesReply()>);
void engine_files_poll();
void engine_files_select(const std::string &);
void engine_files_load(DemoFileEntry,bool confirmed=false);
bool engine_files_action(const std::string &,Rml::Element *);
+4 -2
View File
@@ -36,6 +36,7 @@ Json App::engine_camp_view() const {
return {{"maps", maps}, {"training_camps", camps}};
}
void App::engine_render() {
if(menu_=="save"||menu_=="load"||!files_mode_.empty())files_before_render();
if (ticket_) ticket_->close(false);
if(menu_=="scorers"||menu_=="fairplay")rankings_remember_scroll();
fixture_half_width_=-1.f;
@@ -51,7 +52,7 @@ void App::engine_render() {
if (engine_data_.empty()) {
out = "<div class=\"fill center\"><div class=\"panel\" style=\"padding:70dp;\"><h1>OpenBMH</h1><p>" +
esc(engine_busy_ ? "Spielstand wird geladen …" : engine_notice_) + "</p></div></div>";
} else if(engine_opening_active()) {
} else if(engine_opening_active()&&menu_.empty()) {
out=main_menu()+"<div class=\"fill\" style=\"z-index:100;\">"+render_opening()+"</div>";
} else {
const auto &desk = engine_data_.at("desktop").at("data"), &meta = engine_data_.at("desktop").at("meta");
@@ -118,11 +119,12 @@ void App::engine_render() {
const auto route = id.substr(4);
const bool camp_allowed = desk.at("menuAvailability").at("camps").value("status", "") == "available";
const auto commands = meta.at("scope").value("allowedCommands", Json::array());
const bool supported = ((route=="tables"||route=="strengths"||route=="league"||route=="other"||route=="scorers"||route=="fairplay")&&engine_fresh_&&meta.at("scope").at("role")=="club") || (route == "almanac" && engine_fresh_) || (route == "friendlies" && friendlies_available && engine_fresh_) || (route == "calendar" && calendar_available && engine_fresh_) || (route == "postpone" && scheduling_available && engine_fresh_) || (route == "contracts" && contracts_available && engine_fresh_) || (route == "environment" && environment_available && engine_fresh_) || (route == "advertising" && advertising_available && engine_fresh_) || (route == "bank" && bank_available && engine_fresh_) || (route == "training" && training_available && engine_fresh_) || (route == "tactics" && tactics_available && engine_fresh_) || (route == "lineup" && lineup_available && engine_fresh_) || route == "save" || (route == "camp" && engine_fresh_ && camp_allowed && std::find(commands.begin(), commands.end(), Json("camp.book")) != commands.end());
const bool supported = ((route=="tables"||route=="strengths"||route=="league"||route=="other"||route=="scorers"||route=="fairplay")&&engine_fresh_&&meta.at("scope").at("role")=="club") || (route == "almanac" && engine_fresh_) || (route == "friendlies" && friendlies_available && engine_fresh_) || (route == "calendar" && calendar_available && engine_fresh_) || (route == "postpone" && scheduling_available && engine_fresh_) || (route == "contracts" && contracts_available && engine_fresh_) || (route == "environment" && environment_available && engine_fresh_) || (route == "advertising" && advertising_available && engine_fresh_) || (route == "bank" && bank_available && engine_fresh_) || (route == "training" && training_available && engine_fresh_) || (route == "tactics" && tactics_available && engine_fresh_) || (route == "lineup" && lineup_available && engine_fresh_) || route == "save" || route == "load" || (route == "camp" && engine_fresh_ && camp_allowed && std::find(commands.begin(), commands.end(), Json("camp.book")) != commands.end());
out += desktop_button(id, o, "engine-open", supported && !engine_busy_);
}
}
out += "</div>";
if(menu_=="save"||menu_=="load")out+="<div class=\"fill\" style=\"z-index:100;\">"+window(menu_=="save"?"Spiel speichern":"Spiel laden",render_files(false,menu_=="save"))+"</div>";
if(menu_=="scorers")out+="<div class=\"fill\" style=\"z-index:100;\">"+window("Spielerstatistiken",engine_rankings_value_.is_object()?render_scorers():"<div class=\"fill center\">"+esc(engine_busy_?"Spielerstatistiken werden geladen …":engine_notice_)+"</div>")+"</div>";
if(menu_=="fairplay")out+="<div class=\"fill\" style=\"z-index:100;\">"+window("Fairplay",engine_fairplay_value_.is_object()?render_fairplay():"<div class=\"fill center\">"+esc(engine_busy_?"Fairplay wird geladen …":engine_notice_)+"</div>")+"</div>";
if(menu_=="other")out+="<div class=\"fill\" style=\"z-index:100;\">"+window("Übrige Spiele",engine_other_value_.is_object()?render_reports("other"):"<div class=\"fill center\">"+esc(engine_busy_?"Wettbewerbe werden geladen …":engine_other_index_.is_object()?"Keine aktiven Wettbewerbe.":engine_notice_)+"</div>")+"</div>";
+1 -1
View File
@@ -199,7 +199,7 @@ void App::opening_tick() {
}
void App::handle_event(SDL_Event &event) {
if (event.type == SDL_QUIT) {
if(engine_creation_busy_){message("Die Partie wird noch vorbereitet. Bitte kurz warten.");return;}
if(engine_creation_busy_||engine_files_busy_){message("Die Partie wird noch vorbereitet. Bitte kurz warten.");return;}
if (engine_mode_) { engine_quit(); return; }
if (front_busy_) {
front_feedback_ = "Bitte den laufenden Import abwarten.";
+8 -1
View File
@@ -11,6 +11,7 @@ bool App::files_bound() const {
files_desktop_base_ == desktop_ && files_theme_base_ == theme_;
}
void App::reset_files() {
files_native_=false;engine_files_metadata_=Json();
files_mode_.clear();
files_selected_.clear();
files_name_.clear();
@@ -27,6 +28,7 @@ void App::reset_files() {
files_reveal_selected_ = false;
}
void App::files_begin(const std::string &mode) {
if(!config_.preview_only&&(mode=="save"||mode=="load")){engine_files_begin(mode);return;}
reset_files();
files_mode_ = mode;
files_world_ = world_;
@@ -48,6 +50,7 @@ void App::files_begin(const std::string &mode) {
}
}
void App::files_reload(const std::string &selected) {
if(files_native_){engine_files_select(selected.empty()?files_selected_:selected);return;}
files_rows_ = files_store().list();
if (!selected.empty())
files_selected_ = selected;
@@ -71,6 +74,7 @@ void App::files_reload(const std::string &selected) {
}
}
void App::files_select(const std::string &selected) {
if(files_native_){engine_files_select(selected);return;}
files_selected_ = selected;
files_feedback_.clear();
files_reload();
@@ -103,6 +107,7 @@ void App::files_before_render() {
}
}
void App::files_after_render() {
if(files_native_&&engine_files_busy_){Rml::ElementList nodes;doc_->QuerySelectorAll(nodes,".window button,.window input");for(auto *n:nodes)n->SetAttribute("disabled",true);}
if (files_capturing_ || files_mode_ != menu_)
return;
context_->Update();
@@ -266,6 +271,7 @@ void App::files_load() {
refresh();
}
bool App::files_action(const std::string &action, Rml::Element *target) {
if(files_native_){if(action=="close")return engine_files_action("files-close",target);return engine_files_action(action,target);}
if (!action.starts_with("files-"))
return false;
const auto id =
@@ -431,7 +437,7 @@ bool App::files_change(Rml::Element *target) {
if (auto *button = element("files-confirm")) {
bool valid = true;
try {
DemoFiles::clean_name(files_name_);
if(files_native_)CareerFiles::clean_name(files_name_);else DemoFiles::clean_name(files_name_);
} catch (...) {
valid = false;
}
@@ -446,6 +452,7 @@ bool App::files_change(Rml::Element *target) {
return true;
}
bool App::files_event(Rml::Event &event) {
if(files_native_&&engine_files_busy_){event.StopImmediatePropagation();return true;}
if (files_mode_.empty() || !popup_.empty())
return false;
if (event.GetType() == "input" || event.GetType() == "change")
+8 -7
View File
@@ -5,6 +5,7 @@ std::string App::files_standard_preview() {
}
std::string App::files_details(bool layouts, bool save) {
if(files_native_&&engine_files_busy_&&save&&!engine_files_metadata_.is_object())return "<div class=\"files-empty-details\"><h2>Spielstände werden geladen …</h2></div>";
const bool standard = layouts && files_selected_ == "standard";
const bool fresh = save && files_selected_.empty();
if (files_entry_ && !files_entry_->valid())
@@ -35,8 +36,8 @@ std::string App::files_details(bool layouts, bool save) {
for (const auto &[label, value] : meta) out += "<div class=\"files-metadata-cell\"><span>" + esc(label) + "</span><strong>" + esc(value) + "</strong></div>";
return out + "</div>";
}
const auto data = fresh ? snap().state : files_entry_->data;
const auto meta = DemoFiles::career_metadata(data);
const auto data = fresh ? (files_native_?engine_files_metadata_:snap().state) : files_entry_->data;
const auto meta = files_native_?data:DemoFiles::career_metadata(data);
const auto &managers = meta.at("managers");
const Json *own = managers.empty() ? nullptr : world_->find("clubs", meta.at("current_manager").value("club", ""));
out = "<div class=\"files-detail-heading\"><div class=\"files-crest\">" + (meta.at("role")=="national"?img("career.national-de",108,108,false,false,256):crest(own,108)) + "</div><div><p>" + std::string(fresh ? "Aktuelles Spiel" : "Gespeicherter Spielstand") + "</p><h2>" + esc(fresh ? "Neuer Speicherstand" : files_entry_->name) + "</h2><span>" + esc(meta.at("role")=="national"?"Deutschland":own ? world_->name(*own) : "") + "</span></div></div>";
@@ -49,9 +50,9 @@ std::string App::files_details(bool layouts, bool save) {
out += "</div><section class=\"files-managers\"><h3>Mitspieler</h3>";
for (const auto &manager : managers) {
const auto *managed = world_->find("clubs", manager.value("club", ""));
out += "<div><strong>" + esc(manager.value("name", "")) + "</strong><span>" + esc(meta.at("role")=="national"&&manager.value("portrait",0)==meta.at("current_manager").value("portrait",0)?"Deutschland":managed ? world_->name(*managed) : "") + "</span></div>";
out += "<div><strong>" + esc(manager.value("name", "")) + "</strong><span>" + esc(files_native_?manager.value("team_name",std::string()):meta.at("role")=="national"&&manager.value("portrait",0)==meta.at("current_manager").value("portrait",0)?"Deutschland":managed ? world_->name(*managed) : "") + "</span></div>";
}
return out + "</section><p class=\"files-timestamp\">" + (fresh ? "Diese Angaben werden mit dem Spielstand gespeichert." : "Gespeichert am " + esc(files_entry_->created) + "<br/>Geändert am " + esc(files_entry_->modified) + " · " + std::to_string(files_entry_->bytes) + " Bytes") + "</p>";
return out + "</section><p class=\"files-timestamp\">" + (fresh ? "Diese Angaben werden mit dem Spielstand gespeichert." : (files_native_?"Datei geändert am ":"Gespeichert am ") + esc(files_entry_->created) + (files_native_?std::string():"<br/>Geändert am "+esc(files_entry_->modified)) + " · " + std::to_string(files_entry_->bytes) + " Bytes") + "</p>";
}
std::string App::render_files(bool layouts, bool save) {
if (files_mode_ != menu_) files_begin(menu_);
@@ -66,13 +67,13 @@ std::string App::render_files(bool layouts, bool save) {
const auto &entry = files_rows_[i];
entries += row("files-select", entry.id, entry.name, entry.valid() ? "Gespeichert am " + entry.created : "Datei kann nicht geöffnet werden", files_selected_ == entry.id, "files-entry-" + std::to_string(i));
}
if (entries.empty()) entries = "<p class=\"files-empty-list\">Noch keine Spielstände vorhanden.</p>";
if (entries.empty()) entries = "<p class=\"files-empty-list\">"+std::string(files_native_&&engine_files_busy_?"Spielstände werden geladen …":"Noch keine Spielstände vorhanden.")+"</p>";
std::string details;
try { details = files_details(layouts, save); }
catch (const std::exception &e) { details = "<div class=\"files-empty-details\"><h2>Datei nicht verfügbar</h2><p>" + esc(e.what()) + "</p></div>"; }
const bool selected = files_entry_ && files_entry_->valid();
bool can_save = save && (!files_entry_ || selected);
if (save && !selected) try { DemoFiles::clean_name(files_name_); } catch (...) { can_save = false; }
bool can_save = save && (!files_entry_ || selected) && (!files_native_||engine_files_metadata_.is_object());
if (save && !selected) try { if(files_native_)CareerFiles::clean_name(files_name_);else DemoFiles::clean_name(files_name_); } catch (...) { can_save = false; }
const auto disabled = selected ? "" : "disabled";
std::string footer = "<div class=\"files-file-actions\">";
if (!layouts) footer += btn("files-import", "Importieren") + btn("files-export", "Exportieren", {}, disabled);
+1 -1
View File
@@ -54,7 +54,7 @@ std::string App::main_menu() {
"class=\"front-active-dot\"></span><div><small>Aktive Mod</small><strong "
"id=\"front-active-name\">" +
esc(label) + "</strong></div></div><small class=\"front-version\">v" +
std::string(kOpenBmhVersion) + " · UI-Demo</small></footer></div>";
std::string(kOpenBmhVersion) + (config_.preview_only ? " · UI-Demo" : " · Entwicklung") + "</small></footer></div>";
return out;
}
std::string App::front_mod_details() {
+5
View File
@@ -7,6 +7,7 @@
#include "modern/ui/controls.hpp"
#include "modern/ui/crest_contrast.hpp"
#include "modern/ui/engine_bridge.hpp"
#include "modern/ui/career_files.hpp"
#include "modern/ui/live_match_info.hpp"
#include "modern/ui/script_locator.hpp"
#include "modern/ui/select_menu.hpp"
@@ -480,6 +481,7 @@ class App final : public Rml::EventListener {
#include "modern/ui/settings_state.inc"
#include "modern/ui/widgets_state.inc"
#include "modern/ui/files_state.inc"
#include "modern/ui/engine_files_state.inc"
#include "modern/ui/front_state.inc"
#include "modern/ui/live_state.inc"
#include "modern/ui/postmatch_state.inc"
@@ -1110,6 +1112,7 @@ class App final : public Rml::EventListener {
}
void frame() {
engine_create_poll();
engine_files_poll();
if (engine_mode_) { engine_frame(); return; }
front_poll();
flush_selects();
@@ -1444,6 +1447,7 @@ public:
while (!closed_) {
front_poll();
engine_create_poll();
engine_files_poll();
if (engine_mode_) engine_poll();
opening_tick();
live_tick();
@@ -1536,6 +1540,7 @@ public:
#include "modern/ui/engine_reports.inc"
#include "modern/ui/engine_rankings.inc"
#include "modern/ui/engine_creation.inc"
#include "modern/ui/engine_files.inc"
} // namespace
bool is_modern_world(const fs::path &file) {
try {