From 8e4091f9af905eeda151c321b6608c1e617870f5 Mon Sep 17 00:00:00 2001
From: Ryan Fields <metalfox@gmail.com>
Date: Fri, 5 Oct 2012 10:26:50 -0400
Subject: [PATCH] Makes joystick button ordering predictable.

Fixes unpredictable or unintentional joystick button ordering by sorting
buttons according to their HID Usage property.  This allows SFML to
adhere to a manufacturer's (or driver implentation's) intended button
ordering.
---
 src/SFML/Window/OSX/JoystickImpl.cpp | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/src/SFML/Window/OSX/JoystickImpl.cpp b/src/SFML/Window/OSX/JoystickImpl.cpp
index c35161fc3..4160465ef 100644
--- a/src/SFML/Window/OSX/JoystickImpl.cpp
+++ b/src/SFML/Window/OSX/JoystickImpl.cpp
@@ -30,6 +30,14 @@
 #include <SFML/Window/OSX/HIDInputManager.hpp>
 #include <SFML/Window/OSX/HIDJoystickManager.hpp>
 
+// Translation unit namespace
+namespace {
+    ////////////////////////////////////////////////////////////
+    bool JoystickButtonSortPredicate(IOHIDElementRef b1, IOHIDElementRef b2)
+    {
+        return IOHIDElementGetUsage(b1) < IOHIDElementGetUsage(b2);
+    }
+}
 
 namespace sf
 {
@@ -218,6 +226,10 @@ bool JoystickImpl::open(unsigned int index)
         }
     }
     
+    // Ensure that the buttons will be indexed in the same order as their
+    // HID Usage (assigned by manufacturer and/or a driver).
+    std::sort(m_buttons.begin(), m_buttons.end(), JoystickButtonSortPredicate);
+    
     // Note : Joy::AxisPovX/Y are not supported (yet).
     // Maybe kIOHIDElementTypeInput_Axis is the corresponding type but I can't test.