code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ extern int MacHaptic_MaybeAddDevice( io_object_t device ); extern int MacHaptic_MaybeRemoveDevice( io_object_t device ); /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/haptic/darwin/SDL_syshaptic_c.h
C
apache-2.0
1,098
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if defined(SDL_HAPTIC_DUMMY) || defined(SDL_HAPTIC_DISABLED) #include "SDL_haptic.h" #include "../SDL_syshaptic.h" static int SDL_SYS_LogicError(void) { return SDL_SetError("Logic error: No haptic devices available."); } int SDL_SYS_HapticInit(void) { return 0; } int SDL_SYS_NumHaptics(void) { return 0; } const char * SDL_SYS_HapticName(int index) { SDL_SYS_LogicError(); return NULL; } int SDL_SYS_HapticOpen(SDL_Haptic * haptic) { return SDL_SYS_LogicError(); } int SDL_SYS_HapticMouse(void) { return -1; } int SDL_SYS_JoystickIsHaptic(SDL_Joystick * joystick) { return 0; } int SDL_SYS_HapticOpenFromJoystick(SDL_Haptic * haptic, SDL_Joystick * joystick) { return SDL_SYS_LogicError(); } int SDL_SYS_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick) { return 0; } void SDL_SYS_HapticClose(SDL_Haptic * haptic) { return; } void SDL_SYS_HapticQuit(void) { return; } int SDL_SYS_HapticNewEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * base) { return SDL_SYS_LogicError(); } int SDL_SYS_HapticUpdateEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * data) { return SDL_SYS_LogicError(); } int SDL_SYS_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect *effect, Uint32 iterations) { return SDL_SYS_LogicError(); } int SDL_SYS_HapticStopEffect(SDL_Haptic * haptic, struct haptic_effect *effect) { return SDL_SYS_LogicError(); } void SDL_SYS_HapticDestroyEffect(SDL_Haptic * haptic, struct haptic_effect *effect) { SDL_SYS_LogicError(); return; } int SDL_SYS_HapticGetEffectStatus(SDL_Haptic * haptic, struct haptic_effect *effect) { return SDL_SYS_LogicError(); } int SDL_SYS_HapticSetGain(SDL_Haptic * haptic, int gain) { return SDL_SYS_LogicError(); } int SDL_SYS_HapticSetAutocenter(SDL_Haptic * haptic, int autocenter) { return SDL_SYS_LogicError(); } int SDL_SYS_HapticPause(SDL_Haptic * haptic) { return SDL_SYS_LogicError(); } int SDL_SYS_HapticUnpause(SDL_Haptic * haptic) { return SDL_SYS_LogicError(); } int SDL_SYS_HapticStopAll(SDL_Haptic * haptic) { return SDL_SYS_LogicError(); } #endif /* SDL_HAPTIC_DUMMY || SDL_HAPTIC_DISABLED */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/haptic/dummy/SDL_syshaptic.c
C
apache-2.0
3,402
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_HAPTIC_LINUX #include "SDL_assert.h" #include "SDL_haptic.h" #include "../SDL_syshaptic.h" #include "SDL_joystick.h" #include "../../joystick/SDL_sysjoystick.h" /* For the real SDL_Joystick */ #include "../../joystick/linux/SDL_sysjoystick_c.h" /* For joystick hwdata */ #include "../../core/linux/SDL_udev.h" #include <unistd.h> /* close */ #include <linux/input.h> /* Force feedback linux stuff. */ #include <fcntl.h> /* O_RDWR */ #include <limits.h> /* INT_MAX */ #include <errno.h> /* errno, strerror */ #include <math.h> /* atan2 */ #include <sys/stat.h> /* stat */ /* Just in case. */ #ifndef M_PI # define M_PI 3.14159265358979323846 #endif #define MAX_HAPTICS 32 /* It's doubtful someone has more then 32 evdev */ static int MaybeAddDevice(const char *path); #if SDL_USE_LIBUDEV static int MaybeRemoveDevice(const char *path); static void haptic_udev_callback(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath); #endif /* SDL_USE_LIBUDEV */ /* * List of available haptic devices. */ typedef struct SDL_hapticlist_item { char *fname; /* Dev path name (like /dev/input/event1) */ SDL_Haptic *haptic; /* Associated haptic. */ dev_t dev_num; struct SDL_hapticlist_item *next; } SDL_hapticlist_item; /* * Haptic system hardware data. */ struct haptic_hwdata { int fd; /* File descriptor of the device. */ char *fname; /* Points to the name in SDL_hapticlist. */ }; /* * Haptic system effect data. */ struct haptic_hweffect { struct ff_effect effect; /* The linux kernel effect structure. */ }; static SDL_hapticlist_item *SDL_hapticlist = NULL; static SDL_hapticlist_item *SDL_hapticlist_tail = NULL; static int numhaptics = 0; #define test_bit(nr, addr) \ (((1UL << ((nr) & 31)) & (((const unsigned int *) addr)[(nr) >> 5])) != 0) #define EV_TEST(ev,f) \ if (test_bit((ev), features)) ret |= (f); /* * Test whether a device has haptic properties. * Returns available properties or 0 if there are none. */ static int EV_IsHaptic(int fd) { unsigned int ret; unsigned long features[1 + FF_MAX / sizeof(unsigned long)]; /* Ask device for what it has. */ ret = 0; if (ioctl(fd, EVIOCGBIT(EV_FF, sizeof(features)), features) < 0) { return SDL_SetError("Haptic: Unable to get device's features: %s", strerror(errno)); } /* Convert supported features to SDL_HAPTIC platform-neutral features. */ EV_TEST(FF_CONSTANT, SDL_HAPTIC_CONSTANT); EV_TEST(FF_SINE, SDL_HAPTIC_SINE); /* !!! FIXME: put this back when we have more bits in 2.1 */ /* EV_TEST(FF_SQUARE, SDL_HAPTIC_SQUARE); */ EV_TEST(FF_TRIANGLE, SDL_HAPTIC_TRIANGLE); EV_TEST(FF_SAW_UP, SDL_HAPTIC_SAWTOOTHUP); EV_TEST(FF_SAW_DOWN, SDL_HAPTIC_SAWTOOTHDOWN); EV_TEST(FF_RAMP, SDL_HAPTIC_RAMP); EV_TEST(FF_SPRING, SDL_HAPTIC_SPRING); EV_TEST(FF_FRICTION, SDL_HAPTIC_FRICTION); EV_TEST(FF_DAMPER, SDL_HAPTIC_DAMPER); EV_TEST(FF_INERTIA, SDL_HAPTIC_INERTIA); EV_TEST(FF_CUSTOM, SDL_HAPTIC_CUSTOM); EV_TEST(FF_GAIN, SDL_HAPTIC_GAIN); EV_TEST(FF_AUTOCENTER, SDL_HAPTIC_AUTOCENTER); EV_TEST(FF_RUMBLE, SDL_HAPTIC_LEFTRIGHT); /* Return what it supports. */ return ret; } /* * Tests whether a device is a mouse or not. */ static int EV_IsMouse(int fd) { unsigned long argp[40]; /* Ask for supported features. */ if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(argp)), argp) < 0) { return -1; } /* Currently we only test for BTN_MOUSE which can give fake positives. */ if (test_bit(BTN_MOUSE, argp) != 0) { return 1; } return 0; } /* * Initializes the haptic subsystem by finding available devices. */ int SDL_SYS_HapticInit(void) { const char joydev_pattern[] = "/dev/input/event%d"; char path[PATH_MAX]; int i, j; /* * Limit amount of checks to MAX_HAPTICS since we may or may not have * permission to some or all devices. */ i = 0; for (j = 0; j < MAX_HAPTICS; ++j) { snprintf(path, PATH_MAX, joydev_pattern, i++); MaybeAddDevice(path); } #if SDL_USE_LIBUDEV if (SDL_UDEV_Init() < 0) { return SDL_SetError("Could not initialize UDEV"); } if ( SDL_UDEV_AddCallback(haptic_udev_callback) < 0) { SDL_UDEV_Quit(); return SDL_SetError("Could not setup haptic <-> udev callback"); } /* Force a scan to build the initial device list */ SDL_UDEV_Scan(); #endif /* SDL_USE_LIBUDEV */ return numhaptics; } int SDL_SYS_NumHaptics(void) { return numhaptics; } static SDL_hapticlist_item * HapticByDevIndex(int device_index) { SDL_hapticlist_item *item = SDL_hapticlist; if ((device_index < 0) || (device_index >= numhaptics)) { return NULL; } while (device_index > 0) { SDL_assert(item != NULL); --device_index; item = item->next; } return item; } #if SDL_USE_LIBUDEV static void haptic_udev_callback(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath) { if (devpath == NULL || !(udev_class & SDL_UDEV_DEVICE_JOYSTICK)) { return; } switch( udev_type ) { case SDL_UDEV_DEVICEADDED: MaybeAddDevice(devpath); break; case SDL_UDEV_DEVICEREMOVED: MaybeRemoveDevice(devpath); break; default: break; } } #endif /* SDL_USE_LIBUDEV */ static int MaybeAddDevice(const char *path) { struct stat sb; int fd; int success; SDL_hapticlist_item *item; if (path == NULL) { return -1; } /* check to see if file exists */ if (stat(path, &sb) != 0) { return -1; } /* check for duplicates */ for (item = SDL_hapticlist; item != NULL; item = item->next) { if (item->dev_num == sb.st_rdev) { return -1; /* duplicate. */ } } /* try to open */ fd = open(path, O_RDWR, 0); if (fd < 0) { return -1; } #ifdef DEBUG_INPUT_EVENTS printf("Checking %s\n", path); #endif /* see if it works */ success = EV_IsHaptic(fd); close(fd); if (success <= 0) { return -1; } item = (SDL_hapticlist_item *) SDL_calloc(1, sizeof (SDL_hapticlist_item)); if (item == NULL) { return -1; } item->fname = SDL_strdup(path); if (item->fname == NULL) { SDL_free(item); return -1; } item->dev_num = sb.st_rdev; /* TODO: should we add instance IDs? */ if (SDL_hapticlist_tail == NULL) { SDL_hapticlist = SDL_hapticlist_tail = item; } else { SDL_hapticlist_tail->next = item; SDL_hapticlist_tail = item; } ++numhaptics; /* !!! TODO: Send a haptic add event? */ return numhaptics; } #if SDL_USE_LIBUDEV static int MaybeRemoveDevice(const char* path) { SDL_hapticlist_item *item; SDL_hapticlist_item *prev = NULL; if (path == NULL) { return -1; } for (item = SDL_hapticlist; item != NULL; item = item->next) { /* found it, remove it. */ if (SDL_strcmp(path, item->fname) == 0) { const int retval = item->haptic ? item->haptic->index : -1; if (prev != NULL) { prev->next = item->next; } else { SDL_assert(SDL_hapticlist == item); SDL_hapticlist = item->next; } if (item == SDL_hapticlist_tail) { SDL_hapticlist_tail = prev; } /* Need to decrement the haptic count */ --numhaptics; /* !!! TODO: Send a haptic remove event? */ SDL_free(item->fname); SDL_free(item); return retval; } prev = item; } return -1; } #endif /* SDL_USE_LIBUDEV */ /* * Gets the name from a file descriptor. */ static const char * SDL_SYS_HapticNameFromFD(int fd) { static char namebuf[128]; /* We use the evdev name ioctl. */ if (ioctl(fd, EVIOCGNAME(sizeof(namebuf)), namebuf) <= 0) { return NULL; } return namebuf; } /* * Return the name of a haptic device, does not need to be opened. */ const char * SDL_SYS_HapticName(int index) { SDL_hapticlist_item *item; int fd; const char *name; item = HapticByDevIndex(index); /* Open the haptic device. */ name = NULL; fd = open(item->fname, O_RDONLY, 0); if (fd >= 0) { name = SDL_SYS_HapticNameFromFD(fd); if (name == NULL) { /* No name found, return device character device */ name = item->fname; } close(fd); } return name; } /* * Opens the haptic device from the file descriptor. */ static int SDL_SYS_HapticOpenFromFD(SDL_Haptic * haptic, int fd) { /* Allocate the hwdata */ haptic->hwdata = (struct haptic_hwdata *) SDL_malloc(sizeof(*haptic->hwdata)); if (haptic->hwdata == NULL) { SDL_OutOfMemory(); goto open_err; } SDL_memset(haptic->hwdata, 0, sizeof(*haptic->hwdata)); /* Set the data. */ haptic->hwdata->fd = fd; haptic->supported = EV_IsHaptic(fd); haptic->naxes = 2; /* Hardcoded for now, not sure if it's possible to find out. */ /* Set the effects */ if (ioctl(fd, EVIOCGEFFECTS, &haptic->neffects) < 0) { SDL_SetError("Haptic: Unable to query device memory: %s", strerror(errno)); goto open_err; } haptic->nplaying = haptic->neffects; /* Linux makes no distinction. */ haptic->effects = (struct haptic_effect *) SDL_malloc(sizeof(struct haptic_effect) * haptic->neffects); if (haptic->effects == NULL) { SDL_OutOfMemory(); goto open_err; } /* Clear the memory */ SDL_memset(haptic->effects, 0, sizeof(struct haptic_effect) * haptic->neffects); return 0; /* Error handling */ open_err: close(fd); if (haptic->hwdata != NULL) { SDL_free(haptic->hwdata); haptic->hwdata = NULL; } return -1; } /* * Opens a haptic device for usage. */ int SDL_SYS_HapticOpen(SDL_Haptic * haptic) { int fd; int ret; SDL_hapticlist_item *item; item = HapticByDevIndex(haptic->index); /* Open the character device */ fd = open(item->fname, O_RDWR, 0); if (fd < 0) { return SDL_SetError("Haptic: Unable to open %s: %s", item->fname, strerror(errno)); } /* Try to create the haptic. */ ret = SDL_SYS_HapticOpenFromFD(haptic, fd); /* Already closes on error. */ if (ret < 0) { return -1; } /* Set the fname. */ haptic->hwdata->fname = SDL_strdup( item->fname ); return 0; } /* * Opens a haptic device from first mouse it finds for usage. */ int SDL_SYS_HapticMouse(void) { int fd; int device_index = 0; SDL_hapticlist_item *item; for (item = SDL_hapticlist; item; item = item->next) { /* Open the device. */ fd = open(item->fname, O_RDWR, 0); if (fd < 0) { return SDL_SetError("Haptic: Unable to open %s: %s", item->fname, strerror(errno)); } /* Is it a mouse? */ if (EV_IsMouse(fd)) { close(fd); return device_index; } close(fd); ++device_index; } return -1; } /* * Checks to see if a joystick has haptic features. */ int SDL_SYS_JoystickIsHaptic(SDL_Joystick * joystick) { #ifdef SDL_JOYSTICK_LINUX if (joystick->driver != &SDL_LINUX_JoystickDriver) { return SDL_FALSE; } if (EV_IsHaptic(joystick->hwdata->fd)) { return SDL_TRUE; } #endif return SDL_FALSE; } /* * Checks to see if the haptic device and joystick are in reality the same. */ int SDL_SYS_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick) { #ifdef SDL_JOYSTICK_LINUX if (joystick->driver != &SDL_LINUX_JoystickDriver) { return 0; } /* We are assuming Linux is using evdev which should trump the old * joystick methods. */ if (SDL_strcmp(joystick->hwdata->fname, haptic->hwdata->fname) == 0) { return 1; } #endif return 0; } /* * Opens a SDL_Haptic from a SDL_Joystick. */ int SDL_SYS_HapticOpenFromJoystick(SDL_Haptic * haptic, SDL_Joystick * joystick) { #ifdef SDL_JOYSTICK_LINUX int device_index = 0; int fd; int ret; SDL_hapticlist_item *item; if (joystick->driver != &SDL_LINUX_JoystickDriver) { return -1; } /* Find the joystick in the haptic list. */ for (item = SDL_hapticlist; item; item = item->next) { if (SDL_strcmp(item->fname, joystick->hwdata->fname) == 0) { break; } ++device_index; } haptic->index = device_index; if (device_index >= MAX_HAPTICS) { return SDL_SetError("Haptic: Joystick doesn't have Haptic capabilities"); } fd = open(joystick->hwdata->fname, O_RDWR, 0); if (fd < 0) { return SDL_SetError("Haptic: Unable to open %s: %s", joystick->hwdata->fname, strerror(errno)); } ret = SDL_SYS_HapticOpenFromFD(haptic, fd); /* Already closes on error. */ if (ret < 0) { return -1; } haptic->hwdata->fname = SDL_strdup( joystick->hwdata->fname ); return 0; #else return -1; #endif } /* * Closes the haptic device. */ void SDL_SYS_HapticClose(SDL_Haptic * haptic) { if (haptic->hwdata) { /* Free effects. */ SDL_free(haptic->effects); haptic->effects = NULL; haptic->neffects = 0; /* Clean up */ close(haptic->hwdata->fd); /* Free */ SDL_free(haptic->hwdata->fname); SDL_free(haptic->hwdata); haptic->hwdata = NULL; } /* Clear the rest. */ SDL_memset(haptic, 0, sizeof(SDL_Haptic)); } /* * Clean up after system specific haptic stuff */ void SDL_SYS_HapticQuit(void) { SDL_hapticlist_item *item = NULL; SDL_hapticlist_item *next = NULL; for (item = SDL_hapticlist; item; item = next) { next = item->next; /* Opened and not closed haptics are leaked, this is on purpose. * Close your haptic devices after usage. */ SDL_free(item->fname); SDL_free(item); } #if SDL_USE_LIBUDEV SDL_UDEV_DelCallback(haptic_udev_callback); SDL_UDEV_Quit(); #endif /* SDL_USE_LIBUDEV */ numhaptics = 0; SDL_hapticlist = NULL; SDL_hapticlist_tail = NULL; } /* * Converts an SDL button to a ff_trigger button. */ static Uint16 SDL_SYS_ToButton(Uint16 button) { Uint16 ff_button; ff_button = 0; /* * Not sure what the proper syntax is because this actually isn't implemented * in the current kernel from what I've seen (2.6.26). */ if (button != 0) { ff_button = BTN_GAMEPAD + button - 1; } return ff_button; } /* * Initializes the ff_effect usable direction from a SDL_HapticDirection. */ static int SDL_SYS_ToDirection(Uint16 *dest, SDL_HapticDirection * src) { Uint32 tmp; switch (src->type) { case SDL_HAPTIC_POLAR: /* Linux directions start from south. (and range from 0 to 0xFFFF) Quoting include/linux/input.h, line 926: Direction of the effect is encoded as follows: 0 deg -> 0x0000 (down) 90 deg -> 0x4000 (left) 180 deg -> 0x8000 (up) 270 deg -> 0xC000 (right) The force pulls into the direction specified by Linux directions, i.e. the opposite convention of SDL directions. */ tmp = ((src->dir[0] % 36000) * 0x8000) / 18000; /* convert to range [0,0xFFFF] */ *dest = (Uint16) tmp; break; case SDL_HAPTIC_SPHERICAL: /* We convert to polar, because that's the only supported direction on Linux. The first value of a spherical direction is practically the same as a Polar direction, except that we have to add 90 degrees. It is the angle from EAST {1,0} towards SOUTH {0,1}. --> add 9000 --> finally convert to [0,0xFFFF] as in case SDL_HAPTIC_POLAR. */ tmp = ((src->dir[0]) + 9000) % 36000; /* Convert to polars */ tmp = (tmp * 0x8000) / 18000; /* convert to range [0,0xFFFF] */ *dest = (Uint16) tmp; break; case SDL_HAPTIC_CARTESIAN: if (!src->dir[1]) *dest = (src->dir[0] >= 0 ? 0x4000 : 0xC000); else if (!src->dir[0]) *dest = (src->dir[1] >= 0 ? 0x8000 : 0); else { float f = SDL_atan2(src->dir[1], src->dir[0]); /* Ideally we'd use fixed point math instead of floats... */ /* atan2 takes the parameters: Y-axis-value and X-axis-value (in that order) - Y-axis-value is the second coordinate (from center to SOUTH) - X-axis-value is the first coordinate (from center to EAST) We add 36000, because atan2 also returns negative values. Then we practically have the first spherical value. Therefore we proceed as in case SDL_HAPTIC_SPHERICAL and add another 9000 to get the polar value. --> add 45000 in total --> finally convert to [0,0xFFFF] as in case SDL_HAPTIC_POLAR. */ tmp = (((Sint32) (f * 18000. / M_PI)) + 45000) % 36000; tmp = (tmp * 0x8000) / 18000; /* convert to range [0,0xFFFF] */ *dest = (Uint16) tmp; } break; case SDL_HAPTIC_STEERING_AXIS: *dest = 0x4000; break; default: return SDL_SetError("Haptic: Unsupported direction type."); } return 0; } #define CLAMP(x) (((x) > 32767) ? 32767 : x) /* * Initializes the Linux effect struct from a haptic_effect. * Values above 32767 (for unsigned) are unspecified so we must clamp. */ static int SDL_SYS_ToFFEffect(struct ff_effect *dest, SDL_HapticEffect * src) { SDL_HapticConstant *constant; SDL_HapticPeriodic *periodic; SDL_HapticCondition *condition; SDL_HapticRamp *ramp; SDL_HapticLeftRight *leftright; /* Clear up */ SDL_memset(dest, 0, sizeof(struct ff_effect)); switch (src->type) { case SDL_HAPTIC_CONSTANT: constant = &src->constant; /* Header */ dest->type = FF_CONSTANT; if (SDL_SYS_ToDirection(&dest->direction, &constant->direction) == -1) return -1; /* Replay */ dest->replay.length = (constant->length == SDL_HAPTIC_INFINITY) ? 0 : CLAMP(constant->length); dest->replay.delay = CLAMP(constant->delay); /* Trigger */ dest->trigger.button = SDL_SYS_ToButton(constant->button); dest->trigger.interval = CLAMP(constant->interval); /* Constant */ dest->u.constant.level = constant->level; /* Envelope */ dest->u.constant.envelope.attack_length = CLAMP(constant->attack_length); dest->u.constant.envelope.attack_level = CLAMP(constant->attack_level); dest->u.constant.envelope.fade_length = CLAMP(constant->fade_length); dest->u.constant.envelope.fade_level = CLAMP(constant->fade_level); break; case SDL_HAPTIC_SINE: /* !!! FIXME: put this back when we have more bits in 2.1 */ /* case SDL_HAPTIC_SQUARE: */ case SDL_HAPTIC_TRIANGLE: case SDL_HAPTIC_SAWTOOTHUP: case SDL_HAPTIC_SAWTOOTHDOWN: periodic = &src->periodic; /* Header */ dest->type = FF_PERIODIC; if (SDL_SYS_ToDirection(&dest->direction, &periodic->direction) == -1) return -1; /* Replay */ dest->replay.length = (periodic->length == SDL_HAPTIC_INFINITY) ? 0 : CLAMP(periodic->length); dest->replay.delay = CLAMP(periodic->delay); /* Trigger */ dest->trigger.button = SDL_SYS_ToButton(periodic->button); dest->trigger.interval = CLAMP(periodic->interval); /* Periodic */ if (periodic->type == SDL_HAPTIC_SINE) dest->u.periodic.waveform = FF_SINE; /* !!! FIXME: put this back when we have more bits in 2.1 */ /* else if (periodic->type == SDL_HAPTIC_SQUARE) dest->u.periodic.waveform = FF_SQUARE; */ else if (periodic->type == SDL_HAPTIC_TRIANGLE) dest->u.periodic.waveform = FF_TRIANGLE; else if (periodic->type == SDL_HAPTIC_SAWTOOTHUP) dest->u.periodic.waveform = FF_SAW_UP; else if (periodic->type == SDL_HAPTIC_SAWTOOTHDOWN) dest->u.periodic.waveform = FF_SAW_DOWN; dest->u.periodic.period = CLAMP(periodic->period); dest->u.periodic.magnitude = periodic->magnitude; dest->u.periodic.offset = periodic->offset; /* Linux phase is defined in interval "[0x0000, 0x10000[", corresponds with "[0deg, 360deg[" phase shift. */ dest->u.periodic.phase = ((Uint32)periodic->phase * 0x10000U) / 36000; /* Envelope */ dest->u.periodic.envelope.attack_length = CLAMP(periodic->attack_length); dest->u.periodic.envelope.attack_level = CLAMP(periodic->attack_level); dest->u.periodic.envelope.fade_length = CLAMP(periodic->fade_length); dest->u.periodic.envelope.fade_level = CLAMP(periodic->fade_level); break; case SDL_HAPTIC_SPRING: case SDL_HAPTIC_DAMPER: case SDL_HAPTIC_INERTIA: case SDL_HAPTIC_FRICTION: condition = &src->condition; /* Header */ if (condition->type == SDL_HAPTIC_SPRING) dest->type = FF_SPRING; else if (condition->type == SDL_HAPTIC_DAMPER) dest->type = FF_DAMPER; else if (condition->type == SDL_HAPTIC_INERTIA) dest->type = FF_INERTIA; else if (condition->type == SDL_HAPTIC_FRICTION) dest->type = FF_FRICTION; dest->direction = 0; /* Handled by the condition-specifics. */ /* Replay */ dest->replay.length = (condition->length == SDL_HAPTIC_INFINITY) ? 0 : CLAMP(condition->length); dest->replay.delay = CLAMP(condition->delay); /* Trigger */ dest->trigger.button = SDL_SYS_ToButton(condition->button); dest->trigger.interval = CLAMP(condition->interval); /* Condition */ /* X axis */ dest->u.condition[0].right_saturation = condition->right_sat[0]; dest->u.condition[0].left_saturation = condition->left_sat[0]; dest->u.condition[0].right_coeff = condition->right_coeff[0]; dest->u.condition[0].left_coeff = condition->left_coeff[0]; dest->u.condition[0].deadband = condition->deadband[0]; dest->u.condition[0].center = condition->center[0]; /* Y axis */ dest->u.condition[1].right_saturation = condition->right_sat[1]; dest->u.condition[1].left_saturation = condition->left_sat[1]; dest->u.condition[1].right_coeff = condition->right_coeff[1]; dest->u.condition[1].left_coeff = condition->left_coeff[1]; dest->u.condition[1].deadband = condition->deadband[1]; dest->u.condition[1].center = condition->center[1]; /* * There is no envelope in the linux force feedback api for conditions. */ break; case SDL_HAPTIC_RAMP: ramp = &src->ramp; /* Header */ dest->type = FF_RAMP; if (SDL_SYS_ToDirection(&dest->direction, &ramp->direction) == -1) return -1; /* Replay */ dest->replay.length = (ramp->length == SDL_HAPTIC_INFINITY) ? 0 : CLAMP(ramp->length); dest->replay.delay = CLAMP(ramp->delay); /* Trigger */ dest->trigger.button = SDL_SYS_ToButton(ramp->button); dest->trigger.interval = CLAMP(ramp->interval); /* Ramp */ dest->u.ramp.start_level = ramp->start; dest->u.ramp.end_level = ramp->end; /* Envelope */ dest->u.ramp.envelope.attack_length = CLAMP(ramp->attack_length); dest->u.ramp.envelope.attack_level = CLAMP(ramp->attack_level); dest->u.ramp.envelope.fade_length = CLAMP(ramp->fade_length); dest->u.ramp.envelope.fade_level = CLAMP(ramp->fade_level); break; case SDL_HAPTIC_LEFTRIGHT: leftright = &src->leftright; /* Header */ dest->type = FF_RUMBLE; dest->direction = 0; /* Replay */ dest->replay.length = (leftright->length == SDL_HAPTIC_INFINITY) ? 0 : CLAMP(leftright->length); /* Trigger */ dest->trigger.button = 0; dest->trigger.interval = 0; /* Rumble (Linux expects 0-65535, so multiply by 2) */ dest->u.rumble.strong_magnitude = CLAMP(leftright->large_magnitude) * 2; dest->u.rumble.weak_magnitude = CLAMP(leftright->small_magnitude) * 2; break; default: return SDL_SetError("Haptic: Unknown effect type."); } return 0; } /* * Creates a new haptic effect. */ int SDL_SYS_HapticNewEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * base) { struct ff_effect *linux_effect; /* Allocate the hardware effect */ effect->hweffect = (struct haptic_hweffect *) SDL_malloc(sizeof(struct haptic_hweffect)); if (effect->hweffect == NULL) { return SDL_OutOfMemory(); } /* Prepare the ff_effect */ linux_effect = &effect->hweffect->effect; if (SDL_SYS_ToFFEffect(linux_effect, base) != 0) { goto new_effect_err; } linux_effect->id = -1; /* Have the kernel give it an id */ /* Upload the effect */ if (ioctl(haptic->hwdata->fd, EVIOCSFF, linux_effect) < 0) { SDL_SetError("Haptic: Error uploading effect to the device: %s", strerror(errno)); goto new_effect_err; } return 0; new_effect_err: SDL_free(effect->hweffect); effect->hweffect = NULL; return -1; } /* * Updates an effect. * * Note: Dynamically updating the direction can in some cases force * the effect to restart and run once. */ int SDL_SYS_HapticUpdateEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * data) { struct ff_effect linux_effect; /* Create the new effect */ if (SDL_SYS_ToFFEffect(&linux_effect, data) != 0) { return -1; } linux_effect.id = effect->hweffect->effect.id; /* See if it can be uploaded. */ if (ioctl(haptic->hwdata->fd, EVIOCSFF, &linux_effect) < 0) { return SDL_SetError("Haptic: Error updating the effect: %s", strerror(errno)); } /* Copy the new effect into memory. */ SDL_memcpy(&effect->hweffect->effect, &linux_effect, sizeof(struct ff_effect)); return effect->hweffect->effect.id; } /* * Runs an effect. */ int SDL_SYS_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect *effect, Uint32 iterations) { struct input_event run; /* Prepare to run the effect */ run.type = EV_FF; run.code = effect->hweffect->effect.id; /* We don't actually have infinity here, so we just do INT_MAX which is pretty damn close. */ run.value = (iterations > INT_MAX) ? INT_MAX : iterations; if (write(haptic->hwdata->fd, (const void *) &run, sizeof(run)) < 0) { return SDL_SetError("Haptic: Unable to run the effect: %s", strerror(errno)); } return 0; } /* * Stops an effect. */ int SDL_SYS_HapticStopEffect(SDL_Haptic * haptic, struct haptic_effect *effect) { struct input_event stop; stop.type = EV_FF; stop.code = effect->hweffect->effect.id; stop.value = 0; if (write(haptic->hwdata->fd, (const void *) &stop, sizeof(stop)) < 0) { return SDL_SetError("Haptic: Unable to stop the effect: %s", strerror(errno)); } return 0; } /* * Frees the effect. */ void SDL_SYS_HapticDestroyEffect(SDL_Haptic * haptic, struct haptic_effect *effect) { if (ioctl(haptic->hwdata->fd, EVIOCRMFF, effect->hweffect->effect.id) < 0) { SDL_SetError("Haptic: Error removing the effect from the device: %s", strerror(errno)); } SDL_free(effect->hweffect); effect->hweffect = NULL; } /* * Gets the status of a haptic effect. */ int SDL_SYS_HapticGetEffectStatus(SDL_Haptic * haptic, struct haptic_effect *effect) { #if 0 /* Not supported atm. */ struct input_event ie; ie.type = EV_FF; ie.type = EV_FF_STATUS; ie.code = effect->hweffect->effect.id; if (write(haptic->hwdata->fd, &ie, sizeof(ie)) < 0) { return SDL_SetError("Haptic: Error getting device status."); } return 0; #endif return -1; } /* * Sets the gain. */ int SDL_SYS_HapticSetGain(SDL_Haptic * haptic, int gain) { struct input_event ie; ie.type = EV_FF; ie.code = FF_GAIN; ie.value = (0xFFFFUL * gain) / 100; if (write(haptic->hwdata->fd, &ie, sizeof(ie)) < 0) { return SDL_SetError("Haptic: Error setting gain: %s", strerror(errno)); } return 0; } /* * Sets the autocentering. */ int SDL_SYS_HapticSetAutocenter(SDL_Haptic * haptic, int autocenter) { struct input_event ie; ie.type = EV_FF; ie.code = FF_AUTOCENTER; ie.value = (0xFFFFUL * autocenter) / 100; if (write(haptic->hwdata->fd, &ie, sizeof(ie)) < 0) { return SDL_SetError("Haptic: Error setting autocenter: %s", strerror(errno)); } return 0; } /* * Pausing is not supported atm by linux. */ int SDL_SYS_HapticPause(SDL_Haptic * haptic) { return -1; } /* * Unpausing is not supported atm by linux. */ int SDL_SYS_HapticUnpause(SDL_Haptic * haptic) { return -1; } /* * Stops all the currently playing effects. */ int SDL_SYS_HapticStopAll(SDL_Haptic * haptic) { int i, ret; /* Linux does not support this natively so we have to loop. */ for (i = 0; i < haptic->neffects; i++) { if (haptic->effects[i].hweffect != NULL) { ret = SDL_SYS_HapticStopEffect(haptic, &haptic->effects[i]); if (ret < 0) { return SDL_SetError ("Haptic: Error while trying to stop all playing effects."); } } } return 0; } #endif /* SDL_HAPTIC_LINUX */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/haptic/linux/SDL_syshaptic.c
C
apache-2.0
32,026
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #include "SDL_error.h" #include "SDL_haptic.h" #include "../SDL_syshaptic.h" #if SDL_HAPTIC_DINPUT #include "SDL_stdinc.h" #include "SDL_timer.h" #include "SDL_windowshaptic_c.h" #include "SDL_dinputhaptic_c.h" #include "../../joystick/windows/SDL_windowsjoystick_c.h" /* * External stuff. */ extern HWND SDL_HelperWindow; /* * Internal stuff. */ static SDL_bool coinitialized = SDL_FALSE; static LPDIRECTINPUT8 dinput = NULL; /* * Like SDL_SetError but for DX error codes. */ static int DI_SetError(const char *str, HRESULT err) { return SDL_SetError("Haptic error %s", str); } /* * Callback to find the haptic devices. */ static BOOL CALLBACK EnumHapticsCallback(const DIDEVICEINSTANCE * pdidInstance, VOID * pContext) { (void) pContext; SDL_DINPUT_MaybeAddDevice(pdidInstance); return DIENUM_CONTINUE; /* continue enumerating */ } int SDL_DINPUT_HapticInit(void) { HRESULT ret; HINSTANCE instance; if (dinput != NULL) { /* Already open. */ return SDL_SetError("Haptic: SubSystem already open."); } ret = WIN_CoInitialize(); if (FAILED(ret)) { return DI_SetError("Coinitialize", ret); } coinitialized = SDL_TRUE; ret = CoCreateInstance(&CLSID_DirectInput8, NULL, CLSCTX_INPROC_SERVER, &IID_IDirectInput8, (LPVOID *) &dinput); if (FAILED(ret)) { SDL_SYS_HapticQuit(); return DI_SetError("CoCreateInstance", ret); } /* Because we used CoCreateInstance, we need to Initialize it, first. */ instance = GetModuleHandle(NULL); if (instance == NULL) { SDL_SYS_HapticQuit(); return SDL_SetError("GetModuleHandle() failed with error code %lu.", GetLastError()); } ret = IDirectInput8_Initialize(dinput, instance, DIRECTINPUT_VERSION); if (FAILED(ret)) { SDL_SYS_HapticQuit(); return DI_SetError("Initializing DirectInput device", ret); } /* Look for haptic devices. */ ret = IDirectInput8_EnumDevices(dinput, 0, EnumHapticsCallback, NULL, DIEDFL_FORCEFEEDBACK | DIEDFL_ATTACHEDONLY); if (FAILED(ret)) { SDL_SYS_HapticQuit(); return DI_SetError("Enumerating DirectInput devices", ret); } return 0; } int SDL_DINPUT_MaybeAddDevice(const DIDEVICEINSTANCE * pdidInstance) { HRESULT ret; LPDIRECTINPUTDEVICE8 device; const DWORD needflags = DIDC_ATTACHED | DIDC_FORCEFEEDBACK; DIDEVCAPS capabilities; SDL_hapticlist_item *item = NULL; if (dinput == NULL) { return -1; /* not initialized. We'll pick these up on enumeration if we init later. */ } /* Make sure we don't already have it */ for (item = SDL_hapticlist; item; item = item->next) { if ((!item->bXInputHaptic) && (SDL_memcmp(&item->instance, pdidInstance, sizeof(*pdidInstance)) == 0)) { return -1; /* Already added */ } } /* Open the device */ ret = IDirectInput8_CreateDevice(dinput, &pdidInstance->guidInstance, &device, NULL); if (FAILED(ret)) { /* DI_SetError("Creating DirectInput device",ret); */ return -1; } /* Get capabilities. */ SDL_zero(capabilities); capabilities.dwSize = sizeof(DIDEVCAPS); ret = IDirectInputDevice8_GetCapabilities(device, &capabilities); IDirectInputDevice8_Release(device); if (FAILED(ret)) { /* DI_SetError("Getting device capabilities",ret); */ return -1; } if ((capabilities.dwFlags & needflags) != needflags) { return -1; /* not a device we can use. */ } item = (SDL_hapticlist_item *)SDL_calloc(1, sizeof(SDL_hapticlist_item)); if (item == NULL) { return SDL_OutOfMemory(); } item->name = WIN_StringToUTF8(pdidInstance->tszProductName); if (!item->name) { SDL_free(item); return -1; } /* Copy the instance over, useful for creating devices. */ SDL_memcpy(&item->instance, pdidInstance, sizeof(DIDEVICEINSTANCE)); SDL_memcpy(&item->capabilities, &capabilities, sizeof(capabilities)); return SDL_SYS_AddHapticDevice(item); } int SDL_DINPUT_MaybeRemoveDevice(const DIDEVICEINSTANCE * pdidInstance) { SDL_hapticlist_item *item; SDL_hapticlist_item *prev = NULL; if (dinput == NULL) { return -1; /* not initialized, ignore this. */ } for (item = SDL_hapticlist; item != NULL; item = item->next) { if (!item->bXInputHaptic && SDL_memcmp(&item->instance, pdidInstance, sizeof(*pdidInstance)) == 0) { /* found it, remove it. */ return SDL_SYS_RemoveHapticDevice(prev, item); } prev = item; } return -1; } /* * Callback to get supported axes. */ static BOOL CALLBACK DI_DeviceObjectCallback(LPCDIDEVICEOBJECTINSTANCE dev, LPVOID pvRef) { SDL_Haptic *haptic = (SDL_Haptic *) pvRef; if ((dev->dwType & DIDFT_AXIS) && (dev->dwFlags & DIDOI_FFACTUATOR)) { const GUID *guid = &dev->guidType; DWORD offset = 0; if (WIN_IsEqualGUID(guid, &GUID_XAxis)) { offset = DIJOFS_X; } else if (WIN_IsEqualGUID(guid, &GUID_YAxis)) { offset = DIJOFS_Y; } else if (WIN_IsEqualGUID(guid, &GUID_ZAxis)) { offset = DIJOFS_Z; } else if (WIN_IsEqualGUID(guid, &GUID_RxAxis)) { offset = DIJOFS_RX; } else if (WIN_IsEqualGUID(guid, &GUID_RyAxis)) { offset = DIJOFS_RY; } else if (WIN_IsEqualGUID(guid, &GUID_RzAxis)) { offset = DIJOFS_RZ; } else { return DIENUM_CONTINUE; /* can't use this, go on. */ } haptic->hwdata->axes[haptic->naxes] = offset; haptic->naxes++; /* Currently using the artificial limit of 3 axes. */ if (haptic->naxes >= 3) { return DIENUM_STOP; } } return DIENUM_CONTINUE; } /* * Callback to get all supported effects. */ #define EFFECT_TEST(e,s) \ if (WIN_IsEqualGUID(&pei->guid, &(e))) \ haptic->supported |= (s) static BOOL CALLBACK DI_EffectCallback(LPCDIEFFECTINFO pei, LPVOID pv) { /* Prepare the haptic device. */ SDL_Haptic *haptic = (SDL_Haptic *) pv; /* Get supported. */ EFFECT_TEST(GUID_Spring, SDL_HAPTIC_SPRING); EFFECT_TEST(GUID_Damper, SDL_HAPTIC_DAMPER); EFFECT_TEST(GUID_Inertia, SDL_HAPTIC_INERTIA); EFFECT_TEST(GUID_Friction, SDL_HAPTIC_FRICTION); EFFECT_TEST(GUID_ConstantForce, SDL_HAPTIC_CONSTANT); EFFECT_TEST(GUID_CustomForce, SDL_HAPTIC_CUSTOM); EFFECT_TEST(GUID_Sine, SDL_HAPTIC_SINE); /* !!! FIXME: put this back when we have more bits in 2.1 */ /* EFFECT_TEST(GUID_Square, SDL_HAPTIC_SQUARE); */ EFFECT_TEST(GUID_Triangle, SDL_HAPTIC_TRIANGLE); EFFECT_TEST(GUID_SawtoothUp, SDL_HAPTIC_SAWTOOTHUP); EFFECT_TEST(GUID_SawtoothDown, SDL_HAPTIC_SAWTOOTHDOWN); EFFECT_TEST(GUID_RampForce, SDL_HAPTIC_RAMP); /* Check for more. */ return DIENUM_CONTINUE; } /* * Opens the haptic device. * * Steps: * - Set cooperative level. * - Set data format. * - Acquire exclusiveness. * - Reset actuators. * - Get supported features. */ static int SDL_DINPUT_HapticOpenFromDevice(SDL_Haptic * haptic, LPDIRECTINPUTDEVICE8 device8, SDL_bool is_joystick) { HRESULT ret; DIPROPDWORD dipdw; /* Allocate the hwdata */ haptic->hwdata = (struct haptic_hwdata *)SDL_malloc(sizeof(*haptic->hwdata)); if (haptic->hwdata == NULL) { return SDL_OutOfMemory(); } SDL_memset(haptic->hwdata, 0, sizeof(*haptic->hwdata)); /* We'll use the device8 from now on. */ haptic->hwdata->device = device8; haptic->hwdata->is_joystick = is_joystick; /* !!! FIXME: opening a haptic device here first will make an attempt to !!! FIXME: SDL_JoystickOpen() that same device fail later, since we !!! FIXME: have it open in exclusive mode. But this will allow !!! FIXME: SDL_JoystickOpen() followed by SDL_HapticOpenFromJoystick() !!! FIXME: to work, and that's probably the common case. Still, !!! FIXME: ideally, We need to unify the opening code. */ if (!is_joystick) { /* if is_joystick, we already set this up elsewhere. */ /* Grab it exclusively to use force feedback stuff. */ ret = IDirectInputDevice8_SetCooperativeLevel(haptic->hwdata->device, SDL_HelperWindow, DISCL_EXCLUSIVE | DISCL_BACKGROUND); if (FAILED(ret)) { DI_SetError("Setting cooperative level to exclusive", ret); goto acquire_err; } /* Set data format. */ ret = IDirectInputDevice8_SetDataFormat(haptic->hwdata->device, &SDL_c_dfDIJoystick2); if (FAILED(ret)) { DI_SetError("Setting data format", ret); goto acquire_err; } /* Acquire the device. */ ret = IDirectInputDevice8_Acquire(haptic->hwdata->device); if (FAILED(ret)) { DI_SetError("Acquiring DirectInput device", ret); goto acquire_err; } } /* Get number of axes. */ ret = IDirectInputDevice8_EnumObjects(haptic->hwdata->device, DI_DeviceObjectCallback, haptic, DIDFT_AXIS); if (FAILED(ret)) { DI_SetError("Getting device axes", ret); goto acquire_err; } /* Reset all actuators - just in case. */ ret = IDirectInputDevice8_SendForceFeedbackCommand(haptic->hwdata->device, DISFFC_RESET); if (FAILED(ret)) { DI_SetError("Resetting device", ret); goto acquire_err; } /* Enabling actuators. */ ret = IDirectInputDevice8_SendForceFeedbackCommand(haptic->hwdata->device, DISFFC_SETACTUATORSON); if (FAILED(ret)) { DI_SetError("Enabling actuators", ret); goto acquire_err; } /* Get supported effects. */ ret = IDirectInputDevice8_EnumEffects(haptic->hwdata->device, DI_EffectCallback, haptic, DIEFT_ALL); if (FAILED(ret)) { DI_SetError("Enumerating supported effects", ret); goto acquire_err; } if (haptic->supported == 0) { /* Error since device supports nothing. */ SDL_SetError("Haptic: Internal error on finding supported effects."); goto acquire_err; } /* Check autogain and autocenter. */ dipdw.diph.dwSize = sizeof(DIPROPDWORD); dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); dipdw.diph.dwObj = 0; dipdw.diph.dwHow = DIPH_DEVICE; dipdw.dwData = 10000; ret = IDirectInputDevice8_SetProperty(haptic->hwdata->device, DIPROP_FFGAIN, &dipdw.diph); if (!FAILED(ret)) { /* Gain is supported. */ haptic->supported |= SDL_HAPTIC_GAIN; } dipdw.diph.dwObj = 0; dipdw.diph.dwHow = DIPH_DEVICE; dipdw.dwData = DIPROPAUTOCENTER_OFF; ret = IDirectInputDevice8_SetProperty(haptic->hwdata->device, DIPROP_AUTOCENTER, &dipdw.diph); if (!FAILED(ret)) { /* Autocenter is supported. */ haptic->supported |= SDL_HAPTIC_AUTOCENTER; } /* Status is always supported. */ haptic->supported |= SDL_HAPTIC_STATUS | SDL_HAPTIC_PAUSE; /* Check maximum effects. */ haptic->neffects = 128; /* This is not actually supported as thus under windows, there is no way to tell the number of EFFECTS that a device can hold, so we'll just use a "random" number instead and put warnings in SDL_haptic.h */ haptic->nplaying = 128; /* Even more impossible to get this then neffects. */ /* Prepare effects memory. */ haptic->effects = (struct haptic_effect *) SDL_malloc(sizeof(struct haptic_effect) * haptic->neffects); if (haptic->effects == NULL) { SDL_OutOfMemory(); goto acquire_err; } /* Clear the memory */ SDL_memset(haptic->effects, 0, sizeof(struct haptic_effect) * haptic->neffects); return 0; /* Error handling */ acquire_err: IDirectInputDevice8_Unacquire(haptic->hwdata->device); return -1; } int SDL_DINPUT_HapticOpen(SDL_Haptic * haptic, SDL_hapticlist_item *item) { HRESULT ret; LPDIRECTINPUTDEVICE8 device; LPDIRECTINPUTDEVICE8 device8; /* Open the device */ ret = IDirectInput8_CreateDevice(dinput, &item->instance.guidInstance, &device, NULL); if (FAILED(ret)) { DI_SetError("Creating DirectInput device", ret); return -1; } /* Now get the IDirectInputDevice8 interface, instead. */ ret = IDirectInputDevice8_QueryInterface(device, &IID_IDirectInputDevice8, (LPVOID *)&device8); /* Done with the temporary one now. */ IDirectInputDevice8_Release(device); if (FAILED(ret)) { DI_SetError("Querying DirectInput interface", ret); return -1; } if (SDL_DINPUT_HapticOpenFromDevice(haptic, device8, SDL_FALSE) < 0) { IDirectInputDevice8_Release(device8); return -1; } return 0; } int SDL_DINPUT_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick) { HRESULT ret; DIDEVICEINSTANCE hap_instance, joy_instance; hap_instance.dwSize = sizeof(DIDEVICEINSTANCE); joy_instance.dwSize = sizeof(DIDEVICEINSTANCE); /* Get the device instances. */ ret = IDirectInputDevice8_GetDeviceInfo(haptic->hwdata->device, &hap_instance); if (FAILED(ret)) { return 0; } ret = IDirectInputDevice8_GetDeviceInfo(joystick->hwdata->InputDevice, &joy_instance); if (FAILED(ret)) { return 0; } return WIN_IsEqualGUID(&hap_instance.guidInstance, &joy_instance.guidInstance); } int SDL_DINPUT_HapticOpenFromJoystick(SDL_Haptic * haptic, SDL_Joystick * joystick) { SDL_hapticlist_item *item; int index = 0; HRESULT ret; DIDEVICEINSTANCE joy_instance; joy_instance.dwSize = sizeof(DIDEVICEINSTANCE); ret = IDirectInputDevice8_GetDeviceInfo(joystick->hwdata->InputDevice, &joy_instance); if (FAILED(ret)) { return -1; } /* Since it comes from a joystick we have to try to match it with a haptic device on our haptic list. */ for (item = SDL_hapticlist; item != NULL; item = item->next) { if (!item->bXInputHaptic && WIN_IsEqualGUID(&item->instance.guidInstance, &joy_instance.guidInstance)) { haptic->index = index; return SDL_DINPUT_HapticOpenFromDevice(haptic, joystick->hwdata->InputDevice, SDL_TRUE); } ++index; } SDL_SetError("Couldn't find joystick in haptic device list"); return -1; } void SDL_DINPUT_HapticClose(SDL_Haptic * haptic) { IDirectInputDevice8_Unacquire(haptic->hwdata->device); /* Only release if isn't grabbed by a joystick. */ if (haptic->hwdata->is_joystick == 0) { IDirectInputDevice8_Release(haptic->hwdata->device); } } void SDL_DINPUT_HapticQuit(void) { if (dinput != NULL) { IDirectInput8_Release(dinput); dinput = NULL; } if (coinitialized) { WIN_CoUninitialize(); coinitialized = SDL_FALSE; } } /* * Converts an SDL trigger button to an DIEFFECT trigger button. */ static DWORD DIGetTriggerButton(Uint16 button) { DWORD dwTriggerButton; dwTriggerButton = DIEB_NOTRIGGER; if (button != 0) { dwTriggerButton = DIJOFS_BUTTON(button - 1); } return dwTriggerButton; } /* * Sets the direction. */ static int SDL_SYS_SetDirection(DIEFFECT * effect, SDL_HapticDirection * dir, int naxes) { LONG *rglDir; /* Handle no axes a part. */ if (naxes == 0) { effect->dwFlags |= DIEFF_SPHERICAL; /* Set as default. */ effect->rglDirection = NULL; return 0; } /* Has axes. */ rglDir = SDL_malloc(sizeof(LONG) * naxes); if (rglDir == NULL) { return SDL_OutOfMemory(); } SDL_memset(rglDir, 0, sizeof(LONG) * naxes); effect->rglDirection = rglDir; switch (dir->type) { case SDL_HAPTIC_POLAR: effect->dwFlags |= DIEFF_POLAR; rglDir[0] = dir->dir[0]; return 0; case SDL_HAPTIC_CARTESIAN: effect->dwFlags |= DIEFF_CARTESIAN; rglDir[0] = dir->dir[0]; if (naxes > 1) rglDir[1] = dir->dir[1]; if (naxes > 2) rglDir[2] = dir->dir[2]; return 0; case SDL_HAPTIC_SPHERICAL: effect->dwFlags |= DIEFF_SPHERICAL; rglDir[0] = dir->dir[0]; if (naxes > 1) rglDir[1] = dir->dir[1]; if (naxes > 2) rglDir[2] = dir->dir[2]; return 0; case SDL_HAPTIC_STEERING_AXIS: effect->dwFlags |= DIEFF_CARTESIAN; rglDir[0] = 0; return 0; default: return SDL_SetError("Haptic: Unknown direction type."); } } /* Clamps and converts. */ #define CCONVERT(x) (((x) > 0x7FFF) ? 10000 : ((x)*10000) / 0x7FFF) /* Just converts. */ #define CONVERT(x) (((x)*10000) / 0x7FFF) /* * Creates the DIEFFECT from a SDL_HapticEffect. */ static int SDL_SYS_ToDIEFFECT(SDL_Haptic * haptic, DIEFFECT * dest, SDL_HapticEffect * src) { int i; DICONSTANTFORCE *constant; DIPERIODIC *periodic; DICONDITION *condition; /* Actually an array of conditions - one per axis. */ DIRAMPFORCE *ramp; DICUSTOMFORCE *custom; DIENVELOPE *envelope; SDL_HapticConstant *hap_constant; SDL_HapticPeriodic *hap_periodic; SDL_HapticCondition *hap_condition; SDL_HapticRamp *hap_ramp; SDL_HapticCustom *hap_custom; DWORD *axes; /* Set global stuff. */ SDL_memset(dest, 0, sizeof(DIEFFECT)); dest->dwSize = sizeof(DIEFFECT); /* Set the structure size. */ dest->dwSamplePeriod = 0; /* Not used by us. */ dest->dwGain = 10000; /* Gain is set globally, not locally. */ dest->dwFlags = DIEFF_OBJECTOFFSETS; /* Seems obligatory. */ /* Envelope. */ envelope = SDL_malloc(sizeof(DIENVELOPE)); if (envelope == NULL) { return SDL_OutOfMemory(); } SDL_memset(envelope, 0, sizeof(DIENVELOPE)); dest->lpEnvelope = envelope; envelope->dwSize = sizeof(DIENVELOPE); /* Always should be this. */ /* Axes. */ if (src->constant.direction.type == SDL_HAPTIC_STEERING_AXIS) { dest->cAxes = 1; } else { dest->cAxes = haptic->naxes; } if (dest->cAxes > 0) { axes = SDL_malloc(sizeof(DWORD) * dest->cAxes); if (axes == NULL) { return SDL_OutOfMemory(); } axes[0] = haptic->hwdata->axes[0]; /* Always at least one axis. */ if (dest->cAxes > 1) { axes[1] = haptic->hwdata->axes[1]; } if (dest->cAxes > 2) { axes[2] = haptic->hwdata->axes[2]; } dest->rgdwAxes = axes; } /* The big type handling switch, even bigger than Linux's version. */ switch (src->type) { case SDL_HAPTIC_CONSTANT: hap_constant = &src->constant; constant = SDL_malloc(sizeof(DICONSTANTFORCE)); if (constant == NULL) { return SDL_OutOfMemory(); } SDL_memset(constant, 0, sizeof(DICONSTANTFORCE)); /* Specifics */ constant->lMagnitude = CONVERT(hap_constant->level); dest->cbTypeSpecificParams = sizeof(DICONSTANTFORCE); dest->lpvTypeSpecificParams = constant; /* Generics */ dest->dwDuration = hap_constant->length * 1000; /* In microseconds. */ dest->dwTriggerButton = DIGetTriggerButton(hap_constant->button); dest->dwTriggerRepeatInterval = hap_constant->interval; dest->dwStartDelay = hap_constant->delay * 1000; /* In microseconds. */ /* Direction. */ if (SDL_SYS_SetDirection(dest, &hap_constant->direction, dest->cAxes) < 0) { return -1; } /* Envelope */ if ((hap_constant->attack_length == 0) && (hap_constant->fade_length == 0)) { SDL_free(dest->lpEnvelope); dest->lpEnvelope = NULL; } else { envelope->dwAttackLevel = CCONVERT(hap_constant->attack_level); envelope->dwAttackTime = hap_constant->attack_length * 1000; envelope->dwFadeLevel = CCONVERT(hap_constant->fade_level); envelope->dwFadeTime = hap_constant->fade_length * 1000; } break; case SDL_HAPTIC_SINE: /* !!! FIXME: put this back when we have more bits in 2.1 */ /* case SDL_HAPTIC_SQUARE: */ case SDL_HAPTIC_TRIANGLE: case SDL_HAPTIC_SAWTOOTHUP: case SDL_HAPTIC_SAWTOOTHDOWN: hap_periodic = &src->periodic; periodic = SDL_malloc(sizeof(DIPERIODIC)); if (periodic == NULL) { return SDL_OutOfMemory(); } SDL_memset(periodic, 0, sizeof(DIPERIODIC)); /* Specifics */ periodic->dwMagnitude = CONVERT(SDL_abs(hap_periodic->magnitude)); periodic->lOffset = CONVERT(hap_periodic->offset); periodic->dwPhase = (hap_periodic->phase + (hap_periodic->magnitude < 0 ? 18000 : 0)) % 36000; periodic->dwPeriod = hap_periodic->period * 1000; dest->cbTypeSpecificParams = sizeof(DIPERIODIC); dest->lpvTypeSpecificParams = periodic; /* Generics */ dest->dwDuration = hap_periodic->length * 1000; /* In microseconds. */ dest->dwTriggerButton = DIGetTriggerButton(hap_periodic->button); dest->dwTriggerRepeatInterval = hap_periodic->interval; dest->dwStartDelay = hap_periodic->delay * 1000; /* In microseconds. */ /* Direction. */ if (SDL_SYS_SetDirection(dest, &hap_periodic->direction, dest->cAxes) < 0) { return -1; } /* Envelope */ if ((hap_periodic->attack_length == 0) && (hap_periodic->fade_length == 0)) { SDL_free(dest->lpEnvelope); dest->lpEnvelope = NULL; } else { envelope->dwAttackLevel = CCONVERT(hap_periodic->attack_level); envelope->dwAttackTime = hap_periodic->attack_length * 1000; envelope->dwFadeLevel = CCONVERT(hap_periodic->fade_level); envelope->dwFadeTime = hap_periodic->fade_length * 1000; } break; case SDL_HAPTIC_SPRING: case SDL_HAPTIC_DAMPER: case SDL_HAPTIC_INERTIA: case SDL_HAPTIC_FRICTION: hap_condition = &src->condition; condition = SDL_malloc(sizeof(DICONDITION) * dest->cAxes); if (condition == NULL) { return SDL_OutOfMemory(); } SDL_memset(condition, 0, sizeof(DICONDITION)); /* Specifics */ for (i = 0; i < (int) dest->cAxes; i++) { condition[i].lOffset = CONVERT(hap_condition->center[i]); condition[i].lPositiveCoefficient = CONVERT(hap_condition->right_coeff[i]); condition[i].lNegativeCoefficient = CONVERT(hap_condition->left_coeff[i]); condition[i].dwPositiveSaturation = CCONVERT(hap_condition->right_sat[i] / 2); condition[i].dwNegativeSaturation = CCONVERT(hap_condition->left_sat[i] / 2); condition[i].lDeadBand = CCONVERT(hap_condition->deadband[i] / 2); } dest->cbTypeSpecificParams = sizeof(DICONDITION) * dest->cAxes; dest->lpvTypeSpecificParams = condition; /* Generics */ dest->dwDuration = hap_condition->length * 1000; /* In microseconds. */ dest->dwTriggerButton = DIGetTriggerButton(hap_condition->button); dest->dwTriggerRepeatInterval = hap_condition->interval; dest->dwStartDelay = hap_condition->delay * 1000; /* In microseconds. */ /* Direction. */ if (SDL_SYS_SetDirection(dest, &hap_condition->direction, dest->cAxes) < 0) { return -1; } /* Envelope - Not actually supported by most CONDITION implementations. */ SDL_free(dest->lpEnvelope); dest->lpEnvelope = NULL; break; case SDL_HAPTIC_RAMP: hap_ramp = &src->ramp; ramp = SDL_malloc(sizeof(DIRAMPFORCE)); if (ramp == NULL) { return SDL_OutOfMemory(); } SDL_memset(ramp, 0, sizeof(DIRAMPFORCE)); /* Specifics */ ramp->lStart = CONVERT(hap_ramp->start); ramp->lEnd = CONVERT(hap_ramp->end); dest->cbTypeSpecificParams = sizeof(DIRAMPFORCE); dest->lpvTypeSpecificParams = ramp; /* Generics */ dest->dwDuration = hap_ramp->length * 1000; /* In microseconds. */ dest->dwTriggerButton = DIGetTriggerButton(hap_ramp->button); dest->dwTriggerRepeatInterval = hap_ramp->interval; dest->dwStartDelay = hap_ramp->delay * 1000; /* In microseconds. */ /* Direction. */ if (SDL_SYS_SetDirection(dest, &hap_ramp->direction, dest->cAxes) < 0) { return -1; } /* Envelope */ if ((hap_ramp->attack_length == 0) && (hap_ramp->fade_length == 0)) { SDL_free(dest->lpEnvelope); dest->lpEnvelope = NULL; } else { envelope->dwAttackLevel = CCONVERT(hap_ramp->attack_level); envelope->dwAttackTime = hap_ramp->attack_length * 1000; envelope->dwFadeLevel = CCONVERT(hap_ramp->fade_level); envelope->dwFadeTime = hap_ramp->fade_length * 1000; } break; case SDL_HAPTIC_CUSTOM: hap_custom = &src->custom; custom = SDL_malloc(sizeof(DICUSTOMFORCE)); if (custom == NULL) { return SDL_OutOfMemory(); } SDL_memset(custom, 0, sizeof(DICUSTOMFORCE)); /* Specifics */ custom->cChannels = hap_custom->channels; custom->dwSamplePeriod = hap_custom->period * 1000; custom->cSamples = hap_custom->samples; custom->rglForceData = SDL_malloc(sizeof(LONG) * custom->cSamples * custom->cChannels); for (i = 0; i < hap_custom->samples * hap_custom->channels; i++) { /* Copy data. */ custom->rglForceData[i] = CCONVERT(hap_custom->data[i]); } dest->cbTypeSpecificParams = sizeof(DICUSTOMFORCE); dest->lpvTypeSpecificParams = custom; /* Generics */ dest->dwDuration = hap_custom->length * 1000; /* In microseconds. */ dest->dwTriggerButton = DIGetTriggerButton(hap_custom->button); dest->dwTriggerRepeatInterval = hap_custom->interval; dest->dwStartDelay = hap_custom->delay * 1000; /* In microseconds. */ /* Direction. */ if (SDL_SYS_SetDirection(dest, &hap_custom->direction, dest->cAxes) < 0) { return -1; } /* Envelope */ if ((hap_custom->attack_length == 0) && (hap_custom->fade_length == 0)) { SDL_free(dest->lpEnvelope); dest->lpEnvelope = NULL; } else { envelope->dwAttackLevel = CCONVERT(hap_custom->attack_level); envelope->dwAttackTime = hap_custom->attack_length * 1000; envelope->dwFadeLevel = CCONVERT(hap_custom->fade_level); envelope->dwFadeTime = hap_custom->fade_length * 1000; } break; default: return SDL_SetError("Haptic: Unknown effect type."); } return 0; } /* * Frees an DIEFFECT allocated by SDL_SYS_ToDIEFFECT. */ static void SDL_SYS_HapticFreeDIEFFECT(DIEFFECT * effect, int type) { DICUSTOMFORCE *custom; SDL_free(effect->lpEnvelope); effect->lpEnvelope = NULL; SDL_free(effect->rgdwAxes); effect->rgdwAxes = NULL; if (effect->lpvTypeSpecificParams != NULL) { if (type == SDL_HAPTIC_CUSTOM) { /* Must free the custom data. */ custom = (DICUSTOMFORCE *) effect->lpvTypeSpecificParams; SDL_free(custom->rglForceData); custom->rglForceData = NULL; } SDL_free(effect->lpvTypeSpecificParams); effect->lpvTypeSpecificParams = NULL; } SDL_free(effect->rglDirection); effect->rglDirection = NULL; } /* * Gets the effect type from the generic SDL haptic effect wrapper. */ static REFGUID SDL_SYS_HapticEffectType(SDL_HapticEffect * effect) { switch (effect->type) { case SDL_HAPTIC_CONSTANT: return &GUID_ConstantForce; case SDL_HAPTIC_RAMP: return &GUID_RampForce; /* !!! FIXME: put this back when we have more bits in 2.1 */ /* case SDL_HAPTIC_SQUARE: return &GUID_Square; */ case SDL_HAPTIC_SINE: return &GUID_Sine; case SDL_HAPTIC_TRIANGLE: return &GUID_Triangle; case SDL_HAPTIC_SAWTOOTHUP: return &GUID_SawtoothUp; case SDL_HAPTIC_SAWTOOTHDOWN: return &GUID_SawtoothDown; case SDL_HAPTIC_SPRING: return &GUID_Spring; case SDL_HAPTIC_DAMPER: return &GUID_Damper; case SDL_HAPTIC_INERTIA: return &GUID_Inertia; case SDL_HAPTIC_FRICTION: return &GUID_Friction; case SDL_HAPTIC_CUSTOM: return &GUID_CustomForce; default: return NULL; } } int SDL_DINPUT_HapticNewEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * base) { HRESULT ret; REFGUID type = SDL_SYS_HapticEffectType(base); if (type == NULL) { SDL_SetError("Haptic: Unknown effect type."); return -1; } /* Get the effect. */ if (SDL_SYS_ToDIEFFECT(haptic, &effect->hweffect->effect, base) < 0) { goto err_effectdone; } /* Create the actual effect. */ ret = IDirectInputDevice8_CreateEffect(haptic->hwdata->device, type, &effect->hweffect->effect, &effect->hweffect->ref, NULL); if (FAILED(ret)) { DI_SetError("Unable to create effect", ret); goto err_effectdone; } return 0; err_effectdone: SDL_SYS_HapticFreeDIEFFECT(&effect->hweffect->effect, base->type); return -1; } int SDL_DINPUT_HapticUpdateEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * data) { HRESULT ret; DWORD flags; DIEFFECT temp; /* Get the effect. */ SDL_memset(&temp, 0, sizeof(DIEFFECT)); if (SDL_SYS_ToDIEFFECT(haptic, &temp, data) < 0) { goto err_update; } /* Set the flags. Might be worthwhile to diff temp with loaded effect and * only change those parameters. */ flags = DIEP_DIRECTION | DIEP_DURATION | DIEP_ENVELOPE | DIEP_STARTDELAY | DIEP_TRIGGERBUTTON | DIEP_TRIGGERREPEATINTERVAL | DIEP_TYPESPECIFICPARAMS; /* Create the actual effect. */ ret = IDirectInputEffect_SetParameters(effect->hweffect->ref, &temp, flags); if (ret == DIERR_NOTEXCLUSIVEACQUIRED) { IDirectInputDevice8_Unacquire(haptic->hwdata->device); ret = IDirectInputDevice8_SetCooperativeLevel(haptic->hwdata->device, SDL_HelperWindow, DISCL_EXCLUSIVE | DISCL_BACKGROUND); if (SUCCEEDED(ret)) { ret = DIERR_NOTACQUIRED; } } if (ret == DIERR_INPUTLOST || ret == DIERR_NOTACQUIRED) { ret = IDirectInputDevice8_Acquire(haptic->hwdata->device); if (SUCCEEDED(ret)) { ret = IDirectInputEffect_SetParameters(effect->hweffect->ref, &temp, flags); } } if (FAILED(ret)) { DI_SetError("Unable to update effect", ret); goto err_update; } /* Copy it over. */ SDL_SYS_HapticFreeDIEFFECT(&effect->hweffect->effect, data->type); SDL_memcpy(&effect->hweffect->effect, &temp, sizeof(DIEFFECT)); return 0; err_update: SDL_SYS_HapticFreeDIEFFECT(&temp, data->type); return -1; } int SDL_DINPUT_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect *effect, Uint32 iterations) { HRESULT ret; DWORD iter; /* Check if it's infinite. */ if (iterations == SDL_HAPTIC_INFINITY) { iter = INFINITE; } else { iter = iterations; } /* Run the effect. */ ret = IDirectInputEffect_Start(effect->hweffect->ref, iter, 0); if (FAILED(ret)) { return DI_SetError("Running the effect", ret); } return 0; } int SDL_DINPUT_HapticStopEffect(SDL_Haptic * haptic, struct haptic_effect *effect) { HRESULT ret; ret = IDirectInputEffect_Stop(effect->hweffect->ref); if (FAILED(ret)) { return DI_SetError("Unable to stop effect", ret); } return 0; } void SDL_DINPUT_HapticDestroyEffect(SDL_Haptic * haptic, struct haptic_effect *effect) { HRESULT ret; ret = IDirectInputEffect_Unload(effect->hweffect->ref); if (FAILED(ret)) { DI_SetError("Removing effect from the device", ret); } SDL_SYS_HapticFreeDIEFFECT(&effect->hweffect->effect, effect->effect.type); } int SDL_DINPUT_HapticGetEffectStatus(SDL_Haptic * haptic, struct haptic_effect *effect) { HRESULT ret; DWORD status; ret = IDirectInputEffect_GetEffectStatus(effect->hweffect->ref, &status); if (FAILED(ret)) { return DI_SetError("Getting effect status", ret); } if (status == 0) return SDL_FALSE; return SDL_TRUE; } int SDL_DINPUT_HapticSetGain(SDL_Haptic * haptic, int gain) { HRESULT ret; DIPROPDWORD dipdw; /* Create the weird structure thingy. */ dipdw.diph.dwSize = sizeof(DIPROPDWORD); dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); dipdw.diph.dwObj = 0; dipdw.diph.dwHow = DIPH_DEVICE; dipdw.dwData = gain * 100; /* 0 to 10,000 */ /* Try to set the autocenter. */ ret = IDirectInputDevice8_SetProperty(haptic->hwdata->device, DIPROP_FFGAIN, &dipdw.diph); if (FAILED(ret)) { return DI_SetError("Setting gain", ret); } return 0; } int SDL_DINPUT_HapticSetAutocenter(SDL_Haptic * haptic, int autocenter) { HRESULT ret; DIPROPDWORD dipdw; /* Create the weird structure thingy. */ dipdw.diph.dwSize = sizeof(DIPROPDWORD); dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); dipdw.diph.dwObj = 0; dipdw.diph.dwHow = DIPH_DEVICE; dipdw.dwData = (autocenter == 0) ? DIPROPAUTOCENTER_OFF : DIPROPAUTOCENTER_ON; /* Try to set the autocenter. */ ret = IDirectInputDevice8_SetProperty(haptic->hwdata->device, DIPROP_AUTOCENTER, &dipdw.diph); if (FAILED(ret)) { return DI_SetError("Setting autocenter", ret); } return 0; } int SDL_DINPUT_HapticPause(SDL_Haptic * haptic) { HRESULT ret; /* Pause the device. */ ret = IDirectInputDevice8_SendForceFeedbackCommand(haptic->hwdata->device, DISFFC_PAUSE); if (FAILED(ret)) { return DI_SetError("Pausing the device", ret); } return 0; } int SDL_DINPUT_HapticUnpause(SDL_Haptic * haptic) { HRESULT ret; /* Unpause the device. */ ret = IDirectInputDevice8_SendForceFeedbackCommand(haptic->hwdata->device, DISFFC_CONTINUE); if (FAILED(ret)) { return DI_SetError("Pausing the device", ret); } return 0; } int SDL_DINPUT_HapticStopAll(SDL_Haptic * haptic) { HRESULT ret; /* Try to stop the effects. */ ret = IDirectInputDevice8_SendForceFeedbackCommand(haptic->hwdata->device, DISFFC_STOPALL); if (FAILED(ret)) { return DI_SetError("Stopping the device", ret); } return 0; } #else /* !SDL_HAPTIC_DINPUT */ typedef struct DIDEVICEINSTANCE DIDEVICEINSTANCE; typedef struct SDL_hapticlist_item SDL_hapticlist_item; int SDL_DINPUT_HapticInit(void) { return 0; } int SDL_DINPUT_MaybeAddDevice(const DIDEVICEINSTANCE * pdidInstance) { return SDL_Unsupported(); } int SDL_DINPUT_MaybeRemoveDevice(const DIDEVICEINSTANCE * pdidInstance) { return SDL_Unsupported(); } int SDL_DINPUT_HapticOpen(SDL_Haptic * haptic, SDL_hapticlist_item *item) { return SDL_Unsupported(); } int SDL_DINPUT_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick) { return SDL_Unsupported(); } int SDL_DINPUT_HapticOpenFromJoystick(SDL_Haptic * haptic, SDL_Joystick * joystick) { return SDL_Unsupported(); } void SDL_DINPUT_HapticClose(SDL_Haptic * haptic) { } void SDL_DINPUT_HapticQuit(void) { } int SDL_DINPUT_HapticNewEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * base) { return SDL_Unsupported(); } int SDL_DINPUT_HapticUpdateEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * data) { return SDL_Unsupported(); } int SDL_DINPUT_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect *effect, Uint32 iterations) { return SDL_Unsupported(); } int SDL_DINPUT_HapticStopEffect(SDL_Haptic * haptic, struct haptic_effect *effect) { return SDL_Unsupported(); } void SDL_DINPUT_HapticDestroyEffect(SDL_Haptic * haptic, struct haptic_effect *effect) { } int SDL_DINPUT_HapticGetEffectStatus(SDL_Haptic * haptic, struct haptic_effect *effect) { return SDL_Unsupported(); } int SDL_DINPUT_HapticSetGain(SDL_Haptic * haptic, int gain) { return SDL_Unsupported(); } int SDL_DINPUT_HapticSetAutocenter(SDL_Haptic * haptic, int autocenter) { return SDL_Unsupported(); } int SDL_DINPUT_HapticPause(SDL_Haptic * haptic) { return SDL_Unsupported(); } int SDL_DINPUT_HapticUnpause(SDL_Haptic * haptic) { return SDL_Unsupported(); } int SDL_DINPUT_HapticStopAll(SDL_Haptic * haptic) { return SDL_Unsupported(); } #endif /* SDL_HAPTIC_DINPUT */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/haptic/windows/SDL_dinputhaptic.c
C
apache-2.0
38,977
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #include "SDL_haptic.h" #include "SDL_windowshaptic_c.h" extern int SDL_DINPUT_HapticInit(void); extern int SDL_DINPUT_MaybeAddDevice(const DIDEVICEINSTANCE *pdidInstance); extern int SDL_DINPUT_MaybeRemoveDevice(const DIDEVICEINSTANCE *pdidInstance); extern int SDL_DINPUT_HapticOpen(SDL_Haptic * haptic, SDL_hapticlist_item *item); extern int SDL_DINPUT_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick); extern int SDL_DINPUT_HapticOpenFromJoystick(SDL_Haptic * haptic, SDL_Joystick * joystick); extern void SDL_DINPUT_HapticClose(SDL_Haptic * haptic); extern void SDL_DINPUT_HapticQuit(void); extern int SDL_DINPUT_HapticNewEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * base); extern int SDL_DINPUT_HapticUpdateEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * data); extern int SDL_DINPUT_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect *effect, Uint32 iterations); extern int SDL_DINPUT_HapticStopEffect(SDL_Haptic * haptic, struct haptic_effect *effect); extern void SDL_DINPUT_HapticDestroyEffect(SDL_Haptic * haptic, struct haptic_effect *effect); extern int SDL_DINPUT_HapticGetEffectStatus(SDL_Haptic * haptic, struct haptic_effect *effect); extern int SDL_DINPUT_HapticSetGain(SDL_Haptic * haptic, int gain); extern int SDL_DINPUT_HapticSetAutocenter(SDL_Haptic * haptic, int autocenter); extern int SDL_DINPUT_HapticPause(SDL_Haptic * haptic); extern int SDL_DINPUT_HapticUnpause(SDL_Haptic * haptic); extern int SDL_DINPUT_HapticStopAll(SDL_Haptic * haptic); /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/haptic/windows/SDL_dinputhaptic_c.h
C
apache-2.0
2,566
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_HAPTIC_DINPUT || SDL_HAPTIC_XINPUT #include "SDL_assert.h" #include "SDL_thread.h" #include "SDL_mutex.h" #include "SDL_timer.h" #include "SDL_hints.h" #include "SDL_haptic.h" #include "../SDL_syshaptic.h" #include "SDL_joystick.h" #include "../../joystick/SDL_sysjoystick.h" /* For the real SDL_Joystick */ #include "../../joystick/windows/SDL_windowsjoystick_c.h" /* For joystick hwdata */ #include "../../joystick/windows/SDL_xinputjoystick_c.h" /* For xinput rumble */ #include "SDL_windowshaptic_c.h" #include "SDL_dinputhaptic_c.h" #include "SDL_xinputhaptic_c.h" /* * Internal stuff. */ SDL_hapticlist_item *SDL_hapticlist = NULL; static SDL_hapticlist_item *SDL_hapticlist_tail = NULL; static int numhaptics = 0; /* * Initializes the haptic subsystem. */ int SDL_SYS_HapticInit(void) { if (SDL_DINPUT_HapticInit() < 0) { return -1; } if (SDL_XINPUT_HapticInit() < 0) { return -1; } return numhaptics; } int SDL_SYS_AddHapticDevice(SDL_hapticlist_item *item) { if (SDL_hapticlist_tail == NULL) { SDL_hapticlist = SDL_hapticlist_tail = item; } else { SDL_hapticlist_tail->next = item; SDL_hapticlist_tail = item; } /* Device has been added. */ ++numhaptics; return numhaptics; } int SDL_SYS_RemoveHapticDevice(SDL_hapticlist_item *prev, SDL_hapticlist_item *item) { const int retval = item->haptic ? item->haptic->index : -1; if (prev != NULL) { prev->next = item->next; } else { SDL_assert(SDL_hapticlist == item); SDL_hapticlist = item->next; } if (item == SDL_hapticlist_tail) { SDL_hapticlist_tail = prev; } --numhaptics; /* !!! TODO: Send a haptic remove event? */ SDL_free(item); return retval; } int SDL_SYS_NumHaptics(void) { return numhaptics; } static SDL_hapticlist_item * HapticByDevIndex(int device_index) { SDL_hapticlist_item *item = SDL_hapticlist; if ((device_index < 0) || (device_index >= numhaptics)) { return NULL; } while (device_index > 0) { SDL_assert(item != NULL); --device_index; item = item->next; } return item; } /* * Return the name of a haptic device, does not need to be opened. */ const char * SDL_SYS_HapticName(int index) { SDL_hapticlist_item *item = HapticByDevIndex(index); return item->name; } /* * Opens a haptic device for usage. */ int SDL_SYS_HapticOpen(SDL_Haptic * haptic) { SDL_hapticlist_item *item = HapticByDevIndex(haptic->index); if (item->bXInputHaptic) { return SDL_XINPUT_HapticOpen(haptic, item); } else { return SDL_DINPUT_HapticOpen(haptic, item); } } /* * Opens a haptic device from first mouse it finds for usage. */ int SDL_SYS_HapticMouse(void) { #if SDL_HAPTIC_DINPUT SDL_hapticlist_item *item; int index = 0; /* Grab the first mouse haptic device we find. */ for (item = SDL_hapticlist; item != NULL; item = item->next) { if (item->capabilities.dwDevType == DI8DEVCLASS_POINTER) { return index; } ++index; } #endif /* SDL_HAPTIC_DINPUT */ return -1; } /* * Checks to see if a joystick has haptic features. */ int SDL_SYS_JoystickIsHaptic(SDL_Joystick * joystick) { if (joystick->driver != &SDL_WINDOWS_JoystickDriver) { return 0; } #if SDL_HAPTIC_XINPUT if (joystick->hwdata->bXInputHaptic) { return 1; } #endif #if SDL_HAPTIC_DINPUT if (joystick->hwdata->Capabilities.dwFlags & DIDC_FORCEFEEDBACK) { return 1; } #endif return 0; } /* * Checks to see if the haptic device and joystick are in reality the same. */ int SDL_SYS_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick) { if (joystick->driver != &SDL_WINDOWS_JoystickDriver) { return 0; } if (joystick->hwdata->bXInputHaptic != haptic->hwdata->bXInputHaptic) { return 0; /* one is XInput, one is not; not the same device. */ } else if (joystick->hwdata->bXInputHaptic) { return SDL_XINPUT_JoystickSameHaptic(haptic, joystick); } else { return SDL_DINPUT_JoystickSameHaptic(haptic, joystick); } } /* * Opens a SDL_Haptic from a SDL_Joystick. */ int SDL_SYS_HapticOpenFromJoystick(SDL_Haptic * haptic, SDL_Joystick * joystick) { SDL_assert(joystick->driver == &SDL_WINDOWS_JoystickDriver); if (joystick->hwdata->bXInputDevice) { return SDL_XINPUT_HapticOpenFromJoystick(haptic, joystick); } else { return SDL_DINPUT_HapticOpenFromJoystick(haptic, joystick); } } /* * Closes the haptic device. */ void SDL_SYS_HapticClose(SDL_Haptic * haptic) { if (haptic->hwdata) { /* Free effects. */ SDL_free(haptic->effects); haptic->effects = NULL; haptic->neffects = 0; /* Clean up */ if (haptic->hwdata->bXInputHaptic) { SDL_XINPUT_HapticClose(haptic); } else { SDL_DINPUT_HapticClose(haptic); } /* Free */ SDL_free(haptic->hwdata); haptic->hwdata = NULL; } } /* * Clean up after system specific haptic stuff */ void SDL_SYS_HapticQuit(void) { SDL_hapticlist_item *item; SDL_hapticlist_item *next = NULL; SDL_Haptic *hapticitem = NULL; extern SDL_Haptic *SDL_haptics; for (hapticitem = SDL_haptics; hapticitem; hapticitem = hapticitem->next) { if ((hapticitem->hwdata->bXInputHaptic) && (hapticitem->hwdata->thread)) { /* we _have_ to stop the thread before we free the XInput DLL! */ SDL_AtomicSet(&hapticitem->hwdata->stopThread, 1); SDL_WaitThread(hapticitem->hwdata->thread, NULL); hapticitem->hwdata->thread = NULL; } } for (item = SDL_hapticlist; item; item = next) { /* Opened and not closed haptics are leaked, this is on purpose. * Close your haptic devices after usage. */ /* !!! FIXME: (...is leaking on purpose a good idea?) - No, of course not. */ next = item->next; SDL_free(item->name); SDL_free(item); } SDL_XINPUT_HapticQuit(); SDL_DINPUT_HapticQuit(); numhaptics = 0; SDL_hapticlist = NULL; SDL_hapticlist_tail = NULL; } /* * Creates a new haptic effect. */ int SDL_SYS_HapticNewEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * base) { int result; /* Alloc the effect. */ effect->hweffect = (struct haptic_hweffect *) SDL_malloc(sizeof(struct haptic_hweffect)); if (effect->hweffect == NULL) { SDL_OutOfMemory(); return -1; } SDL_zerop(effect->hweffect); if (haptic->hwdata->bXInputHaptic) { result = SDL_XINPUT_HapticNewEffect(haptic, effect, base); } else { result = SDL_DINPUT_HapticNewEffect(haptic, effect, base); } if (result < 0) { SDL_free(effect->hweffect); effect->hweffect = NULL; } return result; } /* * Updates an effect. */ int SDL_SYS_HapticUpdateEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * data) { if (haptic->hwdata->bXInputHaptic) { return SDL_XINPUT_HapticUpdateEffect(haptic, effect, data); } else { return SDL_DINPUT_HapticUpdateEffect(haptic, effect, data); } } /* * Runs an effect. */ int SDL_SYS_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect *effect, Uint32 iterations) { if (haptic->hwdata->bXInputHaptic) { return SDL_XINPUT_HapticRunEffect(haptic, effect, iterations); } else { return SDL_DINPUT_HapticRunEffect(haptic, effect, iterations); } } /* * Stops an effect. */ int SDL_SYS_HapticStopEffect(SDL_Haptic * haptic, struct haptic_effect *effect) { if (haptic->hwdata->bXInputHaptic) { return SDL_XINPUT_HapticStopEffect(haptic, effect); } else { return SDL_DINPUT_HapticStopEffect(haptic, effect); } } /* * Frees the effect. */ void SDL_SYS_HapticDestroyEffect(SDL_Haptic * haptic, struct haptic_effect *effect) { if (haptic->hwdata->bXInputHaptic) { SDL_XINPUT_HapticDestroyEffect(haptic, effect); } else { SDL_DINPUT_HapticDestroyEffect(haptic, effect); } SDL_free(effect->hweffect); effect->hweffect = NULL; } /* * Gets the status of a haptic effect. */ int SDL_SYS_HapticGetEffectStatus(SDL_Haptic * haptic, struct haptic_effect *effect) { if (haptic->hwdata->bXInputHaptic) { return SDL_XINPUT_HapticGetEffectStatus(haptic, effect); } else { return SDL_DINPUT_HapticGetEffectStatus(haptic, effect); } } /* * Sets the gain. */ int SDL_SYS_HapticSetGain(SDL_Haptic * haptic, int gain) { if (haptic->hwdata->bXInputHaptic) { return SDL_XINPUT_HapticSetGain(haptic, gain); } else { return SDL_DINPUT_HapticSetGain(haptic, gain); } } /* * Sets the autocentering. */ int SDL_SYS_HapticSetAutocenter(SDL_Haptic * haptic, int autocenter) { if (haptic->hwdata->bXInputHaptic) { return SDL_XINPUT_HapticSetAutocenter(haptic, autocenter); } else { return SDL_DINPUT_HapticSetAutocenter(haptic, autocenter); } } /* * Pauses the device. */ int SDL_SYS_HapticPause(SDL_Haptic * haptic) { if (haptic->hwdata->bXInputHaptic) { return SDL_XINPUT_HapticPause(haptic); } else { return SDL_DINPUT_HapticPause(haptic); } } /* * Pauses the device. */ int SDL_SYS_HapticUnpause(SDL_Haptic * haptic) { if (haptic->hwdata->bXInputHaptic) { return SDL_XINPUT_HapticUnpause(haptic); } else { return SDL_DINPUT_HapticUnpause(haptic); } } /* * Stops all the playing effects on the device. */ int SDL_SYS_HapticStopAll(SDL_Haptic * haptic) { if (haptic->hwdata->bXInputHaptic) { return SDL_XINPUT_HapticStopAll(haptic); } else { return SDL_DINPUT_HapticStopAll(haptic); } } #endif /* SDL_HAPTIC_DINPUT || SDL_HAPTIC_XINPUT */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/haptic/windows/SDL_windowshaptic.c
C
apache-2.0
11,136
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_windowshaptic_c_h_ #define SDL_windowshaptic_c_h_ #include "SDL_thread.h" #include "../SDL_syshaptic.h" #include "../../core/windows/SDL_directx.h" #include "../../core/windows/SDL_xinput.h" /* * Haptic system hardware data. */ struct haptic_hwdata { #if SDL_HAPTIC_DINPUT LPDIRECTINPUTDEVICE8 device; #endif DWORD axes[3]; /* Axes to use. */ SDL_bool is_joystick; /* Device is loaded as joystick. */ Uint8 bXInputHaptic; /* Supports force feedback via XInput. */ Uint8 userid; /* XInput userid index for this joystick */ SDL_Thread *thread; SDL_mutex *mutex; Uint32 stopTicks; SDL_atomic_t stopThread; }; /* * Haptic system effect data. */ struct haptic_hweffect { #if SDL_HAPTIC_DINPUT DIEFFECT effect; LPDIRECTINPUTEFFECT ref; #endif #if SDL_HAPTIC_XINPUT XINPUT_VIBRATION vibration; #endif }; /* * List of available haptic devices. */ typedef struct SDL_hapticlist_item { char *name; SDL_Haptic *haptic; #if SDL_HAPTIC_DINPUT DIDEVICEINSTANCE instance; DIDEVCAPS capabilities; #endif SDL_bool bXInputHaptic; /* Supports force feedback via XInput. */ Uint8 userid; /* XInput userid index for this joystick */ struct SDL_hapticlist_item *next; } SDL_hapticlist_item; extern SDL_hapticlist_item *SDL_hapticlist; extern int SDL_SYS_AddHapticDevice(SDL_hapticlist_item *item); extern int SDL_SYS_RemoveHapticDevice(SDL_hapticlist_item *prev, SDL_hapticlist_item *item); #endif /* SDL_windowshaptic_c_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/haptic/windows/SDL_windowshaptic_c.h
C
apache-2.0
2,533
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #include "SDL_error.h" #include "SDL_haptic.h" #include "../SDL_syshaptic.h" #if SDL_HAPTIC_XINPUT #include "SDL_assert.h" #include "SDL_hints.h" #include "SDL_timer.h" #include "SDL_windowshaptic_c.h" #include "SDL_xinputhaptic_c.h" #include "../../core/windows/SDL_xinput.h" #include "../../joystick/windows/SDL_windowsjoystick_c.h" #include "../../thread/SDL_systhread.h" /* * Internal stuff. */ static SDL_bool loaded_xinput = SDL_FALSE; int SDL_XINPUT_HapticInit(void) { if (SDL_GetHintBoolean(SDL_HINT_XINPUT_ENABLED, SDL_TRUE)) { loaded_xinput = (WIN_LoadXInputDLL() == 0); } if (loaded_xinput) { DWORD i; for (i = 0; i < XUSER_MAX_COUNT; i++) { SDL_XINPUT_MaybeAddDevice(i); } } return 0; } int SDL_XINPUT_MaybeAddDevice(const DWORD dwUserid) { const Uint8 userid = (Uint8)dwUserid; SDL_hapticlist_item *item; XINPUT_VIBRATION state; if ((!loaded_xinput) || (dwUserid >= XUSER_MAX_COUNT)) { return -1; } /* Make sure we don't already have it */ for (item = SDL_hapticlist; item; item = item->next) { if (item->bXInputHaptic && item->userid == userid) { return -1; /* Already added */ } } SDL_zero(state); if (XINPUTSETSTATE(dwUserid, &state) != ERROR_SUCCESS) { return -1; /* no force feedback on this device. */ } item = (SDL_hapticlist_item *)SDL_malloc(sizeof(SDL_hapticlist_item)); if (item == NULL) { return SDL_OutOfMemory(); } SDL_zerop(item); /* !!! FIXME: I'm not bothering to query for a real name right now (can we even?) */ { char buf[64]; SDL_snprintf(buf, sizeof(buf), "XInput Controller #%u", (unsigned int)(userid + 1)); item->name = SDL_strdup(buf); } if (!item->name) { SDL_free(item); return -1; } /* Copy the instance over, useful for creating devices. */ item->bXInputHaptic = SDL_TRUE; item->userid = userid; return SDL_SYS_AddHapticDevice(item); } int SDL_XINPUT_MaybeRemoveDevice(const DWORD dwUserid) { const Uint8 userid = (Uint8)dwUserid; SDL_hapticlist_item *item; SDL_hapticlist_item *prev = NULL; if ((!loaded_xinput) || (dwUserid >= XUSER_MAX_COUNT)) { return -1; } for (item = SDL_hapticlist; item != NULL; item = item->next) { if (item->bXInputHaptic && item->userid == userid) { /* found it, remove it. */ return SDL_SYS_RemoveHapticDevice(prev, item); } prev = item; } return -1; } /* !!! FIXME: this is a hack, remove this later. */ /* Since XInput doesn't offer a way to vibrate for X time, we hook into * SDL_PumpEvents() to check if it's time to stop vibrating with some * frequency. * In practice, this works for 99% of use cases. But in an ideal world, * we do this in a separate thread so that: * - we aren't bound to when the app chooses to pump the event queue. * - we aren't adding more polling to the event queue * - we can emulate all the haptic effects correctly (start on a delay, * mix multiple effects, etc). * * Mostly, this is here to get rumbling to work, and all the other features * are absent in the XInput path for now. :( */ static int SDLCALL SDL_RunXInputHaptic(void *arg) { struct haptic_hwdata *hwdata = (struct haptic_hwdata *) arg; while (!SDL_AtomicGet(&hwdata->stopThread)) { SDL_Delay(50); SDL_LockMutex(hwdata->mutex); /* If we're currently running and need to stop... */ if (hwdata->stopTicks) { if ((hwdata->stopTicks != SDL_HAPTIC_INFINITY) && SDL_TICKS_PASSED(SDL_GetTicks(), hwdata->stopTicks)) { XINPUT_VIBRATION vibration = { 0, 0 }; hwdata->stopTicks = 0; XINPUTSETSTATE(hwdata->userid, &vibration); } } SDL_UnlockMutex(hwdata->mutex); } return 0; } static int SDL_XINPUT_HapticOpenFromUserIndex(SDL_Haptic *haptic, const Uint8 userid) { char threadName[32]; XINPUT_VIBRATION vibration = { 0, 0 }; /* stop any current vibration */ XINPUTSETSTATE(userid, &vibration); haptic->supported = SDL_HAPTIC_LEFTRIGHT; haptic->neffects = 1; haptic->nplaying = 1; /* Prepare effects memory. */ haptic->effects = (struct haptic_effect *) SDL_malloc(sizeof(struct haptic_effect) * haptic->neffects); if (haptic->effects == NULL) { return SDL_OutOfMemory(); } /* Clear the memory */ SDL_memset(haptic->effects, 0, sizeof(struct haptic_effect) * haptic->neffects); haptic->hwdata = (struct haptic_hwdata *) SDL_malloc(sizeof(*haptic->hwdata)); if (haptic->hwdata == NULL) { SDL_free(haptic->effects); haptic->effects = NULL; return SDL_OutOfMemory(); } SDL_memset(haptic->hwdata, 0, sizeof(*haptic->hwdata)); haptic->hwdata->bXInputHaptic = 1; haptic->hwdata->userid = userid; haptic->hwdata->mutex = SDL_CreateMutex(); if (haptic->hwdata->mutex == NULL) { SDL_free(haptic->effects); SDL_free(haptic->hwdata); haptic->effects = NULL; return SDL_SetError("Couldn't create XInput haptic mutex"); } SDL_snprintf(threadName, sizeof(threadName), "SDLXInputDev%d", (int)userid); haptic->hwdata->thread = SDL_CreateThreadInternal(SDL_RunXInputHaptic, threadName, 64 * 1024, haptic->hwdata); if (haptic->hwdata->thread == NULL) { SDL_DestroyMutex(haptic->hwdata->mutex); SDL_free(haptic->effects); SDL_free(haptic->hwdata); haptic->effects = NULL; return SDL_SetError("Couldn't create XInput haptic thread"); } return 0; } int SDL_XINPUT_HapticOpen(SDL_Haptic * haptic, SDL_hapticlist_item *item) { return SDL_XINPUT_HapticOpenFromUserIndex(haptic, item->userid); } int SDL_XINPUT_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick) { return (haptic->hwdata->userid == joystick->hwdata->userid); } int SDL_XINPUT_HapticOpenFromJoystick(SDL_Haptic * haptic, SDL_Joystick * joystick) { SDL_hapticlist_item *item; int index = 0; /* Since it comes from a joystick we have to try to match it with a haptic device on our haptic list. */ for (item = SDL_hapticlist; item != NULL; item = item->next) { if (item->bXInputHaptic && item->userid == joystick->hwdata->userid) { haptic->index = index; return SDL_XINPUT_HapticOpenFromUserIndex(haptic, joystick->hwdata->userid); } ++index; } SDL_SetError("Couldn't find joystick in haptic device list"); return -1; } void SDL_XINPUT_HapticClose(SDL_Haptic * haptic) { SDL_AtomicSet(&haptic->hwdata->stopThread, 1); SDL_WaitThread(haptic->hwdata->thread, NULL); SDL_DestroyMutex(haptic->hwdata->mutex); } void SDL_XINPUT_HapticQuit(void) { if (loaded_xinput) { WIN_UnloadXInputDLL(); loaded_xinput = SDL_FALSE; } } int SDL_XINPUT_HapticNewEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * base) { SDL_assert(base->type == SDL_HAPTIC_LEFTRIGHT); /* should catch this at higher level */ return SDL_XINPUT_HapticUpdateEffect(haptic, effect, base); } int SDL_XINPUT_HapticUpdateEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * data) { XINPUT_VIBRATION *vib = &effect->hweffect->vibration; SDL_assert(data->type == SDL_HAPTIC_LEFTRIGHT); /* SDL_HapticEffect has max magnitude of 32767, XInput expects 65535 max, so multiply */ vib->wLeftMotorSpeed = data->leftright.large_magnitude * 2; vib->wRightMotorSpeed = data->leftright.small_magnitude * 2; SDL_LockMutex(haptic->hwdata->mutex); if (haptic->hwdata->stopTicks) { /* running right now? Update it. */ XINPUTSETSTATE(haptic->hwdata->userid, vib); } SDL_UnlockMutex(haptic->hwdata->mutex); return 0; } int SDL_XINPUT_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect *effect, Uint32 iterations) { XINPUT_VIBRATION *vib = &effect->hweffect->vibration; SDL_assert(effect->effect.type == SDL_HAPTIC_LEFTRIGHT); /* should catch this at higher level */ SDL_LockMutex(haptic->hwdata->mutex); if (effect->effect.leftright.length == SDL_HAPTIC_INFINITY || iterations == SDL_HAPTIC_INFINITY) { haptic->hwdata->stopTicks = SDL_HAPTIC_INFINITY; } else if ((!effect->effect.leftright.length) || (!iterations)) { /* do nothing. Effect runs for zero milliseconds. */ } else { haptic->hwdata->stopTicks = SDL_GetTicks() + (effect->effect.leftright.length * iterations); if ((haptic->hwdata->stopTicks == SDL_HAPTIC_INFINITY) || (haptic->hwdata->stopTicks == 0)) { haptic->hwdata->stopTicks = 1; /* fix edge cases. */ } } SDL_UnlockMutex(haptic->hwdata->mutex); return (XINPUTSETSTATE(haptic->hwdata->userid, vib) == ERROR_SUCCESS) ? 0 : -1; } int SDL_XINPUT_HapticStopEffect(SDL_Haptic * haptic, struct haptic_effect *effect) { XINPUT_VIBRATION vibration = { 0, 0 }; SDL_LockMutex(haptic->hwdata->mutex); haptic->hwdata->stopTicks = 0; SDL_UnlockMutex(haptic->hwdata->mutex); return (XINPUTSETSTATE(haptic->hwdata->userid, &vibration) == ERROR_SUCCESS) ? 0 : -1; } void SDL_XINPUT_HapticDestroyEffect(SDL_Haptic * haptic, struct haptic_effect *effect) { SDL_XINPUT_HapticStopEffect(haptic, effect); } int SDL_XINPUT_HapticGetEffectStatus(SDL_Haptic * haptic, struct haptic_effect *effect) { return SDL_Unsupported(); } int SDL_XINPUT_HapticSetGain(SDL_Haptic * haptic, int gain) { return SDL_Unsupported(); } int SDL_XINPUT_HapticSetAutocenter(SDL_Haptic * haptic, int autocenter) { return SDL_Unsupported(); } int SDL_XINPUT_HapticPause(SDL_Haptic * haptic) { return SDL_Unsupported(); } int SDL_XINPUT_HapticUnpause(SDL_Haptic * haptic) { return SDL_Unsupported(); } int SDL_XINPUT_HapticStopAll(SDL_Haptic * haptic) { XINPUT_VIBRATION vibration = { 0, 0 }; SDL_LockMutex(haptic->hwdata->mutex); haptic->hwdata->stopTicks = 0; SDL_UnlockMutex(haptic->hwdata->mutex); return (XINPUTSETSTATE(haptic->hwdata->userid, &vibration) == ERROR_SUCCESS) ? 0 : -1; } #else /* !SDL_HAPTIC_XINPUT */ #include "../../core/windows/SDL_windows.h" typedef struct SDL_hapticlist_item SDL_hapticlist_item; int SDL_XINPUT_HapticInit(void) { return 0; } int SDL_XINPUT_MaybeAddDevice(const DWORD dwUserid) { return SDL_Unsupported(); } int SDL_XINPUT_MaybeRemoveDevice(const DWORD dwUserid) { return SDL_Unsupported(); } int SDL_XINPUT_HapticOpen(SDL_Haptic * haptic, SDL_hapticlist_item *item) { return SDL_Unsupported(); } int SDL_XINPUT_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick) { return SDL_Unsupported(); } int SDL_XINPUT_HapticOpenFromJoystick(SDL_Haptic * haptic, SDL_Joystick * joystick) { return SDL_Unsupported(); } void SDL_XINPUT_HapticClose(SDL_Haptic * haptic) { } void SDL_XINPUT_HapticQuit(void) { } int SDL_XINPUT_HapticNewEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * base) { return SDL_Unsupported(); } int SDL_XINPUT_HapticUpdateEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * data) { return SDL_Unsupported(); } int SDL_XINPUT_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect *effect, Uint32 iterations) { return SDL_Unsupported(); } int SDL_XINPUT_HapticStopEffect(SDL_Haptic * haptic, struct haptic_effect *effect) { return SDL_Unsupported(); } void SDL_XINPUT_HapticDestroyEffect(SDL_Haptic * haptic, struct haptic_effect *effect) { } int SDL_XINPUT_HapticGetEffectStatus(SDL_Haptic * haptic, struct haptic_effect *effect) { return SDL_Unsupported(); } int SDL_XINPUT_HapticSetGain(SDL_Haptic * haptic, int gain) { return SDL_Unsupported(); } int SDL_XINPUT_HapticSetAutocenter(SDL_Haptic * haptic, int autocenter) { return SDL_Unsupported(); } int SDL_XINPUT_HapticPause(SDL_Haptic * haptic) { return SDL_Unsupported(); } int SDL_XINPUT_HapticUnpause(SDL_Haptic * haptic) { return SDL_Unsupported(); } int SDL_XINPUT_HapticStopAll(SDL_Haptic * haptic) { return SDL_Unsupported(); } #endif /* SDL_HAPTIC_XINPUT */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/haptic/windows/SDL_xinputhaptic.c
C
apache-2.0
13,329
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #include "SDL_haptic.h" #include "SDL_windowshaptic_c.h" extern int SDL_XINPUT_HapticInit(void); extern int SDL_XINPUT_MaybeAddDevice(const DWORD dwUserid); extern int SDL_XINPUT_MaybeRemoveDevice(const DWORD dwUserid); extern int SDL_XINPUT_HapticOpen(SDL_Haptic * haptic, SDL_hapticlist_item *item); extern int SDL_XINPUT_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick); extern int SDL_XINPUT_HapticOpenFromJoystick(SDL_Haptic * haptic, SDL_Joystick * joystick); extern void SDL_XINPUT_HapticClose(SDL_Haptic * haptic); extern void SDL_XINPUT_HapticQuit(void); extern int SDL_XINPUT_HapticNewEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * base); extern int SDL_XINPUT_HapticUpdateEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * data); extern int SDL_XINPUT_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect *effect, Uint32 iterations); extern int SDL_XINPUT_HapticStopEffect(SDL_Haptic * haptic, struct haptic_effect *effect); extern void SDL_XINPUT_HapticDestroyEffect(SDL_Haptic * haptic, struct haptic_effect *effect); extern int SDL_XINPUT_HapticGetEffectStatus(SDL_Haptic * haptic, struct haptic_effect *effect); extern int SDL_XINPUT_HapticSetGain(SDL_Haptic * haptic, int gain); extern int SDL_XINPUT_HapticSetAutocenter(SDL_Haptic * haptic, int autocenter); extern int SDL_XINPUT_HapticPause(SDL_Haptic * haptic); extern int SDL_XINPUT_HapticUnpause(SDL_Haptic * haptic); extern int SDL_XINPUT_HapticStopAll(SDL_Haptic * haptic); /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/haptic/windows/SDL_xinputhaptic_c.h
C
apache-2.0
2,534
ACLOCAL_AMFLAGS = -I m4 if OS_FREEBSD pkgconfigdir=$(prefix)/libdata/pkgconfig else pkgconfigdir=$(libdir)/pkgconfig endif if OS_LINUX pkgconfig_DATA=pc/hidapi-hidraw.pc pc/hidapi-libusb.pc else pkgconfig_DATA=pc/hidapi.pc endif SUBDIRS= if OS_LINUX SUBDIRS += linux libusb endif if OS_DARWIN SUBDIRS += mac endif if OS_IOS SUBDIRS += ios endif if OS_FREEBSD SUBDIRS += libusb endif if OS_KFREEBSD SUBDIRS += libusb endif if OS_WINDOWS SUBDIRS += windows endif SUBDIRS += hidtest if BUILD_TESTGUI SUBDIRS += testgui endif EXTRA_DIST = udev doxygen dist_doc_DATA = \ README.txt \ AUTHORS.txt \ LICENSE-bsd.txt \ LICENSE-gpl3.txt \ LICENSE-orig.txt \ LICENSE.txt SCMCLEAN_TARGETS= \ aclocal.m4 \ config.guess \ config.sub \ configure \ config.h.in \ depcomp \ install-sh \ ltmain.sh \ missing \ mac/Makefile.in \ testgui/Makefile.in \ libusb/Makefile.in \ Makefile.in \ linux/Makefile.in \ windows/Makefile.in \ m4/libtool.m4 \ m4/lt~obsolete.m4 \ m4/ltoptions.m4 \ m4/ltsugar.m4 \ m4/ltversion.m4 SCMCLEAN_DIR_TARGETS = \ autom4te.cache scm-clean: distclean rm -f $(SCMCLEAN_TARGETS) rm -Rf $(SCMCLEAN_DIR_TARGETS)
YifuLiu/AliOS-Things
components/SDL2/src/hidapi/Makefile.am
Makefile
apache-2.0
1,160
/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. Alan Ott Signal 11 Software 8/22/2009 Copyright 2009, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: https://github.com/libusb/hidapi . ********************************************************/ /** @file * @defgroup API hidapi API */ #ifndef HIDAPI_H__ #define HIDAPI_H__ #include <wchar.h> #if defined(_WIN32) && !defined(NAMESPACE) && (0) /* SDL: don't export hidapi syms */ #define HID_API_EXPORT __declspec(dllexport) #define HID_API_CALL #else #ifndef HID_API_EXPORT #define HID_API_EXPORT /**< API export macro */ #endif #ifndef HID_API_CALL #define HID_API_CALL /**< API call macro */ #endif #endif #define HID_API_EXPORT_CALL HID_API_EXPORT HID_API_CALL /**< API export and call macro*/ #if defined(__cplusplus) && !defined(NAMESPACE) extern "C" { #endif #ifdef NAMESPACE namespace NAMESPACE { #endif struct hid_device_; typedef struct hid_device_ hid_device; /**< opaque hidapi structure */ /** hidapi info structure */ struct hid_device_info { /** Platform-specific device path */ char *path; /** Device Vendor ID */ unsigned short vendor_id; /** Device Product ID */ unsigned short product_id; /** Serial Number */ wchar_t *serial_number; /** Device Release Number in binary-coded decimal, also known as Device Version Number */ unsigned short release_number; /** Manufacturer String */ wchar_t *manufacturer_string; /** Product string */ wchar_t *product_string; /** Usage Page for this Device/Interface (Windows/Mac only). */ unsigned short usage_page; /** Usage for this Device/Interface (Windows/Mac only).*/ unsigned short usage; /** The USB interface which this logical device represents. Valid on both Linux implementations in all cases, and valid on the Windows implementation only if the device contains more than one interface. */ int interface_number; /** Additional information about the USB interface. Valid on libusb and Android implementations. */ int interface_class; int interface_subclass; int interface_protocol; /** Pointer to the next device */ struct hid_device_info *next; }; /** @brief Initialize the HIDAPI library. This function initializes the HIDAPI library. Calling it is not strictly necessary, as it will be called automatically by hid_enumerate() and any of the hid_open_*() functions if it is needed. This function should be called at the beginning of execution however, if there is a chance of HIDAPI handles being opened by different threads simultaneously. @ingroup API @returns This function returns 0 on success and -1 on error. */ int HID_API_EXPORT HID_API_CALL hid_init(void); /** @brief Finalize the HIDAPI library. This function frees all of the static data associated with HIDAPI. It should be called at the end of execution to avoid memory leaks. @ingroup API @returns This function returns 0 on success and -1 on error. */ int HID_API_EXPORT HID_API_CALL hid_exit(void); /** @brief Enumerate the HID Devices. This function returns a linked list of all the HID devices attached to the system which match vendor_id and product_id. If @p vendor_id is set to 0 then any vendor matches. If @p product_id is set to 0 then any product matches. If @p vendor_id and @p product_id are both set to 0, then all HID devices will be returned. @ingroup API @param vendor_id The Vendor ID (VID) of the types of device to open. @param product_id The Product ID (PID) of the types of device to open. @returns This function returns a pointer to a linked list of type struct #hid_device, containing information about the HID devices attached to the system, or NULL in the case of failure. Free this linked list by calling hid_free_enumeration(). */ struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id); /** @brief Free an enumeration Linked List This function frees a linked list created by hid_enumerate(). @ingroup API @param devs Pointer to a list of struct_device returned from hid_enumerate(). */ void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs); /** @brief Open a HID device using a Vendor ID (VID), Product ID (PID) and optionally a serial number. If @p serial_number is NULL, the first device with the specified VID and PID is opened. @ingroup API @param vendor_id The Vendor ID (VID) of the device to open. @param product_id The Product ID (PID) of the device to open. @param serial_number The Serial Number of the device to open (Optionally NULL). @returns This function returns a pointer to a #hid_device object on success or NULL on failure. */ HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number); /** @brief Open a HID device by its path name. The path name be determined by calling hid_enumerate(), or a platform-specific path name can be used (eg: /dev/hidraw0 on Linux). @ingroup API @param path The path name of the device to open @returns This function returns a pointer to a #hid_device object on success or NULL on failure. */ HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path, int bExclusive /* = false */); /** @brief Write an Output report to a HID device. The first byte of @p data[] must contain the Report ID. For devices which only support a single report, this must be set to 0x0. The remaining bytes contain the report data. Since the Report ID is mandatory, calls to hid_write() will always contain one more byte than the report contains. For example, if a hid report is 16 bytes long, 17 bytes must be passed to hid_write(), the Report ID (or 0x0, for devices with a single report), followed by the report data (16 bytes). In this example, the length passed in would be 17. hid_write() will send the data on the first OUT endpoint, if one exists. If it does not, it will send the data through the Control Endpoint (Endpoint 0). @ingroup API @param device A device handle returned from hid_open(). @param data The data to send, including the report number as the first byte. @param length The length in bytes of the data to send. @returns This function returns the actual number of bytes written and -1 on error. */ int HID_API_EXPORT HID_API_CALL hid_write(hid_device *device, const unsigned char *data, size_t length); /** @brief Read an Input report from a HID device with timeout. Input reports are returned to the host through the INTERRUPT IN endpoint. The first byte will contain the Report number if the device uses numbered reports. @ingroup API @param device A device handle returned from hid_open(). @param data A buffer to put the read data into. @param length The number of bytes to read. For devices with multiple reports, make sure to read an extra byte for the report number. @param milliseconds timeout in milliseconds or -1 for blocking wait. @returns This function returns the actual number of bytes read and -1 on error. If no packet was available to be read within the timeout period, this function returns 0. */ int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *device, unsigned char *data, size_t length, int milliseconds); /** @brief Read an Input report from a HID device. Input reports are returned to the host through the INTERRUPT IN endpoint. The first byte will contain the Report number if the device uses numbered reports. @ingroup API @param device A device handle returned from hid_open(). @param data A buffer to put the read data into. @param length The number of bytes to read. For devices with multiple reports, make sure to read an extra byte for the report number. @returns This function returns the actual number of bytes read and -1 on error. If no packet was available to be read and the handle is in non-blocking mode, this function returns 0. */ int HID_API_EXPORT HID_API_CALL hid_read(hid_device *device, unsigned char *data, size_t length); /** @brief Set the device handle to be non-blocking. In non-blocking mode calls to hid_read() will return immediately with a value of 0 if there is no data to be read. In blocking mode, hid_read() will wait (block) until there is data to read before returning. Nonblocking can be turned on and off at any time. @ingroup API @param device A device handle returned from hid_open(). @param nonblock enable or not the nonblocking reads - 1 to enable nonblocking - 0 to disable nonblocking. @returns This function returns 0 on success and -1 on error. */ int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *device, int nonblock); /** @brief Send a Feature report to the device. Feature reports are sent over the Control endpoint as a Set_Report transfer. The first byte of @p data[] must contain the Report ID. For devices which only support a single report, this must be set to 0x0. The remaining bytes contain the report data. Since the Report ID is mandatory, calls to hid_send_feature_report() will always contain one more byte than the report contains. For example, if a hid report is 16 bytes long, 17 bytes must be passed to hid_send_feature_report(): the Report ID (or 0x0, for devices which do not use numbered reports), followed by the report data (16 bytes). In this example, the length passed in would be 17. @ingroup API @param device A device handle returned from hid_open(). @param data The data to send, including the report number as the first byte. @param length The length in bytes of the data to send, including the report number. @returns This function returns the actual number of bytes written and -1 on error. */ int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *device, const unsigned char *data, size_t length); /** @brief Get a feature report from a HID device. Set the first byte of @p data[] to the Report ID of the report to be read. Make sure to allow space for this extra byte in @p data[]. Upon return, the first byte will still contain the Report ID, and the report data will start in data[1]. @ingroup API @param device A device handle returned from hid_open(). @param data A buffer to put the read data into, including the Report ID. Set the first byte of @p data[] to the Report ID of the report to be read, or set it to zero if your device does not use numbered reports. @param length The number of bytes to read, including an extra byte for the report ID. The buffer can be longer than the actual report. @returns This function returns the number of bytes read plus one for the report ID (which is still in the first byte), or -1 on error. */ int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *device, unsigned char *data, size_t length); /** @brief Close a HID device. @ingroup API @param device A device handle returned from hid_open(). */ void HID_API_EXPORT HID_API_CALL hid_close(hid_device *device); /** @brief Get The Manufacturer String from a HID device. @ingroup API @param device A device handle returned from hid_open(). @param string A wide string buffer to put the data into. @param maxlen The length of the buffer in multiples of wchar_t. @returns This function returns 0 on success and -1 on error. */ int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen); /** @brief Get The Product String from a HID device. @ingroup API @param device A device handle returned from hid_open(). @param string A wide string buffer to put the data into. @param maxlen The length of the buffer in multiples of wchar_t. @returns This function returns 0 on success and -1 on error. */ int HID_API_EXPORT_CALL hid_get_product_string(hid_device *device, wchar_t *string, size_t maxlen); /** @brief Get The Serial Number String from a HID device. @ingroup API @param device A device handle returned from hid_open(). @param string A wide string buffer to put the data into. @param maxlen The length of the buffer in multiples of wchar_t. @returns This function returns 0 on success and -1 on error. */ int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *device, wchar_t *string, size_t maxlen); /** @brief Get a string from a HID device, based on its string index. @ingroup API @param device A device handle returned from hid_open(). @param string_index The index of the string to get. @param string A wide string buffer to put the data into. @param maxlen The length of the buffer in multiples of wchar_t. @returns This function returns 0 on success and -1 on error. */ int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *device, int string_index, wchar_t *string, size_t maxlen); /** @brief Get a string describing the last error which occurred. @ingroup API @param device A device handle returned from hid_open(). @returns This function returns a string containing the last error which occurred or NULL if none has occurred. */ HID_API_EXPORT const wchar_t* HID_API_CALL hid_error(hid_device *device); #if defined(__cplusplus) && !defined(NAMESPACE) } #endif #ifdef NAMESPACE } #endif #endif
YifuLiu/AliOS-Things
components/SDL2/src/hidapi/hidapi/hidapi.h
C++
apache-2.0
14,352
SDL_IMAGE_LOCAL_PATH := $(call my-dir) # Enable this if you want to support loading JPEG images # The library path should be a relative path to this directory. SUPPORT_JPG ?= true JPG_LIBRARY_PATH := external/jpeg-9b # Enable this if you want to support loading PNG images # The library path should be a relative path to this directory. SUPPORT_PNG ?= true PNG_LIBRARY_PATH := external/libpng-1.6.37 # Enable this if you want to support loading WebP images # The library path should be a relative path to this directory. SUPPORT_WEBP ?= true WEBP_LIBRARY_PATH := external/libwebp-1.0.2 # Build the library ifeq ($(SUPPORT_JPG),true) include $(SDL_IMAGE_LOCAL_PATH)/$(JPG_LIBRARY_PATH)/Android.mk endif # Build the library ifeq ($(SUPPORT_PNG),true) include $(SDL_IMAGE_LOCAL_PATH)/$(PNG_LIBRARY_PATH)/Android.mk endif # Build the library ifeq ($(SUPPORT_WEBP),true) include $(SDL_IMAGE_LOCAL_PATH)/$(WEBP_LIBRARY_PATH)/Android.mk endif # Restore local path LOCAL_PATH := $(SDL_IMAGE_LOCAL_PATH) include $(CLEAR_VARS) LOCAL_MODULE := SDL2_image LOCAL_SRC_FILES := \ IMG.c \ IMG_bmp.c \ IMG_gif.c \ IMG_jpg.c \ IMG_lbm.c \ IMG_pcx.c \ IMG_png.c \ IMG_pnm.c \ IMG_svg.c \ IMG_tga.c \ IMG_tif.c \ IMG_webp.c \ IMG_WIC.c \ IMG_xcf.c \ IMG_xpm.c.arm \ IMG_xv.c \ IMG_xxx.c LOCAL_CFLAGS := -DLOAD_BMP -DLOAD_GIF -DLOAD_LBM -DLOAD_PCX -DLOAD_PNM \ -DLOAD_SVG -DLOAD_TGA -DLOAD_XCF -DLOAD_XPM -DLOAD_XV LOCAL_LDLIBS := LOCAL_STATIC_LIBRARIES := LOCAL_SHARED_LIBRARIES := SDL2 ifeq ($(SUPPORT_JPG),true) LOCAL_C_INCLUDES += $(LOCAL_PATH)/$(JPG_LIBRARY_PATH) LOCAL_CFLAGS += -DLOAD_JPG LOCAL_STATIC_LIBRARIES += jpeg endif ifeq ($(SUPPORT_PNG),true) LOCAL_C_INCLUDES += $(LOCAL_PATH)/$(PNG_LIBRARY_PATH) LOCAL_CFLAGS += -DLOAD_PNG LOCAL_STATIC_LIBRARIES += png LOCAL_LDLIBS += -lz endif ifeq ($(SUPPORT_WEBP),true) LOCAL_C_INCLUDES += $(LOCAL_PATH)/$(WEBP_LIBRARY_PATH)/src LOCAL_CFLAGS += -DLOAD_WEBP LOCAL_STATIC_LIBRARIES += webp endif LOCAL_EXPORT_C_INCLUDES += $(LOCAL_PATH) include $(BUILD_SHARED_LIBRARY)
YifuLiu/AliOS-Things
components/SDL2/src/image/Android.mk
Makefile
apache-2.0
2,253
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* A simple library to load images of various formats as SDL surfaces */ #include "SDL_image.h" #ifdef __EMSCRIPTEN__ #include <emscripten/emscripten.h> #endif #define ARRAYSIZE(a) (sizeof(a) / sizeof((a)[0])) /* Table of image detection and loading functions */ static struct { const char *type; int (SDLCALL *is)(SDL_RWops *src); SDL_Surface *(SDLCALL *load)(SDL_RWops *src); } supported[] = { /* keep magicless formats first */ { "TGA", NULL, IMG_LoadTGA_RW }, { "CUR", IMG_isCUR, IMG_LoadCUR_RW }, { "ICO", IMG_isICO, IMG_LoadICO_RW }, { "BMP", IMG_isBMP, IMG_LoadBMP_RW }, { "GIF", IMG_isGIF, IMG_LoadGIF_RW }, { "JPG", IMG_isJPG, IMG_LoadJPG_RW }, { "LBM", IMG_isLBM, IMG_LoadLBM_RW }, { "PCX", IMG_isPCX, IMG_LoadPCX_RW }, { "PNG", IMG_isPNG, IMG_LoadPNG_RW }, { "PNM", IMG_isPNM, IMG_LoadPNM_RW }, /* P[BGP]M share code */ { "SVG", IMG_isSVG, IMG_LoadSVG_RW }, { "TIF", IMG_isTIF, IMG_LoadTIF_RW }, { "XCF", IMG_isXCF, IMG_LoadXCF_RW }, { "XPM", IMG_isXPM, IMG_LoadXPM_RW }, { "XV", IMG_isXV, IMG_LoadXV_RW }, { "WEBP", IMG_isWEBP, IMG_LoadWEBP_RW }, }; const SDL_version *IMG_Linked_Version(void) { static SDL_version linked_version; SDL_IMAGE_VERSION(&linked_version); return(&linked_version); } extern int IMG_InitJPG(void); extern void IMG_QuitJPG(void); extern int IMG_InitPNG(void); extern void IMG_QuitPNG(void); extern int IMG_InitTIF(void); extern void IMG_QuitTIF(void); extern int IMG_InitWEBP(void); extern void IMG_QuitWEBP(void); static int initialized = 0; int IMG_Init(int flags) { int result = 0; /* Passing 0 returns the currently initialized loaders */ if (!flags) { return initialized; } if (flags & IMG_INIT_JPG) { if ((initialized & IMG_INIT_JPG) || IMG_InitJPG() == 0) { result |= IMG_INIT_JPG; } } if (flags & IMG_INIT_PNG) { if ((initialized & IMG_INIT_PNG) || IMG_InitPNG() == 0) { result |= IMG_INIT_PNG; } } if (flags & IMG_INIT_TIF) { if ((initialized & IMG_INIT_TIF) || IMG_InitTIF() == 0) { result |= IMG_INIT_TIF; } } if (flags & IMG_INIT_WEBP) { if ((initialized & IMG_INIT_WEBP) || IMG_InitWEBP() == 0) { result |= IMG_INIT_WEBP; } } initialized |= result; return result; } void IMG_Quit() { if (initialized & IMG_INIT_JPG) { IMG_QuitJPG(); } if (initialized & IMG_INIT_PNG) { IMG_QuitPNG(); } if (initialized & IMG_INIT_TIF) { IMG_QuitTIF(); } if (initialized & IMG_INIT_WEBP) { IMG_QuitWEBP(); } initialized = 0; } #if !defined(__APPLE__) || defined(SDL_IMAGE_USE_COMMON_BACKEND) /* Load an image from a file */ SDL_Surface *IMG_Load(const char *file) { #if __EMSCRIPTEN__ int w, h; char *data; SDL_Surface *surf; data = emscripten_get_preloaded_image_data(file, &w, &h); if (data != NULL) { surf = SDL_CreateRGBSurface(0, w, h, 32, 0xFF, 0xFF00, 0xFF0000, 0xFF000000); if (surf != NULL) { memcpy(surf->pixels, data, w * h * 4); } free(data); return surf; } #endif SDL_RWops *src = SDL_RWFromFile(file, "rb"); const char *ext = SDL_strrchr(file, '.'); if(ext) { ext++; } if(!src) { /* The error message has been set in SDL_RWFromFile */ return NULL; } return IMG_LoadTyped_RW(src, 1, ext); } #endif /* Load an image from an SDL datasource (for compatibility) */ SDL_Surface *IMG_Load_RW(SDL_RWops *src, int freesrc) { return IMG_LoadTyped_RW(src, freesrc, NULL); } /* Portable case-insensitive string compare function */ static int IMG_string_equals(const char *str1, const char *str2) { while ( *str1 && *str2 ) { if ( SDL_toupper((unsigned char)*str1) != SDL_toupper((unsigned char)*str2) ) break; ++str1; ++str2; } return (!*str1 && !*str2); } /* Load an image from an SDL datasource, optionally specifying the type */ SDL_Surface *IMG_LoadTyped_RW(SDL_RWops *src, int freesrc, const char *type) { int i; SDL_Surface *image; /* Make sure there is something to do.. */ if ( src == NULL ) { IMG_SetError("Passed a NULL data source"); return(NULL); } /* See whether or not this data source can handle seeking */ if ( SDL_RWseek(src, 0, RW_SEEK_CUR) < 0 ) { IMG_SetError("Can't seek in this data source"); if(freesrc) SDL_RWclose(src); return(NULL); } #ifdef __EMSCRIPTEN__ /*load through preloadedImages*/ if ( src->type == SDL_RWOPS_STDFILE ) { int w, h, success; char *data; SDL_Surface *surf; data = emscripten_get_preloaded_image_data_from_FILE(src->hidden.stdio.fp, &w, &h); if(data) { surf = SDL_CreateRGBSurface(0, w, h, 32, 0xFF, 0xFF00, 0xFF0000, 0xFF000000); if (surf != NULL) { memcpy(surf->pixels, data, w * h * 4); } free(data); if(freesrc) SDL_RWclose(src); /* If SDL_CreateRGBSurface returns NULL, it has set the error message for us */ return surf; } } #endif /* Detect the type of image being loaded */ image = NULL; for ( i=0; i < ARRAYSIZE(supported); ++i ) { if(supported[i].is) { if(!supported[i].is(src)) continue; } else { /* magicless format */ if(!type || !IMG_string_equals(type, supported[i].type)) continue; } #ifdef DEBUG_IMGLIB fprintf(stderr, "IMGLIB: Loading image as %s\n", supported[i].type); #endif long long start = aos_now_ms(); image = supported[i].load(src); printf("load image duration %d ms\n", (int)(aos_now_ms() - start)); if(freesrc) SDL_RWclose(src); return image; } if ( freesrc ) { SDL_RWclose(src); } IMG_SetError("Unsupported image format"); return NULL; } #if SDL_VERSION_ATLEAST(2,0,0) SDL_Texture *IMG_LoadTexture(SDL_Renderer *renderer, const char *file) { SDL_Texture *texture = NULL; SDL_Surface *surface = IMG_Load(file); if (surface) { texture = SDL_CreateTextureFromSurface(renderer, surface); SDL_FreeSurface(surface); } return texture; } SDL_Texture *IMG_LoadTexture_RW(SDL_Renderer *renderer, SDL_RWops *src, int freesrc) { SDL_Texture *texture = NULL; SDL_Surface *surface = IMG_Load_RW(src, freesrc); if (surface) { texture = SDL_CreateTextureFromSurface(renderer, surface); SDL_FreeSurface(surface); } return texture; } SDL_Texture *IMG_LoadTextureTyped_RW(SDL_Renderer *renderer, SDL_RWops *src, int freesrc, const char *type) { SDL_Texture *texture = NULL; SDL_Surface *surface = IMG_LoadTyped_RW(src, freesrc, type); if (surface) { texture = SDL_CreateTextureFromSurface(renderer, surface); SDL_FreeSurface(surface); } return texture; } #endif /* SDL 2.0 */
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG.c
C
apache-2.0
8,210
/* * IMG_ImageIO.c * SDL_image * * Created by Eric Wing on 1/1/09. * Copyright 2009 __MyCompanyName__. All rights reserved. * */ #if defined(__APPLE__) && !defined(SDL_IMAGE_USE_COMMON_BACKEND) #include "SDL_image.h" // Used because CGDataProviderCreate became deprecated in 10.5 #include <AvailabilityMacros.h> #include <TargetConditionals.h> #include <Foundation/Foundation.h> #if (TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1) #ifdef ALLOW_UIIMAGE_FALLBACK #define USE_UIIMAGE_BACKEND() ([UIImage instancesRespondToSelector:@selector(initWithCGImage:scale:orientation:)] == NO) #else #define USE_UIIMAGE_BACKEND() (Internal_checkImageIOisAvailable()) #endif #import <MobileCoreServices/MobileCoreServices.h> // for UTCoreTypes.h #import <ImageIO/ImageIO.h> #import <UIKit/UIImage.h> #else // For ImageIO framework and also LaunchServices framework (for UTIs) #include <ApplicationServices/ApplicationServices.h> #endif /************************************************************** ***** Begin Callback functions for block reading ************* **************************************************************/ // This callback reads some bytes from an SDL_rwops and copies it // to a Quartz buffer (supplied by Apple framework). static size_t MyProviderGetBytesCallback(void* rwops_userdata, void* quartz_buffer, size_t the_count) { return (size_t)SDL_RWread((struct SDL_RWops *)rwops_userdata, quartz_buffer, 1, the_count); } // This callback is triggered when the data provider is released // so you can clean up any resources. static void MyProviderReleaseInfoCallback(void* rwops_userdata) { // What should I put here? // I think the user and SDL_RWops controls closing, so I don't do anything. } static void MyProviderRewindCallback(void* rwops_userdata) { SDL_RWseek((struct SDL_RWops *)rwops_userdata, 0, RW_SEEK_SET); } #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1050 // CGDataProviderCreateSequential was introduced in 10.5; CGDataProviderCreate is deprecated off_t MyProviderSkipForwardBytesCallback(void* rwops_userdata, off_t the_count) { off_t start_position = SDL_RWtell((struct SDL_RWops *)rwops_userdata); SDL_RWseek((struct SDL_RWops *)rwops_userdata, the_count, RW_SEEK_CUR); off_t end_position = SDL_RWtell((struct SDL_RWops *)rwops_userdata); return (end_position - start_position); } #else // CGDataProviderCreate was deprecated in 10.5 static void MyProviderSkipBytesCallback(void* rwops_userdata, size_t the_count) { SDL_RWseek((struct SDL_RWops *)rwops_userdata, the_count, RW_SEEK_CUR); } #endif /************************************************************** ***** End Callback functions for block reading *************** **************************************************************/ // This creates a CGImageSourceRef which is a handle to an image that can be used to examine information // about the image or load the actual image data. static CGImageSourceRef CreateCGImageSourceFromRWops(SDL_RWops* rw_ops, CFDictionaryRef hints_and_options) { CGImageSourceRef source_ref; // Similar to SDL_RWops, Apple has their own callbacks for dealing with data streams. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1050 // CGDataProviderCreateSequential was introduced in 10.5; CGDataProviderCreate is deprecated CGDataProviderSequentialCallbacks provider_callbacks = { 0, MyProviderGetBytesCallback, MyProviderSkipForwardBytesCallback, MyProviderRewindCallback, MyProviderReleaseInfoCallback }; CGDataProviderRef data_provider = CGDataProviderCreateSequential(rw_ops, &provider_callbacks); #else // CGDataProviderCreate was deprecated in 10.5 CGDataProviderCallbacks provider_callbacks = { MyProviderGetBytesCallback, MyProviderSkipBytesCallback, MyProviderRewindCallback, MyProviderReleaseInfoCallback }; CGDataProviderRef data_provider = CGDataProviderCreate(rw_ops, &provider_callbacks); #endif // Get the CGImageSourceRef. // The dictionary can be NULL or contain hints to help ImageIO figure out the image type. source_ref = CGImageSourceCreateWithDataProvider(data_provider, hints_and_options); CGDataProviderRelease(data_provider); return source_ref; } /* Create a CGImageSourceRef from a file. */ /* Remember to CFRelease the created source when done. */ static CGImageSourceRef CreateCGImageSourceFromFile(const char* the_path) { CFURLRef the_url = NULL; CGImageSourceRef source_ref = NULL; CFStringRef cf_string = NULL; /* Create a CFString from a C string */ cf_string = CFStringCreateWithCString(NULL, the_path, kCFStringEncodingUTF8); if (!cf_string) { return NULL; } /* Create a CFURL from a CFString */ the_url = CFURLCreateWithFileSystemPath(NULL, cf_string, kCFURLPOSIXPathStyle, false); /* Don't need the CFString any more (error or not) */ CFRelease(cf_string); if(!the_url) { return NULL; } source_ref = CGImageSourceCreateWithURL(the_url, NULL); /* Don't need the URL any more (error or not) */ CFRelease(the_url); return source_ref; } static CGImageRef CreateCGImageFromCGImageSource(CGImageSourceRef image_source) { CGImageRef image_ref = NULL; if(NULL == image_source) { return NULL; } // Get the first item in the image source (some image formats may // contain multiple items). image_ref = CGImageSourceCreateImageAtIndex(image_source, 0, NULL); if(NULL == image_ref) { IMG_SetError("CGImageSourceCreateImageAtIndex() failed"); } return image_ref; } static CFDictionaryRef CreateHintDictionary(CFStringRef uti_string_hint) { CFDictionaryRef hint_dictionary = NULL; if(uti_string_hint != NULL) { // Do a bunch of work to setup a CFDictionary containing the jpeg compression properties. CFStringRef the_keys[1]; CFStringRef the_values[1]; the_keys[0] = kCGImageSourceTypeIdentifierHint; the_values[0] = uti_string_hint; // kCFTypeDictionaryKeyCallBacks or kCFCopyStringDictionaryKeyCallBacks? hint_dictionary = CFDictionaryCreate(NULL, (const void**)&the_keys, (const void**)&the_values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } return hint_dictionary; } // Once we have our image, we need to get it into an SDL_Surface static SDL_Surface* Create_SDL_Surface_From_CGImage_RGB(CGImageRef image_ref) { /* This code is adapted from Apple's Documentation found here: * http://developer.apple.com/documentation/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/index.html * Listing 9-4††Using a Quartz image as a texture source. * Unfortunately, this guide doesn't show what to do about * non-RGBA image formats so I'm making the rest up. * All this code should be scrutinized. */ size_t w = CGImageGetWidth(image_ref); size_t h = CGImageGetHeight(image_ref); CGRect rect = {{0, 0}, {w, h}}; CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image_ref); //size_t bits_per_pixel = CGImageGetBitsPerPixel(image_ref); size_t bits_per_component = 8; SDL_Surface* surface; Uint32 Amask; Uint32 Rmask; Uint32 Gmask; Uint32 Bmask; CGContextRef bitmap_context; CGBitmapInfo bitmap_info; CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB(); if (alpha == kCGImageAlphaNone || alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast) { bitmap_info = kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host; /* XRGB */ Amask = 0x00000000; } else { /* kCGImageAlphaFirst isn't supported */ //bitmap_info = kCGImageAlphaFirst | kCGBitmapByteOrder32Host; /* ARGB */ bitmap_info = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host; /* ARGB */ Amask = 0xFF000000; } Rmask = 0x00FF0000; Gmask = 0x0000FF00; Bmask = 0x000000FF; surface = SDL_CreateRGBSurface(SDL_SWSURFACE, (int)w, (int)h, 32, Rmask, Gmask, Bmask, Amask); if (surface) { // Sets up a context to be drawn to with surface->pixels as the area to be drawn to bitmap_context = CGBitmapContextCreate( surface->pixels, surface->w, surface->h, bits_per_component, surface->pitch, color_space, bitmap_info ); // Draws the image into the context's image_data CGContextDrawImage(bitmap_context, rect, image_ref); CGContextRelease(bitmap_context); // FIXME: Reverse the premultiplied alpha if ((bitmap_info & kCGBitmapAlphaInfoMask) == kCGImageAlphaPremultipliedFirst) { int i, j; Uint8 *p = (Uint8 *)surface->pixels; for (i = surface->h * surface->pitch/4; i--; ) { #if __LITTLE_ENDIAN__ Uint8 A = p[3]; if (A) { for (j = 0; j < 3; ++j) { p[j] = (p[j] * 255) / A; } } #else Uint8 A = p[0]; if (A) { for (j = 1; j < 4; ++j) { p[j] = (p[j] * 255) / A; } } #endif /* ENDIAN */ p += 4; } } } if (color_space) { CGColorSpaceRelease(color_space); } return surface; } static SDL_Surface* Create_SDL_Surface_From_CGImage_Index(CGImageRef image_ref) { size_t w = CGImageGetWidth(image_ref); size_t h = CGImageGetHeight(image_ref); size_t bits_per_pixel = CGImageGetBitsPerPixel(image_ref); size_t bytes_per_row = CGImageGetBytesPerRow(image_ref); SDL_Surface* surface; SDL_Palette* palette; CGColorSpaceRef color_space = CGImageGetColorSpace(image_ref); CGColorSpaceRef base_color_space = CGColorSpaceGetBaseColorSpace(color_space); size_t num_components = CGColorSpaceGetNumberOfComponents(base_color_space); size_t num_entries = CGColorSpaceGetColorTableCount(color_space); uint8_t *entry, entries[num_components * num_entries]; /* What do we do if it's not RGB? */ if (num_components != 3) { SDL_SetError("Unknown colorspace components %lu", num_components); return NULL; } if (bits_per_pixel != 8) { SDL_SetError("Unknown bits_per_pixel %lu", bits_per_pixel); return NULL; } CGColorSpaceGetColorTable(color_space, entries); surface = SDL_CreateRGBSurface(SDL_SWSURFACE, (int)w, (int)h, bits_per_pixel, 0, 0, 0, 0); if (surface) { uint8_t* pixels = (uint8_t*)surface->pixels; CGDataProviderRef provider = CGImageGetDataProvider(image_ref); NSData* data = (id)CGDataProviderCopyData(provider); [data autorelease]; const uint8_t* bytes = [data bytes]; size_t i; palette = surface->format->palette; for (i = 0, entry = entries; i < num_entries; ++i) { palette->colors[i].r = entry[0]; palette->colors[i].g = entry[1]; palette->colors[i].b = entry[2]; entry += num_components; } for (i = 0; i < h; ++i) { SDL_memcpy(pixels, bytes, w); pixels += surface->pitch; bytes += bytes_per_row; } } return surface; } static SDL_Surface* Create_SDL_Surface_From_CGImage(CGImageRef image_ref) { CGColorSpaceRef color_space = CGImageGetColorSpace(image_ref); if (CGColorSpaceGetModel(color_space) == kCGColorSpaceModelIndexed) { return Create_SDL_Surface_From_CGImage_Index(image_ref); } else { return Create_SDL_Surface_From_CGImage_RGB(image_ref); } } #pragma mark - #pragma mark IMG_Init stubs #if !defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)) static int Internal_checkImageIOisAvailable() { // just check if we are running on ios 4 or more, else throw exception if ([UIImage instancesRespondToSelector:@selector(initWithCGImage:scale:orientation:)]) return 0; [NSException raise:@"UIImage fallback not enabled at compile time" format:@"ImageIO is not available on your platform, please recompile SDL_Image with ALLOW_UIIMAGE_FALLBACK."]; return -1; } #endif int IMG_InitJPG() { return 0; } void IMG_QuitJPG() { } int IMG_InitPNG() { return 0; } void IMG_QuitPNG() { } int IMG_InitTIF() { return 0; } void IMG_QuitTIF() { } #pragma mark - #pragma mark Get type of image static int Internal_isType_UIImage (SDL_RWops *rw_ops, CFStringRef uti_string_to_test) { int is_type = 0; #if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)) Sint64 start = SDL_RWtell(rw_ops); if ((0 == CFStringCompare(uti_string_to_test, kUTTypeICO, 0)) || (0 == CFStringCompare(uti_string_to_test, CFSTR("com.microsoft.cur"), 0))) { // The Win32 ICO file header (14 bytes) Uint16 bfReserved; Uint16 bfType; Uint16 bfCount; int type = (0 == CFStringCompare(uti_string_to_test, kUTTypeICO, 0)) ? 1 : 2; bfReserved = SDL_ReadLE16(rw_ops); bfType = SDL_ReadLE16(rw_ops); bfCount = SDL_ReadLE16(rw_ops); if ((bfReserved == 0) && (bfType == type) && (bfCount != 0)) is_type = 1; } else if (0 == CFStringCompare(uti_string_to_test, kUTTypeBMP, 0)) { char magic[2]; if ( SDL_RWread(rw_ops, magic, sizeof(magic), 1) ) { if ( strncmp(magic, "BM", 2) == 0 ) { is_type = 1; } } } else if (0 == CFStringCompare(uti_string_to_test, kUTTypeGIF, 0)) { char magic[6]; if ( SDL_RWread(rw_ops, magic, sizeof(magic), 1) ) { if ( (strncmp(magic, "GIF", 3) == 0) && ((memcmp(magic + 3, "87a", 3) == 0) || (memcmp(magic + 3, "89a", 3) == 0)) ) { is_type = 1; } } } else if (0 == CFStringCompare(uti_string_to_test, kUTTypeJPEG, 0)) { int in_scan = 0; Uint8 magic[4]; // This detection code is by Steaphan Greene <stea@cs.binghamton.edu> // Blame me, not Sam, if this doesn't work right. */ // And don't forget to report the problem to the the sdl list too! */ if ( SDL_RWread(rw_ops, magic, 2, 1) ) { if ( (magic[0] == 0xFF) && (magic[1] == 0xD8) ) { is_type = 1; while (is_type == 1) { if(SDL_RWread(rw_ops, magic, 1, 2) != 2) { is_type = 0; } else if( (magic[0] != 0xFF) && (in_scan == 0) ) { is_type = 0; } else if( (magic[0] != 0xFF) || (magic[1] == 0xFF) ) { /* Extra padding in JPEG (legal) */ /* or this is data and we are scanning */ SDL_RWseek(rw_ops, -1, SEEK_CUR); } else if(magic[1] == 0xD9) { /* Got to end of good JPEG */ break; } else if( (in_scan == 1) && (magic[1] == 0x00) ) { /* This is an encoded 0xFF within the data */ } else if( (magic[1] >= 0xD0) && (magic[1] < 0xD9) ) { /* These have nothing else */ } else if(SDL_RWread(rw_ops, magic+2, 1, 2) != 2) { is_type = 0; } else { /* Yes, it's big-endian */ Uint32 start; Uint32 size; Uint32 end; start = SDL_RWtell(rw_ops); size = (magic[2] << 8) + magic[3]; end = SDL_RWseek(rw_ops, size-2, SEEK_CUR); if ( end != start + size - 2 ) is_type = 0; if ( magic[1] == 0xDA ) { /* Now comes the actual JPEG meat */ #ifdef FAST_IS_JPEG /* Ok, I'm convinced. It is a JPEG. */ break; #else /* I'm not convinced. Prove it! */ in_scan = 1; #endif } } } } } } else if (0 == CFStringCompare(uti_string_to_test, kUTTypePNG, 0)) { Uint8 magic[4]; if ( SDL_RWread(rw_ops, magic, 1, sizeof(magic)) == sizeof(magic) ) { if ( magic[0] == 0x89 && magic[1] == 'P' && magic[2] == 'N' && magic[3] == 'G' ) { is_type = 1; } } } else if (0 == CFStringCompare(uti_string_to_test, CFSTR("com.truevision.tga-image"), 0)) { //TODO: fill me! } else if (0 == CFStringCompare(uti_string_to_test, kUTTypeTIFF, 0)) { Uint8 magic[4]; if ( SDL_RWread(rw_ops, magic, 1, sizeof(magic)) == sizeof(magic) ) { if ( (magic[0] == 'I' && magic[1] == 'I' && magic[2] == 0x2a && magic[3] == 0x00) || (magic[0] == 'M' && magic[1] == 'M' && magic[2] == 0x00 && magic[3] == 0x2a) ) { is_type = 1; } } } // reset the file pointer SDL_RWseek(rw_ops, start, SEEK_SET); #endif /* #if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)) */ return is_type; } static int Internal_isType_ImageIO (SDL_RWops *rw_ops, CFStringRef uti_string_to_test) { int is_type = 0; Sint64 start = SDL_RWtell(rw_ops); CFDictionaryRef hint_dictionary = CreateHintDictionary(uti_string_to_test); CGImageSourceRef image_source = CreateCGImageSourceFromRWops(rw_ops, hint_dictionary); if (hint_dictionary != NULL) { CFRelease(hint_dictionary); } if (NULL == image_source) { // reset the file pointer SDL_RWseek(rw_ops, start, SEEK_SET); return 0; } // This will get the UTI of the container, not the image itself. // Under most cases, this won't be a problem. // But if a person passes an icon file which contains a bmp, // the format will be of the icon file. // But I think the main SDL_image codebase has this same problem so I'm not going to worry about it. CFStringRef uti_type = CGImageSourceGetType(image_source); // CFShow(uti_type); // Unsure if we really want conformance or equality is_type = (int)UTTypeConformsTo(uti_string_to_test, uti_type); CFRelease(image_source); // reset the file pointer SDL_RWseek(rw_ops, start, SEEK_SET); return is_type; } static int Internal_isType (SDL_RWops *rw_ops, CFStringRef uti_string_to_test) { if (rw_ops == NULL) return 0; #if (TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1) if (USE_UIIMAGE_BACKEND()) return Internal_isType_UIImage(rw_ops, uti_string_to_test); else #endif return Internal_isType_ImageIO(rw_ops, uti_string_to_test); } #ifdef BMP_USES_IMAGEIO int IMG_isCUR(SDL_RWops *src) { /* FIXME: Is this a supported type? */ return Internal_isType(src, CFSTR("com.microsoft.cur")); } int IMG_isICO(SDL_RWops *src) { return Internal_isType(src, kUTTypeICO); } int IMG_isBMP(SDL_RWops *src) { return Internal_isType(src, kUTTypeBMP); } #endif /* BMP_USES_IMAGEIO */ int IMG_isGIF(SDL_RWops *src) { return Internal_isType(src, kUTTypeGIF); } // Note: JPEG 2000 is kUTTypeJPEG2000 int IMG_isJPG(SDL_RWops *src) { return Internal_isType(src, kUTTypeJPEG); } int IMG_isPNG(SDL_RWops *src) { return Internal_isType(src, kUTTypePNG); } // This isn't a public API function. Apple seems to be able to identify tga's. int IMG_isTGA(SDL_RWops *src) { return Internal_isType(src, CFSTR("com.truevision.tga-image")); } int IMG_isTIF(SDL_RWops *src) { return Internal_isType(src, kUTTypeTIFF); } #pragma mark - #pragma mark Load image engine static SDL_Surface *LoadImageFromRWops_UIImage (SDL_RWops* rw_ops, CFStringRef uti_string_hint) { SDL_Surface *sdl_surface = NULL; #if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)) NSAutoreleasePool* autorelease_pool = [[NSAutoreleasePool alloc] init]; UIImage *ui_image; int bytes_read = 0; // I don't know what a good size is. // Max recommended texture size is 1024x1024 on iPhone so maybe base it on that? const int block_size = 1024*4; char temp_buffer[block_size]; NSMutableData* ns_data = [[NSMutableData alloc] initWithCapacity:1024*1024*4]; do { bytes_read = SDL_RWread(rw_ops, temp_buffer, 1, block_size); [ns_data appendBytes:temp_buffer length:bytes_read]; } while (bytes_read > 0); ui_image = [[UIImage alloc] initWithData:ns_data]; if (ui_image != nil) sdl_surface = Create_SDL_Surface_From_CGImage([ui_image CGImage]); [ui_image release]; [ns_data release]; [autorelease_pool drain]; #endif /* #if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)) */ return sdl_surface; } static SDL_Surface *LoadImageFromRWops_ImageIO (SDL_RWops *rw_ops, CFStringRef uti_string_hint) { CFDictionaryRef hint_dictionary = CreateHintDictionary(uti_string_hint); CGImageSourceRef image_source = CreateCGImageSourceFromRWops(rw_ops, hint_dictionary); if (hint_dictionary != NULL) CFRelease(hint_dictionary); if (NULL == image_source) return NULL; CGImageRef image_ref = CreateCGImageFromCGImageSource(image_source); CFRelease(image_source); if (NULL == image_ref) return NULL; SDL_Surface *sdl_surface = Create_SDL_Surface_From_CGImage(image_ref); CFRelease(image_ref); return sdl_surface; } static SDL_Surface *LoadImageFromRWops (SDL_RWops *rw_ops, CFStringRef uti_string_hint) { #if (TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1) if (USE_UIIMAGE_BACKEND()) return LoadImageFromRWops_UIImage(rw_ops, uti_string_hint); else #endif return LoadImageFromRWops_ImageIO(rw_ops, uti_string_hint); } static SDL_Surface* LoadImageFromFile_UIImage (const char *file) { SDL_Surface *sdl_surface = NULL; #if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)) NSAutoreleasePool* autorelease_pool = [[NSAutoreleasePool alloc] init]; NSString *ns_string = [[NSString alloc] initWithUTF8String:file]; UIImage *ui_image = [[UIImage alloc] initWithContentsOfFile:ns_string]; if (ui_image != nil) sdl_surface = Create_SDL_Surface_From_CGImage([ui_image CGImage]); [ui_image release]; [ns_string release]; [autorelease_pool drain]; #endif /* #if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)) */ return sdl_surface; } static SDL_Surface* LoadImageFromFile_ImageIO (const char *file) { CGImageSourceRef image_source = NULL; image_source = CreateCGImageSourceFromFile(file); if(NULL == image_source) return NULL; CGImageRef image_ref = CreateCGImageFromCGImageSource(image_source); CFRelease(image_source); if (NULL == image_ref) return NULL; SDL_Surface *sdl_surface = Create_SDL_Surface_From_CGImage(image_ref); CFRelease(image_ref); return sdl_surface; } static SDL_Surface* LoadImageFromFile (const char *file) { #if (TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1) if (USE_UIIMAGE_BACKEND()) return LoadImageFromFile_UIImage(file); else #endif return LoadImageFromFile_ImageIO(file); } #ifdef BMP_USES_IMAGEIO SDL_Surface* IMG_LoadCUR_RW (SDL_RWops *src) { /* FIXME: Is this a supported type? */ return LoadImageFromRWops(src, CFSTR("com.microsoft.cur")); } SDL_Surface* IMG_LoadICO_RW (SDL_RWops *src) { return LoadImageFromRWops(src, kUTTypeICO); } SDL_Surface* IMG_LoadBMP_RW (SDL_RWops *src) { return LoadImageFromRWops(src, kUTTypeBMP); } #endif /* BMP_USES_IMAGEIO */ SDL_Surface* IMG_LoadGIF_RW (SDL_RWops *src) { return LoadImageFromRWops (src, kUTTypeGIF); } SDL_Surface* IMG_LoadJPG_RW (SDL_RWops *src) { return LoadImageFromRWops (src, kUTTypeJPEG); } SDL_Surface* IMG_LoadPNG_RW (SDL_RWops *src) { return LoadImageFromRWops (src, kUTTypePNG); } SDL_Surface* IMG_LoadTGA_RW (SDL_RWops *src) { return LoadImageFromRWops(src, CFSTR("com.truevision.tga-image")); } SDL_Surface* IMG_LoadTIF_RW (SDL_RWops *src) { return LoadImageFromRWops(src, kUTTypeTIFF); } // Since UIImage doesn't really support streams well, we should optimize for the file case. // Apple provides both stream and file loading functions in ImageIO. // Potentially, Apple can optimize for either case. SDL_Surface* IMG_Load (const char *file) { SDL_Surface* sdl_surface = NULL; sdl_surface = LoadImageFromFile(file); if(NULL == sdl_surface) { // Either the file doesn't exist or ImageIO doesn't understand the format. // For the latter case, fallback to the native SDL_image handlers. SDL_RWops *src = SDL_RWFromFile(file, "rb"); char *ext = strrchr(file, '.'); if (ext) { ext++; } if (!src) { /* The error message has been set in SDL_RWFromFile */ return NULL; } sdl_surface = IMG_LoadTyped_RW(src, 1, ext); } return sdl_surface; } #endif /* defined(__APPLE__) && !defined(SDL_IMAGE_USE_COMMON_BACKEND) */
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG_ImageIO.m
Objective-C
apache-2.0
26,131
/* * IMG_ImageIO.c * SDL_image * * Created by Eric Wing on 1/2/09. * Copyright 2009 __MyCompanyName__. All rights reserved. * */ #include "SDL_image.h" #import <UIKit/UIKit.h> #import <MobileCoreServices/MobileCoreServices.h> // for UTCoreTypes.h // Once we have our image, we need to get it into an SDL_Surface // (Copied straight from the ImageIO backend.) static SDL_Surface* Create_SDL_Surface_From_CGImage(CGImageRef image_ref) { /* This code is adapted from Apple's Documentation found here: * http://developer.apple.com/documentation/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/index.html * Listing 9-4††Using a Quartz image as a texture source. * Unfortunately, this guide doesn't show what to do about * non-RGBA image formats so I'm making the rest up. * All this code should be scrutinized. */ size_t w = CGImageGetWidth(image_ref); size_t h = CGImageGetHeight(image_ref); CGRect rect = {{0, 0}, {w, h}}; CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image_ref); //size_t bits_per_pixel = CGImageGetBitsPerPixel(image_ref); size_t bits_per_component = 8; SDL_Surface* surface; Uint32 Amask; Uint32 Rmask; Uint32 Gmask; Uint32 Bmask; CGContextRef bitmap_context; CGBitmapInfo bitmap_info; CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB(); if (alpha == kCGImageAlphaNone || alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast) { bitmap_info = kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host; /* XRGB */ Amask = 0x00000000; } else { /* kCGImageAlphaFirst isn't supported */ //bitmap_info = kCGImageAlphaFirst | kCGBitmapByteOrder32Host; /* ARGB */ bitmap_info = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host; /* ARGB */ Amask = 0xFF000000; } Rmask = 0x00FF0000; Gmask = 0x0000FF00; Bmask = 0x000000FF; surface = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 32, Rmask, Gmask, Bmask, Amask); if (surface) { // Sets up a context to be drawn to with surface->pixels as the area to be drawn to bitmap_context = CGBitmapContextCreate( surface->pixels, surface->w, surface->h, bits_per_component, surface->pitch, color_space, bitmap_info ); // Draws the image into the context's image_data CGContextDrawImage(bitmap_context, rect, image_ref); CGContextRelease(bitmap_context); // FIXME: Reverse the premultiplied alpha if ((bitmap_info & kCGBitmapAlphaInfoMask) == kCGImageAlphaPremultipliedFirst) { int i, j; Uint8 *p = (Uint8 *)surface->pixels; for (i = surface->h * surface->pitch/4; i--; ) { #if __LITTLE_ENDIAN__ Uint8 A = p[3]; if (A) { for (j = 0; j < 3; ++j) { p[j] = (p[j] * 255) / A; } } #else Uint8 A = p[0]; if (A) { for (j = 1; j < 4; ++j) { p[j] = (p[j] * 255) / A; } } #endif /* ENDIAN */ p += 4; } } } if (color_space) { CGColorSpaceRelease(color_space); } return surface; } static SDL_Surface* LoadImageFromRWops(SDL_RWops* rw_ops, CFStringRef uti_string_hint) { NSAutoreleasePool* autorelease_pool = [[NSAutoreleasePool alloc] init]; SDL_Surface* sdl_surface; UIImage* ui_image; int bytes_read = 0; // I don't know what a good size is. // Max recommended texture size is 1024x1024 on iPhone so maybe base it on that? const int block_size = 1024*4; char temp_buffer[block_size]; NSMutableData* ns_data = [[NSMutableData alloc] initWithCapacity:1024*1024*4]; do { bytes_read = SDL_RWread(rw_ops, temp_buffer, 1, block_size); [ns_data appendBytes:temp_buffer length:bytes_read]; } while(bytes_read > 0); ui_image = [[UIImage alloc] initWithData:ns_data]; sdl_surface = Create_SDL_Surface_From_CGImage([ui_image CGImage]); [ui_image release]; [ns_data release]; [autorelease_pool drain]; return sdl_surface; } static SDL_Surface* LoadImageFromFile(const char *file) { NSAutoreleasePool* autorelease_pool = [[NSAutoreleasePool alloc] init]; SDL_Surface* sdl_surface = NULL; UIImage* ui_image; NSString* ns_string; ns_string = [[NSString alloc] initWithUTF8String:file]; ui_image = [[UIImage alloc] initWithContentsOfFile:ns_string]; if(ui_image != NULL) { sdl_surface = Create_SDL_Surface_From_CGImage([ui_image CGImage]); } [ui_image release]; [ns_string release]; [autorelease_pool drain]; return sdl_surface; } /* Since UIImage doesn't really support streams well, we should optimize for the file case. */ SDL_Surface *IMG_Load(const char *file) { SDL_Surface* sdl_surface = NULL; sdl_surface = LoadImageFromFile(file); if(NULL == sdl_surface) { // Either the file doesn't exist or ImageIO doesn't understand the format. // For the latter case, fallback to the native SDL_image handlers. SDL_RWops *src = SDL_RWFromFile(file, "rb"); char *ext = strrchr(file, '.'); if(ext) { ext++; } if(!src) { /* The error message has been set in SDL_RWFromFile */ return NULL; } sdl_surface = IMG_LoadTyped_RW(src, 1, ext); } return sdl_surface; } int IMG_InitJPG() { return 0; } void IMG_QuitJPG() { } int IMG_InitPNG() { return 0; } void IMG_QuitPNG() { } int IMG_InitTIF() { return 0; } void IMG_QuitTIF() { } /* Copied straight from other files so I don't have to alter them. */ static int IMG_isICOCUR(SDL_RWops *src, int type) { int start; int is_ICOCUR; /* The Win32 ICO file header (14 bytes) */ Uint16 bfReserved; Uint16 bfType; Uint16 bfCount; if ( !src ) return 0; start = SDL_RWtell(src); is_ICOCUR = 0; bfReserved = SDL_ReadLE16(src); bfType = SDL_ReadLE16(src); bfCount = SDL_ReadLE16(src); if ((bfReserved == 0) && (bfType == type) && (bfCount != 0)) is_ICOCUR = 1; SDL_RWseek(src, start, SEEK_SET); return (is_ICOCUR); } int IMG_isICO(SDL_RWops *src) { return IMG_isICOCUR(src, 1); } int IMG_isCUR(SDL_RWops *src) { return IMG_isICOCUR(src, 2); } int IMG_isBMP(SDL_RWops *src) { int start; int is_BMP; char magic[2]; if ( !src ) return 0; start = SDL_RWtell(src); is_BMP = 0; if ( SDL_RWread(src, magic, sizeof(magic), 1) ) { if ( strncmp(magic, "BM", 2) == 0 ) { is_BMP = 1; } } SDL_RWseek(src, start, SEEK_SET); return(is_BMP); } int IMG_isGIF(SDL_RWops *src) { int start; int is_GIF; char magic[6]; if ( !src ) return 0; start = SDL_RWtell(src); is_GIF = 0; if ( SDL_RWread(src, magic, sizeof(magic), 1) ) { if ( (strncmp(magic, "GIF", 3) == 0) && ((memcmp(magic + 3, "87a", 3) == 0) || (memcmp(magic + 3, "89a", 3) == 0)) ) { is_GIF = 1; } } SDL_RWseek(src, start, SEEK_SET); return(is_GIF); } int IMG_isJPG(SDL_RWops *src) { int start; int is_JPG; int in_scan; Uint8 magic[4]; /* This detection code is by Steaphan Greene <stea@cs.binghamton.edu> */ /* Blame me, not Sam, if this doesn't work right. */ /* And don't forget to report the problem to the the sdl list too! */ if ( !src ) return 0; start = SDL_RWtell(src); is_JPG = 0; in_scan = 0; if ( SDL_RWread(src, magic, 2, 1) ) { if ( (magic[0] == 0xFF) && (magic[1] == 0xD8) ) { is_JPG = 1; while (is_JPG == 1) { if(SDL_RWread(src, magic, 1, 2) != 2) { is_JPG = 0; } else if( (magic[0] != 0xFF) && (in_scan == 0) ) { is_JPG = 0; } else if( (magic[0] != 0xFF) || (magic[1] == 0xFF) ) { /* Extra padding in JPEG (legal) */ /* or this is data and we are scanning */ SDL_RWseek(src, -1, SEEK_CUR); } else if(magic[1] == 0xD9) { /* Got to end of good JPEG */ break; } else if( (in_scan == 1) && (magic[1] == 0x00) ) { /* This is an encoded 0xFF within the data */ } else if( (magic[1] >= 0xD0) && (magic[1] < 0xD9) ) { /* These have nothing else */ } else if(SDL_RWread(src, magic+2, 1, 2) != 2) { is_JPG = 0; } else { /* Yes, it's big-endian */ Uint32 start; Uint32 size; Uint32 end; start = SDL_RWtell(src); size = (magic[2] << 8) + magic[3]; end = SDL_RWseek(src, size-2, SEEK_CUR); if ( end != start + size - 2 ) is_JPG = 0; if ( magic[1] == 0xDA ) { /* Now comes the actual JPEG meat */ #ifdef FAST_IS_JPEG /* Ok, I'm convinced. It is a JPEG. */ break; #else /* I'm not convinced. Prove it! */ in_scan = 1; #endif } } } } } SDL_RWseek(src, start, SEEK_SET); return(is_JPG); } int IMG_isPNG(SDL_RWops *src) { int start; int is_PNG; Uint8 magic[4]; if ( !src ) return 0; start = SDL_RWtell(src); is_PNG = 0; if ( SDL_RWread(src, magic, 1, sizeof(magic)) == sizeof(magic) ) { if ( magic[0] == 0x89 && magic[1] == 'P' && magic[2] == 'N' && magic[3] == 'G' ) { is_PNG = 1; } } SDL_RWseek(src, start, SEEK_SET); return(is_PNG); } int IMG_isTIF(SDL_RWops* src) { int start; int is_TIF; Uint8 magic[4]; if ( !src ) return 0; start = SDL_RWtell(src); is_TIF = 0; if ( SDL_RWread(src, magic, 1, sizeof(magic)) == sizeof(magic) ) { if ( (magic[0] == 'I' && magic[1] == 'I' && magic[2] == 0x2a && magic[3] == 0x00) || (magic[0] == 'M' && magic[1] == 'M' && magic[2] == 0x00 && magic[3] == 0x2a) ) { is_TIF = 1; } } SDL_RWseek(src, start, SEEK_SET); return(is_TIF); } SDL_Surface* IMG_LoadCUR_RW(SDL_RWops *src) { /* FIXME: Is this a supported type? */ return LoadImageFromRWops(src, CFSTR("com.microsoft.cur")); } SDL_Surface* IMG_LoadICO_RW(SDL_RWops *src) { return LoadImageFromRWops(src, kUTTypeICO); } SDL_Surface* IMG_LoadBMP_RW(SDL_RWops *src) { return LoadImageFromRWops(src, kUTTypeBMP); } SDL_Surface* IMG_LoadGIF_RW(SDL_RWops *src) { return LoadImageFromRWops(src, kUTTypeGIF); } SDL_Surface* IMG_LoadJPG_RW(SDL_RWops *src) { return LoadImageFromRWops(src, kUTTypeJPEG); } SDL_Surface* IMG_LoadPNG_RW(SDL_RWops *src) { return LoadImageFromRWops(src, kUTTypePNG); } SDL_Surface* IMG_LoadTGA_RW(SDL_RWops *src) { return LoadImageFromRWops(src, CFSTR("com.truevision.tga-image")); } SDL_Surface* IMG_LoadTIF_RW(SDL_RWops *src) { return LoadImageFromRWops(src, kUTTypeTIFF); }
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG_UIImage.m
Objective-C
apache-2.0
12,080
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #if defined(SDL_IMAGE_USE_WIC_BACKEND) #include "SDL_image.h" #define COBJMACROS #include <initguid.h> #include <wincodec.h> static IWICImagingFactory* wicFactory = NULL; static int WIC_Init() { if (wicFactory == NULL) { HRESULT hr = CoCreateInstance( &CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, &IID_IWICImagingFactory, (void**)&wicFactory ); if (FAILED(hr)) { return -1; } } return 0; } static void WIC_Quit() { if (wicFactory) { IWICImagingFactory_Release(wicFactory); } } int IMG_InitPNG() { return WIC_Init(); } void IMG_QuitPNG() { WIC_Quit(); } int IMG_InitJPG() { return WIC_Init(); } void IMG_QuitJPG() { WIC_Quit(); } int IMG_InitTIF() { return WIC_Init(); } void IMG_QuitTIF() { WIC_Quit(); } int IMG_isPNG(SDL_RWops *src) { Sint64 start; int is_PNG; Uint8 magic[4]; if ( !src ) { return 0; } start = SDL_RWtell(src); is_PNG = 0; if ( SDL_RWread(src, magic, 1, sizeof(magic)) == sizeof(magic) ) { if ( magic[0] == 0x89 && magic[1] == 'P' && magic[2] == 'N' && magic[3] == 'G' ) { is_PNG = 1; } } SDL_RWseek(src, start, RW_SEEK_SET); return(is_PNG); } int IMG_isJPG(SDL_RWops *src) { Sint64 start; int is_JPG; int in_scan; Uint8 magic[4]; /* This detection code is by Steaphan Greene <stea@cs.binghamton.edu> */ /* Blame me, not Sam, if this doesn't work right. */ /* And don't forget to report the problem to the the sdl list too! */ if (!src) return 0; start = SDL_RWtell(src); is_JPG = 0; in_scan = 0; if (SDL_RWread(src, magic, 2, 1)) { if ((magic[0] == 0xFF) && (magic[1] == 0xD8)) { is_JPG = 1; while (is_JPG == 1) { if (SDL_RWread(src, magic, 1, 2) != 2) { is_JPG = 0; } else if ((magic[0] != 0xFF) && (in_scan == 0)) { is_JPG = 0; } else if ((magic[0] != 0xFF) || (magic[1] == 0xFF)) { /* Extra padding in JPEG (legal) */ /* or this is data and we are scanning */ SDL_RWseek(src, -1, RW_SEEK_CUR); } else if (magic[1] == 0xD9) { /* Got to end of good JPEG */ break; } else if ((in_scan == 1) && (magic[1] == 0x00)) { /* This is an encoded 0xFF within the data */ } else if ((magic[1] >= 0xD0) && (magic[1] < 0xD9)) { /* These have nothing else */ } else if (SDL_RWread(src, magic + 2, 1, 2) != 2) { is_JPG = 0; } else { /* Yes, it's big-endian */ Sint64 innerStart; Uint32 size; Sint64 end; innerStart = SDL_RWtell(src); size = (magic[2] << 8) + magic[3]; end = SDL_RWseek(src, size - 2, RW_SEEK_CUR); if (end != innerStart + size - 2) is_JPG = 0; if (magic[1] == 0xDA) { /* Now comes the actual JPEG meat */ #ifdef FAST_IS_JPEG /* Ok, I'm convinced. It is a JPEG. */ break; #else /* I'm not convinced. Prove it! */ in_scan = 1; #endif } } } } } SDL_RWseek(src, start, RW_SEEK_SET); return(is_JPG); } int IMG_isTIF(SDL_RWops* src) { Sint64 start; int is_TIF; Uint8 magic[4]; if (!src) return 0; start = SDL_RWtell(src); is_TIF = 0; if (SDL_RWread(src, magic, 1, sizeof(magic)) == sizeof(magic)) { if ((magic[0] == 'I' && magic[1] == 'I' && magic[2] == 0x2a && magic[3] == 0x00) || (magic[0] == 'M' && magic[1] == 'M' && magic[2] == 0x00 && magic[3] == 0x2a)) { is_TIF = 1; } } SDL_RWseek(src, start, RW_SEEK_SET); return(is_TIF); } static SDL_Surface* WIC_LoadImage(SDL_RWops *src) { SDL_Surface* surface = NULL; IWICStream* stream = NULL; IWICBitmapDecoder* bitmapDecoder = NULL; IWICBitmapFrameDecode* bitmapFrame = NULL; IWICFormatConverter* formatConverter = NULL; UINT width, height; if (wicFactory == NULL && (WIC_Init() < 0)) { IMG_SetError("WIC failed to initialize!"); return NULL; } Sint64 fileSize = SDL_RWsize(src); Uint8* memoryBuffer = (Uint8*)SDL_malloc(fileSize); if (!memoryBuffer) { SDL_OutOfMemory(); return NULL; } SDL_RWread(src, memoryBuffer, 1, fileSize); #define DONE_IF_FAILED(X) if (FAILED((X))) { goto done; } DONE_IF_FAILED(IWICImagingFactory_CreateStream(wicFactory, &stream)); DONE_IF_FAILED(IWICStream_InitializeFromMemory(stream, memoryBuffer, fileSize)); DONE_IF_FAILED(IWICImagingFactory_CreateDecoderFromStream( wicFactory, (IStream*)stream, NULL, WICDecodeMetadataCacheOnDemand, &bitmapDecoder )); DONE_IF_FAILED(IWICBitmapDecoder_GetFrame(bitmapDecoder, 0, &bitmapFrame)); DONE_IF_FAILED(IWICImagingFactory_CreateFormatConverter(wicFactory, &formatConverter)); DONE_IF_FAILED(IWICFormatConverter_Initialize( formatConverter, (IWICBitmapSource*)bitmapFrame, &GUID_WICPixelFormat32bppPRGBA, WICBitmapDitherTypeNone, NULL, 0.0, WICBitmapPaletteTypeCustom )); DONE_IF_FAILED(IWICBitmapFrameDecode_GetSize(bitmapFrame, &width, &height)); #undef DONE_IF_FAILED surface = SDL_CreateRGBSurface( 0, width, height, 32, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 ); IWICFormatConverter_CopyPixels( formatConverter, NULL, width * 4, width * height * 4, (BYTE*)surface->pixels ); done: if (formatConverter) { IWICFormatConverter_Release(formatConverter); } if (bitmapFrame) { IWICBitmapFrameDecode_Release(bitmapFrame); } if (bitmapDecoder) { IWICBitmapDecoder_Release(bitmapDecoder); } if (stream) { IWICStream_Release(stream); } SDL_free(memoryBuffer); return surface; } SDL_Surface *IMG_LoadPNG_RW(SDL_RWops *src) { return WIC_LoadImage(src); } SDL_Surface *IMG_LoadJPG_RW(SDL_RWops *src) { return WIC_LoadImage(src); } SDL_Surface *IMG_LoadTIF_RW(SDL_RWops *src) { return WIC_LoadImage(src); } #endif /* SDL_IMAGE_USE_WIC_BACKEND */
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG_WIC.c
C
apache-2.0
7,958
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #if (!defined(__APPLE__) || defined(SDL_IMAGE_USE_COMMON_BACKEND)) || !defined(BMP_USES_IMAGEIO) /* This is a BMP image file loading framework * * ICO/CUR file support is here as well since it uses similar internal * representation * * A good test suite of BMP images is available at: * http://entropymine.com/jason/bmpsuite/bmpsuite/html/bmpsuite.html */ #include "SDL_image.h" #ifdef LOAD_BMP /* See if an image is contained in a data source */ int IMG_isBMP(SDL_RWops *src) { Sint64 start; int is_BMP; char magic[2]; if ( !src ) return 0; start = SDL_RWtell(src); is_BMP = 0; if ( SDL_RWread(src, magic, sizeof(magic), 1) ) { if ( SDL_strncmp(magic, "BM", 2) == 0 ) { is_BMP = 1; } } SDL_RWseek(src, start, RW_SEEK_SET); return(is_BMP); } static int IMG_isICOCUR(SDL_RWops *src, int type) { Sint64 start; int is_ICOCUR; /* The Win32 ICO file header (14 bytes) */ Uint16 bfReserved; Uint16 bfType; Uint16 bfCount; if ( !src ) return 0; start = SDL_RWtell(src); is_ICOCUR = 0; bfReserved = SDL_ReadLE16(src); bfType = SDL_ReadLE16(src); bfCount = SDL_ReadLE16(src); if ((bfReserved == 0) && (bfType == type) && (bfCount != 0)) is_ICOCUR = 1; SDL_RWseek(src, start, RW_SEEK_SET); return (is_ICOCUR); } int IMG_isICO(SDL_RWops *src) { return IMG_isICOCUR(src, 1); } int IMG_isCUR(SDL_RWops *src) { return IMG_isICOCUR(src, 2); } #include "SDL_error.h" #include "SDL_video.h" #include "SDL_endian.h" /* Compression encodings for BMP files */ #ifndef BI_RGB #define BI_RGB 0 #define BI_RLE8 1 #define BI_RLE4 2 #define BI_BITFIELDS 3 #endif static int readRlePixels(SDL_Surface * surface, SDL_RWops * src, int isRle8) { /* | Sets the surface pixels from src. A bmp image is upside down. */ int pitch = surface->pitch; int height = surface->h; Uint8 *start = (Uint8 *)surface->pixels; Uint8 *end = start + (height*pitch); Uint8 *bits = end-pitch, *spot; int ofs = 0; Uint8 ch; Uint8 needsPad; #define COPY_PIXEL(x) spot = &bits[ofs++]; if(spot >= start && spot < end) *spot = (x) for (;;) { if ( !SDL_RWread(src, &ch, 1, 1) ) return 1; /* | encoded mode starts with a run length, and then a byte | with two colour indexes to alternate between for the run */ if ( ch ) { Uint8 pixel; if ( !SDL_RWread(src, &pixel, 1, 1) ) return 1; if ( isRle8 ) { /* 256-color bitmap, compressed */ do { COPY_PIXEL(pixel); } while (--ch); } else { /* 16-color bitmap, compressed */ Uint8 pixel0 = pixel >> 4; Uint8 pixel1 = pixel & 0x0F; for (;;) { COPY_PIXEL(pixel0); /* even count, high nibble */ if (!--ch) break; COPY_PIXEL(pixel1); /* odd count, low nibble */ if (!--ch) break; } } } else { /* | A leading zero is an escape; it may signal the end of the bitmap, | a cursor move, or some absolute data. | zero tag may be absolute mode or an escape */ if ( !SDL_RWread(src, &ch, 1, 1) ) return 1; switch (ch) { case 0: /* end of line */ ofs = 0; bits -= pitch; /* go to previous */ break; case 1: /* end of bitmap */ return 0; /* success! */ case 2: /* delta */ if ( !SDL_RWread(src, &ch, 1, 1) ) return 1; ofs += ch; if ( !SDL_RWread(src, &ch, 1, 1) ) return 1; bits -= (ch * pitch); break; default: /* no compression */ if (isRle8) { needsPad = ( ch & 1 ); do { Uint8 pixel; if ( !SDL_RWread(src, &pixel, 1, 1) ) return 1; COPY_PIXEL(pixel); } while (--ch); } else { needsPad = ( ((ch+1)>>1) & 1 ); /* (ch+1)>>1: bytes size */ for (;;) { Uint8 pixel; if ( !SDL_RWread(src, &pixel, 1, 1) ) return 1; COPY_PIXEL(pixel >> 4); if (!--ch) break; COPY_PIXEL(pixel & 0x0F); if (!--ch) break; } } /* pad at even boundary */ if ( needsPad && !SDL_RWread(src, &ch, 1, 1) ) return 1; break; } } } } static void CorrectAlphaChannel(SDL_Surface *surface) { /* Check to see if there is any alpha channel data */ SDL_bool hasAlpha = SDL_FALSE; #if SDL_BYTEORDER == SDL_BIG_ENDIAN int alphaChannelOffset = 0; #else int alphaChannelOffset = 3; #endif Uint8 *alpha = ((Uint8*)surface->pixels) + alphaChannelOffset; Uint8 *end = alpha + surface->h * surface->pitch; while (alpha < end) { if (*alpha != 0) { hasAlpha = SDL_TRUE; break; } alpha += 4; } if (!hasAlpha) { alpha = ((Uint8*)surface->pixels) + alphaChannelOffset; while (alpha < end) { *alpha = SDL_ALPHA_OPAQUE; alpha += 4; } } } static SDL_Surface *LoadBMP_RW (SDL_RWops *src, int freesrc) { SDL_bool was_error; Sint64 fp_offset; int bmpPitch; int i, pad; SDL_Surface *surface; Uint32 Rmask = 0; Uint32 Gmask = 0; Uint32 Bmask = 0; Uint32 Amask = 0; SDL_Palette *palette; Uint8 *bits; Uint8 *top, *end; SDL_bool topDown; int ExpandBMP; SDL_bool haveRGBMasks = SDL_FALSE; SDL_bool haveAlphaMask = SDL_FALSE; SDL_bool correctAlpha = SDL_FALSE; /* The Win32 BMP file header (14 bytes) */ char magic[2]; Uint32 bfSize; Uint16 bfReserved1; Uint16 bfReserved2; Uint32 bfOffBits; /* The Win32 BITMAPINFOHEADER struct (40 bytes) */ Uint32 biSize; Sint32 biWidth; Sint32 biHeight = 0; Uint16 biPlanes; Uint16 biBitCount; Uint32 biCompression; Uint32 biSizeImage; Sint32 biXPelsPerMeter; Sint32 biYPelsPerMeter; Uint32 biClrUsed; Uint32 biClrImportant; /* Make sure we are passed a valid data source */ surface = NULL; was_error = SDL_FALSE; if ( src == NULL ) { was_error = SDL_TRUE; goto done; } /* Read in the BMP file header */ fp_offset = SDL_RWtell(src); SDL_ClearError(); if ( SDL_RWread(src, magic, 1, 2) != 2 ) { SDL_Error(SDL_EFREAD); was_error = SDL_TRUE; goto done; } if ( SDL_strncmp(magic, "BM", 2) != 0 ) { IMG_SetError("File is not a Windows BMP file"); was_error = SDL_TRUE; goto done; } bfSize = SDL_ReadLE32(src); bfReserved1 = SDL_ReadLE16(src); bfReserved2 = SDL_ReadLE16(src); bfOffBits = SDL_ReadLE32(src); /* Read the Win32 BITMAPINFOHEADER */ biSize = SDL_ReadLE32(src); if ( biSize == 12 ) { /* really old BITMAPCOREHEADER */ biWidth = (Uint32)SDL_ReadLE16(src); biHeight = (Uint32)SDL_ReadLE16(src); biPlanes = SDL_ReadLE16(src); biBitCount = SDL_ReadLE16(src); biCompression = BI_RGB; biSizeImage = 0; biXPelsPerMeter = 0; biYPelsPerMeter = 0; biClrUsed = 0; biClrImportant = 0; } else if (biSize >= 40) { /* some version of BITMAPINFOHEADER */ Uint32 headerSize; biWidth = SDL_ReadLE32(src); biHeight = SDL_ReadLE32(src); biPlanes = SDL_ReadLE16(src); biBitCount = SDL_ReadLE16(src); biCompression = SDL_ReadLE32(src); biSizeImage = SDL_ReadLE32(src); biXPelsPerMeter = SDL_ReadLE32(src); biYPelsPerMeter = SDL_ReadLE32(src); biClrUsed = SDL_ReadLE32(src); biClrImportant = SDL_ReadLE32(src); /* 64 == BITMAPCOREHEADER2, an incompatible OS/2 2.x extension. Skip this stuff for now. */ if (biSize != 64) { /* This is complicated. If compression is BI_BITFIELDS, then we have 3 DWORDS that specify the RGB masks. This is either stored here in an BITMAPV2INFOHEADER (which only differs in that it adds these RGB masks) and biSize >= 52, or we've got these masks stored in the exact same place, but strictly speaking, this is the bmiColors field in BITMAPINFO immediately following the legacy v1 info header, just past biSize. */ if (biCompression == BI_BITFIELDS) { haveRGBMasks = SDL_TRUE; Rmask = SDL_ReadLE32(src); Gmask = SDL_ReadLE32(src); Bmask = SDL_ReadLE32(src); /* ...v3 adds an alpha mask. */ if (biSize >= 56) { /* BITMAPV3INFOHEADER; adds alpha mask */ haveAlphaMask = SDL_TRUE; Amask = SDL_ReadLE32(src); } } else { /* the mask fields are ignored for v2+ headers if not BI_BITFIELD. */ if (biSize >= 52) { /* BITMAPV2INFOHEADER; adds RGB masks */ /*Rmask = */ SDL_ReadLE32(src); /*Gmask = */ SDL_ReadLE32(src); /*Bmask = */ SDL_ReadLE32(src); } if (biSize >= 56) { /* BITMAPV3INFOHEADER; adds alpha mask */ /*Amask = */ SDL_ReadLE32(src); } } /* Insert other fields here; Wikipedia and MSDN say we're up to v5 of this header, but we ignore those for now (they add gamma, color spaces, etc). Ignoring the weird OS/2 2.x format, we currently parse up to v3 correctly (hopefully!). */ } /* skip any header bytes we didn't handle... */ headerSize = (Uint32) (SDL_RWtell(src) - (fp_offset + 14)); if (biSize > headerSize) { SDL_RWseek(src, (biSize - headerSize), RW_SEEK_CUR); } } if (biHeight < 0) { topDown = SDL_TRUE; biHeight = -biHeight; } else { topDown = SDL_FALSE; } /* Check for read error */ if (SDL_strcmp(SDL_GetError(), "") != 0) { was_error = SDL_TRUE; goto done; } /* Expand 1 and 4 bit bitmaps to 8 bits per pixel */ switch (biBitCount) { case 1: case 4: ExpandBMP = biBitCount; biBitCount = 8; break; case 2: case 3: case 5: case 6: case 7: SDL_SetError("%d-bpp BMP images are not supported", biBitCount); was_error = SDL_TRUE; goto done; default: ExpandBMP = 0; break; } /* RLE4 and RLE8 BMP compression is supported */ switch (biCompression) { case BI_RGB: /* If there are no masks, use the defaults */ SDL_assert(!haveRGBMasks); SDL_assert(!haveAlphaMask); /* Default values for the BMP format */ switch (biBitCount) { case 15: case 16: Rmask = 0x7C00; Gmask = 0x03E0; Bmask = 0x001F; break; case 24: #if SDL_BYTEORDER == SDL_BIG_ENDIAN Rmask = 0x000000FF; Gmask = 0x0000FF00; Bmask = 0x00FF0000; #else Rmask = 0x00FF0000; Gmask = 0x0000FF00; Bmask = 0x000000FF; #endif break; case 32: /* We don't know if this has alpha channel or not */ correctAlpha = SDL_TRUE; Amask = 0xFF000000; Rmask = 0x00FF0000; Gmask = 0x0000FF00; Bmask = 0x000000FF; break; default: break; } break; case BI_BITFIELDS: break; /* we handled this in the info header. */ default: break; } /* Create a compatible surface, note that the colors are RGB ordered */ surface = SDL_CreateRGBSurface(SDL_SWSURFACE, biWidth, biHeight, biBitCount, Rmask, Gmask, Bmask, Amask); if ( surface == NULL ) { was_error = SDL_TRUE; goto done; } /* Load the palette, if any */ palette = (surface->format)->palette; if ( palette ) { if ( SDL_RWseek(src, fp_offset+14+biSize, RW_SEEK_SET) < 0 ) { SDL_Error(SDL_EFSEEK); was_error = SDL_TRUE; goto done; } /* | guich: always use 1<<bpp b/c some bitmaps can bring wrong information | for colorsUsed */ /* if ( biClrUsed == 0 ) { */ biClrUsed = 1 << biBitCount; /* } */ if ( biSize == 12 ) { for ( i = 0; i < (int)biClrUsed; ++i ) { SDL_RWread(src, &palette->colors[i].b, 1, 1); SDL_RWread(src, &palette->colors[i].g, 1, 1); SDL_RWread(src, &palette->colors[i].r, 1, 1); palette->colors[i].a = SDL_ALPHA_OPAQUE; } } else { for ( i = 0; i < (int)biClrUsed; ++i ) { SDL_RWread(src, &palette->colors[i].b, 1, 1); SDL_RWread(src, &palette->colors[i].g, 1, 1); SDL_RWread(src, &palette->colors[i].r, 1, 1); SDL_RWread(src, &palette->colors[i].a, 1, 1); /* According to Microsoft documentation, the fourth element is reserved and must be zero, so we shouldn't treat it as alpha. */ palette->colors[i].a = SDL_ALPHA_OPAQUE; } } palette->ncolors = biClrUsed; } /* Read the surface pixels. Note that the bmp image is upside down */ if ( SDL_RWseek(src, fp_offset+bfOffBits, RW_SEEK_SET) < 0 ) { SDL_Error(SDL_EFSEEK); was_error = SDL_TRUE; goto done; } if ((biCompression == BI_RLE4) || (biCompression == BI_RLE8)) { was_error = (SDL_bool)readRlePixels(surface, src, biCompression == BI_RLE8); if (was_error) IMG_SetError("Error reading from BMP"); goto done; } top = (Uint8 *)surface->pixels; end = (Uint8 *)surface->pixels+(surface->h*surface->pitch); switch (ExpandBMP) { case 1: bmpPitch = (biWidth + 7) >> 3; pad = (((bmpPitch)%4) ? (4-((bmpPitch)%4)) : 0); break; case 4: bmpPitch = (biWidth + 1) >> 1; pad = (((bmpPitch)%4) ? (4-((bmpPitch)%4)) : 0); break; default: pad = ((surface->pitch%4) ? (4-(surface->pitch%4)) : 0); break; } if ( topDown ) { bits = top; } else { bits = end - surface->pitch; } while ( bits >= top && bits < end ) { switch (ExpandBMP) { case 1: case 4: { Uint8 pixel = 0; int shift = (8-ExpandBMP); for ( i=0; i<surface->w; ++i ) { if ( i%(8/ExpandBMP) == 0 ) { if ( !SDL_RWread(src, &pixel, 1, 1) ) { IMG_SetError("Error reading from BMP"); was_error = SDL_TRUE; goto done; } } bits[i] = (pixel >> shift); if (bits[i] >= biClrUsed) { IMG_SetError("A BMP image contains a pixel with a color out of the palette"); was_error = SDL_TRUE; goto done; } pixel <<= ExpandBMP; } } break; default: if ( SDL_RWread(src, bits, 1, surface->pitch) != surface->pitch ) { SDL_Error(SDL_EFREAD); was_error = SDL_TRUE; goto done; } if (biBitCount == 8 && palette && biClrUsed < (1 << biBitCount)) { for (i = 0; i < surface->w; ++i) { if (bits[i] >= biClrUsed) { SDL_SetError("A BMP image contains a pixel with a color out of the palette"); was_error = SDL_TRUE; goto done; } } } #if SDL_BYTEORDER == SDL_BIG_ENDIAN /* Byte-swap the pixels if needed. Note that the 24bpp case has already been taken care of above. */ switch(biBitCount) { case 15: case 16: { Uint16 *pix = (Uint16 *)bits; for(i = 0; i < surface->w; i++) pix[i] = SDL_Swap16(pix[i]); break; } case 32: { Uint32 *pix = (Uint32 *)bits; for(i = 0; i < surface->w; i++) pix[i] = SDL_Swap32(pix[i]); break; } } #endif break; } /* Skip padding bytes, ugh */ if ( pad ) { Uint8 padbyte; for ( i=0; i<pad; ++i ) { SDL_RWread(src, &padbyte, 1, 1); } } if ( topDown ) { bits += surface->pitch; } else { bits -= surface->pitch; } } if (correctAlpha) { CorrectAlphaChannel(surface); } done: if ( was_error ) { if ( src ) { SDL_RWseek(src, fp_offset, RW_SEEK_SET); } if ( surface ) { SDL_FreeSurface(surface); } surface = NULL; } if ( freesrc && src ) { SDL_RWclose(src); } return(surface); } static Uint8 SDL_Read8(SDL_RWops * src) { Uint8 value; SDL_RWread(src, &value, 1, 1); return (value); } static SDL_Surface * LoadICOCUR_RW(SDL_RWops * src, int type, int freesrc) { SDL_bool was_error; Sint64 fp_offset; int bmpPitch; int i, pad; SDL_Surface *surface; Uint32 Rmask; Uint32 Gmask; Uint32 Bmask; Uint8 *bits; int ExpandBMP; int maxCol = 0; int icoOfs = 0; Uint32 palette[256]; /* The Win32 ICO file header (14 bytes) */ Uint16 bfReserved; Uint16 bfType; Uint16 bfCount; /* The Win32 BITMAPINFOHEADER struct (40 bytes) */ Uint32 biSize; Sint32 biWidth; Sint32 biHeight; Uint16 biPlanes; Uint16 biBitCount; Uint32 biCompression; Uint32 biSizeImage; Sint32 biXPelsPerMeter; Sint32 biYPelsPerMeter; Uint32 biClrUsed; Uint32 biClrImportant; /* Make sure we are passed a valid data source */ surface = NULL; was_error = SDL_FALSE; if (src == NULL) { was_error = SDL_TRUE; goto done; } /* Read in the ICO file header */ fp_offset = SDL_RWtell(src); SDL_ClearError(); bfReserved = SDL_ReadLE16(src); bfType = SDL_ReadLE16(src); bfCount = SDL_ReadLE16(src); if ((bfReserved != 0) || (bfType != type) || (bfCount == 0)) { IMG_SetError("File is not a Windows %s file", type == 1 ? "ICO" : "CUR"); was_error = SDL_TRUE; goto done; } /* Read the Win32 Icon Directory */ for (i = 0; i < bfCount; i++) { /* Icon Directory Entries */ int bWidth = SDL_Read8(src); /* Uint8, but 0 = 256 ! */ int bHeight = SDL_Read8(src); /* Uint8, but 0 = 256 ! */ int bColorCount = SDL_Read8(src); /* Uint8, but 0 = 256 ! */ Uint8 bReserved = SDL_Read8(src); Uint16 wPlanes = SDL_ReadLE16(src); Uint16 wBitCount = SDL_ReadLE16(src); Uint32 dwBytesInRes = SDL_ReadLE32(src); Uint32 dwImageOffset = SDL_ReadLE32(src); if (!bWidth) bWidth = 256; if (!bHeight) bHeight = 256; if (!bColorCount) bColorCount = 256; //printf("%dx%d@%d - %08x\n", bWidth, bHeight, bColorCount, dwImageOffset); if (bColorCount > maxCol) { maxCol = bColorCount; icoOfs = dwImageOffset; //printf("marked\n"); } } /* Advance to the DIB Data */ if (SDL_RWseek(src, icoOfs, RW_SEEK_SET) < 0) { SDL_Error(SDL_EFSEEK); was_error = SDL_TRUE; goto done; } /* Read the Win32 BITMAPINFOHEADER */ biSize = SDL_ReadLE32(src); if (biSize == 40) { biWidth = SDL_ReadLE32(src); biHeight = SDL_ReadLE32(src); biPlanes = SDL_ReadLE16(src); biBitCount = SDL_ReadLE16(src); biCompression = SDL_ReadLE32(src); biSizeImage = SDL_ReadLE32(src); biXPelsPerMeter = SDL_ReadLE32(src); biYPelsPerMeter = SDL_ReadLE32(src); biClrUsed = SDL_ReadLE32(src); biClrImportant = SDL_ReadLE32(src); } else { IMG_SetError("Unsupported ICO bitmap format"); was_error = SDL_TRUE; goto done; } /* Check for read error */ if (SDL_strcmp(SDL_GetError(), "") != 0) { was_error = SDL_TRUE; goto done; } /* We don't support any BMP compression right now */ switch (biCompression) { case BI_RGB: /* Default values for the BMP format */ switch (biBitCount) { case 1: case 4: ExpandBMP = biBitCount; biBitCount = 8; break; case 8: ExpandBMP = 8; break; case 32: Rmask = 0x00FF0000; Gmask = 0x0000FF00; Bmask = 0x000000FF; ExpandBMP = 0; break; default: IMG_SetError("ICO file with unsupported bit count"); was_error = SDL_TRUE; goto done; } break; default: IMG_SetError("Compressed ICO files not supported"); was_error = SDL_TRUE; goto done; } /* sanity check image size, so we don't overflow integers, etc. */ if ((biWidth < 0) || (biWidth > 0xFFFFFF) || (biHeight < 0) || (biHeight > 0xFFFFFF)) { IMG_SetError("Unsupported or invalid ICO dimensions"); was_error = SDL_TRUE; goto done; } /* Create a RGBA surface */ biHeight = biHeight >> 1; //printf("%d x %d\n", biWidth, biHeight); surface = SDL_CreateRGBSurface(0, biWidth, biHeight, 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); if (surface == NULL) { was_error = SDL_TRUE; goto done; } /* Load the palette, if any */ //printf("bc %d bused %d\n", biBitCount, biClrUsed); if (biBitCount <= 8) { if (biClrUsed == 0) { biClrUsed = 1 << biBitCount; } if (biClrUsed > SDL_arraysize(palette)) { IMG_SetError("Unsupported or incorrect biClrUsed field"); was_error = SDL_TRUE; goto done; } for (i = 0; i < (int) biClrUsed; ++i) { SDL_RWread(src, &palette[i], 4, 1); } } /* Read the surface pixels. Note that the bmp image is upside down */ bits = (Uint8 *) surface->pixels + (surface->h * surface->pitch); switch (ExpandBMP) { case 1: bmpPitch = (biWidth + 7) >> 3; pad = (((bmpPitch) % 4) ? (4 - ((bmpPitch) % 4)) : 0); break; case 4: bmpPitch = (biWidth + 1) >> 1; pad = (((bmpPitch) % 4) ? (4 - ((bmpPitch) % 4)) : 0); break; case 8: bmpPitch = biWidth; pad = (((bmpPitch) % 4) ? (4 - ((bmpPitch) % 4)) : 0); break; default: bmpPitch = biWidth * 4; pad = 0; break; } while (bits > (Uint8 *) surface->pixels) { bits -= surface->pitch; switch (ExpandBMP) { case 1: case 4: case 8: { Uint8 pixel = 0; int shift = (8 - ExpandBMP); for (i = 0; i < surface->w; ++i) { if (i % (8 / ExpandBMP) == 0) { if (!SDL_RWread(src, &pixel, 1, 1)) { IMG_SetError("Error reading from ICO"); was_error = SDL_TRUE; goto done; } } *((Uint32 *) bits + i) = (palette[pixel >> shift]); pixel <<= ExpandBMP; } } break; default: if (SDL_RWread(src, bits, 1, surface->pitch) != surface->pitch) { SDL_Error(SDL_EFREAD); was_error = SDL_TRUE; goto done; } break; } /* Skip padding bytes, ugh */ if (pad) { Uint8 padbyte; for (i = 0; i < pad; ++i) { SDL_RWread(src, &padbyte, 1, 1); } } } /* Read the mask pixels. Note that the bmp image is upside down */ bits = (Uint8 *) surface->pixels + (surface->h * surface->pitch); ExpandBMP = 1; bmpPitch = (biWidth + 7) >> 3; pad = (((bmpPitch) % 4) ? (4 - ((bmpPitch) % 4)) : 0); while (bits > (Uint8 *) surface->pixels) { Uint8 pixel = 0; int shift = (8 - ExpandBMP); bits -= surface->pitch; for (i = 0; i < surface->w; ++i) { if (i % (8 / ExpandBMP) == 0) { if (!SDL_RWread(src, &pixel, 1, 1)) { IMG_SetError("Error reading from ICO"); was_error = SDL_TRUE; goto done; } } *((Uint32 *) bits + i) |= ((pixel >> shift) ? 0 : 0xFF000000); pixel <<= ExpandBMP; } /* Skip padding bytes, ugh */ if (pad) { Uint8 padbyte; for (i = 0; i < pad; ++i) { SDL_RWread(src, &padbyte, 1, 1); } } } done: if (was_error) { if (src) { SDL_RWseek(src, fp_offset, RW_SEEK_SET); } if (surface) { SDL_FreeSurface(surface); } surface = NULL; } if (freesrc && src) { SDL_RWclose(src); } return (surface); } /* Load a BMP type image from an SDL datasource */ SDL_Surface *IMG_LoadBMP_RW(SDL_RWops *src) { return(LoadBMP_RW(src, 0)); } /* Load a ICO type image from an SDL datasource */ SDL_Surface *IMG_LoadICO_RW(SDL_RWops *src) { return(LoadICOCUR_RW(src, 1, 0)); } /* Load a CUR type image from an SDL datasource */ SDL_Surface *IMG_LoadCUR_RW(SDL_RWops *src) { return(LoadICOCUR_RW(src, 2, 0)); } #else /* See if an image is contained in a data source */ int IMG_isBMP(SDL_RWops *src) { return(0); } int IMG_isICO(SDL_RWops *src) { return(0); } int IMG_isCUR(SDL_RWops *src) { return(0); } /* Load a BMP type image from an SDL datasource */ SDL_Surface *IMG_LoadBMP_RW(SDL_RWops *src) { return(NULL); } /* Load a BMP type image from an SDL datasource */ SDL_Surface *IMG_LoadCUR_RW(SDL_RWops *src) { return(NULL); } /* Load a BMP type image from an SDL datasource */ SDL_Surface *IMG_LoadICO_RW(SDL_RWops *src) { return(NULL); } #endif /* LOAD_BMP */ #endif /* !defined(__APPLE__) || defined(SDL_IMAGE_USE_COMMON_BACKEND) */
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG_bmp.c
C
apache-2.0
29,201
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #if !defined(__APPLE__) || defined(SDL_IMAGE_USE_COMMON_BACKEND) /* This is a GIF image file loading framework */ #include "SDL_image.h" #ifdef LOAD_GIF /* See if an image is contained in a data source */ int IMG_isGIF(SDL_RWops *src) { Sint64 start; int is_GIF; char magic[6]; if ( !src ) return 0; start = SDL_RWtell(src); is_GIF = 0; if ( SDL_RWread(src, magic, sizeof(magic), 1) ) { if ( (SDL_strncmp(magic, "GIF", 3) == 0) && ((SDL_memcmp(magic + 3, "87a", 3) == 0) || (SDL_memcmp(magic + 3, "89a", 3) == 0)) ) { is_GIF = 1; } } SDL_RWseek(src, start, RW_SEEK_SET); return(is_GIF); } /* Code from here to end of file has been adapted from XPaint: */ /* +-------------------------------------------------------------------+ */ /* | Copyright 1990, 1991, 1993 David Koblas. | */ /* | Copyright 1996 Torsten Martinsen. | */ /* | Permission to use, copy, modify, and distribute this software | */ /* | and its documentation for any purpose and without fee is hereby | */ /* | granted, provided that the above copyright notice appear in all | */ /* | copies and that both that copyright notice and this permission | */ /* | notice appear in supporting documentation. This software is | */ /* | provided "as is" without express or implied warranty. | */ /* +-------------------------------------------------------------------+ */ /* Adapted for use in SDL by Sam Lantinga -- 7/20/98 */ #define USED_BY_SDL #include <stdio.h> #include <string.h> #ifdef USED_BY_SDL /* Changes to work with SDL: Include SDL header file Use SDL_Surface rather than xpaint Image structure Define SDL versions of RWSetMsg(), ImageNewCmap() and ImageSetCmap() */ #include "SDL.h" #define Image SDL_Surface #define RWSetMsg IMG_SetError #define ImageNewCmap(w, h, s) SDL_CreateRGBSurface(SDL_SWSURFACE,w,h,8,0,0,0,0) #define ImageSetCmap(s, i, R, G, B) do { \ s->format->palette->colors[i].r = R; \ s->format->palette->colors[i].g = G; \ s->format->palette->colors[i].b = B; \ } while (0) /* * * * * */ #else /* Original XPaint sources */ #include "image.h" #include "rwTable.h" #define SDL_RWops FILE #define SDL_RWclose fclose #endif /* USED_BY_SDL */ #define MAXCOLORMAPSIZE 256 #define TRUE 1 #define FALSE 0 #define CM_RED 0 #define CM_GREEN 1 #define CM_BLUE 2 #define MAX_LWZ_BITS 12 #define INTERLACE 0x40 #define LOCALCOLORMAP 0x80 #define BitSet(byte, bit) (((byte) & (bit)) == (bit)) #define ReadOK(file,buffer,len) SDL_RWread(file, buffer, len, 1) #define LM_to_uint(a,b) (((b)<<8)|(a)) typedef struct { struct { unsigned int Width; unsigned int Height; unsigned char ColorMap[3][MAXCOLORMAPSIZE]; unsigned int BitPixel; unsigned int ColorResolution; unsigned int Background; unsigned int AspectRatio; int GrayScale; } GifScreen; struct { int transparent; int delayTime; int inputFlag; int disposal; } Gif89; unsigned char buf[280]; int curbit, lastbit, done, last_byte; int fresh; int code_size, set_code_size; int max_code, max_code_size; int firstcode, oldcode; int clear_code, end_code; int table[2][(1 << MAX_LWZ_BITS)]; int stack[(1 << (MAX_LWZ_BITS)) * 2], *sp; int ZeroDataBlock; } State_t; static int ReadColorMap(SDL_RWops * src, int number, unsigned char buffer[3][MAXCOLORMAPSIZE], int *flag); static int DoExtension(SDL_RWops * src, int label, State_t * state); static int GetDataBlock(SDL_RWops * src, unsigned char *buf, State_t * state); static int GetCode(SDL_RWops * src, int code_size, int flag, State_t * state); static int LWZReadByte(SDL_RWops * src, int flag, int input_code_size, State_t * state); static Image *ReadImage(SDL_RWops * src, int len, int height, int, unsigned char cmap[3][MAXCOLORMAPSIZE], int gray, int interlace, int ignore, State_t * state); Image * IMG_LoadGIF_RW(SDL_RWops *src) { Sint64 start; unsigned char buf[16]; unsigned char c; unsigned char localColorMap[3][MAXCOLORMAPSIZE]; int grayScale; int useGlobalColormap; int bitPixel; int imageCount = 0; char version[4]; int imageNumber = 1; Image *image = NULL; State_t state; state.ZeroDataBlock = FALSE; state.fresh = FALSE; state.last_byte = 0; if ( src == NULL ) { return NULL; } start = SDL_RWtell(src); if (!ReadOK(src, buf, 6)) { RWSetMsg("error reading magic number"); goto done; } if (SDL_strncmp((char *) buf, "GIF", 3) != 0) { RWSetMsg("not a GIF file"); goto done; } SDL_memcpy(version, (char *) buf + 3, 3); version[3] = '\0'; if ((SDL_strcmp(version, "87a") != 0) && (SDL_strcmp(version, "89a") != 0)) { RWSetMsg("bad version number, not '87a' or '89a'"); goto done; } state.Gif89.transparent = -1; state.Gif89.delayTime = -1; state.Gif89.inputFlag = -1; state.Gif89.disposal = 0; if (!ReadOK(src, buf, 7)) { RWSetMsg("failed to read screen descriptor"); goto done; } state.GifScreen.Width = LM_to_uint(buf[0], buf[1]); state.GifScreen.Height = LM_to_uint(buf[2], buf[3]); state.GifScreen.BitPixel = 2 << (buf[4] & 0x07); state.GifScreen.ColorResolution = (((buf[4] & 0x70) >> 3) + 1); state.GifScreen.Background = buf[5]; state.GifScreen.AspectRatio = buf[6]; if (BitSet(buf[4], LOCALCOLORMAP)) { /* Global Colormap */ if (ReadColorMap(src, state.GifScreen.BitPixel, state.GifScreen.ColorMap, &state.GifScreen.GrayScale)) { RWSetMsg("error reading global colormap"); goto done; } } do { if (!ReadOK(src, &c, 1)) { RWSetMsg("EOF / read error on image data"); goto done; } if (c == ';') { /* GIF terminator */ if (imageCount < imageNumber) { RWSetMsg("only %d image%s found in file", imageCount, imageCount > 1 ? "s" : ""); goto done; } } if (c == '!') { /* Extension */ if (!ReadOK(src, &c, 1)) { RWSetMsg("EOF / read error on extention function code"); goto done; } DoExtension(src, c, &state); continue; } if (c != ',') { /* Not a valid start character */ continue; } ++imageCount; if (!ReadOK(src, buf, 9)) { RWSetMsg("couldn't read left/top/width/height"); goto done; } useGlobalColormap = !BitSet(buf[8], LOCALCOLORMAP); bitPixel = 1 << ((buf[8] & 0x07) + 1); if (!useGlobalColormap) { if (ReadColorMap(src, bitPixel, localColorMap, &grayScale)) { RWSetMsg("error reading local colormap"); goto done; } image = ReadImage(src, LM_to_uint(buf[4], buf[5]), LM_to_uint(buf[6], buf[7]), bitPixel, localColorMap, grayScale, BitSet(buf[8], INTERLACE), imageCount != imageNumber, &state); } else { image = ReadImage(src, LM_to_uint(buf[4], buf[5]), LM_to_uint(buf[6], buf[7]), state.GifScreen.BitPixel, state.GifScreen.ColorMap, state.GifScreen.GrayScale, BitSet(buf[8], INTERLACE), imageCount != imageNumber, &state); } } while (image == NULL); #ifdef USED_BY_SDL if ( state.Gif89.transparent >= 0 ) { SDL_SetColorKey(image, SDL_TRUE, state.Gif89.transparent); } #endif done: if ( image == NULL ) { SDL_RWseek(src, start, RW_SEEK_SET); } return image; } static int ReadColorMap(SDL_RWops *src, int number, unsigned char buffer[3][MAXCOLORMAPSIZE], int *gray) { int i; unsigned char rgb[3]; int flag; flag = TRUE; for (i = 0; i < number; ++i) { if (!ReadOK(src, rgb, sizeof(rgb))) { RWSetMsg("bad colormap"); return 1; } buffer[CM_RED][i] = rgb[0]; buffer[CM_GREEN][i] = rgb[1]; buffer[CM_BLUE][i] = rgb[2]; flag &= (rgb[0] == rgb[1] && rgb[1] == rgb[2]); } #if 0 if (flag) *gray = (number == 2) ? PBM_TYPE : PGM_TYPE; else *gray = PPM_TYPE; #else *gray = 0; #endif return FALSE; } static int DoExtension(SDL_RWops *src, int label, State_t * state) { unsigned char buf[256]; char *str; switch (label) { case 0x01: /* Plain Text Extension */ str = "Plain Text Extension"; break; case 0xff: /* Application Extension */ str = "Application Extension"; break; case 0xfe: /* Comment Extension */ str = "Comment Extension"; while (GetDataBlock(src, (unsigned char *) buf, state) > 0) ; return FALSE; case 0xf9: /* Graphic Control Extension */ str = "Graphic Control Extension"; (void) GetDataBlock(src, (unsigned char *) buf, state); state->Gif89.disposal = (buf[0] >> 2) & 0x7; state->Gif89.inputFlag = (buf[0] >> 1) & 0x1; state->Gif89.delayTime = LM_to_uint(buf[1], buf[2]); if ((buf[0] & 0x1) != 0) state->Gif89.transparent = buf[3]; while (GetDataBlock(src, (unsigned char *) buf, state) > 0) ; return FALSE; default: str = (char *)buf; SDL_snprintf(str, 256, "UNKNOWN (0x%02x)", label); break; } while (GetDataBlock(src, (unsigned char *) buf, state) > 0) ; return FALSE; } static int GetDataBlock(SDL_RWops *src, unsigned char *buf, State_t * state) { unsigned char count; if (!ReadOK(src, &count, 1)) { /* pm_message("error in getting DataBlock size" ); */ return -1; } state->ZeroDataBlock = count == 0; if ((count != 0) && (!ReadOK(src, buf, count))) { /* pm_message("error in reading DataBlock" ); */ return -1; } return count; } static int GetCode(SDL_RWops *src, int code_size, int flag, State_t * state) { int i, j, ret; unsigned char count; if (flag) { state->curbit = 0; state->lastbit = 0; state->done = FALSE; return 0; } if ((state->curbit + code_size) >= state->lastbit) { if (state->done) { if (state->curbit >= state->lastbit) RWSetMsg("ran off the end of my bits"); return -1; } state->buf[0] = state->buf[state->last_byte - 2]; state->buf[1] = state->buf[state->last_byte - 1]; if ((count = GetDataBlock(src, &state->buf[2], state)) <= 0) state->done = TRUE; state->last_byte = 2 + count; state->curbit = (state->curbit - state->lastbit) + 16; state->lastbit = (2 + count) * 8; } ret = 0; for (i = state->curbit, j = 0; j < code_size; ++i, ++j) ret |= ((state->buf[i / 8] & (1 << (i % 8))) != 0) << j; state->curbit += code_size; return ret; } static int LWZReadByte(SDL_RWops *src, int flag, int input_code_size, State_t * state) { int code, incode; register int i; /* Fixed buffer overflow found by Michael Skladnikiewicz */ if (input_code_size > MAX_LWZ_BITS) return -1; if (flag) { state->set_code_size = input_code_size; state->code_size = state->set_code_size + 1; state->clear_code = 1 << state->set_code_size; state->end_code = state->clear_code + 1; state->max_code_size = 2 * state->clear_code; state->max_code = state->clear_code + 2; GetCode(src, 0, TRUE, state); state->fresh = TRUE; for (i = 0; i < state->clear_code; ++i) { state->table[0][i] = 0; state->table[1][i] = i; } state->table[1][0] = 0; for (; i < (1 << MAX_LWZ_BITS); ++i) state->table[0][i] = 0; state->sp = state->stack; return 0; } else if (state->fresh) { state->fresh = FALSE; do { state->firstcode = state->oldcode = GetCode(src, state->code_size, FALSE, state); } while (state->firstcode == state->clear_code); return state->firstcode; } if (state->sp > state->stack) return *--state->sp; while ((code = GetCode(src, state->code_size, FALSE, state)) >= 0) { if (code == state->clear_code) { for (i = 0; i < state->clear_code; ++i) { state->table[0][i] = 0; state->table[1][i] = i; } for (; i < (1 << MAX_LWZ_BITS); ++i) state->table[0][i] = state->table[1][i] = 0; state->code_size = state->set_code_size + 1; state->max_code_size = 2 * state->clear_code; state->max_code = state->clear_code + 2; state->sp = state->stack; state->firstcode = state->oldcode = GetCode(src, state->code_size, FALSE, state); return state->firstcode; } else if (code == state->end_code) { int count; unsigned char buf[260]; if (state->ZeroDataBlock) return -2; while ((count = GetDataBlock(src, buf, state)) > 0) ; if (count != 0) { /* * pm_message("missing EOD in data stream (common occurence)"); */ } return -2; } incode = code; if (code >= state->max_code) { *state->sp++ = state->firstcode; code = state->oldcode; } while (code >= state->clear_code) { /* Guard against buffer overruns */ if (code < 0 || code >= (1 << MAX_LWZ_BITS)) { RWSetMsg("invalid LWZ data"); return -3; } *state->sp++ = state->table[1][code]; if (code == state->table[0][code]) { RWSetMsg("circular table entry BIG ERROR"); return -3; } code = state->table[0][code]; } /* Guard against buffer overruns */ if (code < 0 || code >= (1 << MAX_LWZ_BITS)) { RWSetMsg("invalid LWZ data"); return -4; } *state->sp++ = state->firstcode = state->table[1][code]; if ((code = state->max_code) < (1 << MAX_LWZ_BITS)) { state->table[0][code] = state->oldcode; state->table[1][code] = state->firstcode; ++state->max_code; if ((state->max_code >= state->max_code_size) && (state->max_code_size < (1 << MAX_LWZ_BITS))) { state->max_code_size *= 2; ++state->code_size; } } state->oldcode = incode; if (state->sp > state->stack) return *--state->sp; } return code; } static Image * ReadImage(SDL_RWops * src, int len, int height, int cmapSize, unsigned char cmap[3][MAXCOLORMAPSIZE], int gray, int interlace, int ignore, State_t * state) { Image *image; unsigned char c; int i, v; int xpos = 0, ypos = 0, pass = 0; /* ** Initialize the compression routines */ if (!ReadOK(src, &c, 1)) { RWSetMsg("EOF / read error on image data"); return NULL; } if (LWZReadByte(src, TRUE, c, state) < 0) { RWSetMsg("error reading image"); return NULL; } /* ** If this is an "uninteresting picture" ignore it. */ if (ignore) { while (LWZReadByte(src, FALSE, c, state) >= 0) ; return NULL; } image = ImageNewCmap(len, height, cmapSize); for (i = 0; i < cmapSize; i++) ImageSetCmap(image, i, cmap[CM_RED][i], cmap[CM_GREEN][i], cmap[CM_BLUE][i]); while ((v = LWZReadByte(src, FALSE, c, state)) >= 0) { #ifdef USED_BY_SDL ((Uint8 *)image->pixels)[xpos + ypos * image->pitch] = v; #else image->data[xpos + ypos * len] = v; #endif ++xpos; if (xpos == len) { xpos = 0; if (interlace) { switch (pass) { case 0: case 1: ypos += 8; break; case 2: ypos += 4; break; case 3: ypos += 2; break; } if (ypos >= height) { ++pass; switch (pass) { case 1: ypos = 4; break; case 2: ypos = 2; break; case 3: ypos = 1; break; default: goto fini; } } } else { ++ypos; } } if (ypos >= height) break; } fini: return image; } #else /* See if an image is contained in a data source */ int IMG_isGIF(SDL_RWops *src) { return(0); } /* Load a GIF type image from an SDL datasource */ SDL_Surface *IMG_LoadGIF_RW(SDL_RWops *src) { return(NULL); } #endif /* LOAD_GIF */ #endif /* !defined(__APPLE__) || defined(SDL_IMAGE_USE_COMMON_BACKEND) */
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG_gif.c
C
apache-2.0
17,736
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* This is a JPEG image file loading framework */ #include <stdio.h> #include <setjmp.h> #include "SDL_image.h" #if !(defined(__APPLE__) || defined(SDL_IMAGE_USE_WIC_BACKEND)) || defined(SDL_IMAGE_USE_COMMON_BACKEND) #ifdef LOAD_JPG #define USE_JPEGLIB #include <jpeglib.h> #ifdef JPEG_TRUE /* MinGW version of jpeg-8.x renamed TRUE to JPEG_TRUE etc. */ typedef JPEG_boolean boolean; #define TRUE JPEG_TRUE #define FALSE JPEG_FALSE #endif /* Define this for fast loading and not as good image quality */ #define FAST_JPEG /* Define this for quicker (but less perfect) JPEG identification */ #define FAST_IS_JPEG static struct { int loaded; void *handle; void (*jpeg_calc_output_dimensions) (j_decompress_ptr cinfo); void (*jpeg_CreateDecompress) (j_decompress_ptr cinfo, int version, size_t structsize); void (*jpeg_destroy_decompress) (j_decompress_ptr cinfo); boolean (*jpeg_finish_decompress) (j_decompress_ptr cinfo); int (*jpeg_read_header) (j_decompress_ptr cinfo, boolean require_image); JDIMENSION (*jpeg_read_scanlines) (j_decompress_ptr cinfo, JSAMPARRAY scanlines, JDIMENSION max_lines); boolean (*jpeg_resync_to_restart) (j_decompress_ptr cinfo, int desired); boolean (*jpeg_start_decompress) (j_decompress_ptr cinfo); void (*jpeg_CreateCompress) (j_compress_ptr cinfo, int version, size_t structsize); void (*jpeg_start_compress) (j_compress_ptr cinfo, boolean write_all_tables); void (*jpeg_set_quality) (j_compress_ptr cinfo, int quality, boolean force_baseline); void (*jpeg_set_defaults) (j_compress_ptr cinfo); JDIMENSION (*jpeg_write_scanlines) (j_compress_ptr cinfo, JSAMPARRAY scanlines, JDIMENSION num_lines); void (*jpeg_finish_compress) (j_compress_ptr cinfo); void (*jpeg_destroy_compress) (j_compress_ptr cinfo); struct jpeg_error_mgr * (*jpeg_std_error) (struct jpeg_error_mgr * err); } lib; #ifdef LOAD_JPG_DYNAMIC #define FUNCTION_LOADER(FUNC, SIG) \ lib.FUNC = (SIG) SDL_LoadFunction(lib.handle, #FUNC); \ if (lib.FUNC == NULL) { SDL_UnloadObject(lib.handle); return -1; } #else #define FUNCTION_LOADER(FUNC, SIG) \ lib.FUNC = FUNC; #endif int IMG_InitJPG() { if ( lib.loaded == 0 ) { #ifdef LOAD_JPG_DYNAMIC lib.handle = SDL_LoadObject(LOAD_JPG_DYNAMIC); if ( lib.handle == NULL ) { return -1; } #endif FUNCTION_LOADER(jpeg_calc_output_dimensions, void (*) (j_decompress_ptr cinfo)) FUNCTION_LOADER(jpeg_CreateDecompress, void (*) (j_decompress_ptr cinfo, int version, size_t structsize)) FUNCTION_LOADER(jpeg_destroy_decompress, void (*) (j_decompress_ptr cinfo)) FUNCTION_LOADER(jpeg_finish_decompress, boolean (*) (j_decompress_ptr cinfo)) FUNCTION_LOADER(jpeg_read_header, int (*) (j_decompress_ptr cinfo, boolean require_image)) FUNCTION_LOADER(jpeg_read_scanlines, JDIMENSION (*) (j_decompress_ptr cinfo, JSAMPARRAY scanlines, JDIMENSION max_lines)) FUNCTION_LOADER(jpeg_resync_to_restart, boolean (*) (j_decompress_ptr cinfo, int desired)) FUNCTION_LOADER(jpeg_start_decompress, boolean (*) (j_decompress_ptr cinfo)) FUNCTION_LOADER(jpeg_CreateCompress, void (*) (j_compress_ptr cinfo, int version, size_t structsize)) FUNCTION_LOADER(jpeg_start_compress, void (*) (j_compress_ptr cinfo, boolean write_all_tables)) FUNCTION_LOADER(jpeg_set_quality, void (*) (j_compress_ptr cinfo, int quality, boolean force_baseline)) FUNCTION_LOADER(jpeg_set_defaults, void (*) (j_compress_ptr cinfo)) FUNCTION_LOADER(jpeg_write_scanlines, JDIMENSION (*) (j_compress_ptr cinfo, JSAMPARRAY scanlines, JDIMENSION num_lines)) FUNCTION_LOADER(jpeg_finish_compress, void (*) (j_compress_ptr cinfo)) FUNCTION_LOADER(jpeg_destroy_compress, void (*) (j_compress_ptr cinfo)) FUNCTION_LOADER(jpeg_std_error, struct jpeg_error_mgr * (*) (struct jpeg_error_mgr * err)) } ++lib.loaded; return 0; } void IMG_QuitJPG() { if ( lib.loaded == 0 ) { return; } if ( lib.loaded == 1 ) { #ifdef LOAD_JPG_DYNAMIC SDL_UnloadObject(lib.handle); #endif } --lib.loaded; } /* See if an image is contained in a data source */ int IMG_isJPG(SDL_RWops *src) { Sint64 start; int is_JPG; int in_scan; Uint8 magic[4]; /* This detection code is by Steaphan Greene <stea@cs.binghamton.edu> */ /* Blame me, not Sam, if this doesn't work right. */ /* And don't forget to report the problem to the the sdl list too! */ if ( !src ) return 0; start = SDL_RWtell(src); is_JPG = 0; in_scan = 0; if ( SDL_RWread(src, magic, 2, 1) ) { if ( (magic[0] == 0xFF) && (magic[1] == 0xD8) ) { is_JPG = 1; while (is_JPG == 1) { if(SDL_RWread(src, magic, 1, 2) != 2) { is_JPG = 0; } else if( (magic[0] != 0xFF) && (in_scan == 0) ) { is_JPG = 0; } else if( (magic[0] != 0xFF) || (magic[1] == 0xFF) ) { /* Extra padding in JPEG (legal) */ /* or this is data and we are scanning */ SDL_RWseek(src, -1, RW_SEEK_CUR); } else if(magic[1] == 0xD9) { /* Got to end of good JPEG */ break; } else if( (in_scan == 1) && (magic[1] == 0x00) ) { /* This is an encoded 0xFF within the data */ } else if( (magic[1] >= 0xD0) && (magic[1] < 0xD9) ) { /* These have nothing else */ } else if(SDL_RWread(src, magic+2, 1, 2) != 2) { is_JPG = 0; } else { /* Yes, it's big-endian */ Sint64 innerStart; Uint32 size; Sint64 end; innerStart = SDL_RWtell(src); size = (magic[2] << 8) + magic[3]; end = SDL_RWseek(src, size-2, RW_SEEK_CUR); if ( end != innerStart + size - 2 ) is_JPG = 0; if ( magic[1] == 0xDA ) { /* Now comes the actual JPEG meat */ #ifdef FAST_IS_JPEG /* Ok, I'm convinced. It is a JPEG. */ break; #else /* I'm not convinced. Prove it! */ in_scan = 1; #endif } } } } } SDL_RWseek(src, start, RW_SEEK_SET); return(is_JPG); } #define INPUT_BUFFER_SIZE 4096 typedef struct { struct jpeg_source_mgr pub; SDL_RWops *ctx; Uint8 buffer[INPUT_BUFFER_SIZE]; } my_source_mgr; /* * Initialize source --- called by jpeg_read_header * before any data is actually read. */ static void init_source (j_decompress_ptr cinfo) { /* We don't actually need to do anything */ return; } /* * Fill the input buffer --- called whenever buffer is emptied. */ static boolean fill_input_buffer (j_decompress_ptr cinfo) { my_source_mgr * src = (my_source_mgr *) cinfo->src; int nbytes; nbytes = (int)SDL_RWread(src->ctx, src->buffer, 1, INPUT_BUFFER_SIZE); if (nbytes <= 0) { /* Insert a fake EOI marker */ src->buffer[0] = (Uint8) 0xFF; src->buffer[1] = (Uint8) JPEG_EOI; nbytes = 2; } src->pub.next_input_byte = src->buffer; src->pub.bytes_in_buffer = nbytes; return TRUE; } /* * Skip data --- used to skip over a potentially large amount of * uninteresting data (such as an APPn marker). * * Writers of suspendable-input applications must note that skip_input_data * is not granted the right to give a suspension return. If the skip extends * beyond the data currently in the buffer, the buffer can be marked empty so * that the next read will cause a fill_input_buffer call that can suspend. * Arranging for additional bytes to be discarded before reloading the input * buffer is the application writer's problem. */ static void skip_input_data (j_decompress_ptr cinfo, long num_bytes) { my_source_mgr * src = (my_source_mgr *) cinfo->src; /* Just a dumb implementation for now. Could use fseek() except * it doesn't work on pipes. Not clear that being smart is worth * any trouble anyway --- large skips are infrequent. */ if (num_bytes > 0) { while (num_bytes > (long) src->pub.bytes_in_buffer) { num_bytes -= (long) src->pub.bytes_in_buffer; (void) src->pub.fill_input_buffer(cinfo); /* note we assume that fill_input_buffer will never * return FALSE, so suspension need not be handled. */ } src->pub.next_input_byte += (size_t) num_bytes; src->pub.bytes_in_buffer -= (size_t) num_bytes; } } /* * Terminate source --- called by jpeg_finish_decompress * after all data has been read. */ static void term_source (j_decompress_ptr cinfo) { /* We don't actually need to do anything */ return; } /* * Prepare for input from a stdio stream. * The caller must have already opened the stream, and is responsible * for closing it after finishing decompression. */ static void jpeg_SDL_RW_src (j_decompress_ptr cinfo, SDL_RWops *ctx) { my_source_mgr *src; /* The source object and input buffer are made permanent so that a series * of JPEG images can be read from the same file by calling jpeg_stdio_src * only before the first one. (If we discarded the buffer at the end of * one image, we'd likely lose the start of the next one.) * This makes it unsafe to use this manager and a different source * manager serially with the same JPEG object. Caveat programmer. */ if (cinfo->src == NULL) { /* first time for this JPEG object? */ cinfo->src = (struct jpeg_source_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_source_mgr)); src = (my_source_mgr *) cinfo->src; } src = (my_source_mgr *) cinfo->src; src->pub.init_source = init_source; src->pub.fill_input_buffer = fill_input_buffer; src->pub.skip_input_data = skip_input_data; src->pub.resync_to_restart = lib.jpeg_resync_to_restart; /* use default method */ src->pub.term_source = term_source; src->ctx = ctx; src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */ src->pub.next_input_byte = NULL; /* until buffer loaded */ } struct my_error_mgr { struct jpeg_error_mgr errmgr; jmp_buf escape; }; static void my_error_exit(j_common_ptr cinfo) { struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err; longjmp(err->escape, 1); } static void output_no_message(j_common_ptr cinfo) { /* do nothing */ } /* Load a JPEG type image from an SDL datasource */ SDL_Surface *IMG_LoadJPG_RW(SDL_RWops *src) { Sint64 start; struct jpeg_decompress_struct cinfo; JSAMPROW rowptr[1]; SDL_Surface *volatile surface = NULL; struct my_error_mgr jerr; if ( !src ) { /* The error message has been set in SDL_RWFromFile */ return NULL; } start = SDL_RWtell(src); if ( (IMG_Init(IMG_INIT_JPG) & IMG_INIT_JPG) == 0 ) { return NULL; } /* Create a decompression structure and load the JPEG header */ cinfo.err = lib.jpeg_std_error(&jerr.errmgr); jerr.errmgr.error_exit = my_error_exit; jerr.errmgr.output_message = output_no_message; if(setjmp(jerr.escape)) { /* If we get here, libjpeg found an error */ lib.jpeg_destroy_decompress(&cinfo); if ( surface != NULL ) { SDL_FreeSurface(surface); } SDL_RWseek(src, start, RW_SEEK_SET); IMG_SetError("JPEG loading error"); return NULL; } lib.jpeg_create_decompress(&cinfo); jpeg_SDL_RW_src(&cinfo, src); lib.jpeg_read_header(&cinfo, TRUE); if(cinfo.num_components == 4) { /* Set 32-bit Raw output */ cinfo.out_color_space = JCS_CMYK; cinfo.quantize_colors = FALSE; lib.jpeg_calc_output_dimensions(&cinfo); /* Allocate an output surface to hold the image */ surface = SDL_CreateRGBSurface(SDL_SWSURFACE, cinfo.output_width, cinfo.output_height, 32, #if SDL_BYTEORDER == SDL_LIL_ENDIAN 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); #else 0x0000FF00, 0x00FF0000, 0xFF000000, 0x000000FF); #endif } else { /* Set 24-bit RGB output */ cinfo.out_color_space = JCS_RGB; cinfo.quantize_colors = FALSE; #ifdef FAST_JPEG cinfo.scale_num = 1; cinfo.scale_denom = 1; cinfo.dct_method = JDCT_FASTEST; cinfo.do_fancy_upsampling = FALSE; #endif lib.jpeg_calc_output_dimensions(&cinfo); /* Allocate an output surface to hold the image */ surface = SDL_CreateRGBSurface(SDL_SWSURFACE, cinfo.output_width, cinfo.output_height, 24, #if SDL_BYTEORDER == SDL_LIL_ENDIAN 0x0000FF, 0x00FF00, 0xFF0000, #else 0xFF0000, 0x00FF00, 0x0000FF, #endif 0); } if ( surface == NULL ) { lib.jpeg_destroy_decompress(&cinfo); SDL_RWseek(src, start, RW_SEEK_SET); IMG_SetError("Out of memory"); return NULL; } /* Decompress the image */ lib.jpeg_start_decompress(&cinfo); while ( cinfo.output_scanline < cinfo.output_height ) { rowptr[0] = (JSAMPROW)(Uint8 *)surface->pixels + cinfo.output_scanline * surface->pitch; lib.jpeg_read_scanlines(&cinfo, rowptr, (JDIMENSION) 1); } lib.jpeg_finish_decompress(&cinfo); lib.jpeg_destroy_decompress(&cinfo); return(surface); } #define OUTPUT_BUFFER_SIZE 4096 typedef struct { struct jpeg_destination_mgr pub; SDL_RWops *ctx; Uint8 buffer[OUTPUT_BUFFER_SIZE]; } my_destination_mgr; static void init_destination(j_compress_ptr cinfo) { /* We don't actually need to do anything */ return; } static boolean empty_output_buffer(j_compress_ptr cinfo) { my_destination_mgr * dest = (my_destination_mgr *)cinfo->dest; /* In typical applications, it should write out the *entire* buffer */ SDL_RWwrite(dest->ctx, dest->buffer, 1, OUTPUT_BUFFER_SIZE); dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = OUTPUT_BUFFER_SIZE; return TRUE; } static void term_destination(j_compress_ptr cinfo) { my_destination_mgr * dest = (my_destination_mgr *)cinfo->dest; /* In most applications, this must flush any data remaining in the buffer */ SDL_RWwrite(dest->ctx, dest->buffer, 1, OUTPUT_BUFFER_SIZE - dest->pub.free_in_buffer); } static void jpeg_SDL_RW_dest(j_compress_ptr cinfo, SDL_RWops *ctx) { my_destination_mgr *dest; if (cinfo->dest == NULL) { cinfo->dest = (struct jpeg_destination_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_PERMANENT, sizeof(my_destination_mgr)); dest = (my_destination_mgr *)cinfo->dest; } dest = (my_destination_mgr *)cinfo->dest; dest->pub.init_destination = init_destination; dest->pub.empty_output_buffer = empty_output_buffer; dest->pub.term_destination = term_destination; dest->ctx = ctx; dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = OUTPUT_BUFFER_SIZE; } static int IMG_SaveJPG_RW_jpeglib(SDL_Surface *surface, SDL_RWops *dst, int freedst, int quality) { #if SDL_BYTEORDER == SDL_LIL_ENDIAN static const Uint32 jpg_format = SDL_PIXELFORMAT_RGB24; #else static const Uint32 jpg_format = SDL_PIXELFORMAT_BGR24; #endif struct jpeg_compress_struct cinfo; struct my_error_mgr jerr; JSAMPROW row_pointer[1]; SDL_Surface* jpeg_surface = surface; int result = -1; if (!dst) { SDL_SetError("Passed NULL dst"); goto done; } if (!IMG_Init(IMG_INIT_JPG)) { goto done; } /* Convert surface to format we can save */ if (surface->format->format != jpg_format) { jpeg_surface = SDL_ConvertSurfaceFormat(surface, jpg_format, 0); if (!jpeg_surface) { goto done; } } /* Create a decompression structure and load the JPEG header */ cinfo.err = lib.jpeg_std_error(&jerr.errmgr); jerr.errmgr.error_exit = my_error_exit; jerr.errmgr.output_message = output_no_message; lib.jpeg_create_compress(&cinfo); jpeg_SDL_RW_dest(&cinfo, dst); cinfo.image_width = jpeg_surface->w; cinfo.image_height = jpeg_surface->h; cinfo.in_color_space = JCS_RGB; cinfo.input_components = 3; lib.jpeg_set_defaults(&cinfo); lib.jpeg_set_quality(&cinfo, quality, TRUE); lib.jpeg_start_compress(&cinfo, TRUE); while (cinfo.next_scanline < cinfo.image_height) { int offset = cinfo.next_scanline * jpeg_surface->pitch; row_pointer[0] = ((Uint8*)jpeg_surface->pixels) + offset; lib.jpeg_write_scanlines(&cinfo, row_pointer, 1); } lib.jpeg_finish_compress(&cinfo); lib.jpeg_destroy_compress(&cinfo); if (jpeg_surface != surface) { SDL_FreeSurface(jpeg_surface); } result = 0; done: if (freedst) { SDL_RWclose(dst); } return result; } #else int IMG_InitJPG() { IMG_SetError("JPEG images are not supported"); return(-1); } void IMG_QuitJPG() { } /* See if an image is contained in a data source */ int IMG_isJPG(SDL_RWops *src) { return(0); } /* Load a JPEG type image from an SDL datasource */ SDL_Surface *IMG_LoadJPG_RW(SDL_RWops *src) { return(NULL); } #endif /* LOAD_JPG */ #endif /* !defined(__APPLE__) || defined(SDL_IMAGE_USE_COMMON_BACKEND) */ /* We'll always have JPG save support */ #define SAVE_JPG #ifdef SAVE_JPG int IMG_SaveJPG(SDL_Surface *surface, const char *file, int quality) { SDL_RWops *dst = SDL_RWFromFile(file, "wb"); if (dst) { return IMG_SaveJPG_RW(surface, dst, 1, quality); } else { return -1; } } int IMG_SaveJPG_RW(SDL_Surface *surface, SDL_RWops *dst, int freedst, int quality) { #ifdef USE_JPEGLIB return IMG_SaveJPG_RW_jpeglib(surface, dst, freedst, quality); #else return IMG_SetError("SDL_image not built with jpeglib, saving not supported"); #endif } #endif /* SAVE_JPG */
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG_jpg.c
C
apache-2.0
19,433
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* This is a ILBM image file loading framework Load IFF pictures, PBM & ILBM packing methods, with or without stencil Written by Daniel Morais ( Daniel AT Morais DOT com ) in September 2001. 24 bits ILBM files support added by Marc Le Douarain (http://www.multimania.com/mavati) in December 2002. EHB and HAM (specific Amiga graphic chip modes) support added by Marc Le Douarain (http://www.multimania.com/mavati) in December 2003. Stencil and colorkey fixes by David Raulo (david.raulo AT free DOT fr) in February 2004. Buffer overflow fix in RLE decompression by David Raulo in January 2008. */ #include "SDL_endian.h" #include "SDL_image.h" #ifdef LOAD_LBM #define MAXCOLORS 256 /* Structure for an IFF picture ( BMHD = Bitmap Header ) */ typedef struct { Uint16 w, h; /* width & height of the bitmap in pixels */ Sint16 x, y; /* screen coordinates of the bitmap */ Uint8 planes; /* number of planes of the bitmap */ Uint8 mask; /* mask type ( 0 => no mask ) */ Uint8 tcomp; /* compression type */ Uint8 pad1; /* dummy value, for padding */ Uint16 tcolor; /* transparent color */ Uint8 xAspect, /* pixel aspect ratio */ yAspect; Sint16 Lpage; /* width of the screen in pixels */ Sint16 Hpage; /* height of the screen in pixels */ } BMHD; int IMG_isLBM( SDL_RWops *src ) { Sint64 start; int is_LBM; Uint8 magic[4+4+4]; if ( !src ) return 0; start = SDL_RWtell(src); is_LBM = 0; if ( SDL_RWread( src, magic, sizeof(magic), 1 ) ) { if ( !SDL_memcmp( magic, "FORM", 4 ) && ( !SDL_memcmp( magic + 8, "PBM ", 4 ) || !SDL_memcmp( magic + 8, "ILBM", 4 ) ) ) { is_LBM = 1; } } SDL_RWseek(src, start, RW_SEEK_SET); return( is_LBM ); } SDL_Surface *IMG_LoadLBM_RW( SDL_RWops *src ) { Sint64 start; SDL_Surface *Image; Uint8 id[4], pbm, colormap[MAXCOLORS*3], *MiniBuf, *ptr, count, color, msk; Uint32 size, bytesloaded, nbcolors; Uint32 i, j, bytesperline, nbplanes, stencil, plane, h; Uint32 remainingbytes; Uint32 width; BMHD bmhd; char *error; Uint8 flagHAM,flagEHB; Image = NULL; error = NULL; MiniBuf = NULL; if ( !src ) { /* The error message has been set in SDL_RWFromFile */ return NULL; } start = SDL_RWtell(src); if ( !SDL_RWread( src, id, 4, 1 ) ) { error="error reading IFF chunk"; goto done; } /* Should be the size of the file minus 4+4 ( 'FORM'+size ) */ if ( !SDL_RWread( src, &size, 4, 1 ) ) { error="error reading IFF chunk size"; goto done; } /* As size is not used here, no need to swap it */ if ( SDL_memcmp( id, "FORM", 4 ) != 0 ) { error="not a IFF file"; goto done; } if ( !SDL_RWread( src, id, 4, 1 ) ) { error="error reading IFF chunk"; goto done; } pbm = 0; /* File format : PBM=Packed Bitmap, ILBM=Interleaved Bitmap */ if ( !SDL_memcmp( id, "PBM ", 4 ) ) pbm = 1; else if ( SDL_memcmp( id, "ILBM", 4 ) ) { error="not a IFF picture"; goto done; } nbcolors = 0; SDL_memset( &bmhd, 0, sizeof( BMHD ) ); flagHAM = 0; flagEHB = 0; while ( SDL_memcmp( id, "BODY", 4 ) != 0 ) { if ( !SDL_RWread( src, id, 4, 1 ) ) { error="error reading IFF chunk"; goto done; } if ( !SDL_RWread( src, &size, 4, 1 ) ) { error="error reading IFF chunk size"; goto done; } bytesloaded = 0; size = SDL_SwapBE32( size ); if ( !SDL_memcmp( id, "BMHD", 4 ) ) /* Bitmap header */ { if ( !SDL_RWread( src, &bmhd, sizeof( BMHD ), 1 ) ) { error="error reading BMHD chunk"; goto done; } bytesloaded = sizeof( BMHD ); bmhd.w = SDL_SwapBE16( bmhd.w ); bmhd.h = SDL_SwapBE16( bmhd.h ); bmhd.x = SDL_SwapBE16( bmhd.x ); bmhd.y = SDL_SwapBE16( bmhd.y ); bmhd.tcolor = SDL_SwapBE16( bmhd.tcolor ); bmhd.Lpage = SDL_SwapBE16( bmhd.Lpage ); bmhd.Hpage = SDL_SwapBE16( bmhd.Hpage ); } if ( !SDL_memcmp( id, "CMAP", 4 ) ) /* palette ( Color Map ) */ { if (size > sizeof (colormap)) { error="colormap size is too large"; goto done; } if ( !SDL_RWread( src, &colormap, size, 1 ) ) { error="error reading CMAP chunk"; goto done; } bytesloaded = size; nbcolors = size / 3; } if ( !SDL_memcmp( id, "CAMG", 4 ) ) /* Amiga ViewMode */ { Uint32 viewmodes; if ( !SDL_RWread( src, &viewmodes, sizeof(viewmodes), 1 ) ) { error="error reading CAMG chunk"; goto done; } bytesloaded = size; viewmodes = SDL_SwapBE32( viewmodes ); if ( viewmodes & 0x0800 ) flagHAM = 1; if ( viewmodes & 0x0080 ) flagEHB = 1; } if ( SDL_memcmp( id, "BODY", 4 ) ) { if ( size & 1 ) ++size; /* padding ! */ size -= bytesloaded; /* skip the remaining bytes of this chunk */ if ( size ) SDL_RWseek( src, size, RW_SEEK_CUR ); } } /* compute some usefull values, based on the bitmap header */ width = ( bmhd.w + 15 ) & 0xFFFFFFF0; /* Width in pixels modulo 16 */ bytesperline = ( ( bmhd.w + 15 ) / 16 ) * 2; nbplanes = bmhd.planes; if ( pbm ) /* File format : 'Packed Bitmap' */ { bytesperline *= 8; nbplanes = 1; } stencil = (bmhd.mask & 1); /* There is a mask ( 'stencil' ) */ /* Allocate memory for a temporary buffer ( used for decompression/deinterleaving ) */ MiniBuf = (Uint8 *)SDL_malloc( bytesperline * (nbplanes + stencil) ); if ( MiniBuf == NULL ) { error="not enough memory for temporary buffer"; goto done; } if ( ( Image = SDL_CreateRGBSurface( SDL_SWSURFACE, width, bmhd.h, (nbplanes==24 || flagHAM==1)?24:8, 0, 0, 0, 0 ) ) == NULL ) goto done; if ( bmhd.mask & 2 ) /* There is a transparent color */ SDL_SetColorKey( Image, SDL_TRUE, bmhd.tcolor ); /* Update palette informations */ /* There is no palette in 24 bits ILBM file */ if ( nbcolors>0 && flagHAM==0 ) { /* FIXME: Should this include the stencil? See comment below */ int nbrcolorsfinal = 1 << (nbplanes + stencil); ptr = &colormap[0]; for ( i=0; i<nbcolors; i++ ) { Image->format->palette->colors[i].r = *ptr++; Image->format->palette->colors[i].g = *ptr++; Image->format->palette->colors[i].b = *ptr++; } /* Amiga EHB mode (Extra-Half-Bright) */ /* 6 bitplanes mode with a 32 colors palette */ /* The 32 last colors are the same but divided by 2 */ /* Some Amiga pictures save 64 colors with 32 last wrong colors, */ /* they shouldn't !, and here we overwrite these 32 bad colors. */ if ( (nbcolors==32 || flagEHB ) && (1<<nbplanes)==64 ) { nbcolors = 64; ptr = &colormap[0]; for ( i=32; i<64; i++ ) { Image->format->palette->colors[i].r = (*ptr++)/2; Image->format->palette->colors[i].g = (*ptr++)/2; Image->format->palette->colors[i].b = (*ptr++)/2; } } /* If nbcolors < 2^nbplanes, repeat the colormap */ /* This happens when pictures have a stencil mask */ if ( nbrcolorsfinal > (1<<nbplanes) ) { nbrcolorsfinal = (1<<nbplanes); } for ( i=nbcolors; i < (Uint32)nbrcolorsfinal; i++ ) { Image->format->palette->colors[i].r = Image->format->palette->colors[i%nbcolors].r; Image->format->palette->colors[i].g = Image->format->palette->colors[i%nbcolors].g; Image->format->palette->colors[i].b = Image->format->palette->colors[i%nbcolors].b; } if ( !pbm ) Image->format->palette->ncolors = nbrcolorsfinal; } /* Get the bitmap */ for ( h=0; h < bmhd.h; h++ ) { /* uncompress the datas of each planes */ for ( plane=0; plane < (nbplanes+stencil); plane++ ) { ptr = MiniBuf + ( plane * bytesperline ); remainingbytes = bytesperline; if ( bmhd.tcomp == 1 ) /* Datas are compressed */ { do { if ( !SDL_RWread( src, &count, 1, 1 ) ) { error="error reading BODY chunk"; goto done; } if ( count & 0x80 ) { count ^= 0xFF; count += 2; /* now it */ if ( ( count > remainingbytes ) || !SDL_RWread( src, &color, 1, 1 ) ) { error="error reading BODY chunk"; goto done; } SDL_memset( ptr, color, count ); } else { ++count; if ( ( count > remainingbytes ) || !SDL_RWread( src, ptr, count, 1 ) ) { error="error reading BODY chunk"; goto done; } } ptr += count; remainingbytes -= count; } while ( remainingbytes > 0 ); } else { if ( !SDL_RWread( src, ptr, bytesperline, 1 ) ) { error="error reading BODY chunk"; goto done; } } } /* One line has been read, store it ! */ ptr = (Uint8 *)Image->pixels; if ( nbplanes==24 || flagHAM==1 ) ptr += h * width * 3; else ptr += h * width; if ( pbm ) /* File format : 'Packed Bitmap' */ { SDL_memcpy( ptr, MiniBuf, width ); } else /* We have to un-interlace the bits ! */ { if ( nbplanes!=24 && flagHAM==0 ) { size = ( width + 7 ) / 8; for ( i=0; i < size; i++ ) { SDL_memset( ptr, 0, 8 ); for ( plane=0; plane < (nbplanes + stencil); plane++ ) { color = *( MiniBuf + i + ( plane * bytesperline ) ); msk = 0x80; for ( j=0; j<8; j++ ) { if ( ( plane + j ) <= 7 ) ptr[j] |= (Uint8)( color & msk ) >> ( 7 - plane - j ); else ptr[j] |= (Uint8)( color & msk ) << ( plane + j - 7 ); msk >>= 1; } } ptr += 8; } } else { Uint32 finalcolor = 0; size = ( width + 7 ) / 8; /* 24 bitplanes ILBM : R0...R7,G0...G7,B0...B7 */ /* or HAM (6 bitplanes) or HAM8 (8 bitplanes) modes */ for ( i=0; i<width; i=i+8 ) { Uint8 maskBit = 0x80; for ( j=0; j<8; j++ ) { Uint32 pixelcolor = 0; Uint32 maskColor = 1; Uint8 dataBody; for ( plane=0; plane < nbplanes; plane++ ) { dataBody = MiniBuf[ plane*size+i/8 ]; if ( dataBody&maskBit ) pixelcolor = pixelcolor | maskColor; maskColor = maskColor<<1; } /* HAM : 12 bits RGB image (4 bits per color component) */ /* HAM8 : 18 bits RGB image (6 bits per color component) */ if ( flagHAM ) { switch( pixelcolor>>(nbplanes-2) ) { case 0: /* take direct color from palette */ finalcolor = colormap[ pixelcolor*3 ] + (colormap[ pixelcolor*3+1 ]<<8) + (colormap[ pixelcolor*3+2 ]<<16); break; case 1: /* modify only blue component */ finalcolor = finalcolor&0x00FFFF; finalcolor = finalcolor | (pixelcolor<<(16+(10-nbplanes))); break; case 2: /* modify only red component */ finalcolor = finalcolor&0xFFFF00; finalcolor = finalcolor | pixelcolor<<(10-nbplanes); break; case 3: /* modify only green component */ finalcolor = finalcolor&0xFF00FF; finalcolor = finalcolor | (pixelcolor<<(8+(10-nbplanes))); break; } } else { finalcolor = pixelcolor; } #if SDL_BYTEORDER == SDL_LIL_ENDIAN *ptr++ = (Uint8)(finalcolor>>16); *ptr++ = (Uint8)(finalcolor>>8); *ptr++ = (Uint8)(finalcolor); #else *ptr++ = (Uint8)(finalcolor); *ptr++ = (Uint8)(finalcolor>>8); *ptr++ = (Uint8)(finalcolor>>16); #endif maskBit = maskBit>>1; } } } } } done: if ( MiniBuf ) SDL_free( MiniBuf ); if ( error ) { SDL_RWseek(src, start, RW_SEEK_SET); if ( Image ) { SDL_FreeSurface( Image ); Image = NULL; } IMG_SetError( "%s", error ); } return( Image ); } #else /* LOAD_LBM */ /* See if an image is contained in a data source */ int IMG_isLBM(SDL_RWops *src) { return(0); } /* Load an IFF type image from an SDL datasource */ SDL_Surface *IMG_LoadLBM_RW(SDL_RWops *src) { return(NULL); } #endif /* LOAD_LBM */
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG_lbm.c
C
apache-2.0
16,331
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* * PCX file reader: * Supports: * 1..4 bits/pixel in multiplanar format (1 bit/plane/pixel) * 8 bits/pixel in single-planar format (8 bits/plane/pixel) * 24 bits/pixel in 3-plane format (8 bits/plane/pixel) * * (The <8bpp formats are expanded to 8bpp surfaces) * * Doesn't support: * single-planar packed-pixel formats other than 8bpp * 4-plane 32bpp format with a fourth "intensity" plane */ #include "SDL_endian.h" #include "SDL_image.h" #ifdef LOAD_PCX struct PCXheader { Uint8 Manufacturer; Uint8 Version; Uint8 Encoding; Uint8 BitsPerPixel; Sint16 Xmin, Ymin, Xmax, Ymax; Sint16 HDpi, VDpi; Uint8 Colormap[48]; Uint8 Reserved; Uint8 NPlanes; Sint16 BytesPerLine; Sint16 PaletteInfo; Sint16 HscreenSize; Sint16 VscreenSize; Uint8 Filler[54]; }; /* See if an image is contained in a data source */ int IMG_isPCX(SDL_RWops *src) { Sint64 start; int is_PCX; const int ZSoft_Manufacturer = 10; const int PC_Paintbrush_Version = 5; const int PCX_Uncompressed_Encoding = 0; const int PCX_RunLength_Encoding = 1; struct PCXheader pcxh; if ( !src ) return 0; start = SDL_RWtell(src); is_PCX = 0; if ( SDL_RWread(src, &pcxh, sizeof(pcxh), 1) == 1 ) { if ( (pcxh.Manufacturer == ZSoft_Manufacturer) && (pcxh.Version == PC_Paintbrush_Version) && (pcxh.Encoding == PCX_RunLength_Encoding || pcxh.Encoding == PCX_Uncompressed_Encoding) ) { is_PCX = 1; } } SDL_RWseek(src, start, RW_SEEK_SET); return(is_PCX); } /* Load a PCX type image from an SDL datasource */ SDL_Surface *IMG_LoadPCX_RW(SDL_RWops *src) { Sint64 start; struct PCXheader pcxh; Uint32 Rmask; Uint32 Gmask; Uint32 Bmask; Uint32 Amask; SDL_Surface *surface = NULL; int width, height; int y, bpl; Uint8 *row, *buf = NULL; char *error = NULL; int bits, src_bits; int count = 0; Uint8 ch; if ( !src ) { /* The error message has been set in SDL_RWFromFile */ return NULL; } start = SDL_RWtell(src); if ( !SDL_RWread(src, &pcxh, sizeof(pcxh), 1) ) { error = "file truncated"; goto done; } pcxh.Xmin = SDL_SwapLE16(pcxh.Xmin); pcxh.Ymin = SDL_SwapLE16(pcxh.Ymin); pcxh.Xmax = SDL_SwapLE16(pcxh.Xmax); pcxh.Ymax = SDL_SwapLE16(pcxh.Ymax); pcxh.BytesPerLine = SDL_SwapLE16(pcxh.BytesPerLine); #if 0 printf("Manufacturer = %d\n", pcxh.Manufacturer); printf("Version = %d\n", pcxh.Version); printf("Encoding = %d\n", pcxh.Encoding); printf("BitsPerPixel = %d\n", pcxh.BitsPerPixel); printf("Xmin = %d, Ymin = %d, Xmax = %d, Ymax = %d\n", pcxh.Xmin, pcxh.Ymin, pcxh.Xmax, pcxh.Ymax); printf("HDpi = %d, VDpi = %d\n", pcxh.HDpi, pcxh.VDpi); printf("NPlanes = %d\n", pcxh.NPlanes); printf("BytesPerLine = %d\n", pcxh.BytesPerLine); printf("PaletteInfo = %d\n", pcxh.PaletteInfo); printf("HscreenSize = %d\n", pcxh.HscreenSize); printf("VscreenSize = %d\n", pcxh.VscreenSize); #endif /* Create the surface of the appropriate type */ width = (pcxh.Xmax - pcxh.Xmin) + 1; height = (pcxh.Ymax - pcxh.Ymin) + 1; Rmask = Gmask = Bmask = Amask = 0; src_bits = pcxh.BitsPerPixel * pcxh.NPlanes; if((pcxh.BitsPerPixel == 1 && pcxh.NPlanes >= 1 && pcxh.NPlanes <= 4) || (pcxh.BitsPerPixel == 8 && pcxh.NPlanes == 1)) { bits = 8; } else if(pcxh.BitsPerPixel == 8 && pcxh.NPlanes == 3) { bits = 24; #if SDL_BYTEORDER == SDL_LIL_ENDIAN Rmask = 0x000000FF; Gmask = 0x0000FF00; Bmask = 0x00FF0000; #else Rmask = 0xFF0000; Gmask = 0x00FF00; Bmask = 0x0000FF; #endif } else { error = "unsupported PCX format"; goto done; } surface = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, bits, Rmask, Gmask, Bmask, Amask); if ( surface == NULL ) { goto done; } bpl = pcxh.NPlanes * pcxh.BytesPerLine; buf = (Uint8 *)SDL_calloc(bpl, 1); if ( !buf ) { error = "Out of memory"; goto done; } row = (Uint8 *)surface->pixels; for ( y=0; y<surface->h; ++y ) { /* decode a scan line to a temporary buffer first */ int i; if ( pcxh.Encoding == 0 ) { if ( !SDL_RWread(src, buf, bpl, 1) ) { error = "file truncated"; goto done; } } else { for ( i = 0; i < bpl; i++ ) { if ( !count ) { if ( !SDL_RWread(src, &ch, 1, 1) ) { error = "file truncated"; goto done; } if ( ch < 0xc0 ) { count = 1; } else { count = ch - 0xc0; if( !SDL_RWread(src, &ch, 1, 1) ) { error = "file truncated"; goto done; } } } buf[i] = ch; count--; } } if ( src_bits <= 4 ) { /* expand planes to 1 byte/pixel */ Uint8 *innerSrc = buf; int plane; for ( plane = 0; plane < pcxh.NPlanes; plane++ ) { int j, k, x = 0; for( j = 0; j < pcxh.BytesPerLine; j++ ) { Uint8 byte = *innerSrc++; for( k = 7; k >= 0; k-- ) { unsigned bit = (byte >> k) & 1; /* skip padding bits */ if (j * 8 + k >= width) continue; row[x++] |= bit << plane; } } } } else if ( src_bits == 8 ) { /* Copy the row directly */ SDL_memcpy(row, buf, SDL_min(width, bpl)); } else if ( src_bits == 24 ) { /* de-interlace planes */ Uint8 *innerSrc = buf; int plane; for ( plane = 0; plane < pcxh.NPlanes; plane++ ) { int x; Uint8 *dst = row + plane; for ( x = 0; x < width; x++ ) { if ( dst >= row+surface->pitch ) { error = "decoding out of bounds (corrupt?)"; goto done; } *dst = *innerSrc++; dst += pcxh.NPlanes; } } } row += surface->pitch; } if ( bits == 8 ) { SDL_Color *colors = surface->format->palette->colors; int nc = 1 << src_bits; int i; surface->format->palette->ncolors = nc; if ( src_bits == 8 ) { Uint8 ch; /* look for a 256-colour palette */ do { if ( !SDL_RWread(src, &ch, 1, 1) ) { /* Couldn't find the palette, try the end of the file */ SDL_RWseek(src, -768, RW_SEEK_END); break; } } while ( ch != 12 ); for ( i = 0; i < 256; i++ ) { SDL_RWread(src, &colors[i].r, 1, 1); SDL_RWread(src, &colors[i].g, 1, 1); SDL_RWread(src, &colors[i].b, 1, 1); } } else { for ( i = 0; i < nc; i++ ) { colors[i].r = pcxh.Colormap[i * 3]; colors[i].g = pcxh.Colormap[i * 3 + 1]; colors[i].b = pcxh.Colormap[i * 3 + 2]; } } } done: SDL_free(buf); if ( error ) { SDL_RWseek(src, start, RW_SEEK_SET); if ( surface ) { SDL_FreeSurface(surface); surface = NULL; } IMG_SetError("%s", error); } return(surface); } #else /* See if an image is contained in a data source */ int IMG_isPCX(SDL_RWops *src) { return(0); } /* Load a PCX type image from an SDL datasource */ SDL_Surface *IMG_LoadPCX_RW(SDL_RWops *src) { return(NULL); } #endif /* LOAD_PCX */
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG_pcx.c
C
apache-2.0
9,218
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* This is a PNG image file loading framework */ #include "SDL_image.h" /* We'll always have PNG save support */ #define SAVE_PNG #if !(defined(__APPLE__) || defined(SDL_IMAGE_USE_WIC_BACKEND)) || defined(SDL_IMAGE_USE_COMMON_BACKEND) #ifdef LOAD_PNG #define USE_LIBPNG /*============================================================================= File: SDL_png.c Purpose: A PNG loader and saver for the SDL library Revision: Created by: Philippe Lavoie (2 November 1998) lavoie@zeus.genie.uottawa.ca Modified by: Copyright notice: Copyright (C) 1998 Philippe Lavoie This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Comments: The load and save routine are basically the ones you can find in the example.c file from the libpng distribution. Changes: 5/17/99 - Modified to use the new SDL data sources - Sam Lantinga =============================================================================*/ #include "SDL_endian.h" #ifdef macintosh #define MACOS #endif #include <png.h> /* Check for the older version of libpng */ #if (PNG_LIBPNG_VER_MAJOR == 1) #if (PNG_LIBPNG_VER_MINOR < 5) #define LIBPNG_VERSION_12 typedef png_bytep png_const_bytep; typedef png_color *png_const_colorp; #endif #if (PNG_LIBPNG_VER_MINOR < 4) typedef png_structp png_const_structp; typedef png_infop png_const_infop; #endif #if (PNG_LIBPNG_VER_MINOR < 6) typedef png_structp png_structrp; typedef png_infop png_inforp; typedef png_const_structp png_const_structrp; typedef png_const_infop png_const_inforp; /* noconst15: version < 1.6 doesn't have const, >= 1.6 adds it */ /* noconst16: version < 1.6 does have const, >= 1.6 removes it */ typedef png_structp png_noconst15_structrp; typedef png_inforp png_noconst15_inforp; typedef png_const_inforp png_noconst16_inforp; #else typedef png_const_structp png_noconst15_structrp; typedef png_const_inforp png_noconst15_inforp; typedef png_inforp png_noconst16_inforp; #endif #else typedef png_const_structp png_noconst15_structrp; typedef png_const_inforp png_noconst15_inforp; typedef png_inforp png_noconst16_inforp; #endif static struct { int loaded; void *handle; png_infop (*png_create_info_struct) (png_noconst15_structrp png_ptr); png_structp (*png_create_read_struct) (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn); void (*png_destroy_read_struct) (png_structpp png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr); png_uint_32 (*png_get_IHDR) (png_noconst15_structrp png_ptr, png_noconst15_inforp info_ptr, png_uint_32 *width, png_uint_32 *height, int *bit_depth, int *color_type, int *interlace_method, int *compression_method, int *filter_method); png_voidp (*png_get_io_ptr) (png_noconst15_structrp png_ptr); png_byte (*png_get_channels) (png_const_structrp png_ptr, png_const_inforp info_ptr); png_uint_32 (*png_get_PLTE) (png_const_structrp png_ptr, png_noconst16_inforp info_ptr, png_colorp *palette, int *num_palette); png_uint_32 (*png_get_tRNS) (png_const_structrp png_ptr, png_inforp info_ptr, png_bytep *trans, int *num_trans, png_color_16p *trans_values); png_uint_32 (*png_get_valid) (png_const_structrp png_ptr, png_const_inforp info_ptr, png_uint_32 flag); void (*png_read_image) (png_structrp png_ptr, png_bytepp image); void (*png_read_info) (png_structrp png_ptr, png_inforp info_ptr); void (*png_read_update_info) (png_structrp png_ptr, png_inforp info_ptr); void (*png_set_expand) (png_structrp png_ptr); void (*png_set_gray_to_rgb) (png_structrp png_ptr); void (*png_set_packing) (png_structrp png_ptr); void (*png_set_read_fn) (png_structrp png_ptr, png_voidp io_ptr, png_rw_ptr read_data_fn); void (*png_set_strip_16) (png_structrp png_ptr); int (*png_set_interlace_handling) (png_structrp png_ptr); int (*png_sig_cmp) (png_const_bytep sig, png_size_t start, png_size_t num_to_check); #ifdef PNG_SETJMP_SUPPORTED #ifndef LIBPNG_VERSION_12 jmp_buf* (*png_set_longjmp_fn) (png_structrp, png_longjmp_ptr, size_t); #endif #endif #ifdef SAVE_PNG png_structp (*png_create_write_struct) (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn); void (*png_destroy_write_struct) (png_structpp png_ptr_ptr, png_infopp info_ptr_ptr); void (*png_set_write_fn) (png_structrp png_ptr, png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn); void (*png_set_IHDR) (png_noconst15_structrp png_ptr, png_inforp info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth, int color_type, int interlace_type, int compression_type, int filter_type); void (*png_write_info) (png_structrp png_ptr, png_noconst15_inforp info_ptr); void (*png_set_rows) (png_noconst15_structrp png_ptr, png_inforp info_ptr, png_bytepp row_pointers); void (*png_write_png) (png_structrp png_ptr, png_inforp info_ptr, int transforms, png_voidp params); void (*png_set_PLTE) (png_structrp png_ptr, png_inforp info_ptr, png_const_colorp palette, int num_palette); #endif } lib; #ifdef LOAD_PNG_DYNAMIC #define FUNCTION_LOADER(FUNC, SIG) \ lib.FUNC = (SIG) SDL_LoadFunction(lib.handle, #FUNC); \ if (lib.FUNC == NULL) { SDL_UnloadObject(lib.handle); return -1; } #else #define FUNCTION_LOADER(FUNC, SIG) \ lib.FUNC = FUNC; #endif int IMG_InitPNG() { if ( lib.loaded == 0 ) { #ifdef LOAD_PNG_DYNAMIC lib.handle = SDL_LoadObject(LOAD_PNG_DYNAMIC); if ( lib.handle == NULL ) { return -1; } #endif FUNCTION_LOADER(png_create_info_struct, png_infop (*) (png_noconst15_structrp png_ptr)) FUNCTION_LOADER(png_create_read_struct, png_structp (*) (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn)) FUNCTION_LOADER(png_destroy_read_struct, void (*) (png_structpp png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr)) FUNCTION_LOADER(png_get_IHDR, png_uint_32 (*) (png_noconst15_structrp png_ptr, png_noconst15_inforp info_ptr, png_uint_32 *width, png_uint_32 *height, int *bit_depth, int *color_type, int *interlace_method, int *compression_method, int *filter_method)) FUNCTION_LOADER(png_get_io_ptr, png_voidp (*) (png_noconst15_structrp png_ptr)) FUNCTION_LOADER(png_get_channels, png_byte (*) (png_const_structrp png_ptr, png_const_inforp info_ptr)) FUNCTION_LOADER(png_get_PLTE, png_uint_32 (*) (png_const_structrp png_ptr, png_noconst16_inforp info_ptr, png_colorp *palette, int *num_palette)) FUNCTION_LOADER(png_get_tRNS, png_uint_32 (*) (png_const_structrp png_ptr, png_inforp info_ptr, png_bytep *trans, int *num_trans, png_color_16p *trans_values)) FUNCTION_LOADER(png_get_valid, png_uint_32 (*) (png_const_structrp png_ptr, png_const_inforp info_ptr, png_uint_32 flag)) FUNCTION_LOADER(png_read_image, void (*) (png_structrp png_ptr, png_bytepp image)) FUNCTION_LOADER(png_read_info, void (*) (png_structrp png_ptr, png_inforp info_ptr)) FUNCTION_LOADER(png_read_update_info, void (*) (png_structrp png_ptr, png_inforp info_ptr)) FUNCTION_LOADER(png_set_expand, void (*) (png_structrp png_ptr)) FUNCTION_LOADER(png_set_gray_to_rgb, void (*) (png_structrp png_ptr)) FUNCTION_LOADER(png_set_packing, void (*) (png_structrp png_ptr)) FUNCTION_LOADER(png_set_read_fn, void (*) (png_structrp png_ptr, png_voidp io_ptr, png_rw_ptr read_data_fn)) FUNCTION_LOADER(png_set_strip_16, void (*) (png_structrp png_ptr)) FUNCTION_LOADER(png_set_interlace_handling, int (*) (png_structrp png_ptr)) FUNCTION_LOADER(png_sig_cmp, int (*) (png_const_bytep sig, png_size_t start, png_size_t num_to_check)) #ifdef PNG_SETJMP_SUPPORTED #ifndef LIBPNG_VERSION_12 FUNCTION_LOADER(png_set_longjmp_fn, jmp_buf* (*) (png_structrp, png_longjmp_ptr, size_t)) #endif #endif #ifdef SAVE_PNG FUNCTION_LOADER(png_create_write_struct, png_structp (*) (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn)) FUNCTION_LOADER(png_destroy_write_struct, void (*) (png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)) FUNCTION_LOADER(png_set_write_fn, void (*) (png_structrp png_ptr, png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)) FUNCTION_LOADER(png_set_IHDR, void (*) (png_noconst15_structrp png_ptr, png_inforp info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth, int color_type, int interlace_type, int compression_type, int filter_type)) FUNCTION_LOADER(png_write_info, void (*) (png_structrp png_ptr, png_noconst15_inforp info_ptr)) FUNCTION_LOADER(png_set_rows, void (*) (png_noconst15_structrp png_ptr, png_inforp info_ptr, png_bytepp row_pointers)) FUNCTION_LOADER(png_write_png, void (*) (png_structrp png_ptr, png_inforp info_ptr, int transforms, png_voidp params)) FUNCTION_LOADER(png_set_PLTE, void (*) (png_structrp png_ptr, png_inforp info_ptr, png_const_colorp palette, int num_palette)) #endif } ++lib.loaded; return 0; } void IMG_QuitPNG() { if ( lib.loaded == 0 ) { return; } if ( lib.loaded == 1 ) { #ifdef LOAD_PNG_DYNAMIC SDL_UnloadObject(lib.handle); #endif } --lib.loaded; } /* See if an image is contained in a data source */ int IMG_isPNG(SDL_RWops *src) { Sint64 start; int is_PNG; Uint8 magic[4]; if ( !src ) { return 0; } start = SDL_RWtell(src); is_PNG = 0; if ( SDL_RWread(src, magic, 1, sizeof(magic)) == sizeof(magic) ) { if ( magic[0] == 0x89 && magic[1] == 'P' && magic[2] == 'N' && magic[3] == 'G' ) { is_PNG = 1; } } SDL_RWseek(src, start, RW_SEEK_SET); return(is_PNG); } /* Load a PNG type image from an SDL datasource */ static void png_read_data(png_structp ctx, png_bytep area, png_size_t size) { SDL_RWops *src; src = (SDL_RWops *)lib.png_get_io_ptr(ctx); SDL_RWread(src, area, size, 1); } SDL_Surface *IMG_LoadPNG_RW(SDL_RWops *src) { Sint64 start; const char *error; SDL_Surface *volatile surface; png_structp png_ptr; png_infop info_ptr; png_uint_32 width, height; int bit_depth, color_type, interlace_type, num_channels; Uint32 Rmask; Uint32 Gmask; Uint32 Bmask; Uint32 Amask; SDL_Palette *palette; png_bytep *volatile row_pointers; int row, i; int ckey = -1; png_color_16 *transv; if ( !src ) { /* The error message has been set in SDL_RWFromFile */ return NULL; } start = SDL_RWtell(src); if ( (IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) == 0 ) { return NULL; } /* Initialize the data we will clean up when we're done */ error = NULL; png_ptr = NULL; info_ptr = NULL; row_pointers = NULL; surface = NULL; /* Create the PNG loading context structure */ png_ptr = lib.png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL,NULL,NULL); if (png_ptr == NULL){ error = "Couldn't allocate memory for PNG file or incompatible PNG dll"; goto done; } /* Allocate/initialize the memory for image information. REQUIRED. */ info_ptr = lib.png_create_info_struct(png_ptr); if (info_ptr == NULL) { error = "Couldn't create image information for PNG file"; goto done; } /* Set error handling if you are using setjmp/longjmp method (this is * the normal method of doing things with libpng). REQUIRED unless you * set up your own error handlers in png_create_read_struct() earlier. */ #ifdef PNG_SETJMP_SUPPORTED #ifndef LIBPNG_VERSION_12 if ( setjmp(*lib.png_set_longjmp_fn(png_ptr, longjmp, sizeof (jmp_buf))) ) #else if ( setjmp(png_ptr->jmpbuf) ) #endif { error = "Error reading the PNG file."; goto done; } #endif /* Set up the input control */ lib.png_set_read_fn(png_ptr, src, png_read_data); /* Read PNG header info */ lib.png_read_info(png_ptr, info_ptr); lib.png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL); /* tell libpng to strip 16 bit/color files down to 8 bits/color */ lib.png_set_strip_16(png_ptr); /* tell libpng to de-interlace (if the image is interlaced) */ lib.png_set_interlace_handling(png_ptr); /* Extract multiple pixels with bit depths of 1, 2, and 4 from a single * byte into separate bytes (useful for paletted and grayscale images). */ lib.png_set_packing(png_ptr); /* scale greyscale values to the range 0..255 */ if (color_type == PNG_COLOR_TYPE_GRAY) lib.png_set_expand(png_ptr); /* For images with a single "transparent colour", set colour key; if more than one index has transparency, or if partially transparent entries exist, use full alpha channel */ if (lib.png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { int num_trans; Uint8 *trans; lib.png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, &transv); if (color_type == PNG_COLOR_TYPE_PALETTE) { /* Check if all tRNS entries are opaque except one */ int j, t = -1; for (j = 0; j < num_trans; j++) { if (trans[j] == 0) { if (t >= 0) { break; } t = j; } else if (trans[j] != 255) { break; } } if (j == num_trans) { /* exactly one transparent index */ ckey = t; } else { /* more than one transparent index, or translucency */ lib.png_set_expand(png_ptr); } } else { ckey = 0; /* actual value will be set later */ } } if ( color_type == PNG_COLOR_TYPE_GRAY_ALPHA ) lib.png_set_gray_to_rgb(png_ptr); lib.png_read_update_info(png_ptr, info_ptr); lib.png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL); /* Allocate the SDL surface to hold the image */ Rmask = Gmask = Bmask = Amask = 0 ; num_channels = lib.png_get_channels(png_ptr, info_ptr); if ( num_channels >= 3 ) { #if SDL_BYTEORDER == SDL_LIL_ENDIAN Rmask = 0x000000FF; Gmask = 0x0000FF00; Bmask = 0x00FF0000; Amask = (num_channels == 4) ? 0xFF000000 : 0; #else int s = (num_channels == 4) ? 0 : 8; Rmask = 0xFF000000 >> s; Gmask = 0x00FF0000 >> s; Bmask = 0x0000FF00 >> s; Amask = 0x000000FF >> s; #endif } surface = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, bit_depth*num_channels, Rmask,Gmask,Bmask,Amask); if ( surface == NULL ) { error = SDL_GetError(); goto done; } if (ckey != -1) { if (color_type != PNG_COLOR_TYPE_PALETTE) { /* FIXME: Should these be truncated or shifted down? */ ckey = SDL_MapRGB(surface->format, (Uint8)transv->red, (Uint8)transv->green, (Uint8)transv->blue); } SDL_SetColorKey(surface, SDL_TRUE, ckey); } /* Create the array of pointers to image data */ row_pointers = (png_bytep*) SDL_malloc(sizeof(png_bytep)*height); if (!row_pointers) { error = "Out of memory"; goto done; } for (row = 0; row < (int)height; row++) { row_pointers[row] = (png_bytep) (Uint8 *)surface->pixels + row*surface->pitch; } /* Read the entire image in one go */ lib.png_read_image(png_ptr, row_pointers); /* and we're done! (png_read_end() can be omitted if no processing of * post-IDAT text/time/etc. is desired) * In some cases it can't read PNG's created by some popular programs (ACDSEE), * we do not want to process comments, so we omit png_read_end lib.png_read_end(png_ptr, info_ptr); */ /* Load the palette, if any */ palette = surface->format->palette; if ( palette ) { int png_num_palette; png_colorp png_palette; lib.png_get_PLTE(png_ptr, info_ptr, &png_palette, &png_num_palette); if (color_type == PNG_COLOR_TYPE_GRAY) { palette->ncolors = 256; for (i = 0; i < 256; i++) { palette->colors[i].r = (Uint8)i; palette->colors[i].g = (Uint8)i; palette->colors[i].b = (Uint8)i; } } else if (png_num_palette > 0 ) { palette->ncolors = png_num_palette; for ( i=0; i<png_num_palette; ++i ) { palette->colors[i].b = png_palette[i].blue; palette->colors[i].g = png_palette[i].green; palette->colors[i].r = png_palette[i].red; } } } done: /* Clean up and return */ if ( png_ptr ) { lib.png_destroy_read_struct(&png_ptr, info_ptr ? &info_ptr : (png_infopp)0, (png_infopp)0); } if ( row_pointers ) { SDL_free(row_pointers); } if ( error ) { SDL_RWseek(src, start, RW_SEEK_SET); if ( surface ) { SDL_FreeSurface(surface); surface = NULL; } IMG_SetError("%s", error); } return(surface); } #else int IMG_InitPNG() { IMG_SetError("PNG images are not supported"); return(-1); } void IMG_QuitPNG() { } /* See if an image is contained in a data source */ int IMG_isPNG(SDL_RWops *src) { return(0); } /* Load a PNG type image from an SDL datasource */ SDL_Surface *IMG_LoadPNG_RW(SDL_RWops *src) { return(NULL); } #endif /* LOAD_PNG */ #endif /* !defined(__APPLE__) || defined(SDL_IMAGE_USE_COMMON_BACKEND) */ #ifdef SAVE_PNG int IMG_SavePNG(SDL_Surface *surface, const char *file) { SDL_RWops *dst = SDL_RWFromFile(file, "wb"); if (dst) { return IMG_SavePNG_RW(surface, dst, 1); } else { return -1; } } #if SDL_BYTEORDER == SDL_LIL_ENDIAN static const Uint32 png_format = SDL_PIXELFORMAT_ABGR8888; #else static const Uint32 png_format = SDL_PIXELFORMAT_RGBA8888; #endif #ifdef USE_LIBPNG static void png_write_data(png_structp png_ptr, png_bytep src, png_size_t size) { SDL_RWops *dst = (SDL_RWops *)lib.png_get_io_ptr(png_ptr); SDL_RWwrite(dst, src, size, 1); } static void png_flush_data(png_structp png_ptr) { } static int IMG_SavePNG_RW_libpng(SDL_Surface *surface, SDL_RWops *dst, int freedst) { if (dst) { png_structp png_ptr; png_infop info_ptr; png_colorp color_ptr = NULL; SDL_Surface *source = surface; SDL_Palette *palette; int png_color_type = PNG_COLOR_TYPE_RGB_ALPHA; png_ptr = lib.png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (png_ptr == NULL) { SDL_SetError("Couldn't allocate memory for PNG file or incompatible PNG dll"); return -1; } info_ptr = lib.png_create_info_struct(png_ptr); if (info_ptr == NULL) { lib.png_destroy_write_struct(&png_ptr, NULL); SDL_SetError("Couldn't create image information for PNG file"); return -1; } #ifdef PNG_SETJMP_SUPPORTED #ifndef LIBPNG_VERSION_12 if (setjmp(*lib.png_set_longjmp_fn(png_ptr, longjmp, sizeof (jmp_buf)))) #else if (setjmp(png_ptr->jmpbuf)) #endif #endif { lib.png_destroy_write_struct(&png_ptr, &info_ptr); SDL_SetError("Error writing the PNG file."); return -1; } palette = surface->format->palette; if (palette) { const int ncolors = palette->ncolors; int i; color_ptr = SDL_malloc(sizeof(png_colorp) * ncolors); if (color_ptr == NULL) { lib.png_destroy_write_struct(&png_ptr, &info_ptr); SDL_SetError("Couldn't create palette for PNG file"); return -1; } for (i = 0; i < ncolors; i++) { color_ptr[i].red = palette->colors[i].r; color_ptr[i].green = palette->colors[i].g; color_ptr[i].blue = palette->colors[i].b; } lib.png_set_PLTE(png_ptr, info_ptr, color_ptr, ncolors); png_color_type = PNG_COLOR_TYPE_PALETTE; } else if (surface->format->format != png_format) { source = SDL_ConvertSurfaceFormat(surface, png_format, 0); } lib.png_set_write_fn(png_ptr, dst, png_write_data, png_flush_data); lib.png_set_IHDR(png_ptr, info_ptr, surface->w, surface->h, 8, png_color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); if (source) { png_bytep *row_pointers; int row; row_pointers = (png_bytep *) SDL_malloc(sizeof(png_bytep) * source->h); if (!row_pointers) { lib.png_destroy_write_struct(&png_ptr, &info_ptr); SDL_SetError("Out of memory"); return -1; } for (row = 0; row < (int)source->h; row++) { row_pointers[row] = (png_bytep) (Uint8 *) source->pixels + row * source->pitch; } lib.png_set_rows(png_ptr, info_ptr, row_pointers); lib.png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL); SDL_free(row_pointers); if (source != surface) { SDL_FreeSurface(source); } } lib.png_destroy_write_struct(&png_ptr, &info_ptr); if (color_ptr) { SDL_free(color_ptr); } if (freedst) { SDL_RWclose(dst); } } else { SDL_SetError("Passed NULL dst"); return -1; } return 0; } #endif /* USE_LIBPNG */ /* Replace C runtime functions with SDL C runtime functions for building on Windows */ #define MINIZ_NO_STDIO #define MINIZ_NO_TIME #define MINIZ_SDL_MALLOC #define MZ_ASSERT(x) SDL_assert(x) #undef memcpy #define memcpy SDL_memcpy #undef memset #define memset SDL_memset #define strlen SDL_strlen #include "miniz.h" static int IMG_SavePNG_RW_miniz(SDL_Surface *surface, SDL_RWops *dst, int freedst) { int result = -1; if (dst) { size_t size = 0; void *png = NULL; if (surface->format->format == png_format) { png = tdefl_write_image_to_png_file_in_memory(surface->pixels, surface->w, surface->h, surface->format->BytesPerPixel, surface->pitch, &size); } else { SDL_Surface *cvt = SDL_ConvertSurfaceFormat(surface, png_format, 0); if (cvt) { png = tdefl_write_image_to_png_file_in_memory(cvt->pixels, cvt->w, cvt->h, cvt->format->BytesPerPixel, cvt->pitch, &size); SDL_FreeSurface(cvt); } } if (png) { if (SDL_RWwrite(dst, png, size, 1)) { result = 0; } SDL_free(png); } else { SDL_SetError("Failed to convert and save image"); } if (freedst) { SDL_RWclose(dst); } } else { SDL_SetError("Passed NULL dst"); } return result; } int IMG_SavePNG_RW(SDL_Surface *surface, SDL_RWops *dst, int freedst) { static int (*rw_func)(SDL_Surface *surface, SDL_RWops *dst, int freedst); if (!rw_func) { #ifdef USE_LIBPNG if (IMG_Init(IMG_INIT_PNG)) { rw_func = IMG_SavePNG_RW_libpng; } else #endif rw_func = IMG_SavePNG_RW_miniz; } return rw_func(surface, dst, freedst); } #endif /* SAVE_PNG */
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG_png.c
C
apache-2.0
25,783
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* * PNM (portable anymap) image loader: * * Supports: PBM, PGM and PPM, ASCII and binary formats * (PBM and PGM are loaded as 8bpp surfaces) * Does not support: maximum component value > 255 */ #include "SDL_image.h" #ifdef LOAD_PNM /* See if an image is contained in a data source */ int IMG_isPNM(SDL_RWops *src) { Sint64 start; int is_PNM; char magic[2]; if ( !src ) return 0; start = SDL_RWtell(src); is_PNM = 0; if ( SDL_RWread(src, magic, sizeof(magic), 1) ) { /* * PNM magic signatures: * P1 PBM, ascii format * P2 PGM, ascii format * P3 PPM, ascii format * P4 PBM, binary format * P5 PGM, binary format * P6 PPM, binary format * P7 PAM, a general wrapper for PNM data */ if ( magic[0] == 'P' && magic[1] >= '1' && magic[1] <= '6' ) { is_PNM = 1; } } SDL_RWseek(src, start, RW_SEEK_SET); return(is_PNM); } /* read a non-negative integer from the source. return -1 upon error */ static int ReadNumber(SDL_RWops *src) { int number; unsigned char ch; /* Initialize return value */ number = 0; /* Skip leading whitespace */ do { if ( ! SDL_RWread(src, &ch, 1, 1) ) { return(-1); } /* Eat comments as whitespace */ if ( ch == '#' ) { /* Comment is '#' to end of line */ do { if ( ! SDL_RWread(src, &ch, 1, 1) ) { return -1; } } while ( (ch != '\r') && (ch != '\n') ); } } while ( SDL_isspace(ch) ); /* Add up the number */ if (!SDL_isdigit(ch)) { return -1; } do { /* Protect from possible overflow */ if (number >= (SDL_MAX_SINT32 / 10)) { return -1; } number *= 10; number += ch-'0'; if ( !SDL_RWread(src, &ch, 1, 1) ) { return -1; } } while ( SDL_isdigit(ch) ); return(number); } SDL_Surface *IMG_LoadPNM_RW(SDL_RWops *src) { Sint64 start; SDL_Surface *surface = NULL; int width, height; int maxval, y, bpl; Uint8 *row; Uint8 *buf = NULL; char *error = NULL; Uint8 magic[2]; int ascii; enum { PBM, PGM, PPM, PAM } kind; #define ERROR(s) do { error = (s); goto done; } while(0) if ( !src ) { /* The error message has been set in SDL_RWFromFile */ return NULL; } start = SDL_RWtell(src); SDL_RWread(src, magic, 2, 1); kind = magic[1] - '1'; ascii = 1; if(kind >= 3) { ascii = 0; kind -= 3; } width = ReadNumber(src); height = ReadNumber(src); if(width <= 0 || height <= 0) ERROR("Unable to read image width and height"); if(kind != PBM) { maxval = ReadNumber(src); if(maxval <= 0 || maxval > 255) ERROR("unsupported PNM format"); } else maxval = 255; /* never scale PBMs */ /* binary PNM allows just a single character of whitespace after the last parameter, and we've already consumed it */ if(kind == PPM) { /* 24-bit surface in R,G,B byte order */ surface = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 24, #if SDL_BYTEORDER == SDL_LIL_ENDIAN 0x000000ff, 0x0000ff00, 0x00ff0000, #else 0x00ff0000, 0x0000ff00, 0x000000ff, #endif 0); } else { /* load PBM/PGM as 8-bit indexed images */ surface = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 8, 0, 0, 0, 0); } if ( surface == NULL ) ERROR("Out of memory"); bpl = width * surface->format->BytesPerPixel; if(kind == PGM) { SDL_Color *c = surface->format->palette->colors; int i; for(i = 0; i < 256; i++) c[i].r = c[i].g = c[i].b = i; surface->format->palette->ncolors = 256; } else if(kind == PBM) { /* for some reason PBM has 1=black, 0=white */ SDL_Color *c = surface->format->palette->colors; c[0].r = c[0].g = c[0].b = 255; c[1].r = c[1].g = c[1].b = 0; surface->format->palette->ncolors = 2; bpl = (width + 7) >> 3; buf = (Uint8 *)SDL_malloc(bpl); if(buf == NULL) ERROR("Out of memory"); } /* Read the image into the surface */ row = (Uint8 *)surface->pixels; for(y = 0; y < height; y++) { if(ascii) { int i; if(kind == PBM) { for(i = 0; i < width; i++) { Uint8 ch; do { if(!SDL_RWread(src, &ch, 1, 1)) ERROR("file truncated"); ch -= '0'; } while(ch > 1); row[i] = ch; } } else { for(i = 0; i < bpl; i++) { int c; c = ReadNumber(src); if(c < 0) ERROR("file truncated"); row[i] = c; } } } else { Uint8 *dst = (kind == PBM) ? buf : row; if(!SDL_RWread(src, dst, bpl, 1)) ERROR("file truncated"); if(kind == PBM) { /* expand bitmap to 8bpp */ int i; for(i = 0; i < width; i++) { int bit = 7 - (i & 7); row[i] = (buf[i >> 3] >> bit) & 1; } } } if(maxval < 255) { /* scale up to full dynamic range (slow) */ int i; for(i = 0; i < bpl; i++) row[i] = row[i] * 255 / maxval; } row += surface->pitch; } done: SDL_free(buf); if(error) { SDL_RWseek(src, start, RW_SEEK_SET); if ( surface ) { SDL_FreeSurface(surface); surface = NULL; } IMG_SetError("%s", error); } return(surface); } #else /* See if an image is contained in a data source */ int IMG_isPNM(SDL_RWops *src) { return(0); } /* Load a PNM type image from an SDL datasource */ SDL_Surface *IMG_LoadPNM_RW(SDL_RWops *src) { return(NULL); } #endif /* LOAD_PNM */
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG_pnm.c
C
apache-2.0
7,373
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* This is an SVG image file loading framework, based on Nano SVG: * https://github.com/memononen/nanosvg */ #include "SDL_image.h" #ifdef LOAD_SVG /* Replace C runtime functions with SDL C runtime functions for building on Windows */ #define acosf SDL_acosf #define atan2f SDL_atan2f #define cosf SDL_cosf #define ceilf SDL_ceilf #define fabs SDL_fabs #define fabsf SDL_fabsf #define floorf SDL_floorf #define fmodf SDL_fmodf #define free SDL_free #define malloc SDL_malloc #undef memcpy #define memcpy SDL_memcpy #undef memset #define memset SDL_memset #define pow SDL_pow #define qsort SDL_qsort #define realloc SDL_realloc #define sinf SDL_sinf #define sqrt SDL_sqrt #define sqrtf SDL_sqrtf #define sscanf SDL_sscanf #undef strchr #define strchr SDL_strchr #undef strcmp #define strcmp SDL_strcmp #undef strncmp #define strncmp SDL_strncmp #undef strncpy #define strncpy SDL_strlcpy #define strlen SDL_strlen #define strstr SDL_strstr #define strtol SDL_strtol #define strtoll SDL_strtoll #define tanf SDL_tanf #ifndef FLT_MAX #define FLT_MAX 3.402823466e+38F #endif #undef HAVE_STDIO_H #define NANOSVG_IMPLEMENTATION #include "nanosvg.h" #define NANOSVGRAST_IMPLEMENTATION #include "nanosvgrast.h" /* See if an image is contained in a data source */ int IMG_isSVG(SDL_RWops *src) { Sint64 start; int is_SVG; char magic[4096]; size_t magic_len; if ( !src ) return 0; start = SDL_RWtell(src); is_SVG = 0; magic_len = SDL_RWread(src, magic, 1, sizeof(magic) - 1); magic[magic_len] = '\0'; if ( SDL_strstr(magic, "<svg") ) { is_SVG = 1; } SDL_RWseek(src, start, RW_SEEK_SET); return(is_SVG); } /* Load a SVG type image from an SDL datasource */ SDL_Surface *IMG_LoadSVG_RW(SDL_RWops *src) { char *data; struct NSVGimage *image; struct NSVGrasterizer *rasterizer; SDL_Surface *surface = NULL; float scale = 1.0f; data = (char *)SDL_LoadFile_RW(src, NULL, SDL_FALSE); if ( !data ) { return NULL; } /* For now just use default units of pixels at 96 DPI */ image = nsvgParse(data, "px", 96.0f); SDL_free(data); if ( !image ) { IMG_SetError("Couldn't parse SVG image"); return NULL; } rasterizer = nsvgCreateRasterizer(); if ( !rasterizer ) { IMG_SetError("Couldn't create SVG rasterizer"); nsvgDelete( image ); return NULL; } surface = SDL_CreateRGBSurface(SDL_SWSURFACE, (int)(image->width * scale), (int)(image->height * scale), 32, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000); if ( !surface ) { nsvgDeleteRasterizer( rasterizer ); nsvgDelete( image ); return NULL; } nsvgRasterize(rasterizer, image, 0.0f, 0.0f, scale, (unsigned char *)surface->pixels, surface->w, surface->h, surface->pitch); nsvgDeleteRasterizer( rasterizer ); nsvgDelete( image ); return surface; } #else /* See if an image is contained in a data source */ int IMG_isSVG(SDL_RWops *src) { return(0); } /* Load a SVG type image from an SDL datasource */ SDL_Surface *IMG_LoadSVG_RW(SDL_RWops *src) { return(NULL); } #endif /* LOAD_SVG */
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG_svg.c
C
apache-2.0
4,441
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #if !(defined(__APPLE__) || defined(SDL_IMAGE_USE_WIC_BACKEND)) || defined(SDL_IMAGE_USE_COMMON_BACKEND) /* This is a TIFF image file loading framework */ #include "SDL_image.h" #ifdef LOAD_TIF #include <tiffio.h> static struct { int loaded; void *handle; TIFF* (*TIFFClientOpen)(const char*, const char*, thandle_t, TIFFReadWriteProc, TIFFReadWriteProc, TIFFSeekProc, TIFFCloseProc, TIFFSizeProc, TIFFMapFileProc, TIFFUnmapFileProc); void (*TIFFClose)(TIFF*); int (*TIFFGetField)(TIFF*, ttag_t, ...); int (*TIFFReadRGBAImageOriented)(TIFF*, uint32, uint32, uint32*, int, int); TIFFErrorHandler (*TIFFSetErrorHandler)(TIFFErrorHandler); } lib; #ifdef LOAD_TIF_DYNAMIC #define FUNCTION_LOADER(FUNC, SIG) \ lib.FUNC = (SIG) SDL_LoadFunction(lib.handle, #FUNC); \ if (lib.FUNC == NULL) { SDL_UnloadObject(lib.handle); return -1; } #else #define FUNCTION_LOADER(FUNC, SIG) \ lib.FUNC = FUNC; #endif int IMG_InitTIF() { if ( lib.loaded == 0 ) { #ifdef LOAD_TIF_DYNAMIC lib.handle = SDL_LoadObject(LOAD_TIF_DYNAMIC); if ( lib.handle == NULL ) { return -1; } #endif FUNCTION_LOADER(TIFFClientOpen, TIFF * (*)(const char*, const char*, thandle_t, TIFFReadWriteProc, TIFFReadWriteProc, TIFFSeekProc, TIFFCloseProc, TIFFSizeProc, TIFFMapFileProc, TIFFUnmapFileProc)) FUNCTION_LOADER(TIFFClose, void (*)(TIFF*)) FUNCTION_LOADER(TIFFGetField, int (*)(TIFF*, ttag_t, ...)) FUNCTION_LOADER(TIFFReadRGBAImageOriented, int (*)(TIFF*, uint32, uint32, uint32*, int, int)) FUNCTION_LOADER(TIFFSetErrorHandler, TIFFErrorHandler (*)(TIFFErrorHandler)) } ++lib.loaded; return 0; } void IMG_QuitTIF() { if ( lib.loaded == 0 ) { return; } if ( lib.loaded == 1 ) { #ifdef LOAD_TIF_DYNAMIC SDL_UnloadObject(lib.handle); #endif } --lib.loaded; } /* * These are the thunking routine to use the SDL_RWops* routines from * libtiff's internals. */ static tsize_t tiff_read(thandle_t fd, tdata_t buf, tsize_t size) { return (tsize_t)SDL_RWread((SDL_RWops*)fd, buf, 1, size); } static toff_t tiff_seek(thandle_t fd, toff_t offset, int origin) { return SDL_RWseek((SDL_RWops*)fd, offset, origin); } static tsize_t tiff_write(thandle_t fd, tdata_t buf, tsize_t size) { return (tsize_t)SDL_RWwrite((SDL_RWops*)fd, buf, 1, size); } static int tiff_close(thandle_t fd) { /* * We don't want libtiff closing our SDL_RWops*, but if it's not given * a routine to try, and if the image isn't a TIFF, it'll segfault. */ return 0; } static int tiff_map(thandle_t fd, tdata_t* pbase, toff_t* psize) { return (0); } static void tiff_unmap(thandle_t fd, tdata_t base, toff_t size) { return; } static toff_t tiff_size(thandle_t fd) { Sint64 save_pos; toff_t size; save_pos = SDL_RWtell((SDL_RWops*)fd); SDL_RWseek((SDL_RWops*)fd, 0, RW_SEEK_END); size = SDL_RWtell((SDL_RWops*)fd); SDL_RWseek((SDL_RWops*)fd, save_pos, RW_SEEK_SET); return size; } int IMG_isTIF(SDL_RWops* src) { Sint64 start; int is_TIF; Uint8 magic[4]; if ( !src ) return 0; start = SDL_RWtell(src); is_TIF = 0; if ( SDL_RWread(src, magic, 1, sizeof(magic)) == sizeof(magic) ) { if ( (magic[0] == 'I' && magic[1] == 'I' && magic[2] == 0x2a && magic[3] == 0x00) || (magic[0] == 'M' && magic[1] == 'M' && magic[2] == 0x00 && magic[3] == 0x2a) ) { is_TIF = 1; } } SDL_RWseek(src, start, RW_SEEK_SET); return(is_TIF); } SDL_Surface* IMG_LoadTIF_RW(SDL_RWops* src) { Sint64 start; TIFF* tiff = NULL; SDL_Surface* surface = NULL; Uint32 img_width, img_height; Uint32 Rmask, Gmask, Bmask, Amask; if ( !src ) { /* The error message has been set in SDL_RWFromFile */ return NULL; } start = SDL_RWtell(src); if ( (IMG_Init(IMG_INIT_TIF) & IMG_INIT_TIF) == 0 ) { return NULL; } /* turn off memory mapped access with the m flag */ tiff = lib.TIFFClientOpen("SDL_image", "rm", (thandle_t)src, tiff_read, tiff_write, tiff_seek, tiff_close, tiff_size, tiff_map, tiff_unmap); if(!tiff) goto error; /* Retrieve the dimensions of the image from the TIFF tags */ lib.TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &img_width); lib.TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &img_height); Rmask = 0x000000FF; Gmask = 0x0000FF00; Bmask = 0x00FF0000; Amask = 0xFF000000; surface = SDL_CreateRGBSurface(SDL_SWSURFACE, img_width, img_height, 32, Rmask, Gmask, Bmask, Amask); if(!surface) goto error; if(!lib.TIFFReadRGBAImageOriented(tiff, img_width, img_height, (uint32 *)surface->pixels, ORIENTATION_TOPLEFT, 0)) goto error; lib.TIFFClose(tiff); return surface; error: SDL_RWseek(src, start, RW_SEEK_SET); if (surface) { SDL_FreeSurface(surface); } if (tiff) { lib.TIFFClose(tiff); } return NULL; } #else int IMG_InitTIF() { IMG_SetError("TIFF images are not supported"); return(-1); } void IMG_QuitTIF() { } /* See if an image is contained in a data source */ int IMG_isTIF(SDL_RWops *src) { return(0); } /* Load a TIFF type image from an SDL datasource */ SDL_Surface *IMG_LoadTIF_RW(SDL_RWops *src) { return(NULL); } #endif /* LOAD_TIF */ #endif /* !defined(__APPLE__) || defined(SDL_IMAGE_USE_COMMON_BACKEND) */
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG_tif.c
C
apache-2.0
6,586
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* This is a WEBP image file loading framework */ #include "SDL_image.h" #ifdef LOAD_WEBP /*============================================================================= File: SDL_webp.c Purpose: A WEBP loader for the SDL library Revision: Created by: Michael Bonfils (Murlock) (26 November 2011) murlock42@gmail.com =============================================================================*/ #include "SDL_endian.h" #ifdef macintosh #define MACOS #endif #include <webp/decode.h> static struct { int loaded; void *handle; #if WEBP_DECODER_ABI_VERSION < 0x0100 VP8StatusCode (*WebPGetFeaturesInternal) (const uint8_t *data, uint32_t data_size, WebPBitstreamFeatures* const features, int decoder_abi_version); uint8_t* (*WebPDecodeRGBInto) (const uint8_t* data, uint32_t data_size, uint8_t* output_buffer, int output_buffer_size, int output_stride); uint8_t* (*WebPDecodeRGBAInto) (const uint8_t* data, uint32_t data_size, uint8_t* output_buffer, int output_buffer_size, int output_stride); #else VP8StatusCode (*WebPGetFeaturesInternal) (const uint8_t *data, size_t data_size, WebPBitstreamFeatures* features, int decoder_abi_version); uint8_t* (*WebPDecodeRGBInto) (const uint8_t* data, size_t data_size, uint8_t* output_buffer, size_t output_buffer_size, int output_stride); uint8_t* (*WebPDecodeRGBAInto) (const uint8_t* data, size_t data_size, uint8_t* output_buffer, size_t output_buffer_size, int output_stride); #endif } lib; #ifdef LOAD_WEBP_DYNAMIC #define FUNCTION_LOADER(FUNC, SIG) \ lib.FUNC = (SIG) SDL_LoadFunction(lib.handle, #FUNC); \ if (lib.FUNC == NULL) { SDL_UnloadObject(lib.handle); return -1; } #else #define FUNCTION_LOADER(FUNC, SIG) \ lib.FUNC = FUNC; #endif int IMG_InitWEBP() { if ( lib.loaded == 0 ) { #ifdef LOAD_WEBP_DYNAMIC lib.handle = SDL_LoadObject(LOAD_WEBP_DYNAMIC); if ( lib.handle == NULL ) { return -1; } #endif #if WEBP_DECODER_ABI_VERSION < 0x0100 FUNCTION_LOADER(WebPGetFeaturesInternal, VP8StatusCode (*) (const uint8_t *data, uint32_t data_size, WebPBitstreamFeatures* const features, int decoder_abi_version)) FUNCTION_LOADER(WebPDecodeRGBInto, uint8_t * (*) (const uint8_t* data, uint32_t data_size, uint8_t* output_buffer, int output_buffer_size, int output_stride)) FUNCTION_LOADER(WebPDecodeRGBAInto, uint8_t * (*) (const uint8_t* data, uint32_t data_size, uint8_t* output_buffer, int output_buffer_size, int output_stride)) #else FUNCTION_LOADER(WebPGetFeaturesInternal, VP8StatusCode (*) (const uint8_t *data, size_t data_size, WebPBitstreamFeatures* features, int decoder_abi_version)) FUNCTION_LOADER(WebPDecodeRGBInto, uint8_t * (*) (const uint8_t* data, size_t data_size, uint8_t* output_buffer, size_t output_buffer_size, int output_stride)) FUNCTION_LOADER(WebPDecodeRGBAInto, uint8_t * (*) (const uint8_t* data, size_t data_size, uint8_t* output_buffer, size_t output_buffer_size, int output_stride)) #endif } ++lib.loaded; return 0; } void IMG_QuitWEBP() { if ( lib.loaded == 0 ) { return; } if ( lib.loaded == 1 ) { #ifdef LOAD_WEBP_DYNAMIC SDL_UnloadObject(lib.handle); #endif } --lib.loaded; } static int webp_getinfo( SDL_RWops *src, int *datasize ) { Sint64 start; int is_WEBP; Uint8 magic[20]; if ( !src ) { return 0; } start = SDL_RWtell(src); is_WEBP = 0; if ( SDL_RWread(src, magic, 1, sizeof(magic)) == sizeof(magic) ) { if ( magic[ 0] == 'R' && magic[ 1] == 'I' && magic[ 2] == 'F' && magic[ 3] == 'F' && magic[ 8] == 'W' && magic[ 9] == 'E' && magic[10] == 'B' && magic[11] == 'P' && magic[12] == 'V' && magic[13] == 'P' && magic[14] == '8' && /* old versions don't support VP8X and VP8L */ #if (WEBP_DECODER_ABI_VERSION < 0x0003) magic[15] == ' ' #else (magic[15] == ' ' || magic[15] == 'X' || magic[15] == 'L') #endif ) { is_WEBP = 1; if ( datasize ) { *datasize = (int)(SDL_RWseek(src, 0, RW_SEEK_END) - start); } } } SDL_RWseek(src, start, RW_SEEK_SET); return(is_WEBP); } /* See if an image is contained in a data source */ int IMG_isWEBP(SDL_RWops *src) { return webp_getinfo( src, NULL ); } SDL_Surface *IMG_LoadWEBP_RW(SDL_RWops *src) { Sint64 start; const char *error = NULL; SDL_Surface *volatile surface = NULL; Uint32 Rmask; Uint32 Gmask; Uint32 Bmask; Uint32 Amask; WebPBitstreamFeatures features; int raw_data_size; uint8_t *raw_data = NULL; int r; uint8_t *ret; if ( !src ) { /* The error message has been set in SDL_RWFromFile */ return NULL; } start = SDL_RWtell(src); if ( (IMG_Init(IMG_INIT_WEBP) & IMG_INIT_WEBP) == 0 ) { goto error; } raw_data_size = -1; if ( !webp_getinfo( src, &raw_data_size ) ) { error = "Invalid WEBP"; goto error; } raw_data = (uint8_t*) SDL_malloc( raw_data_size ); if ( raw_data == NULL ) { error = "Failed to allocate enough buffer for WEBP"; goto error; } r = (int)SDL_RWread(src, raw_data, 1, raw_data_size ); if ( r != raw_data_size ) { error = "Failed to read WEBP"; goto error; } #if 0 // extract size of picture, not interesting since we don't know about alpha channel int width = -1, height = -1; if ( !WebPGetInfo( raw_data, raw_data_size, &width, &height ) ) { printf("WebPGetInfo has failed\n" ); return NULL; } #endif if ( lib.WebPGetFeaturesInternal( raw_data, raw_data_size, &features, WEBP_DECODER_ABI_VERSION ) != VP8_STATUS_OK ) { error = "WebPGetFeatures has failed"; goto error; } /* Check if it's ok !*/ #if SDL_BYTEORDER == SDL_LIL_ENDIAN Rmask = 0x000000FF; Gmask = 0x0000FF00; Bmask = 0x00FF0000; Amask = (features.has_alpha) ? 0xFF000000 : 0; #else { int s = (features.has_alpha) ? 0 : 8; Rmask = 0xFF000000 >> s; Gmask = 0x00FF0000 >> s; Bmask = 0x0000FF00 >> s; Amask = 0x000000FF >> s; } #endif surface = SDL_CreateRGBSurface(SDL_SWSURFACE, features.width, features.height, features.has_alpha?32:24, Rmask,Gmask,Bmask,Amask); if ( surface == NULL ) { error = "Failed to allocate SDL_Surface"; goto error; } if ( features.has_alpha ) { ret = lib.WebPDecodeRGBAInto( raw_data, raw_data_size, (uint8_t *)surface->pixels, surface->pitch * surface->h, surface->pitch ); } else { ret = lib.WebPDecodeRGBInto( raw_data, raw_data_size, (uint8_t *)surface->pixels, surface->pitch * surface->h, surface->pitch ); } if ( !ret ) { error = "Failed to decode WEBP"; goto error; } if ( raw_data ) { SDL_free( raw_data ); } return surface; error: if ( raw_data ) { SDL_free( raw_data ); } if ( surface ) { SDL_FreeSurface( surface ); } if ( error ) { IMG_SetError( "%s", error ); } SDL_RWseek(src, start, RW_SEEK_SET); return(NULL); } #else int IMG_InitWEBP() { IMG_SetError("WEBP images are not supported"); return(-1); } void IMG_QuitWEBP() { } /* See if an image is contained in a data source */ int IMG_isWEBP(SDL_RWops *src) { return(0); } /* Load a WEBP type image from an SDL datasource */ SDL_Surface *IMG_LoadWEBP_RW(SDL_RWops *src) { return(NULL); } #endif /* LOAD_WEBP */
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG_webp.c
C
apache-2.0
8,782
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* This is a XCF image file loading framework */ #include "SDL_endian.h" #include "SDL_image.h" #ifdef LOAD_XCF #if DEBUG static char prop_names [][30] = { "end", "colormap", "active_layer", "active_channel", "selection", "floating_selection", "opacity", "mode", "visible", "linked", "preserve_transparency", "apply_mask", "edit_mask", "show_mask", "show_masked", "offsets", "color", "compression", "guides", "resolution", "tattoo", "parasites", "unit", "paths", "user_unit" }; #endif typedef enum { PROP_END = 0, PROP_COLORMAP = 1, PROP_ACTIVE_LAYER = 2, PROP_ACTIVE_CHANNEL = 3, PROP_SELECTION = 4, PROP_FLOATING_SELECTION = 5, PROP_OPACITY = 6, PROP_MODE = 7, PROP_VISIBLE = 8, PROP_LINKED = 9, PROP_PRESERVE_TRANSPARENCY = 10, PROP_APPLY_MASK = 11, PROP_EDIT_MASK = 12, PROP_SHOW_MASK = 13, PROP_SHOW_MASKED = 14, PROP_OFFSETS = 15, PROP_COLOR = 16, PROP_COMPRESSION = 17, PROP_GUIDES = 18, PROP_RESOLUTION = 19, PROP_TATTOO = 20, PROP_PARASITES = 21, PROP_UNIT = 22, PROP_PATHS = 23, PROP_USER_UNIT = 24 } xcf_prop_type; typedef enum { COMPR_NONE = 0, COMPR_RLE = 1, COMPR_ZLIB = 2, COMPR_FRACTAL = 3 } xcf_compr_type; typedef enum { IMAGE_RGB = 0, IMAGE_GREYSCALE = 1, IMAGE_INDEXED = 2 } xcf_image_type; typedef struct { Uint32 id; Uint32 length; union { struct { Uint32 num; char * cmap; } colormap; // 1 struct { Uint32 drawable_offset; } floating_selection; // 5 Sint32 opacity; Sint32 mode; int visible; int linked; int preserve_transparency; int apply_mask; int show_mask; struct { Sint32 x; Sint32 y; } offset; unsigned char color [3]; Uint8 compression; struct { Sint32 x; Sint32 y; } resolution; struct { char * name; Uint32 flags; Uint32 size; char * data; } parasite; } data; } xcf_prop; typedef struct { char sign [14]; Uint32 file_version; Uint32 width; Uint32 height; Sint32 image_type; Uint32 precision; xcf_prop * properties; Uint32 * layer_file_offsets; Uint32 * channel_file_offsets; xcf_compr_type compr; Uint32 cm_num; unsigned char * cm_map; } xcf_header; typedef struct { Uint32 width; Uint32 height; Sint32 layer_type; char * name; xcf_prop * properties; Uint32 hierarchy_file_offset; Uint32 layer_mask_offset; Uint32 offset_x; Uint32 offset_y; int visible; } xcf_layer; typedef struct { Uint32 width; Uint32 height; char * name; xcf_prop * properties; Uint32 hierarchy_file_offset; Uint32 color; Uint32 opacity; int selection; int visible; } xcf_channel; typedef struct { Uint32 width; Uint32 height; Uint32 bpp; Uint32 * level_file_offsets; } xcf_hierarchy; typedef struct { Uint32 width; Uint32 height; Uint32 * tile_file_offsets; } xcf_level; typedef unsigned char * xcf_tile; typedef unsigned char * (* load_tile_type) (SDL_RWops *, Uint32, int, int, int); /* See if an image is contained in a data source */ int IMG_isXCF(SDL_RWops *src) { Sint64 start; int is_XCF; char magic[14]; if ( !src ) return 0; start = SDL_RWtell(src); is_XCF = 0; if ( SDL_RWread(src, magic, sizeof(magic), 1) ) { if (SDL_strncmp(magic, "gimp xcf ", 9) == 0) { is_XCF = 1; } } SDL_RWseek(src, start, RW_SEEK_SET); return(is_XCF); } static char * read_string (SDL_RWops * src) { Sint64 remaining; Uint32 tmp; char * data; tmp = SDL_ReadBE32(src); remaining = SDL_RWsize(src) - SDL_RWtell(src); if (tmp > 0 && (Sint32)tmp <= remaining) { data = (char *) SDL_malloc (sizeof (char) * tmp); if (data) { SDL_RWread(src, data, tmp, 1); data[tmp - 1] = '\0'; } } else { data = NULL; } return data; } static Uint64 read_offset (SDL_RWops * src, const xcf_header * h) { Uint64 offset; // starting with version 11, offsets are 64 bits offset = (h->file_version >= 11) ? (Uint64)SDL_ReadBE32 (src) << 32 : 0; offset |= SDL_ReadBE32 (src); return offset; } static Uint32 Swap32 (Uint32 v) { return ((v & 0x000000FF) << 16) | ((v & 0x0000FF00)) | ((v & 0x00FF0000) >> 16) | ((v & 0xFF000000)); } static int xcf_read_property (SDL_RWops * src, xcf_prop * prop) { Uint32 len; prop->id = SDL_ReadBE32 (src); prop->length = SDL_ReadBE32 (src); #if DEBUG printf ("%.8X: %s(%u): %u\n", SDL_RWtell (src), prop->id < 25 ? prop_names [prop->id] : "unknown", prop->id, prop->length); #endif switch (prop->id) { case PROP_COLORMAP: prop->data.colormap.num = SDL_ReadBE32 (src); prop->data.colormap.cmap = (char *) SDL_malloc (sizeof (char) * prop->data.colormap.num * 3); SDL_RWread (src, prop->data.colormap.cmap, prop->data.colormap.num*3, 1); break; case PROP_OFFSETS: prop->data.offset.x = SDL_ReadBE32 (src); prop->data.offset.y = SDL_ReadBE32 (src); break; case PROP_OPACITY: prop->data.opacity = SDL_ReadBE32 (src); break; case PROP_COMPRESSION: case PROP_COLOR: if (prop->length > sizeof(prop->data)) { len = sizeof(prop->data); } else { len = prop->length; } SDL_RWread(src, &prop->data, len, 1); break; case PROP_VISIBLE: prop->data.visible = SDL_ReadBE32 (src); break; default: // SDL_RWread (src, &prop->data, prop->length, 1); if (SDL_RWseek (src, prop->length, RW_SEEK_CUR) < 0) return 0; // ERROR } return 1; // OK } static void free_xcf_header (xcf_header * h) { if (h->cm_num) SDL_free (h->cm_map); if (h->layer_file_offsets) SDL_free (h->layer_file_offsets); SDL_free (h); } static xcf_header * read_xcf_header (SDL_RWops * src) { xcf_header * h; xcf_prop prop; h = (xcf_header *) SDL_malloc (sizeof (xcf_header)); if (!h) { return NULL; } SDL_RWread (src, h->sign, 14, 1); h->width = SDL_ReadBE32 (src); h->height = SDL_ReadBE32 (src); h->image_type = SDL_ReadBE32 (src); h->file_version = (h->sign[10] - '0') * 100 + (h->sign[11] - '0') * 10 + (h->sign[12] - '0'); #ifdef DEBUG printf ("XCF signature : %.14s (version %u)\n", h->sign, h->file_version); printf (" (%u,%u) type=%u\n", h->width, h->height, h->image_type); #endif if (h->file_version >= 4) h->precision = SDL_ReadBE32 (src); else h->precision = 150; h->properties = NULL; h->layer_file_offsets = NULL; h->compr = COMPR_NONE; h->cm_num = 0; h->cm_map = NULL; // Just read, don't save do { if (!xcf_read_property (src, &prop)) { free_xcf_header (h); return NULL; } if (prop.id == PROP_COMPRESSION) h->compr = (xcf_compr_type)prop.data.compression; else if (prop.id == PROP_COLORMAP) { // unused var: int i; Uint32 cm_num; unsigned char *cm_map; cm_num = prop.data.colormap.num; cm_map = (unsigned char *) SDL_realloc(h->cm_map, sizeof (unsigned char) * 3 * cm_num); if (cm_map) { h->cm_num = cm_num; h->cm_map = cm_map; SDL_memcpy (h->cm_map, prop.data.colormap.cmap, 3*sizeof (char)*h->cm_num); } SDL_free (prop.data.colormap.cmap); if (!cm_map) { free_xcf_header(h); return NULL; } } } while (prop.id != PROP_END); return h; } static void free_xcf_layer (xcf_layer * l) { SDL_free (l->name); SDL_free (l); } static xcf_layer * read_xcf_layer (SDL_RWops * src, const xcf_header * h) { xcf_layer * l; xcf_prop prop; l = (xcf_layer *) SDL_malloc (sizeof (xcf_layer)); l->width = SDL_ReadBE32 (src); l->height = SDL_ReadBE32 (src); l->layer_type = SDL_ReadBE32 (src); l->name = read_string (src); #ifdef DEBUG printf ("layer (%d,%d) type=%d '%s'\n", l->width, l->height, l->layer_type, l->name); #endif do { if (!xcf_read_property (src, &prop)) { free_xcf_layer (l); return NULL; } if (prop.id == PROP_OFFSETS) { l->offset_x = prop.data.offset.x; l->offset_y = prop.data.offset.y; } else if (prop.id == PROP_VISIBLE) { l->visible = prop.data.visible ? 1 : 0; } else if (prop.id == PROP_COLORMAP) { SDL_free (prop.data.colormap.cmap); } } while (prop.id != PROP_END); l->hierarchy_file_offset = read_offset (src, h); l->layer_mask_offset = read_offset (src, h); return l; } static void free_xcf_channel (xcf_channel * c) { SDL_free (c->name); SDL_free (c); } static xcf_channel * read_xcf_channel (SDL_RWops * src, const xcf_header * h) { xcf_channel * l; xcf_prop prop; l = (xcf_channel *) SDL_malloc (sizeof (xcf_channel)); l->width = SDL_ReadBE32 (src); l->height = SDL_ReadBE32 (src); l->name = read_string (src); #ifdef DEBUG printf ("channel (%u,%u) '%s'\n", l->width, l->height, l->name); #endif l->selection = 0; do { if (!xcf_read_property (src, &prop)) { free_xcf_channel (l); return NULL; } switch (prop.id) { case PROP_OPACITY: l->opacity = prop.data.opacity << 24; break; case PROP_COLOR: l->color = ((Uint32) prop.data.color[0] << 16) | ((Uint32) prop.data.color[1] << 8) | ((Uint32) prop.data.color[2]); break; case PROP_SELECTION: l->selection = 1; break; case PROP_VISIBLE: l->visible = prop.data.visible ? 1 : 0; break; default: ; } } while (prop.id != PROP_END); l->hierarchy_file_offset = read_offset (src, h); return l; } static void free_xcf_hierarchy (xcf_hierarchy * h) { SDL_free (h->level_file_offsets); SDL_free (h); } static xcf_hierarchy * read_xcf_hierarchy (SDL_RWops * src, const xcf_header * head) { xcf_hierarchy * h; int i; h = (xcf_hierarchy *) SDL_malloc (sizeof (xcf_hierarchy)); h->width = SDL_ReadBE32 (src); h->height = SDL_ReadBE32 (src); h->bpp = SDL_ReadBE32 (src); h->level_file_offsets = NULL; i = 0; do { h->level_file_offsets = (Uint32 *) SDL_realloc (h->level_file_offsets, sizeof (Uint32) * (i+1)); h->level_file_offsets [i] = read_offset (src, head); } while (h->level_file_offsets [i++]); return h; } static void free_xcf_level (xcf_level * l) { SDL_free (l->tile_file_offsets); SDL_free (l); } static xcf_level * read_xcf_level (SDL_RWops * src, const xcf_header * h) { xcf_level * l; int i; l = (xcf_level *) SDL_malloc (sizeof (xcf_level)); l->width = SDL_ReadBE32 (src); l->height = SDL_ReadBE32 (src); l->tile_file_offsets = NULL; i = 0; do { l->tile_file_offsets = (Uint32 *) SDL_realloc (l->tile_file_offsets, sizeof (Uint32) * (i+1)); l->tile_file_offsets [i] = read_offset (src, h); } while (l->tile_file_offsets [i++]); return l; } static void free_xcf_tile (unsigned char * t) { SDL_free (t); } static unsigned char * load_xcf_tile_none (SDL_RWops * src, Uint32 len, int bpp, int x, int y) { unsigned char * load; load = (unsigned char *) SDL_malloc (len); // expect this is okay if (load != NULL) SDL_RWread (src, load, len, 1); return load; } static unsigned char * load_xcf_tile_rle (SDL_RWops * src, Uint32 len, int bpp, int x, int y) { unsigned char * load, * t, * data, * d; Uint32 reallen; int i, size, count, j, length; unsigned char val; if (len == 0) { /* probably bogus data. */ return NULL; } t = load = (unsigned char *) SDL_malloc (len); if (load == NULL) return NULL; reallen = SDL_RWread (src, t, 1, len); data = (unsigned char *) SDL_calloc (1, x*y*bpp); for (i = 0; i < bpp; i++) { d = data + i; size = x*y; count = 0; while (size > 0) { val = *t++; length = val; if (length >= 128) { length = 255 - (length - 1); if (length == 128) { length = (*t << 8) + t[1]; t += 2; } if (((size_t) (t - load) + length) >= len) { break; /* bogus data */ } else if (length > size) { break; /* bogus data */ } count += length; size -= length; while (length-- > 0) { *d = *t++; d += bpp; } } else { length += 1; if (length == 128) { length = (*t << 8) + t[1]; t += 2; } if (((size_t) (t - load)) >= len) { break; /* bogus data */ } else if (length > size) { break; /* bogus data */ } count += length; size -= length; val = *t++; for (j = 0; j < length; j++) { *d = val; d += bpp; } } } if (size > 0) { break; /* just drop out, untouched data initialized to zero. */ } } SDL_free (load); return (data); } static Uint32 rgb2grey (Uint32 a) { Uint8 l; l = (Uint8)(0.2990 * ((a & 0x00FF0000) >> 16) + 0.5870 * ((a & 0x0000FF00) >> 8) + 0.1140 * ((a & 0x000000FF))); return (l << 16) | (l << 8) | l; } static void create_channel_surface (SDL_Surface * surf, xcf_image_type itype, Uint32 color, Uint32 opacity) { Uint32 c = 0; switch (itype) { case IMAGE_RGB: case IMAGE_INDEXED: c = opacity | color; break; case IMAGE_GREYSCALE: c = opacity | rgb2grey (color); break; } SDL_FillRect (surf, NULL, c); } static int do_layer_surface(SDL_Surface * surface, SDL_RWops * src, xcf_header * head, xcf_layer * layer, load_tile_type load_tile) { xcf_hierarchy *hierarchy; xcf_level *level; unsigned char *tile; Uint8 *p8; Uint16 *p16; Uint32 *p; int i, j; Uint32 x, y, tx, ty, ox, oy; Uint32 *row; Uint32 length; SDL_RWseek(src, layer->hierarchy_file_offset, RW_SEEK_SET); hierarchy = read_xcf_hierarchy(src, head); if (hierarchy->bpp > 4) { /* unsupported. */ SDL_Log("Unknown Gimp image bpp (%u)\n", (unsigned int) hierarchy->bpp); free_xcf_hierarchy(hierarchy); return 1; } if ((hierarchy->width > 20000) || (hierarchy->height > 20000)) { /* arbitrary limit to avoid integer overflow. */ SDL_Log("Gimp image too large (%ux%u)\n", (unsigned int) hierarchy->width, (unsigned int) hierarchy->height); free_xcf_hierarchy(hierarchy); return 1; } level = NULL; for (i = 0; hierarchy->level_file_offsets[i]; i++) { if (SDL_RWseek(src, hierarchy->level_file_offsets[i], RW_SEEK_SET) < 0) break; if (i > 0) // skip level except the 1st one, just like GIMP does continue; level = read_xcf_level(src, head); ty = tx = 0; for (j = 0; level->tile_file_offsets[j]; j++) { SDL_RWseek(src, level->tile_file_offsets[j], RW_SEEK_SET); ox = tx + 64 > level->width ? level->width % 64 : 64; oy = ty + 64 > level->height ? level->height % 64 : 64; length = ox*oy*6; if (level->tile_file_offsets[j + 1] > level->tile_file_offsets[j]) { length = level->tile_file_offsets[j + 1] - level->tile_file_offsets[j]; } tile = load_tile(src, length, hierarchy->bpp, ox, oy); if (!tile) { if (hierarchy) { free_xcf_hierarchy(hierarchy); } if (level) { free_xcf_level(level); } return 1; } p8 = tile; p16 = (Uint16 *) p8; p = (Uint32 *) p8; for (y = ty; y < ty + oy; y++) { if ((y >= surface->h) || ((tx+ox) > surface->w)) { break; } row = (Uint32 *) ((Uint8 *) surface->pixels + y * surface->pitch + tx * 4); switch (hierarchy->bpp) { case 4: for (x = tx; x < tx + ox; x++) *row++ = Swap32(*p++); break; case 3: for (x = tx; x < tx + ox; x++) { *row = 0xFF000000; *row |= ((Uint32)*p8++ << 16); *row |= ((Uint32)*p8++ << 8); *row |= ((Uint32)*p8++ << 0); row++; } break; case 2: /* Indexed / Greyscale + Alpha */ switch (head->image_type) { case IMAGE_INDEXED: for (x = tx; x < tx + ox; x++) { *row = ((Uint32)(head->cm_map[*p8 * 3]) << 16); *row |= ((Uint32)(head->cm_map[*p8 * 3 + 1]) << 8); *row |= ((Uint32)(head->cm_map[*p8++ * 3 + 2]) << 0); *row |= ((Uint32)*p8++ << 24); row++; } break; case IMAGE_GREYSCALE: for (x = tx; x < tx + ox; x++) { *row = ((Uint32)*p8 << 16); *row |= ((Uint32)*p8 << 8); *row |= ((Uint32)*p8++ << 0); *row |= ((Uint32)*p8++ << 24); row++; } break; default: SDL_Log("Unknown Gimp image type (%d)\n", head->image_type); if (hierarchy) { free_xcf_hierarchy(hierarchy); } if (level) free_xcf_level(level); return 1; } break; case 1: /* Indexed / Greyscale */ switch (head->image_type) { case IMAGE_INDEXED: for (x = tx; x < tx + ox; x++) { *row++ = 0xFF000000 | ((Uint32)(head->cm_map[*p8 * 3]) << 16) | ((Uint32)(head->cm_map[*p8 * 3 + 1]) << 8) | ((Uint32)(head->cm_map[*p8 * 3 + 2]) << 0); p8++; } break; case IMAGE_GREYSCALE: for (x = tx; x < tx + ox; x++) { *row++ = 0xFF000000 | (((Uint32)(*p8)) << 16) | (((Uint32)(*p8)) << 8) | (((Uint32)(*p8)) << 0); ++p8; } break; default: SDL_Log("Unknown Gimp image type (%d)\n", head->image_type); if (tile) free_xcf_tile(tile); if (level) free_xcf_level(level); if (hierarchy) free_xcf_hierarchy(hierarchy); return 1; } break; } } free_xcf_tile(tile); tx += 64; if (tx >= level->width) { tx = 0; ty += 64; } if (ty >= level->height) { break; } } free_xcf_level(level); } free_xcf_hierarchy(hierarchy); return 0; } SDL_Surface *IMG_LoadXCF_RW(SDL_RWops *src) { Sint64 start; const char *error = NULL; SDL_Surface *surface, *lays; xcf_header * head; xcf_layer * layer; xcf_channel ** channel; int chnls, i, offsets; Sint64 offset, fp; unsigned char * (* load_tile) (SDL_RWops *, Uint32, int, int, int); if (!src) { /* The error message has been set in SDL_RWFromFile */ return NULL; } start = SDL_RWtell(src); /* Initialize the data we will clean up when we're done */ surface = NULL; head = read_xcf_header(src); if (!head) { return NULL; } switch (head->compr) { case COMPR_NONE: load_tile = load_xcf_tile_none; break; case COMPR_RLE: load_tile = load_xcf_tile_rle; break; default: SDL_Log("Unsupported Compression.\n"); free_xcf_header (head); return NULL; } /* Create the surface of the appropriate type */ surface = SDL_CreateRGBSurface(SDL_SWSURFACE, head->width, head->height, 32, 0x00FF0000,0x0000FF00,0x000000FF,0xFF000000); if ( surface == NULL ) { error = "Out of memory"; goto done; } offsets = 0; while ((offset = read_offset (src, head))) { head->layer_file_offsets = (Uint32 *) SDL_realloc (head->layer_file_offsets, sizeof (Uint32) * (offsets+1)); head->layer_file_offsets [offsets] = (Uint32)offset; offsets++; } fp = SDL_RWtell (src); lays = SDL_CreateRGBSurface(SDL_SWSURFACE, head->width, head->height, 32, 0x00FF0000,0x0000FF00,0x000000FF,0xFF000000); if ( lays == NULL ) { error = "Out of memory"; goto done; } // Blit layers backwards, because Gimp saves them highest first for (i = offsets; i > 0; i--) { SDL_Rect rs, rd; SDL_RWseek (src, head->layer_file_offsets [i-1], RW_SEEK_SET); layer = read_xcf_layer (src, head); if (layer != NULL) { do_layer_surface (lays, src, head, layer, load_tile); rs.x = 0; rs.y = 0; rs.w = layer->width; rs.h = layer->height; rd.x = layer->offset_x; rd.y = layer->offset_y; rd.w = layer->width; rd.h = layer->height; if (layer->visible) SDL_BlitSurface (lays, &rs, surface, &rd); free_xcf_layer (layer); } } SDL_FreeSurface (lays); SDL_RWseek (src, fp, RW_SEEK_SET); // read channels channel = NULL; chnls = 0; while ((offset = read_offset (src, head))) { channel = (xcf_channel **) SDL_realloc (channel, sizeof (xcf_channel *) * (chnls+1)); fp = SDL_RWtell (src); SDL_RWseek (src, offset, RW_SEEK_SET); channel [chnls] = (read_xcf_channel (src, head)); if (channel [chnls] != NULL) chnls++; SDL_RWseek (src, fp, RW_SEEK_SET); } if (chnls) { SDL_Surface * chs; chs = SDL_CreateRGBSurface(SDL_SWSURFACE, head->width, head->height, 32, 0x00FF0000,0x0000FF00,0x000000FF,0xFF000000); if (chs == NULL) { error = "Out of memory"; goto done; } for (i = 0; i < chnls; i++) { // printf ("CNLBLT %i\n", i); if (!channel [i]->selection && channel [i]->visible) { create_channel_surface (chs, (xcf_image_type)head->image_type, channel [i]->color, channel [i]->opacity); SDL_BlitSurface (chs, NULL, surface, NULL); } free_xcf_channel (channel [i]); } SDL_free(channel); SDL_FreeSurface (chs); } done: free_xcf_header (head); if ( error ) { SDL_RWseek(src, start, RW_SEEK_SET); if ( surface ) { SDL_FreeSurface(surface); surface = NULL; } IMG_SetError("%s", error); } return(surface); } #else /* See if an image is contained in a data source */ int IMG_isXCF(SDL_RWops *src) { return(0); } /* Load a XCF type image from an SDL datasource */ SDL_Surface *IMG_LoadXCF_RW(SDL_RWops *src) { return(NULL); } #endif /* LOAD_XCF */
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG_xcf.c
C
apache-2.0
24,496
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* * XPM (X PixMap) image loader: * * Supports the XPMv3 format, EXCEPT: * - hotspot coordinates are ignored * - only colour ('c') colour symbols are used * - rgb.txt is not used (for portability), so only RGB colours * are recognized (#rrggbb etc) - only a few basic colour names are * handled * * The result is an 8bpp indexed surface if possible, otherwise 32bpp. * The colourkey is correctly set if transparency is used. * * Besides the standard API, also provides * * SDL_Surface *IMG_ReadXPMFromArray(char **xpm) * * that reads the image data from an XPM file included in the C source. * * TODO: include rgb.txt here. The full table (from solaris 2.6) only * requires about 13K in binary form. */ #include "SDL_image.h" #ifdef LOAD_XPM /* See if an image is contained in a data source */ int IMG_isXPM(SDL_RWops *src) { Sint64 start; int is_XPM; char magic[9]; if ( !src ) return 0; start = SDL_RWtell(src); is_XPM = 0; if ( SDL_RWread(src, magic, sizeof(magic), 1) ) { if ( SDL_memcmp(magic, "/* XPM */", sizeof(magic)) == 0 ) { is_XPM = 1; } } SDL_RWseek(src, start, RW_SEEK_SET); return(is_XPM); } /* Hash table to look up colors from pixel strings */ #define STARTING_HASH_SIZE 256 struct hash_entry { char *key; Uint32 color; struct hash_entry *next; }; struct color_hash { struct hash_entry **table; struct hash_entry *entries; /* array of all entries */ struct hash_entry *next_free; int size; int maxnum; }; static int hash_key(const char *key, int cpp, int size) { int hash; hash = 0; while ( cpp-- > 0 ) { hash = hash * 33 + *key++; } return hash & (size - 1); } static struct color_hash *create_colorhash(int maxnum) { int bytes, s; struct color_hash *hash; /* we know how many entries we need, so we can allocate everything here */ hash = (struct color_hash *)SDL_calloc(1, sizeof(*hash)); if (!hash) return NULL; /* use power-of-2 sized hash table for decoding speed */ for (s = STARTING_HASH_SIZE; s < maxnum; s <<= 1) ; hash->size = s; hash->maxnum = maxnum; bytes = hash->size * sizeof(struct hash_entry **); /* Check for overflow */ if ((bytes / sizeof(struct hash_entry **)) != hash->size) { IMG_SetError("memory allocation overflow"); SDL_free(hash); return NULL; } hash->table = (struct hash_entry **)SDL_calloc(1, bytes); if (!hash->table) { SDL_free(hash); return NULL; } bytes = maxnum * sizeof(struct hash_entry); /* Check for overflow */ if ((bytes / sizeof(struct hash_entry)) != maxnum) { IMG_SetError("memory allocation overflow"); SDL_free(hash->table); SDL_free(hash); return NULL; } hash->entries = (struct hash_entry *)SDL_calloc(1, bytes); if (!hash->entries) { SDL_free(hash->table); SDL_free(hash); return NULL; } hash->next_free = hash->entries; return hash; } static int add_colorhash(struct color_hash *hash, char *key, int cpp, Uint32 color) { int index = hash_key(key, cpp, hash->size); struct hash_entry *e = hash->next_free++; e->color = color; e->key = key; e->next = hash->table[index]; hash->table[index] = e; return 1; } /* fast lookup that works if cpp == 1 */ #define QUICK_COLORHASH(hash, key) ((hash)->table[*(Uint8 *)(key)]->color) static Uint32 get_colorhash(struct color_hash *hash, const char *key, int cpp) { struct hash_entry *entry = hash->table[hash_key(key, cpp, hash->size)]; while (entry) { if (SDL_memcmp(key, entry->key, cpp) == 0) return entry->color; entry = entry->next; } return 0; /* garbage in - garbage out */ } static void free_colorhash(struct color_hash *hash) { if (hash) { if (hash->table) SDL_free(hash->table); if (hash->entries) SDL_free(hash->entries); SDL_free(hash); } } /* * convert colour spec to RGB (in 0xrrggbb format). * return 1 if successful. */ static int color_to_rgb(char *spec, int speclen, Uint32 *rgb) { /* poor man's rgb.txt */ static struct { char *name; Uint32 rgb; } known[] = { { "none", 0xFFFFFFFF }, { "black", 0x000000 }, { "white", 0xFFFFFF }, { "red", 0xFF0000 }, { "green", 0x00FF00 }, { "blue", 0x0000FF }, /* This table increases the size of the library by 40K, so it's disabled by default */ #ifdef EXTENDED_XPM_COLORS { "aliceblue", 0xf0f8ff }, { "antiquewhite", 0xfaebd7 }, { "antiquewhite1", 0xffefdb }, { "antiquewhite2", 0xeedfcc }, { "antiquewhite3", 0xcdc0b0 }, { "antiquewhite4", 0x8b8378 }, { "aqua", 0x00ffff }, { "aquamarine", 0x7fffd4 }, { "aquamarine1", 0x7fffd4 }, { "aquamarine2", 0x76eec6 }, { "aquamarine3", 0x66cdaa }, { "aquamarine4", 0x458b74 }, { "azure", 0xf0ffff }, { "azure1", 0xf0ffff }, { "azure2", 0xe0eeee }, { "azure3", 0xc1cdcd }, { "azure4", 0x838b8b }, { "beige", 0xf5f5dc }, { "bisque", 0xffe4c4 }, { "bisque1", 0xffe4c4 }, { "bisque2", 0xeed5b7 }, { "bisque3", 0xcdb79e }, { "bisque4", 0x8b7d6b }, { "black", 0x000000 }, { "blanchedalmond", 0xffebcd }, { "blue", 0x0000ff }, { "blue1", 0x0000ff }, { "blue2", 0x0000ee }, { "blue3", 0x0000cd }, { "blue4", 0x00008B }, { "blueviolet", 0x8a2be2 }, { "brown", 0xA52A2A }, { "brown1", 0xFF4040 }, { "brown2", 0xEE3B3B }, { "brown3", 0xCD3333 }, { "brown4", 0x8B2323 }, { "burlywood", 0xDEB887 }, { "burlywood1", 0xFFD39B }, { "burlywood2", 0xEEC591 }, { "burlywood3", 0xCDAA7D }, { "burlywood4", 0x8B7355 }, { "cadetblue", 0x5F9EA0 }, { "cadetblue", 0x5f9ea0 }, { "cadetblue1", 0x98f5ff }, { "cadetblue2", 0x8ee5ee }, { "cadetblue3", 0x7ac5cd }, { "cadetblue4", 0x53868b }, { "chartreuse", 0x7FFF00 }, { "chartreuse1", 0x7FFF00 }, { "chartreuse2", 0x76EE00 }, { "chartreuse3", 0x66CD00 }, { "chartreuse4", 0x458B00 }, { "chocolate", 0xD2691E }, { "chocolate1", 0xFF7F24 }, { "chocolate2", 0xEE7621 }, { "chocolate3", 0xCD661D }, { "chocolate4", 0x8B4513 }, { "coral", 0xFF7F50 }, { "coral1", 0xFF7256 }, { "coral2", 0xEE6A50 }, { "coral3", 0xCD5B45 }, { "coral4", 0x8B3E2F }, { "cornflowerblue", 0x6495ed }, { "cornsilk", 0xFFF8DC }, { "cornsilk1", 0xFFF8DC }, { "cornsilk2", 0xEEE8CD }, { "cornsilk3", 0xCDC8B1 }, { "cornsilk4", 0x8B8878 }, { "crimson", 0xDC143C }, { "cyan", 0x00FFFF }, { "cyan1", 0x00FFFF }, { "cyan2", 0x00EEEE }, { "cyan3", 0x00CDCD }, { "cyan4", 0x008B8B }, { "darkblue", 0x00008b }, { "darkcyan", 0x008b8b }, { "darkgoldenrod", 0xb8860b }, { "darkgoldenrod1", 0xffb90f }, { "darkgoldenrod2", 0xeead0e }, { "darkgoldenrod3", 0xcd950c }, { "darkgoldenrod4", 0x8b6508 }, { "darkgray", 0xa9a9a9 }, { "darkgreen", 0x006400 }, { "darkgrey", 0xa9a9a9 }, { "darkkhaki", 0xbdb76b }, { "darkmagenta", 0x8b008b }, { "darkolivegreen", 0x556b2f }, { "darkolivegreen1", 0xcaff70 }, { "darkolivegreen2", 0xbcee68 }, { "darkolivegreen3", 0xa2cd5a }, { "darkolivegreen4", 0x6e8b3d }, { "darkorange", 0xff8c00 }, { "darkorange1", 0xff7f00 }, { "darkorange2", 0xee7600 }, { "darkorange3", 0xcd6600 }, { "darkorange4", 0x8b4500 }, { "darkorchid", 0x9932cc }, { "darkorchid1", 0xbf3eff }, { "darkorchid2", 0xb23aee }, { "darkorchid3", 0x9a32cd }, { "darkorchid4", 0x68228b }, { "darkred", 0x8b0000 }, { "darksalmon", 0xe9967a }, { "darkseagreen", 0x8fbc8f }, { "darkseagreen1", 0xc1ffc1 }, { "darkseagreen2", 0xb4eeb4 }, { "darkseagreen3", 0x9bcd9b }, { "darkseagreen4", 0x698b69 }, { "darkslateblue", 0x483d8b }, { "darkslategray", 0x2f4f4f }, { "darkslategray1", 0x97ffff }, { "darkslategray2", 0x8deeee }, { "darkslategray3", 0x79cdcd }, { "darkslategray4", 0x528b8b }, { "darkslategrey", 0x2f4f4f }, { "darkturquoise", 0x00ced1 }, { "darkviolet", 0x9400D3 }, { "darkviolet", 0x9400d3 }, { "deeppink", 0xff1493 }, { "deeppink1", 0xff1493 }, { "deeppink2", 0xee1289 }, { "deeppink3", 0xcd1076 }, { "deeppink4", 0x8b0a50 }, { "deepskyblue", 0x00bfff }, { "deepskyblue1", 0x00bfff }, { "deepskyblue2", 0x00b2ee }, { "deepskyblue3", 0x009acd }, { "deepskyblue4", 0x00688b }, { "dimgray", 0x696969 }, { "dimgrey", 0x696969 }, { "dodgerblue", 0x1e90ff }, { "dodgerblue1", 0x1e90ff }, { "dodgerblue2", 0x1c86ee }, { "dodgerblue3", 0x1874cd }, { "dodgerblue4", 0x104e8b }, { "firebrick", 0xB22222 }, { "firebrick1", 0xFF3030 }, { "firebrick2", 0xEE2C2C }, { "firebrick3", 0xCD2626 }, { "firebrick4", 0x8B1A1A }, { "floralwhite", 0xfffaf0 }, { "forestgreen", 0x228b22 }, { "fractal", 0x808080 }, { "fuchsia", 0xFF00FF }, { "gainsboro", 0xDCDCDC }, { "ghostwhite", 0xf8f8ff }, { "gold", 0xFFD700 }, { "gold1", 0xFFD700 }, { "gold2", 0xEEC900 }, { "gold3", 0xCDAD00 }, { "gold4", 0x8B7500 }, { "goldenrod", 0xDAA520 }, { "goldenrod1", 0xFFC125 }, { "goldenrod2", 0xEEB422 }, { "goldenrod3", 0xCD9B1D }, { "goldenrod4", 0x8B6914 }, { "gray", 0x7E7E7E }, { "gray", 0xBEBEBE }, { "gray0", 0x000000 }, { "gray1", 0x030303 }, { "gray10", 0x1A1A1A }, { "gray100", 0xFFFFFF }, { "gray11", 0x1C1C1C }, { "gray12", 0x1F1F1F }, { "gray13", 0x212121 }, { "gray14", 0x242424 }, { "gray15", 0x262626 }, { "gray16", 0x292929 }, { "gray17", 0x2B2B2B }, { "gray18", 0x2E2E2E }, { "gray19", 0x303030 }, { "gray2", 0x050505 }, { "gray20", 0x333333 }, { "gray21", 0x363636 }, { "gray22", 0x383838 }, { "gray23", 0x3B3B3B }, { "gray24", 0x3D3D3D }, { "gray25", 0x404040 }, { "gray26", 0x424242 }, { "gray27", 0x454545 }, { "gray28", 0x474747 }, { "gray29", 0x4A4A4A }, { "gray3", 0x080808 }, { "gray30", 0x4D4D4D }, { "gray31", 0x4F4F4F }, { "gray32", 0x525252 }, { "gray33", 0x545454 }, { "gray34", 0x575757 }, { "gray35", 0x595959 }, { "gray36", 0x5C5C5C }, { "gray37", 0x5E5E5E }, { "gray38", 0x616161 }, { "gray39", 0x636363 }, { "gray4", 0x0A0A0A }, { "gray40", 0x666666 }, { "gray41", 0x696969 }, { "gray42", 0x6B6B6B }, { "gray43", 0x6E6E6E }, { "gray44", 0x707070 }, { "gray45", 0x737373 }, { "gray46", 0x757575 }, { "gray47", 0x787878 }, { "gray48", 0x7A7A7A }, { "gray49", 0x7D7D7D }, { "gray5", 0x0D0D0D }, { "gray50", 0x7F7F7F }, { "gray51", 0x828282 }, { "gray52", 0x858585 }, { "gray53", 0x878787 }, { "gray54", 0x8A8A8A }, { "gray55", 0x8C8C8C }, { "gray56", 0x8F8F8F }, { "gray57", 0x919191 }, { "gray58", 0x949494 }, { "gray59", 0x969696 }, { "gray6", 0x0F0F0F }, { "gray60", 0x999999 }, { "gray61", 0x9C9C9C }, { "gray62", 0x9E9E9E }, { "gray63", 0xA1A1A1 }, { "gray64", 0xA3A3A3 }, { "gray65", 0xA6A6A6 }, { "gray66", 0xA8A8A8 }, { "gray67", 0xABABAB }, { "gray68", 0xADADAD }, { "gray69", 0xB0B0B0 }, { "gray7", 0x121212 }, { "gray70", 0xB3B3B3 }, { "gray71", 0xB5B5B5 }, { "gray72", 0xB8B8B8 }, { "gray73", 0xBABABA }, { "gray74", 0xBDBDBD }, { "gray75", 0xBFBFBF }, { "gray76", 0xC2C2C2 }, { "gray77", 0xC4C4C4 }, { "gray78", 0xC7C7C7 }, { "gray79", 0xC9C9C9 }, { "gray8", 0x141414 }, { "gray80", 0xCCCCCC }, { "gray81", 0xCFCFCF }, { "gray82", 0xD1D1D1 }, { "gray83", 0xD4D4D4 }, { "gray84", 0xD6D6D6 }, { "gray85", 0xD9D9D9 }, { "gray86", 0xDBDBDB }, { "gray87", 0xDEDEDE }, { "gray88", 0xE0E0E0 }, { "gray89", 0xE3E3E3 }, { "gray9", 0x171717 }, { "gray90", 0xE5E5E5 }, { "gray91", 0xE8E8E8 }, { "gray92", 0xEBEBEB }, { "gray93", 0xEDEDED }, { "gray94", 0xF0F0F0 }, { "gray95", 0xF2F2F2 }, { "gray96", 0xF5F5F5 }, { "gray97", 0xF7F7F7 }, { "gray98", 0xFAFAFA }, { "gray99", 0xFCFCFC }, { "green", 0x008000 }, { "green", 0x00FF00 }, { "green1", 0x00FF00 }, { "green2", 0x00EE00 }, { "green3", 0x00CD00 }, { "green4", 0x008B00 }, { "greenyellow", 0xadff2f }, { "grey", 0xBEBEBE }, { "grey0", 0x000000 }, { "grey1", 0x030303 }, { "grey10", 0x1A1A1A }, { "grey100", 0xFFFFFF }, { "grey11", 0x1C1C1C }, { "grey12", 0x1F1F1F }, { "grey13", 0x212121 }, { "grey14", 0x242424 }, { "grey15", 0x262626 }, { "grey16", 0x292929 }, { "grey17", 0x2B2B2B }, { "grey18", 0x2E2E2E }, { "grey19", 0x303030 }, { "grey2", 0x050505 }, { "grey20", 0x333333 }, { "grey21", 0x363636 }, { "grey22", 0x383838 }, { "grey23", 0x3B3B3B }, { "grey24", 0x3D3D3D }, { "grey25", 0x404040 }, { "grey26", 0x424242 }, { "grey27", 0x454545 }, { "grey28", 0x474747 }, { "grey29", 0x4A4A4A }, { "grey3", 0x080808 }, { "grey30", 0x4D4D4D }, { "grey31", 0x4F4F4F }, { "grey32", 0x525252 }, { "grey33", 0x545454 }, { "grey34", 0x575757 }, { "grey35", 0x595959 }, { "grey36", 0x5C5C5C }, { "grey37", 0x5E5E5E }, { "grey38", 0x616161 }, { "grey39", 0x636363 }, { "grey4", 0x0A0A0A }, { "grey40", 0x666666 }, { "grey41", 0x696969 }, { "grey42", 0x6B6B6B }, { "grey43", 0x6E6E6E }, { "grey44", 0x707070 }, { "grey45", 0x737373 }, { "grey46", 0x757575 }, { "grey47", 0x787878 }, { "grey48", 0x7A7A7A }, { "grey49", 0x7D7D7D }, { "grey5", 0x0D0D0D }, { "grey50", 0x7F7F7F }, { "grey51", 0x828282 }, { "grey52", 0x858585 }, { "grey53", 0x878787 }, { "grey54", 0x8A8A8A }, { "grey55", 0x8C8C8C }, { "grey56", 0x8F8F8F }, { "grey57", 0x919191 }, { "grey58", 0x949494 }, { "grey59", 0x969696 }, { "grey6", 0x0F0F0F }, { "grey60", 0x999999 }, { "grey61", 0x9C9C9C }, { "grey62", 0x9E9E9E }, { "grey63", 0xA1A1A1 }, { "grey64", 0xA3A3A3 }, { "grey65", 0xA6A6A6 }, { "grey66", 0xA8A8A8 }, { "grey67", 0xABABAB }, { "grey68", 0xADADAD }, { "grey69", 0xB0B0B0 }, { "grey7", 0x121212 }, { "grey70", 0xB3B3B3 }, { "grey71", 0xB5B5B5 }, { "grey72", 0xB8B8B8 }, { "grey73", 0xBABABA }, { "grey74", 0xBDBDBD }, { "grey75", 0xBFBFBF }, { "grey76", 0xC2C2C2 }, { "grey77", 0xC4C4C4 }, { "grey78", 0xC7C7C7 }, { "grey79", 0xC9C9C9 }, { "grey8", 0x141414 }, { "grey80", 0xCCCCCC }, { "grey81", 0xCFCFCF }, { "grey82", 0xD1D1D1 }, { "grey83", 0xD4D4D4 }, { "grey84", 0xD6D6D6 }, { "grey85", 0xD9D9D9 }, { "grey86", 0xDBDBDB }, { "grey87", 0xDEDEDE }, { "grey88", 0xE0E0E0 }, { "grey89", 0xE3E3E3 }, { "grey9", 0x171717 }, { "grey90", 0xE5E5E5 }, { "grey91", 0xE8E8E8 }, { "grey92", 0xEBEBEB }, { "grey93", 0xEDEDED }, { "grey94", 0xF0F0F0 }, { "grey95", 0xF2F2F2 }, { "grey96", 0xF5F5F5 }, { "grey97", 0xF7F7F7 }, { "grey98", 0xFAFAFA }, { "grey99", 0xFCFCFC }, { "honeydew", 0xF0FFF0 }, { "honeydew1", 0xF0FFF0 }, { "honeydew2", 0xE0EEE0 }, { "honeydew3", 0xC1CDC1 }, { "honeydew4", 0x838B83 }, { "hotpink", 0xff69b4 }, { "hotpink1", 0xff6eb4 }, { "hotpink2", 0xee6aa7 }, { "hotpink3", 0xcd6090 }, { "hotpink4", 0x8b3a62 }, { "indianred", 0xcd5c5c }, { "indianred1", 0xff6a6a }, { "indianred2", 0xee6363 }, { "indianred3", 0xcd5555 }, { "indianred4", 0x8b3a3a }, { "indigo", 0x4B0082 }, { "ivory", 0xFFFFF0 }, { "ivory1", 0xFFFFF0 }, { "ivory2", 0xEEEEE0 }, { "ivory3", 0xCDCDC1 }, { "ivory4", 0x8B8B83 }, { "khaki", 0xF0E68C }, { "khaki1", 0xFFF68F }, { "khaki2", 0xEEE685 }, { "khaki3", 0xCDC673 }, { "khaki4", 0x8B864E }, { "lavender", 0xE6E6FA }, { "lavenderblush", 0xfff0f5 }, { "lavenderblush1", 0xfff0f5 }, { "lavenderblush2", 0xeee0e5 }, { "lavenderblush3", 0xcdc1c5 }, { "lavenderblush4", 0x8b8386 }, { "lawngreen", 0x7cfc00 }, { "lemonchiffon", 0xfffacd }, { "lemonchiffon1", 0xfffacd }, { "lemonchiffon2", 0xeee9bf }, { "lemonchiffon3", 0xcdc9a5 }, { "lemonchiffon4", 0x8b8970 }, { "lightblue", 0xadd8e6 }, { "lightblue1", 0xbfefff }, { "lightblue2", 0xb2dfee }, { "lightblue3", 0x9ac0cd }, { "lightblue4", 0x68838b }, { "lightcoral", 0xf08080 }, { "lightcyan", 0xe0ffff }, { "lightcyan1", 0xe0ffff }, { "lightcyan2", 0xd1eeee }, { "lightcyan3", 0xb4cdcd }, { "lightcyan4", 0x7a8b8b }, { "lightgoldenrod", 0xeedd82 }, { "lightgoldenrod1", 0xffec8b }, { "lightgoldenrod2", 0xeedc82 }, { "lightgoldenrod3", 0xcdbe70 }, { "lightgoldenrod4", 0x8b814c }, { "lightgoldenrodyellow", 0xfafad2 }, { "lightgray", 0xd3d3d3 }, { "lightgreen", 0x90ee90 }, { "lightgrey", 0xd3d3d3 }, { "lightpink", 0xffb6c1 }, { "lightpink1", 0xffaeb9 }, { "lightpink2", 0xeea2ad }, { "lightpink3", 0xcd8c95 }, { "lightpink4", 0x8b5f65 }, { "lightsalmon", 0xffa07a }, { "lightsalmon1", 0xffa07a }, { "lightsalmon2", 0xee9572 }, { "lightsalmon3", 0xcd8162 }, { "lightsalmon4", 0x8b5742 }, { "lightseagreen", 0x20b2aa }, { "lightskyblue", 0x87cefa }, { "lightskyblue1", 0xb0e2ff }, { "lightskyblue2", 0xa4d3ee }, { "lightskyblue3", 0x8db6cd }, { "lightskyblue4", 0x607b8b }, { "lightslateblue", 0x8470ff }, { "lightslategray", 0x778899 }, { "lightslategrey", 0x778899 }, { "lightsteelblue", 0xb0c4de }, { "lightsteelblue1", 0xcae1ff }, { "lightsteelblue2", 0xbcd2ee }, { "lightsteelblue3", 0xa2b5cd }, { "lightsteelblue4", 0x6e7b8b }, { "lightyellow", 0xffffe0 }, { "lightyellow1", 0xffffe0 }, { "lightyellow2", 0xeeeed1 }, { "lightyellow3", 0xcdcdb4 }, { "lightyellow4", 0x8b8b7a }, { "lime", 0x00FF00 }, { "limegreen", 0x32cd32 }, { "linen", 0xFAF0E6 }, { "magenta", 0xFF00FF }, { "magenta1", 0xFF00FF }, { "magenta2", 0xEE00EE }, { "magenta3", 0xCD00CD }, { "magenta4", 0x8B008B }, { "maroon", 0x800000 }, { "maroon", 0xB03060 }, { "maroon1", 0xFF34B3 }, { "maroon2", 0xEE30A7 }, { "maroon3", 0xCD2990 }, { "maroon4", 0x8B1C62 }, { "mediumaquamarine", 0x66cdaa }, { "mediumblue", 0x0000cd }, { "mediumforestgreen", 0x32814b }, { "mediumgoldenrod", 0xd1c166 }, { "mediumorchid", 0xba55d3 }, { "mediumorchid1", 0xe066ff }, { "mediumorchid2", 0xd15fee }, { "mediumorchid3", 0xb452cd }, { "mediumorchid4", 0x7a378b }, { "mediumpurple", 0x9370db }, { "mediumpurple1", 0xab82ff }, { "mediumpurple2", 0x9f79ee }, { "mediumpurple3", 0x8968cd }, { "mediumpurple4", 0x5d478b }, { "mediumseagreen", 0x3cb371 }, { "mediumslateblue", 0x7b68ee }, { "mediumspringgreen", 0x00fa9a }, { "mediumturquoise", 0x48d1cc }, { "mediumvioletred", 0xc71585 }, { "midnightblue", 0x191970 }, { "mintcream", 0xf5fffa }, { "mistyrose", 0xffe4e1 }, { "mistyrose1", 0xffe4e1 }, { "mistyrose2", 0xeed5d2 }, { "mistyrose3", 0xcdb7b5 }, { "mistyrose4", 0x8b7d7b }, { "moccasin", 0xFFE4B5 }, { "navajowhite", 0xffdead }, { "navajowhite1", 0xffdead }, { "navajowhite2", 0xeecfa1 }, { "navajowhite3", 0xcdb38b }, { "navajowhite4", 0x8b795e }, { "navy", 0x000080 }, { "navyblue", 0x000080 }, { "none", 0x0000FF }, { "oldlace", 0xfdf5e6 }, { "olive", 0x808000 }, { "olivedrab", 0x6b8e23 }, { "olivedrab1", 0xc0ff3e }, { "olivedrab2", 0xb3ee3a }, { "olivedrab3", 0x9acd32 }, { "olivedrab4", 0x698b22 }, { "opaque", 0x000000 }, { "orange", 0xFFA500 }, { "orange1", 0xFFA500 }, { "orange2", 0xEE9A00 }, { "orange3", 0xCD8500 }, { "orange4", 0x8B5A00 }, { "orangered", 0xff4500 }, { "orangered1", 0xff4500 }, { "orangered2", 0xee4000 }, { "orangered3", 0xcd3700 }, { "orangered4", 0x8b2500 }, { "orchid", 0xDA70D6 }, { "orchid1", 0xFF83FA }, { "orchid2", 0xEE7AE9 }, { "orchid3", 0xCD69C9 }, { "orchid4", 0x8B4789 }, { "palegoldenrod", 0xeee8aa }, { "palegreen", 0x98fb98 }, { "palegreen1", 0x9aff9a }, { "palegreen2", 0x90ee90 }, { "palegreen3", 0x7ccd7c }, { "palegreen4", 0x548b54 }, { "paleturquoise", 0xafeeee }, { "paleturquoise1", 0xbbffff }, { "paleturquoise2", 0xaeeeee }, { "paleturquoise3", 0x96cdcd }, { "paleturquoise4", 0x668b8b }, { "palevioletred", 0xdb7093 }, { "palevioletred1", 0xff82ab }, { "palevioletred2", 0xee799f }, { "palevioletred3", 0xcd6889 }, { "palevioletred4", 0x8b475d }, { "papayawhip", 0xffefd5 }, { "peachpuff", 0xffdab9 }, { "peachpuff1", 0xffdab9 }, { "peachpuff2", 0xeecbad }, { "peachpuff3", 0xcdaf95 }, { "peachpuff4", 0x8b7765 }, { "peru", 0xCD853F }, { "pink", 0xFFC0CB }, { "pink1", 0xFFB5C5 }, { "pink2", 0xEEA9B8 }, { "pink3", 0xCD919E }, { "pink4", 0x8B636C }, { "plum", 0xDDA0DD }, { "plum1", 0xFFBBFF }, { "plum2", 0xEEAEEE }, { "plum3", 0xCD96CD }, { "plum4", 0x8B668B }, { "powderblue", 0xb0e0e6 }, { "purple", 0x800080 }, { "purple", 0xA020F0 }, { "purple1", 0x9B30FF }, { "purple2", 0x912CEE }, { "purple3", 0x7D26CD }, { "purple4", 0x551A8B }, { "red", 0xFF0000 }, { "red1", 0xFF0000 }, { "red2", 0xEE0000 }, { "red3", 0xCD0000 }, { "red4", 0x8B0000 }, { "rosybrown", 0xbc8f8f }, { "rosybrown1", 0xffc1c1 }, { "rosybrown2", 0xeeb4b4 }, { "rosybrown3", 0xcd9b9b }, { "rosybrown4", 0x8b6969 }, { "royalblue", 0x4169e1 }, { "royalblue1", 0x4876ff }, { "royalblue2", 0x436eee }, { "royalblue3", 0x3a5fcd }, { "royalblue4", 0x27408b }, { "saddlebrown", 0x8b4513 }, { "salmon", 0xFA8072 }, { "salmon1", 0xFF8C69 }, { "salmon2", 0xEE8262 }, { "salmon3", 0xCD7054 }, { "salmon4", 0x8B4C39 }, { "sandybrown", 0xf4a460 }, { "seagreen", 0x2e8b57 }, { "seagreen1", 0x54ff9f }, { "seagreen2", 0x4eee94 }, { "seagreen3", 0x43cd80 }, { "seagreen4", 0x2e8b57 }, { "seashell", 0xFFF5EE }, { "seashell1", 0xFFF5EE }, { "seashell2", 0xEEE5DE }, { "seashell3", 0xCDC5BF }, { "seashell4", 0x8B8682 }, { "sienna", 0xA0522D }, { "sienna1", 0xFF8247 }, { "sienna2", 0xEE7942 }, { "sienna3", 0xCD6839 }, { "sienna4", 0x8B4726 }, { "silver", 0xC0C0C0 }, { "skyblue", 0x87ceeb }, { "skyblue1", 0x87ceff }, { "skyblue2", 0x7ec0ee }, { "skyblue3", 0x6ca6cd }, { "skyblue4", 0x4a708b }, { "slateblue", 0x6a5acd }, { "slateblue1", 0x836fff }, { "slateblue2", 0x7a67ee }, { "slateblue3", 0x6959cd }, { "slateblue4", 0x473c8b }, { "slategray", 0x708090 }, { "slategray1", 0xc6e2ff }, { "slategray2", 0xb9d3ee }, { "slategray3", 0x9fb6cd }, { "slategray4", 0x6c7b8b }, { "slategrey", 0x708090 }, { "snow", 0xFFFAFA }, { "snow1", 0xFFFAFA }, { "snow2", 0xEEE9E9 }, { "snow3", 0xCDC9C9 }, { "snow4", 0x8B8989 }, { "springgreen", 0x00ff7f }, { "springgreen1", 0x00ff7f }, { "springgreen2", 0x00ee76 }, { "springgreen3", 0x00cd66 }, { "springgreen4", 0x008b45 }, { "steelblue", 0x4682b4 }, { "steelblue1", 0x63b8ff }, { "steelblue2", 0x5cacee }, { "steelblue3", 0x4f94cd }, { "steelblue4", 0x36648b }, { "tan", 0xD2B48C }, { "tan1", 0xFFA54F }, { "tan2", 0xEE9A49 }, { "tan3", 0xCD853F }, { "tan4", 0x8B5A2B }, { "teal", 0x008080 }, { "thistle", 0xD8BFD8 }, { "thistle1", 0xFFE1FF }, { "thistle2", 0xEED2EE }, { "thistle3", 0xCDB5CD }, { "thistle4", 0x8B7B8B }, { "tomato", 0xFF6347 }, { "tomato1", 0xFF6347 }, { "tomato2", 0xEE5C42 }, { "tomato3", 0xCD4F39 }, { "tomato4", 0x8B3626 }, { "transparent", 0x0000FF }, { "turquoise", 0x40E0D0 }, { "turquoise1", 0x00F5FF }, { "turquoise2", 0x00E5EE }, { "turquoise3", 0x00C5CD }, { "turquoise4", 0x00868B }, { "violet", 0xEE82EE }, { "violetred", 0xd02090 }, { "violetred1", 0xff3e96 }, { "violetred2", 0xee3a8c }, { "violetred3", 0xcd3278 }, { "violetred4", 0x8b2252 }, { "wheat", 0xF5DEB3 }, { "wheat1", 0xFFE7BA }, { "wheat2", 0xEED8AE }, { "wheat3", 0xCDBA96 }, { "wheat4", 0x8B7E66 }, { "white", 0xFFFFFF }, { "whitesmoke", 0xf5f5f5 }, { "yellow", 0xFFFF00 }, { "yellow1", 0xFFFF00 }, { "yellow2", 0xEEEE00 }, { "yellow3", 0xCDCD00 }, { "yellow4", 0x8B8B00 }, { "yellowgreen", 0x9acd32 }, #endif /* EXTENDED_XPM_COLORS */ {"none", 0xFFFFFF} }; if (spec[0] == '#') { char buf[7]; switch(speclen) { case 4: buf[0] = buf[1] = spec[1]; buf[2] = buf[3] = spec[2]; buf[4] = buf[5] = spec[3]; break; case 7: SDL_memcpy(buf, spec + 1, 6); break; case 13: buf[0] = spec[1]; buf[1] = spec[2]; buf[2] = spec[5]; buf[3] = spec[6]; buf[4] = spec[9]; buf[5] = spec[10]; break; } buf[6] = '\0'; *rgb = (Uint32)SDL_strtol(buf, NULL, 16); return 1; } else { int i; for (i = 0; i < SDL_arraysize(known); i++) { if (SDL_strncasecmp(known[i].name, spec, speclen) == 0) { *rgb = known[i].rgb; return 1; } } return 0; } } #ifndef MAX #define MAX(a, b) ((a) > (b) ? (a) : (b)) #endif static char *linebuf; static int buflen; static char *error; /* * Read next line from the source. * If len > 0, it's assumed to be at least len chars (for efficiency). * Return NULL and set error upon EOF or parse error. */ static char *get_next_line(char ***lines, SDL_RWops *src, int len) { char *linebufnew; if (lines) { return *(*lines)++; } else { char c; int n; do { if (SDL_RWread(src, &c, 1, 1) <= 0) { error = "Premature end of data"; return NULL; } } while (c != '"'); if (len) { len += 4; /* "\",\n\0" */ if (len > buflen){ buflen = len; linebufnew = (char *)SDL_realloc(linebuf, buflen); if (!linebufnew) { SDL_free(linebuf); error = "Out of memory"; return NULL; } linebuf = linebufnew; } if (SDL_RWread(src, linebuf, len - 1, 1) <= 0) { error = "Premature end of data"; return NULL; } n = len - 2; } else { n = 0; do { if (n >= buflen - 1) { if (buflen == 0) buflen = 16; buflen *= 2; linebufnew = (char *)SDL_realloc(linebuf, buflen); if (!linebufnew) { SDL_free(linebuf); error = "Out of memory"; return NULL; } linebuf = linebufnew; } if (SDL_RWread(src, linebuf + n, 1, 1) <= 0) { error = "Premature end of data"; return NULL; } } while (linebuf[n++] != '"'); n--; } linebuf[n] = '\0'; return linebuf; } } #define SKIPSPACE(p) \ do { \ while (SDL_isspace((unsigned char)*(p))) \ ++(p); \ } while (0) #define SKIPNONSPACE(p) \ do { \ while (!SDL_isspace((unsigned char)*(p)) && *p) \ ++(p); \ } while (0) /* read XPM from either array or RWops */ static SDL_Surface *load_xpm(char **xpm, SDL_RWops *src) { Sint64 start = 0; SDL_Surface *image = NULL; int index; int x, y; int w, h, ncolors, cpp; int indexed; Uint8 *dst; struct color_hash *colors = NULL; SDL_Color *im_colors = NULL; char *keystrings = NULL, *nextkey; char *line; char ***xpmlines = NULL; int pixels_len; error = NULL; linebuf = NULL; buflen = 0; if (src) start = SDL_RWtell(src); if (xpm) xpmlines = &xpm; line = get_next_line(xpmlines, src, 0); if (!line) goto done; /* * The header string of an XPMv3 image has the format * * <width> <height> <ncolors> <cpp> [ <hotspot_x> <hotspot_y> ] * * where the hotspot coords are intended for mouse cursors. * Right now we don't use the hotspots but it should be handled * one day. */ if (SDL_sscanf(line, "%d %d %d %d", &w, &h, &ncolors, &cpp) != 4 || w <= 0 || h <= 0 || ncolors <= 0 || cpp <= 0) { error = "Invalid format description"; goto done; } /* Check for allocation overflow */ if ((size_t)(ncolors * cpp)/cpp != ncolors) { error = "Invalid color specification"; goto done; } keystrings = (char *)SDL_malloc(ncolors * cpp); if (!keystrings) { error = "Out of memory"; goto done; } nextkey = keystrings; /* Create the new surface */ if (ncolors <= 256) { indexed = 1; image = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 8, 0, 0, 0, 0); im_colors = image->format->palette->colors; image->format->palette->ncolors = ncolors; } else { indexed = 0; image = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 32, 0xff0000, 0x00ff00, 0x0000ff, 0); } if (!image) { /* Hmm, some SDL error (out of memory?) */ goto done; } /* Read the colors */ colors = create_colorhash(ncolors); if (!colors) { error = "Out of memory"; goto done; } for (index = 0; index < ncolors; ++index ) { char *p; line = get_next_line(xpmlines, src, 0); if (!line) goto done; p = line + cpp + 1; /* parse a colour definition */ for (;;) { char nametype; char *colname; Uint32 rgb, pixel; SKIPSPACE(p); if (!*p) { error = "colour parse error"; goto done; } nametype = *p; SKIPNONSPACE(p); SKIPSPACE(p); colname = p; SKIPNONSPACE(p); if (nametype == 's') continue; /* skip symbolic colour names */ if (!color_to_rgb(colname, (int)(p - colname), &rgb)) continue; SDL_memcpy(nextkey, line, cpp); if (indexed) { SDL_Color *c = im_colors + index; c->r = (Uint8)(rgb >> 16); c->g = (Uint8)(rgb >> 8); c->b = (Uint8)(rgb); pixel = index; } else { pixel = rgb; } add_colorhash(colors, nextkey, cpp, pixel); nextkey += cpp; if (rgb == 0xffffffff) SDL_SetColorKey(image, SDL_TRUE, pixel); break; } } /* Read the pixels */ pixels_len = w * cpp; dst = (Uint8 *)image->pixels; for (y = 0; y < h; y++) { line = get_next_line(xpmlines, src, pixels_len); if (!line) goto done; if (indexed) { /* optimization for some common cases */ if (cpp == 1) for (x = 0; x < w; x++) dst[x] = (Uint8)QUICK_COLORHASH(colors, line + x); else for (x = 0; x < w; x++) dst[x] = (Uint8)get_colorhash(colors, line + x * cpp, cpp); } else { for (x = 0; x < w; x++) ((Uint32*)dst)[x] = get_colorhash(colors, line + x * cpp, cpp); } dst += image->pitch; } done: if (error) { if ( src ) SDL_RWseek(src, start, RW_SEEK_SET); if ( image ) { SDL_FreeSurface(image); image = NULL; } IMG_SetError("%s", error); } if (keystrings) SDL_free(keystrings); free_colorhash(colors); if (linebuf) SDL_free(linebuf); return(image); } /* Load a XPM type image from an RWops datasource */ SDL_Surface *IMG_LoadXPM_RW(SDL_RWops *src) { if ( !src ) { /* The error message has been set in SDL_RWFromFile */ return NULL; } return load_xpm(NULL, src); } SDL_Surface *IMG_ReadXPMFromArray(char **xpm) { if (!xpm) { IMG_SetError("array is NULL"); return NULL; } return load_xpm(xpm, NULL); } #else /* not LOAD_XPM */ /* See if an image is contained in a data source */ int IMG_isXPM(SDL_RWops *src) { return(0); } /* Load a XPM type image from an SDL datasource */ SDL_Surface *IMG_LoadXPM_RW(SDL_RWops *src) { return(NULL); } SDL_Surface *IMG_ReadXPMFromArray(char **xpm) { return NULL; } #endif /* not LOAD_XPM */
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG_xpm.c
C
apache-2.0
45,762
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* This is a XV thumbnail image file loading framework */ #include "SDL_image.h" #ifdef LOAD_XV static int get_line(SDL_RWops *src, char *line, int size) { while ( size > 0 ) { if ( SDL_RWread(src, line, 1, 1) <= 0 ) { return -1; } if ( *line == '\r' ) { continue; } if ( *line == '\n' ) { *line = '\0'; return 0; } ++line; --size; } /* Out of space for the line */ return -1; } static int get_header(SDL_RWops *src, int *w, int *h) { char line[1024]; *w = 0; *h = 0; /* Check the header magic */ if ( (get_line(src, line, sizeof(line)) < 0) || (SDL_memcmp(line, "P7 332", 6) != 0) ) { return -1; } /* Read the header */ while ( get_line(src, line, sizeof(line)) == 0 ) { if ( SDL_memcmp(line, "#BUILTIN:", 9) == 0 ) { /* Builtin image, no data */ break; } if ( SDL_memcmp(line, "#END_OF_COMMENTS", 16) == 0 ) { if ( get_line(src, line, sizeof(line)) == 0 ) { SDL_sscanf(line, "%d %d", w, h); if ( *w >= 0 && *h >= 0 ) { return 0; } } break; } } /* No image data */ return -1; } /* See if an image is contained in a data source */ int IMG_isXV(SDL_RWops *src) { Sint64 start; int is_XV; int w, h; if ( !src ) return 0; start = SDL_RWtell(src); is_XV = 0; if ( get_header(src, &w, &h) == 0 ) { is_XV = 1; } SDL_RWseek(src, start, RW_SEEK_SET); return(is_XV); } /* Load a XV thumbnail image from an SDL datasource */ SDL_Surface *IMG_LoadXV_RW(SDL_RWops *src) { Sint64 start; const char *error = NULL; SDL_Surface *surface = NULL; int w, h; Uint8 *pixels; if ( !src ) { /* The error message has been set in SDL_RWFromFile */ return NULL; } start = SDL_RWtell(src); /* Read the header */ if ( get_header(src, &w, &h) < 0 ) { error = "Unsupported image format"; goto done; } /* Create the 3-3-2 indexed palette surface */ surface = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 8, 0xe0, 0x1c, 0x03, 0); if ( surface == NULL ) { error = "Out of memory"; goto done; } /* Load the image data */ for ( pixels = (Uint8 *)surface->pixels; h > 0; --h ) { if ( SDL_RWread(src, pixels, w, 1) <= 0 ) { error = "Couldn't read image data"; goto done; } pixels += surface->pitch; } done: if ( error ) { SDL_RWseek(src, start, RW_SEEK_SET); if ( surface ) { SDL_FreeSurface(surface); surface = NULL; } IMG_SetError("%s", error); } return surface; } #else /* See if an image is contained in a data source */ int IMG_isXV(SDL_RWops *src) { return(0); } /* Load a XXX type image from an SDL datasource */ SDL_Surface *IMG_LoadXV_RW(SDL_RWops *src) { return(NULL); } #endif /* LOAD_XV */
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG_xv.c
C
apache-2.0
4,107
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* This is a generic "format not supported" image framework */ #include "SDL_image.h" #ifdef LOAD_XXX /* See if an image is contained in a data source */ int IMG_isXXX(SDL_RWops *src) { int start; int is_XXX; if ( !src ) return 0; start = SDL_RWtell(src); is_XXX = 0; /* Detect the image here */ SDL_RWseek(src, start, RW_SEEK_SET); return(is_XXX); } /* Load a XXX type image from an SDL datasource */ SDL_Surface *IMG_LoadXXX_RW(SDL_RWops *src) { int start; const char *error = NULL; SDL_Surface *surface = NULL; if ( !src ) { /* The error message has been set in SDL_RWFromFile */ return NULL; } start = SDL_RWtell(src); /* Load the image here */ if ( error ) { SDL_RWseek(src, start, RW_SEEK_SET); if ( surface ) { SDL_FreeSurface(surface); surface = NULL; } IMG_SetError("%s", error); } return surface; } #else /* See if an image is contained in a data source */ int IMG_isXXX(SDL_RWops *src) { return(0); } /* Load a XXX type image from an SDL datasource */ SDL_Surface *IMG_LoadXXX_RW(SDL_RWops *src) { return(NULL); } #endif /* LOAD_XXX */
YifuLiu/AliOS-Things
components/SDL2/src/image/IMG_xxx.c
C
apache-2.0
2,198
# Makefile.am for the SDL sample image loading library and viewer lib_LTLIBRARIES = libSDL2_image.la libSDL2_imageincludedir = $(includedir)/SDL2 libSDL2_imageinclude_HEADERS = \ SDL_image.h if USE_IMAGEIO IMAGEIO_SOURCE = IMG_ImageIO.m endif libSDL2_image_la_SOURCES = \ IMG.c \ IMG_bmp.c \ IMG_gif.c \ IMG_jpg.c \ IMG_lbm.c \ IMG_pcx.c \ IMG_png.c \ IMG_pnm.c \ IMG_svg.c \ IMG_tga.c \ IMG_tif.c \ IMG_xcf.c \ IMG_xpm.c \ IMG_xv.c \ IMG_webp.c \ IMG_WIC.c \ $(IMAGEIO_SOURCE) \ miniz.h \ nanosvg.h \ nanosvgrast.h EXTRA_DIST = \ Android.mk \ debian \ external \ version.rc \ VisualC \ VisualCE \ VisualC-WinRT \ Xcode \ Xcode-iOS \ IMG_xxx.c \ $(srcdir)/*.m \ SDL2_image.spec \ gcc-fat.sh \ autogen.sh \ $(srcdir)/*.txt if USE_VERSION_RC libSDL2_image_la_LDFLAGS = \ -no-undefined \ -release $(LT_RELEASE) \ -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE) -Wl,version.o libSDL2_image_la_LIBADD = $(IMG_LIBS) libSDL2_image_la_DEPENDENCIES = version.o else libSDL2_image_la_LDFLAGS = \ -no-undefined \ -release $(LT_RELEASE) \ -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE) libSDL2_image_la_LIBADD = $(IMG_LIBS) endif pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = SDL2_image.pc %.o : %.rc $(WINDRES) $< $@ noinst_PROGRAMS = showimage showimage_LDADD = libSDL2_image.la # Rule to build tar-gzipped distribution package $(PACKAGE)-$(VERSION).tar.gz: distcheck # Rule to build RPM distribution package rpm: $(PACKAGE)-$(VERSION).tar.gz rpmbuild -ta $(PACKAGE)-$(VERSION).tar.gz
YifuLiu/AliOS-Things
components/SDL2/src/image/Makefile.am
Makefile
apache-2.0
1,591
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* A simple library to load images of various formats as SDL surfaces */ #ifndef SDL_IMAGE_H_ #define SDL_IMAGE_H_ #include "SDL.h" #include "SDL_version.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* Printable format: "%d.%d.%d", MAJOR, MINOR, PATCHLEVEL */ #define SDL_IMAGE_MAJOR_VERSION 2 #define SDL_IMAGE_MINOR_VERSION 0 #define SDL_IMAGE_PATCHLEVEL 5 /* This macro can be used to fill a version structure with the compile-time * version of the SDL_image library. */ #define SDL_IMAGE_VERSION(X) \ { \ (X)->major = SDL_IMAGE_MAJOR_VERSION; \ (X)->minor = SDL_IMAGE_MINOR_VERSION; \ (X)->patch = SDL_IMAGE_PATCHLEVEL; \ } /** * This is the version number macro for the current SDL_image version. */ #define SDL_IMAGE_COMPILEDVERSION \ SDL_VERSIONNUM(SDL_IMAGE_MAJOR_VERSION, SDL_IMAGE_MINOR_VERSION, SDL_IMAGE_PATCHLEVEL) /** * This macro will evaluate to true if compiled with SDL_image at least X.Y.Z. */ #define SDL_IMAGE_VERSION_ATLEAST(X, Y, Z) \ (SDL_IMAGE_COMPILEDVERSION >= SDL_VERSIONNUM(X, Y, Z)) /* This function gets the version of the dynamically linked SDL_image library. it should NOT be used to fill a version structure, instead you should use the SDL_IMAGE_VERSION() macro. */ extern DECLSPEC const SDL_version * SDLCALL IMG_Linked_Version(void); typedef enum { IMG_INIT_JPG = 0x00000001, IMG_INIT_PNG = 0x00000002, IMG_INIT_TIF = 0x00000004, IMG_INIT_WEBP = 0x00000008 } IMG_InitFlags; /* Loads dynamic libraries and prepares them for use. Flags should be one or more flags from IMG_InitFlags OR'd together. It returns the flags successfully initialized, or 0 on failure. */ extern DECLSPEC int SDLCALL IMG_Init(int flags); /* Unloads libraries loaded with IMG_Init */ extern DECLSPEC void SDLCALL IMG_Quit(void); /* Load an image from an SDL data source. The 'type' may be one of: "BMP", "GIF", "PNG", etc. If the image format supports a transparent pixel, SDL will set the colorkey for the surface. You can enable RLE acceleration on the surface afterwards by calling: SDL_SetColorKey(image, SDL_RLEACCEL, image->format->colorkey); */ extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadTyped_RW(SDL_RWops *src, int freesrc, const char *type); /* Convenience functions */ extern DECLSPEC SDL_Surface * SDLCALL IMG_Load(const char *file); extern DECLSPEC SDL_Surface * SDLCALL IMG_Load_RW(SDL_RWops *src, int freesrc); #if SDL_VERSION_ATLEAST(2,0,0) /* Load an image directly into a render texture. */ extern DECLSPEC SDL_Texture * SDLCALL IMG_LoadTexture(SDL_Renderer *renderer, const char *file); extern DECLSPEC SDL_Texture * SDLCALL IMG_LoadTexture_RW(SDL_Renderer *renderer, SDL_RWops *src, int freesrc); extern DECLSPEC SDL_Texture * SDLCALL IMG_LoadTextureTyped_RW(SDL_Renderer *renderer, SDL_RWops *src, int freesrc, const char *type); #endif /* SDL 2.0 */ /* Functions to detect a file type, given a seekable source */ extern DECLSPEC int SDLCALL IMG_isICO(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isCUR(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isBMP(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isGIF(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isJPG(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isLBM(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isPCX(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isPNG(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isPNM(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isSVG(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isTIF(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isXCF(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isXPM(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isXV(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isWEBP(SDL_RWops *src); /* Individual loading functions */ extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadICO_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadCUR_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadBMP_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadGIF_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadJPG_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadLBM_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadPCX_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadPNG_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadPNM_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadSVG_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadTGA_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadTIF_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadXCF_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadXPM_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadXV_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadWEBP_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_ReadXPMFromArray(char **xpm); /* Individual saving functions */ extern DECLSPEC int SDLCALL IMG_SavePNG(SDL_Surface *surface, const char *file); extern DECLSPEC int SDLCALL IMG_SavePNG_RW(SDL_Surface *surface, SDL_RWops *dst, int freedst); extern DECLSPEC int SDLCALL IMG_SaveJPG(SDL_Surface *surface, const char *file, int quality); extern DECLSPEC int SDLCALL IMG_SaveJPG_RW(SDL_Surface *surface, SDL_RWops *dst, int freedst, int quality); /* We'll use SDL for reporting errors */ #define IMG_SetError SDL_SetError #define IMG_GetError SDL_GetError /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_IMAGE_H_ */
YifuLiu/AliOS-Things
components/SDL2/src/image/SDL_image.h
C
apache-2.0
6,820
#!/bin/sh find . -type f \( -name '*.user' -o -name '*.sdf' -o -name '*.ncb' -o -name '*.suo' \) -print -delete rm -rvf Win32 */Win32 x64 */x64
YifuLiu/AliOS-Things
components/SDL2/src/image/VisualC/clean.sh
Shell
apache-2.0
144
//{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by Version.rc // // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
YifuLiu/AliOS-Things
components/SDL2/src/image/VisualC/resource.h
C
apache-2.0
395
find . -type d -name 'Debug' -exec rm -rv {} \; find . -type d -name 'Release' -exec rm -rv {} \; find . -type f -name '*.user' -exec rm -v {} \; find . -type f -name '*.ncb' -exec rm -v {} \; find . -type f -name '*.suo' -exec rm -v {} \;
YifuLiu/AliOS-Things
components/SDL2/src/image/VisualCE/clean.sh
Shell
apache-2.0
240
//{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by Version.rc // // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
YifuLiu/AliOS-Things
components/SDL2/src/image/VisualCE/resource.h
C
apache-2.0
395
// Copyright 2010 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // Main decoding functions for WebP images. // // Author: Skal (pascal.massimino@gmail.com) #ifndef WEBP_WEBP_DECODE_H_ #define WEBP_WEBP_DECODE_H_ #include "./types.h" #ifdef __cplusplus extern "C" { #endif #define WEBP_DECODER_ABI_VERSION 0x0208 // MAJOR(8b) + MINOR(8b) // Note: forward declaring enumerations is not allowed in (strict) C and C++, // the types are left here for reference. // typedef enum VP8StatusCode VP8StatusCode; // typedef enum WEBP_CSP_MODE WEBP_CSP_MODE; typedef struct WebPRGBABuffer WebPRGBABuffer; typedef struct WebPYUVABuffer WebPYUVABuffer; typedef struct WebPDecBuffer WebPDecBuffer; typedef struct WebPIDecoder WebPIDecoder; typedef struct WebPBitstreamFeatures WebPBitstreamFeatures; typedef struct WebPDecoderOptions WebPDecoderOptions; typedef struct WebPDecoderConfig WebPDecoderConfig; // Return the decoder's version number, packed in hexadecimal using 8bits for // each of major/minor/revision. E.g: v2.5.7 is 0x020507. WEBP_EXTERN int WebPGetDecoderVersion(void); // Retrieve basic header information: width, height. // This function will also validate the header, returning true on success, // false otherwise. '*width' and '*height' are only valid on successful return. // Pointers 'width' and 'height' can be passed NULL if deemed irrelevant. // Note: The following chunk sequences (before the raw VP8/VP8L data) are // considered valid by this function: // RIFF + VP8(L) // RIFF + VP8X + (optional chunks) + VP8(L) // ALPH + VP8 <-- Not a valid WebP format: only allowed for internal purpose. // VP8(L) <-- Not a valid WebP format: only allowed for internal purpose. WEBP_EXTERN int WebPGetInfo(const uint8_t* data, size_t data_size, int* width, int* height); // Decodes WebP images pointed to by 'data' and returns RGBA samples, along // with the dimensions in *width and *height. The ordering of samples in // memory is R, G, B, A, R, G, B, A... in scan order (endian-independent). // The returned pointer should be deleted calling WebPFree(). // Returns NULL in case of error. WEBP_EXTERN uint8_t* WebPDecodeRGBA(const uint8_t* data, size_t data_size, int* width, int* height); // Same as WebPDecodeRGBA, but returning A, R, G, B, A, R, G, B... ordered data. WEBP_EXTERN uint8_t* WebPDecodeARGB(const uint8_t* data, size_t data_size, int* width, int* height); // Same as WebPDecodeRGBA, but returning B, G, R, A, B, G, R, A... ordered data. WEBP_EXTERN uint8_t* WebPDecodeBGRA(const uint8_t* data, size_t data_size, int* width, int* height); // Same as WebPDecodeRGBA, but returning R, G, B, R, G, B... ordered data. // If the bitstream contains transparency, it is ignored. WEBP_EXTERN uint8_t* WebPDecodeRGB(const uint8_t* data, size_t data_size, int* width, int* height); // Same as WebPDecodeRGB, but returning B, G, R, B, G, R... ordered data. WEBP_EXTERN uint8_t* WebPDecodeBGR(const uint8_t* data, size_t data_size, int* width, int* height); // Decode WebP images pointed to by 'data' to Y'UV format(*). The pointer // returned is the Y samples buffer. Upon return, *u and *v will point to // the U and V chroma data. These U and V buffers need NOT be passed to // WebPFree(), unlike the returned Y luma one. The dimension of the U and V // planes are both (*width + 1) / 2 and (*height + 1)/ 2. // Upon return, the Y buffer has a stride returned as '*stride', while U and V // have a common stride returned as '*uv_stride'. // Return NULL in case of error. // (*) Also named Y'CbCr. See: http://en.wikipedia.org/wiki/YCbCr WEBP_EXTERN uint8_t* WebPDecodeYUV(const uint8_t* data, size_t data_size, int* width, int* height, uint8_t** u, uint8_t** v, int* stride, int* uv_stride); // Releases memory returned by the WebPDecode*() functions above. WEBP_EXTERN void WebPFree(void* ptr); // These five functions are variants of the above ones, that decode the image // directly into a pre-allocated buffer 'output_buffer'. The maximum storage // available in this buffer is indicated by 'output_buffer_size'. If this // storage is not sufficient (or an error occurred), NULL is returned. // Otherwise, output_buffer is returned, for convenience. // The parameter 'output_stride' specifies the distance (in bytes) // between scanlines. Hence, output_buffer_size is expected to be at least // output_stride x picture-height. WEBP_EXTERN uint8_t* WebPDecodeRGBAInto( const uint8_t* data, size_t data_size, uint8_t* output_buffer, size_t output_buffer_size, int output_stride); WEBP_EXTERN uint8_t* WebPDecodeARGBInto( const uint8_t* data, size_t data_size, uint8_t* output_buffer, size_t output_buffer_size, int output_stride); WEBP_EXTERN uint8_t* WebPDecodeBGRAInto( const uint8_t* data, size_t data_size, uint8_t* output_buffer, size_t output_buffer_size, int output_stride); // RGB and BGR variants. Here too the transparency information, if present, // will be dropped and ignored. WEBP_EXTERN uint8_t* WebPDecodeRGBInto( const uint8_t* data, size_t data_size, uint8_t* output_buffer, size_t output_buffer_size, int output_stride); WEBP_EXTERN uint8_t* WebPDecodeBGRInto( const uint8_t* data, size_t data_size, uint8_t* output_buffer, size_t output_buffer_size, int output_stride); // WebPDecodeYUVInto() is a variant of WebPDecodeYUV() that operates directly // into pre-allocated luma/chroma plane buffers. This function requires the // strides to be passed: one for the luma plane and one for each of the // chroma ones. The size of each plane buffer is passed as 'luma_size', // 'u_size' and 'v_size' respectively. // Pointer to the luma plane ('*luma') is returned or NULL if an error occurred // during decoding (or because some buffers were found to be too small). WEBP_EXTERN uint8_t* WebPDecodeYUVInto( const uint8_t* data, size_t data_size, uint8_t* luma, size_t luma_size, int luma_stride, uint8_t* u, size_t u_size, int u_stride, uint8_t* v, size_t v_size, int v_stride); //------------------------------------------------------------------------------ // Output colorspaces and buffer // Colorspaces // Note: the naming describes the byte-ordering of packed samples in memory. // For instance, MODE_BGRA relates to samples ordered as B,G,R,A,B,G,R,A,... // Non-capital names (e.g.:MODE_Argb) relates to pre-multiplied RGB channels. // RGBA-4444 and RGB-565 colorspaces are represented by following byte-order: // RGBA-4444: [r3 r2 r1 r0 g3 g2 g1 g0], [b3 b2 b1 b0 a3 a2 a1 a0], ... // RGB-565: [r4 r3 r2 r1 r0 g5 g4 g3], [g2 g1 g0 b4 b3 b2 b1 b0], ... // In the case WEBP_SWAP_16BITS_CSP is defined, the bytes are swapped for // these two modes: // RGBA-4444: [b3 b2 b1 b0 a3 a2 a1 a0], [r3 r2 r1 r0 g3 g2 g1 g0], ... // RGB-565: [g2 g1 g0 b4 b3 b2 b1 b0], [r4 r3 r2 r1 r0 g5 g4 g3], ... typedef enum WEBP_CSP_MODE { MODE_RGB = 0, MODE_RGBA = 1, MODE_BGR = 2, MODE_BGRA = 3, MODE_ARGB = 4, MODE_RGBA_4444 = 5, MODE_RGB_565 = 6, // RGB-premultiplied transparent modes (alpha value is preserved) MODE_rgbA = 7, MODE_bgrA = 8, MODE_Argb = 9, MODE_rgbA_4444 = 10, // YUV modes must come after RGB ones. MODE_YUV = 11, MODE_YUVA = 12, // yuv 4:2:0 MODE_LAST = 13 } WEBP_CSP_MODE; // Some useful macros: static WEBP_INLINE int WebPIsPremultipliedMode(WEBP_CSP_MODE mode) { return (mode == MODE_rgbA || mode == MODE_bgrA || mode == MODE_Argb || mode == MODE_rgbA_4444); } static WEBP_INLINE int WebPIsAlphaMode(WEBP_CSP_MODE mode) { return (mode == MODE_RGBA || mode == MODE_BGRA || mode == MODE_ARGB || mode == MODE_RGBA_4444 || mode == MODE_YUVA || WebPIsPremultipliedMode(mode)); } static WEBP_INLINE int WebPIsRGBMode(WEBP_CSP_MODE mode) { return (mode < MODE_YUV); } //------------------------------------------------------------------------------ // WebPDecBuffer: Generic structure for describing the output sample buffer. struct WebPRGBABuffer { // view as RGBA uint8_t* rgba; // pointer to RGBA samples int stride; // stride in bytes from one scanline to the next. size_t size; // total size of the *rgba buffer. }; struct WebPYUVABuffer { // view as YUVA uint8_t* y, *u, *v, *a; // pointer to luma, chroma U/V, alpha samples int y_stride; // luma stride int u_stride, v_stride; // chroma strides int a_stride; // alpha stride size_t y_size; // luma plane size size_t u_size, v_size; // chroma planes size size_t a_size; // alpha-plane size }; // Output buffer struct WebPDecBuffer { WEBP_CSP_MODE colorspace; // Colorspace. int width, height; // Dimensions. int is_external_memory; // If non-zero, 'internal_memory' pointer is not // used. If value is '2' or more, the external // memory is considered 'slow' and multiple // read/write will be avoided. union { WebPRGBABuffer RGBA; WebPYUVABuffer YUVA; } u; // Nameless union of buffer parameters. uint32_t pad[4]; // padding for later use uint8_t* private_memory; // Internally allocated memory (only when // is_external_memory is 0). Should not be used // externally, but accessed via the buffer union. }; // Internal, version-checked, entry point WEBP_EXTERN int WebPInitDecBufferInternal(WebPDecBuffer*, int); // Initialize the structure as empty. Must be called before any other use. // Returns false in case of version mismatch static WEBP_INLINE int WebPInitDecBuffer(WebPDecBuffer* buffer) { return WebPInitDecBufferInternal(buffer, WEBP_DECODER_ABI_VERSION); } // Free any memory associated with the buffer. Must always be called last. // Note: doesn't free the 'buffer' structure itself. WEBP_EXTERN void WebPFreeDecBuffer(WebPDecBuffer* buffer); //------------------------------------------------------------------------------ // Enumeration of the status codes typedef enum VP8StatusCode { VP8_STATUS_OK = 0, VP8_STATUS_OUT_OF_MEMORY, VP8_STATUS_INVALID_PARAM, VP8_STATUS_BITSTREAM_ERROR, VP8_STATUS_UNSUPPORTED_FEATURE, VP8_STATUS_SUSPENDED, VP8_STATUS_USER_ABORT, VP8_STATUS_NOT_ENOUGH_DATA } VP8StatusCode; //------------------------------------------------------------------------------ // Incremental decoding // // This API allows streamlined decoding of partial data. // Picture can be incrementally decoded as data become available thanks to the // WebPIDecoder object. This object can be left in a SUSPENDED state if the // picture is only partially decoded, pending additional input. // Code example: // // WebPInitDecBuffer(&output_buffer); // output_buffer.colorspace = mode; // ... // WebPIDecoder* idec = WebPINewDecoder(&output_buffer); // while (additional_data_is_available) { // // ... (get additional data in some new_data[] buffer) // status = WebPIAppend(idec, new_data, new_data_size); // if (status != VP8_STATUS_OK && status != VP8_STATUS_SUSPENDED) { // break; // an error occurred. // } // // // The above call decodes the current available buffer. // // Part of the image can now be refreshed by calling // // WebPIDecGetRGB()/WebPIDecGetYUVA() etc. // } // WebPIDelete(idec); // Creates a new incremental decoder with the supplied buffer parameter. // This output_buffer can be passed NULL, in which case a default output buffer // is used (with MODE_RGB). Otherwise, an internal reference to 'output_buffer' // is kept, which means that the lifespan of 'output_buffer' must be larger than // that of the returned WebPIDecoder object. // The supplied 'output_buffer' content MUST NOT be changed between calls to // WebPIAppend() or WebPIUpdate() unless 'output_buffer.is_external_memory' is // not set to 0. In such a case, it is allowed to modify the pointers, size and // stride of output_buffer.u.RGBA or output_buffer.u.YUVA, provided they remain // within valid bounds. // All other fields of WebPDecBuffer MUST remain constant between calls. // Returns NULL if the allocation failed. WEBP_EXTERN WebPIDecoder* WebPINewDecoder(WebPDecBuffer* output_buffer); // This function allocates and initializes an incremental-decoder object, which // will output the RGB/A samples specified by 'csp' into a preallocated // buffer 'output_buffer'. The size of this buffer is at least // 'output_buffer_size' and the stride (distance in bytes between two scanlines) // is specified by 'output_stride'. // Additionally, output_buffer can be passed NULL in which case the output // buffer will be allocated automatically when the decoding starts. The // colorspace 'csp' is taken into account for allocating this buffer. All other // parameters are ignored. // Returns NULL if the allocation failed, or if some parameters are invalid. WEBP_EXTERN WebPIDecoder* WebPINewRGB( WEBP_CSP_MODE csp, uint8_t* output_buffer, size_t output_buffer_size, int output_stride); // This function allocates and initializes an incremental-decoder object, which // will output the raw luma/chroma samples into a preallocated planes if // supplied. The luma plane is specified by its pointer 'luma', its size // 'luma_size' and its stride 'luma_stride'. Similarly, the chroma-u plane // is specified by the 'u', 'u_size' and 'u_stride' parameters, and the chroma-v // plane by 'v' and 'v_size'. And same for the alpha-plane. The 'a' pointer // can be pass NULL in case one is not interested in the transparency plane. // Conversely, 'luma' can be passed NULL if no preallocated planes are supplied. // In this case, the output buffer will be automatically allocated (using // MODE_YUVA) when decoding starts. All parameters are then ignored. // Returns NULL if the allocation failed or if a parameter is invalid. WEBP_EXTERN WebPIDecoder* WebPINewYUVA( uint8_t* luma, size_t luma_size, int luma_stride, uint8_t* u, size_t u_size, int u_stride, uint8_t* v, size_t v_size, int v_stride, uint8_t* a, size_t a_size, int a_stride); // Deprecated version of the above, without the alpha plane. // Kept for backward compatibility. WEBP_EXTERN WebPIDecoder* WebPINewYUV( uint8_t* luma, size_t luma_size, int luma_stride, uint8_t* u, size_t u_size, int u_stride, uint8_t* v, size_t v_size, int v_stride); // Deletes the WebPIDecoder object and associated memory. Must always be called // if WebPINewDecoder, WebPINewRGB or WebPINewYUV succeeded. WEBP_EXTERN void WebPIDelete(WebPIDecoder* idec); // Copies and decodes the next available data. Returns VP8_STATUS_OK when // the image is successfully decoded. Returns VP8_STATUS_SUSPENDED when more // data is expected. Returns error in other cases. WEBP_EXTERN VP8StatusCode WebPIAppend( WebPIDecoder* idec, const uint8_t* data, size_t data_size); // A variant of the above function to be used when data buffer contains // partial data from the beginning. In this case data buffer is not copied // to the internal memory. // Note that the value of the 'data' pointer can change between calls to // WebPIUpdate, for instance when the data buffer is resized to fit larger data. WEBP_EXTERN VP8StatusCode WebPIUpdate( WebPIDecoder* idec, const uint8_t* data, size_t data_size); // Returns the RGB/A image decoded so far. Returns NULL if output params // are not initialized yet. The RGB/A output type corresponds to the colorspace // specified during call to WebPINewDecoder() or WebPINewRGB(). // *last_y is the index of last decoded row in raster scan order. Some pointers // (*last_y, *width etc.) can be NULL if corresponding information is not // needed. The values in these pointers are only valid on successful (non-NULL) // return. WEBP_EXTERN uint8_t* WebPIDecGetRGB( const WebPIDecoder* idec, int* last_y, int* width, int* height, int* stride); // Same as above function to get a YUVA image. Returns pointer to the luma // plane or NULL in case of error. If there is no alpha information // the alpha pointer '*a' will be returned NULL. WEBP_EXTERN uint8_t* WebPIDecGetYUVA( const WebPIDecoder* idec, int* last_y, uint8_t** u, uint8_t** v, uint8_t** a, int* width, int* height, int* stride, int* uv_stride, int* a_stride); // Deprecated alpha-less version of WebPIDecGetYUVA(): it will ignore the // alpha information (if present). Kept for backward compatibility. static WEBP_INLINE uint8_t* WebPIDecGetYUV( const WebPIDecoder* idec, int* last_y, uint8_t** u, uint8_t** v, int* width, int* height, int* stride, int* uv_stride) { return WebPIDecGetYUVA(idec, last_y, u, v, NULL, width, height, stride, uv_stride, NULL); } // Generic call to retrieve information about the displayable area. // If non NULL, the left/right/width/height pointers are filled with the visible // rectangular area so far. // Returns NULL in case the incremental decoder object is in an invalid state. // Otherwise returns the pointer to the internal representation. This structure // is read-only, tied to WebPIDecoder's lifespan and should not be modified. WEBP_EXTERN const WebPDecBuffer* WebPIDecodedArea( const WebPIDecoder* idec, int* left, int* top, int* width, int* height); //------------------------------------------------------------------------------ // Advanced decoding parametrization // // Code sample for using the advanced decoding API /* // A) Init a configuration object WebPDecoderConfig config; CHECK(WebPInitDecoderConfig(&config)); // B) optional: retrieve the bitstream's features. CHECK(WebPGetFeatures(data, data_size, &config.input) == VP8_STATUS_OK); // C) Adjust 'config', if needed config.no_fancy_upsampling = 1; config.output.colorspace = MODE_BGRA; // etc. // Note that you can also make config.output point to an externally // supplied memory buffer, provided it's big enough to store the decoded // picture. Otherwise, config.output will just be used to allocate memory // and store the decoded picture. // D) Decode! CHECK(WebPDecode(data, data_size, &config) == VP8_STATUS_OK); // E) Decoded image is now in config.output (and config.output.u.RGBA) // F) Reclaim memory allocated in config's object. It's safe to call // this function even if the memory is external and wasn't allocated // by WebPDecode(). WebPFreeDecBuffer(&config.output); */ // Features gathered from the bitstream struct WebPBitstreamFeatures { int width; // Width in pixels, as read from the bitstream. int height; // Height in pixels, as read from the bitstream. int has_alpha; // True if the bitstream contains an alpha channel. int has_animation; // True if the bitstream is an animation. int format; // 0 = undefined (/mixed), 1 = lossy, 2 = lossless uint32_t pad[5]; // padding for later use }; // Internal, version-checked, entry point WEBP_EXTERN VP8StatusCode WebPGetFeaturesInternal( const uint8_t*, size_t, WebPBitstreamFeatures*, int); // Retrieve features from the bitstream. The *features structure is filled // with information gathered from the bitstream. // Returns VP8_STATUS_OK when the features are successfully retrieved. Returns // VP8_STATUS_NOT_ENOUGH_DATA when more data is needed to retrieve the // features from headers. Returns error in other cases. // Note: The following chunk sequences (before the raw VP8/VP8L data) are // considered valid by this function: // RIFF + VP8(L) // RIFF + VP8X + (optional chunks) + VP8(L) // ALPH + VP8 <-- Not a valid WebP format: only allowed for internal purpose. // VP8(L) <-- Not a valid WebP format: only allowed for internal purpose. static WEBP_INLINE VP8StatusCode WebPGetFeatures( const uint8_t* data, size_t data_size, WebPBitstreamFeatures* features) { return WebPGetFeaturesInternal(data, data_size, features, WEBP_DECODER_ABI_VERSION); } // Decoding options struct WebPDecoderOptions { int bypass_filtering; // if true, skip the in-loop filtering int no_fancy_upsampling; // if true, use faster pointwise upsampler int use_cropping; // if true, cropping is applied _first_ int crop_left, crop_top; // top-left position for cropping. // Will be snapped to even values. int crop_width, crop_height; // dimension of the cropping area int use_scaling; // if true, scaling is applied _afterward_ int scaled_width, scaled_height; // final resolution int use_threads; // if true, use multi-threaded decoding int dithering_strength; // dithering strength (0=Off, 100=full) int flip; // flip output vertically int alpha_dithering_strength; // alpha dithering strength in [0..100] uint32_t pad[5]; // padding for later use }; // Main object storing the configuration for advanced decoding. struct WebPDecoderConfig { WebPBitstreamFeatures input; // Immutable bitstream features (optional) WebPDecBuffer output; // Output buffer (can point to external mem) WebPDecoderOptions options; // Decoding options }; // Internal, version-checked, entry point WEBP_EXTERN int WebPInitDecoderConfigInternal(WebPDecoderConfig*, int); // Initialize the configuration as empty. This function must always be // called first, unless WebPGetFeatures() is to be called. // Returns false in case of mismatched version. static WEBP_INLINE int WebPInitDecoderConfig(WebPDecoderConfig* config) { return WebPInitDecoderConfigInternal(config, WEBP_DECODER_ABI_VERSION); } // Instantiate a new incremental decoder object with the requested // configuration. The bitstream can be passed using 'data' and 'data_size' // parameter, in which case the features will be parsed and stored into // config->input. Otherwise, 'data' can be NULL and no parsing will occur. // Note that 'config' can be NULL too, in which case a default configuration // is used. If 'config' is not NULL, it must outlive the WebPIDecoder object // as some references to its fields will be used. No internal copy of 'config' // is made. // The return WebPIDecoder object must always be deleted calling WebPIDelete(). // Returns NULL in case of error (and config->status will then reflect // the error condition, if available). WEBP_EXTERN WebPIDecoder* WebPIDecode(const uint8_t* data, size_t data_size, WebPDecoderConfig* config); // Non-incremental version. This version decodes the full data at once, taking // 'config' into account. Returns decoding status (which should be VP8_STATUS_OK // if the decoding was successful). Note that 'config' cannot be NULL. WEBP_EXTERN VP8StatusCode WebPDecode(const uint8_t* data, size_t data_size, WebPDecoderConfig* config); #ifdef __cplusplus } // extern "C" #endif #endif // WEBP_WEBP_DECODE_H_
YifuLiu/AliOS-Things
components/SDL2/src/image/Xcode/Frameworks/webp.framework/Versions/A/Headers/webp/decode.h
C
apache-2.0
23,805
// Copyright 2012 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // Demux API. // Enables extraction of image and extended format data from WebP files. // Code Example: Demuxing WebP data to extract all the frames, ICC profile // and EXIF/XMP metadata. /* WebPDemuxer* demux = WebPDemux(&webp_data); uint32_t width = WebPDemuxGetI(demux, WEBP_FF_CANVAS_WIDTH); uint32_t height = WebPDemuxGetI(demux, WEBP_FF_CANVAS_HEIGHT); // ... (Get information about the features present in the WebP file). uint32_t flags = WebPDemuxGetI(demux, WEBP_FF_FORMAT_FLAGS); // ... (Iterate over all frames). WebPIterator iter; if (WebPDemuxGetFrame(demux, 1, &iter)) { do { // ... (Consume 'iter'; e.g. Decode 'iter.fragment' with WebPDecode(), // ... and get other frame properties like width, height, offsets etc. // ... see 'struct WebPIterator' below for more info). } while (WebPDemuxNextFrame(&iter)); WebPDemuxReleaseIterator(&iter); } // ... (Extract metadata). WebPChunkIterator chunk_iter; if (flags & ICCP_FLAG) WebPDemuxGetChunk(demux, "ICCP", 1, &chunk_iter); // ... (Consume the ICC profile in 'chunk_iter.chunk'). WebPDemuxReleaseChunkIterator(&chunk_iter); if (flags & EXIF_FLAG) WebPDemuxGetChunk(demux, "EXIF", 1, &chunk_iter); // ... (Consume the EXIF metadata in 'chunk_iter.chunk'). WebPDemuxReleaseChunkIterator(&chunk_iter); if (flags & XMP_FLAG) WebPDemuxGetChunk(demux, "XMP ", 1, &chunk_iter); // ... (Consume the XMP metadata in 'chunk_iter.chunk'). WebPDemuxReleaseChunkIterator(&chunk_iter); WebPDemuxDelete(demux); */ #ifndef WEBP_WEBP_DEMUX_H_ #define WEBP_WEBP_DEMUX_H_ #include "./decode.h" // for WEBP_CSP_MODE #include "./mux_types.h" #ifdef __cplusplus extern "C" { #endif #define WEBP_DEMUX_ABI_VERSION 0x0107 // MAJOR(8b) + MINOR(8b) // Note: forward declaring enumerations is not allowed in (strict) C and C++, // the types are left here for reference. // typedef enum WebPDemuxState WebPDemuxState; // typedef enum WebPFormatFeature WebPFormatFeature; typedef struct WebPDemuxer WebPDemuxer; typedef struct WebPIterator WebPIterator; typedef struct WebPChunkIterator WebPChunkIterator; typedef struct WebPAnimInfo WebPAnimInfo; typedef struct WebPAnimDecoderOptions WebPAnimDecoderOptions; //------------------------------------------------------------------------------ // Returns the version number of the demux library, packed in hexadecimal using // 8bits for each of major/minor/revision. E.g: v2.5.7 is 0x020507. WEBP_EXTERN int WebPGetDemuxVersion(void); //------------------------------------------------------------------------------ // Life of a Demux object typedef enum WebPDemuxState { WEBP_DEMUX_PARSE_ERROR = -1, // An error occurred while parsing. WEBP_DEMUX_PARSING_HEADER = 0, // Not enough data to parse full header. WEBP_DEMUX_PARSED_HEADER = 1, // Header parsing complete, // data may be available. WEBP_DEMUX_DONE = 2 // Entire file has been parsed. } WebPDemuxState; // Internal, version-checked, entry point WEBP_EXTERN WebPDemuxer* WebPDemuxInternal( const WebPData*, int, WebPDemuxState*, int); // Parses the full WebP file given by 'data'. For single images the WebP file // header alone or the file header and the chunk header may be absent. // Returns a WebPDemuxer object on successful parse, NULL otherwise. static WEBP_INLINE WebPDemuxer* WebPDemux(const WebPData* data) { return WebPDemuxInternal(data, 0, NULL, WEBP_DEMUX_ABI_VERSION); } // Parses the possibly incomplete WebP file given by 'data'. // If 'state' is non-NULL it will be set to indicate the status of the demuxer. // Returns NULL in case of error or if there isn't enough data to start parsing; // and a WebPDemuxer object on successful parse. // Note that WebPDemuxer keeps internal pointers to 'data' memory segment. // If this data is volatile, the demuxer object should be deleted (by calling // WebPDemuxDelete()) and WebPDemuxPartial() called again on the new data. // This is usually an inexpensive operation. static WEBP_INLINE WebPDemuxer* WebPDemuxPartial( const WebPData* data, WebPDemuxState* state) { return WebPDemuxInternal(data, 1, state, WEBP_DEMUX_ABI_VERSION); } // Frees memory associated with 'dmux'. WEBP_EXTERN void WebPDemuxDelete(WebPDemuxer* dmux); //------------------------------------------------------------------------------ // Data/information extraction. typedef enum WebPFormatFeature { WEBP_FF_FORMAT_FLAGS, // bit-wise combination of WebPFeatureFlags // corresponding to the 'VP8X' chunk (if present). WEBP_FF_CANVAS_WIDTH, WEBP_FF_CANVAS_HEIGHT, WEBP_FF_LOOP_COUNT, // only relevant for animated file WEBP_FF_BACKGROUND_COLOR, // idem. WEBP_FF_FRAME_COUNT // Number of frames present in the demux object. // In case of a partial demux, this is the number // of frames seen so far, with the last frame // possibly being partial. } WebPFormatFeature; // Get the 'feature' value from the 'dmux'. // NOTE: values are only valid if WebPDemux() was used or WebPDemuxPartial() // returned a state > WEBP_DEMUX_PARSING_HEADER. // If 'feature' is WEBP_FF_FORMAT_FLAGS, the returned value is a bit-wise // combination of WebPFeatureFlags values. // If 'feature' is WEBP_FF_LOOP_COUNT, WEBP_FF_BACKGROUND_COLOR, the returned // value is only meaningful if the bitstream is animated. WEBP_EXTERN uint32_t WebPDemuxGetI( const WebPDemuxer* dmux, WebPFormatFeature feature); //------------------------------------------------------------------------------ // Frame iteration. struct WebPIterator { int frame_num; int num_frames; // equivalent to WEBP_FF_FRAME_COUNT. int x_offset, y_offset; // offset relative to the canvas. int width, height; // dimensions of this frame. int duration; // display duration in milliseconds. WebPMuxAnimDispose dispose_method; // dispose method for the frame. int complete; // true if 'fragment' contains a full frame. partial images // may still be decoded with the WebP incremental decoder. WebPData fragment; // The frame given by 'frame_num'. Note for historical // reasons this is called a fragment. int has_alpha; // True if the frame contains transparency. WebPMuxAnimBlend blend_method; // Blend operation for the frame. uint32_t pad[2]; // padding for later use. void* private_; // for internal use only. }; // Retrieves frame 'frame_number' from 'dmux'. // 'iter->fragment' points to the frame on return from this function. // Setting 'frame_number' equal to 0 will return the last frame of the image. // Returns false if 'dmux' is NULL or frame 'frame_number' is not present. // Call WebPDemuxReleaseIterator() when use of the iterator is complete. // NOTE: 'dmux' must persist for the lifetime of 'iter'. WEBP_EXTERN int WebPDemuxGetFrame( const WebPDemuxer* dmux, int frame_number, WebPIterator* iter); // Sets 'iter->fragment' to point to the next ('iter->frame_num' + 1) or // previous ('iter->frame_num' - 1) frame. These functions do not loop. // Returns true on success, false otherwise. WEBP_EXTERN int WebPDemuxNextFrame(WebPIterator* iter); WEBP_EXTERN int WebPDemuxPrevFrame(WebPIterator* iter); // Releases any memory associated with 'iter'. // Must be called before any subsequent calls to WebPDemuxGetChunk() on the same // iter. Also, must be called before destroying the associated WebPDemuxer with // WebPDemuxDelete(). WEBP_EXTERN void WebPDemuxReleaseIterator(WebPIterator* iter); //------------------------------------------------------------------------------ // Chunk iteration. struct WebPChunkIterator { // The current and total number of chunks with the fourcc given to // WebPDemuxGetChunk(). int chunk_num; int num_chunks; WebPData chunk; // The payload of the chunk. uint32_t pad[6]; // padding for later use void* private_; }; // Retrieves the 'chunk_number' instance of the chunk with id 'fourcc' from // 'dmux'. // 'fourcc' is a character array containing the fourcc of the chunk to return, // e.g., "ICCP", "XMP ", "EXIF", etc. // Setting 'chunk_number' equal to 0 will return the last chunk in a set. // Returns true if the chunk is found, false otherwise. Image related chunk // payloads are accessed through WebPDemuxGetFrame() and related functions. // Call WebPDemuxReleaseChunkIterator() when use of the iterator is complete. // NOTE: 'dmux' must persist for the lifetime of the iterator. WEBP_EXTERN int WebPDemuxGetChunk(const WebPDemuxer* dmux, const char fourcc[4], int chunk_number, WebPChunkIterator* iter); // Sets 'iter->chunk' to point to the next ('iter->chunk_num' + 1) or previous // ('iter->chunk_num' - 1) chunk. These functions do not loop. // Returns true on success, false otherwise. WEBP_EXTERN int WebPDemuxNextChunk(WebPChunkIterator* iter); WEBP_EXTERN int WebPDemuxPrevChunk(WebPChunkIterator* iter); // Releases any memory associated with 'iter'. // Must be called before destroying the associated WebPDemuxer with // WebPDemuxDelete(). WEBP_EXTERN void WebPDemuxReleaseChunkIterator(WebPChunkIterator* iter); //------------------------------------------------------------------------------ // WebPAnimDecoder API // // This API allows decoding (possibly) animated WebP images. // // Code Example: /* WebPAnimDecoderOptions dec_options; WebPAnimDecoderOptionsInit(&dec_options); // Tune 'dec_options' as needed. WebPAnimDecoder* dec = WebPAnimDecoderNew(webp_data, &dec_options); WebPAnimInfo anim_info; WebPAnimDecoderGetInfo(dec, &anim_info); for (uint32_t i = 0; i < anim_info.loop_count; ++i) { while (WebPAnimDecoderHasMoreFrames(dec)) { uint8_t* buf; int timestamp; WebPAnimDecoderGetNext(dec, &buf, &timestamp); // ... (Render 'buf' based on 'timestamp'). // ... (Do NOT free 'buf', as it is owned by 'dec'). } WebPAnimDecoderReset(dec); } const WebPDemuxer* demuxer = WebPAnimDecoderGetDemuxer(dec); // ... (Do something using 'demuxer'; e.g. get EXIF/XMP/ICC data). WebPAnimDecoderDelete(dec); */ typedef struct WebPAnimDecoder WebPAnimDecoder; // Main opaque object. // Global options. struct WebPAnimDecoderOptions { // Output colorspace. Only the following modes are supported: // MODE_RGBA, MODE_BGRA, MODE_rgbA and MODE_bgrA. WEBP_CSP_MODE color_mode; int use_threads; // If true, use multi-threaded decoding. uint32_t padding[7]; // Padding for later use. }; // Internal, version-checked, entry point. WEBP_EXTERN int WebPAnimDecoderOptionsInitInternal( WebPAnimDecoderOptions*, int); // Should always be called, to initialize a fresh WebPAnimDecoderOptions // structure before modification. Returns false in case of version mismatch. // WebPAnimDecoderOptionsInit() must have succeeded before using the // 'dec_options' object. static WEBP_INLINE int WebPAnimDecoderOptionsInit( WebPAnimDecoderOptions* dec_options) { return WebPAnimDecoderOptionsInitInternal(dec_options, WEBP_DEMUX_ABI_VERSION); } // Internal, version-checked, entry point. WEBP_EXTERN WebPAnimDecoder* WebPAnimDecoderNewInternal( const WebPData*, const WebPAnimDecoderOptions*, int); // Creates and initializes a WebPAnimDecoder object. // Parameters: // webp_data - (in) WebP bitstream. This should remain unchanged during the // lifetime of the output WebPAnimDecoder object. // dec_options - (in) decoding options. Can be passed NULL to choose // reasonable defaults (in particular, color mode MODE_RGBA // will be picked). // Returns: // A pointer to the newly created WebPAnimDecoder object, or NULL in case of // parsing error, invalid option or memory error. static WEBP_INLINE WebPAnimDecoder* WebPAnimDecoderNew( const WebPData* webp_data, const WebPAnimDecoderOptions* dec_options) { return WebPAnimDecoderNewInternal(webp_data, dec_options, WEBP_DEMUX_ABI_VERSION); } // Global information about the animation.. struct WebPAnimInfo { uint32_t canvas_width; uint32_t canvas_height; uint32_t loop_count; uint32_t bgcolor; uint32_t frame_count; uint32_t pad[4]; // padding for later use }; // Get global information about the animation. // Parameters: // dec - (in) decoder instance to get information from. // info - (out) global information fetched from the animation. // Returns: // True on success. WEBP_EXTERN int WebPAnimDecoderGetInfo(const WebPAnimDecoder* dec, WebPAnimInfo* info); // Fetch the next frame from 'dec' based on options supplied to // WebPAnimDecoderNew(). This will be a fully reconstructed canvas of size // 'canvas_width * 4 * canvas_height', and not just the frame sub-rectangle. The // returned buffer 'buf' is valid only until the next call to // WebPAnimDecoderGetNext(), WebPAnimDecoderReset() or WebPAnimDecoderDelete(). // Parameters: // dec - (in/out) decoder instance from which the next frame is to be fetched. // buf - (out) decoded frame. // timestamp - (out) timestamp of the frame in milliseconds. // Returns: // False if any of the arguments are NULL, or if there is a parsing or // decoding error, or if there are no more frames. Otherwise, returns true. WEBP_EXTERN int WebPAnimDecoderGetNext(WebPAnimDecoder* dec, uint8_t** buf, int* timestamp); // Check if there are more frames left to decode. // Parameters: // dec - (in) decoder instance to be checked. // Returns: // True if 'dec' is not NULL and some frames are yet to be decoded. // Otherwise, returns false. WEBP_EXTERN int WebPAnimDecoderHasMoreFrames(const WebPAnimDecoder* dec); // Resets the WebPAnimDecoder object, so that next call to // WebPAnimDecoderGetNext() will restart decoding from 1st frame. This would be // helpful when all frames need to be decoded multiple times (e.g. // info.loop_count times) without destroying and recreating the 'dec' object. // Parameters: // dec - (in/out) decoder instance to be reset WEBP_EXTERN void WebPAnimDecoderReset(WebPAnimDecoder* dec); // Grab the internal demuxer object. // Getting the demuxer object can be useful if one wants to use operations only // available through demuxer; e.g. to get XMP/EXIF/ICC metadata. The returned // demuxer object is owned by 'dec' and is valid only until the next call to // WebPAnimDecoderDelete(). // // Parameters: // dec - (in) decoder instance from which the demuxer object is to be fetched. WEBP_EXTERN const WebPDemuxer* WebPAnimDecoderGetDemuxer( const WebPAnimDecoder* dec); // Deletes the WebPAnimDecoder object. // Parameters: // dec - (in/out) decoder instance to be deleted WEBP_EXTERN void WebPAnimDecoderDelete(WebPAnimDecoder* dec); #ifdef __cplusplus } // extern "C" #endif #endif // WEBP_WEBP_DEMUX_H_
YifuLiu/AliOS-Things
components/SDL2/src/image/Xcode/Frameworks/webp.framework/Versions/A/Headers/webp/demux.h
C
apache-2.0
15,603
// Copyright 2011 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // WebP encoder: main interface // // Author: Skal (pascal.massimino@gmail.com) #ifndef WEBP_WEBP_ENCODE_H_ #define WEBP_WEBP_ENCODE_H_ #include "./types.h" #ifdef __cplusplus extern "C" { #endif #define WEBP_ENCODER_ABI_VERSION 0x020e // MAJOR(8b) + MINOR(8b) // Note: forward declaring enumerations is not allowed in (strict) C and C++, // the types are left here for reference. // typedef enum WebPImageHint WebPImageHint; // typedef enum WebPEncCSP WebPEncCSP; // typedef enum WebPPreset WebPPreset; // typedef enum WebPEncodingError WebPEncodingError; typedef struct WebPConfig WebPConfig; typedef struct WebPPicture WebPPicture; // main structure for I/O typedef struct WebPAuxStats WebPAuxStats; typedef struct WebPMemoryWriter WebPMemoryWriter; // Return the encoder's version number, packed in hexadecimal using 8bits for // each of major/minor/revision. E.g: v2.5.7 is 0x020507. WEBP_EXTERN int WebPGetEncoderVersion(void); //------------------------------------------------------------------------------ // One-stop-shop call! No questions asked: // Returns the size of the compressed data (pointed to by *output), or 0 if // an error occurred. The compressed data must be released by the caller // using the call 'WebPFree(*output)'. // These functions compress using the lossy format, and the quality_factor // can go from 0 (smaller output, lower quality) to 100 (best quality, // larger output). WEBP_EXTERN size_t WebPEncodeRGB(const uint8_t* rgb, int width, int height, int stride, float quality_factor, uint8_t** output); WEBP_EXTERN size_t WebPEncodeBGR(const uint8_t* bgr, int width, int height, int stride, float quality_factor, uint8_t** output); WEBP_EXTERN size_t WebPEncodeRGBA(const uint8_t* rgba, int width, int height, int stride, float quality_factor, uint8_t** output); WEBP_EXTERN size_t WebPEncodeBGRA(const uint8_t* bgra, int width, int height, int stride, float quality_factor, uint8_t** output); // These functions are the equivalent of the above, but compressing in a // lossless manner. Files are usually larger than lossy format, but will // not suffer any compression loss. WEBP_EXTERN size_t WebPEncodeLosslessRGB(const uint8_t* rgb, int width, int height, int stride, uint8_t** output); WEBP_EXTERN size_t WebPEncodeLosslessBGR(const uint8_t* bgr, int width, int height, int stride, uint8_t** output); WEBP_EXTERN size_t WebPEncodeLosslessRGBA(const uint8_t* rgba, int width, int height, int stride, uint8_t** output); WEBP_EXTERN size_t WebPEncodeLosslessBGRA(const uint8_t* bgra, int width, int height, int stride, uint8_t** output); // Releases memory returned by the WebPEncode*() functions above. WEBP_EXTERN void WebPFree(void* ptr); //------------------------------------------------------------------------------ // Coding parameters // Image characteristics hint for the underlying encoder. typedef enum WebPImageHint { WEBP_HINT_DEFAULT = 0, // default preset. WEBP_HINT_PICTURE, // digital picture, like portrait, inner shot WEBP_HINT_PHOTO, // outdoor photograph, with natural lighting WEBP_HINT_GRAPH, // Discrete tone image (graph, map-tile etc). WEBP_HINT_LAST } WebPImageHint; // Compression parameters. struct WebPConfig { int lossless; // Lossless encoding (0=lossy(default), 1=lossless). float quality; // between 0 and 100. For lossy, 0 gives the smallest // size and 100 the largest. For lossless, this // parameter is the amount of effort put into the // compression: 0 is the fastest but gives larger // files compared to the slowest, but best, 100. int method; // quality/speed trade-off (0=fast, 6=slower-better) WebPImageHint image_hint; // Hint for image type (lossless only for now). int target_size; // if non-zero, set the desired target size in bytes. // Takes precedence over the 'compression' parameter. float target_PSNR; // if non-zero, specifies the minimal distortion to // try to achieve. Takes precedence over target_size. int segments; // maximum number of segments to use, in [1..4] int sns_strength; // Spatial Noise Shaping. 0=off, 100=maximum. int filter_strength; // range: [0 = off .. 100 = strongest] int filter_sharpness; // range: [0 = off .. 7 = least sharp] int filter_type; // filtering type: 0 = simple, 1 = strong (only used // if filter_strength > 0 or autofilter > 0) int autofilter; // Auto adjust filter's strength [0 = off, 1 = on] int alpha_compression; // Algorithm for encoding the alpha plane (0 = none, // 1 = compressed with WebP lossless). Default is 1. int alpha_filtering; // Predictive filtering method for alpha plane. // 0: none, 1: fast, 2: best. Default if 1. int alpha_quality; // Between 0 (smallest size) and 100 (lossless). // Default is 100. int pass; // number of entropy-analysis passes (in [1..10]). int show_compressed; // if true, export the compressed picture back. // In-loop filtering is not applied. int preprocessing; // preprocessing filter: // 0=none, 1=segment-smooth, 2=pseudo-random dithering int partitions; // log2(number of token partitions) in [0..3]. Default // is set to 0 for easier progressive decoding. int partition_limit; // quality degradation allowed to fit the 512k limit // on prediction modes coding (0: no degradation, // 100: maximum possible degradation). int emulate_jpeg_size; // If true, compression parameters will be remapped // to better match the expected output size from // JPEG compression. Generally, the output size will // be similar but the degradation will be lower. int thread_level; // If non-zero, try and use multi-threaded encoding. int low_memory; // If set, reduce memory usage (but increase CPU use). int near_lossless; // Near lossless encoding [0 = max loss .. 100 = off // (default)]. int exact; // if non-zero, preserve the exact RGB values under // transparent area. Otherwise, discard this invisible // RGB information for better compression. The default // value is 0. int use_delta_palette; // reserved for future lossless feature int use_sharp_yuv; // if needed, use sharp (and slow) RGB->YUV conversion uint32_t pad[2]; // padding for later use }; // Enumerate some predefined settings for WebPConfig, depending on the type // of source picture. These presets are used when calling WebPConfigPreset(). typedef enum WebPPreset { WEBP_PRESET_DEFAULT = 0, // default preset. WEBP_PRESET_PICTURE, // digital picture, like portrait, inner shot WEBP_PRESET_PHOTO, // outdoor photograph, with natural lighting WEBP_PRESET_DRAWING, // hand or line drawing, with high-contrast details WEBP_PRESET_ICON, // small-sized colorful images WEBP_PRESET_TEXT // text-like } WebPPreset; // Internal, version-checked, entry point WEBP_EXTERN int WebPConfigInitInternal(WebPConfig*, WebPPreset, float, int); // Should always be called, to initialize a fresh WebPConfig structure before // modification. Returns false in case of version mismatch. WebPConfigInit() // must have succeeded before using the 'config' object. // Note that the default values are lossless=0 and quality=75. static WEBP_INLINE int WebPConfigInit(WebPConfig* config) { return WebPConfigInitInternal(config, WEBP_PRESET_DEFAULT, 75.f, WEBP_ENCODER_ABI_VERSION); } // This function will initialize the configuration according to a predefined // set of parameters (referred to by 'preset') and a given quality factor. // This function can be called as a replacement to WebPConfigInit(). Will // return false in case of error. static WEBP_INLINE int WebPConfigPreset(WebPConfig* config, WebPPreset preset, float quality) { return WebPConfigInitInternal(config, preset, quality, WEBP_ENCODER_ABI_VERSION); } // Activate the lossless compression mode with the desired efficiency level // between 0 (fastest, lowest compression) and 9 (slower, best compression). // A good default level is '6', providing a fair tradeoff between compression // speed and final compressed size. // This function will overwrite several fields from config: 'method', 'quality' // and 'lossless'. Returns false in case of parameter error. WEBP_EXTERN int WebPConfigLosslessPreset(WebPConfig* config, int level); // Returns true if 'config' is non-NULL and all configuration parameters are // within their valid ranges. WEBP_EXTERN int WebPValidateConfig(const WebPConfig* config); //------------------------------------------------------------------------------ // Input / Output // Structure for storing auxiliary statistics. struct WebPAuxStats { int coded_size; // final size float PSNR[5]; // peak-signal-to-noise ratio for Y/U/V/All/Alpha int block_count[3]; // number of intra4/intra16/skipped macroblocks int header_bytes[2]; // approximate number of bytes spent for header // and mode-partition #0 int residual_bytes[3][4]; // approximate number of bytes spent for // DC/AC/uv coefficients for each (0..3) segments. int segment_size[4]; // number of macroblocks in each segments int segment_quant[4]; // quantizer values for each segments int segment_level[4]; // filtering strength for each segments [0..63] int alpha_data_size; // size of the transparency data int layer_data_size; // size of the enhancement layer data // lossless encoder statistics uint32_t lossless_features; // bit0:predictor bit1:cross-color transform // bit2:subtract-green bit3:color indexing int histogram_bits; // number of precision bits of histogram int transform_bits; // precision bits for transform int cache_bits; // number of bits for color cache lookup int palette_size; // number of color in palette, if used int lossless_size; // final lossless size int lossless_hdr_size; // lossless header (transform, huffman etc) size int lossless_data_size; // lossless image data size uint32_t pad[2]; // padding for later use }; // Signature for output function. Should return true if writing was successful. // data/data_size is the segment of data to write, and 'picture' is for // reference (and so one can make use of picture->custom_ptr). typedef int (*WebPWriterFunction)(const uint8_t* data, size_t data_size, const WebPPicture* picture); // WebPMemoryWrite: a special WebPWriterFunction that writes to memory using // the following WebPMemoryWriter object (to be set as a custom_ptr). struct WebPMemoryWriter { uint8_t* mem; // final buffer (of size 'max_size', larger than 'size'). size_t size; // final size size_t max_size; // total capacity uint32_t pad[1]; // padding for later use }; // The following must be called first before any use. WEBP_EXTERN void WebPMemoryWriterInit(WebPMemoryWriter* writer); // The following must be called to deallocate writer->mem memory. The 'writer' // object itself is not deallocated. WEBP_EXTERN void WebPMemoryWriterClear(WebPMemoryWriter* writer); // The custom writer to be used with WebPMemoryWriter as custom_ptr. Upon // completion, writer.mem and writer.size will hold the coded data. // writer.mem must be freed by calling WebPMemoryWriterClear. WEBP_EXTERN int WebPMemoryWrite(const uint8_t* data, size_t data_size, const WebPPicture* picture); // Progress hook, called from time to time to report progress. It can return // false to request an abort of the encoding process, or true otherwise if // everything is OK. typedef int (*WebPProgressHook)(int percent, const WebPPicture* picture); // Color spaces. typedef enum WebPEncCSP { // chroma sampling WEBP_YUV420 = 0, // 4:2:0 WEBP_YUV420A = 4, // alpha channel variant WEBP_CSP_UV_MASK = 3, // bit-mask to get the UV sampling factors WEBP_CSP_ALPHA_BIT = 4 // bit that is set if alpha is present } WebPEncCSP; // Encoding error conditions. typedef enum WebPEncodingError { VP8_ENC_OK = 0, VP8_ENC_ERROR_OUT_OF_MEMORY, // memory error allocating objects VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY, // memory error while flushing bits VP8_ENC_ERROR_NULL_PARAMETER, // a pointer parameter is NULL VP8_ENC_ERROR_INVALID_CONFIGURATION, // configuration is invalid VP8_ENC_ERROR_BAD_DIMENSION, // picture has invalid width/height VP8_ENC_ERROR_PARTITION0_OVERFLOW, // partition is bigger than 512k VP8_ENC_ERROR_PARTITION_OVERFLOW, // partition is bigger than 16M VP8_ENC_ERROR_BAD_WRITE, // error while flushing bytes VP8_ENC_ERROR_FILE_TOO_BIG, // file is bigger than 4G VP8_ENC_ERROR_USER_ABORT, // abort request by user VP8_ENC_ERROR_LAST // list terminator. always last. } WebPEncodingError; // maximum width/height allowed (inclusive), in pixels #define WEBP_MAX_DIMENSION 16383 // Main exchange structure (input samples, output bytes, statistics) struct WebPPicture { // INPUT ////////////// // Main flag for encoder selecting between ARGB or YUV input. // It is recommended to use ARGB input (*argb, argb_stride) for lossless // compression, and YUV input (*y, *u, *v, etc.) for lossy compression // since these are the respective native colorspace for these formats. int use_argb; // YUV input (mostly used for input to lossy compression) WebPEncCSP colorspace; // colorspace: should be YUV420 for now (=Y'CbCr). int width, height; // dimensions (less or equal to WEBP_MAX_DIMENSION) uint8_t *y, *u, *v; // pointers to luma/chroma planes. int y_stride, uv_stride; // luma/chroma strides. uint8_t* a; // pointer to the alpha plane int a_stride; // stride of the alpha plane uint32_t pad1[2]; // padding for later use // ARGB input (mostly used for input to lossless compression) uint32_t* argb; // Pointer to argb (32 bit) plane. int argb_stride; // This is stride in pixels units, not bytes. uint32_t pad2[3]; // padding for later use // OUTPUT /////////////// // Byte-emission hook, to store compressed bytes as they are ready. WebPWriterFunction writer; // can be NULL void* custom_ptr; // can be used by the writer. // map for extra information (only for lossy compression mode) int extra_info_type; // 1: intra type, 2: segment, 3: quant // 4: intra-16 prediction mode, // 5: chroma prediction mode, // 6: bit cost, 7: distortion uint8_t* extra_info; // if not NULL, points to an array of size // ((width + 15) / 16) * ((height + 15) / 16) that // will be filled with a macroblock map, depending // on extra_info_type. // STATS AND REPORTS /////////////////////////// // Pointer to side statistics (updated only if not NULL) WebPAuxStats* stats; // Error code for the latest error encountered during encoding WebPEncodingError error_code; // If not NULL, report progress during encoding. WebPProgressHook progress_hook; void* user_data; // this field is free to be set to any value and // used during callbacks (like progress-report e.g.). uint32_t pad3[3]; // padding for later use // Unused for now uint8_t *pad4, *pad5; uint32_t pad6[8]; // padding for later use // PRIVATE FIELDS //////////////////// void* memory_; // row chunk of memory for yuva planes void* memory_argb_; // and for argb too. void* pad7[2]; // padding for later use }; // Internal, version-checked, entry point WEBP_EXTERN int WebPPictureInitInternal(WebPPicture*, int); // Should always be called, to initialize the structure. Returns false in case // of version mismatch. WebPPictureInit() must have succeeded before using the // 'picture' object. // Note that, by default, use_argb is false and colorspace is WEBP_YUV420. static WEBP_INLINE int WebPPictureInit(WebPPicture* picture) { return WebPPictureInitInternal(picture, WEBP_ENCODER_ABI_VERSION); } //------------------------------------------------------------------------------ // WebPPicture utils // Convenience allocation / deallocation based on picture->width/height: // Allocate y/u/v buffers as per colorspace/width/height specification. // Note! This function will free the previous buffer if needed. // Returns false in case of memory error. WEBP_EXTERN int WebPPictureAlloc(WebPPicture* picture); // Release the memory allocated by WebPPictureAlloc() or WebPPictureImport*(). // Note that this function does _not_ free the memory used by the 'picture' // object itself. // Besides memory (which is reclaimed) all other fields of 'picture' are // preserved. WEBP_EXTERN void WebPPictureFree(WebPPicture* picture); // Copy the pixels of *src into *dst, using WebPPictureAlloc. Upon return, *dst // will fully own the copied pixels (this is not a view). The 'dst' picture need // not be initialized as its content is overwritten. // Returns false in case of memory allocation error. WEBP_EXTERN int WebPPictureCopy(const WebPPicture* src, WebPPicture* dst); // Compute the single distortion for packed planes of samples. // 'src' will be compared to 'ref', and the raw distortion stored into // '*distortion'. The refined metric (log(MSE), log(1 - ssim),...' will be // stored in '*result'. // 'x_step' is the horizontal stride (in bytes) between samples. // 'src/ref_stride' is the byte distance between rows. // Returns false in case of error (bad parameter, memory allocation error, ...). WEBP_EXTERN int WebPPlaneDistortion(const uint8_t* src, size_t src_stride, const uint8_t* ref, size_t ref_stride, int width, int height, size_t x_step, int type, // 0 = PSNR, 1 = SSIM, 2 = LSIM float* distortion, float* result); // Compute PSNR, SSIM or LSIM distortion metric between two pictures. Results // are in dB, stored in result[] in the B/G/R/A/All order. The distortion is // always performed using ARGB samples. Hence if the input is YUV(A), the // picture will be internally converted to ARGB (just for the measurement). // Warning: this function is rather CPU-intensive. WEBP_EXTERN int WebPPictureDistortion( const WebPPicture* src, const WebPPicture* ref, int metric_type, // 0 = PSNR, 1 = SSIM, 2 = LSIM float result[5]); // self-crops a picture to the rectangle defined by top/left/width/height. // Returns false in case of memory allocation error, or if the rectangle is // outside of the source picture. // The rectangle for the view is defined by the top-left corner pixel // coordinates (left, top) as well as its width and height. This rectangle // must be fully be comprised inside the 'src' source picture. If the source // picture uses the YUV420 colorspace, the top and left coordinates will be // snapped to even values. WEBP_EXTERN int WebPPictureCrop(WebPPicture* picture, int left, int top, int width, int height); // Extracts a view from 'src' picture into 'dst'. The rectangle for the view // is defined by the top-left corner pixel coordinates (left, top) as well // as its width and height. This rectangle must be fully be comprised inside // the 'src' source picture. If the source picture uses the YUV420 colorspace, // the top and left coordinates will be snapped to even values. // Picture 'src' must out-live 'dst' picture. Self-extraction of view is allowed // ('src' equal to 'dst') as a mean of fast-cropping (but note that doing so, // the original dimension will be lost). Picture 'dst' need not be initialized // with WebPPictureInit() if it is different from 'src', since its content will // be overwritten. // Returns false in case of memory allocation error or invalid parameters. WEBP_EXTERN int WebPPictureView(const WebPPicture* src, int left, int top, int width, int height, WebPPicture* dst); // Returns true if the 'picture' is actually a view and therefore does // not own the memory for pixels. WEBP_EXTERN int WebPPictureIsView(const WebPPicture* picture); // Rescale a picture to new dimension width x height. // If either 'width' or 'height' (but not both) is 0 the corresponding // dimension will be calculated preserving the aspect ratio. // No gamma correction is applied. // Returns false in case of error (invalid parameter or insufficient memory). WEBP_EXTERN int WebPPictureRescale(WebPPicture* pic, int width, int height); // Colorspace conversion function to import RGB samples. // Previous buffer will be free'd, if any. // *rgb buffer should have a size of at least height * rgb_stride. // Returns false in case of memory error. WEBP_EXTERN int WebPPictureImportRGB( WebPPicture* picture, const uint8_t* rgb, int rgb_stride); // Same, but for RGBA buffer. WEBP_EXTERN int WebPPictureImportRGBA( WebPPicture* picture, const uint8_t* rgba, int rgba_stride); // Same, but for RGBA buffer. Imports the RGB direct from the 32-bit format // input buffer ignoring the alpha channel. Avoids needing to copy the data // to a temporary 24-bit RGB buffer to import the RGB only. WEBP_EXTERN int WebPPictureImportRGBX( WebPPicture* picture, const uint8_t* rgbx, int rgbx_stride); // Variants of the above, but taking BGR(A|X) input. WEBP_EXTERN int WebPPictureImportBGR( WebPPicture* picture, const uint8_t* bgr, int bgr_stride); WEBP_EXTERN int WebPPictureImportBGRA( WebPPicture* picture, const uint8_t* bgra, int bgra_stride); WEBP_EXTERN int WebPPictureImportBGRX( WebPPicture* picture, const uint8_t* bgrx, int bgrx_stride); // Converts picture->argb data to the YUV420A format. The 'colorspace' // parameter is deprecated and should be equal to WEBP_YUV420. // Upon return, picture->use_argb is set to false. The presence of real // non-opaque transparent values is detected, and 'colorspace' will be // adjusted accordingly. Note that this method is lossy. // Returns false in case of error. WEBP_EXTERN int WebPPictureARGBToYUVA(WebPPicture* picture, WebPEncCSP /*colorspace = WEBP_YUV420*/); // Same as WebPPictureARGBToYUVA(), but the conversion is done using // pseudo-random dithering with a strength 'dithering' between // 0.0 (no dithering) and 1.0 (maximum dithering). This is useful // for photographic picture. WEBP_EXTERN int WebPPictureARGBToYUVADithered( WebPPicture* picture, WebPEncCSP colorspace, float dithering); // Performs 'sharp' RGBA->YUVA420 downsampling and colorspace conversion. // Downsampling is handled with extra care in case of color clipping. This // method is roughly 2x slower than WebPPictureARGBToYUVA() but produces better // and sharper YUV representation. // Returns false in case of error. WEBP_EXTERN int WebPPictureSharpARGBToYUVA(WebPPicture* picture); // kept for backward compatibility: WEBP_EXTERN int WebPPictureSmartARGBToYUVA(WebPPicture* picture); // Converts picture->yuv to picture->argb and sets picture->use_argb to true. // The input format must be YUV_420 or YUV_420A. The conversion from YUV420 to // ARGB incurs a small loss too. // Note that the use of this colorspace is discouraged if one has access to the // raw ARGB samples, since using YUV420 is comparatively lossy. // Returns false in case of error. WEBP_EXTERN int WebPPictureYUVAToARGB(WebPPicture* picture); // Helper function: given a width x height plane of RGBA or YUV(A) samples // clean-up or smoothen the YUV or RGB samples under fully transparent area, // to help compressibility (no guarantee, though). WEBP_EXTERN void WebPCleanupTransparentArea(WebPPicture* picture); // Scan the picture 'picture' for the presence of non fully opaque alpha values. // Returns true in such case. Otherwise returns false (indicating that the // alpha plane can be ignored altogether e.g.). WEBP_EXTERN int WebPPictureHasTransparency(const WebPPicture* picture); // Remove the transparency information (if present) by blending the color with // the background color 'background_rgb' (specified as 24bit RGB triplet). // After this call, all alpha values are reset to 0xff. WEBP_EXTERN void WebPBlendAlpha(WebPPicture* pic, uint32_t background_rgb); //------------------------------------------------------------------------------ // Main call // Main encoding call, after config and picture have been initialized. // 'picture' must be less than 16384x16384 in dimension (cf WEBP_MAX_DIMENSION), // and the 'config' object must be a valid one. // Returns false in case of error, true otherwise. // In case of error, picture->error_code is updated accordingly. // 'picture' can hold the source samples in both YUV(A) or ARGB input, depending // on the value of 'picture->use_argb'. It is highly recommended to use // the former for lossy encoding, and the latter for lossless encoding // (when config.lossless is true). Automatic conversion from one format to // another is provided but they both incur some loss. WEBP_EXTERN int WebPEncode(const WebPConfig* config, WebPPicture* picture); //------------------------------------------------------------------------------ #ifdef __cplusplus } // extern "C" #endif #endif // WEBP_WEBP_ENCODE_H_
YifuLiu/AliOS-Things
components/SDL2/src/image/Xcode/Frameworks/webp.framework/Versions/A/Headers/webp/encode.h
C
apache-2.0
27,478
// Copyright 2012 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // Data-types common to the mux and demux libraries. // // Author: Urvang (urvang@google.com) #ifndef WEBP_WEBP_MUX_TYPES_H_ #define WEBP_WEBP_MUX_TYPES_H_ #include <stdlib.h> // free() #include <string.h> // memset() #include "./types.h" #ifdef __cplusplus extern "C" { #endif // Note: forward declaring enumerations is not allowed in (strict) C and C++, // the types are left here for reference. // typedef enum WebPFeatureFlags WebPFeatureFlags; // typedef enum WebPMuxAnimDispose WebPMuxAnimDispose; // typedef enum WebPMuxAnimBlend WebPMuxAnimBlend; typedef struct WebPData WebPData; // VP8X Feature Flags. typedef enum WebPFeatureFlags { ANIMATION_FLAG = 0x00000002, XMP_FLAG = 0x00000004, EXIF_FLAG = 0x00000008, ALPHA_FLAG = 0x00000010, ICCP_FLAG = 0x00000020, ALL_VALID_FLAGS = 0x0000003e } WebPFeatureFlags; // Dispose method (animation only). Indicates how the area used by the current // frame is to be treated before rendering the next frame on the canvas. typedef enum WebPMuxAnimDispose { WEBP_MUX_DISPOSE_NONE, // Do not dispose. WEBP_MUX_DISPOSE_BACKGROUND // Dispose to background color. } WebPMuxAnimDispose; // Blend operation (animation only). Indicates how transparent pixels of the // current frame are blended with those of the previous canvas. typedef enum WebPMuxAnimBlend { WEBP_MUX_BLEND, // Blend. WEBP_MUX_NO_BLEND // Do not blend. } WebPMuxAnimBlend; // Data type used to describe 'raw' data, e.g., chunk data // (ICC profile, metadata) and WebP compressed image data. struct WebPData { const uint8_t* bytes; size_t size; }; // Initializes the contents of the 'webp_data' object with default values. static WEBP_INLINE void WebPDataInit(WebPData* webp_data) { if (webp_data != NULL) { memset(webp_data, 0, sizeof(*webp_data)); } } // Clears the contents of the 'webp_data' object by calling free(). Does not // deallocate the object itself. static WEBP_INLINE void WebPDataClear(WebPData* webp_data) { if (webp_data != NULL) { free((void*)webp_data->bytes); WebPDataInit(webp_data); } } // Allocates necessary storage for 'dst' and copies the contents of 'src'. // Returns true on success. static WEBP_INLINE int WebPDataCopy(const WebPData* src, WebPData* dst) { if (src == NULL || dst == NULL) return 0; WebPDataInit(dst); if (src->bytes != NULL && src->size != 0) { dst->bytes = (uint8_t*)malloc(src->size); if (dst->bytes == NULL) return 0; memcpy((void*)dst->bytes, src->bytes, src->size); dst->size = src->size; } return 1; } #ifdef __cplusplus } // extern "C" #endif #endif // WEBP_WEBP_MUX_TYPES_H_
YifuLiu/AliOS-Things
components/SDL2/src/image/Xcode/Frameworks/webp.framework/Versions/A/Headers/webp/mux_types.h
C
apache-2.0
3,147
// Copyright 2010 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // Common types // // Author: Skal (pascal.massimino@gmail.com) #ifndef WEBP_WEBP_TYPES_H_ #define WEBP_WEBP_TYPES_H_ #include <stddef.h> // for size_t #ifndef _MSC_VER #include <inttypes.h> #if defined(__cplusplus) || !defined(__STRICT_ANSI__) || \ (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) #define WEBP_INLINE inline #else #define WEBP_INLINE #endif #else typedef signed char int8_t; typedef unsigned char uint8_t; typedef signed short int16_t; typedef unsigned short uint16_t; typedef signed int int32_t; typedef unsigned int uint32_t; typedef unsigned long long int uint64_t; typedef long long int int64_t; #define WEBP_INLINE __forceinline #endif /* _MSC_VER */ #ifndef WEBP_EXTERN // This explicitly marks library functions and allows for changing the // signature for e.g., Windows DLL builds. # if defined(__GNUC__) && __GNUC__ >= 4 # define WEBP_EXTERN extern __attribute__ ((visibility ("default"))) # else # define WEBP_EXTERN extern # endif /* __GNUC__ >= 4 */ #endif /* WEBP_EXTERN */ // Macro to check ABI compatibility (same major revision number) #define WEBP_ABI_IS_INCOMPATIBLE(a, b) (((a) >> 8) != ((b) >> 8)) #endif // WEBP_WEBP_TYPES_H_
YifuLiu/AliOS-Things
components/SDL2/src/image/Xcode/Frameworks/webp.framework/Versions/A/Headers/webp/types.h
C
apache-2.0
1,662
#! /bin/csh -ef set prog = `/usr/bin/basename $0` set usage = "Usage: $prog [-f] root-dir info-file [tiff-file] [-d dest-dir] [-r resource-dir] [-traditional | -gnutar]" set noglob if (-x /usr/bin/mkbom) then set mkbom=/usr/bin/mkbom set lsbom=/usr/bin/lsbom else set mkbom=/usr/etc/mkbom set lsbom=/usr/etc/lsbom endif if (-x /usr/bin/awk) then set awk=/usr/bin/awk else set awk=/bin/awk endif set gnutar=/usr/bin/gnutar set tar=/usr/bin/tar set pax=/bin/pax # gather parameters if ($#argv == 0) then echo $usage exit(1) endif while ( $#argv > 0 ) switch ( $argv[1] ) case -d: if ( $?destDir ) then echo ${prog}: dest-dir parameter already set to ${destDir}. echo $usage exit(1) else if ( $#argv < 2 ) then echo ${prog}: -d option requires destination directory. echo $usage exit(1) else set destDir = $argv[2] shift; shift breaksw endif case -f: if ( $?rootDir ) then echo ${prog}: root-dir parameter already set to ${rootDir}. echo $usage exit(1) else if ( $#argv < 2 ) then echo ${prog}: -f option requires package root directory. echo $usage exit(1) else set rootDir = $argv[2] set fflag shift; shift breaksw endif case -r: if ( $?resDir ) then echo ${prog}: resource-dir parameter already set to ${resDir}. echo $usage exit(1) else if ( $#argv < 2 ) then echo ${prog}: -r option requires package resource directory. echo $usage exit(1) else set resDir = $argv[2] shift; shift breaksw endif case -traditional: set usetar unset usegnutar unset usepax breaksw case -gnutar: set usegnutar unset usepax unset usetar case -B: # We got long file names, better use bigtar instead #set archiver = /NextAdmin/Installer.app/Resources/installer_bigtar echo 2>&1 ${prog}: -B flag is no longer relevant. shift breaksw case -*: echo ${prog}: Unknown option: $argv[1] echo $usage exit(1) case *.info: if ( $?info ) then echo ${prog}: info-file parameter already set to ${info}. echo $usage exit(1) else set info = "$argv[1]" shift breaksw endif case *.tiff: if ( $?tiff ) then echo ${prog}: tiff-file parameter already set to ${tiff}. echo $usage exit(1) else set tiff = "$argv[1]" shift breaksw endif default: if ( $?rootDir ) then echo ${prog}: unrecognized parameter: $argv[1] echo $usage exit(1) else set rootDir = "$argv[1]" shift breaksw endif endsw end # check for mandatory parameters if ( ! $?rootDir ) then echo ${prog}: missing root-dir parameter. echo $usage exit(1) else if ( ! $?info) then echo ${prog}: missing info-file parameter. echo $usage exit(1) endif # destDir gets default value if unset on command line if ( $?destDir ) then /bin/mkdir -p $destDir else set destDir = . endif # derive the root name for the package from the root name of the info file set root = `/usr/bin/basename $info .info` # create package directory set pkg = ${destDir}/${root}.pkg echo Generating Installer package $pkg ... if ( -e $pkg ) /bin/rm -rf $pkg /bin/mkdir -p -m 755 $pkg # (gnu)tar/pax and compress root directory to package archive echo -n " creating package archive ... " if ( $?fflag ) then set pkgTop = ${rootDir:t} set parent = ${rootDir:h} if ( "$parent" == "$pkgTop" ) set parent = "." else set parent = $rootDir set pkgTop = . endif if ( $?usetar ) then set pkgArchive = $pkg/$root.tar.Z (cd $parent; $tar -w $pkgTop) | /usr/bin/compress -f -c > $pkgArchive else if ( $?usegnutar ) then set pkgArchive = $pkg/$root.tar.gz (cd $parent; $gnutar zcf $pkgArchive $pkgTop) else set pkgArchive = $pkg/$root.pax.gz (cd $parent; $pax -w -z -x cpio $pkgTop) > $pkgArchive endif /bin/chmod 444 $pkgArchive echo done. # copy info file to package set pkgInfo = $pkg/$root.info echo -n " copying ${info:t} ... " /bin/cp $info $pkgInfo /bin/chmod 444 $pkgInfo echo done. # copy tiff file to package if ( $?tiff ) then set pkgTiff = $pkg/$root.tiff echo -n " copying ${tiff:t} ... " /bin/cp $tiff $pkgTiff /bin/chmod 444 $pkgTiff echo done. endif # copy resources to package if ( $?resDir ) then echo -n " copying ${resDir:t} ... " # don't want to see push/pop output pushd $resDir > /dev/null # get lists of resources. We'll want to change # permissions on just these things later. set directoriesInResDir = `find . -type d` set filesInResDir = `find . -type f` popd > /dev/null # copy the resource directory contents into the package directory foreach resFile (`ls $resDir`) cp -r $resDir/$resFile $pkg end pushd $pkg > /dev/null # Change all directories to +r+x, except the package # directory itself foreach resFileItem ($directoriesInResDir) if ( $resFileItem != "." ) then chmod 555 $resFileItem endif end # change all flat files to read only foreach resFileItem ($filesInResDir) chmod 444 $resFileItem end popd > /dev/null echo done. endif # generate bom file set pkgBom = $pkg/$root.bom echo -n " generating bom file ... " /bin/rm -f $pkgBom if ( $?fflag ) then $mkbom $parent $pkgBom >& /dev/null else $mkbom $rootDir $pkgBom >& /dev/null endif /bin/chmod 444 $pkgArchive echo done. # generate sizes file set pkgSizes = $pkg/$root.sizes echo -n " generating sizes file ... " # compute number of files in package set numFiles = `$lsbom -s $pkgBom | /usr/bin/wc -l` # compute package size when compressed @ compressedSize = `/usr/bin/du -k -s $pkg | $awk '{print $1}'` @ compressedSize += 3 # add 1KB each for sizes, location, status files @ infoSize = `/bin/ls -s $pkgInfo | $awk '{print $1}'` @ bomSize = `/bin/ls -s $pkgBom | $awk '{print $1}'` if ( $?tiff ) then @ tiffSize = `/bin/ls -s $pkgTiff | $awk '{print $1}'` else @ tiffSize = 0 endif @ installedSize = `/usr/bin/du -k -s $rootDir | $awk '{print $1}'` @ installedSize += $infoSize + $bomSize + $tiffSize + 3 # echo size parameters to sizes file echo NumFiles $numFiles > $pkgSizes echo InstalledSize $installedSize >> $pkgSizes echo CompressedSize $compressedSize >> $pkgSizes echo done. echo " ... finished generating $pkg." exit(0) # end package
YifuLiu/AliOS-Things
components/SDL2/src/image/Xcode/package
Tcsh
apache-2.0
6,460
#!/bin/sh # Generic script to create a package with Project Builder in mind # There should only be one version of this script for all projects! FRAMEWORK="$1" VARIANT="$2" PACKAGE="$FRAMEWORK" PACKAGE_RESOURCES="pkg-support/resources" echo "Building package for $FRAMEWORK.framework" echo "Will fetch resources from $PACKAGE_RESOURCES" echo "Will create the package $PACKAGE.pkg" # create a copy of the framework mkdir -p build/pkg-tmp xcrun CpMac -r "build/$FRAMEWORK.framework" build/pkg-tmp/ ./package build/pkg-tmp "pkg-support/$PACKAGE.info" -d build -r "$PACKAGE_RESOURCES" # remove temporary files rm -rf build/pkg-tmp # compress (cd build; tar -zcvf "$PACKAGE.pkg.tar.gz" "$PACKAGE.pkg")
YifuLiu/AliOS-Things
components/SDL2/src/image/Xcode/pkg-support/mkpackage.sh
Shell
apache-2.0
707
/* SDLMain.m - main entry point for our Cocoa-ized SDL app Initial Version: Darrell Walisser <dwaliss1@purdue.edu> Non-NIB-Code & other changes: Max Horn <max@quendi.de> Feel free to customize this file to suit your needs */ #ifndef _SDLMain_h_ #define _SDLMain_h_ #import <Cocoa/Cocoa.h> @interface SDLMain : NSObject @end #endif /* _SDLMain_h_ */
YifuLiu/AliOS-Things
components/SDL2/src/image/Xcode/showimage/SDLMain.h
Objective-C
apache-2.0
374
/* SDLMain.m - main entry point for our Cocoa-ized SDL app Initial Version: Darrell Walisser <dwaliss1@purdue.edu> Non-NIB-Code & other changes: Max Horn <max@quendi.de> Feel free to customize this file to suit your needs */ #include <SDL/SDL.h> #include "SDLMain.h" #include <sys/param.h> /* for MAXPATHLEN */ #include <unistd.h> /* For some reaon, Apple removed setAppleMenu from the headers in 10.4, but the method still is there and works. To avoid warnings, we declare it ourselves here. */ @interface NSApplication(SDL_Missing_Methods) - (void)setAppleMenu:(NSMenu *)menu; @end /* Use this flag to determine whether we use SDLMain.nib or not */ #define SDL_USE_NIB_FILE 0 /* Use this flag to determine whether we use CPS (docking) or not */ #define SDL_USE_CPS 1 #ifdef SDL_USE_CPS /* Portions of CPS.h */ typedef struct CPSProcessSerNum { UInt32 lo; UInt32 hi; } CPSProcessSerNum; extern OSErr CPSGetCurrentProcess( CPSProcessSerNum *psn); extern OSErr CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5); extern OSErr CPSSetFrontProcess( CPSProcessSerNum *psn); #endif /* SDL_USE_CPS */ static int gArgc; static char **gArgv; static BOOL gFinderLaunch; static BOOL gCalledAppMainline = FALSE; static NSString *getApplicationName(void) { const NSDictionary *dict; NSString *appName = 0; /* Determine the application name */ dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle()); if (dict) appName = [dict objectForKey: @"CFBundleName"]; if (![appName length]) appName = [[NSProcessInfo processInfo] processName]; return appName; } #if SDL_USE_NIB_FILE /* A helper category for NSString */ @interface NSString (ReplaceSubString) - (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString; @end #endif @interface SDLApplication : NSApplication @end @implementation SDLApplication /* Invoked from the Quit menu item */ - (void)terminate:(id)sender { /* Post a SDL_QUIT event */ SDL_Event event; event.type = SDL_QUIT; SDL_PushEvent(&event); } @end /* The main class of the application, the application's delegate */ @implementation SDLMain /* Set the working directory to the .app's parent directory */ - (void) setupWorkingDirectory:(BOOL)shouldChdir { if (shouldChdir) { char parentdir[MAXPATHLEN]; CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url); if (CFURLGetFileSystemRepresentation(url2, 1, (UInt8 *)parentdir, MAXPATHLEN)) { chdir(parentdir); /* chdir to the binary app's parent */ } CFRelease(url); CFRelease(url2); } } #if SDL_USE_NIB_FILE /* Fix menu to contain the real app name instead of "SDL App" */ - (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName { NSRange aRange; NSEnumerator *enumerator; NSMenuItem *menuItem; aRange = [[aMenu title] rangeOfString:@"SDL App"]; if (aRange.length != 0) [aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]]; enumerator = [[aMenu itemArray] objectEnumerator]; while ((menuItem = [enumerator nextObject])) { aRange = [[menuItem title] rangeOfString:@"SDL App"]; if (aRange.length != 0) [menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]]; if ([menuItem hasSubmenu]) [self fixMenu:[menuItem submenu] withAppName:appName]; } [ aMenu sizeToFit ]; } #else static void setApplicationMenu(void) { /* warning: this code is very odd */ NSMenu *appleMenu; NSMenuItem *menuItem; NSString *title; NSString *appName; appName = getApplicationName(); appleMenu = [[NSMenu alloc] initWithTitle:@""]; /* Add menu items */ title = [@"About " stringByAppendingString:appName]; [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""]; [appleMenu addItem:[NSMenuItem separatorItem]]; title = [@"Hide " stringByAppendingString:appName]; [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"]; menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)]; [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; [appleMenu addItem:[NSMenuItem separatorItem]]; title = [@"Quit " stringByAppendingString:appName]; [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"]; /* Put menu into the menubar */ menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""]; [menuItem setSubmenu:appleMenu]; [[NSApp mainMenu] addItem:menuItem]; /* Tell the application object that this is now the application menu */ [NSApp setAppleMenu:appleMenu]; /* Finally give up our references to the objects */ [appleMenu release]; [menuItem release]; } /* Create a window menu */ static void setupWindowMenu(void) { NSMenu *windowMenu; NSMenuItem *windowMenuItem; NSMenuItem *menuItem; windowMenu = [[NSMenu alloc] initWithTitle:@"Window"]; /* "Minimize" item */ menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; [windowMenu addItem:menuItem]; [menuItem release]; /* Put menu into the menubar */ windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""]; [windowMenuItem setSubmenu:windowMenu]; [[NSApp mainMenu] addItem:windowMenuItem]; /* Tell the application object that this is now the window menu */ [NSApp setWindowsMenu:windowMenu]; /* Finally give up our references to the objects */ [windowMenu release]; [windowMenuItem release]; } /* Replacement for NSApplicationMain */ static void CustomApplicationMain (int argc, char **argv) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; SDLMain *sdlMain; /* Ensure the application object is initialised */ [SDLApplication sharedApplication]; #ifdef SDL_USE_CPS { CPSProcessSerNum PSN; /* Tell the dock about us */ if (!CPSGetCurrentProcess(&PSN)) if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103)) if (!CPSSetFrontProcess(&PSN)) [SDLApplication sharedApplication]; } #endif /* SDL_USE_CPS */ /* Set up the menubar */ [NSApp setMainMenu:[[NSMenu alloc] init]]; setApplicationMenu(); setupWindowMenu(); /* Create SDLMain and make it the app delegate */ sdlMain = [[SDLMain alloc] init]; [NSApp setDelegate:sdlMain]; /* Start the main event loop */ [NSApp run]; [sdlMain release]; [pool release]; } #endif /* * Catch document open requests...this lets us notice files when the app * was launched by double-clicking a document, or when a document was * dragged/dropped on the app's icon. You need to have a * CFBundleDocumentsType section in your Info.plist to get this message, * apparently. * * Files are added to gArgv, so to the app, they'll look like command line * arguments. Previously, apps launched from the finder had nothing but * an argv[0]. * * This message may be received multiple times to open several docs on launch. * * This message is ignored once the app's mainline has been called. */ - (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename { const char *temparg; size_t arglen; char *arg; char **newargv; if (!gFinderLaunch) /* MacOS is passing command line args. */ return FALSE; if (gCalledAppMainline) /* app has started, ignore this document. */ return FALSE; temparg = [filename UTF8String]; arglen = SDL_strlen(temparg) + 1; arg = (char *) SDL_malloc(arglen); if (arg == NULL) return FALSE; newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2)); if (newargv == NULL) { SDL_free(arg); return FALSE; } gArgv = newargv; SDL_strlcpy(arg, temparg, arglen); gArgv[gArgc++] = arg; gArgv[gArgc] = NULL; return TRUE; } /* Called when the internal event loop has just started running */ - (void) applicationDidFinishLaunching: (NSNotification *) note { int status; /* Set the working directory to the .app's parent directory */ [self setupWorkingDirectory:gFinderLaunch]; #if SDL_USE_NIB_FILE /* Set the main menu to contain the real app name instead of "SDL App" */ [self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()]; #endif /* Hand off to main application code */ gCalledAppMainline = TRUE; status = SDL_main (gArgc, gArgv); /* We're done, thank you for playing */ exit(status); } @end @implementation NSString (ReplaceSubString) - (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString { unsigned int bufferSize; unsigned int selfLen = [self length]; unsigned int aStringLen = [aString length]; unichar *buffer; NSRange localRange; NSString *result; bufferSize = selfLen + aStringLen - aRange.length; buffer = (unichar *)NSAllocateMemoryPages(bufferSize*sizeof(unichar)); /* Get first part into buffer */ localRange.location = 0; localRange.length = aRange.location; [self getCharacters:buffer range:localRange]; /* Get middle part into buffer */ localRange.location = 0; localRange.length = aStringLen; [aString getCharacters:(buffer+aRange.location) range:localRange]; /* Get last part into buffer */ localRange.location = aRange.location + aRange.length; localRange.length = selfLen - localRange.location; [self getCharacters:(buffer+aRange.location+aStringLen) range:localRange]; /* Build output string */ result = [NSString stringWithCharacters:buffer length:bufferSize]; NSDeallocateMemoryPages(buffer, bufferSize); return result; } @end #ifdef main # undef main #endif /* Main entry point to executable - should *not* be SDL_main! */ int main (int argc, char **argv) { /* Copy the arguments into a global variable */ /* This is passed if we are launched by double-clicking */ if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) { gArgv = (char **) SDL_malloc(sizeof (char *) * 2); gArgv[0] = argv[0]; gArgv[1] = NULL; gArgc = 1; gFinderLaunch = YES; } else { int i; gArgc = argc; gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1)); for (i = 0; i <= argc; i++) gArgv[i] = argv[i]; gFinderLaunch = NO; } #if SDL_USE_NIB_FILE [SDLApplication poseAsClass:[NSApplication class]]; NSApplicationMain (argc, argv); #else CustomApplicationMain (argc, argv); #endif return 0; }
YifuLiu/AliOS-Things
components/SDL2/src/image/Xcode/showimage/SDLMain.m
Objective-C
apache-2.0
11,248
# pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*- # # Copyright © 2004 Scott James Remnant <scott@netsplit.com>. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # PKG_PROG_PKG_CONFIG([MIN-VERSION]) # ---------------------------------- AC_DEFUN([PKG_PROG_PKG_CONFIG], [m4_pattern_forbid([^_?PKG_[A-Z_]+$]) m4_pattern_allow([^PKG_CONFIG(_PATH)?$]) AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])dnl if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then AC_PATH_TOOL([PKG_CONFIG], [pkg-config]) fi if test -n "$PKG_CONFIG"; then _pkg_min_version=m4_default([$1], [0.9.0]) AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version]) if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) PKG_CONFIG="" fi fi[]dnl ])# PKG_PROG_PKG_CONFIG # PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]) # # Check to see whether a particular set of modules exists. Similar # to PKG_CHECK_MODULES(), but does not set variables or print errors. # # # Similar to PKG_CHECK_MODULES, make sure that the first instance of # this or PKG_CHECK_MODULES is called, or make sure to call # PKG_CHECK_EXISTS manually # -------------------------------------------------------------- AC_DEFUN([PKG_CHECK_EXISTS], [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl if test -n "$PKG_CONFIG" && \ AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then m4_ifval([$2], [$2], [:]) m4_ifvaln([$3], [else $3])dnl fi]) # _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES]) # --------------------------------------------- m4_define([_PKG_CONFIG], [if test -n "$PKG_CONFIG"; then if test -n "$$1"; then pkg_cv_[]$1="$$1" else PKG_CHECK_EXISTS([$3], [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`], [pkg_failed=yes]) fi else pkg_failed=untried fi[]dnl ])# _PKG_CONFIG # _PKG_SHORT_ERRORS_SUPPORTED # ----------------------------- AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED], [AC_REQUIRE([PKG_PROG_PKG_CONFIG]) if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi[]dnl ])# _PKG_SHORT_ERRORS_SUPPORTED # PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND], # [ACTION-IF-NOT-FOUND]) # # # Note that if there is a possibility the first call to # PKG_CHECK_MODULES might not happen, you should be sure to include an # explicit call to PKG_PROG_PKG_CONFIG in your configure.ac # # # -------------------------------------------------------------- AC_DEFUN([PKG_CHECK_MODULES], [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl pkg_failed=no AC_MSG_CHECKING([for $1]) _PKG_CONFIG([$1][_CFLAGS], [cflags], [$2]) _PKG_CONFIG([$1][_LIBS], [libs], [$2]) m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS and $1[]_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details.]) if test $pkg_failed = yes; then _PKG_SHORT_ERRORS_SUPPORTED if test $_pkg_short_errors_supported = yes; then $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --errors-to-stdout --print-errors "$2"` else $1[]_PKG_ERRORS=`$PKG_CONFIG --errors-to-stdout --print-errors "$2"` fi # Put the nasty error message in config.log where it belongs echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD ifelse([$4], , [AC_MSG_ERROR(dnl [Package requirements ($2) were not met: $$1_PKG_ERRORS Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix. _PKG_TEXT ])], [AC_MSG_RESULT([no]) $4]) elif test $pkg_failed = untried; then ifelse([$4], , [AC_MSG_FAILURE(dnl [The pkg-config script could not be found or is too old. Make sure it is in your PATH or set the PKG_CONFIG environment variable to the full path to pkg-config. _PKG_TEXT To get pkg-config, see <http://pkg-config.freedesktop.org/>.])], [$4]) else $1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS $1[]_LIBS=$pkg_cv_[]$1[]_LIBS AC_MSG_RESULT([yes]) ifelse([$3], , :, [$3]) fi[]dnl ])# PKG_CHECK_MODULES
YifuLiu/AliOS-Things
components/SDL2/src/image/acinclude/pkg.m4
M4Sugar
apache-2.0
5,221
# Configure paths for SDL # Sam Lantinga 9/21/99 # stolen from Manish Singh # stolen back from Frank Belew # stolen from Manish Singh # Shamelessly stolen from Owen Taylor # serial 1 dnl AM_PATH_SDL2([MINIMUM-VERSION, [ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]]) dnl Test for SDL, and define SDL_CFLAGS and SDL_LIBS dnl AC_DEFUN([AM_PATH_SDL2], [dnl dnl Get the cflags and libraries from the sdl2-config script dnl AC_ARG_WITH(sdl-prefix,[ --with-sdl-prefix=PFX Prefix where SDL is installed (optional)], sdl_prefix="$withval", sdl_prefix="") AC_ARG_WITH(sdl-exec-prefix,[ --with-sdl-exec-prefix=PFX Exec prefix where SDL is installed (optional)], sdl_exec_prefix="$withval", sdl_exec_prefix="") AC_ARG_ENABLE(sdltest, [ --disable-sdltest Do not try to compile and run a test SDL program], , enable_sdltest=yes) min_sdl_version=ifelse([$1], ,2.0.0,$1) if test "x$sdl_prefix$sdl_exec_prefix" = x ; then PKG_CHECK_MODULES([SDL], [sdl2 >= $min_sdl_version], [sdl_pc=yes], [sdl_pc=no]) else sdl_pc=no if test x$sdl_exec_prefix != x ; then sdl_config_args="$sdl_config_args --exec-prefix=$sdl_exec_prefix" if test x${SDL2_CONFIG+set} != xset ; then SDL2_CONFIG=$sdl_exec_prefix/bin/sdl2-config fi fi if test x$sdl_prefix != x ; then sdl_config_args="$sdl_config_args --prefix=$sdl_prefix" if test x${SDL2_CONFIG+set} != xset ; then SDL2_CONFIG=$sdl_prefix/bin/sdl2-config fi fi fi if test "x$sdl_pc" = xyes ; then no_sdl="" SDL2_CONFIG="pkg-config sdl2" else as_save_PATH="$PATH" if test "x$prefix" != xNONE && test "$cross_compiling" != yes; then PATH="$prefix/bin:$prefix/usr/bin:$PATH" fi AC_PATH_PROG(SDL2_CONFIG, sdl2-config, no, [$PATH]) PATH="$as_save_PATH" AC_MSG_CHECKING(for SDL - version >= $min_sdl_version) no_sdl="" if test "$SDL2_CONFIG" = "no" ; then no_sdl=yes else SDL_CFLAGS=`$SDL2_CONFIG $sdl_config_args --cflags` SDL_LIBS=`$SDL2_CONFIG $sdl_config_args --libs` sdl_major_version=`$SDL2_CONFIG $sdl_config_args --version | \ sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'` sdl_minor_version=`$SDL2_CONFIG $sdl_config_args --version | \ sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'` sdl_micro_version=`$SDL2_CONFIG $sdl_config_args --version | \ sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'` if test "x$enable_sdltest" = "xyes" ; then ac_save_CFLAGS="$CFLAGS" ac_save_CXXFLAGS="$CXXFLAGS" ac_save_LIBS="$LIBS" CFLAGS="$CFLAGS $SDL_CFLAGS" CXXFLAGS="$CXXFLAGS $SDL_CFLAGS" LIBS="$LIBS $SDL_LIBS" dnl dnl Now check if the installed SDL is sufficiently new. (Also sanity dnl checks the results of sdl2-config to some extent dnl rm -f conf.sdltest AC_TRY_RUN([ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "SDL.h" char* my_strdup (char *str) { char *new_str; if (str) { new_str = (char *)malloc ((strlen (str) + 1) * sizeof(char)); strcpy (new_str, str); } else new_str = NULL; return new_str; } int main (int argc, char *argv[]) { int major, minor, micro; char *tmp_version; /* This hangs on some systems (?) system ("touch conf.sdltest"); */ { FILE *fp = fopen("conf.sdltest", "a"); if ( fp ) fclose(fp); } /* HP/UX 9 (%@#!) writes to sscanf strings */ tmp_version = my_strdup("$min_sdl_version"); if (sscanf(tmp_version, "%d.%d.%d", &major, &minor, &micro) != 3) { printf("%s, bad version string\n", "$min_sdl_version"); exit(1); } if (($sdl_major_version > major) || (($sdl_major_version == major) && ($sdl_minor_version > minor)) || (($sdl_major_version == major) && ($sdl_minor_version == minor) && ($sdl_micro_version >= micro))) { return 0; } else { printf("\n*** 'sdl2-config --version' returned %d.%d.%d, but the minimum version\n", $sdl_major_version, $sdl_minor_version, $sdl_micro_version); printf("*** of SDL required is %d.%d.%d. If sdl2-config is correct, then it is\n", major, minor, micro); printf("*** best to upgrade to the required version.\n"); printf("*** If sdl2-config was wrong, set the environment variable SDL2_CONFIG\n"); printf("*** to point to the correct copy of sdl2-config, and remove the file\n"); printf("*** config.cache before re-running configure\n"); return 1; } } ],, no_sdl=yes,[echo $ac_n "cross compiling; assumed OK... $ac_c"]) CFLAGS="$ac_save_CFLAGS" CXXFLAGS="$ac_save_CXXFLAGS" LIBS="$ac_save_LIBS" fi fi if test "x$no_sdl" = x ; then AC_MSG_RESULT(yes) else AC_MSG_RESULT(no) fi fi if test "x$no_sdl" = x ; then ifelse([$2], , :, [$2]) else if test "$SDL2_CONFIG" = "no" ; then echo "*** The sdl2-config script installed by SDL could not be found" echo "*** If SDL was installed in PREFIX, make sure PREFIX/bin is in" echo "*** your path, or set the SDL2_CONFIG environment variable to the" echo "*** full path to sdl2-config." else if test -f conf.sdltest ; then : else echo "*** Could not run SDL test program, checking why..." CFLAGS="$CFLAGS $SDL_CFLAGS" CXXFLAGS="$CXXFLAGS $SDL_CFLAGS" LIBS="$LIBS $SDL_LIBS" AC_TRY_LINK([ #include <stdio.h> #include "SDL.h" int main(int argc, char *argv[]) { return 0; } #undef main #define main K_and_R_C_main ], [ return 0; ], [ echo "*** The test program compiled, but did not run. This usually means" echo "*** that the run-time linker is not finding SDL or finding the wrong" echo "*** version of SDL. If it is not finding SDL, you'll need to set your" echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point" echo "*** to the installed location Also, make sure you have run ldconfig if that" echo "*** is required on your system" echo "***" echo "*** If you have an old version installed, it is best to remove it, although" echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH"], [ echo "*** The test program failed to compile or link. See the file config.log for the" echo "*** exact error that occured. This usually means SDL was incorrectly installed" echo "*** or that you have moved SDL since it was installed. In the latter case, you" echo "*** may want to edit the sdl2-config script: $SDL2_CONFIG" ]) CFLAGS="$ac_save_CFLAGS" CXXFLAGS="$ac_save_CXXFLAGS" LIBS="$ac_save_LIBS" fi fi SDL_CFLAGS="" SDL_LIBS="" ifelse([$3], , :, [$3]) fi AC_SUBST(SDL_CFLAGS) AC_SUBST(SDL_LIBS) rm -f conf.sdltest ])
YifuLiu/AliOS-Things
components/SDL2/src/image/acinclude/sdl2.m4
M4Sugar
apache-2.0
6,982
#!/bin/sh # aclocal -I acinclude automake --foreign --include-deps --add-missing --copy autoconf #./configure $* echo "Now you are ready to run ./configure"
YifuLiu/AliOS-Things
components/SDL2/src/image/autogen.sh
Shell
apache-2.0
158
m4trace:aclocal.m4:1253: -1- m4_include([acinclude/libtool.m4]) m4trace:aclocal.m4:1254: -1- m4_include([acinclude/ltoptions.m4]) m4trace:aclocal.m4:1255: -1- m4_include([acinclude/ltsugar.m4]) m4trace:aclocal.m4:1256: -1- m4_include([acinclude/ltversion.m4]) m4trace:aclocal.m4:1257: -1- m4_include([acinclude/lt~obsolete.m4]) m4trace:aclocal.m4:1258: -1- m4_include([acinclude/pkg.m4]) m4trace:aclocal.m4:1259: -1- m4_include([acinclude/sdl2.m4]) m4trace:configure.in:2: -1- AC_INIT([README.txt]) m4trace:configure.in:2: -1- m4_pattern_forbid([^_?A[CHUM]_]) m4trace:configure.in:2: -1- m4_pattern_forbid([_AC_]) m4trace:configure.in:2: -1- m4_pattern_forbid([^LIBOBJS$], [do not use LIBOBJS directly, use AC_LIBOBJ (see section `AC_LIBOBJ vs LIBOBJS']) m4trace:configure.in:2: -1- m4_pattern_allow([^AS_FLAGS$]) m4trace:configure.in:2: -1- m4_pattern_forbid([^_?m4_]) m4trace:configure.in:2: -1- m4_pattern_forbid([^dnl$]) m4trace:configure.in:2: -1- m4_pattern_forbid([^_?AS_]) m4trace:configure.in:2: -1- AC_SUBST([SHELL]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([SHELL]) m4trace:configure.in:2: -1- m4_pattern_allow([^SHELL$]) m4trace:configure.in:2: -1- AC_SUBST([PATH_SEPARATOR]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([PATH_SEPARATOR]) m4trace:configure.in:2: -1- m4_pattern_allow([^PATH_SEPARATOR$]) m4trace:configure.in:2: -1- AC_SUBST([PACKAGE_NAME], [m4_ifdef([AC_PACKAGE_NAME], ['AC_PACKAGE_NAME'])]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([PACKAGE_NAME]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_NAME$]) m4trace:configure.in:2: -1- AC_SUBST([PACKAGE_TARNAME], [m4_ifdef([AC_PACKAGE_TARNAME], ['AC_PACKAGE_TARNAME'])]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([PACKAGE_TARNAME]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_TARNAME$]) m4trace:configure.in:2: -1- AC_SUBST([PACKAGE_VERSION], [m4_ifdef([AC_PACKAGE_VERSION], ['AC_PACKAGE_VERSION'])]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([PACKAGE_VERSION]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_VERSION$]) m4trace:configure.in:2: -1- AC_SUBST([PACKAGE_STRING], [m4_ifdef([AC_PACKAGE_STRING], ['AC_PACKAGE_STRING'])]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([PACKAGE_STRING]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_STRING$]) m4trace:configure.in:2: -1- AC_SUBST([PACKAGE_BUGREPORT], [m4_ifdef([AC_PACKAGE_BUGREPORT], ['AC_PACKAGE_BUGREPORT'])]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([PACKAGE_BUGREPORT]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_BUGREPORT$]) m4trace:configure.in:2: -1- AC_SUBST([PACKAGE_URL], [m4_ifdef([AC_PACKAGE_URL], ['AC_PACKAGE_URL'])]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([PACKAGE_URL]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_URL$]) m4trace:configure.in:2: -1- AC_SUBST([exec_prefix], [NONE]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([exec_prefix]) m4trace:configure.in:2: -1- m4_pattern_allow([^exec_prefix$]) m4trace:configure.in:2: -1- AC_SUBST([prefix], [NONE]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([prefix]) m4trace:configure.in:2: -1- m4_pattern_allow([^prefix$]) m4trace:configure.in:2: -1- AC_SUBST([program_transform_name], [s,x,x,]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([program_transform_name]) m4trace:configure.in:2: -1- m4_pattern_allow([^program_transform_name$]) m4trace:configure.in:2: -1- AC_SUBST([bindir], ['${exec_prefix}/bin']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([bindir]) m4trace:configure.in:2: -1- m4_pattern_allow([^bindir$]) m4trace:configure.in:2: -1- AC_SUBST([sbindir], ['${exec_prefix}/sbin']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([sbindir]) m4trace:configure.in:2: -1- m4_pattern_allow([^sbindir$]) m4trace:configure.in:2: -1- AC_SUBST([libexecdir], ['${exec_prefix}/libexec']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([libexecdir]) m4trace:configure.in:2: -1- m4_pattern_allow([^libexecdir$]) m4trace:configure.in:2: -1- AC_SUBST([datarootdir], ['${prefix}/share']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([datarootdir]) m4trace:configure.in:2: -1- m4_pattern_allow([^datarootdir$]) m4trace:configure.in:2: -1- AC_SUBST([datadir], ['${datarootdir}']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([datadir]) m4trace:configure.in:2: -1- m4_pattern_allow([^datadir$]) m4trace:configure.in:2: -1- AC_SUBST([sysconfdir], ['${prefix}/etc']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([sysconfdir]) m4trace:configure.in:2: -1- m4_pattern_allow([^sysconfdir$]) m4trace:configure.in:2: -1- AC_SUBST([sharedstatedir], ['${prefix}/com']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([sharedstatedir]) m4trace:configure.in:2: -1- m4_pattern_allow([^sharedstatedir$]) m4trace:configure.in:2: -1- AC_SUBST([localstatedir], ['${prefix}/var']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([localstatedir]) m4trace:configure.in:2: -1- m4_pattern_allow([^localstatedir$]) m4trace:configure.in:2: -1- AC_SUBST([runstatedir], ['${localstatedir}/run']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([runstatedir]) m4trace:configure.in:2: -1- m4_pattern_allow([^runstatedir$]) m4trace:configure.in:2: -1- AC_SUBST([includedir], ['${prefix}/include']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([includedir]) m4trace:configure.in:2: -1- m4_pattern_allow([^includedir$]) m4trace:configure.in:2: -1- AC_SUBST([oldincludedir], ['/usr/include']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([oldincludedir]) m4trace:configure.in:2: -1- m4_pattern_allow([^oldincludedir$]) m4trace:configure.in:2: -1- AC_SUBST([docdir], [m4_ifset([AC_PACKAGE_TARNAME], ['${datarootdir}/doc/${PACKAGE_TARNAME}'], ['${datarootdir}/doc/${PACKAGE}'])]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([docdir]) m4trace:configure.in:2: -1- m4_pattern_allow([^docdir$]) m4trace:configure.in:2: -1- AC_SUBST([infodir], ['${datarootdir}/info']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([infodir]) m4trace:configure.in:2: -1- m4_pattern_allow([^infodir$]) m4trace:configure.in:2: -1- AC_SUBST([htmldir], ['${docdir}']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([htmldir]) m4trace:configure.in:2: -1- m4_pattern_allow([^htmldir$]) m4trace:configure.in:2: -1- AC_SUBST([dvidir], ['${docdir}']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([dvidir]) m4trace:configure.in:2: -1- m4_pattern_allow([^dvidir$]) m4trace:configure.in:2: -1- AC_SUBST([pdfdir], ['${docdir}']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([pdfdir]) m4trace:configure.in:2: -1- m4_pattern_allow([^pdfdir$]) m4trace:configure.in:2: -1- AC_SUBST([psdir], ['${docdir}']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([psdir]) m4trace:configure.in:2: -1- m4_pattern_allow([^psdir$]) m4trace:configure.in:2: -1- AC_SUBST([libdir], ['${exec_prefix}/lib']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([libdir]) m4trace:configure.in:2: -1- m4_pattern_allow([^libdir$]) m4trace:configure.in:2: -1- AC_SUBST([localedir], ['${datarootdir}/locale']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([localedir]) m4trace:configure.in:2: -1- m4_pattern_allow([^localedir$]) m4trace:configure.in:2: -1- AC_SUBST([mandir], ['${datarootdir}/man']) m4trace:configure.in:2: -1- AC_SUBST_TRACE([mandir]) m4trace:configure.in:2: -1- m4_pattern_allow([^mandir$]) m4trace:configure.in:2: -1- AC_DEFINE_TRACE_LITERAL([PACKAGE_NAME]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_NAME$]) m4trace:configure.in:2: -1- AH_OUTPUT([PACKAGE_NAME], [/* Define to the full name of this package. */ @%:@undef PACKAGE_NAME]) m4trace:configure.in:2: -1- AC_DEFINE_TRACE_LITERAL([PACKAGE_TARNAME]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_TARNAME$]) m4trace:configure.in:2: -1- AH_OUTPUT([PACKAGE_TARNAME], [/* Define to the one symbol short name of this package. */ @%:@undef PACKAGE_TARNAME]) m4trace:configure.in:2: -1- AC_DEFINE_TRACE_LITERAL([PACKAGE_VERSION]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_VERSION$]) m4trace:configure.in:2: -1- AH_OUTPUT([PACKAGE_VERSION], [/* Define to the version of this package. */ @%:@undef PACKAGE_VERSION]) m4trace:configure.in:2: -1- AC_DEFINE_TRACE_LITERAL([PACKAGE_STRING]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_STRING$]) m4trace:configure.in:2: -1- AH_OUTPUT([PACKAGE_STRING], [/* Define to the full name and version of this package. */ @%:@undef PACKAGE_STRING]) m4trace:configure.in:2: -1- AC_DEFINE_TRACE_LITERAL([PACKAGE_BUGREPORT]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_BUGREPORT$]) m4trace:configure.in:2: -1- AH_OUTPUT([PACKAGE_BUGREPORT], [/* Define to the address where bug reports for this package should be sent. */ @%:@undef PACKAGE_BUGREPORT]) m4trace:configure.in:2: -1- AC_DEFINE_TRACE_LITERAL([PACKAGE_URL]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_URL$]) m4trace:configure.in:2: -1- AH_OUTPUT([PACKAGE_URL], [/* Define to the home page for this package. */ @%:@undef PACKAGE_URL]) m4trace:configure.in:2: -1- AC_SUBST([DEFS]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([DEFS]) m4trace:configure.in:2: -1- m4_pattern_allow([^DEFS$]) m4trace:configure.in:2: -1- AC_SUBST([ECHO_C]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([ECHO_C]) m4trace:configure.in:2: -1- m4_pattern_allow([^ECHO_C$]) m4trace:configure.in:2: -1- AC_SUBST([ECHO_N]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([ECHO_N]) m4trace:configure.in:2: -1- m4_pattern_allow([^ECHO_N$]) m4trace:configure.in:2: -1- AC_SUBST([ECHO_T]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([ECHO_T]) m4trace:configure.in:2: -1- m4_pattern_allow([^ECHO_T$]) m4trace:configure.in:2: -1- AC_SUBST([LIBS]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([LIBS]) m4trace:configure.in:2: -1- m4_pattern_allow([^LIBS$]) m4trace:configure.in:2: -1- AC_SUBST([build_alias]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([build_alias]) m4trace:configure.in:2: -1- m4_pattern_allow([^build_alias$]) m4trace:configure.in:2: -1- AC_SUBST([host_alias]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([host_alias]) m4trace:configure.in:2: -1- m4_pattern_allow([^host_alias$]) m4trace:configure.in:2: -1- AC_SUBST([target_alias]) m4trace:configure.in:2: -1- AC_SUBST_TRACE([target_alias]) m4trace:configure.in:2: -1- m4_pattern_allow([^target_alias$]) m4trace:configure.in:21: -1- AC_SUBST([MAJOR_VERSION]) m4trace:configure.in:21: -1- AC_SUBST_TRACE([MAJOR_VERSION]) m4trace:configure.in:21: -1- m4_pattern_allow([^MAJOR_VERSION$]) m4trace:configure.in:22: -1- AC_SUBST([MINOR_VERSION]) m4trace:configure.in:22: -1- AC_SUBST_TRACE([MINOR_VERSION]) m4trace:configure.in:22: -1- m4_pattern_allow([^MINOR_VERSION$]) m4trace:configure.in:23: -1- AC_SUBST([MICRO_VERSION]) m4trace:configure.in:23: -1- AC_SUBST_TRACE([MICRO_VERSION]) m4trace:configure.in:23: -1- m4_pattern_allow([^MICRO_VERSION$]) m4trace:configure.in:24: -1- AC_SUBST([INTERFACE_AGE]) m4trace:configure.in:24: -1- AC_SUBST_TRACE([INTERFACE_AGE]) m4trace:configure.in:24: -1- m4_pattern_allow([^INTERFACE_AGE$]) m4trace:configure.in:25: -1- AC_SUBST([BINARY_AGE]) m4trace:configure.in:25: -1- AC_SUBST_TRACE([BINARY_AGE]) m4trace:configure.in:25: -1- m4_pattern_allow([^BINARY_AGE$]) m4trace:configure.in:26: -1- AC_SUBST([VERSION]) m4trace:configure.in:26: -1- AC_SUBST_TRACE([VERSION]) m4trace:configure.in:26: -1- m4_pattern_allow([^VERSION$]) m4trace:configure.in:29: -1- LT_INIT([win32-dll]) m4trace:configure.in:29: -1- m4_pattern_forbid([^_?LT_[A-Z_]+$]) m4trace:configure.in:29: -1- m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$]) m4trace:configure.in:29: -1- AC_REQUIRE_AUX_FILE([ltmain.sh]) m4trace:configure.in:29: -1- AC_SUBST([AS]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([AS]) m4trace:configure.in:29: -1- m4_pattern_allow([^AS$]) m4trace:configure.in:29: -1- AC_SUBST([DLLTOOL]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([DLLTOOL]) m4trace:configure.in:29: -1- m4_pattern_allow([^DLLTOOL$]) m4trace:configure.in:29: -1- AC_SUBST([OBJDUMP]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([OBJDUMP]) m4trace:configure.in:29: -1- m4_pattern_allow([^OBJDUMP$]) m4trace:configure.in:29: -1- AC_SUBST([LIBTOOL]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([LIBTOOL]) m4trace:configure.in:29: -1- m4_pattern_allow([^LIBTOOL$]) m4trace:configure.in:29: -1- AC_CANONICAL_HOST m4trace:configure.in:29: -1- AC_CANONICAL_BUILD m4trace:configure.in:29: -1- AC_REQUIRE_AUX_FILE([config.sub]) m4trace:configure.in:29: -1- AC_REQUIRE_AUX_FILE([config.guess]) m4trace:configure.in:29: -1- AC_SUBST([build], [$ac_cv_build]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([build]) m4trace:configure.in:29: -1- m4_pattern_allow([^build$]) m4trace:configure.in:29: -1- AC_SUBST([build_cpu], [$[1]]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([build_cpu]) m4trace:configure.in:29: -1- m4_pattern_allow([^build_cpu$]) m4trace:configure.in:29: -1- AC_SUBST([build_vendor], [$[2]]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([build_vendor]) m4trace:configure.in:29: -1- m4_pattern_allow([^build_vendor$]) m4trace:configure.in:29: -1- AC_SUBST([build_os]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([build_os]) m4trace:configure.in:29: -1- m4_pattern_allow([^build_os$]) m4trace:configure.in:29: -1- AC_SUBST([host], [$ac_cv_host]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([host]) m4trace:configure.in:29: -1- m4_pattern_allow([^host$]) m4trace:configure.in:29: -1- AC_SUBST([host_cpu], [$[1]]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([host_cpu]) m4trace:configure.in:29: -1- m4_pattern_allow([^host_cpu$]) m4trace:configure.in:29: -1- AC_SUBST([host_vendor], [$[2]]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([host_vendor]) m4trace:configure.in:29: -1- m4_pattern_allow([^host_vendor$]) m4trace:configure.in:29: -1- AC_SUBST([host_os]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([host_os]) m4trace:configure.in:29: -1- m4_pattern_allow([^host_os$]) m4trace:configure.in:29: -1- AC_SUBST([CC]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([CC]) m4trace:configure.in:29: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:29: -1- AC_SUBST([CFLAGS]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([CFLAGS]) m4trace:configure.in:29: -1- m4_pattern_allow([^CFLAGS$]) m4trace:configure.in:29: -1- AC_SUBST([LDFLAGS]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([LDFLAGS]) m4trace:configure.in:29: -1- m4_pattern_allow([^LDFLAGS$]) m4trace:configure.in:29: -1- AC_SUBST([LIBS]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([LIBS]) m4trace:configure.in:29: -1- m4_pattern_allow([^LIBS$]) m4trace:configure.in:29: -1- AC_SUBST([CPPFLAGS]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([CPPFLAGS]) m4trace:configure.in:29: -1- m4_pattern_allow([^CPPFLAGS$]) m4trace:configure.in:29: -1- AC_SUBST([CC]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([CC]) m4trace:configure.in:29: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:29: -1- AC_SUBST([CC]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([CC]) m4trace:configure.in:29: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:29: -1- AC_SUBST([CC]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([CC]) m4trace:configure.in:29: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:29: -1- AC_SUBST([CC]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([CC]) m4trace:configure.in:29: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:29: -1- AC_SUBST([ac_ct_CC]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([ac_ct_CC]) m4trace:configure.in:29: -1- m4_pattern_allow([^ac_ct_CC$]) m4trace:configure.in:29: -1- AC_SUBST([EXEEXT], [$ac_cv_exeext]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([EXEEXT]) m4trace:configure.in:29: -1- m4_pattern_allow([^EXEEXT$]) m4trace:configure.in:29: -1- AC_SUBST([OBJEXT], [$ac_cv_objext]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([OBJEXT]) m4trace:configure.in:29: -1- m4_pattern_allow([^OBJEXT$]) m4trace:configure.in:29: -1- AC_REQUIRE_AUX_FILE([compile]) m4trace:configure.in:29: -1- AC_SUBST([SED]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([SED]) m4trace:configure.in:29: -1- m4_pattern_allow([^SED$]) m4trace:configure.in:29: -1- AC_SUBST([GREP]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([GREP]) m4trace:configure.in:29: -1- m4_pattern_allow([^GREP$]) m4trace:configure.in:29: -1- AC_SUBST([EGREP]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([EGREP]) m4trace:configure.in:29: -1- m4_pattern_allow([^EGREP$]) m4trace:configure.in:29: -1- AC_SUBST([FGREP]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([FGREP]) m4trace:configure.in:29: -1- m4_pattern_allow([^FGREP$]) m4trace:configure.in:29: -1- AC_SUBST([GREP]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([GREP]) m4trace:configure.in:29: -1- m4_pattern_allow([^GREP$]) m4trace:configure.in:29: -1- AC_SUBST([LD]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([LD]) m4trace:configure.in:29: -1- m4_pattern_allow([^LD$]) m4trace:configure.in:29: -1- AC_SUBST([DUMPBIN]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([DUMPBIN]) m4trace:configure.in:29: -1- m4_pattern_allow([^DUMPBIN$]) m4trace:configure.in:29: -1- AC_SUBST([ac_ct_DUMPBIN]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([ac_ct_DUMPBIN]) m4trace:configure.in:29: -1- m4_pattern_allow([^ac_ct_DUMPBIN$]) m4trace:configure.in:29: -1- AC_SUBST([DUMPBIN]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([DUMPBIN]) m4trace:configure.in:29: -1- m4_pattern_allow([^DUMPBIN$]) m4trace:configure.in:29: -1- AC_SUBST([NM]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([NM]) m4trace:configure.in:29: -1- m4_pattern_allow([^NM$]) m4trace:configure.in:29: -1- AC_SUBST([LN_S], [$as_ln_s]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([LN_S]) m4trace:configure.in:29: -1- m4_pattern_allow([^LN_S$]) m4trace:configure.in:29: -1- AC_SUBST([OBJDUMP]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([OBJDUMP]) m4trace:configure.in:29: -1- m4_pattern_allow([^OBJDUMP$]) m4trace:configure.in:29: -1- AC_SUBST([OBJDUMP]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([OBJDUMP]) m4trace:configure.in:29: -1- m4_pattern_allow([^OBJDUMP$]) m4trace:configure.in:29: -1- AC_SUBST([AR]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([AR]) m4trace:configure.in:29: -1- m4_pattern_allow([^AR$]) m4trace:configure.in:29: -1- AC_SUBST([STRIP]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([STRIP]) m4trace:configure.in:29: -1- m4_pattern_allow([^STRIP$]) m4trace:configure.in:29: -1- AC_SUBST([RANLIB]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([RANLIB]) m4trace:configure.in:29: -1- m4_pattern_allow([^RANLIB$]) m4trace:configure.in:29: -1- m4_pattern_allow([LT_OBJDIR]) m4trace:configure.in:29: -1- AC_DEFINE_TRACE_LITERAL([LT_OBJDIR]) m4trace:configure.in:29: -1- m4_pattern_allow([^LT_OBJDIR$]) m4trace:configure.in:29: -1- AH_OUTPUT([LT_OBJDIR], [/* Define to the sub-directory in which libtool stores uninstalled libraries. */ @%:@undef LT_OBJDIR]) m4trace:configure.in:29: -1- AC_SUBST([lt_ECHO]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([lt_ECHO]) m4trace:configure.in:29: -1- m4_pattern_allow([^lt_ECHO$]) m4trace:configure.in:29: -1- LT_SUPPORTED_TAG([CC]) m4trace:configure.in:29: -1- _m4_warn([syntax], [AC_LANG_CONFTEST: no AC_LANG_SOURCE call detected in body], [../../lib/autoconf/lang.m4:193: AC_LANG_CONFTEST is expanded from... ../../lib/autoconf/general.m4:2672: _AC_LINK_IFELSE is expanded from... ../../lib/autoconf/general.m4:2689: AC_LINK_IFELSE is expanded from... acinclude/libtool.m4:1024: _LT_SYS_MODULE_PATH_AIX is expanded from... acinclude/libtool.m4:4173: _LT_LINKER_SHLIBS is expanded from... acinclude/libtool.m4:5248: _LT_LANG_C_CONFIG is expanded from... acinclude/libtool.m4:140: _LT_SETUP is expanded from... acinclude/libtool.m4:69: LT_INIT is expanded from... configure.in:29: the top level]) m4trace:configure.in:29: -1- _m4_warn([syntax], [AC_LANG_CONFTEST: no AC_LANG_SOURCE call detected in body], [../../lib/autoconf/lang.m4:193: AC_LANG_CONFTEST is expanded from... ../../lib/autoconf/general.m4:2672: _AC_LINK_IFELSE is expanded from... ../../lib/autoconf/general.m4:2689: AC_LINK_IFELSE is expanded from... acinclude/libtool.m4:1024: _LT_SYS_MODULE_PATH_AIX is expanded from... acinclude/libtool.m4:4173: _LT_LINKER_SHLIBS is expanded from... acinclude/libtool.m4:5248: _LT_LANG_C_CONFIG is expanded from... acinclude/libtool.m4:140: _LT_SETUP is expanded from... acinclude/libtool.m4:69: LT_INIT is expanded from... configure.in:29: the top level]) m4trace:configure.in:29: -1- AC_SUBST([DSYMUTIL]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([DSYMUTIL]) m4trace:configure.in:29: -1- m4_pattern_allow([^DSYMUTIL$]) m4trace:configure.in:29: -1- AC_SUBST([NMEDIT]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([NMEDIT]) m4trace:configure.in:29: -1- m4_pattern_allow([^NMEDIT$]) m4trace:configure.in:29: -1- AC_SUBST([LIPO]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([LIPO]) m4trace:configure.in:29: -1- m4_pattern_allow([^LIPO$]) m4trace:configure.in:29: -1- AC_SUBST([OTOOL]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([OTOOL]) m4trace:configure.in:29: -1- m4_pattern_allow([^OTOOL$]) m4trace:configure.in:29: -1- AC_SUBST([OTOOL64]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([OTOOL64]) m4trace:configure.in:29: -1- m4_pattern_allow([^OTOOL64$]) m4trace:configure.in:29: -1- _m4_warn([syntax], [AC_LANG_CONFTEST: no AC_LANG_SOURCE call detected in body], [../../lib/autoconf/lang.m4:193: AC_LANG_CONFTEST is expanded from... ../../lib/autoconf/general.m4:2672: _AC_LINK_IFELSE is expanded from... ../../lib/autoconf/general.m4:2689: AC_LINK_IFELSE is expanded from... acinclude/libtool.m4:4173: _LT_LINKER_SHLIBS is expanded from... acinclude/libtool.m4:5248: _LT_LANG_C_CONFIG is expanded from... acinclude/libtool.m4:140: _LT_SETUP is expanded from... acinclude/libtool.m4:69: LT_INIT is expanded from... configure.in:29: the top level]) m4trace:configure.in:29: -1- AH_OUTPUT([HAVE_DLFCN_H], [/* Define to 1 if you have the <dlfcn.h> header file. */ @%:@undef HAVE_DLFCN_H]) m4trace:configure.in:29: -1- AC_SUBST([CPP]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([CPP]) m4trace:configure.in:29: -1- m4_pattern_allow([^CPP$]) m4trace:configure.in:29: -1- AC_SUBST([CPPFLAGS]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([CPPFLAGS]) m4trace:configure.in:29: -1- m4_pattern_allow([^CPPFLAGS$]) m4trace:configure.in:29: -1- AC_SUBST([CPP]) m4trace:configure.in:29: -1- AC_SUBST_TRACE([CPP]) m4trace:configure.in:29: -1- m4_pattern_allow([^CPP$]) m4trace:configure.in:29: -1- AC_DEFINE_TRACE_LITERAL([STDC_HEADERS]) m4trace:configure.in:29: -1- m4_pattern_allow([^STDC_HEADERS$]) m4trace:configure.in:29: -1- AH_OUTPUT([STDC_HEADERS], [/* Define to 1 if you have the ANSI C header files. */ @%:@undef STDC_HEADERS]) m4trace:configure.in:29: -1- AH_OUTPUT([HAVE_SYS_TYPES_H], [/* Define to 1 if you have the <sys/types.h> header file. */ @%:@undef HAVE_SYS_TYPES_H]) m4trace:configure.in:29: -1- AH_OUTPUT([HAVE_SYS_STAT_H], [/* Define to 1 if you have the <sys/stat.h> header file. */ @%:@undef HAVE_SYS_STAT_H]) m4trace:configure.in:29: -1- AH_OUTPUT([HAVE_STDLIB_H], [/* Define to 1 if you have the <stdlib.h> header file. */ @%:@undef HAVE_STDLIB_H]) m4trace:configure.in:29: -1- AH_OUTPUT([HAVE_STRING_H], [/* Define to 1 if you have the <string.h> header file. */ @%:@undef HAVE_STRING_H]) m4trace:configure.in:29: -1- AH_OUTPUT([HAVE_MEMORY_H], [/* Define to 1 if you have the <memory.h> header file. */ @%:@undef HAVE_MEMORY_H]) m4trace:configure.in:29: -1- AH_OUTPUT([HAVE_STRINGS_H], [/* Define to 1 if you have the <strings.h> header file. */ @%:@undef HAVE_STRINGS_H]) m4trace:configure.in:29: -1- AH_OUTPUT([HAVE_INTTYPES_H], [/* Define to 1 if you have the <inttypes.h> header file. */ @%:@undef HAVE_INTTYPES_H]) m4trace:configure.in:29: -1- AH_OUTPUT([HAVE_STDINT_H], [/* Define to 1 if you have the <stdint.h> header file. */ @%:@undef HAVE_STDINT_H]) m4trace:configure.in:29: -1- AH_OUTPUT([HAVE_UNISTD_H], [/* Define to 1 if you have the <unistd.h> header file. */ @%:@undef HAVE_UNISTD_H]) m4trace:configure.in:29: -1- AC_DEFINE_TRACE_LITERAL([HAVE_DLFCN_H]) m4trace:configure.in:29: -1- m4_pattern_allow([^HAVE_DLFCN_H$]) m4trace:configure.in:36: -1- AC_SUBST([LT_RELEASE]) m4trace:configure.in:36: -1- AC_SUBST_TRACE([LT_RELEASE]) m4trace:configure.in:36: -1- m4_pattern_allow([^LT_RELEASE$]) m4trace:configure.in:37: -1- AC_SUBST([LT_CURRENT]) m4trace:configure.in:37: -1- AC_SUBST_TRACE([LT_CURRENT]) m4trace:configure.in:37: -1- m4_pattern_allow([^LT_CURRENT$]) m4trace:configure.in:38: -1- AC_SUBST([LT_REVISION]) m4trace:configure.in:38: -1- AC_SUBST_TRACE([LT_REVISION]) m4trace:configure.in:38: -1- m4_pattern_allow([^LT_REVISION$]) m4trace:configure.in:39: -1- AC_SUBST([LT_AGE]) m4trace:configure.in:39: -1- AC_SUBST_TRACE([LT_AGE]) m4trace:configure.in:39: -1- m4_pattern_allow([^LT_AGE$]) m4trace:configure.in:42: -1- AC_CANONICAL_HOST m4trace:configure.in:45: -1- AM_INIT_AUTOMAKE([SDL2_image], [$VERSION]) m4trace:configure.in:45: -1- m4_pattern_allow([^AM_[A-Z]+FLAGS$]) m4trace:configure.in:45: -1- AM_AUTOMAKE_VERSION([1.15]) m4trace:configure.in:45: -1- AC_REQUIRE_AUX_FILE([install-sh]) m4trace:configure.in:45: -1- AC_SUBST([INSTALL_PROGRAM]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([INSTALL_PROGRAM]) m4trace:configure.in:45: -1- m4_pattern_allow([^INSTALL_PROGRAM$]) m4trace:configure.in:45: -1- AC_SUBST([INSTALL_SCRIPT]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([INSTALL_SCRIPT]) m4trace:configure.in:45: -1- m4_pattern_allow([^INSTALL_SCRIPT$]) m4trace:configure.in:45: -1- AC_SUBST([INSTALL_DATA]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([INSTALL_DATA]) m4trace:configure.in:45: -1- m4_pattern_allow([^INSTALL_DATA$]) m4trace:configure.in:45: -1- AC_SUBST([am__isrc], [' -I$(srcdir)']) m4trace:configure.in:45: -1- AC_SUBST_TRACE([am__isrc]) m4trace:configure.in:45: -1- m4_pattern_allow([^am__isrc$]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([am__isrc]) m4trace:configure.in:45: -1- AC_SUBST([CYGPATH_W]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([CYGPATH_W]) m4trace:configure.in:45: -1- m4_pattern_allow([^CYGPATH_W$]) m4trace:configure.in:45: -1- _m4_warn([obsolete], [AM_INIT_AUTOMAKE: two- and three-arguments forms are deprecated.], [aclocal.m4:537: AM_INIT_AUTOMAKE is expanded from... configure.in:45: the top level]) m4trace:configure.in:45: -1- AC_SUBST([PACKAGE], [SDL2_image]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([PACKAGE]) m4trace:configure.in:45: -1- m4_pattern_allow([^PACKAGE$]) m4trace:configure.in:45: -1- AC_SUBST([VERSION], [$VERSION]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([VERSION]) m4trace:configure.in:45: -1- m4_pattern_allow([^VERSION$]) m4trace:configure.in:45: -1- AC_DEFINE_TRACE_LITERAL([PACKAGE]) m4trace:configure.in:45: -1- m4_pattern_allow([^PACKAGE$]) m4trace:configure.in:45: -1- AH_OUTPUT([PACKAGE], [/* Name of package */ @%:@undef PACKAGE]) m4trace:configure.in:45: -1- AC_DEFINE_TRACE_LITERAL([VERSION]) m4trace:configure.in:45: -1- m4_pattern_allow([^VERSION$]) m4trace:configure.in:45: -1- AH_OUTPUT([VERSION], [/* Version number of package */ @%:@undef VERSION]) m4trace:configure.in:45: -1- AC_REQUIRE_AUX_FILE([missing]) m4trace:configure.in:45: -1- AC_SUBST([ACLOCAL]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([ACLOCAL]) m4trace:configure.in:45: -1- m4_pattern_allow([^ACLOCAL$]) m4trace:configure.in:45: -1- AC_SUBST([AUTOCONF]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([AUTOCONF]) m4trace:configure.in:45: -1- m4_pattern_allow([^AUTOCONF$]) m4trace:configure.in:45: -1- AC_SUBST([AUTOMAKE]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([AUTOMAKE]) m4trace:configure.in:45: -1- m4_pattern_allow([^AUTOMAKE$]) m4trace:configure.in:45: -1- AC_SUBST([AUTOHEADER]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([AUTOHEADER]) m4trace:configure.in:45: -1- m4_pattern_allow([^AUTOHEADER$]) m4trace:configure.in:45: -1- AC_SUBST([MAKEINFO]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([MAKEINFO]) m4trace:configure.in:45: -1- m4_pattern_allow([^MAKEINFO$]) m4trace:configure.in:45: -1- AC_SUBST([install_sh]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([install_sh]) m4trace:configure.in:45: -1- m4_pattern_allow([^install_sh$]) m4trace:configure.in:45: -1- AC_SUBST([STRIP]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([STRIP]) m4trace:configure.in:45: -1- m4_pattern_allow([^STRIP$]) m4trace:configure.in:45: -1- AC_SUBST([INSTALL_STRIP_PROGRAM]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([INSTALL_STRIP_PROGRAM]) m4trace:configure.in:45: -1- m4_pattern_allow([^INSTALL_STRIP_PROGRAM$]) m4trace:configure.in:45: -1- AC_REQUIRE_AUX_FILE([install-sh]) m4trace:configure.in:45: -1- AC_SUBST([MKDIR_P]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([MKDIR_P]) m4trace:configure.in:45: -1- m4_pattern_allow([^MKDIR_P$]) m4trace:configure.in:45: -1- AC_SUBST([mkdir_p], ['$(MKDIR_P)']) m4trace:configure.in:45: -1- AC_SUBST_TRACE([mkdir_p]) m4trace:configure.in:45: -1- m4_pattern_allow([^mkdir_p$]) m4trace:configure.in:45: -1- AC_SUBST([AWK]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([AWK]) m4trace:configure.in:45: -1- m4_pattern_allow([^AWK$]) m4trace:configure.in:45: -1- AC_SUBST([SET_MAKE]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([SET_MAKE]) m4trace:configure.in:45: -1- m4_pattern_allow([^SET_MAKE$]) m4trace:configure.in:45: -1- AC_SUBST([am__leading_dot]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([am__leading_dot]) m4trace:configure.in:45: -1- m4_pattern_allow([^am__leading_dot$]) m4trace:configure.in:45: -1- AC_SUBST([AMTAR], ['$${TAR-tar}']) m4trace:configure.in:45: -1- AC_SUBST_TRACE([AMTAR]) m4trace:configure.in:45: -1- m4_pattern_allow([^AMTAR$]) m4trace:configure.in:45: -1- AC_SUBST([am__tar]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([am__tar]) m4trace:configure.in:45: -1- m4_pattern_allow([^am__tar$]) m4trace:configure.in:45: -1- AC_SUBST([am__untar]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([am__untar]) m4trace:configure.in:45: -1- m4_pattern_allow([^am__untar$]) m4trace:configure.in:45: -1- AC_SUBST([DEPDIR], ["${am__leading_dot}deps"]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([DEPDIR]) m4trace:configure.in:45: -1- m4_pattern_allow([^DEPDIR$]) m4trace:configure.in:45: -1- AC_SUBST([am__include]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([am__include]) m4trace:configure.in:45: -1- m4_pattern_allow([^am__include$]) m4trace:configure.in:45: -1- AC_SUBST([am__quote]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([am__quote]) m4trace:configure.in:45: -1- m4_pattern_allow([^am__quote$]) m4trace:configure.in:45: -1- AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno]) m4trace:configure.in:45: -1- AC_SUBST([AMDEP_TRUE]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([AMDEP_TRUE]) m4trace:configure.in:45: -1- m4_pattern_allow([^AMDEP_TRUE$]) m4trace:configure.in:45: -1- AC_SUBST([AMDEP_FALSE]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([AMDEP_FALSE]) m4trace:configure.in:45: -1- m4_pattern_allow([^AMDEP_FALSE$]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([AMDEP_TRUE]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([AMDEP_FALSE]) m4trace:configure.in:45: -1- AC_SUBST([AMDEPBACKSLASH]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([AMDEPBACKSLASH]) m4trace:configure.in:45: -1- m4_pattern_allow([^AMDEPBACKSLASH$]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([AMDEPBACKSLASH]) m4trace:configure.in:45: -1- AC_SUBST([am__nodep]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([am__nodep]) m4trace:configure.in:45: -1- m4_pattern_allow([^am__nodep$]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([am__nodep]) m4trace:configure.in:45: -1- AC_SUBST([CCDEPMODE], [depmode=$am_cv_CC_dependencies_compiler_type]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([CCDEPMODE]) m4trace:configure.in:45: -1- m4_pattern_allow([^CCDEPMODE$]) m4trace:configure.in:45: -1- AM_CONDITIONAL([am__fastdepCC], [ test "x$enable_dependency_tracking" != xno \ && test "$am_cv_CC_dependencies_compiler_type" = gcc3]) m4trace:configure.in:45: -1- AC_SUBST([am__fastdepCC_TRUE]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([am__fastdepCC_TRUE]) m4trace:configure.in:45: -1- m4_pattern_allow([^am__fastdepCC_TRUE$]) m4trace:configure.in:45: -1- AC_SUBST([am__fastdepCC_FALSE]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([am__fastdepCC_FALSE]) m4trace:configure.in:45: -1- m4_pattern_allow([^am__fastdepCC_FALSE$]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([am__fastdepCC_TRUE]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([am__fastdepCC_FALSE]) m4trace:configure.in:45: -1- AM_SILENT_RULES m4trace:configure.in:45: -1- AC_SUBST([AM_V]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([AM_V]) m4trace:configure.in:45: -1- m4_pattern_allow([^AM_V$]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([AM_V]) m4trace:configure.in:45: -1- AC_SUBST([AM_DEFAULT_V]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([AM_DEFAULT_V]) m4trace:configure.in:45: -1- m4_pattern_allow([^AM_DEFAULT_V$]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([AM_DEFAULT_V]) m4trace:configure.in:45: -1- AC_SUBST([AM_DEFAULT_VERBOSITY]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([AM_DEFAULT_VERBOSITY]) m4trace:configure.in:45: -1- m4_pattern_allow([^AM_DEFAULT_VERBOSITY$]) m4trace:configure.in:45: -1- AC_SUBST([AM_BACKSLASH]) m4trace:configure.in:45: -1- AC_SUBST_TRACE([AM_BACKSLASH]) m4trace:configure.in:45: -1- m4_pattern_allow([^AM_BACKSLASH$]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([AM_BACKSLASH]) m4trace:configure.in:48: -1- AC_PROG_LIBTOOL m4trace:configure.in:48: -1- _m4_warn([obsolete], [The macro `AC_PROG_LIBTOOL' is obsolete. You should run autoupdate.], [acinclude/libtool.m4:104: AC_PROG_LIBTOOL is expanded from... configure.in:48: the top level]) m4trace:configure.in:48: -1- LT_INIT m4trace:configure.in:49: -1- AC_SUBST([CC]) m4trace:configure.in:49: -1- AC_SUBST_TRACE([CC]) m4trace:configure.in:49: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:49: -1- AC_SUBST([CFLAGS]) m4trace:configure.in:49: -1- AC_SUBST_TRACE([CFLAGS]) m4trace:configure.in:49: -1- m4_pattern_allow([^CFLAGS$]) m4trace:configure.in:49: -1- AC_SUBST([LDFLAGS]) m4trace:configure.in:49: -1- AC_SUBST_TRACE([LDFLAGS]) m4trace:configure.in:49: -1- m4_pattern_allow([^LDFLAGS$]) m4trace:configure.in:49: -1- AC_SUBST([LIBS]) m4trace:configure.in:49: -1- AC_SUBST_TRACE([LIBS]) m4trace:configure.in:49: -1- m4_pattern_allow([^LIBS$]) m4trace:configure.in:49: -1- AC_SUBST([CPPFLAGS]) m4trace:configure.in:49: -1- AC_SUBST_TRACE([CPPFLAGS]) m4trace:configure.in:49: -1- m4_pattern_allow([^CPPFLAGS$]) m4trace:configure.in:49: -1- AC_SUBST([CC]) m4trace:configure.in:49: -1- AC_SUBST_TRACE([CC]) m4trace:configure.in:49: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:49: -1- AC_SUBST([CC]) m4trace:configure.in:49: -1- AC_SUBST_TRACE([CC]) m4trace:configure.in:49: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:49: -1- AC_SUBST([CC]) m4trace:configure.in:49: -1- AC_SUBST_TRACE([CC]) m4trace:configure.in:49: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:49: -1- AC_SUBST([CC]) m4trace:configure.in:49: -1- AC_SUBST_TRACE([CC]) m4trace:configure.in:49: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:49: -1- AC_SUBST([ac_ct_CC]) m4trace:configure.in:49: -1- AC_SUBST_TRACE([ac_ct_CC]) m4trace:configure.in:49: -1- m4_pattern_allow([^ac_ct_CC$]) m4trace:configure.in:49: -1- AC_REQUIRE_AUX_FILE([compile]) m4trace:configure.in:50: -1- AC_SUBST([OBJC]) m4trace:configure.in:50: -1- AC_SUBST_TRACE([OBJC]) m4trace:configure.in:50: -1- m4_pattern_allow([^OBJC$]) m4trace:configure.in:50: -1- AC_SUBST([OBJCFLAGS]) m4trace:configure.in:50: -1- AC_SUBST_TRACE([OBJCFLAGS]) m4trace:configure.in:50: -1- m4_pattern_allow([^OBJCFLAGS$]) m4trace:configure.in:50: -1- AC_SUBST([LDFLAGS]) m4trace:configure.in:50: -1- AC_SUBST_TRACE([LDFLAGS]) m4trace:configure.in:50: -1- m4_pattern_allow([^LDFLAGS$]) m4trace:configure.in:50: -1- AC_SUBST([LIBS]) m4trace:configure.in:50: -1- AC_SUBST_TRACE([LIBS]) m4trace:configure.in:50: -1- m4_pattern_allow([^LIBS$]) m4trace:configure.in:50: -1- AC_SUBST([CPPFLAGS]) m4trace:configure.in:50: -1- AC_SUBST_TRACE([CPPFLAGS]) m4trace:configure.in:50: -1- m4_pattern_allow([^CPPFLAGS$]) m4trace:configure.in:50: -1- AC_SUBST([OBJC]) m4trace:configure.in:50: -1- AC_SUBST_TRACE([OBJC]) m4trace:configure.in:50: -1- m4_pattern_allow([^OBJC$]) m4trace:configure.in:50: -1- AC_SUBST([ac_ct_OBJC]) m4trace:configure.in:50: -1- AC_SUBST_TRACE([ac_ct_OBJC]) m4trace:configure.in:50: -1- m4_pattern_allow([^ac_ct_OBJC$]) m4trace:configure.in:50: -1- AC_SUBST([OBJCDEPMODE], [depmode=$am_cv_OBJC_dependencies_compiler_type]) m4trace:configure.in:50: -1- AC_SUBST_TRACE([OBJCDEPMODE]) m4trace:configure.in:50: -1- m4_pattern_allow([^OBJCDEPMODE$]) m4trace:configure.in:50: -1- AM_CONDITIONAL([am__fastdepOBJC], [ test "x$enable_dependency_tracking" != xno \ && test "$am_cv_OBJC_dependencies_compiler_type" = gcc3]) m4trace:configure.in:50: -1- AC_SUBST([am__fastdepOBJC_TRUE]) m4trace:configure.in:50: -1- AC_SUBST_TRACE([am__fastdepOBJC_TRUE]) m4trace:configure.in:50: -1- m4_pattern_allow([^am__fastdepOBJC_TRUE$]) m4trace:configure.in:50: -1- AC_SUBST([am__fastdepOBJC_FALSE]) m4trace:configure.in:50: -1- AC_SUBST_TRACE([am__fastdepOBJC_FALSE]) m4trace:configure.in:50: -1- m4_pattern_allow([^am__fastdepOBJC_FALSE$]) m4trace:configure.in:50: -1- _AM_SUBST_NOTMAKE([am__fastdepOBJC_TRUE]) m4trace:configure.in:50: -1- _AM_SUBST_NOTMAKE([am__fastdepOBJC_FALSE]) m4trace:configure.in:51: -1- AH_OUTPUT([inline], [/* Define to `__inline__\' or `__inline\' if that\'s what the C compiler calls it, or to nothing if \'inline\' is not supported under any name. */ #ifndef __cplusplus #undef inline #endif]) m4trace:configure.in:53: -1- AC_SUBST([SET_MAKE]) m4trace:configure.in:53: -1- AC_SUBST_TRACE([SET_MAKE]) m4trace:configure.in:53: -1- m4_pattern_allow([^SET_MAKE$]) m4trace:configure.in:59: -1- AC_SUBST([WINDRES]) m4trace:configure.in:59: -1- AC_SUBST_TRACE([WINDRES]) m4trace:configure.in:59: -1- m4_pattern_allow([^WINDRES$]) m4trace:configure.in:80: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:80: the top level]) m4trace:configure.in:92: -1- AM_CONDITIONAL([USE_IMAGEIO], [test x$enable_imageio = xyes]) m4trace:configure.in:92: -1- AC_SUBST([USE_IMAGEIO_TRUE]) m4trace:configure.in:92: -1- AC_SUBST_TRACE([USE_IMAGEIO_TRUE]) m4trace:configure.in:92: -1- m4_pattern_allow([^USE_IMAGEIO_TRUE$]) m4trace:configure.in:92: -1- AC_SUBST([USE_IMAGEIO_FALSE]) m4trace:configure.in:92: -1- AC_SUBST_TRACE([USE_IMAGEIO_FALSE]) m4trace:configure.in:92: -1- m4_pattern_allow([^USE_IMAGEIO_FALSE$]) m4trace:configure.in:92: -1- _AM_SUBST_NOTMAKE([USE_IMAGEIO_TRUE]) m4trace:configure.in:92: -1- _AM_SUBST_NOTMAKE([USE_IMAGEIO_FALSE]) m4trace:configure.in:93: -1- AM_CONDITIONAL([USE_VERSION_RC], [test x$use_version_rc = xtrue]) m4trace:configure.in:93: -1- AC_SUBST([USE_VERSION_RC_TRUE]) m4trace:configure.in:93: -1- AC_SUBST_TRACE([USE_VERSION_RC_TRUE]) m4trace:configure.in:93: -1- m4_pattern_allow([^USE_VERSION_RC_TRUE$]) m4trace:configure.in:93: -1- AC_SUBST([USE_VERSION_RC_FALSE]) m4trace:configure.in:93: -1- AC_SUBST_TRACE([USE_VERSION_RC_FALSE]) m4trace:configure.in:93: -1- m4_pattern_allow([^USE_VERSION_RC_FALSE$]) m4trace:configure.in:93: -1- _AM_SUBST_NOTMAKE([USE_VERSION_RC_TRUE]) m4trace:configure.in:93: -1- _AM_SUBST_NOTMAKE([USE_VERSION_RC_FALSE]) m4trace:configure.in:120: -1- AC_SUBST([SDL_VERSION]) m4trace:configure.in:120: -1- AC_SUBST_TRACE([SDL_VERSION]) m4trace:configure.in:120: -1- m4_pattern_allow([^SDL_VERSION$]) m4trace:configure.in:121: -1- m4_pattern_forbid([^_?PKG_[A-Z_]+$]) m4trace:configure.in:121: -1- m4_pattern_allow([^PKG_CONFIG(_PATH)?$]) m4trace:configure.in:121: -1- AC_SUBST([PKG_CONFIG]) m4trace:configure.in:121: -1- AC_SUBST_TRACE([PKG_CONFIG]) m4trace:configure.in:121: -1- m4_pattern_allow([^PKG_CONFIG$]) m4trace:configure.in:121: -1- AC_SUBST([PKG_CONFIG]) m4trace:configure.in:121: -1- AC_SUBST_TRACE([PKG_CONFIG]) m4trace:configure.in:121: -1- m4_pattern_allow([^PKG_CONFIG$]) m4trace:configure.in:121: -1- AC_SUBST([SDL_CFLAGS]) m4trace:configure.in:121: -1- AC_SUBST_TRACE([SDL_CFLAGS]) m4trace:configure.in:121: -1- m4_pattern_allow([^SDL_CFLAGS$]) m4trace:configure.in:121: -1- AC_SUBST([SDL_LIBS]) m4trace:configure.in:121: -1- AC_SUBST_TRACE([SDL_LIBS]) m4trace:configure.in:121: -1- m4_pattern_allow([^SDL_LIBS$]) m4trace:configure.in:121: -1- AC_SUBST([SDL2_CONFIG]) m4trace:configure.in:121: -1- AC_SUBST_TRACE([SDL2_CONFIG]) m4trace:configure.in:121: -1- m4_pattern_allow([^SDL2_CONFIG$]) m4trace:configure.in:121: -1- _m4_warn([obsolete], [The macro `AC_TRY_RUN' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:2775: AC_TRY_RUN is expanded from... acinclude/sdl2.m4:13: AM_PATH_SDL2 is expanded from... configure.in:121: the top level]) m4trace:configure.in:121: -1- _m4_warn([obsolete], [The macro `AC_TRY_LINK' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:2698: AC_TRY_LINK is expanded from... acinclude/sdl2.m4:13: AM_PATH_SDL2 is expanded from... configure.in:121: the top level]) m4trace:configure.in:121: -1- AC_SUBST([SDL_CFLAGS]) m4trace:configure.in:121: -1- AC_SUBST_TRACE([SDL_CFLAGS]) m4trace:configure.in:121: -1- m4_pattern_allow([^SDL_CFLAGS$]) m4trace:configure.in:121: -1- AC_SUBST([SDL_LIBS]) m4trace:configure.in:121: -1- AC_SUBST_TRACE([SDL_LIBS]) m4trace:configure.in:121: -1- m4_pattern_allow([^SDL_LIBS$]) m4trace:configure.in:130: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:130: the top level]) m4trace:configure.in:132: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:132: the top level]) m4trace:configure.in:134: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:134: the top level]) m4trace:configure.in:136: -2- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... configure.in:136: the top level]) m4trace:configure.in:138: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:138: the top level]) m4trace:configure.in:140: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:140: the top level]) m4trace:configure.in:142: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:142: the top level]) m4trace:configure.in:144: -2- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... configure.in:144: the top level]) m4trace:configure.in:146: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:146: the top level]) m4trace:configure.in:148: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:148: the top level]) m4trace:configure.in:150: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:150: the top level]) m4trace:configure.in:152: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:152: the top level]) m4trace:configure.in:154: -2- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... configure.in:154: the top level]) m4trace:configure.in:156: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:156: the top level]) m4trace:configure.in:158: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:158: the top level]) m4trace:configure.in:160: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:160: the top level]) m4trace:configure.in:162: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:162: the top level]) m4trace:configure.in:164: -2- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... configure.in:164: the top level]) m4trace:configure.in:172: -1- AC_DEFINE_TRACE_LITERAL([LOAD_JPG]) m4trace:configure.in:172: -1- m4_pattern_allow([^LOAD_JPG$]) m4trace:configure.in:197: -1- AC_SUBST([LIBPNG_CFLAGS]) m4trace:configure.in:197: -1- AC_SUBST_TRACE([LIBPNG_CFLAGS]) m4trace:configure.in:197: -1- m4_pattern_allow([^LIBPNG_CFLAGS$]) m4trace:configure.in:197: -1- AC_SUBST([LIBPNG_LIBS]) m4trace:configure.in:197: -1- AC_SUBST_TRACE([LIBPNG_LIBS]) m4trace:configure.in:197: -1- m4_pattern_allow([^LIBPNG_LIBS$]) m4trace:configure.in:211: -1- AC_DEFINE_TRACE_LITERAL([LOAD_PNG]) m4trace:configure.in:211: -1- m4_pattern_allow([^LOAD_PNG$]) m4trace:configure.in:237: -1- AC_DEFINE_TRACE_LITERAL([LOAD_TIF]) m4trace:configure.in:237: -1- m4_pattern_allow([^LOAD_TIF$]) m4trace:configure.in:260: -1- AC_SUBST([LIBWEBP_CFLAGS]) m4trace:configure.in:260: -1- AC_SUBST_TRACE([LIBWEBP_CFLAGS]) m4trace:configure.in:260: -1- m4_pattern_allow([^LIBWEBP_CFLAGS$]) m4trace:configure.in:260: -1- AC_SUBST([LIBWEBP_LIBS]) m4trace:configure.in:260: -1- AC_SUBST_TRACE([LIBWEBP_LIBS]) m4trace:configure.in:260: -1- m4_pattern_allow([^LIBWEBP_LIBS$]) m4trace:configure.in:274: -1- AC_DEFINE_TRACE_LITERAL([LOAD_WEBP]) m4trace:configure.in:274: -1- m4_pattern_allow([^LOAD_WEBP$]) m4trace:configure.in:297: -1- AC_DEFINE_TRACE_LITERAL([LOAD_BMP]) m4trace:configure.in:297: -1- m4_pattern_allow([^LOAD_BMP$]) m4trace:configure.in:301: -1- AC_DEFINE_TRACE_LITERAL([LOAD_GIF]) m4trace:configure.in:301: -1- m4_pattern_allow([^LOAD_GIF$]) m4trace:configure.in:305: -1- AC_DEFINE_TRACE_LITERAL([LOAD_LBM]) m4trace:configure.in:305: -1- m4_pattern_allow([^LOAD_LBM$]) m4trace:configure.in:309: -1- AC_DEFINE_TRACE_LITERAL([LOAD_PCX]) m4trace:configure.in:309: -1- m4_pattern_allow([^LOAD_PCX$]) m4trace:configure.in:313: -1- AC_DEFINE_TRACE_LITERAL([LOAD_PNM]) m4trace:configure.in:313: -1- m4_pattern_allow([^LOAD_PNM$]) m4trace:configure.in:317: -1- AC_DEFINE_TRACE_LITERAL([LOAD_SVG]) m4trace:configure.in:317: -1- m4_pattern_allow([^LOAD_SVG$]) m4trace:configure.in:321: -1- AC_DEFINE_TRACE_LITERAL([LOAD_TGA]) m4trace:configure.in:321: -1- m4_pattern_allow([^LOAD_TGA$]) m4trace:configure.in:325: -1- AC_DEFINE_TRACE_LITERAL([LOAD_XCF]) m4trace:configure.in:325: -1- m4_pattern_allow([^LOAD_XCF$]) m4trace:configure.in:329: -1- AC_DEFINE_TRACE_LITERAL([LOAD_XPM]) m4trace:configure.in:329: -1- m4_pattern_allow([^LOAD_XPM$]) m4trace:configure.in:333: -1- AC_DEFINE_TRACE_LITERAL([LOAD_XV]) m4trace:configure.in:333: -1- m4_pattern_allow([^LOAD_XV$]) m4trace:configure.in:340: -1- AC_DEFINE_TRACE_LITERAL([LOAD_WEBP_DYNAMIC]) m4trace:configure.in:340: -1- m4_pattern_allow([^LOAD_WEBP_DYNAMIC$]) m4trace:configure.in:349: -1- AC_DEFINE_TRACE_LITERAL([LOAD_TIF_DYNAMIC]) m4trace:configure.in:349: -1- m4_pattern_allow([^LOAD_TIF_DYNAMIC$]) m4trace:configure.in:361: -1- AC_DEFINE_TRACE_LITERAL([LOAD_JPG_DYNAMIC]) m4trace:configure.in:361: -1- m4_pattern_allow([^LOAD_JPG_DYNAMIC$]) m4trace:configure.in:370: -1- AC_DEFINE_TRACE_LITERAL([LOAD_PNG_DYNAMIC]) m4trace:configure.in:370: -1- m4_pattern_allow([^LOAD_PNG_DYNAMIC$]) m4trace:configure.in:378: -1- AC_SUBST([WINDRES]) m4trace:configure.in:378: -1- AC_SUBST_TRACE([WINDRES]) m4trace:configure.in:378: -1- m4_pattern_allow([^WINDRES$]) m4trace:configure.in:379: -1- AC_SUBST([IMG_LIBS]) m4trace:configure.in:379: -1- AC_SUBST_TRACE([IMG_LIBS]) m4trace:configure.in:379: -1- m4_pattern_allow([^IMG_LIBS$]) m4trace:configure.in:384: -1- AC_CONFIG_FILES([ Makefile SDL2_image.spec SDL2_image.pc ]) m4trace:configure.in:384: -1- _m4_warn([obsolete], [AC_OUTPUT should be used without arguments. You should run autoupdate.], []) m4trace:configure.in:384: -1- AC_SUBST([LIB@&t@OBJS], [$ac_libobjs]) m4trace:configure.in:384: -1- AC_SUBST_TRACE([LIB@&t@OBJS]) m4trace:configure.in:384: -1- m4_pattern_allow([^LIB@&t@OBJS$]) m4trace:configure.in:384: -1- AC_SUBST([LTLIBOBJS], [$ac_ltlibobjs]) m4trace:configure.in:384: -1- AC_SUBST_TRACE([LTLIBOBJS]) m4trace:configure.in:384: -1- m4_pattern_allow([^LTLIBOBJS$]) m4trace:configure.in:384: -1- AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"]) m4trace:configure.in:384: -1- AC_SUBST([am__EXEEXT_TRUE]) m4trace:configure.in:384: -1- AC_SUBST_TRACE([am__EXEEXT_TRUE]) m4trace:configure.in:384: -1- m4_pattern_allow([^am__EXEEXT_TRUE$]) m4trace:configure.in:384: -1- AC_SUBST([am__EXEEXT_FALSE]) m4trace:configure.in:384: -1- AC_SUBST_TRACE([am__EXEEXT_FALSE]) m4trace:configure.in:384: -1- m4_pattern_allow([^am__EXEEXT_FALSE$]) m4trace:configure.in:384: -1- _AM_SUBST_NOTMAKE([am__EXEEXT_TRUE]) m4trace:configure.in:384: -1- _AM_SUBST_NOTMAKE([am__EXEEXT_FALSE]) m4trace:configure.in:384: -1- AC_SUBST_TRACE([top_builddir]) m4trace:configure.in:384: -1- AC_SUBST_TRACE([top_build_prefix]) m4trace:configure.in:384: -1- AC_SUBST_TRACE([srcdir]) m4trace:configure.in:384: -1- AC_SUBST_TRACE([abs_srcdir]) m4trace:configure.in:384: -1- AC_SUBST_TRACE([top_srcdir]) m4trace:configure.in:384: -1- AC_SUBST_TRACE([abs_top_srcdir]) m4trace:configure.in:384: -1- AC_SUBST_TRACE([builddir]) m4trace:configure.in:384: -1- AC_SUBST_TRACE([abs_builddir]) m4trace:configure.in:384: -1- AC_SUBST_TRACE([abs_top_builddir]) m4trace:configure.in:384: -1- AC_SUBST_TRACE([INSTALL]) m4trace:configure.in:384: -1- AC_SUBST_TRACE([MKDIR_P]) m4trace:configure.in:384: -1- AC_REQUIRE_AUX_FILE([ltmain.sh])
YifuLiu/AliOS-Things
components/SDL2/src/image/autom4te.cache/traces.1
Roff
apache-2.0
51,540
m4trace:/usr/share/aclocal/libtool.m4:61: -1- AC_DEFUN([LT_INIT], [AC_PREREQ([2.62])dnl We use AC_PATH_PROGS_FEATURE_CHECK AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl AC_BEFORE([$0], [LT_LANG])dnl AC_BEFORE([$0], [LT_OUTPUT])dnl AC_BEFORE([$0], [LTDL_INIT])dnl m4_require([_LT_CHECK_BUILDDIR])dnl dnl Autoconf doesn't catch unexpanded LT_ macros by default: m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4 dnl unless we require an AC_DEFUNed macro: AC_REQUIRE([LTOPTIONS_VERSION])dnl AC_REQUIRE([LTSUGAR_VERSION])dnl AC_REQUIRE([LTVERSION_VERSION])dnl AC_REQUIRE([LTOBSOLETE_VERSION])dnl m4_require([_LT_PROG_LTMAIN])dnl _LT_SHELL_INIT([SHELL=${CONFIG_SHELL-/bin/sh}]) dnl Parse OPTIONS _LT_SET_OPTIONS([$0], [$1]) # This can be used to rebuild libtool when needed LIBTOOL_DEPS=$ltmain # Always use our own libtool. LIBTOOL='$(SHELL) $(top_builddir)/libtool' AC_SUBST(LIBTOOL)dnl _LT_SETUP # Only expand once: m4_define([LT_INIT]) ]) m4trace:/usr/share/aclocal/libtool.m4:99: -1- AU_DEFUN([AC_PROG_LIBTOOL], [m4_if($#, 0, [LT_INIT], [LT_INIT($@)])]) m4trace:/usr/share/aclocal/libtool.m4:99: -1- AC_DEFUN([AC_PROG_LIBTOOL], [AC_DIAGNOSE([obsolete], [The macro `AC_PROG_LIBTOOL' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_INIT], [LT_INIT($@)])]) m4trace:/usr/share/aclocal/libtool.m4:100: -1- AU_DEFUN([AM_PROG_LIBTOOL], [m4_if($#, 0, [LT_INIT], [LT_INIT($@)])]) m4trace:/usr/share/aclocal/libtool.m4:100: -1- AC_DEFUN([AM_PROG_LIBTOOL], [AC_DIAGNOSE([obsolete], [The macro `AM_PROG_LIBTOOL' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_INIT], [LT_INIT($@)])]) m4trace:/usr/share/aclocal/libtool.m4:619: -1- AC_DEFUN([LT_OUTPUT], [: ${CONFIG_LT=./config.lt} AC_MSG_NOTICE([creating $CONFIG_LT]) _LT_GENERATED_FILE_INIT(["$CONFIG_LT"], [# Run this file to recreate a libtool stub with the current configuration.]) cat >>"$CONFIG_LT" <<\_LTEOF lt_cl_silent=false exec AS_MESSAGE_LOG_FD>>config.log { echo AS_BOX([Running $as_me.]) } >&AS_MESSAGE_LOG_FD lt_cl_help="\ '$as_me' creates a local libtool stub from the current configuration, for use in further configure time tests before the real libtool is generated. Usage: $[0] [[OPTIONS]] -h, --help print this help, then exit -V, --version print version number, then exit -q, --quiet do not print progress messages -d, --debug don't remove temporary files Report bugs to <bug-libtool@gnu.org>." lt_cl_version="\ m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION]) configured by $[0], generated by m4_PACKAGE_STRING. Copyright (C) 2011 Free Software Foundation, Inc. This config.lt script is free software; the Free Software Foundation gives unlimited permision to copy, distribute and modify it." while test 0 != $[#] do case $[1] in --version | --v* | -V ) echo "$lt_cl_version"; exit 0 ;; --help | --h* | -h ) echo "$lt_cl_help"; exit 0 ;; --debug | --d* | -d ) debug=: ;; --quiet | --q* | --silent | --s* | -q ) lt_cl_silent=: ;; -*) AC_MSG_ERROR([unrecognized option: $[1] Try '$[0] --help' for more information.]) ;; *) AC_MSG_ERROR([unrecognized argument: $[1] Try '$[0] --help' for more information.]) ;; esac shift done if $lt_cl_silent; then exec AS_MESSAGE_FD>/dev/null fi _LTEOF cat >>"$CONFIG_LT" <<_LTEOF _LT_OUTPUT_LIBTOOL_COMMANDS_INIT _LTEOF cat >>"$CONFIG_LT" <<\_LTEOF AC_MSG_NOTICE([creating $ofile]) _LT_OUTPUT_LIBTOOL_COMMANDS AS_EXIT(0) _LTEOF chmod +x "$CONFIG_LT" # configure is writing to config.log, but config.lt does its own redirection, # appending to config.log, which fails on DOS, as config.log is still kept # open by configure. Here we exec the FD to /dev/null, effectively closing # config.log, so it can be properly (re)opened and appended to by config.lt. lt_cl_success=: test yes = "$silent" && lt_config_lt_args="$lt_config_lt_args --quiet" exec AS_MESSAGE_LOG_FD>/dev/null $SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false exec AS_MESSAGE_LOG_FD>>config.log $lt_cl_success || AS_EXIT(1) ]) m4trace:/usr/share/aclocal/libtool.m4:812: -1- AC_DEFUN([LT_SUPPORTED_TAG], []) m4trace:/usr/share/aclocal/libtool.m4:823: -1- AC_DEFUN([LT_LANG], [AC_BEFORE([$0], [LT_OUTPUT])dnl m4_case([$1], [C], [_LT_LANG(C)], [C++], [_LT_LANG(CXX)], [Go], [_LT_LANG(GO)], [Java], [_LT_LANG(GCJ)], [Fortran 77], [_LT_LANG(F77)], [Fortran], [_LT_LANG(FC)], [Windows Resource], [_LT_LANG(RC)], [m4_ifdef([_LT_LANG_]$1[_CONFIG], [_LT_LANG($1)], [m4_fatal([$0: unsupported language: "$1"])])])dnl ]) m4trace:/usr/share/aclocal/libtool.m4:915: -1- AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)]) m4trace:/usr/share/aclocal/libtool.m4:915: -1- AC_DEFUN([AC_LIBTOOL_CXX], [AC_DIAGNOSE([obsolete], [The macro `AC_LIBTOOL_CXX' is obsolete. You should run autoupdate.])dnl LT_LANG(C++)]) m4trace:/usr/share/aclocal/libtool.m4:916: -1- AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)]) m4trace:/usr/share/aclocal/libtool.m4:916: -1- AC_DEFUN([AC_LIBTOOL_F77], [AC_DIAGNOSE([obsolete], [The macro `AC_LIBTOOL_F77' is obsolete. You should run autoupdate.])dnl LT_LANG(Fortran 77)]) m4trace:/usr/share/aclocal/libtool.m4:917: -1- AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)]) m4trace:/usr/share/aclocal/libtool.m4:917: -1- AC_DEFUN([AC_LIBTOOL_FC], [AC_DIAGNOSE([obsolete], [The macro `AC_LIBTOOL_FC' is obsolete. You should run autoupdate.])dnl LT_LANG(Fortran)]) m4trace:/usr/share/aclocal/libtool.m4:918: -1- AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)]) m4trace:/usr/share/aclocal/libtool.m4:918: -1- AC_DEFUN([AC_LIBTOOL_GCJ], [AC_DIAGNOSE([obsolete], [The macro `AC_LIBTOOL_GCJ' is obsolete. You should run autoupdate.])dnl LT_LANG(Java)]) m4trace:/usr/share/aclocal/libtool.m4:919: -1- AU_DEFUN([AC_LIBTOOL_RC], [LT_LANG(Windows Resource)]) m4trace:/usr/share/aclocal/libtool.m4:919: -1- AC_DEFUN([AC_LIBTOOL_RC], [AC_DIAGNOSE([obsolete], [The macro `AC_LIBTOOL_RC' is obsolete. You should run autoupdate.])dnl LT_LANG(Windows Resource)]) m4trace:/usr/share/aclocal/libtool.m4:1247: -1- AC_DEFUN([_LT_WITH_SYSROOT], [AC_MSG_CHECKING([for sysroot]) AC_ARG_WITH([sysroot], [AS_HELP_STRING([--with-sysroot@<:@=DIR@:>@], [Search for dependent libraries within DIR (or the compiler's sysroot if not specified).])], [], [with_sysroot=no]) dnl lt_sysroot will always be passed unquoted. We quote it here dnl in case the user passed a directory name. lt_sysroot= case $with_sysroot in #( yes) if test yes = "$GCC"; then lt_sysroot=`$CC --print-sysroot 2>/dev/null` fi ;; #( /*) lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"` ;; #( no|'') ;; #( *) AC_MSG_RESULT([$with_sysroot]) AC_MSG_ERROR([The sysroot must be an absolute path.]) ;; esac AC_MSG_RESULT([${lt_sysroot:-no}]) _LT_DECL([], [lt_sysroot], [0], [The root where to search for ]dnl [dependent libraries, and where our libraries should be installed.])]) m4trace:/usr/share/aclocal/libtool.m4:1578: -1- AC_DEFUN([_LT_COMPILER_OPTION], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_SED])dnl AC_CACHE_CHECK([$1], [$2], [$2=no m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4]) echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$3" ## exclude from sc_useless_quotes_in_assignment # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&AS_MESSAGE_LOG_FD echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then $2=yes fi fi $RM conftest* ]) if test yes = "[$]$2"; then m4_if([$5], , :, [$5]) else m4_if([$6], , :, [$6]) fi ]) m4trace:/usr/share/aclocal/libtool.m4:1620: -1- AU_DEFUN([AC_LIBTOOL_COMPILER_OPTION], [m4_if($#, 0, [_LT_COMPILER_OPTION], [_LT_COMPILER_OPTION($@)])]) m4trace:/usr/share/aclocal/libtool.m4:1620: -1- AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], [AC_DIAGNOSE([obsolete], [The macro `AC_LIBTOOL_COMPILER_OPTION' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [_LT_COMPILER_OPTION], [_LT_COMPILER_OPTION($@)])]) m4trace:/usr/share/aclocal/libtool.m4:1629: -1- AC_DEFUN([_LT_LINKER_OPTION], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_SED])dnl AC_CACHE_CHECK([$1], [$2], [$2=no save_LDFLAGS=$LDFLAGS LDFLAGS="$LDFLAGS $3" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&AS_MESSAGE_LOG_FD $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then $2=yes fi else $2=yes fi fi $RM -r conftest* LDFLAGS=$save_LDFLAGS ]) if test yes = "[$]$2"; then m4_if([$4], , :, [$4]) else m4_if([$5], , :, [$5]) fi ]) m4trace:/usr/share/aclocal/libtool.m4:1664: -1- AU_DEFUN([AC_LIBTOOL_LINKER_OPTION], [m4_if($#, 0, [_LT_LINKER_OPTION], [_LT_LINKER_OPTION($@)])]) m4trace:/usr/share/aclocal/libtool.m4:1664: -1- AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], [AC_DIAGNOSE([obsolete], [The macro `AC_LIBTOOL_LINKER_OPTION' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [_LT_LINKER_OPTION], [_LT_LINKER_OPTION($@)])]) m4trace:/usr/share/aclocal/libtool.m4:1671: -1- AC_DEFUN([LT_CMD_MAX_LEN], [AC_REQUIRE([AC_CANONICAL_HOST])dnl # find the maximum length of command line arguments AC_MSG_CHECKING([the maximum length of command line arguments]) AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl i=0 teststring=ABCD case $build_os in msdosdjgpp*) # On DJGPP, this test can blow up pretty badly due to problems in libc # (any single argument exceeding 2000 bytes causes a buffer overrun # during glob expansion). Even if it were fixed, the result of this # check would be larger than it should be. lt_cv_sys_max_cmd_len=12288; # 12K is about right ;; gnu*) # Under GNU Hurd, this test is not required because there is # no limit to the length of command line arguments. # Libtool will interpret -1 as no limit whatsoever lt_cv_sys_max_cmd_len=-1; ;; cygwin* | mingw* | cegcc*) # On Win9x/ME, this test blows up -- it succeeds, but takes # about 5 minutes as the teststring grows exponentially. # Worse, since 9x/ME are not pre-emptively multitasking, # you end up with a "frozen" computer, even though with patience # the test eventually succeeds (with a max line length of 256k). # Instead, let's just punt: use the minimum linelength reported by # all of the supported platforms: 8192 (on NT/2K/XP). lt_cv_sys_max_cmd_len=8192; ;; mint*) # On MiNT this can take a long time and run out of memory. lt_cv_sys_max_cmd_len=8192; ;; amigaos*) # On AmigaOS with pdksh, this test takes hours, literally. # So we just punt and use a minimum line length of 8192. lt_cv_sys_max_cmd_len=8192; ;; bitrig* | darwin* | dragonfly* | freebsd* | netbsd* | openbsd*) # This has been around since 386BSD, at least. Likely further. if test -x /sbin/sysctl; then lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` elif test -x /usr/sbin/sysctl; then lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` else lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs fi # And add a safety zone lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` ;; interix*) # We know the value 262144 and hardcode it with a safety zone (like BSD) lt_cv_sys_max_cmd_len=196608 ;; os2*) # The test takes a long time on OS/2. lt_cv_sys_max_cmd_len=8192 ;; osf*) # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not # nice to cause kernel panics so lets avoid the loop below. # First set a reasonable default. lt_cv_sys_max_cmd_len=16384 # if test -x /sbin/sysconfig; then case `/sbin/sysconfig -q proc exec_disable_arg_limit` in *1*) lt_cv_sys_max_cmd_len=-1 ;; esac fi ;; sco3.2v5*) lt_cv_sys_max_cmd_len=102400 ;; sysv5* | sco5v6* | sysv4.2uw2*) kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` if test -n "$kargmax"; then lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[ ]]//'` else lt_cv_sys_max_cmd_len=32768 fi ;; *) lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` if test -n "$lt_cv_sys_max_cmd_len" && \ test undefined != "$lt_cv_sys_max_cmd_len"; then lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` else # Make teststring a little bigger before we do anything with it. # a 1K string should be a reasonable start. for i in 1 2 3 4 5 6 7 8; do teststring=$teststring$teststring done SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} # If test is not a shell built-in, we'll probably end up computing a # maximum length that is only half of the actual maximum length, but # we can't tell. while { test X`env echo "$teststring$teststring" 2>/dev/null` \ = "X$teststring$teststring"; } >/dev/null 2>&1 && test 17 != "$i" # 1/2 MB should be enough do i=`expr $i + 1` teststring=$teststring$teststring done # Only check the string length outside the loop. lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` teststring= # Add a significant safety factor because C++ compilers can tack on # massive amounts of additional arguments before passing them to the # linker. It appears as though 1/2 is a usable value. lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` fi ;; esac ]) if test -n "$lt_cv_sys_max_cmd_len"; then AC_MSG_RESULT($lt_cv_sys_max_cmd_len) else AC_MSG_RESULT(none) fi max_cmd_len=$lt_cv_sys_max_cmd_len _LT_DECL([], [max_cmd_len], [0], [What is the maximum length of a command?]) ]) m4trace:/usr/share/aclocal/libtool.m4:1810: -1- AU_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], [m4_if($#, 0, [LT_CMD_MAX_LEN], [LT_CMD_MAX_LEN($@)])]) m4trace:/usr/share/aclocal/libtool.m4:1810: -1- AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], [AC_DIAGNOSE([obsolete], [The macro `AC_LIBTOOL_SYS_MAX_CMD_LEN' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_CMD_MAX_LEN], [LT_CMD_MAX_LEN($@)])]) m4trace:/usr/share/aclocal/libtool.m4:1921: -1- AC_DEFUN([LT_SYS_DLOPEN_SELF], [m4_require([_LT_HEADER_DLFCN])dnl if test yes != "$enable_dlopen"; then enable_dlopen=unknown enable_dlopen_self=unknown enable_dlopen_self_static=unknown else lt_cv_dlopen=no lt_cv_dlopen_libs= case $host_os in beos*) lt_cv_dlopen=load_add_on lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ;; mingw* | pw32* | cegcc*) lt_cv_dlopen=LoadLibrary lt_cv_dlopen_libs= ;; cygwin*) lt_cv_dlopen=dlopen lt_cv_dlopen_libs= ;; darwin*) # if libdl is installed we need to link against it AC_CHECK_LIB([dl], [dlopen], [lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl],[ lt_cv_dlopen=dyld lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ]) ;; tpf*) # Don't try to run any link tests for TPF. We know it's impossible # because TPF is a cross-compiler, and we know how we open DSOs. lt_cv_dlopen=dlopen lt_cv_dlopen_libs= lt_cv_dlopen_self=no ;; *) AC_CHECK_FUNC([shl_load], [lt_cv_dlopen=shl_load], [AC_CHECK_LIB([dld], [shl_load], [lt_cv_dlopen=shl_load lt_cv_dlopen_libs=-ldld], [AC_CHECK_FUNC([dlopen], [lt_cv_dlopen=dlopen], [AC_CHECK_LIB([dl], [dlopen], [lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl], [AC_CHECK_LIB([svld], [dlopen], [lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-lsvld], [AC_CHECK_LIB([dld], [dld_link], [lt_cv_dlopen=dld_link lt_cv_dlopen_libs=-ldld]) ]) ]) ]) ]) ]) ;; esac if test no = "$lt_cv_dlopen"; then enable_dlopen=no else enable_dlopen=yes fi case $lt_cv_dlopen in dlopen) save_CPPFLAGS=$CPPFLAGS test yes = "$ac_cv_header_dlfcn_h" && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" save_LDFLAGS=$LDFLAGS wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" save_LIBS=$LIBS LIBS="$lt_cv_dlopen_libs $LIBS" AC_CACHE_CHECK([whether a program can dlopen itself], lt_cv_dlopen_self, [dnl _LT_TRY_DLOPEN_SELF( lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes, lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross) ]) if test yes = "$lt_cv_dlopen_self"; then wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" AC_CACHE_CHECK([whether a statically linked program can dlopen itself], lt_cv_dlopen_self_static, [dnl _LT_TRY_DLOPEN_SELF( lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=no, lt_cv_dlopen_self_static=cross) ]) fi CPPFLAGS=$save_CPPFLAGS LDFLAGS=$save_LDFLAGS LIBS=$save_LIBS ;; esac case $lt_cv_dlopen_self in yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; *) enable_dlopen_self=unknown ;; esac case $lt_cv_dlopen_self_static in yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; *) enable_dlopen_self_static=unknown ;; esac fi _LT_DECL([dlopen_support], [enable_dlopen], [0], [Whether dlopen is supported]) _LT_DECL([dlopen_self], [enable_dlopen_self], [0], [Whether dlopen of programs is supported]) _LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0], [Whether dlopen of statically linked programs is supported]) ]) m4trace:/usr/share/aclocal/libtool.m4:2046: -1- AU_DEFUN([AC_LIBTOOL_DLOPEN_SELF], [m4_if($#, 0, [LT_SYS_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF($@)])]) m4trace:/usr/share/aclocal/libtool.m4:2046: -1- AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], [AC_DIAGNOSE([obsolete], [The macro `AC_LIBTOOL_DLOPEN_SELF' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_SYS_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF($@)])]) m4trace:/usr/share/aclocal/libtool.m4:3167: -1- AC_DEFUN([_LT_PATH_TOOL_PREFIX], [m4_require([_LT_DECL_EGREP])dnl AC_MSG_CHECKING([for $1]) AC_CACHE_VAL(lt_cv_path_MAGIC_CMD, [case $MAGIC_CMD in [[\\/*] | ?:[\\/]*]) lt_cv_path_MAGIC_CMD=$MAGIC_CMD # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD=$MAGIC_CMD lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR dnl $ac_dummy forces splitting on constant user-supplied paths. dnl POSIX.2 word splitting is done only on the output of word expansions, dnl not every word. This closes a longstanding sh security hole. ac_dummy="m4_if([$2], , $PATH, [$2])" for ac_dir in $ac_dummy; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$1"; then lt_cv_path_MAGIC_CMD=$ac_dir/"$1" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD=$lt_cv_path_MAGIC_CMD if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS=$lt_save_ifs MAGIC_CMD=$lt_save_MAGIC_CMD ;; esac]) MAGIC_CMD=$lt_cv_path_MAGIC_CMD if test -n "$MAGIC_CMD"; then AC_MSG_RESULT($MAGIC_CMD) else AC_MSG_RESULT(no) fi _LT_DECL([], [MAGIC_CMD], [0], [Used to examine libraries when file_magic_cmd begins with "file"])dnl ]) m4trace:/usr/share/aclocal/libtool.m4:3229: -1- AU_DEFUN([AC_PATH_TOOL_PREFIX], [m4_if($#, 0, [_LT_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX($@)])]) m4trace:/usr/share/aclocal/libtool.m4:3229: -1- AC_DEFUN([AC_PATH_TOOL_PREFIX], [AC_DIAGNOSE([obsolete], [The macro `AC_PATH_TOOL_PREFIX' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [_LT_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX($@)])]) m4trace:/usr/share/aclocal/libtool.m4:3252: -1- AC_DEFUN([LT_PATH_LD], [AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_PROG_ECHO_BACKSLASH])dnl AC_ARG_WITH([gnu-ld], [AS_HELP_STRING([--with-gnu-ld], [assume the C compiler uses GNU ld @<:@default=no@:>@])], [test no = "$withval" || with_gnu_ld=yes], [with_gnu_ld=no])dnl ac_prog=ld if test yes = "$GCC"; then # Check if gcc -print-prog-name=ld gives a path. AC_MSG_CHECKING([for ld used by $CC]) case $host in *-*-mingw*) # gcc leaves a trailing carriage return, which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [[\\/]]* | ?:[[\\/]]*) re_direlt='/[[^/]][[^/]]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD=$ac_prog ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test yes = "$with_gnu_ld"; then AC_MSG_CHECKING([for GNU ld]) else AC_MSG_CHECKING([for non-GNU ld]) fi AC_CACHE_VAL(lt_cv_path_LD, [if test -z "$LD"; then lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD=$ac_dir/$ac_prog # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in *GNU* | *'with BFD'*) test no != "$with_gnu_ld" && break ;; *) test yes != "$with_gnu_ld" && break ;; esac fi done IFS=$lt_save_ifs else lt_cv_path_LD=$LD # Let the user override the test with a path. fi]) LD=$lt_cv_path_LD if test -n "$LD"; then AC_MSG_RESULT($LD) else AC_MSG_RESULT(no) fi test -z "$LD" && AC_MSG_ERROR([no acceptable ld found in \$PATH]) _LT_PATH_LD_GNU AC_SUBST([LD]) _LT_TAGDECL([], [LD], [1], [The linker used to build libraries]) ]) m4trace:/usr/share/aclocal/libtool.m4:3341: -1- AU_DEFUN([AM_PROG_LD], [m4_if($#, 0, [LT_PATH_LD], [LT_PATH_LD($@)])]) m4trace:/usr/share/aclocal/libtool.m4:3341: -1- AC_DEFUN([AM_PROG_LD], [AC_DIAGNOSE([obsolete], [The macro `AM_PROG_LD' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_PATH_LD], [LT_PATH_LD($@)])]) m4trace:/usr/share/aclocal/libtool.m4:3342: -1- AU_DEFUN([AC_PROG_LD], [m4_if($#, 0, [LT_PATH_LD], [LT_PATH_LD($@)])]) m4trace:/usr/share/aclocal/libtool.m4:3342: -1- AC_DEFUN([AC_PROG_LD], [AC_DIAGNOSE([obsolete], [The macro `AC_PROG_LD' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_PATH_LD], [LT_PATH_LD($@)])]) m4trace:/usr/share/aclocal/libtool.m4:3671: -1- AC_DEFUN([LT_PATH_NM], [AC_REQUIRE([AC_PROG_CC])dnl AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM, [if test -n "$NM"; then # Let the user override the test. lt_cv_path_NM=$NM else lt_nm_to_check=${ac_tool_prefix}nm if test -n "$ac_tool_prefix" && test "$build" = "$host"; then lt_nm_to_check="$lt_nm_to_check nm" fi for lt_tmp_nm in $lt_nm_to_check; do lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. tmp_nm=$ac_dir/$lt_tmp_nm if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext"; then # Check to see if the nm accepts a BSD-compat flag. # Adding the 'sed 1q' prevents false positives on HP-UX, which says: # nm: unknown option "B" ignored # Tru64's nm complains that /dev/null is an invalid object file # MSYS converts /dev/null to NUL, MinGW nm treats NUL as empty case $build_os in mingw*) lt_bad_file=conftest.nm/nofile ;; *) lt_bad_file=/dev/null ;; esac case `"$tmp_nm" -B $lt_bad_file 2>&1 | sed '1q'` in *$lt_bad_file* | *'Invalid file or object type'*) lt_cv_path_NM="$tmp_nm -B" break 2 ;; *) case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in */dev/null*) lt_cv_path_NM="$tmp_nm -p" break 2 ;; *) lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but continue # so that we can try to find one that supports BSD flags ;; esac ;; esac fi done IFS=$lt_save_ifs done : ${lt_cv_path_NM=no} fi]) if test no != "$lt_cv_path_NM"; then NM=$lt_cv_path_NM else # Didn't find any BSD compatible name lister, look for dumpbin. if test -n "$DUMPBIN"; then : # Let the user override the test. else AC_CHECK_TOOLS(DUMPBIN, [dumpbin "link -dump"], :) case `$DUMPBIN -symbols -headers /dev/null 2>&1 | sed '1q'` in *COFF*) DUMPBIN="$DUMPBIN -symbols -headers" ;; *) DUMPBIN=: ;; esac fi AC_SUBST([DUMPBIN]) if test : != "$DUMPBIN"; then NM=$DUMPBIN fi fi test -z "$NM" && NM=nm AC_SUBST([NM]) _LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface], [lt_cv_nm_interface="BSD nm" echo "int some_variable = 0;" > conftest.$ac_ext (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$ac_compile" 2>conftest.err) cat conftest.err >&AS_MESSAGE_LOG_FD (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD) (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) cat conftest.err >&AS_MESSAGE_LOG_FD (eval echo "\"\$as_me:$LINENO: output\"" >&AS_MESSAGE_LOG_FD) cat conftest.out >&AS_MESSAGE_LOG_FD if $GREP 'External.*some_variable' conftest.out > /dev/null; then lt_cv_nm_interface="MS dumpbin" fi rm -f conftest*]) ]) m4trace:/usr/share/aclocal/libtool.m4:3766: -1- AU_DEFUN([AM_PROG_NM], [m4_if($#, 0, [LT_PATH_NM], [LT_PATH_NM($@)])]) m4trace:/usr/share/aclocal/libtool.m4:3766: -1- AC_DEFUN([AM_PROG_NM], [AC_DIAGNOSE([obsolete], [The macro `AM_PROG_NM' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_PATH_NM], [LT_PATH_NM($@)])]) m4trace:/usr/share/aclocal/libtool.m4:3767: -1- AU_DEFUN([AC_PROG_NM], [m4_if($#, 0, [LT_PATH_NM], [LT_PATH_NM($@)])]) m4trace:/usr/share/aclocal/libtool.m4:3767: -1- AC_DEFUN([AC_PROG_NM], [AC_DIAGNOSE([obsolete], [The macro `AC_PROG_NM' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_PATH_NM], [LT_PATH_NM($@)])]) m4trace:/usr/share/aclocal/libtool.m4:3838: -1- AC_DEFUN([_LT_DLL_DEF_P], [dnl test DEF = "`$SED -n dnl -e '\''s/^[[ ]]*//'\'' dnl Strip leading whitespace -e '\''/^\(;.*\)*$/d'\'' dnl Delete empty lines and comments -e '\''s/^\(EXPORTS\|LIBRARY\)\([[ ]].*\)*$/DEF/p'\'' dnl -e q dnl Only consider the first "real" line $1`" dnl ]) m4trace:/usr/share/aclocal/libtool.m4:3852: -1- AC_DEFUN([LT_LIB_M], [AC_REQUIRE([AC_CANONICAL_HOST])dnl LIBM= case $host in *-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-haiku* | *-*-pw32* | *-*-darwin*) # These system don't have libm, or don't need it ;; *-ncr-sysv4.3*) AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM=-lmw) AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm") ;; *) AC_CHECK_LIB(m, cos, LIBM=-lm) ;; esac AC_SUBST([LIBM]) ]) m4trace:/usr/share/aclocal/libtool.m4:3871: -1- AU_DEFUN([AC_CHECK_LIBM], [m4_if($#, 0, [LT_LIB_M], [LT_LIB_M($@)])]) m4trace:/usr/share/aclocal/libtool.m4:3871: -1- AC_DEFUN([AC_CHECK_LIBM], [AC_DIAGNOSE([obsolete], [The macro `AC_CHECK_LIBM' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_LIB_M], [LT_LIB_M($@)])]) m4trace:/usr/share/aclocal/libtool.m4:8141: -1- AC_DEFUN([LT_PROG_GCJ], [m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ], [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ], [AC_CHECK_TOOL(GCJ, gcj,) test set = "${GCJFLAGS+set}" || GCJFLAGS="-g -O2" AC_SUBST(GCJFLAGS)])])[]dnl ]) m4trace:/usr/share/aclocal/libtool.m4:8150: -1- AU_DEFUN([LT_AC_PROG_GCJ], [m4_if($#, 0, [LT_PROG_GCJ], [LT_PROG_GCJ($@)])]) m4trace:/usr/share/aclocal/libtool.m4:8150: -1- AC_DEFUN([LT_AC_PROG_GCJ], [AC_DIAGNOSE([obsolete], [The macro `LT_AC_PROG_GCJ' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_PROG_GCJ], [LT_PROG_GCJ($@)])]) m4trace:/usr/share/aclocal/libtool.m4:8157: -1- AC_DEFUN([LT_PROG_GO], [AC_CHECK_TOOL(GOC, gccgo,) ]) m4trace:/usr/share/aclocal/libtool.m4:8164: -1- AC_DEFUN([LT_PROG_RC], [AC_CHECK_TOOL(RC, windres,) ]) m4trace:/usr/share/aclocal/libtool.m4:8169: -1- AU_DEFUN([LT_AC_PROG_RC], [m4_if($#, 0, [LT_PROG_RC], [LT_PROG_RC($@)])]) m4trace:/usr/share/aclocal/libtool.m4:8169: -1- AC_DEFUN([LT_AC_PROG_RC], [AC_DIAGNOSE([obsolete], [The macro `LT_AC_PROG_RC' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_PROG_RC], [LT_PROG_RC($@)])]) m4trace:/usr/share/aclocal/libtool.m4:8289: -1- AU_DEFUN([LT_AC_PROG_SED], [m4_if($#, 0, [AC_PROG_SED], [AC_PROG_SED($@)])]) m4trace:/usr/share/aclocal/libtool.m4:8289: -1- AC_DEFUN([LT_AC_PROG_SED], [AC_DIAGNOSE([obsolete], [The macro `LT_AC_PROG_SED' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [AC_PROG_SED], [AC_PROG_SED($@)])]) m4trace:/usr/share/aclocal/ltargz.m4:12: -1- AC_DEFUN([LT_FUNC_ARGZ], [ AC_CHECK_HEADERS([argz.h], [], [], [AC_INCLUDES_DEFAULT]) AC_CHECK_TYPES([error_t], [], [AC_DEFINE([error_t], [int], [Define to a type to use for 'error_t' if it is not otherwise available.]) AC_DEFINE([__error_t_defined], [1], [Define so that glibc/gnulib argp.h does not typedef error_t.])], [#if defined(HAVE_ARGZ_H) # include <argz.h> #endif]) LT_ARGZ_H= AC_CHECK_FUNCS([argz_add argz_append argz_count argz_create_sep argz_insert \ argz_next argz_stringify], [], [LT_ARGZ_H=lt__argz.h; AC_LIBOBJ([lt__argz])]) dnl if have system argz functions, allow forced use of dnl libltdl-supplied implementation (and default to do so dnl on "known bad" systems). Could use a runtime check, but dnl (a) detecting malloc issues is notoriously unreliable dnl (b) only known system that declares argz functions, dnl provides them, yet they are broken, is cygwin dnl releases prior to 16-Mar-2007 (1.5.24 and earlier) dnl So, it's more straightforward simply to special case dnl this for known bad systems. AS_IF([test -z "$LT_ARGZ_H"], [AC_CACHE_CHECK( [if argz actually works], [lt_cv_sys_argz_works], [[case $host_os in #( *cygwin*) lt_cv_sys_argz_works=no if test no != "$cross_compiling"; then lt_cv_sys_argz_works="guessing no" else lt_sed_extract_leading_digits='s/^\([0-9\.]*\).*/\1/' save_IFS=$IFS IFS=-. set x `uname -r | sed -e "$lt_sed_extract_leading_digits"` IFS=$save_IFS lt_os_major=${2-0} lt_os_minor=${3-0} lt_os_micro=${4-0} if test 1 -lt "$lt_os_major" \ || { test 1 -eq "$lt_os_major" \ && { test 5 -lt "$lt_os_minor" \ || { test 5 -eq "$lt_os_minor" \ && test 24 -lt "$lt_os_micro"; }; }; }; then lt_cv_sys_argz_works=yes fi fi ;; #( *) lt_cv_sys_argz_works=yes ;; esac]]) AS_IF([test yes = "$lt_cv_sys_argz_works"], [AC_DEFINE([HAVE_WORKING_ARGZ], 1, [This value is set to 1 to indicate that the system argz facility works])], [LT_ARGZ_H=lt__argz.h AC_LIBOBJ([lt__argz])])]) AC_SUBST([LT_ARGZ_H]) ]) m4trace:/usr/share/aclocal/ltdl.m4:16: -1- AC_DEFUN([LT_CONFIG_LTDL_DIR], [AC_BEFORE([$0], [LTDL_INIT]) _$0($*) ]) m4trace:/usr/share/aclocal/ltdl.m4:68: -1- AC_DEFUN([LTDL_CONVENIENCE], [AC_BEFORE([$0], [LTDL_INIT])dnl dnl Although the argument is deprecated and no longer documented, dnl LTDL_CONVENIENCE used to take a DIRECTORY orgument, if we have one dnl here make sure it is the same as any other declaration of libltdl's dnl location! This also ensures lt_ltdl_dir is set when configure.ac is dnl not yet using an explicit LT_CONFIG_LTDL_DIR. m4_ifval([$1], [_LT_CONFIG_LTDL_DIR([$1])])dnl _$0() ]) m4trace:/usr/share/aclocal/ltdl.m4:81: -1- AU_DEFUN([AC_LIBLTDL_CONVENIENCE], [_LT_CONFIG_LTDL_DIR([m4_default([$1], [libltdl])]) _LTDL_CONVENIENCE]) m4trace:/usr/share/aclocal/ltdl.m4:81: -1- AC_DEFUN([AC_LIBLTDL_CONVENIENCE], [AC_DIAGNOSE([obsolete], [The macro `AC_LIBLTDL_CONVENIENCE' is obsolete. You should run autoupdate.])dnl _LT_CONFIG_LTDL_DIR([m4_default([$1], [libltdl])]) _LTDL_CONVENIENCE]) m4trace:/usr/share/aclocal/ltdl.m4:124: -1- AC_DEFUN([LTDL_INSTALLABLE], [AC_BEFORE([$0], [LTDL_INIT])dnl dnl Although the argument is deprecated and no longer documented, dnl LTDL_INSTALLABLE used to take a DIRECTORY orgument, if we have one dnl here make sure it is the same as any other declaration of libltdl's dnl location! This also ensures lt_ltdl_dir is set when configure.ac is dnl not yet using an explicit LT_CONFIG_LTDL_DIR. m4_ifval([$1], [_LT_CONFIG_LTDL_DIR([$1])])dnl _$0() ]) m4trace:/usr/share/aclocal/ltdl.m4:137: -1- AU_DEFUN([AC_LIBLTDL_INSTALLABLE], [_LT_CONFIG_LTDL_DIR([m4_default([$1], [libltdl])]) _LTDL_INSTALLABLE]) m4trace:/usr/share/aclocal/ltdl.m4:137: -1- AC_DEFUN([AC_LIBLTDL_INSTALLABLE], [AC_DIAGNOSE([obsolete], [The macro `AC_LIBLTDL_INSTALLABLE' is obsolete. You should run autoupdate.])dnl _LT_CONFIG_LTDL_DIR([m4_default([$1], [libltdl])]) _LTDL_INSTALLABLE]) m4trace:/usr/share/aclocal/ltdl.m4:213: -1- AC_DEFUN([_LT_LIBOBJ], [ m4_pattern_allow([^_LT_LIBOBJS$]) _LT_LIBOBJS="$_LT_LIBOBJS $1.$ac_objext" ]) m4trace:/usr/share/aclocal/ltdl.m4:226: -1- AC_DEFUN([LTDL_INIT], [dnl Parse OPTIONS _LT_SET_OPTIONS([$0], [$1]) dnl We need to keep our own list of libobjs separate from our parent project, dnl and the easiest way to do that is redefine the AC_LIBOBJs macro while dnl we look for our own LIBOBJs. m4_pushdef([AC_LIBOBJ], m4_defn([_LT_LIBOBJ])) m4_pushdef([AC_LIBSOURCES]) dnl If not otherwise defined, default to the 1.5.x compatible subproject mode: m4_if(_LTDL_MODE, [], [m4_define([_LTDL_MODE], m4_default([$2], [subproject])) m4_if([-1], [m4_bregexp(_LTDL_MODE, [\(subproject\|\(non\)?recursive\)])], [m4_fatal([unknown libltdl mode: ]_LTDL_MODE)])]) AC_ARG_WITH([included_ltdl], [AS_HELP_STRING([--with-included-ltdl], [use the GNU ltdl sources included here])]) if test yes != "$with_included_ltdl"; then # We are not being forced to use the included libltdl sources, so # decide whether there is a useful installed version we can use. AC_CHECK_HEADER([ltdl.h], [AC_CHECK_DECL([lt_dlinterface_register], [AC_CHECK_LIB([ltdl], [lt_dladvise_preload], [with_included_ltdl=no], [with_included_ltdl=yes])], [with_included_ltdl=yes], [AC_INCLUDES_DEFAULT #include <ltdl.h>])], [with_included_ltdl=yes], [AC_INCLUDES_DEFAULT] ) fi dnl If neither LT_CONFIG_LTDL_DIR, LTDL_CONVENIENCE nor LTDL_INSTALLABLE dnl was called yet, then for old times' sake, we assume libltdl is in an dnl eponymous directory: AC_PROVIDE_IFELSE([LT_CONFIG_LTDL_DIR], [], [_LT_CONFIG_LTDL_DIR([libltdl])]) AC_ARG_WITH([ltdl_include], [AS_HELP_STRING([--with-ltdl-include=DIR], [use the ltdl headers installed in DIR])]) if test -n "$with_ltdl_include"; then if test -f "$with_ltdl_include/ltdl.h"; then : else AC_MSG_ERROR([invalid ltdl include directory: '$with_ltdl_include']) fi else with_ltdl_include=no fi AC_ARG_WITH([ltdl_lib], [AS_HELP_STRING([--with-ltdl-lib=DIR], [use the libltdl.la installed in DIR])]) if test -n "$with_ltdl_lib"; then if test -f "$with_ltdl_lib/libltdl.la"; then : else AC_MSG_ERROR([invalid ltdl library directory: '$with_ltdl_lib']) fi else with_ltdl_lib=no fi case ,$with_included_ltdl,$with_ltdl_include,$with_ltdl_lib, in ,yes,no,no,) m4_case(m4_default(_LTDL_TYPE, [convenience]), [convenience], [_LTDL_CONVENIENCE], [installable], [_LTDL_INSTALLABLE], [m4_fatal([unknown libltdl build type: ]_LTDL_TYPE)]) ;; ,no,no,no,) # If the included ltdl is not to be used, then use the # preinstalled libltdl we found. AC_DEFINE([HAVE_LTDL], [1], [Define this if a modern libltdl is already installed]) LIBLTDL=-lltdl LTDLDEPS= LTDLINCL= ;; ,no*,no,*) AC_MSG_ERROR(['--with-ltdl-include' and '--with-ltdl-lib' options must be used together]) ;; *) with_included_ltdl=no LIBLTDL="-L$with_ltdl_lib -lltdl" LTDLDEPS= LTDLINCL=-I$with_ltdl_include ;; esac INCLTDL=$LTDLINCL # Report our decision... AC_MSG_CHECKING([where to find libltdl headers]) AC_MSG_RESULT([$LTDLINCL]) AC_MSG_CHECKING([where to find libltdl library]) AC_MSG_RESULT([$LIBLTDL]) _LTDL_SETUP dnl restore autoconf definition. m4_popdef([AC_LIBOBJ]) m4_popdef([AC_LIBSOURCES]) AC_CONFIG_COMMANDS_PRE([ _ltdl_libobjs= _ltdl_ltlibobjs= if test -n "$_LT_LIBOBJS"; then # Remove the extension. _lt_sed_drop_objext='s/\.o$//;s/\.obj$//' for i in `for i in $_LT_LIBOBJS; do echo "$i"; done | sed "$_lt_sed_drop_objext" | sort -u`; do _ltdl_libobjs="$_ltdl_libobjs $lt_libobj_prefix$i.$ac_objext" _ltdl_ltlibobjs="$_ltdl_ltlibobjs $lt_libobj_prefix$i.lo" done fi AC_SUBST([ltdl_LIBOBJS], [$_ltdl_libobjs]) AC_SUBST([ltdl_LTLIBOBJS], [$_ltdl_ltlibobjs]) ]) # Only expand once: m4_define([LTDL_INIT]) ]) m4trace:/usr/share/aclocal/ltdl.m4:352: -1- AU_DEFUN([AC_LIB_LTDL], [LTDL_INIT($@)]) m4trace:/usr/share/aclocal/ltdl.m4:352: -1- AC_DEFUN([AC_LIB_LTDL], [AC_DIAGNOSE([obsolete], [The macro `AC_LIB_LTDL' is obsolete. You should run autoupdate.])dnl LTDL_INIT($@)]) m4trace:/usr/share/aclocal/ltdl.m4:353: -1- AU_DEFUN([AC_WITH_LTDL], [LTDL_INIT($@)]) m4trace:/usr/share/aclocal/ltdl.m4:353: -1- AC_DEFUN([AC_WITH_LTDL], [AC_DIAGNOSE([obsolete], [The macro `AC_WITH_LTDL' is obsolete. You should run autoupdate.])dnl LTDL_INIT($@)]) m4trace:/usr/share/aclocal/ltdl.m4:354: -1- AU_DEFUN([LT_WITH_LTDL], [LTDL_INIT($@)]) m4trace:/usr/share/aclocal/ltdl.m4:354: -1- AC_DEFUN([LT_WITH_LTDL], [AC_DIAGNOSE([obsolete], [The macro `LT_WITH_LTDL' is obsolete. You should run autoupdate.])dnl LTDL_INIT($@)]) m4trace:/usr/share/aclocal/ltdl.m4:367: -1- AC_DEFUN([_LTDL_SETUP], [AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([LT_SYS_MODULE_EXT])dnl AC_REQUIRE([LT_SYS_MODULE_PATH])dnl AC_REQUIRE([LT_SYS_DLSEARCH_PATH])dnl AC_REQUIRE([LT_LIB_DLLOAD])dnl AC_REQUIRE([LT_SYS_SYMBOL_USCORE])dnl AC_REQUIRE([LT_FUNC_DLSYM_USCORE])dnl AC_REQUIRE([LT_SYS_DLOPEN_DEPLIBS])dnl AC_REQUIRE([LT_FUNC_ARGZ])dnl m4_require([_LT_CHECK_OBJDIR])dnl m4_require([_LT_HEADER_DLFCN])dnl m4_require([_LT_CHECK_DLPREOPEN])dnl m4_require([_LT_DECL_SED])dnl dnl Don't require this, or it will be expanded earlier than the code dnl that sets the variables it relies on: _LT_ENABLE_INSTALL dnl _LTDL_MODE specific code must be called at least once: _LTDL_MODE_DISPATCH # In order that ltdl.c can compile, find out the first AC_CONFIG_HEADERS # the user used. This is so that ltdl.h can pick up the parent projects # config.h file, The first file in AC_CONFIG_HEADERS must contain the # definitions required by ltdl.c. # FIXME: Remove use of undocumented AC_LIST_HEADERS (2.59 compatibility). AC_CONFIG_COMMANDS_PRE([dnl m4_pattern_allow([^LT_CONFIG_H$])dnl m4_ifset([AH_HEADER], [LT_CONFIG_H=AH_HEADER], [m4_ifset([AC_LIST_HEADERS], [LT_CONFIG_H=`echo "AC_LIST_HEADERS" | $SED 's|^[[ ]]*||;s|[[ :]].*$||'`], [])])]) AC_SUBST([LT_CONFIG_H]) AC_CHECK_HEADERS([unistd.h dl.h sys/dl.h dld.h mach-o/dyld.h dirent.h], [], [], [AC_INCLUDES_DEFAULT]) AC_CHECK_FUNCS([closedir opendir readdir], [], [AC_LIBOBJ([lt__dirent])]) AC_CHECK_FUNCS([strlcat strlcpy], [], [AC_LIBOBJ([lt__strl])]) m4_pattern_allow([LT_LIBEXT])dnl AC_DEFINE_UNQUOTED([LT_LIBEXT],["$libext"],[The archive extension]) name= eval "lt_libprefix=\"$libname_spec\"" m4_pattern_allow([LT_LIBPREFIX])dnl AC_DEFINE_UNQUOTED([LT_LIBPREFIX],["$lt_libprefix"],[The archive prefix]) name=ltdl eval "LTDLOPEN=\"$libname_spec\"" AC_SUBST([LTDLOPEN]) ]) m4trace:/usr/share/aclocal/ltdl.m4:443: -1- AC_DEFUN([LT_SYS_DLOPEN_DEPLIBS], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_CACHE_CHECK([whether deplibs are loaded by dlopen], [lt_cv_sys_dlopen_deplibs], [# PORTME does your system automatically load deplibs for dlopen? # or its logical equivalent (e.g. shl_load for HP-UX < 11) # For now, we just catch OSes we know something about -- in the # future, we'll try test this programmatically. lt_cv_sys_dlopen_deplibs=unknown case $host_os in aix3*|aix4.1.*|aix4.2.*) # Unknown whether this is true for these versions of AIX, but # we want this 'case' here to explicitly catch those versions. lt_cv_sys_dlopen_deplibs=unknown ;; aix[[4-9]]*) lt_cv_sys_dlopen_deplibs=yes ;; amigaos*) case $host_cpu in powerpc) lt_cv_sys_dlopen_deplibs=no ;; esac ;; bitrig*) lt_cv_sys_dlopen_deplibs=yes ;; darwin*) # Assuming the user has installed a libdl from somewhere, this is true # If you are looking for one http://www.opendarwin.org/projects/dlcompat lt_cv_sys_dlopen_deplibs=yes ;; freebsd* | dragonfly*) lt_cv_sys_dlopen_deplibs=yes ;; gnu* | linux* | k*bsd*-gnu | kopensolaris*-gnu) # GNU and its variants, using gnu ld.so (Glibc) lt_cv_sys_dlopen_deplibs=yes ;; hpux10*|hpux11*) lt_cv_sys_dlopen_deplibs=yes ;; interix*) lt_cv_sys_dlopen_deplibs=yes ;; irix[[12345]]*|irix6.[[01]]*) # Catch all versions of IRIX before 6.2, and indicate that we don't # know how it worked for any of those versions. lt_cv_sys_dlopen_deplibs=unknown ;; irix*) # The case above catches anything before 6.2, and it's known that # at 6.2 and later dlopen does load deplibs. lt_cv_sys_dlopen_deplibs=yes ;; netbsd* | netbsdelf*-gnu) lt_cv_sys_dlopen_deplibs=yes ;; openbsd*) lt_cv_sys_dlopen_deplibs=yes ;; osf[[1234]]*) # dlopen did load deplibs (at least at 4.x), but until the 5.x series, # it did *not* use an RPATH in a shared library to find objects the # library depends on, so we explicitly say 'no'. lt_cv_sys_dlopen_deplibs=no ;; osf5.0|osf5.0a|osf5.1) # dlopen *does* load deplibs and with the right loader patch applied # it even uses RPATH in a shared library to search for shared objects # that the library depends on, but there's no easy way to know if that # patch is installed. Since this is the case, all we can really # say is unknown -- it depends on the patch being installed. If # it is, this changes to 'yes'. Without it, it would be 'no'. lt_cv_sys_dlopen_deplibs=unknown ;; osf*) # the two cases above should catch all versions of osf <= 5.1. Read # the comments above for what we know about them. # At > 5.1, deplibs are loaded *and* any RPATH in a shared library # is used to find them so we can finally say 'yes'. lt_cv_sys_dlopen_deplibs=yes ;; qnx*) lt_cv_sys_dlopen_deplibs=yes ;; solaris*) lt_cv_sys_dlopen_deplibs=yes ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) libltdl_cv_sys_dlopen_deplibs=yes ;; esac ]) if test yes != "$lt_cv_sys_dlopen_deplibs"; then AC_DEFINE([LTDL_DLOPEN_DEPLIBS], [1], [Define if the OS needs help to load dependent libraries for dlopen().]) fi ]) m4trace:/usr/share/aclocal/ltdl.m4:545: -1- AU_DEFUN([AC_LTDL_SYS_DLOPEN_DEPLIBS], [m4_if($#, 0, [LT_SYS_DLOPEN_DEPLIBS], [LT_SYS_DLOPEN_DEPLIBS($@)])]) m4trace:/usr/share/aclocal/ltdl.m4:545: -1- AC_DEFUN([AC_LTDL_SYS_DLOPEN_DEPLIBS], [AC_DIAGNOSE([obsolete], [The macro `AC_LTDL_SYS_DLOPEN_DEPLIBS' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_SYS_DLOPEN_DEPLIBS], [LT_SYS_DLOPEN_DEPLIBS($@)])]) m4trace:/usr/share/aclocal/ltdl.m4:552: -1- AC_DEFUN([LT_SYS_MODULE_EXT], [m4_require([_LT_SYS_DYNAMIC_LINKER])dnl AC_CACHE_CHECK([what extension is used for runtime loadable modules], [libltdl_cv_shlibext], [ module=yes eval libltdl_cv_shlibext=$shrext_cmds module=no eval libltdl_cv_shrext=$shrext_cmds ]) if test -n "$libltdl_cv_shlibext"; then m4_pattern_allow([LT_MODULE_EXT])dnl AC_DEFINE_UNQUOTED([LT_MODULE_EXT], ["$libltdl_cv_shlibext"], [Define to the extension used for runtime loadable modules, say, ".so".]) fi if test "$libltdl_cv_shrext" != "$libltdl_cv_shlibext"; then m4_pattern_allow([LT_SHARED_EXT])dnl AC_DEFINE_UNQUOTED([LT_SHARED_EXT], ["$libltdl_cv_shrext"], [Define to the shared library suffix, say, ".dylib".]) fi if test -n "$shared_archive_member_spec"; then m4_pattern_allow([LT_SHARED_LIB_MEMBER])dnl AC_DEFINE_UNQUOTED([LT_SHARED_LIB_MEMBER], ["($shared_archive_member_spec.o)"], [Define to the shared archive member specification, say "(shr.o)".]) fi ]) m4trace:/usr/share/aclocal/ltdl.m4:580: -1- AU_DEFUN([AC_LTDL_SHLIBEXT], [m4_if($#, 0, [LT_SYS_MODULE_EXT], [LT_SYS_MODULE_EXT($@)])]) m4trace:/usr/share/aclocal/ltdl.m4:580: -1- AC_DEFUN([AC_LTDL_SHLIBEXT], [AC_DIAGNOSE([obsolete], [The macro `AC_LTDL_SHLIBEXT' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_SYS_MODULE_EXT], [LT_SYS_MODULE_EXT($@)])]) m4trace:/usr/share/aclocal/ltdl.m4:587: -1- AC_DEFUN([LT_SYS_MODULE_PATH], [m4_require([_LT_SYS_DYNAMIC_LINKER])dnl AC_CACHE_CHECK([what variable specifies run-time module search path], [lt_cv_module_path_var], [lt_cv_module_path_var=$shlibpath_var]) if test -n "$lt_cv_module_path_var"; then m4_pattern_allow([LT_MODULE_PATH_VAR])dnl AC_DEFINE_UNQUOTED([LT_MODULE_PATH_VAR], ["$lt_cv_module_path_var"], [Define to the name of the environment variable that determines the run-time module search path.]) fi ]) m4trace:/usr/share/aclocal/ltdl.m4:599: -1- AU_DEFUN([AC_LTDL_SHLIBPATH], [m4_if($#, 0, [LT_SYS_MODULE_PATH], [LT_SYS_MODULE_PATH($@)])]) m4trace:/usr/share/aclocal/ltdl.m4:599: -1- AC_DEFUN([AC_LTDL_SHLIBPATH], [AC_DIAGNOSE([obsolete], [The macro `AC_LTDL_SHLIBPATH' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_SYS_MODULE_PATH], [LT_SYS_MODULE_PATH($@)])]) m4trace:/usr/share/aclocal/ltdl.m4:606: -1- AC_DEFUN([LT_SYS_DLSEARCH_PATH], [m4_require([_LT_SYS_DYNAMIC_LINKER])dnl AC_CACHE_CHECK([for the default library search path], [lt_cv_sys_dlsearch_path], [lt_cv_sys_dlsearch_path=$sys_lib_dlsearch_path_spec]) if test -n "$lt_cv_sys_dlsearch_path"; then sys_dlsearch_path= for dir in $lt_cv_sys_dlsearch_path; do if test -z "$sys_dlsearch_path"; then sys_dlsearch_path=$dir else sys_dlsearch_path=$sys_dlsearch_path$PATH_SEPARATOR$dir fi done m4_pattern_allow([LT_DLSEARCH_PATH])dnl AC_DEFINE_UNQUOTED([LT_DLSEARCH_PATH], ["$sys_dlsearch_path"], [Define to the system default library search path.]) fi ]) m4trace:/usr/share/aclocal/ltdl.m4:627: -1- AU_DEFUN([AC_LTDL_SYSSEARCHPATH], [m4_if($#, 0, [LT_SYS_DLSEARCH_PATH], [LT_SYS_DLSEARCH_PATH($@)])]) m4trace:/usr/share/aclocal/ltdl.m4:627: -1- AC_DEFUN([AC_LTDL_SYSSEARCHPATH], [AC_DIAGNOSE([obsolete], [The macro `AC_LTDL_SYSSEARCHPATH' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_SYS_DLSEARCH_PATH], [LT_SYS_DLSEARCH_PATH($@)])]) m4trace:/usr/share/aclocal/ltdl.m4:653: -1- AC_DEFUN([LT_LIB_DLLOAD], [m4_pattern_allow([^LT_DLLOADERS$]) LT_DLLOADERS= AC_SUBST([LT_DLLOADERS]) AC_LANG_PUSH([C]) lt_dlload_save_LIBS=$LIBS LIBADD_DLOPEN= AC_SEARCH_LIBS([dlopen], [dl], [AC_DEFINE([HAVE_LIBDL], [1], [Define if you have the libdl library or equivalent.]) if test "$ac_cv_search_dlopen" != "none required"; then LIBADD_DLOPEN=-ldl fi libltdl_cv_lib_dl_dlopen=yes LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}dlopen.la"], [AC_LINK_IFELSE([AC_LANG_PROGRAM([[#if HAVE_DLFCN_H # include <dlfcn.h> #endif ]], [[dlopen(0, 0);]])], [AC_DEFINE([HAVE_LIBDL], [1], [Define if you have the libdl library or equivalent.]) libltdl_cv_func_dlopen=yes LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}dlopen.la"], [AC_CHECK_LIB([svld], [dlopen], [AC_DEFINE([HAVE_LIBDL], [1], [Define if you have the libdl library or equivalent.]) LIBADD_DLOPEN=-lsvld libltdl_cv_func_dlopen=yes LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}dlopen.la"])])]) if test yes = "$libltdl_cv_func_dlopen" || test yes = "$libltdl_cv_lib_dl_dlopen" then lt_save_LIBS=$LIBS LIBS="$LIBS $LIBADD_DLOPEN" AC_CHECK_FUNCS([dlerror]) LIBS=$lt_save_LIBS fi AC_SUBST([LIBADD_DLOPEN]) LIBADD_SHL_LOAD= AC_CHECK_FUNC([shl_load], [AC_DEFINE([HAVE_SHL_LOAD], [1], [Define if you have the shl_load function.]) LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}shl_load.la"], [AC_CHECK_LIB([dld], [shl_load], [AC_DEFINE([HAVE_SHL_LOAD], [1], [Define if you have the shl_load function.]) LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}shl_load.la" LIBADD_SHL_LOAD=-ldld])]) AC_SUBST([LIBADD_SHL_LOAD]) case $host_os in darwin[[1567]].*) # We only want this for pre-Mac OS X 10.4. AC_CHECK_FUNC([_dyld_func_lookup], [AC_DEFINE([HAVE_DYLD], [1], [Define if you have the _dyld_func_lookup function.]) LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}dyld.la"]) ;; beos*) LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}load_add_on.la" ;; cygwin* | mingw* | pw32*) AC_CHECK_DECLS([cygwin_conv_path], [], [], [[#include <sys/cygwin.h>]]) LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}loadlibrary.la" ;; esac AC_CHECK_LIB([dld], [dld_link], [AC_DEFINE([HAVE_DLD], [1], [Define if you have the GNU dld library.]) LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}dld_link.la"]) AC_SUBST([LIBADD_DLD_LINK]) m4_pattern_allow([^LT_DLPREOPEN$]) LT_DLPREOPEN= if test -n "$LT_DLLOADERS" then for lt_loader in $LT_DLLOADERS; do LT_DLPREOPEN="$LT_DLPREOPEN-dlpreopen $lt_loader " done AC_DEFINE([HAVE_LIBDLLOADER], [1], [Define if libdlloader will be built on this platform]) fi AC_SUBST([LT_DLPREOPEN]) dnl This isn't used anymore, but set it for backwards compatibility LIBADD_DL="$LIBADD_DLOPEN $LIBADD_SHL_LOAD" AC_SUBST([LIBADD_DL]) LIBS=$lt_dlload_save_LIBS AC_LANG_POP ]) m4trace:/usr/share/aclocal/ltdl.m4:748: -1- AU_DEFUN([AC_LTDL_DLLIB], [m4_if($#, 0, [LT_LIB_DLLOAD], [LT_LIB_DLLOAD($@)])]) m4trace:/usr/share/aclocal/ltdl.m4:748: -1- AC_DEFUN([AC_LTDL_DLLIB], [AC_DIAGNOSE([obsolete], [The macro `AC_LTDL_DLLIB' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_LIB_DLLOAD], [LT_LIB_DLLOAD($@)])]) m4trace:/usr/share/aclocal/ltdl.m4:756: -1- AC_DEFUN([LT_SYS_SYMBOL_USCORE], [m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl AC_CACHE_CHECK([for _ prefix in compiled symbols], [lt_cv_sys_symbol_underscore], [lt_cv_sys_symbol_underscore=no cat > conftest.$ac_ext <<_LT_EOF void nm_test_func(){} int main(){nm_test_func;return 0;} _LT_EOF if AC_TRY_EVAL(ac_compile); then # Now try to grab the symbols. ac_nlist=conftest.nm if AC_TRY_EVAL(NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $ac_nlist) && test -s "$ac_nlist"; then # See whether the symbols have a leading underscore. if grep '^. _nm_test_func' "$ac_nlist" >/dev/null; then lt_cv_sys_symbol_underscore=yes else if grep '^. nm_test_func ' "$ac_nlist" >/dev/null; then : else echo "configure: cannot find nm_test_func in $ac_nlist" >&AS_MESSAGE_LOG_FD fi fi else echo "configure: cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD fi else echo "configure: failed program was:" >&AS_MESSAGE_LOG_FD cat conftest.c >&AS_MESSAGE_LOG_FD fi rm -rf conftest* ]) sys_symbol_underscore=$lt_cv_sys_symbol_underscore AC_SUBST([sys_symbol_underscore]) ]) m4trace:/usr/share/aclocal/ltdl.m4:793: -1- AU_DEFUN([AC_LTDL_SYMBOL_USCORE], [m4_if($#, 0, [LT_SYS_SYMBOL_USCORE], [LT_SYS_SYMBOL_USCORE($@)])]) m4trace:/usr/share/aclocal/ltdl.m4:793: -1- AC_DEFUN([AC_LTDL_SYMBOL_USCORE], [AC_DIAGNOSE([obsolete], [The macro `AC_LTDL_SYMBOL_USCORE' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_SYS_SYMBOL_USCORE], [LT_SYS_SYMBOL_USCORE($@)])]) m4trace:/usr/share/aclocal/ltdl.m4:800: -1- AC_DEFUN([LT_FUNC_DLSYM_USCORE], [AC_REQUIRE([_LT_COMPILER_PIC])dnl for lt_prog_compiler_wl AC_REQUIRE([LT_SYS_SYMBOL_USCORE])dnl for lt_cv_sys_symbol_underscore AC_REQUIRE([LT_SYS_MODULE_EXT])dnl for libltdl_cv_shlibext if test yes = "$lt_cv_sys_symbol_underscore"; then if test yes = "$libltdl_cv_func_dlopen" || test yes = "$libltdl_cv_lib_dl_dlopen"; then AC_CACHE_CHECK([whether we have to add an underscore for dlsym], [libltdl_cv_need_uscore], [libltdl_cv_need_uscore=unknown dlsym_uscore_save_LIBS=$LIBS LIBS="$LIBS $LIBADD_DLOPEN" libname=conftmod # stay within 8.3 filename limits! cat >$libname.$ac_ext <<_LT_EOF [#line $LINENO "configure" #include "confdefs.h" /* When -fvisibility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined __GNUC__ && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; }] _LT_EOF # ltfn_module_cmds module_cmds # Execute tilde-delimited MODULE_CMDS with environment primed for # $module_cmds or $archive_cmds type content. ltfn_module_cmds () {( # subshell avoids polluting parent global environment module_cmds_save_ifs=$IFS; IFS='~' for cmd in @S|@1; do IFS=$module_cmds_save_ifs libobjs=$libname.$ac_objext; lib=$libname$libltdl_cv_shlibext rpath=/not-exists; soname=$libname$libltdl_cv_shlibext; output_objdir=. major=; versuffix=; verstring=; deplibs= ECHO=echo; wl=$lt_prog_compiler_wl; allow_undefined_flag= eval $cmd done IFS=$module_cmds_save_ifs )} # Compile a loadable module using libtool macro expansion results. $CC $pic_flag -c $libname.$ac_ext ltfn_module_cmds "${module_cmds:-$archive_cmds}" # Try to fetch fnord with dlsym(). libltdl_dlunknown=0; libltdl_dlnouscore=1; libltdl_dluscore=2 cat >conftest.$ac_ext <<_LT_EOF [#line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include <dlfcn.h> #endif #include <stdio.h> #ifndef RTLD_GLOBAL # ifdef DL_GLOBAL # define RTLD_GLOBAL DL_GLOBAL # else # define RTLD_GLOBAL 0 # endif #endif #ifndef RTLD_NOW # ifdef DL_NOW # define RTLD_NOW DL_NOW # else # define RTLD_NOW 0 # endif #endif int main () { void *handle = dlopen ("`pwd`/$libname$libltdl_cv_shlibext", RTLD_GLOBAL|RTLD_NOW); int status = $libltdl_dlunknown; if (handle) { if (dlsym (handle, "fnord")) status = $libltdl_dlnouscore; else { if (dlsym (handle, "_fnord")) status = $libltdl_dluscore; else puts (dlerror ()); } dlclose (handle); } else puts (dlerror ()); return status; }] _LT_EOF if AC_TRY_EVAL(ac_link) && test -s "conftest$ac_exeext" 2>/dev/null; then (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null libltdl_status=$? case x$libltdl_status in x$libltdl_dlnouscore) libltdl_cv_need_uscore=no ;; x$libltdl_dluscore) libltdl_cv_need_uscore=yes ;; x*) libltdl_cv_need_uscore=unknown ;; esac fi rm -rf conftest* $libname* LIBS=$dlsym_uscore_save_LIBS ]) fi fi if test yes = "$libltdl_cv_need_uscore"; then AC_DEFINE([NEED_USCORE], [1], [Define if dlsym() requires a leading underscore in symbol names.]) fi ]) m4trace:/usr/share/aclocal/ltdl.m4:907: -1- AU_DEFUN([AC_LTDL_DLSYM_USCORE], [m4_if($#, 0, [LT_FUNC_DLSYM_USCORE], [LT_FUNC_DLSYM_USCORE($@)])]) m4trace:/usr/share/aclocal/ltdl.m4:907: -1- AC_DEFUN([AC_LTDL_DLSYM_USCORE], [AC_DIAGNOSE([obsolete], [The macro `AC_LTDL_DLSYM_USCORE' is obsolete. You should run autoupdate.])dnl m4_if($#, 0, [LT_FUNC_DLSYM_USCORE], [LT_FUNC_DLSYM_USCORE($@)])]) m4trace:/usr/share/aclocal/ltoptions.m4:14: -1- AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])]) m4trace:/usr/share/aclocal/ltoptions.m4:113: -1- AU_DEFUN([AC_LIBTOOL_DLOPEN], [_LT_SET_OPTION([LT_INIT], [dlopen]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'dlopen' option into LT_INIT's first parameter.]) ]) m4trace:/usr/share/aclocal/ltoptions.m4:113: -1- AC_DEFUN([AC_LIBTOOL_DLOPEN], [AC_DIAGNOSE([obsolete], [The macro `AC_LIBTOOL_DLOPEN' is obsolete. You should run autoupdate.])dnl _LT_SET_OPTION([LT_INIT], [dlopen]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'dlopen' option into LT_INIT's first parameter.]) ]) m4trace:/usr/share/aclocal/ltoptions.m4:148: -1- AU_DEFUN([AC_LIBTOOL_WIN32_DLL], [AC_REQUIRE([AC_CANONICAL_HOST])dnl _LT_SET_OPTION([LT_INIT], [win32-dll]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'win32-dll' option into LT_INIT's first parameter.]) ]) m4trace:/usr/share/aclocal/ltoptions.m4:148: -1- AC_DEFUN([AC_LIBTOOL_WIN32_DLL], [AC_DIAGNOSE([obsolete], [The macro `AC_LIBTOOL_WIN32_DLL' is obsolete. You should run autoupdate.])dnl AC_REQUIRE([AC_CANONICAL_HOST])dnl _LT_SET_OPTION([LT_INIT], [win32-dll]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'win32-dll' option into LT_INIT's first parameter.]) ]) m4trace:/usr/share/aclocal/ltoptions.m4:197: -1- AC_DEFUN([AC_ENABLE_SHARED], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared]) ]) m4trace:/usr/share/aclocal/ltoptions.m4:201: -1- AC_DEFUN([AC_DISABLE_SHARED], [_LT_SET_OPTION([LT_INIT], [disable-shared]) ]) m4trace:/usr/share/aclocal/ltoptions.m4:205: -1- AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)]) m4trace:/usr/share/aclocal/ltoptions.m4:205: -1- AC_DEFUN([AM_ENABLE_SHARED], [AC_DIAGNOSE([obsolete], [The macro `AM_ENABLE_SHARED' is obsolete. You should run autoupdate.])dnl AC_ENABLE_SHARED($@)]) m4trace:/usr/share/aclocal/ltoptions.m4:206: -1- AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)]) m4trace:/usr/share/aclocal/ltoptions.m4:206: -1- AC_DEFUN([AM_DISABLE_SHARED], [AC_DIAGNOSE([obsolete], [The macro `AM_DISABLE_SHARED' is obsolete. You should run autoupdate.])dnl AC_DISABLE_SHARED($@)]) m4trace:/usr/share/aclocal/ltoptions.m4:251: -1- AC_DEFUN([AC_ENABLE_STATIC], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static]) ]) m4trace:/usr/share/aclocal/ltoptions.m4:255: -1- AC_DEFUN([AC_DISABLE_STATIC], [_LT_SET_OPTION([LT_INIT], [disable-static]) ]) m4trace:/usr/share/aclocal/ltoptions.m4:259: -1- AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)]) m4trace:/usr/share/aclocal/ltoptions.m4:259: -1- AC_DEFUN([AM_ENABLE_STATIC], [AC_DIAGNOSE([obsolete], [The macro `AM_ENABLE_STATIC' is obsolete. You should run autoupdate.])dnl AC_ENABLE_STATIC($@)]) m4trace:/usr/share/aclocal/ltoptions.m4:260: -1- AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)]) m4trace:/usr/share/aclocal/ltoptions.m4:260: -1- AC_DEFUN([AM_DISABLE_STATIC], [AC_DIAGNOSE([obsolete], [The macro `AM_DISABLE_STATIC' is obsolete. You should run autoupdate.])dnl AC_DISABLE_STATIC($@)]) m4trace:/usr/share/aclocal/ltoptions.m4:305: -1- AU_DEFUN([AC_ENABLE_FAST_INSTALL], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'fast-install' option into LT_INIT's first parameter.]) ]) m4trace:/usr/share/aclocal/ltoptions.m4:305: -1- AC_DEFUN([AC_ENABLE_FAST_INSTALL], [AC_DIAGNOSE([obsolete], [The macro `AC_ENABLE_FAST_INSTALL' is obsolete. You should run autoupdate.])dnl _LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'fast-install' option into LT_INIT's first parameter.]) ]) m4trace:/usr/share/aclocal/ltoptions.m4:312: -1- AU_DEFUN([AC_DISABLE_FAST_INSTALL], [_LT_SET_OPTION([LT_INIT], [disable-fast-install]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'disable-fast-install' option into LT_INIT's first parameter.]) ]) m4trace:/usr/share/aclocal/ltoptions.m4:312: -1- AC_DEFUN([AC_DISABLE_FAST_INSTALL], [AC_DIAGNOSE([obsolete], [The macro `AC_DISABLE_FAST_INSTALL' is obsolete. You should run autoupdate.])dnl _LT_SET_OPTION([LT_INIT], [disable-fast-install]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'disable-fast-install' option into LT_INIT's first parameter.]) ]) m4trace:/usr/share/aclocal/ltoptions.m4:411: -1- AU_DEFUN([AC_LIBTOOL_PICMODE], [_LT_SET_OPTION([LT_INIT], [pic-only]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'pic-only' option into LT_INIT's first parameter.]) ]) m4trace:/usr/share/aclocal/ltoptions.m4:411: -1- AC_DEFUN([AC_LIBTOOL_PICMODE], [AC_DIAGNOSE([obsolete], [The macro `AC_LIBTOOL_PICMODE' is obsolete. You should run autoupdate.])dnl _LT_SET_OPTION([LT_INIT], [pic-only]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'pic-only' option into LT_INIT's first parameter.]) ]) m4trace:/usr/share/aclocal/ltsugar.m4:14: -1- AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])]) m4trace:/usr/share/aclocal/ltversion.m4:18: -1- AC_DEFUN([LTVERSION_VERSION], [macro_version='2.4.6' macro_revision='2.4.6' _LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?]) _LT_DECL(, macro_revision, 0) ]) m4trace:/usr/share/aclocal/lt~obsolete.m4:37: -1- AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])]) m4trace:/usr/share/aclocal/lt~obsolete.m4:41: -1- AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH]) m4trace:/usr/share/aclocal/lt~obsolete.m4:42: -1- AC_DEFUN([_LT_AC_SHELL_INIT]) m4trace:/usr/share/aclocal/lt~obsolete.m4:43: -1- AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX]) m4trace:/usr/share/aclocal/lt~obsolete.m4:45: -1- AC_DEFUN([_LT_AC_TAGVAR]) m4trace:/usr/share/aclocal/lt~obsolete.m4:46: -1- AC_DEFUN([AC_LTDL_ENABLE_INSTALL]) m4trace:/usr/share/aclocal/lt~obsolete.m4:47: -1- AC_DEFUN([AC_LTDL_PREOPEN]) m4trace:/usr/share/aclocal/lt~obsolete.m4:48: -1- AC_DEFUN([_LT_AC_SYS_COMPILER]) m4trace:/usr/share/aclocal/lt~obsolete.m4:49: -1- AC_DEFUN([_LT_AC_LOCK]) m4trace:/usr/share/aclocal/lt~obsolete.m4:50: -1- AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE]) m4trace:/usr/share/aclocal/lt~obsolete.m4:51: -1- AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF]) m4trace:/usr/share/aclocal/lt~obsolete.m4:52: -1- AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O]) m4trace:/usr/share/aclocal/lt~obsolete.m4:53: -1- AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS]) m4trace:/usr/share/aclocal/lt~obsolete.m4:54: -1- AC_DEFUN([AC_LIBTOOL_OBJDIR]) m4trace:/usr/share/aclocal/lt~obsolete.m4:55: -1- AC_DEFUN([AC_LTDL_OBJDIR]) m4trace:/usr/share/aclocal/lt~obsolete.m4:56: -1- AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH]) m4trace:/usr/share/aclocal/lt~obsolete.m4:57: -1- AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP]) m4trace:/usr/share/aclocal/lt~obsolete.m4:58: -1- AC_DEFUN([AC_PATH_MAGIC]) m4trace:/usr/share/aclocal/lt~obsolete.m4:59: -1- AC_DEFUN([AC_PROG_LD_GNU]) m4trace:/usr/share/aclocal/lt~obsolete.m4:60: -1- AC_DEFUN([AC_PROG_LD_RELOAD_FLAG]) m4trace:/usr/share/aclocal/lt~obsolete.m4:61: -1- AC_DEFUN([AC_DEPLIBS_CHECK_METHOD]) m4trace:/usr/share/aclocal/lt~obsolete.m4:62: -1- AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI]) m4trace:/usr/share/aclocal/lt~obsolete.m4:63: -1- AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE]) m4trace:/usr/share/aclocal/lt~obsolete.m4:64: -1- AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC]) m4trace:/usr/share/aclocal/lt~obsolete.m4:65: -1- AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS]) m4trace:/usr/share/aclocal/lt~obsolete.m4:66: -1- AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP]) m4trace:/usr/share/aclocal/lt~obsolete.m4:67: -1- AC_DEFUN([LT_AC_PROG_EGREP]) m4trace:/usr/share/aclocal/lt~obsolete.m4:72: -1- AC_DEFUN([_AC_PROG_LIBTOOL]) m4trace:/usr/share/aclocal/lt~obsolete.m4:73: -1- AC_DEFUN([AC_LIBTOOL_SETUP]) m4trace:/usr/share/aclocal/lt~obsolete.m4:74: -1- AC_DEFUN([_LT_AC_CHECK_DLFCN]) m4trace:/usr/share/aclocal/lt~obsolete.m4:75: -1- AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER]) m4trace:/usr/share/aclocal/lt~obsolete.m4:76: -1- AC_DEFUN([_LT_AC_TAGCONFIG]) m4trace:/usr/share/aclocal/lt~obsolete.m4:78: -1- AC_DEFUN([_LT_AC_LANG_CXX]) m4trace:/usr/share/aclocal/lt~obsolete.m4:79: -1- AC_DEFUN([_LT_AC_LANG_F77]) m4trace:/usr/share/aclocal/lt~obsolete.m4:80: -1- AC_DEFUN([_LT_AC_LANG_GCJ]) m4trace:/usr/share/aclocal/lt~obsolete.m4:81: -1- AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG]) m4trace:/usr/share/aclocal/lt~obsolete.m4:82: -1- AC_DEFUN([_LT_AC_LANG_C_CONFIG]) m4trace:/usr/share/aclocal/lt~obsolete.m4:83: -1- AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG]) m4trace:/usr/share/aclocal/lt~obsolete.m4:84: -1- AC_DEFUN([_LT_AC_LANG_CXX_CONFIG]) m4trace:/usr/share/aclocal/lt~obsolete.m4:85: -1- AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG]) m4trace:/usr/share/aclocal/lt~obsolete.m4:86: -1- AC_DEFUN([_LT_AC_LANG_F77_CONFIG]) m4trace:/usr/share/aclocal/lt~obsolete.m4:87: -1- AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG]) m4trace:/usr/share/aclocal/lt~obsolete.m4:88: -1- AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG]) m4trace:/usr/share/aclocal/lt~obsolete.m4:89: -1- AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG]) m4trace:/usr/share/aclocal/lt~obsolete.m4:90: -1- AC_DEFUN([_LT_AC_LANG_RC_CONFIG]) m4trace:/usr/share/aclocal/lt~obsolete.m4:91: -1- AC_DEFUN([AC_LIBTOOL_CONFIG]) m4trace:/usr/share/aclocal/lt~obsolete.m4:92: -1- AC_DEFUN([_LT_AC_FILE_LTDLL_C]) m4trace:/usr/share/aclocal/lt~obsolete.m4:94: -1- AC_DEFUN([_LT_AC_PROG_CXXCPP]) m4trace:/usr/share/aclocal/lt~obsolete.m4:97: -1- AC_DEFUN([_LT_PROG_F77]) m4trace:/usr/share/aclocal/lt~obsolete.m4:98: -1- AC_DEFUN([_LT_PROG_FC]) m4trace:/usr/share/aclocal/lt~obsolete.m4:99: -1- AC_DEFUN([_LT_PROG_CXX]) m4trace:/usr/share/aclocal/pkg.m4:58: -1- AC_DEFUN([PKG_PROG_PKG_CONFIG], [m4_pattern_forbid([^_?PKG_[A-Z_]+$]) m4_pattern_allow([^PKG_CONFIG(_(PATH|LIBDIR|SYSROOT_DIR|ALLOW_SYSTEM_(CFLAGS|LIBS)))?$]) m4_pattern_allow([^PKG_CONFIG_(DISABLE_UNINSTALLED|TOP_BUILD_DIR|DEBUG_SPEW)$]) AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility]) AC_ARG_VAR([PKG_CONFIG_PATH], [directories to add to pkg-config's search path]) AC_ARG_VAR([PKG_CONFIG_LIBDIR], [path overriding pkg-config's built-in search path]) if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then AC_PATH_TOOL([PKG_CONFIG], [pkg-config]) fi if test -n "$PKG_CONFIG"; then _pkg_min_version=m4_default([$1], [0.9.0]) AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version]) if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) PKG_CONFIG="" fi fi[]dnl ]) m4trace:/usr/share/aclocal/pkg.m4:92: -1- AC_DEFUN([PKG_CHECK_EXISTS], [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl if test -n "$PKG_CONFIG" && \ AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then m4_default([$2], [:]) m4_ifvaln([$3], [else $3])dnl fi]) m4trace:/usr/share/aclocal/pkg.m4:121: -1- AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED], [AC_REQUIRE([PKG_PROG_PKG_CONFIG]) if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi[]dnl ]) m4trace:/usr/share/aclocal/pkg.m4:139: -1- AC_DEFUN([PKG_CHECK_MODULES], [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl pkg_failed=no AC_MSG_CHECKING([for $1]) _PKG_CONFIG([$1][_CFLAGS], [cflags], [$2]) _PKG_CONFIG([$1][_LIBS], [libs], [$2]) m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS and $1[]_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details.]) if test $pkg_failed = yes; then AC_MSG_RESULT([no]) _PKG_SHORT_ERRORS_SUPPORTED if test $_pkg_short_errors_supported = yes; then $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "$2" 2>&1` else $1[]_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "$2" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD m4_default([$4], [AC_MSG_ERROR( [Package requirements ($2) were not met: $$1_PKG_ERRORS Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix. _PKG_TEXT])[]dnl ]) elif test $pkg_failed = untried; then AC_MSG_RESULT([no]) m4_default([$4], [AC_MSG_FAILURE( [The pkg-config script could not be found or is too old. Make sure it is in your PATH or set the PKG_CONFIG environment variable to the full path to pkg-config. _PKG_TEXT To get pkg-config, see <http://pkg-config.freedesktop.org/>.])[]dnl ]) else $1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS $1[]_LIBS=$pkg_cv_[]$1[]_LIBS AC_MSG_RESULT([yes]) $3 fi[]dnl ]) m4trace:/usr/share/aclocal/pkg.m4:208: -1- AC_DEFUN([PKG_CHECK_MODULES_STATIC], [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl _save_PKG_CONFIG=$PKG_CONFIG PKG_CONFIG="$PKG_CONFIG --static" PKG_CHECK_MODULES($@) PKG_CONFIG=$_save_PKG_CONFIG[]dnl ]) m4trace:/usr/share/aclocal/pkg.m4:226: -1- AC_DEFUN([PKG_INSTALLDIR], [m4_pushdef([pkg_default], [m4_default([$1], ['${libdir}/pkgconfig'])]) m4_pushdef([pkg_description], [pkg-config installation directory @<:@]pkg_default[@:>@]) AC_ARG_WITH([pkgconfigdir], [AS_HELP_STRING([--with-pkgconfigdir], pkg_description)],, [with_pkgconfigdir=]pkg_default) AC_SUBST([pkgconfigdir], [$with_pkgconfigdir]) m4_popdef([pkg_default]) m4_popdef([pkg_description]) ]) m4trace:/usr/share/aclocal/pkg.m4:248: -1- AC_DEFUN([PKG_NOARCH_INSTALLDIR], [m4_pushdef([pkg_default], [m4_default([$1], ['${datadir}/pkgconfig'])]) m4_pushdef([pkg_description], [pkg-config arch-independent installation directory @<:@]pkg_default[@:>@]) AC_ARG_WITH([noarch-pkgconfigdir], [AS_HELP_STRING([--with-noarch-pkgconfigdir], pkg_description)],, [with_noarch_pkgconfigdir=]pkg_default) AC_SUBST([noarch_pkgconfigdir], [$with_noarch_pkgconfigdir]) m4_popdef([pkg_default]) m4_popdef([pkg_description]) ]) m4trace:/usr/share/aclocal/pkg.m4:267: -1- AC_DEFUN([PKG_CHECK_VAR], [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl AC_ARG_VAR([$1], [value of $3 for $2, overriding pkg-config])dnl _PKG_CONFIG([$1], [variable="][$3]["], [$2]) AS_VAR_COPY([$1], [pkg_cv_][$1]) AS_VAR_IF([$1], [""], [$5], [$4])dnl ]) m4trace:/usr/share/aclocal-1.15/amversion.m4:14: -1- AC_DEFUN([AM_AUTOMAKE_VERSION], [am__api_version='1.15' dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to dnl require some minimum version. Point them to the right macro. m4_if([$1], [1.15], [], [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl ]) m4trace:/usr/share/aclocal-1.15/amversion.m4:33: -1- AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], [AM_AUTOMAKE_VERSION([1.15])dnl m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl _AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))]) m4trace:/usr/share/aclocal-1.15/auxdir.m4:47: -1- AC_DEFUN([AM_AUX_DIR_EXPAND], [AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl # Expand $ac_aux_dir to an absolute path. am_aux_dir=`cd "$ac_aux_dir" && pwd` ]) m4trace:/usr/share/aclocal-1.15/cond.m4:12: -1- AC_DEFUN([AM_CONDITIONAL], [AC_PREREQ([2.52])dnl m4_if([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])], [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl AC_SUBST([$1_TRUE])dnl AC_SUBST([$1_FALSE])dnl _AM_SUBST_NOTMAKE([$1_TRUE])dnl _AM_SUBST_NOTMAKE([$1_FALSE])dnl m4_define([_AM_COND_VALUE_$1], [$2])dnl if $2; then $1_TRUE= $1_FALSE='#' else $1_TRUE='#' $1_FALSE= fi AC_CONFIG_COMMANDS_PRE( [if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then AC_MSG_ERROR([[conditional "$1" was never defined. Usually this means the macro was only invoked conditionally.]]) fi])]) m4trace:/usr/share/aclocal-1.15/depend.m4:26: -1- AC_DEFUN([_AM_DEPENDENCIES], [AC_REQUIRE([AM_SET_DEPDIR])dnl AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl AC_REQUIRE([AM_MAKE_INCLUDE])dnl AC_REQUIRE([AM_DEP_TRACK])dnl m4_if([$1], [CC], [depcc="$CC" am_compiler_list=], [$1], [CXX], [depcc="$CXX" am_compiler_list=], [$1], [OBJC], [depcc="$OBJC" am_compiler_list='gcc3 gcc'], [$1], [OBJCXX], [depcc="$OBJCXX" am_compiler_list='gcc3 gcc'], [$1], [UPC], [depcc="$UPC" am_compiler_list=], [$1], [GCJ], [depcc="$GCJ" am_compiler_list='gcc3 gcc'], [depcc="$$1" am_compiler_list=]) AC_CACHE_CHECK([dependency style of $depcc], [am_cv_$1_dependencies_compiler_type], [if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named 'D' -- because '-MD' means "put the output # in D". rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_$1_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp` fi am__universal=false m4_case([$1], [CC], [case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac], [CXX], [case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac]) for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using ": > sub/conftst$i.h" creates only sub/conftst1.h with # Solaris 10 /bin/sh. echo '/* dummy */' > sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with '-c' and '-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle '-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs. am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # After this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested. if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok '-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_$1_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_$1_dependencies_compiler_type=none fi ]) AC_SUBST([$1DEPMODE], [depmode=$am_cv_$1_dependencies_compiler_type]) AM_CONDITIONAL([am__fastdep$1], [ test "x$enable_dependency_tracking" != xno \ && test "$am_cv_$1_dependencies_compiler_type" = gcc3]) ]) m4trace:/usr/share/aclocal-1.15/depend.m4:163: -1- AC_DEFUN([AM_SET_DEPDIR], [AC_REQUIRE([AM_SET_LEADING_DOT])dnl AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl ]) m4trace:/usr/share/aclocal-1.15/depend.m4:171: -1- AC_DEFUN([AM_DEP_TRACK], [AC_ARG_ENABLE([dependency-tracking], [dnl AS_HELP_STRING( [--enable-dependency-tracking], [do not reject slow dependency extractors]) AS_HELP_STRING( [--disable-dependency-tracking], [speeds up one-time build])]) if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' am__nodep='_no' fi AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno]) AC_SUBST([AMDEPBACKSLASH])dnl _AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl AC_SUBST([am__nodep])dnl _AM_SUBST_NOTMAKE([am__nodep])dnl ]) m4trace:/usr/share/aclocal-1.15/depout.m4:12: -1- AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS], [{ # Older Autoconf quotes --file arguments for eval, but not when files # are listed without --file. Let's play safe and only enable the eval # if we detect the quoting. case $CONFIG_FILES in *\'*) eval set x "$CONFIG_FILES" ;; *) set x $CONFIG_FILES ;; esac shift for mf do # Strip MF so we end up with the name of the file. mf=`echo "$mf" | sed -e 's/:.*$//'` # Check whether this is an Automake generated Makefile or not. # We used to match only the files named 'Makefile.in', but # some people rename them; so instead we look at the file content. # Grep'ing the first line is not enough: some people post-process # each Makefile.in and add a new line on top of each file to say so. # Grep'ing the whole file is not good either: AIX grep has a line # limit of 2048, but all sed's we know have understand at least 4000. if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then dirpart=`AS_DIRNAME("$mf")` else continue fi # Extract the definition of DEPDIR, am__include, and am__quote # from the Makefile without running 'make'. DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` test -z "$DEPDIR" && continue am__include=`sed -n 's/^am__include = //p' < "$mf"` test -z "$am__include" && continue am__quote=`sed -n 's/^am__quote = //p' < "$mf"` # Find all dependency output files, they are included files with # $(DEPDIR) in their names. We invoke sed twice because it is the # simplest approach to changing $(DEPDIR) to its actual value in the # expansion. for file in `sed -n " s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g'`; do # Make sure the directory exists. test -f "$dirpart/$file" && continue fdir=`AS_DIRNAME(["$file"])` AS_MKDIR_P([$dirpart/$fdir]) # echo "creating $dirpart/$file" echo '# dummy' > "$dirpart/$file" done done } ]) m4trace:/usr/share/aclocal-1.15/depout.m4:71: -1- AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS], [AC_CONFIG_COMMANDS([depfiles], [test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS], [AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"]) ]) m4trace:/usr/share/aclocal-1.15/init.m4:29: -1- AC_DEFUN([AM_INIT_AUTOMAKE], [AC_PREREQ([2.65])dnl dnl Autoconf wants to disallow AM_ names. We explicitly allow dnl the ones we care about. m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl AC_REQUIRE([AC_PROG_INSTALL])dnl if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl # test to see if srcdir already configured if test -f $srcdir/config.status; then AC_MSG_ERROR([source directory already configured; run "make distclean" there first]) fi fi # test whether we have cygpath if test -z "$CYGPATH_W"; then if (cygpath --version) >/dev/null 2>/dev/null; then CYGPATH_W='cygpath -w' else CYGPATH_W=echo fi fi AC_SUBST([CYGPATH_W]) # Define the identity of the package. dnl Distinguish between old-style and new-style calls. m4_ifval([$2], [AC_DIAGNOSE([obsolete], [$0: two- and three-arguments forms are deprecated.]) m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl AC_SUBST([PACKAGE], [$1])dnl AC_SUBST([VERSION], [$2])], [_AM_SET_OPTIONS([$1])dnl dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT. m4_if( m4_ifdef([AC_PACKAGE_NAME], [ok]):m4_ifdef([AC_PACKAGE_VERSION], [ok]), [ok:ok],, [m4_fatal([AC_INIT should be called with package and version arguments])])dnl AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl _AM_IF_OPTION([no-define],, [AC_DEFINE_UNQUOTED([PACKAGE], ["$PACKAGE"], [Name of package]) AC_DEFINE_UNQUOTED([VERSION], ["$VERSION"], [Version number of package])])dnl # Some tools Automake needs. AC_REQUIRE([AM_SANITY_CHECK])dnl AC_REQUIRE([AC_ARG_PROGRAM])dnl AM_MISSING_PROG([ACLOCAL], [aclocal-${am__api_version}]) AM_MISSING_PROG([AUTOCONF], [autoconf]) AM_MISSING_PROG([AUTOMAKE], [automake-${am__api_version}]) AM_MISSING_PROG([AUTOHEADER], [autoheader]) AM_MISSING_PROG([MAKEINFO], [makeinfo]) AC_REQUIRE([AM_PROG_INSTALL_SH])dnl AC_REQUIRE([AM_PROG_INSTALL_STRIP])dnl AC_REQUIRE([AC_PROG_MKDIR_P])dnl # For better backward compatibility. To be removed once Automake 1.9.x # dies out for good. For more background, see: # <http://lists.gnu.org/archive/html/automake/2012-07/msg00001.html> # <http://lists.gnu.org/archive/html/automake/2012-07/msg00014.html> AC_SUBST([mkdir_p], ['$(MKDIR_P)']) # We need awk for the "check" target (and possibly the TAP driver). The # system "awk" is bad on some platforms. AC_REQUIRE([AC_PROG_AWK])dnl AC_REQUIRE([AC_PROG_MAKE_SET])dnl AC_REQUIRE([AM_SET_LEADING_DOT])dnl _AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])], [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], [_AM_PROG_TAR([v7])])]) _AM_IF_OPTION([no-dependencies],, [AC_PROVIDE_IFELSE([AC_PROG_CC], [_AM_DEPENDENCIES([CC])], [m4_define([AC_PROG_CC], m4_defn([AC_PROG_CC])[_AM_DEPENDENCIES([CC])])])dnl AC_PROVIDE_IFELSE([AC_PROG_CXX], [_AM_DEPENDENCIES([CXX])], [m4_define([AC_PROG_CXX], m4_defn([AC_PROG_CXX])[_AM_DEPENDENCIES([CXX])])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJC], [_AM_DEPENDENCIES([OBJC])], [m4_define([AC_PROG_OBJC], m4_defn([AC_PROG_OBJC])[_AM_DEPENDENCIES([OBJC])])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJCXX], [_AM_DEPENDENCIES([OBJCXX])], [m4_define([AC_PROG_OBJCXX], m4_defn([AC_PROG_OBJCXX])[_AM_DEPENDENCIES([OBJCXX])])])dnl ]) AC_REQUIRE([AM_SILENT_RULES])dnl dnl The testsuite driver may need to know about EXEEXT, so add the dnl 'am__EXEEXT' conditional if _AM_COMPILER_EXEEXT was seen. This dnl macro is hooked onto _AC_COMPILER_EXEEXT early, see below. AC_CONFIG_COMMANDS_PRE(dnl [m4_provide_if([_AM_COMPILER_EXEEXT], [AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"])])])dnl # POSIX will say in a future version that running "rm -f" with no argument # is OK; and we want to be able to make that assumption in our Makefile # recipes. So use an aggressive probe to check that the usage we want is # actually supported "in the wild" to an acceptable degree. # See automake bug#10828. # To make any issue more visible, cause the running configure to be aborted # by default if the 'rm' program in use doesn't match our expectations; the # user can still override this though. if rm -f && rm -fr && rm -rf; then : OK; else cat >&2 <<'END' Oops! Your 'rm' program seems unable to run without file operands specified on the command line, even when the '-f' option is present. This is contrary to the behaviour of most rm programs out there, and not conforming with the upcoming POSIX standard: <http://austingroupbugs.net/view.php?id=542> Please tell bug-automake@gnu.org about your system, including the value of your $PATH and any error possibly output before this message. This can help us improve future automake versions. END if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then echo 'Configuration will proceed anyway, since you have set the' >&2 echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2 echo >&2 else cat >&2 <<'END' Aborting the configuration process, to ensure you take notice of the issue. You can download and install GNU coreutils to get an 'rm' implementation that behaves properly: <http://www.gnu.org/software/coreutils/>. If you want to complete the configuration process using your problematic 'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM to "yes", and re-run configure. END AC_MSG_ERROR([Your 'rm' program is bad, sorry.]) fi fi dnl The trailing newline in this macro's definition is deliberate, for dnl backward compatibility and to allow trailing 'dnl'-style comments dnl after the AM_INIT_AUTOMAKE invocation. See automake bug#16841. ]) m4trace:/usr/share/aclocal-1.15/init.m4:186: -1- AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK], [# Compute $1's index in $config_headers. _am_arg=$1 _am_stamp_count=1 for _am_header in $config_headers :; do case $_am_header in $_am_arg | $_am_arg:* ) break ;; * ) _am_stamp_count=`expr $_am_stamp_count + 1` ;; esac done echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count]) m4trace:/usr/share/aclocal-1.15/install-sh.m4:11: -1- AC_DEFUN([AM_PROG_INSTALL_SH], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl if test x"${install_sh+set}" != xset; then case $am_aux_dir in *\ * | *\ *) install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; *) install_sh="\${SHELL} $am_aux_dir/install-sh" esac fi AC_SUBST([install_sh])]) m4trace:/usr/share/aclocal-1.15/lead-dot.m4:10: -1- AC_DEFUN([AM_SET_LEADING_DOT], [rm -rf .tst 2>/dev/null mkdir .tst 2>/dev/null if test -d .tst; then am__leading_dot=. else am__leading_dot=_ fi rmdir .tst 2>/dev/null AC_SUBST([am__leading_dot])]) m4trace:/usr/share/aclocal-1.15/make.m4:12: -1- AC_DEFUN([AM_MAKE_INCLUDE], [am_make=${MAKE-make} cat > confinc << 'END' am__doit: @echo this is the am__doit target .PHONY: am__doit END # If we don't find an include directive, just comment out the code. AC_MSG_CHECKING([for style of include used by $am_make]) am__include="#" am__quote= _am_result=none # First try GNU make style include. echo "include confinc" > confmf # Ignore all kinds of additional output from 'make'. case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=include am__quote= _am_result=GNU ;; esac # Now try BSD make style include. if test "$am__include" = "#"; then echo '.include "confinc"' > confmf case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=.include am__quote="\"" _am_result=BSD ;; esac fi AC_SUBST([am__include]) AC_SUBST([am__quote]) AC_MSG_RESULT([$_am_result]) rm -f confinc confmf ]) m4trace:/usr/share/aclocal-1.15/missing.m4:11: -1- AC_DEFUN([AM_MISSING_PROG], [AC_REQUIRE([AM_MISSING_HAS_RUN]) $1=${$1-"${am_missing_run}$2"} AC_SUBST($1)]) m4trace:/usr/share/aclocal-1.15/missing.m4:20: -1- AC_DEFUN([AM_MISSING_HAS_RUN], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl AC_REQUIRE_AUX_FILE([missing])dnl if test x"${MISSING+set}" != xset; then case $am_aux_dir in *\ * | *\ *) MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; *) MISSING="\${SHELL} $am_aux_dir/missing" ;; esac fi # Use eval to expand $SHELL if eval "$MISSING --is-lightweight"; then am_missing_run="$MISSING " else am_missing_run= AC_MSG_WARN(['missing' script is too old or missing]) fi ]) m4trace:/usr/share/aclocal-1.15/options.m4:11: -1- AC_DEFUN([_AM_MANGLE_OPTION], [[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])]) m4trace:/usr/share/aclocal-1.15/options.m4:17: -1- AC_DEFUN([_AM_SET_OPTION], [m4_define(_AM_MANGLE_OPTION([$1]), [1])]) m4trace:/usr/share/aclocal-1.15/options.m4:23: -1- AC_DEFUN([_AM_SET_OPTIONS], [m4_foreach_w([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])]) m4trace:/usr/share/aclocal-1.15/options.m4:29: -1- AC_DEFUN([_AM_IF_OPTION], [m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])]) m4trace:/usr/share/aclocal-1.15/prog-cc-c-o.m4:12: -1- AC_DEFUN([_AM_PROG_CC_C_O], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl AC_REQUIRE_AUX_FILE([compile])dnl AC_LANG_PUSH([C])dnl AC_CACHE_CHECK( [whether $CC understands -c and -o together], [am_cv_prog_cc_c_o], [AC_LANG_CONFTEST([AC_LANG_PROGRAM([])]) # Make sure it works both with $CC and with simple cc. # Following AC_PROG_CC_C_O, we do the test twice because some # compilers refuse to overwrite an existing .o file with -o, # though they will create one. am_cv_prog_cc_c_o=yes for am_i in 1 2; do if AM_RUN_LOG([$CC -c conftest.$ac_ext -o conftest2.$ac_objext]) \ && test -f conftest2.$ac_objext; then : OK else am_cv_prog_cc_c_o=no break fi done rm -f core conftest* unset am_i]) if test "$am_cv_prog_cc_c_o" != yes; then # Losing compiler, so override with the script. # FIXME: It is wrong to rewrite CC. # But if we don't then we get into trouble of one sort or another. # A longer-term fix would be to have automake use am__CC in this case, # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)" CC="$am_aux_dir/compile $CC" fi AC_LANG_POP([C])]) m4trace:/usr/share/aclocal-1.15/prog-cc-c-o.m4:47: -1- AC_DEFUN_ONCE([AM_PROG_CC_C_O], [AC_REQUIRE([AC_PROG_CC])]) m4trace:/usr/share/aclocal-1.15/runlog.m4:12: -1- AC_DEFUN([AM_RUN_LOG], [{ echo "$as_me:$LINENO: $1" >&AS_MESSAGE_LOG_FD ($1) >&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD (exit $ac_status); }]) m4trace:/usr/share/aclocal-1.15/sanity.m4:11: -1- AC_DEFUN([AM_SANITY_CHECK], [AC_MSG_CHECKING([whether build environment is sane]) # Reject unsafe characters in $srcdir or the absolute working directory # name. Accept space and tab only in the latter. am_lf=' ' case `pwd` in *[[\\\"\#\$\&\'\`$am_lf]]*) AC_MSG_ERROR([unsafe absolute working directory name]);; esac case $srcdir in *[[\\\"\#\$\&\'\`$am_lf\ \ ]]*) AC_MSG_ERROR([unsafe srcdir value: '$srcdir']);; esac # Do 'set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( am_has_slept=no for am_try in 1 2; do echo "timestamp, slept: $am_has_slept" > conftest.file set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` if test "$[*]" = "X"; then # -L didn't work. set X `ls -t "$srcdir/configure" conftest.file` fi if test "$[*]" != "X $srcdir/configure conftest.file" \ && test "$[*]" != "X conftest.file $srcdir/configure"; then # If neither matched, then we have a broken ls. This can happen # if, for instance, CONFIG_SHELL is bash and it inherits a # broken ls alias from the environment. This has actually # happened. Such a system could not be considered "sane". AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken alias in your environment]) fi if test "$[2]" = conftest.file || test $am_try -eq 2; then break fi # Just in case. sleep 1 am_has_slept=yes done test "$[2]" = conftest.file ) then # Ok. : else AC_MSG_ERROR([newly created file is older than distributed files! Check your system clock]) fi AC_MSG_RESULT([yes]) # If we didn't sleep, we still need to ensure time stamps of config.status and # generated files are strictly newer. am_sleep_pid= if grep 'slept: no' conftest.file >/dev/null 2>&1; then ( sleep 1 ) & am_sleep_pid=$! fi AC_CONFIG_COMMANDS_PRE( [AC_MSG_CHECKING([that generated files are newer than configure]) if test -n "$am_sleep_pid"; then # Hide warnings about reused PIDs. wait $am_sleep_pid 2>/dev/null fi AC_MSG_RESULT([done])]) rm -f conftest.file ]) m4trace:/usr/share/aclocal-1.15/silent.m4:12: -1- AC_DEFUN([AM_SILENT_RULES], [AC_ARG_ENABLE([silent-rules], [dnl AS_HELP_STRING( [--enable-silent-rules], [less verbose build output (undo: "make V=1")]) AS_HELP_STRING( [--disable-silent-rules], [verbose build output (undo: "make V=0")])dnl ]) case $enable_silent_rules in @%:@ ((( yes) AM_DEFAULT_VERBOSITY=0;; no) AM_DEFAULT_VERBOSITY=1;; *) AM_DEFAULT_VERBOSITY=m4_if([$1], [yes], [0], [1]);; esac dnl dnl A few 'make' implementations (e.g., NonStop OS and NextStep) dnl do not support nested variable expansions. dnl See automake bug#9928 and bug#10237. am_make=${MAKE-make} AC_CACHE_CHECK([whether $am_make supports nested variables], [am_cv_make_support_nested_variables], [if AS_ECHO([['TRUE=$(BAR$(V)) BAR0=false BAR1=true V=1 am__doit: @$(TRUE) .PHONY: am__doit']]) | $am_make -f - >/dev/null 2>&1; then am_cv_make_support_nested_variables=yes else am_cv_make_support_nested_variables=no fi]) if test $am_cv_make_support_nested_variables = yes; then dnl Using '$V' instead of '$(V)' breaks IRIX make. AM_V='$(V)' AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' else AM_V=$AM_DEFAULT_VERBOSITY AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY fi AC_SUBST([AM_V])dnl AM_SUBST_NOTMAKE([AM_V])dnl AC_SUBST([AM_DEFAULT_V])dnl AM_SUBST_NOTMAKE([AM_DEFAULT_V])dnl AC_SUBST([AM_DEFAULT_VERBOSITY])dnl AM_BACKSLASH='\' AC_SUBST([AM_BACKSLASH])dnl _AM_SUBST_NOTMAKE([AM_BACKSLASH])dnl ]) m4trace:/usr/share/aclocal-1.15/strip.m4:17: -1- AC_DEFUN([AM_PROG_INSTALL_STRIP], [AC_REQUIRE([AM_PROG_INSTALL_SH])dnl # Installed binaries are usually stripped using 'strip' when the user # run "make install-strip". However 'strip' might not be the right # tool to use in cross-compilation environments, therefore Automake # will honor the 'STRIP' environment variable to overrule this program. dnl Don't test for $cross_compiling = yes, because it might be 'maybe'. if test "$cross_compiling" != no; then AC_CHECK_TOOL([STRIP], [strip], :) fi INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" AC_SUBST([INSTALL_STRIP_PROGRAM])]) m4trace:/usr/share/aclocal-1.15/substnot.m4:12: -1- AC_DEFUN([_AM_SUBST_NOTMAKE]) m4trace:/usr/share/aclocal-1.15/substnot.m4:17: -1- AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)]) m4trace:/usr/share/aclocal-1.15/tar.m4:23: -1- AC_DEFUN([_AM_PROG_TAR], [# Always define AMTAR for backward compatibility. Yes, it's still used # in the wild :-( We should find a proper way to deprecate it ... AC_SUBST([AMTAR], ['$${TAR-tar}']) # We'll loop over all known methods to create a tar archive until one works. _am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none' m4_if([$1], [v7], [am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -'], [m4_case([$1], [ustar], [# The POSIX 1988 'ustar' format is defined with fixed-size fields. # There is notably a 21 bits limit for the UID and the GID. In fact, # the 'pax' utility can hang on bigger UID/GID (see automake bug#8343 # and bug#13588). am_max_uid=2097151 # 2^21 - 1 am_max_gid=$am_max_uid # The $UID and $GID variables are not portable, so we need to resort # to the POSIX-mandated id(1) utility. Errors in the 'id' calls # below are definitely unexpected, so allow the users to see them # (that is, avoid stderr redirection). am_uid=`id -u || echo unknown` am_gid=`id -g || echo unknown` AC_MSG_CHECKING([whether UID '$am_uid' is supported by ustar format]) if test $am_uid -le $am_max_uid; then AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) _am_tools=none fi AC_MSG_CHECKING([whether GID '$am_gid' is supported by ustar format]) if test $am_gid -le $am_max_gid; then AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) _am_tools=none fi], [pax], [], [m4_fatal([Unknown tar format])]) AC_MSG_CHECKING([how to create a $1 tar archive]) # Go ahead even if we have the value already cached. We do so because we # need to set the values for the 'am__tar' and 'am__untar' variables. _am_tools=${am_cv_prog_tar_$1-$_am_tools} for _am_tool in $_am_tools; do case $_am_tool in gnutar) for _am_tar in tar gnutar gtar; do AM_RUN_LOG([$_am_tar --version]) && break done am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"' am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"' am__untar="$_am_tar -xf -" ;; plaintar) # Must skip GNU tar: if it does not support --format= it doesn't create # ustar tarball either. (tar --version) >/dev/null 2>&1 && continue am__tar='tar chf - "$$tardir"' am__tar_='tar chf - "$tardir"' am__untar='tar xf -' ;; pax) am__tar='pax -L -x $1 -w "$$tardir"' am__tar_='pax -L -x $1 -w "$tardir"' am__untar='pax -r' ;; cpio) am__tar='find "$$tardir" -print | cpio -o -H $1 -L' am__tar_='find "$tardir" -print | cpio -o -H $1 -L' am__untar='cpio -i -H $1 -d' ;; none) am__tar=false am__tar_=false am__untar=false ;; esac # If the value was cached, stop now. We just wanted to have am__tar # and am__untar set. test -n "${am_cv_prog_tar_$1}" && break # tar/untar a dummy directory, and stop if the command works. rm -rf conftest.dir mkdir conftest.dir echo GrepMe > conftest.dir/file AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar]) rm -rf conftest.dir if test -s conftest.tar; then AM_RUN_LOG([$am__untar <conftest.tar]) AM_RUN_LOG([cat conftest.dir/file]) grep GrepMe conftest.dir/file >/dev/null 2>&1 && break fi done rm -rf conftest.dir AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool]) AC_MSG_RESULT([$am_cv_prog_tar_$1])]) AC_SUBST([am__tar]) AC_SUBST([am__untar]) ]) m4trace:configure.in:2: -1- m4_pattern_forbid([^_?A[CHUM]_]) m4trace:configure.in:2: -1- m4_pattern_forbid([_AC_]) m4trace:configure.in:2: -1- m4_pattern_forbid([^LIBOBJS$], [do not use LIBOBJS directly, use AC_LIBOBJ (see section `AC_LIBOBJ vs LIBOBJS']) m4trace:configure.in:2: -1- m4_pattern_allow([^AS_FLAGS$]) m4trace:configure.in:2: -1- m4_pattern_forbid([^_?m4_]) m4trace:configure.in:2: -1- m4_pattern_forbid([^dnl$]) m4trace:configure.in:2: -1- m4_pattern_forbid([^_?AS_]) m4trace:configure.in:2: -1- m4_pattern_allow([^SHELL$]) m4trace:configure.in:2: -1- m4_pattern_allow([^PATH_SEPARATOR$]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_NAME$]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_TARNAME$]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_VERSION$]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_STRING$]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_BUGREPORT$]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_URL$]) m4trace:configure.in:2: -1- m4_pattern_allow([^exec_prefix$]) m4trace:configure.in:2: -1- m4_pattern_allow([^prefix$]) m4trace:configure.in:2: -1- m4_pattern_allow([^program_transform_name$]) m4trace:configure.in:2: -1- m4_pattern_allow([^bindir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^sbindir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^libexecdir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^datarootdir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^datadir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^sysconfdir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^sharedstatedir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^localstatedir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^runstatedir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^includedir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^oldincludedir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^docdir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^infodir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^htmldir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^dvidir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^pdfdir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^psdir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^libdir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^localedir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^mandir$]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_NAME$]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_TARNAME$]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_VERSION$]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_STRING$]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_BUGREPORT$]) m4trace:configure.in:2: -1- m4_pattern_allow([^PACKAGE_URL$]) m4trace:configure.in:2: -1- m4_pattern_allow([^DEFS$]) m4trace:configure.in:2: -1- m4_pattern_allow([^ECHO_C$]) m4trace:configure.in:2: -1- m4_pattern_allow([^ECHO_N$]) m4trace:configure.in:2: -1- m4_pattern_allow([^ECHO_T$]) m4trace:configure.in:2: -1- m4_pattern_allow([^LIBS$]) m4trace:configure.in:2: -1- m4_pattern_allow([^build_alias$]) m4trace:configure.in:2: -1- m4_pattern_allow([^host_alias$]) m4trace:configure.in:2: -1- m4_pattern_allow([^target_alias$]) m4trace:configure.in:21: -1- m4_pattern_allow([^MAJOR_VERSION$]) m4trace:configure.in:22: -1- m4_pattern_allow([^MINOR_VERSION$]) m4trace:configure.in:23: -1- m4_pattern_allow([^MICRO_VERSION$]) m4trace:configure.in:24: -1- m4_pattern_allow([^INTERFACE_AGE$]) m4trace:configure.in:25: -1- m4_pattern_allow([^BINARY_AGE$]) m4trace:configure.in:26: -1- m4_pattern_allow([^VERSION$]) m4trace:configure.in:29: -1- LT_INIT([win32-dll]) m4trace:configure.in:29: -1- m4_pattern_forbid([^_?LT_[A-Z_]+$]) m4trace:configure.in:29: -1- m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$]) m4trace:configure.in:29: -1- LTOPTIONS_VERSION m4trace:configure.in:29: -1- LTSUGAR_VERSION m4trace:configure.in:29: -1- LTVERSION_VERSION m4trace:configure.in:29: -1- LTOBSOLETE_VERSION m4trace:configure.in:29: -1- _LT_PROG_LTMAIN m4trace:configure.in:29: -1- m4_pattern_allow([^AS$]) m4trace:configure.in:29: -1- m4_pattern_allow([^DLLTOOL$]) m4trace:configure.in:29: -1- m4_pattern_allow([^OBJDUMP$]) m4trace:configure.in:29: -1- m4_pattern_allow([^LIBTOOL$]) m4trace:configure.in:29: -1- m4_pattern_allow([^build$]) m4trace:configure.in:29: -1- m4_pattern_allow([^build_cpu$]) m4trace:configure.in:29: -1- m4_pattern_allow([^build_vendor$]) m4trace:configure.in:29: -1- m4_pattern_allow([^build_os$]) m4trace:configure.in:29: -1- m4_pattern_allow([^host$]) m4trace:configure.in:29: -1- m4_pattern_allow([^host_cpu$]) m4trace:configure.in:29: -1- m4_pattern_allow([^host_vendor$]) m4trace:configure.in:29: -1- m4_pattern_allow([^host_os$]) m4trace:configure.in:29: -1- _LT_PREPARE_SED_QUOTE_VARS m4trace:configure.in:29: -1- _LT_PROG_ECHO_BACKSLASH m4trace:configure.in:29: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:29: -1- m4_pattern_allow([^CFLAGS$]) m4trace:configure.in:29: -1- m4_pattern_allow([^LDFLAGS$]) m4trace:configure.in:29: -1- m4_pattern_allow([^LIBS$]) m4trace:configure.in:29: -1- m4_pattern_allow([^CPPFLAGS$]) m4trace:configure.in:29: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:29: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:29: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:29: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:29: -1- m4_pattern_allow([^ac_ct_CC$]) m4trace:configure.in:29: -1- m4_pattern_allow([^EXEEXT$]) m4trace:configure.in:29: -1- m4_pattern_allow([^OBJEXT$]) m4trace:configure.in:29: -1- _AM_PROG_CC_C_O m4trace:configure.in:29: -1- AM_AUX_DIR_EXPAND m4trace:configure.in:29: -1- AM_RUN_LOG([$CC -c conftest.$ac_ext -o conftest2.$ac_objext]) m4trace:configure.in:29: -1- LT_PATH_LD m4trace:configure.in:29: -1- m4_pattern_allow([^SED$]) m4trace:configure.in:29: -1- AC_PROG_EGREP m4trace:configure.in:29: -1- m4_pattern_allow([^GREP$]) m4trace:configure.in:29: -1- m4_pattern_allow([^EGREP$]) m4trace:configure.in:29: -1- m4_pattern_allow([^FGREP$]) m4trace:configure.in:29: -1- m4_pattern_allow([^GREP$]) m4trace:configure.in:29: -1- m4_pattern_allow([^LD$]) m4trace:configure.in:29: -1- LT_PATH_NM m4trace:configure.in:29: -1- m4_pattern_allow([^DUMPBIN$]) m4trace:configure.in:29: -1- m4_pattern_allow([^ac_ct_DUMPBIN$]) m4trace:configure.in:29: -1- m4_pattern_allow([^DUMPBIN$]) m4trace:configure.in:29: -1- m4_pattern_allow([^NM$]) m4trace:configure.in:29: -1- m4_pattern_allow([^LN_S$]) m4trace:configure.in:29: -1- LT_CMD_MAX_LEN m4trace:configure.in:29: -1- m4_pattern_allow([^OBJDUMP$]) m4trace:configure.in:29: -1- m4_pattern_allow([^OBJDUMP$]) m4trace:configure.in:29: -1- m4_pattern_allow([^DLLTOOL$]) m4trace:configure.in:29: -1- m4_pattern_allow([^DLLTOOL$]) m4trace:configure.in:29: -1- m4_pattern_allow([^AR$]) m4trace:configure.in:29: -1- m4_pattern_allow([^ac_ct_AR$]) m4trace:configure.in:29: -1- m4_pattern_allow([^STRIP$]) m4trace:configure.in:29: -1- m4_pattern_allow([^RANLIB$]) m4trace:configure.in:29: -1- m4_pattern_allow([^AWK$]) m4trace:configure.in:29: -1- _LT_WITH_SYSROOT m4trace:configure.in:29: -1- m4_pattern_allow([LT_OBJDIR]) m4trace:configure.in:29: -1- m4_pattern_allow([^LT_OBJDIR$]) m4trace:configure.in:29: -1- _LT_CC_BASENAME([$compiler]) m4trace:configure.in:29: -1- _LT_PATH_TOOL_PREFIX([${ac_tool_prefix}file], [/usr/bin$PATH_SEPARATOR$PATH]) m4trace:configure.in:29: -1- _LT_PATH_TOOL_PREFIX([file], [/usr/bin$PATH_SEPARATOR$PATH]) m4trace:configure.in:29: -1- LT_SUPPORTED_TAG([CC]) m4trace:configure.in:29: -1- _LT_COMPILER_BOILERPLATE m4trace:configure.in:29: -1- _LT_LINKER_BOILERPLATE m4trace:configure.in:29: -1- _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions], [lt_cv_prog_compiler_rtti_exceptions], [-fno-rtti -fno-exceptions], [], [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, )="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, ) -fno-rtti -fno-exceptions"]) m4trace:configure.in:29: -1- _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, ) works], [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, )], [$_LT_TAGVAR(lt_prog_compiler_pic, )@&t@m4_if([],[],[ -DPIC],[m4_if([],[CXX],[ -DPIC],[])])], [], [case $_LT_TAGVAR(lt_prog_compiler_pic, ) in "" | " "*) ;; *) _LT_TAGVAR(lt_prog_compiler_pic, )=" $_LT_TAGVAR(lt_prog_compiler_pic, )" ;; esac], [_LT_TAGVAR(lt_prog_compiler_pic, )= _LT_TAGVAR(lt_prog_compiler_can_build_shared, )=no]) m4trace:configure.in:29: -1- _LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works], [lt_cv_prog_compiler_static_works], [$lt_tmp_static_flag], [], [_LT_TAGVAR(lt_prog_compiler_static, )=]) m4trace:configure.in:29: -1- m4_pattern_allow([^MANIFEST_TOOL$]) m4trace:configure.in:29: -1- _LT_DLL_DEF_P([$export_symbols]) m4trace:configure.in:29: -1- _LT_DLL_DEF_P([$export_symbols]) m4trace:configure.in:29: -1- _LT_REQUIRED_DARWIN_CHECKS m4trace:configure.in:29: -1- m4_pattern_allow([^DSYMUTIL$]) m4trace:configure.in:29: -1- m4_pattern_allow([^NMEDIT$]) m4trace:configure.in:29: -1- m4_pattern_allow([^LIPO$]) m4trace:configure.in:29: -1- m4_pattern_allow([^OTOOL$]) m4trace:configure.in:29: -1- m4_pattern_allow([^OTOOL64$]) m4trace:configure.in:29: -1- _LT_LINKER_OPTION([if $CC understands -b], [lt_cv_prog_compiler__b], [-b], [_LT_TAGVAR(archive_cmds, )='$CC -b $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags'], [_LT_TAGVAR(archive_cmds, )='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags']) m4trace:configure.in:29: -1- m4_pattern_allow([^LT_SYS_LIBRARY_PATH$]) m4trace:configure.in:29: -1- LT_SYS_DLOPEN_SELF m4trace:configure.in:29: -1- m4_pattern_allow([^CPP$]) m4trace:configure.in:29: -1- m4_pattern_allow([^CPPFLAGS$]) m4trace:configure.in:29: -1- m4_pattern_allow([^CPP$]) m4trace:configure.in:29: -1- m4_pattern_allow([^STDC_HEADERS$]) m4trace:configure.in:29: -1- m4_pattern_allow([^HAVE_DLFCN_H$]) m4trace:configure.in:36: -1- m4_pattern_allow([^LT_RELEASE$]) m4trace:configure.in:37: -1- m4_pattern_allow([^LT_CURRENT$]) m4trace:configure.in:38: -1- m4_pattern_allow([^LT_REVISION$]) m4trace:configure.in:39: -1- m4_pattern_allow([^LT_AGE$]) m4trace:configure.in:45: -1- AM_INIT_AUTOMAKE([SDL2_image], [$VERSION]) m4trace:configure.in:45: -1- m4_pattern_allow([^AM_[A-Z]+FLAGS$]) m4trace:configure.in:45: -1- AM_SET_CURRENT_AUTOMAKE_VERSION m4trace:configure.in:45: -1- AM_AUTOMAKE_VERSION([1.15]) m4trace:configure.in:45: -1- _AM_AUTOCONF_VERSION([2.69]) m4trace:configure.in:45: -1- m4_pattern_allow([^INSTALL_PROGRAM$]) m4trace:configure.in:45: -1- m4_pattern_allow([^INSTALL_SCRIPT$]) m4trace:configure.in:45: -1- m4_pattern_allow([^INSTALL_DATA$]) m4trace:configure.in:45: -1- m4_pattern_allow([^am__isrc$]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([am__isrc]) m4trace:configure.in:45: -1- m4_pattern_allow([^CYGPATH_W$]) m4trace:configure.in:45: -1- _m4_warn([obsolete], [AM_INIT_AUTOMAKE: two- and three-arguments forms are deprecated.], [/usr/share/aclocal-1.15/init.m4:29: AM_INIT_AUTOMAKE is expanded from... configure.in:45: the top level]) m4trace:configure.in:45: -1- m4_pattern_allow([^PACKAGE$]) m4trace:configure.in:45: -1- m4_pattern_allow([^VERSION$]) m4trace:configure.in:45: -1- _AM_IF_OPTION([no-define], [], [AC_DEFINE_UNQUOTED([PACKAGE], ["$PACKAGE"], [Name of package]) AC_DEFINE_UNQUOTED([VERSION], ["$VERSION"], [Version number of package])]) m4trace:configure.in:45: -2- _AM_MANGLE_OPTION([no-define]) m4trace:configure.in:45: -1- m4_pattern_allow([^PACKAGE$]) m4trace:configure.in:45: -1- m4_pattern_allow([^VERSION$]) m4trace:configure.in:45: -1- AM_SANITY_CHECK m4trace:configure.in:45: -1- AM_MISSING_PROG([ACLOCAL], [aclocal-${am__api_version}]) m4trace:configure.in:45: -1- AM_MISSING_HAS_RUN m4trace:configure.in:45: -1- m4_pattern_allow([^ACLOCAL$]) m4trace:configure.in:45: -1- AM_MISSING_PROG([AUTOCONF], [autoconf]) m4trace:configure.in:45: -1- m4_pattern_allow([^AUTOCONF$]) m4trace:configure.in:45: -1- AM_MISSING_PROG([AUTOMAKE], [automake-${am__api_version}]) m4trace:configure.in:45: -1- m4_pattern_allow([^AUTOMAKE$]) m4trace:configure.in:45: -1- AM_MISSING_PROG([AUTOHEADER], [autoheader]) m4trace:configure.in:45: -1- m4_pattern_allow([^AUTOHEADER$]) m4trace:configure.in:45: -1- AM_MISSING_PROG([MAKEINFO], [makeinfo]) m4trace:configure.in:45: -1- m4_pattern_allow([^MAKEINFO$]) m4trace:configure.in:45: -1- AM_PROG_INSTALL_SH m4trace:configure.in:45: -1- m4_pattern_allow([^install_sh$]) m4trace:configure.in:45: -1- AM_PROG_INSTALL_STRIP m4trace:configure.in:45: -1- m4_pattern_allow([^STRIP$]) m4trace:configure.in:45: -1- m4_pattern_allow([^INSTALL_STRIP_PROGRAM$]) m4trace:configure.in:45: -1- m4_pattern_allow([^MKDIR_P$]) m4trace:configure.in:45: -1- m4_pattern_allow([^mkdir_p$]) m4trace:configure.in:45: -1- m4_pattern_allow([^SET_MAKE$]) m4trace:configure.in:45: -1- AM_SET_LEADING_DOT m4trace:configure.in:45: -1- m4_pattern_allow([^am__leading_dot$]) m4trace:configure.in:45: -1- _AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])], [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], [_AM_PROG_TAR([v7])])]) m4trace:configure.in:45: -2- _AM_MANGLE_OPTION([tar-ustar]) m4trace:configure.in:45: -1- _AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], [_AM_PROG_TAR([v7])]) m4trace:configure.in:45: -2- _AM_MANGLE_OPTION([tar-pax]) m4trace:configure.in:45: -1- _AM_PROG_TAR([v7]) m4trace:configure.in:45: -1- m4_pattern_allow([^AMTAR$]) m4trace:configure.in:45: -1- m4_pattern_allow([^am__tar$]) m4trace:configure.in:45: -1- m4_pattern_allow([^am__untar$]) m4trace:configure.in:45: -1- _AM_IF_OPTION([no-dependencies], [], [AC_PROVIDE_IFELSE([AC_PROG_CC], [_AM_DEPENDENCIES([CC])], [m4_define([AC_PROG_CC], m4_defn([AC_PROG_CC])[_AM_DEPENDENCIES([CC])])])dnl AC_PROVIDE_IFELSE([AC_PROG_CXX], [_AM_DEPENDENCIES([CXX])], [m4_define([AC_PROG_CXX], m4_defn([AC_PROG_CXX])[_AM_DEPENDENCIES([CXX])])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJC], [_AM_DEPENDENCIES([OBJC])], [m4_define([AC_PROG_OBJC], m4_defn([AC_PROG_OBJC])[_AM_DEPENDENCIES([OBJC])])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJCXX], [_AM_DEPENDENCIES([OBJCXX])], [m4_define([AC_PROG_OBJCXX], m4_defn([AC_PROG_OBJCXX])[_AM_DEPENDENCIES([OBJCXX])])])dnl ]) m4trace:configure.in:45: -2- _AM_MANGLE_OPTION([no-dependencies]) m4trace:configure.in:45: -1- _AM_DEPENDENCIES([CC]) m4trace:configure.in:45: -1- AM_SET_DEPDIR m4trace:configure.in:45: -1- m4_pattern_allow([^DEPDIR$]) m4trace:configure.in:45: -1- AM_OUTPUT_DEPENDENCY_COMMANDS m4trace:configure.in:45: -1- AM_MAKE_INCLUDE m4trace:configure.in:45: -1- m4_pattern_allow([^am__include$]) m4trace:configure.in:45: -1- m4_pattern_allow([^am__quote$]) m4trace:configure.in:45: -1- AM_DEP_TRACK m4trace:configure.in:45: -1- AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno]) m4trace:configure.in:45: -1- m4_pattern_allow([^AMDEP_TRUE$]) m4trace:configure.in:45: -1- m4_pattern_allow([^AMDEP_FALSE$]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([AMDEP_TRUE]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([AMDEP_FALSE]) m4trace:configure.in:45: -1- m4_pattern_allow([^AMDEPBACKSLASH$]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([AMDEPBACKSLASH]) m4trace:configure.in:45: -1- m4_pattern_allow([^am__nodep$]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([am__nodep]) m4trace:configure.in:45: -1- m4_pattern_allow([^CCDEPMODE$]) m4trace:configure.in:45: -1- AM_CONDITIONAL([am__fastdepCC], [ test "x$enable_dependency_tracking" != xno \ && test "$am_cv_CC_dependencies_compiler_type" = gcc3]) m4trace:configure.in:45: -1- m4_pattern_allow([^am__fastdepCC_TRUE$]) m4trace:configure.in:45: -1- m4_pattern_allow([^am__fastdepCC_FALSE$]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([am__fastdepCC_TRUE]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([am__fastdepCC_FALSE]) m4trace:configure.in:45: -1- AM_SILENT_RULES m4trace:configure.in:45: -1- m4_pattern_allow([^AM_V$]) m4trace:configure.in:45: -1- AM_SUBST_NOTMAKE([AM_V]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([AM_V]) m4trace:configure.in:45: -1- m4_pattern_allow([^AM_DEFAULT_V$]) m4trace:configure.in:45: -1- AM_SUBST_NOTMAKE([AM_DEFAULT_V]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([AM_DEFAULT_V]) m4trace:configure.in:45: -1- m4_pattern_allow([^AM_DEFAULT_VERBOSITY$]) m4trace:configure.in:45: -1- m4_pattern_allow([^AM_BACKSLASH$]) m4trace:configure.in:45: -1- _AM_SUBST_NOTMAKE([AM_BACKSLASH]) m4trace:configure.in:48: -1- AC_PROG_LIBTOOL m4trace:configure.in:48: -1- _m4_warn([obsolete], [The macro `AC_PROG_LIBTOOL' is obsolete. You should run autoupdate.], [/usr/share/aclocal/libtool.m4:99: AC_PROG_LIBTOOL is expanded from... configure.in:48: the top level]) m4trace:configure.in:48: -1- LT_INIT m4trace:configure.in:49: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:49: -1- m4_pattern_allow([^CFLAGS$]) m4trace:configure.in:49: -1- m4_pattern_allow([^LDFLAGS$]) m4trace:configure.in:49: -1- m4_pattern_allow([^LIBS$]) m4trace:configure.in:49: -1- m4_pattern_allow([^CPPFLAGS$]) m4trace:configure.in:49: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:49: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:49: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:49: -1- m4_pattern_allow([^CC$]) m4trace:configure.in:49: -1- m4_pattern_allow([^ac_ct_CC$]) m4trace:configure.in:49: -1- _AM_PROG_CC_C_O m4trace:configure.in:49: -1- AM_RUN_LOG([$CC -c conftest.$ac_ext -o conftest2.$ac_objext]) m4trace:configure.in:50: -1- m4_pattern_allow([^OBJC$]) m4trace:configure.in:50: -1- m4_pattern_allow([^OBJCFLAGS$]) m4trace:configure.in:50: -1- m4_pattern_allow([^LDFLAGS$]) m4trace:configure.in:50: -1- m4_pattern_allow([^LIBS$]) m4trace:configure.in:50: -1- m4_pattern_allow([^CPPFLAGS$]) m4trace:configure.in:50: -1- m4_pattern_allow([^OBJC$]) m4trace:configure.in:50: -1- m4_pattern_allow([^ac_ct_OBJC$]) m4trace:configure.in:50: -1- _AM_DEPENDENCIES([OBJC]) m4trace:configure.in:50: -1- m4_pattern_allow([^OBJCDEPMODE$]) m4trace:configure.in:50: -1- AM_CONDITIONAL([am__fastdepOBJC], [ test "x$enable_dependency_tracking" != xno \ && test "$am_cv_OBJC_dependencies_compiler_type" = gcc3]) m4trace:configure.in:50: -1- m4_pattern_allow([^am__fastdepOBJC_TRUE$]) m4trace:configure.in:50: -1- m4_pattern_allow([^am__fastdepOBJC_FALSE$]) m4trace:configure.in:50: -1- _AM_SUBST_NOTMAKE([am__fastdepOBJC_TRUE]) m4trace:configure.in:50: -1- _AM_SUBST_NOTMAKE([am__fastdepOBJC_FALSE]) m4trace:configure.in:53: -1- m4_pattern_allow([^SET_MAKE$]) m4trace:configure.in:59: -1- m4_pattern_allow([^WINDRES$]) m4trace:configure.in:80: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:80: the top level]) m4trace:configure.in:92: -1- AM_CONDITIONAL([USE_IMAGEIO], [test x$enable_imageio = xyes]) m4trace:configure.in:92: -1- m4_pattern_allow([^USE_IMAGEIO_TRUE$]) m4trace:configure.in:92: -1- m4_pattern_allow([^USE_IMAGEIO_FALSE$]) m4trace:configure.in:92: -1- _AM_SUBST_NOTMAKE([USE_IMAGEIO_TRUE]) m4trace:configure.in:92: -1- _AM_SUBST_NOTMAKE([USE_IMAGEIO_FALSE]) m4trace:configure.in:93: -1- AM_CONDITIONAL([USE_VERSION_RC], [test x$use_version_rc = xtrue]) m4trace:configure.in:93: -1- m4_pattern_allow([^USE_VERSION_RC_TRUE$]) m4trace:configure.in:93: -1- m4_pattern_allow([^USE_VERSION_RC_FALSE$]) m4trace:configure.in:93: -1- _AM_SUBST_NOTMAKE([USE_VERSION_RC_TRUE]) m4trace:configure.in:93: -1- _AM_SUBST_NOTMAKE([USE_VERSION_RC_FALSE]) m4trace:configure.in:120: -1- m4_pattern_allow([^SDL_VERSION$]) m4trace:configure.in:130: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:130: the top level]) m4trace:configure.in:132: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:132: the top level]) m4trace:configure.in:134: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:134: the top level]) m4trace:configure.in:136: -2- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... configure.in:136: the top level]) m4trace:configure.in:138: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:138: the top level]) m4trace:configure.in:140: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:140: the top level]) m4trace:configure.in:142: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:142: the top level]) m4trace:configure.in:144: -2- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... configure.in:144: the top level]) m4trace:configure.in:146: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:146: the top level]) m4trace:configure.in:148: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:148: the top level]) m4trace:configure.in:150: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:150: the top level]) m4trace:configure.in:152: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:152: the top level]) m4trace:configure.in:154: -2- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... configure.in:154: the top level]) m4trace:configure.in:156: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:156: the top level]) m4trace:configure.in:158: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:158: the top level]) m4trace:configure.in:160: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:160: the top level]) m4trace:configure.in:162: -1- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... ../../lib/autoconf/general.m4:1473: AC_ARG_ENABLE is expanded from... configure.in:162: the top level]) m4trace:configure.in:164: -2- _m4_warn([obsolete], [The macro `AC_HELP_STRING' is obsolete. You should run autoupdate.], [../../lib/autoconf/general.m4:207: AC_HELP_STRING is expanded from... configure.in:164: the top level]) m4trace:configure.in:172: -1- m4_pattern_allow([^LOAD_JPG$]) m4trace:configure.in:197: -1- PKG_CHECK_MODULES([LIBPNG], [libpng], [dnl have_png_hdr=yes have_png_lib=yes ], [dnl AC_CHECK_HEADER([png.h], [ have_png_hdr=yes LIBPNG_CFLAGS="" ]) AC_CHECK_LIB([png], [png_create_read_struct], [ have_png_lib=yes LIBPNG_LIBS="-lpng -lz" ], [], [-lz]) ]) m4trace:configure.in:197: -1- PKG_PROG_PKG_CONFIG m4trace:configure.in:197: -1- m4_pattern_forbid([^_?PKG_[A-Z_]+$]) m4trace:configure.in:197: -1- m4_pattern_allow([^PKG_CONFIG(_(PATH|LIBDIR|SYSROOT_DIR|ALLOW_SYSTEM_(CFLAGS|LIBS)))?$]) m4trace:configure.in:197: -1- m4_pattern_allow([^PKG_CONFIG_(DISABLE_UNINSTALLED|TOP_BUILD_DIR|DEBUG_SPEW)$]) m4trace:configure.in:197: -1- m4_pattern_allow([^PKG_CONFIG$]) m4trace:configure.in:197: -1- m4_pattern_allow([^PKG_CONFIG_PATH$]) m4trace:configure.in:197: -1- m4_pattern_allow([^PKG_CONFIG_LIBDIR$]) m4trace:configure.in:197: -1- m4_pattern_allow([^PKG_CONFIG$]) m4trace:configure.in:197: -1- m4_pattern_allow([^LIBPNG_CFLAGS$]) m4trace:configure.in:197: -1- m4_pattern_allow([^LIBPNG_LIBS$]) m4trace:configure.in:197: -1- PKG_CHECK_EXISTS([libpng], [pkg_cv_[]LIBPNG_CFLAGS=`$PKG_CONFIG --[]cflags "libpng" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes ], [pkg_failed=yes]) m4trace:configure.in:197: -1- PKG_CHECK_EXISTS([libpng], [pkg_cv_[]LIBPNG_LIBS=`$PKG_CONFIG --[]libs "libpng" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes ], [pkg_failed=yes]) m4trace:configure.in:197: -1- _PKG_SHORT_ERRORS_SUPPORTED m4trace:configure.in:211: -1- m4_pattern_allow([^LOAD_PNG$]) m4trace:configure.in:237: -1- m4_pattern_allow([^LOAD_TIF$]) m4trace:configure.in:260: -1- PKG_CHECK_MODULES([LIBWEBP], [libwebp], [dnl have_webp_hdr=yes have_webp_lib=yes ], [dnl AC_CHECK_HEADER([webp/decode.h], [ have_webp_hdr=yes LIBWEBP_CFLAGS="" ]) AC_CHECK_LIB([webp], [WebPGetDecoderVersion], [ have_webp_lib=yes LIBWEBP_LIBS="-lwebp" ], [], [-lm]) ]) m4trace:configure.in:260: -1- m4_pattern_allow([^LIBWEBP_CFLAGS$]) m4trace:configure.in:260: -1- m4_pattern_allow([^LIBWEBP_LIBS$]) m4trace:configure.in:260: -1- PKG_CHECK_EXISTS([libwebp], [pkg_cv_[]LIBWEBP_CFLAGS=`$PKG_CONFIG --[]cflags "libwebp" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes ], [pkg_failed=yes]) m4trace:configure.in:260: -1- PKG_CHECK_EXISTS([libwebp], [pkg_cv_[]LIBWEBP_LIBS=`$PKG_CONFIG --[]libs "libwebp" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes ], [pkg_failed=yes]) m4trace:configure.in:260: -1- _PKG_SHORT_ERRORS_SUPPORTED m4trace:configure.in:274: -1- m4_pattern_allow([^LOAD_WEBP$]) m4trace:configure.in:297: -1- m4_pattern_allow([^LOAD_BMP$]) m4trace:configure.in:301: -1- m4_pattern_allow([^LOAD_GIF$]) m4trace:configure.in:305: -1- m4_pattern_allow([^LOAD_LBM$]) m4trace:configure.in:309: -1- m4_pattern_allow([^LOAD_PCX$]) m4trace:configure.in:313: -1- m4_pattern_allow([^LOAD_PNM$]) m4trace:configure.in:317: -1- m4_pattern_allow([^LOAD_SVG$]) m4trace:configure.in:321: -1- m4_pattern_allow([^LOAD_TGA$]) m4trace:configure.in:325: -1- m4_pattern_allow([^LOAD_XCF$]) m4trace:configure.in:329: -1- m4_pattern_allow([^LOAD_XPM$]) m4trace:configure.in:333: -1- m4_pattern_allow([^LOAD_XV$]) m4trace:configure.in:340: -1- m4_pattern_allow([^LOAD_WEBP_DYNAMIC$]) m4trace:configure.in:349: -1- m4_pattern_allow([^LOAD_TIF_DYNAMIC$]) m4trace:configure.in:361: -1- m4_pattern_allow([^LOAD_JPG_DYNAMIC$]) m4trace:configure.in:370: -1- m4_pattern_allow([^LOAD_PNG_DYNAMIC$]) m4trace:configure.in:378: -1- m4_pattern_allow([^WINDRES$]) m4trace:configure.in:379: -1- m4_pattern_allow([^IMG_LIBS$]) m4trace:configure.in:384: -1- _m4_warn([obsolete], [AC_OUTPUT should be used without arguments. You should run autoupdate.], []) m4trace:configure.in:384: -1- m4_pattern_allow([^LIB@&t@OBJS$]) m4trace:configure.in:384: -1- m4_pattern_allow([^LTLIBOBJS$]) m4trace:configure.in:384: -1- AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"]) m4trace:configure.in:384: -1- m4_pattern_allow([^am__EXEEXT_TRUE$]) m4trace:configure.in:384: -1- m4_pattern_allow([^am__EXEEXT_FALSE$]) m4trace:configure.in:384: -1- _AM_SUBST_NOTMAKE([am__EXEEXT_TRUE]) m4trace:configure.in:384: -1- _AM_SUBST_NOTMAKE([am__EXEEXT_FALSE]) m4trace:configure.in:384: -1- _LT_PROG_LTMAIN m4trace:configure.in:384: -1- _AM_OUTPUT_DEPENDENCY_COMMANDS
YifuLiu/AliOS-Things
components/SDL2/src/image/autom4te.cache/traces.2
Roff
apache-2.0
131,107
#! /bin/sh # Wrapper for compilers which do not understand '-c -o'. scriptversion=2017-09-16.17; # UTC # Copyright (C) 1999-2018 Free Software Foundation, Inc. # Written by Tom Tromey <tromey@cygnus.com>. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # This file is maintained in Automake, please report # bugs to <bug-automake@gnu.org> or send patches to # <automake-patches@gnu.org>. nl=' ' # We need space, tab and new line, in precisely that order. Quoting is # there to prevent tools from complaining about whitespace usage. IFS=" "" $nl" file_conv= # func_file_conv build_file lazy # Convert a $build file to $host form and store it in $file # Currently only supports Windows hosts. If the determined conversion # type is listed in (the comma separated) LAZY, no conversion will # take place. func_file_conv () { file=$1 case $file in / | /[!/]*) # absolute file, and not a UNC file if test -z "$file_conv"; then # lazily determine how to convert abs files case `uname -s` in MINGW*) file_conv=mingw ;; CYGWIN*) file_conv=cygwin ;; *) file_conv=wine ;; esac fi case $file_conv/,$2, in *,$file_conv,*) ;; mingw/*) file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'` ;; cygwin/*) file=`cygpath -m "$file" || echo "$file"` ;; wine/*) file=`winepath -w "$file" || echo "$file"` ;; esac ;; esac } # func_cl_dashL linkdir # Make cl look for libraries in LINKDIR func_cl_dashL () { func_file_conv "$1" if test -z "$lib_path"; then lib_path=$file else lib_path="$lib_path;$file" fi linker_opts="$linker_opts -LIBPATH:$file" } # func_cl_dashl library # Do a library search-path lookup for cl func_cl_dashl () { lib=$1 found=no save_IFS=$IFS IFS=';' for dir in $lib_path $LIB do IFS=$save_IFS if $shared && test -f "$dir/$lib.dll.lib"; then found=yes lib=$dir/$lib.dll.lib break fi if test -f "$dir/$lib.lib"; then found=yes lib=$dir/$lib.lib break fi if test -f "$dir/lib$lib.a"; then found=yes lib=$dir/lib$lib.a break fi done IFS=$save_IFS if test "$found" != yes; then lib=$lib.lib fi } # func_cl_wrapper cl arg... # Adjust compile command to suit cl func_cl_wrapper () { # Assume a capable shell lib_path= shared=: linker_opts= for arg do if test -n "$eat"; then eat= else case $1 in -o) # configure might choose to run compile as 'compile cc -o foo foo.c'. eat=1 case $2 in *.o | *.[oO][bB][jJ]) func_file_conv "$2" set x "$@" -Fo"$file" shift ;; *) func_file_conv "$2" set x "$@" -Fe"$file" shift ;; esac ;; -I) eat=1 func_file_conv "$2" mingw set x "$@" -I"$file" shift ;; -I*) func_file_conv "${1#-I}" mingw set x "$@" -I"$file" shift ;; -l) eat=1 func_cl_dashl "$2" set x "$@" "$lib" shift ;; -l*) func_cl_dashl "${1#-l}" set x "$@" "$lib" shift ;; -L) eat=1 func_cl_dashL "$2" ;; -L*) func_cl_dashL "${1#-L}" ;; -static) shared=false ;; -Wl,*) arg=${1#-Wl,} save_ifs="$IFS"; IFS=',' for flag in $arg; do IFS="$save_ifs" linker_opts="$linker_opts $flag" done IFS="$save_ifs" ;; -Xlinker) eat=1 linker_opts="$linker_opts $2" ;; -*) set x "$@" "$1" shift ;; *.cc | *.CC | *.cxx | *.CXX | *.[cC]++) func_file_conv "$1" set x "$@" -Tp"$file" shift ;; *.c | *.cpp | *.CPP | *.lib | *.LIB | *.Lib | *.OBJ | *.obj | *.[oO]) func_file_conv "$1" mingw set x "$@" "$file" shift ;; *) set x "$@" "$1" shift ;; esac fi shift done if test -n "$linker_opts"; then linker_opts="-link$linker_opts" fi exec "$@" $linker_opts exit 1 } eat= case $1 in '') echo "$0: No command. Try '$0 --help' for more information." 1>&2 exit 1; ;; -h | --h*) cat <<\EOF Usage: compile [--help] [--version] PROGRAM [ARGS] Wrapper for compilers which do not understand '-c -o'. Remove '-o dest.o' from ARGS, run PROGRAM with the remaining arguments, and rename the output as expected. If you are trying to build a whole package this is not the right script to run: please start by reading the file 'INSTALL'. Report bugs to <bug-automake@gnu.org>. EOF exit $? ;; -v | --v*) echo "compile $scriptversion" exit $? ;; cl | *[/\\]cl | cl.exe | *[/\\]cl.exe | \ icl | *[/\\]icl | icl.exe | *[/\\]icl.exe ) func_cl_wrapper "$@" # Doesn't return... ;; esac ofile= cfile= for arg do if test -n "$eat"; then eat= else case $1 in -o) # configure might choose to run compile as 'compile cc -o foo foo.c'. # So we strip '-o arg' only if arg is an object. eat=1 case $2 in *.o | *.obj) ofile=$2 ;; *) set x "$@" -o "$2" shift ;; esac ;; *.c) cfile=$1 set x "$@" "$1" shift ;; *) set x "$@" "$1" shift ;; esac fi shift done if test -z "$ofile" || test -z "$cfile"; then # If no '-o' option was seen then we might have been invoked from a # pattern rule where we don't need one. That is ok -- this is a # normal compilation that the losing compiler can handle. If no # '.c' file was seen then we are probably linking. That is also # ok. exec "$@" fi # Name of file we expect compiler to create. cofile=`echo "$cfile" | sed 's|^.*[\\/]||; s|^[a-zA-Z]:||; s/\.c$/.o/'` # Create the lock directory. # Note: use '[/\\:.-]' here to ensure that we don't use the same name # that we are using for the .o file. Also, base the name on the expected # object file name, since that is what matters with a parallel build. lockdir=`echo "$cofile" | sed -e 's|[/\\:.-]|_|g'`.d while true; do if mkdir "$lockdir" >/dev/null 2>&1; then break fi sleep 1 done # FIXME: race condition here if user kills between mkdir and trap. trap "rmdir '$lockdir'; exit 1" 1 2 15 # Run the compile. "$@" ret=$? if test -f "$cofile"; then test "$cofile" = "$ofile" || mv "$cofile" "$ofile" elif test -f "${cofile}bj"; then test "${cofile}bj" = "$ofile" || mv "${cofile}bj" "$ofile" fi rmdir "$lockdir" exit $ret # Local Variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End:
YifuLiu/AliOS-Things
components/SDL2/src/image/compile
Shell
apache-2.0
7,383
# Makefile for showimage CC = gcc CFLAGS = $(shell sdl2-config --cflags) -Wall -O LIBS = $(shell sdl2-config --libs) -lSDL2_image EXE = showimage all: $(EXE) showimage: showimage.c Makefile $(CC) -o $@ $@.c $(CFLAGS) $(LIBS) clean: -rm *.o $(EXE)
YifuLiu/AliOS-Things
components/SDL2/src/image/debian/examples/Makefile
Makefile
apache-2.0
253
#!/usr/bin/make -f confflags = # These flags can be used to create a package directly linking with external libraries and having the appropriate package dependencies #confflags += --disable-jpg-shared #confflags += --disable-png-shared #confflags += --disable-tif-shared #confflags += --disable-webp-shared %: dh $@ --with autoreconf --parallel override_dh_autoreconf: dh_autoreconf ./autogen.sh override_dh_auto_configure: dh_auto_configure -- $(confflags) override_dh_auto_installchangelogs: dh_auto_installchangelogs -- CHANGES override_dh_compress: dh_compress -Xshowimage.c
YifuLiu/AliOS-Things
components/SDL2/src/image/debian/rules
Makefile
apache-2.0
591
#! /bin/sh # depcomp - compile a program generating dependencies as side-effects scriptversion=2017-09-16.17; # UTC # Copyright (C) 1999-2018 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # Originally written by Alexandre Oliva <oliva@dcc.unicamp.br>. case $1 in '') echo "$0: No command. Try '$0 --help' for more information." 1>&2 exit 1; ;; -h | --h*) cat <<\EOF Usage: depcomp [--help] [--version] PROGRAM [ARGS] Run PROGRAMS ARGS to compile a file, generating dependencies as side-effects. Environment variables: depmode Dependency tracking mode. source Source file read by 'PROGRAMS ARGS'. object Object file output by 'PROGRAMS ARGS'. DEPDIR directory where to store dependencies. depfile Dependency file to output. tmpdepfile Temporary file to use when outputting dependencies. libtool Whether libtool is used (yes/no). Report bugs to <bug-automake@gnu.org>. EOF exit $? ;; -v | --v*) echo "depcomp $scriptversion" exit $? ;; esac # Get the directory component of the given path, and save it in the # global variables '$dir'. Note that this directory component will # be either empty or ending with a '/' character. This is deliberate. set_dir_from () { case $1 in */*) dir=`echo "$1" | sed -e 's|/[^/]*$|/|'`;; *) dir=;; esac } # Get the suffix-stripped basename of the given path, and save it the # global variable '$base'. set_base_from () { base=`echo "$1" | sed -e 's|^.*/||' -e 's/\.[^.]*$//'` } # If no dependency file was actually created by the compiler invocation, # we still have to create a dummy depfile, to avoid errors with the # Makefile "include basename.Plo" scheme. make_dummy_depfile () { echo "#dummy" > "$depfile" } # Factor out some common post-processing of the generated depfile. # Requires the auxiliary global variable '$tmpdepfile' to be set. aix_post_process_depfile () { # If the compiler actually managed to produce a dependency file, # post-process it. if test -f "$tmpdepfile"; then # Each line is of the form 'foo.o: dependency.h'. # Do two passes, one to just change these to # $object: dependency.h # and one to simply output # dependency.h: # which is needed to avoid the deleted-header problem. { sed -e "s,^.*\.[$lower]*:,$object:," < "$tmpdepfile" sed -e "s,^.*\.[$lower]*:[$tab ]*,," -e 's,$,:,' < "$tmpdepfile" } > "$depfile" rm -f "$tmpdepfile" else make_dummy_depfile fi } # A tabulation character. tab=' ' # A newline character. nl=' ' # Character ranges might be problematic outside the C locale. # These definitions help. upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ lower=abcdefghijklmnopqrstuvwxyz digits=0123456789 alpha=${upper}${lower} if test -z "$depmode" || test -z "$source" || test -z "$object"; then echo "depcomp: Variables source, object and depmode must be set" 1>&2 exit 1 fi # Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po. depfile=${depfile-`echo "$object" | sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`} tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`} rm -f "$tmpdepfile" # Avoid interferences from the environment. gccflag= dashmflag= # Some modes work just like other modes, but use different flags. We # parameterize here, but still list the modes in the big case below, # to make depend.m4 easier to write. Note that we *cannot* use a case # here, because this file can only contain one case statement. if test "$depmode" = hp; then # HP compiler uses -M and no extra arg. gccflag=-M depmode=gcc fi if test "$depmode" = dashXmstdout; then # This is just like dashmstdout with a different argument. dashmflag=-xM depmode=dashmstdout fi cygpath_u="cygpath -u -f -" if test "$depmode" = msvcmsys; then # This is just like msvisualcpp but w/o cygpath translation. # Just convert the backslash-escaped backslashes to single forward # slashes to satisfy depend.m4 cygpath_u='sed s,\\\\,/,g' depmode=msvisualcpp fi if test "$depmode" = msvc7msys; then # This is just like msvc7 but w/o cygpath translation. # Just convert the backslash-escaped backslashes to single forward # slashes to satisfy depend.m4 cygpath_u='sed s,\\\\,/,g' depmode=msvc7 fi if test "$depmode" = xlc; then # IBM C/C++ Compilers xlc/xlC can output gcc-like dependency information. gccflag=-qmakedep=gcc,-MF depmode=gcc fi case "$depmode" in gcc3) ## gcc 3 implements dependency tracking that does exactly what ## we want. Yay! Note: for some reason libtool 1.4 doesn't like ## it if -MD -MP comes after the -MF stuff. Hmm. ## Unfortunately, FreeBSD c89 acceptance of flags depends upon ## the command line argument order; so add the flags where they ## appear in depend2.am. Note that the slowdown incurred here ## affects only configure: in makefiles, %FASTDEP% shortcuts this. for arg do case $arg in -c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;; *) set fnord "$@" "$arg" ;; esac shift # fnord shift # $arg done "$@" stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi mv "$tmpdepfile" "$depfile" ;; gcc) ## Note that this doesn't just cater to obsosete pre-3.x GCC compilers. ## but also to in-use compilers like IMB xlc/xlC and the HP C compiler. ## (see the conditional assignment to $gccflag above). ## There are various ways to get dependency output from gcc. Here's ## why we pick this rather obscure method: ## - Don't want to use -MD because we'd like the dependencies to end ## up in a subdir. Having to rename by hand is ugly. ## (We might end up doing this anyway to support other compilers.) ## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like ## -MM, not -M (despite what the docs say). Also, it might not be ## supported by the other compilers which use the 'gcc' depmode. ## - Using -M directly means running the compiler twice (even worse ## than renaming). if test -z "$gccflag"; then gccflag=-MD, fi "$@" -Wp,"$gccflag$tmpdepfile" stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" echo "$object : \\" > "$depfile" # The second -e expression handles DOS-style file names with drive # letters. sed -e 's/^[^:]*: / /' \ -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile" ## This next piece of magic avoids the "deleted header file" problem. ## The problem is that when a header file which appears in a .P file ## is deleted, the dependency causes make to die (because there is ## typically no way to rebuild the header). We avoid this by adding ## dummy dependencies for each header file. Too bad gcc doesn't do ## this for us directly. ## Some versions of gcc put a space before the ':'. On the theory ## that the space means something, we add a space to the output as ## well. hp depmode also adds that space, but also prefixes the VPATH ## to the object. Take care to not repeat it in the output. ## Some versions of the HPUX 10.20 sed can't process this invocation ## correctly. Breaking it into two sed invocations is a workaround. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^\\$//' -e '/^$/d' -e "s|.*$object$||" -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; hp) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; sgi) if test "$libtool" = yes; then "$@" "-Wp,-MDupdate,$tmpdepfile" else "$@" -MDupdate "$tmpdepfile" fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files echo "$object : \\" > "$depfile" # Clip off the initial element (the dependent). Don't try to be # clever and replace this with sed code, as IRIX sed won't handle # lines with more than a fixed number of characters (4096 in # IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines; # the IRIX cc adds comments like '#:fec' to the end of the # dependency line. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' \ | tr "$nl" ' ' >> "$depfile" echo >> "$depfile" # The second pass generates a dummy entry for each header file. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \ >> "$depfile" else make_dummy_depfile fi rm -f "$tmpdepfile" ;; xlc) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; aix) # The C for AIX Compiler uses -M and outputs the dependencies # in a .u file. In older versions, this file always lives in the # current directory. Also, the AIX compiler puts '$object:' at the # start of each line; $object doesn't have directory information. # Version 6 uses the directory in both cases. set_dir_from "$object" set_base_from "$object" if test "$libtool" = yes; then tmpdepfile1=$dir$base.u tmpdepfile2=$base.u tmpdepfile3=$dir.libs/$base.u "$@" -Wc,-M else tmpdepfile1=$dir$base.u tmpdepfile2=$dir$base.u tmpdepfile3=$dir$base.u "$@" -M fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" do test -f "$tmpdepfile" && break done aix_post_process_depfile ;; tcc) # tcc (Tiny C Compiler) understand '-MD -MF file' since version 0.9.26 # FIXME: That version still under development at the moment of writing. # Make that this statement remains true also for stable, released # versions. # It will wrap lines (doesn't matter whether long or short) with a # trailing '\', as in: # # foo.o : \ # foo.c \ # foo.h \ # # It will put a trailing '\' even on the last line, and will use leading # spaces rather than leading tabs (at least since its commit 0394caf7 # "Emit spaces for -MD"). "$@" -MD -MF "$tmpdepfile" stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" # Each non-empty line is of the form 'foo.o : \' or ' dep.h \'. # We have to change lines of the first kind to '$object: \'. sed -e "s|.*:|$object :|" < "$tmpdepfile" > "$depfile" # And for each line of the second kind, we have to emit a 'dep.h:' # dummy dependency, to avoid the deleted-header problem. sed -n -e 's|^ *\(.*\) *\\$|\1:|p' < "$tmpdepfile" >> "$depfile" rm -f "$tmpdepfile" ;; ## The order of this option in the case statement is important, since the ## shell code in configure will try each of these formats in the order ## listed in this file. A plain '-MD' option would be understood by many ## compilers, so we must ensure this comes after the gcc and icc options. pgcc) # Portland's C compiler understands '-MD'. # Will always output deps to 'file.d' where file is the root name of the # source file under compilation, even if file resides in a subdirectory. # The object file name does not affect the name of the '.d' file. # pgcc 10.2 will output # foo.o: sub/foo.c sub/foo.h # and will wrap long lines using '\' : # foo.o: sub/foo.c ... \ # sub/foo.h ... \ # ... set_dir_from "$object" # Use the source, not the object, to determine the base name, since # that's sadly what pgcc will do too. set_base_from "$source" tmpdepfile=$base.d # For projects that build the same source file twice into different object # files, the pgcc approach of using the *source* file root name can cause # problems in parallel builds. Use a locking strategy to avoid stomping on # the same $tmpdepfile. lockdir=$base.d-lock trap " echo '$0: caught signal, cleaning up...' >&2 rmdir '$lockdir' exit 1 " 1 2 13 15 numtries=100 i=$numtries while test $i -gt 0; do # mkdir is a portable test-and-set. if mkdir "$lockdir" 2>/dev/null; then # This process acquired the lock. "$@" -MD stat=$? # Release the lock. rmdir "$lockdir" break else # If the lock is being held by a different process, wait # until the winning process is done or we timeout. while test -d "$lockdir" && test $i -gt 0; do sleep 1 i=`expr $i - 1` done fi i=`expr $i - 1` done trap - 1 2 13 15 if test $i -le 0; then echo "$0: failed to acquire lock after $numtries attempts" >&2 echo "$0: check lockdir '$lockdir'" >&2 exit 1 fi if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" # Each line is of the form `foo.o: dependent.h', # or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'. # Do two passes, one to just change these to # `$object: dependent.h' and one to simply `dependent.h:'. sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile" # Some versions of the HPUX 10.20 sed can't process this invocation # correctly. Breaking it into two sed invocations is a workaround. sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; hp2) # The "hp" stanza above does not work with aCC (C++) and HP's ia64 # compilers, which have integrated preprocessors. The correct option # to use with these is +Maked; it writes dependencies to a file named # 'foo.d', which lands next to the object file, wherever that # happens to be. # Much of this is similar to the tru64 case; see comments there. set_dir_from "$object" set_base_from "$object" if test "$libtool" = yes; then tmpdepfile1=$dir$base.d tmpdepfile2=$dir.libs/$base.d "$@" -Wc,+Maked else tmpdepfile1=$dir$base.d tmpdepfile2=$dir$base.d "$@" +Maked fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile1" "$tmpdepfile2" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" do test -f "$tmpdepfile" && break done if test -f "$tmpdepfile"; then sed -e "s,^.*\.[$lower]*:,$object:," "$tmpdepfile" > "$depfile" # Add 'dependent.h:' lines. sed -ne '2,${ s/^ *// s/ \\*$// s/$/:/ p }' "$tmpdepfile" >> "$depfile" else make_dummy_depfile fi rm -f "$tmpdepfile" "$tmpdepfile2" ;; tru64) # The Tru64 compiler uses -MD to generate dependencies as a side # effect. 'cc -MD -o foo.o ...' puts the dependencies into 'foo.o.d'. # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put # dependencies in 'foo.d' instead, so we check for that too. # Subdirectories are respected. set_dir_from "$object" set_base_from "$object" if test "$libtool" = yes; then # Libtool generates 2 separate objects for the 2 libraries. These # two compilations output dependencies in $dir.libs/$base.o.d and # in $dir$base.o.d. We have to check for both files, because # one of the two compilations can be disabled. We should prefer # $dir$base.o.d over $dir.libs/$base.o.d because the latter is # automatically cleaned when .libs/ is deleted, while ignoring # the former would cause a distcleancheck panic. tmpdepfile1=$dir$base.o.d # libtool 1.5 tmpdepfile2=$dir.libs/$base.o.d # Likewise. tmpdepfile3=$dir.libs/$base.d # Compaq CCC V6.2-504 "$@" -Wc,-MD else tmpdepfile1=$dir$base.d tmpdepfile2=$dir$base.d tmpdepfile3=$dir$base.d "$@" -MD fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" do test -f "$tmpdepfile" && break done # Same post-processing that is required for AIX mode. aix_post_process_depfile ;; msvc7) if test "$libtool" = yes; then showIncludes=-Wc,-showIncludes else showIncludes=-showIncludes fi "$@" $showIncludes > "$tmpdepfile" stat=$? grep -v '^Note: including file: ' "$tmpdepfile" if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" echo "$object : \\" > "$depfile" # The first sed program below extracts the file names and escapes # backslashes for cygpath. The second sed program outputs the file # name when reading, but also accumulates all include files in the # hold buffer in order to output them again at the end. This only # works with sed implementations that can handle large buffers. sed < "$tmpdepfile" -n ' /^Note: including file: *\(.*\)/ { s//\1/ s/\\/\\\\/g p }' | $cygpath_u | sort -u | sed -n ' s/ /\\ /g s/\(.*\)/'"$tab"'\1 \\/p s/.\(.*\) \\/\1:/ H $ { s/.*/'"$tab"'/ G p }' >> "$depfile" echo >> "$depfile" # make sure the fragment doesn't end with a backslash rm -f "$tmpdepfile" ;; msvc7msys) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; #nosideeffect) # This comment above is used by automake to tell side-effect # dependency tracking mechanisms from slower ones. dashmstdout) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout, regardless of -o. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # Remove '-o $object'. IFS=" " for arg do case $arg in -o) shift ;; $object) shift ;; *) set fnord "$@" "$arg" shift # fnord shift # $arg ;; esac done test -z "$dashmflag" && dashmflag=-M # Require at least two characters before searching for ':' # in the target name. This is to cope with DOS-style filenames: # a dependency such as 'c:/foo/bar' could be seen as target 'c' otherwise. "$@" $dashmflag | sed "s|^[$tab ]*[^:$tab ][^:][^:]*:[$tab ]*|$object: |" > "$tmpdepfile" rm -f "$depfile" cat < "$tmpdepfile" > "$depfile" # Some versions of the HPUX 10.20 sed can't process this sed invocation # correctly. Breaking it into two sed invocations is a workaround. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; dashXmstdout) # This case only exists to satisfy depend.m4. It is never actually # run, as this mode is specially recognized in the preamble. exit 1 ;; makedepend) "$@" || exit $? # Remove any Libtool call if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # X makedepend shift cleared=no eat=no for arg do case $cleared in no) set ""; shift cleared=yes ;; esac if test $eat = yes; then eat=no continue fi case "$arg" in -D*|-I*) set fnord "$@" "$arg"; shift ;; # Strip any option that makedepend may not understand. Remove # the object too, otherwise makedepend will parse it as a source file. -arch) eat=yes ;; -*|$object) ;; *) set fnord "$@" "$arg"; shift ;; esac done obj_suffix=`echo "$object" | sed 's/^.*\././'` touch "$tmpdepfile" ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@" rm -f "$depfile" # makedepend may prepend the VPATH from the source file name to the object. # No need to regex-escape $object, excess matching of '.' is harmless. sed "s|^.*\($object *:\)|\1|" "$tmpdepfile" > "$depfile" # Some versions of the HPUX 10.20 sed can't process the last invocation # correctly. Breaking it into two sed invocations is a workaround. sed '1,2d' "$tmpdepfile" \ | tr ' ' "$nl" \ | sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" "$tmpdepfile".bak ;; cpp) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # Remove '-o $object'. IFS=" " for arg do case $arg in -o) shift ;; $object) shift ;; *) set fnord "$@" "$arg" shift # fnord shift # $arg ;; esac done "$@" -E \ | sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \ -e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \ | sed '$ s: \\$::' > "$tmpdepfile" rm -f "$depfile" echo "$object : \\" > "$depfile" cat < "$tmpdepfile" >> "$depfile" sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; msvisualcpp) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi IFS=" " for arg do case "$arg" in -o) shift ;; $object) shift ;; "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI") set fnord "$@" shift shift ;; *) set fnord "$@" "$arg" shift shift ;; esac done "$@" -E 2>/dev/null | sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::\1:p' | $cygpath_u | sort -u > "$tmpdepfile" rm -f "$depfile" echo "$object : \\" > "$depfile" sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::'"$tab"'\1 \\:p' >> "$depfile" echo "$tab" >> "$depfile" sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::\1\::p' >> "$depfile" rm -f "$tmpdepfile" ;; msvcmsys) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; none) exec "$@" ;; *) echo "Unknown depmode $depmode" 1>&2 exit 1 ;; esac exit 0 # Local Variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End:
YifuLiu/AliOS-Things
components/SDL2/src/image/depcomp
Shell
apache-2.0
23,568
#!/bin/sh # # Build Universal binaries on Mac OS X, thanks Ryan! # # Usage: ./configure CC="sh gcc-fat.sh" && make && rm -rf x86 x64 DEVELOPER="`xcode-select -print-path`/Platforms/MacOSX.platform/Developer" # Intel 32-bit compiler flags (10.6 runtime compatibility) GCC_COMPILE_X86="gcc -arch i386 -mmacosx-version-min=10.6 \ -DMAC_OS_X_VERSION_MIN_REQUIRED=1040 \ -I/usr/local/include" GCC_LINK_X86="-mmacosx-version-min=10.6" # Intel 64-bit compiler flags (10.6 runtime compatibility) GCC_COMPILE_X64="gcc -arch x86_64 -mmacosx-version-min=10.6 \ -DMAC_OS_X_VERSION_MIN_REQUIRED=1050 \ -I/usr/local/include" GCC_LINK_X64="-mmacosx-version-min=10.6" # Output both PowerPC and Intel object files args="$*" compile=yes link=yes while test x$1 != x; do case $1 in --version) exec gcc $1;; -v) exec gcc $1;; -V) exec gcc $1;; -print-prog-name=*) exec gcc $1;; -print-search-dirs) exec gcc $1;; -E) GCC_COMPILE_X86="$GCC_COMPILE_X86 -E" GCC_COMPILE_X64="$GCC_COMPILE_X64 -E" compile=no; link=no;; -c) link=no;; -o) output=$2;; *.c|*.cc|*.cpp|*.S) source=$1;; esac shift done if test x$link = xyes; then GCC_COMPILE_X86="$GCC_COMPILE_X86 $GCC_LINK_X86" GCC_COMPILE_X64="$GCC_COMPILE_X64 $GCC_LINK_X64" fi if test x"$output" = x; then if test x$link = xyes; then output=a.out elif test x$compile = xyes; then output=`echo $source | sed -e 's|.*/||' -e 's|\(.*\)\.[^\.]*|\1|'`.o fi fi # Compile X86 32-bit if test x"$output" != x; then dir=x86/`dirname $output` if test -d $dir; then : else mkdir -p $dir fi fi set -- $args while test x$1 != x; do if test -f "x86/$1" && test "$1" != "$output"; then x86_args="$x86_args x86/$1" else x86_args="$x86_args $1" fi shift done $GCC_COMPILE_X86 $x86_args || exit $? if test x"$output" != x; then cp $output x86/$output fi # Compile X86 32-bit if test x"$output" != x; then dir=x64/`dirname $output` if test -d $dir; then : else mkdir -p $dir fi fi set -- $args while test x$1 != x; do if test -f "x64/$1" && test "$1" != "$output"; then x64_args="$x64_args x64/$1" else x64_args="$x64_args $1" fi shift done $GCC_COMPILE_X64 $x64_args || exit $? if test x"$output" != x; then cp $output x64/$output fi if test x"$output" != x; then lipo -create -o $output x86/$output x64/$output fi
YifuLiu/AliOS-Things
components/SDL2/src/image/gcc-fat.sh
Shell
apache-2.0
2,513
#!/bin/sh # install - install a program, script, or datafile scriptversion=2017-09-23.17; # UTC # This originates from X11R5 (mit/util/scripts/install.sh), which was # later released in X11R6 (xc/config/util/install.sh) with the # following copyright and license. # # Copyright (C) 1994 X Consortium # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN # AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- # TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # Except as contained in this notice, the name of the X Consortium shall not # be used in advertising or otherwise to promote the sale, use or other deal- # ings in this Software without prior written authorization from the X Consor- # tium. # # # FSF changes to this file are in the public domain. # # Calling this script install-sh is preferred over install.sh, to prevent # 'make' implicit rules from creating a file called install from it # when there is no Makefile. # # This script is compatible with the BSD install script, but was written # from scratch. tab=' ' nl=' ' IFS=" $tab$nl" # Set DOITPROG to "echo" to test this script. doit=${DOITPROG-} doit_exec=${doit:-exec} # Put in absolute file names if you don't have them in your path; # or use environment vars. chgrpprog=${CHGRPPROG-chgrp} chmodprog=${CHMODPROG-chmod} chownprog=${CHOWNPROG-chown} cmpprog=${CMPPROG-cmp} cpprog=${CPPROG-cp} mkdirprog=${MKDIRPROG-mkdir} mvprog=${MVPROG-mv} rmprog=${RMPROG-rm} stripprog=${STRIPPROG-strip} posix_mkdir= # Desired mode of installed file. mode=0755 chgrpcmd= chmodcmd=$chmodprog chowncmd= mvcmd=$mvprog rmcmd="$rmprog -f" stripcmd= src= dst= dir_arg= dst_arg= copy_on_change=false is_target_a_directory=possibly usage="\ Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE or: $0 [OPTION]... SRCFILES... DIRECTORY or: $0 [OPTION]... -t DIRECTORY SRCFILES... or: $0 [OPTION]... -d DIRECTORIES... In the 1st form, copy SRCFILE to DSTFILE. In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. In the 4th, create DIRECTORIES. Options: --help display this help and exit. --version display version info and exit. -c (ignored) -C install only if different (preserve the last data modification time) -d create directories instead of installing files. -g GROUP $chgrpprog installed files to GROUP. -m MODE $chmodprog installed files to MODE. -o USER $chownprog installed files to USER. -s $stripprog installed files. -t DIRECTORY install into DIRECTORY. -T report an error if DSTFILE is a directory. Environment variables override the default commands: CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG " while test $# -ne 0; do case $1 in -c) ;; -C) copy_on_change=true;; -d) dir_arg=true;; -g) chgrpcmd="$chgrpprog $2" shift;; --help) echo "$usage"; exit $?;; -m) mode=$2 case $mode in *' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*) echo "$0: invalid mode: $mode" >&2 exit 1;; esac shift;; -o) chowncmd="$chownprog $2" shift;; -s) stripcmd=$stripprog;; -t) is_target_a_directory=always dst_arg=$2 # Protect names problematic for 'test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac shift;; -T) is_target_a_directory=never;; --version) echo "$0 $scriptversion"; exit $?;; --) shift break;; -*) echo "$0: invalid option: $1" >&2 exit 1;; *) break;; esac shift done # We allow the use of options -d and -T together, by making -d # take the precedence; this is for compatibility with GNU install. if test -n "$dir_arg"; then if test -n "$dst_arg"; then echo "$0: target directory not allowed when installing a directory." >&2 exit 1 fi fi if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then # When -d is used, all remaining arguments are directories to create. # When -t is used, the destination is already specified. # Otherwise, the last argument is the destination. Remove it from $@. for arg do if test -n "$dst_arg"; then # $@ is not empty: it contains at least $arg. set fnord "$@" "$dst_arg" shift # fnord fi shift # arg dst_arg=$arg # Protect names problematic for 'test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac done fi if test $# -eq 0; then if test -z "$dir_arg"; then echo "$0: no input file specified." >&2 exit 1 fi # It's OK to call 'install-sh -d' without argument. # This can happen when creating conditional directories. exit 0 fi if test -z "$dir_arg"; then if test $# -gt 1 || test "$is_target_a_directory" = always; then if test ! -d "$dst_arg"; then echo "$0: $dst_arg: Is not a directory." >&2 exit 1 fi fi fi if test -z "$dir_arg"; then do_exit='(exit $ret); exit $ret' trap "ret=129; $do_exit" 1 trap "ret=130; $do_exit" 2 trap "ret=141; $do_exit" 13 trap "ret=143; $do_exit" 15 # Set umask so as not to create temps with too-generous modes. # However, 'strip' requires both read and write access to temps. case $mode in # Optimize common cases. *644) cp_umask=133;; *755) cp_umask=22;; *[0-7]) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw='% 200' fi cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; *) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw=,u+rw fi cp_umask=$mode$u_plus_rw;; esac fi for src do # Protect names problematic for 'test' and other utilities. case $src in -* | [=\(\)!]) src=./$src;; esac if test -n "$dir_arg"; then dst=$src dstdir=$dst test -d "$dstdir" dstdir_status=$? else # Waiting for this to be detected by the "$cpprog $src $dsttmp" command # might cause directories to be created, which would be especially bad # if $src (and thus $dsttmp) contains '*'. if test ! -f "$src" && test ! -d "$src"; then echo "$0: $src does not exist." >&2 exit 1 fi if test -z "$dst_arg"; then echo "$0: no destination specified." >&2 exit 1 fi dst=$dst_arg # If destination is a directory, append the input filename. if test -d "$dst"; then if test "$is_target_a_directory" = never; then echo "$0: $dst_arg: Is a directory" >&2 exit 1 fi dstdir=$dst dstbase=`basename "$src"` case $dst in */) dst=$dst$dstbase;; *) dst=$dst/$dstbase;; esac dstdir_status=0 else dstdir=`dirname "$dst"` test -d "$dstdir" dstdir_status=$? fi fi case $dstdir in */) dstdirslash=$dstdir;; *) dstdirslash=$dstdir/;; esac obsolete_mkdir_used=false if test $dstdir_status != 0; then case $posix_mkdir in '') # Create intermediate dirs using mode 755 as modified by the umask. # This is like FreeBSD 'install' as of 1997-10-28. umask=`umask` case $stripcmd.$umask in # Optimize common cases. *[2367][2367]) mkdir_umask=$umask;; .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;; *[0-7]) mkdir_umask=`expr $umask + 22 \ - $umask % 100 % 40 + $umask % 20 \ - $umask % 10 % 4 + $umask % 2 `;; *) mkdir_umask=$umask,go-w;; esac # With -d, create the new directory with the user-specified mode. # Otherwise, rely on $mkdir_umask. if test -n "$dir_arg"; then mkdir_mode=-m$mode else mkdir_mode= fi posix_mkdir=false case $umask in *[123567][0-7][0-7]) # POSIX mkdir -p sets u+wx bits regardless of umask, which # is incompatible with FreeBSD 'install' when (umask & 300) != 0. ;; *) tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0 if (umask $mkdir_umask && exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1 then if test -z "$dir_arg" || { # Check for POSIX incompatibilities with -m. # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or # other-writable bit of parent directory when it shouldn't. # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. ls_ld_tmpdir=`ls -ld "$tmpdir"` case $ls_ld_tmpdir in d????-?r-*) different_mode=700;; d????-?--*) different_mode=755;; *) false;; esac && $mkdirprog -m$different_mode -p -- "$tmpdir" && { ls_ld_tmpdir_1=`ls -ld "$tmpdir"` test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" } } then posix_mkdir=: fi rmdir "$tmpdir/d" "$tmpdir" else # Remove any dirs left behind by ancient mkdir implementations. rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null fi trap '' 0;; esac;; esac if $posix_mkdir && ( umask $mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" ) then : else # The umask is ridiculous, or mkdir does not conform to POSIX, # or it failed possibly due to a race condition. Create the # directory the slow way, step by step, checking for races as we go. case $dstdir in /*) prefix='/';; [-=\(\)!]*) prefix='./';; *) prefix='';; esac oIFS=$IFS IFS=/ set -f set fnord $dstdir shift set +f IFS=$oIFS prefixes= for d do test X"$d" = X && continue prefix=$prefix$d if test -d "$prefix"; then prefixes= else if $posix_mkdir; then (umask=$mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break # Don't fail if two instances are running concurrently. test -d "$prefix" || exit 1 else case $prefix in *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; *) qprefix=$prefix;; esac prefixes="$prefixes '$qprefix'" fi fi prefix=$prefix/ done if test -n "$prefixes"; then # Don't fail if two instances are running concurrently. (umask $mkdir_umask && eval "\$doit_exec \$mkdirprog $prefixes") || test -d "$dstdir" || exit 1 obsolete_mkdir_used=true fi fi fi if test -n "$dir_arg"; then { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 else # Make a couple of temp file names in the proper directory. dsttmp=${dstdirslash}_inst.$$_ rmtmp=${dstdirslash}_rm.$$_ # Trap to clean up those temp files at exit. trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 # Copy the file name to the temp name. (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") && # and set any options; do chmod last to preserve setuid bits. # # If any of these fail, we abort the whole thing. If we want to # ignore errors from any of these, just make sure not to ignore # errors from the above "$doit $cpprog $src $dsttmp" command. # { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } && { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && # If -C, don't bother to copy if it wouldn't change the file. if $copy_on_change && old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` && new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` && set -f && set X $old && old=:$2:$4:$5:$6 && set X $new && new=:$2:$4:$5:$6 && set +f && test "$old" = "$new" && $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1 then rm -f "$dsttmp" else # Rename the file to the real destination. $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null || # The rename failed, perhaps because mv can't rename something else # to itself, or perhaps because mv is so ancient that it does not # support -f. { # Now remove or move aside any old file at destination location. # We try this two ways since rm can't unlink itself on some # systems and the destination file might be busy for other # reasons. In this case, the final cleanup might fail but the new # file should still install successfully. { test ! -f "$dst" || $doit $rmcmd -f "$dst" 2>/dev/null || { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null && { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; } } || { echo "$0: cannot unlink or rename $dst" >&2 (exit 1); exit 1 } } && # Now rename the file to the real destination. $doit $mvcmd "$dsttmp" "$dst" } fi || exit 1 trap '' 0 fi done # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End:
YifuLiu/AliOS-Things
components/SDL2/src/image/install-sh
Shell
apache-2.0
14,799
#! /bin/bash # libtool - Provide generalized library-building support services. # Generated automatically by config.status (SDL2_image) 2.0.5 # Libtool was configured on host localhost: # NOTE: Changes made to this file will be lost: look at ltmain.sh. # # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, # 2006, 2007, 2008 Free Software Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is part of GNU Libtool. # # GNU Libtool is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, or # obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # The names of the tagged configurations supported by this script. available_tags="" # ### BEGIN LIBTOOL CONFIG # Which release of libtool.m4 was used? macro_version=2.2.6 macro_revision=1.3012 # Assembler program. AS=as # DLL creation program. DLLTOOL=dlltool # Object dumper program. OBJDUMP=objdump # Whether or not to build shared libraries. build_libtool_libs=yes # Whether or not to build static libraries. build_old_libs=yes # What type of objects to build. pic_mode=default # Whether or not to optimize for fast installation. fast_install=yes # The host system. host_alias= host=x86_64-pc-linux-gnu host_os=linux-gnu # The build system. build_alias= build=x86_64-pc-linux-gnu build_os=linux-gnu # A sed program that does not truncate output. SED="/bin/sed" # Sed that helps us avoid accidentally triggering echo(1) options like -n. Xsed="$SED -e 1s/^X//" # A grep program that handles long lines. GREP="/bin/grep" # An ERE matcher. EGREP="/bin/grep -E" # A literal string matcher. FGREP="/bin/grep -F" # A BSD- or MS-compatible name lister. NM="/usr/bin/nm -B" # Whether we need soft or hard links. LN_S="ln -s" # What is the maximum length of a command? max_cmd_len=1572864 # Object file suffix (normally "o"). objext=o # Executable file suffix (normally ""). exeext= # whether the shell understands "unset". lt_unset=unset # turn spaces into newlines. SP2NL="tr \\040 \\012" # turn newlines into spaces. NL2SP="tr \\015\\012 \\040\\040" # How to create reloadable object files. reload_flag=" -r" reload_cmds="\$LD\$reload_flag -o \$output\$reload_objs" # Method to check whether dependent libraries are shared objects. deplibs_check_method="pass_all" # Command to use when deplibs_check_method == "file_magic". file_magic_cmd="\$MAGIC_CMD" # The archiver. AR="ar" AR_FLAGS="cru" # A symbol stripping program. STRIP="strip" # Commands used to install an old-style archive. RANLIB="ranlib" old_postinstall_cmds="chmod 644 \$oldlib~\$RANLIB \$oldlib" old_postuninstall_cmds="" # A C compiler. LTCC="gcc" # LTCC compiler flags. LTCFLAGS="-g -O2 -D_REENTRANT -I/usr/local/include/SDL2" # Take the output of nm and produce a listing of raw symbols and C names. global_symbol_pipe="sed -n -e 's/^.*[ ]\\([ABCDGIRSTW][ABCDGIRSTW]*\\)[ ][ ]*\\([_A-Za-z][_A-Za-z0-9]*\\)\$/\\1 \\2 \\2/p'" # Transform the output of nm in a proper C declaration. global_symbol_to_cdecl="sed -n -e 's/^T .* \\(.*\\)\$/extern int \\1();/p' -e 's/^[ABCDGIRSTW]* .* \\(.*\\)\$/extern char \\1;/p'" # Transform the output of nm in a C name address pair. global_symbol_to_c_name_address="sed -n -e 's/^: \\([^ ]*\\) \$/ {\\\"\\1\\\", (void *) 0},/p' -e 's/^[ABCDGIRSTW]* \\([^ ]*\\) \\([^ ]*\\)\$/ {\"\\2\", (void *) \\&\\2},/p'" # Transform the output of nm in a C name address pair when lib prefix is needed. global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \\([^ ]*\\) \$/ {\\\"\\1\\\", (void *) 0},/p' -e 's/^[ABCDGIRSTW]* \\([^ ]*\\) \\(lib[^ ]*\\)\$/ {\"\\2\", (void *) \\&\\2},/p' -e 's/^[ABCDGIRSTW]* \\([^ ]*\\) \\([^ ]*\\)\$/ {\"lib\\2\", (void *) \\&\\2},/p'" # The name of the directory that contains temporary libtool files. objdir=.libs # Shell to use when invoking shell scripts. SHELL="/bin/bash" # An echo program that does not interpret backslashes. ECHO="echo" # Used to examine libraries when file_magic_cmd begins with "file". MAGIC_CMD=file # Must we lock files when doing compilation? need_locks="no" # Tool to manipulate archived DWARF debug symbol files on Mac OS X. DSYMUTIL="" # Tool to change global to local symbols on Mac OS X. NMEDIT="" # Tool to manipulate fat objects and archives on Mac OS X. LIPO="" # ldd/readelf like tool for Mach-O binaries on Mac OS X. OTOOL="" # ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4. OTOOL64="" # Old archive suffix (normally "a"). libext=a # Shared library suffix (normally ".so"). shrext_cmds=".so" # The commands to extract the exported symbol list from a shared archive. extract_expsyms_cmds="" # Variables whose values should be saved in libtool wrapper scripts and # restored at link time. variables_saved_for_relink="PATH LD_LIBRARY_PATH LD_RUN_PATH GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" # Do we need the "lib" prefix for modules? need_lib_prefix=no # Do we need a version for libraries? need_version=no # Library versioning type. version_type=linux # Shared library runtime path variable. runpath_var=LD_RUN_PATH # Shared library path variable. shlibpath_var=LD_LIBRARY_PATH # Is shlibpath searched before the hard-coded library search path? shlibpath_overrides_runpath=no # Format of library name prefix. libname_spec="lib\$name" # List of archive names. First name is the real one, the rest are links. # The last name is the one that the linker finds with -lNAME library_names_spec="\${libname}\${release}\${shared_ext}\$versuffix \${libname}\${release}\${shared_ext}\$major \$libname\${shared_ext}" # The coded name of the library, if different from the real name. soname_spec="\${libname}\${release}\${shared_ext}\$major" # Command to use after installation of a shared archive. postinstall_cmds="" # Command to use after uninstallation of a shared archive. postuninstall_cmds="" # Commands used to finish a libtool library installation in a directory. finish_cmds="PATH=\\\"\\\$PATH:/sbin\\\" ldconfig -n \$libdir" # As "finish_cmds", except a single script fragment to be evaled but # not shown. finish_eval="" # Whether we should hardcode library paths into libraries. hardcode_into_libs=yes # Compile-time system search path for libraries. sys_lib_search_path_spec="/usr/lib/gcc/x86_64-linux-gnu/5 /usr/lib/x86_64-linux-gnu /usr/lib /lib/x86_64-linux-gnu /lib" # Run-time system search path for libraries. sys_lib_dlsearch_path_spec="/lib /usr/lib /lib/i386-linux-gnu /usr/lib/i386-linux-gnu /lib/i686-linux-gnu /usr/lib/i686-linux-gnu /usr/local/lib /lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu/mesa-egl /usr/lib/x86_64-linux-gnu/mesa /lib32 /usr/lib32 /libx32 /usr/libx32 " # Whether dlopen is supported. dlopen_support=unknown # Whether dlopen of programs is supported. dlopen_self=unknown # Whether dlopen of statically linked programs is supported. dlopen_self_static=unknown # Commands to strip libraries. old_striplib="strip --strip-debug" striplib="strip --strip-unneeded" # The linker used to build libraries. LD="/usr/bin/ld -m elf_x86_64" # Commands used to build an old-style archive. old_archive_cmds="\$AR \$AR_FLAGS \$oldlib\$oldobjs~\$RANLIB \$oldlib" # A language specific compiler. CC="gcc" # Is the compiler the GNU compiler? with_gcc=yes # Compiler flag to turn off builtin functions. no_builtin_flag=" -fno-builtin" # How to pass a linker flag through the compiler. wl="-Wl," # Additional compiler flags for building library objects. pic_flag=" -fPIC -DPIC" # Compiler flag to prevent dynamic linking. link_static_flag="-static" # Does compiler simultaneously support -c and -o options? compiler_c_o="yes" # Whether or not to add -lc for building shared libraries. build_libtool_need_lc=no # Whether or not to disallow shared libs when runtime libs are static. allow_libtool_libs_with_static_runtimes=no # Compiler flag to allow reflexive dlopens. export_dynamic_flag_spec="\${wl}--export-dynamic" # Compiler flag to generate shared objects directly from archives. whole_archive_flag_spec="\${wl}--whole-archive\$convenience \${wl}--no-whole-archive" # Whether the compiler copes with passing no objects directly. compiler_needs_object="no" # Create an old-style archive from a shared archive. old_archive_from_new_cmds="" # Create a temporary old-style archive to link instead of a shared archive. old_archive_from_expsyms_cmds="" # Commands used to build a shared archive. archive_cmds="\$CC -shared \$libobjs \$deplibs \$compiler_flags \${wl}-soname \$wl\$soname -o \$lib" archive_expsym_cmds="echo \\\"{ global:\\\" > \$output_objdir/\$libname.ver~ cat \$export_symbols | sed -e \\\"s/\\\\(.*\\\\)/\\\\1;/\\\" >> \$output_objdir/\$libname.ver~ echo \\\"local: *; };\\\" >> \$output_objdir/\$libname.ver~ \$CC -shared \$libobjs \$deplibs \$compiler_flags \${wl}-soname \$wl\$soname \${wl}-version-script \${wl}\$output_objdir/\$libname.ver -o \$lib" # Commands used to build a loadable module if different from building # a shared archive. module_cmds="" module_expsym_cmds="" # Whether we are building with GNU ld or not. with_gnu_ld="yes" # Flag that allows shared libraries with undefined symbols to be built. allow_undefined_flag="" # Flag that enforces no undefined symbols. no_undefined_flag="" # Flag to hardcode $libdir into a binary during linking. # This must work even if $libdir does not exist hardcode_libdir_flag_spec="\${wl}-rpath \${wl}\$libdir" # If ld is used when linking, flag to hardcode $libdir into a binary # during linking. This must work even if $libdir does not exist. hardcode_libdir_flag_spec_ld="" # Whether we need a single "-rpath" flag with a separated argument. hardcode_libdir_separator="" # Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes # DIR into the resulting binary. hardcode_direct=no # Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes # DIR into the resulting binary and the resulting library dependency is # "absolute",i.e impossible to change by setting ${shlibpath_var} if the # library is relocated. hardcode_direct_absolute=no # Set to "yes" if using the -LDIR flag during linking hardcodes DIR # into the resulting binary. hardcode_minus_L=no # Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR # into the resulting binary. hardcode_shlibpath_var=unsupported # Set to "yes" if building a shared library automatically hardcodes DIR # into the library and all subsequent libraries and executables linked # against it. hardcode_automatic=no # Set to yes if linker adds runtime paths of dependent libraries # to runtime path list. inherit_rpath=no # Whether libtool must link a program against all its dependency libraries. link_all_deplibs=unknown # Fix the shell variable $srcfile for the compiler. fix_srcfile_path="" # Set to "yes" if exported symbols are required. always_export_symbols=no # The commands to list exported symbols. export_symbols_cmds="\$NM \$libobjs \$convenience | \$global_symbol_pipe | \$SED 's/.* //' | sort | uniq > \$export_symbols" # Symbols that should not be listed in the preloaded symbols. exclude_expsyms="_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*" # Symbols that must always be exported. include_expsyms="" # Commands necessary for linking programs (against libraries) with templates. prelink_cmds="" # Specify filename containing input files. file_list_spec="" # How to hardcode a shared library path into an executable. hardcode_action=immediate # ### END LIBTOOL CONFIG # Generated from ltmain.m4sh. # ltmain.sh (GNU libtool) 2.2.6 # Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996 # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007 2008 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, # or obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Usage: $progname [OPTION]... [MODE-ARG]... # # Provide generalized library-building support services. # # --config show all configuration variables # --debug enable verbose shell tracing # -n, --dry-run display commands without modifying any files # --features display basic configuration information and exit # --mode=MODE use operation mode MODE # --preserve-dup-deps don't remove duplicate dependency libraries # --quiet, --silent don't print informational messages # --tag=TAG use configuration variables from tag TAG # -v, --verbose print informational messages (default) # --version print version information # -h, --help print short or long help message # # MODE must be one of the following: # # clean remove files from the build directory # compile compile a source file into a libtool object # execute automatically set library path, then run a program # finish complete the installation of libtool libraries # install install libraries or executables # link create a library or an executable # uninstall remove libraries from an installed directory # # MODE-ARGS vary depending on the MODE. # Try `$progname --help --mode=MODE' for a more detailed description of MODE. # # When reporting a bug, please describe a test case to reproduce it and # include the following information: # # host-triplet: $host # shell: $SHELL # compiler: $LTCC # compiler flags: $LTCFLAGS # linker: $LD (gnu? $with_gnu_ld) # $progname: (GNU libtool) 2.2.6 # automake: $automake_version # autoconf: $autoconf_version # # Report bugs to <bug-libtool@gnu.org>. PROGRAM=ltmain.sh PACKAGE=libtool VERSION=2.2.6 TIMESTAMP="" package_revision=1.3012 # Be Bourne compatible if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # NLS nuisances: We save the old values to restore during execute mode. # Only set LANG and LC_ALL to C if already set. # These must not be set unconditionally because not all systems understand # e.g. LANG=C (notably SCO). lt_user_locale= lt_safe_locale= for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${$lt_var+set}\" = set; then save_$lt_var=\$$lt_var $lt_var=C export $lt_var lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\" lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\" fi" done $lt_unset CDPATH : ${CP="cp -f"} : ${ECHO="echo"} : ${EGREP="/usr/bin/grep -E"} : ${FGREP="/usr/bin/grep -F"} : ${GREP="/usr/bin/grep"} : ${LN_S="ln -s"} : ${MAKE="make"} : ${MKDIR="mkdir"} : ${MV="mv -f"} : ${RM="rm -f"} : ${SED="/opt/local/bin/gsed"} : ${SHELL="${CONFIG_SHELL-/bin/sh}"} : ${Xsed="$SED -e 1s/^X//"} # Global variables: EXIT_SUCCESS=0 EXIT_FAILURE=1 EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. exit_status=$EXIT_SUCCESS # Make sure IFS has a sensible default lt_nl=' ' IFS=" $lt_nl" dirname="s,/[^/]*$,," basename="s,^.*/,," # func_dirname_and_basename file append nondir_replacement # perform func_basename and func_dirname in a single function # call: # dirname: Compute the dirname of FILE. If nonempty, # add APPEND to the result, otherwise set result # to NONDIR_REPLACEMENT. # value returned in "$func_dirname_result" # basename: Compute filename of FILE. # value retuned in "$func_basename_result" # Implementation must be kept synchronized with func_dirname # and func_basename. For efficiency, we do not delegate to # those functions but instead duplicate the functionality here. func_dirname_and_basename () { # Extract subdirectory from the argument. func_dirname_result=`$ECHO "X${1}" | $Xsed -e "$dirname"` if test "X$func_dirname_result" = "X${1}"; then func_dirname_result="${3}" else func_dirname_result="$func_dirname_result${2}" fi func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"` } # Generated shell functions inserted here. # func_dirname file append nondir_replacement # Compute the dirname of FILE. If nonempty, add APPEND to the result, # otherwise set result to NONDIR_REPLACEMENT. func_dirname () { case ${1} in */*) func_dirname_result="${1%/*}${2}" ;; * ) func_dirname_result="${3}" ;; esac } # func_basename file func_basename () { func_basename_result="${1##*/}" } # func_dirname_and_basename file append nondir_replacement # perform func_basename and func_dirname in a single function # call: # dirname: Compute the dirname of FILE. If nonempty, # add APPEND to the result, otherwise set result # to NONDIR_REPLACEMENT. # value returned in "$func_dirname_result" # basename: Compute filename of FILE. # value retuned in "$func_basename_result" # Implementation must be kept synchronized with func_dirname # and func_basename. For efficiency, we do not delegate to # those functions but instead duplicate the functionality here. func_dirname_and_basename () { case ${1} in */*) func_dirname_result="${1%/*}${2}" ;; * ) func_dirname_result="${3}" ;; esac func_basename_result="${1##*/}" } # func_stripname prefix suffix name # strip PREFIX and SUFFIX off of NAME. # PREFIX and SUFFIX must not contain globbing or regex special # characters, hashes, percent signs, but SUFFIX may contain a leading # dot (in which case that matches only a dot). func_stripname () { # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are # positional parameters, so assign one to ordinary parameter first. func_stripname_result=${3} func_stripname_result=${func_stripname_result#"${1}"} func_stripname_result=${func_stripname_result%"${2}"} } # func_opt_split func_opt_split () { func_opt_split_opt=${1%%=*} func_opt_split_arg=${1#*=} } # func_lo2o object func_lo2o () { case ${1} in *.lo) func_lo2o_result=${1%.lo}.${objext} ;; *) func_lo2o_result=${1} ;; esac } # func_xform libobj-or-source func_xform () { func_xform_result=${1%.*}.lo } # func_arith arithmetic-term... func_arith () { func_arith_result=$(( $* )) } # func_len string # STRING may not start with a hyphen. func_len () { func_len_result=${#1} } # func_append var value # Append VALUE to the end of shell variable VAR. func_append () { eval "$1+=\$2" } # Generated shell functions inserted here. # Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh # is ksh but when the shell is invoked as "sh" and the current value of # the _XPG environment variable is not equal to 1 (one), the special # positional parameter $0, within a function call, is the name of the # function. progpath="$0" # The name of this program: # In the unlikely event $progname began with a '-', it would play havoc with # func_echo (imagine progname=-n), so we prepend ./ in that case: func_dirname_and_basename "$progpath" progname=$func_basename_result case $progname in -*) progname=./$progname ;; esac # Make sure we have an absolute path for reexecution: case $progpath in [\\/]*|[A-Za-z]:\\*) ;; *[\\/]*) progdir=$func_dirname_result progdir=`cd "$progdir" && pwd` progpath="$progdir/$progname" ;; *) save_IFS="$IFS" IFS=: for progdir in $PATH; do IFS="$save_IFS" test -x "$progdir/$progname" && break done IFS="$save_IFS" test -n "$progdir" || progdir=`pwd` progpath="$progdir/$progname" ;; esac # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. Xsed="${SED}"' -e 1s/^X//' sed_quote_subst='s/\([`"$\\]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\(["`\\]\)/\\\1/g' # Re-`\' parameter expansions in output of double_quote_subst that were # `\'-ed in input to the same. If an odd number of `\' preceded a '$' # in input to double_quote_subst, that '$' was protected from expansion. # Since each input `\' is now two `\'s, look for any number of runs of # four `\'s followed by two `\'s and then a '$'. `\' that '$'. bs='\\' bs2='\\\\' bs4='\\\\\\\\' dollar='\$' sed_double_backslash="\ s/$bs4/&\\ /g s/^$bs2$dollar/$bs&/ s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g s/\n//g" # Standard options: opt_dry_run=false opt_help=false opt_quiet=false opt_verbose=false opt_warning=: # func_echo arg... # Echo program name prefixed message, along with the current mode # name if it has been set yet. func_echo () { $ECHO "$progname${mode+: }$mode: $*" } # func_verbose arg... # Echo program name prefixed message in verbose mode only. func_verbose () { $opt_verbose && func_echo ${1+"$@"} # A bug in bash halts the script if the last line of a function # fails when set -e is in force, so we need another command to # work around that: : } # func_error arg... # Echo program name prefixed message to standard error. func_error () { $ECHO "$progname${mode+: }$mode: "${1+"$@"} 1>&2 } # func_warning arg... # Echo program name prefixed warning message to standard error. func_warning () { $opt_warning && $ECHO "$progname${mode+: }$mode: warning: "${1+"$@"} 1>&2 # bash bug again: : } # func_fatal_error arg... # Echo program name prefixed message to standard error, and exit. func_fatal_error () { func_error ${1+"$@"} exit $EXIT_FAILURE } # func_fatal_help arg... # Echo program name prefixed message to standard error, followed by # a help hint, and exit. func_fatal_help () { func_error ${1+"$@"} func_fatal_error "$help" } help="Try \`$progname --help' for more information." ## default # func_grep expression filename # Check whether EXPRESSION matches any line of FILENAME, without output. func_grep () { $GREP "$1" "$2" >/dev/null 2>&1 } # func_mkdir_p directory-path # Make sure the entire path to DIRECTORY-PATH is available. func_mkdir_p () { my_directory_path="$1" my_dir_list= if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then # Protect directory names starting with `-' case $my_directory_path in -*) my_directory_path="./$my_directory_path" ;; esac # While some portion of DIR does not yet exist... while test ! -d "$my_directory_path"; do # ...make a list in topmost first order. Use a colon delimited # list incase some portion of path contains whitespace. my_dir_list="$my_directory_path:$my_dir_list" # If the last portion added has no slash in it, the list is done case $my_directory_path in */*) ;; *) break ;; esac # ...otherwise throw away the child directory and loop my_directory_path=`$ECHO "X$my_directory_path" | $Xsed -e "$dirname"` done my_dir_list=`$ECHO "X$my_dir_list" | $Xsed -e 's,:*$,,'` save_mkdir_p_IFS="$IFS"; IFS=':' for my_dir in $my_dir_list; do IFS="$save_mkdir_p_IFS" # mkdir can fail with a `File exist' error if two processes # try to create one of the directories concurrently. Don't # stop in that case! $MKDIR "$my_dir" 2>/dev/null || : done IFS="$save_mkdir_p_IFS" # Bail out if we (or some other process) failed to create a directory. test -d "$my_directory_path" || \ func_fatal_error "Failed to create \`$1'" fi } # func_mktempdir [string] # Make a temporary directory that won't clash with other running # libtool processes, and avoids race conditions if possible. If # given, STRING is the basename for that directory. func_mktempdir () { my_template="${TMPDIR-/tmp}/${1-$progname}" if test "$opt_dry_run" = ":"; then # Return a directory name, but don't create it in dry-run mode my_tmpdir="${my_template}-$$" else # If mktemp works, use that first and foremost my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null` if test ! -d "$my_tmpdir"; then # Failing that, at least try and use $RANDOM to avoid a race my_tmpdir="${my_template}-${RANDOM-0}$$" save_mktempdir_umask=`umask` umask 0077 $MKDIR "$my_tmpdir" umask $save_mktempdir_umask fi # If we're not in dry-run mode, bomb out on failure test -d "$my_tmpdir" || \ func_fatal_error "cannot create temporary directory \`$my_tmpdir'" fi $ECHO "X$my_tmpdir" | $Xsed } # func_quote_for_eval arg # Aesthetically quote ARG to be evaled later. # This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT # is double-quoted, suitable for a subsequent eval, whereas # FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters # which are still active within double quotes backslashified. func_quote_for_eval () { case $1 in *[\\\`\"\$]*) func_quote_for_eval_unquoted_result=`$ECHO "X$1" | $Xsed -e "$sed_quote_subst"` ;; *) func_quote_for_eval_unquoted_result="$1" ;; esac case $func_quote_for_eval_unquoted_result in # Double-quote args containing shell metacharacters to delay # word splitting, command substitution and and variable # expansion for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\"" ;; *) func_quote_for_eval_result="$func_quote_for_eval_unquoted_result" esac } # func_quote_for_expand arg # Aesthetically quote ARG to be evaled later; same as above, # but do not quote variable references. func_quote_for_expand () { case $1 in *[\\\`\"]*) my_arg=`$ECHO "X$1" | $Xsed \ -e "$double_quote_subst" -e "$sed_double_backslash"` ;; *) my_arg="$1" ;; esac case $my_arg in # Double-quote args containing shell metacharacters to delay # word splitting and command substitution for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") my_arg="\"$my_arg\"" ;; esac func_quote_for_expand_result="$my_arg" } # func_show_eval cmd [fail_exp] # Unless opt_silent is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. func_show_eval () { my_cmd="$1" my_fail_exp="${2-:}" ${opt_silent-false} || { func_quote_for_expand "$my_cmd" eval "func_echo $func_quote_for_expand_result" } if ${opt_dry_run-false}; then :; else eval "$my_cmd" my_status=$? if test "$my_status" -eq 0; then :; else eval "(exit $my_status); $my_fail_exp" fi fi } # func_show_eval_locale cmd [fail_exp] # Unless opt_silent is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. Use the saved locale for evaluation. func_show_eval_locale () { my_cmd="$1" my_fail_exp="${2-:}" ${opt_silent-false} || { func_quote_for_expand "$my_cmd" eval "func_echo $func_quote_for_expand_result" } if ${opt_dry_run-false}; then :; else eval "$lt_user_locale $my_cmd" my_status=$? eval "$lt_safe_locale" if test "$my_status" -eq 0; then :; else eval "(exit $my_status); $my_fail_exp" fi fi } # func_version # Echo version message to standard output and exit. func_version () { $SED -n '/^# '$PROGRAM' (GNU /,/# warranty; / { s/^# // s/^# *$// s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/ p }' < "$progpath" exit $? } # func_usage # Echo short help message to standard output and exit. func_usage () { $SED -n '/^# Usage:/,/# -h/ { s/^# // s/^# *$// s/\$progname/'$progname'/ p }' < "$progpath" $ECHO $ECHO "run \`$progname --help | more' for full usage" exit $? } # func_help # Echo long help message to standard output and exit. func_help () { $SED -n '/^# Usage:/,/# Report bugs to/ { s/^# // s/^# *$// s*\$progname*'$progname'* s*\$host*'"$host"'* s*\$SHELL*'"$SHELL"'* s*\$LTCC*'"$LTCC"'* s*\$LTCFLAGS*'"$LTCFLAGS"'* s*\$LD*'"$LD"'* s/\$with_gnu_ld/'"$with_gnu_ld"'/ s/\$automake_version/'"`(automake --version) 2>/dev/null |$SED 1q`"'/ s/\$autoconf_version/'"`(autoconf --version) 2>/dev/null |$SED 1q`"'/ p }' < "$progpath" exit $? } # func_missing_arg argname # Echo program name prefixed message to standard error and set global # exit_cmd. func_missing_arg () { func_error "missing argument for $1" exit_cmd=exit } exit_cmd=: # Check that we have a working $ECHO. if test "X$1" = X--no-reexec; then # Discard the --no-reexec flag, and continue. shift elif test "X$1" = X--fallback-echo; then # Avoid inline document here, it may be left over : elif test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t'; then # Yippee, $ECHO works! : else # Restart under the correct shell, and then maybe $ECHO will work. exec $SHELL "$progpath" --no-reexec ${1+"$@"} fi if test "X$1" = X--fallback-echo; then # used as fallback echo shift cat <<EOF $* EOF exit $EXIT_SUCCESS fi magic="%%%MAGIC variable%%%" magic_exe="%%%MAGIC EXE variable%%%" # Global variables. # $mode is unset nonopt= execute_dlfiles= preserve_args= lo2o="s/\\.lo\$/.${objext}/" o2lo="s/\\.${objext}\$/.lo/" extracted_archives= extracted_serial=0 opt_dry_run=false opt_duplicate_deps=false opt_silent=false opt_debug=: # If this variable is set in any of the actions, the command in it # will be execed at the end. This prevents here-documents from being # left over by shells. exec_cmd= # func_fatal_configuration arg... # Echo program name prefixed message to standard error, followed by # a configuration failure hint, and exit. func_fatal_configuration () { func_error ${1+"$@"} func_error "See the $PACKAGE documentation for more information." func_fatal_error "Fatal configuration error." } # func_config # Display the configuration for all the tags in this script. func_config () { re_begincf='^# ### BEGIN LIBTOOL' re_endcf='^# ### END LIBTOOL' # Default configuration. $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath" # Now print the configurations for the tags. for tagname in $taglist; do $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath" done exit $? } # func_features # Display the features supported by this script. func_features () { $ECHO "host: $host" if test "$build_libtool_libs" = yes; then $ECHO "enable shared libraries" else $ECHO "disable shared libraries" fi if test "$build_old_libs" = yes; then $ECHO "enable static libraries" else $ECHO "disable static libraries" fi exit $? } # func_enable_tag tagname # Verify that TAGNAME is valid, and either flag an error and exit, or # enable the TAGNAME tag. We also add TAGNAME to the global $taglist # variable here. func_enable_tag () { # Global variable: tagname="$1" re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$" re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$" sed_extractcf="/$re_begincf/,/$re_endcf/p" # Validate tagname. case $tagname in *[!-_A-Za-z0-9,/]*) func_fatal_error "invalid tag name: $tagname" ;; esac # Don't test for the "default" C tag, as we know it's # there but not specially marked. case $tagname in CC) ;; *) if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then taglist="$taglist $tagname" # Evaluate the configuration. Be careful to quote the path # and the sed script, to avoid splitting on whitespace, but # also don't use non-portable quotes within backquotes within # quotes we have to do it in 2 steps: extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` eval "$extractedcf" else func_error "ignoring unknown tag $tagname" fi ;; esac } # Parse options once, thoroughly. This comes as soon as possible in # the script to make things like `libtool --version' happen quickly. { # Shorthand for --mode=foo, only valid as the first argument case $1 in clean|clea|cle|cl) shift; set dummy --mode clean ${1+"$@"}; shift ;; compile|compil|compi|comp|com|co|c) shift; set dummy --mode compile ${1+"$@"}; shift ;; execute|execut|execu|exec|exe|ex|e) shift; set dummy --mode execute ${1+"$@"}; shift ;; finish|finis|fini|fin|fi|f) shift; set dummy --mode finish ${1+"$@"}; shift ;; install|instal|insta|inst|ins|in|i) shift; set dummy --mode install ${1+"$@"}; shift ;; link|lin|li|l) shift; set dummy --mode link ${1+"$@"}; shift ;; uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) shift; set dummy --mode uninstall ${1+"$@"}; shift ;; esac # Parse non-mode specific arguments: while test "$#" -gt 0; do opt="$1" shift case $opt in --config) func_config ;; --debug) preserve_args="$preserve_args $opt" func_echo "enabling shell trace mode" opt_debug='set -x' $opt_debug ;; -dlopen) test "$#" -eq 0 && func_missing_arg "$opt" && break execute_dlfiles="$execute_dlfiles $1" shift ;; --dry-run | -n) opt_dry_run=: ;; --features) func_features ;; --finish) mode="finish" ;; --mode) test "$#" -eq 0 && func_missing_arg "$opt" && break case $1 in # Valid mode arguments: clean) ;; compile) ;; execute) ;; finish) ;; install) ;; link) ;; relink) ;; uninstall) ;; # Catch anything else as an error *) func_error "invalid argument for $opt" exit_cmd=exit break ;; esac mode="$1" shift ;; --preserve-dup-deps) opt_duplicate_deps=: ;; --quiet|--silent) preserve_args="$preserve_args $opt" opt_silent=: ;; --verbose| -v) preserve_args="$preserve_args $opt" opt_silent=false ;; --tag) test "$#" -eq 0 && func_missing_arg "$opt" && break preserve_args="$preserve_args $opt $1" func_enable_tag "$1" # tagname is set here shift ;; # Separate optargs to long options: -dlopen=*|--mode=*|--tag=*) func_opt_split "$opt" set dummy "$func_opt_split_opt" "$func_opt_split_arg" ${1+"$@"} shift ;; -\?|-h) func_usage ;; --help) opt_help=: ;; --version) func_version ;; -*) func_fatal_help "unrecognized option \`$opt'" ;; *) nonopt="$opt" break ;; esac done case $host in *cygwin* | *mingw* | *pw32* | *cegcc*) # don't eliminate duplications in $postdeps and $predeps opt_duplicate_compiler_generated_deps=: ;; *) opt_duplicate_compiler_generated_deps=$opt_duplicate_deps ;; esac # Having warned about all mis-specified options, bail out if # anything was wrong. $exit_cmd $EXIT_FAILURE } # func_check_version_match # Ensure that we are using m4 macros, and libtool script from the same # release of libtool. func_check_version_match () { if test "$package_revision" != "$macro_revision"; then if test "$VERSION" != "$macro_version"; then if test -z "$macro_version"; then cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from an older release. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from $PACKAGE $macro_version. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF fi else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, $progname: but the definition of this LT_INIT comes from revision $macro_revision. $progname: You should recreate aclocal.m4 with macros from revision $package_revision $progname: of $PACKAGE $VERSION and run autoconf again. _LT_EOF fi exit $EXIT_MISMATCH fi } ## ----------- ## ## Main. ## ## ----------- ## $opt_help || { # Sanity checks first: func_check_version_match if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then func_fatal_configuration "not configured to build any kind of library" fi test -z "$mode" && func_fatal_error "error: you must specify a MODE." # Darwin sucks eval std_shrext=\"$shrext_cmds\" # Only execute mode is allowed to have -dlopen flags. if test -n "$execute_dlfiles" && test "$mode" != execute; then func_error "unrecognized option \`-dlopen'" $ECHO "$help" 1>&2 exit $EXIT_FAILURE fi # Change the help message to a mode-specific one. generic_help="$help" help="Try \`$progname --help --mode=$mode' for more information." } # func_lalib_p file # True iff FILE is a libtool `.la' library or `.lo' object file. # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_lalib_p () { test -f "$1" && $SED -e 4q "$1" 2>/dev/null \ | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 } # func_lalib_unsafe_p file # True iff FILE is a libtool `.la' library or `.lo' object file. # This function implements the same check as func_lalib_p without # resorting to external programs. To this end, it redirects stdin and # closes it afterwards, without saving the original file descriptor. # As a safety measure, use it only where a negative result would be # fatal anyway. Works if `file' does not exist. func_lalib_unsafe_p () { lalib_p=no if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then for lalib_p_l in 1 2 3 4 do read lalib_p_line case "$lalib_p_line" in \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; esac done exec 0<&5 5<&- fi test "$lalib_p" = yes } # func_ltwrapper_script_p file # True iff FILE is a libtool wrapper script # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_script_p () { func_lalib_p "$1" } # func_ltwrapper_executable_p file # True iff FILE is a libtool wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_executable_p () { func_ltwrapper_exec_suffix= case $1 in *.exe) ;; *) func_ltwrapper_exec_suffix=.exe ;; esac $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 } # func_ltwrapper_scriptname file # Assumes file is an ltwrapper_executable # uses $file to determine the appropriate filename for a # temporary ltwrapper_script. func_ltwrapper_scriptname () { func_ltwrapper_scriptname_result="" if func_ltwrapper_executable_p "$1"; then func_dirname_and_basename "$1" "" "." func_stripname '' '.exe' "$func_basename_result" func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper" fi } # func_ltwrapper_p file # True iff FILE is a libtool wrapper script or wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_p () { func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" } # func_execute_cmds commands fail_cmd # Execute tilde-delimited COMMANDS. # If FAIL_CMD is given, eval that upon failure. # FAIL_CMD may read-access the current command in variable CMD! func_execute_cmds () { $opt_debug save_ifs=$IFS; IFS='~' for cmd in $1; do IFS=$save_ifs eval cmd=\"$cmd\" func_show_eval "$cmd" "${2-:}" done IFS=$save_ifs } # func_source file # Source FILE, adding directory component if necessary. # Note that it is not necessary on cygwin/mingw to append a dot to # FILE even if both FILE and FILE.exe exist: automatic-append-.exe # behavior happens only for exec(3), not for open(2)! Also, sourcing # `FILE.' does not work on cygwin managed mounts. func_source () { $opt_debug case $1 in */* | *\\*) . "$1" ;; *) . "./$1" ;; esac } # func_infer_tag arg # Infer tagged configuration to use if any are available and # if one wasn't chosen via the "--tag" command line option. # Only attempt this if the compiler in the base compile # command doesn't match the default compiler. # arg is usually of the form 'gcc ...' func_infer_tag () { $opt_debug if test -n "$available_tags" && test -z "$tagname"; then CC_quoted= for arg in $CC; do func_quote_for_eval "$arg" CC_quoted="$CC_quoted $func_quote_for_eval_result" done case $@ in # Blanks in the command may have been stripped by the calling shell, # but not from the CC environment variable when configure was run. " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*) ;; # Blanks at the start of $base_compile will cause this to fail # if we don't check for them as well. *) for z in $available_tags; do if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then # Evaluate the configuration. eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" CC_quoted= for arg in $CC; do # Double-quote args containing other shell metacharacters. func_quote_for_eval "$arg" CC_quoted="$CC_quoted $func_quote_for_eval_result" done case "$@ " in " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*) # The compiler in the base compile command matches # the one in the tagged configuration. # Assume this is the tagged configuration we want. tagname=$z break ;; esac fi done # If $tagname still isn't set, then no tagged configuration # was found and let the user know that the "--tag" command # line option must be used. if test -z "$tagname"; then func_echo "unable to infer tagged configuration" func_fatal_error "specify a tag with \`--tag'" # else # func_verbose "using $tagname tagged configuration" fi ;; esac fi } # func_write_libtool_object output_name pic_name nonpic_name # Create a libtool object file (analogous to a ".la" file), # but don't create it if we're doing a dry run. func_write_libtool_object () { write_libobj=${1} if test "$build_libtool_libs" = yes; then write_lobj=\'${2}\' else write_lobj=none fi if test "$build_old_libs" = yes; then write_oldobj=\'${3}\' else write_oldobj=none fi $opt_dry_run || { cat >${write_libobj}T <<EOF # $write_libobj - a libtool object file # Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION # # Please DO NOT delete this file! # It is necessary for linking the library. # Name of the PIC object. pic_object=$write_lobj # Name of the non-PIC object non_pic_object=$write_oldobj EOF $MV "${write_libobj}T" "${write_libobj}" } } # func_mode_compile arg... func_mode_compile () { $opt_debug # Get the compilation command and the source file. base_compile= srcfile="$nonopt" # always keep a non-empty value in "srcfile" suppress_opt=yes suppress_output= arg_mode=normal libobj= later= pie_flag= for arg do case $arg_mode in arg ) # do not "continue". Instead, add this to base_compile lastarg="$arg" arg_mode=normal ;; target ) libobj="$arg" arg_mode=normal continue ;; normal ) # Accept any command-line options. case $arg in -o) test -n "$libobj" && \ func_fatal_error "you cannot specify \`-o' more than once" arg_mode=target continue ;; -pie | -fpie | -fPIE) pie_flag="$pie_flag $arg" continue ;; -shared | -static | -prefer-pic | -prefer-non-pic) later="$later $arg" continue ;; -no-suppress) suppress_opt=no continue ;; -Xcompiler) arg_mode=arg # the next one goes into the "base_compile" arg list continue # The current "srcfile" will either be retained or ;; # replaced later. I would guess that would be a bug. -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result lastarg= save_ifs="$IFS"; IFS=',' for arg in $args; do IFS="$save_ifs" func_quote_for_eval "$arg" lastarg="$lastarg $func_quote_for_eval_result" done IFS="$save_ifs" func_stripname ' ' '' "$lastarg" lastarg=$func_stripname_result # Add the arguments to base_compile. base_compile="$base_compile $lastarg" continue ;; *) # Accept the current argument as the source file. # The previous "srcfile" becomes the current argument. # lastarg="$srcfile" srcfile="$arg" ;; esac # case $arg ;; esac # case $arg_mode # Aesthetically quote the previous argument. func_quote_for_eval "$lastarg" base_compile="$base_compile $func_quote_for_eval_result" done # for arg case $arg_mode in arg) func_fatal_error "you must specify an argument for -Xcompile" ;; target) func_fatal_error "you must specify a target with \`-o'" ;; *) # Get the name of the library object. test -z "$libobj" && { func_basename "$srcfile" libobj="$func_basename_result" } ;; esac # Recognize several different file suffixes. # If the user specifies -o file.o, it is replaced with file.lo case $libobj in *.[cCFSifmso] | \ *.ada | *.adb | *.ads | *.asm | \ *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \ *.[fF][09]? | *.for | *.java | *.obj | *.sx) func_xform "$libobj" libobj=$func_xform_result ;; esac case $libobj in *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;; *) func_fatal_error "cannot determine name of library object from \`$libobj'" ;; esac func_infer_tag $base_compile for arg in $later; do case $arg in -shared) test "$build_libtool_libs" != yes && \ func_fatal_configuration "can not build a shared library" build_old_libs=no continue ;; -static) build_libtool_libs=no build_old_libs=yes continue ;; -prefer-pic) pic_mode=yes continue ;; -prefer-non-pic) pic_mode=no continue ;; esac done func_quote_for_eval "$libobj" test "X$libobj" != "X$func_quote_for_eval_result" \ && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"' &()|`$[]' \ && func_warning "libobj name \`$libobj' may not contain shell special characters." func_dirname_and_basename "$obj" "/" "" objname="$func_basename_result" xdir="$func_dirname_result" lobj=${xdir}$objdir/$objname test -z "$base_compile" && \ func_fatal_help "you must specify a compilation command" # Delete any leftover library objects. if test "$build_old_libs" = yes; then removelist="$obj $lobj $libobj ${libobj}T" else removelist="$lobj $libobj ${libobj}T" fi # On Cygwin there's no "real" PIC flag so we must build both object types case $host_os in cygwin* | mingw* | pw32* | os2* | cegcc*) pic_mode=default ;; esac if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then # non-PIC code in shared libraries is not supported pic_mode=default fi # Calculate the filename of the output object if compiler does # not support -o with -c if test "$compiler_c_o" = no; then output_obj=`$ECHO "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$%%'`.${objext} lockfile="$output_obj.lock" else output_obj= need_locks=no lockfile= fi # Lock this critical section if it is needed # We use this script file to make the link, it avoids creating a new file if test "$need_locks" = yes; then until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done elif test "$need_locks" = warn; then if test -f "$lockfile"; then $ECHO "\ *** ERROR, $lockfile exists and contains: `cat $lockfile 2>/dev/null` This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi removelist="$removelist $output_obj" $ECHO "$srcfile" > "$lockfile" fi $opt_dry_run || $RM $removelist removelist="$removelist $lockfile" trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 if test -n "$fix_srcfile_path"; then eval srcfile=\"$fix_srcfile_path\" fi func_quote_for_eval "$srcfile" qsrcfile=$func_quote_for_eval_result # Only build a PIC object if we are building libtool libraries. if test "$build_libtool_libs" = yes; then # Without this assignment, base_compile gets emptied. fbsd_hideous_sh_bug=$base_compile if test "$pic_mode" != no; then command="$base_compile $qsrcfile $pic_flag" else # Don't build PIC code command="$base_compile $qsrcfile" fi func_mkdir_p "$xdir$objdir" if test -z "$output_obj"; then # Place PIC objects in $objdir command="$command -o $lobj" fi func_show_eval_locale "$command" \ 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' if test "$need_locks" = warn && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed, then go on to compile the next one if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then func_show_eval '$MV "$output_obj" "$lobj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi # Allow error messages only from the first compilation. if test "$suppress_opt" = yes; then suppress_output=' >/dev/null 2>&1' fi fi # Only build a position-dependent object if we build old libraries. if test "$build_old_libs" = yes; then if test "$pic_mode" != yes; then # Don't build PIC code command="$base_compile $qsrcfile$pie_flag" else command="$base_compile $qsrcfile $pic_flag" fi if test "$compiler_c_o" = yes; then command="$command -o $obj" fi # Suppress compiler output if we already did a PIC compilation. command="$command$suppress_output" func_show_eval_locale "$command" \ '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' if test "$need_locks" = warn && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then func_show_eval '$MV "$output_obj" "$obj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi fi $opt_dry_run || { func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" # Unlock the critical section if it was locked if test "$need_locks" != no; then removelist=$lockfile $RM "$lockfile" fi } exit $EXIT_SUCCESS } $opt_help || { test "$mode" = compile && func_mode_compile ${1+"$@"} } func_mode_help () { # We need to display help for each of the modes. case $mode in "") # Generic help is extracted from the usage comments # at the start of this file. func_help ;; clean) $ECHO \ "Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... Remove files from the build directory. RM is the name of the program to use to delete files associated with each FILE (typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed to RM. If FILE is a libtool library, object or program, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; compile) $ECHO \ "Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE Compile a source file into a libtool library object. This mode accepts the following additional options: -o OUTPUT-FILE set the output file name to OUTPUT-FILE -no-suppress do not suppress compiler output for multiple passes -prefer-pic try to building PIC objects only -prefer-non-pic try to building non-PIC objects only -shared do not build a \`.o' file suitable for static linking -static only build a \`.o' file suitable for static linking COMPILE-COMMAND is a command to be used in creating a \`standard' object file from the given SOURCEFILE. The output file name is determined by removing the directory component from SOURCEFILE, then substituting the C source code suffix \`.c' with the library object suffix, \`.lo'." ;; execute) $ECHO \ "Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... Automatically set library path, then run a program. This mode accepts the following additional options: -dlopen FILE add the directory containing FILE to the library path This mode sets the library path environment variable according to \`-dlopen' flags. If any of the ARGS are libtool executable wrappers, then they are translated into their corresponding uninstalled binary, and any of their required library directories are added to the library path. Then, COMMAND is executed, with ARGS as arguments." ;; finish) $ECHO \ "Usage: $progname [OPTION]... --mode=finish [LIBDIR]... Complete the installation of libtool libraries. Each LIBDIR is a directory that contains libtool libraries. The commands that this mode executes may require superuser privileges. Use the \`--dry-run' option if you just want to see what would be executed." ;; install) $ECHO \ "Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... Install executables or libraries. INSTALL-COMMAND is the installation command. The first component should be either the \`install' or \`cp' program. The following components of INSTALL-COMMAND are treated specially: -inst-prefix PREFIX-DIR Use PREFIX-DIR as a staging area for installation The rest of the components are interpreted as arguments to that command (only BSD-compatible install options are recognized)." ;; link) $ECHO \ "Usage: $progname [OPTION]... --mode=link LINK-COMMAND... Link object files or libraries together to form another library, or to create an executable program. LINK-COMMAND is a command using the C compiler that you would use to create a program from several object files. The following components of LINK-COMMAND are treated specially: -all-static do not do any dynamic linking at all -avoid-version do not add a version suffix if possible -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) -export-symbols SYMFILE try to export only the symbols listed in SYMFILE -export-symbols-regex REGEX try to export only the symbols matching REGEX -LLIBDIR search LIBDIR for required installed libraries -lNAME OUTPUT-FILE requires the installed library libNAME -module build a library that can dlopened -no-fast-install disable the fast-install mode -no-install link a not-installable executable -no-undefined declare that a library does not refer to external symbols -o OUTPUT-FILE create OUTPUT-FILE from the specified objects -objectlist FILE Use a list of object files found in FILE to specify objects -precious-files-regex REGEX don't remove output files matching REGEX -release RELEASE specify package release information -rpath LIBDIR the created library will eventually be installed in LIBDIR -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries -shared only do dynamic linking of libtool libraries -shrext SUFFIX override the standard shared library file extension -static do not do any dynamic linking of uninstalled libtool libraries -static-libtool-libs do not do any dynamic linking of libtool libraries -version-info CURRENT[:REVISION[:AGE]] specify library version info [each variable defaults to 0] -weak LIBNAME declare that the target provides the LIBNAME interface All other options (arguments beginning with \`-') are ignored. Every other argument is treated as a filename. Files ending in \`.la' are treated as uninstalled libtool libraries, other files are standard or library object files. If the OUTPUT-FILE ends in \`.la', then a libtool library is created, only library objects (\`.lo' files) may be specified, and \`-rpath' is required, except when creating a convenience library. If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created using \`ar' and \`ranlib', or on Windows using \`lib'. If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file is created, otherwise an executable program is created." ;; uninstall) $ECHO \ "Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... Remove libraries from an installation directory. RM is the name of the program to use to delete files associated with each FILE (typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed to RM. If FILE is a libtool library, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; *) func_fatal_help "invalid operation mode \`$mode'" ;; esac $ECHO $ECHO "Try \`$progname --help' for more information about other modes." exit $? } # Now that we've collected a possible --mode arg, show help if necessary $opt_help && func_mode_help # func_mode_execute arg... func_mode_execute () { $opt_debug # The first argument is the command name. cmd="$nonopt" test -z "$cmd" && \ func_fatal_help "you must specify a COMMAND" # Handle -dlopen flags immediately. for file in $execute_dlfiles; do test -f "$file" \ || func_fatal_help "\`$file' is not a file" dir= case $file in *.la) # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "\`$lib' is not a valid libtool archive" # Read the libtool library. dlname= library_names= func_source "$file" # Skip this library if it cannot be dlopened. if test -z "$dlname"; then # Warn if it was a shared library. test -n "$library_names" && \ func_warning "\`$file' was not linked with \`-export-dynamic'" continue fi func_dirname "$file" "" "." dir="$func_dirname_result" if test -f "$dir/$objdir/$dlname"; then dir="$dir/$objdir" else if test ! -f "$dir/$dlname"; then func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" fi fi ;; *.lo) # Just add the directory containing the .lo file. func_dirname "$file" "" "." dir="$func_dirname_result" ;; *) func_warning "\`-dlopen' is ignored for non-libtool libraries and objects" continue ;; esac # Get the absolute pathname. absdir=`cd "$dir" && pwd` test -n "$absdir" && dir="$absdir" # Now add the directory to shlibpath_var. if eval "test -z \"\$$shlibpath_var\""; then eval "$shlibpath_var=\"\$dir\"" else eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" fi done # This variable tells wrapper scripts just to set shlibpath_var # rather than running their programs. libtool_execute_magic="$magic" # Check if any of the arguments is a wrapper script. args= for file do case $file in -*) ;; *) # Do a test to see if this is really a libtool program. if func_ltwrapper_script_p "$file"; then func_source "$file" # Transform arg to wrapped name. file="$progdir/$program" elif func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" func_source "$func_ltwrapper_scriptname_result" # Transform arg to wrapped name. file="$progdir/$program" fi ;; esac # Quote arguments (to preserve shell metacharacters). func_quote_for_eval "$file" args="$args $func_quote_for_eval_result" done if test "X$opt_dry_run" = Xfalse; then if test -n "$shlibpath_var"; then # Export the shlibpath_var. eval "export $shlibpath_var" fi # Restore saved environment variables for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${save_$lt_var+set}\" = set; then $lt_var=\$save_$lt_var; export $lt_var else $lt_unset $lt_var fi" done # Now prepare to actually exec the command. exec_cmd="\$cmd$args" else # Display what would be done. if test -n "$shlibpath_var"; then eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" $ECHO "export $shlibpath_var" fi $ECHO "$cmd$args" exit $EXIT_SUCCESS fi } test "$mode" = execute && func_mode_execute ${1+"$@"} # func_mode_finish arg... func_mode_finish () { $opt_debug libdirs="$nonopt" admincmds= if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then for dir do libdirs="$libdirs $dir" done for libdir in $libdirs; do if test -n "$finish_cmds"; then # Do each command in the finish commands. func_execute_cmds "$finish_cmds" 'admincmds="$admincmds '"$cmd"'"' fi if test -n "$finish_eval"; then # Do the single finish_eval. eval cmds=\"$finish_eval\" $opt_dry_run || eval "$cmds" || admincmds="$admincmds $cmds" fi done fi # Exit here if they wanted silent mode. $opt_silent && exit $EXIT_SUCCESS $ECHO "X----------------------------------------------------------------------" | $Xsed $ECHO "Libraries have been installed in:" for libdir in $libdirs; do $ECHO " $libdir" done $ECHO $ECHO "If you ever happen to want to link against installed libraries" $ECHO "in a given directory, LIBDIR, you must either use libtool, and" $ECHO "specify the full pathname of the library, or use the \`-LLIBDIR'" $ECHO "flag during linking and do at least one of the following:" if test -n "$shlibpath_var"; then $ECHO " - add LIBDIR to the \`$shlibpath_var' environment variable" $ECHO " during execution" fi if test -n "$runpath_var"; then $ECHO " - add LIBDIR to the \`$runpath_var' environment variable" $ECHO " during linking" fi if test -n "$hardcode_libdir_flag_spec"; then libdir=LIBDIR eval flag=\"$hardcode_libdir_flag_spec\" $ECHO " - use the \`$flag' linker flag" fi if test -n "$admincmds"; then $ECHO " - have your system administrator run these commands:$admincmds" fi if test -f /etc/ld.so.conf; then $ECHO " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'" fi $ECHO $ECHO "See any operating system documentation about shared libraries for" case $host in solaris2.[6789]|solaris2.1[0-9]) $ECHO "more information, such as the ld(1), crle(1) and ld.so(8) manual" $ECHO "pages." ;; *) $ECHO "more information, such as the ld(1) and ld.so(8) manual pages." ;; esac $ECHO "X----------------------------------------------------------------------" | $Xsed exit $EXIT_SUCCESS } test "$mode" = finish && func_mode_finish ${1+"$@"} # func_mode_install arg... func_mode_install () { $opt_debug # There may be an optional sh(1) argument at the beginning of # install_prog (especially on Windows NT). if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh || # Allow the use of GNU shtool's install command. $ECHO "X$nonopt" | $GREP shtool >/dev/null; then # Aesthetically quote it. func_quote_for_eval "$nonopt" install_prog="$func_quote_for_eval_result " arg=$1 shift else install_prog= arg=$nonopt fi # The real first argument should be the name of the installation program. # Aesthetically quote it. func_quote_for_eval "$arg" install_prog="$install_prog$func_quote_for_eval_result" # We need to accept at least all the BSD install flags. dest= files= opts= prev= install_type= isdir=no stripme= for arg do if test -n "$dest"; then files="$files $dest" dest=$arg continue fi case $arg in -d) isdir=yes ;; -f) case " $install_prog " in *[\\\ /]cp\ *) ;; *) prev=$arg ;; esac ;; -g | -m | -o) prev=$arg ;; -s) stripme=" -s" continue ;; -*) ;; *) # If the previous option needed an argument, then skip it. if test -n "$prev"; then prev= else dest=$arg continue fi ;; esac # Aesthetically quote the argument. func_quote_for_eval "$arg" install_prog="$install_prog $func_quote_for_eval_result" done test -z "$install_prog" && \ func_fatal_help "you must specify an install program" test -n "$prev" && \ func_fatal_help "the \`$prev' option requires an argument" if test -z "$files"; then if test -z "$dest"; then func_fatal_help "no file or destination specified" else func_fatal_help "you must specify a destination" fi fi # Strip any trailing slash from the destination. func_stripname '' '/' "$dest" dest=$func_stripname_result # Check to see that the destination is a directory. test -d "$dest" && isdir=yes if test "$isdir" = yes; then destdir="$dest" destname= else func_dirname_and_basename "$dest" "" "." destdir="$func_dirname_result" destname="$func_basename_result" # Not a directory, so check to see that there is only one file specified. set dummy $files; shift test "$#" -gt 1 && \ func_fatal_help "\`$dest' is not a directory" fi case $destdir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) for file in $files; do case $file in *.lo) ;; *) func_fatal_help "\`$destdir' must be an absolute directory name" ;; esac done ;; esac # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic="$magic" staticlibs= future_libdirs= current_libdirs= for file in $files; do # Do each installation. case $file in *.$libext) # Do the static libraries later. staticlibs="$staticlibs $file" ;; *.la) # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "\`$file' is not a valid libtool archive" library_names= old_library= relink_command= func_source "$file" # Add the libdir to current_libdirs if it is the destination. if test "X$destdir" = "X$libdir"; then case "$current_libdirs " in *" $libdir "*) ;; *) current_libdirs="$current_libdirs $libdir" ;; esac else # Note the libdir as a future libdir. case "$future_libdirs " in *" $libdir "*) ;; *) future_libdirs="$future_libdirs $libdir" ;; esac fi func_dirname "$file" "/" "" dir="$func_dirname_result" dir="$dir$objdir" if test -n "$relink_command"; then # Determine the prefix the user has applied to our future dir. inst_prefix_dir=`$ECHO "X$destdir" | $Xsed -e "s%$libdir\$%%"` # Don't allow the user to place us outside of our expected # location b/c this prevents finding dependent libraries that # are installed to the same prefix. # At present, this check doesn't affect windows .dll's that # are installed into $libdir/../bin (currently, that works fine) # but it's something to keep an eye on. test "$inst_prefix_dir" = "$destdir" && \ func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir" if test -n "$inst_prefix_dir"; then # Stick the inst_prefix_dir data into the link command. relink_command=`$ECHO "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` else relink_command=`$ECHO "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%%"` fi func_warning "relinking \`$file'" func_show_eval "$relink_command" \ 'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"' fi # See the names of the shared library. set dummy $library_names; shift if test -n "$1"; then realname="$1" shift srcname="$realname" test -n "$relink_command" && srcname="$realname"T # Install the shared library and build the symlinks. func_show_eval "$install_prog $dir/$srcname $destdir/$realname" \ 'exit $?' tstripme="$stripme" case $host_os in cygwin* | mingw* | pw32* | cegcc*) case $realname in *.dll.a) tstripme="" ;; esac ;; esac if test -n "$tstripme" && test -n "$striplib"; then func_show_eval "$striplib $destdir/$realname" 'exit $?' fi if test "$#" -gt 0; then # Delete the old symlinks, and create new ones. # Try `ln -sf' first, because the `ln' binary might depend on # the symlink we replace! Solaris /bin/ln does not understand -f, # so we also need to try rm && ln -s. for linkname do test "$linkname" != "$realname" \ && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" done fi # Do each command in the postinstall commands. lib="$destdir/$realname" func_execute_cmds "$postinstall_cmds" 'exit $?' fi # Install the pseudo-library for information purposes. func_basename "$file" name="$func_basename_result" instname="$dir/$name"i func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' # Maybe install the static library, too. test -n "$old_library" && staticlibs="$staticlibs $dir/$old_library" ;; *.lo) # Install (i.e. copy) a libtool object. # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile="$destdir/$destname" else func_basename "$file" destfile="$func_basename_result" destfile="$destdir/$destfile" fi # Deduce the name of the destination old-style object file. case $destfile in *.lo) func_lo2o "$destfile" staticdest=$func_lo2o_result ;; *.$objext) staticdest="$destfile" destfile= ;; *) func_fatal_help "cannot copy a libtool object to \`$destfile'" ;; esac # Install the libtool object if requested. test -n "$destfile" && \ func_show_eval "$install_prog $file $destfile" 'exit $?' # Install the old object if enabled. if test "$build_old_libs" = yes; then # Deduce the name of the old-style object file. func_lo2o "$file" staticobj=$func_lo2o_result func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' fi exit $EXIT_SUCCESS ;; *) # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile="$destdir/$destname" else func_basename "$file" destfile="$func_basename_result" destfile="$destdir/$destfile" fi # If the file is missing, and there is a .exe on the end, strip it # because it is most likely a libtool script we actually want to # install stripped_ext="" case $file in *.exe) if test ! -f "$file"; then func_stripname '' '.exe' "$file" file=$func_stripname_result stripped_ext=".exe" fi ;; esac # Do a test to see if this is really a libtool program. case $host in *cygwin* | *mingw*) if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" wrapper=$func_ltwrapper_scriptname_result else func_stripname '' '.exe' "$file" wrapper=$func_stripname_result fi ;; *) wrapper=$file ;; esac if func_ltwrapper_script_p "$wrapper"; then notinst_deplibs= relink_command= func_source "$wrapper" # Check the variables that should have been set. test -z "$generated_by_libtool_version" && \ func_fatal_error "invalid libtool wrapper script \`$wrapper'" finalize=yes for lib in $notinst_deplibs; do # Check to see that each library is installed. libdir= if test -f "$lib"; then func_source "$lib" fi libfile="$libdir/"`$ECHO "X$lib" | $Xsed -e 's%^.*/%%g'` ### testsuite: skip nested quoting test if test -n "$libdir" && test ! -f "$libfile"; then func_warning "\`$lib' has not been installed in \`$libdir'" finalize=no fi done relink_command= func_source "$wrapper" outputname= if test "$fast_install" = no && test -n "$relink_command"; then $opt_dry_run || { if test "$finalize" = yes; then tmpdir=`func_mktempdir` func_basename "$file$stripped_ext" file="$func_basename_result" outputname="$tmpdir/$file" # Replace the output file specification. relink_command=`$ECHO "X$relink_command" | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g'` $opt_silent || { func_quote_for_expand "$relink_command" eval "func_echo $func_quote_for_expand_result" } if eval "$relink_command"; then : else func_error "error: relink \`$file' with the above command before installing it" $opt_dry_run || ${RM}r "$tmpdir" continue fi file="$outputname" else func_warning "cannot relink \`$file'" fi } else # Install the binary that we compiled earlier. file=`$ECHO "X$file$stripped_ext" | $Xsed -e "s%\([^/]*\)$%$objdir/\1%"` fi fi # remove .exe since cygwin /usr/bin/install will append another # one anyway case $install_prog,$host in */usr/bin/install*,*cygwin*) case $file:$destfile in *.exe:*.exe) # this is ok ;; *.exe:*) destfile=$destfile.exe ;; *:*.exe) func_stripname '' '.exe' "$destfile" destfile=$func_stripname_result ;; esac ;; esac func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' $opt_dry_run || if test -n "$outputname"; then ${RM}r "$tmpdir" fi ;; esac done for file in $staticlibs; do func_basename "$file" name="$func_basename_result" # Set up the ranlib parameters. oldlib="$destdir/$name" func_show_eval "$install_prog \$file \$oldlib" 'exit $?' if test -n "$stripme" && test -n "$old_striplib"; then func_show_eval "$old_striplib $oldlib" 'exit $?' fi # Do each command in the postinstall commands. func_execute_cmds "$old_postinstall_cmds" 'exit $?' done test -n "$future_libdirs" && \ func_warning "remember to run \`$progname --finish$future_libdirs'" if test -n "$current_libdirs"; then # Maybe just do a dry run. $opt_dry_run && current_libdirs=" -n$current_libdirs" exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs' else exit $EXIT_SUCCESS fi } test "$mode" = install && func_mode_install ${1+"$@"} # func_generate_dlsyms outputname originator pic_p # Extract symbols from dlprefiles and create ${outputname}S.o with # a dlpreopen symbol table. func_generate_dlsyms () { $opt_debug my_outputname="$1" my_originator="$2" my_pic_p="${3-no}" my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'` my_dlsyms= if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then if test -n "$NM" && test -n "$global_symbol_pipe"; then my_dlsyms="${my_outputname}S.c" else func_error "not configured to extract global symbols from dlpreopened files" fi fi if test -n "$my_dlsyms"; then case $my_dlsyms in "") ;; *.c) # Discover the nlist of each of the dlfiles. nlist="$output_objdir/${my_outputname}.nm" func_show_eval "$RM $nlist ${nlist}S ${nlist}T" # Parse the name list into a source file. func_verbose "creating $output_objdir/$my_dlsyms" $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ /* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */ /* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */ #ifdef __cplusplus extern \"C\" { #endif /* External symbol declarations for the compiler. */\ " if test "$dlself" = yes; then func_verbose "generating symbol list for \`$output'" $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" # Add our own program objects to the symbol list. progfiles=`$ECHO "X$objs$old_deplibs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` for progfile in $progfiles; do func_verbose "extracting global C symbols from \`$progfile'" $opt_dry_run || eval "$NM $progfile | $global_symbol_pipe >> '$nlist'" done if test -n "$exclude_expsyms"; then $opt_dry_run || { eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi if test -n "$export_symbols_regex"; then $opt_dry_run || { eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi # Prepare the list of exported symbols if test -z "$export_symbols"; then export_symbols="$output_objdir/$outputname.exp" $opt_dry_run || { $RM $export_symbols eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' ;; esac } else $opt_dry_run || { eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' case $host in *cygwin | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' ;; esac } fi fi for dlprefile in $dlprefiles; do func_verbose "extracting global C symbols from \`$dlprefile'" func_basename "$dlprefile" name="$func_basename_result" $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' eval "$NM $dlprefile 2>/dev/null | $global_symbol_pipe >> '$nlist'" } done $opt_dry_run || { # Make sure we have at least an empty file. test -f "$nlist" || : > "$nlist" if test -n "$exclude_expsyms"; then $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T $MV "$nlist"T "$nlist" fi # Try sorting and uniquifying the output. if $GREP -v "^: " < "$nlist" | if sort -k 3 </dev/null >/dev/null 2>&1; then sort -k 3 else sort +2 fi | uniq > "$nlist"S; then : else $GREP -v "^: " < "$nlist" > "$nlist"S fi if test -f "$nlist"S; then eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' else $ECHO '/* NONE */' >> "$output_objdir/$my_dlsyms" fi $ECHO >> "$output_objdir/$my_dlsyms" "\ /* The mapping between symbol names and symbols. */ typedef struct { const char *name; void *address; } lt_dlsymlist; " case $host in *cygwin* | *mingw* | *cegcc* ) $ECHO >> "$output_objdir/$my_dlsyms" "\ /* DATA imports from DLLs on WIN32 con't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */" lt_dlsym_const= ;; *osf5*) echo >> "$output_objdir/$my_dlsyms" "\ /* This system does not cope well with relocations in const data */" lt_dlsym_const= ;; *) lt_dlsym_const=const ;; esac $ECHO >> "$output_objdir/$my_dlsyms" "\ extern $lt_dlsym_const lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[]; $lt_dlsym_const lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[] = {\ { \"$my_originator\", (void *) 0 }," case $need_lib_prefix in no) eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; *) eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; esac $ECHO >> "$output_objdir/$my_dlsyms" "\ {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt_${my_prefix}_LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif\ " } # !$opt_dry_run pic_flag_for_symtable= case "$compile_command " in *" -static "*) ;; *) case $host in # compiling the symbol table file with pic_flag works around # a FreeBSD bug that causes programs to crash when -lm is # linked before any other PIC object. But we must not use # pic_flag when linking with -static. The problem exists in # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. *-*-freebsd2*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; *-*-hpux*) pic_flag_for_symtable=" $pic_flag" ;; *) if test "X$my_pic_p" != Xno; then pic_flag_for_symtable=" $pic_flag" fi ;; esac ;; esac symtab_cflags= for arg in $LTCFLAGS; do case $arg in -pie | -fpie | -fPIE) ;; *) symtab_cflags="$symtab_cflags $arg" ;; esac done # Now compile the dynamic symbol file. func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' # Clean up the generated files. func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"' # Transform the symbol file into the correct name. symfileobj="$output_objdir/${my_outputname}S.$objext" case $host in *cygwin* | *mingw* | *cegcc* ) if test -f "$output_objdir/$my_outputname.def"; then compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` else compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` fi ;; *) compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` ;; esac ;; *) func_fatal_error "unknown suffix for \`$my_dlsyms'" ;; esac else # We keep going just in case the user didn't refer to # lt_preloaded_symbols. The linker will fail if global_symbol_pipe # really was required. # Nullify the symbol file. compile_command=`$ECHO "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"` finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%"` fi } # func_win32_libid arg # return the library type of file 'arg' # # Need a lot of goo to handle *both* DLLs and import libs # Has to be a shell function in order to 'eat' the argument # that is supplied when $file_magic_command is called. func_win32_libid () { $opt_debug win32_libid_type="unknown" win32_fileres=`file -L $1 2>/dev/null` case $win32_fileres in *ar\ archive\ import\ library*) # definitely import win32_libid_type="x86 archive import" ;; *ar\ archive*) # could be an import, or static if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null ; then win32_nmres=`eval $NM -f posix -A $1 | $SED -n -e ' 1,100{ / I /{ s,.*,import, p q } }'` case $win32_nmres in import*) win32_libid_type="x86 archive import";; *) win32_libid_type="x86 archive static";; esac fi ;; *DLL*) win32_libid_type="x86 DLL" ;; *executable*) # but shell scripts are "executable" too... case $win32_fileres in *MS\ Windows\ PE\ Intel*) win32_libid_type="x86 DLL" ;; esac ;; esac $ECHO "$win32_libid_type" } # func_extract_an_archive dir oldlib func_extract_an_archive () { $opt_debug f_ex_an_ar_dir="$1"; shift f_ex_an_ar_oldlib="$1" func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" 'exit $?' if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then : else func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" fi } # func_extract_archives gentop oldlib ... func_extract_archives () { $opt_debug my_gentop="$1"; shift my_oldlibs=${1+"$@"} my_oldobjs="" my_xlib="" my_xabs="" my_xdir="" for my_xlib in $my_oldlibs; do # Extract the objects. case $my_xlib in [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;; *) my_xabs=`pwd`"/$my_xlib" ;; esac func_basename "$my_xlib" my_xlib="$func_basename_result" my_xlib_u=$my_xlib while :; do case " $extracted_archives " in *" $my_xlib_u "*) func_arith $extracted_serial + 1 extracted_serial=$func_arith_result my_xlib_u=lt$extracted_serial-$my_xlib ;; *) break ;; esac done extracted_archives="$extracted_archives $my_xlib_u" my_xdir="$my_gentop/$my_xlib_u" func_mkdir_p "$my_xdir" case $host in *-darwin*) func_verbose "Extracting $my_xabs" # Do not bother doing anything if just a dry run $opt_dry_run || { darwin_orig_dir=`pwd` cd $my_xdir || exit $? darwin_archive=$my_xabs darwin_curdir=`pwd` darwin_base_archive=`basename "$darwin_archive"` darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` if test -n "$darwin_arches"; then darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` darwin_arch= func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" for darwin_arch in $darwin_arches ; do func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}" $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}" cd "unfat-$$/${darwin_base_archive}-${darwin_arch}" func_extract_an_archive "`pwd`" "${darwin_base_archive}" cd "$darwin_curdir" $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" done # $darwin_arches ## Okay now we've a bunch of thin objects, gotta fatten them up :) darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u` darwin_file= darwin_files= for darwin_file in $darwin_filelist; do darwin_files=`find unfat-$$ -name $darwin_file -print | $NL2SP` $LIPO -create -output "$darwin_file" $darwin_files done # $darwin_filelist $RM -rf unfat-$$ cd "$darwin_orig_dir" else cd $darwin_orig_dir func_extract_an_archive "$my_xdir" "$my_xabs" fi # $darwin_arches } # !$opt_dry_run ;; *) func_extract_an_archive "$my_xdir" "$my_xabs" ;; esac my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP` done func_extract_archives_result="$my_oldobjs" } # func_emit_wrapper_part1 [arg=no] # # Emit the first part of a libtool wrapper script on stdout. # For more information, see the description associated with # func_emit_wrapper(), below. func_emit_wrapper_part1 () { func_emit_wrapper_part1_arg1=no if test -n "$1" ; then func_emit_wrapper_part1_arg1=$1 fi $ECHO "\ #! $SHELL # $output - temporary wrapper script for $objdir/$outputname # Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION # # The $output program cannot be directly executed until all the libtool # libraries that it depends on are installed. # # This wrapper script should never be moved out of the build directory. # If it is, it will not operate correctly. # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. Xsed='${SED} -e 1s/^X//' sed_quote_subst='$sed_quote_subst' # Be Bourne compatible if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH relink_command=\"$relink_command\" # This environment variable determines our operation mode. if test \"\$libtool_install_magic\" = \"$magic\"; then # install mode needs the following variables: generated_by_libtool_version='$macro_version' notinst_deplibs='$notinst_deplibs' else # When we are sourced in execute mode, \$file and \$ECHO are already set. if test \"\$libtool_execute_magic\" != \"$magic\"; then ECHO=\"$qecho\" file=\"\$0\" # Make sure echo works. if test \"X\$1\" = X--no-reexec; then # Discard the --no-reexec flag, and continue. shift elif test \"X\`{ \$ECHO '\t'; } 2>/dev/null\`\" = 'X\t'; then # Yippee, \$ECHO works! : else # Restart under the correct shell, and then maybe \$ECHO will work. exec $SHELL \"\$0\" --no-reexec \${1+\"\$@\"} fi fi\ " $ECHO "\ # Find the directory that this script lives in. thisdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\` test \"x\$thisdir\" = \"x\$file\" && thisdir=. # Follow symbolic links until we get to the real thisdir. file=\`ls -ld \"\$file\" | ${SED} -n 's/.*-> //p'\` while test -n \"\$file\"; do destdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\` # If there was a directory component, then change thisdir. if test \"x\$destdir\" != \"x\$file\"; then case \"\$destdir\" in [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; *) thisdir=\"\$thisdir/\$destdir\" ;; esac fi file=\`\$ECHO \"X\$file\" | \$Xsed -e 's%^.*/%%'\` file=\`ls -ld \"\$thisdir/\$file\" | ${SED} -n 's/.*-> //p'\` done " } # end: func_emit_wrapper_part1 # func_emit_wrapper_part2 [arg=no] # # Emit the second part of a libtool wrapper script on stdout. # For more information, see the description associated with # func_emit_wrapper(), below. func_emit_wrapper_part2 () { func_emit_wrapper_part2_arg1=no if test -n "$1" ; then func_emit_wrapper_part2_arg1=$1 fi $ECHO "\ # Usually 'no', except on cygwin/mingw when embedded into # the cwrapper. WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_part2_arg1 if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then # special case for '.' if test \"\$thisdir\" = \".\"; then thisdir=\`pwd\` fi # remove .libs from thisdir case \"\$thisdir\" in *[\\\\/]$objdir ) thisdir=\`\$ECHO \"X\$thisdir\" | \$Xsed -e 's%[\\\\/][^\\\\/]*$%%'\` ;; $objdir ) thisdir=. ;; esac fi # Try to get the absolute directory name. absdir=\`cd \"\$thisdir\" && pwd\` test -n \"\$absdir\" && thisdir=\"\$absdir\" " if test "$fast_install" = yes; then $ECHO "\ program=lt-'$outputname'$exeext progdir=\"\$thisdir/$objdir\" if test ! -f \"\$progdir/\$program\" || { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\ test \"X\$file\" != \"X\$progdir/\$program\"; }; then file=\"\$\$-\$program\" if test ! -d \"\$progdir\"; then $MKDIR \"\$progdir\" else $RM \"\$progdir/\$file\" fi" $ECHO "\ # relink executable if necessary if test -n \"\$relink_command\"; then if relink_command_output=\`eval \$relink_command 2>&1\`; then : else $ECHO \"\$relink_command_output\" >&2 $RM \"\$progdir/\$file\" exit 1 fi fi $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || { $RM \"\$progdir/\$program\"; $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } $RM \"\$progdir/\$file\" fi" else $ECHO "\ program='$outputname' progdir=\"\$thisdir/$objdir\" " fi $ECHO "\ if test -f \"\$progdir/\$program\"; then" # Export our shlibpath_var if we have one. if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then $ECHO "\ # Add our own library path to $shlibpath_var $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" # Some systems cannot cope with colon-terminated $shlibpath_var # The second colon is a workaround for a bug in BeOS R4 sed $shlibpath_var=\`\$ECHO \"X\$$shlibpath_var\" | \$Xsed -e 's/::*\$//'\` export $shlibpath_var " fi # fixup the dll searchpath if we need to. if test -n "$dllsearchpath"; then $ECHO "\ # Add the dll search path components to the executable PATH PATH=$dllsearchpath:\$PATH " fi $ECHO "\ if test \"\$libtool_execute_magic\" != \"$magic\"; then # Run the actual program with our arguments. " case $host in # Backslashes separate directories on plain windows *-*-mingw | *-*-os2* | *-cegcc*) $ECHO "\ exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} " ;; *) $ECHO "\ exec \"\$progdir/\$program\" \${1+\"\$@\"} " ;; esac $ECHO "\ \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 exit 1 fi else # The program doesn't exist. \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2 \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 $ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 exit 1 fi fi\ " } # end: func_emit_wrapper_part2 # func_emit_wrapper [arg=no] # # Emit a libtool wrapper script on stdout. # Don't directly open a file because we may want to # incorporate the script contents within a cygwin/mingw # wrapper executable. Must ONLY be called from within # func_mode_link because it depends on a number of variables # set therein. # # ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR # variable will take. If 'yes', then the emitted script # will assume that the directory in which it is stored is # the $objdir directory. This is a cygwin/mingw-specific # behavior. func_emit_wrapper () { func_emit_wrapper_arg1=no if test -n "$1" ; then func_emit_wrapper_arg1=$1 fi # split this up so that func_emit_cwrapperexe_src # can call each part independently. func_emit_wrapper_part1 "${func_emit_wrapper_arg1}" func_emit_wrapper_part2 "${func_emit_wrapper_arg1}" } # func_to_host_path arg # # Convert paths to host format when used with build tools. # Intended for use with "native" mingw (where libtool itself # is running under the msys shell), or in the following cross- # build environments: # $build $host # mingw (msys) mingw [e.g. native] # cygwin mingw # *nix + wine mingw # where wine is equipped with the `winepath' executable. # In the native mingw case, the (msys) shell automatically # converts paths for any non-msys applications it launches, # but that facility isn't available from inside the cwrapper. # Similar accommodations are necessary for $host mingw and # $build cygwin. Calling this function does no harm for other # $host/$build combinations not listed above. # # ARG is the path (on $build) that should be converted to # the proper representation for $host. The result is stored # in $func_to_host_path_result. func_to_host_path () { func_to_host_path_result="$1" if test -n "$1" ; then case $host in *mingw* ) lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' case $build in *mingw* ) # actually, msys # awkward: cmd appends spaces to result lt_sed_strip_trailing_spaces="s/[ ]*\$//" func_to_host_path_tmp1=`( cmd //c echo "$1" |\ $SED -e "$lt_sed_strip_trailing_spaces" ) 2>/dev/null || echo ""` func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\ $SED -e "$lt_sed_naive_backslashify"` ;; *cygwin* ) func_to_host_path_tmp1=`cygpath -w "$1"` func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\ $SED -e "$lt_sed_naive_backslashify"` ;; * ) # Unfortunately, winepath does not exit with a non-zero # error code, so we are forced to check the contents of # stdout. On the other hand, if the command is not # found, the shell will set an exit code of 127 and print # *an error message* to stdout. So we must check for both # error code of zero AND non-empty stdout, which explains # the odd construction: func_to_host_path_tmp1=`winepath -w "$1" 2>/dev/null` if test "$?" -eq 0 && test -n "${func_to_host_path_tmp1}"; then func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\ $SED -e "$lt_sed_naive_backslashify"` else # Allow warning below. func_to_host_path_result="" fi ;; esac if test -z "$func_to_host_path_result" ; then #func_error "Could not determine host path corresponding to" #func_error " '$1'" #func_error "Continuing, but uninstalled executables may not work." # Fallback: func_to_host_path_result="$1" fi ;; esac fi } # end: func_to_host_path # func_to_host_pathlist arg # # Convert pathlists to host format when used with build tools. # See func_to_host_path(), above. This function supports the # following $build/$host combinations (but does no harm for # combinations not listed here): # $build $host # mingw (msys) mingw [e.g. native] # cygwin mingw # *nix + wine mingw # # Path separators are also converted from $build format to # $host format. If ARG begins or ends with a path separator # character, it is preserved (but converted to $host format) # on output. # # ARG is a pathlist (on $build) that should be converted to # the proper representation on $host. The result is stored # in $func_to_host_pathlist_result. func_to_host_pathlist () { func_to_host_pathlist_result="$1" if test -n "$1" ; then case $host in *mingw* ) lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' # Remove leading and trailing path separator characters from # ARG. msys behavior is inconsistent here, cygpath turns them # into '.;' and ';.', and winepath ignores them completely. func_to_host_pathlist_tmp2="$1" # Once set for this call, this variable should not be # reassigned. It is used in tha fallback case. func_to_host_pathlist_tmp1=`echo "$func_to_host_pathlist_tmp2" |\ $SED -e 's|^:*||' -e 's|:*$||'` case $build in *mingw* ) # Actually, msys. # Awkward: cmd appends spaces to result. lt_sed_strip_trailing_spaces="s/[ ]*\$//" func_to_host_pathlist_tmp2=`( cmd //c echo "$func_to_host_pathlist_tmp1" |\ $SED -e "$lt_sed_strip_trailing_spaces" ) 2>/dev/null || echo ""` func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp2" |\ $SED -e "$lt_sed_naive_backslashify"` ;; *cygwin* ) func_to_host_pathlist_tmp2=`cygpath -w -p "$func_to_host_pathlist_tmp1"` func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp2" |\ $SED -e "$lt_sed_naive_backslashify"` ;; * ) # unfortunately, winepath doesn't convert pathlists func_to_host_pathlist_result="" func_to_host_pathlist_oldIFS=$IFS IFS=: for func_to_host_pathlist_f in $func_to_host_pathlist_tmp1 ; do IFS=$func_to_host_pathlist_oldIFS if test -n "$func_to_host_pathlist_f" ; then func_to_host_path "$func_to_host_pathlist_f" if test -n "$func_to_host_path_result" ; then if test -z "$func_to_host_pathlist_result" ; then func_to_host_pathlist_result="$func_to_host_path_result" else func_to_host_pathlist_result="$func_to_host_pathlist_result;$func_to_host_path_result" fi fi fi IFS=: done IFS=$func_to_host_pathlist_oldIFS ;; esac if test -z "$func_to_host_pathlist_result" ; then func_error "Could not determine the host path(s) corresponding to" func_error " '$1'" func_error "Continuing, but uninstalled executables may not work." # Fallback. This may break if $1 contains DOS-style drive # specifications. The fix is not to complicate the expression # below, but for the user to provide a working wine installation # with winepath so that path translation in the cross-to-mingw # case works properly. lt_replace_pathsep_nix_to_dos="s|:|;|g" func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp1" |\ $SED -e "$lt_replace_pathsep_nix_to_dos"` fi # Now, add the leading and trailing path separators back case "$1" in :* ) func_to_host_pathlist_result=";$func_to_host_pathlist_result" ;; esac case "$1" in *: ) func_to_host_pathlist_result="$func_to_host_pathlist_result;" ;; esac ;; esac fi } # end: func_to_host_pathlist # func_emit_cwrapperexe_src # emit the source code for a wrapper executable on stdout # Must ONLY be called from within func_mode_link because # it depends on a number of variable set therein. func_emit_cwrapperexe_src () { cat <<EOF /* $cwrappersource - temporary wrapper executable for $objdir/$outputname Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION The $output program cannot be directly executed until all the libtool libraries that it depends on are installed. This wrapper executable should never be moved out of the build directory. If it is, it will not operate correctly. Currently, it simply execs the wrapper *script* "$SHELL $output", but could eventually absorb all of the scripts functionality and exec $objdir/$outputname directly. */ EOF cat <<"EOF" #include <stdio.h> #include <stdlib.h> #ifdef _MSC_VER # include <direct.h> # include <process.h> # include <io.h> # define setmode _setmode #else # include <unistd.h> # include <stdint.h> # ifdef __CYGWIN__ # include <io.h> # define HAVE_SETENV # ifdef __STRICT_ANSI__ char *realpath (const char *, char *); int putenv (char *); int setenv (const char *, const char *, int); # endif # endif #endif #include <malloc.h> #include <stdarg.h> #include <assert.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <sys/stat.h> #if defined(PATH_MAX) # define LT_PATHMAX PATH_MAX #elif defined(MAXPATHLEN) # define LT_PATHMAX MAXPATHLEN #else # define LT_PATHMAX 1024 #endif #ifndef S_IXOTH # define S_IXOTH 0 #endif #ifndef S_IXGRP # define S_IXGRP 0 #endif #ifdef _MSC_VER # define S_IXUSR _S_IEXEC # define stat _stat # ifndef _INTPTR_T_DEFINED # define intptr_t int # endif #endif #ifndef DIR_SEPARATOR # define DIR_SEPARATOR '/' # define PATH_SEPARATOR ':' #endif #if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \ defined (__OS2__) # define HAVE_DOS_BASED_FILE_SYSTEM # define FOPEN_WB "wb" # ifndef DIR_SEPARATOR_2 # define DIR_SEPARATOR_2 '\\' # endif # ifndef PATH_SEPARATOR_2 # define PATH_SEPARATOR_2 ';' # endif #endif #ifndef DIR_SEPARATOR_2 # define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) #else /* DIR_SEPARATOR_2 */ # define IS_DIR_SEPARATOR(ch) \ (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) #endif /* DIR_SEPARATOR_2 */ #ifndef PATH_SEPARATOR_2 # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) #else /* PATH_SEPARATOR_2 */ # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) #endif /* PATH_SEPARATOR_2 */ #ifdef __CYGWIN__ # define FOPEN_WB "wb" #endif #ifndef FOPEN_WB # define FOPEN_WB "w" #endif #ifndef _O_BINARY # define _O_BINARY 0 #endif #define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) #define XFREE(stale) do { \ if (stale) { free ((void *) stale); stale = 0; } \ } while (0) #undef LTWRAPPER_DEBUGPRINTF #if defined DEBUGWRAPPER # define LTWRAPPER_DEBUGPRINTF(args) ltwrapper_debugprintf args static void ltwrapper_debugprintf (const char *fmt, ...) { va_list args; va_start (args, fmt); (void) vfprintf (stderr, fmt, args); va_end (args); } #else # define LTWRAPPER_DEBUGPRINTF(args) #endif const char *program_name = NULL; void *xmalloc (size_t num); char *xstrdup (const char *string); const char *base_name (const char *name); char *find_executable (const char *wrapper); char *chase_symlinks (const char *pathspec); int make_executable (const char *path); int check_executable (const char *path); char *strendzap (char *str, const char *pat); void lt_fatal (const char *message, ...); void lt_setenv (const char *name, const char *value); char *lt_extend_str (const char *orig_value, const char *add, int to_end); void lt_opt_process_env_set (const char *arg); void lt_opt_process_env_prepend (const char *arg); void lt_opt_process_env_append (const char *arg); int lt_split_name_value (const char *arg, char** name, char** value); void lt_update_exe_path (const char *name, const char *value); void lt_update_lib_path (const char *name, const char *value); static const char *script_text_part1 = EOF func_emit_wrapper_part1 yes | $SED -e 's/\([\\"]\)/\\\1/g' \ -e 's/^/ "/' -e 's/$/\\n"/' echo ";" cat <<EOF static const char *script_text_part2 = EOF func_emit_wrapper_part2 yes | $SED -e 's/\([\\"]\)/\\\1/g' \ -e 's/^/ "/' -e 's/$/\\n"/' echo ";" cat <<EOF const char * MAGIC_EXE = "$magic_exe"; const char * LIB_PATH_VARNAME = "$shlibpath_var"; EOF if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then func_to_host_pathlist "$temp_rpath" cat <<EOF const char * LIB_PATH_VALUE = "$func_to_host_pathlist_result"; EOF else cat <<"EOF" const char * LIB_PATH_VALUE = ""; EOF fi if test -n "$dllsearchpath"; then func_to_host_pathlist "$dllsearchpath:" cat <<EOF const char * EXE_PATH_VARNAME = "PATH"; const char * EXE_PATH_VALUE = "$func_to_host_pathlist_result"; EOF else cat <<"EOF" const char * EXE_PATH_VARNAME = ""; const char * EXE_PATH_VALUE = ""; EOF fi if test "$fast_install" = yes; then cat <<EOF const char * TARGET_PROGRAM_NAME = "lt-$outputname"; /* hopefully, no .exe */ EOF else cat <<EOF const char * TARGET_PROGRAM_NAME = "$outputname"; /* hopefully, no .exe */ EOF fi cat <<"EOF" #define LTWRAPPER_OPTION_PREFIX "--lt-" #define LTWRAPPER_OPTION_PREFIX_LENGTH 5 static const size_t opt_prefix_len = LTWRAPPER_OPTION_PREFIX_LENGTH; static const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX; static const char *dumpscript_opt = LTWRAPPER_OPTION_PREFIX "dump-script"; static const size_t env_set_opt_len = LTWRAPPER_OPTION_PREFIX_LENGTH + 7; static const char *env_set_opt = LTWRAPPER_OPTION_PREFIX "env-set"; /* argument is putenv-style "foo=bar", value of foo is set to bar */ static const size_t env_prepend_opt_len = LTWRAPPER_OPTION_PREFIX_LENGTH + 11; static const char *env_prepend_opt = LTWRAPPER_OPTION_PREFIX "env-prepend"; /* argument is putenv-style "foo=bar", new value of foo is bar${foo} */ static const size_t env_append_opt_len = LTWRAPPER_OPTION_PREFIX_LENGTH + 10; static const char *env_append_opt = LTWRAPPER_OPTION_PREFIX "env-append"; /* argument is putenv-style "foo=bar", new value of foo is ${foo}bar */ #undef main int main (int argc, char *argv[]) { char **newargz; int newargc; char *tmp_pathspec; char *actual_cwrapper_path; char *actual_cwrapper_name; char *target_name; char *lt_argv_zero; intptr_t rval = 127; int i; program_name = (char *) xstrdup (base_name (argv[0])); LTWRAPPER_DEBUGPRINTF (("(main) argv[0] : %s\n", argv[0])); LTWRAPPER_DEBUGPRINTF (("(main) program_name : %s\n", program_name)); /* very simple arg parsing; don't want to rely on getopt */ for (i = 1; i < argc; i++) { if (strcmp (argv[i], dumpscript_opt) == 0) { EOF case "$host" in *mingw* | *cygwin* ) # make stdout use "unix" line endings echo " setmode(1,_O_BINARY);" ;; esac cat <<"EOF" printf ("%s", script_text_part1); printf ("%s", script_text_part2); return 0; } } newargz = XMALLOC (char *, argc + 1); tmp_pathspec = find_executable (argv[0]); if (tmp_pathspec == NULL) lt_fatal ("Couldn't find %s", argv[0]); LTWRAPPER_DEBUGPRINTF (("(main) found exe (before symlink chase) at : %s\n", tmp_pathspec)); actual_cwrapper_path = chase_symlinks (tmp_pathspec); LTWRAPPER_DEBUGPRINTF (("(main) found exe (after symlink chase) at : %s\n", actual_cwrapper_path)); XFREE (tmp_pathspec); actual_cwrapper_name = xstrdup( base_name (actual_cwrapper_path)); strendzap (actual_cwrapper_path, actual_cwrapper_name); /* wrapper name transforms */ strendzap (actual_cwrapper_name, ".exe"); tmp_pathspec = lt_extend_str (actual_cwrapper_name, ".exe", 1); XFREE (actual_cwrapper_name); actual_cwrapper_name = tmp_pathspec; tmp_pathspec = 0; /* target_name transforms -- use actual target program name; might have lt- prefix */ target_name = xstrdup (base_name (TARGET_PROGRAM_NAME)); strendzap (target_name, ".exe"); tmp_pathspec = lt_extend_str (target_name, ".exe", 1); XFREE (target_name); target_name = tmp_pathspec; tmp_pathspec = 0; LTWRAPPER_DEBUGPRINTF (("(main) libtool target name: %s\n", target_name)); EOF cat <<EOF newargz[0] = XMALLOC (char, (strlen (actual_cwrapper_path) + strlen ("$objdir") + 1 + strlen (actual_cwrapper_name) + 1)); strcpy (newargz[0], actual_cwrapper_path); strcat (newargz[0], "$objdir"); strcat (newargz[0], "/"); EOF cat <<"EOF" /* stop here, and copy so we don't have to do this twice */ tmp_pathspec = xstrdup (newargz[0]); /* do NOT want the lt- prefix here, so use actual_cwrapper_name */ strcat (newargz[0], actual_cwrapper_name); /* DO want the lt- prefix here if it exists, so use target_name */ lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1); XFREE (tmp_pathspec); tmp_pathspec = NULL; EOF case $host_os in mingw*) cat <<"EOF" { char* p; while ((p = strchr (newargz[0], '\\')) != NULL) { *p = '/'; } while ((p = strchr (lt_argv_zero, '\\')) != NULL) { *p = '/'; } } EOF ;; esac cat <<"EOF" XFREE (target_name); XFREE (actual_cwrapper_path); XFREE (actual_cwrapper_name); lt_setenv ("BIN_SH", "xpg4"); /* for Tru64 */ lt_setenv ("DUALCASE", "1"); /* for MSK sh */ lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE); lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE); newargc=0; for (i = 1; i < argc; i++) { if (strncmp (argv[i], env_set_opt, env_set_opt_len) == 0) { if (argv[i][env_set_opt_len] == '=') { const char *p = argv[i] + env_set_opt_len + 1; lt_opt_process_env_set (p); } else if (argv[i][env_set_opt_len] == '\0' && i + 1 < argc) { lt_opt_process_env_set (argv[++i]); /* don't copy */ } else lt_fatal ("%s missing required argument", env_set_opt); continue; } if (strncmp (argv[i], env_prepend_opt, env_prepend_opt_len) == 0) { if (argv[i][env_prepend_opt_len] == '=') { const char *p = argv[i] + env_prepend_opt_len + 1; lt_opt_process_env_prepend (p); } else if (argv[i][env_prepend_opt_len] == '\0' && i + 1 < argc) { lt_opt_process_env_prepend (argv[++i]); /* don't copy */ } else lt_fatal ("%s missing required argument", env_prepend_opt); continue; } if (strncmp (argv[i], env_append_opt, env_append_opt_len) == 0) { if (argv[i][env_append_opt_len] == '=') { const char *p = argv[i] + env_append_opt_len + 1; lt_opt_process_env_append (p); } else if (argv[i][env_append_opt_len] == '\0' && i + 1 < argc) { lt_opt_process_env_append (argv[++i]); /* don't copy */ } else lt_fatal ("%s missing required argument", env_append_opt); continue; } if (strncmp (argv[i], ltwrapper_option_prefix, opt_prefix_len) == 0) { /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX namespace, but it is not one of the ones we know about and have already dealt with, above (inluding dump-script), then report an error. Otherwise, targets might begin to believe they are allowed to use options in the LTWRAPPER_OPTION_PREFIX namespace. The first time any user complains about this, we'll need to make LTWRAPPER_OPTION_PREFIX a configure-time option or a configure.ac-settable value. */ lt_fatal ("Unrecognized option in %s namespace: '%s'", ltwrapper_option_prefix, argv[i]); } /* otherwise ... */ newargz[++newargc] = xstrdup (argv[i]); } newargz[++newargc] = NULL; LTWRAPPER_DEBUGPRINTF (("(main) lt_argv_zero : %s\n", (lt_argv_zero ? lt_argv_zero : "<NULL>"))); for (i = 0; i < newargc; i++) { LTWRAPPER_DEBUGPRINTF (("(main) newargz[%d] : %s\n", i, (newargz[i] ? newargz[i] : "<NULL>"))); } EOF case $host_os in mingw*) cat <<"EOF" /* execv doesn't actually work on mingw as expected on unix */ rval = _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz); if (rval == -1) { /* failed to start process */ LTWRAPPER_DEBUGPRINTF (("(main) failed to launch target \"%s\": errno = %d\n", lt_argv_zero, errno)); return 127; } return rval; EOF ;; *) cat <<"EOF" execv (lt_argv_zero, newargz); return rval; /* =127, but avoids unused variable warning */ EOF ;; esac cat <<"EOF" } void * xmalloc (size_t num) { void *p = (void *) malloc (num); if (!p) lt_fatal ("Memory exhausted"); return p; } char * xstrdup (const char *string) { return string ? strcpy ((char *) xmalloc (strlen (string) + 1), string) : NULL; } const char * base_name (const char *name) { const char *base; #if defined (HAVE_DOS_BASED_FILE_SYSTEM) /* Skip over the disk name in MSDOS pathnames. */ if (isalpha ((unsigned char) name[0]) && name[1] == ':') name += 2; #endif for (base = name; *name; name++) if (IS_DIR_SEPARATOR (*name)) base = name + 1; return base; } int check_executable (const char *path) { struct stat st; LTWRAPPER_DEBUGPRINTF (("(check_executable) : %s\n", path ? (*path ? path : "EMPTY!") : "NULL!")); if ((!path) || (!*path)) return 0; if ((stat (path, &st) >= 0) && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return 1; else return 0; } int make_executable (const char *path) { int rval = 0; struct stat st; LTWRAPPER_DEBUGPRINTF (("(make_executable) : %s\n", path ? (*path ? path : "EMPTY!") : "NULL!")); if ((!path) || (!*path)) return 0; if (stat (path, &st) >= 0) { rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); } return rval; } /* Searches for the full path of the wrapper. Returns newly allocated full path name if found, NULL otherwise Does not chase symlinks, even on platforms that support them. */ char * find_executable (const char *wrapper) { int has_slash = 0; const char *p; const char *p_next; /* static buffer for getcwd */ char tmp[LT_PATHMAX + 1]; int tmp_len; char *concat_name; LTWRAPPER_DEBUGPRINTF (("(find_executable) : %s\n", wrapper ? (*wrapper ? wrapper : "EMPTY!") : "NULL!")); if ((wrapper == NULL) || (*wrapper == '\0')) return NULL; /* Absolute path? */ #if defined (HAVE_DOS_BASED_FILE_SYSTEM) if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } else { #endif if (IS_DIR_SEPARATOR (wrapper[0])) { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } #if defined (HAVE_DOS_BASED_FILE_SYSTEM) } #endif for (p = wrapper; *p; p++) if (*p == '/') { has_slash = 1; break; } if (!has_slash) { /* no slashes; search PATH */ const char *path = getenv ("PATH"); if (path != NULL) { for (p = path; *p; p = p_next) { const char *q; size_t p_len; for (q = p; *q; q++) if (IS_PATH_SEPARATOR (*q)) break; p_len = q - p; p_next = (*q == '\0' ? q : q + 1); if (p_len == 0) { /* empty path: current directory */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal ("getcwd failed"); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); } else { concat_name = XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, p, p_len); concat_name[p_len] = '/'; strcpy (concat_name + p_len + 1, wrapper); } if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } } /* not found in PATH; assume curdir */ } /* Relative path | not found in path: prepend cwd */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal ("getcwd failed"); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); return NULL; } char * chase_symlinks (const char *pathspec) { #ifndef S_ISLNK return xstrdup (pathspec); #else char buf[LT_PATHMAX]; struct stat s; char *tmp_pathspec = xstrdup (pathspec); char *p; int has_symlinks = 0; while (strlen (tmp_pathspec) && !has_symlinks) { LTWRAPPER_DEBUGPRINTF (("checking path component for symlinks: %s\n", tmp_pathspec)); if (lstat (tmp_pathspec, &s) == 0) { if (S_ISLNK (s.st_mode) != 0) { has_symlinks = 1; break; } /* search backwards for last DIR_SEPARATOR */ p = tmp_pathspec + strlen (tmp_pathspec) - 1; while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) p--; if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) { /* no more DIR_SEPARATORS left */ break; } *p = '\0'; } else { char *errstr = strerror (errno); lt_fatal ("Error accessing file %s (%s)", tmp_pathspec, errstr); } } XFREE (tmp_pathspec); if (!has_symlinks) { return xstrdup (pathspec); } tmp_pathspec = realpath (pathspec, buf); if (tmp_pathspec == 0) { lt_fatal ("Could not follow symlinks for %s", pathspec); } return xstrdup (tmp_pathspec); #endif } char * strendzap (char *str, const char *pat) { size_t len, patlen; assert (str != NULL); assert (pat != NULL); len = strlen (str); patlen = strlen (pat); if (patlen <= len) { str += len - patlen; if (strcmp (str, pat) == 0) *str = '\0'; } return str; } static void lt_error_core (int exit_status, const char *mode, const char *message, va_list ap) { fprintf (stderr, "%s: %s: ", program_name, mode); vfprintf (stderr, message, ap); fprintf (stderr, ".\n"); if (exit_status >= 0) exit (exit_status); } void lt_fatal (const char *message, ...) { va_list ap; va_start (ap, message); lt_error_core (EXIT_FAILURE, "FATAL", message, ap); va_end (ap); } void lt_setenv (const char *name, const char *value) { LTWRAPPER_DEBUGPRINTF (("(lt_setenv) setting '%s' to '%s'\n", (name ? name : "<NULL>"), (value ? value : "<NULL>"))); { #ifdef HAVE_SETENV /* always make a copy, for consistency with !HAVE_SETENV */ char *str = xstrdup (value); setenv (name, str, 1); #else int len = strlen (name) + 1 + strlen (value) + 1; char *str = XMALLOC (char, len); sprintf (str, "%s=%s", name, value); if (putenv (str) != EXIT_SUCCESS) { XFREE (str); } #endif } } char * lt_extend_str (const char *orig_value, const char *add, int to_end) { char *new_value; if (orig_value && *orig_value) { int orig_value_len = strlen (orig_value); int add_len = strlen (add); new_value = XMALLOC (char, add_len + orig_value_len + 1); if (to_end) { strcpy (new_value, orig_value); strcpy (new_value + orig_value_len, add); } else { strcpy (new_value, add); strcpy (new_value + add_len, orig_value); } } else { new_value = xstrdup (add); } return new_value; } int lt_split_name_value (const char *arg, char** name, char** value) { const char *p; int len; if (!arg || !*arg) return 1; p = strchr (arg, (int)'='); if (!p) return 1; *value = xstrdup (++p); len = strlen (arg) - strlen (*value); *name = XMALLOC (char, len); strncpy (*name, arg, len-1); (*name)[len - 1] = '\0'; return 0; } void lt_opt_process_env_set (const char *arg) { char *name = NULL; char *value = NULL; if (lt_split_name_value (arg, &name, &value) != 0) { XFREE (name); XFREE (value); lt_fatal ("bad argument for %s: '%s'", env_set_opt, arg); } lt_setenv (name, value); XFREE (name); XFREE (value); } void lt_opt_process_env_prepend (const char *arg) { char *name = NULL; char *value = NULL; char *new_value = NULL; if (lt_split_name_value (arg, &name, &value) != 0) { XFREE (name); XFREE (value); lt_fatal ("bad argument for %s: '%s'", env_prepend_opt, arg); } new_value = lt_extend_str (getenv (name), value, 0); lt_setenv (name, new_value); XFREE (new_value); XFREE (name); XFREE (value); } void lt_opt_process_env_append (const char *arg) { char *name = NULL; char *value = NULL; char *new_value = NULL; if (lt_split_name_value (arg, &name, &value) != 0) { XFREE (name); XFREE (value); lt_fatal ("bad argument for %s: '%s'", env_append_opt, arg); } new_value = lt_extend_str (getenv (name), value, 1); lt_setenv (name, new_value); XFREE (new_value); XFREE (name); XFREE (value); } void lt_update_exe_path (const char *name, const char *value) { LTWRAPPER_DEBUGPRINTF (("(lt_update_exe_path) modifying '%s' by prepending '%s'\n", (name ? name : "<NULL>"), (value ? value : "<NULL>"))); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); /* some systems can't cope with a ':'-terminated path #' */ int len = strlen (new_value); while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1])) { new_value[len-1] = '\0'; } lt_setenv (name, new_value); XFREE (new_value); } } void lt_update_lib_path (const char *name, const char *value) { LTWRAPPER_DEBUGPRINTF (("(lt_update_lib_path) modifying '%s' by prepending '%s'\n", (name ? name : "<NULL>"), (value ? value : "<NULL>"))); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); lt_setenv (name, new_value); XFREE (new_value); } } EOF } # end: func_emit_cwrapperexe_src # func_mode_link arg... func_mode_link () { $opt_debug case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) # It is impossible to link a dll without this setting, and # we shouldn't force the makefile maintainer to figure out # which system we are compiling for in order to pass an extra # flag for every libtool invocation. # allow_undefined=no # FIXME: Unfortunately, there are problems with the above when trying # to make a dll which has undefined symbols, in which case not # even a static library is built. For now, we need to specify # -no-undefined on the libtool link line when we can be certain # that all symbols are satisfied, otherwise we get a static library. allow_undefined=yes ;; *) allow_undefined=yes ;; esac libtool_args=$nonopt base_compile="$nonopt $@" compile_command=$nonopt finalize_command=$nonopt compile_rpath= finalize_rpath= compile_shlibpath= finalize_shlibpath= convenience= old_convenience= deplibs= old_deplibs= compiler_flags= linker_flags= dllsearchpath= lib_search_path=`pwd` inst_prefix_dir= new_inherited_linker_flags= avoid_version=no dlfiles= dlprefiles= dlself=no export_dynamic=no export_symbols= export_symbols_regex= generated= libobjs= ltlibs= module=no no_install=no objs= non_pic_objects= precious_files_regex= prefer_static_libs=no preload=no prev= prevarg= release= rpath= xrpath= perm_rpath= temp_rpath= thread_safe=no vinfo= vinfo_number=no weak_libs= single_module="${wl}-single_module" func_infer_tag $base_compile # We need to know -static, to get the right output filenames. for arg do case $arg in -shared) test "$build_libtool_libs" != yes && \ func_fatal_configuration "can not build a shared library" build_old_libs=no break ;; -all-static | -static | -static-libtool-libs) case $arg in -all-static) if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then func_warning "complete static linking is impossible in this configuration" fi if test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; -static) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=built ;; -static-libtool-libs) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; esac build_libtool_libs=no build_old_libs=yes break ;; esac done # See if our shared archives depend on static archives. test -n "$old_archive_from_new_cmds" && build_old_libs=yes # Go through the arguments, transforming them on the way. while test "$#" -gt 0; do arg="$1" shift func_quote_for_eval "$arg" qarg=$func_quote_for_eval_unquoted_result func_append libtool_args " $func_quote_for_eval_result" # If the previous option needs an argument, assign it. if test -n "$prev"; then case $prev in output) func_append compile_command " @OUTPUT@" func_append finalize_command " @OUTPUT@" ;; esac case $prev in dlfiles|dlprefiles) if test "$preload" = no; then # Add the symbol object into the linking commands. func_append compile_command " @SYMFILE@" func_append finalize_command " @SYMFILE@" preload=yes fi case $arg in *.la | *.lo) ;; # We handle these cases below. force) if test "$dlself" = no; then dlself=needless export_dynamic=yes fi prev= continue ;; self) if test "$prev" = dlprefiles; then dlself=yes elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then dlself=yes else dlself=needless export_dynamic=yes fi prev= continue ;; *) if test "$prev" = dlfiles; then dlfiles="$dlfiles $arg" else dlprefiles="$dlprefiles $arg" fi prev= continue ;; esac ;; expsyms) export_symbols="$arg" test -f "$arg" \ || func_fatal_error "symbol file \`$arg' does not exist" prev= continue ;; expsyms_regex) export_symbols_regex="$arg" prev= continue ;; framework) case $host in *-*-darwin*) case "$deplibs " in *" $qarg.ltframework "*) ;; *) deplibs="$deplibs $qarg.ltframework" # this is fixed later ;; esac ;; esac prev= continue ;; inst_prefix) inst_prefix_dir="$arg" prev= continue ;; objectlist) if test -f "$arg"; then save_arg=$arg moreargs= for fil in `cat "$save_arg"` do # moreargs="$moreargs $fil" arg=$fil # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test "$pic_object" = none && test "$non_pic_object" = none; then func_fatal_error "cannot find name of object for \`$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" if test "$pic_object" != none; then # Prepend the subdirectory the object is found in. pic_object="$xdir$pic_object" if test "$prev" = dlfiles; then if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then dlfiles="$dlfiles $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test "$prev" = dlprefiles; then # Preload the old-style object. dlprefiles="$dlprefiles $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg="$pic_object" fi # Non-PIC object. if test "$non_pic_object" != none; then # Prepend the subdirectory the object is found in. non_pic_object="$xdir$non_pic_object" # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test "$pic_object" = none ; then arg="$non_pic_object" fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object="$pic_object" func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "\`$arg' is not a valid libtool object" fi fi done else func_fatal_error "link input file \`$arg' does not exist" fi arg=$save_arg prev= continue ;; precious_regex) precious_files_regex="$arg" prev= continue ;; release) release="-$arg" prev= continue ;; rpath | xrpath) # We need an absolute path. case $arg in [\\/]* | [A-Za-z]:[\\/]*) ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac if test "$prev" = rpath; then case "$rpath " in *" $arg "*) ;; *) rpath="$rpath $arg" ;; esac else case "$xrpath " in *" $arg "*) ;; *) xrpath="$xrpath $arg" ;; esac fi prev= continue ;; shrext) shrext_cmds="$arg" prev= continue ;; weak) weak_libs="$weak_libs $arg" prev= continue ;; xcclinker) linker_flags="$linker_flags $qarg" compiler_flags="$compiler_flags $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xcompiler) compiler_flags="$compiler_flags $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xlinker) linker_flags="$linker_flags $qarg" compiler_flags="$compiler_flags $wl$qarg" prev= func_append compile_command " $wl$qarg" func_append finalize_command " $wl$qarg" continue ;; *) eval "$prev=\"\$arg\"" prev= continue ;; esac fi # test -n "$prev" prevarg="$arg" case $arg in -all-static) if test -n "$link_static_flag"; then # See comment for -static flag below, for more details. func_append compile_command " $link_static_flag" func_append finalize_command " $link_static_flag" fi continue ;; -allow-undefined) # FIXME: remove this flag sometime in the future. func_fatal_error "\`-allow-undefined' must not be used because it is the default" ;; -avoid-version) avoid_version=yes continue ;; -dlopen) prev=dlfiles continue ;; -dlpreopen) prev=dlprefiles continue ;; -export-dynamic) export_dynamic=yes continue ;; -export-symbols | -export-symbols-regex) if test -n "$export_symbols" || test -n "$export_symbols_regex"; then func_fatal_error "more than one -exported-symbols argument is not allowed" fi if test "X$arg" = "X-export-symbols"; then prev=expsyms else prev=expsyms_regex fi continue ;; -framework) prev=framework continue ;; -inst-prefix-dir) prev=inst_prefix continue ;; # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* # so, if we see these flags be careful not to treat them like -L -L[A-Z][A-Z]*:*) case $with_gcc/$host in no/*-*-irix* | /*-*-irix*) func_append compile_command " $arg" func_append finalize_command " $arg" ;; esac continue ;; -L*) func_stripname '-L' '' "$arg" dir=$func_stripname_result if test -z "$dir"; then if test "$#" -gt 0; then func_fatal_error "require no space between \`-L' and \`$1'" else func_fatal_error "need path for \`-L' option" fi fi # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) absdir=`cd "$dir" && pwd` test -z "$absdir" && \ func_fatal_error "cannot determine absolute directory name of \`$dir'" dir="$absdir" ;; esac case "$deplibs " in *" -L$dir "*) ;; *) deplibs="$deplibs -L$dir" lib_search_path="$lib_search_path $dir" ;; esac case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "X$dir" | $Xsed -e 's*/lib$*/bin*'` case :$dllsearchpath: in *":$dir:"*) ;; ::) dllsearchpath=$dir;; *) dllsearchpath="$dllsearchpath:$dir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) dllsearchpath="$dllsearchpath:$testbindir";; esac ;; esac continue ;; -l*) if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc*) # These systems don't actually have a C or math library (as such) continue ;; *-*-os2*) # These systems don't actually have a C library (as such) test "X$arg" = "X-lc" && continue ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. test "X$arg" = "X-lc" && continue ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C and math libraries are in the System framework deplibs="$deplibs System.ltframework" continue ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype test "X$arg" = "X-lc" && continue ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work test "X$arg" = "X-lc" && continue ;; esac elif test "X$arg" = "X-lc_r"; then case $host in *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc_r directly, use -pthread flag. continue ;; esac fi deplibs="$deplibs $arg" continue ;; -module) module=yes continue ;; # Tru64 UNIX uses -model [arg] to determine the layout of C++ # classes, name mangling, and exception handling. # Darwin uses the -arch flag to determine output architecture. -model|-arch|-isysroot) compiler_flags="$compiler_flags $arg" func_append compile_command " $arg" func_append finalize_command " $arg" prev=xcompiler continue ;; -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads) compiler_flags="$compiler_flags $arg" func_append compile_command " $arg" func_append finalize_command " $arg" case "$new_inherited_linker_flags " in *" $arg "*) ;; * ) new_inherited_linker_flags="$new_inherited_linker_flags $arg" ;; esac continue ;; -multi_module) single_module="${wl}-multi_module" continue ;; -no-fast-install) fast_install=no continue ;; -no-install) case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) # The PATH hackery in wrapper scripts is required on Windows # and Darwin in order for the loader to find any dlls it needs. func_warning "\`-no-install' is ignored for $host" func_warning "assuming \`-no-fast-install' instead" fast_install=no ;; *) no_install=yes ;; esac continue ;; -no-undefined) allow_undefined=no continue ;; -objectlist) prev=objectlist continue ;; -o) prev=output ;; -precious-files-regex) prev=precious_regex continue ;; -release) prev=release continue ;; -rpath) prev=rpath continue ;; -R) prev=xrpath continue ;; -R*) func_stripname '-R' '' "$arg" dir=$func_stripname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac case "$xrpath " in *" $dir "*) ;; *) xrpath="$xrpath $dir" ;; esac continue ;; -shared) # The effects of -shared are defined in a previous loop. continue ;; -shrext) prev=shrext continue ;; -static | -static-libtool-libs) # The effects of -static are defined in a previous loop. # We used to do the same as -all-static on platforms that # didn't have a PIC flag, but the assumption that the effects # would be equivalent was wrong. It would break on at least # Digital Unix and AIX. continue ;; -thread-safe) thread_safe=yes continue ;; -version-info) prev=vinfo continue ;; -version-number) prev=vinfo vinfo_number=yes continue ;; -weak) prev=weak continue ;; -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result arg= save_ifs="$IFS"; IFS=',' for flag in $args; do IFS="$save_ifs" func_quote_for_eval "$flag" arg="$arg $wl$func_quote_for_eval_result" compiler_flags="$compiler_flags $func_quote_for_eval_result" done IFS="$save_ifs" func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Wl,*) func_stripname '-Wl,' '' "$arg" args=$func_stripname_result arg= save_ifs="$IFS"; IFS=',' for flag in $args; do IFS="$save_ifs" func_quote_for_eval "$flag" arg="$arg $wl$func_quote_for_eval_result" compiler_flags="$compiler_flags $wl$func_quote_for_eval_result" linker_flags="$linker_flags $func_quote_for_eval_result" done IFS="$save_ifs" func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Xcompiler) prev=xcompiler continue ;; -Xlinker) prev=xlinker continue ;; -XCClinker) prev=xcclinker continue ;; # -msg_* for osf cc -msg_*) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; # -64, -mips[0-9] enable 64-bit mode on the SGI compiler # -r[0-9][0-9]* specifies the processor on the SGI compiler # -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler # +DA*, +DD* enable 64-bit mode on the HP compiler # -q* pass through compiler args for the IBM compiler # -m*, -t[45]*, -txscale* pass through architecture-specific # compiler args for GCC # -F/path gives path to uninstalled frameworks, gcc on darwin # -p, -pg, --coverage, -fprofile-* pass through profiling flag for GCC # @file GCC response files -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" func_append compile_command " $arg" func_append finalize_command " $arg" compiler_flags="$compiler_flags $arg" continue ;; # Some other compiler flag. -* | +*) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; *.$objext) # A standard object. objs="$objs $arg" ;; *.lo) # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test "$pic_object" = none && test "$non_pic_object" = none; then func_fatal_error "cannot find name of object for \`$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" if test "$pic_object" != none; then # Prepend the subdirectory the object is found in. pic_object="$xdir$pic_object" if test "$prev" = dlfiles; then if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then dlfiles="$dlfiles $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test "$prev" = dlprefiles; then # Preload the old-style object. dlprefiles="$dlprefiles $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg="$pic_object" fi # Non-PIC object. if test "$non_pic_object" != none; then # Prepend the subdirectory the object is found in. non_pic_object="$xdir$non_pic_object" # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test "$pic_object" = none ; then arg="$non_pic_object" fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object="$pic_object" func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "\`$arg' is not a valid libtool object" fi fi ;; *.$libext) # An archive. deplibs="$deplibs $arg" old_deplibs="$old_deplibs $arg" continue ;; *.la) # A libtool-controlled library. if test "$prev" = dlfiles; then # This library was specified with -dlopen. dlfiles="$dlfiles $arg" prev= elif test "$prev" = dlprefiles; then # The library was specified with -dlpreopen. dlprefiles="$dlprefiles $arg" prev= else deplibs="$deplibs $arg" fi continue ;; # Some other compiler argument. *) # Unknown arguments in both finalize_command and compile_command need # to be aesthetically quoted because they are evaled later. func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; esac # arg # Now actually substitute the argument into the commands. if test -n "$arg"; then func_append compile_command " $arg" func_append finalize_command " $arg" fi done # argument parsing loop test -n "$prev" && \ func_fatal_help "the \`$prevarg' option requires an argument" if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then eval arg=\"$export_dynamic_flag_spec\" func_append compile_command " $arg" func_append finalize_command " $arg" fi oldlibs= # calculate the name of the file, without its directory func_basename "$output" outputname="$func_basename_result" libobjs_save="$libobjs" if test -n "$shlibpath_var"; then # get the directories listed in $shlibpath_var eval shlib_search_path=\`\$ECHO \"X\${$shlibpath_var}\" \| \$Xsed -e \'s/:/ /g\'\` else shlib_search_path= fi eval sys_lib_search_path=\"$sys_lib_search_path_spec\" eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" func_dirname "$output" "/" "" output_objdir="$func_dirname_result$objdir" # Create the object directory. func_mkdir_p "$output_objdir" # Determine the type of output case $output in "") func_fatal_help "you must specify an output file" ;; *.$libext) linkmode=oldlib ;; *.lo | *.$objext) linkmode=obj ;; *.la) linkmode=lib ;; *) linkmode=prog ;; # Anything else should be a program. esac specialdeplibs= libs= # Find all interdependent deplibs by searching for libraries # that are linked more than once (e.g. -la -lb -la) for deplib in $deplibs; do if $opt_duplicate_deps ; then case "$libs " in *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; esac fi libs="$libs $deplib" done if test "$linkmode" = lib; then libs="$predeps $libs $compiler_lib_search_path $postdeps" # Compute libraries that are listed more than once in $predeps # $postdeps and mark them as special (i.e., whose duplicates are # not to be eliminated). pre_post_deps= if $opt_duplicate_compiler_generated_deps; then for pre_post_dep in $predeps $postdeps; do case "$pre_post_deps " in *" $pre_post_dep "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;; esac pre_post_deps="$pre_post_deps $pre_post_dep" done fi pre_post_deps= fi deplibs= newdependency_libs= newlib_search_path= need_relink=no # whether we're linking any uninstalled libtool libraries notinst_deplibs= # not-installed libtool libraries notinst_path= # paths that contain not-installed libtool libraries case $linkmode in lib) passes="conv dlpreopen link" for file in $dlfiles $dlprefiles; do case $file in *.la) ;; *) func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file" ;; esac done ;; prog) compile_deplibs= finalize_deplibs= alldeplibs=no newdlfiles= newdlprefiles= passes="conv scan dlopen dlpreopen link" ;; *) passes="conv" ;; esac for pass in $passes; do # The preopen pass in lib mode reverses $deplibs; put it back here # so that -L comes before libs that need it for instance... if test "$linkmode,$pass" = "lib,link"; then ## FIXME: Find the place where the list is rebuilt in the wrong ## order, and fix it there properly tmp_deplibs= for deplib in $deplibs; do tmp_deplibs="$deplib $tmp_deplibs" done deplibs="$tmp_deplibs" fi if test "$linkmode,$pass" = "lib,link" || test "$linkmode,$pass" = "prog,scan"; then libs="$deplibs" deplibs= fi if test "$linkmode" = prog; then case $pass in dlopen) libs="$dlfiles" ;; dlpreopen) libs="$dlprefiles" ;; link) libs="$deplibs %DEPLIBS% $dependency_libs" ;; esac fi if test "$linkmode,$pass" = "lib,dlpreopen"; then # Collect and forward deplibs of preopened libtool libs for lib in $dlprefiles; do # Ignore non-libtool-libs dependency_libs= case $lib in *.la) func_source "$lib" ;; esac # Collect preopened libtool deplibs, except any this library # has declared as weak libs for deplib in $dependency_libs; do deplib_base=`$ECHO "X$deplib" | $Xsed -e "$basename"` case " $weak_libs " in *" $deplib_base "*) ;; *) deplibs="$deplibs $deplib" ;; esac done done libs="$dlprefiles" fi if test "$pass" = dlopen; then # Collect dlpreopened libraries save_deplibs="$deplibs" deplibs= fi for deplib in $libs; do lib= found=no case $deplib in -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads) if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else compiler_flags="$compiler_flags $deplib" if test "$linkmode" = lib ; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) new_inherited_linker_flags="$new_inherited_linker_flags $deplib" ;; esac fi fi continue ;; -l*) if test "$linkmode" != lib && test "$linkmode" != prog; then func_warning "\`-l' is ignored for archives/objects" continue fi func_stripname '-l' '' "$deplib" name=$func_stripname_result if test "$linkmode" = lib; then searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" else searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" fi for searchdir in $searchdirs; do for search_ext in .la $std_shrext .so .a; do # Search the libtool library lib="$searchdir/lib${name}${search_ext}" if test -f "$lib"; then if test "$search_ext" = ".la"; then found=yes else found=no fi break 2 fi done done if test "$found" != yes; then # deplib doesn't seem to be a libtool library if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" fi continue else # deplib is a libtool library # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, # We need to do some special things here, and not later. if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $deplib "*) if func_lalib_p "$lib"; then library_names= old_library= func_source "$lib" for l in $old_library $library_names; do ll="$l" done if test "X$ll" = "X$old_library" ; then # only static version available found=no func_dirname "$lib" "" "." ladir="$func_dirname_result" lib=$ladir/$old_library if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" fi continue fi fi ;; *) ;; esac fi fi ;; # -l *.ltframework) if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" if test "$linkmode" = lib ; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) new_inherited_linker_flags="$new_inherited_linker_flags $deplib" ;; esac fi fi continue ;; -L*) case $linkmode in lib) deplibs="$deplib $deplibs" test "$pass" = conv && continue newdependency_libs="$deplib $newdependency_libs" func_stripname '-L' '' "$deplib" newlib_search_path="$newlib_search_path $func_stripname_result" ;; prog) if test "$pass" = conv; then deplibs="$deplib $deplibs" continue fi if test "$pass" = scan; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi func_stripname '-L' '' "$deplib" newlib_search_path="$newlib_search_path $func_stripname_result" ;; *) func_warning "\`-L' is ignored for archives/objects" ;; esac # linkmode continue ;; # -L -R*) if test "$pass" = link; then func_stripname '-R' '' "$deplib" dir=$func_stripname_result # Make sure the xrpath contains only unique directories. case "$xrpath " in *" $dir "*) ;; *) xrpath="$xrpath $dir" ;; esac fi deplibs="$deplib $deplibs" continue ;; *.la) lib="$deplib" ;; *.$libext) if test "$pass" = conv; then deplibs="$deplib $deplibs" continue fi case $linkmode in lib) # Linking convenience modules into shared libraries is allowed, # but linking other static libraries is non-portable. case " $dlpreconveniencelibs " in *" $deplib "*) ;; *) valid_a_lib=no case $deplibs_check_method in match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` if eval "\$ECHO \"X$deplib\"" 2>/dev/null | $Xsed -e 10q \ | $EGREP "$match_pattern_regex" > /dev/null; then valid_a_lib=yes fi ;; pass_all) valid_a_lib=yes ;; esac if test "$valid_a_lib" != yes; then $ECHO $ECHO "*** Warning: Trying to link with static lib archive $deplib." $ECHO "*** I have the capability to make that library automatically link in when" $ECHO "*** you link to this library. But I can only do this if you have a" $ECHO "*** shared version of the library, which you do not appear to have" $ECHO "*** because the file extensions .$libext of this argument makes me believe" $ECHO "*** that it is just a static archive that I should not use here." else $ECHO $ECHO "*** Warning: Linking the shared library $output against the" $ECHO "*** static library $deplib is not portable!" deplibs="$deplib $deplibs" fi ;; esac continue ;; prog) if test "$pass" != link; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi continue ;; esac # linkmode ;; # *.$libext *.lo | *.$objext) if test "$pass" = conv; then deplibs="$deplib $deplibs" elif test "$linkmode" = prog; then if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then # If there is no dlopen support or we're linking statically, # we need to preload. newdlprefiles="$newdlprefiles $deplib" compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else newdlfiles="$newdlfiles $deplib" fi fi continue ;; %DEPLIBS%) alldeplibs=yes continue ;; esac # case $deplib if test "$found" = yes || test -f "$lib"; then : else func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'" fi # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$lib" \ || func_fatal_error "\`$lib' is not a valid libtool archive" func_dirname "$lib" "" "." ladir="$func_dirname_result" dlname= dlopen= dlpreopen= libdir= library_names= old_library= inherited_linker_flags= # If the library was installed with an old release of libtool, # it will not redefine variables installed, or shouldnotlink installed=yes shouldnotlink=no avoidtemprpath= # Read the .la file func_source "$lib" # Convert "-framework foo" to "foo.ltframework" if test -n "$inherited_linker_flags"; then tmp_inherited_linker_flags=`$ECHO "X$inherited_linker_flags" | $Xsed -e 's/-framework \([^ $]*\)/\1.ltframework/g'` for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do case " $new_inherited_linker_flags " in *" $tmp_inherited_linker_flag "*) ;; *) new_inherited_linker_flags="$new_inherited_linker_flags $tmp_inherited_linker_flag";; esac done fi dependency_libs=`$ECHO "X $dependency_libs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` if test "$linkmode,$pass" = "lib,link" || test "$linkmode,$pass" = "prog,scan" || { test "$linkmode" != prog && test "$linkmode" != lib; }; then test -n "$dlopen" && dlfiles="$dlfiles $dlopen" test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen" fi if test "$pass" = conv; then # Only check for convenience libraries deplibs="$lib $deplibs" if test -z "$libdir"; then if test -z "$old_library"; then func_fatal_error "cannot find name of link library for \`$lib'" fi # It is a libtool convenience library, so add in its objects. convenience="$convenience $ladir/$objdir/$old_library" old_convenience="$old_convenience $ladir/$objdir/$old_library" elif test "$linkmode" != prog && test "$linkmode" != lib; then func_fatal_error "\`$lib' is not a convenience library" fi tmp_libs= for deplib in $dependency_libs; do deplibs="$deplib $deplibs" if $opt_duplicate_deps ; then case "$tmp_libs " in *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; esac fi tmp_libs="$tmp_libs $deplib" done continue fi # $pass = conv # Get the name of the library we link against. linklib= for l in $old_library $library_names; do linklib="$l" done if test -z "$linklib"; then func_fatal_error "cannot find name of link library for \`$lib'" fi # This library was specified with -dlopen. if test "$pass" = dlopen; then if test -z "$libdir"; then func_fatal_error "cannot -dlopen a convenience library: \`$lib'" fi if test -z "$dlname" || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then # If there is no dlname, no dlopen support or we're linking # statically, we need to preload. We also need to preload any # dependent libraries so libltdl's deplib preloader doesn't # bomb out in the load deplibs phase. dlprefiles="$dlprefiles $lib $dependency_libs" else newdlfiles="$newdlfiles $lib" fi continue fi # $pass = dlopen # We need an absolute path. case $ladir in [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;; *) abs_ladir=`cd "$ladir" && pwd` if test -z "$abs_ladir"; then func_warning "cannot determine absolute directory name of \`$ladir'" func_warning "passing it literally to the linker, although it might fail" abs_ladir="$ladir" fi ;; esac func_basename "$lib" laname="$func_basename_result" # Find the relevant object directory and library name. if test "X$installed" = Xyes; then if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then func_warning "library \`$lib' was moved." dir="$ladir" absdir="$abs_ladir" libdir="$abs_ladir" else dir="$libdir" absdir="$libdir" fi test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes else if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then dir="$ladir" absdir="$abs_ladir" # Remove this search path later notinst_path="$notinst_path $abs_ladir" else dir="$ladir/$objdir" absdir="$abs_ladir/$objdir" # Remove this search path later notinst_path="$notinst_path $abs_ladir" fi fi # $installed = yes func_stripname 'lib' '.la' "$laname" name=$func_stripname_result # This library was specified with -dlpreopen. if test "$pass" = dlpreopen; then if test -z "$libdir" && test "$linkmode" = prog; then func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'" fi # Prefer using a static library (so that no silly _DYNAMIC symbols # are required to link). if test -n "$old_library"; then newdlprefiles="$newdlprefiles $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ dlpreconveniencelibs="$dlpreconveniencelibs $dir/$old_library" # Otherwise, use the dlname, so that lt_dlopen finds it. elif test -n "$dlname"; then newdlprefiles="$newdlprefiles $dir/$dlname" else newdlprefiles="$newdlprefiles $dir/$linklib" fi fi # $pass = dlpreopen if test -z "$libdir"; then # Link the convenience library if test "$linkmode" = lib; then deplibs="$dir/$old_library $deplibs" elif test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$dir/$old_library $compile_deplibs" finalize_deplibs="$dir/$old_library $finalize_deplibs" else deplibs="$lib $deplibs" # used for prog,scan pass fi continue fi if test "$linkmode" = prog && test "$pass" != link; then newlib_search_path="$newlib_search_path $ladir" deplibs="$lib $deplibs" linkalldeplibs=no if test "$link_all_deplibs" != no || test -z "$library_names" || test "$build_libtool_libs" = no; then linkalldeplibs=yes fi tmp_libs= for deplib in $dependency_libs; do case $deplib in -L*) func_stripname '-L' '' "$deplib" newlib_search_path="$newlib_search_path $func_stripname_result" ;; esac # Need to link against all dependency_libs? if test "$linkalldeplibs" = yes; then deplibs="$deplib $deplibs" else # Need to hardcode shared library paths # or/and link against static libraries newdependency_libs="$deplib $newdependency_libs" fi if $opt_duplicate_deps ; then case "$tmp_libs " in *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; esac fi tmp_libs="$tmp_libs $deplib" done # for deplib continue fi # $linkmode = prog... if test "$linkmode,$pass" = "prog,link"; then if test -n "$library_names" && { { test "$prefer_static_libs" = no || test "$prefer_static_libs,$installed" = "built,yes"; } || test -z "$old_library"; }; then # We need to hardcode the library path if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then # Make sure the rpath contains only unique directories. case "$temp_rpath:" in *"$absdir:"*) ;; *) temp_rpath="$temp_rpath$absdir:" ;; esac fi # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) compile_rpath="$compile_rpath $absdir" esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) finalize_rpath="$finalize_rpath $libdir" esac ;; esac fi # $linkmode,$pass = prog,link... if test "$alldeplibs" = yes && { test "$deplibs_check_method" = pass_all || { test "$build_libtool_libs" = yes && test -n "$library_names"; }; }; then # We only need to search for static libraries continue fi fi link_static=no # Whether the deplib will be linked statically use_static_libs=$prefer_static_libs if test "$use_static_libs" = built && test "$installed" = yes; then use_static_libs=no fi if test -n "$library_names" && { test "$use_static_libs" = no || test -z "$old_library"; }; then case $host in *cygwin* | *mingw* | *cegcc*) # No point in relinking DLLs because paths are not encoded notinst_deplibs="$notinst_deplibs $lib" need_relink=no ;; *) if test "$installed" = no; then notinst_deplibs="$notinst_deplibs $lib" need_relink=yes fi ;; esac # This is a shared library # Warn about portability, can't link against -module's on some # systems (darwin). Don't bleat about dlopened modules though! dlopenmodule="" for dlpremoduletest in $dlprefiles; do if test "X$dlpremoduletest" = "X$lib"; then dlopenmodule="$dlpremoduletest" break fi done if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then $ECHO if test "$linkmode" = prog; then $ECHO "*** Warning: Linking the executable $output against the loadable module" else $ECHO "*** Warning: Linking the shared library $output against the loadable module" fi $ECHO "*** $linklib is not portable!" fi if test "$linkmode" = lib && test "$hardcode_into_libs" = yes; then # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) compile_rpath="$compile_rpath $absdir" esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) finalize_rpath="$finalize_rpath $libdir" esac ;; esac fi if test -n "$old_archive_from_expsyms_cmds"; then # figure out the soname set dummy $library_names shift realname="$1" shift libname=`eval "\\$ECHO \"$libname_spec\""` # use dlname if we got it. it's perfectly good, no? if test -n "$dlname"; then soname="$dlname" elif test -n "$soname_spec"; then # bleh windows case $host in *cygwin* | mingw* | *cegcc*) func_arith $current - $age major=$func_arith_result versuffix="-$major" ;; esac eval soname=\"$soname_spec\" else soname="$realname" fi # Make a new name for the extract_expsyms_cmds to use soroot="$soname" func_basename "$soroot" soname="$func_basename_result" func_stripname 'lib' '.dll' "$soname" newlib=libimp-$func_stripname_result.a # If the library has no export list, then create one now if test -f "$output_objdir/$soname-def"; then : else func_verbose "extracting exported symbol list from \`$soname'" func_execute_cmds "$extract_expsyms_cmds" 'exit $?' fi # Create $newlib if test -f "$output_objdir/$newlib"; then :; else func_verbose "generating import library for \`$soname'" func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' fi # make sure the library variables are pointing to the new library dir=$output_objdir linklib=$newlib fi # test -n "$old_archive_from_expsyms_cmds" if test "$linkmode" = prog || test "$mode" != relink; then add_shlibpath= add_dir= add= lib_linked=yes case $hardcode_action in immediate | unsupported) if test "$hardcode_direct" = no; then add="$dir/$linklib" case $host in *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;; *-*-sysv4*uw2*) add_dir="-L$dir" ;; *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ *-*-unixware7*) add_dir="-L$dir" ;; *-*-darwin* ) # if the lib is a (non-dlopened) module then we can not # link against it, someone is ignoring the earlier warnings if /usr/bin/file -L $add 2> /dev/null | $GREP ": [^:]* bundle" >/dev/null ; then if test "X$dlopenmodule" != "X$lib"; then $ECHO "*** Warning: lib $linklib is a module, not a shared library" if test -z "$old_library" ; then $ECHO $ECHO "*** And there doesn't seem to be a static archive available" $ECHO "*** The link will probably fail, sorry" else add="$dir/$old_library" fi elif test -n "$old_library"; then add="$dir/$old_library" fi fi esac elif test "$hardcode_minus_L" = no; then case $host in *-*-sunos*) add_shlibpath="$dir" ;; esac add_dir="-L$dir" add="-l$name" elif test "$hardcode_shlibpath_var" = no; then add_shlibpath="$dir" add="-l$name" else lib_linked=no fi ;; relink) if test "$hardcode_direct" = yes && test "$hardcode_direct_absolute" = no; then add="$dir/$linklib" elif test "$hardcode_minus_L" = yes; then add_dir="-L$dir" # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) add_dir="$add_dir -L$inst_prefix_dir$libdir" ;; esac fi add="-l$name" elif test "$hardcode_shlibpath_var" = yes; then add_shlibpath="$dir" add="-l$name" else lib_linked=no fi ;; *) lib_linked=no ;; esac if test "$lib_linked" != yes; then func_fatal_configuration "unsupported hardcode properties" fi if test -n "$add_shlibpath"; then case :$compile_shlibpath: in *":$add_shlibpath:"*) ;; *) compile_shlibpath="$compile_shlibpath$add_shlibpath:" ;; esac fi if test "$linkmode" = prog; then test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" test -n "$add" && compile_deplibs="$add $compile_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" if test "$hardcode_direct" != yes && test "$hardcode_minus_L" != yes && test "$hardcode_shlibpath_var" = yes; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; esac fi fi fi if test "$linkmode" = prog || test "$mode" = relink; then add_shlibpath= add_dir= add= # Finalize command for both is simple: just hardcode it. if test "$hardcode_direct" = yes && test "$hardcode_direct_absolute" = no; then add="$libdir/$linklib" elif test "$hardcode_minus_L" = yes; then add_dir="-L$libdir" add="-l$name" elif test "$hardcode_shlibpath_var" = yes; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; esac add="-l$name" elif test "$hardcode_automatic" = yes; then if test -n "$inst_prefix_dir" && test -f "$inst_prefix_dir$libdir/$linklib" ; then add="$inst_prefix_dir$libdir/$linklib" else add="$libdir/$linklib" fi else # We cannot seem to hardcode it, guess we'll fake it. add_dir="-L$libdir" # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) add_dir="$add_dir -L$inst_prefix_dir$libdir" ;; esac fi add="-l$name" fi if test "$linkmode" = prog; then test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" test -n "$add" && finalize_deplibs="$add $finalize_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" fi fi elif test "$linkmode" = prog; then # Here we assume that one of hardcode_direct or hardcode_minus_L # is not unsupported. This is valid on all known static and # shared platforms. if test "$hardcode_direct" != unsupported; then test -n "$old_library" && linklib="$old_library" compile_deplibs="$dir/$linklib $compile_deplibs" finalize_deplibs="$dir/$linklib $finalize_deplibs" else compile_deplibs="-l$name -L$dir $compile_deplibs" finalize_deplibs="-l$name -L$dir $finalize_deplibs" fi elif test "$build_libtool_libs" = yes; then # Not a shared library if test "$deplibs_check_method" != pass_all; then # We're trying link a shared library against a static one # but the system doesn't support it. # Just print a warning and add the library to dependency_libs so # that the program can be linked against the static library. $ECHO $ECHO "*** Warning: This system can not link to static lib archive $lib." $ECHO "*** I have the capability to make that library automatically link in when" $ECHO "*** you link to this library. But I can only do this if you have a" $ECHO "*** shared version of the library, which you do not appear to have." if test "$module" = yes; then $ECHO "*** But as you try to build a module library, libtool will still create " $ECHO "*** a static module, that should work as long as the dlopening application" $ECHO "*** is linked with the -dlopen flag to resolve symbols at runtime." if test -z "$global_symbol_pipe"; then $ECHO $ECHO "*** However, this would only work if libtool was able to extract symbol" $ECHO "*** lists from a program, using \`nm' or equivalent, but libtool could" $ECHO "*** not find such a program. So, this module is probably useless." $ECHO "*** \`nm' from GNU binutils and a full rebuild may help." fi if test "$build_old_libs" = no; then build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi else deplibs="$dir/$old_library $deplibs" link_static=yes fi fi # link shared/static library? if test "$linkmode" = lib; then if test -n "$dependency_libs" && { test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes || test "$link_static" = yes; }; then # Extract -R from dependency_libs temp_deplibs= for libdir in $dependency_libs; do case $libdir in -R*) func_stripname '-R' '' "$libdir" temp_xrpath=$func_stripname_result case " $xrpath " in *" $temp_xrpath "*) ;; *) xrpath="$xrpath $temp_xrpath";; esac;; *) temp_deplibs="$temp_deplibs $libdir";; esac done dependency_libs="$temp_deplibs" fi newlib_search_path="$newlib_search_path $absdir" # Link against this library test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs" # ... and its dependency_libs tmp_libs= for deplib in $dependency_libs; do newdependency_libs="$deplib $newdependency_libs" if $opt_duplicate_deps ; then case "$tmp_libs " in *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; esac fi tmp_libs="$tmp_libs $deplib" done if test "$link_all_deplibs" != no; then # Add the search paths of all dependency libraries for deplib in $dependency_libs; do case $deplib in -L*) path="$deplib" ;; *.la) func_dirname "$deplib" "" "." dir="$func_dirname_result" # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;; *) absdir=`cd "$dir" && pwd` if test -z "$absdir"; then func_warning "cannot determine absolute directory name of \`$dir'" absdir="$dir" fi ;; esac if $GREP "^installed=no" $deplib > /dev/null; then case $host in *-*-darwin*) depdepl= eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` if test -n "$deplibrary_names" ; then for tmp in $deplibrary_names ; do depdepl=$tmp done if test -f "$absdir/$objdir/$depdepl" ; then depdepl="$absdir/$objdir/$depdepl" darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` if test -z "$darwin_install_name"; then darwin_install_name=`${OTOOL64} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` fi compiler_flags="$compiler_flags ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}" linker_flags="$linker_flags -dylib_file ${darwin_install_name}:${depdepl}" path= fi fi ;; *) path="-L$absdir/$objdir" ;; esac else eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` test -z "$libdir" && \ func_fatal_error "\`$deplib' is not a valid libtool archive" test "$absdir" != "$libdir" && \ func_warning "\`$deplib' seems to be moved" path="-L$absdir" fi ;; esac case " $deplibs " in *" $path "*) ;; *) deplibs="$path $deplibs" ;; esac done fi # link_all_deplibs != no fi # linkmode = lib done # for deplib in $libs if test "$pass" = link; then if test "$linkmode" = "prog"; then compile_deplibs="$new_inherited_linker_flags $compile_deplibs" finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" else compiler_flags="$compiler_flags "`$ECHO "X $new_inherited_linker_flags" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` fi fi dependency_libs="$newdependency_libs" if test "$pass" = dlpreopen; then # Link the dlpreopened libraries before other libraries for deplib in $save_deplibs; do deplibs="$deplib $deplibs" done fi if test "$pass" != dlopen; then if test "$pass" != conv; then # Make sure lib_search_path contains only unique directories. lib_search_path= for dir in $newlib_search_path; do case "$lib_search_path " in *" $dir "*) ;; *) lib_search_path="$lib_search_path $dir" ;; esac done newlib_search_path= fi if test "$linkmode,$pass" != "prog,link"; then vars="deplibs" else vars="compile_deplibs finalize_deplibs" fi for var in $vars dependency_libs; do # Add libraries to $var in reverse order eval tmp_libs=\"\$$var\" new_libs= for deplib in $tmp_libs; do # FIXME: Pedantically, this is the right thing to do, so # that some nasty dependency loop isn't accidentally # broken: #new_libs="$deplib $new_libs" # Pragmatically, this seems to cause very few problems in # practice: case $deplib in -L*) new_libs="$deplib $new_libs" ;; -R*) ;; *) # And here is the reason: when a library appears more # than once as an explicit dependence of a library, or # is implicitly linked in more than once by the # compiler, it is considered special, and multiple # occurrences thereof are not removed. Compare this # with having the same library being listed as a # dependency of multiple other libraries: in this case, # we know (pedantically, we assume) the library does not # need to be listed more than once, so we keep only the # last copy. This is not always right, but it is rare # enough that we require users that really mean to play # such unportable linking tricks to link the library # using -Wl,-lname, so that libtool does not consider it # for duplicate removal. case " $specialdeplibs " in *" $deplib "*) new_libs="$deplib $new_libs" ;; *) case " $new_libs " in *" $deplib "*) ;; *) new_libs="$deplib $new_libs" ;; esac ;; esac ;; esac done tmp_libs= for deplib in $new_libs; do case $deplib in -L*) case " $tmp_libs " in *" $deplib "*) ;; *) tmp_libs="$tmp_libs $deplib" ;; esac ;; *) tmp_libs="$tmp_libs $deplib" ;; esac done eval $var=\"$tmp_libs\" done # for var fi # Last step: remove runtime libs from dependency_libs # (they stay in deplibs) tmp_libs= for i in $dependency_libs ; do case " $predeps $postdeps $compiler_lib_search_path " in *" $i "*) i="" ;; esac if test -n "$i" ; then tmp_libs="$tmp_libs $i" fi done dependency_libs=$tmp_libs done # for pass if test "$linkmode" = prog; then dlfiles="$newdlfiles" fi if test "$linkmode" = prog || test "$linkmode" = lib; then dlprefiles="$newdlprefiles" fi case $linkmode in oldlib) if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then func_warning "\`-dlopen' is ignored for archives" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "\`-l' and \`-L' are ignored for archives" ;; esac test -n "$rpath" && \ func_warning "\`-rpath' is ignored for archives" test -n "$xrpath" && \ func_warning "\`-R' is ignored for archives" test -n "$vinfo" && \ func_warning "\`-version-info/-version-number' is ignored for archives" test -n "$release" && \ func_warning "\`-release' is ignored for archives" test -n "$export_symbols$export_symbols_regex" && \ func_warning "\`-export-symbols' is ignored for archives" # Now set the variables for building old libraries. build_libtool_libs=no oldlibs="$output" objs="$objs$old_deplibs" ;; lib) # Make sure we only generate libraries of the form `libNAME.la'. case $outputname in lib*) func_stripname 'lib' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" ;; *) test "$module" = no && \ func_fatal_help "libtool library \`$output' must begin with \`lib'" if test "$need_lib_prefix" != no; then # Add the "lib" prefix for modules if required func_stripname '' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" else func_stripname '' '.la' "$outputname" libname=$func_stripname_result fi ;; esac if test -n "$objs"; then if test "$deplibs_check_method" != pass_all; then func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs" else $ECHO $ECHO "*** Warning: Linking the shared library $output against the non-libtool" $ECHO "*** objects $objs is not portable!" libobjs="$libobjs $objs" fi fi test "$dlself" != no && \ func_warning "\`-dlopen self' is ignored for libtool libraries" set dummy $rpath shift test "$#" -gt 1 && \ func_warning "ignoring multiple \`-rpath's for a libtool library" install_libdir="$1" oldlibs= if test -z "$rpath"; then if test "$build_libtool_libs" = yes; then # Building a libtool convenience library. # Some compilers have problems with a `.al' extension so # convenience libraries should have the same extension an # archive normally would. oldlibs="$output_objdir/$libname.$libext $oldlibs" build_libtool_libs=convenience build_old_libs=yes fi test -n "$vinfo" && \ func_warning "\`-version-info/-version-number' is ignored for convenience libraries" test -n "$release" && \ func_warning "\`-release' is ignored for convenience libraries" else # Parse the version information argument. save_ifs="$IFS"; IFS=':' set dummy $vinfo 0 0 0 shift IFS="$save_ifs" test -n "$7" && \ func_fatal_help "too many parameters to \`-version-info'" # convert absolute version numbers to libtool ages # this retains compatibility with .la files and attempts # to make the code below a bit more comprehensible case $vinfo_number in yes) number_major="$1" number_minor="$2" number_revision="$3" # # There are really only two kinds -- those that # use the current revision as the major version # and those that subtract age and use age as # a minor version. But, then there is irix # which has an extra 1 added just for fun # case $version_type in darwin|linux|osf|windows|none) func_arith $number_major + $number_minor current=$func_arith_result age="$number_minor" revision="$number_revision" ;; freebsd-aout|freebsd-elf|sunos) current="$number_major" revision="$number_minor" age="0" ;; irix|nonstopux) func_arith $number_major + $number_minor current=$func_arith_result age="$number_minor" revision="$number_minor" lt_irix_increment=no ;; esac ;; no) current="$1" revision="$2" age="$3" ;; esac # Check that each of the things are valid numbers. case $current in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "CURRENT \`$current' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac case $revision in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "REVISION \`$revision' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac case $age in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "AGE \`$age' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac if test "$age" -gt "$current"; then func_error "AGE \`$age' is greater than the current interface number \`$current'" func_fatal_error "\`$vinfo' is not valid version information" fi # Calculate the version variables. major= versuffix= verstring= case $version_type in none) ;; darwin) # Like Linux, but with the current version available in # verstring for coding it into the library header func_arith $current - $age major=.$func_arith_result versuffix="$major.$age.$revision" # Darwin ld doesn't like 0 for these options... func_arith $current + 1 minor_current=$func_arith_result xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision" verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" ;; freebsd-aout) major=".$current" versuffix=".$current.$revision"; ;; freebsd-elf) major=".$current" versuffix=".$current" ;; irix | nonstopux) if test "X$lt_irix_increment" = "Xno"; then func_arith $current - $age else func_arith $current - $age + 1 fi major=$func_arith_result case $version_type in nonstopux) verstring_prefix=nonstopux ;; *) verstring_prefix=sgi ;; esac verstring="$verstring_prefix$major.$revision" # Add in all the interfaces that we are compatible with. loop=$revision while test "$loop" -ne 0; do func_arith $revision - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring="$verstring_prefix$major.$iface:$verstring" done # Before this point, $major must not contain `.'. major=.$major versuffix="$major.$revision" ;; linux) func_arith $current - $age major=.$func_arith_result versuffix="$major.$age.$revision" ;; osf) func_arith $current - $age major=.$func_arith_result versuffix=".$current.$age.$revision" verstring="$current.$age.$revision" # Add in all the interfaces that we are compatible with. loop=$age while test "$loop" -ne 0; do func_arith $current - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring="$verstring:${iface}.0" done # Make executables depend on our current version. verstring="$verstring:${current}.0" ;; qnx) major=".$current" versuffix=".$current" ;; sunos) major=".$current" versuffix=".$current.$revision" ;; windows) # Use '-' rather than '.', since we only want one # extension on DOS 8.3 filesystems. func_arith $current - $age major=$func_arith_result versuffix="-$major" ;; *) func_fatal_configuration "unknown library version type \`$version_type'" ;; esac # Clear the version info if we defaulted, and they specified a release. if test -z "$vinfo" && test -n "$release"; then major= case $version_type in darwin) # we can't check for "0.0" in archive_cmds due to quoting # problems, so we reset it completely verstring= ;; *) verstring="0.0" ;; esac if test "$need_version" = no; then versuffix= else versuffix=".0.0" fi fi # Remove version info from name if versioning should be avoided if test "$avoid_version" = yes && test "$need_version" = no; then major= versuffix= verstring="" fi # Check to see if the archive will have undefined symbols. if test "$allow_undefined" = yes; then if test "$allow_undefined_flag" = unsupported; then func_warning "undefined symbols not allowed in $host shared libraries" build_libtool_libs=no build_old_libs=yes fi else # Don't allow undefined symbols. allow_undefined_flag="$no_undefined_flag" fi fi func_generate_dlsyms "$libname" "$libname" "yes" libobjs="$libobjs $symfileobj" test "X$libobjs" = "X " && libobjs= if test "$mode" != relink; then # Remove our outputs, but don't remove object files since they # may have been created when compiling PIC objects. removelist= tempremovelist=`$ECHO "$output_objdir/*"` for p in $tempremovelist; do case $p in *.$objext | *.gcno) ;; $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*) if test "X$precious_files_regex" != "X"; then if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 then continue fi fi removelist="$removelist $p" ;; *) ;; esac done test -n "$removelist" && \ func_show_eval "${RM}r \$removelist" fi # Now set the variables for building old libraries. if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then oldlibs="$oldlibs $output_objdir/$libname.$libext" # Transform .lo files to .o files. oldobjs="$objs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}'$/d' -e "$lo2o" | $NL2SP` fi # Eliminate all temporary directories. #for path in $notinst_path; do # lib_search_path=`$ECHO "X$lib_search_path " | $Xsed -e "s% $path % %g"` # deplibs=`$ECHO "X$deplibs " | $Xsed -e "s% -L$path % %g"` # dependency_libs=`$ECHO "X$dependency_libs " | $Xsed -e "s% -L$path % %g"` #done if test -n "$xrpath"; then # If the user specified any rpath flags, then add them. temp_xrpath= for libdir in $xrpath; do temp_xrpath="$temp_xrpath -R$libdir" case "$finalize_rpath " in *" $libdir "*) ;; *) finalize_rpath="$finalize_rpath $libdir" ;; esac done if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then dependency_libs="$temp_xrpath $dependency_libs" fi fi # Make sure dlfiles contains only unique files that won't be dlpreopened old_dlfiles="$dlfiles" dlfiles= for lib in $old_dlfiles; do case " $dlprefiles $dlfiles " in *" $lib "*) ;; *) dlfiles="$dlfiles $lib" ;; esac done # Make sure dlprefiles contains only unique files old_dlprefiles="$dlprefiles" dlprefiles= for lib in $old_dlprefiles; do case "$dlprefiles " in *" $lib "*) ;; *) dlprefiles="$dlprefiles $lib" ;; esac done if test "$build_libtool_libs" = yes; then if test -n "$rpath"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc*) # these systems don't actually have a c library (as such)! ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C library is in the System framework deplibs="$deplibs System.ltframework" ;; *-*-netbsd*) # Don't link with libc until the a.out ld.so is fixed. ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work ;; *) # Add libc to deplibs on all other systems if necessary. if test "$build_libtool_need_lc" = "yes"; then deplibs="$deplibs -lc" fi ;; esac fi # Transform deplibs into only deplibs that can be linked in shared. name_save=$name libname_save=$libname release_save=$release versuffix_save=$versuffix major_save=$major # I'm not sure if I'm treating the release correctly. I think # release should show up in the -l (ie -lgmp5) so we don't want to # add it in twice. Is that correct? release="" versuffix="" major="" newdeplibs= droppeddeps=no case $deplibs_check_method in pass_all) # Don't check for shared/static. Everything works. # This might be a little naive. We might want to check # whether the library exists or not. But this is on # osf3 & osf4 and I'm not really sure... Just # implementing what was already the behavior. newdeplibs=$deplibs ;; test_compile) # This code stresses the "libraries are programs" paradigm to its # limits. Maybe even breaks it. We compile a program, linking it # against the deplibs as a proxy for the library. Then we can check # whether they linked in statically or dynamically with ldd. $opt_dry_run || $RM conftest.c cat > conftest.c <<EOF int main() { return 0; } EOF $opt_dry_run || $RM conftest if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then ldd_output=`ldd conftest` for i in $deplibs; do case $i in -l*) func_stripname -l '' "$i" name=$func_stripname_result if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $i "*) newdeplibs="$newdeplibs $i" i="" ;; esac fi if test -n "$i" ; then libname=`eval "\\$ECHO \"$libname_spec\""` deplib_matches=`eval "\\$ECHO \"$library_names_spec\""` set dummy $deplib_matches; shift deplib_match=$1 if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then newdeplibs="$newdeplibs $i" else droppeddeps=yes $ECHO $ECHO "*** Warning: dynamic linker does not accept needed library $i." $ECHO "*** I have the capability to make that library automatically link in when" $ECHO "*** you link to this library. But I can only do this if you have a" $ECHO "*** shared version of the library, which I believe you do not have" $ECHO "*** because a test_compile did reveal that the linker did not use it for" $ECHO "*** its dynamic dependency list that programs get resolved with at runtime." fi fi ;; *) newdeplibs="$newdeplibs $i" ;; esac done else # Error occurred in the first compile. Let's try to salvage # the situation: Compile a separate program for each library. for i in $deplibs; do case $i in -l*) func_stripname -l '' "$i" name=$func_stripname_result $opt_dry_run || $RM conftest if $LTCC $LTCFLAGS -o conftest conftest.c $i; then ldd_output=`ldd conftest` if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $i "*) newdeplibs="$newdeplibs $i" i="" ;; esac fi if test -n "$i" ; then libname=`eval "\\$ECHO \"$libname_spec\""` deplib_matches=`eval "\\$ECHO \"$library_names_spec\""` set dummy $deplib_matches; shift deplib_match=$1 if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then newdeplibs="$newdeplibs $i" else droppeddeps=yes $ECHO $ECHO "*** Warning: dynamic linker does not accept needed library $i." $ECHO "*** I have the capability to make that library automatically link in when" $ECHO "*** you link to this library. But I can only do this if you have a" $ECHO "*** shared version of the library, which you do not appear to have" $ECHO "*** because a test_compile did reveal that the linker did not use this one" $ECHO "*** as a dynamic dependency that programs can get resolved with at runtime." fi fi else droppeddeps=yes $ECHO $ECHO "*** Warning! Library $i is needed by this library but I was not able to" $ECHO "*** make it link in! You will probably need to install it or some" $ECHO "*** library that it depends on before this library will be fully" $ECHO "*** functional. Installing it before continuing would be even better." fi ;; *) newdeplibs="$newdeplibs $i" ;; esac done fi ;; file_magic*) set dummy $deplibs_check_method; shift file_magic_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` for a_deplib in $deplibs; do case $a_deplib in -l*) func_stripname -l '' "$a_deplib" name=$func_stripname_result if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $a_deplib "*) newdeplibs="$newdeplibs $a_deplib" a_deplib="" ;; esac fi if test -n "$a_deplib" ; then libname=`eval "\\$ECHO \"$libname_spec\""` for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do potential_libs=`ls $i/$libname[.-]* 2>/dev/null` for potent_lib in $potential_libs; do # Follow soft links. if ls -lLd "$potent_lib" 2>/dev/null | $GREP " -> " >/dev/null; then continue fi # The statement above tries to avoid entering an # endless loop below, in case of cyclic links. # We might still enter an endless loop, since a link # loop can be closed while we follow links, # but so what? potlib="$potent_lib" while test -h "$potlib" 2>/dev/null; do potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'` case $potliblink in [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";; *) potlib=`$ECHO "X$potlib" | $Xsed -e 's,[^/]*$,,'`"$potliblink";; esac done if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | $SED -e 10q | $EGREP "$file_magic_regex" > /dev/null; then newdeplibs="$newdeplibs $a_deplib" a_deplib="" break 2 fi done done fi if test -n "$a_deplib" ; then droppeddeps=yes $ECHO $ECHO "*** Warning: linker path does not have real file for library $a_deplib." $ECHO "*** I have the capability to make that library automatically link in when" $ECHO "*** you link to this library. But I can only do this if you have a" $ECHO "*** shared version of the library, which you do not appear to have" $ECHO "*** because I did check the linker path looking for a file starting" if test -z "$potlib" ; then $ECHO "*** with $libname but no candidates were found. (...for file magic test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a file magic. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. newdeplibs="$newdeplibs $a_deplib" ;; esac done # Gone through all deplibs. ;; match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` for a_deplib in $deplibs; do case $a_deplib in -l*) func_stripname -l '' "$a_deplib" name=$func_stripname_result if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $a_deplib "*) newdeplibs="$newdeplibs $a_deplib" a_deplib="" ;; esac fi if test -n "$a_deplib" ; then libname=`eval "\\$ECHO \"$libname_spec\""` for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do potential_libs=`ls $i/$libname[.-]* 2>/dev/null` for potent_lib in $potential_libs; do potlib="$potent_lib" # see symlink-check above in file_magic test if eval "\$ECHO \"X$potent_lib\"" 2>/dev/null | $Xsed -e 10q | \ $EGREP "$match_pattern_regex" > /dev/null; then newdeplibs="$newdeplibs $a_deplib" a_deplib="" break 2 fi done done fi if test -n "$a_deplib" ; then droppeddeps=yes $ECHO $ECHO "*** Warning: linker path does not have real file for library $a_deplib." $ECHO "*** I have the capability to make that library automatically link in when" $ECHO "*** you link to this library. But I can only do this if you have a" $ECHO "*** shared version of the library, which you do not appear to have" $ECHO "*** because I did check the linker path looking for a file starting" if test -z "$potlib" ; then $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a regex pattern. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. newdeplibs="$newdeplibs $a_deplib" ;; esac done # Gone through all deplibs. ;; none | unknown | *) newdeplibs="" tmp_deplibs=`$ECHO "X $deplibs" | $Xsed \ -e 's/ -lc$//' -e 's/ -[LR][^ ]*//g'` if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then for i in $predeps $postdeps ; do # can't use Xsed below, because $i might contain '/' tmp_deplibs=`$ECHO "X $tmp_deplibs" | $Xsed -e "s,$i,,"` done fi if $ECHO "X $tmp_deplibs" | $Xsed -e 's/[ ]//g' | $GREP . >/dev/null; then $ECHO if test "X$deplibs_check_method" = "Xnone"; then $ECHO "*** Warning: inter-library dependencies are not supported in this platform." else $ECHO "*** Warning: inter-library dependencies are not known to be supported." fi $ECHO "*** All declared inter-library dependencies are being dropped." droppeddeps=yes fi ;; esac versuffix=$versuffix_save major=$major_save release=$release_save libname=$libname_save name=$name_save case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library with the System framework newdeplibs=`$ECHO "X $newdeplibs" | $Xsed -e 's/ -lc / System.ltframework /'` ;; esac if test "$droppeddeps" = yes; then if test "$module" = yes; then $ECHO $ECHO "*** Warning: libtool could not satisfy all declared inter-library" $ECHO "*** dependencies of module $libname. Therefore, libtool will create" $ECHO "*** a static module, that should work as long as the dlopening" $ECHO "*** application is linked with the -dlopen flag." if test -z "$global_symbol_pipe"; then $ECHO $ECHO "*** However, this would only work if libtool was able to extract symbol" $ECHO "*** lists from a program, using \`nm' or equivalent, but libtool could" $ECHO "*** not find such a program. So, this module is probably useless." $ECHO "*** \`nm' from GNU binutils and a full rebuild may help." fi if test "$build_old_libs" = no; then oldlibs="$output_objdir/$libname.$libext" build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi else $ECHO "*** The inter-library dependencies that have been dropped here will be" $ECHO "*** automatically added whenever a program is linked with this library" $ECHO "*** or is declared to -dlopen it." if test "$allow_undefined" = no; then $ECHO $ECHO "*** Since this library must not contain undefined symbols," $ECHO "*** because either the platform does not support them or" $ECHO "*** it was explicitly requested with -no-undefined," $ECHO "*** libtool will only create a static version of it." if test "$build_old_libs" = no; then oldlibs="$output_objdir/$libname.$libext" build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi fi fi # Done checking deplibs! deplibs=$newdeplibs fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" case $host in *-*-darwin*) newdeplibs=`$ECHO "X $newdeplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` new_inherited_linker_flags=`$ECHO "X $new_inherited_linker_flags" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` deplibs=`$ECHO "X $deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $deplibs " in *" -L$path/$objdir "*) new_libs="$new_libs -L$path/$objdir" ;; esac ;; esac done for deplib in $deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) new_libs="$new_libs $deplib" ;; esac ;; *) new_libs="$new_libs $deplib" ;; esac done deplibs="$new_libs" # All the library-specific variables (install_libdir is set above). library_names= old_library= dlname= # Test again, we may have decided not to build it any more if test "$build_libtool_libs" = yes; then if test "$hardcode_into_libs" = yes; then # Hardcode the library paths hardcode_libdirs= dep_rpath= rpath="$finalize_rpath" test "$mode" != relink && rpath="$compile_rpath$rpath" for libdir in $rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" dep_rpath="$dep_rpath $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) perm_rpath="$perm_rpath $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" if test -n "$hardcode_libdir_flag_spec_ld"; then eval dep_rpath=\"$hardcode_libdir_flag_spec_ld\" else eval dep_rpath=\"$hardcode_libdir_flag_spec\" fi fi if test -n "$runpath_var" && test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do rpath="$rpath$dir:" done eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" fi test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" fi shlibpath="$finalize_shlibpath" test "$mode" != relink && shlibpath="$compile_shlibpath$shlibpath" if test -n "$shlibpath"; then eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" fi # Get the real and link names of the library. eval shared_ext=\"$shrext_cmds\" eval library_names=\"$library_names_spec\" set dummy $library_names shift realname="$1" shift if test -n "$soname_spec"; then eval soname=\"$soname_spec\" else soname="$realname" fi if test -z "$dlname"; then dlname=$soname fi lib="$output_objdir/$realname" linknames= for link do linknames="$linknames $link" done # Use standard objects if they are pic test -z "$pic_flag" && libobjs=`$ECHO "X$libobjs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` test "X$libobjs" = "X " && libobjs= delfiles= if test -n "$export_symbols" && test -n "$include_expsyms"; then $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" export_symbols="$output_objdir/$libname.uexp" delfiles="$delfiles $export_symbols" fi orig_export_symbols= case $host_os in cygwin* | mingw* | cegcc*) if test -n "$export_symbols" && test -z "$export_symbols_regex"; then # exporting using user supplied symfile if test "x`$SED 1q $export_symbols`" != xEXPORTS; then # and it's NOT already a .def file. Must figure out # which of the given symbols are data symbols and tag # them as such. So, trigger use of export_symbols_cmds. # export_symbols gets reassigned inside the "prepare # the list of exported symbols" if statement, so the # include_expsyms logic still works. orig_export_symbols="$export_symbols" export_symbols= always_export_symbols=yes fi fi ;; esac # Prepare the list of exported symbols if test -z "$export_symbols"; then if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then func_verbose "generating symbol list for \`$libname.la'" export_symbols="$output_objdir/$libname.exp" $opt_dry_run || $RM $export_symbols cmds=$export_symbols_cmds save_ifs="$IFS"; IFS='~' for cmd in $cmds; do IFS="$save_ifs" eval cmd=\"$cmd\" func_len " $cmd" len=$func_len_result if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then func_show_eval "$cmd" 'exit $?' skipped_export=false else # The command line is too long to execute in one step. func_verbose "using reloadable object file for export list..." skipped_export=: # Break out early, otherwise skipped_export may be # set to false by a later but shorter cmd. break fi done IFS="$save_ifs" if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi fi if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols="$export_symbols" test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" $opt_dry_run || eval '$ECHO "X$include_expsyms" | $Xsed | $SP2NL >> "$tmp_export_symbols"' fi if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter delfiles="$delfiles $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi tmp_deplibs= for test_deplib in $deplibs; do case " $convenience " in *" $test_deplib "*) ;; *) tmp_deplibs="$tmp_deplibs $test_deplib" ;; esac done deplibs="$tmp_deplibs" if test -n "$convenience"; then if test -n "$whole_archive_flag_spec" && test "$compiler_needs_object" = yes && test -z "$libobjs"; then # extract the archives, so we have objects to list. # TODO: could optimize this to just extract one archive. whole_archive_flag_spec= fi if test -n "$whole_archive_flag_spec"; then save_libobjs=$libobjs eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= else gentop="$output_objdir/${outputname}x" generated="$generated $gentop" func_extract_archives $gentop $convenience libobjs="$libobjs $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi fi if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then eval flag=\"$thread_safe_flag_spec\" linker_flags="$linker_flags $flag" fi # Make a backup of the uninstalled library when relinking if test "$mode" = relink; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? fi # Do each of the archive commands. if test "$module" = yes && test -n "$module_cmds" ; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then eval test_cmds=\"$module_expsym_cmds\" cmds=$module_expsym_cmds else eval test_cmds=\"$module_cmds\" cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then eval test_cmds=\"$archive_expsym_cmds\" cmds=$archive_expsym_cmds else eval test_cmds=\"$archive_cmds\" cmds=$archive_cmds fi fi if test "X$skipped_export" != "X:" && func_len " $test_cmds" && len=$func_len_result && test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then : else # The command line is too long to link in one step, link piecewise # or, if using GNU ld and skipped_export is not :, use a linker # script. # Save the value of $output and $libobjs because we want to # use them later. If we have whole_archive_flag_spec, we # want to use save_libobjs as it was before # whole_archive_flag_spec was expanded, because we can't # assume the linker understands whole_archive_flag_spec. # This may have to be revisited, in case too many # convenience libraries get linked in and end up exceeding # the spec. if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then save_libobjs=$libobjs fi save_output=$output output_la=`$ECHO "X$output" | $Xsed -e "$basename"` # Clear the reloadable object creation command queue and # initialize k to one. test_cmds= concat_cmds= objlist= last_robj= k=1 if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then output=${output_objdir}/${output_la}.lnkscript func_verbose "creating GNU ld script: $output" $ECHO 'INPUT (' > $output for obj in $save_libobjs do $ECHO "$obj" >> $output done $ECHO ')' >> $output delfiles="$delfiles $output" elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then output=${output_objdir}/${output_la}.lnk func_verbose "creating linker input file list: $output" : > $output set x $save_libobjs shift firstobj= if test "$compiler_needs_object" = yes; then firstobj="$1 " shift fi for obj do $ECHO "$obj" >> $output done delfiles="$delfiles $output" output=$firstobj\"$file_list_spec$output\" else if test -n "$save_libobjs"; then func_verbose "creating reloadable object files..." output=$output_objdir/$output_la-${k}.$objext eval test_cmds=\"$reload_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 # Loop over the list of objects to be linked. for obj in $save_libobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result if test "X$objlist" = X || test "$len" -lt "$max_cmd_len"; then func_append objlist " $obj" else # The command $test_cmds is almost too long, add a # command to the queue. if test "$k" -eq 1 ; then # The first file doesn't have a previous command to add. eval concat_cmds=\"$reload_cmds $objlist $last_robj\" else # All subsequent reloadable object files will link in # the last one created. eval concat_cmds=\"\$concat_cmds~$reload_cmds $objlist $last_robj~\$RM $last_robj\" fi last_robj=$output_objdir/$output_la-${k}.$objext func_arith $k + 1 k=$func_arith_result output=$output_objdir/$output_la-${k}.$objext objlist=$obj func_len " $last_robj" func_arith $len0 + $func_len_result len=$func_arith_result fi done # Handle the remaining objects by creating one last # reloadable object file. All subsequent reloadable object # files will link in the last one created. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\${concat_cmds}$reload_cmds $objlist $last_robj\" if test -n "$last_robj"; then eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\" fi delfiles="$delfiles $output" else output= fi if ${skipped_export-false}; then func_verbose "generating symbol list for \`$libname.la'" export_symbols="$output_objdir/$libname.exp" $opt_dry_run || $RM $export_symbols libobjs=$output # Append the command to create the export file. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" fi fi test -n "$save_libobjs" && func_verbose "creating a temporary reloadable object file: $output" # Loop through the commands generated above and execute them. save_ifs="$IFS"; IFS='~' for cmd in $concat_cmds; do IFS="$save_ifs" $opt_silent || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test "$mode" = relink; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS="$save_ifs" if test -n "$export_symbols_regex" && ${skipped_export-false}; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi if ${skipped_export-false}; then if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols="$export_symbols" test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" $opt_dry_run || eval '$ECHO "X$include_expsyms" | $Xsed | $SP2NL >> "$tmp_export_symbols"' fi if test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter delfiles="$delfiles $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi fi libobjs=$output # Restore the value of output. output=$save_output if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= fi # Expand the library linking commands again to reset the # value of $libobjs for piecewise linking. # Do each of the archive commands. if test "$module" = yes && test -n "$module_cmds" ; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then cmds=$module_expsym_cmds else cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then cmds=$archive_expsym_cmds else cmds=$archive_cmds fi fi fi if test -n "$delfiles"; then # Append the command to remove temporary files to $cmds. eval cmds=\"\$cmds~\$RM $delfiles\" fi # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop="$output_objdir/${outputname}x" generated="$generated $gentop" func_extract_archives $gentop $dlprefiles libobjs="$libobjs $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi save_ifs="$IFS"; IFS='~' for cmd in $cmds; do IFS="$save_ifs" eval cmd=\"$cmd\" $opt_silent || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test "$mode" = relink; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS="$save_ifs" # Restore the uninstalled library and exit if test "$mode" = relink; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? if test -n "$convenience"; then if test -z "$whole_archive_flag_spec"; then func_show_eval '${RM}r "$gentop"' fi fi exit $EXIT_SUCCESS fi # Create links to the real library. for linkname in $linknames; do if test "$realname" != "$linkname"; then func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' fi done # If -module or -export-dynamic was specified, set the dlname. if test "$module" = yes || test "$export_dynamic" = yes; then # On all known operating systems, these are identical. dlname="$soname" fi fi ;; obj) if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then func_warning "\`-dlopen' is ignored for objects" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "\`-l' and \`-L' are ignored for objects" ;; esac test -n "$rpath" && \ func_warning "\`-rpath' is ignored for objects" test -n "$xrpath" && \ func_warning "\`-R' is ignored for objects" test -n "$vinfo" && \ func_warning "\`-version-info' is ignored for objects" test -n "$release" && \ func_warning "\`-release' is ignored for objects" case $output in *.lo) test -n "$objs$old_deplibs" && \ func_fatal_error "cannot build library object \`$output' from non-libtool objects" libobj=$output func_lo2o "$libobj" obj=$func_lo2o_result ;; *) libobj= obj="$output" ;; esac # Delete the old objects. $opt_dry_run || $RM $obj $libobj # Objects from convenience libraries. This assumes # single-version convenience libraries. Whenever we create # different ones for PIC/non-PIC, this we'll have to duplicate # the extraction. reload_conv_objs= gentop= # reload_cmds runs $LD directly, so let us get rid of # -Wl from whole_archive_flag_spec and hope we can get by with # turning comma into space.. wl= if test -n "$convenience"; then if test -n "$whole_archive_flag_spec"; then eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" reload_conv_objs=$reload_objs\ `$ECHO "X$tmp_whole_archive_flags" | $Xsed -e 's|,| |g'` else gentop="$output_objdir/${obj}x" generated="$generated $gentop" func_extract_archives $gentop $convenience reload_conv_objs="$reload_objs $func_extract_archives_result" fi fi # Create the old-style object. reload_objs="$objs$old_deplibs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}$'/d' -e '/\.lib$/d' -e "$lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test output="$obj" func_execute_cmds "$reload_cmds" 'exit $?' # Exit if we aren't doing a library object file. if test -z "$libobj"; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS fi if test "$build_libtool_libs" != yes; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi # Create an invalid libtool object if no PIC, so that we don't # accidentally link it into a program. # $show "echo timestamp > $libobj" # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? exit $EXIT_SUCCESS fi if test -n "$pic_flag" || test "$pic_mode" != default; then # Only do commands if we really have different PIC objects. reload_objs="$libobjs $reload_conv_objs" output="$libobj" func_execute_cmds "$reload_cmds" 'exit $?' fi if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS ;; prog) case $host in *cygwin*) func_stripname '' '.exe' "$output" output=$func_stripname_result.exe;; esac test -n "$vinfo" && \ func_warning "\`-version-info' is ignored for programs" test -n "$release" && \ func_warning "\`-release' is ignored for programs" test "$preload" = yes \ && test "$dlopen_support" = unknown \ && test "$dlopen_self" = unknown \ && test "$dlopen_self_static" = unknown && \ func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support." case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library is the System framework compile_deplibs=`$ECHO "X $compile_deplibs" | $Xsed -e 's/ -lc / System.ltframework /'` finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e 's/ -lc / System.ltframework /'` ;; esac case $host in *-*-darwin*) # Don't allow lazy linking, it breaks C++ global constructors # But is supposedly fixed on 10.4 or later (yay!). if test "$tagname" = CXX ; then case ${MACOSX_DEPLOYMENT_TARGET-10.0} in 10.[0123]) compile_command="$compile_command ${wl}-bind_at_load" finalize_command="$finalize_command ${wl}-bind_at_load" ;; esac fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" compile_deplibs=`$ECHO "X $compile_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $compile_deplibs " in *" -L$path/$objdir "*) new_libs="$new_libs -L$path/$objdir" ;; esac ;; esac done for deplib in $compile_deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) new_libs="$new_libs $deplib" ;; esac ;; *) new_libs="$new_libs $deplib" ;; esac done compile_deplibs="$new_libs" compile_command="$compile_command $compile_deplibs" finalize_command="$finalize_command $finalize_deplibs" if test -n "$rpath$xrpath"; then # If the user specified any rpath flags, then add them. for libdir in $rpath $xrpath; do # This is the magic to use -rpath. case "$finalize_rpath " in *" $libdir "*) ;; *) finalize_rpath="$finalize_rpath $libdir" ;; esac done fi # Now hardcode the library paths rpath= hardcode_libdirs= for libdir in $compile_rpath $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" rpath="$rpath $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) perm_rpath="$perm_rpath $libdir" ;; esac fi case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'` case :$dllsearchpath: in *":$libdir:"*) ;; ::) dllsearchpath=$libdir;; *) dllsearchpath="$dllsearchpath:$libdir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) dllsearchpath="$dllsearchpath:$testbindir";; esac ;; esac done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval rpath=\" $hardcode_libdir_flag_spec\" fi compile_rpath="$rpath" rpath= hardcode_libdirs= for libdir in $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" rpath="$rpath $flag" fi elif test -n "$runpath_var"; then case "$finalize_perm_rpath " in *" $libdir "*) ;; *) finalize_perm_rpath="$finalize_perm_rpath $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval rpath=\" $hardcode_libdir_flag_spec\" fi finalize_rpath="$rpath" if test -n "$libobjs" && test "$build_old_libs" = yes; then # Transform all the library objects into standard objects. compile_command=`$ECHO "X$compile_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` finalize_command=`$ECHO "X$finalize_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` fi func_generate_dlsyms "$outputname" "@PROGRAM@" "no" # template prelinking step if test -n "$prelink_cmds"; then func_execute_cmds "$prelink_cmds" 'exit $?' fi wrappers_required=yes case $host in *cygwin* | *mingw* ) if test "$build_libtool_libs" != yes; then wrappers_required=no fi ;; *cegcc) # Disable wrappers for cegcc, we are cross compiling anyway. wrappers_required=no ;; *) if test "$need_relink" = no || test "$build_libtool_libs" != yes; then wrappers_required=no fi ;; esac if test "$wrappers_required" = no; then # Replace the output file specification. compile_command=`$ECHO "X$compile_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` link_command="$compile_command$compile_rpath" # We have no uninstalled library dependencies, so finalize right now. exit_status=0 func_show_eval "$link_command" 'exit_status=$?' # Delete the generated files. if test -f "$output_objdir/${outputname}S.${objext}"; then func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"' fi exit $exit_status fi if test -n "$compile_shlibpath$finalize_shlibpath"; then compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" fi if test -n "$finalize_shlibpath"; then finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" fi compile_var= finalize_var= if test -n "$runpath_var"; then if test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do rpath="$rpath$dir:" done compile_var="$runpath_var=\"$rpath\$$runpath_var\" " fi if test -n "$finalize_perm_rpath"; then # We should set the runpath_var. rpath= for dir in $finalize_perm_rpath; do rpath="$rpath$dir:" done finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " fi fi if test "$no_install" = yes; then # We don't need to create a wrapper script. link_command="$compile_var$compile_command$compile_rpath" # Replace the output file specification. link_command=`$ECHO "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` # Delete the old output file. $opt_dry_run || $RM $output # Link the executable and exit func_show_eval "$link_command" 'exit $?' exit $EXIT_SUCCESS fi if test "$hardcode_action" = relink; then # Fast installation is not supported link_command="$compile_var$compile_command$compile_rpath" relink_command="$finalize_var$finalize_command$finalize_rpath" func_warning "this platform does not like uninstalled shared libraries" func_warning "\`$output' will be relinked during installation" else if test "$fast_install" != no; then link_command="$finalize_var$compile_command$finalize_rpath" if test "$fast_install" = yes; then relink_command=`$ECHO "X$compile_var$compile_command$compile_rpath" | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g'` else # fast_install is set to needless relink_command= fi else link_command="$compile_var$compile_command$compile_rpath" relink_command="$finalize_var$finalize_command$finalize_rpath" fi fi # Replace the output file specification. link_command=`$ECHO "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` # Delete the old output files. $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname func_show_eval "$link_command" 'exit $?' # Now create the wrapper script. func_verbose "creating $output" # Quote the relink command for shipping. if test -n "$relink_command"; then # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done relink_command="(cd `pwd`; $relink_command)" relink_command=`$ECHO "X$relink_command" | $Xsed -e "$sed_quote_subst"` fi # Quote $ECHO for shipping. if test "X$ECHO" = "X$SHELL $progpath --fallback-echo"; then case $progpath in [\\/]* | [A-Za-z]:[\\/]*) qecho="$SHELL $progpath --fallback-echo";; *) qecho="$SHELL `pwd`/$progpath --fallback-echo";; esac qecho=`$ECHO "X$qecho" | $Xsed -e "$sed_quote_subst"` else qecho=`$ECHO "X$ECHO" | $Xsed -e "$sed_quote_subst"` fi # Only actually do things if not in dry run mode. $opt_dry_run || { # win32 will think the script is a binary if it has # a .exe suffix, so we strip it off here. case $output in *.exe) func_stripname '' '.exe' "$output" output=$func_stripname_result ;; esac # test for cygwin because mv fails w/o .exe extensions case $host in *cygwin*) exeext=.exe func_stripname '' '.exe' "$outputname" outputname=$func_stripname_result ;; *) exeext= ;; esac case $host in *cygwin* | *mingw* ) func_dirname_and_basename "$output" "" "." output_name=$func_basename_result output_path=$func_dirname_result cwrappersource="$output_path/$objdir/lt-$output_name.c" cwrapper="$output_path/$output_name.exe" $RM $cwrappersource $cwrapper trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 func_emit_cwrapperexe_src > $cwrappersource # The wrapper executable is built using the $host compiler, # because it contains $host paths and files. If cross- # compiling, it, like the target executable, must be # executed on the $host or under an emulation environment. $opt_dry_run || { $LTCC $LTCFLAGS -o $cwrapper $cwrappersource $STRIP $cwrapper } # Now, create the wrapper script for func_source use: func_ltwrapper_scriptname $cwrapper $RM $func_ltwrapper_scriptname_result trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 $opt_dry_run || { # note: this script will not be executed, so do not chmod. if test "x$build" = "x$host" ; then $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result else func_emit_wrapper no > $func_ltwrapper_scriptname_result fi } ;; * ) $RM $output trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 func_emit_wrapper no > $output chmod +x $output ;; esac } exit $EXIT_SUCCESS ;; esac # See if we need to build an old-fashioned archive. for oldlib in $oldlibs; do if test "$build_libtool_libs" = convenience; then oldobjs="$libobjs_save $symfileobj" addlibs="$convenience" build_libtool_libs=no else if test "$build_libtool_libs" = module; then oldobjs="$libobjs_save" build_libtool_libs=no else oldobjs="$old_deplibs $non_pic_objects" if test "$preload" = yes && test -f "$symfileobj"; then oldobjs="$oldobjs $symfileobj" fi fi addlibs="$old_convenience" fi if test -n "$addlibs"; then gentop="$output_objdir/${outputname}x" generated="$generated $gentop" func_extract_archives $gentop $addlibs oldobjs="$oldobjs $func_extract_archives_result" fi # Do each command in the archive commands. if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then cmds=$old_archive_from_new_cmds else # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop="$output_objdir/${outputname}x" generated="$generated $gentop" func_extract_archives $gentop $dlprefiles oldobjs="$oldobjs $func_extract_archives_result" fi # POSIX demands no paths to be encoded in archives. We have # to avoid creating archives with duplicate basenames if we # might have to extract them afterwards, e.g., when creating a # static archive out of a convenience library, or when linking # the entirety of a libtool archive into another (currently # not supported by libtool). if (for obj in $oldobjs do func_basename "$obj" $ECHO "$func_basename_result" done | sort | sort -uc >/dev/null 2>&1); then : else $ECHO "copying selected object files to avoid basename conflicts..." gentop="$output_objdir/${outputname}x" generated="$generated $gentop" func_mkdir_p "$gentop" save_oldobjs=$oldobjs oldobjs= counter=1 for obj in $save_oldobjs do func_basename "$obj" objbase="$func_basename_result" case " $oldobjs " in " ") oldobjs=$obj ;; *[\ /]"$objbase "*) while :; do # Make sure we don't pick an alternate name that also # overlaps. newobj=lt$counter-$objbase func_arith $counter + 1 counter=$func_arith_result case " $oldobjs " in *[\ /]"$newobj "*) ;; *) if test ! -f "$gentop/$newobj"; then break; fi ;; esac done func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" oldobjs="$oldobjs $gentop/$newobj" ;; *) oldobjs="$oldobjs $obj" ;; esac done fi eval cmds=\"$old_archive_cmds\" func_len " $cmds" len=$func_len_result if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then cmds=$old_archive_cmds else # the command line is too long to link in one step, link in parts func_verbose "using piecewise archive linking..." save_RANLIB=$RANLIB RANLIB=: objlist= concat_cmds= save_oldobjs=$oldobjs oldobjs= # Is there a better way of finding the last object in the list? for obj in $save_oldobjs do last_oldobj=$obj done eval test_cmds=\"$old_archive_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 for obj in $save_oldobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result func_append objlist " $obj" if test "$len" -lt "$max_cmd_len"; then : else # the above command should be used before it gets too long oldobjs=$objlist if test "$obj" = "$last_oldobj" ; then RANLIB=$save_RANLIB fi test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\" objlist= len=$len0 fi done RANLIB=$save_RANLIB oldobjs=$objlist if test "X$oldobjs" = "X" ; then eval cmds=\"\$concat_cmds\" else eval cmds=\"\$concat_cmds~\$old_archive_cmds\" fi fi fi func_execute_cmds "$cmds" 'exit $?' done test -n "$generated" && \ func_show_eval "${RM}r$generated" # Now create the libtool archive. case $output in *.la) old_library= test "$build_old_libs" = yes && old_library="$libname.$libext" func_verbose "creating $output" # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done # Quote the link command for shipping. relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" relink_command=`$ECHO "X$relink_command" | $Xsed -e "$sed_quote_subst"` if test "$hardcode_automatic" = yes ; then relink_command= fi # Only create the output if not a dry run. $opt_dry_run || { for installed in no yes; do if test "$installed" = yes; then if test -z "$install_libdir"; then break fi output="$output_objdir/$outputname"i # Replace all uninstalled libtool libraries with the installed ones newdependency_libs= for deplib in $dependency_libs; do case $deplib in *.la) func_basename "$deplib" name="$func_basename_result" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` test -z "$libdir" && \ func_fatal_error "\`$deplib' is not a valid libtool archive" newdependency_libs="$newdependency_libs $libdir/$name" ;; *) newdependency_libs="$newdependency_libs $deplib" ;; esac done dependency_libs="$newdependency_libs" newdlfiles= for lib in $dlfiles; do case $lib in *.la) func_basename "$lib" name="$func_basename_result" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "\`$lib' is not a valid libtool archive" newdlfiles="$newdlfiles $libdir/$name" ;; *) newdlfiles="$newdlfiles $lib" ;; esac done dlfiles="$newdlfiles" newdlprefiles= for lib in $dlprefiles; do case $lib in *.la) # Only pass preopened files to the pseudo-archive (for # eventual linking with the app. that links it) if we # didn't already link the preopened objects directly into # the library: func_basename "$lib" name="$func_basename_result" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "\`$lib' is not a valid libtool archive" newdlprefiles="$newdlprefiles $libdir/$name" ;; esac done dlprefiles="$newdlprefiles" else newdlfiles= for lib in $dlfiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; *) abs=`pwd`"/$lib" ;; esac newdlfiles="$newdlfiles $abs" done dlfiles="$newdlfiles" newdlprefiles= for lib in $dlprefiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; *) abs=`pwd`"/$lib" ;; esac newdlprefiles="$newdlprefiles $abs" done dlprefiles="$newdlprefiles" fi $RM $output # place dlname in correct position for cygwin tdlname=$dlname case $host,$output,$installed,$module,$dlname in *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) tdlname=../bin/$dlname ;; esac $ECHO > $output "\ # $outputname - a libtool library file # Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION # # Please DO NOT delete this file! # It is necessary for linking the library. # The name that we can dlopen(3). dlname='$tdlname' # Names of this library. library_names='$library_names' # The name of the static archive. old_library='$old_library' # Linker flags that can not go in dependency_libs. inherited_linker_flags='$new_inherited_linker_flags' # Libraries that this one depends upon. dependency_libs='$dependency_libs' # Names of additional weak libraries provided by this library weak_library_names='$weak_libs' # Version information for $libname. current=$current age=$age revision=$revision # Is this an already installed library? installed=$installed # Should we warn about portability when linking against -modules? shouldnotlink=$module # Files to dlopen/dlpreopen dlopen='$dlfiles' dlpreopen='$dlprefiles' # Directory that this library needs to be installed in: libdir='$install_libdir'" if test "$installed" = no && test "$need_relink" = yes; then $ECHO >> $output "\ relink_command=\"$relink_command\"" fi done } # Do a symbolic link so that the libtool archive can be found in # LD_LIBRARY_PATH before the program is installed. func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' ;; esac exit $EXIT_SUCCESS } { test "$mode" = link || test "$mode" = relink; } && func_mode_link ${1+"$@"} # func_mode_uninstall arg... func_mode_uninstall () { $opt_debug RM="$nonopt" files= rmforce= exit_status=0 # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic="$magic" for arg do case $arg in -f) RM="$RM $arg"; rmforce=yes ;; -*) RM="$RM $arg" ;; *) files="$files $arg" ;; esac done test -z "$RM" && \ func_fatal_help "you must specify an RM program" rmdirs= origobjdir="$objdir" for file in $files; do func_dirname "$file" "" "." dir="$func_dirname_result" if test "X$dir" = X.; then objdir="$origobjdir" else objdir="$dir/$origobjdir" fi func_basename "$file" name="$func_basename_result" test "$mode" = uninstall && objdir="$dir" # Remember objdir for removal later, being careful to avoid duplicates if test "$mode" = clean; then case " $rmdirs " in *" $objdir "*) ;; *) rmdirs="$rmdirs $objdir" ;; esac fi # Don't error if the file doesn't exist and rm -f was used. if { test -L "$file"; } >/dev/null 2>&1 || { test -h "$file"; } >/dev/null 2>&1 || test -f "$file"; then : elif test -d "$file"; then exit_status=1 continue elif test "$rmforce" = yes; then continue fi rmfiles="$file" case $name in *.la) # Possibly a libtool archive, so verify it. if func_lalib_p "$file"; then func_source $dir/$name # Delete the libtool libraries and symlinks. for n in $library_names; do rmfiles="$rmfiles $objdir/$n" done test -n "$old_library" && rmfiles="$rmfiles $objdir/$old_library" case "$mode" in clean) case " $library_names " in # " " in the beginning catches empty $dlname *" $dlname "*) ;; *) rmfiles="$rmfiles $objdir/$dlname" ;; esac test -n "$libdir" && rmfiles="$rmfiles $objdir/$name $objdir/${name}i" ;; uninstall) if test -n "$library_names"; then # Do each command in the postuninstall commands. func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' fi if test -n "$old_library"; then # Do each command in the old_postuninstall commands. func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' fi # FIXME: should reinstall the best remaining shared library. ;; esac fi ;; *.lo) # Possibly a libtool object, so verify it. if func_lalib_p "$file"; then # Read the .lo file func_source $dir/$name # Add PIC object to the list of files to remove. if test -n "$pic_object" && test "$pic_object" != none; then rmfiles="$rmfiles $dir/$pic_object" fi # Add non-PIC object to the list of files to remove. if test -n "$non_pic_object" && test "$non_pic_object" != none; then rmfiles="$rmfiles $dir/$non_pic_object" fi fi ;; *) if test "$mode" = clean ; then noexename=$name case $file in *.exe) func_stripname '' '.exe' "$file" file=$func_stripname_result func_stripname '' '.exe' "$name" noexename=$func_stripname_result # $file with .exe has already been added to rmfiles, # add $file without .exe rmfiles="$rmfiles $file" ;; esac # Do a test to see if this is a libtool program. if func_ltwrapper_p "$file"; then if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" relink_command= func_source $func_ltwrapper_scriptname_result rmfiles="$rmfiles $func_ltwrapper_scriptname_result" else relink_command= func_source $dir/$noexename fi # note $name still contains .exe if it was in $file originally # as does the version of $file that was added into $rmfiles rmfiles="$rmfiles $objdir/$name $objdir/${name}S.${objext}" if test "$fast_install" = yes && test -n "$relink_command"; then rmfiles="$rmfiles $objdir/lt-$name" fi if test "X$noexename" != "X$name" ; then rmfiles="$rmfiles $objdir/lt-${noexename}.c" fi fi fi ;; esac func_show_eval "$RM $rmfiles" 'exit_status=1' done objdir="$origobjdir" # Try to remove the ${objdir}s in the directories where we deleted files for dir in $rmdirs; do if test -d "$dir"; then func_show_eval "rmdir $dir >/dev/null 2>&1" fi done exit $exit_status } { test "$mode" = uninstall || test "$mode" = clean; } && func_mode_uninstall ${1+"$@"} test -z "$mode" && { help="$generic_help" func_fatal_help "you must specify a MODE" } test -z "$exec_cmd" && \ func_fatal_help "invalid operation mode \`$mode'" if test -n "$exec_cmd"; then eval exec "$exec_cmd" exit $EXIT_FAILURE fi exit $exit_status # The TAGs below are defined such that we never get into a situation # in which we disable both kinds of libraries. Given conflicting # choices, we go for a static library, that is the most portable, # since we can't tell whether shared libraries were disabled because # the user asked for that or because the platform doesn't support # them. This is particularly important on AIX, because we don't # support having both static and shared libraries enabled at the same # time on that platform, so we default to a shared-only configuration. # If a disable-shared tag is given, we'll fallback to a static-only # configuration. But we'll never go from static-only to shared-only. # ### BEGIN LIBTOOL TAG CONFIG: disable-shared build_libtool_libs=no build_old_libs=yes # ### END LIBTOOL TAG CONFIG: disable-shared # ### BEGIN LIBTOOL TAG CONFIG: disable-static build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` # ### END LIBTOOL TAG CONFIG: disable-static # Local Variables: # mode:shell-script # sh-indentation:2 # End: # vi:sw=2
YifuLiu/AliOS-Things
components/SDL2/src/image/libtool
Shell
apache-2.0
258,138
# Generated from ltmain.m4sh. # ltmain.sh (GNU libtool) 2.2.6 # Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996 # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007 2008 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, # or obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Usage: $progname [OPTION]... [MODE-ARG]... # # Provide generalized library-building support services. # # --config show all configuration variables # --debug enable verbose shell tracing # -n, --dry-run display commands without modifying any files # --features display basic configuration information and exit # --mode=MODE use operation mode MODE # --preserve-dup-deps don't remove duplicate dependency libraries # --quiet, --silent don't print informational messages # --tag=TAG use configuration variables from tag TAG # -v, --verbose print informational messages (default) # --version print version information # -h, --help print short or long help message # # MODE must be one of the following: # # clean remove files from the build directory # compile compile a source file into a libtool object # execute automatically set library path, then run a program # finish complete the installation of libtool libraries # install install libraries or executables # link create a library or an executable # uninstall remove libraries from an installed directory # # MODE-ARGS vary depending on the MODE. # Try `$progname --help --mode=MODE' for a more detailed description of MODE. # # When reporting a bug, please describe a test case to reproduce it and # include the following information: # # host-triplet: $host # shell: $SHELL # compiler: $LTCC # compiler flags: $LTCFLAGS # linker: $LD (gnu? $with_gnu_ld) # $progname: (GNU libtool) 2.2.6 # automake: $automake_version # autoconf: $autoconf_version # # Report bugs to <bug-libtool@gnu.org>. PROGRAM=ltmain.sh PACKAGE=libtool VERSION=2.2.6 TIMESTAMP="" package_revision=1.3012 # Be Bourne compatible if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # NLS nuisances: We save the old values to restore during execute mode. # Only set LANG and LC_ALL to C if already set. # These must not be set unconditionally because not all systems understand # e.g. LANG=C (notably SCO). lt_user_locale= lt_safe_locale= for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${$lt_var+set}\" = set; then save_$lt_var=\$$lt_var $lt_var=C export $lt_var lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\" lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\" fi" done $lt_unset CDPATH : ${CP="cp -f"} : ${ECHO="echo"} : ${EGREP="/usr/bin/grep -E"} : ${FGREP="/usr/bin/grep -F"} : ${GREP="/usr/bin/grep"} : ${LN_S="ln -s"} : ${MAKE="make"} : ${MKDIR="mkdir"} : ${MV="mv -f"} : ${RM="rm -f"} : ${SED="/opt/local/bin/gsed"} : ${SHELL="${CONFIG_SHELL-/bin/sh}"} : ${Xsed="$SED -e 1s/^X//"} # Global variables: EXIT_SUCCESS=0 EXIT_FAILURE=1 EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. exit_status=$EXIT_SUCCESS # Make sure IFS has a sensible default lt_nl=' ' IFS=" $lt_nl" dirname="s,/[^/]*$,," basename="s,^.*/,," # func_dirname_and_basename file append nondir_replacement # perform func_basename and func_dirname in a single function # call: # dirname: Compute the dirname of FILE. If nonempty, # add APPEND to the result, otherwise set result # to NONDIR_REPLACEMENT. # value returned in "$func_dirname_result" # basename: Compute filename of FILE. # value retuned in "$func_basename_result" # Implementation must be kept synchronized with func_dirname # and func_basename. For efficiency, we do not delegate to # those functions but instead duplicate the functionality here. func_dirname_and_basename () { # Extract subdirectory from the argument. func_dirname_result=`$ECHO "X${1}" | $Xsed -e "$dirname"` if test "X$func_dirname_result" = "X${1}"; then func_dirname_result="${3}" else func_dirname_result="$func_dirname_result${2}" fi func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"` } # Generated shell functions inserted here. # Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh # is ksh but when the shell is invoked as "sh" and the current value of # the _XPG environment variable is not equal to 1 (one), the special # positional parameter $0, within a function call, is the name of the # function. progpath="$0" # The name of this program: # In the unlikely event $progname began with a '-', it would play havoc with # func_echo (imagine progname=-n), so we prepend ./ in that case: func_dirname_and_basename "$progpath" progname=$func_basename_result case $progname in -*) progname=./$progname ;; esac # Make sure we have an absolute path for reexecution: case $progpath in [\\/]*|[A-Za-z]:\\*) ;; *[\\/]*) progdir=$func_dirname_result progdir=`cd "$progdir" && pwd` progpath="$progdir/$progname" ;; *) save_IFS="$IFS" IFS=: for progdir in $PATH; do IFS="$save_IFS" test -x "$progdir/$progname" && break done IFS="$save_IFS" test -n "$progdir" || progdir=`pwd` progpath="$progdir/$progname" ;; esac # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. Xsed="${SED}"' -e 1s/^X//' sed_quote_subst='s/\([`"$\\]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\(["`\\]\)/\\\1/g' # Re-`\' parameter expansions in output of double_quote_subst that were # `\'-ed in input to the same. If an odd number of `\' preceded a '$' # in input to double_quote_subst, that '$' was protected from expansion. # Since each input `\' is now two `\'s, look for any number of runs of # four `\'s followed by two `\'s and then a '$'. `\' that '$'. bs='\\' bs2='\\\\' bs4='\\\\\\\\' dollar='\$' sed_double_backslash="\ s/$bs4/&\\ /g s/^$bs2$dollar/$bs&/ s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g s/\n//g" # Standard options: opt_dry_run=false opt_help=false opt_quiet=false opt_verbose=false opt_warning=: # func_echo arg... # Echo program name prefixed message, along with the current mode # name if it has been set yet. func_echo () { $ECHO "$progname${mode+: }$mode: $*" } # func_verbose arg... # Echo program name prefixed message in verbose mode only. func_verbose () { $opt_verbose && func_echo ${1+"$@"} # A bug in bash halts the script if the last line of a function # fails when set -e is in force, so we need another command to # work around that: : } # func_error arg... # Echo program name prefixed message to standard error. func_error () { $ECHO "$progname${mode+: }$mode: "${1+"$@"} 1>&2 } # func_warning arg... # Echo program name prefixed warning message to standard error. func_warning () { $opt_warning && $ECHO "$progname${mode+: }$mode: warning: "${1+"$@"} 1>&2 # bash bug again: : } # func_fatal_error arg... # Echo program name prefixed message to standard error, and exit. func_fatal_error () { func_error ${1+"$@"} exit $EXIT_FAILURE } # func_fatal_help arg... # Echo program name prefixed message to standard error, followed by # a help hint, and exit. func_fatal_help () { func_error ${1+"$@"} func_fatal_error "$help" } help="Try \`$progname --help' for more information." ## default # func_grep expression filename # Check whether EXPRESSION matches any line of FILENAME, without output. func_grep () { $GREP "$1" "$2" >/dev/null 2>&1 } # func_mkdir_p directory-path # Make sure the entire path to DIRECTORY-PATH is available. func_mkdir_p () { my_directory_path="$1" my_dir_list= if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then # Protect directory names starting with `-' case $my_directory_path in -*) my_directory_path="./$my_directory_path" ;; esac # While some portion of DIR does not yet exist... while test ! -d "$my_directory_path"; do # ...make a list in topmost first order. Use a colon delimited # list incase some portion of path contains whitespace. my_dir_list="$my_directory_path:$my_dir_list" # If the last portion added has no slash in it, the list is done case $my_directory_path in */*) ;; *) break ;; esac # ...otherwise throw away the child directory and loop my_directory_path=`$ECHO "X$my_directory_path" | $Xsed -e "$dirname"` done my_dir_list=`$ECHO "X$my_dir_list" | $Xsed -e 's,:*$,,'` save_mkdir_p_IFS="$IFS"; IFS=':' for my_dir in $my_dir_list; do IFS="$save_mkdir_p_IFS" # mkdir can fail with a `File exist' error if two processes # try to create one of the directories concurrently. Don't # stop in that case! $MKDIR "$my_dir" 2>/dev/null || : done IFS="$save_mkdir_p_IFS" # Bail out if we (or some other process) failed to create a directory. test -d "$my_directory_path" || \ func_fatal_error "Failed to create \`$1'" fi } # func_mktempdir [string] # Make a temporary directory that won't clash with other running # libtool processes, and avoids race conditions if possible. If # given, STRING is the basename for that directory. func_mktempdir () { my_template="${TMPDIR-/tmp}/${1-$progname}" if test "$opt_dry_run" = ":"; then # Return a directory name, but don't create it in dry-run mode my_tmpdir="${my_template}-$$" else # If mktemp works, use that first and foremost my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null` if test ! -d "$my_tmpdir"; then # Failing that, at least try and use $RANDOM to avoid a race my_tmpdir="${my_template}-${RANDOM-0}$$" save_mktempdir_umask=`umask` umask 0077 $MKDIR "$my_tmpdir" umask $save_mktempdir_umask fi # If we're not in dry-run mode, bomb out on failure test -d "$my_tmpdir" || \ func_fatal_error "cannot create temporary directory \`$my_tmpdir'" fi $ECHO "X$my_tmpdir" | $Xsed } # func_quote_for_eval arg # Aesthetically quote ARG to be evaled later. # This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT # is double-quoted, suitable for a subsequent eval, whereas # FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters # which are still active within double quotes backslashified. func_quote_for_eval () { case $1 in *[\\\`\"\$]*) func_quote_for_eval_unquoted_result=`$ECHO "X$1" | $Xsed -e "$sed_quote_subst"` ;; *) func_quote_for_eval_unquoted_result="$1" ;; esac case $func_quote_for_eval_unquoted_result in # Double-quote args containing shell metacharacters to delay # word splitting, command substitution and and variable # expansion for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\"" ;; *) func_quote_for_eval_result="$func_quote_for_eval_unquoted_result" esac } # func_quote_for_expand arg # Aesthetically quote ARG to be evaled later; same as above, # but do not quote variable references. func_quote_for_expand () { case $1 in *[\\\`\"]*) my_arg=`$ECHO "X$1" | $Xsed \ -e "$double_quote_subst" -e "$sed_double_backslash"` ;; *) my_arg="$1" ;; esac case $my_arg in # Double-quote args containing shell metacharacters to delay # word splitting and command substitution for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") my_arg="\"$my_arg\"" ;; esac func_quote_for_expand_result="$my_arg" } # func_show_eval cmd [fail_exp] # Unless opt_silent is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. func_show_eval () { my_cmd="$1" my_fail_exp="${2-:}" ${opt_silent-false} || { func_quote_for_expand "$my_cmd" eval "func_echo $func_quote_for_expand_result" } if ${opt_dry_run-false}; then :; else eval "$my_cmd" my_status=$? if test "$my_status" -eq 0; then :; else eval "(exit $my_status); $my_fail_exp" fi fi } # func_show_eval_locale cmd [fail_exp] # Unless opt_silent is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. Use the saved locale for evaluation. func_show_eval_locale () { my_cmd="$1" my_fail_exp="${2-:}" ${opt_silent-false} || { func_quote_for_expand "$my_cmd" eval "func_echo $func_quote_for_expand_result" } if ${opt_dry_run-false}; then :; else eval "$lt_user_locale $my_cmd" my_status=$? eval "$lt_safe_locale" if test "$my_status" -eq 0; then :; else eval "(exit $my_status); $my_fail_exp" fi fi } # func_version # Echo version message to standard output and exit. func_version () { $SED -n '/^# '$PROGRAM' (GNU /,/# warranty; / { s/^# // s/^# *$// s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/ p }' < "$progpath" exit $? } # func_usage # Echo short help message to standard output and exit. func_usage () { $SED -n '/^# Usage:/,/# -h/ { s/^# // s/^# *$// s/\$progname/'$progname'/ p }' < "$progpath" $ECHO $ECHO "run \`$progname --help | more' for full usage" exit $? } # func_help # Echo long help message to standard output and exit. func_help () { $SED -n '/^# Usage:/,/# Report bugs to/ { s/^# // s/^# *$// s*\$progname*'$progname'* s*\$host*'"$host"'* s*\$SHELL*'"$SHELL"'* s*\$LTCC*'"$LTCC"'* s*\$LTCFLAGS*'"$LTCFLAGS"'* s*\$LD*'"$LD"'* s/\$with_gnu_ld/'"$with_gnu_ld"'/ s/\$automake_version/'"`(automake --version) 2>/dev/null |$SED 1q`"'/ s/\$autoconf_version/'"`(autoconf --version) 2>/dev/null |$SED 1q`"'/ p }' < "$progpath" exit $? } # func_missing_arg argname # Echo program name prefixed message to standard error and set global # exit_cmd. func_missing_arg () { func_error "missing argument for $1" exit_cmd=exit } exit_cmd=: # Check that we have a working $ECHO. if test "X$1" = X--no-reexec; then # Discard the --no-reexec flag, and continue. shift elif test "X$1" = X--fallback-echo; then # Avoid inline document here, it may be left over : elif test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t'; then # Yippee, $ECHO works! : else # Restart under the correct shell, and then maybe $ECHO will work. exec $SHELL "$progpath" --no-reexec ${1+"$@"} fi if test "X$1" = X--fallback-echo; then # used as fallback echo shift cat <<EOF $* EOF exit $EXIT_SUCCESS fi magic="%%%MAGIC variable%%%" magic_exe="%%%MAGIC EXE variable%%%" # Global variables. # $mode is unset nonopt= execute_dlfiles= preserve_args= lo2o="s/\\.lo\$/.${objext}/" o2lo="s/\\.${objext}\$/.lo/" extracted_archives= extracted_serial=0 opt_dry_run=false opt_duplicate_deps=false opt_silent=false opt_debug=: # If this variable is set in any of the actions, the command in it # will be execed at the end. This prevents here-documents from being # left over by shells. exec_cmd= # func_fatal_configuration arg... # Echo program name prefixed message to standard error, followed by # a configuration failure hint, and exit. func_fatal_configuration () { func_error ${1+"$@"} func_error "See the $PACKAGE documentation for more information." func_fatal_error "Fatal configuration error." } # func_config # Display the configuration for all the tags in this script. func_config () { re_begincf='^# ### BEGIN LIBTOOL' re_endcf='^# ### END LIBTOOL' # Default configuration. $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath" # Now print the configurations for the tags. for tagname in $taglist; do $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath" done exit $? } # func_features # Display the features supported by this script. func_features () { $ECHO "host: $host" if test "$build_libtool_libs" = yes; then $ECHO "enable shared libraries" else $ECHO "disable shared libraries" fi if test "$build_old_libs" = yes; then $ECHO "enable static libraries" else $ECHO "disable static libraries" fi exit $? } # func_enable_tag tagname # Verify that TAGNAME is valid, and either flag an error and exit, or # enable the TAGNAME tag. We also add TAGNAME to the global $taglist # variable here. func_enable_tag () { # Global variable: tagname="$1" re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$" re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$" sed_extractcf="/$re_begincf/,/$re_endcf/p" # Validate tagname. case $tagname in *[!-_A-Za-z0-9,/]*) func_fatal_error "invalid tag name: $tagname" ;; esac # Don't test for the "default" C tag, as we know it's # there but not specially marked. case $tagname in CC) ;; *) if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then taglist="$taglist $tagname" # Evaluate the configuration. Be careful to quote the path # and the sed script, to avoid splitting on whitespace, but # also don't use non-portable quotes within backquotes within # quotes we have to do it in 2 steps: extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` eval "$extractedcf" else func_error "ignoring unknown tag $tagname" fi ;; esac } # Parse options once, thoroughly. This comes as soon as possible in # the script to make things like `libtool --version' happen quickly. { # Shorthand for --mode=foo, only valid as the first argument case $1 in clean|clea|cle|cl) shift; set dummy --mode clean ${1+"$@"}; shift ;; compile|compil|compi|comp|com|co|c) shift; set dummy --mode compile ${1+"$@"}; shift ;; execute|execut|execu|exec|exe|ex|e) shift; set dummy --mode execute ${1+"$@"}; shift ;; finish|finis|fini|fin|fi|f) shift; set dummy --mode finish ${1+"$@"}; shift ;; install|instal|insta|inst|ins|in|i) shift; set dummy --mode install ${1+"$@"}; shift ;; link|lin|li|l) shift; set dummy --mode link ${1+"$@"}; shift ;; uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) shift; set dummy --mode uninstall ${1+"$@"}; shift ;; esac # Parse non-mode specific arguments: while test "$#" -gt 0; do opt="$1" shift case $opt in --config) func_config ;; --debug) preserve_args="$preserve_args $opt" func_echo "enabling shell trace mode" opt_debug='set -x' $opt_debug ;; -dlopen) test "$#" -eq 0 && func_missing_arg "$opt" && break execute_dlfiles="$execute_dlfiles $1" shift ;; --dry-run | -n) opt_dry_run=: ;; --features) func_features ;; --finish) mode="finish" ;; --mode) test "$#" -eq 0 && func_missing_arg "$opt" && break case $1 in # Valid mode arguments: clean) ;; compile) ;; execute) ;; finish) ;; install) ;; link) ;; relink) ;; uninstall) ;; # Catch anything else as an error *) func_error "invalid argument for $opt" exit_cmd=exit break ;; esac mode="$1" shift ;; --preserve-dup-deps) opt_duplicate_deps=: ;; --quiet|--silent) preserve_args="$preserve_args $opt" opt_silent=: ;; --verbose| -v) preserve_args="$preserve_args $opt" opt_silent=false ;; --tag) test "$#" -eq 0 && func_missing_arg "$opt" && break preserve_args="$preserve_args $opt $1" func_enable_tag "$1" # tagname is set here shift ;; # Separate optargs to long options: -dlopen=*|--mode=*|--tag=*) func_opt_split "$opt" set dummy "$func_opt_split_opt" "$func_opt_split_arg" ${1+"$@"} shift ;; -\?|-h) func_usage ;; --help) opt_help=: ;; --version) func_version ;; -*) func_fatal_help "unrecognized option \`$opt'" ;; *) nonopt="$opt" break ;; esac done case $host in *cygwin* | *mingw* | *pw32* | *cegcc*) # don't eliminate duplications in $postdeps and $predeps opt_duplicate_compiler_generated_deps=: ;; *) opt_duplicate_compiler_generated_deps=$opt_duplicate_deps ;; esac # Having warned about all mis-specified options, bail out if # anything was wrong. $exit_cmd $EXIT_FAILURE } # func_check_version_match # Ensure that we are using m4 macros, and libtool script from the same # release of libtool. func_check_version_match () { if test "$package_revision" != "$macro_revision"; then if test "$VERSION" != "$macro_version"; then if test -z "$macro_version"; then cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from an older release. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from $PACKAGE $macro_version. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF fi else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, $progname: but the definition of this LT_INIT comes from revision $macro_revision. $progname: You should recreate aclocal.m4 with macros from revision $package_revision $progname: of $PACKAGE $VERSION and run autoconf again. _LT_EOF fi exit $EXIT_MISMATCH fi } ## ----------- ## ## Main. ## ## ----------- ## $opt_help || { # Sanity checks first: func_check_version_match if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then func_fatal_configuration "not configured to build any kind of library" fi test -z "$mode" && func_fatal_error "error: you must specify a MODE." # Darwin sucks eval std_shrext=\"$shrext_cmds\" # Only execute mode is allowed to have -dlopen flags. if test -n "$execute_dlfiles" && test "$mode" != execute; then func_error "unrecognized option \`-dlopen'" $ECHO "$help" 1>&2 exit $EXIT_FAILURE fi # Change the help message to a mode-specific one. generic_help="$help" help="Try \`$progname --help --mode=$mode' for more information." } # func_lalib_p file # True iff FILE is a libtool `.la' library or `.lo' object file. # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_lalib_p () { test -f "$1" && $SED -e 4q "$1" 2>/dev/null \ | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 } # func_lalib_unsafe_p file # True iff FILE is a libtool `.la' library or `.lo' object file. # This function implements the same check as func_lalib_p without # resorting to external programs. To this end, it redirects stdin and # closes it afterwards, without saving the original file descriptor. # As a safety measure, use it only where a negative result would be # fatal anyway. Works if `file' does not exist. func_lalib_unsafe_p () { lalib_p=no if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then for lalib_p_l in 1 2 3 4 do read lalib_p_line case "$lalib_p_line" in \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; esac done exec 0<&5 5<&- fi test "$lalib_p" = yes } # func_ltwrapper_script_p file # True iff FILE is a libtool wrapper script # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_script_p () { func_lalib_p "$1" } # func_ltwrapper_executable_p file # True iff FILE is a libtool wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_executable_p () { func_ltwrapper_exec_suffix= case $1 in *.exe) ;; *) func_ltwrapper_exec_suffix=.exe ;; esac $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 } # func_ltwrapper_scriptname file # Assumes file is an ltwrapper_executable # uses $file to determine the appropriate filename for a # temporary ltwrapper_script. func_ltwrapper_scriptname () { func_ltwrapper_scriptname_result="" if func_ltwrapper_executable_p "$1"; then func_dirname_and_basename "$1" "" "." func_stripname '' '.exe' "$func_basename_result" func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper" fi } # func_ltwrapper_p file # True iff FILE is a libtool wrapper script or wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_p () { func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" } # func_execute_cmds commands fail_cmd # Execute tilde-delimited COMMANDS. # If FAIL_CMD is given, eval that upon failure. # FAIL_CMD may read-access the current command in variable CMD! func_execute_cmds () { $opt_debug save_ifs=$IFS; IFS='~' for cmd in $1; do IFS=$save_ifs eval cmd=\"$cmd\" func_show_eval "$cmd" "${2-:}" done IFS=$save_ifs } # func_source file # Source FILE, adding directory component if necessary. # Note that it is not necessary on cygwin/mingw to append a dot to # FILE even if both FILE and FILE.exe exist: automatic-append-.exe # behavior happens only for exec(3), not for open(2)! Also, sourcing # `FILE.' does not work on cygwin managed mounts. func_source () { $opt_debug case $1 in */* | *\\*) . "$1" ;; *) . "./$1" ;; esac } # func_infer_tag arg # Infer tagged configuration to use if any are available and # if one wasn't chosen via the "--tag" command line option. # Only attempt this if the compiler in the base compile # command doesn't match the default compiler. # arg is usually of the form 'gcc ...' func_infer_tag () { $opt_debug if test -n "$available_tags" && test -z "$tagname"; then CC_quoted= for arg in $CC; do func_quote_for_eval "$arg" CC_quoted="$CC_quoted $func_quote_for_eval_result" done case $@ in # Blanks in the command may have been stripped by the calling shell, # but not from the CC environment variable when configure was run. " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*) ;; # Blanks at the start of $base_compile will cause this to fail # if we don't check for them as well. *) for z in $available_tags; do if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then # Evaluate the configuration. eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" CC_quoted= for arg in $CC; do # Double-quote args containing other shell metacharacters. func_quote_for_eval "$arg" CC_quoted="$CC_quoted $func_quote_for_eval_result" done case "$@ " in " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*) # The compiler in the base compile command matches # the one in the tagged configuration. # Assume this is the tagged configuration we want. tagname=$z break ;; esac fi done # If $tagname still isn't set, then no tagged configuration # was found and let the user know that the "--tag" command # line option must be used. if test -z "$tagname"; then func_echo "unable to infer tagged configuration" func_fatal_error "specify a tag with \`--tag'" # else # func_verbose "using $tagname tagged configuration" fi ;; esac fi } # func_write_libtool_object output_name pic_name nonpic_name # Create a libtool object file (analogous to a ".la" file), # but don't create it if we're doing a dry run. func_write_libtool_object () { write_libobj=${1} if test "$build_libtool_libs" = yes; then write_lobj=\'${2}\' else write_lobj=none fi if test "$build_old_libs" = yes; then write_oldobj=\'${3}\' else write_oldobj=none fi $opt_dry_run || { cat >${write_libobj}T <<EOF # $write_libobj - a libtool object file # Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION # # Please DO NOT delete this file! # It is necessary for linking the library. # Name of the PIC object. pic_object=$write_lobj # Name of the non-PIC object non_pic_object=$write_oldobj EOF $MV "${write_libobj}T" "${write_libobj}" } } # func_mode_compile arg... func_mode_compile () { $opt_debug # Get the compilation command and the source file. base_compile= srcfile="$nonopt" # always keep a non-empty value in "srcfile" suppress_opt=yes suppress_output= arg_mode=normal libobj= later= pie_flag= for arg do case $arg_mode in arg ) # do not "continue". Instead, add this to base_compile lastarg="$arg" arg_mode=normal ;; target ) libobj="$arg" arg_mode=normal continue ;; normal ) # Accept any command-line options. case $arg in -o) test -n "$libobj" && \ func_fatal_error "you cannot specify \`-o' more than once" arg_mode=target continue ;; -pie | -fpie | -fPIE) pie_flag="$pie_flag $arg" continue ;; -shared | -static | -prefer-pic | -prefer-non-pic) later="$later $arg" continue ;; -no-suppress) suppress_opt=no continue ;; -Xcompiler) arg_mode=arg # the next one goes into the "base_compile" arg list continue # The current "srcfile" will either be retained or ;; # replaced later. I would guess that would be a bug. -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result lastarg= save_ifs="$IFS"; IFS=',' for arg in $args; do IFS="$save_ifs" func_quote_for_eval "$arg" lastarg="$lastarg $func_quote_for_eval_result" done IFS="$save_ifs" func_stripname ' ' '' "$lastarg" lastarg=$func_stripname_result # Add the arguments to base_compile. base_compile="$base_compile $lastarg" continue ;; *) # Accept the current argument as the source file. # The previous "srcfile" becomes the current argument. # lastarg="$srcfile" srcfile="$arg" ;; esac # case $arg ;; esac # case $arg_mode # Aesthetically quote the previous argument. func_quote_for_eval "$lastarg" base_compile="$base_compile $func_quote_for_eval_result" done # for arg case $arg_mode in arg) func_fatal_error "you must specify an argument for -Xcompile" ;; target) func_fatal_error "you must specify a target with \`-o'" ;; *) # Get the name of the library object. test -z "$libobj" && { func_basename "$srcfile" libobj="$func_basename_result" } ;; esac # Recognize several different file suffixes. # If the user specifies -o file.o, it is replaced with file.lo case $libobj in *.[cCFSifmso] | \ *.ada | *.adb | *.ads | *.asm | \ *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \ *.[fF][09]? | *.for | *.java | *.obj | *.sx) func_xform "$libobj" libobj=$func_xform_result ;; esac case $libobj in *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;; *) func_fatal_error "cannot determine name of library object from \`$libobj'" ;; esac func_infer_tag $base_compile for arg in $later; do case $arg in -shared) test "$build_libtool_libs" != yes && \ func_fatal_configuration "can not build a shared library" build_old_libs=no continue ;; -static) build_libtool_libs=no build_old_libs=yes continue ;; -prefer-pic) pic_mode=yes continue ;; -prefer-non-pic) pic_mode=no continue ;; esac done func_quote_for_eval "$libobj" test "X$libobj" != "X$func_quote_for_eval_result" \ && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"' &()|`$[]' \ && func_warning "libobj name \`$libobj' may not contain shell special characters." func_dirname_and_basename "$obj" "/" "" objname="$func_basename_result" xdir="$func_dirname_result" lobj=${xdir}$objdir/$objname test -z "$base_compile" && \ func_fatal_help "you must specify a compilation command" # Delete any leftover library objects. if test "$build_old_libs" = yes; then removelist="$obj $lobj $libobj ${libobj}T" else removelist="$lobj $libobj ${libobj}T" fi # On Cygwin there's no "real" PIC flag so we must build both object types case $host_os in cygwin* | mingw* | pw32* | os2* | cegcc*) pic_mode=default ;; esac if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then # non-PIC code in shared libraries is not supported pic_mode=default fi # Calculate the filename of the output object if compiler does # not support -o with -c if test "$compiler_c_o" = no; then output_obj=`$ECHO "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$%%'`.${objext} lockfile="$output_obj.lock" else output_obj= need_locks=no lockfile= fi # Lock this critical section if it is needed # We use this script file to make the link, it avoids creating a new file if test "$need_locks" = yes; then until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done elif test "$need_locks" = warn; then if test -f "$lockfile"; then $ECHO "\ *** ERROR, $lockfile exists and contains: `cat $lockfile 2>/dev/null` This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi removelist="$removelist $output_obj" $ECHO "$srcfile" > "$lockfile" fi $opt_dry_run || $RM $removelist removelist="$removelist $lockfile" trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 if test -n "$fix_srcfile_path"; then eval srcfile=\"$fix_srcfile_path\" fi func_quote_for_eval "$srcfile" qsrcfile=$func_quote_for_eval_result # Only build a PIC object if we are building libtool libraries. if test "$build_libtool_libs" = yes; then # Without this assignment, base_compile gets emptied. fbsd_hideous_sh_bug=$base_compile if test "$pic_mode" != no; then command="$base_compile $qsrcfile $pic_flag" else # Don't build PIC code command="$base_compile $qsrcfile" fi func_mkdir_p "$xdir$objdir" if test -z "$output_obj"; then # Place PIC objects in $objdir command="$command -o $lobj" fi func_show_eval_locale "$command" \ 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' if test "$need_locks" = warn && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed, then go on to compile the next one if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then func_show_eval '$MV "$output_obj" "$lobj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi # Allow error messages only from the first compilation. if test "$suppress_opt" = yes; then suppress_output=' >/dev/null 2>&1' fi fi # Only build a position-dependent object if we build old libraries. if test "$build_old_libs" = yes; then if test "$pic_mode" != yes; then # Don't build PIC code command="$base_compile $qsrcfile$pie_flag" else command="$base_compile $qsrcfile $pic_flag" fi if test "$compiler_c_o" = yes; then command="$command -o $obj" fi # Suppress compiler output if we already did a PIC compilation. command="$command$suppress_output" func_show_eval_locale "$command" \ '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' if test "$need_locks" = warn && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then func_show_eval '$MV "$output_obj" "$obj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi fi $opt_dry_run || { func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" # Unlock the critical section if it was locked if test "$need_locks" != no; then removelist=$lockfile $RM "$lockfile" fi } exit $EXIT_SUCCESS } $opt_help || { test "$mode" = compile && func_mode_compile ${1+"$@"} } func_mode_help () { # We need to display help for each of the modes. case $mode in "") # Generic help is extracted from the usage comments # at the start of this file. func_help ;; clean) $ECHO \ "Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... Remove files from the build directory. RM is the name of the program to use to delete files associated with each FILE (typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed to RM. If FILE is a libtool library, object or program, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; compile) $ECHO \ "Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE Compile a source file into a libtool library object. This mode accepts the following additional options: -o OUTPUT-FILE set the output file name to OUTPUT-FILE -no-suppress do not suppress compiler output for multiple passes -prefer-pic try to building PIC objects only -prefer-non-pic try to building non-PIC objects only -shared do not build a \`.o' file suitable for static linking -static only build a \`.o' file suitable for static linking COMPILE-COMMAND is a command to be used in creating a \`standard' object file from the given SOURCEFILE. The output file name is determined by removing the directory component from SOURCEFILE, then substituting the C source code suffix \`.c' with the library object suffix, \`.lo'." ;; execute) $ECHO \ "Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... Automatically set library path, then run a program. This mode accepts the following additional options: -dlopen FILE add the directory containing FILE to the library path This mode sets the library path environment variable according to \`-dlopen' flags. If any of the ARGS are libtool executable wrappers, then they are translated into their corresponding uninstalled binary, and any of their required library directories are added to the library path. Then, COMMAND is executed, with ARGS as arguments." ;; finish) $ECHO \ "Usage: $progname [OPTION]... --mode=finish [LIBDIR]... Complete the installation of libtool libraries. Each LIBDIR is a directory that contains libtool libraries. The commands that this mode executes may require superuser privileges. Use the \`--dry-run' option if you just want to see what would be executed." ;; install) $ECHO \ "Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... Install executables or libraries. INSTALL-COMMAND is the installation command. The first component should be either the \`install' or \`cp' program. The following components of INSTALL-COMMAND are treated specially: -inst-prefix PREFIX-DIR Use PREFIX-DIR as a staging area for installation The rest of the components are interpreted as arguments to that command (only BSD-compatible install options are recognized)." ;; link) $ECHO \ "Usage: $progname [OPTION]... --mode=link LINK-COMMAND... Link object files or libraries together to form another library, or to create an executable program. LINK-COMMAND is a command using the C compiler that you would use to create a program from several object files. The following components of LINK-COMMAND are treated specially: -all-static do not do any dynamic linking at all -avoid-version do not add a version suffix if possible -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) -export-symbols SYMFILE try to export only the symbols listed in SYMFILE -export-symbols-regex REGEX try to export only the symbols matching REGEX -LLIBDIR search LIBDIR for required installed libraries -lNAME OUTPUT-FILE requires the installed library libNAME -module build a library that can dlopened -no-fast-install disable the fast-install mode -no-install link a not-installable executable -no-undefined declare that a library does not refer to external symbols -o OUTPUT-FILE create OUTPUT-FILE from the specified objects -objectlist FILE Use a list of object files found in FILE to specify objects -precious-files-regex REGEX don't remove output files matching REGEX -release RELEASE specify package release information -rpath LIBDIR the created library will eventually be installed in LIBDIR -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries -shared only do dynamic linking of libtool libraries -shrext SUFFIX override the standard shared library file extension -static do not do any dynamic linking of uninstalled libtool libraries -static-libtool-libs do not do any dynamic linking of libtool libraries -version-info CURRENT[:REVISION[:AGE]] specify library version info [each variable defaults to 0] -weak LIBNAME declare that the target provides the LIBNAME interface All other options (arguments beginning with \`-') are ignored. Every other argument is treated as a filename. Files ending in \`.la' are treated as uninstalled libtool libraries, other files are standard or library object files. If the OUTPUT-FILE ends in \`.la', then a libtool library is created, only library objects (\`.lo' files) may be specified, and \`-rpath' is required, except when creating a convenience library. If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created using \`ar' and \`ranlib', or on Windows using \`lib'. If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file is created, otherwise an executable program is created." ;; uninstall) $ECHO \ "Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... Remove libraries from an installation directory. RM is the name of the program to use to delete files associated with each FILE (typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed to RM. If FILE is a libtool library, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; *) func_fatal_help "invalid operation mode \`$mode'" ;; esac $ECHO $ECHO "Try \`$progname --help' for more information about other modes." exit $? } # Now that we've collected a possible --mode arg, show help if necessary $opt_help && func_mode_help # func_mode_execute arg... func_mode_execute () { $opt_debug # The first argument is the command name. cmd="$nonopt" test -z "$cmd" && \ func_fatal_help "you must specify a COMMAND" # Handle -dlopen flags immediately. for file in $execute_dlfiles; do test -f "$file" \ || func_fatal_help "\`$file' is not a file" dir= case $file in *.la) # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "\`$lib' is not a valid libtool archive" # Read the libtool library. dlname= library_names= func_source "$file" # Skip this library if it cannot be dlopened. if test -z "$dlname"; then # Warn if it was a shared library. test -n "$library_names" && \ func_warning "\`$file' was not linked with \`-export-dynamic'" continue fi func_dirname "$file" "" "." dir="$func_dirname_result" if test -f "$dir/$objdir/$dlname"; then dir="$dir/$objdir" else if test ! -f "$dir/$dlname"; then func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" fi fi ;; *.lo) # Just add the directory containing the .lo file. func_dirname "$file" "" "." dir="$func_dirname_result" ;; *) func_warning "\`-dlopen' is ignored for non-libtool libraries and objects" continue ;; esac # Get the absolute pathname. absdir=`cd "$dir" && pwd` test -n "$absdir" && dir="$absdir" # Now add the directory to shlibpath_var. if eval "test -z \"\$$shlibpath_var\""; then eval "$shlibpath_var=\"\$dir\"" else eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" fi done # This variable tells wrapper scripts just to set shlibpath_var # rather than running their programs. libtool_execute_magic="$magic" # Check if any of the arguments is a wrapper script. args= for file do case $file in -*) ;; *) # Do a test to see if this is really a libtool program. if func_ltwrapper_script_p "$file"; then func_source "$file" # Transform arg to wrapped name. file="$progdir/$program" elif func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" func_source "$func_ltwrapper_scriptname_result" # Transform arg to wrapped name. file="$progdir/$program" fi ;; esac # Quote arguments (to preserve shell metacharacters). func_quote_for_eval "$file" args="$args $func_quote_for_eval_result" done if test "X$opt_dry_run" = Xfalse; then if test -n "$shlibpath_var"; then # Export the shlibpath_var. eval "export $shlibpath_var" fi # Restore saved environment variables for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${save_$lt_var+set}\" = set; then $lt_var=\$save_$lt_var; export $lt_var else $lt_unset $lt_var fi" done # Now prepare to actually exec the command. exec_cmd="\$cmd$args" else # Display what would be done. if test -n "$shlibpath_var"; then eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" $ECHO "export $shlibpath_var" fi $ECHO "$cmd$args" exit $EXIT_SUCCESS fi } test "$mode" = execute && func_mode_execute ${1+"$@"} # func_mode_finish arg... func_mode_finish () { $opt_debug libdirs="$nonopt" admincmds= if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then for dir do libdirs="$libdirs $dir" done for libdir in $libdirs; do if test -n "$finish_cmds"; then # Do each command in the finish commands. func_execute_cmds "$finish_cmds" 'admincmds="$admincmds '"$cmd"'"' fi if test -n "$finish_eval"; then # Do the single finish_eval. eval cmds=\"$finish_eval\" $opt_dry_run || eval "$cmds" || admincmds="$admincmds $cmds" fi done fi # Exit here if they wanted silent mode. $opt_silent && exit $EXIT_SUCCESS $ECHO "X----------------------------------------------------------------------" | $Xsed $ECHO "Libraries have been installed in:" for libdir in $libdirs; do $ECHO " $libdir" done $ECHO $ECHO "If you ever happen to want to link against installed libraries" $ECHO "in a given directory, LIBDIR, you must either use libtool, and" $ECHO "specify the full pathname of the library, or use the \`-LLIBDIR'" $ECHO "flag during linking and do at least one of the following:" if test -n "$shlibpath_var"; then $ECHO " - add LIBDIR to the \`$shlibpath_var' environment variable" $ECHO " during execution" fi if test -n "$runpath_var"; then $ECHO " - add LIBDIR to the \`$runpath_var' environment variable" $ECHO " during linking" fi if test -n "$hardcode_libdir_flag_spec"; then libdir=LIBDIR eval flag=\"$hardcode_libdir_flag_spec\" $ECHO " - use the \`$flag' linker flag" fi if test -n "$admincmds"; then $ECHO " - have your system administrator run these commands:$admincmds" fi if test -f /etc/ld.so.conf; then $ECHO " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'" fi $ECHO $ECHO "See any operating system documentation about shared libraries for" case $host in solaris2.[6789]|solaris2.1[0-9]) $ECHO "more information, such as the ld(1), crle(1) and ld.so(8) manual" $ECHO "pages." ;; *) $ECHO "more information, such as the ld(1) and ld.so(8) manual pages." ;; esac $ECHO "X----------------------------------------------------------------------" | $Xsed exit $EXIT_SUCCESS } test "$mode" = finish && func_mode_finish ${1+"$@"} # func_mode_install arg... func_mode_install () { $opt_debug # There may be an optional sh(1) argument at the beginning of # install_prog (especially on Windows NT). if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh || # Allow the use of GNU shtool's install command. $ECHO "X$nonopt" | $GREP shtool >/dev/null; then # Aesthetically quote it. func_quote_for_eval "$nonopt" install_prog="$func_quote_for_eval_result " arg=$1 shift else install_prog= arg=$nonopt fi # The real first argument should be the name of the installation program. # Aesthetically quote it. func_quote_for_eval "$arg" install_prog="$install_prog$func_quote_for_eval_result" # We need to accept at least all the BSD install flags. dest= files= opts= prev= install_type= isdir=no stripme= for arg do if test -n "$dest"; then files="$files $dest" dest=$arg continue fi case $arg in -d) isdir=yes ;; -f) case " $install_prog " in *[\\\ /]cp\ *) ;; *) prev=$arg ;; esac ;; -g | -m | -o) prev=$arg ;; -s) stripme=" -s" continue ;; -*) ;; *) # If the previous option needed an argument, then skip it. if test -n "$prev"; then prev= else dest=$arg continue fi ;; esac # Aesthetically quote the argument. func_quote_for_eval "$arg" install_prog="$install_prog $func_quote_for_eval_result" done test -z "$install_prog" && \ func_fatal_help "you must specify an install program" test -n "$prev" && \ func_fatal_help "the \`$prev' option requires an argument" if test -z "$files"; then if test -z "$dest"; then func_fatal_help "no file or destination specified" else func_fatal_help "you must specify a destination" fi fi # Strip any trailing slash from the destination. func_stripname '' '/' "$dest" dest=$func_stripname_result # Check to see that the destination is a directory. test -d "$dest" && isdir=yes if test "$isdir" = yes; then destdir="$dest" destname= else func_dirname_and_basename "$dest" "" "." destdir="$func_dirname_result" destname="$func_basename_result" # Not a directory, so check to see that there is only one file specified. set dummy $files; shift test "$#" -gt 1 && \ func_fatal_help "\`$dest' is not a directory" fi case $destdir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) for file in $files; do case $file in *.lo) ;; *) func_fatal_help "\`$destdir' must be an absolute directory name" ;; esac done ;; esac # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic="$magic" staticlibs= future_libdirs= current_libdirs= for file in $files; do # Do each installation. case $file in *.$libext) # Do the static libraries later. staticlibs="$staticlibs $file" ;; *.la) # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "\`$file' is not a valid libtool archive" library_names= old_library= relink_command= func_source "$file" # Add the libdir to current_libdirs if it is the destination. if test "X$destdir" = "X$libdir"; then case "$current_libdirs " in *" $libdir "*) ;; *) current_libdirs="$current_libdirs $libdir" ;; esac else # Note the libdir as a future libdir. case "$future_libdirs " in *" $libdir "*) ;; *) future_libdirs="$future_libdirs $libdir" ;; esac fi func_dirname "$file" "/" "" dir="$func_dirname_result" dir="$dir$objdir" if test -n "$relink_command"; then # Determine the prefix the user has applied to our future dir. inst_prefix_dir=`$ECHO "X$destdir" | $Xsed -e "s%$libdir\$%%"` # Don't allow the user to place us outside of our expected # location b/c this prevents finding dependent libraries that # are installed to the same prefix. # At present, this check doesn't affect windows .dll's that # are installed into $libdir/../bin (currently, that works fine) # but it's something to keep an eye on. test "$inst_prefix_dir" = "$destdir" && \ func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir" if test -n "$inst_prefix_dir"; then # Stick the inst_prefix_dir data into the link command. relink_command=`$ECHO "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` else relink_command=`$ECHO "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%%"` fi func_warning "relinking \`$file'" func_show_eval "$relink_command" \ 'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"' fi # See the names of the shared library. set dummy $library_names; shift if test -n "$1"; then realname="$1" shift srcname="$realname" test -n "$relink_command" && srcname="$realname"T # Install the shared library and build the symlinks. func_show_eval "$install_prog $dir/$srcname $destdir/$realname" \ 'exit $?' tstripme="$stripme" case $host_os in cygwin* | mingw* | pw32* | cegcc*) case $realname in *.dll.a) tstripme="" ;; esac ;; esac if test -n "$tstripme" && test -n "$striplib"; then func_show_eval "$striplib $destdir/$realname" 'exit $?' fi if test "$#" -gt 0; then # Delete the old symlinks, and create new ones. # Try `ln -sf' first, because the `ln' binary might depend on # the symlink we replace! Solaris /bin/ln does not understand -f, # so we also need to try rm && ln -s. for linkname do test "$linkname" != "$realname" \ && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" done fi # Do each command in the postinstall commands. lib="$destdir/$realname" func_execute_cmds "$postinstall_cmds" 'exit $?' fi # Install the pseudo-library for information purposes. func_basename "$file" name="$func_basename_result" instname="$dir/$name"i func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' # Maybe install the static library, too. test -n "$old_library" && staticlibs="$staticlibs $dir/$old_library" ;; *.lo) # Install (i.e. copy) a libtool object. # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile="$destdir/$destname" else func_basename "$file" destfile="$func_basename_result" destfile="$destdir/$destfile" fi # Deduce the name of the destination old-style object file. case $destfile in *.lo) func_lo2o "$destfile" staticdest=$func_lo2o_result ;; *.$objext) staticdest="$destfile" destfile= ;; *) func_fatal_help "cannot copy a libtool object to \`$destfile'" ;; esac # Install the libtool object if requested. test -n "$destfile" && \ func_show_eval "$install_prog $file $destfile" 'exit $?' # Install the old object if enabled. if test "$build_old_libs" = yes; then # Deduce the name of the old-style object file. func_lo2o "$file" staticobj=$func_lo2o_result func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' fi exit $EXIT_SUCCESS ;; *) # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile="$destdir/$destname" else func_basename "$file" destfile="$func_basename_result" destfile="$destdir/$destfile" fi # If the file is missing, and there is a .exe on the end, strip it # because it is most likely a libtool script we actually want to # install stripped_ext="" case $file in *.exe) if test ! -f "$file"; then func_stripname '' '.exe' "$file" file=$func_stripname_result stripped_ext=".exe" fi ;; esac # Do a test to see if this is really a libtool program. case $host in *cygwin* | *mingw*) if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" wrapper=$func_ltwrapper_scriptname_result else func_stripname '' '.exe' "$file" wrapper=$func_stripname_result fi ;; *) wrapper=$file ;; esac if func_ltwrapper_script_p "$wrapper"; then notinst_deplibs= relink_command= func_source "$wrapper" # Check the variables that should have been set. test -z "$generated_by_libtool_version" && \ func_fatal_error "invalid libtool wrapper script \`$wrapper'" finalize=yes for lib in $notinst_deplibs; do # Check to see that each library is installed. libdir= if test -f "$lib"; then func_source "$lib" fi libfile="$libdir/"`$ECHO "X$lib" | $Xsed -e 's%^.*/%%g'` ### testsuite: skip nested quoting test if test -n "$libdir" && test ! -f "$libfile"; then func_warning "\`$lib' has not been installed in \`$libdir'" finalize=no fi done relink_command= func_source "$wrapper" outputname= if test "$fast_install" = no && test -n "$relink_command"; then $opt_dry_run || { if test "$finalize" = yes; then tmpdir=`func_mktempdir` func_basename "$file$stripped_ext" file="$func_basename_result" outputname="$tmpdir/$file" # Replace the output file specification. relink_command=`$ECHO "X$relink_command" | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g'` $opt_silent || { func_quote_for_expand "$relink_command" eval "func_echo $func_quote_for_expand_result" } if eval "$relink_command"; then : else func_error "error: relink \`$file' with the above command before installing it" $opt_dry_run || ${RM}r "$tmpdir" continue fi file="$outputname" else func_warning "cannot relink \`$file'" fi } else # Install the binary that we compiled earlier. file=`$ECHO "X$file$stripped_ext" | $Xsed -e "s%\([^/]*\)$%$objdir/\1%"` fi fi # remove .exe since cygwin /usr/bin/install will append another # one anyway case $install_prog,$host in */usr/bin/install*,*cygwin*) case $file:$destfile in *.exe:*.exe) # this is ok ;; *.exe:*) destfile=$destfile.exe ;; *:*.exe) func_stripname '' '.exe' "$destfile" destfile=$func_stripname_result ;; esac ;; esac func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' $opt_dry_run || if test -n "$outputname"; then ${RM}r "$tmpdir" fi ;; esac done for file in $staticlibs; do func_basename "$file" name="$func_basename_result" # Set up the ranlib parameters. oldlib="$destdir/$name" func_show_eval "$install_prog \$file \$oldlib" 'exit $?' if test -n "$stripme" && test -n "$old_striplib"; then func_show_eval "$old_striplib $oldlib" 'exit $?' fi # Do each command in the postinstall commands. func_execute_cmds "$old_postinstall_cmds" 'exit $?' done test -n "$future_libdirs" && \ func_warning "remember to run \`$progname --finish$future_libdirs'" if test -n "$current_libdirs"; then # Maybe just do a dry run. $opt_dry_run && current_libdirs=" -n$current_libdirs" exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs' else exit $EXIT_SUCCESS fi } test "$mode" = install && func_mode_install ${1+"$@"} # func_generate_dlsyms outputname originator pic_p # Extract symbols from dlprefiles and create ${outputname}S.o with # a dlpreopen symbol table. func_generate_dlsyms () { $opt_debug my_outputname="$1" my_originator="$2" my_pic_p="${3-no}" my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'` my_dlsyms= if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then if test -n "$NM" && test -n "$global_symbol_pipe"; then my_dlsyms="${my_outputname}S.c" else func_error "not configured to extract global symbols from dlpreopened files" fi fi if test -n "$my_dlsyms"; then case $my_dlsyms in "") ;; *.c) # Discover the nlist of each of the dlfiles. nlist="$output_objdir/${my_outputname}.nm" func_show_eval "$RM $nlist ${nlist}S ${nlist}T" # Parse the name list into a source file. func_verbose "creating $output_objdir/$my_dlsyms" $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ /* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */ /* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */ #ifdef __cplusplus extern \"C\" { #endif /* External symbol declarations for the compiler. */\ " if test "$dlself" = yes; then func_verbose "generating symbol list for \`$output'" $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" # Add our own program objects to the symbol list. progfiles=`$ECHO "X$objs$old_deplibs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` for progfile in $progfiles; do func_verbose "extracting global C symbols from \`$progfile'" $opt_dry_run || eval "$NM $progfile | $global_symbol_pipe >> '$nlist'" done if test -n "$exclude_expsyms"; then $opt_dry_run || { eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi if test -n "$export_symbols_regex"; then $opt_dry_run || { eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi # Prepare the list of exported symbols if test -z "$export_symbols"; then export_symbols="$output_objdir/$outputname.exp" $opt_dry_run || { $RM $export_symbols eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' ;; esac } else $opt_dry_run || { eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' case $host in *cygwin | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' ;; esac } fi fi for dlprefile in $dlprefiles; do func_verbose "extracting global C symbols from \`$dlprefile'" func_basename "$dlprefile" name="$func_basename_result" $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' eval "$NM $dlprefile 2>/dev/null | $global_symbol_pipe >> '$nlist'" } done $opt_dry_run || { # Make sure we have at least an empty file. test -f "$nlist" || : > "$nlist" if test -n "$exclude_expsyms"; then $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T $MV "$nlist"T "$nlist" fi # Try sorting and uniquifying the output. if $GREP -v "^: " < "$nlist" | if sort -k 3 </dev/null >/dev/null 2>&1; then sort -k 3 else sort +2 fi | uniq > "$nlist"S; then : else $GREP -v "^: " < "$nlist" > "$nlist"S fi if test -f "$nlist"S; then eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' else $ECHO '/* NONE */' >> "$output_objdir/$my_dlsyms" fi $ECHO >> "$output_objdir/$my_dlsyms" "\ /* The mapping between symbol names and symbols. */ typedef struct { const char *name; void *address; } lt_dlsymlist; " case $host in *cygwin* | *mingw* | *cegcc* ) $ECHO >> "$output_objdir/$my_dlsyms" "\ /* DATA imports from DLLs on WIN32 con't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */" lt_dlsym_const= ;; *osf5*) echo >> "$output_objdir/$my_dlsyms" "\ /* This system does not cope well with relocations in const data */" lt_dlsym_const= ;; *) lt_dlsym_const=const ;; esac $ECHO >> "$output_objdir/$my_dlsyms" "\ extern $lt_dlsym_const lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[]; $lt_dlsym_const lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[] = {\ { \"$my_originator\", (void *) 0 }," case $need_lib_prefix in no) eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; *) eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; esac $ECHO >> "$output_objdir/$my_dlsyms" "\ {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt_${my_prefix}_LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif\ " } # !$opt_dry_run pic_flag_for_symtable= case "$compile_command " in *" -static "*) ;; *) case $host in # compiling the symbol table file with pic_flag works around # a FreeBSD bug that causes programs to crash when -lm is # linked before any other PIC object. But we must not use # pic_flag when linking with -static. The problem exists in # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. *-*-freebsd2*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; *-*-hpux*) pic_flag_for_symtable=" $pic_flag" ;; *) if test "X$my_pic_p" != Xno; then pic_flag_for_symtable=" $pic_flag" fi ;; esac ;; esac symtab_cflags= for arg in $LTCFLAGS; do case $arg in -pie | -fpie | -fPIE) ;; *) symtab_cflags="$symtab_cflags $arg" ;; esac done # Now compile the dynamic symbol file. func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' # Clean up the generated files. func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"' # Transform the symbol file into the correct name. symfileobj="$output_objdir/${my_outputname}S.$objext" case $host in *cygwin* | *mingw* | *cegcc* ) if test -f "$output_objdir/$my_outputname.def"; then compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` else compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` fi ;; *) compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` ;; esac ;; *) func_fatal_error "unknown suffix for \`$my_dlsyms'" ;; esac else # We keep going just in case the user didn't refer to # lt_preloaded_symbols. The linker will fail if global_symbol_pipe # really was required. # Nullify the symbol file. compile_command=`$ECHO "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"` finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%"` fi } # func_win32_libid arg # return the library type of file 'arg' # # Need a lot of goo to handle *both* DLLs and import libs # Has to be a shell function in order to 'eat' the argument # that is supplied when $file_magic_command is called. func_win32_libid () { $opt_debug win32_libid_type="unknown" win32_fileres=`file -L $1 2>/dev/null` case $win32_fileres in *ar\ archive\ import\ library*) # definitely import win32_libid_type="x86 archive import" ;; *ar\ archive*) # could be an import, or static if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null ; then win32_nmres=`eval $NM -f posix -A $1 | $SED -n -e ' 1,100{ / I /{ s,.*,import, p q } }'` case $win32_nmres in import*) win32_libid_type="x86 archive import";; *) win32_libid_type="x86 archive static";; esac fi ;; *DLL*) win32_libid_type="x86 DLL" ;; *executable*) # but shell scripts are "executable" too... case $win32_fileres in *MS\ Windows\ PE\ Intel*) win32_libid_type="x86 DLL" ;; esac ;; esac $ECHO "$win32_libid_type" } # func_extract_an_archive dir oldlib func_extract_an_archive () { $opt_debug f_ex_an_ar_dir="$1"; shift f_ex_an_ar_oldlib="$1" func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" 'exit $?' if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then : else func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" fi } # func_extract_archives gentop oldlib ... func_extract_archives () { $opt_debug my_gentop="$1"; shift my_oldlibs=${1+"$@"} my_oldobjs="" my_xlib="" my_xabs="" my_xdir="" for my_xlib in $my_oldlibs; do # Extract the objects. case $my_xlib in [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;; *) my_xabs=`pwd`"/$my_xlib" ;; esac func_basename "$my_xlib" my_xlib="$func_basename_result" my_xlib_u=$my_xlib while :; do case " $extracted_archives " in *" $my_xlib_u "*) func_arith $extracted_serial + 1 extracted_serial=$func_arith_result my_xlib_u=lt$extracted_serial-$my_xlib ;; *) break ;; esac done extracted_archives="$extracted_archives $my_xlib_u" my_xdir="$my_gentop/$my_xlib_u" func_mkdir_p "$my_xdir" case $host in *-darwin*) func_verbose "Extracting $my_xabs" # Do not bother doing anything if just a dry run $opt_dry_run || { darwin_orig_dir=`pwd` cd $my_xdir || exit $? darwin_archive=$my_xabs darwin_curdir=`pwd` darwin_base_archive=`basename "$darwin_archive"` darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` if test -n "$darwin_arches"; then darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` darwin_arch= func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" for darwin_arch in $darwin_arches ; do func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}" $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}" cd "unfat-$$/${darwin_base_archive}-${darwin_arch}" func_extract_an_archive "`pwd`" "${darwin_base_archive}" cd "$darwin_curdir" $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" done # $darwin_arches ## Okay now we've a bunch of thin objects, gotta fatten them up :) darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u` darwin_file= darwin_files= for darwin_file in $darwin_filelist; do darwin_files=`find unfat-$$ -name $darwin_file -print | $NL2SP` $LIPO -create -output "$darwin_file" $darwin_files done # $darwin_filelist $RM -rf unfat-$$ cd "$darwin_orig_dir" else cd $darwin_orig_dir func_extract_an_archive "$my_xdir" "$my_xabs" fi # $darwin_arches } # !$opt_dry_run ;; *) func_extract_an_archive "$my_xdir" "$my_xabs" ;; esac my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP` done func_extract_archives_result="$my_oldobjs" } # func_emit_wrapper_part1 [arg=no] # # Emit the first part of a libtool wrapper script on stdout. # For more information, see the description associated with # func_emit_wrapper(), below. func_emit_wrapper_part1 () { func_emit_wrapper_part1_arg1=no if test -n "$1" ; then func_emit_wrapper_part1_arg1=$1 fi $ECHO "\ #! $SHELL # $output - temporary wrapper script for $objdir/$outputname # Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION # # The $output program cannot be directly executed until all the libtool # libraries that it depends on are installed. # # This wrapper script should never be moved out of the build directory. # If it is, it will not operate correctly. # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. Xsed='${SED} -e 1s/^X//' sed_quote_subst='$sed_quote_subst' # Be Bourne compatible if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH relink_command=\"$relink_command\" # This environment variable determines our operation mode. if test \"\$libtool_install_magic\" = \"$magic\"; then # install mode needs the following variables: generated_by_libtool_version='$macro_version' notinst_deplibs='$notinst_deplibs' else # When we are sourced in execute mode, \$file and \$ECHO are already set. if test \"\$libtool_execute_magic\" != \"$magic\"; then ECHO=\"$qecho\" file=\"\$0\" # Make sure echo works. if test \"X\$1\" = X--no-reexec; then # Discard the --no-reexec flag, and continue. shift elif test \"X\`{ \$ECHO '\t'; } 2>/dev/null\`\" = 'X\t'; then # Yippee, \$ECHO works! : else # Restart under the correct shell, and then maybe \$ECHO will work. exec $SHELL \"\$0\" --no-reexec \${1+\"\$@\"} fi fi\ " $ECHO "\ # Find the directory that this script lives in. thisdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\` test \"x\$thisdir\" = \"x\$file\" && thisdir=. # Follow symbolic links until we get to the real thisdir. file=\`ls -ld \"\$file\" | ${SED} -n 's/.*-> //p'\` while test -n \"\$file\"; do destdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\` # If there was a directory component, then change thisdir. if test \"x\$destdir\" != \"x\$file\"; then case \"\$destdir\" in [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; *) thisdir=\"\$thisdir/\$destdir\" ;; esac fi file=\`\$ECHO \"X\$file\" | \$Xsed -e 's%^.*/%%'\` file=\`ls -ld \"\$thisdir/\$file\" | ${SED} -n 's/.*-> //p'\` done " } # end: func_emit_wrapper_part1 # func_emit_wrapper_part2 [arg=no] # # Emit the second part of a libtool wrapper script on stdout. # For more information, see the description associated with # func_emit_wrapper(), below. func_emit_wrapper_part2 () { func_emit_wrapper_part2_arg1=no if test -n "$1" ; then func_emit_wrapper_part2_arg1=$1 fi $ECHO "\ # Usually 'no', except on cygwin/mingw when embedded into # the cwrapper. WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_part2_arg1 if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then # special case for '.' if test \"\$thisdir\" = \".\"; then thisdir=\`pwd\` fi # remove .libs from thisdir case \"\$thisdir\" in *[\\\\/]$objdir ) thisdir=\`\$ECHO \"X\$thisdir\" | \$Xsed -e 's%[\\\\/][^\\\\/]*$%%'\` ;; $objdir ) thisdir=. ;; esac fi # Try to get the absolute directory name. absdir=\`cd \"\$thisdir\" && pwd\` test -n \"\$absdir\" && thisdir=\"\$absdir\" " if test "$fast_install" = yes; then $ECHO "\ program=lt-'$outputname'$exeext progdir=\"\$thisdir/$objdir\" if test ! -f \"\$progdir/\$program\" || { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\ test \"X\$file\" != \"X\$progdir/\$program\"; }; then file=\"\$\$-\$program\" if test ! -d \"\$progdir\"; then $MKDIR \"\$progdir\" else $RM \"\$progdir/\$file\" fi" $ECHO "\ # relink executable if necessary if test -n \"\$relink_command\"; then if relink_command_output=\`eval \$relink_command 2>&1\`; then : else $ECHO \"\$relink_command_output\" >&2 $RM \"\$progdir/\$file\" exit 1 fi fi $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || { $RM \"\$progdir/\$program\"; $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } $RM \"\$progdir/\$file\" fi" else $ECHO "\ program='$outputname' progdir=\"\$thisdir/$objdir\" " fi $ECHO "\ if test -f \"\$progdir/\$program\"; then" # Export our shlibpath_var if we have one. if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then $ECHO "\ # Add our own library path to $shlibpath_var $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" # Some systems cannot cope with colon-terminated $shlibpath_var # The second colon is a workaround for a bug in BeOS R4 sed $shlibpath_var=\`\$ECHO \"X\$$shlibpath_var\" | \$Xsed -e 's/::*\$//'\` export $shlibpath_var " fi # fixup the dll searchpath if we need to. if test -n "$dllsearchpath"; then $ECHO "\ # Add the dll search path components to the executable PATH PATH=$dllsearchpath:\$PATH " fi $ECHO "\ if test \"\$libtool_execute_magic\" != \"$magic\"; then # Run the actual program with our arguments. " case $host in # Backslashes separate directories on plain windows *-*-mingw | *-*-os2* | *-cegcc*) $ECHO "\ exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} " ;; *) $ECHO "\ exec \"\$progdir/\$program\" \${1+\"\$@\"} " ;; esac $ECHO "\ \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 exit 1 fi else # The program doesn't exist. \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2 \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 $ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 exit 1 fi fi\ " } # end: func_emit_wrapper_part2 # func_emit_wrapper [arg=no] # # Emit a libtool wrapper script on stdout. # Don't directly open a file because we may want to # incorporate the script contents within a cygwin/mingw # wrapper executable. Must ONLY be called from within # func_mode_link because it depends on a number of variables # set therein. # # ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR # variable will take. If 'yes', then the emitted script # will assume that the directory in which it is stored is # the $objdir directory. This is a cygwin/mingw-specific # behavior. func_emit_wrapper () { func_emit_wrapper_arg1=no if test -n "$1" ; then func_emit_wrapper_arg1=$1 fi # split this up so that func_emit_cwrapperexe_src # can call each part independently. func_emit_wrapper_part1 "${func_emit_wrapper_arg1}" func_emit_wrapper_part2 "${func_emit_wrapper_arg1}" } # func_to_host_path arg # # Convert paths to host format when used with build tools. # Intended for use with "native" mingw (where libtool itself # is running under the msys shell), or in the following cross- # build environments: # $build $host # mingw (msys) mingw [e.g. native] # cygwin mingw # *nix + wine mingw # where wine is equipped with the `winepath' executable. # In the native mingw case, the (msys) shell automatically # converts paths for any non-msys applications it launches, # but that facility isn't available from inside the cwrapper. # Similar accommodations are necessary for $host mingw and # $build cygwin. Calling this function does no harm for other # $host/$build combinations not listed above. # # ARG is the path (on $build) that should be converted to # the proper representation for $host. The result is stored # in $func_to_host_path_result. func_to_host_path () { func_to_host_path_result="$1" if test -n "$1" ; then case $host in *mingw* ) lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' case $build in *mingw* ) # actually, msys # awkward: cmd appends spaces to result lt_sed_strip_trailing_spaces="s/[ ]*\$//" func_to_host_path_tmp1=`( cmd //c echo "$1" |\ $SED -e "$lt_sed_strip_trailing_spaces" ) 2>/dev/null || echo ""` func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\ $SED -e "$lt_sed_naive_backslashify"` ;; *cygwin* ) func_to_host_path_tmp1=`cygpath -w "$1"` func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\ $SED -e "$lt_sed_naive_backslashify"` ;; * ) # Unfortunately, winepath does not exit with a non-zero # error code, so we are forced to check the contents of # stdout. On the other hand, if the command is not # found, the shell will set an exit code of 127 and print # *an error message* to stdout. So we must check for both # error code of zero AND non-empty stdout, which explains # the odd construction: func_to_host_path_tmp1=`winepath -w "$1" 2>/dev/null` if test "$?" -eq 0 && test -n "${func_to_host_path_tmp1}"; then func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\ $SED -e "$lt_sed_naive_backslashify"` else # Allow warning below. func_to_host_path_result="" fi ;; esac if test -z "$func_to_host_path_result" ; then #func_error "Could not determine host path corresponding to" #func_error " '$1'" #func_error "Continuing, but uninstalled executables may not work." # Fallback: func_to_host_path_result="$1" fi ;; esac fi } # end: func_to_host_path # func_to_host_pathlist arg # # Convert pathlists to host format when used with build tools. # See func_to_host_path(), above. This function supports the # following $build/$host combinations (but does no harm for # combinations not listed here): # $build $host # mingw (msys) mingw [e.g. native] # cygwin mingw # *nix + wine mingw # # Path separators are also converted from $build format to # $host format. If ARG begins or ends with a path separator # character, it is preserved (but converted to $host format) # on output. # # ARG is a pathlist (on $build) that should be converted to # the proper representation on $host. The result is stored # in $func_to_host_pathlist_result. func_to_host_pathlist () { func_to_host_pathlist_result="$1" if test -n "$1" ; then case $host in *mingw* ) lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' # Remove leading and trailing path separator characters from # ARG. msys behavior is inconsistent here, cygpath turns them # into '.;' and ';.', and winepath ignores them completely. func_to_host_pathlist_tmp2="$1" # Once set for this call, this variable should not be # reassigned. It is used in tha fallback case. func_to_host_pathlist_tmp1=`echo "$func_to_host_pathlist_tmp2" |\ $SED -e 's|^:*||' -e 's|:*$||'` case $build in *mingw* ) # Actually, msys. # Awkward: cmd appends spaces to result. lt_sed_strip_trailing_spaces="s/[ ]*\$//" func_to_host_pathlist_tmp2=`( cmd //c echo "$func_to_host_pathlist_tmp1" |\ $SED -e "$lt_sed_strip_trailing_spaces" ) 2>/dev/null || echo ""` func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp2" |\ $SED -e "$lt_sed_naive_backslashify"` ;; *cygwin* ) func_to_host_pathlist_tmp2=`cygpath -w -p "$func_to_host_pathlist_tmp1"` func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp2" |\ $SED -e "$lt_sed_naive_backslashify"` ;; * ) # unfortunately, winepath doesn't convert pathlists func_to_host_pathlist_result="" func_to_host_pathlist_oldIFS=$IFS IFS=: for func_to_host_pathlist_f in $func_to_host_pathlist_tmp1 ; do IFS=$func_to_host_pathlist_oldIFS if test -n "$func_to_host_pathlist_f" ; then func_to_host_path "$func_to_host_pathlist_f" if test -n "$func_to_host_path_result" ; then if test -z "$func_to_host_pathlist_result" ; then func_to_host_pathlist_result="$func_to_host_path_result" else func_to_host_pathlist_result="$func_to_host_pathlist_result;$func_to_host_path_result" fi fi fi IFS=: done IFS=$func_to_host_pathlist_oldIFS ;; esac if test -z "$func_to_host_pathlist_result" ; then func_error "Could not determine the host path(s) corresponding to" func_error " '$1'" func_error "Continuing, but uninstalled executables may not work." # Fallback. This may break if $1 contains DOS-style drive # specifications. The fix is not to complicate the expression # below, but for the user to provide a working wine installation # with winepath so that path translation in the cross-to-mingw # case works properly. lt_replace_pathsep_nix_to_dos="s|:|;|g" func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp1" |\ $SED -e "$lt_replace_pathsep_nix_to_dos"` fi # Now, add the leading and trailing path separators back case "$1" in :* ) func_to_host_pathlist_result=";$func_to_host_pathlist_result" ;; esac case "$1" in *: ) func_to_host_pathlist_result="$func_to_host_pathlist_result;" ;; esac ;; esac fi } # end: func_to_host_pathlist # func_emit_cwrapperexe_src # emit the source code for a wrapper executable on stdout # Must ONLY be called from within func_mode_link because # it depends on a number of variable set therein. func_emit_cwrapperexe_src () { cat <<EOF /* $cwrappersource - temporary wrapper executable for $objdir/$outputname Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION The $output program cannot be directly executed until all the libtool libraries that it depends on are installed. This wrapper executable should never be moved out of the build directory. If it is, it will not operate correctly. Currently, it simply execs the wrapper *script* "$SHELL $output", but could eventually absorb all of the scripts functionality and exec $objdir/$outputname directly. */ EOF cat <<"EOF" #include <stdio.h> #include <stdlib.h> #ifdef _MSC_VER # include <direct.h> # include <process.h> # include <io.h> # define setmode _setmode #else # include <unistd.h> # include <stdint.h> # ifdef __CYGWIN__ # include <io.h> # define HAVE_SETENV # ifdef __STRICT_ANSI__ char *realpath (const char *, char *); int putenv (char *); int setenv (const char *, const char *, int); # endif # endif #endif #include <malloc.h> #include <stdarg.h> #include <assert.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <sys/stat.h> #if defined(PATH_MAX) # define LT_PATHMAX PATH_MAX #elif defined(MAXPATHLEN) # define LT_PATHMAX MAXPATHLEN #else # define LT_PATHMAX 1024 #endif #ifndef S_IXOTH # define S_IXOTH 0 #endif #ifndef S_IXGRP # define S_IXGRP 0 #endif #ifdef _MSC_VER # define S_IXUSR _S_IEXEC # define stat _stat # ifndef _INTPTR_T_DEFINED # define intptr_t int # endif #endif #ifndef DIR_SEPARATOR # define DIR_SEPARATOR '/' # define PATH_SEPARATOR ':' #endif #if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \ defined (__OS2__) # define HAVE_DOS_BASED_FILE_SYSTEM # define FOPEN_WB "wb" # ifndef DIR_SEPARATOR_2 # define DIR_SEPARATOR_2 '\\' # endif # ifndef PATH_SEPARATOR_2 # define PATH_SEPARATOR_2 ';' # endif #endif #ifndef DIR_SEPARATOR_2 # define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) #else /* DIR_SEPARATOR_2 */ # define IS_DIR_SEPARATOR(ch) \ (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) #endif /* DIR_SEPARATOR_2 */ #ifndef PATH_SEPARATOR_2 # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) #else /* PATH_SEPARATOR_2 */ # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) #endif /* PATH_SEPARATOR_2 */ #ifdef __CYGWIN__ # define FOPEN_WB "wb" #endif #ifndef FOPEN_WB # define FOPEN_WB "w" #endif #ifndef _O_BINARY # define _O_BINARY 0 #endif #define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) #define XFREE(stale) do { \ if (stale) { free ((void *) stale); stale = 0; } \ } while (0) #undef LTWRAPPER_DEBUGPRINTF #if defined DEBUGWRAPPER # define LTWRAPPER_DEBUGPRINTF(args) ltwrapper_debugprintf args static void ltwrapper_debugprintf (const char *fmt, ...) { va_list args; va_start (args, fmt); (void) vfprintf (stderr, fmt, args); va_end (args); } #else # define LTWRAPPER_DEBUGPRINTF(args) #endif const char *program_name = NULL; void *xmalloc (size_t num); char *xstrdup (const char *string); const char *base_name (const char *name); char *find_executable (const char *wrapper); char *chase_symlinks (const char *pathspec); int make_executable (const char *path); int check_executable (const char *path); char *strendzap (char *str, const char *pat); void lt_fatal (const char *message, ...); void lt_setenv (const char *name, const char *value); char *lt_extend_str (const char *orig_value, const char *add, int to_end); void lt_opt_process_env_set (const char *arg); void lt_opt_process_env_prepend (const char *arg); void lt_opt_process_env_append (const char *arg); int lt_split_name_value (const char *arg, char** name, char** value); void lt_update_exe_path (const char *name, const char *value); void lt_update_lib_path (const char *name, const char *value); static const char *script_text_part1 = EOF func_emit_wrapper_part1 yes | $SED -e 's/\([\\"]\)/\\\1/g' \ -e 's/^/ "/' -e 's/$/\\n"/' echo ";" cat <<EOF static const char *script_text_part2 = EOF func_emit_wrapper_part2 yes | $SED -e 's/\([\\"]\)/\\\1/g' \ -e 's/^/ "/' -e 's/$/\\n"/' echo ";" cat <<EOF const char * MAGIC_EXE = "$magic_exe"; const char * LIB_PATH_VARNAME = "$shlibpath_var"; EOF if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then func_to_host_pathlist "$temp_rpath" cat <<EOF const char * LIB_PATH_VALUE = "$func_to_host_pathlist_result"; EOF else cat <<"EOF" const char * LIB_PATH_VALUE = ""; EOF fi if test -n "$dllsearchpath"; then func_to_host_pathlist "$dllsearchpath:" cat <<EOF const char * EXE_PATH_VARNAME = "PATH"; const char * EXE_PATH_VALUE = "$func_to_host_pathlist_result"; EOF else cat <<"EOF" const char * EXE_PATH_VARNAME = ""; const char * EXE_PATH_VALUE = ""; EOF fi if test "$fast_install" = yes; then cat <<EOF const char * TARGET_PROGRAM_NAME = "lt-$outputname"; /* hopefully, no .exe */ EOF else cat <<EOF const char * TARGET_PROGRAM_NAME = "$outputname"; /* hopefully, no .exe */ EOF fi cat <<"EOF" #define LTWRAPPER_OPTION_PREFIX "--lt-" #define LTWRAPPER_OPTION_PREFIX_LENGTH 5 static const size_t opt_prefix_len = LTWRAPPER_OPTION_PREFIX_LENGTH; static const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX; static const char *dumpscript_opt = LTWRAPPER_OPTION_PREFIX "dump-script"; static const size_t env_set_opt_len = LTWRAPPER_OPTION_PREFIX_LENGTH + 7; static const char *env_set_opt = LTWRAPPER_OPTION_PREFIX "env-set"; /* argument is putenv-style "foo=bar", value of foo is set to bar */ static const size_t env_prepend_opt_len = LTWRAPPER_OPTION_PREFIX_LENGTH + 11; static const char *env_prepend_opt = LTWRAPPER_OPTION_PREFIX "env-prepend"; /* argument is putenv-style "foo=bar", new value of foo is bar${foo} */ static const size_t env_append_opt_len = LTWRAPPER_OPTION_PREFIX_LENGTH + 10; static const char *env_append_opt = LTWRAPPER_OPTION_PREFIX "env-append"; /* argument is putenv-style "foo=bar", new value of foo is ${foo}bar */ #undef main int main (int argc, char *argv[]) { char **newargz; int newargc; char *tmp_pathspec; char *actual_cwrapper_path; char *actual_cwrapper_name; char *target_name; char *lt_argv_zero; intptr_t rval = 127; int i; program_name = (char *) xstrdup (base_name (argv[0])); LTWRAPPER_DEBUGPRINTF (("(main) argv[0] : %s\n", argv[0])); LTWRAPPER_DEBUGPRINTF (("(main) program_name : %s\n", program_name)); /* very simple arg parsing; don't want to rely on getopt */ for (i = 1; i < argc; i++) { if (strcmp (argv[i], dumpscript_opt) == 0) { EOF case "$host" in *mingw* | *cygwin* ) # make stdout use "unix" line endings echo " setmode(1,_O_BINARY);" ;; esac cat <<"EOF" printf ("%s", script_text_part1); printf ("%s", script_text_part2); return 0; } } newargz = XMALLOC (char *, argc + 1); tmp_pathspec = find_executable (argv[0]); if (tmp_pathspec == NULL) lt_fatal ("Couldn't find %s", argv[0]); LTWRAPPER_DEBUGPRINTF (("(main) found exe (before symlink chase) at : %s\n", tmp_pathspec)); actual_cwrapper_path = chase_symlinks (tmp_pathspec); LTWRAPPER_DEBUGPRINTF (("(main) found exe (after symlink chase) at : %s\n", actual_cwrapper_path)); XFREE (tmp_pathspec); actual_cwrapper_name = xstrdup( base_name (actual_cwrapper_path)); strendzap (actual_cwrapper_path, actual_cwrapper_name); /* wrapper name transforms */ strendzap (actual_cwrapper_name, ".exe"); tmp_pathspec = lt_extend_str (actual_cwrapper_name, ".exe", 1); XFREE (actual_cwrapper_name); actual_cwrapper_name = tmp_pathspec; tmp_pathspec = 0; /* target_name transforms -- use actual target program name; might have lt- prefix */ target_name = xstrdup (base_name (TARGET_PROGRAM_NAME)); strendzap (target_name, ".exe"); tmp_pathspec = lt_extend_str (target_name, ".exe", 1); XFREE (target_name); target_name = tmp_pathspec; tmp_pathspec = 0; LTWRAPPER_DEBUGPRINTF (("(main) libtool target name: %s\n", target_name)); EOF cat <<EOF newargz[0] = XMALLOC (char, (strlen (actual_cwrapper_path) + strlen ("$objdir") + 1 + strlen (actual_cwrapper_name) + 1)); strcpy (newargz[0], actual_cwrapper_path); strcat (newargz[0], "$objdir"); strcat (newargz[0], "/"); EOF cat <<"EOF" /* stop here, and copy so we don't have to do this twice */ tmp_pathspec = xstrdup (newargz[0]); /* do NOT want the lt- prefix here, so use actual_cwrapper_name */ strcat (newargz[0], actual_cwrapper_name); /* DO want the lt- prefix here if it exists, so use target_name */ lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1); XFREE (tmp_pathspec); tmp_pathspec = NULL; EOF case $host_os in mingw*) cat <<"EOF" { char* p; while ((p = strchr (newargz[0], '\\')) != NULL) { *p = '/'; } while ((p = strchr (lt_argv_zero, '\\')) != NULL) { *p = '/'; } } EOF ;; esac cat <<"EOF" XFREE (target_name); XFREE (actual_cwrapper_path); XFREE (actual_cwrapper_name); lt_setenv ("BIN_SH", "xpg4"); /* for Tru64 */ lt_setenv ("DUALCASE", "1"); /* for MSK sh */ lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE); lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE); newargc=0; for (i = 1; i < argc; i++) { if (strncmp (argv[i], env_set_opt, env_set_opt_len) == 0) { if (argv[i][env_set_opt_len] == '=') { const char *p = argv[i] + env_set_opt_len + 1; lt_opt_process_env_set (p); } else if (argv[i][env_set_opt_len] == '\0' && i + 1 < argc) { lt_opt_process_env_set (argv[++i]); /* don't copy */ } else lt_fatal ("%s missing required argument", env_set_opt); continue; } if (strncmp (argv[i], env_prepend_opt, env_prepend_opt_len) == 0) { if (argv[i][env_prepend_opt_len] == '=') { const char *p = argv[i] + env_prepend_opt_len + 1; lt_opt_process_env_prepend (p); } else if (argv[i][env_prepend_opt_len] == '\0' && i + 1 < argc) { lt_opt_process_env_prepend (argv[++i]); /* don't copy */ } else lt_fatal ("%s missing required argument", env_prepend_opt); continue; } if (strncmp (argv[i], env_append_opt, env_append_opt_len) == 0) { if (argv[i][env_append_opt_len] == '=') { const char *p = argv[i] + env_append_opt_len + 1; lt_opt_process_env_append (p); } else if (argv[i][env_append_opt_len] == '\0' && i + 1 < argc) { lt_opt_process_env_append (argv[++i]); /* don't copy */ } else lt_fatal ("%s missing required argument", env_append_opt); continue; } if (strncmp (argv[i], ltwrapper_option_prefix, opt_prefix_len) == 0) { /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX namespace, but it is not one of the ones we know about and have already dealt with, above (inluding dump-script), then report an error. Otherwise, targets might begin to believe they are allowed to use options in the LTWRAPPER_OPTION_PREFIX namespace. The first time any user complains about this, we'll need to make LTWRAPPER_OPTION_PREFIX a configure-time option or a configure.ac-settable value. */ lt_fatal ("Unrecognized option in %s namespace: '%s'", ltwrapper_option_prefix, argv[i]); } /* otherwise ... */ newargz[++newargc] = xstrdup (argv[i]); } newargz[++newargc] = NULL; LTWRAPPER_DEBUGPRINTF (("(main) lt_argv_zero : %s\n", (lt_argv_zero ? lt_argv_zero : "<NULL>"))); for (i = 0; i < newargc; i++) { LTWRAPPER_DEBUGPRINTF (("(main) newargz[%d] : %s\n", i, (newargz[i] ? newargz[i] : "<NULL>"))); } EOF case $host_os in mingw*) cat <<"EOF" /* execv doesn't actually work on mingw as expected on unix */ rval = _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz); if (rval == -1) { /* failed to start process */ LTWRAPPER_DEBUGPRINTF (("(main) failed to launch target \"%s\": errno = %d\n", lt_argv_zero, errno)); return 127; } return rval; EOF ;; *) cat <<"EOF" execv (lt_argv_zero, newargz); return rval; /* =127, but avoids unused variable warning */ EOF ;; esac cat <<"EOF" } void * xmalloc (size_t num) { void *p = (void *) malloc (num); if (!p) lt_fatal ("Memory exhausted"); return p; } char * xstrdup (const char *string) { return string ? strcpy ((char *) xmalloc (strlen (string) + 1), string) : NULL; } const char * base_name (const char *name) { const char *base; #if defined (HAVE_DOS_BASED_FILE_SYSTEM) /* Skip over the disk name in MSDOS pathnames. */ if (isalpha ((unsigned char) name[0]) && name[1] == ':') name += 2; #endif for (base = name; *name; name++) if (IS_DIR_SEPARATOR (*name)) base = name + 1; return base; } int check_executable (const char *path) { struct stat st; LTWRAPPER_DEBUGPRINTF (("(check_executable) : %s\n", path ? (*path ? path : "EMPTY!") : "NULL!")); if ((!path) || (!*path)) return 0; if ((stat (path, &st) >= 0) && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return 1; else return 0; } int make_executable (const char *path) { int rval = 0; struct stat st; LTWRAPPER_DEBUGPRINTF (("(make_executable) : %s\n", path ? (*path ? path : "EMPTY!") : "NULL!")); if ((!path) || (!*path)) return 0; if (stat (path, &st) >= 0) { rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); } return rval; } /* Searches for the full path of the wrapper. Returns newly allocated full path name if found, NULL otherwise Does not chase symlinks, even on platforms that support them. */ char * find_executable (const char *wrapper) { int has_slash = 0; const char *p; const char *p_next; /* static buffer for getcwd */ char tmp[LT_PATHMAX + 1]; int tmp_len; char *concat_name; LTWRAPPER_DEBUGPRINTF (("(find_executable) : %s\n", wrapper ? (*wrapper ? wrapper : "EMPTY!") : "NULL!")); if ((wrapper == NULL) || (*wrapper == '\0')) return NULL; /* Absolute path? */ #if defined (HAVE_DOS_BASED_FILE_SYSTEM) if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } else { #endif if (IS_DIR_SEPARATOR (wrapper[0])) { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } #if defined (HAVE_DOS_BASED_FILE_SYSTEM) } #endif for (p = wrapper; *p; p++) if (*p == '/') { has_slash = 1; break; } if (!has_slash) { /* no slashes; search PATH */ const char *path = getenv ("PATH"); if (path != NULL) { for (p = path; *p; p = p_next) { const char *q; size_t p_len; for (q = p; *q; q++) if (IS_PATH_SEPARATOR (*q)) break; p_len = q - p; p_next = (*q == '\0' ? q : q + 1); if (p_len == 0) { /* empty path: current directory */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal ("getcwd failed"); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); } else { concat_name = XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, p, p_len); concat_name[p_len] = '/'; strcpy (concat_name + p_len + 1, wrapper); } if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } } /* not found in PATH; assume curdir */ } /* Relative path | not found in path: prepend cwd */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal ("getcwd failed"); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); return NULL; } char * chase_symlinks (const char *pathspec) { #ifndef S_ISLNK return xstrdup (pathspec); #else char buf[LT_PATHMAX]; struct stat s; char *tmp_pathspec = xstrdup (pathspec); char *p; int has_symlinks = 0; while (strlen (tmp_pathspec) && !has_symlinks) { LTWRAPPER_DEBUGPRINTF (("checking path component for symlinks: %s\n", tmp_pathspec)); if (lstat (tmp_pathspec, &s) == 0) { if (S_ISLNK (s.st_mode) != 0) { has_symlinks = 1; break; } /* search backwards for last DIR_SEPARATOR */ p = tmp_pathspec + strlen (tmp_pathspec) - 1; while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) p--; if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) { /* no more DIR_SEPARATORS left */ break; } *p = '\0'; } else { char *errstr = strerror (errno); lt_fatal ("Error accessing file %s (%s)", tmp_pathspec, errstr); } } XFREE (tmp_pathspec); if (!has_symlinks) { return xstrdup (pathspec); } tmp_pathspec = realpath (pathspec, buf); if (tmp_pathspec == 0) { lt_fatal ("Could not follow symlinks for %s", pathspec); } return xstrdup (tmp_pathspec); #endif } char * strendzap (char *str, const char *pat) { size_t len, patlen; assert (str != NULL); assert (pat != NULL); len = strlen (str); patlen = strlen (pat); if (patlen <= len) { str += len - patlen; if (strcmp (str, pat) == 0) *str = '\0'; } return str; } static void lt_error_core (int exit_status, const char *mode, const char *message, va_list ap) { fprintf (stderr, "%s: %s: ", program_name, mode); vfprintf (stderr, message, ap); fprintf (stderr, ".\n"); if (exit_status >= 0) exit (exit_status); } void lt_fatal (const char *message, ...) { va_list ap; va_start (ap, message); lt_error_core (EXIT_FAILURE, "FATAL", message, ap); va_end (ap); } void lt_setenv (const char *name, const char *value) { LTWRAPPER_DEBUGPRINTF (("(lt_setenv) setting '%s' to '%s'\n", (name ? name : "<NULL>"), (value ? value : "<NULL>"))); { #ifdef HAVE_SETENV /* always make a copy, for consistency with !HAVE_SETENV */ char *str = xstrdup (value); setenv (name, str, 1); #else int len = strlen (name) + 1 + strlen (value) + 1; char *str = XMALLOC (char, len); sprintf (str, "%s=%s", name, value); if (putenv (str) != EXIT_SUCCESS) { XFREE (str); } #endif } } char * lt_extend_str (const char *orig_value, const char *add, int to_end) { char *new_value; if (orig_value && *orig_value) { int orig_value_len = strlen (orig_value); int add_len = strlen (add); new_value = XMALLOC (char, add_len + orig_value_len + 1); if (to_end) { strcpy (new_value, orig_value); strcpy (new_value + orig_value_len, add); } else { strcpy (new_value, add); strcpy (new_value + add_len, orig_value); } } else { new_value = xstrdup (add); } return new_value; } int lt_split_name_value (const char *arg, char** name, char** value) { const char *p; int len; if (!arg || !*arg) return 1; p = strchr (arg, (int)'='); if (!p) return 1; *value = xstrdup (++p); len = strlen (arg) - strlen (*value); *name = XMALLOC (char, len); strncpy (*name, arg, len-1); (*name)[len - 1] = '\0'; return 0; } void lt_opt_process_env_set (const char *arg) { char *name = NULL; char *value = NULL; if (lt_split_name_value (arg, &name, &value) != 0) { XFREE (name); XFREE (value); lt_fatal ("bad argument for %s: '%s'", env_set_opt, arg); } lt_setenv (name, value); XFREE (name); XFREE (value); } void lt_opt_process_env_prepend (const char *arg) { char *name = NULL; char *value = NULL; char *new_value = NULL; if (lt_split_name_value (arg, &name, &value) != 0) { XFREE (name); XFREE (value); lt_fatal ("bad argument for %s: '%s'", env_prepend_opt, arg); } new_value = lt_extend_str (getenv (name), value, 0); lt_setenv (name, new_value); XFREE (new_value); XFREE (name); XFREE (value); } void lt_opt_process_env_append (const char *arg) { char *name = NULL; char *value = NULL; char *new_value = NULL; if (lt_split_name_value (arg, &name, &value) != 0) { XFREE (name); XFREE (value); lt_fatal ("bad argument for %s: '%s'", env_append_opt, arg); } new_value = lt_extend_str (getenv (name), value, 1); lt_setenv (name, new_value); XFREE (new_value); XFREE (name); XFREE (value); } void lt_update_exe_path (const char *name, const char *value) { LTWRAPPER_DEBUGPRINTF (("(lt_update_exe_path) modifying '%s' by prepending '%s'\n", (name ? name : "<NULL>"), (value ? value : "<NULL>"))); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); /* some systems can't cope with a ':'-terminated path #' */ int len = strlen (new_value); while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1])) { new_value[len-1] = '\0'; } lt_setenv (name, new_value); XFREE (new_value); } } void lt_update_lib_path (const char *name, const char *value) { LTWRAPPER_DEBUGPRINTF (("(lt_update_lib_path) modifying '%s' by prepending '%s'\n", (name ? name : "<NULL>"), (value ? value : "<NULL>"))); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); lt_setenv (name, new_value); XFREE (new_value); } } EOF } # end: func_emit_cwrapperexe_src # func_mode_link arg... func_mode_link () { $opt_debug case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) # It is impossible to link a dll without this setting, and # we shouldn't force the makefile maintainer to figure out # which system we are compiling for in order to pass an extra # flag for every libtool invocation. # allow_undefined=no # FIXME: Unfortunately, there are problems with the above when trying # to make a dll which has undefined symbols, in which case not # even a static library is built. For now, we need to specify # -no-undefined on the libtool link line when we can be certain # that all symbols are satisfied, otherwise we get a static library. allow_undefined=yes ;; *) allow_undefined=yes ;; esac libtool_args=$nonopt base_compile="$nonopt $@" compile_command=$nonopt finalize_command=$nonopt compile_rpath= finalize_rpath= compile_shlibpath= finalize_shlibpath= convenience= old_convenience= deplibs= old_deplibs= compiler_flags= linker_flags= dllsearchpath= lib_search_path=`pwd` inst_prefix_dir= new_inherited_linker_flags= avoid_version=no dlfiles= dlprefiles= dlself=no export_dynamic=no export_symbols= export_symbols_regex= generated= libobjs= ltlibs= module=no no_install=no objs= non_pic_objects= precious_files_regex= prefer_static_libs=no preload=no prev= prevarg= release= rpath= xrpath= perm_rpath= temp_rpath= thread_safe=no vinfo= vinfo_number=no weak_libs= single_module="${wl}-single_module" func_infer_tag $base_compile # We need to know -static, to get the right output filenames. for arg do case $arg in -shared) test "$build_libtool_libs" != yes && \ func_fatal_configuration "can not build a shared library" build_old_libs=no break ;; -all-static | -static | -static-libtool-libs) case $arg in -all-static) if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then func_warning "complete static linking is impossible in this configuration" fi if test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; -static) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=built ;; -static-libtool-libs) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; esac build_libtool_libs=no build_old_libs=yes break ;; esac done # See if our shared archives depend on static archives. test -n "$old_archive_from_new_cmds" && build_old_libs=yes # Go through the arguments, transforming them on the way. while test "$#" -gt 0; do arg="$1" shift func_quote_for_eval "$arg" qarg=$func_quote_for_eval_unquoted_result func_append libtool_args " $func_quote_for_eval_result" # If the previous option needs an argument, assign it. if test -n "$prev"; then case $prev in output) func_append compile_command " @OUTPUT@" func_append finalize_command " @OUTPUT@" ;; esac case $prev in dlfiles|dlprefiles) if test "$preload" = no; then # Add the symbol object into the linking commands. func_append compile_command " @SYMFILE@" func_append finalize_command " @SYMFILE@" preload=yes fi case $arg in *.la | *.lo) ;; # We handle these cases below. force) if test "$dlself" = no; then dlself=needless export_dynamic=yes fi prev= continue ;; self) if test "$prev" = dlprefiles; then dlself=yes elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then dlself=yes else dlself=needless export_dynamic=yes fi prev= continue ;; *) if test "$prev" = dlfiles; then dlfiles="$dlfiles $arg" else dlprefiles="$dlprefiles $arg" fi prev= continue ;; esac ;; expsyms) export_symbols="$arg" test -f "$arg" \ || func_fatal_error "symbol file \`$arg' does not exist" prev= continue ;; expsyms_regex) export_symbols_regex="$arg" prev= continue ;; framework) case $host in *-*-darwin*) case "$deplibs " in *" $qarg.ltframework "*) ;; *) deplibs="$deplibs $qarg.ltframework" # this is fixed later ;; esac ;; esac prev= continue ;; inst_prefix) inst_prefix_dir="$arg" prev= continue ;; objectlist) if test -f "$arg"; then save_arg=$arg moreargs= for fil in `cat "$save_arg"` do # moreargs="$moreargs $fil" arg=$fil # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test "$pic_object" = none && test "$non_pic_object" = none; then func_fatal_error "cannot find name of object for \`$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" if test "$pic_object" != none; then # Prepend the subdirectory the object is found in. pic_object="$xdir$pic_object" if test "$prev" = dlfiles; then if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then dlfiles="$dlfiles $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test "$prev" = dlprefiles; then # Preload the old-style object. dlprefiles="$dlprefiles $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg="$pic_object" fi # Non-PIC object. if test "$non_pic_object" != none; then # Prepend the subdirectory the object is found in. non_pic_object="$xdir$non_pic_object" # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test "$pic_object" = none ; then arg="$non_pic_object" fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object="$pic_object" func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "\`$arg' is not a valid libtool object" fi fi done else func_fatal_error "link input file \`$arg' does not exist" fi arg=$save_arg prev= continue ;; precious_regex) precious_files_regex="$arg" prev= continue ;; release) release="-$arg" prev= continue ;; rpath | xrpath) # We need an absolute path. case $arg in [\\/]* | [A-Za-z]:[\\/]*) ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac if test "$prev" = rpath; then case "$rpath " in *" $arg "*) ;; *) rpath="$rpath $arg" ;; esac else case "$xrpath " in *" $arg "*) ;; *) xrpath="$xrpath $arg" ;; esac fi prev= continue ;; shrext) shrext_cmds="$arg" prev= continue ;; weak) weak_libs="$weak_libs $arg" prev= continue ;; xcclinker) linker_flags="$linker_flags $qarg" compiler_flags="$compiler_flags $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xcompiler) compiler_flags="$compiler_flags $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xlinker) linker_flags="$linker_flags $qarg" compiler_flags="$compiler_flags $wl$qarg" prev= func_append compile_command " $wl$qarg" func_append finalize_command " $wl$qarg" continue ;; *) eval "$prev=\"\$arg\"" prev= continue ;; esac fi # test -n "$prev" prevarg="$arg" case $arg in -all-static) if test -n "$link_static_flag"; then # See comment for -static flag below, for more details. func_append compile_command " $link_static_flag" func_append finalize_command " $link_static_flag" fi continue ;; -allow-undefined) # FIXME: remove this flag sometime in the future. func_fatal_error "\`-allow-undefined' must not be used because it is the default" ;; -avoid-version) avoid_version=yes continue ;; -dlopen) prev=dlfiles continue ;; -dlpreopen) prev=dlprefiles continue ;; -export-dynamic) export_dynamic=yes continue ;; -export-symbols | -export-symbols-regex) if test -n "$export_symbols" || test -n "$export_symbols_regex"; then func_fatal_error "more than one -exported-symbols argument is not allowed" fi if test "X$arg" = "X-export-symbols"; then prev=expsyms else prev=expsyms_regex fi continue ;; -framework) prev=framework continue ;; -inst-prefix-dir) prev=inst_prefix continue ;; # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* # so, if we see these flags be careful not to treat them like -L -L[A-Z][A-Z]*:*) case $with_gcc/$host in no/*-*-irix* | /*-*-irix*) func_append compile_command " $arg" func_append finalize_command " $arg" ;; esac continue ;; -L*) func_stripname '-L' '' "$arg" dir=$func_stripname_result if test -z "$dir"; then if test "$#" -gt 0; then func_fatal_error "require no space between \`-L' and \`$1'" else func_fatal_error "need path for \`-L' option" fi fi # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) absdir=`cd "$dir" && pwd` test -z "$absdir" && \ func_fatal_error "cannot determine absolute directory name of \`$dir'" dir="$absdir" ;; esac case "$deplibs " in *" -L$dir "*) ;; *) deplibs="$deplibs -L$dir" lib_search_path="$lib_search_path $dir" ;; esac case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "X$dir" | $Xsed -e 's*/lib$*/bin*'` case :$dllsearchpath: in *":$dir:"*) ;; ::) dllsearchpath=$dir;; *) dllsearchpath="$dllsearchpath:$dir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) dllsearchpath="$dllsearchpath:$testbindir";; esac ;; esac continue ;; -l*) if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc*) # These systems don't actually have a C or math library (as such) continue ;; *-*-os2*) # These systems don't actually have a C library (as such) test "X$arg" = "X-lc" && continue ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. test "X$arg" = "X-lc" && continue ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C and math libraries are in the System framework deplibs="$deplibs System.ltframework" continue ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype test "X$arg" = "X-lc" && continue ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work test "X$arg" = "X-lc" && continue ;; esac elif test "X$arg" = "X-lc_r"; then case $host in *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc_r directly, use -pthread flag. continue ;; esac fi deplibs="$deplibs $arg" continue ;; -module) module=yes continue ;; # Tru64 UNIX uses -model [arg] to determine the layout of C++ # classes, name mangling, and exception handling. # Darwin uses the -arch flag to determine output architecture. -model|-arch|-isysroot) compiler_flags="$compiler_flags $arg" func_append compile_command " $arg" func_append finalize_command " $arg" prev=xcompiler continue ;; -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads) compiler_flags="$compiler_flags $arg" func_append compile_command " $arg" func_append finalize_command " $arg" case "$new_inherited_linker_flags " in *" $arg "*) ;; * ) new_inherited_linker_flags="$new_inherited_linker_flags $arg" ;; esac continue ;; -multi_module) single_module="${wl}-multi_module" continue ;; -no-fast-install) fast_install=no continue ;; -no-install) case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) # The PATH hackery in wrapper scripts is required on Windows # and Darwin in order for the loader to find any dlls it needs. func_warning "\`-no-install' is ignored for $host" func_warning "assuming \`-no-fast-install' instead" fast_install=no ;; *) no_install=yes ;; esac continue ;; -no-undefined) allow_undefined=no continue ;; -objectlist) prev=objectlist continue ;; -o) prev=output ;; -precious-files-regex) prev=precious_regex continue ;; -release) prev=release continue ;; -rpath) prev=rpath continue ;; -R) prev=xrpath continue ;; -R*) func_stripname '-R' '' "$arg" dir=$func_stripname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac case "$xrpath " in *" $dir "*) ;; *) xrpath="$xrpath $dir" ;; esac continue ;; -shared) # The effects of -shared are defined in a previous loop. continue ;; -shrext) prev=shrext continue ;; -static | -static-libtool-libs) # The effects of -static are defined in a previous loop. # We used to do the same as -all-static on platforms that # didn't have a PIC flag, but the assumption that the effects # would be equivalent was wrong. It would break on at least # Digital Unix and AIX. continue ;; -thread-safe) thread_safe=yes continue ;; -version-info) prev=vinfo continue ;; -version-number) prev=vinfo vinfo_number=yes continue ;; -weak) prev=weak continue ;; -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result arg= save_ifs="$IFS"; IFS=',' for flag in $args; do IFS="$save_ifs" func_quote_for_eval "$flag" arg="$arg $wl$func_quote_for_eval_result" compiler_flags="$compiler_flags $func_quote_for_eval_result" done IFS="$save_ifs" func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Wl,*) func_stripname '-Wl,' '' "$arg" args=$func_stripname_result arg= save_ifs="$IFS"; IFS=',' for flag in $args; do IFS="$save_ifs" func_quote_for_eval "$flag" arg="$arg $wl$func_quote_for_eval_result" compiler_flags="$compiler_flags $wl$func_quote_for_eval_result" linker_flags="$linker_flags $func_quote_for_eval_result" done IFS="$save_ifs" func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Xcompiler) prev=xcompiler continue ;; -Xlinker) prev=xlinker continue ;; -XCClinker) prev=xcclinker continue ;; # -msg_* for osf cc -msg_*) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; # -64, -mips[0-9] enable 64-bit mode on the SGI compiler # -r[0-9][0-9]* specifies the processor on the SGI compiler # -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler # +DA*, +DD* enable 64-bit mode on the HP compiler # -q* pass through compiler args for the IBM compiler # -m*, -t[45]*, -txscale* pass through architecture-specific # compiler args for GCC # -F/path gives path to uninstalled frameworks, gcc on darwin # -p, -pg, --coverage, -fprofile-* pass through profiling flag for GCC # @file GCC response files -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" func_append compile_command " $arg" func_append finalize_command " $arg" compiler_flags="$compiler_flags $arg" continue ;; # Some other compiler flag. -* | +*) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; *.$objext) # A standard object. objs="$objs $arg" ;; *.lo) # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test "$pic_object" = none && test "$non_pic_object" = none; then func_fatal_error "cannot find name of object for \`$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" if test "$pic_object" != none; then # Prepend the subdirectory the object is found in. pic_object="$xdir$pic_object" if test "$prev" = dlfiles; then if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then dlfiles="$dlfiles $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test "$prev" = dlprefiles; then # Preload the old-style object. dlprefiles="$dlprefiles $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg="$pic_object" fi # Non-PIC object. if test "$non_pic_object" != none; then # Prepend the subdirectory the object is found in. non_pic_object="$xdir$non_pic_object" # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test "$pic_object" = none ; then arg="$non_pic_object" fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object="$pic_object" func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "\`$arg' is not a valid libtool object" fi fi ;; *.$libext) # An archive. deplibs="$deplibs $arg" old_deplibs="$old_deplibs $arg" continue ;; *.la) # A libtool-controlled library. if test "$prev" = dlfiles; then # This library was specified with -dlopen. dlfiles="$dlfiles $arg" prev= elif test "$prev" = dlprefiles; then # The library was specified with -dlpreopen. dlprefiles="$dlprefiles $arg" prev= else deplibs="$deplibs $arg" fi continue ;; # Some other compiler argument. *) # Unknown arguments in both finalize_command and compile_command need # to be aesthetically quoted because they are evaled later. func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; esac # arg # Now actually substitute the argument into the commands. if test -n "$arg"; then func_append compile_command " $arg" func_append finalize_command " $arg" fi done # argument parsing loop test -n "$prev" && \ func_fatal_help "the \`$prevarg' option requires an argument" if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then eval arg=\"$export_dynamic_flag_spec\" func_append compile_command " $arg" func_append finalize_command " $arg" fi oldlibs= # calculate the name of the file, without its directory func_basename "$output" outputname="$func_basename_result" libobjs_save="$libobjs" if test -n "$shlibpath_var"; then # get the directories listed in $shlibpath_var eval shlib_search_path=\`\$ECHO \"X\${$shlibpath_var}\" \| \$Xsed -e \'s/:/ /g\'\` else shlib_search_path= fi eval sys_lib_search_path=\"$sys_lib_search_path_spec\" eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" func_dirname "$output" "/" "" output_objdir="$func_dirname_result$objdir" # Create the object directory. func_mkdir_p "$output_objdir" # Determine the type of output case $output in "") func_fatal_help "you must specify an output file" ;; *.$libext) linkmode=oldlib ;; *.lo | *.$objext) linkmode=obj ;; *.la) linkmode=lib ;; *) linkmode=prog ;; # Anything else should be a program. esac specialdeplibs= libs= # Find all interdependent deplibs by searching for libraries # that are linked more than once (e.g. -la -lb -la) for deplib in $deplibs; do if $opt_duplicate_deps ; then case "$libs " in *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; esac fi libs="$libs $deplib" done if test "$linkmode" = lib; then libs="$predeps $libs $compiler_lib_search_path $postdeps" # Compute libraries that are listed more than once in $predeps # $postdeps and mark them as special (i.e., whose duplicates are # not to be eliminated). pre_post_deps= if $opt_duplicate_compiler_generated_deps; then for pre_post_dep in $predeps $postdeps; do case "$pre_post_deps " in *" $pre_post_dep "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;; esac pre_post_deps="$pre_post_deps $pre_post_dep" done fi pre_post_deps= fi deplibs= newdependency_libs= newlib_search_path= need_relink=no # whether we're linking any uninstalled libtool libraries notinst_deplibs= # not-installed libtool libraries notinst_path= # paths that contain not-installed libtool libraries case $linkmode in lib) passes="conv dlpreopen link" for file in $dlfiles $dlprefiles; do case $file in *.la) ;; *) func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file" ;; esac done ;; prog) compile_deplibs= finalize_deplibs= alldeplibs=no newdlfiles= newdlprefiles= passes="conv scan dlopen dlpreopen link" ;; *) passes="conv" ;; esac for pass in $passes; do # The preopen pass in lib mode reverses $deplibs; put it back here # so that -L comes before libs that need it for instance... if test "$linkmode,$pass" = "lib,link"; then ## FIXME: Find the place where the list is rebuilt in the wrong ## order, and fix it there properly tmp_deplibs= for deplib in $deplibs; do tmp_deplibs="$deplib $tmp_deplibs" done deplibs="$tmp_deplibs" fi if test "$linkmode,$pass" = "lib,link" || test "$linkmode,$pass" = "prog,scan"; then libs="$deplibs" deplibs= fi if test "$linkmode" = prog; then case $pass in dlopen) libs="$dlfiles" ;; dlpreopen) libs="$dlprefiles" ;; link) libs="$deplibs %DEPLIBS% $dependency_libs" ;; esac fi if test "$linkmode,$pass" = "lib,dlpreopen"; then # Collect and forward deplibs of preopened libtool libs for lib in $dlprefiles; do # Ignore non-libtool-libs dependency_libs= case $lib in *.la) func_source "$lib" ;; esac # Collect preopened libtool deplibs, except any this library # has declared as weak libs for deplib in $dependency_libs; do deplib_base=`$ECHO "X$deplib" | $Xsed -e "$basename"` case " $weak_libs " in *" $deplib_base "*) ;; *) deplibs="$deplibs $deplib" ;; esac done done libs="$dlprefiles" fi if test "$pass" = dlopen; then # Collect dlpreopened libraries save_deplibs="$deplibs" deplibs= fi for deplib in $libs; do lib= found=no case $deplib in -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads) if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else compiler_flags="$compiler_flags $deplib" if test "$linkmode" = lib ; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) new_inherited_linker_flags="$new_inherited_linker_flags $deplib" ;; esac fi fi continue ;; -l*) if test "$linkmode" != lib && test "$linkmode" != prog; then func_warning "\`-l' is ignored for archives/objects" continue fi func_stripname '-l' '' "$deplib" name=$func_stripname_result if test "$linkmode" = lib; then searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" else searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" fi for searchdir in $searchdirs; do for search_ext in .la $std_shrext .so .a; do # Search the libtool library lib="$searchdir/lib${name}${search_ext}" if test -f "$lib"; then if test "$search_ext" = ".la"; then found=yes else found=no fi break 2 fi done done if test "$found" != yes; then # deplib doesn't seem to be a libtool library if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" fi continue else # deplib is a libtool library # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, # We need to do some special things here, and not later. if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $deplib "*) if func_lalib_p "$lib"; then library_names= old_library= func_source "$lib" for l in $old_library $library_names; do ll="$l" done if test "X$ll" = "X$old_library" ; then # only static version available found=no func_dirname "$lib" "" "." ladir="$func_dirname_result" lib=$ladir/$old_library if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" fi continue fi fi ;; *) ;; esac fi fi ;; # -l *.ltframework) if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" if test "$linkmode" = lib ; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) new_inherited_linker_flags="$new_inherited_linker_flags $deplib" ;; esac fi fi continue ;; -L*) case $linkmode in lib) deplibs="$deplib $deplibs" test "$pass" = conv && continue newdependency_libs="$deplib $newdependency_libs" func_stripname '-L' '' "$deplib" newlib_search_path="$newlib_search_path $func_stripname_result" ;; prog) if test "$pass" = conv; then deplibs="$deplib $deplibs" continue fi if test "$pass" = scan; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi func_stripname '-L' '' "$deplib" newlib_search_path="$newlib_search_path $func_stripname_result" ;; *) func_warning "\`-L' is ignored for archives/objects" ;; esac # linkmode continue ;; # -L -R*) if test "$pass" = link; then func_stripname '-R' '' "$deplib" dir=$func_stripname_result # Make sure the xrpath contains only unique directories. case "$xrpath " in *" $dir "*) ;; *) xrpath="$xrpath $dir" ;; esac fi deplibs="$deplib $deplibs" continue ;; *.la) lib="$deplib" ;; *.$libext) if test "$pass" = conv; then deplibs="$deplib $deplibs" continue fi case $linkmode in lib) # Linking convenience modules into shared libraries is allowed, # but linking other static libraries is non-portable. case " $dlpreconveniencelibs " in *" $deplib "*) ;; *) valid_a_lib=no case $deplibs_check_method in match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` if eval "\$ECHO \"X$deplib\"" 2>/dev/null | $Xsed -e 10q \ | $EGREP "$match_pattern_regex" > /dev/null; then valid_a_lib=yes fi ;; pass_all) valid_a_lib=yes ;; esac if test "$valid_a_lib" != yes; then $ECHO $ECHO "*** Warning: Trying to link with static lib archive $deplib." $ECHO "*** I have the capability to make that library automatically link in when" $ECHO "*** you link to this library. But I can only do this if you have a" $ECHO "*** shared version of the library, which you do not appear to have" $ECHO "*** because the file extensions .$libext of this argument makes me believe" $ECHO "*** that it is just a static archive that I should not use here." else $ECHO $ECHO "*** Warning: Linking the shared library $output against the" $ECHO "*** static library $deplib is not portable!" deplibs="$deplib $deplibs" fi ;; esac continue ;; prog) if test "$pass" != link; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi continue ;; esac # linkmode ;; # *.$libext *.lo | *.$objext) if test "$pass" = conv; then deplibs="$deplib $deplibs" elif test "$linkmode" = prog; then if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then # If there is no dlopen support or we're linking statically, # we need to preload. newdlprefiles="$newdlprefiles $deplib" compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else newdlfiles="$newdlfiles $deplib" fi fi continue ;; %DEPLIBS%) alldeplibs=yes continue ;; esac # case $deplib if test "$found" = yes || test -f "$lib"; then : else func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'" fi # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$lib" \ || func_fatal_error "\`$lib' is not a valid libtool archive" func_dirname "$lib" "" "." ladir="$func_dirname_result" dlname= dlopen= dlpreopen= libdir= library_names= old_library= inherited_linker_flags= # If the library was installed with an old release of libtool, # it will not redefine variables installed, or shouldnotlink installed=yes shouldnotlink=no avoidtemprpath= # Read the .la file func_source "$lib" # Convert "-framework foo" to "foo.ltframework" if test -n "$inherited_linker_flags"; then tmp_inherited_linker_flags=`$ECHO "X$inherited_linker_flags" | $Xsed -e 's/-framework \([^ $]*\)/\1.ltframework/g'` for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do case " $new_inherited_linker_flags " in *" $tmp_inherited_linker_flag "*) ;; *) new_inherited_linker_flags="$new_inherited_linker_flags $tmp_inherited_linker_flag";; esac done fi dependency_libs=`$ECHO "X $dependency_libs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` if test "$linkmode,$pass" = "lib,link" || test "$linkmode,$pass" = "prog,scan" || { test "$linkmode" != prog && test "$linkmode" != lib; }; then test -n "$dlopen" && dlfiles="$dlfiles $dlopen" test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen" fi if test "$pass" = conv; then # Only check for convenience libraries deplibs="$lib $deplibs" if test -z "$libdir"; then if test -z "$old_library"; then func_fatal_error "cannot find name of link library for \`$lib'" fi # It is a libtool convenience library, so add in its objects. convenience="$convenience $ladir/$objdir/$old_library" old_convenience="$old_convenience $ladir/$objdir/$old_library" elif test "$linkmode" != prog && test "$linkmode" != lib; then func_fatal_error "\`$lib' is not a convenience library" fi tmp_libs= for deplib in $dependency_libs; do deplibs="$deplib $deplibs" if $opt_duplicate_deps ; then case "$tmp_libs " in *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; esac fi tmp_libs="$tmp_libs $deplib" done continue fi # $pass = conv # Get the name of the library we link against. linklib= for l in $old_library $library_names; do linklib="$l" done if test -z "$linklib"; then func_fatal_error "cannot find name of link library for \`$lib'" fi # This library was specified with -dlopen. if test "$pass" = dlopen; then if test -z "$libdir"; then func_fatal_error "cannot -dlopen a convenience library: \`$lib'" fi if test -z "$dlname" || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then # If there is no dlname, no dlopen support or we're linking # statically, we need to preload. We also need to preload any # dependent libraries so libltdl's deplib preloader doesn't # bomb out in the load deplibs phase. dlprefiles="$dlprefiles $lib $dependency_libs" else newdlfiles="$newdlfiles $lib" fi continue fi # $pass = dlopen # We need an absolute path. case $ladir in [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;; *) abs_ladir=`cd "$ladir" && pwd` if test -z "$abs_ladir"; then func_warning "cannot determine absolute directory name of \`$ladir'" func_warning "passing it literally to the linker, although it might fail" abs_ladir="$ladir" fi ;; esac func_basename "$lib" laname="$func_basename_result" # Find the relevant object directory and library name. if test "X$installed" = Xyes; then if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then func_warning "library \`$lib' was moved." dir="$ladir" absdir="$abs_ladir" libdir="$abs_ladir" else dir="$libdir" absdir="$libdir" fi test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes else if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then dir="$ladir" absdir="$abs_ladir" # Remove this search path later notinst_path="$notinst_path $abs_ladir" else dir="$ladir/$objdir" absdir="$abs_ladir/$objdir" # Remove this search path later notinst_path="$notinst_path $abs_ladir" fi fi # $installed = yes func_stripname 'lib' '.la' "$laname" name=$func_stripname_result # This library was specified with -dlpreopen. if test "$pass" = dlpreopen; then if test -z "$libdir" && test "$linkmode" = prog; then func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'" fi # Prefer using a static library (so that no silly _DYNAMIC symbols # are required to link). if test -n "$old_library"; then newdlprefiles="$newdlprefiles $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ dlpreconveniencelibs="$dlpreconveniencelibs $dir/$old_library" # Otherwise, use the dlname, so that lt_dlopen finds it. elif test -n "$dlname"; then newdlprefiles="$newdlprefiles $dir/$dlname" else newdlprefiles="$newdlprefiles $dir/$linklib" fi fi # $pass = dlpreopen if test -z "$libdir"; then # Link the convenience library if test "$linkmode" = lib; then deplibs="$dir/$old_library $deplibs" elif test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$dir/$old_library $compile_deplibs" finalize_deplibs="$dir/$old_library $finalize_deplibs" else deplibs="$lib $deplibs" # used for prog,scan pass fi continue fi if test "$linkmode" = prog && test "$pass" != link; then newlib_search_path="$newlib_search_path $ladir" deplibs="$lib $deplibs" linkalldeplibs=no if test "$link_all_deplibs" != no || test -z "$library_names" || test "$build_libtool_libs" = no; then linkalldeplibs=yes fi tmp_libs= for deplib in $dependency_libs; do case $deplib in -L*) func_stripname '-L' '' "$deplib" newlib_search_path="$newlib_search_path $func_stripname_result" ;; esac # Need to link against all dependency_libs? if test "$linkalldeplibs" = yes; then deplibs="$deplib $deplibs" else # Need to hardcode shared library paths # or/and link against static libraries newdependency_libs="$deplib $newdependency_libs" fi if $opt_duplicate_deps ; then case "$tmp_libs " in *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; esac fi tmp_libs="$tmp_libs $deplib" done # for deplib continue fi # $linkmode = prog... if test "$linkmode,$pass" = "prog,link"; then if test -n "$library_names" && { { test "$prefer_static_libs" = no || test "$prefer_static_libs,$installed" = "built,yes"; } || test -z "$old_library"; }; then # We need to hardcode the library path if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then # Make sure the rpath contains only unique directories. case "$temp_rpath:" in *"$absdir:"*) ;; *) temp_rpath="$temp_rpath$absdir:" ;; esac fi # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) compile_rpath="$compile_rpath $absdir" esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) finalize_rpath="$finalize_rpath $libdir" esac ;; esac fi # $linkmode,$pass = prog,link... if test "$alldeplibs" = yes && { test "$deplibs_check_method" = pass_all || { test "$build_libtool_libs" = yes && test -n "$library_names"; }; }; then # We only need to search for static libraries continue fi fi link_static=no # Whether the deplib will be linked statically use_static_libs=$prefer_static_libs if test "$use_static_libs" = built && test "$installed" = yes; then use_static_libs=no fi if test -n "$library_names" && { test "$use_static_libs" = no || test -z "$old_library"; }; then case $host in *cygwin* | *mingw* | *cegcc*) # No point in relinking DLLs because paths are not encoded notinst_deplibs="$notinst_deplibs $lib" need_relink=no ;; *) if test "$installed" = no; then notinst_deplibs="$notinst_deplibs $lib" need_relink=yes fi ;; esac # This is a shared library # Warn about portability, can't link against -module's on some # systems (darwin). Don't bleat about dlopened modules though! dlopenmodule="" for dlpremoduletest in $dlprefiles; do if test "X$dlpremoduletest" = "X$lib"; then dlopenmodule="$dlpremoduletest" break fi done if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then $ECHO if test "$linkmode" = prog; then $ECHO "*** Warning: Linking the executable $output against the loadable module" else $ECHO "*** Warning: Linking the shared library $output against the loadable module" fi $ECHO "*** $linklib is not portable!" fi if test "$linkmode" = lib && test "$hardcode_into_libs" = yes; then # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) compile_rpath="$compile_rpath $absdir" esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) finalize_rpath="$finalize_rpath $libdir" esac ;; esac fi if test -n "$old_archive_from_expsyms_cmds"; then # figure out the soname set dummy $library_names shift realname="$1" shift libname=`eval "\\$ECHO \"$libname_spec\""` # use dlname if we got it. it's perfectly good, no? if test -n "$dlname"; then soname="$dlname" elif test -n "$soname_spec"; then # bleh windows case $host in *cygwin* | mingw* | *cegcc*) func_arith $current - $age major=$func_arith_result versuffix="-$major" ;; esac eval soname=\"$soname_spec\" else soname="$realname" fi # Make a new name for the extract_expsyms_cmds to use soroot="$soname" func_basename "$soroot" soname="$func_basename_result" func_stripname 'lib' '.dll' "$soname" newlib=libimp-$func_stripname_result.a # If the library has no export list, then create one now if test -f "$output_objdir/$soname-def"; then : else func_verbose "extracting exported symbol list from \`$soname'" func_execute_cmds "$extract_expsyms_cmds" 'exit $?' fi # Create $newlib if test -f "$output_objdir/$newlib"; then :; else func_verbose "generating import library for \`$soname'" func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' fi # make sure the library variables are pointing to the new library dir=$output_objdir linklib=$newlib fi # test -n "$old_archive_from_expsyms_cmds" if test "$linkmode" = prog || test "$mode" != relink; then add_shlibpath= add_dir= add= lib_linked=yes case $hardcode_action in immediate | unsupported) if test "$hardcode_direct" = no; then add="$dir/$linklib" case $host in *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;; *-*-sysv4*uw2*) add_dir="-L$dir" ;; *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ *-*-unixware7*) add_dir="-L$dir" ;; *-*-darwin* ) # if the lib is a (non-dlopened) module then we can not # link against it, someone is ignoring the earlier warnings if /usr/bin/file -L $add 2> /dev/null | $GREP ": [^:]* bundle" >/dev/null ; then if test "X$dlopenmodule" != "X$lib"; then $ECHO "*** Warning: lib $linklib is a module, not a shared library" if test -z "$old_library" ; then $ECHO $ECHO "*** And there doesn't seem to be a static archive available" $ECHO "*** The link will probably fail, sorry" else add="$dir/$old_library" fi elif test -n "$old_library"; then add="$dir/$old_library" fi fi esac elif test "$hardcode_minus_L" = no; then case $host in *-*-sunos*) add_shlibpath="$dir" ;; esac add_dir="-L$dir" add="-l$name" elif test "$hardcode_shlibpath_var" = no; then add_shlibpath="$dir" add="-l$name" else lib_linked=no fi ;; relink) if test "$hardcode_direct" = yes && test "$hardcode_direct_absolute" = no; then add="$dir/$linklib" elif test "$hardcode_minus_L" = yes; then add_dir="-L$dir" # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) add_dir="$add_dir -L$inst_prefix_dir$libdir" ;; esac fi add="-l$name" elif test "$hardcode_shlibpath_var" = yes; then add_shlibpath="$dir" add="-l$name" else lib_linked=no fi ;; *) lib_linked=no ;; esac if test "$lib_linked" != yes; then func_fatal_configuration "unsupported hardcode properties" fi if test -n "$add_shlibpath"; then case :$compile_shlibpath: in *":$add_shlibpath:"*) ;; *) compile_shlibpath="$compile_shlibpath$add_shlibpath:" ;; esac fi if test "$linkmode" = prog; then test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" test -n "$add" && compile_deplibs="$add $compile_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" if test "$hardcode_direct" != yes && test "$hardcode_minus_L" != yes && test "$hardcode_shlibpath_var" = yes; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; esac fi fi fi if test "$linkmode" = prog || test "$mode" = relink; then add_shlibpath= add_dir= add= # Finalize command for both is simple: just hardcode it. if test "$hardcode_direct" = yes && test "$hardcode_direct_absolute" = no; then add="$libdir/$linklib" elif test "$hardcode_minus_L" = yes; then add_dir="-L$libdir" add="-l$name" elif test "$hardcode_shlibpath_var" = yes; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; esac add="-l$name" elif test "$hardcode_automatic" = yes; then if test -n "$inst_prefix_dir" && test -f "$inst_prefix_dir$libdir/$linklib" ; then add="$inst_prefix_dir$libdir/$linklib" else add="$libdir/$linklib" fi else # We cannot seem to hardcode it, guess we'll fake it. add_dir="-L$libdir" # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) add_dir="$add_dir -L$inst_prefix_dir$libdir" ;; esac fi add="-l$name" fi if test "$linkmode" = prog; then test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" test -n "$add" && finalize_deplibs="$add $finalize_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" fi fi elif test "$linkmode" = prog; then # Here we assume that one of hardcode_direct or hardcode_minus_L # is not unsupported. This is valid on all known static and # shared platforms. if test "$hardcode_direct" != unsupported; then test -n "$old_library" && linklib="$old_library" compile_deplibs="$dir/$linklib $compile_deplibs" finalize_deplibs="$dir/$linklib $finalize_deplibs" else compile_deplibs="-l$name -L$dir $compile_deplibs" finalize_deplibs="-l$name -L$dir $finalize_deplibs" fi elif test "$build_libtool_libs" = yes; then # Not a shared library if test "$deplibs_check_method" != pass_all; then # We're trying link a shared library against a static one # but the system doesn't support it. # Just print a warning and add the library to dependency_libs so # that the program can be linked against the static library. $ECHO $ECHO "*** Warning: This system can not link to static lib archive $lib." $ECHO "*** I have the capability to make that library automatically link in when" $ECHO "*** you link to this library. But I can only do this if you have a" $ECHO "*** shared version of the library, which you do not appear to have." if test "$module" = yes; then $ECHO "*** But as you try to build a module library, libtool will still create " $ECHO "*** a static module, that should work as long as the dlopening application" $ECHO "*** is linked with the -dlopen flag to resolve symbols at runtime." if test -z "$global_symbol_pipe"; then $ECHO $ECHO "*** However, this would only work if libtool was able to extract symbol" $ECHO "*** lists from a program, using \`nm' or equivalent, but libtool could" $ECHO "*** not find such a program. So, this module is probably useless." $ECHO "*** \`nm' from GNU binutils and a full rebuild may help." fi if test "$build_old_libs" = no; then build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi else deplibs="$dir/$old_library $deplibs" link_static=yes fi fi # link shared/static library? if test "$linkmode" = lib; then if test -n "$dependency_libs" && { test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes || test "$link_static" = yes; }; then # Extract -R from dependency_libs temp_deplibs= for libdir in $dependency_libs; do case $libdir in -R*) func_stripname '-R' '' "$libdir" temp_xrpath=$func_stripname_result case " $xrpath " in *" $temp_xrpath "*) ;; *) xrpath="$xrpath $temp_xrpath";; esac;; *) temp_deplibs="$temp_deplibs $libdir";; esac done dependency_libs="$temp_deplibs" fi newlib_search_path="$newlib_search_path $absdir" # Link against this library test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs" # ... and its dependency_libs tmp_libs= for deplib in $dependency_libs; do newdependency_libs="$deplib $newdependency_libs" if $opt_duplicate_deps ; then case "$tmp_libs " in *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; esac fi tmp_libs="$tmp_libs $deplib" done if test "$link_all_deplibs" != no; then # Add the search paths of all dependency libraries for deplib in $dependency_libs; do case $deplib in -L*) path="$deplib" ;; *.la) func_dirname "$deplib" "" "." dir="$func_dirname_result" # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;; *) absdir=`cd "$dir" && pwd` if test -z "$absdir"; then func_warning "cannot determine absolute directory name of \`$dir'" absdir="$dir" fi ;; esac if $GREP "^installed=no" $deplib > /dev/null; then case $host in *-*-darwin*) depdepl= eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` if test -n "$deplibrary_names" ; then for tmp in $deplibrary_names ; do depdepl=$tmp done if test -f "$absdir/$objdir/$depdepl" ; then depdepl="$absdir/$objdir/$depdepl" darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` if test -z "$darwin_install_name"; then darwin_install_name=`${OTOOL64} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` fi compiler_flags="$compiler_flags ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}" linker_flags="$linker_flags -dylib_file ${darwin_install_name}:${depdepl}" path= fi fi ;; *) path="-L$absdir/$objdir" ;; esac else eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` test -z "$libdir" && \ func_fatal_error "\`$deplib' is not a valid libtool archive" test "$absdir" != "$libdir" && \ func_warning "\`$deplib' seems to be moved" path="-L$absdir" fi ;; esac case " $deplibs " in *" $path "*) ;; *) deplibs="$path $deplibs" ;; esac done fi # link_all_deplibs != no fi # linkmode = lib done # for deplib in $libs if test "$pass" = link; then if test "$linkmode" = "prog"; then compile_deplibs="$new_inherited_linker_flags $compile_deplibs" finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" else compiler_flags="$compiler_flags "`$ECHO "X $new_inherited_linker_flags" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` fi fi dependency_libs="$newdependency_libs" if test "$pass" = dlpreopen; then # Link the dlpreopened libraries before other libraries for deplib in $save_deplibs; do deplibs="$deplib $deplibs" done fi if test "$pass" != dlopen; then if test "$pass" != conv; then # Make sure lib_search_path contains only unique directories. lib_search_path= for dir in $newlib_search_path; do case "$lib_search_path " in *" $dir "*) ;; *) lib_search_path="$lib_search_path $dir" ;; esac done newlib_search_path= fi if test "$linkmode,$pass" != "prog,link"; then vars="deplibs" else vars="compile_deplibs finalize_deplibs" fi for var in $vars dependency_libs; do # Add libraries to $var in reverse order eval tmp_libs=\"\$$var\" new_libs= for deplib in $tmp_libs; do # FIXME: Pedantically, this is the right thing to do, so # that some nasty dependency loop isn't accidentally # broken: #new_libs="$deplib $new_libs" # Pragmatically, this seems to cause very few problems in # practice: case $deplib in -L*) new_libs="$deplib $new_libs" ;; -R*) ;; *) # And here is the reason: when a library appears more # than once as an explicit dependence of a library, or # is implicitly linked in more than once by the # compiler, it is considered special, and multiple # occurrences thereof are not removed. Compare this # with having the same library being listed as a # dependency of multiple other libraries: in this case, # we know (pedantically, we assume) the library does not # need to be listed more than once, so we keep only the # last copy. This is not always right, but it is rare # enough that we require users that really mean to play # such unportable linking tricks to link the library # using -Wl,-lname, so that libtool does not consider it # for duplicate removal. case " $specialdeplibs " in *" $deplib "*) new_libs="$deplib $new_libs" ;; *) case " $new_libs " in *" $deplib "*) ;; *) new_libs="$deplib $new_libs" ;; esac ;; esac ;; esac done tmp_libs= for deplib in $new_libs; do case $deplib in -L*) case " $tmp_libs " in *" $deplib "*) ;; *) tmp_libs="$tmp_libs $deplib" ;; esac ;; *) tmp_libs="$tmp_libs $deplib" ;; esac done eval $var=\"$tmp_libs\" done # for var fi # Last step: remove runtime libs from dependency_libs # (they stay in deplibs) tmp_libs= for i in $dependency_libs ; do case " $predeps $postdeps $compiler_lib_search_path " in *" $i "*) i="" ;; esac if test -n "$i" ; then tmp_libs="$tmp_libs $i" fi done dependency_libs=$tmp_libs done # for pass if test "$linkmode" = prog; then dlfiles="$newdlfiles" fi if test "$linkmode" = prog || test "$linkmode" = lib; then dlprefiles="$newdlprefiles" fi case $linkmode in oldlib) if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then func_warning "\`-dlopen' is ignored for archives" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "\`-l' and \`-L' are ignored for archives" ;; esac test -n "$rpath" && \ func_warning "\`-rpath' is ignored for archives" test -n "$xrpath" && \ func_warning "\`-R' is ignored for archives" test -n "$vinfo" && \ func_warning "\`-version-info/-version-number' is ignored for archives" test -n "$release" && \ func_warning "\`-release' is ignored for archives" test -n "$export_symbols$export_symbols_regex" && \ func_warning "\`-export-symbols' is ignored for archives" # Now set the variables for building old libraries. build_libtool_libs=no oldlibs="$output" objs="$objs$old_deplibs" ;; lib) # Make sure we only generate libraries of the form `libNAME.la'. case $outputname in lib*) func_stripname 'lib' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" ;; *) test "$module" = no && \ func_fatal_help "libtool library \`$output' must begin with \`lib'" if test "$need_lib_prefix" != no; then # Add the "lib" prefix for modules if required func_stripname '' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" else func_stripname '' '.la' "$outputname" libname=$func_stripname_result fi ;; esac if test -n "$objs"; then if test "$deplibs_check_method" != pass_all; then func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs" else $ECHO $ECHO "*** Warning: Linking the shared library $output against the non-libtool" $ECHO "*** objects $objs is not portable!" libobjs="$libobjs $objs" fi fi test "$dlself" != no && \ func_warning "\`-dlopen self' is ignored for libtool libraries" set dummy $rpath shift test "$#" -gt 1 && \ func_warning "ignoring multiple \`-rpath's for a libtool library" install_libdir="$1" oldlibs= if test -z "$rpath"; then if test "$build_libtool_libs" = yes; then # Building a libtool convenience library. # Some compilers have problems with a `.al' extension so # convenience libraries should have the same extension an # archive normally would. oldlibs="$output_objdir/$libname.$libext $oldlibs" build_libtool_libs=convenience build_old_libs=yes fi test -n "$vinfo" && \ func_warning "\`-version-info/-version-number' is ignored for convenience libraries" test -n "$release" && \ func_warning "\`-release' is ignored for convenience libraries" else # Parse the version information argument. save_ifs="$IFS"; IFS=':' set dummy $vinfo 0 0 0 shift IFS="$save_ifs" test -n "$7" && \ func_fatal_help "too many parameters to \`-version-info'" # convert absolute version numbers to libtool ages # this retains compatibility with .la files and attempts # to make the code below a bit more comprehensible case $vinfo_number in yes) number_major="$1" number_minor="$2" number_revision="$3" # # There are really only two kinds -- those that # use the current revision as the major version # and those that subtract age and use age as # a minor version. But, then there is irix # which has an extra 1 added just for fun # case $version_type in darwin|linux|osf|windows|none) func_arith $number_major + $number_minor current=$func_arith_result age="$number_minor" revision="$number_revision" ;; freebsd-aout|freebsd-elf|sunos) current="$number_major" revision="$number_minor" age="0" ;; irix|nonstopux) func_arith $number_major + $number_minor current=$func_arith_result age="$number_minor" revision="$number_minor" lt_irix_increment=no ;; esac ;; no) current="$1" revision="$2" age="$3" ;; esac # Check that each of the things are valid numbers. case $current in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "CURRENT \`$current' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac case $revision in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "REVISION \`$revision' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac case $age in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "AGE \`$age' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac if test "$age" -gt "$current"; then func_error "AGE \`$age' is greater than the current interface number \`$current'" func_fatal_error "\`$vinfo' is not valid version information" fi # Calculate the version variables. major= versuffix= verstring= case $version_type in none) ;; darwin) # Like Linux, but with the current version available in # verstring for coding it into the library header func_arith $current - $age major=.$func_arith_result versuffix="$major.$age.$revision" # Darwin ld doesn't like 0 for these options... func_arith $current + 1 minor_current=$func_arith_result xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision" verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" ;; freebsd-aout) major=".$current" versuffix=".$current.$revision"; ;; freebsd-elf) major=".$current" versuffix=".$current" ;; irix | nonstopux) if test "X$lt_irix_increment" = "Xno"; then func_arith $current - $age else func_arith $current - $age + 1 fi major=$func_arith_result case $version_type in nonstopux) verstring_prefix=nonstopux ;; *) verstring_prefix=sgi ;; esac verstring="$verstring_prefix$major.$revision" # Add in all the interfaces that we are compatible with. loop=$revision while test "$loop" -ne 0; do func_arith $revision - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring="$verstring_prefix$major.$iface:$verstring" done # Before this point, $major must not contain `.'. major=.$major versuffix="$major.$revision" ;; linux) func_arith $current - $age major=.$func_arith_result versuffix="$major.$age.$revision" ;; osf) func_arith $current - $age major=.$func_arith_result versuffix=".$current.$age.$revision" verstring="$current.$age.$revision" # Add in all the interfaces that we are compatible with. loop=$age while test "$loop" -ne 0; do func_arith $current - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring="$verstring:${iface}.0" done # Make executables depend on our current version. verstring="$verstring:${current}.0" ;; qnx) major=".$current" versuffix=".$current" ;; sunos) major=".$current" versuffix=".$current.$revision" ;; windows) # Use '-' rather than '.', since we only want one # extension on DOS 8.3 filesystems. func_arith $current - $age major=$func_arith_result versuffix="-$major" ;; *) func_fatal_configuration "unknown library version type \`$version_type'" ;; esac # Clear the version info if we defaulted, and they specified a release. if test -z "$vinfo" && test -n "$release"; then major= case $version_type in darwin) # we can't check for "0.0" in archive_cmds due to quoting # problems, so we reset it completely verstring= ;; *) verstring="0.0" ;; esac if test "$need_version" = no; then versuffix= else versuffix=".0.0" fi fi # Remove version info from name if versioning should be avoided if test "$avoid_version" = yes && test "$need_version" = no; then major= versuffix= verstring="" fi # Check to see if the archive will have undefined symbols. if test "$allow_undefined" = yes; then if test "$allow_undefined_flag" = unsupported; then func_warning "undefined symbols not allowed in $host shared libraries" build_libtool_libs=no build_old_libs=yes fi else # Don't allow undefined symbols. allow_undefined_flag="$no_undefined_flag" fi fi func_generate_dlsyms "$libname" "$libname" "yes" libobjs="$libobjs $symfileobj" test "X$libobjs" = "X " && libobjs= if test "$mode" != relink; then # Remove our outputs, but don't remove object files since they # may have been created when compiling PIC objects. removelist= tempremovelist=`$ECHO "$output_objdir/*"` for p in $tempremovelist; do case $p in *.$objext | *.gcno) ;; $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*) if test "X$precious_files_regex" != "X"; then if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 then continue fi fi removelist="$removelist $p" ;; *) ;; esac done test -n "$removelist" && \ func_show_eval "${RM}r \$removelist" fi # Now set the variables for building old libraries. if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then oldlibs="$oldlibs $output_objdir/$libname.$libext" # Transform .lo files to .o files. oldobjs="$objs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}'$/d' -e "$lo2o" | $NL2SP` fi # Eliminate all temporary directories. #for path in $notinst_path; do # lib_search_path=`$ECHO "X$lib_search_path " | $Xsed -e "s% $path % %g"` # deplibs=`$ECHO "X$deplibs " | $Xsed -e "s% -L$path % %g"` # dependency_libs=`$ECHO "X$dependency_libs " | $Xsed -e "s% -L$path % %g"` #done if test -n "$xrpath"; then # If the user specified any rpath flags, then add them. temp_xrpath= for libdir in $xrpath; do temp_xrpath="$temp_xrpath -R$libdir" case "$finalize_rpath " in *" $libdir "*) ;; *) finalize_rpath="$finalize_rpath $libdir" ;; esac done if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then dependency_libs="$temp_xrpath $dependency_libs" fi fi # Make sure dlfiles contains only unique files that won't be dlpreopened old_dlfiles="$dlfiles" dlfiles= for lib in $old_dlfiles; do case " $dlprefiles $dlfiles " in *" $lib "*) ;; *) dlfiles="$dlfiles $lib" ;; esac done # Make sure dlprefiles contains only unique files old_dlprefiles="$dlprefiles" dlprefiles= for lib in $old_dlprefiles; do case "$dlprefiles " in *" $lib "*) ;; *) dlprefiles="$dlprefiles $lib" ;; esac done if test "$build_libtool_libs" = yes; then if test -n "$rpath"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc*) # these systems don't actually have a c library (as such)! ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C library is in the System framework deplibs="$deplibs System.ltframework" ;; *-*-netbsd*) # Don't link with libc until the a.out ld.so is fixed. ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work ;; *) # Add libc to deplibs on all other systems if necessary. if test "$build_libtool_need_lc" = "yes"; then deplibs="$deplibs -lc" fi ;; esac fi # Transform deplibs into only deplibs that can be linked in shared. name_save=$name libname_save=$libname release_save=$release versuffix_save=$versuffix major_save=$major # I'm not sure if I'm treating the release correctly. I think # release should show up in the -l (ie -lgmp5) so we don't want to # add it in twice. Is that correct? release="" versuffix="" major="" newdeplibs= droppeddeps=no case $deplibs_check_method in pass_all) # Don't check for shared/static. Everything works. # This might be a little naive. We might want to check # whether the library exists or not. But this is on # osf3 & osf4 and I'm not really sure... Just # implementing what was already the behavior. newdeplibs=$deplibs ;; test_compile) # This code stresses the "libraries are programs" paradigm to its # limits. Maybe even breaks it. We compile a program, linking it # against the deplibs as a proxy for the library. Then we can check # whether they linked in statically or dynamically with ldd. $opt_dry_run || $RM conftest.c cat > conftest.c <<EOF int main() { return 0; } EOF $opt_dry_run || $RM conftest if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then ldd_output=`ldd conftest` for i in $deplibs; do case $i in -l*) func_stripname -l '' "$i" name=$func_stripname_result if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $i "*) newdeplibs="$newdeplibs $i" i="" ;; esac fi if test -n "$i" ; then libname=`eval "\\$ECHO \"$libname_spec\""` deplib_matches=`eval "\\$ECHO \"$library_names_spec\""` set dummy $deplib_matches; shift deplib_match=$1 if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then newdeplibs="$newdeplibs $i" else droppeddeps=yes $ECHO $ECHO "*** Warning: dynamic linker does not accept needed library $i." $ECHO "*** I have the capability to make that library automatically link in when" $ECHO "*** you link to this library. But I can only do this if you have a" $ECHO "*** shared version of the library, which I believe you do not have" $ECHO "*** because a test_compile did reveal that the linker did not use it for" $ECHO "*** its dynamic dependency list that programs get resolved with at runtime." fi fi ;; *) newdeplibs="$newdeplibs $i" ;; esac done else # Error occurred in the first compile. Let's try to salvage # the situation: Compile a separate program for each library. for i in $deplibs; do case $i in -l*) func_stripname -l '' "$i" name=$func_stripname_result $opt_dry_run || $RM conftest if $LTCC $LTCFLAGS -o conftest conftest.c $i; then ldd_output=`ldd conftest` if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $i "*) newdeplibs="$newdeplibs $i" i="" ;; esac fi if test -n "$i" ; then libname=`eval "\\$ECHO \"$libname_spec\""` deplib_matches=`eval "\\$ECHO \"$library_names_spec\""` set dummy $deplib_matches; shift deplib_match=$1 if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then newdeplibs="$newdeplibs $i" else droppeddeps=yes $ECHO $ECHO "*** Warning: dynamic linker does not accept needed library $i." $ECHO "*** I have the capability to make that library automatically link in when" $ECHO "*** you link to this library. But I can only do this if you have a" $ECHO "*** shared version of the library, which you do not appear to have" $ECHO "*** because a test_compile did reveal that the linker did not use this one" $ECHO "*** as a dynamic dependency that programs can get resolved with at runtime." fi fi else droppeddeps=yes $ECHO $ECHO "*** Warning! Library $i is needed by this library but I was not able to" $ECHO "*** make it link in! You will probably need to install it or some" $ECHO "*** library that it depends on before this library will be fully" $ECHO "*** functional. Installing it before continuing would be even better." fi ;; *) newdeplibs="$newdeplibs $i" ;; esac done fi ;; file_magic*) set dummy $deplibs_check_method; shift file_magic_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` for a_deplib in $deplibs; do case $a_deplib in -l*) func_stripname -l '' "$a_deplib" name=$func_stripname_result if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $a_deplib "*) newdeplibs="$newdeplibs $a_deplib" a_deplib="" ;; esac fi if test -n "$a_deplib" ; then libname=`eval "\\$ECHO \"$libname_spec\""` for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do potential_libs=`ls $i/$libname[.-]* 2>/dev/null` for potent_lib in $potential_libs; do # Follow soft links. if ls -lLd "$potent_lib" 2>/dev/null | $GREP " -> " >/dev/null; then continue fi # The statement above tries to avoid entering an # endless loop below, in case of cyclic links. # We might still enter an endless loop, since a link # loop can be closed while we follow links, # but so what? potlib="$potent_lib" while test -h "$potlib" 2>/dev/null; do potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'` case $potliblink in [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";; *) potlib=`$ECHO "X$potlib" | $Xsed -e 's,[^/]*$,,'`"$potliblink";; esac done if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | $SED -e 10q | $EGREP "$file_magic_regex" > /dev/null; then newdeplibs="$newdeplibs $a_deplib" a_deplib="" break 2 fi done done fi if test -n "$a_deplib" ; then droppeddeps=yes $ECHO $ECHO "*** Warning: linker path does not have real file for library $a_deplib." $ECHO "*** I have the capability to make that library automatically link in when" $ECHO "*** you link to this library. But I can only do this if you have a" $ECHO "*** shared version of the library, which you do not appear to have" $ECHO "*** because I did check the linker path looking for a file starting" if test -z "$potlib" ; then $ECHO "*** with $libname but no candidates were found. (...for file magic test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a file magic. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. newdeplibs="$newdeplibs $a_deplib" ;; esac done # Gone through all deplibs. ;; match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` for a_deplib in $deplibs; do case $a_deplib in -l*) func_stripname -l '' "$a_deplib" name=$func_stripname_result if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $a_deplib "*) newdeplibs="$newdeplibs $a_deplib" a_deplib="" ;; esac fi if test -n "$a_deplib" ; then libname=`eval "\\$ECHO \"$libname_spec\""` for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do potential_libs=`ls $i/$libname[.-]* 2>/dev/null` for potent_lib in $potential_libs; do potlib="$potent_lib" # see symlink-check above in file_magic test if eval "\$ECHO \"X$potent_lib\"" 2>/dev/null | $Xsed -e 10q | \ $EGREP "$match_pattern_regex" > /dev/null; then newdeplibs="$newdeplibs $a_deplib" a_deplib="" break 2 fi done done fi if test -n "$a_deplib" ; then droppeddeps=yes $ECHO $ECHO "*** Warning: linker path does not have real file for library $a_deplib." $ECHO "*** I have the capability to make that library automatically link in when" $ECHO "*** you link to this library. But I can only do this if you have a" $ECHO "*** shared version of the library, which you do not appear to have" $ECHO "*** because I did check the linker path looking for a file starting" if test -z "$potlib" ; then $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a regex pattern. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. newdeplibs="$newdeplibs $a_deplib" ;; esac done # Gone through all deplibs. ;; none | unknown | *) newdeplibs="" tmp_deplibs=`$ECHO "X $deplibs" | $Xsed \ -e 's/ -lc$//' -e 's/ -[LR][^ ]*//g'` if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then for i in $predeps $postdeps ; do # can't use Xsed below, because $i might contain '/' tmp_deplibs=`$ECHO "X $tmp_deplibs" | $Xsed -e "s,$i,,"` done fi if $ECHO "X $tmp_deplibs" | $Xsed -e 's/[ ]//g' | $GREP . >/dev/null; then $ECHO if test "X$deplibs_check_method" = "Xnone"; then $ECHO "*** Warning: inter-library dependencies are not supported in this platform." else $ECHO "*** Warning: inter-library dependencies are not known to be supported." fi $ECHO "*** All declared inter-library dependencies are being dropped." droppeddeps=yes fi ;; esac versuffix=$versuffix_save major=$major_save release=$release_save libname=$libname_save name=$name_save case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library with the System framework newdeplibs=`$ECHO "X $newdeplibs" | $Xsed -e 's/ -lc / System.ltframework /'` ;; esac if test "$droppeddeps" = yes; then if test "$module" = yes; then $ECHO $ECHO "*** Warning: libtool could not satisfy all declared inter-library" $ECHO "*** dependencies of module $libname. Therefore, libtool will create" $ECHO "*** a static module, that should work as long as the dlopening" $ECHO "*** application is linked with the -dlopen flag." if test -z "$global_symbol_pipe"; then $ECHO $ECHO "*** However, this would only work if libtool was able to extract symbol" $ECHO "*** lists from a program, using \`nm' or equivalent, but libtool could" $ECHO "*** not find such a program. So, this module is probably useless." $ECHO "*** \`nm' from GNU binutils and a full rebuild may help." fi if test "$build_old_libs" = no; then oldlibs="$output_objdir/$libname.$libext" build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi else $ECHO "*** The inter-library dependencies that have been dropped here will be" $ECHO "*** automatically added whenever a program is linked with this library" $ECHO "*** or is declared to -dlopen it." if test "$allow_undefined" = no; then $ECHO $ECHO "*** Since this library must not contain undefined symbols," $ECHO "*** because either the platform does not support them or" $ECHO "*** it was explicitly requested with -no-undefined," $ECHO "*** libtool will only create a static version of it." if test "$build_old_libs" = no; then oldlibs="$output_objdir/$libname.$libext" build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi fi fi # Done checking deplibs! deplibs=$newdeplibs fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" case $host in *-*-darwin*) newdeplibs=`$ECHO "X $newdeplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` new_inherited_linker_flags=`$ECHO "X $new_inherited_linker_flags" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` deplibs=`$ECHO "X $deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $deplibs " in *" -L$path/$objdir "*) new_libs="$new_libs -L$path/$objdir" ;; esac ;; esac done for deplib in $deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) new_libs="$new_libs $deplib" ;; esac ;; *) new_libs="$new_libs $deplib" ;; esac done deplibs="$new_libs" # All the library-specific variables (install_libdir is set above). library_names= old_library= dlname= # Test again, we may have decided not to build it any more if test "$build_libtool_libs" = yes; then if test "$hardcode_into_libs" = yes; then # Hardcode the library paths hardcode_libdirs= dep_rpath= rpath="$finalize_rpath" test "$mode" != relink && rpath="$compile_rpath$rpath" for libdir in $rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" dep_rpath="$dep_rpath $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) perm_rpath="$perm_rpath $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" if test -n "$hardcode_libdir_flag_spec_ld"; then eval dep_rpath=\"$hardcode_libdir_flag_spec_ld\" else eval dep_rpath=\"$hardcode_libdir_flag_spec\" fi fi if test -n "$runpath_var" && test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do rpath="$rpath$dir:" done eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" fi test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" fi shlibpath="$finalize_shlibpath" test "$mode" != relink && shlibpath="$compile_shlibpath$shlibpath" if test -n "$shlibpath"; then eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" fi # Get the real and link names of the library. eval shared_ext=\"$shrext_cmds\" eval library_names=\"$library_names_spec\" set dummy $library_names shift realname="$1" shift if test -n "$soname_spec"; then eval soname=\"$soname_spec\" else soname="$realname" fi if test -z "$dlname"; then dlname=$soname fi lib="$output_objdir/$realname" linknames= for link do linknames="$linknames $link" done # Use standard objects if they are pic test -z "$pic_flag" && libobjs=`$ECHO "X$libobjs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` test "X$libobjs" = "X " && libobjs= delfiles= if test -n "$export_symbols" && test -n "$include_expsyms"; then $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" export_symbols="$output_objdir/$libname.uexp" delfiles="$delfiles $export_symbols" fi orig_export_symbols= case $host_os in cygwin* | mingw* | cegcc*) if test -n "$export_symbols" && test -z "$export_symbols_regex"; then # exporting using user supplied symfile if test "x`$SED 1q $export_symbols`" != xEXPORTS; then # and it's NOT already a .def file. Must figure out # which of the given symbols are data symbols and tag # them as such. So, trigger use of export_symbols_cmds. # export_symbols gets reassigned inside the "prepare # the list of exported symbols" if statement, so the # include_expsyms logic still works. orig_export_symbols="$export_symbols" export_symbols= always_export_symbols=yes fi fi ;; esac # Prepare the list of exported symbols if test -z "$export_symbols"; then if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then func_verbose "generating symbol list for \`$libname.la'" export_symbols="$output_objdir/$libname.exp" $opt_dry_run || $RM $export_symbols cmds=$export_symbols_cmds save_ifs="$IFS"; IFS='~' for cmd in $cmds; do IFS="$save_ifs" eval cmd=\"$cmd\" func_len " $cmd" len=$func_len_result if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then func_show_eval "$cmd" 'exit $?' skipped_export=false else # The command line is too long to execute in one step. func_verbose "using reloadable object file for export list..." skipped_export=: # Break out early, otherwise skipped_export may be # set to false by a later but shorter cmd. break fi done IFS="$save_ifs" if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi fi if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols="$export_symbols" test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" $opt_dry_run || eval '$ECHO "X$include_expsyms" | $Xsed | $SP2NL >> "$tmp_export_symbols"' fi if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter delfiles="$delfiles $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi tmp_deplibs= for test_deplib in $deplibs; do case " $convenience " in *" $test_deplib "*) ;; *) tmp_deplibs="$tmp_deplibs $test_deplib" ;; esac done deplibs="$tmp_deplibs" if test -n "$convenience"; then if test -n "$whole_archive_flag_spec" && test "$compiler_needs_object" = yes && test -z "$libobjs"; then # extract the archives, so we have objects to list. # TODO: could optimize this to just extract one archive. whole_archive_flag_spec= fi if test -n "$whole_archive_flag_spec"; then save_libobjs=$libobjs eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= else gentop="$output_objdir/${outputname}x" generated="$generated $gentop" func_extract_archives $gentop $convenience libobjs="$libobjs $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi fi if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then eval flag=\"$thread_safe_flag_spec\" linker_flags="$linker_flags $flag" fi # Make a backup of the uninstalled library when relinking if test "$mode" = relink; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? fi # Do each of the archive commands. if test "$module" = yes && test -n "$module_cmds" ; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then eval test_cmds=\"$module_expsym_cmds\" cmds=$module_expsym_cmds else eval test_cmds=\"$module_cmds\" cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then eval test_cmds=\"$archive_expsym_cmds\" cmds=$archive_expsym_cmds else eval test_cmds=\"$archive_cmds\" cmds=$archive_cmds fi fi if test "X$skipped_export" != "X:" && func_len " $test_cmds" && len=$func_len_result && test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then : else # The command line is too long to link in one step, link piecewise # or, if using GNU ld and skipped_export is not :, use a linker # script. # Save the value of $output and $libobjs because we want to # use them later. If we have whole_archive_flag_spec, we # want to use save_libobjs as it was before # whole_archive_flag_spec was expanded, because we can't # assume the linker understands whole_archive_flag_spec. # This may have to be revisited, in case too many # convenience libraries get linked in and end up exceeding # the spec. if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then save_libobjs=$libobjs fi save_output=$output output_la=`$ECHO "X$output" | $Xsed -e "$basename"` # Clear the reloadable object creation command queue and # initialize k to one. test_cmds= concat_cmds= objlist= last_robj= k=1 if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then output=${output_objdir}/${output_la}.lnkscript func_verbose "creating GNU ld script: $output" $ECHO 'INPUT (' > $output for obj in $save_libobjs do $ECHO "$obj" >> $output done $ECHO ')' >> $output delfiles="$delfiles $output" elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then output=${output_objdir}/${output_la}.lnk func_verbose "creating linker input file list: $output" : > $output set x $save_libobjs shift firstobj= if test "$compiler_needs_object" = yes; then firstobj="$1 " shift fi for obj do $ECHO "$obj" >> $output done delfiles="$delfiles $output" output=$firstobj\"$file_list_spec$output\" else if test -n "$save_libobjs"; then func_verbose "creating reloadable object files..." output=$output_objdir/$output_la-${k}.$objext eval test_cmds=\"$reload_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 # Loop over the list of objects to be linked. for obj in $save_libobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result if test "X$objlist" = X || test "$len" -lt "$max_cmd_len"; then func_append objlist " $obj" else # The command $test_cmds is almost too long, add a # command to the queue. if test "$k" -eq 1 ; then # The first file doesn't have a previous command to add. eval concat_cmds=\"$reload_cmds $objlist $last_robj\" else # All subsequent reloadable object files will link in # the last one created. eval concat_cmds=\"\$concat_cmds~$reload_cmds $objlist $last_robj~\$RM $last_robj\" fi last_robj=$output_objdir/$output_la-${k}.$objext func_arith $k + 1 k=$func_arith_result output=$output_objdir/$output_la-${k}.$objext objlist=$obj func_len " $last_robj" func_arith $len0 + $func_len_result len=$func_arith_result fi done # Handle the remaining objects by creating one last # reloadable object file. All subsequent reloadable object # files will link in the last one created. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\${concat_cmds}$reload_cmds $objlist $last_robj\" if test -n "$last_robj"; then eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\" fi delfiles="$delfiles $output" else output= fi if ${skipped_export-false}; then func_verbose "generating symbol list for \`$libname.la'" export_symbols="$output_objdir/$libname.exp" $opt_dry_run || $RM $export_symbols libobjs=$output # Append the command to create the export file. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" fi fi test -n "$save_libobjs" && func_verbose "creating a temporary reloadable object file: $output" # Loop through the commands generated above and execute them. save_ifs="$IFS"; IFS='~' for cmd in $concat_cmds; do IFS="$save_ifs" $opt_silent || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test "$mode" = relink; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS="$save_ifs" if test -n "$export_symbols_regex" && ${skipped_export-false}; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi if ${skipped_export-false}; then if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols="$export_symbols" test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" $opt_dry_run || eval '$ECHO "X$include_expsyms" | $Xsed | $SP2NL >> "$tmp_export_symbols"' fi if test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter delfiles="$delfiles $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi fi libobjs=$output # Restore the value of output. output=$save_output if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= fi # Expand the library linking commands again to reset the # value of $libobjs for piecewise linking. # Do each of the archive commands. if test "$module" = yes && test -n "$module_cmds" ; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then cmds=$module_expsym_cmds else cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then cmds=$archive_expsym_cmds else cmds=$archive_cmds fi fi fi if test -n "$delfiles"; then # Append the command to remove temporary files to $cmds. eval cmds=\"\$cmds~\$RM $delfiles\" fi # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop="$output_objdir/${outputname}x" generated="$generated $gentop" func_extract_archives $gentop $dlprefiles libobjs="$libobjs $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi save_ifs="$IFS"; IFS='~' for cmd in $cmds; do IFS="$save_ifs" eval cmd=\"$cmd\" $opt_silent || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test "$mode" = relink; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS="$save_ifs" # Restore the uninstalled library and exit if test "$mode" = relink; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? if test -n "$convenience"; then if test -z "$whole_archive_flag_spec"; then func_show_eval '${RM}r "$gentop"' fi fi exit $EXIT_SUCCESS fi # Create links to the real library. for linkname in $linknames; do if test "$realname" != "$linkname"; then func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' fi done # If -module or -export-dynamic was specified, set the dlname. if test "$module" = yes || test "$export_dynamic" = yes; then # On all known operating systems, these are identical. dlname="$soname" fi fi ;; obj) if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then func_warning "\`-dlopen' is ignored for objects" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "\`-l' and \`-L' are ignored for objects" ;; esac test -n "$rpath" && \ func_warning "\`-rpath' is ignored for objects" test -n "$xrpath" && \ func_warning "\`-R' is ignored for objects" test -n "$vinfo" && \ func_warning "\`-version-info' is ignored for objects" test -n "$release" && \ func_warning "\`-release' is ignored for objects" case $output in *.lo) test -n "$objs$old_deplibs" && \ func_fatal_error "cannot build library object \`$output' from non-libtool objects" libobj=$output func_lo2o "$libobj" obj=$func_lo2o_result ;; *) libobj= obj="$output" ;; esac # Delete the old objects. $opt_dry_run || $RM $obj $libobj # Objects from convenience libraries. This assumes # single-version convenience libraries. Whenever we create # different ones for PIC/non-PIC, this we'll have to duplicate # the extraction. reload_conv_objs= gentop= # reload_cmds runs $LD directly, so let us get rid of # -Wl from whole_archive_flag_spec and hope we can get by with # turning comma into space.. wl= if test -n "$convenience"; then if test -n "$whole_archive_flag_spec"; then eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" reload_conv_objs=$reload_objs\ `$ECHO "X$tmp_whole_archive_flags" | $Xsed -e 's|,| |g'` else gentop="$output_objdir/${obj}x" generated="$generated $gentop" func_extract_archives $gentop $convenience reload_conv_objs="$reload_objs $func_extract_archives_result" fi fi # Create the old-style object. reload_objs="$objs$old_deplibs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}$'/d' -e '/\.lib$/d' -e "$lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test output="$obj" func_execute_cmds "$reload_cmds" 'exit $?' # Exit if we aren't doing a library object file. if test -z "$libobj"; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS fi if test "$build_libtool_libs" != yes; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi # Create an invalid libtool object if no PIC, so that we don't # accidentally link it into a program. # $show "echo timestamp > $libobj" # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? exit $EXIT_SUCCESS fi if test -n "$pic_flag" || test "$pic_mode" != default; then # Only do commands if we really have different PIC objects. reload_objs="$libobjs $reload_conv_objs" output="$libobj" func_execute_cmds "$reload_cmds" 'exit $?' fi if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS ;; prog) case $host in *cygwin*) func_stripname '' '.exe' "$output" output=$func_stripname_result.exe;; esac test -n "$vinfo" && \ func_warning "\`-version-info' is ignored for programs" test -n "$release" && \ func_warning "\`-release' is ignored for programs" test "$preload" = yes \ && test "$dlopen_support" = unknown \ && test "$dlopen_self" = unknown \ && test "$dlopen_self_static" = unknown && \ func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support." case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library is the System framework compile_deplibs=`$ECHO "X $compile_deplibs" | $Xsed -e 's/ -lc / System.ltframework /'` finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e 's/ -lc / System.ltframework /'` ;; esac case $host in *-*-darwin*) # Don't allow lazy linking, it breaks C++ global constructors # But is supposedly fixed on 10.4 or later (yay!). if test "$tagname" = CXX ; then case ${MACOSX_DEPLOYMENT_TARGET-10.0} in 10.[0123]) compile_command="$compile_command ${wl}-bind_at_load" finalize_command="$finalize_command ${wl}-bind_at_load" ;; esac fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" compile_deplibs=`$ECHO "X $compile_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $compile_deplibs " in *" -L$path/$objdir "*) new_libs="$new_libs -L$path/$objdir" ;; esac ;; esac done for deplib in $compile_deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) new_libs="$new_libs $deplib" ;; esac ;; *) new_libs="$new_libs $deplib" ;; esac done compile_deplibs="$new_libs" compile_command="$compile_command $compile_deplibs" finalize_command="$finalize_command $finalize_deplibs" if test -n "$rpath$xrpath"; then # If the user specified any rpath flags, then add them. for libdir in $rpath $xrpath; do # This is the magic to use -rpath. case "$finalize_rpath " in *" $libdir "*) ;; *) finalize_rpath="$finalize_rpath $libdir" ;; esac done fi # Now hardcode the library paths rpath= hardcode_libdirs= for libdir in $compile_rpath $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" rpath="$rpath $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) perm_rpath="$perm_rpath $libdir" ;; esac fi case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'` case :$dllsearchpath: in *":$libdir:"*) ;; ::) dllsearchpath=$libdir;; *) dllsearchpath="$dllsearchpath:$libdir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) dllsearchpath="$dllsearchpath:$testbindir";; esac ;; esac done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval rpath=\" $hardcode_libdir_flag_spec\" fi compile_rpath="$rpath" rpath= hardcode_libdirs= for libdir in $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" rpath="$rpath $flag" fi elif test -n "$runpath_var"; then case "$finalize_perm_rpath " in *" $libdir "*) ;; *) finalize_perm_rpath="$finalize_perm_rpath $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval rpath=\" $hardcode_libdir_flag_spec\" fi finalize_rpath="$rpath" if test -n "$libobjs" && test "$build_old_libs" = yes; then # Transform all the library objects into standard objects. compile_command=`$ECHO "X$compile_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` finalize_command=`$ECHO "X$finalize_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` fi func_generate_dlsyms "$outputname" "@PROGRAM@" "no" # template prelinking step if test -n "$prelink_cmds"; then func_execute_cmds "$prelink_cmds" 'exit $?' fi wrappers_required=yes case $host in *cygwin* | *mingw* ) if test "$build_libtool_libs" != yes; then wrappers_required=no fi ;; *cegcc) # Disable wrappers for cegcc, we are cross compiling anyway. wrappers_required=no ;; *) if test "$need_relink" = no || test "$build_libtool_libs" != yes; then wrappers_required=no fi ;; esac if test "$wrappers_required" = no; then # Replace the output file specification. compile_command=`$ECHO "X$compile_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` link_command="$compile_command$compile_rpath" # We have no uninstalled library dependencies, so finalize right now. exit_status=0 func_show_eval "$link_command" 'exit_status=$?' # Delete the generated files. if test -f "$output_objdir/${outputname}S.${objext}"; then func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"' fi exit $exit_status fi if test -n "$compile_shlibpath$finalize_shlibpath"; then compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" fi if test -n "$finalize_shlibpath"; then finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" fi compile_var= finalize_var= if test -n "$runpath_var"; then if test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do rpath="$rpath$dir:" done compile_var="$runpath_var=\"$rpath\$$runpath_var\" " fi if test -n "$finalize_perm_rpath"; then # We should set the runpath_var. rpath= for dir in $finalize_perm_rpath; do rpath="$rpath$dir:" done finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " fi fi if test "$no_install" = yes; then # We don't need to create a wrapper script. link_command="$compile_var$compile_command$compile_rpath" # Replace the output file specification. link_command=`$ECHO "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` # Delete the old output file. $opt_dry_run || $RM $output # Link the executable and exit func_show_eval "$link_command" 'exit $?' exit $EXIT_SUCCESS fi if test "$hardcode_action" = relink; then # Fast installation is not supported link_command="$compile_var$compile_command$compile_rpath" relink_command="$finalize_var$finalize_command$finalize_rpath" func_warning "this platform does not like uninstalled shared libraries" func_warning "\`$output' will be relinked during installation" else if test "$fast_install" != no; then link_command="$finalize_var$compile_command$finalize_rpath" if test "$fast_install" = yes; then relink_command=`$ECHO "X$compile_var$compile_command$compile_rpath" | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g'` else # fast_install is set to needless relink_command= fi else link_command="$compile_var$compile_command$compile_rpath" relink_command="$finalize_var$finalize_command$finalize_rpath" fi fi # Replace the output file specification. link_command=`$ECHO "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` # Delete the old output files. $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname func_show_eval "$link_command" 'exit $?' # Now create the wrapper script. func_verbose "creating $output" # Quote the relink command for shipping. if test -n "$relink_command"; then # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done relink_command="(cd `pwd`; $relink_command)" relink_command=`$ECHO "X$relink_command" | $Xsed -e "$sed_quote_subst"` fi # Quote $ECHO for shipping. if test "X$ECHO" = "X$SHELL $progpath --fallback-echo"; then case $progpath in [\\/]* | [A-Za-z]:[\\/]*) qecho="$SHELL $progpath --fallback-echo";; *) qecho="$SHELL `pwd`/$progpath --fallback-echo";; esac qecho=`$ECHO "X$qecho" | $Xsed -e "$sed_quote_subst"` else qecho=`$ECHO "X$ECHO" | $Xsed -e "$sed_quote_subst"` fi # Only actually do things if not in dry run mode. $opt_dry_run || { # win32 will think the script is a binary if it has # a .exe suffix, so we strip it off here. case $output in *.exe) func_stripname '' '.exe' "$output" output=$func_stripname_result ;; esac # test for cygwin because mv fails w/o .exe extensions case $host in *cygwin*) exeext=.exe func_stripname '' '.exe' "$outputname" outputname=$func_stripname_result ;; *) exeext= ;; esac case $host in *cygwin* | *mingw* ) func_dirname_and_basename "$output" "" "." output_name=$func_basename_result output_path=$func_dirname_result cwrappersource="$output_path/$objdir/lt-$output_name.c" cwrapper="$output_path/$output_name.exe" $RM $cwrappersource $cwrapper trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 func_emit_cwrapperexe_src > $cwrappersource # The wrapper executable is built using the $host compiler, # because it contains $host paths and files. If cross- # compiling, it, like the target executable, must be # executed on the $host or under an emulation environment. $opt_dry_run || { $LTCC $LTCFLAGS -o $cwrapper $cwrappersource $STRIP $cwrapper } # Now, create the wrapper script for func_source use: func_ltwrapper_scriptname $cwrapper $RM $func_ltwrapper_scriptname_result trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 $opt_dry_run || { # note: this script will not be executed, so do not chmod. if test "x$build" = "x$host" ; then $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result else func_emit_wrapper no > $func_ltwrapper_scriptname_result fi } ;; * ) $RM $output trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 func_emit_wrapper no > $output chmod +x $output ;; esac } exit $EXIT_SUCCESS ;; esac # See if we need to build an old-fashioned archive. for oldlib in $oldlibs; do if test "$build_libtool_libs" = convenience; then oldobjs="$libobjs_save $symfileobj" addlibs="$convenience" build_libtool_libs=no else if test "$build_libtool_libs" = module; then oldobjs="$libobjs_save" build_libtool_libs=no else oldobjs="$old_deplibs $non_pic_objects" if test "$preload" = yes && test -f "$symfileobj"; then oldobjs="$oldobjs $symfileobj" fi fi addlibs="$old_convenience" fi if test -n "$addlibs"; then gentop="$output_objdir/${outputname}x" generated="$generated $gentop" func_extract_archives $gentop $addlibs oldobjs="$oldobjs $func_extract_archives_result" fi # Do each command in the archive commands. if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then cmds=$old_archive_from_new_cmds else # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop="$output_objdir/${outputname}x" generated="$generated $gentop" func_extract_archives $gentop $dlprefiles oldobjs="$oldobjs $func_extract_archives_result" fi # POSIX demands no paths to be encoded in archives. We have # to avoid creating archives with duplicate basenames if we # might have to extract them afterwards, e.g., when creating a # static archive out of a convenience library, or when linking # the entirety of a libtool archive into another (currently # not supported by libtool). if (for obj in $oldobjs do func_basename "$obj" $ECHO "$func_basename_result" done | sort | sort -uc >/dev/null 2>&1); then : else $ECHO "copying selected object files to avoid basename conflicts..." gentop="$output_objdir/${outputname}x" generated="$generated $gentop" func_mkdir_p "$gentop" save_oldobjs=$oldobjs oldobjs= counter=1 for obj in $save_oldobjs do func_basename "$obj" objbase="$func_basename_result" case " $oldobjs " in " ") oldobjs=$obj ;; *[\ /]"$objbase "*) while :; do # Make sure we don't pick an alternate name that also # overlaps. newobj=lt$counter-$objbase func_arith $counter + 1 counter=$func_arith_result case " $oldobjs " in *[\ /]"$newobj "*) ;; *) if test ! -f "$gentop/$newobj"; then break; fi ;; esac done func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" oldobjs="$oldobjs $gentop/$newobj" ;; *) oldobjs="$oldobjs $obj" ;; esac done fi eval cmds=\"$old_archive_cmds\" func_len " $cmds" len=$func_len_result if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then cmds=$old_archive_cmds else # the command line is too long to link in one step, link in parts func_verbose "using piecewise archive linking..." save_RANLIB=$RANLIB RANLIB=: objlist= concat_cmds= save_oldobjs=$oldobjs oldobjs= # Is there a better way of finding the last object in the list? for obj in $save_oldobjs do last_oldobj=$obj done eval test_cmds=\"$old_archive_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 for obj in $save_oldobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result func_append objlist " $obj" if test "$len" -lt "$max_cmd_len"; then : else # the above command should be used before it gets too long oldobjs=$objlist if test "$obj" = "$last_oldobj" ; then RANLIB=$save_RANLIB fi test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\" objlist= len=$len0 fi done RANLIB=$save_RANLIB oldobjs=$objlist if test "X$oldobjs" = "X" ; then eval cmds=\"\$concat_cmds\" else eval cmds=\"\$concat_cmds~\$old_archive_cmds\" fi fi fi func_execute_cmds "$cmds" 'exit $?' done test -n "$generated" && \ func_show_eval "${RM}r$generated" # Now create the libtool archive. case $output in *.la) old_library= test "$build_old_libs" = yes && old_library="$libname.$libext" func_verbose "creating $output" # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done # Quote the link command for shipping. relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" relink_command=`$ECHO "X$relink_command" | $Xsed -e "$sed_quote_subst"` if test "$hardcode_automatic" = yes ; then relink_command= fi # Only create the output if not a dry run. $opt_dry_run || { for installed in no yes; do if test "$installed" = yes; then if test -z "$install_libdir"; then break fi output="$output_objdir/$outputname"i # Replace all uninstalled libtool libraries with the installed ones newdependency_libs= for deplib in $dependency_libs; do case $deplib in *.la) func_basename "$deplib" name="$func_basename_result" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` test -z "$libdir" && \ func_fatal_error "\`$deplib' is not a valid libtool archive" newdependency_libs="$newdependency_libs $libdir/$name" ;; *) newdependency_libs="$newdependency_libs $deplib" ;; esac done dependency_libs="$newdependency_libs" newdlfiles= for lib in $dlfiles; do case $lib in *.la) func_basename "$lib" name="$func_basename_result" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "\`$lib' is not a valid libtool archive" newdlfiles="$newdlfiles $libdir/$name" ;; *) newdlfiles="$newdlfiles $lib" ;; esac done dlfiles="$newdlfiles" newdlprefiles= for lib in $dlprefiles; do case $lib in *.la) # Only pass preopened files to the pseudo-archive (for # eventual linking with the app. that links it) if we # didn't already link the preopened objects directly into # the library: func_basename "$lib" name="$func_basename_result" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "\`$lib' is not a valid libtool archive" newdlprefiles="$newdlprefiles $libdir/$name" ;; esac done dlprefiles="$newdlprefiles" else newdlfiles= for lib in $dlfiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; *) abs=`pwd`"/$lib" ;; esac newdlfiles="$newdlfiles $abs" done dlfiles="$newdlfiles" newdlprefiles= for lib in $dlprefiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; *) abs=`pwd`"/$lib" ;; esac newdlprefiles="$newdlprefiles $abs" done dlprefiles="$newdlprefiles" fi $RM $output # place dlname in correct position for cygwin tdlname=$dlname case $host,$output,$installed,$module,$dlname in *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) tdlname=../bin/$dlname ;; esac $ECHO > $output "\ # $outputname - a libtool library file # Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION # # Please DO NOT delete this file! # It is necessary for linking the library. # The name that we can dlopen(3). dlname='$tdlname' # Names of this library. library_names='$library_names' # The name of the static archive. old_library='$old_library' # Linker flags that can not go in dependency_libs. inherited_linker_flags='$new_inherited_linker_flags' # Libraries that this one depends upon. dependency_libs='$dependency_libs' # Names of additional weak libraries provided by this library weak_library_names='$weak_libs' # Version information for $libname. current=$current age=$age revision=$revision # Is this an already installed library? installed=$installed # Should we warn about portability when linking against -modules? shouldnotlink=$module # Files to dlopen/dlpreopen dlopen='$dlfiles' dlpreopen='$dlprefiles' # Directory that this library needs to be installed in: libdir='$install_libdir'" if test "$installed" = no && test "$need_relink" = yes; then $ECHO >> $output "\ relink_command=\"$relink_command\"" fi done } # Do a symbolic link so that the libtool archive can be found in # LD_LIBRARY_PATH before the program is installed. func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' ;; esac exit $EXIT_SUCCESS } { test "$mode" = link || test "$mode" = relink; } && func_mode_link ${1+"$@"} # func_mode_uninstall arg... func_mode_uninstall () { $opt_debug RM="$nonopt" files= rmforce= exit_status=0 # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic="$magic" for arg do case $arg in -f) RM="$RM $arg"; rmforce=yes ;; -*) RM="$RM $arg" ;; *) files="$files $arg" ;; esac done test -z "$RM" && \ func_fatal_help "you must specify an RM program" rmdirs= origobjdir="$objdir" for file in $files; do func_dirname "$file" "" "." dir="$func_dirname_result" if test "X$dir" = X.; then objdir="$origobjdir" else objdir="$dir/$origobjdir" fi func_basename "$file" name="$func_basename_result" test "$mode" = uninstall && objdir="$dir" # Remember objdir for removal later, being careful to avoid duplicates if test "$mode" = clean; then case " $rmdirs " in *" $objdir "*) ;; *) rmdirs="$rmdirs $objdir" ;; esac fi # Don't error if the file doesn't exist and rm -f was used. if { test -L "$file"; } >/dev/null 2>&1 || { test -h "$file"; } >/dev/null 2>&1 || test -f "$file"; then : elif test -d "$file"; then exit_status=1 continue elif test "$rmforce" = yes; then continue fi rmfiles="$file" case $name in *.la) # Possibly a libtool archive, so verify it. if func_lalib_p "$file"; then func_source $dir/$name # Delete the libtool libraries and symlinks. for n in $library_names; do rmfiles="$rmfiles $objdir/$n" done test -n "$old_library" && rmfiles="$rmfiles $objdir/$old_library" case "$mode" in clean) case " $library_names " in # " " in the beginning catches empty $dlname *" $dlname "*) ;; *) rmfiles="$rmfiles $objdir/$dlname" ;; esac test -n "$libdir" && rmfiles="$rmfiles $objdir/$name $objdir/${name}i" ;; uninstall) if test -n "$library_names"; then # Do each command in the postuninstall commands. func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' fi if test -n "$old_library"; then # Do each command in the old_postuninstall commands. func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' fi # FIXME: should reinstall the best remaining shared library. ;; esac fi ;; *.lo) # Possibly a libtool object, so verify it. if func_lalib_p "$file"; then # Read the .lo file func_source $dir/$name # Add PIC object to the list of files to remove. if test -n "$pic_object" && test "$pic_object" != none; then rmfiles="$rmfiles $dir/$pic_object" fi # Add non-PIC object to the list of files to remove. if test -n "$non_pic_object" && test "$non_pic_object" != none; then rmfiles="$rmfiles $dir/$non_pic_object" fi fi ;; *) if test "$mode" = clean ; then noexename=$name case $file in *.exe) func_stripname '' '.exe' "$file" file=$func_stripname_result func_stripname '' '.exe' "$name" noexename=$func_stripname_result # $file with .exe has already been added to rmfiles, # add $file without .exe rmfiles="$rmfiles $file" ;; esac # Do a test to see if this is a libtool program. if func_ltwrapper_p "$file"; then if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" relink_command= func_source $func_ltwrapper_scriptname_result rmfiles="$rmfiles $func_ltwrapper_scriptname_result" else relink_command= func_source $dir/$noexename fi # note $name still contains .exe if it was in $file originally # as does the version of $file that was added into $rmfiles rmfiles="$rmfiles $objdir/$name $objdir/${name}S.${objext}" if test "$fast_install" = yes && test -n "$relink_command"; then rmfiles="$rmfiles $objdir/lt-$name" fi if test "X$noexename" != "X$name" ; then rmfiles="$rmfiles $objdir/lt-${noexename}.c" fi fi fi ;; esac func_show_eval "$RM $rmfiles" 'exit_status=1' done objdir="$origobjdir" # Try to remove the ${objdir}s in the directories where we deleted files for dir in $rmdirs; do if test -d "$dir"; then func_show_eval "rmdir $dir >/dev/null 2>&1" fi done exit $exit_status } { test "$mode" = uninstall || test "$mode" = clean; } && func_mode_uninstall ${1+"$@"} test -z "$mode" && { help="$generic_help" func_fatal_help "you must specify a MODE" } test -z "$exec_cmd" && \ func_fatal_help "invalid operation mode \`$mode'" if test -n "$exec_cmd"; then eval exec "$exec_cmd" exit $EXIT_FAILURE fi exit $exit_status # The TAGs below are defined such that we never get into a situation # in which we disable both kinds of libraries. Given conflicting # choices, we go for a static library, that is the most portable, # since we can't tell whether shared libraries were disabled because # the user asked for that or because the platform doesn't support # them. This is particularly important on AIX, because we don't # support having both static and shared libraries enabled at the same # time on that platform, so we default to a shared-only configuration. # If a disable-shared tag is given, we'll fallback to a static-only # configuration. But we'll never go from static-only to shared-only. # ### BEGIN LIBTOOL TAG CONFIG: disable-shared build_libtool_libs=no build_old_libs=yes # ### END LIBTOOL TAG CONFIG: disable-shared # ### BEGIN LIBTOOL TAG CONFIG: disable-static build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` # ### END LIBTOOL TAG CONFIG: disable-static # Local Variables: # mode:shell-script # sh-indentation:2 # End: # vi:sw=2
YifuLiu/AliOS-Things
components/SDL2/src/image/ltmain.sh
Shell
apache-2.0
243,310
/* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing See "unlicense" statement at the end of this file. Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). * Change History 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!): - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug would only have occured in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place() (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag). - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries. Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice). - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6. - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti - Merged MZ_FORCEINLINE fix from hdeanclark - Fix <time.h> include before config #ifdef, thanks emil.brink - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can set it to 1 for real-time compression). - Merged in some compiler fixes from paulharris's github repro. - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3. - Added example6.c, which dumps an image of the mandelbrot set to a PNG file. - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more. - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include <time.h> (thanks fermtect). 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64. - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson <bruced@valvesoftware.com> for the feedback/bug report. 5/28/11 v1.11 - Added statement from unlicense.org 5/27/11 v1.10 - Substantial compressor optimizations: - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. - Refactored the compression code for better readability and maintainability. - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large drop in throughput on some files). 5/15/11 v1.09 - Initial stable release. * Low-level Deflate/Inflate implementation notes: Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses approximately as well as zlib. Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory block large enough to hold the entire file. The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. * zlib-style API notes: miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in zlib replacement in many apps: The z_stream struct, optional memory allocation callbacks deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound inflateInit/inflateInit2/inflate/inflateEnd compress, compress2, compressBound, uncompress CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. Supports raw deflate streams or standard zlib streams with adler-32 checking. Limitations: The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but there are no guarantees that miniz.c pulls this off perfectly. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by Alex Evans. Supports 1-4 bytes/pixel images. * ZIP archive API notes: The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to get the job done with minimal fuss. There are simple API's to retrieve file information, read files from existing archives, create new archives, append new files to existing archives, or clone archive data from one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), or you can specify custom file read/write callbacks. - Archive reading: Just call this function to read a single file from a disk archive: void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); The locate operation can optionally check file comments too, which (as one example) can be used to identify multiple versions of the same file in an archive. This function uses a simple linear search through the central directory, so it's not very fast. Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and retrieve detailed info on each file by calling mz_zip_reader_file_stat(). - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data to disk and builds an exact image of the central directory in memory. The central directory image is written all at once at the end of the archive file when the archive is finalized. The archive writer can optionally align each file's local header and file data to any power of 2 alignment, which can be useful when the archive will be read from optical media. Also, the writer supports placing arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still readable by any ZIP tool. - Archive appending: The simple way to add a single file to an archive is to call this function: mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); The archive will be created if it doesn't already exist, otherwise it'll be appended to. Note the appending is done in-place and is not an atomic operation, so if something goes wrong during the operation it's possible the archive could be left without a central directory (although the local file headers and file data will be fine, so the archive will be recoverable). For more complex archive modification scenarios: 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and you're done. This is safe but requires a bunch of temporary disk space or heap memory. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), append new files as needed, then finalize the archive which will write an updated central directory to the original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a possibility that the archive's central directory could be lost with this method if anything goes wrong, though. - ZIP archive support limitations: No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. Requires streams capable of seeking. * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. * Important: For best perf. be sure to customize the below macros for your target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1 * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). */ #ifndef MINIZ_HEADER_INCLUDED #define MINIZ_HEADER_INCLUDED /*#include <stdlib.h>*/ // Defines to completely disable specific portions of miniz.c: // If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. #define MINIZ_NO_STDIO // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or // get/set file times, and the C run-time funcs that get/set times won't be called. // The current downside is the times written to your archives will be from 1979. #define MINIZ_NO_TIME // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. #define MINIZ_NO_ARCHIVE_APIS // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's. #define MINIZ_NO_ARCHIVE_WRITING_APIS // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. #define MINIZ_NO_ZLIB_APIS // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. #define MINIZ_NO_ZLIB_COMPATIBLE_NAMES // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc // callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user // functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. //#define MINIZ_NO_MALLOC #define MINIZ_SDL_MALLOC // Define MINIZ_STATIC_FUNCTIONS to make all functions static. You probably // want this if you're using miniz in a library #define MINIZ_STATIC_FUNCTIONS #if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux #define MINIZ_NO_TIME #endif #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) #include <time.h> #endif #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) // MINIZ_X86_OR_X64_CPU is only used to help set the below macros. #define MINIZ_X86_OR_X64_CPU 1 #endif #if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif #if MINIZ_X86_OR_X64_CPU // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #endif #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) // Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). #define MINIZ_HAS_64BIT_REGISTERS 1 #endif #ifdef MINIZ_STATIC_FUNCTIONS #define MINIZ_STATIC static #else #define MINIZ_STATIC #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API Definitions. // For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! typedef unsigned long mz_ulong; // mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. MINIZ_STATIC void mz_free(void *p); #define MZ_ADLER32_INIT (1) // mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. MINIZ_STATIC mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); #define MZ_CRC32_INIT (0) // mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. MINIZ_STATIC mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); // Compression strategies. enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; // Method #define MZ_DEFLATED 8 #ifndef MINIZ_NO_ZLIB_APIS // Heap allocation callbacks. // Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); typedef void (*mz_free_func)(void *opaque, void *address); typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); #define MZ_VERSION "9.1.15" #define MZ_VERNUM 0x91F0 #define MZ_VER_MAJOR 9 #define MZ_VER_MINOR 1 #define MZ_VER_REVISION 15 #define MZ_VER_SUBREVISION 0 // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; // Return status codes. MZ_PARAM_ERROR is non-standard. enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; // Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; // Window bits #define MZ_DEFAULT_WINDOW_BITS 15 struct mz_internal_state; // Compression/decompression stream struct. typedef struct mz_stream_s { const unsigned char *next_in; // pointer to next byte to read unsigned int avail_in; // number of bytes available at next_in mz_ulong total_in; // total number of bytes consumed so far unsigned char *next_out; // pointer to next byte to write unsigned int avail_out; // number of bytes that can be written to next_out mz_ulong total_out; // total number of bytes produced so far char *msg; // error msg (unused) struct mz_internal_state *state; // internal state, allocated by zalloc/zfree mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) mz_free_func zfree; // optional heap free function (defaults to free) void *opaque; // heap alloc function user pointer int data_type; // data_type (unused) mz_ulong adler; // adler32 of the source or uncompressed data mz_ulong reserved; // not used } mz_stream; typedef mz_stream *mz_streamp; // Returns the version string of miniz.c. MINIZ_STATIC const char *mz_version(void); // mz_deflateInit() initializes a compressor with default options: // Parameters: // pStream must point to an initialized mz_stream struct. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. // level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. // (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if the input parameters are bogus. // MZ_MEM_ERROR on out of memory. MINIZ_STATIC int mz_deflateInit(mz_streamp pStream, int level); // mz_deflateInit2() is like mz_deflate(), except with more control: // Additional parameters: // method must be MZ_DEFLATED // window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) // mem_level must be between [1, 9] (it's checked but ignored by miniz.c) MINIZ_STATIC int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); // Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). MINIZ_STATIC int mz_deflateReset(mz_streamp pStream); // mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. // Return values: // MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). // MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) MINIZ_STATIC int mz_deflate(mz_streamp pStream, int flush); // mz_deflateEnd() deinitializes a compressor: // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. MINIZ_STATIC int mz_deflateEnd(mz_streamp pStream); // mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. MINIZ_STATIC mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); // Single-call compression functions mz_compress() and mz_compress2(): // Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. MINIZ_STATIC int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); MINIZ_STATIC int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); // mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). MINIZ_STATIC mz_ulong mz_compressBound(mz_ulong source_len); // Initializes a decompressor. MINIZ_STATIC int mz_inflateInit(mz_streamp pStream); // mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). MINIZ_STATIC int mz_inflateInit2(mz_streamp pStream, int window_bits); // Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. // On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). // MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. // Return values: // MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. // MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. // MZ_STREAM_ERROR if the stream is bogus. // MZ_DATA_ERROR if the deflate stream is invalid. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again // with more input data, or with more room in the output buffer (except when using single call decompression, described above). MINIZ_STATIC int mz_inflate(mz_streamp pStream, int flush); // Deinitializes a decompressor. MINIZ_STATIC int mz_inflateEnd(mz_streamp pStream); // Single-call decompression. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. MINIZ_STATIC int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); // Returns a string description of the specified error code, or NULL if the error code is invalid. MINIZ_STATIC const char *mz_error(int err); // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES typedef unsigned char Byte; typedef unsigned int uInt; typedef mz_ulong uLong; typedef Byte Bytef; typedef uInt uIntf; typedef char charf; typedef int intf; typedef void *voidpf; typedef uLong uLongf; typedef void *voidp; typedef void *const voidpc; #define Z_NULL 0 #define Z_NO_FLUSH MZ_NO_FLUSH #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH #define Z_SYNC_FLUSH MZ_SYNC_FLUSH #define Z_FULL_FLUSH MZ_FULL_FLUSH #define Z_FINISH MZ_FINISH #define Z_BLOCK MZ_BLOCK #define Z_OK MZ_OK #define Z_STREAM_END MZ_STREAM_END #define Z_NEED_DICT MZ_NEED_DICT #define Z_ERRNO MZ_ERRNO #define Z_STREAM_ERROR MZ_STREAM_ERROR #define Z_DATA_ERROR MZ_DATA_ERROR #define Z_MEM_ERROR MZ_MEM_ERROR #define Z_BUF_ERROR MZ_BUF_ERROR #define Z_VERSION_ERROR MZ_VERSION_ERROR #define Z_PARAM_ERROR MZ_PARAM_ERROR #define Z_NO_COMPRESSION MZ_NO_COMPRESSION #define Z_BEST_SPEED MZ_BEST_SPEED #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY #define Z_FILTERED MZ_FILTERED #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY #define Z_RLE MZ_RLE #define Z_FIXED MZ_FIXED #define Z_DEFLATED MZ_DEFLATED #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS #define alloc_func mz_alloc_func #define free_func mz_free_func #define internal_state mz_internal_state #define z_stream mz_stream #define deflateInit mz_deflateInit #define deflateInit2 mz_deflateInit2 #define deflateReset mz_deflateReset #define deflate mz_deflate #define deflateEnd mz_deflateEnd #define deflateBound mz_deflateBound #define compress mz_compress #define compress2 mz_compress2 #define compressBound mz_compressBound #define inflateInit mz_inflateInit #define inflateInit2 mz_inflateInit2 #define inflate mz_inflate #define inflateEnd mz_inflateEnd #define uncompress mz_uncompress #define crc32 mz_crc32 #define adler32 mz_adler32 #define MAX_WBITS 15 #define MAX_MEM_LEVEL 9 #define zError mz_error #define ZLIB_VERSION MZ_VERSION #define ZLIB_VERNUM MZ_VERNUM #define ZLIB_VER_MAJOR MZ_VER_MAJOR #define ZLIB_VER_MINOR MZ_VER_MINOR #define ZLIB_VER_REVISION MZ_VER_REVISION #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION #define zlibVersion mz_version #define zlib_version mz_version() #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES #endif // MINIZ_NO_ZLIB_APIS // ------------------- Types and macros typedef unsigned char mz_uint8; typedef signed short mz_int16; typedef unsigned short mz_uint16; typedef unsigned int mz_uint32; typedef unsigned int mz_uint; typedef long long mz_int64; typedef unsigned long long mz_uint64; typedef int mz_bool; #define MZ_FALSE (0) #define MZ_TRUE (1) // An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message. #ifdef _MSC_VER #define MZ_MACRO_END while (0, 0) #else #define MZ_MACRO_END while (0) #endif // ------------------- ZIP archive reading/writing #ifndef MINIZ_NO_ARCHIVE_APIS enum { MZ_ZIP_MAX_IO_BUF_SIZE = 64*1024, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 }; typedef struct { mz_uint32 m_file_index; mz_uint32 m_central_dir_ofs; mz_uint16 m_version_made_by; mz_uint16 m_version_needed; mz_uint16 m_bit_flag; mz_uint16 m_method; #ifndef MINIZ_NO_TIME time_t m_time; #endif mz_uint32 m_crc32; mz_uint64 m_comp_size; mz_uint64 m_uncomp_size; mz_uint16 m_internal_attr; mz_uint32 m_external_attr; mz_uint64 m_local_header_ofs; mz_uint32 m_comment_size; char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; } mz_zip_archive_file_stat; typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); struct mz_zip_internal_state_tag; typedef struct mz_zip_internal_state_tag mz_zip_internal_state; typedef enum { MZ_ZIP_MODE_INVALID = 0, MZ_ZIP_MODE_READING = 1, MZ_ZIP_MODE_WRITING = 2, MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 } mz_zip_mode; typedef struct mz_zip_archive_tag { mz_uint64 m_archive_size; mz_uint64 m_central_directory_file_ofs; mz_uint m_total_files; mz_zip_mode m_zip_mode; mz_uint m_file_offset_alignment; mz_alloc_func m_pAlloc; mz_free_func m_pFree; mz_realloc_func m_pRealloc; void *m_pAlloc_opaque; mz_file_read_func m_pRead; mz_file_write_func m_pWrite; void *m_pIO_opaque; mz_zip_internal_state *m_pState; } mz_zip_archive; typedef enum { MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 } mz_zip_flags; // ZIP archive reading // Inits a ZIP archive reader. // These functions read and validate the archive's central directory. MINIZ_STATIC mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); MINIZ_STATIC mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); #ifndef MINIZ_NO_STDIO MINIZ_STATIC mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); #endif // Returns the total number of files in the archive. MINIZ_STATIC mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); // Returns detailed information about an archive file entry. MINIZ_STATIC mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); // Determines if an archive file entry is a directory entry. MINIZ_STATIC mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); MINIZ_STATIC mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); // Retrieves the filename of an archive file entry. // Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. MINIZ_STATIC mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); // Attempts to locates a file in the archive's central directory. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH // Returns -1 if the file cannot be found. MINIZ_STATIC int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); // Extracts a archive file to a memory buffer using no memory allocation. MINIZ_STATIC mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); MINIZ_STATIC mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); // Extracts a archive file to a memory buffer. MINIZ_STATIC mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); MINIZ_STATIC mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); // Extracts a archive file to a dynamically allocated heap buffer. MINIZ_STATIC void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); MINIZ_STATIC void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); // Extracts a archive file using a callback function to output the file's data. MINIZ_STATIC mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); MINIZ_STATIC mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); #ifndef MINIZ_NO_STDIO // Extracts a archive file to a disk file and sets its last accessed and modified times. // This function only extracts files, not archive directory records. MINIZ_STATIC mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); MINIZ_STATIC mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); #endif // Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. MINIZ_STATIC mz_bool mz_zip_reader_end(mz_zip_archive *pZip); // ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS // Inits a ZIP archive writer. MINIZ_STATIC mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); MINIZ_STATIC mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); #ifndef MINIZ_NO_STDIO MINIZ_STATIC mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); #endif // Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. // For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. // For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. // Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before // the archive is finalized the file's central directory will be hosed. MINIZ_STATIC mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); // Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. // To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. MINIZ_STATIC mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); MINIZ_STATIC mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); #ifndef MINIZ_NO_STDIO // Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. MINIZ_STATIC mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); #endif // Adds a file to an archive by fully cloning the data from another archive. // This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields. MINIZ_STATIC mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); // Finalizes the archive by writing the central directory records followed by the end of central directory record. // After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). // An archive must be manually finalized by calling this function for it to be valid. MINIZ_STATIC mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); MINIZ_STATIC mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); // Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. // Note for the archive to be valid, it must have been finalized before ending. MINIZ_STATIC mz_bool mz_zip_writer_end(mz_zip_archive *pZip); // Misc. high-level helper functions: // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. MINIZ_STATIC mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); // Reads a single file from an archive into a heap block. // Returns NULL on failure. MINIZ_STATIC void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS // ------------------- Low-level Decompression API Definitions // Decompression flags used by tinfl_decompress(). // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. enum { TINFL_FLAG_PARSE_ZLIB_HEADER = 1, TINFL_FLAG_HAS_MORE_INPUT = 2, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, TINFL_FLAG_COMPUTE_ADLER32 = 8 }; // High level decompression functions: // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. // On return: // Function returns a pointer to the decompressed data, or NULL on failure. // *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. // The caller must call mz_free() on the returned block when it's no longer needed. MINIZ_STATIC void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) MINIZ_STATIC size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. // Returns 1 on success or 0 on failure. typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); MINIZ_STATIC int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; // Max size of LZ dictionary. #define TINFL_LZ_DICT_SIZE 32768 // Return status. typedef enum { TINFL_STATUS_BAD_PARAM = -3, TINFL_STATUS_ADLER32_MISMATCH = -2, TINFL_STATUS_FAILED = -1, TINFL_STATUS_DONE = 0, TINFL_STATUS_NEEDS_MORE_INPUT = 1, TINFL_STATUS_HAS_MORE_OUTPUT = 2 } tinfl_status; // Initializes the decompressor to its initial state. #define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END #define tinfl_get_adler32(r) (r)->m_check_adler32 // Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. // This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. MINIZ_STATIC tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); // Internal/private bits follow. enum { TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS }; typedef struct { mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; } tinfl_huff_table; #if MINIZ_HAS_64BIT_REGISTERS #define TINFL_USE_64BIT_BITBUF 1 #endif #if TINFL_USE_64BIT_BITBUF typedef mz_uint64 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (64) #else typedef mz_uint32 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (32) #endif struct tinfl_decompressor_tag { mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; tinfl_bit_buf_t m_bit_buf; size_t m_dist_from_out_buf_start; tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; }; // ------------------- Low-level Compression API Definitions // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). #define TDEFL_LESS_MEMORY 0 // tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). enum { TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF }; // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. // The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). enum { TDEFL_WRITE_ZLIB_HEADER = 0x01000, TDEFL_COMPUTE_ADLER32 = 0x02000, TDEFL_GREEDY_PARSING_FLAG = 0x04000, TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, TDEFL_RLE_MATCHES = 0x10000, TDEFL_FILTER_MATCHES = 0x20000, TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 }; // High level compression functions: // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of source block to compress. // flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. // The caller must free() the returned block when it's no longer needed. MINIZ_STATIC void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. // Returns 0 on failure. MINIZ_STATIC size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // Compresses an image to a compressed PNG file in memory. // On entry: // pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. // The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. // level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL // If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pLen_out will be set to the size of the PNG image file. // The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. MINIZ_STATIC void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, int bpl, size_t *pLen_out, mz_uint level, mz_bool flip); MINIZ_STATIC void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, int bpl, size_t *pLen_out); // Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. typedef mz_bool (*tdefl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); // tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. MINIZ_STATIC mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). #if TDEFL_LESS_MEMORY enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #else enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #endif // The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. typedef enum { TDEFL_STATUS_BAD_PARAM = -2, TDEFL_STATUS_PUT_BUF_FAILED = -1, TDEFL_STATUS_OKAY = 0, TDEFL_STATUS_DONE = 1, } tdefl_status; // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums typedef enum { TDEFL_NO_FLUSH = 0, TDEFL_SYNC_FLUSH = 2, TDEFL_FULL_FLUSH = 3, TDEFL_FINISH = 4 } tdefl_flush; // tdefl's compression state structure. typedef struct { tdefl_put_buf_func_ptr m_pPut_buf_func; void *m_pPut_buf_user; mz_uint m_flags, m_max_probes[2]; int m_greedy_parsing; mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; tdefl_status m_prev_return_status; const void *m_pIn_buf; void *m_pOut_buf; size_t *m_pIn_buf_size, *m_pOut_buf_size; tdefl_flush m_flush; const mz_uint8 *m_pSrc; size_t m_src_buf_left, m_out_buf_ofs; mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; } tdefl_compressor; // Initializes the compressor. // There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. // pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. // If pBut_buf_func is NULL the user should always call the tdefl_compress() API. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) MINIZ_STATIC tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); // Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. MINIZ_STATIC tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. // tdefl_compress_buffer() always consumes the entire input buffer. MINIZ_STATIC tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); MINIZ_STATIC tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); MINIZ_STATIC mz_uint32 tdefl_get_adler32(tdefl_compressor *d); // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros. #ifndef MINIZ_NO_ZLIB_APIS // Create tdefl_compress() flags given zlib-style compression parameters. // level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) // window_bits may be -15 (raw deflate) or 15 (zlib) // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED MINIZ_STATIC mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); #endif // #ifndef MINIZ_NO_ZLIB_APIS #ifdef __cplusplus } #endif #endif // MINIZ_HEADER_INCLUDED // ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.) #ifndef MINIZ_HEADER_FILE_ONLY typedef unsigned char mz_validate_uint16[sizeof(mz_uint16)==2 ? 1 : -1]; typedef unsigned char mz_validate_uint32[sizeof(mz_uint32)==4 ? 1 : -1]; typedef unsigned char mz_validate_uint64[sizeof(mz_uint64)==8 ? 1 : -1]; /*#include <string.h>*/ #ifndef MZ_ASSERT #include <assert.h> #define MZ_ASSERT(x) assert(x) #endif #ifdef MINIZ_NO_MALLOC #define MZ_MALLOC(x) NULL #define MZ_FREE(x) (void)x, ((void)0) #define MZ_REALLOC(p, x) NULL #elif defined(MINIZ_SDL_MALLOC) #define MZ_MALLOC(x) SDL_malloc(x) #define MZ_FREE(x) SDL_free(x) #define MZ_REALLOC(p, x) SDL_realloc(p, x) #else #define MZ_MALLOC(x) malloc(x) #define MZ_FREE(x) free(x) #define MZ_REALLOC(p, x) realloc(p, x) #endif #define MZ_MAX(a,b) (((a)>(b))?(a):(b)) #define MZ_MIN(a,b) (((a)<(b))?(a):(b)) #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) #else #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) #endif #ifdef _MSC_VER #define MZ_FORCEINLINE __forceinline #elif defined(__GNUC__) #define MZ_FORCEINLINE inline __attribute__((__always_inline__)) #else #define MZ_FORCEINLINE inline #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API's mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) { mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; if (!ptr) return MZ_ADLER32_INIT; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } return (s2 << 16) + s1; } // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) { static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; mz_uint32 crcu32 = (mz_uint32)crc; if (!ptr) return MZ_CRC32_INIT; crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } return ~crcu32; } MINIZ_STATIC void mz_free(void *p) { MZ_FREE(p); } #ifndef MINIZ_NO_ZLIB_APIS static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } static void *def_realloc_func(void *opaque, void *address, size_t items, size_t size) { (void)opaque, (void)address, (void)items, (void)size; return MZ_REALLOC(address, items * size); } const char *mz_version(void) { return MZ_VERSION; } int mz_deflateInit(mz_streamp pStream, int level) { return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); } int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) { tdefl_compressor *pComp; mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); if (!pStream) return MZ_STREAM_ERROR; if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = MZ_ADLER32_INIT; pStream->msg = NULL; pStream->reserved = 0; pStream->total_in = 0; pStream->total_out = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); if (!pComp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pComp; if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) { mz_deflateEnd(pStream); return MZ_PARAM_ERROR; } return MZ_OK; } int mz_deflateReset(mz_streamp pStream) { if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; pStream->total_in = pStream->total_out = 0; tdefl_init((tdefl_compressor*)pStream->state, NULL, NULL, ((tdefl_compressor*)pStream->state)->m_flags); return MZ_OK; } int mz_deflate(mz_streamp pStream, int flush) { size_t in_bytes, out_bytes; mz_ulong orig_total_in, orig_total_out; int mz_status = MZ_OK; if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; if (!pStream->avail_out) return MZ_BUF_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if (((tdefl_compressor*)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; for ( ; ; ) { tdefl_status defl_status; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; defl_status = tdefl_compress((tdefl_compressor*)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor*)pStream->state); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (defl_status < 0) { mz_status = MZ_STREAM_ERROR; break; } else if (defl_status == TDEFL_STATUS_DONE) { mz_status = MZ_STREAM_END; break; } else if (!pStream->avail_out) break; else if ((!pStream->avail_in) && (flush != MZ_FINISH)) { if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) break; return MZ_BUF_ERROR; // Can't make forward progress without some input. } } return mz_status; } int mz_deflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) { (void)pStream; // This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); } int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) { int status; mz_stream stream; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_deflateInit(&stream, level); if (status != MZ_OK) return status; status = mz_deflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_deflateEnd(&stream); return (status == MZ_OK) ? MZ_BUF_ERROR : status; } *pDest_len = stream.total_out; return mz_deflateEnd(&stream); } int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); } mz_ulong mz_compressBound(mz_ulong source_len) { return mz_deflateBound(NULL, source_len); } typedef struct { tinfl_decompressor m_decomp; mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; tinfl_status m_last_status; } inflate_state; int mz_inflateInit2(mz_streamp pStream, int window_bits) { inflate_state *pDecomp; if (!pStream) return MZ_STREAM_ERROR; if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = 0; pStream->msg = NULL; pStream->total_in = 0; pStream->total_out = 0; pStream->reserved = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pDecomp = (inflate_state*)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); if (!pDecomp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pDecomp; tinfl_init(&pDecomp->m_decomp); pDecomp->m_dict_ofs = 0; pDecomp->m_dict_avail = 0; pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; pDecomp->m_first_call = 1; pDecomp->m_has_flushed = 0; pDecomp->m_window_bits = window_bits; return MZ_OK; } int mz_inflateInit(mz_streamp pStream) { return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); } int mz_inflate(mz_streamp pStream, int flush) { inflate_state* pState; mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; size_t in_bytes, out_bytes, orig_avail_in; tinfl_status status; if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState = (inflate_state*)pStream->state; if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; orig_avail_in = pStream->avail_in; first_call = pState->m_first_call; pState->m_first_call = 0; if (pState->m_last_status < 0) return MZ_DATA_ERROR; if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState->m_has_flushed |= (flush == MZ_FINISH); if ((flush == MZ_FINISH) && (first_call)) { // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (status < 0) return MZ_DATA_ERROR; else if (status != TINFL_STATUS_DONE) { pState->m_last_status = TINFL_STATUS_FAILED; return MZ_BUF_ERROR; } return MZ_STREAM_END; } // flush != MZ_FINISH then we must assume there's more input. if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; if (pState->m_dict_avail) { n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } for ( ; ; ) { in_bytes = pStream->avail_in; out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pState->m_dict_avail = (mz_uint)out_bytes; n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); if (status < 0) return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. else if (flush == MZ_FINISH) { // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. if (status == TINFL_STATUS_DONE) return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. else if (!pStream->avail_out) return MZ_BUF_ERROR; } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) break; } return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } int mz_inflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { mz_stream stream; int status; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_inflateInit(&stream); if (status != MZ_OK) return status; status = mz_inflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_inflateEnd(&stream); return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; } *pDest_len = stream.total_out; return mz_inflateEnd(&stream); } const char *mz_error(int err) { static struct { int m_err; const char *m_pDesc; } s_error_descs[] = { { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } }; mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; return NULL; } #endif //MINIZ_NO_ZLIB_APIS // ------------------- Low-level Decompression (completely independent from all compression API's) #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) #define TINFL_MEMSET(p, c, l) memset(p, c, l) #define TINFL_CR_BEGIN switch(r->m_state) { case 0: #define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END #define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END #define TINFL_CR_FINISH } // TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario. #define TINFL_GET_BYTE(state_index, c) do { \ if (pIn_buf_cur >= pIn_buf_end) { \ for ( ; ; ) { \ if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ if (pIn_buf_cur < pIn_buf_end) { \ c = *pIn_buf_cur++; \ break; \ } \ } else { \ c = 0; \ break; \ } \ } \ } else c = *pIn_buf_cur++; } MZ_MACRO_END #define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n)) #define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END #define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. // It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a // Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the // bit buffer contains >=15 bits (deflate's max. Huffman code size). #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ do { \ temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ if (temp >= 0) { \ code_len = temp >> 9; \ if ((code_len) && (num_bits >= code_len)) \ break; \ } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \ } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \ } while (num_bits < 15); // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read // beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully // decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. // The slow path is only executed at the very end of the input buffer. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \ int temp; mz_uint code_len, c; \ if (num_bits < 15) { \ if ((pIn_buf_end - pIn_buf_cur) < 2) { \ TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ } else { \ bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \ } \ } \ if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ code_len = temp >> 9, temp &= 511; \ else { \ code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \ } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) { static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; static const int s_min_table_sizes[3] = { 257, 1, 4 }; tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; TINFL_CR_BEGIN bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } } do { TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; if (r->m_type == 0) { TINFL_SKIP_BITS(5, num_bits & 7); for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } while ((counter) && (num_bits)) { TINFL_GET_BITS(51, dist, 8); while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)dist; counter--; } while (counter) { size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } while (pIn_buf_cur >= pIn_buf_end) { if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); } else { TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); } } n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; } } else if (r->m_type == 3) { TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); } else { if (r->m_type == 1) { mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); for ( i = 0; i <= 143; ++i) *p++ = 8; for ( ; i <= 255; ++i) *p++ = 9; for ( ; i <= 279; ++i) *p++ = 7; for ( ; i <= 287; ++i) *p++ = 8; } else { for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } r->m_table_sizes[2] = 19; } for ( ; (int)r->m_type >= 0; r->m_type--) { int tree_next, tree_cur; tinfl_huff_table *pTable; mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } if ((65536 != total) && (used_syms > 1)) { TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); } for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) { tree_cur -= ((rev_code >>= 1) & 1); if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; } tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; } if (r->m_type == 2) { for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); ) { mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } if ((dist == 16) && (!counter)) { TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); } num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; } if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); } TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); } } for ( ; ; ) { mz_uint8 *pSrc; for ( ; ; ) { if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) { TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); if (counter >= 256) break; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)counter; } else { int sym2; mz_uint code_len; #if TINFL_USE_64BIT_BITBUF if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } #else if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } counter = sym2; bit_buf >>= code_len; num_bits -= code_len; if (counter & 256) break; #if !TINFL_USE_64BIT_BITBUF if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } bit_buf >>= code_len; num_bits -= code_len; pOut_buf_cur[0] = (mz_uint8)counter; if (sym2 & 256) { pOut_buf_cur++; counter = sym2; break; } pOut_buf_cur[1] = (mz_uint8)sym2; pOut_buf_cur += 2; } } if ((counter &= 511) == 256) break; num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); } pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { while (counter--) { while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; } continue; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES else if ((counter >= 9) && (counter <= dist)) { const mz_uint8 *pSrc_end = pSrc + (counter & ~7); do { ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; pOut_buf_cur += 8; } while ((pSrc += 8) < pSrc_end); if ((counter &= 7) < 3) { if (counter) { pOut_buf_cur[0] = pSrc[0]; if (counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } continue; } } #endif do { pOut_buf_cur[0] = pSrc[0]; pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur[2] = pSrc[2]; pOut_buf_cur += 3; pSrc += 3; } while ((int)(counter -= 3) > 2); if ((int)counter > 0) { pOut_buf_cur[0] = pSrc[0]; if ((int)counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } } } } while (!(r->m_final & 1)); if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } } TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); TINFL_CR_FINISH common_exit: r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) { const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; } return status; } // Higher level helper functions. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; *pOut_len = 0; tinfl_init(&decomp); for ( ; ; ) { size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, &dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } src_buf_ofs += src_buf_size; *pOut_len += dst_buf_size; if (status == TINFL_STATUS_DONE) break; new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); if (!pNew_buf) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; } return pBuf; } size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; } int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { int result = 0; tinfl_decompressor decomp; mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; if (!pDict) return TINFL_STATUS_FAILED; tinfl_init(&decomp); for ( ; ; ) { size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); in_buf_ofs += in_buf_size; if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) break; if (status != TINFL_STATUS_HAS_MORE_OUTPUT) { result = (status == TINFL_STATUS_DONE); break; } dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); } MZ_FREE(pDict); *pIn_buf_size = in_buf_ofs; return result; } // ------------------- Low-level Compression (independent from all decompression API's) // Purposely making these tables static for faster init and thread safety. static const mz_uint16 s_tdefl_len_sym[256] = { 257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272, 273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276, 277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278, 279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280, 281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281, 282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282, 283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283, 284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285 }; static const mz_uint8 s_tdefl_len_extra[256] = { 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0 }; static const mz_uint8 s_tdefl_small_dist_sym[512] = { 0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11, 11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13, 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14, 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14, 14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15, 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16, 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17, 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17 }; static const mz_uint8 s_tdefl_small_dist_extra[512] = { 0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7 }; static const mz_uint8 s_tdefl_large_dist_sym[128] = { 0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26, 26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28, 28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29 }; static const mz_uint8 s_tdefl_large_dist_extra[128] = { 0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12, 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13, 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13 }; // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq; static tdefl_sym_freq* tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1) { mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) { const mz_uint32* pHist = &hist[pass << 8]; mz_uint offsets[256], cur_ofs = 0; for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; { tdefl_sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } } return pCur_syms; } // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) { int root, leaf, next, avbl, used, dpth; if (n==0) return; else if (n==1) { A[0].m_key = 1; return; } A[0].m_key += A[1].m_key; root = 0; leaf = 2; for (next=1; next < n-1; next++) { if (leaf>=n || A[root].m_key<A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else A[next].m_key = A[leaf++].m_key; if (leaf>=n || (root<next && A[root].m_key<A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; } else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); } A[n-2].m_key = 0; for (next=n-3; next>=0; next--) A[next].m_key = A[A[next].m_key].m_key+1; avbl = 1; used = dpth = 0; root = n-2; next = n-1; while (avbl>0) { while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; } while (avbl>used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; } avbl = 2*used; dpth++; used = 0; } } // Limits canonical Huffman code table's max code size. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) { int i; mz_uint32 total = 0; if (code_list_len <= 1) return; for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); while (total != (1UL << max_code_size)) { pNum_codes[max_code_size]--; for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } total--; } } static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) { int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); if (static_table) { for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; } else { tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; int num_used_syms = 0; const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; } pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); for (i = 1, j = num_used_syms; i <= code_size_limit; i++) for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); } next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); for (i = 0; i < table_len; i++) { mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; } } #define TDEFL_PUT_BITS(b, l) do { \ mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \ d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \ while (d->m_bits_in >= 8) { \ if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ d->m_bit_buffer >>= 8; \ d->m_bits_in -= 8; \ } \ } MZ_MACRO_END #define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \ if (rle_repeat_count < 3) { \ d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ } else { \ d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ } rle_repeat_count = 0; } } #define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \ if (rle_z_count < 3) { \ d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ } else if (rle_z_count <= 10) { \ d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ } else { \ d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ } rle_z_count = 0; } } static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; static void tdefl_start_dynamic_block(tdefl_compressor *d) { int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; d->m_huff_count[0][256] = 1; tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); for (i = 0; i < total_code_sizes_to_pack; i++) { mz_uint8 code_size = code_sizes_to_pack[i]; if (!code_size) { TDEFL_RLE_PREV_CODE_SIZE(); if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } } else { TDEFL_RLE_ZERO_CODE_SIZE(); if (code_size != prev_code_size) { TDEFL_RLE_PREV_CODE_SIZE(); d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; } else if (++rle_repeat_count == 6) { TDEFL_RLE_PREV_CODE_SIZE(); } } prev_code_size = code_size; } if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); TDEFL_PUT_BITS(2, 2); TDEFL_PUT_BITS(num_lit_codes - 257, 5); TDEFL_PUT_BITS(num_dist_codes - 1, 5); for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; ) { mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); } } static void tdefl_start_static_block(tdefl_compressor *d) { mz_uint i; mz_uint8 *p = &d->m_huff_code_sizes[0][0]; for (i = 0; i <= 143; ++i) *p++ = 8; for ( ; i <= 255; ++i) *p++ = 9; for ( ; i <= 279; ++i) *p++ = 7; for ( ; i <= 287; ++i) *p++ = 8; memset(d->m_huff_code_sizes[1], 5, 32); tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); TDEFL_PUT_BITS(1, 2); } static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; mz_uint8 *pOutput_buf = d->m_pOutput_buf; mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; mz_uint64 bit_buffer = d->m_bit_buffer; mz_uint bits_in = d->m_bits_in; #define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); } flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint s0, s1, n0, n1, sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); // This sequence coaxes MSVC into using cmov's vs. jmp's. s0 = s_tdefl_small_dist_sym[match_dist & 511]; n0 = s_tdefl_small_dist_extra[match_dist & 511]; s1 = s_tdefl_large_dist_sym[match_dist >> 8]; n1 = s_tdefl_large_dist_extra[match_dist >> 8]; sym = (match_dist < 512) ? s0 : s1; num_extra_bits = (match_dist < 512) ? n0 : n1; MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } } if (pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE; *(mz_uint64*)pOutput_buf = bit_buffer; pOutput_buf += (bits_in >> 3); bit_buffer >>= (bits_in & ~7); bits_in &= 7; } #undef TDEFL_PUT_BITS_FAST d->m_pOutput_buf = pOutput_buf; d->m_bits_in = 0; d->m_bit_buffer = 0; while (bits_in) { mz_uint32 n = MZ_MIN(bits_in, 16); TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); bit_buffer >>= n; bits_in -= n; } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #else static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); if (match_dist < 512) { sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; } else { sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; } MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) { if (static_block) tdefl_start_static_block(d); else tdefl_start_dynamic_block(d); return tdefl_compress_lz_codes(d); } static int tdefl_flush_block(tdefl_compressor *d, int flush) { mz_uint saved_bit_buf, saved_bits_in; mz_uint8 *pSaved_output_buf; mz_bool comp_block_succeeded = MZ_FALSE; int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; d->m_pOutput_buf = pOutput_buf_start; d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; MZ_ASSERT(!d->m_output_flush_remaining); d->m_output_flush_ofs = 0; d->m_output_flush_remaining = 0; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) { TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); } TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; if (!use_raw_block) comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. if ( ((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size) ) { mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; TDEFL_PUT_BITS(0, 2); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) { TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); } for (i = 0; i < d->m_total_lz_bytes; ++i) { TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); } } // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. else if (!comp_block_succeeded) { d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; tdefl_compress_block(d, MZ_TRUE); } if (flush) { if (flush == TDEFL_FINISH) { if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } } else { mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } } } MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) { if (d->m_pPut_buf_func) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); } else if (pOutput_buf_start == d->m_output_buf) { int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); d->m_out_buf_ofs += bytes_to_copy; if ((n -= bytes_to_copy) != 0) { d->m_output_flush_ofs = bytes_to_copy; d->m_output_flush_remaining = n; } } else { d->m_out_buf_ofs += n; } } return d->m_output_flush_remaining; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p) static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint16 *s = (const mz_uint16*)(d->m_dict + pos), *p, *q; mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for ( ; ; ) { for ( ; ; ) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; q = (const mz_uint16*)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32; do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); if (!probe_len) { *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break; } else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8*)p == *(const mz_uint8*)q)) > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); } } } #else static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint8 *s = d->m_dict + pos, *p, *q; mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for ( ; ; ) { for ( ; ; ) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break; if (probe_len > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return; c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; } } } #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static mz_bool tdefl_compress_fast(tdefl_compressor *d) { // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) { const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); d->m_src_buf_left -= num_bytes_to_process; lookahead_size += num_bytes_to_process; while (num_bytes_to_process) { mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); memcpy(d->m_dict + dst_pos, d->m_pSrc, n); if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); d->m_pSrc += n; dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; num_bytes_to_process -= n; } dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; while (lookahead_size >= 4) { mz_uint cur_match_dist, cur_match_len = 1; mz_uint8 *pCur_dict = d->m_dict + cur_pos; mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; mz_uint probe_pos = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)lookahead_pos; if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) { const mz_uint16 *p = (const mz_uint16 *)pCur_dict; const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); mz_uint32 probe_len = 32; do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); if (!probe_len) cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U))) { cur_match_len = 1; *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } else { mz_uint32 s0, s1; cur_match_len = MZ_MIN(cur_match_len, lookahead_size); MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); cur_match_dist--; pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; pLZ_code_buf += 3; *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; } } else { *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } total_lz_bytes += cur_match_len; lookahead_pos += cur_match_len; dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; MZ_ASSERT(lookahead_size >= cur_match_len); lookahead_size -= cur_match_len; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } while (lookahead_size) { mz_uint8 lit = d->m_dict[cur_pos]; total_lz_bytes++; *pLZ_code_buf++ = lit; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } d->m_huff_count[0][lit]++; lookahead_pos++; dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; lookahead_size--; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } } d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; return MZ_TRUE; } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) { d->m_total_lz_bytes++; *d->m_pLZ_code_buf++ = lit; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } d->m_huff_count[0][lit]++; } static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) { mz_uint32 s0, s1; MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); d->m_total_lz_bytes += match_len; d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); match_dist -= 1; d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3; *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; } static mz_bool tdefl_compress_normal(tdefl_compressor *d) { const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; tdefl_flush flush = d->m_flush; while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) { mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) { mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; src_buf_left -= num_bytes_to_process; d->m_lookahead_size += num_bytes_to_process; while (pSrc != pSrc_end) { mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; } } else { while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) { mz_uint8 c = *pSrc++; mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; src_buf_left--; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) { mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); } } } d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) break; // Simple lazy/greedy parsing state machine. len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) { if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) { mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; } } else { tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); } if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) { cur_match_dist = cur_match_len = 0; } if (d->m_saved_match_len) { if (cur_match_len > d->m_saved_match_len) { tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); if (cur_match_len >= 128) { tdefl_record_match(d, cur_match_len, cur_match_dist); d->m_saved_match_len = 0; len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } } else { tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; } } else if (!cur_match_dist) tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) { tdefl_record_match(d, cur_match_len, cur_match_dist); len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } // Move the lookahead forward by len_to_move bytes. d->m_lookahead_pos += len_to_move; MZ_ASSERT(d->m_lookahead_size >= len_to_move); d->m_lookahead_size -= len_to_move; d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, TDEFL_LZ_DICT_SIZE); // Check if it's time to flush the current LZ codes to the internal output buffer. if ( (d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || ( (d->m_total_lz_bytes > 31*1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) ) { int n; d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; } } d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; return MZ_TRUE; } static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) { if (d->m_pIn_buf_size) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; } if (d->m_pOut_buf_size) { size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); d->m_output_flush_ofs += (mz_uint)n; d->m_output_flush_remaining -= (mz_uint)n; d->m_out_buf_ofs += n; *d->m_pOut_buf_size = d->m_out_buf_ofs; } return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; } tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) { if (!d) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return TDEFL_STATUS_BAD_PARAM; } d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; d->m_out_buf_ofs = 0; d->m_flush = flush; if ( ((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf) ) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); } d->m_wants_to_finish |= (flush == TDEFL_FINISH); if ((d->m_output_flush_remaining) || (d->m_finished)) return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) { if (!tdefl_compress_fast(d)) return d->m_prev_return_status; } else #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN { if (!tdefl_compress_normal(d)) return d->m_prev_return_status; } if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) { if (tdefl_flush_block(d, flush) < 0) return d->m_prev_return_status; d->m_finished = (flush == TDEFL_FINISH); if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; } } return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); } tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) { MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); } tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); return TDEFL_STATUS_OKAY; } tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) { return d->m_prev_return_status; } mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; } mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE; pComp = (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE; succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); MZ_FREE(pComp); return succeeded; } typedef struct { size_t m_size, m_capacity; mz_uint8 *m_pBuf; mz_bool m_expandable; } tdefl_output_buffer; static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) { tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; size_t new_size = p->m_size + len; if (new_size > p->m_capacity) { size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE; do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity); pNew_buf = (mz_uint8*)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE; p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; } memcpy((mz_uint8*)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; return MZ_TRUE; } void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_len) return MZ_FALSE; else *pOut_len = 0; out_buf.m_expandable = MZ_TRUE; if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL; *pOut_len = out_buf.m_size; return out_buf.m_pBuf; } size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_buf) return 0; out_buf.m_pBuf = (mz_uint8*)pOut_buf; out_buf.m_capacity = out_buf_len; if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0; return out_buf.m_size; } #ifndef MINIZ_NO_ZLIB_APIS static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; // level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) { mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER; if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES; else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK; else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES; return comp_flags; } #endif //MINIZ_NO_ZLIB_APIS #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) #endif // Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. // This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck. MINIZ_STATIC void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, int bpl, size_t *pLen_out, mz_uint level, mz_bool flip) { // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined. static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, y, z; mz_uint32 c; *pLen_out = 0; if (!pComp) return NULL; MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57+MZ_MAX(64, (1+bpl)*h); if (NULL == (out_buf.m_pBuf = (mz_uint8*)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } // write dummy header for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf); // compress image data tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8*)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); } if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } // write real header *pLen_out = out_buf.m_size-41; { static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06}; mz_uint8 pnghdr[41]={0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52, 0, 0, 0/*[18]*/, 0/*[19]*/, 0, 0, 0/*[22]*/, 0/*[23]*/, 8, 0/*[25]*/, 0,0,0,0,0,0,0, 0/*[33]*/, 0/*[34]*/, 0/*[35]*/, 0/*[36]*/, 0x49, 0x44, 0x41, 0x54}; pnghdr[18] = (mz_uint8)(w>>8); pnghdr[19] = (mz_uint8)w; pnghdr[22] = (mz_uint8)(h>>8); pnghdr[23] = (mz_uint8)h; pnghdr[25] = chans[num_chans]; pnghdr[33] = (mz_uint8)(*pLen_out>>24); pnghdr[34] = (mz_uint8)(*pLen_out>>16); pnghdr[35] = (mz_uint8)(*pLen_out>>8); pnghdr[36] = (mz_uint8)*pLen_out; c=(mz_uint32)mz_crc32(MZ_CRC32_INIT,pnghdr+12,17); for (i=0; i<4; ++i, c<<=8) ((mz_uint8*)(pnghdr+29))[i]=(mz_uint8)(c>>24); memcpy(out_buf.m_pBuf, pnghdr, 41); } // write footer (IDAT CRC-32, followed by IEND chunk) if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } c = (mz_uint32)mz_crc32(MZ_CRC32_INIT,out_buf.m_pBuf+41-4, *pLen_out+4); for (i=0; i<4; ++i, c<<=8) (out_buf.m_pBuf+out_buf.m_size-16)[i] = (mz_uint8)(c >> 24); // compute final size of file, grab compressed data buffer and return *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf; } MINIZ_STATIC void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, int bpl, size_t *pLen_out) { // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out) return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, bpl, pLen_out, 6, MZ_FALSE); } #ifdef _MSC_VER #pragma warning (pop) #endif // ------------------- .ZIP archive reading #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef MINIZ_NO_STDIO #define MZ_FILE void * #else #include <stdio.h> #include <sys/stat.h> #if defined(_MSC_VER) || defined(__MINGW64__) static FILE *mz_fopen(const char *pFilename, const char *pMode) { FILE* pFile = NULL; fopen_s(&pFile, pFilename, pMode); return pFile; } static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) { FILE* pFile = NULL; if (freopen_s(&pFile, pPath, pMode, pStream)) return NULL; return pFile; } #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN mz_fopen #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 _ftelli64 #define MZ_FSEEK64 _fseeki64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN mz_freopen #define MZ_DELETE_FILE remove #elif defined(__MINGW32__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__TINYC__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftell #define MZ_FSEEK64 fseek #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__GNUC__) && _LARGEFILE64_SOURCE #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen64(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT stat64 #define MZ_FILE_STAT stat64 #define MZ_FFLUSH fflush #define MZ_FREOPEN(p, m, s) freopen64(p, m, s) #define MZ_DELETE_FILE remove #else #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello #define MZ_FSEEK64 fseeko #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #endif // #ifdef _MSC_VER #endif // #ifdef MINIZ_NO_STDIO #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) // Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. enum { // ZIP archive identifiers and record sizes MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, // Central directory header record offsets MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, // Local directory header offsets MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, // End of central directory offsets MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, }; typedef struct { void *m_p; size_t m_size, m_capacity; mz_uint m_element_size; } mz_zip_array; struct mz_zip_internal_state_tag { mz_zip_array m_central_dir; mz_zip_array m_central_dir_offsets; mz_zip_array m_sorted_central_dir_offsets; MZ_FILE *m_pFile; void *m_pMem; size_t m_mem_size; size_t m_mem_capacity; }; #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) { pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); memset(pArray, 0, sizeof(mz_zip_array)); } static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) { void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE; if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; } if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) { if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; } return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) { if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } pArray->m_size = new_size; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) { return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); } static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) { size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE; memcpy((mz_uint8*)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); return MZ_TRUE; } #ifndef MINIZ_NO_TIME static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) { struct tm tm; memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31; tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62; return mktime(&tm); } static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef _MSC_VER struct tm tm_struct; struct tm *tm = &tm_struct; errno_t err = localtime_s(tm, &time); if (err) { *pDOS_date = 0; *pDOS_time = 0; return; } #else struct tm *tm = localtime(&time); #endif *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); } #endif #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef MINIZ_NO_TIME (void)pFilename; *pDOS_date = *pDOS_time = 0; #else struct MZ_FILE_STAT_STRUCT file_stat; // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE; mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date); #endif // #ifdef MINIZ_NO_TIME return MZ_TRUE; } #ifndef MINIZ_NO_TIME static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time) { struct utimbuf t; t.actime = access_time; t.modtime = modified_time; return !utime(pFilename, &t); } #endif // #ifndef MINIZ_NO_TIME #endif // #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags) { (void)flags; if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_READING; pZip->m_archive_size = 0; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (l_len < r_len) : (l < r); } #define MZ_SWAP_UINT32(a, b) do { mz_uint32 t = a; a = b; b = t; } MZ_MACRO_END // Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; int start = (size - 2) >> 1, end; while (start >= 0) { int child, root = start; for ( ; ; ) { if ((child = (root << 1) + 1) >= size) break; child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]))); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } start--; } end = size - 1; while (end > 0) { int child, root = 0; MZ_SWAP_UINT32(pIndices[end], pIndices[0]); for ( ; ; ) { if ((child = (root << 1) + 1) >= end) break; child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } end--; } } static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags) { mz_uint cdir_size, num_this_disk, cdir_disk_index; mz_uint64 cdir_ofs; mz_int64 cur_file_ofs; const mz_uint8 *p; mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); // Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; // Find the end of central directory record by scanning the file from the end towards the beginning. cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); for ( ; ; ) { int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) return MZ_FALSE; for (i = n - 4; i >= 0; --i) if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) break; if (i >= 0) { cur_file_ofs += i; break; } if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) return MZ_FALSE; cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); } // Read and verify the end of central directory record. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) || ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) return MZ_FALSE; num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) return MZ_FALSE; if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) return MZ_FALSE; pZip->m_central_directory_file_ofs = cdir_ofs; if (pZip->m_total_files) { mz_uint i, n; // Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and another to hold the sorted indices. if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) return MZ_FALSE; if (sort_central_dir) { if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) return MZ_FALSE; } if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) return MZ_FALSE; // Now create an index into the central directory file records, do some basic sanity checking on each record, and check for zip64 entries (which are not yet supported). p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) { mz_uint total_header_size, comp_size, decomp_size, disk_index; if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) return MZ_FALSE; MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); if (sort_central_dir) MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) return MZ_FALSE; disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); if ((disk_index != num_this_disk) && (disk_index != 1)) return MZ_FALSE; if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) return MZ_FALSE; n -= total_header_size; p += total_header_size; } } if (sort_central_dir) mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); return MZ_TRUE; } mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags) { if ((!pZip) || (!pZip->m_pRead)) return MZ_FALSE; if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); return s; } mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags) { if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; pZip->m_pRead = mz_zip_mem_read_func; pZip->m_pIO_opaque = pZip; #ifdef __cplusplus pZip->m_pState->m_pMem = const_cast<void *>(pMem); #else pZip->m_pState->m_pMem = (void *)pMem; #endif pZip->m_pState->m_mem_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) { mz_uint64 file_size; MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); if (!pFile) return MZ_FALSE; if (MZ_FSEEK64(pFile, 0, SEEK_END)) { MZ_FCLOSE(pFile); return MZ_FALSE; } file_size = MZ_FTELL64(pFile); if (!mz_zip_reader_init_internal(pZip, flags)) { MZ_FCLOSE(pFile); return MZ_FALSE; } pZip->m_pRead = mz_zip_file_read_func; pZip->m_pIO_opaque = pZip; pZip->m_pState->m_pFile = pFile; pZip->m_archive_size = file_size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) { return pZip ? pZip->m_total_files : 0; } static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh(mz_zip_archive *pZip, mz_uint file_index) { if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return NULL; return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); } mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) { mz_uint m_bit_flag; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); return (m_bit_flag & 1); } mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) { mz_uint filename_len, external_attr; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; // First see if the filename ends with a '/' character. filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_len) { if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') return MZ_TRUE; } // Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct. // Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field. // FIXME: Remove this check? Is it necessary - we already check the filename. external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); if ((external_attr & 0x10) != 0) return MZ_TRUE; return MZ_FALSE; } mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if ((!p) || (!pStat)) return MZ_FALSE; // Unpack the central directory record. pStat->m_file_index = file_index; pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); #ifndef MINIZ_NO_TIME pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); #endif pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); // Copy as much of the filename and comment as possible. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); pStat->m_comment_size = n; memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; return MZ_TRUE; } mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; } n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_buf_size) { n = MZ_MIN(n, filename_buf_size - 1); memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pFilename[n] = '\0'; } return n + 1; } static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) { mz_uint i; if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) return 0 == memcmp(pA, pB, len); for (i = 0; i < len; ++i) if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) return MZ_FALSE; return MZ_TRUE; } static MZ_FORCEINLINE int mz_zip_reader_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (int)(l_len - r_len) : (l - r); } static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; const mz_uint filename_len = (mz_uint)strlen(pFilename); int l = 0, h = size - 1; while (l <= h) { int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); if (!comp) return file_index; else if (comp < 0) l = m + 1; else h = m - 1; } return -1; } int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) { mz_uint file_index; size_t name_len, comment_len; if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return -1; if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) return mz_zip_reader_locate_file_binary_search(pZip, pName); name_len = strlen(pName); if (name_len > 0xFFFF) return -1; comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1; for (file_index = 0; file_index < pZip->m_total_files; file_index++) { const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; if (filename_len < name_len) continue; if (comment_len) { mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); const char *pFile_comment = pFilename + filename_len + file_extra_len; if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags))) continue; } if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) { int ofs = filename_len - 1; do { if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) break; } while (--ofs >= 0); ofs++; pFilename += ofs; filename_len -= ofs; } if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags))) return file_index; } return -1; } mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int status = TINFL_STATUS_DONE; mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; mz_zip_archive_file_stat file_stat; void *pRead_buf; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; tinfl_decompressor inflator; if ((buf_size) && (!pBuf)) return MZ_FALSE; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Ensure supplied output buffer is large enough. needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; if (buf_size < needed_size) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) return MZ_FALSE; return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32); } // Decompress the file either directly from memory or from a file input buffer. tinfl_init(&inflator); if (pZip->m_pState->m_pMem) { // Read directly from the archive in memory. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else if (pUser_read_buf) { // Use a user provided read buffer. if (!user_read_buf_size) return MZ_FALSE; pRead_buf = (mz_uint8 *)pUser_read_buf; read_buf_size = user_read_buf_size; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } else { // Temporarily allocate a read buffer. read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #endif return MZ_FALSE; if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } do { size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; out_buf_ofs += out_buf_size; } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); if (status == TINFL_STATUS_DONE) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); } mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); } mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); } void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) { mz_uint64 comp_size, uncomp_size, alloc_size; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); void *pBuf; if (pSize) *pSize = 0; if (!p) return NULL; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #endif return NULL; if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) return NULL; if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return NULL; } if (pSize) *pSize = (size_t)alloc_size; return pBuf; } void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) { if (pSize) *pSize = 0; return MZ_FALSE; } return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); } mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT; mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; mz_zip_archive_file_stat file_stat; void *pRead_buf = NULL; void *pWrite_buf = NULL; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; // Decompress the file either directly from memory or from a file input buffer. if (pZip->m_pState->m_pMem) { pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else { read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pState->m_pMem) { #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #endif return MZ_FALSE; if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) status = TINFL_STATUS_FAILED; else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); cur_file_ofs += file_stat.m_comp_size; out_buf_ofs += file_stat.m_comp_size; comp_remaining = 0; } else { while (comp_remaining) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; out_buf_ofs += read_buf_avail; comp_remaining -= read_buf_avail; } } } else { tinfl_decompressor inflator; tinfl_init(&inflator); if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) status = TINFL_STATUS_FAILED; else { do { mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; if (out_buf_size) { if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) { status = TINFL_STATUS_FAILED; break; } file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) { status = TINFL_STATUS_FAILED; break; } } } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); } } if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if (!pZip->m_pState->m_pMem) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); if (pWrite_buf) pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) { (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE*)pOpaque); } mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) { mz_bool status; mz_zip_archive_file_stat file_stat; MZ_FILE *pFile; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; pFile = MZ_FOPEN(pDst_filename, "wb"); if (!pFile) return MZ_FALSE; status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); if (MZ_FCLOSE(pFile) == EOF) return MZ_FALSE; #ifndef MINIZ_NO_TIME if (status) mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); #endif return status; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_end(mz_zip_archive *pZip) { if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; if (pZip->m_pState) { mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO pZip->m_pFree(pZip->m_pAlloc_opaque, pState); } pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); } #endif // ------------------- .ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); } static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); } #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) { if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (pZip->m_file_offset_alignment) { // Ensure user specified file offset alignment is a power of 2. if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) return MZ_FALSE; } if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_archive_size = existing_size; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_zip_internal_state *pState = pZip->m_pState; mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); #ifdef _MSC_VER if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #else if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #endif return 0; if (new_size > pState->m_mem_capacity) { void *pNew_block; size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2; if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) return 0; pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity; } memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); pState->m_mem_size = (size_t)new_size; return n; } mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) { pZip->m_pWrite = mz_zip_heap_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) { if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_mem_capacity = initial_allocation_size; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) { MZ_FILE *pFile; pZip->m_pWrite = mz_zip_file_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_pFile = pFile; if (size_to_reserve_at_beginning) { mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf); do { size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) { mz_zip_writer_end(pZip); return MZ_FALSE; } cur_ofs += n; size_to_reserve_at_beginning -= n; } while (size_to_reserve_at_beginning); } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; // No sense in trying to write to an archive that's already at the support max size if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; pState = pZip->m_pState; if (pState->m_pFile) { #ifdef MINIZ_NO_STDIO pFilename; return MZ_FALSE; #else // Archive is being read from stdio - try to reopen as writable. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; if (!pFilename) return MZ_FALSE; pZip->m_pWrite = mz_zip_file_write_func; if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) { // The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. mz_zip_reader_end(pZip); return MZ_FALSE; } #endif // #ifdef MINIZ_NO_STDIO } else if (pState->m_pMem) { // Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; pState->m_mem_capacity = pState->m_mem_size; pZip->m_pWrite = mz_zip_heap_write_func; } // Archive is being read via a user provided read function - make sure the user has specified a write function too. else if (!pZip->m_pWrite) return MZ_FALSE; // Start writing new files at the archive's current central directory location. pZip->m_archive_size = pZip->m_central_directory_file_ofs; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_central_directory_file_ofs = 0; return MZ_TRUE; } mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) { return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); } typedef struct { mz_zip_archive *m_pZip; mz_uint64 m_cur_archive_file_ofs; mz_uint64 m_comp_size; } mz_zip_writer_add_state; static mz_bool mz_zip_writer_add_put_buf_callback(const void* pBuf, int len, void *pUser) { mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) return MZ_FALSE; pState->m_cur_archive_file_ofs += len; pState->m_comp_size += len; return MZ_TRUE; } static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) { (void)pZip; memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); return MZ_TRUE; } static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { (void)pZip; memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs); return MZ_TRUE; } static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { mz_zip_internal_state *pState = pZip->m_pState; mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; size_t orig_central_dir_size = pState->m_central_dir.m_size; mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; // No zip64 support yet if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) return MZ_FALSE; if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &central_dir_ofs, 1))) { // Try to push the central directory array back into its original state. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } return MZ_TRUE; } static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) { // Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. if (*pArchive_name == '/') return MZ_FALSE; while (*pArchive_name) { if ((*pArchive_name == '\\') || (*pArchive_name == ':')) return MZ_FALSE; pArchive_name++; } return MZ_TRUE; } static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) { mz_uint32 n; if (!pZip->m_file_offset_alignment) return 0; n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1); } static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) { char buf[4096]; memset(buf, 0, MZ_MIN(sizeof(buf), n)); while (n) { mz_uint32 s = MZ_MIN(sizeof(buf), n); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) return MZ_FALSE; cur_file_ofs += s; n -= s; } return MZ_TRUE; } mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) { mz_uint16 method = 0, dos_time = 0, dos_date = 0; mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; tdefl_compressor *pComp = NULL; mz_bool store_data_uncompressed; mz_zip_internal_state *pState; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; pState = pZip->m_pState; if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) return MZ_FALSE; // No zip64 support yet if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; #ifndef MINIZ_NO_TIME { time_t cur_time; time(&cur_time); mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date); } #endif // #ifndef MINIZ_NO_TIME archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) { // Set DOS Subdirectory attribute bit. ext_attributes |= 0x10; // Subdirectories cannot contain data. if ((buf_size) || (uncomp_size)) return MZ_FALSE; } // Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) return MZ_FALSE; if ((!store_data_uncompressed) && (buf_size)) { if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) return MZ_FALSE; } if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8*)pBuf, buf_size); uncomp_size = buf_size; if (uncomp_size <= 3) { level = 0; store_data_uncompressed = MZ_TRUE; } } if (store_data_uncompressed) { if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += buf_size; comp_size = buf_size; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) method = MZ_DEFLATED; } else if (buf_size) { mz_zip_writer_add_state state; state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pComp = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; MZ_FILE *pSrc_file = NULL; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date)) return MZ_FALSE; pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); if (!pSrc_file) return MZ_FALSE; MZ_FSEEK64(pSrc_file, 0, SEEK_END); uncomp_size = MZ_FTELL64(pSrc_file); MZ_FSEEK64(pSrc_file, 0, SEEK_SET); if (uncomp_size > 0xFFFFFFFF) { // No zip64 support yet MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (uncomp_size <= 3) level = 0; if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (uncomp_size) { mz_uint64 uncomp_remaining = uncomp_size; void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); if (!pRead_buf) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (!level) { while (uncomp_remaining) { mz_uint n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); uncomp_remaining -= n; cur_archive_file_ofs += n; } comp_size = uncomp_size; } else { mz_bool result = MZ_FALSE; mz_zip_writer_add_state state; tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); if (!pComp) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } for ( ; ; ) { size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, MZ_ZIP_MAX_IO_BUF_SIZE); tdefl_status status; if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) break; uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); uncomp_remaining -= in_buf_size; status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); if (status == TDEFL_STATUS_DONE) { result = MZ_TRUE; break; } else if (status != TDEFL_STATUS_OKAY) break; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); if (!result) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); } MZ_FCLOSE(pSrc_file); pSrc_file = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index) { mz_uint n, bit_flags, num_alignment_padding_bytes; mz_uint64 comp_bytes_remaining, local_dir_header_ofs; mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; size_t orig_central_dir_size; mz_zip_internal_state *pState; void *pBuf; const mz_uint8 *pSrc_central_header; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index))) return MZ_FALSE; pState = pZip->m_pState; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); cur_dst_file_ofs = pZip->m_archive_size; if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) return MZ_FALSE; cur_dst_file_ofs += num_alignment_padding_bytes; local_dir_header_ofs = cur_dst_file_ofs; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining))))) return MZ_FALSE; while (comp_bytes_remaining) { n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_dst_file_ofs += n; comp_bytes_remaining -= n; } bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); if (bit_flags & 8) { // Copy data descriptor if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; cur_dst_file_ofs += n; } pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); // no zip64 support yet if (cur_dst_file_ofs > 0xFFFFFFFF) return MZ_FALSE; orig_central_dir_size = pState->m_central_dir.m_size; memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) return MZ_FALSE; n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } if (pState->m_central_dir.m_size > 0xFFFFFFFF) return MZ_FALSE; n = (mz_uint32)orig_central_dir_size; if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } pZip->m_total_files++; pZip->m_archive_size = cur_dst_file_ofs; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_uint64 central_dir_ofs, central_dir_size; mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; pState = pZip->m_pState; // no zip64 support yet if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; central_dir_ofs = 0; central_dir_size = 0; if (pZip->m_total_files) { // Write central directory central_dir_ofs = pZip->m_archive_size; central_dir_size = pState->m_central_dir.m_size; pZip->m_central_directory_file_ofs = central_dir_ofs; if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) return MZ_FALSE; pZip->m_archive_size += central_dir_size; } // Write end of central directory record MZ_CLEAR_OBJ(hdr); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr)) return MZ_FALSE; #ifndef MINIZ_NO_STDIO if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) return MZ_FALSE; #endif // #ifndef MINIZ_NO_STDIO pZip->m_archive_size += sizeof(hdr); pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize) { if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) return MZ_FALSE; if (pZip->m_pWrite != mz_zip_heap_write_func) return MZ_FALSE; if (!mz_zip_writer_finalize_archive(pZip)) return MZ_FALSE; *pBuf = pZip->m_pState->m_pMem; *pSize = pZip->m_pState->m_mem_size; pZip->m_pState->m_pMem = NULL; pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; return MZ_TRUE; } mz_bool mz_zip_writer_end(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_bool status = MZ_TRUE; if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) return MZ_FALSE; pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); pState->m_pMem = NULL; } pZip->m_pFree(pZip->m_pAlloc_opaque, pState); pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return status; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_bool status, created_new_archive = MZ_FALSE; mz_zip_archive zip_archive; struct MZ_FILE_STAT_STRUCT file_stat; MZ_CLEAR_OBJ(zip_archive); if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) { // Create a new archive. if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0)) return MZ_FALSE; created_new_archive = MZ_TRUE; } else { // Append to an existing archive. if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return MZ_FALSE; if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) { mz_zip_reader_end(&zip_archive); return MZ_FALSE; } } status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); // Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) if (!mz_zip_writer_finalize_archive(&zip_archive)) status = MZ_FALSE; if (!mz_zip_writer_end(&zip_archive)) status = MZ_FALSE; if ((!status) && (created_new_archive)) { // It's a new archive and something went wrong, so just delete it. int ignoredStatus = MZ_DELETE_FILE(pZip_filename); (void)ignoredStatus; } return status; } void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) { int file_index; mz_zip_archive zip_archive; void *p = NULL; if (pSize) *pSize = 0; if ((!pZip_filename) || (!pArchive_name)) return NULL; MZ_CLEAR_OBJ(zip_archive); if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return NULL; if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0) p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); mz_zip_reader_end(&zip_archive); return p; } #endif // #ifndef MINIZ_NO_STDIO #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef __cplusplus } #endif #endif // MINIZ_HEADER_FILE_ONLY /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org/> */
YifuLiu/AliOS-Things
components/SDL2/src/image/miniz.h
C
apache-2.0
227,537
#! /bin/sh # Common wrapper for a few potentially missing GNU programs. scriptversion=2018-01-04.22; # UTC # Copyright (C) 1996-2018 Free Software Foundation, Inc. # Originally written by Fran,cois Pinard <pinard@iro.umontreal.ca>, 1996. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. if test $# -eq 0; then echo 1>&2 "Try '$0 --help' for more information" exit 1 fi case $1 in --is-lightweight) # Used by our autoconf macros to check whether the available missing # script is modern enough. exit 0 ;; --run) # Back-compat with the calling convention used by older automake. shift ;; -h|--h|--he|--hel|--help) echo "\ $0 [OPTION]... PROGRAM [ARGUMENT]... Run 'PROGRAM [ARGUMENT]...', returning a proper advice when this fails due to PROGRAM being missing or too old. Options: -h, --help display this help and exit -v, --version output version information and exit Supported PROGRAM values: aclocal autoconf autoheader autom4te automake makeinfo bison yacc flex lex help2man Version suffixes to PROGRAM as well as the prefixes 'gnu-', 'gnu', and 'g' are ignored when checking the name. Send bug reports to <bug-automake@gnu.org>." exit $? ;; -v|--v|--ve|--ver|--vers|--versi|--versio|--version) echo "missing $scriptversion (GNU Automake)" exit $? ;; -*) echo 1>&2 "$0: unknown '$1' option" echo 1>&2 "Try '$0 --help' for more information" exit 1 ;; esac # Run the given program, remember its exit status. "$@"; st=$? # If it succeeded, we are done. test $st -eq 0 && exit 0 # Also exit now if we it failed (or wasn't found), and '--version' was # passed; such an option is passed most likely to detect whether the # program is present and works. case $2 in --version|--help) exit $st;; esac # Exit code 63 means version mismatch. This often happens when the user # tries to use an ancient version of a tool on a file that requires a # minimum version. if test $st -eq 63; then msg="probably too old" elif test $st -eq 127; then # Program was missing. msg="missing on your system" else # Program was found and executed, but failed. Give up. exit $st fi perl_URL=https://www.perl.org/ flex_URL=https://github.com/westes/flex gnu_software_URL=https://www.gnu.org/software program_details () { case $1 in aclocal|automake) echo "The '$1' program is part of the GNU Automake package:" echo "<$gnu_software_URL/automake>" echo "It also requires GNU Autoconf, GNU m4 and Perl in order to run:" echo "<$gnu_software_URL/autoconf>" echo "<$gnu_software_URL/m4/>" echo "<$perl_URL>" ;; autoconf|autom4te|autoheader) echo "The '$1' program is part of the GNU Autoconf package:" echo "<$gnu_software_URL/autoconf/>" echo "It also requires GNU m4 and Perl in order to run:" echo "<$gnu_software_URL/m4/>" echo "<$perl_URL>" ;; esac } give_advice () { # Normalize program name to check for. normalized_program=`echo "$1" | sed ' s/^gnu-//; t s/^gnu//; t s/^g//; t'` printf '%s\n' "'$1' is $msg." configure_deps="'configure.ac' or m4 files included by 'configure.ac'" case $normalized_program in autoconf*) echo "You should only need it if you modified 'configure.ac'," echo "or m4 files included by it." program_details 'autoconf' ;; autoheader*) echo "You should only need it if you modified 'acconfig.h' or" echo "$configure_deps." program_details 'autoheader' ;; automake*) echo "You should only need it if you modified 'Makefile.am' or" echo "$configure_deps." program_details 'automake' ;; aclocal*) echo "You should only need it if you modified 'acinclude.m4' or" echo "$configure_deps." program_details 'aclocal' ;; autom4te*) echo "You might have modified some maintainer files that require" echo "the 'autom4te' program to be rebuilt." program_details 'autom4te' ;; bison*|yacc*) echo "You should only need it if you modified a '.y' file." echo "You may want to install the GNU Bison package:" echo "<$gnu_software_URL/bison/>" ;; lex*|flex*) echo "You should only need it if you modified a '.l' file." echo "You may want to install the Fast Lexical Analyzer package:" echo "<$flex_URL>" ;; help2man*) echo "You should only need it if you modified a dependency" \ "of a man page." echo "You may want to install the GNU Help2man package:" echo "<$gnu_software_URL/help2man/>" ;; makeinfo*) echo "You should only need it if you modified a '.texi' file, or" echo "any other file indirectly affecting the aspect of the manual." echo "You might want to install the Texinfo package:" echo "<$gnu_software_URL/texinfo/>" echo "The spurious makeinfo call might also be the consequence of" echo "using a buggy 'make' (AIX, DU, IRIX), in which case you might" echo "want to install GNU make:" echo "<$gnu_software_URL/make/>" ;; *) echo "You might have modified some files without having the proper" echo "tools for further handling them. Check the 'README' file, it" echo "often tells you about the needed prerequisites for installing" echo "this package. You may also peek at any GNU archive site, in" echo "case some other package contains this missing '$1' program." ;; esac } give_advice "$1" | sed -e '1s/^/WARNING: /' \ -e '2,$s/^/ /' >&2 # Propagate the correct exit status (expected to be 127 for a program # not found, 63 for a program that failed due to version mismatch). exit $st # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End:
YifuLiu/AliOS-Things
components/SDL2/src/image/missing
Shell
apache-2.0
6,878
/* * Copyright (c) 2013-14 Mikko Mononen memon@inside.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * * The SVG parser is based on Anti-Grain Geometry 2.4 SVG example * Copyright (C) 2002-2004 Maxim Shemanarev (McSeem) (http://www.antigrain.com/) * * Arc calculation code based on canvg (https://code.google.com/p/canvg/) * * Bounding box calculation based on http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html * */ #ifndef NANOSVG_H #define NANOSVG_H #ifdef __cplusplus extern "C" { #endif // NanoSVG is a simple stupid single-header-file SVG parse. The output of the parser is a list of cubic bezier shapes. // // The library suits well for anything from rendering scalable icons in your editor application to prototyping a game. // // NanoSVG supports a wide range of SVG features, but something may be missing, feel free to create a pull request! // // The shapes in the SVG images are transformed by the viewBox and converted to specified units. // That is, you should get the same looking data as your designed in your favorite app. // // NanoSVG can return the paths in few different units. For example if you want to render an image, you may choose // to get the paths in pixels, or if you are feeding the data into a CNC-cutter, you may want to use millimeters. // // The units passed to NanoVG should be one of: 'px', 'pt', 'pc' 'mm', 'cm', or 'in'. // DPI (dots-per-inch) controls how the unit conversion is done. // // If you don't know or care about the units stuff, "px" and 96 should get you going. /* Example Usage: // Load NSVGImage* image; image = nsvgParseFromFile("test.svg", "px", 96); printf("size: %f x %f\n", image->width, image->height); // Use... for (NSVGshape *shape = image->shapes; shape != NULL; shape = shape->next) { for (NSVGpath *path = shape->paths; path != NULL; path = path->next) { for (int i = 0; i < path->npts-1; i += 3) { float* p = &path->pts[i*2]; drawCubicBez(p[0],p[1], p[2],p[3], p[4],p[5], p[6],p[7]); } } } // Delete nsvgDelete(image); */ enum NSVGpaintType { NSVG_PAINT_NONE = 0, NSVG_PAINT_COLOR = 1, NSVG_PAINT_LINEAR_GRADIENT = 2, NSVG_PAINT_RADIAL_GRADIENT = 3 }; enum NSVGspreadType { NSVG_SPREAD_PAD = 0, NSVG_SPREAD_REFLECT = 1, NSVG_SPREAD_REPEAT = 2 }; enum NSVGlineJoin { NSVG_JOIN_MITER = 0, NSVG_JOIN_ROUND = 1, NSVG_JOIN_BEVEL = 2 }; enum NSVGlineCap { NSVG_CAP_BUTT = 0, NSVG_CAP_ROUND = 1, NSVG_CAP_SQUARE = 2 }; enum NSVGfillRule { NSVG_FILLRULE_NONZERO = 0, NSVG_FILLRULE_EVENODD = 1 }; enum NSVGflags { NSVG_FLAGS_VISIBLE = 0x01 }; typedef struct NSVGgradientStop { unsigned int color; float offset; } NSVGgradientStop; typedef struct NSVGgradient { float xform[6]; char spread; float fx, fy; int nstops; NSVGgradientStop stops[1]; } NSVGgradient; typedef struct NSVGpaint { char type; union { unsigned int color; NSVGgradient* gradient; }; } NSVGpaint; typedef struct NSVGpath { float* pts; // Cubic bezier points: x0,y0, [cpx1,cpx1,cpx2,cpy2,x1,y1], ... int npts; // Total number of bezier points. char closed; // Flag indicating if shapes should be treated as closed. float bounds[4]; // Tight bounding box of the shape [minx,miny,maxx,maxy]. struct NSVGpath* next; // Pointer to next path, or NULL if last element. } NSVGpath; typedef struct NSVGshape { char id[64]; // Optional 'id' attr of the shape or its group NSVGpaint fill; // Fill paint NSVGpaint stroke; // Stroke paint float opacity; // Opacity of the shape. float strokeWidth; // Stroke width (scaled). float strokeDashOffset; // Stroke dash offset (scaled). float strokeDashArray[8]; // Stroke dash array (scaled). char strokeDashCount; // Number of dash values in dash array. char strokeLineJoin; // Stroke join type. char strokeLineCap; // Stroke cap type. float miterLimit; // Miter limit char fillRule; // Fill rule, see NSVGfillRule. unsigned char flags; // Logical or of NSVG_FLAGS_* flags float bounds[4]; // Tight bounding box of the shape [minx,miny,maxx,maxy]. NSVGpath* paths; // Linked list of paths in the image. struct NSVGshape* next; // Pointer to next shape, or NULL if last element. } NSVGshape; typedef struct NSVGimage { float width; // Width of the image. float height; // Height of the image. NSVGshape* shapes; // Linked list of shapes in the image. } NSVGimage; // Parses SVG file from a file, returns SVG image as paths. NSVGimage* nsvgParseFromFile(const char* filename, const char* units, float dpi); // Parses SVG file from a null terminated string, returns SVG image as paths. // Important note: changes the string. NSVGimage* nsvgParse(char* input, const char* units, float dpi); // Deletes list of paths. void nsvgDelete(NSVGimage* image); #ifdef __cplusplus } #endif #endif // NANOSVG_H #ifdef NANOSVG_IMPLEMENTATION /* #include <string.h> #include <stdlib.h> #include <math.h> */ #define NSVG_PI (3.14159265358979323846264338327f) #define NSVG_KAPPA90 (0.5522847493f) // Length proportional to radius of a cubic bezier handle for 90deg arcs. #define NSVG_ALIGN_MIN 0 #define NSVG_ALIGN_MID 1 #define NSVG_ALIGN_MAX 2 #define NSVG_ALIGN_NONE 0 #define NSVG_ALIGN_MEET 1 #define NSVG_ALIGN_SLICE 2 #define NSVG_NOTUSED(v) do { (void)(1 ? (void)0 : ( (void)(v) ) ); } while(0) #define NSVG_RGB(r, g, b) (((unsigned int)r) | ((unsigned int)g << 8) | ((unsigned int)b << 16)) #ifdef _MSC_VER #pragma warning (disable: 4996) // Switch off security warnings #pragma warning (disable: 4100) // Switch off unreferenced formal parameter warnings #ifdef __cplusplus #define NSVG_INLINE inline #else #define NSVG_INLINE #endif #else #define NSVG_INLINE inline #endif static int nsvg__isspace(char c) { return strchr(" \t\n\v\f\r", c) != 0; } static int nsvg__isdigit(char c) { return c >= '0' && c <= '9'; } static int nsvg__isnum(char c) { return strchr("0123456789+-.eE", c) != 0; } static NSVG_INLINE float nsvg__minf(float a, float b) { return a < b ? a : b; } static NSVG_INLINE float nsvg__maxf(float a, float b) { return a > b ? a : b; } // Simple XML parser #define NSVG_XML_TAG 1 #define NSVG_XML_CONTENT 2 #define NSVG_XML_MAX_ATTRIBS 256 static void nsvg__parseContent(char* s, void (*contentCb)(void* ud, const char* s), void* ud) { // Trim start white spaces while (*s && nsvg__isspace(*s)) s++; if (!*s) return; if (contentCb) (*contentCb)(ud, s); } static void nsvg__parseElement(char* s, void (*startelCb)(void* ud, const char* el, const char** attr), void (*endelCb)(void* ud, const char* el), void* ud) { const char* attr[NSVG_XML_MAX_ATTRIBS]; int nattr = 0; char* name; int start = 0; int end = 0; char quote; // Skip white space after the '<' while (*s && nsvg__isspace(*s)) s++; // Check if the tag is end tag if (*s == '/') { s++; end = 1; } else { start = 1; } // Skip comments, data and preprocessor stuff. if (!*s || *s == '?' || *s == '!') return; // Get tag name name = s; while (*s && !nsvg__isspace(*s)) s++; if (*s) { *s++ = '\0'; } // Get attribs while (!end && *s && nattr < NSVG_XML_MAX_ATTRIBS-3) { char* name = NULL; char* value = NULL; // Skip white space before the attrib name while (*s && nsvg__isspace(*s)) s++; if (!*s) break; if (*s == '/') { end = 1; break; } name = s; // Find end of the attrib name. while (*s && !nsvg__isspace(*s) && *s != '=') s++; if (*s) { *s++ = '\0'; } // Skip until the beginning of the value. while (*s && *s != '\"' && *s != '\'') s++; if (!*s) break; quote = *s; s++; // Store value and find the end of it. value = s; while (*s && *s != quote) s++; if (*s) { *s++ = '\0'; } // Store only well formed attributes if (name && value) { attr[nattr++] = name; attr[nattr++] = value; } } // List terminator attr[nattr++] = 0; attr[nattr++] = 0; // Call callbacks. if (start && startelCb) (*startelCb)(ud, name, attr); if (end && endelCb) (*endelCb)(ud, name); } int nsvg__parseXML(char* input, void (*startelCb)(void* ud, const char* el, const char** attr), void (*endelCb)(void* ud, const char* el), void (*contentCb)(void* ud, const char* s), void* ud) { char* s = input; char* mark = s; int state = NSVG_XML_CONTENT; while (*s) { if (*s == '<' && state == NSVG_XML_CONTENT) { // Start of a tag *s++ = '\0'; nsvg__parseContent(mark, contentCb, ud); mark = s; state = NSVG_XML_TAG; } else if (*s == '>' && state == NSVG_XML_TAG) { // Start of a content or new tag. *s++ = '\0'; nsvg__parseElement(mark, startelCb, endelCb, ud); mark = s; state = NSVG_XML_CONTENT; } else { s++; } } return 1; } /* Simple SVG parser. */ #define NSVG_MAX_ATTR 128 enum NSVGgradientUnits { NSVG_USER_SPACE = 0, NSVG_OBJECT_SPACE = 1 }; #define NSVG_MAX_DASHES 8 enum NSVGunits { NSVG_UNITS_USER, NSVG_UNITS_PX, NSVG_UNITS_PT, NSVG_UNITS_PC, NSVG_UNITS_MM, NSVG_UNITS_CM, NSVG_UNITS_IN, NSVG_UNITS_PERCENT, NSVG_UNITS_EM, NSVG_UNITS_EX }; typedef struct NSVGcoordinate { float value; int units; } NSVGcoordinate; typedef struct NSVGlinearData { NSVGcoordinate x1, y1, x2, y2; } NSVGlinearData; typedef struct NSVGradialData { NSVGcoordinate cx, cy, r, fx, fy; } NSVGradialData; typedef struct NSVGgradientData { char id[64]; char ref[64]; char type; union { NSVGlinearData linear; NSVGradialData radial; }; char spread; char units; float xform[6]; int nstops; NSVGgradientStop* stops; struct NSVGgradientData* next; } NSVGgradientData; typedef struct NSVGattrib { char id[64]; float xform[6]; unsigned int fillColor; unsigned int strokeColor; float opacity; float fillOpacity; float strokeOpacity; char fillGradient[64]; char strokeGradient[64]; float strokeWidth; float strokeDashOffset; float strokeDashArray[NSVG_MAX_DASHES]; int strokeDashCount; char strokeLineJoin; char strokeLineCap; float miterLimit; char fillRule; float fontSize; unsigned int stopColor; float stopOpacity; float stopOffset; char hasFill; char hasStroke; char visible; } NSVGattrib; typedef struct NSVGstyles { char* name; char* description; struct NSVGstyles* next; } NSVGstyles; typedef struct NSVGparser { NSVGattrib attr[NSVG_MAX_ATTR]; int attrHead; float* pts; int npts; int cpts; NSVGpath* plist; NSVGimage* image; NSVGstyles* styles; NSVGgradientData* gradients; NSVGshape* shapesTail; float viewMinx, viewMiny, viewWidth, viewHeight; int alignX, alignY, alignType; float dpi; char pathFlag; char defsFlag; char styleFlag; } NSVGparser; static void nsvg__xformIdentity(float* t) { t[0] = 1.0f; t[1] = 0.0f; t[2] = 0.0f; t[3] = 1.0f; t[4] = 0.0f; t[5] = 0.0f; } static void nsvg__xformSetTranslation(float* t, float tx, float ty) { t[0] = 1.0f; t[1] = 0.0f; t[2] = 0.0f; t[3] = 1.0f; t[4] = tx; t[5] = ty; } static void nsvg__xformSetScale(float* t, float sx, float sy) { t[0] = sx; t[1] = 0.0f; t[2] = 0.0f; t[3] = sy; t[4] = 0.0f; t[5] = 0.0f; } static void nsvg__xformSetSkewX(float* t, float a) { t[0] = 1.0f; t[1] = 0.0f; t[2] = tanf(a); t[3] = 1.0f; t[4] = 0.0f; t[5] = 0.0f; } static void nsvg__xformSetSkewY(float* t, float a) { t[0] = 1.0f; t[1] = tanf(a); t[2] = 0.0f; t[3] = 1.0f; t[4] = 0.0f; t[5] = 0.0f; } static void nsvg__xformSetRotation(float* t, float a) { float cs = cosf(a), sn = sinf(a); t[0] = cs; t[1] = sn; t[2] = -sn; t[3] = cs; t[4] = 0.0f; t[5] = 0.0f; } static void nsvg__xformMultiply(float* t, float* s) { float t0 = t[0] * s[0] + t[1] * s[2]; float t2 = t[2] * s[0] + t[3] * s[2]; float t4 = t[4] * s[0] + t[5] * s[2] + s[4]; t[1] = t[0] * s[1] + t[1] * s[3]; t[3] = t[2] * s[1] + t[3] * s[3]; t[5] = t[4] * s[1] + t[5] * s[3] + s[5]; t[0] = t0; t[2] = t2; t[4] = t4; } static void nsvg__xformInverse(float* inv, float* t) { double invdet, det = (double)t[0] * t[3] - (double)t[2] * t[1]; if (det > -1e-6 && det < 1e-6) { nsvg__xformIdentity(t); return; } invdet = 1.0 / det; inv[0] = (float)(t[3] * invdet); inv[2] = (float)(-t[2] * invdet); inv[4] = (float)(((double)t[2] * t[5] - (double)t[3] * t[4]) * invdet); inv[1] = (float)(-t[1] * invdet); inv[3] = (float)(t[0] * invdet); inv[5] = (float)(((double)t[1] * t[4] - (double)t[0] * t[5]) * invdet); } static void nsvg__xformPremultiply(float* t, float* s) { float s2[6]; memcpy(s2, s, sizeof(float)*6); nsvg__xformMultiply(s2, t); memcpy(t, s2, sizeof(float)*6); } static void nsvg__xformPoint(float* dx, float* dy, float x, float y, float* t) { *dx = x*t[0] + y*t[2] + t[4]; *dy = x*t[1] + y*t[3] + t[5]; } static void nsvg__xformVec(float* dx, float* dy, float x, float y, float* t) { *dx = x*t[0] + y*t[2]; *dy = x*t[1] + y*t[3]; } #define NSVG_EPSILON (1e-12) static int nsvg__ptInBounds(float* pt, float* bounds) { return pt[0] >= bounds[0] && pt[0] <= bounds[2] && pt[1] >= bounds[1] && pt[1] <= bounds[3]; } static double nsvg__evalBezier(double t, double p0, double p1, double p2, double p3) { double it = 1.0-t; return it*it*it*p0 + 3.0*it*it*t*p1 + 3.0*it*t*t*p2 + t*t*t*p3; } static void nsvg__curveBounds(float* bounds, float* curve) { int i, j, count; double roots[2], a, b, c, b2ac, t, v; float* v0 = &curve[0]; float* v1 = &curve[2]; float* v2 = &curve[4]; float* v3 = &curve[6]; // Start the bounding box by end points bounds[0] = nsvg__minf(v0[0], v3[0]); bounds[1] = nsvg__minf(v0[1], v3[1]); bounds[2] = nsvg__maxf(v0[0], v3[0]); bounds[3] = nsvg__maxf(v0[1], v3[1]); // Bezier curve fits inside the convex hull of it's control points. // If control points are inside the bounds, we're done. if (nsvg__ptInBounds(v1, bounds) && nsvg__ptInBounds(v2, bounds)) return; // Add bezier curve inflection points in X and Y. for (i = 0; i < 2; i++) { a = -3.0 * v0[i] + 9.0 * v1[i] - 9.0 * v2[i] + 3.0 * v3[i]; b = 6.0 * v0[i] - 12.0 * v1[i] + 6.0 * v2[i]; c = 3.0 * v1[i] - 3.0 * v0[i]; count = 0; if (fabs(a) < NSVG_EPSILON) { if (fabs(b) > NSVG_EPSILON) { t = -c / b; if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON) roots[count++] = t; } } else { b2ac = b*b - 4.0*c*a; if (b2ac > NSVG_EPSILON) { t = (-b + sqrt(b2ac)) / (2.0 * a); if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON) roots[count++] = t; t = (-b - sqrt(b2ac)) / (2.0 * a); if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON) roots[count++] = t; } } for (j = 0; j < count; j++) { v = nsvg__evalBezier(roots[j], v0[i], v1[i], v2[i], v3[i]); bounds[0+i] = nsvg__minf(bounds[0+i], (float)v); bounds[2+i] = nsvg__maxf(bounds[2+i], (float)v); } } } static NSVGparser* nsvg__createParser() { NSVGparser* p; p = (NSVGparser*)malloc(sizeof(NSVGparser)); if (p == NULL) goto error; memset(p, 0, sizeof(NSVGparser)); p->image = (NSVGimage*)malloc(sizeof(NSVGimage)); if (p->image == NULL) goto error; memset(p->image, 0, sizeof(NSVGimage)); // Init style nsvg__xformIdentity(p->attr[0].xform); memset(p->attr[0].id, 0, sizeof p->attr[0].id); p->attr[0].fillColor = NSVG_RGB(0,0,0); p->attr[0].strokeColor = NSVG_RGB(0,0,0); p->attr[0].opacity = 1; p->attr[0].fillOpacity = 1; p->attr[0].strokeOpacity = 1; p->attr[0].stopOpacity = 1; p->attr[0].strokeWidth = 1; p->attr[0].strokeLineJoin = NSVG_JOIN_MITER; p->attr[0].strokeLineCap = NSVG_CAP_BUTT; p->attr[0].miterLimit = 4; p->attr[0].fillRule = NSVG_FILLRULE_NONZERO; p->attr[0].hasFill = 1; p->attr[0].visible = 1; return p; error: if (p) { if (p->image) free(p->image); free(p); } return NULL; } static void nsvg__deleteStyles(NSVGstyles* style) { while (style) { NSVGstyles *next = style->next; if (style->name!= NULL) free(style->name); if (style->description != NULL) free(style->description); free(style); style = next; } } static void nsvg__deletePaths(NSVGpath* path) { while (path) { NSVGpath *next = path->next; if (path->pts != NULL) free(path->pts); free(path); path = next; } } static void nsvg__deletePaint(NSVGpaint* paint) { if (paint->type == NSVG_PAINT_LINEAR_GRADIENT || paint->type == NSVG_PAINT_RADIAL_GRADIENT) free(paint->gradient); } static void nsvg__deleteGradientData(NSVGgradientData* grad) { NSVGgradientData* next; while (grad != NULL) { next = grad->next; free(grad->stops); free(grad); grad = next; } } static void nsvg__deleteParser(NSVGparser* p) { if (p != NULL) { nsvg__deleteStyles(p->styles); nsvg__deletePaths(p->plist); nsvg__deleteGradientData(p->gradients); nsvgDelete(p->image); free(p->pts); free(p); } } static void nsvg__resetPath(NSVGparser* p) { p->npts = 0; } static void nsvg__addPoint(NSVGparser* p, float x, float y) { if (p->npts+1 > p->cpts) { p->cpts = p->cpts ? p->cpts*2 : 8; p->pts = (float*)realloc(p->pts, p->cpts*2*sizeof(float)); if (!p->pts) return; } p->pts[p->npts*2+0] = x; p->pts[p->npts*2+1] = y; p->npts++; } static void nsvg__moveTo(NSVGparser* p, float x, float y) { if (p->npts > 0) { p->pts[(p->npts-1)*2+0] = x; p->pts[(p->npts-1)*2+1] = y; } else { nsvg__addPoint(p, x, y); } } static void nsvg__lineTo(NSVGparser* p, float x, float y) { float px,py, dx,dy; if (p->npts > 0) { px = p->pts[(p->npts-1)*2+0]; py = p->pts[(p->npts-1)*2+1]; dx = x - px; dy = y - py; nsvg__addPoint(p, px + dx/3.0f, py + dy/3.0f); nsvg__addPoint(p, x - dx/3.0f, y - dy/3.0f); nsvg__addPoint(p, x, y); } } static void nsvg__cubicBezTo(NSVGparser* p, float cpx1, float cpy1, float cpx2, float cpy2, float x, float y) { nsvg__addPoint(p, cpx1, cpy1); nsvg__addPoint(p, cpx2, cpy2); nsvg__addPoint(p, x, y); } static NSVGattrib* nsvg__getAttr(NSVGparser* p) { return &p->attr[p->attrHead]; } static void nsvg__pushAttr(NSVGparser* p) { if (p->attrHead < NSVG_MAX_ATTR-1) { p->attrHead++; memcpy(&p->attr[p->attrHead], &p->attr[p->attrHead-1], sizeof(NSVGattrib)); } } static void nsvg__popAttr(NSVGparser* p) { if (p->attrHead > 0) p->attrHead--; } static float nsvg__actualOrigX(NSVGparser* p) { return p->viewMinx; } static float nsvg__actualOrigY(NSVGparser* p) { return p->viewMiny; } static float nsvg__actualWidth(NSVGparser* p) { return p->viewWidth; } static float nsvg__actualHeight(NSVGparser* p) { return p->viewHeight; } static float nsvg__actualLength(NSVGparser* p) { float w = nsvg__actualWidth(p), h = nsvg__actualHeight(p); return sqrtf(w*w + h*h) / sqrtf(2.0f); } static float nsvg__convertToPixels(NSVGparser* p, NSVGcoordinate c, float orig, float length) { NSVGattrib* attr = nsvg__getAttr(p); switch (c.units) { case NSVG_UNITS_USER: return c.value; case NSVG_UNITS_PX: return c.value; case NSVG_UNITS_PT: return c.value / 72.0f * p->dpi; case NSVG_UNITS_PC: return c.value / 6.0f * p->dpi; case NSVG_UNITS_MM: return c.value / 25.4f * p->dpi; case NSVG_UNITS_CM: return c.value / 2.54f * p->dpi; case NSVG_UNITS_IN: return c.value * p->dpi; case NSVG_UNITS_EM: return c.value * attr->fontSize; case NSVG_UNITS_EX: return c.value * attr->fontSize * 0.52f; // x-height of Helvetica. case NSVG_UNITS_PERCENT: return orig + c.value / 100.0f * length; default: return c.value; } return c.value; } static NSVGgradientData* nsvg__findGradientData(NSVGparser* p, const char* id) { NSVGgradientData* grad = p->gradients; while (grad) { if (strcmp(grad->id, id) == 0) return grad; grad = grad->next; } return NULL; } static NSVGgradient* nsvg__createGradient(NSVGparser* p, const char* id, const float* localBounds, char* paintType) { NSVGattrib* attr = nsvg__getAttr(p); NSVGgradientData* data = NULL; NSVGgradientData* ref = NULL; NSVGgradientStop* stops = NULL; NSVGgradient* grad; float ox, oy, sw, sh, sl; int nstops = 0; data = nsvg__findGradientData(p, id); if (data == NULL) return NULL; // TODO: use ref to fill in all unset values too. ref = data; while (ref != NULL) { if (stops == NULL && ref->stops != NULL) { stops = ref->stops; nstops = ref->nstops; break; } ref = nsvg__findGradientData(p, ref->ref); } if (stops == NULL) return NULL; grad = (NSVGgradient*)malloc(sizeof(NSVGgradient) + sizeof(NSVGgradientStop)*(nstops-1)); if (grad == NULL) return NULL; // The shape width and height. if (data->units == NSVG_OBJECT_SPACE) { ox = localBounds[0]; oy = localBounds[1]; sw = localBounds[2] - localBounds[0]; sh = localBounds[3] - localBounds[1]; } else { ox = nsvg__actualOrigX(p); oy = nsvg__actualOrigY(p); sw = nsvg__actualWidth(p); sh = nsvg__actualHeight(p); } sl = sqrtf(sw*sw + sh*sh) / sqrtf(2.0f); if (data->type == NSVG_PAINT_LINEAR_GRADIENT) { float x1, y1, x2, y2, dx, dy; x1 = nsvg__convertToPixels(p, data->linear.x1, ox, sw); y1 = nsvg__convertToPixels(p, data->linear.y1, oy, sh); x2 = nsvg__convertToPixels(p, data->linear.x2, ox, sw); y2 = nsvg__convertToPixels(p, data->linear.y2, oy, sh); // Calculate transform aligned to the line dx = x2 - x1; dy = y2 - y1; grad->xform[0] = dy; grad->xform[1] = -dx; grad->xform[2] = dx; grad->xform[3] = dy; grad->xform[4] = x1; grad->xform[5] = y1; } else { float cx, cy, fx, fy, r; cx = nsvg__convertToPixels(p, data->radial.cx, ox, sw); cy = nsvg__convertToPixels(p, data->radial.cy, oy, sh); fx = nsvg__convertToPixels(p, data->radial.fx, ox, sw); fy = nsvg__convertToPixels(p, data->radial.fy, oy, sh); r = nsvg__convertToPixels(p, data->radial.r, 0, sl); // Calculate transform aligned to the circle grad->xform[0] = r; grad->xform[1] = 0; grad->xform[2] = 0; grad->xform[3] = r; grad->xform[4] = cx; grad->xform[5] = cy; grad->fx = fx / r; grad->fy = fy / r; } nsvg__xformMultiply(grad->xform, data->xform); nsvg__xformMultiply(grad->xform, attr->xform); grad->spread = data->spread; memcpy(grad->stops, stops, nstops*sizeof(NSVGgradientStop)); grad->nstops = nstops; *paintType = data->type; return grad; } static float nsvg__getAverageScale(float* t) { float sx = sqrtf(t[0]*t[0] + t[2]*t[2]); float sy = sqrtf(t[1]*t[1] + t[3]*t[3]); return (sx + sy) * 0.5f; } static void nsvg__getLocalBounds(float* bounds, NSVGshape *shape, float* xform) { NSVGpath* path; float curve[4*2], curveBounds[4]; int i, first = 1; for (path = shape->paths; path != NULL; path = path->next) { nsvg__xformPoint(&curve[0], &curve[1], path->pts[0], path->pts[1], xform); for (i = 0; i < path->npts-1; i += 3) { nsvg__xformPoint(&curve[2], &curve[3], path->pts[(i+1)*2], path->pts[(i+1)*2+1], xform); nsvg__xformPoint(&curve[4], &curve[5], path->pts[(i+2)*2], path->pts[(i+2)*2+1], xform); nsvg__xformPoint(&curve[6], &curve[7], path->pts[(i+3)*2], path->pts[(i+3)*2+1], xform); nsvg__curveBounds(curveBounds, curve); if (first) { bounds[0] = curveBounds[0]; bounds[1] = curveBounds[1]; bounds[2] = curveBounds[2]; bounds[3] = curveBounds[3]; first = 0; } else { bounds[0] = nsvg__minf(bounds[0], curveBounds[0]); bounds[1] = nsvg__minf(bounds[1], curveBounds[1]); bounds[2] = nsvg__maxf(bounds[2], curveBounds[2]); bounds[3] = nsvg__maxf(bounds[3], curveBounds[3]); } curve[0] = curve[6]; curve[1] = curve[7]; } } } static void nsvg__addShape(NSVGparser* p) { NSVGattrib* attr = nsvg__getAttr(p); float scale = 1.0f; NSVGshape* shape; NSVGpath* path; int i; if (p->plist == NULL) return; shape = (NSVGshape*)malloc(sizeof(NSVGshape)); if (shape == NULL) goto error; memset(shape, 0, sizeof(NSVGshape)); memcpy(shape->id, attr->id, sizeof shape->id); scale = nsvg__getAverageScale(attr->xform); shape->strokeWidth = attr->strokeWidth * scale; shape->strokeDashOffset = attr->strokeDashOffset * scale; shape->strokeDashCount = (char)attr->strokeDashCount; for (i = 0; i < attr->strokeDashCount; i++) shape->strokeDashArray[i] = attr->strokeDashArray[i] * scale; shape->strokeLineJoin = attr->strokeLineJoin; shape->strokeLineCap = attr->strokeLineCap; shape->miterLimit = attr->miterLimit; shape->fillRule = attr->fillRule; shape->opacity = attr->opacity; shape->paths = p->plist; p->plist = NULL; // Calculate shape bounds shape->bounds[0] = shape->paths->bounds[0]; shape->bounds[1] = shape->paths->bounds[1]; shape->bounds[2] = shape->paths->bounds[2]; shape->bounds[3] = shape->paths->bounds[3]; for (path = shape->paths->next; path != NULL; path = path->next) { shape->bounds[0] = nsvg__minf(shape->bounds[0], path->bounds[0]); shape->bounds[1] = nsvg__minf(shape->bounds[1], path->bounds[1]); shape->bounds[2] = nsvg__maxf(shape->bounds[2], path->bounds[2]); shape->bounds[3] = nsvg__maxf(shape->bounds[3], path->bounds[3]); } // Set fill if (attr->hasFill == 0) { shape->fill.type = NSVG_PAINT_NONE; } else if (attr->hasFill == 1) { shape->fill.type = NSVG_PAINT_COLOR; shape->fill.color = attr->fillColor; shape->fill.color |= (unsigned int)(attr->fillOpacity*255) << 24; } else if (attr->hasFill == 2) { float inv[6], localBounds[4]; nsvg__xformInverse(inv, attr->xform); nsvg__getLocalBounds(localBounds, shape, inv); shape->fill.gradient = nsvg__createGradient(p, attr->fillGradient, localBounds, &shape->fill.type); if (shape->fill.gradient == NULL) { shape->fill.type = NSVG_PAINT_NONE; } } // Set stroke if (attr->hasStroke == 0) { shape->stroke.type = NSVG_PAINT_NONE; } else if (attr->hasStroke == 1) { shape->stroke.type = NSVG_PAINT_COLOR; shape->stroke.color = attr->strokeColor; shape->stroke.color |= (unsigned int)(attr->strokeOpacity*255) << 24; } else if (attr->hasStroke == 2) { float inv[6], localBounds[4]; nsvg__xformInverse(inv, attr->xform); nsvg__getLocalBounds(localBounds, shape, inv); shape->stroke.gradient = nsvg__createGradient(p, attr->strokeGradient, localBounds, &shape->stroke.type); if (shape->stroke.gradient == NULL) shape->stroke.type = NSVG_PAINT_NONE; } // Set flags shape->flags = (attr->visible ? NSVG_FLAGS_VISIBLE : 0x00); // Add to tail if (p->image->shapes == NULL) p->image->shapes = shape; else p->shapesTail->next = shape; p->shapesTail = shape; return; error: if (shape) free(shape); } static void nsvg__addPath(NSVGparser* p, char closed) { NSVGattrib* attr = nsvg__getAttr(p); NSVGpath* path = NULL; float bounds[4]; float* curve; int i; if (p->npts < 4) return; if (closed) nsvg__lineTo(p, p->pts[0], p->pts[1]); path = (NSVGpath*)malloc(sizeof(NSVGpath)); if (path == NULL) goto error; memset(path, 0, sizeof(NSVGpath)); path->pts = (float*)malloc(p->npts*2*sizeof(float)); if (path->pts == NULL) goto error; path->closed = closed; path->npts = p->npts; // Transform path. for (i = 0; i < p->npts; ++i) nsvg__xformPoint(&path->pts[i*2], &path->pts[i*2+1], p->pts[i*2], p->pts[i*2+1], attr->xform); // Find bounds for (i = 0; i < path->npts-1; i += 3) { curve = &path->pts[i*2]; nsvg__curveBounds(bounds, curve); if (i == 0) { path->bounds[0] = bounds[0]; path->bounds[1] = bounds[1]; path->bounds[2] = bounds[2]; path->bounds[3] = bounds[3]; } else { path->bounds[0] = nsvg__minf(path->bounds[0], bounds[0]); path->bounds[1] = nsvg__minf(path->bounds[1], bounds[1]); path->bounds[2] = nsvg__maxf(path->bounds[2], bounds[2]); path->bounds[3] = nsvg__maxf(path->bounds[3], bounds[3]); } } path->next = p->plist; p->plist = path; return; error: if (path != NULL) { if (path->pts != NULL) free(path->pts); free(path); } } // We roll our own string to float because the std library one uses locale and messes things up. static double nsvg__atof(const char* s) { char* cur = (char*)s; char* end = NULL; double res = 0.0, sign = 1.0; long long intPart = 0, fracPart = 0; char hasIntPart = 0, hasFracPart = 0; // Parse optional sign if (*cur == '+') { cur++; } else if (*cur == '-') { sign = -1; cur++; } // Parse integer part if (nsvg__isdigit(*cur)) { // Parse digit sequence intPart = strtoll(cur, &end, 10); if (cur != end) { res = (double)intPart; hasIntPart = 1; cur = end; } } // Parse fractional part. if (*cur == '.') { cur++; // Skip '.' if (nsvg__isdigit(*cur)) { // Parse digit sequence fracPart = strtoll(cur, &end, 10); if (cur != end) { res += (double)fracPart / pow(10.0, (double)(end - cur)); hasFracPart = 1; cur = end; } } } // A valid number should have integer or fractional part. if (!hasIntPart && !hasFracPart) return 0.0; // Parse optional exponent if (*cur == 'e' || *cur == 'E') { int expPart = 0; cur++; // skip 'E' expPart = (int)strtol(cur, &end, 10); // Parse digit sequence with sign if (cur != end) { res *= pow(10.0, (double)expPart); } } return res * sign; } static const char* nsvg__parseNumber(const char* s, char* it, const int size) { const int last = size-1; int i = 0; // sign if (*s == '-' || *s == '+') { if (i < last) it[i++] = *s; s++; } // integer part while (*s && nsvg__isdigit(*s)) { if (i < last) it[i++] = *s; s++; } if (*s == '.') { // decimal point if (i < last) it[i++] = *s; s++; // fraction part while (*s && nsvg__isdigit(*s)) { if (i < last) it[i++] = *s; s++; } } // exponent if (*s == 'e' || *s == 'E') { if (i < last) it[i++] = *s; s++; if (*s == '-' || *s == '+') { if (i < last) it[i++] = *s; s++; } while (*s && nsvg__isdigit(*s)) { if (i < last) it[i++] = *s; s++; } } it[i] = '\0'; return s; } static const char* nsvg__getNextPathItem(const char* s, char* it) { it[0] = '\0'; // Skip white spaces and commas while (*s && (nsvg__isspace(*s) || *s == ',')) s++; if (!*s) return s; if (*s == '-' || *s == '+' || *s == '.' || nsvg__isdigit(*s)) { s = nsvg__parseNumber(s, it, 64); } else { // Parse command it[0] = *s++; it[1] = '\0'; return s; } return s; } static unsigned int nsvg__parseColorHex(const char* str) { unsigned int c = 0, r = 0, g = 0, b = 0; int n = 0; str++; // skip # // Calculate number of characters. while(str[n] && !nsvg__isspace(str[n])) n++; if (n == 6) { sscanf(str, "%x", &c); } else if (n == 3) { sscanf(str, "%x", &c); c = (c&0xf) | ((c&0xf0) << 4) | ((c&0xf00) << 8); c |= c<<4; } r = (c >> 16) & 0xff; g = (c >> 8) & 0xff; b = c & 0xff; return NSVG_RGB(r,g,b); } static unsigned int nsvg__parseColorRGB(const char* str) { int r = -1, g = -1, b = -1; char s1[32]="", s2[32]=""; sscanf(str + 4, "%d%[%%, \t]%d%[%%, \t]%d", &r, s1, &g, s2, &b); if (strchr(s1, '%')) { return NSVG_RGB((r*255)/100,(g*255)/100,(b*255)/100); } else { return NSVG_RGB(r,g,b); } } typedef struct NSVGNamedColor { const char* name; unsigned int color; } NSVGNamedColor; NSVGNamedColor nsvg__colors[] = { { "red", NSVG_RGB(255, 0, 0) }, { "green", NSVG_RGB( 0, 128, 0) }, { "blue", NSVG_RGB( 0, 0, 255) }, { "yellow", NSVG_RGB(255, 255, 0) }, { "cyan", NSVG_RGB( 0, 255, 255) }, { "magenta", NSVG_RGB(255, 0, 255) }, { "black", NSVG_RGB( 0, 0, 0) }, { "grey", NSVG_RGB(128, 128, 128) }, { "gray", NSVG_RGB(128, 128, 128) }, { "white", NSVG_RGB(255, 255, 255) }, #ifdef NANOSVG_ALL_COLOR_KEYWORDS { "aliceblue", NSVG_RGB(240, 248, 255) }, { "antiquewhite", NSVG_RGB(250, 235, 215) }, { "aqua", NSVG_RGB( 0, 255, 255) }, { "aquamarine", NSVG_RGB(127, 255, 212) }, { "azure", NSVG_RGB(240, 255, 255) }, { "beige", NSVG_RGB(245, 245, 220) }, { "bisque", NSVG_RGB(255, 228, 196) }, { "blanchedalmond", NSVG_RGB(255, 235, 205) }, { "blueviolet", NSVG_RGB(138, 43, 226) }, { "brown", NSVG_RGB(165, 42, 42) }, { "burlywood", NSVG_RGB(222, 184, 135) }, { "cadetblue", NSVG_RGB( 95, 158, 160) }, { "chartreuse", NSVG_RGB(127, 255, 0) }, { "chocolate", NSVG_RGB(210, 105, 30) }, { "coral", NSVG_RGB(255, 127, 80) }, { "cornflowerblue", NSVG_RGB(100, 149, 237) }, { "cornsilk", NSVG_RGB(255, 248, 220) }, { "crimson", NSVG_RGB(220, 20, 60) }, { "darkblue", NSVG_RGB( 0, 0, 139) }, { "darkcyan", NSVG_RGB( 0, 139, 139) }, { "darkgoldenrod", NSVG_RGB(184, 134, 11) }, { "darkgray", NSVG_RGB(169, 169, 169) }, { "darkgreen", NSVG_RGB( 0, 100, 0) }, { "darkgrey", NSVG_RGB(169, 169, 169) }, { "darkkhaki", NSVG_RGB(189, 183, 107) }, { "darkmagenta", NSVG_RGB(139, 0, 139) }, { "darkolivegreen", NSVG_RGB( 85, 107, 47) }, { "darkorange", NSVG_RGB(255, 140, 0) }, { "darkorchid", NSVG_RGB(153, 50, 204) }, { "darkred", NSVG_RGB(139, 0, 0) }, { "darksalmon", NSVG_RGB(233, 150, 122) }, { "darkseagreen", NSVG_RGB(143, 188, 143) }, { "darkslateblue", NSVG_RGB( 72, 61, 139) }, { "darkslategray", NSVG_RGB( 47, 79, 79) }, { "darkslategrey", NSVG_RGB( 47, 79, 79) }, { "darkturquoise", NSVG_RGB( 0, 206, 209) }, { "darkviolet", NSVG_RGB(148, 0, 211) }, { "deeppink", NSVG_RGB(255, 20, 147) }, { "deepskyblue", NSVG_RGB( 0, 191, 255) }, { "dimgray", NSVG_RGB(105, 105, 105) }, { "dimgrey", NSVG_RGB(105, 105, 105) }, { "dodgerblue", NSVG_RGB( 30, 144, 255) }, { "firebrick", NSVG_RGB(178, 34, 34) }, { "floralwhite", NSVG_RGB(255, 250, 240) }, { "forestgreen", NSVG_RGB( 34, 139, 34) }, { "fuchsia", NSVG_RGB(255, 0, 255) }, { "gainsboro", NSVG_RGB(220, 220, 220) }, { "ghostwhite", NSVG_RGB(248, 248, 255) }, { "gold", NSVG_RGB(255, 215, 0) }, { "goldenrod", NSVG_RGB(218, 165, 32) }, { "greenyellow", NSVG_RGB(173, 255, 47) }, { "honeydew", NSVG_RGB(240, 255, 240) }, { "hotpink", NSVG_RGB(255, 105, 180) }, { "indianred", NSVG_RGB(205, 92, 92) }, { "indigo", NSVG_RGB( 75, 0, 130) }, { "ivory", NSVG_RGB(255, 255, 240) }, { "khaki", NSVG_RGB(240, 230, 140) }, { "lavender", NSVG_RGB(230, 230, 250) }, { "lavenderblush", NSVG_RGB(255, 240, 245) }, { "lawngreen", NSVG_RGB(124, 252, 0) }, { "lemonchiffon", NSVG_RGB(255, 250, 205) }, { "lightblue", NSVG_RGB(173, 216, 230) }, { "lightcoral", NSVG_RGB(240, 128, 128) }, { "lightcyan", NSVG_RGB(224, 255, 255) }, { "lightgoldenrodyellow", NSVG_RGB(250, 250, 210) }, { "lightgray", NSVG_RGB(211, 211, 211) }, { "lightgreen", NSVG_RGB(144, 238, 144) }, { "lightgrey", NSVG_RGB(211, 211, 211) }, { "lightpink", NSVG_RGB(255, 182, 193) }, { "lightsalmon", NSVG_RGB(255, 160, 122) }, { "lightseagreen", NSVG_RGB( 32, 178, 170) }, { "lightskyblue", NSVG_RGB(135, 206, 250) }, { "lightslategray", NSVG_RGB(119, 136, 153) }, { "lightslategrey", NSVG_RGB(119, 136, 153) }, { "lightsteelblue", NSVG_RGB(176, 196, 222) }, { "lightyellow", NSVG_RGB(255, 255, 224) }, { "lime", NSVG_RGB( 0, 255, 0) }, { "limegreen", NSVG_RGB( 50, 205, 50) }, { "linen", NSVG_RGB(250, 240, 230) }, { "maroon", NSVG_RGB(128, 0, 0) }, { "mediumaquamarine", NSVG_RGB(102, 205, 170) }, { "mediumblue", NSVG_RGB( 0, 0, 205) }, { "mediumorchid", NSVG_RGB(186, 85, 211) }, { "mediumpurple", NSVG_RGB(147, 112, 219) }, { "mediumseagreen", NSVG_RGB( 60, 179, 113) }, { "mediumslateblue", NSVG_RGB(123, 104, 238) }, { "mediumspringgreen", NSVG_RGB( 0, 250, 154) }, { "mediumturquoise", NSVG_RGB( 72, 209, 204) }, { "mediumvioletred", NSVG_RGB(199, 21, 133) }, { "midnightblue", NSVG_RGB( 25, 25, 112) }, { "mintcream", NSVG_RGB(245, 255, 250) }, { "mistyrose", NSVG_RGB(255, 228, 225) }, { "moccasin", NSVG_RGB(255, 228, 181) }, { "navajowhite", NSVG_RGB(255, 222, 173) }, { "navy", NSVG_RGB( 0, 0, 128) }, { "oldlace", NSVG_RGB(253, 245, 230) }, { "olive", NSVG_RGB(128, 128, 0) }, { "olivedrab", NSVG_RGB(107, 142, 35) }, { "orange", NSVG_RGB(255, 165, 0) }, { "orangered", NSVG_RGB(255, 69, 0) }, { "orchid", NSVG_RGB(218, 112, 214) }, { "palegoldenrod", NSVG_RGB(238, 232, 170) }, { "palegreen", NSVG_RGB(152, 251, 152) }, { "paleturquoise", NSVG_RGB(175, 238, 238) }, { "palevioletred", NSVG_RGB(219, 112, 147) }, { "papayawhip", NSVG_RGB(255, 239, 213) }, { "peachpuff", NSVG_RGB(255, 218, 185) }, { "peru", NSVG_RGB(205, 133, 63) }, { "pink", NSVG_RGB(255, 192, 203) }, { "plum", NSVG_RGB(221, 160, 221) }, { "powderblue", NSVG_RGB(176, 224, 230) }, { "purple", NSVG_RGB(128, 0, 128) }, { "rosybrown", NSVG_RGB(188, 143, 143) }, { "royalblue", NSVG_RGB( 65, 105, 225) }, { "saddlebrown", NSVG_RGB(139, 69, 19) }, { "salmon", NSVG_RGB(250, 128, 114) }, { "sandybrown", NSVG_RGB(244, 164, 96) }, { "seagreen", NSVG_RGB( 46, 139, 87) }, { "seashell", NSVG_RGB(255, 245, 238) }, { "sienna", NSVG_RGB(160, 82, 45) }, { "silver", NSVG_RGB(192, 192, 192) }, { "skyblue", NSVG_RGB(135, 206, 235) }, { "slateblue", NSVG_RGB(106, 90, 205) }, { "slategray", NSVG_RGB(112, 128, 144) }, { "slategrey", NSVG_RGB(112, 128, 144) }, { "snow", NSVG_RGB(255, 250, 250) }, { "springgreen", NSVG_RGB( 0, 255, 127) }, { "steelblue", NSVG_RGB( 70, 130, 180) }, { "tan", NSVG_RGB(210, 180, 140) }, { "teal", NSVG_RGB( 0, 128, 128) }, { "thistle", NSVG_RGB(216, 191, 216) }, { "tomato", NSVG_RGB(255, 99, 71) }, { "turquoise", NSVG_RGB( 64, 224, 208) }, { "violet", NSVG_RGB(238, 130, 238) }, { "wheat", NSVG_RGB(245, 222, 179) }, { "whitesmoke", NSVG_RGB(245, 245, 245) }, { "yellowgreen", NSVG_RGB(154, 205, 50) }, #endif }; static unsigned int nsvg__parseColorName(const char* str) { int i, ncolors = sizeof(nsvg__colors) / sizeof(NSVGNamedColor); for (i = 0; i < ncolors; i++) { if (strcmp(nsvg__colors[i].name, str) == 0) { return nsvg__colors[i].color; } } return NSVG_RGB(128, 128, 128); } static unsigned int nsvg__parseColor(const char* str) { size_t len = 0; while(*str == ' ') ++str; len = strlen(str); if (len >= 1 && *str == '#') return nsvg__parseColorHex(str); else if (len >= 4 && str[0] == 'r' && str[1] == 'g' && str[2] == 'b' && str[3] == '(') return nsvg__parseColorRGB(str); return nsvg__parseColorName(str); } static float nsvg__parseOpacity(const char* str) { float val = 0; sscanf(str, "%f", &val); if (val < 0.0f) val = 0.0f; if (val > 1.0f) val = 1.0f; return val; } static float nsvg__parseMiterLimit(const char* str) { float val = 0; sscanf(str, "%f", &val); if (val < 0.0f) val = 0.0f; return val; } static int nsvg__parseUnits(const char* units) { if (units[0] == 'p' && units[1] == 'x') return NSVG_UNITS_PX; else if (units[0] == 'p' && units[1] == 't') return NSVG_UNITS_PT; else if (units[0] == 'p' && units[1] == 'c') return NSVG_UNITS_PC; else if (units[0] == 'm' && units[1] == 'm') return NSVG_UNITS_MM; else if (units[0] == 'c' && units[1] == 'm') return NSVG_UNITS_CM; else if (units[0] == 'i' && units[1] == 'n') return NSVG_UNITS_IN; else if (units[0] == '%') return NSVG_UNITS_PERCENT; else if (units[0] == 'e' && units[1] == 'm') return NSVG_UNITS_EM; else if (units[0] == 'e' && units[1] == 'x') return NSVG_UNITS_EX; return NSVG_UNITS_USER; } static NSVGcoordinate nsvg__parseCoordinateRaw(const char* str) { NSVGcoordinate coord = {0, NSVG_UNITS_USER}; char units[32]=""; sscanf(str, "%f%31s", &coord.value, units); coord.units = nsvg__parseUnits(units); return coord; } static NSVGcoordinate nsvg__coord(float v, int units) { NSVGcoordinate coord ; coord.value = v; coord.units = units; return coord; } static float nsvg__parseCoordinate(NSVGparser* p, const char* str, float orig, float length) { NSVGcoordinate coord = nsvg__parseCoordinateRaw(str); return nsvg__convertToPixels(p, coord, orig, length); } static int nsvg__parseTransformArgs(const char* str, float* args, int maxNa, int* na) { const char* end; const char* ptr; char it[64]; *na = 0; ptr = str; while (*ptr && *ptr != '(') ++ptr; if (*ptr == 0) return 1; end = ptr; while (*end && *end != ')') ++end; if (*end == 0) return 1; while (ptr < end) { if (*ptr == '-' || *ptr == '+' || *ptr == '.' || nsvg__isdigit(*ptr)) { if (*na >= maxNa) return 0; ptr = nsvg__parseNumber(ptr, it, 64); args[(*na)++] = (float)nsvg__atof(it); } else { ++ptr; } } return (int)(end - str); } static int nsvg__parseMatrix(float* xform, const char* str) { float t[6]; int na = 0; int len = nsvg__parseTransformArgs(str, t, 6, &na); if (na != 6) return len; memcpy(xform, t, sizeof(float)*6); return len; } static int nsvg__parseTranslate(float* xform, const char* str) { float args[2]; float t[6]; int na = 0; int len = nsvg__parseTransformArgs(str, args, 2, &na); if (na == 1) args[1] = 0.0; nsvg__xformSetTranslation(t, args[0], args[1]); memcpy(xform, t, sizeof(float)*6); return len; } static int nsvg__parseScale(float* xform, const char* str) { float args[2]; int na = 0; float t[6]; int len = nsvg__parseTransformArgs(str, args, 2, &na); if (na == 1) args[1] = args[0]; nsvg__xformSetScale(t, args[0], args[1]); memcpy(xform, t, sizeof(float)*6); return len; } static int nsvg__parseSkewX(float* xform, const char* str) { float args[1]; int na = 0; float t[6]; int len = nsvg__parseTransformArgs(str, args, 1, &na); nsvg__xformSetSkewX(t, args[0]/180.0f*NSVG_PI); memcpy(xform, t, sizeof(float)*6); return len; } static int nsvg__parseSkewY(float* xform, const char* str) { float args[1]; int na = 0; float t[6]; int len = nsvg__parseTransformArgs(str, args, 1, &na); nsvg__xformSetSkewY(t, args[0]/180.0f*NSVG_PI); memcpy(xform, t, sizeof(float)*6); return len; } static int nsvg__parseRotate(float* xform, const char* str) { float args[3]; int na = 0; float m[6]; float t[6]; int len = nsvg__parseTransformArgs(str, args, 3, &na); if (na == 1) args[1] = args[2] = 0.0f; nsvg__xformIdentity(m); if (na > 1) { nsvg__xformSetTranslation(t, -args[1], -args[2]); nsvg__xformMultiply(m, t); } nsvg__xformSetRotation(t, args[0]/180.0f*NSVG_PI); nsvg__xformMultiply(m, t); if (na > 1) { nsvg__xformSetTranslation(t, args[1], args[2]); nsvg__xformMultiply(m, t); } memcpy(xform, m, sizeof(float)*6); return len; } static void nsvg__parseTransform(float* xform, const char* str) { float t[6]; nsvg__xformIdentity(xform); while (*str) { if (strncmp(str, "matrix", 6) == 0) str += nsvg__parseMatrix(t, str); else if (strncmp(str, "translate", 9) == 0) str += nsvg__parseTranslate(t, str); else if (strncmp(str, "scale", 5) == 0) str += nsvg__parseScale(t, str); else if (strncmp(str, "rotate", 6) == 0) str += nsvg__parseRotate(t, str); else if (strncmp(str, "skewX", 5) == 0) str += nsvg__parseSkewX(t, str); else if (strncmp(str, "skewY", 5) == 0) str += nsvg__parseSkewY(t, str); else{ ++str; continue; } nsvg__xformPremultiply(xform, t); } } static void nsvg__parseUrl(char* id, const char* str) { int i = 0; str += 4; // "url("; if (*str == '#') str++; while (i < 63 && *str != ')') { id[i] = *str++; i++; } id[i] = '\0'; } static char nsvg__parseLineCap(const char* str) { if (strcmp(str, "butt") == 0) return NSVG_CAP_BUTT; else if (strcmp(str, "round") == 0) return NSVG_CAP_ROUND; else if (strcmp(str, "square") == 0) return NSVG_CAP_SQUARE; // TODO: handle inherit. return NSVG_CAP_BUTT; } static char nsvg__parseLineJoin(const char* str) { if (strcmp(str, "miter") == 0) return NSVG_JOIN_MITER; else if (strcmp(str, "round") == 0) return NSVG_JOIN_ROUND; else if (strcmp(str, "bevel") == 0) return NSVG_JOIN_BEVEL; // TODO: handle inherit. return NSVG_CAP_BUTT; } static char nsvg__parseFillRule(const char* str) { if (strcmp(str, "nonzero") == 0) return NSVG_FILLRULE_NONZERO; else if (strcmp(str, "evenodd") == 0) return NSVG_FILLRULE_EVENODD; // TODO: handle inherit. return NSVG_FILLRULE_NONZERO; } static const char* nsvg__getNextDashItem(const char* s, char* it) { int n = 0; it[0] = '\0'; // Skip white spaces and commas while (*s && (nsvg__isspace(*s) || *s == ',')) s++; // Advance until whitespace, comma or end. while (*s && (!nsvg__isspace(*s) && *s != ',')) { if (n < 63) it[n++] = *s; s++; } it[n++] = '\0'; return s; } static int nsvg__parseStrokeDashArray(NSVGparser* p, const char* str, float* strokeDashArray) { char item[64]; int count = 0, i; float sum = 0.0f; // Handle "none" if (str[0] == 'n') return 0; // Parse dashes while (*str) { str = nsvg__getNextDashItem(str, item); if (!*item) break; if (count < NSVG_MAX_DASHES) strokeDashArray[count++] = fabsf(nsvg__parseCoordinate(p, item, 0.0f, nsvg__actualLength(p))); } for (i = 0; i < count; i++) sum += strokeDashArray[i]; if (sum <= 1e-6f) count = 0; return count; } static void nsvg__parseStyle(NSVGparser* p, const char* str); static int nsvg__parseAttr(NSVGparser* p, const char* name, const char* value) { float xform[6]; NSVGattrib* attr = nsvg__getAttr(p); if (!attr) return 0; if (strcmp(name, "style") == 0) { nsvg__parseStyle(p, value); } else if (strcmp(name, "display") == 0) { if (strcmp(value, "none") == 0) attr->visible = 0; // Don't reset ->visible on display:inline, one display:none hides the whole subtree } else if (strcmp(name, "fill") == 0) { if (strcmp(value, "none") == 0) { attr->hasFill = 0; } else if (strncmp(value, "url(", 4) == 0) { attr->hasFill = 2; nsvg__parseUrl(attr->fillGradient, value); } else { attr->hasFill = 1; attr->fillColor = nsvg__parseColor(value); } } else if (strcmp(name, "opacity") == 0) { attr->opacity = nsvg__parseOpacity(value); } else if (strcmp(name, "fill-opacity") == 0) { attr->fillOpacity = nsvg__parseOpacity(value); } else if (strcmp(name, "stroke") == 0) { if (strcmp(value, "none") == 0) { attr->hasStroke = 0; } else if (strncmp(value, "url(", 4) == 0) { attr->hasStroke = 2; nsvg__parseUrl(attr->strokeGradient, value); } else { attr->hasStroke = 1; attr->strokeColor = nsvg__parseColor(value); } } else if (strcmp(name, "stroke-width") == 0) { attr->strokeWidth = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p)); } else if (strcmp(name, "stroke-dasharray") == 0) { attr->strokeDashCount = nsvg__parseStrokeDashArray(p, value, attr->strokeDashArray); } else if (strcmp(name, "stroke-dashoffset") == 0) { attr->strokeDashOffset = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p)); } else if (strcmp(name, "stroke-opacity") == 0) { attr->strokeOpacity = nsvg__parseOpacity(value); } else if (strcmp(name, "stroke-linecap") == 0) { attr->strokeLineCap = nsvg__parseLineCap(value); } else if (strcmp(name, "stroke-linejoin") == 0) { attr->strokeLineJoin = nsvg__parseLineJoin(value); } else if (strcmp(name, "stroke-miterlimit") == 0) { attr->miterLimit = nsvg__parseMiterLimit(value); } else if (strcmp(name, "fill-rule") == 0) { attr->fillRule = nsvg__parseFillRule(value); } else if (strcmp(name, "font-size") == 0) { attr->fontSize = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p)); } else if (strcmp(name, "transform") == 0) { nsvg__parseTransform(xform, value); nsvg__xformPremultiply(attr->xform, xform); } else if (strcmp(name, "stop-color") == 0) { attr->stopColor = nsvg__parseColor(value); } else if (strcmp(name, "stop-opacity") == 0) { attr->stopOpacity = nsvg__parseOpacity(value); } else if (strcmp(name, "offset") == 0) { attr->stopOffset = nsvg__parseCoordinate(p, value, 0.0f, 1.0f); } else if (strcmp(name, "id") == 0) { strncpy(attr->id, value, 63); attr->id[63] = '\0'; } else if (strcmp(name, "class") == 0) { NSVGstyles* style = p->styles; while (style) { if (strcmp(style->name + 1, value) == 0) { break; } style = style->next; } if (style) { nsvg__parseStyle(p, style->description); } } else { return 0; } return 1; } static int nsvg__parseNameValue(NSVGparser* p, const char* start, const char* end) { const char* str; const char* val; char name[512]; char value[512]; int n; str = start; while (str < end && *str != ':') ++str; val = str; // Right Trim while (str > start && (*str == ':' || nsvg__isspace(*str))) --str; ++str; n = (int)(str - start); if (n > 511) n = 511; if (n) memcpy(name, start, n); name[n] = 0; while (val < end && (*val == ':' || nsvg__isspace(*val))) ++val; n = (int)(end - val); if (n > 511) n = 511; if (n) memcpy(value, val, n); value[n] = 0; return nsvg__parseAttr(p, name, value); } static void nsvg__parseStyle(NSVGparser* p, const char* str) { const char* start; const char* end; while (*str) { // Left Trim while(*str && nsvg__isspace(*str)) ++str; start = str; while(*str && *str != ';') ++str; end = str; // Right Trim while (end > start && (*end == ';' || nsvg__isspace(*end))) --end; ++end; nsvg__parseNameValue(p, start, end); if (*str) ++str; } } static void nsvg__parseAttribs(NSVGparser* p, const char** attr) { int i; for (i = 0; attr[i]; i += 2) { if (strcmp(attr[i], "style") == 0) nsvg__parseStyle(p, attr[i + 1]); else nsvg__parseAttr(p, attr[i], attr[i + 1]); } } static int nsvg__getArgsPerElement(char cmd) { switch (cmd) { case 'v': case 'V': case 'h': case 'H': return 1; case 'm': case 'M': case 'l': case 'L': case 't': case 'T': return 2; case 'q': case 'Q': case 's': case 'S': return 4; case 'c': case 'C': return 6; case 'a': case 'A': return 7; } return 0; } static void nsvg__pathMoveTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) { if (rel) { *cpx += args[0]; *cpy += args[1]; } else { *cpx = args[0]; *cpy = args[1]; } nsvg__moveTo(p, *cpx, *cpy); } static void nsvg__pathLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) { if (rel) { *cpx += args[0]; *cpy += args[1]; } else { *cpx = args[0]; *cpy = args[1]; } nsvg__lineTo(p, *cpx, *cpy); } static void nsvg__pathHLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) { if (rel) *cpx += args[0]; else *cpx = args[0]; nsvg__lineTo(p, *cpx, *cpy); } static void nsvg__pathVLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) { if (rel) *cpy += args[0]; else *cpy = args[0]; nsvg__lineTo(p, *cpx, *cpy); } static void nsvg__pathCubicBezTo(NSVGparser* p, float* cpx, float* cpy, float* cpx2, float* cpy2, float* args, int rel) { float x2, y2, cx1, cy1, cx2, cy2; if (rel) { cx1 = *cpx + args[0]; cy1 = *cpy + args[1]; cx2 = *cpx + args[2]; cy2 = *cpy + args[3]; x2 = *cpx + args[4]; y2 = *cpy + args[5]; } else { cx1 = args[0]; cy1 = args[1]; cx2 = args[2]; cy2 = args[3]; x2 = args[4]; y2 = args[5]; } nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); *cpx2 = cx2; *cpy2 = cy2; *cpx = x2; *cpy = y2; } static void nsvg__pathCubicBezShortTo(NSVGparser* p, float* cpx, float* cpy, float* cpx2, float* cpy2, float* args, int rel) { float x1, y1, x2, y2, cx1, cy1, cx2, cy2; x1 = *cpx; y1 = *cpy; if (rel) { cx2 = *cpx + args[0]; cy2 = *cpy + args[1]; x2 = *cpx + args[2]; y2 = *cpy + args[3]; } else { cx2 = args[0]; cy2 = args[1]; x2 = args[2]; y2 = args[3]; } cx1 = 2*x1 - *cpx2; cy1 = 2*y1 - *cpy2; nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); *cpx2 = cx2; *cpy2 = cy2; *cpx = x2; *cpy = y2; } static void nsvg__pathQuadBezTo(NSVGparser* p, float* cpx, float* cpy, float* cpx2, float* cpy2, float* args, int rel) { float x1, y1, x2, y2, cx, cy; float cx1, cy1, cx2, cy2; x1 = *cpx; y1 = *cpy; if (rel) { cx = *cpx + args[0]; cy = *cpy + args[1]; x2 = *cpx + args[2]; y2 = *cpy + args[3]; } else { cx = args[0]; cy = args[1]; x2 = args[2]; y2 = args[3]; } // Convert to cubic bezier cx1 = x1 + 2.0f/3.0f*(cx - x1); cy1 = y1 + 2.0f/3.0f*(cy - y1); cx2 = x2 + 2.0f/3.0f*(cx - x2); cy2 = y2 + 2.0f/3.0f*(cy - y2); nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); *cpx2 = cx; *cpy2 = cy; *cpx = x2; *cpy = y2; } static void nsvg__pathQuadBezShortTo(NSVGparser* p, float* cpx, float* cpy, float* cpx2, float* cpy2, float* args, int rel) { float x1, y1, x2, y2, cx, cy; float cx1, cy1, cx2, cy2; x1 = *cpx; y1 = *cpy; if (rel) { x2 = *cpx + args[0]; y2 = *cpy + args[1]; } else { x2 = args[0]; y2 = args[1]; } cx = 2*x1 - *cpx2; cy = 2*y1 - *cpy2; // Convert to cubix bezier cx1 = x1 + 2.0f/3.0f*(cx - x1); cy1 = y1 + 2.0f/3.0f*(cy - y1); cx2 = x2 + 2.0f/3.0f*(cx - x2); cy2 = y2 + 2.0f/3.0f*(cy - y2); nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); *cpx2 = cx; *cpy2 = cy; *cpx = x2; *cpy = y2; } static float nsvg__sqr(float x) { return x*x; } static float nsvg__vmag(float x, float y) { return sqrtf(x*x + y*y); } static float nsvg__vecrat(float ux, float uy, float vx, float vy) { return (ux*vx + uy*vy) / (nsvg__vmag(ux,uy) * nsvg__vmag(vx,vy)); } static float nsvg__vecang(float ux, float uy, float vx, float vy) { float r = nsvg__vecrat(ux,uy, vx,vy); if (r < -1.0f) r = -1.0f; if (r > 1.0f) r = 1.0f; return ((ux*vy < uy*vx) ? -1.0f : 1.0f) * acosf(r); } static void nsvg__pathArcTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) { // Ported from canvg (https://code.google.com/p/canvg/) float rx, ry, rotx; float x1, y1, x2, y2, cx, cy, dx, dy, d; float x1p, y1p, cxp, cyp, s, sa, sb; float ux, uy, vx, vy, a1, da; float x, y, tanx, tany, a, px = 0, py = 0, ptanx = 0, ptany = 0, t[6]; float sinrx, cosrx; int fa, fs; int i, ndivs; float hda, kappa; rx = fabsf(args[0]); // y radius ry = fabsf(args[1]); // x radius rotx = args[2] / 180.0f * NSVG_PI; // x rotation angle fa = fabsf(args[3]) > 1e-6 ? 1 : 0; // Large arc fs = fabsf(args[4]) > 1e-6 ? 1 : 0; // Sweep direction x1 = *cpx; // start point y1 = *cpy; if (rel) { // end point x2 = *cpx + args[5]; y2 = *cpy + args[6]; } else { x2 = args[5]; y2 = args[6]; } dx = x1 - x2; dy = y1 - y2; d = sqrtf(dx*dx + dy*dy); if (d < 1e-6f || rx < 1e-6f || ry < 1e-6f) { // The arc degenerates to a line nsvg__lineTo(p, x2, y2); *cpx = x2; *cpy = y2; return; } sinrx = sinf(rotx); cosrx = cosf(rotx); // Convert to center point parameterization. // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes // 1) Compute x1', y1' x1p = cosrx * dx / 2.0f + sinrx * dy / 2.0f; y1p = -sinrx * dx / 2.0f + cosrx * dy / 2.0f; d = nsvg__sqr(x1p)/nsvg__sqr(rx) + nsvg__sqr(y1p)/nsvg__sqr(ry); if (d > 1) { d = sqrtf(d); rx *= d; ry *= d; } // 2) Compute cx', cy' s = 0.0f; sa = nsvg__sqr(rx)*nsvg__sqr(ry) - nsvg__sqr(rx)*nsvg__sqr(y1p) - nsvg__sqr(ry)*nsvg__sqr(x1p); sb = nsvg__sqr(rx)*nsvg__sqr(y1p) + nsvg__sqr(ry)*nsvg__sqr(x1p); if (sa < 0.0f) sa = 0.0f; if (sb > 0.0f) s = sqrtf(sa / sb); if (fa == fs) s = -s; cxp = s * rx * y1p / ry; cyp = s * -ry * x1p / rx; // 3) Compute cx,cy from cx',cy' cx = (x1 + x2)/2.0f + cosrx*cxp - sinrx*cyp; cy = (y1 + y2)/2.0f + sinrx*cxp + cosrx*cyp; // 4) Calculate theta1, and delta theta. ux = (x1p - cxp) / rx; uy = (y1p - cyp) / ry; vx = (-x1p - cxp) / rx; vy = (-y1p - cyp) / ry; a1 = nsvg__vecang(1.0f,0.0f, ux,uy); // Initial angle da = nsvg__vecang(ux,uy, vx,vy); // Delta angle // if (vecrat(ux,uy,vx,vy) <= -1.0f) da = NSVG_PI; // if (vecrat(ux,uy,vx,vy) >= 1.0f) da = 0; if (fs == 0 && da > 0) da -= 2 * NSVG_PI; else if (fs == 1 && da < 0) da += 2 * NSVG_PI; // Approximate the arc using cubic spline segments. t[0] = cosrx; t[1] = sinrx; t[2] = -sinrx; t[3] = cosrx; t[4] = cx; t[5] = cy; // Split arc into max 90 degree segments. // The loop assumes an iteration per end point (including start and end), this +1. ndivs = (int)(fabsf(da) / (NSVG_PI*0.5f) + 1.0f); hda = (da / (float)ndivs) / 2.0f; kappa = fabsf(4.0f / 3.0f * (1.0f - cosf(hda)) / sinf(hda)); if (da < 0.0f) kappa = -kappa; for (i = 0; i <= ndivs; i++) { a = a1 + da * ((float)i/(float)ndivs); dx = cosf(a); dy = sinf(a); nsvg__xformPoint(&x, &y, dx*rx, dy*ry, t); // position nsvg__xformVec(&tanx, &tany, -dy*rx * kappa, dx*ry * kappa, t); // tangent if (i > 0) nsvg__cubicBezTo(p, px+ptanx,py+ptany, x-tanx, y-tany, x, y); px = x; py = y; ptanx = tanx; ptany = tany; } *cpx = x2; *cpy = y2; } static void nsvg__parsePath(NSVGparser* p, const char** attr) { const char* s = NULL; char cmd = '\0'; float args[10]; int nargs; int rargs = 0; float cpx, cpy, cpx2, cpy2; const char* tmp[4]; char closedFlag; int i; char item[64]; for (i = 0; attr[i]; i += 2) { if (strcmp(attr[i], "d") == 0) { s = attr[i + 1]; } else { tmp[0] = attr[i]; tmp[1] = attr[i + 1]; tmp[2] = 0; tmp[3] = 0; nsvg__parseAttribs(p, tmp); } } if (s) { nsvg__resetPath(p); cpx = 0; cpy = 0; cpx2 = 0; cpy2 = 0; closedFlag = 0; nargs = 0; while (*s) { s = nsvg__getNextPathItem(s, item); if (!*item) break; if (nsvg__isnum(item[0])) { if (nargs < 10) args[nargs++] = (float)nsvg__atof(item); if (nargs >= rargs) { switch (cmd) { case 'm': case 'M': nsvg__pathMoveTo(p, &cpx, &cpy, args, cmd == 'm' ? 1 : 0); // Moveto can be followed by multiple coordinate pairs, // which should be treated as linetos. cmd = (cmd == 'm') ? 'l' : 'L'; rargs = nsvg__getArgsPerElement(cmd); cpx2 = cpx; cpy2 = cpy; break; case 'l': case 'L': nsvg__pathLineTo(p, &cpx, &cpy, args, cmd == 'l' ? 1 : 0); cpx2 = cpx; cpy2 = cpy; break; case 'H': case 'h': nsvg__pathHLineTo(p, &cpx, &cpy, args, cmd == 'h' ? 1 : 0); cpx2 = cpx; cpy2 = cpy; break; case 'V': case 'v': nsvg__pathVLineTo(p, &cpx, &cpy, args, cmd == 'v' ? 1 : 0); cpx2 = cpx; cpy2 = cpy; break; case 'C': case 'c': nsvg__pathCubicBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'c' ? 1 : 0); break; case 'S': case 's': nsvg__pathCubicBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 's' ? 1 : 0); break; case 'Q': case 'q': nsvg__pathQuadBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'q' ? 1 : 0); break; case 'T': case 't': nsvg__pathQuadBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 't' ? 1 : 0); break; case 'A': case 'a': nsvg__pathArcTo(p, &cpx, &cpy, args, cmd == 'a' ? 1 : 0); cpx2 = cpx; cpy2 = cpy; break; default: if (nargs >= 2) { cpx = args[nargs-2]; cpy = args[nargs-1]; cpx2 = cpx; cpy2 = cpy; } break; } nargs = 0; } } else { cmd = item[0]; rargs = nsvg__getArgsPerElement(cmd); if (cmd == 'M' || cmd == 'm') { // Commit path. if (p->npts > 0) nsvg__addPath(p, closedFlag); // Start new subpath. nsvg__resetPath(p); closedFlag = 0; nargs = 0; } else if (cmd == 'Z' || cmd == 'z') { closedFlag = 1; // Commit path. if (p->npts > 0) { // Move current point to first point cpx = p->pts[0]; cpy = p->pts[1]; cpx2 = cpx; cpy2 = cpy; nsvg__addPath(p, closedFlag); } // Start new subpath. nsvg__resetPath(p); nsvg__moveTo(p, cpx, cpy); closedFlag = 0; nargs = 0; } } } // Commit path. if (p->npts) nsvg__addPath(p, closedFlag); } nsvg__addShape(p); } static void nsvg__parseRect(NSVGparser* p, const char** attr) { float x = 0.0f; float y = 0.0f; float w = 0.0f; float h = 0.0f; float rx = -1.0f; // marks not set float ry = -1.0f; int i; for (i = 0; attr[i]; i += 2) { if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { if (strcmp(attr[i], "x") == 0) x = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); if (strcmp(attr[i], "y") == 0) y = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); if (strcmp(attr[i], "width") == 0) w = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p)); if (strcmp(attr[i], "height") == 0) h = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p)); if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p))); if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p))); } } if (rx < 0.0f && ry > 0.0f) rx = ry; if (ry < 0.0f && rx > 0.0f) ry = rx; if (rx < 0.0f) rx = 0.0f; if (ry < 0.0f) ry = 0.0f; if (rx > w/2.0f) rx = w/2.0f; if (ry > h/2.0f) ry = h/2.0f; if (w != 0.0f && h != 0.0f) { nsvg__resetPath(p); if (rx < 0.00001f || ry < 0.0001f) { nsvg__moveTo(p, x, y); nsvg__lineTo(p, x+w, y); nsvg__lineTo(p, x+w, y+h); nsvg__lineTo(p, x, y+h); } else { // Rounded rectangle nsvg__moveTo(p, x+rx, y); nsvg__lineTo(p, x+w-rx, y); nsvg__cubicBezTo(p, x+w-rx*(1-NSVG_KAPPA90), y, x+w, y+ry*(1-NSVG_KAPPA90), x+w, y+ry); nsvg__lineTo(p, x+w, y+h-ry); nsvg__cubicBezTo(p, x+w, y+h-ry*(1-NSVG_KAPPA90), x+w-rx*(1-NSVG_KAPPA90), y+h, x+w-rx, y+h); nsvg__lineTo(p, x+rx, y+h); nsvg__cubicBezTo(p, x+rx*(1-NSVG_KAPPA90), y+h, x, y+h-ry*(1-NSVG_KAPPA90), x, y+h-ry); nsvg__lineTo(p, x, y+ry); nsvg__cubicBezTo(p, x, y+ry*(1-NSVG_KAPPA90), x+rx*(1-NSVG_KAPPA90), y, x+rx, y); } nsvg__addPath(p, 1); nsvg__addShape(p); } } static void nsvg__parseCircle(NSVGparser* p, const char** attr) { float cx = 0.0f; float cy = 0.0f; float r = 0.0f; int i; for (i = 0; attr[i]; i += 2) { if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); if (strcmp(attr[i], "r") == 0) r = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualLength(p))); } } if (r > 0.0f) { nsvg__resetPath(p); nsvg__moveTo(p, cx+r, cy); nsvg__cubicBezTo(p, cx+r, cy+r*NSVG_KAPPA90, cx+r*NSVG_KAPPA90, cy+r, cx, cy+r); nsvg__cubicBezTo(p, cx-r*NSVG_KAPPA90, cy+r, cx-r, cy+r*NSVG_KAPPA90, cx-r, cy); nsvg__cubicBezTo(p, cx-r, cy-r*NSVG_KAPPA90, cx-r*NSVG_KAPPA90, cy-r, cx, cy-r); nsvg__cubicBezTo(p, cx+r*NSVG_KAPPA90, cy-r, cx+r, cy-r*NSVG_KAPPA90, cx+r, cy); nsvg__addPath(p, 1); nsvg__addShape(p); } } static void nsvg__parseEllipse(NSVGparser* p, const char** attr) { float cx = 0.0f; float cy = 0.0f; float rx = 0.0f; float ry = 0.0f; int i; for (i = 0; attr[i]; i += 2) { if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p))); if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p))); } } if (rx > 0.0f && ry > 0.0f) { nsvg__resetPath(p); nsvg__moveTo(p, cx+rx, cy); nsvg__cubicBezTo(p, cx+rx, cy+ry*NSVG_KAPPA90, cx+rx*NSVG_KAPPA90, cy+ry, cx, cy+ry); nsvg__cubicBezTo(p, cx-rx*NSVG_KAPPA90, cy+ry, cx-rx, cy+ry*NSVG_KAPPA90, cx-rx, cy); nsvg__cubicBezTo(p, cx-rx, cy-ry*NSVG_KAPPA90, cx-rx*NSVG_KAPPA90, cy-ry, cx, cy-ry); nsvg__cubicBezTo(p, cx+rx*NSVG_KAPPA90, cy-ry, cx+rx, cy-ry*NSVG_KAPPA90, cx+rx, cy); nsvg__addPath(p, 1); nsvg__addShape(p); } } static void nsvg__parseLine(NSVGparser* p, const char** attr) { float x1 = 0.0; float y1 = 0.0; float x2 = 0.0; float y2 = 0.0; int i; for (i = 0; attr[i]; i += 2) { if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { if (strcmp(attr[i], "x1") == 0) x1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); if (strcmp(attr[i], "y1") == 0) y1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); if (strcmp(attr[i], "x2") == 0) x2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); if (strcmp(attr[i], "y2") == 0) y2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); } } nsvg__resetPath(p); nsvg__moveTo(p, x1, y1); nsvg__lineTo(p, x2, y2); nsvg__addPath(p, 0); nsvg__addShape(p); } static void nsvg__parsePoly(NSVGparser* p, const char** attr, int closeFlag) { int i; const char* s; float args[2]; int nargs, npts = 0; char item[64]; nsvg__resetPath(p); for (i = 0; attr[i]; i += 2) { if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { if (strcmp(attr[i], "points") == 0) { s = attr[i + 1]; nargs = 0; while (*s) { s = nsvg__getNextPathItem(s, item); args[nargs++] = (float)nsvg__atof(item); if (nargs >= 2) { if (npts == 0) nsvg__moveTo(p, args[0], args[1]); else nsvg__lineTo(p, args[0], args[1]); nargs = 0; npts++; } } } } } nsvg__addPath(p, (char)closeFlag); nsvg__addShape(p); } static void nsvg__parseSVG(NSVGparser* p, const char** attr) { int i; for (i = 0; attr[i]; i += 2) { if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { if (strcmp(attr[i], "width") == 0) { p->image->width = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 1.0f); } else if (strcmp(attr[i], "height") == 0) { p->image->height = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 1.0f); } else if (strcmp(attr[i], "viewBox") == 0) { sscanf(attr[i + 1], "%f%*[%%, \t]%f%*[%%, \t]%f%*[%%, \t]%f", &p->viewMinx, &p->viewMiny, &p->viewWidth, &p->viewHeight); } else if (strcmp(attr[i], "preserveAspectRatio") == 0) { if (strstr(attr[i + 1], "none") != 0) { // No uniform scaling p->alignType = NSVG_ALIGN_NONE; } else { // Parse X align if (strstr(attr[i + 1], "xMin") != 0) p->alignX = NSVG_ALIGN_MIN; else if (strstr(attr[i + 1], "xMid") != 0) p->alignX = NSVG_ALIGN_MID; else if (strstr(attr[i + 1], "xMax") != 0) p->alignX = NSVG_ALIGN_MAX; // Parse X align if (strstr(attr[i + 1], "yMin") != 0) p->alignY = NSVG_ALIGN_MIN; else if (strstr(attr[i + 1], "yMid") != 0) p->alignY = NSVG_ALIGN_MID; else if (strstr(attr[i + 1], "yMax") != 0) p->alignY = NSVG_ALIGN_MAX; // Parse meet/slice p->alignType = NSVG_ALIGN_MEET; if (strstr(attr[i + 1], "slice") != 0) p->alignType = NSVG_ALIGN_SLICE; } } } } } static void nsvg__parseGradient(NSVGparser* p, const char** attr, char type) { int i; NSVGgradientData* grad = (NSVGgradientData*)malloc(sizeof(NSVGgradientData)); if (grad == NULL) return; memset(grad, 0, sizeof(NSVGgradientData)); grad->units = NSVG_OBJECT_SPACE; grad->type = type; if (grad->type == NSVG_PAINT_LINEAR_GRADIENT) { grad->linear.x1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT); grad->linear.y1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT); grad->linear.x2 = nsvg__coord(100.0f, NSVG_UNITS_PERCENT); grad->linear.y2 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT); } else if (grad->type == NSVG_PAINT_RADIAL_GRADIENT) { grad->radial.cx = nsvg__coord(50.0f, NSVG_UNITS_PERCENT); grad->radial.cy = nsvg__coord(50.0f, NSVG_UNITS_PERCENT); grad->radial.r = nsvg__coord(50.0f, NSVG_UNITS_PERCENT); } nsvg__xformIdentity(grad->xform); for (i = 0; attr[i]; i += 2) { if (strcmp(attr[i], "id") == 0) { strncpy(grad->id, attr[i+1], 63); grad->id[63] = '\0'; } else if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { if (strcmp(attr[i], "gradientUnits") == 0) { if (strcmp(attr[i+1], "objectBoundingBox") == 0) grad->units = NSVG_OBJECT_SPACE; else grad->units = NSVG_USER_SPACE; } else if (strcmp(attr[i], "gradientTransform") == 0) { nsvg__parseTransform(grad->xform, attr[i + 1]); } else if (strcmp(attr[i], "cx") == 0) { grad->radial.cx = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "cy") == 0) { grad->radial.cy = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "r") == 0) { grad->radial.r = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "fx") == 0) { grad->radial.fx = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "fy") == 0) { grad->radial.fy = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "x1") == 0) { grad->linear.x1 = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "y1") == 0) { grad->linear.y1 = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "x2") == 0) { grad->linear.x2 = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "y2") == 0) { grad->linear.y2 = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "spreadMethod") == 0) { if (strcmp(attr[i+1], "pad") == 0) grad->spread = NSVG_SPREAD_PAD; else if (strcmp(attr[i+1], "reflect") == 0) grad->spread = NSVG_SPREAD_REFLECT; else if (strcmp(attr[i+1], "repeat") == 0) grad->spread = NSVG_SPREAD_REPEAT; } else if (strcmp(attr[i], "xlink:href") == 0) { const char *href = attr[i+1]; strncpy(grad->ref, href+1, 62); grad->ref[62] = '\0'; } } } grad->next = p->gradients; p->gradients = grad; } static void nsvg__parseGradientStop(NSVGparser* p, const char** attr) { NSVGattrib* curAttr = nsvg__getAttr(p); NSVGgradientData* grad; NSVGgradientStop* stop; int i, idx; curAttr->stopOffset = 0; curAttr->stopColor = 0; curAttr->stopOpacity = 1.0f; for (i = 0; attr[i]; i += 2) { nsvg__parseAttr(p, attr[i], attr[i + 1]); } // Add stop to the last gradient. grad = p->gradients; if (grad == NULL) return; grad->nstops++; grad->stops = (NSVGgradientStop*)realloc(grad->stops, sizeof(NSVGgradientStop)*grad->nstops); if (grad->stops == NULL) return; // Insert idx = grad->nstops-1; for (i = 0; i < grad->nstops-1; i++) { if (curAttr->stopOffset < grad->stops[i].offset) { idx = i; break; } } if (idx != grad->nstops-1) { for (i = grad->nstops-1; i > idx; i--) grad->stops[i] = grad->stops[i-1]; } stop = &grad->stops[idx]; stop->color = curAttr->stopColor; stop->color |= (unsigned int)(curAttr->stopOpacity*255) << 24; stop->offset = curAttr->stopOffset; } static void nsvg__startElement(void* ud, const char* el, const char** attr) { NSVGparser* p = (NSVGparser*)ud; if (p->defsFlag) { // Skip everything but gradients in defs if (strcmp(el, "linearGradient") == 0) { nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT); } else if (strcmp(el, "radialGradient") == 0) { nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT); } else if (strcmp(el, "stop") == 0) { nsvg__parseGradientStop(p, attr); } return; } if (strcmp(el, "g") == 0) { nsvg__pushAttr(p); nsvg__parseAttribs(p, attr); } else if (strcmp(el, "path") == 0) { if (p->pathFlag) // Do not allow nested paths. return; nsvg__pushAttr(p); nsvg__parsePath(p, attr); nsvg__popAttr(p); } else if (strcmp(el, "rect") == 0) { nsvg__pushAttr(p); nsvg__parseRect(p, attr); nsvg__popAttr(p); } else if (strcmp(el, "circle") == 0) { nsvg__pushAttr(p); nsvg__parseCircle(p, attr); nsvg__popAttr(p); } else if (strcmp(el, "ellipse") == 0) { nsvg__pushAttr(p); nsvg__parseEllipse(p, attr); nsvg__popAttr(p); } else if (strcmp(el, "line") == 0) { nsvg__pushAttr(p); nsvg__parseLine(p, attr); nsvg__popAttr(p); } else if (strcmp(el, "polyline") == 0) { nsvg__pushAttr(p); nsvg__parsePoly(p, attr, 0); nsvg__popAttr(p); } else if (strcmp(el, "polygon") == 0) { nsvg__pushAttr(p); nsvg__parsePoly(p, attr, 1); nsvg__popAttr(p); } else if (strcmp(el, "linearGradient") == 0) { nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT); } else if (strcmp(el, "radialGradient") == 0) { nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT); } else if (strcmp(el, "stop") == 0) { nsvg__parseGradientStop(p, attr); } else if (strcmp(el, "defs") == 0) { p->defsFlag = 1; } else if (strcmp(el, "svg") == 0) { nsvg__parseSVG(p, attr); } else if (strcmp(el, "style") == 0) { p->styleFlag = 1; } } static void nsvg__endElement(void* ud, const char* el) { NSVGparser* p = (NSVGparser*)ud; if (strcmp(el, "g") == 0) { nsvg__popAttr(p); } else if (strcmp(el, "path") == 0) { p->pathFlag = 0; } else if (strcmp(el, "defs") == 0) { p->defsFlag = 0; } else if (strcmp(el, "style") == 0) { p->styleFlag = 0; } } static char *nsvg__strndup(const char *s, size_t n) { char *result; size_t len = strlen(s); if (n < len) len = n; result = (char *)malloc(len + 1); if (!result) return 0; result[len] = '\0'; return (char *)memcpy(result, s, len); } static void nsvg__content(void* ud, const char* s) { NSVGparser* p = (NSVGparser*)ud; if (p->styleFlag) { int state = 0; const char* start; while (*s) { char c = *s; if (nsvg__isspace(c) || c == '{') { if (state == 1) { NSVGstyles* next = p->styles; p->styles = (NSVGstyles*)malloc(sizeof(NSVGstyles)); p->styles->next = next; p->styles->name = nsvg__strndup(start, (size_t)(s - start)); p->styles->next = NULL; start = s + 1; state = 2; } } else if (state == 2 && c == '}') { p->styles->description = nsvg__strndup(start, (size_t)(s - start)); state = 0; } else if (state == 0) { start = s; state = 1; } s++; } // if (*s == '{' && state == NSVG_XML_CONTENT) { // // Start of a tag // *s++ = '\0'; // nsvg__parseContent(mark, contentCb, ud); // mark = s; // state = NSVG_XML_TAG; // } // else if (*s == '>' && state == NSVG_XML_TAG) { // // Start of a content or new tag. // *s++ = '\0'; // nsvg__parseElement(mark, startelCb, endelCb, ud); // mark = s; // state = NSVG_XML_CONTENT; // } // else { // s++; // } //} } // empty } static void nsvg__imageBounds(NSVGparser* p, float* bounds) { NSVGshape* shape; int count = 0; shape = p->image->shapes; bounds[0] = FLT_MAX; bounds[1] = FLT_MAX; bounds[2] = -FLT_MAX; bounds[3] = -FLT_MAX; for (; shape != NULL; shape = shape->next) { if ( (shape->flags & NSVG_FLAGS_VISIBLE) == NSVG_FLAGS_VISIBLE) { bounds[0] = nsvg__minf(bounds[0], shape->bounds[0]); bounds[1] = nsvg__minf(bounds[1], shape->bounds[1]); bounds[2] = nsvg__maxf(bounds[2], shape->bounds[2]); bounds[3] = nsvg__maxf(bounds[3], shape->bounds[3]); ++count; } } if (count == 0) { bounds[0] = bounds[1] = bounds[2] = bounds[3] = 0.0; } } static float nsvg__viewAlign(float content, float container, int type) { if (type == NSVG_ALIGN_MIN) return 0; else if (type == NSVG_ALIGN_MAX) return container - content; // mid return (container - content) * 0.5f; } static void nsvg__scaleGradient(NSVGgradient* grad, float tx, float ty, float sx, float sy) { float t[6]; nsvg__xformSetTranslation(t, tx, ty); nsvg__xformMultiply (grad->xform, t); nsvg__xformSetScale(t, sx, sy); nsvg__xformMultiply (grad->xform, t); } static void nsvg__scaleToViewbox(NSVGparser* p, const char* units) { NSVGshape* shape; NSVGpath* path; float tx, ty, sx, sy, us, bounds[4], t[6], avgs; int i; float* pt; // Guess image size if not set completely. nsvg__imageBounds(p, bounds); if (p->viewWidth == 0) { if (p->image->width > 0) { p->viewWidth = p->image->width; } else { p->viewMinx = bounds[0]; p->viewWidth = bounds[2] - bounds[0]; } } if (p->viewHeight == 0) { if (p->image->height > 0) { p->viewHeight = p->image->height; } else { p->viewMiny = bounds[1]; p->viewHeight = bounds[3] - bounds[1]; } } if (p->image->width == 0) p->image->width = p->viewWidth; if (p->image->height == 0) p->image->height = p->viewHeight; tx = -p->viewMinx; ty = -p->viewMiny; sx = p->viewWidth > 0 ? p->image->width / p->viewWidth : 0; sy = p->viewHeight > 0 ? p->image->height / p->viewHeight : 0; // Unit scaling us = 1.0f / nsvg__convertToPixels(p, nsvg__coord(1.0f, nsvg__parseUnits(units)), 0.0f, 1.0f); // Fix aspect ratio if (p->alignType == NSVG_ALIGN_MEET) { // fit whole image into viewbox sx = sy = nsvg__minf(sx, sy); tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx; ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy; } else if (p->alignType == NSVG_ALIGN_SLICE) { // fill whole viewbox with image sx = sy = nsvg__maxf(sx, sy); tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx; ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy; } // Transform sx *= us; sy *= us; avgs = (sx+sy) / 2.0f; for (shape = p->image->shapes; shape != NULL; shape = shape->next) { shape->bounds[0] = (shape->bounds[0] + tx) * sx; shape->bounds[1] = (shape->bounds[1] + ty) * sy; shape->bounds[2] = (shape->bounds[2] + tx) * sx; shape->bounds[3] = (shape->bounds[3] + ty) * sy; for (path = shape->paths; path != NULL; path = path->next) { path->bounds[0] = (path->bounds[0] + tx) * sx; path->bounds[1] = (path->bounds[1] + ty) * sy; path->bounds[2] = (path->bounds[2] + tx) * sx; path->bounds[3] = (path->bounds[3] + ty) * sy; for (i =0; i < path->npts; i++) { pt = &path->pts[i*2]; pt[0] = (pt[0] + tx) * sx; pt[1] = (pt[1] + ty) * sy; } } if (shape->fill.type == NSVG_PAINT_LINEAR_GRADIENT || shape->fill.type == NSVG_PAINT_RADIAL_GRADIENT) { nsvg__scaleGradient(shape->fill.gradient, tx,ty, sx,sy); memcpy(t, shape->fill.gradient->xform, sizeof(float)*6); nsvg__xformInverse(shape->fill.gradient->xform, t); } if (shape->stroke.type == NSVG_PAINT_LINEAR_GRADIENT || shape->stroke.type == NSVG_PAINT_RADIAL_GRADIENT) { nsvg__scaleGradient(shape->stroke.gradient, tx,ty, sx,sy); memcpy(t, shape->stroke.gradient->xform, sizeof(float)*6); nsvg__xformInverse(shape->stroke.gradient->xform, t); } shape->strokeWidth *= avgs; shape->strokeDashOffset *= avgs; for (i = 0; i < shape->strokeDashCount; i++) shape->strokeDashArray[i] *= avgs; } } NSVGimage* nsvgParse(char* input, const char* units, float dpi) { NSVGparser* p; NSVGimage* ret = 0; p = nsvg__createParser(); if (p == NULL) { return NULL; } p->dpi = dpi; nsvg__parseXML(input, nsvg__startElement, nsvg__endElement, nsvg__content, p); // Scale to viewBox nsvg__scaleToViewbox(p, units); ret = p->image; p->image = NULL; nsvg__deleteParser(p); return ret; } #ifdef HAVE_STDIO_H NSVGimage* nsvgParseFromFile(const char* filename, const char* units, float dpi) { FILE* fp = NULL; size_t size; char* data = NULL; NSVGimage* image = NULL; fp = fopen(filename, "rb"); if (!fp) goto error; fseek(fp, 0, SEEK_END); size = ftell(fp); fseek(fp, 0, SEEK_SET); data = (char*)malloc(size+1); if (data == NULL) goto error; if (fread(data, 1, size, fp) != size) goto error; data[size] = '\0'; // Must be null terminated. fclose(fp); image = nsvgParse(data, units, dpi); free(data); return image; error: if (fp) fclose(fp); if (data) free(data); if (image) nsvgDelete(image); return NULL; } #endif /* HAVE_STDIO_H */ void nsvgDelete(NSVGimage* image) { NSVGshape *snext, *shape; if (image == NULL) return; shape = image->shapes; while (shape != NULL) { snext = shape->next; nsvg__deletePaths(shape->paths); nsvg__deletePaint(&shape->fill); nsvg__deletePaint(&shape->stroke); free(shape); shape = snext; } free(image); } #endif
YifuLiu/AliOS-Things
components/SDL2/src/image/nanosvg.h
C
apache-2.0
80,039
/* * Copyright (c) 2013-14 Mikko Mononen memon@inside.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * * The polygon rasterization is heavily based on stb_truetype rasterizer * by Sean Barrett - http://nothings.org/ * */ #ifndef NANOSVGRAST_H #define NANOSVGRAST_H #ifdef __cplusplus extern "C" { #endif typedef struct NSVGrasterizer NSVGrasterizer; /* Example Usage: // Load SVG struct SNVGImage* image = nsvgParseFromFile("test.svg."); // Create rasterizer (can be used to render multiple images). struct NSVGrasterizer* rast = nsvgCreateRasterizer(); // Allocate memory for image unsigned char* img = malloc(w*h*4); // Rasterize nsvgRasterize(rast, image, 0,0,1, img, w, h, w*4); */ // Allocated rasterizer context. NSVGrasterizer* nsvgCreateRasterizer(void); // Rasterizes SVG image, returns RGBA image (non-premultiplied alpha) // r - pointer to rasterizer context // image - pointer to image to rasterize // tx,ty - image offset (applied after scaling) // scale - image scale // dst - pointer to destination image data, 4 bytes per pixel (RGBA) // w - width of the image to render // h - height of the image to render // stride - number of bytes per scaleline in the destination buffer void nsvgRasterize(NSVGrasterizer* r, NSVGimage* image, float tx, float ty, float scale, unsigned char* dst, int w, int h, int stride); // Deletes rasterizer context. void nsvgDeleteRasterizer(NSVGrasterizer*); #ifdef __cplusplus } #endif #endif // NANOSVGRAST_H #ifdef NANOSVGRAST_IMPLEMENTATION /* #include <math.h> */ #define NSVG__SUBSAMPLES 5 #define NSVG__FIXSHIFT 10 #define NSVG__FIX (1 << NSVG__FIXSHIFT) #define NSVG__FIXMASK (NSVG__FIX-1) #define NSVG__MEMPAGE_SIZE 1024 typedef struct NSVGedge { float x0,y0, x1,y1; int dir; struct NSVGedge* next; } NSVGedge; typedef struct NSVGpoint { float x, y; float dx, dy; float len; float dmx, dmy; unsigned char flags; } NSVGpoint; typedef struct NSVGactiveEdge { int x,dx; float ey; int dir; struct NSVGactiveEdge *next; } NSVGactiveEdge; typedef struct NSVGmemPage { unsigned char mem[NSVG__MEMPAGE_SIZE]; int size; struct NSVGmemPage* next; } NSVGmemPage; typedef struct NSVGcachedPaint { char type; char spread; float xform[6]; unsigned int colors[256]; } NSVGcachedPaint; struct NSVGrasterizer { float px, py; float tessTol; float distTol; NSVGedge* edges; int nedges; int cedges; NSVGpoint* points; int npoints; int cpoints; NSVGpoint* points2; int npoints2; int cpoints2; NSVGactiveEdge* freelist; NSVGmemPage* pages; NSVGmemPage* curpage; unsigned char* scanline; int cscanline; unsigned char* bitmap; int width, height, stride; }; NSVGrasterizer* nsvgCreateRasterizer() { NSVGrasterizer* r = (NSVGrasterizer*)malloc(sizeof(NSVGrasterizer)); if (r == NULL) goto error; memset(r, 0, sizeof(NSVGrasterizer)); r->tessTol = 0.25f; r->distTol = 0.01f; return r; error: nsvgDeleteRasterizer(r); return NULL; } void nsvgDeleteRasterizer(NSVGrasterizer* r) { NSVGmemPage* p; if (r == NULL) return; p = r->pages; while (p != NULL) { NSVGmemPage* next = p->next; free(p); p = next; } if (r->edges) free(r->edges); if (r->points) free(r->points); if (r->points2) free(r->points2); if (r->scanline) free(r->scanline); free(r); } static NSVGmemPage* nsvg__nextPage(NSVGrasterizer* r, NSVGmemPage* cur) { NSVGmemPage *newp; // If using existing chain, return the next page in chain if (cur != NULL && cur->next != NULL) { return cur->next; } // Alloc new page newp = (NSVGmemPage*)malloc(sizeof(NSVGmemPage)); if (newp == NULL) return NULL; memset(newp, 0, sizeof(NSVGmemPage)); // Add to linked list if (cur != NULL) cur->next = newp; else r->pages = newp; return newp; } static void nsvg__resetPool(NSVGrasterizer* r) { NSVGmemPage* p = r->pages; while (p != NULL) { p->size = 0; p = p->next; } r->curpage = r->pages; } static unsigned char* nsvg__alloc(NSVGrasterizer* r, int size) { unsigned char* buf; if (size > NSVG__MEMPAGE_SIZE) return NULL; if (r->curpage == NULL || r->curpage->size+size > NSVG__MEMPAGE_SIZE) { r->curpage = nsvg__nextPage(r, r->curpage); } buf = &r->curpage->mem[r->curpage->size]; r->curpage->size += size; return buf; } static int nsvg__ptEquals(float x1, float y1, float x2, float y2, float tol) { float dx = x2 - x1; float dy = y2 - y1; return dx*dx + dy*dy < tol*tol; } static void nsvg__addPathPoint(NSVGrasterizer* r, float x, float y, int flags) { NSVGpoint* pt; if (r->npoints > 0) { pt = &r->points[r->npoints-1]; if (nsvg__ptEquals(pt->x,pt->y, x,y, r->distTol)) { pt->flags = (unsigned char)(pt->flags | flags); return; } } if (r->npoints+1 > r->cpoints) { r->cpoints = r->cpoints > 0 ? r->cpoints * 2 : 64; r->points = (NSVGpoint*)realloc(r->points, sizeof(NSVGpoint) * r->cpoints); if (r->points == NULL) return; } pt = &r->points[r->npoints]; pt->x = x; pt->y = y; pt->flags = (unsigned char)flags; r->npoints++; } static void nsvg__appendPathPoint(NSVGrasterizer* r, NSVGpoint pt) { if (r->npoints+1 > r->cpoints) { r->cpoints = r->cpoints > 0 ? r->cpoints * 2 : 64; r->points = (NSVGpoint*)realloc(r->points, sizeof(NSVGpoint) * r->cpoints); if (r->points == NULL) return; } r->points[r->npoints] = pt; r->npoints++; } static void nsvg__duplicatePoints(NSVGrasterizer* r) { if (r->npoints > r->cpoints2) { r->cpoints2 = r->npoints; r->points2 = (NSVGpoint*)realloc(r->points2, sizeof(NSVGpoint) * r->cpoints2); if (r->points2 == NULL) return; } memcpy(r->points2, r->points, sizeof(NSVGpoint) * r->npoints); r->npoints2 = r->npoints; } static void nsvg__addEdge(NSVGrasterizer* r, float x0, float y0, float x1, float y1) { NSVGedge* e; // Skip horizontal edges if (y0 == y1) return; if (r->nedges+1 > r->cedges) { r->cedges = r->cedges > 0 ? r->cedges * 2 : 64; r->edges = (NSVGedge*)realloc(r->edges, sizeof(NSVGedge) * r->cedges); if (r->edges == NULL) return; } e = &r->edges[r->nedges]; r->nedges++; if (y0 < y1) { e->x0 = x0; e->y0 = y0; e->x1 = x1; e->y1 = y1; e->dir = 1; } else { e->x0 = x1; e->y0 = y1; e->x1 = x0; e->y1 = y0; e->dir = -1; } } static float nsvg__normalize(float *x, float* y) { float d = sqrtf((*x)*(*x) + (*y)*(*y)); if (d > 1e-6f) { float id = 1.0f / d; *x *= id; *y *= id; } return d; } static float nsvg__absf(float x) { return x < 0 ? -x : x; } static void nsvg__flattenCubicBez(NSVGrasterizer* r, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, int level, int type) { float x12,y12,x23,y23,x34,y34,x123,y123,x234,y234,x1234,y1234; float dx,dy,d2,d3; if (level > 10) return; x12 = (x1+x2)*0.5f; y12 = (y1+y2)*0.5f; x23 = (x2+x3)*0.5f; y23 = (y2+y3)*0.5f; x34 = (x3+x4)*0.5f; y34 = (y3+y4)*0.5f; x123 = (x12+x23)*0.5f; y123 = (y12+y23)*0.5f; dx = x4 - x1; dy = y4 - y1; d2 = nsvg__absf(((x2 - x4) * dy - (y2 - y4) * dx)); d3 = nsvg__absf(((x3 - x4) * dy - (y3 - y4) * dx)); if ((d2 + d3)*(d2 + d3) < r->tessTol * (dx*dx + dy*dy)) { nsvg__addPathPoint(r, x4, y4, type); return; } x234 = (x23+x34)*0.5f; y234 = (y23+y34)*0.5f; x1234 = (x123+x234)*0.5f; y1234 = (y123+y234)*0.5f; nsvg__flattenCubicBez(r, x1,y1, x12,y12, x123,y123, x1234,y1234, level+1, 0); nsvg__flattenCubicBez(r, x1234,y1234, x234,y234, x34,y34, x4,y4, level+1, type); } static void nsvg__flattenShape(NSVGrasterizer* r, NSVGshape* shape, float scale) { int i, j; NSVGpath* path; for (path = shape->paths; path != NULL; path = path->next) { r->npoints = 0; // Flatten path nsvg__addPathPoint(r, path->pts[0]*scale, path->pts[1]*scale, 0); for (i = 0; i < path->npts-1; i += 3) { float* p = &path->pts[i*2]; nsvg__flattenCubicBez(r, p[0]*scale,p[1]*scale, p[2]*scale,p[3]*scale, p[4]*scale,p[5]*scale, p[6]*scale,p[7]*scale, 0, 0); } // Close path nsvg__addPathPoint(r, path->pts[0]*scale, path->pts[1]*scale, 0); // Build edges for (i = 0, j = r->npoints-1; i < r->npoints; j = i++) nsvg__addEdge(r, r->points[j].x, r->points[j].y, r->points[i].x, r->points[i].y); } } enum NSVGpointFlags { NSVG_PT_CORNER = 0x01, NSVG_PT_BEVEL = 0x02, NSVG_PT_LEFT = 0x04 }; static void nsvg__initClosed(NSVGpoint* left, NSVGpoint* right, NSVGpoint* p0, NSVGpoint* p1, float lineWidth) { float w = lineWidth * 0.5f; float dx = p1->x - p0->x; float dy = p1->y - p0->y; float len = nsvg__normalize(&dx, &dy); float px = p0->x + dx*len*0.5f, py = p0->y + dy*len*0.5f; float dlx = dy, dly = -dx; float lx = px - dlx*w, ly = py - dly*w; float rx = px + dlx*w, ry = py + dly*w; left->x = lx; left->y = ly; right->x = rx; right->y = ry; } static void nsvg__buttCap(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p, float dx, float dy, float lineWidth, int connect) { float w = lineWidth * 0.5f; float px = p->x, py = p->y; float dlx = dy, dly = -dx; float lx = px - dlx*w, ly = py - dly*w; float rx = px + dlx*w, ry = py + dly*w; nsvg__addEdge(r, lx, ly, rx, ry); if (connect) { nsvg__addEdge(r, left->x, left->y, lx, ly); nsvg__addEdge(r, rx, ry, right->x, right->y); } left->x = lx; left->y = ly; right->x = rx; right->y = ry; } static void nsvg__squareCap(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p, float dx, float dy, float lineWidth, int connect) { float w = lineWidth * 0.5f; float px = p->x - dx*w, py = p->y - dy*w; float dlx = dy, dly = -dx; float lx = px - dlx*w, ly = py - dly*w; float rx = px + dlx*w, ry = py + dly*w; nsvg__addEdge(r, lx, ly, rx, ry); if (connect) { nsvg__addEdge(r, left->x, left->y, lx, ly); nsvg__addEdge(r, rx, ry, right->x, right->y); } left->x = lx; left->y = ly; right->x = rx; right->y = ry; } #ifndef NSVG_PI #define NSVG_PI (3.14159265358979323846264338327f) #endif static void nsvg__roundCap(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p, float dx, float dy, float lineWidth, int ncap, int connect) { int i; float w = lineWidth * 0.5f; float px = p->x, py = p->y; float dlx = dy, dly = -dx; float lx = 0, ly = 0, rx = 0, ry = 0, prevx = 0, prevy = 0; for (i = 0; i < ncap; i++) { float a = (float)i/(float)(ncap-1)*NSVG_PI; float ax = cosf(a) * w, ay = sinf(a) * w; float x = px - dlx*ax - dx*ay; float y = py - dly*ax - dy*ay; if (i > 0) nsvg__addEdge(r, prevx, prevy, x, y); prevx = x; prevy = y; if (i == 0) { lx = x; ly = y; } else if (i == ncap-1) { rx = x; ry = y; } } if (connect) { nsvg__addEdge(r, left->x, left->y, lx, ly); nsvg__addEdge(r, rx, ry, right->x, right->y); } left->x = lx; left->y = ly; right->x = rx; right->y = ry; } static void nsvg__bevelJoin(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p0, NSVGpoint* p1, float lineWidth) { float w = lineWidth * 0.5f; float dlx0 = p0->dy, dly0 = -p0->dx; float dlx1 = p1->dy, dly1 = -p1->dx; float lx0 = p1->x - (dlx0 * w), ly0 = p1->y - (dly0 * w); float rx0 = p1->x + (dlx0 * w), ry0 = p1->y + (dly0 * w); float lx1 = p1->x - (dlx1 * w), ly1 = p1->y - (dly1 * w); float rx1 = p1->x + (dlx1 * w), ry1 = p1->y + (dly1 * w); nsvg__addEdge(r, lx0, ly0, left->x, left->y); nsvg__addEdge(r, lx1, ly1, lx0, ly0); nsvg__addEdge(r, right->x, right->y, rx0, ry0); nsvg__addEdge(r, rx0, ry0, rx1, ry1); left->x = lx1; left->y = ly1; right->x = rx1; right->y = ry1; } static void nsvg__miterJoin(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p0, NSVGpoint* p1, float lineWidth) { float w = lineWidth * 0.5f; float dlx0 = p0->dy, dly0 = -p0->dx; float dlx1 = p1->dy, dly1 = -p1->dx; float lx0, rx0, lx1, rx1; float ly0, ry0, ly1, ry1; if (p1->flags & NSVG_PT_LEFT) { lx0 = lx1 = p1->x - p1->dmx * w; ly0 = ly1 = p1->y - p1->dmy * w; nsvg__addEdge(r, lx1, ly1, left->x, left->y); rx0 = p1->x + (dlx0 * w); ry0 = p1->y + (dly0 * w); rx1 = p1->x + (dlx1 * w); ry1 = p1->y + (dly1 * w); nsvg__addEdge(r, right->x, right->y, rx0, ry0); nsvg__addEdge(r, rx0, ry0, rx1, ry1); } else { lx0 = p1->x - (dlx0 * w); ly0 = p1->y - (dly0 * w); lx1 = p1->x - (dlx1 * w); ly1 = p1->y - (dly1 * w); nsvg__addEdge(r, lx0, ly0, left->x, left->y); nsvg__addEdge(r, lx1, ly1, lx0, ly0); rx0 = rx1 = p1->x + p1->dmx * w; ry0 = ry1 = p1->y + p1->dmy * w; nsvg__addEdge(r, right->x, right->y, rx1, ry1); } left->x = lx1; left->y = ly1; right->x = rx1; right->y = ry1; } static void nsvg__roundJoin(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p0, NSVGpoint* p1, float lineWidth, int ncap) { int i, n; float w = lineWidth * 0.5f; float dlx0 = p0->dy, dly0 = -p0->dx; float dlx1 = p1->dy, dly1 = -p1->dx; float a0 = atan2f(dly0, dlx0); float a1 = atan2f(dly1, dlx1); float da = a1 - a0; float lx, ly, rx, ry; if (da < NSVG_PI) da += NSVG_PI*2; if (da > NSVG_PI) da -= NSVG_PI*2; n = (int)ceilf((nsvg__absf(da) / NSVG_PI) * (float)ncap); if (n < 2) n = 2; if (n > ncap) n = ncap; lx = left->x; ly = left->y; rx = right->x; ry = right->y; for (i = 0; i < n; i++) { float u = (float)i/(float)(n-1); float a = a0 + u*da; float ax = cosf(a) * w, ay = sinf(a) * w; float lx1 = p1->x - ax, ly1 = p1->y - ay; float rx1 = p1->x + ax, ry1 = p1->y + ay; nsvg__addEdge(r, lx1, ly1, lx, ly); nsvg__addEdge(r, rx, ry, rx1, ry1); lx = lx1; ly = ly1; rx = rx1; ry = ry1; } left->x = lx; left->y = ly; right->x = rx; right->y = ry; } static void nsvg__straightJoin(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p1, float lineWidth) { float w = lineWidth * 0.5f; float lx = p1->x - (p1->dmx * w), ly = p1->y - (p1->dmy * w); float rx = p1->x + (p1->dmx * w), ry = p1->y + (p1->dmy * w); nsvg__addEdge(r, lx, ly, left->x, left->y); nsvg__addEdge(r, right->x, right->y, rx, ry); left->x = lx; left->y = ly; right->x = rx; right->y = ry; } static int nsvg__curveDivs(float r, float arc, float tol) { float da = acosf(r / (r + tol)) * 2.0f; int divs = (int)ceilf(arc / da); if (divs < 2) divs = 2; return divs; } static void nsvg__expandStroke(NSVGrasterizer* r, NSVGpoint* points, int npoints, int closed, int lineJoin, int lineCap, float lineWidth) { int ncap = nsvg__curveDivs(lineWidth*0.5f, NSVG_PI, r->tessTol); // Calculate divisions per half circle. NSVGpoint left = {0,0,0,0,0,0,0,0}, right = {0,0,0,0,0,0,0,0}, firstLeft = {0,0,0,0,0,0,0,0}, firstRight = {0,0,0,0,0,0,0,0}; NSVGpoint* p0, *p1; int j, s, e; // Build stroke edges if (closed) { // Looping p0 = &points[npoints-1]; p1 = &points[0]; s = 0; e = npoints; } else { // Add cap p0 = &points[0]; p1 = &points[1]; s = 1; e = npoints-1; } if (closed) { nsvg__initClosed(&left, &right, p0, p1, lineWidth); firstLeft = left; firstRight = right; } else { // Add cap float dx = p1->x - p0->x; float dy = p1->y - p0->y; nsvg__normalize(&dx, &dy); if (lineCap == NSVG_CAP_BUTT) nsvg__buttCap(r, &left, &right, p0, dx, dy, lineWidth, 0); else if (lineCap == NSVG_CAP_SQUARE) nsvg__squareCap(r, &left, &right, p0, dx, dy, lineWidth, 0); else if (lineCap == NSVG_CAP_ROUND) nsvg__roundCap(r, &left, &right, p0, dx, dy, lineWidth, ncap, 0); } for (j = s; j < e; ++j) { if (p1->flags & NSVG_PT_CORNER) { if (lineJoin == NSVG_JOIN_ROUND) nsvg__roundJoin(r, &left, &right, p0, p1, lineWidth, ncap); else if (lineJoin == NSVG_JOIN_BEVEL || (p1->flags & NSVG_PT_BEVEL)) nsvg__bevelJoin(r, &left, &right, p0, p1, lineWidth); else nsvg__miterJoin(r, &left, &right, p0, p1, lineWidth); } else { nsvg__straightJoin(r, &left, &right, p1, lineWidth); } p0 = p1++; } if (closed) { // Loop it nsvg__addEdge(r, firstLeft.x, firstLeft.y, left.x, left.y); nsvg__addEdge(r, right.x, right.y, firstRight.x, firstRight.y); } else { // Add cap float dx = p1->x - p0->x; float dy = p1->y - p0->y; nsvg__normalize(&dx, &dy); if (lineCap == NSVG_CAP_BUTT) nsvg__buttCap(r, &right, &left, p1, -dx, -dy, lineWidth, 1); else if (lineCap == NSVG_CAP_SQUARE) nsvg__squareCap(r, &right, &left, p1, -dx, -dy, lineWidth, 1); else if (lineCap == NSVG_CAP_ROUND) nsvg__roundCap(r, &right, &left, p1, -dx, -dy, lineWidth, ncap, 1); } } static void nsvg__prepareStroke(NSVGrasterizer* r, float miterLimit, int lineJoin) { int i, j; NSVGpoint* p0, *p1; p0 = &r->points[r->npoints-1]; p1 = &r->points[0]; for (i = 0; i < r->npoints; i++) { // Calculate segment direction and length p0->dx = p1->x - p0->x; p0->dy = p1->y - p0->y; p0->len = nsvg__normalize(&p0->dx, &p0->dy); // Advance p0 = p1++; } // calculate joins p0 = &r->points[r->npoints-1]; p1 = &r->points[0]; for (j = 0; j < r->npoints; j++) { float dlx0, dly0, dlx1, dly1, dmr2, cross; dlx0 = p0->dy; dly0 = -p0->dx; dlx1 = p1->dy; dly1 = -p1->dx; // Calculate extrusions p1->dmx = (dlx0 + dlx1) * 0.5f; p1->dmy = (dly0 + dly1) * 0.5f; dmr2 = p1->dmx*p1->dmx + p1->dmy*p1->dmy; if (dmr2 > 0.000001f) { float s2 = 1.0f / dmr2; if (s2 > 600.0f) { s2 = 600.0f; } p1->dmx *= s2; p1->dmy *= s2; } // Clear flags, but keep the corner. p1->flags = (p1->flags & NSVG_PT_CORNER) ? NSVG_PT_CORNER : 0; // Keep track of left turns. cross = p1->dx * p0->dy - p0->dx * p1->dy; if (cross > 0.0f) p1->flags |= NSVG_PT_LEFT; // Check to see if the corner needs to be beveled. if (p1->flags & NSVG_PT_CORNER) { if ((dmr2 * miterLimit*miterLimit) < 1.0f || lineJoin == NSVG_JOIN_BEVEL || lineJoin == NSVG_JOIN_ROUND) { p1->flags |= NSVG_PT_BEVEL; } } p0 = p1++; } } static void nsvg__flattenShapeStroke(NSVGrasterizer* r, NSVGshape* shape, float scale) { int i, j, closed; NSVGpath* path; NSVGpoint* p0, *p1; float miterLimit = shape->miterLimit; int lineJoin = shape->strokeLineJoin; int lineCap = shape->strokeLineCap; float lineWidth = shape->strokeWidth * scale; for (path = shape->paths; path != NULL; path = path->next) { // Flatten path r->npoints = 0; nsvg__addPathPoint(r, path->pts[0]*scale, path->pts[1]*scale, NSVG_PT_CORNER); for (i = 0; i < path->npts-1; i += 3) { float* p = &path->pts[i*2]; nsvg__flattenCubicBez(r, p[0]*scale,p[1]*scale, p[2]*scale,p[3]*scale, p[4]*scale,p[5]*scale, p[6]*scale,p[7]*scale, 0, NSVG_PT_CORNER); } if (r->npoints < 2) continue; closed = path->closed; // If the first and last points are the same, remove the last, mark as closed path. p0 = &r->points[r->npoints-1]; p1 = &r->points[0]; if (nsvg__ptEquals(p0->x,p0->y, p1->x,p1->y, r->distTol)) { r->npoints--; p0 = &r->points[r->npoints-1]; closed = 1; } if (shape->strokeDashCount > 0) { int idash = 0, dashState = 1; float totalDist = 0, dashLen, allDashLen, dashOffset; NSVGpoint cur; if (closed) nsvg__appendPathPoint(r, r->points[0]); // Duplicate points -> points2. nsvg__duplicatePoints(r); r->npoints = 0; cur = r->points2[0]; nsvg__appendPathPoint(r, cur); // Figure out dash offset. allDashLen = 0; for (j = 0; j < shape->strokeDashCount; j++) allDashLen += shape->strokeDashArray[j]; if (shape->strokeDashCount & 1) allDashLen *= 2.0f; // Find location inside pattern dashOffset = fmodf(shape->strokeDashOffset, allDashLen); if (dashOffset < 0.0f) dashOffset += allDashLen; while (dashOffset > shape->strokeDashArray[idash]) { dashOffset -= shape->strokeDashArray[idash]; idash = (idash + 1) % shape->strokeDashCount; } dashLen = (shape->strokeDashArray[idash] - dashOffset) * scale; for (j = 1; j < r->npoints2; ) { float dx = r->points2[j].x - cur.x; float dy = r->points2[j].y - cur.y; float dist = sqrtf(dx*dx + dy*dy); if ((totalDist + dist) > dashLen) { // Calculate intermediate point float d = (dashLen - totalDist) / dist; float x = cur.x + dx * d; float y = cur.y + dy * d; nsvg__addPathPoint(r, x, y, NSVG_PT_CORNER); // Stroke if (r->npoints > 1 && dashState) { nsvg__prepareStroke(r, miterLimit, lineJoin); nsvg__expandStroke(r, r->points, r->npoints, 0, lineJoin, lineCap, lineWidth); } // Advance dash pattern dashState = !dashState; idash = (idash+1) % shape->strokeDashCount; dashLen = shape->strokeDashArray[idash] * scale; // Restart cur.x = x; cur.y = y; cur.flags = NSVG_PT_CORNER; totalDist = 0.0f; r->npoints = 0; nsvg__appendPathPoint(r, cur); } else { totalDist += dist; cur = r->points2[j]; nsvg__appendPathPoint(r, cur); j++; } } // Stroke any leftover path if (r->npoints > 1 && dashState) nsvg__expandStroke(r, r->points, r->npoints, 0, lineJoin, lineCap, lineWidth); } else { nsvg__prepareStroke(r, miterLimit, lineJoin); nsvg__expandStroke(r, r->points, r->npoints, closed, lineJoin, lineCap, lineWidth); } } } static int nsvg__cmpEdge(const void *p, const void *q) { const NSVGedge* a = (const NSVGedge*)p; const NSVGedge* b = (const NSVGedge*)q; if (a->y0 < b->y0) return -1; if (a->y0 > b->y0) return 1; return 0; } static NSVGactiveEdge* nsvg__addActive(NSVGrasterizer* r, NSVGedge* e, float startPoint) { NSVGactiveEdge* z; float dxdy; if (r->freelist != NULL) { // Restore from freelist. z = r->freelist; r->freelist = z->next; } else { // Alloc new edge. z = (NSVGactiveEdge*)nsvg__alloc(r, sizeof(NSVGactiveEdge)); if (z == NULL) return NULL; } dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); // STBTT_assert(e->y0 <= start_point); // round dx down to avoid going too far if (dxdy < 0) z->dx = (int)(-floorf(NSVG__FIX * -dxdy)); else z->dx = (int)floorf(NSVG__FIX * dxdy); z->x = (int)floorf(NSVG__FIX * (e->x0 + dxdy * (startPoint - e->y0))); // z->x -= off_x * FIX; z->ey = e->y1; z->next = 0; z->dir = e->dir; return z; } static void nsvg__freeActive(NSVGrasterizer* r, NSVGactiveEdge* z) { z->next = r->freelist; r->freelist = z; } static void nsvg__fillScanline(unsigned char* scanline, int len, int x0, int x1, int maxWeight, int* xmin, int* xmax) { int i = x0 >> NSVG__FIXSHIFT; int j = x1 >> NSVG__FIXSHIFT; if (i < *xmin) *xmin = i; if (j > *xmax) *xmax = j; if (i < len && j >= 0) { if (i == j) { // x0,x1 are the same pixel, so compute combined coverage scanline[i] = (unsigned char)(scanline[i] + ((x1 - x0) * maxWeight >> NSVG__FIXSHIFT)); } else { if (i >= 0) // add antialiasing for x0 scanline[i] = (unsigned char)(scanline[i] + (((NSVG__FIX - (x0 & NSVG__FIXMASK)) * maxWeight) >> NSVG__FIXSHIFT)); else i = -1; // clip if (j < len) // add antialiasing for x1 scanline[j] = (unsigned char)(scanline[j] + (((x1 & NSVG__FIXMASK) * maxWeight) >> NSVG__FIXSHIFT)); else j = len; // clip for (++i; i < j; ++i) // fill pixels between x0 and x1 scanline[i] = (unsigned char)(scanline[i] + maxWeight); } } } // note: this routine clips fills that extend off the edges... ideally this // wouldn't happen, but it could happen if the truetype glyph bounding boxes // are wrong, or if the user supplies a too-small bitmap static void nsvg__fillActiveEdges(unsigned char* scanline, int len, NSVGactiveEdge* e, int maxWeight, int* xmin, int* xmax, char fillRule) { // non-zero winding fill int x0 = 0, w = 0; if (fillRule == NSVG_FILLRULE_NONZERO) { // Non-zero while (e != NULL) { if (w == 0) { // if we're currently at zero, we need to record the edge start point x0 = e->x; w += e->dir; } else { int x1 = e->x; w += e->dir; // if we went to zero, we need to draw if (w == 0) nsvg__fillScanline(scanline, len, x0, x1, maxWeight, xmin, xmax); } e = e->next; } } else if (fillRule == NSVG_FILLRULE_EVENODD) { // Even-odd while (e != NULL) { if (w == 0) { // if we're currently at zero, we need to record the edge start point x0 = e->x; w = 1; } else { int x1 = e->x; w = 0; nsvg__fillScanline(scanline, len, x0, x1, maxWeight, xmin, xmax); } e = e->next; } } } static float nsvg__clampf(float a, float mn, float mx) { return a < mn ? mn : (a > mx ? mx : a); } static unsigned int nsvg__RGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a) { return (r) | (g << 8) | (b << 16) | (a << 24); } static unsigned int nsvg__lerpRGBA(unsigned int c0, unsigned int c1, float u) { int iu = (int)(nsvg__clampf(u, 0.0f, 1.0f) * 256.0f); int r = (((c0) & 0xff)*(256-iu) + (((c1) & 0xff)*iu)) >> 8; int g = (((c0>>8) & 0xff)*(256-iu) + (((c1>>8) & 0xff)*iu)) >> 8; int b = (((c0>>16) & 0xff)*(256-iu) + (((c1>>16) & 0xff)*iu)) >> 8; int a = (((c0>>24) & 0xff)*(256-iu) + (((c1>>24) & 0xff)*iu)) >> 8; return nsvg__RGBA((unsigned char)r, (unsigned char)g, (unsigned char)b, (unsigned char)a); } static unsigned int nsvg__applyOpacity(unsigned int c, float u) { int iu = (int)(nsvg__clampf(u, 0.0f, 1.0f) * 256.0f); int r = (c) & 0xff; int g = (c>>8) & 0xff; int b = (c>>16) & 0xff; int a = (((c>>24) & 0xff)*iu) >> 8; return nsvg__RGBA((unsigned char)r, (unsigned char)g, (unsigned char)b, (unsigned char)a); } static int nsvg__div255(int x) { return ((x+1) * 257) >> 16; } static void nsvg__scanlineSolid(unsigned char* dst, int count, unsigned char* cover, int x, int y, float tx, float ty, float scale, NSVGcachedPaint* cache) { if (cache->type == NSVG_PAINT_COLOR) { int i, cr, cg, cb, ca; cr = cache->colors[0] & 0xff; cg = (cache->colors[0] >> 8) & 0xff; cb = (cache->colors[0] >> 16) & 0xff; ca = (cache->colors[0] >> 24) & 0xff; for (i = 0; i < count; i++) { int r,g,b; int a = nsvg__div255((int)cover[0] * ca); int ia = 255 - a; // Premultiply r = nsvg__div255(cr * a); g = nsvg__div255(cg * a); b = nsvg__div255(cb * a); // Blend over r += nsvg__div255(ia * (int)dst[0]); g += nsvg__div255(ia * (int)dst[1]); b += nsvg__div255(ia * (int)dst[2]); a += nsvg__div255(ia * (int)dst[3]); dst[0] = (unsigned char)r; dst[1] = (unsigned char)g; dst[2] = (unsigned char)b; dst[3] = (unsigned char)a; cover++; dst += 4; } } else if (cache->type == NSVG_PAINT_LINEAR_GRADIENT) { // TODO: spread modes. // TODO: plenty of opportunities to optimize. float fx, fy, dx, gy; float* t = cache->xform; int i, cr, cg, cb, ca; unsigned int c; fx = ((float)x - tx) / scale; fy = ((float)y - ty) / scale; dx = 1.0f / scale; for (i = 0; i < count; i++) { int r,g,b,a,ia; gy = fx*t[1] + fy*t[3] + t[5]; c = cache->colors[(int)nsvg__clampf(gy*255.0f, 0, 255.0f)]; cr = (c) & 0xff; cg = (c >> 8) & 0xff; cb = (c >> 16) & 0xff; ca = (c >> 24) & 0xff; a = nsvg__div255((int)cover[0] * ca); ia = 255 - a; // Premultiply r = nsvg__div255(cr * a); g = nsvg__div255(cg * a); b = nsvg__div255(cb * a); // Blend over r += nsvg__div255(ia * (int)dst[0]); g += nsvg__div255(ia * (int)dst[1]); b += nsvg__div255(ia * (int)dst[2]); a += nsvg__div255(ia * (int)dst[3]); dst[0] = (unsigned char)r; dst[1] = (unsigned char)g; dst[2] = (unsigned char)b; dst[3] = (unsigned char)a; cover++; dst += 4; fx += dx; } } else if (cache->type == NSVG_PAINT_RADIAL_GRADIENT) { // TODO: spread modes. // TODO: plenty of opportunities to optimize. // TODO: focus (fx,fy) float fx, fy, dx, gx, gy, gd; float* t = cache->xform; int i, cr, cg, cb, ca; unsigned int c; fx = ((float)x - tx) / scale; fy = ((float)y - ty) / scale; dx = 1.0f / scale; for (i = 0; i < count; i++) { int r,g,b,a,ia; gx = fx*t[0] + fy*t[2] + t[4]; gy = fx*t[1] + fy*t[3] + t[5]; gd = sqrtf(gx*gx + gy*gy); c = cache->colors[(int)nsvg__clampf(gd*255.0f, 0, 255.0f)]; cr = (c) & 0xff; cg = (c >> 8) & 0xff; cb = (c >> 16) & 0xff; ca = (c >> 24) & 0xff; a = nsvg__div255((int)cover[0] * ca); ia = 255 - a; // Premultiply r = nsvg__div255(cr * a); g = nsvg__div255(cg * a); b = nsvg__div255(cb * a); // Blend over r += nsvg__div255(ia * (int)dst[0]); g += nsvg__div255(ia * (int)dst[1]); b += nsvg__div255(ia * (int)dst[2]); a += nsvg__div255(ia * (int)dst[3]); dst[0] = (unsigned char)r; dst[1] = (unsigned char)g; dst[2] = (unsigned char)b; dst[3] = (unsigned char)a; cover++; dst += 4; fx += dx; } } } static void nsvg__rasterizeSortedEdges(NSVGrasterizer *r, float tx, float ty, float scale, NSVGcachedPaint* cache, char fillRule) { NSVGactiveEdge *active = NULL; int y, s; int e = 0; int maxWeight = (255 / NSVG__SUBSAMPLES); // weight per vertical scanline int xmin, xmax; for (y = 0; y < r->height; y++) { memset(r->scanline, 0, r->width); xmin = r->width; xmax = 0; for (s = 0; s < NSVG__SUBSAMPLES; ++s) { // find center of pixel for this scanline float scany = (float)(y*NSVG__SUBSAMPLES + s) + 0.5f; NSVGactiveEdge **step = &active; // update all active edges; // remove all active edges that terminate before the center of this scanline while (*step) { NSVGactiveEdge *z = *step; if (z->ey <= scany) { *step = z->next; // delete from list // NSVG__assert(z->valid); nsvg__freeActive(r, z); } else { z->x += z->dx; // advance to position for current scanline step = &((*step)->next); // advance through list } } // resort the list if needed for (;;) { int changed = 0; step = &active; while (*step && (*step)->next) { if ((*step)->x > (*step)->next->x) { NSVGactiveEdge* t = *step; NSVGactiveEdge* q = t->next; t->next = q->next; q->next = t; *step = q; changed = 1; } step = &(*step)->next; } if (!changed) break; } // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline while (e < r->nedges && r->edges[e].y0 <= scany) { if (r->edges[e].y1 > scany) { NSVGactiveEdge* z = nsvg__addActive(r, &r->edges[e], scany); if (z == NULL) break; // find insertion point if (active == NULL) { active = z; } else if (z->x < active->x) { // insert at front z->next = active; active = z; } else { // find thing to insert AFTER NSVGactiveEdge* p = active; while (p->next && p->next->x < z->x) p = p->next; // at this point, p->next->x is NOT < z->x z->next = p->next; p->next = z; } } e++; } // now process all active edges in non-zero fashion if (active != NULL) nsvg__fillActiveEdges(r->scanline, r->width, active, maxWeight, &xmin, &xmax, fillRule); } // Blit if (xmin < 0) xmin = 0; if (xmax > r->width-1) xmax = r->width-1; if (xmin <= xmax) { nsvg__scanlineSolid(&r->bitmap[y * r->stride] + xmin*4, xmax-xmin+1, &r->scanline[xmin], xmin, y, tx,ty, scale, cache); } } } static void nsvg__unpremultiplyAlpha(unsigned char* image, int w, int h, int stride) { int x,y; // Unpremultiply for (y = 0; y < h; y++) { unsigned char *row = &image[y*stride]; for (x = 0; x < w; x++) { int r = row[0], g = row[1], b = row[2], a = row[3]; if (a != 0) { row[0] = (unsigned char)(r*255/a); row[1] = (unsigned char)(g*255/a); row[2] = (unsigned char)(b*255/a); } row += 4; } } // Defringe for (y = 0; y < h; y++) { unsigned char *row = &image[y*stride]; for (x = 0; x < w; x++) { int r = 0, g = 0, b = 0, a = row[3], n = 0; if (a == 0) { if (x-1 > 0 && row[-1] != 0) { r += row[-4]; g += row[-3]; b += row[-2]; n++; } if (x+1 < w && row[7] != 0) { r += row[4]; g += row[5]; b += row[6]; n++; } if (y-1 > 0 && row[-stride+3] != 0) { r += row[-stride]; g += row[-stride+1]; b += row[-stride+2]; n++; } if (y+1 < h && row[stride+3] != 0) { r += row[stride]; g += row[stride+1]; b += row[stride+2]; n++; } if (n > 0) { row[0] = (unsigned char)(r/n); row[1] = (unsigned char)(g/n); row[2] = (unsigned char)(b/n); } } row += 4; } } } static void nsvg__initPaint(NSVGcachedPaint* cache, NSVGpaint* paint, float opacity) { int i, j; NSVGgradient* grad; cache->type = paint->type; if (paint->type == NSVG_PAINT_COLOR) { cache->colors[0] = nsvg__applyOpacity(paint->color, opacity); return; } grad = paint->gradient; cache->spread = grad->spread; memcpy(cache->xform, grad->xform, sizeof(float)*6); if (grad->nstops == 0) { for (i = 0; i < 256; i++) cache->colors[i] = 0; } if (grad->nstops == 1) { for (i = 0; i < 256; i++) cache->colors[i] = nsvg__applyOpacity(grad->stops[i].color, opacity); } else { unsigned int ca, cb = 0; float ua, ub, du, u; int ia, ib, count; ca = nsvg__applyOpacity(grad->stops[0].color, opacity); ua = nsvg__clampf(grad->stops[0].offset, 0, 1); ub = nsvg__clampf(grad->stops[grad->nstops-1].offset, ua, 1); ia = (int)(ua * 255.0f); ib = (int)(ub * 255.0f); for (i = 0; i < ia; i++) { cache->colors[i] = ca; } for (i = 0; i < grad->nstops-1; i++) { ca = nsvg__applyOpacity(grad->stops[i].color, opacity); cb = nsvg__applyOpacity(grad->stops[i+1].color, opacity); ua = nsvg__clampf(grad->stops[i].offset, 0, 1); ub = nsvg__clampf(grad->stops[i+1].offset, 0, 1); ia = (int)(ua * 255.0f); ib = (int)(ub * 255.0f); count = ib - ia; if (count <= 0) continue; u = 0; du = 1.0f / (float)count; for (j = 0; j < count; j++) { cache->colors[ia+j] = nsvg__lerpRGBA(ca,cb,u); u += du; } } for (i = ib; i < 256; i++) cache->colors[i] = cb; } } /* static void dumpEdges(NSVGrasterizer* r, const char* name) { float xmin = 0, xmax = 0, ymin = 0, ymax = 0; NSVGedge *e = NULL; int i; if (r->nedges == 0) return; FILE* fp = fopen(name, "w"); if (fp == NULL) return; xmin = xmax = r->edges[0].x0; ymin = ymax = r->edges[0].y0; for (i = 0; i < r->nedges; i++) { e = &r->edges[i]; xmin = nsvg__minf(xmin, e->x0); xmin = nsvg__minf(xmin, e->x1); xmax = nsvg__maxf(xmax, e->x0); xmax = nsvg__maxf(xmax, e->x1); ymin = nsvg__minf(ymin, e->y0); ymin = nsvg__minf(ymin, e->y1); ymax = nsvg__maxf(ymax, e->y0); ymax = nsvg__maxf(ymax, e->y1); } fprintf(fp, "<svg viewBox=\"%f %f %f %f\" xmlns=\"http://www.w3.org/2000/svg\">", xmin, ymin, (xmax - xmin), (ymax - ymin)); for (i = 0; i < r->nedges; i++) { e = &r->edges[i]; fprintf(fp ,"<line x1=\"%f\" y1=\"%f\" x2=\"%f\" y2=\"%f\" style=\"stroke:#000;\" />", e->x0,e->y0, e->x1,e->y1); } for (i = 0; i < r->npoints; i++) { if (i+1 < r->npoints) fprintf(fp ,"<line x1=\"%f\" y1=\"%f\" x2=\"%f\" y2=\"%f\" style=\"stroke:#f00;\" />", r->points[i].x, r->points[i].y, r->points[i+1].x, r->points[i+1].y); fprintf(fp ,"<circle cx=\"%f\" cy=\"%f\" r=\"1\" style=\"fill:%s;\" />", r->points[i].x, r->points[i].y, r->points[i].flags == 0 ? "#f00" : "#0f0"); } fprintf(fp, "</svg>"); fclose(fp); } */ void nsvgRasterize(NSVGrasterizer* r, NSVGimage* image, float tx, float ty, float scale, unsigned char* dst, int w, int h, int stride) { NSVGshape *shape = NULL; NSVGedge *e = NULL; NSVGcachedPaint cache; int i; r->bitmap = dst; r->width = w; r->height = h; r->stride = stride; if (w > r->cscanline) { r->cscanline = w; r->scanline = (unsigned char*)realloc(r->scanline, w); if (r->scanline == NULL) return; } for (i = 0; i < h; i++) memset(&dst[i*stride], 0, w*4); for (shape = image->shapes; shape != NULL; shape = shape->next) { if (!(shape->flags & NSVG_FLAGS_VISIBLE)) continue; if (shape->fill.type != NSVG_PAINT_NONE) { nsvg__resetPool(r); r->freelist = NULL; r->nedges = 0; nsvg__flattenShape(r, shape, scale); // Scale and translate edges for (i = 0; i < r->nedges; i++) { e = &r->edges[i]; e->x0 = tx + e->x0; e->y0 = (ty + e->y0) * NSVG__SUBSAMPLES; e->x1 = tx + e->x1; e->y1 = (ty + e->y1) * NSVG__SUBSAMPLES; } // Rasterize edges qsort(r->edges, r->nedges, sizeof(NSVGedge), nsvg__cmpEdge); // now, traverse the scanlines and find the intersections on each scanline, use non-zero rule nsvg__initPaint(&cache, &shape->fill, shape->opacity); nsvg__rasterizeSortedEdges(r, tx,ty,scale, &cache, shape->fillRule); } if (shape->stroke.type != NSVG_PAINT_NONE && (shape->strokeWidth * scale) > 0.01f) { nsvg__resetPool(r); r->freelist = NULL; r->nedges = 0; nsvg__flattenShapeStroke(r, shape, scale); // dumpEdges(r, "edge.svg"); // Scale and translate edges for (i = 0; i < r->nedges; i++) { e = &r->edges[i]; e->x0 = tx + e->x0; e->y0 = (ty + e->y0) * NSVG__SUBSAMPLES; e->x1 = tx + e->x1; e->y1 = (ty + e->y1) * NSVG__SUBSAMPLES; } // Rasterize edges qsort(r->edges, r->nedges, sizeof(NSVGedge), nsvg__cmpEdge); // now, traverse the scanlines and find the intersections on each scanline, use non-zero rule nsvg__initPaint(&cache, &shape->stroke, shape->opacity); nsvg__rasterizeSortedEdges(r, tx,ty,scale, &cache, NSVG_FILLRULE_NONZERO); } } nsvg__unpremultiplyAlpha(dst, w, h, stride); r->bitmap = NULL; r->width = 0; r->height = 0; r->stride = 0; } #endif
YifuLiu/AliOS-Things
components/SDL2/src/image/nanosvgrast.h
C
apache-2.0
38,122
/* showimage: A test application for the SDL image loading library. Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "SDL.h" #include "SDL_image.h" /* Draw a Gimpish background pattern to show transparency in the image */ static void draw_background(SDL_Renderer *renderer, int w, int h) { SDL_Color col[2] = { { 0x66, 0x66, 0x66, 0xff }, { 0x99, 0x99, 0x99, 0xff }, }; int i, x, y; SDL_Rect rect; rect.w = 8; rect.h = 8; for (y = 0; y < h; y += rect.h) { for (x = 0; x < w; x += rect.w) { /* use an 8x8 checkerboard pattern */ i = (((x ^ y) >> 3) & 1); SDL_SetRenderDrawColor(renderer, col[i].r, col[i].g, col[i].b, col[i].a); rect.x = x; rect.y = y; SDL_RenderFillRect(renderer, &rect); } } } int main(int argc, char *argv[]) { SDL_Window *window; SDL_Renderer *renderer; SDL_Texture *texture; Uint32 flags; int i, w, h, done; SDL_Event event; const char *saveFile = NULL; /* Check command line usage */ if ( ! argv[1] ) { SDL_Log("Usage: %s [-fullscreen] [-save file.png] <image_file> ...\n", argv[0]); return(1); } flags = SDL_WINDOW_HIDDEN; for ( i=1; argv[i]; ++i ) { if ( SDL_strcmp(argv[i], "-fullscreen") == 0 ) { SDL_ShowCursor(0); flags |= SDL_WINDOW_FULLSCREEN; } } if (SDL_Init(SDL_INIT_VIDEO) == -1) { SDL_Log("SDL_Init(SDL_INIT_VIDEO) failed: %s\n", SDL_GetError()); return(2); } if (SDL_CreateWindowAndRenderer(0, 0, flags, &window, &renderer) < 0) { SDL_Log("SDL_CreateWindowAndRenderer() failed: %s\n", SDL_GetError()); return(2); } for ( i=1; argv[i]; ++i ) { if ( SDL_strcmp(argv[i], "-fullscreen") == 0 ) { continue; } if ( SDL_strcmp(argv[i], "-save") == 0 && argv[i+1] ) { ++i; saveFile = argv[i]; continue; } /* Open the image file */ texture = IMG_LoadTexture(renderer, argv[i]); if (!texture) { SDL_Log("Couldn't load %s: %s\n", argv[i], SDL_GetError()); continue; } SDL_QueryTexture(texture, NULL, NULL, &w, &h); /* Save the image file, if desired */ if ( saveFile ) { SDL_Surface *surface = IMG_Load(argv[i]); if (surface) { int result; const char *ext = SDL_strrchr(saveFile, '.'); if ( ext && SDL_strcasecmp(ext, ".bmp") == 0 ) { result = SDL_SaveBMP(surface, saveFile); } else if ( ext && SDL_strcasecmp(ext, ".jpg") == 0 ) { result = IMG_SaveJPG(surface, saveFile, 90); } else { result = IMG_SavePNG(surface, saveFile); } if ( result < 0 ) { SDL_Log("Couldn't save %s: %s\n", saveFile, SDL_GetError()); } } else { SDL_Log("Couldn't load %s: %s\n", argv[i], SDL_GetError()); } } /* Show the window */ SDL_SetWindowTitle(window, argv[i]); SDL_SetWindowSize(window, w, h); SDL_ShowWindow(window); done = 0; while ( ! done ) { while ( SDL_PollEvent(&event) ) { switch (event.type) { case SDL_KEYUP: switch (event.key.keysym.sym) { case SDLK_LEFT: if ( i > 1 ) { i -= 2; done = 1; } break; case SDLK_RIGHT: if ( argv[i+1] ) { done = 1; } break; case SDLK_ESCAPE: case SDLK_q: argv[i+1] = NULL; /* Drop through to done */ case SDLK_SPACE: case SDLK_TAB: done = 1; break; default: break; } break; case SDL_MOUSEBUTTONDOWN: done = 1; break; case SDL_QUIT: argv[i+1] = NULL; done = 1; break; default: break; } } /* Draw a background pattern in case the image has transparency */ draw_background(renderer, w, h); /* Display the image */ SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); SDL_Delay(100); } SDL_DestroyTexture(texture); } SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); /* We're done! */ SDL_Quit(); return(0); }
YifuLiu/AliOS-Things
components/SDL2/src/image/unused/showimage.c
C
apache-2.0
6,226
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" /* This is the game controller API for Simple DirectMedia Layer */ #include "SDL_events.h" #include "SDL_assert.h" #include "SDL_hints.h" #include "SDL_timer.h" #include "SDL_sysjoystick.h" #include "SDL_joystick_c.h" #include "SDL_gamecontrollerdb.h" #if !SDL_EVENTS_DISABLED #include "../events/SDL_events_c.h" #endif #if defined(__ANDROID__) #include "SDL_system.h" #endif /* Many controllers turn the center button into an instantaneous button press */ #define SDL_MINIMUM_GUIDE_BUTTON_DELAY_MS 250 #define SDL_CONTROLLER_PLATFORM_FIELD "platform:" #define SDL_CONTROLLER_HINT_FIELD "hint:" #define SDL_CONTROLLER_SDKGE_FIELD "sdk>=:" #define SDL_CONTROLLER_SDKLE_FIELD "sdk<=:" /* a list of currently opened game controllers */ static SDL_GameController *SDL_gamecontrollers = NULL; typedef struct { SDL_GameControllerBindType inputType; union { int button; struct { int axis; int axis_min; int axis_max; } axis; struct { int hat; int hat_mask; } hat; } input; SDL_GameControllerBindType outputType; union { SDL_GameControllerButton button; struct { SDL_GameControllerAxis axis; int axis_min; int axis_max; } axis; } output; } SDL_ExtendedGameControllerBind; /* our hard coded list of mapping support */ typedef enum { SDL_CONTROLLER_MAPPING_PRIORITY_DEFAULT, SDL_CONTROLLER_MAPPING_PRIORITY_API, SDL_CONTROLLER_MAPPING_PRIORITY_USER, } SDL_ControllerMappingPriority; typedef struct _ControllerMapping_t { SDL_JoystickGUID guid; char *name; char *mapping; SDL_ControllerMappingPriority priority; struct _ControllerMapping_t *next; } ControllerMapping_t; static SDL_JoystickGUID s_zeroGUID; static ControllerMapping_t *s_pSupportedControllers = NULL; static ControllerMapping_t *s_pDefaultMapping = NULL; static ControllerMapping_t *s_pHIDAPIMapping = NULL; static ControllerMapping_t *s_pXInputMapping = NULL; /* The SDL game controller structure */ struct _SDL_GameController { SDL_Joystick *joystick; /* underlying joystick device */ int ref_count; const char *name; int num_bindings; SDL_ExtendedGameControllerBind *bindings; SDL_ExtendedGameControllerBind **last_match_axis; Uint8 *last_hat_mask; Uint32 guide_button_down; struct _SDL_GameController *next; /* pointer to next game controller we have allocated */ }; typedef struct { int num_entries; int max_entries; Uint32 *entries; } SDL_vidpid_list; static SDL_vidpid_list SDL_allowed_controllers; static SDL_vidpid_list SDL_ignored_controllers; static void SDL_LoadVIDPIDListFromHint(const char *hint, SDL_vidpid_list *list) { Uint32 entry; char *spot; char *file = NULL; list->num_entries = 0; if (hint && *hint == '@') { spot = file = (char *)SDL_LoadFile(hint+1, NULL); } else { spot = (char *)hint; } if (!spot) { return; } while ((spot = SDL_strstr(spot, "0x")) != NULL) { entry = (Uint16)SDL_strtol(spot, &spot, 0); entry <<= 16; spot = SDL_strstr(spot, "0x"); if (!spot) { break; } entry |= (Uint16)SDL_strtol(spot, &spot, 0); if (list->num_entries == list->max_entries) { int max_entries = list->max_entries + 16; Uint32 *entries = (Uint32 *)SDL_realloc(list->entries, max_entries*sizeof(*list->entries)); if (entries == NULL) { /* Out of memory, go with what we have already */ break; } list->entries = entries; list->max_entries = max_entries; } list->entries[list->num_entries++] = entry; } if (file) { SDL_free(file); } } static void SDLCALL SDL_GameControllerIgnoreDevicesChanged(void *userdata, const char *name, const char *oldValue, const char *hint) { SDL_LoadVIDPIDListFromHint(hint, &SDL_ignored_controllers); } static void SDLCALL SDL_GameControllerIgnoreDevicesExceptChanged(void *userdata, const char *name, const char *oldValue, const char *hint) { SDL_LoadVIDPIDListFromHint(hint, &SDL_allowed_controllers); } static int SDL_PrivateGameControllerAxis(SDL_GameController * gamecontroller, SDL_GameControllerAxis axis, Sint16 value); static int SDL_PrivateGameControllerButton(SDL_GameController * gamecontroller, SDL_GameControllerButton button, Uint8 state); /* * If there is an existing add event in the queue, it needs to be modified * to have the right value for which, because the number of controllers in * the system is now one less. */ static void UpdateEventsForDeviceRemoval() { int i, num_events; SDL_Event *events; SDL_bool isstack; num_events = SDL_PeepEvents(NULL, 0, SDL_PEEKEVENT, SDL_CONTROLLERDEVICEADDED, SDL_CONTROLLERDEVICEADDED); if (num_events <= 0) { return; } events = SDL_small_alloc(SDL_Event, num_events, &isstack); if (!events) { return; } num_events = SDL_PeepEvents(events, num_events, SDL_GETEVENT, SDL_CONTROLLERDEVICEADDED, SDL_CONTROLLERDEVICEADDED); for (i = 0; i < num_events; ++i) { --events[i].cdevice.which; } SDL_PeepEvents(events, num_events, SDL_ADDEVENT, 0, 0); SDL_small_free(events, isstack); } static SDL_bool HasSameOutput(SDL_ExtendedGameControllerBind *a, SDL_ExtendedGameControllerBind *b) { if (a->outputType != b->outputType) { return SDL_FALSE; } if (a->outputType == SDL_CONTROLLER_BINDTYPE_AXIS) { return (a->output.axis.axis == b->output.axis.axis); } else { return (a->output.button == b->output.button); } } static void ResetOutput(SDL_GameController *gamecontroller, SDL_ExtendedGameControllerBind *bind) { if (bind->outputType == SDL_CONTROLLER_BINDTYPE_AXIS) { SDL_PrivateGameControllerAxis(gamecontroller, bind->output.axis.axis, 0); } else { SDL_PrivateGameControllerButton(gamecontroller, bind->output.button, SDL_RELEASED); } } static void HandleJoystickAxis(SDL_GameController *gamecontroller, int axis, int value) { int i; SDL_ExtendedGameControllerBind *last_match = gamecontroller->last_match_axis[axis]; SDL_ExtendedGameControllerBind *match = NULL; for (i = 0; i < gamecontroller->num_bindings; ++i) { SDL_ExtendedGameControllerBind *binding = &gamecontroller->bindings[i]; if (binding->inputType == SDL_CONTROLLER_BINDTYPE_AXIS && axis == binding->input.axis.axis) { if (binding->input.axis.axis_min < binding->input.axis.axis_max) { if (value >= binding->input.axis.axis_min && value <= binding->input.axis.axis_max) { match = binding; break; } } else { if (value >= binding->input.axis.axis_max && value <= binding->input.axis.axis_min) { match = binding; break; } } } } if (last_match && (!match || !HasSameOutput(last_match, match))) { /* Clear the last input that this axis generated */ ResetOutput(gamecontroller, last_match); } if (match) { if (match->outputType == SDL_CONTROLLER_BINDTYPE_AXIS) { if (match->input.axis.axis_min != match->output.axis.axis_min || match->input.axis.axis_max != match->output.axis.axis_max) { float normalized_value = (float)(value - match->input.axis.axis_min) / (match->input.axis.axis_max - match->input.axis.axis_min); value = match->output.axis.axis_min + (int)(normalized_value * (match->output.axis.axis_max - match->output.axis.axis_min)); } SDL_PrivateGameControllerAxis(gamecontroller, match->output.axis.axis, (Sint16)value); } else { Uint8 state; int threshold = match->input.axis.axis_min + (match->input.axis.axis_max - match->input.axis.axis_min) / 2; if (match->input.axis.axis_max < match->input.axis.axis_min) { state = (value <= threshold) ? SDL_PRESSED : SDL_RELEASED; } else { state = (value >= threshold) ? SDL_PRESSED : SDL_RELEASED; } SDL_PrivateGameControllerButton(gamecontroller, match->output.button, state); } } gamecontroller->last_match_axis[axis] = match; } static void HandleJoystickButton(SDL_GameController *gamecontroller, int button, Uint8 state) { int i; for (i = 0; i < gamecontroller->num_bindings; ++i) { SDL_ExtendedGameControllerBind *binding = &gamecontroller->bindings[i]; if (binding->inputType == SDL_CONTROLLER_BINDTYPE_BUTTON && button == binding->input.button) { if (binding->outputType == SDL_CONTROLLER_BINDTYPE_AXIS) { int value = state ? binding->output.axis.axis_max : binding->output.axis.axis_min; SDL_PrivateGameControllerAxis(gamecontroller, binding->output.axis.axis, (Sint16)value); } else { SDL_PrivateGameControllerButton(gamecontroller, binding->output.button, state); } break; } } } static void HandleJoystickHat(SDL_GameController *gamecontroller, int hat, Uint8 value) { int i; Uint8 last_mask = gamecontroller->last_hat_mask[hat]; Uint8 changed_mask = (last_mask ^ value); for (i = 0; i < gamecontroller->num_bindings; ++i) { SDL_ExtendedGameControllerBind *binding = &gamecontroller->bindings[i]; if (binding->inputType == SDL_CONTROLLER_BINDTYPE_HAT && hat == binding->input.hat.hat) { if ((changed_mask & binding->input.hat.hat_mask) != 0) { if (value & binding->input.hat.hat_mask) { if (binding->outputType == SDL_CONTROLLER_BINDTYPE_AXIS) { SDL_PrivateGameControllerAxis(gamecontroller, binding->output.axis.axis, (Sint16)binding->output.axis.axis_max); } else { SDL_PrivateGameControllerButton(gamecontroller, binding->output.button, SDL_PRESSED); } } else { ResetOutput(gamecontroller, binding); } } } } gamecontroller->last_hat_mask[hat] = value; } /* The joystick layer will _also_ send events to recenter before disconnect, but it has to make (sometimes incorrect) guesses at what being "centered" is. The game controller layer, however, can set a definite logical idle position, so set them all here. If we happened to already be at the center thanks to the joystick layer or idle hands, this won't generate duplicate events. */ static void RecenterGameController(SDL_GameController *gamecontroller) { SDL_GameControllerButton button; SDL_GameControllerAxis axis; for (button = (SDL_GameControllerButton) 0; button < SDL_CONTROLLER_BUTTON_MAX; button++) { if (SDL_GameControllerGetButton(gamecontroller, button)) { SDL_PrivateGameControllerButton(gamecontroller, button, SDL_RELEASED); } } for (axis = (SDL_GameControllerAxis) 0; axis < SDL_CONTROLLER_AXIS_MAX; axis++) { if (SDL_GameControllerGetAxis(gamecontroller, axis) != 0) { SDL_PrivateGameControllerAxis(gamecontroller, axis, 0); } } } /* * Event filter to fire controller events from joystick ones */ static int SDLCALL SDL_GameControllerEventWatcher(void *userdata, SDL_Event * event) { switch(event->type) { case SDL_JOYAXISMOTION: { SDL_GameController *controllerlist = SDL_gamecontrollers; while (controllerlist) { if (controllerlist->joystick->instance_id == event->jaxis.which) { HandleJoystickAxis(controllerlist, event->jaxis.axis, event->jaxis.value); break; } controllerlist = controllerlist->next; } } break; case SDL_JOYBUTTONDOWN: case SDL_JOYBUTTONUP: { SDL_GameController *controllerlist = SDL_gamecontrollers; while (controllerlist) { if (controllerlist->joystick->instance_id == event->jbutton.which) { HandleJoystickButton(controllerlist, event->jbutton.button, event->jbutton.state); break; } controllerlist = controllerlist->next; } } break; case SDL_JOYHATMOTION: { SDL_GameController *controllerlist = SDL_gamecontrollers; while (controllerlist) { if (controllerlist->joystick->instance_id == event->jhat.which) { HandleJoystickHat(controllerlist, event->jhat.hat, event->jhat.value); break; } controllerlist = controllerlist->next; } } break; case SDL_JOYDEVICEADDED: { if (SDL_IsGameController(event->jdevice.which)) { SDL_Event deviceevent; deviceevent.type = SDL_CONTROLLERDEVICEADDED; deviceevent.cdevice.which = event->jdevice.which; SDL_PushEvent(&deviceevent); } } break; case SDL_JOYDEVICEREMOVED: { SDL_GameController *controllerlist = SDL_gamecontrollers; while (controllerlist) { if (controllerlist->joystick->instance_id == event->jdevice.which) { SDL_Event deviceevent; RecenterGameController(controllerlist); deviceevent.type = SDL_CONTROLLERDEVICEREMOVED; deviceevent.cdevice.which = event->jdevice.which; SDL_PushEvent(&deviceevent); UpdateEventsForDeviceRemoval(); break; } controllerlist = controllerlist->next; } } break; default: break; } return 1; } /* * Helper function to scan the mappings database for a controller with the specified GUID */ static ControllerMapping_t *SDL_PrivateGetControllerMappingForGUID(SDL_JoystickGUID *guid, SDL_bool exact_match) { ControllerMapping_t *pSupportedController = s_pSupportedControllers; while (pSupportedController) { if (SDL_memcmp(guid, &pSupportedController->guid, sizeof(*guid)) == 0) { return pSupportedController; } pSupportedController = pSupportedController->next; } if (!exact_match) { if (SDL_IsJoystickHIDAPI(*guid)) { /* This is a HIDAPI device */ return s_pHIDAPIMapping; } #if SDL_JOYSTICK_RAWINPUT if (SDL_IsJoystickRAWINPUT(*guid)) { /* This is a RAWINPUT device - same data as HIDAPI */ return s_pHIDAPIMapping; } #endif #if SDL_JOYSTICK_XINPUT if (SDL_IsJoystickXInput(*guid)) { /* This is an XInput device */ return s_pXInputMapping; } #endif } return NULL; } static const char* map_StringForControllerAxis[] = { "leftx", "lefty", "rightx", "righty", "lefttrigger", "righttrigger", NULL }; /* * convert a string to its enum equivalent */ SDL_GameControllerAxis SDL_GameControllerGetAxisFromString(const char *pchString) { int entry; if (pchString && (*pchString == '+' || *pchString == '-')) { ++pchString; } if (!pchString || !pchString[0]) { return SDL_CONTROLLER_AXIS_INVALID; } for (entry = 0; map_StringForControllerAxis[entry]; ++entry) { if (!SDL_strcasecmp(pchString, map_StringForControllerAxis[entry])) return (SDL_GameControllerAxis) entry; } return SDL_CONTROLLER_AXIS_INVALID; } /* * convert an enum to its string equivalent */ const char* SDL_GameControllerGetStringForAxis(SDL_GameControllerAxis axis) { if (axis > SDL_CONTROLLER_AXIS_INVALID && axis < SDL_CONTROLLER_AXIS_MAX) { return map_StringForControllerAxis[axis]; } return NULL; } static const char* map_StringForControllerButton[] = { "a", "b", "x", "y", "back", "guide", "start", "leftstick", "rightstick", "leftshoulder", "rightshoulder", "dpup", "dpdown", "dpleft", "dpright", NULL }; /* * convert a string to its enum equivalent */ SDL_GameControllerButton SDL_GameControllerGetButtonFromString(const char *pchString) { int entry; if (!pchString || !pchString[0]) return SDL_CONTROLLER_BUTTON_INVALID; for (entry = 0; map_StringForControllerButton[entry]; ++entry) { if (SDL_strcasecmp(pchString, map_StringForControllerButton[entry]) == 0) return (SDL_GameControllerButton) entry; } return SDL_CONTROLLER_BUTTON_INVALID; } /* * convert an enum to its string equivalent */ const char* SDL_GameControllerGetStringForButton(SDL_GameControllerButton axis) { if (axis > SDL_CONTROLLER_BUTTON_INVALID && axis < SDL_CONTROLLER_BUTTON_MAX) { return map_StringForControllerButton[axis]; } return NULL; } /* * given a controller button name and a joystick name update our mapping structure with it */ static void SDL_PrivateGameControllerParseElement(SDL_GameController *gamecontroller, const char *szGameButton, const char *szJoystickButton) { SDL_ExtendedGameControllerBind bind; SDL_GameControllerButton button; SDL_GameControllerAxis axis; SDL_bool invert_input = SDL_FALSE; char half_axis_input = 0; char half_axis_output = 0; if (*szGameButton == '+' || *szGameButton == '-') { half_axis_output = *szGameButton++; } axis = SDL_GameControllerGetAxisFromString(szGameButton); button = SDL_GameControllerGetButtonFromString(szGameButton); if (axis != SDL_CONTROLLER_AXIS_INVALID) { bind.outputType = SDL_CONTROLLER_BINDTYPE_AXIS; bind.output.axis.axis = axis; if (axis == SDL_CONTROLLER_AXIS_TRIGGERLEFT || axis == SDL_CONTROLLER_AXIS_TRIGGERRIGHT) { bind.output.axis.axis_min = 0; bind.output.axis.axis_max = SDL_JOYSTICK_AXIS_MAX; } else { if (half_axis_output == '+') { bind.output.axis.axis_min = 0; bind.output.axis.axis_max = SDL_JOYSTICK_AXIS_MAX; } else if (half_axis_output == '-') { bind.output.axis.axis_min = 0; bind.output.axis.axis_max = SDL_JOYSTICK_AXIS_MIN; } else { bind.output.axis.axis_min = SDL_JOYSTICK_AXIS_MIN; bind.output.axis.axis_max = SDL_JOYSTICK_AXIS_MAX; } } } else if (button != SDL_CONTROLLER_BUTTON_INVALID) { bind.outputType = SDL_CONTROLLER_BINDTYPE_BUTTON; bind.output.button = button; } else { SDL_SetError("Unexpected controller element %s", szGameButton); return; } if (*szJoystickButton == '+' || *szJoystickButton == '-') { half_axis_input = *szJoystickButton++; } if (szJoystickButton[SDL_strlen(szJoystickButton) - 1] == '~') { invert_input = SDL_TRUE; } if (szJoystickButton[0] == 'a' && SDL_isdigit(szJoystickButton[1])) { bind.inputType = SDL_CONTROLLER_BINDTYPE_AXIS; bind.input.axis.axis = SDL_atoi(&szJoystickButton[1]); if (half_axis_input == '+') { bind.input.axis.axis_min = 0; bind.input.axis.axis_max = SDL_JOYSTICK_AXIS_MAX; } else if (half_axis_input == '-') { bind.input.axis.axis_min = 0; bind.input.axis.axis_max = SDL_JOYSTICK_AXIS_MIN; } else { bind.input.axis.axis_min = SDL_JOYSTICK_AXIS_MIN; bind.input.axis.axis_max = SDL_JOYSTICK_AXIS_MAX; } if (invert_input) { int tmp = bind.input.axis.axis_min; bind.input.axis.axis_min = bind.input.axis.axis_max; bind.input.axis.axis_max = tmp; } } else if (szJoystickButton[0] == 'b' && SDL_isdigit(szJoystickButton[1])) { bind.inputType = SDL_CONTROLLER_BINDTYPE_BUTTON; bind.input.button = SDL_atoi(&szJoystickButton[1]); } else if (szJoystickButton[0] == 'h' && SDL_isdigit(szJoystickButton[1]) && szJoystickButton[2] == '.' && SDL_isdigit(szJoystickButton[3])) { int hat = SDL_atoi(&szJoystickButton[1]); int mask = SDL_atoi(&szJoystickButton[3]); bind.inputType = SDL_CONTROLLER_BINDTYPE_HAT; bind.input.hat.hat = hat; bind.input.hat.hat_mask = mask; } else { SDL_SetError("Unexpected joystick element: %s", szJoystickButton); return; } ++gamecontroller->num_bindings; gamecontroller->bindings = (SDL_ExtendedGameControllerBind *)SDL_realloc(gamecontroller->bindings, gamecontroller->num_bindings * sizeof(*gamecontroller->bindings)); if (!gamecontroller->bindings) { gamecontroller->num_bindings = 0; SDL_OutOfMemory(); return; } gamecontroller->bindings[gamecontroller->num_bindings - 1] = bind; } /* * given a controller mapping string update our mapping object */ static void SDL_PrivateGameControllerParseControllerConfigString(SDL_GameController *gamecontroller, const char *pchString) { char szGameButton[20]; char szJoystickButton[20]; SDL_bool bGameButton = SDL_TRUE; int i = 0; const char *pchPos = pchString; SDL_zeroa(szGameButton); SDL_zeroa(szJoystickButton); while (pchPos && *pchPos) { if (*pchPos == ':') { i = 0; bGameButton = SDL_FALSE; } else if (*pchPos == ' ') { } else if (*pchPos == ',') { i = 0; bGameButton = SDL_TRUE; SDL_PrivateGameControllerParseElement(gamecontroller, szGameButton, szJoystickButton); SDL_zeroa(szGameButton); SDL_zeroa(szJoystickButton); } else if (bGameButton) { if (i >= sizeof(szGameButton)) { SDL_SetError("Button name too large: %s", szGameButton); return; } szGameButton[i] = *pchPos; i++; } else { if (i >= sizeof(szJoystickButton)) { SDL_SetError("Joystick button name too large: %s", szJoystickButton); return; } szJoystickButton[i] = *pchPos; i++; } pchPos++; } /* No more values if the string was terminated by a comma. Don't report an error. */ if (szGameButton[0] != '\0' || szJoystickButton[0] != '\0') { SDL_PrivateGameControllerParseElement(gamecontroller, szGameButton, szJoystickButton); } } /* * Make a new button mapping struct */ static void SDL_PrivateLoadButtonMapping(SDL_GameController *gamecontroller, const char *pchName, const char *pchMapping) { int i; gamecontroller->name = pchName; gamecontroller->num_bindings = 0; if (gamecontroller->joystick->naxes) { SDL_memset(gamecontroller->last_match_axis, 0, gamecontroller->joystick->naxes * sizeof(*gamecontroller->last_match_axis)); } SDL_PrivateGameControllerParseControllerConfigString(gamecontroller, pchMapping); /* Set the zero point for triggers */ for (i = 0; i < gamecontroller->num_bindings; ++i) { SDL_ExtendedGameControllerBind *binding = &gamecontroller->bindings[i]; if (binding->inputType == SDL_CONTROLLER_BINDTYPE_AXIS && binding->outputType == SDL_CONTROLLER_BINDTYPE_AXIS && (binding->output.axis.axis == SDL_CONTROLLER_AXIS_TRIGGERLEFT || binding->output.axis.axis == SDL_CONTROLLER_AXIS_TRIGGERRIGHT)) { if (binding->input.axis.axis < gamecontroller->joystick->naxes) { gamecontroller->joystick->axes[binding->input.axis.axis].value = gamecontroller->joystick->axes[binding->input.axis.axis].zero = (Sint16)binding->input.axis.axis_min; } } } } /* * grab the guid string from a mapping string */ static char *SDL_PrivateGetControllerGUIDFromMappingString(const char *pMapping) { const char *pFirstComma = SDL_strchr(pMapping, ','); if (pFirstComma) { char *pchGUID = SDL_malloc(pFirstComma - pMapping + 1); if (!pchGUID) { SDL_OutOfMemory(); return NULL; } SDL_memcpy(pchGUID, pMapping, pFirstComma - pMapping); pchGUID[pFirstComma - pMapping] = '\0'; /* Convert old style GUIDs to the new style in 2.0.5 */ #if __WIN32__ if (SDL_strlen(pchGUID) == 32 && SDL_memcmp(&pchGUID[20], "504944564944", 12) == 0) { SDL_memcpy(&pchGUID[20], "000000000000", 12); SDL_memcpy(&pchGUID[16], &pchGUID[4], 4); SDL_memcpy(&pchGUID[8], &pchGUID[0], 4); SDL_memcpy(&pchGUID[0], "03000000", 8); } #elif __MACOSX__ if (SDL_strlen(pchGUID) == 32 && SDL_memcmp(&pchGUID[4], "000000000000", 12) == 0 && SDL_memcmp(&pchGUID[20], "000000000000", 12) == 0) { SDL_memcpy(&pchGUID[20], "000000000000", 12); SDL_memcpy(&pchGUID[8], &pchGUID[0], 4); SDL_memcpy(&pchGUID[0], "03000000", 8); } #endif return pchGUID; } return NULL; } /* * grab the name string from a mapping string */ static char *SDL_PrivateGetControllerNameFromMappingString(const char *pMapping) { const char *pFirstComma, *pSecondComma; char *pchName; pFirstComma = SDL_strchr(pMapping, ','); if (!pFirstComma) return NULL; pSecondComma = SDL_strchr(pFirstComma + 1, ','); if (!pSecondComma) return NULL; pchName = SDL_malloc(pSecondComma - pFirstComma); if (!pchName) { SDL_OutOfMemory(); return NULL; } SDL_memcpy(pchName, pFirstComma + 1, pSecondComma - pFirstComma); pchName[pSecondComma - pFirstComma - 1] = 0; return pchName; } /* * grab the button mapping string from a mapping string */ static char *SDL_PrivateGetControllerMappingFromMappingString(const char *pMapping) { const char *pFirstComma, *pSecondComma; pFirstComma = SDL_strchr(pMapping, ','); if (!pFirstComma) return NULL; pSecondComma = SDL_strchr(pFirstComma + 1, ','); if (!pSecondComma) return NULL; return SDL_strdup(pSecondComma + 1); /* mapping is everything after the 3rd comma */ } /* * Helper function to refresh a mapping */ static void SDL_PrivateGameControllerRefreshMapping(ControllerMapping_t *pControllerMapping) { SDL_GameController *gamecontrollerlist = SDL_gamecontrollers; while (gamecontrollerlist) { if (!SDL_memcmp(&gamecontrollerlist->joystick->guid, &pControllerMapping->guid, sizeof(pControllerMapping->guid))) { /* Not really threadsafe. Should this lock access within SDL_GameControllerEventWatcher? */ SDL_PrivateLoadButtonMapping(gamecontrollerlist, pControllerMapping->name, pControllerMapping->mapping); { SDL_Event event; event.type = SDL_CONTROLLERDEVICEREMAPPED; event.cdevice.which = gamecontrollerlist->joystick->instance_id; SDL_PushEvent(&event); } } gamecontrollerlist = gamecontrollerlist->next; } } /* * Helper function to add a mapping for a guid */ static ControllerMapping_t * SDL_PrivateAddMappingForGUID(SDL_JoystickGUID jGUID, const char *mappingString, SDL_bool *existing, SDL_ControllerMappingPriority priority) { char *pchName; char *pchMapping; ControllerMapping_t *pControllerMapping; pchName = SDL_PrivateGetControllerNameFromMappingString(mappingString); if (!pchName) { SDL_SetError("Couldn't parse name from %s", mappingString); return NULL; } pchMapping = SDL_PrivateGetControllerMappingFromMappingString(mappingString); if (!pchMapping) { SDL_free(pchName); SDL_SetError("Couldn't parse %s", mappingString); return NULL; } pControllerMapping = SDL_PrivateGetControllerMappingForGUID(&jGUID, SDL_TRUE); if (pControllerMapping) { /* Only overwrite the mapping if the priority is the same or higher. */ if (pControllerMapping->priority <= priority) { /* Update existing mapping */ SDL_free(pControllerMapping->name); pControllerMapping->name = pchName; SDL_free(pControllerMapping->mapping); pControllerMapping->mapping = pchMapping; pControllerMapping->priority = priority; /* refresh open controllers */ SDL_PrivateGameControllerRefreshMapping(pControllerMapping); } else { SDL_free(pchName); SDL_free(pchMapping); } *existing = SDL_TRUE; } else { pControllerMapping = SDL_malloc(sizeof(*pControllerMapping)); if (!pControllerMapping) { SDL_free(pchName); SDL_free(pchMapping); SDL_OutOfMemory(); return NULL; } pControllerMapping->guid = jGUID; pControllerMapping->name = pchName; pControllerMapping->mapping = pchMapping; pControllerMapping->next = NULL; pControllerMapping->priority = priority; if (s_pSupportedControllers) { /* Add the mapping to the end of the list */ ControllerMapping_t *pCurrMapping, *pPrevMapping; for ( pPrevMapping = s_pSupportedControllers, pCurrMapping = pPrevMapping->next; pCurrMapping; pPrevMapping = pCurrMapping, pCurrMapping = pCurrMapping->next ) { /* continue; */ } pPrevMapping->next = pControllerMapping; } else { s_pSupportedControllers = pControllerMapping; } *existing = SDL_FALSE; } return pControllerMapping; } #ifdef __ANDROID__ /* * Helper function to guess at a mapping based on the elements reported for this controller */ static ControllerMapping_t *SDL_CreateMappingForAndroidController(const char *name, SDL_JoystickGUID guid) { SDL_bool existing; char name_string[128]; char mapping_string[1024]; int button_mask; int axis_mask; button_mask = SDL_SwapLE16(*(Uint16*)(&guid.data[sizeof(guid.data)-4])); axis_mask = SDL_SwapLE16(*(Uint16*)(&guid.data[sizeof(guid.data)-2])); if (!button_mask && !axis_mask) { /* Accelerometer, shouldn't have a game controller mapping */ return NULL; } /* Remove any commas in the name */ SDL_strlcpy(name_string, name, sizeof(name_string)); { char *spot; for (spot = name_string; *spot; ++spot) { if (*spot == ',') { *spot = ' '; } } } SDL_snprintf(mapping_string, sizeof(mapping_string), "none,%s,", name_string); if (button_mask & (1 << SDL_CONTROLLER_BUTTON_A)) { SDL_strlcat(mapping_string, "a:b0,", sizeof(mapping_string)); } if (button_mask & (1 << SDL_CONTROLLER_BUTTON_B)) { SDL_strlcat(mapping_string, "b:b1,", sizeof(mapping_string)); } else if (button_mask & (1 << SDL_CONTROLLER_BUTTON_BACK)) { /* Use the back button as "B" for easy UI navigation with TV remotes */ SDL_strlcat(mapping_string, "b:b4,", sizeof(mapping_string)); button_mask &= ~(1 << SDL_CONTROLLER_BUTTON_BACK); } if (button_mask & (1 << SDL_CONTROLLER_BUTTON_X)) { SDL_strlcat(mapping_string, "x:b2,", sizeof(mapping_string)); } if (button_mask & (1 << SDL_CONTROLLER_BUTTON_Y)) { SDL_strlcat(mapping_string, "y:b3,", sizeof(mapping_string)); } if (button_mask & (1 << SDL_CONTROLLER_BUTTON_BACK)) { SDL_strlcat(mapping_string, "back:b4,", sizeof(mapping_string)); } #if 0 /* The guide button generally isn't functional (or acts as a home button) on most Android controllers */ if (button_mask & (1 << SDL_CONTROLLER_BUTTON_GUIDE)) { SDL_strlcat(mapping_string, "guide:b5,", sizeof(mapping_string)); #if 0 /* Actually this will be done in Steam */ } else if (button_mask & (1 << SDL_CONTROLLER_BUTTON_START)) { /* The guide button doesn't exist, use the start button instead, so you can do Steam guide button chords and open the Steam overlay. */ SDL_strlcat(mapping_string, "guide:b6,", sizeof(mapping_string)); button_mask &= ~(1 << SDL_CONTROLLER_BUTTON_START); #endif } #endif if (button_mask & (1 << SDL_CONTROLLER_BUTTON_START)) { SDL_strlcat(mapping_string, "start:b6,", sizeof(mapping_string)); } if (button_mask & (1 << SDL_CONTROLLER_BUTTON_LEFTSTICK)) { SDL_strlcat(mapping_string, "leftstick:b7,", sizeof(mapping_string)); } if (button_mask & (1 << SDL_CONTROLLER_BUTTON_RIGHTSTICK)) { SDL_strlcat(mapping_string, "rightstick:b8,", sizeof(mapping_string)); } if (button_mask & (1 << SDL_CONTROLLER_BUTTON_LEFTSHOULDER)) { SDL_strlcat(mapping_string, "leftshoulder:b9,", sizeof(mapping_string)); } if (button_mask & (1 << SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)) { SDL_strlcat(mapping_string, "rightshoulder:b10,", sizeof(mapping_string)); } if (button_mask & (1 << SDL_CONTROLLER_BUTTON_DPAD_UP)) { SDL_strlcat(mapping_string, "dpup:b11,", sizeof(mapping_string)); } if (button_mask & (1 << SDL_CONTROLLER_BUTTON_DPAD_DOWN)) { SDL_strlcat(mapping_string, "dpdown:b12,", sizeof(mapping_string)); } if (button_mask & (1 << SDL_CONTROLLER_BUTTON_DPAD_LEFT)) { SDL_strlcat(mapping_string, "dpleft:b13,", sizeof(mapping_string)); } if (button_mask & (1 << SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) { SDL_strlcat(mapping_string, "dpright:b14,", sizeof(mapping_string)); } if (axis_mask & (1 << SDL_CONTROLLER_AXIS_LEFTX)) { SDL_strlcat(mapping_string, "leftx:a0,", sizeof(mapping_string)); } if (axis_mask & (1 << SDL_CONTROLLER_AXIS_LEFTY)) { SDL_strlcat(mapping_string, "lefty:a1,", sizeof(mapping_string)); } if (axis_mask & (1 << SDL_CONTROLLER_AXIS_RIGHTX)) { SDL_strlcat(mapping_string, "rightx:a2,", sizeof(mapping_string)); } if (axis_mask & (1 << SDL_CONTROLLER_AXIS_RIGHTY)) { SDL_strlcat(mapping_string, "righty:a3,", sizeof(mapping_string)); } if (axis_mask & (1 << SDL_CONTROLLER_AXIS_TRIGGERLEFT)) { SDL_strlcat(mapping_string, "lefttrigger:a4,", sizeof(mapping_string)); } if (axis_mask & (1 << SDL_CONTROLLER_AXIS_TRIGGERRIGHT)) { SDL_strlcat(mapping_string, "righttrigger:a5,", sizeof(mapping_string)); } /* Remove trailing comma */ { int pos = (int)SDL_strlen(mapping_string) - 1; if (pos >= 0) { if (mapping_string[pos] == ',') { mapping_string[pos] = '\0'; } } } return SDL_PrivateAddMappingForGUID(guid, mapping_string, &existing, SDL_CONTROLLER_MAPPING_PRIORITY_DEFAULT); } #endif /* __ANDROID__ */ /* * Helper function to determine pre-calculated offset to certain joystick mappings */ static ControllerMapping_t *SDL_PrivateGetControllerMappingForNameAndGUID(const char *name, SDL_JoystickGUID guid) { ControllerMapping_t *mapping; mapping = SDL_PrivateGetControllerMappingForGUID(&guid, SDL_FALSE); #ifdef __LINUX__ if (!mapping && name) { if (SDL_strstr(name, "Xbox 360 Wireless Receiver")) { /* The Linux driver xpad.c maps the wireless dpad to buttons */ SDL_bool existing; mapping = SDL_PrivateAddMappingForGUID(guid, "none,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3", &existing, SDL_CONTROLLER_MAPPING_PRIORITY_DEFAULT); } } #endif /* __LINUX__ */ if (!mapping && name && !SDL_IsJoystickWGI(guid)) { if (SDL_strstr(name, "Xbox") || SDL_strstr(name, "X-Box") || SDL_strstr(name, "XBOX")) { mapping = s_pXInputMapping; } } #ifdef __ANDROID__ if (!mapping && name && !SDL_IsJoystickHIDAPI(guid)) { mapping = SDL_CreateMappingForAndroidController(name, guid); } #endif if (!mapping) { mapping = s_pDefaultMapping; } return mapping; } static void SDL_PrivateAppendToMappingString(char *mapping_string, size_t mapping_string_len, const char *input_name, SDL_InputMapping *mapping) { char buffer[16]; if (mapping->kind == EMappingKind_None) { return; } SDL_strlcat(mapping_string, input_name, mapping_string_len); SDL_strlcat(mapping_string, ":", mapping_string_len); switch (mapping->kind) { case EMappingKind_Button: SDL_snprintf(buffer, sizeof(buffer), "b%i", mapping->target); break; case EMappingKind_Axis: SDL_snprintf(buffer, sizeof(buffer), "a%i", mapping->target); break; case EMappingKind_Hat: SDL_snprintf(buffer, sizeof(buffer), "h%i.%i", mapping->target >> 4, mapping->target & 0x0F); break; default: SDL_assert(SDL_FALSE); } SDL_strlcat(mapping_string, buffer, mapping_string_len); SDL_strlcat(mapping_string, ",", mapping_string_len); } static ControllerMapping_t *SDL_PrivateGenerateAutomaticControllerMapping(const char *name, SDL_JoystickGUID guid, SDL_GamepadMapping *raw_map) { SDL_bool existing; char name_string[128]; char mapping[1024]; /* Remove any commas in the name */ SDL_strlcpy(name_string, name, sizeof(name_string)); { char *spot; for (spot = name_string; *spot; ++spot) { if (*spot == ',') { *spot = ' '; } } } SDL_snprintf(mapping, sizeof(mapping), "none,%s,", name_string); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "a", &raw_map->a); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "b", &raw_map->b); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "x", &raw_map->x); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "y", &raw_map->y); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "back", &raw_map->back); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "guide", &raw_map->guide); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "start", &raw_map->start); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "leftstick", &raw_map->leftstick); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "rightstick", &raw_map->rightstick); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "leftshoulder", &raw_map->leftshoulder); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "rightshoulder", &raw_map->rightshoulder); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "dpup", &raw_map->dpup); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "dpdown", &raw_map->dpdown); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "dpleft", &raw_map->dpleft); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "dpright", &raw_map->dpright); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "leftx", &raw_map->leftx); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "lefty", &raw_map->lefty); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "rightx", &raw_map->rightx); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "righty", &raw_map->righty); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "lefttrigger", &raw_map->lefttrigger); SDL_PrivateAppendToMappingString(mapping, sizeof(mapping), "righttrigger", &raw_map->righttrigger); /* Remove trailing comma */ { int pos = (int)SDL_strlen(mapping) - 1; if (pos >= 0) { if (mapping[pos] == ',') { mapping[pos] = '\0'; } } } return SDL_PrivateAddMappingForGUID(guid, mapping, &existing, SDL_CONTROLLER_MAPPING_PRIORITY_DEFAULT); } static ControllerMapping_t *SDL_PrivateGetControllerMapping(int device_index) { const char *name; SDL_JoystickGUID guid; ControllerMapping_t *mapping; SDL_LockJoysticks(); if ((device_index < 0) || (device_index >= SDL_NumJoysticks())) { SDL_SetError("There are %d joysticks available", SDL_NumJoysticks()); SDL_UnlockJoysticks(); return (NULL); } name = SDL_JoystickNameForIndex(device_index); guid = SDL_JoystickGetDeviceGUID(device_index); mapping = SDL_PrivateGetControllerMappingForNameAndGUID(name, guid); if (!mapping) { SDL_GamepadMapping raw_map; SDL_zero(raw_map); if (SDL_PrivateJoystickGetAutoGamepadMapping(device_index, &raw_map)) { mapping = SDL_PrivateGenerateAutomaticControllerMapping(name, guid, &raw_map); } } SDL_UnlockJoysticks(); return mapping; } /* * Add or update an entry into the Mappings Database */ int SDL_GameControllerAddMappingsFromRW(SDL_RWops * rw, int freerw) { const char *platform = SDL_GetPlatform(); int controllers = 0; char *buf, *line, *line_end, *tmp, *comma, line_platform[64]; size_t db_size, platform_len; if (rw == NULL) { return SDL_SetError("Invalid RWops"); } db_size = (size_t)SDL_RWsize(rw); buf = (char *)SDL_malloc(db_size + 1); if (buf == NULL) { if (freerw) { SDL_RWclose(rw); } return SDL_SetError("Could not allocate space to read DB into memory"); } if (SDL_RWread(rw, buf, db_size, 1) != 1) { if (freerw) { SDL_RWclose(rw); } SDL_free(buf); return SDL_SetError("Could not read DB"); } if (freerw) { SDL_RWclose(rw); } buf[db_size] = '\0'; line = buf; while (line < buf + db_size) { line_end = SDL_strchr(line, '\n'); if (line_end != NULL) { *line_end = '\0'; } else { line_end = buf + db_size; } /* Extract and verify the platform */ tmp = SDL_strstr(line, SDL_CONTROLLER_PLATFORM_FIELD); if (tmp != NULL) { tmp += SDL_strlen(SDL_CONTROLLER_PLATFORM_FIELD); comma = SDL_strchr(tmp, ','); if (comma != NULL) { platform_len = comma - tmp + 1; if (platform_len + 1 < SDL_arraysize(line_platform)) { SDL_strlcpy(line_platform, tmp, platform_len); if (SDL_strncasecmp(line_platform, platform, platform_len) == 0 && SDL_GameControllerAddMapping(line) > 0) { controllers++; } } } } line = line_end + 1; } SDL_free(buf); return controllers; } /* * Add or update an entry into the Mappings Database with a priority */ static int SDL_PrivateGameControllerAddMapping(const char *mappingString, SDL_ControllerMappingPriority priority) { char *pchGUID; SDL_JoystickGUID jGUID; SDL_bool is_default_mapping = SDL_FALSE; SDL_bool is_hidapi_mapping = SDL_FALSE; SDL_bool is_xinput_mapping = SDL_FALSE; SDL_bool existing = SDL_FALSE; ControllerMapping_t *pControllerMapping; if (!mappingString) { return SDL_InvalidParamError("mappingString"); } { /* Extract and verify the hint field */ const char *tmp; tmp = SDL_strstr(mappingString, SDL_CONTROLLER_HINT_FIELD); if (tmp != NULL) { SDL_bool default_value, value, negate; int len; char hint[128]; tmp += SDL_strlen(SDL_CONTROLLER_HINT_FIELD); if (*tmp == '!') { negate = SDL_TRUE; ++tmp; } else { negate = SDL_FALSE; } len = 0; while (*tmp && *tmp != ',' && *tmp != ':' && len < (sizeof(hint) - 1)) { hint[len++] = *tmp++; } hint[len] = '\0'; if (tmp[0] == ':' && tmp[1] == '=') { tmp += 2; default_value = SDL_atoi(tmp); } else { default_value = SDL_FALSE; } value = SDL_GetHintBoolean(hint, default_value); if (negate) { value = !value; } if (!value) { return 0; } } } #ifdef ANDROID { /* Extract and verify the SDK version */ const char *tmp; tmp = SDL_strstr(mappingString, SDL_CONTROLLER_SDKGE_FIELD); if (tmp != NULL) { tmp += SDL_strlen(SDL_CONTROLLER_SDKGE_FIELD); if (!(SDL_GetAndroidSDKVersion() >= SDL_atoi(tmp))) { return SDL_SetError("SDK version %d < minimum version %d", SDL_GetAndroidSDKVersion(), SDL_atoi(tmp)); } } tmp = SDL_strstr(mappingString, SDL_CONTROLLER_SDKLE_FIELD); if (tmp != NULL) { tmp += SDL_strlen(SDL_CONTROLLER_SDKLE_FIELD); if (!(SDL_GetAndroidSDKVersion() <= SDL_atoi(tmp))) { return SDL_SetError("SDK version %d > maximum version %d", SDL_GetAndroidSDKVersion(), SDL_atoi(tmp)); } } } #endif pchGUID = SDL_PrivateGetControllerGUIDFromMappingString(mappingString); if (!pchGUID) { return SDL_SetError("Couldn't parse GUID from %s", mappingString); } if (!SDL_strcasecmp(pchGUID, "default")) { is_default_mapping = SDL_TRUE; } else if (!SDL_strcasecmp(pchGUID, "hidapi")) { is_hidapi_mapping = SDL_TRUE; } else if (!SDL_strcasecmp(pchGUID, "xinput")) { is_xinput_mapping = SDL_TRUE; } jGUID = SDL_JoystickGetGUIDFromString(pchGUID); SDL_free(pchGUID); pControllerMapping = SDL_PrivateAddMappingForGUID(jGUID, mappingString, &existing, priority); if (!pControllerMapping) { return -1; } if (existing) { return 0; } else { if (is_default_mapping) { s_pDefaultMapping = pControllerMapping; } else if (is_hidapi_mapping) { s_pHIDAPIMapping = pControllerMapping; } else if (is_xinput_mapping) { s_pXInputMapping = pControllerMapping; } return 1; } } /* * Add or update an entry into the Mappings Database */ int SDL_GameControllerAddMapping(const char *mappingString) { return SDL_PrivateGameControllerAddMapping(mappingString, SDL_CONTROLLER_MAPPING_PRIORITY_API); } /* * Get the number of mappings installed */ int SDL_GameControllerNumMappings(void) { int num_mappings = 0; ControllerMapping_t *mapping; for (mapping = s_pSupportedControllers; mapping; mapping = mapping->next) { if (SDL_memcmp(&mapping->guid, &s_zeroGUID, sizeof(mapping->guid)) == 0) { continue; } ++num_mappings; } return num_mappings; } /* * Get the mapping at a particular index. */ char * SDL_GameControllerMappingForIndex(int mapping_index) { ControllerMapping_t *mapping; for (mapping = s_pSupportedControllers; mapping; mapping = mapping->next) { if (SDL_memcmp(&mapping->guid, &s_zeroGUID, sizeof(mapping->guid)) == 0) { continue; } if (mapping_index == 0) { char *pMappingString; char pchGUID[33]; size_t needed; SDL_JoystickGetGUIDString(mapping->guid, pchGUID, sizeof(pchGUID)); /* allocate enough memory for GUID + ',' + name + ',' + mapping + \0 */ needed = SDL_strlen(pchGUID) + 1 + SDL_strlen(mapping->name) + 1 + SDL_strlen(mapping->mapping) + 1; pMappingString = SDL_malloc(needed); if (!pMappingString) { SDL_OutOfMemory(); return NULL; } SDL_snprintf(pMappingString, needed, "%s,%s,%s", pchGUID, mapping->name, mapping->mapping); return pMappingString; } --mapping_index; } return NULL; } /* * Get the mapping string for this GUID */ char * SDL_GameControllerMappingForGUID(SDL_JoystickGUID guid) { char *pMappingString = NULL; ControllerMapping_t *mapping = SDL_PrivateGetControllerMappingForGUID(&guid, SDL_FALSE); if (mapping) { char pchGUID[33]; size_t needed; SDL_JoystickGetGUIDString(guid, pchGUID, sizeof(pchGUID)); /* allocate enough memory for GUID + ',' + name + ',' + mapping + \0 */ needed = SDL_strlen(pchGUID) + 1 + SDL_strlen(mapping->name) + 1 + SDL_strlen(mapping->mapping) + 1; pMappingString = SDL_malloc(needed); if (!pMappingString) { SDL_OutOfMemory(); return NULL; } SDL_snprintf(pMappingString, needed, "%s,%s,%s", pchGUID, mapping->name, mapping->mapping); } return pMappingString; } /* * Get the mapping string for this device */ char * SDL_GameControllerMapping(SDL_GameController * gamecontroller) { if (!gamecontroller) { return NULL; } return SDL_GameControllerMappingForGUID(gamecontroller->joystick->guid); } static void SDL_GameControllerLoadHints() { const char *hint = SDL_GetHint(SDL_HINT_GAMECONTROLLERCONFIG); if (hint && hint[0]) { size_t nchHints = SDL_strlen(hint); char *pUserMappings = SDL_malloc(nchHints + 1); char *pTempMappings = pUserMappings; SDL_memcpy(pUserMappings, hint, nchHints); pUserMappings[nchHints] = '\0'; while (pUserMappings) { char *pchNewLine = NULL; pchNewLine = SDL_strchr(pUserMappings, '\n'); if (pchNewLine) *pchNewLine = '\0'; SDL_PrivateGameControllerAddMapping(pUserMappings, SDL_CONTROLLER_MAPPING_PRIORITY_USER); if (pchNewLine) { pUserMappings = pchNewLine + 1; } else { pUserMappings = NULL; } } SDL_free(pTempMappings); } } /* * Fill the given buffer with the expected controller mapping filepath. * Usually this will just be SDL_HINT_GAMECONTROLLERCONFIG_FILE, but for * Android, we want to get the internal storage path. */ static SDL_bool SDL_GetControllerMappingFilePath(char *path, size_t size) { const char *hint = SDL_GetHint(SDL_HINT_GAMECONTROLLERCONFIG_FILE); if (hint && *hint) { return SDL_strlcpy(path, hint, size) < size; } #if defined(__ANDROID__) return SDL_snprintf(path, size, "%s/controller_map.txt", SDL_AndroidGetInternalStoragePath()) < size; #else return SDL_FALSE; #endif } /* * Initialize the game controller system, mostly load our DB of controller config mappings */ int SDL_GameControllerInitMappings(void) { char szControllerMapPath[1024]; int i = 0; const char *pMappingString = NULL; pMappingString = s_ControllerMappings[i]; while (pMappingString) { SDL_PrivateGameControllerAddMapping(pMappingString, SDL_CONTROLLER_MAPPING_PRIORITY_DEFAULT); i++; pMappingString = s_ControllerMappings[i]; } if (SDL_GetControllerMappingFilePath(szControllerMapPath, sizeof(szControllerMapPath))) { SDL_GameControllerAddMappingsFromFile(szControllerMapPath); } /* load in any user supplied config */ SDL_GameControllerLoadHints(); SDL_AddHintCallback(SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES, SDL_GameControllerIgnoreDevicesChanged, NULL); SDL_AddHintCallback(SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT, SDL_GameControllerIgnoreDevicesExceptChanged, NULL); return (0); } int SDL_GameControllerInit(void) { int i; /* watch for joy events and fire controller ones if needed */ SDL_AddEventWatch(SDL_GameControllerEventWatcher, NULL); /* Send added events for controllers currently attached */ for (i = 0; i < SDL_NumJoysticks(); ++i) { if (SDL_IsGameController(i)) { SDL_Event deviceevent; deviceevent.type = SDL_CONTROLLERDEVICEADDED; deviceevent.cdevice.which = i; SDL_PushEvent(&deviceevent); } } return (0); } /* * Get the implementation dependent name of a controller */ const char * SDL_GameControllerNameForIndex(int device_index) { ControllerMapping_t *pSupportedController = SDL_PrivateGetControllerMapping(device_index); if (pSupportedController) { if (SDL_strcmp(pSupportedController->name, "*") == 0) { return SDL_JoystickNameForIndex(device_index); } else { return pSupportedController->name; } } return NULL; } /** * Get the type of a game controller. */ SDL_GameControllerType SDL_GameControllerTypeForIndex(int joystick_index) { return SDL_GetJoystickGameControllerTypeFromGUID(SDL_JoystickGetDeviceGUID(joystick_index), SDL_JoystickNameForIndex(joystick_index)); } /** * Get the mapping of a game controller. * This can be called before any controllers are opened. * If no mapping can be found, this function returns NULL. */ char * SDL_GameControllerMappingForDeviceIndex(int joystick_index) { char *pMappingString = NULL; ControllerMapping_t *mapping; SDL_LockJoysticks(); mapping = SDL_PrivateGetControllerMapping(joystick_index); if (mapping) { SDL_JoystickGUID guid; char pchGUID[33]; size_t needed; guid = SDL_JoystickGetDeviceGUID(joystick_index); SDL_JoystickGetGUIDString(guid, pchGUID, sizeof(pchGUID)); /* allocate enough memory for GUID + ',' + name + ',' + mapping + \0 */ needed = SDL_strlen(pchGUID) + 1 + SDL_strlen(mapping->name) + 1 + SDL_strlen(mapping->mapping) + 1; pMappingString = SDL_malloc(needed); if (!pMappingString) { SDL_OutOfMemory(); SDL_UnlockJoysticks(); return NULL; } SDL_snprintf(pMappingString, needed, "%s,%s,%s", pchGUID, mapping->name, mapping->mapping); } SDL_UnlockJoysticks(); return pMappingString; } /* * Return 1 if the joystick with this name and GUID is a supported controller */ SDL_bool SDL_IsGameControllerNameAndGUID(const char *name, SDL_JoystickGUID guid) { ControllerMapping_t *pSupportedController = SDL_PrivateGetControllerMappingForNameAndGUID(name, guid); if (pSupportedController) { return SDL_TRUE; } return SDL_FALSE; } /* * Return 1 if the joystick at this device index is a supported controller */ SDL_bool SDL_IsGameController(int device_index) { ControllerMapping_t *pSupportedController = SDL_PrivateGetControllerMapping(device_index); if (pSupportedController) { return SDL_TRUE; } return SDL_FALSE; } /* * Return 1 if the game controller should be ignored by SDL */ SDL_bool SDL_ShouldIgnoreGameController(const char *name, SDL_JoystickGUID guid) { int i; Uint16 vendor; Uint16 product; Uint16 version; Uint32 vidpid; #if defined(__LINUX__) if (name && SDL_strstr(name, "Controller Motion Sensors")) { /* Don't treat the PS3 and PS4 motion controls as a separate game controller */ return SDL_TRUE; } #endif if (SDL_allowed_controllers.num_entries == 0 && SDL_ignored_controllers.num_entries == 0) { return SDL_FALSE; } SDL_GetJoystickGUIDInfo(guid, &vendor, &product, &version); if (SDL_GetHintBoolean("SDL_GAMECONTROLLER_ALLOW_STEAM_VIRTUAL_GAMEPAD", SDL_FALSE)) { /* We shouldn't ignore Steam's virtual gamepad since it's using the hints to filter out the real controllers so it can remap input for the virtual controller */ SDL_bool bSteamVirtualGamepad = SDL_FALSE; #if defined(__LINUX__) bSteamVirtualGamepad = (vendor == 0x28DE && product == 0x11FF); #elif defined(__MACOSX__) bSteamVirtualGamepad = (vendor == 0x045E && product == 0x028E && version == 1); #elif defined(__WIN32__) /* We can't tell on Windows, but Steam will block others in input hooks */ bSteamVirtualGamepad = SDL_TRUE; #endif if (bSteamVirtualGamepad) { return SDL_FALSE; } } vidpid = MAKE_VIDPID(vendor, product); if (SDL_allowed_controllers.num_entries > 0) { for (i = 0; i < SDL_allowed_controllers.num_entries; ++i) { if (vidpid == SDL_allowed_controllers.entries[i]) { return SDL_FALSE; } } return SDL_TRUE; } else { for (i = 0; i < SDL_ignored_controllers.num_entries; ++i) { if (vidpid == SDL_ignored_controllers.entries[i]) { return SDL_TRUE; } } return SDL_FALSE; } } /* * Open a controller for use - the index passed as an argument refers to * the N'th controller on the system. This index is the value which will * identify this controller in future controller events. * * This function returns a controller identifier, or NULL if an error occurred. */ SDL_GameController * SDL_GameControllerOpen(int device_index) { SDL_JoystickID instance_id; SDL_GameController *gamecontroller; SDL_GameController *gamecontrollerlist; ControllerMapping_t *pSupportedController = NULL; SDL_LockJoysticks(); gamecontrollerlist = SDL_gamecontrollers; /* If the controller is already open, return it */ instance_id = SDL_JoystickGetDeviceInstanceID(device_index); while (gamecontrollerlist) { if (instance_id == gamecontrollerlist->joystick->instance_id) { gamecontroller = gamecontrollerlist; ++gamecontroller->ref_count; SDL_UnlockJoysticks(); return (gamecontroller); } gamecontrollerlist = gamecontrollerlist->next; } /* Find a controller mapping */ pSupportedController = SDL_PrivateGetControllerMapping(device_index); if (!pSupportedController) { SDL_SetError("Couldn't find mapping for device (%d)", device_index); SDL_UnlockJoysticks(); return NULL; } /* Create and initialize the controller */ gamecontroller = (SDL_GameController *) SDL_calloc(1, sizeof(*gamecontroller)); if (gamecontroller == NULL) { SDL_OutOfMemory(); SDL_UnlockJoysticks(); return NULL; } gamecontroller->joystick = SDL_JoystickOpen(device_index); if (!gamecontroller->joystick) { SDL_free(gamecontroller); SDL_UnlockJoysticks(); return NULL; } if (gamecontroller->joystick->naxes) { gamecontroller->last_match_axis = (SDL_ExtendedGameControllerBind **)SDL_calloc(gamecontroller->joystick->naxes, sizeof(*gamecontroller->last_match_axis)); if (!gamecontroller->last_match_axis) { SDL_OutOfMemory(); SDL_JoystickClose(gamecontroller->joystick); SDL_free(gamecontroller); SDL_UnlockJoysticks(); return NULL; } } if (gamecontroller->joystick->nhats) { gamecontroller->last_hat_mask = (Uint8 *)SDL_calloc(gamecontroller->joystick->nhats, sizeof(*gamecontroller->last_hat_mask)); if (!gamecontroller->last_hat_mask) { SDL_OutOfMemory(); SDL_JoystickClose(gamecontroller->joystick); SDL_free(gamecontroller->last_match_axis); SDL_free(gamecontroller); SDL_UnlockJoysticks(); return NULL; } } SDL_PrivateLoadButtonMapping(gamecontroller, pSupportedController->name, pSupportedController->mapping); /* Add the controller to list */ ++gamecontroller->ref_count; /* Link the controller in the list */ gamecontroller->next = SDL_gamecontrollers; SDL_gamecontrollers = gamecontroller; SDL_UnlockJoysticks(); return (gamecontroller); } /* * Manually pump for controller updates. */ void SDL_GameControllerUpdate(void) { /* Just for API completeness; the joystick API does all the work. */ SDL_JoystickUpdate(); } /* * Get the current state of an axis control on a controller */ Sint16 SDL_GameControllerGetAxis(SDL_GameController * gamecontroller, SDL_GameControllerAxis axis) { int i; if (!gamecontroller) return 0; for (i = 0; i < gamecontroller->num_bindings; ++i) { SDL_ExtendedGameControllerBind *binding = &gamecontroller->bindings[i]; if (binding->outputType == SDL_CONTROLLER_BINDTYPE_AXIS && binding->output.axis.axis == axis) { int value = 0; SDL_bool valid_input_range; SDL_bool valid_output_range; if (binding->inputType == SDL_CONTROLLER_BINDTYPE_AXIS) { value = SDL_JoystickGetAxis(gamecontroller->joystick, binding->input.axis.axis); if (binding->input.axis.axis_min < binding->input.axis.axis_max) { valid_input_range = (value >= binding->input.axis.axis_min && value <= binding->input.axis.axis_max); } else { valid_input_range = (value >= binding->input.axis.axis_max && value <= binding->input.axis.axis_min); } if (valid_input_range) { if (binding->input.axis.axis_min != binding->output.axis.axis_min || binding->input.axis.axis_max != binding->output.axis.axis_max) { float normalized_value = (float)(value - binding->input.axis.axis_min) / (binding->input.axis.axis_max - binding->input.axis.axis_min); value = binding->output.axis.axis_min + (int)(normalized_value * (binding->output.axis.axis_max - binding->output.axis.axis_min)); } } else { value = 0; } } else if (binding->inputType == SDL_CONTROLLER_BINDTYPE_BUTTON) { value = SDL_JoystickGetButton(gamecontroller->joystick, binding->input.button); if (value == SDL_PRESSED) { value = binding->output.axis.axis_max; } } else if (binding->inputType == SDL_CONTROLLER_BINDTYPE_HAT) { int hat_mask = SDL_JoystickGetHat(gamecontroller->joystick, binding->input.hat.hat); if (hat_mask & binding->input.hat.hat_mask) { value = binding->output.axis.axis_max; } } if (binding->output.axis.axis_min < binding->output.axis.axis_max) { valid_output_range = (value >= binding->output.axis.axis_min && value <= binding->output.axis.axis_max); } else { valid_output_range = (value >= binding->output.axis.axis_max && value <= binding->output.axis.axis_min); } /* If the value is zero, there might be another binding that makes it non-zero */ if (value != 0 && valid_output_range) { return (Sint16)value; } } } return 0; } /* * Get the current state of a button on a controller */ Uint8 SDL_GameControllerGetButton(SDL_GameController * gamecontroller, SDL_GameControllerButton button) { int i; if (!gamecontroller) return 0; for (i = 0; i < gamecontroller->num_bindings; ++i) { SDL_ExtendedGameControllerBind *binding = &gamecontroller->bindings[i]; if (binding->outputType == SDL_CONTROLLER_BINDTYPE_BUTTON && binding->output.button == button) { if (binding->inputType == SDL_CONTROLLER_BINDTYPE_AXIS) { SDL_bool valid_input_range; int value = SDL_JoystickGetAxis(gamecontroller->joystick, binding->input.axis.axis); int threshold = binding->input.axis.axis_min + (binding->input.axis.axis_max - binding->input.axis.axis_min) / 2; if (binding->input.axis.axis_min < binding->input.axis.axis_max) { valid_input_range = (value >= binding->input.axis.axis_min && value <= binding->input.axis.axis_max); if (valid_input_range) { return (value >= threshold) ? SDL_PRESSED : SDL_RELEASED; } } else { valid_input_range = (value >= binding->input.axis.axis_max && value <= binding->input.axis.axis_min); if (valid_input_range) { return (value <= threshold) ? SDL_PRESSED : SDL_RELEASED; } } } else if (binding->inputType == SDL_CONTROLLER_BINDTYPE_BUTTON) { return SDL_JoystickGetButton(gamecontroller->joystick, binding->input.button); } else if (binding->inputType == SDL_CONTROLLER_BINDTYPE_HAT) { int hat_mask = SDL_JoystickGetHat(gamecontroller->joystick, binding->input.hat.hat); return (hat_mask & binding->input.hat.hat_mask) ? SDL_PRESSED : SDL_RELEASED; } } } return SDL_RELEASED; } const char * SDL_GameControllerName(SDL_GameController * gamecontroller) { if (!gamecontroller) return NULL; if (SDL_strcmp(gamecontroller->name, "*") == 0) { return SDL_JoystickName(SDL_GameControllerGetJoystick(gamecontroller)); } else { return gamecontroller->name; } } SDL_GameControllerType SDL_GameControllerGetType(SDL_GameController *gamecontroller) { return SDL_GetJoystickGameControllerTypeFromGUID(SDL_JoystickGetGUID(SDL_GameControllerGetJoystick(gamecontroller)), SDL_JoystickName(SDL_GameControllerGetJoystick(gamecontroller))); } int SDL_GameControllerGetPlayerIndex(SDL_GameController *gamecontroller) { return SDL_JoystickGetPlayerIndex(SDL_GameControllerGetJoystick(gamecontroller)); } /** * Set the player index of an opened game controller */ void SDL_GameControllerSetPlayerIndex(SDL_GameController *gamecontroller, int player_index) { SDL_JoystickSetPlayerIndex(SDL_GameControllerGetJoystick(gamecontroller), player_index); } Uint16 SDL_GameControllerGetVendor(SDL_GameController * gamecontroller) { return SDL_JoystickGetVendor(SDL_GameControllerGetJoystick(gamecontroller)); } Uint16 SDL_GameControllerGetProduct(SDL_GameController * gamecontroller) { return SDL_JoystickGetProduct(SDL_GameControllerGetJoystick(gamecontroller)); } Uint16 SDL_GameControllerGetProductVersion(SDL_GameController * gamecontroller) { return SDL_JoystickGetProductVersion(SDL_GameControllerGetJoystick(gamecontroller)); } /* * Return if the controller in question is currently attached to the system, * \return 0 if not plugged in, 1 if still present. */ SDL_bool SDL_GameControllerGetAttached(SDL_GameController * gamecontroller) { if (!gamecontroller) return SDL_FALSE; return SDL_JoystickGetAttached(gamecontroller->joystick); } /* * Get the joystick for this controller */ SDL_Joystick *SDL_GameControllerGetJoystick(SDL_GameController * gamecontroller) { if (!gamecontroller) return NULL; return gamecontroller->joystick; } /* * Return the SDL_GameController associated with an instance id. */ SDL_GameController * SDL_GameControllerFromInstanceID(SDL_JoystickID joyid) { SDL_GameController *gamecontroller; SDL_LockJoysticks(); gamecontroller = SDL_gamecontrollers; while (gamecontroller) { if (gamecontroller->joystick->instance_id == joyid) { SDL_UnlockJoysticks(); return gamecontroller; } gamecontroller = gamecontroller->next; } SDL_UnlockJoysticks(); return NULL; } /** * Return the SDL_GameController associated with a player index. */ SDL_GameController *SDL_GameControllerFromPlayerIndex(int player_index) { SDL_Joystick *joystick = SDL_JoystickFromPlayerIndex(player_index); if (joystick) { return SDL_GameControllerFromInstanceID(joystick->instance_id); } return NULL; } /* * Get the SDL joystick layer binding for this controller axis mapping */ SDL_GameControllerButtonBind SDL_GameControllerGetBindForAxis(SDL_GameController * gamecontroller, SDL_GameControllerAxis axis) { int i; SDL_GameControllerButtonBind bind; SDL_zero(bind); if (!gamecontroller || axis == SDL_CONTROLLER_AXIS_INVALID) return bind; for (i = 0; i < gamecontroller->num_bindings; ++i) { SDL_ExtendedGameControllerBind *binding = &gamecontroller->bindings[i]; if (binding->outputType == SDL_CONTROLLER_BINDTYPE_AXIS && binding->output.axis.axis == axis) { bind.bindType = binding->inputType; if (binding->inputType == SDL_CONTROLLER_BINDTYPE_AXIS) { /* FIXME: There might be multiple axes bound now that we have axis ranges... */ bind.value.axis = binding->input.axis.axis; } else if (binding->inputType == SDL_CONTROLLER_BINDTYPE_BUTTON) { bind.value.button = binding->input.button; } else if (binding->inputType == SDL_CONTROLLER_BINDTYPE_HAT) { bind.value.hat.hat = binding->input.hat.hat; bind.value.hat.hat_mask = binding->input.hat.hat_mask; } break; } } return bind; } /* * Get the SDL joystick layer binding for this controller button mapping */ SDL_GameControllerButtonBind SDL_GameControllerGetBindForButton(SDL_GameController * gamecontroller, SDL_GameControllerButton button) { int i; SDL_GameControllerButtonBind bind; SDL_zero(bind); if (!gamecontroller || button == SDL_CONTROLLER_BUTTON_INVALID) return bind; for (i = 0; i < gamecontroller->num_bindings; ++i) { SDL_ExtendedGameControllerBind *binding = &gamecontroller->bindings[i]; if (binding->outputType == SDL_CONTROLLER_BINDTYPE_BUTTON && binding->output.button == button) { bind.bindType = binding->inputType; if (binding->inputType == SDL_CONTROLLER_BINDTYPE_AXIS) { bind.value.axis = binding->input.axis.axis; } else if (binding->inputType == SDL_CONTROLLER_BINDTYPE_BUTTON) { bind.value.button = binding->input.button; } else if (binding->inputType == SDL_CONTROLLER_BINDTYPE_HAT) { bind.value.hat.hat = binding->input.hat.hat; bind.value.hat.hat_mask = binding->input.hat.hat_mask; } break; } } return bind; } int SDL_GameControllerRumble(SDL_GameController *gamecontroller, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble, Uint32 duration_ms) { return SDL_JoystickRumble(SDL_GameControllerGetJoystick(gamecontroller), low_frequency_rumble, high_frequency_rumble, duration_ms); } void SDL_GameControllerClose(SDL_GameController * gamecontroller) { SDL_GameController *gamecontrollerlist, *gamecontrollerlistprev; if (!gamecontroller) return; SDL_LockJoysticks(); /* First decrement ref count */ if (--gamecontroller->ref_count > 0) { SDL_UnlockJoysticks(); return; } SDL_JoystickClose(gamecontroller->joystick); gamecontrollerlist = SDL_gamecontrollers; gamecontrollerlistprev = NULL; while (gamecontrollerlist) { if (gamecontroller == gamecontrollerlist) { if (gamecontrollerlistprev) { /* unlink this entry */ gamecontrollerlistprev->next = gamecontrollerlist->next; } else { SDL_gamecontrollers = gamecontroller->next; } break; } gamecontrollerlistprev = gamecontrollerlist; gamecontrollerlist = gamecontrollerlist->next; } SDL_free(gamecontroller->bindings); SDL_free(gamecontroller->last_match_axis); SDL_free(gamecontroller->last_hat_mask); SDL_free(gamecontroller); SDL_UnlockJoysticks(); } /* * Quit the controller subsystem */ void SDL_GameControllerQuit(void) { SDL_LockJoysticks(); while (SDL_gamecontrollers) { SDL_gamecontrollers->ref_count = 1; SDL_GameControllerClose(SDL_gamecontrollers); } SDL_UnlockJoysticks(); } void SDL_GameControllerQuitMappings(void) { ControllerMapping_t *pControllerMap; while (s_pSupportedControllers) { pControllerMap = s_pSupportedControllers; s_pSupportedControllers = s_pSupportedControllers->next; SDL_free(pControllerMap->name); SDL_free(pControllerMap->mapping); SDL_free(pControllerMap); } SDL_DelEventWatch(SDL_GameControllerEventWatcher, NULL); SDL_DelHintCallback(SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES, SDL_GameControllerIgnoreDevicesChanged, NULL); SDL_DelHintCallback(SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT, SDL_GameControllerIgnoreDevicesExceptChanged, NULL); if (SDL_allowed_controllers.entries) { SDL_free(SDL_allowed_controllers.entries); SDL_zero(SDL_allowed_controllers); } if (SDL_ignored_controllers.entries) { SDL_free(SDL_ignored_controllers.entries); SDL_zero(SDL_ignored_controllers); } } /* * Event filter to transform joystick events into appropriate game controller ones */ static int SDL_PrivateGameControllerAxis(SDL_GameController * gamecontroller, SDL_GameControllerAxis axis, Sint16 value) { int posted; /* translate the event, if desired */ posted = 0; #if !SDL_EVENTS_DISABLED if (SDL_GetEventState(SDL_CONTROLLERAXISMOTION) == SDL_ENABLE) { SDL_Event event; event.type = SDL_CONTROLLERAXISMOTION; event.caxis.which = gamecontroller->joystick->instance_id; event.caxis.axis = axis; event.caxis.value = value; posted = SDL_PushEvent(&event) == 1; } #endif /* !SDL_EVENTS_DISABLED */ return (posted); } /* * Event filter to transform joystick events into appropriate game controller ones */ static int SDL_PrivateGameControllerButton(SDL_GameController * gamecontroller, SDL_GameControllerButton button, Uint8 state) { int posted; #if !SDL_EVENTS_DISABLED SDL_Event event; if (button == SDL_CONTROLLER_BUTTON_INVALID) return (0); switch (state) { case SDL_PRESSED: event.type = SDL_CONTROLLERBUTTONDOWN; break; case SDL_RELEASED: event.type = SDL_CONTROLLERBUTTONUP; break; default: /* Invalid state -- bail */ return (0); } #endif /* !SDL_EVENTS_DISABLED */ if (button == SDL_CONTROLLER_BUTTON_GUIDE) { Uint32 now = SDL_GetTicks(); if (state == SDL_PRESSED) { gamecontroller->guide_button_down = now; if (gamecontroller->joystick->delayed_guide_button) { /* Skip duplicate press */ return (0); } } else { if (!SDL_TICKS_PASSED(now, gamecontroller->guide_button_down+SDL_MINIMUM_GUIDE_BUTTON_DELAY_MS)) { gamecontroller->joystick->delayed_guide_button = SDL_TRUE; return (0); } gamecontroller->joystick->delayed_guide_button = SDL_FALSE; } } /* translate the event, if desired */ posted = 0; #if !SDL_EVENTS_DISABLED if (SDL_GetEventState(event.type) == SDL_ENABLE) { event.cbutton.which = gamecontroller->joystick->instance_id; event.cbutton.button = button; event.cbutton.state = state; posted = SDL_PushEvent(&event) == 1; } #endif /* !SDL_EVENTS_DISABLED */ return (posted); } /* * Turn off controller events */ int SDL_GameControllerEventState(int state) { #if SDL_EVENTS_DISABLED return SDL_IGNORE; #else const Uint32 event_list[] = { SDL_CONTROLLERAXISMOTION, SDL_CONTROLLERBUTTONDOWN, SDL_CONTROLLERBUTTONUP, SDL_CONTROLLERDEVICEADDED, SDL_CONTROLLERDEVICEREMOVED, SDL_CONTROLLERDEVICEREMAPPED, }; unsigned int i; switch (state) { case SDL_QUERY: state = SDL_IGNORE; for (i = 0; i < SDL_arraysize(event_list); ++i) { state = SDL_EventState(event_list[i], SDL_QUERY); if (state == SDL_ENABLE) { break; } } break; default: for (i = 0; i < SDL_arraysize(event_list); ++i) { SDL_EventState(event_list[i], state); } break; } return (state); #endif /* SDL_EVENTS_DISABLED */ } void SDL_GameControllerHandleDelayedGuideButton(SDL_Joystick *joystick) { SDL_GameController *controllerlist = SDL_gamecontrollers; while (controllerlist) { if (controllerlist->joystick == joystick) { SDL_PrivateGameControllerButton(controllerlist, SDL_CONTROLLER_BUTTON_GUIDE, SDL_RELEASED); break; } controllerlist = controllerlist->next; } } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/SDL_gamecontroller.c
C
apache-2.0
78,752
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" /* Default mappings we support The easiest way to generate a new mapping is to start Steam in Big Picture mode, configure your joystick and then look in config/config.vdf in your Steam installation directory for the "SDL_GamepadBind" entry. Alternatively, you can use the app located in test/controllermap */ static const char *s_ControllerMappings [] = { #if SDL_JOYSTICK_XINPUT "xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", #endif #if SDL_JOYSTICK_WGI "030000007e0500000920000000007701,Nintendo Switch Pro Controller,a:b1,b:b0,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "030000007e0500000920000000007701,Nintendo Switch Pro Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "0300000032150000000a000000007703,Razer Atrox Arcade Stick,a:b0,b:b1,dpdown:b12,dpleft:b13,dpright:b11,dpup:b10,leftshoulder:b4,lefttrigger:b8,rightshoulder:b5,righttrigger:b9,x:b2,y:b3,", #endif #if SDL_JOYSTICK_DINPUT "03000000fa2d00000100000000000000,3DRUDDER,leftx:a0,lefty:a1,rightx:a5,righty:a2,", "03000000c82d00000090000000000000,8BitDo FC30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000090000000000000,8BitDo FC30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001038000000000000,8BitDo FC30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001038000000000000,8BitDo FC30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000650000000000000,8BitDo M30 Gamepad,a:b0,b:b1,back:b10,guide:b2,leftshoulder:b6,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b9,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000650000000000000,8BitDo M30 Gamepad,a:b1,b:b0,back:b10,guide:b2,leftshoulder:b6,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b9,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00005106000000000000,8BitDo M30 Gamepad,a:b0,b:b1,back:b10,guide:b2,leftshoulder:b6,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b9,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00005106000000000000,8BitDo M30 Gamepad,a:b1,b:b0,back:b10,guide:b2,leftshoulder:b6,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b9,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001590000000000000,8BitDo N30 Pro 2,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001590000000000000,8BitDo N30 Pro 2,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00006528000000000000,8BitDo N30 Pro 2,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00006528000000000000,8BitDo N30 Pro 2,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "030000003512000012ab000000000000,8BitDo NES30 Gamepad,a:b0,b:b1,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "030000003512000012ab000000000000,8BitDo NES30 Gamepad,a:b1,b:b0,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000022000000090000000000000,8BitDo NES30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000022000000090000000000000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000203800000900000000000000,8BitDo NES30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000203800000900000000000000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00002038000000000000,8BitDo NES30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00002038000000000000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000060000000000000,8BitDo SF30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000060000000000000,8BitDo SF30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000061000000000000,8BitDo SF30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000061000000000000,8BitDo SF30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000102800000900000000000000,8BitDo SFC30 Gamepad,a:b0,b:b1,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000102800000900000000000000,8BitDo SFC30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001290000000000000,8BitDo SN30 Gamepad,a:b0,b:b1,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001290000000000000,8BitDo SN30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00006228000000000000,8BitDo SN30 Gamepad,a:b0,b:b1,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00006228000000000000,8BitDo SN30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000260000000000000,8BitDo SN30 Pro+,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000260000000000000,8BitDo SN30 Pro+,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000261000000000000,8BitDo SN30 Pro+,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000261000000000000,8BitDo SN30 Pro+,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000160000000000000,8BitDo SN30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000160000000000000,8BitDo SN30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "030000003512000020ab000000000000,8BitDo SNES30 Gamepad,a:b0,b:b1,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "030000003512000020ab000000000000,8BitDo SNES30 Gamepad,a:b1,b:b0,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001890000000000000,8BitDo Zero 2,a:b0,b:b1,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001890000000000000,8BitDo Zero 2,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00003032000000000000,8BitDo Zero 2,a:b0,b:b1,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00003032000000000000,8BitDo Zero 2,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000a00500003232000000000000,8BitDo Zero Gamepad,a:b0,b:b1,back:b10,dpdown:+a2,dpleft:-a0,dpright:+a0,dpup:-a2,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000a00500003232000000000000,8BitDo Zero Gamepad,a:b1,b:b0,back:b10,dpdown:+a2,dpleft:-a0,dpright:+a0,dpup:-a2,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "030000008f0e00001200000000000000,Acme GA-02,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b2,y:b3,", "03000000fa190000f0ff000000000000,Acteck AGJ-3200,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000341a00003608000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006f0e00000263000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006f0e00001101000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006f0e00001401000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006f0e00001402000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006f0e00001901000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006f0e00001a01000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000d62000001d57000000000000,Airflo PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000d62000002a79000000000000,BDA PS4 Fightpad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000d81d00000b00000000000000,BUFFALO BSGP1601 Series ,a:b5,b:b3,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b8,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b9,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b13,x:b4,y:b2,", "03000000d6200000e557000000000000,Batarang,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000c01100001352000000000000,Battalife Joystick,a:b6,b:b7,back:b2,leftshoulder:b0,leftx:a0,lefty:a1,rightshoulder:b1,start:b3,x:b4,y:b5,", "030000006f0e00003201000000000000,Battlefield 4 PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000bc2000006012000000000000,Betop 2126F,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000bc2000000055000000000000,Betop BFM Gamepad,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", "03000000bc2000006312000000000000,Betop Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000bc2000006412000000000000,Betop Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000c01100000555000000000000,Betop Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000c01100000655000000000000,Betop Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000790000000700000000000000,Betop Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b3,y:b0,", "03000000808300000300000000000000,Betop Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b3,y:b0,", "030000006b1400000055000000000000,Bigben PS3 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "030000006b1400000103000000000000,Bigben PS3 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,", "0300000066f700000500000000000000,BrutalLegendTest,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b3,", "03000000e82000006058000000000000,Cideko AK08b,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000260900008888000000000000,Cyber Gadget GameCube Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:a4,rightx:a2,righty:a3~,start:b7,x:b2,y:b3,", "03000000a306000022f6000000000000,Cyborg V.3 Rumble Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:+a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:-a3,rightx:a2,righty:a4,start:b9,x:b0,y:b3,", "03000000451300000830000000000000,Defender Game Racer X7,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "03000000791d00000103000000000000,Dual Box WII,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000bd12000002e0000000000000,Dual USB Vibration Joystick,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b9,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b10,righttrigger:b5,rightx:a3,righty:a2,start:b11,x:b3,y:b0,", "030000006f0e00003001000000000000,EA SPORTS PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000341a00000108000000000000,EXEQ RF USB Gamepad 8206,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "030000008f0e00000f31000000000000,EXEQ,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,", "03000000b80500000410000000000000,Elecom Gamepad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b1,", "03000000b80500000610000000000000,Elecom Gamepad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b1,", "03000000852100000201000000000000,FF-GP1,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f00002700000000000000,FIGHTING STICK V3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "030000000d0f00008700000000000000,Fighting Stick mini 4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "030000000d0f00008800000000000000,Fighting Stick mini 4,a:b1,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b8,x:b0,y:b3,", "78696e70757403000000000000000000,Fightstick TES,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,lefttrigger:a2,rightshoulder:b5,righttrigger:a5,start:b7,x:b2,y:b3,", "03000000790000000600000000000000,G-Shark GS-GP702,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b3,y:b0,", "030000008f0e00000d31000000000000,GAMEPAD 3 TURBO,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000300f00000b01000000000000,GGE909 Recoil Pad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", "03000000790000002201000000000000,Game Controller for PC,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "0300000066f700000100000000000000,Game VIB Joystick,a:b2,b:b3,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a3,righty:a2,start:b11,x:b0,y:b1,", "03000000ac0500003d03000000000000,GameSir,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", "03000000ac0500004d04000000000000,GameSir,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", "03000000ffff00000000000000000000,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "03000000c01100000140000000000000,GameStop PS4 Fun Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000260900002625000000000000,Gamecube Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,lefttrigger:a4,leftx:a0,lefty:a1,righttrigger:a5,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", "03000000280400000140000000000000,Gamepad Pro USB,a:b1,b:b2,back:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "030000005c1a00003330000000000000,Genius MaxFire Grandias 12V,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b7,leftx:a0,lefty:a1,rightshoulder:b4,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b2,y:b3,", "030000008305000031b0000000000000,Genius Maxfire Blaze 3,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "03000000451300000010000000000000,Genius Maxfire Grandias 12,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "030000008305000009a0000000000000,Genius,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "03000000f025000021c1000000000000,Gioteck PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000f0250000c383000000000000,Gioteck VX2 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000f0250000c483000000000000,Gioteck VX2 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000f0250000c283000000000000,Gioteck,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000632500002605000000000000,HJD-X,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", "030000000d0f00008400000000000000,HORI Fighting Commander,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000000d0f00008500000000000000,HORI Fighting Commander,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f00006e00000000000000,HORIPAD 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f00006600000000000000,HORIPAD 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000000d0f0000ee00000000000000,HORIPAD mini4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000250900000017000000000000,HRAP2 on PS/SS/N64 Joypad to USB BOX,a:b2,b:b1,back:b9,leftshoulder:b5,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b6,start:b8,x:b3,y:b0,", "03000000341a00000302000000000000,Hama Scorpad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f00004900000000000000,Hatsune Miku Sho Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000d81400000862000000000000,HitBox Edition Cthulhu+,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b5,lefttrigger:b4,rightshoulder:b7,righttrigger:b6,start:b9,x:b0,y:b3,", "030000000d0f00005f00000000000000,Hori Fighting Commander 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f00005e00000000000000,Hori Fighting Commander 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000000d0f00004000000000000000,Hori Fighting Stick Mini 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b5,lefttrigger:b4,rightshoulder:b7,righttrigger:b6,start:b9,x:b0,y:b3,", "030000000d0f00000900000000000000,Hori Pad 3 Turbo,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f00005400000000000000,Hori Pad 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f00004d00000000000000,Hori Pad A,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f0000c100000000000000,Horipad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000008f0e00001330000000000000,HuiJia SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b9,x:b3,y:b0,", "030000006f0e00002401000000000000,INJUSTICE FightStick PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "03000000ac0500002c02000000000000,IPEGA,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b8,leftstick:b13,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b9,rightstick:b14,righttrigger:b7,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", "03000000b50700001403000000000000,Impact Black,a:b2,b:b3,back:b8,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,", "03000000491900000204000000000000,Ipega PG-9023,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", "030000006e0500000520000000000000,JC-P301U,a:b2,b:b3,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3,start:b11,x:b0,y:b1,", "030000006e0500000320000000000000,JC-U3613M (DInput),a:b2,b:b3,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3,start:b11,x:b0,y:b1,", "030000006e0500000720000000000000,JC-W01U,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b1,", "03000000790000000200000000000000,King PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b3,y:b0,", "030000006d040000d1ca000000000000,Logitech ChillStream,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006d040000d2ca000000000000,Logitech Cordless Precision,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006d04000011c2000000000000,Logitech Cordless Wingman,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b9,leftstick:b5,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b2,righttrigger:b7,rightx:a3,righty:a4,x:b4,", "030000006d04000016c2000000000000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006d04000018c2000000000000,Logitech F510 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006d04000019c2000000000000,Logitech F710 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* Guide button doesn't seem to be sent in DInput mode. */ "03000000380700008081000000000000,MADCATZ SFV Arcade FightStick Alpha PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000380700006382000000000000,MLG Gamepad PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000c62400002a89000000000000,MOGA XP5-A Plus,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b15,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", "03000000c62400002b89000000000000,MOGA XP5-A Plus,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", "03000000250900006688000000000000,MP-8866 Super Dual Box,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,", "03000000380700006652000000000000,Mad Catz C.T.R.L.R,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b0,y:b3,", "03000000380700005032000000000000,Mad Catz FightPad PRO (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000380700005082000000000000,Mad Catz FightPad PRO (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000380700008433000000000000,Mad Catz FightStick TE S+ (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000380700008483000000000000,Mad Catz FightStick TE S+ (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000380700008134000000000000,Mad Catz FightStick TE2+ PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b7,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b4,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000380700008184000000000000,Mad Catz FightStick TE2+ PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b5,leftstick:b10,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b4,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000380700006252000000000000,Mad Catz Micro C.T.R.L.R,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b0,y:b3,", "03000000380700008034000000000000,Mad Catz TE2 PS3 Fightstick,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000380700008084000000000000,Mad Catz TE2 PS4 Fightstick,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000380700001888000000000000,MadCatz SFIV FightStick PS3,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b5,lefttrigger:b7,leftx:a0,lefty:a1,rightshoulder:b4,righttrigger:b6,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "03000000380700008532000000000000,Madcatz Arcade Fightstick TE S PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000380700003888000000000000,Madcatz Arcade Fightstick TE S+ PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000002a0600001024000000000000,Matricom,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b2,y:b3,", "03000000250900000128000000000000,Mayflash Arcade Stick,a:b1,b:b2,back:b8,leftshoulder:b0,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b3,righttrigger:b7,start:b9,x:b5,y:b6,", "03000000790000004418000000000000,Mayflash GameCube Controller,a:b1,b:b2,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,", "030000008f0e00001030000000000000,Mayflash USB Adapter for original Sega Saturn controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,lefttrigger:b5,rightshoulder:b2,righttrigger:b7,start:b9,x:b3,y:b4,", "0300000025090000e803000000000000,Mayflash Wii Classic Controller,a:b1,b:b0,back:b8,dpdown:b13,dpleft:b12,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,", "03000000790000000018000000000000,Mayflash WiiU Pro Game Controller Adapter (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000efbe0000edfe000000000000,Monect Virtual Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b0,", "030000006b140000010c000000000000,NACON GC-400ES,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "030000001008000001e5000000000000,NEXT SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b6,start:b9,x:b3,y:b0,", "03000000152000000182000000000000,NGDS,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b3,y:b0,", "030000004b120000014d000000000000,NYKO AIRFLO,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:a3,leftstick:a0,lefttrigger:b6,rightshoulder:b5,rightstick:a2,righttrigger:b7,start:b9,x:b2,y:b3,", "03000000790000004318000000000000,Nintendo GameCube Controller,a:b1,b:b2,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000790000004318000000000000,Nintendo GameCube Controller,a:b1,b:b0,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b2,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000bd12000015d0000000000000,Nintendo Retrolink USB Super SNES Classic Controller,a:b2,b:b1,back:b8,leftshoulder:b4,leftx:a0,lefty:a1,rightshoulder:b5,start:b9,x:b3,y:b0,", "030000007e0500000920000000000000,Nintendo Switch Pro Controller,a:b1,b:b0,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "030000007e0500000920000000000000,Nintendo Switch Pro Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "030000000d0500000308000000000000,Nostromo N45,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b12,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b10,x:b2,y:b3,", "03000000d62000006d57000000000000,OPP PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000362800000100000000000000,OUYA Game Controller,a:b0,b:b3,dpdown:b9,dpleft:b10,dpright:b11,dpup:b8,guide:b14,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:b13,rightx:a3,righty:a4,x:b1,y:b2,", "03000000782300000a10000000000000,Onlive Wireless Controller,a:b15,b:b14,back:b7,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b5,leftshoulder:b11,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a3,righty:a4,start:b6,x:b13,y:b12,", "030000006b14000001a1000000000000,Orange Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b2,y:b3,", "03000000120c0000f60e000000000000,P4 Wired Gamepad,a:b1,b:b2,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b5,lefttrigger:b7,rightshoulder:b4,righttrigger:b6,start:b9,x:b0,y:b3,", "030000006f0e00000901000000000000,PDP Versus Fighting Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "03000000632500002306000000000000,PS Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", "03000000e30500009605000000000000,PS to USB convert cable,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,", "03000000100800000100000000000000,PS1 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", "030000008f0e00007530000000000000,PS1 Controller,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b1,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000100800000300000000000000,PS2 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a4,righty:a2,start:b9,x:b3,y:b0,", "03000000250900008888000000000000,PS2 Controller,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,", "03000000666600006706000000000000,PS2 Controller,a:b2,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,leftshoulder:b6,leftstick:b9,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b10,righttrigger:b5,rightx:a2,righty:a3,start:b11,x:b3,y:b0,", "030000006b1400000303000000000000,PS2 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "030000009d0d00001330000000000000,PS2 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "03000000250900000500000000000000,PS3 Controller,a:b2,b:b1,back:b9,dpdown:h0.8,dpleft:h0.4,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b0,y:b3,", "030000004c0500006802000000000000,PS3 Controller,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b10,lefttrigger:a3~,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:a4~,rightx:a2,righty:a5,start:b8,x:b3,y:b0,", "03000000632500007505000000000000,PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000888800000803000000000000,PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.8,dpleft:h0.4,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b9,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:b7,rightx:a3,righty:a4,start:b11,x:b0,y:b3,", "030000008f0e00001431000000000000,PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000003807000056a8000000000000,PS3 RF pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000100000008200000000000000,PS360+ v1.66,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:h0.4,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "030000004c050000a00b000000000000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000004c050000c405000000000000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000004c050000cc09000000000000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000008f0e00000300000000000000,Piranha xtreme,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", "03000000d62000006dca000000000000,PowerA Pro Ex,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000d62000009557000000000000,Pro Elite PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000d62000009f31000000000000,Pro Ex mini PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000d6200000c757000000000000,Pro Ex mini PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000222c00000020000000000000,QANBA DRONE ARCADE JOYSTICK,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,rightshoulder:b5,righttrigger:a4,start:b9,x:b0,y:b3,", "03000000300f00000011000000000000,QanBa Arcade JoyStick 1008,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b10,x:b0,y:b3,", "03000000300f00001611000000000000,QanBa Arcade JoyStick 4018,a:b1,b:b2,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b8,x:b0,y:b3,", "03000000300f00001210000000000000,QanBa Joystick Plus,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,rightshoulder:b5,start:b9,x:b2,y:b3,", "03000000341a00000104000000000000,QanBa Joystick Q4RAF,a:b5,b:b6,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b0,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b3,righttrigger:b7,start:b9,x:b1,y:b2,", "03000000222c00000223000000000000,Qanba Obsidian Arcade Joystick PS3 Mode,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000222c00000023000000000000,Qanba Obsidian Arcade Joystick PS4 Mode,a:b1,b:b2,back:b13,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000000d0f00001100000000000000,REAL ARCADE PRO.3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,rightshoulder:b5,rightstick:b11,righttrigger:b7,start:b9,x:b0,y:b3,", "030000000d0f00007000000000000000,REAL ARCADE PRO.4 VLX,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,rightshoulder:b5,rightstick:b11,righttrigger:b7,start:b9,x:b0,y:b3,", "030000000d0f00002200000000000000,REAL ARCADE Pro.V3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000321500000003000000000000,Razer Hydra,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a2,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "03000000321500000204000000000000,Razer Panthera (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000321500000104000000000000,Razer Panthera (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000321500000507000000000000,Razer Raiju Mobile,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", "03000000321500000707000000000000,Razer Raiju Mobile,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", "03000000321500000011000000000000,Razer Raion Fightpad for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000321500000009000000000000,Razer Serval,+lefty:+a2,-lefty:-a1,a:b0,b:b1,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,leftx:a0,rightshoulder:b5,rightstick:b9,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000000d0f00006a00000000000000,Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000000d0f00006b00000000000000,Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f00008a00000000000000,Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000000d0f00008b00000000000000,Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f00005b00000000000000,Real Arcade Pro.V4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000000d0f00005c00000000000000,Real Arcade Pro.V4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "0300000000f000000300000000000000,RetroUSB.com RetroPad,a:b1,b:b5,back:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b3,x:b0,y:b4,", "0300000000f00000f100000000000000,RetroUSB.com Super RetroPort,a:b1,b:b5,back:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b3,x:b0,y:b4,", "03000000790000001100000000000000,Retrolink SNES Controller,a:b2,b:b1,back:b8,dpdown:+a4,dpleft:-a3,dpright:+a3,dpup:-a4,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,", "030000006b140000130d000000000000,Revolution Pro Controller 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000006b140000010d000000000000,Revolution Pro Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000006f0e00001e01000000000000,Rock Candy PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006f0e00002801000000000000,Rock Candy PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006f0e00002f01000000000000,Rock Candy PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000341a00000208000000000000,SL-6555-SBK,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:-a4,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a4,rightx:a3,righty:a2,start:b7,x:b2,y:b3,", "03000000341a00000908000000000000,SL-6566,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "03000000790000001c18000000000000,STK-7024X,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", "03000000ff1100003133000000000000,SVEN X-PAD,a:b2,b:b3,back:b4,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b9,rightx:a2,righty:a4,start:b5,x:b0,y:b1,", "03000000457500002211000000000000,SZMY-POWER PC Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000a306000023f6000000000000,Saitek Cyborg V.1 Game pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b0,y:b3,", "03000000a30600001af5000000000000,Saitek Cyborg,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b0,y:b3,", "03000000300f00001201000000000000,Saitek Dual Analog Pad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,", "03000000a30600000cff000000000000,Saitek P2500 Force Rumble Pad,a:b2,b:b3,back:b11,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3,x:b0,y:b1,", "03000000a30600000c04000000000000,Saitek P2900,a:b1,b:b2,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b3,", "03000000300f00001001000000000000,Saitek P480 Rumble Pad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,", "03000000a30600000b04000000010000,Saitek P990 Dual Analog Pad,a:b1,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b8,x:b0,y:b3,", "03000000a30600000b04000000000000,Saitek P990,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b3,", "03000000a30600002106000000000000,Saitek PS1000,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b0,y:b3,", "03000000a306000020f6000000000000,Saitek PS2700,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b0,y:b3,", "03000000300f00001101000000000000,Saitek Rumble Pad,a:b2,b:b3,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,", "0300000000050000289b000000000000,Saturn_Adapter_2.0,a:b1,b:b2,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b0,y:b3,", "030000009b2800000500000000000000,Saturn_Adapter_2.0,a:b1,b:b2,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b0,y:b3,", "030000008f0e00000800000000000000,SpeedLink Strike FX,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000c01100000591000000000000,Speedlink Torid,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000d11800000094000000000000,Stadia Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:b12,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:b11,rightx:a3,righty:a4,start:b9,x:b2,y:b3,", "03000000110100003114000000000000,SteelSeries Stratus Duo,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", "03000000381000001814000000000000,SteelSeries Stratus XL,a:b0,b:b1,back:b18,dpdown:b13,dpleft:b14,dpright:b15,dpup:b12,guide:b19,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b2,y:b3,", "03000000110100001914000000000000,SteelSeries,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:,leftstick:b13,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:,rightstick:b14,righttrigger:b7,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", "03000000d620000011a7000000000000,Switch,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000004f04000007d0000000000000,T Mini Wireless,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000fa1900000706000000000000,Team 5,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000b50700001203000000000000,Techmobility X6-38V,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,", "030000004f0400000ed0000000000000,ThrustMaster eSwap PRO Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000004f04000015b3000000000000,Thrustmaster Dual Analog 4,a:b0,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b1,y:b3,", "030000004f04000023b3000000000000,Thrustmaster Dual Trigger 3-in-1,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000004f04000004b3000000000000,Thrustmaster Firestorm Dual Power 3,a:b0,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b1,y:b3,", "030000004f04000000b3000000000000,Thrustmaster Firestorm Dual Power,a:b0,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b11,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b10,x:b1,y:b3,", "03000000666600000488000000000000,TigerGame PS/PS2 Game Controller Adapter,a:b2,b:b1,back:b9,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,", "03000000d62000006000000000000000,Tournament PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000005f140000c501000000000000,Trust Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000b80500000210000000000000,Trust Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000d90400000200000000000000,TwinShock PS2,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", "03000000300f00000701000000000000,USB 4-Axis 12-Button Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", "03000000341a00002308000000000000,USB Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "030000005509000000b4000000000000,USB Gamepad,a:b10,b:b11,back:b5,dpdown:b1,dpleft:b2,dpright:b3,dpup:b0,guide:b14,leftshoulder:b8,leftstick:b6,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b9,rightstick:b7,righttrigger:a5,rightx:a2,righty:a3,start:b4,x:b12,y:b13,", "030000006b1400000203000000000000,USB Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "03000000790000000a00000000000000,USB Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b3,y:b0,", "03000000f0250000c183000000000000,USB Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000ff1100004133000000000000,USB Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a4,righty:a2,start:b9,x:b3,y:b0,", "03000000632500002305000000000000,USB Vibration Joystick (BM),a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000790000001b18000000000000,Venom Arcade Joystick,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "030000006f0e00000302000000000000,Victrix Pro Fight Stick for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "030000006f0e00000702000000000000,Victrix Pro Fight Stick for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "03000000450c00002043000000000000,XEOX Gamepad SL-6556-BK,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "03000000341a00000608000000000000,Xeox,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "03000000172700004431000000000000,XiaoMi Game Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b20,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a7,rightx:a2,righty:a5,start:b11,x:b3,y:b4,", "03000000790000004f18000000000000,ZD-T Android,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,", "03000000120c0000101e000000000000,ZEROPLUS P4 Wired Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000d81d00000f00000000000000,iBUFFALO BSGP1204 Series,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000d81d00001000000000000000,iBUFFALO BSGP1204P Series,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000830500006020000000000000,iBuffalo SNES Controller,a:b0,b:b1,back:b6,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b7,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000830500006020000000000000,iBuffalo SNES Controller,a:b1,b:b0,back:b6,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b7,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "030000004f04000003d0000000000000,run'n'drive,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b7,leftshoulder:a3,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:a4,rightstick:b11,righttrigger:b5,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000101c0000171c000000000000,uRage Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", #endif #if defined(__MACOSX__) "03000000c82d00000090000001000000,8BitDo FC30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000090000001000000,8BitDo FC30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001038000000010000,8BitDo FC30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001038000000010000,8BitDo FC30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000650000001000000,8BitDo M30 Gamepad,a:b0,b:b1,back:b10,guide:b2,leftshoulder:b6,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a5,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000650000001000000,8BitDo M30 Gamepad,a:b1,b:b0,back:b10,guide:b2,leftshoulder:b6,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a5,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00005106000000010000,8BitDo M30 Gamepad,a:b0,b:b1,back:b10,guide:b2,leftshoulder:b6,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00005106000000010000,8BitDo M30 Gamepad,a:b1,b:b0,back:b10,guide:b2,leftshoulder:b6,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001590000001000000,8BitDo N30 Pro 2,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001590000001000000,8BitDo N30 Pro 2,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00006528000000010000,8BitDo N30 Pro 2,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00006528000000010000,8BitDo N30 Pro 2,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "030000003512000012ab000001000000,8BitDo NES30 Gamepad,a:b0,b:b1,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "030000003512000012ab000001000000,8BitDo NES30 Gamepad,a:b1,b:b0,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000022000000090000001000000,8BitDo NES30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000022000000090000001000000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000203800000900000000010000,8BitDo NES30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000203800000900000000010000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000102800000900000000000000,8BitDo SFC30 Gamepad,a:b0,b:b1,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000102800000900000000000000,8BitDo SFC30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001290000001000000,8BitDo SN30 Gamepad,a:b0,b:b1,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001290000001000000,8BitDo SN30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000260000001000000,8BitDo SN30 Pro+,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000260000001000000,8BitDo SN30 Pro+,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000261000000010000,8BitDo SN30 Pro+,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000261000000010000,8BitDo SN30 Pro+,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000160000001000000,8BitDo SN30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000160000001000000,8BitDo SN30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001890000001000000,8BitDo Zero 2,a:b0,b:b1,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001890000001000000,8BitDo Zero 2,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00003032000000010000,8BitDo Zero 2,a:b0,b:b1,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00003032000000010000,8BitDo Zero 2,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000a00500003232000008010000,8BitDo Zero Gamepad,a:b0,b:b1,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000a00500003232000008010000,8BitDo Zero Gamepad,a:b1,b:b2,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000a00500003232000009010000,8BitDo Zero Gamepad,a:b0,b:b1,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000a00500003232000009010000,8BitDo Zero Gamepad,a:b1,b:b0,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000d62000002a79000000010000,BDA PS4 Fightpad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000008305000031b0000000000000,Cideko AK08b,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000260900008888000088020000,Cyber Gadget GameCube Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:a5,rightx:a2,righty:a3~,start:b7,x:b2,y:b3,", "03000000a306000022f6000001030000,Cyborg V.3 Rumble Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:+a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:-a3,rightx:a2,righty:a4,start:b9,x:b0,y:b3,", "030000000d0f00008400000000010000,Fighting Commander,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000000d0f00008500000000010000,Fighting Commander,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000790000000600000000000000,G-Shark GP-702,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b3,y:b0,", "0500000047532047616d657061640000,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "03000000c01100000140000000010000,GameStop PS4 Fun Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000ad1b000001f9000000000000,Gamestop BB-070 X360 Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", "030000000d0f00005f00000000000000,HORI Fighting Commander 4 PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f00005e00000000000000,HORI Fighting Commander 4 PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f00004d00000000000000,HORI Gem Pad 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f0000aa00000072050000,HORI Real Arcade Pro,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "030000000d0f00006e00000000010000,HORIPAD 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f00006600000000010000,HORIPAD 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000000d0f00006600000000000000,HORIPAD FPS PLUS 4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000000d0f00005f00000000010000,Hori Fighting Commander 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f00005e00000000010000,Hori Fighting Commander 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000008f0e00001330000011010000,HuiJia SNES Controller,a:b4,b:b2,back:b16,dpdown:+a2,dpleft:-a0,dpright:+a0,dpup:-a2,leftshoulder:b12,rightshoulder:b14,start:b18,x:b6,y:b0,", "030000006d04000016c2000000020000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006d04000016c2000000030000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006d04000016c2000014040000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006d04000016c2000000000000,Logitech F310 Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* Guide button doesn't seem to be sent in DInput mode. */ "030000006d04000018c2000000000000,Logitech F510 Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006d0400001fc2000000000000,Logitech F710 Gamepad (XInput),a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", "030000006d04000019c2000000000000,Logitech Wireless Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* This includes F710 in DInput mode and the "Logitech Cordless RumblePad 2", at the very least. */ "03000000d8140000cecf000000000000,MC Cthulhu,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "03000000c62400002a89000000010000,MOGA XP5-A Plus,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b21,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", "03000000c62400002b89000000010000,MOGA XP5-A Plus,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", "03000000380700005032000000010000,Mad Catz FightPad PRO (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000380700005082000000010000,Mad Catz FightPad PRO (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000380700008433000000010000,Mad Catz FightStick TE S+ (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000380700008483000000010000,Mad Catz FightStick TE S+ (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000790000004418000000010000,Mayflash GameCube Controller,a:b1,b:b2,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,", "0300000025090000e803000000000000,Mayflash Wii Classic Controller,a:b1,b:b0,back:b8,dpdown:b13,dpleft:b12,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,", "03000000790000000018000000000000,Mayflash WiiU Pro Game Controller Adapter (DInput),a:b4,b:b8,back:b32,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b16,leftstick:b40,lefttrigger:b24,leftx:a0,lefty:a4,rightshoulder:b20,rightstick:b44,righttrigger:b28,rightx:a8,righty:a12,start:b36,x:b0,y:b12,", "030000001008000001e5000006010000,NEXT SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b6,start:b9,x:b3,y:b0,", "03000000550900001472000025050000,NVIDIA Controller v01.04,a:b0,b:b1,back:b17,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b15,leftshoulder:b4,leftstick:b7,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a5,start:b6,x:b2,y:b3,", "030000007e0500000920000000000000,Nintendo Switch Pro Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "030000006f0e00000901000002010000,PDP Versus Fighting Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "030000004c0500006802000000000000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,", "030000004c0500006802000000010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,", "030000004c050000a00b000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000004c050000c405000000000000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000004c050000c405000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000004c050000cc09000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000008f0e00000300000000000000,Piranha xtreme,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", "030000008916000000fd000000000000,Razer Onza TE,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", "03000000321500000204000000010000,Razer Panthera (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000321500000104000000010000,Razer Panthera (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000321500000010000000010000,Razer RAIJU,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000321500000507000001010000,Razer Raiju Mobile,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b21,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", "03000000321500000011000000010000,Razer Raion Fightpad for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000321500000009000000020000,Razer Serval,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", "0300000032150000030a000000000000,Razer Wildcat,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", "03000000790000001100000000000000,Retrolink Classic Controller,a:b2,b:b1,back:b8,leftshoulder:b4,leftx:a3,lefty:a4,rightshoulder:b5,start:b9,x:b3,y:b0,", "03000000790000001100000006010000,Retrolink SNES Controller,a:b2,b:b1,back:b8,dpdown:+a4,dpleft:-a3,dpright:+a3,dpup:-a4,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,", "030000006b140000130d000000010000,Revolution Pro Controller 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000006b140000010d000000010000,Revolution Pro Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000003512000021ab000000000000,SFC30 Joystick,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,", "03000000457500002211000000010000,SZMY-POWER PC Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000b40400000a01000000000000,Sega Saturn USB Gamepad,a:b0,b:b1,back:b5,guide:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b8,x:b3,y:b4,", "03000000811700007e05000000000000,Sega Saturn,a:b2,b:b4,dpdown:b16,dpleft:b15,dpright:b14,dpup:b17,leftshoulder:b8,lefttrigger:a5,leftx:a0,lefty:a2,rightshoulder:b9,righttrigger:a4,start:b13,x:b0,y:b6,", "030000004c050000cc09000000000000,Sony DualShock 4 V2,a:b1,b:b2,back:b13,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000004c050000a00b000000000000,Sony DualShock 4 Wireless Adaptor,a:b1,b:b2,back:b13,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000d11800000094000000010000,Stadia Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", "030000005e0400008e02000001000000,Steam Virtual Gamepad,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", "03000000110100002014000000000000,SteelSeries Nimbus,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b12,x:b2,y:b3,", "03000000110100002014000001000000,SteelSeries Nimbus,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3~,x:b2,y:b3,", "03000000381000002014000001000000,SteelSeries Nimbus,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3~,x:b2,y:b3,", "03000000110100001714000000000000,SteelSeries Stratus XL,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3~,start:b12,x:b2,y:b3,", "03000000110100001714000020010000,SteelSeries Stratus XL,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3~,start:b12,x:b2,y:b3,", "030000004f0400000ed0000000020000,ThrustMaster eSwap PRO Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000004f04000015b3000000000000,Thrustmaster Dual Analog 3.2,a:b0,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b1,y:b3,", "030000004f04000000b3000000000000,Thrustmaster Firestorm Dual Power,a:b0,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b11,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:b7,rightx:a2,righty:a3,start:b10,x:b1,y:b3,", "03000000bd12000015d0000000000000,Tomee SNES USB Controller,a:b2,b:b1,back:b8,leftshoulder:b4,leftx:a0,lefty:a1,rightshoulder:b5,start:b9,x:b3,y:b0,", "03000000bd12000015d0000000010000,Tomee SNES USB Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,", "03000000100800000100000000000000,Twin USB Joystick,a:b4,b:b2,back:b16,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b12,leftstick:b20,lefttrigger:b8,leftx:a0,lefty:a2,rightshoulder:b14,rightstick:b22,righttrigger:b10,rightx:a6,righty:a4,start:b18,x:b6,y:b0,", "030000006f0e00000302000025040000,Victrix Pro Fight Stick for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "030000006f0e00000702000003060000,Victrix Pro Fight Stick for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "050000005769696d6f74652028303000,Wii Remote,a:b4,b:b5,back:b7,dpdown:b3,dpleft:b0,dpright:b1,dpup:b2,guide:b8,leftshoulder:b11,lefttrigger:b12,leftx:a0,lefty:a1,start:b6,x:b10,y:b9,", "050000005769696d6f74652028313800,Wii U Pro Controller,a:b16,b:b15,back:b7,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b8,leftshoulder:b19,leftstick:b23,lefttrigger:b21,leftx:a0,lefty:a1,rightshoulder:b20,rightstick:b24,righttrigger:b22,rightx:a2,righty:a3,start:b6,x:b18,y:b17,", "030000005e0400008e02000000000000,X360 Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", "03000000c6240000045d000000000000,Xbox 360 Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", "030000005e040000050b000003090000,Xbox Elite Wireless Controller,a:b0,b:b1,back:b38,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", "030000005e040000d102000000000000,Xbox One Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", "030000005e040000dd02000000000000,Xbox One Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", "030000005e040000e302000000000000,Xbox One Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", "030000005e040000e002000000000000,Xbox Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000005e040000e002000003090000,Xbox Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000005e040000ea02000000000000,Xbox Wireless Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,", "030000005e040000fd02000003090000,Xbox Wireless Controller,a:b0,b:b1,back:b16,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b15,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", "03000000172700004431000029010000,XiaoMi Game Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b15,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a6,rightx:a2,righty:a5,start:b11,x:b3,y:b4,", "03000000120c0000100e000000010000,ZEROPLUS P4 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000120c0000101e000000010000,ZEROPLUS P4 Wired Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000830500006020000000010000,iBuffalo SNES Controller,a:b0,b:b1,back:b6,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b7,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000830500006020000000010000,iBuffalo SNES Controller,a:b1,b:b0,back:b6,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b7,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000830500006020000000000000,iBuffalo USB 2-axis 8-button Gamepad,a:b1,b:b0,back:b6,leftshoulder:b4,leftx:a0,lefty:a1,rightshoulder:b5,start:b7,x:b3,y:b2,", #endif #if defined(__LINUX__) "03000000c82d00000090000011010000,8BitDo FC30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000090000011010000,8BitDo FC30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d00001038000000010000,8BitDo FC30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d00001038000000010000,8BitDo FC30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000650000011010000,8BitDo M30 Gamepad,a:b0,b:b1,back:b10,guide:b2,leftshoulder:b6,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a5,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d00005106000000010000,8BitDo M30 Gamepad,a:b1,b:b0,back:b10,guide:b2,leftshoulder:b6,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001590000011010000,8BitDo N30 Pro 2,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001590000011010000,8BitDo N30 Pro 2,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d00006528000000010000,8BitDo N30 Pro 2,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d00006528000000010000,8BitDo N30 Pro 2,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "030000003512000012ab000010010000,8BitDo NES30 Gamepad,a:b0,b:b1,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "030000003512000012ab000010010000,8BitDo NES30 Gamepad,a:b1,b:b0,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000022000000090000011010000,8BitDo NES30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000022000000090000011010000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000190000011010000,8BitDo NES30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000190000011010000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000203800000900000000010000,8BitDo NES30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000203800000900000000010000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d00002038000000010000,8BitDo NES30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d00002038000000010000,8BitDo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d00000061000000010000,8BitDo SF30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d00000061000000010000,8BitDo SF30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000102800000900000000010000,8BitDo SFC30 Gamepad,a:b0,b:b1,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000102800000900000000010000,8BitDo SFC30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d00003028000000010000,8BitDo SFC30 Gamepad,a:b0,b:b1,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d00003028000000010000,8BitDo SFC30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000260000011010000,8BitDo SN30 Pro+,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000260000011010000,8BitDo SN30 Pro+,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d00000261000000010000,8BitDo SN30 Pro+,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d00000261000000010000,8BitDo SN30 Pro+,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000160000011010000,8BitDo SN30 Pro,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00000160000011010000,8BitDo SN30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "030000003512000020ab000010010000,8BitDo SNES30 Gamepad,a:b0,b:b1,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "030000003512000020ab000010010000,8BitDo SNES30 Gamepad,a:b1,b:b0,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000202800000900000000010000,8BitDo SNES30 Gamepad,a:b0,b:b1,back:b10,dpdown:b122,dpleft:b119,dpright:b120,dpup:b117,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000202800000900000000010000,8BitDo SNES30 Gamepad,a:b1,b:b0,back:b10,dpdown:b122,dpleft:b119,dpright:b120,dpup:b117,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001890000011010000,8BitDo Zero 2,a:b0,b:b1,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001890000011010000,8BitDo Zero 2,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d00003032000000010000,8BitDo Zero 2,a:b0,b:b1,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d00003032000000010000,8BitDo Zero 2,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000a00500003232000001000000,8BitDo Zero Gamepad,a:b0,b:b1,back:b10,dpdown:b122,dpleft:b119,dpright:b120,dpup:b117,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000a00500003232000001000000,8BitDo Zero Gamepad,a:b1,b:b0,back:b10,dpdown:b122,dpleft:b119,dpright:b120,dpup:b117,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000a00500003232000008010000,8BitDo Zero Gamepad,a:b0,b:b1,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000a00500003232000008010000,8BitDo Zero Gamepad,a:b1,b:b0,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001290000011010000,8Bitdo SN30 Gamepad,a:b0,b:b1,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000c82d00001290000011010000,8Bitdo SN30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d00006228000000010000,8Bitdo SN30 Gamepad,a:b0,b:b1,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b3,y:b4,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d00006228000000010000,8Bitdo SN30 Gamepad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000050b00000045000031000000,ASUS Gamepad,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b10,x:b2,y:b3,", "05000000050b00000045000040000000,ASUS Gamepad,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b10,x:b2,y:b3,", "030000006f0e00003901000020060000,Afterglow Controller for Xbox One,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000006f0e00003901000000430000,Afterglow Prismatic Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000006f0e00001302000000010000,Afterglow,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "03000000100000008200000011010000,Akishop Customs PS360+ v1.66,a:b1,b:b2,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "03000000d62000002a79000011010000,BDA PS4 Fightpad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000b40400000a01000000010000,CYPRESS USB Gamepad,a:b0,b:b1,back:b5,guide:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b8,x:b3,y:b4,", "03000000ffff0000ffff000000010000,Chinese-made Xbox Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b5,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b2,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b3,y:b4,", "03000000e82000006058000001010000,Cideko AK08b,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000260900008888000000010000,Cyber Gadget GameCube Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:a5,rightx:a2,righty:a3~,start:b7,x:b2,y:b3,", "03000000a306000022f6000011010000,Cyborg V.3 Rumble Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:+a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:-a3,rightx:a2,righty:a4,start:b9,x:b0,y:b3,", "03000000790000000600000010010000,DragonRise Inc. Generic USB Joystick,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b3,y:b0,", "030000006f0e00003001000001010000,EA Sports PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "0300000079000000d418000000010000,GPD Win 2 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "0500000047532067616d657061640000,GS Gamepad,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "03000000341a000005f7000010010000,GameCube {HuiJia USB box},a:b1,b:b2,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,", "03000000bc2000000055000011010000,GameSir G3w,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", "0500000047532047616d657061640000,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "03000000c01100000140000011010000,GameStop PS4 Fun Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000006f0e00000104000000010000,Gamestop Logic3 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000008f0e00000800000010010000,Gasia Co. Ltd PS(R) Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "030000006f0e00001304000000010000,Generic X-Box pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "03000000f0250000c183000010010000,Goodbetterbest Ltd USB Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000280400000140000000010000,Gravis Gamepad Pro USB ,a:b1,b:b2,back:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "030000008f0e00000610000000010000,GreenAsia Electronics 4Axes 12Keys Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b9,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b10,righttrigger:b5,rightx:a3,righty:a2,start:b11,x:b3,y:b0,", "030000008f0e00001200000010010000,GreenAsia Inc. USB Joystick,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b2,y:b3,", "03000000c9110000f055000011010000,HJC Game GAMEPAD,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "030000000d0f00001000000011010000,HORI CO. LTD. FIGHTING STICK 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "030000000d0f00002200000011010000,HORI CO. LTD. REAL ARCADE Pro.V3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "030000000d0f00006a00000011010000,HORI CO. LTD. Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000000d0f00006b00000011010000,HORI CO. LTD. Real Arcade Pro.4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f00008400000011010000,HORI Fighting Commander,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000000d0f00008500000010010000,HORI Fighting Commander,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f0000aa00000011010000,HORI Real Arcade Pro,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "030000000d0f00006e00000011010000,HORIPAD 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f00006600000011010000,HORIPAD 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000000d0f00006700000001010000,HORIPAD ONE,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "06000000adde0000efbe000002010000,Hidromancer Game Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "03000000d81400000862000011010000,HitBox (PS3/PC) Analog Mode,a:b1,b:b2,back:b8,guide:b9,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b12,x:b0,y:b3,", "030000000d0f00005f00000011010000,Hori Fighting Commander 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000000d0f00005e00000011010000,Hori Fighting Commander 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000000d0f00008600000002010000,Hori Fighting Commander,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "03000000ad1b000001f5000033050000,Hori Pad EX Turbo 2,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000008f0e00001330000010010000,HuiJia SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b9,x:b3,y:b0,", "03000000242e00008816000001010000,Hyperkin X91,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "03000000d80400008200000003000000,IMS PCU#0 Gamepad Interface,a:b1,b:b0,back:b4,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,start:b5,x:b3,y:b2,", "03000000fd0500000030000000010000,InterAct GoPad I-73000 (Fighting Game Layout),a:b3,b:b4,back:b6,leftx:a0,lefty:a1,rightshoulder:b2,righttrigger:b5,start:b7,x:b0,y:b1,", "030000006e0500000320000010010000,JC-U3613M - DirectInput Mode,a:b2,b:b3,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3,start:b11,x:b0,y:b1,", "03000000300f00001001000010010000,Jess Tech Dual Analog Rumble Pad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,", "03000000ba2200002010000001010000,Jess Technology USB Game Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", "030000006f0e00000103000000020000,Logic3 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000006d04000019c2000010010000,Logitech Cordless RumblePad 2,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006d04000016c2000010010000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006d04000016c2000011010000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006d0400001dc2000014400000,Logitech F310 Gamepad (XInput),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000006d0400001ec2000020200000,Logitech F510 Gamepad (XInput),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000006d04000019c2000011010000,Logitech F710 Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* Guide button doesn't seem to be sent in DInput mode. */ "030000006d0400001fc2000005030000,Logitech F710 Gamepad (XInput),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000006d04000015c2000010010000,Logitech Logitech Extreme 3D,a:b0,b:b4,back:b6,guide:b8,leftshoulder:b9,leftstick:h0.8,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:h0.2,start:b7,x:b2,y:b5,", "030000006d04000018c2000010010000,Logitech RumblePad 2,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006d04000011c2000010010000,Logitech WingMan Cordless RumblePad,a:b0,b:b1,back:b2,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b5,leftshoulder:b6,lefttrigger:b9,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b10,rightx:a3,righty:a4,start:b8,x:b3,y:b4,", "03000000c62400002b89000011010000,MOGA XP5-A Plus,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", "05000000c62400002a89000000010000,MOGA XP5-A Plus,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b22,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", "03000000250900006688000000010000,MP-8866 Super Dual Box,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,", "05000000380700006652000025010000,Mad Catz C.T.R.L.R ,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000380700005032000011010000,Mad Catz FightPad PRO (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000380700005082000011010000,Mad Catz FightPad PRO (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000380700008433000011010000,Mad Catz FightStick TE S+ (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000380700008483000011010000,Mad Catz FightStick TE S+ (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000ad1b00002ef0000090040000,Mad Catz Fightpad SFxT,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,lefttrigger:a2,rightshoulder:b5,righttrigger:a5,start:b7,x:b2,y:b3,", "03000000380700003847000090040000,Mad Catz Wired Xbox 360 Controller (SFIV),a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "03000000380700001647000010040000,Mad Catz Wired Xbox 360 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "03000000ad1b000016f0000090040000,Mad Catz Xbox 360 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "03000000380700008034000011010000,Mad Catz fightstick (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000380700008084000011010000,Mad Catz fightstick (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000380700001888000010010000,MadCatz PC USB Wired Stick 8818,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000380700003888000010010000,MadCatz PC USB Wired Stick 8838,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:a0,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000790000004418000010010000,Mayflash GameCube Controller,a:b1,b:b2,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,", "03000000780000000600000010010000,Microntek USB Joystick,a:b2,b:b1,back:b8,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b3,y:b0,", "030000005e0400000e00000000010000,Microsoft SideWinder,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,rightshoulder:b7,start:b8,x:b3,y:b4,", "030000005e0400008e02000004010000,Microsoft X-Box 360 pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000005e0400008e02000062230000,Microsoft X-Box 360 pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000005e040000d102000003020000,Microsoft X-Box One pad v2,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000005e040000d102000001010000,Microsoft X-Box One pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000005e0400008502000000010000,Microsoft X-Box pad (Japan),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b5,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b2,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b3,y:b4,", "030000005e0400008902000021010000,Microsoft X-Box pad v2 (US),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b5,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b2,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b3,y:b4,", "05000000d6200000ad0d000001000000,Moga Pro,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", "030000006b140000010c000010010000,NACON GC-400ES,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "030000001008000001e5000010010000,NEXT SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b6,start:b9,x:b3,y:b0,", "03000000550900001472000011010000,NVIDIA Controller v01.04,a:b0,b:b1,back:b14,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b17,leftshoulder:b4,leftstick:b7,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a5,start:b6,x:b2,y:b3,", "03000000550900001072000011010000,NVIDIA Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b13,leftshoulder:b4,leftstick:b8,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", "03000000451300000830000010010000,NYKO CORE,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000790000004318000010010000,Nintendo GameCube Controller,a:b1,b:b2,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000790000004318000010010000,Nintendo GameCube Controller,a:b1,b:b0,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b2,y:b3,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "030000007e0500003703000000016800,Nintendo GameCube Controller,a:b0,b:b2,dpdown:b6,dpleft:b4,dpright:b5,dpup:b7,lefttrigger:a4,leftx:a0,lefty:a1~,rightshoulder:b9,righttrigger:a5,rightx:a2,righty:a3~,start:b8,x:b1,y:b3,", "050000007e0500000920000001000000,Nintendo Switch Pro Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "050000007e0500003003000001000000,Nintendo Wii Remote Pro Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,", "05000000010000000100000003000000,Nintendo Wiimote,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "030000000d0500000308000010010000,Nostromo n45 Dual Analog Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b12,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b10,x:b2,y:b3,", "05000000362800000100000002010000,OUYA Game Controller,a:b0,b:b3,dpdown:b9,dpleft:b10,dpright:b11,dpup:b8,guide:b14,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,x:b1,y:b2,", "05000000362800000100000003010000,OUYA Game Controller,a:b0,b:b3,dpdown:b9,dpleft:b10,dpright:b11,dpup:b8,guide:b14,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,x:b1,y:b2,", "030000005e0400000202000000010000,Old Xbox pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b5,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b2,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b3,y:b4,", "03000000ff1100003133000010010000,PC Game Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "030000006f0e00006401000001010000,PDP Battlefield One,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000006f0e00000901000011010000,PDP Versus Fighting Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "03000000ff1100004133000010010000,PS2 Controller,a:b2,b:b1,back:b8,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b3,y:b0,", "03000000341a00003608000011010000,PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000004c0500006802000010010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,", "030000004c0500006802000010810000,PS3 Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", "030000004c0500006802000011010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:a12,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:a13,rightx:a2,righty:a3,start:b3,x:b15,y:b12,", "030000004c0500006802000011810000,PS3 Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", "030000006f0e00001402000011010000,PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000008f0e00000300000010010000,PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "050000004c0500006802000000010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:a12,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:a13,rightx:a2,righty:a3,start:b3,x:b15,y:b12,", "050000004c0500006802000000800000,PS3 Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", "050000004c0500006802000000810000,PS3 Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", "05000000504c415953544154494f4e00,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,", "060000004c0500006802000000010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,", "030000004c050000a00b000011010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000004c050000a00b000011810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", "030000004c050000c405000011010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000004c050000c405000011810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", "030000004c050000cc09000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000004c050000cc09000011010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000004c050000cc09000011810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", "050000004c050000c405000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "050000004c050000c405000000810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", "050000004c050000cc09000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "050000004c050000cc09000000810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", "050000004c050000cc09000001800000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,", "030000004c050000da0c000011010000,Playstation Controller,a:b2,b:b1,back:b8,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b3,y:b0,", "03000000c62400000053000000010000,PowerA,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "03000000300f00001211000011010000,QanBa Arcade JoyStick,a:b2,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b5,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b6,start:b9,x:b1,y:b3,", "030000008916000001fd000024010000,Razer Onza Classic Edition,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000008916000000fd000024010000,Razer Onza Tournament Edition,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "03000000321500000204000011010000,Razer Panthera (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000321500000104000011010000,Razer Panthera (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000321500000010000011010000,Razer RAIJU,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000321500000507000000010000,Razer Raiju Mobile,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b21,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", "03000000321500000011000011010000,Razer Raion Fightpad for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000008916000000fe000024010000,Razer Sabertooth,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "03000000c6240000045d000024010000,Razer Sabertooth,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "03000000c6240000045d000025010000,Razer Sabertooth,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "03000000321500000009000011010000,Razer Serval,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", "050000003215000000090000163a0000,Razer Serval,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", "0300000032150000030a000001010000,Razer Wildcat,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "0300000000f000000300000000010000,RetroPad,a:b1,b:b5,back:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b3,x:b0,y:b4,", "03000000790000001100000010010000,Retrolink SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,", "030000006b140000130d000011010000,Revolution Pro Controller 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000006b140000010d000011010000,Revolution Pro Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000006f0e00001e01000011010000,Rock Candy PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000006f0e00004601000001010000,Rock Candy Xbox One Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000006f0e00001f01000000010000,Rock Candy,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "03000000632500007505000010010000,SHANWAN PS3/PC Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000341a00000908000010010000,SL-6566,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "03000000457500002211000010010000,SZMY-POWER PC Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000a306000023f6000011010000,Saitek Cyborg V.1 Game Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b0,y:b3,", "03000000a30600000cff000010010000,Saitek P2500 Force Rumble Pad,a:b2,b:b3,back:b11,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a3,righty:a2,x:b0,y:b1,", "03000000a30600000c04000011010000,Saitek P2900 Wireless Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b12,x:b0,y:b3,", "03000000a30600000901000000010000,Saitek P880,a:b2,b:b3,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a3,righty:a2,x:b0,y:b1,", "03000000a30600000b04000000010000,Saitek P990 Dual Analog Pad,a:b1,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b8,x:b0,y:b3,", "03000000a306000018f5000010010000,Saitek PLC Saitek P3200 Rumble Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b0,y:b3,", "03000000c01600008704000011010000,Serial/Keyboard/Mouse/Joystick,a:b12,b:b10,back:b4,dpdown:b2,dpleft:b3,dpright:b1,dpup:b0,leftshoulder:b9,leftstick:b14,lefttrigger:b6,leftx:a1,lefty:a0,rightshoulder:b8,rightstick:b15,righttrigger:b7,rightx:a2,righty:a3,start:b5,x:b13,y:b11,", "03000000f025000021c1000010010000,ShanWan Gioteck PS3 Wired Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000632500002305000010010000,ShanWan USB Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,", "03000000250900000500000000010000,Sony PS2 pad with SmartJoy adapter,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,", "030000005e0400008e02000020200000,SpeedLink XEOX Pro Analog Gamepad pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000005e0400008e02000073050000,Speedlink TORID Wireless Gamepad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "03000000d11800000094000011010000,Stadia Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", "03000000de2800000112000001000000,Steam Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,", "03000000de2800000211000001000000,Steam Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,", "03000000de2800004211000001000000,Steam Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,", "03000000de280000fc11000001000000,Steam Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "05000000de2800000212000001000000,Steam Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,", "05000000de2800000511000001000000,Steam Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,", "05000000de2800000611000001000000,Steam Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,", "03000000de280000ff11000001000000,Steam Virtual Gamepad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "0500000011010000311400001b010000,SteelSeries Stratus Duo,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b32,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", "03000000ad1b000038f0000090040000,Street Fighter IV FightStick TE,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "03000000666600000488000000010000,Super Joy Box 5 Pro,a:b2,b:b1,back:b9,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,", "0300000000f00000f100000000010000,Super RetroPort,a:b1,b:b5,back:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b3,x:b0,y:b4,", "030000004f0400000ed0000011010000,ThrustMaster eSwap PRO Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000004f04000020b3000010010000,Thrustmaster 2 in 1 DT,a:b0,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b1,y:b3,", "030000004f04000015b3000010010000,Thrustmaster Dual Analog 4,a:b0,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b1,y:b3,", "030000004f04000023b3000000010000,Thrustmaster Dual Trigger 3-in-1,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "030000004f04000000b3000010010000,Thrustmaster Firestorm Dual Power,a:b0,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b11,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b10,x:b1,y:b3,", "030000004f04000009d0000000010000,Thrustmaster Run N Drive Wireless PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "030000004f04000008d0000000010000,Thrustmaster Run N Drive Wireless,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000bd12000015d0000010010000,Tomee SNES USB Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,", "03000000d814000007cd000011010000,Toodles 2008 Chimp PC/PS3,a:b0,b:b1,back:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b9,x:b3,y:b2,", "03000000100800000100000010010000,Twin USB PS2 Adapter,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", "03000000100800000300000010010000,USB Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,", "03000000790000000600000007010000,USB Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b3,y:b0,", "03000000790000001100000000010000,USB Gamepad1,a:b2,b:b1,back:b8,dpdown:a0,dpleft:a1,dpright:a2,dpup:a4,start:b9,", "05000000ac0500003232000001000000,VR-BOX,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b2,y:b3,", "030000006f0e00000302000011010000,Victrix Pro Fight Stick for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "030000006f0e00000702000011010000,Victrix Pro Fight Stick for PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,", "030000005e0400008e02000010010000,X360 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000005e0400008e02000014010000,X360 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000005e0400001907000000010000,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000005e0400009102000007010000,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000005e040000a102000000010000,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000005e040000a102000007010000,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "03000000450c00002043000010010000,XEOX Gamepad SL-6556-BK,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", "xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "0000000058626f782033363020576900,Xbox 360 Wireless Controller,a:b0,b:b1,back:b14,dpdown:b11,dpleft:b12,dpright:b13,dpup:b10,guide:b7,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b6,x:b2,y:b3,", "030000005e040000a102000014010000,Xbox 360 Wireless Receiver (XBOX),a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "0000000058626f782047616d65706100,Xbox Gamepad (userspace driver),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,", "050000005e040000050b000002090000,Xbox One Elite Series 2,a:b0,b:b1,back:b136,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a6,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a5,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", "050000005e040000050b000003090000,Xbox One Elite Series 2,a:b0,b:b1,back:b121,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", "030000005e040000ea02000000000000,Xbox One Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "030000005e040000ea02000001030000,Xbox One Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "050000005e040000e002000003090000,Xbox One Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,", "050000005e040000fd02000003090000,Xbox One Wireless Controller,a:b0,b:b1,back:b15,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,guide:b16,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,", "05000000172700004431000029010000,XiaoMi Game Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b20,leftshoulder:b6,leftstick:b13,lefttrigger:a7,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a6,rightx:a2,righty:a5,start:b11,x:b3,y:b4,", "03000000c0160000e105000001010000,Xin-Mo Xin-Mo Dual Arcade,a:b4,b:b3,back:b6,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b9,leftshoulder:b2,leftx:a0,lefty:a1,rightshoulder:b5,start:b7,x:b1,y:b0,", "03000000120c0000100e000011010000,ZEROPLUS P4 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000120c0000101e000011010000,ZEROPLUS P4 Wired Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,", "03000000666600006706000000010000,boom PSX to PC Converter,a:b2,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,leftshoulder:b6,leftstick:b9,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b10,righttrigger:b5,rightx:a2,righty:a3,start:b11,x:b3,y:b0,", "030000000d0f00000d00000000010000,hori,a:b0,b:b6,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b3,leftx:b4,lefty:b5,rightshoulder:b7,start:b9,x:b1,y:b2,", "03000000830500006020000010010000,iBuffalo SNES Controller,a:b0,b:b1,back:b6,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b7,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "03000000830500006020000010010000,iBuffalo SNES Controller,a:b1,b:b0,back:b6,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b7,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "050000006964726f69643a636f6e0000,idroid:con,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", "03000000b50700001503000010010000,impact,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,", "030000009b2800000300000001010000,raphnet.net 4nes4snes v1.5,a:b0,b:b4,back:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b3,x:b1,y:b5,", #endif #if defined(__ANDROID__) "05000000c82d000006500000ffff3f00,8BitDo M30 Gamepad,a:b0,b:b1,back:b4,guide:b17,leftshoulder:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b10,righttrigger:a4,start:b6,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000006500000ffff3f00,8BitDo M30 Gamepad,a:b1,b:b0,back:b4,guide:b17,leftshoulder:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b10,righttrigger:a4,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000051060000ffff3f00,8BitDo M30 Gamepad,a:b0,b:b1,back:b4,guide:b17,leftshoulder:b9,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,righttrigger:a5,start:b6,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000051060000ffff3f00,8BitDo M30 Gamepad,a:b1,b:b0,back:b4,guide:b17,leftshoulder:b9,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,righttrigger:a5,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000015900000ffff3f00,8BitDo N30 Pro 2,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000015900000ffff3f00,8BitDo N30 Pro 2,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000065280000ffff3f00,8BitDo N30 Pro 2,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b17,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000065280000ffff3f00,8BitDo N30 Pro 2,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b17,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "050000000220000000900000ffff3f00,8BitDo NES30 Pro,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "050000000220000000900000ffff3f00,8BitDo NES30 Pro,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "050000002038000009000000ffff3f00,8BitDo NES30 Pro,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "050000002038000009000000ffff3f00,8BitDo NES30 Pro,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000000600000ffff3f00,8BitDo SF30 Pro,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:b15,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:b16,rightx:a2,righty:a3,start:b6,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000000600000ffff3f00,8BitDo SF30 Pro,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:b15,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:b16,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000000610000ffff3f00,8BitDo SF30 Pro,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000000610000ffff3f00,8BitDo SF30 Pro,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000012900000ffff3f00,8BitDo SN30 Gamepad,a:b0,b:b1,back:b4,leftshoulder:b9,leftx:a0,lefty:a1,rightshoulder:b10,start:b6,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000012900000ffff3f00,8BitDo SN30 Gamepad,a:b1,b:b0,back:b4,leftshoulder:b9,leftx:a0,lefty:a1,rightshoulder:b10,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000062280000ffff3f00,8BitDo SN30 Gamepad,a:b0,b:b1,back:b4,leftshoulder:b9,leftx:a0,lefty:a1,rightshoulder:b10,start:b6,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000062280000ffff3f00,8BitDo SN30 Gamepad,a:b1,b:b0,back:b4,leftshoulder:b9,leftx:a0,lefty:a1,rightshoulder:b10,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000002600000ffff0f00,8BitDo SN30 Pro+,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b17,leftshoulder:b9,leftstick:b7,lefttrigger:b15,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:b16,rightx:a2,righty:a3,start:b6,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000002600000ffff0f00,8BitDo SN30 Pro+,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b17,leftshoulder:b9,leftstick:b7,lefttrigger:b15,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:b16,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000001600000ffff3f00,8BitDo SN30 Pro,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000001600000ffff3f00,8BitDo SN30 Pro,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "050000002028000009000000ffff3f00,8BitDo SNES30 Gamepad,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "050000002028000009000000ffff3f00,8BitDo SNES30 Gamepad,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "050000003512000020ab000000780f00,8BitDo SNES30 Gamepad,a:b20,b:b21,back:b30,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b26,rightshoulder:b27,start:b31,x:b23,y:b24,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "050000003512000020ab000000780f00,8BitDo SNES30 Gamepad,a:b21,b:b20,back:b30,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b26,rightshoulder:b27,start:b31,x:b24,y:b23,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000018900000ffff0f00,8BitDo Zero 2,a:b0,b:b1,back:b4,leftshoulder:b9,leftx:a0,lefty:a1,rightshoulder:b10,start:b6,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000018900000ffff0f00,8BitDo Zero 2,a:b1,b:b0,back:b4,leftshoulder:b9,leftx:a0,lefty:a1,rightshoulder:b10,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000030320000ffff0f00,8BitDo Zero 2,a:b0,b:b1,back:b4,leftshoulder:b9,leftx:a0,lefty:a1,rightshoulder:b10,start:b6,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000c82d000030320000ffff0f00,8BitDo Zero 2,a:b1,b:b0,back:b4,leftshoulder:b9,leftx:a0,lefty:a1,rightshoulder:b10,start:b6,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "05000000d6020000e5890000dfff3f00,GPD XD Plus,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a4,rightx:a2,righty:a5,start:b6,x:b2,y:b3,", "0500000031366332860c44aadfff0f00,GS Gamepad,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:b15,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:b16,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", "05000000bc20000000550000ffff3f00,GameSir G3w,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", "050000005509000003720000cf7f3f00,NVIDIA Controller v01.01,a:b0,b:b1,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", "050000005509000010720000ffff3f00,NVIDIA Controller v01.03,a:b0,b:b1,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", "050000005509000014720000df7f3f00,NVIDIA Controller v01.04,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a4,rightx:a2,righty:a5,start:b6,x:b2,y:b3,", "050000007e05000009200000ffff0f00,Nintendo Switch Pro Controller,a:b1,b:b0,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:b15,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:b16,rightx:a2,righty:a3,start:b6,x:b3,y:b2,sdk>=:29,", "050000007e05000009200000ffff0f00,Nintendo Switch Pro Controller,a:b0,b:b1,back:b15,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b3,leftstick:b4,lefttrigger:b9,leftx:a0,lefty:a1,rightshoulder:b18,rightstick:b6,righttrigger:b10,rightx:a2,righty:a3,start:b16,x:b17,y:b2,sdk<=:28,", /* Extremely slow in Bluetooth mode on Android */ "050000004c05000068020000dfff3f00,PS3 Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", "030000004c050000cc09000000006800,PS4 Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", "050000004c050000c4050000fffe3f00,PS4 Controller,a:b1,b:b17,back:b15,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b3,leftstick:b4,lefttrigger:+a3,leftx:a0,lefty:a1,rightshoulder:b18,rightstick:b6,righttrigger:+a4,rightx:a2,righty:a5,start:b16,x:b0,y:b2,", "050000004c050000cc090000fffe3f00,PS4 Controller,a:b1,b:b17,back:b15,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b3,leftstick:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b18,rightstick:b6,righttrigger:a4,rightx:a2,righty:a5,start:b16,x:b0,y:b2,", "050000004c050000cc090000ffff3f00,PS4 Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", "05000000f8270000bf0b0000ffff3f00,Razer Kishi,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", "050000003215000005070000ffff3f00,Razer Raiju Mobile,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", "050000003215000007070000ffff3f00,Razer Raiju Mobile,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", "050000003215000000090000bf7f3f00,Razer Serval,a:b0,b:b1,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,x:b2,y:b3,", "05000000de2800000511000001000000,Steam Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,", "05000000de2800000611000001000000,Steam Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,", "050000004f0400000ed00000fffe3f00,ThrustMaster eSwap PRO Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", "050000005e040000e00200000ffe3f00,Xbox One Wireless Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b3,leftstick:b15,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b18,rightstick:b16,righttrigger:a5,rightx:a3,righty:a4,start:b10,x:b17,y:b2,", "050000005e040000fd020000ffff3f00,Xbox One Wireless Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", "050000005e04000091020000ff073f00,Xbox Wireless Controller,a:b0,b:b1,back:b4,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a3,righty:a4,start:b6,x:b2,y:b3,", /* The DPAD doesn't seem to work on this controller on Android TV? */ "050000001727000044310000ffff3f00,XiaoMi Game Controller,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b9,leftstick:b7,lefttrigger:a7,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a6,rightx:a2,righty:a5,start:b6,x:b2,y:b3,", "0500000083050000602000000ffe0000,iBuffalo SNES Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b15,rightshoulder:b16,start:b10,x:b2,y:b3,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "0500000083050000602000000ffe0000,iBuffalo SNES Controller,a:b1,b:b0,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b15,rightshoulder:b16,start:b10,x:b3,y:b2,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", #endif #if defined(SDL_JOYSTICK_MFI) "05000000ac050000010000004f066d01,*,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,leftshoulder:b4,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a5,rightx:a3,righty:a4,x:b2,y:b3,", "05000000ac05000001000000cf076d01,*,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,x:b2,y:b3,", "05000000ac050000020000004f066d02,*,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,leftshoulder:b4,rightshoulder:b5,x:b2,y:b3,", "050000004c050000cc090000df070000,DUALSHOCK 4 Wireless Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b2,y:b3,", "05000000ac0500000300000043006d03,Remote,a:b0,b:b2,leftx:a0,lefty:a1,", "05000000de2800000511000001000000,Steam Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,", "05000000de2800000611000001000000,Steam Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,", "050000005e040000e0020000df070000,Xbox Wireless Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b2,y:b3,", #endif #if defined(SDL_JOYSTICK_VIRTUAL) "00000000000000000000000000007601,Virtual Joystick,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", #endif #if defined(SDL_JOYSTICK_EMSCRIPTEN) "default,Standard Gamepad,a:b0,b:b1,back:b8,dpdown:b13,dpleft:b14,dpright:b15,dpup:b12,guide:b16,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,", #endif "hidapi,*,a:b0,b:b1,back:b4,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b5,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,", NULL }; /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/SDL_gamecontrollerdb.h
C
apache-2.0
209,588
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" /* This is the joystick API for Simple DirectMedia Layer */ #include "SDL.h" #include "SDL_atomic.h" #include "SDL_events.h" #include "SDL_sysjoystick.h" #include "SDL_assert.h" #include "SDL_hints.h" #if !SDL_EVENTS_DISABLED #include "../events/SDL_events_c.h" #endif #include "../video/SDL_sysvideo.h" #include "hidapi/SDL_hidapijoystick_c.h" /* This is included in only one place because it has a large static list of controllers */ #include "controller_type.h" #ifdef __WIN32__ /* Needed for checking for input remapping programs */ #include "../core/windows/SDL_windows.h" #undef UNICODE /* We want ASCII functions */ #include <tlhelp32.h> #endif #if SDL_JOYSTICK_VIRTUAL #include "./virtual/SDL_virtualjoystick_c.h" #endif static SDL_JoystickDriver *SDL_joystick_drivers[] = { #ifdef SDL_JOYSTICK_RAWINPUT /* Before WINDOWS_ driver, as WINDOWS wants to check if this driver is handling things */ /* Also before HIDAPI, as HIDAPI wants to check if this driver is handling things */ &SDL_RAWINPUT_JoystickDriver, #endif #ifdef SDL_JOYSTICK_HIDAPI /* Before WINDOWS_ driver, as WINDOWS wants to check if this driver is handling things */ &SDL_HIDAPI_JoystickDriver, #endif #if defined(SDL_JOYSTICK_WGI) &SDL_WGI_JoystickDriver, #endif #if defined(SDL_JOYSTICK_DINPUT) || defined(SDL_JOYSTICK_XINPUT) &SDL_WINDOWS_JoystickDriver, #endif #ifdef SDL_JOYSTICK_LINUX &SDL_LINUX_JoystickDriver, #endif #ifdef SDL_JOYSTICK_IOKIT &SDL_DARWIN_JoystickDriver, #endif #if (defined(__IPHONEOS__) || defined(__TVOS__)) && !defined(SDL_JOYSTICK_DISABLED) &SDL_IOS_JoystickDriver, #endif #ifdef SDL_JOYSTICK_ANDROID &SDL_ANDROID_JoystickDriver, #endif #ifdef SDL_JOYSTICK_EMSCRIPTEN &SDL_EMSCRIPTEN_JoystickDriver, #endif #ifdef SDL_JOYSTICK_HAIKU &SDL_HAIKU_JoystickDriver, #endif #ifdef SDL_JOYSTICK_USBHID /* !!! FIXME: "USBHID" is a generic name, and doubly-confusing with HIDAPI next to it. This is the *BSD interface, rename this. */ &SDL_BSD_JoystickDriver, #endif #ifdef SDL_JOYSTICK_VIRTUAL &SDL_VIRTUAL_JoystickDriver, #endif #ifdef SDL_JOYSTICK_ALIOS &SDL_AliOS_JoystickDriver, #endif #if defined(SDL_JOYSTICK_DUMMY) || defined(SDL_JOYSTICK_DISABLED) &SDL_DUMMY_JoystickDriver #endif }; static SDL_bool SDL_joystick_allows_background_events = SDL_FALSE; static SDL_Joystick *SDL_joysticks = NULL; static SDL_bool SDL_updating_joystick = SDL_FALSE; static SDL_mutex *SDL_joystick_lock = NULL; /* This needs to support recursive locks */ static SDL_atomic_t SDL_next_joystick_instance_id; static int SDL_joystick_player_count = 0; static SDL_JoystickID *SDL_joystick_players = NULL; void SDL_LockJoysticks(void) { if (SDL_joystick_lock) { SDL_LockMutex(SDL_joystick_lock); } } void SDL_UnlockJoysticks(void) { if (SDL_joystick_lock) { SDL_UnlockMutex(SDL_joystick_lock); } } static int SDL_FindFreePlayerIndex() { int player_index; for (player_index = 0; player_index < SDL_joystick_player_count; ++player_index) { if (SDL_joystick_players[player_index] == -1) { return player_index; } } return player_index; } static int SDL_GetPlayerIndexForJoystickID(SDL_JoystickID instance_id) { int player_index; for (player_index = 0; player_index < SDL_joystick_player_count; ++player_index) { if (instance_id == SDL_joystick_players[player_index]) { break; } } if (player_index == SDL_joystick_player_count) { player_index = -1; } return player_index; } static SDL_JoystickID SDL_GetJoystickIDForPlayerIndex(int player_index) { if (player_index < 0 || player_index >= SDL_joystick_player_count) { return -1; } return SDL_joystick_players[player_index]; } static SDL_bool SDL_SetJoystickIDForPlayerIndex(int player_index, SDL_JoystickID instance_id) { SDL_JoystickID existing_instance = SDL_GetJoystickIDForPlayerIndex(player_index); SDL_JoystickDriver *driver; int device_index; int existing_player_index; if (player_index < 0) { return SDL_FALSE; } if (player_index >= SDL_joystick_player_count) { SDL_JoystickID *new_players = (SDL_JoystickID *)SDL_realloc(SDL_joystick_players, (player_index + 1)*sizeof(*SDL_joystick_players)); if (!new_players) { SDL_OutOfMemory(); return SDL_FALSE; } SDL_joystick_players = new_players; SDL_memset(&SDL_joystick_players[SDL_joystick_player_count], 0xFF, (player_index - SDL_joystick_player_count + 1) * sizeof(SDL_joystick_players[0])); SDL_joystick_player_count = player_index + 1; } else if (SDL_joystick_players[player_index] == instance_id) { /* Joystick is already assigned the requested player index */ return SDL_TRUE; } /* Clear the old player index */ existing_player_index = SDL_GetPlayerIndexForJoystickID(instance_id); if (existing_player_index >= 0) { SDL_joystick_players[existing_player_index] = -1; } SDL_joystick_players[player_index] = instance_id; /* Update the driver with the new index */ device_index = SDL_JoystickGetDeviceIndexFromInstanceID(instance_id); if (SDL_GetDriverAndJoystickIndex(device_index, &driver, &device_index)) { driver->SetDevicePlayerIndex(device_index, player_index); } /* Move any existing joystick to another slot */ if (existing_instance >= 0) { SDL_SetJoystickIDForPlayerIndex(SDL_FindFreePlayerIndex(), existing_instance); } return SDL_TRUE; } static void SDLCALL SDL_JoystickAllowBackgroundEventsChanged(void *userdata, const char *name, const char *oldValue, const char *hint) { if (hint && *hint == '1') { SDL_joystick_allows_background_events = SDL_TRUE; } else { SDL_joystick_allows_background_events = SDL_FALSE; } } int SDL_JoystickInit(void) { int i, status; SDL_GameControllerInitMappings(); /* Create the joystick list lock */ if (!SDL_joystick_lock) { SDL_joystick_lock = SDL_CreateMutex(); } /* See if we should allow joystick events while in the background */ SDL_AddHintCallback(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, SDL_JoystickAllowBackgroundEventsChanged, NULL); #if !SDL_EVENTS_DISABLED if (SDL_InitSubSystem(SDL_INIT_EVENTS) < 0) { return -1; } #endif /* !SDL_EVENTS_DISABLED */ status = -1; for (i = 0; i < SDL_arraysize(SDL_joystick_drivers); ++i) { if (SDL_joystick_drivers[i]->Init() >= 0) { status = 0; } } return status; } /* * Count the number of joysticks attached to the system */ int SDL_NumJoysticks(void) { int i, total_joysticks = 0; SDL_LockJoysticks(); for (i = 0; i < SDL_arraysize(SDL_joystick_drivers); ++i) { total_joysticks += SDL_joystick_drivers[i]->GetCount(); } SDL_UnlockJoysticks(); return total_joysticks; } /* * Return the next available joystick instance ID * This may be called by drivers from multiple threads, unprotected by any locks */ SDL_JoystickID SDL_GetNextJoystickInstanceID() { return SDL_AtomicIncRef(&SDL_next_joystick_instance_id); } /* * Get the driver and device index for an API device index * This should be called while the joystick lock is held, to prevent another thread from updating the list */ SDL_bool SDL_GetDriverAndJoystickIndex(int device_index, SDL_JoystickDriver **driver, int *driver_index) { int i, num_joysticks, total_joysticks = 0; if (device_index >= 0) { for (i = 0; i < SDL_arraysize(SDL_joystick_drivers); ++i) { num_joysticks = SDL_joystick_drivers[i]->GetCount(); if (device_index < num_joysticks) { *driver = SDL_joystick_drivers[i]; *driver_index = device_index; return SDL_TRUE; } device_index -= num_joysticks; total_joysticks += num_joysticks; } } SDL_SetError("There are %d joysticks available", total_joysticks); return SDL_FALSE; } /* * Get the implementation dependent name of a joystick */ const char * SDL_JoystickNameForIndex(int device_index) { SDL_JoystickDriver *driver; const char *name = NULL; SDL_LockJoysticks(); if (SDL_GetDriverAndJoystickIndex(device_index, &driver, &device_index)) { name = driver->GetDeviceName(device_index); } SDL_UnlockJoysticks(); /* FIXME: Really we should reference count this name so it doesn't go away after unlock */ return name; } /* * Get the player index of a joystick, or -1 if it's not available */ int SDL_JoystickGetDevicePlayerIndex(int device_index) { int player_index; SDL_LockJoysticks(); player_index = SDL_GetPlayerIndexForJoystickID(SDL_JoystickGetDeviceInstanceID(device_index)); SDL_UnlockJoysticks(); return player_index; } /* * Return true if this joystick is known to have all axes centered at zero * This isn't generally needed unless the joystick never generates an initial axis value near zero, * e.g. it's emulating axes with digital buttons */ static SDL_bool SDL_JoystickAxesCenteredAtZero(SDL_Joystick *joystick) { static Uint32 zero_centered_joysticks[] = { MAKE_VIDPID(0x0e8f, 0x3013), /* HuiJia SNES USB adapter */ MAKE_VIDPID(0x05a0, 0x3232), /* 8Bitdo Zero Gamepad */ }; int i; Uint32 id = MAKE_VIDPID(SDL_JoystickGetVendor(joystick), SDL_JoystickGetProduct(joystick)); /*printf("JOYSTICK '%s' VID/PID 0x%.4x/0x%.4x AXES: %d\n", joystick->name, vendor, product, joystick->naxes);*/ if (joystick->naxes == 2) { /* Assume D-pad or thumbstick style axes are centered at 0 */ return SDL_TRUE; } for (i = 0; i < SDL_arraysize(zero_centered_joysticks); ++i) { if (id == zero_centered_joysticks[i]) { return SDL_TRUE; } } return SDL_FALSE; } /* * Open a joystick for use - the index passed as an argument refers to * the N'th joystick on the system. This index is the value which will * identify this joystick in future joystick events. * * This function returns a joystick identifier, or NULL if an error occurred. */ SDL_Joystick * SDL_JoystickOpen(int device_index) { SDL_JoystickDriver *driver; SDL_JoystickID instance_id; SDL_Joystick *joystick; SDL_Joystick *joysticklist; const char *joystickname = NULL; SDL_LockJoysticks(); printf("SDL_JoystickOpen\n"); if (!SDL_GetDriverAndJoystickIndex(device_index, &driver, &device_index)) { SDL_UnlockJoysticks(); printf("SDL_GetDriverAndJoystickIndex\n"); return NULL; } joysticklist = SDL_joysticks; /* If the joystick is already open, return it * it is important that we have a single joystick * for each instance id */ instance_id = driver->GetDeviceInstanceID(device_index); while (joysticklist) { if (instance_id == joysticklist->instance_id) { joystick = joysticklist; ++joystick->ref_count; SDL_UnlockJoysticks(); printf("return joystick\n"); return joystick; } joysticklist = joysticklist->next; } /* Create and initialize the joystick */ joystick = (SDL_Joystick *) SDL_calloc(sizeof(*joystick), 1); if (joystick == NULL) { SDL_OutOfMemory(); SDL_UnlockJoysticks(); return NULL; } joystick->driver = driver; joystick->instance_id = instance_id; joystick->attached = SDL_TRUE; joystick->epowerlevel = SDL_JOYSTICK_POWER_UNKNOWN; printf("SDL_JoystickOpen\n"); if (driver->Open(joystick, device_index) < 0) { SDL_free(joystick); SDL_UnlockJoysticks(); return NULL; } joystickname = driver->GetDeviceName(device_index); if (joystickname) { joystick->name = SDL_strdup(joystickname); } else { joystick->name = NULL; } joystick->guid = driver->GetDeviceGUID(device_index); if (joystick->naxes > 0) { joystick->axes = (SDL_JoystickAxisInfo *) SDL_calloc(joystick->naxes, sizeof(SDL_JoystickAxisInfo)); } if (joystick->nhats > 0) { joystick->hats = (Uint8 *) SDL_calloc(joystick->nhats, sizeof(Uint8)); } if (joystick->nballs > 0) { joystick->balls = (struct balldelta *) SDL_calloc(joystick->nballs, sizeof(*joystick->balls)); } if (joystick->nbuttons > 0) { joystick->buttons = (Uint8 *) SDL_calloc(joystick->nbuttons, sizeof(Uint8)); } if (((joystick->naxes > 0) && !joystick->axes) || ((joystick->nhats > 0) && !joystick->hats) || ((joystick->nballs > 0) && !joystick->balls) || ((joystick->nbuttons > 0) && !joystick->buttons)) { SDL_OutOfMemory(); SDL_JoystickClose(joystick); SDL_UnlockJoysticks(); return NULL; } /* If this joystick is known to have all zero centered axes, skip the auto-centering code */ if (SDL_JoystickAxesCenteredAtZero(joystick)) { int i; for (i = 0; i < joystick->naxes; ++i) { joystick->axes[i].has_initial_value = SDL_TRUE; } } joystick->is_game_controller = SDL_IsGameController(device_index); /* Add joystick to list */ ++joystick->ref_count; /* Link the joystick in the list */ joystick->next = SDL_joysticks; SDL_joysticks = joystick; SDL_UnlockJoysticks(); printf("driver->Update\n"); driver->Update(joystick); return joystick; } int SDL_JoystickAttachVirtual(SDL_JoystickType type, int naxes, int nbuttons, int nhats) { #if SDL_JOYSTICK_VIRTUAL return SDL_JoystickAttachVirtualInner(type, naxes, nbuttons, nhats); #else return SDL_SetError("SDL not built with virtual-joystick support"); #endif } int SDL_JoystickDetachVirtual(int device_index) { #if SDL_JOYSTICK_VIRTUAL SDL_JoystickDriver *driver; SDL_LockJoysticks(); if (SDL_GetDriverAndJoystickIndex(device_index, &driver, &device_index)) { if (driver == &SDL_VIRTUAL_JoystickDriver) { const int result = SDL_JoystickDetachVirtualInner(device_index); SDL_UnlockJoysticks(); return result; } } SDL_UnlockJoysticks(); return SDL_SetError("Virtual joystick not found at provided index"); #else return SDL_SetError("SDL not built with virtual-joystick support"); #endif } SDL_bool SDL_JoystickIsVirtual(int device_index) { #if SDL_JOYSTICK_VIRTUAL SDL_JoystickDriver *driver; int driver_device_index; SDL_bool is_virtual = SDL_FALSE; SDL_LockJoysticks(); if (SDL_GetDriverAndJoystickIndex(device_index, &driver, &driver_device_index)) { if (driver == &SDL_VIRTUAL_JoystickDriver) { is_virtual = SDL_TRUE; } } SDL_UnlockJoysticks(); return is_virtual; #else return SDL_FALSE; #endif } int SDL_JoystickSetVirtualAxis(SDL_Joystick * joystick, int axis, Sint16 value) { #if SDL_JOYSTICK_VIRTUAL return SDL_JoystickSetVirtualAxisInner(joystick, axis, value); #else return SDL_SetError("SDL not built with virtual-joystick support"); #endif } int SDL_JoystickSetVirtualButton(SDL_Joystick * joystick, int button, Uint8 value) { #if SDL_JOYSTICK_VIRTUAL return SDL_JoystickSetVirtualButtonInner(joystick, button, value); #else return SDL_SetError("SDL not built with virtual-joystick support"); #endif } int SDL_JoystickSetVirtualHat(SDL_Joystick * joystick, int hat, Uint8 value) { #if SDL_JOYSTICK_VIRTUAL return SDL_JoystickSetVirtualHatInner(joystick, hat, value); #else return SDL_SetError("SDL not built with virtual-joystick support"); #endif } /* * Checks to make sure the joystick is valid. */ SDL_bool SDL_PrivateJoystickValid(SDL_Joystick * joystick) { SDL_bool valid; if (joystick == NULL) { SDL_SetError("Joystick hasn't been opened yet"); valid = SDL_FALSE; } else { valid = SDL_TRUE; } return valid; } SDL_bool SDL_PrivateJoystickGetAutoGamepadMapping(int device_index, SDL_GamepadMapping * out) { SDL_JoystickDriver *driver; SDL_bool is_ok = SDL_FALSE; SDL_LockJoysticks(); if (SDL_GetDriverAndJoystickIndex(device_index, &driver, &device_index)) { is_ok = driver->GetGamepadMapping(device_index, out); } SDL_UnlockJoysticks(); return is_ok; } /* * Get the number of multi-dimensional axis controls on a joystick */ int SDL_JoystickNumAxes(SDL_Joystick * joystick) { if (!SDL_PrivateJoystickValid(joystick)) { return -1; } return joystick->naxes; } /* * Get the number of hats on a joystick */ int SDL_JoystickNumHats(SDL_Joystick * joystick) { if (!SDL_PrivateJoystickValid(joystick)) { return -1; } return joystick->nhats; } /* * Get the number of trackballs on a joystick */ int SDL_JoystickNumBalls(SDL_Joystick * joystick) { if (!SDL_PrivateJoystickValid(joystick)) { return -1; } return joystick->nballs; } /* * Get the number of buttons on a joystick */ int SDL_JoystickNumButtons(SDL_Joystick * joystick) { if (!SDL_PrivateJoystickValid(joystick)) { return -1; } return joystick->nbuttons; } /* * Get the current state of an axis control on a joystick */ Sint16 SDL_JoystickGetAxis(SDL_Joystick * joystick, int axis) { Sint16 state; if (!SDL_PrivateJoystickValid(joystick)) { return 0; } if (axis < joystick->naxes) { state = joystick->axes[axis].value; } else { SDL_SetError("Joystick only has %d axes", joystick->naxes); state = 0; } return state; } /* * Get the initial state of an axis control on a joystick */ SDL_bool SDL_JoystickGetAxisInitialState(SDL_Joystick * joystick, int axis, Sint16 *state) { if (!SDL_PrivateJoystickValid(joystick)) { return SDL_FALSE; } if (axis >= joystick->naxes) { SDL_SetError("Joystick only has %d axes", joystick->naxes); return SDL_FALSE; } if (state) { *state = joystick->axes[axis].initial_value; } return joystick->axes[axis].has_initial_value; } /* * Get the current state of a hat on a joystick */ Uint8 SDL_JoystickGetHat(SDL_Joystick * joystick, int hat) { Uint8 state; if (!SDL_PrivateJoystickValid(joystick)) { return 0; } if (hat < joystick->nhats) { state = joystick->hats[hat]; } else { SDL_SetError("Joystick only has %d hats", joystick->nhats); state = 0; } return state; } /* * Get the ball axis change since the last poll */ int SDL_JoystickGetBall(SDL_Joystick * joystick, int ball, int *dx, int *dy) { int retval; if (!SDL_PrivateJoystickValid(joystick)) { return -1; } retval = 0; if (ball < joystick->nballs) { if (dx) { *dx = joystick->balls[ball].dx; } if (dy) { *dy = joystick->balls[ball].dy; } joystick->balls[ball].dx = 0; joystick->balls[ball].dy = 0; } else { return SDL_SetError("Joystick only has %d balls", joystick->nballs); } return retval; } /* * Get the current state of a button on a joystick */ Uint8 SDL_JoystickGetButton(SDL_Joystick * joystick, int button) { Uint8 state; if (!SDL_PrivateJoystickValid(joystick)) { return 0; } if (button < joystick->nbuttons) { state = joystick->buttons[button]; } else { SDL_SetError("Joystick only has %d buttons", joystick->nbuttons); state = 0; } return state; } /* * Return if the joystick in question is currently attached to the system, * \return SDL_FALSE if not plugged in, SDL_TRUE if still present. */ SDL_bool SDL_JoystickGetAttached(SDL_Joystick * joystick) { if (!SDL_PrivateJoystickValid(joystick)) { return SDL_FALSE; } return joystick->attached; } /* * Get the instance id for this opened joystick */ SDL_JoystickID SDL_JoystickInstanceID(SDL_Joystick * joystick) { if (!SDL_PrivateJoystickValid(joystick)) { return -1; } return joystick->instance_id; } /* * Return the SDL_Joystick associated with an instance id. */ SDL_Joystick * SDL_JoystickFromInstanceID(SDL_JoystickID instance_id) { SDL_Joystick *joystick; SDL_LockJoysticks(); for (joystick = SDL_joysticks; joystick; joystick = joystick->next) { if (joystick->instance_id == instance_id) { break; } } SDL_UnlockJoysticks(); return joystick; } /** * Return the SDL_Joystick associated with a player index. */ SDL_Joystick * SDL_JoystickFromPlayerIndex(int player_index) { SDL_JoystickID instance_id; SDL_Joystick *joystick; SDL_LockJoysticks(); instance_id = SDL_GetJoystickIDForPlayerIndex(player_index); for (joystick = SDL_joysticks; joystick; joystick = joystick->next) { if (joystick->instance_id == instance_id) { break; } } SDL_UnlockJoysticks(); return joystick; } /* * Get the friendly name of this joystick */ const char * SDL_JoystickName(SDL_Joystick * joystick) { if (!SDL_PrivateJoystickValid(joystick)) { return NULL; } return joystick->name; } /** * Get the player index of an opened joystick, or -1 if it's not available */ int SDL_JoystickGetPlayerIndex(SDL_Joystick * joystick) { int player_index; if (!SDL_PrivateJoystickValid(joystick)) { return -1; } SDL_LockJoysticks(); player_index = SDL_GetPlayerIndexForJoystickID(joystick->instance_id); SDL_UnlockJoysticks(); return player_index; } /** * Set the player index of an opened joystick */ void SDL_JoystickSetPlayerIndex(SDL_Joystick * joystick, int player_index) { if (!SDL_PrivateJoystickValid(joystick)) { return; } SDL_LockJoysticks(); SDL_SetJoystickIDForPlayerIndex(player_index, joystick->instance_id); SDL_UnlockJoysticks(); } int SDL_JoystickRumble(SDL_Joystick * joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble, Uint32 duration_ms) { int result; if (!SDL_PrivateJoystickValid(joystick)) { return -1; } SDL_LockJoysticks(); if (low_frequency_rumble == joystick->low_frequency_rumble && high_frequency_rumble == joystick->high_frequency_rumble) { /* Just update the expiration */ result = 0; } else { result = joystick->driver->Rumble(joystick, low_frequency_rumble, high_frequency_rumble); } /* Save the rumble value regardless of success, so we don't spam the driver */ joystick->low_frequency_rumble = low_frequency_rumble; joystick->high_frequency_rumble = high_frequency_rumble; if ((low_frequency_rumble || high_frequency_rumble) && duration_ms) { joystick->rumble_expiration = SDL_GetTicks() + SDL_min(duration_ms, SDL_MAX_RUMBLE_DURATION_MS); if (!joystick->rumble_expiration) { joystick->rumble_expiration = 1; } } else { joystick->rumble_expiration = 0; } SDL_UnlockJoysticks(); return result; } /* * Close a joystick previously opened with SDL_JoystickOpen() */ void SDL_JoystickClose(SDL_Joystick * joystick) { SDL_Joystick *joysticklist; SDL_Joystick *joysticklistprev; if (!SDL_PrivateJoystickValid(joystick)) { return; } SDL_LockJoysticks(); /* First decrement ref count */ if (--joystick->ref_count > 0) { SDL_UnlockJoysticks(); return; } if (SDL_updating_joystick) { SDL_UnlockJoysticks(); return; } if (joystick->rumble_expiration) { SDL_JoystickRumble(joystick, 0, 0, 0); } joystick->driver->Close(joystick); joystick->hwdata = NULL; joysticklist = SDL_joysticks; joysticklistprev = NULL; while (joysticklist) { if (joystick == joysticklist) { if (joysticklistprev) { /* unlink this entry */ joysticklistprev->next = joysticklist->next; } else { SDL_joysticks = joystick->next; } break; } joysticklistprev = joysticklist; joysticklist = joysticklist->next; } SDL_free(joystick->name); /* Free the data associated with this joystick */ SDL_free(joystick->axes); SDL_free(joystick->hats); SDL_free(joystick->balls); SDL_free(joystick->buttons); SDL_free(joystick); SDL_UnlockJoysticks(); } void SDL_JoystickQuit(void) { int i; /* Make sure we're not getting called in the middle of updating joysticks */ SDL_LockJoysticks(); while (SDL_updating_joystick) { SDL_UnlockJoysticks(); SDL_Delay(1); SDL_LockJoysticks(); } /* Stop the event polling */ while (SDL_joysticks) { SDL_joysticks->ref_count = 1; SDL_JoystickClose(SDL_joysticks); } /* Quit the joystick setup */ for (i = 0; i < SDL_arraysize(SDL_joystick_drivers); ++i) { SDL_joystick_drivers[i]->Quit(); } if (SDL_joystick_players) { SDL_free(SDL_joystick_players); SDL_joystick_players = NULL; SDL_joystick_player_count = 0; } SDL_UnlockJoysticks(); #if !SDL_EVENTS_DISABLED SDL_QuitSubSystem(SDL_INIT_EVENTS); #endif SDL_DelHintCallback(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, SDL_JoystickAllowBackgroundEventsChanged, NULL); if (SDL_joystick_lock) { SDL_mutex *mutex = SDL_joystick_lock; SDL_joystick_lock = NULL; SDL_DestroyMutex(mutex); } SDL_GameControllerQuitMappings(); } static SDL_bool SDL_PrivateJoystickShouldIgnoreEvent() { if (SDL_joystick_allows_background_events) { return SDL_FALSE; } if (SDL_HasWindows() && SDL_GetKeyboardFocus() == NULL) { /* We have windows but we don't have focus, ignore the event. */ return SDL_TRUE; } return SDL_FALSE; } /* These are global for SDL_sysjoystick.c and SDL_events.c */ void SDL_PrivateJoystickAdded(SDL_JoystickID device_instance) { SDL_JoystickDriver *driver; int driver_device_index; int player_index = -1; int device_index = SDL_JoystickGetDeviceIndexFromInstanceID(device_instance); if (device_index < 0) { printf("device_index : %d\n", device_index); return; } printf("SDL_PrivateJoystickAdded\n"); SDL_LockJoysticks(); if (SDL_GetDriverAndJoystickIndex(device_index, &driver, &driver_device_index)) { player_index = driver->GetDevicePlayerIndex(driver_device_index); } if (player_index < 0 && SDL_IsGameController(device_index)) { player_index = SDL_FindFreePlayerIndex(); } if (player_index >= 0) { SDL_SetJoystickIDForPlayerIndex(player_index, device_instance); } SDL_UnlockJoysticks(); #if !SDL_EVENTS_DISABLED { SDL_Event event; event.type = SDL_JOYDEVICEADDED; printf("send SDL_JOYDEVICEADDED\n"); if (SDL_GetEventState(event.type) == SDL_ENABLE) { event.jdevice.which = device_index; printf("SDL_PushEvent\n"); SDL_PushEvent(&event); } } #endif /* !SDL_EVENTS_DISABLED */ } /* * If there is an existing add event in the queue, it needs to be modified * to have the right value for which, because the number of controllers in * the system is now one less. */ static void UpdateEventsForDeviceRemoval() { int i, num_events; SDL_Event *events; SDL_bool isstack; num_events = SDL_PeepEvents(NULL, 0, SDL_PEEKEVENT, SDL_JOYDEVICEADDED, SDL_JOYDEVICEADDED); if (num_events <= 0) { return; } events = SDL_small_alloc(SDL_Event, num_events, &isstack); if (!events) { return; } num_events = SDL_PeepEvents(events, num_events, SDL_GETEVENT, SDL_JOYDEVICEADDED, SDL_JOYDEVICEADDED); for (i = 0; i < num_events; ++i) { --events[i].jdevice.which; } SDL_PeepEvents(events, num_events, SDL_ADDEVENT, 0, 0); SDL_small_free(events, isstack); } static void SDL_PrivateJoystickForceRecentering(SDL_Joystick *joystick) { int i; /* Tell the app that everything is centered/unpressed... */ for (i = 0; i < joystick->naxes; i++) { if (joystick->axes[i].has_initial_value) { SDL_PrivateJoystickAxis(joystick, i, joystick->axes[i].zero); } } for (i = 0; i < joystick->nbuttons; i++) { SDL_PrivateJoystickButton(joystick, i, 0); } for (i = 0; i < joystick->nhats; i++) { SDL_PrivateJoystickHat(joystick, i, SDL_HAT_CENTERED); } } void SDL_PrivateJoystickRemoved(SDL_JoystickID device_instance) { SDL_Joystick *joystick = NULL; int player_index; #if !SDL_EVENTS_DISABLED SDL_Event event; #endif /* Find this joystick... */ for (joystick = SDL_joysticks; joystick; joystick = joystick->next) { if (joystick->instance_id == device_instance) { SDL_PrivateJoystickForceRecentering(joystick); joystick->attached = SDL_FALSE; break; } } #if !SDL_EVENTS_DISABLED SDL_zero(event); event.type = SDL_JOYDEVICEREMOVED; if (SDL_GetEventState(event.type) == SDL_ENABLE) { event.jdevice.which = device_instance; SDL_PushEvent(&event); } UpdateEventsForDeviceRemoval(); #endif /* !SDL_EVENTS_DISABLED */ SDL_LockJoysticks(); player_index = SDL_GetPlayerIndexForJoystickID(device_instance); if (player_index >= 0) { SDL_joystick_players[player_index] = -1; } SDL_UnlockJoysticks(); } int SDL_PrivateJoystickAxis(SDL_Joystick * joystick, Uint8 axis, Sint16 value) { int posted; SDL_JoystickAxisInfo *info; /* Make sure we're not getting garbage or duplicate events */ if (axis >= joystick->naxes) { return 0; } info = &joystick->axes[axis]; if (!info->has_initial_value || (!info->has_second_value && (info->initial_value <= -32767 || info->initial_value == 32767) && SDL_abs(value) < (SDL_JOYSTICK_AXIS_MAX / 4))) { info->initial_value = value; info->value = value; info->zero = value; info->has_initial_value = SDL_TRUE; } else if (value == info->value) { return 0; } else { info->has_second_value = SDL_TRUE; } if (!info->sent_initial_value) { /* Make sure we don't send motion until there's real activity on this axis */ const int MAX_ALLOWED_JITTER = SDL_JOYSTICK_AXIS_MAX / 80; /* ShanWan PS3 controller needed 96 */ if (SDL_abs(value - info->value) <= MAX_ALLOWED_JITTER) { return 0; } info->sent_initial_value = SDL_TRUE; info->value = ~value; /* Just so we pass the check above */ SDL_PrivateJoystickAxis(joystick, axis, info->initial_value); } /* We ignore events if we don't have keyboard focus, except for centering * events. */ if (SDL_PrivateJoystickShouldIgnoreEvent()) { if ((value > info->zero && value >= info->value) || (value < info->zero && value <= info->value)) { return 0; } } /* Update internal joystick state */ info->value = value; /* Post the event, if desired */ posted = 0; #if !SDL_EVENTS_DISABLED if (SDL_GetEventState(SDL_JOYAXISMOTION) == SDL_ENABLE) { SDL_Event event; event.type = SDL_JOYAXISMOTION; event.jaxis.which = joystick->instance_id; event.jaxis.axis = axis; event.jaxis.value = value; posted = SDL_PushEvent(&event) == 1; } #endif /* !SDL_EVENTS_DISABLED */ return posted; } int SDL_PrivateJoystickHat(SDL_Joystick * joystick, Uint8 hat, Uint8 value) { int posted; /* Make sure we're not getting garbage or duplicate events */ if (hat >= joystick->nhats) { return 0; } if (value == joystick->hats[hat]) { return 0; } /* We ignore events if we don't have keyboard focus, except for centering * events. */ if (SDL_PrivateJoystickShouldIgnoreEvent()) { if (value != SDL_HAT_CENTERED) { return 0; } } /* Update internal joystick state */ joystick->hats[hat] = value; /* Post the event, if desired */ posted = 0; #if !SDL_EVENTS_DISABLED if (SDL_GetEventState(SDL_JOYHATMOTION) == SDL_ENABLE) { SDL_Event event; event.jhat.type = SDL_JOYHATMOTION; event.jhat.which = joystick->instance_id; event.jhat.hat = hat; event.jhat.value = value; posted = SDL_PushEvent(&event) == 1; } #endif /* !SDL_EVENTS_DISABLED */ return posted; } int SDL_PrivateJoystickBall(SDL_Joystick * joystick, Uint8 ball, Sint16 xrel, Sint16 yrel) { int posted; /* Make sure we're not getting garbage events */ if (ball >= joystick->nballs) { return 0; } /* We ignore events if we don't have keyboard focus. */ if (SDL_PrivateJoystickShouldIgnoreEvent()) { return 0; } /* Update internal mouse state */ joystick->balls[ball].dx += xrel; joystick->balls[ball].dy += yrel; /* Post the event, if desired */ posted = 0; #if !SDL_EVENTS_DISABLED if (SDL_GetEventState(SDL_JOYBALLMOTION) == SDL_ENABLE) { SDL_Event event; event.jball.type = SDL_JOYBALLMOTION; event.jball.which = joystick->instance_id; event.jball.ball = ball; event.jball.xrel = xrel; event.jball.yrel = yrel; posted = SDL_PushEvent(&event) == 1; } #endif /* !SDL_EVENTS_DISABLED */ return posted; } int SDL_PrivateJoystickButton(SDL_Joystick * joystick, Uint8 button, Uint8 state) { int posted; #if !SDL_EVENTS_DISABLED SDL_Event event; switch (state) { case SDL_PRESSED: event.type = SDL_JOYBUTTONDOWN; break; case SDL_RELEASED: event.type = SDL_JOYBUTTONUP; break; default: /* Invalid state -- bail */ return 0; } #endif /* !SDL_EVENTS_DISABLED */ /* Make sure we're not getting garbage or duplicate events */ if (button >= joystick->nbuttons) { return 0; } if (state == joystick->buttons[button]) { return 0; } /* We ignore events if we don't have keyboard focus, except for button * release. */ if (SDL_PrivateJoystickShouldIgnoreEvent()) { if (state == SDL_PRESSED) { return 0; } } /* Update internal joystick state */ joystick->buttons[button] = state; /* Post the event, if desired */ posted = 0; #if !SDL_EVENTS_DISABLED if (SDL_GetEventState(event.type) == SDL_ENABLE) { event.jbutton.which = joystick->instance_id; event.jbutton.button = button; event.jbutton.state = state; posted = SDL_PushEvent(&event) == 1; } #endif /* !SDL_EVENTS_DISABLED */ return posted; } void SDL_JoystickUpdate(void) { int i; SDL_Joystick *joystick, *next; if (!SDL_WasInit(SDL_INIT_JOYSTICK)) { return; } SDL_LockJoysticks(); if (SDL_updating_joystick) { /* The joysticks are already being updated */ SDL_UnlockJoysticks(); return; } SDL_updating_joystick = SDL_TRUE; /* Make sure the list is unlocked while dispatching events to prevent application deadlocks */ SDL_UnlockJoysticks(); #ifdef SDL_JOYSTICK_HIDAPI /* Special function for HIDAPI devices, as a single device can provide multiple SDL_Joysticks */ HIDAPI_UpdateDevices(); #endif /* SDL_JOYSTICK_HIDAPI */ for (joystick = SDL_joysticks; joystick; joystick = joystick->next) { if (joystick->attached) { /* This should always be true, but seeing a crash in the wild...? */ if (joystick->driver) { joystick->driver->Update(joystick); } if (joystick->delayed_guide_button) { SDL_GameControllerHandleDelayedGuideButton(joystick); } } if (joystick->rumble_expiration) { SDL_LockJoysticks(); /* Double check now that the lock is held */ if (joystick->rumble_expiration && SDL_TICKS_PASSED(SDL_GetTicks(), joystick->rumble_expiration)) { SDL_JoystickRumble(joystick, 0, 0, 0); } SDL_UnlockJoysticks(); } } SDL_LockJoysticks(); SDL_updating_joystick = SDL_FALSE; /* If any joysticks were closed while updating, free them here */ for (joystick = SDL_joysticks; joystick; joystick = next) { next = joystick->next; if (joystick->ref_count <= 0) { SDL_JoystickClose(joystick); } } /* this needs to happen AFTER walking the joystick list above, so that any dangling hardware data from removed devices can be free'd */ for (i = 0; i < SDL_arraysize(SDL_joystick_drivers); ++i) { SDL_joystick_drivers[i]->Detect(); } SDL_UnlockJoysticks(); } int SDL_JoystickEventState(int state) { #if SDL_EVENTS_DISABLED return SDL_DISABLE; #else const Uint32 event_list[] = { SDL_JOYAXISMOTION, SDL_JOYBALLMOTION, SDL_JOYHATMOTION, SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP, SDL_JOYDEVICEADDED, SDL_JOYDEVICEREMOVED }; unsigned int i; switch (state) { case SDL_QUERY: state = SDL_DISABLE; for (i = 0; i < SDL_arraysize(event_list); ++i) { state = SDL_EventState(event_list[i], SDL_QUERY); if (state == SDL_ENABLE) { break; } } break; default: for (i = 0; i < SDL_arraysize(event_list); ++i) { SDL_EventState(event_list[i], state); } break; } return state; #endif /* SDL_EVENTS_DISABLED */ } void SDL_GetJoystickGUIDInfo(SDL_JoystickGUID guid, Uint16 *vendor, Uint16 *product, Uint16 *version) { Uint16 *guid16 = (Uint16 *)guid.data; /* If the GUID fits the form of BUS 0000 VENDOR 0000 PRODUCT 0000, return the data */ if (/* guid16[0] is device bus type */ guid16[1] == 0x0000 && /* guid16[2] is vendor ID */ guid16[3] == 0x0000 && /* guid16[4] is product ID */ guid16[5] == 0x0000 /* guid16[6] is product version */ ) { if (vendor) { *vendor = guid16[2]; } if (product) { *product = guid16[4]; } if (version) { *version = guid16[6]; } } else { if (vendor) { *vendor = 0; } if (product) { *product = 0; } if (version) { *version = 0; } } } static int PrefixMatch(const char *a, const char *b) { int matchlen = 0; while (*a && *b) { if (SDL_tolower(*a++) == SDL_tolower(*b++)) { ++matchlen; } else { break; } } return matchlen; } char * SDL_CreateJoystickName(Uint16 vendor, Uint16 product, const char *vendor_name, const char *product_name) { static struct { const char *prefix; const char *replacement; } replacements[] = { { "NVIDIA Corporation ", "" }, { "Performance Designed Products", "PDP" }, { "HORI CO.,LTD", "HORI" }, }; const char *custom_name; char *name; size_t i, len; custom_name = GuessControllerName(vendor, product); if (custom_name) { return SDL_strdup(custom_name); } if (!vendor_name) { vendor_name = ""; } if (!product_name) { product_name = ""; } while (*vendor_name == ' ') { ++vendor_name; } while (*product_name == ' ') { ++product_name; } if (*vendor_name && *product_name) { len = (SDL_strlen(vendor_name) + 1 + SDL_strlen(product_name) + 1); name = (char *)SDL_malloc(len); if (!name) { return NULL; } SDL_snprintf(name, len, "%s %s", vendor_name, product_name); } else if (*product_name) { name = SDL_strdup(product_name); } else if (vendor || product) { len = (6 + 1 + 6 + 1); name = (char *)SDL_malloc(len); if (!name) { return NULL; } SDL_snprintf(name, len, "0x%.4x/0x%.4x", vendor, product); } else { name = SDL_strdup("Controller"); } /* Trim trailing whitespace */ for (len = SDL_strlen(name); (len > 0 && name[len - 1] == ' '); --len) { /* continue */ } name[len] = '\0'; /* Compress duplicate spaces */ for (i = 0; i < (len - 1); ) { if (name[i] == ' ' && name[i+1] == ' ') { SDL_memmove(&name[i], &name[i+1], (len - i)); --len; } else { ++i; } } /* Remove duplicate manufacturer or product in the name */ for (i = 1; i < (len - 1); ++i) { int matchlen = PrefixMatch(name, &name[i]); if (matchlen > 0 && name[matchlen-1] == ' ') { SDL_memmove(name, name+matchlen, len-matchlen+1); len -= matchlen; break; } else if (matchlen > 0 && name[matchlen] == ' ') { SDL_memmove(name, name+matchlen+1, len-matchlen); len -= (matchlen + 1); break; } } /* Perform any manufacturer replacements */ for (i = 0; i < SDL_arraysize(replacements); ++i) { size_t prefixlen = SDL_strlen(replacements[i].prefix); if (SDL_strncasecmp(name, replacements[i].prefix, prefixlen) == 0) { size_t replacementlen = SDL_strlen(replacements[i].replacement); SDL_memcpy(name, replacements[i].replacement, replacementlen); SDL_memmove(name+replacementlen, name+prefixlen, (len-prefixlen+1)); break; } } return name; } SDL_GameControllerType SDL_GetJoystickGameControllerTypeFromGUID(SDL_JoystickGUID guid, const char *name) { SDL_GameControllerType type; Uint16 vendor, product; SDL_GetJoystickGUIDInfo(guid, &vendor, &product, NULL); type = SDL_GetJoystickGameControllerType(name, vendor, product, -1, 0, 0, 0); if (type == SDL_CONTROLLER_TYPE_UNKNOWN) { if (SDL_IsJoystickXInput(guid)) { /* This is probably an Xbox One controller */ return SDL_CONTROLLER_TYPE_XBOXONE; } } return type; } SDL_GameControllerType SDL_GetJoystickGameControllerType(const char *name, Uint16 vendor, Uint16 product, int interface_number, int interface_class, int interface_subclass, int interface_protocol) { static const int LIBUSB_CLASS_VENDOR_SPEC = 0xFF; static const int XB360_IFACE_SUBCLASS = 93; static const int XB360_IFACE_PROTOCOL = 1; /* Wired */ static const int XB360W_IFACE_PROTOCOL = 129; /* Wireless */ static const int XBONE_IFACE_SUBCLASS = 71; static const int XBONE_IFACE_PROTOCOL = 208; SDL_GameControllerType type = SDL_CONTROLLER_TYPE_UNKNOWN; /* This code should match the checks in libusb/hid.c and HIDDeviceManager.java */ if (interface_class == LIBUSB_CLASS_VENDOR_SPEC && interface_subclass == XB360_IFACE_SUBCLASS && (interface_protocol == XB360_IFACE_PROTOCOL || interface_protocol == XB360W_IFACE_PROTOCOL)) { static const int SUPPORTED_VENDORS[] = { 0x0079, /* GPD Win 2 */ 0x044f, /* Thrustmaster */ 0x045e, /* Microsoft */ 0x046d, /* Logitech */ 0x056e, /* Elecom */ 0x06a3, /* Saitek */ 0x0738, /* Mad Catz */ 0x07ff, /* Mad Catz */ 0x0e6f, /* PDP */ 0x0f0d, /* Hori */ 0x1038, /* SteelSeries */ 0x11c9, /* Nacon */ 0x12ab, /* Unknown */ 0x1430, /* RedOctane */ 0x146b, /* BigBen */ 0x1532, /* Razer Sabertooth */ 0x15e4, /* Numark */ 0x162e, /* Joytech */ 0x1689, /* Razer Onza */ 0x1bad, /* Harmonix */ 0x24c6, /* PowerA */ }; int i; for (i = 0; i < SDL_arraysize(SUPPORTED_VENDORS); ++i) { if (vendor == SUPPORTED_VENDORS[i]) { type = SDL_CONTROLLER_TYPE_XBOX360; break; } } } if (interface_number == 0 && interface_class == LIBUSB_CLASS_VENDOR_SPEC && interface_subclass == XBONE_IFACE_SUBCLASS && interface_protocol == XBONE_IFACE_PROTOCOL) { static const int SUPPORTED_VENDORS[] = { 0x045e, /* Microsoft */ 0x0738, /* Mad Catz */ 0x0e6f, /* PDP */ 0x0f0d, /* Hori */ 0x1532, /* Razer Wildcat */ 0x24c6, /* PowerA */ 0x2e24, /* Hyperkin */ }; int i; for (i = 0; i < SDL_arraysize(SUPPORTED_VENDORS); ++i) { if (vendor == SUPPORTED_VENDORS[i]) { type = SDL_CONTROLLER_TYPE_XBOXONE; break; } } } if (type == SDL_CONTROLLER_TYPE_UNKNOWN) { if (vendor == 0x0000 && product == 0x0000) { /* Some devices are only identifiable by their name */ if (SDL_strcmp(name, "Lic Pro Controller") == 0 || SDL_strcmp(name, "Nintendo Wireless Gamepad") == 0 || SDL_strcmp(name, "Wireless Gamepad") == 0) { /* HORI or PowerA Switch Pro Controller clone */ type = SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO; } else if (SDL_strcmp(name, "Virtual Joystick") == 0) { type = SDL_CONTROLLER_TYPE_VIRTUAL; } else { type = SDL_CONTROLLER_TYPE_UNKNOWN; } } else if (vendor == 0x0001 && product == 0x0001) { type = SDL_CONTROLLER_TYPE_UNKNOWN; } else { switch (GuessControllerType(vendor, product)) { case k_eControllerType_XBox360Controller: type = SDL_CONTROLLER_TYPE_XBOX360; break; case k_eControllerType_XBoxOneController: type = SDL_CONTROLLER_TYPE_XBOXONE; break; case k_eControllerType_PS3Controller: type = SDL_CONTROLLER_TYPE_PS3; break; case k_eControllerType_PS4Controller: type = SDL_CONTROLLER_TYPE_PS4; break; case k_eControllerType_SwitchProController: case k_eControllerType_SwitchInputOnlyController: type = SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO; break; default: type = SDL_CONTROLLER_TYPE_UNKNOWN; break; } } } return type; } SDL_bool SDL_IsJoystickNintendoSwitchProInputOnly(Uint16 vendor, Uint16 product) { EControllerType eType = GuessControllerType(vendor, product); return (eType == k_eControllerType_SwitchInputOnlyController); } SDL_bool SDL_IsJoystickSteamController(Uint16 vendor, Uint16 product) { EControllerType eType = GuessControllerType(vendor, product); return (eType == k_eControllerType_SteamController || eType == k_eControllerType_SteamControllerV2); } SDL_bool SDL_IsJoystickXInput(SDL_JoystickGUID guid) { return (guid.data[14] == 'x') ? SDL_TRUE : SDL_FALSE; } SDL_bool SDL_IsJoystickWGI(SDL_JoystickGUID guid) { return (guid.data[14] == 'w') ? SDL_TRUE : SDL_FALSE; } SDL_bool SDL_IsJoystickHIDAPI(SDL_JoystickGUID guid) { return (guid.data[14] == 'h') ? SDL_TRUE : SDL_FALSE; } SDL_bool SDL_IsJoystickRAWINPUT(SDL_JoystickGUID guid) { return (guid.data[14] == 'r') ? SDL_TRUE : SDL_FALSE; } SDL_bool SDL_IsJoystickVirtual(SDL_JoystickGUID guid) { return (guid.data[14] == 'v') ? SDL_TRUE : SDL_FALSE; } static SDL_bool SDL_IsJoystickProductWheel(Uint32 vidpid) { static Uint32 wheel_joysticks[] = { MAKE_VIDPID(0x046d, 0xc294), /* Logitech generic wheel */ MAKE_VIDPID(0x046d, 0xc295), /* Logitech Momo Force */ MAKE_VIDPID(0x046d, 0xc298), /* Logitech Driving Force Pro */ MAKE_VIDPID(0x046d, 0xc299), /* Logitech G25 */ MAKE_VIDPID(0x046d, 0xc29a), /* Logitech Driving Force GT */ MAKE_VIDPID(0x046d, 0xc29b), /* Logitech G27 */ MAKE_VIDPID(0x046d, 0xc24f), /* Logitech G29 */ MAKE_VIDPID(0x046d, 0xc261), /* Logitech G920 (initial mode) */ MAKE_VIDPID(0x046d, 0xc262), /* Logitech G920 (active mode) */ MAKE_VIDPID(0x044f, 0xb65d), /* Thrustmaster Wheel FFB */ MAKE_VIDPID(0x044f, 0xb66d), /* Thrustmaster Wheel FFB */ MAKE_VIDPID(0x044f, 0xb677), /* Thrustmaster T150 */ MAKE_VIDPID(0x044f, 0xb664), /* Thrustmaster TX (initial mode) */ MAKE_VIDPID(0x044f, 0xb669), /* Thrustmaster TX (active mode) */ }; int i; for (i = 0; i < SDL_arraysize(wheel_joysticks); ++i) { if (vidpid == wheel_joysticks[i]) { return SDL_TRUE; } } return SDL_FALSE; } static SDL_bool SDL_IsJoystickProductFlightStick(Uint32 vidpid) { static Uint32 flightstick_joysticks[] = { MAKE_VIDPID(0x044f, 0x0402), /* HOTAS Warthog Joystick */ MAKE_VIDPID(0x0738, 0x2221), /* Saitek Pro Flight X-56 Rhino Stick */ }; int i; for (i = 0; i < SDL_arraysize(flightstick_joysticks); ++i) { if (vidpid == flightstick_joysticks[i]) { return SDL_TRUE; } } return SDL_FALSE; } static SDL_bool SDL_IsJoystickProductThrottle(Uint32 vidpid) { static Uint32 throttle_joysticks[] = { MAKE_VIDPID(0x044f, 0x0404), /* HOTAS Warthog Throttle */ MAKE_VIDPID(0x0738, 0xa221), /* Saitek Pro Flight X-56 Rhino Throttle */ }; int i; for (i = 0; i < SDL_arraysize(throttle_joysticks); ++i) { if (vidpid == throttle_joysticks[i]) { return SDL_TRUE; } } return SDL_FALSE; } static SDL_JoystickType SDL_GetJoystickGUIDType(SDL_JoystickGUID guid) { Uint16 vendor; Uint16 product; Uint32 vidpid; if (SDL_IsJoystickXInput(guid)) { /* XInput GUID, get the type based on the XInput device subtype */ switch (guid.data[15]) { case 0x01: /* XINPUT_DEVSUBTYPE_GAMEPAD */ return SDL_JOYSTICK_TYPE_GAMECONTROLLER; case 0x02: /* XINPUT_DEVSUBTYPE_WHEEL */ return SDL_JOYSTICK_TYPE_WHEEL; case 0x03: /* XINPUT_DEVSUBTYPE_ARCADE_STICK */ return SDL_JOYSTICK_TYPE_ARCADE_STICK; case 0x04: /* XINPUT_DEVSUBTYPE_FLIGHT_STICK */ return SDL_JOYSTICK_TYPE_FLIGHT_STICK; case 0x05: /* XINPUT_DEVSUBTYPE_DANCE_PAD */ return SDL_JOYSTICK_TYPE_DANCE_PAD; case 0x06: /* XINPUT_DEVSUBTYPE_GUITAR */ case 0x07: /* XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE */ case 0x0B: /* XINPUT_DEVSUBTYPE_GUITAR_BASS */ return SDL_JOYSTICK_TYPE_GUITAR; case 0x08: /* XINPUT_DEVSUBTYPE_DRUM_KIT */ return SDL_JOYSTICK_TYPE_DRUM_KIT; case 0x13: /* XINPUT_DEVSUBTYPE_ARCADE_PAD */ return SDL_JOYSTICK_TYPE_ARCADE_PAD; default: return SDL_JOYSTICK_TYPE_UNKNOWN; } } if (SDL_IsJoystickWGI(guid)) { return (SDL_JoystickType)guid.data[15]; } if (SDL_IsJoystickVirtual(guid)) { return (SDL_JoystickType)guid.data[15]; } SDL_GetJoystickGUIDInfo(guid, &vendor, &product, NULL); vidpid = MAKE_VIDPID(vendor, product); if (SDL_IsJoystickProductWheel(vidpid)) { return SDL_JOYSTICK_TYPE_WHEEL; } if (SDL_IsJoystickProductFlightStick(vidpid)) { return SDL_JOYSTICK_TYPE_FLIGHT_STICK; } if (SDL_IsJoystickProductThrottle(vidpid)) { return SDL_JOYSTICK_TYPE_THROTTLE; } if (GuessControllerType(vendor, product) != k_eControllerType_UnknownNonSteamController) { return SDL_JOYSTICK_TYPE_GAMECONTROLLER; } return SDL_JOYSTICK_TYPE_UNKNOWN; } static SDL_bool SDL_IsPS4RemapperRunning(void) { #ifdef __WIN32__ const char *mapper_processes[] = { "DS4Windows.exe", "InputMapper.exe", }; int i; PROCESSENTRY32 pe32; SDL_bool found = SDL_FALSE; /* Take a snapshot of all processes in the system */ HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnap != INVALID_HANDLE_VALUE) { pe32.dwSize = sizeof(PROCESSENTRY32); if (Process32First(hProcessSnap, &pe32)) { do { for (i = 0; i < SDL_arraysize(mapper_processes); ++i) { if (SDL_strcasecmp(pe32.szExeFile, mapper_processes[i]) == 0) { found = SDL_TRUE; } } } while (Process32Next(hProcessSnap, &pe32) && !found); } CloseHandle(hProcessSnap); } return found; #else return SDL_FALSE; #endif } SDL_bool SDL_ShouldIgnoreJoystick(const char *name, SDL_JoystickGUID guid) { /* This list is taken from: https://raw.githubusercontent.com/denilsonsa/udev-joystick-blacklist/master/generate_rules.py */ static Uint32 joystick_blacklist[] = { /* Microsoft Microsoft Wireless Optical Desktop 2.10 */ /* Microsoft Wireless Desktop - Comfort Edition */ MAKE_VIDPID(0x045e, 0x009d), /* Microsoft Microsoft Digital Media Pro Keyboard */ /* Microsoft Corp. Digital Media Pro Keyboard */ MAKE_VIDPID(0x045e, 0x00b0), /* Microsoft Microsoft Digital Media Keyboard */ /* Microsoft Corp. Digital Media Keyboard 1.0A */ MAKE_VIDPID(0x045e, 0x00b4), /* Microsoft Microsoft Digital Media Keyboard 3000 */ MAKE_VIDPID(0x045e, 0x0730), /* Microsoft Microsoft 2.4GHz Transceiver v6.0 */ /* Microsoft Microsoft 2.4GHz Transceiver v8.0 */ /* Microsoft Corp. Nano Transceiver v1.0 for Bluetooth */ /* Microsoft Wireless Mobile Mouse 1000 */ /* Microsoft Wireless Desktop 3000 */ MAKE_VIDPID(0x045e, 0x0745), /* Microsoft SideWinder(TM) 2.4GHz Transceiver */ MAKE_VIDPID(0x045e, 0x0748), /* Microsoft Corp. Wired Keyboard 600 */ MAKE_VIDPID(0x045e, 0x0750), /* Microsoft Corp. Sidewinder X4 keyboard */ MAKE_VIDPID(0x045e, 0x0768), /* Microsoft Corp. Arc Touch Mouse Transceiver */ MAKE_VIDPID(0x045e, 0x0773), /* Microsoft 2.4GHz Transceiver v9.0 */ /* Microsoft Nano Transceiver v2.1 */ /* Microsoft Sculpt Ergonomic Keyboard (5KV-00001) */ MAKE_VIDPID(0x045e, 0x07a5), /* Microsoft Nano Transceiver v1.0 */ /* Microsoft Wireless Keyboard 800 */ MAKE_VIDPID(0x045e, 0x07b2), /* Microsoft Nano Transceiver v2.0 */ MAKE_VIDPID(0x045e, 0x0800), MAKE_VIDPID(0x046d, 0xc30a), /* Logitech, Inc. iTouch Composite keboard */ MAKE_VIDPID(0x04d9, 0xa0df), /* Tek Syndicate Mouse (E-Signal USB Gaming Mouse) */ /* List of Wacom devices at: http://linuxwacom.sourceforge.net/wiki/index.php/Device_IDs */ MAKE_VIDPID(0x056a, 0x0010), /* Wacom ET-0405 Graphire */ MAKE_VIDPID(0x056a, 0x0011), /* Wacom ET-0405A Graphire2 (4x5) */ MAKE_VIDPID(0x056a, 0x0012), /* Wacom ET-0507A Graphire2 (5x7) */ MAKE_VIDPID(0x056a, 0x0013), /* Wacom CTE-430 Graphire3 (4x5) */ MAKE_VIDPID(0x056a, 0x0014), /* Wacom CTE-630 Graphire3 (6x8) */ MAKE_VIDPID(0x056a, 0x0015), /* Wacom CTE-440 Graphire4 (4x5) */ MAKE_VIDPID(0x056a, 0x0016), /* Wacom CTE-640 Graphire4 (6x8) */ MAKE_VIDPID(0x056a, 0x0017), /* Wacom CTE-450 Bamboo Fun (4x5) */ MAKE_VIDPID(0x056a, 0x0018), /* Wacom CTE-650 Bamboo Fun 6x8 */ MAKE_VIDPID(0x056a, 0x0019), /* Wacom CTE-631 Bamboo One */ MAKE_VIDPID(0x056a, 0x00d1), /* Wacom Bamboo Pen and Touch CTH-460 */ MAKE_VIDPID(0x056a, 0x030e), /* Wacom Intuos Pen (S) CTL-480 */ MAKE_VIDPID(0x09da, 0x054f), /* A4 Tech Co., G7 750 mouse */ MAKE_VIDPID(0x09da, 0x1410), /* A4 Tech Co., Ltd Bloody AL9 mouse */ MAKE_VIDPID(0x09da, 0x3043), /* A4 Tech Co., Ltd Bloody R8A Gaming Mouse */ MAKE_VIDPID(0x09da, 0x31b5), /* A4 Tech Co., Ltd Bloody TL80 Terminator Laser Gaming Mouse */ MAKE_VIDPID(0x09da, 0x3997), /* A4 Tech Co., Ltd Bloody RT7 Terminator Wireless */ MAKE_VIDPID(0x09da, 0x3f8b), /* A4 Tech Co., Ltd Bloody V8 mouse */ MAKE_VIDPID(0x09da, 0x51f4), /* Modecom MC-5006 Keyboard */ MAKE_VIDPID(0x09da, 0x5589), /* A4 Tech Co., Ltd Terminator TL9 Laser Gaming Mouse */ MAKE_VIDPID(0x09da, 0x7b22), /* A4 Tech Co., Ltd Bloody V5 */ MAKE_VIDPID(0x09da, 0x7f2d), /* A4 Tech Co., Ltd Bloody R3 mouse */ MAKE_VIDPID(0x09da, 0x8090), /* A4 Tech Co., Ltd X-718BK Oscar Optical Gaming Mouse */ MAKE_VIDPID(0x09da, 0x9033), /* A4 Tech Co., X7 X-705K */ MAKE_VIDPID(0x09da, 0x9066), /* A4 Tech Co., Sharkoon Fireglider Optical */ MAKE_VIDPID(0x09da, 0x9090), /* A4 Tech Co., Ltd XL-730K / XL-750BK / XL-755BK Laser Mouse */ MAKE_VIDPID(0x09da, 0x90c0), /* A4 Tech Co., Ltd X7 G800V keyboard */ MAKE_VIDPID(0x09da, 0xf012), /* A4 Tech Co., Ltd Bloody V7 mouse */ MAKE_VIDPID(0x09da, 0xf32a), /* A4 Tech Co., Ltd Bloody B540 keyboard */ MAKE_VIDPID(0x09da, 0xf613), /* A4 Tech Co., Ltd Bloody V2 mouse */ MAKE_VIDPID(0x09da, 0xf624), /* A4 Tech Co., Ltd Bloody B120 Keyboard */ MAKE_VIDPID(0x1b1c, 0x1b3c), /* Corsair Harpoon RGB gaming mouse */ MAKE_VIDPID(0x1d57, 0xad03), /* [T3] 2.4GHz and IR Air Mouse Remote Control */ MAKE_VIDPID(0x1e7d, 0x2e4a), /* Roccat Tyon Mouse */ MAKE_VIDPID(0x20a0, 0x422d), /* Winkeyless.kr Keyboards */ MAKE_VIDPID(0x2516, 0x001f), /* Cooler Master Storm Mizar Mouse */ MAKE_VIDPID(0x2516, 0x0028), /* Cooler Master Storm Alcor Mouse */ }; unsigned int i; Uint32 id; Uint16 vendor; Uint16 product; SDL_GetJoystickGUIDInfo(guid, &vendor, &product, NULL); /* Check the joystick blacklist */ id = MAKE_VIDPID(vendor, product); for (i = 0; i < SDL_arraysize(joystick_blacklist); ++i) { if (id == joystick_blacklist[i]) { return SDL_TRUE; } } if (SDL_GetJoystickGameControllerType(name, vendor, product, -1, 0, 0, 0) == SDL_CONTROLLER_TYPE_PS4 && SDL_IsPS4RemapperRunning()) { return SDL_TRUE; } if (SDL_IsGameControllerNameAndGUID(name, guid) && SDL_ShouldIgnoreGameController(name, guid)) { return SDL_TRUE; } return SDL_FALSE; } /* return the guid for this index */ SDL_JoystickGUID SDL_JoystickGetDeviceGUID(int device_index) { SDL_JoystickDriver *driver; SDL_JoystickGUID guid; SDL_LockJoysticks(); if (SDL_GetDriverAndJoystickIndex(device_index, &driver, &device_index)) { guid = driver->GetDeviceGUID(device_index); } else { SDL_zero(guid); } SDL_UnlockJoysticks(); return guid; } Uint16 SDL_JoystickGetDeviceVendor(int device_index) { Uint16 vendor; SDL_JoystickGUID guid = SDL_JoystickGetDeviceGUID(device_index); SDL_GetJoystickGUIDInfo(guid, &vendor, NULL, NULL); return vendor; } Uint16 SDL_JoystickGetDeviceProduct(int device_index) { Uint16 product; SDL_JoystickGUID guid = SDL_JoystickGetDeviceGUID(device_index); SDL_GetJoystickGUIDInfo(guid, NULL, &product, NULL); return product; } Uint16 SDL_JoystickGetDeviceProductVersion(int device_index) { Uint16 version; SDL_JoystickGUID guid = SDL_JoystickGetDeviceGUID(device_index); SDL_GetJoystickGUIDInfo(guid, NULL, NULL, &version); return version; } SDL_JoystickType SDL_JoystickGetDeviceType(int device_index) { SDL_JoystickType type; SDL_JoystickGUID guid = SDL_JoystickGetDeviceGUID(device_index); type = SDL_GetJoystickGUIDType(guid); if (type == SDL_JOYSTICK_TYPE_UNKNOWN) { if (SDL_IsGameController(device_index)) { type = SDL_JOYSTICK_TYPE_GAMECONTROLLER; } } return type; } SDL_JoystickID SDL_JoystickGetDeviceInstanceID(int device_index) { SDL_JoystickDriver *driver; SDL_JoystickID instance_id = -1; SDL_LockJoysticks(); if (SDL_GetDriverAndJoystickIndex(device_index, &driver, &device_index)) { instance_id = driver->GetDeviceInstanceID(device_index); } SDL_UnlockJoysticks(); return instance_id; } int SDL_JoystickGetDeviceIndexFromInstanceID(SDL_JoystickID instance_id) { int i, num_joysticks, device_index = -1; SDL_LockJoysticks(); num_joysticks = SDL_NumJoysticks(); for (i = 0; i < num_joysticks; ++i) { if (SDL_JoystickGetDeviceInstanceID(i) == instance_id) { device_index = i; break; } } SDL_UnlockJoysticks(); return device_index; } SDL_JoystickGUID SDL_JoystickGetGUID(SDL_Joystick * joystick) { if (!SDL_PrivateJoystickValid(joystick)) { SDL_JoystickGUID emptyGUID; SDL_zero(emptyGUID); return emptyGUID; } return joystick->guid; } Uint16 SDL_JoystickGetVendor(SDL_Joystick * joystick) { Uint16 vendor; SDL_JoystickGUID guid = SDL_JoystickGetGUID(joystick); SDL_GetJoystickGUIDInfo(guid, &vendor, NULL, NULL); return vendor; } Uint16 SDL_JoystickGetProduct(SDL_Joystick * joystick) { Uint16 product; SDL_JoystickGUID guid = SDL_JoystickGetGUID(joystick); SDL_GetJoystickGUIDInfo(guid, NULL, &product, NULL); return product; } Uint16 SDL_JoystickGetProductVersion(SDL_Joystick * joystick) { Uint16 version; SDL_JoystickGUID guid = SDL_JoystickGetGUID(joystick); SDL_GetJoystickGUIDInfo(guid, NULL, NULL, &version); return version; } SDL_JoystickType SDL_JoystickGetType(SDL_Joystick * joystick) { SDL_JoystickType type; SDL_JoystickGUID guid = SDL_JoystickGetGUID(joystick); type = SDL_GetJoystickGUIDType(guid); if (type == SDL_JOYSTICK_TYPE_UNKNOWN) { if (joystick && joystick->is_game_controller) { type = SDL_JOYSTICK_TYPE_GAMECONTROLLER; } } return type; } /* convert the guid to a printable string */ void SDL_JoystickGetGUIDString(SDL_JoystickGUID guid, char *pszGUID, int cbGUID) { static const char k_rgchHexToASCII[] = "0123456789abcdef"; int i; if ((pszGUID == NULL) || (cbGUID <= 0)) { return; } for (i = 0; i < sizeof(guid.data) && i < (cbGUID-1)/2; i++) { /* each input byte writes 2 ascii chars, and might write a null byte. */ /* If we don't have room for next input byte, stop */ unsigned char c = guid.data[i]; *pszGUID++ = k_rgchHexToASCII[c >> 4]; *pszGUID++ = k_rgchHexToASCII[c & 0x0F]; } *pszGUID = '\0'; } /*----------------------------------------------------------------------------- * Purpose: Returns the 4 bit nibble for a hex character * Input : c - * Output : unsigned char *-----------------------------------------------------------------------------*/ static unsigned char nibble(char c) { if ((c >= '0') && (c <= '9')) { return (unsigned char)(c - '0'); } if ((c >= 'A') && (c <= 'F')) { return (unsigned char)(c - 'A' + 0x0a); } if ((c >= 'a') && (c <= 'f')) { return (unsigned char)(c - 'a' + 0x0a); } /* received an invalid character, and no real way to return an error */ /* AssertMsg1(false, "Q_nibble invalid hex character '%c' ", c); */ return 0; } /* convert the string version of a joystick guid to the struct */ SDL_JoystickGUID SDL_JoystickGetGUIDFromString(const char *pchGUID) { SDL_JoystickGUID guid; int maxoutputbytes= sizeof(guid); size_t len = SDL_strlen(pchGUID); Uint8 *p; size_t i; /* Make sure it's even */ len = (len) & ~0x1; SDL_memset(&guid, 0x00, sizeof(guid)); p = (Uint8 *)&guid; for (i = 0; (i < len) && ((p - (Uint8 *)&guid) < maxoutputbytes); i+=2, p++) { *p = (nibble(pchGUID[i]) << 4) | nibble(pchGUID[i+1]); } return guid; } /* update the power level for this joystick */ void SDL_PrivateJoystickBatteryLevel(SDL_Joystick * joystick, SDL_JoystickPowerLevel ePowerLevel) { joystick->epowerlevel = ePowerLevel; } /* return its power level */ SDL_JoystickPowerLevel SDL_JoystickCurrentPowerLevel(SDL_Joystick * joystick) { if (!SDL_PrivateJoystickValid(joystick)) { return SDL_JOYSTICK_POWER_UNKNOWN; } return joystick->epowerlevel; } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/SDL_joystick.c
C
apache-2.0
66,194
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_joystick_c_h_ #define SDL_joystick_c_h_ #include "../SDL_internal.h" /* Useful functions and variables from SDL_joystick.c */ #include "SDL_gamecontroller.h" #include "SDL_joystick.h" struct _SDL_JoystickDriver; /* Initialization and shutdown functions */ extern int SDL_JoystickInit(void); extern void SDL_JoystickQuit(void); /* Function to get the next available joystick instance ID */ extern SDL_JoystickID SDL_GetNextJoystickInstanceID(void); /* Initialization and shutdown functions */ extern int SDL_GameControllerInitMappings(void); extern void SDL_GameControllerQuitMappings(void); extern int SDL_GameControllerInit(void); extern void SDL_GameControllerQuit(void); /* Function to get the joystick driver and device index for an API device index */ extern SDL_bool SDL_GetDriverAndJoystickIndex(int device_index, struct _SDL_JoystickDriver **driver, int *driver_index); /* Function to return the device index for a joystick ID, or -1 if not found */ extern int SDL_JoystickGetDeviceIndexFromInstanceID(SDL_JoystickID instance_id); /* Function to extract information from an SDL joystick GUID */ extern void SDL_GetJoystickGUIDInfo(SDL_JoystickGUID guid, Uint16 *vendor, Uint16 *product, Uint16 *version); /* Function to standardize the name for a controller This should be freed with SDL_free() when no longer needed */ extern char *SDL_CreateJoystickName(Uint16 vendor, Uint16 product, const char *vendor_name, const char *product_name); /* Function to return the type of a controller */ extern SDL_GameControllerType SDL_GetJoystickGameControllerTypeFromGUID(SDL_JoystickGUID guid, const char *name); extern SDL_GameControllerType SDL_GetJoystickGameControllerType(const char *name, Uint16 vendor, Uint16 product, int interface_number, int interface_class, int interface_subclass, int interface_protocol); /* Function to return whether a joystick is a Nintendo Switch Pro controller */ extern SDL_bool SDL_IsJoystickNintendoSwitchProInputOnly(Uint16 vendor_id, Uint16 product_id); /* Function to return whether a joystick is a Steam Controller */ extern SDL_bool SDL_IsJoystickSteamController(Uint16 vendor_id, Uint16 product_id); /* Function to return whether a joystick guid comes from the XInput driver */ extern SDL_bool SDL_IsJoystickXInput(SDL_JoystickGUID guid); /* Function to return whether a joystick guid comes from the WGI driver */ extern SDL_bool SDL_IsJoystickWGI(SDL_JoystickGUID guid); /* Function to return whether a joystick guid comes from the HIDAPI driver */ extern SDL_bool SDL_IsJoystickHIDAPI(SDL_JoystickGUID guid); /* Function to return whether a joystick guid comes from the RAWINPUT driver */ extern SDL_bool SDL_IsJoystickRAWINPUT(SDL_JoystickGUID guid); /* Function to return whether a joystick guid comes from the Virtual driver */ extern SDL_bool SDL_IsJoystickVirtual(SDL_JoystickGUID guid); /* Function to return whether a joystick should be ignored */ extern SDL_bool SDL_ShouldIgnoreJoystick(const char *name, SDL_JoystickGUID guid); /* Function to return whether a joystick name and GUID is a game controller */ extern SDL_bool SDL_IsGameControllerNameAndGUID(const char *name, SDL_JoystickGUID guid); /* Function to return whether a game controller should be ignored */ extern SDL_bool SDL_ShouldIgnoreGameController(const char *name, SDL_JoystickGUID guid); /* Handle delayed guide button on a game controller */ extern void SDL_GameControllerHandleDelayedGuideButton(SDL_Joystick *joystick); /* Internal event queueing functions */ extern void SDL_PrivateJoystickAdded(SDL_JoystickID device_instance); extern void SDL_PrivateJoystickRemoved(SDL_JoystickID device_instance); extern int SDL_PrivateJoystickAxis(SDL_Joystick * joystick, Uint8 axis, Sint16 value); extern int SDL_PrivateJoystickBall(SDL_Joystick * joystick, Uint8 ball, Sint16 xrel, Sint16 yrel); extern int SDL_PrivateJoystickHat(SDL_Joystick * joystick, Uint8 hat, Uint8 value); extern int SDL_PrivateJoystickButton(SDL_Joystick * joystick, Uint8 button, Uint8 state); extern void SDL_PrivateJoystickBatteryLevel(SDL_Joystick * joystick, SDL_JoystickPowerLevel ePowerLevel); /* Internal sanity checking functions */ extern SDL_bool SDL_PrivateJoystickValid(SDL_Joystick * joystick); typedef enum { EMappingKind_None = 0, EMappingKind_Button = 1, EMappingKind_Axis = 2, EMappingKind_Hat = 3 } EMappingKind; typedef struct _SDL_InputMapping { EMappingKind kind; Uint8 target; } SDL_InputMapping; typedef struct _SDL_GamepadMapping { SDL_InputMapping a; SDL_InputMapping b; SDL_InputMapping x; SDL_InputMapping y; SDL_InputMapping back; SDL_InputMapping guide; SDL_InputMapping start; SDL_InputMapping leftstick; SDL_InputMapping rightstick; SDL_InputMapping leftshoulder; SDL_InputMapping rightshoulder; SDL_InputMapping dpup; SDL_InputMapping dpdown; SDL_InputMapping dpleft; SDL_InputMapping dpright; SDL_InputMapping leftx; SDL_InputMapping lefty; SDL_InputMapping rightx; SDL_InputMapping righty; SDL_InputMapping lefttrigger; SDL_InputMapping righttrigger; } SDL_GamepadMapping; /* Function to get autodetected gamepad controller mapping from the driver */ extern SDL_bool SDL_PrivateJoystickGetAutoGamepadMapping(int device_index, SDL_GamepadMapping *out); #endif /* SDL_joystick_c_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/SDL_joystick_c.h
C
apache-2.0
6,580
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" #ifndef SDL_sysjoystick_h_ #define SDL_sysjoystick_h_ /* This is the system specific header for the SDL joystick API */ #include "SDL_joystick.h" #include "SDL_joystick_c.h" /* The SDL joystick structure */ typedef struct _SDL_JoystickAxisInfo { Sint16 initial_value; /* Initial axis state */ Sint16 value; /* Current axis state */ Sint16 zero; /* Zero point on the axis (-32768 for triggers) */ SDL_bool has_initial_value; /* Whether we've seen a value on the axis yet */ SDL_bool has_second_value; /* Whether we've seen a second value on the axis yet */ SDL_bool sent_initial_value; /* Whether we've sent the initial axis value */ } SDL_JoystickAxisInfo; struct _SDL_Joystick { SDL_JoystickID instance_id; /* Device instance, monotonically increasing from 0 */ char *name; /* Joystick name - system dependent */ SDL_JoystickGUID guid; /* Joystick guid */ int naxes; /* Number of axis controls on the joystick */ SDL_JoystickAxisInfo *axes; int nhats; /* Number of hats on the joystick */ Uint8 *hats; /* Current hat states */ int nballs; /* Number of trackballs on the joystick */ struct balldelta { int dx; int dy; } *balls; /* Current ball motion deltas */ int nbuttons; /* Number of buttons on the joystick */ Uint8 *buttons; /* Current button states */ Uint16 low_frequency_rumble; Uint16 high_frequency_rumble; Uint32 rumble_expiration; SDL_bool attached; SDL_bool is_game_controller; SDL_bool delayed_guide_button; /* SDL_TRUE if this device has the guide button event delayed */ SDL_JoystickPowerLevel epowerlevel; /* power level of this joystick, SDL_JOYSTICK_POWER_UNKNOWN if not supported */ struct _SDL_JoystickDriver *driver; struct joystick_hwdata *hwdata; /* Driver dependent information */ int ref_count; /* Reference count for multiple opens */ struct _SDL_Joystick *next; /* pointer to next joystick we have allocated */ }; /* Device bus definitions */ #define SDL_HARDWARE_BUS_USB 0x03 #define SDL_HARDWARE_BUS_BLUETOOTH 0x05 /* Macro to combine a USB vendor ID and product ID into a single Uint32 value */ #define MAKE_VIDPID(VID, PID) (((Uint32)(VID))<<16|(PID)) typedef struct _SDL_JoystickDriver { /* Function to scan the system for joysticks. * Joystick 0 should be the system default joystick. * This function should return 0, or -1 on an unrecoverable error. */ int (*Init)(void); /* Function to return the number of joystick devices plugged in right now */ int (*GetCount)(void); /* Function to cause any queued joystick insertions to be processed */ void (*Detect)(void); /* Function to get the device-dependent name of a joystick */ const char *(*GetDeviceName)(int device_index); /* Function to get the player index of a joystick */ int (*GetDevicePlayerIndex)(int device_index); /* Function to get the player index of a joystick */ void (*SetDevicePlayerIndex)(int device_index, int player_index); /* Function to return the stable GUID for a plugged in device */ SDL_JoystickGUID (*GetDeviceGUID)(int device_index); /* Function to get the current instance id of the joystick located at device_index */ SDL_JoystickID (*GetDeviceInstanceID)(int device_index); /* Function to open a joystick for use. The joystick to open is specified by the device index. This should fill the nbuttons and naxes fields of the joystick structure. It returns 0, or -1 if there is an error. */ int (*Open)(SDL_Joystick * joystick, int device_index); /* Rumble functionality */ int (*Rumble)(SDL_Joystick * joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble); /* Function to update the state of a joystick - called as a device poll. * This function shouldn't update the joystick structure directly, * but instead should call SDL_PrivateJoystick*() to deliver events * and update joystick device state. */ void (*Update)(SDL_Joystick * joystick); /* Function to close a joystick after use */ void (*Close)(SDL_Joystick * joystick); /* Function to perform any system-specific joystick related cleanup */ void (*Quit)(void); /* Function to get the autodetected controller mapping; returns false if there isn't any. */ SDL_bool (*GetGamepadMapping)(int device_index, SDL_GamepadMapping * out); } SDL_JoystickDriver; /* Windows and Mac OSX has a limit of MAX_DWORD / 1000, Linux kernel has a limit of 0xFFFF */ #define SDL_MAX_RUMBLE_DURATION_MS 0xFFFF /* The available joystick drivers */ extern SDL_JoystickDriver SDL_ANDROID_JoystickDriver; extern SDL_JoystickDriver SDL_BSD_JoystickDriver; extern SDL_JoystickDriver SDL_DARWIN_JoystickDriver; extern SDL_JoystickDriver SDL_DUMMY_JoystickDriver; extern SDL_JoystickDriver SDL_EMSCRIPTEN_JoystickDriver; extern SDL_JoystickDriver SDL_HAIKU_JoystickDriver; extern SDL_JoystickDriver SDL_HIDAPI_JoystickDriver; extern SDL_JoystickDriver SDL_RAWINPUT_JoystickDriver; extern SDL_JoystickDriver SDL_IOS_JoystickDriver; extern SDL_JoystickDriver SDL_LINUX_JoystickDriver; extern SDL_JoystickDriver SDL_VIRTUAL_JoystickDriver; extern SDL_JoystickDriver SDL_WGI_JoystickDriver; extern SDL_JoystickDriver SDL_WINDOWS_JoystickDriver; extern SDL_JoystickDriver SDL_AliOS_JoystickDriver; #endif /* SDL_sysjoystick_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/SDL_sysjoystick.h
C
apache-2.0
6,619
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if defined(SDL_JOYSTICK_ALIOS) || defined(SDL_JOYSTICK_DISABLED) /* This is the dummy implementation of the SDL joystick API */ #include "SDL_joystick.h" #include "../SDL_sysjoystick.h" #include "../SDL_joystick_c.h" #include <aos/hal/gpio.h> #include <aos/hal/adc.h> #include <SDL_events.h> void game_key_irq_fun(int key_num) { int i = 0; Uint8 button; SDL_Joystick *joystick = SDL_JoystickFromInstanceID(0); // do your things here printf("key %d down\n", key_num); if (!joystick) return; if (key_num == 0) { button = SDL_SCANCODE_LSHIFT; } else if (key_num == 1) { button = SDL_SCANCODE_SPACE; } else if (key_num == 2) { button = SDL_SCANCODE_RETURN; } else if (key_num == 3) { button = SDL_SCANCODE_ESCAPE; } SDL_PrivateJoystickButton(joystick, button, SDL_PRESSED); } static gpio_dev_t key_array[4] = { /*key_num, Port*/ {33, IRQ_MODE, NULL}, /*Y*/ {32, IRQ_MODE, NULL}, /*R*/ {22, IRQ_MODE, NULL}, /*B*/ {23, IRQ_MODE, NULL}, /*W*/ }; static int AliOS_JoystickInit(void) { int ret = 0, i = 0; int key_num = 0; // 在这里填键值 gpio_dev_t key; printf("AliOS_JoystickInit\n"); SDL_PrivateJoystickAdded(0); for (i = 0; i < 4; i++) { key_num = i; key.port = key_array[i].port; key.config = key_array[i].config; key.priv = key_array[i].priv; ret |= hal_gpio_init(&key); ret |= hal_gpio_enable_irq(&key, IRQ_TRIGGER_RISING_EDGE, game_key_irq_fun, key_num); } return 0; } static int AliOS_JoystickGetCount(void) { return 1; } static void AliOS_JoystickDetect(void) { } static const char * AliOS_JoystickGetDeviceName(int device_index) { return NULL; } static int AliOS_JoystickGetDevicePlayerIndex(int device_index) { return 0; } static void AliOS_JoystickSetDevicePlayerIndex(int device_index, int player_index) { } static SDL_JoystickGUID AliOS_JoystickGetDeviceGUID(int device_index) { SDL_JoystickGUID guid; SDL_zero(guid); return guid; } static SDL_JoystickID AliOS_JoystickGetDeviceInstanceID(int device_index) { return 0; } static int AliOS_JoystickOpen(SDL_Joystick * joystick, int device_index) { joystick->nballs = 1; joystick->nbuttons = 4; printf("AliOS_JoystickOpen ok\n"); return 0; } static int AliOS_JoystickRumble(SDL_Joystick * joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { return SDL_Unsupported(); } static void AliOS_JoystickUpdate(SDL_Joystick * joystick) { int adc_ret = 0, i; static Sint16 last_xrel, last_yrel; adc_dev_t roll_x; adc_dev_t roll_y; if (!joystick || !joystick->balls) return; roll_x.port = 0; roll_x.config.sampling_cycle = 100; hal_adc_init(&roll_x); roll_y.port = 2; roll_y.config.sampling_cycle = 100; hal_adc_init(&roll_y); /* Deliver ball motion updates */ for (i = 0; i < joystick->nballs; ++i) { int xrel, yrel; adc_ret |= hal_adc_value_get(&roll_x, &xrel, 5); adc_ret |= hal_adc_value_get(&roll_y, &yrel, 5); //printf("xrel: %d, yrel: %d\n", xrel, yrel); if (xrel || yrel) { if ((last_xrel == xrel) && (last_yrel == yrel)) return; SDL_PrivateJoystickBall(joystick, (Uint8) i, xrel, yrel); last_xrel = xrel; last_yrel = yrel; } } } static void AliOS_JoystickClose(SDL_Joystick * joystick) { } static void AliOS_JoystickQuit(void) { } static SDL_bool AliOS_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) { return SDL_FALSE; } SDL_JoystickDriver SDL_AliOS_JoystickDriver = { AliOS_JoystickInit, AliOS_JoystickGetCount, AliOS_JoystickDetect, AliOS_JoystickGetDeviceName, AliOS_JoystickGetDevicePlayerIndex, AliOS_JoystickSetDevicePlayerIndex, AliOS_JoystickGetDeviceGUID, AliOS_JoystickGetDeviceInstanceID, AliOS_JoystickOpen, AliOS_JoystickRumble, AliOS_JoystickUpdate, AliOS_JoystickClose, AliOS_JoystickQuit, AliOS_JoystickGetGamepadMapping }; #endif /* SDL_JOYSTICK_AliOS || SDL_JOYSTICK_DISABLED */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/alios/SDL_sysjoystick.c
C
apache-2.0
5,198
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_ANDROID #include <stdio.h> /* For the definition of NULL */ #include "SDL_error.h" #include "SDL_events.h" #include "SDL_joystick.h" #include "SDL_hints.h" #include "SDL_assert.h" #include "SDL_timer.h" #include "SDL_sysjoystick_c.h" #include "../SDL_joystick_c.h" #include "../../events/SDL_keyboard_c.h" #include "../../core/android/SDL_android.h" #include "../hidapi/SDL_hidapijoystick_c.h" #include "android/keycodes.h" /* As of platform android-14, android/keycodes.h is missing these defines */ #ifndef AKEYCODE_BUTTON_1 #define AKEYCODE_BUTTON_1 188 #define AKEYCODE_BUTTON_2 189 #define AKEYCODE_BUTTON_3 190 #define AKEYCODE_BUTTON_4 191 #define AKEYCODE_BUTTON_5 192 #define AKEYCODE_BUTTON_6 193 #define AKEYCODE_BUTTON_7 194 #define AKEYCODE_BUTTON_8 195 #define AKEYCODE_BUTTON_9 196 #define AKEYCODE_BUTTON_10 197 #define AKEYCODE_BUTTON_11 198 #define AKEYCODE_BUTTON_12 199 #define AKEYCODE_BUTTON_13 200 #define AKEYCODE_BUTTON_14 201 #define AKEYCODE_BUTTON_15 202 #define AKEYCODE_BUTTON_16 203 #endif #define ANDROID_ACCELEROMETER_NAME "Android Accelerometer" #define ANDROID_ACCELEROMETER_DEVICE_ID INT_MIN #define ANDROID_MAX_NBUTTONS 36 static SDL_joylist_item * JoystickByDeviceId(int device_id); static SDL_joylist_item *SDL_joylist = NULL; static SDL_joylist_item *SDL_joylist_tail = NULL; static int numjoysticks = 0; /* Public domain CRC implementation adapted from: http://home.thep.lu.se/~bjorn/crc/crc32_simple.c */ static Uint32 crc32_for_byte(Uint32 r) { int i; for(i = 0; i < 8; ++i) { r = (r & 1? 0: (Uint32)0xEDB88320L) ^ r >> 1; } return r ^ (Uint32)0xFF000000L; } static Uint32 crc32(const void *data, size_t count) { Uint32 crc = 0; int i; for(i = 0; i < count; ++i) { crc = crc32_for_byte((Uint8)crc ^ ((const Uint8*)data)[i]) ^ crc >> 8; } return crc; } /* Function to convert Android keyCodes into SDL ones. * This code manipulation is done to get a sequential list of codes. * FIXME: This is only suited for the case where we use a fixed number of buttons determined by ANDROID_MAX_NBUTTONS */ static int keycode_to_SDL(int keycode) { /* FIXME: If this function gets too unwieldy in the future, replace with a lookup table */ int button = 0; switch (keycode) { /* Some gamepad buttons (API 9) */ case AKEYCODE_BUTTON_A: button = SDL_CONTROLLER_BUTTON_A; break; case AKEYCODE_BUTTON_B: button = SDL_CONTROLLER_BUTTON_B; break; case AKEYCODE_BUTTON_X: button = SDL_CONTROLLER_BUTTON_X; break; case AKEYCODE_BUTTON_Y: button = SDL_CONTROLLER_BUTTON_Y; break; case AKEYCODE_BUTTON_L1: button = SDL_CONTROLLER_BUTTON_LEFTSHOULDER; break; case AKEYCODE_BUTTON_R1: button = SDL_CONTROLLER_BUTTON_RIGHTSHOULDER; break; case AKEYCODE_BUTTON_THUMBL: button = SDL_CONTROLLER_BUTTON_LEFTSTICK; break; case AKEYCODE_BUTTON_THUMBR: button = SDL_CONTROLLER_BUTTON_RIGHTSTICK; break; case AKEYCODE_BUTTON_START: button = SDL_CONTROLLER_BUTTON_START; break; case AKEYCODE_BACK: case AKEYCODE_BUTTON_SELECT: button = SDL_CONTROLLER_BUTTON_BACK; break; case AKEYCODE_BUTTON_MODE: button = SDL_CONTROLLER_BUTTON_GUIDE; break; case AKEYCODE_BUTTON_L2: button = SDL_CONTROLLER_BUTTON_MAX; /* Not supported by GameController */ break; case AKEYCODE_BUTTON_R2: button = SDL_CONTROLLER_BUTTON_MAX+1; /* Not supported by GameController */ break; case AKEYCODE_BUTTON_C: button = SDL_CONTROLLER_BUTTON_MAX+2; /* Not supported by GameController */ break; case AKEYCODE_BUTTON_Z: button = SDL_CONTROLLER_BUTTON_MAX+3; /* Not supported by GameController */ break; /* D-Pad key codes (API 1) */ case AKEYCODE_DPAD_UP: button = SDL_CONTROLLER_BUTTON_DPAD_UP; break; case AKEYCODE_DPAD_DOWN: button = SDL_CONTROLLER_BUTTON_DPAD_DOWN; break; case AKEYCODE_DPAD_LEFT: button = SDL_CONTROLLER_BUTTON_DPAD_LEFT; break; case AKEYCODE_DPAD_RIGHT: button = SDL_CONTROLLER_BUTTON_DPAD_RIGHT; break; case AKEYCODE_DPAD_CENTER: /* This is handled better by applications as the A button */ /*button = SDL_CONTROLLER_BUTTON_MAX+4;*/ /* Not supported by GameController */ button = SDL_CONTROLLER_BUTTON_A; break; /* More gamepad buttons (API 12), these get mapped to 20...35*/ case AKEYCODE_BUTTON_1: case AKEYCODE_BUTTON_2: case AKEYCODE_BUTTON_3: case AKEYCODE_BUTTON_4: case AKEYCODE_BUTTON_5: case AKEYCODE_BUTTON_6: case AKEYCODE_BUTTON_7: case AKEYCODE_BUTTON_8: case AKEYCODE_BUTTON_9: case AKEYCODE_BUTTON_10: case AKEYCODE_BUTTON_11: case AKEYCODE_BUTTON_12: case AKEYCODE_BUTTON_13: case AKEYCODE_BUTTON_14: case AKEYCODE_BUTTON_15: case AKEYCODE_BUTTON_16: button = keycode - AKEYCODE_BUTTON_1 + SDL_CONTROLLER_BUTTON_MAX + 5; break; default: return -1; /* break; -Wunreachable-code-break */ } /* This is here in case future generations, probably with six fingers per hand, * happily add new cases up above and forget to update the max number of buttons. */ SDL_assert(button < ANDROID_MAX_NBUTTONS); return button; } static SDL_Scancode button_to_scancode(int button) { switch (button) { case SDL_CONTROLLER_BUTTON_A: return SDL_SCANCODE_RETURN; case SDL_CONTROLLER_BUTTON_B: return SDL_SCANCODE_ESCAPE; case SDL_CONTROLLER_BUTTON_BACK: return SDL_SCANCODE_ESCAPE; case SDL_CONTROLLER_BUTTON_DPAD_UP: return SDL_SCANCODE_UP; case SDL_CONTROLLER_BUTTON_DPAD_DOWN: return SDL_SCANCODE_DOWN; case SDL_CONTROLLER_BUTTON_DPAD_LEFT: return SDL_SCANCODE_LEFT; case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: return SDL_SCANCODE_RIGHT; } /* Unsupported button */ return SDL_SCANCODE_UNKNOWN; } int Android_OnPadDown(int device_id, int keycode) { SDL_joylist_item *item; int button = keycode_to_SDL(keycode); if (button >= 0) { item = JoystickByDeviceId(device_id); if (item && item->joystick) { SDL_PrivateJoystickButton(item->joystick, button, SDL_PRESSED); } else { SDL_SendKeyboardKey(SDL_PRESSED, button_to_scancode(button)); } return 0; } return -1; } int Android_OnPadUp(int device_id, int keycode) { SDL_joylist_item *item; int button = keycode_to_SDL(keycode); if (button >= 0) { item = JoystickByDeviceId(device_id); if (item && item->joystick) { SDL_PrivateJoystickButton(item->joystick, button, SDL_RELEASED); } else { SDL_SendKeyboardKey(SDL_RELEASED, button_to_scancode(button)); } return 0; } return -1; } int Android_OnJoy(int device_id, int axis, float value) { /* Android gives joy info normalized as [-1.0, 1.0] or [0.0, 1.0] */ SDL_joylist_item *item = JoystickByDeviceId(device_id); if (item && item->joystick) { SDL_PrivateJoystickAxis(item->joystick, axis, (Sint16) (32767.*value)); } return 0; } int Android_OnHat(int device_id, int hat_id, int x, int y) { const int DPAD_UP_MASK = (1 << SDL_CONTROLLER_BUTTON_DPAD_UP); const int DPAD_DOWN_MASK = (1 << SDL_CONTROLLER_BUTTON_DPAD_DOWN); const int DPAD_LEFT_MASK = (1 << SDL_CONTROLLER_BUTTON_DPAD_LEFT); const int DPAD_RIGHT_MASK = (1 << SDL_CONTROLLER_BUTTON_DPAD_RIGHT); if (x >= -1 && x <= 1 && y >= -1 && y <= 1) { SDL_joylist_item *item = JoystickByDeviceId(device_id); if (item && item->joystick) { int dpad_state = 0; int dpad_delta; if (x < 0) { dpad_state |= DPAD_LEFT_MASK; } else if (x > 0) { dpad_state |= DPAD_RIGHT_MASK; } if (y < 0) { dpad_state |= DPAD_UP_MASK; } else if (y > 0) { dpad_state |= DPAD_DOWN_MASK; } dpad_delta = (dpad_state ^ item->dpad_state); if (dpad_delta) { if (dpad_delta & DPAD_UP_MASK) { SDL_PrivateJoystickButton(item->joystick, SDL_CONTROLLER_BUTTON_DPAD_UP, (dpad_state & DPAD_UP_MASK) ? SDL_PRESSED : SDL_RELEASED); } if (dpad_delta & DPAD_DOWN_MASK) { SDL_PrivateJoystickButton(item->joystick, SDL_CONTROLLER_BUTTON_DPAD_DOWN, (dpad_state & DPAD_DOWN_MASK) ? SDL_PRESSED : SDL_RELEASED); } if (dpad_delta & DPAD_LEFT_MASK) { SDL_PrivateJoystickButton(item->joystick, SDL_CONTROLLER_BUTTON_DPAD_LEFT, (dpad_state & DPAD_LEFT_MASK) ? SDL_PRESSED : SDL_RELEASED); } if (dpad_delta & DPAD_RIGHT_MASK) { SDL_PrivateJoystickButton(item->joystick, SDL_CONTROLLER_BUTTON_DPAD_RIGHT, (dpad_state & DPAD_RIGHT_MASK) ? SDL_PRESSED : SDL_RELEASED); } item->dpad_state = dpad_state; } } return 0; } return -1; } int Android_AddJoystick(int device_id, const char *name, const char *desc, int vendor_id, int product_id, SDL_bool is_accelerometer, int button_mask, int naxes, int nhats, int nballs) { SDL_joylist_item *item; SDL_JoystickGUID guid; Uint16 *guid16 = (Uint16 *)guid.data; int i; int axis_mask; if (!SDL_GetHintBoolean(SDL_HINT_TV_REMOTE_AS_JOYSTICK, SDL_TRUE)) { /* Ignore devices that aren't actually controllers (e.g. remotes), they'll be handled as keyboard input */ if (naxes < 2 && nhats < 1) { return -1; } } if (JoystickByDeviceId(device_id) != NULL || name == NULL) { return -1; } #ifdef SDL_JOYSTICK_HIDAPI if (HIDAPI_IsDevicePresent(vendor_id, product_id, 0, name)) { /* The HIDAPI driver is taking care of this device */ return -1; } #endif #ifdef DEBUG_JOYSTICK SDL_Log("Joystick: %s, descriptor %s, vendor = 0x%.4x, product = 0x%.4x, %d axes, %d hats\n", name, desc, vendor_id, product_id, naxes, nhats); #endif /* Add the available buttons and axes The axis mask should probably come from Java where there is more information about the axes... */ axis_mask = 0; if (!is_accelerometer) { if (naxes >= 2) { axis_mask |= ((1 << SDL_CONTROLLER_AXIS_LEFTX) | (1 << SDL_CONTROLLER_AXIS_LEFTY)); } if (naxes >= 4) { axis_mask |= ((1 << SDL_CONTROLLER_AXIS_RIGHTX) | (1 << SDL_CONTROLLER_AXIS_RIGHTY)); } if (naxes >= 6) { axis_mask |= ((1 << SDL_CONTROLLER_AXIS_TRIGGERLEFT) | (1 << SDL_CONTROLLER_AXIS_TRIGGERRIGHT)); } } if (nhats > 0) { /* Hat is translated into DPAD buttons */ button_mask |= ((1 << SDL_CONTROLLER_BUTTON_DPAD_UP) | (1 << SDL_CONTROLLER_BUTTON_DPAD_DOWN) | (1 << SDL_CONTROLLER_BUTTON_DPAD_LEFT) | (1 << SDL_CONTROLLER_BUTTON_DPAD_RIGHT)); nhats = 0; } SDL_memset(guid.data, 0, sizeof(guid.data)); /* We only need 16 bits for each of these; space them out to fill 128. */ /* Byteswap so devices get same GUID on little/big endian platforms. */ *guid16++ = SDL_SwapLE16(SDL_HARDWARE_BUS_BLUETOOTH); *guid16++ = 0; if (vendor_id && product_id) { *guid16++ = SDL_SwapLE16(vendor_id); *guid16++ = 0; *guid16++ = SDL_SwapLE16(product_id); *guid16++ = 0; } else { Uint32 crc = crc32(desc, SDL_strlen(desc)); SDL_memcpy(guid16, desc, SDL_min(2*sizeof(*guid16), SDL_strlen(desc))); guid16 += 2; *(Uint32 *)guid16 = SDL_SwapLE32(crc); guid16 += 2; } *guid16++ = SDL_SwapLE16(button_mask); *guid16++ = SDL_SwapLE16(axis_mask); item = (SDL_joylist_item *) SDL_malloc(sizeof (SDL_joylist_item)); if (item == NULL) { return -1; } SDL_zerop(item); item->guid = guid; item->device_id = device_id; item->name = SDL_CreateJoystickName(vendor_id, product_id, NULL, name); if (item->name == NULL) { SDL_free(item); return -1; } item->is_accelerometer = is_accelerometer; if (button_mask == 0xFFFFFFFF) { item->nbuttons = ANDROID_MAX_NBUTTONS; } else { for (i = 0; i < sizeof(button_mask)*8; ++i) { if (button_mask & (1 << i)) { item->nbuttons = i+1; } } } item->naxes = naxes; item->nhats = nhats; item->nballs = nballs; item->device_instance = SDL_GetNextJoystickInstanceID(); if (SDL_joylist_tail == NULL) { SDL_joylist = SDL_joylist_tail = item; } else { SDL_joylist_tail->next = item; SDL_joylist_tail = item; } /* Need to increment the joystick count before we post the event */ ++numjoysticks; SDL_PrivateJoystickAdded(item->device_instance); #ifdef DEBUG_JOYSTICK SDL_Log("Added joystick %s with device_id %d", item->name, device_id); #endif return numjoysticks; } int Android_RemoveJoystick(int device_id) { SDL_joylist_item *item = SDL_joylist; SDL_joylist_item *prev = NULL; /* Don't call JoystickByDeviceId here or there'll be an infinite loop! */ while (item != NULL) { if (item->device_id == device_id) { break; } prev = item; item = item->next; } if (item == NULL) { return -1; } if (item->joystick) { item->joystick->hwdata = NULL; } if (prev != NULL) { prev->next = item->next; } else { SDL_assert(SDL_joylist == item); SDL_joylist = item->next; } if (item == SDL_joylist_tail) { SDL_joylist_tail = prev; } /* Need to decrement the joystick count before we post the event */ --numjoysticks; SDL_PrivateJoystickRemoved(item->device_instance); #ifdef DEBUG_JOYSTICK SDL_Log("Removed joystick with device_id %d", device_id); #endif SDL_free(item->name); SDL_free(item); return numjoysticks; } static void ANDROID_JoystickDetect(void); static int ANDROID_JoystickInit(void) { ANDROID_JoystickDetect(); if (SDL_GetHintBoolean(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, SDL_TRUE)) { /* Default behavior, accelerometer as joystick */ Android_AddJoystick(ANDROID_ACCELEROMETER_DEVICE_ID, ANDROID_ACCELEROMETER_NAME, ANDROID_ACCELEROMETER_NAME, 0, 0, SDL_TRUE, 0, 3, 0, 0); } return 0; } static int ANDROID_JoystickGetCount(void) { return numjoysticks; } static void ANDROID_JoystickDetect(void) { /* Support for device connect/disconnect is API >= 16 only, * so we poll every three seconds * Ref: http://developer.android.com/reference/android/hardware/input/InputManager.InputDeviceListener.html */ static Uint32 timeout = 0; if (!timeout || SDL_TICKS_PASSED(SDL_GetTicks(), timeout)) { timeout = SDL_GetTicks() + 3000; Android_JNI_PollInputDevices(); } } static SDL_joylist_item * JoystickByDevIndex(int device_index) { SDL_joylist_item *item = SDL_joylist; if ((device_index < 0) || (device_index >= numjoysticks)) { return NULL; } while (device_index > 0) { SDL_assert(item != NULL); device_index--; item = item->next; } return item; } static SDL_joylist_item * JoystickByDeviceId(int device_id) { SDL_joylist_item *item = SDL_joylist; while (item != NULL) { if (item->device_id == device_id) { return item; } item = item->next; } /* Joystick not found, try adding it */ ANDROID_JoystickDetect(); while (item != NULL) { if (item->device_id == device_id) { return item; } item = item->next; } return NULL; } static const char * ANDROID_JoystickGetDeviceName(int device_index) { return JoystickByDevIndex(device_index)->name; } static int ANDROID_JoystickGetDevicePlayerIndex(int device_index) { return -1; } static void ANDROID_JoystickSetDevicePlayerIndex(int device_index, int player_index) { } static SDL_JoystickGUID ANDROID_JoystickGetDeviceGUID(int device_index) { return JoystickByDevIndex(device_index)->guid; } static SDL_JoystickID ANDROID_JoystickGetDeviceInstanceID(int device_index) { return JoystickByDevIndex(device_index)->device_instance; } static int ANDROID_JoystickOpen(SDL_Joystick * joystick, int device_index) { SDL_joylist_item *item = JoystickByDevIndex(device_index); if (item == NULL) { return SDL_SetError("No such device"); } if (item->joystick != NULL) { return SDL_SetError("Joystick already opened"); } joystick->instance_id = item->device_instance; joystick->hwdata = (struct joystick_hwdata *) item; item->joystick = joystick; joystick->nhats = item->nhats; joystick->nballs = item->nballs; joystick->nbuttons = item->nbuttons; joystick->naxes = item->naxes; return (0); } static int ANDROID_JoystickRumble(SDL_Joystick * joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { return SDL_Unsupported(); } static void ANDROID_JoystickUpdate(SDL_Joystick * joystick) { SDL_joylist_item *item = (SDL_joylist_item *) joystick->hwdata; if (item == NULL) { return; } if (item->is_accelerometer) { int i; Sint16 value; float values[3]; if (Android_JNI_GetAccelerometerValues(values)) { for (i = 0; i < 3; i++) { if (values[i] > 1.0f) { values[i] = 1.0f; } else if (values[i] < -1.0f) { values[i] = -1.0f; } value = (Sint16)(values[i] * 32767.0f); SDL_PrivateJoystickAxis(item->joystick, i, value); } } } } static void ANDROID_JoystickClose(SDL_Joystick * joystick) { SDL_joylist_item *item = (SDL_joylist_item *) joystick->hwdata; if (item) { item->joystick = NULL; } } static void ANDROID_JoystickQuit(void) { /* We don't have any way to scan for joysticks at init, so don't wipe the list * of joysticks here in case this is a reinit. */ #if 0 SDL_joylist_item *item = NULL; SDL_joylist_item *next = NULL; for (item = SDL_joylist; item; item = next) { next = item->next; SDL_free(item->name); SDL_free(item); } SDL_joylist = SDL_joylist_tail = NULL; numjoysticks = 0; #endif /* 0 */ } static SDL_bool ANDROID_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) { return SDL_FALSE; } SDL_JoystickDriver SDL_ANDROID_JoystickDriver = { ANDROID_JoystickInit, ANDROID_JoystickGetCount, ANDROID_JoystickDetect, ANDROID_JoystickGetDeviceName, ANDROID_JoystickGetDevicePlayerIndex, ANDROID_JoystickSetDevicePlayerIndex, ANDROID_JoystickGetDeviceGUID, ANDROID_JoystickGetDeviceInstanceID, ANDROID_JoystickOpen, ANDROID_JoystickRumble, ANDROID_JoystickUpdate, ANDROID_JoystickClose, ANDROID_JoystickQuit, ANDROID_JoystickGetGamepadMapping }; #endif /* SDL_JOYSTICK_ANDROID */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/android/SDL_sysjoystick.c
C
apache-2.0
21,036
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_ANDROID #ifndef SDL_sysjoystick_c_h_ #define SDL_sysjoystick_c_h_ #include "../SDL_sysjoystick.h" extern int Android_OnPadDown(int device_id, int keycode); extern int Android_OnPadUp(int device_id, int keycode); extern int Android_OnJoy(int device_id, int axisnum, float value); extern int Android_OnHat(int device_id, int hat_id, int x, int y); extern int Android_AddJoystick(int device_id, const char *name, const char *desc, int vendor_id, int product_id, SDL_bool is_accelerometer, int button_mask, int naxes, int nhats, int nballs); extern int Android_RemoveJoystick(int device_id); /* A linked list of available joysticks */ typedef struct SDL_joylist_item { int device_instance; int device_id; /* Android's device id */ char *name; /* "SideWinder 3D Pro" or whatever */ SDL_JoystickGUID guid; SDL_bool is_accelerometer; SDL_Joystick *joystick; int nbuttons, naxes, nhats, nballs; int dpad_state; struct SDL_joylist_item *next; } SDL_joylist_item; typedef SDL_joylist_item joystick_hwdata; #endif /* SDL_sysjoystick_c_h_ */ #endif /* SDL_JOYSTICK_ANDROID */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/android/SDL_sysjoystick_c.h
C
apache-2.0
2,143
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_USBHID /* * Joystick driver for the uhid(4) interface found in OpenBSD, * NetBSD and FreeBSD. * * Maintainer: <vedge at csoft.org> */ #include <sys/param.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #ifndef __FreeBSD_kernel_version #define __FreeBSD_kernel_version __FreeBSD_version #endif #if defined(HAVE_USB_H) #include <usb.h> #endif #ifdef __DragonFly__ #include <bus/usb/usb.h> #include <bus/usb/usbhid.h> #else #include <dev/usb/usb.h> #include <dev/usb/usbhid.h> #endif #if defined(HAVE_USBHID_H) #include <usbhid.h> #elif defined(HAVE_LIBUSB_H) #include <libusb.h> #elif defined(HAVE_LIBUSBHID_H) #include <libusbhid.h> #endif #if defined(__FREEBSD__) || defined(__FreeBSD_kernel__) #ifndef __DragonFly__ #include <osreldate.h> #endif #if __FreeBSD_kernel_version > 800063 #include <dev/usb/usb_ioctl.h> #endif #include <sys/joystick.h> #endif #if SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H #include <machine/joystick.h> #endif #include "SDL_joystick.h" #include "../SDL_sysjoystick.h" #include "../SDL_joystick_c.h" #define MAX_UHID_JOYS 64 #define MAX_JOY_JOYS 2 #define MAX_JOYS (MAX_UHID_JOYS + MAX_JOY_JOYS) #ifdef __OpenBSD__ #define HUG_DPAD_UP 0x90 #define HUG_DPAD_DOWN 0x91 #define HUG_DPAD_RIGHT 0x92 #define HUG_DPAD_LEFT 0x93 #define HAT_CENTERED 0x00 #define HAT_UP 0x01 #define HAT_RIGHT 0x02 #define HAT_DOWN 0x04 #define HAT_LEFT 0x08 #define HAT_RIGHTUP (HAT_RIGHT|HAT_UP) #define HAT_RIGHTDOWN (HAT_RIGHT|HAT_DOWN) #define HAT_LEFTUP (HAT_LEFT|HAT_UP) #define HAT_LEFTDOWN (HAT_LEFT|HAT_DOWN) /* calculate the value from the state of the dpad */ int dpad_to_sdl(Sint32 *dpad) { if (dpad[2]) { if (dpad[0]) return HAT_RIGHTUP; else if (dpad[1]) return HAT_RIGHTDOWN; else return HAT_RIGHT; } else if (dpad[3]) { if (dpad[0]) return HAT_LEFTUP; else if (dpad[1]) return HAT_LEFTDOWN; else return HAT_LEFT; } else if (dpad[0]) { return HAT_UP; } else if (dpad[1]) { return HAT_DOWN; } return HAT_CENTERED; } #endif struct report { #if defined(__FREEBSD__) && (__FreeBSD_kernel_version > 900000) void *buf; /* Buffer */ #elif defined(__FREEBSD__) && (__FreeBSD_kernel_version > 800063) struct usb_gen_descriptor *buf; /* Buffer */ #else struct usb_ctl_report *buf; /* Buffer */ #endif size_t size; /* Buffer size */ int rid; /* Report ID */ enum { SREPORT_UNINIT, SREPORT_CLEAN, SREPORT_DIRTY } status; }; static struct { int uhid_report; hid_kind_t kind; const char *name; } const repinfo[] = { {UHID_INPUT_REPORT, hid_input, "input"}, {UHID_OUTPUT_REPORT, hid_output, "output"}, {UHID_FEATURE_REPORT, hid_feature, "feature"} }; enum { REPORT_INPUT = 0, REPORT_OUTPUT = 1, REPORT_FEATURE = 2 }; enum { JOYAXE_X, JOYAXE_Y, JOYAXE_Z, JOYAXE_SLIDER, JOYAXE_WHEEL, JOYAXE_RX, JOYAXE_RY, JOYAXE_RZ, JOYAXE_count }; struct joystick_hwdata { int fd; char *path; enum { BSDJOY_UHID, /* uhid(4) */ BSDJOY_JOY /* joy(4) */ } type; struct report_desc *repdesc; struct report inreport; int axis_map[JOYAXE_count]; /* map present JOYAXE_* to 0,1,.. */ }; static char *joynames[MAX_JOYS]; static char *joydevnames[MAX_JOYS]; static int report_alloc(struct report *, struct report_desc *, int); static void report_free(struct report *); #if defined(USBHID_UCR_DATA) || (defined(__FreeBSD_kernel__) && __FreeBSD_kernel_version <= 800063) #define REP_BUF_DATA(rep) ((rep)->buf->ucr_data) #elif (defined(__FREEBSD__) && (__FreeBSD_kernel_version > 900000)) #define REP_BUF_DATA(rep) ((rep)->buf) #elif (defined(__FREEBSD__) && (__FreeBSD_kernel_version > 800063)) #define REP_BUF_DATA(rep) ((rep)->buf->ugd_data) #else #define REP_BUF_DATA(rep) ((rep)->buf->data) #endif static int numjoysticks = 0; static int BSD_JoystickOpen(SDL_Joystick * joy, int device_index); static void BSD_JoystickClose(SDL_Joystick * joy); static int BSD_JoystickInit(void) { char s[16]; int i, fd; numjoysticks = 0; SDL_memset(joynames, 0, sizeof(joynames)); SDL_memset(joydevnames, 0, sizeof(joydevnames)); for (i = 0; i < MAX_UHID_JOYS; i++) { SDL_Joystick nj; SDL_snprintf(s, SDL_arraysize(s), "/dev/uhid%d", i); joynames[numjoysticks] = SDL_strdup(s); if (BSD_JoystickOpen(&nj, numjoysticks) == 0) { BSD_JoystickClose(&nj); numjoysticks++; } else { SDL_free(joynames[numjoysticks]); joynames[numjoysticks] = NULL; } } for (i = 0; i < MAX_JOY_JOYS; i++) { SDL_snprintf(s, SDL_arraysize(s), "/dev/joy%d", i); fd = open(s, O_RDONLY); if (fd != -1) { joynames[numjoysticks++] = SDL_strdup(s); close(fd); } } /* Read the default USB HID usage table. */ hid_init(NULL); return (numjoysticks); } static int BSD_JoystickGetCount(void) { return numjoysticks; } static void BSD_JoystickDetect(void) { } static const char * BSD_JoystickGetDeviceName(int device_index) { if (joydevnames[device_index] != NULL) { return (joydevnames[device_index]); } return (joynames[device_index]); } static int BSD_JoystickGetDevicePlayerIndex(int device_index) { return -1; } static void BSD_JoystickSetDevicePlayerIndex(int device_index, int player_index) { } /* Function to perform the mapping from device index to the instance id for this index */ static SDL_JoystickID BSD_JoystickGetDeviceInstanceID(int device_index) { return device_index; } static int usage_to_joyaxe(unsigned usage) { int joyaxe; switch (usage) { case HUG_X: joyaxe = JOYAXE_X; break; case HUG_Y: joyaxe = JOYAXE_Y; break; case HUG_Z: joyaxe = JOYAXE_Z; break; case HUG_SLIDER: joyaxe = JOYAXE_SLIDER; break; case HUG_WHEEL: joyaxe = JOYAXE_WHEEL; break; case HUG_RX: joyaxe = JOYAXE_RX; break; case HUG_RY: joyaxe = JOYAXE_RY; break; case HUG_RZ: joyaxe = JOYAXE_RZ; break; default: joyaxe = -1; } return joyaxe; } static unsigned hatval_to_sdl(Sint32 hatval) { static const unsigned hat_dir_map[8] = { SDL_HAT_UP, SDL_HAT_RIGHTUP, SDL_HAT_RIGHT, SDL_HAT_RIGHTDOWN, SDL_HAT_DOWN, SDL_HAT_LEFTDOWN, SDL_HAT_LEFT, SDL_HAT_LEFTUP }; unsigned result; if ((hatval & 7) == hatval) result = hat_dir_map[hatval]; else result = SDL_HAT_CENTERED; return result; } static int BSD_JoystickOpen(SDL_Joystick * joy, int device_index) { char *path = joynames[device_index]; struct joystick_hwdata *hw; struct hid_item hitem; struct hid_data *hdata; struct report *rep = NULL; #if defined(__NetBSD__) usb_device_descriptor_t udd; struct usb_string_desc usd; #endif int fd; int i; fd = open(path, O_RDONLY); if (fd == -1) { return SDL_SetError("%s: %s", path, strerror(errno)); } joy->instance_id = device_index; hw = (struct joystick_hwdata *) SDL_malloc(sizeof(struct joystick_hwdata)); if (hw == NULL) { close(fd); return SDL_OutOfMemory(); } joy->hwdata = hw; hw->fd = fd; hw->path = SDL_strdup(path); if (!SDL_strncmp(path, "/dev/joy", 8)) { hw->type = BSDJOY_JOY; joy->naxes = 2; joy->nbuttons = 2; joy->nhats = 0; joy->nballs = 0; joydevnames[device_index] = SDL_strdup("Gameport joystick"); goto usbend; } else { hw->type = BSDJOY_UHID; } { int ax; for (ax = 0; ax < JOYAXE_count; ax++) hw->axis_map[ax] = -1; } hw->repdesc = hid_get_report_desc(fd); if (hw->repdesc == NULL) { SDL_SetError("%s: USB_GET_REPORT_DESC: %s", hw->path, strerror(errno)); goto usberr; } rep = &hw->inreport; #if defined(__FREEBSD__) && (__FreeBSD_kernel_version > 800063) || defined(__FreeBSD_kernel__) rep->rid = hid_get_report_id(fd); if (rep->rid < 0) { #else if (ioctl(fd, USB_GET_REPORT_ID, &rep->rid) < 0) { #endif rep->rid = -1; /* XXX */ } #if defined(__NetBSD__) if (ioctl(fd, USB_GET_DEVICE_DESC, &udd) == -1) goto desc_failed; /* Get default language */ usd.usd_string_index = USB_LANGUAGE_TABLE; usd.usd_language_id = 0; if (ioctl(fd, USB_GET_STRING_DESC, &usd) == -1 || usd.usd_desc.bLength < 4) { usd.usd_language_id = 0; } else { usd.usd_language_id = UGETW(usd.usd_desc.bString[0]); } usd.usd_string_index = udd.iProduct; if (ioctl(fd, USB_GET_STRING_DESC, &usd) == 0) { char str[128]; char *new_name = NULL; int i; for (i = 0; i < (usd.usd_desc.bLength >> 1) - 1 && i < sizeof(str) - 1; i++) { str[i] = UGETW(usd.usd_desc.bString[i]); } str[i] = '\0'; asprintf(&new_name, "%s @ %s", str, path); if (new_name != NULL) { SDL_free(joydevnames[numjoysticks]); joydevnames[numjoysticks] = new_name; } } desc_failed: #endif if (report_alloc(rep, hw->repdesc, REPORT_INPUT) < 0) { goto usberr; } if (rep->size <= 0) { SDL_SetError("%s: Input report descriptor has invalid length", hw->path); goto usberr; } #if defined(USBHID_NEW) || (defined(__FREEBSD__) && __FreeBSD_kernel_version >= 500111) || defined(__FreeBSD_kernel__) hdata = hid_start_parse(hw->repdesc, 1 << hid_input, rep->rid); #else hdata = hid_start_parse(hw->repdesc, 1 << hid_input); #endif if (hdata == NULL) { SDL_SetError("%s: Cannot start HID parser", hw->path); goto usberr; } joy->naxes = 0; joy->nbuttons = 0; joy->nhats = 0; joy->nballs = 0; for (i = 0; i < JOYAXE_count; i++) hw->axis_map[i] = -1; while (hid_get_item(hdata, &hitem) > 0) { char *sp; const char *s; switch (hitem.kind) { case hid_collection: switch (HID_PAGE(hitem.usage)) { case HUP_GENERIC_DESKTOP: switch (HID_USAGE(hitem.usage)) { case HUG_JOYSTICK: case HUG_GAME_PAD: s = hid_usage_in_page(hitem.usage); sp = SDL_malloc(SDL_strlen(s) + 5); SDL_snprintf(sp, SDL_strlen(s) + 5, "%s (%d)", s, device_index); joydevnames[device_index] = sp; } } break; case hid_input: switch (HID_PAGE(hitem.usage)) { case HUP_GENERIC_DESKTOP: { unsigned usage = HID_USAGE(hitem.usage); int joyaxe = usage_to_joyaxe(usage); if (joyaxe >= 0) { hw->axis_map[joyaxe] = 1; } else if (usage == HUG_HAT_SWITCH #ifdef __OpenBSD__ || usage == HUG_DPAD_UP #endif ) { joy->nhats++; } break; } case HUP_BUTTON: joy->nbuttons++; break; default: break; } break; default: break; } } hid_end_parse(hdata); for (i = 0; i < JOYAXE_count; i++) if (hw->axis_map[i] > 0) hw->axis_map[i] = joy->naxes++; if (joy->naxes == 0 && joy->nbuttons == 0 && joy->nhats == 0 && joy->nballs == 0) { SDL_SetError("%s: Not a joystick, ignoring", hw->path); goto usberr; } usbend: /* The poll blocks the event thread. */ fcntl(fd, F_SETFL, O_NONBLOCK); #ifdef __NetBSD__ /* Flush pending events */ if (rep) { while (read(joy->hwdata->fd, REP_BUF_DATA(rep), rep->size) == rep->size) ; } #endif return (0); usberr: close(hw->fd); SDL_free(hw->path); SDL_free(hw); return (-1); } static void BSD_JoystickUpdate(SDL_Joystick * joy) { struct hid_item hitem; struct hid_data *hdata; struct report *rep; int nbutton, naxe = -1; Sint32 v; #ifdef __OpenBSD__ Sint32 dpad[4] = {0, 0, 0, 0}; #endif #if defined(__FREEBSD__) || SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H || defined(__FreeBSD_kernel__) struct joystick gameport; static int x, y, xmin = 0xffff, ymin = 0xffff, xmax = 0, ymax = 0; if (joy->hwdata->type == BSDJOY_JOY) { while (read(joy->hwdata->fd, &gameport, sizeof gameport) == sizeof gameport) { if (abs(x - gameport.x) > 8) { x = gameport.x; if (x < xmin) { xmin = x; } if (x > xmax) { xmax = x; } if (xmin == xmax) { xmin--; xmax++; } v = (Sint32) x; v -= (xmax + xmin + 1) / 2; v *= 32768 / ((xmax - xmin + 1) / 2); SDL_PrivateJoystickAxis(joy, 0, v); } if (abs(y - gameport.y) > 8) { y = gameport.y; if (y < ymin) { ymin = y; } if (y > ymax) { ymax = y; } if (ymin == ymax) { ymin--; ymax++; } v = (Sint32) y; v -= (ymax + ymin + 1) / 2; v *= 32768 / ((ymax - ymin + 1) / 2); SDL_PrivateJoystickAxis(joy, 1, v); } SDL_PrivateJoystickButton(joy, 0, gameport.b1); SDL_PrivateJoystickButton(joy, 1, gameport.b2); } return; } #endif /* defined(__FREEBSD__) || SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H */ rep = &joy->hwdata->inreport; while (read(joy->hwdata->fd, REP_BUF_DATA(rep), rep->size) == rep->size) { #if defined(USBHID_NEW) || (defined(__FREEBSD__) && __FreeBSD_kernel_version >= 500111) || defined(__FreeBSD_kernel__) hdata = hid_start_parse(joy->hwdata->repdesc, 1 << hid_input, rep->rid); #else hdata = hid_start_parse(joy->hwdata->repdesc, 1 << hid_input); #endif if (hdata == NULL) { /*fprintf(stderr, "%s: Cannot start HID parser\n", joy->hwdata->path);*/ continue; } for (nbutton = 0; hid_get_item(hdata, &hitem) > 0;) { switch (hitem.kind) { case hid_input: switch (HID_PAGE(hitem.usage)) { case HUP_GENERIC_DESKTOP: { unsigned usage = HID_USAGE(hitem.usage); int joyaxe = usage_to_joyaxe(usage); if (joyaxe >= 0) { naxe = joy->hwdata->axis_map[joyaxe]; /* scaleaxe */ v = (Sint32) hid_get_data(REP_BUF_DATA(rep), &hitem); v -= (hitem.logical_maximum + hitem.logical_minimum + 1) / 2; v *= 32768 / ((hitem.logical_maximum - hitem.logical_minimum + 1) / 2); SDL_PrivateJoystickAxis(joy, naxe, v); } else if (usage == HUG_HAT_SWITCH) { v = (Sint32) hid_get_data(REP_BUF_DATA(rep), &hitem); SDL_PrivateJoystickHat(joy, 0, hatval_to_sdl(v) - hitem.logical_minimum); } #ifdef __OpenBSD__ else if (usage == HUG_DPAD_UP) { dpad[0] = (Sint32) hid_get_data(REP_BUF_DATA(rep), &hitem); SDL_PrivateJoystickHat(joy, 0, dpad_to_sdl(dpad)); } else if (usage == HUG_DPAD_DOWN) { dpad[1] = (Sint32) hid_get_data(REP_BUF_DATA(rep), &hitem); SDL_PrivateJoystickHat(joy, 0, dpad_to_sdl(dpad)); } else if (usage == HUG_DPAD_RIGHT) { dpad[2] = (Sint32) hid_get_data(REP_BUF_DATA(rep), &hitem); SDL_PrivateJoystickHat(joy, 0, dpad_to_sdl(dpad)); } else if (usage == HUG_DPAD_LEFT) { dpad[3] = (Sint32) hid_get_data(REP_BUF_DATA(rep), &hitem); SDL_PrivateJoystickHat(joy, 0, dpad_to_sdl(dpad)); } #endif break; } case HUP_BUTTON: v = (Sint32) hid_get_data(REP_BUF_DATA(rep), &hitem); SDL_PrivateJoystickButton(joy, nbutton, v); nbutton++; break; default: continue; } break; default: break; } } hid_end_parse(hdata); } } /* Function to close a joystick after use */ static void BSD_JoystickClose(SDL_Joystick * joy) { if (SDL_strncmp(joy->hwdata->path, "/dev/joy", 8)) { report_free(&joy->hwdata->inreport); hid_dispose_report_desc(joy->hwdata->repdesc); } close(joy->hwdata->fd); SDL_free(joy->hwdata->path); SDL_free(joy->hwdata); } static void BSD_JoystickQuit(void) { int i; for (i = 0; i < MAX_JOYS; i++) { SDL_free(joynames[i]); SDL_free(joydevnames[i]); } return; } static SDL_JoystickGUID BSD_JoystickGetDeviceGUID( int device_index ) { SDL_JoystickGUID guid; /* the GUID is just the first 16 chars of the name for now */ const char *name = BSD_JoystickGetDeviceName( device_index ); SDL_zero( guid ); SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) ); return guid; } static int report_alloc(struct report *r, struct report_desc *rd, int repind) { int len; #ifdef __DragonFly__ len = hid_report_size(rd, r->rid, repinfo[repind].kind); #elif __FREEBSD__ # if (__FreeBSD_kernel_version >= 460000) || defined(__FreeBSD_kernel__) # if (__FreeBSD_kernel_version <= 500111) len = hid_report_size(rd, r->rid, repinfo[repind].kind); # else len = hid_report_size(rd, repinfo[repind].kind, r->rid); # endif # else len = hid_report_size(rd, repinfo[repind].kind, &r->rid); # endif #else # ifdef USBHID_NEW len = hid_report_size(rd, repinfo[repind].kind, r->rid); # else len = hid_report_size(rd, repinfo[repind].kind, &r->rid); # endif #endif if (len < 0) { return SDL_SetError("Negative HID report size"); } r->size = len; if (r->size > 0) { #if defined(__FREEBSD__) && (__FreeBSD_kernel_version > 900000) r->buf = SDL_malloc(r->size); #else r->buf = SDL_malloc(sizeof(*r->buf) - sizeof(REP_BUF_DATA(r)) + r->size); #endif if (r->buf == NULL) { return SDL_OutOfMemory(); } } else { r->buf = NULL; } r->status = SREPORT_CLEAN; return 0; } static void report_free(struct report *r) { SDL_free(r->buf); r->status = SREPORT_UNINIT; } static int BSD_JoystickRumble(SDL_Joystick * joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { return SDL_Unsupported(); } static SDL_bool BSD_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) { return SDL_FALSE; } SDL_JoystickDriver SDL_BSD_JoystickDriver = { BSD_JoystickInit, BSD_JoystickGetCount, BSD_JoystickDetect, BSD_JoystickGetDeviceName, BSD_JoystickGetDevicePlayerIndex, BSD_JoystickSetDevicePlayerIndex, BSD_JoystickGetDeviceGUID, BSD_JoystickGetDeviceInstanceID, BSD_JoystickOpen, BSD_JoystickRumble, BSD_JoystickUpdate, BSD_JoystickClose, BSD_JoystickQuit, BSD_JoystickGetGamepadMapping }; #endif /* SDL_JOYSTICK_USBHID */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/bsd/SDL_sysjoystick.c
C
apache-2.0
21,770
#!/bin/sh # # Check to make sure 8BitDo controller configurations are correct echo "Expected output:" cat <<__EOF__ "050000003512000020ab000000780f00,8BitDo SNES30 Gamepad,a:b20,b:b21,back:b30,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b26,rightshoulder:b27,start:b31,x:b23,y:b24,hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", "050000003512000020ab000000780f00,8BitDo SNES30 Gamepad,a:b21,b:b20,back:b30,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b26,rightshoulder:b27,start:b31,x:b24,y:b23,hint:!SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1,", __EOF__ echo "Actual output:" fgrep 8BitDo SDL_gamecontrollerdb.h | fgrep -v hint egrep "hint:SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1" SDL_gamecontrollerdb.h | fgrep -i 8bit | fgrep -v x:b2,y:b3 | fgrep -v x:b3,y:b4 egrep "hint:.SDL_GAMECONTROLLER_USE_BUTTON_LABELS:=1" SDL_gamecontrollerdb.h | fgrep -i 8bit | fgrep -v x:b3,y:b2 | fgrep -v x:b4,y:b3
YifuLiu/AliOS-Things
components/SDL2/src/joystick/check_8bitdo.sh
Shell
apache-2.0
931
/* Copyright (C) Valve Corporation This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef CONTROLLER_TYPE_H #define CONTROLLER_TYPE_H #ifdef _WIN32 #pragma once #endif //----------------------------------------------------------------------------- // Purpose: Steam Controller models // WARNING: DO NOT RENUMBER EXISTING VALUES - STORED IN A DATABASE //----------------------------------------------------------------------------- typedef enum { k_eControllerType_None = -1, k_eControllerType_Unknown = 0, // Steam Controllers k_eControllerType_UnknownSteamController = 1, k_eControllerType_SteamController = 2, k_eControllerType_SteamControllerV2 = 3, // Other Controllers k_eControllerType_UnknownNonSteamController = 30, k_eControllerType_XBox360Controller = 31, k_eControllerType_XBoxOneController = 32, k_eControllerType_PS3Controller = 33, k_eControllerType_PS4Controller = 34, k_eControllerType_WiiController = 35, k_eControllerType_AppleController = 36, k_eControllerType_AndroidController = 37, k_eControllerType_SwitchProController = 38, k_eControllerType_SwitchJoyConLeft = 39, k_eControllerType_SwitchJoyConRight = 40, k_eControllerType_SwitchJoyConPair = 41, k_eControllerType_SwitchInputOnlyController = 42, k_eControllerType_MobileTouch = 43, k_eControllerType_XInputSwitchController = 44, // Client-side only, used to mark Switch-compatible controllers as not supporting Switch controller protocol k_eControllerType_LastController, // Don't add game controllers below this enumeration - this enumeration can change value // Keyboards and Mice k_eControllertype_GenericKeyboard = 400, k_eControllertype_GenericMouse = 800, } EControllerType; #define MAKE_CONTROLLER_ID( nVID, nPID ) (unsigned int)( (unsigned int)nVID << 16 | (unsigned int)nPID ) typedef struct { unsigned int m_unDeviceID; EControllerType m_eControllerType; const char *m_pszName; } ControllerDescription_t; static const ControllerDescription_t arrControllers[] = { { MAKE_CONTROLLER_ID( 0x0079, 0x181a ), k_eControllerType_PS3Controller, NULL }, // Venom Arcade Stick { MAKE_CONTROLLER_ID( 0x0079, 0x1844 ), k_eControllerType_PS3Controller, NULL }, // From SDL { MAKE_CONTROLLER_ID( 0x044f, 0xb315 ), k_eControllerType_PS3Controller, NULL }, // Firestorm Dual Analog 3 { MAKE_CONTROLLER_ID( 0x044f, 0xd007 ), k_eControllerType_PS3Controller, NULL }, // Thrustmaster wireless 3-1 { MAKE_CONTROLLER_ID( 0x054c, 0x0268 ), k_eControllerType_PS3Controller, NULL }, // Sony PS3 Controller { MAKE_CONTROLLER_ID( 0x056e, 0x200f ), k_eControllerType_PS3Controller, NULL }, // From SDL { MAKE_CONTROLLER_ID( 0x056e, 0x2013 ), k_eControllerType_PS3Controller, NULL }, // JC-U4113SBK { MAKE_CONTROLLER_ID( 0x05b8, 0x1004 ), k_eControllerType_PS3Controller, NULL }, // From SDL { MAKE_CONTROLLER_ID( 0x05b8, 0x1006 ), k_eControllerType_PS3Controller, NULL }, // JC-U3412SBK { MAKE_CONTROLLER_ID( 0x06a3, 0xf622 ), k_eControllerType_PS3Controller, NULL }, // Cyborg V3 { MAKE_CONTROLLER_ID( 0x0738, 0x3180 ), k_eControllerType_PS3Controller, NULL }, // Mad Catz Alpha PS3 mode { MAKE_CONTROLLER_ID( 0x0738, 0x3250 ), k_eControllerType_PS3Controller, NULL }, // madcats fightpad pro ps3 { MAKE_CONTROLLER_ID( 0x0738, 0x8180 ), k_eControllerType_PS3Controller, NULL }, // Mad Catz Alpha PS4 mode (no touchpad on device) { MAKE_CONTROLLER_ID( 0x0738, 0x8838 ), k_eControllerType_PS3Controller, NULL }, // Madcatz Fightstick Pro { MAKE_CONTROLLER_ID( 0x0810, 0x0001 ), k_eControllerType_PS3Controller, NULL }, // actually ps2 - maybe break out later { MAKE_CONTROLLER_ID( 0x0810, 0x0003 ), k_eControllerType_PS3Controller, NULL }, // actually ps2 - maybe break out later { MAKE_CONTROLLER_ID( 0x0925, 0x0005 ), k_eControllerType_PS3Controller, NULL }, // Sony PS3 Controller { MAKE_CONTROLLER_ID( 0x0925, 0x8866 ), k_eControllerType_PS3Controller, NULL }, // PS2 maybe break out later { MAKE_CONTROLLER_ID( 0x0925, 0x8888 ), k_eControllerType_PS3Controller, NULL }, // Actually ps2 -maybe break out later Lakeview Research WiseGroup Ltd, MP-8866 Dual Joypad { MAKE_CONTROLLER_ID( 0x0e6f, 0x0109 ), k_eControllerType_PS3Controller, NULL }, // PDP Versus Fighting Pad { MAKE_CONTROLLER_ID( 0x0e6f, 0x011e ), k_eControllerType_PS3Controller, NULL }, // Rock Candy PS4 { MAKE_CONTROLLER_ID( 0x0e6f, 0x0128 ), k_eControllerType_PS3Controller, NULL }, // Rock Candy PS3 { MAKE_CONTROLLER_ID( 0x0e6f, 0x0203 ), k_eControllerType_PS3Controller, NULL }, // Victrix Pro FS (PS4 peripheral but no trackpad/lightbar) { MAKE_CONTROLLER_ID( 0x0e6f, 0x0214 ), k_eControllerType_PS3Controller, NULL }, // afterglow ps3 { MAKE_CONTROLLER_ID( 0x0e6f, 0x1314 ), k_eControllerType_PS3Controller, NULL }, // PDP Afterglow Wireless PS3 controller { MAKE_CONTROLLER_ID( 0x0e6f, 0x6302 ), k_eControllerType_PS3Controller, NULL }, // From SDL { MAKE_CONTROLLER_ID( 0x0e8f, 0x0008 ), k_eControllerType_PS3Controller, NULL }, // Green Asia { MAKE_CONTROLLER_ID( 0x0e8f, 0x3075 ), k_eControllerType_PS3Controller, NULL }, // SpeedLink Strike FX { MAKE_CONTROLLER_ID( 0x0e8f, 0x310d ), k_eControllerType_PS3Controller, NULL }, // From SDL { MAKE_CONTROLLER_ID( 0x0f0d, 0x0009 ), k_eControllerType_PS3Controller, NULL }, // HORI BDA GP1 { MAKE_CONTROLLER_ID( 0x0f0d, 0x004d ), k_eControllerType_PS3Controller, NULL }, // Horipad 3 { MAKE_CONTROLLER_ID( 0x0f0d, 0x005e ), k_eControllerType_PS3Controller, NULL }, // HORI Fighting commander ps4 { MAKE_CONTROLLER_ID( 0x0f0d, 0x005f ), k_eControllerType_PS3Controller, NULL }, // HORI Fighting commander ps3 { MAKE_CONTROLLER_ID( 0x0f0d, 0x006a ), k_eControllerType_PS3Controller, NULL }, // Real Arcade Pro 4 { MAKE_CONTROLLER_ID( 0x0f0d, 0x006e ), k_eControllerType_PS3Controller, NULL }, // HORI horipad4 ps3 { MAKE_CONTROLLER_ID( 0x0f0d, 0x0085 ), k_eControllerType_PS3Controller, NULL }, // HORI Fighting Commander PS3 { MAKE_CONTROLLER_ID( 0x0f0d, 0x0086 ), k_eControllerType_PS3Controller, NULL }, // HORI Fighting Commander PC (Uses the Xbox 360 protocol, but has PS3 buttons) { MAKE_CONTROLLER_ID( 0x0f0d, 0x0087 ), k_eControllerType_PS3Controller, NULL }, // HORI fighting mini stick { MAKE_CONTROLLER_ID( 0x0f30, 0x1100 ), k_eControllerType_PS3Controller, NULL }, // Quanba Q1 fight stick { MAKE_CONTROLLER_ID( 0x11ff, 0x3331 ), k_eControllerType_PS3Controller, NULL }, // SRXJ-PH2400 { MAKE_CONTROLLER_ID( 0x1345, 0x1000 ), k_eControllerType_PS3Controller, NULL }, // PS2 ACME GA-D5 { MAKE_CONTROLLER_ID( 0x1345, 0x6005 ), k_eControllerType_PS3Controller, NULL }, // ps2 maybe break out later { MAKE_CONTROLLER_ID( 0x146b, 0x0603 ), k_eControllerType_PS3Controller, NULL }, // From SDL { MAKE_CONTROLLER_ID( 0x146b, 0x5500 ), k_eControllerType_PS3Controller, NULL }, // From SDL { MAKE_CONTROLLER_ID( 0x1a34, 0x0836 ), k_eControllerType_PS3Controller, NULL }, // Afterglow PS3 { MAKE_CONTROLLER_ID( 0x20bc, 0x5500 ), k_eControllerType_PS3Controller, NULL }, // ShanWan PS3 { MAKE_CONTROLLER_ID( 0x20d6, 0x576d ), k_eControllerType_PS3Controller, NULL }, // Power A PS3 { MAKE_CONTROLLER_ID( 0x20d6, 0xca6d ), k_eControllerType_PS3Controller, NULL }, // From SDL { MAKE_CONTROLLER_ID( 0x2563, 0x0523 ), k_eControllerType_PS3Controller, NULL }, // Digiflip GP006 { MAKE_CONTROLLER_ID( 0x2563, 0x0575 ), k_eControllerType_PS3Controller, NULL }, // From SDL { MAKE_CONTROLLER_ID( 0x25f0, 0x83c3 ), k_eControllerType_PS3Controller, NULL }, // gioteck vx2 { MAKE_CONTROLLER_ID( 0x25f0, 0xc121 ), k_eControllerType_PS3Controller, NULL }, // { MAKE_CONTROLLER_ID( 0x2c22, 0x2000 ), k_eControllerType_PS3Controller, NULL }, // Quanba Drone { MAKE_CONTROLLER_ID( 0x2c22, 0x2003 ), k_eControllerType_PS3Controller, NULL }, // From SDL { MAKE_CONTROLLER_ID( 0x8380, 0x0003 ), k_eControllerType_PS3Controller, NULL }, // BTP 2163 { MAKE_CONTROLLER_ID( 0x8888, 0x0308 ), k_eControllerType_PS3Controller, NULL }, // Sony PS3 Controller { MAKE_CONTROLLER_ID( 0x0079, 0x181b ), k_eControllerType_PS4Controller, NULL }, // Venom Arcade Stick - XXX:this may not work and may need to be called a ps3 controller { MAKE_CONTROLLER_ID( 0x054c, 0x05c4 ), k_eControllerType_PS4Controller, NULL }, // Sony PS4 Controller { MAKE_CONTROLLER_ID( 0x054c, 0x05c5 ), k_eControllerType_PS4Controller, NULL }, // STRIKEPAD PS4 Grip Add-on { MAKE_CONTROLLER_ID( 0x054c, 0x09cc ), k_eControllerType_PS4Controller, NULL }, // Sony PS4 Slim Controller { MAKE_CONTROLLER_ID( 0x054c, 0x0ba0 ), k_eControllerType_PS4Controller, NULL }, // Sony PS4 Controller (Wireless dongle) { MAKE_CONTROLLER_ID( 0x0738, 0x8250 ), k_eControllerType_PS4Controller, NULL }, // Mad Catz FightPad Pro PS4 { MAKE_CONTROLLER_ID( 0x0738, 0x8384 ), k_eControllerType_PS4Controller, NULL }, // Mad Catz FightStick TE S+ PS4 { MAKE_CONTROLLER_ID( 0x0738, 0x8480 ), k_eControllerType_PS4Controller, NULL }, // Mad Catz FightStick TE 2 PS4 { MAKE_CONTROLLER_ID( 0x0738, 0x8481 ), k_eControllerType_PS4Controller, NULL }, // Mad Catz FightStick TE 2+ PS4 { MAKE_CONTROLLER_ID( 0x0C12, 0x0E10 ), k_eControllerType_PS4Controller, NULL }, // Armor Armor 3 Pad PS4 { MAKE_CONTROLLER_ID( 0x0C12, 0x1CF6 ), k_eControllerType_PS4Controller, NULL }, // EMIO PS4 Elite Controller { MAKE_CONTROLLER_ID( 0x0c12, 0x0e15 ), k_eControllerType_PS4Controller, NULL }, // Game:Pad 4 { MAKE_CONTROLLER_ID( 0x0c12, 0x0ef6 ), k_eControllerType_PS4Controller, NULL }, // Hitbox Arcade Stick { MAKE_CONTROLLER_ID( 0x0f0d, 0x0055 ), k_eControllerType_PS4Controller, NULL }, // HORIPAD 4 FPS { MAKE_CONTROLLER_ID( 0x0f0d, 0x0066 ), k_eControllerType_PS4Controller, NULL }, // HORIPAD 4 FPS Plus { MAKE_CONTROLLER_ID( 0x0f0d, 0x0084 ), k_eControllerType_PS4Controller, NULL }, // HORI Fighting Commander PS4 { MAKE_CONTROLLER_ID( 0x0f0d, 0x008a ), k_eControllerType_PS4Controller, NULL }, // HORI Real Arcade Pro 4 { MAKE_CONTROLLER_ID( 0x0f0d, 0x009c ), k_eControllerType_PS4Controller, NULL }, // HORI TAC PRO mousething { MAKE_CONTROLLER_ID( 0x0f0d, 0x00a0 ), k_eControllerType_PS4Controller, NULL }, // HORI TAC4 mousething { MAKE_CONTROLLER_ID( 0x0f0d, 0x00ee ), k_eControllerType_PS4Controller, NULL }, // Hori mini wired https://www.playstation.com/en-us/explore/accessories/gaming-controllers/mini-wired-gamepad/ { MAKE_CONTROLLER_ID( 0x11c0, 0x4001 ), k_eControllerType_PS4Controller, NULL }, // "PS4 Fun Controller" added from user log { MAKE_CONTROLLER_ID( 0x146b, 0x0d01 ), k_eControllerType_PS4Controller, NULL }, // Nacon Revolution Pro Controller - has gyro { MAKE_CONTROLLER_ID( 0x146b, 0x0d02 ), k_eControllerType_PS4Controller, NULL }, // Nacon Revolution Pro Controller v2 - has gyro { MAKE_CONTROLLER_ID( 0x146b, 0x0d10 ), k_eControllerType_PS4Controller, NULL }, // NACON Revolution Infinite - has gyro { MAKE_CONTROLLER_ID( 0x1532, 0X0401 ), k_eControllerType_PS4Controller, NULL }, // Razer Panthera PS4 Controller { MAKE_CONTROLLER_ID( 0x1532, 0x1000 ), k_eControllerType_PS4Controller, NULL }, // Razer Raiju PS4 Controller { MAKE_CONTROLLER_ID( 0x1532, 0x1004 ), k_eControllerType_PS4Controller, NULL }, // Razer Raiju 2 Ultimate USB { MAKE_CONTROLLER_ID( 0x1532, 0x1007 ), k_eControllerType_PS4Controller, NULL }, // Razer Raiju 2 Tournament edition USB { MAKE_CONTROLLER_ID( 0x1532, 0x1008 ), k_eControllerType_PS4Controller, NULL }, // Razer Panthera Evo Fightstick { MAKE_CONTROLLER_ID( 0x1532, 0x1009 ), k_eControllerType_PS4Controller, NULL }, // Razer Raiju 2 Ultimate BT { MAKE_CONTROLLER_ID( 0x1532, 0x100A ), k_eControllerType_PS4Controller, NULL }, // Razer Raiju 2 Tournament edition BT { MAKE_CONTROLLER_ID( 0x1532, 0x1100 ), k_eControllerType_PS4Controller, NULL }, // Razer RAION Fightpad - Trackpad, no gyro, lightbar hardcoded to green { MAKE_CONTROLLER_ID( 0x20d6, 0x792a ), k_eControllerType_PS4Controller, NULL }, // PowerA - Fusion Fight Pad { MAKE_CONTROLLER_ID( 0x7545, 0x0104 ), k_eControllerType_PS4Controller, NULL }, // Armor 3 or Level Up Cobra - At least one variant has gyro { MAKE_CONTROLLER_ID( 0x9886, 0x0025 ), k_eControllerType_PS4Controller, NULL }, // Astro C40 { MAKE_CONTROLLER_ID( 0x0e6f, 0x0207 ), k_eControllerType_PS4Controller, NULL }, // Victrix Pro Fightstick w/ Touchpad for PS4 // Removing the Giotek because there were a bunch of help tickets from users w/ issues including from non-PS4 controller users. This VID/PID is probably used in different FW's // { MAKE_CONTROLLER_ID( 0x7545, 0x1122 ), k_eControllerType_PS4Controller, NULL }, // Giotek VX4 - trackpad/gyro don't work. Had to not filter on interface info. Light bar is flaky, but works. { MAKE_CONTROLLER_ID( 0x044f, 0xd00e ), k_eControllerType_PS4Controller, NULL }, // Thrustmast Eswap Pro - No gyro and lightbar doesn't change color. Works otherwise { MAKE_CONTROLLER_ID( 0x0c12, 0x1e10 ), k_eControllerType_PS4Controller, NULL }, // P4 Wired Gamepad generic knock off - lightbar but not trackpad or gyro { MAKE_CONTROLLER_ID( 0x146b, 0x0d09 ), k_eControllerType_PS4Controller, NULL }, // NACON Daija Fight Stick - touchpad but no gyro/rumble { MAKE_CONTROLLER_ID( 0x146b, 0x0d10 ), k_eControllerType_PS4Controller, NULL }, // NACON Revolution Unlimited { MAKE_CONTROLLER_ID( 0x146b, 0x0d08 ), k_eControllerType_PS4Controller, NULL }, // NACON Revolution Unlimited Wireless Dongle { MAKE_CONTROLLER_ID( 0x146b, 0x0d06 ), k_eControllerType_PS4Controller, NULL }, // NACON Asymetrical Controller Wireless Dongle -- show up as ps4 until you connect controller to it then it reboots into Xbox controller with different vvid/pid { MAKE_CONTROLLER_ID( 0x146b, 0x1103 ), k_eControllerType_PS4Controller, NULL }, // NACON Asymetrical Controller -- on windows this doesn't enumerate { MAKE_CONTROLLER_ID( 0x0f0d, 0x0123 ), k_eControllerType_PS4Controller, NULL }, // HORI Wireless Controller Light (Japan only) - only over bt- over usb is xbox and pid 0x0124 { MAKE_CONTROLLER_ID( 0x146b, 0x0d13 ), k_eControllerType_PS4Controller, NULL }, // NACON Revolution 3 { MAKE_CONTROLLER_ID( 0x0079, 0x0006 ), k_eControllerType_UnknownNonSteamController, NULL }, // DragonRise Generic USB PCB, sometimes configured as a PC Twin Shock Controller - looks like a DS3 but the face buttons are 1-4 instead of symbols { MAKE_CONTROLLER_ID( 0x0079, 0x18d4 ), k_eControllerType_XBox360Controller, NULL }, // GPD Win 2 X-Box Controller { MAKE_CONTROLLER_ID( 0x044f, 0xb326 ), k_eControllerType_XBox360Controller, NULL }, // Thrustmaster Gamepad GP XID { MAKE_CONTROLLER_ID( 0x045e, 0x028e ), k_eControllerType_XBox360Controller, "Xbox 360 Controller" }, // Microsoft X-Box 360 pad { MAKE_CONTROLLER_ID( 0x045e, 0x028f ), k_eControllerType_XBox360Controller, "Xbox 360 Controller" }, // Microsoft X-Box 360 pad v2 { MAKE_CONTROLLER_ID( 0x045e, 0x0291 ), k_eControllerType_XBox360Controller, "Xbox 360 Wireless Controller" }, // Xbox 360 Wireless Receiver (XBOX) { MAKE_CONTROLLER_ID( 0x045e, 0x02a0 ), k_eControllerType_XBox360Controller, NULL }, // Microsoft X-Box 360 Big Button IR { MAKE_CONTROLLER_ID( 0x045e, 0x02a1 ), k_eControllerType_XBox360Controller, NULL }, // Microsoft X-Box 360 pad { MAKE_CONTROLLER_ID( 0x045e, 0x02a9 ), k_eControllerType_XBox360Controller, "Xbox 360 Wireless Controller" }, // Xbox 360 Wireless Receiver (third party knockoff) { MAKE_CONTROLLER_ID( 0x045e, 0x0719 ), k_eControllerType_XBox360Controller, "Xbox 360 Wireless Controller" }, // Xbox 360 Wireless Receiver { MAKE_CONTROLLER_ID( 0x046d, 0xc21d ), k_eControllerType_XBox360Controller, NULL }, // Logitech Gamepad F310 { MAKE_CONTROLLER_ID( 0x046d, 0xc21e ), k_eControllerType_XBox360Controller, NULL }, // Logitech Gamepad F510 { MAKE_CONTROLLER_ID( 0x046d, 0xc21f ), k_eControllerType_XBox360Controller, NULL }, // Logitech Gamepad F710 { MAKE_CONTROLLER_ID( 0x046d, 0xc242 ), k_eControllerType_XBox360Controller, NULL }, // Logitech Chillstream Controller { MAKE_CONTROLLER_ID( 0x056e, 0x2004 ), k_eControllerType_XBox360Controller, NULL }, // Elecom JC-U3613M { MAKE_CONTROLLER_ID( 0x06a3, 0xf51a ), k_eControllerType_XBox360Controller, NULL }, // Saitek P3600 { MAKE_CONTROLLER_ID( 0x0738, 0x4716 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Wired Xbox 360 Controller { MAKE_CONTROLLER_ID( 0x0738, 0x4718 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Street Fighter IV FightStick SE { MAKE_CONTROLLER_ID( 0x0738, 0x4726 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Xbox 360 Controller { MAKE_CONTROLLER_ID( 0x0738, 0x4728 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Street Fighter IV FightPad { MAKE_CONTROLLER_ID( 0x0738, 0x4736 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz MicroCon Gamepad { MAKE_CONTROLLER_ID( 0x0738, 0x4738 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Wired Xbox 360 Controller (SFIV) { MAKE_CONTROLLER_ID( 0x0738, 0x4740 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Beat Pad { MAKE_CONTROLLER_ID( 0x0738, 0xb726 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Xbox controller - MW2 { MAKE_CONTROLLER_ID( 0x0738, 0xbeef ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz JOYTECH NEO SE Advanced GamePad { MAKE_CONTROLLER_ID( 0x0738, 0xcb02 ), k_eControllerType_XBox360Controller, NULL }, // Saitek Cyborg Rumble Pad - PC/Xbox 360 { MAKE_CONTROLLER_ID( 0x0738, 0xcb03 ), k_eControllerType_XBox360Controller, NULL }, // Saitek P3200 Rumble Pad - PC/Xbox 360 { MAKE_CONTROLLER_ID( 0x0738, 0xf738 ), k_eControllerType_XBox360Controller, NULL }, // Super SFIV FightStick TE S { MAKE_CONTROLLER_ID( 0x0955, 0x7210 ), k_eControllerType_XBox360Controller, NULL }, // Nvidia Shield local controller { MAKE_CONTROLLER_ID( 0x0955, 0xb400 ), k_eControllerType_XBox360Controller, NULL }, // NVIDIA Shield streaming controller { MAKE_CONTROLLER_ID( 0x0e6f, 0x0105 ), k_eControllerType_XBox360Controller, NULL }, // HSM3 Xbox360 dancepad { MAKE_CONTROLLER_ID( 0x0e6f, 0x0113 ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Afterglow" }, // PDP Afterglow Gamepad for Xbox 360 { MAKE_CONTROLLER_ID( 0x0e6f, 0x011f ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Rock Candy" }, // PDP Rock Candy Gamepad for Xbox 360 { MAKE_CONTROLLER_ID( 0x0e6f, 0x0125 ), k_eControllerType_XBox360Controller, "PDP INJUSTICE FightStick" }, // PDP INJUSTICE FightStick for Xbox 360 { MAKE_CONTROLLER_ID( 0x0e6f, 0x0127 ), k_eControllerType_XBox360Controller, "PDP INJUSTICE FightPad" }, // PDP INJUSTICE FightPad for Xbox 360 { MAKE_CONTROLLER_ID( 0x0e6f, 0x0131 ), k_eControllerType_XBox360Controller, "PDP EA Soccer Controller" }, // PDP EA Soccer Gamepad { MAKE_CONTROLLER_ID( 0x0e6f, 0x0133 ), k_eControllerType_XBox360Controller, "PDP Battlefield 4 Controller" }, // PDP Battlefield 4 Gamepad { MAKE_CONTROLLER_ID( 0x0e6f, 0x0143 ), k_eControllerType_XBox360Controller, "PDP MK X Fight Stick" }, // PDP MK X Fight Stick for Xbox 360 { MAKE_CONTROLLER_ID( 0x0e6f, 0x0147 ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Marvel Controller" }, // PDP Marvel Controller for Xbox 360 { MAKE_CONTROLLER_ID( 0x0e6f, 0x0201 ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Controller" }, // PDP Gamepad for Xbox 360 { MAKE_CONTROLLER_ID( 0x0e6f, 0x0213 ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Afterglow" }, // PDP Afterglow Gamepad for Xbox 360 { MAKE_CONTROLLER_ID( 0x0e6f, 0x021f ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Rock Candy" }, // PDP Rock Candy Gamepad for Xbox 360 { MAKE_CONTROLLER_ID( 0x0e6f, 0x0301 ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Controller" }, // PDP Gamepad for Xbox 360 { MAKE_CONTROLLER_ID( 0x0e6f, 0x0313 ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Afterglow" }, // PDP Afterglow Gamepad for Xbox 360 { MAKE_CONTROLLER_ID( 0x0e6f, 0x0314 ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Afterglow" }, // PDP Afterglow Gamepad for Xbox 360 { MAKE_CONTROLLER_ID( 0x0e6f, 0x0401 ), k_eControllerType_XBox360Controller, "PDP Xbox 360 Controller" }, // PDP Gamepad for Xbox 360 { MAKE_CONTROLLER_ID( 0x0e6f, 0x0413 ), k_eControllerType_XBox360Controller, NULL }, // PDP Afterglow AX.1 (unlisted) { MAKE_CONTROLLER_ID( 0x0e6f, 0x0501 ), k_eControllerType_XBox360Controller, NULL }, // PDP Xbox 360 Controller (unlisted) { MAKE_CONTROLLER_ID( 0x0e6f, 0xf900 ), k_eControllerType_XBox360Controller, NULL }, // PDP Afterglow AX.1 (unlisted) { MAKE_CONTROLLER_ID( 0x0f0d, 0x000a ), k_eControllerType_XBox360Controller, NULL }, // Hori Co. DOA4 FightStick { MAKE_CONTROLLER_ID( 0x0f0d, 0x000c ), k_eControllerType_XBox360Controller, NULL }, // Hori PadEX Turbo { MAKE_CONTROLLER_ID( 0x0f0d, 0x000d ), k_eControllerType_XBox360Controller, NULL }, // Hori Fighting Stick EX2 { MAKE_CONTROLLER_ID( 0x0f0d, 0x0016 ), k_eControllerType_XBox360Controller, NULL }, // Hori Real Arcade Pro.EX { MAKE_CONTROLLER_ID( 0x0f0d, 0x001b ), k_eControllerType_XBox360Controller, NULL }, // Hori Real Arcade Pro VX { MAKE_CONTROLLER_ID( 0x0f0d, 0x008c ), k_eControllerType_XBox360Controller, NULL }, // Hori Real Arcade Pro 4 { MAKE_CONTROLLER_ID( 0x0f0d, 0x00db ), k_eControllerType_XBox360Controller, "HORI Slime Controller" }, // Hori Dragon Quest Slime Controller { MAKE_CONTROLLER_ID( 0x1038, 0x1430 ), k_eControllerType_XBox360Controller, "SteelSeries Stratus Duo" }, // SteelSeries Stratus Duo { MAKE_CONTROLLER_ID( 0x1038, 0x1431 ), k_eControllerType_XBox360Controller, "SteelSeries Stratus Duo" }, // SteelSeries Stratus Duo { MAKE_CONTROLLER_ID( 0x1038, 0xb360 ), k_eControllerType_XBox360Controller, NULL }, // SteelSeries Nimbus/Stratus XL { MAKE_CONTROLLER_ID( 0x11c9, 0x55f0 ), k_eControllerType_XBox360Controller, NULL }, // Nacon GC-100XF { MAKE_CONTROLLER_ID( 0x12ab, 0x0004 ), k_eControllerType_XBox360Controller, NULL }, // Honey Bee Xbox360 dancepad { MAKE_CONTROLLER_ID( 0x12ab, 0x0301 ), k_eControllerType_XBox360Controller, NULL }, // PDP AFTERGLOW AX.1 { MAKE_CONTROLLER_ID( 0x12ab, 0x0303 ), k_eControllerType_XBox360Controller, NULL }, // Mortal Kombat Klassic FightStick { MAKE_CONTROLLER_ID( 0x1430, 0x02a0 ), k_eControllerType_XBox360Controller, NULL }, // RedOctane Controller Adapter { MAKE_CONTROLLER_ID( 0x1430, 0x4748 ), k_eControllerType_XBox360Controller, NULL }, // RedOctane Guitar Hero X-plorer { MAKE_CONTROLLER_ID( 0x1430, 0xf801 ), k_eControllerType_XBox360Controller, NULL }, // RedOctane Controller { MAKE_CONTROLLER_ID( 0x146b, 0x0601 ), k_eControllerType_XBox360Controller, NULL }, // BigBen Interactive XBOX 360 Controller // { MAKE_CONTROLLER_ID( 0x1532, 0x0037 ), k_eControllerType_XBox360Controller, NULL }, // Razer Sabertooth { MAKE_CONTROLLER_ID( 0x15e4, 0x3f00 ), k_eControllerType_XBox360Controller, NULL }, // Power A Mini Pro Elite { MAKE_CONTROLLER_ID( 0x15e4, 0x3f0a ), k_eControllerType_XBox360Controller, NULL }, // Xbox Airflo wired controller { MAKE_CONTROLLER_ID( 0x15e4, 0x3f10 ), k_eControllerType_XBox360Controller, NULL }, // Batarang Xbox 360 controller { MAKE_CONTROLLER_ID( 0x162e, 0xbeef ), k_eControllerType_XBox360Controller, NULL }, // Joytech Neo-Se Take2 { MAKE_CONTROLLER_ID( 0x1689, 0xfd00 ), k_eControllerType_XBox360Controller, NULL }, // Razer Onza Tournament Edition { MAKE_CONTROLLER_ID( 0x1689, 0xfd01 ), k_eControllerType_XBox360Controller, NULL }, // Razer Onza Classic Edition { MAKE_CONTROLLER_ID( 0x1689, 0xfe00 ), k_eControllerType_XBox360Controller, NULL }, // Razer Sabertooth { MAKE_CONTROLLER_ID( 0x1bad, 0x0002 ), k_eControllerType_XBox360Controller, NULL }, // Harmonix Rock Band Guitar { MAKE_CONTROLLER_ID( 0x1bad, 0x0003 ), k_eControllerType_XBox360Controller, NULL }, // Harmonix Rock Band Drumkit { MAKE_CONTROLLER_ID( 0x1bad, 0xf016 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Xbox 360 Controller { MAKE_CONTROLLER_ID( 0x1bad, 0xf018 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Street Fighter IV SE Fighting Stick { MAKE_CONTROLLER_ID( 0x1bad, 0xf019 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Brawlstick for Xbox 360 { MAKE_CONTROLLER_ID( 0x1bad, 0xf021 ), k_eControllerType_XBox360Controller, NULL }, // Mad Cats Ghost Recon FS GamePad { MAKE_CONTROLLER_ID( 0x1bad, 0xf023 ), k_eControllerType_XBox360Controller, NULL }, // MLG Pro Circuit Controller (Xbox) { MAKE_CONTROLLER_ID( 0x1bad, 0xf025 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Call Of Duty { MAKE_CONTROLLER_ID( 0x1bad, 0xf027 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz FPS Pro { MAKE_CONTROLLER_ID( 0x1bad, 0xf028 ), k_eControllerType_XBox360Controller, NULL }, // Street Fighter IV FightPad { MAKE_CONTROLLER_ID( 0x1bad, 0xf02e ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Fightpad { MAKE_CONTROLLER_ID( 0x1bad, 0xf036 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz MicroCon GamePad Pro { MAKE_CONTROLLER_ID( 0x1bad, 0xf038 ), k_eControllerType_XBox360Controller, NULL }, // Street Fighter IV FightStick TE { MAKE_CONTROLLER_ID( 0x1bad, 0xf039 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz MvC2 TE { MAKE_CONTROLLER_ID( 0x1bad, 0xf03a ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz SFxT Fightstick Pro { MAKE_CONTROLLER_ID( 0x1bad, 0xf03d ), k_eControllerType_XBox360Controller, NULL }, // Street Fighter IV Arcade Stick TE - Chun Li { MAKE_CONTROLLER_ID( 0x1bad, 0xf03e ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz MLG FightStick TE { MAKE_CONTROLLER_ID( 0x1bad, 0xf03f ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz FightStick SoulCaliber { MAKE_CONTROLLER_ID( 0x1bad, 0xf042 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz FightStick TES+ { MAKE_CONTROLLER_ID( 0x1bad, 0xf080 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz FightStick TE2 { MAKE_CONTROLLER_ID( 0x1bad, 0xf501 ), k_eControllerType_XBox360Controller, NULL }, // HoriPad EX2 Turbo { MAKE_CONTROLLER_ID( 0x1bad, 0xf502 ), k_eControllerType_XBox360Controller, NULL }, // Hori Real Arcade Pro.VX SA { MAKE_CONTROLLER_ID( 0x1bad, 0xf503 ), k_eControllerType_XBox360Controller, NULL }, // Hori Fighting Stick VX { MAKE_CONTROLLER_ID( 0x1bad, 0xf504 ), k_eControllerType_XBox360Controller, NULL }, // Hori Real Arcade Pro. EX { MAKE_CONTROLLER_ID( 0x1bad, 0xf505 ), k_eControllerType_XBox360Controller, NULL }, // Hori Fighting Stick EX2B { MAKE_CONTROLLER_ID( 0x1bad, 0xf506 ), k_eControllerType_XBox360Controller, NULL }, // Hori Real Arcade Pro.EX Premium VLX { MAKE_CONTROLLER_ID( 0x1bad, 0xf900 ), k_eControllerType_XBox360Controller, NULL }, // Harmonix Xbox 360 Controller { MAKE_CONTROLLER_ID( 0x1bad, 0xf901 ), k_eControllerType_XBox360Controller, NULL }, // Gamestop Xbox 360 Controller { MAKE_CONTROLLER_ID( 0x1bad, 0xf902 ), k_eControllerType_XBox360Controller, NULL }, // Mad Catz Gamepad2 { MAKE_CONTROLLER_ID( 0x1bad, 0xf903 ), k_eControllerType_XBox360Controller, NULL }, // Tron Xbox 360 controller { MAKE_CONTROLLER_ID( 0x1bad, 0xf904 ), k_eControllerType_XBox360Controller, NULL }, // PDP Versus Fighting Pad { MAKE_CONTROLLER_ID( 0x1bad, 0xf906 ), k_eControllerType_XBox360Controller, NULL }, // MortalKombat FightStick { MAKE_CONTROLLER_ID( 0x1bad, 0xfa01 ), k_eControllerType_XBox360Controller, NULL }, // MadCatz GamePad { MAKE_CONTROLLER_ID( 0x1bad, 0xfd00 ), k_eControllerType_XBox360Controller, NULL }, // Razer Onza TE { MAKE_CONTROLLER_ID( 0x1bad, 0xfd01 ), k_eControllerType_XBox360Controller, NULL }, // Razer Onza { MAKE_CONTROLLER_ID( 0x24c6, 0x5000 ), k_eControllerType_XBox360Controller, NULL }, // Razer Atrox Arcade Stick { MAKE_CONTROLLER_ID( 0x24c6, 0x5300 ), k_eControllerType_XBox360Controller, NULL }, // PowerA MINI PROEX Controller { MAKE_CONTROLLER_ID( 0x24c6, 0x5303 ), k_eControllerType_XBox360Controller, NULL }, // Xbox Airflo wired controller { MAKE_CONTROLLER_ID( 0x24c6, 0x530a ), k_eControllerType_XBox360Controller, NULL }, // Xbox 360 Pro EX Controller { MAKE_CONTROLLER_ID( 0x24c6, 0x531a ), k_eControllerType_XBox360Controller, NULL }, // PowerA Pro Ex { MAKE_CONTROLLER_ID( 0x24c6, 0x5397 ), k_eControllerType_XBox360Controller, NULL }, // FUS1ON Tournament Controller { MAKE_CONTROLLER_ID( 0x24c6, 0x5500 ), k_eControllerType_XBox360Controller, NULL }, // Hori XBOX 360 EX 2 with Turbo { MAKE_CONTROLLER_ID( 0x24c6, 0x5501 ), k_eControllerType_XBox360Controller, NULL }, // Hori Real Arcade Pro VX-SA { MAKE_CONTROLLER_ID( 0x24c6, 0x5502 ), k_eControllerType_XBox360Controller, NULL }, // Hori Fighting Stick VX Alt { MAKE_CONTROLLER_ID( 0x24c6, 0x5503 ), k_eControllerType_XBox360Controller, NULL }, // Hori Fighting Edge { MAKE_CONTROLLER_ID( 0x24c6, 0x5506 ), k_eControllerType_XBox360Controller, NULL }, // Hori SOULCALIBUR V Stick { MAKE_CONTROLLER_ID( 0x24c6, 0x550d ), k_eControllerType_XBox360Controller, NULL }, // Hori GEM Xbox controller { MAKE_CONTROLLER_ID( 0x24c6, 0x550e ), k_eControllerType_XBox360Controller, NULL }, // Hori Real Arcade Pro V Kai 360 { MAKE_CONTROLLER_ID( 0x24c6, 0x5508 ), k_eControllerType_XBox360Controller, NULL }, // Hori PAD A { MAKE_CONTROLLER_ID( 0x24c6, 0x5510 ), k_eControllerType_XBox360Controller, NULL }, // Hori Fighting Commander ONE { MAKE_CONTROLLER_ID( 0x24c6, 0x5b00 ), k_eControllerType_XBox360Controller, NULL }, // ThrustMaster Ferrari Italia 458 Racing Wheel { MAKE_CONTROLLER_ID( 0x24c6, 0x5b02 ), k_eControllerType_XBox360Controller, NULL }, // Thrustmaster, Inc. GPX Controller { MAKE_CONTROLLER_ID( 0x24c6, 0x5b03 ), k_eControllerType_XBox360Controller, NULL }, // Thrustmaster Ferrari 458 Racing Wheel { MAKE_CONTROLLER_ID( 0x24c6, 0x5d04 ), k_eControllerType_XBox360Controller, NULL }, // Razer Sabertooth { MAKE_CONTROLLER_ID( 0x24c6, 0xfafa ), k_eControllerType_XBox360Controller, NULL }, // Aplay Controller { MAKE_CONTROLLER_ID( 0x24c6, 0xfafb ), k_eControllerType_XBox360Controller, NULL }, // Aplay Controller { MAKE_CONTROLLER_ID( 0x24c6, 0xfafc ), k_eControllerType_XBox360Controller, NULL }, // Afterglow Gamepad 1 { MAKE_CONTROLLER_ID( 0x24c6, 0xfafd ), k_eControllerType_XBox360Controller, NULL }, // Afterglow Gamepad 3 { MAKE_CONTROLLER_ID( 0x24c6, 0xfafe ), k_eControllerType_XBox360Controller, NULL }, // Rock Candy Gamepad for Xbox 360 { MAKE_CONTROLLER_ID( 0x045e, 0x02d1 ), k_eControllerType_XBoxOneController, "Xbox One Controller" }, // Microsoft X-Box One pad { MAKE_CONTROLLER_ID( 0x045e, 0x02dd ), k_eControllerType_XBoxOneController, "Xbox One Controller" }, // Microsoft X-Box One pad (Firmware 2015) { MAKE_CONTROLLER_ID( 0x045e, 0x02e0 ), k_eControllerType_XBoxOneController, "Xbox One S Controller" }, // Microsoft X-Box One S pad (Bluetooth) { MAKE_CONTROLLER_ID( 0x045e, 0x02e3 ), k_eControllerType_XBoxOneController, "Xbox One Elite Controller" }, // Microsoft X-Box One Elite pad { MAKE_CONTROLLER_ID( 0x045e, 0x02ea ), k_eControllerType_XBoxOneController, "Xbox One S Controller" }, // Microsoft X-Box One S pad { MAKE_CONTROLLER_ID( 0x045e, 0x02fd ), k_eControllerType_XBoxOneController, "Xbox One S Controller" }, // Microsoft X-Box One S pad (Bluetooth) { MAKE_CONTROLLER_ID( 0x045e, 0x02ff ), k_eControllerType_XBoxOneController, NULL }, // Microsoft X-Box One controller with the RAWINPUT driver on Windows { MAKE_CONTROLLER_ID( 0x045e, 0x0b00 ), k_eControllerType_XBoxOneController, "Xbox One Elite 2 Controller" }, // Microsoft X-Box One Elite Series 2 pad { MAKE_CONTROLLER_ID( 0x045e, 0x0b05 ), k_eControllerType_XBoxOneController, "Xbox One Elite 2 Controller" }, // Microsoft X-Box One Elite Series 2 pad (Bluetooth) { MAKE_CONTROLLER_ID( 0x0738, 0x4a01 ), k_eControllerType_XBoxOneController, NULL }, // Mad Catz FightStick TE 2 { MAKE_CONTROLLER_ID( 0x0e6f, 0x0139 ), k_eControllerType_XBoxOneController, "PDP Xbox One Afterglow" }, // PDP Afterglow Wired Controller for Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x013B ), k_eControllerType_XBoxOneController, "PDP Xbox One Face-Off Controller" }, // PDP Face-Off Gamepad for Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x013a ), k_eControllerType_XBoxOneController, NULL }, // PDP Xbox One Controller (unlisted) { MAKE_CONTROLLER_ID( 0x0e6f, 0x0145 ), k_eControllerType_XBoxOneController, "PDP MK X Fight Pad" }, // PDP MK X Fight Pad for Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x0146 ), k_eControllerType_XBoxOneController, "PDP Xbox One Rock Candy" }, // PDP Rock Candy Wired Controller for Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x015b ), k_eControllerType_XBoxOneController, "PDP Fallout 4 Vault Boy Controller" }, // PDP Fallout 4 Vault Boy Wired Controller for Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x015c ), k_eControllerType_XBoxOneController, "PDP Xbox One @Play Controller" }, // PDP @Play Wired Controller for Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x015d ), k_eControllerType_XBoxOneController, "PDP Mirror's Edge Controller" }, // PDP Mirror's Edge Wired Controller for Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x015f ), k_eControllerType_XBoxOneController, "PDP Metallic Controller" }, // PDP Metallic Wired Controller for Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x0160 ), k_eControllerType_XBoxOneController, "PDP NFL Face-Off Controller" }, // PDP NFL Official Face-Off Wired Controller for Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x0161 ), k_eControllerType_XBoxOneController, "PDP Xbox One Camo" }, // PDP Camo Wired Controller for Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x0162 ), k_eControllerType_XBoxOneController, "PDP Xbox One Controller" }, // PDP Wired Controller for Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x0163 ), k_eControllerType_XBoxOneController, "PDP Deliverer of Truth" }, // PDP Legendary Collection: Deliverer of Truth { MAKE_CONTROLLER_ID( 0x0e6f, 0x0164 ), k_eControllerType_XBoxOneController, "PDP Battlefield 1 Controller" }, // PDP Battlefield 1 Official Wired Controller for Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x0165 ), k_eControllerType_XBoxOneController, "PDP Titanfall 2 Controller" }, // PDP Titanfall 2 Official Wired Controller for Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x0166 ), k_eControllerType_XBoxOneController, "PDP Mass Effect: Andromeda Controller" }, // PDP Mass Effect: Andromeda Official Wired Controller for Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x0167 ), k_eControllerType_XBoxOneController, "PDP Halo Wars 2 Face-Off Controller" }, // PDP Halo Wars 2 Official Face-Off Wired Controller for Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x0205 ), k_eControllerType_XBoxOneController, "PDP Victrix Pro Fight Stick" }, // PDP Victrix Pro Fight Stick { MAKE_CONTROLLER_ID( 0x0e6f, 0x0206 ), k_eControllerType_XBoxOneController, "PDP Mortal Kombat Controller" }, // PDP Mortal Kombat 25 Anniversary Edition Stick (Xbox One) { MAKE_CONTROLLER_ID( 0x0e6f, 0x0246 ), k_eControllerType_XBoxOneController, "PDP Xbox One Rock Candy" }, // PDP Rock Candy Wired Controller for Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x0261 ), k_eControllerType_XBoxOneController, "PDP Xbox One Camo" }, // PDP Camo Wired Controller { MAKE_CONTROLLER_ID( 0x0e6f, 0x0262 ), k_eControllerType_XBoxOneController, "PDP Xbox One Controller" }, // PDP Wired Controller { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a0 ), k_eControllerType_XBoxOneController, "PDP Xbox One Midnight Blue" }, // PDP Wired Controller for Xbox One - Midnight Blue { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a1 ), k_eControllerType_XBoxOneController, "PDP Xbox One Verdant Green" }, // PDP Wired Controller for Xbox One - Verdant Green { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a2 ), k_eControllerType_XBoxOneController, "PDP Xbox One Crimson Red" }, // PDP Wired Controller for Xbox One - Crimson Red { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a3 ), k_eControllerType_XBoxOneController, "PDP Xbox One Arctic White" }, // PDP Wired Controller for Xbox One - Arctic White { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a4 ), k_eControllerType_XBoxOneController, "PDP Xbox One Phantom Black" }, // PDP Wired Controller for Xbox One - Stealth Series | Phantom Black { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a5 ), k_eControllerType_XBoxOneController, "PDP Xbox One Ghost White" }, // PDP Wired Controller for Xbox One - Stealth Series | Ghost White { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a6 ), k_eControllerType_XBoxOneController, "PDP Xbox One Revenant Blue" }, // PDP Wired Controller for Xbox One - Stealth Series | Revenant Blue { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a7 ), k_eControllerType_XBoxOneController, "PDP Xbox One Raven Black" }, // PDP Wired Controller for Xbox One - Raven Black { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a8 ), k_eControllerType_XBoxOneController, "PDP Xbox One Arctic White" }, // PDP Wired Controller for Xbox One - Arctic White { MAKE_CONTROLLER_ID( 0x0e6f, 0x02a9 ), k_eControllerType_XBoxOneController, "PDP Xbox One Midnight Blue" }, // PDP Wired Controller for Xbox One - Midnight Blue { MAKE_CONTROLLER_ID( 0x0e6f, 0x02aa ), k_eControllerType_XBoxOneController, "PDP Xbox One Verdant Green" }, // PDP Wired Controller for Xbox One - Verdant Green { MAKE_CONTROLLER_ID( 0x0e6f, 0x02ab ), k_eControllerType_XBoxOneController, "PDP Xbox One Crimson Red" }, // PDP Wired Controller for Xbox One - Crimson Red { MAKE_CONTROLLER_ID( 0x0e6f, 0x02ac ), k_eControllerType_XBoxOneController, "PDP Xbox One Ember Orange" }, // PDP Wired Controller for Xbox One - Ember Orange { MAKE_CONTROLLER_ID( 0x0e6f, 0x02ad ), k_eControllerType_XBoxOneController, "PDP Xbox One Phantom Black" }, // PDP Wired Controller for Xbox One - Stealth Series | Phantom Black { MAKE_CONTROLLER_ID( 0x0e6f, 0x02ae ), k_eControllerType_XBoxOneController, "PDP Xbox One Ghost White" }, // PDP Wired Controller for Xbox One - Stealth Series | Ghost White { MAKE_CONTROLLER_ID( 0x0e6f, 0x02af ), k_eControllerType_XBoxOneController, "PDP Xbox One Revenant Blue" }, // PDP Wired Controller for Xbox One - Stealth Series | Revenant Blue { MAKE_CONTROLLER_ID( 0x0e6f, 0x02b0 ), k_eControllerType_XBoxOneController, "PDP Xbox One Raven Black" }, // PDP Wired Controller for Xbox One - Raven Black { MAKE_CONTROLLER_ID( 0x0e6f, 0x02b1 ), k_eControllerType_XBoxOneController, "PDP Xbox One Arctic White" }, // PDP Wired Controller for Xbox One - Arctic White { MAKE_CONTROLLER_ID( 0x0e6f, 0x02b3 ), k_eControllerType_XBoxOneController, "PDP Xbox One Afterglow" }, // PDP Afterglow Prismatic Wired Controller { MAKE_CONTROLLER_ID( 0x0e6f, 0x02b5 ), k_eControllerType_XBoxOneController, "PDP Xbox One GAMEware Controller" }, // PDP GAMEware Wired Controller Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x02b6 ), k_eControllerType_XBoxOneController, NULL }, // PDP One-Handed Joystick Adaptive Controller { MAKE_CONTROLLER_ID( 0x0e6f, 0x02bd ), k_eControllerType_XBoxOneController, "PDP Xbox One Royal Purple" }, // PDP Wired Controller for Xbox One - Royal Purple { MAKE_CONTROLLER_ID( 0x0e6f, 0x02be ), k_eControllerType_XBoxOneController, "PDP Xbox One Raven Black" }, // PDP Deluxe Wired Controller for Xbox One - Raven Black { MAKE_CONTROLLER_ID( 0x0e6f, 0x02bf ), k_eControllerType_XBoxOneController, "PDP Xbox One Midnight Blue" }, // PDP Deluxe Wired Controller for Xbox One - Midnight Blue { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c0 ), k_eControllerType_XBoxOneController, "PDP Xbox One Phantom Black" }, // PDP Deluxe Wired Controller for Xbox One - Stealth Series | Phantom Black { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c1 ), k_eControllerType_XBoxOneController, "PDP Xbox One Ghost White" }, // PDP Deluxe Wired Controller for Xbox One - Stealth Series | Ghost White { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c2 ), k_eControllerType_XBoxOneController, "PDP Xbox One Revenant Blue" }, // PDP Deluxe Wired Controller for Xbox One - Stealth Series | Revenant Blue { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c3 ), k_eControllerType_XBoxOneController, "PDP Xbox One Verdant Green" }, // PDP Deluxe Wired Controller for Xbox One - Verdant Green { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c4 ), k_eControllerType_XBoxOneController, "PDP Xbox One Ember Orange" }, // PDP Deluxe Wired Controller for Xbox One - Ember Orange { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c5 ), k_eControllerType_XBoxOneController, "PDP Xbox One Royal Purple" }, // PDP Deluxe Wired Controller for Xbox One - Royal Purple { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c6 ), k_eControllerType_XBoxOneController, "PDP Xbox One Crimson Red" }, // PDP Deluxe Wired Controller for Xbox One - Crimson Red { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c7 ), k_eControllerType_XBoxOneController, "PDP Xbox One Arctic White" }, // PDP Deluxe Wired Controller for Xbox One - Arctic White { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c8 ), k_eControllerType_XBoxOneController, "PDP Kingdom Hearts Controller" }, // PDP Kingdom Hearts Wired Controller { MAKE_CONTROLLER_ID( 0x0e6f, 0x02c9 ), k_eControllerType_XBoxOneController, "PDP Xbox One Phantasm Red" }, // PDP Deluxe Wired Controller for Xbox One - Stealth Series | Phantasm Red { MAKE_CONTROLLER_ID( 0x0e6f, 0x02ca ), k_eControllerType_XBoxOneController, "PDP Xbox One Specter Violet" }, // PDP Deluxe Wired Controller for Xbox One - Stealth Series | Specter Violet { MAKE_CONTROLLER_ID( 0x0e6f, 0x02cb ), k_eControllerType_XBoxOneController, "PDP Xbox One Specter Violet" }, // PDP Wired Controller for Xbox One - Stealth Series | Specter Violet { MAKE_CONTROLLER_ID( 0x0e6f, 0x02cd ), k_eControllerType_XBoxOneController, "PDP Xbox One Blu-merang" }, // PDP Rock Candy Wired Controller for Xbox One - Blu-merang { MAKE_CONTROLLER_ID( 0x0e6f, 0x02ce ), k_eControllerType_XBoxOneController, "PDP Xbox One Cranblast" }, // PDP Rock Candy Wired Controller for Xbox One - Cranblast { MAKE_CONTROLLER_ID( 0x0e6f, 0x02cf ), k_eControllerType_XBoxOneController, "PDP Xbox One Aqualime" }, // PDP Rock Candy Wired Controller for Xbox One - Aqualime { MAKE_CONTROLLER_ID( 0x0e6f, 0x02d5 ), k_eControllerType_XBoxOneController, "PDP Xbox One Red Camo" }, // PDP Wired Controller for Xbox One - Red Camo { MAKE_CONTROLLER_ID( 0x0e6f, 0x0346 ), k_eControllerType_XBoxOneController, "PDP Xbox One RC Gamepad" }, // PDP RC Gamepad for Xbox One { MAKE_CONTROLLER_ID( 0x0e6f, 0x0446 ), k_eControllerType_XBoxOneController, "PDP Xbox One RC Gamepad" }, // PDP RC Gamepad for Xbox One { MAKE_CONTROLLER_ID( 0x0f0d, 0x0063 ), k_eControllerType_XBoxOneController, NULL }, // Hori Real Arcade Pro Hayabusa (USA) Xbox One { MAKE_CONTROLLER_ID( 0x0f0d, 0x0067 ), k_eControllerType_XBoxOneController, NULL }, // HORIPAD ONE { MAKE_CONTROLLER_ID( 0x0f0d, 0x0078 ), k_eControllerType_XBoxOneController, NULL }, // Hori Real Arcade Pro V Kai Xbox One { MAKE_CONTROLLER_ID( 0x0f0d, 0x00c5 ), k_eControllerType_XBoxOneController, NULL }, // HORI Fighting Commander { MAKE_CONTROLLER_ID( 0x1532, 0x0a00 ), k_eControllerType_XBoxOneController, NULL }, // Razer Atrox Arcade Stick { MAKE_CONTROLLER_ID( 0x1532, 0x0a03 ), k_eControllerType_XBoxOneController, NULL }, // Razer Wildcat { MAKE_CONTROLLER_ID( 0x1532, 0x0a14 ), k_eControllerType_XBoxOneController, NULL }, // Razer Wolverine Ultimate { MAKE_CONTROLLER_ID( 0x24c6, 0x541a ), k_eControllerType_XBoxOneController, NULL }, // PowerA Xbox One Mini Wired Controller { MAKE_CONTROLLER_ID( 0x24c6, 0x542a ), k_eControllerType_XBoxOneController, NULL }, // Xbox ONE spectra { MAKE_CONTROLLER_ID( 0x24c6, 0x543a ), k_eControllerType_XBoxOneController, "PowerA XBox One Controller" }, // PowerA Xbox ONE liquid metal controller { MAKE_CONTROLLER_ID( 0x24c6, 0x551a ), k_eControllerType_XBoxOneController, NULL }, // PowerA FUSION Pro Controller { MAKE_CONTROLLER_ID( 0x24c6, 0x561a ), k_eControllerType_XBoxOneController, NULL }, // PowerA FUSION Controller { MAKE_CONTROLLER_ID( 0x24c6, 0x581a ), k_eControllerType_XBoxOneController, NULL }, // BDA XB1 Classic Controller { MAKE_CONTROLLER_ID( 0x24c6, 0x591a ), k_eControllerType_XBoxOneController, NULL }, // PowerA FUSION Pro Controller { MAKE_CONTROLLER_ID( 0x24c6, 0x592a ), k_eControllerType_XBoxOneController, NULL }, // BDA XB1 Spectra Pro { MAKE_CONTROLLER_ID( 0x24c6, 0x791a ), k_eControllerType_XBoxOneController, NULL }, // PowerA Fusion Fight Pad { MAKE_CONTROLLER_ID( 0x2e24, 0x0652 ), k_eControllerType_XBoxOneController, NULL }, // Hyperkin Duke { MAKE_CONTROLLER_ID( 0x2e24, 0x1618 ), k_eControllerType_XBoxOneController, NULL }, // Hyperkin Duke { MAKE_CONTROLLER_ID( 0x2e24, 0x1688 ), k_eControllerType_XBoxOneController, NULL }, // Hyperkin X91 { MAKE_CONTROLLER_ID( 0x146b, 0x0611 ), k_eControllerType_XBoxOneController, NULL }, // Xbox Controller Mode for NACON Revolution 3 // These have been added via Minidump for unrecognized Xinput controller assert { MAKE_CONTROLLER_ID( 0x0000, 0x0000 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x045e, 0x02a2 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller - Microsoft VID { MAKE_CONTROLLER_ID( 0x0e6f, 0x1414 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x0e6f, 0x0159 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x24c6, 0xfaff ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x0f0d, 0x006d ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x0f0d, 0x00a4 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x0079, 0x1832 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x0079, 0x187f ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x0079, 0x1883 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x03eb, 0xff01 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x2c22, 0x2303 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x0c12, 0x0ef8 ), k_eControllerType_XBox360Controller, NULL }, // Homemade fightstick based on brook pcb (with XInput driver??) { MAKE_CONTROLLER_ID( 0x046d, 0x1000 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x1345, 0x6006 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x056e, 0x2012 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x146b, 0x0602 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x0f0d, 0x00ae ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x046d, 0x0401 ), k_eControllerType_XBox360Controller, NULL }, // logitech xinput { MAKE_CONTROLLER_ID( 0x046d, 0x0301 ), k_eControllerType_XBox360Controller, NULL }, // logitech xinput { MAKE_CONTROLLER_ID( 0x046d, 0xcaa3 ), k_eControllerType_XBox360Controller, NULL }, // logitech xinput { MAKE_CONTROLLER_ID( 0x046d, 0xc261 ), k_eControllerType_XBox360Controller, NULL }, // logitech xinput { MAKE_CONTROLLER_ID( 0x046d, 0x0291 ), k_eControllerType_XBox360Controller, NULL }, // logitech xinput { MAKE_CONTROLLER_ID( 0x0079, 0x18d3 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x0f0d, 0x00b1 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x0001, 0x0001 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x0079, 0x188e ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x0079, 0x187c ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x0079, 0x189c ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x0079, 0x1874 ), k_eControllerType_XBox360Controller, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x2f24, 0x0050 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x2f24, 0x2e ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x9886, 0x24 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x2f24, 0x91 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x1430, 0x719 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xf0d, 0xed ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x3eb, 0xff02 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xf0d, 0xc0 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xe6f, 0x152 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xe6f, 0x2a7 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x46d, 0x1007 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xe6f, 0x2b8 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xe6f, 0x2a8 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x2c22, 0x2503 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x79, 0x18a1 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller /* Added from Minidumps 10-9-19 */ { MAKE_CONTROLLER_ID( 0x0, 0x6686 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x11ff, 0x511 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x12ab, 0x304 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x1430, 0x291 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x1430, 0x2a9 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x1430, 0x70b ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x146b, 0x604 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x146b, 0x605 ), k_eControllerType_XBoxOneController, NULL }, // NACON PS4 controller in Xbox mode - might also be other bigben brand xbox controllers { MAKE_CONTROLLER_ID( 0x146b, 0x606 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x146b, 0x609 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x1bad, 0x28e ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x1bad, 0x2a0 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x1bad, 0x5500 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x20ab, 0x55ef ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x24c6, 0x5509 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x2516, 0x69 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x25b1, 0x360 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x2c22, 0x2203 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x2f24, 0x11 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x2f24, 0x53 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x2f24, 0xb7 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x46d, 0x0 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x46d, 0x1004 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x46d, 0x1008 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x46d, 0xf301 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x738, 0x2a0 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x738, 0x7263 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x738, 0xb738 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x738, 0xcb29 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x738, 0xf401 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x79, 0x18c2 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x79, 0x18c8 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x79, 0x18cf ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xc12, 0xe17 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xc12, 0xe1c ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xc12, 0xe22 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xc12, 0xe30 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xd2d2, 0xd2d2 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xd62, 0x9a1a ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xd62, 0x9a1b ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xe00, 0xe00 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xe6f, 0x12a ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xe6f, 0x2a1 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xe6f, 0x2a2 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xe6f, 0x2a5 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xe6f, 0x2b2 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xe6f, 0x2bd ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xe6f, 0x2bf ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xe6f, 0x2c0 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xe6f, 0x2c6 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xf0d, 0x97 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xf0d, 0xba ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xf0d, 0xd8 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0xfff, 0x2a1 ), k_eControllerType_XBoxOneController, NULL }, // Unknown Controller //{ MAKE_CONTROLLER_ID( 0x1949, 0x0402 ), /*android*/, NULL }, // Unknown Controller { MAKE_CONTROLLER_ID( 0x05ac, 0x0001 ), k_eControllerType_AppleController, NULL }, // MFI Extended Gamepad (generic entry for iOS/tvOS) { MAKE_CONTROLLER_ID( 0x05ac, 0x0002 ), k_eControllerType_AppleController, NULL }, // MFI Standard Gamepad (generic entry for iOS/tvOS) // We currently don't support using a pair of Switch Joy-Con's as a single // controller and we don't want to support using them individually for the // time being, so these should be disabled until one of the above is true // { MAKE_CONTROLLER_ID( 0x057e, 0x2006 ), k_eControllerType_SwitchJoyConLeft, NULL }, // Nintendo Switch Joy-Con (Left) // { MAKE_CONTROLLER_ID( 0x057e, 0x2007 ), k_eControllerType_SwitchJoyConRight, NULL }, // Nintendo Switch Joy-Con (Right) // This same controller ID is spoofed by many 3rd-party Switch controllers. // The ones we currently know of are: // * Any 8bitdo controller with Switch support // * ORTZ Gaming Wireless Pro Controller // * ZhiXu Gamepad Wireless // * Sunwaytek Wireless Motion Controller for Nintendo Switch { MAKE_CONTROLLER_ID( 0x057e, 0x2009 ), k_eControllerType_SwitchProController, NULL }, // Nintendo Switch Pro Controller { MAKE_CONTROLLER_ID( 0x0f0d, 0x00c1 ), k_eControllerType_SwitchInputOnlyController, NULL }, // HORIPAD for Nintendo Switch { MAKE_CONTROLLER_ID( 0x0f0d, 0x0092 ), k_eControllerType_SwitchInputOnlyController, NULL }, // HORI Pokken Tournament DX Pro Pad { MAKE_CONTROLLER_ID( 0x0f0d, 0x00f6 ), k_eControllerType_SwitchProController, NULL }, // HORI Wireless Switch Pad { MAKE_CONTROLLER_ID( 0x0f0d, 0x00dc ), k_eControllerType_XInputSwitchController, NULL }, // HORI Battle Pad. Is a Switch controller but shows up through XInput on Windows. { MAKE_CONTROLLER_ID( 0x0e6f, 0x0185 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PDP Wired Fight Pad Pro for Nintendo Switch { MAKE_CONTROLLER_ID( 0x0e6f, 0x0180 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PDP Faceoff Wired Pro Controller for Nintendo Switch { MAKE_CONTROLLER_ID( 0x0e6f, 0x0181 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PDP Faceoff Deluxe Wired Pro Controller for Nintendo Switch { MAKE_CONTROLLER_ID( 0x20d6, 0xa711 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PowerA Wired Controller Plus/PowerA Wired Controller Nintendo GameCube Style { MAKE_CONTROLLER_ID( 0x20d6, 0xa712 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PowerA - Fusion Fight Pad { MAKE_CONTROLLER_ID( 0x20d6, 0xa713 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PowerA - Super Mario Controller { MAKE_CONTROLLER_ID( 0x0e6f, 0x0186 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PDP Afterglow Wireless Switch Controller - working gyro. USB doesn't work { MAKE_CONTROLLER_ID( 0x0e6f, 0x0184 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PDP Faceoff Wired Deluxe+ Audio Controller { MAKE_CONTROLLER_ID( 0x0f0d, 0x00aa ), k_eControllerType_SwitchInputOnlyController, NULL }, // HORI Real Arcade Pro V Hayabusa in Switch Mode { MAKE_CONTROLLER_ID( 0x0e6f, 0x0188 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PDP Afterglow Wired Deluxe+ Audio Controller { MAKE_CONTROLLER_ID( 0x0e6f, 0x0187 ), k_eControllerType_SwitchInputOnlyController, NULL }, // PDP Rockcandy Wirec Controller // Valve products - don't add to public list { MAKE_CONTROLLER_ID( 0x0000, 0x11fb ), k_eControllerType_MobileTouch, NULL }, // Streaming mobile touch virtual controls { MAKE_CONTROLLER_ID( 0x28de, 0x1101 ), k_eControllerType_SteamController, NULL }, // Valve Legacy Steam Controller (CHELL) { MAKE_CONTROLLER_ID( 0x28de, 0x1102 ), k_eControllerType_SteamController, NULL }, // Valve wired Steam Controller (D0G) { MAKE_CONTROLLER_ID( 0x28de, 0x1105 ), k_eControllerType_SteamController, NULL }, // Valve Bluetooth Steam Controller (D0G) { MAKE_CONTROLLER_ID( 0x28de, 0x1106 ), k_eControllerType_SteamController, NULL }, // Valve Bluetooth Steam Controller (D0G) { MAKE_CONTROLLER_ID( 0x28de, 0x1142 ), k_eControllerType_SteamController, NULL }, // Valve wireless Steam Controller { MAKE_CONTROLLER_ID( 0x28de, 0x1201 ), k_eControllerType_SteamControllerV2, NULL }, // Valve wired Steam Controller (HEADCRAB) { MAKE_CONTROLLER_ID( 0x28de, 0x1202 ), k_eControllerType_SteamControllerV2, NULL }, // Valve Bluetooth Steam Controller (HEADCRAB) }; static SDL_INLINE const char *GetControllerTypeOverride( int nVID, int nPID ) { const char *hint = SDL_GetHint(SDL_HINT_GAMECONTROLLERTYPE); if (hint) { char key[32]; const char *spot = NULL; SDL_snprintf(key, sizeof(key), "0x%.4x/0x%.4x=", nVID, nPID); spot = SDL_strstr(hint, key); if (!spot) { SDL_snprintf(key, sizeof(key), "0x%.4X/0x%.4X=", nVID, nPID); spot = SDL_strstr(hint, key); } if (spot) { spot += SDL_strlen(key); if (SDL_strncmp(spot, "k_eControllerType_", 18) == 0) { spot += 18; } return spot; } } return NULL; } static SDL_INLINE EControllerType GuessControllerType( int nVID, int nPID ) { #if 0//def _DEBUG // Verify that there are no duplicates in the controller list // If the list were sorted, we could do this much more efficiently, as well as improve lookup speed. static bool s_bCheckedForDuplicates; if ( !s_bCheckedForDuplicates ) { s_bCheckedForDuplicates = true; for ( int i = 0; i < sizeof( arrControllers ) / sizeof( arrControllers[ 0 ] ); ++i ) { for ( int j = i + 1; j < sizeof( arrControllers ) / sizeof( arrControllers[ 0 ] ); ++j ) { if ( arrControllers[ i ].m_unDeviceID == arrControllers[ j ].m_unDeviceID ) { Log( "Duplicate controller entry found for VID 0x%.4x PID 0x%.4x\n", ( arrControllers[ i ].m_unDeviceID >> 16 ), arrControllers[ i ].m_unDeviceID & 0xFFFF ); } } } } #endif // _DEBUG unsigned int unDeviceID = MAKE_CONTROLLER_ID( nVID, nPID ); int iIndex; const char *pszOverride = GetControllerTypeOverride( nVID, nPID ); if ( pszOverride ) { if ( SDL_strncasecmp( pszOverride, "Xbox360", 7 ) == 0 ) { return k_eControllerType_XBox360Controller; } if ( SDL_strncasecmp( pszOverride, "XboxOne", 7 ) == 0 ) { return k_eControllerType_XBoxOneController; } if ( SDL_strncasecmp( pszOverride, "PS3", 3 ) == 0 ) { return k_eControllerType_PS3Controller; } if ( SDL_strncasecmp( pszOverride, "PS4", 3 ) == 0 ) { return k_eControllerType_PS4Controller; } if ( SDL_strncasecmp( pszOverride, "SwitchPro", 9 ) == 0 ) { return k_eControllerType_SwitchProController; } if ( SDL_strncasecmp( pszOverride, "Steam", 5 ) == 0 ) { return k_eControllerType_SteamController; } return k_eControllerType_UnknownNonSteamController; } for ( iIndex = 0; iIndex < sizeof( arrControllers ) / sizeof( arrControllers[0] ); ++iIndex ) { if ( unDeviceID == arrControllers[ iIndex ].m_unDeviceID ) { return arrControllers[ iIndex ].m_eControllerType; } } return k_eControllerType_UnknownNonSteamController; } static SDL_INLINE const char *GuessControllerName( int nVID, int nPID ) { unsigned int unDeviceID = MAKE_CONTROLLER_ID( nVID, nPID ); int iIndex; for ( iIndex = 0; iIndex < sizeof( arrControllers ) / sizeof( arrControllers[0] ); ++iIndex ) { if ( unDeviceID == arrControllers[ iIndex ].m_unDeviceID ) { return arrControllers[ iIndex ].m_pszName; } } return NULL; } #undef MAKE_CONTROLLER_ID static SDL_INLINE int GetDefaultDeadzoneSizeForControllerType( EControllerType eControllerType ) { switch ( eControllerType ) { case k_eControllerType_UnknownNonSteamController: case k_eControllerType_XBoxOneController: case k_eControllerType_XBox360Controller: case k_eControllerType_AppleController: case k_eControllerType_AndroidController: case k_eControllerType_PS3Controller: return 10000; case k_eControllerType_SteamControllerV2: return 8192; case k_eControllerType_PS4Controller: return 4096; case k_eControllerType_SwitchJoyConLeft: case k_eControllerType_SwitchJoyConRight: case k_eControllerType_SwitchJoyConPair: return 8192; // Actual dead-zone should be 15% of full-scale, but we use this to account for variances in 3rd-party controllers case k_eControllerType_SwitchProController: return 8192; // Actual dead-zone should be closer to 10% of full-scale, but we use this to account for variances in 3rd-party controllers default: return 8192; } } #endif // CONSTANTS_H
YifuLiu/AliOS-Things
components/SDL2/src/joystick/controller_type.h
C
apache-2.0
64,492
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_IOKIT #include "SDL_events.h" #include "SDL_joystick.h" #include "../SDL_sysjoystick.h" #include "../SDL_joystick_c.h" #include "SDL_sysjoystick_c.h" #include "../hidapi/SDL_hidapijoystick_c.h" #include "../../haptic/darwin/SDL_syshaptic_c.h" /* For haptic hot plugging */ #define SDL_JOYSTICK_RUNLOOP_MODE CFSTR("SDLJoystick") #define CONVERT_MAGNITUDE(x) (((x)*10000) / 0x7FFF) /* The base object of the HID Manager API */ static IOHIDManagerRef hidman = NULL; /* Linked list of all available devices */ static recDevice *gpDeviceList = NULL; void FreeRumbleEffectData(FFEFFECT *effect) { if (!effect) { return; } SDL_free(effect->rgdwAxes); SDL_free(effect->rglDirection); SDL_free(effect->lpvTypeSpecificParams); SDL_free(effect); } FFEFFECT *CreateRumbleEffectData(Sint16 magnitude) { FFEFFECT *effect; FFPERIODIC *periodic; /* Create the effect */ effect = (FFEFFECT *)SDL_calloc(1, sizeof(*effect)); if (!effect) { return NULL; } effect->dwSize = sizeof(*effect); effect->dwGain = 10000; effect->dwFlags = FFEFF_OBJECTOFFSETS; effect->dwDuration = SDL_MAX_RUMBLE_DURATION_MS * 1000; /* In microseconds. */ effect->dwTriggerButton = FFEB_NOTRIGGER; effect->cAxes = 2; effect->rgdwAxes = (DWORD *)SDL_calloc(effect->cAxes, sizeof(DWORD)); if (!effect->rgdwAxes) { FreeRumbleEffectData(effect); return NULL; } effect->rglDirection = (LONG *)SDL_calloc(effect->cAxes, sizeof(LONG)); if (!effect->rglDirection) { FreeRumbleEffectData(effect); return NULL; } effect->dwFlags |= FFEFF_CARTESIAN; periodic = (FFPERIODIC *)SDL_calloc(1, sizeof(*periodic)); if (!periodic) { FreeRumbleEffectData(effect); return NULL; } periodic->dwMagnitude = CONVERT_MAGNITUDE(magnitude); periodic->dwPeriod = 1000000; effect->cbTypeSpecificParams = sizeof(*periodic); effect->lpvTypeSpecificParams = periodic; return effect; } static recDevice *GetDeviceForIndex(int device_index) { recDevice *device = gpDeviceList; while (device) { if (!device->removed) { if (device_index == 0) break; --device_index; } device = device->pNext; } return device; } static void FreeElementList(recElement *pElement) { while (pElement) { recElement *pElementNext = pElement->pNext; SDL_free(pElement); pElement = pElementNext; } } static recDevice * FreeDevice(recDevice *removeDevice) { recDevice *pDeviceNext = NULL; if (removeDevice) { if (removeDevice->deviceRef) { if (removeDevice->runLoopAttached) { /* Calling IOHIDDeviceUnscheduleFromRunLoop without a prior, * paired call to IOHIDDeviceScheduleWithRunLoop can lead * to crashes in MacOS 10.14.x and earlier. This doesn't * appear to be a problem in MacOS 10.15.x, but we'll * do it anyways. (Part-of fix for Bug 5034) */ IOHIDDeviceUnscheduleFromRunLoop(removeDevice->deviceRef, CFRunLoopGetCurrent(), SDL_JOYSTICK_RUNLOOP_MODE); } CFRelease(removeDevice->deviceRef); removeDevice->deviceRef = NULL; } /* clear out any reference to removeDevice from an associated, * live instance of SDL_Joystick (Part-of fix for Bug 5034) */ SDL_LockJoysticks(); if (removeDevice->joystick) { removeDevice->joystick->hwdata = NULL; } SDL_UnlockJoysticks(); /* save next device prior to disposing of this device */ pDeviceNext = removeDevice->pNext; if ( gpDeviceList == removeDevice ) { gpDeviceList = pDeviceNext; } else if (gpDeviceList) { recDevice *device = gpDeviceList; while (device->pNext != removeDevice) { device = device->pNext; } device->pNext = pDeviceNext; } removeDevice->pNext = NULL; /* free element lists */ FreeElementList(removeDevice->firstAxis); FreeElementList(removeDevice->firstButton); FreeElementList(removeDevice->firstHat); SDL_free(removeDevice); } return pDeviceNext; } static SDL_bool GetHIDElementState(recDevice *pDevice, recElement *pElement, SInt32 *pValue) { SInt32 value = 0; int returnValue = SDL_FALSE; if (pDevice && pDevice->deviceRef && pElement) { IOHIDValueRef valueRef; if (IOHIDDeviceGetValue(pDevice->deviceRef, pElement->elementRef, &valueRef) == kIOReturnSuccess) { value = (SInt32) IOHIDValueGetIntegerValue(valueRef); /* record min and max for auto calibration */ if (value < pElement->minReport) { pElement->minReport = value; } if (value > pElement->maxReport) { pElement->maxReport = value; } *pValue = value; returnValue = SDL_TRUE; } } return returnValue; } static SDL_bool GetHIDScaledCalibratedState(recDevice * pDevice, recElement * pElement, SInt32 min, SInt32 max, SInt32 *pValue) { const float deviceScale = max - min; const float readScale = pElement->maxReport - pElement->minReport; int returnValue = SDL_FALSE; if (GetHIDElementState(pDevice, pElement, pValue)) { if (readScale == 0) { returnValue = SDL_TRUE; /* no scaling at all */ } else { *pValue = ((*pValue - pElement->minReport) * deviceScale / readScale) + min; returnValue = SDL_TRUE; } } return returnValue; } static void JoystickDeviceWasRemovedCallback(void *ctx, IOReturn result, void *sender) { recDevice *device = (recDevice *) ctx; device->removed = SDL_TRUE; if (device->deviceRef) { // deviceRef was invalidated due to the remove CFRelease(device->deviceRef); device->deviceRef = NULL; } if (device->ffeffect_ref) { FFDeviceReleaseEffect(device->ffdevice, device->ffeffect_ref); device->ffeffect_ref = NULL; } if (device->ffeffect) { FreeRumbleEffectData(device->ffeffect); device->ffeffect = NULL; } if (device->ffdevice) { FFReleaseDevice(device->ffdevice); device->ffdevice = NULL; device->ff_initialized = SDL_FALSE; } #if SDL_HAPTIC_IOKIT MacHaptic_MaybeRemoveDevice(device->ffservice); #endif SDL_PrivateJoystickRemoved(device->instance_id); } static void AddHIDElement(const void *value, void *parameter); /* Call AddHIDElement() on all elements in an array of IOHIDElementRefs */ static void AddHIDElements(CFArrayRef array, recDevice *pDevice) { const CFRange range = { 0, CFArrayGetCount(array) }; CFArrayApplyFunction(array, range, AddHIDElement, pDevice); } static SDL_bool ElementAlreadyAdded(const IOHIDElementCookie cookie, const recElement *listitem) { while (listitem) { if (listitem->cookie == cookie) { return SDL_TRUE; } listitem = listitem->pNext; } return SDL_FALSE; } /* See if we care about this HID element, and if so, note it in our recDevice. */ static void AddHIDElement(const void *value, void *parameter) { recDevice *pDevice = (recDevice *) parameter; IOHIDElementRef refElement = (IOHIDElementRef) value; const CFTypeID elementTypeID = refElement ? CFGetTypeID(refElement) : 0; if (refElement && (elementTypeID == IOHIDElementGetTypeID())) { const IOHIDElementCookie cookie = IOHIDElementGetCookie(refElement); const uint32_t usagePage = IOHIDElementGetUsagePage(refElement); const uint32_t usage = IOHIDElementGetUsage(refElement); recElement *element = NULL; recElement **headElement = NULL; /* look at types of interest */ switch (IOHIDElementGetType(refElement)) { case kIOHIDElementTypeInput_Misc: case kIOHIDElementTypeInput_Button: case kIOHIDElementTypeInput_Axis: { switch (usagePage) { /* only interested in kHIDPage_GenericDesktop and kHIDPage_Button */ case kHIDPage_GenericDesktop: switch (usage) { case kHIDUsage_GD_X: case kHIDUsage_GD_Y: case kHIDUsage_GD_Z: case kHIDUsage_GD_Rx: case kHIDUsage_GD_Ry: case kHIDUsage_GD_Rz: case kHIDUsage_GD_Slider: case kHIDUsage_GD_Dial: case kHIDUsage_GD_Wheel: if (!ElementAlreadyAdded(cookie, pDevice->firstAxis)) { element = (recElement *) SDL_calloc(1, sizeof (recElement)); if (element) { pDevice->axes++; headElement = &(pDevice->firstAxis); } } break; case kHIDUsage_GD_Hatswitch: if (!ElementAlreadyAdded(cookie, pDevice->firstHat)) { element = (recElement *) SDL_calloc(1, sizeof (recElement)); if (element) { pDevice->hats++; headElement = &(pDevice->firstHat); } } break; case kHIDUsage_GD_DPadUp: case kHIDUsage_GD_DPadDown: case kHIDUsage_GD_DPadRight: case kHIDUsage_GD_DPadLeft: case kHIDUsage_GD_Start: case kHIDUsage_GD_Select: case kHIDUsage_GD_SystemMainMenu: if (!ElementAlreadyAdded(cookie, pDevice->firstButton)) { element = (recElement *) SDL_calloc(1, sizeof (recElement)); if (element) { pDevice->buttons++; headElement = &(pDevice->firstButton); } } break; } break; case kHIDPage_Simulation: switch (usage) { case kHIDUsage_Sim_Rudder: case kHIDUsage_Sim_Throttle: case kHIDUsage_Sim_Accelerator: case kHIDUsage_Sim_Brake: if (!ElementAlreadyAdded(cookie, pDevice->firstAxis)) { element = (recElement *) SDL_calloc(1, sizeof (recElement)); if (element) { pDevice->axes++; headElement = &(pDevice->firstAxis); } } break; default: break; } break; case kHIDPage_Button: case kHIDPage_Consumer: /* e.g. 'pause' button on Steelseries MFi gamepads. */ if (!ElementAlreadyAdded(cookie, pDevice->firstButton)) { element = (recElement *) SDL_calloc(1, sizeof (recElement)); if (element) { pDevice->buttons++; headElement = &(pDevice->firstButton); } } break; default: break; } } break; case kIOHIDElementTypeCollection: { CFArrayRef array = IOHIDElementGetChildren(refElement); if (array) { AddHIDElements(array, pDevice); } } break; default: break; } if (element && headElement) { /* add to list */ recElement *elementPrevious = NULL; recElement *elementCurrent = *headElement; while (elementCurrent && usage >= elementCurrent->usage) { elementPrevious = elementCurrent; elementCurrent = elementCurrent->pNext; } if (elementPrevious) { elementPrevious->pNext = element; } else { *headElement = element; } element->elementRef = refElement; element->usagePage = usagePage; element->usage = usage; element->pNext = elementCurrent; element->minReport = element->min = (SInt32) IOHIDElementGetLogicalMin(refElement); element->maxReport = element->max = (SInt32) IOHIDElementGetLogicalMax(refElement); element->cookie = IOHIDElementGetCookie(refElement); pDevice->elements++; } } } static SDL_bool GetDeviceInfo(IOHIDDeviceRef hidDevice, recDevice *pDevice) { Sint32 vendor = 0; Sint32 product = 0; Sint32 version = 0; char *name; char manufacturer_string[256]; char product_string[256]; CFTypeRef refCF = NULL; CFArrayRef array = NULL; Uint16 *guid16 = (Uint16 *)pDevice->guid.data; /* get usage page and usage */ refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDPrimaryUsagePageKey)); if (refCF) { CFNumberGetValue(refCF, kCFNumberSInt32Type, &pDevice->usagePage); } if (pDevice->usagePage != kHIDPage_GenericDesktop) { return SDL_FALSE; /* Filter device list to non-keyboard/mouse stuff */ } refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDPrimaryUsageKey)); if (refCF) { CFNumberGetValue(refCF, kCFNumberSInt32Type, &pDevice->usage); } if ((pDevice->usage != kHIDUsage_GD_Joystick && pDevice->usage != kHIDUsage_GD_GamePad && pDevice->usage != kHIDUsage_GD_MultiAxisController)) { return SDL_FALSE; /* Filter device list to non-keyboard/mouse stuff */ } /* Make sure we retain the use of the IOKit-provided device-object, lest the device get disconnected and we try to use it. (Fixes SDL-Bugzilla #4961, aka. https://bugzilla.libsdl.org/show_bug.cgi?id=4961 ) */ CFRetain(hidDevice); /* Now that we've CFRetain'ed the device-object (for our use), we'll save the reference to it. */ pDevice->deviceRef = hidDevice; refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDVendorIDKey)); if (refCF) { CFNumberGetValue(refCF, kCFNumberSInt32Type, &vendor); } refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDProductIDKey)); if (refCF) { CFNumberGetValue(refCF, kCFNumberSInt32Type, &product); } refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDVersionNumberKey)); if (refCF) { CFNumberGetValue(refCF, kCFNumberSInt32Type, &version); } /* get device name */ refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDManufacturerKey)); if ((!refCF) || (!CFStringGetCString(refCF, manufacturer_string, sizeof(manufacturer_string), kCFStringEncodingUTF8))) { manufacturer_string[0] = '\0'; } refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDProductKey)); if ((!refCF) || (!CFStringGetCString(refCF, product_string, sizeof(product_string), kCFStringEncodingUTF8))) { product_string[0] = '\0'; } name = SDL_CreateJoystickName(vendor, product, manufacturer_string, product_string); if (name) { SDL_strlcpy(pDevice->product, name, sizeof(pDevice->product)); SDL_free(name); } #ifdef SDL_JOYSTICK_HIDAPI if (HIDAPI_IsDevicePresent(vendor, product, version, pDevice->product)) { /* The HIDAPI driver is taking care of this device */ return 0; } #endif SDL_memset(pDevice->guid.data, 0, sizeof(pDevice->guid.data)); if (vendor && product) { *guid16++ = SDL_SwapLE16(SDL_HARDWARE_BUS_USB); *guid16++ = 0; *guid16++ = SDL_SwapLE16((Uint16)vendor); *guid16++ = 0; *guid16++ = SDL_SwapLE16((Uint16)product); *guid16++ = 0; *guid16++ = SDL_SwapLE16((Uint16)version); *guid16++ = 0; } else { *guid16++ = SDL_SwapLE16(SDL_HARDWARE_BUS_BLUETOOTH); *guid16++ = 0; SDL_strlcpy((char*)guid16, pDevice->product, sizeof(pDevice->guid.data) - 4); } array = IOHIDDeviceCopyMatchingElements(hidDevice, NULL, kIOHIDOptionsTypeNone); if (array) { AddHIDElements(array, pDevice); CFRelease(array); } return SDL_TRUE; } static SDL_bool JoystickAlreadyKnown(IOHIDDeviceRef ioHIDDeviceObject) { recDevice *i; for (i = gpDeviceList; i != NULL; i = i->pNext) { if (i->deviceRef == ioHIDDeviceObject) { return SDL_TRUE; } } return SDL_FALSE; } static void JoystickDeviceWasAddedCallback(void *ctx, IOReturn res, void *sender, IOHIDDeviceRef ioHIDDeviceObject) { recDevice *device; int device_index = 0; io_service_t ioservice; if (res != kIOReturnSuccess) { return; } if (JoystickAlreadyKnown(ioHIDDeviceObject)) { return; /* IOKit sent us a duplicate. */ } device = (recDevice *) SDL_calloc(1, sizeof(recDevice)); if (!device) { SDL_OutOfMemory(); return; } if (!GetDeviceInfo(ioHIDDeviceObject, device)) { FreeDevice(device); return; /* not a device we care about, probably. */ } if (SDL_ShouldIgnoreJoystick(device->product, device->guid)) { FreeDevice(device); return; } /* Get notified when this device is disconnected. */ IOHIDDeviceRegisterRemovalCallback(ioHIDDeviceObject, JoystickDeviceWasRemovedCallback, device); IOHIDDeviceScheduleWithRunLoop(ioHIDDeviceObject, CFRunLoopGetCurrent(), SDL_JOYSTICK_RUNLOOP_MODE); device->runLoopAttached = SDL_TRUE; /* Allocate an instance ID for this device */ device->instance_id = SDL_GetNextJoystickInstanceID(); /* We have to do some storage of the io_service_t for SDL_HapticOpenFromJoystick */ ioservice = IOHIDDeviceGetService(ioHIDDeviceObject); if ((ioservice) && (FFIsForceFeedback(ioservice) == FF_OK)) { device->ffservice = ioservice; #if SDL_HAPTIC_IOKIT MacHaptic_MaybeAddDevice(ioservice); #endif } /* Add device to the end of the list */ if ( !gpDeviceList ) { gpDeviceList = device; } else { recDevice *curdevice; curdevice = gpDeviceList; while ( curdevice->pNext ) { ++device_index; curdevice = curdevice->pNext; } curdevice->pNext = device; ++device_index; /* bump by one since we counted by pNext. */ } SDL_PrivateJoystickAdded(device->instance_id); } static SDL_bool ConfigHIDManager(CFArrayRef matchingArray) { CFRunLoopRef runloop = CFRunLoopGetCurrent(); if (IOHIDManagerOpen(hidman, kIOHIDOptionsTypeNone) != kIOReturnSuccess) { return SDL_FALSE; } IOHIDManagerSetDeviceMatchingMultiple(hidman, matchingArray); IOHIDManagerRegisterDeviceMatchingCallback(hidman, JoystickDeviceWasAddedCallback, NULL); IOHIDManagerScheduleWithRunLoop(hidman, runloop, SDL_JOYSTICK_RUNLOOP_MODE); while (CFRunLoopRunInMode(SDL_JOYSTICK_RUNLOOP_MODE,0,TRUE) == kCFRunLoopRunHandledSource) { /* no-op. Callback fires once per existing device. */ } /* future hotplug events will come through SDL_JOYSTICK_RUNLOOP_MODE now. */ return SDL_TRUE; /* good to go. */ } static CFDictionaryRef CreateHIDDeviceMatchDictionary(const UInt32 page, const UInt32 usage, int *okay) { CFDictionaryRef retval = NULL; CFNumberRef pageNumRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &page); CFNumberRef usageNumRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage); const void *keys[2] = { (void *) CFSTR(kIOHIDDeviceUsagePageKey), (void *) CFSTR(kIOHIDDeviceUsageKey) }; const void *vals[2] = { (void *) pageNumRef, (void *) usageNumRef }; if (pageNumRef && usageNumRef) { retval = CFDictionaryCreate(kCFAllocatorDefault, keys, vals, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } if (pageNumRef) { CFRelease(pageNumRef); } if (usageNumRef) { CFRelease(usageNumRef); } if (!retval) { *okay = 0; } return retval; } static SDL_bool CreateHIDManager(void) { SDL_bool retval = SDL_FALSE; int okay = 1; const void *vals[] = { (void *) CreateHIDDeviceMatchDictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_Joystick, &okay), (void *) CreateHIDDeviceMatchDictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_GamePad, &okay), (void *) CreateHIDDeviceMatchDictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_MultiAxisController, &okay), }; const size_t numElements = SDL_arraysize(vals); CFArrayRef array = okay ? CFArrayCreate(kCFAllocatorDefault, vals, numElements, &kCFTypeArrayCallBacks) : NULL; size_t i; for (i = 0; i < numElements; i++) { if (vals[i]) { CFRelease((CFTypeRef) vals[i]); } } if (array) { hidman = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); if (hidman != NULL) { retval = ConfigHIDManager(array); } CFRelease(array); } return retval; } static int DARWIN_JoystickInit(void) { if (gpDeviceList) { return SDL_SetError("Joystick: Device list already inited."); } if (!CreateHIDManager()) { return SDL_SetError("Joystick: Couldn't initialize HID Manager"); } return 0; } static int DARWIN_JoystickGetCount(void) { recDevice *device = gpDeviceList; int nJoySticks = 0; while (device) { if (!device->removed) { nJoySticks++; } device = device->pNext; } return nJoySticks; } static void DARWIN_JoystickDetect(void) { recDevice *device = gpDeviceList; while (device) { if (device->removed) { device = FreeDevice(device); } else { device = device->pNext; } } /* run this after the checks above so we don't set device->removed and delete the device before DARWIN_JoystickUpdate can run to clean up the SDL_Joystick object that owns this device */ while (CFRunLoopRunInMode(SDL_JOYSTICK_RUNLOOP_MODE,0,TRUE) == kCFRunLoopRunHandledSource) { /* no-op. Pending callbacks will fire in CFRunLoopRunInMode(). */ } } /* Function to get the device-dependent name of a joystick */ const char * DARWIN_JoystickGetDeviceName(int device_index) { recDevice *device = GetDeviceForIndex(device_index); return device ? device->product : "UNKNOWN"; } static int DARWIN_JoystickGetDevicePlayerIndex(int device_index) { return -1; } static void DARWIN_JoystickSetDevicePlayerIndex(int device_index, int player_index) { } static SDL_JoystickGUID DARWIN_JoystickGetDeviceGUID( int device_index ) { recDevice *device = GetDeviceForIndex(device_index); SDL_JoystickGUID guid; if (device) { guid = device->guid; } else { SDL_zero(guid); } return guid; } static SDL_JoystickID DARWIN_JoystickGetDeviceInstanceID(int device_index) { recDevice *device = GetDeviceForIndex(device_index); return device ? device->instance_id : 0; } static int DARWIN_JoystickOpen(SDL_Joystick * joystick, int device_index) { recDevice *device = GetDeviceForIndex(device_index); joystick->instance_id = device->instance_id; joystick->hwdata = device; device->joystick = joystick; joystick->name = device->product; joystick->naxes = device->axes; joystick->nhats = device->hats; joystick->nballs = 0; joystick->nbuttons = device->buttons; return 0; } /* * Like strerror but for force feedback errors. */ static const char * FFStrError(unsigned int err) { switch (err) { case FFERR_DEVICEFULL: return "device full"; /* This should be valid, but for some reason isn't defined... */ /* case FFERR_DEVICENOTREG: return "device not registered"; */ case FFERR_DEVICEPAUSED: return "device paused"; case FFERR_DEVICERELEASED: return "device released"; case FFERR_EFFECTPLAYING: return "effect playing"; case FFERR_EFFECTTYPEMISMATCH: return "effect type mismatch"; case FFERR_EFFECTTYPENOTSUPPORTED: return "effect type not supported"; case FFERR_GENERIC: return "undetermined error"; case FFERR_HASEFFECTS: return "device has effects"; case FFERR_INCOMPLETEEFFECT: return "incomplete effect"; case FFERR_INTERNAL: return "internal fault"; case FFERR_INVALIDDOWNLOADID: return "invalid download id"; case FFERR_INVALIDPARAM: return "invalid parameter"; case FFERR_MOREDATA: return "more data"; case FFERR_NOINTERFACE: return "interface not supported"; case FFERR_NOTDOWNLOADED: return "effect is not downloaded"; case FFERR_NOTINITIALIZED: return "object has not been initialized"; case FFERR_OUTOFMEMORY: return "out of memory"; case FFERR_UNPLUGGED: return "device is unplugged"; case FFERR_UNSUPPORTED: return "function call unsupported"; case FFERR_UNSUPPORTEDAXIS: return "axis unsupported"; default: return "unknown error"; } } static int DARWIN_JoystickInitRumble(recDevice *device, Sint16 magnitude) { HRESULT result; if (!device->ffdevice) { result = FFCreateDevice(device->ffservice, &device->ffdevice); if (result != FF_OK) { return SDL_SetError("Unable to create force feedback device from service: %s", FFStrError(result)); } } /* Reset and then enable actuators */ result = FFDeviceSendForceFeedbackCommand(device->ffdevice, FFSFFC_RESET); if (result != FF_OK) { return SDL_SetError("Unable to reset force feedback device: %s", FFStrError(result)); } result = FFDeviceSendForceFeedbackCommand(device->ffdevice, FFSFFC_SETACTUATORSON); if (result != FF_OK) { return SDL_SetError("Unable to enable force feedback actuators: %s", FFStrError(result)); } /* Create the effect */ device->ffeffect = CreateRumbleEffectData(magnitude); if (!device->ffeffect) { return SDL_OutOfMemory(); } result = FFDeviceCreateEffect(device->ffdevice, kFFEffectType_Sine_ID, device->ffeffect, &device->ffeffect_ref); if (result != FF_OK) { return SDL_SetError("Haptic: Unable to create effect: %s", FFStrError(result)); } return 0; } static int DARWIN_JoystickRumble(SDL_Joystick * joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { HRESULT result; recDevice *device = joystick->hwdata; /* Scale and average the two rumble strengths */ Sint16 magnitude = (Sint16)(((low_frequency_rumble / 2) + (high_frequency_rumble / 2)) / 2); if (!device) { return SDL_SetError("Rumble failed, device disconnected"); } if (!device->ffservice) { return SDL_Unsupported(); } if (device->ff_initialized) { FFPERIODIC *periodic = ((FFPERIODIC *)device->ffeffect->lpvTypeSpecificParams); periodic->dwMagnitude = CONVERT_MAGNITUDE(magnitude); result = FFEffectSetParameters(device->ffeffect_ref, device->ffeffect, (FFEP_DURATION | FFEP_TYPESPECIFICPARAMS)); if (result != FF_OK) { return SDL_SetError("Unable to update rumble effect: %s", FFStrError(result)); } } else { if (DARWIN_JoystickInitRumble(device, magnitude) < 0) { return -1; } device->ff_initialized = SDL_TRUE; } result = FFEffectStart(device->ffeffect_ref, 1, 0); if (result != FF_OK) { return SDL_SetError("Unable to run the rumble effect: %s", FFStrError(result)); } return 0; } static void DARWIN_JoystickUpdate(SDL_Joystick * joystick) { recDevice *device = joystick->hwdata; recElement *element; SInt32 value, range; int i; if (!device) { return; } if (device->removed) { /* device was unplugged; ignore it. */ if (joystick->hwdata) { joystick->hwdata = NULL; } return; } element = device->firstAxis; i = 0; int goodRead = SDL_FALSE; while (element) { goodRead = GetHIDScaledCalibratedState(device, element, -32768, 32767, &value); if (goodRead) { SDL_PrivateJoystickAxis(joystick, i, value); } element = element->pNext; ++i; } element = device->firstButton; i = 0; while (element) { goodRead = GetHIDElementState(device, element, &value); if (goodRead) { if (value > 1) { /* handle pressure-sensitive buttons */ value = 1; } SDL_PrivateJoystickButton(joystick, i, value); } element = element->pNext; ++i; } element = device->firstHat; i = 0; while (element) { Uint8 pos = 0; range = (element->max - element->min + 1); goodRead = GetHIDElementState(device, element, &value); if (goodRead) { value -= element->min; if (range == 4) { /* 4 position hatswitch - scale up value */ value *= 2; } else if (range != 8) { /* Neither a 4 nor 8 positions - fall back to default position (centered) */ value = -1; } switch (value) { case 0: pos = SDL_HAT_UP; break; case 1: pos = SDL_HAT_RIGHTUP; break; case 2: pos = SDL_HAT_RIGHT; break; case 3: pos = SDL_HAT_RIGHTDOWN; break; case 4: pos = SDL_HAT_DOWN; break; case 5: pos = SDL_HAT_LEFTDOWN; break; case 6: pos = SDL_HAT_LEFT; break; case 7: pos = SDL_HAT_LEFTUP; break; default: /* Every other value is mapped to center. We do that because some * joysticks use 8 and some 15 for this value, and apparently * there are even more variants out there - so we try to be generous. */ pos = SDL_HAT_CENTERED; break; } SDL_PrivateJoystickHat(joystick, i, pos); } element = element->pNext; ++i; } } static void DARWIN_JoystickClose(SDL_Joystick * joystick) { recDevice *device = joystick->hwdata; if (device) { device->joystick = NULL; } } static void DARWIN_JoystickQuit(void) { while (FreeDevice(gpDeviceList)) { /* spin */ } if (hidman) { IOHIDManagerUnscheduleFromRunLoop(hidman, CFRunLoopGetCurrent(), SDL_JOYSTICK_RUNLOOP_MODE); IOHIDManagerClose(hidman, kIOHIDOptionsTypeNone); CFRelease(hidman); hidman = NULL; } } static SDL_bool DARWIN_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) { return SDL_FALSE; } SDL_JoystickDriver SDL_DARWIN_JoystickDriver = { DARWIN_JoystickInit, DARWIN_JoystickGetCount, DARWIN_JoystickDetect, DARWIN_JoystickGetDeviceName, DARWIN_JoystickGetDevicePlayerIndex, DARWIN_JoystickSetDevicePlayerIndex, DARWIN_JoystickGetDeviceGUID, DARWIN_JoystickGetDeviceInstanceID, DARWIN_JoystickOpen, DARWIN_JoystickRumble, DARWIN_JoystickUpdate, DARWIN_JoystickClose, DARWIN_JoystickQuit, DARWIN_JoystickGetGamepadMapping }; #endif /* SDL_JOYSTICK_IOKIT */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/darwin/SDL_sysjoystick.c
C
apache-2.0
34,013
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_JOYSTICK_IOKIT_H #define SDL_JOYSTICK_IOKIT_H #include <IOKit/hid/IOHIDLib.h> #include <ForceFeedback/ForceFeedback.h> #include <ForceFeedback/ForceFeedbackConstants.h> struct recElement { IOHIDElementRef elementRef; IOHIDElementCookie cookie; uint32_t usagePage, usage; /* HID usage */ SInt32 min; /* reported min value possible */ SInt32 max; /* reported max value possible */ /* runtime variables used for auto-calibration */ SInt32 minReport; /* min returned value */ SInt32 maxReport; /* max returned value */ struct recElement *pNext; /* next element in list */ }; typedef struct recElement recElement; struct joystick_hwdata { IOHIDDeviceRef deviceRef; /* HIDManager device handle */ io_service_t ffservice; /* Interface for force feedback, 0 = no ff */ FFDeviceObjectReference ffdevice; FFEFFECT *ffeffect; FFEffectObjectReference ffeffect_ref; SDL_bool ff_initialized; char product[256]; /* name of product */ uint32_t usage; /* usage page from IOUSBHID Parser.h which defines general usage */ uint32_t usagePage; /* usage within above page from IOUSBHID Parser.h which defines specific usage */ int axes; /* number of axis (calculated, not reported by device) */ int buttons; /* number of buttons (calculated, not reported by device) */ int hats; /* number of hat switches (calculated, not reported by device) */ int elements; /* number of total elements (should be total of above) (calculated, not reported by device) */ recElement *firstAxis; recElement *firstButton; recElement *firstHat; SDL_bool removed; SDL_Joystick *joystick; SDL_bool runLoopAttached; /* is 'deviceRef' attached to a CFRunLoop? */ int instance_id; SDL_JoystickGUID guid; struct joystick_hwdata *pNext; /* next device */ }; typedef struct joystick_hwdata recDevice; #endif /* SDL_JOYSTICK_IOKIT_H */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/darwin/SDL_sysjoystick_c.h
C
apache-2.0
3,118
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if defined(SDL_JOYSTICK_DUMMY) || defined(SDL_JOYSTICK_DISABLED) /* This is the dummy implementation of the SDL joystick API */ #include "SDL_joystick.h" #include "../SDL_sysjoystick.h" #include "../SDL_joystick_c.h" static int DUMMY_JoystickInit(void) { return 0; } static int DUMMY_JoystickGetCount(void) { return 0; } static void DUMMY_JoystickDetect(void) { } static const char * DUMMY_JoystickGetDeviceName(int device_index) { return NULL; } static int DUMMY_JoystickGetDevicePlayerIndex(int device_index) { return -1; } static void DUMMY_JoystickSetDevicePlayerIndex(int device_index, int player_index) { } static SDL_JoystickGUID DUMMY_JoystickGetDeviceGUID(int device_index) { SDL_JoystickGUID guid; SDL_zero(guid); return guid; } static SDL_JoystickID DUMMY_JoystickGetDeviceInstanceID(int device_index) { return -1; } static int DUMMY_JoystickOpen(SDL_Joystick * joystick, int device_index) { return SDL_SetError("Logic error: No joysticks available"); } static int DUMMY_JoystickRumble(SDL_Joystick * joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { return SDL_Unsupported(); } static void DUMMY_JoystickUpdate(SDL_Joystick * joystick) { } static void DUMMY_JoystickClose(SDL_Joystick * joystick) { } static void DUMMY_JoystickQuit(void) { } static SDL_bool DUMMY_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) { return SDL_FALSE; } SDL_JoystickDriver SDL_DUMMY_JoystickDriver = { DUMMY_JoystickInit, DUMMY_JoystickGetCount, DUMMY_JoystickDetect, DUMMY_JoystickGetDeviceName, DUMMY_JoystickGetDevicePlayerIndex, DUMMY_JoystickSetDevicePlayerIndex, DUMMY_JoystickGetDeviceGUID, DUMMY_JoystickGetDeviceInstanceID, DUMMY_JoystickOpen, DUMMY_JoystickRumble, DUMMY_JoystickUpdate, DUMMY_JoystickClose, DUMMY_JoystickQuit, DUMMY_JoystickGetGamepadMapping }; #endif /* SDL_JOYSTICK_DUMMY || SDL_JOYSTICK_DISABLED */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/dummy/SDL_sysjoystick.c
C
apache-2.0
2,992
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_EMSCRIPTEN #include <stdio.h> /* For the definition of NULL */ #include "SDL_error.h" #include "SDL_events.h" #include "SDL_joystick.h" #include "SDL_assert.h" #include "SDL_timer.h" #include "SDL_sysjoystick_c.h" #include "../SDL_joystick_c.h" static SDL_joylist_item * JoystickByIndex(int index); static SDL_joylist_item *SDL_joylist = NULL; static SDL_joylist_item *SDL_joylist_tail = NULL; static int numjoysticks = 0; static int instance_counter = 0; static EM_BOOL Emscripten_JoyStickConnected(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData) { int i; SDL_joylist_item *item; if (JoystickByIndex(gamepadEvent->index) != NULL) { return 1; } item = (SDL_joylist_item *) SDL_malloc(sizeof (SDL_joylist_item)); if (item == NULL) { return 1; } SDL_zerop(item); item->index = gamepadEvent->index; item->name = SDL_CreateJoystickName(0, 0, NULL, gamepadEvent->id); if ( item->name == NULL ) { SDL_free(item); return 1; } item->mapping = SDL_strdup(gamepadEvent->mapping); if ( item->mapping == NULL ) { SDL_free(item->name); SDL_free(item); return 1; } item->naxes = gamepadEvent->numAxes; item->nbuttons = gamepadEvent->numButtons; item->device_instance = instance_counter++; item->timestamp = gamepadEvent->timestamp; for( i = 0; i < item->naxes; i++) { item->axis[i] = gamepadEvent->axis[i]; } for( i = 0; i < item->nbuttons; i++) { item->analogButton[i] = gamepadEvent->analogButton[i]; item->digitalButton[i] = gamepadEvent->digitalButton[i]; } if (SDL_joylist_tail == NULL) { SDL_joylist = SDL_joylist_tail = item; } else { SDL_joylist_tail->next = item; SDL_joylist_tail = item; } ++numjoysticks; SDL_PrivateJoystickAdded(item->device_instance); #ifdef DEBUG_JOYSTICK SDL_Log("Number of joysticks is %d", numjoysticks); #endif #ifdef DEBUG_JOYSTICK SDL_Log("Added joystick with index %d", item->index); #endif return 1; } static EM_BOOL Emscripten_JoyStickDisconnected(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData) { SDL_joylist_item *item = SDL_joylist; SDL_joylist_item *prev = NULL; while (item != NULL) { if (item->index == gamepadEvent->index) { break; } prev = item; item = item->next; } if (item == NULL) { return 1; } if (item->joystick) { item->joystick->hwdata = NULL; } if (prev != NULL) { prev->next = item->next; } else { SDL_assert(SDL_joylist == item); SDL_joylist = item->next; } if (item == SDL_joylist_tail) { SDL_joylist_tail = prev; } /* Need to decrement the joystick count before we post the event */ --numjoysticks; SDL_PrivateJoystickRemoved(item->device_instance); #ifdef DEBUG_JOYSTICK SDL_Log("Removed joystick with id %d", item->device_instance); #endif SDL_free(item->name); SDL_free(item->mapping); SDL_free(item); return 1; } /* Function to perform any system-specific joystick related cleanup */ static void EMSCRIPTEN_JoystickQuit(void) { SDL_joylist_item *item = NULL; SDL_joylist_item *next = NULL; for (item = SDL_joylist; item; item = next) { next = item->next; SDL_free(item->mapping); SDL_free(item->name); SDL_free(item); } SDL_joylist = SDL_joylist_tail = NULL; numjoysticks = 0; instance_counter = 0; emscripten_set_gamepadconnected_callback(NULL, 0, NULL); emscripten_set_gamepaddisconnected_callback(NULL, 0, NULL); } /* Function to scan the system for joysticks. * It should return 0, or -1 on an unrecoverable fatal error. */ static int EMSCRIPTEN_JoystickInit(void) { int retval, i, numjs; EmscriptenGamepadEvent gamepadState; numjoysticks = 0; retval = emscripten_sample_gamepad_data(); /* Check if gamepad is supported by browser */ if (retval == EMSCRIPTEN_RESULT_NOT_SUPPORTED) { return SDL_SetError("Gamepads not supported"); } numjs = emscripten_get_num_gamepads(); /* handle already connected gamepads */ if (numjs > 0) { for(i = 0; i < numjs; i++) { retval = emscripten_get_gamepad_status(i, &gamepadState); if (retval == EMSCRIPTEN_RESULT_SUCCESS) { Emscripten_JoyStickConnected(EMSCRIPTEN_EVENT_GAMEPADCONNECTED, &gamepadState, NULL); } } } retval = emscripten_set_gamepadconnected_callback(NULL, 0, Emscripten_JoyStickConnected); if(retval != EMSCRIPTEN_RESULT_SUCCESS) { EMSCRIPTEN_JoystickQuit(); return SDL_SetError("Could not set gamepad connect callback"); } retval = emscripten_set_gamepaddisconnected_callback(NULL, 0, Emscripten_JoyStickDisconnected); if(retval != EMSCRIPTEN_RESULT_SUCCESS) { EMSCRIPTEN_JoystickQuit(); return SDL_SetError("Could not set gamepad disconnect callback"); } return 0; } /* Returns item matching given SDL device index. */ static SDL_joylist_item * JoystickByDeviceIndex(int device_index) { SDL_joylist_item *item = SDL_joylist; while (0 < device_index) { --device_index; item = item->next; } return item; } /* Returns item matching given HTML gamepad index. */ static SDL_joylist_item * JoystickByIndex(int index) { SDL_joylist_item *item = SDL_joylist; if (index < 0) { return NULL; } while (item != NULL) { if (item->index == index) { break; } item = item->next; } return item; } static int EMSCRIPTEN_JoystickGetCount(void) { return numjoysticks; } static void EMSCRIPTEN_JoystickDetect(void) { } static const char * EMSCRIPTEN_JoystickGetDeviceName(int device_index) { return JoystickByDeviceIndex(device_index)->name; } static int EMSCRIPTEN_JoystickGetDevicePlayerIndex(int device_index) { return -1; } static void EMSCRIPTEN_JoystickSetDevicePlayerIndex(int device_index, int player_index) { } static SDL_JoystickID EMSCRIPTEN_JoystickGetDeviceInstanceID(int device_index) { return JoystickByDeviceIndex(device_index)->device_instance; } /* Function to open a joystick for use. The joystick to open is specified by the device index. This should fill the nbuttons and naxes fields of the joystick structure. It returns 0, or -1 if there is an error. */ static int EMSCRIPTEN_JoystickOpen(SDL_Joystick * joystick, int device_index) { SDL_joylist_item *item = JoystickByDeviceIndex(device_index); if (item == NULL ) { return SDL_SetError("No such device"); } if (item->joystick != NULL) { return SDL_SetError("Joystick already opened"); } joystick->instance_id = item->device_instance; joystick->hwdata = (struct joystick_hwdata *) item; item->joystick = joystick; /* HTML5 Gamepad API doesn't say anything about these */ joystick->nhats = 0; joystick->nballs = 0; joystick->nbuttons = item->nbuttons; joystick->naxes = item->naxes; return (0); } /* Function to update the state of a joystick - called as a device poll. * This function shouldn't update the joystick structure directly, * but instead should call SDL_PrivateJoystick*() to deliver events * and update joystick device state. */ static void EMSCRIPTEN_JoystickUpdate(SDL_Joystick * joystick) { EmscriptenGamepadEvent gamepadState; SDL_joylist_item *item = (SDL_joylist_item *) joystick->hwdata; int i, result, buttonState; emscripten_sample_gamepad_data(); if (item) { result = emscripten_get_gamepad_status(item->index, &gamepadState); if( result == EMSCRIPTEN_RESULT_SUCCESS) { if(gamepadState.timestamp == 0 || gamepadState.timestamp != item->timestamp) { for(i = 0; i < item->nbuttons; i++) { if(item->digitalButton[i] != gamepadState.digitalButton[i]) { buttonState = gamepadState.digitalButton[i]? SDL_PRESSED: SDL_RELEASED; SDL_PrivateJoystickButton(item->joystick, i, buttonState); } /* store values to compare them in the next update */ item->analogButton[i] = gamepadState.analogButton[i]; item->digitalButton[i] = gamepadState.digitalButton[i]; } for(i = 0; i < item->naxes; i++) { if(item->axis[i] != gamepadState.axis[i]) { /* do we need to do conversion? */ SDL_PrivateJoystickAxis(item->joystick, i, (Sint16) (32767.*gamepadState.axis[i])); } /* store to compare in next update */ item->axis[i] = gamepadState.axis[i]; } item->timestamp = gamepadState.timestamp; } } } } /* Function to close a joystick after use */ static void EMSCRIPTEN_JoystickClose(SDL_Joystick * joystick) { SDL_joylist_item *item = (SDL_joylist_item *) joystick->hwdata; if (item) { item->joystick = NULL; } } static SDL_JoystickGUID EMSCRIPTEN_JoystickGetDeviceGUID(int device_index) { SDL_JoystickGUID guid; /* the GUID is just the first 16 chars of the name for now */ const char *name = EMSCRIPTEN_JoystickGetDeviceName(device_index); SDL_zero(guid); SDL_memcpy(&guid, name, SDL_min(sizeof(guid), SDL_strlen(name))); return guid; } static int EMSCRIPTEN_JoystickRumble(SDL_Joystick * joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { return SDL_Unsupported(); } static SDL_bool EMSCRIPTEN_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) { return SDL_FALSE; } SDL_JoystickDriver SDL_EMSCRIPTEN_JoystickDriver = { EMSCRIPTEN_JoystickInit, EMSCRIPTEN_JoystickGetCount, EMSCRIPTEN_JoystickDetect, EMSCRIPTEN_JoystickGetDeviceName, EMSCRIPTEN_JoystickGetDevicePlayerIndex, EMSCRIPTEN_JoystickSetDevicePlayerIndex, EMSCRIPTEN_JoystickGetDeviceGUID, EMSCRIPTEN_JoystickGetDeviceInstanceID, EMSCRIPTEN_JoystickOpen, EMSCRIPTEN_JoystickRumble, EMSCRIPTEN_JoystickUpdate, EMSCRIPTEN_JoystickClose, EMSCRIPTEN_JoystickQuit, EMSCRIPTEN_JoystickGetGamepadMapping }; #endif /* SDL_JOYSTICK_EMSCRIPTEN */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/emscripten/SDL_sysjoystick.c
C
apache-2.0
11,920
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_EMSCRIPTEN #include "../SDL_sysjoystick.h" #include <emscripten/html5.h> /* A linked list of available joysticks */ typedef struct SDL_joylist_item { int index; char *name; char *mapping; SDL_JoystickID device_instance; SDL_Joystick *joystick; int nbuttons; int naxes; double timestamp; double axis[64]; double analogButton[64]; EM_BOOL digitalButton[64]; struct SDL_joylist_item *next; } SDL_joylist_item; typedef SDL_joylist_item joystick_hwdata; #endif /* SDL_JOYSTICK_EMSCRIPTEN */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/emscripten/SDL_sysjoystick_c.h
C
apache-2.0
1,545
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_HAIKU /* This is the Haiku implementation of the SDL joystick API */ #include <support/String.h> #include <device/Joystick.h> extern "C" { #include "SDL_joystick.h" #include "../SDL_sysjoystick.h" #include "../SDL_joystick_c.h" /* The maximum number of joysticks we'll detect */ #define MAX_JOYSTICKS 16 /* A list of available joysticks */ static char *SDL_joyport[MAX_JOYSTICKS]; static char *SDL_joyname[MAX_JOYSTICKS]; /* The private structure used to keep track of a joystick */ struct joystick_hwdata { BJoystick *stick; uint8 *new_hats; int16 *new_axes; }; static int numjoysticks = 0; /* Function to scan the system for joysticks. * Joystick 0 should be the system default joystick. * It should return 0, or -1 on an unrecoverable fatal error. */ static int HAIKU_JoystickInit(void) { BJoystick joystick; int i; int32 nports; char name[B_OS_NAME_LENGTH]; /* Search for attached joysticks */ nports = joystick.CountDevices(); numjoysticks = 0; SDL_memset(SDL_joyport, 0, (sizeof SDL_joyport)); SDL_memset(SDL_joyname, 0, (sizeof SDL_joyname)); for (i = 0; (numjoysticks < MAX_JOYSTICKS) && (i < nports); ++i) { if (joystick.GetDeviceName(i, name) == B_OK) { if (joystick.Open(name) != B_ERROR) { BString stick_name; joystick.GetControllerName(&stick_name); SDL_joyport[numjoysticks] = SDL_strdup(name); SDL_joyname[numjoysticks] = SDL_CreateJoystickName(0, 0, NULL, stick_name.String()); numjoysticks++; joystick.Close(); } } } return (numjoysticks); } static int HAIKU_JoystickGetCount(void) { return numjoysticks; } static void HAIKU_JoystickDetect(void) { } /* Function to get the device-dependent name of a joystick */ static const char *HAIKU_JoystickGetDeviceName(int device_index) { return SDL_joyname[device_index]; } static int HAIKU_JoystickGetDevicePlayerIndex(int device_index) { return -1; } static void HAIKU_JoystickSetDevicePlayerIndex(int device_index, int player_index) { } /* Function to perform the mapping from device index to the instance id for this index */ static SDL_JoystickID HAIKU_JoystickGetDeviceInstanceID(int device_index) { return device_index; } static void HAIKU_JoystickClose(SDL_Joystick * joystick); /* Function to open a joystick for use. The joystick to open is specified by the device index. This should fill the nbuttons and naxes fields of the joystick structure. It returns 0, or -1 if there is an error. */ static int HAIKU_JoystickOpen(SDL_Joystick * joystick, int device_index) { BJoystick *stick; /* Create the joystick data structure */ joystick->instance_id = device_index; joystick->hwdata = (struct joystick_hwdata *) SDL_malloc(sizeof(*joystick->hwdata)); if (joystick->hwdata == NULL) { return SDL_OutOfMemory(); } SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata)); stick = new BJoystick; joystick->hwdata->stick = stick; /* Open the requested joystick for use */ if (stick->Open(SDL_joyport[device_index]) == B_ERROR) { HAIKU_JoystickClose(joystick); return SDL_SetError("Unable to open joystick"); } /* Set the joystick to calibrated mode */ stick->EnableCalibration(); /* Get the number of buttons, hats, and axes on the joystick */ joystick->nbuttons = stick->CountButtons(); joystick->naxes = stick->CountAxes(); joystick->nhats = stick->CountHats(); joystick->hwdata->new_axes = (int16 *) SDL_malloc(joystick->naxes * sizeof(int16)); joystick->hwdata->new_hats = (uint8 *) SDL_malloc(joystick->nhats * sizeof(uint8)); if (!joystick->hwdata->new_hats || !joystick->hwdata->new_axes) { HAIKU_JoystickClose(joystick); return SDL_OutOfMemory(); } /* We're done! */ return 0; } /* Function to update the state of a joystick - called as a device poll. * This function shouldn't update the joystick structure directly, * but instead should call SDL_PrivateJoystick*() to deliver events * and update joystick device state. */ static void HAIKU_JoystickUpdate(SDL_Joystick * joystick) { static const Uint8 hat_map[9] = { SDL_HAT_CENTERED, SDL_HAT_UP, SDL_HAT_RIGHTUP, SDL_HAT_RIGHT, SDL_HAT_RIGHTDOWN, SDL_HAT_DOWN, SDL_HAT_LEFTDOWN, SDL_HAT_LEFT, SDL_HAT_LEFTUP }; BJoystick *stick; int i; int16 *axes; uint8 *hats; uint32 buttons; /* Set up data pointers */ stick = joystick->hwdata->stick; axes = joystick->hwdata->new_axes; hats = joystick->hwdata->new_hats; /* Get the new joystick state */ stick->Update(); stick->GetAxisValues(axes); stick->GetHatValues(hats); buttons = stick->ButtonValues(); /* Generate axis motion events */ for (i = 0; i < joystick->naxes; ++i) { SDL_PrivateJoystickAxis(joystick, i, axes[i]); } /* Generate hat change events */ for (i = 0; i < joystick->nhats; ++i) { SDL_PrivateJoystickHat(joystick, i, hat_map[hats[i]]); } /* Generate button events */ for (i = 0; i < joystick->nbuttons; ++i) { SDL_PrivateJoystickButton(joystick, i, (buttons & 0x01)); buttons >>= 1; } } /* Function to close a joystick after use */ static void HAIKU_JoystickClose(SDL_Joystick * joystick) { if (joystick->hwdata) { joystick->hwdata->stick->Close(); delete joystick->hwdata->stick; SDL_free(joystick->hwdata->new_hats); SDL_free(joystick->hwdata->new_axes); SDL_free(joystick->hwdata); } } /* Function to perform any system-specific joystick related cleanup */ static void HAIKU_JoystickQuit(void) { int i; for (i = 0; i < numjoysticks; ++i) { SDL_free(SDL_joyport[i]); } SDL_joyport[0] = NULL; for (i = 0; i < numjoysticks; ++i) { SDL_free(SDL_joyname[i]); } SDL_joyname[0] = NULL; } static SDL_JoystickGUID HAIKU_JoystickGetDeviceGUID( int device_index ) { SDL_JoystickGUID guid; /* the GUID is just the first 16 chars of the name for now */ const char *name = HAIKU_JoystickGetDeviceName( device_index ); SDL_zero( guid ); SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) ); return guid; } static int HAIKU_JoystickRumble(SDL_Joystick * joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { return SDL_Unsupported(); } static SDL_bool HAIKU_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) { return SDL_FALSE; } SDL_JoystickDriver SDL_HAIKU_JoystickDriver = { HAIKU_JoystickInit, HAIKU_JoystickGetCount, HAIKU_JoystickDetect, HAIKU_JoystickGetDeviceName, HAIKU_JoystickGetDevicePlayerIndex, HAIKU_JoystickSetDevicePlayerIndex, HAIKU_JoystickGetDeviceGUID, HAIKU_JoystickGetDeviceInstanceID, HAIKU_JoystickOpen, HAIKU_JoystickRumble, HAIKU_JoystickUpdate, HAIKU_JoystickClose, HAIKU_JoystickQuit, HAIKU_JoystickGetGamepadMapping }; } // extern "C" #endif /* SDL_JOYSTICK_HAIKU */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/haiku/SDL_haikujoystick.cc
C++
apache-2.0
9,081
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_HIDAPI #include "SDL_hints.h" #include "SDL_events.h" #include "SDL_timer.h" #include "SDL_haptic.h" #include "SDL_joystick.h" #include "SDL_gamecontroller.h" #include "../../SDL_hints_c.h" #include "../SDL_sysjoystick.h" #include "SDL_hidapijoystick_c.h" #include "SDL_hidapi_rumble.h" #ifdef SDL_JOYSTICK_HIDAPI_GAMECUBE #define MAX_CONTROLLERS 4 typedef struct { SDL_JoystickID joysticks[MAX_CONTROLLERS]; Uint8 wireless[MAX_CONTROLLERS]; Uint8 min_axis[MAX_CONTROLLERS*SDL_CONTROLLER_AXIS_MAX]; Uint8 max_axis[MAX_CONTROLLERS*SDL_CONTROLLER_AXIS_MAX]; Uint8 rumbleAllowed[MAX_CONTROLLERS]; Uint8 rumble[1+MAX_CONTROLLERS]; /* Without this variable, hid_write starts to lag a TON */ SDL_bool rumbleUpdate; SDL_bool m_bUseButtonLabels; } SDL_DriverGameCube_Context; static SDL_bool HIDAPI_DriverGameCube_IsSupportedDevice(const char *name, SDL_GameControllerType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) { if (vendor_id == USB_VENDOR_NINTENDO && product_id == USB_PRODUCT_NINTENDO_GAMECUBE_ADAPTER) { /* Nintendo Co., Ltd. Wii U GameCube Controller Adapter */ return SDL_TRUE; } return SDL_FALSE; } static const char * HIDAPI_DriverGameCube_GetDeviceName(Uint16 vendor_id, Uint16 product_id) { return "Nintendo GameCube Controller"; } static void ResetAxisRange(SDL_DriverGameCube_Context *ctx, int joystick_index) { SDL_memset(&ctx->min_axis[joystick_index*SDL_CONTROLLER_AXIS_MAX], 128-88, SDL_CONTROLLER_AXIS_MAX); SDL_memset(&ctx->max_axis[joystick_index*SDL_CONTROLLER_AXIS_MAX], 128+88, SDL_CONTROLLER_AXIS_MAX); /* Trigger axes may have a higher resting value */ ctx->min_axis[joystick_index*SDL_CONTROLLER_AXIS_MAX+SDL_CONTROLLER_AXIS_TRIGGERLEFT] = 40; ctx->min_axis[joystick_index*SDL_CONTROLLER_AXIS_MAX+SDL_CONTROLLER_AXIS_TRIGGERRIGHT] = 40; } static float fsel(float fComparand, float fValGE, float fLT) { return fComparand >= 0 ? fValGE : fLT; } static float RemapVal(float val, float A, float B, float C, float D) { if (A == B) { return fsel(val - B , D , C); } if (val < A) { val = A; } if (val > B) { val = B; } return C + (D - C) * (val - A) / (B - A); } static void SDLCALL SDL_GameControllerButtonReportingHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) { SDL_DriverGameCube_Context *ctx = (SDL_DriverGameCube_Context *)userdata; ctx->m_bUseButtonLabels = SDL_GetStringBoolean(hint, SDL_TRUE); } static Uint8 RemapButton(SDL_DriverGameCube_Context *ctx, Uint8 button) { if (!ctx->m_bUseButtonLabels) { /* Use button positions */ switch (button) { case SDL_CONTROLLER_BUTTON_B: return SDL_CONTROLLER_BUTTON_X; case SDL_CONTROLLER_BUTTON_X: return SDL_CONTROLLER_BUTTON_B; default: break; } } return button; } static SDL_bool HIDAPI_DriverGameCube_InitDevice(SDL_HIDAPI_Device *device) { SDL_DriverGameCube_Context *ctx; Uint8 packet[37]; Uint8 *curSlot; Uint8 i; int size; Uint8 initMagic = 0x13; Uint8 rumbleMagic = 0x11; ctx = (SDL_DriverGameCube_Context *)SDL_calloc(1, sizeof(*ctx)); if (!ctx) { SDL_OutOfMemory(); return SDL_FALSE; } device->dev = hid_open_path(device->path, 0); if (!device->dev) { SDL_free(ctx); SDL_SetError("Couldn't open %s", device->path); return SDL_FALSE; } device->context = ctx; ctx->joysticks[0] = -1; ctx->joysticks[1] = -1; ctx->joysticks[2] = -1; ctx->joysticks[3] = -1; ctx->rumble[0] = rumbleMagic; /* This is all that's needed to initialize the device. Really! */ if (hid_write(device->dev, &initMagic, sizeof(initMagic)) != sizeof(initMagic)) { SDL_SetError("Couldn't initialize WUP-028"); goto error; } /* Wait for the adapter to initialize */ SDL_Delay(10); /* Add all the applicable joysticks */ while ((size = hid_read_timeout(device->dev, packet, sizeof(packet), 0)) > 0) { if (size < 37 || packet[0] != 0x21) { continue; /* Nothing to do yet...? */ } /* Go through all 4 slots */ curSlot = packet + 1; for (i = 0; i < MAX_CONTROLLERS; i += 1, curSlot += 9) { ctx->wireless[i] = (curSlot[0] & 0x20) != 0; /* Only allow rumble if the adapter's second USB cable is connected */ ctx->rumbleAllowed[i] = (curSlot[0] & 0x04) != 0 && !ctx->wireless[i]; if (curSlot[0] & 0x30) { /* 0x10 - Wired, 0x20 - Wireless */ if (ctx->joysticks[i] == -1) { ResetAxisRange(ctx, i); HIDAPI_JoystickConnected(device, &ctx->joysticks[i], SDL_FALSE); } } else { if (ctx->joysticks[i] != -1) { HIDAPI_JoystickDisconnected(device, ctx->joysticks[i], SDL_FALSE); ctx->joysticks[i] = -1; } continue; } } } SDL_AddHintCallback(SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS, SDL_GameControllerButtonReportingHintChanged, ctx); return SDL_TRUE; error: if (device->dev) { hid_close(device->dev); device->dev = NULL; } if (device->context) { SDL_free(device->context); device->context = NULL; } return SDL_FALSE; } static int HIDAPI_DriverGameCube_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) { SDL_DriverGameCube_Context *ctx = (SDL_DriverGameCube_Context *)device->context; Uint8 i; for (i = 0; i < 4; ++i) { if (instance_id == ctx->joysticks[i]) { return i; } } return -1; } static void HIDAPI_DriverGameCube_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) { } static SDL_bool HIDAPI_DriverGameCube_UpdateDevice(SDL_HIDAPI_Device *device) { SDL_DriverGameCube_Context *ctx = (SDL_DriverGameCube_Context *)device->context; SDL_Joystick *joystick; Uint8 packet[37]; Uint8 *curSlot; Uint8 i; Sint16 axis_value; int size; /* Read input packet */ while ((size = hid_read_timeout(device->dev, packet, sizeof(packet), 0)) > 0) { if (size < 37 || packet[0] != 0x21) { continue; /* Nothing to do right now...? */ } /* Go through all 4 slots */ curSlot = packet + 1; for (i = 0; i < MAX_CONTROLLERS; i += 1, curSlot += 9) { ctx->wireless[i] = (curSlot[0] & 0x20) != 0; /* Only allow rumble if the adapter's second USB cable is connected */ ctx->rumbleAllowed[i] = (curSlot[0] & 0x04) != 0 && !ctx->wireless[i]; if (curSlot[0] & 0x30) { /* 0x10 - Wired, 0x20 - Wireless */ if (ctx->joysticks[i] == -1) { ResetAxisRange(ctx, i); HIDAPI_JoystickConnected(device, &ctx->joysticks[i], SDL_FALSE); } joystick = SDL_JoystickFromInstanceID(ctx->joysticks[i]); /* Hasn't been opened yet, skip */ if (joystick == NULL) { continue; } } else { if (ctx->joysticks[i] != -1) { HIDAPI_JoystickDisconnected(device, ctx->joysticks[i], SDL_FALSE); ctx->joysticks[i] = -1; } continue; } #define READ_BUTTON(off, flag, button) \ SDL_PrivateJoystickButton( \ joystick, \ RemapButton(ctx, button), \ (curSlot[off] & flag) ? SDL_PRESSED : SDL_RELEASED \ ); READ_BUTTON(1, 0x01, 0) /* A */ READ_BUTTON(1, 0x04, 1) /* B */ READ_BUTTON(1, 0x02, 2) /* X */ READ_BUTTON(1, 0x08, 3) /* Y */ READ_BUTTON(1, 0x10, 4) /* DPAD_LEFT */ READ_BUTTON(1, 0x20, 5) /* DPAD_RIGHT */ READ_BUTTON(1, 0x40, 6) /* DPAD_DOWN */ READ_BUTTON(1, 0x80, 7) /* DPAD_UP */ READ_BUTTON(2, 0x01, 8) /* START */ READ_BUTTON(2, 0x02, 9) /* RIGHTSHOULDER */ /* These two buttons are for the bottoms of the analog triggers. * More than likely, you're going to want to read the axes instead! * -flibit */ READ_BUTTON(2, 0x04, 10) /* TRIGGERRIGHT */ READ_BUTTON(2, 0x08, 11) /* TRIGGERLEFT */ #undef READ_BUTTON #define READ_AXIS(off, axis) \ if (axis < SDL_CONTROLLER_AXIS_TRIGGERLEFT) \ if (curSlot[off] < ctx->min_axis[i*SDL_CONTROLLER_AXIS_MAX+axis]) ctx->min_axis[i*SDL_CONTROLLER_AXIS_MAX+axis] = curSlot[off]; \ if (curSlot[off] > ctx->max_axis[i*SDL_CONTROLLER_AXIS_MAX+axis]) ctx->max_axis[i*SDL_CONTROLLER_AXIS_MAX+axis] = curSlot[off]; \ axis_value = (Sint16)(RemapVal(curSlot[off], ctx->min_axis[i*SDL_CONTROLLER_AXIS_MAX+axis], ctx->max_axis[i*SDL_CONTROLLER_AXIS_MAX+axis], SDL_MIN_SINT16, SDL_MAX_SINT16)); \ SDL_PrivateJoystickAxis( \ joystick, \ axis, axis_value \ ); READ_AXIS(3, SDL_CONTROLLER_AXIS_LEFTX) READ_AXIS(4, SDL_CONTROLLER_AXIS_LEFTY) READ_AXIS(5, SDL_CONTROLLER_AXIS_RIGHTX) READ_AXIS(6, SDL_CONTROLLER_AXIS_RIGHTY) READ_AXIS(7, SDL_CONTROLLER_AXIS_TRIGGERLEFT) READ_AXIS(8, SDL_CONTROLLER_AXIS_TRIGGERRIGHT) #undef READ_AXIS } } /* Write rumble packet */ if (ctx->rumbleUpdate) { SDL_HIDAPI_SendRumble(device, ctx->rumble, sizeof(ctx->rumble)); ctx->rumbleUpdate = SDL_FALSE; } /* If we got here, nothing bad happened! */ return SDL_TRUE; } static SDL_bool HIDAPI_DriverGameCube_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) { SDL_DriverGameCube_Context *ctx = (SDL_DriverGameCube_Context *)device->context; Uint8 i; for (i = 0; i < MAX_CONTROLLERS; i += 1) { if (joystick->instance_id == ctx->joysticks[i]) { joystick->nbuttons = 12; joystick->naxes = SDL_CONTROLLER_AXIS_MAX; joystick->epowerlevel = ctx->wireless[i] ? SDL_JOYSTICK_POWER_UNKNOWN : SDL_JOYSTICK_POWER_WIRED; return SDL_TRUE; } } return SDL_FALSE; /* Should never get here! */ } static int HIDAPI_DriverGameCube_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { SDL_DriverGameCube_Context *ctx = (SDL_DriverGameCube_Context *)device->context; Uint8 i, val; for (i = 0; i < MAX_CONTROLLERS; i += 1) { if (joystick->instance_id == ctx->joysticks[i]) { if (ctx->wireless[i]) { return SDL_SetError("Ninteno GameCube WaveBird controllers do not support rumble"); } if (!ctx->rumbleAllowed[i]) { return SDL_SetError("Second USB cable for WUP-028 not connected"); } val = (low_frequency_rumble > 0 || high_frequency_rumble > 0); if (val != ctx->rumble[i + 1]) { ctx->rumble[i + 1] = val; ctx->rumbleUpdate = SDL_TRUE; } return 0; } } /* Should never get here! */ SDL_SetError("Couldn't find joystick"); return -1; } static void HIDAPI_DriverGameCube_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) { SDL_DriverGameCube_Context *ctx = (SDL_DriverGameCube_Context *)device->context; /* Stop rumble activity */ if (ctx->rumbleUpdate) { SDL_HIDAPI_SendRumble(device, ctx->rumble, sizeof(ctx->rumble)); ctx->rumbleUpdate = SDL_FALSE; } } static void HIDAPI_DriverGameCube_FreeDevice(SDL_HIDAPI_Device *device) { SDL_DriverGameCube_Context *ctx = (SDL_DriverGameCube_Context *)device->context; hid_close(device->dev); device->dev = NULL; SDL_DelHintCallback(SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS, SDL_GameControllerButtonReportingHintChanged, ctx); SDL_free(device->context); device->context = NULL; } SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverGameCube = { SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE, SDL_TRUE, HIDAPI_DriverGameCube_IsSupportedDevice, HIDAPI_DriverGameCube_GetDeviceName, HIDAPI_DriverGameCube_InitDevice, HIDAPI_DriverGameCube_GetDevicePlayerIndex, HIDAPI_DriverGameCube_SetDevicePlayerIndex, HIDAPI_DriverGameCube_UpdateDevice, HIDAPI_DriverGameCube_OpenJoystick, HIDAPI_DriverGameCube_RumbleJoystick, HIDAPI_DriverGameCube_CloseJoystick, HIDAPI_DriverGameCube_FreeDevice, NULL, }; #endif /* SDL_JOYSTICK_HIDAPI_GAMECUBE */ #endif /* SDL_JOYSTICK_HIDAPI */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/hidapi/SDL_hidapi_gamecube.c
C
apache-2.0
14,187
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* This driver supports both simplified reports and the extended input reports enabled by Steam. Code and logic contributed by Valve Corporation under the SDL zlib license. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_HIDAPI #include "SDL_hints.h" #include "SDL_events.h" #include "SDL_timer.h" #include "SDL_joystick.h" #include "SDL_gamecontroller.h" #include "../SDL_sysjoystick.h" #include "SDL_hidapijoystick_c.h" #include "SDL_hidapi_rumble.h" #ifdef SDL_JOYSTICK_HIDAPI_PS4 typedef enum { k_EPS4ReportIdUsbState = 1, k_EPS4ReportIdUsbEffects = 5, k_EPS4ReportIdBluetoothState = 17, k_EPS4ReportIdBluetoothEffects = 17, k_EPS4ReportIdDisconnectMessage = 226, } EPS4ReportId; typedef enum { k_ePS4FeatureReportIdGyroCalibration_USB = 0x02, k_ePS4FeatureReportIdGyroCalibration_BT = 0x05, k_ePS4FeatureReportIdSerialNumber = 0x12, } EPS4FeatureReportID; typedef struct { Uint8 ucLeftJoystickX; Uint8 ucLeftJoystickY; Uint8 ucRightJoystickX; Uint8 ucRightJoystickY; Uint8 rgucButtonsHatAndCounter[ 3 ]; Uint8 ucTriggerLeft; Uint8 ucTriggerRight; Uint8 _rgucPad0[ 3 ]; Sint16 sGyroX; Sint16 sGyroY; Sint16 sGyroZ; Sint16 sAccelX; Sint16 sAccelY; Sint16 sAccelZ; Uint8 _rgucPad1[ 5 ]; Uint8 ucBatteryLevel; Uint8 _rgucPad2[ 4 ]; Uint8 ucTrackpadCounter1; Uint8 rgucTrackpadData1[ 3 ]; Uint8 ucTrackpadCounter2; Uint8 rgucTrackpadData2[ 3 ]; } PS4StatePacket_t; typedef struct { Uint8 ucRumbleRight; Uint8 ucRumbleLeft; Uint8 ucLedRed; Uint8 ucLedGreen; Uint8 ucLedBlue; Uint8 ucLedDelayOn; Uint8 ucLedDelayOff; Uint8 _rgucPad0[ 8 ]; Uint8 ucVolumeLeft; Uint8 ucVolumeRight; Uint8 ucVolumeMic; Uint8 ucVolumeSpeaker; } DS4EffectsState_t; typedef struct { SDL_bool is_dongle; SDL_bool is_bluetooth; SDL_bool audio_supported; SDL_bool rumble_supported; int player_index; Uint8 volume; Uint32 last_volume_check; PS4StatePacket_t last_state; } SDL_DriverPS4_Context; /* Public domain CRC implementation adapted from: http://home.thep.lu.se/~bjorn/crc/crc32_simple.c */ static Uint32 crc32_for_byte(Uint32 r) { int i; for(i = 0; i < 8; ++i) { r = (r & 1? 0: (Uint32)0xEDB88320L) ^ r >> 1; } return r ^ (Uint32)0xFF000000L; } static Uint32 crc32(Uint32 crc, const void *data, int count) { int i; for(i = 0; i < count; ++i) { crc = crc32_for_byte((Uint8)crc ^ ((const Uint8*)data)[i]) ^ crc >> 8; } return crc; } static SDL_bool HIDAPI_DriverPS4_IsSupportedDevice(const char *name, SDL_GameControllerType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) { return (type == SDL_CONTROLLER_TYPE_PS4); } static const char * HIDAPI_DriverPS4_GetDeviceName(Uint16 vendor_id, Uint16 product_id) { if (vendor_id == USB_VENDOR_SONY) { return "PS4 Controller"; } return NULL; } static SDL_bool ReadFeatureReport(hid_device *dev, Uint8 report_id, Uint8 *data, size_t size) { Uint8 report[USB_PACKET_LENGTH + 1]; SDL_memset(report, 0, sizeof(report)); report[0] = report_id; if (hid_get_feature_report(dev, report, sizeof(report)) < 0) { return SDL_FALSE; } SDL_memcpy(data, report, SDL_min(size, sizeof(report))); return SDL_TRUE; } static SDL_bool CheckUSBConnected(hid_device *dev) { int i; Uint8 data[16]; /* This will fail if we're on Bluetooth */ if (ReadFeatureReport(dev, k_ePS4FeatureReportIdSerialNumber, data, sizeof(data))) { for (i = 0; i < sizeof(data); ++i) { if (data[i] != 0x00) { return SDL_TRUE; } } /* Maybe the dongle without a connected controller? */ } return SDL_FALSE; } static SDL_bool HIDAPI_DriverPS4_CanRumble(Uint16 vendor_id, Uint16 product_id) { /* The Razer Panthera fight stick hangs when trying to rumble */ if (vendor_id == USB_VENDOR_RAZER && (product_id == USB_PRODUCT_RAZER_PANTHERA || product_id == USB_PRODUCT_RAZER_PANTHERA_EVO)) { return SDL_FALSE; } return SDL_TRUE; } static void SetLedsForPlayerIndex(DS4EffectsState_t *effects, int player_index) { /* This list is the same as what hid-sony.c uses in the Linux kernel. The first 4 values correspond to what the PS4 assigns. */ static const Uint8 colors[7][3] = { { 0x00, 0x00, 0x40 }, /* Blue */ { 0x40, 0x00, 0x00 }, /* Red */ { 0x00, 0x40, 0x00 }, /* Green */ { 0x20, 0x00, 0x20 }, /* Pink */ { 0x02, 0x01, 0x00 }, /* Orange */ { 0x00, 0x01, 0x01 }, /* Teal */ { 0x01, 0x01, 0x01 } /* White */ }; if (player_index >= 0) { player_index %= SDL_arraysize(colors); } else { player_index = 0; } effects->ucLedRed = colors[player_index][0]; effects->ucLedGreen = colors[player_index][1]; effects->ucLedBlue = colors[player_index][2]; } static SDL_bool HIDAPI_DriverPS4_InitDevice(SDL_HIDAPI_Device *device) { return HIDAPI_JoystickConnected(device, NULL, SDL_FALSE); } static int HIDAPI_DriverPS4_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) { return -1; } static int HIDAPI_DriverPS4_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble); static void HIDAPI_DriverPS4_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) { SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context; if (!ctx) { return; } ctx->player_index = player_index; /* This will set the new LED state based on the new player index */ HIDAPI_DriverPS4_RumbleJoystick(device, SDL_JoystickFromInstanceID(instance_id), 0, 0); } static SDL_bool HIDAPI_DriverPS4_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) { SDL_DriverPS4_Context *ctx; ctx = (SDL_DriverPS4_Context *)SDL_calloc(1, sizeof(*ctx)); if (!ctx) { SDL_OutOfMemory(); return SDL_FALSE; } device->dev = hid_open_path(device->path, 0); if (!device->dev) { SDL_free(ctx); SDL_SetError("Couldn't open %s", device->path); return SDL_FALSE; } device->context = ctx; /* Check for type of connection */ ctx->is_dongle = (device->vendor_id == USB_VENDOR_SONY && device->product_id == USB_PRODUCT_SONY_DS4_DONGLE); if (ctx->is_dongle) { ctx->is_bluetooth = SDL_FALSE; } else if (device->vendor_id == USB_VENDOR_SONY) { ctx->is_bluetooth = !CheckUSBConnected(device->dev); } else { /* Third party controllers appear to all be wired */ ctx->is_bluetooth = SDL_FALSE; } #ifdef DEBUG_PS4 SDL_Log("PS4 dongle = %s, bluetooth = %s\n", ctx->is_dongle ? "TRUE" : "FALSE", ctx->is_bluetooth ? "TRUE" : "FALSE"); #endif /* Check to see if audio is supported */ if (device->vendor_id == USB_VENDOR_SONY && (device->product_id == USB_PRODUCT_SONY_DS4_SLIM || device->product_id == USB_PRODUCT_SONY_DS4_DONGLE)) { ctx->audio_supported = SDL_TRUE; } if (HIDAPI_DriverPS4_CanRumble(device->vendor_id, device->product_id)) { if (ctx->is_bluetooth) { ctx->rumble_supported = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE, SDL_FALSE); } else { ctx->rumble_supported = SDL_TRUE; } } /* Initialize player index (needed for setting LEDs) */ ctx->player_index = SDL_JoystickGetPlayerIndex(joystick); /* Initialize LED and effect state */ HIDAPI_DriverPS4_RumbleJoystick(device, joystick, 0, 0); /* Initialize the joystick capabilities */ joystick->nbuttons = 16; joystick->naxes = SDL_CONTROLLER_AXIS_MAX; joystick->epowerlevel = SDL_JOYSTICK_POWER_WIRED; return SDL_TRUE; } static int HIDAPI_DriverPS4_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context; DS4EffectsState_t *effects; Uint8 data[78]; int report_size, offset; if (!ctx->rumble_supported) { return SDL_Unsupported(); } /* In order to send rumble, we have to send a complete effect packet */ SDL_memset(data, 0, sizeof(data)); if (ctx->is_bluetooth) { data[0] = k_EPS4ReportIdBluetoothEffects; data[1] = 0xC0 | 0x04; /* Magic value HID + CRC, also sets interval to 4ms for samples */ data[3] = 0x03; /* 0x1 is rumble, 0x2 is lightbar, 0x4 is the blink interval */ report_size = 78; offset = 6; } else { data[0] = k_EPS4ReportIdUsbEffects; data[1] = 0x07; /* Magic value */ report_size = 32; offset = 4; } effects = (DS4EffectsState_t *)&data[offset]; effects->ucRumbleLeft = (low_frequency_rumble >> 8); effects->ucRumbleRight = (high_frequency_rumble >> 8); /* Populate the LED state with the appropriate color from our lookup table */ SetLedsForPlayerIndex(effects, ctx->player_index); if (ctx->is_bluetooth) { /* Bluetooth reports need a CRC at the end of the packet (at least on Linux) */ Uint8 ubHdr = 0xA2; /* hidp header is part of the CRC calculation */ Uint32 unCRC; unCRC = crc32(0, &ubHdr, 1); unCRC = crc32(unCRC, data, (Uint32)(report_size - sizeof(unCRC))); SDL_memcpy(&data[report_size - sizeof(unCRC)], &unCRC, sizeof(unCRC)); } if (SDL_HIDAPI_SendRumble(device, data, report_size) != report_size) { return SDL_SetError("Couldn't send rumble packet"); } return 0; } static void HIDAPI_DriverPS4_HandleStatePacket(SDL_Joystick *joystick, hid_device *dev, SDL_DriverPS4_Context *ctx, PS4StatePacket_t *packet) { Sint16 axis; if (ctx->last_state.rgucButtonsHatAndCounter[0] != packet->rgucButtonsHatAndCounter[0]) { { Uint8 data = (packet->rgucButtonsHatAndCounter[0] >> 4); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_X, (data & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_A, (data & 0x02) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_B, (data & 0x04) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_Y, (data & 0x08) ? SDL_PRESSED : SDL_RELEASED); } { Uint8 data = (packet->rgucButtonsHatAndCounter[0] & 0x0F); SDL_bool dpad_up = SDL_FALSE; SDL_bool dpad_down = SDL_FALSE; SDL_bool dpad_left = SDL_FALSE; SDL_bool dpad_right = SDL_FALSE; switch (data) { case 0: dpad_up = SDL_TRUE; break; case 1: dpad_up = SDL_TRUE; dpad_right = SDL_TRUE; break; case 2: dpad_right = SDL_TRUE; break; case 3: dpad_right = SDL_TRUE; dpad_down = SDL_TRUE; break; case 4: dpad_down = SDL_TRUE; break; case 5: dpad_left = SDL_TRUE; dpad_down = SDL_TRUE; break; case 6: dpad_left = SDL_TRUE; break; case 7: dpad_up = SDL_TRUE; dpad_left = SDL_TRUE; break; default: break; } SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_DOWN, dpad_down); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_UP, dpad_up); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_RIGHT, dpad_right); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_LEFT, dpad_left); } } if (ctx->last_state.rgucButtonsHatAndCounter[1] != packet->rgucButtonsHatAndCounter[1]) { Uint8 data = packet->rgucButtonsHatAndCounter[1]; SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSHOULDER, (data & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, (data & 0x02) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_BACK, (data & 0x10) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_START, (data & 0x20) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSTICK, (data & 0x40) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSTICK, (data & 0x80) ? SDL_PRESSED : SDL_RELEASED); } /* Some fightsticks, ex: Victrix FS Pro will only this these digital trigger bits and not the analog values so this needs to run whenever the trigger is evaluated */ if ((packet->rgucButtonsHatAndCounter[1] & 0x0C) != 0) { Uint8 data = packet->rgucButtonsHatAndCounter[1]; packet->ucTriggerLeft = (data & 0x04) && packet->ucTriggerLeft == 0 ? 255 : packet->ucTriggerLeft; packet->ucTriggerRight = (data & 0x08) && packet->ucTriggerRight == 0 ? 255 : packet->ucTriggerRight; } if (ctx->last_state.rgucButtonsHatAndCounter[2] != packet->rgucButtonsHatAndCounter[2]) { Uint8 data = (packet->rgucButtonsHatAndCounter[2] & 0x03); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, (data & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, 15, (data & 0x02) ? SDL_PRESSED : SDL_RELEASED); } axis = ((int)packet->ucTriggerLeft * 257) - 32768; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, axis); axis = ((int)packet->ucTriggerRight * 257) - 32768; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, axis); axis = ((int)packet->ucLeftJoystickX * 257) - 32768; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTX, axis); axis = ((int)packet->ucLeftJoystickY * 257) - 32768; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTY, axis); axis = ((int)packet->ucRightJoystickX * 257) - 32768; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTX, axis); axis = ((int)packet->ucRightJoystickY * 257) - 32768; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTY, axis); if (packet->ucBatteryLevel & 0x10) { joystick->epowerlevel = SDL_JOYSTICK_POWER_WIRED; } else { /* Battery level ranges from 0 to 10 */ int level = (packet->ucBatteryLevel & 0xF); if (level == 0) { joystick->epowerlevel = SDL_JOYSTICK_POWER_EMPTY; } else if (level <= 2) { joystick->epowerlevel = SDL_JOYSTICK_POWER_LOW; } else if (level <= 7) { joystick->epowerlevel = SDL_JOYSTICK_POWER_MEDIUM; } else { joystick->epowerlevel = SDL_JOYSTICK_POWER_FULL; } } SDL_memcpy(&ctx->last_state, packet, sizeof(ctx->last_state)); } static SDL_bool HIDAPI_DriverPS4_UpdateDevice(SDL_HIDAPI_Device *device) { SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context; SDL_Joystick *joystick = NULL; Uint8 data[USB_PACKET_LENGTH]; int size; if (device->num_joysticks > 0) { joystick = SDL_JoystickFromInstanceID(device->joysticks[0]); } if (!joystick) { return SDL_FALSE; } while ((size = hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) { switch (data[0]) { case k_EPS4ReportIdUsbState: HIDAPI_DriverPS4_HandleStatePacket(joystick, device->dev, ctx, (PS4StatePacket_t *)&data[1]); break; case k_EPS4ReportIdBluetoothState: /* Bluetooth state packets have two additional bytes at the beginning */ HIDAPI_DriverPS4_HandleStatePacket(joystick, device->dev, ctx, (PS4StatePacket_t *)&data[3]); break; default: #ifdef DEBUG_JOYSTICK SDL_Log("Unknown PS4 packet: 0x%.2x\n", data[0]); #endif break; } } if (size < 0) { /* Read error, device is disconnected */ HIDAPI_JoystickDisconnected(device, joystick->instance_id, SDL_FALSE); } return (size >= 0); } static void HIDAPI_DriverPS4_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) { hid_close(device->dev); device->dev = NULL; SDL_free(device->context); device->context = NULL; } static void HIDAPI_DriverPS4_FreeDevice(SDL_HIDAPI_Device *device) { } SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverPS4 = { SDL_HINT_JOYSTICK_HIDAPI_PS4, SDL_TRUE, HIDAPI_DriverPS4_IsSupportedDevice, HIDAPI_DriverPS4_GetDeviceName, HIDAPI_DriverPS4_InitDevice, HIDAPI_DriverPS4_GetDevicePlayerIndex, HIDAPI_DriverPS4_SetDevicePlayerIndex, HIDAPI_DriverPS4_UpdateDevice, HIDAPI_DriverPS4_OpenJoystick, HIDAPI_DriverPS4_RumbleJoystick, HIDAPI_DriverPS4_CloseJoystick, HIDAPI_DriverPS4_FreeDevice, NULL }; #endif /* SDL_JOYSTICK_HIDAPI_PS4 */ #endif /* SDL_JOYSTICK_HIDAPI */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/hidapi/SDL_hidapi_ps4.c
C
apache-2.0
18,477
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_HIDAPI /* Handle rumble on a separate thread so it doesn't block the application */ #include "SDL_assert.h" #include "SDL_thread.h" #include "SDL_hidapijoystick_c.h" #include "SDL_hidapi_rumble.h" #include "../../thread/SDL_systhread.h" typedef struct SDL_HIDAPI_RumbleRequest { SDL_HIDAPI_Device *device; Uint8 data[2*USB_PACKET_LENGTH]; /* need enough space for the biggest report: dualshock4 is 78 bytes */ int size; struct SDL_HIDAPI_RumbleRequest *prev; } SDL_HIDAPI_RumbleRequest; typedef struct SDL_HIDAPI_RumbleContext { SDL_atomic_t initialized; SDL_atomic_t running; SDL_Thread *thread; SDL_mutex *lock; SDL_sem *request_sem; SDL_HIDAPI_RumbleRequest *requests_head; SDL_HIDAPI_RumbleRequest *requests_tail; } SDL_HIDAPI_RumbleContext; static SDL_HIDAPI_RumbleContext rumble_context; static int SDL_HIDAPI_RumbleThread(void *data) { SDL_HIDAPI_RumbleContext *ctx = (SDL_HIDAPI_RumbleContext *)data; SDL_SetThreadPriority(SDL_THREAD_PRIORITY_HIGH); while (SDL_AtomicGet(&ctx->running)) { SDL_HIDAPI_RumbleRequest *request = NULL; SDL_SemWait(ctx->request_sem); SDL_LockMutex(ctx->lock); request = ctx->requests_tail; if (request) { if (request == ctx->requests_head) { ctx->requests_head = NULL; } ctx->requests_tail = request->prev; } SDL_UnlockMutex(ctx->lock); if (request) { SDL_LockMutex(request->device->dev_lock); if (request->device->dev) { hid_write( request->device->dev, request->data, request->size ); } SDL_UnlockMutex(request->device->dev_lock); (void)SDL_AtomicDecRef(&request->device->rumble_pending); SDL_free(request); } } return 0; } static void SDL_HIDAPI_StopRumbleThread(SDL_HIDAPI_RumbleContext *ctx) { SDL_AtomicSet(&ctx->running, SDL_FALSE); if (ctx->thread) { int result; SDL_SemPost(ctx->request_sem); SDL_WaitThread(ctx->thread, &result); ctx->thread = NULL; } /* This should always be called with an empty queue */ SDL_assert(!ctx->requests_head); SDL_assert(!ctx->requests_tail); if (ctx->request_sem) { SDL_DestroySemaphore(ctx->request_sem); ctx->request_sem = NULL; } if (ctx->lock) { SDL_DestroyMutex(ctx->lock); ctx->lock = NULL; } SDL_AtomicSet(&ctx->initialized, SDL_FALSE); } static int SDL_HIDAPI_StartRumbleThread(SDL_HIDAPI_RumbleContext *ctx) { ctx->lock = SDL_CreateMutex(); if (!ctx->lock) { SDL_HIDAPI_StopRumbleThread(ctx); return -1; } ctx->request_sem = SDL_CreateSemaphore(0); if (!ctx->request_sem) { SDL_HIDAPI_StopRumbleThread(ctx); return -1; } SDL_AtomicSet(&ctx->running, SDL_TRUE); ctx->thread = SDL_CreateThreadInternal(SDL_HIDAPI_RumbleThread, "HIDAPI Rumble", 0, ctx); if (!ctx->thread) { SDL_HIDAPI_StopRumbleThread(ctx); return -1; } return 0; } int SDL_HIDAPI_LockRumble(void) { SDL_HIDAPI_RumbleContext *ctx = &rumble_context; if (SDL_AtomicCAS(&ctx->initialized, SDL_FALSE, SDL_TRUE)) { if (SDL_HIDAPI_StartRumbleThread(ctx) < 0) { return -1; } } return SDL_LockMutex(ctx->lock); } SDL_bool SDL_HIDAPI_GetPendingRumbleLocked(SDL_HIDAPI_Device *device, Uint8 **data, int **size, int *maximum_size) { SDL_HIDAPI_RumbleContext *ctx = &rumble_context; SDL_HIDAPI_RumbleRequest *request; for (request = ctx->requests_tail; request; request = request->prev) { if (request->device == device) { *data = request->data; *size = &request->size; *maximum_size = sizeof(request->data); return SDL_TRUE; } } return SDL_FALSE; } int SDL_HIDAPI_SendRumbleAndUnlock(SDL_HIDAPI_Device *device, const Uint8 *data, int size) { SDL_HIDAPI_RumbleContext *ctx = &rumble_context; SDL_HIDAPI_RumbleRequest *request; if (size > sizeof(request->data)) { SDL_HIDAPI_UnlockRumble(); return SDL_SetError("Couldn't send rumble, size %d is greater than %d", size, (int)sizeof(request->data)); } request = (SDL_HIDAPI_RumbleRequest *)SDL_calloc(1, sizeof(*request)); if (!request) { SDL_HIDAPI_UnlockRumble(); return SDL_OutOfMemory(); } request->device = device; SDL_memcpy(request->data, data, size); request->size = size; SDL_AtomicIncRef(&device->rumble_pending); if (ctx->requests_head) { ctx->requests_head->prev = request; } else { ctx->requests_tail = request; } ctx->requests_head = request; /* Make sure we unlock before posting the semaphore so the rumble thread can run immediately */ SDL_HIDAPI_UnlockRumble(); SDL_SemPost(ctx->request_sem); return size; } void SDL_HIDAPI_UnlockRumble(void) { SDL_HIDAPI_RumbleContext *ctx = &rumble_context; SDL_UnlockMutex(ctx->lock); } int SDL_HIDAPI_SendRumble(SDL_HIDAPI_Device *device, const Uint8 *data, int size) { Uint8 *pending_data; int *pending_size; int maximum_size; if (SDL_HIDAPI_LockRumble() < 0) { return -1; } /* check if there is a pending request for the device and update it */ if (SDL_HIDAPI_GetPendingRumbleLocked(device, &pending_data, &pending_size, &maximum_size)) { if (size > maximum_size) { SDL_HIDAPI_UnlockRumble(); return SDL_SetError("Couldn't send rumble, size %d is greater than %d", size, maximum_size); } SDL_memcpy(pending_data, data, size); *pending_size = size; SDL_HIDAPI_UnlockRumble(); return size; } return SDL_HIDAPI_SendRumbleAndUnlock(device, data, size); } void SDL_HIDAPI_QuitRumble(void) { SDL_HIDAPI_RumbleContext *ctx = &rumble_context; if (SDL_AtomicGet(&ctx->running)) { SDL_HIDAPI_StopRumbleThread(ctx); } } #endif /* SDL_JOYSTICK_HIDAPI */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/hidapi/SDL_hidapi_rumble.c
C
apache-2.0
7,134
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_HIDAPI /* Handle rumble on a separate thread so it doesn't block the application */ /* Advanced API */ int SDL_HIDAPI_LockRumble(void); SDL_bool SDL_HIDAPI_GetPendingRumbleLocked(SDL_HIDAPI_Device *device, Uint8 **data, int **size, int *maximum_size); int SDL_HIDAPI_SendRumbleAndUnlock(SDL_HIDAPI_Device *device, const Uint8 *data, int size); void SDL_HIDAPI_UnlockRumble(void); /* Simple API, will replace any pending rumble with the new data */ int SDL_HIDAPI_SendRumble(SDL_HIDAPI_Device *device, const Uint8 *data, int size); void SDL_HIDAPI_QuitRumble(void); #endif /* SDL_JOYSTICK_HIDAPI */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/hidapi/SDL_hidapi_rumble.h
C
apache-2.0
1,630
/* Simple DirectMedia Layer Copyright (C) 1997-2018 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_HIDAPI #include "SDL_hints.h" #include "SDL_events.h" #include "SDL_timer.h" #include "SDL_joystick.h" #include "SDL_gamecontroller.h" #include "../SDL_sysjoystick.h" #include "SDL_hidapijoystick_c.h" #ifdef SDL_JOYSTICK_HIDAPI_STEAM /*****************************************************************************************************/ #include <stdint.h> typedef enum { false, true } bool; typedef uint32_t uint32; typedef uint64_t uint64; #include "steam/controller_constants.h" #include "steam/controller_structs.h" typedef struct SteamControllerStateInternal_t { // Controller Type for this Controller State uint32 eControllerType; // If packet num matches that on your prior call, then the controller state hasn't been changed since // your last call and there is no need to process it uint32 unPacketNum; // bit flags for each of the buttons uint64 ulButtons; // Left pad coordinates short sLeftPadX; short sLeftPadY; // Right pad coordinates short sRightPadX; short sRightPadY; // Center pad coordinates short sCenterPadX; short sCenterPadY; // Left analog stick coordinates short sLeftStickX; short sLeftStickY; // Right analog stick coordinates short sRightStickX; short sRightStickY; unsigned short sTriggerL; unsigned short sTriggerR; short sAccelX; short sAccelY; short sAccelZ; short sGyroX; short sGyroY; short sGyroZ; float sGyroQuatW; float sGyroQuatX; float sGyroQuatY; float sGyroQuatZ; short sGyroSteeringAngle; unsigned short sBatteryLevel; // Pressure sensor data. unsigned short sPressurePadLeft; unsigned short sPressurePadRight; unsigned short sPressureBumperLeft; unsigned short sPressureBumperRight; // Internal state data short sPrevLeftPad[2]; short sPrevLeftStick[2]; } SteamControllerStateInternal_t; /* Defines for ulButtons in SteamControllerStateInternal_t */ #define STEAM_RIGHT_TRIGGER_MASK 0x00000001 #define STEAM_LEFT_TRIGGER_MASK 0x00000002 #define STEAM_RIGHT_BUMPER_MASK 0x00000004 #define STEAM_LEFT_BUMPER_MASK 0x00000008 #define STEAM_BUTTON_0_MASK 0x00000010 /* Y */ #define STEAM_BUTTON_1_MASK 0x00000020 /* B */ #define STEAM_BUTTON_2_MASK 0x00000040 /* X */ #define STEAM_BUTTON_3_MASK 0x00000080 /* A */ #define STEAM_TOUCH_0_MASK 0x00000100 /* DPAD UP */ #define STEAM_TOUCH_1_MASK 0x00000200 /* DPAD RIGHT */ #define STEAM_TOUCH_2_MASK 0x00000400 /* DPAD LEFT */ #define STEAM_TOUCH_3_MASK 0x00000800 /* DPAD DOWN */ #define STEAM_BUTTON_MENU_MASK 0x00001000 /* SELECT */ #define STEAM_BUTTON_STEAM_MASK 0x00002000 /* GUIDE */ #define STEAM_BUTTON_ESCAPE_MASK 0x00004000 /* START */ #define STEAM_BUTTON_BACK_LEFT_MASK 0x00008000 #define STEAM_BUTTON_BACK_RIGHT_MASK 0x00010000 #define STEAM_BUTTON_LEFTPAD_CLICKED_MASK 0x00020000 #define STEAM_BUTTON_RIGHTPAD_CLICKED_MASK 0x00040000 #define STEAM_LEFTPAD_FINGERDOWN_MASK 0x00080000 #define STEAM_RIGHTPAD_FINGERDOWN_MASK 0x00100000 #define STEAM_JOYSTICK_BUTTON_MASK 0x00400000 #define STEAM_LEFTPAD_AND_JOYSTICK_MASK 0x00800000 // Look for report version 0x0001, type WIRELESS (3), length >= 1 byte #define D0G_IS_VALID_WIRELESS_EVENT(data, len) ((len) >= 5 && (data)[0] == 1 && (data)[1] == 0 && (data)[2] == 3 && (data)[3] >= 1) #define D0G_GET_WIRELESS_EVENT_TYPE(data) ((data)[4]) #define D0G_WIRELESS_DISCONNECTED 1 #define D0G_WIRELESS_ESTABLISHED 2 #define D0G_WIRELESS_NEWLYPAIRED 3 #define D0G_IS_WIRELESS_DISCONNECT(data, len) ( D0G_IS_VALID_WIRELESS_EVENT(data,len) && D0G_GET_WIRELESS_EVENT_TYPE(data) == D0G_WIRELESS_DISCONNECTED ) #define MAX_REPORT_SEGMENT_PAYLOAD_SIZE 18 /* * SteamControllerPacketAssembler has to be used when reading output repots from controllers. */ typedef struct { uint8_t uBuffer[ MAX_REPORT_SEGMENT_PAYLOAD_SIZE * 8 + 1 ]; int nExpectedSegmentNumber; bool bIsBle; } SteamControllerPacketAssembler; #undef clamp #define clamp(val, min, max) (((val) > (max)) ? (max) : (((val) < (min)) ? (min) : (val))) #undef offsetof #define offsetof(s,m) (size_t)&(((s *)0)->m) #ifdef DEBUG_STEAM_CONTROLLER #define DPRINTF(format, ...) printf(format, ##__VA_ARGS__) #define HEXDUMP(ptr, len) hexdump(ptr, len) #else #define DPRINTF(format, ...) #define HEXDUMP(ptr, len) #endif #define printf SDL_Log #define MAX_REPORT_SEGMENT_SIZE ( MAX_REPORT_SEGMENT_PAYLOAD_SIZE + 2 ) #define CALC_REPORT_SEGMENT_NUM(index) ( ( index / MAX_REPORT_SEGMENT_PAYLOAD_SIZE ) & 0x07 ) #define REPORT_SEGMENT_DATA_FLAG 0x80 #define REPORT_SEGMENT_LAST_FLAG 0x40 #define BLE_REPORT_NUMBER 0x03 #define STEAMCONTROLLER_TRIGGER_MAX_ANALOG 26000 // Enable mouse mode when using the Steam Controller locally #undef ENABLE_MOUSE_MODE // Wireless firmware quirk: the firmware intentionally signals "failure" when performing // SET_FEATURE / GET_FEATURE when it actually means "pending radio round-trip". The only // way to make SET_FEATURE / GET_FEATURE work is to loop several times with a sleep. If // it takes more than 50ms to get the response for SET_FEATURE / GET_FEATURE, we assume // that the controller has failed. #define RADIO_WORKAROUND_SLEEP_ATTEMPTS 50 #define RADIO_WORKAROUND_SLEEP_DURATION_US 500 // This was defined by experimentation. 2000 seemed to work but to give that extra bit of margin, set to 3ms. #define CONTROLLER_CONFIGURATION_DELAY_US 3000 static uint8_t GetSegmentHeader( int nSegmentNumber, bool bLastPacket ) { uint8_t header = REPORT_SEGMENT_DATA_FLAG; header |= nSegmentNumber; if ( bLastPacket ) header |= REPORT_SEGMENT_LAST_FLAG; return header; } static void hexdump( const uint8_t *ptr, int len ) { int i; for ( i = 0; i < len ; ++i ) printf("%02x ", ptr[i]); printf("\n"); } static void ResetSteamControllerPacketAssembler( SteamControllerPacketAssembler *pAssembler ) { memset( pAssembler->uBuffer, 0, sizeof( pAssembler->uBuffer ) ); pAssembler->nExpectedSegmentNumber = 0; } static void InitializeSteamControllerPacketAssembler( SteamControllerPacketAssembler *pAssembler ) { /* We only support BLE devices right now */ pAssembler->bIsBle = true; ResetSteamControllerPacketAssembler( pAssembler ); } // Returns: // <0 on error // 0 on not ready // Complete packet size on completion static int WriteSegmentToSteamControllerPacketAssembler( SteamControllerPacketAssembler *pAssembler, const uint8_t *pSegment, int nSegmentLength ) { if ( pAssembler->bIsBle ) { HEXDUMP( pSegment, nSegmentLength ); if ( pSegment[ 0 ] != BLE_REPORT_NUMBER ) { // We may get keyboard/mouse input events until controller stops sending them return 0; } if ( nSegmentLength != MAX_REPORT_SEGMENT_SIZE ) { printf( "Bad segment size! %d\n", (int)nSegmentLength ); hexdump( pSegment, nSegmentLength ); ResetSteamControllerPacketAssembler( pAssembler ); return -1; } uint8_t uSegmentHeader = pSegment[ 1 ]; DPRINTF("GOT PACKET HEADER = 0x%x\n", uSegmentHeader); if ( ( uSegmentHeader & REPORT_SEGMENT_DATA_FLAG ) == 0 ) { // We get empty segments, just ignore them return 0; } int nSegmentNumber = uSegmentHeader & 0x07; if ( nSegmentNumber != pAssembler->nExpectedSegmentNumber ) { ResetSteamControllerPacketAssembler( pAssembler ); if ( nSegmentNumber ) { // This happens occasionally DPRINTF("Bad segment number, got %d, expected %d\n", nSegmentNumber, pAssembler->nExpectedSegmentNumber ); return -1; } } memcpy( pAssembler->uBuffer + nSegmentNumber * MAX_REPORT_SEGMENT_PAYLOAD_SIZE, pSegment + 2, // ignore header and report number MAX_REPORT_SEGMENT_PAYLOAD_SIZE ); if ( uSegmentHeader & REPORT_SEGMENT_LAST_FLAG ) { pAssembler->nExpectedSegmentNumber = 0; return ( nSegmentNumber + 1 ) * MAX_REPORT_SEGMENT_PAYLOAD_SIZE; } pAssembler->nExpectedSegmentNumber++; } else { // Just pass through memcpy( pAssembler->uBuffer, pSegment, nSegmentLength ); return nSegmentLength; } return 0; } #define BLE_MAX_READ_RETRIES 8 static int SetFeatureReport( hid_device *dev, unsigned char uBuffer[65], int nActualDataLen ) { DPRINTF("SetFeatureReport %p %p %d\n", dev, uBuffer, nActualDataLen); int nRet = -1; bool bBle = true; // only wireless/BLE for now, though macOS could do wired in the future if ( bBle ) { if ( nActualDataLen < 1 ) return -1; int nSegmentNumber = 0; uint8_t uPacketBuffer[ MAX_REPORT_SEGMENT_SIZE ]; // Skip report number in data unsigned char *pBufferPtr = uBuffer + 1; nActualDataLen--; while ( nActualDataLen > 0 ) { int nBytesInPacket = nActualDataLen > MAX_REPORT_SEGMENT_PAYLOAD_SIZE ? MAX_REPORT_SEGMENT_PAYLOAD_SIZE : nActualDataLen; nActualDataLen -= nBytesInPacket; // Construct packet memset( uPacketBuffer, 0, sizeof( uPacketBuffer ) ); uPacketBuffer[ 0 ] = BLE_REPORT_NUMBER; uPacketBuffer[ 1 ] = GetSegmentHeader( nSegmentNumber, nActualDataLen == 0 ); memcpy( &uPacketBuffer[ 2 ], pBufferPtr, nBytesInPacket ); pBufferPtr += nBytesInPacket; nSegmentNumber++; nRet = hid_send_feature_report( dev, uPacketBuffer, sizeof( uPacketBuffer ) ); DPRINTF("SetFeatureReport() ret = %d\n", nRet); } } return nRet; } static int GetFeatureReport( hid_device *dev, unsigned char uBuffer[65] ) { DPRINTF("GetFeatureReport( %p %p )\n", dev, uBuffer ); int nRet = -1; bool bBle = true; if ( bBle ) { SteamControllerPacketAssembler assembler; InitializeSteamControllerPacketAssembler( &assembler ); int nRetries = 0; uint8_t uSegmentBuffer[ MAX_REPORT_SEGMENT_SIZE ]; while( nRetries < BLE_MAX_READ_RETRIES ) { memset( uSegmentBuffer, 0, sizeof( uSegmentBuffer ) ); uSegmentBuffer[ 0 ] = BLE_REPORT_NUMBER; nRet = hid_get_feature_report( dev, uSegmentBuffer, sizeof( uSegmentBuffer ) ); DPRINTF( "GetFeatureReport ble ret=%d\n", nRet ); HEXDUMP( uSegmentBuffer, nRet ); // Zero retry counter if we got data if ( nRet > 2 && ( uSegmentBuffer[ 1 ] & REPORT_SEGMENT_DATA_FLAG ) ) nRetries = 0; else nRetries++; if ( nRet > 0 ) { int nPacketLength = WriteSegmentToSteamControllerPacketAssembler( &assembler, uSegmentBuffer, nRet ); if ( nPacketLength > 0 && nPacketLength < 65 ) { // Leave space for "report number" uBuffer[ 0 ] = 0; memcpy( uBuffer + 1, assembler.uBuffer, nPacketLength ); return nPacketLength; } } } printf("Could not get a full ble packet after %d retries\n", nRetries ); return -1; } return nRet; } static int ReadResponse( hid_device *dev, uint8_t uBuffer[65], int nExpectedResponse ) { DPRINTF("ReadResponse( %p %p %d )\n", dev, uBuffer, nExpectedResponse ); int nRet = GetFeatureReport( dev, uBuffer ); if ( nRet < 0 ) return nRet; DPRINTF("ReadResponse got %d bytes of data: ", nRet ); HEXDUMP( uBuffer, nRet ); if ( uBuffer[1] != nExpectedResponse ) return -1; return nRet; } //--------------------------------------------------------------------------- // Reset steam controller (unmap buttons and pads) and re-fetch capability bits //--------------------------------------------------------------------------- static bool ResetSteamController( hid_device *dev, bool bSuppressErrorSpew ) { DPRINTF( "ResetSteamController hid=%p\n", dev ); // Firmware quirk: Set Feature and Get Feature requests always require a 65-byte buffer. unsigned char buf[65]; int res = -1; buf[0] = 0; buf[1] = ID_GET_ATTRIBUTES_VALUES; res = SetFeatureReport( dev, buf, 2 ); if ( res < 0 ) { if ( !bSuppressErrorSpew ) printf( "GET_ATTRIBUTES_VALUES failed for controller %p\n", dev ); return false; } // Retrieve GET_ATTRIBUTES_VALUES result // Wireless controller endpoints without a connected controller will return nAttrs == 0 res = ReadResponse( dev, buf, ID_GET_ATTRIBUTES_VALUES ); if ( res < 0 || buf[1] != ID_GET_ATTRIBUTES_VALUES ) { HEXDUMP(buf, res); if ( !bSuppressErrorSpew ) printf( "Bad GET_ATTRIBUTES_VALUES response for controller %p\n", dev ); return false; } int nAttributesLength = buf[ 2 ]; if ( nAttributesLength > res ) { if ( !bSuppressErrorSpew ) printf( "Bad GET_ATTRIBUTES_VALUES response for controller %p\n", dev ); return false; } // Clear digital button mappings buf[0] = 0; buf[1] = ID_CLEAR_DIGITAL_MAPPINGS; res = SetFeatureReport( dev, buf, 2 ); if ( res < 0 ) { if ( !bSuppressErrorSpew ) printf( "CLEAR_DIGITAL_MAPPINGS failed for controller %p\n", dev ); return false; } // Reset the default settings memset( buf, 0, 65 ); buf[1] = ID_LOAD_DEFAULT_SETTINGS; buf[2] = 0; res = SetFeatureReport( dev, buf, 3 ); if ( res < 0 ) { if ( !bSuppressErrorSpew ) printf( "LOAD_DEFAULT_SETTINGS failed for controller %p\n", dev ); return false; } // Apply custom settings - clear trackpad modes (cancel mouse emulation), etc int nSettings = 0; #define ADD_SETTING(SETTING, VALUE) \ buf[3+nSettings*3] = SETTING; \ buf[3+nSettings*3+1] = ((uint16_t)VALUE)&0xFF; \ buf[3+nSettings*3+2] = ((uint16_t)VALUE)>>8; \ ++nSettings; memset( buf, 0, 65 ); buf[1] = ID_SET_SETTINGS_VALUES; ADD_SETTING( SETTING_WIRELESS_PACKET_VERSION, 2 ); ADD_SETTING( SETTING_LEFT_TRACKPAD_MODE, TRACKPAD_NONE ); #ifdef ENABLE_MOUSE_MODE ADD_SETTING( SETTING_RIGHT_TRACKPAD_MODE, TRACKPAD_ABSOLUTE_MOUSE ); ADD_SETTING( SETTING_SMOOTH_ABSOLUTE_MOUSE, 1 ); ADD_SETTING( SETTING_MOMENTUM_MAXIMUM_VELOCITY, 20000 ); // [0-20000] default 8000 ADD_SETTING( SETTING_MOMENTUM_DECAY_AMMOUNT, 50 ); // [0-50] default 5 #else ADD_SETTING( SETTING_RIGHT_TRACKPAD_MODE, TRACKPAD_NONE ); ADD_SETTING( SETTING_SMOOTH_ABSOLUTE_MOUSE, 0 ); #endif buf[2] = nSettings*3; res = SetFeatureReport( dev, buf, 3+nSettings*3 ); if ( res < 0 ) { if ( !bSuppressErrorSpew ) printf( "SET_SETTINGS failed for controller %p\n", dev ); return false; } #ifdef ENABLE_MOUSE_MODE // Wait for ID_CLEAR_DIGITAL_MAPPINGS to be processed on the controller bool bMappingsCleared = false; int iRetry; for ( iRetry = 0; iRetry < 2; ++iRetry ) { memset( buf, 0, 65 ); buf[1] = ID_GET_DIGITAL_MAPPINGS; buf[2] = 1; // one byte - requesting from index 0 buf[3] = 0; res = SetFeatureReport( dev, buf, 4 ); if ( res < 0 ) { printf( "GET_DIGITAL_MAPPINGS failed for controller %p\n", dev ); return false; } res = ReadResponse( dev, buf, ID_GET_DIGITAL_MAPPINGS ); if ( res < 0 || buf[1] != ID_GET_DIGITAL_MAPPINGS ) { printf( "Bad GET_DIGITAL_MAPPINGS response for controller %p\n", dev ); return false; } // If the length of the digital mappings result is not 1 (index byte, no mappings) then clearing hasn't executed if ( buf[2] == 1 && buf[3] == 0xFF ) { bMappingsCleared = true; break; } usleep( CONTROLLER_CONFIGURATION_DELAY_US ); } if ( !bMappingsCleared && !bSuppressErrorSpew ) { printf( "Warning: CLEAR_DIGITAL_MAPPINGS never completed for controller %p\n", dev ); } // Set our new mappings memset( buf, 0, 65 ); buf[1] = ID_SET_DIGITAL_MAPPINGS; buf[2] = 6; // 2 settings x 3 bytes buf[3] = IO_DIGITAL_BUTTON_RIGHT_TRIGGER; buf[4] = DEVICE_MOUSE; buf[5] = MOUSE_BTN_LEFT; buf[6] = IO_DIGITAL_BUTTON_LEFT_TRIGGER; buf[7] = DEVICE_MOUSE; buf[8] = MOUSE_BTN_RIGHT; res = SetFeatureReport( dev, buf, 9 ); if ( res < 0 ) { if ( !bSuppressErrorSpew ) printf( "SET_DIGITAL_MAPPINGS failed for controller %p\n", dev ); return false; } #endif // ENABLE_MOUSE_MODE return true; } //--------------------------------------------------------------------------- // Read from a Steam Controller //--------------------------------------------------------------------------- static int ReadSteamController( hid_device *dev, uint8_t *pData, int nDataSize ) { memset( pData, 0, nDataSize ); pData[ 0 ] = BLE_REPORT_NUMBER; // hid_read will also overwrite this with the same value, 0x03 return hid_read( dev, pData, nDataSize ); } //--------------------------------------------------------------------------- // Close a Steam Controller //--------------------------------------------------------------------------- static void CloseSteamController( hid_device *dev ) { // Switch the Steam Controller back to lizard mode so it works with the OS unsigned char buf[65]; int nSettings = 0; // Reset digital button mappings memset( buf, 0, 65 ); buf[1] = ID_SET_DEFAULT_DIGITAL_MAPPINGS; SetFeatureReport( dev, buf, 2 ); // Reset the default settings memset( buf, 0, 65 ); buf[1] = ID_LOAD_DEFAULT_SETTINGS; buf[2] = 0; SetFeatureReport( dev, buf, 3 ); // Reset mouse mode for lizard mode memset( buf, 0, 65 ); buf[1] = ID_SET_SETTINGS_VALUES; ADD_SETTING( SETTING_RIGHT_TRACKPAD_MODE, TRACKPAD_ABSOLUTE_MOUSE ); buf[2] = nSettings*3; SetFeatureReport( dev, buf, 3+nSettings*3 ); } //--------------------------------------------------------------------------- // Scale and clamp values to a range //--------------------------------------------------------------------------- static float RemapValClamped( float val, float A, float B, float C, float D) { if ( A == B ) { return ( val - B ) >= 0.0f ? D : C; } else { float cVal = (val - A) / (B - A); cVal = clamp( cVal, 0.0f, 1.0f ); return C + (D - C) * cVal; } } //--------------------------------------------------------------------------- // Rotate the pad coordinates //--------------------------------------------------------------------------- static void RotatePad( int *pX, int *pY, float flAngleInRad ) { short int origX = *pX, origY = *pY; *pX = (int)( SDL_cosf( flAngleInRad ) * origX - SDL_sinf( flAngleInRad ) * origY ); *pY = (int)( SDL_sinf( flAngleInRad ) * origX + SDL_cosf( flAngleInRad ) * origY ); } static void RotatePadShort( short *pX, short *pY, float flAngleInRad ) { short int origX = *pX, origY = *pY; *pX = (short)( SDL_cosf( flAngleInRad ) * origX - SDL_sinf( flAngleInRad ) * origY ); *pY = (short)( SDL_sinf( flAngleInRad ) * origX + SDL_cosf( flAngleInRad ) * origY ); } //--------------------------------------------------------------------------- // Format the first part of the state packet //--------------------------------------------------------------------------- static void FormatStatePacketUntilGyro( SteamControllerStateInternal_t *pState, ValveControllerStatePacket_t *pStatePacket ) { memset(pState, 0, offsetof(SteamControllerStateInternal_t, sBatteryLevel)); //pState->eControllerType = m_eControllerType; pState->eControllerType = 2; // k_eControllerType_SteamController; pState->unPacketNum = pStatePacket->unPacketNum; // We have a chunk of trigger data in the packet format here, so zero it out afterwards memcpy(&pState->ulButtons, &pStatePacket->ButtonTriggerData.ulButtons, 8); pState->ulButtons &= ~0xFFFF000000LL; // The firmware uses this bit to tell us what kind of data is packed into the left two axises if (pStatePacket->ButtonTriggerData.ulButtons & STEAM_LEFTPAD_FINGERDOWN_MASK) { // Finger-down bit not set; "left pad" is actually trackpad pState->sLeftPadX = pState->sPrevLeftPad[0] = pStatePacket->sLeftPadX; pState->sLeftPadY = pState->sPrevLeftPad[1] = pStatePacket->sLeftPadY; if (pStatePacket->ButtonTriggerData.ulButtons & STEAM_LEFTPAD_AND_JOYSTICK_MASK) { // The controller is interleaving both stick and pad data, both are active pState->sLeftStickX = pState->sPrevLeftStick[0]; pState->sLeftStickY = pState->sPrevLeftStick[1]; } else { // The stick is not active pState->sPrevLeftStick[0] = 0; pState->sPrevLeftStick[1] = 0; } } else { // Finger-down bit not set; "left pad" is actually joystick // XXX there's a firmware bug where sometimes padX is 0 and padY is a large number (acutally the battery voltage) // If that happens skip this packet and report last frames stick /* if ( m_eControllerType == k_eControllerType_SteamControllerV2 && pStatePacket->sLeftPadY > 900 ) { pState->sLeftStickX = pState->sPrevLeftStick[0]; pState->sLeftStickY = pState->sPrevLeftStick[1]; } else */ { pState->sPrevLeftStick[0] = pState->sLeftStickX = pStatePacket->sLeftPadX; pState->sPrevLeftStick[1] = pState->sLeftStickY = pStatePacket->sLeftPadY; } /* if (m_eControllerType == k_eControllerType_SteamControllerV2) { UpdateV2JoystickCap(&state); } */ if (pStatePacket->ButtonTriggerData.ulButtons & STEAM_LEFTPAD_AND_JOYSTICK_MASK) { // The controller is interleaving both stick and pad data, both are active pState->sLeftPadX = pState->sPrevLeftPad[0]; pState->sLeftPadY = pState->sPrevLeftPad[1]; } else { // The trackpad is not active pState->sPrevLeftPad[0] = 0; pState->sPrevLeftPad[1] = 0; // Old controllers send trackpad click for joystick button when trackpad is not active if (pState->ulButtons & STEAM_BUTTON_LEFTPAD_CLICKED_MASK) { pState->ulButtons &= ~STEAM_BUTTON_LEFTPAD_CLICKED_MASK; pState->ulButtons |= STEAM_JOYSTICK_BUTTON_MASK; } } } // Fingerdown bit indicates if the packed left axis data was joystick or pad, // but if we are interleaving both, the left finger is definitely on the pad. if (pStatePacket->ButtonTriggerData.ulButtons & STEAM_LEFTPAD_AND_JOYSTICK_MASK) pState->ulButtons |= STEAM_LEFTPAD_FINGERDOWN_MASK; pState->sRightPadX = pStatePacket->sRightPadX; pState->sRightPadY = pStatePacket->sRightPadY; int nLeftPadX = pState->sLeftPadX; int nLeftPadY = pState->sLeftPadY; int nRightPadX = pState->sRightPadX; int nRightPadY = pState->sRightPadY; // 15 degrees in rad const float flRotationAngle = 0.261799f; RotatePad(&nLeftPadX, &nLeftPadY, -flRotationAngle); RotatePad(&nRightPadX, &nRightPadY, flRotationAngle); int nPadOffset; if (pState->ulButtons & STEAM_LEFTPAD_FINGERDOWN_MASK) nPadOffset = 1000; else nPadOffset = 0; pState->sLeftPadX = clamp(nLeftPadX + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16); pState->sLeftPadY = clamp(nLeftPadY + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16); nPadOffset = 0; if (pState->ulButtons & STEAM_RIGHTPAD_FINGERDOWN_MASK) nPadOffset = 1000; else nPadOffset = 0; pState->sRightPadX = clamp(nRightPadX + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16); pState->sRightPadY = clamp(nRightPadY + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16); pState->sTriggerL = (unsigned short)RemapValClamped( (pStatePacket->ButtonTriggerData.Triggers.nLeft << 7) | pStatePacket->ButtonTriggerData.Triggers.nLeft, 0, STEAMCONTROLLER_TRIGGER_MAX_ANALOG, 0, SDL_MAX_SINT16 ); pState->sTriggerR = (unsigned short)RemapValClamped( (pStatePacket->ButtonTriggerData.Triggers.nRight << 7) | pStatePacket->ButtonTriggerData.Triggers.nRight, 0, STEAMCONTROLLER_TRIGGER_MAX_ANALOG, 0, SDL_MAX_SINT16 ); } //--------------------------------------------------------------------------- // Update Steam Controller state from a BLE data packet, returns true if it parsed data //--------------------------------------------------------------------------- static bool UpdateBLESteamControllerState( const uint8_t *pData, int nDataSize, SteamControllerStateInternal_t *pState ) { const float flRotationAngle = 0.261799f; uint32_t ucOptionDataMask; pState->unPacketNum++; ucOptionDataMask = ( *pData++ & 0xF0 ); ucOptionDataMask |= (uint32_t)(*pData++) << 8; if ( ucOptionDataMask & k_EBLEButtonChunk1 ) { memcpy( &pState->ulButtons, pData, 3 ); pData += 3; } if ( ucOptionDataMask & k_EBLEButtonChunk2 ) { // The middle 2 bytes of the button bits over the wire are triggers when over the wire and non-SC buttons in the internal controller state packet pState->sTriggerL = (unsigned short)RemapValClamped( ( pData[ 0 ] << 7 ) | pData[ 0 ], 0, STEAMCONTROLLER_TRIGGER_MAX_ANALOG, 0, SDL_MAX_SINT16 ); pState->sTriggerR = (unsigned short)RemapValClamped( ( pData[ 1 ] << 7 ) | pData[ 1 ], 0, STEAMCONTROLLER_TRIGGER_MAX_ANALOG, 0, SDL_MAX_SINT16 ); pData += 2; } if ( ucOptionDataMask & k_EBLEButtonChunk3 ) { uint8_t *pButtonByte = (uint8_t *)&pState->ulButtons; pButtonByte[ 5 ] = *pData++; pButtonByte[ 6 ] = *pData++; pButtonByte[ 7 ] = *pData++; } if ( ucOptionDataMask & k_EBLELeftJoystickChunk ) { // This doesn't handle any of the special headcrab stuff for raw joystick which is OK for now since that FW doesn't support // this protocol yet either int nLength = sizeof( pState->sLeftStickX ) + sizeof( pState->sLeftStickY ); memcpy( &pState->sLeftStickX, pData, nLength ); pData += nLength; } if ( ucOptionDataMask & k_EBLELeftTrackpadChunk ) { int nLength = sizeof( pState->sLeftPadX ) + sizeof( pState->sLeftPadY ); int nPadOffset; memcpy( &pState->sLeftPadX, pData, nLength ); if ( pState->ulButtons & STEAM_LEFTPAD_FINGERDOWN_MASK ) nPadOffset = 1000; else nPadOffset = 0; RotatePadShort( &pState->sLeftPadX, &pState->sLeftPadY, -flRotationAngle ); pState->sLeftPadX = clamp( pState->sLeftPadX + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16 ); pState->sLeftPadY = clamp( pState->sLeftPadY + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16 ); pData += nLength; } if ( ucOptionDataMask & k_EBLERightTrackpadChunk ) { int nLength = sizeof( pState->sRightPadX ) + sizeof( pState->sRightPadY ); int nPadOffset = 0; memcpy( &pState->sRightPadX, pData, nLength ); if ( pState->ulButtons & STEAM_RIGHTPAD_FINGERDOWN_MASK ) nPadOffset = 1000; else nPadOffset = 0; RotatePadShort( &pState->sRightPadX, &pState->sRightPadY, flRotationAngle ); pState->sRightPadX = clamp( pState->sRightPadX + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16 ); pState->sRightPadY = clamp( pState->sRightPadY + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16 ); pData += nLength; } if ( ucOptionDataMask & k_EBLEIMUAccelChunk ) { int nLength = sizeof( pState->sAccelX ) + sizeof( pState->sAccelY ) + sizeof( pState->sAccelZ ); memcpy( &pState->sAccelX, pData, nLength ); pData += nLength; } if ( ucOptionDataMask & k_EBLEIMUGyroChunk ) { int nLength = sizeof( pState->sAccelX ) + sizeof( pState->sAccelY ) + sizeof( pState->sAccelZ ); memcpy( &pState->sGyroX, pData, nLength ); pData += nLength; } if ( ucOptionDataMask & k_EBLEIMUQuatChunk ) { int nLength = sizeof( pState->sGyroQuatW ) + sizeof( pState->sGyroQuatX ) + sizeof( pState->sGyroQuatY ) + sizeof( pState->sGyroQuatZ ); memcpy( &pState->sGyroQuatW, pData, nLength ); pData += nLength; } return true; } //--------------------------------------------------------------------------- // Update Steam Controller state from a data packet, returns true if it parsed data //--------------------------------------------------------------------------- static bool UpdateSteamControllerState( const uint8_t *pData, int nDataSize, SteamControllerStateInternal_t *pState ) { ValveInReport_t *pInReport = (ValveInReport_t*)pData; if ( pInReport->header.unReportVersion != k_ValveInReportMsgVersion ) { if ( ( pData[ 0 ] & 0x0F ) == k_EBLEReportState ) { return UpdateBLESteamControllerState( pData, nDataSize, pState ); } return false; } if ( ( pInReport->header.ucType != ID_CONTROLLER_STATE ) && ( pInReport->header.ucType != ID_CONTROLLER_BLE_STATE ) ) { return false; } if ( pInReport->header.ucType == ID_CONTROLLER_STATE ) { ValveControllerStatePacket_t *pStatePacket = &pInReport->payload.controllerState; // No new data to process; indicate that we received a state packet, but otherwise do nothing. if ( pState->unPacketNum == pStatePacket->unPacketNum ) return true; FormatStatePacketUntilGyro( pState, pStatePacket ); pState->sAccelX = pStatePacket->sAccelX; pState->sAccelY = pStatePacket->sAccelY; pState->sAccelZ = pStatePacket->sAccelZ; pState->sGyroQuatW = pStatePacket->sGyroQuatW; pState->sGyroQuatX = pStatePacket->sGyroQuatX; pState->sGyroQuatY = pStatePacket->sGyroQuatY; pState->sGyroQuatZ = pStatePacket->sGyroQuatZ; pState->sGyroX = pStatePacket->sGyroX; pState->sGyroY = pStatePacket->sGyroY; pState->sGyroZ = pStatePacket->sGyroZ; } else if ( pInReport->header.ucType == ID_CONTROLLER_BLE_STATE ) { ValveControllerBLEStatePacket_t *pBLEStatePacket = &pInReport->payload.controllerBLEState; ValveControllerStatePacket_t *pStatePacket = &pInReport->payload.controllerState; // No new data to process; indicate that we received a state packet, but otherwise do nothing. if ( pState->unPacketNum == pStatePacket->unPacketNum ) return true; FormatStatePacketUntilGyro( pState, pStatePacket ); switch ( pBLEStatePacket->ucGyroDataType ) { case 1: pState->sGyroQuatW = (( float ) pBLEStatePacket->sGyro[0]); pState->sGyroQuatX = (( float ) pBLEStatePacket->sGyro[1]); pState->sGyroQuatY = (( float ) pBLEStatePacket->sGyro[2]); pState->sGyroQuatZ = (( float ) pBLEStatePacket->sGyro[3]); break; case 2: pState->sAccelX = pBLEStatePacket->sGyro[0]; pState->sAccelY = pBLEStatePacket->sGyro[1]; pState->sAccelZ = pBLEStatePacket->sGyro[2]; break; case 3: pState->sGyroX = pBLEStatePacket->sGyro[0]; pState->sGyroY = pBLEStatePacket->sGyro[1]; pState->sGyroZ = pBLEStatePacket->sGyro[2]; break; default: break; } } return true; } /*****************************************************************************************************/ typedef struct { SteamControllerPacketAssembler m_assembler; SteamControllerStateInternal_t m_state; SteamControllerStateInternal_t m_last_state; } SDL_DriverSteam_Context; static SDL_bool HIDAPI_DriverSteam_IsSupportedDevice(const char *name, SDL_GameControllerType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) { return SDL_IsJoystickSteamController(vendor_id, product_id); } static const char * HIDAPI_DriverSteam_GetDeviceName(Uint16 vendor_id, Uint16 product_id) { return "Steam Controller"; } static SDL_bool HIDAPI_DriverSteam_InitDevice(SDL_HIDAPI_Device *device) { return HIDAPI_JoystickConnected(device, NULL, SDL_FALSE); } static int HIDAPI_DriverSteam_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) { return -1; } static void HIDAPI_DriverSteam_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) { } static SDL_bool HIDAPI_DriverSteam_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) { SDL_DriverSteam_Context *ctx; ctx = (SDL_DriverSteam_Context *)SDL_calloc(1, sizeof(*ctx)); if (!ctx) { SDL_OutOfMemory(); goto error; } device->context = ctx; device->dev = hid_open_path(device->path, 0); if (!device->dev) { SDL_SetError("Couldn't open %s", device->path); goto error; } if (!ResetSteamController(device->dev, false)) { goto error; } InitializeSteamControllerPacketAssembler(&ctx->m_assembler); /* Initialize the joystick capabilities */ joystick->nbuttons = SDL_CONTROLLER_BUTTON_MAX; joystick->naxes = SDL_CONTROLLER_AXIS_MAX; return SDL_TRUE; error: if (device->dev) { hid_close(device->dev); device->dev = NULL; } if (device->context) { SDL_free(device->context); device->context = NULL; } return SDL_FALSE; } static int HIDAPI_DriverSteam_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { /* You should use the full Steam Input API for rumble support */ return SDL_Unsupported(); } static SDL_bool HIDAPI_DriverSteam_UpdateDevice(SDL_HIDAPI_Device *device) { SDL_DriverSteam_Context *ctx = (SDL_DriverSteam_Context *)device->context; SDL_Joystick *joystick = NULL; if (device->num_joysticks > 0) { joystick = SDL_JoystickFromInstanceID(device->joysticks[0]); } if (!joystick) { return SDL_FALSE; } for (;;) { uint8_t data[128]; int r, nPacketLength; const Uint8 *pPacket; r = ReadSteamController(device->dev, data, sizeof(data)); if (r == 0) { break; } nPacketLength = 0; if (r > 0) { nPacketLength = WriteSegmentToSteamControllerPacketAssembler(&ctx->m_assembler, data, r); } pPacket = ctx->m_assembler.uBuffer; if (nPacketLength > 0 && UpdateSteamControllerState(pPacket, nPacketLength, &ctx->m_state)) { if (ctx->m_state.ulButtons != ctx->m_last_state.ulButtons) { SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_A, (ctx->m_state.ulButtons & STEAM_BUTTON_3_MASK) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_B, (ctx->m_state.ulButtons & STEAM_BUTTON_1_MASK) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_X, (ctx->m_state.ulButtons & STEAM_BUTTON_2_MASK) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_Y, (ctx->m_state.ulButtons & STEAM_BUTTON_0_MASK) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSHOULDER, (ctx->m_state.ulButtons & STEAM_LEFT_BUMPER_MASK) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, (ctx->m_state.ulButtons & STEAM_RIGHT_BUMPER_MASK) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_BACK, (ctx->m_state.ulButtons & STEAM_BUTTON_MENU_MASK) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_START, (ctx->m_state.ulButtons & STEAM_BUTTON_ESCAPE_MASK) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, (ctx->m_state.ulButtons & STEAM_BUTTON_STEAM_MASK) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSTICK, (ctx->m_state.ulButtons & STEAM_JOYSTICK_BUTTON_MASK) ? SDL_PRESSED : SDL_RELEASED); } { /* Minimum distance from center of pad to register a direction */ const int kPadDeadZone = 10000; /* Pad coordinates are like math grid coordinates: negative is bottom left */ SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_UP, (ctx->m_state.sLeftPadY > kPadDeadZone) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_DOWN, (ctx->m_state.sLeftPadY < -kPadDeadZone) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_LEFT, (ctx->m_state.sLeftPadX < -kPadDeadZone) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_RIGHT, (ctx->m_state.sLeftPadX > kPadDeadZone) ? SDL_PRESSED : SDL_RELEASED); } SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, (int)ctx->m_state.sTriggerL * 2 - 32768); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, (int)ctx->m_state.sTriggerR * 2 - 32768); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTX, ctx->m_state.sLeftStickX); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTY, ~ctx->m_state.sLeftStickY); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTX, ctx->m_state.sRightPadX); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTY, ~ctx->m_state.sRightPadY); ctx->m_last_state = ctx->m_state; } if (r <= 0) { /* Failed to read from controller */ HIDAPI_JoystickDisconnected(device, device->joysticks[0], SDL_FALSE); return SDL_FALSE; } } return SDL_TRUE; } static void HIDAPI_DriverSteam_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) { CloseSteamController(device->dev); hid_close(device->dev); device->dev = NULL; SDL_free(device->context); device->context = NULL; } static void HIDAPI_DriverSteam_FreeDevice(SDL_HIDAPI_Device *device) { } SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverSteam = { SDL_HINT_JOYSTICK_HIDAPI_STEAM, SDL_TRUE, HIDAPI_DriverSteam_IsSupportedDevice, HIDAPI_DriverSteam_GetDeviceName, HIDAPI_DriverSteam_InitDevice, HIDAPI_DriverSteam_GetDevicePlayerIndex, HIDAPI_DriverSteam_SetDevicePlayerIndex, HIDAPI_DriverSteam_UpdateDevice, HIDAPI_DriverSteam_OpenJoystick, HIDAPI_DriverSteam_RumbleJoystick, HIDAPI_DriverSteam_CloseJoystick, HIDAPI_DriverSteam_FreeDevice, NULL }; #endif /* SDL_JOYSTICK_HIDAPI_STEAM */ #endif /* SDL_JOYSTICK_HIDAPI */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/hidapi/SDL_hidapi_steam.c
C
apache-2.0
41,946
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* This driver supports the Nintendo Switch Pro controller. Code and logic contributed by Valve Corporation under the SDL zlib license. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_HIDAPI #include "SDL_hints.h" #include "SDL_events.h" #include "SDL_timer.h" #include "SDL_joystick.h" #include "SDL_gamecontroller.h" #include "../../SDL_hints_c.h" #include "../SDL_sysjoystick.h" #include "SDL_hidapijoystick_c.h" #include "SDL_hidapi_rumble.h" #ifdef SDL_JOYSTICK_HIDAPI_SWITCH /* Define this to get log output for rumble logic */ /*#define DEBUG_RUMBLE*/ /* How often you can write rumble commands to the controller in Bluetooth mode If you send commands more frequently than this, you can turn off the controller. */ #define RUMBLE_WRITE_FREQUENCY_MS 25 /* How often you have to refresh a long duration rumble to keep the motors running */ #define RUMBLE_REFRESH_FREQUENCY_MS 40 typedef enum { k_eSwitchInputReportIDs_SubcommandReply = 0x21, k_eSwitchInputReportIDs_FullControllerState = 0x30, k_eSwitchInputReportIDs_SimpleControllerState = 0x3F, k_eSwitchInputReportIDs_CommandAck = 0x81, } ESwitchInputReportIDs; typedef enum { k_eSwitchOutputReportIDs_RumbleAndSubcommand = 0x01, k_eSwitchOutputReportIDs_Rumble = 0x10, k_eSwitchOutputReportIDs_Proprietary = 0x80, } ESwitchOutputReportIDs; typedef enum { k_eSwitchSubcommandIDs_BluetoothManualPair = 0x01, k_eSwitchSubcommandIDs_RequestDeviceInfo = 0x02, k_eSwitchSubcommandIDs_SetInputReportMode = 0x03, k_eSwitchSubcommandIDs_SetHCIState = 0x06, k_eSwitchSubcommandIDs_SPIFlashRead = 0x10, k_eSwitchSubcommandIDs_SetPlayerLights = 0x30, k_eSwitchSubcommandIDs_SetHomeLight = 0x38, k_eSwitchSubcommandIDs_EnableIMU = 0x40, k_eSwitchSubcommandIDs_SetIMUSensitivity = 0x41, k_eSwitchSubcommandIDs_EnableVibration = 0x48, } ESwitchSubcommandIDs; typedef enum { k_eSwitchProprietaryCommandIDs_Handshake = 0x02, k_eSwitchProprietaryCommandIDs_HighSpeed = 0x03, k_eSwitchProprietaryCommandIDs_ForceUSB = 0x04, k_eSwitchProprietaryCommandIDs_ClearUSB = 0x05, k_eSwitchProprietaryCommandIDs_ResetMCU = 0x06, } ESwitchProprietaryCommandIDs; typedef enum { k_eSwitchDeviceInfoControllerType_JoyConLeft = 0x1, k_eSwitchDeviceInfoControllerType_JoyConRight = 0x2, k_eSwitchDeviceInfoControllerType_ProController = 0x3, } ESwitchDeviceInfoControllerType; #define k_unSwitchOutputPacketDataLength 49 #define k_unSwitchMaxOutputPacketLength 64 #define k_unSwitchBluetoothPacketLength k_unSwitchOutputPacketDataLength #define k_unSwitchUSBPacketLength k_unSwitchMaxOutputPacketLength #define k_unSPIStickCalibrationStartOffset 0x603D #define k_unSPIStickCalibrationEndOffset 0x604E #define k_unSPIStickCalibrationLength (k_unSPIStickCalibrationEndOffset - k_unSPIStickCalibrationStartOffset + 1) #pragma pack(1) typedef struct { Uint8 rgucButtons[2]; Uint8 ucStickHat; Uint8 rgucJoystickLeft[2]; Uint8 rgucJoystickRight[2]; } SwitchInputOnlyControllerStatePacket_t; typedef struct { Uint8 rgucButtons[2]; Uint8 ucStickHat; Sint16 sJoystickLeft[2]; Sint16 sJoystickRight[2]; } SwitchSimpleStatePacket_t; typedef struct { Uint8 ucCounter; Uint8 ucBatteryAndConnection; Uint8 rgucButtons[3]; Uint8 rgucJoystickLeft[3]; Uint8 rgucJoystickRight[3]; Uint8 ucVibrationCode; } SwitchControllerStatePacket_t; typedef struct { SwitchControllerStatePacket_t controllerState; struct { Sint16 sAccelX; Sint16 sAccelY; Sint16 sAccelZ; Sint16 sGyroX; Sint16 sGyroY; Sint16 sGyroZ; } imuState[3]; } SwitchStatePacket_t; typedef struct { Uint32 unAddress; Uint8 ucLength; } SwitchSPIOpData_t; typedef struct { SwitchControllerStatePacket_t m_controllerState; Uint8 ucSubcommandAck; Uint8 ucSubcommandID; #define k_unSubcommandDataBytes 35 union { Uint8 rgucSubcommandData[k_unSubcommandDataBytes]; struct { SwitchSPIOpData_t opData; Uint8 rgucReadData[k_unSubcommandDataBytes - sizeof(SwitchSPIOpData_t)]; } spiReadData; struct { Uint8 rgucFirmwareVersion[2]; Uint8 ucDeviceType; Uint8 ucFiller1; Uint8 rgucMACAddress[6]; Uint8 ucFiller2; Uint8 ucColorLocation; } deviceInfo; }; } SwitchSubcommandInputPacket_t; typedef struct { Uint8 rgucData[4]; } SwitchRumbleData_t; typedef struct { Uint8 ucPacketType; Uint8 ucPacketNumber; SwitchRumbleData_t rumbleData[2]; } SwitchCommonOutputPacket_t; typedef struct { SwitchCommonOutputPacket_t commonData; Uint8 ucSubcommandID; Uint8 rgucSubcommandData[k_unSwitchOutputPacketDataLength - sizeof(SwitchCommonOutputPacket_t) - 1]; } SwitchSubcommandOutputPacket_t; typedef struct { Uint8 ucPacketType; Uint8 ucProprietaryID; Uint8 rgucProprietaryData[k_unSwitchOutputPacketDataLength - 1 - 1]; } SwitchProprietaryOutputPacket_t; #pragma pack() typedef struct { SDL_HIDAPI_Device *device; SDL_bool m_bInputOnly; SDL_bool m_bHasHomeLED; SDL_bool m_bUsingBluetooth; SDL_bool m_bIsGameCube; SDL_bool m_bUseButtonLabels; Uint8 m_nCommandNumber; SwitchCommonOutputPacket_t m_RumblePacket; Uint8 m_rgucReadBuffer[k_unSwitchMaxOutputPacketLength]; SDL_bool m_bRumbleActive; Uint32 m_unRumbleSent; SDL_bool m_bRumblePending; SDL_bool m_bRumbleZeroPending; Uint32 m_unRumblePending; SwitchInputOnlyControllerStatePacket_t m_lastInputOnlyState; SwitchSimpleStatePacket_t m_lastSimpleState; SwitchStatePacket_t m_lastFullState; struct StickCalibrationData { struct { Sint16 sCenter; Sint16 sMin; Sint16 sMax; } axis[2]; } m_StickCalData[2]; struct StickExtents { struct { Sint16 sMin; Sint16 sMax; } axis[2]; } m_StickExtents[2]; } SDL_DriverSwitch_Context; static SDL_bool HasHomeLED(int vendor_id, int product_id) { /* The Power A Nintendo Switch Pro controllers don't have a Home LED */ if (vendor_id == 0 && product_id == 0) { return SDL_FALSE; } /* HORI Wireless Switch Pad */ if (vendor_id == 0x0f0d && product_id == 0x00f6) { return SDL_FALSE; } return SDL_TRUE; } static SDL_bool IsGameCubeFormFactor(int vendor_id, int product_id) { static Uint32 gamecube_formfactor[] = { MAKE_VIDPID(0x0e6f, 0x0185), /* PDP Wired Fight Pad Pro for Nintendo Switch */ MAKE_VIDPID(0x20d6, 0xa711), /* Core (Plus) Wired Controller */ }; Uint32 id = MAKE_VIDPID(vendor_id, product_id); int i; for (i = 0; i < SDL_arraysize(gamecube_formfactor); ++i) { if (id == gamecube_formfactor[i]) { return SDL_TRUE; } } return SDL_FALSE; } static SDL_bool HIDAPI_DriverSwitch_IsSupportedDevice(const char *name, SDL_GameControllerType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) { /* The HORI Wireless Switch Pad enumerates as a HID device when connected via USB with the same VID/PID as when connected over Bluetooth but doesn't actually support communication over USB. The most reliable way to block this without allowing the controller to continually attempt to reconnect is to filter it out by manufactuer/product string. Note that the controller does have a different product string when connected over Bluetooth. */ if (SDL_strcmp( name, "HORI Wireless Switch Pad" ) == 0) { return SDL_FALSE; } return (type == SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO); } static const char * HIDAPI_DriverSwitch_GetDeviceName(Uint16 vendor_id, Uint16 product_id) { /* Give a user friendly name for this controller */ return "Nintendo Switch Pro Controller"; } static int ReadInput(SDL_DriverSwitch_Context *ctx) { /* Make sure we don't try to read at the same time a write is happening */ if (SDL_AtomicGet(&ctx->device->rumble_pending) > 0) { return 0; } return hid_read_timeout(ctx->device->dev, ctx->m_rgucReadBuffer, sizeof(ctx->m_rgucReadBuffer), 0); } static int WriteOutput(SDL_DriverSwitch_Context *ctx, const Uint8 *data, int size) { /* Use the rumble thread for general asynchronous writes */ if (SDL_HIDAPI_LockRumble() < 0) { return -1; } return SDL_HIDAPI_SendRumbleAndUnlock(ctx->device, data, size); } static SwitchSubcommandInputPacket_t *ReadSubcommandReply(SDL_DriverSwitch_Context *ctx, ESwitchSubcommandIDs expectedID) { /* Average response time for messages is ~30ms */ Uint32 TimeoutMs = 100; Uint32 startTicks = SDL_GetTicks(); int nRead = 0; while ((nRead = ReadInput(ctx)) != -1) { if (nRead > 0) { if (ctx->m_rgucReadBuffer[0] == k_eSwitchInputReportIDs_SubcommandReply) { SwitchSubcommandInputPacket_t *reply = (SwitchSubcommandInputPacket_t *)&ctx->m_rgucReadBuffer[1]; if (reply->ucSubcommandID == expectedID && (reply->ucSubcommandAck & 0x80)) { return reply; } } } else { SDL_Delay(1); } if (SDL_TICKS_PASSED(SDL_GetTicks(), startTicks + TimeoutMs)) { break; } } return NULL; } static SDL_bool ReadProprietaryReply(SDL_DriverSwitch_Context *ctx, ESwitchProprietaryCommandIDs expectedID) { /* Average response time for messages is ~30ms */ Uint32 TimeoutMs = 100; Uint32 startTicks = SDL_GetTicks(); int nRead = 0; while ((nRead = ReadInput(ctx)) != -1) { if (nRead > 0) { if (ctx->m_rgucReadBuffer[0] == k_eSwitchInputReportIDs_CommandAck && ctx->m_rgucReadBuffer[1] == expectedID) { return SDL_TRUE; } } else { SDL_Delay(1); } if (SDL_TICKS_PASSED(SDL_GetTicks(), startTicks + TimeoutMs)) { break; } } return SDL_FALSE; } static void ConstructSubcommand(SDL_DriverSwitch_Context *ctx, ESwitchSubcommandIDs ucCommandID, Uint8 *pBuf, Uint8 ucLen, SwitchSubcommandOutputPacket_t *outPacket) { SDL_memset(outPacket, 0, sizeof(*outPacket)); outPacket->commonData.ucPacketType = k_eSwitchOutputReportIDs_RumbleAndSubcommand; outPacket->commonData.ucPacketNumber = ctx->m_nCommandNumber; SDL_memcpy(&outPacket->commonData.rumbleData, &ctx->m_RumblePacket.rumbleData, sizeof(ctx->m_RumblePacket.rumbleData)); outPacket->ucSubcommandID = ucCommandID; SDL_memcpy(outPacket->rgucSubcommandData, pBuf, ucLen); ctx->m_nCommandNumber = (ctx->m_nCommandNumber + 1) & 0xF; } static SDL_bool WritePacket(SDL_DriverSwitch_Context *ctx, void *pBuf, Uint8 ucLen) { Uint8 rgucBuf[k_unSwitchMaxOutputPacketLength]; const size_t unWriteSize = ctx->m_bUsingBluetooth ? k_unSwitchBluetoothPacketLength : k_unSwitchUSBPacketLength; if (ucLen > k_unSwitchOutputPacketDataLength) { return SDL_FALSE; } if (ucLen < unWriteSize) { SDL_memcpy(rgucBuf, pBuf, ucLen); SDL_memset(rgucBuf+ucLen, 0, unWriteSize-ucLen); pBuf = rgucBuf; ucLen = (Uint8)unWriteSize; } return (WriteOutput(ctx, (Uint8 *)pBuf, ucLen) >= 0); } static SDL_bool WriteSubcommand(SDL_DriverSwitch_Context *ctx, ESwitchSubcommandIDs ucCommandID, Uint8 *pBuf, Uint8 ucLen, SwitchSubcommandInputPacket_t **ppReply) { int nRetries = 5; SwitchSubcommandInputPacket_t *reply = NULL; while (!reply && nRetries--) { SwitchSubcommandOutputPacket_t commandPacket; ConstructSubcommand(ctx, ucCommandID, pBuf, ucLen, &commandPacket); if (!WritePacket(ctx, &commandPacket, sizeof(commandPacket))) { continue; } reply = ReadSubcommandReply(ctx, ucCommandID); } if (ppReply) { *ppReply = reply; } return reply != NULL; } static SDL_bool WriteProprietary(SDL_DriverSwitch_Context *ctx, ESwitchProprietaryCommandIDs ucCommand, Uint8 *pBuf, Uint8 ucLen, SDL_bool waitForReply) { int nRetries = 5; while (nRetries--) { SwitchProprietaryOutputPacket_t packet; if ((!pBuf && ucLen > 0) || ucLen > sizeof(packet.rgucProprietaryData)) { return SDL_FALSE; } packet.ucPacketType = k_eSwitchOutputReportIDs_Proprietary; packet.ucProprietaryID = ucCommand; if (pBuf) { SDL_memcpy(packet.rgucProprietaryData, pBuf, ucLen); } if (!WritePacket(ctx, &packet, sizeof(packet))) { continue; } if (!waitForReply || ReadProprietaryReply(ctx, ucCommand)) { return SDL_TRUE; } } return SDL_FALSE; } static void SetNeutralRumble(SwitchRumbleData_t *pRumble) { pRumble->rgucData[0] = 0x00; pRumble->rgucData[1] = 0x01; pRumble->rgucData[2] = 0x40; pRumble->rgucData[3] = 0x40; } static void EncodeRumble(SwitchRumbleData_t *pRumble, Uint16 usHighFreq, Uint8 ucHighFreqAmp, Uint8 ucLowFreq, Uint16 usLowFreqAmp) { if (ucHighFreqAmp > 0 || usLowFreqAmp > 0) { // High-band frequency and low-band amplitude are actually nine-bits each so they // take a bit from the high-band amplitude and low-band frequency bytes respectively pRumble->rgucData[0] = usHighFreq & 0xFF; pRumble->rgucData[1] = ucHighFreqAmp | ((usHighFreq >> 8) & 0x01); pRumble->rgucData[2] = ucLowFreq | ((usLowFreqAmp >> 8) & 0x80); pRumble->rgucData[3] = usLowFreqAmp & 0xFF; #ifdef DEBUG_RUMBLE SDL_Log("Freq: %.2X %.2X %.2X, Amp: %.2X %.2X %.2X\n", usHighFreq & 0xFF, ((usHighFreq >> 8) & 0x01), ucLowFreq, ucHighFreqAmp, ((usLowFreqAmp >> 8) & 0x80), usLowFreqAmp & 0xFF); #endif } else { SetNeutralRumble(pRumble); } } static SDL_bool WriteRumble(SDL_DriverSwitch_Context *ctx) { /* Write into m_RumblePacket rather than a temporary buffer to allow the current rumble state * to be retained for subsequent rumble or subcommand packets sent to the controller */ ctx->m_RumblePacket.ucPacketType = k_eSwitchOutputReportIDs_Rumble; ctx->m_RumblePacket.ucPacketNumber = ctx->m_nCommandNumber; ctx->m_nCommandNumber = (ctx->m_nCommandNumber + 1) & 0xF; /* Refresh the rumble state periodically */ ctx->m_unRumbleSent = SDL_GetTicks(); return WritePacket(ctx, (Uint8 *)&ctx->m_RumblePacket, sizeof(ctx->m_RumblePacket)); } static SDL_bool BTrySetupUSB(SDL_DriverSwitch_Context *ctx) { /* We have to send a connection handshake to the controller when communicating over USB * before we're able to send it other commands. Luckily this command is not supported * over Bluetooth, so we can use the controller's lack of response as a way to * determine if the connection is over USB or Bluetooth */ if (!WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_Handshake, NULL, 0, SDL_TRUE)) { return SDL_FALSE; } if (!WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_HighSpeed, NULL, 0, SDL_TRUE)) { /* The 8BitDo M30 and SF30 Pro don't respond to this command, but otherwise work correctly */ /*return SDL_FALSE;*/ } if (!WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_Handshake, NULL, 0, SDL_TRUE)) { return SDL_FALSE; } return SDL_TRUE; } static SDL_bool SetVibrationEnabled(SDL_DriverSwitch_Context *ctx, Uint8 enabled) { return WriteSubcommand(ctx, k_eSwitchSubcommandIDs_EnableVibration, &enabled, sizeof(enabled), NULL); } static SDL_bool SetInputMode(SDL_DriverSwitch_Context *ctx, Uint8 input_mode) { return WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SetInputReportMode, &input_mode, 1, NULL); } static SDL_bool SetHomeLED(SDL_DriverSwitch_Context *ctx, Uint8 brightness) { Uint8 ucLedIntensity = 0; Uint8 rgucBuffer[4]; if (brightness > 0) { if (brightness < 65) { ucLedIntensity = (brightness + 5) / 10; } else { ucLedIntensity = (Uint8)SDL_ceilf(0xF * SDL_powf((float)brightness / 100.f, 2.13f)); } } rgucBuffer[0] = (0x0 << 4) | 0x1; /* 0 mini cycles (besides first), cycle duration 8ms */ rgucBuffer[1] = ((ucLedIntensity & 0xF) << 4) | 0x0; /* LED start intensity (0x0-0xF), 0 cycles (LED stays on at start intensity after first cycle) */ rgucBuffer[2] = ((ucLedIntensity & 0xF) << 4) | 0x0; /* First cycle LED intensity, 0x0 intensity for second cycle */ rgucBuffer[3] = (0x0 << 4) | 0x0; /* 8ms fade transition to first cycle, 8ms first cycle LED duration */ return WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SetHomeLight, rgucBuffer, sizeof(rgucBuffer), NULL); } static SDL_bool SetSlotLED(SDL_DriverSwitch_Context *ctx, Uint8 slot) { Uint8 led_data = (1 << slot); return WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SetPlayerLights, &led_data, sizeof(led_data), NULL); } static SDL_bool LoadStickCalibration(SDL_DriverSwitch_Context *ctx, Uint8 input_mode) { Uint8 *pStickCal; size_t stick, axis; SwitchSubcommandInputPacket_t *reply = NULL; /* Read Calibration Info */ SwitchSPIOpData_t readParams; readParams.unAddress = k_unSPIStickCalibrationStartOffset; readParams.ucLength = k_unSPIStickCalibrationLength; if (!WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SPIFlashRead, (uint8_t *)&readParams, sizeof(readParams), &reply)) { return SDL_FALSE; } /* Stick calibration values are 12-bits each and are packed by bit * For whatever reason the fields are in a different order for each stick * Left: X-Max, Y-Max, X-Center, Y-Center, X-Min, Y-Min * Right: X-Center, Y-Center, X-Min, Y-Min, X-Max, Y-Max */ pStickCal = reply->spiReadData.rgucReadData; /* Left stick */ ctx->m_StickCalData[0].axis[0].sMax = ((pStickCal[1] << 8) & 0xF00) | pStickCal[0]; /* X Axis max above center */ ctx->m_StickCalData[0].axis[1].sMax = (pStickCal[2] << 4) | (pStickCal[1] >> 4); /* Y Axis max above center */ ctx->m_StickCalData[0].axis[0].sCenter = ((pStickCal[4] << 8) & 0xF00) | pStickCal[3]; /* X Axis center */ ctx->m_StickCalData[0].axis[1].sCenter = (pStickCal[5] << 4) | (pStickCal[4] >> 4); /* Y Axis center */ ctx->m_StickCalData[0].axis[0].sMin = ((pStickCal[7] << 8) & 0xF00) | pStickCal[6]; /* X Axis min below center */ ctx->m_StickCalData[0].axis[1].sMin = (pStickCal[8] << 4) | (pStickCal[7] >> 4); /* Y Axis min below center */ /* Right stick */ ctx->m_StickCalData[1].axis[0].sCenter = ((pStickCal[10] << 8) & 0xF00) | pStickCal[9]; /* X Axis center */ ctx->m_StickCalData[1].axis[1].sCenter = (pStickCal[11] << 4) | (pStickCal[10] >> 4); /* Y Axis center */ ctx->m_StickCalData[1].axis[0].sMin = ((pStickCal[13] << 8) & 0xF00) | pStickCal[12]; /* X Axis min below center */ ctx->m_StickCalData[1].axis[1].sMin = (pStickCal[14] << 4) | (pStickCal[13] >> 4); /* Y Axis min below center */ ctx->m_StickCalData[1].axis[0].sMax = ((pStickCal[16] << 8) & 0xF00) | pStickCal[15]; /* X Axis max above center */ ctx->m_StickCalData[1].axis[1].sMax = (pStickCal[17] << 4) | (pStickCal[16] >> 4); /* Y Axis max above center */ /* Filter out any values that were uninitialized (0xFFF) in the SPI read */ for (stick = 0; stick < 2; ++stick) { for (axis = 0; axis < 2; ++axis) { if (ctx->m_StickCalData[stick].axis[axis].sCenter == 0xFFF) { ctx->m_StickCalData[stick].axis[axis].sCenter = 0; } if (ctx->m_StickCalData[stick].axis[axis].sMax == 0xFFF) { ctx->m_StickCalData[stick].axis[axis].sMax = 0; } if (ctx->m_StickCalData[stick].axis[axis].sMin == 0xFFF) { ctx->m_StickCalData[stick].axis[axis].sMin = 0; } } } if (input_mode == k_eSwitchInputReportIDs_SimpleControllerState) { for (stick = 0; stick < 2; ++stick) { for(axis = 0; axis < 2; ++axis) { ctx->m_StickExtents[stick].axis[axis].sMin = (Sint16)(SDL_MIN_SINT16 * 0.5f); ctx->m_StickExtents[stick].axis[axis].sMax = (Sint16)(SDL_MAX_SINT16 * 0.5f); } } } else { for (stick = 0; stick < 2; ++stick) { for(axis = 0; axis < 2; ++axis) { ctx->m_StickExtents[stick].axis[axis].sMin = -(Sint16)(ctx->m_StickCalData[stick].axis[axis].sMin * 0.7f); ctx->m_StickExtents[stick].axis[axis].sMax = (Sint16)(ctx->m_StickCalData[stick].axis[axis].sMax * 0.7f); } } } return SDL_TRUE; } static float fsel(float fComparand, float fValGE, float fLT) { return fComparand >= 0 ? fValGE : fLT; } static float RemapVal(float val, float A, float B, float C, float D) { if (A == B) { return fsel(val - B , D , C); } return C + (D - C) * (val - A) / (B - A); } static Sint16 ApplyStickCalibrationCentered(SDL_DriverSwitch_Context *ctx, int nStick, int nAxis, Sint16 sRawValue, Sint16 sCenter) { sRawValue -= sCenter; if (sRawValue > ctx->m_StickExtents[nStick].axis[nAxis].sMax) { ctx->m_StickExtents[nStick].axis[nAxis].sMax = sRawValue; } if (sRawValue < ctx->m_StickExtents[nStick].axis[nAxis].sMin) { ctx->m_StickExtents[nStick].axis[nAxis].sMin = sRawValue; } if (sRawValue > 0) { return (Sint16)(RemapVal(sRawValue, 0, ctx->m_StickExtents[nStick].axis[nAxis].sMax, 0, SDL_MAX_SINT16)); } else { return (Sint16)(RemapVal(sRawValue, ctx->m_StickExtents[nStick].axis[nAxis].sMin, 0, SDL_MIN_SINT16, 0)); } } static Sint16 ApplyStickCalibration(SDL_DriverSwitch_Context *ctx, int nStick, int nAxis, Sint16 sRawValue) { return ApplyStickCalibrationCentered(ctx, nStick, nAxis, sRawValue, ctx->m_StickCalData[nStick].axis[nAxis].sCenter); } static void SDLCALL SDL_GameControllerButtonReportingHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) { SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)userdata; ctx->m_bUseButtonLabels = SDL_GetStringBoolean(hint, SDL_TRUE); } static Uint8 RemapButton(SDL_DriverSwitch_Context *ctx, Uint8 button) { if (!ctx->m_bUseButtonLabels) { /* Use button positions */ if (ctx->m_bIsGameCube) { switch (button) { case SDL_CONTROLLER_BUTTON_B: return SDL_CONTROLLER_BUTTON_X; case SDL_CONTROLLER_BUTTON_X: return SDL_CONTROLLER_BUTTON_B; default: break; } } else { switch (button) { case SDL_CONTROLLER_BUTTON_A: return SDL_CONTROLLER_BUTTON_B; case SDL_CONTROLLER_BUTTON_B: return SDL_CONTROLLER_BUTTON_A; case SDL_CONTROLLER_BUTTON_X: return SDL_CONTROLLER_BUTTON_Y; case SDL_CONTROLLER_BUTTON_Y: return SDL_CONTROLLER_BUTTON_X; default: break; } } } return button; } static SDL_bool HIDAPI_DriverSwitch_InitDevice(SDL_HIDAPI_Device *device) { return HIDAPI_JoystickConnected(device, NULL, SDL_FALSE); } static int HIDAPI_DriverSwitch_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) { return -1; } static void HIDAPI_DriverSwitch_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) { } static SDL_bool HIDAPI_DriverSwitch_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) { SDL_DriverSwitch_Context *ctx; Uint8 input_mode; ctx = (SDL_DriverSwitch_Context *)SDL_calloc(1, sizeof(*ctx)); if (!ctx) { SDL_OutOfMemory(); goto error; } ctx->device = device; device->context = ctx; device->dev = hid_open_path(device->path, 0); if (!device->dev) { SDL_SetError("Couldn't open %s", device->path); goto error; } /* Find out whether or not we can send output reports */ ctx->m_bInputOnly = SDL_IsJoystickNintendoSwitchProInputOnly(device->vendor_id, device->product_id); if (!ctx->m_bInputOnly) { ctx->m_bHasHomeLED = HasHomeLED(device->vendor_id, device->product_id); /* Initialize rumble data */ SetNeutralRumble(&ctx->m_RumblePacket.rumbleData[0]); SetNeutralRumble(&ctx->m_RumblePacket.rumbleData[1]); /* Try setting up USB mode, and if that fails we're using Bluetooth */ if (!BTrySetupUSB(ctx)) { ctx->m_bUsingBluetooth = SDL_TRUE; } /* Determine the desired input mode (needed before loading stick calibration) */ if (ctx->m_bUsingBluetooth) { input_mode = k_eSwitchInputReportIDs_SimpleControllerState; } else { input_mode = k_eSwitchInputReportIDs_FullControllerState; } /* The official Nintendo Switch Pro Controller supports FullControllerState over bluetooth * just fine. We really should use that, or else the epowerlevel code in * HandleFullControllerState is completely pointless. We need full state if we want battery * level and we only care about battery level over bluetooth anyway. */ if (device->vendor_id == USB_VENDOR_NINTENDO && device->product_id == USB_PRODUCT_NINTENDO_SWITCH_PRO) { input_mode = k_eSwitchInputReportIDs_FullControllerState; } if (!LoadStickCalibration(ctx, input_mode)) { SDL_SetError("Couldn't load stick calibration"); goto error; } if (!SetVibrationEnabled(ctx, 1)) { SDL_SetError("Couldn't enable vibration"); goto error; } /* Set desired input mode */ if (!SetInputMode(ctx, input_mode)) { SDL_SetError("Couldn't set input mode"); goto error; } /* Start sending USB reports */ if (!ctx->m_bUsingBluetooth) { /* ForceUSB doesn't generate an ACK, so don't wait for a reply */ if (!WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_ForceUSB, NULL, 0, SDL_FALSE)) { SDL_SetError("Couldn't start USB reports"); goto error; } } /* Set the LED state */ if (ctx->m_bHasHomeLED) { SetHomeLED(ctx, 100); } SetSlotLED(ctx, (joystick->instance_id % 4)); } if (IsGameCubeFormFactor(device->vendor_id, device->product_id)) { /* This is a controller shaped like a GameCube controller, with a large central A button */ ctx->m_bIsGameCube = SDL_TRUE; } SDL_AddHintCallback(SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS, SDL_GameControllerButtonReportingHintChanged, ctx); /* Initialize the joystick capabilities */ joystick->nbuttons = SDL_CONTROLLER_BUTTON_MAX; joystick->naxes = SDL_CONTROLLER_AXIS_MAX; joystick->epowerlevel = SDL_JOYSTICK_POWER_WIRED; return SDL_TRUE; error: if (device->dev) { hid_close(device->dev); device->dev = NULL; } if (device->context) { SDL_free(device->context); device->context = NULL; } return SDL_FALSE; } static int HIDAPI_DriverSwitch_ActuallyRumbleJoystick(SDL_DriverSwitch_Context *ctx, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { /* Experimentally determined rumble values. These will only matter on some controllers as tested ones * seem to disregard these and just use any non-zero rumble values as a binary flag for constant rumble * * More information about these values can be found here: * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/rumble_data_table.md */ const Uint16 k_usHighFreq = 0x0074; const Uint8 k_ucHighFreqAmp = 0xBE; const Uint8 k_ucLowFreq = 0x3D; const Uint16 k_usLowFreqAmp = 0x806F; if (low_frequency_rumble) { EncodeRumble(&ctx->m_RumblePacket.rumbleData[0], k_usHighFreq, k_ucHighFreqAmp, k_ucLowFreq, k_usLowFreqAmp); } else { SetNeutralRumble(&ctx->m_RumblePacket.rumbleData[0]); } if (high_frequency_rumble) { EncodeRumble(&ctx->m_RumblePacket.rumbleData[1], k_usHighFreq, k_ucHighFreqAmp, k_ucLowFreq, k_usLowFreqAmp); } else { SetNeutralRumble(&ctx->m_RumblePacket.rumbleData[1]); } ctx->m_bRumbleActive = (low_frequency_rumble || high_frequency_rumble) ? SDL_TRUE : SDL_FALSE; if (!WriteRumble(ctx)) { SDL_SetError("Couldn't send rumble packet"); return -1; } return 0; } static int HIDAPI_DriverSwitch_SendPendingRumble(SDL_DriverSwitch_Context *ctx) { if ((SDL_GetTicks() - ctx->m_unRumbleSent) < RUMBLE_WRITE_FREQUENCY_MS) { return 0; } if (ctx->m_bRumblePending) { Uint16 low_frequency_rumble = (Uint16)(ctx->m_unRumblePending >> 16); Uint16 high_frequency_rumble = (Uint16)ctx->m_unRumblePending; #ifdef DEBUG_RUMBLE SDL_Log("Sent pending rumble %d/%d\n", low_frequency_rumble, high_frequency_rumble); #endif ctx->m_bRumblePending = SDL_FALSE; ctx->m_unRumblePending = 0; return HIDAPI_DriverSwitch_ActuallyRumbleJoystick(ctx, low_frequency_rumble, high_frequency_rumble); } if (ctx->m_bRumbleZeroPending) { ctx->m_bRumbleZeroPending = SDL_FALSE; #ifdef DEBUG_RUMBLE SDL_Log("Sent pending zero rumble\n"); #endif return HIDAPI_DriverSwitch_ActuallyRumbleJoystick(ctx, 0, 0); } return 0; } static int HIDAPI_DriverSwitch_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context; if (ctx->m_bRumblePending) { if (HIDAPI_DriverSwitch_SendPendingRumble(ctx) < 0) { return -1; } } if (ctx->m_bUsingBluetooth && (SDL_GetTicks() - ctx->m_unRumbleSent) < RUMBLE_WRITE_FREQUENCY_MS) { if (low_frequency_rumble || high_frequency_rumble) { Uint32 unRumblePending = ((Uint32)low_frequency_rumble << 16) | high_frequency_rumble; /* Keep the highest rumble intensity in the given interval */ if (unRumblePending > ctx->m_unRumblePending) { ctx->m_unRumblePending = unRumblePending; } ctx->m_bRumblePending = SDL_TRUE; ctx->m_bRumbleZeroPending = SDL_FALSE; } else { /* When rumble is complete, turn it off */ ctx->m_bRumbleZeroPending = SDL_TRUE; } return 0; } #ifdef DEBUG_RUMBLE SDL_Log("Sent rumble %d/%d\n", low_frequency_rumble, high_frequency_rumble); #endif return HIDAPI_DriverSwitch_ActuallyRumbleJoystick(ctx, low_frequency_rumble, high_frequency_rumble); } static void HandleInputOnlyControllerState(SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchInputOnlyControllerStatePacket_t *packet) { Sint16 axis; if (packet->rgucButtons[0] != ctx->m_lastInputOnlyState.rgucButtons[0]) { Uint8 data = packet->rgucButtons[0]; SDL_PrivateJoystickButton(joystick, RemapButton(ctx, SDL_CONTROLLER_BUTTON_A), (data & 0x04) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, RemapButton(ctx, SDL_CONTROLLER_BUTTON_B), (data & 0x02) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, RemapButton(ctx, SDL_CONTROLLER_BUTTON_X), (data & 0x08) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, RemapButton(ctx, SDL_CONTROLLER_BUTTON_Y), (data & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSHOULDER, (data & 0x10) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, (data & 0x20) ? SDL_PRESSED : SDL_RELEASED); axis = (data & 0x40) ? 32767 : -32768; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, axis); axis = (data & 0x80) ? 32767 : -32768; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, axis); } if (packet->rgucButtons[1] != ctx->m_lastInputOnlyState.rgucButtons[1]) { Uint8 data = packet->rgucButtons[1]; SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_BACK, (data & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_START, (data & 0x02) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSTICK, (data & 0x04) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSTICK, (data & 0x08) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, (data & 0x10) ? SDL_PRESSED : SDL_RELEASED); } if (packet->ucStickHat != ctx->m_lastInputOnlyState.ucStickHat) { SDL_bool dpad_up = SDL_FALSE; SDL_bool dpad_down = SDL_FALSE; SDL_bool dpad_left = SDL_FALSE; SDL_bool dpad_right = SDL_FALSE; switch (packet->ucStickHat) { case 0: dpad_up = SDL_TRUE; break; case 1: dpad_up = SDL_TRUE; dpad_right = SDL_TRUE; break; case 2: dpad_right = SDL_TRUE; break; case 3: dpad_right = SDL_TRUE; dpad_down = SDL_TRUE; break; case 4: dpad_down = SDL_TRUE; break; case 5: dpad_left = SDL_TRUE; dpad_down = SDL_TRUE; break; case 6: dpad_left = SDL_TRUE; break; case 7: dpad_up = SDL_TRUE; dpad_left = SDL_TRUE; break; default: break; } SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_DOWN, dpad_down); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_UP, dpad_up); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_RIGHT, dpad_right); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_LEFT, dpad_left); } if (packet->rgucJoystickLeft[0] != ctx->m_lastInputOnlyState.rgucJoystickLeft[0]) { axis = (Sint16)(RemapVal(packet->rgucJoystickLeft[0], SDL_MIN_UINT8, SDL_MAX_UINT8, SDL_MIN_SINT16, SDL_MAX_SINT16)); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTX, axis); } if (packet->rgucJoystickLeft[1] != ctx->m_lastInputOnlyState.rgucJoystickLeft[1]) { axis = (Sint16)(RemapVal(packet->rgucJoystickLeft[1], SDL_MIN_UINT8, SDL_MAX_UINT8, SDL_MIN_SINT16, SDL_MAX_SINT16)); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTY, axis); } if (packet->rgucJoystickRight[0] != ctx->m_lastInputOnlyState.rgucJoystickRight[0]) { axis = (Sint16)(RemapVal(packet->rgucJoystickRight[0], SDL_MIN_UINT8, SDL_MAX_UINT8, SDL_MIN_SINT16, SDL_MAX_SINT16)); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTX, axis); } if (packet->rgucJoystickRight[1] != ctx->m_lastInputOnlyState.rgucJoystickRight[1]) { axis = (Sint16)(RemapVal(packet->rgucJoystickRight[1], SDL_MIN_UINT8, SDL_MAX_UINT8, SDL_MIN_SINT16, SDL_MAX_SINT16)); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTY, axis); } ctx->m_lastInputOnlyState = *packet; } static void HandleSimpleControllerState(SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchSimpleStatePacket_t *packet) { /* 0x8000 is the neutral value for all joystick axes */ const Uint16 usJoystickCenter = 0x8000; Sint16 axis; if (packet->rgucButtons[0] != ctx->m_lastSimpleState.rgucButtons[0]) { Uint8 data = packet->rgucButtons[0]; SDL_PrivateJoystickButton(joystick, RemapButton(ctx, SDL_CONTROLLER_BUTTON_A), (data & 0x02) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, RemapButton(ctx, SDL_CONTROLLER_BUTTON_B), (data & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, RemapButton(ctx, SDL_CONTROLLER_BUTTON_X), (data & 0x08) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, RemapButton(ctx, SDL_CONTROLLER_BUTTON_Y), (data & 0x04) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSHOULDER, (data & 0x10) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, (data & 0x20) ? SDL_PRESSED : SDL_RELEASED); axis = (data & 0x40) ? 32767 : -32768; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, axis); axis = (data & 0x80) ? 32767 : -32768; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, axis); } if (packet->rgucButtons[1] != ctx->m_lastSimpleState.rgucButtons[1]) { Uint8 data = packet->rgucButtons[1]; SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_BACK, (data & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_START, (data & 0x02) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSTICK, (data & 0x04) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSTICK, (data & 0x08) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, (data & 0x10) ? SDL_PRESSED : SDL_RELEASED); } if (packet->ucStickHat != ctx->m_lastSimpleState.ucStickHat) { SDL_bool dpad_up = SDL_FALSE; SDL_bool dpad_down = SDL_FALSE; SDL_bool dpad_left = SDL_FALSE; SDL_bool dpad_right = SDL_FALSE; switch (packet->ucStickHat) { case 0: dpad_up = SDL_TRUE; break; case 1: dpad_up = SDL_TRUE; dpad_right = SDL_TRUE; break; case 2: dpad_right = SDL_TRUE; break; case 3: dpad_right = SDL_TRUE; dpad_down = SDL_TRUE; break; case 4: dpad_down = SDL_TRUE; break; case 5: dpad_left = SDL_TRUE; dpad_down = SDL_TRUE; break; case 6: dpad_left = SDL_TRUE; break; case 7: dpad_up = SDL_TRUE; dpad_left = SDL_TRUE; break; default: break; } SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_DOWN, dpad_down); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_UP, dpad_up); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_RIGHT, dpad_right); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_LEFT, dpad_left); } axis = ApplyStickCalibrationCentered(ctx, 0, 0, packet->sJoystickLeft[0], (Sint16)usJoystickCenter); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTX, axis); axis = ApplyStickCalibrationCentered(ctx, 0, 1, packet->sJoystickLeft[1], (Sint16)usJoystickCenter); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTY, axis); axis = ApplyStickCalibrationCentered(ctx, 1, 0, packet->sJoystickRight[0], (Sint16)usJoystickCenter); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTX, axis); axis = ApplyStickCalibrationCentered(ctx, 1, 1, packet->sJoystickRight[1], (Sint16)usJoystickCenter); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTY, axis); ctx->m_lastSimpleState = *packet; } static void HandleFullControllerState(SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchStatePacket_t *packet) { Sint16 axis; if (packet->controllerState.rgucButtons[0] != ctx->m_lastFullState.controllerState.rgucButtons[0]) { Uint8 data = packet->controllerState.rgucButtons[0]; SDL_PrivateJoystickButton(joystick, RemapButton(ctx, SDL_CONTROLLER_BUTTON_A), (data & 0x08) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, RemapButton(ctx, SDL_CONTROLLER_BUTTON_B), (data & 0x04) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, RemapButton(ctx, SDL_CONTROLLER_BUTTON_X), (data & 0x02) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, RemapButton(ctx, SDL_CONTROLLER_BUTTON_Y), (data & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, (data & 0x40) ? SDL_PRESSED : SDL_RELEASED); axis = (data & 0x80) ? 32767 : -32768; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, axis); } if (packet->controllerState.rgucButtons[1] != ctx->m_lastFullState.controllerState.rgucButtons[1]) { Uint8 data = packet->controllerState.rgucButtons[1]; SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_BACK, (data & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_START, (data & 0x02) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSTICK, (data & 0x04) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSTICK, (data & 0x08) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, (data & 0x10) ? SDL_PRESSED : SDL_RELEASED); } if (packet->controllerState.rgucButtons[2] != ctx->m_lastFullState.controllerState.rgucButtons[2]) { Uint8 data = packet->controllerState.rgucButtons[2]; SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_DOWN, (data & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_UP, (data & 0x02) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_RIGHT, (data & 0x04) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_LEFT, (data & 0x08) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSHOULDER, (data & 0x40) ? SDL_PRESSED : SDL_RELEASED); axis = (data & 0x80) ? 32767 : -32768; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, axis); } axis = packet->controllerState.rgucJoystickLeft[0] | ((packet->controllerState.rgucJoystickLeft[1] & 0xF) << 8); axis = ApplyStickCalibration(ctx, 0, 0, axis); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTX, axis); axis = ((packet->controllerState.rgucJoystickLeft[1] & 0xF0) >> 4) | (packet->controllerState.rgucJoystickLeft[2] << 4); axis = ApplyStickCalibration(ctx, 0, 1, axis); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTY, ~axis); axis = packet->controllerState.rgucJoystickRight[0] | ((packet->controllerState.rgucJoystickRight[1] & 0xF) << 8); axis = ApplyStickCalibration(ctx, 1, 0, axis); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTX, axis); axis = ((packet->controllerState.rgucJoystickRight[1] & 0xF0) >> 4) | (packet->controllerState.rgucJoystickRight[2] << 4); axis = ApplyStickCalibration(ctx, 1, 1, axis); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTY, ~axis); /* High nibble of battery/connection byte is battery level, low nibble is connection status * LSB of connection nibble is USB/Switch connection status */ if (packet->controllerState.ucBatteryAndConnection & 0x1) { joystick->epowerlevel = SDL_JOYSTICK_POWER_WIRED; } else { /* LSB of the battery nibble is used to report charging. * The battery level is reported from 0(empty)-8(full) */ int level = (packet->controllerState.ucBatteryAndConnection & 0xE0) >> 4; if (level == 0) { joystick->epowerlevel = SDL_JOYSTICK_POWER_EMPTY; } else if (level <= 2) { joystick->epowerlevel = SDL_JOYSTICK_POWER_LOW; } else if (level <= 6) { joystick->epowerlevel = SDL_JOYSTICK_POWER_MEDIUM; } else { joystick->epowerlevel = SDL_JOYSTICK_POWER_FULL; } } ctx->m_lastFullState = *packet; } static SDL_bool HIDAPI_DriverSwitch_UpdateDevice(SDL_HIDAPI_Device *device) { SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context; SDL_Joystick *joystick = NULL; int size; if (device->num_joysticks > 0) { joystick = SDL_JoystickFromInstanceID(device->joysticks[0]); } if (!joystick) { return SDL_FALSE; } while ((size = ReadInput(ctx)) > 0) { if (ctx->m_bInputOnly) { HandleInputOnlyControllerState(joystick, ctx, (SwitchInputOnlyControllerStatePacket_t *)&ctx->m_rgucReadBuffer[0]); } else { switch (ctx->m_rgucReadBuffer[0]) { case k_eSwitchInputReportIDs_SimpleControllerState: HandleSimpleControllerState(joystick, ctx, (SwitchSimpleStatePacket_t *)&ctx->m_rgucReadBuffer[1]); break; case k_eSwitchInputReportIDs_FullControllerState: HandleFullControllerState(joystick, ctx, (SwitchStatePacket_t *)&ctx->m_rgucReadBuffer[1]); break; default: break; } } } if (ctx->m_bRumblePending || ctx->m_bRumbleZeroPending) { HIDAPI_DriverSwitch_SendPendingRumble(ctx); } else if (ctx->m_bRumbleActive && SDL_TICKS_PASSED(SDL_GetTicks(), ctx->m_unRumbleSent + RUMBLE_REFRESH_FREQUENCY_MS)) { #ifdef DEBUG_RUMBLE SDL_Log("Sent continuing rumble\n"); #endif WriteRumble(ctx); } if (size < 0) { /* Read error, device is disconnected */ HIDAPI_JoystickDisconnected(device, joystick->instance_id, SDL_FALSE); } return (size >= 0); } static void HIDAPI_DriverSwitch_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) { SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context; if (!ctx->m_bInputOnly) { /* Restore simple input mode for other applications */ SetInputMode(ctx, k_eSwitchInputReportIDs_SimpleControllerState); } SDL_DelHintCallback(SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS, SDL_GameControllerButtonReportingHintChanged, ctx); hid_close(device->dev); device->dev = NULL; SDL_free(device->context); device->context = NULL; } static void HIDAPI_DriverSwitch_FreeDevice(SDL_HIDAPI_Device *device) { } SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverSwitch = { SDL_HINT_JOYSTICK_HIDAPI_SWITCH, SDL_TRUE, HIDAPI_DriverSwitch_IsSupportedDevice, HIDAPI_DriverSwitch_GetDeviceName, HIDAPI_DriverSwitch_InitDevice, HIDAPI_DriverSwitch_GetDevicePlayerIndex, HIDAPI_DriverSwitch_SetDevicePlayerIndex, HIDAPI_DriverSwitch_UpdateDevice, HIDAPI_DriverSwitch_OpenJoystick, HIDAPI_DriverSwitch_RumbleJoystick, HIDAPI_DriverSwitch_CloseJoystick, HIDAPI_DriverSwitch_FreeDevice, NULL }; #endif /* SDL_JOYSTICK_HIDAPI_SWITCH */ #endif /* SDL_JOYSTICK_HIDAPI */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/hidapi/SDL_hidapi_switch.c
C
apache-2.0
48,909
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_HIDAPI #include "SDL_hints.h" #include "SDL_events.h" #include "SDL_timer.h" #include "SDL_joystick.h" #include "SDL_gamecontroller.h" #include "../SDL_sysjoystick.h" #include "SDL_hidapijoystick_c.h" #include "SDL_hidapi_rumble.h" #ifdef SDL_JOYSTICK_HIDAPI_XBOX360 #ifdef __WIN32__ #define SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT /* This requires the Windows 10 SDK to build */ /*#define SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT*/ #endif #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT #include "../../core/windows/SDL_xinput.h" #endif #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT #include "../../core/windows/SDL_windows.h" typedef struct WindowsGamingInputGamepadState WindowsGamingInputGamepadState; #define GamepadButtons_GUIDE 0x40000000 #define COBJMACROS #include "windows.gaming.input.h" #endif #if defined(SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT) || defined(SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT) #define SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING #endif typedef struct { Uint8 last_state[USB_PACKET_LENGTH]; #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING Uint32 match_state; /* Low 16 bits for button states, high 16 for 4 4bit axes */ Uint32 last_state_packet; #endif #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT SDL_bool xinput_enabled; SDL_bool xinput_correlated; Uint8 xinput_correlation_id; Uint8 xinput_correlation_count; Uint8 xinput_uncorrelate_count; Uint8 xinput_slot; #endif #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT SDL_bool wgi_correlated; Uint8 wgi_correlation_id; Uint8 wgi_correlation_count; Uint8 wgi_uncorrelate_count; WindowsGamingInputGamepadState *wgi_slot; #endif } SDL_DriverXbox360_Context; #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING static struct { Uint32 last_state_packet; SDL_Joystick *joystick; SDL_Joystick *last_joystick; } guide_button_candidate; typedef struct WindowsMatchState { SHORT match_axes[4]; #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT WORD xinput_buttons; #endif #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT Uint32 wgi_buttons; #endif SDL_bool any_data; } WindowsMatchState; static void HIDAPI_DriverXbox360_FillMatchState(WindowsMatchState *state, Uint32 match_state) { int ii; state->any_data = SDL_FALSE; /* SHORT state->match_axes[4] = { (match_state & 0x000F0000) >> 4, (match_state & 0x00F00000) >> 8, (match_state & 0x0F000000) >> 12, (match_state & 0xF0000000) >> 16, }; */ for (ii = 0; ii < 4; ii++) { state->match_axes[ii] = (match_state & (0x000F0000 << (ii * 4))) >> (4 + ii * 4); if ((Uint32)(state->match_axes[ii] + 0x1000) > 0x2000) { /* match_state bit is not 0xF, 0x1, or 0x2 */ state->any_data = SDL_TRUE; } } #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT /* Match axes by checking if the distance between the high 4 bits of axis and the 4 bits from match_state is 1 or less */ #define XInputAxesMatch(gamepad) (\ (Uint32)(gamepad.sThumbLX - state->match_axes[0] + 0x1000) <= 0x2fff && \ (Uint32)(~gamepad.sThumbLY - state->match_axes[1] + 0x1000) <= 0x2fff && \ (Uint32)(gamepad.sThumbRX - state->match_axes[2] + 0x1000) <= 0x2fff && \ (Uint32)(~gamepad.sThumbRY - state->match_axes[3] + 0x1000) <= 0x2fff) /* Explicit #define XInputAxesMatch(gamepad) (\ SDL_abs((Sint8)((gamepad.sThumbLX & 0xF000) >> 8) - ((match_state & 0x000F0000) >> 12)) <= 0x10 && \ SDL_abs((Sint8)((~gamepad.sThumbLY & 0xF000) >> 8) - ((match_state & 0x00F00000) >> 16)) <= 0x10 && \ SDL_abs((Sint8)((gamepad.sThumbRX & 0xF000) >> 8) - ((match_state & 0x0F000000) >> 20)) <= 0x10 && \ SDL_abs((Sint8)((~gamepad.sThumbRY & 0xF000) >> 8) - ((match_state & 0xF0000000) >> 24)) <= 0x10) */ state->xinput_buttons = /* Bitwise map .RLDUWVQTS.KYXBA -> YXBA..WVQTKSRLDU */ match_state << 12 | (match_state & 0x0780) >> 1 | (match_state & 0x0010) << 1 | (match_state & 0x0040) >> 2 | (match_state & 0x7800) >> 11; /* Explicit ((match_state & (1<<SDL_CONTROLLER_BUTTON_A)) ? XINPUT_GAMEPAD_A : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_B)) ? XINPUT_GAMEPAD_B : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_X)) ? XINPUT_GAMEPAD_X : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_Y)) ? XINPUT_GAMEPAD_Y : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_BACK)) ? XINPUT_GAMEPAD_BACK : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_START)) ? XINPUT_GAMEPAD_START : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_LEFTSTICK)) ? XINPUT_GAMEPAD_LEFT_THUMB : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_RIGHTSTICK)) ? XINPUT_GAMEPAD_RIGHT_THUMB: 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_LEFTSHOULDER)) ? XINPUT_GAMEPAD_LEFT_SHOULDER : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)) ? XINPUT_GAMEPAD_RIGHT_SHOULDER : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_UP)) ? XINPUT_GAMEPAD_DPAD_UP : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_DOWN)) ? XINPUT_GAMEPAD_DPAD_DOWN : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_LEFT)) ? XINPUT_GAMEPAD_DPAD_LEFT : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) ? XINPUT_GAMEPAD_DPAD_RIGHT : 0); */ if (state->xinput_buttons) state->any_data = SDL_TRUE; #endif #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT /* Match axes by checking if the distance between the high 4 bits of axis and the 4 bits from match_state is 1 or less */ #define WindowsGamingInputAxesMatch(gamepad) (\ (Uint16)(((Sint16)(gamepad.LeftThumbstickX * SDL_MAX_SINT16) & 0xF000) - state->match_axes[0] + 0x1000) <= 0x2fff && \ (Uint16)((~(Sint16)(gamepad.LeftThumbstickY * SDL_MAX_SINT16) & 0xF000) - state->match_axes[1] + 0x1000) <= 0x2fff && \ (Uint16)(((Sint16)(gamepad.RightThumbstickX * SDL_MAX_SINT16) & 0xF000) - state->match_axes[2] + 0x1000) <= 0x2fff && \ (Uint16)((~(Sint16)(gamepad.RightThumbstickY * SDL_MAX_SINT16) & 0xF000) - state->match_axes[3] + 0x1000) <= 0x2fff) state->wgi_buttons = /* Bitwise map .RLD UWVQ TS.K YXBA -> ..QT WVRL DUYX BAKS */ /* RStick/LStick (QT) RShould/LShould (WV) DPad R/L/D/U YXBA bac(K) (S)tart */ (match_state & 0x0180) << 5 | (match_state & 0x0600) << 1 | (match_state & 0x7800) >> 5 | (match_state & 0x000F) << 2 | (match_state & 0x0010) >> 3 | (match_state & 0x0040) >> 6; /* Explicit ((match_state & (1<<SDL_CONTROLLER_BUTTON_A)) ? GamepadButtons_A : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_B)) ? GamepadButtons_B : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_X)) ? GamepadButtons_X : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_Y)) ? GamepadButtons_Y : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_BACK)) ? GamepadButtons_View : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_START)) ? GamepadButtons_Menu : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_LEFTSTICK)) ? GamepadButtons_LeftThumbstick : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_RIGHTSTICK)) ? GamepadButtons_RightThumbstick: 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_LEFTSHOULDER)) ? GamepadButtons_LeftShoulder: 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)) ? GamepadButtons_RightShoulder: 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_UP)) ? GamepadButtons_DPadUp : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_DOWN)) ? GamepadButtons_DPadDown : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_LEFT)) ? GamepadButtons_DPadLeft : 0) | ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) ? GamepadButtons_DPadRight : 0); */ if (state->wgi_buttons) state->any_data = SDL_TRUE; #endif } #endif #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT static struct { XINPUT_STATE_EX state; SDL_bool connected; /* Currently has an active XInput device */ SDL_bool used; /* Is currently mapped to an SDL device */ Uint8 correlation_id; } xinput_state[XUSER_MAX_COUNT]; static SDL_bool xinput_device_change = SDL_TRUE; static SDL_bool xinput_state_dirty = SDL_TRUE; static void HIDAPI_DriverXbox360_UpdateXInput() { DWORD user_index; if (xinput_device_change) { for (user_index = 0; user_index < XUSER_MAX_COUNT; user_index++) { XINPUT_CAPABILITIES capabilities; xinput_state[user_index].connected = XINPUTGETCAPABILITIES(user_index, XINPUT_FLAG_GAMEPAD, &capabilities) == ERROR_SUCCESS; } xinput_device_change = SDL_FALSE; xinput_state_dirty = SDL_TRUE; } if (xinput_state_dirty) { xinput_state_dirty = SDL_FALSE; for (user_index = 0; user_index < SDL_arraysize(xinput_state); ++user_index) { if (xinput_state[user_index].connected) { if (XINPUTGETSTATE(user_index, &xinput_state[user_index].state) != ERROR_SUCCESS) { xinput_state[user_index].connected = SDL_FALSE; } } } } } static void HIDAPI_DriverXbox360_MarkXInputSlotUsed(Uint8 xinput_slot) { if (xinput_slot != XUSER_INDEX_ANY) { xinput_state[xinput_slot].used = SDL_TRUE; } } static void HIDAPI_DriverXbox360_MarkXInputSlotFree(Uint8 xinput_slot) { if (xinput_slot != XUSER_INDEX_ANY) { xinput_state[xinput_slot].used = SDL_FALSE; } } static SDL_bool HIDAPI_DriverXbox360_MissingXInputSlot() { int ii; for (ii = 0; ii < SDL_arraysize(xinput_state); ii++) { if (xinput_state[ii].connected && !xinput_state[ii].used) { return SDL_TRUE; } } return SDL_FALSE; } static SDL_bool HIDAPI_DriverXbox360_XInputSlotMatches(const WindowsMatchState *state, Uint8 slot_idx) { if (xinput_state[slot_idx].connected) { WORD xinput_buttons = xinput_state[slot_idx].state.Gamepad.wButtons; if ((xinput_buttons & ~XINPUT_GAMEPAD_GUIDE) == state->xinput_buttons && XInputAxesMatch(xinput_state[slot_idx].state.Gamepad)) { return SDL_TRUE; } } return SDL_FALSE; } static SDL_bool HIDAPI_DriverXbox360_GuessXInputSlot(const WindowsMatchState *state, Uint8 *correlation_id, Uint8 *slot_idx) { int user_index; int match_count; *slot_idx = 0; match_count = 0; for (user_index = 0; user_index < XUSER_MAX_COUNT; ++user_index) { if (!xinput_state[user_index].used && HIDAPI_DriverXbox360_XInputSlotMatches(state, user_index)) { ++match_count; *slot_idx = (Uint8)user_index; /* Incrementing correlation_id for any match, as negative evidence for others being correlated */ *correlation_id = ++xinput_state[user_index].correlation_id; } } /* Only return a match if we match exactly one, and we have some non-zero data (buttons or axes) that matched. Note that we're still invalidating *other* potential correlations if we have more than one match or we have no data. */ if (match_count == 1 && state->any_data) { return SDL_TRUE; } return SDL_FALSE; } #endif /* SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT */ #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT typedef struct WindowsGamingInputGamepadState { __x_ABI_CWindows_CGaming_CInput_CIGamepad *gamepad; struct __x_ABI_CWindows_CGaming_CInput_CGamepadReading state; SDL_DriverXbox360_Context *correlated_context; SDL_bool used; /* Is currently mapped to an SDL device */ SDL_bool connected; /* Just used during update to track disconnected */ Uint8 correlation_id; struct __x_ABI_CWindows_CGaming_CInput_CGamepadVibration vibration; } WindowsGamingInputGamepadState; static struct { WindowsGamingInputGamepadState **per_gamepad; int per_gamepad_count; SDL_bool initialized; SDL_bool dirty; SDL_bool need_device_list_update; int ref_count; __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics *gamepad_statics; } wgi_state; static void HIDAPI_DriverXbox360_MarkWindowsGamingInputSlotUsed(WindowsGamingInputGamepadState *wgi_slot, SDL_DriverXbox360_Context *ctx) { wgi_slot->used = SDL_TRUE; wgi_slot->correlated_context = ctx; } static void HIDAPI_DriverXbox360_MarkWindowsGamingInputSlotFree(WindowsGamingInputGamepadState *wgi_slot) { wgi_slot->used = SDL_FALSE; wgi_slot->correlated_context = NULL; } static SDL_bool HIDAPI_DriverXbox360_MissingWindowsGamingInputSlot() { int ii; for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) { if (!wgi_state.per_gamepad[ii]->used) { return SDL_TRUE; } } return SDL_FALSE; } static void HIDAPI_DriverXbox360_UpdateWindowsGamingInput() { int ii; if (!wgi_state.gamepad_statics) return; if (!wgi_state.dirty) return; wgi_state.dirty = SDL_FALSE; if (wgi_state.need_device_list_update) { wgi_state.need_device_list_update = SDL_FALSE; for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) { wgi_state.per_gamepad[ii]->connected = SDL_FALSE; } HRESULT hr; __FIVectorView_1_Windows__CGaming__CInput__CGamepad *gamepads; hr = __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_get_Gamepads(wgi_state.gamepad_statics, &gamepads); if (SUCCEEDED(hr)) { unsigned int num_gamepads; hr = __FIVectorView_1_Windows__CGaming__CInput__CGamepad_get_Size(gamepads, &num_gamepads); if (SUCCEEDED(hr)) { unsigned int i; for (i = 0; i < num_gamepads; ++i) { __x_ABI_CWindows_CGaming_CInput_CIGamepad *gamepad; hr = __FIVectorView_1_Windows__CGaming__CInput__CGamepad_GetAt(gamepads, i, &gamepad); if (SUCCEEDED(hr)) { SDL_bool found = SDL_FALSE; int jj; for (jj = 0; jj < wgi_state.per_gamepad_count ; jj++) { if (wgi_state.per_gamepad[jj]->gamepad == gamepad) { found = SDL_TRUE; wgi_state.per_gamepad[jj]->connected = SDL_TRUE; break; } } if (!found) { /* New device, add it */ wgi_state.per_gamepad_count++; wgi_state.per_gamepad = SDL_realloc(wgi_state.per_gamepad, sizeof(wgi_state.per_gamepad[0]) * wgi_state.per_gamepad_count); if (!wgi_state.per_gamepad) { SDL_OutOfMemory(); return; } WindowsGamingInputGamepadState *gamepad_state = SDL_calloc(1, sizeof(*gamepad_state)); if (!gamepad_state) { SDL_OutOfMemory(); return; } wgi_state.per_gamepad[wgi_state.per_gamepad_count - 1] = gamepad_state; gamepad_state->gamepad = gamepad; gamepad_state->connected = SDL_TRUE; } else { /* Already tracked */ __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(gamepad); } } } for (ii = wgi_state.per_gamepad_count - 1; ii >= 0; ii--) { WindowsGamingInputGamepadState *gamepad_state = wgi_state.per_gamepad[ii]; if (!gamepad_state->connected) { /* Device missing, must be disconnected */ if (gamepad_state->correlated_context) { gamepad_state->correlated_context->wgi_correlated = SDL_FALSE; gamepad_state->correlated_context->wgi_slot = NULL; } __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(gamepad_state->gamepad); SDL_free(gamepad_state); wgi_state.per_gamepad[ii] = wgi_state.per_gamepad[wgi_state.per_gamepad_count - 1]; --wgi_state.per_gamepad_count; } } } __FIVectorView_1_Windows__CGaming__CInput__CGamepad_Release(gamepads); } } /* need_device_list_update */ for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) { HRESULT hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_GetCurrentReading(wgi_state.per_gamepad[ii]->gamepad, &wgi_state.per_gamepad[ii]->state); if (!SUCCEEDED(hr)) { wgi_state.per_gamepad[ii]->connected = SDL_FALSE; /* Not used by anything, currently */ } } } static void HIDAPI_DriverXbox360_InitWindowsGamingInput(SDL_DriverXbox360_Context *ctx) { wgi_state.need_device_list_update = SDL_TRUE; wgi_state.ref_count++; if (!wgi_state.initialized) { /* I think this takes care of RoInitialize() in a way that is compatible with the rest of SDL */ if (FAILED(WIN_CoInitialize())) { return; } wgi_state.initialized = SDL_TRUE; wgi_state.dirty = SDL_TRUE; static const IID SDL_IID_IGamepadStatics = { 0x8BBCE529, 0xD49C, 0x39E9, { 0x95, 0x60, 0xE4, 0x7D, 0xDE, 0x96, 0xB7, 0xC8 } }; HRESULT hr; HMODULE hModule = LoadLibraryA("combase.dll"); if (hModule != NULL) { typedef HRESULT (WINAPI *WindowsCreateString_t)(PCNZWCH sourceString, UINT32 length, HSTRING* string); typedef HRESULT (WINAPI *WindowsDeleteString_t)(HSTRING string); typedef HRESULT (WINAPI *RoGetActivationFactory_t)(HSTRING activatableClassId, REFIID iid, void** factory); WindowsCreateString_t WindowsCreateStringFunc = (WindowsCreateString_t)GetProcAddress(hModule, "WindowsCreateString"); WindowsDeleteString_t WindowsDeleteStringFunc = (WindowsDeleteString_t)GetProcAddress(hModule, "WindowsDeleteString"); RoGetActivationFactory_t RoGetActivationFactoryFunc = (RoGetActivationFactory_t)GetProcAddress(hModule, "RoGetActivationFactory"); if (WindowsCreateStringFunc && WindowsDeleteStringFunc && RoGetActivationFactoryFunc) { LPTSTR pNamespace = L"Windows.Gaming.Input.Gamepad"; HSTRING hNamespaceString; hr = WindowsCreateStringFunc(pNamespace, SDL_wcslen(pNamespace), &hNamespaceString); if (SUCCEEDED(hr)) { RoGetActivationFactoryFunc(hNamespaceString, &SDL_IID_IGamepadStatics, &wgi_state.gamepad_statics); WindowsDeleteStringFunc(hNamespaceString); } } FreeLibrary(hModule); } } } static SDL_bool HIDAPI_DriverXbox360_WindowsGamingInputSlotMatches(const WindowsMatchState *state, WindowsGamingInputGamepadState *slot) { Uint32 wgi_buttons = slot->state.Buttons; if ((wgi_buttons & 0x3FFF) == state->wgi_buttons && WindowsGamingInputAxesMatch(slot->state)) { return SDL_TRUE; } return SDL_FALSE; } static SDL_bool HIDAPI_DriverXbox360_GuessWindowsGamingInputSlot(const WindowsMatchState *state, Uint8 *correlation_id, WindowsGamingInputGamepadState **slot) { int match_count; match_count = 0; for (int user_index = 0; user_index < wgi_state.per_gamepad_count; ++user_index) { WindowsGamingInputGamepadState *gamepad_state = wgi_state.per_gamepad[user_index]; if (HIDAPI_DriverXbox360_WindowsGamingInputSlotMatches(state, gamepad_state)) { ++match_count; *slot = gamepad_state; /* Incrementing correlation_id for any match, as negative evidence for others being correlated */ *correlation_id = ++gamepad_state->correlation_id; } } /* Only return a match if we match exactly one, and we have some non-zero data (buttons or axes) that matched. Note that we're still invalidating *other* potential correlations if we have more than one match or we have no data. */ if (match_count == 1 && state->any_data) { return SDL_TRUE; } return SDL_FALSE; } static void HIDAPI_DriverXbox360_QuitWindowsGamingInput(SDL_DriverXbox360_Context *ctx) { wgi_state.need_device_list_update = SDL_TRUE; --wgi_state.ref_count; if (!wgi_state.ref_count && wgi_state.initialized) { for (int ii = 0; ii < wgi_state.per_gamepad_count; ii++) { __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(wgi_state.per_gamepad[ii]->gamepad); } if (wgi_state.per_gamepad) { SDL_free(wgi_state.per_gamepad); wgi_state.per_gamepad = NULL; } wgi_state.per_gamepad_count = 0; if (wgi_state.gamepad_statics) { __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_Release(wgi_state.gamepad_statics); wgi_state.gamepad_statics = NULL; } WIN_CoUninitialize(); wgi_state.initialized = SDL_FALSE; } } #endif /* SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT */ static void HIDAPI_DriverXbox360_PostUpdate(void) { #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING SDL_bool unmapped_guide_pressed = SDL_FALSE; #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT if (!wgi_state.dirty) { int ii; for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) { WindowsGamingInputGamepadState *gamepad_state = wgi_state.per_gamepad[ii]; if (!gamepad_state->used && (gamepad_state->state.Buttons & GamepadButtons_GUIDE)) { unmapped_guide_pressed = SDL_TRUE; break; } } } wgi_state.dirty = SDL_TRUE; #endif #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT if (!xinput_state_dirty) { int ii; for (ii = 0; ii < SDL_arraysize(xinput_state); ii++) { if (xinput_state[ii].connected && !xinput_state[ii].used && (xinput_state[ii].state.Gamepad.wButtons & XINPUT_GAMEPAD_GUIDE)) { unmapped_guide_pressed = SDL_TRUE; break; } } } xinput_state_dirty = SDL_TRUE; #endif if (unmapped_guide_pressed) { if (guide_button_candidate.joystick && !guide_button_candidate.last_joystick) { SDL_PrivateJoystickButton(guide_button_candidate.joystick, SDL_CONTROLLER_BUTTON_GUIDE, SDL_PRESSED); guide_button_candidate.last_joystick = guide_button_candidate.joystick; } } else if (guide_button_candidate.last_joystick) { SDL_PrivateJoystickButton(guide_button_candidate.last_joystick, SDL_CONTROLLER_BUTTON_GUIDE, SDL_RELEASED); guide_button_candidate.last_joystick = NULL; } guide_button_candidate.joystick = NULL; #endif } #if defined(__MACOSX__) static SDL_bool IsBluetoothXboxOneController(Uint16 vendor_id, Uint16 product_id) { /* Check to see if it's the Xbox One S or Xbox One Elite Series 2 in Bluetooth mode */ if (vendor_id == USB_VENDOR_MICROSOFT) { if (product_id == USB_PRODUCT_XBOX_ONE_S_REV1_BLUETOOTH || product_id == USB_PRODUCT_XBOX_ONE_S_REV2_BLUETOOTH || product_id == USB_PRODUCT_XBOX_ONE_ELITE_SERIES_2_BLUETOOTH) { return SDL_TRUE; } } return SDL_FALSE; } #endif static SDL_bool HIDAPI_DriverXbox360_IsSupportedDevice(const char *name, SDL_GameControllerType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) { const int XB360W_IFACE_PROTOCOL = 129; /* Wireless */ if (vendor_id == USB_VENDOR_NVIDIA) { /* This is the NVIDIA Shield controller which doesn't talk Xbox controller protocol */ return SDL_FALSE; } if ((vendor_id == USB_VENDOR_MICROSOFT && (product_id == 0x0291 || product_id == 0x0719)) || (type == SDL_CONTROLLER_TYPE_XBOX360 && interface_protocol == XB360W_IFACE_PROTOCOL)) { /* This is the wireless dongle, which talks a different protocol */ return SDL_FALSE; } if (interface_number > 0) { /* This is the chatpad or other input interface, not the Xbox 360 interface */ return SDL_FALSE; } #if defined(__MACOSX__) || defined(__WIN32__) if (vendor_id == USB_VENDOR_MICROSOFT && product_id == 0x028e && version == 1) { /* This is the Steam Virtual Gamepad, which isn't supported by this driver */ return SDL_FALSE; } #if defined(__MACOSX__) /* Wired Xbox One controllers are handled by this driver, interfacing with the 360Controller driver available from: https://github.com/360Controller/360Controller/releases Bluetooth Xbox One controllers are handled by the SDL Xbox One driver */ if (IsBluetoothXboxOneController(vendor_id, product_id)) { return SDL_FALSE; } #endif return (type == SDL_CONTROLLER_TYPE_XBOX360 || type == SDL_CONTROLLER_TYPE_XBOXONE); #else return (type == SDL_CONTROLLER_TYPE_XBOX360); #endif } static const char * HIDAPI_DriverXbox360_GetDeviceName(Uint16 vendor_id, Uint16 product_id) { return NULL; } static SDL_bool SetSlotLED(hid_device *dev, Uint8 slot) { Uint8 mode = 0x02 + slot; const Uint8 led_packet[] = { 0x01, 0x03, mode }; if (hid_write(dev, led_packet, sizeof(led_packet)) != sizeof(led_packet)) { return SDL_FALSE; } return SDL_TRUE; } static SDL_bool HIDAPI_DriverXbox360_InitDevice(SDL_HIDAPI_Device *device) { return HIDAPI_JoystickConnected(device, NULL, SDL_FALSE); } static int HIDAPI_DriverXbox360_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) { return -1; } static void HIDAPI_DriverXbox360_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) { if (device->dev) { SetSlotLED(device->dev, (player_index % 4)); } } static SDL_bool HIDAPI_DriverXbox360_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) { SDL_DriverXbox360_Context *ctx; int player_index; ctx = (SDL_DriverXbox360_Context *)SDL_calloc(1, sizeof(*ctx)); if (!ctx) { SDL_OutOfMemory(); return SDL_FALSE; } if (device->path) { /* else opened for RAWINPUT driver */ device->dev = hid_open_path(device->path, 0); if (!device->dev) { SDL_SetError("Couldn't open %s", device->path); SDL_free(ctx); return SDL_FALSE; } } device->context = ctx; #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT xinput_device_change = SDL_TRUE; ctx->xinput_enabled = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_CORRELATE_XINPUT, SDL_TRUE); if (ctx->xinput_enabled && (WIN_LoadXInputDLL() < 0 || !XINPUTGETSTATE)) { ctx->xinput_enabled = SDL_FALSE; } ctx->xinput_slot = XUSER_INDEX_ANY; #endif #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT HIDAPI_DriverXbox360_InitWindowsGamingInput(ctx); #endif /* Set the controller LED */ player_index = SDL_JoystickGetPlayerIndex(joystick); if (player_index >= 0 && device->dev) { SetSlotLED(device->dev, (player_index % 4)); } /* Initialize the joystick capabilities */ joystick->nbuttons = SDL_CONTROLLER_BUTTON_MAX; joystick->naxes = SDL_CONTROLLER_AXIS_MAX; joystick->epowerlevel = SDL_JOYSTICK_POWER_WIRED; return SDL_TRUE; } static int HIDAPI_DriverXbox360_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { #if defined(SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT) || defined(SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT) SDL_DriverXbox360_Context *ctx = (SDL_DriverXbox360_Context *)device->context; #endif #ifdef __WIN32__ SDL_bool rumbled = SDL_FALSE; #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT if (!rumbled && ctx->wgi_correlated) { WindowsGamingInputGamepadState *gamepad_state = ctx->wgi_slot; HRESULT hr; gamepad_state->vibration.LeftMotor = (DOUBLE)low_frequency_rumble / SDL_MAX_UINT16; gamepad_state->vibration.RightMotor = (DOUBLE)high_frequency_rumble / SDL_MAX_UINT16; hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_put_Vibration(gamepad_state->gamepad, gamepad_state->vibration); if (SUCCEEDED(hr)) { rumbled = SDL_TRUE; } } #endif #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT if (!rumbled && ctx->xinput_correlated) { XINPUT_VIBRATION XVibration; if (!XINPUTSETSTATE) { return SDL_Unsupported(); } XVibration.wLeftMotorSpeed = low_frequency_rumble; XVibration.wRightMotorSpeed = high_frequency_rumble; if (XINPUTSETSTATE(ctx->xinput_slot, &XVibration) == ERROR_SUCCESS) { rumbled = SDL_TRUE; } else { return SDL_SetError("XInputSetState() failed"); } } #endif /* SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT */ #else /* !__WIN32__ */ #ifdef __MACOSX__ if (IsBluetoothXboxOneController(device->vendor_id, device->product_id)) { Uint8 rumble_packet[] = { 0x03, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00 }; rumble_packet[4] = (low_frequency_rumble >> 8); rumble_packet[5] = (high_frequency_rumble >> 8); if (SDL_HIDAPI_SendRumble(device, rumble_packet, sizeof(rumble_packet)) != sizeof(rumble_packet)) { return SDL_SetError("Couldn't send rumble packet"); } } else { /* On Mac OS X the 360Controller driver uses this short report, and we need to prefix it with a magic token so hidapi passes it through untouched */ Uint8 rumble_packet[] = { 'M', 'A', 'G', 'I', 'C', '0', 0x00, 0x04, 0x00, 0x00 }; rumble_packet[6+2] = (low_frequency_rumble >> 8); rumble_packet[6+3] = (high_frequency_rumble >> 8); if (SDL_HIDAPI_SendRumble(device, rumble_packet, sizeof(rumble_packet)) != sizeof(rumble_packet)) { return SDL_SetError("Couldn't send rumble packet"); } } #else Uint8 rumble_packet[] = { 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; rumble_packet[3] = (low_frequency_rumble >> 8); rumble_packet[4] = (high_frequency_rumble >> 8); if (SDL_HIDAPI_SendRumble(device, rumble_packet, sizeof(rumble_packet)) != sizeof(rumble_packet)) { return SDL_SetError("Couldn't send rumble packet"); } #endif #endif /* __WIN32__ */ return 0; } #ifdef __WIN32__ /* This is the packet format for Xbox 360 and Xbox One controllers on Windows, however with this interface there is no rumble support, no guide button, and the left and right triggers are tied together as a single axis. We use XInput and Windows.Gaming.Input to make up for these shortcomings. */ static void HIDAPI_DriverXbox360_HandleStatePacket(SDL_Joystick *joystick, hid_device *dev, SDL_DriverXbox360_Context *ctx, Uint8 *data, int size) { #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING Uint32 match_state = ctx->match_state; /* Update match_state with button bit, then fall through */ # define SDL_PrivateJoystickButton(joystick, button, state) if (state) match_state |= 1 << (button); else match_state &=~(1<<(button)); SDL_PrivateJoystickButton(joystick, button, state) /* Grab high 4 bits of value, then fall through */ # define SDL_PrivateJoystickAxis(joystick, axis, value) if (axis < 4) match_state = (match_state & ~(0xF << (4 * axis + 16))) | ((value) & 0xF000) << (4 * axis + 4); SDL_PrivateJoystickAxis(joystick, axis, value) #endif Sint16 axis; SDL_bool has_trigger_data = SDL_FALSE; if (ctx->last_state[10] != data[10]) { SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_A, (data[10] & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_B, (data[10] & 0x02) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_X, (data[10] & 0x04) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_Y, (data[10] & 0x08) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSHOULDER, (data[10] & 0x10) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, (data[10] & 0x20) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_BACK, (data[10] & 0x40) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_START, (data[10] & 0x80) ? SDL_PRESSED : SDL_RELEASED); } if (ctx->last_state[11] != data[11]) { SDL_bool dpad_up = SDL_FALSE; SDL_bool dpad_down = SDL_FALSE; SDL_bool dpad_left = SDL_FALSE; SDL_bool dpad_right = SDL_FALSE; SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSTICK, (data[11] & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSTICK, (data[11] & 0x02) ? SDL_PRESSED : SDL_RELEASED); switch (data[11] & 0x3C) { case 4: dpad_up = SDL_TRUE; break; case 8: dpad_up = SDL_TRUE; dpad_right = SDL_TRUE; break; case 12: dpad_right = SDL_TRUE; break; case 16: dpad_right = SDL_TRUE; dpad_down = SDL_TRUE; break; case 20: dpad_down = SDL_TRUE; break; case 24: dpad_left = SDL_TRUE; dpad_down = SDL_TRUE; break; case 28: dpad_left = SDL_TRUE; break; case 32: dpad_up = SDL_TRUE; dpad_left = SDL_TRUE; break; default: break; } SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_DOWN, dpad_down); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_UP, dpad_up); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_RIGHT, dpad_right); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_LEFT, dpad_left); } axis = (int)*(Uint16*)(&data[0]) - 0x8000; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTX, axis); axis = (int)*(Uint16*)(&data[2]) - 0x8000; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTY, axis); axis = (int)*(Uint16*)(&data[4]) - 0x8000; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTX, axis); axis = (int)*(Uint16*)(&data[6]) - 0x8000; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTY, axis); #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING #undef SDL_PrivateJoystickAxis #endif #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT /* Prefer XInput over WindowsGamingInput, it continues to provide data in the background */ if (!has_trigger_data && ctx->xinput_enabled && ctx->xinput_correlated) { has_trigger_data = SDL_TRUE; } #endif /* SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT */ #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT if (!has_trigger_data && ctx->wgi_correlated) { has_trigger_data = SDL_TRUE; } #endif /* SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT */ if (!has_trigger_data) { axis = (data[9] * 257) - 32768; if (data[9] < 0x80) { axis = -axis * 2 - 32769; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, SDL_MIN_SINT16); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, axis); } else if (data[9] > 0x80) { axis = axis * 2 - 32767; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, axis); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, SDL_MIN_SINT16); } else { SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, SDL_MIN_SINT16); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, SDL_MIN_SINT16); } } #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING ctx->match_state = match_state; ctx->last_state_packet = SDL_GetTicks(); #undef SDL_PrivateJoystickButton #endif SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); } #ifdef SDL_JOYSTICK_RAWINPUT static void HIDAPI_DriverXbox360_HandleStatePacketFromRAWINPUT(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 *data, int size) { SDL_DriverXbox360_Context *ctx = (SDL_DriverXbox360_Context *)device->context; HIDAPI_DriverXbox360_HandleStatePacket(joystick, NULL, ctx, data, size); } #endif #else static void HIDAPI_DriverXbox360_HandleStatePacket(SDL_Joystick *joystick, hid_device *dev, SDL_DriverXbox360_Context *ctx, Uint8 *data, int size) { Sint16 axis; #ifdef __MACOSX__ const SDL_bool invert_y_axes = SDL_FALSE; #else const SDL_bool invert_y_axes = SDL_TRUE; #endif if (ctx->last_state[2] != data[2]) { SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_UP, (data[2] & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_DOWN, (data[2] & 0x02) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_LEFT, (data[2] & 0x04) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_RIGHT, (data[2] & 0x08) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_START, (data[2] & 0x10) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_BACK, (data[2] & 0x20) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSTICK, (data[2] & 0x40) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSTICK, (data[2] & 0x80) ? SDL_PRESSED : SDL_RELEASED); } if (ctx->last_state[3] != data[3]) { SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSHOULDER, (data[3] & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, (data[3] & 0x02) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, (data[3] & 0x04) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_A, (data[3] & 0x10) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_B, (data[3] & 0x20) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_X, (data[3] & 0x40) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_Y, (data[3] & 0x80) ? SDL_PRESSED : SDL_RELEASED); } axis = ((int)data[4] * 257) - 32768; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, axis); axis = ((int)data[5] * 257) - 32768; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, axis); axis = *(Sint16*)(&data[6]); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTX, axis); axis = *(Sint16*)(&data[8]); if (invert_y_axes) { axis = ~axis; } SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTY, axis); axis = *(Sint16*)(&data[10]); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTX, axis); axis = *(Sint16*)(&data[12]); if (invert_y_axes) { axis = ~axis; } SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTY, axis); SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); } #endif /* __WIN32__ */ static void HIDAPI_DriverXbox360_UpdateOtherAPIs(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) { #if defined(SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING) || defined(SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT) || defined(SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT) SDL_DriverXbox360_Context *ctx = (SDL_DriverXbox360_Context *)device->context; SDL_bool has_trigger_data = SDL_FALSE; SDL_bool correlated = SDL_FALSE; #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING WindowsMatchState match_state_xinput; #endif /* Poll for trigger data once (not per-state-packet) */ #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT /* Prefer XInput over WindowsGamingInput, it continues to provide data in the background */ if (!has_trigger_data && ctx->xinput_enabled && ctx->xinput_correlated) { HIDAPI_DriverXbox360_UpdateXInput(); if (xinput_state[ctx->xinput_slot].connected) { SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, (xinput_state[ctx->xinput_slot].state.Gamepad.wButtons & XINPUT_GAMEPAD_GUIDE) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, ((int)xinput_state[ctx->xinput_slot].state.Gamepad.bLeftTrigger * 257) - 32768); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, ((int)xinput_state[ctx->xinput_slot].state.Gamepad.bRightTrigger * 257) - 32768); has_trigger_data = SDL_TRUE; } } #endif /* SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT */ #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT if (!has_trigger_data && ctx->wgi_correlated) { HIDAPI_DriverXbox360_UpdateWindowsGamingInput(); /* May detect disconnect / cause uncorrelation */ if (ctx->wgi_correlated) { /* Still connected */ struct __x_ABI_CWindows_CGaming_CInput_CGamepadReading *state = &ctx->wgi_slot->state; SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, (state->Buttons & GamepadButtons_GUIDE) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, ((int)(state->LeftTrigger * SDL_MAX_UINT16)) - 32768); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, ((int)(state->RightTrigger * SDL_MAX_UINT16)) - 32768); has_trigger_data = SDL_TRUE; } } #endif /* SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT */ #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING HIDAPI_DriverXbox360_FillMatchState(&match_state_xinput, ctx->match_state); #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT /* Parallel logic to WINDOWS_XINPUT below */ HIDAPI_DriverXbox360_UpdateWindowsGamingInput(); if (ctx->wgi_correlated) { /* We have been previously correlated, ensure we are still matching, see comments in XINPUT section */ if (HIDAPI_DriverXbox360_WindowsGamingInputSlotMatches(&match_state_xinput, ctx->wgi_slot)) { ctx->wgi_uncorrelate_count = 0; } else { ++ctx->wgi_uncorrelate_count; /* Only un-correlate if this is consistent over multiple Update() calls - the timing of polling/event pumping can easily cause this to uncorrelate for a frame. 2 seemed reliable in my testing, but let's set it to 3 to be safe. An incorrect un-correlation will simply result in lower precision triggers for a frame. */ if (ctx->wgi_uncorrelate_count >= 3) { #ifdef DEBUG_JOYSTICK SDL_Log("UN-Correlated joystick %d to WindowsGamingInput device #%d\n", joystick->instance_id, ctx->wgi_slot); #endif HIDAPI_DriverXbox360_MarkWindowsGamingInputSlotFree(ctx->wgi_slot); ctx->wgi_correlated = SDL_FALSE; ctx->wgi_correlation_count = 0; /* Force immediate update of triggers */ HIDAPI_DriverXbox360_HandleStatePacket(joystick, NULL, ctx, ctx->last_state, sizeof(ctx->last_state)); /* Force release of Guide button, it can't possibly be down on this device now. */ /* It gets left down if we were actually correlated incorrectly and it was released on the WindowsGamingInput device but we didn't get a state packet. */ SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, SDL_RELEASED); } } } if (!ctx->wgi_correlated) { SDL_bool new_correlation_count = 0; if (HIDAPI_DriverXbox360_MissingWindowsGamingInputSlot()) { Uint8 correlation_id; WindowsGamingInputGamepadState *slot_idx; if (HIDAPI_DriverXbox360_GuessWindowsGamingInputSlot(&match_state_xinput, &correlation_id, &slot_idx)) { /* we match exactly one WindowsGamingInput device */ /* Probably can do without wgi_correlation_count, just check and clear wgi_slot to NULL, unless we need even more frames to be sure. */ if (ctx->wgi_correlation_count && ctx->wgi_slot == slot_idx) { /* was correlated previously, and still the same device */ if (ctx->wgi_correlation_id + 1 == correlation_id) { /* no one else was correlated in the meantime */ new_correlation_count = ctx->wgi_correlation_count + 1; if (new_correlation_count == 2) { /* correlation stayed steady and uncontested across multiple frames, guaranteed match */ ctx->wgi_correlated = SDL_TRUE; #ifdef DEBUG_JOYSTICK SDL_Log("Correlated joystick %d to WindowsGamingInput device #%d\n", joystick->instance_id, slot_idx); #endif correlated = SDL_TRUE; HIDAPI_DriverXbox360_MarkWindowsGamingInputSlotUsed(ctx->wgi_slot, ctx); /* If the generalized Guide button was using us, it doesn't need to anymore */ if (guide_button_candidate.joystick == joystick) guide_button_candidate.joystick = NULL; if (guide_button_candidate.last_joystick == joystick) guide_button_candidate.last_joystick = NULL; /* Force immediate update of guide button / triggers */ HIDAPI_DriverXbox360_HandleStatePacket(joystick, NULL, ctx, ctx->last_state, sizeof(ctx->last_state)); } } else { /* someone else also possibly correlated to this device, start over */ new_correlation_count = 1; } } else { /* new possible correlation */ new_correlation_count = 1; ctx->wgi_slot = slot_idx; } ctx->wgi_correlation_id = correlation_id; } else { /* Match multiple WindowsGamingInput devices, or none (possibly due to no buttons pressed) */ } } ctx->wgi_correlation_count = new_correlation_count; } else { correlated = SDL_TRUE; } #endif #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT /* Parallel logic to WINDOWS_GAMING_INPUT above */ if (ctx->xinput_enabled) { HIDAPI_DriverXbox360_UpdateXInput(); if (ctx->xinput_correlated) { /* We have been previously correlated, ensure we are still matching */ /* This is required to deal with two (mostly) un-preventable mis-correlation situations: A) Since the HID data stream does not provide an initial state (but polling XInput does), if we open 5 controllers (#1-4 XInput mapped, #5 is not), and controller 1 had the A button down (and we don't know), and the user presses A on controller #5, we'll see exactly 1 controller with A down (#5) and exactly 1 XInput device with A down (#1), and incorrectly correlate. This code will then un-correlate when A is released from either controller #1 or #5. B) Since the app may not open all controllers, we could have a similar situation where only controller #5 is opened, and the user holds A on controllers #1 and #5 simultaneously - again we see only 1 controller with A down and 1 XInput device with A down, and incorrectly correlate. This should be very unusual (only when apps do not open all controllers, yet are listening to Guide button presses, yet for some reason want to ignore guide button presses on the un-opened controllers, yet users are pressing buttons on the unopened controllers), and will resolve itself when either button is released and we un-correlate. We could prevent this by processing the state packets for *all* controllers, even un-opened ones, as that would allow more precise correlation. */ if (HIDAPI_DriverXbox360_XInputSlotMatches(&match_state_xinput, ctx->xinput_slot)) { ctx->xinput_uncorrelate_count = 0; } else { ++ctx->xinput_uncorrelate_count; /* Only un-correlate if this is consistent over multiple Update() calls - the timing of polling/event pumping can easily cause this to uncorrelate for a frame. 2 seemed reliable in my testing, but let's set it to 3 to be safe. An incorrect un-correlation will simply result in lower precision triggers for a frame. */ if (ctx->xinput_uncorrelate_count >= 3) { #ifdef DEBUG_JOYSTICK SDL_Log("UN-Correlated joystick %d to XInput device #%d\n", joystick->instance_id, ctx->xinput_slot); #endif HIDAPI_DriverXbox360_MarkXInputSlotFree(ctx->xinput_slot); ctx->xinput_correlated = SDL_FALSE; ctx->xinput_correlation_count = 0; /* Force immediate update of triggers */ HIDAPI_DriverXbox360_HandleStatePacket(joystick, NULL, ctx, ctx->last_state, sizeof(ctx->last_state)); /* Force release of Guide button, it can't possibly be down on this device now. */ /* It gets left down if we were actually correlated incorrectly and it was released on the XInput device but we didn't get a state packet. */ SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, SDL_RELEASED); } } } if (!ctx->xinput_correlated) { SDL_bool new_correlation_count = 0; if (HIDAPI_DriverXbox360_MissingXInputSlot()) { Uint8 correlation_id = 0; Uint8 slot_idx = 0; if (HIDAPI_DriverXbox360_GuessXInputSlot(&match_state_xinput, &correlation_id, &slot_idx)) { /* we match exactly one XInput device */ /* Probably can do without xinput_correlation_count, just check and clear xinput_slot to ANY, unless we need even more frames to be sure */ if (ctx->xinput_correlation_count && ctx->xinput_slot == slot_idx) { /* was correlated previously, and still the same device */ if (ctx->xinput_correlation_id + 1 == correlation_id) { /* no one else was correlated in the meantime */ new_correlation_count = ctx->xinput_correlation_count + 1; if (new_correlation_count == 2) { /* correlation stayed steady and uncontested across multiple frames, guaranteed match */ ctx->xinput_correlated = SDL_TRUE; #ifdef DEBUG_JOYSTICK SDL_Log("Correlated joystick %d to XInput device #%d\n", joystick->instance_id, slot_idx); #endif correlated = SDL_TRUE; HIDAPI_DriverXbox360_MarkXInputSlotUsed(ctx->xinput_slot); /* If the generalized Guide button was using us, it doesn't need to anymore */ if (guide_button_candidate.joystick == joystick) guide_button_candidate.joystick = NULL; if (guide_button_candidate.last_joystick == joystick) guide_button_candidate.last_joystick = NULL; /* Force immediate update of guide button / triggers */ HIDAPI_DriverXbox360_HandleStatePacket(joystick, NULL, ctx, ctx->last_state, sizeof(ctx->last_state)); } } else { /* someone else also possibly correlated to this device, start over */ new_correlation_count = 1; } } else { /* new possible correlation */ new_correlation_count = 1; ctx->xinput_slot = slot_idx; } ctx->xinput_correlation_id = correlation_id; } else { /* Match multiple XInput devices, or none (possibly due to no buttons pressed) */ } } ctx->xinput_correlation_count = new_correlation_count; } else { correlated = SDL_TRUE; } } #endif if (!correlated) { if (!guide_button_candidate.joystick || (ctx->last_state_packet && ( !guide_button_candidate.last_state_packet || SDL_TICKS_PASSED(ctx->last_state_packet, guide_button_candidate.last_state_packet) )) ) { guide_button_candidate.joystick = joystick; guide_button_candidate.last_state_packet = ctx->last_state_packet; } } #endif #endif } static SDL_bool HIDAPI_DriverXbox360_UpdateDevice(SDL_HIDAPI_Device *device) { SDL_DriverXbox360_Context *ctx = (SDL_DriverXbox360_Context *)device->context; SDL_Joystick *joystick = NULL; Uint8 data[USB_PACKET_LENGTH]; int size = 0; if (device->num_joysticks > 0) { joystick = SDL_JoystickFromInstanceID(device->joysticks[0]); } if (!joystick) { return SDL_FALSE; } while (device->dev && (size = hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) { HIDAPI_DriverXbox360_HandleStatePacket(joystick, device->dev, ctx, data, size); } if (size < 0) { /* Read error, device is disconnected */ HIDAPI_JoystickDisconnected(device, joystick->instance_id, SDL_FALSE); } else { HIDAPI_DriverXbox360_UpdateOtherAPIs(device, joystick); } return (size >= 0); } static void HIDAPI_DriverXbox360_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) { #if defined(SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT) || defined(SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT) SDL_DriverXbox360_Context *ctx = (SDL_DriverXbox360_Context *)device->context; #endif #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_MATCHING if (guide_button_candidate.joystick == joystick) guide_button_candidate.joystick = NULL; if (guide_button_candidate.last_joystick == joystick) guide_button_candidate.last_joystick = NULL; #endif #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_XINPUT xinput_device_change = SDL_TRUE; if (ctx->xinput_enabled) { if (ctx->xinput_correlated) { HIDAPI_DriverXbox360_MarkXInputSlotFree(ctx->xinput_slot); } WIN_UnloadXInputDLL(); } #endif #ifdef SDL_JOYSTICK_HIDAPI_WINDOWS_GAMING_INPUT HIDAPI_DriverXbox360_QuitWindowsGamingInput(ctx); #endif if (device->dev) { hid_close(device->dev); device->dev = NULL; } SDL_free(device->context); device->context = NULL; } static void HIDAPI_DriverXbox360_FreeDevice(SDL_HIDAPI_Device *device) { } SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverXbox360 = { SDL_HINT_JOYSTICK_HIDAPI_XBOX, SDL_TRUE, HIDAPI_DriverXbox360_IsSupportedDevice, HIDAPI_DriverXbox360_GetDeviceName, HIDAPI_DriverXbox360_InitDevice, HIDAPI_DriverXbox360_GetDevicePlayerIndex, HIDAPI_DriverXbox360_SetDevicePlayerIndex, HIDAPI_DriverXbox360_UpdateDevice, HIDAPI_DriverXbox360_OpenJoystick, HIDAPI_DriverXbox360_RumbleJoystick, HIDAPI_DriverXbox360_CloseJoystick, HIDAPI_DriverXbox360_FreeDevice, HIDAPI_DriverXbox360_PostUpdate, #ifdef SDL_JOYSTICK_RAWINPUT HIDAPI_DriverXbox360_HandleStatePacketFromRAWINPUT, #endif }; #endif /* SDL_JOYSTICK_HIDAPI_XBOX360 */ #endif /* SDL_JOYSTICK_HIDAPI */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/hidapi/SDL_hidapi_xbox360.c
C
apache-2.0
58,123
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_HIDAPI #include "SDL_hints.h" #include "SDL_events.h" #include "SDL_timer.h" #include "SDL_joystick.h" #include "SDL_gamecontroller.h" #include "../SDL_sysjoystick.h" #include "SDL_hidapijoystick_c.h" #include "SDL_hidapi_rumble.h" #ifdef SDL_JOYSTICK_HIDAPI_XBOX360 typedef struct { SDL_bool connected; Uint8 last_state[USB_PACKET_LENGTH]; } SDL_DriverXbox360W_Context; static SDL_bool HIDAPI_DriverXbox360W_IsSupportedDevice(const char *name, SDL_GameControllerType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) { const int XB360W_IFACE_PROTOCOL = 129; /* Wireless */ if ((vendor_id == USB_VENDOR_MICROSOFT && (product_id == 0x0291 || product_id == 0x02a9 || product_id == 0x0719)) || (type == SDL_CONTROLLER_TYPE_XBOX360 && interface_protocol == XB360W_IFACE_PROTOCOL)) { return SDL_TRUE; } return SDL_FALSE; } static const char * HIDAPI_DriverXbox360W_GetDeviceName(Uint16 vendor_id, Uint16 product_id) { return "Xbox 360 Wireless Controller"; } static SDL_bool SetSlotLED(hid_device *dev, Uint8 slot) { Uint8 mode = 0x02 + slot; const Uint8 led_packet[] = { 0x00, 0x00, 0x08, (0x40 + (mode % 0x0e)), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; if (hid_write(dev, led_packet, sizeof(led_packet)) != sizeof(led_packet)) { return SDL_FALSE; } return SDL_TRUE; } static void UpdatePowerLevel(SDL_Joystick *joystick, Uint8 level) { float normalized_level = (float)level / 255.0f; if (normalized_level <= 0.05f) { joystick->epowerlevel = SDL_JOYSTICK_POWER_EMPTY; } else if (normalized_level <= 0.20f) { joystick->epowerlevel = SDL_JOYSTICK_POWER_LOW; } else if (normalized_level <= 0.70f) { joystick->epowerlevel = SDL_JOYSTICK_POWER_MEDIUM; } else { joystick->epowerlevel = SDL_JOYSTICK_POWER_FULL; } } static SDL_bool HIDAPI_DriverXbox360W_InitDevice(SDL_HIDAPI_Device *device) { SDL_DriverXbox360W_Context *ctx; /* Requests controller presence information from the wireless dongle */ const Uint8 init_packet[] = { 0x08, 0x00, 0x0F, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; ctx = (SDL_DriverXbox360W_Context *)SDL_calloc(1, sizeof(*ctx)); if (!ctx) { SDL_OutOfMemory(); return SDL_FALSE; } device->dev = hid_open_path(device->path, 0); if (!device->dev) { SDL_free(ctx); SDL_SetError("Couldn't open %s", device->path); return SDL_FALSE; } device->context = ctx; if (hid_write(device->dev, init_packet, sizeof(init_packet)) != sizeof(init_packet)) { SDL_SetError("Couldn't write init packet"); return SDL_FALSE; } return SDL_TRUE; } static int HIDAPI_DriverXbox360W_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) { return -1; } static void HIDAPI_DriverXbox360W_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) { SetSlotLED(device->dev, (player_index % 4)); } static SDL_bool HIDAPI_DriverXbox360W_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) { SDL_DriverXbox360W_Context *ctx = (SDL_DriverXbox360W_Context *)device->context; SDL_zeroa(ctx->last_state); /* Initialize the joystick capabilities */ joystick->nbuttons = SDL_CONTROLLER_BUTTON_MAX; joystick->naxes = SDL_CONTROLLER_AXIS_MAX; joystick->epowerlevel = SDL_JOYSTICK_POWER_UNKNOWN; return SDL_TRUE; } static int HIDAPI_DriverXbox360W_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { Uint8 rumble_packet[] = { 0x00, 0x01, 0x0f, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; rumble_packet[5] = (low_frequency_rumble >> 8); rumble_packet[6] = (high_frequency_rumble >> 8); if (SDL_HIDAPI_SendRumble(device, rumble_packet, sizeof(rumble_packet)) != sizeof(rumble_packet)) { return SDL_SetError("Couldn't send rumble packet"); } return 0; } static void HIDAPI_DriverXbox360W_HandleStatePacket(SDL_Joystick *joystick, hid_device *dev, SDL_DriverXbox360W_Context *ctx, Uint8 *data, int size) { Sint16 axis; const SDL_bool invert_y_axes = SDL_TRUE; if (ctx->last_state[2] != data[2]) { SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_UP, (data[2] & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_DOWN, (data[2] & 0x02) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_LEFT, (data[2] & 0x04) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_RIGHT, (data[2] & 0x08) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_START, (data[2] & 0x10) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_BACK, (data[2] & 0x20) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSTICK, (data[2] & 0x40) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSTICK, (data[2] & 0x80) ? SDL_PRESSED : SDL_RELEASED); } if (ctx->last_state[3] != data[3]) { SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSHOULDER, (data[3] & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, (data[3] & 0x02) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, (data[3] & 0x04) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_A, (data[3] & 0x10) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_B, (data[3] & 0x20) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_X, (data[3] & 0x40) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_Y, (data[3] & 0x80) ? SDL_PRESSED : SDL_RELEASED); } axis = ((int)data[4] * 257) - 32768; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, axis); axis = ((int)data[5] * 257) - 32768; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, axis); axis = *(Sint16*)(&data[6]); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTX, axis); axis = *(Sint16*)(&data[8]); if (invert_y_axes) { axis = ~axis; } SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTY, axis); axis = *(Sint16*)(&data[10]); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTX, axis); axis = *(Sint16*)(&data[12]); if (invert_y_axes) { axis = ~axis; } SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTY, axis); SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); } static SDL_bool HIDAPI_DriverXbox360W_UpdateDevice(SDL_HIDAPI_Device *device) { SDL_DriverXbox360W_Context *ctx = (SDL_DriverXbox360W_Context *)device->context; SDL_Joystick *joystick = NULL; Uint8 data[USB_PACKET_LENGTH]; int size; if (device->num_joysticks > 0) { joystick = SDL_JoystickFromInstanceID(device->joysticks[0]); } while ((size = hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) { if (size == 2 && data[0] == 0x08) { SDL_bool connected = (data[1] & 0x80) ? SDL_TRUE : SDL_FALSE; #ifdef DEBUG_JOYSTICK SDL_Log("Connected = %s\n", connected ? "TRUE" : "FALSE"); #endif if (connected != ctx->connected) { ctx->connected = connected; if (connected) { SDL_JoystickID joystickID; HIDAPI_JoystickConnected(device, &joystickID, SDL_FALSE); } else if (device->num_joysticks > 0) { HIDAPI_JoystickDisconnected(device, device->joysticks[0], SDL_FALSE); } } } else if (size == 29 && data[0] == 0x00 && data[1] == 0x0f && data[2] == 0x00 && data[3] == 0xf0) { /* Serial number is data[7-13] */ #ifdef DEBUG_JOYSTICK SDL_Log("Battery status (initial): %d\n", data[17]); #endif if (joystick) { UpdatePowerLevel(joystick, data[17]); } } else if (size == 29 && data[0] == 0x00 && data[1] == 0x00 && data[2] == 0x00 && data[3] == 0x13) { #ifdef DEBUG_JOYSTICK SDL_Log("Battery status: %d\n", data[4]); #endif if (joystick) { UpdatePowerLevel(joystick, data[4]); } } else if (size == 29 && data[0] == 0x00 && (data[1] & 0x01) == 0x01) { if (joystick) { HIDAPI_DriverXbox360W_HandleStatePacket(joystick, device->dev, ctx, data+4, size-4); } } } if (joystick) { if (size < 0) { /* Read error, device is disconnected */ HIDAPI_JoystickDisconnected(device, joystick->instance_id, SDL_FALSE); } } return (size >= 0); } static void HIDAPI_DriverXbox360W_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) { } static void HIDAPI_DriverXbox360W_FreeDevice(SDL_HIDAPI_Device *device) { hid_close(device->dev); device->dev = NULL; SDL_free(device->context); device->context = NULL; } SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverXbox360W = { SDL_HINT_JOYSTICK_HIDAPI_XBOX, SDL_TRUE, HIDAPI_DriverXbox360W_IsSupportedDevice, HIDAPI_DriverXbox360W_GetDeviceName, HIDAPI_DriverXbox360W_InitDevice, HIDAPI_DriverXbox360W_GetDevicePlayerIndex, HIDAPI_DriverXbox360W_SetDevicePlayerIndex, HIDAPI_DriverXbox360W_UpdateDevice, HIDAPI_DriverXbox360W_OpenJoystick, HIDAPI_DriverXbox360W_RumbleJoystick, HIDAPI_DriverXbox360W_CloseJoystick, HIDAPI_DriverXbox360W_FreeDevice, NULL }; #endif /* SDL_JOYSTICK_HIDAPI_XBOX360 */ #endif /* SDL_JOYSTICK_HIDAPI */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/hidapi/SDL_hidapi_xbox360w.c
C
apache-2.0
11,252
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_HIDAPI #include "SDL_hints.h" #include "SDL_events.h" #include "SDL_timer.h" #include "SDL_joystick.h" #include "SDL_gamecontroller.h" #include "../SDL_sysjoystick.h" #include "SDL_hidapijoystick_c.h" #include "SDL_hidapi_rumble.h" #ifdef SDL_JOYSTICK_HIDAPI_XBOXONE /* Define this if you want to log all packets from the controller */ /*#define DEBUG_XBOX_PROTOCOL*/ /* The amount of time to wait after hotplug to send controller init sequence */ #define CONTROLLER_INIT_DELAY_MS 1500 /* 475 for Xbox One S, 1275 for the PDP Battlefield 1 */ /* The amount of time to wait after init for valid input */ #define CONTROLLER_INPUT_DELAY_MS 50 /* 42 for Razer Wolverine Ultimate */ /* Connect controller */ static const Uint8 xboxone_init0[] = { 0x04, 0x20, 0x00, 0x00 }; /* Initial ack */ static const Uint8 xboxone_init1[] = { 0x01, 0x20, 0x01, 0x09, 0x00, 0x04, 0x20, 0x3a, 0x00, 0x00, 0x00, 0x80, 0x00 }; /* Start controller - extended? */ static const Uint8 xboxone_init2[] = { 0x05, 0x20, 0x00, 0x0F, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x53, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; /* Start controller with input */ static const Uint8 xboxone_init3[] = { 0x05, 0x20, 0x03, 0x01, 0x00 }; /* Enable LED */ static const Uint8 xboxone_init4[] = { 0x0A, 0x20, 0x00, 0x03, 0x00, 0x01, 0x14 }; /* Start input reports? */ static const Uint8 xboxone_init5[] = { 0x06, 0x20, 0x00, 0x02, 0x01, 0x00 }; /* Start rumble? */ static const Uint8 xboxone_init6[] = { 0x09, 0x00, 0x00, 0x09, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xEB }; /* * This specifies the selection of init packets that a gamepad * will be sent on init *and* the order in which they will be * sent. The correct sequence number will be added when the * packet is going to be sent. */ typedef struct { Uint16 vendor_id; Uint16 product_id; Uint16 exclude_vendor_id; Uint16 exclude_product_id; const Uint8 *data; int size; const Uint8 response[2]; } SDL_DriverXboxOne_InitPacket; static const SDL_DriverXboxOne_InitPacket xboxone_init_packets[] = { { 0x0000, 0x0000, 0x0000, 0x0000, xboxone_init0, sizeof(xboxone_init0), { 0x04, 0xf0 } }, { 0x0000, 0x0000, 0x0000, 0x0000, xboxone_init1, sizeof(xboxone_init1), { 0x04, 0xb0 } }, { 0x0000, 0x0000, 0x0000, 0x0000, xboxone_init2, sizeof(xboxone_init2), { 0x00, 0x00 } }, { 0x0000, 0x0000, 0x0000, 0x0000, xboxone_init3, sizeof(xboxone_init3), { 0x00, 0x00 } }, { 0x0000, 0x0000, 0x0000, 0x0000, xboxone_init4, sizeof(xboxone_init4), { 0x00, 0x00 } }, /* These next packets are required for third party controllers (PowerA, PDP, HORI), but aren't the correct protocol for Microsoft Xbox controllers. */ { 0x0000, 0x0000, 0x045e, 0x0000, xboxone_init5, sizeof(xboxone_init5), { 0x00, 0x00 } }, { 0x0000, 0x0000, 0x045e, 0x0000, xboxone_init6, sizeof(xboxone_init6), { 0x00, 0x00 } }, }; typedef enum { XBOX_ONE_WIRELESS_PROTOCOL_UNKNOWN, XBOX_ONE_WIRELESS_PROTOCOL_V1, XBOX_ONE_WIRELESS_PROTOCOL_V2, } SDL_XboxOneWirelessProtocol; typedef struct { Uint16 vendor_id; Uint16 product_id; SDL_bool bluetooth; SDL_XboxOneWirelessProtocol wireless_protocol; SDL_bool initialized; SDL_bool input_ready; Uint32 start_time; Uint32 initialized_time; Uint8 sequence; Uint8 last_state[USB_PACKET_LENGTH]; SDL_bool has_paddles; } SDL_DriverXboxOne_Context; #ifdef DEBUG_XBOX_PROTOCOL static void DumpPacket(const char *prefix, Uint8 *data, int size) { int i; char *buffer; size_t length = SDL_strlen(prefix) + 11*(USB_PACKET_LENGTH/8) + (5*USB_PACKET_LENGTH) + 1 + 1; buffer = (char *)SDL_malloc(length); SDL_snprintf(buffer, length, prefix, size); for (i = 0; i < size; ++i) { if ((i % 8) == 0) { SDL_snprintf(&buffer[SDL_strlen(buffer)], length - SDL_strlen(buffer), "\n%.2d: ", i); } SDL_snprintf(&buffer[SDL_strlen(buffer)], length - SDL_strlen(buffer), " 0x%.2x", data[i]); } SDL_strlcat(buffer, "\n", length); SDL_Log("%s", buffer); SDL_free(buffer); } #endif /* DEBUG_XBOX_PROTOCOL */ static SDL_bool IsBluetoothXboxOneController(Uint16 vendor_id, Uint16 product_id) { /* Check to see if it's the Xbox One S or Xbox One Elite Series 2 in Bluetooth mode */ if (vendor_id == USB_VENDOR_MICROSOFT) { if (product_id == USB_PRODUCT_XBOX_ONE_S_REV1_BLUETOOTH || product_id == USB_PRODUCT_XBOX_ONE_S_REV2_BLUETOOTH || product_id == USB_PRODUCT_XBOX_ONE_ELITE_SERIES_2_BLUETOOTH) { return SDL_TRUE; } } return SDL_FALSE; } static SDL_bool ControllerHasPaddles(Uint16 vendor_id, Uint16 product_id) { if (vendor_id == USB_VENDOR_MICROSOFT) { if (product_id == USB_PRODUCT_XBOX_ONE_ELITE_SERIES_1 || product_id == USB_PRODUCT_XBOX_ONE_ELITE_SERIES_2) { return SDL_TRUE; } } return SDL_FALSE; } /* Return true if this controller sends the 0x02 "waiting for init" packet */ static SDL_bool ControllerSendsWaitingForInit(Uint16 vendor_id, Uint16 product_id) { if (vendor_id == USB_VENDOR_HYPERKIN) { /* The Hyperkin controllers always send 0x02 when waiting for init, and the Hyperkin Duke plays an Xbox startup animation, so we want to make sure we don't send the init sequence if it isn't needed. */ return SDL_TRUE; } if (vendor_id == USB_VENDOR_PDP) { /* The PDP Rock Candy (PID 0x0246) doesn't send 0x02 on Linux for some reason */ return SDL_FALSE; } /* It doesn't hurt to reinit, especially if a driver has misconfigured the controller */ /*return SDL_TRUE;*/ return SDL_FALSE; } static SDL_bool SendControllerInit(SDL_HIDAPI_Device *device, SDL_DriverXboxOne_Context *ctx) { Uint16 vendor_id = ctx->vendor_id; Uint16 product_id = ctx->product_id; int i; Uint8 init_packet[USB_PACKET_LENGTH]; for (i = 0; i < SDL_arraysize(xboxone_init_packets); ++i) { const SDL_DriverXboxOne_InitPacket *packet = &xboxone_init_packets[i]; if (packet->vendor_id && (vendor_id != packet->vendor_id)) { continue; } if (packet->product_id && (product_id != packet->product_id)) { continue; } if (packet->exclude_vendor_id && (vendor_id == packet->exclude_vendor_id)) { continue; } if (packet->exclude_product_id && (product_id == packet->exclude_product_id)) { continue; } SDL_memcpy(init_packet, packet->data, packet->size); if (init_packet[0] != 0x01) { init_packet[2] = ctx->sequence++; } if (hid_write(device->dev, init_packet, packet->size) != packet->size) { SDL_SetError("Couldn't write Xbox One initialization packet"); return SDL_FALSE; } if (packet->response[0]) { const Uint32 RESPONSE_TIMEOUT_MS = 100; Uint32 start = SDL_GetTicks(); SDL_bool got_response = SDL_FALSE; while (!got_response && !SDL_TICKS_PASSED(SDL_GetTicks(), start + RESPONSE_TIMEOUT_MS)) { Uint8 data[USB_PACKET_LENGTH]; int size; while ((size = hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) { #ifdef DEBUG_XBOX_PROTOCOL DumpPacket("Xbox One INIT packet: size = %d", data, size); #endif if (size >= 2 && data[0] == packet->response[0] && data[1] == packet->response[1]) { got_response = SDL_TRUE; } } } #ifdef DEBUG_XBOX_PROTOCOL SDL_Log("Init sequence %d got response after %u ms: %s\n", i, (SDL_GetTicks() - start), got_response ? "TRUE" : "FALSE"); #endif } } return SDL_TRUE; } static SDL_bool HIDAPI_DriverXboxOne_IsSupportedDevice(const char *name, SDL_GameControllerType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol) { #ifdef __LINUX__ if (vendor_id == USB_VENDOR_POWERA && product_id == 0x541a) { /* The PowerA Mini controller, model 1240245-01, blocks while writing feature reports */ return SDL_FALSE; } #endif #ifdef __MACOSX__ /* Wired Xbox One controllers are handled by the 360Controller driver */ if (!IsBluetoothXboxOneController(vendor_id, product_id)) { return SDL_FALSE; } #endif return (type == SDL_CONTROLLER_TYPE_XBOXONE); } static const char * HIDAPI_DriverXboxOne_GetDeviceName(Uint16 vendor_id, Uint16 product_id) { return NULL; } static SDL_bool HIDAPI_DriverXboxOne_InitDevice(SDL_HIDAPI_Device *device) { return HIDAPI_JoystickConnected(device, NULL, SDL_FALSE); } static int HIDAPI_DriverXboxOne_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id) { return -1; } static void HIDAPI_DriverXboxOne_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index) { } static SDL_bool HIDAPI_DriverXboxOne_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) { SDL_DriverXboxOne_Context *ctx; ctx = (SDL_DriverXboxOne_Context *)SDL_calloc(1, sizeof(*ctx)); if (!ctx) { SDL_OutOfMemory(); return SDL_FALSE; } device->dev = hid_open_path(device->path, 0); if (!device->dev) { SDL_free(ctx); SDL_SetError("Couldn't open %s", device->path); return SDL_FALSE; } device->context = ctx; ctx->vendor_id = device->vendor_id; ctx->product_id = device->product_id; ctx->bluetooth = IsBluetoothXboxOneController(device->vendor_id, device->product_id); ctx->initialized = ctx->bluetooth ? SDL_TRUE : SDL_FALSE; ctx->start_time = SDL_GetTicks(); ctx->input_ready = SDL_TRUE; ctx->sequence = 1; ctx->has_paddles = ControllerHasPaddles(ctx->vendor_id, ctx->product_id); /* Initialize the joystick capabilities */ joystick->nbuttons = ctx->has_paddles ? SDL_CONTROLLER_BUTTON_MAX : (SDL_CONTROLLER_BUTTON_MAX + 4); joystick->naxes = SDL_CONTROLLER_AXIS_MAX; joystick->epowerlevel = SDL_JOYSTICK_POWER_WIRED; return SDL_TRUE; } static int HIDAPI_DriverXboxOne_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { SDL_DriverXboxOne_Context *ctx = (SDL_DriverXboxOne_Context *)device->context; if (ctx->bluetooth) { Uint8 rumble_packet[] = { 0x03, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00 }; rumble_packet[4] = (low_frequency_rumble >> 8); rumble_packet[5] = (high_frequency_rumble >> 8); if (SDL_HIDAPI_SendRumble(device, rumble_packet, sizeof(rumble_packet)) != sizeof(rumble_packet)) { return SDL_SetError("Couldn't send rumble packet"); } } else { Uint8 rumble_packet[] = { 0x09, 0x00, 0x00, 0x09, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF }; /* Magnitude is 1..100 so scale the 16-bit input here */ rumble_packet[8] = low_frequency_rumble / 655; rumble_packet[9] = high_frequency_rumble / 655; if (SDL_HIDAPI_SendRumble(device, rumble_packet, sizeof(rumble_packet)) != sizeof(rumble_packet)) { return SDL_SetError("Couldn't send rumble packet"); } } return 0; } static void HIDAPI_DriverXboxOne_HandleStatePacket(SDL_Joystick *joystick, hid_device *dev, SDL_DriverXboxOne_Context *ctx, Uint8 *data, int size) { Sint16 axis; if (ctx->last_state[4] != data[4]) { SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_START, (data[4] & 0x04) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_BACK, (data[4] & 0x08) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_A, (data[4] & 0x10) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_B, (data[4] & 0x20) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_X, (data[4] & 0x40) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_Y, (data[4] & 0x80) ? SDL_PRESSED : SDL_RELEASED); } if (ctx->last_state[5] != data[5]) { SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_UP, (data[5] & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_DOWN, (data[5] & 0x02) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_LEFT, (data[5] & 0x04) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_RIGHT, (data[5] & 0x08) ? SDL_PRESSED : SDL_RELEASED); if (ctx->vendor_id == USB_VENDOR_RAZER && ctx->product_id == USB_PRODUCT_RAZER_ATROX) { /* The Razer Atrox has the right and left shoulder bits reversed */ SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSHOULDER, (data[5] & 0x20) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, (data[5] & 0x10) ? SDL_PRESSED : SDL_RELEASED); } else { SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSHOULDER, (data[5] & 0x10) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, (data[5] & 0x20) ? SDL_PRESSED : SDL_RELEASED); } SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSTICK, (data[5] & 0x40) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSTICK, (data[5] & 0x80) ? SDL_PRESSED : SDL_RELEASED); } /* Xbox One S report is 18 bytes Xbox One Elite Series 1 report is 33 bytes, paddles in data[32], mode in data[32] & 0x10, both modes have mapped paddles by default Paddle bits: UL: 0x01 (A) UR: 0x02 (B) LL: 0x04 (X) LR: 0x08 (Y) Xbox One Elite Series 2 report is 38 bytes, paddles in data[18], mode in data[19], mode 0 has no mapped paddles by default Paddle bits: UL: 0x04 (A) UR: 0x01 (B) LL: 0x08 (X) LR: 0x02 (Y) */ if (ctx->has_paddles && (size == 33 || size == 38)) { int paddle_index; int button1_bit; int button2_bit; int button3_bit; int button4_bit; SDL_bool paddles_mapped; if (size == 33) { /* XBox One Elite Series 1 */ paddle_index = 32; button1_bit = 0x01; button2_bit = 0x02; button3_bit = 0x04; button4_bit = 0x08; /* The mapped controller state is at offset 4, the raw state is at offset 18, compare them to see if the paddles are mapped */ paddles_mapped = (SDL_memcmp(&data[4], &data[18], 14) != 0); } else /* if (size == 38) */ { /* XBox One Elite Series 2 */ paddle_index = 18; button1_bit = 0x04; button2_bit = 0x01; button3_bit = 0x08; button4_bit = 0x02; paddles_mapped = (data[19] != 0); } #ifdef DEBUG_XBOX_PROTOCOL SDL_Log(">>> Paddles: %d,%d,%d,%d mapped = %s\n", (data[paddle_index] & button1_bit) ? 1 : 0, (data[paddle_index] & button2_bit) ? 1 : 0, (data[paddle_index] & button3_bit) ? 1 : 0, (data[paddle_index] & button4_bit) ? 1 : 0, paddles_mapped ? "TRUE" : "FALSE" ); #endif if (paddles_mapped) { /* Respect that the paddles are being used for other controls and don't pass them on to the app */ data[paddle_index] = 0; } if (ctx->last_state[paddle_index] != data[paddle_index]) { SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_MAX+0, (data[paddle_index] & button1_bit) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_MAX+1, (data[paddle_index] & button2_bit) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_MAX+2, (data[paddle_index] & button3_bit) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_MAX+3, (data[paddle_index] & button4_bit) ? SDL_PRESSED : SDL_RELEASED); } } axis = ((int)*(Sint16*)(&data[6]) * 64) - 32768; if (axis == 32704) { axis = 32767; } if (axis == -32768 && size == 30 && (data[22] & 0x80) != 0) { axis = 32767; } SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, axis); axis = ((int)*(Sint16*)(&data[8]) * 64) - 32768; if (axis == -32768 && size == 30 && (data[22] & 0x40) != 0) { axis = 32767; } if (axis == 32704) { axis = 32767; } SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, axis); axis = *(Sint16*)(&data[10]); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTX, axis); axis = *(Sint16*)(&data[12]); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTY, ~axis); axis = *(Sint16*)(&data[14]); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTX, axis); axis = *(Sint16*)(&data[16]); SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTY, ~axis); SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); } static void HIDAPI_DriverXboxOne_HandleModePacket(SDL_Joystick *joystick, hid_device *dev, SDL_DriverXboxOne_Context *ctx, Uint8 *data, int size) { if (data[1] == 0x30) { /* The Xbox One S controller needs acks for mode reports */ const Uint8 seqnum = data[2]; const Uint8 ack[] = { 0x01, 0x20, seqnum, 0x09, 0x00, 0x07, 0x20, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 }; hid_write(dev, ack, sizeof(ack)); } SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, (data[4] & 0x01) ? SDL_PRESSED : SDL_RELEASED); } static void HIDAPI_DriverXboxOneBluetooth_HandleStatePacketV1(SDL_Joystick *joystick, hid_device *dev, SDL_DriverXboxOne_Context *ctx, Uint8 *data, int size) { Sint16 axis; if (ctx->last_state[14] != data[14]) { SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_A, (data[14] & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_B, (data[14] & 0x02) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_X, (data[14] & 0x04) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_Y, (data[14] & 0x08) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSHOULDER, (data[14] & 0x10) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, (data[14] & 0x20) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_BACK, (data[14] & 0x40) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_START, (data[14] & 0x80) ? SDL_PRESSED : SDL_RELEASED); } if (ctx->last_state[15] != data[15]) { SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSTICK, (data[15] & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSTICK, (data[15] & 0x02) ? SDL_PRESSED : SDL_RELEASED); } if (ctx->last_state[13] != data[13]) { SDL_bool dpad_up = SDL_FALSE; SDL_bool dpad_down = SDL_FALSE; SDL_bool dpad_left = SDL_FALSE; SDL_bool dpad_right = SDL_FALSE; switch (data[13]) { case 1: dpad_up = SDL_TRUE; break; case 2: dpad_up = SDL_TRUE; dpad_right = SDL_TRUE; break; case 3: dpad_right = SDL_TRUE; break; case 4: dpad_right = SDL_TRUE; dpad_down = SDL_TRUE; break; case 5: dpad_down = SDL_TRUE; break; case 6: dpad_left = SDL_TRUE; dpad_down = SDL_TRUE; break; case 7: dpad_left = SDL_TRUE; break; case 8: dpad_up = SDL_TRUE; dpad_left = SDL_TRUE; break; default: break; } SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_DOWN, dpad_down); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_UP, dpad_up); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_RIGHT, dpad_right); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_LEFT, dpad_left); } axis = (int)*(Uint16*)(&data[1]) - 0x8000; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTX, axis); axis = (int)*(Uint16*)(&data[3]) - 0x8000; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTY, axis); axis = (int)*(Uint16*)(&data[5]) - 0x8000; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTX, axis); axis = (int)*(Uint16*)(&data[7]) - 0x8000; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTY, axis); axis = ((int)*(Sint16*)(&data[9]) * 64) - 32768; if (axis == 32704) { axis = 32767; } SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, axis); axis = ((int)*(Sint16*)(&data[11]) * 64) - 32768; if (axis == 32704) { axis = 32767; } SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, axis); SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); } static void HIDAPI_DriverXboxOneBluetooth_HandleStatePacketV2(SDL_Joystick *joystick, hid_device *dev, SDL_DriverXboxOne_Context *ctx, Uint8 *data, int size) { Sint16 axis; if (ctx->last_state[14] != data[14]) { SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_A, (data[14] & 0x01) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_B, (data[14] & 0x02) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_X, (data[14] & 0x08) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_Y, (data[14] & 0x10) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSHOULDER, (data[14] & 0x40) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, (data[14] & 0x80) ? SDL_PRESSED : SDL_RELEASED); } if (ctx->last_state[15] != data[15]) { SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_START, (data[15] & 0x08) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSTICK, (data[15] & 0x20) ? SDL_PRESSED : SDL_RELEASED); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSTICK, (data[15] & 0x40) ? SDL_PRESSED : SDL_RELEASED); if (ctx->wireless_protocol == XBOX_ONE_WIRELESS_PROTOCOL_UNKNOWN) { if (data[15] & 0x10) { ctx->wireless_protocol = XBOX_ONE_WIRELESS_PROTOCOL_V2; } } if (ctx->wireless_protocol == XBOX_ONE_WIRELESS_PROTOCOL_V2) { SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, (data[15] & 0x10) ? SDL_PRESSED : SDL_RELEASED); } } if (ctx->last_state[16] != data[16]) { SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_BACK, (data[16] & 0x01) ? SDL_PRESSED : SDL_RELEASED); } if (ctx->last_state[13] != data[13]) { SDL_bool dpad_up = SDL_FALSE; SDL_bool dpad_down = SDL_FALSE; SDL_bool dpad_left = SDL_FALSE; SDL_bool dpad_right = SDL_FALSE; switch (data[13]) { case 1: dpad_up = SDL_TRUE; break; case 2: dpad_up = SDL_TRUE; dpad_right = SDL_TRUE; break; case 3: dpad_right = SDL_TRUE; break; case 4: dpad_right = SDL_TRUE; dpad_down = SDL_TRUE; break; case 5: dpad_down = SDL_TRUE; break; case 6: dpad_left = SDL_TRUE; dpad_down = SDL_TRUE; break; case 7: dpad_left = SDL_TRUE; break; case 8: dpad_up = SDL_TRUE; dpad_left = SDL_TRUE; break; default: break; } SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_DOWN, dpad_down); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_UP, dpad_up); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_RIGHT, dpad_right); SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_LEFT, dpad_left); } axis = (int)*(Uint16*)(&data[1]) - 0x8000; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTX, axis); axis = (int)*(Uint16*)(&data[3]) - 0x8000; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTY, axis); axis = (int)*(Uint16*)(&data[5]) - 0x8000; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTX, axis); axis = (int)*(Uint16*)(&data[7]) - 0x8000; SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTY, axis); axis = ((int)*(Sint16*)(&data[9]) * 64) - 32768; if (axis == 32704) { axis = 32767; } SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, axis); axis = ((int)*(Sint16*)(&data[11]) * 64) - 32768; if (axis == 32704) { axis = 32767; } SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, axis); SDL_memcpy(ctx->last_state, data, SDL_min(size, sizeof(ctx->last_state))); } static void HIDAPI_DriverXboxOneBluetooth_HandleGuidePacket(SDL_Joystick *joystick, hid_device *dev, SDL_DriverXboxOne_Context *ctx, Uint8 *data, int size) { ctx->wireless_protocol = XBOX_ONE_WIRELESS_PROTOCOL_V1; SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, (data[1] & 0x01) ? SDL_PRESSED : SDL_RELEASED); } static SDL_bool HIDAPI_DriverXboxOne_UpdateDevice(SDL_HIDAPI_Device *device) { SDL_DriverXboxOne_Context *ctx = (SDL_DriverXboxOne_Context *)device->context; SDL_Joystick *joystick = NULL; Uint8 data[USB_PACKET_LENGTH]; int size; if (device->num_joysticks > 0) { joystick = SDL_JoystickFromInstanceID(device->joysticks[0]); } if (!joystick) { return SDL_FALSE; } if (!ctx->initialized && !ControllerSendsWaitingForInit(device->vendor_id, device->product_id)) { if (SDL_TICKS_PASSED(SDL_GetTicks(), ctx->start_time + CONTROLLER_INIT_DELAY_MS)) { if (!SendControllerInit(device, ctx)) { HIDAPI_JoystickDisconnected(device, joystick->instance_id, SDL_FALSE); return SDL_FALSE; } ctx->initialized = SDL_TRUE; ctx->initialized_time = SDL_GetTicks(); ctx->input_ready = SDL_FALSE; } } while ((size = hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) { #ifdef DEBUG_XBOX_PROTOCOL DumpPacket("Xbox One packet: size = %d", data, size); #endif if (ctx->bluetooth) { switch (data[0]) { case 0x01: switch (size) { case 16: HIDAPI_DriverXboxOneBluetooth_HandleStatePacketV1(joystick, device->dev, ctx, data, size); break; case 17: HIDAPI_DriverXboxOneBluetooth_HandleStatePacketV2(joystick, device->dev, ctx, data, size); break; default: break; } break; case 0x02: HIDAPI_DriverXboxOneBluetooth_HandleGuidePacket(joystick, device->dev, ctx, data, size); break; default: #ifdef DEBUG_JOYSTICK SDL_Log("Unknown Xbox One packet: 0x%.2x\n", data[0]); #endif break; } } else { switch (data[0]) { case 0x02: /* Controller is connected and waiting for initialization */ if (!ctx->initialized) { #ifdef DEBUG_XBOX_PROTOCOL SDL_Log("Delay after init: %ums\n", SDL_GetTicks() - ctx->start_time); #endif if (!SendControllerInit(device, ctx)) { HIDAPI_JoystickDisconnected(device, joystick->instance_id, SDL_FALSE); return SDL_FALSE; } ctx->initialized = SDL_TRUE; ctx->initialized_time = SDL_GetTicks(); ctx->input_ready = SDL_FALSE; } break; case 0x03: /* Controller heartbeat */ break; case 0x20: if (!ctx->input_ready) { if (!SDL_TICKS_PASSED(SDL_GetTicks(), ctx->initialized_time + CONTROLLER_INPUT_DELAY_MS)) { #ifdef DEBUG_XBOX_PROTOCOL SDL_Log("Spurious input at %ums\n", SDL_GetTicks() - ctx->initialized_time); #endif break; } ctx->input_ready = SDL_TRUE; } HIDAPI_DriverXboxOne_HandleStatePacket(joystick, device->dev, ctx, data, size); break; case 0x07: HIDAPI_DriverXboxOne_HandleModePacket(joystick, device->dev, ctx, data, size); break; default: #ifdef DEBUG_JOYSTICK SDL_Log("Unknown Xbox One packet: 0x%.2x\n", data[0]); #endif break; } } } if (size < 0) { /* Read error, device is disconnected */ HIDAPI_JoystickDisconnected(device, joystick->instance_id, SDL_FALSE); } return (size >= 0); } static void HIDAPI_DriverXboxOne_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick) { hid_close(device->dev); device->dev = NULL; SDL_free(device->context); device->context = NULL; } static void HIDAPI_DriverXboxOne_FreeDevice(SDL_HIDAPI_Device *device) { } SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverXboxOne = { SDL_HINT_JOYSTICK_HIDAPI_XBOX, SDL_TRUE, HIDAPI_DriverXboxOne_IsSupportedDevice, HIDAPI_DriverXboxOne_GetDeviceName, HIDAPI_DriverXboxOne_InitDevice, HIDAPI_DriverXboxOne_GetDevicePlayerIndex, HIDAPI_DriverXboxOne_SetDevicePlayerIndex, HIDAPI_DriverXboxOne_UpdateDevice, HIDAPI_DriverXboxOne_OpenJoystick, HIDAPI_DriverXboxOne_RumbleJoystick, HIDAPI_DriverXboxOne_CloseJoystick, HIDAPI_DriverXboxOne_FreeDevice, NULL }; #endif /* SDL_JOYSTICK_HIDAPI_XBOXONE */ #endif /* SDL_JOYSTICK_HIDAPI */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/hidapi/SDL_hidapi_xboxone.c
C
apache-2.0
32,393
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_HIDAPI #include "SDL_assert.h" #include "SDL_atomic.h" #include "SDL_endian.h" #include "SDL_hints.h" #include "SDL_thread.h" #include "SDL_timer.h" #include "SDL_joystick.h" #include "../SDL_sysjoystick.h" #include "SDL_hidapijoystick_c.h" #include "SDL_hidapi_rumble.h" #include "../../SDL_hints_c.h" #if defined(__WIN32__) #include "../../core/windows/SDL_windows.h" #include "../windows/SDL_rawinputjoystick_c.h" #endif #if defined(__MACOSX__) #include <CoreFoundation/CoreFoundation.h> #include <mach/mach.h> #include <IOKit/IOKitLib.h> #include <IOKit/hid/IOHIDDevice.h> #include <IOKit/usb/USBSpec.h> #endif #if defined(__LINUX__) #include "../../core/linux/SDL_udev.h" #ifdef SDL_USE_LIBUDEV #include <poll.h> #endif #endif struct joystick_hwdata { SDL_HIDAPI_Device *device; }; static SDL_HIDAPI_DeviceDriver *SDL_HIDAPI_drivers[] = { #ifdef SDL_JOYSTICK_HIDAPI_PS4 &SDL_HIDAPI_DriverPS4, #endif #ifdef SDL_JOYSTICK_HIDAPI_STEAM &SDL_HIDAPI_DriverSteam, #endif #ifdef SDL_JOYSTICK_HIDAPI_SWITCH &SDL_HIDAPI_DriverSwitch, #endif #ifdef SDL_JOYSTICK_HIDAPI_XBOX360 &SDL_HIDAPI_DriverXbox360, &SDL_HIDAPI_DriverXbox360W, #endif #ifdef SDL_JOYSTICK_HIDAPI_XBOXONE &SDL_HIDAPI_DriverXboxOne, #endif #ifdef SDL_JOYSTICK_HIDAPI_GAMECUBE &SDL_HIDAPI_DriverGameCube, #endif }; static int SDL_HIDAPI_numdrivers = 0; static SDL_SpinLock SDL_HIDAPI_spinlock; static SDL_HIDAPI_Device *SDL_HIDAPI_devices; static int SDL_HIDAPI_numjoysticks = 0; static SDL_bool initialized = SDL_FALSE; static SDL_bool shutting_down = SDL_FALSE; #if defined(SDL_USE_LIBUDEV) static const SDL_UDEV_Symbols * usyms = NULL; #endif static struct { SDL_bool m_bHaveDevicesChanged; SDL_bool m_bCanGetNotifications; Uint32 m_unLastDetect; #if defined(__WIN32__) SDL_threadID m_nThreadID; WNDCLASSEXA m_wndClass; HWND m_hwndMsg; HDEVNOTIFY m_hNotify; double m_flLastWin32MessageCheck; #endif #if defined(__MACOSX__) IONotificationPortRef m_notificationPort; mach_port_t m_notificationMach; #endif #if defined(SDL_USE_LIBUDEV) struct udev *m_pUdev; struct udev_monitor *m_pUdevMonitor; int m_nUdevFd; #endif } SDL_HIDAPI_discovery; #ifdef __WIN32__ struct _DEV_BROADCAST_HDR { DWORD dbch_size; DWORD dbch_devicetype; DWORD dbch_reserved; }; typedef struct _DEV_BROADCAST_DEVICEINTERFACE_A { DWORD dbcc_size; DWORD dbcc_devicetype; DWORD dbcc_reserved; GUID dbcc_classguid; char dbcc_name[ 1 ]; } DEV_BROADCAST_DEVICEINTERFACE_A, *PDEV_BROADCAST_DEVICEINTERFACE_A; typedef struct _DEV_BROADCAST_HDR DEV_BROADCAST_HDR; #define DBT_DEVICEARRIVAL 0x8000 /* system detected a new device */ #define DBT_DEVICEREMOVECOMPLETE 0x8004 /* device was removed from the system */ #define DBT_DEVTYP_DEVICEINTERFACE 0x00000005 /* device interface class */ #define DBT_DEVNODES_CHANGED 0x0007 #define DBT_CONFIGCHANGED 0x0018 #define DBT_DEVICETYPESPECIFIC 0x8005 /* type specific event */ #define DBT_DEVINSTSTARTED 0x8008 /* device installed and started */ #include <initguid.h> DEFINE_GUID(GUID_DEVINTERFACE_USB_DEVICE, 0xA5DCBF10L, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED); static LRESULT CALLBACK ControllerWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_DEVICECHANGE: switch (wParam) { case DBT_DEVICEARRIVAL: case DBT_DEVICEREMOVECOMPLETE: if (((DEV_BROADCAST_HDR*)lParam)->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) { SDL_HIDAPI_discovery.m_bHaveDevicesChanged = SDL_TRUE; } break; } return TRUE; } return DefWindowProc(hwnd, message, wParam, lParam); } #endif /* __WIN32__ */ #if defined(__MACOSX__) static void CallbackIOServiceFunc(void *context, io_iterator_t portIterator) { /* Must drain the iterator, or we won't receive new notifications */ io_object_t entry; while ((entry = IOIteratorNext(portIterator)) != 0) { IOObjectRelease(entry); *(SDL_bool*)context = SDL_TRUE; } } #endif /* __MACOSX__ */ static void HIDAPI_InitializeDiscovery() { SDL_HIDAPI_discovery.m_bHaveDevicesChanged = SDL_TRUE; SDL_HIDAPI_discovery.m_bCanGetNotifications = SDL_FALSE; SDL_HIDAPI_discovery.m_unLastDetect = 0; #if defined(__WIN32__) SDL_HIDAPI_discovery.m_nThreadID = SDL_ThreadID(); SDL_memset(&SDL_HIDAPI_discovery.m_wndClass, 0x0, sizeof(SDL_HIDAPI_discovery.m_wndClass)); SDL_HIDAPI_discovery.m_wndClass.hInstance = GetModuleHandle(NULL); SDL_HIDAPI_discovery.m_wndClass.lpszClassName = "SDL_HIDAPI_DEVICE_DETECTION"; SDL_HIDAPI_discovery.m_wndClass.lpfnWndProc = ControllerWndProc; /* This function is called by windows */ SDL_HIDAPI_discovery.m_wndClass.cbSize = sizeof(WNDCLASSEX); RegisterClassExA(&SDL_HIDAPI_discovery.m_wndClass); SDL_HIDAPI_discovery.m_hwndMsg = CreateWindowExA(0, "SDL_HIDAPI_DEVICE_DETECTION", NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL); { DEV_BROADCAST_DEVICEINTERFACE_A devBroadcast; SDL_memset( &devBroadcast, 0x0, sizeof( devBroadcast ) ); devBroadcast.dbcc_size = sizeof( devBroadcast ); devBroadcast.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBroadcast.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE; /* DEVICE_NOTIFY_ALL_INTERFACE_CLASSES is important, makes GUID_DEVINTERFACE_USB_DEVICE ignored, * but that seems to be necessary to get a notice after each individual usb input device actually * installs, rather than just as the composite device is seen. */ SDL_HIDAPI_discovery.m_hNotify = RegisterDeviceNotification( SDL_HIDAPI_discovery.m_hwndMsg, &devBroadcast, DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES ); SDL_HIDAPI_discovery.m_bCanGetNotifications = ( SDL_HIDAPI_discovery.m_hNotify != 0 ); } #endif /* __WIN32__ */ #if defined(__MACOSX__) SDL_HIDAPI_discovery.m_notificationPort = IONotificationPortCreate(kIOMasterPortDefault); if (SDL_HIDAPI_discovery.m_notificationPort) { { io_iterator_t portIterator = 0; io_object_t entry; IOReturn result = IOServiceAddMatchingNotification( SDL_HIDAPI_discovery.m_notificationPort, kIOFirstMatchNotification, IOServiceMatching(kIOHIDDeviceKey), CallbackIOServiceFunc, &SDL_HIDAPI_discovery.m_bHaveDevicesChanged, &portIterator); if (result == 0) { /* Must drain the existing iterator, or we won't receive new notifications */ while ((entry = IOIteratorNext(portIterator)) != 0) { IOObjectRelease(entry); } } else { IONotificationPortDestroy(SDL_HIDAPI_discovery.m_notificationPort); SDL_HIDAPI_discovery.m_notificationPort = nil; } } { io_iterator_t portIterator = 0; io_object_t entry; IOReturn result = IOServiceAddMatchingNotification( SDL_HIDAPI_discovery.m_notificationPort, kIOTerminatedNotification, IOServiceMatching(kIOHIDDeviceKey), CallbackIOServiceFunc, &SDL_HIDAPI_discovery.m_bHaveDevicesChanged, &portIterator); if (result == 0) { /* Must drain the existing iterator, or we won't receive new notifications */ while ((entry = IOIteratorNext(portIterator)) != 0) { IOObjectRelease(entry); } } else { IONotificationPortDestroy(SDL_HIDAPI_discovery.m_notificationPort); SDL_HIDAPI_discovery.m_notificationPort = nil; } } } SDL_HIDAPI_discovery.m_notificationMach = MACH_PORT_NULL; if (SDL_HIDAPI_discovery.m_notificationPort) { SDL_HIDAPI_discovery.m_notificationMach = IONotificationPortGetMachPort(SDL_HIDAPI_discovery.m_notificationPort); } SDL_HIDAPI_discovery.m_bCanGetNotifications = (SDL_HIDAPI_discovery.m_notificationMach != MACH_PORT_NULL); #endif // __MACOSX__ #if defined(SDL_USE_LIBUDEV) SDL_HIDAPI_discovery.m_pUdev = NULL; SDL_HIDAPI_discovery.m_pUdevMonitor = NULL; SDL_HIDAPI_discovery.m_nUdevFd = -1; usyms = SDL_UDEV_GetUdevSyms(); if (usyms) { SDL_HIDAPI_discovery.m_pUdev = usyms->udev_new(); } if (SDL_HIDAPI_discovery.m_pUdev) { SDL_HIDAPI_discovery.m_pUdevMonitor = usyms->udev_monitor_new_from_netlink(SDL_HIDAPI_discovery.m_pUdev, "udev"); if (SDL_HIDAPI_discovery.m_pUdevMonitor) { usyms->udev_monitor_enable_receiving(SDL_HIDAPI_discovery.m_pUdevMonitor); SDL_HIDAPI_discovery.m_nUdevFd = usyms->udev_monitor_get_fd(SDL_HIDAPI_discovery.m_pUdevMonitor); SDL_HIDAPI_discovery.m_bCanGetNotifications = SDL_TRUE; } } #endif /* SDL_USE_LIBUDEV */ } static void HIDAPI_UpdateDiscovery() { if (!SDL_HIDAPI_discovery.m_bCanGetNotifications) { const Uint32 SDL_HIDAPI_DETECT_INTERVAL_MS = 3000; /* Update every 3 seconds */ Uint32 now = SDL_GetTicks(); if (!SDL_HIDAPI_discovery.m_unLastDetect || SDL_TICKS_PASSED(now, SDL_HIDAPI_discovery.m_unLastDetect + SDL_HIDAPI_DETECT_INTERVAL_MS)) { SDL_HIDAPI_discovery.m_bHaveDevicesChanged = SDL_TRUE; SDL_HIDAPI_discovery.m_unLastDetect = now; } return; } #if defined(__WIN32__) #if 0 /* just let the usual SDL_PumpEvents loop dispatch these, fixing bug 4286. --ryan. */ /* We'll only get messages on the same thread that created the window */ if (SDL_ThreadID() == SDL_HIDAPI_discovery.m_nThreadID) { MSG msg; while (PeekMessage(&msg, SDL_HIDAPI_discovery.m_hwndMsg, 0, 0, PM_NOREMOVE)) { if (GetMessageA(&msg, SDL_HIDAPI_discovery.m_hwndMsg, 0, 0) != 0) { TranslateMessage(&msg); DispatchMessage(&msg); } } } #endif #endif /* __WIN32__ */ #if defined(__MACOSX__) if (SDL_HIDAPI_discovery.m_notificationPort) { struct { mach_msg_header_t hdr; char payload[ 4096 ]; } msg; while (mach_msg(&msg.hdr, MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0, sizeof(msg), SDL_HIDAPI_discovery.m_notificationMach, 0, MACH_PORT_NULL) == KERN_SUCCESS) { IODispatchCalloutFromMessage(NULL, &msg.hdr, SDL_HIDAPI_discovery.m_notificationPort); } } #endif #if defined(SDL_USE_LIBUDEV) if (SDL_HIDAPI_discovery.m_nUdevFd >= 0) { /* Drain all notification events. * We don't expect a lot of device notifications so just * do a new discovery on any kind or number of notifications. * This could be made more restrictive if necessary. */ for (;;) { struct pollfd PollUdev; struct udev_device *pUdevDevice; PollUdev.fd = SDL_HIDAPI_discovery.m_nUdevFd; PollUdev.events = POLLIN; if (poll(&PollUdev, 1, 0) != 1) { break; } SDL_HIDAPI_discovery.m_bHaveDevicesChanged = SDL_TRUE; pUdevDevice = usyms->udev_monitor_receive_device(SDL_HIDAPI_discovery.m_pUdevMonitor); if (pUdevDevice) { usyms->udev_device_unref(pUdevDevice); } } } #endif } static void HIDAPI_ShutdownDiscovery() { #if defined(__WIN32__) if (SDL_HIDAPI_discovery.m_hNotify) UnregisterDeviceNotification(SDL_HIDAPI_discovery.m_hNotify); if (SDL_HIDAPI_discovery.m_hwndMsg) { DestroyWindow(SDL_HIDAPI_discovery.m_hwndMsg); } UnregisterClassA(SDL_HIDAPI_discovery.m_wndClass.lpszClassName, SDL_HIDAPI_discovery.m_wndClass.hInstance); #endif #if defined(__MACOSX__) if (SDL_HIDAPI_discovery.m_notificationPort) { IONotificationPortDestroy(SDL_HIDAPI_discovery.m_notificationPort); } #endif #if defined(SDL_USE_LIBUDEV) if (usyms) { if (SDL_HIDAPI_discovery.m_pUdevMonitor) { usyms->udev_monitor_unref(SDL_HIDAPI_discovery.m_pUdevMonitor); } if (SDL_HIDAPI_discovery.m_pUdev) { usyms->udev_unref(SDL_HIDAPI_discovery.m_pUdev); } SDL_UDEV_ReleaseUdevSyms(); usyms = NULL; } #endif } static void HIDAPI_JoystickDetect(void); static void HIDAPI_JoystickClose(SDL_Joystick * joystick); static SDL_bool HIDAPI_IsDeviceSupported(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name) { int i; SDL_GameControllerType type = SDL_GetJoystickGameControllerType(name, vendor_id, product_id, -1, 0, 0, 0); for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) { SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i]; if (driver->enabled && driver->IsSupportedDevice(name, type, vendor_id, product_id, version, -1, 0, 0, 0)) { return SDL_TRUE; } } return SDL_FALSE; } static SDL_HIDAPI_DeviceDriver * HIDAPI_GetDeviceDriver(SDL_HIDAPI_Device *device) { const Uint16 USAGE_PAGE_GENERIC_DESKTOP = 0x0001; const Uint16 USAGE_JOYSTICK = 0x0004; const Uint16 USAGE_GAMEPAD = 0x0005; const Uint16 USAGE_MULTIAXISCONTROLLER = 0x0008; int i; SDL_GameControllerType type; if (SDL_ShouldIgnoreJoystick(device->name, device->guid)) { return NULL; } #ifdef SDL_JOYSTICK_RAWINPUT if (RAWINPUT_IsDevicePresent(device->vendor_id, device->product_id, device->version)) { /* The RAWINPUT driver is taking care of this device */ return NULL; } #endif if (device->vendor_id != USB_VENDOR_VALVE) { if (device->usage_page && device->usage_page != USAGE_PAGE_GENERIC_DESKTOP) { return NULL; } if (device->usage && device->usage != USAGE_JOYSTICK && device->usage != USAGE_GAMEPAD && device->usage != USAGE_MULTIAXISCONTROLLER) { return NULL; } } type = SDL_GetJoystickGameControllerType(device->name, device->vendor_id, device->product_id, device->interface_number, device->interface_class, device->interface_subclass, device->interface_protocol); for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) { SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i]; if (driver->enabled && driver->IsSupportedDevice(device->name, type, device->vendor_id, device->product_id, device->version, device->interface_number, device->interface_class, device->interface_subclass, device->interface_protocol)) { return driver; } } return NULL; } static SDL_HIDAPI_Device * HIDAPI_GetDeviceByIndex(int device_index, SDL_JoystickID *pJoystickID) { SDL_HIDAPI_Device *device = SDL_HIDAPI_devices; while (device) { if (device->driver) { if (device_index < device->num_joysticks) { if (pJoystickID) { *pJoystickID = device->joysticks[device_index]; } return device; } device_index -= device->num_joysticks; } device = device->next; } return NULL; } static SDL_HIDAPI_Device * HIDAPI_GetJoystickByInfo(const char *path, Uint16 vendor_id, Uint16 product_id) { SDL_HIDAPI_Device *device = SDL_HIDAPI_devices; while (device) { if (device->vendor_id == vendor_id && device->product_id == product_id && SDL_strcmp(device->path, path) == 0) { break; } device = device->next; } return device; } static void HIDAPI_SetupDeviceDriver(SDL_HIDAPI_Device *device) { if (device->driver) { /* Already setup */ return; } device->driver = HIDAPI_GetDeviceDriver(device); if (device->driver) { const char *name = device->driver->GetDeviceName(device->vendor_id, device->product_id); if (name) { SDL_free(device->name); device->name = SDL_strdup(name); } } /* Initialize the device, which may cause a connected event */ if (device->driver && !device->driver->InitDevice(device)) { device->driver = NULL; } } static void HIDAPI_CleanupDeviceDriver(SDL_HIDAPI_Device *device) { if (!device->driver) { /* Already cleaned up */ return; } /* Disconnect any joysticks */ while (device->num_joysticks) { HIDAPI_JoystickDisconnected(device, device->joysticks[0], SDL_FALSE); } device->driver->FreeDevice(device); device->driver = NULL; } static void SDLCALL SDL_HIDAPIDriverHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) { int i; SDL_HIDAPI_Device *device; SDL_bool enabled = SDL_GetStringBoolean(hint, SDL_TRUE); if (SDL_strcmp(name, SDL_HINT_JOYSTICK_HIDAPI) == 0) { for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) { SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i]; driver->enabled = SDL_GetHintBoolean(driver->hint, enabled); } } else { for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) { SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i]; if (SDL_strcmp(name, driver->hint) == 0) { driver->enabled = enabled; } } } SDL_HIDAPI_numdrivers = 0; for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) { SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i]; if (driver->enabled) { ++SDL_HIDAPI_numdrivers; } } /* Update device list if driver availability changes */ SDL_LockJoysticks(); for (device = SDL_HIDAPI_devices; device; device = device->next) { if (device->driver && !device->driver->enabled) { HIDAPI_CleanupDeviceDriver(device); } HIDAPI_SetupDeviceDriver(device); } SDL_UnlockJoysticks(); } static int HIDAPI_JoystickInit(void) { int i; if (initialized) { return 0; } #if defined(__MACOSX__) || defined(__IPHONEOS__) || defined(__TVOS__) /* The hidapi framwork is weak-linked on Apple platforms */ int HID_API_EXPORT HID_API_CALL hid_init(void) __attribute__((weak_import)); if (hid_init == NULL) { SDL_SetError("Couldn't initialize hidapi, framework not available"); return -1; } #endif /* __MACOSX__ || __IPHONEOS__ || __TVOS__ */ if (hid_init() < 0) { SDL_SetError("Couldn't initialize hidapi"); return -1; } #ifdef __WINDOWS__ /* On Windows, turns out HIDAPI for Xbox controllers doesn't allow background input, so off by default */ SDL_SetHintWithPriority(SDL_HINT_JOYSTICK_HIDAPI_XBOX, "0", SDL_HINT_DEFAULT); #endif for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) { SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i]; SDL_AddHintCallback(driver->hint, SDL_HIDAPIDriverHintChanged, NULL); } SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPIDriverHintChanged, NULL); HIDAPI_InitializeDiscovery(); HIDAPI_JoystickDetect(); HIDAPI_UpdateDevices(); initialized = SDL_TRUE; return 0; } SDL_bool HIDAPI_JoystickConnected(SDL_HIDAPI_Device *device, SDL_JoystickID *pJoystickID, SDL_bool is_external) { SDL_JoystickID joystickID; SDL_JoystickID *joysticks = (SDL_JoystickID *)SDL_realloc(device->joysticks, (device->num_joysticks + 1)*sizeof(*device->joysticks)); if (!joysticks) { return SDL_FALSE; } joystickID = SDL_GetNextJoystickInstanceID(); device->joysticks = joysticks; device->joysticks[device->num_joysticks++] = joystickID; if (!is_external) { ++SDL_HIDAPI_numjoysticks; } SDL_PrivateJoystickAdded(joystickID); if (pJoystickID) { *pJoystickID = joystickID; } return SDL_TRUE; } void HIDAPI_JoystickDisconnected(SDL_HIDAPI_Device *device, SDL_JoystickID joystickID, SDL_bool is_external) { int i, size; for (i = 0; i < device->num_joysticks; ++i) { if (device->joysticks[i] == joystickID) { SDL_Joystick *joystick = SDL_JoystickFromInstanceID(joystickID); if (joystick && !is_external) { HIDAPI_JoystickClose(joystick); } size = (device->num_joysticks - i - 1) * sizeof(SDL_JoystickID); SDL_memmove(&device->joysticks[i], &device->joysticks[i+1], size); --device->num_joysticks; if (!is_external) { --SDL_HIDAPI_numjoysticks; } if (device->num_joysticks == 0) { SDL_free(device->joysticks); device->joysticks = NULL; } if (!shutting_down) { SDL_PrivateJoystickRemoved(joystickID); } return; } } } static int HIDAPI_JoystickGetCount(void) { return SDL_HIDAPI_numjoysticks; } static void HIDAPI_AddDevice(struct hid_device_info *info) { SDL_HIDAPI_Device *device; SDL_HIDAPI_Device *curr, *last = NULL; for (curr = SDL_HIDAPI_devices, last = NULL; curr; last = curr, curr = curr->next) { continue; } device = (SDL_HIDAPI_Device *)SDL_calloc(1, sizeof(*device)); if (!device) { return; } device->path = SDL_strdup(info->path); if (!device->path) { SDL_free(device); return; } device->seen = SDL_TRUE; device->vendor_id = info->vendor_id; device->product_id = info->product_id; device->version = info->release_number; device->interface_number = info->interface_number; device->interface_class = info->interface_class; device->interface_subclass = info->interface_subclass; device->interface_protocol = info->interface_protocol; device->usage_page = info->usage_page; device->usage = info->usage; { /* FIXME: Is there any way to tell whether this is a Bluetooth device? */ const Uint16 vendor = device->vendor_id; const Uint16 product = device->product_id; const Uint16 version = device->version; Uint16 *guid16 = (Uint16 *)device->guid.data; *guid16++ = SDL_SwapLE16(SDL_HARDWARE_BUS_USB); *guid16++ = 0; *guid16++ = SDL_SwapLE16(vendor); *guid16++ = 0; *guid16++ = SDL_SwapLE16(product); *guid16++ = 0; *guid16++ = SDL_SwapLE16(version); *guid16++ = 0; /* Note that this is a HIDAPI device for special handling elsewhere */ device->guid.data[14] = 'h'; device->guid.data[15] = 0; } device->dev_lock = SDL_CreateMutex(); /* Need the device name before getting the driver to know whether to ignore this device */ { char *manufacturer_string = NULL; char *product_string = NULL; if (info->manufacturer_string) { manufacturer_string = SDL_iconv_string("UTF-8", "WCHAR_T", (char*)info->manufacturer_string, (SDL_wcslen(info->manufacturer_string)+1)*sizeof(wchar_t)); if (!manufacturer_string) { if (sizeof(wchar_t) == sizeof(Uint16)) { manufacturer_string = SDL_iconv_string("UTF-8", "UCS-2-INTERNAL", (char*)info->manufacturer_string, (SDL_wcslen(info->manufacturer_string)+1)*sizeof(wchar_t)); } else if (sizeof(wchar_t) == sizeof(Uint32)) { manufacturer_string = SDL_iconv_string("UTF-8", "UCS-4-INTERNAL", (char*)info->manufacturer_string, (SDL_wcslen(info->manufacturer_string)+1)*sizeof(wchar_t)); } } } if (info->product_string) { product_string = SDL_iconv_string("UTF-8", "WCHAR_T", (char*)info->product_string, (SDL_wcslen(info->product_string)+1)*sizeof(wchar_t)); if (!product_string) { if (sizeof(wchar_t) == sizeof(Uint16)) { product_string = SDL_iconv_string("UTF-8", "UCS-2-INTERNAL", (char*)info->product_string, (SDL_wcslen(info->product_string)+1)*sizeof(wchar_t)); } else if (sizeof(wchar_t) == sizeof(Uint32)) { product_string = SDL_iconv_string("UTF-8", "UCS-4-INTERNAL", (char*)info->product_string, (SDL_wcslen(info->product_string)+1)*sizeof(wchar_t)); } } } device->name = SDL_CreateJoystickName(device->vendor_id, device->product_id, manufacturer_string, product_string); if (manufacturer_string) { SDL_free(manufacturer_string); } if (product_string) { SDL_free(product_string); } if (!device->name) { SDL_free(device->path); SDL_free(device); return; } } /* Add it to the list */ if (last) { last->next = device; } else { SDL_HIDAPI_devices = device; } HIDAPI_SetupDeviceDriver(device); #ifdef DEBUG_HIDAPI SDL_Log("Added HIDAPI device '%s' VID 0x%.4x, PID 0x%.4x, version %d, interface %d, interface_class %d, interface_subclass %d, interface_protocol %d, usage page 0x%.4x, usage 0x%.4x, path = %s, driver = %s (%s)\n", device->name, device->vendor_id, device->product_id, device->version, device->interface_number, device->interface_class, device->interface_subclass, device->interface_protocol, device->usage_page, device->usage, device->path, device->driver ? device->driver->hint : "NONE", device->driver && device->driver->enabled ? "ENABLED" : "DISABLED"); #endif } static void HIDAPI_DelDevice(SDL_HIDAPI_Device *device) { SDL_HIDAPI_Device *curr, *last; for (curr = SDL_HIDAPI_devices, last = NULL; curr; last = curr, curr = curr->next) { if (curr == device) { if (last) { last->next = curr->next; } else { SDL_HIDAPI_devices = curr->next; } HIDAPI_CleanupDeviceDriver(device); SDL_DestroyMutex(device->dev_lock); SDL_free(device->name); SDL_free(device->path); SDL_free(device); return; } } } static void HIDAPI_UpdateDeviceList(void) { SDL_HIDAPI_Device *device; struct hid_device_info *devs, *info; SDL_LockJoysticks(); /* Prepare the existing device list */ device = SDL_HIDAPI_devices; while (device) { device->seen = SDL_FALSE; device = device->next; } /* Enumerate the devices */ if (SDL_HIDAPI_numdrivers > 0) { devs = hid_enumerate(0, 0); if (devs) { for (info = devs; info; info = info->next) { device = HIDAPI_GetJoystickByInfo(info->path, info->vendor_id, info->product_id); if (device) { device->seen = SDL_TRUE; } else { HIDAPI_AddDevice(info); } } hid_free_enumeration(devs); } } /* Remove any devices that weren't seen */ device = SDL_HIDAPI_devices; while (device) { SDL_HIDAPI_Device *next = device->next; if (!device->seen) { HIDAPI_DelDevice(device); } device = next; } SDL_UnlockJoysticks(); } SDL_bool HIDAPI_IsDevicePresent(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name) { SDL_HIDAPI_Device *device; SDL_bool supported = SDL_FALSE; SDL_bool result = SDL_FALSE; /* Make sure we're initialized, as this could be called from other drivers during startup */ if (HIDAPI_JoystickInit() < 0) { return SDL_FALSE; } /* Only update the device list for devices we know might be supported. If we did this for every device, it would hit the USB driver too hard and potentially lock up the system. This won't catch devices that we support but can only detect using USB interface details, like Xbox controllers, but hopefully the device list update is responsive enough to catch those. */ supported = HIDAPI_IsDeviceSupported(vendor_id, product_id, version, name); #if defined(SDL_JOYSTICK_HIDAPI_XBOX360) || defined(SDL_JOYSTICK_HIDAPI_XBOXONE) if (!supported && (SDL_strstr(name, "Xbox") || SDL_strstr(name, "X-Box") || SDL_strstr(name, "XBOX"))) { supported = SDL_TRUE; } #endif /* SDL_JOYSTICK_HIDAPI_XBOX360 || SDL_JOYSTICK_HIDAPI_XBOXONE */ if (supported) { if (SDL_AtomicTryLock(&SDL_HIDAPI_spinlock)) { HIDAPI_UpdateDeviceList(); SDL_AtomicUnlock(&SDL_HIDAPI_spinlock); } } /* Note that this isn't a perfect check - there may be multiple devices with 0 VID/PID, or a different name than we have it listed here, etc, but if we support the device and we have something similar in our device list, mark it as present. */ SDL_LockJoysticks(); device = SDL_HIDAPI_devices; while (device) { if (device->vendor_id == vendor_id && device->product_id == product_id && device->driver) { result = SDL_TRUE; } device = device->next; } SDL_UnlockJoysticks(); /* If we're looking for the wireless XBox 360 controller, also look for the dongle */ if (!result && vendor_id == USB_VENDOR_MICROSOFT && product_id == 0x02a1) { return HIDAPI_IsDevicePresent(USB_VENDOR_MICROSOFT, 0x0719, version, name); } #ifdef DEBUG_HIDAPI SDL_Log("HIDAPI_IsDevicePresent() returning %s for 0x%.4x / 0x%.4x\n", result ? "true" : "false", vendor_id, product_id); #endif return result; } static void HIDAPI_JoystickDetect(void) { int i; if (SDL_AtomicTryLock(&SDL_HIDAPI_spinlock)) { HIDAPI_UpdateDiscovery(); if (SDL_HIDAPI_discovery.m_bHaveDevicesChanged) { /* FIXME: We probably need to schedule an update in a few seconds as well */ HIDAPI_UpdateDeviceList(); SDL_HIDAPI_discovery.m_bHaveDevicesChanged = SDL_FALSE; } SDL_AtomicUnlock(&SDL_HIDAPI_spinlock); } for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) { SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i]; if (driver->enabled && driver->PostUpdate) { driver->PostUpdate(); } } } void HIDAPI_UpdateDevices(void) { SDL_HIDAPI_Device *device; /* Update the devices, which may change connected joysticks and send events */ /* Prepare the existing device list */ if (SDL_AtomicTryLock(&SDL_HIDAPI_spinlock)) { device = SDL_HIDAPI_devices; while (device) { if (device->driver) { if (SDL_TryLockMutex(device->dev_lock) == 0) { device->driver->UpdateDevice(device); SDL_UnlockMutex(device->dev_lock); } } device = device->next; } SDL_AtomicUnlock(&SDL_HIDAPI_spinlock); } } static const char * HIDAPI_JoystickGetDeviceName(int device_index) { SDL_HIDAPI_Device *device; const char *name = NULL; device = HIDAPI_GetDeviceByIndex(device_index, NULL); if (device) { /* FIXME: The device could be freed after this name is returned... */ name = device->name; } return name; } static int HIDAPI_JoystickGetDevicePlayerIndex(int device_index) { SDL_HIDAPI_Device *device; SDL_JoystickID instance_id; int player_index = -1; device = HIDAPI_GetDeviceByIndex(device_index, &instance_id); if (device) { player_index = device->driver->GetDevicePlayerIndex(device, instance_id); } return player_index; } static void HIDAPI_JoystickSetDevicePlayerIndex(int device_index, int player_index) { SDL_HIDAPI_Device *device; SDL_JoystickID instance_id; device = HIDAPI_GetDeviceByIndex(device_index, &instance_id); if (device) { device->driver->SetDevicePlayerIndex(device, instance_id, player_index); } } static SDL_JoystickGUID HIDAPI_JoystickGetDeviceGUID(int device_index) { SDL_HIDAPI_Device *device; SDL_JoystickGUID guid; device = HIDAPI_GetDeviceByIndex(device_index, NULL); if (device) { SDL_memcpy(&guid, &device->guid, sizeof(guid)); } else { SDL_zero(guid); } return guid; } static SDL_JoystickID HIDAPI_JoystickGetDeviceInstanceID(int device_index) { SDL_JoystickID joystickID = -1; HIDAPI_GetDeviceByIndex(device_index, &joystickID); return joystickID; } static int HIDAPI_JoystickOpen(SDL_Joystick * joystick, int device_index) { SDL_JoystickID joystickID; SDL_HIDAPI_Device *device = HIDAPI_GetDeviceByIndex(device_index, &joystickID); struct joystick_hwdata *hwdata; hwdata = (struct joystick_hwdata *)SDL_calloc(1, sizeof(*hwdata)); if (!hwdata) { return SDL_OutOfMemory(); } hwdata->device = device; if (!device->driver->OpenJoystick(device, joystick)) { SDL_free(hwdata); return -1; } joystick->hwdata = hwdata; return 0; } static int HIDAPI_JoystickRumble(SDL_Joystick * joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { int result; if (joystick->hwdata) { SDL_HIDAPI_Device *device = joystick->hwdata->device; result = device->driver->RumbleJoystick(device, joystick, low_frequency_rumble, high_frequency_rumble); } else { SDL_SetError("Rumble failed, device disconnected"); result = -1; } return result; } static void HIDAPI_JoystickUpdate(SDL_Joystick * joystick) { /* This is handled in SDL_HIDAPI_UpdateDevices() */ } static void HIDAPI_JoystickClose(SDL_Joystick * joystick) { if (joystick->hwdata) { SDL_HIDAPI_Device *device = joystick->hwdata->device; /* Wait for pending rumble to complete */ while (SDL_AtomicGet(&device->rumble_pending) > 0) { SDL_Delay(10); } device->driver->CloseJoystick(device, joystick); SDL_free(joystick->hwdata); joystick->hwdata = NULL; } } static void HIDAPI_JoystickQuit(void) { int i; shutting_down = SDL_TRUE; HIDAPI_ShutdownDiscovery(); while (SDL_HIDAPI_devices) { HIDAPI_DelDevice(SDL_HIDAPI_devices); } SDL_HIDAPI_QuitRumble(); for (i = 0; i < SDL_arraysize(SDL_HIDAPI_drivers); ++i) { SDL_HIDAPI_DeviceDriver *driver = SDL_HIDAPI_drivers[i]; SDL_DelHintCallback(driver->hint, SDL_HIDAPIDriverHintChanged, NULL); } SDL_DelHintCallback(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPIDriverHintChanged, NULL); hid_exit(); /* Make sure the drivers cleaned up properly */ SDL_assert(SDL_HIDAPI_numjoysticks == 0); shutting_down = SDL_FALSE; initialized = SDL_FALSE; } static SDL_bool HIDAPI_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) { return SDL_FALSE; } SDL_JoystickDriver SDL_HIDAPI_JoystickDriver = { HIDAPI_JoystickInit, HIDAPI_JoystickGetCount, HIDAPI_JoystickDetect, HIDAPI_JoystickGetDeviceName, HIDAPI_JoystickGetDevicePlayerIndex, HIDAPI_JoystickSetDevicePlayerIndex, HIDAPI_JoystickGetDeviceGUID, HIDAPI_JoystickGetDeviceInstanceID, HIDAPI_JoystickOpen, HIDAPI_JoystickRumble, HIDAPI_JoystickUpdate, HIDAPI_JoystickClose, HIDAPI_JoystickQuit, HIDAPI_JoystickGetGamepadMapping }; #endif /* SDL_JOYSTICK_HIDAPI */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/hidapi/SDL_hidapijoystick.c
C
apache-2.0
36,583
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_JOYSTICK_HIDAPI_H #define SDL_JOYSTICK_HIDAPI_H #include "SDL_atomic.h" #include "SDL_mutex.h" #include "SDL_joystick.h" #include "SDL_gamecontroller.h" #include "../../hidapi/hidapi/hidapi.h" #include "../usb_ids.h" /* This is the full set of HIDAPI drivers available */ #define SDL_JOYSTICK_HIDAPI_PS4 #define SDL_JOYSTICK_HIDAPI_SWITCH #define SDL_JOYSTICK_HIDAPI_XBOX360 #define SDL_JOYSTICK_HIDAPI_XBOXONE #define SDL_JOYSTICK_HIDAPI_GAMECUBE #ifdef __WINDOWS__ /* On Windows, Xbox One controllers are handled by the Xbox 360 driver */ #undef SDL_JOYSTICK_HIDAPI_XBOXONE #endif #if defined(__IPHONEOS__) || defined(__TVOS__) || defined(__ANDROID__) /* Very basic Steam Controller support on mobile devices */ #define SDL_JOYSTICK_HIDAPI_STEAM #endif /* The maximum size of a USB packet for HID devices */ #define USB_PACKET_LENGTH 64 /* Forward declaration */ struct _SDL_HIDAPI_DeviceDriver; typedef struct _SDL_HIDAPI_Device { char *name; char *path; Uint16 vendor_id; Uint16 product_id; Uint16 version; SDL_JoystickGUID guid; int interface_number; /* Available on Windows and Linux */ int interface_class; int interface_subclass; int interface_protocol; Uint16 usage_page; /* Available on Windows and Mac OS X */ Uint16 usage; /* Available on Windows and Mac OS X */ struct _SDL_HIDAPI_DeviceDriver *driver; void *context; SDL_mutex *dev_lock; hid_device *dev; SDL_atomic_t rumble_pending; int num_joysticks; SDL_JoystickID *joysticks; /* Used during scanning for device changes */ SDL_bool seen; struct _SDL_HIDAPI_Device *next; } SDL_HIDAPI_Device; typedef struct _SDL_HIDAPI_DeviceDriver { const char *hint; SDL_bool enabled; SDL_bool (*IsSupportedDevice)(const char *name, SDL_GameControllerType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol); const char *(*GetDeviceName)(Uint16 vendor_id, Uint16 product_id); SDL_bool (*InitDevice)(SDL_HIDAPI_Device *device); int (*GetDevicePlayerIndex)(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id); void (*SetDevicePlayerIndex)(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index); SDL_bool (*UpdateDevice)(SDL_HIDAPI_Device *device); SDL_bool (*OpenJoystick)(SDL_HIDAPI_Device *device, SDL_Joystick *joystick); int (*RumbleJoystick)(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble); void (*CloseJoystick)(SDL_HIDAPI_Device *device, SDL_Joystick *joystick); void (*FreeDevice)(SDL_HIDAPI_Device *device); void (*PostUpdate)(void); #ifdef SDL_JOYSTICK_RAWINPUT void (*HandleStatePacketFromRAWINPUT)(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 *data, int size); #endif } SDL_HIDAPI_DeviceDriver; /* HIDAPI device support */ extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverPS4; extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverSteam; extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverSwitch; extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverXbox360; extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverXbox360W; extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverXboxOne; extern SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverGameCube; /* Return true if a HID device is present and supported as a joystick */ extern SDL_bool HIDAPI_IsDevicePresent(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name); extern void HIDAPI_UpdateDevices(void); extern SDL_bool HIDAPI_JoystickConnected(SDL_HIDAPI_Device *device, SDL_JoystickID *pJoystickID, SDL_bool is_external); extern void HIDAPI_JoystickDisconnected(SDL_HIDAPI_Device *device, SDL_JoystickID joystickID, SDL_bool is_external); #endif /* SDL_JOYSTICK_HIDAPI_H */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/hidapi/SDL_hidapijoystick_c.h
C
apache-2.0
4,868
/* Simple DirectMedia Layer Copyright (C) 2020 Valve Corporation This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef _CONTROLLER_CONSTANTS_ #define _CONTROLLER_CONSTANTS_ #include "controller_structs.h" #ifdef __cplusplus extern "C" { #endif #define FEATURE_REPORT_SIZE 64 #define VALVE_USB_VID 0x28DE // Frame update rate (in ms). #define FAST_SCAN_INTERVAL 6 #define SLOW_SCAN_INTERVAL 9 // Contains each of the USB PIDs for Valve controllers (only add to this enum and never change the order) enum ValveControllerPID { BASTILLE_PID = 0x2202, CHELL_PID = 0x1101, D0G_PID = 0x1102, ELI_PID = 0x1103, FREEMAN_PID = 0x1104, D0G_BLE_PID = 0x1105, D0G_BLE2_PID = 0x1106, D0GGLE_PID = 0x1142, }; // This enum contains all of the messages exchanged between the host and the target (only add to this enum and never change the order) enum FeatureReportMessageIDs { ID_SET_DIGITAL_MAPPINGS = 0x80, ID_CLEAR_DIGITAL_MAPPINGS = 0x81, ID_GET_DIGITAL_MAPPINGS = 0x82, ID_GET_ATTRIBUTES_VALUES = 0x83, ID_GET_ATTRIBUTE_LABEL = 0x84, ID_SET_DEFAULT_DIGITAL_MAPPINGS = 0x85, ID_FACTORY_RESET = 0x86, ID_SET_SETTINGS_VALUES = 0x87, ID_CLEAR_SETTINGS_VALUES = 0x88, ID_GET_SETTINGS_VALUES = 0x89, ID_GET_SETTING_LABEL = 0x8A, ID_GET_SETTINGS_MAXS = 0x8B, ID_GET_SETTINGS_DEFAULTS = 0x8C, ID_SET_CONTROLLER_MODE = 0x8D, ID_LOAD_DEFAULT_SETTINGS = 0x8E, ID_TRIGGER_HAPTIC_PULSE = 0x8F, ID_TURN_OFF_CONTROLLER = 0x9F, ID_GET_DEVICE_INFO = 0xA1, ID_CALIBRATE_TRACKPADS = 0xA7, ID_RESERVED_0 = 0xA8, ID_SET_SERIAL_NUMBER = 0xA9, ID_GET_TRACKPAD_CALIBRATION = 0xAA, ID_GET_TRACKPAD_FACTORY_CALIBRATION = 0xAB, ID_GET_TRACKPAD_RAW_DATA = 0xAC, ID_ENABLE_PAIRING = 0xAD, ID_GET_STRING_ATTRIBUTE = 0xAE, ID_RADIO_ERASE_RECORDS = 0xAF, ID_RADIO_WRITE_RECORD = 0xB0, ID_SET_DONGLE_SETTING = 0xB1, ID_DONGLE_DISCONNECT_DEVICE = 0xB2, ID_DONGLE_COMMIT_DEVICE = 0xB3, ID_DONGLE_GET_WIRELESS_STATE = 0xB4, ID_CALIBRATE_GYRO = 0xB5, ID_PLAY_AUDIO = 0xB6, ID_AUDIO_UPDATE_START = 0xB7, ID_AUDIO_UPDATE_DATA = 0xB8, ID_AUDIO_UPDATE_COMPLETE = 0xB9, ID_GET_CHIPID = 0xBA, ID_CALIBRATE_JOYSTICK = 0xBF, ID_CALIBRATE_ANALOG_TRIGGERS = 0xC0, ID_SET_AUDIO_MAPPING = 0xC1, ID_CHECK_GYRO_FW_LOAD = 0xC2, ID_CALIBRATE_ANALOG = 0xC3, ID_DONGLE_GET_CONNECTED_SLOTS = 0xC4, }; // Enumeration of all wireless dongle events typedef enum WirelessEventTypes { WIRELESS_EVENT_DISCONNECT = 1, WIRELESS_EVENT_CONNECT = 2, WIRELESS_EVENT_PAIR = 3, } EWirelessEventType; // Enumeration of generic digital inputs - not all of these will be supported on all controllers (only add to this enum and never change the order) typedef enum { IO_DIGITAL_BUTTON_NONE = -1, IO_DIGITAL_BUTTON_RIGHT_TRIGGER, IO_DIGITAL_BUTTON_LEFT_TRIGGER, IO_DIGITAL_BUTTON_1, IO_DIGITAL_BUTTON_Y=IO_DIGITAL_BUTTON_1, IO_DIGITAL_BUTTON_2, IO_DIGITAL_BUTTON_B=IO_DIGITAL_BUTTON_2, IO_DIGITAL_BUTTON_3, IO_DIGITAL_BUTTON_X=IO_DIGITAL_BUTTON_3, IO_DIGITAL_BUTTON_4, IO_DIGITAL_BUTTON_A=IO_DIGITAL_BUTTON_4, IO_DIGITAL_BUTTON_RIGHT_BUMPER, IO_DIGITAL_BUTTON_LEFT_BUMPER, IO_DIGITAL_BUTTON_LEFT_JOYSTICK_CLICK, IO_DIGITAL_BUTTON_ESCAPE, IO_DIGITAL_BUTTON_STEAM, IO_DIGITAL_BUTTON_MENU, IO_DIGITAL_STICK_UP, IO_DIGITAL_STICK_DOWN, IO_DIGITAL_STICK_LEFT, IO_DIGITAL_STICK_RIGHT, IO_DIGITAL_TOUCH_1, IO_DIGITAL_BUTTON_UP=IO_DIGITAL_TOUCH_1, IO_DIGITAL_TOUCH_2, IO_DIGITAL_BUTTON_RIGHT=IO_DIGITAL_TOUCH_2, IO_DIGITAL_TOUCH_3, IO_DIGITAL_BUTTON_LEFT=IO_DIGITAL_TOUCH_3, IO_DIGITAL_TOUCH_4, IO_DIGITAL_BUTTON_DOWN=IO_DIGITAL_TOUCH_4, IO_DIGITAL_BUTTON_BACK_LEFT, IO_DIGITAL_BUTTON_BACK_RIGHT, IO_DIGITAL_LEFT_TRACKPAD_N, IO_DIGITAL_LEFT_TRACKPAD_NE, IO_DIGITAL_LEFT_TRACKPAD_E, IO_DIGITAL_LEFT_TRACKPAD_SE, IO_DIGITAL_LEFT_TRACKPAD_S, IO_DIGITAL_LEFT_TRACKPAD_SW, IO_DIGITAL_LEFT_TRACKPAD_W, IO_DIGITAL_LEFT_TRACKPAD_NW, IO_DIGITAL_RIGHT_TRACKPAD_N, IO_DIGITAL_RIGHT_TRACKPAD_NE, IO_DIGITAL_RIGHT_TRACKPAD_E, IO_DIGITAL_RIGHT_TRACKPAD_SE, IO_DIGITAL_RIGHT_TRACKPAD_S, IO_DIGITAL_RIGHT_TRACKPAD_SW, IO_DIGITAL_RIGHT_TRACKPAD_W, IO_DIGITAL_RIGHT_TRACKPAD_NW, IO_DIGITAL_LEFT_TRACKPAD_DOUBLE_TAP, IO_DIGITAL_RIGHT_TRACKPAD_DOUBLE_TAP, IO_DIGITAL_LEFT_TRACKPAD_OUTER_RADIUS, IO_DIGITAL_RIGHT_TRACKPAD_OUTER_RADIUS, IO_DIGITAL_LEFT_TRACKPAD_CLICK, IO_DIGITAL_RIGHT_TRACKPAD_CLICK, IO_DIGITAL_BATTERY_LOW, IO_DIGITAL_LEFT_TRIGGER_THRESHOLD, IO_DIGITAL_RIGHT_TRIGGER_THRESHOLD, IO_DIGITAL_BUTTON_BACK_LEFT2, IO_DIGITAL_BUTTON_BACK_RIGHT2, IO_DIGITAL_BUTTON_ALWAYS_ON, IO_DIGITAL_BUTTON_ANCILLARY_1, IO_DIGITAL_BUTTON_MACRO_0, IO_DIGITAL_BUTTON_MACRO_1, IO_DIGITAL_BUTTON_MACRO_2, IO_DIGITAL_BUTTON_MACRO_3, IO_DIGITAL_BUTTON_MACRO_4, IO_DIGITAL_BUTTON_MACRO_5, IO_DIGITAL_BUTTON_MACRO_6, IO_DIGITAL_BUTTON_MACRO_7, IO_DIGITAL_BUTTON_MACRO_1FINGER, IO_DIGITAL_BUTTON_MACRO_2FINGER, IO_DIGITAL_COUNT } DigitalIO ; // Enumeration of generic analog inputs - not all of these will be supported on all controllers (only add to this enum and never change the order) typedef enum { IO_ANALOG_LEFT_STICK_X, IO_ANALOG_LEFT_STICK_Y, IO_ANALOG_RIGHT_STICK_X, IO_ANALOG_RIGHT_STICK_Y, IO_ANALOG_LEFT_TRIGGER, IO_ANALOG_RIGHT_TRIGGER, IO_MOUSE1_X, IO_MOUSE1_Y, IO_MOUSE1_Z, IO_ACCEL_X, IO_ACCEL_Y, IO_ACCEL_Z, IO_GYRO_X, IO_GYRO_Y, IO_GYRO_Z, IO_GYRO_QUAT_W, IO_GYRO_QUAT_X, IO_GYRO_QUAT_Y, IO_GYRO_QUAT_Z, IO_GYRO_STEERING_VEC, IO_RAW_TRIGGER_LEFT, IO_RAW_TRIGGER_RIGHT, IO_RAW_JOYSTICK_X, IO_RAW_JOYSTICK_Y, IO_GYRO_TILT_VEC, IO_ANALOG_COUNT } AnalogIO; // Contains list of all types of devices that the controller emulates (only add to this enum and never change the order) enum DeviceTypes { DEVICE_KEYBOARD, DEVICE_MOUSE, DEVICE_GAMEPAD, DEVICE_MODE_ADJUST, DEVICE_COUNT }; // Scan codes for HID keyboards enum HIDKeyboardKeys { KEY_INVALID, KEY_FIRST = 0x04, KEY_A = KEY_FIRST, KEY_B, KEY_C, KEY_D, KEY_E, KEY_F, KEY_G, KEY_H, KEY_I, KEY_J, KEY_K, KEY_L, KEY_M, KEY_N, KEY_O, KEY_P, KEY_Q, KEY_R, KEY_S, KEY_T, KEY_U, KEY_V, KEY_W, KEY_X, KEY_Y, KEY_Z, KEY_1, KEY_2, KEY_3, KEY_4, KEY_5, KEY_6, KEY_7, KEY_8, KEY_9, KEY_0, KEY_RETURN, KEY_ESCAPE, KEY_BACKSPACE, KEY_TAB, KEY_SPACE, KEY_DASH, KEY_EQUALS, KEY_LEFT_BRACKET, KEY_RIGHT_BRACKET, KEY_BACKSLASH, KEY_UNUSED1, KEY_SEMICOLON, KEY_SINGLE_QUOTE, KEY_BACK_TICK, KEY_COMMA, KEY_PERIOD, KEY_FORWARD_SLASH, KEY_CAPSLOCK, KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_F7, KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_F12, KEY_PRINT_SCREEN, KEY_SCROLL_LOCK, KEY_BREAK, KEY_INSERT, KEY_HOME, KEY_PAGE_UP, KEY_DELETE, KEY_END, KEY_PAGE_DOWN, KEY_RIGHT_ARROW, KEY_LEFT_ARROW, KEY_DOWN_ARROW, KEY_UP_ARROW, KEY_NUM_LOCK, KEY_KEYPAD_FORWARD_SLASH, KEY_KEYPAD_ASTERISK, KEY_KEYPAD_DASH, KEY_KEYPAD_PLUS, KEY_KEYPAD_ENTER, KEY_KEYPAD_1, KEY_KEYPAD_2, KEY_KEYPAD_3, KEY_KEYPAD_4, KEY_KEYPAD_5, KEY_KEYPAD_6, KEY_KEYPAD_7, KEY_KEYPAD_8, KEY_KEYPAD_9, KEY_KEYPAD_0, KEY_KEYPAD_PERIOD, KEY_LALT, KEY_LSHIFT, KEY_LWIN, KEY_LCONTROL, KEY_RALT, KEY_RSHIFT, KEY_RWIN, KEY_RCONTROL, KEY_VOLUP, KEY_VOLDOWN, KEY_MUTE, KEY_PLAY, KEY_STOP, KEY_NEXT, KEY_PREV, KEY_LAST = KEY_PREV }; enum ModifierMasks { KEY_LCONTROL_MASK = (1<<0), KEY_LSHIFT_MASK = (1<<1), KEY_LALT_MASK = (1<<2), KEY_LWIN_MASK = (1<<3), KEY_RCONTROL_MASK = (1<<4), KEY_RSHIFT_MASK = (1<<5), KEY_RALT_MASK = (1<<6), KEY_RWIN_MASK = (1<<7) }; // Standard mouse buttons as specified in the HID mouse spec enum MouseButtons { MOUSE_BTN_LEFT, MOUSE_BTN_RIGHT, MOUSE_BTN_MIDDLE, MOUSE_BTN_BACK, MOUSE_BTN_FORWARD, MOUSE_SCROLL_UP, MOUSE_SCROLL_DOWN, MOUSE_BTN_COUNT }; // Gamepad buttons enum GamepadButtons { GAMEPAD_BTN_TRIGGER_LEFT=1, GAMEPAD_BTN_TRIGGER_RIGHT, GAMEPAD_BTN_A, GAMEPAD_BTN_B, GAMEPAD_BTN_Y, GAMEPAD_BTN_X, GAMEPAD_BTN_SHOULDER_LEFT, GAMEPAD_BTN_SHOULDER_RIGHT, GAMEPAD_BTN_LEFT_JOYSTICK, GAMEPAD_BTN_RIGHT_JOYSTICK, GAMEPAD_BTN_START, GAMEPAD_BTN_SELECT, GAMEPAD_BTN_STEAM, GAMEPAD_BTN_DPAD_UP, GAMEPAD_BTN_DPAD_DOWN, GAMEPAD_BTN_DPAD_LEFT, GAMEPAD_BTN_DPAD_RIGHT, GAMEPAD_BTN_LSTICK_UP, GAMEPAD_BTN_LSTICK_DOWN, GAMEPAD_BTN_LSTICK_LEFT, GAMEPAD_BTN_LSTICK_RIGHT, GAMEPAD_BTN_RSTICK_UP, GAMEPAD_BTN_RSTICK_DOWN, GAMEPAD_BTN_RSTICK_LEFT, GAMEPAD_BTN_RSTICK_RIGHT, GAMEPAD_BTN_COUNT }; // Mode adjust enum ModeAdjustModes { MODE_ADJUST_SENSITITY=1, MODE_ADJUST_LEFT_PAD_SECONDARY_MODE, MODE_ADJUST_RIGHT_PAD_SECONDARY_MODE, MODE_ADJUST_COUNT }; // Read-only attributes of controllers (only add to this enum and never change the order) typedef enum { ATTRIB_UNIQUE_ID, ATTRIB_PRODUCT_ID, ATTRIB_PRODUCT_REVISON, // deprecated ATTRIB_CAPABILITIES = ATTRIB_PRODUCT_REVISON, // intentional aliasing ATTRIB_FIRMWARE_VERSION, // deprecated ATTRIB_FIRMWARE_BUILD_TIME, ATTRIB_RADIO_FIRMWARE_BUILD_TIME, ATTRIB_RADIO_DEVICE_ID0, ATTRIB_RADIO_DEVICE_ID1, ATTRIB_DONGLE_FIRMWARE_BUILD_TIME, ATTRIB_BOARD_REVISION, ATTRIB_BOOTLOADER_BUILD_TIME, ATTRIB_CONNECTION_INTERVAL_IN_US, ATTRIB_COUNT } ControllerAttributes; // Read-only string attributes of controllers (only add to this enum and never change the order) typedef enum { ATTRIB_STR_BOARD_SERIAL, ATTRIB_STR_UNIT_SERIAL, ATTRIB_STR_COUNT } ControllerStringAttributes; typedef enum { STATUS_CODE_NORMAL, STATUS_CODE_CRITICAL_BATTERY, STATUS_CODE_GYRO_INIT_ERROR, } ControllerStatusEventCodes; typedef enum { STATUS_STATE_LOW_BATTERY=0, } ControllerStatusStateFlags; typedef enum { TRACKPAD_ABSOLUTE_MOUSE, TRACKPAD_RELATIVE_MOUSE, TRACKPAD_DPAD_FOUR_WAY_DISCRETE, TRACKPAD_DPAD_FOUR_WAY_OVERLAP, TRACKPAD_DPAD_EIGHT_WAY, TRACKPAD_RADIAL_MODE, TRACKPAD_ABSOLUTE_DPAD, TRACKPAD_NONE, TRACKPAD_GESTURE_KEYBOARD, TRACKPAD_NUM_MODES } TrackpadDPadMode; // Read-write controller settings (only add to this enum and never change the order) typedef enum { SETTING_MOUSE_SENSITIVITY, SETTING_MOUSE_ACCELERATION, SETTING_TRACKBALL_ROTATION_ANGLE, SETTING_HAPTIC_INTENSITY, SETTING_LEFT_GAMEPAD_STICK_ENABLED, SETTING_RIGHT_GAMEPAD_STICK_ENABLED, SETTING_USB_DEBUG_MODE, SETTING_LEFT_TRACKPAD_MODE, SETTING_RIGHT_TRACKPAD_MODE, SETTING_MOUSE_POINTER_ENABLED, SETTING_DPAD_DEADZONE, SETTING_MINIMUM_MOMENTUM_VEL, SETTING_MOMENTUM_DECAY_AMMOUNT, SETTING_TRACKPAD_RELATIVE_MODE_TICKS_PER_PIXEL, SETTING_HAPTIC_INCREMENT, SETTING_DPAD_ANGLE_SIN, SETTING_DPAD_ANGLE_COS, SETTING_MOMENTUM_VERTICAL_DIVISOR, SETTING_MOMENTUM_MAXIMUM_VELOCITY, SETTING_TRACKPAD_Z_ON, SETTING_TRACKPAD_Z_OFF, SETTING_SENSITIVY_SCALE_AMMOUNT, SETTING_LEFT_TRACKPAD_SECONDARY_MODE, SETTING_RIGHT_TRACKPAD_SECONDARY_MODE, SETTING_SMOOTH_ABSOLUTE_MOUSE, SETTING_STEAMBUTTON_POWEROFF_TIME, SETTING_UNUSED_1, SETTING_TRACKPAD_OUTER_RADIUS, SETTING_TRACKPAD_Z_ON_LEFT, SETTING_TRACKPAD_Z_OFF_LEFT, SETTING_TRACKPAD_OUTER_SPIN_VEL, SETTING_TRACKPAD_OUTER_SPIN_RADIUS, SETTING_TRACKPAD_OUTER_SPIN_HORIZONTAL_ONLY, SETTING_TRACKPAD_RELATIVE_MODE_DEADZONE, SETTING_TRACKPAD_RELATIVE_MODE_MAX_VEL, SETTING_TRACKPAD_RELATIVE_MODE_INVERT_Y, SETTING_TRACKPAD_DOUBLE_TAP_BEEP_ENABLED, SETTING_TRACKPAD_DOUBLE_TAP_BEEP_PERIOD, SETTING_TRACKPAD_DOUBLE_TAP_BEEP_COUNT, SETTING_TRACKPAD_OUTER_RADIUS_RELEASE_ON_TRANSITION, SETTING_RADIAL_MODE_ANGLE, SETTING_HAPTIC_INTENSITY_MOUSE_MODE, SETTING_LEFT_DPAD_REQUIRES_CLICK, SETTING_RIGHT_DPAD_REQUIRES_CLICK, SETTING_LED_BASELINE_BRIGHTNESS, SETTING_LED_USER_BRIGHTNESS, SETTING_ENABLE_RAW_JOYSTICK, SETTING_ENABLE_FAST_SCAN, SETTING_GYRO_MODE, SETTING_WIRELESS_PACKET_VERSION, SETTING_SLEEP_INACTIVITY_TIMEOUT, SETTING_COUNT, // This is a special setting value use for callbacks and should not be set/get explicitly. SETTING_ALL=0xFF } ControllerSettings; typedef enum { SETTING_DEFAULT, SETTING_MIN, SETTING_MAX, SETTING_DEFAULTMINMAXCOUNT } SettingDefaultMinMax; // Bitmask that define which IMU features to enable. typedef enum { SETTING_GYRO_MODE_OFF = 0x0000, SETTING_GYRO_MODE_STEERING = 0x0001, SETTING_GYRO_MODE_TILT = 0x0002, SETTING_GYRO_MODE_SEND_ORIENTATION = 0x0004, SETTING_GYRO_MODE_SEND_RAW_ACCEL = 0x0008, SETTING_GYRO_MODE_SEND_RAW_GYRO = 0x0010, } SettingGyroMode; // Bitmask for haptic pulse flags typedef enum { HAPTIC_PULSE_NORMAL = 0x0000, HAPTIC_PULSE_HIGH_PRIORITY = 0x0001, HAPTIC_PULSE_VERY_HIGH_PRIORITY = 0x0002, } SettingHapticPulseFlags; typedef struct { // default,min,max in this array in that order short defaultminmax[SETTING_DEFAULTMINMAXCOUNT]; } SettingValueRange_t; // below is from controller_constants.c which should be compiled into any code that uses this extern const SettingValueRange_t g_DefaultSettingValues[SETTING_COUNT]; // Read-write settings for dongle (only add to this enum and never change the order) typedef enum { DONGLE_SETTING_MOUSE_KEYBOARD_ENABLED, DONGLE_SETTING_COUNT, } DongleSettings; typedef enum { AUDIO_STARTUP = 0, AUDIO_SHUTDOWN = 1, AUDIO_PAIR = 2, AUDIO_PAIR_SUCCESS = 3, AUDIO_IDENTIFY = 4, AUDIO_LIZARDMODE = 5, AUDIO_NORMALMODE = 6, AUDIO_MAX_SLOT = 15 } ControllerAudio; #ifdef __cplusplus } #endif #endif // _CONTROLLER_CONSTANTS_H
YifuLiu/AliOS-Things
components/SDL2/src/joystick/hidapi/steam/controller_constants.h
C
apache-2.0
14,638
/* Simple DirectMedia Layer Copyright (C) 2020 Valve Corporation This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef _CONTROLLER_STRUCTS_ #define _CONTROLLER_STRUCTS_ #pragma pack(1) // Roll this version forward anytime that you are breaking compatibility of existing // message types within ValveInReport_t or the header itself. Hopefully this should // be super rare and instead you shoudl just add new message payloads to the union, // or just add fields to the end of existing payload structs which is expected to be // safe in all code consuming these as they should just consume/copy upto the prior size // they were aware of when processing. #define k_ValveInReportMsgVersion 0x01 typedef enum { ID_CONTROLLER_STATE = 1, ID_CONTROLLER_DEBUG = 2, ID_CONTROLLER_WIRELESS = 3, ID_CONTROLLER_STATUS = 4, ID_CONTROLLER_DEBUG2 = 5, ID_CONTROLLER_SECONDARY_STATE = 6, ID_CONTROLLER_BLE_STATE = 7, ID_CONTROLLER_MSG_COUNT } ValveInReportMessageIDs; typedef struct { unsigned short unReportVersion; unsigned char ucType; unsigned char ucLength; } ValveInReportHeader_t; // State payload typedef struct { // If packet num matches that on your prior call, then the controller state hasn't been changed since // your last call and there is no need to process it uint32 unPacketNum; // Button bitmask and trigger data. union { uint64 ulButtons; struct { unsigned char _pad0[3]; unsigned char nLeft; unsigned char nRight; unsigned char _pad1[3]; } Triggers; } ButtonTriggerData; // Left pad coordinates short sLeftPadX; short sLeftPadY; // Right pad coordinates short sRightPadX; short sRightPadY; // This is redundant, packed above, but still sent over wired unsigned short sTriggerL; unsigned short sTriggerR; // FIXME figure out a way to grab this stuff over wireless short sAccelX; short sAccelY; short sAccelZ; short sGyroX; short sGyroY; short sGyroZ; short sGyroQuatW; short sGyroQuatX; short sGyroQuatY; short sGyroQuatZ; } ValveControllerStatePacket_t; // BLE State payload this has to be re-formatted from the normal state because BLE controller shows up as //a HID device and we don't want to send all the optional parts of the message. Keep in sync with struct above. typedef struct { // If packet num matches that on your prior call, then the controller state hasn't been changed since // your last call and there is no need to process it uint32 unPacketNum; // Button bitmask and trigger data. union { uint64 ulButtons; struct { unsigned char _pad0[3]; unsigned char nLeft; unsigned char nRight; unsigned char _pad1[3]; } Triggers; } ButtonTriggerData; // Left pad coordinates short sLeftPadX; short sLeftPadY; // Right pad coordinates short sRightPadX; short sRightPadY; //This mimcs how the dongle reconstitutes HID packets, there will be 0-4 shorts depending on gyro mode unsigned char ucGyroDataType; //TODO could maybe find some unused bits in the button field for this info (is only 2bits) short sGyro[4]; } ValveControllerBLEStatePacket_t; // Define a payload for reporting debug information typedef struct { // Left pad coordinates short sLeftPadX; short sLeftPadY; // Right pad coordinates short sRightPadX; short sRightPadY; // Left mouse deltas short sLeftPadMouseDX; short sLeftPadMouseDY; // Right mouse deltas short sRightPadMouseDX; short sRightPadMouseDY; // Left mouse filtered deltas short sLeftPadMouseFilteredDX; short sLeftPadMouseFilteredDY; // Right mouse filtered deltas short sRightPadMouseFilteredDX; short sRightPadMouseFilteredDY; // Pad Z values unsigned char ucLeftZ; unsigned char ucRightZ; // FingerPresent unsigned char ucLeftFingerPresent; unsigned char ucRightFingerPresent; // Timestamps unsigned char ucLeftTimestamp; unsigned char ucRightTimestamp; // Double tap state unsigned char ucLeftTapState; unsigned char ucRightTapState; unsigned int unDigitalIOStates0; unsigned int unDigitalIOStates1; } ValveControllerDebugPacket_t; typedef struct { unsigned char ucPadNum; unsigned char ucPad[3]; // need Data to be word aligned short Data[20]; unsigned short unNoise; } ValveControllerTrackpadImage_t; typedef struct { unsigned char ucPadNum; unsigned char ucOffset; unsigned char ucPad[2]; // need Data to be word aligned short rgData[28]; } ValveControllerRawTrackpadImage_t; // Payload for wireless metadata typedef struct { unsigned char ucEventType; } SteamControllerWirelessEvent_t; typedef struct { // Current packet number. unsigned int unPacketNum; // Event codes and state information. unsigned short sEventCode; unsigned short unStateFlags; // Current battery voltage (mV). unsigned short sBatteryVoltage; // Current battery level (0-100). unsigned char ucBatteryLevel; } SteamControllerStatusEvent_t; typedef struct { ValveInReportHeader_t header; union { ValveControllerStatePacket_t controllerState; ValveControllerBLEStatePacket_t controllerBLEState; ValveControllerDebugPacket_t debugState; ValveControllerTrackpadImage_t padImage; ValveControllerRawTrackpadImage_t rawPadImage; SteamControllerWirelessEvent_t wirelessEvent; SteamControllerStatusEvent_t statusEvent; } payload; } ValveInReport_t; // Enumeration for BLE packet protocol enum EBLEPacketReportNums { // Skipping past 2-3 because they are escape characters in Uart protocol k_EBLEReportState = 4, k_EBLEReportStatus = 5, }; // Enumeration of data chunks in BLE state packets enum EBLEOptionDataChunksBitmask { // First byte uppper nibble k_EBLEButtonChunk1 = 0x10, k_EBLEButtonChunk2 = 0x20, k_EBLEButtonChunk3 = 0x40, k_EBLELeftJoystickChunk = 0x80, // Second full byte k_EBLELeftTrackpadChunk = 0x100, k_EBLERightTrackpadChunk = 0x200, k_EBLEIMUAccelChunk = 0x400, k_EBLEIMUGyroChunk = 0x800, k_EBLEIMUQuatChunk = 0x1000, }; #pragma pack() #endif // _CONTROLLER_STRUCTS
YifuLiu/AliOS-Things
components/SDL2/src/joystick/hidapi/steam/controller_structs.h
C
apache-2.0
6,773
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" /* This is the iOS implementation of the SDL joystick API */ #include "SDL_sysjoystick_c.h" /* needed for SDL_IPHONE_MAX_GFORCE macro */ #include "../../../include/SDL_config_iphoneos.h" #include "SDL_assert.h" #include "SDL_events.h" #include "SDL_joystick.h" #include "SDL_hints.h" #include "SDL_stdinc.h" #include "../SDL_sysjoystick.h" #include "../SDL_joystick_c.h" #if !SDL_EVENTS_DISABLED #include "../../events/SDL_events_c.h" #endif #if !TARGET_OS_TV #import <CoreMotion/CoreMotion.h> #endif #ifdef SDL_JOYSTICK_MFI #import <GameController/GameController.h> static id connectObserver = nil; static id disconnectObserver = nil; #include <Availability.h> #include <objc/message.h> /* remove compilation warnings for strict builds by defining these selectors, even though * they are only ever used indirectly through objc_msgSend */ @interface GCExtendedGamepad (SDL) #if (__IPHONE_OS_VERSION_MAX_ALLOWED < 121000) || (__APPLETV_OS_VERSION_MAX_ALLOWED < 121000) || (__MAC_OS_VERSION_MAX_ALLOWED < 1401000) @property (nonatomic, readonly, nullable) GCControllerButtonInput *leftThumbstickButton; @property (nonatomic, readonly, nullable) GCControllerButtonInput *rightThumbstickButton; #endif #if (__IPHONE_OS_VERSION_MAX_ALLOWED < 130000) || (__APPLETV_OS_VERSION_MAX_ALLOWED < 130000) || (__MAC_OS_VERSION_MAX_ALLOWED < 1500000) @property (nonatomic, readonly) GCControllerButtonInput *buttonMenu; @property (nonatomic, readonly, nullable) GCControllerButtonInput *buttonOptions; #endif @end @interface GCMicroGamepad (SDL) #if (__IPHONE_OS_VERSION_MAX_ALLOWED < 130000) || (__APPLETV_OS_VERSION_MAX_ALLOWED < 130000) || (__MAC_OS_VERSION_MAX_ALLOWED < 1500000) @property (nonatomic, readonly) GCControllerButtonInput *buttonMenu; #endif @end #endif /* SDL_JOYSTICK_MFI */ #if !TARGET_OS_TV static const char *accelerometerName = "iOS Accelerometer"; static CMMotionManager *motionManager = nil; #endif /* !TARGET_OS_TV */ static SDL_JoystickDeviceItem *deviceList = NULL; static int numjoysticks = 0; int SDL_AppleTVRemoteOpenedAsJoystick = 0; static SDL_JoystickDeviceItem * GetDeviceForIndex(int device_index) { SDL_JoystickDeviceItem *device = deviceList; int i = 0; while (i < device_index) { if (device == NULL) { return NULL; } device = device->next; i++; } return device; } static void IOS_AddMFIJoystickDevice(SDL_JoystickDeviceItem *device, GCController *controller) { #ifdef SDL_JOYSTICK_MFI const Uint16 VENDOR_APPLE = 0x05AC; const Uint16 VENDOR_MICROSOFT = 0x045e; const Uint16 VENDOR_SONY = 0x054C; Uint16 *guid16 = (Uint16 *)device->guid.data; Uint16 vendor = 0; Uint16 product = 0; Uint8 subtype = 0; const char *name = NULL; /* Explicitly retain the controller because SDL_JoystickDeviceItem is a * struct, and ARC doesn't work with structs. */ device->controller = (__bridge GCController *) CFBridgingRetain(controller); if (controller.vendorName) { name = controller.vendorName.UTF8String; } if (!name) { name = "MFi Gamepad"; } device->name = SDL_CreateJoystickName(0, 0, NULL, name); if (controller.extendedGamepad) { GCExtendedGamepad *gamepad = controller.extendedGamepad; BOOL is_xbox = [controller.vendorName containsString: @"Xbox"]; BOOL is_ps4 = [controller.vendorName containsString: @"DUALSHOCK"]; #if TARGET_OS_TV BOOL is_MFi = (!is_xbox && !is_ps4); #endif int nbuttons = 0; /* These buttons are part of the original MFi spec */ device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_A); device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_B); device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_X); device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_Y); device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_LEFTSHOULDER); device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); nbuttons += 6; /* These buttons are available on some newer controllers */ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunguarded-availability-new" if ([gamepad respondsToSelector:@selector(leftThumbstickButton)] && gamepad.leftThumbstickButton) { device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_LEFTSTICK); ++nbuttons; } if ([gamepad respondsToSelector:@selector(rightThumbstickButton)] && gamepad.rightThumbstickButton) { device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_RIGHTSTICK); ++nbuttons; } if ([gamepad respondsToSelector:@selector(buttonOptions)] && gamepad.buttonOptions) { device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_BACK); ++nbuttons; } BOOL has_direct_menu = [gamepad respondsToSelector:@selector(buttonMenu)] && gamepad.buttonMenu; #if TARGET_OS_TV /* On tvOS MFi controller menu button brings you to the home screen */ if (is_MFi) { has_direct_menu = FALSE; } #endif device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_START); ++nbuttons; if (!has_direct_menu) { device->uses_pause_handler = SDL_TRUE; } #pragma clang diagnostic pop if (is_xbox) { vendor = VENDOR_MICROSOFT; product = 0x02E0; /* Assume Xbox One S BLE Controller unless/until GCController flows VID/PID */ } else if (is_ps4) { vendor = VENDOR_SONY; product = 0x09CC; /* Assume DS4 Slim unless/until GCController flows VID/PID */ } else { vendor = VENDOR_APPLE; product = 1; subtype = 1; } device->naxes = 6; /* 2 thumbsticks and 2 triggers */ device->nhats = 1; /* d-pad */ device->nbuttons = nbuttons; } else if (controller.gamepad) { int nbuttons = 0; /* These buttons are part of the original MFi spec */ device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_A); device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_B); device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_X); device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_Y); device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_LEFTSHOULDER); device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_START); nbuttons += 7; device->uses_pause_handler = SDL_TRUE; vendor = VENDOR_APPLE; product = 2; subtype = 2; device->naxes = 0; /* no traditional analog inputs */ device->nhats = 1; /* d-pad */ device->nbuttons = nbuttons; } #if TARGET_OS_TV else if (controller.microGamepad) { int nbuttons = 0; device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_A); device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_B); /* Button X on microGamepad */ nbuttons += 2; device->button_mask |= (1 << SDL_CONTROLLER_BUTTON_START); ++nbuttons; device->uses_pause_handler = SDL_TRUE; vendor = VENDOR_APPLE; product = 3; subtype = 3; device->naxes = 2; /* treat the touch surface as two axes */ device->nhats = 0; /* apparently the touch surface-as-dpad is buggy */ device->nbuttons = nbuttons; controller.microGamepad.allowsRotation = SDL_GetHintBoolean(SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION, SDL_FALSE); } #endif /* TARGET_OS_TV */ /* We only need 16 bits for each of these; space them out to fill 128. */ /* Byteswap so devices get same GUID on little/big endian platforms. */ *guid16++ = SDL_SwapLE16(SDL_HARDWARE_BUS_BLUETOOTH); *guid16++ = 0; *guid16++ = SDL_SwapLE16(vendor); *guid16++ = 0; *guid16++ = SDL_SwapLE16(product); *guid16++ = 0; *guid16++ = SDL_SwapLE16(device->button_mask); if (subtype != 0) { /* Note that this is an MFI controller and what subtype it is */ device->guid.data[14] = 'm'; device->guid.data[15] = subtype; } /* This will be set when the first button press of the controller is * detected. */ controller.playerIndex = -1; #endif /* SDL_JOYSTICK_MFI */ } static void IOS_AddJoystickDevice(GCController *controller, SDL_bool accelerometer) { SDL_JoystickDeviceItem *device = deviceList; #if TARGET_OS_TV if (!SDL_GetHintBoolean(SDL_HINT_TV_REMOTE_AS_JOYSTICK, SDL_TRUE)) { /* Ignore devices that aren't actually controllers (e.g. remotes), they'll be handled as keyboard input */ if (controller && !controller.extendedGamepad && !controller.gamepad && controller.microGamepad) { return; } } #endif while (device != NULL) { if (device->controller == controller) { return; } device = device->next; } device = (SDL_JoystickDeviceItem *) SDL_calloc(1, sizeof(SDL_JoystickDeviceItem)); if (device == NULL) { return; } device->accelerometer = accelerometer; device->instance_id = SDL_GetNextJoystickInstanceID(); if (accelerometer) { #if TARGET_OS_TV SDL_free(device); return; #else device->name = SDL_strdup(accelerometerName); device->naxes = 3; /* Device acceleration in the x, y, and z axes. */ device->nhats = 0; device->nbuttons = 0; /* Use the accelerometer name as a GUID. */ SDL_memcpy(&device->guid.data, device->name, SDL_min(sizeof(SDL_JoystickGUID), SDL_strlen(device->name))); #endif /* TARGET_OS_TV */ } else if (controller) { IOS_AddMFIJoystickDevice(device, controller); } if (deviceList == NULL) { deviceList = device; } else { SDL_JoystickDeviceItem *lastdevice = deviceList; while (lastdevice->next != NULL) { lastdevice = lastdevice->next; } lastdevice->next = device; } ++numjoysticks; SDL_PrivateJoystickAdded(device->instance_id); } static SDL_JoystickDeviceItem * IOS_RemoveJoystickDevice(SDL_JoystickDeviceItem *device) { SDL_JoystickDeviceItem *prev = NULL; SDL_JoystickDeviceItem *next = NULL; SDL_JoystickDeviceItem *item = deviceList; if (device == NULL) { return NULL; } next = device->next; while (item != NULL) { if (item == device) { break; } prev = item; item = item->next; } /* Unlink the device item from the device list. */ if (prev) { prev->next = device->next; } else if (device == deviceList) { deviceList = device->next; } if (device->joystick) { device->joystick->hwdata = NULL; } #ifdef SDL_JOYSTICK_MFI @autoreleasepool { if (device->controller) { /* The controller was explicitly retained in the struct, so it * should be explicitly released before freeing the struct. */ GCController *controller = CFBridgingRelease((__bridge CFTypeRef)(device->controller)); controller.controllerPausedHandler = nil; device->controller = nil; } } #endif /* SDL_JOYSTICK_MFI */ --numjoysticks; SDL_PrivateJoystickRemoved(device->instance_id); SDL_free(device->name); SDL_free(device); return next; } #if TARGET_OS_TV static void SDLCALL SDL_AppleTVRemoteRotationHintChanged(void *udata, const char *name, const char *oldValue, const char *newValue) { BOOL allowRotation = newValue != NULL && *newValue != '0'; @autoreleasepool { for (GCController *controller in [GCController controllers]) { if (controller.microGamepad) { controller.microGamepad.allowsRotation = allowRotation; } } } } #endif /* TARGET_OS_TV */ static int IOS_JoystickInit(void) { @autoreleasepool { #if !TARGET_OS_TV if (SDL_GetHintBoolean(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, SDL_TRUE)) { /* Default behavior, accelerometer as joystick */ IOS_AddJoystickDevice(nil, SDL_TRUE); } #endif /* !TARGET_OS_TV */ #ifdef SDL_JOYSTICK_MFI /* GameController.framework was added in iOS 7. */ if (![GCController class]) { return 0; } for (GCController *controller in [GCController controllers]) { IOS_AddJoystickDevice(controller, SDL_FALSE); } #if TARGET_OS_TV SDL_AddHintCallback(SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION, SDL_AppleTVRemoteRotationHintChanged, NULL); #endif /* TARGET_OS_TV */ NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; connectObserver = [center addObserverForName:GCControllerDidConnectNotification object:nil queue:nil usingBlock:^(NSNotification *note) { GCController *controller = note.object; IOS_AddJoystickDevice(controller, SDL_FALSE); }]; disconnectObserver = [center addObserverForName:GCControllerDidDisconnectNotification object:nil queue:nil usingBlock:^(NSNotification *note) { GCController *controller = note.object; SDL_JoystickDeviceItem *device = deviceList; while (device != NULL) { if (device->controller == controller) { IOS_RemoveJoystickDevice(device); break; } device = device->next; } }]; #endif /* SDL_JOYSTICK_MFI */ } return 0; } static int IOS_JoystickGetCount(void) { return numjoysticks; } static void IOS_JoystickDetect(void) { } static const char * IOS_JoystickGetDeviceName(int device_index) { SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index); return device ? device->name : "Unknown"; } static int IOS_JoystickGetDevicePlayerIndex(int device_index) { #ifdef SDL_JOYSTICK_MFI SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index); if (device && device->controller) { return (int)device->controller.playerIndex; } #endif return -1; } static void IOS_JoystickSetDevicePlayerIndex(int device_index, int player_index) { #ifdef SDL_JOYSTICK_MFI SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index); if (device && device->controller) { device->controller.playerIndex = player_index; } #endif } static SDL_JoystickGUID IOS_JoystickGetDeviceGUID( int device_index ) { SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index); SDL_JoystickGUID guid; if (device) { guid = device->guid; } else { SDL_zero(guid); } return guid; } static SDL_JoystickID IOS_JoystickGetDeviceInstanceID(int device_index) { SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index); return device ? device->instance_id : -1; } static int IOS_JoystickOpen(SDL_Joystick * joystick, int device_index) { SDL_JoystickDeviceItem *device = GetDeviceForIndex(device_index); if (device == NULL) { return SDL_SetError("Could not open Joystick: no hardware device for the specified index"); } joystick->hwdata = device; joystick->instance_id = device->instance_id; joystick->naxes = device->naxes; joystick->nhats = device->nhats; joystick->nbuttons = device->nbuttons; joystick->nballs = 0; device->joystick = joystick; @autoreleasepool { if (device->accelerometer) { #if !TARGET_OS_TV if (motionManager == nil) { motionManager = [[CMMotionManager alloc] init]; } /* Shorter times between updates can significantly increase CPU usage. */ motionManager.accelerometerUpdateInterval = 0.1; [motionManager startAccelerometerUpdates]; #endif /* !TARGET_OS_TV */ } else { #ifdef SDL_JOYSTICK_MFI if (device->uses_pause_handler) { GCController *controller = device->controller; controller.controllerPausedHandler = ^(GCController *c) { if (joystick->hwdata) { ++joystick->hwdata->num_pause_presses; } }; } #endif /* SDL_JOYSTICK_MFI */ } } if (device->remote) { ++SDL_AppleTVRemoteOpenedAsJoystick; } return 0; } static void IOS_AccelerometerUpdate(SDL_Joystick * joystick) { #if !TARGET_OS_TV const float maxgforce = SDL_IPHONE_MAX_GFORCE; const SInt16 maxsint16 = 0x7FFF; CMAcceleration accel; @autoreleasepool { if (!motionManager.isAccelerometerActive) { return; } accel = motionManager.accelerometerData.acceleration; } /* Convert accelerometer data from floating point to Sint16, which is what the joystick system expects. To do the conversion, the data is first clamped onto the interval [-SDL_IPHONE_MAX_G_FORCE, SDL_IPHONE_MAX_G_FORCE], then the data is multiplied by MAX_SINT16 so that it is mapped to the full range of an Sint16. You can customize the clamped range of this function by modifying the SDL_IPHONE_MAX_GFORCE macro in SDL_config_iphoneos.h. Once converted to Sint16, the accelerometer data no longer has coherent units. You can convert the data back to units of g-force by multiplying it in your application's code by SDL_IPHONE_MAX_GFORCE / 0x7FFF. */ /* clamp the data */ accel.x = SDL_min(SDL_max(accel.x, -maxgforce), maxgforce); accel.y = SDL_min(SDL_max(accel.y, -maxgforce), maxgforce); accel.z = SDL_min(SDL_max(accel.z, -maxgforce), maxgforce); /* pass in data mapped to range of SInt16 */ SDL_PrivateJoystickAxis(joystick, 0, (accel.x / maxgforce) * maxsint16); SDL_PrivateJoystickAxis(joystick, 1, -(accel.y / maxgforce) * maxsint16); SDL_PrivateJoystickAxis(joystick, 2, (accel.z / maxgforce) * maxsint16); #endif /* !TARGET_OS_TV */ } #ifdef SDL_JOYSTICK_MFI static Uint8 IOS_MFIJoystickHatStateForDPad(GCControllerDirectionPad *dpad) { Uint8 hat = 0; if (dpad.up.isPressed) { hat |= SDL_HAT_UP; } else if (dpad.down.isPressed) { hat |= SDL_HAT_DOWN; } if (dpad.left.isPressed) { hat |= SDL_HAT_LEFT; } else if (dpad.right.isPressed) { hat |= SDL_HAT_RIGHT; } if (hat == 0) { return SDL_HAT_CENTERED; } return hat; } #endif static void IOS_MFIJoystickUpdate(SDL_Joystick * joystick) { #if SDL_JOYSTICK_MFI @autoreleasepool { GCController *controller = joystick->hwdata->controller; Uint8 hatstate = SDL_HAT_CENTERED; int i; int pause_button_index = 0; if (controller.extendedGamepad) { GCExtendedGamepad *gamepad = controller.extendedGamepad; /* Axis order matches the XInput Windows mappings. */ Sint16 axes[] = { (Sint16) (gamepad.leftThumbstick.xAxis.value * 32767), (Sint16) (gamepad.leftThumbstick.yAxis.value * -32767), (Sint16) ((gamepad.leftTrigger.value * 65535) - 32768), (Sint16) (gamepad.rightThumbstick.xAxis.value * 32767), (Sint16) (gamepad.rightThumbstick.yAxis.value * -32767), (Sint16) ((gamepad.rightTrigger.value * 65535) - 32768), }; /* Button order matches the XInput Windows mappings. */ Uint8 buttons[joystick->nbuttons]; int button_count = 0; /* These buttons are part of the original MFi spec */ buttons[button_count++] = gamepad.buttonA.isPressed; buttons[button_count++] = gamepad.buttonB.isPressed; buttons[button_count++] = gamepad.buttonX.isPressed; buttons[button_count++] = gamepad.buttonY.isPressed; buttons[button_count++] = gamepad.leftShoulder.isPressed; buttons[button_count++] = gamepad.rightShoulder.isPressed; /* These buttons are available on some newer controllers */ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunguarded-availability-new" if (joystick->hwdata->button_mask & (1 << SDL_CONTROLLER_BUTTON_LEFTSTICK)) { buttons[button_count++] = gamepad.leftThumbstickButton.isPressed; } if (joystick->hwdata->button_mask & (1 << SDL_CONTROLLER_BUTTON_RIGHTSTICK)) { buttons[button_count++] = gamepad.rightThumbstickButton.isPressed; } if (joystick->hwdata->button_mask & (1 << SDL_CONTROLLER_BUTTON_BACK)) { buttons[button_count++] = gamepad.buttonOptions.isPressed; } /* This must be the last button, so we can optionally handle it with pause_button_index below */ if (joystick->hwdata->button_mask & (1 << SDL_CONTROLLER_BUTTON_START)) { if (joystick->hwdata->uses_pause_handler) { pause_button_index = button_count; buttons[button_count++] = joystick->delayed_guide_button; } else { buttons[button_count++] = gamepad.buttonMenu.isPressed; } } #pragma clang diagnostic pop hatstate = IOS_MFIJoystickHatStateForDPad(gamepad.dpad); for (i = 0; i < SDL_arraysize(axes); i++) { SDL_PrivateJoystickAxis(joystick, i, axes[i]); } for (i = 0; i < button_count; i++) { SDL_PrivateJoystickButton(joystick, i, buttons[i]); } } else if (controller.gamepad) { GCGamepad *gamepad = controller.gamepad; /* Button order matches the XInput Windows mappings. */ Uint8 buttons[joystick->nbuttons]; int button_count = 0; buttons[button_count++] = gamepad.buttonA.isPressed; buttons[button_count++] = gamepad.buttonB.isPressed; buttons[button_count++] = gamepad.buttonX.isPressed; buttons[button_count++] = gamepad.buttonY.isPressed; buttons[button_count++] = gamepad.leftShoulder.isPressed; buttons[button_count++] = gamepad.rightShoulder.isPressed; pause_button_index = button_count; buttons[button_count++] = joystick->delayed_guide_button; hatstate = IOS_MFIJoystickHatStateForDPad(gamepad.dpad); for (i = 0; i < button_count; i++) { SDL_PrivateJoystickButton(joystick, i, buttons[i]); } } #if TARGET_OS_TV else if (controller.microGamepad) { GCMicroGamepad *gamepad = controller.microGamepad; Sint16 axes[] = { (Sint16) (gamepad.dpad.xAxis.value * 32767), (Sint16) (gamepad.dpad.yAxis.value * -32767), }; for (i = 0; i < SDL_arraysize(axes); i++) { SDL_PrivateJoystickAxis(joystick, i, axes[i]); } Uint8 buttons[joystick->nbuttons]; int button_count = 0; buttons[button_count++] = gamepad.buttonA.isPressed; buttons[button_count++] = gamepad.buttonX.isPressed; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunguarded-availability-new" /* This must be the last button, so we can optionally handle it with pause_button_index below */ if (joystick->hwdata->button_mask & (1 << SDL_CONTROLLER_BUTTON_START)) { if (joystick->hwdata->uses_pause_handler) { pause_button_index = button_count; buttons[button_count++] = joystick->delayed_guide_button; } else { buttons[button_count++] = gamepad.buttonMenu.isPressed; } } #pragma clang diagnostic pop for (i = 0; i < button_count; i++) { SDL_PrivateJoystickButton(joystick, i, buttons[i]); } } #endif /* TARGET_OS_TV */ if (joystick->nhats > 0) { SDL_PrivateJoystickHat(joystick, 0, hatstate); } if (joystick->hwdata->uses_pause_handler) { for (i = 0; i < joystick->hwdata->num_pause_presses; i++) { SDL_PrivateJoystickButton(joystick, pause_button_index, SDL_PRESSED); SDL_PrivateJoystickButton(joystick, pause_button_index, SDL_RELEASED); } joystick->hwdata->num_pause_presses = 0; } } #endif /* SDL_JOYSTICK_MFI */ } static int IOS_JoystickRumble(SDL_Joystick * joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { return SDL_Unsupported(); } static void IOS_JoystickUpdate(SDL_Joystick * joystick) { SDL_JoystickDeviceItem *device = joystick->hwdata; if (device == NULL) { return; } if (device->accelerometer) { IOS_AccelerometerUpdate(joystick); } else if (device->controller) { IOS_MFIJoystickUpdate(joystick); } } static void IOS_JoystickClose(SDL_Joystick * joystick) { SDL_JoystickDeviceItem *device = joystick->hwdata; if (device == NULL) { return; } device->joystick = NULL; @autoreleasepool { if (device->accelerometer) { #if !TARGET_OS_TV [motionManager stopAccelerometerUpdates]; #endif /* !TARGET_OS_TV */ } else if (device->controller) { #ifdef SDL_JOYSTICK_MFI GCController *controller = device->controller; controller.controllerPausedHandler = nil; controller.playerIndex = -1; #endif } } if (device->remote) { --SDL_AppleTVRemoteOpenedAsJoystick; } } static void IOS_JoystickQuit(void) { @autoreleasepool { #ifdef SDL_JOYSTICK_MFI NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; if (connectObserver) { [center removeObserver:connectObserver name:GCControllerDidConnectNotification object:nil]; connectObserver = nil; } if (disconnectObserver) { [center removeObserver:disconnectObserver name:GCControllerDidDisconnectNotification object:nil]; disconnectObserver = nil; } #if TARGET_OS_TV SDL_DelHintCallback(SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION, SDL_AppleTVRemoteRotationHintChanged, NULL); #endif /* TARGET_OS_TV */ #endif /* SDL_JOYSTICK_MFI */ while (deviceList != NULL) { IOS_RemoveJoystickDevice(deviceList); } #if !TARGET_OS_TV motionManager = nil; #endif /* !TARGET_OS_TV */ } numjoysticks = 0; } static SDL_bool IOS_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) { return SDL_FALSE; } SDL_JoystickDriver SDL_IOS_JoystickDriver = { IOS_JoystickInit, IOS_JoystickGetCount, IOS_JoystickDetect, IOS_JoystickGetDeviceName, IOS_JoystickGetDevicePlayerIndex, IOS_JoystickSetDevicePlayerIndex, IOS_JoystickGetDeviceGUID, IOS_JoystickGetDeviceInstanceID, IOS_JoystickOpen, IOS_JoystickRumble, IOS_JoystickUpdate, IOS_JoystickClose, IOS_JoystickQuit, IOS_JoystickGetGamepadMapping }; /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/iphoneos/SDL_sysjoystick.m
Objective-C
apache-2.0
29,031
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_JOYSTICK_IOS_H #define SDL_JOYSTICK_IOS_H #include "SDL_stdinc.h" #include "../SDL_sysjoystick.h" @class GCController; typedef struct joystick_hwdata { SDL_bool accelerometer; SDL_bool remote; GCController __unsafe_unretained *controller; SDL_bool uses_pause_handler; int num_pause_presses; Uint32 pause_button_down_time; char *name; SDL_Joystick *joystick; SDL_JoystickID instance_id; SDL_JoystickGUID guid; int naxes; int nbuttons; int nhats; Uint16 button_mask; struct joystick_hwdata *next; } joystick_hwdata; typedef joystick_hwdata SDL_JoystickDeviceItem; #endif /* SDL_JOYSTICK_IOS_H */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/iphoneos/SDL_sysjoystick_c.h
Objective-C
apache-2.0
1,684
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_LINUX #ifndef SDL_INPUT_LINUXEV #error SDL now requires a Linux 2.4+ kernel with /dev/input/event support. #endif /* This is the Linux implementation of the SDL joystick API */ #include <sys/stat.h> #include <errno.h> /* errno, strerror */ #include <fcntl.h> #include <limits.h> /* For the definition of PATH_MAX */ #include <sys/ioctl.h> #include <unistd.h> #include <dirent.h> #include <linux/joystick.h> #include "SDL_assert.h" #include "SDL_joystick.h" #include "SDL_endian.h" #include "SDL_timer.h" #include "../../events/SDL_events_c.h" #include "../SDL_sysjoystick.h" #include "../SDL_joystick_c.h" #include "../steam/SDL_steamcontroller.h" #include "SDL_sysjoystick_c.h" #include "../hidapi/SDL_hidapijoystick_c.h" /* This isn't defined in older Linux kernel headers */ #ifndef SYN_DROPPED #define SYN_DROPPED 3 #endif #ifndef BTN_SOUTH #define BTN_SOUTH 0x130 #endif #ifndef BTN_EAST #define BTN_EAST 0x131 #endif #ifndef BTN_NORTH #define BTN_NORTH 0x133 #endif #ifndef BTN_WEST #define BTN_WEST 0x134 #endif #ifndef BTN_DPAD_UP #define BTN_DPAD_UP 0x220 #endif #ifndef BTN_DPAD_DOWN #define BTN_DPAD_DOWN 0x221 #endif #ifndef BTN_DPAD_LEFT #define BTN_DPAD_LEFT 0x222 #endif #ifndef BTN_DPAD_RIGHT #define BTN_DPAD_RIGHT 0x223 #endif #include "../../core/linux/SDL_udev.h" #if 0 #define DEBUG_INPUT_EVENTS 1 #endif static int MaybeAddDevice(const char *path); #if SDL_USE_LIBUDEV static int MaybeRemoveDevice(const char *path); #endif /* SDL_USE_LIBUDEV */ /* A linked list of available joysticks */ typedef struct SDL_joylist_item { int device_instance; char *path; /* "/dev/input/event2" or whatever */ char *name; /* "SideWinder 3D Pro" or whatever */ SDL_JoystickGUID guid; dev_t devnum; struct joystick_hwdata *hwdata; struct SDL_joylist_item *next; /* Steam Controller support */ SDL_bool m_bSteamController; } SDL_joylist_item; static SDL_joylist_item *SDL_joylist = NULL; static SDL_joylist_item *SDL_joylist_tail = NULL; static int numjoysticks = 0; #if !SDL_USE_LIBUDEV static Uint32 last_joy_detect_time; static time_t last_input_dir_mtime; #endif #define test_bit(nr, addr) \ (((1UL << ((nr) % (sizeof(long) * 8))) & ((addr)[(nr) / (sizeof(long) * 8)])) != 0) #define NBITS(x) ((((x)-1)/(sizeof(long) * 8))+1) static void FixupDeviceInfoForMapping(int fd, struct input_id *inpid) { if (inpid->vendor == 0x045e && inpid->product == 0x0b05 && inpid->version == 0x0903) { /* This is a Microsoft Xbox One Elite Series 2 controller */ unsigned long keybit[NBITS(KEY_MAX)] = { 0 }; /* The first version of the firmware duplicated all the inputs */ if ((ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) >= 0) && test_bit(0x2c0, keybit)) { /* Change the version to 0x0902, so we can map it differently */ inpid->version = 0x0902; } } } #ifdef SDL_JOYSTICK_HIDAPI static SDL_bool IsVirtualJoystick(Uint16 vendor, Uint16 product, Uint16 version, const char *name) { if (vendor == USB_VENDOR_MICROSOFT && product == USB_PRODUCT_XBOX_ONE_S && version == 0 && SDL_strcmp(name, "Xbox One S Controller") == 0) { /* This is the virtual device created by the xow driver */ return SDL_TRUE; } return SDL_FALSE; } #endif /* SDL_JOYSTICK_HIDAPI */ static int IsJoystick(int fd, char **name_return, SDL_JoystickGUID *guid) { struct input_id inpid; Uint16 *guid16 = (Uint16 *)guid->data; char *name; char product_string[128]; #if !SDL_USE_LIBUDEV /* When udev is enabled we only get joystick devices here, so there's no need to test them */ unsigned long evbit[NBITS(EV_MAX)] = { 0 }; unsigned long keybit[NBITS(KEY_MAX)] = { 0 }; unsigned long absbit[NBITS(ABS_MAX)] = { 0 }; if ((ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), evbit) < 0) || (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) || (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) { return (0); } if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) && test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit))) { return 0; } #endif if (ioctl(fd, EVIOCGID, &inpid) < 0) { return 0; } if (ioctl(fd, EVIOCGNAME(sizeof(product_string)), product_string) < 0) { return 0; } name = SDL_CreateJoystickName(inpid.vendor, inpid.product, NULL, product_string); if (!name) { return 0; } #ifdef SDL_JOYSTICK_HIDAPI if (!IsVirtualJoystick(inpid.vendor, inpid.product, inpid.version, name) && HIDAPI_IsDevicePresent(inpid.vendor, inpid.product, inpid.version, name)) { /* The HIDAPI driver is taking care of this device */ SDL_free(name); return 0; } #endif FixupDeviceInfoForMapping(fd, &inpid); #ifdef DEBUG_JOYSTICK printf("Joystick: %s, bustype = %d, vendor = 0x%.4x, product = 0x%.4x, version = %d\n", name, inpid.bustype, inpid.vendor, inpid.product, inpid.version); #endif SDL_memset(guid->data, 0, sizeof(guid->data)); /* We only need 16 bits for each of these; space them out to fill 128. */ /* Byteswap so devices get same GUID on little/big endian platforms. */ *guid16++ = SDL_SwapLE16(inpid.bustype); *guid16++ = 0; if (inpid.vendor && inpid.product) { *guid16++ = SDL_SwapLE16(inpid.vendor); *guid16++ = 0; *guid16++ = SDL_SwapLE16(inpid.product); *guid16++ = 0; *guid16++ = SDL_SwapLE16(inpid.version); *guid16++ = 0; } else { SDL_strlcpy((char*)guid16, name, sizeof(guid->data) - 4); } if (SDL_ShouldIgnoreJoystick(name, *guid)) { SDL_free(name); return 0; } *name_return = name; return 1; } #if SDL_USE_LIBUDEV static void joystick_udev_callback(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath) { if (devpath == NULL) { return; } switch (udev_type) { case SDL_UDEV_DEVICEADDED: if (!(udev_class & SDL_UDEV_DEVICE_JOYSTICK)) { return; } MaybeAddDevice(devpath); break; case SDL_UDEV_DEVICEREMOVED: MaybeRemoveDevice(devpath); break; default: break; } } #endif /* SDL_USE_LIBUDEV */ static int MaybeAddDevice(const char *path) { struct stat sb; int fd = -1; int isstick = 0; char *name = NULL; SDL_JoystickGUID guid; SDL_joylist_item *item; if (path == NULL) { return -1; } if (stat(path, &sb) == -1) { return -1; } /* Check to make sure it's not already in list. */ for (item = SDL_joylist; item != NULL; item = item->next) { if (sb.st_rdev == item->devnum) { return -1; /* already have this one */ } } fd = open(path, O_RDONLY, 0); if (fd < 0) { return -1; } #ifdef DEBUG_INPUT_EVENTS printf("Checking %s\n", path); #endif isstick = IsJoystick(fd, &name, &guid); close(fd); if (!isstick) { return -1; } item = (SDL_joylist_item *) SDL_malloc(sizeof (SDL_joylist_item)); if (item == NULL) { return -1; } SDL_zerop(item); item->devnum = sb.st_rdev; item->path = SDL_strdup(path); item->name = name; item->guid = guid; if ((item->path == NULL) || (item->name == NULL)) { SDL_free(item->path); SDL_free(item->name); SDL_free(item); return -1; } item->device_instance = SDL_GetNextJoystickInstanceID(); if (SDL_joylist_tail == NULL) { SDL_joylist = SDL_joylist_tail = item; } else { SDL_joylist_tail->next = item; SDL_joylist_tail = item; } /* Need to increment the joystick count before we post the event */ ++numjoysticks; SDL_PrivateJoystickAdded(item->device_instance); return numjoysticks; } #if SDL_USE_LIBUDEV static int MaybeRemoveDevice(const char *path) { SDL_joylist_item *item; SDL_joylist_item *prev = NULL; if (path == NULL) { return -1; } for (item = SDL_joylist; item != NULL; item = item->next) { /* found it, remove it. */ if (SDL_strcmp(path, item->path) == 0) { const int retval = item->device_instance; if (item->hwdata) { item->hwdata->item = NULL; } if (prev != NULL) { prev->next = item->next; } else { SDL_assert(SDL_joylist == item); SDL_joylist = item->next; } if (item == SDL_joylist_tail) { SDL_joylist_tail = prev; } /* Need to decrement the joystick count before we post the event */ --numjoysticks; SDL_PrivateJoystickRemoved(item->device_instance); SDL_free(item->path); SDL_free(item->name); SDL_free(item); return retval; } prev = item; } return -1; } #endif static void HandlePendingRemovals(void) { SDL_joylist_item *prev = NULL; SDL_joylist_item *item = SDL_joylist; while (item != NULL) { if (item->hwdata && item->hwdata->gone) { item->hwdata->item = NULL; if (prev != NULL) { prev->next = item->next; } else { SDL_assert(SDL_joylist == item); SDL_joylist = item->next; } if (item == SDL_joylist_tail) { SDL_joylist_tail = prev; } /* Need to decrement the joystick count before we post the event */ --numjoysticks; SDL_PrivateJoystickRemoved(item->device_instance); SDL_free(item->path); SDL_free(item->name); SDL_free(item); if (prev != NULL) { item = prev->next; } else { item = SDL_joylist; } } else { prev = item; item = item->next; } } } static SDL_bool SteamControllerConnectedCallback(const char *name, SDL_JoystickGUID guid, int *device_instance) { SDL_joylist_item *item; item = (SDL_joylist_item *) SDL_calloc(1, sizeof (SDL_joylist_item)); if (item == NULL) { return SDL_FALSE; } item->path = SDL_strdup(""); item->name = SDL_strdup(name); item->guid = guid; item->m_bSteamController = SDL_TRUE; if ((item->path == NULL) || (item->name == NULL)) { SDL_free(item->path); SDL_free(item->name); SDL_free(item); return SDL_FALSE; } *device_instance = item->device_instance = SDL_GetNextJoystickInstanceID(); if (SDL_joylist_tail == NULL) { SDL_joylist = SDL_joylist_tail = item; } else { SDL_joylist_tail->next = item; SDL_joylist_tail = item; } /* Need to increment the joystick count before we post the event */ ++numjoysticks; SDL_PrivateJoystickAdded(item->device_instance); return SDL_TRUE; } static void SteamControllerDisconnectedCallback(int device_instance) { SDL_joylist_item *item; SDL_joylist_item *prev = NULL; for (item = SDL_joylist; item != NULL; item = item->next) { /* found it, remove it. */ if (item->device_instance == device_instance) { if (item->hwdata) { item->hwdata->item = NULL; } if (prev != NULL) { prev->next = item->next; } else { SDL_assert(SDL_joylist == item); SDL_joylist = item->next; } if (item == SDL_joylist_tail) { SDL_joylist_tail = prev; } /* Need to decrement the joystick count before we post the event */ --numjoysticks; SDL_PrivateJoystickRemoved(item->device_instance); SDL_free(item->name); SDL_free(item); return; } prev = item; } } static void LINUX_JoystickDetect(void) { #if SDL_USE_LIBUDEV SDL_UDEV_Poll(); #else const Uint32 SDL_JOY_DETECT_INTERVAL_MS = 3000; /* Update every 3 seconds */ Uint32 now = SDL_GetTicks(); if (!last_joy_detect_time || SDL_TICKS_PASSED(now, last_joy_detect_time + SDL_JOY_DETECT_INTERVAL_MS)) { struct stat sb; /* Opening input devices can generate synchronous device I/O, so avoid it if we can */ if (stat("/dev/input", &sb) == 0 && sb.st_mtime != last_input_dir_mtime) { DIR *folder; struct dirent *dent; folder = opendir("/dev/input"); if (folder) { while ((dent = readdir(folder))) { int len = SDL_strlen(dent->d_name); if (len > 5 && SDL_strncmp(dent->d_name, "event", 5) == 0) { char path[PATH_MAX]; SDL_snprintf(path, SDL_arraysize(path), "/dev/input/%s", dent->d_name); MaybeAddDevice(path); } } closedir(folder); } last_input_dir_mtime = sb.st_mtime; } last_joy_detect_time = now; } #endif HandlePendingRemovals(); SDL_UpdateSteamControllers(); } static int LINUX_JoystickInit(void) { /* First see if the user specified one or more joysticks to use */ if (SDL_getenv("SDL_JOYSTICK_DEVICE") != NULL) { char *envcopy, *envpath, *delim; envcopy = SDL_strdup(SDL_getenv("SDL_JOYSTICK_DEVICE")); envpath = envcopy; while (envpath != NULL) { delim = SDL_strchr(envpath, ':'); if (delim != NULL) { *delim++ = '\0'; } MaybeAddDevice(envpath); envpath = delim; } SDL_free(envcopy); } SDL_InitSteamControllers(SteamControllerConnectedCallback, SteamControllerDisconnectedCallback); #if SDL_USE_LIBUDEV if (SDL_UDEV_Init() < 0) { return SDL_SetError("Could not initialize UDEV"); } /* Set up the udev callback */ if (SDL_UDEV_AddCallback(joystick_udev_callback) < 0) { SDL_UDEV_Quit(); return SDL_SetError("Could not set up joystick <-> udev callback"); } /* Force a scan to build the initial device list */ SDL_UDEV_Scan(); #else /* Force immediate joystick detection */ last_joy_detect_time = 0; last_input_dir_mtime = 0; /* Report all devices currently present */ LINUX_JoystickDetect(); #endif return 0; } static int LINUX_JoystickGetCount(void) { return numjoysticks; } static SDL_joylist_item * JoystickByDevIndex(int device_index) { SDL_joylist_item *item = SDL_joylist; if ((device_index < 0) || (device_index >= numjoysticks)) { return NULL; } while (device_index > 0) { SDL_assert(item != NULL); device_index--; item = item->next; } return item; } /* Function to get the device-dependent name of a joystick */ static const char * LINUX_JoystickGetDeviceName(int device_index) { return JoystickByDevIndex(device_index)->name; } static int LINUX_JoystickGetDevicePlayerIndex(int device_index) { return -1; } static void LINUX_JoystickSetDevicePlayerIndex(int device_index, int player_index) { } static SDL_JoystickGUID LINUX_JoystickGetDeviceGUID( int device_index ) { return JoystickByDevIndex(device_index)->guid; } /* Function to perform the mapping from device index to the instance id for this index */ static SDL_JoystickID LINUX_JoystickGetDeviceInstanceID(int device_index) { return JoystickByDevIndex(device_index)->device_instance; } static int allocate_hatdata(SDL_Joystick * joystick) { int i; joystick->hwdata->hats = (struct hwdata_hat *) SDL_malloc(joystick->nhats * sizeof(struct hwdata_hat)); if (joystick->hwdata->hats == NULL) { return (-1); } for (i = 0; i < joystick->nhats; ++i) { joystick->hwdata->hats[i].axis[0] = 1; joystick->hwdata->hats[i].axis[1] = 1; } return (0); } static int allocate_balldata(SDL_Joystick * joystick) { int i; joystick->hwdata->balls = (struct hwdata_ball *) SDL_malloc(joystick->nballs * sizeof(struct hwdata_ball)); if (joystick->hwdata->balls == NULL) { return (-1); } for (i = 0; i < joystick->nballs; ++i) { joystick->hwdata->balls[i].axis[0] = 0; joystick->hwdata->balls[i].axis[1] = 0; } return (0); } static void ConfigJoystick(SDL_Joystick * joystick, int fd) { int i, t; unsigned long keybit[NBITS(KEY_MAX)] = { 0 }; unsigned long absbit[NBITS(ABS_MAX)] = { 0 }; unsigned long relbit[NBITS(REL_MAX)] = { 0 }; unsigned long ffbit[NBITS(FF_MAX)] = { 0 }; /* See if this device uses the new unified event API */ if ((ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) >= 0) && (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) >= 0) && (ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relbit)), relbit) >= 0)) { /* Get the number of buttons, axes, and other thingamajigs */ for (i = BTN_JOYSTICK; i < KEY_MAX; ++i) { if (test_bit(i, keybit)) { #ifdef DEBUG_INPUT_EVENTS printf("Joystick has button: 0x%x\n", i); #endif joystick->hwdata->key_map[i] = joystick->nbuttons; joystick->hwdata->has_key[i] = SDL_TRUE; ++joystick->nbuttons; } } for (i = 0; i < BTN_JOYSTICK; ++i) { if (test_bit(i, keybit)) { #ifdef DEBUG_INPUT_EVENTS printf("Joystick has button: 0x%x\n", i); #endif joystick->hwdata->key_map[i] = joystick->nbuttons; joystick->hwdata->has_key[i] = SDL_TRUE; ++joystick->nbuttons; } } for (i = 0; i < ABS_MAX; ++i) { /* Skip hats */ if (i == ABS_HAT0X) { i = ABS_HAT3Y; continue; } if (test_bit(i, absbit)) { struct input_absinfo absinfo; if (ioctl(fd, EVIOCGABS(i), &absinfo) < 0) { continue; } #ifdef DEBUG_INPUT_EVENTS printf("Joystick has absolute axis: 0x%.2x\n", i); printf("Values = { %d, %d, %d, %d, %d }\n", absinfo.value, absinfo.minimum, absinfo.maximum, absinfo.fuzz, absinfo.flat); #endif /* DEBUG_INPUT_EVENTS */ joystick->hwdata->abs_map[i] = joystick->naxes; joystick->hwdata->has_abs[i] = SDL_TRUE; if (absinfo.minimum == absinfo.maximum) { joystick->hwdata->abs_correct[i].used = 0; } else { joystick->hwdata->abs_correct[i].used = 1; joystick->hwdata->abs_correct[i].coef[0] = (absinfo.maximum + absinfo.minimum) - 2 * absinfo.flat; joystick->hwdata->abs_correct[i].coef[1] = (absinfo.maximum + absinfo.minimum) + 2 * absinfo.flat; t = ((absinfo.maximum - absinfo.minimum) - 4 * absinfo.flat); if (t != 0) { joystick->hwdata->abs_correct[i].coef[2] = (1 << 28) / t; } else { joystick->hwdata->abs_correct[i].coef[2] = 0; } } ++joystick->naxes; } } for (i = ABS_HAT0X; i <= ABS_HAT3Y; i += 2) { if (test_bit(i, absbit) || test_bit(i + 1, absbit)) { struct input_absinfo absinfo; int hat_index = (i - ABS_HAT0X) / 2; if (ioctl(fd, EVIOCGABS(i), &absinfo) < 0) { continue; } #ifdef DEBUG_INPUT_EVENTS printf("Joystick has hat %d\n", hat_index); printf("Values = { %d, %d, %d, %d, %d }\n", absinfo.value, absinfo.minimum, absinfo.maximum, absinfo.fuzz, absinfo.flat); #endif /* DEBUG_INPUT_EVENTS */ joystick->hwdata->hats_indices[hat_index] = joystick->nhats++; joystick->hwdata->has_hat[hat_index] = SDL_TRUE; } } if (test_bit(REL_X, relbit) || test_bit(REL_Y, relbit)) { ++joystick->nballs; } /* Allocate data to keep track of these thingamajigs */ if (joystick->nhats > 0) { if (allocate_hatdata(joystick) < 0) { joystick->nhats = 0; } } if (joystick->nballs > 0) { if (allocate_balldata(joystick) < 0) { joystick->nballs = 0; } } } if (ioctl(fd, EVIOCGBIT(EV_FF, sizeof(ffbit)), ffbit) >= 0) { if (test_bit(FF_RUMBLE, ffbit)) { joystick->hwdata->ff_rumble = SDL_TRUE; } if (test_bit(FF_SINE, ffbit)) { joystick->hwdata->ff_sine = SDL_TRUE; } } } /* Function to open a joystick for use. The joystick to open is specified by the device index. This should fill the nbuttons and naxes fields of the joystick structure. It returns 0, or -1 if there is an error. */ static int LINUX_JoystickOpen(SDL_Joystick * joystick, int device_index) { SDL_joylist_item *item = JoystickByDevIndex(device_index); if (item == NULL) { return SDL_SetError("No such device"); } joystick->instance_id = item->device_instance; joystick->hwdata = (struct joystick_hwdata *) SDL_calloc(1, sizeof(*joystick->hwdata)); if (joystick->hwdata == NULL) { return SDL_OutOfMemory(); } joystick->hwdata->item = item; joystick->hwdata->guid = item->guid; joystick->hwdata->effect.id = -1; joystick->hwdata->m_bSteamController = item->m_bSteamController; SDL_memset(joystick->hwdata->abs_map, 0xFF, sizeof(joystick->hwdata->abs_map)); if (item->m_bSteamController) { joystick->hwdata->fd = -1; SDL_GetSteamControllerInputs(&joystick->nbuttons, &joystick->naxes, &joystick->nhats); } else { int fd = open(item->path, O_RDWR, 0); if (fd < 0) { SDL_free(joystick->hwdata); joystick->hwdata = NULL; return SDL_SetError("Unable to open %s", item->path); } joystick->hwdata->fd = fd; joystick->hwdata->fname = SDL_strdup(item->path); if (joystick->hwdata->fname == NULL) { SDL_free(joystick->hwdata); joystick->hwdata = NULL; close(fd); return SDL_OutOfMemory(); } /* Set the joystick to non-blocking read mode */ fcntl(fd, F_SETFL, O_NONBLOCK); /* Get the number of buttons and axes on the joystick */ ConfigJoystick(joystick, fd); } SDL_assert(item->hwdata == NULL); item->hwdata = joystick->hwdata; /* mark joystick as fresh and ready */ joystick->hwdata->fresh = SDL_TRUE; return (0); } static int LINUX_JoystickRumble(SDL_Joystick * joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { struct input_event event; if (joystick->hwdata->ff_rumble) { struct ff_effect *effect = &joystick->hwdata->effect; effect->type = FF_RUMBLE; effect->replay.length = SDL_MAX_RUMBLE_DURATION_MS; effect->u.rumble.strong_magnitude = low_frequency_rumble; effect->u.rumble.weak_magnitude = high_frequency_rumble; } else if (joystick->hwdata->ff_sine) { /* Scale and average the two rumble strengths */ Sint16 magnitude = (Sint16)(((low_frequency_rumble / 2) + (high_frequency_rumble / 2)) / 2); struct ff_effect *effect = &joystick->hwdata->effect; effect->type = FF_PERIODIC; effect->replay.length = SDL_MAX_RUMBLE_DURATION_MS; effect->u.periodic.waveform = FF_SINE; effect->u.periodic.magnitude = magnitude; } else { return SDL_Unsupported(); } if (ioctl(joystick->hwdata->fd, EVIOCSFF, &joystick->hwdata->effect) < 0) { /* The kernel may have lost this effect, try to allocate a new one */ joystick->hwdata->effect.id = -1; if (ioctl(joystick->hwdata->fd, EVIOCSFF, &joystick->hwdata->effect) < 0) { return SDL_SetError("Couldn't update rumble effect: %s", strerror(errno)); } } event.type = EV_FF; event.code = joystick->hwdata->effect.id; event.value = 1; if (write(joystick->hwdata->fd, &event, sizeof(event)) < 0) { return SDL_SetError("Couldn't start rumble effect: %s", strerror(errno)); } return 0; } static SDL_INLINE void HandleHat(SDL_Joystick * stick, Uint8 hat, int axis, int value) { struct hwdata_hat *the_hat; const Uint8 position_map[3][3] = { {SDL_HAT_LEFTUP, SDL_HAT_UP, SDL_HAT_RIGHTUP}, {SDL_HAT_LEFT, SDL_HAT_CENTERED, SDL_HAT_RIGHT}, {SDL_HAT_LEFTDOWN, SDL_HAT_DOWN, SDL_HAT_RIGHTDOWN} }; the_hat = &stick->hwdata->hats[hat]; if (value < 0) { value = 0; } else if (value == 0) { value = 1; } else if (value > 0) { value = 2; } if (value != the_hat->axis[axis]) { the_hat->axis[axis] = value; SDL_PrivateJoystickHat(stick, hat, position_map[the_hat->axis[1]][the_hat->axis[0]]); } } static SDL_INLINE void HandleBall(SDL_Joystick * stick, Uint8 ball, int axis, int value) { stick->hwdata->balls[ball].axis[axis] += value; } static SDL_INLINE int AxisCorrect(SDL_Joystick * joystick, int which, int value) { struct axis_correct *correct; correct = &joystick->hwdata->abs_correct[which]; if (correct->used) { value *= 2; if (value > correct->coef[0]) { if (value < correct->coef[1]) { return 0; } value -= correct->coef[1]; } else { value -= correct->coef[0]; } value *= correct->coef[2]; value >>= 13; } /* Clamp and return */ if (value < -32768) return -32768; if (value > 32767) return 32767; return value; } static SDL_INLINE void PollAllValues(SDL_Joystick * joystick) { struct input_absinfo absinfo; unsigned long keyinfo[NBITS(KEY_MAX)]; int i; /* Poll all axis */ for (i = ABS_X; i < ABS_MAX; i++) { if (i == ABS_HAT0X) { /* we handle hats in the next loop, skip them for now. */ i = ABS_HAT3Y; continue; } if (joystick->hwdata->abs_correct[i].used) { if (ioctl(joystick->hwdata->fd, EVIOCGABS(i), &absinfo) >= 0) { absinfo.value = AxisCorrect(joystick, i, absinfo.value); #ifdef DEBUG_INPUT_EVENTS printf("Joystick : Re-read Axis %d (%d) val= %d\n", joystick->hwdata->abs_map[i], i, absinfo.value); #endif SDL_PrivateJoystickAxis(joystick, joystick->hwdata->abs_map[i], absinfo.value); } } } /* Poll all hats */ for (i = ABS_HAT0X; i <= ABS_HAT3Y; i++) { const int baseaxis = i - ABS_HAT0X; const int hatidx = baseaxis / 2; SDL_assert(hatidx < SDL_arraysize(joystick->hwdata->has_hat)); if (joystick->hwdata->has_hat[hatidx]) { if (ioctl(joystick->hwdata->fd, EVIOCGABS(i), &absinfo) >= 0) { const int hataxis = baseaxis % 2; HandleHat(joystick, joystick->hwdata->hats_indices[hatidx], hataxis, absinfo.value); } } } /* Poll all buttons */ SDL_zeroa(keyinfo); if (ioctl(joystick->hwdata->fd, EVIOCGKEY(sizeof (keyinfo)), keyinfo) >= 0) { for (i = 0; i < KEY_MAX; i++) { if (joystick->hwdata->has_key[i]) { const Uint8 value = test_bit(i, keyinfo) ? SDL_PRESSED : SDL_RELEASED; #ifdef DEBUG_INPUT_EVENTS printf("Joystick : Re-read Button %d (%d) val= %d\n", joystick->hwdata->key_map[i], i, value); #endif SDL_PrivateJoystickButton(joystick, joystick->hwdata->key_map[i], value); } } } /* Joyballs are relative input, so there's no poll state. Events only! */ } static SDL_INLINE void HandleInputEvents(SDL_Joystick * joystick) { struct input_event events[32]; int i, len; int code; if (joystick->hwdata->fresh) { PollAllValues(joystick); joystick->hwdata->fresh = SDL_FALSE; } while ((len = read(joystick->hwdata->fd, events, (sizeof events))) > 0) { len /= sizeof(events[0]); for (i = 0; i < len; ++i) { code = events[i].code; /* If the kernel sent a SYN_DROPPED, we are supposed to ignore the rest of the packet (the end of it signified by a SYN_REPORT) */ if ( joystick->hwdata->recovering_from_dropped && ((events[i].type != EV_SYN) || (code != SYN_REPORT)) ) { continue; } switch (events[i].type) { case EV_KEY: SDL_PrivateJoystickButton(joystick, joystick->hwdata->key_map[code], events[i].value); break; case EV_ABS: switch (code) { case ABS_HAT0X: case ABS_HAT0Y: case ABS_HAT1X: case ABS_HAT1Y: case ABS_HAT2X: case ABS_HAT2Y: case ABS_HAT3X: case ABS_HAT3Y: code -= ABS_HAT0X; HandleHat(joystick, joystick->hwdata->hats_indices[code / 2], code % 2, events[i].value); break; default: if (joystick->hwdata->abs_map[code] != 0xFF) { events[i].value = AxisCorrect(joystick, code, events[i].value); SDL_PrivateJoystickAxis(joystick, joystick->hwdata->abs_map[code], events[i].value); } break; } break; case EV_REL: switch (code) { case REL_X: case REL_Y: code -= REL_X; HandleBall(joystick, code / 2, code % 2, events[i].value); break; default: break; } break; case EV_SYN: switch (code) { case SYN_DROPPED : #ifdef DEBUG_INPUT_EVENTS printf("Event SYN_DROPPED detected\n"); #endif joystick->hwdata->recovering_from_dropped = SDL_TRUE; break; case SYN_REPORT : if (joystick->hwdata->recovering_from_dropped) { joystick->hwdata->recovering_from_dropped = SDL_FALSE; PollAllValues(joystick); /* try to sync up to current state now */ } break; default: break; } default: break; } } } if (errno == ENODEV) { /* We have to wait until the JoystickDetect callback to remove this */ joystick->hwdata->gone = SDL_TRUE; } } static void LINUX_JoystickUpdate(SDL_Joystick * joystick) { int i; if (joystick->hwdata->m_bSteamController) { SDL_UpdateSteamController(joystick); return; } HandleInputEvents(joystick); /* Deliver ball motion updates */ for (i = 0; i < joystick->nballs; ++i) { int xrel, yrel; xrel = joystick->hwdata->balls[i].axis[0]; yrel = joystick->hwdata->balls[i].axis[1]; if (xrel || yrel) { joystick->hwdata->balls[i].axis[0] = 0; joystick->hwdata->balls[i].axis[1] = 0; SDL_PrivateJoystickBall(joystick, (Uint8) i, xrel, yrel); } } } /* Function to close a joystick after use */ static void LINUX_JoystickClose(SDL_Joystick * joystick) { if (joystick->hwdata) { if (joystick->hwdata->effect.id >= 0) { ioctl(joystick->hwdata->fd, EVIOCRMFF, joystick->hwdata->effect.id); joystick->hwdata->effect.id = -1; } if (joystick->hwdata->fd >= 0) { close(joystick->hwdata->fd); } if (joystick->hwdata->item) { joystick->hwdata->item->hwdata = NULL; } SDL_free(joystick->hwdata->hats); SDL_free(joystick->hwdata->balls); SDL_free(joystick->hwdata->fname); SDL_free(joystick->hwdata); } } /* Function to perform any system-specific joystick related cleanup */ static void LINUX_JoystickQuit(void) { SDL_joylist_item *item = NULL; SDL_joylist_item *next = NULL; for (item = SDL_joylist; item; item = next) { next = item->next; SDL_free(item->path); SDL_free(item->name); SDL_free(item); } SDL_joylist = SDL_joylist_tail = NULL; numjoysticks = 0; #if SDL_USE_LIBUDEV SDL_UDEV_DelCallback(joystick_udev_callback); SDL_UDEV_Quit(); #endif SDL_QuitSteamControllers(); } /* This is based on the Linux Gamepad Specification available at: https://www.kernel.org/doc/html/v4.15/input/gamepad.html */ static SDL_bool LINUX_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) { SDL_Joystick * joystick; joystick = (SDL_Joystick *) SDL_calloc(sizeof(*joystick), 1); if (joystick == NULL) { SDL_OutOfMemory(); return SDL_FALSE; } /* We temporarily open the device to check how it's configured. */ if (LINUX_JoystickOpen(joystick, device_index) < 0) { SDL_free(joystick); return SDL_FALSE; } if (!joystick->hwdata->has_key[BTN_GAMEPAD]) { /* Not a gamepad according to the specs. */ LINUX_JoystickClose(joystick); SDL_free(joystick); return SDL_FALSE; } /* We have a gamepad, start filling out the mappings */ if (joystick->hwdata->has_key[BTN_SOUTH]) { out->a.kind = EMappingKind_Button; out->a.target = joystick->hwdata->key_map[BTN_SOUTH]; } if (joystick->hwdata->has_key[BTN_EAST]) { out->b.kind = EMappingKind_Button; out->b.target = joystick->hwdata->key_map[BTN_EAST]; } if (joystick->hwdata->has_key[BTN_NORTH]) { out->y.kind = EMappingKind_Button; out->y.target = joystick->hwdata->key_map[BTN_NORTH]; } if (joystick->hwdata->has_key[BTN_WEST]) { out->x.kind = EMappingKind_Button; out->x.target = joystick->hwdata->key_map[BTN_WEST]; } if (joystick->hwdata->has_key[BTN_SELECT]) { out->back.kind = EMappingKind_Button; out->back.target = joystick->hwdata->key_map[BTN_SELECT]; } if (joystick->hwdata->has_key[BTN_START]) { out->start.kind = EMappingKind_Button; out->start.target = joystick->hwdata->key_map[BTN_START]; } if (joystick->hwdata->has_key[BTN_THUMBL]) { out->leftstick.kind = EMappingKind_Button; out->leftstick.target = joystick->hwdata->key_map[BTN_THUMBL]; } if (joystick->hwdata->has_key[BTN_THUMBR]) { out->rightstick.kind = EMappingKind_Button; out->rightstick.target = joystick->hwdata->key_map[BTN_THUMBR]; } if (joystick->hwdata->has_key[BTN_MODE]) { out->guide.kind = EMappingKind_Button; out->guide.target = joystick->hwdata->key_map[BTN_MODE]; } /* According to the specs the D-Pad, the shoulder buttons and the triggers can be digital, or analog, or both at the same time. */ /* Prefer digital shoulder buttons, but settle for analog if missing. */ if (joystick->hwdata->has_key[BTN_TL]) { out->leftshoulder.kind = EMappingKind_Button; out->leftshoulder.target = joystick->hwdata->key_map[BTN_TL]; } if (joystick->hwdata->has_key[BTN_TR]) { out->rightshoulder.kind = EMappingKind_Button; out->rightshoulder.target = joystick->hwdata->key_map[BTN_TR]; } if (joystick->hwdata->has_hat[1] && /* Check if ABS_HAT1{X, Y} is available. */ (!joystick->hwdata->has_key[BTN_TL] || !joystick->hwdata->has_key[BTN_TR])) { int hat = joystick->hwdata->hats_indices[1] << 4; out->leftshoulder.kind = EMappingKind_Hat; out->rightshoulder.kind = EMappingKind_Hat; out->leftshoulder.target = hat | 0x4; out->rightshoulder.target = hat | 0x2; } /* Prefer analog triggers, but settle for digital if missing. */ if (joystick->hwdata->has_hat[2]) { /* Check if ABS_HAT2{X,Y} is available. */ int hat = joystick->hwdata->hats_indices[2] << 4; out->lefttrigger.kind = EMappingKind_Hat; out->righttrigger.kind = EMappingKind_Hat; out->lefttrigger.target = hat | 0x4; out->righttrigger.target = hat | 0x2; } else { if (joystick->hwdata->has_key[BTN_TL2]) { out->lefttrigger.kind = EMappingKind_Button; out->lefttrigger.target = joystick->hwdata->key_map[BTN_TL2]; } if (joystick->hwdata->has_key[BTN_TR2]) { out->righttrigger.kind = EMappingKind_Button; out->righttrigger.target = joystick->hwdata->key_map[BTN_TR2]; } } /* Prefer digital D-Pad, but settle for analog if missing. */ if (joystick->hwdata->has_key[BTN_DPAD_UP]) { out->dpup.kind = EMappingKind_Button; out->dpup.target = joystick->hwdata->key_map[BTN_DPAD_UP]; } if (joystick->hwdata->has_key[BTN_DPAD_DOWN]) { out->dpdown.kind = EMappingKind_Button; out->dpdown.target = joystick->hwdata->key_map[BTN_DPAD_DOWN]; } if (joystick->hwdata->has_key[BTN_DPAD_LEFT]) { out->dpleft.kind = EMappingKind_Button; out->dpleft.target = joystick->hwdata->key_map[BTN_DPAD_LEFT]; } if (joystick->hwdata->has_key[BTN_DPAD_RIGHT]) { out->dpright.kind = EMappingKind_Button; out->dpright.target = joystick->hwdata->key_map[BTN_DPAD_RIGHT]; } if (joystick->hwdata->has_hat[0] && /* Check if ABS_HAT0{X,Y} is available. */ (!joystick->hwdata->has_key[BTN_DPAD_LEFT] || !joystick->hwdata->has_key[BTN_DPAD_RIGHT] || !joystick->hwdata->has_key[BTN_DPAD_UP] || !joystick->hwdata->has_key[BTN_DPAD_DOWN])) { int hat = joystick->hwdata->hats_indices[0] << 4; out->dpleft.kind = EMappingKind_Hat; out->dpright.kind = EMappingKind_Hat; out->dpup.kind = EMappingKind_Hat; out->dpdown.kind = EMappingKind_Hat; out->dpleft.target = hat | 0x8; out->dpright.target = hat | 0x2; out->dpup.target = hat | 0x1; out->dpdown.target = hat | 0x4; } if (joystick->hwdata->has_abs[ABS_X] && joystick->hwdata->has_abs[ABS_Y]) { out->leftx.kind = EMappingKind_Axis; out->lefty.kind = EMappingKind_Axis; out->leftx.target = joystick->hwdata->abs_map[ABS_X]; out->lefty.target = joystick->hwdata->abs_map[ABS_Y]; } if (joystick->hwdata->has_abs[ABS_RX] && joystick->hwdata->has_abs[ABS_RY]) { out->rightx.kind = EMappingKind_Axis; out->righty.kind = EMappingKind_Axis; out->rightx.target = joystick->hwdata->abs_map[ABS_RX]; out->righty.target = joystick->hwdata->abs_map[ABS_RY]; } LINUX_JoystickClose(joystick); SDL_free(joystick); return SDL_TRUE; } SDL_JoystickDriver SDL_LINUX_JoystickDriver = { LINUX_JoystickInit, LINUX_JoystickGetCount, LINUX_JoystickDetect, LINUX_JoystickGetDeviceName, LINUX_JoystickGetDevicePlayerIndex, LINUX_JoystickSetDevicePlayerIndex, LINUX_JoystickGetDeviceGUID, LINUX_JoystickGetDeviceInstanceID, LINUX_JoystickOpen, LINUX_JoystickRumble, LINUX_JoystickUpdate, LINUX_JoystickClose, LINUX_JoystickQuit, LINUX_JoystickGetGamepadMapping }; #endif /* SDL_JOYSTICK_LINUX */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/linux/SDL_sysjoystick.c
C
apache-2.0
41,890
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_sysjoystick_c_h_ #define SDL_sysjoystick_c_h_ #include <linux/input.h> struct SDL_joylist_item; /* The private structure used to keep track of a joystick */ struct joystick_hwdata { int fd; struct SDL_joylist_item *item; SDL_JoystickGUID guid; char *fname; /* Used in haptic subsystem */ SDL_bool ff_rumble; SDL_bool ff_sine; struct ff_effect effect; Uint32 effect_expiration; /* The current Linux joystick driver maps hats to two axes */ struct hwdata_hat { int axis[2]; } *hats; /* The current Linux joystick driver maps balls to two axes */ struct hwdata_ball { int axis[2]; } *balls; /* Support for the Linux 2.4 unified input interface */ Uint8 key_map[KEY_MAX]; Uint8 abs_map[ABS_MAX]; SDL_bool has_key[KEY_MAX]; SDL_bool has_abs[ABS_MAX]; struct axis_correct { int used; int coef[3]; } abs_correct[ABS_MAX]; SDL_bool fresh; SDL_bool recovering_from_dropped; /* Steam Controller support */ SDL_bool m_bSteamController; /* 4 = (ABS_HAT3X-ABS_HAT0X)/2 (see input-event-codes.h in kernel) */ int hats_indices[4]; SDL_bool has_hat[4]; /* Set when gamepad is pending removal due to ENODEV read error */ SDL_bool gone; }; #endif /* SDL_sysjoystick_c_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/linux/SDL_sysjoystick_c.h
C
apache-2.0
2,334
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_JOYSTICK_PSP /* This is the PSP implementation of the SDL joystick API */ #include <pspctrl.h> #include <pspkernel.h> #include <stdio.h> /* For the definition of NULL */ #include <stdlib.h> #include "../SDL_sysjoystick.h" #include "../SDL_joystick_c.h" #include "SDL_events.h" #include "SDL_error.h" #include "SDL_mutex.h" #include "SDL_timer.h" #include "../../thread/SDL_systhread.h" /* Current pad state */ static SceCtrlData pad = { .Lx = 0, .Ly = 0, .Buttons = 0 }; static SDL_sem *pad_sem = NULL; static SDL_Thread *thread = NULL; static int running = 0; static const enum PspCtrlButtons button_map[] = { PSP_CTRL_TRIANGLE, PSP_CTRL_CIRCLE, PSP_CTRL_CROSS, PSP_CTRL_SQUARE, PSP_CTRL_LTRIGGER, PSP_CTRL_RTRIGGER, PSP_CTRL_DOWN, PSP_CTRL_LEFT, PSP_CTRL_UP, PSP_CTRL_RIGHT, PSP_CTRL_SELECT, PSP_CTRL_START, PSP_CTRL_HOME, PSP_CTRL_HOLD }; static int analog_map[256]; /* Map analog inputs to -32768 -> 32767 */ typedef struct { int x; int y; } point; /* 4 points define the bezier-curve. */ static point a = { 0, 0 }; static point b = { 50, 0 }; static point c = { 78, 32767 }; static point d = { 128, 32767 }; /* simple linear interpolation between two points */ static SDL_INLINE void lerp (point *dest, point *a, point *b, float t) { dest->x = a->x + (b->x - a->x)*t; dest->y = a->y + (b->y - a->y)*t; } /* evaluate a point on a bezier-curve. t goes from 0 to 1.0 */ static int calc_bezier_y(float t) { point ab, bc, cd, abbc, bccd, dest; lerp (&ab, &a, &b, t); /* point between a and b */ lerp (&bc, &b, &c, t); /* point between b and c */ lerp (&cd, &c, &d, t); /* point between c and d */ lerp (&abbc, &ab, &bc, t); /* point between ab and bc */ lerp (&bccd, &bc, &cd, t); /* point between bc and cd */ lerp (&dest, &abbc, &bccd, t); /* point on the bezier-curve */ return dest.y; } /* * Collect pad data about once per frame */ int JoystickUpdate(void *data) { while (running) { SDL_SemWait(pad_sem); sceCtrlPeekBufferPositive(&pad, 1); SDL_SemPost(pad_sem); /* Delay 1/60th of a second */ sceKernelDelayThread(1000000 / 60); } return 0; } /* Function to scan the system for joysticks. * Joystick 0 should be the system default joystick. * It should return number of joysticks, or -1 on an unrecoverable fatal error. */ int SDL_SYS_JoystickInit(void) { int i; /* Setup input */ sceCtrlSetSamplingCycle(0); sceCtrlSetSamplingMode(PSP_CTRL_MODE_ANALOG); /* Start thread to read data */ if((pad_sem = SDL_CreateSemaphore(1)) == NULL) { return SDL_SetError("Can't create input semaphore"); } running = 1; if((thread = SDL_CreateThreadInternal(JoystickUpdate, "JoystickThread", 4096, NULL)) == NULL) { return SDL_SetError("Can't create input thread"); } /* Create an accurate map from analog inputs (0 to 255) to SDL joystick positions (-32768 to 32767) */ for (i = 0; i < 128; i++) { float t = (float)i/127.0f; analog_map[i+128] = calc_bezier_y(t); analog_map[127-i] = -1 * analog_map[i+128]; } return 1; } int SDL_SYS_NumJoysticks(void) { return 1; } void SDL_SYS_JoystickDetect(void) { } /* Function to get the device-dependent name of a joystick */ const char * SDL_SYS_JoystickNameForDeviceIndex(int device_index) { return "PSP builtin joypad"; } /* Function to perform the mapping from device index to the instance id for this index */ SDL_JoystickID SDL_SYS_GetInstanceIdOfDeviceIndex(int device_index) { return device_index; } /* Function to get the device-dependent name of a joystick */ const char *SDL_SYS_JoystickName(int index) { if (index == 0) return "PSP controller"; SDL_SetError("No joystick available with that index"); return(NULL); } /* Function to open a joystick for use. The joystick to open is specified by the device index. This should fill the nbuttons and naxes fields of the joystick structure. It returns 0, or -1 if there is an error. */ int SDL_SYS_JoystickOpen(SDL_Joystick *joystick, int device_index) { joystick->nbuttons = 14; joystick->naxes = 2; joystick->nhats = 0; return 0; } /* Function to update the state of a joystick - called as a device poll. * This function shouldn't update the joystick structure directly, * but instead should call SDL_PrivateJoystick*() to deliver events * and update joystick device state. */ void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick) { int i; enum PspCtrlButtons buttons; enum PspCtrlButtons changed; unsigned char x, y; static enum PspCtrlButtons old_buttons = 0; static unsigned char old_x = 0, old_y = 0; SDL_SemWait(pad_sem); buttons = pad.Buttons; x = pad.Lx; y = pad.Ly; SDL_SemPost(pad_sem); /* Axes */ if(old_x != x) { SDL_PrivateJoystickAxis(joystick, 0, analog_map[x]); old_x = x; } if(old_y != y) { SDL_PrivateJoystickAxis(joystick, 1, analog_map[y]); old_y = y; } /* Buttons */ changed = old_buttons ^ buttons; old_buttons = buttons; if(changed) { for(i=0; i<sizeof(button_map)/sizeof(button_map[0]); i++) { if(changed & button_map[i]) { SDL_PrivateJoystickButton( joystick, i, (buttons & button_map[i]) ? SDL_PRESSED : SDL_RELEASED); } } } sceKernelDelayThread(0); } /* Function to close a joystick after use */ void SDL_SYS_JoystickClose(SDL_Joystick *joystick) { } /* Function to perform any system-specific joystick related cleanup */ void SDL_SYS_JoystickQuit(void) { /* Cleanup Threads and Semaphore. */ running = 0; SDL_WaitThread(thread, NULL); SDL_DestroySemaphore(pad_sem); } SDL_JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index ) { SDL_JoystickGUID guid; /* the GUID is just the first 16 chars of the name for now */ const char *name = SDL_SYS_JoystickNameForDeviceIndex( device_index ); SDL_zero( guid ); SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) ); return guid; } SDL_JoystickGUID SDL_SYS_JoystickGetGUID(SDL_Joystick * joystick) { SDL_JoystickGUID guid; /* the GUID is just the first 16 chars of the name for now */ const char *name = joystick->name; SDL_zero( guid ); SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) ); return guid; } #endif /* SDL_JOYSTICK_PSP */ /* vim: ts=4 sw=4 */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/psp/SDL_sysjoystick.c
C
apache-2.0
7,611
#!/usr/bin/env python # # Script to sort the game controller database entries in SDL_gamecontroller.c import re filename = "SDL_gamecontrollerdb.h" input = open(filename) output = open(filename + ".new", "w") parsing_controllers = False controllers = [] controller_guids = {} conditionals = [] split_pattern = re.compile(r'([^"]*")([^,]*,)([^,]*,)([^"]*)(".*)') def find_element(prefix, bindings): i=0 for element in bindings: if element.startswith(prefix): return i i=(i + 1) return -1 def save_controller(line): global controllers match = split_pattern.match(line) entry = [ match.group(1), match.group(2), match.group(3) ] bindings = sorted(match.group(4).split(",")) if (bindings[0] == ""): bindings.pop(0) pos=find_element("sdk", bindings) if pos >= 0: bindings.append(bindings.pop(pos)) pos=find_element("hint:", bindings) if pos >= 0: bindings.append(bindings.pop(pos)) entry.extend(",".join(bindings) + ",") entry.append(match.group(5)) controllers.append(entry) if ',sdk' in line or ',hint:' in line: conditionals.append(entry[1]) def write_controllers(): global controllers global controller_guids # Check for duplicates for entry in controllers: if (entry[1] in controller_guids and entry[1] not in conditionals): current_name = entry[2] existing_name = controller_guids[entry[1]][2] print("Warning: entry '%s' is duplicate of entry '%s'" % (current_name, existing_name)) if (not current_name.startswith("(DUPE)")): entry[2] = "(DUPE) " + current_name if (not existing_name.startswith("(DUPE)")): controller_guids[entry[1]][2] = "(DUPE) " + existing_name controller_guids[entry[1]] = entry for entry in sorted(controllers, key=lambda entry: entry[2]+"-"+entry[1]): line = "".join(entry) + "\n" line = line.replace("\t", " ") if not line.endswith(",\n") and not line.endswith("*/\n"): print("Warning: '%s' is missing a comma at the end of the line" % (line)) output.write(line) controllers = [] controller_guids = {} for line in input: if (parsing_controllers): if (line.startswith("{")): output.write(line) elif (line.startswith(" NULL")): parsing_controllers = False write_controllers() output.write(line) elif (line.startswith("#if")): print("Parsing " + line.strip()) output.write(line) elif (line.startswith("#endif")): write_controllers() output.write(line) else: save_controller(line) else: if (line.startswith("static const char *s_ControllerMappings")): parsing_controllers = True output.write(line) output.close() print("Finished writing %s.new" % filename)
YifuLiu/AliOS-Things
components/SDL2/src/joystick/sort_controllers.py
Python
apache-2.0
2,998
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #include "../SDL_sysjoystick.h" #include "../SDL_joystick_c.h" #include "SDL_steamcontroller.h" void SDL_InitSteamControllers(SteamControllerConnectedCallback_t connectedCallback, SteamControllerDisconnectedCallback_t disconnectedCallback) { } void SDL_GetSteamControllerInputs(int *nbuttons, int *naxes, int *nhats) { *nbuttons = 0; *naxes = 0; *nhats = 0; } void SDL_UpdateSteamControllers(void) { } void SDL_UpdateSteamController(SDL_Joystick *joystick) { } void SDL_QuitSteamControllers(void) { } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/joystick/steam/SDL_steamcontroller.c
C
apache-2.0
1,557