NavigatorGamepad.cpp [plain text]
#include "config.h"
#include "NavigatorGamepad.h"
#if ENABLE(GAMEPAD)
#include "Gamepad.h"
#include "GamepadManager.h"
#include "GamepadProvider.h"
#include "Navigator.h"
#include "PlatformGamepad.h"
namespace WebCore {
NavigatorGamepad::NavigatorGamepad()
{
GamepadManager::singleton().registerNavigator(this);
}
NavigatorGamepad::~NavigatorGamepad()
{
GamepadManager::singleton().unregisterNavigator(this);
}
const char* NavigatorGamepad::supplementName()
{
return "NavigatorGamepad";
}
NavigatorGamepad* NavigatorGamepad::from(Navigator* navigator)
{
NavigatorGamepad* supplement = static_cast<NavigatorGamepad*>(Supplement<Navigator>::from(navigator, supplementName()));
if (!supplement) {
auto newSupplement = makeUnique<NavigatorGamepad>();
supplement = newSupplement.get();
provideTo(navigator, supplementName(), WTFMove(newSupplement));
}
return supplement;
}
Ref<Gamepad> NavigatorGamepad::gamepadFromPlatformGamepad(PlatformGamepad& platformGamepad)
{
unsigned index = platformGamepad.index();
if (index >= m_gamepads.size() || !m_gamepads[index])
return Gamepad::create(platformGamepad);
return *m_gamepads[index];
}
const Vector<RefPtr<Gamepad>>& NavigatorGamepad::getGamepads(Navigator& navigator)
{
return NavigatorGamepad::from(&navigator)->gamepads();
}
const Vector<RefPtr<Gamepad>>& NavigatorGamepad::gamepads()
{
if (m_gamepads.isEmpty())
return m_gamepads;
const Vector<PlatformGamepad*>& platformGamepads = GamepadProvider::singleton().platformGamepads();
for (unsigned i = 0; i < platformGamepads.size(); ++i) {
if (!platformGamepads[i]) {
ASSERT(!m_gamepads[i]);
continue;
}
ASSERT(m_gamepads[i]);
m_gamepads[i]->updateFromPlatformGamepad(*platformGamepads[i]);
}
return m_gamepads;
}
void NavigatorGamepad::gamepadsBecameVisible()
{
const Vector<PlatformGamepad*>& platformGamepads = GamepadProvider::singleton().platformGamepads();
m_gamepads.resize(platformGamepads.size());
for (unsigned i = 0; i < platformGamepads.size(); ++i) {
if (!platformGamepads[i])
continue;
m_gamepads[i] = Gamepad::create(*platformGamepads[i]);
}
}
void NavigatorGamepad::gamepadConnected(PlatformGamepad& platformGamepad)
{
if (m_gamepads.isEmpty()) {
gamepadsBecameVisible();
return;
}
unsigned index = platformGamepad.index();
ASSERT(GamepadProvider::singleton().platformGamepads()[index] == &platformGamepad);
ASSERT(index <= m_gamepads.size());
if (index < m_gamepads.size())
m_gamepads[index] = Gamepad::create(platformGamepad);
else if (index == m_gamepads.size())
m_gamepads.append(Gamepad::create(platformGamepad));
}
void NavigatorGamepad::gamepadDisconnected(PlatformGamepad& platformGamepad)
{
if (!m_gamepads.size())
return;
ASSERT(platformGamepad.index() < m_gamepads.size());
ASSERT(m_gamepads[platformGamepad.index()]);
m_gamepads[platformGamepad.index()] = nullptr;
}
}
#endif // ENABLE(GAMEPAD)