Build 0.2 native launcher and portable Classic runtime (by Codex)

This commit is contained in:
Codex committed 2026-10-18 11:28:51 +02:00
1 parent 3a021fc160
commit 2552528176
84 files changed
+5004 -197

No files matched your search

+90
View File
@@ -0,0 +1,90 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "launch/launcher.hpp"
#include "launch/launcher_ui.hpp"
#include "launch/process.hpp"
#include "launch/game_data.hpp"
#include "launch/archive.hpp"
#include <atomic>
#include <future>
#include <mutex>
namespace bmh::launch {
int run_launcher(const std::filesystem::path &executable, const SaveMigrator &migrate) {
auto ui = make_launcher_ui();
ModLibrary library(executable.parent_path());
for (;;)
try {
const auto mods = library.list();
const auto action = ui->next(mods);
if (action.action == LauncherAction::end)
return 0;
if (action.action == LauncherAction::add) {
const auto source = ui->choose_folder("BMH-/Football-Limited-Installation wählen");
if (!source)
continue;
const auto check = check_game_directory(*source);
if (!check.playable)
throw FormatError("Installation wird nicht unterstützt: " + check.unsupported);
AddMod initial;
initial.source = check.directory;
initial.saves = check.directory;
initial.name = check.family == GameFamily::english ? "FTDL-classic" : "BMH-classic";
const auto request = ui->configure_add(initial);
if (!request)
continue;
std::mutex mutex;
std::string text = "Import wird vorbereitet …";
std::atomic_bool cancelled = false;
ui->progress(text, true);
auto job = std::async(std::launch::async, [&] {
return library.add(*request, migrate, [&](const std::string &s) {
if (cancelled.load())
throw FormatError("Import abgebrochen");
std::lock_guard lock(mutex);
text = s;
});
});
while (job.wait_for(std::chrono::milliseconds(20)) != std::future_status::ready) {
if (ui->pump())
cancelled = true;
std::lock_guard lock(mutex);
ui->progress(text, true);
}
ui->finish_progress();
const auto report = job.get();
std::string summary =
"Mod importiert: " + report.mod.name +
"\nÜbernommene Spielstände/Einstellungen: " + std::to_string(report.migrated);
for (const auto &error : report.errors)
summary += "\n" + error;
ui->message(summary, false);
continue;
}
if (action.selection < 0 || size_t(action.selection) >= mods.size())
continue;
const auto &mod = mods[size_t(action.selection)];
if (action.action == LauncherAction::remove) {
if (ui->confirm_delete(mod.name))
library.remove(mod);
} else if (action.action == LauncherAction::rename) {
if (const auto name = ui->rename(mod.name))
library.rename(mod, *name);
} else if (action.action == LauncherAction::start) {
if (!mod.error.empty())
throw FormatError(mod.error);
(void)content::open(mod.directory / "content.obw");
const auto userdata = library.user_directory(mod);
ui->progress("Spiel läuft: " + mod.name, false);
const int code = run_child(executable,
{"--run-mod", path_to_utf8(mod.directory / "content.obw"),
"--save-directory", path_to_utf8(userdata)},
[&] { ui->pump(); });
ui->finish_progress();
if (code)
ui->message("Das Spiel wurde mit Fehlercode " + std::to_string(code) + " beendet.", true);
}
} catch (const std::exception &e) {
ui->finish_progress();
ui->message(e.what(), true);
}
}
} // namespace bmh::launch
+6
View File
@@ -0,0 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "launch/mods.hpp"
namespace bmh::launch {
int run_launcher(const std::filesystem::path &executable, const SaveMigrator &);
} // namespace bmh::launch
+300
View File
@@ -0,0 +1,300 @@
// SPDX-License-Identifier: GPL-3.0-only
#import <AppKit/AppKit.h>
#include "launch/launcher_ui.hpp"
#include "launch/archive.hpp"
#include <functional>
@interface OBMLauncherBridge : NSObject <NSTableViewDataSource, NSTableViewDelegate, NSWindowDelegate> {
@public
std::function<void(NSInteger)> action;
std::function<void()> selection;
}
@property(strong) NSArray<NSDictionary *> *rows;
- (void)activate:(id)sender;
@end
@implementation OBMLauncherBridge
- (NSInteger)numberOfRowsInTableView:(NSTableView *)table {
(void)table;
return self.rows.count;
}
- (id)tableView:(NSTableView *)table objectValueForTableColumn:(NSTableColumn *)column row:(NSInteger)row {
(void)table;
return self.rows[row][column.identifier];
}
- (void)tableViewSelectionDidChange:(NSNotification *)note {
(void)note;
if (selection)
selection();
}
- (void)activate:(id)sender {
if (action)
action([sender tag]);
}
- (BOOL)windowShouldClose:(NSWindow *)window {
(void)window;
if (action)
action(0);
return NO;
}
@end
namespace bmh::launch {
namespace {
NSString *string(const std::string &s) {
auto value = [[NSString alloc] initWithBytes:s.data() length:s.size() encoding:NSUTF8StringEncoding];
if (!value)
throw std::runtime_error("Invalid UTF-8 launcher text");
return value;
}
std::string utf8(NSString *s) { return std::string(s.UTF8String ?: ""); }
NSTextField *label(NSString *text, NSRect frame) {
auto *field = [NSTextField labelWithString:text];
field.frame = frame;
return field;
}
NSTextField *input(NSString *text, NSRect frame) {
auto *field = [[NSTextField alloc] initWithFrame:frame];
field.stringValue = text;
return field;
}
class CocoaLauncher final : public LauncherUI {
NSWindow *window_;
NSTableView *table_;
OBMLauncherBridge *bridge_;
NSMutableArray<NSButton *> *buttons_;
NSWindow *progress_ = nil;
NSTextField *progress_label_ = nil;
OBMLauncherBridge *progress_bridge_ = nil;
bool cancelled_ = false;
public:
CocoaLauncher() {
[NSApplication sharedApplication];
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
[NSApp finishLaunching];
window_ = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 660, 340)
styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
NSWindowStyleMaskMiniaturizable
backing:NSBackingStoreBuffered
defer:NO];
window_.title = @"OpenBMH";
[window_ center];
window_.releasedWhenClosed = NO;
bridge_ = [OBMLauncherBridge new];
bridge_.rows = @[];
window_.delegate = bridge_;
auto *scroll = [[NSScrollView alloc] initWithFrame:NSMakeRect(16, 16, 490, 308)];
scroll.hasVerticalScroller = YES;
scroll.borderType = NSBezelBorder;
table_ = [[NSTableView alloc] initWithFrame:scroll.bounds];
table_.allowsMultipleSelection = NO;
table_.dataSource = bridge_;
table_.delegate = bridge_;
for (NSString *identifier in @[ @"Name", @"Art" ]) {
auto *column = [[NSTableColumn alloc] initWithIdentifier:identifier];
column.title = identifier;
column.width = [identifier isEqualToString:@"Name"] ? 350 : 110;
[table_ addTableColumn:column];
}
table_.target = bridge_;
table_.doubleAction = @selector(activate:);
table_.tag = 1;
scroll.documentView = table_;
[window_.contentView addSubview:scroll];
buttons_ = [NSMutableArray new];
NSArray *titles = @[ @"Start", @"Add", @"Delete", @"Rename", @"End" ];
for (NSInteger i = 0; i < 5; ++i) {
auto *button = [NSButton buttonWithTitle:titles[i] target:bridge_ action:@selector(activate:)];
button.tag = i + 1;
button.frame = NSMakeRect(522, 282 - i * 50, 120, 34);
[window_.contentView addSubview:button];
[buttons_ addObject:button];
}
bridge_->action = [this](NSInteger code) {
if ((code == 1 || code == 3 || code == 4) && table_.selectedRow < 0)
return;
[NSApp stopModalWithCode:code];
};
bridge_->selection = [this] {
for (NSInteger i : {0, 2, 3})
buttons_[i].enabled = table_.selectedRow >= 0;
};
bridge_->selection();
[window_ makeKeyAndOrderFront:nil];
[NSApp activateIgnoringOtherApps:YES];
}
~CocoaLauncher() override {
bridge_->action = {};
bridge_->selection = {};
finish_progress();
window_.delegate = nil;
[window_ orderOut:nil];
[window_ close];
}
LauncherChoice next(const std::vector<ModEntry> &mods) override {
const NSInteger old = table_.selectedRow;
auto *rows = [NSMutableArray new];
for (const auto &mod : mods)
[rows addObject:@{
@"Name" : string(mod.name + (mod.error.empty() ? "" : " ⚠")),
@"Art" : string(mod.type)
}];
bridge_.rows = rows;
[table_ reloadData];
if (old >= 0 && size_t(old) < mods.size())
[table_ selectRowIndexes:[NSIndexSet indexSetWithIndex:old] byExtendingSelection:NO];
bridge_->selection();
[window_ makeKeyAndOrderFront:nil];
const NSInteger response = [NSApp runModalForWindow:window_];
return {response == 1 ? LauncherAction::start
: response == 2 ? LauncherAction::add
: response == 3 ? LauncherAction::remove
: response == 4 ? LauncherAction::rename
: LauncherAction::end,
int(table_.selectedRow)};
}
std::optional<std::filesystem::path> choose_folder(const std::string &title,
const std::filesystem::path &initial) override {
auto *panel = [NSOpenPanel openPanel];
panel.title = string(title);
panel.canChooseFiles = NO;
panel.canChooseDirectories = YES;
panel.allowsMultipleSelection = NO;
if (!initial.empty())
panel.directoryURL = [NSURL fileURLWithPath:string(path_to_utf8(initial)) isDirectory:YES];
if ([panel runModal] != NSModalResponseOK)
return {};
return path_from_utf8(utf8(panel.URL.path));
}
std::optional<AddMod> configure_add(AddMod initial) override {
auto *alert = [NSAlert new];
alert.messageText = @"Classic-Mod hinzufügen";
[alert addButtonWithTitle:@"Importieren"];
[alert addButtonWithTitle:@"Abbrechen"];
auto *view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 540, 180)];
[view addSubview:label(@"Bezeichnung", NSMakeRect(0, 146, 160, 24))];
auto *name = input(string(initial.name), NSMakeRect(170, 146, 370, 24));
[view addSubview:name];
[view addSubview:label(@"Startjahr (nur Anzeige)", NSMakeRect(0, 106, 165, 24))];
auto *year = input(string(std::to_string(initial.start_year)), NSMakeRect(170, 106, 110, 24));
[view addSubview:year];
auto *migrate = [NSButton checkboxWithTitle:@"Spielstände/Einstellungen übernehmen"
target:nil
action:nil];
migrate.frame = NSMakeRect(0, 68, 540, 24);
migrate.state = initial.migrate ? NSControlStateValueOn : NSControlStateValueOff;
[view addSubview:migrate];
[view addSubview:label(@"Spielstandsordner", NSMakeRect(0, 25, 160, 24))];
auto *saves = input(string(path_to_utf8(initial.saves)), NSMakeRect(170, 25, 245, 24));
[view addSubview:saves];
auto *browse_bridge = [OBMLauncherBridge new];
browse_bridge->action = [this, saves](NSInteger) {
if (auto p = choose_folder("Spielstandsordner wählen", path_from_utf8(utf8(saves.stringValue))))
saves.stringValue = string(path_to_utf8(*p));
};
auto *browse = [NSButton buttonWithTitle:@"Auswählen …"
target:browse_bridge
action:@selector(activate:)];
browse.frame = NSMakeRect(420, 22, 120, 30);
[view addSubview:browse];
alert.accessoryView = view;
while ([alert runModal] == NSAlertFirstButtonReturn)
try {
initial.name = utf8(name.stringValue);
ModLibrary::validate_name(initial.name);
const auto value = utf8(year.stringValue);
size_t end = 0;
initial.start_year = std::stoi(value, &end);
if (end != value.size() || initial.start_year < 1900 || initial.start_year > 9998)
throw std::runtime_error("Startjahr muss zwischen 1900 und 9998 liegen");
initial.saves = path_from_utf8(utf8(saves.stringValue));
initial.migrate = migrate.state == NSControlStateValueOn;
return initial;
} catch (const std::exception &e) {
message(e.what(), true);
}
return {};
}
std::optional<std::string> rename(const std::string &old) override {
auto *alert = [NSAlert new];
alert.messageText = @"Mod umbenennen";
[alert addButtonWithTitle:@"Umbenennen"];
[alert addButtonWithTitle:@"Abbrechen"];
auto *field = input(string(old), NSMakeRect(0, 0, 380, 26));
alert.accessoryView = field;
if ([alert runModal] != NSAlertFirstButtonReturn)
return {};
return utf8(field.stringValue);
}
bool confirm_delete(const std::string &name) override {
auto *alert = [NSAlert new];
alert.messageText = string("Mod „" + name + "“ löschen?");
alert.informativeText = @"Spielstände und persönliche Einstellungen bleiben erhalten.";
[alert addButtonWithTitle:@"Abbrechen"];
[alert addButtonWithTitle:@"Löschen"];
return [alert runModal] == NSAlertSecondButtonReturn;
}
void message(const std::string &value, bool error) override {
auto *alert = [NSAlert new];
alert.messageText = @"OpenBMH";
alert.informativeText = string(value);
alert.alertStyle = error ? NSAlertStyleWarning : NSAlertStyleInformational;
[alert runModal];
}
void progress(const std::string &value, bool cancellable) override {
if (!progress_) {
cancelled_ = false;
for (NSButton *b in buttons_)
b.enabled = NO;
progress_ = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 580, 125)
styleMask:NSWindowStyleMaskTitled
backing:NSBackingStoreBuffered
defer:NO];
progress_.title = @"OpenBMH";
progress_.releasedWhenClosed = NO;
progress_label_ = label(string(value), NSMakeRect(16, 65, 548, 40));
[progress_.contentView addSubview:progress_label_];
progress_bridge_ = [OBMLauncherBridge new];
progress_bridge_->action = [this](NSInteger) { cancelled_ = true; };
progress_.delegate = progress_bridge_;
if (cancellable) {
auto *button = [NSButton buttonWithTitle:@"Abbrechen"
target:progress_bridge_
action:@selector(activate:)];
button.frame = NSMakeRect(440, 15, 120, 30);
[progress_.contentView addSubview:button];
}
[window_ beginSheet:progress_ completionHandler:nil];
}
progress_label_.stringValue = string(value);
}
bool pump() override {
@autoreleasepool {
NSEvent *event;
while ((event = [NSApp nextEventMatchingMask:NSEventMaskAny
untilDate:[NSDate distantPast]
inMode:NSDefaultRunLoopMode
dequeue:YES]))
[NSApp sendEvent:event];
[NSApp updateWindows];
}
return cancelled_;
}
void finish_progress() override {
if (progress_) {
progress_bridge_->action = {};
[window_ endSheet:progress_];
[progress_ orderOut:nil];
[progress_ close];
progress_ = nil;
progress_label_ = nil;
progress_bridge_ = nil;
for (NSButton *b in buttons_)
b.enabled = YES;
bridge_->selection();
}
}
};
} // namespace
std::unique_ptr<LauncherUI> make_launcher_ui() { return std::make_unique<CocoaLauncher>(); }
} // namespace bmh::launch
+269
View File
@@ -0,0 +1,269 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "launch/launcher_ui.hpp"
#include "launch/archive.hpp"
#include <gtk/gtk.h>
#include <array>
namespace bmh::launch {
namespace {
class GtkLauncher final : public LauncherUI {
GtkWidget *window_ = nullptr, *tree_ = nullptr, *progress_ = nullptr, *progress_label_ = nullptr;
GtkListStore *model_ = nullptr;
std::array<GtkWidget *, 5> buttons_{};
bool cancelled_ = false;
std::string selection_;
enum { Start = 1, Add, Delete, Rename, End };
static void selection_changed(GtkTreeSelection *selection, gpointer data) {
auto &self = *static_cast<GtkLauncher *>(data);
GtkTreeIter it;
GtkTreeModel *model;
const bool selected = gtk_tree_selection_get_selected(selection, &model, &it);
for (int id : {Start, Delete, Rename})
gtk_widget_set_sensitive(self.buttons_[size_t(id - 1)], selected);
}
GtkWidget *entry(GtkWidget *grid, int row, const char *label, const std::string &initial) {
auto *title = gtk_label_new(label);
gtk_widget_set_halign(title, GTK_ALIGN_START);
gtk_grid_attach(GTK_GRID(grid), title, 0, row, 1, 1);
auto *input = gtk_entry_new();
gtk_entry_set_text(GTK_ENTRY(input), initial.c_str());
gtk_widget_set_hexpand(input, TRUE);
gtk_grid_attach(GTK_GRID(grid), input, 1, row, 1, 1);
return input;
}
public:
GtkLauncher() {
if (!gtk_init_check(nullptr, nullptr))
throw std::runtime_error("Kein Desktop für den nativen Launcher verfügbar");
window_ = gtk_dialog_new();
gtk_window_set_title(GTK_WINDOW(window_), "OpenBMH");
gtk_window_set_default_size(GTK_WINDOW(window_), 620, 340);
auto *body = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 16);
gtk_container_set_border_width(GTK_CONTAINER(body), 16);
gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(window_))), body, TRUE, TRUE, 0);
model_ = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING);
tree_ = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model_));
auto *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree_));
gtk_tree_selection_set_mode(selection, GTK_SELECTION_SINGLE);
g_signal_connect(selection, "changed", G_CALLBACK(selection_changed), this);
for (int i = 0; i < 2; ++i) {
auto *renderer = gtk_cell_renderer_text_new();
auto *column =
gtk_tree_view_column_new_with_attributes(i ? "Art" : "Name", renderer, "text", i, nullptr);
gtk_tree_view_column_set_expand(column, i == 0);
gtk_tree_view_append_column(GTK_TREE_VIEW(tree_), column);
}
gtk_tree_view_set_tooltip_column(GTK_TREE_VIEW(tree_), 2);
auto *scroller = gtk_scrolled_window_new(nullptr, nullptr);
gtk_widget_set_hexpand(scroller, TRUE);
gtk_widget_set_vexpand(scroller, TRUE);
gtk_container_add(GTK_CONTAINER(scroller), tree_);
gtk_box_pack_start(GTK_BOX(body), scroller, TRUE, TRUE, 0);
auto *buttons = gtk_box_new(GTK_ORIENTATION_VERTICAL, 8);
gtk_box_pack_start(GTK_BOX(body), buttons, FALSE, FALSE, 0);
const char *labels[] = {"Start", "Add", "Delete", "Rename", "End"};
for (int i = 0; i < 5; ++i) {
auto *button = gtk_button_new_with_label(labels[i]);
buttons_[size_t(i)] = button;
gtk_box_pack_start(GTK_BOX(buttons), button, FALSE, FALSE, 0);
g_object_set_data(G_OBJECT(button), "response-id", GINT_TO_POINTER(i + 1));
g_signal_connect(button, "clicked", G_CALLBACK(+[](GtkButton *button, gpointer self) {
auto *window = static_cast<GtkLauncher *>(self)->window_;
gtk_dialog_response(
GTK_DIALOG(window),
GPOINTER_TO_INT(g_object_get_data(G_OBJECT(button), "response-id")));
}),
this);
}
g_signal_connect(tree_, "row-activated",
G_CALLBACK(+[](GtkTreeView *, GtkTreePath *, GtkTreeViewColumn *, gpointer data) {
gtk_dialog_response(GTK_DIALOG(static_cast<GtkLauncher *>(data)->window_),
Start);
}),
this);
gtk_widget_show_all(window_);
}
~GtkLauncher() override {
finish_progress();
gtk_widget_destroy(window_);
g_object_unref(model_);
}
LauncherChoice next(const std::vector<ModEntry> &mods) override {
gtk_list_store_clear(model_);
int selected = -1;
for (size_t i = 0; i < mods.size(); ++i) {
GtkTreeIter it;
gtk_list_store_append(model_, &it);
const auto &mod = mods[i];
const auto shown = mod.error.empty() ? mod.name : mod.name + " ⚠";
gtk_list_store_set(model_, &it, 0, shown.c_str(), 1, mod.type.c_str(), 2, mod.error.c_str(), -1);
if (mod.name == selection_) {
auto *path = gtk_tree_path_new_from_indices(int(i), -1);
gtk_tree_view_set_cursor(GTK_TREE_VIEW(tree_), path, nullptr, FALSE);
gtk_tree_path_free(path);
}
}
selection_changed(gtk_tree_view_get_selection(GTK_TREE_VIEW(tree_)), this);
const int response = gtk_dialog_run(GTK_DIALOG(window_));
GtkTreeIter it;
GtkTreeModel *model;
if (gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(tree_)), &model, &it)) {
auto *path = gtk_tree_model_get_path(model, &it);
selected = gtk_tree_path_get_indices(path)[0];
gtk_tree_path_free(path);
if (selected >= 0 && size_t(selected) < mods.size())
selection_ = mods[size_t(selected)].name;
}
return {response == Start ? LauncherAction::start
: response == Add ? LauncherAction::add
: response == Delete ? LauncherAction::remove
: response == Rename ? LauncherAction::rename
: LauncherAction::end,
selected};
}
std::optional<std::filesystem::path> choose_folder(const std::string &title,
const std::filesystem::path &initial) override {
auto *dialog = gtk_file_chooser_dialog_new(
title.c_str(), GTK_WINDOW(window_), GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, "Abbrechen",
GTK_RESPONSE_CANCEL, "Auswählen", GTK_RESPONSE_ACCEPT, nullptr);
if (!initial.empty())
gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog), path_to_utf8(initial).c_str());
std::optional<std::filesystem::path> result;
if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
char *file = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
if (file) {
result = path_from_utf8(file);
g_free(file);
}
}
gtk_widget_destroy(dialog);
return result;
}
std::optional<AddMod> configure_add(AddMod initial) override {
auto *dialog = gtk_dialog_new_with_buttons("Classic-Mod hinzufügen", GTK_WINDOW(window_),
GTK_DIALOG_MODAL, "Abbrechen", GTK_RESPONSE_CANCEL,
"Importieren", GTK_RESPONSE_ACCEPT, nullptr);
gtk_window_set_default_size(GTK_WINDOW(dialog), 540, -1);
auto *grid = gtk_grid_new();
gtk_grid_set_row_spacing(GTK_GRID(grid), 12);
gtk_grid_set_column_spacing(GTK_GRID(grid), 12);
gtk_container_set_border_width(GTK_CONTAINER(grid), 16);
gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), grid, TRUE, TRUE, 0);
auto *name = entry(grid, 0, "Bezeichnung", initial.name);
auto *year = entry(grid, 1, "Startjahr (nur Anzeige)", std::to_string(initial.start_year));
auto *migrate = gtk_check_button_new_with_label("Spielstände/Einstellungen übernehmen");
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(migrate), initial.migrate);
gtk_grid_attach(GTK_GRID(grid), migrate, 0, 2, 3, 1);
auto *saves = entry(grid, 3, "Spielstandsordner", path_to_utf8(initial.saves));
auto *browse = gtk_button_new_with_label("Auswählen …");
gtk_grid_attach(GTK_GRID(grid), browse, 2, 3, 1, 1);
struct Browse {
GtkLauncher *self;
GtkWidget *input;
};
Browse context{this, saves};
g_signal_connect(
browse, "clicked", G_CALLBACK(+[](GtkButton *, gpointer p) {
auto &c = *static_cast<Browse *>(p);
if (auto path = c.self->choose_folder("Spielstandsordner wählen",
path_from_utf8(gtk_entry_get_text(GTK_ENTRY(c.input)))))
gtk_entry_set_text(GTK_ENTRY(c.input), path_to_utf8(*path).c_str());
}),
&context);
gtk_widget_show_all(dialog);
std::optional<AddMod> result;
while (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT)
try {
initial.name = gtk_entry_get_text(GTK_ENTRY(name));
ModLibrary::validate_name(initial.name);
std::string value = gtk_entry_get_text(GTK_ENTRY(year));
size_t end = 0;
initial.start_year = std::stoi(value, &end);
if (end != value.size() || initial.start_year < 1900 || initial.start_year > 9998)
throw std::runtime_error("Startjahr muss zwischen 1900 und 9998 liegen");
initial.saves = path_from_utf8(gtk_entry_get_text(GTK_ENTRY(saves)));
initial.migrate = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(migrate));
result = initial;
break;
} catch (const std::exception &e) {
message(e.what(), true);
}
gtk_widget_destroy(dialog);
return result;
}
std::optional<std::string> rename(const std::string &old) override {
auto *dialog =
gtk_dialog_new_with_buttons("Mod umbenennen", GTK_WINDOW(window_), GTK_DIALOG_MODAL, "Abbrechen",
GTK_RESPONSE_CANCEL, "Umbenennen", GTK_RESPONSE_ACCEPT, nullptr);
auto *input = gtk_entry_new();
gtk_entry_set_text(GTK_ENTRY(input), old.c_str());
gtk_container_set_border_width(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), 16);
gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), input, TRUE, TRUE, 0);
gtk_widget_show_all(dialog);
std::optional<std::string> result;
if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT)
result = gtk_entry_get_text(GTK_ENTRY(input));
gtk_widget_destroy(dialog);
return result;
}
bool confirm_delete(const std::string &name) override {
auto *dialog = gtk_message_dialog_new(GTK_WINDOW(window_), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION,
GTK_BUTTONS_YES_NO, "Mod „%s“ löschen?", name.c_str());
gtk_message_dialog_format_secondary_text(
GTK_MESSAGE_DIALOG(dialog), "Spielstände und persönliche Einstellungen bleiben erhalten.");
const bool yes = gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_YES;
gtk_widget_destroy(dialog);
return yes;
}
void message(const std::string &text, bool error) override {
auto *dialog = gtk_message_dialog_new(GTK_WINDOW(window_), GTK_DIALOG_MODAL,
error ? GTK_MESSAGE_ERROR : GTK_MESSAGE_INFO, GTK_BUTTONS_OK,
"%s", text.c_str());
gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
}
void progress(const std::string &text, bool cancellable) override {
if (!progress_) {
cancelled_ = false;
progress_ = gtk_dialog_new();
gtk_window_set_title(GTK_WINDOW(progress_), "OpenBMH");
gtk_window_set_transient_for(GTK_WINDOW(progress_), GTK_WINDOW(window_));
gtk_window_set_modal(GTK_WINDOW(progress_), TRUE);
gtk_container_set_border_width(GTK_CONTAINER(progress_), 20);
progress_label_ = gtk_label_new(text.c_str());
gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(progress_))), progress_label_,
TRUE, TRUE, 0);
if (cancellable)
gtk_dialog_add_button(GTK_DIALOG(progress_), "Abbrechen", GTK_RESPONSE_CANCEL);
g_signal_connect(progress_, "response", G_CALLBACK(+[](GtkDialog *, int, gpointer data) {
static_cast<GtkLauncher *>(data)->cancelled_ = true;
}),
this);
g_signal_connect(progress_, "delete-event",
G_CALLBACK(+[](GtkWidget *, GdkEvent *, gpointer data) -> gboolean {
static_cast<GtkLauncher *>(data)->cancelled_ = true;
return TRUE;
}),
this);
gtk_widget_set_sensitive(window_, FALSE);
gtk_widget_show_all(progress_);
}
gtk_label_set_text(GTK_LABEL(progress_label_), text.c_str());
}
bool pump() override {
while (gtk_events_pending())
gtk_main_iteration();
return cancelled_;
}
void finish_progress() override {
if (progress_) {
gtk_widget_destroy(progress_);
progress_ = progress_label_ = nullptr;
gtk_widget_set_sensitive(window_, TRUE);
gtk_window_present(GTK_WINDOW(window_));
}
}
};
} // namespace
std::unique_ptr<LauncherUI> make_launcher_ui() { return std::make_unique<GtkLauncher>(); }
} // namespace bmh::launch
+27
View File
@@ -0,0 +1,27 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "launch/mods.hpp"
#include <memory>
#include <optional>
namespace bmh::launch {
enum class LauncherAction { start, add, remove, rename, end };
struct LauncherChoice {
LauncherAction action = LauncherAction::end;
int selection = -1;
};
class LauncherUI {
public:
virtual ~LauncherUI() = default;
virtual LauncherChoice next(const std::vector<ModEntry> &) = 0;
virtual std::optional<std::filesystem::path> choose_folder(const std::string &title,
const std::filesystem::path &initial = {}) = 0;
virtual std::optional<AddMod> configure_add(AddMod defaults) = 0;
virtual std::optional<std::string> rename(const std::string &) = 0;
virtual bool confirm_delete(const std::string &) = 0;
virtual void message(const std::string &, bool error) = 0;
virtual void progress(const std::string &, bool cancellable) = 0;
virtual bool pump() = 0; // cancellation requested
virtual void finish_progress() = 0;
};
std::unique_ptr<LauncherUI> make_launcher_ui();
} // namespace bmh::launch
+317
View File
@@ -0,0 +1,317 @@
// SPDX-License-Identifier: GPL-3.0-only
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <commctrl.h>
#include <shobjidl.h>
#include "launch/launcher_ui.hpp"
#include "launch/archive.hpp"
#include <functional>
namespace bmh::launch {
namespace {
std::wstring wide(const std::string &s) { return path_from_utf8(s).wstring(); }
std::string text(HWND window) {
int n = GetWindowTextLengthW(window);
std::wstring s(size_t(n) + 1, L'\0');
GetWindowTextW(window, s.data(), n + 1);
s.resize(size_t(n));
return path_to_utf8(std::filesystem::path(s));
}
struct Form {
HWND window = nullptr;
bool done = false;
int response = 0;
bool prevent_close = false;
std::function<void(int)> command;
static LRESULT CALLBACK procedure(HWND h, UINT msg, WPARAM w, LPARAM l) {
auto *form = reinterpret_cast<Form *>(GetWindowLongPtrW(h, GWLP_USERDATA));
if (msg == WM_NCCREATE) {
form = static_cast<Form *>(reinterpret_cast<CREATESTRUCTW *>(l)->lpCreateParams);
SetWindowLongPtrW(h, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(form));
form->window = h;
}
if (form) {
if (msg == WM_COMMAND && form->command) {
try {
form->command(LOWORD(w));
} catch (const std::exception &e) {
MessageBoxW(h, wide(e.what()).c_str(), L"OpenBMH", MB_OK | MB_ICONERROR);
}
return 0;
}
if (msg == WM_NOTIFY && reinterpret_cast<NMHDR *>(l)->code == LVN_ITEMCHANGED) {
const bool selected =
ListView_GetNextItem(reinterpret_cast<NMHDR *>(l)->hwndFrom, -1, LVNI_SELECTED) >= 0;
for (int id : {1, 3, 4})
EnableWindow(GetDlgItem(h, id), selected);
return 0;
}
if (msg == WM_CLOSE) {
form->response = 0;
form->done = true;
if (!form->prevent_close)
ShowWindow(h, SW_HIDE);
return 0;
}
}
return DefWindowProcW(h, msg, w, l);
}
Form(const wchar_t *title, int width, int height, HWND owner = nullptr) {
static const bool registered = [] {
WNDCLASSW c{};
c.lpfnWndProc = procedure;
c.hInstance = GetModuleHandleW(nullptr);
c.lpszClassName = L"OpenBMHLauncher";
c.hCursor = LoadCursorW(nullptr, IDC_ARROW);
c.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BTNFACE + 1);
return RegisterClassW(&c) != 0;
}();
if (!registered)
throw std::runtime_error("Cannot register native launcher window");
window =
CreateWindowExW(WS_EX_DLGMODALFRAME, L"OpenBMHLauncher", title,
WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, CW_USEDEFAULT,
CW_USEDEFAULT, width, height, owner, nullptr, GetModuleHandleW(nullptr), this);
if (!window)
throw std::runtime_error("Cannot create native launcher window");
command = [this](int id) {
response = id;
done = true;
};
}
~Form() {
if (window)
DestroyWindow(window);
}
HWND control(const wchar_t *cls, const std::wstring &label, int x, int y, int w, int h, int id,
DWORD style = 0) {
auto window =
CreateWindowExW(cls == std::wstring(L"EDIT") ? WS_EX_CLIENTEDGE : 0, cls, label.c_str(),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | style, x, y, w, h, this->window,
reinterpret_cast<HMENU>(INT_PTR(id)), GetModuleHandleW(nullptr), nullptr);
SendMessageW(window, WM_SETFONT, reinterpret_cast<WPARAM>(GetStockObject(DEFAULT_GUI_FONT)), TRUE);
return window;
}
int run() {
done = false;
response = 0;
ShowWindow(window, SW_SHOW);
SetForegroundWindow(window);
MSG msg;
while (!done && GetMessageW(&msg, nullptr, 0, 0) > 0)
if (!IsDialogMessageW(window, &msg)) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
return response;
}
};
class WinLauncher final : public LauncherUI {
Form main_{L"OpenBMH", 660, 370};
HWND list_ = nullptr;
std::unique_ptr<Form> progress_;
HWND progress_label_ = nullptr;
bool com_ = false;
public:
WinLauncher() {
const auto result = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
com_ = SUCCEEDED(result);
if (FAILED(result) && result != RPC_E_CHANGED_MODE)
throw std::runtime_error("Cannot initialize native folder dialog");
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES};
InitCommonControlsEx(&controls);
list_ = main_.control(WC_LISTVIEWW, L"", 16, 16, 480, 290, 100,
LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | WS_BORDER);
ListView_SetExtendedListViewStyle(list_, LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER);
for (int i = 0; i < 2; ++i) {
LVCOLUMNW c{};
c.mask = LVCF_TEXT | LVCF_WIDTH;
c.cx = i ? 110 : 340;
c.pszText = const_cast<wchar_t *>(i ? L"Art" : L"Name");
ListView_InsertColumn(list_, i, &c);
}
const wchar_t *labels[] = {L"Start", L"Add", L"Delete", L"Rename", L"End"};
for (int i = 0; i < 5; ++i)
main_.control(L"BUTTON", labels[i], 514, 16 + i * 48, 110, 34, i + 1, BS_PUSHBUTTON);
main_.command = [this](int id) {
if (id < 1 || id > 5)
return;
const int selected = ListView_GetNextItem(list_, -1, LVNI_SELECTED);
if (id != 2 && id != 5 && selected < 0)
return;
main_.response = id;
main_.done = true;
};
}
~WinLauncher() override {
if (com_)
CoUninitialize();
}
LauncherChoice next(const std::vector<ModEntry> &mods) override {
const int old = ListView_GetNextItem(list_, -1, LVNI_SELECTED);
ListView_DeleteAllItems(list_);
for (size_t i = 0; i < mods.size(); ++i) {
auto name = wide(mods[i].name + (mods[i].error.empty() ? "" : " [!]"));
LVITEMW row{};
row.mask = LVIF_TEXT;
row.iItem = int(i);
row.pszText = name.data();
ListView_InsertItem(list_, &row);
auto type = wide(mods[i].type);
ListView_SetItemText(list_, int(i), 1, type.data());
}
if (old >= 0 && size_t(old) < mods.size())
ListView_SetItemState(list_, old, LVIS_SELECTED, LVIS_SELECTED);
const bool selected = ListView_GetNextItem(list_, -1, LVNI_SELECTED) >= 0;
for (int id : {1, 3, 4})
EnableWindow(GetDlgItem(main_.window, id), selected);
const int response = main_.run();
return {response == 1 ? LauncherAction::start
: response == 2 ? LauncherAction::add
: response == 3 ? LauncherAction::remove
: response == 4 ? LauncherAction::rename
: LauncherAction::end,
ListView_GetNextItem(list_, -1, LVNI_SELECTED)};
}
std::optional<std::filesystem::path> choose_folder(const std::string &title,
const std::filesystem::path &initial) override {
IFileOpenDialog *dialog = nullptr;
if (FAILED(
CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&dialog))))
throw std::runtime_error("Cannot create folder dialog");
struct Release {
IFileOpenDialog *p;
~Release() { p->Release(); }
} release{dialog};
DWORD options = 0;
dialog->GetOptions(&options);
dialog->SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM);
dialog->SetTitle(wide(title).c_str());
if (!initial.empty()) {
IShellItem *folder = nullptr;
if (SUCCEEDED(SHCreateItemFromParsingName(initial.c_str(), nullptr, IID_PPV_ARGS(&folder)))) {
dialog->SetFolder(folder);
folder->Release();
}
}
const auto status = dialog->Show(main_.window);
if (status == HRESULT_FROM_WIN32(ERROR_CANCELLED))
return {};
if (FAILED(status))
throw std::runtime_error("Folder dialog failed");
IShellItem *item = nullptr;
if (FAILED(dialog->GetResult(&item)))
throw std::runtime_error("No folder selected");
PWSTR name = nullptr;
const auto result = item->GetDisplayName(SIGDN_FILESYSPATH, &name);
item->Release();
if (FAILED(result))
throw std::runtime_error("Invalid folder selection");
std::filesystem::path path(name);
CoTaskMemFree(name);
return path;
}
std::optional<AddMod> configure_add(AddMod initial) override {
Form form(L"Classic-Mod hinzufügen", 650, 295, main_.window);
form.control(L"STATIC", L"Bezeichnung", 16, 20, 160, 22, 100);
auto name = form.control(L"EDIT", wide(initial.name), 182, 16, 425, 26, 101, ES_AUTOHSCROLL);
form.control(L"STATIC", L"Startjahr (nur Anzeige)", 16, 62, 164, 22, 102);
auto year =
form.control(L"EDIT", wide(std::to_string(initial.start_year)), 182, 58, 110, 26, 103, ES_NUMBER);
auto migrate = form.control(L"BUTTON", L"Spielstände/Einstellungen übernehmen", 16, 100, 550, 26, 104,
BS_AUTOCHECKBOX);
SendMessageW(migrate, BM_SETCHECK, initial.migrate ? BST_CHECKED : BST_UNCHECKED, 0);
form.control(L"STATIC", L"Spielstandsordner", 16, 146, 160, 22, 105);
auto saves = form.control(L"EDIT", initial.saves.wstring(), 182, 140, 310, 26, 106, ES_AUTOHSCROLL);
form.control(L"BUTTON", L"Auswählen …", 502, 140, 106, 26, 107);
form.control(L"BUTTON", L"Importieren", 365, 204, 116, 32, 1);
form.control(L"BUTTON", L"Abbrechen", 493, 204, 116, 32, 2);
form.command = [&](int id) {
if (id == 107) {
if (auto path = choose_folder("Spielstandsordner wählen", path_from_utf8(text(saves))))
SetWindowTextW(saves, path->c_str());
} else if (id == 1 || id == 2) {
form.response = id;
form.done = true;
}
};
EnableWindow(main_.window, FALSE);
std::optional<AddMod> out;
while (form.run() == 1)
try {
initial.name = text(name);
ModLibrary::validate_name(initial.name);
auto value = text(year);
size_t end = 0;
initial.start_year = std::stoi(value, &end);
if (end != value.size() || initial.start_year < 1900 || initial.start_year > 9998)
throw std::runtime_error("Startjahr muss zwischen 1900 und 9998 liegen");
initial.saves = path_from_utf8(text(saves));
initial.migrate = SendMessageW(migrate, BM_GETCHECK, 0, 0) == BST_CHECKED;
out = initial;
break;
} catch (const std::exception &e) {
message(e.what(), true);
}
EnableWindow(main_.window, TRUE);
return out;
}
std::optional<std::string> rename(const std::string &old) override {
Form form(L"Mod umbenennen", 480, 165, main_.window);
auto input = form.control(L"EDIT", wide(old), 16, 16, 430, 26, 100, ES_AUTOHSCROLL);
form.control(L"BUTTON", L"Umbenennen", 190, 65, 120, 32, 1);
form.control(L"BUTTON", L"Abbrechen", 322, 65, 124, 32, 2);
EnableWindow(main_.window, FALSE);
const auto response = form.run();
EnableWindow(main_.window, TRUE);
return response == 1 ? std::optional<std::string>(text(input)) : std::nullopt;
}
bool confirm_delete(const std::string &name) override {
return MessageBoxW(main_.window,
wide("Mod „" + name +
"“ löschen?\nSpielstände und persönliche Einstellungen bleiben erhalten.")
.c_str(),
L"OpenBMH", MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2) == IDYES;
}
void message(const std::string &value, bool error) override {
MessageBoxW(main_.window, wide(value).c_str(), L"OpenBMH",
MB_OK | (error ? MB_ICONERROR : MB_ICONINFORMATION));
}
void progress(const std::string &value, bool cancellable) override {
if (!progress_) {
EnableWindow(main_.window, FALSE);
progress_ = std::make_unique<Form>(L"OpenBMH", 600, 150, main_.window);
progress_->prevent_close = true;
progress_label_ = progress_->control(L"STATIC", L"", 16, 18, 550, 40, 100);
if (cancellable)
progress_->control(L"BUTTON", L"Abbrechen", 440, 65, 115, 28, 1);
ShowWindow(progress_->window, SW_SHOW);
}
SetWindowTextW(progress_label_, wide(value).c_str());
}
bool pump() override {
MSG msg;
while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
return progress_ && progress_->done;
}
void finish_progress() override {
if (progress_) {
progress_.reset();
EnableWindow(main_.window, TRUE);
SetForegroundWindow(main_.window);
}
}
};
} // namespace
std::unique_ptr<LauncherUI> make_launcher_ui() { return std::make_unique<WinLauncher>(); }
} // namespace bmh::launch
+190
View File
@@ -0,0 +1,190 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "launch/mods.hpp"
#include "content/save.hpp"
#include "launch/archive.hpp"
#include <algorithm>
#include <cctype>
#include <chrono>
#include <set>
namespace bmh::launch {
namespace fs = std::filesystem;
namespace {
std::string fold(std::string s) {
for (auto &c : s)
c = char(std::tolower(static_cast<unsigned char>(c)));
return s;
}
std::string filename(const fs::path &p) { return path_to_utf8(p.filename()); }
void safe_directory(const fs::path &path) {
const auto status = fs::symlink_status(path);
if (fs::is_symlink(status) || (fs::exists(status) && !fs::is_directory(status)))
throw FormatError("Unsafe portable directory: " + path_to_utf8(path));
fs::create_directories(path);
}
} // namespace
ModLibrary::ModLibrary(fs::path root) : root_(fs::absolute(std::move(root)).lexically_normal()) {}
void ModLibrary::validate_name(const std::string &name) {
if (name.empty() || name.size() > 100 || name == "." || name == ".." || name.front() == '.' ||
name.back() == '.' || name.back() == ' ')
throw FormatError("Invalid mod name");
for (unsigned char c : name)
if (c < 32 || c == 127 || std::string("/\\:*?\"<>|").find(char(c)) != std::string::npos)
throw FormatError("Invalid character in mod name");
auto base = fold(name.substr(0, name.find('.')));
const std::set<std::string> reserved{"con", "prn", "aux", "nul", "com1", "com2", "com3", "com4",
"com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
"lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9"};
if (reserved.contains(base))
throw FormatError("Reserved mod name");
}
std::vector<ModEntry> ModLibrary::list() const {
std::vector<ModEntry> out;
const auto folder = root_ / "mods";
if (!fs::exists(fs::symlink_status(folder)))
return out;
if (fs::is_symlink(fs::symlink_status(folder)) || !fs::is_directory(folder))
throw FormatError("Unsafe mods directory");
for (const auto &entry : fs::directory_iterator(folder)) {
const auto name = filename(entry.path());
if (name.starts_with('.'))
continue;
if (!entry.is_directory() && !entry.is_symlink())
continue;
ModEntry mod;
mod.name = name;
mod.directory = entry.path();
try {
validate_name(name);
if (entry.is_symlink())
throw FormatError("Linked mod directories are not supported");
for (const auto &child : fs::directory_iterator(entry.path()))
if (child.path().filename() != "content.obw")
throw FormatError("Unexpected files in sealed Classic mod");
const auto content = content::open(entry.path() / "content.obw");
mod.content_id = content->content_id;
} catch (const std::exception &e) {
mod.error = e.what();
}
out.push_back(std::move(mod));
}
std::sort(out.begin(), out.end(),
[](const auto &a, const auto &b) { return fold(a.name) < fold(b.name); });
return out;
}
void ModLibrary::available(const std::string &name) const {
validate_name(name);
const auto folder = root_ / "mods";
if (fs::exists(fs::symlink_status(folder))) {
if (fs::is_symlink(fs::symlink_status(folder)) || !fs::is_directory(folder))
throw FormatError("Unsafe mods directory");
for (const auto &entry : fs::directory_iterator(folder))
if (fold(filename(entry.path())) == fold(name))
throw FormatError("A mod with this name already exists");
}
}
void ModLibrary::owned(const ModEntry &mod) const {
if (mod.directory.parent_path() != root_ / "mods" || filename(mod.directory) != mod.name ||
fs::is_symlink(fs::symlink_status(mod.directory)))
throw FormatError("Mod path is not owned by this library");
}
fs::path ModLibrary::user_directory(const ModEntry &mod) const {
if (mod.content_id.size() != 64 ||
mod.content_id.find_first_not_of("0123456789abcdef") != std::string::npos)
throw FormatError("Invalid mod identity");
safe_directory(root_ / "userdata");
const auto directory = root_ / "userdata" / mod.content_id;
safe_directory(directory);
return directory;
}
ImportReport ModLibrary::add(const AddMod &request, const SaveMigrator &migrate,
const ImportProgress &progress) {
available(request.name);
if (request.start_year < 1900 || request.start_year > 9998)
throw FormatError("Start year must be 1900–9998");
safe_directory(root_ / "mods");
const auto update = [&](const std::string &s) {
if (progress)
progress(s);
};
update("Installation wird konvertiert …");
obw::Options options;
options.start_date = std::to_string(request.start_year) + "-07-01";
options.title = "Classic installation";
auto docs = obw::import_installation(request.source, options);
const auto identity = content::seal(docs);
update("Konvertierte Inhalte werden geprüft …");
const auto staging =
root_ / "mods" /
(".import-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
if (!fs::create_directory(staging))
throw FormatError("Cannot reserve mod staging directory");
struct Cleanup {
fs::path p;
~Cleanup() {
std::error_code ec;
fs::remove_all(p, ec);
}
} cleanup{staging};
content::write_archive(docs, staging / "content.obw");
(void)content::open(staging / "content.obw");
ImportReport report;
report.mod = {request.name, "Classic", identity, {}, root_ / "mods" / path_from_utf8(request.name)};
const auto userdata = user_directory(report.mod);
// User data is retained separately, and never overwrites a previous migration.
if (request.migrate) {
const auto source = request.saves.empty() ? request.source : request.saves;
if (!fs::is_directory(source))
report.errors.push_back("Spielstandsordner ist nicht verfügbar");
else {
std::vector<fs::path> files;
for (const auto &entry : fs::directory_iterator(source))
if (entry.is_regular_file() && !entry.is_symlink())
files.push_back(entry.path());
std::sort(files.begin(), files.end());
for (const auto &input : files) {
const auto ext = fold(path_to_utf8(input.extension()));
if (ext != ".fbm" && ext != ".ein" && ext != ".men")
continue;
update("Übernahme: " + filename(input));
try {
auto destination = userdata / input.stem();
destination += ext == ".fbm" ? ".obs" : ext == ".ein" ? ".obsettings" : ".oblayout";
if (fs::exists(fs::symlink_status(destination)))
throw FormatError("Destination already exists; retained existing file");
if (ext == ".fbm") {
if (!migrate)
throw FormatError("Save migrator unavailable");
migrate(staging / "content.obw", input, destination);
} else {
auto bytes = read_file(input);
if (ext == ".ein" && bytes.size() != 180)
throw FormatError("Invalid settings length");
if (ext == ".men" && bytes.size() != 0x360)
throw FormatError("Invalid desktop layout length");
content::save_preferences(destination, ext == ".ein" ? "settings" : "layout", bytes,
false);
}
++report.migrated;
} catch (const std::exception &e) {
report.errors.push_back(filename(input) + ": " + e.what());
}
}
}
}
update("Mod wird eingetragen …");
available(request.name);
fs::rename(staging, report.mod.directory);
return report;
}
void ModLibrary::rename(const ModEntry &mod, const std::string &name) {
owned(mod);
if (name == mod.name)
return;
available(name);
fs::rename(mod.directory, root_ / "mods" / path_from_utf8(name));
}
void ModLibrary::remove(const ModEntry &mod) {
owned(mod);
fs::remove_all(mod.directory);
}
} // namespace bmh::launch
+41
View File
@@ -0,0 +1,41 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "content/package.hpp"
#include <functional>
namespace bmh::launch {
struct ModEntry {
std::string name, type = "Classic", content_id, error;
std::filesystem::path directory;
};
struct AddMod {
std::filesystem::path source, saves;
std::string name;
int start_year = 2026;
bool migrate = true;
};
using SaveMigrator =
std::function<void(const std::filesystem::path &content, const std::filesystem::path &source,
const std::filesystem::path &destination)>;
using ImportProgress = std::function<void(const std::string &)>;
struct ImportReport {
ModEntry mod;
size_t migrated = 0;
std::vector<std::string> errors;
};
class ModLibrary {
public:
explicit ModLibrary(std::filesystem::path portable_root);
std::vector<ModEntry> list() const;
ImportReport add(const AddMod &, const SaveMigrator &, const ImportProgress &progress = {});
void rename(const ModEntry &, const std::string &name);
void remove(const ModEntry &);
std::filesystem::path user_directory(const ModEntry &) const;
const std::filesystem::path &root() const { return root_; }
static void validate_name(const std::string &);
private:
std::filesystem::path root_;
void available(const std::string &) const;
void owned(const ModEntry &) const;
};
} // namespace bmh::launch
+84
View File
@@ -0,0 +1,84 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "launch/process.hpp"
#include "launch/archive.hpp"
#include <chrono>
#include <thread>
#include <stdexcept>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <spawn.h>
#include <sys/wait.h>
#include <cerrno>
extern char **environ;
#endif
namespace bmh::launch {
int run_child(const std::filesystem::path &executable, const std::vector<std::string> &args,
const std::function<void()> &pump) {
#ifdef _WIN32
const auto quote = [](const std::wstring &value) {
std::wstring out = L"\"";
size_t slashes = 0;
for (wchar_t c : value) {
if (c == L'\\') {
++slashes;
continue;
}
if (c == L'\"')
out.append(slashes * 2 + 1, L'\\');
else
out.append(slashes, L'\\');
out += c;
slashes = 0;
}
out.append(slashes * 2, L'\\');
out += L'\"';
return out;
};
auto command = quote(executable.wstring());
for (const auto &a : args) {
command += L' ';
command += quote(path_from_utf8(a).wstring());
}
STARTUPINFOW start{};
start.cb = sizeof(start);
PROCESS_INFORMATION process{};
if (!CreateProcessW(executable.c_str(), command.data(), nullptr, nullptr, FALSE, 0, nullptr,
executable.parent_path().c_str(), &start, &process))
throw std::runtime_error("Cannot start OpenBMH game process");
CloseHandle(process.hThread);
while (WaitForSingleObject(process.hProcess, 20) == WAIT_TIMEOUT)
if (pump)
pump();
DWORD code = 1;
GetExitCodeProcess(process.hProcess, &code);
CloseHandle(process.hProcess);
return int(code);
#else
const auto binary = path_to_utf8(executable);
std::vector<std::string> storage{binary};
storage.insert(storage.end(), args.begin(), args.end());
std::vector<char *> argv;
for (auto &s : storage)
argv.push_back(s.data());
argv.push_back(nullptr);
pid_t pid;
const int error = posix_spawn(&pid, binary.c_str(), nullptr, nullptr, argv.data(), environ);
if (error)
throw std::runtime_error("Cannot start OpenBMH game process (" + std::to_string(error) + ")");
int status = 0;
for (;;) {
const auto result = waitpid(pid, &status, WNOHANG);
if (result == pid)
break;
if (result < 0 && errno != EINTR)
throw std::runtime_error("Cannot wait for game process");
if (pump)
pump();
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
return WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
#endif
}
} // namespace bmh::launch
+10
View File
@@ -0,0 +1,10 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <filesystem>
#include <functional>
#include <string>
#include <vector>
namespace bmh::launch {
int run_child(const std::filesystem::path &, const std::vector<std::string> &,
const std::function<void()> &pump);
} // namespace bmh::launch