]> git.mxchange.org Git - flightgear.git/blob - src/Input/FGMacOSXEventInput.cxx
28c3094cccfa84c0653d891f8d43c181eea19531
[flightgear.git] / src / Input / FGMacOSXEventInput.cxx
1 // FGMacOSXEventInput.cxx -- handle event driven input devices for Mac OS X
2 //
3 // Written by Tatsuhiro Nishioka, started Aug. 2009.
4 //
5 // Copyright (C) 2009 Tasuhiro Nishioka, tat <dot> fgmacosx <at> gmail <dot> com
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23 #include "FGMacOSXEventInput.hxx"
24
25 using std::stringstream;
26 using std::map;
27 using std::string;
28
29 #define GetHIDElementLongValue(element, key) ({ \
30       long value = 0; \
31       CFNumberRef refType = (CFNumberRef)CFDictionaryGetValue(element, CFSTR(key)); \
32       if (refType) { CFNumberGetValue(refType, kCFNumberLongType, &value); } \
33       value; })
34
35 #define GetHIDElementBooleanValue(element, key) ({ \
36       bool value = 0; \
37       CFBooleanRef refType = (CFBooleanRef)CFDictionaryGetValue(element, CFSTR(key)); \
38       if (refType) { value = CFBooleanGetValue(refType); } \
39       value; })
40
41 #define GetHIDElementStringValue(element, key) ({ \
42       const char *buf = ""; \
43       CFStringRef refType = (CFStringRef)CFDictionaryGetValue(element, CFSTR(key)); \
44       if (refType) { \
45         buf = CFStringGetCStringPtr(refType, CFStringGetSystemEncoding());  \
46        } \
47       buf; })
48
49 // HID Element Types (log / debug use)
50 struct HIDTypes HID_TYPE_TABLE[] = {
51   {kIOHIDElementTypeInput_Misc, kHIDElementType, "Input Misc"},
52   {kIOHIDElementTypeInput_Button, kHIDElementType, "Input Button"},
53   {kIOHIDElementTypeInput_Axis, kHIDElementType, "Input Axis"},
54   {kIOHIDElementTypeInput_ScanCodes, kHIDElementType, "Input ScanCodes"},
55   {kIOHIDElementTypeOutput, kHIDElementType, "Output"},
56   {kIOHIDElementTypeFeature, kHIDElementType, "Feature"},
57   {kIOHIDElementTypeCollection, kHIDElementType, "Collection"},
58   {-1, kHIDElementType, ""}
59 };
60
61 // HID Element Pages (log / debug use)
62 struct HIDTypes HID_PAGE_TABLE[] = {
63   // Page
64   {kHIDPage_GenericDesktop, kHIDElementPage, "GenericDesktop"},
65   {kHIDPage_Simulation, kHIDElementPage, "Simulation Controls"},
66   {kHIDPage_VR, kHIDElementPage, "VR Controls"},
67   {kHIDPage_Sport, kHIDElementPage, "Sport Controls"},
68   {kHIDPage_Game, kHIDElementPage, "Game Controls"},
69   {0x06, kHIDElementPage, "Generic Device Controls"},
70   {kHIDPage_KeyboardOrKeypad, kHIDElementPage, "KeyboardOrKeypad"},
71   {kHIDPage_LEDs, kHIDElementPage, "LEDs"},
72   {kHIDPage_Button, kHIDElementPage, "Button"},
73   {kHIDPage_Ordinal, kHIDElementPage, "Ordinal"},
74   {kHIDPage_Telephony, kHIDElementPage, "Telephony"},
75   {kHIDPage_Consumer, kHIDElementPage, "Consumer"},
76   {kHIDPage_Digitizer, kHIDElementPage, "Digitizer"},
77   {kHIDPage_PID, kHIDElementPage, "PID"},
78   {kHIDPage_VendorDefinedStart, kHIDElementPage, "VendorDefinedStart"},
79   {-1, kHIDElementPage, ""}
80 };
81
82 #define USAGE_KEY(PAGE,USAGE) (PAGE << 16 | USAGE)
83 #define GET_PAGE(KEY)  (KEY >> 16)
84 #define GET_USAGE(KEY) (KEY & 0xFFFF)
85
86 #define GD_USAGE(USAGE) USAGE_KEY(kHIDPage_GenericDesktop, USAGE)
87 #define SIM_USAGE(USAGE) USAGE_KEY(kHIDPage_GenericDesktop, USAGE)
88 #define VR_USAGE(USAGE) USAGE_KEY(kHIDPage_VR, USAGE)
89 #define SP_USAGE(USAGE) USAGE_KEY(kHIDPage_Sport, USAGE)
90 #define GAME_USAGE(USAGE) USAGE_KEY(kHIDPage_Game, USAGE)
91 #define GDC_USAGE(USAGE) USAGE_KEY(0x06, USAGE) // Generic Device Control is "Reserved" in Apple's definition
92 #define KEY_USAGE(USAGE) USAGE_KEY(kHIDPage_KeyboardOrKeypad, USAGE)
93 #define LED_USAGE(USAGE) USAGE_KEY(kHIDPage_LEDs, USAGE)
94 #define BUTTON_USAGE(USAGE) USAGE_KEY(kHIDPage_Button, USAGE)
95 #define DIG_USAGE(USAGE) USAGE_KEY(kHIDPage_Digitizer, USAGE)
96 #define CON_USAGE(USAGE) USAGE_KEY(kHIDPage_Consumer, USAGE)
97
98 // HID Element Usage <-> FGEventData convertion data
99 // See http://www.usb.org/developers/devclass_docs/Hut1_12.pdf for detail on HID pages and usages
100 // Note 
101 // kHIDUsageAxis is FG specific type of DV since it is needed to be normalized into -1.0 to 1.0
102 // kHIDUsageHat also is FG specific type of DV. it's value is converted into two axis events
103 struct HIDTypes HID_USAGE_TABLE[] = {
104   // Generic Desktop Page
105   {GD_USAGE(kHIDUsage_GD_X), kHIDUsageAxis, "x-translate"},
106   {GD_USAGE(kHIDUsage_GD_Y), kHIDUsageAxis, "y-translate"},
107   {GD_USAGE(kHIDUsage_GD_Z), kHIDUsageAxis, "z-translate"},  
108   {GD_USAGE(kHIDUsage_GD_Rx), kHIDUsageAxis, "x-rotate"},  
109   {GD_USAGE(kHIDUsage_GD_Ry), kHIDUsageAxis, "y-rotate"},
110   {GD_USAGE(kHIDUsage_GD_Rz), kHIDUsageAxis, "z-rotate"},
111   {GD_USAGE(kHIDUsage_GD_Slider), kHIDUsageAxis, "slider"},
112   {GD_USAGE(kHIDUsage_GD_Dial), kHIDUsageAxis, "dial"},
113   {GD_USAGE(kHIDUsage_GD_Wheel), kHIDUsageAxis, "wheel"},
114   {GD_USAGE(kHIDUsage_GD_Hatswitch), kHIDUsageHat, "hat"},
115   
116   {GD_USAGE(kHIDUsage_GD_CountedBuffer), kHIDUsageNotSupported, "counted-buffer"},
117   {GD_USAGE(kHIDUsage_GD_ByteCount), kHIDUsageNotSupported, "byte-count"},
118   {GD_USAGE(kHIDUsage_GD_MotionWakeup), kHIDUsageDF, "motion-wakeup"},
119   {GD_USAGE(kHIDUsage_GD_Start), kHIDUsageOOC, "button-start"},
120   {GD_USAGE(kHIDUsage_GD_Select), kHIDUsageOOC, "button-select"},
121   {GD_USAGE(kHIDUsage_GD_Vx), kHIDUsageAxis, "x-vector"},
122   {GD_USAGE(kHIDUsage_GD_Vy), kHIDUsageAxis, "y-vector"},
123   {GD_USAGE(kHIDUsage_GD_Vz), kHIDUsageAxis, "z-vector"},
124   {GD_USAGE(kHIDUsage_GD_Vbrx), kHIDUsageAxis, "x-rel-vector"},
125   {GD_USAGE(kHIDUsage_GD_Vbry), kHIDUsageAxis, "y-rel-vector"},
126   {GD_USAGE(kHIDUsage_GD_Vbrz), kHIDUsageAxis, "z-rel-vector"},
127   {GD_USAGE(kHIDUsage_GD_Vno),  kHIDUsageAxis, "no-vector"},
128
129   {GD_USAGE(kHIDUsage_GD_SystemPowerDown), kHIDUsageOSC, "button-system-power-down"},
130   {GD_USAGE(kHIDUsage_GD_SystemSleep), kHIDUsageOSC, "button-system-sleep"},
131   {GD_USAGE(kHIDUsage_GD_SystemWakeUp), kHIDUsageOSC, "button-system-wake-up"},
132   {GD_USAGE(kHIDUsage_GD_SystemContextMenu), kHIDUsageOSC, "button-system-context-menu"},
133   {GD_USAGE(kHIDUsage_GD_SystemMainMenu), kHIDUsageOSC, "button-system-main-menu"},
134   {GD_USAGE(kHIDUsage_GD_SystemAppMenu), kHIDUsageOSC, "button-system-app-menu"},
135   {GD_USAGE(kHIDUsage_GD_SystemMenuHelp), kHIDUsageOSC, "button-system-menu-help"},
136   {GD_USAGE(kHIDUsage_GD_SystemMenuExit), kHIDUsageOSC, "button-system-menu-exit"},
137   {GD_USAGE(kHIDUsage_GD_SystemMenu), kHIDUsageOSC, "button-system-menu"},
138   {GD_USAGE(kHIDUsage_GD_SystemMenuRight), kHIDUsageRTC, "button-system-menu-right"},
139   {GD_USAGE(kHIDUsage_GD_SystemMenuLeft), kHIDUsageRTC, "button-system-menu-left"},
140   {GD_USAGE(kHIDUsage_GD_SystemMenuUp), kHIDUsageRTC, "button-system-menu-up"},
141   {GD_USAGE(kHIDUsage_GD_SystemMenuDown), kHIDUsageRTC, "button-system-menu-down"},
142   {GD_USAGE(kHIDUsage_GD_DPadUp), kHIDUsageOOC, "dpad-up"},
143   {GD_USAGE(kHIDUsage_GD_DPadDown), kHIDUsageOOC, "dpad-down"},
144   {GD_USAGE(kHIDUsage_GD_DPadRight), kHIDUsageOOC, "dpad-right"},
145   {GD_USAGE(kHIDUsage_GD_DPadLeft), kHIDUsageOOC, "dpad-left"},
146
147   // Game Controls Page
148   {GAME_USAGE(kHIDUsage_Game_TurnRightOrLeft), kHIDUsageAxis, "turn"},
149   {GAME_USAGE(kHIDUsage_Game_PitchUpOrDown), kHIDUsageAxis, "pitch"},
150   {GAME_USAGE(kHIDUsage_Game_MoveRightOrLeft), kHIDUsageAxis, "x-move"},
151   {GAME_USAGE(kHIDUsage_Game_MoveForwardOrBackward), kHIDUsageAxis, "y-move"},
152   {GAME_USAGE(kHIDUsage_Game_MoveUpOrDown), kHIDUsageAxis, "z-move"},
153   {GAME_USAGE(kHIDUsage_Game_LeanRightOrLeft), kHIDUsageAxis, "x-lean"},
154   {GAME_USAGE(kHIDUsage_Game_LeanForwardOrBackward), kHIDUsageAxis, "z-lean"},
155
156   // General Control Devices Page
157   {GDC_USAGE(0x20), kHIDUsageDV, "battery-strength"},
158   {GDC_USAGE(0x21), kHIDUsageDV, "wireless-channel"},
159   {GDC_USAGE(0x22), kHIDUsageDV, "wireless-id"},
160   {GDC_USAGE(0x23), kHIDUsageDV, "discover-wireless-control"},
161   {GDC_USAGE(0x24), kHIDUsageOSC, "security-code-character-entered"},
162   {GDC_USAGE(0x25), kHIDUsageOSC, "security-code-character-erased"},
163   {GDC_USAGE(0x26), kHIDUsageOSC, "security-code-cleared"},
164
165   // Simulation Controls Page
166   {SIM_USAGE(kHIDUsage_Sim_Aileron), kHIDUsageAxis, "aileron"},
167   {SIM_USAGE(kHIDUsage_Sim_AileronTrim), kHIDUsageAxis, "aileron-trim"},
168   {SIM_USAGE(kHIDUsage_Sim_AntiTorqueControl), kHIDUsageAxis, "anti-torque-control"},
169   {SIM_USAGE(kHIDUsage_Sim_AutopilotEnable), kHIDUsageOOC, "button-autopilot-enable"},
170   {SIM_USAGE(kHIDUsage_Sim_ChaffRelease), kHIDUsageOSC, "button-chaff-release"},
171   {SIM_USAGE(kHIDUsage_Sim_CollectiveControl), kHIDUsageAxis, "collective-control"},
172   {SIM_USAGE(kHIDUsage_Sim_DiveBrake), kHIDUsageAxis, "dive-brake"},
173   {SIM_USAGE(kHIDUsage_Sim_ElectronicCountermeasures), kHIDUsageOOC, "electronic-countermeasures"}, // OOC
174   {SIM_USAGE(kHIDUsage_Sim_Elevator), kHIDUsageAxis, "elevator"},
175   {SIM_USAGE(kHIDUsage_Sim_ElevatorTrim), kHIDUsageAxis, "elevator-trim"},
176   {SIM_USAGE(kHIDUsage_Sim_Rudder), kHIDUsageAxis, "rudder"},
177   {SIM_USAGE(kHIDUsage_Sim_Throttle), kHIDUsageAxis, "throttle"},
178   {SIM_USAGE(kHIDUsage_Sim_FlightCommunications), kHIDUsageOOC, "button-flight-communications"}, // OOC
179   {SIM_USAGE(kHIDUsage_Sim_FlareRelease), kHIDUsageOSC, "button-flare-release"},
180   {SIM_USAGE(kHIDUsage_Sim_LandingGear), kHIDUsageOOC, "button-landing-gear"}, // OOC
181   {SIM_USAGE(kHIDUsage_Sim_ToeBrake), kHIDUsageAxis, "toe-brake"},
182   {SIM_USAGE(kHIDUsage_Sim_Trigger), kHIDUsageMC, "button-trigger"},
183   {SIM_USAGE(kHIDUsage_Sim_WeaponsArm), kHIDUsageOOC, "button-weapons-arm"}, // OOC
184   {SIM_USAGE(kHIDUsage_Sim_Weapons), kHIDUsageOSC, "button-weapons"},
185   {SIM_USAGE(kHIDUsage_Sim_WingFlaps), kHIDUsageAxis, "wing-flaps"},  // DV
186   {SIM_USAGE(kHIDUsage_Sim_Accelerator), kHIDUsageAxis, "accelerator"}, // DV
187   {SIM_USAGE(kHIDUsage_Sim_Brake), kHIDUsageAxis, "brake"}, // DV
188   {SIM_USAGE(kHIDUsage_Sim_Clutch), kHIDUsageAxis, "clutch"}, // DV
189   {SIM_USAGE(kHIDUsage_Sim_Shifter), kHIDUsageAxis, "shifter"}, // DV
190   {SIM_USAGE(kHIDUsage_Sim_Steering), kHIDUsageAxis, "steering"}, // DV
191   {SIM_USAGE(kHIDUsage_Sim_TurretDirection), kHIDUsageAxis, "turret-direction"}, // DV
192   {SIM_USAGE(kHIDUsage_Sim_BarrelElevation), kHIDUsageAxis, "barrel-elevation"}, // DV
193   {SIM_USAGE(kHIDUsage_Sim_DivePlane), kHIDUsageAxis, "dive-plane"}, // DV
194   {SIM_USAGE(kHIDUsage_Sim_Ballast), kHIDUsageAxis, "ballast"}, // DV
195   {SIM_USAGE(kHIDUsage_Sim_BicycleCrank), kHIDUsageAxis, "bicycle-crank"}, // DV
196   {SIM_USAGE(kHIDUsage_Sim_HandleBars), kHIDUsageAxis, "handle-bars"}, // DV
197   {SIM_USAGE(kHIDUsage_Sim_FrontBrake), kHIDUsageAxis, "front-brake"}, // DV
198   {SIM_USAGE(kHIDUsage_Sim_RearBrake), kHIDUsageAxis, "rear-brake"}, // DV
199
200   // Digitizer Controls Page
201   {DIG_USAGE(kHIDUsage_Dig_TipPressure), kHIDUsageAxis, "tip-pressure"}, // DV
202   {DIG_USAGE(kHIDUsage_Dig_BarrelPressure), kHIDUsageAxis, "barrel-pressure"}, // DV
203   {DIG_USAGE(kHIDUsage_Dig_InRange), kHIDUsageMC, "in-range"}, // MC
204   {DIG_USAGE(kHIDUsage_Dig_Touch), kHIDUsageMC, "touch"}, // MC
205   {DIG_USAGE(kHIDUsage_Dig_Untouch), kHIDUsageOSC, "button-untouch"}, // OSC
206   {DIG_USAGE(kHIDUsage_Dig_Tap), kHIDUsageOSC, "button-tap"}, // OSC
207   {DIG_USAGE(kHIDUsage_Dig_Quality), kHIDUsageDV, "quality"}, // DV
208   {DIG_USAGE(kHIDUsage_Dig_DataValid), kHIDUsageDV, "button-data-valid"}, // MC
209   {DIG_USAGE(kHIDUsage_Dig_TransducerIndex), kHIDUsageDV, "transducer-index"}, // DV
210   {DIG_USAGE(kHIDUsage_Dig_BatteryStrength), kHIDUsageDV, "battery-strength"}, // DV
211   {DIG_USAGE(kHIDUsage_Dig_Invert), kHIDUsageMC, "invert"}, // MC
212   {DIG_USAGE(kHIDUsage_Dig_XTilt), kHIDUsageAxis, "x-tilt"}, // DV
213   {DIG_USAGE(kHIDUsage_Dig_YTilt), kHIDUsageAxis, "y-tilt"}, // DV
214   {DIG_USAGE(kHIDUsage_Dig_Azimuth), kHIDUsageAxis, "azimuth"}, // DV
215   {DIG_USAGE(kHIDUsage_Dig_Altitude), kHIDUsageAxis, "altitude"}, // DV
216   {DIG_USAGE(kHIDUsage_Dig_Twist), kHIDUsageAxis, "twist"}, // DV
217   {DIG_USAGE(kHIDUsage_Dig_TipSwitch), kHIDUsageMC, "button-tipswitch"}, // MC
218   {DIG_USAGE(kHIDUsage_Dig_SecondaryTipSwitch), kHIDUsageMC, "button-secondary-tipswitch"}, // MC
219   {DIG_USAGE(kHIDUsage_Dig_BarrelSwitch), kHIDUsageMC, "button-barrelswitch"}, // MC
220   {DIG_USAGE(kHIDUsage_Dig_Eraser), kHIDUsageMC, "eraser"}, // MC
221   {DIG_USAGE(kHIDUsage_Dig_TabletPick), kHIDUsageMC, "table-pick"}, // MC
222
223  // Consumer Page
224   {CON_USAGE(kHIDUsage_Csmr_Plus10), kHIDUsageOSC, "plus10"},
225   {CON_USAGE(kHIDUsage_Csmr_Plus100), kHIDUsageOSC, "plus100"},
226   {CON_USAGE(kHIDUsage_Csmr_AMOrPM), kHIDUsageOSC, "am-pm"},
227   {CON_USAGE(kHIDUsage_Csmr_Power), kHIDUsageOOC, "power"},
228   {CON_USAGE(kHIDUsage_Csmr_Reset), kHIDUsageOSC, "reset"},
229   {CON_USAGE(kHIDUsage_Csmr_Sleep), kHIDUsageOSC, "sleep"},
230   {CON_USAGE(kHIDUsage_Csmr_SleepAfter), kHIDUsageOSC, "sleep-after"},
231   {CON_USAGE(kHIDUsage_Csmr_SleepMode), kHIDUsageRTC, "sleep-mode"},
232   {CON_USAGE(kHIDUsage_Csmr_Illumination), kHIDUsageOOC, "illumination"},
233   {CON_USAGE(kHIDUsage_Csmr_Menu), kHIDUsageOOC, "menu"},
234   {CON_USAGE(kHIDUsage_Csmr_MenuPick), kHIDUsageOSC, "menu-pick"},
235   {CON_USAGE(kHIDUsage_Csmr_MenuUp), kHIDUsageOSC, "menu-up"},
236   {CON_USAGE(kHIDUsage_Csmr_MenuDown), kHIDUsageOSC, "menu-down"},
237   {CON_USAGE(kHIDUsage_Csmr_MenuLeft), kHIDUsageOSC, "menu-left"},
238   {CON_USAGE(kHIDUsage_Csmr_MenuRight), kHIDUsageOSC, "menu-right"},
239   {CON_USAGE(kHIDUsage_Csmr_MenuEscape), kHIDUsageOSC, "menu-escape"},
240   {CON_USAGE(kHIDUsage_Csmr_MenuValueIncrease), kHIDUsageOSC, "menu-value-increase"},
241   {CON_USAGE(kHIDUsage_Csmr_MenuValueDecrease), kHIDUsageOSC, "menu-value-decrease"},
242   {CON_USAGE(kHIDUsage_Csmr_DataOnScreen), kHIDUsageOOC, "data-on-screen"},
243   {CON_USAGE(kHIDUsage_Csmr_ClosedCaption), kHIDUsageOOC, "closed-caption"},
244   {CON_USAGE(kHIDUsage_Csmr_ClosedCaptionSelect), kHIDUsageSel, "closed-caption-select"},
245   {CON_USAGE(kHIDUsage_Csmr_VCROrTV), kHIDUsageOOC, "vcr-tv"},
246   {CON_USAGE(kHIDUsage_Csmr_BroadcastMode), kHIDUsageOSC, "broadcast-mode"},
247   {CON_USAGE(kHIDUsage_Csmr_Snapshot), kHIDUsageOSC, "snapshot"},
248   {CON_USAGE(kHIDUsage_Csmr_Still), kHIDUsageOSC, "still"},
249   {CON_USAGE(kHIDUsage_Csmr_Assign), kHIDUsageOSC, "assign"},
250   {CON_USAGE(kHIDUsage_Csmr_ModeStep), kHIDUsageOSC, "mode-step"},
251   {CON_USAGE(kHIDUsage_Csmr_RecallLast), kHIDUsageOSC, "recall-last"},
252   {CON_USAGE(kHIDUsage_Csmr_EnterChannel), kHIDUsageOSC, "enter-channel"},
253   {CON_USAGE(kHIDUsage_Csmr_OrderMovie), kHIDUsageOSC, "order-movie"},
254   {CON_USAGE(kHIDUsage_Csmr_Channel), kHIDUsageDV, "channel"}, // LC
255   {CON_USAGE(kHIDUsage_Csmr_MediaSelection), kHIDUsageSel, "media-selection"},
256   {CON_USAGE(kHIDUsage_Csmr_MediaSelectComputer), kHIDUsageSel, "media-select-computer"},
257   {CON_USAGE(kHIDUsage_Csmr_MediaSelectTV), kHIDUsageSel, "media-select-tv"},
258   {CON_USAGE(kHIDUsage_Csmr_MediaSelectWWW), kHIDUsageSel, "media-seleci-www"},
259   {CON_USAGE(kHIDUsage_Csmr_MediaSelectDVD), kHIDUsageSel, "media-select-dvd"},
260   {CON_USAGE(kHIDUsage_Csmr_MediaSelectTelephone), kHIDUsageSel, "media-select-telephone"},
261   {CON_USAGE(kHIDUsage_Csmr_MediaSelectProgramGuide), kHIDUsageSel, "media-select-programguide"},
262   {CON_USAGE(kHIDUsage_Csmr_MediaSelectVideoPhone), kHIDUsageSel, "media-select-videophone"},
263   {CON_USAGE(kHIDUsage_Csmr_MediaSelectGames), kHIDUsageSel, "media-select-games"},
264   {CON_USAGE(kHIDUsage_Csmr_MediaSelectMessages), kHIDUsageSel, "media-select-messages"},
265   {CON_USAGE(kHIDUsage_Csmr_MediaSelectCD), kHIDUsageSel, "media-select-cd"},
266   {CON_USAGE(kHIDUsage_Csmr_MediaSelectVCR), kHIDUsageSel, "media-select-vcr"},
267   {CON_USAGE(kHIDUsage_Csmr_MediaSelectTuner), kHIDUsageOSC, "media-select-tuner"},
268   {CON_USAGE(kHIDUsage_Csmr_Quit), kHIDUsageOSC, "quit"},
269   {CON_USAGE(kHIDUsage_Csmr_Help), kHIDUsageOOC, "help"},
270   {CON_USAGE(kHIDUsage_Csmr_MediaSelectTape), kHIDUsageSel, "media-select-tape"},
271   {CON_USAGE(kHIDUsage_Csmr_MediaSelectCable), kHIDUsageSel, "media-select-cable"},
272   {CON_USAGE(kHIDUsage_Csmr_MediaSelectSatellite), kHIDUsageSel, "media-select-satellite"},
273   {CON_USAGE(kHIDUsage_Csmr_MediaSelectSecurity), kHIDUsageSel, "media-select-security"},
274   {CON_USAGE(kHIDUsage_Csmr_MediaSelectHome), kHIDUsageSel, "media-select-home"},
275   {CON_USAGE(kHIDUsage_Csmr_MediaSelectCall), kHIDUsageSel, "media-select-call"},
276   {CON_USAGE(kHIDUsage_Csmr_ChannelIncrement), kHIDUsageOSC, "channel-increment"},
277   {CON_USAGE(kHIDUsage_Csmr_ChannelDecrement), kHIDUsageOSC, "channel-decrement"},
278   {CON_USAGE(kHIDUsage_Csmr_Media), kHIDUsageSel, "media"},
279   {CON_USAGE(kHIDUsage_Csmr_VCRPlus), kHIDUsageOSC, "vcr-plus"},
280   {CON_USAGE(kHIDUsage_Csmr_Once), kHIDUsageOSC, "once"},
281   {CON_USAGE(kHIDUsage_Csmr_Daily), kHIDUsageOSC, "daily"},
282   {CON_USAGE(kHIDUsage_Csmr_Weekly), kHIDUsageOSC, "weekly"},
283   {CON_USAGE(kHIDUsage_Csmr_Monthly), kHIDUsageOSC, "monthly"},
284   {CON_USAGE(kHIDUsage_Csmr_Play), kHIDUsageOOC, "play"},
285   {CON_USAGE(kHIDUsage_Csmr_Pause), kHIDUsageOOC, "pause"},
286   {CON_USAGE(kHIDUsage_Csmr_Record), kHIDUsageOOC, "record"},
287   {CON_USAGE(kHIDUsage_Csmr_FastForward), kHIDUsageOOC,"fastforward"},
288   {CON_USAGE(kHIDUsage_Csmr_Rewind), kHIDUsageOOC, "rewind"},
289   {CON_USAGE(kHIDUsage_Csmr_ScanNextTrack), kHIDUsageOSC, "scan-next-track"},
290   {CON_USAGE(kHIDUsage_Csmr_ScanPreviousTrack), kHIDUsageOSC, "scan-previous-track"},
291   {CON_USAGE(kHIDUsage_Csmr_Stop), kHIDUsageOSC, "stop"},
292   {CON_USAGE(kHIDUsage_Csmr_Eject), kHIDUsageOSC, "eject"},
293   {CON_USAGE(kHIDUsage_Csmr_RandomPlay), kHIDUsageOOC, "random-play"},
294   {CON_USAGE(kHIDUsage_Csmr_SelectDisc), kHIDUsageNotSupported, "select-disc"}, //NamedArray
295
296   {CON_USAGE(kHIDUsage_Csmr_VolumeIncrement), kHIDUsageRTC, "volume-increment"},
297   {CON_USAGE(kHIDUsage_Csmr_VolumeDecrement), kHIDUsageRTC, "volume-decrement"},
298   {CON_USAGE(kHIDUsage_Csmr_PlayOrPause), kHIDUsageOSC, "play-pause"},
299   {CON_USAGE(kHIDUsage_Csmr_Mute), kHIDUsageOOC, "mute"},
300   // Too many... and the rest are T.B.D. ;-)
301   {-1, kHIDElementPage, ""},
302 };
303
304 static HIDTypeByID hidTypeByID(HID_TYPE_TABLE);
305 static HIDTypeByID hidPageByID(HID_PAGE_TABLE);
306 static HIDTypeByID hidUsageByID(HID_USAGE_TABLE);
307
308
309 HIDElement::HIDElement(CFDictionaryRef element, long page, long usage) : 
310   page(page), usage(usage), value(0.0), lastValue(0.0) {
311
312   cookie = (IOHIDElementCookie)GetHIDElementLongValue(element, kIOHIDElementCookieKey);
313   name = hidUsageByID.getName(USAGE_KEY(page, usage));
314 }
315
316 long HIDElement::read(IOHIDDeviceInterface **interface)
317 {
318   IOHIDEventStruct event;
319   lastValue = value;
320   IOReturn ret = (*interface)->getElementValue(interface, cookie, &event);
321   if (ret == kIOReturnSuccess) {
322     value = event.value;
323 //    SG_LOG(SG_INPUT, SG_BULK, "Element: " << name << "; value = " << value);
324     return event.value;
325   } else {
326     SG_LOG(SG_INPUT, SG_WARN, "Failed reading value for HID Element: " << name);
327     return 0;
328   }
329 }
330
331 bool HIDElement::isUpdated()
332 {
333   return (value != lastValue);
334 }
335
336 void HIDElement::generateEvent(FGMacOSXInputDevice *device, double dt, int modifiers)
337 {
338   SG_LOG(SG_INPUT, SG_DEBUG, "Generating Input Event: " << name << "=" << value);
339   FGMacOSXEventData eventData(name, (float)value, dt, modifiers);
340   device->HandleEvent(eventData);
341 }
342
343 AxisElement::AxisElement(CFDictionaryRef element, long page, long usage) : 
344   HIDElement(element, page, usage), dead_band(0.00), saturate(1.0)
345 {
346   min = GetHIDElementLongValue(element, kIOHIDElementMinKey); 
347   max = GetHIDElementLongValue(element, kIOHIDElementMaxKey);
348   isRelative = GetHIDElementBooleanValue(element, kIOHIDElementIsRelativeKey);
349   isWrapping = GetHIDElementBooleanValue(element, kIOHIDElementIsWrappingKey);
350   isNonLinear = GetHIDElementBooleanValue(element, kIOHIDElementIsNonLinearKey);
351
352   name = ((isRelative == true) ? "rel-" : "abs-") + name;
353
354   center = min + (max - abs(min)) * 0.5;
355   SG_LOG(SG_INPUT, SG_DEBUG, "HID Axis Element; " << name << " min: " << min << " max:" << max << " center: " << center);
356   SG_LOG(SG_INPUT, SG_DEBUG, "isRelative=" << isRelative << ", isWrapping=" << isWrapping << ", isNonLinear=" << isNonLinear);
357 }
358
359 long AxisElement::read(IOHIDDeviceInterface **interface)
360 {
361   lastValue = value;
362   return HIDElement::read(interface);
363 }
364
365 // FIXME: This can be removed when AxisInputEvent can normalize its value
366 void AxisElement::generateEvent(FGMacOSXInputDevice *device, double dt, int modifiers)
367 {
368   float normalizedValue = (float)value;
369   if (!isRelative) {
370     normalizedValue = (value - (float)center) / (float)(max - center);
371     if (fabs(normalizedValue) < dead_band)
372       normalizedValue = 0.0;
373   }
374
375   SG_LOG(SG_INPUT, SG_DEBUG, "Generating Input Event: " << name << "=" << normalizedValue);
376   FGMacOSXEventData eventData(name, normalizedValue, dt, modifiers);
377   device->HandleEvent(eventData);
378 }
379
380 ButtonElement::ButtonElement(CFDictionaryRef element, long page, long usage) :
381   HIDElement(element, page, usage)
382 {
383   if (name == "") {
384     stringstream ss;
385     ss << (page == kHIDPage_KeyboardOrKeypad ? "keyboard-" : "button-") << usage;
386     ss >> name;
387   }
388 }
389
390 HatElement::HatElement(CFDictionaryRef element, long page, long usage, int id) :
391   HIDElement(element, page, usage), id(id)
392 {
393   min = GetHIDElementLongValue(element, kIOHIDElementMinKey);
394   max = GetHIDElementLongValue(element, kIOHIDElementMaxKey);
395   lastValue = 8;
396 }
397
398 void HatElement::generateEvent(FGMacOSXInputDevice *device, double dt, int modifiers)
399 {
400   // Hat value is from 0 to 8, representing:
401   // 0:N, 1:NE, 2:E, 3:SE, 4:S, 5:SW, 6:W, 7:NW, 8:Neutral
402   // FG can't bind hat directly, so need to convert its value to two axis events
403   static float xvalues[] = {0, 1, 1,  1,  0, -1, -1, -1, 0};
404   static float yvalues[] = {1, 1, 0, -1, -1, -1,  0,  1, 0};
405   stringstream ss1, ss2;
406   ss1 << "abs-hat" << id << "-x";
407   SG_LOG(SG_INPUT, SG_BULK, "Generating Input Event: " << ss1.str() << "=" << xvalues[(int)value]);
408   FGMacOSXEventData eventDataX(ss1.str(), xvalues[(int)value], dt, modifiers);
409   ss2 << "abs-hat" << id << "-y";
410   SG_LOG(SG_INPUT, SG_BULK, "Generating Input Event: " << ss2.str() << "=" << yvalues[(int)value]);
411   FGMacOSXEventData eventDataY(ss2.str(), yvalues[(int)value], dt, modifiers);
412   device->HandleEvent((FGEventData &)eventDataX);
413   device->HandleEvent((FGEventData &)eventDataY);
414 }
415
416
417 LEDElement::LEDElement(CFDictionaryRef element, long page, long usage) :
418   HIDElement(element, page, usage)
419 {
420   stringstream ss;
421   if (name == "") {
422     ss << "led-" << usage;
423     ss >> name;
424   }
425 }
426
427 void LEDElement::write(IOHIDDeviceInterface **interface, double value) {
428   IOHIDEventStruct event = (IOHIDEventStruct){kIOHIDElementTypeOutput, cookie, 0, {0}, 0, 0};
429   event.value = value;
430   (*interface)->setElementValue(interface, cookie, &event, 0, NULL, NULL, NULL);
431 }
432
433 //
434 // This is just for testing....
435 //
436 FeatureElement::FeatureElement(CFDictionaryRef element, long page, long usage, int count=1) :
437   HIDElement(element, page, usage) 
438 {
439   stringstream ss;
440   if (name == "") {
441     ss << "feature-" << usage;
442     if (count > 1) 
443       ss << "-" << count;
444     ss >> name;
445   }
446 }
447
448 long FeatureElement::read(IOHIDDeviceInterface **interface) {
449   IOHIDEventStruct event;
450   IOReturn ret = (*interface)->queryElementValue(interface, cookie, &event, 0, NULL, NULL, NULL);
451   if (ret != kIOReturnSuccess) {
452     ret = (*interface)->getElementValue(interface, cookie, &event);
453     if (ret != kIOReturnSuccess) {
454       SG_LOG(SG_INPUT, SG_WARN, "Can't get element value for feature element: " << getName());
455       return 0;
456     }
457   }
458   return event.value;
459 }
460
461 //
462 // HIDElementFactory
463 //
464 void HIDElementFactory::create(CFTypeRef element, FGMacOSXInputDevice *inputDevice)
465 {
466   assert(CFGetTypeID(element) == CFArrayGetTypeID());
467   CFRange range = {0, CFArrayGetCount((CFArrayRef)element)};
468   CFArrayApplyFunction((CFArrayRef) element, range, 
469                        HIDElementFactory::elementEnumerator, (void *)inputDevice);
470 };
471
472
473 void HIDElementFactory::elementEnumerator( const void *element, void *inputDevice) {
474   if (CFGetTypeID((CFTypeRef) element) != CFDictionaryGetTypeID()) {
475     SG_LOG(SG_INPUT, SG_WARN, "Element Enumerator passed non-dictionary value.");
476   }
477   HIDElementFactory::parseElement((CFDictionaryRef)element, (FGMacOSXInputDevice *)inputDevice);
478 };
479
480
481 void HIDElementFactory::parseElement(CFDictionaryRef element, FGMacOSXInputDevice *inputDevice) {
482   long page = GetHIDElementLongValue(element, kIOHIDElementUsagePageKey);
483   long usage = GetHIDElementLongValue(element, kIOHIDElementUsageKey);
484
485   static int id=0;
486   static map<FGMacOSXInputDevice *, map<long, unsigned> > elementCount;
487
488   long type = GetHIDElementLongValue(element, kIOHIDElementTypeKey);
489
490   if (type == kIOHIDElementTypeCollection) {
491     id = 0;
492     SG_LOG(SG_INPUT, SG_DEBUG, "Collection: " << hidTypeByID.getName(type) << "(" << type << ")" 
493                                               << ":" << hidPageByID.getName(page) << "(" << page << ")" 
494                                               << ":" << hidUsageByID.getName(USAGE_KEY(page, usage)) << "(" << usage << ")");
495     HIDElementFactory::create(CFDictionaryGetValue(element, CFSTR(kIOHIDElementKey)), inputDevice);
496   } else {
497     HIDUsageType usageType = hidUsageByID.getType(USAGE_KEY(page, usage));
498     // FIXME: Any other elegant way for counting the same usage on a device?
499     // This is mainly needed for feature / hat elements to avoid assigning the sane event name.
500     elementCount[inputDevice][USAGE_KEY(page, usage)] += 1;
501     
502     switch (usageType) {
503       case kHIDUsageAxis:
504           inputDevice->addElement(new AxisElement(element, page, usage));
505           break;
506       case kHIDUsageDV:
507       case kHIDUsageDF:
508           inputDevice->addElement(new HIDElement(element, page, usage));
509           break;
510       case kHIDUsageHat:
511           inputDevice->addElement(new HatElement(element, page, usage, elementCount[inputDevice][USAGE_KEY(page, usage)]));
512           break;
513       case kHIDUsageOOC:
514       case kHIDUsageOSC:
515       case kHIDUsageMC:
516       case kHIDUsageRTC:
517           if (usage > 0)
518             inputDevice->addElement(new ButtonElement(element, page, usage));
519           break;
520           
521       default:
522         if (page == kHIDPage_Button || type == kIOHIDElementTypeInput_Button && usage > 0) {
523         // FIXME: most of KeyboardOrKeypad elements should be treated as Selector type, not as Button...
524           inputDevice->addElement(new ButtonElement(element, page, usage));
525         } else if (page == kHIDPage_LEDs && usage > 0) {
526           inputDevice->addElement(new LEDElement(element, page, usage));
527 /* Feature elements are not fully tested yet
528         } else if (type == kIOHIDElementTypeFeature) {
529           // just for testing feature elements
530           inputDevice->addElement(new FeatureElement(element, page, usage, elementCount[inputDevice][USAGE_KEY(page, usage)]));
531 */
532         } else {
533           SG_LOG(SG_INPUT, SG_INFO, "HID Element Page/Usage is not supported: type=" << hidTypeByID.getName(type) 
534                     << "(" << type << ")" << ", page=" << hidPageByID.getName(page) << "(" << page << ")" 
535                     << ", usage=" << usage);
536         }
537     }
538   }
539 }
540
541 //
542 // FGMacOSXInputDevice implementation
543 //
544
545 FGMacOSXInputDevice::FGMacOSXInputDevice(io_object_t device) : device(device), devInterface(NULL)
546 {
547   CFDictionaryRef properties = getProperties();
548   string deviceName = GetHIDElementStringValue(properties, kIOHIDProductKey);
549   if (deviceName == "") {
550     deviceName = GetHIDElementStringValue(properties, "USB Product Name");
551   }
552
553   SetName(deviceName);
554   CFRelease(properties);
555 }
556
557 const char *FGMacOSXInputDevice::TranslateEventName(FGEventData &eventData)
558 {
559   FGMacOSXEventData &macEvent = (FGMacOSXEventData &)eventData;
560   return macEvent.name.c_str();
561 }
562
563
564 //
565 // Outputs value to an writable element (like LEDElement)
566 //
567 void FGMacOSXInputDevice::Send(const char *eventName, double value)
568 {
569   HIDElement *element = elements[eventName];
570   if (element) {
571     element->write(devInterface, value);
572   } else {
573     SG_LOG(SG_INPUT, SG_WARN, "No element to handle event: " << eventName);
574   }
575 }
576
577
578 CFDictionaryRef FGMacOSXInputDevice::getProperties(io_object_t device)
579 {
580   IOReturn ret;
581   CFMutableDictionaryRef properties;
582
583   ret = IORegistryEntryCreateCFProperties( device, &properties, kCFAllocatorDefault, kNilOptions);
584   if (ret != kIOReturnSuccess || !properties) {
585     SG_LOG(SG_INPUT, SG_WARN, "Error getting device properties.");
586     return NULL;
587   }
588
589   return properties;
590 }
591
592 //
593 // Adds HID element to FGMacOSXInputDevice.
594 // On Mac OS X, update() will read value of each HID element.
595 // Thus, FGMacOSXInputDevice needs all supported elements when a device is opened
596 //
597 void FGMacOSXInputDevice::addElement(HIDElement *element)
598 {
599   elements[element->getName()] = element;
600   int count = elements.size();
601   SG_LOG(SG_INPUT, SG_DEBUG, "adding element " << count << ":" << element->getName());
602 }
603
604 void FGMacOSXInputDevice::Open() {
605   // create device interface
606   IOReturn ret;
607   SInt32 score;
608   IOCFPlugInInterface **plugin;
609   SG_LOG(SG_INPUT, SG_INFO, "Opening HID : " << GetName());
610
611   ret = IOCreatePlugInInterfaceForService(device,
612                                           kIOHIDDeviceUserClientTypeID,
613                                           kIOCFPlugInInterfaceID,
614                                           &plugin, &score);
615         
616   if (ret != kIOReturnSuccess) {
617     SG_LOG(SG_INPUT, SG_ALERT, "Error creating a plugin for HID : " << GetName());
618     throw std::exception();
619     return;
620   }
621
622   HRESULT result = (*plugin)->QueryInterface(plugin, 
623                                              CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID), 
624                                              (LPVOID*)&devInterface );
625         
626   if (result != S_OK)
627     SG_LOG(SG_INPUT, SG_WARN, "Failed Querying HID plugin interface: " << GetName());
628
629   (*plugin)->Release(plugin); // don't leak a ref
630   if (devInterface == NULL) {
631     return;
632     throw std::exception();
633   }
634         
635   // store the interface in this instance
636   ret = (*devInterface)->open(devInterface, 0);
637   if (ret != kIOReturnSuccess) {
638     SG_LOG(SG_INPUT, SG_ALERT, "Error opening device interface: " << GetName());
639     throw std::exception();
640     return;
641   }
642   CFDictionaryRef props = getProperties();
643                 
644   // recursively adds all supported HID elements to FGMacOSXInputDevice
645   CFTypeRef topLevelElement = CFDictionaryGetValue (props, CFSTR(kIOHIDElementKey));
646   HIDElementFactory::create(topLevelElement, this);
647   CFRelease(props);
648 }
649
650 void FGMacOSXInputDevice::Close() {
651   SG_LOG(SG_INPUT, SG_INFO, "Closing HID: " << GetName());
652   if (devInterface) {
653     (*devInterface)->close(devInterface);
654   }
655
656   map<string, HIDElement *>::iterator it;
657   for (it = elements.begin(); it != elements.end(); it++) {
658     if ((*it).second)
659       delete (*it).second;
660   }
661   elements.clear();
662 }
663
664 //
665 // Reads values of assigned HIDElement and generates events
666 //
667 void FGMacOSXInputDevice::update(double dt)
668 {
669   map<string, HIDElement *>::iterator it;
670   for (it = elements.begin(); it != elements.end(); it++) {
671     (*it).second->read(devInterface);
672     if ((*it).second->isUpdated()) { // Is this needed?
673       int modifiers = fgGetKeyModifiers();
674       (*it).second->generateEvent(this, dt, modifiers);
675     }
676   }
677 }
678
679 //
680 // FGMacOSXEventInput implementation
681 //
682 FGMacOSXEventInput::~FGMacOSXEventInput() {
683   deviceIndices.clear();
684 }
685
686 void FGMacOSXEventInput::init()
687 {
688   IOReturn ret;
689   SG_LOG(SG_INPUT, SG_INFO, "initializing FGMacOSXEventInput");
690
691   // We want all HID devices for matching
692   CFMutableDictionaryRef matchingDictionary = IOServiceMatching(kIOHIDDeviceKey);
693
694   // Needs to retain machingDict since IOServiceAddMatchingNotification consumes one reference.
695   matchingDictionary = (CFMutableDictionaryRef) CFRetain(matchingDictionary);
696   matchingDictionary = (CFMutableDictionaryRef) CFRetain(matchingDictionary);
697
698   // Registers Hotplug notification for plug and play.
699   notifyPort = IONotificationPortCreate(kIOMasterPortDefault); 
700   runLoopSource = IONotificationPortGetRunLoopSource(notifyPort);
701   CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
702   ret = IOServiceAddMatchingNotification(notifyPort, kIOFirstMatchNotification, 
703                                          matchingDictionary, FGMacOSXEventInput::deviceAttached, (void *)this, &addedIterator);
704   ret = IOServiceAddMatchingNotification(notifyPort, kIOTerminatedNotification, 
705                                          matchingDictionary, FGMacOSXEventInput::deviceDetached, (void *)this, &removedIterator);
706
707   // prepare for notification by calling these callback funcs to remove existing HID device iterators
708   FGMacOSXEventInput::deviceAttached((void *)this, addedIterator);
709   FGMacOSXEventInput::deviceDetached((void *)this, removedIterator);
710 }
711
712
713 void FGMacOSXEventInput::attachDevice(io_iterator_t iterator)
714 {
715   io_object_t device;
716
717   while ((device = IOIteratorNext(iterator))) {
718     FGMacOSXInputDevice *inputDevice = new FGMacOSXInputDevice(device);
719     if (inputDevice) {
720       SG_LOG(SG_INPUT, SG_INFO, "HID Device Atached: " << inputDevice->GetName());
721       unsigned index = AddDevice(inputDevice);
722       // Needs to check if AddDevice closed the device due to lack of config file
723       if (index != FGEventInput::INVALID_DEVICE_INDEX) {
724         // maps device with FG device index. 
725         // This map is needed in detachDevice to tell FGEventInput which deivce ID is to be removed
726         deviceIndices[device] = index;
727       }
728     }
729     IOObjectRelease(device);
730   }
731 }
732
733
734 void FGMacOSXEventInput::detachDevice(io_iterator_t iterator)
735 {
736   io_object_t device;
737
738   while ((device = IOIteratorNext(iterator))) {
739     unsigned index = deviceIndices[device];
740     if (index != FGEventInput::INVALID_DEVICE_INDEX) {
741       FGMacOSXInputDevice *inputDevice = dynamic_cast<FGMacOSXInputDevice *>(input_devices[index]);
742       if (inputDevice) {
743         SG_LOG(SG_INPUT, SG_INFO, "HID Device Detached: " << inputDevice->GetName());
744         RemoveDevice(index);
745         deviceIndices.erase(device); 
746       } else {
747         SG_LOG(SG_INPUT, SG_WARN, "Invalid device index:" << index << ". Detach failed.");
748       }
749     } else {
750       SG_LOG(SG_INPUT, SG_INFO, "Device ID unmatched: " << (int)device << " No HID deivce is detached since it is not supported by FG.");
751     }
752     IOObjectRelease(device);
753   }
754 }
755
756 //
757 // read all elements in each input device
758 //
759 void FGMacOSXEventInput::update(double dt)
760 {
761   FGEventInput::update(dt);
762
763   map<int, FGInputDevice*>::const_iterator it;
764   for (it = input_devices.begin(); it != input_devices.end(); it++) {
765     if ((*it).second) {
766       FGMacOSXInputDevice *inputDevice = dynamic_cast<FGMacOSXInputDevice *>((*it).second);
767       if (inputDevice) {
768         inputDevice->update(dt);
769       } else {
770         SG_LOG(SG_INPUT, SG_WARN, "Invalid device. Update failed.");
771       }
772     }
773   }
774 }