Add RmlUI night-stadium launcher and shared theme (by Codex)

This commit is contained in:
Codex committed 2026-10-18 13:30:24 +02:00
1 parent 00f522c1f3
commit 8aa849e9fa
32 files changed
+1841 -917

No files matched your search

+6 -14
View File
@@ -30,20 +30,12 @@ target_link_libraries(bmh_content PUBLIC bmh_obw PRIVATE bmh_miniz)
add_library(bmh_launcher STATIC ../launch/mods.cpp ../launch/process.cpp ../launch/launcher.cpp)
target_include_directories(bmh_launcher PUBLIC ..)
target_link_libraries(bmh_launcher PUBLIC bmh_content)
if(WIN32)
target_sources(bmh_launcher PRIVATE ../launch/launcher_win32.cpp)
target_link_libraries(bmh_launcher PRIVATE comctl32 ole32 shell32 uuid)
elseif(APPLE)
set_property(TARGET bmh_launcher PROPERTY OBJCXX_STANDARD 20)
target_sources(bmh_launcher PRIVATE ../launch/launcher_cocoa.mm)
set_source_files_properties(../launch/launcher_cocoa.mm PROPERTIES COMPILE_OPTIONS "-fobjc-arc")
target_link_libraries(bmh_launcher PRIVATE "-framework AppKit")
else()
find_package(PkgConfig REQUIRED)
pkg_check_modules(BMH_GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
target_sources(bmh_launcher PRIVATE ../launch/launcher_gtk.cpp)
target_link_libraries(bmh_launcher PRIVATE PkgConfig::BMH_GTK)
endif()
include(../launch/rmlui.cmake)
target_sources(bmh_launcher PRIVATE ../launch/launcher_rmlui.cpp)
target_link_libraries(bmh_launcher PRIVATE bmh_rmlui nfd)
add_executable(launcher_document_tests ../../tests/launcher_document_tests.cpp)
target_link_libraries(launcher_document_tests PRIVATE RmlUi::Core)
add_test(NAME launcher_document_tests COMMAND launcher_document_tests "${launcher_assets}")
add_executable(native_content_tests ../../tests/native_content_tests.cpp)
target_link_libraries(native_content_tests PRIVATE bmh_launcher)
add_test(NAME native_content_tests COMMAND native_content_tests)
-300
View File
@@ -1,300 +0,0 @@
// 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 {
finish_progress();
bridge_->action = {};
bridge_->selection = {};
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
@@ -1,269 +0,0 @@
// 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);
const auto folder=initial.empty()?path_from_utf8(g_get_home_dir()):initial;
gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog),path_to_utf8(folder).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
+557
View File
@@ -0,0 +1,557 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "launch/launcher_ui.hpp"
#include "launch/archive.hpp"
#include "launch/process.hpp"
#include "version.hpp"
#include <RmlUi/Core.h>
#include <RmlUi/Core/Elements/ElementFormControl.h>
#include <RmlUi/Core/Elements/ElementFormControlInput.h>
#include <RmlUi_Platform_SDL.h>
#include <RmlUi_Renderer_GL3.h>
#include <nfd.hpp>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <stdexcept>
namespace bmh::launch {
namespace {
std::string escape(std::string_view value) {
std::string result;
for (char c : value)
switch (c) {
case '&':
result += "&amp;";
break;
case '<':
result += "&lt;";
break;
case '>':
result += "&gt;";
break;
case '"':
result += "&quot;";
break;
case '\n':
result += "<br/>";
break;
default:
result += c;
}
return result;
}
[[noreturn]] void sdl_error(const char *operation) {
throw std::runtime_error(std::string(operation) + ": " + SDL_GetError());
}
int modifiers(Uint16 state) {
int result = 0;
if (state & KMOD_CTRL)
result |= Rml::Input::KM_CTRL;
if (state & KMOD_SHIFT)
result |= Rml::Input::KM_SHIFT;
if (state & KMOD_ALT)
result |= Rml::Input::KM_ALT;
if (state & KMOD_GUI)
result |= Rml::Input::KM_META;
#ifdef __APPLE__
// RmlUI text widgets use the Ctrl flag for editing shortcuts.
if (state & KMOD_GUI)
result |= Rml::Input::KM_CTRL;
#endif
if (state & KMOD_CAPS)
result |= Rml::Input::KM_CAPSLOCK;
if (state & KMOD_NUM)
result |= Rml::Input::KM_NUMLOCK;
return result;
}
struct Video {
SDL_Window *window = nullptr;
SDL_GLContext gl = nullptr;
bool loader = false;
Video() {
try {
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER) != 0)
sdl_error("Launcher video initialization");
SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
#ifdef __APPLE__
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
#else
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
#endif
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
window = SDL_CreateWindow("OpenBMH", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1100, 688,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI |
SDL_WINDOW_HIDDEN);
if (!window)
sdl_error("Launcher window");
SDL_SetWindowMinimumSize(window, 800, 540);
gl = SDL_GL_CreateContext(window);
if (!gl)
sdl_error("Launcher requires OpenGL 3.3 (macOS: 4.1)");
SDL_GL_MakeCurrent(window, gl);
SDL_GL_SetSwapInterval(1);
std::string error;
if (!RmlGL3::Initialize(&error))
throw std::runtime_error("Launcher graphics initialization: " + error);
loader = true;
SDL_StopTextInput();
} catch (...) {
close();
throw;
}
}
void close() {
if (loader)
RmlGL3::Shutdown();
if (gl)
SDL_GL_DeleteContext(gl);
if (window)
SDL_DestroyWindow(window);
SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER);
}
~Video() { close(); }
};
class RmlLauncher final : public LauncherUI, public Rml::EventListener {
Video video_;
SystemInterface_SDL system_{video_.window};
RenderInterface_GL3 renderer_;
TextInputMethodEditor_SDL ime_;
Rml::Context *context_ = nullptr;
Rml::ElementDocument *document_ = nullptr;
bool initialized_ = false, closed_ = false, dirty_ = true;
bool answered_ = false, accepted_ = false, busy_ = false, cancelled_ = false;
bool cancellable_ = false, modal_visible_ = false;
int selected_ = -1;
std::string selected_name_;
std::vector<ModEntry> mods_;
std::optional<LauncherAction> action_;
Rml::Element *element(const char *id) const {
auto *value = document_->GetElementById(id);
if (!value)
throw std::runtime_error(std::string("Launcher element missing: ") + id);
return value;
}
void text(const char *id, const std::string &value) {
element(id)->SetInnerRML(escape(value));
dirty_ = true;
}
void display(const char *id, bool shown, const char *style = "block") {
element(id)->SetProperty("display", shown ? style : "none");
dirty_ = true;
}
void enabled(const char *id, bool active) {
auto *button = element(id);
if (active)
button->RemoveAttribute("disabled");
else
button->SetAttribute("disabled", "disabled");
button->SetPseudoClass("disabled", !active);
button->SetProperty("focus", active ? "auto" : "none");
dirty_ = true;
}
std::string value(const char *id) const {
auto *input = dynamic_cast<Rml::ElementFormControl *>(element(id));
if (!input)
throw std::runtime_error("Launcher input has the wrong type");
return input->GetValue();
}
void resize() {
int w = 0, h = 0, pixels_w = 0, pixels_h = 0;
SDL_GetWindowSize(video_.window, &w, &h);
SDL_GL_GetDrawableSize(video_.window, &pixels_w, &pixels_h);
if (w <= 0 || h <= 0 || pixels_w <= 0 || pixels_h <= 0)
return;
renderer_.SetViewport(pixels_w, pixels_h);
context_->SetDimensions({pixels_w, pixels_h});
const float scale = std::clamp(std::min(w / 1100.f, h / 688.f), .72f, 2.5f);
context_->SetDensityIndependentPixelRatio(float(pixels_w) / w * scale);
dirty_ = true;
}
void select(int index, bool focus = false) {
if (index < 0 || size_t(index) >= mods_.size())
index = -1;
selected_ = index;
selected_name_ = index >= 0 ? mods_[size_t(index)].name : std::string{};
for (size_t i = 0; i < mods_.size(); ++i) {
auto *row = document_->GetElementById("mod-" + std::to_string(i));
row->SetClass("selected", int(i) == selected_);
row->SetAttribute("aria-selected", int(i) == selected_ ? "true" : "false");
if (focus && int(i) == selected_) {
row->Focus(true);
row->ScrollIntoView();
}
}
enabled("start", selected_ >= 0);
enabled("delete", selected_ >= 0);
enabled("rename", selected_ >= 0);
}
bool modal_open() const { return modal_visible_; }
void close_modal() {
modal_visible_ = false;
display("overlay", false);
answered_ = false;
busy_ = false;
SDL_StopTextInput();
if (selected_ >= 0)
select(selected_, true);
else
element("add")->Focus(true);
}
void modal(const std::string &title, const std::string &body, const std::string &accept,
bool cancel = true, bool danger = false) {
text("modal-title", title);
element("modal-body")->SetInnerRML(body);
text("modal-error", "");
text("accept", accept);
element("accept")->SetClass("danger", danger);
element("accept")->SetClass("primary", !danger);
display("accept", !accept.empty(), "inline-block");
display("cancel", cancel, "inline-block");
answered_ = accepted_ = false;
display("overlay", true);
modal_visible_ = true;
if (auto *input = document_->GetElementById("mod-name"))
input->Focus(true);
else
element(cancel ? "cancel" : "accept")->Focus(true);
context_->Update();
dirty_ = true;
}
void dispatch(const std::string &command) {
if (command == "cancel") {
if (busy_) {
if (cancellable_)
cancelled_ = true;
} else {
answered_ = true;
accepted_ = false;
}
} else if (command == "accept" && !busy_) {
answered_ = accepted_ = true;
} else if (command == "browse" && !busy_) {
try {
if (auto path =
choose_folder("Spielstandsordner wählen", path_from_utf8(value("save-folder")))) {
auto *input = dynamic_cast<Rml::ElementFormControl *>(element("save-folder"));
input->SetValue(path_to_utf8(*path));
}
} catch (const std::exception &e) {
text("modal-error", e.what());
}
} else if (!modal_open()) {
if (command == "add")
action_ = LauncherAction::add;
else if (command == "end")
action_ = LauncherAction::end;
else if (selected_ >= 0) {
if (command == "start")
action_ = LauncherAction::start;
else if (command == "rename")
action_ = LauncherAction::rename;
else if (command == "delete")
action_ = LauncherAction::remove;
}
}
dirty_ = true;
}
void ProcessEvent(Rml::Event &event) override {
const bool double_click = event.GetType() == "dblclick";
if (event.GetType() != "click" && !double_click)
return;
for (auto *target = event.GetTargetElement(); target && target != document_;
target = target->GetParentNode()) {
if (target->HasAttribute("data-row") && !modal_open()) {
select(target->GetAttribute<int>("data-row", -1));
if (double_click)
dispatch("start");
return;
}
if (target->HasAttribute("data-action")) {
if (double_click)
return;
if (!target->HasAttribute("disabled"))
dispatch(target->GetAttribute<Rml::String>("data-action", ""));
return;
}
}
}
void step(bool wait) {
// Modal visibility and refreshed rows must be laid out before queued
// pointer events are hit-tested against the new document state.
if (dirty_) context_->Update();
SDL_Event event;
const int timeout = dirty_ ? 0 : int(std::clamp(context_->GetNextUpdateDelay(), 0.0, .2) * 1000);
bool got = wait ? SDL_WaitEventTimeout(&event, timeout) != 0 : SDL_PollEvent(&event) != 0;
bool redraw = dirty_ || got || context_->GetNextUpdateDelay() <= 0;
while (got) {
if (event.type == SDL_QUIT ||
(event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE)) {
closed_ = answered_ = true;
accepted_ = false;
cancelled_ = true;
action_ = LauncherAction::end;
} else if (event.type == SDL_KEYDOWN && !event.key.repeat &&
event.key.keysym.sym == SDLK_ESCAPE) {
if (modal_open())
dispatch("cancel");
else
action_ = LauncherAction::end;
} else if (event.type == SDL_KEYDOWN && modal_open() && event.key.keysym.sym == SDLK_TAB) {
Rml::ElementList controls;
element("modal")->QuerySelectorAll(controls, "input, button");
std::erase_if(controls, [](auto *control) {
return !control->IsVisible() || control->HasAttribute("disabled");
});
if (!controls.empty()) {
const auto at = std::find(controls.begin(), controls.end(), context_->GetFocusElement());
const int current = at == controls.end() ? -1 : int(at - controls.begin());
const int step = event.key.keysym.mod & KMOD_SHIFT ? -1 : 1;
const int next = (current + step + int(controls.size())) % int(controls.size());
controls[size_t(next)]->Focus(true);
}
} else if (event.type == SDL_KEYDOWN && !modal_open() && !event.key.repeat &&
(event.key.keysym.sym == SDLK_UP || event.key.keysym.sym == SDLK_DOWN)) {
const int direction = event.key.keysym.sym == SDLK_UP ? -1 : 1;
if (!mods_.empty())
select(std::clamp(selected_ < 0 ? 0 : selected_ + direction, 0, int(mods_.size()) - 1),
true);
} else if (event.type == SDL_KEYDOWN && !event.key.repeat &&
(event.key.keysym.sym == SDLK_RETURN || event.key.keysym.sym == SDLK_SPACE) &&
context_->GetFocusElement() &&
context_->GetFocusElement()->HasAttribute("data-action")) {
auto *focused = context_->GetFocusElement();
if (!focused->HasAttribute("disabled"))
dispatch(focused->GetAttribute<Rml::String>("data-action", ""));
} else if (event.type == SDL_KEYDOWN && !event.key.repeat &&
event.key.keysym.sym == SDLK_RETURN) {
if (modal_open() && !busy_)
dispatch("accept");
else if (!modal_open() && selected_ >= 0)
dispatch("start");
} else if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) {
// Use the modifiers captured with this event, not SDL's final
// state after pumping a batch containing the key releases.
const auto key = RmlSDL::ConvertKey(event.key.keysym.sym);
if (event.type == SDL_KEYDOWN)
context_->ProcessKeyDown(key, modifiers(event.key.keysym.mod));
else
context_->ProcessKeyUp(key, modifiers(event.key.keysym.mod));
} else {
if (event.type == SDL_TEXTEDITING)
ime_.HandleEdit(event.edit);
// SDL2 reports mouse coordinates in window units on Retina/HiDPI.
int w = 0, h = 0, pw = 0, ph = 0;
SDL_GetWindowSize(video_.window, &w, &h);
SDL_GL_GetDrawableSize(video_.window, &pw, &ph);
if (w > 0 && h > 0) {
if (event.type == SDL_MOUSEMOTION) {
event.motion.x = int(double(event.motion.x) * pw / w);
event.motion.y = int(double(event.motion.y) * ph / h);
}
if (event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP) {
event.button.x = int(double(event.button.x) * pw / w);
event.button.y = int(double(event.button.y) * ph / h);
// Repeated clicks need a fresh hover target even when
// the pointer has not moved since a modal was closed.
context_->ProcessMouseMove(event.button.x, event.button.y,
RmlSDL::GetKeyModifierState());
}
}
RmlSDL::InputEventHandler(context_, video_.window, event);
}
if (event.type == SDL_WINDOWEVENT)
resize();
got = SDL_PollEvent(&event) != 0;
}
if (redraw) {
context_->Update();
renderer_.BeginFrame();
renderer_.Clear();
context_->Render();
renderer_.EndFrame();
SDL_GL_SwapWindow(video_.window);
dirty_ = false;
}
}
bool wait_modal() {
while (!answered_ && !closed_)
step(true);
answered_ = false;
return accepted_ && !closed_;
}
public:
RmlLauncher() {
if (!renderer_)
throw std::runtime_error("RmlUI could not create the OpenGL renderer");
try {
Rml::SetSystemInterface(&system_);
Rml::SetRenderInterface(&renderer_);
Rml::SetTextInputHandler(&ime_);
initialized_ = Rml::Initialise();
if (!initialized_)
throw std::runtime_error("RmlUI initialization failed");
const auto assets = executable_path({}).parent_path() / "assets" / "launcher";
for (const char *weight : {"Regular", "Bold"})
if (!Rml::LoadFontFace(path_to_utf8(assets / (std::string("LatoLatin-") + weight + ".ttf"))))
throw std::runtime_error("Launcher font missing; extract the complete OpenBMH package");
context_ = Rml::CreateContext("launcher", {1100, 688});
if (!context_)
throw std::runtime_error("RmlUI launcher context failed");
document_ = context_->LoadDocument(path_to_utf8(assets / "launcher.rml"));
if (!document_)
throw std::runtime_error("Launcher layout missing; extract the complete OpenBMH package");
document_->AddEventListener("click", this);
document_->AddEventListener("dblclick", this);
text("version", std::string("v") + bmh::kOpenBmhVersion);
resize();
document_->Show();
SDL_ShowWindow(video_.window);
element("add")->Focus(true);
} catch (...) {
if (initialized_)
Rml::Shutdown();
throw;
}
}
~RmlLauncher() override {
if (initialized_)
Rml::Shutdown();
}
LauncherChoice next(const std::vector<ModEntry> &mods) override {
if (closed_)
return {LauncherAction::end, -1};
mods_ = mods;
std::string rows;
int selection = -1;
for (size_t i = 0; i < mods.size(); ++i) {
const auto &mod = mods[i];
if (mod.name == selected_name_)
selection = int(i);
rows += "<button id=\"mod-" + std::to_string(i) + "\" class=\"mod-row" +
(mod.error.empty() ? "" : " invalid") + "\" data-row=\"" + std::to_string(i) +
"\" title=\"" + escape(mod.error) + "\"><span class=\"name\">" + escape(mod.name) +
"</span><span class=\"type\">" + escape(mod.type) + "</span></button>";
}
if (mods.empty())
rows = "<div class=\"empty\">Keine Mods vorhanden.<div class=\"empty-detail\">Über Add eine "
"Installation hinzufügen.</div></div>";
element("mod-list")->SetInnerRML(rows);
text("mod-count", std::to_string(mods.size()) + (mods.size() == 1 ? " Mod" : " Mods"));
select(selection);
action_.reset();
while (!action_ && !closed_)
step(true);
return {action_.value_or(LauncherAction::end), selected_};
}
std::optional<std::filesystem::path> choose_folder(const std::string &title,
const std::filesystem::path &initial = {}) override {
(void)title;
NFD::Guard guard;
NFD::UniquePathU8 result;
const auto directory = path_to_utf8(initial.empty() ? executable_path({}).parent_path() : initial);
const auto status = NFD::PickFolder(result, directory.c_str());
SDL_RaiseWindow(video_.window);
dirty_ = true;
if (status == NFD_CANCEL)
return {};
if (status != NFD_OKAY)
throw std::runtime_error(std::string("Ordnerauswahl: ") + NFD::GetError());
return path_from_utf8(result.get());
}
std::optional<AddMod> configure_add(AddMod initial) override {
modal("Classic-Mod hinzufügen",
"<label>Bezeichnung</label><input id=\"mod-name\" type=\"text\" maxlength=\"100\" value=\"" +
escape(initial.name) +
"\"/><div class=\"fields\"><div class=\"year\"><label>Startjahr (nur "
"Anzeige)</label><input id=\"start-year\" type=\"text\" maxlength=\"4\" value=\"" +
std::to_string(initial.start_year) +
"\"/></div></div><div class=\"check-row\"><input id=\"migrate\" class=\"checkbox\" "
"type=\"checkbox\" " +
(initial.migrate ? "checked=\"checked\"" : "") +
"/><label for=\"migrate\">Spielstände/Einstellungen "
"übernehmen</label></div><label>Spielstandsordner</label><div class=\"browse-row\"><input "
"id=\"save-folder\" type=\"text\" value=\"" +
escape(path_to_utf8(initial.saves)) +
"\"/><button data-action=\"browse\">Auswählen …</button></div>",
"Importieren");
while (wait_modal()) {
try {
initial.name = value("mod-name");
ModLibrary::validate_name(initial.name);
const auto year = value("start-year");
size_t end = 0;
initial.start_year = std::stoi(year, &end);
if (end != year.size() || initial.start_year < 1900 || initial.start_year > 9998)
throw std::runtime_error("Startjahr muss zwischen 1900 und 9998 liegen.");
initial.migrate = element("migrate")->HasAttribute("checked");
initial.saves = path_from_utf8(value("save-folder"));
close_modal();
return initial;
} catch (const std::exception &e) {
text("modal-error", e.what());
}
}
close_modal();
return {};
}
std::optional<std::string> rename(const std::string &old) override {
modal("Mod umbenennen",
"<label>Bezeichnung</label><input id=\"mod-name\" type=\"text\" maxlength=\"100\" value=\"" +
escape(old) + "\"/>",
"Umbenennen");
std::optional<std::string> result;
while (wait_modal()) {
try {
auto name = value("mod-name");
ModLibrary::validate_name(name);
result = name;
break;
} catch (const std::exception &e) {
text("modal-error", e.what());
}
}
close_modal();
return result;
}
bool confirm_delete(const std::string &name) override {
modal("Mod löschen?",
"„" + escape(name) + "“<br/><br/>Spielstände und persönliche Einstellungen bleiben erhalten.",
"Löschen", true, true);
const bool result = wait_modal();
close_modal();
return result;
}
void message(const std::string &value, bool error) override {
if (closed_)
return;
modal(error ? "OpenBMH · Hinweis" : "OpenBMH", escape(value), "OK", false);
wait_modal();
close_modal();
}
void progress(const std::string &value, bool cancellable) override {
if (!busy_) {
modal(cancellable ? "Mod importieren" : "Spiel läuft", escape(value), "", cancellable);
busy_ = true;
cancelled_ = false;
cancellable_ = cancellable;
} else
text("modal-body", value);
}
bool pump() override {
step(false);
return cancelled_ || closed_;
}
void finish_progress() override {
if (busy_)
close_modal();
}
};
} // namespace
std::unique_ptr<LauncherUI> make_launcher_ui() { return std::make_unique<RmlLauncher>(); }
} // namespace bmh::launch
-320
View File
@@ -1,320 +0,0 @@
// 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) {
// Edit controls also emit WM_COMMAND while the user types.
if (id != IDOK && id != IDCANCEL)
return;
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
+41
View File
@@ -0,0 +1,41 @@
# SPDX-License-Identifier: GPL-3.0-only
# A shared visual layer for the launcher and future modern screens.
set(BUILD_SHARED_LIBS OFF CACHE BOOL "Build dependencies statically" FORCE)
foreach(feature IN ITEMS ZLIB BZIP2 PNG HARFBUZZ BROTLI)
set(FT_DISABLE_${feature} ON CACHE BOOL "Keep the bundled font engine minimal" FORCE)
endforeach()
set(SKIP_INSTALL_ALL ON)
FetchContent_Declare(freetype
GIT_REPOSITORY https://github.com/freetype/freetype.git
GIT_TAG VER-2-13-3 GIT_SHALLOW TRUE GIT_SUBMODULES "")
FetchContent_MakeAvailable(freetype)
if(NOT TARGET Freetype::Freetype)
add_library(Freetype::Freetype ALIAS freetype)
endif()
set(RMLUI_SAMPLES OFF CACHE BOOL "" FORCE)
set(RMLUI_LUA_BINDINGS OFF CACHE BOOL "" FORCE)
set(RMLUI_SVG_PLUGIN OFF CACHE BOOL "" FORCE)
set(RMLUI_LOTTIE_PLUGIN OFF CACHE BOOL "" FORCE)
FetchContent_Declare(rmlui
GIT_REPOSITORY https://github.com/mikke89/RmlUi.git
GIT_TAG 6.3 GIT_SHALLOW TRUE)
FetchContent_MakeAvailable(rmlui)
add_library(bmh_rmlui STATIC
${rmlui_SOURCE_DIR}/Backends/RmlUi_Platform_SDL.cpp
${rmlui_SOURCE_DIR}/Backends/RmlUi_Renderer_GL3.cpp)
target_include_directories(bmh_rmlui PUBLIC ${rmlui_SOURCE_DIR}/Backends)
target_compile_definitions(bmh_rmlui PUBLIC RMLUI_SDL_VERSION_MAJOR=2 RMLUI_NUM_MSAA_SAMPLES=0)
target_link_libraries(bmh_rmlui PUBLIC RmlUi::Core ${BMH_SDL_TARGET} PRIVATE ${CMAKE_DL_LIBS})
# The background is project artwork, and the unmodified fonts come from the
# pinned dependency. All assets are located relative to the executable at runtime.
set(launcher_assets "${CMAKE_BINARY_DIR}/assets/launcher")
file(MAKE_DIRECTORY "${launcher_assets}")
foreach(asset IN ITEMS launcher.rml theme.rcss stadium.tga)
configure_file("${CMAKE_SOURCE_DIR}/assets/launcher/${asset}" "${launcher_assets}/${asset}" COPYONLY)
endforeach()
foreach(weight IN ITEMS Regular Bold)
configure_file("${rmlui_SOURCE_DIR}/Samples/assets/LatoLatin-${weight}.ttf"
"${launcher_assets}/LatoLatin-${weight}.ttf" COPYONLY)
endforeach()
install(DIRECTORY "${launcher_assets}/" DESTINATION assets/launcher COMPONENT Runtime)