summaryrefslogtreecommitdiffhomepage
path: root/opentrack/win32-joystick-shortcuts.hpp
blob: 530545dc98620e78b89b35a99dade8fc731a6aa6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#pragma once

#include <cstring>
#include <memory>
#include <vector>
#include <functional>
#include <algorithm>
#ifndef DIRECTINPUT_VERSION
#   define DIRECTINPUT_VERSION 0x800
#endif
#include <dinput.h>
#include <windows.h>
#include "opentrack-compat/timer.hpp"
#include <QString>
#include <QDebug>

struct win32_joy_ctx
{
    using fn = std::function<void(const QString& guid, int btn, bool held)>;
    
    void poll(fn f)
    {
        refresh(false);
        for (int i = joys.size() - 1; i >= 0; i--)
        {
            if (!joys[i]->poll(f))
                joys.erase(joys.begin() + i);
        }
    }
    
    struct joy
    {
        LPDIRECTINPUTDEVICE8 joy_handle;
        QString guid;
        bool pressed[128];
        
        joy(LPDIRECTINPUTDEVICE8 handle, const QString& guid) : joy_handle(handle), guid(guid)
        {
            qDebug() << "got joy" << guid;
            for (int i = 0; i < 128; i++)
                pressed[i] = false;
            poll([&](const QString&, int idx, bool held) -> void { pressed[idx] = held; });
        }
        
        ~joy()
        {
            qDebug() << "nix joy" << guid;
            release();
        }
        
        void release()
        {
            if (joy_handle)
            {
                (void) joy_handle->Unacquire();
                joy_handle->Release();
                joy_handle = nullptr;
            }
        }
        
        bool poll(fn f)
        {
            HRESULT hr;
            bool ok = false;
            
            for (int i = 0; i < 5; i++)
            {
                if (!FAILED(joy_handle->Poll()))
                {
                    ok = true;
                    break;
                }
                if ((hr = joy_handle->Acquire()) != DI_OK)
                    continue;
                else
                    ok = true;
                break;
            }
            
            if (!ok)
            {
                qDebug() << "joy acquire failed" << guid << hr;
                return false;
            }
            
            DIJOYSTATE2 js;
            memset(&js, 0, sizeof(js));
            
            if (FAILED(hr = joy_handle->GetDeviceState(sizeof(js), &js)))
            {
                qDebug() << "joy get state failed" << guid << hr;
                return false;
            }
            
            for (int i = 0; i < 128; i++)
            {
                const bool state = !!(js.rgbButtons[i] & 0x80);
                if (state != pressed[i])
                {
                    f(guid, i, state);
                    qDebug() << "btn" << guid << i << state;
                }
                pressed[i] = state;
            }
            
            return true;
        }
    };
    
    static QString guid_to_string(const GUID guid)
    {
        char buf[40] = {0};
        wchar_t szGuidW[40] = {0};
        
        StringFromGUID2(guid, szGuidW, 40);
        WideCharToMultiByte(0, 0, szGuidW, -1, buf, 40, NULL, NULL);
        
        return QString(buf);
    }
    
    win32_joy_ctx() : dinput_handle(nullptr)
    {
        (void) CoInitialize(nullptr);
        
        HRESULT hr;
        
        if (FAILED(hr = DirectInput8Create(GetModuleHandle(nullptr),
                                           DIRECTINPUT_VERSION,
                                           IID_IDirectInput8,
                                           (void**) &dinput_handle,
                                           nullptr)))
            goto fail;
        
        refresh(true);
        
        return;
fail:
        qDebug() << "dinput8 failed for shortcuts" << hr;
        
        release();
    }
    
    ~win32_joy_ctx()
    {
        release();
    }
    
    void release()
    {
        joys = std::vector<std::shared_ptr<joy>>();
        if (dinput_handle)
        {
            dinput_handle->Release();
            dinput_handle = nullptr;
        }
    }
    
    void refresh(bool first)
    {
        if (!dinput_handle)
            return;
        
        if (!first)
        {
            if (timer_joylist.elapsed_ms() < joylist_refresh_ms)
                return;
            timer_joylist.start();
        }
        
        enum_state st(dinput_handle, joys);
    }
    
    struct enum_state
    {
        std::vector<std::shared_ptr<joy>>& joys;
        std::vector<QString> all;
        LPDIRECTINPUT8 dinput_handle;
        
        enum_state(LPDIRECTINPUT8 di, std::vector<std::shared_ptr<joy>>& joys) : joys(joys), dinput_handle(di)
        {
            HRESULT hr;
            
            if(FAILED(hr = dinput_handle->EnumDevices(DI8DEVCLASS_GAMECTRL,
                                                      EnumJoysticksCallback,
                                                      this,
                                                      DIEDFL_ATTACHEDONLY)))
            {
                qDebug() << "failed enum joysticks" << hr;
                return;
            }
            
            for (int i = joys.size() - 1; i >= 0; i--)
            {
                const auto& guid = joys[i]->guid;
                if (std::find_if(all.cbegin(), all.cend(), [&](const QString& guid2) -> bool { return guid == guid2; }) == all.cend())
                    joys.erase(joys.begin() + i);
            }
        }
        
        static BOOL CALLBACK EnumJoysticksCallback(const DIDEVICEINSTANCE* pdidInstance, VOID* pContext)
        {
            enum_state& state = *reinterpret_cast<enum_state*>(pContext);
            const QString guid = guid_to_string(pdidInstance->guidInstance);
#if 0
            const QString name = QString(pdidInstance->tszInstanceName);
            // the logic here is that iff multiple joysticks of same name exist, then take guids into account at all
            const int cnt_names = std::count_if(state.joys.begin(), state.joys.end(), [&](const joy& j) -> bool { return j.name == name; });
            // this is potentially bad since replugged sticks can change guids (?)
#endif
            
            const bool exists = std::find_if(state.joys.cbegin(),
                                             state.joys.cend(),
                                             [&](const std::shared_ptr<joy>& j) -> bool { return j->guid == guid; }) != state.joys.cend();
            
            state.all.push_back(guid);
            
            if (!exists)
            {
                HRESULT hr;
                LPDIRECTINPUTDEVICE8 h;
                if (FAILED(hr = state.dinput_handle->CreateDevice(pdidInstance->guidInstance, &h, nullptr)))
                {
                    qDebug() << "create joystick breakage" << guid << hr;
                    goto end;
                }
                if (FAILED(h->SetDataFormat(&c_dfDIJoystick2)))
                {
                    qDebug() << "format";
                    h->Release();
                    goto end;
                }
                
                if (FAILED(h->SetCooperativeLevel((HWND) GetDesktopWindow(), DISCL_NONEXCLUSIVE | DISCL_BACKGROUND)))
                {
                    qDebug() << "coop";
                    h->Release();
                    goto end;
                }
#if 0
                if (FAILED(hr = h->EnumObjects(EnumObjectsCallback, h, DIDFT_ALL)))
                {
                    qDebug() << "enum-objects";
                    h->Release();
                    goto end;
                }
#endif
                state.joys.push_back(std::make_shared<joy>(h, guid));
            }
            
end:        return DIENUM_CONTINUE;
        }
        
#if 0
        static BOOL CALLBACK EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE* pdidoi, VOID* ctx)
        {
            if (pdidoi->dwType & DIDFT_AXIS)
            {
                DIPROPRANGE diprg;
                memset(&diprg, 0, sizeof(diprg));
                diprg.diph.dwSize = sizeof( DIPROPRANGE );
                diprg.diph.dwHeaderSize = sizeof( DIPROPHEADER );
                diprg.diph.dwHow = DIPH_BYID;
                diprg.diph.dwObj = pdidoi->dwType;
                diprg.lMax = 32;
                diprg.lMin = -32;
                
                if (FAILED(reinterpret_cast<LPDIRECTINPUTDEVICE8>(ctx)->SetProperty(DIPROP_RANGE, &diprg.diph)))
                    return DIENUM_STOP;
            }
            
            return DIENUM_CONTINUE;
        }
#endif
    };
    
    LPDIRECTINPUT8 dinput_handle;
    std::vector<std::shared_ptr<joy>> joys;
    Timer timer_joylist;
    enum { joylist_refresh_ms = 250 };
};