summaryrefslogtreecommitdiffhomepage
path: root/dinput/dinput.cpp
blob: 22781a324073988cc39fb2e654928df84db67653 (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
#include "dinput.hpp"
#include "compat/macros.hpp"

#include <QDebug>

int di_t::refcnt{0};
diptr di_t::handle;
QMutex di_t::lock;

diptr di_t::init_di_()
{
    CoInitialize(nullptr);

    diptr di = nullptr;
    HRESULT hr = DirectInput8Create(GetModuleHandle(nullptr),
                                    DIRECTINPUT_VERSION,
                                    IID_IDirectInput8,
                                    (void**)&di,
                                    nullptr);
    if (!SUCCEEDED(hr))
    {
        qDebug() << "can't make dinput:" << (void*)(LONG_PTR)hr;
        qDebug() << "crashing!";
        std::abort();
    }

    return di;
}

di_t::di_t()
{
    ref_di();
}

void di_t::ref_di()
{
    QMutexLocker l(&lock);

    if (!handle)
        handle = init_di_();

    ++refcnt;
}

void di_t::unref_di()
{
    QMutexLocker l(&lock);

    const int refcnt_ = --refcnt;

    if (refcnt_ == 0)
    {
        qDebug() << "exit: di handle";
        handle->Release();
    }
}

di_t::~di_t()
{
    unref_di();
}

bool di_t::poll_device(LPDIRECTINPUTDEVICE8 dev)
{
    HRESULT hr;

    switch (dev->Poll())
    {
    case DI_OK:
    case DI_NOEFFECT:
        return true;
    default:
        break;
    }

    switch (hr = dev->Acquire())
    {
    default:
        break;
    case DI_OK:
    case S_FALSE:
        switch (hr = dev->Poll())
        {
        case DI_OK:
        case DI_NOEFFECT:
            return true;
        default:
            break;
        }
        break;
    }

    eval_once(qDebug() << "dinput: device poll failed:" << (void*)hr);

    return false;
}