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