dinput: Fix pointer cast warnings on 64-bit.
[wine] / dlls / dinput / joystick_linuxinput.c
1 /*              DirectInput Joystick device
2  *
3  * Copyright 1998,2000 Marcus Meissner
4  * Copyright 1998,1999 Lionel Ulmer
5  * Copyright 2000-2001 TransGaming Technologies Inc.
6  * Copyright 2005 Daniel Remenak
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include <assert.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <time.h>
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34 #ifdef HAVE_SYS_TIME_H
35 # include <sys/time.h>
36 #endif
37 #include <fcntl.h>
38 #ifdef HAVE_SYS_IOCTL_H
39 # include <sys/ioctl.h>
40 #endif
41 #include <errno.h>
42 #ifdef HAVE_SYS_ERRNO_H
43 # include <sys/errno.h>
44 #endif
45 #ifdef HAVE_LINUX_INPUT_H
46 # include <linux/input.h>
47 # undef SW_MAX
48 # if defined(EVIOCGBIT) && defined(EV_ABS) && defined(BTN_PINKIE)
49 #  define HAVE_CORRECT_LINUXINPUT_H
50 # endif
51 #endif
52 #ifdef HAVE_SYS_POLL_H
53 # include <sys/poll.h>
54 #endif
55
56 #include "wine/debug.h"
57 #include "wine/unicode.h"
58 #include "wine/list.h"
59 #include "windef.h"
60 #include "winbase.h"
61 #include "winerror.h"
62 #include "winreg.h"
63 #include "dinput.h"
64
65 #include "dinput_private.h"
66 #include "device_private.h"
67
68 WINE_DEFAULT_DEBUG_CHANNEL(dinput);
69
70
71 /*
72  * Maps POV x & y event values to a DX "clock" position:
73  *         0
74  *   31500    4500
75  * 27000  -1    9000
76  *   22500   13500
77  *       18000
78  */
79 DWORD joystick_map_pov(POINTL *p)
80 {
81     if (p->x > 0)
82         return p->y < 0 ?  4500 : !p->y ?  9000 : 13500;
83     else if (p->x < 0)
84         return p->y < 0 ? 31500 : !p->y ? 27000 : 22500;
85     else
86         return p->y < 0 ?     0 : !p->y ?    -1 : 18000;
87 }
88
89 /*
90  * This maps the read value (from the input event) to a value in the
91  * 'wanted' range.
92  * Notes:
93  *   Dead zone is in % multiplied by a 100 (range 0..10000)
94  */
95 LONG joystick_map_axis(ObjProps *props, int val)
96 {
97     LONG ret;
98     LONG dead_zone = MulDiv( props->lDeadZone, props->lDevMax - props->lDevMin, 10000 );
99     LONG dev_range = props->lDevMax - props->lDevMin - dead_zone;
100
101     /* Center input */
102     val -= (props->lDevMin + props->lDevMax) / 2;
103
104     /* Remove dead zone */
105     if (abs( val ) <= dead_zone / 2)
106         val = 0;
107     else
108         val = val < 0 ? val + dead_zone / 2 : val - dead_zone / 2;
109
110     /* Scale and map the value from the device range into the required range */
111     ret = MulDiv( val, props->lMax - props->lMin, dev_range ) +
112           (props->lMin + props->lMax) / 2;
113
114     /* Clamp in case or rounding errors */
115     if      (ret > props->lMax) ret = props->lMax;
116     else if (ret < props->lMin) ret = props->lMin;
117
118     TRACE( "(%d <%d> %d) -> (%d <%d> %d): val=%d ret=%d\n",
119            props->lDevMin, dead_zone, props->lDevMax,
120            props->lMin, props->lDeadZone, props->lMax,
121            val, ret );
122
123     return ret;
124 }
125
126 #ifdef HAVE_CORRECT_LINUXINPUT_H
127
128 #define EVDEVPREFIX     "/dev/input/event"
129
130 /* Wine joystick driver object instances */
131 #define WINE_JOYSTICK_MAX_AXES    8
132 #define WINE_JOYSTICK_MAX_POVS    4
133 #define WINE_JOYSTICK_MAX_BUTTONS 128
134
135 struct wine_input_absinfo {
136     LONG value;
137     LONG minimum;
138     LONG maximum;
139     LONG fuzz;
140     LONG flat;
141 };
142
143 /* implemented in effect_linuxinput.c */
144 HRESULT linuxinput_create_effect(int* fd, REFGUID rguid, struct list *parent_list_entry, LPDIRECTINPUTEFFECT* peff);
145 HRESULT linuxinput_get_info_A(int fd, REFGUID rguid, LPDIEFFECTINFOA info);
146 HRESULT linuxinput_get_info_W(int fd, REFGUID rguid, LPDIEFFECTINFOW info);
147
148 typedef struct JoystickImpl JoystickImpl;
149 static const IDirectInputDevice8AVtbl JoystickAvt;
150 static const IDirectInputDevice8WVtbl JoystickWvt;
151
152 struct JoyDev {
153         char *device;
154         char *name;
155         GUID guid;
156
157         int has_ff;
158         int num_effects;
159
160         /* data returned by EVIOCGBIT for caps, EV_ABS, EV_KEY, and EV_FF */
161         BYTE                            evbits[(EV_MAX+7)/8];
162         BYTE                            absbits[(ABS_MAX+7)/8];
163         BYTE                            keybits[(KEY_MAX+7)/8];
164         BYTE                            ffbits[(FF_MAX+7)/8];   
165
166         /* data returned by the EVIOCGABS() ioctl */
167         struct wine_input_absinfo       axes[ABS_MAX];
168 };
169
170 struct JoystickImpl
171 {
172         struct IDirectInputDevice2AImpl base;
173
174         struct JoyDev                  *joydev;
175
176         /* joystick private */
177         int                             joyfd;
178
179         DIJOYSTATE2                     js;
180
181         ObjProps                        props[ABS_MAX];
182
183         int                             axes[ABS_MAX];
184         POINTL                          povs[4];
185
186         /* LUT for KEY_ to offset in rgbButtons */
187         BYTE                            buttons[KEY_MAX];
188
189         DWORD                           numAxes;
190         DWORD                           numPOVs;
191         DWORD                           numButtons;
192
193         /* Force feedback variables */
194         struct list                     ff_effects;
195         int                             ff_state;
196 };
197
198 static void fake_current_js_state(JoystickImpl *ji);
199 static void find_joydevs(void);
200
201 /* This GUID is slightly different from the linux joystick one. Take note. */
202 static const GUID DInput_Wine_Joystick_Base_GUID = { /* 9e573eda-7734-11d2-8d4a-23903fb6bdf7 */
203   0x9e573eda,
204   0x7734,
205   0x11d2,
206   {0x8d, 0x4a, 0x23, 0x90, 0x3f, 0xb6, 0xbd, 0xf7}
207 };
208
209 #define test_bit(arr,bit) (((BYTE*)(arr))[(bit)>>3]&(1<<((bit)&7)))
210
211 #define MAX_JOYDEV 64
212
213 static int have_joydevs = -1;
214 static struct JoyDev *joydevs = NULL;
215
216 static void find_joydevs(void)
217 {
218     int i;
219
220     if (InterlockedCompareExchange(&have_joydevs, 0, -1) != -1)
221         /* Someone beat us to it */
222         return;
223
224     for (i = 0; i < MAX_JOYDEV; i++)
225     {
226         char buf[MAX_PATH];
227         struct JoyDev joydev = {0};
228         int fd;
229         int no_ff_check = 0;
230         int j;
231         struct JoyDev *new_joydevs;
232
233         snprintf(buf, sizeof(buf), EVDEVPREFIX"%d", i);
234
235         if ((fd = open(buf, O_RDWR)) == -1)
236         {
237             fd = open(buf, O_RDONLY);
238             no_ff_check = 1;
239         }
240
241         if (fd == -1)
242         {
243             WARN("Failed to open \"%s\": %d %s\n", buf, errno, strerror(errno));
244             continue;
245         }
246
247         if (ioctl(fd, EVIOCGBIT(0, sizeof(joydev.evbits)), joydev.evbits) == -1)
248         {
249             WARN("ioct(EVIOCGBIT, 0) failed: %d %s\n", errno, strerror(errno));
250             close(fd);
251             continue;
252         }
253         if (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(joydev.absbits)), joydev.absbits) == -1)
254         {
255             WARN("ioct(EVIOCGBIT, EV_ABS) failed: %d %s\n", errno, strerror(errno));
256             close(fd);
257             continue;
258         }
259         if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(joydev.keybits)), joydev.keybits) == -1)
260         {
261             WARN("ioct(EVIOCGBIT, EV_KEY) failed: %d %s\n", errno, strerror(errno));
262             close(fd);
263             continue;
264         }
265
266         /* A true joystick has at least axis X and Y, and at least 1
267          * button. copied from linux/drivers/input/joydev.c */
268         if (!test_bit(joydev.absbits, ABS_X) || !test_bit(joydev.absbits, ABS_Y) ||
269             !(test_bit(joydev.keybits, BTN_TRIGGER) ||
270               test_bit(joydev.keybits, BTN_A) ||
271               test_bit(joydev.keybits, BTN_1)))
272         {
273             close(fd);
274             continue;
275         }
276
277         if (!(joydev.device = HeapAlloc(GetProcessHeap(), 0, strlen(buf) + 1)))
278         {
279             close(fd);
280             continue;
281         }
282         strcpy(joydev.device, buf);
283
284         buf[MAX_PATH - 1] = 0;
285         if (ioctl(fd, EVIOCGNAME(MAX_PATH - 1), buf) != -1 &&
286             (joydev.name = HeapAlloc(GetProcessHeap(), 0, strlen(buf) + 1)))
287             strcpy(joydev.name, buf);
288         else
289             joydev.name = joydev.device;
290
291         joydev.guid = DInput_Wine_Joystick_Base_GUID;
292         joydev.guid.Data3 += have_joydevs;
293
294         TRACE("Found a joystick on %s: %s (%s)\n", 
295             joydev.device, joydev.name, 
296             debugstr_guid(&joydev.guid)
297             );
298
299 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
300         if (!no_ff_check &&
301             test_bit(joydev.evbits, EV_FF) &&
302             ioctl(fd, EVIOCGBIT(EV_FF, sizeof(joydev.ffbits)), joydev.ffbits) != -1 &&
303             ioctl(fd, EVIOCGEFFECTS, &joydev.num_effects) != -1 &&
304             joydev.num_effects > 0)
305         {
306             TRACE(" ... with force feedback\n");
307             joydev.has_ff = 1;
308         }
309 #endif
310
311         for (j = 0; j < ABS_MAX;j ++)
312         {
313             if (!test_bit(joydev.absbits, j)) continue;
314             if (ioctl(fd, EVIOCGABS(j), &(joydev.axes[j])) != -1)
315             {
316               TRACE(" ... with axis %d: cur=%d, min=%d, max=%d, fuzz=%d, flat=%d\n",
317                   j,
318                   joydev.axes[j].value,
319                   joydev.axes[j].minimum,
320                   joydev.axes[j].maximum,
321                   joydev.axes[j].fuzz,
322                   joydev.axes[j].flat
323                   );
324             }
325         }
326
327         if (!have_joydevs)
328             new_joydevs = HeapAlloc(GetProcessHeap(), 0, sizeof(struct JoyDev));
329         else
330             new_joydevs = HeapReAlloc(GetProcessHeap(), 0, joydevs, (1 + have_joydevs) * sizeof(struct JoyDev));
331
332         if (!new_joydevs)
333         {
334             close(fd);
335             continue;
336         }
337         joydevs = new_joydevs;
338         memcpy(joydevs + have_joydevs, &joydev, sizeof(joydev));
339         have_joydevs++;
340
341         close(fd);
342     }
343 }
344
345 static void fill_joystick_dideviceinstanceA(LPDIDEVICEINSTANCEA lpddi, DWORD version, int id)
346 {
347     DWORD dwSize = lpddi->dwSize;
348
349     TRACE("%d %p\n", dwSize, lpddi);
350     memset(lpddi, 0, dwSize);
351
352     lpddi->dwSize       = dwSize;
353     lpddi->guidInstance = joydevs[id].guid;
354     lpddi->guidProduct  = DInput_Wine_Joystick_Base_GUID;
355     lpddi->guidFFDriver = GUID_NULL;
356
357     if (version >= 0x0800)
358         lpddi->dwDevType = DI8DEVTYPE_JOYSTICK | (DI8DEVTYPEJOYSTICK_STANDARD << 8);
359     else
360         lpddi->dwDevType = DIDEVTYPE_JOYSTICK | (DIDEVTYPEJOYSTICK_TRADITIONAL << 8);
361
362     strcpy(lpddi->tszInstanceName, joydevs[id].name);
363     strcpy(lpddi->tszProductName, joydevs[id].device);
364 }
365
366 static void fill_joystick_dideviceinstanceW(LPDIDEVICEINSTANCEW lpddi, DWORD version, int id)
367 {
368     DWORD dwSize = lpddi->dwSize;
369
370     TRACE("%d %p\n", dwSize, lpddi);
371     memset(lpddi, 0, dwSize);
372
373     lpddi->dwSize       = dwSize;
374     lpddi->guidInstance = joydevs[id].guid;
375     lpddi->guidProduct  = DInput_Wine_Joystick_Base_GUID;
376     lpddi->guidFFDriver = GUID_NULL;
377
378     if (version >= 0x0800)
379         lpddi->dwDevType = DI8DEVTYPE_JOYSTICK | (DI8DEVTYPEJOYSTICK_STANDARD << 8);
380     else
381         lpddi->dwDevType = DIDEVTYPE_JOYSTICK | (DIDEVTYPEJOYSTICK_TRADITIONAL << 8);
382
383     MultiByteToWideChar(CP_ACP, 0, joydevs[id].name, -1, lpddi->tszInstanceName, MAX_PATH);
384     MultiByteToWideChar(CP_ACP, 0, joydevs[id].device, -1, lpddi->tszProductName, MAX_PATH);
385 }
386
387 static BOOL joydev_enum_deviceA(DWORD dwDevType, DWORD dwFlags, LPDIDEVICEINSTANCEA lpddi, DWORD version, int id)
388 {
389   find_joydevs();
390
391   if (id >= have_joydevs) {
392     return FALSE;
393   }
394
395   if (!((dwDevType == 0) ||
396         ((dwDevType == DIDEVTYPE_JOYSTICK) && (version > 0x0300 && version < 0x0800)) ||
397         (((dwDevType == DI8DEVCLASS_GAMECTRL) || (dwDevType == DI8DEVTYPE_JOYSTICK)) && (version >= 0x0800))))
398     return FALSE;
399
400 #ifndef HAVE_STRUCT_FF_EFFECT_DIRECTION
401   if (dwFlags & DIEDFL_FORCEFEEDBACK)
402     return FALSE;
403 #endif
404
405   if (!(dwFlags & DIEDFL_FORCEFEEDBACK) || joydevs[id].has_ff) {
406     fill_joystick_dideviceinstanceA(lpddi, version, id);
407     return TRUE;
408   }
409   return FALSE;
410 }
411
412 static BOOL joydev_enum_deviceW(DWORD dwDevType, DWORD dwFlags, LPDIDEVICEINSTANCEW lpddi, DWORD version, int id)
413 {
414   find_joydevs();
415
416   if (id >= have_joydevs) {
417     return FALSE;
418   }
419
420   if (!((dwDevType == 0) ||
421         ((dwDevType == DIDEVTYPE_JOYSTICK) && (version > 0x0300 && version < 0x0800)) ||
422         (((dwDevType == DI8DEVCLASS_GAMECTRL) || (dwDevType == DI8DEVTYPE_JOYSTICK)) && (version >= 0x0800))))
423     return FALSE;
424
425 #ifndef HAVE_STRUCT_FF_EFFECT_DIRECTION
426   if (dwFlags & DIEDFL_FORCEFEEDBACK)
427     return FALSE;
428 #endif
429
430   if (!(dwFlags & DIEDFL_FORCEFEEDBACK) || joydevs[id].has_ff) {
431     fill_joystick_dideviceinstanceW(lpddi, version, id);
432     return TRUE;
433   }
434   return FALSE;
435 }
436
437 static JoystickImpl *alloc_device(REFGUID rguid, const void *jvt, IDirectInputImpl *dinput, unsigned short index)
438 {
439     JoystickImpl* newDevice;
440     LPDIDATAFORMAT df = NULL;
441     int i, idx = 0;
442     char buffer[MAX_PATH+16];
443     HKEY hkey, appkey;
444     LONG def_deadzone = 0;
445
446     newDevice = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(JoystickImpl));
447     if (!newDevice) return NULL;
448
449     newDevice->base.lpVtbl = jvt;
450     newDevice->base.ref    = 1;
451     newDevice->base.guid   = *rguid;
452     newDevice->base.dinput = dinput;
453     newDevice->joyfd       = -1;
454     newDevice->joydev      = &joydevs[index];
455     list_init(&newDevice->ff_effects);
456 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
457     newDevice->ff_state    = FF_STATUS_STOPPED;
458 #endif
459     InitializeCriticalSection(&newDevice->base.crit);
460     newDevice->base.crit.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": JoystickImpl*->base.crit");
461
462     /* get options */
463     get_app_key(&hkey, &appkey);
464
465     if (!get_config_key(hkey, appkey, "DefaultDeadZone", buffer, MAX_PATH))
466     {
467         def_deadzone = atoi(buffer);
468         TRACE("setting default deadzone to: %d\n", def_deadzone);
469     }
470     if (appkey) RegCloseKey(appkey);
471     if (hkey) RegCloseKey(hkey);
472
473     /* Create copy of default data format */
474     if (!(df = HeapAlloc(GetProcessHeap(), 0, c_dfDIJoystick2.dwSize))) goto failed;
475     memcpy(df, &c_dfDIJoystick2, c_dfDIJoystick2.dwSize);
476     if (!(df->rgodf = HeapAlloc(GetProcessHeap(), 0, df->dwNumObjs * df->dwObjSize))) goto failed;
477
478     /* Supported Axis & POVs should map 1-to-1 */
479     for (i = 0; i < WINE_JOYSTICK_MAX_AXES; i++)
480     {
481         if (!test_bit(newDevice->joydev->absbits, i)) {
482             newDevice->axes[i] = -1;
483             continue;
484         }
485
486         memcpy(&df->rgodf[idx], &c_dfDIJoystick2.rgodf[i], df->dwObjSize);
487         newDevice->axes[i] = idx;
488         newDevice->props[idx].lDevMin = newDevice->joydev->axes[i].minimum;
489         newDevice->props[idx].lDevMax = newDevice->joydev->axes[i].maximum;
490         newDevice->props[idx].lMin    = 0;
491         newDevice->props[idx].lMax    = 0xffff;
492         newDevice->props[idx].lSaturation = 0;
493         newDevice->props[idx].lDeadZone = def_deadzone;
494
495         /* Linux supports force-feedback on X & Y axes only */
496         if (newDevice->joydev->has_ff && (i == 0 || i == 1))
497             df->rgodf[idx].dwFlags |= DIDOI_FFACTUATOR;
498
499         df->rgodf[idx++].dwType = DIDFT_MAKEINSTANCE(newDevice->numAxes++) | DIDFT_ABSAXIS;
500     }
501
502     for (i = 0; i < WINE_JOYSTICK_MAX_POVS; i++)
503     {
504         if (!test_bit(newDevice->joydev->absbits, ABS_HAT0X + i * 2) ||
505             !test_bit(newDevice->joydev->absbits, ABS_HAT0Y + i * 2)) {
506             newDevice->axes[ABS_HAT0X + i * 2] = newDevice->axes[ABS_HAT0Y + i * 2] = -1;
507             continue;
508         }
509
510         memcpy(&df->rgodf[idx], &c_dfDIJoystick2.rgodf[i + WINE_JOYSTICK_MAX_AXES], df->dwObjSize);
511         newDevice->axes[ABS_HAT0X + i * 2] = newDevice->axes[ABS_HAT0Y + i * 2] = i;
512         df->rgodf[idx++].dwType = DIDFT_MAKEINSTANCE(newDevice->numPOVs++) | DIDFT_POV;
513     }
514
515     /* Buttons can be anywhere, so check all */
516     for (i = 0; i < KEY_MAX && newDevice->numButtons < WINE_JOYSTICK_MAX_BUTTONS; i++)
517     {
518         if (!test_bit(newDevice->joydev->keybits, i)) continue;
519
520         memcpy(&df->rgodf[idx], &c_dfDIJoystick2.rgodf[newDevice->numButtons + WINE_JOYSTICK_MAX_AXES + WINE_JOYSTICK_MAX_POVS], df->dwObjSize);
521         newDevice->buttons[i] = 0x80 | newDevice->numButtons;
522         df->rgodf[idx  ].pguid = &GUID_Button;
523         df->rgodf[idx++].dwType = DIDFT_MAKEINSTANCE(newDevice->numButtons++) | DIDFT_PSHBUTTON;
524     }
525     df->dwNumObjs = idx;
526
527     fake_current_js_state(newDevice);
528
529     newDevice->base.data_format.wine_df = df;
530     IDirectInput_AddRef((LPDIRECTINPUTDEVICE8A)newDevice->base.dinput);
531     return newDevice;
532
533 failed:
534     if (df) HeapFree(GetProcessHeap(), 0, df->rgodf);
535     HeapFree(GetProcessHeap(), 0, df);
536     HeapFree(GetProcessHeap(), 0, newDevice);
537     return NULL;
538 }
539
540 /******************************************************************************
541   *     get_joystick_index : Get the joystick index from a given GUID
542   */
543 static unsigned short get_joystick_index(REFGUID guid)
544 {
545     GUID wine_joystick = DInput_Wine_Joystick_Base_GUID;
546     GUID dev_guid = *guid;
547
548     wine_joystick.Data3 = 0;
549     dev_guid.Data3 = 0;
550
551     /* for the standard joystick GUID use index 0 */
552     if(IsEqualGUID(&GUID_Joystick,guid)) return 0;
553
554     /* for the wine joystick GUIDs use the index stored in Data3 */
555     if(IsEqualGUID(&wine_joystick, &dev_guid)) return guid->Data3 - DInput_Wine_Joystick_Base_GUID.Data3;
556
557     return MAX_JOYDEV;
558 }
559
560 static HRESULT joydev_create_deviceA(IDirectInputImpl *dinput, REFGUID rguid, REFIID riid, LPDIRECTINPUTDEVICEA* pdev)
561 {
562     unsigned short index;
563
564     find_joydevs();
565
566     if ((index = get_joystick_index(rguid)) < MAX_JOYDEV &&
567         have_joydevs && index < have_joydevs)
568     {
569         if ((riid == NULL) ||
570             IsEqualGUID(&IID_IDirectInputDeviceA,  riid) ||
571             IsEqualGUID(&IID_IDirectInputDevice2A, riid) ||
572             IsEqualGUID(&IID_IDirectInputDevice7A, riid) ||
573             IsEqualGUID(&IID_IDirectInputDevice8A, riid))
574         {
575             *pdev = (IDirectInputDeviceA*) alloc_device(rguid, &JoystickAvt, dinput, index);
576             TRACE("Created a Joystick device (%p)\n", *pdev);
577
578             if (*pdev == NULL)
579             {
580                 ERR("out of memory\n");
581                 return DIERR_OUTOFMEMORY;
582             }
583             return DI_OK;
584         }
585
586         WARN("no interface\n");
587         return DIERR_NOINTERFACE;
588     }
589
590     return DIERR_DEVICENOTREG;
591 }
592
593
594 static HRESULT joydev_create_deviceW(IDirectInputImpl *dinput, REFGUID rguid, REFIID riid, LPDIRECTINPUTDEVICEW* pdev)
595 {
596     unsigned short index;
597
598     find_joydevs();
599
600     if ((index = get_joystick_index(rguid)) < MAX_JOYDEV &&
601         have_joydevs && index < have_joydevs)
602     {
603         if ((riid == NULL) ||
604             IsEqualGUID(&IID_IDirectInputDeviceW,  riid) ||
605             IsEqualGUID(&IID_IDirectInputDevice2W, riid) ||
606             IsEqualGUID(&IID_IDirectInputDevice7W, riid) ||
607             IsEqualGUID(&IID_IDirectInputDevice8W, riid))
608         {
609             *pdev = (IDirectInputDeviceW*) alloc_device(rguid, &JoystickWvt, dinput, index);
610             TRACE("Created a Joystick device (%p)\n", *pdev);
611
612             if (*pdev == NULL)
613             {
614                 ERR("out of memory\n");
615                 return DIERR_OUTOFMEMORY;
616             }
617             return DI_OK;
618         }
619         WARN("no interface\n");
620         return DIERR_NOINTERFACE;
621     }
622
623     WARN("invalid device GUID\n");
624     return DIERR_DEVICENOTREG;
625 }
626
627 const struct dinput_device joystick_linuxinput_device = {
628   "Wine Linux-input joystick driver",
629   joydev_enum_deviceA,
630   joydev_enum_deviceW,
631   joydev_create_deviceA,
632   joydev_create_deviceW
633 };
634
635 /******************************************************************************
636   *     Acquire : gets exclusive control of the joystick
637   */
638 static HRESULT WINAPI JoystickAImpl_Acquire(LPDIRECTINPUTDEVICE8A iface)
639 {
640     JoystickImpl *This = (JoystickImpl *)iface;
641     HRESULT res;
642
643     TRACE("(this=%p)\n",This);
644
645     if ((res = IDirectInputDevice2AImpl_Acquire(iface)) != DI_OK)
646     {
647         WARN("Failed to acquire: %x\n", res);
648         return res;
649     }
650
651     if ((This->joyfd = open(This->joydev->device, O_RDWR)) == -1)
652     {
653         if ((This->joyfd = open(This->joydev->device, O_RDONLY)) == -1)
654         {
655             /* Couldn't open the device at all */
656             ERR("Failed to open device %s: %d %s\n", This->joydev->device, errno, strerror(errno));
657             IDirectInputDevice2AImpl_Unacquire(iface);
658             return DIERR_NOTFOUND;
659         }
660     }
661     else
662     {
663         /* Couldn't open in r/w but opened in read-only. */
664         WARN("Could not open %s in read-write mode.  Force feedback will be disabled.\n", This->joydev->device);
665     }
666
667     return DI_OK;
668 }
669
670 /******************************************************************************
671   *     Unacquire : frees the joystick
672   */
673 static HRESULT WINAPI JoystickAImpl_Unacquire(LPDIRECTINPUTDEVICE8A iface)
674 {
675     JoystickImpl *This = (JoystickImpl *)iface;
676     HRESULT res;
677
678     TRACE("(this=%p)\n",This);
679     res = IDirectInputDevice2AImpl_Unacquire(iface);
680     if (res==DI_OK && This->joyfd!=-1) {
681       close(This->joyfd);
682       This->joyfd = -1;
683     }
684     return res;
685 }
686
687 /* 
688  * set the current state of the js device as it would be with the middle
689  * values on the axes
690  */
691 #define CENTER_AXIS(a) \
692     (ji->axes[a] == -1 ? 0 : joystick_map_axis( &ji->props[ji->axes[a]], \
693                                                 ji->joydev->axes[a].value ))
694 static void fake_current_js_state(JoystickImpl *ji)
695 {
696     int i;
697
698     /* center the axes */
699     ji->js.lX           = CENTER_AXIS(ABS_X);
700     ji->js.lY           = CENTER_AXIS(ABS_Y);
701     ji->js.lZ           = CENTER_AXIS(ABS_Z);
702     ji->js.lRx          = CENTER_AXIS(ABS_RX);
703     ji->js.lRy          = CENTER_AXIS(ABS_RY);
704     ji->js.lRz          = CENTER_AXIS(ABS_RZ);
705     ji->js.rglSlider[0] = CENTER_AXIS(ABS_THROTTLE);
706     ji->js.rglSlider[1] = CENTER_AXIS(ABS_RUDDER);
707
708     /* POV center is -1 */
709     for (i = 0; i < 4; i++)
710         ji->js.rgdwPOV[i] = -1;
711 }
712 #undef CENTER_AXIS
713
714 /* convert wine format offset to user format object index */
715 static void joy_polldev(JoystickImpl *This)
716 {
717     struct pollfd plfd;
718     struct input_event ie;
719
720     if (This->joyfd==-1)
721         return;
722
723     while (1)
724     {
725         LONG value = 0;
726         int inst_id = -1;
727
728         plfd.fd = This->joyfd;
729         plfd.events = POLLIN;
730
731         if (poll(&plfd,1,0) != 1)
732             return;
733
734         /* we have one event, so we can read */
735         if (sizeof(ie)!=read(This->joyfd,&ie,sizeof(ie)))
736             return;
737
738         TRACE("input_event: type %d, code %d, value %d\n",ie.type,ie.code,ie.value);
739         switch (ie.type) {
740         case EV_KEY:    /* button */
741         {
742             int btn = This->buttons[ie.code];
743
744             TRACE("(%p) %d -> %d\n", This, ie.code, btn);
745             if (btn & 0x80)
746             {
747                 btn &= 0x7F;
748                 inst_id = DIDFT_MAKEINSTANCE(btn) | DIDFT_PSHBUTTON;
749                 This->js.rgbButtons[btn] = value = ie.value ? 0x80 : 0x00;
750             }
751             break;
752         }
753         case EV_ABS:
754         {
755             int axis = This->axes[ie.code];
756             if (axis==-1) {
757                 break;
758             }
759             inst_id = DIDFT_MAKEINSTANCE(axis) | (ie.code < ABS_HAT0X ? DIDFT_ABSAXIS : DIDFT_POV);
760             value = joystick_map_axis(&This->props[id_to_object(This->base.data_format.wine_df, inst_id)], ie.value);
761
762             switch (ie.code) {
763             case ABS_X:         This->js.lX  = value; break;
764             case ABS_Y:         This->js.lY  = value; break;
765             case ABS_Z:         This->js.lZ  = value; break;
766             case ABS_RX:        This->js.lRx = value; break;
767             case ABS_RY:        This->js.lRy = value; break;
768             case ABS_RZ:        This->js.lRz = value; break;
769             case ABS_THROTTLE:  This->js.rglSlider[0] = value; break;
770             case ABS_RUDDER:    This->js.rglSlider[1] = value; break;
771             case ABS_HAT0X: case ABS_HAT0Y: case ABS_HAT1X: case ABS_HAT1Y:
772             case ABS_HAT2X: case ABS_HAT2Y: case ABS_HAT3X: case ABS_HAT3Y:
773             {
774                 int idx = (ie.code - ABS_HAT0X) / 2;
775
776                 if (ie.code % 2)
777                     This->povs[idx].y = ie.value;
778                 else
779                     This->povs[idx].x = ie.value;
780
781                 This->js.rgdwPOV[idx] = value = joystick_map_pov(&This->povs[idx]);
782                 break;
783             }
784             default:
785                 FIXME("unhandled joystick axis event (code %d, value %d)\n",ie.code,ie.value);
786             }
787             break;
788         }
789 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
790         case EV_FF_STATUS:
791             This->ff_state = ie.value;
792             break;
793 #endif
794 #ifdef EV_SYN
795         case EV_SYN:
796             /* there is nothing to do */
797             break;
798 #endif
799         default:
800             FIXME("joystick cannot handle type %d event (code %d)\n",ie.type,ie.code);
801             break;
802         }
803         if (inst_id >= 0)
804             queue_event((LPDIRECTINPUTDEVICE8A)This,
805                         id_to_offset(&This->base.data_format, inst_id),
806                         value, ie.time.tv_usec, This->base.dinput->evsequence++);
807     }
808 }
809
810 /******************************************************************************
811   *     GetDeviceState : returns the "state" of the joystick.
812   *
813   */
814 static HRESULT WINAPI JoystickAImpl_GetDeviceState(
815         LPDIRECTINPUTDEVICE8A iface,DWORD len,LPVOID ptr
816 ) {
817     JoystickImpl *This = (JoystickImpl *)iface;
818
819     TRACE("(this=%p,0x%08x,%p)\n", This, len, ptr);
820
821     if (!This->base.acquired)
822     {
823         WARN("not acquired\n");
824         return DIERR_NOTACQUIRED;
825     }
826
827     joy_polldev(This);
828
829     /* convert and copy data to user supplied buffer */
830     fill_DataFormat(ptr, len, &This->js, &This->base.data_format);
831
832     return DI_OK;
833 }
834
835 /******************************************************************************
836   *     SetProperty : change input device properties
837   */
838 static HRESULT WINAPI JoystickAImpl_SetProperty(LPDIRECTINPUTDEVICE8A iface,
839                                             REFGUID rguid,
840                                             LPCDIPROPHEADER ph)
841 {
842   JoystickImpl *This = (JoystickImpl *)iface;
843
844   if (!ph) {
845     WARN("invalid argument\n");
846     return DIERR_INVALIDPARAM;
847   }
848
849   TRACE("(this=%p,%s,%p)\n",This,debugstr_guid(rguid),ph);
850   TRACE("ph.dwSize = %d, ph.dwHeaderSize =%d, ph.dwObj = %d, ph.dwHow= %d\n",
851         ph->dwSize, ph->dwHeaderSize, ph->dwObj, ph->dwHow);
852
853   if (!HIWORD(rguid)) {
854     switch (LOWORD(rguid)) {
855     case (DWORD_PTR)DIPROP_RANGE: {
856       LPCDIPROPRANGE pr = (LPCDIPROPRANGE)ph;
857
858       if (ph->dwHow == DIPH_DEVICE) {
859         DWORD i;
860         TRACE("proprange(%d,%d) all\n", pr->lMin, pr->lMax);
861         for (i = 0; i < This->base.data_format.wine_df->dwNumObjs; i++) {
862           /* Scale dead-zone */
863           This->props[i].lDeadZone = MulDiv(This->props[i].lDeadZone, pr->lMax - pr->lMin,
864                                             This->props[i].lMax - This->props[i].lMin);
865           This->props[i].lMin = pr->lMin;
866           This->props[i].lMax = pr->lMax;
867         }
868       } else {
869         int obj = find_property(&This->base.data_format, ph);
870
871         TRACE("proprange(%d,%d) obj=%d\n", pr->lMin, pr->lMax, obj);
872         if (obj >= 0) {
873           /* Scale dead-zone */
874           This->props[obj].lDeadZone = MulDiv(This->props[obj].lDeadZone, pr->lMax - pr->lMin,
875                                               This->props[obj].lMax - This->props[obj].lMin);
876           This->props[obj].lMin = pr->lMin;
877           This->props[obj].lMax = pr->lMax;
878         }
879       }
880       fake_current_js_state(This);
881       break;
882     }
883     case (DWORD_PTR)DIPROP_DEADZONE: {
884       LPCDIPROPDWORD pd = (LPCDIPROPDWORD)ph;
885       if (ph->dwHow == DIPH_DEVICE) {
886         DWORD i;
887         TRACE("deadzone(%d) all\n", pd->dwData);
888         for (i = 0; i < This->base.data_format.wine_df->dwNumObjs; i++) {
889           This->props[i].lDeadZone = pd->dwData;
890         }
891       } else {
892         int obj = find_property(&This->base.data_format, ph);
893
894         TRACE("deadzone(%d) obj=%d\n", pd->dwData, obj);
895         if (obj >= 0) {
896           This->props[obj].lDeadZone = pd->dwData;
897         }
898       }
899       fake_current_js_state(This);
900       break;
901     }
902     case (DWORD_PTR)DIPROP_CALIBRATIONMODE: {
903       LPCDIPROPDWORD    pd = (LPCDIPROPDWORD)ph;
904       FIXME("DIPROP_CALIBRATIONMODE(%d)\n", pd->dwData);
905       break;
906     }
907     case (DWORD_PTR)DIPROP_AUTOCENTER: {
908       LPCDIPROPDWORD pd = (LPCDIPROPDWORD)ph;
909
910       FIXME("DIPROP_AUTOCENTER(%d)\n", pd->dwData);
911       break;
912     }
913     case (DWORD_PTR)DIPROP_SATURATION: {
914       LPCDIPROPDWORD pd = (LPCDIPROPDWORD)ph;
915
916       if (ph->dwHow == DIPH_DEVICE) {
917         DWORD i;
918
919         TRACE("saturation(%d) all\n", pd->dwData);
920         for (i = 0; i < This->base.data_format.wine_df->dwNumObjs; i++)
921           This->props[i].lSaturation = pd->dwData;
922       } else {
923           int obj = find_property(&This->base.data_format, ph);
924
925           if (obj < 0) return DIERR_OBJECTNOTFOUND;
926
927           TRACE("saturation(%d) obj=%d\n", pd->dwData, obj);
928           This->props[obj].lSaturation = pd->dwData;
929       }
930       fake_current_js_state(This);
931       break;
932     }
933     default:
934       return IDirectInputDevice2AImpl_SetProperty(iface, rguid, ph);
935     }
936   }
937   return DI_OK;
938 }
939
940 static HRESULT WINAPI JoystickAImpl_GetCapabilities(
941         LPDIRECTINPUTDEVICE8A iface,
942         LPDIDEVCAPS lpDIDevCaps)
943 {
944     JoystickImpl *This = (JoystickImpl *)iface;
945
946     TRACE("%p->(%p)\n",iface,lpDIDevCaps);
947
948     if (!lpDIDevCaps) {
949         WARN("invalid pointer\n");
950         return E_POINTER;
951     }
952
953     if (lpDIDevCaps->dwSize != sizeof(DIDEVCAPS)) {
954         WARN("invalid argument\n");
955         return DIERR_INVALIDPARAM;
956     }
957
958     lpDIDevCaps->dwFlags        = DIDC_ATTACHED;
959     if (This->base.dinput->dwVersion >= 0x0800)
960         lpDIDevCaps->dwDevType = DI8DEVTYPE_JOYSTICK | (DI8DEVTYPEJOYSTICK_STANDARD << 8);
961     else
962         lpDIDevCaps->dwDevType = DIDEVTYPE_JOYSTICK | (DIDEVTYPEJOYSTICK_TRADITIONAL << 8);
963
964     if (This->joydev->has_ff) 
965          lpDIDevCaps->dwFlags |= DIDC_FORCEFEEDBACK;
966
967     lpDIDevCaps->dwAxes = This->numAxes;
968     lpDIDevCaps->dwButtons = This->numButtons;
969     lpDIDevCaps->dwPOVs = This->numPOVs;
970
971     return DI_OK;
972 }
973
974 static HRESULT WINAPI JoystickAImpl_Poll(LPDIRECTINPUTDEVICE8A iface)
975 {
976     JoystickImpl *This = (JoystickImpl *)iface;
977
978     TRACE("(%p)\n",This);
979
980     if (!This->base.acquired)
981         return DIERR_NOTACQUIRED;
982
983     joy_polldev(This);
984     return DI_OK;
985 }
986
987 /******************************************************************************
988   *     GetProperty : get input device properties
989   */
990 static HRESULT WINAPI JoystickAImpl_GetProperty(LPDIRECTINPUTDEVICE8A iface,
991                                                 REFGUID rguid,
992                                                 LPDIPROPHEADER pdiph)
993 {
994     JoystickImpl *This = (JoystickImpl *)iface;
995
996     TRACE("(this=%p,%s,%p)\n", iface, debugstr_guid(rguid), pdiph);
997     _dump_DIPROPHEADER(pdiph);
998
999     if (HIWORD(rguid)) return DI_OK;
1000
1001     switch (LOWORD(rguid)) {
1002     case (DWORD_PTR) DIPROP_RANGE:
1003     {
1004         LPDIPROPRANGE pr = (LPDIPROPRANGE) pdiph;
1005         int obj = find_property(&This->base.data_format, pdiph);
1006
1007         if (obj < 0) return DIERR_OBJECTNOTFOUND;
1008
1009         pr->lMin = This->props[obj].lMin;
1010         pr->lMax = This->props[obj].lMax;
1011         TRACE("range(%d, %d) obj=%d\n", pr->lMin, pr->lMax, obj);
1012         break;
1013     }
1014     case (DWORD_PTR) DIPROP_DEADZONE:
1015     {
1016         LPDIPROPDWORD pd = (LPDIPROPDWORD)pdiph;
1017         int obj = find_property(&This->base.data_format, pdiph);
1018
1019         if (obj < 0) return DIERR_OBJECTNOTFOUND;
1020
1021         pd->dwData = This->props[obj].lDeadZone;
1022         TRACE("deadzone(%d) obj=%d\n", pd->dwData, obj);
1023         break;
1024     }
1025     case (DWORD_PTR) DIPROP_SATURATION:
1026     {
1027         LPDIPROPDWORD pd = (LPDIPROPDWORD)pdiph;
1028         int obj = find_property(&This->base.data_format, pdiph);
1029
1030         if (obj < 0) return DIERR_OBJECTNOTFOUND;
1031
1032         pd->dwData = This->props[obj].lSaturation;
1033         TRACE("saturation(%d) obj=%d\n", pd->dwData, obj);
1034         break;
1035     }
1036
1037     default:
1038         return IDirectInputDevice2AImpl_GetProperty(iface, rguid, pdiph);
1039     }
1040
1041     return DI_OK;
1042 }
1043
1044 /******************************************************************************
1045   *     GetObjectInfo : get information about a device object such as a button
1046   *                     or axis
1047   */
1048 static HRESULT WINAPI JoystickWImpl_GetObjectInfo(LPDIRECTINPUTDEVICE8W iface,
1049         LPDIDEVICEOBJECTINSTANCEW pdidoi, DWORD dwObj, DWORD dwHow)
1050 {
1051     static const WCHAR axisW[] = {'A','x','i','s',' ','%','d',0};
1052     static const WCHAR povW[] = {'P','O','V',' ','%','d',0};
1053     static const WCHAR buttonW[] = {'B','u','t','t','o','n',' ','%','d',0};
1054     HRESULT res;
1055
1056     res = IDirectInputDevice2WImpl_GetObjectInfo(iface, pdidoi, dwObj, dwHow);
1057     if (res != DI_OK) return res;
1058
1059     if      (pdidoi->dwType & DIDFT_AXIS)
1060         sprintfW(pdidoi->tszName, axisW, DIDFT_GETINSTANCE(pdidoi->dwType));
1061     else if (pdidoi->dwType & DIDFT_POV)
1062         sprintfW(pdidoi->tszName, povW, DIDFT_GETINSTANCE(pdidoi->dwType));
1063     else if (pdidoi->dwType & DIDFT_BUTTON)
1064         sprintfW(pdidoi->tszName, buttonW, DIDFT_GETINSTANCE(pdidoi->dwType));
1065
1066     _dump_OBJECTINSTANCEW(pdidoi);
1067     return res;
1068 }
1069
1070 static HRESULT WINAPI JoystickAImpl_GetObjectInfo(LPDIRECTINPUTDEVICE8A iface,
1071         LPDIDEVICEOBJECTINSTANCEA pdidoi, DWORD dwObj, DWORD dwHow)
1072 {
1073     HRESULT res;
1074     DIDEVICEOBJECTINSTANCEW didoiW;
1075     DWORD dwSize = pdidoi->dwSize;
1076
1077     didoiW.dwSize = sizeof(didoiW);
1078     res = JoystickWImpl_GetObjectInfo((LPDIRECTINPUTDEVICE8W)iface, &didoiW, dwObj, dwHow);
1079     if (res != DI_OK) return res;
1080
1081     memset(pdidoi, 0, pdidoi->dwSize);
1082     memcpy(pdidoi, &didoiW, FIELD_OFFSET(DIDEVICEOBJECTINSTANCEW, tszName));
1083     pdidoi->dwSize = dwSize;
1084     WideCharToMultiByte(CP_ACP, 0, didoiW.tszName, -1, pdidoi->tszName,
1085                         sizeof(pdidoi->tszName), NULL, NULL);
1086
1087     return res;
1088 }
1089
1090 /****************************************************************************** 
1091   *     CreateEffect - Create a new FF effect with the specified params
1092   */
1093 static HRESULT WINAPI JoystickAImpl_CreateEffect(LPDIRECTINPUTDEVICE8A iface,
1094                                                  REFGUID rguid,
1095                                                  LPCDIEFFECT lpeff,
1096                                                  LPDIRECTINPUTEFFECT *ppdef,
1097                                                  LPUNKNOWN pUnkOuter)
1098 {
1099 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
1100     effect_list_item* new_effect = NULL;
1101     HRESULT retval = DI_OK;
1102 #endif
1103
1104     JoystickImpl* This = (JoystickImpl*)iface;
1105     TRACE("(this=%p,%p,%p,%p,%p)\n", This, rguid, lpeff, ppdef, pUnkOuter);
1106
1107 #ifndef HAVE_STRUCT_FF_EFFECT_DIRECTION
1108     TRACE("not available (compiled w/o ff support)\n");
1109     *ppdef = NULL;
1110     return DI_OK;
1111 #else
1112
1113     if (!(new_effect = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_effect))))
1114         return DIERR_OUTOFMEMORY;
1115
1116     retval = linuxinput_create_effect(&This->joyfd, rguid, &new_effect->entry, &new_effect->ref);
1117     if (retval != DI_OK)
1118     {
1119         HeapFree(GetProcessHeap(), 0, new_effect);
1120         return retval;
1121     }
1122
1123     if (lpeff != NULL)
1124     {
1125         retval = IDirectInputEffect_SetParameters(new_effect->ref, lpeff, 0);
1126
1127         if (retval != DI_OK && retval != DI_DOWNLOADSKIPPED)
1128         {
1129             HeapFree(GetProcessHeap(), 0, new_effect);
1130             return retval;
1131         }
1132     }
1133
1134     list_add_tail(&This->ff_effects, &new_effect->entry);
1135     *ppdef = new_effect->ref;
1136
1137     if (pUnkOuter != NULL)
1138         FIXME("Interface aggregation not implemented.\n");
1139
1140     return DI_OK;
1141
1142 #endif /* HAVE_STRUCT_FF_EFFECT_DIRECTION */
1143
1144
1145 /*******************************************************************************
1146  *      EnumEffects - Enumerate available FF effects
1147  */
1148 static HRESULT WINAPI JoystickAImpl_EnumEffects(LPDIRECTINPUTDEVICE8A iface,
1149                                                 LPDIENUMEFFECTSCALLBACKA lpCallback,
1150                                                 LPVOID pvRef,
1151                                                 DWORD dwEffType)
1152 {
1153 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
1154     DIEFFECTINFOA dei; /* feif */
1155     DWORD type = DIEFT_GETTYPE(dwEffType);
1156     JoystickImpl* This = (JoystickImpl*)iface;
1157
1158     TRACE("(this=%p,%p,%d) type=%d\n", This, pvRef, dwEffType, type);
1159
1160     dei.dwSize = sizeof(DIEFFECTINFOA);          
1161
1162     if ((type == DIEFT_ALL || type == DIEFT_CONSTANTFORCE)
1163         && test_bit(This->joydev->ffbits, FF_CONSTANT)) {
1164         IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_ConstantForce);
1165         (*lpCallback)(&dei, pvRef);
1166     }
1167
1168     if ((type == DIEFT_ALL || type == DIEFT_PERIODIC)
1169         && test_bit(This->joydev->ffbits, FF_PERIODIC)) {
1170         if (test_bit(This->joydev->ffbits, FF_SQUARE)) {
1171             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Square);
1172             (*lpCallback)(&dei, pvRef);
1173         }
1174         if (test_bit(This->joydev->ffbits, FF_SINE)) {
1175             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Sine);
1176             (*lpCallback)(&dei, pvRef);
1177         }
1178         if (test_bit(This->joydev->ffbits, FF_TRIANGLE)) {
1179             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Triangle);
1180             (*lpCallback)(&dei, pvRef);
1181         }
1182         if (test_bit(This->joydev->ffbits, FF_SAW_UP)) {
1183             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_SawtoothUp);
1184             (*lpCallback)(&dei, pvRef);
1185         }
1186         if (test_bit(This->joydev->ffbits, FF_SAW_DOWN)) {
1187             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_SawtoothDown);
1188             (*lpCallback)(&dei, pvRef);
1189         }
1190     } 
1191
1192     if ((type == DIEFT_ALL || type == DIEFT_RAMPFORCE)
1193         && test_bit(This->joydev->ffbits, FF_RAMP)) {
1194         IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_RampForce);
1195         (*lpCallback)(&dei, pvRef);
1196     }
1197
1198     if (type == DIEFT_ALL || type == DIEFT_CONDITION) {
1199         if (test_bit(This->joydev->ffbits, FF_SPRING)) {
1200             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Spring);
1201             (*lpCallback)(&dei, pvRef);
1202         }
1203         if (test_bit(This->joydev->ffbits, FF_DAMPER)) {
1204             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Damper);
1205             (*lpCallback)(&dei, pvRef);
1206         }
1207         if (test_bit(This->joydev->ffbits, FF_INERTIA)) {
1208             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Inertia);
1209             (*lpCallback)(&dei, pvRef);
1210         }
1211         if (test_bit(This->joydev->ffbits, FF_FRICTION)) {
1212             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Friction);
1213             (*lpCallback)(&dei, pvRef);
1214         }
1215     }
1216
1217 #endif
1218
1219     return DI_OK;
1220 }
1221
1222 static HRESULT WINAPI JoystickWImpl_EnumEffects(LPDIRECTINPUTDEVICE8W iface,
1223                                                 LPDIENUMEFFECTSCALLBACKW lpCallback,
1224                                                 LPVOID pvRef,
1225                                                 DWORD dwEffType)
1226 {
1227 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
1228     /* seems silly to duplicate all this code but all the structures and functions
1229      * are actually different (A/W) */
1230     DIEFFECTINFOW dei; /* feif */
1231     DWORD type = DIEFT_GETTYPE(dwEffType);
1232     JoystickImpl* This = (JoystickImpl*)iface;
1233     int xfd = This->joyfd;
1234
1235     TRACE("(this=%p,%p,%d) type=%d fd=%d\n", This, pvRef, dwEffType, type, xfd);
1236
1237     dei.dwSize = sizeof(DIEFFECTINFOW);          
1238
1239     if ((type == DIEFT_ALL || type == DIEFT_CONSTANTFORCE)
1240         && test_bit(This->joydev->ffbits, FF_CONSTANT)) {
1241         IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_ConstantForce);
1242         (*lpCallback)(&dei, pvRef);
1243     }
1244
1245     if ((type == DIEFT_ALL || type == DIEFT_PERIODIC)
1246         && test_bit(This->joydev->ffbits, FF_PERIODIC)) {
1247         if (test_bit(This->joydev->ffbits, FF_SQUARE)) {
1248             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Square);
1249             (*lpCallback)(&dei, pvRef);
1250         }
1251         if (test_bit(This->joydev->ffbits, FF_SINE)) {
1252             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Sine);
1253             (*lpCallback)(&dei, pvRef);
1254         }
1255         if (test_bit(This->joydev->ffbits, FF_TRIANGLE)) {
1256             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Triangle);
1257             (*lpCallback)(&dei, pvRef);
1258         }
1259         if (test_bit(This->joydev->ffbits, FF_SAW_UP)) {
1260             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_SawtoothUp);
1261             (*lpCallback)(&dei, pvRef);
1262         }
1263         if (test_bit(This->joydev->ffbits, FF_SAW_DOWN)) {
1264             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_SawtoothDown);
1265             (*lpCallback)(&dei, pvRef);
1266         }
1267     } 
1268
1269     if ((type == DIEFT_ALL || type == DIEFT_RAMPFORCE)
1270         && test_bit(This->joydev->ffbits, FF_RAMP)) {
1271         IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_RampForce);
1272         (*lpCallback)(&dei, pvRef);
1273     }
1274
1275     if (type == DIEFT_ALL || type == DIEFT_CONDITION) {
1276         if (test_bit(This->joydev->ffbits, FF_SPRING)) {
1277             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Spring);
1278             (*lpCallback)(&dei, pvRef);
1279         }
1280         if (test_bit(This->joydev->ffbits, FF_DAMPER)) {
1281             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Damper);
1282             (*lpCallback)(&dei, pvRef);
1283         }
1284         if (test_bit(This->joydev->ffbits, FF_INERTIA)) {
1285             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Inertia);
1286             (*lpCallback)(&dei, pvRef);
1287         }
1288         if (test_bit(This->joydev->ffbits, FF_FRICTION)) {
1289             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Friction);
1290             (*lpCallback)(&dei, pvRef);
1291         }
1292     }
1293
1294     /* return to unacquired state if that's where it was */
1295     if (xfd == -1)
1296         IDirectInputDevice8_Unacquire(iface);
1297 #endif
1298
1299     return DI_OK;
1300 }
1301
1302 /*******************************************************************************
1303  *      GetEffectInfo - Get information about a particular effect 
1304  */
1305 static HRESULT WINAPI JoystickAImpl_GetEffectInfo(LPDIRECTINPUTDEVICE8A iface,
1306                                                   LPDIEFFECTINFOA pdei,
1307                                                   REFGUID guid)
1308 {
1309     JoystickImpl* This = (JoystickImpl*)iface;
1310
1311     TRACE("(this=%p,%p,%s)\n", This, pdei, _dump_dinput_GUID(guid));
1312
1313 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
1314     return linuxinput_get_info_A(This->joyfd, guid, pdei); 
1315 #else
1316     return DI_OK;
1317 #endif
1318 }
1319
1320 static HRESULT WINAPI JoystickWImpl_GetEffectInfo(LPDIRECTINPUTDEVICE8W iface,
1321                                                   LPDIEFFECTINFOW pdei,
1322                                                   REFGUID guid)
1323 {
1324     JoystickImpl* This = (JoystickImpl*)iface;
1325             
1326     TRACE("(this=%p,%p,%s)\n", This, pdei, _dump_dinput_GUID(guid));
1327         
1328 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
1329     return linuxinput_get_info_W(This->joyfd, guid, pdei);
1330 #else
1331     return DI_OK;
1332 #endif
1333 }
1334
1335 /*******************************************************************************
1336  *      GetForceFeedbackState - Get information about the device's FF state 
1337  */
1338 static HRESULT WINAPI JoystickAImpl_GetForceFeedbackState(
1339         LPDIRECTINPUTDEVICE8A iface,
1340         LPDWORD pdwOut)
1341 {
1342     JoystickImpl* This = (JoystickImpl*)iface;
1343
1344     TRACE("(this=%p,%p)\n", This, pdwOut);
1345
1346     (*pdwOut) = 0;
1347
1348 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
1349     /* DIGFFS_STOPPED is the only mandatory flag to report */
1350     if (This->ff_state == FF_STATUS_STOPPED)
1351         (*pdwOut) |= DIGFFS_STOPPED;
1352 #endif
1353
1354     return DI_OK;
1355 }
1356
1357 /*******************************************************************************
1358  *      SendForceFeedbackCommand - Send a command to the device's FF system
1359  */
1360 static HRESULT WINAPI JoystickAImpl_SendForceFeedbackCommand(
1361         LPDIRECTINPUTDEVICE8A iface,
1362         DWORD dwFlags)
1363 {
1364     JoystickImpl* This = (JoystickImpl*)iface;
1365     TRACE("(this=%p,%d)\n", This, dwFlags);
1366
1367 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
1368     switch (dwFlags)
1369     {
1370     case DISFFC_STOPALL:
1371     {
1372         /* Stop all effects */
1373         effect_list_item *itr;
1374
1375         LIST_FOR_EACH_ENTRY(itr, &This->ff_effects, effect_list_item, entry)
1376             IDirectInputEffect_Stop(itr->ref);
1377         break;
1378     }
1379
1380     case DISFFC_RESET:
1381     {
1382         effect_list_item *itr, *ptr;
1383
1384         /* Stop, unload, release and free all effects */
1385         /* This returns the device to its "bare" state */
1386         LIST_FOR_EACH_ENTRY_SAFE(itr, ptr, &This->ff_effects, effect_list_item, entry)
1387             IDirectInputEffect_Release(itr->ref);
1388         break;
1389     }
1390     case DISFFC_PAUSE:
1391     case DISFFC_CONTINUE:
1392         FIXME("No support for Pause or Continue in linux\n");
1393         break;
1394
1395     case DISFFC_SETACTUATORSOFF:
1396     case DISFFC_SETACTUATORSON:
1397         FIXME("No direct actuator control in linux\n");
1398         break;
1399
1400     default:
1401         FIXME("Unknown Force Feedback Command!\n");
1402         return DIERR_INVALIDPARAM;
1403     }
1404     return DI_OK;
1405 #else
1406     return DIERR_UNSUPPORTED;
1407 #endif
1408 }
1409
1410 /*******************************************************************************
1411  *      EnumCreatedEffectObjects - Enumerate all the effects that have been
1412  *              created for this device.
1413  */
1414 static HRESULT WINAPI JoystickAImpl_EnumCreatedEffectObjects(
1415         LPDIRECTINPUTDEVICE8A iface,
1416         LPDIENUMCREATEDEFFECTOBJECTSCALLBACK lpCallback,
1417         LPVOID pvRef,
1418         DWORD dwFlags)
1419 {
1420     /* this function is safe to call on non-ff-enabled builds */
1421     JoystickImpl* This = (JoystickImpl*)iface;
1422     effect_list_item *itr, *ptr;
1423
1424     TRACE("(this=%p,%p,%p,%d)\n", This, lpCallback, pvRef, dwFlags);
1425
1426     if (!lpCallback)
1427         return DIERR_INVALIDPARAM;
1428
1429     if (dwFlags != 0)
1430         FIXME("Flags specified, but no flags exist yet (DX9)!\n");
1431
1432     LIST_FOR_EACH_ENTRY_SAFE(itr, ptr, &This->ff_effects, effect_list_item, entry)
1433         (*lpCallback)(itr->ref, pvRef);
1434
1435     return DI_OK;
1436 }
1437
1438 /******************************************************************************
1439   *     GetDeviceInfo : get information about a device's identity
1440   */
1441 static HRESULT WINAPI JoystickAImpl_GetDeviceInfo(LPDIRECTINPUTDEVICE8A iface,
1442                                                   LPDIDEVICEINSTANCEA pdidi)
1443 {
1444     JoystickImpl *This = (JoystickImpl *)iface;
1445
1446     TRACE("(%p) %p\n", This, pdidi);
1447
1448     if (pdidi == NULL) return E_POINTER;
1449     if ((pdidi->dwSize != sizeof(DIDEVICEINSTANCE_DX3A)) &&
1450         (pdidi->dwSize != sizeof(DIDEVICEINSTANCEA)))
1451         return DIERR_INVALIDPARAM;
1452
1453     fill_joystick_dideviceinstanceA(pdidi, This->base.dinput->dwVersion,
1454                                     get_joystick_index(&This->base.guid));
1455     return DI_OK;
1456 }
1457
1458 static HRESULT WINAPI JoystickWImpl_GetDeviceInfo(LPDIRECTINPUTDEVICE8W iface,
1459                                                   LPDIDEVICEINSTANCEW pdidi)
1460 {
1461     JoystickImpl *This = (JoystickImpl *)iface;
1462
1463     TRACE("(%p) %p\n", This, pdidi);
1464
1465     if (pdidi == NULL) return E_POINTER;
1466     if ((pdidi->dwSize != sizeof(DIDEVICEINSTANCE_DX3W)) &&
1467         (pdidi->dwSize != sizeof(DIDEVICEINSTANCEW)))
1468         return DIERR_INVALIDPARAM;
1469
1470     fill_joystick_dideviceinstanceW(pdidi, This->base.dinput->dwVersion,
1471                                     get_joystick_index(&This->base.guid));
1472     return DI_OK;
1473 }
1474
1475 static const IDirectInputDevice8AVtbl JoystickAvt =
1476 {
1477         IDirectInputDevice2AImpl_QueryInterface,
1478         IDirectInputDevice2AImpl_AddRef,
1479         IDirectInputDevice2AImpl_Release,
1480         JoystickAImpl_GetCapabilities,
1481         IDirectInputDevice2AImpl_EnumObjects,
1482         JoystickAImpl_GetProperty,
1483         JoystickAImpl_SetProperty,
1484         JoystickAImpl_Acquire,
1485         JoystickAImpl_Unacquire,
1486         JoystickAImpl_GetDeviceState,
1487         IDirectInputDevice2AImpl_GetDeviceData,
1488         IDirectInputDevice2AImpl_SetDataFormat,
1489         IDirectInputDevice2AImpl_SetEventNotification,
1490         IDirectInputDevice2AImpl_SetCooperativeLevel,
1491         JoystickAImpl_GetObjectInfo,
1492         JoystickAImpl_GetDeviceInfo,
1493         IDirectInputDevice2AImpl_RunControlPanel,
1494         IDirectInputDevice2AImpl_Initialize,
1495         JoystickAImpl_CreateEffect,
1496         JoystickAImpl_EnumEffects,
1497         JoystickAImpl_GetEffectInfo,
1498         JoystickAImpl_GetForceFeedbackState,
1499         JoystickAImpl_SendForceFeedbackCommand,
1500         JoystickAImpl_EnumCreatedEffectObjects,
1501         IDirectInputDevice2AImpl_Escape,
1502         JoystickAImpl_Poll,
1503         IDirectInputDevice2AImpl_SendDeviceData,
1504         IDirectInputDevice7AImpl_EnumEffectsInFile,
1505         IDirectInputDevice7AImpl_WriteEffectToFile,
1506         IDirectInputDevice8AImpl_BuildActionMap,
1507         IDirectInputDevice8AImpl_SetActionMap,
1508         IDirectInputDevice8AImpl_GetImageInfo
1509 };
1510
1511 #if !defined(__STRICT_ANSI__) && defined(__GNUC__)
1512 # define XCAST(fun)     (typeof(JoystickWvt.fun))
1513 #else
1514 # define XCAST(fun)     (void*)
1515 #endif
1516
1517 static const IDirectInputDevice8WVtbl JoystickWvt =
1518 {
1519         IDirectInputDevice2WImpl_QueryInterface,
1520         XCAST(AddRef)IDirectInputDevice2AImpl_AddRef,
1521         XCAST(Release)IDirectInputDevice2AImpl_Release,
1522         XCAST(GetCapabilities)JoystickAImpl_GetCapabilities,
1523         IDirectInputDevice2WImpl_EnumObjects,
1524         XCAST(GetProperty)JoystickAImpl_GetProperty,
1525         XCAST(SetProperty)JoystickAImpl_SetProperty,
1526         XCAST(Acquire)JoystickAImpl_Acquire,
1527         XCAST(Unacquire)JoystickAImpl_Unacquire,
1528         XCAST(GetDeviceState)JoystickAImpl_GetDeviceState,
1529         XCAST(GetDeviceData)IDirectInputDevice2AImpl_GetDeviceData,
1530         XCAST(SetDataFormat)IDirectInputDevice2AImpl_SetDataFormat,
1531         XCAST(SetEventNotification)IDirectInputDevice2AImpl_SetEventNotification,
1532         XCAST(SetCooperativeLevel)IDirectInputDevice2AImpl_SetCooperativeLevel,
1533         JoystickWImpl_GetObjectInfo,
1534         JoystickWImpl_GetDeviceInfo,
1535         XCAST(RunControlPanel)IDirectInputDevice2AImpl_RunControlPanel,
1536         XCAST(Initialize)IDirectInputDevice2AImpl_Initialize,
1537         XCAST(CreateEffect)JoystickAImpl_CreateEffect,
1538         JoystickWImpl_EnumEffects,
1539         JoystickWImpl_GetEffectInfo,
1540         XCAST(GetForceFeedbackState)JoystickAImpl_GetForceFeedbackState,
1541         XCAST(SendForceFeedbackCommand)JoystickAImpl_SendForceFeedbackCommand,
1542         XCAST(EnumCreatedEffectObjects)JoystickAImpl_EnumCreatedEffectObjects,
1543         XCAST(Escape)IDirectInputDevice2AImpl_Escape,
1544         XCAST(Poll)JoystickAImpl_Poll,
1545         XCAST(SendDeviceData)IDirectInputDevice2AImpl_SendDeviceData,
1546         IDirectInputDevice7WImpl_EnumEffectsInFile,
1547         IDirectInputDevice7WImpl_WriteEffectToFile,
1548         IDirectInputDevice8WImpl_BuildActionMap,
1549         IDirectInputDevice8WImpl_SetActionMap,
1550         IDirectInputDevice8WImpl_GetImageInfo
1551 };
1552 #undef XCAST
1553
1554 #else  /* HAVE_CORRECT_LINUXINPUT_H */
1555
1556 const struct dinput_device joystick_linuxinput_device = {
1557   "Wine Linux-input joystick driver",
1558   NULL,
1559   NULL,
1560   NULL,
1561   NULL
1562 };
1563
1564 #endif  /* HAVE_CORRECT_LINUXINPUT_H */