fix(gamepad): gamepads no longer crash BikeControl on Windows; update to gamepads 0.1.13

The Store health report lists access violations in gamepads_windows_plugin.dll.
The vendored plugin shared its pad list between GameInput's callback thread,
one detached reader thread per pad and the platform thread without a lock:
listGamepads (polled every 3 s) could read a pad that a disconnect had just
freed, and on shutdown the readers kept calling into the deleted plugin.

- Pads are shared_ptr-owned under a mutex; listGamepads returns copies.
- Reader threads are joined when their pad disconnects and on shutdown.
- Events are posted to a message-only window and sent from the platform
  thread, the only thread a channel may be used from.

Also moves to gamepads 0.1.13: the vendored Windows plugin takes 0.3.2's
connection events, vendorId/productId and rumble (on the GameInput v2 API it
already uses), and the vendored darwin plugin now also serves iOS, which
0.1.12 moved from gamepads_ios to gamepads_darwin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jonas.bark@gmx.de
2026-10-23 17:19:26 +02:00
parent b4d94fac40
commit c430d9e04d
8 changed files with 501 additions and 216 deletions

View File

@@ -5,8 +5,8 @@ publish_to: none
homepage: https://github.com/flame-engine/gamepads
repository: https://github.com/flame-engine/gamepads/tree/main/packages/gamepads_darwin
# Vendored from pub.dev gamepads_darwin 0.1.4, macOS only (iOS stays on
# gamepads_ios). BikeControl changes:
# Vendored from pub.dev gamepads_darwin 0.1.4, which gamepads 0.1.12+ uses on
# both iOS and macOS. BikeControl changes (macOS only, iOS is upstream):
# - GCController.shouldMonitorBackgroundEvents, so gamepads keep working while
# another app (Zwift, MyWhoosh, ...) has focus.
# - Generic HID pads that the GameController framework doesn't support are read
@@ -17,6 +17,9 @@ flutter:
plugin:
implements: gamepads
platforms:
ios:
pluginClass: GamepadsDarwinPlugin
sharedDarwinSource: true
macos:
pluginClass: GamepadsDarwinPlugin
sharedDarwinSource: true
@@ -28,4 +31,4 @@ environment:
dependencies:
flutter:
sdk: flutter
gamepads_platform_interface: ^0.1.3
gamepads_platform_interface: ^0.1.4

View File

@@ -1,15 +1,19 @@
name: gamepads_windows
description: Windows implementation of gamepads, a Flutter plugin to handle gamepad input across multiple platforms.
version: 0.3.0+1
version: 0.3.2
publish_to: none
homepage: https://github.com/flame-engine/gamepads
repository: https://github.com/flame-engine/gamepads/tree/main/packages/gamepads_windows
# Vendored from pub.dev gamepads_windows 0.3.0+1. BikeControl change: uses
# the GameInput v2 API (Microsoft.GameInput 4.0.300 NuGet, in
# windows/gameinput/) with background input enabled, so gamepads keep working
# while another app (Zwift, MyWhoosh, ...) has focus. The Windows SDK v0 API
# only delivers input to the foreground app.
# Vendored from pub.dev gamepads_windows 0.3.2 (rumble, connection events,
# vendorId/productId). BikeControl changes:
# - Uses the GameInput v2 API (Microsoft.GameInput 4.0.300 NuGet, in
# windows/gameinput/) with background input enabled, so gamepads keep
# working while another app (Zwift, MyWhoosh, ...) has focus. The Windows
# SDK v0 API only delivers input to the foreground app.
# - Thread safety: the device list is locked, reader threads are joined
# before their pad is freed and on shutdown, and every channel call is
# marshalled to the platform thread.
flutter:
plugin:
@@ -25,4 +29,4 @@ environment:
dependencies:
flutter:
sdk: flutter
gamepads_platform_interface: ^0.1.3
gamepads_platform_interface: ^0.1.4

View File

@@ -1,25 +1,19 @@
#include <algorithm>
#include <cmath>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <memory>
#include <ppl.h>
#include <sstream>
#include <vector>
#include <concrt.h>
#include <winerror.h>
#include "gamepad.h"
#include "utils.h"
#include <iomanip>
#include <sstream>
// Exported by gameinput/GameInput.cpp. It loads the newest GameInput runtime
// available: the GameInputRedist.dll bundled next to the exe, or a newer one
// installed system-wide.
STDAPI GameInputInitialize(_In_ REFIID riid, _COM_Outptr_ LPVOID* ppv);
Gamepads gamepads;
static IGameInput* g_gameInput = nullptr;
std::string get_button_name(uint32_t button) {
switch (button) {
case GameInputGamepadMenu:
@@ -118,23 +112,41 @@ bool are_states_different(const GameInputGamepadState& a,
a.rightTrigger != b.rightTrigger || a.buttons != b.buttons;
}
void Gamepads::init() {
GamepadData::~GamepadData() {
if (device != nullptr) {
device->Release();
}
}
Gamepads::~Gamepads() {
stop();
}
void Gamepads::init(GamepadEventEmitter event_emitter,
GamepadConnectionEmitter connection_emitter) {
{
std::lock_guard<std::mutex> lock(emit_mutex_);
event_emitter_ = std::move(event_emitter);
connection_emitter_ = std::move(connection_emitter);
}
HRESULT hr = GameInputInitialize(IID_IGameInput,
reinterpret_cast<void**>(&g_gameInput));
if (FAILED(hr) || g_gameInput == nullptr) {
reinterpret_cast<void**>(&game_input_));
if (FAILED(hr) || game_input_ == nullptr) {
std::cerr << "GameInput init failed: 0x" << std::hex << hr << std::dec
<< std::endl;
g_gameInput = nullptr;
game_input_ = nullptr;
return;
}
// GameInput only delivers input to the foreground app by default, which
// makes a gamepad useless while the trainer app (Zwift, ...) has focus.
g_gameInput->SetFocusPolicy(GameInputEnableBackgroundInput);
game_input_->SetFocusPolicy(GameInputEnableBackgroundInput);
// Controller also covers generic HID pads that GameInput can't map to a
// gamepad (every gamepad is a controller too).
g_gameInput->RegisterDeviceCallback(
game_input_->RegisterDeviceCallback(
nullptr, // All devices
static_cast<GameInputKind>(GameInputKindGamepad | GameInputKindController),
GameInputDeviceConnected, GameInputAsyncEnumeration,
@@ -150,30 +162,133 @@ void Gamepads::init() {
self->on_gamepad_disconnected(device);
}
},
&this->deviceCallbackToken);
&device_callback_token_);
}
void Gamepads::stop() {
if (g_gameInput) {
g_gameInput->UnregisterCallback(this->deviceCallbackToken);
// Waits for a device callback that is already running, so none can add a
// gamepad after the list is taken below.
if (game_input_ != nullptr && device_callback_token_ != 0) {
game_input_->UnregisterCallback(device_callback_token_);
device_callback_token_ = 0;
}
{
std::lock_guard<std::mutex> lock(emit_mutex_);
event_emitter_ = nullptr;
connection_emitter_ = nullptr;
}
// Stop/cleanup threads
for (auto gp : this->gamepads) {
if (!gp->stop_thread) {
if (gp->alive) {
gp->stop_thread = true;
} else {
// Cleanup data of threads that exited due to error state.
delete gp;
}
std::list<std::shared_ptr<GamepadData>> stopping;
{
std::lock_guard<std::mutex> lock(gamepads_mutex_);
stopping.swap(gamepads_);
}
for (auto& gamepad : stopping) {
gamepad->stop_thread = true;
}
for (auto& gamepad : stopping) {
if (gamepad->thread.joinable()) {
gamepad->thread.join();
}
}
this->gamepads.clear();
stopping.clear();
if (game_input_ != nullptr) {
game_input_->Release();
game_input_ = nullptr;
}
}
std::list<GamepadData*> Gamepads::get_gamepads() {
return this->gamepads;
std::vector<GamepadInfo> Gamepads::get_gamepads() {
std::lock_guard<std::mutex> lock(gamepads_mutex_);
std::vector<GamepadInfo> list;
list.reserve(gamepads_.size());
for (const auto& gamepad : gamepads_) {
list.push_back(gamepad->info);
}
return list;
}
std::shared_ptr<GamepadData> Gamepads::find_gamepad(const std::string& id) {
std::lock_guard<std::mutex> lock(gamepads_mutex_);
for (const auto& gamepad : gamepads_) {
if (gamepad->info.id == id) {
return gamepad;
}
}
return nullptr;
}
std::shared_ptr<GamepadData> Gamepads::remove_gamepad(const std::string& id) {
std::lock_guard<std::mutex> lock(gamepads_mutex_);
for (auto it = gamepads_.begin(); it != gamepads_.end(); ++it) {
if ((*it)->info.id == id) {
auto gamepad = *it;
gamepads_.erase(it);
return gamepad;
}
}
return nullptr;
}
bool Gamepads::has_rumble(const std::string& id) {
const auto gamepad = find_gamepad(id);
return gamepad != nullptr && gamepad->supports_rumble;
}
bool Gamepads::set_rumble(const std::string& id,
double low,
double high,
int milliseconds) {
if (!(low >= 0 && low <= 1 && high >= 0 && high <= 1) || milliseconds < 0 ||
milliseconds > 30000) {
return false;
}
const auto gamepad = find_gamepad(id);
if (gamepad == nullptr || !gamepad->supports_rumble) {
return false;
}
const bool stop = milliseconds == 0 || (low == 0 && high == 0);
// Some GameInput runtimes dereference null rumble parameters: always pass
// an explicit state, all zero to stop.
GameInputRumbleParams params{};
if (!stop) {
params.lowFrequency = static_cast<float>(low);
params.highFrequency = static_cast<float>(high);
}
std::lock_guard<std::mutex> lock(gamepad->rumble_mutex);
gamepad->device->SetRumbleState(&params);
gamepad->rumble_active = !stop;
gamepad->rumble_until = std::chrono::steady_clock::now() +
std::chrono::milliseconds(milliseconds);
return true;
}
// GameInput has no timed rumble, so the reader thread, which wakes every few
// milliseconds anyway, turns the motors off once the effect has run out.
void Gamepads::expire_rumble(GamepadData* gamepad) {
std::lock_guard<std::mutex> lock(gamepad->rumble_mutex);
if (gamepad->rumble_active &&
(gamepad->stop_thread ||
std::chrono::steady_clock::now() >= gamepad->rumble_until)) {
const GameInputRumbleParams zero{};
gamepad->device->SetRumbleState(&zero);
gamepad->rumble_active = false;
}
}
void Gamepads::emit_event(const GamepadData* gamepad, const Event& event) {
std::lock_guard<std::mutex> lock(emit_mutex_);
if (event_emitter_) {
event_emitter_(gamepad->info, event);
}
}
void Gamepads::emit_connection(const GamepadInfo& gamepad, bool connected) {
std::lock_guard<std::mutex> lock(emit_mutex_);
if (connection_emitter_) {
connection_emitter_(gamepad, connected);
}
}
void Gamepads::on_gamepad_connected(IGameInputDevice* device) {
@@ -182,30 +297,39 @@ void Gamepads::on_gamepad_connected(IGameInputDevice* device) {
std::cerr << "Gamepad connected but failed to read info" << std::endl;
return;
}
auto gp = new GamepadData();
gp->id = AppLocalDeviceIdToString(info->deviceId);
gp->name = info->displayName != nullptr ? info->displayName : "";
gp->num_buttons = info->controllerButtonCount;
gp->stop_thread = false;
gp->alive = true;
gp->vendor_id = static_cast<int>(info->vendorId);
gp->product_id = static_cast<int>(info->productId);
auto gp = std::make_shared<GamepadData>();
gp->info.id = AppLocalDeviceIdToString(info->deviceId);
gp->info.name = info->displayName != nullptr ? info->displayName : "";
gp->info.vendor_id = static_cast<int>(info->vendorId);
gp->info.product_id = static_cast<int>(info->productId);
gp->is_gamepad = (info->supportedInput & GameInputKindGamepad) != 0;
this->gamepads.push_back(gp);
std::cout << "Gamepad connected: " << gp->id << " : " << gp->name
<< (gp->is_gamepad ? "" : " (generic controller)") << std::endl;
gp->supports_rumble =
(info->supportedRumbleMotors &
(GameInputRumbleLowFrequency | GameInputRumbleHighFrequency)) != 0;
// The reading thread outlives this callback; keep the device alive for it.
device->AddRef();
std::thread read_thread([this, gp, device]() {
if (gp->is_gamepad) {
this->read_gamepad(gp, device);
gp->device = device;
// A device that reconnects without a disconnect in between replaces its
// old entry instead of getting a second reader.
on_gamepad_disconnected(device);
std::cout << "Gamepad connected: " << gp->info.id << " : " << gp->info.name
<< (gp->is_gamepad ? "" : " (generic controller)") << std::endl;
GamepadData* raw = gp.get();
gp->thread = std::thread([this, raw]() {
if (raw->is_gamepad) {
this->read_gamepad(raw);
} else {
this->read_controller(gp, device);
this->read_controller(raw);
}
});
read_thread.detach();
{
std::lock_guard<std::mutex> lock(gamepads_mutex_);
gamepads_.push_back(gp);
}
emit_connection(gp->info, true);
}
void Gamepads::on_gamepad_disconnected(IGameInputDevice* device) {
@@ -214,37 +338,31 @@ void Gamepads::on_gamepad_disconnected(IGameInputDevice* device) {
std::cerr << "Gamepad disconnected but failed to read info" << std::endl;
return;
}
std::string removeId = AppLocalDeviceIdToString(info->deviceId);
std::cout << "Gamepad disconnected: " << removeId << std::endl;
GamepadData* removeGp = nullptr;
for (auto gp : this->gamepads) {
if (gp->id == removeId) {
gp->stop_thread = true;
removeGp = gp;
break;
}
const auto gamepad = remove_gamepad(AppLocalDeviceIdToString(info->deviceId));
if (gamepad == nullptr) {
return;
}
// Remove the gamepad from list. The thread will free up memory.
if (removeGp != nullptr) {
this->gamepads.remove(removeGp);
std::cout << "Gamepad disconnected: " << gamepad->info.id << std::endl;
// listGamepads no longer returns it; stop the reader before it is freed.
gamepad->stop_thread = true;
if (gamepad->thread.joinable()) {
gamepad->thread.join();
}
emit_connection(gamepad->info, false);
}
void Gamepads::read_gamepad(GamepadData* gamepad, IGameInputDevice* device) {
void Gamepads::read_gamepad(GamepadData* gamepad) {
GameInputGamepadState previous_state = {
GameInputGamepadNone, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
while (!gamepad->stop_thread && g_gameInput != nullptr) {
while (!gamepad->stop_thread) {
IGameInputReading* reading = nullptr;
if (SUCCEEDED(g_gameInput->GetCurrentReading(GameInputKindGamepad, device,
&reading))) {
if (SUCCEEDED(game_input_->GetCurrentReading(GameInputKindGamepad,
gamepad->device, &reading))) {
GameInputGamepadState state;
if (reading->GetGamepadState(&state)) {
if (are_states_different(previous_state, state)) {
auto events = diff_states(previous_state, state);
for (auto event : events) {
if (event_emitter.has_value()) {
(*event_emitter)(gamepad, event);
}
for (const auto& event : diff_states(previous_state, state)) {
emit_event(gamepad, event);
}
}
previous_state = state;
@@ -252,10 +370,10 @@ void Gamepads::read_gamepad(GamepadData* gamepad, IGameInputDevice* device) {
reading->Release();
}
expire_rumble(gamepad);
Sleep(8);
}
on_thread_exit(gamepad, device);
expire_rumble(gamepad);
}
// Directions (up, right, down, left) a hat switch position presses.
@@ -276,17 +394,16 @@ static const char* kDpadKeys[] = {"dpadUp", "dpadRight", "dpadDown",
// Generic controllers have no fixed layout, so they emit raw keys:
// "button-N", "axis-N" (-1.0 to 1.0) and, for the first hat switch, the
// regular d-pad keys. Further hat switches emit "switchN-dpadUp" etc.
void Gamepads::read_controller(GamepadData* gamepad,
IGameInputDevice* device) {
void Gamepads::read_controller(GamepadData* gamepad) {
std::vector<bool> previous_buttons;
std::vector<float> previous_axes;
std::vector<GameInputSwitchPosition> previous_switches;
bool has_previous = false;
while (!gamepad->stop_thread && g_gameInput != nullptr) {
while (!gamepad->stop_thread) {
IGameInputReading* reading = nullptr;
if (SUCCEEDED(g_gameInput->GetCurrentReading(GameInputKindController,
device, &reading))) {
if (SUCCEEDED(game_input_->GetCurrentReading(GameInputKindController,
gamepad->device, &reading))) {
uint32_t button_count = reading->GetControllerButtonCount();
std::unique_ptr<bool[]> button_state(new bool[button_count]());
reading->GetControllerButtonState(button_count, button_state.get());
@@ -349,30 +466,14 @@ void Gamepads::read_controller(GamepadData* gamepad,
previous_buttons = buttons;
previous_switches = switches;
for (auto& event : events) {
if (event_emitter.has_value()) {
(*event_emitter)(gamepad, event);
}
for (const auto& event : events) {
emit_event(gamepad, event);
}
}
}
expire_rumble(gamepad);
Sleep(8);
}
on_thread_exit(gamepad, device);
}
void Gamepads::on_thread_exit(GamepadData* gamepad, IGameInputDevice* device) {
device->Release();
if (gamepad->stop_thread) {
std::cout << "Gamepad thread exit (via signal) " << gamepad->id
<< std::endl;
delete gamepad;
} else {
std::cout << "Gamepad thread exit (due to error state) " << gamepad->id
<< std::endl;
gamepad->alive = false;
}
expire_rumble(gamepad);
}

View File

@@ -1,30 +1,22 @@
#pragma once
#include <wtypes.h>
#include <windows.h>
#include <atomic>
#include <chrono>
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <optional>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
// GameInput v2 API (Microsoft.GameInput NuGet): v0 from the Windows SDK has
// no way to receive input while another app is in the foreground.
#include "gameinput/GameInput.h"
using namespace GameInput::v2;
struct GamepadData {
std::string id;
std::string name;
int num_buttons;
bool stop_thread;
bool alive;
int vendor_id;
int product_id;
// False for generic (DirectInput/HID) controllers GameInput has no gamepad
// mapping for. They are read as raw buttons, axes and switches.
bool is_gamepad;
};
struct Event {
int time;
std::string type;
@@ -32,24 +24,79 @@ struct Event {
double value;
};
class Gamepads {
private:
std::list<GamepadData*> gamepads;
// What listGamepads reports. A copy, so it stays valid after the pad is gone.
struct GamepadInfo {
std::string id;
std::string name;
int vendor_id;
int product_id;
};
GameInputCallbackToken deviceCallbackToken = 0;
void read_gamepad(GamepadData* gamepad, IGameInputDevice* device);
void read_controller(GamepadData* gamepad, IGameInputDevice* device);
void on_thread_exit(GamepadData* gamepad, IGameInputDevice* device);
// One connected device and the thread polling it. Owned by Gamepads; the
// reader thread is always joined before this is destroyed.
struct GamepadData {
GamepadInfo info;
// False for generic (DirectInput/HID) controllers GameInput has no gamepad
// mapping for. They are read as raw buttons, axes and switches.
bool is_gamepad = false;
bool supports_rumble = false;
IGameInputDevice* device = nullptr; // One reference, released on destroy.
std::atomic<bool> stop_thread{false};
std::thread thread;
// Rumble is set from the platform thread and expired by the reader thread.
std::mutex rumble_mutex;
bool rumble_active = false;
std::chrono::steady_clock::time_point rumble_until;
~GamepadData();
};
// Both run on GameInput's callback thread or a reader thread, never the
// platform thread: they must not block and must not call into Flutter.
using GamepadEventEmitter =
std::function<void(const GamepadInfo& gamepad, const Event& event)>;
using GamepadConnectionEmitter =
std::function<void(const GamepadInfo& gamepad, bool connected)>;
class Gamepads {
public:
~Gamepads();
void init(GamepadEventEmitter event_emitter,
GamepadConnectionEmitter connection_emitter);
// Returns once no callback or reader thread is running and none will start.
void stop();
std::vector<GamepadInfo> get_gamepads();
bool has_rumble(const std::string& id);
// Replaces the current effect; zero intensities or duration stop it.
bool set_rumble(const std::string& id,
double low,
double high,
int milliseconds);
private:
IGameInput* game_input_ = nullptr;
GameInputCallbackToken device_callback_token_ = 0;
std::mutex gamepads_mutex_;
std::list<std::shared_ptr<GamepadData>> gamepads_;
// Held while emitting, so stop() can clear the emitters and know no event
// is still on its way out.
std::mutex emit_mutex_;
GamepadEventEmitter event_emitter_;
GamepadConnectionEmitter connection_emitter_;
void on_gamepad_connected(IGameInputDevice* device);
void on_gamepad_disconnected(IGameInputDevice* device);
std::shared_ptr<GamepadData> remove_gamepad(const std::string& id);
std::shared_ptr<GamepadData> find_gamepad(const std::string& id);
public:
std::optional<std::function<void(GamepadData* gamepad, const Event& event)>>
event_emitter;
void init();
void stop();
std::list<GamepadData*> get_gamepads();
void read_gamepad(GamepadData* gamepad);
void read_controller(GamepadData* gamepad);
void expire_rumble(GamepadData* gamepad);
void emit_event(const GamepadData* gamepad, const Event& event);
void emit_connection(const GamepadInfo& gamepad, bool connected);
};
extern Gamepads gamepads;

View File

@@ -1,7 +1,5 @@
#include "gamepads_windows_plugin.h"
#include <dbt.h>
#include <hidclass.h>
#include <windows.h>
#include <flutter/encodable_value.h>
@@ -10,75 +8,205 @@
#include <flutter/standard_method_codec.h>
#include <memory>
#include <sstream>
#include <optional>
namespace gamepads_windows {
namespace {
constexpr wchar_t kMessageWindowClass[] = L"GamepadsWindowsPluginMessageWindow";
constexpr UINT kChannelMessage = WM_APP + 1;
// A channel call posted from another thread, owned by the message queue
// until the platform thread sends it.
struct PendingCall {
const char* method;
flutter::EncodableMap arguments;
};
const flutter::EncodableValue* FindArgument(const flutter::EncodableMap& args,
const char* key) {
const auto it = args.find(flutter::EncodableValue(key));
return it == args.end() ? nullptr : &it->second;
}
std::optional<double> DoubleArgument(const flutter::EncodableMap& args,
const char* key) {
const auto* value = FindArgument(args, key);
if (value != nullptr && std::holds_alternative<double>(*value)) {
return std::get<double>(*value);
}
return std::nullopt;
}
std::optional<int64_t> IntArgument(const flutter::EncodableMap& args,
const char* key) {
const auto* value = FindArgument(args, key);
if (value == nullptr) {
return std::nullopt;
}
if (std::holds_alternative<int32_t>(*value)) {
return std::get<int32_t>(*value);
}
if (std::holds_alternative<int64_t>(*value)) {
return std::get<int64_t>(*value);
}
return std::nullopt;
}
} // namespace
void GamepadsWindowsPlugin::RegisterWithRegistrar(
flutter::PluginRegistrarWindows* registrar) {
channel = std::make_unique<flutter::MethodChannel<flutter::EncodableValue>>(
registrar->messenger(), "xyz.luan/gamepads",
&flutter::StandardMethodCodec::GetInstance());
auto plugin = std::make_unique<GamepadsWindowsPlugin>(registrar);
channel->SetMethodCallHandler(
[plugin_pointer = plugin.get()](const auto& call, auto result) {
plugin_pointer->HandleMethodCall(call, std::move(result));
});
registrar->AddPlugin(std::move(plugin));
registrar->AddPlugin(std::make_unique<GamepadsWindowsPlugin>(registrar));
}
GamepadsWindowsPlugin::GamepadsWindowsPlugin(
flutter::PluginRegistrarWindows* registrar)
: registrar(registrar) {
gamepads.event_emitter = [&](GamepadData* gamepad, const Event& event) {
this->emit_gamepad_event(gamepad, event);
};
gamepads.init();
flutter::PluginRegistrarWindows* registrar) {
channel_ = std::make_unique<flutter::MethodChannel<flutter::EncodableValue>>(
registrar->messenger(), "xyz.luan/gamepads",
&flutter::StandardMethodCodec::GetInstance());
channel_->SetMethodCallHandler([this](const auto& call, auto result) {
HandleMethodCall(call, std::move(result));
});
WNDCLASSEXW window_class{};
window_class.cbSize = sizeof(window_class);
window_class.lpfnWndProc = MessageWindowProc;
window_class.hInstance = GetModuleHandle(nullptr);
window_class.lpszClassName = kMessageWindowClass;
RegisterClassExW(&window_class); // Fails harmlessly if already registered.
message_window_ =
CreateWindowExW(0, kMessageWindowClass, L"", 0, 0, 0, 0, 0, HWND_MESSAGE,
nullptr, GetModuleHandle(nullptr), nullptr);
if (message_window_ != nullptr) {
SetWindowLongPtr(message_window_, GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(this));
}
gamepads_.init(
[this](const GamepadInfo& gamepad, const Event& event) {
flutter::EncodableMap map;
map[flutter::EncodableValue("gamepadId")] =
flutter::EncodableValue(gamepad.id);
map[flutter::EncodableValue("time")] =
flutter::EncodableValue(event.time);
map[flutter::EncodableValue("type")] =
flutter::EncodableValue(event.type);
map[flutter::EncodableValue("key")] =
flutter::EncodableValue(event.key);
map[flutter::EncodableValue("value")] =
flutter::EncodableValue(event.value);
map[flutter::EncodableValue("vendorId")] =
flutter::EncodableValue(gamepad.vendor_id);
map[flutter::EncodableValue("productId")] =
flutter::EncodableValue(gamepad.product_id);
PostToChannel("onGamepadEvent", std::move(map));
},
[this](const GamepadInfo& gamepad, bool connected) {
flutter::EncodableMap map;
map[flutter::EncodableValue("gamepadId")] =
flutter::EncodableValue(gamepad.id);
map[flutter::EncodableValue("name")] =
flutter::EncodableValue(gamepad.name);
map[flutter::EncodableValue("type")] =
flutter::EncodableValue(connected ? "connected" : "disconnected");
PostToChannel("onGamepadConnectionEvent", std::move(map));
});
}
GamepadsWindowsPlugin::~GamepadsWindowsPlugin() {
gamepads.stop();
// Joins every GameInput callback and reader thread: nothing posts after it.
gamepads_.stop();
channel_->SetMethodCallHandler(nullptr);
if (message_window_ != nullptr) {
SetWindowLongPtr(message_window_, GWLP_USERDATA, 0);
MSG message;
while (PeekMessage(&message, message_window_, kChannelMessage,
kChannelMessage, PM_REMOVE)) {
delete reinterpret_cast<PendingCall*>(message.lParam);
}
DestroyWindow(message_window_);
message_window_ = nullptr;
}
}
void GamepadsWindowsPlugin::PostToChannel(const char* method,
flutter::EncodableMap arguments) {
if (message_window_ == nullptr) {
return;
}
auto* call = new PendingCall{method, std::move(arguments)};
if (!PostMessage(message_window_, kChannelMessage, 0,
reinterpret_cast<LPARAM>(call))) {
delete call;
}
}
LRESULT CALLBACK GamepadsWindowsPlugin::MessageWindowProc(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) {
if (message == kChannelMessage) {
std::unique_ptr<PendingCall> call(reinterpret_cast<PendingCall*>(lparam));
auto* plugin = reinterpret_cast<GamepadsWindowsPlugin*>(
GetWindowLongPtr(hwnd, GWLP_USERDATA));
if (plugin != nullptr) {
plugin->channel_->InvokeMethod(
call->method, std::make_unique<flutter::EncodableValue>(
std::move(call->arguments)));
}
return 0;
}
return DefWindowProc(hwnd, message, wparam, lparam);
}
void GamepadsWindowsPlugin::HandleMethodCall(
const flutter::MethodCall<flutter::EncodableValue>& method_call,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result) {
if (method_call.method_name().compare("listGamepads") == 0) {
const auto& method = method_call.method_name();
if (method == "listGamepads") {
flutter::EncodableList list;
for (auto gamepad : gamepads.get_gamepads()) {
for (const auto& gamepad : gamepads_.get_gamepads()) {
flutter::EncodableMap map;
map[flutter::EncodableValue("id")] = flutter::EncodableValue(gamepad->id);
map[flutter::EncodableValue("id")] = flutter::EncodableValue(gamepad.id);
map[flutter::EncodableValue("name")] =
flutter::EncodableValue(gamepad->name);
flutter::EncodableValue(gamepad.name);
map[flutter::EncodableValue("vendorId")] =
flutter::EncodableValue(gamepad.vendor_id);
map[flutter::EncodableValue("productId")] =
flutter::EncodableValue(gamepad.product_id);
list.push_back(flutter::EncodableValue(map));
}
result->Success(flutter::EncodableValue(list));
} else {
result->NotImplemented();
return;
}
if (method == "hasRumble" || method == "rumble" || method == "stopRumble") {
const auto* args =
std::get_if<flutter::EncodableMap>(method_call.arguments());
const auto* id = args == nullptr ? nullptr : FindArgument(*args, "gamepadId");
if (id == nullptr || !std::holds_alternative<std::string>(*id)) {
result->Success(flutter::EncodableValue(false));
return;
}
const auto& gamepad_id = std::get<std::string>(*id);
bool accepted = false;
if (method == "hasRumble") {
accepted = gamepads_.has_rumble(gamepad_id);
} else if (method == "stopRumble") {
accepted = gamepads_.set_rumble(gamepad_id, 0, 0, 0);
} else {
const auto low = DoubleArgument(*args, "lowFrequency");
const auto high = DoubleArgument(*args, "highFrequency");
const auto duration = IntArgument(*args, "durationMillis");
if (low && high && duration && *duration >= 0 && *duration <= 30000) {
accepted = gamepads_.set_rumble(gamepad_id, *low, *high,
static_cast<int>(*duration));
}
}
result->Success(flutter::EncodableValue(accepted));
return;
}
result->NotImplemented();
}
void GamepadsWindowsPlugin::emit_gamepad_event(GamepadData* gamepad,
const Event& event) {
auto _channel = this->channel.get();
if (_channel) {
flutter::EncodableMap map;
map[flutter::EncodableValue("gamepadId")] =
flutter::EncodableValue(gamepad->id);
map[flutter::EncodableValue("time")] = flutter::EncodableValue(event.time);
map[flutter::EncodableValue("type")] = flutter::EncodableValue(event.type);
map[flutter::EncodableValue("key")] = flutter::EncodableValue(event.key);
map[flutter::EncodableValue("value")] =
flutter::EncodableValue(event.value);
map[flutter::EncodableValue("vendorId")] =
flutter::EncodableValue(gamepad->vendor_id);
map[flutter::EncodableValue("productId")] =
flutter::EncodableValue(gamepad->product_id);
_channel->InvokeMethod("onGamepadEvent",
std::make_unique<flutter::EncodableValue>(
flutter::EncodableValue(map)));
}
}
} // namespace gamepads_windows

View File

@@ -1,6 +1,7 @@
#ifndef FLUTTER_PLUGIN_GAMEPADS_WINDOWS_PLUGIN_H_
#define FLUTTER_PLUGIN_GAMEPADS_WINDOWS_PLUGIN_H_
#include <flutter/encodable_value.h>
#include <flutter/method_channel.h>
#include <flutter/plugin_registrar_windows.h>
@@ -23,15 +24,22 @@ class GamepadsWindowsPlugin : public flutter::Plugin {
GamepadsWindowsPlugin& operator=(const GamepadsWindowsPlugin&) = delete;
private:
flutter::PluginRegistrarWindows* registrar;
static inline std::unique_ptr<flutter::MethodChannel<flutter::EncodableValue>>
channel{};
std::unique_ptr<flutter::MethodChannel<flutter::EncodableValue>> channel_;
// Message-only window on the platform thread. GameInput callbacks and the
// reader threads post their events here, since the channel may only be
// used from the platform thread.
HWND message_window_ = nullptr;
Gamepads gamepads_;
void HandleMethodCall(
const flutter::MethodCall<flutter::EncodableValue>& method_call,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
void emit_gamepad_event(GamepadData* gamepad, const Event& event);
void PostToChannel(const char* method, flutter::EncodableMap arguments);
static LRESULT CALLBACK MessageWindowProc(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam);
};
} // namespace gamepads_windows

View File

@@ -689,18 +689,18 @@ packages:
dependency: "direct main"
description:
name: gamepads
sha256: "8134c967c29496cbc20e73c88b31c6d11765e846b8e465c52b436fe6e88339ce"
sha256: ed72d5f3698fc2468e8444012823587379bbbb09e70c9063e332023aa65bdebb
url: "https://pub.dev"
source: hosted
version: "0.1.11"
version: "0.1.13"
gamepads_android:
dependency: transitive
description:
name: gamepads_android
sha256: f3a600e1212374771bdd47206088940a36fb75791b3c4223eccfa487dfd1ed0f
sha256: c50ccad8cd5dab70b9a1eda11862f2756da2a82005b9b580fbb0f4b2c0fbd3a2
url: "https://pub.dev"
source: hosted
version: "0.1.9"
version: "0.1.10"
gamepads_darwin:
dependency: "direct overridden"
description:
@@ -708,45 +708,37 @@ packages:
relative: true
source: path
version: "0.1.4"
gamepads_ios:
dependency: transitive
description:
name: gamepads_ios
sha256: "9a65f16797c7479d2bc6d7967d45e8b2448c6302b128fcf3231460f839021a37"
url: "https://pub.dev"
source: hosted
version: "0.1.4"
gamepads_linux:
dependency: transitive
description:
name: gamepads_linux
sha256: "80bf70df6da6185926e6d8b2feb98e725e6fe99290afafaea91dba471e8c1c1e"
sha256: "7177a3a24aeb41f7bcb273621a0cc8f46b97e198d1d624c04d43af74faca84a0"
url: "https://pub.dev"
source: hosted
version: "0.1.2"
version: "0.1.4"
gamepads_platform_interface:
dependency: transitive
dependency: "direct main"
description:
name: gamepads_platform_interface
sha256: "9ddb3b61c780284a17739d759929d2e32b912d12d9145ee493ffe2b43fc6256a"
sha256: "51b243f64c3d02900ac37eef0ed0177710ef5b0a1265dbf46bb93ca0f4200f17"
url: "https://pub.dev"
source: hosted
version: "0.1.3"
version: "0.1.4"
gamepads_web:
dependency: transitive
description:
name: gamepads_web
sha256: "4f044a6003b34a8d5c5854924fbbfd64b6653bcb49169cf2aca26938f812672e"
sha256: "5ceaa635cdba536f1ee2b650227c39f5e4a8b1ec6588b00ea0ea6e7291d8e62e"
url: "https://pub.dev"
source: hosted
version: "0.1.2"
version: "0.1.3"
gamepads_windows:
dependency: "direct overridden"
description:
path: "packages/gamepads_windows"
relative: true
source: path
version: "0.3.0+1"
version: "0.3.2"
gap:
dependency: transitive
description:
@@ -1979,10 +1971,11 @@ packages:
universal_ble:
dependency: "direct main"
description:
name: universal_ble
sha256: "6aa8d5a1de5ac8e41133d44b9c35f92bf87079188a0ee9a23a68a97f9068f4a0"
url: "https://pub.dev"
source: hosted
path: "."
ref: c0a1031dc529de93fed7e19cf5691769cc91e4db
resolved-ref: c0a1031dc529de93fed7e19cf5691769cc91e4db
url: "https://github.com/jonasbark/universal_ble.git"
source: git
version: "3.1.0"
url_launcher:
dependency: "direct main"

View File

@@ -16,7 +16,8 @@ dependencies:
# fork to allow iOS background BLE connections
universal_ble: ^3.1.0
gamepads: ^0.1.10+1
gamepads: ^0.1.13
gamepads_platform_interface: ^0.1.4
lottie: ^3.3.2
d4rt: ^0.2.2