Get rid of HeapAlloc casts.
[wine] / dlls / dinput / joystick_linux.c
1 /*              DirectInput Joystick device
2  *
3  * Copyright 1998 Marcus Meissner
4  * Copyright 1998,1999 Lionel Ulmer
5  * Copyright 2000-2001 TransGaming Technologies Inc.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 /*
23  * To Do:
24  *      dead zone
25  *      force feedback
26  */
27
28 #include "config.h"
29 #include "wine/port.h"
30
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <time.h>
35 #include <errno.h>
36 #ifdef HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
39 #ifdef HAVE_SYS_TIME_H
40 # include <sys/time.h>
41 #endif
42 #include <sys/fcntl.h>
43 #ifdef HAVE_SYS_IOCTL_H
44 # include <sys/ioctl.h>
45 #endif
46 #include <errno.h>
47 #ifdef HAVE_SYS_ERRNO_H
48 # include <sys/errno.h>
49 #endif
50 #ifdef HAVE_LINUX_IOCTL_H
51 # include <linux/ioctl.h>
52 #endif
53 #ifdef HAVE_LINUX_JOYSTICK_H
54 # include <linux/joystick.h>
55 #endif
56
57 #include "wine/debug.h"
58 #include "wine/unicode.h"
59 #include "windef.h"
60 #include "winbase.h"
61 #include "winerror.h"
62 #include "winreg.h"
63 #include "dinput.h"
64
65 #include "dinput_private.h"
66 #include "device_private.h"
67
68 WINE_DEFAULT_DEBUG_CHANNEL(dinput);
69
70 #ifdef HAVE_LINUX_22_JOYSTICK_API
71
72 #define JOYDEV "/dev/js"
73
74 typedef struct {
75     LONG lMin;
76     LONG lMax;
77     LONG lDeadZone;
78     LONG lSaturation;
79 } ObjProps;
80
81 typedef struct {
82     LONG lX;
83     LONG lY;
84 } POV;
85
86 typedef struct JoystickImpl JoystickImpl;
87 static IDirectInputDevice8AVtbl JoystickAvt;
88 static IDirectInputDevice8WVtbl JoystickWvt;
89 struct JoystickImpl
90 {
91         LPVOID                          lpVtbl;
92         DWORD                           ref;
93         GUID                            guid;
94         char                            dev[32];
95
96         /* The 'parent' DInput */
97         IDirectInputImpl               *dinput;
98
99         /* joystick private */
100         int                             joyfd;
101         DIJOYSTATE2                     js;             /* wine data */
102         LPDIDATAFORMAT                  user_df;        /* user defined format */
103         DataFormat                      *transform;     /* wine to user format converter */
104         int                             *offsets;       /* object offsets */
105         ObjProps                        *props;
106         HANDLE                          hEvent;
107         LPDIDEVICEOBJECTDATA            data_queue;
108         int                             queue_head, queue_tail, queue_len;
109         BOOL                            acquired;
110         char                            *name;
111         DIDEVCAPS                       devcaps;
112         LONG                            deadzone;
113         int                             *axis_map;
114         int                             axes;
115         int                             buttons;
116         POV                             povs[4];
117         CRITICAL_SECTION                crit;
118         BOOL                            overflow;
119 };
120
121 static GUID DInput_Wine_Joystick_GUID = { /* 9e573ed9-7734-11d2-8d4a-23903fb6bdf7 */
122   0x9e573ed9,
123   0x7734,
124   0x11d2,
125   {0x8d, 0x4a, 0x23, 0x90, 0x3f, 0xb6, 0xbd, 0xf7}
126 };
127
128 static void _dump_DIDEVCAPS(LPDIDEVCAPS lpDIDevCaps)
129 {
130     TRACE("dwSize: %ld\n", lpDIDevCaps->dwSize);
131     TRACE("dwFlags: %08lx\n",lpDIDevCaps->dwFlags);
132     TRACE("dwDevType: %08lx %s\n", lpDIDevCaps->dwDevType,
133           lpDIDevCaps->dwDevType == DIDEVTYPE_DEVICE ? "DIDEVTYPE_DEVICE" :
134           lpDIDevCaps->dwDevType == DIDEVTYPE_DEVICE ? "DIDEVTYPE_DEVICE" :
135           lpDIDevCaps->dwDevType == DIDEVTYPE_MOUSE ? "DIDEVTYPE_MOUSE" :
136           lpDIDevCaps->dwDevType == DIDEVTYPE_KEYBOARD ? "DIDEVTYPE_KEYBOARD" :
137           lpDIDevCaps->dwDevType == DIDEVTYPE_JOYSTICK ? "DIDEVTYPE_JOYSTICK" :
138           lpDIDevCaps->dwDevType == DIDEVTYPE_HID ? "DIDEVTYPE_HID" : "UNKNOWN");
139     TRACE("dwAxes: %ld\n",lpDIDevCaps->dwAxes);
140     TRACE("dwButtons: %ld\n",lpDIDevCaps->dwButtons);
141     TRACE("dwPOVs: %ld\n",lpDIDevCaps->dwPOVs);
142     if (lpDIDevCaps->dwSize > sizeof(DIDEVCAPS_DX3)) {
143         TRACE("dwFFSamplePeriod: %ld\n",lpDIDevCaps->dwFFSamplePeriod);
144         TRACE("dwFFMinTimeResolution: %ld\n",lpDIDevCaps->dwFFMinTimeResolution);
145         TRACE("dwFirmwareRevision: %ld\n",lpDIDevCaps->dwFirmwareRevision);
146         TRACE("dwHardwareRevision: %ld\n",lpDIDevCaps->dwHardwareRevision);
147         TRACE("dwFFDriverVersion: %ld\n",lpDIDevCaps->dwFFDriverVersion);
148     }
149 }
150
151 static BOOL joydev_enum_deviceA(DWORD dwDevType, DWORD dwFlags, LPDIDEVICEINSTANCEA lpddi, int version, int id)
152 {
153     int fd = -1;
154     char dev[32];
155
156     if (dwFlags & DIEDFL_FORCEFEEDBACK) {
157         WARN("force feedback not supported\n");
158         return FALSE;
159     }
160
161     if ((dwDevType == 0) ||
162         ((dwDevType == DIDEVTYPE_JOYSTICK) && (version < 8)) ||
163         (((dwDevType == DI8DEVCLASS_GAMECTRL) || (dwDevType == DI8DEVTYPE_JOYSTICK)) && (version >= 8))) {
164         /* check whether we have a joystick */
165         sprintf(dev, "%s%d", JOYDEV, id);
166         if ((fd = open(dev,O_RDONLY)) < 0) {
167             WARN("open(%s,O_RDONLY) failed: %s\n", dev, strerror(errno));
168             return FALSE;
169         }
170
171         /* Return joystick */
172         lpddi->guidInstance = DInput_Wine_Joystick_GUID;
173         lpddi->guidInstance.Data3 = id;
174         lpddi->guidProduct = DInput_Wine_Joystick_GUID;
175         /* we only support traditional joysticks for now */
176         if (version >= 8)
177             lpddi->dwDevType = DI8DEVTYPE_JOYSTICK | (DI8DEVTYPEJOYSTICK_STANDARD << 8);
178         else
179             lpddi->dwDevType = DIDEVTYPE_JOYSTICK | (DIDEVTYPEJOYSTICK_TRADITIONAL << 8);
180         sprintf(lpddi->tszInstanceName, "Joystick %d", id);
181 #if defined(JSIOCGNAME)
182         if (ioctl(fd,JSIOCGNAME(sizeof(lpddi->tszProductName)),lpddi->tszProductName) < 0) {
183             WARN("ioctl(%s,JSIOCGNAME) failed: %s\n", dev, strerror(errno));
184             strcpy(lpddi->tszProductName, "Wine Joystick");
185         }
186 #else
187         strcpy(lpddi->tszProductName, "Wine Joystick");
188 #endif
189
190         lpddi->guidFFDriver = GUID_NULL;
191         close(fd);
192         TRACE("Enumerating the linux Joystick device: %s (%s)\n", dev, lpddi->tszProductName);
193         return TRUE;
194     }
195
196     return FALSE;
197 }
198
199 static BOOL joydev_enum_deviceW(DWORD dwDevType, DWORD dwFlags, LPDIDEVICEINSTANCEW lpddi, int version, int id)
200 {
201     int fd = -1;
202     char name[MAX_PATH];
203     char dev[32];
204     char friendly[32];
205
206     if (dwFlags & DIEDFL_FORCEFEEDBACK) {
207         WARN("force feedback not supported\n");
208         return FALSE;
209     }
210
211     if ((dwDevType == 0) ||
212         ((dwDevType == DIDEVTYPE_JOYSTICK) && (version < 8)) ||
213         (((dwDevType == DI8DEVCLASS_GAMECTRL) || (dwDevType == DI8DEVTYPE_JOYSTICK)) && (version >= 8))) {
214         /* check whether we have a joystick */
215         sprintf(dev, "%s%d", JOYDEV, id);
216         if ((fd = open(dev,O_RDONLY)) < 0) {
217             WARN("open(%s,O_RDONLY) failed: %s\n", dev, strerror(errno));
218             return FALSE;
219         }
220
221         /* Return joystick */
222         lpddi->guidInstance = DInput_Wine_Joystick_GUID;
223         lpddi->guidInstance.Data3 = id;
224         lpddi->guidProduct = DInput_Wine_Joystick_GUID;
225         /* we only support traditional joysticks for now */
226         if (version >= 8)
227             lpddi->dwDevType = DI8DEVTYPE_JOYSTICK | (DI8DEVTYPEJOYSTICK_STANDARD << 8);
228         else
229             lpddi->dwDevType = DIDEVTYPE_JOYSTICK | (DIDEVTYPEJOYSTICK_TRADITIONAL << 8);
230         sprintf(friendly, "Joystick %d", id);
231         MultiByteToWideChar(CP_ACP, 0, friendly, -1, lpddi->tszInstanceName, MAX_PATH);
232 #if defined(JSIOCGNAME)
233         if (ioctl(fd,JSIOCGNAME(sizeof(name)),name) < 0) {
234             WARN("ioctl(%s,JSIOCGNAME) failed: %s\n", dev, strerror(errno));
235             strcpy(name, "Wine Joystick");
236         }
237 #else
238         strcpy(name, "Wine Joystick");
239 #endif
240         MultiByteToWideChar(CP_ACP, 0, name, -1, lpddi->tszProductName, MAX_PATH);
241         lpddi->guidFFDriver = GUID_NULL;
242         close(fd);
243         TRACE("Enumerating the linux Joystick device: %s (%s)\n",dev,name);
244         return TRUE;
245     }
246
247     return FALSE;
248 }
249
250 /*
251  * Get a config key from either the app-specific or the default config
252  */
253
254 inline static DWORD get_config_key( HKEY defkey, HKEY appkey, const char *name,
255                                     char *buffer, DWORD size )
256 {
257     if (appkey && !RegQueryValueExA( appkey, name, 0, NULL, buffer, &size ))
258         return 0;
259
260     if (defkey && !RegQueryValueExA( defkey, name, 0, NULL, buffer, &size ))
261         return 0;
262
263     return ERROR_FILE_NOT_FOUND;
264 }
265
266 /*
267  * Setup the dinput options.
268  */
269
270 static HRESULT setup_dinput_options(JoystickImpl * device)
271 {
272     char buffer[MAX_PATH+1];
273     HKEY hkey, appkey = 0;
274     DWORD len;
275
276     buffer[MAX_PATH]='\0';
277
278     if (RegOpenKeyA( HKEY_LOCAL_MACHINE, "Software\\Wine\\dinput", &hkey)) hkey = 0;
279
280     len = GetModuleFileNameA( 0, buffer, MAX_PATH );
281     if (len && len < MAX_PATH) {
282         HKEY tmpkey;
283
284         if (!RegOpenKeyA( HKEY_LOCAL_MACHINE, "Software\\Wine\\AppDefaults", &tmpkey )) {
285            char appname[MAX_PATH+16];
286            char *p = strrchr( buffer, '\\' );
287            if (p!=NULL) {
288                    strcpy(appname,p+1);
289                    strcat(appname,"\\dinput");
290                    TRACE("appname = [%s] \n",appname);
291                    if (RegOpenKeyA( tmpkey, appname, &appkey )) appkey = 0;
292            }
293            RegCloseKey( tmpkey );
294         }
295     }
296
297     /* get options */
298
299     if (!get_config_key( hkey, appkey, "DefaultDeadZone", buffer, MAX_PATH )) {
300         device->deadzone = atoi(buffer);
301         TRACE("setting default deadzone to: \"%s\" %ld\n", buffer, device->deadzone);
302     }
303
304     if (!get_config_key( hkey, appkey, device->name, buffer, MAX_PATH )) {
305         int tokens = 0;
306         int axis = 0;
307         int pov = 0;
308         const char *delim = ",";
309         char * ptr;
310         TRACE("\"%s\" = \"%s\"\n", device->name, buffer);
311
312         device->axis_map = HeapAlloc(GetProcessHeap(), 0, device->axes * sizeof(int));
313         if (device->axis_map == 0)
314             return DIERR_OUTOFMEMORY;
315
316         if ((ptr = strtok(buffer, delim)) != NULL) {
317             do {
318                 if (strcmp(ptr, "X") == 0) {
319                     device->axis_map[tokens] = 0;
320                     axis++;
321                 } else if (strcmp(ptr, "Y") == 0) {
322                     device->axis_map[tokens] = 1;
323                     axis++;
324                 } else if (strcmp(ptr, "Z") == 0) {
325                     device->axis_map[tokens] = 2;
326                     axis++;
327                 } else if (strcmp(ptr, "Rx") == 0) {
328                     device->axis_map[tokens] = 3;
329                     axis++;
330                 } else if (strcmp(ptr, "Ry") == 0) {
331                     device->axis_map[tokens] = 4;
332                     axis++;
333                 } else if (strcmp(ptr, "Rz") == 0) {
334                     device->axis_map[tokens] = 5;
335                     axis++;
336                 } else if (strcmp(ptr, "Slider1") == 0) {
337                     device->axis_map[tokens] = 6;
338                     axis++;
339                 } else if (strcmp(ptr, "Slider2") == 0) {
340                     device->axis_map[tokens] = 7;
341                     axis++;
342                 } else if (strcmp(ptr, "POV1") == 0) {
343                     device->axis_map[tokens++] = 8;
344                     device->axis_map[tokens] = 8;
345                     pov++;
346                 } else if (strcmp(ptr, "POV2") == 0) {
347                     device->axis_map[tokens++] = 9;
348                     device->axis_map[tokens] = 9;
349                     pov++;
350                 } else if (strcmp(ptr, "POV3") == 0) {
351                     device->axis_map[tokens++] = 10;
352                     device->axis_map[tokens] = 10;
353                     pov++;
354                 } else if (strcmp(ptr, "POV4") == 0) {
355                     device->axis_map[tokens++] = 11;
356                     device->axis_map[tokens] = 11;
357                     pov++;
358                 } else {
359                     ERR("invalid joystick axis type: %s\n", ptr);
360                     device->axis_map[tokens] = tokens;
361                     axis++;
362                 }
363
364                 tokens++;
365             } while ((ptr = strtok(NULL, delim)) != NULL);
366
367             if (tokens != device->devcaps.dwAxes) {
368                 ERR("not all joystick axes mapped: %d axes(%d,%d), %d arguments\n", device->axes, axis, pov,tokens);
369                 while (tokens < device->axes) {
370                     device->axis_map[tokens] = tokens;
371                     tokens++;
372                 }
373             }
374         }
375
376         device->devcaps.dwAxes = axis;
377         device->devcaps.dwPOVs = pov;
378     }
379
380     if (appkey)
381         RegCloseKey( appkey );
382
383     if (hkey)
384         RegCloseKey( hkey );
385
386     return DI_OK;
387 }
388
389 void calculate_ids(JoystickImpl* device)
390 {
391     int i;
392     int axis = 0;
393     int button = 0;
394     int pov = 0;
395     int axis_base;
396     int pov_base;
397     int button_base;
398
399     /* Make two passes over the format. The first counts the number
400      * for each type and the second sets the id */
401     for (i = 0; i < device->user_df->dwNumObjs; i++) {
402         if (DIDFT_GETTYPE(device->user_df->rgodf[i].dwType) & DIDFT_AXIS)
403             axis++;
404         else if (DIDFT_GETTYPE(device->user_df->rgodf[i].dwType) & DIDFT_POV)
405             pov++;
406         else if (DIDFT_GETTYPE(device->user_df->rgodf[i].dwType) & DIDFT_BUTTON)
407             button++;
408     }
409
410     axis_base = 0;
411     pov_base = axis;
412     button_base = axis + pov;
413
414     axis = 0;
415     button = 0;
416     pov = 0;
417
418     for (i = 0; i < device->user_df->dwNumObjs; i++) {
419         DWORD type = 0;
420         if (DIDFT_GETTYPE(device->user_df->rgodf[i].dwType) & DIDFT_AXIS) {
421             axis++;
422             type = DIDFT_GETTYPE(device->user_df->rgodf[i].dwType) |
423                 DIDFT_MAKEINSTANCE(axis + axis_base);
424             TRACE("axis type = 0x%08lx\n", type);
425         } else if (DIDFT_GETTYPE(device->user_df->rgodf[i].dwType) & DIDFT_POV) {
426             pov++;
427             type = DIDFT_GETTYPE(device->user_df->rgodf[i].dwType) |
428                 DIDFT_MAKEINSTANCE(pov + pov_base);
429             TRACE("POV type = 0x%08lx\n", type);
430         } else if (DIDFT_GETTYPE(device->user_df->rgodf[i].dwType) & DIDFT_BUTTON) {
431             button++;
432             type = DIDFT_GETTYPE(device->user_df->rgodf[i].dwType) |
433                 DIDFT_MAKEINSTANCE(button + button_base);
434             TRACE("button type = 0x%08lx\n", type);
435         }
436         device->user_df->rgodf[i].dwType = type;
437     }
438 }
439
440 static HRESULT alloc_device(REFGUID rguid, LPVOID jvt, IDirectInputImpl *dinput, LPDIRECTINPUTDEVICEA* pdev)
441 {
442     DWORD i;
443     JoystickImpl* newDevice;
444     char name[MAX_PATH];
445     HRESULT hr;
446
447     newDevice = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(JoystickImpl));
448     if (newDevice == 0) {
449         WARN("out of memory\n");
450         *pdev = 0;
451         return DIERR_OUTOFMEMORY;
452     }
453
454     sprintf(newDevice->dev, "%s%d", JOYDEV, rguid->Data3);
455
456     if ((newDevice->joyfd = open(newDevice->dev,O_RDONLY)) < 0) {
457         WARN("open(%s,O_RDONLY) failed: %s\n", newDevice->dev, strerror(errno));
458         HeapFree(GetProcessHeap(), 0, newDevice);
459         return DIERR_DEVICENOTREG;
460     }
461
462     /* get the device name */
463 #if defined(JSIOCGNAME)
464     if (ioctl(newDevice->joyfd,JSIOCGNAME(MAX_PATH),name) < 0) {
465         WARN("ioctl(%s,JSIOCGNAME) failed: %s\n", newDevice->dev, strerror(errno));
466         strcpy(name, "Wine Joystick");
467     }
468 #else
469     strcpy(name, "Wine Joystick");
470 #endif
471
472     /* copy the device name */
473     newDevice->name = HeapAlloc(GetProcessHeap(),0,strlen(name) + 1);
474     strcpy(newDevice->name, name);
475
476 #ifdef JSIOCGAXES
477     if (ioctl(newDevice->joyfd,JSIOCGAXES,&newDevice->axes) < 0) {
478         WARN("ioctl(%s,JSIOCGAXES) failed: %s, defauting to 2\n", newDevice->dev, strerror(errno));
479         newDevice->axes = 2;
480     }
481 #endif
482 #ifdef JSIOCGBUTTONS
483     if (ioctl(newDevice->joyfd,JSIOCGBUTTONS,&newDevice->buttons) < 0) {
484         WARN("ioctl(%s,JSIOCGBUTTONS) failed: %s, defauting to 2\n", newDevice->dev, strerror(errno));
485         newDevice->buttons = 2;
486     }
487 #endif
488
489     newDevice->lpVtbl = jvt;
490     newDevice->ref = 1;
491     newDevice->dinput = dinput;
492     newDevice->acquired = FALSE;
493     newDevice->overflow = FALSE;
494     CopyMemory(&(newDevice->guid),rguid,sizeof(*rguid));
495
496     /* setup_dinput_options may change these */
497     newDevice->deadzone = 5000;
498     newDevice->devcaps.dwButtons = newDevice->buttons;
499     newDevice->devcaps.dwAxes = newDevice->axes;
500     newDevice->devcaps.dwPOVs = 0;
501
502     /* do any user specified configuration */
503     hr = setup_dinput_options(newDevice);
504     if (hr != DI_OK)
505         goto FAILED1;
506
507     if (newDevice->axis_map == 0) {
508         newDevice->axis_map = HeapAlloc(GetProcessHeap(), 0, newDevice->axes * sizeof(int));
509         if (newDevice->axis_map == 0)
510             goto FAILED;
511
512         for (i = 0; i < newDevice->axes; i++)
513             newDevice->axis_map[i] = i;
514     }
515
516     /* wine uses DIJOYSTATE2 as it's internal format so copy
517      * the already defined format c_dfDIJoystick2 */
518     newDevice->user_df = HeapAlloc(GetProcessHeap(),0,c_dfDIJoystick2.dwSize);
519     if (newDevice->user_df == 0)
520         goto FAILED;
521
522     CopyMemory(newDevice->user_df, &c_dfDIJoystick2, c_dfDIJoystick2.dwSize);
523
524     /* copy default objects */
525     newDevice->user_df->rgodf = HeapAlloc(GetProcessHeap(),0,c_dfDIJoystick2.dwNumObjs*c_dfDIJoystick2.dwObjSize);
526     if (newDevice->user_df->rgodf == 0)
527         goto FAILED;
528
529     CopyMemory(newDevice->user_df->rgodf,c_dfDIJoystick2.rgodf,c_dfDIJoystick2.dwNumObjs*c_dfDIJoystick2.dwObjSize);
530
531     /* create default properties */
532     newDevice->props = HeapAlloc(GetProcessHeap(),0,c_dfDIJoystick2.dwNumObjs*sizeof(ObjProps));
533     if (newDevice->props == 0)
534         goto FAILED;
535
536     /* initialize default properties */
537     for (i = 0; i < c_dfDIJoystick2.dwNumObjs; i++) {
538         newDevice->props[i].lMin = 0;
539         newDevice->props[i].lMax = 0xffff;
540         newDevice->props[i].lDeadZone = newDevice->deadzone;    /* % * 1000 */
541         newDevice->props[i].lSaturation = 0;
542     }
543
544     /* create an offsets array */
545     newDevice->offsets = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,c_dfDIJoystick2.dwNumObjs*sizeof(int));
546     if (newDevice->offsets == 0)
547         goto FAILED;
548
549     /* create the default transform filter */
550     newDevice->transform = create_DataFormat(&c_dfDIJoystick2, newDevice->user_df, newDevice->offsets);
551
552     calculate_ids(newDevice);
553
554     IDirectInputDevice_AddRef((LPDIRECTINPUTDEVICE8A)newDevice->dinput);
555     InitializeCriticalSection(&(newDevice->crit));
556     newDevice->crit.DebugInfo->Spare[1] = (DWORD)"DINPUT_Mouse";
557
558     newDevice->devcaps.dwSize = sizeof(newDevice->devcaps);
559     newDevice->devcaps.dwFlags = DIDC_ATTACHED;
560     if (newDevice->dinput->version >= 8)
561         newDevice->devcaps.dwDevType = DI8DEVTYPE_JOYSTICK | (DI8DEVTYPEJOYSTICK_STANDARD << 8);
562     else
563         newDevice->devcaps.dwDevType = DIDEVTYPE_JOYSTICK | (DIDEVTYPEJOYSTICK_TRADITIONAL << 8);
564     newDevice->devcaps.dwFFSamplePeriod = 0;
565     newDevice->devcaps.dwFFMinTimeResolution = 0;
566     newDevice->devcaps.dwFirmwareRevision = 0;
567     newDevice->devcaps.dwHardwareRevision = 0;
568     newDevice->devcaps.dwFFDriverVersion = 0;
569
570     if (TRACE_ON(dinput)) {
571         _dump_DIDATAFORMAT(newDevice->user_df);
572        for (i = 0; i < (newDevice->axes); i++)
573            TRACE("axis_map[%ld] = %d\n", i, newDevice->axis_map[i]);
574         _dump_DIDEVCAPS(&newDevice->devcaps);
575     }
576
577     *pdev = (LPDIRECTINPUTDEVICEA)newDevice;
578
579     return DI_OK;
580
581 FAILED:
582     hr = DIERR_OUTOFMEMORY;
583 FAILED1:
584     HeapFree(GetProcessHeap(),0,newDevice->axis_map);
585     HeapFree(GetProcessHeap(),0,newDevice->name);
586     HeapFree(GetProcessHeap(),0,newDevice->props);
587     HeapFree(GetProcessHeap(),0,newDevice->user_df->rgodf);
588     HeapFree(GetProcessHeap(),0,newDevice->user_df);
589     HeapFree(GetProcessHeap(),0,newDevice);
590     *pdev = 0;
591
592     return hr;
593 }
594
595 static BOOL IsJoystickGUID(REFGUID guid)
596 {
597     GUID wine_joystick = DInput_Wine_Joystick_GUID;
598     GUID dev_guid = *guid;
599
600     wine_joystick.Data3 = 0;
601     dev_guid.Data3 = 0;
602
603     return IsEqualGUID(&wine_joystick, &dev_guid);
604 }
605
606 static HRESULT joydev_create_deviceA(IDirectInputImpl *dinput, REFGUID rguid, REFIID riid, LPDIRECTINPUTDEVICEA* pdev)
607 {
608   if ((IsEqualGUID(&GUID_Joystick,rguid)) ||
609       (IsJoystickGUID(rguid))) {
610     if ((riid == NULL) ||
611         IsEqualGUID(&IID_IDirectInputDeviceA,riid) ||
612         IsEqualGUID(&IID_IDirectInputDevice2A,riid) ||
613         IsEqualGUID(&IID_IDirectInputDevice7A,riid) ||
614         IsEqualGUID(&IID_IDirectInputDevice8A,riid)) {
615       return alloc_device(rguid, &JoystickAvt, dinput, pdev);
616     } else {
617       WARN("no interface\n");
618       *pdev = 0;
619       return DIERR_NOINTERFACE;
620     }
621   }
622
623   WARN("invalid device GUID\n");
624   *pdev = 0;
625   return DIERR_DEVICENOTREG;
626 }
627
628 static HRESULT joydev_create_deviceW(IDirectInputImpl *dinput, REFGUID rguid, REFIID riid, LPDIRECTINPUTDEVICEW* pdev)
629 {
630   if ((IsEqualGUID(&GUID_Joystick,rguid)) ||
631       (IsJoystickGUID(rguid))) {
632     if ((riid == NULL) ||
633         IsEqualGUID(&IID_IDirectInputDeviceW,riid) ||
634         IsEqualGUID(&IID_IDirectInputDevice2W,riid) ||
635         IsEqualGUID(&IID_IDirectInputDevice7W,riid) ||
636         IsEqualGUID(&IID_IDirectInputDevice8W,riid)) {
637       return alloc_device(rguid, &JoystickWvt, dinput, (LPDIRECTINPUTDEVICEA *)pdev);
638     } else {
639       WARN("no interface\n");
640       *pdev = 0;
641       return DIERR_NOINTERFACE;
642     }
643   }
644
645   WARN("invalid device GUID\n");
646   *pdev = 0;
647   return DIERR_DEVICENOTREG;
648 }
649
650 const struct dinput_device joystick_linux_device = {
651   "Wine Linux joystick driver",
652   joydev_enum_deviceA,
653   joydev_enum_deviceW,
654   joydev_create_deviceA,
655   joydev_create_deviceW
656 };
657
658 /******************************************************************************
659  *      Joystick
660  */
661 static ULONG WINAPI JoystickAImpl_Release(LPDIRECTINPUTDEVICE8A iface)
662 {
663     JoystickImpl *This = (JoystickImpl *)iface;
664     ULONG ref;
665
666     ref = InterlockedDecrement((&This->ref));
667     if (ref)
668         return ref;
669
670     /* Free the device name */
671     HeapFree(GetProcessHeap(),0,This->name);
672
673     /* Free the axis map */
674     HeapFree(GetProcessHeap(),0,This->axis_map);
675
676     /* Free the data queue */
677     HeapFree(GetProcessHeap(),0,This->data_queue);
678
679     /* Free the DataFormat */
680     HeapFree(GetProcessHeap(), 0, This->user_df->rgodf);
681     HeapFree(GetProcessHeap(), 0, This->user_df);
682
683     /* Free the properties */
684     HeapFree(GetProcessHeap(), 0, This->props);
685
686     /* Free the offsets array */
687     HeapFree(GetProcessHeap(),0,This->offsets);
688
689     /* release the data transform filter */
690     release_DataFormat(This->transform);
691
692     This->crit.DebugInfo->Spare[1] = 0;
693     DeleteCriticalSection(&(This->crit));
694     IDirectInputDevice_Release((LPDIRECTINPUTDEVICE8A)This->dinput);
695
696     HeapFree(GetProcessHeap(),0,This);
697     return 0;
698 }
699
700 /******************************************************************************
701   *   SetDataFormat : the application can choose the format of the data
702   *   the device driver sends back with GetDeviceState.
703   */
704 static HRESULT WINAPI JoystickAImpl_SetDataFormat(
705     LPDIRECTINPUTDEVICE8A iface,
706     LPCDIDATAFORMAT df)
707 {
708     JoystickImpl *This = (JoystickImpl *)iface;
709     unsigned int i;
710     LPDIDATAFORMAT new_df = 0;
711     LPDIOBJECTDATAFORMAT new_rgodf = 0;
712     ObjProps * new_props = 0;
713
714     TRACE("(%p,%p)\n",This,df);
715
716     if (This->acquired) {
717         WARN("acquired\n");
718         return DIERR_ACQUIRED;
719     }
720
721     if (TRACE_ON(dinput))
722         _dump_DIDATAFORMAT(df);
723
724     /* Store the new data format */
725     new_df = HeapAlloc(GetProcessHeap(),0,df->dwSize);
726     if (new_df == 0)
727         goto FAILED;
728
729     new_rgodf = HeapAlloc(GetProcessHeap(),0,df->dwNumObjs*df->dwObjSize);
730     if (new_rgodf == 0)
731         goto FAILED;
732
733     new_props = HeapAlloc(GetProcessHeap(),0,df->dwNumObjs*sizeof(ObjProps));
734     if (new_props == 0)
735         goto FAILED;
736
737     HeapFree(GetProcessHeap(),0,This->user_df);
738     HeapFree(GetProcessHeap(),0,This->user_df->rgodf);
739     HeapFree(GetProcessHeap(),0,This->props);
740     release_DataFormat(This->transform);
741
742     This->user_df = new_df;
743     CopyMemory(This->user_df, df, df->dwSize);
744     This->user_df->rgodf = new_rgodf;
745     CopyMemory(This->user_df->rgodf,df->rgodf,df->dwNumObjs*df->dwObjSize);
746     This->props = new_props;
747     for (i = 0; i < df->dwNumObjs; i++) {
748         This->props[i].lMin = 0;
749         This->props[i].lMax = 0xffff;
750         This->props[i].lDeadZone = 1000;
751         This->props[i].lSaturation = 0;
752     }
753     This->transform = create_DataFormat(&c_dfDIJoystick2, This->user_df, This->offsets);
754
755     calculate_ids(This);
756
757     return DI_OK;
758
759 FAILED:
760     WARN("out of memory\n");
761     HeapFree(GetProcessHeap(),0,new_props);
762     HeapFree(GetProcessHeap(),0,new_rgodf);
763     HeapFree(GetProcessHeap(),0,new_df);
764     return DIERR_OUTOFMEMORY;
765 }
766
767 /******************************************************************************
768   *     Acquire : gets exclusive control of the joystick
769   */
770 static HRESULT WINAPI JoystickAImpl_Acquire(LPDIRECTINPUTDEVICE8A iface)
771 {
772     JoystickImpl *This = (JoystickImpl *)iface;
773
774     TRACE("(%p)\n",This);
775
776     if (This->acquired) {
777         WARN("already acquired\n");
778         return S_FALSE;
779     }
780
781     /* open the joystick device */
782     if (This->joyfd==-1) {
783         TRACE("opening joystick device %s\n", This->dev);
784
785         This->joyfd=open(This->dev,O_RDONLY);
786         if (This->joyfd==-1) {
787             ERR("open(%s) failed: %s\n", This->dev, strerror(errno));
788             return DIERR_NOTFOUND;
789         }
790     }
791
792     This->acquired = TRUE;
793
794     return DI_OK;
795 }
796
797 /******************************************************************************
798   *     Unacquire : frees the joystick
799   */
800 static HRESULT WINAPI JoystickAImpl_Unacquire(LPDIRECTINPUTDEVICE8A iface)
801 {
802     JoystickImpl *This = (JoystickImpl *)iface;
803
804     TRACE("(%p)\n",This);
805
806     if (!This->acquired) {
807         WARN("not acquired\n");
808         return DIERR_NOTACQUIRED;
809     }
810
811     if (This->joyfd!=-1) {
812         TRACE("closing joystick device\n");
813         close(This->joyfd);
814         This->joyfd = -1;
815         This->acquired = FALSE;
816         return DI_OK;
817     }
818
819     This->acquired = FALSE;
820
821     return DI_NOEFFECT;
822 }
823
824 LONG map_axis(JoystickImpl * This, short val, short index)
825 {
826     double    fval = val;
827     double    fmin = This->props[index].lMin;
828     double    fmax = This->props[index].lMax;
829     double    fret;
830
831     fret = (((fval + 32767.0) * (fmax - fmin)) / (32767.0*2.0)) + fmin;
832
833     if (fret >= 0.0)
834         fret += 0.5;
835     else
836         fret -= 0.5;
837
838     return fret;
839 }
840
841 /* convert wine format offset to user format object index */
842 int offset_to_object(JoystickImpl *This, int offset)
843 {
844     int i;
845
846     for (i = 0; i < This->user_df->dwNumObjs; i++) {
847         if (This->user_df->rgodf[i].dwOfs == offset)
848             return i;
849     }
850
851     return -1;
852 }
853
854 static LONG calculate_pov(JoystickImpl *This, int index)
855 {
856     if (This->povs[index].lX < 16384) {
857         if (This->povs[index].lY < 16384)
858             This->js.rgdwPOV[index] = 31500;
859         else if (This->povs[index].lY > 49150)
860             This->js.rgdwPOV[index] = 22500;
861         else
862             This->js.rgdwPOV[index] = 27000;
863     } else if (This->povs[index].lX > 49150) {
864         if (This->povs[index].lY < 16384)
865             This->js.rgdwPOV[index] = 4500;
866         else if (This->povs[index].lY > 49150)
867             This->js.rgdwPOV[index] = 13500;
868         else
869             This->js.rgdwPOV[index] = 9000;
870     } else {
871         if (This->povs[index].lY < 16384)
872             This->js.rgdwPOV[index] = 0;
873         else if (This->povs[index].lY > 49150)
874             This->js.rgdwPOV[index] = 18000;
875         else
876             This->js.rgdwPOV[index] = -1;
877     }
878
879     return This->js.rgdwPOV[index];
880 }
881
882 static void joy_polldev(JoystickImpl *This) {
883     struct timeval tv;
884     fd_set      readfds;
885     struct      js_event jse;
886     TRACE("(%p)\n", This);
887
888     if (This->joyfd==-1) {
889         WARN("no device\n");
890         return;
891     }
892     while (1) {
893         memset(&tv,0,sizeof(tv));
894         FD_ZERO(&readfds);FD_SET(This->joyfd,&readfds);
895         if (1>select(This->joyfd+1,&readfds,NULL,NULL,&tv))
896             return;
897         /* we have one event, so we can read */
898         if (sizeof(jse)!=read(This->joyfd,&jse,sizeof(jse))) {
899             return;
900         }
901         TRACE("js_event: type 0x%x, number %d, value %d\n",
902               jse.type,jse.number,jse.value);
903         if (jse.type & JS_EVENT_BUTTON) {
904             int offset = This->offsets[jse.number + 12];
905             int value = jse.value?0x80:0x00;
906
907             This->js.rgbButtons[jse.number] = value;
908             GEN_EVENT(offset,value,jse.time,(This->dinput->evsequence)++);
909         } else if (jse.type & JS_EVENT_AXIS) {
910             int number = This->axis_map[jse.number];    /* wine format object index */
911             if (number < 12) {
912                 int offset = This->offsets[number];
913                 int index = offset_to_object(This, offset);
914                 LONG value = map_axis(This, jse.value, index);
915
916                 /* FIXME do deadzone and saturation here */
917
918                 TRACE("changing axis %d => %d\n", jse.number, number);
919                 switch (number) {
920                 case 0:
921                     This->js.lX = value;
922                     break;
923                 case 1:
924                     This->js.lY = value;
925                     break;
926                 case 2:
927                     This->js.lZ = value;
928                     break;
929                 case 3:
930                     This->js.lRx = value;
931                     break;
932                 case 4:
933                     This->js.lRy = value;
934                     break;
935                 case 5:
936                     This->js.lRz = value;
937                     break;
938                 case 6:
939                     This->js.rglSlider[0] = value;
940                     break;
941                 case 7:
942                     This->js.rglSlider[1] = value;
943                     break;
944                 case 8:
945                     /* FIXME don't go off array */
946                     if (This->axis_map[jse.number + 1] == number)
947                         This->povs[0].lX = value;
948                     else if (This->axis_map[jse.number - 1] == number)
949                         This->povs[0].lY = value;
950                     value = calculate_pov(This, 0);
951                     break;
952                 case 9:
953                     if (This->axis_map[jse.number + 1] == number)
954                         This->povs[1].lX = value;
955                     else if (This->axis_map[jse.number - 1] == number)
956                         This->povs[1].lY = value;
957                     value = calculate_pov(This, 1);
958                     break;
959                 case 10:
960                     if (This->axis_map[jse.number + 1] == number)
961                         This->povs[2].lX = value;
962                     else if (This->axis_map[jse.number - 1] == number)
963                         This->povs[2].lY = value;
964                     value = calculate_pov(This, 2);
965                     break;
966                 case 11:
967                     if (This->axis_map[jse.number + 1] == number)
968                         This->povs[3].lX = value;
969                     else if (This->axis_map[jse.number - 1] == number)
970                         This->povs[3].lY = value;
971                     value = calculate_pov(This, 3);
972                     break;
973                 }
974
975                 GEN_EVENT(offset,value,jse.time,(This->dinput->evsequence)++);
976             } else
977                 WARN("axis %d not supported\n", number);
978         }
979     }
980 }
981
982 /******************************************************************************
983   *     GetDeviceState : returns the "state" of the joystick.
984   *
985   */
986 static HRESULT WINAPI JoystickAImpl_GetDeviceState(
987     LPDIRECTINPUTDEVICE8A iface,
988     DWORD len,
989     LPVOID ptr)
990 {
991     JoystickImpl *This = (JoystickImpl *)iface;
992
993     TRACE("(%p,0x%08lx,%p)\n",This,len,ptr);
994
995     if (!This->acquired) {
996         WARN("not acquired\n");
997         return DIERR_NOTACQUIRED;
998     }
999
1000     /* update joystick state */
1001     joy_polldev(This);
1002
1003     /* convert and copy data to user supplied buffer */
1004     fill_DataFormat(ptr, &This->js, This->transform);
1005
1006     return DI_OK;
1007 }
1008
1009 /******************************************************************************
1010   *     GetDeviceData : gets buffered input data.
1011   */
1012 static HRESULT WINAPI JoystickAImpl_GetDeviceData(
1013     LPDIRECTINPUTDEVICE8A iface,
1014     DWORD dodsize,
1015     LPDIDEVICEOBJECTDATA dod,
1016     LPDWORD entries,
1017     DWORD flags)
1018 {
1019     JoystickImpl *This = (JoystickImpl *)iface;
1020     DWORD len;
1021     int nqtail;
1022     HRESULT hr = DI_OK;
1023
1024     TRACE("(%p)->(dods=%ld,entries=%ld,fl=0x%08lx)\n",This,dodsize,*entries,flags);
1025
1026     if (!This->acquired) {
1027         WARN("not acquired\n");
1028         return DIERR_NOTACQUIRED;
1029     }
1030
1031     EnterCriticalSection(&(This->crit));
1032
1033     joy_polldev(This);
1034
1035     len = ((This->queue_head < This->queue_tail) ? This->queue_len : 0)
1036         + (This->queue_head - This->queue_tail);
1037     if (len > *entries)
1038         len = *entries;
1039
1040     if (dod == NULL) {
1041         if (len)
1042             TRACE("Application discarding %ld event(s).\n", len);
1043
1044         *entries = len;
1045         nqtail = This->queue_tail + len;
1046         while (nqtail >= This->queue_len)
1047             nqtail -= This->queue_len;
1048     } else {
1049         if (dodsize < sizeof(DIDEVICEOBJECTDATA_DX3)) {
1050             ERR("Wrong structure size !\n");
1051             LeaveCriticalSection(&(This->crit));
1052             return DIERR_INVALIDPARAM;
1053         }
1054
1055         if (len)
1056             TRACE("Application retrieving %ld event(s).\n", len);
1057
1058         *entries = 0;
1059         nqtail = This->queue_tail;
1060         while (len) {
1061             /* Copy the buffered data into the application queue */
1062             memcpy((char *)dod + *entries * dodsize, This->data_queue + nqtail, dodsize);
1063             /* Advance position */
1064             nqtail++;
1065             if (nqtail >= This->queue_len)
1066                 nqtail -= This->queue_len;
1067             (*entries)++;
1068             len--;
1069         }
1070     }
1071
1072     if (This->overflow) {
1073         hr = DI_BUFFEROVERFLOW;
1074         if (!(flags & DIGDD_PEEK)) {
1075             This->overflow = FALSE;
1076         }
1077     }
1078
1079     if (!(flags & DIGDD_PEEK))
1080         This->queue_tail = nqtail;
1081
1082     LeaveCriticalSection(&(This->crit));
1083
1084     return hr;
1085 }
1086
1087 int find_property(JoystickImpl * This, LPCDIPROPHEADER ph)
1088 {
1089     int i;
1090     if (ph->dwHow == DIPH_BYOFFSET) {
1091         return offset_to_object(This, ph->dwObj);
1092     } else if (ph->dwHow == DIPH_BYID) {
1093         for (i = 0; i < This->user_df->dwNumObjs; i++) {
1094             if ((This->user_df->rgodf[i].dwType & 0x00ffffff) == (ph->dwObj & 0x00ffffff)) {
1095                 return i;
1096             }
1097         }
1098     }
1099
1100     return -1;
1101 }
1102
1103 /******************************************************************************
1104   *     SetProperty : change input device properties
1105   */
1106 static HRESULT WINAPI JoystickAImpl_SetProperty(
1107     LPDIRECTINPUTDEVICE8A iface,
1108     REFGUID rguid,
1109     LPCDIPROPHEADER ph)
1110 {
1111     JoystickImpl *This = (JoystickImpl *)iface;
1112     int i;
1113
1114     TRACE("(%p,%s,%p)\n",This,debugstr_guid(rguid),ph);
1115
1116     if (TRACE_ON(dinput))
1117         _dump_DIPROPHEADER(ph);
1118
1119     if (!HIWORD(rguid)) {
1120         switch ((DWORD)rguid) {
1121         case (DWORD) DIPROP_BUFFERSIZE: {
1122             LPCDIPROPDWORD      pd = (LPCDIPROPDWORD)ph;
1123             TRACE("buffersize = %ld\n",pd->dwData);
1124             if (This->data_queue)
1125                 This->data_queue = HeapReAlloc(GetProcessHeap(),0, This->data_queue, pd->dwData * sizeof(DIDEVICEOBJECTDATA));
1126             else
1127                 This->data_queue = HeapAlloc(GetProcessHeap(),0, pd->dwData * sizeof(DIDEVICEOBJECTDATA));
1128             This->queue_head = 0;
1129             This->queue_tail = 0;
1130             This->queue_len  = pd->dwData;
1131             break;
1132         }
1133         case (DWORD)DIPROP_RANGE: {
1134             LPCDIPROPRANGE      pr = (LPCDIPROPRANGE)ph;
1135             if (ph->dwHow == DIPH_DEVICE) {
1136                 TRACE("proprange(%ld,%ld) all\n",pr->lMin,pr->lMax);
1137                 for (i = 0; i < This->user_df->dwNumObjs; i++) {
1138                     This->props[i].lMin = pr->lMin;
1139                     This->props[i].lMax = pr->lMax;
1140                 }
1141             } else {
1142                 int obj = find_property(This, ph);
1143                 TRACE("proprange(%ld,%ld) obj=%d\n",pr->lMin,pr->lMax,obj);
1144                 if (obj >= 0) {
1145                     This->props[obj].lMin = pr->lMin;
1146                     This->props[obj].lMax = pr->lMax;
1147                     return DI_OK;
1148                 }
1149             }
1150             break;
1151         }
1152         case (DWORD)DIPROP_DEADZONE: {
1153             LPCDIPROPDWORD      pd = (LPCDIPROPDWORD)ph;
1154             if (ph->dwHow == DIPH_DEVICE) {
1155                 TRACE("deadzone(%ld) all\n",pd->dwData);
1156                 for (i = 0; i < This->user_df->dwNumObjs; i++)
1157                     This->props[i].lDeadZone  = pd->dwData;
1158             } else {
1159                 int obj = find_property(This, ph);
1160                 TRACE("deadzone(%ld) obj=%d\n",pd->dwData,obj);
1161                 if (obj >= 0) {
1162                     This->props[obj].lDeadZone  = pd->dwData;
1163                     return DI_OK;
1164                 }
1165             }
1166             break;
1167         }
1168         case (DWORD)DIPROP_SATURATION: {
1169             LPCDIPROPDWORD      pd = (LPCDIPROPDWORD)ph;
1170             if (ph->dwHow == DIPH_DEVICE) {
1171                 TRACE("saturation(%ld) all\n",pd->dwData);
1172                 for (i = 0; i < This->user_df->dwNumObjs; i++)
1173                     This->props[i].lSaturation = pd->dwData;
1174             } else {
1175                 int obj = find_property(This, ph);
1176                 TRACE("saturation(%ld) obj=%d\n",pd->dwData,obj);
1177                 if (obj >= 0) {
1178                     This->props[obj].lSaturation = pd->dwData;
1179                     return DI_OK;
1180                 }
1181             }
1182             break;
1183         }
1184         default:
1185             FIXME("Unknown type %ld (%s)\n",(DWORD)rguid,debugstr_guid(rguid));
1186             break;
1187         }
1188     }
1189
1190     return DI_OK;
1191 }
1192
1193 /******************************************************************************
1194   *     SetEventNotification : specifies event to be sent on state change
1195   */
1196 static HRESULT WINAPI JoystickAImpl_SetEventNotification(
1197         LPDIRECTINPUTDEVICE8A iface, HANDLE hnd
1198 ) {
1199     JoystickImpl *This = (JoystickImpl *)iface;
1200
1201     TRACE("(this=%p,0x%08lx)\n",This,(DWORD)hnd);
1202     This->hEvent = hnd;
1203     return DI_OK;
1204 }
1205
1206 static HRESULT WINAPI JoystickAImpl_GetCapabilities(
1207         LPDIRECTINPUTDEVICE8A iface,
1208         LPDIDEVCAPS lpDIDevCaps)
1209 {
1210     JoystickImpl *This = (JoystickImpl *)iface;
1211     int size;
1212
1213     TRACE("%p->(%p)\n",iface,lpDIDevCaps);
1214
1215     if (lpDIDevCaps == NULL) {
1216         WARN("invalid parameter: lpDIDevCaps = NULL\n");
1217         return DIERR_INVALIDPARAM;
1218     }
1219
1220     size = lpDIDevCaps->dwSize;
1221     CopyMemory(lpDIDevCaps, &This->devcaps, size);
1222     lpDIDevCaps->dwSize = size;
1223
1224     if (TRACE_ON(dinput))
1225         _dump_DIDEVCAPS(lpDIDevCaps);
1226
1227     return DI_OK;
1228 }
1229
1230 static HRESULT WINAPI JoystickAImpl_Poll(LPDIRECTINPUTDEVICE8A iface)
1231 {
1232     JoystickImpl *This = (JoystickImpl *)iface;
1233
1234     TRACE("(%p)\n",This);
1235
1236     if (!This->acquired) {
1237         WARN("not acquired\n");
1238         return DIERR_NOTACQUIRED;
1239     }
1240
1241     joy_polldev(This);
1242     return DI_OK;
1243 }
1244
1245 /******************************************************************************
1246   *     EnumObjects : enumerate the different buttons and axis...
1247   */
1248 static HRESULT WINAPI JoystickAImpl_EnumObjects(
1249         LPDIRECTINPUTDEVICE8A iface,
1250         LPDIENUMDEVICEOBJECTSCALLBACKA lpCallback,
1251         LPVOID lpvRef,
1252         DWORD dwFlags)
1253 {
1254   JoystickImpl *This = (JoystickImpl *)iface;
1255   DIDEVICEOBJECTINSTANCEA ddoi;
1256   BYTE i;
1257   int user_offset;
1258   int user_object;
1259
1260   TRACE("(this=%p,%p,%p,%08lx)\n", This, lpCallback, lpvRef, dwFlags);
1261   if (TRACE_ON(dinput)) {
1262     TRACE("  - flags = ");
1263     _dump_EnumObjects_flags(dwFlags);
1264     TRACE("\n");
1265   }
1266
1267   /* Only the fields till dwFFMaxForce are relevant */
1268   ddoi.dwSize = FIELD_OFFSET(DIDEVICEOBJECTINSTANCEA, dwFFMaxForce);
1269
1270   /* For the joystick, do as is done in the GetCapabilities function */
1271   if ((dwFlags == DIDFT_ALL) ||
1272       (dwFlags & DIDFT_AXIS) ||
1273       (dwFlags & DIDFT_POV)) {
1274     int pov[4] = { 0, 0, 0, 0 };
1275     int axes = 0;
1276     int povs = 0;
1277
1278     for (i = 0; i < This->axes; i++) {
1279       int wine_obj = This->axis_map[i];
1280       BOOL skip = FALSE;
1281
1282       switch (wine_obj) {
1283       case 0:
1284         ddoi.guidType = GUID_XAxis;
1285         break;
1286       case 1:
1287         ddoi.guidType = GUID_YAxis;
1288         break;
1289       case 2:
1290         ddoi.guidType = GUID_ZAxis;
1291         break;
1292       case 3:
1293         ddoi.guidType = GUID_RxAxis;
1294         break;
1295       case 4:
1296         ddoi.guidType = GUID_RyAxis;
1297         break;
1298       case 5:
1299         ddoi.guidType = GUID_RzAxis;
1300         break;
1301       case 6:
1302         ddoi.guidType = GUID_Slider;
1303         break;
1304       case 7:
1305         ddoi.guidType = GUID_Slider;
1306         break;
1307       case 8:
1308         pov[0]++;
1309         ddoi.guidType = GUID_POV;
1310         break;
1311       case 9:
1312         pov[1]++;
1313         ddoi.guidType = GUID_POV;
1314         break;
1315       case 10:
1316         pov[2]++;
1317         ddoi.guidType = GUID_POV;
1318         break;
1319       case 11:
1320         pov[3]++;
1321         ddoi.guidType = GUID_POV;
1322         break;
1323       default:
1324         ddoi.guidType = GUID_Unknown;
1325       }
1326       if (wine_obj < 8) {
1327           user_offset = This->offsets[wine_obj];        /* get user offset from wine index */
1328           user_object = offset_to_object(This, user_offset);
1329
1330           ddoi.dwType = This->user_df->rgodf[user_object].dwType & 0x00ffffff;
1331           ddoi.dwOfs =  This->user_df->rgodf[user_object].dwOfs;
1332           sprintf(ddoi.tszName, "Axis %d", axes);
1333           axes++;
1334       } else {
1335           if (pov[wine_obj - 8] < 2) {
1336               user_offset = This->offsets[wine_obj];    /* get user offset from wine index */
1337               user_object = offset_to_object(This, user_offset);
1338
1339               ddoi.dwType = This->user_df->rgodf[user_object].dwType & 0x00ffffff;
1340               ddoi.dwOfs =  This->user_df->rgodf[user_object].dwOfs;
1341               sprintf(ddoi.tszName, "POV %d", povs);
1342               povs++;
1343           } else
1344               skip = TRUE;
1345       }
1346       if (!skip) {
1347           _dump_OBJECTINSTANCEA(&ddoi);
1348           if (lpCallback(&ddoi, lpvRef) != DIENUM_CONTINUE)
1349               return DI_OK;
1350       }
1351     }
1352   }
1353
1354   if ((dwFlags == DIDFT_ALL) ||
1355       (dwFlags & DIDFT_BUTTON)) {
1356
1357     /* The DInput SDK says that GUID_Button is only for mouse buttons but well... */
1358     ddoi.guidType = GUID_Button;
1359
1360     for (i = 0; i < This->buttons; i++) {
1361       user_offset = This->offsets[i + 12];      /* get user offset from wine index */
1362       user_object = offset_to_object(This, user_offset);
1363       ddoi.guidType = GUID_Button;
1364       ddoi.dwType = This->user_df->rgodf[user_object].dwType & 0x00ffffff;
1365       ddoi.dwOfs =  This->user_df->rgodf[user_object].dwOfs;
1366       sprintf(ddoi.tszName, "Button %d", i);
1367       _dump_OBJECTINSTANCEA(&ddoi);
1368       if (lpCallback(&ddoi, lpvRef) != DIENUM_CONTINUE) return DI_OK;
1369     }
1370   }
1371
1372   return DI_OK;
1373 }
1374
1375 /******************************************************************************
1376   *     EnumObjects : enumerate the different buttons and axis...
1377   */
1378 static HRESULT WINAPI JoystickWImpl_EnumObjects(
1379         LPDIRECTINPUTDEVICE8W iface,
1380         LPDIENUMDEVICEOBJECTSCALLBACKW lpCallback,
1381         LPVOID lpvRef,
1382         DWORD dwFlags)
1383 {
1384   JoystickImpl *This = (JoystickImpl *)iface;
1385
1386   device_enumobjects_AtoWcb_data data;
1387
1388   data.lpCallBack = lpCallback;
1389   data.lpvRef = lpvRef;
1390
1391   return JoystickAImpl_EnumObjects((LPDIRECTINPUTDEVICE8A) This, (LPDIENUMDEVICEOBJECTSCALLBACKA) DIEnumDevicesCallbackAtoW, (LPVOID) &data, dwFlags);
1392 }
1393
1394 /******************************************************************************
1395   *     GetProperty : get input device properties
1396   */
1397 static HRESULT WINAPI JoystickAImpl_GetProperty(
1398     LPDIRECTINPUTDEVICE8A iface,
1399     REFGUID rguid,
1400     LPDIPROPHEADER pdiph)
1401 {
1402     JoystickImpl *This = (JoystickImpl *)iface;
1403
1404     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(rguid), pdiph);
1405
1406     if (TRACE_ON(dinput))
1407         _dump_DIPROPHEADER(pdiph);
1408
1409     if (!HIWORD(rguid)) {
1410         switch ((DWORD)rguid) {
1411         case (DWORD) DIPROP_BUFFERSIZE: {
1412             LPDIPROPDWORD       pd = (LPDIPROPDWORD)pdiph;
1413             TRACE(" return buffersize = %d\n",This->queue_len);
1414             pd->dwData = This->queue_len;
1415             break;
1416         }
1417         case (DWORD) DIPROP_RANGE: {
1418             LPDIPROPRANGE pr = (LPDIPROPRANGE) pdiph;
1419             int obj = find_property(This, pdiph);
1420             /* The app is querying the current range of the axis
1421              * return the lMin and lMax values */
1422             if (obj >= 0) {
1423                 pr->lMin = This->props[obj].lMin;
1424                 pr->lMax = This->props[obj].lMax;
1425                 TRACE("range(%ld, %ld) obj=%d\n", pr->lMin, pr->lMax, obj);
1426                 return DI_OK;
1427             }
1428             break;
1429         }
1430         case (DWORD) DIPROP_DEADZONE: {
1431             LPDIPROPDWORD       pd = (LPDIPROPDWORD)pdiph;
1432             int obj = find_property(This, pdiph);
1433             if (obj >= 0) {
1434                 pd->dwData = This->props[obj].lDeadZone;
1435                 TRACE("deadzone(%ld) obj=%d\n", pd->dwData, obj);
1436                 return DI_OK;
1437             }
1438             break;
1439         }
1440         case (DWORD) DIPROP_SATURATION: {
1441             LPDIPROPDWORD       pd = (LPDIPROPDWORD)pdiph;
1442             int obj = find_property(This, pdiph);
1443             if (obj >= 0) {
1444                 pd->dwData = This->props[obj].lSaturation;
1445                 TRACE("saturation(%ld) obj=%d\n", pd->dwData, obj);
1446                 return DI_OK;
1447             }
1448             break;
1449         }
1450         default:
1451             FIXME("Unknown type %ld (%s)\n",(DWORD)rguid,debugstr_guid(rguid));
1452             break;
1453         }
1454     }
1455
1456     return DI_OK;
1457 }
1458
1459 /******************************************************************************
1460   *     GetObjectInfo : get object info
1461   */
1462 HRESULT WINAPI JoystickAImpl_GetObjectInfo(
1463         LPDIRECTINPUTDEVICE8A iface,
1464         LPDIDEVICEOBJECTINSTANCEA pdidoi,
1465         DWORD dwObj,
1466         DWORD dwHow)
1467 {
1468     JoystickImpl *This = (JoystickImpl *)iface;
1469     DIDEVICEOBJECTINSTANCEA didoiA;
1470     unsigned int i;
1471
1472     TRACE("(%p,%p,%ld,0x%08lx(%s))\n",
1473           iface, pdidoi, dwObj, dwHow,
1474           dwHow == DIPH_BYOFFSET ? "DIPH_BYOFFSET" :
1475           dwHow == DIPH_BYID ? "DIPH_BYID" :
1476           dwHow == DIPH_BYUSAGE ? "DIPH_BYUSAGE" :
1477           "UNKNOWN");
1478
1479     if (pdidoi == NULL) {
1480         WARN("invalid parameter: pdidoi = NULL\n");
1481         return DIERR_INVALIDPARAM;
1482     }
1483
1484     if ((pdidoi->dwSize != sizeof(DIDEVICEOBJECTINSTANCEA)) &&
1485         (pdidoi->dwSize != sizeof(DIDEVICEOBJECTINSTANCE_DX3A))) {
1486         WARN("invalid parameter: pdidoi->dwSize = %ld != %d or %d\n",
1487              pdidoi->dwSize, sizeof(DIDEVICEOBJECTINSTANCEA),
1488              sizeof(DIDEVICEOBJECTINSTANCE_DX3A));
1489         return DIERR_INVALIDPARAM;
1490     }
1491
1492     ZeroMemory(&didoiA, sizeof(didoiA));
1493     didoiA.dwSize = pdidoi->dwSize;
1494
1495     switch (dwHow) {
1496     case DIPH_BYOFFSET: {
1497         int axis = 0;
1498         int pov = 0;
1499         int button = 0;
1500         for (i = 0; i < This->user_df->dwNumObjs; i++) {
1501             if (This->user_df->rgodf[i].dwOfs == dwObj) {
1502                 if (This->user_df->rgodf[i].pguid)
1503                     didoiA.guidType = *This->user_df->rgodf[i].pguid;
1504                 else
1505                     didoiA.guidType = GUID_NULL;
1506
1507                 didoiA.dwOfs = dwObj;
1508                 didoiA.dwType = This->user_df->rgodf[i].dwType;
1509                 didoiA.dwFlags = This->user_df->rgodf[i].dwFlags;
1510
1511                 if (DIDFT_GETTYPE(This->user_df->rgodf[i].dwType) & DIDFT_AXIS)
1512                     sprintf(didoiA.tszName, "Axis %d", axis);
1513                 else if (DIDFT_GETTYPE(This->user_df->rgodf[i].dwType) & DIDFT_POV)
1514                     sprintf(didoiA.tszName, "POV %d", pov);
1515                 else if (DIDFT_GETTYPE(This->user_df->rgodf[i].dwType) & DIDFT_BUTTON)
1516                     sprintf(didoiA.tszName, "Button %d", button);
1517
1518                 CopyMemory(pdidoi, &didoiA, pdidoi->dwSize);
1519                 return DI_OK;
1520             }
1521
1522             if (DIDFT_GETTYPE(This->user_df->rgodf[i].dwType) & DIDFT_AXIS)
1523                 axis++;
1524             else if (DIDFT_GETTYPE(This->user_df->rgodf[i].dwType) & DIDFT_POV)
1525                 pov++;
1526             else if (DIDFT_GETTYPE(This->user_df->rgodf[i].dwType) & DIDFT_BUTTON)
1527                 button++;
1528         }
1529         break;
1530     }
1531     case DIPH_BYID:
1532         FIXME("dwHow = DIPH_BYID not implemented\n");
1533         break;
1534     case DIPH_BYUSAGE:
1535         FIXME("dwHow = DIPH_BYUSAGE not implemented\n");
1536         break;
1537     default:
1538         WARN("invalid parameter: dwHow = %08lx\n", dwHow);
1539         return DIERR_INVALIDPARAM;
1540     }
1541
1542     CopyMemory(pdidoi, &didoiA, pdidoi->dwSize);
1543
1544     return DI_OK;
1545 }
1546
1547 /******************************************************************************
1548   *     GetDeviceInfo : get information about a device's identity
1549   */
1550 HRESULT WINAPI JoystickAImpl_GetDeviceInfo(
1551     LPDIRECTINPUTDEVICE8A iface,
1552     LPDIDEVICEINSTANCEA pdidi)
1553 {
1554     JoystickImpl *This = (JoystickImpl *)iface;
1555
1556     TRACE("(%p,%p)\n", iface, pdidi);
1557
1558     if ((pdidi->dwSize != sizeof(DIDEVICEINSTANCE_DX3A)) &&
1559         (pdidi->dwSize != sizeof(DIDEVICEINSTANCEA))) {
1560         WARN("invalid parameter: pdidi->dwSize = %ld != %d or %d\n",
1561              pdidi->dwSize, sizeof(DIDEVICEINSTANCE_DX3A),
1562              sizeof(DIDEVICEINSTANCEA));
1563         return DIERR_INVALIDPARAM;
1564     }
1565
1566     /* Return joystick */
1567     pdidi->guidInstance = GUID_Joystick;
1568     pdidi->guidProduct = DInput_Wine_Joystick_GUID;
1569     /* we only support traditional joysticks for now */
1570     pdidi->dwDevType = This->devcaps.dwDevType;
1571     strcpy(pdidi->tszInstanceName, "Joystick");
1572     strcpy(pdidi->tszProductName, This->name);
1573     if (pdidi->dwSize > sizeof(DIDEVICEINSTANCE_DX3A)) {
1574         pdidi->guidFFDriver = GUID_NULL;
1575         pdidi->wUsagePage = 0;
1576         pdidi->wUsage = 0;
1577     }
1578
1579     return DI_OK;
1580 }
1581
1582 /******************************************************************************
1583   *     GetDeviceInfo : get information about a device's identity
1584   */
1585 HRESULT WINAPI JoystickWImpl_GetDeviceInfo(
1586     LPDIRECTINPUTDEVICE8W iface,
1587     LPDIDEVICEINSTANCEW pdidi)
1588 {
1589     JoystickImpl *This = (JoystickImpl *)iface;
1590
1591     TRACE("(%p,%p)\n", iface, pdidi);
1592
1593     if ((pdidi->dwSize != sizeof(DIDEVICEINSTANCE_DX3W)) &&
1594         (pdidi->dwSize != sizeof(DIDEVICEINSTANCEW))) {
1595         WARN("invalid parameter: pdidi->dwSize = %ld != %d or %d\n",
1596              pdidi->dwSize, sizeof(DIDEVICEINSTANCE_DX3W),
1597              sizeof(DIDEVICEINSTANCEW));
1598         return DIERR_INVALIDPARAM;
1599     }
1600
1601     /* Return joystick */
1602     pdidi->guidInstance = GUID_Joystick;
1603     pdidi->guidProduct = DInput_Wine_Joystick_GUID;
1604     /* we only support traditional joysticks for now */
1605     pdidi->dwDevType = This->devcaps.dwDevType;
1606     MultiByteToWideChar(CP_ACP, 0, "Joystick", -1, pdidi->tszInstanceName, MAX_PATH);
1607     MultiByteToWideChar(CP_ACP, 0, This->name, -1, pdidi->tszProductName, MAX_PATH);
1608     if (pdidi->dwSize > sizeof(DIDEVICEINSTANCE_DX3W)) {
1609         pdidi->guidFFDriver = GUID_NULL;
1610         pdidi->wUsagePage = 0;
1611         pdidi->wUsage = 0;
1612     }
1613
1614     return DI_OK;
1615 }
1616
1617 static IDirectInputDevice8AVtbl JoystickAvt =
1618 {
1619         IDirectInputDevice2AImpl_QueryInterface,
1620         IDirectInputDevice2AImpl_AddRef,
1621         JoystickAImpl_Release,
1622         JoystickAImpl_GetCapabilities,
1623         JoystickAImpl_EnumObjects,
1624         JoystickAImpl_GetProperty,
1625         JoystickAImpl_SetProperty,
1626         JoystickAImpl_Acquire,
1627         JoystickAImpl_Unacquire,
1628         JoystickAImpl_GetDeviceState,
1629         JoystickAImpl_GetDeviceData,
1630         JoystickAImpl_SetDataFormat,
1631         JoystickAImpl_SetEventNotification,
1632         IDirectInputDevice2AImpl_SetCooperativeLevel,
1633         JoystickAImpl_GetObjectInfo,
1634         JoystickAImpl_GetDeviceInfo,
1635         IDirectInputDevice2AImpl_RunControlPanel,
1636         IDirectInputDevice2AImpl_Initialize,
1637         IDirectInputDevice2AImpl_CreateEffect,
1638         IDirectInputDevice2AImpl_EnumEffects,
1639         IDirectInputDevice2AImpl_GetEffectInfo,
1640         IDirectInputDevice2AImpl_GetForceFeedbackState,
1641         IDirectInputDevice2AImpl_SendForceFeedbackCommand,
1642         IDirectInputDevice2AImpl_EnumCreatedEffectObjects,
1643         IDirectInputDevice2AImpl_Escape,
1644         JoystickAImpl_Poll,
1645         IDirectInputDevice2AImpl_SendDeviceData,
1646         IDirectInputDevice7AImpl_EnumEffectsInFile,
1647         IDirectInputDevice7AImpl_WriteEffectToFile,
1648         IDirectInputDevice8AImpl_BuildActionMap,
1649         IDirectInputDevice8AImpl_SetActionMap,
1650         IDirectInputDevice8AImpl_GetImageInfo
1651 };
1652
1653 #if !defined(__STRICT_ANSI__) && defined(__GNUC__)
1654 # define XCAST(fun)     (typeof(SysJoystickWvt.fun))
1655 #else
1656 # define XCAST(fun)     (void*)
1657 #endif
1658
1659 static IDirectInputDevice8WVtbl SysJoystickWvt =
1660 {
1661         IDirectInputDevice2WImpl_QueryInterface,
1662         XCAST(AddRef)IDirectInputDevice2AImpl_AddRef,
1663         XCAST(Release)JoystickAImpl_Release,
1664         XCAST(GetCapabilities)JoystickAImpl_GetCapabilities,
1665         JoystickWImpl_EnumObjects,
1666         XCAST(GetProperty)JoystickAImpl_GetProperty,
1667         XCAST(SetProperty)JoystickAImpl_SetProperty,
1668         XCAST(Acquire)JoystickAImpl_Acquire,
1669         XCAST(Unacquire)JoystickAImpl_Unacquire,
1670         XCAST(GetDeviceState)JoystickAImpl_GetDeviceState,
1671         XCAST(GetDeviceData)JoystickAImpl_GetDeviceData,
1672         XCAST(SetDataFormat)JoystickAImpl_SetDataFormat,
1673         XCAST(SetEventNotification)JoystickAImpl_SetEventNotification,
1674         XCAST(SetCooperativeLevel)IDirectInputDevice2AImpl_SetCooperativeLevel,
1675         IDirectInputDevice2WImpl_GetObjectInfo,
1676         JoystickWImpl_GetDeviceInfo,
1677         XCAST(RunControlPanel)IDirectInputDevice2AImpl_RunControlPanel,
1678         XCAST(Initialize)IDirectInputDevice2AImpl_Initialize,
1679         XCAST(CreateEffect)IDirectInputDevice2AImpl_CreateEffect,
1680         IDirectInputDevice2WImpl_EnumEffects,
1681         IDirectInputDevice2WImpl_GetEffectInfo,
1682         XCAST(GetForceFeedbackState)IDirectInputDevice2AImpl_GetForceFeedbackState,
1683         XCAST(SendForceFeedbackCommand)IDirectInputDevice2AImpl_SendForceFeedbackCommand,
1684         XCAST(EnumCreatedEffectObjects)IDirectInputDevice2AImpl_EnumCreatedEffectObjects,
1685         XCAST(Escape)IDirectInputDevice2AImpl_Escape,
1686         XCAST(Poll)JoystickAImpl_Poll,
1687         XCAST(SendDeviceData)IDirectInputDevice2AImpl_SendDeviceData,
1688         IDirectInputDevice7WImpl_EnumEffectsInFile,
1689         IDirectInputDevice7WImpl_WriteEffectToFile,
1690         IDirectInputDevice8WImpl_BuildActionMap,
1691         IDirectInputDevice8WImpl_SetActionMap,
1692         IDirectInputDevice8WImpl_GetImageInfo
1693 };
1694 #undef XCAST
1695
1696 #else  /* HAVE_LINUX_22_JOYSTICK_API */
1697
1698 const struct dinput_device joystick_linux_device = {
1699   "Wine Linux joystick driver",
1700   NULL,
1701   NULL,
1702   NULL,
1703   NULL
1704 };
1705
1706 #endif  /* HAVE_LINUX_22_JOYSTICK_API */