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