dinput: Dynamic handling of buttons of a device.
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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 # if defined(EVIOCGBIT) && defined(EV_ABS) && defined(BTN_PINKIE)
48 #  define HAVE_CORRECT_LINUXINPUT_H
49 # endif
50 #endif
51
52 #include "wine/debug.h"
53 #include "wine/unicode.h"
54 #include "windef.h"
55 #include "winbase.h"
56 #include "winerror.h"
57 #include "dinput.h"
58
59 #include "dinput_private.h"
60 #include "device_private.h"
61
62 WINE_DEFAULT_DEBUG_CHANNEL(dinput);
63
64 #ifdef HAVE_CORRECT_LINUXINPUT_H
65
66 #define EVDEVPREFIX     "/dev/input/event"
67
68 /* Wine joystick driver object instances */
69 #define WINE_JOYSTICK_AXIS_BASE   0
70 #define WINE_JOYSTICK_BUTTON_BASE 8
71
72 typedef struct EffectListItem EffectListItem;
73 struct EffectListItem
74 {
75         LPDIRECTINPUTEFFECT ref;
76         struct EffectListItem* next;
77 };
78
79 /* implemented in effect_linuxinput.c */
80 HRESULT linuxinput_create_effect(int* fd, REFGUID rguid, LPDIRECTINPUTEFFECT* peff);
81 HRESULT linuxinput_get_info_A(int fd, REFGUID rguid, LPDIEFFECTINFOA info);
82 HRESULT linuxinput_get_info_W(int fd, REFGUID rguid, LPDIEFFECTINFOW info);
83
84 typedef struct JoystickImpl JoystickImpl;
85 static const IDirectInputDevice8AVtbl JoystickAvt;
86 static const IDirectInputDevice8WVtbl JoystickWvt;
87 struct JoystickImpl
88 {
89         const void                     *lpVtbl;
90         LONG                            ref;
91         GUID                            guid;
92
93
94         /* The 'parent' DInput */
95         IDirectInputImpl               *dinput;
96
97         /* joystick private */
98         /* what range and deadzone the game wants */
99         LONG                            wantmin[ABS_MAX];
100         LONG                            wantmax[ABS_MAX];
101         LONG                            deadz[ABS_MAX];
102
103         /* autodetecting ranges per axe by following movement */
104         LONG                            havemax[ABS_MAX];
105         LONG                            havemin[ABS_MAX];
106
107         int                             joyfd;
108
109         LPDIDATAFORMAT                  df;
110         HANDLE                          hEvent;
111         LPDIDEVICEOBJECTDATA            data_queue;
112         int                             queue_head, queue_tail, queue_len;
113         BOOL                            overflow;
114         DIJOYSTATE2                     js;
115
116         /* Force feedback variables */
117         BOOL                            has_ff;
118         int                             num_effects;
119         EffectListItem*                 top_effect;
120         int                             ff_state;
121
122         /* data returned by the EVIOCGABS() ioctl */
123         int                             axes[ABS_MAX][5];
124         /* LUT for KEY_ to offset in rgbButtons */
125         BYTE                            buttons[KEY_MAX];
126
127 #define AXE_ABS         0
128 #define AXE_ABSMIN      1
129 #define AXE_ABSMAX      2
130 #define AXE_ABSFUZZ     3
131 #define AXE_ABSFLAT     4
132
133
134         /* data returned by EVIOCGBIT for caps, EV_ABS, EV_KEY, and EV_FF */
135         BYTE                            evbits[(EV_MAX+7)/8];
136         BYTE                            absbits[(ABS_MAX+7)/8];
137         BYTE                            keybits[(KEY_MAX+7)/8];
138         BYTE                            ffbits[(FF_MAX+7)/8];   
139 };
140
141 /* This GUID is slightly different from the linux joystick one. Take note. */
142 static GUID DInput_Wine_Joystick_GUID = { /* 9e573eda-7734-11d2-8d4a-23903fb6bdf7 */
143   0x9e573eda,
144   0x7734,
145   0x11d2,
146   {0x8d, 0x4a, 0x23, 0x90, 0x3f, 0xb6, 0xbd, 0xf7}
147 };
148
149 static void fake_current_js_state(JoystickImpl *ji);
150 static int find_property_offset(JoystickImpl *This, LPCDIPROPHEADER ph);
151
152 #define test_bit(arr,bit) (((BYTE*)arr)[bit>>3]&(1<<(bit&7)))
153
154 static int joydev_have(BOOL require_ff)
155 {
156   int i, fd, flags, num_effects;
157   int havejoy = 0;
158
159   for (i=0;i<64;i++) {
160       char      buf[200];
161       BYTE      absbits[(ABS_MAX+7)/8],keybits[(KEY_MAX+7)/8];
162       BYTE      evbits[(EV_MAX+7)/8],ffbits[(FF_MAX+7)/8];
163
164       sprintf(buf,EVDEVPREFIX"%d",i);
165
166       if (require_ff) 
167           flags = O_RDWR;
168       else
169           flags = O_RDONLY;
170
171       if (-1!=(fd=open(buf,flags))) {
172           if (-1==ioctl(fd,EVIOCGBIT(EV_ABS,sizeof(absbits)),absbits)) {
173               perror("EVIOCGBIT EV_ABS");
174               close(fd);
175               continue;
176           }
177           if (-1==ioctl(fd,EVIOCGBIT(EV_KEY,sizeof(keybits)),keybits)) {
178               perror("EVIOCGBIT EV_KEY");
179               close(fd);
180               continue;
181           }
182
183           /* test for force feedback if it's required */
184           if (require_ff) {
185               if ((-1==ioctl(fd,EVIOCGBIT(0,sizeof(evbits)),evbits))) {
186                   perror("EVIOCGBIT 0");
187                   close(fd);
188                   continue; 
189               }
190               if (   (!test_bit(evbits,EV_FF))
191                   || (-1==ioctl(fd,EVIOCGBIT(EV_FF,sizeof(ffbits)),ffbits)) 
192                   || (-1==ioctl(fd,EVIOCGEFFECTS,&num_effects))
193                   || (num_effects <= 0)) {
194                   close(fd);
195                   continue;
196               }
197           }
198
199           /* A true joystick has at least axis X and Y, and at least 1
200            * button. copied from linux/drivers/input/joydev.c */
201           if (test_bit(absbits,ABS_X) && test_bit(absbits,ABS_Y) &&
202               (   test_bit(keybits,BTN_TRIGGER) ||
203                   test_bit(keybits,BTN_A)       ||
204                   test_bit(keybits,BTN_1)
205               )
206           ) {
207               FIXME("found a joystick at %s!\n",buf);
208               havejoy = 1;
209           }
210           close(fd);
211       }
212       if (havejoy || (errno==ENODEV))
213           break;
214   }
215   return havejoy;
216 }
217
218 static BOOL joydev_enum_deviceA(DWORD dwDevType, DWORD dwFlags, LPDIDEVICEINSTANCEA lpddi, DWORD version, int id)
219 {
220   int havejoy = 0;
221
222   if (id != 0)
223       return FALSE;
224
225   if (!((dwDevType == 0) ||
226         ((dwDevType == DIDEVTYPE_JOYSTICK) && (version < 0x0800)) ||
227         (((dwDevType == DI8DEVCLASS_GAMECTRL) || (dwDevType == DI8DEVTYPE_JOYSTICK)) && (version >= 0x0800))))
228     return FALSE;
229
230 #ifndef HAVE_STRUCT_FF_EFFECT_DIRECTION
231   if (dwFlags & DIEDFL_FORCEFEEDBACK)
232     return FALSE;
233 #endif
234
235   havejoy = joydev_have(dwFlags & DIEDFL_FORCEFEEDBACK);
236
237   if (!havejoy)
238       return FALSE;
239
240   TRACE("Enumerating the linuxinput Joystick device\n");
241
242   /* Return joystick */
243   lpddi->guidInstance   = GUID_Joystick;
244   lpddi->guidProduct    = DInput_Wine_Joystick_GUID;
245
246   lpddi->guidFFDriver = GUID_NULL;
247   if (version >= 0x0800)
248     lpddi->dwDevType    = DI8DEVTYPE_JOYSTICK | (DI8DEVTYPEJOYSTICK_STANDARD << 8);
249   else
250     lpddi->dwDevType    = DIDEVTYPE_JOYSTICK | (DIDEVTYPEJOYSTICK_TRADITIONAL << 8);
251
252   strcpy(lpddi->tszInstanceName, "Joystick");
253   /* ioctl JSIOCGNAME(len) */
254   strcpy(lpddi->tszProductName, "Wine Joystick");
255   return TRUE;
256 }
257
258 static BOOL joydev_enum_deviceW(DWORD dwDevType, DWORD dwFlags, LPDIDEVICEINSTANCEW lpddi, DWORD version, int id)
259 {
260   int havejoy = 0;
261
262   if (id != 0)
263       return FALSE;
264
265   if (!((dwDevType == 0) ||
266         ((dwDevType == DIDEVTYPE_JOYSTICK) && (version < 0x0800)) ||
267         (((dwDevType == DI8DEVCLASS_GAMECTRL) || (dwDevType == DI8DEVTYPE_JOYSTICK)) && (version >= 0x0800))))
268     return FALSE;
269
270 #ifndef HAVE_STRUCT_FF_EFFECT_DIRECTION
271   if (dwFlags & DIEDFL_FORCEFEEDBACK)
272     return FALSE;
273 #endif
274
275   havejoy = joydev_have(dwFlags & DIEDFL_FORCEFEEDBACK);
276
277   if (!havejoy)
278       return FALSE;
279
280   TRACE("Enumerating the linuxinput Joystick device\n");
281
282   /* Return joystick */
283   lpddi->guidInstance   = GUID_Joystick;
284   lpddi->guidProduct    = DInput_Wine_Joystick_GUID;
285
286   lpddi->guidFFDriver = GUID_NULL;
287   if (version >= 0x0800)
288     lpddi->dwDevType    = DI8DEVTYPE_JOYSTICK | (DI8DEVTYPEJOYSTICK_STANDARD << 8);
289   else
290     lpddi->dwDevType    = DIDEVTYPE_JOYSTICK | (DIDEVTYPEJOYSTICK_TRADITIONAL << 8);
291
292   MultiByteToWideChar(CP_ACP, 0, "Joystick", -1, lpddi->tszInstanceName, MAX_PATH);
293   /* ioctl JSIOCGNAME(len) */
294   MultiByteToWideChar(CP_ACP, 0, "Wine Joystick", -1, lpddi->tszProductName, MAX_PATH);
295   return TRUE;
296 }
297
298 static JoystickImpl *alloc_device(REFGUID rguid, const void *jvt, IDirectInputImpl *dinput)
299 {
300   JoystickImpl* newDevice;
301   int i;
302
303   newDevice = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(JoystickImpl));
304   newDevice->lpVtbl = jvt;
305   newDevice->ref = 1;
306   newDevice->joyfd = -1;
307   newDevice->dinput = dinput;
308 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
309   newDevice->ff_state = FF_STATUS_STOPPED;
310 #endif
311   memcpy(&(newDevice->guid),rguid,sizeof(*rguid));
312   for (i=0;i<ABS_MAX;i++) {
313     newDevice->wantmin[i] = -32768;
314     newDevice->wantmax[i] =  32767;
315     /* TODO: 
316      * direct input defines a default for the deadzone somewhere; but as long
317      * as in map_axis the code for the dead zone is commented out its no
318      * problem
319      */
320     newDevice->deadz[i]   =  0;
321   }
322   fake_current_js_state(newDevice);
323   return newDevice;
324 }
325
326 static HRESULT joydev_create_deviceA(IDirectInputImpl *dinput, REFGUID rguid, REFIID riid, LPDIRECTINPUTDEVICEA* pdev)
327 {
328   int havejoy = 0;
329
330   havejoy = joydev_have(FALSE);
331
332   if (!havejoy)
333       return DIERR_DEVICENOTREG;
334
335   if ((IsEqualGUID(&GUID_Joystick,rguid)) ||
336       (IsEqualGUID(&DInput_Wine_Joystick_GUID,rguid))) {
337     if ((riid == NULL) ||
338         IsEqualGUID(&IID_IDirectInputDeviceA,riid) ||
339         IsEqualGUID(&IID_IDirectInputDevice2A,riid) ||
340         IsEqualGUID(&IID_IDirectInputDevice7A,riid) ||
341         IsEqualGUID(&IID_IDirectInputDevice8A,riid)) {
342       *pdev = (IDirectInputDeviceA*) alloc_device(rguid, &JoystickAvt, dinput);
343       TRACE("Creating a Joystick device (%p)\n", *pdev);
344       return DI_OK;
345     } else
346       return DIERR_NOINTERFACE;
347   }
348
349   return DIERR_DEVICENOTREG;
350 }
351
352
353 static HRESULT joydev_create_deviceW(IDirectInputImpl *dinput, REFGUID rguid, REFIID riid, LPDIRECTINPUTDEVICEW* pdev)
354 {
355   int havejoy = 0;
356
357   havejoy = joydev_have(FALSE);
358
359   if (!havejoy)
360       return DIERR_DEVICENOTREG;
361
362   if ((IsEqualGUID(&GUID_Joystick,rguid)) ||
363       (IsEqualGUID(&DInput_Wine_Joystick_GUID,rguid))) {
364     if ((riid == NULL) ||
365         IsEqualGUID(&IID_IDirectInputDeviceW,riid) ||
366         IsEqualGUID(&IID_IDirectInputDevice2W,riid) ||
367         IsEqualGUID(&IID_IDirectInputDevice7W,riid) ||
368         IsEqualGUID(&IID_IDirectInputDevice8W,riid)) {
369       *pdev = (IDirectInputDeviceW*) alloc_device(rguid, &JoystickWvt, dinput);
370       TRACE("Creating a Joystick device (%p)\n", *pdev);
371       return DI_OK;
372     } else
373       return DIERR_NOINTERFACE;
374   }
375
376   return DIERR_DEVICENOTREG;
377 }
378
379 const struct dinput_device joystick_linuxinput_device = {
380   "Wine Linux-input joystick driver",
381   joydev_enum_deviceA,
382   joydev_enum_deviceW,
383   joydev_create_deviceA,
384   joydev_create_deviceW
385 };
386
387 /******************************************************************************
388  *      Joystick
389  */
390 static ULONG WINAPI JoystickAImpl_Release(LPDIRECTINPUTDEVICE8A iface)
391 {
392         JoystickImpl *This = (JoystickImpl *)iface;
393         ULONG ref;
394
395         ref = InterlockedDecrement(&(This->ref));
396         if (ref)
397                 return ref;
398
399         /* Reset the FF state, free all effects, etc */
400         IDirectInputDevice8_SendForceFeedbackCommand(iface, DISFFC_RESET);
401
402         /* Free the data queue */
403         HeapFree(GetProcessHeap(),0,This->data_queue);
404
405         /* Free the DataFormat */
406         HeapFree(GetProcessHeap(), 0, This->df);
407
408         HeapFree(GetProcessHeap(),0,This);
409         return 0;
410 }
411
412 /******************************************************************************
413   *   SetDataFormat : the application can choose the format of the data
414   *   the device driver sends back with GetDeviceState.
415   */
416 static HRESULT WINAPI JoystickAImpl_SetDataFormat(
417         LPDIRECTINPUTDEVICE8A iface,LPCDIDATAFORMAT df
418 )
419 {
420   JoystickImpl *This = (JoystickImpl *)iface;
421
422   TRACE("(this=%p,%p)\n",This,df);
423
424   if (df == NULL) {
425     WARN("invalid pointer\n");
426     return E_POINTER;
427   }
428
429   if (df->dwSize != sizeof(*df)) {
430     WARN("invalid argument\n");
431     return DIERR_INVALIDPARAM;
432   }
433
434   _dump_DIDATAFORMAT(df);
435
436   if (This->joyfd!=-1) {
437     WARN("acquired\n");
438     return DIERR_ACQUIRED;
439   }
440
441   /* Store the new data format */
442   This->df = HeapAlloc(GetProcessHeap(),0,df->dwSize);
443   if (This->df==NULL) {
444     return DIERR_OUTOFMEMORY;
445   }
446   memcpy(This->df, df, df->dwSize);
447   This->df->rgodf = HeapAlloc(GetProcessHeap(),0,df->dwNumObjs*df->dwObjSize);
448   if (This->df->rgodf==NULL) {
449     HeapFree(GetProcessHeap(), 0, This->df);
450     return DIERR_OUTOFMEMORY;
451   }
452   memcpy(This->df->rgodf,df->rgodf,df->dwNumObjs*df->dwObjSize);
453
454   return DI_OK;
455 }
456
457 /******************************************************************************
458   *     Acquire : gets exclusive control of the joystick
459   */
460 static HRESULT WINAPI JoystickAImpl_Acquire(LPDIRECTINPUTDEVICE8A iface)
461 {
462     int         i,buttons;
463     JoystickImpl *This = (JoystickImpl *)iface;
464     char        buf[200];
465     BOOL        readonly = TRUE;
466
467     TRACE("(this=%p)\n",This);
468     if (This->joyfd!=-1)
469         return 0;
470     for (i=0;i<64;i++) {
471       sprintf(buf,EVDEVPREFIX"%d",i);
472       if (-1==(This->joyfd=open(buf,O_RDWR))) { 
473         if (-1==(This->joyfd=open(buf,O_RDONLY))) {
474           /* Couldn't open the device at all */ 
475           if (errno==ENODEV)
476             return DIERR_NOTFOUND;
477           perror(buf);
478           continue;
479         }
480         else {
481           /* Couldn't open in r/w but opened in read-only. */
482           WARN("Could not open %s in read-write mode.  Force feedback will be disabled.\n",buf);
483         }
484       }
485       else {
486         /* Opened device in read-write */
487         readonly = FALSE;
488       }
489       if ((-1!=ioctl(This->joyfd,EVIOCGBIT(0,sizeof(This->evbits)),This->evbits)) &&
490           (-1!=ioctl(This->joyfd,EVIOCGBIT(EV_ABS,sizeof(This->absbits)),This->absbits)) &&
491           (-1!=ioctl(This->joyfd,EVIOCGBIT(EV_KEY,sizeof(This->keybits)),This->keybits)) &&
492           (test_bit(This->absbits,ABS_X) && test_bit(This->absbits,ABS_Y) &&
493            (test_bit(This->keybits,BTN_TRIGGER)||
494             test_bit(This->keybits,BTN_A)        ||
495             test_bit(This->keybits,BTN_1)
496           )
497          )
498       )
499         break;
500       close(This->joyfd);
501       This->joyfd = -1;
502     }
503     if (This->joyfd==-1)
504         return DIERR_NOTFOUND;
505
506     This->has_ff = FALSE;
507     This->num_effects = 0;
508
509 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
510     if (!readonly && test_bit(This->evbits, EV_FF)) {
511         if (-1!=ioctl(This->joyfd,EVIOCGBIT(EV_FF,sizeof(This->ffbits)),This->ffbits)) {
512             if (-1!=ioctl(This->joyfd,EVIOCGEFFECTS,&This->num_effects) 
513                 && This->num_effects > 0) {
514                 This->has_ff = TRUE;
515                 TRACE("Joystick seems to be capable of force feedback.\n");
516             }
517             else {
518                 TRACE("Joystick does not support any effects, disabling force feedback.\n");
519             }
520         }
521         else {
522             TRACE("Could not get EV_FF bits; disabling force feedback.\n");
523         }
524     }
525     else {
526         TRACE("Force feedback disabled (device is readonly or joystick incapable).\n");
527     }
528 #endif
529
530     for (i=0;i<ABS_MAX;i++) {
531         if (test_bit(This->absbits,i)) {
532           if (-1==ioctl(This->joyfd,EVIOCGABS(i),&(This->axes[i])))
533             continue;
534           TRACE("axe %d: cur=%d, min=%d, max=%d, fuzz=%d, flat=%d\n",
535               i,
536               This->axes[i][AXE_ABS],
537               This->axes[i][AXE_ABSMIN],
538               This->axes[i][AXE_ABSMAX],
539               This->axes[i][AXE_ABSFUZZ],
540               This->axes[i][AXE_ABSFLAT]
541           );
542           This->havemin[i] = This->axes[i][AXE_ABSMIN];
543           This->havemax[i] = This->axes[i][AXE_ABSMAX];
544         }
545     }
546     buttons = 0;
547     for (i=0;i<KEY_MAX;i++) {
548             if (test_bit(This->keybits,i)) {
549                     TRACE("button %d: %d\n", i, buttons);
550                     This->buttons[i] = 0x80 | buttons;
551                     buttons++;
552             }
553     }
554
555         fake_current_js_state(This);
556
557     return 0;
558 }
559
560 /******************************************************************************
561   *     Unacquire : frees the joystick
562   */
563 static HRESULT WINAPI JoystickAImpl_Unacquire(LPDIRECTINPUTDEVICE8A iface)
564 {
565     JoystickImpl *This = (JoystickImpl *)iface;
566
567     TRACE("(this=%p)\n",This);
568     if (This->joyfd!=-1) {
569         close(This->joyfd);
570         This->joyfd = -1;
571         return DI_OK;
572     }
573     else 
574         return DI_NOEFFECT;
575 }
576
577 /*
578  * This maps the read value (from the input event) to a value in the
579  * 'wanted' range. It also autodetects the possible range of the axe and
580  * adapts values accordingly.
581  */
582 static int
583 map_axis(JoystickImpl* This, int axis, int val) {
584     int xmin = This->axes[axis][AXE_ABSMIN];
585     int xmax = This->axes[axis][AXE_ABSMAX];
586     int hmax = This->havemax[axis];
587     int hmin = This->havemin[axis];
588     int wmin = This->wantmin[axis];
589     int wmax = This->wantmax[axis];
590     int ret;
591
592     if (val > hmax) This->havemax[axis] = hmax = val;
593     if (val < hmin) This->havemin[axis] = hmin = val;
594
595     if (xmin == xmax) return val;
596
597     /* map the value from the hmin-hmax range into the wmin-wmax range */
598     ret = ((val-hmin) * (wmax-wmin)) / (hmax-hmin) + wmin;
599
600     TRACE("xmin=%d xmax=%d hmin=%d hmax=%d wmin=%d wmax=%d val=%d ret=%d\n", xmin, xmax, hmin, hmax, wmin, wmax, val, ret);
601
602 #if 0
603     /* deadzone doesn't work comfortably enough right now. needs more testing*/
604     if ((ret > -deadz/2 ) && (ret < deadz/2)) {
605         FIXME("%d in deadzone, return mid.\n",val);
606         return (wmax-wmin)/2+wmin;
607     }
608 #endif
609     return ret;
610 }
611
612 /* 
613  * set the current state of the js device as it would be with the middle
614  * values on the axes
615  */
616 static void fake_current_js_state(JoystickImpl *ji)
617 {
618         ji->js.lX  = map_axis(ji, ABS_X,  ji->axes[ABS_X ][AXE_ABS]);
619         ji->js.lY  = map_axis(ji, ABS_Y,  ji->axes[ABS_Y ][AXE_ABS]);
620         ji->js.lZ  = map_axis(ji, ABS_Z,  ji->axes[ABS_Z ][AXE_ABS]);
621         ji->js.lRx = map_axis(ji, ABS_RX, ji->axes[ABS_RX][AXE_ABS]);
622         ji->js.lRy = map_axis(ji, ABS_RY, ji->axes[ABS_RY][AXE_ABS]);
623         ji->js.lRz = map_axis(ji, ABS_RZ, ji->axes[ABS_RZ][AXE_ABS]);
624         ji->js.rglSlider[0] = map_axis(ji, ABS_THROTTLE, ji->axes[ABS_THROTTLE][AXE_ABS]);
625         ji->js.rglSlider[1] = map_axis(ji, ABS_RUDDER,   ji->axes[ABS_RUDDER  ][AXE_ABS]);
626 }
627
628 static int find_property_offset(JoystickImpl *This, LPCDIPROPHEADER ph)
629 {
630   int i,c;
631   switch (ph->dwHow) {
632     case DIPH_BYOFFSET:
633       for (i=0; i<This->df->dwNumObjs; i++) {
634         if (This->df->rgodf[i].dwOfs == ph->dwObj) {
635           return i;
636         }
637       }
638       break;
639     case DIPH_BYID:
640       /* XXX: this is a hack - see below */
641       c = DIDFT_GETINSTANCE(ph->dwObj)>>WINE_JOYSTICK_AXIS_BASE;
642       for (i=0; (c&1)==0 && i<0x0F; i++) {
643         c >>= 1;
644       }
645       if (i<0x0F) {
646         return i;
647       }
648
649       /* XXX - the following part won't work with LiveForSpeed
650        * - the game sets the dwTypes to something else then
651        * the ddoi.dwType set in EnumObjects
652        */
653 #if 0
654       for (i=0; i<This->df->dwNumObjs; i++) {
655         TRACE("dwType='%08x'\n", This->df->rgodf[i].dwType);
656         if ((This->df->rgodf[i].dwType & 0x00ffffff) == (ph->dwObj & 0x00ffffff)) {
657           return i;
658         }
659       }
660 #endif
661       break;
662     default:
663       FIXME("Unhandled ph->dwHow=='%04X'\n", (unsigned int)ph->dwHow);
664   }
665
666   return -1;
667 }
668
669 static void joy_polldev(JoystickImpl *This) {
670     struct timeval tv;
671     fd_set      readfds;
672     struct      input_event ie;
673     int         btn;
674
675     if (This->joyfd==-1)
676         return;
677
678     while (1) {
679         memset(&tv,0,sizeof(tv));
680         FD_ZERO(&readfds);
681         FD_SET(This->joyfd,&readfds);
682
683         if (1>select(This->joyfd+1,&readfds,NULL,NULL,&tv))
684             return;
685
686         /* we have one event, so we can read */
687         if (sizeof(ie)!=read(This->joyfd,&ie,sizeof(ie)))
688             return;
689
690         TRACE("input_event: type %d, code %d, value %d\n",ie.type,ie.code,ie.value);
691         switch (ie.type) {
692         case EV_KEY:    /* button */
693                 btn = This->buttons[ie.code];
694                 TRACE("(%p) %d -> %d\n", This, ie.code, btn);
695                 if (btn&0x80) {
696                         btn &= 0x7F;
697                         This->js.rgbButtons[btn] = ie.value?0x80:0x00;
698                         GEN_EVENT(DIJOFS_BUTTON(btn),ie.value?0x80:0x0,ie.time.tv_usec,(This->dinput->evsequence)++);
699                 }
700                 break;
701         case EV_ABS:
702             switch (ie.code) {
703             case ABS_X:
704                 This->js.lX = map_axis(This,ABS_X,ie.value);
705                 GEN_EVENT(DIJOFS_X,This->js.lX,ie.time.tv_usec,(This->dinput->evsequence)++);
706                 break;
707             case ABS_Y:
708                 This->js.lY = map_axis(This,ABS_Y,ie.value);
709                 GEN_EVENT(DIJOFS_Y,This->js.lY,ie.time.tv_usec,(This->dinput->evsequence)++);
710                 break;
711             case ABS_Z:
712                 This->js.lZ = map_axis(This,ABS_Z,ie.value);
713                 GEN_EVENT(DIJOFS_Z,This->js.lZ,ie.time.tv_usec,(This->dinput->evsequence)++);
714                 break;
715             case ABS_RX:
716                 This->js.lRx = map_axis(This,ABS_RX,ie.value);
717                 GEN_EVENT(DIJOFS_RX,This->js.lRx,ie.time.tv_usec,(This->dinput->evsequence)++);
718                 break;
719             case ABS_RY:
720                 This->js.lRy = map_axis(This,ABS_RY,ie.value);
721                 GEN_EVENT(DIJOFS_RY,This->js.lRy,ie.time.tv_usec,(This->dinput->evsequence)++);
722                 break;
723             case ABS_RZ:
724                 This->js.lRz = map_axis(This,ABS_RZ,ie.value);
725                 GEN_EVENT(DIJOFS_RZ,This->js.lRz,ie.time.tv_usec,(This->dinput->evsequence)++);
726                 break;
727             case ABS_THROTTLE:
728                 This->js.rglSlider[0] = map_axis(This,ABS_THROTTLE,ie.value);
729                 GEN_EVENT(DIJOFS_SLIDER(0),This->js.rglSlider[0],ie.time.tv_usec,(This->dinput->evsequence)++);
730                 break;
731             case ABS_RUDDER:
732                 This->js.rglSlider[1] = map_axis(This,ABS_RUDDER,ie.value);
733                 GEN_EVENT(DIJOFS_SLIDER(1),This->js.rglSlider[1],ie.time.tv_usec,(This->dinput->evsequence)++);
734                 break;
735             default:
736                 FIXME("unhandled joystick axe event (code %d, value %d)\n",ie.code,ie.value);
737                 break;
738             }
739             break;
740 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
741         case EV_FF_STATUS:
742             This->ff_state = ie.value;
743             break;
744 #endif
745         case EV_SYN:
746             /* there is nothing to do */
747             break;
748         default:
749             FIXME("joystick cannot handle type %d event (code %d)\n",ie.type,ie.code);
750             break;
751         }
752     }
753 }
754
755 /******************************************************************************
756   *     GetDeviceState : returns the "state" of the joystick.
757   *
758   */
759 static HRESULT WINAPI JoystickAImpl_GetDeviceState(
760         LPDIRECTINPUTDEVICE8A iface,DWORD len,LPVOID ptr
761 ) {
762     JoystickImpl *This = (JoystickImpl *)iface;
763
764     joy_polldev(This);
765
766     TRACE("(this=%p,0x%08lx,%p)\n",This,len,ptr);
767     if ((len != sizeof(DIJOYSTATE)) && (len != sizeof(DIJOYSTATE2))) {
768         FIXME("len %ld is not sizeof(DIJOYSTATE) or DIJOYSTATE2, unsupported format.\n",len);
769         return E_FAIL;
770     }
771     memcpy(ptr,&(This->js),len);
772     This->queue_head = 0;
773     This->queue_tail = 0;
774     return 0;
775 }
776
777 /******************************************************************************
778   *     GetDeviceData : gets buffered input data.
779   */
780 static HRESULT WINAPI JoystickAImpl_GetDeviceData(LPDIRECTINPUTDEVICE8A iface,
781                                               DWORD dodsize,
782                                               LPDIDEVICEOBJECTDATA dod,
783                                               LPDWORD entries,
784                                               DWORD flags
785 ) {
786   JoystickImpl *This = (JoystickImpl *)iface;
787   DWORD len;
788   int nqtail;
789   HRESULT hr = DI_OK;
790
791   TRACE("(%p)->(dods=%ld,entries=%ld,fl=0x%08lx)\n",This,dodsize,*entries,flags);
792
793   if (This->joyfd==-!1) {
794     WARN("not acquired\n");
795     return DIERR_NOTACQUIRED;
796   }
797
798   joy_polldev(This);
799   if (flags & DIGDD_PEEK)
800     FIXME("DIGDD_PEEK\n");
801
802   len = ((This->queue_head < This->queue_tail) ? This->queue_len : 0)
803     + (This->queue_head - This->queue_tail);
804   if (len > *entries)
805     len = *entries;
806
807   if (dod == NULL) {
808     if (len)
809       TRACE("Application discarding %ld event(s).\n", len);
810
811     *entries = len;
812     nqtail = This->queue_tail + len;
813     while (nqtail >= This->queue_len)
814       nqtail -= This->queue_len;
815   } else {
816     if (dodsize < sizeof(DIDEVICEOBJECTDATA_DX3)) {
817       ERR("Wrong structure size !\n");
818       return DIERR_INVALIDPARAM;
819   }
820
821     if (len)
822       TRACE("Application retrieving %ld event(s).\n", len);
823
824     *entries = 0;
825     nqtail = This->queue_tail;
826     while (len) {
827       /* Copy the buffered data into the application queue */
828       memcpy((char *)dod + *entries * dodsize, This->data_queue + nqtail, dodsize);
829       /* Advance position */
830       nqtail++;
831       if (nqtail >= This->queue_len)
832         nqtail -= This->queue_len;
833       (*entries)++;
834       len--;
835     }
836   }
837
838   if (This->overflow) {
839     hr = DI_BUFFEROVERFLOW;
840     if (!(flags & DIGDD_PEEK)) {
841       This->overflow = FALSE;
842     }
843   }
844
845   if (!(flags & DIGDD_PEEK))
846     This->queue_tail = nqtail;
847
848   return hr;
849 }
850
851 /******************************************************************************
852   *     SetProperty : change input device properties
853   */
854 static HRESULT WINAPI JoystickAImpl_SetProperty(LPDIRECTINPUTDEVICE8A iface,
855                                             REFGUID rguid,
856                                             LPCDIPROPHEADER ph)
857 {
858   JoystickImpl *This = (JoystickImpl *)iface;
859
860   if (!ph) {
861     WARN("invalid argument\n");
862     return DIERR_INVALIDPARAM;
863   }
864
865   TRACE("(this=%p,%s,%p)\n",This,debugstr_guid(rguid),ph);
866   TRACE("ph.dwSize = %ld, ph.dwHeaderSize =%ld, ph.dwObj = %ld, ph.dwHow= %ld\n",ph->dwSize, ph->dwHeaderSize,ph->dwObj,ph->dwHow);
867
868   if (!HIWORD(rguid)) {
869     switch (LOWORD(rguid)) {
870     case (DWORD) DIPROP_BUFFERSIZE: {
871       LPCDIPROPDWORD    pd = (LPCDIPROPDWORD)ph;
872
873       TRACE("buffersize = %ld\n",pd->dwData);
874       if (This->data_queue) {
875         This->data_queue = HeapReAlloc(GetProcessHeap(),0, This->data_queue, pd->dwData * sizeof(DIDEVICEOBJECTDATA));
876       } else {
877         This->data_queue = HeapAlloc(GetProcessHeap(),0, pd->dwData * sizeof(DIDEVICEOBJECTDATA));
878       }
879       This->queue_head = 0;
880       This->queue_tail = 0;
881       This->queue_len  = pd->dwData;
882       break;
883     }
884     case (DWORD)DIPROP_RANGE: {
885       LPCDIPROPRANGE    pr = (LPCDIPROPRANGE)ph;
886
887       if (ph->dwHow == DIPH_DEVICE) {
888         int i;
889         TRACE("proprange(%ld,%ld) all\n",pr->lMin,pr->lMax);
890         for (i = 0; i < This->df->dwNumObjs; i++) {
891           This->wantmin[i] = pr->lMin;
892           This->wantmax[i] = pr->lMax;
893         }
894       } else {
895         int obj = find_property_offset(This, ph);
896         TRACE("proprange(%ld,%ld) obj=%d\n",pr->lMin,pr->lMax,obj);
897         if (obj >= 0) {
898           This->wantmin[obj] = pr->lMin;
899           This->wantmax[obj] = pr->lMax;
900         }
901       }
902       return DI_OK;
903     }
904     case (DWORD)DIPROP_DEADZONE: {
905       LPCDIPROPDWORD    pd = (LPCDIPROPDWORD)ph;
906       if (ph->dwHow == DIPH_DEVICE) {
907         int i;
908         TRACE("deadzone(%ld) all\n",pd->dwData);
909         for (i = 0; i < This->df->dwNumObjs; i++) {
910           This->deadz[i] = pd->dwData;
911         }
912       } else {
913         int obj = find_property_offset(This, ph);
914         TRACE("deadzone(%ld) obj=%d\n",pd->dwData,obj);
915         if (obj >= 0) {
916           This->deadz[obj] = pd->dwData;
917         }
918       }
919       return DI_OK;
920     }
921     default:
922       FIXME("Unknown type %p (%s)\n",rguid,debugstr_guid(rguid));
923       break;
924     }
925   }
926   fake_current_js_state(This);
927   return 0;
928 }
929
930 /******************************************************************************
931   *     SetEventNotification : specifies event to be sent on state change
932   */
933 static HRESULT WINAPI JoystickAImpl_SetEventNotification(
934         LPDIRECTINPUTDEVICE8A iface, HANDLE hnd
935 ) {
936     JoystickImpl *This = (JoystickImpl *)iface;
937
938     TRACE("(this=%p,%p)\n",This,hnd);
939     This->hEvent = hnd;
940     return DI_OK;
941 }
942
943 static HRESULT WINAPI JoystickAImpl_GetCapabilities(
944         LPDIRECTINPUTDEVICE8A iface,
945         LPDIDEVCAPS lpDIDevCaps)
946 {
947     JoystickImpl *This = (JoystickImpl *)iface;
948     int         xfd = This->joyfd;
949     int         i,axes,buttons;
950
951     TRACE("%p->(%p)\n",iface,lpDIDevCaps);
952
953     if (!lpDIDevCaps) {
954         WARN("invalid pointer\n");
955         return E_POINTER;
956     }
957
958     if (lpDIDevCaps->dwSize != sizeof(DIDEVCAPS)) {
959         WARN("invalid argument\n");
960         return DIERR_INVALIDPARAM;
961     }
962
963     if (xfd==-1) {
964         /* yes, games assume we return something, even if unacquired */
965         JoystickAImpl_Acquire(iface);
966     }
967
968     lpDIDevCaps->dwFlags        = DIDC_ATTACHED;
969     if (This->dinput->dwVersion >= 0x0800)
970         lpDIDevCaps->dwDevType = DI8DEVTYPE_JOYSTICK | (DI8DEVTYPEJOYSTICK_STANDARD << 8);
971     else
972         lpDIDevCaps->dwDevType = DIDEVTYPE_JOYSTICK | (DIDEVTYPEJOYSTICK_TRADITIONAL << 8);
973
974     axes=0;
975     for (i=0;i<ABS_MAX;i++) if (test_bit(This->absbits,i)) axes++;
976     buttons=0;
977     for (i=0;i<KEY_MAX;i++) if (test_bit(This->keybits,i)) buttons++;
978
979     if (This->has_ff) 
980          lpDIDevCaps->dwFlags |= DIDC_FORCEFEEDBACK;
981
982     lpDIDevCaps->dwAxes = axes;
983     lpDIDevCaps->dwButtons = buttons;
984
985     if (xfd==-1) {
986       JoystickAImpl_Unacquire(iface);
987     }
988
989     return DI_OK;
990 }
991
992 static HRESULT WINAPI JoystickAImpl_Poll(LPDIRECTINPUTDEVICE8A iface) {
993     JoystickImpl *This = (JoystickImpl *)iface;
994     TRACE("(%p)\n",This);
995
996     if (This->joyfd==-1) {
997       return DIERR_NOTACQUIRED;
998     }
999
1000     joy_polldev(This);
1001     return DI_OK;
1002 }
1003
1004 /******************************************************************************
1005   *     EnumObjects : enumerate the different buttons and axis...
1006   */
1007 static HRESULT WINAPI JoystickAImpl_EnumObjects(
1008         LPDIRECTINPUTDEVICE8A iface,
1009         LPDIENUMDEVICEOBJECTSCALLBACKA lpCallback,
1010         LPVOID lpvRef,
1011         DWORD dwFlags)
1012 {
1013   JoystickImpl *This = (JoystickImpl *)iface;
1014   DIDEVICEOBJECTINSTANCEA ddoi;
1015   int xfd = This->joyfd;
1016
1017   TRACE("(this=%p,%p,%p,%08lx)\n", This, lpCallback, lpvRef, dwFlags);
1018   if (TRACE_ON(dinput)) {
1019     TRACE("  - flags = ");
1020     _dump_EnumObjects_flags(dwFlags);
1021     TRACE("\n");
1022   }
1023
1024   /* We need to work even if we're not yet acquired */
1025   if (xfd == -1)
1026     IDirectInputDevice8_Acquire(iface);
1027
1028   /* Only the fields till dwFFMaxForce are relevant */
1029   ddoi.dwSize = FIELD_OFFSET(DIDEVICEOBJECTINSTANCEA, dwFFMaxForce);
1030
1031   /* For the joystick, do as is done in the GetCapabilities function */
1032   /* FIXME: needs more items */
1033   if ((dwFlags == DIDFT_ALL) ||
1034       (dwFlags & DIDFT_AXIS)) {
1035     BYTE i;
1036
1037     for (i = 0; i < ABS_MAX; i++) {
1038       if (!test_bit(This->absbits,i)) continue;
1039
1040       switch (i) {
1041       case ABS_X:
1042         ddoi.guidType = GUID_XAxis;
1043         ddoi.dwOfs = DIJOFS_X;
1044         break;
1045       case ABS_Y:
1046         ddoi.guidType = GUID_YAxis;
1047         ddoi.dwOfs = DIJOFS_Y;
1048         break;
1049       case ABS_Z:
1050         ddoi.guidType = GUID_ZAxis;
1051         ddoi.dwOfs = DIJOFS_Z;
1052         break;
1053       case ABS_RX:
1054         ddoi.guidType = GUID_RxAxis;
1055         ddoi.dwOfs = DIJOFS_RX;
1056         break;
1057       case ABS_RY:
1058         ddoi.guidType = GUID_RyAxis;
1059         ddoi.dwOfs = DIJOFS_RY;
1060         break;
1061       case ABS_RZ:
1062         ddoi.guidType = GUID_RzAxis;
1063         ddoi.dwOfs = DIJOFS_RZ;
1064         break;
1065       case ABS_THROTTLE:
1066         ddoi.guidType = GUID_Slider;
1067         ddoi.dwOfs = DIJOFS_SLIDER(0);
1068         break;
1069       case ABS_RUDDER:
1070         ddoi.guidType = GUID_Slider;
1071         ddoi.dwOfs = DIJOFS_SLIDER(1);
1072         break;
1073       default:
1074         FIXME("unhandled abs axis %d, ignoring!\n",i);
1075       }
1076       ddoi.dwType = DIDFT_MAKEINSTANCE((1<<i) << WINE_JOYSTICK_AXIS_BASE) | DIDFT_ABSAXIS;
1077       /* Linux event force feedback supports only (and always) x and y axes */
1078       if (i == ABS_X || i == ABS_Y) {
1079         if (This->has_ff)
1080           ddoi.dwFlags |= DIDOI_FFACTUATOR;
1081       }
1082       sprintf(ddoi.tszName, "%d-Axis", i);
1083       _dump_OBJECTINSTANCEA(&ddoi);
1084       if (lpCallback(&ddoi, lpvRef) != DIENUM_CONTINUE) {
1085         /* return to unaquired state if that's where we were */
1086         if (xfd == -1)
1087           IDirectInputDevice8_Unacquire(iface);
1088         return DI_OK;
1089       }
1090     }
1091   }
1092
1093   if ((dwFlags == DIDFT_ALL) ||
1094       (dwFlags & DIDFT_BUTTON)) {
1095     int i, btncount=0;
1096
1097     /*The DInput SDK says that GUID_Button is only for mouse buttons but well*/
1098
1099     ddoi.guidType = GUID_Button;
1100
1101     for (i = 0; i < KEY_MAX; i++) {
1102       if (!test_bit(This->keybits,i)) continue;
1103       ddoi.dwOfs = DIJOFS_BUTTON(btncount);
1104       ddoi.dwType = DIDFT_MAKEINSTANCE(btncount << WINE_JOYSTICK_BUTTON_BASE) | DIDFT_PSHBUTTON;
1105       sprintf(ddoi.tszName, "%d-Button", btncount);
1106       btncount++;
1107       _dump_OBJECTINSTANCEA(&ddoi);
1108       if (lpCallback(&ddoi, lpvRef) != DIENUM_CONTINUE) {
1109         /* return to unaquired state if that's where we were */
1110         if (xfd == -1)
1111           IDirectInputDevice8_Unacquire(iface);
1112         return DI_OK;
1113       }
1114     }
1115   }
1116
1117   /* return to unaquired state if that's where we were */
1118   if (xfd == -1)
1119     IDirectInputDevice8_Unacquire(iface);
1120
1121   return DI_OK;
1122 }
1123
1124 static HRESULT WINAPI JoystickWImpl_EnumObjects(LPDIRECTINPUTDEVICE8W iface,
1125                                                 LPDIENUMDEVICEOBJECTSCALLBACKW lpCallback,
1126                                                 LPVOID lpvRef,
1127                                                 DWORD dwFlags)
1128 {
1129   JoystickImpl *This = (JoystickImpl *)iface;
1130
1131   device_enumobjects_AtoWcb_data data;
1132
1133   data.lpCallBack = lpCallback;
1134   data.lpvRef = lpvRef;
1135
1136   return JoystickAImpl_EnumObjects((LPDIRECTINPUTDEVICE8A) This, (LPDIENUMDEVICEOBJECTSCALLBACKA) DIEnumDevicesCallbackAtoW, (LPVOID) &data, dwFlags);
1137 }
1138
1139 /******************************************************************************
1140   *     GetProperty : get input device properties
1141   */
1142 static HRESULT WINAPI JoystickAImpl_GetProperty(LPDIRECTINPUTDEVICE8A iface,
1143                                                 REFGUID rguid,
1144                                                 LPDIPROPHEADER pdiph)
1145 {
1146   JoystickImpl *This = (JoystickImpl *)iface;
1147
1148   TRACE("(this=%p,%s,%p)\n",
1149         iface, debugstr_guid(rguid), pdiph);
1150
1151   if (TRACE_ON(dinput))
1152     _dump_DIPROPHEADER(pdiph);
1153
1154   if (!HIWORD(rguid)) {
1155     switch (LOWORD(rguid)) {
1156     case (DWORD) DIPROP_BUFFERSIZE: {
1157       LPDIPROPDWORD     pd = (LPDIPROPDWORD)pdiph;
1158
1159       TRACE(" return buffersize = %d\n",This->queue_len);
1160       pd->dwData = This->queue_len;
1161       break;
1162     }
1163
1164     case (DWORD) DIPROP_RANGE: {
1165       /* LPDIPROPRANGE pr = (LPDIPROPRANGE) pdiph; */
1166       if ((pdiph->dwHow == DIPH_BYID) &&
1167           (pdiph->dwObj & DIDFT_ABSAXIS)) {
1168         /* The app is querying the current range of the axis : return the lMin and lMax values */
1169         FIXME("unimplemented axis range query.\n");
1170       }
1171
1172       break;
1173     }
1174
1175     default:
1176       FIXME("Unknown type %p (%s)\n",rguid,debugstr_guid(rguid));
1177       break;
1178     }
1179   }
1180
1181
1182   return DI_OK;
1183 }
1184
1185 /****************************************************************************** 
1186   *     CreateEffect - Create a new FF effect with the specified params
1187   */
1188 static HRESULT WINAPI JoystickAImpl_CreateEffect(LPDIRECTINPUTDEVICE8A iface,
1189                                                  REFGUID rguid,
1190                                                  LPCDIEFFECT lpeff,
1191                                                  LPDIRECTINPUTEFFECT *ppdef,
1192                                                  LPUNKNOWN pUnkOuter)
1193 {
1194 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
1195     EffectListItem* new = NULL;
1196     HRESULT retval = DI_OK;
1197 #endif
1198
1199     JoystickImpl* This = (JoystickImpl*)iface;
1200     TRACE("(this=%p,%p,%p,%p,%p)\n", This, rguid, lpeff, ppdef, pUnkOuter);
1201
1202 #ifndef HAVE_STRUCT_FF_EFFECT_DIRECTION
1203     TRACE("not available (compiled w/o ff support)\n");
1204     *ppdef = NULL;
1205     return DI_OK; 
1206 #else
1207
1208     new = malloc(sizeof(EffectListItem));
1209     new->next = This->top_effect;
1210     This->top_effect = new;
1211
1212     retval = linuxinput_create_effect(&(This->joyfd), rguid, &(new->ref));
1213     if (retval != DI_OK)
1214         return retval;
1215  
1216     if (lpeff != NULL)
1217         retval = IDirectInputEffect_SetParameters(new->ref, lpeff, 0);
1218     if (retval != DI_OK && retval != DI_DOWNLOADSKIPPED)
1219         return retval;
1220
1221     *ppdef = new->ref;
1222
1223     if (pUnkOuter != NULL)
1224         FIXME("Interface aggregation not implemented.\n");
1225
1226     return DI_OK;
1227
1228 #endif /* HAVE_STRUCT_FF_EFFECT_DIRECTION */
1229
1230
1231 /*******************************************************************************
1232  *      EnumEffects - Enumerate available FF effects
1233  */
1234 static HRESULT WINAPI JoystickAImpl_EnumEffects(LPDIRECTINPUTDEVICE8A iface,
1235                                                 LPDIENUMEFFECTSCALLBACKA lpCallback,
1236                                                 LPVOID pvRef,
1237                                                 DWORD dwEffType)
1238 {
1239 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
1240     DIEFFECTINFOA dei; /* feif */
1241     DWORD type = DIEFT_GETTYPE(dwEffType);
1242     JoystickImpl* This = (JoystickImpl*)iface;
1243     int xfd = This->joyfd;
1244
1245     TRACE("(this=%p,%p,%ld) type=%ld fd=%d\n", This, pvRef, dwEffType, type, xfd);
1246
1247     dei.dwSize = sizeof(DIEFFECTINFOA);          
1248
1249     /* We need to return something even if we're not yet acquired */
1250     if (xfd == -1)
1251         IDirectInputDevice8_Acquire(iface);
1252
1253     if ((type == DIEFT_ALL || type == DIEFT_CONSTANTFORCE)
1254         && test_bit(This->ffbits, FF_CONSTANT)) {
1255         IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_ConstantForce);
1256         (*lpCallback)(&dei, pvRef);
1257     }
1258
1259     if ((type == DIEFT_ALL || type == DIEFT_PERIODIC)
1260         && test_bit(This->ffbits, FF_PERIODIC)) {
1261         if (test_bit(This->ffbits, FF_SQUARE)) {
1262             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Square);
1263             (*lpCallback)(&dei, pvRef);
1264         }
1265         if (test_bit(This->ffbits, FF_SINE)) {
1266             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Sine);
1267             (*lpCallback)(&dei, pvRef);
1268         }
1269         if (test_bit(This->ffbits, FF_TRIANGLE)) {
1270             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Triangle);
1271             (*lpCallback)(&dei, pvRef);
1272         }
1273         if (test_bit(This->ffbits, FF_SAW_UP)) {
1274             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_SawtoothUp);
1275             (*lpCallback)(&dei, pvRef);
1276         }
1277         if (test_bit(This->ffbits, FF_SAW_DOWN)) {
1278             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_SawtoothDown);
1279             (*lpCallback)(&dei, pvRef);
1280         }
1281     } 
1282
1283     if ((type == DIEFT_ALL || type == DIEFT_RAMPFORCE)
1284         && test_bit(This->ffbits, FF_RAMP)) {
1285         IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_RampForce);
1286         (*lpCallback)(&dei, pvRef);
1287     }
1288
1289     if (type == DIEFT_ALL || type == DIEFT_CONDITION) {
1290         if (test_bit(This->ffbits, FF_SPRING)) {
1291             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Spring);
1292             (*lpCallback)(&dei, pvRef);
1293         }
1294         if (test_bit(This->ffbits, FF_DAMPER)) {
1295             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Damper);
1296             (*lpCallback)(&dei, pvRef);
1297         }
1298         if (test_bit(This->ffbits, FF_INERTIA)) {
1299             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Inertia);
1300             (*lpCallback)(&dei, pvRef);
1301         }
1302         if (test_bit(This->ffbits, FF_FRICTION)) {
1303             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Friction);
1304             (*lpCallback)(&dei, pvRef);
1305         }
1306     }
1307
1308     /* return to unaquired state if that's where it was */
1309     if (xfd == -1)
1310         IDirectInputDevice8_Unacquire(iface);
1311 #endif
1312
1313     return DI_OK;
1314 }
1315
1316 static HRESULT WINAPI JoystickWImpl_EnumEffects(LPDIRECTINPUTDEVICE8W iface,
1317                                                 LPDIENUMEFFECTSCALLBACKW lpCallback,
1318                                                 LPVOID pvRef,
1319                                                 DWORD dwEffType)
1320 {
1321 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
1322     /* seems silly to duplicate all this code but all the structures and functions
1323      * are actually different (A/W) */
1324     DIEFFECTINFOW dei; /* feif */
1325     DWORD type = DIEFT_GETTYPE(dwEffType);
1326     JoystickImpl* This = (JoystickImpl*)iface;
1327     int xfd = This->joyfd;
1328
1329     TRACE("(this=%p,%p,%ld) type=%ld fd=%d\n", This, pvRef, dwEffType, type, xfd);
1330
1331     dei.dwSize = sizeof(DIEFFECTINFOW);          
1332
1333     /* We need to return something even if we're not yet acquired */
1334     if (xfd == -1)
1335         IDirectInputDevice8_Acquire(iface);
1336
1337     if ((type == DIEFT_ALL || type == DIEFT_CONSTANTFORCE)
1338         && test_bit(This->ffbits, FF_CONSTANT)) {
1339         IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_ConstantForce);
1340         (*lpCallback)(&dei, pvRef);
1341     }
1342
1343     if ((type == DIEFT_ALL || type == DIEFT_PERIODIC)
1344         && test_bit(This->ffbits, FF_PERIODIC)) {
1345         if (test_bit(This->ffbits, FF_SQUARE)) {
1346             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Square);
1347             (*lpCallback)(&dei, pvRef);
1348         }
1349         if (test_bit(This->ffbits, FF_SINE)) {
1350             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Sine);
1351             (*lpCallback)(&dei, pvRef);
1352         }
1353         if (test_bit(This->ffbits, FF_TRIANGLE)) {
1354             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Triangle);
1355             (*lpCallback)(&dei, pvRef);
1356         }
1357         if (test_bit(This->ffbits, FF_SAW_UP)) {
1358             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_SawtoothUp);
1359             (*lpCallback)(&dei, pvRef);
1360         }
1361         if (test_bit(This->ffbits, FF_SAW_DOWN)) {
1362             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_SawtoothDown);
1363             (*lpCallback)(&dei, pvRef);
1364         }
1365     } 
1366
1367     if ((type == DIEFT_ALL || type == DIEFT_RAMPFORCE)
1368         && test_bit(This->ffbits, FF_RAMP)) {
1369         IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_RampForce);
1370         (*lpCallback)(&dei, pvRef);
1371     }
1372
1373     if (type == DIEFT_ALL || type == DIEFT_CONDITION) {
1374         if (test_bit(This->ffbits, FF_SPRING)) {
1375             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Spring);
1376             (*lpCallback)(&dei, pvRef);
1377         }
1378         if (test_bit(This->ffbits, FF_DAMPER)) {
1379             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Damper);
1380             (*lpCallback)(&dei, pvRef);
1381         }
1382         if (test_bit(This->ffbits, FF_INERTIA)) {
1383             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Inertia);
1384             (*lpCallback)(&dei, pvRef);
1385         }
1386         if (test_bit(This->ffbits, FF_FRICTION)) {
1387             IDirectInputDevice8_GetEffectInfo(iface, &dei, &GUID_Friction);
1388             (*lpCallback)(&dei, pvRef);
1389         }
1390     }
1391
1392     /* return to unaquired state if that's where it was */
1393     if (xfd == -1)
1394         IDirectInputDevice8_Unacquire(iface);
1395 #endif
1396
1397     return DI_OK;
1398 }
1399
1400 /*******************************************************************************
1401  *      GetEffectInfo - Get information about a particular effect 
1402  */
1403 static HRESULT WINAPI JoystickAImpl_GetEffectInfo(LPDIRECTINPUTDEVICE8A iface,
1404                                                   LPDIEFFECTINFOA pdei,
1405                                                   REFGUID guid)
1406 {
1407     JoystickImpl* This = (JoystickImpl*)iface;
1408
1409     TRACE("(this=%p,%p,%s)\n", This, pdei, _dump_dinput_GUID(guid));
1410
1411 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
1412     return linuxinput_get_info_A(This->joyfd, guid, pdei); 
1413 #else
1414     return DI_OK;
1415 #endif
1416 }
1417
1418 static HRESULT WINAPI JoystickWImpl_GetEffectInfo(LPDIRECTINPUTDEVICE8W iface,
1419                                                   LPDIEFFECTINFOW pdei,
1420                                                   REFGUID guid)
1421 {
1422     JoystickImpl* This = (JoystickImpl*)iface;
1423             
1424     TRACE("(this=%p,%p,%s)\n", This, pdei, _dump_dinput_GUID(guid));
1425         
1426 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
1427     return linuxinput_get_info_W(This->joyfd, guid, pdei);
1428 #else
1429     return DI_OK;
1430 #endif
1431 }
1432
1433 /*******************************************************************************
1434  *      GetForceFeedbackState - Get information about the device's FF state 
1435  */
1436 static HRESULT WINAPI JoystickAImpl_GetForceFeedbackState(
1437         LPDIRECTINPUTDEVICE8A iface,
1438         LPDWORD pdwOut)
1439 {
1440     JoystickImpl* This = (JoystickImpl*)iface;
1441
1442     TRACE("(this=%p,%p)\n", This, pdwOut);
1443
1444     (*pdwOut) = 0;
1445
1446 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
1447     /* DIGFFS_STOPPED is the only mandatory flag to report */
1448     if (This->ff_state == FF_STATUS_STOPPED)
1449         (*pdwOut) |= DIGFFS_STOPPED;
1450 #endif
1451
1452     return DI_OK;
1453 }
1454
1455 /*******************************************************************************
1456  *      SendForceFeedbackCommand - Send a command to the device's FF system
1457  */
1458 static HRESULT WINAPI JoystickAImpl_SendForceFeedbackCommand(
1459         LPDIRECTINPUTDEVICE8A iface,
1460         DWORD dwFlags)
1461 {
1462     JoystickImpl* This = (JoystickImpl*)iface;
1463     TRACE("(this=%p,%ld)\n", This, dwFlags);
1464
1465 #ifdef HAVE_STRUCT_FF_EFFECT_DIRECTION
1466     if (dwFlags == DISFFC_STOPALL) {
1467         /* Stop all effects */
1468         EffectListItem* itr = This->top_effect;
1469         while (itr) {
1470             IDirectInputEffect_Stop(itr->ref);
1471             itr = itr->next;
1472         }
1473     } else if (dwFlags == DISFFC_RESET) {
1474         /* Stop, unload, release and free all effects */
1475         /* This returns the device to its "bare" state */
1476         while (This->top_effect) {
1477             EffectListItem* temp = This->top_effect; 
1478             IDirectInputEffect_Stop(temp->ref);
1479             IDirectInputEffect_Unload(temp->ref);
1480             IDirectInputEffect_Release(temp->ref);
1481             This->top_effect = temp->next; 
1482             free(temp);
1483         }
1484     } else if (dwFlags == DISFFC_PAUSE || dwFlags == DISFFC_CONTINUE) {
1485         FIXME("No support for Pause or Continue in linux\n");
1486     } else if (dwFlags == DISFFC_SETACTUATORSOFF 
1487                 || dwFlags == DISFFC_SETACTUATORSON) {
1488         FIXME("No direct actuator control in linux\n");
1489     } else {
1490         FIXME("Unknown Force Feedback Command!\n");
1491         return DIERR_INVALIDPARAM;
1492     }
1493     return DI_OK;
1494 #else
1495     return DIERR_UNSUPPORTED;
1496 #endif
1497 }
1498
1499 /*******************************************************************************
1500  *      EnumCreatedEffectObjects - Enumerate all the effects that have been
1501  *              created for this device.
1502  */
1503 static HRESULT WINAPI JoystickAImpl_EnumCreatedEffectObjects(
1504         LPDIRECTINPUTDEVICE8A iface,
1505         LPDIENUMCREATEDEFFECTOBJECTSCALLBACK lpCallback,
1506         LPVOID pvRef,
1507         DWORD dwFlags)
1508 {
1509     /* this function is safe to call on non-ff-enabled builds */
1510
1511     JoystickImpl* This = (JoystickImpl*)iface;
1512     EffectListItem* itr = This->top_effect;
1513     TRACE("(this=%p,%p,%p,%ld)\n", This, lpCallback, pvRef, dwFlags);
1514
1515     if (!lpCallback)
1516         return DIERR_INVALIDPARAM;
1517
1518     if (dwFlags != 0)
1519         FIXME("Flags specified, but no flags exist yet (DX9)!");
1520
1521     while (itr) {
1522         (*lpCallback)(itr->ref, pvRef);
1523         itr = itr->next;
1524     }
1525
1526     return DI_OK;
1527 }
1528
1529 static const IDirectInputDevice8AVtbl JoystickAvt =
1530 {
1531         IDirectInputDevice2AImpl_QueryInterface,
1532         IDirectInputDevice2AImpl_AddRef,
1533         JoystickAImpl_Release,
1534         JoystickAImpl_GetCapabilities,
1535         JoystickAImpl_EnumObjects,
1536         JoystickAImpl_GetProperty,
1537         JoystickAImpl_SetProperty,
1538         JoystickAImpl_Acquire,
1539         JoystickAImpl_Unacquire,
1540         JoystickAImpl_GetDeviceState,
1541         JoystickAImpl_GetDeviceData,
1542         JoystickAImpl_SetDataFormat,
1543         JoystickAImpl_SetEventNotification,
1544         IDirectInputDevice2AImpl_SetCooperativeLevel,
1545         IDirectInputDevice2AImpl_GetObjectInfo,
1546         IDirectInputDevice2AImpl_GetDeviceInfo,
1547         IDirectInputDevice2AImpl_RunControlPanel,
1548         IDirectInputDevice2AImpl_Initialize,
1549         JoystickAImpl_CreateEffect,
1550         JoystickAImpl_EnumEffects,
1551         JoystickAImpl_GetEffectInfo,
1552         JoystickAImpl_GetForceFeedbackState,
1553         JoystickAImpl_SendForceFeedbackCommand,
1554         JoystickAImpl_EnumCreatedEffectObjects,
1555         IDirectInputDevice2AImpl_Escape,
1556         JoystickAImpl_Poll,
1557         IDirectInputDevice2AImpl_SendDeviceData,
1558         IDirectInputDevice7AImpl_EnumEffectsInFile,
1559         IDirectInputDevice7AImpl_WriteEffectToFile,
1560         IDirectInputDevice8AImpl_BuildActionMap,
1561         IDirectInputDevice8AImpl_SetActionMap,
1562         IDirectInputDevice8AImpl_GetImageInfo
1563 };
1564
1565 #if !defined(__STRICT_ANSI__) && defined(__GNUC__)
1566 # define XCAST(fun)     (typeof(JoystickWvt.fun))
1567 #else
1568 # define XCAST(fun)     (void*)
1569 #endif
1570
1571 static const IDirectInputDevice8WVtbl JoystickWvt =
1572 {
1573         IDirectInputDevice2WImpl_QueryInterface,
1574         XCAST(AddRef)IDirectInputDevice2AImpl_AddRef,
1575         XCAST(Release)JoystickAImpl_Release,
1576         XCAST(GetCapabilities)JoystickAImpl_GetCapabilities,
1577         JoystickWImpl_EnumObjects,
1578         XCAST(GetProperty)JoystickAImpl_GetProperty,
1579         XCAST(SetProperty)JoystickAImpl_SetProperty,
1580         XCAST(Acquire)JoystickAImpl_Acquire,
1581         XCAST(Unacquire)JoystickAImpl_Unacquire,
1582         XCAST(GetDeviceState)JoystickAImpl_GetDeviceState,
1583         XCAST(GetDeviceData)JoystickAImpl_GetDeviceData,
1584         XCAST(SetDataFormat)JoystickAImpl_SetDataFormat,
1585         XCAST(SetEventNotification)JoystickAImpl_SetEventNotification,
1586         XCAST(SetCooperativeLevel)IDirectInputDevice2AImpl_SetCooperativeLevel,
1587         IDirectInputDevice2WImpl_GetObjectInfo,
1588         IDirectInputDevice2WImpl_GetDeviceInfo,
1589         XCAST(RunControlPanel)IDirectInputDevice2AImpl_RunControlPanel,
1590         XCAST(Initialize)IDirectInputDevice2AImpl_Initialize,
1591         XCAST(CreateEffect)JoystickAImpl_CreateEffect,
1592         JoystickWImpl_EnumEffects,
1593         JoystickWImpl_GetEffectInfo,
1594         XCAST(GetForceFeedbackState)JoystickAImpl_GetForceFeedbackState,
1595         XCAST(SendForceFeedbackCommand)JoystickAImpl_SendForceFeedbackCommand,
1596         XCAST(EnumCreatedEffectObjects)JoystickAImpl_EnumCreatedEffectObjects,
1597         XCAST(Escape)IDirectInputDevice2AImpl_Escape,
1598         XCAST(Poll)JoystickAImpl_Poll,
1599         XCAST(SendDeviceData)IDirectInputDevice2AImpl_SendDeviceData,
1600         IDirectInputDevice7WImpl_EnumEffectsInFile,
1601         IDirectInputDevice7WImpl_WriteEffectToFile,
1602         IDirectInputDevice8WImpl_BuildActionMap,
1603         IDirectInputDevice8WImpl_SetActionMap,
1604         IDirectInputDevice8WImpl_GetImageInfo
1605 };
1606 #undef XCAST
1607
1608 #else  /* HAVE_CORRECT_LINUXINPUT_H */
1609
1610 const struct dinput_device joystick_linuxinput_device = {
1611   "Wine Linux-input joystick driver",
1612   NULL,
1613   NULL,
1614   NULL,
1615   NULL
1616 };
1617
1618 #endif  /* HAVE_CORRECT_LINUXINPUT_H */