summaryrefslogtreecommitdiff
path: root/src/SFML/Window/Unix/JoystickImpl.cpp
blob: 903d5881074d2beba351e4950306545ab00a6146 (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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2016 Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
//    you must not claim that you wrote the original software.
//    If you use this software in a product, an acknowledgment
//    in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
//    and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window/JoystickImpl.hpp>
#include <SFML/System/Err.hpp>
#include <linux/joystick.h>
#include <libudev.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <vector>
#include <string>
#include <cstring>

namespace
{
    udev* udevContext = 0;
    udev_monitor* udevMonitor = 0;

    struct JoystickRecord
    {
        std::string deviceNode;
        std::string systemPath;
        bool plugged;
    };

    typedef std::vector<JoystickRecord> JoystickList;
    JoystickList joystickList;

    bool isJoystick(udev_device* udevDevice)
    {
        // If anything goes wrong, we go safe and return true

        // No device to check, assume not a joystick
        if (!udevDevice)
            return false;

        const char* devnode = udev_device_get_devnode(udevDevice);

        // We only consider devices with a device node
        if (!devnode)
            return false;

        // SFML doesn't support evdev yet, so make sure we only handle /js nodes
        if (!std::strstr(devnode, "/js"))
            return false;

        // Check if this device is a joystick
        if (udev_device_get_property_value(udevDevice, "ID_INPUT_JOYSTICK"))
            return true;

        // Check if this device is something that isn't a joystick
        // We do this because the absence of any ID_INPUT_ property doesn't
        // necessarily mean that the device isn't a joystick, whereas the
        // presence of any ID_INPUT_ property that isn't ID_INPUT_JOYSTICK does
        if (udev_device_get_property_value(udevDevice, "ID_INPUT_ACCELEROMETER") ||
            udev_device_get_property_value(udevDevice, "ID_INPUT_KEY") ||
            udev_device_get_property_value(udevDevice, "ID_INPUT_KEYBOARD") ||
            udev_device_get_property_value(udevDevice, "ID_INPUT_MOUSE") ||
            udev_device_get_property_value(udevDevice, "ID_INPUT_TABLET") ||
            udev_device_get_property_value(udevDevice, "ID_INPUT_TOUCHPAD") ||
            udev_device_get_property_value(udevDevice, "ID_INPUT_TOUCHSCREEN"))
            return false;

        // On some platforms (older udev), ID_INPUT_ properties are not present, instead
        // the system makes use of the ID_CLASS property to identify the device class
        const char* idClass = udev_device_get_property_value(udevDevice, "ID_CLASS");

        if (idClass)
        {
            // Check if the device class matches joystick
            if (std::strstr(idClass, "joystick"))
                return true;

            // Check if the device class matches something that isn't a joystick
            // Rationale same as above
            if (std::strstr(idClass, "accelerometer") ||
                std::strstr(idClass, "key") ||
                std::strstr(idClass, "keyboard") ||
                std::strstr(idClass, "mouse") ||
                std::strstr(idClass, "tablet") ||
                std::strstr(idClass, "touchpad") ||
                std::strstr(idClass, "touchscreen"))
                return false;
        }

        // At this point, assume it is a joystick
        return true;
    }

    void updatePluggedList(udev_device* udevDevice = NULL)
    {
        if (udevDevice)
        {
            const char* action = udev_device_get_action(udevDevice);

            if (action)
            {
                if (isJoystick(udevDevice))
                {
                    // Since isJoystick returned true, this has to succeed
                    const char* devnode = udev_device_get_devnode(udevDevice);

                    JoystickList::iterator record;

                    for (record = joystickList.begin(); record != joystickList.end(); ++record)
                    {
                        if (record->deviceNode == devnode)
                        {
                            if (std::strstr(action, "add"))
                            {
                                // The system path might have changed so update it
                                const char* syspath = udev_device_get_syspath(udevDevice);

                                record->plugged = true;
                                record->systemPath = syspath ? syspath : "";
                                break;
                            }
                            else if (std::strstr(action, "remove"))
                            {
                                record->plugged = false;
                                break;
                            }
                        }
                    }

                    if (record == joystickList.end())
                    {
                        if (std::strstr(action, "add"))
                        {
                            // If not mapped before and it got added, map it now
                            const char* syspath = udev_device_get_syspath(udevDevice);

                            JoystickRecord record;
                            record.deviceNode = devnode;
                            record.systemPath = syspath ? syspath : "";
                            record.plugged = true;

                            joystickList.push_back(record);
                        }
                        else if (std::strstr(action, "remove"))
                        {
                            // Not mapped during the initial scan, and removed (shouldn't happen)
                            sf::err() << "Trying to disconnect joystick that wasn't connected" << std::endl;
                        }
                    }
                }

                return;
            }

            // Do a full rescan if there was no action just to be sure
        }

        // Reset the plugged status of each mapping since we are doing a full rescan
        for (JoystickList::iterator record = joystickList.begin(); record != joystickList.end(); ++record)
            record->plugged = false;

        udev_enumerate* udevEnumerator = udev_enumerate_new(udevContext);

        if (!udevEnumerator)
        {
            sf::err() << "Error while creating udev enumerator" << std::endl;
            return;
        }

        int result = 0;

        result = udev_enumerate_add_match_subsystem(udevEnumerator, "input");

        if (result < 0)
        {
            sf::err() << "Error while adding udev enumerator match" << std::endl;
            return;
        }

        result = udev_enumerate_scan_devices(udevEnumerator);

        if (result < 0)
        {
            sf::err() << "Error while enumerating udev devices" << std::endl;
            return;
        }

        udev_list_entry* devices = udev_enumerate_get_list_entry(udevEnumerator);
        udev_list_entry* device;

        udev_list_entry_foreach(device, devices) {
            const char* syspath = udev_list_entry_get_name(device);
            udev_device* udevDevice = udev_device_new_from_syspath(udevContext, syspath);

            if (udevDevice && isJoystick(udevDevice))
            {
                // Since isJoystick returned true, this has to succeed
                const char* devnode = udev_device_get_devnode(udevDevice);

                JoystickList::iterator record;

                // Check if the device node has been mapped before
                for (record = joystickList.begin(); record != joystickList.end(); ++record)
                {
                    if (record->deviceNode == devnode)
                    {
                        record->plugged = true;
                        break;
                    }
                }

                // If not mapped before, map it now
                if (record == joystickList.end())
                {
                    JoystickRecord record;
                    record.deviceNode = devnode;
                    record.systemPath = syspath;
                    record.plugged = true;

                    joystickList.push_back(record);
                }
            }

            udev_device_unref(udevDevice);
        }

        udev_enumerate_unref(udevEnumerator);
    }

    bool hasMonitorEvent()
    {
        // This will not fail since we make sure udevMonitor is valid
        int monitorFd = udev_monitor_get_fd(udevMonitor);

        fd_set descriptorSet;
        FD_ZERO(&descriptorSet);
        FD_SET(monitorFd, &descriptorSet);
        timeval timeout = {0, 0};

        return (select(monitorFd + 1, &descriptorSet, NULL, NULL, &timeout) > 0) &&
               FD_ISSET(monitorFd, &descriptorSet);
    }

    // Get a property value from a udev device
    const char* getUdevAttribute(udev_device* udevDevice, const std::string& attributeName)
    {
        return udev_device_get_property_value(udevDevice, attributeName.c_str());
    }

    // Get a system attribute from a USB device
    const char* getUsbAttribute(udev_device* udevDevice, const std::string& attributeName)
    {
        udev_device* udevDeviceParent = udev_device_get_parent_with_subsystem_devtype(udevDevice, "usb", "usb_device");

        if (!udevDeviceParent)
            return NULL;

        return udev_device_get_sysattr_value(udevDeviceParent, attributeName.c_str());
    }

    // Get a USB attribute for a joystick as an unsigned int
    unsigned int getUsbAttributeUint(udev_device* udevDevice, const std::string& attributeName)
    {
        if (!udevDevice)
            return 0;

        const char* attribute = getUsbAttribute(udevDevice, attributeName);
        unsigned int value = 0;

        if (attribute)
            value = static_cast<unsigned int>(std::strtoul(attribute, NULL, 16));

        return value;
    }

    // Get a udev property value for a joystick as an unsigned int
    unsigned int getUdevAttributeUint(udev_device* udevDevice, const std::string& attributeName)
    {
        if (!udevDevice)
            return 0;

        const char* attribute = getUdevAttribute(udevDevice, attributeName);
        unsigned int value = 0;

        if (attribute)
            value = static_cast<unsigned int>(std::strtoul(attribute, NULL, 16));

        return value;
    }

    // Get the joystick vendor id
    unsigned int getJoystickVendorId(unsigned int index)
    {
        if (!udevContext)
        {
            sf::err() << "Failed to get vendor ID of joystick " << joystickList[index].deviceNode << std::endl;
            return 0;
        }

        udev_device* udevDevice = udev_device_new_from_syspath(udevContext, joystickList[index].systemPath.c_str());

        if (!udevDevice)
        {
            sf::err() << "Failed to get vendor ID of joystick " << joystickList[index].deviceNode << std::endl;
            return 0;
        }

        unsigned int id = 0;

        // First try using udev
        id = getUdevAttributeUint(udevDevice, "ID_VENDOR_ID");

        if (id)
        {
            udev_device_unref(udevDevice);
            return id;
        }

        // Fall back to using USB attribute
        id = getUsbAttributeUint(udevDevice, "idVendor");

        udev_device_unref(udevDevice);

        if (id)
            return id;

        sf::err() << "Failed to get vendor ID of joystick " << joystickList[index].deviceNode << std::endl;

        return 0;
    }

    // Get the joystick product id
    unsigned int getJoystickProductId(unsigned int index)
    {
        if (!udevContext)
        {
            sf::err() << "Failed to get product ID of joystick " << joystickList[index].deviceNode << std::endl;
            return 0;
        }

        udev_device* udevDevice = udev_device_new_from_syspath(udevContext, joystickList[index].systemPath.c_str());

        if (!udevDevice)
        {
            sf::err() << "Failed to get product ID of joystick " << joystickList[index].deviceNode << std::endl;
            return 0;
        }

        unsigned int id = 0;

        // First try using udev
        id = getUdevAttributeUint(udevDevice, "ID_MODEL_ID");

        if (id)
        {
            udev_device_unref(udevDevice);
            return id;
        }

        // Fall back to using USB attribute
        id = getUsbAttributeUint(udevDevice, "idProduct");

        udev_device_unref(udevDevice);

        if (id)
            return id;

        sf::err() << "Failed to get product ID of joystick " << joystickList[index].deviceNode << std::endl;

        return 0;
    }

    // Get the joystick name
    std::string getJoystickName(unsigned int index)
    {
        std::string devnode = joystickList[index].deviceNode;

        // First try using ioctl with JSIOCGNAME
        int fd = ::open(devnode.c_str(), O_RDONLY | O_NONBLOCK);

        if (fd >= 0)
        {
            // Get the name
            char name[128];
            std::memset(name, 0, sizeof(name));

            int result = ioctl(fd, JSIOCGNAME(sizeof(name)), name);

            ::close(fd);

            if (result >= 0)
                return std::string(name);
        }

        // Fall back to manual USB chain walk via udev
        if (udevContext)
        {
            udev_device* udevDevice = udev_device_new_from_syspath(udevContext, joystickList[index].systemPath.c_str());

            if (udevDevice)
            {
                const char* product = getUsbAttribute(udevDevice, "product");
                udev_device_unref(udevDevice);

                if (product)
                    return std::string(product);
            }
        }

        sf::err() << "Unable to get name for joystick " << devnode << std::endl;

        return std::string("Unknown Joystick");
    }
}


namespace sf
{
namespace priv
{
////////////////////////////////////////////////////////////
JoystickImpl::JoystickImpl() :
m_file(-1)
{
    std::fill(m_mapping, m_mapping + ABS_MAX + 1, 0);
}


////////////////////////////////////////////////////////////
void JoystickImpl::initialize()
{
    udevContext = udev_new();

    if (!udevContext)
    {
        sf::err() << "Failed to create udev context, joystick support not available" << std::endl;
        return;
    }

    udevMonitor = udev_monitor_new_from_netlink(udevContext, "udev");

    if (!udevMonitor)
    {
        err() << "Failed to create udev monitor, joystick connections and disconnections won't be notified" << std::endl;
    }
    else
    {
        int error = udev_monitor_filter_add_match_subsystem_devtype(udevMonitor, "input", NULL);

        if (error < 0)
        {
            err() << "Failed to add udev monitor filter, joystick connections and disconnections won't be notified: " << error << std::endl;

            udev_monitor_unref(udevMonitor);
            udevMonitor = 0;
        }
        else
        {
            error = udev_monitor_enable_receiving(udevMonitor);

            if (error < 0)
            {
                err() << "Failed to enable udev monitor, joystick connections and disconnections won't be notified: " << error << std::endl;

                udev_monitor_unref(udevMonitor);
                udevMonitor = 0;
            }
        }
    }

    // Do an initial scan
    updatePluggedList();
}


////////////////////////////////////////////////////////////
void JoystickImpl::cleanup()
{
    // Unreference the udev monitor to destroy it
    if (udevMonitor)
    {
        udev_monitor_unref(udevMonitor);
        udevMonitor = 0;
    }

    // Unreference the udev context to destroy it
    if (udevContext)
    {
        udev_unref(udevContext);
        udevContext = 0;
    }
}


////////////////////////////////////////////////////////////
bool JoystickImpl::isConnected(unsigned int index)
{
    // See if we can skip scanning if udev monitor is available
    if (!udevMonitor)
    {
        // udev monitor is not available, perform a scan every query
        updatePluggedList();
    }
    else if (hasMonitorEvent())
    {
        // Check if new joysticks were added/removed since last update
        udev_device* udevDevice = udev_monitor_receive_device(udevMonitor);

        // If we can get the specific device, we check that,
        // otherwise just do a full scan if udevDevice == NULL
        updatePluggedList(udevDevice);

        if (udevDevice)
            udev_device_unref(udevDevice);
    }

    if (index >= joystickList.size())
        return false;

    // Then check if the joystick is connected
    return joystickList[index].plugged;
}

////////////////////////////////////////////////////////////
bool JoystickImpl::open(unsigned int index)
{
    if (index >= joystickList.size())
        return false;

    if (joystickList[index].plugged)
    {
        std::string devnode = joystickList[index].deviceNode;

        // Open the joystick's file descriptor (read-only and non-blocking)
        m_file = ::open(devnode.c_str(), O_RDONLY | O_NONBLOCK);
        if (m_file >= 0)
        {
            // Retrieve the axes mapping
            ioctl(m_file, JSIOCGAXMAP, m_mapping);

            // Get info
            m_identification.name = getJoystickName(index);

            if (udevContext)
            {
                m_identification.vendorId  = getJoystickVendorId(index);
                m_identification.productId = getJoystickProductId(index);
            }

            // Reset the joystick state
            m_state = JoystickState();

            return true;
        }
        else
        {
            err() << "Failed to open joystick " << devnode << ": " << errno << std::endl;
        }
    }

    return false;
}


////////////////////////////////////////////////////////////
void JoystickImpl::close()
{
    ::close(m_file);
    m_file = -1;
}


////////////////////////////////////////////////////////////
JoystickCaps JoystickImpl::getCapabilities() const
{
    JoystickCaps caps;

    if (m_file < 0)
        return caps;

    // Get the number of buttons
    char buttonCount;
    ioctl(m_file, JSIOCGBUTTONS, &buttonCount);
    caps.buttonCount = buttonCount;
    if (caps.buttonCount > Joystick::ButtonCount)
        caps.buttonCount = Joystick::ButtonCount;

    // Get the supported axes
    char axesCount;
    ioctl(m_file, JSIOCGAXES, &axesCount);
    for (int i = 0; i < axesCount; ++i)
    {
        switch (m_mapping[i])
        {
            case ABS_X:        caps.axes[Joystick::X]    = true; break;
            case ABS_Y:        caps.axes[Joystick::Y]    = true; break;
            case ABS_Z:
            case ABS_THROTTLE: caps.axes[Joystick::Z]    = true; break;
            case ABS_RZ:
            case ABS_RUDDER:   caps.axes[Joystick::R]    = true; break;
            case ABS_RX:       caps.axes[Joystick::U]    = true; break;
            case ABS_RY:       caps.axes[Joystick::V]    = true; break;
            case ABS_HAT0X:    caps.axes[Joystick::PovX] = true; break;
            case ABS_HAT0Y:    caps.axes[Joystick::PovY] = true; break;
            default:           break;
        }
    }

    return caps;
}


////////////////////////////////////////////////////////////
Joystick::Identification JoystickImpl::getIdentification() const
{
    return m_identification;
}


////////////////////////////////////////////////////////////
JoystickState JoystickImpl::JoystickImpl::update()
{
    if (m_file < 0)
    {
        m_state = JoystickState();
        return m_state;
    }

    // pop events from the joystick file
    js_event joyState;
    int result = read(m_file, &joyState, sizeof(joyState));
    while (result > 0)
    {
        switch (joyState.type & ~JS_EVENT_INIT)
        {
            // An axis was moved
            case JS_EVENT_AXIS:
            {
                float value = joyState.value * 100.f / 32767.f;

                if (joyState.number < ABS_MAX + 1)
                {
                    switch (m_mapping[joyState.number])
                    {
                        case ABS_X:        m_state.axes[Joystick::X]    = value; break;
                        case ABS_Y:        m_state.axes[Joystick::Y]    = value; break;
                        case ABS_Z:
                        case ABS_THROTTLE: m_state.axes[Joystick::Z]    = value; break;
                        case ABS_RZ:
                        case ABS_RUDDER:   m_state.axes[Joystick::R]    = value; break;
                        case ABS_RX:       m_state.axes[Joystick::U]    = value; break;
                        case ABS_RY:       m_state.axes[Joystick::V]    = value; break;
                        case ABS_HAT0X:    m_state.axes[Joystick::PovX] = value; break;
                        case ABS_HAT0Y:    m_state.axes[Joystick::PovY] = value; break;
                        default:           break;
                    }
                }
                break;
            }

            // A button was pressed
            case JS_EVENT_BUTTON:
            {
                if (joyState.number < Joystick::ButtonCount)
                    m_state.buttons[joyState.number] = (joyState.value != 0);
                break;
            }
        }

        result = read(m_file, &joyState, sizeof(joyState));
    }

    // Check the connection state of the joystick
    // read() returns -1 and errno != EGAIN if it's no longer connected
    // We need to check the result of read() as well, since errno could
    // have been previously set by some other function call that failed
    // result can be either negative or 0 at this point
    // If result is 0, assume the joystick is still connected
    // If result is negative, check errno and disconnect if it is not EAGAIN
    m_state.connected = (!result || (errno == EAGAIN));

    return m_state;
}

} // namespace priv

} // namespace sf