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. */ #include "SDL_pspvideo.h" /* Functions to be exported */
YifuLiu/AliOS-Things
components/SDL2/src/video/psp/SDL_pspmouse_c.h
C
apache-2.0
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" #if SDL_VIDEO_DRIVER_PSP /* SDL internals */ #include "../SDL_sysvideo.h" #include "SDL_version.h" #include "SDL_syswm.h" #include "SDL_loadso.h" #include "SDL_events.h" #include "../../events/SDL_mouse_c.h" #include "../../events/SDL_keyboard_c.h" /* PSP declarations */ #include "SDL_pspvideo.h" #include "SDL_pspevents_c.h" #include "SDL_pspgl_c.h" /* unused static SDL_bool PSP_initialized = SDL_FALSE; */ static int PSP_Available(void) { return 1; } static void PSP_Destroy(SDL_VideoDevice * device) { /* SDL_VideoData *phdata = (SDL_VideoData *) device->driverdata; */ if (device->driverdata != NULL) { device->driverdata = NULL; } } static SDL_VideoDevice * PSP_Create() { SDL_VideoDevice *device; SDL_VideoData *phdata; SDL_GLDriverData *gldata; int status; /* Check if PSP could be initialized */ status = PSP_Available(); if (status == 0) { /* PSP could not be used */ return NULL; } /* Initialize SDL_VideoDevice structure */ device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice)); if (device == NULL) { SDL_OutOfMemory(); return NULL; } /* Initialize internal PSP specific data */ phdata = (SDL_VideoData *) SDL_calloc(1, sizeof(SDL_VideoData)); if (phdata == NULL) { SDL_OutOfMemory(); SDL_free(device); return NULL; } gldata = (SDL_GLDriverData *) SDL_calloc(1, sizeof(SDL_GLDriverData)); if (gldata == NULL) { SDL_OutOfMemory(); SDL_free(device); SDL_free(phdata); return NULL; } device->gl_data = gldata; device->driverdata = phdata; phdata->egl_initialized = SDL_TRUE; /* Setup amount of available displays */ device->num_displays = 0; /* Set device free function */ device->free = PSP_Destroy; /* Setup all functions which we can handle */ device->VideoInit = PSP_VideoInit; device->VideoQuit = PSP_VideoQuit; device->GetDisplayModes = PSP_GetDisplayModes; device->SetDisplayMode = PSP_SetDisplayMode; device->CreateSDLWindow = PSP_CreateWindow; device->CreateSDLWindowFrom = PSP_CreateWindowFrom; device->SetWindowTitle = PSP_SetWindowTitle; device->SetWindowIcon = PSP_SetWindowIcon; device->SetWindowPosition = PSP_SetWindowPosition; device->SetWindowSize = PSP_SetWindowSize; device->ShowWindow = PSP_ShowWindow; device->HideWindow = PSP_HideWindow; device->RaiseWindow = PSP_RaiseWindow; device->MaximizeWindow = PSP_MaximizeWindow; device->MinimizeWindow = PSP_MinimizeWindow; device->RestoreWindow = PSP_RestoreWindow; device->SetWindowGrab = PSP_SetWindowGrab; device->DestroyWindow = PSP_DestroyWindow; #if 0 device->GetWindowWMInfo = PSP_GetWindowWMInfo; #endif device->GL_LoadLibrary = PSP_GL_LoadLibrary; device->GL_GetProcAddress = PSP_GL_GetProcAddress; device->GL_UnloadLibrary = PSP_GL_UnloadLibrary; device->GL_CreateContext = PSP_GL_CreateContext; device->GL_MakeCurrent = PSP_GL_MakeCurrent; device->GL_SetSwapInterval = PSP_GL_SetSwapInterval; device->GL_GetSwapInterval = PSP_GL_GetSwapInterval; device->GL_SwapWindow = PSP_GL_SwapWindow; device->GL_DeleteContext = PSP_GL_DeleteContext; device->HasScreenKeyboardSupport = PSP_HasScreenKeyboardSupport; device->ShowScreenKeyboard = PSP_ShowScreenKeyboard; device->HideScreenKeyboard = PSP_HideScreenKeyboard; device->IsScreenKeyboardShown = PSP_IsScreenKeyboardShown; device->PumpEvents = PSP_PumpEvents; return device; } VideoBootStrap PSP_bootstrap = { "PSP", "PSP Video Driver", PSP_Available, PSP_Create }; /*****************************************************************************/ /* SDL Video and Display initialization/handling functions */ /*****************************************************************************/ int PSP_VideoInit(_THIS) { SDL_VideoDisplay display; SDL_DisplayMode current_mode; SDL_zero(current_mode); current_mode.w = 480; current_mode.h = 272; current_mode.refresh_rate = 60; /* 32 bpp for default */ current_mode.format = SDL_PIXELFORMAT_ABGR8888; current_mode.driverdata = NULL; SDL_zero(display); display.desktop_mode = current_mode; display.current_mode = current_mode; display.driverdata = NULL; SDL_AddVideoDisplay(&display); return 1; } void PSP_VideoQuit(_THIS) { } void PSP_GetDisplayModes(_THIS, SDL_VideoDisplay * display) { } int PSP_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode) { return 0; } #define EGLCHK(stmt) \ do { \ EGLint err; \ \ stmt; \ err = eglGetError(); \ if (err != EGL_SUCCESS) { \ SDL_SetError("EGL error %d", err); \ return 0; \ } \ } while (0) int PSP_CreateWindow(_THIS, SDL_Window * window) { SDL_WindowData *wdata; /* Allocate window internal data */ wdata = (SDL_WindowData *) SDL_calloc(1, sizeof(SDL_WindowData)); if (wdata == NULL) { return SDL_OutOfMemory(); } /* Setup driver data for this window */ window->driverdata = wdata; /* Window has been successfully created */ return 0; } int PSP_CreateWindowFrom(_THIS, SDL_Window * window, const void *data) { return SDL_Unsupported(); } void PSP_SetWindowTitle(_THIS, SDL_Window * window) { } void PSP_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon) { } void PSP_SetWindowPosition(_THIS, SDL_Window * window) { } void PSP_SetWindowSize(_THIS, SDL_Window * window) { } void PSP_ShowWindow(_THIS, SDL_Window * window) { } void PSP_HideWindow(_THIS, SDL_Window * window) { } void PSP_RaiseWindow(_THIS, SDL_Window * window) { } void PSP_MaximizeWindow(_THIS, SDL_Window * window) { } void PSP_MinimizeWindow(_THIS, SDL_Window * window) { } void PSP_RestoreWindow(_THIS, SDL_Window * window) { } void PSP_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed) { } void PSP_DestroyWindow(_THIS, SDL_Window * window) { } /*****************************************************************************/ /* SDL Window Manager function */ /*****************************************************************************/ #if 0 SDL_bool PSP_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info) { if (info->version.major <= SDL_MAJOR_VERSION) { return SDL_TRUE; } else { SDL_SetError("Application not compiled with SDL %d.%d", SDL_MAJOR_VERSION, SDL_MINOR_VERSION); return SDL_FALSE; } /* Failed to get window manager information */ return SDL_FALSE; } #endif /* TO Write Me */ SDL_bool PSP_HasScreenKeyboardSupport(_THIS) { return SDL_FALSE; } void PSP_ShowScreenKeyboard(_THIS, SDL_Window *window) { } void PSP_HideScreenKeyboard(_THIS, SDL_Window *window) { } SDL_bool PSP_IsScreenKeyboardShown(_THIS, SDL_Window *window) { return SDL_FALSE; } #endif /* SDL_VIDEO_DRIVER_PSP */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/psp/SDL_pspvideo.c
C
apache-2.0
8,390
/* 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_pspvideo_h_ #define SDL_pspvideo_h_ #include <GLES/egl.h> #include "../../SDL_internal.h" #include "../SDL_sysvideo.h" typedef struct SDL_VideoData { SDL_bool egl_initialized; /* OpenGL ES device initialization status */ uint32_t egl_refcount; /* OpenGL ES reference count */ } SDL_VideoData; typedef struct SDL_DisplayData { } SDL_DisplayData; typedef struct SDL_WindowData { SDL_bool uses_gles; /* if true window must support OpenGL ES */ } SDL_WindowData; /****************************************************************************/ /* SDL_VideoDevice functions declaration */ /****************************************************************************/ /* Display and window functions */ int PSP_VideoInit(_THIS); void PSP_VideoQuit(_THIS); void PSP_GetDisplayModes(_THIS, SDL_VideoDisplay * display); int PSP_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode); int PSP_CreateWindow(_THIS, SDL_Window * window); int PSP_CreateWindowFrom(_THIS, SDL_Window * window, const void *data); void PSP_SetWindowTitle(_THIS, SDL_Window * window); void PSP_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon); void PSP_SetWindowPosition(_THIS, SDL_Window * window); void PSP_SetWindowSize(_THIS, SDL_Window * window); void PSP_ShowWindow(_THIS, SDL_Window * window); void PSP_HideWindow(_THIS, SDL_Window * window); void PSP_RaiseWindow(_THIS, SDL_Window * window); void PSP_MaximizeWindow(_THIS, SDL_Window * window); void PSP_MinimizeWindow(_THIS, SDL_Window * window); void PSP_RestoreWindow(_THIS, SDL_Window * window); void PSP_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed); void PSP_DestroyWindow(_THIS, SDL_Window * window); /* Window manager function */ SDL_bool PSP_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info); /* OpenGL/OpenGL ES functions */ int PSP_GL_LoadLibrary(_THIS, const char *path); void *PSP_GL_GetProcAddress(_THIS, const char *proc); void PSP_GL_UnloadLibrary(_THIS); SDL_GLContext PSP_GL_CreateContext(_THIS, SDL_Window * window); int PSP_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context); int PSP_GL_SetSwapInterval(_THIS, int interval); int PSP_GL_GetSwapInterval(_THIS); int PSP_GL_SwapWindow(_THIS, SDL_Window * window); void PSP_GL_DeleteContext(_THIS, SDL_GLContext context); /* PSP on screen keyboard */ SDL_bool PSP_HasScreenKeyboardSupport(_THIS); void PSP_ShowScreenKeyboard(_THIS, SDL_Window *window); void PSP_HideScreenKeyboard(_THIS, SDL_Window *window); SDL_bool PSP_IsScreenKeyboardShown(_THIS, SDL_Window *window); #endif /* SDL_pspvideo_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/psp/SDL_pspvideo.h
C
apache-2.0
3,685
/* Simple DirectMedia Layer Copyright (C) 2017 BlackBerry Limited 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_qnx.h" static EGLDisplay egl_disp; /** * Detertmines the pixel format to use based on the current display and EGL * configuration. * @param egl_conf EGL configuration to use * @return A SCREEN_FORMAT* constant for the pixel format to use */ static int chooseFormat(EGLConfig egl_conf) { EGLint buffer_bit_depth; EGLint alpha_bit_depth; eglGetConfigAttrib(egl_disp, egl_conf, EGL_BUFFER_SIZE, &buffer_bit_depth); eglGetConfigAttrib(egl_disp, egl_conf, EGL_ALPHA_SIZE, &alpha_bit_depth); switch (buffer_bit_depth) { case 32: return SCREEN_FORMAT_RGBX8888; case 24: return SCREEN_FORMAT_RGB888; case 16: switch (alpha_bit_depth) { case 4: return SCREEN_FORMAT_RGBX4444; case 1: return SCREEN_FORMAT_RGBA5551; default: return SCREEN_FORMAT_RGB565; } default: return 0; } } /** * Enumerates the supported EGL configurations and chooses a suitable one. * @param[out] pconf The chosen configuration * @param[out] pformat The chosen pixel format * @return 0 if successful, -1 on error */ int glGetConfig(EGLConfig *pconf, int *pformat) { EGLConfig egl_conf = (EGLConfig)0; EGLConfig *egl_configs; EGLint egl_num_configs; EGLint val; EGLBoolean rc; EGLint i; // Determine the numbfer of configurations. rc = eglGetConfigs(egl_disp, NULL, 0, &egl_num_configs); if (rc != EGL_TRUE) { return -1; } if (egl_num_configs == 0) { return -1; } // Allocate enough memory for all configurations. egl_configs = malloc(egl_num_configs * sizeof(*egl_configs)); if (egl_configs == NULL) { return -1; } // Get the list of configurations. rc = eglGetConfigs(egl_disp, egl_configs, egl_num_configs, &egl_num_configs); if (rc != EGL_TRUE) { free(egl_configs); return -1; } // Find a good configuration. for (i = 0; i < egl_num_configs; i++) { eglGetConfigAttrib(egl_disp, egl_configs[i], EGL_SURFACE_TYPE, &val); if (!(val & EGL_WINDOW_BIT)) { continue; } eglGetConfigAttrib(egl_disp, egl_configs[i], EGL_RENDERABLE_TYPE, &val); if (!(val & EGL_OPENGL_ES2_BIT)) { continue; } eglGetConfigAttrib(egl_disp, egl_configs[i], EGL_DEPTH_SIZE, &val); if (val == 0) { continue; } egl_conf = egl_configs[i]; break; } free(egl_configs); *pconf = egl_conf; *pformat = chooseFormat(egl_conf); return 0; } /** * Initializes the EGL library. * @param _THIS * @param name unused * @return 0 if successful, -1 on error */ int glLoadLibrary(_THIS, const char *name) { EGLNativeDisplayType disp_id = EGL_DEFAULT_DISPLAY; egl_disp = eglGetDisplay(disp_id); if (egl_disp == EGL_NO_DISPLAY) { return -1; } if (eglInitialize(egl_disp, NULL, NULL) == EGL_FALSE) { return -1; } return 0; } /** * Finds the address of an EGL extension function. * @param proc Function name * @return Function address */ void * glGetProcAddress(_THIS, const char *proc) { return eglGetProcAddress(proc); } /** * Associates the given window with the necessary EGL structures for drawing and * displaying content. * @param _THIS * @param window The SDL window to create the context for * @return A pointer to the created context, if successful, NULL on error */ SDL_GLContext glCreateContext(_THIS, SDL_Window *window) { window_impl_t *impl = (window_impl_t *)window->driverdata; EGLContext context; EGLSurface surface; struct { EGLint client_version[2]; EGLint none; } egl_ctx_attr = { .client_version = { EGL_CONTEXT_CLIENT_VERSION, 2 }, .none = EGL_NONE }; struct { EGLint render_buffer[2]; EGLint none; } egl_surf_attr = { .render_buffer = { EGL_RENDER_BUFFER, EGL_BACK_BUFFER }, .none = EGL_NONE }; context = eglCreateContext(egl_disp, impl->conf, EGL_NO_CONTEXT, (EGLint *)&egl_ctx_attr); if (context == EGL_NO_CONTEXT) { return NULL; } surface = eglCreateWindowSurface(egl_disp, impl->conf, impl->window, (EGLint *)&egl_surf_attr); if (surface == EGL_NO_SURFACE) { return NULL; } eglMakeCurrent(egl_disp, surface, surface, context); impl->surface = surface; return context; } /** * Sets a new value for the number of frames to display before swapping buffers. * @param _THIS * @param interval New interval value * @return 0 if successful, -1 on error */ int glSetSwapInterval(_THIS, int interval) { if (eglSwapInterval(egl_disp, interval) != EGL_TRUE) { return -1; } return 0; } /** * Swaps the EGL buffers associated with the given window * @param _THIS * @param window Window to swap buffers for * @return 0 if successful, -1 on error */ int glSwapWindow(_THIS, SDL_Window *window) { /* !!! FIXME: should we migrate this all over to use SDL_egl.c? */ window_impl_t *impl = (window_impl_t *)window->driverdata; return eglSwapBuffers(egl_disp, impl->surface) == EGL_TRUE ? 0 : -1; } /** * Makes the given context the current one for drawing operations. * @param _THIS * @param window SDL window associated with the context (maybe NULL) * @param context The context to activate * @return 0 if successful, -1 on error */ int glMakeCurrent(_THIS, SDL_Window *window, SDL_GLContext context) { window_impl_t *impl; EGLSurface surface = NULL; if (window) { impl = (window_impl_t *)window->driverdata; surface = impl->surface; } if (eglMakeCurrent(egl_disp, surface, surface, context) != EGL_TRUE) { return -1; } return 0; } /** * Destroys a context. * @param _THIS * @param context The context to destroy */ void glDeleteContext(_THIS, SDL_GLContext context) { eglDestroyContext(egl_disp, context); } /** * Terminates access to the EGL library. * @param _THIS */ void glUnloadLibrary(_THIS) { eglTerminate(egl_disp); }
YifuLiu/AliOS-Things
components/SDL2/src/video/qnx/gl.c
C
apache-2.0
7,361
/* Simple DirectMedia Layer Copyright (C) 2017 BlackBerry Limited 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 "../../events/SDL_keyboard_c.h" #include "SDL_scancode.h" #include "SDL_events.h" #include "sdl_qnx.h" #include <sys/keycodes.h> /** * A map thta translates Screen key names to SDL scan codes. * This map is incomplete, but should include most major keys. */ static int key_to_sdl[] = { [KEYCODE_SPACE] = SDL_SCANCODE_SPACE, [KEYCODE_APOSTROPHE] = SDL_SCANCODE_APOSTROPHE, [KEYCODE_COMMA] = SDL_SCANCODE_COMMA, [KEYCODE_MINUS] = SDL_SCANCODE_MINUS, [KEYCODE_PERIOD] = SDL_SCANCODE_PERIOD, [KEYCODE_SLASH] = SDL_SCANCODE_SLASH, [KEYCODE_ZERO] = SDL_SCANCODE_0, [KEYCODE_ONE] = SDL_SCANCODE_1, [KEYCODE_TWO] = SDL_SCANCODE_2, [KEYCODE_THREE] = SDL_SCANCODE_3, [KEYCODE_FOUR] = SDL_SCANCODE_4, [KEYCODE_FIVE] = SDL_SCANCODE_5, [KEYCODE_SIX] = SDL_SCANCODE_6, [KEYCODE_SEVEN] = SDL_SCANCODE_7, [KEYCODE_EIGHT] = SDL_SCANCODE_8, [KEYCODE_NINE] = SDL_SCANCODE_9, [KEYCODE_SEMICOLON] = SDL_SCANCODE_SEMICOLON, [KEYCODE_EQUAL] = SDL_SCANCODE_EQUALS, [KEYCODE_LEFT_BRACKET] = SDL_SCANCODE_LEFTBRACKET, [KEYCODE_BACK_SLASH] = SDL_SCANCODE_BACKSLASH, [KEYCODE_RIGHT_BRACKET] = SDL_SCANCODE_RIGHTBRACKET, [KEYCODE_GRAVE] = SDL_SCANCODE_GRAVE, [KEYCODE_A] = SDL_SCANCODE_A, [KEYCODE_B] = SDL_SCANCODE_B, [KEYCODE_C] = SDL_SCANCODE_C, [KEYCODE_D] = SDL_SCANCODE_D, [KEYCODE_E] = SDL_SCANCODE_E, [KEYCODE_F] = SDL_SCANCODE_F, [KEYCODE_G] = SDL_SCANCODE_G, [KEYCODE_H] = SDL_SCANCODE_H, [KEYCODE_I] = SDL_SCANCODE_I, [KEYCODE_J] = SDL_SCANCODE_J, [KEYCODE_K] = SDL_SCANCODE_K, [KEYCODE_L] = SDL_SCANCODE_L, [KEYCODE_M] = SDL_SCANCODE_M, [KEYCODE_N] = SDL_SCANCODE_N, [KEYCODE_O] = SDL_SCANCODE_O, [KEYCODE_P] = SDL_SCANCODE_P, [KEYCODE_Q] = SDL_SCANCODE_Q, [KEYCODE_R] = SDL_SCANCODE_R, [KEYCODE_S] = SDL_SCANCODE_S, [KEYCODE_T] = SDL_SCANCODE_T, [KEYCODE_U] = SDL_SCANCODE_U, [KEYCODE_V] = SDL_SCANCODE_V, [KEYCODE_W] = SDL_SCANCODE_W, [KEYCODE_X] = SDL_SCANCODE_X, [KEYCODE_Y] = SDL_SCANCODE_Y, [KEYCODE_Z] = SDL_SCANCODE_Z, [KEYCODE_UP] = SDL_SCANCODE_UP, [KEYCODE_DOWN] = SDL_SCANCODE_DOWN, [KEYCODE_LEFT] = SDL_SCANCODE_LEFT, [KEYCODE_PG_UP] = SDL_SCANCODE_PAGEUP, [KEYCODE_PG_DOWN] = SDL_SCANCODE_PAGEDOWN, [KEYCODE_RIGHT] = SDL_SCANCODE_RIGHT, [KEYCODE_RETURN] = SDL_SCANCODE_RETURN, [KEYCODE_TAB] = SDL_SCANCODE_TAB, [KEYCODE_ESCAPE] = SDL_SCANCODE_ESCAPE, }; /** * Called from the event dispatcher when a keyboard event is encountered. * Translates the event such that it can be handled by SDL. * @param event Screen keyboard event */ void handleKeyboardEvent(screen_event_t event) { int val; SDL_Scancode scancode; // Get the key value. if (screen_get_event_property_iv(event, SCREEN_PROPERTY_SYM, &val) < 0) { return; } // Skip unrecognized keys. if ((val < 0) || (val >= SDL_TABLESIZE(key_to_sdl))) { return; } // Translate to an SDL scan code. scancode = key_to_sdl[val]; if (scancode == 0) { return; } // Get event flags (key state). if (screen_get_event_property_iv(event, SCREEN_PROPERTY_FLAGS, &val) < 0) { return; } // Propagate the event to SDL. // FIXME: // Need to handle more key states (such as key combinations). if (val & KEY_DOWN) { SDL_SendKeyboardKey(SDL_PRESSED, scancode); } else { SDL_SendKeyboardKey(SDL_RELEASED, scancode); } }
YifuLiu/AliOS-Things
components/SDL2/src/video/qnx/keyboard.c
C
apache-2.0
4,498
/* Simple DirectMedia Layer Copyright (C) 2017 BlackBerry Limited 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_QNX_H__ #define __SDL_QNX_H__ #include "../SDL_sysvideo.h" #include <screen/screen.h> #include <EGL/egl.h> typedef struct { screen_window_t window; EGLSurface surface; EGLConfig conf; } window_impl_t; extern void handleKeyboardEvent(screen_event_t event); extern int glGetConfig(EGLConfig *pconf, int *pformat); extern int glLoadLibrary(_THIS, const char *name); void *glGetProcAddress(_THIS, const char *proc); extern SDL_GLContext glCreateContext(_THIS, SDL_Window *window); extern int glSetSwapInterval(_THIS, int interval); extern int glSwapWindow(_THIS, SDL_Window *window); extern int glMakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context); extern void glDeleteContext(_THIS, SDL_GLContext context); extern void glUnloadLibrary(_THIS); #endif
YifuLiu/AliOS-Things
components/SDL2/src/video/qnx/sdl_qnx.h
C
apache-2.0
1,721
/* Simple DirectMedia Layer Copyright (C) 2017 BlackBerry Limited 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_sysvideo.h" #include "sdl_qnx.h" static screen_context_t context; static screen_event_t event; /** * Initializes the QNX video plugin. * Creates the Screen context and event handles used for all window operations * by the plugin. * @param _THIS * @return 0 if successful, -1 on error */ static int videoInit(_THIS) { SDL_VideoDisplay display; if (screen_create_context(&context, 0) < 0) { return -1; } if (screen_create_event(&event) < 0) { return -1; } SDL_zero(display); if (SDL_AddVideoDisplay(&display) < 0) { return -1; } _this->num_displays = 1; return 0; } static void videoQuit(_THIS) { } /** * Creates a new native Screen window and associates it with the given SDL * window. * @param _THIS * @param window SDL window to initialize * @return 0 if successful, -1 on error */ static int createWindow(_THIS, SDL_Window *window) { window_impl_t *impl; int size[2]; int numbufs; int format; int usage; impl = SDL_calloc(1, sizeof(*impl)); if (impl == NULL) { return -1; } // Create a native window. if (screen_create_window(&impl->window, context) < 0) { goto fail; } // Set the native window's size to match the SDL window. size[0] = window->w; size[1] = window->h; if (screen_set_window_property_iv(impl->window, SCREEN_PROPERTY_SIZE, size) < 0) { goto fail; } if (screen_set_window_property_iv(impl->window, SCREEN_PROPERTY_SOURCE_SIZE, size) < 0) { goto fail; } // Create window buffer(s). if (window->flags & SDL_WINDOW_OPENGL) { if (glGetConfig(&impl->conf, &format) < 0) { goto fail; } numbufs = 2; usage = SCREEN_USAGE_OPENGL_ES2; if (screen_set_window_property_iv(impl->window, SCREEN_PROPERTY_USAGE, &usage) < 0) { return -1; } } else { format = SCREEN_FORMAT_RGBX8888; numbufs = 1; } // Set pixel format. if (screen_set_window_property_iv(impl->window, SCREEN_PROPERTY_FORMAT, &format) < 0) { goto fail; } // Create buffer(s). if (screen_create_window_buffers(impl->window, numbufs) < 0) { goto fail; } window->driverdata = impl; return 0; fail: if (impl->window) { screen_destroy_window(impl->window); } SDL_free(impl); return -1; } /** * Gets a pointer to the Screen buffer associated with the given window. Note * that the buffer is actually created in createWindow(). * @param _THIS * @param window SDL window to get the buffer for * @param[out] pixles Holds a pointer to the window's buffer * @param[out] format Holds the pixel format for the buffer * @param[out] pitch Holds the number of bytes per line * @return 0 if successful, -1 on error */ static int createWindowFramebuffer(_THIS, SDL_Window * window, Uint32 * format, void ** pixels, int *pitch) { window_impl_t *impl = (window_impl_t *)window->driverdata; screen_buffer_t buffer; // Get a pointer to the buffer's memory. if (screen_get_window_property_pv(impl->window, SCREEN_PROPERTY_BUFFERS, (void **)&buffer) < 0) { return -1; } if (screen_get_buffer_property_pv(buffer, SCREEN_PROPERTY_POINTER, pixels) < 0) { return -1; } // Set format and pitch. if (screen_get_buffer_property_iv(buffer, SCREEN_PROPERTY_STRIDE, pitch) < 0) { return -1; } *format = SDL_PIXELFORMAT_RGB888; return 0; } /** * Informs the window manager that the window needs to be updated. * @param _THIS * @param window The window to update * @param rects An array of reectangular areas to update * @param numrects Rect array length * @return 0 if successful, -1 on error */ static int updateWindowFramebuffer(_THIS, SDL_Window *window, const SDL_Rect *rects, int numrects) { window_impl_t *impl = (window_impl_t *)window->driverdata; screen_buffer_t buffer; if (screen_get_window_property_pv(impl->window, SCREEN_PROPERTY_BUFFERS, (void **)&buffer) < 0) { return -1; } screen_post_window(impl->window, buffer, numrects, (int *)rects, 0); screen_flush_context(context, 0); return 0; } /** * Runs the main event loop. * @param _THIS */ static void pumpEvents(_THIS) { int type; for (;;) { if (screen_get_event(context, event, 0) < 0) { break; } if (screen_get_event_property_iv(event, SCREEN_PROPERTY_TYPE, &type) < 0) { break; } if (type == SCREEN_EVENT_NONE) { break; } switch (type) { case SCREEN_EVENT_KEYBOARD: handleKeyboardEvent(event); break; default: break; } } } /** * Updates the size of the native window using the geometry of the SDL window. * @param _THIS * @param window SDL window to update */ static void setWindowSize(_THIS, SDL_Window *window) { window_impl_t *impl = (window_impl_t *)window->driverdata; int size[2]; size[0] = window->w; size[1] = window->h; screen_set_window_property_iv(impl->window, SCREEN_PROPERTY_SIZE, size); screen_set_window_property_iv(impl->window, SCREEN_PROPERTY_SOURCE_SIZE, size); } /** * Makes the native window associated with the given SDL window visible. * @param _THIS * @param window SDL window to update */ static void showWindow(_THIS, SDL_Window *window) { window_impl_t *impl = (window_impl_t *)window->driverdata; const int visible = 1; screen_set_window_property_iv(impl->window, SCREEN_PROPERTY_VISIBLE, &visible); } /** * Makes the native window associated with the given SDL window invisible. * @param _THIS * @param window SDL window to update */ static void hideWindow(_THIS, SDL_Window *window) { window_impl_t *impl = (window_impl_t *)window->driverdata; const int visible = 0; screen_set_window_property_iv(impl->window, SCREEN_PROPERTY_VISIBLE, &visible); } /** * Destroys the native window associated with the given SDL window. * @param _THIS * @param window SDL window that is being destroyed */ static void destroyWindow(_THIS, SDL_Window *window) { window_impl_t *impl = (window_impl_t *)window->driverdata; if (impl) { screen_destroy_window(impl->window); window->driverdata = NULL; } } /** * Frees the plugin object created by createDevice(). * @param device Plugin object to free */ static void deleteDevice(SDL_VideoDevice *device) { SDL_free(device); } /** * Creates the QNX video plugin used by SDL. * @param devindex Unused * @return Initialized device if successful, NULL otherwise */ static SDL_VideoDevice * createDevice(int devindex) { SDL_VideoDevice *device; device = (SDL_VideoDevice *)SDL_calloc(1, sizeof(SDL_VideoDevice)); if (device == NULL) { return NULL; } device->driverdata = NULL; device->VideoInit = videoInit; device->VideoQuit = videoQuit; device->CreateSDLWindow = createWindow; device->CreateWindowFramebuffer = createWindowFramebuffer; device->UpdateWindowFramebuffer = updateWindowFramebuffer; device->SetWindowSize = setWindowSize; device->ShowWindow = showWindow; device->HideWindow = hideWindow; device->PumpEvents = pumpEvents; device->DestroyWindow = destroyWindow; device->GL_LoadLibrary = glLoadLibrary; device->GL_GetProcAddress = glGetProcAddress; device->GL_CreateContext = glCreateContext; device->GL_SetSwapInterval = glSetSwapInterval; device->GL_SwapWindow = glSwapWindow; device->GL_MakeCurrent = glMakeCurrent; device->GL_DeleteContext = glDeleteContext; device->GL_UnloadLibrary = glUnloadLibrary; device->free = deleteDevice; return device; } static int available() { return 1; } VideoBootStrap QNX_bootstrap = { "qnx", "QNX Screen", available, createDevice };
YifuLiu/AliOS-Things
components/SDL2/src/video/qnx/video.c
C
apache-2.0
9,554
/* 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_VIDEO_DRIVER_RPI #include "../../events/SDL_sysevents.h" #include "../../events/SDL_events_c.h" #include "../../events/SDL_keyboard_c.h" #include "SDL_rpivideo.h" #include "SDL_rpievents_c.h" #ifdef SDL_INPUT_LINUXEV #include "../../core/linux/SDL_evdev.h" #endif void RPI_PumpEvents(_THIS) { #ifdef SDL_INPUT_LINUXEV SDL_EVDEV_Poll(); #endif } #endif /* SDL_VIDEO_DRIVER_RPI */
YifuLiu/AliOS-Things
components/SDL2/src/video/raspberry/SDL_rpievents.c
C
apache-2.0
1,374
/* 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_rpievents_c_h_ #define SDL_rpievents_c_h_ #include "SDL_rpivideo.h" void RPI_PumpEvents(_THIS); void RPI_EventInit(_THIS); void RPI_EventQuit(_THIS); #endif /* SDL_rpievents_c_h_ */
YifuLiu/AliOS-Things
components/SDL2/src/video/raspberry/SDL_rpievents_c.h
C
apache-2.0
1,137
/* 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_VIDEO_DRIVER_RPI #include "SDL_assert.h" #include "SDL_surface.h" #include "SDL_hints.h" #include "SDL_rpivideo.h" #include "SDL_rpimouse.h" #include "../SDL_sysvideo.h" #include "../../events/SDL_mouse_c.h" #include "../../events/default_cursor.h" /* Copied from vc_vchi_dispmanx.h which is bugged and tries to include a non existing file */ /* Attributes changes flag mask */ #define ELEMENT_CHANGE_LAYER (1<<0) #define ELEMENT_CHANGE_OPACITY (1<<1) #define ELEMENT_CHANGE_DEST_RECT (1<<2) #define ELEMENT_CHANGE_SRC_RECT (1<<3) #define ELEMENT_CHANGE_MASK_RESOURCE (1<<4) #define ELEMENT_CHANGE_TRANSFORM (1<<5) /* End copied from vc_vchi_dispmanx.h */ static SDL_Cursor *RPI_CreateDefaultCursor(void); static SDL_Cursor *RPI_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y); static int RPI_ShowCursor(SDL_Cursor * cursor); static void RPI_MoveCursor(SDL_Cursor * cursor); static void RPI_FreeCursor(SDL_Cursor * cursor); static void RPI_WarpMouse(SDL_Window * window, int x, int y); static int RPI_WarpMouseGlobal(int x, int y); static SDL_Cursor *global_cursor; static SDL_Cursor * RPI_CreateDefaultCursor(void) { return SDL_CreateCursor(default_cdata, default_cmask, DEFAULT_CWIDTH, DEFAULT_CHEIGHT, DEFAULT_CHOTX, DEFAULT_CHOTY); } /* Create a cursor from a surface */ static SDL_Cursor * RPI_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y) { RPI_CursorData *curdata; SDL_Cursor *cursor; int ret; VC_RECT_T dst_rect; Uint32 dummy; SDL_assert(surface->format->format == SDL_PIXELFORMAT_ARGB8888); SDL_assert(surface->pitch == surface->w * 4); cursor = (SDL_Cursor *) SDL_calloc(1, sizeof(*cursor)); if (cursor == NULL) { SDL_OutOfMemory(); return NULL; } curdata = (RPI_CursorData *) SDL_calloc(1, sizeof(*curdata)); if (curdata == NULL) { SDL_OutOfMemory(); SDL_free(cursor); return NULL; } curdata->hot_x = hot_x; curdata->hot_y = hot_y; curdata->w = surface->w; curdata->h = surface->h; /* This usage is inspired by Wayland/Weston RPI code, how they figured this out is anyone's guess */ curdata->resource = vc_dispmanx_resource_create(VC_IMAGE_ARGB8888, surface->w | (surface->pitch << 16), surface->h | (surface->h << 16), &dummy); SDL_assert(curdata->resource); vc_dispmanx_rect_set(&dst_rect, 0, 0, curdata->w, curdata->h); /* A note from Weston: * vc_dispmanx_resource_write_data() ignores ifmt, * rect.x, rect.width, and uses stride only for computing * the size of the transfer as rect.height * stride. * Therefore we can only write rows starting at x=0. */ ret = vc_dispmanx_resource_write_data(curdata->resource, VC_IMAGE_ARGB8888, surface->pitch, surface->pixels, &dst_rect); SDL_assert (ret == DISPMANX_SUCCESS); cursor->driverdata = curdata; return cursor; } /* Show the specified cursor, or hide if cursor is NULL */ static int RPI_ShowCursor(SDL_Cursor * cursor) { int ret; DISPMANX_UPDATE_HANDLE_T update; RPI_CursorData *curdata; VC_RECT_T src_rect, dst_rect; SDL_Mouse *mouse; SDL_VideoDisplay *display; SDL_DisplayData *data; VC_DISPMANX_ALPHA_T alpha = { DISPMANX_FLAGS_ALPHA_FROM_SOURCE /* flags */ , 255 /*opacity 0->255*/, 0 /* mask */ }; uint32_t layer = SDL_RPI_MOUSELAYER; const char *env; mouse = SDL_GetMouse(); if (mouse == NULL) { return -1; } if (cursor != global_cursor) { if (global_cursor != NULL) { curdata = (RPI_CursorData *) global_cursor->driverdata; if (curdata && curdata->element > DISPMANX_NO_HANDLE) { update = vc_dispmanx_update_start(0); SDL_assert(update); ret = vc_dispmanx_element_remove(update, curdata->element); SDL_assert(ret == DISPMANX_SUCCESS); ret = vc_dispmanx_update_submit_sync(update); SDL_assert(ret == DISPMANX_SUCCESS); curdata->element = DISPMANX_NO_HANDLE; } } global_cursor = cursor; } if (cursor == NULL) { return 0; } curdata = (RPI_CursorData *) cursor->driverdata; if (curdata == NULL) { return -1; } if (mouse->focus == NULL) { return -1; } display = SDL_GetDisplayForWindow(mouse->focus); if (display == NULL) { return -1; } data = (SDL_DisplayData*) display->driverdata; if (data == NULL) { return -1; } if (curdata->element == DISPMANX_NO_HANDLE) { vc_dispmanx_rect_set(&src_rect, 0, 0, curdata->w << 16, curdata->h << 16); vc_dispmanx_rect_set(&dst_rect, mouse->x - curdata->hot_x, mouse->y - curdata->hot_y, curdata->w, curdata->h); update = vc_dispmanx_update_start(0); SDL_assert(update); env = SDL_GetHint(SDL_HINT_RPI_VIDEO_LAYER); if (env) { layer = SDL_atoi(env) + 1; } curdata->element = vc_dispmanx_element_add(update, data->dispman_display, layer, &dst_rect, curdata->resource, &src_rect, DISPMANX_PROTECTION_NONE, &alpha, DISPMANX_NO_HANDLE, // clamp DISPMANX_NO_ROTATE); SDL_assert(curdata->element > DISPMANX_NO_HANDLE); ret = vc_dispmanx_update_submit_sync(update); SDL_assert(ret == DISPMANX_SUCCESS); } return 0; } /* Free a window manager cursor */ static void RPI_FreeCursor(SDL_Cursor * cursor) { int ret; DISPMANX_UPDATE_HANDLE_T update; RPI_CursorData *curdata; if (cursor != NULL) { curdata = (RPI_CursorData *) cursor->driverdata; if (curdata != NULL) { if (curdata->element != DISPMANX_NO_HANDLE) { update = vc_dispmanx_update_start(0); SDL_assert(update); ret = vc_dispmanx_element_remove(update, curdata->element); SDL_assert(ret == DISPMANX_SUCCESS); ret = vc_dispmanx_update_submit_sync(update); SDL_assert(ret == DISPMANX_SUCCESS); } if (curdata->resource != DISPMANX_NO_HANDLE) { ret = vc_dispmanx_resource_delete(curdata->resource); SDL_assert(ret == DISPMANX_SUCCESS); } SDL_free(cursor->driverdata); } SDL_free(cursor); if (cursor == global_cursor) { global_cursor = NULL; } } } /* Warp the mouse to (x,y) */ static void RPI_WarpMouse(SDL_Window * window, int x, int y) { RPI_WarpMouseGlobal(x, y); } /* Warp the mouse to (x,y) */ static int RPI_WarpMouseGlobal(int x, int y) { RPI_CursorData *curdata; DISPMANX_UPDATE_HANDLE_T update; int ret; VC_RECT_T dst_rect; VC_RECT_T src_rect; SDL_Mouse *mouse = SDL_GetMouse(); if (mouse == NULL || mouse->cur_cursor == NULL || mouse->cur_cursor->driverdata == NULL) { return 0; } /* Update internal mouse position. */ SDL_SendMouseMotion(mouse->focus, mouse->mouseID, 0, x, y); curdata = (RPI_CursorData *) mouse->cur_cursor->driverdata; if (curdata->element == DISPMANX_NO_HANDLE) { return 0; } update = vc_dispmanx_update_start(0); if (!update) { return 0; } src_rect.x = 0; src_rect.y = 0; src_rect.width = curdata->w << 16; src_rect.height = curdata->h << 16; dst_rect.x = x - curdata->hot_x; dst_rect.y = y - curdata->hot_y; dst_rect.width = curdata->w; dst_rect.height = curdata->h; ret = vc_dispmanx_element_change_attributes( update, curdata->element, 0, 0, 0, &dst_rect, &src_rect, DISPMANX_NO_HANDLE, DISPMANX_NO_ROTATE); if (ret != DISPMANX_SUCCESS) { return SDL_SetError("vc_dispmanx_element_change_attributes() failed"); } /* Submit asynchronously, otherwise the peformance suffers a lot */ ret = vc_dispmanx_update_submit(update, 0, NULL); if (ret != DISPMANX_SUCCESS) { return SDL_SetError("vc_dispmanx_update_submit() failed"); } return 0; } /* Warp the mouse to (x,y) */ static int RPI_WarpMouseGlobalGraphicOnly(int x, int y) { RPI_CursorData *curdata; DISPMANX_UPDATE_HANDLE_T update; int ret; VC_RECT_T dst_rect; VC_RECT_T src_rect; SDL_Mouse *mouse = SDL_GetMouse(); if (mouse == NULL || mouse->cur_cursor == NULL || mouse->cur_cursor->driverdata == NULL) { return 0; } curdata = (RPI_CursorData *) mouse->cur_cursor->driverdata; if (curdata->element == DISPMANX_NO_HANDLE) { return 0; } update = vc_dispmanx_update_start(0); if (!update) { return 0; } src_rect.x = 0; src_rect.y = 0; src_rect.width = curdata->w << 16; src_rect.height = curdata->h << 16; dst_rect.x = x - curdata->hot_x; dst_rect.y = y - curdata->hot_y; dst_rect.width = curdata->w; dst_rect.height = curdata->h; ret = vc_dispmanx_element_change_attributes( update, curdata->element, 0, 0, 0, &dst_rect, &src_rect, DISPMANX_NO_HANDLE, DISPMANX_NO_ROTATE); if (ret != DISPMANX_SUCCESS) { return SDL_SetError("vc_dispmanx_element_change_attributes() failed"); } /* Submit asynchronously, otherwise the peformance suffers a lot */ ret = vc_dispmanx_update_submit(update, 0, NULL); if (ret != DISPMANX_SUCCESS) { return SDL_SetError("vc_dispmanx_update_submit() failed"); } return 0; } void RPI_InitMouse(_THIS) { /* FIXME: Using UDEV it should be possible to scan all mice * but there's no point in doing so as there's no multimice support...yet! */ SDL_Mouse *mouse = SDL_GetMouse(); mouse->CreateCursor = RPI_CreateCursor; mouse->ShowCursor = RPI_ShowCursor; mouse->MoveCursor = RPI_MoveCursor; mouse->FreeCursor = RPI_FreeCursor; mouse->WarpMouse = RPI_WarpMouse; mouse->WarpMouseGlobal = RPI_WarpMouseGlobal; SDL_SetDefaultCursor(RPI_CreateDefaultCursor()); } void RPI_QuitMouse(_THIS) { } /* This is called when a mouse motion event occurs */ static void RPI_MoveCursor(SDL_Cursor * cursor) { SDL_Mouse *mouse = SDL_GetMouse(); /* We must NOT call SDL_SendMouseMotion() on the next call or we will enter recursivity, * so we create a version of WarpMouseGlobal without it. */ RPI_WarpMouseGlobalGraphicOnly(mouse->x, mouse->y); } #endif /* SDL_VIDEO_DRIVER_RPI */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/raspberry/SDL_rpimouse.c
C
apache-2.0
12,135
/* 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_RPI_mouse_h_ #define SDL_RPI_mouse_h_ #include "../SDL_sysvideo.h" typedef struct _RPI_CursorData RPI_CursorData; struct _RPI_CursorData { DISPMANX_RESOURCE_HANDLE_T resource; DISPMANX_ELEMENT_HANDLE_T element; int hot_x, hot_y; int w, h; }; #define SDL_RPI_CURSORDATA(curs) RPI_CursorData *curdata = (RPI_CursorData *) ((curs) ? (curs)->driverdata : NULL) extern void RPI_InitMouse(_THIS); extern void RPI_QuitMouse(_THIS); #endif /* SDL_RPI_mouse_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/raspberry/SDL_rpimouse.h
C
apache-2.0
1,516
/* 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_hints.h" #if SDL_VIDEO_DRIVER_RPI && SDL_VIDEO_OPENGL_EGL #include "SDL_rpivideo.h" #include "SDL_rpiopengles.h" /* EGL implementation of SDL OpenGL support */ void RPI_GLES_DefaultProfileConfig(_THIS, int *mask, int *major, int *minor) { *mask = SDL_GL_CONTEXT_PROFILE_ES; *major = 2; *minor = 0; } int RPI_GLES_LoadLibrary(_THIS, const char *path) { return SDL_EGL_LoadLibrary(_this, path, EGL_DEFAULT_DISPLAY, 0); } int RPI_GLES_SwapWindow(_THIS, SDL_Window * window) { SDL_WindowData *wdata = ((SDL_WindowData *) window->driverdata); if (!(_this->egl_data->eglSwapBuffers(_this->egl_data->egl_display, wdata->egl_surface))) { SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "eglSwapBuffers failed."); return 0; } /* Wait immediately for vsync (as if we only had two buffers), for low input-lag scenarios. * Run your SDL2 program with "SDL_RPI_DOUBLE_BUFFER=1 <program_name>" to enable this. */ if (wdata->double_buffer) { SDL_LockMutex(wdata->vsync_cond_mutex); SDL_CondWait(wdata->vsync_cond, wdata->vsync_cond_mutex); SDL_UnlockMutex(wdata->vsync_cond_mutex); } return 0; } SDL_EGL_CreateContext_impl(RPI) SDL_EGL_MakeCurrent_impl(RPI) #endif /* SDL_VIDEO_DRIVER_RPI && SDL_VIDEO_OPENGL_EGL */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/raspberry/SDL_rpiopengles.c
C
apache-2.0
2,312
/* 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_rpiopengles_h_ #define SDL_rpiopengles_h_ #if SDL_VIDEO_DRIVER_RPI && SDL_VIDEO_OPENGL_EGL #include "../SDL_sysvideo.h" #include "../SDL_egl_c.h" /* OpenGLES functions */ #define RPI_GLES_GetAttribute SDL_EGL_GetAttribute #define RPI_GLES_GetProcAddress SDL_EGL_GetProcAddress #define RPI_GLES_UnloadLibrary SDL_EGL_UnloadLibrary #define RPI_GLES_SetSwapInterval SDL_EGL_SetSwapInterval #define RPI_GLES_GetSwapInterval SDL_EGL_GetSwapInterval #define RPI_GLES_DeleteContext SDL_EGL_DeleteContext extern int RPI_GLES_LoadLibrary(_THIS, const char *path); extern SDL_GLContext RPI_GLES_CreateContext(_THIS, SDL_Window * window); extern int RPI_GLES_SwapWindow(_THIS, SDL_Window * window); extern int RPI_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context); extern void RPI_GLES_DefaultProfileConfig(_THIS, int *mask, int *major, int *minor); #endif /* SDL_VIDEO_DRIVER_RPI && SDL_VIDEO_OPENGL_EGL */ #endif /* SDL_rpiopengles_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/raspberry/SDL_rpiopengles.h
C
apache-2.0
1,973
/* 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_VIDEO_DRIVER_RPI /* References * http://elinux.org/RPi_VideoCore_APIs * https://github.com/raspberrypi/firmware/blob/master/opt/vc/src/hello_pi/hello_triangle/triangle.c * http://cgit.freedesktop.org/wayland/weston/tree/src/rpi-renderer.c * http://cgit.freedesktop.org/wayland/weston/tree/src/compositor-rpi.c */ /* SDL internals */ #include "../SDL_sysvideo.h" #include "SDL_version.h" #include "SDL_syswm.h" #include "SDL_loadso.h" #include "SDL_events.h" #include "../../events/SDL_mouse_c.h" #include "../../events/SDL_keyboard_c.h" #include "SDL_hints.h" #ifdef SDL_INPUT_LINUXEV #include "../../core/linux/SDL_evdev.h" #endif /* RPI declarations */ #include "SDL_rpivideo.h" #include "SDL_rpievents_c.h" #include "SDL_rpiopengles.h" #include "SDL_rpimouse.h" static int RPI_Available(void) { return 1; } static void RPI_Destroy(SDL_VideoDevice * device) { SDL_free(device->driverdata); SDL_free(device); } static int RPI_GetRefreshRate() { TV_DISPLAY_STATE_T tvstate; if (vc_tv_get_display_state( &tvstate ) == 0) { //The width/height parameters are in the same position in the union //for HDMI and SDTV HDMI_PROPERTY_PARAM_T property; property.property = HDMI_PROPERTY_PIXEL_CLOCK_TYPE; vc_tv_hdmi_get_property(&property); return property.param1 == HDMI_PIXEL_CLOCK_TYPE_NTSC ? tvstate.display.hdmi.frame_rate * (1000.0f/1001.0f) : tvstate.display.hdmi.frame_rate; } return 60; /* Failed to get display state, default to 60 */ } static SDL_VideoDevice * RPI_Create() { SDL_VideoDevice *device; SDL_VideoData *phdata; /* Initialize SDL_VideoDevice structure */ device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice)); if (device == NULL) { SDL_OutOfMemory(); return NULL; } /* Initialize internal data */ phdata = (SDL_VideoData *) SDL_calloc(1, sizeof(SDL_VideoData)); if (phdata == NULL) { SDL_OutOfMemory(); SDL_free(device); return NULL; } device->driverdata = phdata; /* Setup amount of available displays */ device->num_displays = 0; /* Set device free function */ device->free = RPI_Destroy; /* Setup all functions which we can handle */ device->VideoInit = RPI_VideoInit; device->VideoQuit = RPI_VideoQuit; device->GetDisplayModes = RPI_GetDisplayModes; device->SetDisplayMode = RPI_SetDisplayMode; device->CreateSDLWindow = RPI_CreateWindow; device->CreateSDLWindowFrom = RPI_CreateWindowFrom; device->SetWindowTitle = RPI_SetWindowTitle; device->SetWindowIcon = RPI_SetWindowIcon; device->SetWindowPosition = RPI_SetWindowPosition; device->SetWindowSize = RPI_SetWindowSize; device->ShowWindow = RPI_ShowWindow; device->HideWindow = RPI_HideWindow; device->RaiseWindow = RPI_RaiseWindow; device->MaximizeWindow = RPI_MaximizeWindow; device->MinimizeWindow = RPI_MinimizeWindow; device->RestoreWindow = RPI_RestoreWindow; device->SetWindowGrab = RPI_SetWindowGrab; device->DestroyWindow = RPI_DestroyWindow; #if 0 device->GetWindowWMInfo = RPI_GetWindowWMInfo; #endif device->GL_LoadLibrary = RPI_GLES_LoadLibrary; device->GL_GetProcAddress = RPI_GLES_GetProcAddress; device->GL_UnloadLibrary = RPI_GLES_UnloadLibrary; device->GL_CreateContext = RPI_GLES_CreateContext; device->GL_MakeCurrent = RPI_GLES_MakeCurrent; device->GL_SetSwapInterval = RPI_GLES_SetSwapInterval; device->GL_GetSwapInterval = RPI_GLES_GetSwapInterval; device->GL_SwapWindow = RPI_GLES_SwapWindow; device->GL_DeleteContext = RPI_GLES_DeleteContext; device->GL_DefaultProfileConfig = RPI_GLES_DefaultProfileConfig; device->PumpEvents = RPI_PumpEvents; return device; } VideoBootStrap RPI_bootstrap = { "RPI", "RPI Video Driver", RPI_Available, RPI_Create }; /*****************************************************************************/ /* SDL Video and Display initialization/handling functions */ /*****************************************************************************/ static void AddDispManXDisplay(const int display_id) { DISPMANX_MODEINFO_T modeinfo; DISPMANX_DISPLAY_HANDLE_T handle; SDL_VideoDisplay display; SDL_DisplayMode current_mode; SDL_DisplayData *data; handle = vc_dispmanx_display_open(display_id); if (!handle) { return; /* this display isn't available */ } if (vc_dispmanx_display_get_info(handle, &modeinfo) < 0) { vc_dispmanx_display_close(handle); return; } /* RPI_GetRefreshRate() doesn't distinguish between displays. I'm not sure the hardware distinguishes either */ SDL_zero(current_mode); current_mode.w = modeinfo.width; current_mode.h = modeinfo.height; current_mode.refresh_rate = RPI_GetRefreshRate(); /* 32 bpp for default */ current_mode.format = SDL_PIXELFORMAT_ABGR8888; current_mode.driverdata = NULL; SDL_zero(display); display.desktop_mode = current_mode; display.current_mode = current_mode; /* Allocate display internal data */ data = (SDL_DisplayData *) SDL_calloc(1, sizeof(SDL_DisplayData)); if (data == NULL) { vc_dispmanx_display_close(handle); return; /* oh well */ } data->dispman_display = handle; display.driverdata = data; SDL_AddVideoDisplay(&display); } int RPI_VideoInit(_THIS) { /* Initialize BCM Host */ bcm_host_init(); AddDispManXDisplay(DISPMANX_ID_MAIN_LCD); /* your default display */ AddDispManXDisplay(DISPMANX_ID_FORCE_OTHER); /* an "other" display...maybe DSI-connected screen while HDMI is your main */ #ifdef SDL_INPUT_LINUXEV if (SDL_EVDEV_Init() < 0) { return -1; } #endif RPI_InitMouse(_this); return 1; } void RPI_VideoQuit(_THIS) { #ifdef SDL_INPUT_LINUXEV SDL_EVDEV_Quit(); #endif } void RPI_GetDisplayModes(_THIS, SDL_VideoDisplay * display) { /* Only one display mode available, the current one */ SDL_AddDisplayMode(display, &display->current_mode); } int RPI_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode) { return 0; } static void RPI_vsync_callback(DISPMANX_UPDATE_HANDLE_T u, void *data) { SDL_WindowData *wdata = ((SDL_WindowData *) data); SDL_LockMutex(wdata->vsync_cond_mutex); SDL_CondSignal(wdata->vsync_cond); SDL_UnlockMutex(wdata->vsync_cond_mutex); } int RPI_CreateWindow(_THIS, SDL_Window * window) { SDL_WindowData *wdata; SDL_VideoDisplay *display; SDL_DisplayData *displaydata; VC_RECT_T dst_rect; VC_RECT_T src_rect; VC_DISPMANX_ALPHA_T dispman_alpha; DISPMANX_UPDATE_HANDLE_T dispman_update; uint32_t layer = SDL_RPI_VIDEOLAYER; const char *env; /* Disable alpha, otherwise the app looks composed with whatever dispman is showing (X11, console,etc) */ dispman_alpha.flags = DISPMANX_FLAGS_ALPHA_FIXED_ALL_PIXELS; dispman_alpha.opacity = 0xFF; dispman_alpha.mask = 0; /* Allocate window internal data */ wdata = (SDL_WindowData *) SDL_calloc(1, sizeof(SDL_WindowData)); if (wdata == NULL) { return SDL_OutOfMemory(); } display = SDL_GetDisplayForWindow(window); displaydata = (SDL_DisplayData *) display->driverdata; /* Windows have one size for now */ window->w = display->desktop_mode.w; window->h = display->desktop_mode.h; /* OpenGL ES is the law here, buddy */ window->flags |= SDL_WINDOW_OPENGL; /* Create a dispman element and associate a window to it */ dst_rect.x = 0; dst_rect.y = 0; dst_rect.width = window->w; dst_rect.height = window->h; src_rect.x = 0; src_rect.y = 0; src_rect.width = window->w << 16; src_rect.height = window->h << 16; env = SDL_GetHint(SDL_HINT_RPI_VIDEO_LAYER); if (env) { layer = SDL_atoi(env); } dispman_update = vc_dispmanx_update_start( 0 ); wdata->dispman_window.element = vc_dispmanx_element_add (dispman_update, displaydata->dispman_display, layer /* layer */, &dst_rect, 0 /*src*/, &src_rect, DISPMANX_PROTECTION_NONE, &dispman_alpha /*alpha*/, 0 /*clamp*/, 0 /*transform*/); wdata->dispman_window.width = window->w; wdata->dispman_window.height = window->h; vc_dispmanx_update_submit_sync(dispman_update); if (!_this->egl_data) { if (SDL_GL_LoadLibrary(NULL) < 0) { return -1; } } wdata->egl_surface = SDL_EGL_CreateSurface(_this, (NativeWindowType) &wdata->dispman_window); if (wdata->egl_surface == EGL_NO_SURFACE) { return SDL_SetError("Could not create GLES window surface"); } /* Start generating vsync callbacks if necesary */ wdata->double_buffer = SDL_FALSE; if (SDL_GetHintBoolean(SDL_HINT_VIDEO_DOUBLE_BUFFER, SDL_FALSE)) { wdata->vsync_cond = SDL_CreateCond(); wdata->vsync_cond_mutex = SDL_CreateMutex(); wdata->double_buffer = SDL_TRUE; vc_dispmanx_vsync_callback(displaydata->dispman_display, RPI_vsync_callback, (void*)wdata); } /* Setup driver data for this window */ window->driverdata = wdata; /* One window, it always has focus */ SDL_SetMouseFocus(window); SDL_SetKeyboardFocus(window); /* Window has been successfully created */ return 0; } void RPI_DestroyWindow(_THIS, SDL_Window * window) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); SDL_DisplayData *displaydata = (SDL_DisplayData *) display->driverdata; if(data) { if (data->double_buffer) { /* Wait for vsync, and then stop vsync callbacks and destroy related stuff, if needed */ SDL_LockMutex(data->vsync_cond_mutex); SDL_CondWait(data->vsync_cond, data->vsync_cond_mutex); SDL_UnlockMutex(data->vsync_cond_mutex); vc_dispmanx_vsync_callback(displaydata->dispman_display, NULL, NULL); SDL_DestroyCond(data->vsync_cond); SDL_DestroyMutex(data->vsync_cond_mutex); } #if SDL_VIDEO_OPENGL_EGL if (data->egl_surface != EGL_NO_SURFACE) { SDL_EGL_DestroySurface(_this, data->egl_surface); } #endif SDL_free(data); window->driverdata = NULL; } } int RPI_CreateWindowFrom(_THIS, SDL_Window * window, const void *data) { return -1; } void RPI_SetWindowTitle(_THIS, SDL_Window * window) { } void RPI_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon) { } void RPI_SetWindowPosition(_THIS, SDL_Window * window) { } void RPI_SetWindowSize(_THIS, SDL_Window * window) { } void RPI_ShowWindow(_THIS, SDL_Window * window) { } void RPI_HideWindow(_THIS, SDL_Window * window) { } void RPI_RaiseWindow(_THIS, SDL_Window * window) { } void RPI_MaximizeWindow(_THIS, SDL_Window * window) { } void RPI_MinimizeWindow(_THIS, SDL_Window * window) { } void RPI_RestoreWindow(_THIS, SDL_Window * window) { } void RPI_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed) { } /*****************************************************************************/ /* SDL Window Manager function */ /*****************************************************************************/ #if 0 SDL_bool RPI_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info) { if (info->version.major <= SDL_MAJOR_VERSION) { return SDL_TRUE; } else { SDL_SetError("application not compiled with SDL %d.%d", SDL_MAJOR_VERSION, SDL_MINOR_VERSION); return SDL_FALSE; } /* Failed to get window manager information */ return SDL_FALSE; } #endif #endif /* SDL_VIDEO_DRIVER_RPI */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/raspberry/SDL_rpivideo.c
C
apache-2.0
13,433
/* 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_RPIVIDEO_H__ #define __SDL_RPIVIDEO_H__ #include "../../SDL_internal.h" #include "../SDL_sysvideo.h" #include <bcm_host.h> #include "GLES/gl.h" #include "EGL/egl.h" #include "EGL/eglext.h" typedef struct SDL_VideoData { uint32_t egl_refcount; /* OpenGL ES reference count */ } SDL_VideoData; typedef struct SDL_DisplayData { DISPMANX_DISPLAY_HANDLE_T dispman_display; } SDL_DisplayData; typedef struct SDL_WindowData { EGL_DISPMANX_WINDOW_T dispman_window; #if SDL_VIDEO_OPENGL_EGL EGLSurface egl_surface; #endif /* Vsync callback cond and mutex */ SDL_cond *vsync_cond; SDL_mutex *vsync_cond_mutex; SDL_bool double_buffer; } SDL_WindowData; #define SDL_RPI_VIDEOLAYER 10000 /* High enough so to occlude everything */ #define SDL_RPI_MOUSELAYER SDL_RPI_VIDEOLAYER + 1 /****************************************************************************/ /* SDL_VideoDevice functions declaration */ /****************************************************************************/ /* Display and window functions */ int RPI_VideoInit(_THIS); void RPI_VideoQuit(_THIS); void RPI_GetDisplayModes(_THIS, SDL_VideoDisplay * display); int RPI_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode); int RPI_CreateWindow(_THIS, SDL_Window * window); int RPI_CreateWindowFrom(_THIS, SDL_Window * window, const void *data); void RPI_SetWindowTitle(_THIS, SDL_Window * window); void RPI_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon); void RPI_SetWindowPosition(_THIS, SDL_Window * window); void RPI_SetWindowSize(_THIS, SDL_Window * window); void RPI_ShowWindow(_THIS, SDL_Window * window); void RPI_HideWindow(_THIS, SDL_Window * window); void RPI_RaiseWindow(_THIS, SDL_Window * window); void RPI_MaximizeWindow(_THIS, SDL_Window * window); void RPI_MinimizeWindow(_THIS, SDL_Window * window); void RPI_RestoreWindow(_THIS, SDL_Window * window); void RPI_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed); void RPI_DestroyWindow(_THIS, SDL_Window * window); /* Window manager function */ SDL_bool RPI_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info); /* OpenGL/OpenGL ES functions */ int RPI_GLES_LoadLibrary(_THIS, const char *path); void *RPI_GLES_GetProcAddress(_THIS, const char *proc); void RPI_GLES_UnloadLibrary(_THIS); SDL_GLContext RPI_GLES_CreateContext(_THIS, SDL_Window * window); int RPI_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context); int RPI_GLES_SetSwapInterval(_THIS, int interval); int RPI_GLES_GetSwapInterval(_THIS); int RPI_GLES_SwapWindow(_THIS, SDL_Window * window); void RPI_GLES_DeleteContext(_THIS, SDL_GLContext context); #endif /* __SDL_RPIVIDEO_H__ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/raspberry/SDL_rpivideo.h
C
apache-2.0
3,779
#!/usr/bin/perl -w # # A script to generate optimized C blitters for Simple DirectMedia Layer # http://www.libsdl.org/ use warnings; use strict; my %file; # The formats potentially supported by this script: # SDL_PIXELFORMAT_RGB332 # SDL_PIXELFORMAT_RGB444 # SDL_PIXELFORMAT_RGB555 # SDL_PIXELFORMAT_ARGB4444 # SDL_PIXELFORMAT_ARGB1555 # SDL_PIXELFORMAT_RGB565 # SDL_PIXELFORMAT_RGB24 # SDL_PIXELFORMAT_BGR24 # SDL_PIXELFORMAT_RGB888 # SDL_PIXELFORMAT_BGR888 # SDL_PIXELFORMAT_ARGB8888 # SDL_PIXELFORMAT_RGBA8888 # SDL_PIXELFORMAT_ABGR8888 # SDL_PIXELFORMAT_BGRA8888 # SDL_PIXELFORMAT_ARGB2101010 # The formats we're actually creating blitters for: my @src_formats = ( "RGB888", "BGR888", "ARGB8888", "RGBA8888", "ABGR8888", "BGRA8888", ); my @dst_formats = ( "RGB888", "BGR888", "ARGB8888", ); my %format_size = ( "RGB888" => 4, "BGR888" => 4, "ARGB8888" => 4, "RGBA8888" => 4, "ABGR8888" => 4, "BGRA8888" => 4, ); my %format_type = ( "RGB888" => "Uint32", "BGR888" => "Uint32", "ARGB8888" => "Uint32", "RGBA8888" => "Uint32", "ABGR8888" => "Uint32", "BGRA8888" => "Uint32", ); my %get_rgba_string_ignore_alpha = ( "RGB888" => "_R = (Uint8)(_pixel >> 16); _G = (Uint8)(_pixel >> 8); _B = (Uint8)_pixel;", "BGR888" => "_B = (Uint8)(_pixel >> 16); _G = (Uint8)(_pixel >> 8); _R = (Uint8)_pixel;", "ARGB8888" => "_R = (Uint8)(_pixel >> 16); _G = (Uint8)(_pixel >> 8); _B = (Uint8)_pixel;", "RGBA8888" => "_R = (Uint8)(_pixel >> 24); _G = (Uint8)(_pixel >> 16); _B = (Uint8)(_pixel >> 8);", "ABGR8888" => "_B = (Uint8)(_pixel >> 16); _G = (Uint8)(_pixel >> 8); _R = (Uint8)_pixel;", "BGRA8888" => "_B = (Uint8)(_pixel >> 24); _G = (Uint8)(_pixel >> 16); _R = (Uint8)(_pixel >> 8);", ); my %get_rgba_string = ( "RGB888" => $get_rgba_string_ignore_alpha{"RGB888"}, "BGR888" => $get_rgba_string_ignore_alpha{"BGR888"}, "ARGB8888" => $get_rgba_string_ignore_alpha{"ARGB8888"} . " _A = (Uint8)(_pixel >> 24);", "RGBA8888" => $get_rgba_string_ignore_alpha{"RGBA8888"} . " _A = (Uint8)_pixel;", "ABGR8888" => $get_rgba_string_ignore_alpha{"ABGR8888"} . " _A = (Uint8)(_pixel >> 24);", "BGRA8888" => $get_rgba_string_ignore_alpha{"BGRA8888"} . " _A = (Uint8)_pixel;", ); my %set_rgba_string = ( "RGB888" => "_pixel = (_R << 16) | (_G << 8) | _B;", "BGR888" => "_pixel = (_B << 16) | (_G << 8) | _R;", "ARGB8888" => "_pixel = (_A << 24) | (_R << 16) | (_G << 8) | _B;", "RGBA8888" => "_pixel = (_R << 24) | (_G << 16) | (_B << 8) | _A;", "ABGR8888" => "_pixel = (_A << 24) | (_B << 16) | (_G << 8) | _R;", "BGRA8888" => "_pixel = (_B << 24) | (_G << 16) | (_R << 8) | _A;", ); sub open_file { my $name = shift; open(FILE, ">$name.new") || die "Cant' open $name.new: $!"; print FILE <<__EOF__; /* DO NOT EDIT! This file is generated by sdlgenblit.pl */ /* 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_HAVE_BLIT_AUTO /* *INDENT-OFF* */ __EOF__ } sub close_file { my $name = shift; print FILE <<__EOF__; /* *INDENT-ON* */ #endif /* SDL_HAVE_BLIT_AUTO */ /* vi: set ts=4 sw=4 expandtab: */ __EOF__ close FILE; if ( ! -f $name || system("cmp -s $name $name.new") != 0 ) { rename("$name.new", "$name"); } else { unlink("$name.new"); } } sub output_copydefs { print FILE <<__EOF__; extern SDL_BlitFuncEntry SDL_GeneratedBlitFuncTable[]; __EOF__ } sub output_copyfuncname { my $prefix = shift; my $src = shift; my $dst = shift; my $modulate = shift; my $blend = shift; my $scale = shift; my $args = shift; my $suffix = shift; print FILE "$prefix SDL_Blit_${src}_${dst}"; if ( $modulate ) { print FILE "_Modulate"; } if ( $blend ) { print FILE "_Blend"; } if ( $scale ) { print FILE "_Scale"; } if ( $args ) { print FILE "(SDL_BlitInfo *info)"; } print FILE "$suffix"; } sub get_rgba { my $prefix = shift; my $format = shift; my $ignore_alpha = shift; my $string; if ($ignore_alpha) { $string = $get_rgba_string_ignore_alpha{$format}; } else { $string = $get_rgba_string{$format}; } $string =~ s/_/$prefix/g; if ( $prefix ne "" ) { print FILE <<__EOF__; ${prefix}pixel = *$prefix; __EOF__ } else { print FILE <<__EOF__; pixel = *src; __EOF__ } print FILE <<__EOF__; $string __EOF__ } sub set_rgba { my $prefix = shift; my $format = shift; my $string = $set_rgba_string{$format}; $string =~ s/_/$prefix/g; print FILE <<__EOF__; $string *dst = ${prefix}pixel; __EOF__ } sub output_copycore { my $src = shift; my $dst = shift; my $modulate = shift; my $blend = shift; my $is_modulateA_done = shift; my $A_is_const_FF = shift; my $s = ""; my $d = ""; # Nice and easy... if ( $src eq $dst && !$modulate && !$blend ) { print FILE <<__EOF__; *dst = *src; __EOF__ return; } my $dst_has_alpha = ($dst =~ /A/) ? 1 : 0; my $ignore_dst_alpha = !$dst_has_alpha && !$blend; if ( $blend ) { get_rgba("src", $src, $ignore_dst_alpha); get_rgba("dst", $dst, !$dst_has_alpha); $s = "src"; $d = "dst"; } else { get_rgba("", $src, $ignore_dst_alpha); } if ( $modulate ) { print FILE <<__EOF__; if (flags & SDL_COPY_MODULATE_COLOR) { ${s}R = (${s}R * modulateR) / 255; ${s}G = (${s}G * modulateG) / 255; ${s}B = (${s}B * modulateB) / 255; } __EOF__ if (!$ignore_dst_alpha && !$is_modulateA_done) { print FILE <<__EOF__; if (flags & SDL_COPY_MODULATE_ALPHA) { ${s}A = (${s}A * modulateA) / 255; } __EOF__ } } if ( $blend ) { if (!$A_is_const_FF) { print FILE <<__EOF__; if (flags & (SDL_COPY_BLEND|SDL_COPY_ADD)) { /* This goes away if we ever use premultiplied alpha */ if (${s}A < 255) { ${s}R = (${s}R * ${s}A) / 255; ${s}G = (${s}G * ${s}A) / 255; ${s}B = (${s}B * ${s}A) / 255; } } __EOF__ } print FILE <<__EOF__; switch (flags & (SDL_COPY_BLEND|SDL_COPY_ADD|SDL_COPY_MOD|SDL_COPY_MUL)) { case SDL_COPY_BLEND: __EOF__ if ($A_is_const_FF) { print FILE <<__EOF__; ${d}R = ${s}R; ${d}G = ${s}G; ${d}B = ${s}B; __EOF__ } else { print FILE <<__EOF__; ${d}R = ${s}R + ((255 - ${s}A) * ${d}R) / 255; ${d}G = ${s}G + ((255 - ${s}A) * ${d}G) / 255; ${d}B = ${s}B + ((255 - ${s}A) * ${d}B) / 255; __EOF__ } if ( $dst_has_alpha ) { if ($A_is_const_FF) { print FILE <<__EOF__; ${d}A = 0xFF; __EOF__ } else { print FILE <<__EOF__; ${d}A = ${s}A + ((255 - ${s}A) * ${d}A) / 255; __EOF__ } } print FILE <<__EOF__; break; case SDL_COPY_ADD: ${d}R = ${s}R + ${d}R; if (${d}R > 255) ${d}R = 255; ${d}G = ${s}G + ${d}G; if (${d}G > 255) ${d}G = 255; ${d}B = ${s}B + ${d}B; if (${d}B > 255) ${d}B = 255; break; case SDL_COPY_MOD: ${d}R = (${s}R * ${d}R) / 255; ${d}G = (${s}G * ${d}G) / 255; ${d}B = (${s}B * ${d}B) / 255; break; case SDL_COPY_MUL: __EOF__ if ($A_is_const_FF) { print FILE <<__EOF__; ${d}R = (${s}R * ${d}R) / 255; ${d}G = (${s}G * ${d}G) / 255; ${d}B = (${s}B * ${d}B) / 255; __EOF__ } else { print FILE <<__EOF__; ${d}R = ((${s}R * ${d}R) + (${d}R * (255 - ${s}A))) / 255; if (${d}R > 255) ${d}R = 255; ${d}G = ((${s}G * ${d}G) + (${d}G * (255 - ${s}A))) / 255; if (${d}G > 255) ${d}G = 255; ${d}B = ((${s}B * ${d}B) + (${d}B * (255 - ${s}A))) / 255; if (${d}B > 255) ${d}B = 255; __EOF__ } if ( $dst_has_alpha ) { if ($A_is_const_FF) { print FILE <<__EOF__; ${d}A = 0xFF; __EOF__ } else { print FILE <<__EOF__; ${d}A = ((${s}A * ${d}A) + (${d}A * (255 - ${s}A))) / 255; if (${d}A > 255) ${d}A = 255; __EOF__ } } print FILE <<__EOF__; break; } __EOF__ } if ( $blend ) { set_rgba("dst", $dst); } else { set_rgba("", $dst); } } sub output_copyfunc { my $src = shift; my $dst = shift; my $modulate = shift; my $blend = shift; my $scale = shift; my $dst_has_alpha = ($dst =~ /A/) ? 1 : 0; my $ignore_dst_alpha = !$dst_has_alpha && !$blend; my $src_has_alpha = ($src =~ /A/) ? 1 : 0; my $is_modulateA_done = 0; my $A_is_const_FF = 0; output_copyfuncname("static void", $src, $dst, $modulate, $blend, $scale, 1, "\n"); print FILE <<__EOF__; { __EOF__ if ( $modulate || $blend ) { print FILE <<__EOF__; const int flags = info->flags; __EOF__ } if ( $modulate ) { print FILE <<__EOF__; const Uint32 modulateR = info->r; const Uint32 modulateG = info->g; const Uint32 modulateB = info->b; __EOF__ if (!$ignore_dst_alpha) { print FILE <<__EOF__; const Uint32 modulateA = info->a; __EOF__ } } if ( $blend ) { print FILE <<__EOF__; Uint32 srcpixel; __EOF__ if (!$ignore_dst_alpha && !$src_has_alpha) { if ($modulate){ $is_modulateA_done = 1; print FILE <<__EOF__; const Uint32 srcA = (flags & SDL_COPY_MODULATE_ALPHA) ? modulateA : 0xFF; __EOF__ } else { $A_is_const_FF = 1; } print FILE <<__EOF__; Uint32 srcR, srcG, srcB; __EOF__ } else { print FILE <<__EOF__; Uint32 srcR, srcG, srcB, srcA; __EOF__ } print FILE <<__EOF__; Uint32 dstpixel; __EOF__ if ($dst_has_alpha) { print FILE <<__EOF__; Uint32 dstR, dstG, dstB, dstA; __EOF__ } else { print FILE <<__EOF__; Uint32 dstR, dstG, dstB; __EOF__ } } elsif ( $modulate || $src ne $dst ) { print FILE <<__EOF__; Uint32 pixel; __EOF__ if (!$ignore_dst_alpha && !$src_has_alpha) { if ($modulate){ $is_modulateA_done = 1; print FILE <<__EOF__; const Uint32 A = (flags & SDL_COPY_MODULATE_ALPHA) ? modulateA : 0xFF; __EOF__ } else { $A_is_const_FF = 1; print FILE <<__EOF__; const Uint32 A = 0xFF; __EOF__ } print FILE <<__EOF__; Uint32 R, G, B; __EOF__ } elsif (!$ignore_dst_alpha) { print FILE <<__EOF__; Uint32 R, G, B, A; __EOF__ } else { print FILE <<__EOF__; Uint32 R, G, B; __EOF__ } } if ( $scale ) { print FILE <<__EOF__; int srcy, srcx; int posy, posx; int incy, incx; __EOF__ print FILE <<__EOF__; srcy = 0; posy = 0; incy = (info->src_h << 16) / info->dst_h; incx = (info->src_w << 16) / info->dst_w; while (info->dst_h--) { $format_type{$src} *src = 0; $format_type{$dst} *dst = ($format_type{$dst} *)info->dst; int n = info->dst_w; srcx = -1; posx = 0x10000L; while (posy >= 0x10000L) { ++srcy; posy -= 0x10000L; } while (n--) { if (posx >= 0x10000L) { while (posx >= 0x10000L) { ++srcx; posx -= 0x10000L; } src = ($format_type{$src} *)(info->src + (srcy * info->src_pitch) + (srcx * $format_size{$src})); __EOF__ print FILE <<__EOF__; } __EOF__ output_copycore($src, $dst, $modulate, $blend, $is_modulateA_done, $A_is_const_FF); print FILE <<__EOF__; posx += incx; ++dst; } posy += incy; info->dst += info->dst_pitch; } __EOF__ } else { print FILE <<__EOF__; while (info->dst_h--) { $format_type{$src} *src = ($format_type{$src} *)info->src; $format_type{$dst} *dst = ($format_type{$dst} *)info->dst; int n = info->dst_w; while (n--) { __EOF__ output_copycore($src, $dst, $modulate, $blend, $is_modulateA_done, $A_is_const_FF); print FILE <<__EOF__; ++src; ++dst; } info->src += info->src_pitch; info->dst += info->dst_pitch; } __EOF__ } print FILE <<__EOF__; } __EOF__ } sub output_copyfunc_h { } sub output_copyinc { print FILE <<__EOF__; #include "SDL_video.h" #include "SDL_blit.h" #include "SDL_blit_auto.h" __EOF__ } sub output_copyfunctable { print FILE <<__EOF__; SDL_BlitFuncEntry SDL_GeneratedBlitFuncTable[] = { __EOF__ for (my $i = 0; $i <= $#src_formats; ++$i) { my $src = $src_formats[$i]; for (my $j = 0; $j <= $#dst_formats; ++$j) { my $dst = $dst_formats[$j]; for (my $modulate = 0; $modulate <= 1; ++$modulate) { for (my $blend = 0; $blend <= 1; ++$blend) { for (my $scale = 0; $scale <= 1; ++$scale) { if ( $modulate || $blend || $scale ) { print FILE " { SDL_PIXELFORMAT_$src, SDL_PIXELFORMAT_$dst, "; my $flags = ""; my $flag = ""; if ( $modulate ) { $flag = "SDL_COPY_MODULATE_COLOR | SDL_COPY_MODULATE_ALPHA"; if ( $flags eq "" ) { $flags = $flag; } else { $flags = "$flags | $flag"; } } if ( $blend ) { $flag = "SDL_COPY_BLEND | SDL_COPY_ADD | SDL_COPY_MOD | SDL_COPY_MUL"; if ( $flags eq "" ) { $flags = $flag; } else { $flags = "$flags | $flag"; } } if ( $scale ) { $flag = "SDL_COPY_NEAREST"; if ( $flags eq "" ) { $flags = $flag; } else { $flags = "$flags | $flag"; } } if ( $flags eq "" ) { $flags = "0"; } print FILE "($flags), SDL_CPU_ANY,"; output_copyfuncname("", $src_formats[$i], $dst_formats[$j], $modulate, $blend, $scale, 0, " },\n"); } } } } } } print FILE <<__EOF__; { 0, 0, 0, 0, NULL } }; __EOF__ } sub output_copyfunc_c { my $src = shift; my $dst = shift; for (my $modulate = 0; $modulate <= 1; ++$modulate) { for (my $blend = 0; $blend <= 1; ++$blend) { for (my $scale = 0; $scale <= 1; ++$scale) { if ( $modulate || $blend || $scale ) { output_copyfunc($src, $dst, $modulate, $blend, $scale); } } } } } open_file("SDL_blit_auto.h"); output_copydefs(); for (my $i = 0; $i <= $#src_formats; ++$i) { for (my $j = 0; $j <= $#dst_formats; ++$j) { output_copyfunc_h($src_formats[$i], $dst_formats[$j]); } } print FILE "\n"; close_file("SDL_blit_auto.h"); open_file("SDL_blit_auto.c"); output_copyinc(); for (my $i = 0; $i <= $#src_formats; ++$i) { for (my $j = 0; $j <= $#dst_formats; ++$j) { output_copyfunc_c($src_formats[$i], $dst_formats[$j]); } } output_copyfunctable(); close_file("SDL_blit_auto.c");
YifuLiu/AliOS-Things
components/SDL2/src/video/sdlgenblit.pl
Perl
apache-2.0
17,629
/* 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. */ #import <UIKit/UIKit.h> @interface SDLLaunchScreenController : UIViewController - (instancetype)init; - (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil; - (void)loadView; @end @interface SDLUIKitDelegate : NSObject<UIApplicationDelegate> + (id)sharedAppDelegate; + (NSString *)getAppDelegateClassName; - (void)hideLaunchScreen; /* This property is marked as optional, and is only intended to be used when * the app's UI is storyboard-based. SDL is not storyboard-based, however * several major third-party ad APIs (e.g. Google admob) incorrectly assume this * property always exists, and will crash if it doesn't. */ @property (nonatomic) UIWindow *window; @end /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitappdelegate.h
Objective-C
apache-2.0
1,690
/* 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_VIDEO_DRIVER_UIKIT #include "../SDL_sysvideo.h" #include "SDL_assert.h" #include "SDL_hints.h" #include "SDL_system.h" #include "SDL_main.h" #import "SDL_uikitappdelegate.h" #import "SDL_uikitmodes.h" #import "SDL_uikitwindow.h" #include "../../events/SDL_events_c.h" #ifdef main #undef main #endif static SDL_main_func forward_main; static int forward_argc; static char **forward_argv; static int exit_status; #if defined(SDL_MAIN_NEEDED) && !defined(IOS_DYLIB) /* SDL is being built as a static library, include main() */ int main(int argc, char *argv[]) { return SDL_UIKitRunApp(argc, argv, SDL_main); } #endif /* SDL_MAIN_NEEDED && !IOS_DYLIB */ int SDL_UIKitRunApp(int argc, char *argv[], SDL_main_func mainFunction) { int i; /* store arguments */ forward_main = mainFunction; forward_argc = argc; forward_argv = (char **)malloc((argc+1) * sizeof(char *)); for (i = 0; i < argc; i++) { forward_argv[i] = malloc( (strlen(argv[i])+1) * sizeof(char)); strcpy(forward_argv[i], argv[i]); } forward_argv[i] = NULL; /* Give over control to run loop, SDLUIKitDelegate will handle most things from here */ @autoreleasepool { UIApplicationMain(argc, argv, nil, [SDLUIKitDelegate getAppDelegateClassName]); } /* free the memory we used to hold copies of argc and argv */ for (i = 0; i < forward_argc; i++) { free(forward_argv[i]); } free(forward_argv); return exit_status; } static void SDLCALL SDL_IdleTimerDisabledChanged(void *userdata, const char *name, const char *oldValue, const char *hint) { BOOL disable = (hint && *hint != '0'); [UIApplication sharedApplication].idleTimerDisabled = disable; } #if !TARGET_OS_TV /* Load a launch image using the old UILaunchImageFile-era naming rules. */ static UIImage * SDL_LoadLaunchImageNamed(NSString *name, int screenh) { UIInterfaceOrientation curorient = [UIApplication sharedApplication].statusBarOrientation; UIUserInterfaceIdiom idiom = [UIDevice currentDevice].userInterfaceIdiom; UIImage *image = nil; if (idiom == UIUserInterfaceIdiomPhone && screenh == 568) { /* The image name for the iPhone 5 uses its height as a suffix. */ image = [UIImage imageNamed:[NSString stringWithFormat:@"%@-568h", name]]; } else if (idiom == UIUserInterfaceIdiomPad) { /* iPad apps can launch in any orientation. */ if (UIInterfaceOrientationIsLandscape(curorient)) { if (curorient == UIInterfaceOrientationLandscapeLeft) { image = [UIImage imageNamed:[NSString stringWithFormat:@"%@-LandscapeLeft", name]]; } else { image = [UIImage imageNamed:[NSString stringWithFormat:@"%@-LandscapeRight", name]]; } if (!image) { image = [UIImage imageNamed:[NSString stringWithFormat:@"%@-Landscape", name]]; } } else { if (curorient == UIInterfaceOrientationPortraitUpsideDown) { image = [UIImage imageNamed:[NSString stringWithFormat:@"%@-PortraitUpsideDown", name]]; } if (!image) { image = [UIImage imageNamed:[NSString stringWithFormat:@"%@-Portrait", name]]; } } } if (!image) { image = [UIImage imageNamed:name]; } return image; } #endif /* !TARGET_OS_TV */ @interface SDLLaunchScreenController () #if !TARGET_OS_TV - (NSUInteger)supportedInterfaceOrientations; #endif @end @implementation SDLLaunchScreenController - (instancetype)init { return [self initWithNibName:nil bundle:[NSBundle mainBundle]]; } - (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if (!(self = [super initWithNibName:nil bundle:nil])) { return nil; } NSString *screenname = nibNameOrNil; NSBundle *bundle = nibBundleOrNil; BOOL atleastiOS8 = UIKit_IsSystemVersionAtLeast(8.0); /* Launch screens were added in iOS 8. Otherwise we use launch images. */ if (screenname && atleastiOS8) { @try { self.view = [bundle loadNibNamed:screenname owner:self options:nil][0]; } @catch (NSException *exception) { /* If a launch screen name is specified but it fails to load, iOS * displays a blank screen rather than falling back to an image. */ return nil; } } if (!self.view) { NSArray *launchimages = [bundle objectForInfoDictionaryKey:@"UILaunchImages"]; NSString *imagename = nil; UIImage *image = nil; int screenw = (int)([UIScreen mainScreen].bounds.size.width + 0.5); int screenh = (int)([UIScreen mainScreen].bounds.size.height + 0.5); #if !TARGET_OS_TV UIInterfaceOrientation curorient = [UIApplication sharedApplication].statusBarOrientation; /* We always want portrait-oriented size, to match UILaunchImageSize. */ if (screenw > screenh) { int width = screenw; screenw = screenh; screenh = width; } #endif /* Xcode 5 introduced a dictionary of launch images in Info.plist. */ if (launchimages) { for (NSDictionary *dict in launchimages) { NSString *minversion = dict[@"UILaunchImageMinimumOSVersion"]; NSString *sizestring = dict[@"UILaunchImageSize"]; /* Ignore this image if the current version is too low. */ if (minversion && !UIKit_IsSystemVersionAtLeast(minversion.doubleValue)) { continue; } /* Ignore this image if the size doesn't match. */ if (sizestring) { CGSize size = CGSizeFromString(sizestring); if ((int)(size.width + 0.5) != screenw || (int)(size.height + 0.5) != screenh) { continue; } } #if !TARGET_OS_TV UIInterfaceOrientationMask orientmask = UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown; NSString *orientstring = dict[@"UILaunchImageOrientation"]; if (orientstring) { if ([orientstring isEqualToString:@"PortraitUpsideDown"]) { orientmask = UIInterfaceOrientationMaskPortraitUpsideDown; } else if ([orientstring isEqualToString:@"Landscape"]) { orientmask = UIInterfaceOrientationMaskLandscape; } else if ([orientstring isEqualToString:@"LandscapeLeft"]) { orientmask = UIInterfaceOrientationMaskLandscapeLeft; } else if ([orientstring isEqualToString:@"LandscapeRight"]) { orientmask = UIInterfaceOrientationMaskLandscapeRight; } } /* Ignore this image if the orientation doesn't match. */ if ((orientmask & (1 << curorient)) == 0) { continue; } #endif imagename = dict[@"UILaunchImageName"]; } if (imagename) { image = [UIImage imageNamed:imagename]; } } #if !TARGET_OS_TV else { imagename = [bundle objectForInfoDictionaryKey:@"UILaunchImageFile"]; if (imagename) { image = SDL_LoadLaunchImageNamed(imagename, screenh); } if (!image) { image = SDL_LoadLaunchImageNamed(@"Default", screenh); } } #endif if (image) { UIImageView *view = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds]; UIImageOrientation imageorient = UIImageOrientationUp; #if !TARGET_OS_TV /* Bugs observed / workaround tested in iOS 8.3, 7.1, and 6.1. */ if (UIInterfaceOrientationIsLandscape(curorient)) { if (atleastiOS8 && image.size.width < image.size.height) { /* On iOS 8, portrait launch images displayed in forced- * landscape mode (e.g. a standard Default.png on an iPhone * when Info.plist only supports landscape orientations) need * to be rotated to display in the expected orientation. */ if (curorient == UIInterfaceOrientationLandscapeLeft) { imageorient = UIImageOrientationRight; } else if (curorient == UIInterfaceOrientationLandscapeRight) { imageorient = UIImageOrientationLeft; } } else if (!atleastiOS8 && image.size.width > image.size.height) { /* On iOS 7 and below, landscape launch images displayed in * landscape mode (e.g. landscape iPad launch images) need * to be rotated to display in the expected orientation. */ if (curorient == UIInterfaceOrientationLandscapeLeft) { imageorient = UIImageOrientationLeft; } else if (curorient == UIInterfaceOrientationLandscapeRight) { imageorient = UIImageOrientationRight; } } } #endif /* Create the properly oriented image. */ view.image = [[UIImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:imageorient]; self.view = view; } } return self; } - (void)loadView { /* Do nothing. */ } #if !TARGET_OS_TV - (BOOL)shouldAutorotate { /* If YES, the launch image will be incorrectly rotated in some cases. */ return NO; } - (NSUInteger)supportedInterfaceOrientations { /* We keep the supported orientations unrestricted to avoid the case where * there are no common orientations between the ones set in Info.plist and * the ones set here (it will cause an exception in that case.) */ return UIInterfaceOrientationMaskAll; } #endif /* !TARGET_OS_TV */ @end @implementation SDLUIKitDelegate { UIWindow *launchWindow; } /* convenience method */ + (id)sharedAppDelegate { /* the delegate is set in UIApplicationMain(), which is guaranteed to be * called before this method */ return [UIApplication sharedApplication].delegate; } + (NSString *)getAppDelegateClassName { /* subclassing notice: when you subclass this appdelegate, make sure to add * a category to override this method and return the actual name of the * delegate */ return @"SDLUIKitDelegate"; } - (void)hideLaunchScreen { UIWindow *window = launchWindow; if (!window || window.hidden) { return; } launchWindow = nil; /* Do a nice animated fade-out (roughly matches the real launch behavior.) */ [UIView animateWithDuration:0.2 animations:^{ window.alpha = 0.0; } completion:^(BOOL finished) { window.hidden = YES; UIKit_ForceUpdateHomeIndicator(); /* Wait for launch screen to hide so settings are applied to the actual view controller. */ }]; } - (void)postFinishLaunch { /* Hide the launch screen the next time the run loop is run. SDL apps will * have a chance to load resources while the launch screen is still up. */ [self performSelector:@selector(hideLaunchScreen) withObject:nil afterDelay:0.0]; /* run the user's application, passing argc and argv */ SDL_iPhoneSetEventPump(SDL_TRUE); exit_status = forward_main(forward_argc, forward_argv); SDL_iPhoneSetEventPump(SDL_FALSE); if (launchWindow) { launchWindow.hidden = YES; launchWindow = nil; } /* exit, passing the return status from the user's application */ /* We don't actually exit to support applications that do setup in their * main function and then allow the Cocoa event loop to run. */ /* exit(exit_status); */ } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSBundle *bundle = [NSBundle mainBundle]; #if SDL_IPHONE_LAUNCHSCREEN /* The normal launch screen is displayed until didFinishLaunching returns, * but SDL_main is called after that happens and there may be a noticeable * delay between the start of SDL_main and when the first real frame is * displayed (e.g. if resources are loaded before SDL_GL_SwapWindow is * called), so we show the launch screen programmatically until the first * time events are pumped. */ UIViewController *vc = nil; NSString *screenname = nil; /* tvOS only uses a plain launch image. */ #if !TARGET_OS_TV screenname = [bundle objectForInfoDictionaryKey:@"UILaunchStoryboardName"]; if (screenname && UIKit_IsSystemVersionAtLeast(8.0)) { @try { /* The launch storyboard is actually a nib in some older versions of * Xcode. We'll try to load it as a storyboard first, as it's more * modern. */ UIStoryboard *storyboard = [UIStoryboard storyboardWithName:screenname bundle:bundle]; vc = [storyboard instantiateInitialViewController]; } @catch (NSException *exception) { /* Do nothing (there's more code to execute below). */ } } #endif if (vc == nil) { vc = [[SDLLaunchScreenController alloc] initWithNibName:screenname bundle:bundle]; } if (vc.view) { launchWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; /* We don't want the launch window immediately hidden when a real SDL * window is shown - we fade it out ourselves when we're ready. */ launchWindow.windowLevel = UIWindowLevelNormal + 1.0; /* Show the window but don't make it key. Events should always go to * other windows when possible. */ launchWindow.hidden = NO; launchWindow.rootViewController = vc; } #endif /* Set working directory to resource path */ [[NSFileManager defaultManager] changeCurrentDirectoryPath:[bundle resourcePath]]; /* register a callback for the idletimer hint */ SDL_AddHintCallback(SDL_HINT_IDLE_TIMER_DISABLED, SDL_IdleTimerDisabledChanged, NULL); SDL_SetMainReady(); [self performSelector:@selector(postFinishLaunch) withObject:nil afterDelay:0.0]; return YES; } - (UIWindow *)window { SDL_VideoDevice *_this = SDL_GetVideoDevice(); if (_this) { SDL_Window *window = NULL; for (window = _this->windows; window != NULL; window = window->next) { SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; if (data != nil) { return data.uiwindow; } } } return nil; } - (void)setWindow:(UIWindow *)window { /* Do nothing. */ } #if !TARGET_OS_TV - (void)application:(UIApplication *)application didChangeStatusBarOrientation:(UIInterfaceOrientation)oldStatusBarOrientation { SDL_OnApplicationDidChangeStatusBarOrientation(); } #endif - (void)applicationWillTerminate:(UIApplication *)application { SDL_OnApplicationWillTerminate(); } - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { SDL_OnApplicationDidReceiveMemoryWarning(); } - (void)applicationWillResignActive:(UIApplication*)application { SDL_OnApplicationWillResignActive(); } - (void)applicationDidEnterBackground:(UIApplication*)application { SDL_OnApplicationDidEnterBackground(); } - (void)applicationWillEnterForeground:(UIApplication*)application { SDL_OnApplicationWillEnterForeground(); } - (void)applicationDidBecomeActive:(UIApplication*)application { SDL_OnApplicationDidBecomeActive(); } - (void)sendDropFileForURL:(NSURL *)url { NSURL *fileURL = url.filePathURL; if (fileURL != nil) { SDL_SendDropFile(NULL, fileURL.path.UTF8String); } else { SDL_SendDropFile(NULL, url.absoluteString.UTF8String); } SDL_SendDropComplete(NULL); } #if TARGET_OS_TV || (defined(__IPHONE_9_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_9_0) - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options { /* TODO: Handle options */ [self sendDropFileForURL:url]; return YES; } #else - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { [self sendDropFileForURL:url]; return YES; } #endif @end #endif /* SDL_VIDEO_DRIVER_UIKIT */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitappdelegate.m
Objective-C
apache-2.0
17,701
/* 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_uikitclipboard_h_ #define SDL_uikitclipboard_h_ #include "../SDL_sysvideo.h" extern int UIKit_SetClipboardText(_THIS, const char *text); extern char *UIKit_GetClipboardText(_THIS); extern SDL_bool UIKit_HasClipboardText(_THIS); extern void UIKit_InitClipboard(_THIS); extern void UIKit_QuitClipboard(_THIS); #endif /* SDL_uikitclipboard_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitclipboard.h
C
apache-2.0
1,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_VIDEO_DRIVER_UIKIT #include "SDL_uikitvideo.h" #include "../../events/SDL_clipboardevents_c.h" #import <UIKit/UIPasteboard.h> int UIKit_SetClipboardText(_THIS, const char *text) { #if TARGET_OS_TV return SDL_SetError("The clipboard is not available on tvOS"); #else @autoreleasepool { [UIPasteboard generalPasteboard].string = @(text); return 0; } #endif } char * UIKit_GetClipboardText(_THIS) { #if TARGET_OS_TV return SDL_strdup(""); // Unsupported. #else @autoreleasepool { UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; NSString *string = pasteboard.string; if (string != nil) { return SDL_strdup(string.UTF8String); } else { return SDL_strdup(""); } } #endif } SDL_bool UIKit_HasClipboardText(_THIS) { @autoreleasepool { #if !TARGET_OS_TV if ([UIPasteboard generalPasteboard].string != nil) { return SDL_TRUE; } #endif return SDL_FALSE; } } void UIKit_InitClipboard(_THIS) { #if !TARGET_OS_TV @autoreleasepool { SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata; NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; id observer = [center addObserverForName:UIPasteboardChangedNotification object:nil queue:nil usingBlock:^(NSNotification *note) { SDL_SendClipboardUpdate(); }]; data.pasteboardObserver = observer; } #endif } void UIKit_QuitClipboard(_THIS) { @autoreleasepool { SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata; if (data.pasteboardObserver != nil) { [[NSNotificationCenter defaultCenter] removeObserver:data.pasteboardObserver]; } data.pasteboardObserver = nil; } } #endif /* SDL_VIDEO_DRIVER_UIKIT */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitclipboard.m
Objective-C
apache-2.0
3,055
/* 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_uikitevents_h_ #define SDL_uikitevents_h_ #include "../SDL_sysvideo.h" extern void UIKit_PumpEvents(_THIS); #endif /* SDL_uikitevents_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitevents.h
C
apache-2.0
1,130
/* 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_VIDEO_DRIVER_UIKIT #include "../../events/SDL_events_c.h" #include "SDL_uikitvideo.h" #include "SDL_uikitevents.h" #include "SDL_uikitopengles.h" #import <Foundation/Foundation.h> static BOOL UIKit_EventPumpEnabled = YES; void SDL_iPhoneSetEventPump(SDL_bool enabled) { UIKit_EventPumpEnabled = enabled; } void UIKit_PumpEvents(_THIS) { if (!UIKit_EventPumpEnabled) { return; } /* Let the run loop run for a short amount of time: long enough for touch events to get processed (which is important to get certain elements of Game Center's GKLeaderboardViewController to respond to touch input), but not long enough to introduce a significant delay in the rest of the app. */ const CFTimeInterval seconds = 0.000002; /* Pump most event types. */ SInt32 result; do { result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, seconds, TRUE); } while (result == kCFRunLoopRunHandledSource); /* Make sure UIScrollView objects scroll properly. */ do { result = CFRunLoopRunInMode((CFStringRef)UITrackingRunLoopMode, seconds, TRUE); } while(result == kCFRunLoopRunHandledSource); /* See the comment in the function definition. */ #if SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 UIKit_GL_RestoreCurrentContext(); #endif } #endif /* SDL_VIDEO_DRIVER_UIKIT */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitevents.m
Objective-C
apache-2.0
2,380
/* 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_VIDEO_DRIVER_UIKIT extern SDL_bool UIKit_ShowingMessageBox(void); extern int UIKit_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid); #endif /* SDL_VIDEO_DRIVER_UIKIT */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitmessagebox.h
C
apache-2.0
1,211
/* 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_VIDEO_DRIVER_UIKIT #include "SDL.h" #include "SDL_uikitvideo.h" #include "SDL_uikitwindow.h" /* Display a UIKit message box */ static SDL_bool s_showingMessageBox = SDL_FALSE; SDL_bool UIKit_ShowingMessageBox(void) { return s_showingMessageBox; } static void UIKit_WaitUntilMessageBoxClosed(const SDL_MessageBoxData *messageboxdata, int *clickedindex) { *clickedindex = messageboxdata->numbuttons; @autoreleasepool { /* Run the main event loop until the alert has finished */ /* Note that this needs to be done on the main thread */ s_showingMessageBox = SDL_TRUE; while ((*clickedindex) == messageboxdata->numbuttons) { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } s_showingMessageBox = SDL_FALSE; } } static BOOL UIKit_ShowMessageBoxAlertController(const SDL_MessageBoxData *messageboxdata, int *buttonid) { int i; int __block clickedindex = messageboxdata->numbuttons; UIWindow *window = nil; UIWindow *alertwindow = nil; if (![UIAlertController class]) { return NO; } UIAlertController *alert; alert = [UIAlertController alertControllerWithTitle:@(messageboxdata->title) message:@(messageboxdata->message) preferredStyle:UIAlertControllerStyleAlert]; for (i = 0; i < messageboxdata->numbuttons; i++) { UIAlertAction *action; UIAlertActionStyle style = UIAlertActionStyleDefault; const SDL_MessageBoxButtonData *sdlButton; if (messageboxdata->flags & SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT) { sdlButton = &messageboxdata->buttons[messageboxdata->numbuttons - 1 - i]; } else { sdlButton = &messageboxdata->buttons[i]; } if (sdlButton->flags & SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT) { style = UIAlertActionStyleCancel; } action = [UIAlertAction actionWithTitle:@(sdlButton->text) style:style handler:^(UIAlertAction *action) { clickedindex = (int)(sdlButton - messageboxdata->buttons); }]; [alert addAction:action]; if (sdlButton->flags & SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT) { alert.preferredAction = action; } } if (messageboxdata->window) { SDL_WindowData *data = (__bridge SDL_WindowData *) messageboxdata->window->driverdata; window = data.uiwindow; } if (window == nil || window.rootViewController == nil) { alertwindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; alertwindow.rootViewController = [UIViewController new]; alertwindow.windowLevel = UIWindowLevelAlert; window = alertwindow; [alertwindow makeKeyAndVisible]; } [window.rootViewController presentViewController:alert animated:YES completion:nil]; UIKit_WaitUntilMessageBoxClosed(messageboxdata, &clickedindex); if (alertwindow) { alertwindow.hidden = YES; } UIKit_ForceUpdateHomeIndicator(); *buttonid = messageboxdata->buttons[clickedindex].buttonid; return YES; } /* UIAlertView is deprecated in iOS 8+ in favor of UIAlertController. */ #if __IPHONE_OS_VERSION_MIN_REQUIRED < 80000 @interface SDLAlertViewDelegate : NSObject <UIAlertViewDelegate> @property (nonatomic, assign) int *clickedIndex; @end @implementation SDLAlertViewDelegate - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { if (_clickedIndex != NULL) { *_clickedIndex = (int) buttonIndex; } } @end #endif /* __IPHONE_OS_VERSION_MIN_REQUIRED < 80000 */ static BOOL UIKit_ShowMessageBoxAlertView(const SDL_MessageBoxData *messageboxdata, int *buttonid) { /* UIAlertView is deprecated in iOS 8+ in favor of UIAlertController. */ #if __IPHONE_OS_VERSION_MIN_REQUIRED < 80000 int i; int clickedindex = messageboxdata->numbuttons; UIAlertView *alert = [[UIAlertView alloc] init]; SDLAlertViewDelegate *delegate = [[SDLAlertViewDelegate alloc] init]; alert.delegate = delegate; alert.title = @(messageboxdata->title); alert.message = @(messageboxdata->message); for (i = 0; i < messageboxdata->numbuttons; i++) { const SDL_MessageBoxButtonData *sdlButton; if (messageboxdata->flags & SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT) { sdlButton = &messageboxdata->buttons[messageboxdata->numbuttons - 1 - i]; } else { sdlButton = &messageboxdata->buttons[i]; } [alert addButtonWithTitle:@(sdlButton->text)]; } delegate.clickedIndex = &clickedindex; [alert show]; UIKit_WaitUntilMessageBoxClosed(messageboxdata, &clickedindex); alert.delegate = nil; if (messageboxdata->flags & SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT) { clickedindex = messageboxdata->numbuttons - 1 - clickedindex; } *buttonid = messageboxdata->buttons[clickedindex].buttonid; return YES; #else return NO; #endif /* __IPHONE_OS_VERSION_MIN_REQUIRED < 80000 */ } int UIKit_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid) { BOOL success = NO; @autoreleasepool { success = UIKit_ShowMessageBoxAlertController(messageboxdata, buttonid); if (!success) { success = UIKit_ShowMessageBoxAlertView(messageboxdata, buttonid); } } if (!success) { return SDL_SetError("Could not show message box."); } return 0; } #endif /* SDL_VIDEO_DRIVER_UIKIT */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitmessagebox.m
Objective-C
apache-2.0
6,758
/* 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. */ /* * @author Mark Callow, www.edgewise-consulting.com. * * Thanks to Alex Szpakowski, @slime73 on GitHub, for his gist showing * how to add a CAMetalLayer backed view. */ #ifndef SDL_uikitmetalview_h_ #define SDL_uikitmetalview_h_ #include "../SDL_sysvideo.h" #include "SDL_uikitwindow.h" #if SDL_VIDEO_DRIVER_UIKIT && (SDL_VIDEO_VULKAN || SDL_VIDEO_METAL) #import <UIKit/UIKit.h> #import <Metal/Metal.h> #import <QuartzCore/CAMetalLayer.h> #define METALVIEW_TAG 255 @interface SDL_uikitmetalview : SDL_uikitview - (instancetype)initWithFrame:(CGRect)frame scale:(CGFloat)scale; @end SDL_MetalView UIKit_Metal_CreateView(_THIS, SDL_Window * window); void UIKit_Metal_DestroyView(_THIS, SDL_MetalView view); void *UIKit_Metal_GetLayer(_THIS, SDL_MetalView view); void UIKit_Metal_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h); #endif /* SDL_VIDEO_DRIVER_UIKIT && (SDL_VIDEO_VULKAN || SDL_VIDEO_METAL) */ #endif /* SDL_uikitmetalview_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitmetalview.h
Objective-C
apache-2.0
1,947
/* 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. */ /* * @author Mark Callow, www.edgewise-consulting.com. * * Thanks to Alex Szpakowski, @slime73 on GitHub, for his gist showing * how to add a CAMetalLayer backed view. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_UIKIT && (SDL_VIDEO_VULKAN || SDL_VIDEO_METAL) #import "../SDL_sysvideo.h" #import "SDL_uikitwindow.h" #import "SDL_uikitmetalview.h" #include "SDL_assert.h" @implementation SDL_uikitmetalview /* Returns a Metal-compatible layer. */ + (Class)layerClass { return [CAMetalLayer class]; } - (instancetype)initWithFrame:(CGRect)frame scale:(CGFloat)scale { if ((self = [super initWithFrame:frame])) { self.tag = METALVIEW_TAG; self.layer.contentsScale = scale; [self updateDrawableSize]; } return self; } /* Set the size of the metal drawables when the view is resized. */ - (void)layoutSubviews { [super layoutSubviews]; [self updateDrawableSize]; } - (void)updateDrawableSize { CGSize size = self.bounds.size; size.width *= self.layer.contentsScale; size.height *= self.layer.contentsScale; ((CAMetalLayer *)self.layer).drawableSize = size; } @end SDL_MetalView UIKit_Metal_CreateView(_THIS, SDL_Window * window) { @autoreleasepool { SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; CGFloat scale = 1.0; SDL_uikitmetalview *metalview; if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) { /* Set the scale to the natural scale factor of the screen - then * the backing dimensions of the Metal view will match the pixel * dimensions of the screen rather than the dimensions in points * yielding high resolution on retine displays. */ if ([data.uiwindow.screen respondsToSelector:@selector(nativeScale)]) { scale = data.uiwindow.screen.nativeScale; } else { scale = data.uiwindow.screen.scale; } } metalview = [[SDL_uikitmetalview alloc] initWithFrame:data.uiwindow.bounds scale:scale]; [metalview setSDLWindow:window]; return (void*)CFBridgingRetain(metalview); }} void UIKit_Metal_DestroyView(_THIS, SDL_MetalView view) { @autoreleasepool { SDL_uikitmetalview *metalview = CFBridgingRelease(view); if ([metalview isKindOfClass:[SDL_uikitmetalview class]]) { [metalview setSDLWindow:NULL]; } }} void * UIKit_Metal_GetLayer(_THIS, SDL_MetalView view) { @autoreleasepool { SDL_uikitview *uiview = (__bridge SDL_uikitview *)view; return (__bridge void *)uiview.layer; }} void UIKit_Metal_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h) { @autoreleasepool { SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; SDL_uikitview *view = (SDL_uikitview*)data.uiwindow.rootViewController.view; SDL_uikitmetalview* metalview = [view viewWithTag:METALVIEW_TAG]; if (metalview) { CAMetalLayer *layer = (CAMetalLayer*)metalview.layer; assert(layer != NULL); if (w) { *w = layer.drawableSize.width; } if (h) { *h = layer.drawableSize.height; } } else { SDL_GetWindowSize(window, w, h); } } } #endif /* SDL_VIDEO_DRIVER_UIKIT && (SDL_VIDEO_VULKAN || SDL_VIDEO_METAL) */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitmetalview.m
Objective-C
apache-2.0
4,327
/* 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_uikitmodes_h_ #define SDL_uikitmodes_h_ #include "SDL_uikitvideo.h" @interface SDL_DisplayData : NSObject - (instancetype)initWithScreen:(UIScreen*)screen; @property (nonatomic, strong) UIScreen *uiscreen; @property (nonatomic) float screenDPI; @end @interface SDL_DisplayModeData : NSObject @property (nonatomic, strong) UIScreenMode *uiscreenmode; @end extern SDL_bool UIKit_IsDisplayLandscape(UIScreen *uiscreen); extern int UIKit_InitModes(_THIS); extern void UIKit_GetDisplayModes(_THIS, SDL_VideoDisplay * display); extern int UIKit_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi, float * hdpi, float * vdpi); extern int UIKit_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode); extern void UIKit_QuitModes(_THIS); extern int UIKit_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect); #endif /* SDL_uikitmodes_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitmodes.h
Objective-C
apache-2.0
1,914
/* 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_VIDEO_DRIVER_UIKIT #include "SDL_assert.h" #include "SDL_system.h" #include "SDL_uikitmodes.h" #include "../../events/SDL_events_c.h" #import <sys/utsname.h> @implementation SDL_DisplayData - (instancetype)initWithScreen:(UIScreen*)screen { if (self = [super init]) { self.uiscreen = screen; /* * A well up to date list of device info can be found here: * https://github.com/lmirosevic/GBDeviceInfo/blob/master/GBDeviceInfo/GBDeviceInfo_iOS.m */ NSDictionary* devices = @{ @"iPhone1,1": @163, @"iPhone1,2": @163, @"iPhone2,1": @163, @"iPhone3,1": @326, @"iPhone3,2": @326, @"iPhone3,3": @326, @"iPhone4,1": @326, @"iPhone5,1": @326, @"iPhone5,2": @326, @"iPhone5,3": @326, @"iPhone5,4": @326, @"iPhone6,1": @326, @"iPhone6,2": @326, @"iPhone7,1": @401, @"iPhone7,2": @326, @"iPhone8,1": @326, @"iPhone8,2": @401, @"iPhone8,4": @326, @"iPhone9,1": @326, @"iPhone9,2": @401, @"iPhone9,3": @326, @"iPhone9,4": @401, @"iPhone10,1": @326, @"iPhone10,2": @401, @"iPhone10,3": @458, @"iPhone10,4": @326, @"iPhone10,5": @401, @"iPhone10,6": @458, @"iPhone11,2": @458, @"iPhone11,4": @458, @"iPhone11,6": @458, @"iPhone11,8": @326, @"iPhone12,1": @326, @"iPhone12,3": @458, @"iPhone12,5": @458, @"iPad1,1": @132, @"iPad2,1": @132, @"iPad2,2": @132, @"iPad2,3": @132, @"iPad2,4": @132, @"iPad2,5": @163, @"iPad2,6": @163, @"iPad2,7": @163, @"iPad3,1": @264, @"iPad3,2": @264, @"iPad3,3": @264, @"iPad3,4": @264, @"iPad3,5": @264, @"iPad3,6": @264, @"iPad4,1": @264, @"iPad4,2": @264, @"iPad4,3": @264, @"iPad4,4": @326, @"iPad4,5": @326, @"iPad4,6": @326, @"iPad4,7": @326, @"iPad4,8": @326, @"iPad4,9": @326, @"iPad5,1": @326, @"iPad5,2": @326, @"iPad5,3": @264, @"iPad5,4": @264, @"iPad6,3": @264, @"iPad6,4": @264, @"iPad6,7": @264, @"iPad6,8": @264, @"iPad6,11": @264, @"iPad6,12": @264, @"iPad7,1": @264, @"iPad7,2": @264, @"iPad7,3": @264, @"iPad7,4": @264, @"iPad7,5": @264, @"iPad7,6": @264, @"iPad7,11": @264, @"iPad7,12": @264, @"iPad8,1": @264, @"iPad8,2": @264, @"iPad8,3": @264, @"iPad8,4": @264, @"iPad8,5": @264, @"iPad8,6": @264, @"iPad8,7": @264, @"iPad8,8": @264, @"iPad11,1": @326, @"iPad11,2": @326, @"iPad11,3": @326, @"iPad11,4": @326, @"iPod1,1": @163, @"iPod2,1": @163, @"iPod3,1": @163, @"iPod4,1": @326, @"iPod5,1": @326, @"iPod7,1": @326, @"iPod9,1": @326, }; struct utsname systemInfo; uname(&systemInfo); NSString* deviceName = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding]; id foundDPI = devices[deviceName]; if (foundDPI) { self.screenDPI = (float)[foundDPI integerValue]; } else { /* * Estimate the DPI based on the screen scale multiplied by the base DPI for the device * type (e.g. based on iPhone 1 and iPad 1) */ #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000 float scale = (float)screen.nativeScale; #else float scale = (float)screen.scale; #endif float defaultDPI; if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { defaultDPI = 132.0f; } else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { defaultDPI = 163.0f; } else { defaultDPI = 160.0f; } self.screenDPI = scale * defaultDPI; } } return self; } @synthesize uiscreen; @synthesize screenDPI; @end @implementation SDL_DisplayModeData @synthesize uiscreenmode; @end static int UIKit_AllocateDisplayModeData(SDL_DisplayMode * mode, UIScreenMode * uiscreenmode) { SDL_DisplayModeData *data = nil; if (uiscreenmode != nil) { /* Allocate the display mode data */ data = [[SDL_DisplayModeData alloc] init]; if (!data) { return SDL_OutOfMemory(); } data.uiscreenmode = uiscreenmode; } mode->driverdata = (void *) CFBridgingRetain(data); return 0; } static void UIKit_FreeDisplayModeData(SDL_DisplayMode * mode) { if (mode->driverdata != NULL) { CFRelease(mode->driverdata); mode->driverdata = NULL; } } static NSUInteger UIKit_GetDisplayModeRefreshRate(UIScreen *uiscreen) { #ifdef __IPHONE_10_3 if ([uiscreen respondsToSelector:@selector(maximumFramesPerSecond)]) { return uiscreen.maximumFramesPerSecond; } #endif return 0; } static int UIKit_AddSingleDisplayMode(SDL_VideoDisplay * display, int w, int h, UIScreen * uiscreen, UIScreenMode * uiscreenmode) { SDL_DisplayMode mode; SDL_zero(mode); if (UIKit_AllocateDisplayModeData(&mode, uiscreenmode) < 0) { return -1; } mode.format = SDL_PIXELFORMAT_ABGR8888; mode.refresh_rate = (int) UIKit_GetDisplayModeRefreshRate(uiscreen); mode.w = w; mode.h = h; if (SDL_AddDisplayMode(display, &mode)) { return 0; } else { UIKit_FreeDisplayModeData(&mode); return -1; } } static int UIKit_AddDisplayMode(SDL_VideoDisplay * display, int w, int h, UIScreen * uiscreen, UIScreenMode * uiscreenmode, SDL_bool addRotation) { if (UIKit_AddSingleDisplayMode(display, w, h, uiscreen, uiscreenmode) < 0) { return -1; } if (addRotation) { /* Add the rotated version */ if (UIKit_AddSingleDisplayMode(display, h, w, uiscreen, uiscreenmode) < 0) { return -1; } } return 0; } static int UIKit_AddDisplay(UIScreen *uiscreen) { UIScreenMode *uiscreenmode = uiscreen.currentMode; CGSize size = uiscreen.bounds.size; SDL_VideoDisplay display; SDL_DisplayMode mode; SDL_zero(mode); /* Make sure the width/height are oriented correctly */ if (UIKit_IsDisplayLandscape(uiscreen) != (size.width > size.height)) { CGFloat height = size.width; size.width = size.height; size.height = height; } mode.format = SDL_PIXELFORMAT_ABGR8888; mode.refresh_rate = (int) UIKit_GetDisplayModeRefreshRate(uiscreen); mode.w = (int) size.width; mode.h = (int) size.height; if (UIKit_AllocateDisplayModeData(&mode, uiscreenmode) < 0) { return -1; } SDL_zero(display); display.desktop_mode = mode; display.current_mode = mode; /* Allocate the display data */ SDL_DisplayData *data = [[SDL_DisplayData alloc] initWithScreen:uiscreen]; if (!data) { UIKit_FreeDisplayModeData(&display.desktop_mode); return SDL_OutOfMemory(); } display.driverdata = (void *) CFBridgingRetain(data); SDL_AddVideoDisplay(&display); return 0; } SDL_bool UIKit_IsDisplayLandscape(UIScreen *uiscreen) { #if !TARGET_OS_TV if (uiscreen == [UIScreen mainScreen]) { return UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation); } else #endif /* !TARGET_OS_TV */ { CGSize size = uiscreen.bounds.size; return (size.width > size.height); } } int UIKit_InitModes(_THIS) { @autoreleasepool { for (UIScreen *uiscreen in [UIScreen screens]) { if (UIKit_AddDisplay(uiscreen) < 0) { return -1; } } #if !TARGET_OS_TV SDL_OnApplicationDidChangeStatusBarOrientation(); #endif } return 0; } void UIKit_GetDisplayModes(_THIS, SDL_VideoDisplay * display) { @autoreleasepool { SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata; SDL_bool isLandscape = UIKit_IsDisplayLandscape(data.uiscreen); SDL_bool addRotation = (data.uiscreen == [UIScreen mainScreen]); CGFloat scale = data.uiscreen.scale; NSArray *availableModes = nil; #if TARGET_OS_TV addRotation = SDL_FALSE; availableModes = @[data.uiscreen.currentMode]; #else availableModes = data.uiscreen.availableModes; #endif for (UIScreenMode *uimode in availableModes) { /* The size of a UIScreenMode is in pixels, but we deal exclusively * in points (except in SDL_GL_GetDrawableSize.) * * For devices such as iPhone 6/7/8 Plus, the UIScreenMode reported * by iOS is not in physical pixels of the display, but rather the * point size times the scale. For example, on iOS 12.2 on iPhone 8 * Plus the uimode.size is 1242x2208 and the uiscreen.scale is 3 * thus this will give the size in points which is 414x736. The code * used to use the nativeScale, assuming UIScreenMode returned raw * physical pixels (as suggested by its documentation, but in * practice it is returning the retina pixels). */ int w = (int)(uimode.size.width / scale); int h = (int)(uimode.size.height / scale); /* Make sure the width/height are oriented correctly */ if (isLandscape != (w > h)) { int tmp = w; w = h; h = tmp; } UIKit_AddDisplayMode(display, w, h, data.uiscreen, uimode, addRotation); } } } int UIKit_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi, float * hdpi, float * vdpi) { @autoreleasepool { SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata; float dpi = data.screenDPI; if (ddpi) { *ddpi = dpi * (float)SDL_sqrt(2.0); } if (hdpi) { *hdpi = dpi; } if (vdpi) { *vdpi = dpi; } } return 0; } int UIKit_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode) { @autoreleasepool { SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata; #if !TARGET_OS_TV SDL_DisplayModeData *modedata = (__bridge SDL_DisplayModeData *)mode->driverdata; [data.uiscreen setCurrentMode:modedata.uiscreenmode]; #endif if (data.uiscreen == [UIScreen mainScreen]) { /* [UIApplication setStatusBarOrientation:] no longer works reliably * in recent iOS versions, so we can't rotate the screen when setting * the display mode. */ if (mode->w > mode->h) { if (!UIKit_IsDisplayLandscape(data.uiscreen)) { return SDL_SetError("Screen orientation does not match display mode size"); } } else if (mode->w < mode->h) { if (UIKit_IsDisplayLandscape(data.uiscreen)) { return SDL_SetError("Screen orientation does not match display mode size"); } } } } return 0; } int UIKit_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect) { @autoreleasepool { int displayIndex = (int) (display - _this->displays); SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata; CGRect frame = data.uiscreen.bounds; /* the default function iterates displays to make a fake offset, as if all the displays were side-by-side, which is fine for iOS. */ if (SDL_GetDisplayBounds(displayIndex, rect) < 0) { return -1; } #if !TARGET_OS_TV && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0 if (!UIKit_IsSystemVersionAtLeast(7.0)) { frame = [data.uiscreen applicationFrame]; } #endif rect->x += frame.origin.x; rect->y += frame.origin.y; rect->w = frame.size.width; rect->h = frame.size.height; } return 0; } void UIKit_QuitModes(_THIS) { /* Release Objective-C objects, so higher level doesn't free() them. */ int i, j; @autoreleasepool { for (i = 0; i < _this->num_displays; i++) { SDL_VideoDisplay *display = &_this->displays[i]; UIKit_FreeDisplayModeData(&display->desktop_mode); for (j = 0; j < display->num_display_modes; j++) { SDL_DisplayMode *mode = &display->display_modes[j]; UIKit_FreeDisplayModeData(mode); } if (display->driverdata != NULL) { CFRelease(display->driverdata); display->driverdata = NULL; } } } } #if !TARGET_OS_TV void SDL_OnApplicationDidChangeStatusBarOrientation() { BOOL isLandscape = UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation); SDL_VideoDisplay *display = SDL_GetDisplay(0); if (display) { SDL_DisplayMode *desktopmode = &display->desktop_mode; SDL_DisplayMode *currentmode = &display->current_mode; SDL_DisplayOrientation orientation = SDL_ORIENTATION_UNKNOWN; /* The desktop display mode should be kept in sync with the screen * orientation so that updating a window's fullscreen state to * SDL_WINDOW_FULLSCREEN_DESKTOP keeps the window dimensions in the * correct orientation. */ if (isLandscape != (desktopmode->w > desktopmode->h)) { int height = desktopmode->w; desktopmode->w = desktopmode->h; desktopmode->h = height; } /* Same deal with the current mode + SDL_GetCurrentDisplayMode. */ if (isLandscape != (currentmode->w > currentmode->h)) { int height = currentmode->w; currentmode->w = currentmode->h; currentmode->h = height; } switch ([UIApplication sharedApplication].statusBarOrientation) { case UIInterfaceOrientationPortrait: orientation = SDL_ORIENTATION_PORTRAIT; break; case UIInterfaceOrientationPortraitUpsideDown: orientation = SDL_ORIENTATION_PORTRAIT_FLIPPED; break; case UIInterfaceOrientationLandscapeLeft: /* Bug: UIInterfaceOrientationLandscapeLeft/Right are reversed - http://openradar.appspot.com/7216046 */ orientation = SDL_ORIENTATION_LANDSCAPE_FLIPPED; break; case UIInterfaceOrientationLandscapeRight: /* Bug: UIInterfaceOrientationLandscapeLeft/Right are reversed - http://openradar.appspot.com/7216046 */ orientation = SDL_ORIENTATION_LANDSCAPE; break; default: break; } SDL_SendDisplayEvent(display, SDL_DISPLAYEVENT_ORIENTATION, orientation); } } #endif /* !TARGET_OS_TV */ #endif /* SDL_VIDEO_DRIVER_UIKIT */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitmodes.m
Objective-C
apache-2.0
16,678
/* 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_uikitopengles_ #define SDL_uikitopengles_ #if SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 #include "../SDL_sysvideo.h" extern int UIKit_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context); extern void UIKit_GL_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h); extern int UIKit_GL_SwapWindow(_THIS, SDL_Window * window); extern SDL_GLContext UIKit_GL_CreateContext(_THIS, SDL_Window * window); extern void UIKit_GL_DeleteContext(_THIS, SDL_GLContext context); extern void *UIKit_GL_GetProcAddress(_THIS, const char *proc); extern int UIKit_GL_LoadLibrary(_THIS, const char *path); extern void UIKit_GL_RestoreCurrentContext(void); #endif // SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 #endif /* SDL_uikitopengles_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitopengles.h
C
apache-2.0
1,805
/* 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_VIDEO_DRIVER_UIKIT && (SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2) #include "SDL_uikitopengles.h" #import "SDL_uikitopenglview.h" #include "SDL_uikitmodes.h" #include "SDL_uikitwindow.h" #include "SDL_uikitevents.h" #include "../SDL_sysvideo.h" #include "../../events/SDL_keyboard_c.h" #include "../../events/SDL_mouse_c.h" #include "../../power/uikit/SDL_syspower.h" #include "SDL_loadso.h" #include <dlfcn.h> @interface SDLEAGLContext : EAGLContext /* The OpenGL ES context owns a view / drawable. */ @property (nonatomic, strong) SDL_uikitopenglview *sdlView; @end @implementation SDLEAGLContext - (void)dealloc { /* When the context is deallocated, its view should be removed from any * SDL window that it's attached to. */ [self.sdlView setSDLWindow:NULL]; } @end void * UIKit_GL_GetProcAddress(_THIS, const char *proc) { /* Look through all SO's for the proc symbol. Here's why: * -Looking for the path to the OpenGL Library seems not to work in the iOS Simulator. * -We don't know that the path won't change in the future. */ return dlsym(RTLD_DEFAULT, proc); } /* note that SDL_GL_DeleteContext makes it current without passing the window */ int UIKit_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context) { @autoreleasepool { SDLEAGLContext *eaglcontext = (__bridge SDLEAGLContext *) context; if (![EAGLContext setCurrentContext:eaglcontext]) { return SDL_SetError("Could not make EAGL context current"); } if (eaglcontext) { [eaglcontext.sdlView setSDLWindow:window]; } } return 0; } void UIKit_GL_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h) { @autoreleasepool { SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; UIView *view = data.viewcontroller.view; if ([view isKindOfClass:[SDL_uikitopenglview class]]) { SDL_uikitopenglview *glview = (SDL_uikitopenglview *) view; if (w) { *w = glview.backingWidth; } if (h) { *h = glview.backingHeight; } } else { SDL_GetWindowSize(window, w, h); } } } int UIKit_GL_LoadLibrary(_THIS, const char *path) { /* We shouldn't pass a path to this function, since we've already loaded the * library. */ if (path != NULL) { return SDL_SetError("iOS GL Load Library just here for compatibility"); } return 0; } int UIKit_GL_SwapWindow(_THIS, SDL_Window * window) { @autoreleasepool { SDLEAGLContext *context = (__bridge SDLEAGLContext *) SDL_GL_GetCurrentContext(); #if SDL_POWER_UIKIT /* Check once a frame to see if we should turn off the battery monitor. */ SDL_UIKit_UpdateBatteryMonitoring(); #endif [context.sdlView swapBuffers]; /* You need to pump events in order for the OS to make changes visible. * We don't pump events here because we don't want iOS application events * (low memory, terminate, etc.) to happen inside low level rendering. */ } return 0; } SDL_GLContext UIKit_GL_CreateContext(_THIS, SDL_Window * window) { @autoreleasepool { SDLEAGLContext *context = nil; SDL_uikitopenglview *view; SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; CGRect frame = UIKit_ComputeViewFrame(window, data.uiwindow.screen); EAGLSharegroup *sharegroup = nil; CGFloat scale = 1.0; int samples = 0; int major = _this->gl_config.major_version; int minor = _this->gl_config.minor_version; /* The EAGLRenderingAPI enum values currently map 1:1 to major GLES * versions. */ EAGLRenderingAPI api = major; /* iOS currently doesn't support GLES >3.0. iOS 6 also only supports up * to GLES 2.0. */ if (major > 3 || (major == 3 && (minor > 0 || !UIKit_IsSystemVersionAtLeast(7.0)))) { SDL_SetError("OpenGL ES %d.%d context could not be created", major, minor); return NULL; } if (_this->gl_config.multisamplebuffers > 0) { samples = _this->gl_config.multisamplesamples; } if (_this->gl_config.share_with_current_context) { EAGLContext *context = (__bridge EAGLContext *) SDL_GL_GetCurrentContext(); sharegroup = context.sharegroup; } if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) { /* Set the scale to the natural scale factor of the screen - the * backing dimensions of the OpenGL view will match the pixel * dimensions of the screen rather than the dimensions in points. */ if ([data.uiwindow.screen respondsToSelector:@selector(nativeScale)]) { scale = data.uiwindow.screen.nativeScale; } else { scale = data.uiwindow.screen.scale; } } context = [[SDLEAGLContext alloc] initWithAPI:api sharegroup:sharegroup]; if (!context) { SDL_SetError("OpenGL ES %d context could not be created", _this->gl_config.major_version); return NULL; } /* construct our view, passing in SDL's OpenGL configuration data */ view = [[SDL_uikitopenglview alloc] initWithFrame:frame scale:scale retainBacking:_this->gl_config.retained_backing rBits:_this->gl_config.red_size gBits:_this->gl_config.green_size bBits:_this->gl_config.blue_size aBits:_this->gl_config.alpha_size depthBits:_this->gl_config.depth_size stencilBits:_this->gl_config.stencil_size sRGB:_this->gl_config.framebuffer_srgb_capable multisamples:samples context:context]; if (!view) { return NULL; } /* The context owns the view / drawable. */ context.sdlView = view; if (UIKit_GL_MakeCurrent(_this, window, (__bridge SDL_GLContext) context) < 0) { UIKit_GL_DeleteContext(_this, (SDL_GLContext) CFBridgingRetain(context)); return NULL; } /* We return a +1'd context. The window's driverdata owns the view (via * MakeCurrent.) */ return (SDL_GLContext) CFBridgingRetain(context); } } void UIKit_GL_DeleteContext(_THIS, SDL_GLContext context) { @autoreleasepool { /* The context was retained in SDL_GL_CreateContext, so we release it * here. The context's view will be detached from its window when the * context is deallocated. */ CFRelease(context); } } void UIKit_GL_RestoreCurrentContext(void) { @autoreleasepool { /* Some iOS system functionality (such as Dictation on the on-screen keyboard) uses its own OpenGL ES context but doesn't restore the previous one when it's done. This is a workaround to make sure the expected SDL-created OpenGL ES context is active after the OS is finished running its own code for the frame. If this isn't done, the app may crash or have other nasty symptoms when Dictation is used. */ EAGLContext *context = (__bridge EAGLContext *) SDL_GL_GetCurrentContext(); if (context != NULL && [EAGLContext currentContext] != context) { [EAGLContext setCurrentContext:context]; } } } #endif /* SDL_VIDEO_DRIVER_UIKIT */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitopengles.m
Objective-C
apache-2.0
8,931
/* 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. */ #if SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 #import <UIKit/UIKit.h> #import <OpenGLES/EAGL.h> #import <OpenGLES/ES3/gl.h> #import "SDL_uikitview.h" #include "SDL_uikitvideo.h" @interface SDL_uikitopenglview : SDL_uikitview - (instancetype)initWithFrame:(CGRect)frame scale:(CGFloat)scale retainBacking:(BOOL)retained rBits:(int)rBits gBits:(int)gBits bBits:(int)bBits aBits:(int)aBits depthBits:(int)depthBits stencilBits:(int)stencilBits sRGB:(BOOL)sRGB multisamples:(int)multisamples context:(EAGLContext *)glcontext; @property (nonatomic, readonly, weak) EAGLContext *context; /* The width and height of the drawable in pixels (as opposed to points.) */ @property (nonatomic, readonly) int backingWidth; @property (nonatomic, readonly) int backingHeight; @property (nonatomic, readonly) GLuint drawableRenderbuffer; @property (nonatomic, readonly) GLuint drawableFramebuffer; @property (nonatomic, readonly) GLuint msaaResolveFramebuffer; - (void)swapBuffers; - (void)updateFrame; @end #endif // SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitopenglview.h
Objective-C
apache-2.0
2,272
/* 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_VIDEO_DRIVER_UIKIT && (SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2) #include <OpenGLES/EAGLDrawable.h> #include <OpenGLES/ES2/glext.h> #import "SDL_uikitopenglview.h" #include "SDL_uikitwindow.h" @implementation SDL_uikitopenglview { /* The renderbuffer and framebuffer used to render to this layer. */ GLuint viewRenderbuffer, viewFramebuffer; /* The depth buffer that is attached to viewFramebuffer, if it exists. */ GLuint depthRenderbuffer; GLenum colorBufferFormat; /* format of depthRenderbuffer */ GLenum depthBufferFormat; /* The framebuffer and renderbuffer used for rendering with MSAA. */ GLuint msaaFramebuffer, msaaRenderbuffer; /* The number of MSAA samples. */ int samples; BOOL retainedBacking; } @synthesize context; @synthesize backingWidth; @synthesize backingHeight; + (Class)layerClass { return [CAEAGLLayer class]; } - (instancetype)initWithFrame:(CGRect)frame scale:(CGFloat)scale retainBacking:(BOOL)retained rBits:(int)rBits gBits:(int)gBits bBits:(int)bBits aBits:(int)aBits depthBits:(int)depthBits stencilBits:(int)stencilBits sRGB:(BOOL)sRGB multisamples:(int)multisamples context:(EAGLContext *)glcontext { if ((self = [super initWithFrame:frame])) { const BOOL useStencilBuffer = (stencilBits != 0); const BOOL useDepthBuffer = (depthBits != 0); NSString *colorFormat = nil; context = glcontext; samples = multisamples; retainedBacking = retained; if (!context || ![EAGLContext setCurrentContext:context]) { SDL_SetError("Could not create OpenGL ES drawable (could not make context current)"); return nil; } if (samples > 0) { GLint maxsamples = 0; glGetIntegerv(GL_MAX_SAMPLES, &maxsamples); /* Clamp the samples to the max supported count. */ samples = MIN(samples, maxsamples); } if (sRGB) { /* sRGB EAGL drawable support was added in iOS 7. */ if (UIKit_IsSystemVersionAtLeast(7.0)) { colorFormat = kEAGLColorFormatSRGBA8; colorBufferFormat = GL_SRGB8_ALPHA8; } else { SDL_SetError("sRGB drawables are not supported."); return nil; } } else if (rBits >= 8 || gBits >= 8 || bBits >= 8 || aBits > 0) { /* if user specifically requests rbg888 or some color format higher than 16bpp */ colorFormat = kEAGLColorFormatRGBA8; colorBufferFormat = GL_RGBA8; } else { /* default case (potentially faster) */ colorFormat = kEAGLColorFormatRGB565; colorBufferFormat = GL_RGB565; } CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer; eaglLayer.opaque = YES; eaglLayer.drawableProperties = @{ kEAGLDrawablePropertyRetainedBacking:@(retained), kEAGLDrawablePropertyColorFormat:colorFormat }; /* Set the appropriate scale (for retina display support) */ self.contentScaleFactor = scale; /* Create the color Renderbuffer Object */ glGenRenderbuffers(1, &viewRenderbuffer); glBindRenderbuffer(GL_RENDERBUFFER, viewRenderbuffer); if (![context renderbufferStorage:GL_RENDERBUFFER fromDrawable:eaglLayer]) { SDL_SetError("Failed to create OpenGL ES drawable"); return nil; } /* Create the Framebuffer Object */ glGenFramebuffers(1, &viewFramebuffer); glBindFramebuffer(GL_FRAMEBUFFER, viewFramebuffer); /* attach the color renderbuffer to the FBO */ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, viewRenderbuffer); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { SDL_SetError("Failed creating OpenGL ES framebuffer"); return nil; } /* When MSAA is used we'll use a separate framebuffer for rendering to, * since we'll need to do an explicit MSAA resolve before presenting. */ if (samples > 0) { glGenFramebuffers(1, &msaaFramebuffer); glBindFramebuffer(GL_FRAMEBUFFER, msaaFramebuffer); glGenRenderbuffers(1, &msaaRenderbuffer); glBindRenderbuffer(GL_RENDERBUFFER, msaaRenderbuffer); glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, colorBufferFormat, backingWidth, backingHeight); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, msaaRenderbuffer); } if (useDepthBuffer || useStencilBuffer) { if (useStencilBuffer) { /* Apparently you need to pack stencil and depth into one buffer. */ depthBufferFormat = GL_DEPTH24_STENCIL8_OES; } else if (useDepthBuffer) { /* iOS only uses 32-bit float (exposed as fixed point 24-bit) * depth buffers. */ depthBufferFormat = GL_DEPTH_COMPONENT24_OES; } glGenRenderbuffers(1, &depthRenderbuffer); glBindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer); if (samples > 0) { glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, depthBufferFormat, backingWidth, backingHeight); } else { glRenderbufferStorage(GL_RENDERBUFFER, depthBufferFormat, backingWidth, backingHeight); } if (useDepthBuffer) { glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderbuffer); } if (useStencilBuffer) { glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthRenderbuffer); } } if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { SDL_SetError("Failed creating OpenGL ES framebuffer"); return nil; } glBindRenderbuffer(GL_RENDERBUFFER, viewRenderbuffer); [self setDebugLabels]; } return self; } - (GLuint)drawableRenderbuffer { return viewRenderbuffer; } - (GLuint)drawableFramebuffer { /* When MSAA is used, the MSAA draw framebuffer is used for drawing. */ if (msaaFramebuffer) { return msaaFramebuffer; } else { return viewFramebuffer; } } - (GLuint)msaaResolveFramebuffer { /* When MSAA is used, the MSAA draw framebuffer is used for drawing and the * view framebuffer is used as a MSAA resolve framebuffer. */ if (msaaFramebuffer) { return viewFramebuffer; } else { return 0; } } - (void)updateFrame { GLint prevRenderbuffer = 0; glGetIntegerv(GL_RENDERBUFFER_BINDING, &prevRenderbuffer); glBindRenderbuffer(GL_RENDERBUFFER, viewRenderbuffer); [context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer *)self.layer]; glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight); if (msaaRenderbuffer != 0) { glBindRenderbuffer(GL_RENDERBUFFER, msaaRenderbuffer); glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, colorBufferFormat, backingWidth, backingHeight); } if (depthRenderbuffer != 0) { glBindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer); if (samples > 0) { glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, depthBufferFormat, backingWidth, backingHeight); } else { glRenderbufferStorage(GL_RENDERBUFFER, depthBufferFormat, backingWidth, backingHeight); } } glBindRenderbuffer(GL_RENDERBUFFER, prevRenderbuffer); } - (void)setDebugLabels { if (viewFramebuffer != 0) { glLabelObjectEXT(GL_FRAMEBUFFER, viewFramebuffer, 0, "context FBO"); } if (viewRenderbuffer != 0) { glLabelObjectEXT(GL_RENDERBUFFER, viewRenderbuffer, 0, "context color buffer"); } if (depthRenderbuffer != 0) { if (depthBufferFormat == GL_DEPTH24_STENCIL8_OES) { glLabelObjectEXT(GL_RENDERBUFFER, depthRenderbuffer, 0, "context depth-stencil buffer"); } else { glLabelObjectEXT(GL_RENDERBUFFER, depthRenderbuffer, 0, "context depth buffer"); } } if (msaaFramebuffer != 0) { glLabelObjectEXT(GL_FRAMEBUFFER, msaaFramebuffer, 0, "context MSAA FBO"); } if (msaaRenderbuffer != 0) { glLabelObjectEXT(GL_RENDERBUFFER, msaaRenderbuffer, 0, "context MSAA renderbuffer"); } } - (void)swapBuffers { if (msaaFramebuffer) { const GLenum attachments[] = {GL_COLOR_ATTACHMENT0}; glBindFramebuffer(GL_DRAW_FRAMEBUFFER, viewFramebuffer); /* OpenGL ES 3+ provides explicit MSAA resolves via glBlitFramebuffer. * In OpenGL ES 1 and 2, MSAA resolves must be done via an extension. */ if (context.API >= kEAGLRenderingAPIOpenGLES3) { int w = backingWidth; int h = backingHeight; glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST); if (!retainedBacking) { /* Discard the contents of the MSAA drawable color buffer. */ glInvalidateFramebuffer(GL_READ_FRAMEBUFFER, 1, attachments); } } else { glResolveMultisampleFramebufferAPPLE(); if (!retainedBacking) { glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER, 1, attachments); } } /* We assume the "drawable framebuffer" (MSAA draw framebuffer) was * previously bound... */ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, msaaFramebuffer); } /* viewRenderbuffer should always be bound here. Code that binds something * else is responsible for rebinding viewRenderbuffer, to reduce duplicate * state changes. */ [context presentRenderbuffer:GL_RENDERBUFFER]; } - (void)layoutSubviews { [super layoutSubviews]; int width = (int) (self.bounds.size.width * self.contentScaleFactor); int height = (int) (self.bounds.size.height * self.contentScaleFactor); /* Update the color and depth buffer storage if the layer size has changed. */ if (width != backingWidth || height != backingHeight) { EAGLContext *prevContext = [EAGLContext currentContext]; if (prevContext != context) { [EAGLContext setCurrentContext:context]; } [self updateFrame]; if (prevContext != context) { [EAGLContext setCurrentContext:prevContext]; } } } - (void)destroyFramebuffer { if (viewFramebuffer != 0) { glDeleteFramebuffers(1, &viewFramebuffer); viewFramebuffer = 0; } if (viewRenderbuffer != 0) { glDeleteRenderbuffers(1, &viewRenderbuffer); viewRenderbuffer = 0; } if (depthRenderbuffer != 0) { glDeleteRenderbuffers(1, &depthRenderbuffer); depthRenderbuffer = 0; } if (msaaFramebuffer != 0) { glDeleteFramebuffers(1, &msaaFramebuffer); msaaFramebuffer = 0; } if (msaaRenderbuffer != 0) { glDeleteRenderbuffers(1, &msaaRenderbuffer); msaaRenderbuffer = 0; } } - (void)dealloc { if (context && context == [EAGLContext currentContext]) { [self destroyFramebuffer]; [EAGLContext setCurrentContext:nil]; } } @end #endif /* SDL_VIDEO_DRIVER_UIKIT */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitopenglview.m
Objective-C
apache-2.0
13,042
/* 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_uikitvideo_h_ #define SDL_uikitvideo_h_ #include "../SDL_sysvideo.h" #ifdef __OBJC__ #include <UIKit/UIKit.h> @interface SDL_VideoData : NSObject @property (nonatomic, assign) id pasteboardObserver; @end CGRect UIKit_ComputeViewFrame(SDL_Window *window, UIScreen *screen); #endif /* __OBJC__ */ void UIKit_SuspendScreenSaver(_THIS); void UIKit_ForceUpdateHomeIndicator(void); SDL_bool UIKit_IsSystemVersionAtLeast(double version); #endif /* SDL_uikitvideo_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitvideo.h
Objective-C
apache-2.0
1,461
/* 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_VIDEO_DRIVER_UIKIT #import <UIKit/UIKit.h> #include "SDL_video.h" #include "SDL_mouse.h" #include "SDL_hints.h" #include "../SDL_sysvideo.h" #include "../SDL_pixels_c.h" #include "../../events/SDL_events_c.h" #include "SDL_uikitvideo.h" #include "SDL_uikitevents.h" #include "SDL_uikitmodes.h" #include "SDL_uikitwindow.h" #include "SDL_uikitopengles.h" #include "SDL_uikitclipboard.h" #include "SDL_uikitvulkan.h" #include "SDL_uikitmetalview.h" #define UIKITVID_DRIVER_NAME "uikit" @implementation SDL_VideoData @end /* Initialization/Query functions */ static int UIKit_VideoInit(_THIS); static void UIKit_VideoQuit(_THIS); /* DUMMY driver bootstrap functions */ static int UIKit_Available(void) { return 1; } static void UIKit_DeleteDevice(SDL_VideoDevice * device) { @autoreleasepool { CFRelease(device->driverdata); SDL_free(device); } } static SDL_VideoDevice * UIKit_CreateDevice(int devindex) { @autoreleasepool { SDL_VideoDevice *device; SDL_VideoData *data; /* Initialize all variables that we clean on shutdown */ device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice)); if (device) { data = [SDL_VideoData new]; } else { SDL_free(device); SDL_OutOfMemory(); return (0); } device->driverdata = (void *) CFBridgingRetain(data); /* Set the function pointers */ device->VideoInit = UIKit_VideoInit; device->VideoQuit = UIKit_VideoQuit; device->GetDisplayModes = UIKit_GetDisplayModes; device->SetDisplayMode = UIKit_SetDisplayMode; device->PumpEvents = UIKit_PumpEvents; device->SuspendScreenSaver = UIKit_SuspendScreenSaver; device->CreateSDLWindow = UIKit_CreateWindow; device->SetWindowTitle = UIKit_SetWindowTitle; device->ShowWindow = UIKit_ShowWindow; device->HideWindow = UIKit_HideWindow; device->RaiseWindow = UIKit_RaiseWindow; device->SetWindowBordered = UIKit_SetWindowBordered; device->SetWindowFullscreen = UIKit_SetWindowFullscreen; device->DestroyWindow = UIKit_DestroyWindow; device->GetWindowWMInfo = UIKit_GetWindowWMInfo; device->GetDisplayUsableBounds = UIKit_GetDisplayUsableBounds; device->GetDisplayDPI = UIKit_GetDisplayDPI; #if SDL_IPHONE_KEYBOARD device->HasScreenKeyboardSupport = UIKit_HasScreenKeyboardSupport; device->ShowScreenKeyboard = UIKit_ShowScreenKeyboard; device->HideScreenKeyboard = UIKit_HideScreenKeyboard; device->IsScreenKeyboardShown = UIKit_IsScreenKeyboardShown; device->SetTextInputRect = UIKit_SetTextInputRect; #endif device->SetClipboardText = UIKit_SetClipboardText; device->GetClipboardText = UIKit_GetClipboardText; device->HasClipboardText = UIKit_HasClipboardText; /* OpenGL (ES) functions */ #if SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 device->GL_MakeCurrent = UIKit_GL_MakeCurrent; device->GL_GetDrawableSize = UIKit_GL_GetDrawableSize; device->GL_SwapWindow = UIKit_GL_SwapWindow; device->GL_CreateContext = UIKit_GL_CreateContext; device->GL_DeleteContext = UIKit_GL_DeleteContext; device->GL_GetProcAddress = UIKit_GL_GetProcAddress; device->GL_LoadLibrary = UIKit_GL_LoadLibrary; #endif device->free = UIKit_DeleteDevice; #if SDL_VIDEO_VULKAN device->Vulkan_LoadLibrary = UIKit_Vulkan_LoadLibrary; device->Vulkan_UnloadLibrary = UIKit_Vulkan_UnloadLibrary; device->Vulkan_GetInstanceExtensions = UIKit_Vulkan_GetInstanceExtensions; device->Vulkan_CreateSurface = UIKit_Vulkan_CreateSurface; device->Vulkan_GetDrawableSize = UIKit_Vulkan_GetDrawableSize; #endif #if SDL_VIDEO_METAL device->Metal_CreateView = UIKit_Metal_CreateView; device->Metal_DestroyView = UIKit_Metal_DestroyView; device->Metal_GetLayer = UIKit_Metal_GetLayer; device->Metal_GetDrawableSize = UIKit_Metal_GetDrawableSize; #endif device->gl_config.accelerated = 1; return device; } } VideoBootStrap UIKIT_bootstrap = { UIKITVID_DRIVER_NAME, "SDL UIKit video driver", UIKit_Available, UIKit_CreateDevice }; int UIKit_VideoInit(_THIS) { _this->gl_config.driver_loaded = 1; if (UIKit_InitModes(_this) < 0) { return -1; } return 0; } void UIKit_VideoQuit(_THIS) { UIKit_QuitModes(_this); } void UIKit_SuspendScreenSaver(_THIS) { @autoreleasepool { /* Ignore ScreenSaver API calls if the idle timer hint has been set. */ /* FIXME: The idle timer hint should be deprecated for SDL 2.1. */ if (!SDL_GetHintBoolean(SDL_HINT_IDLE_TIMER_DISABLED, SDL_FALSE)) { UIApplication *app = [UIApplication sharedApplication]; /* Prevent the display from dimming and going to sleep. */ app.idleTimerDisabled = (_this->suspend_screensaver != SDL_FALSE); } } } SDL_bool UIKit_IsSystemVersionAtLeast(double version) { return [[UIDevice currentDevice].systemVersion doubleValue] >= version; } CGRect UIKit_ComputeViewFrame(SDL_Window *window, UIScreen *screen) { SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; CGRect frame = screen.bounds; /* Use the UIWindow bounds instead of the UIScreen bounds, when possible. * The uiwindow bounds may be smaller than the screen bounds when Split View * is used on an iPad. */ if (data != nil && data.uiwindow != nil) { frame = data.uiwindow.bounds; } #if !TARGET_OS_TV && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0) BOOL hasiOS7 = UIKit_IsSystemVersionAtLeast(7.0); /* The view should always show behind the status bar in iOS 7+. */ if (!hasiOS7 && !(window->flags & (SDL_WINDOW_BORDERLESS|SDL_WINDOW_FULLSCREEN))) { frame = screen.applicationFrame; } #endif #if !TARGET_OS_TV /* iOS 10 seems to have a bug where, in certain conditions, putting the * device to sleep with the a landscape-only app open, re-orienting the * device to portrait, and turning it back on will result in the screen * bounds returning portrait orientation despite the app being in landscape. * This is a workaround until a better solution can be found. * https://bugzilla.libsdl.org/show_bug.cgi?id=3505 * https://bugzilla.libsdl.org/show_bug.cgi?id=3465 * https://forums.developer.apple.com/thread/65337 */ if (UIKit_IsSystemVersionAtLeast(8.0)) { UIInterfaceOrientation orient = [UIApplication sharedApplication].statusBarOrientation; BOOL landscape = UIInterfaceOrientationIsLandscape(orient); BOOL fullscreen = CGRectEqualToRect(screen.bounds, frame); /* The orientation flip doesn't make sense when the window is smaller * than the screen (iPad Split View, for example). */ if (fullscreen && (landscape != (frame.size.width > frame.size.height))) { float height = frame.size.width; frame.size.width = frame.size.height; frame.size.height = height; } } #endif return frame; } void UIKit_ForceUpdateHomeIndicator() { #if !TARGET_OS_TV /* Force the main SDL window to re-evaluate home indicator state */ SDL_Window *focus = SDL_GetFocusWindow(); if (focus) { SDL_WindowData *data = (__bridge SDL_WindowData *) focus->driverdata; if (data != nil) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunguarded-availability-new" if ([data.viewcontroller respondsToSelector:@selector(setNeedsUpdateOfHomeIndicatorAutoHidden)]) { [data.viewcontroller performSelectorOnMainThread:@selector(setNeedsUpdateOfHomeIndicatorAutoHidden) withObject:nil waitUntilDone:NO]; [data.viewcontroller performSelectorOnMainThread:@selector(setNeedsUpdateOfScreenEdgesDeferringSystemGestures) withObject:nil waitUntilDone:NO]; } #pragma clang diagnostic pop } } #endif /* !TARGET_OS_TV */ } /* * iOS log support. * * This doesn't really have aything to do with the interfaces of the SDL video * subsystem, but we need to stuff this into an Objective-C source code file. * * NOTE: This is copypasted from src/video/cocoa/SDL_cocoavideo.m! Thus, if * Cocoa is supported, we use that one instead. Be sure both versions remain * identical! */ #if !defined(SDL_VIDEO_DRIVER_COCOA) void SDL_NSLog(const char *text) { NSLog(@"%s", text); } #endif /* SDL_VIDEO_DRIVER_COCOA */ /* * iOS Tablet detection * * This doesn't really have aything to do with the interfaces of the SDL video * subsystem, but we need to stuff this into an Objective-C source code file. */ SDL_bool SDL_IsIPad(void) { return ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad); } #endif /* SDL_VIDEO_DRIVER_UIKIT */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitvideo.m
Objective-C
apache-2.0
10,054
/* 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. */ #import <UIKit/UIKit.h> #include "../SDL_sysvideo.h" #include "SDL_touch.h" #if !TARGET_OS_TV && defined(__IPHONE_13_4) @interface SDL_uikitview : UIView <UIPointerInteractionDelegate> #else @interface SDL_uikitview : UIView #endif - (instancetype)initWithFrame:(CGRect)frame; - (void)setSDLWindow:(SDL_Window *)window; #if !TARGET_OS_TV && defined(__IPHONE_13_4) - (UIPointerRegion *)pointerInteraction:(UIPointerInteraction *)interaction regionForRequest:(UIPointerRegionRequest *)request defaultRegion:(UIPointerRegion *)defaultRegion API_AVAILABLE(ios(13.4)); - (UIPointerStyle *)pointerInteraction:(UIPointerInteraction *)interaction styleForRegion:(UIPointerRegion *)region API_AVAILABLE(ios(13.4)); #endif - (CGPoint)touchLocation:(UITouch *)touch shouldNormalize:(BOOL)normalize; - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; @end /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitview.h
Objective-C
apache-2.0
1,976
/* 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_VIDEO_DRIVER_UIKIT #include "SDL_uikitview.h" #include "SDL_hints.h" #include "../../events/SDL_mouse_c.h" #include "../../events/SDL_touch_c.h" #include "../../events/SDL_events_c.h" #import "SDL_uikitappdelegate.h" #import "SDL_uikitmodes.h" #import "SDL_uikitwindow.h" /* The maximum number of mouse buttons we support */ #define MAX_MOUSE_BUTTONS 5 /* This is defined in SDL_sysjoystick.m */ #if !SDL_JOYSTICK_DISABLED extern int SDL_AppleTVRemoteOpenedAsJoystick; #endif @implementation SDL_uikitview { SDL_Window *sdlwindow; SDL_TouchID directTouchId; SDL_TouchID indirectTouchId; } - (instancetype)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { #if TARGET_OS_TV /* Apple TV Remote touchpad swipe gestures. */ UISwipeGestureRecognizer *swipeUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)]; swipeUp.direction = UISwipeGestureRecognizerDirectionUp; [self addGestureRecognizer:swipeUp]; UISwipeGestureRecognizer *swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)]; swipeDown.direction = UISwipeGestureRecognizerDirectionDown; [self addGestureRecognizer:swipeDown]; UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)]; swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft; [self addGestureRecognizer:swipeLeft]; UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)]; swipeRight.direction = UISwipeGestureRecognizerDirectionRight; [self addGestureRecognizer:swipeRight]; #else if (@available(iOS 13.4, *)) { UIPanGestureRecognizer *mouseWheelRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(mouseWheelGesture:)]; mouseWheelRecognizer.allowedScrollTypesMask = UIScrollTypeMaskDiscrete; mouseWheelRecognizer.allowedTouchTypes = @[ @(UITouchTypeIndirectPointer) ]; mouseWheelRecognizer.cancelsTouchesInView = NO; mouseWheelRecognizer.delaysTouchesBegan = NO; mouseWheelRecognizer.delaysTouchesEnded = NO; [self addGestureRecognizer:mouseWheelRecognizer]; } #endif self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; self.autoresizesSubviews = YES; directTouchId = 1; indirectTouchId = 2; #if !TARGET_OS_TV self.multipleTouchEnabled = YES; SDL_AddTouch(directTouchId, SDL_TOUCH_DEVICE_DIRECT, ""); #endif #if !TARGET_OS_TV && defined(__IPHONE_13_4) if (@available(iOS 13.4, *)) { [self addInteraction:[[UIPointerInteraction alloc] initWithDelegate:self]]; } #endif } return self; } - (void)setSDLWindow:(SDL_Window *)window { SDL_WindowData *data = nil; if (window == sdlwindow) { return; } /* Remove ourself from the old window. */ if (sdlwindow) { SDL_uikitview *view = nil; data = (__bridge SDL_WindowData *) sdlwindow->driverdata; [data.views removeObject:self]; [self removeFromSuperview]; /* Restore the next-oldest view in the old window. */ view = data.views.lastObject; data.viewcontroller.view = view; data.uiwindow.rootViewController = nil; data.uiwindow.rootViewController = data.viewcontroller; [data.uiwindow layoutIfNeeded]; } /* Add ourself to the new window. */ if (window) { data = (__bridge SDL_WindowData *) window->driverdata; /* Make sure the SDL window has a strong reference to this view. */ [data.views addObject:self]; /* Replace the view controller's old view with this one. */ [data.viewcontroller.view removeFromSuperview]; data.viewcontroller.view = self; /* The root view controller handles rotation and the status bar. * Assigning it also adds the controller's view to the window. We * explicitly re-set it to make sure the view is properly attached to * the window. Just adding the sub-view if the root view controller is * already correct causes orientation issues on iOS 7 and below. */ data.uiwindow.rootViewController = nil; data.uiwindow.rootViewController = data.viewcontroller; /* The view's bounds may not be correct until the next event cycle. That * might happen after the current dimensions are queried, so we force a * layout now to immediately update the bounds. */ [data.uiwindow layoutIfNeeded]; } sdlwindow = window; } #if !TARGET_OS_TV && defined(__IPHONE_13_4) - (UIPointerRegion *)pointerInteraction:(UIPointerInteraction *)interaction regionForRequest:(UIPointerRegionRequest *)request defaultRegion:(UIPointerRegion *)defaultRegion API_AVAILABLE(ios(13.4)){ if (request != nil) { CGPoint origin = self.bounds.origin; CGPoint point = request.location; point.x -= origin.x; point.y -= origin.y; SDL_SendMouseMotion(sdlwindow, 0, 0, (int)point.x, (int)point.y); } return [UIPointerRegion regionWithRect:self.bounds identifier:nil]; } - (UIPointerStyle *)pointerInteraction:(UIPointerInteraction *)interaction styleForRegion:(UIPointerRegion *)region API_AVAILABLE(ios(13.4)){ if (SDL_ShowCursor(-1)) { return nil; } else { return [UIPointerStyle hiddenPointerStyle]; } } #endif /* !TARGET_OS_TV && __IPHONE_13_4 */ - (SDL_TouchDeviceType)touchTypeForTouch:(UITouch *)touch { #ifdef __IPHONE_9_0 if ([touch respondsToSelector:@selector((type))]) { if (touch.type == UITouchTypeIndirect) { return SDL_TOUCH_DEVICE_INDIRECT_RELATIVE; } } #endif return SDL_TOUCH_DEVICE_DIRECT; } - (SDL_TouchID)touchIdForType:(SDL_TouchDeviceType)type { switch (type) { case SDL_TOUCH_DEVICE_DIRECT: default: return directTouchId; case SDL_TOUCH_DEVICE_INDIRECT_RELATIVE: return indirectTouchId; } } - (CGPoint)touchLocation:(UITouch *)touch shouldNormalize:(BOOL)normalize { CGPoint point = [touch locationInView:self]; if (normalize) { CGRect bounds = self.bounds; point.x /= bounds.size.width; point.y /= bounds.size.height; } return point; } - (float)pressureForTouch:(UITouch *)touch { #ifdef __IPHONE_9_0 if ([touch respondsToSelector:@selector(force)]) { return (float) touch.force; } #endif return 1.0f; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { for (UITouch *touch in touches) { BOOL handled = NO; #if !TARGET_OS_TV && defined(__IPHONE_13_4) if (@available(iOS 13.4, *)) { if (touch.type == UITouchTypeIndirectPointer) { int i; for (i = 1; i <= MAX_MOUSE_BUTTONS; ++i) { if (event.buttonMask & SDL_BUTTON(i)) { Uint8 button; switch (i) { case 1: button = SDL_BUTTON_LEFT; break; case 2: button = SDL_BUTTON_RIGHT; break; case 3: button = SDL_BUTTON_MIDDLE; break; default: button = (Uint8)i; break; } SDL_SendMouseButton(sdlwindow, 0, SDL_PRESSED, button); } } handled = YES; } } #endif if (!handled) { SDL_TouchDeviceType touchType = [self touchTypeForTouch:touch]; SDL_TouchID touchId = [self touchIdForType:touchType]; float pressure = [self pressureForTouch:touch]; if (SDL_AddTouch(touchId, touchType, "") < 0) { continue; } /* FIXME, need to send: int clicks = (int) touch.tapCount; ? */ CGPoint locationInView = [self touchLocation:touch shouldNormalize:YES]; SDL_SendTouch(touchId, (SDL_FingerID)((size_t)touch), sdlwindow, SDL_TRUE, locationInView.x, locationInView.y, pressure); } } } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { for (UITouch *touch in touches) { BOOL handled = NO; #if !TARGET_OS_TV && defined(__IPHONE_13_4) if (@available(iOS 13.4, *)) { if (touch.type == UITouchTypeIndirectPointer) { int i; for (i = 1; i <= MAX_MOUSE_BUTTONS; ++i) { if (!(event.buttonMask & SDL_BUTTON(i))) { Uint8 button; switch (i) { case 1: button = SDL_BUTTON_LEFT; break; case 2: button = SDL_BUTTON_RIGHT; break; case 3: button = SDL_BUTTON_MIDDLE; break; default: button = (Uint8)i; break; } SDL_SendMouseButton(sdlwindow, 0, SDL_RELEASED, button); } } handled = YES; } } #endif if (!handled) { SDL_TouchDeviceType touchType = [self touchTypeForTouch:touch]; SDL_TouchID touchId = [self touchIdForType:touchType]; float pressure = [self pressureForTouch:touch]; if (SDL_AddTouch(touchId, touchType, "") < 0) { continue; } /* FIXME, need to send: int clicks = (int) touch.tapCount; ? */ CGPoint locationInView = [self touchLocation:touch shouldNormalize:YES]; SDL_SendTouch(touchId, (SDL_FingerID)((size_t)touch), sdlwindow, SDL_FALSE, locationInView.x, locationInView.y, pressure); } } } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { [self touchesEnded:touches withEvent:event]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { for (UITouch *touch in touches) { BOOL handled = NO; #if !TARGET_OS_TV && defined(__IPHONE_13_4) if (@available(iOS 13.4, *)) { if (touch.type == UITouchTypeIndirectPointer) { /* Already handled in pointerInteraction callback */ handled = YES; } } #endif if (!handled) { SDL_TouchDeviceType touchType = [self touchTypeForTouch:touch]; SDL_TouchID touchId = [self touchIdForType:touchType]; float pressure = [self pressureForTouch:touch]; if (SDL_AddTouch(touchId, touchType, "") < 0) { continue; } CGPoint locationInView = [self touchLocation:touch shouldNormalize:YES]; SDL_SendTouchMotion(touchId, (SDL_FingerID)((size_t)touch), sdlwindow, locationInView.x, locationInView.y, pressure); } } } #if TARGET_OS_TV || defined(__IPHONE_9_1) - (SDL_Scancode)scancodeFromPress:(UIPress*)press { #ifdef __IPHONE_13_4 if ([press respondsToSelector:@selector((key))]) { if (press.key != nil) { return (SDL_Scancode)press.key.keyCode; } } #endif #if !SDL_JOYSTICK_DISABLED /* Presses from Apple TV remote */ if (!SDL_AppleTVRemoteOpenedAsJoystick) { switch (press.type) { case UIPressTypeUpArrow: return SDL_SCANCODE_UP; case UIPressTypeDownArrow: return SDL_SCANCODE_DOWN; case UIPressTypeLeftArrow: return SDL_SCANCODE_LEFT; case UIPressTypeRightArrow: return SDL_SCANCODE_RIGHT; case UIPressTypeSelect: /* HIG says: "primary button behavior" */ return SDL_SCANCODE_RETURN; case UIPressTypeMenu: /* HIG says: "returns to previous screen" */ return SDL_SCANCODE_ESCAPE; case UIPressTypePlayPause: /* HIG says: "secondary button behavior" */ return SDL_SCANCODE_PAUSE; default: break; } } #endif /* !SDL_JOYSTICK_DISABLED */ return SDL_SCANCODE_UNKNOWN; } - (void)pressesBegan:(NSSet<UIPress *> *)presses withEvent:(UIPressesEvent *)event { for (UIPress *press in presses) { SDL_Scancode scancode = [self scancodeFromPress:press]; SDL_SendKeyboardKey(SDL_PRESSED, scancode); } [super pressesBegan:presses withEvent:event]; } - (void)pressesEnded:(NSSet<UIPress *> *)presses withEvent:(UIPressesEvent *)event { for (UIPress *press in presses) { SDL_Scancode scancode = [self scancodeFromPress:press]; SDL_SendKeyboardKey(SDL_RELEASED, scancode); } [super pressesEnded:presses withEvent:event]; } - (void)pressesCancelled:(NSSet<UIPress *> *)presses withEvent:(UIPressesEvent *)event { for (UIPress *press in presses) { SDL_Scancode scancode = [self scancodeFromPress:press]; SDL_SendKeyboardKey(SDL_RELEASED, scancode); } [super pressesCancelled:presses withEvent:event]; } - (void)pressesChanged:(NSSet<UIPress *> *)presses withEvent:(UIPressesEvent *)event { /* This is only called when the force of a press changes. */ [super pressesChanged:presses withEvent:event]; } #endif /* TARGET_OS_TV || defined(__IPHONE_9_1) */ -(void)mouseWheelGesture:(UIPanGestureRecognizer *)gesture { if (gesture.state == UIGestureRecognizerStateBegan || gesture.state == UIGestureRecognizerStateChanged || gesture.state == UIGestureRecognizerStateEnded) { CGPoint velocity = [gesture velocityInView:self]; if (velocity.x > 0.0f) { velocity.x = -1.0; } else if (velocity.x < 0.0f) { velocity.x = 1.0f; } if (velocity.y > 0.0f) { velocity.y = -1.0; } else if (velocity.y < 0.0f) { velocity.y = 1.0f; } if (velocity.x != 0.0f || velocity.y != 0.0f) { SDL_SendMouseWheel(sdlwindow, 0, velocity.x, velocity.y, SDL_MOUSEWHEEL_NORMAL); } } } #if TARGET_OS_TV -(void)swipeGesture:(UISwipeGestureRecognizer *)gesture { /* Swipe gestures don't trigger begin states. */ if (gesture.state == UIGestureRecognizerStateEnded) { #if !SDL_JOYSTICK_DISABLED if (!SDL_AppleTVRemoteOpenedAsJoystick) { /* Send arrow key presses for now, as we don't have an external API * which better maps to swipe gestures. */ switch (gesture.direction) { case UISwipeGestureRecognizerDirectionUp: SDL_SendKeyboardKeyAutoRelease(SDL_SCANCODE_UP); break; case UISwipeGestureRecognizerDirectionDown: SDL_SendKeyboardKeyAutoRelease(SDL_SCANCODE_DOWN); break; case UISwipeGestureRecognizerDirectionLeft: SDL_SendKeyboardKeyAutoRelease(SDL_SCANCODE_LEFT); break; case UISwipeGestureRecognizerDirectionRight: SDL_SendKeyboardKeyAutoRelease(SDL_SCANCODE_RIGHT); break; } } #endif /* !SDL_JOYSTICK_DISABLED */ } } #endif /* TARGET_OS_TV */ @end #endif /* SDL_VIDEO_DRIVER_UIKIT */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitview.m
Objective-C
apache-2.0
16,892
/* 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" #import <UIKit/UIKit.h> #include "../SDL_sysvideo.h" #include "SDL_touch.h" #if TARGET_OS_TV #import <GameController/GameController.h> #define SDLRootViewController GCEventViewController #else #define SDLRootViewController UIViewController #endif #if SDL_IPHONE_KEYBOARD @interface SDL_uikitviewcontroller : SDLRootViewController <UITextFieldDelegate> #else @interface SDL_uikitviewcontroller : SDLRootViewController #endif @property (nonatomic, assign) SDL_Window *window; - (instancetype)initWithSDLWindow:(SDL_Window *)_window; - (void)setAnimationCallback:(int)interval callback:(void (*)(void*))callback callbackParam:(void*)callbackParam; - (void)startAnimation; - (void)stopAnimation; - (void)doLoop:(CADisplayLink*)sender; - (void)loadView; - (void)viewDidLayoutSubviews; #if !TARGET_OS_TV - (NSUInteger)supportedInterfaceOrientations; - (BOOL)prefersStatusBarHidden; - (BOOL)prefersHomeIndicatorAutoHidden; - (UIRectEdge)preferredScreenEdgesDeferringSystemGestures; @property (nonatomic, assign) int homeIndicatorHidden; #endif #if SDL_IPHONE_KEYBOARD - (void)showKeyboard; - (void)hideKeyboard; - (void)initKeyboard; - (void)deinitKeyboard; - (void)keyboardWillShow:(NSNotification *)notification; - (void)keyboardWillHide:(NSNotification *)notification; - (void)updateKeyboard; @property (nonatomic, assign, getter=isKeyboardVisible) BOOL keyboardVisible; @property (nonatomic, assign) SDL_Rect textInputRect; @property (nonatomic, assign) int keyboardHeight; #endif @end #if SDL_IPHONE_KEYBOARD SDL_bool UIKit_HasScreenKeyboardSupport(_THIS); void UIKit_ShowScreenKeyboard(_THIS, SDL_Window *window); void UIKit_HideScreenKeyboard(_THIS, SDL_Window *window); SDL_bool UIKit_IsScreenKeyboardShown(_THIS, SDL_Window *window); void UIKit_SetTextInputRect(_THIS, SDL_Rect *rect); #endif
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitviewcontroller.h
Objective-C
apache-2.0
2,820
/* 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_VIDEO_DRIVER_UIKIT #include "SDL_video.h" #include "SDL_assert.h" #include "SDL_hints.h" #include "../SDL_sysvideo.h" #include "../../events/SDL_events_c.h" #import "SDL_uikitviewcontroller.h" #import "SDL_uikitmessagebox.h" #include "SDL_uikitvideo.h" #include "SDL_uikitmodes.h" #include "SDL_uikitwindow.h" #include "SDL_uikitopengles.h" #if SDL_IPHONE_KEYBOARD #include "keyinfotable.h" #endif #if TARGET_OS_TV static void SDLCALL SDL_AppleTVControllerUIHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) { @autoreleasepool { SDL_uikitviewcontroller *viewcontroller = (__bridge SDL_uikitviewcontroller *) userdata; viewcontroller.controllerUserInteractionEnabled = hint && (*hint != '0'); } } #endif #if !TARGET_OS_TV static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) { @autoreleasepool { SDL_uikitviewcontroller *viewcontroller = (__bridge SDL_uikitviewcontroller *) userdata; viewcontroller.homeIndicatorHidden = (hint && *hint) ? SDL_atoi(hint) : -1; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunguarded-availability-new" if ([viewcontroller respondsToSelector:@selector(setNeedsUpdateOfHomeIndicatorAutoHidden)]) { [viewcontroller setNeedsUpdateOfHomeIndicatorAutoHidden]; [viewcontroller setNeedsUpdateOfScreenEdgesDeferringSystemGestures]; } #pragma clang diagnostic pop } } #endif @implementation SDL_uikitviewcontroller { CADisplayLink *displayLink; int animationInterval; void (*animationCallback)(void*); void *animationCallbackParam; #if SDL_IPHONE_KEYBOARD UITextField *textField; BOOL hardwareKeyboard; BOOL showingKeyboard; BOOL rotatingOrientation; NSString *changeText; NSString *obligateForBackspace; #endif } @synthesize window; - (instancetype)initWithSDLWindow:(SDL_Window *)_window { if (self = [super initWithNibName:nil bundle:nil]) { self.window = _window; #if SDL_IPHONE_KEYBOARD [self initKeyboard]; hardwareKeyboard = NO; showingKeyboard = NO; rotatingOrientation = NO; #endif #if TARGET_OS_TV SDL_AddHintCallback(SDL_HINT_APPLE_TV_CONTROLLER_UI_EVENTS, SDL_AppleTVControllerUIHintChanged, (__bridge void *) self); #endif #if !TARGET_OS_TV SDL_AddHintCallback(SDL_HINT_IOS_HIDE_HOME_INDICATOR, SDL_HideHomeIndicatorHintChanged, (__bridge void *) self); #endif } return self; } - (void)dealloc { #if SDL_IPHONE_KEYBOARD [self deinitKeyboard]; #endif #if TARGET_OS_TV SDL_DelHintCallback(SDL_HINT_APPLE_TV_CONTROLLER_UI_EVENTS, SDL_AppleTVControllerUIHintChanged, (__bridge void *) self); #endif #if !TARGET_OS_TV SDL_DelHintCallback(SDL_HINT_IOS_HIDE_HOME_INDICATOR, SDL_HideHomeIndicatorHintChanged, (__bridge void *) self); #endif } - (void)setAnimationCallback:(int)interval callback:(void (*)(void*))callback callbackParam:(void*)callbackParam { [self stopAnimation]; animationInterval = interval; animationCallback = callback; animationCallbackParam = callbackParam; if (animationCallback) { [self startAnimation]; } } - (void)startAnimation { displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(doLoop:)]; #ifdef __IPHONE_10_3 SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; if ([displayLink respondsToSelector:@selector(preferredFramesPerSecond)] && data != nil && data.uiwindow != nil && [data.uiwindow.screen respondsToSelector:@selector(maximumFramesPerSecond)]) { displayLink.preferredFramesPerSecond = data.uiwindow.screen.maximumFramesPerSecond / animationInterval; } else #endif { #if __IPHONE_OS_VERSION_MIN_REQUIRED < 100300 [displayLink setFrameInterval:animationInterval]; #endif } [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; } - (void)stopAnimation { [displayLink invalidate]; displayLink = nil; } - (void)doLoop:(CADisplayLink*)sender { /* Don't run the game loop while a messagebox is up */ if (!UIKit_ShowingMessageBox()) { /* See the comment in the function definition. */ #if SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 UIKit_GL_RestoreCurrentContext(); #endif animationCallback(animationCallbackParam); } } - (void)loadView { /* Do nothing. */ } - (void)viewDidLayoutSubviews { const CGSize size = self.view.bounds.size; int w = (int) size.width; int h = (int) size.height; SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESIZED, w, h); } #if !TARGET_OS_TV - (NSUInteger)supportedInterfaceOrientations { return UIKit_GetSupportedOrientations(window); } #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orient { return ([self supportedInterfaceOrientations] & (1 << orient)) != 0; } #endif - (BOOL)prefersStatusBarHidden { BOOL hidden = (window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_BORDERLESS)) != 0; return hidden; } - (BOOL)prefersHomeIndicatorAutoHidden { BOOL hidden = NO; if (self.homeIndicatorHidden == 1) { hidden = YES; } return hidden; } - (UIRectEdge)preferredScreenEdgesDeferringSystemGestures { if (self.homeIndicatorHidden >= 0) { if (self.homeIndicatorHidden == 2) { return UIRectEdgeAll; } else { return UIRectEdgeNone; } } /* By default, fullscreen and borderless windows get all screen gestures */ if ((window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_BORDERLESS)) != 0) { return UIRectEdgeAll; } else { return UIRectEdgeNone; } } #endif /* ---- Keyboard related functionality below this line ---- */ #if SDL_IPHONE_KEYBOARD @synthesize textInputRect; @synthesize keyboardHeight; @synthesize keyboardVisible; /* Set ourselves up as a UITextFieldDelegate */ - (void)initKeyboard { changeText = nil; obligateForBackspace = @" "; /* 64 space */ textField = [[UITextField alloc] initWithFrame:CGRectZero]; textField.delegate = self; /* placeholder so there is something to delete! */ textField.text = obligateForBackspace; /* set UITextInputTrait properties, mostly to defaults */ textField.autocapitalizationType = UITextAutocapitalizationTypeNone; textField.autocorrectionType = UITextAutocorrectionTypeNo; textField.enablesReturnKeyAutomatically = NO; textField.keyboardAppearance = UIKeyboardAppearanceDefault; textField.keyboardType = UIKeyboardTypeDefault; textField.returnKeyType = UIReturnKeyDefault; textField.secureTextEntry = NO; textField.hidden = YES; keyboardVisible = NO; NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; #if !TARGET_OS_TV [center addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [center addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; #endif [center addObserver:self selector:@selector(textFieldTextDidChange:) name:UITextFieldTextDidChangeNotification object:nil]; } - (NSArray *)keyCommands { NSMutableArray *commands = [[NSMutableArray alloc] init]; [commands addObject:[UIKeyCommand keyCommandWithInput:UIKeyInputUpArrow modifierFlags:kNilOptions action:@selector(handleCommand:)]]; [commands addObject:[UIKeyCommand keyCommandWithInput:UIKeyInputDownArrow modifierFlags:kNilOptions action:@selector(handleCommand:)]]; [commands addObject:[UIKeyCommand keyCommandWithInput:UIKeyInputLeftArrow modifierFlags:kNilOptions action:@selector(handleCommand:)]]; [commands addObject:[UIKeyCommand keyCommandWithInput:UIKeyInputRightArrow modifierFlags:kNilOptions action:@selector(handleCommand:)]]; [commands addObject:[UIKeyCommand keyCommandWithInput:UIKeyInputEscape modifierFlags:kNilOptions action:@selector(handleCommand:)]]; return [NSArray arrayWithArray:commands]; } - (void)handleCommand:(UIKeyCommand *)keyCommand { SDL_Scancode scancode = SDL_SCANCODE_UNKNOWN; NSString *input = keyCommand.input; if (input == UIKeyInputUpArrow) { scancode = SDL_SCANCODE_UP; } else if (input == UIKeyInputDownArrow) { scancode = SDL_SCANCODE_DOWN; } else if (input == UIKeyInputLeftArrow) { scancode = SDL_SCANCODE_LEFT; } else if (input == UIKeyInputRightArrow) { scancode = SDL_SCANCODE_RIGHT; } else if (input == UIKeyInputEscape) { scancode = SDL_SCANCODE_ESCAPE; } if (scancode != SDL_SCANCODE_UNKNOWN) { SDL_SendKeyboardKeyAutoRelease(scancode); } } - (void)setView:(UIView *)view { [super setView:view]; [view addSubview:textField]; if (keyboardVisible) { [self showKeyboard]; } } /* willRotateToInterfaceOrientation and didRotateFromInterfaceOrientation are deprecated in iOS 8+ in favor of viewWillTransitionToSize */ #if TARGET_OS_TV || __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000 - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator { [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator]; rotatingOrientation = YES; [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {} completion:^(id<UIViewControllerTransitionCoordinatorContext> context) { self->rotatingOrientation = NO; }]; } #else - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration]; rotatingOrientation = YES; } - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; rotatingOrientation = NO; } #endif /* TARGET_OS_TV || __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000 */ - (void)deinitKeyboard { NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; #if !TARGET_OS_TV [center removeObserver:self name:UIKeyboardWillShowNotification object:nil]; [center removeObserver:self name:UIKeyboardWillHideNotification object:nil]; #endif [center removeObserver:self name:UITextFieldTextDidChangeNotification object:nil]; } /* reveal onscreen virtual keyboard */ - (void)showKeyboard { keyboardVisible = YES; if (textField.window) { showingKeyboard = YES; [textField becomeFirstResponder]; showingKeyboard = NO; } } /* hide onscreen virtual keyboard */ - (void)hideKeyboard { keyboardVisible = NO; [textField resignFirstResponder]; } - (void)keyboardWillShow:(NSNotification *)notification { #if !TARGET_OS_TV CGRect kbrect = [[notification userInfo][UIKeyboardFrameEndUserInfoKey] CGRectValue]; /* The keyboard rect is in the coordinate space of the screen/window, but we * want its height in the coordinate space of the view. */ kbrect = [self.view convertRect:kbrect fromView:nil]; [self setKeyboardHeight:(int)kbrect.size.height]; #endif } - (void)keyboardWillHide:(NSNotification *)notification { if (!showingKeyboard && !rotatingOrientation) { SDL_StopTextInput(); } [self setKeyboardHeight:0]; } - (void)textFieldTextDidChange:(NSNotification *)notification { if (changeText!=nil && textField.markedTextRange == nil) { NSUInteger len = changeText.length; if (len > 0) { if (!SDL_HardwareKeyboardKeyPressed()) { /* Go through all the characters in the string we've been sent and * convert them to key presses */ int i; for (i = 0; i < len; i++) { unichar c = [changeText characterAtIndex:i]; SDL_Scancode code; Uint16 mod; if (c < 127) { /* Figure out the SDL_Scancode and SDL_keymod for this unichar */ code = unicharToUIKeyInfoTable[c].code; mod = unicharToUIKeyInfoTable[c].mod; } else { /* We only deal with ASCII right now */ code = SDL_SCANCODE_UNKNOWN; mod = 0; } if (mod & KMOD_SHIFT) { /* If character uses shift, press shift down */ SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_LSHIFT); } /* send a keydown and keyup even for the character */ SDL_SendKeyboardKey(SDL_PRESSED, code); SDL_SendKeyboardKey(SDL_RELEASED, code); if (mod & KMOD_SHIFT) { /* If character uses shift, press shift back up */ SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_LSHIFT); } } } SDL_SendKeyboardText([changeText UTF8String]); } changeText = nil; } } - (void)updateKeyboard { CGAffineTransform t = self.view.transform; CGPoint offset = CGPointMake(0.0, 0.0); CGRect frame = UIKit_ComputeViewFrame(window, self.view.window.screen); if (self.keyboardHeight) { int rectbottom = self.textInputRect.y + self.textInputRect.h; int keybottom = self.view.bounds.size.height - self.keyboardHeight; if (keybottom < rectbottom) { offset.y = keybottom - rectbottom; } } /* Apply this view's transform (except any translation) to the offset, in * order to orient it correctly relative to the frame's coordinate space. */ t.tx = 0.0; t.ty = 0.0; offset = CGPointApplyAffineTransform(offset, t); /* Apply the updated offset to the view's frame. */ frame.origin.x += offset.x; frame.origin.y += offset.y; self.view.frame = frame; } - (void)setKeyboardHeight:(int)height { keyboardVisible = height > 0; keyboardHeight = height; [self updateKeyboard]; } /* UITextFieldDelegate method. Invoked when user types something. */ - (BOOL)textField:(UITextField *)_textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSUInteger len = string.length; if (len == 0) { changeText = nil; if (textField.markedTextRange == nil) { /* it wants to replace text with nothing, ie a delete */ SDL_SendKeyboardKeyAutoRelease(SDL_SCANCODE_BACKSPACE); } if (textField.text.length < 16) { textField.text = obligateForBackspace; } } else { changeText = string; } return YES; } /* Terminates the editing session */ - (BOOL)textFieldShouldReturn:(UITextField*)_textField { SDL_SendKeyboardKeyAutoRelease(SDL_SCANCODE_RETURN); if (keyboardVisible && SDL_GetHintBoolean(SDL_HINT_RETURN_KEY_HIDES_IME, SDL_FALSE)) { SDL_StopTextInput(); } return YES; } #endif @end /* iPhone keyboard addition functions */ #if SDL_IPHONE_KEYBOARD static SDL_uikitviewcontroller * GetWindowViewController(SDL_Window * window) { if (!window || !window->driverdata) { SDL_SetError("Invalid window"); return nil; } SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; return data.viewcontroller; } SDL_bool UIKit_HasScreenKeyboardSupport(_THIS) { return SDL_TRUE; } void UIKit_ShowScreenKeyboard(_THIS, SDL_Window *window) { @autoreleasepool { SDL_uikitviewcontroller *vc = GetWindowViewController(window); [vc showKeyboard]; } } void UIKit_HideScreenKeyboard(_THIS, SDL_Window *window) { @autoreleasepool { SDL_uikitviewcontroller *vc = GetWindowViewController(window); [vc hideKeyboard]; } } SDL_bool UIKit_IsScreenKeyboardShown(_THIS, SDL_Window *window) { @autoreleasepool { SDL_uikitviewcontroller *vc = GetWindowViewController(window); if (vc != nil) { return vc.keyboardVisible; } return SDL_FALSE; } } void UIKit_SetTextInputRect(_THIS, SDL_Rect *rect) { if (!rect) { SDL_InvalidParamError("rect"); return; } @autoreleasepool { SDL_uikitviewcontroller *vc = GetWindowViewController(SDL_GetFocusWindow()); if (vc != nil) { vc.textInputRect = *rect; if (vc.keyboardVisible) { [vc updateKeyboard]; } } } } #endif /* SDL_IPHONE_KEYBOARD */ #endif /* SDL_VIDEO_DRIVER_UIKIT */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitviewcontroller.m
Objective-C
apache-2.0
18,212
/* 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. */ /* * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's * SDL_x11vulkan.h. */ #include "../../SDL_internal.h" #ifndef SDL_uikitvulkan_h_ #define SDL_uikitvulkan_h_ #include "../SDL_vulkan_internal.h" #include "../SDL_sysvideo.h" #if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_UIKIT int UIKit_Vulkan_LoadLibrary(_THIS, const char *path); void UIKit_Vulkan_UnloadLibrary(_THIS); SDL_bool UIKit_Vulkan_GetInstanceExtensions(_THIS, SDL_Window *window, unsigned *count, const char **names); SDL_bool UIKit_Vulkan_CreateSurface(_THIS, SDL_Window *window, VkInstance instance, VkSurfaceKHR *surface); void UIKit_Vulkan_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h); #endif #endif /* SDL_uikitvulkan_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitvulkan.h
C
apache-2.0
1,944
/* 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. */ /* * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's * SDL_x11vulkan.c. */ #include "../../SDL_internal.h" #if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_UIKIT #include "SDL_uikitvideo.h" #include "SDL_uikitwindow.h" #include "SDL_assert.h" #include "SDL_loadso.h" #include "SDL_uikitvulkan.h" #include "SDL_uikitmetalview.h" #include "SDL_syswm.h" #include <dlfcn.h> const char* defaultPaths[] = { "libvulkan.dylib", }; /* Since libSDL is static, could use RTLD_SELF. Using RTLD_DEFAULT is future * proofing. */ #define DEFAULT_HANDLE RTLD_DEFAULT int UIKit_Vulkan_LoadLibrary(_THIS, const char *path) { VkExtensionProperties *extensions = NULL; Uint32 extensionCount = 0; SDL_bool hasSurfaceExtension = SDL_FALSE; SDL_bool hasIOSSurfaceExtension = SDL_FALSE; PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL; if (_this->vulkan_config.loader_handle) { return SDL_SetError("Vulkan Portability library is already loaded."); } /* Load the Vulkan loader library */ if (!path) { path = SDL_getenv("SDL_VULKAN_LIBRARY"); } if (!path) { /* Handle the case where Vulkan Portability is linked statically. */ vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)dlsym(DEFAULT_HANDLE, "vkGetInstanceProcAddr"); } if (vkGetInstanceProcAddr) { _this->vulkan_config.loader_handle = DEFAULT_HANDLE; } else { const char** paths; const char *foundPath = NULL; int numPaths; int i; if (path) { paths = &path; numPaths = 1; } else { /* Look for the .dylib packaged with the application instead. */ paths = defaultPaths; numPaths = SDL_arraysize(defaultPaths); } for (i = 0; i < numPaths && _this->vulkan_config.loader_handle == NULL; i++) { foundPath = paths[i]; _this->vulkan_config.loader_handle = SDL_LoadObject(foundPath); } if (_this->vulkan_config.loader_handle == NULL) { return SDL_SetError("Failed to load Vulkan Portability library"); } SDL_strlcpy(_this->vulkan_config.loader_path, path, SDL_arraysize(_this->vulkan_config.loader_path)); vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)SDL_LoadFunction( _this->vulkan_config.loader_handle, "vkGetInstanceProcAddr"); } if (!vkGetInstanceProcAddr) { SDL_SetError("Failed to find %s in either executable or %s: %s", "vkGetInstanceProcAddr", "linked Vulkan Portability library", (const char *) dlerror()); goto fail; } _this->vulkan_config.vkGetInstanceProcAddr = (void *)vkGetInstanceProcAddr; _this->vulkan_config.vkEnumerateInstanceExtensionProperties = (void *)((PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr)( VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties"); if (!_this->vulkan_config.vkEnumerateInstanceExtensionProperties) { SDL_SetError("No vkEnumerateInstanceExtensionProperties found."); goto fail; } extensions = SDL_Vulkan_CreateInstanceExtensionsList( (PFN_vkEnumerateInstanceExtensionProperties) _this->vulkan_config.vkEnumerateInstanceExtensionProperties, &extensionCount); if (!extensions) { goto fail; } for (Uint32 i = 0; i < extensionCount; i++) { if (SDL_strcmp(VK_KHR_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0) { hasSurfaceExtension = SDL_TRUE; } else if (SDL_strcmp(VK_MVK_IOS_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0) { hasIOSSurfaceExtension = SDL_TRUE; } } SDL_free(extensions); if (!hasSurfaceExtension) { SDL_SetError("Installed Vulkan Portability doesn't implement the " VK_KHR_SURFACE_EXTENSION_NAME " extension"); goto fail; } else if (!hasIOSSurfaceExtension) { SDL_SetError("Installed Vulkan Portability doesn't implement the " VK_MVK_IOS_SURFACE_EXTENSION_NAME "extension"); goto fail; } return 0; fail: _this->vulkan_config.loader_handle = NULL; return -1; } void UIKit_Vulkan_UnloadLibrary(_THIS) { if (_this->vulkan_config.loader_handle) { if (_this->vulkan_config.loader_handle != DEFAULT_HANDLE) { SDL_UnloadObject(_this->vulkan_config.loader_handle); } _this->vulkan_config.loader_handle = NULL; } } SDL_bool UIKit_Vulkan_GetInstanceExtensions(_THIS, SDL_Window *window, unsigned *count, const char **names) { static const char *const extensionsForUIKit[] = { VK_KHR_SURFACE_EXTENSION_NAME, VK_MVK_IOS_SURFACE_EXTENSION_NAME }; if (!_this->vulkan_config.loader_handle) { SDL_SetError("Vulkan is not loaded"); return SDL_FALSE; } return SDL_Vulkan_GetInstanceExtensions_Helper( count, names, SDL_arraysize(extensionsForUIKit), extensionsForUIKit); } SDL_bool UIKit_Vulkan_CreateSurface(_THIS, SDL_Window *window, VkInstance instance, VkSurfaceKHR *surface) { PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr; PFN_vkCreateIOSSurfaceMVK vkCreateIOSSurfaceMVK = (PFN_vkCreateIOSSurfaceMVK)vkGetInstanceProcAddr( (VkInstance)instance, "vkCreateIOSSurfaceMVK"); VkIOSSurfaceCreateInfoMVK createInfo = {}; VkResult result; SDL_MetalView metalview; if (!_this->vulkan_config.loader_handle) { SDL_SetError("Vulkan is not loaded"); return SDL_FALSE; } if (!vkCreateIOSSurfaceMVK) { SDL_SetError(VK_MVK_IOS_SURFACE_EXTENSION_NAME " extension is not enabled in the Vulkan instance."); return SDL_FALSE; } metalview = UIKit_Metal_CreateView(_this, window); if (metalview == NULL) { return SDL_FALSE; } createInfo.sType = VK_STRUCTURE_TYPE_IOS_SURFACE_CREATE_INFO_MVK; createInfo.pNext = NULL; createInfo.flags = 0; createInfo.pView = (const void *)metalview; result = vkCreateIOSSurfaceMVK(instance, &createInfo, NULL, surface); if (result != VK_SUCCESS) { UIKit_Metal_DestroyView(_this, metalview); SDL_SetError("vkCreateIOSSurfaceMVK failed: %s", SDL_Vulkan_GetResultString(result)); return SDL_FALSE; } /* Unfortunately there's no SDL_Vulkan_DestroySurface function we can call * Metal_DestroyView from. Right now the metal view's ref count is +2 (one * from returning a new view object in CreateView, and one because it's * a subview of the window.) If we release the view here to make it +1, it * will be destroyed when the window is destroyed. */ CFBridgingRelease(metalview); return SDL_TRUE; } void UIKit_Vulkan_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h) { UIKit_Metal_GetDrawableSize(_this, window, w, h); } #endif /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitvulkan.m
Objective-C
apache-2.0
8,591
/* 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_uikitwindow_h_ #define SDL_uikitwindow_h_ #include "../SDL_sysvideo.h" #import "SDL_uikitvideo.h" #import "SDL_uikitview.h" #import "SDL_uikitviewcontroller.h" extern int UIKit_CreateWindow(_THIS, SDL_Window * window); extern void UIKit_SetWindowTitle(_THIS, SDL_Window * window); extern void UIKit_ShowWindow(_THIS, SDL_Window * window); extern void UIKit_HideWindow(_THIS, SDL_Window * window); extern void UIKit_RaiseWindow(_THIS, SDL_Window * window); extern void UIKit_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered); extern void UIKit_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen); extern void UIKit_DestroyWindow(_THIS, SDL_Window * window); extern SDL_bool UIKit_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo * info); extern NSUInteger UIKit_GetSupportedOrientations(SDL_Window * window); @class UIWindow; @interface SDL_WindowData : NSObject @property (nonatomic, strong) UIWindow *uiwindow; @property (nonatomic, strong) SDL_uikitviewcontroller *viewcontroller; /* Array of SDL_uikitviews owned by this window. */ @property (nonatomic, copy) NSMutableArray *views; @end #endif /* SDL_uikitwindow_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitwindow.h
Objective-C
apache-2.0
2,233
/* 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_VIDEO_DRIVER_UIKIT #include "SDL_syswm.h" #include "SDL_video.h" #include "SDL_mouse.h" #include "SDL_assert.h" #include "SDL_hints.h" #include "../SDL_sysvideo.h" #include "../SDL_pixels_c.h" #include "../../events/SDL_events_c.h" #include "SDL_uikitvideo.h" #include "SDL_uikitevents.h" #include "SDL_uikitmodes.h" #include "SDL_uikitwindow.h" #import "SDL_uikitappdelegate.h" #import "SDL_uikitview.h" #import "SDL_uikitopenglview.h" #include <Foundation/Foundation.h> @implementation SDL_WindowData @synthesize uiwindow; @synthesize viewcontroller; @synthesize views; - (instancetype)init { if ((self = [super init])) { views = [NSMutableArray new]; } return self; } @end @interface SDL_uikitwindow : UIWindow - (void)layoutSubviews; @end @implementation SDL_uikitwindow - (void)layoutSubviews { /* Workaround to fix window orientation issues in iOS 8. */ /* As of July 1 2019, I haven't been able to reproduce any orientation * issues with this disabled on iOS 12. The issue this is meant to fix might * only happen on iOS 8, or it might have been fixed another way with other * code... This code prevents split view (iOS 9+) from working on iPads, so * we want to avoid using it if possible. */ if (!UIKit_IsSystemVersionAtLeast(9.0)) { self.frame = self.screen.bounds; } [super layoutSubviews]; } @end static int SetupWindowData(_THIS, SDL_Window *window, UIWindow *uiwindow, SDL_bool created) { SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); SDL_DisplayData *displaydata = (__bridge SDL_DisplayData *) display->driverdata; SDL_uikitview *view; CGRect frame = UIKit_ComputeViewFrame(window, displaydata.uiscreen); int width = (int) frame.size.width; int height = (int) frame.size.height; SDL_WindowData *data = [[SDL_WindowData alloc] init]; if (!data) { return SDL_OutOfMemory(); } window->driverdata = (void *) CFBridgingRetain(data); data.uiwindow = uiwindow; /* only one window on iOS, always shown */ window->flags &= ~SDL_WINDOW_HIDDEN; if (displaydata.uiscreen != [UIScreen mainScreen]) { window->flags &= ~SDL_WINDOW_RESIZABLE; /* window is NEVER resizable */ window->flags &= ~SDL_WINDOW_INPUT_FOCUS; /* never has input focus */ window->flags |= SDL_WINDOW_BORDERLESS; /* never has a status bar. */ } #if !TARGET_OS_TV if (displaydata.uiscreen == [UIScreen mainScreen]) { /* SDL_CreateWindow sets the window w&h to the display's bounds if the * fullscreen flag is set. But the display bounds orientation might not * match what we want, and GetSupportedOrientations call below uses the * window w&h. They're overridden below anyway, so we'll just set them * to the requested size for the purposes of determining orientation. */ window->w = window->windowed.w; window->h = window->windowed.h; NSUInteger orients = UIKit_GetSupportedOrientations(window); BOOL supportsLandscape = (orients & UIInterfaceOrientationMaskLandscape) != 0; BOOL supportsPortrait = (orients & (UIInterfaceOrientationMaskPortrait|UIInterfaceOrientationMaskPortraitUpsideDown)) != 0; /* Make sure the width/height are oriented correctly */ if ((width > height && !supportsLandscape) || (height > width && !supportsPortrait)) { int temp = width; width = height; height = temp; } } #endif /* !TARGET_OS_TV */ window->x = 0; window->y = 0; window->w = width; window->h = height; /* The View Controller will handle rotating the view when the device * orientation changes. This will trigger resize events, if appropriate. */ data.viewcontroller = [[SDL_uikitviewcontroller alloc] initWithSDLWindow:window]; /* The window will initially contain a generic view so resizes, touch events, * etc. can be handled without an active OpenGL view/context. */ view = [[SDL_uikitview alloc] initWithFrame:frame]; /* Sets this view as the controller's view, and adds the view to the window * heirarchy. */ [view setSDLWindow:window]; return 0; } int UIKit_CreateWindow(_THIS, SDL_Window *window) { @autoreleasepool { SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata; /* SDL currently puts this window at the start of display's linked list. We rely on this. */ SDL_assert(_this->windows == window); /* We currently only handle a single window per display on iOS */ if (window->next != NULL) { return SDL_SetError("Only one window allowed per display."); } /* If monitor has a resolution of 0x0 (hasn't been explicitly set by the * user, so it's in standby), try to force the display to a resolution * that most closely matches the desired window size. */ #if !TARGET_OS_TV const CGSize origsize = data.uiscreen.currentMode.size; if ((origsize.width == 0.0f) && (origsize.height == 0.0f)) { if (display->num_display_modes == 0) { _this->GetDisplayModes(_this, display); } int i; const SDL_DisplayMode *bestmode = NULL; for (i = display->num_display_modes; i >= 0; i--) { const SDL_DisplayMode *mode = &display->display_modes[i]; if ((mode->w >= window->w) && (mode->h >= window->h)) { bestmode = mode; } } if (bestmode) { SDL_DisplayModeData *modedata = (__bridge SDL_DisplayModeData *)bestmode->driverdata; [data.uiscreen setCurrentMode:modedata.uiscreenmode]; /* desktop_mode doesn't change here (the higher level will * use it to set all the screens back to their defaults * upon window destruction, SDL_Quit(), etc. */ display->current_mode = *bestmode; } } if (data.uiscreen == [UIScreen mainScreen]) { if (window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_BORDERLESS)) { [UIApplication sharedApplication].statusBarHidden = YES; } else { [UIApplication sharedApplication].statusBarHidden = NO; } } #endif /* !TARGET_OS_TV */ /* ignore the size user requested, and make a fullscreen window */ /* !!! FIXME: can we have a smaller view? */ UIWindow *uiwindow = [[SDL_uikitwindow alloc] initWithFrame:data.uiscreen.bounds]; /* put the window on an external display if appropriate. */ if (data.uiscreen != [UIScreen mainScreen]) { [uiwindow setScreen:data.uiscreen]; } if (SetupWindowData(_this, window, uiwindow, SDL_TRUE) < 0) { return -1; } } return 1; } void UIKit_SetWindowTitle(_THIS, SDL_Window * window) { @autoreleasepool { SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; data.viewcontroller.title = @(window->title); } } void UIKit_ShowWindow(_THIS, SDL_Window * window) { @autoreleasepool { SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; [data.uiwindow makeKeyAndVisible]; /* Make this window the current mouse focus for touch input */ SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); SDL_DisplayData *displaydata = (__bridge SDL_DisplayData *) display->driverdata; if (displaydata.uiscreen == [UIScreen mainScreen]) { SDL_SetMouseFocus(window); SDL_SetKeyboardFocus(window); } } } void UIKit_HideWindow(_THIS, SDL_Window * window) { @autoreleasepool { SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; data.uiwindow.hidden = YES; } } void UIKit_RaiseWindow(_THIS, SDL_Window * window) { /* We don't currently offer a concept of "raising" the SDL window, since * we only allow one per display, in the iOS fashion. * However, we use this entry point to rebind the context to the view * during OnWindowRestored processing. */ _this->GL_MakeCurrent(_this, _this->current_glwin, _this->current_glctx); } static void UIKit_UpdateWindowBorder(_THIS, SDL_Window * window) { SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; SDL_uikitviewcontroller *viewcontroller = data.viewcontroller; #if !TARGET_OS_TV if (data.uiwindow.screen == [UIScreen mainScreen]) { if (window->flags & (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS)) { [UIApplication sharedApplication].statusBarHidden = YES; } else { [UIApplication sharedApplication].statusBarHidden = NO; } /* iOS 7+ won't update the status bar until we tell it to. */ if ([viewcontroller respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) { [viewcontroller setNeedsStatusBarAppearanceUpdate]; } } /* Update the view's frame to account for the status bar change. */ viewcontroller.view.frame = UIKit_ComputeViewFrame(window, data.uiwindow.screen); #endif /* !TARGET_OS_TV */ #ifdef SDL_IPHONE_KEYBOARD /* Make sure the view is offset correctly when the keyboard is visible. */ [viewcontroller updateKeyboard]; #endif [viewcontroller.view setNeedsLayout]; [viewcontroller.view layoutIfNeeded]; } void UIKit_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered) { @autoreleasepool { UIKit_UpdateWindowBorder(_this, window); } } void UIKit_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen) { @autoreleasepool { UIKit_UpdateWindowBorder(_this, window); } } void UIKit_DestroyWindow(_THIS, SDL_Window * window) { @autoreleasepool { if (window->driverdata != NULL) { SDL_WindowData *data = (SDL_WindowData *) CFBridgingRelease(window->driverdata); NSArray *views = nil; [data.viewcontroller stopAnimation]; /* Detach all views from this window. We use a copy of the array * because setSDLWindow will remove the object from the original * array, which would be undesirable if we were iterating over it. */ views = [data.views copy]; for (SDL_uikitview *view in views) { [view setSDLWindow:NULL]; } /* iOS may still hold a reference to the window after we release it. * We want to make sure the SDL view controller isn't accessed in * that case, because it would contain an invalid pointer to the old * SDL window. */ data.uiwindow.rootViewController = nil; data.uiwindow.hidden = YES; } } window->driverdata = NULL; } SDL_bool UIKit_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info) { @autoreleasepool { SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; if (info->version.major <= SDL_MAJOR_VERSION) { int versionnum = SDL_VERSIONNUM(info->version.major, info->version.minor, info->version.patch); info->subsystem = SDL_SYSWM_UIKIT; info->info.uikit.window = data.uiwindow; /* These struct members were added in SDL 2.0.4. */ if (versionnum >= SDL_VERSIONNUM(2,0,4)) { #if SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 if ([data.viewcontroller.view isKindOfClass:[SDL_uikitopenglview class]]) { SDL_uikitopenglview *glview = (SDL_uikitopenglview *)data.viewcontroller.view; info->info.uikit.framebuffer = glview.drawableFramebuffer; info->info.uikit.colorbuffer = glview.drawableRenderbuffer; info->info.uikit.resolveFramebuffer = glview.msaaResolveFramebuffer; } else { #else { #endif info->info.uikit.framebuffer = 0; info->info.uikit.colorbuffer = 0; info->info.uikit.resolveFramebuffer = 0; } } return SDL_TRUE; } else { SDL_SetError("Application not compiled with SDL %d.%d", SDL_MAJOR_VERSION, SDL_MINOR_VERSION); return SDL_FALSE; } } } #if !TARGET_OS_TV NSUInteger UIKit_GetSupportedOrientations(SDL_Window * window) { const char *hint = SDL_GetHint(SDL_HINT_ORIENTATIONS); NSUInteger validOrientations = UIInterfaceOrientationMaskAll; NSUInteger orientationMask = 0; @autoreleasepool { SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; UIApplication *app = [UIApplication sharedApplication]; /* Get all possible valid orientations. If the app delegate doesn't tell * us, we get the orientations from Info.plist via UIApplication. */ if ([app.delegate respondsToSelector:@selector(application:supportedInterfaceOrientationsForWindow:)]) { validOrientations = [app.delegate application:app supportedInterfaceOrientationsForWindow:data.uiwindow]; } else if ([app respondsToSelector:@selector(supportedInterfaceOrientationsForWindow:)]) { validOrientations = [app supportedInterfaceOrientationsForWindow:data.uiwindow]; } if (hint != NULL) { NSArray *orientations = [@(hint) componentsSeparatedByString:@" "]; if ([orientations containsObject:@"LandscapeLeft"]) { orientationMask |= UIInterfaceOrientationMaskLandscapeLeft; } if ([orientations containsObject:@"LandscapeRight"]) { orientationMask |= UIInterfaceOrientationMaskLandscapeRight; } if ([orientations containsObject:@"Portrait"]) { orientationMask |= UIInterfaceOrientationMaskPortrait; } if ([orientations containsObject:@"PortraitUpsideDown"]) { orientationMask |= UIInterfaceOrientationMaskPortraitUpsideDown; } } if (orientationMask == 0 && (window->flags & SDL_WINDOW_RESIZABLE)) { /* any orientation is okay. */ orientationMask = UIInterfaceOrientationMaskAll; } if (orientationMask == 0) { if (window->w >= window->h) { orientationMask |= UIInterfaceOrientationMaskLandscape; } if (window->h >= window->w) { orientationMask |= (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown); } } /* Don't allow upside-down orientation on phones, so answering calls is in the natural orientation */ if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone) { orientationMask &= ~UIInterfaceOrientationMaskPortraitUpsideDown; } /* If none of the specified orientations are actually supported by the * app, we'll revert to what the app supports. An exception would be * thrown by the system otherwise. */ if ((validOrientations & orientationMask) == 0) { orientationMask = validOrientations; } } return orientationMask; } #endif /* !TARGET_OS_TV */ int SDL_iPhoneSetAnimationCallback(SDL_Window * window, int interval, void (*callback)(void*), void *callbackParam) { if (!window || !window->driverdata) { return SDL_SetError("Invalid window"); } @autoreleasepool { SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; [data.viewcontroller setAnimationCallback:interval callback:callback callbackParam:callbackParam]; } return 0; } #endif /* SDL_VIDEO_DRIVER_UIKIT */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/SDL_uikitwindow.m
Objective-C
apache-2.0
17,144
/* 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 _UIKIT_KeyInfo #define _UIKIT_KeyInfo #include "SDL_scancode.h" /* This file is used by the keyboard code in SDL_uikitview.m to convert between characters passed in from the iPhone's virtual keyboard, and tuples of SDL_Scancode and SDL_keymods. For example unicharToUIKeyInfoTable['a'] would give you the scan code and keymod for lower case a. */ typedef struct { SDL_Scancode code; Uint16 mod; } UIKitKeyInfo; /* So far only ASCII characters here */ static UIKitKeyInfo unicharToUIKeyInfoTable[] = { /* 0 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 1 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 2 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 3 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 4 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 5 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 6 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 7 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 8 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 9 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 10 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 11 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 12 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 13 */ { SDL_SCANCODE_RETURN, 0 }, /* 14 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 15 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 16 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 17 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 18 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 19 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 20 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 21 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 22 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 23 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 24 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 25 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 26 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 27 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 28 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 29 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 30 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 31 */ { SDL_SCANCODE_UNKNOWN, 0 }, /* 32 */ { SDL_SCANCODE_SPACE, 0 }, /* 33 */ { SDL_SCANCODE_1, KMOD_SHIFT }, /* plus shift modifier '!' */ /* 34 */ { SDL_SCANCODE_APOSTROPHE, KMOD_SHIFT }, /* plus shift modifier '"' */ /* 35 */ { SDL_SCANCODE_3, KMOD_SHIFT }, /* plus shift modifier '#' */ /* 36 */ { SDL_SCANCODE_4, KMOD_SHIFT }, /* plus shift modifier '$' */ /* 37 */ { SDL_SCANCODE_5, KMOD_SHIFT }, /* plus shift modifier '%' */ /* 38 */ { SDL_SCANCODE_7, KMOD_SHIFT }, /* plus shift modifier '&' */ /* 39 */ { SDL_SCANCODE_APOSTROPHE, 0 }, /* ''' */ /* 40 */ { SDL_SCANCODE_9, KMOD_SHIFT }, /* plus shift modifier '(' */ /* 41 */ { SDL_SCANCODE_0, KMOD_SHIFT }, /* plus shift modifier ')' */ /* 42 */ { SDL_SCANCODE_8, KMOD_SHIFT }, /* '*' */ /* 43 */ { SDL_SCANCODE_EQUALS, KMOD_SHIFT }, /* plus shift modifier '+' */ /* 44 */ { SDL_SCANCODE_COMMA, 0 }, /* ',' */ /* 45 */ { SDL_SCANCODE_MINUS, 0 }, /* '-' */ /* 46 */ { SDL_SCANCODE_PERIOD, 0 }, /* '.' */ /* 47 */ { SDL_SCANCODE_SLASH, 0 }, /* '/' */ /* 48 */ { SDL_SCANCODE_0, 0 }, /* 49 */ { SDL_SCANCODE_1, 0 }, /* 50 */ { SDL_SCANCODE_2, 0 }, /* 51 */ { SDL_SCANCODE_3, 0 }, /* 52 */ { SDL_SCANCODE_4, 0 }, /* 53 */ { SDL_SCANCODE_5, 0 }, /* 54 */ { SDL_SCANCODE_6, 0 }, /* 55 */ { SDL_SCANCODE_7, 0 }, /* 56 */ { SDL_SCANCODE_8, 0 }, /* 57 */ { SDL_SCANCODE_9, 0 }, /* 58 */ { SDL_SCANCODE_SEMICOLON, KMOD_SHIFT }, /* plus shift modifier ';' */ /* 59 */ { SDL_SCANCODE_SEMICOLON, 0 }, /* 60 */ { SDL_SCANCODE_COMMA, KMOD_SHIFT }, /* plus shift modifier '<' */ /* 61 */ { SDL_SCANCODE_EQUALS, 0 }, /* 62 */ { SDL_SCANCODE_PERIOD, KMOD_SHIFT }, /* plus shift modifier '>' */ /* 63 */ { SDL_SCANCODE_SLASH, KMOD_SHIFT }, /* plus shift modifier '?' */ /* 64 */ { SDL_SCANCODE_2, KMOD_SHIFT }, /* plus shift modifier '@' */ /* 65 */ { SDL_SCANCODE_A, KMOD_SHIFT }, /* all the following need shift modifiers */ /* 66 */ { SDL_SCANCODE_B, KMOD_SHIFT }, /* 67 */ { SDL_SCANCODE_C, KMOD_SHIFT }, /* 68 */ { SDL_SCANCODE_D, KMOD_SHIFT }, /* 69 */ { SDL_SCANCODE_E, KMOD_SHIFT }, /* 70 */ { SDL_SCANCODE_F, KMOD_SHIFT }, /* 71 */ { SDL_SCANCODE_G, KMOD_SHIFT }, /* 72 */ { SDL_SCANCODE_H, KMOD_SHIFT }, /* 73 */ { SDL_SCANCODE_I, KMOD_SHIFT }, /* 74 */ { SDL_SCANCODE_J, KMOD_SHIFT }, /* 75 */ { SDL_SCANCODE_K, KMOD_SHIFT }, /* 76 */ { SDL_SCANCODE_L, KMOD_SHIFT }, /* 77 */ { SDL_SCANCODE_M, KMOD_SHIFT }, /* 78 */ { SDL_SCANCODE_N, KMOD_SHIFT }, /* 79 */ { SDL_SCANCODE_O, KMOD_SHIFT }, /* 80 */ { SDL_SCANCODE_P, KMOD_SHIFT }, /* 81 */ { SDL_SCANCODE_Q, KMOD_SHIFT }, /* 82 */ { SDL_SCANCODE_R, KMOD_SHIFT }, /* 83 */ { SDL_SCANCODE_S, KMOD_SHIFT }, /* 84 */ { SDL_SCANCODE_T, KMOD_SHIFT }, /* 85 */ { SDL_SCANCODE_U, KMOD_SHIFT }, /* 86 */ { SDL_SCANCODE_V, KMOD_SHIFT }, /* 87 */ { SDL_SCANCODE_W, KMOD_SHIFT }, /* 88 */ { SDL_SCANCODE_X, KMOD_SHIFT }, /* 89 */ { SDL_SCANCODE_Y, KMOD_SHIFT }, /* 90 */ { SDL_SCANCODE_Z, KMOD_SHIFT }, /* 91 */ { SDL_SCANCODE_LEFTBRACKET, 0 }, /* 92 */ { SDL_SCANCODE_BACKSLASH, 0 }, /* 93 */ { SDL_SCANCODE_RIGHTBRACKET, 0 }, /* 94 */ { SDL_SCANCODE_6, KMOD_SHIFT }, /* plus shift modifier '^' */ /* 95 */ { SDL_SCANCODE_MINUS, KMOD_SHIFT }, /* plus shift modifier '_' */ /* 96 */ { SDL_SCANCODE_GRAVE, KMOD_SHIFT }, /* '`' */ /* 97 */ { SDL_SCANCODE_A, 0 }, /* 98 */ { SDL_SCANCODE_B, 0 }, /* 99 */ { SDL_SCANCODE_C, 0 }, /* 100 */{ SDL_SCANCODE_D, 0 }, /* 101 */{ SDL_SCANCODE_E, 0 }, /* 102 */{ SDL_SCANCODE_F, 0 }, /* 103 */{ SDL_SCANCODE_G, 0 }, /* 104 */{ SDL_SCANCODE_H, 0 }, /* 105 */{ SDL_SCANCODE_I, 0 }, /* 106 */{ SDL_SCANCODE_J, 0 }, /* 107 */{ SDL_SCANCODE_K, 0 }, /* 108 */{ SDL_SCANCODE_L, 0 }, /* 109 */{ SDL_SCANCODE_M, 0 }, /* 110 */{ SDL_SCANCODE_N, 0 }, /* 111 */{ SDL_SCANCODE_O, 0 }, /* 112 */{ SDL_SCANCODE_P, 0 }, /* 113 */{ SDL_SCANCODE_Q, 0 }, /* 114 */{ SDL_SCANCODE_R, 0 }, /* 115 */{ SDL_SCANCODE_S, 0 }, /* 116 */{ SDL_SCANCODE_T, 0 }, /* 117 */{ SDL_SCANCODE_U, 0 }, /* 118 */{ SDL_SCANCODE_V, 0 }, /* 119 */{ SDL_SCANCODE_W, 0 }, /* 120 */{ SDL_SCANCODE_X, 0 }, /* 121 */{ SDL_SCANCODE_Y, 0 }, /* 122 */{ SDL_SCANCODE_Z, 0 }, /* 123 */{ SDL_SCANCODE_LEFTBRACKET, KMOD_SHIFT }, /* plus shift modifier '{' */ /* 124 */{ SDL_SCANCODE_BACKSLASH, KMOD_SHIFT }, /* plus shift modifier '|' */ /* 125 */{ SDL_SCANCODE_RIGHTBRACKET, KMOD_SHIFT }, /* plus shift modifier '}' */ /* 126 */{ SDL_SCANCODE_GRAVE, KMOD_SHIFT }, /* plus shift modifier '~' */ /* 127 */{ SDL_SCANCODE_BACKSPACE, KMOD_SHIFT } }; #endif /* _UIKIT_KeyInfo */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/uikit/keyinfotable.h
C
apache-2.0
7,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" #if SDL_VIDEO_DRIVER_VIVANTE && SDL_VIDEO_OPENGL_EGL #include "SDL_vivanteopengles.h" #include "SDL_vivantevideo.h" /* EGL implementation of SDL OpenGL support */ int VIVANTE_GLES_LoadLibrary(_THIS, const char *path) { SDL_DisplayData *displaydata; displaydata = SDL_GetDisplayDriverData(0); return SDL_EGL_LoadLibrary(_this, path, displaydata->native_display, 0); } SDL_EGL_CreateContext_impl(VIVANTE) SDL_EGL_SwapWindow_impl(VIVANTE) SDL_EGL_MakeCurrent_impl(VIVANTE) #endif /* SDL_VIDEO_DRIVER_VIVANTE && SDL_VIDEO_OPENGL_EGL */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/vivante/SDL_vivanteopengles.c
C
apache-2.0
1,560
/* 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_vivanteopengles_h_ #define SDL_vivanteopengles_h_ #if SDL_VIDEO_DRIVER_VIVANTE && SDL_VIDEO_OPENGL_EGL #include "../SDL_sysvideo.h" #include "../SDL_egl_c.h" /* OpenGLES functions */ #define VIVANTE_GLES_GetAttribute SDL_EGL_GetAttribute #define VIVANTE_GLES_GetProcAddress SDL_EGL_GetProcAddress #define VIVANTE_GLES_UnloadLibrary SDL_EGL_UnloadLibrary #define VIVANTE_GLES_SetSwapInterval SDL_EGL_SetSwapInterval #define VIVANTE_GLES_GetSwapInterval SDL_EGL_GetSwapInterval #define VIVANTE_GLES_DeleteContext SDL_EGL_DeleteContext extern int VIVANTE_GLES_LoadLibrary(_THIS, const char *path); extern SDL_GLContext VIVANTE_GLES_CreateContext(_THIS, SDL_Window * window); extern int VIVANTE_GLES_SwapWindow(_THIS, SDL_Window * window); extern int VIVANTE_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context); #endif /* SDL_VIDEO_DRIVER_VIVANTE && SDL_VIDEO_OPENGL_EGL */ #endif /* SDL_vivanteopengles_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/vivante/SDL_vivanteopengles.h
C
apache-2.0
1,948
/* 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_VIDEO_DRIVER_VIVANTE #include "SDL_vivanteplatform.h" #ifdef VIVANTE_PLATFORM_GENERIC int VIVANTE_SetupPlatform(_THIS) { return 0; } char *VIVANTE_GetDisplayName(_THIS) { return NULL; } void VIVANTE_UpdateDisplayScale(_THIS) { } void VIVANTE_CleanupPlatform(_THIS) { } #endif /* VIVANTE_PLATFORM_GENERIC */ #endif /* SDL_VIDEO_DRIVER_VIVANTE */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/vivante/SDL_vivanteplatform.c
C
apache-2.0
1,377
/* 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_vivanteplatform_h_ #define SDL_vivanteplatform_h_ #if SDL_VIDEO_DRIVER_VIVANTE #include "SDL_vivantevideo.h" #if defined(CAVIUM) #define VIVANTE_PLATFORM_CAVIUM #elif defined(MARVELL) #define VIVANTE_PLATFORM_MARVELL #else #define VIVANTE_PLATFORM_GENERIC #endif extern int VIVANTE_SetupPlatform(_THIS); extern char *VIVANTE_GetDisplayName(_THIS); extern void VIVANTE_UpdateDisplayScale(_THIS); extern void VIVANTE_CleanupPlatform(_THIS); #endif /* SDL_VIDEO_DRIVER_VIVANTE */ #endif /* SDL_vivanteplatform_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/vivante/SDL_vivanteplatform.h
C
apache-2.0
1,539
/* 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_VIDEO_DRIVER_VIVANTE /* SDL internals */ #include "../SDL_sysvideo.h" #include "SDL_version.h" #include "SDL_syswm.h" #include "SDL_loadso.h" #include "SDL_events.h" #include "../../events/SDL_events_c.h" #ifdef SDL_INPUT_LINUXEV #include "../../core/linux/SDL_evdev.h" #endif #include "SDL_vivantevideo.h" #include "SDL_vivanteplatform.h" #include "SDL_vivanteopengles.h" #include "SDL_vivantevulkan.h" static int VIVANTE_Available(void) { return 1; } static void VIVANTE_Destroy(SDL_VideoDevice * device) { if (device->driverdata != NULL) { SDL_free(device->driverdata); device->driverdata = NULL; } } static SDL_VideoDevice * VIVANTE_Create() { SDL_VideoDevice *device; SDL_VideoData *data; /* Initialize SDL_VideoDevice structure */ device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice)); if (device == NULL) { SDL_OutOfMemory(); return NULL; } /* Initialize internal data */ data = (SDL_VideoData *) SDL_calloc(1, sizeof(SDL_VideoData)); if (data == NULL) { SDL_OutOfMemory(); SDL_free(device); return NULL; } device->driverdata = data; /* Setup amount of available displays */ device->num_displays = 0; /* Set device free function */ device->free = VIVANTE_Destroy; /* Setup all functions which we can handle */ device->VideoInit = VIVANTE_VideoInit; device->VideoQuit = VIVANTE_VideoQuit; device->GetDisplayModes = VIVANTE_GetDisplayModes; device->SetDisplayMode = VIVANTE_SetDisplayMode; device->CreateSDLWindow = VIVANTE_CreateWindow; device->SetWindowTitle = VIVANTE_SetWindowTitle; device->SetWindowPosition = VIVANTE_SetWindowPosition; device->SetWindowSize = VIVANTE_SetWindowSize; device->ShowWindow = VIVANTE_ShowWindow; device->HideWindow = VIVANTE_HideWindow; device->DestroyWindow = VIVANTE_DestroyWindow; device->GetWindowWMInfo = VIVANTE_GetWindowWMInfo; #if SDL_VIDEO_OPENGL_EGL device->GL_LoadLibrary = VIVANTE_GLES_LoadLibrary; device->GL_GetProcAddress = VIVANTE_GLES_GetProcAddress; device->GL_UnloadLibrary = VIVANTE_GLES_UnloadLibrary; device->GL_CreateContext = VIVANTE_GLES_CreateContext; device->GL_MakeCurrent = VIVANTE_GLES_MakeCurrent; device->GL_SetSwapInterval = VIVANTE_GLES_SetSwapInterval; device->GL_GetSwapInterval = VIVANTE_GLES_GetSwapInterval; device->GL_SwapWindow = VIVANTE_GLES_SwapWindow; device->GL_DeleteContext = VIVANTE_GLES_DeleteContext; #endif #if SDL_VIDEO_VULKAN device->Vulkan_LoadLibrary = VIVANTE_Vulkan_LoadLibrary; device->Vulkan_UnloadLibrary = VIVANTE_Vulkan_UnloadLibrary; device->Vulkan_GetInstanceExtensions = VIVANTE_Vulkan_GetInstanceExtensions; device->Vulkan_CreateSurface = VIVANTE_Vulkan_CreateSurface; #endif device->PumpEvents = VIVANTE_PumpEvents; return device; } VideoBootStrap VIVANTE_bootstrap = { "vivante", "Vivante EGL Video Driver", VIVANTE_Available, VIVANTE_Create }; /*****************************************************************************/ /* SDL Video and Display initialization/handling functions */ /*****************************************************************************/ static int VIVANTE_AddVideoDisplays(_THIS) { SDL_VideoData *videodata = _this->driverdata; SDL_VideoDisplay display; SDL_DisplayMode current_mode; SDL_DisplayData *data; int pitch = 0, bpp = 0; unsigned long pixels = 0; data = (SDL_DisplayData *) SDL_calloc(1, sizeof(SDL_DisplayData)); if (data == NULL) { return SDL_OutOfMemory(); } SDL_zero(current_mode); #if SDL_VIDEO_DRIVER_VIVANTE_VDK data->native_display = vdkGetDisplay(videodata->vdk_private); vdkGetDisplayInfo(data->native_display, &current_mode.w, &current_mode.h, &pixels, &pitch, &bpp); #else data->native_display = videodata->fbGetDisplayByIndex(0); videodata->fbGetDisplayInfo(data->native_display, &current_mode.w, &current_mode.h, &pixels, &pitch, &bpp); #endif /* SDL_VIDEO_DRIVER_VIVANTE_VDK */ switch (bpp) { default: /* Is another format used? */ case 32: current_mode.format = SDL_PIXELFORMAT_ARGB8888; break; case 16: current_mode.format = SDL_PIXELFORMAT_RGB565; break; } /* FIXME: How do we query refresh rate? */ current_mode.refresh_rate = 60; SDL_zero(display); display.name = VIVANTE_GetDisplayName(_this); display.desktop_mode = current_mode; display.current_mode = current_mode; display.driverdata = data; SDL_AddVideoDisplay(&display); return 0; } int VIVANTE_VideoInit(_THIS) { SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; #if SDL_VIDEO_DRIVER_VIVANTE_VDK videodata->vdk_private = vdkInitialize(); if (!videodata->vdk_private) { return SDL_SetError("vdkInitialize() failed"); } #else videodata->egl_handle = SDL_LoadObject("libEGL.so.1"); if (!videodata->egl_handle) { videodata->egl_handle = SDL_LoadObject("libEGL.so"); if (!videodata->egl_handle) { return -1; } } #define LOAD_FUNC(NAME) \ videodata->NAME = SDL_LoadFunction(videodata->egl_handle, #NAME); \ if (!videodata->NAME) return -1; LOAD_FUNC(fbGetDisplay); LOAD_FUNC(fbGetDisplayByIndex); LOAD_FUNC(fbGetDisplayGeometry); LOAD_FUNC(fbGetDisplayInfo); LOAD_FUNC(fbDestroyDisplay); LOAD_FUNC(fbCreateWindow); LOAD_FUNC(fbGetWindowGeometry); LOAD_FUNC(fbGetWindowInfo); LOAD_FUNC(fbDestroyWindow); #endif if (VIVANTE_SetupPlatform(_this) < 0) { return -1; } if (VIVANTE_AddVideoDisplays(_this) < 0) { return -1; } VIVANTE_UpdateDisplayScale(_this); #ifdef SDL_INPUT_LINUXEV if (SDL_EVDEV_Init() < 0) { return -1; } #endif return 0; } void VIVANTE_VideoQuit(_THIS) { SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; #ifdef SDL_INPUT_LINUXEV SDL_EVDEV_Quit(); #endif VIVANTE_CleanupPlatform(_this); #if SDL_VIDEO_DRIVER_VIVANTE_VDK if (videodata->vdk_private) { vdkExit(videodata->vdk_private); videodata->vdk_private = NULL; } #else if (videodata->egl_handle) { SDL_UnloadObject(videodata->egl_handle); videodata->egl_handle = NULL; } #endif } void VIVANTE_GetDisplayModes(_THIS, SDL_VideoDisplay * display) { /* Only one display mode available, the current one */ SDL_AddDisplayMode(display, &display->current_mode); } int VIVANTE_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode) { return 0; } int VIVANTE_CreateWindow(_THIS, SDL_Window * window) { SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; SDL_DisplayData *displaydata; SDL_WindowData *data; displaydata = SDL_GetDisplayDriverData(0); /* Allocate window internal data */ data = (SDL_WindowData *) SDL_calloc(1, sizeof(SDL_WindowData)); if (data == NULL) { return SDL_OutOfMemory(); } /* Setup driver data for this window */ window->driverdata = data; #if SDL_VIDEO_DRIVER_VIVANTE_VDK data->native_window = vdkCreateWindow(displaydata->native_display, window->x, window->y, window->w, window->h); #else data->native_window = videodata->fbCreateWindow(displaydata->native_display, window->x, window->y, window->w, window->h); #endif if (!data->native_window) { return SDL_SetError("VIVANTE: Can't create native window"); } #if SDL_VIDEO_OPENGL_EGL if (window->flags & SDL_WINDOW_OPENGL) { data->egl_surface = SDL_EGL_CreateSurface(_this, data->native_window); if (data->egl_surface == EGL_NO_SURFACE) { return SDL_SetError("VIVANTE: Can't create EGL surface"); } } else { data->egl_surface = EGL_NO_SURFACE; } #endif /* Window has been successfully created */ return 0; } void VIVANTE_DestroyWindow(_THIS, SDL_Window * window) { SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; SDL_WindowData *data; data = window->driverdata; if (data) { #if SDL_VIDEO_OPENGL_EGL if (data->egl_surface != EGL_NO_SURFACE) { SDL_EGL_DestroySurface(_this, data->egl_surface); } #endif if (data->native_window) { #if SDL_VIDEO_DRIVER_VIVANTE_VDK vdkDestroyWindow(data->native_window); #else videodata->fbDestroyWindow(data->native_window); #endif } SDL_free(data); } window->driverdata = NULL; } void VIVANTE_SetWindowTitle(_THIS, SDL_Window * window) { #if SDL_VIDEO_DRIVER_VIVANTE_VDK SDL_WindowData *data = window->driverdata; vdkSetWindowTitle(data->native_window, window->title); #endif } void VIVANTE_SetWindowPosition(_THIS, SDL_Window * window) { /* FIXME */ } void VIVANTE_SetWindowSize(_THIS, SDL_Window * window) { /* FIXME */ } void VIVANTE_ShowWindow(_THIS, SDL_Window * window) { #if SDL_VIDEO_DRIVER_VIVANTE_VDK SDL_WindowData *data = window->driverdata; vdkShowWindow(data->native_window); #endif SDL_SetMouseFocus(window); SDL_SetKeyboardFocus(window); } void VIVANTE_HideWindow(_THIS, SDL_Window * window) { #if SDL_VIDEO_DRIVER_VIVANTE_VDK SDL_WindowData *data = window->driverdata; vdkHideWindow(data->native_window); #endif } /*****************************************************************************/ /* SDL Window Manager function */ /*****************************************************************************/ SDL_bool VIVANTE_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; SDL_DisplayData *displaydata = SDL_GetDisplayDriverData(0); if (info->version.major == SDL_MAJOR_VERSION && info->version.minor == SDL_MINOR_VERSION) { info->subsystem = SDL_SYSWM_VIVANTE; info->info.vivante.display = displaydata->native_display; info->info.vivante.window = data->native_window; return SDL_TRUE; } else { SDL_SetError("Application not compiled with SDL %d.%d", SDL_MAJOR_VERSION, SDL_MINOR_VERSION); return SDL_FALSE; } } /*****************************************************************************/ /* SDL event functions */ /*****************************************************************************/ void VIVANTE_PumpEvents(_THIS) { #ifdef SDL_INPUT_LINUXEV SDL_EVDEV_Poll(); #endif } #endif /* SDL_VIDEO_DRIVER_VIVANTE */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/vivante/SDL_vivantevideo.c
C
apache-2.0
11,722
/* 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_vivantevideo_h_ #define SDL_vivantevideo_h_ #include "../../SDL_internal.h" #include "../SDL_sysvideo.h" #include "SDL_egl.h" #if SDL_VIDEO_DRIVER_VIVANTE_VDK #include <gc_vdk.h> #else #include <EGL/egl.h> #endif typedef struct SDL_VideoData { #if SDL_VIDEO_DRIVER_VIVANTE_VDK vdkPrivate vdk_private; #else void *egl_handle; /* EGL shared library handle */ EGLNativeDisplayType (EGLAPIENTRY *fbGetDisplay)(void *context); EGLNativeDisplayType (EGLAPIENTRY *fbGetDisplayByIndex)(int DisplayIndex); void (EGLAPIENTRY *fbGetDisplayGeometry)(EGLNativeDisplayType Display, int *Width, int *Height); void (EGLAPIENTRY *fbGetDisplayInfo)(EGLNativeDisplayType Display, int *Width, int *Height, unsigned long *Physical, int *Stride, int *BitsPerPixel); void (EGLAPIENTRY *fbDestroyDisplay)(EGLNativeDisplayType Display); EGLNativeWindowType (EGLAPIENTRY *fbCreateWindow)(EGLNativeDisplayType Display, int X, int Y, int Width, int Height); void (EGLAPIENTRY *fbGetWindowGeometry)(EGLNativeWindowType Window, int *X, int *Y, int *Width, int *Height); void (EGLAPIENTRY *fbGetWindowInfo)(EGLNativeWindowType Window, int *X, int *Y, int *Width, int *Height, int *BitsPerPixel, unsigned int *Offset); void (EGLAPIENTRY *fbDestroyWindow)(EGLNativeWindowType Window); #endif } SDL_VideoData; typedef struct SDL_DisplayData { EGLNativeDisplayType native_display; } SDL_DisplayData; typedef struct SDL_WindowData { EGLNativeWindowType native_window; EGLSurface egl_surface; } SDL_WindowData; /****************************************************************************/ /* SDL_VideoDevice functions declaration */ /****************************************************************************/ /* Display and window functions */ int VIVANTE_VideoInit(_THIS); void VIVANTE_VideoQuit(_THIS); void VIVANTE_GetDisplayModes(_THIS, SDL_VideoDisplay * display); int VIVANTE_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode); int VIVANTE_CreateWindow(_THIS, SDL_Window * window); void VIVANTE_SetWindowTitle(_THIS, SDL_Window * window); void VIVANTE_SetWindowPosition(_THIS, SDL_Window * window); void VIVANTE_SetWindowSize(_THIS, SDL_Window * window); void VIVANTE_ShowWindow(_THIS, SDL_Window * window); void VIVANTE_HideWindow(_THIS, SDL_Window * window); void VIVANTE_DestroyWindow(_THIS, SDL_Window * window); /* Window manager function */ SDL_bool VIVANTE_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info); /* Event functions */ void VIVANTE_PumpEvents(_THIS); #endif /* SDL_vivantevideo_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/vivante/SDL_vivantevideo.h
C
apache-2.0
3,639
/* 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. */ /* * @author Wladimir J. van der Laan. Based on Jacob Lifshay's * SDL_x11vulkan.c, Mark Callow's SDL_androidvulkan.c, and * the FSL demo framework. */ #include "../../SDL_internal.h" #if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_VIVANTE #include "SDL_vivantevideo.h" #include "SDL_assert.h" #include "SDL_loadso.h" #include "SDL_vivantevulkan.h" #include "SDL_syswm.h" int VIVANTE_Vulkan_LoadLibrary(_THIS, const char *path) { VkExtensionProperties *extensions = NULL; Uint32 i, extensionCount = 0; SDL_bool hasSurfaceExtension = SDL_FALSE; SDL_bool hasDisplayExtension = SDL_FALSE; PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL; if(_this->vulkan_config.loader_handle) return SDL_SetError("Vulkan already loaded"); /* Load the Vulkan loader library */ if(!path) path = SDL_getenv("SDL_VULKAN_LIBRARY"); if(!path) { /* If no path set, try Vivante fb vulkan driver explicitly */ path = "libvulkan-fb.so"; _this->vulkan_config.loader_handle = SDL_LoadObject(path); if(!_this->vulkan_config.loader_handle) { /* If that couldn't be loaded, fall back to default name */ path = "libvulkan.so"; _this->vulkan_config.loader_handle = SDL_LoadObject(path); } } else { _this->vulkan_config.loader_handle = SDL_LoadObject(path); } if(!_this->vulkan_config.loader_handle) return -1; SDL_strlcpy(_this->vulkan_config.loader_path, path, SDL_arraysize(_this->vulkan_config.loader_path)); SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "vivante: Loaded vulkan driver %s", path); vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)SDL_LoadFunction( _this->vulkan_config.loader_handle, "vkGetInstanceProcAddr"); if(!vkGetInstanceProcAddr) goto fail; _this->vulkan_config.vkGetInstanceProcAddr = (void *)vkGetInstanceProcAddr; _this->vulkan_config.vkEnumerateInstanceExtensionProperties = (void *)((PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr)( VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties"); if(!_this->vulkan_config.vkEnumerateInstanceExtensionProperties) goto fail; extensions = SDL_Vulkan_CreateInstanceExtensionsList( (PFN_vkEnumerateInstanceExtensionProperties) _this->vulkan_config.vkEnumerateInstanceExtensionProperties, &extensionCount); if(!extensions) goto fail; for(i = 0; i < extensionCount; i++) { if(SDL_strcmp(VK_KHR_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0) hasSurfaceExtension = SDL_TRUE; else if(SDL_strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, extensions[i].extensionName) == 0) hasDisplayExtension = SDL_TRUE; } SDL_free(extensions); if(!hasSurfaceExtension) { SDL_SetError("Installed Vulkan doesn't implement the " VK_KHR_SURFACE_EXTENSION_NAME " extension"); goto fail; } else if(!hasDisplayExtension) { SDL_SetError("Installed Vulkan doesn't implement the " VK_KHR_DISPLAY_EXTENSION_NAME "extension"); goto fail; } return 0; fail: SDL_UnloadObject(_this->vulkan_config.loader_handle); _this->vulkan_config.loader_handle = NULL; return -1; } void VIVANTE_Vulkan_UnloadLibrary(_THIS) { if(_this->vulkan_config.loader_handle) { SDL_UnloadObject(_this->vulkan_config.loader_handle); _this->vulkan_config.loader_handle = NULL; } } SDL_bool VIVANTE_Vulkan_GetInstanceExtensions(_THIS, SDL_Window *window, unsigned *count, const char **names) { static const char *const extensionsForVivante[] = { VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_DISPLAY_EXTENSION_NAME }; if(!_this->vulkan_config.loader_handle) { SDL_SetError("Vulkan is not loaded"); return SDL_FALSE; } return SDL_Vulkan_GetInstanceExtensions_Helper( count, names, SDL_arraysize(extensionsForVivante), extensionsForVivante); } SDL_bool VIVANTE_Vulkan_CreateSurface(_THIS, SDL_Window *window, VkInstance instance, VkSurfaceKHR *surface) { if(!_this->vulkan_config.loader_handle) { SDL_SetError("Vulkan is not loaded"); return SDL_FALSE; } return SDL_Vulkan_Display_CreateSurface(_this->vulkan_config.vkGetInstanceProcAddr, instance, surface); } #endif /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/vivante/SDL_vivantevulkan.c
C
apache-2.0
5,667
/* 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. */ /* * @author Wladimir J. van der Laan. Based on Jacob Lifshay's * SDL_x11vulkan.h and Mark Callow's SDL_vivantevulkan.h */ #include "../../SDL_internal.h" #ifndef SDL_vivantevulkan_h_ #define SDL_vivantevulkan_h_ #include "../SDL_vulkan_internal.h" #include "../SDL_sysvideo.h" #if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_VIVANTE int VIVANTE_Vulkan_LoadLibrary(_THIS, const char *path); void VIVANTE_Vulkan_UnloadLibrary(_THIS); SDL_bool VIVANTE_Vulkan_GetInstanceExtensions(_THIS, SDL_Window *window, unsigned *count, const char **names); SDL_bool VIVANTE_Vulkan_CreateSurface(_THIS, SDL_Window *window, VkInstance instance, VkSurfaceKHR *surface); #endif #endif /* SDL_vivantevulkan_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/vivante/SDL_vivantevulkan.h
C
apache-2.0
1,904
/* 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_VIDEO_DRIVER_WAYLAND #include "SDL_waylanddatamanager.h" #include "SDL_waylandevents_c.h" int Wayland_SetClipboardText(_THIS, const char *text) { SDL_VideoData *video_data = NULL; SDL_WaylandDataDevice *data_device = NULL; int status = 0; if (_this == NULL || _this->driverdata == NULL) { status = SDL_SetError("Video driver uninitialized"); } else { video_data = _this->driverdata; /* TODO: Support more than one seat */ data_device = Wayland_get_data_device(video_data->input); if (text[0] != '\0') { SDL_WaylandDataSource* source = Wayland_data_source_create(_this); Wayland_data_source_add_data(source, TEXT_MIME, text, strlen(text) + 1); status = Wayland_data_device_set_selection(data_device, source); if (status != 0) { Wayland_data_source_destroy(source); } } else { status = Wayland_data_device_clear_selection(data_device); } } return status; } char * Wayland_GetClipboardText(_THIS) { SDL_VideoData *video_data = NULL; SDL_WaylandDataDevice *data_device = NULL; char *text = NULL; void *buffer = NULL; size_t length = 0; if (_this == NULL || _this->driverdata == NULL) { SDL_SetError("Video driver uninitialized"); } else { video_data = _this->driverdata; /* TODO: Support more than one seat */ data_device = Wayland_get_data_device(video_data->input); if (data_device->selection_offer != NULL) { buffer = Wayland_data_offer_receive(data_device->selection_offer, &length, TEXT_MIME, SDL_TRUE); if (length > 0) { text = (char*) buffer; } } else if (data_device->selection_source != NULL) { buffer = Wayland_data_source_get_data(data_device->selection_source, &length, TEXT_MIME, SDL_TRUE); if (length > 0) { text = (char*) buffer; } } } if (text == NULL) { text = SDL_strdup(""); } return text; } SDL_bool Wayland_HasClipboardText(_THIS) { SDL_VideoData *video_data = NULL; SDL_WaylandDataDevice *data_device = NULL; SDL_bool result = SDL_FALSE; if (_this == NULL || _this->driverdata == NULL) { SDL_SetError("Video driver uninitialized"); } else { video_data = _this->driverdata; data_device = Wayland_get_data_device(video_data->input); if (data_device != NULL && Wayland_data_offer_has_mime( data_device->selection_offer, TEXT_MIME)) { result = SDL_TRUE; } else if(data_device != NULL && Wayland_data_source_has_mime( data_device->selection_source, TEXT_MIME)) { result = SDL_TRUE; } } return result; } #endif /* SDL_VIDEO_DRIVER_WAYLAND */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylandclipboard.c
C
apache-2.0
4,055
/* 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_waylandclipboard_h_ #define SDL_waylandclipboard_h_ extern int Wayland_SetClipboardText(_THIS, const char *text); extern char *Wayland_GetClipboardText(_THIS); extern SDL_bool Wayland_HasClipboardText(_THIS); #endif /* SDL_waylandclipboard_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylandclipboard.h
C
apache-2.0
1,268
/* 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_VIDEO_DRIVER_WAYLAND #include <fcntl.h> #include <unistd.h> #include <limits.h> #include <signal.h> #include "SDL_stdinc.h" #include "SDL_assert.h" #include "../../core/unix/SDL_poll.h" #include "SDL_waylandvideo.h" #include "SDL_waylanddatamanager.h" #include "SDL_waylanddyn.h" static ssize_t write_pipe(int fd, const void* buffer, size_t total_length, size_t *pos) { int ready = 0; ssize_t bytes_written = 0; ssize_t length = total_length - *pos; sigset_t sig_set; sigset_t old_sig_set; struct timespec zerotime = {0}; ready = SDL_IOReady(fd, SDL_TRUE, 1 * 1000); sigemptyset(&sig_set); sigaddset(&sig_set, SIGPIPE); #if SDL_THREADS_DISABLED sigprocmask(SIG_BLOCK, &sig_set, &old_sig_set); #else pthread_sigmask(SIG_BLOCK, &sig_set, &old_sig_set); #endif if (ready == 0) { bytes_written = SDL_SetError("Pipe timeout"); } else if (ready < 0) { bytes_written = SDL_SetError("Pipe select error"); } else { if (length > 0) { bytes_written = write(fd, (Uint8*)buffer + *pos, SDL_min(length, PIPE_BUF)); } if (bytes_written > 0) { *pos += bytes_written; } } sigtimedwait(&sig_set, 0, &zerotime); #if SDL_THREADS_DISABLED sigprocmask(SIG_SETMASK, &old_sig_set, NULL); #else pthread_sigmask(SIG_SETMASK, &old_sig_set, NULL); #endif return bytes_written; } static ssize_t read_pipe(int fd, void** buffer, size_t* total_length, SDL_bool null_terminate) { int ready = 0; void* output_buffer = NULL; char temp[PIPE_BUF]; size_t new_buffer_length = 0; ssize_t bytes_read = 0; size_t pos = 0; ready = SDL_IOReady(fd, SDL_FALSE, 1 * 1000); if (ready == 0) { bytes_read = SDL_SetError("Pipe timeout"); } else if (ready < 0) { bytes_read = SDL_SetError("Pipe select error"); } else { bytes_read = read(fd, temp, sizeof(temp)); } if (bytes_read > 0) { pos = *total_length; *total_length += bytes_read; if (null_terminate == SDL_TRUE) { new_buffer_length = *total_length + 1; } else { new_buffer_length = *total_length; } if (*buffer == NULL) { output_buffer = SDL_malloc(new_buffer_length); } else { output_buffer = SDL_realloc(*buffer, new_buffer_length); } if (output_buffer == NULL) { bytes_read = SDL_OutOfMemory(); } else { SDL_memcpy((Uint8*)output_buffer + pos, temp, bytes_read); if (null_terminate == SDL_TRUE) { SDL_memset((Uint8*)output_buffer + (new_buffer_length - 1), 0, 1); } *buffer = output_buffer; } } return bytes_read; } #define MIME_LIST_SIZE 4 static const char* mime_conversion_list[MIME_LIST_SIZE][2] = { {"text/plain", TEXT_MIME}, {"TEXT", TEXT_MIME}, {"UTF8_STRING", TEXT_MIME}, {"STRING", TEXT_MIME} }; const char* Wayland_convert_mime_type(const char *mime_type) { const char *found = mime_type; size_t index = 0; for (index = 0; index < MIME_LIST_SIZE; ++index) { if (strcmp(mime_conversion_list[index][0], mime_type) == 0) { found = mime_conversion_list[index][1]; break; } } return found; } static SDL_MimeDataList* mime_data_list_find(struct wl_list* list, const char* mime_type) { SDL_MimeDataList *found = NULL; SDL_MimeDataList *mime_list = NULL; wl_list_for_each(mime_list, list, link) { if (strcmp(mime_list->mime_type, mime_type) == 0) { found = mime_list; break; } } return found; } static int mime_data_list_add(struct wl_list* list, const char* mime_type, void* buffer, size_t length) { int status = 0; size_t mime_type_length = 0; SDL_MimeDataList *mime_data = NULL; void *internal_buffer = NULL; if (buffer != NULL) { internal_buffer = SDL_malloc(length); if (internal_buffer == NULL) { return SDL_OutOfMemory(); } SDL_memcpy(internal_buffer, buffer, length); } mime_data = mime_data_list_find(list, mime_type); if (mime_data == NULL) { mime_data = SDL_calloc(1, sizeof(*mime_data)); if (mime_data == NULL) { status = SDL_OutOfMemory(); } else { WAYLAND_wl_list_insert(list, &(mime_data->link)); mime_type_length = strlen(mime_type) + 1; mime_data->mime_type = SDL_malloc(mime_type_length); if (mime_data->mime_type == NULL) { status = SDL_OutOfMemory(); } else { SDL_memcpy(mime_data->mime_type, mime_type, mime_type_length); } } } if (mime_data != NULL && buffer != NULL && length > 0) { if (mime_data->data != NULL) { SDL_free(mime_data->data); } mime_data->data = internal_buffer; mime_data->length = length; } else { SDL_free(internal_buffer); } return status; } static void mime_data_list_free(struct wl_list *list) { SDL_MimeDataList *mime_data = NULL; SDL_MimeDataList *next = NULL; wl_list_for_each_safe(mime_data, next, list, link) { if (mime_data->data != NULL) { SDL_free(mime_data->data); } if (mime_data->mime_type != NULL) { SDL_free(mime_data->mime_type); } SDL_free(mime_data); } } ssize_t Wayland_data_source_send(SDL_WaylandDataSource *source, const char *mime_type, int fd) { size_t written_bytes = 0; ssize_t status = 0; SDL_MimeDataList *mime_data = NULL; mime_type = Wayland_convert_mime_type(mime_type); mime_data = mime_data_list_find(&source->mimes, mime_type); if (mime_data == NULL || mime_data->data == NULL) { status = SDL_SetError("Invalid mime type"); close(fd); } else { while (write_pipe(fd, mime_data->data, mime_data->length, &written_bytes) > 0); close(fd); status = written_bytes; } return status; } int Wayland_data_source_add_data(SDL_WaylandDataSource *source, const char *mime_type, const void *buffer, size_t length) { return mime_data_list_add(&source->mimes, mime_type, buffer, length); } SDL_bool Wayland_data_source_has_mime(SDL_WaylandDataSource *source, const char *mime_type) { SDL_bool found = SDL_FALSE; if (source != NULL) { found = mime_data_list_find(&source->mimes, mime_type) != NULL; } return found; } void* Wayland_data_source_get_data(SDL_WaylandDataSource *source, size_t *length, const char* mime_type, SDL_bool null_terminate) { SDL_MimeDataList *mime_data = NULL; void *buffer = NULL; *length = 0; if (source == NULL) { SDL_SetError("Invalid data source"); } else { mime_data = mime_data_list_find(&source->mimes, mime_type); if (mime_data != NULL && mime_data->length > 0) { buffer = SDL_malloc(mime_data->length); if (buffer == NULL) { *length = SDL_OutOfMemory(); } else { *length = mime_data->length; SDL_memcpy(buffer, mime_data->data, mime_data->length); } } } return buffer; } void Wayland_data_source_destroy(SDL_WaylandDataSource *source) { if (source != NULL) { wl_data_source_destroy(source->source); mime_data_list_free(&source->mimes); SDL_free(source); } } void* Wayland_data_offer_receive(SDL_WaylandDataOffer *offer, size_t *length, const char* mime_type, SDL_bool null_terminate) { SDL_WaylandDataDevice *data_device = NULL; int pipefd[2]; void *buffer = NULL; *length = 0; if (offer == NULL) { SDL_SetError("Invalid data offer"); } else if ((data_device = offer->data_device) == NULL) { SDL_SetError("Data device not initialized"); } else if (pipe2(pipefd, O_CLOEXEC|O_NONBLOCK) == -1) { SDL_SetError("Could not read pipe"); } else { wl_data_offer_receive(offer->offer, mime_type, pipefd[1]); /* TODO: Needs pump and flush? */ WAYLAND_wl_display_flush(data_device->video_data->display); close(pipefd[1]); while (read_pipe(pipefd[0], &buffer, length, null_terminate) > 0); close(pipefd[0]); } return buffer; } int Wayland_data_offer_add_mime(SDL_WaylandDataOffer *offer, const char* mime_type) { return mime_data_list_add(&offer->mimes, mime_type, NULL, 0); } SDL_bool Wayland_data_offer_has_mime(SDL_WaylandDataOffer *offer, const char *mime_type) { SDL_bool found = SDL_FALSE; if (offer != NULL) { found = mime_data_list_find(&offer->mimes, mime_type) != NULL; } return found; } void Wayland_data_offer_destroy(SDL_WaylandDataOffer *offer) { if (offer != NULL) { wl_data_offer_destroy(offer->offer); mime_data_list_free(&offer->mimes); SDL_free(offer); } } int Wayland_data_device_clear_selection(SDL_WaylandDataDevice *data_device) { int status = 0; if (data_device == NULL || data_device->data_device == NULL) { status = SDL_SetError("Invalid Data Device"); } else if (data_device->selection_source != 0) { wl_data_device_set_selection(data_device->data_device, NULL, 0); data_device->selection_source = NULL; } return status; } int Wayland_data_device_set_selection(SDL_WaylandDataDevice *data_device, SDL_WaylandDataSource *source) { int status = 0; size_t num_offers = 0; size_t index = 0; if (data_device == NULL) { status = SDL_SetError("Invalid Data Device"); } else if (source == NULL) { status = SDL_SetError("Invalid source"); } else { SDL_MimeDataList *mime_data = NULL; wl_list_for_each(mime_data, &(source->mimes), link) { wl_data_source_offer(source->source, mime_data->mime_type); /* TODO - Improve system for multiple mime types to same data */ for (index = 0; index < MIME_LIST_SIZE; ++index) { if (strcmp(mime_conversion_list[index][1], mime_data->mime_type) == 0) { wl_data_source_offer(source->source, mime_conversion_list[index][0]); } } /* */ ++num_offers; } if (num_offers == 0) { Wayland_data_device_clear_selection(data_device); status = SDL_SetError("No mime data"); } else { /* Only set if there is a valid serial if not set it later */ if (data_device->selection_serial != 0) { wl_data_device_set_selection(data_device->data_device, source->source, data_device->selection_serial); } data_device->selection_source = source; } } return status; } int Wayland_data_device_set_serial(SDL_WaylandDataDevice *data_device, uint32_t serial) { int status = -1; if (data_device != NULL) { status = 0; /* If there was no serial and there is a pending selection set it now. */ if (data_device->selection_serial == 0 && data_device->selection_source != NULL) { wl_data_device_set_selection(data_device->data_device, data_device->selection_source->source, serial); } data_device->selection_serial = serial; } return status; } #endif /* SDL_VIDEO_DRIVER_WAYLAND */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylanddatamanager.c
C
apache-2.0
13,390
/* 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_waylanddatamanager_h_ #define SDL_waylanddatamanager_h_ #include "SDL_waylandvideo.h" #include "SDL_waylandwindow.h" #define TEXT_MIME "text/plain;charset=utf-8" #define FILE_MIME "text/uri-list" typedef struct { char *mime_type; void *data; size_t length; struct wl_list link; } SDL_MimeDataList; typedef struct { struct wl_data_source *source; struct wl_list mimes; } SDL_WaylandDataSource; typedef struct { struct wl_data_offer *offer; struct wl_list mimes; void *data_device; } SDL_WaylandDataOffer; typedef struct { struct wl_data_device *data_device; SDL_VideoData *video_data; /* Drag and Drop */ uint32_t drag_serial; SDL_WaylandDataOffer *drag_offer; SDL_WaylandDataOffer *selection_offer; /* Clipboard */ uint32_t selection_serial; SDL_WaylandDataSource *selection_source; } SDL_WaylandDataDevice; extern const char* Wayland_convert_mime_type(const char *mime_type); /* Wayland Data Source - (Sending) */ extern SDL_WaylandDataSource* Wayland_data_source_create(_THIS); extern ssize_t Wayland_data_source_send(SDL_WaylandDataSource *source, const char *mime_type, int fd); extern int Wayland_data_source_add_data(SDL_WaylandDataSource *source, const char *mime_type, const void *buffer, size_t length); extern SDL_bool Wayland_data_source_has_mime(SDL_WaylandDataSource *source, const char *mime_type); extern void* Wayland_data_source_get_data(SDL_WaylandDataSource *source, size_t *length, const char *mime_type, SDL_bool null_terminate); extern void Wayland_data_source_destroy(SDL_WaylandDataSource *source); /* Wayland Data Offer - (Receiving) */ extern void* Wayland_data_offer_receive(SDL_WaylandDataOffer *offer, size_t *length, const char *mime_type, SDL_bool null_terminate); extern SDL_bool Wayland_data_offer_has_mime(SDL_WaylandDataOffer *offer, const char *mime_type); extern int Wayland_data_offer_add_mime(SDL_WaylandDataOffer *offer, const char *mime_type); extern void Wayland_data_offer_destroy(SDL_WaylandDataOffer *offer); /* Clipboard */ extern int Wayland_data_device_clear_selection(SDL_WaylandDataDevice *device); extern int Wayland_data_device_set_selection(SDL_WaylandDataDevice *device, SDL_WaylandDataSource *source); extern int Wayland_data_device_set_serial(SDL_WaylandDataDevice *device, uint32_t serial); #endif /* SDL_waylanddatamanager_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylanddatamanager.h
C
apache-2.0
4,017
/* 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_VIDEO_DRIVER_WAYLAND #define DEBUG_DYNAMIC_WAYLAND 0 #include "SDL_waylanddyn.h" #ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC #include "SDL_name.h" #include "SDL_loadso.h" typedef struct { void *lib; const char *libname; } waylanddynlib; #ifndef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_EGL #define SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_EGL NULL #endif #ifndef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_CURSOR #define SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_CURSOR NULL #endif #ifndef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_XKBCOMMON #define SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_XKBCOMMON NULL #endif static waylanddynlib waylandlibs[] = { {NULL, SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC}, {NULL, SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_EGL}, {NULL, SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_CURSOR}, {NULL, SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_XKBCOMMON} }; static void * WAYLAND_GetSym(const char *fnname, int *pHasModule) { int i; void *fn = NULL; for (i = 0; i < SDL_TABLESIZE(waylandlibs); i++) { if (waylandlibs[i].lib != NULL) { fn = SDL_LoadFunction(waylandlibs[i].lib, fnname); if (fn != NULL) break; } } #if DEBUG_DYNAMIC_WAYLAND if (fn != NULL) SDL_Log("WAYLAND: Found '%s' in %s (%p)\n", fnname, waylandlibs[i].libname, fn); else SDL_Log("WAYLAND: Symbol '%s' NOT FOUND!\n", fnname); #endif if (fn == NULL) *pHasModule = 0; /* kill this module. */ return fn; } #endif /* SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC */ /* Define all the function pointers and wrappers... */ #define SDL_WAYLAND_MODULE(modname) int SDL_WAYLAND_HAVE_##modname = 0; #define SDL_WAYLAND_SYM(rc,fn,params) SDL_DYNWAYLANDFN_##fn WAYLAND_##fn = NULL; #define SDL_WAYLAND_INTERFACE(iface) const struct wl_interface *WAYLAND_##iface = NULL; #include "SDL_waylandsym.h" static int wayland_load_refcount = 0; void SDL_WAYLAND_UnloadSymbols(void) { /* Don't actually unload if more than one module is using the libs... */ if (wayland_load_refcount > 0) { if (--wayland_load_refcount == 0) { #ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC int i; #endif /* set all the function pointers to NULL. */ #define SDL_WAYLAND_MODULE(modname) SDL_WAYLAND_HAVE_##modname = 0; #define SDL_WAYLAND_SYM(rc,fn,params) WAYLAND_##fn = NULL; #define SDL_WAYLAND_INTERFACE(iface) WAYLAND_##iface = NULL; #include "SDL_waylandsym.h" #ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC for (i = 0; i < SDL_TABLESIZE(waylandlibs); i++) { if (waylandlibs[i].lib != NULL) { SDL_UnloadObject(waylandlibs[i].lib); waylandlibs[i].lib = NULL; } } #endif } } } /* returns non-zero if all needed symbols were loaded. */ int SDL_WAYLAND_LoadSymbols(void) { int rc = 1; /* always succeed if not using Dynamic WAYLAND stuff. */ /* deal with multiple modules (dga, wayland, etc) needing these symbols... */ if (wayland_load_refcount++ == 0) { #ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC int i; int *thismod = NULL; for (i = 0; i < SDL_TABLESIZE(waylandlibs); i++) { if (waylandlibs[i].libname != NULL) { waylandlibs[i].lib = SDL_LoadObject(waylandlibs[i].libname); } } #define SDL_WAYLAND_MODULE(modname) SDL_WAYLAND_HAVE_##modname = 1; /* default yes */ #include "SDL_waylandsym.h" #define SDL_WAYLAND_MODULE(modname) thismod = &SDL_WAYLAND_HAVE_##modname; #define SDL_WAYLAND_SYM(rc,fn,params) WAYLAND_##fn = (SDL_DYNWAYLANDFN_##fn) WAYLAND_GetSym(#fn,thismod); #define SDL_WAYLAND_INTERFACE(iface) WAYLAND_##iface = (struct wl_interface *) WAYLAND_GetSym(#iface,thismod); #include "SDL_waylandsym.h" if (SDL_WAYLAND_HAVE_WAYLAND_CLIENT) { /* all required symbols loaded. */ SDL_ClearError(); } else { /* in case something got loaded... */ SDL_WAYLAND_UnloadSymbols(); rc = 0; } #else /* no dynamic WAYLAND */ #define SDL_WAYLAND_MODULE(modname) SDL_WAYLAND_HAVE_##modname = 1; /* default yes */ #define SDL_WAYLAND_SYM(rc,fn,params) WAYLAND_##fn = fn; #define SDL_WAYLAND_INTERFACE(iface) WAYLAND_##iface = &iface; #include "SDL_waylandsym.h" #endif } return rc; } #endif /* SDL_VIDEO_DRIVER_WAYLAND */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylanddyn.c
C
apache-2.0
5,395
/* 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_waylanddyn_h_ #define SDL_waylanddyn_h_ #include "../../SDL_internal.h" /* We can't include wayland-client.h here * but we need some structs from it */ struct wl_interface; struct wl_proxy; struct wl_event_queue; struct wl_display; struct wl_surface; struct wl_shm; #include <stdint.h> #include "wayland-cursor.h" #include "wayland-util.h" #include "xkbcommon/xkbcommon.h" #ifdef __cplusplus extern "C" { #endif int SDL_WAYLAND_LoadSymbols(void); void SDL_WAYLAND_UnloadSymbols(void); #define SDL_WAYLAND_MODULE(modname) extern int SDL_WAYLAND_HAVE_##modname; #define SDL_WAYLAND_SYM(rc,fn,params) \ typedef rc (*SDL_DYNWAYLANDFN_##fn) params; \ extern SDL_DYNWAYLANDFN_##fn WAYLAND_##fn; #define SDL_WAYLAND_INTERFACE(iface) extern const struct wl_interface *WAYLAND_##iface; #include "SDL_waylandsym.h" #ifdef __cplusplus } #endif /* Must be included before our #defines, see Bugzilla #4957 */ #include "wayland-client-core.h" #ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC #ifdef _WAYLAND_CLIENT_H #error Do not include wayland-client ahead of SDL_waylanddyn.h in dynamic loading mode #endif /* wayland-client-protocol.h included from wayland-client.h * has inline functions that require these to be defined in dynamic loading mode */ #define wl_proxy_create (*WAYLAND_wl_proxy_create) #define wl_proxy_destroy (*WAYLAND_wl_proxy_destroy) #define wl_proxy_marshal (*WAYLAND_wl_proxy_marshal) #define wl_proxy_set_user_data (*WAYLAND_wl_proxy_set_user_data) #define wl_proxy_get_user_data (*WAYLAND_wl_proxy_get_user_data) #define wl_proxy_get_version (*WAYLAND_wl_proxy_get_version) #define wl_proxy_add_listener (*WAYLAND_wl_proxy_add_listener) #define wl_proxy_marshal_constructor (*WAYLAND_wl_proxy_marshal_constructor) #define wl_proxy_marshal_constructor_versioned (*WAYLAND_wl_proxy_marshal_constructor_versioned) #define wl_seat_interface (*WAYLAND_wl_seat_interface) #define wl_surface_interface (*WAYLAND_wl_surface_interface) #define wl_shm_pool_interface (*WAYLAND_wl_shm_pool_interface) #define wl_buffer_interface (*WAYLAND_wl_buffer_interface) #define wl_registry_interface (*WAYLAND_wl_registry_interface) #define wl_shell_surface_interface (*WAYLAND_wl_shell_surface_interface) #define wl_region_interface (*WAYLAND_wl_region_interface) #define wl_pointer_interface (*WAYLAND_wl_pointer_interface) #define wl_keyboard_interface (*WAYLAND_wl_keyboard_interface) #define wl_compositor_interface (*WAYLAND_wl_compositor_interface) #define wl_output_interface (*WAYLAND_wl_output_interface) #define wl_shell_interface (*WAYLAND_wl_shell_interface) #define wl_shm_interface (*WAYLAND_wl_shm_interface) #define wl_data_device_interface (*WAYLAND_wl_data_device_interface) #define wl_data_offer_interface (*WAYLAND_wl_data_offer_interface) #define wl_data_source_interface (*WAYLAND_wl_data_source_interface) #define wl_data_device_manager_interface (*WAYLAND_wl_data_device_manager_interface) #endif /* SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC */ #include "wayland-client-protocol.h" #include "wayland-egl.h" #endif /* SDL_waylanddyn_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylanddyn.h
C
apache-2.0
4,056
/* 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_VIDEO_DRIVER_WAYLAND #include "SDL_stdinc.h" #include "SDL_assert.h" #include "../../core/unix/SDL_poll.h" #include "../../events/SDL_sysevents.h" #include "../../events/SDL_events_c.h" #include "../../events/scancodes_xfree86.h" #include "SDL_waylandvideo.h" #include "SDL_waylandevents_c.h" #include "SDL_waylandwindow.h" #include "SDL_waylanddyn.h" #include "pointer-constraints-unstable-v1-client-protocol.h" #include "relative-pointer-unstable-v1-client-protocol.h" #include "xdg-shell-client-protocol.h" #include "xdg-shell-unstable-v6-client-protocol.h" #ifdef SDL_INPUT_LINUXEV #include <linux/input.h> #else #define BTN_LEFT (0x110) #define BTN_RIGHT (0x111) #define BTN_MIDDLE (0x112) #define BTN_SIDE (0x113) #define BTN_EXTRA (0x114) #endif #include <sys/select.h> #include <sys/mman.h> #include <poll.h> #include <unistd.h> #include <xkbcommon/xkbcommon.h> struct SDL_WaylandInput { SDL_VideoData *display; struct wl_seat *seat; struct wl_pointer *pointer; struct wl_touch *touch; struct wl_keyboard *keyboard; SDL_WaylandDataDevice *data_device; struct zwp_relative_pointer_v1 *relative_pointer; struct zwp_confined_pointer_v1 *confined_pointer; SDL_WindowData *pointer_focus; SDL_WindowData *keyboard_focus; /* Last motion location */ wl_fixed_t sx_w; wl_fixed_t sy_w; double dx_frac; double dy_frac; struct { struct xkb_keymap *keymap; struct xkb_state *state; } xkb; /* information about axis events on current frame */ struct { SDL_bool is_x_discrete; float x; SDL_bool is_y_discrete; float y; } pointer_curr_axis_info; }; struct SDL_WaylandTouchPoint { SDL_TouchID id; float x; float y; struct wl_surface* surface; struct SDL_WaylandTouchPoint* prev; struct SDL_WaylandTouchPoint* next; }; struct SDL_WaylandTouchPointList { struct SDL_WaylandTouchPoint* head; struct SDL_WaylandTouchPoint* tail; }; static struct SDL_WaylandTouchPointList touch_points = {NULL, NULL}; static void touch_add(SDL_TouchID id, float x, float y, struct wl_surface *surface) { struct SDL_WaylandTouchPoint* tp = SDL_malloc(sizeof(struct SDL_WaylandTouchPoint)); tp->id = id; tp->x = x; tp->y = y; tp->surface = surface; if (touch_points.tail) { touch_points.tail->next = tp; tp->prev = touch_points.tail; } else { touch_points.head = tp; tp->prev = NULL; } touch_points.tail = tp; tp->next = NULL; } static void touch_update(SDL_TouchID id, float x, float y) { struct SDL_WaylandTouchPoint* tp = touch_points.head; while (tp) { if (tp->id == id) { tp->x = x; tp->y = y; } tp = tp->next; } } static void touch_del(SDL_TouchID id, float* x, float* y, struct wl_surface **surface) { struct SDL_WaylandTouchPoint* tp = touch_points.head; while (tp) { if (tp->id == id) { *x = tp->x; *y = tp->y; *surface = tp->surface; if (tp->prev) { tp->prev->next = tp->next; } else { touch_points.head = tp->next; } if (tp->next) { tp->next->prev = tp->prev; } else { touch_points.tail = tp->prev; } { struct SDL_WaylandTouchPoint *next = tp->next; SDL_free(tp); tp = next; } } else { tp = tp->next; } } } static struct wl_surface* touch_surface(SDL_TouchID id) { struct SDL_WaylandTouchPoint* tp = touch_points.head; while (tp) { if (tp->id == id) { return tp->surface; } tp = tp->next; } return NULL; } void Wayland_PumpEvents(_THIS) { SDL_VideoData *d = _this->driverdata; int err; WAYLAND_wl_display_flush(d->display); if (SDL_IOReady(WAYLAND_wl_display_get_fd(d->display), SDL_FALSE, 0)) { err = WAYLAND_wl_display_dispatch(d->display); } else { err = WAYLAND_wl_display_dispatch_pending(d->display); } if (err == -1 && !d->display_disconnected) { /* Something has failed with the Wayland connection -- for example, * the compositor may have shut down and closed its end of the socket, * or there is a library-specific error. No recovery is possible. */ d->display_disconnected = 1; /* Only send a single quit message, as application shutdown might call * SDL_PumpEvents */ SDL_SendQuit(); } } static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx_w, wl_fixed_t sy_w) { struct SDL_WaylandInput *input = data; SDL_WindowData *window = input->pointer_focus; input->sx_w = sx_w; input->sy_w = sy_w; if (input->pointer_focus) { const int sx = wl_fixed_to_int(sx_w); const int sy = wl_fixed_to_int(sy_w); SDL_SendMouseMotion(window->sdlwindow, 0, 0, sx, sy); } } static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx_w, wl_fixed_t sy_w) { struct SDL_WaylandInput *input = data; SDL_WindowData *window; if (!surface) { /* enter event for a window we've just destroyed */ return; } /* This handler will be called twice in Wayland 1.4 * Once for the window surface which has valid user data * and again for the mouse cursor surface which does not have valid user data * We ignore the later */ window = (SDL_WindowData *)wl_surface_get_user_data(surface); if (window) { input->pointer_focus = window; SDL_SetMouseFocus(window->sdlwindow); /* In the case of e.g. a pointer confine warp, we may receive an enter * event with no following motion event, but with the new coordinates * as part of the enter event. */ pointer_handle_motion(data, pointer, serial, sx_w, sy_w); } } static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) { struct SDL_WaylandInput *input = data; if (input->pointer_focus) { SDL_SetMouseFocus(NULL); input->pointer_focus = NULL; } } static SDL_bool ProcessHitTest(struct SDL_WaylandInput *input, uint32_t serial) { SDL_WindowData *window_data = input->pointer_focus; SDL_Window *window = window_data->sdlwindow; if (window->hit_test) { const SDL_Point point = { wl_fixed_to_int(input->sx_w), wl_fixed_to_int(input->sy_w) }; const SDL_HitTestResult rc = window->hit_test(window, &point, window->hit_test_data); static const uint32_t directions_wl[] = { WL_SHELL_SURFACE_RESIZE_TOP_LEFT, WL_SHELL_SURFACE_RESIZE_TOP, WL_SHELL_SURFACE_RESIZE_TOP_RIGHT, WL_SHELL_SURFACE_RESIZE_RIGHT, WL_SHELL_SURFACE_RESIZE_BOTTOM_RIGHT, WL_SHELL_SURFACE_RESIZE_BOTTOM, WL_SHELL_SURFACE_RESIZE_BOTTOM_LEFT, WL_SHELL_SURFACE_RESIZE_LEFT }; /* the names are different (ZXDG_TOPLEVEL_V6_RESIZE_EDGE_* vs WL_SHELL_SURFACE_RESIZE_*), but the values are the same. */ const uint32_t *directions_zxdg = directions_wl; switch (rc) { case SDL_HITTEST_DRAGGABLE: if (input->display->shell.xdg) { xdg_toplevel_move(window_data->shell_surface.xdg.roleobj.toplevel, input->seat, serial); } else if (input->display->shell.zxdg) { zxdg_toplevel_v6_move(window_data->shell_surface.zxdg.roleobj.toplevel, input->seat, serial); } else { wl_shell_surface_move(window_data->shell_surface.wl, input->seat, serial); } return SDL_TRUE; case SDL_HITTEST_RESIZE_TOPLEFT: case SDL_HITTEST_RESIZE_TOP: case SDL_HITTEST_RESIZE_TOPRIGHT: case SDL_HITTEST_RESIZE_RIGHT: case SDL_HITTEST_RESIZE_BOTTOMRIGHT: case SDL_HITTEST_RESIZE_BOTTOM: case SDL_HITTEST_RESIZE_BOTTOMLEFT: case SDL_HITTEST_RESIZE_LEFT: if (input->display->shell.xdg) { xdg_toplevel_resize(window_data->shell_surface.xdg.roleobj.toplevel, input->seat, serial, directions_zxdg[rc - SDL_HITTEST_RESIZE_TOPLEFT]); } else if (input->display->shell.zxdg) { zxdg_toplevel_v6_resize(window_data->shell_surface.zxdg.roleobj.toplevel, input->seat, serial, directions_zxdg[rc - SDL_HITTEST_RESIZE_TOPLEFT]); } else { wl_shell_surface_resize(window_data->shell_surface.wl, input->seat, serial, directions_wl[rc - SDL_HITTEST_RESIZE_TOPLEFT]); } return SDL_TRUE; default: return SDL_FALSE; } } return SDL_FALSE; } static void pointer_handle_button_common(struct SDL_WaylandInput *input, uint32_t serial, uint32_t time, uint32_t button, uint32_t state_w) { SDL_WindowData *window = input->pointer_focus; enum wl_pointer_button_state state = state_w; uint32_t sdl_button; if (input->pointer_focus) { switch (button) { case BTN_LEFT: sdl_button = SDL_BUTTON_LEFT; if (ProcessHitTest(input, serial)) { return; /* don't pass this event on to app. */ } break; case BTN_MIDDLE: sdl_button = SDL_BUTTON_MIDDLE; break; case BTN_RIGHT: sdl_button = SDL_BUTTON_RIGHT; break; case BTN_SIDE: sdl_button = SDL_BUTTON_X1; break; case BTN_EXTRA: sdl_button = SDL_BUTTON_X2; break; default: return; } Wayland_data_device_set_serial(input->data_device, serial); SDL_SendMouseButton(window->sdlwindow, 0, state ? SDL_PRESSED : SDL_RELEASED, sdl_button); } } static void pointer_handle_button(void *data, struct wl_pointer *pointer, uint32_t serial, uint32_t time, uint32_t button, uint32_t state_w) { struct SDL_WaylandInput *input = data; pointer_handle_button_common(input, serial, time, button, state_w); } static void pointer_handle_axis_common_v1(struct SDL_WaylandInput *input, uint32_t time, uint32_t axis, wl_fixed_t value) { SDL_WindowData *window = input->pointer_focus; enum wl_pointer_axis a = axis; float x, y; if (input->pointer_focus) { switch (a) { case WL_POINTER_AXIS_VERTICAL_SCROLL: x = 0; y = 0 - (float)wl_fixed_to_double(value); break; case WL_POINTER_AXIS_HORIZONTAL_SCROLL: x = 0 - (float)wl_fixed_to_double(value); y = 0; break; default: return; } SDL_SendMouseWheel(window->sdlwindow, 0, x, y, SDL_MOUSEWHEEL_NORMAL); } } static void pointer_handle_axis_common(struct SDL_WaylandInput *input, SDL_bool discrete, uint32_t axis, wl_fixed_t value) { enum wl_pointer_axis a = axis; if (input->pointer_focus) { switch (a) { case WL_POINTER_AXIS_VERTICAL_SCROLL: if (discrete) { /* this is a discrete axis event so we process it and flag * to ignore future continuous axis events in this frame */ input->pointer_curr_axis_info.is_y_discrete = SDL_TRUE; } else if(input->pointer_curr_axis_info.is_y_discrete) { /* this is a continuous axis event and we have already * processed a discrete axis event before so we ignore it */ break; } input->pointer_curr_axis_info.y = 0 - (float)wl_fixed_to_double(value); break; case WL_POINTER_AXIS_HORIZONTAL_SCROLL: if (discrete) { /* this is a discrete axis event so we process it and flag * to ignore future continuous axis events in this frame */ input->pointer_curr_axis_info.is_x_discrete = SDL_TRUE; } else if(input->pointer_curr_axis_info.is_x_discrete) { /* this is a continuous axis event and we have already * processed a discrete axis event before so we ignore it */ break; } input->pointer_curr_axis_info.x = 0 - (float)wl_fixed_to_double(value); break; } } } static void pointer_handle_axis(void *data, struct wl_pointer *pointer, uint32_t time, uint32_t axis, wl_fixed_t value) { struct SDL_WaylandInput *input = data; if(wl_seat_get_version(input->seat) >= 5) pointer_handle_axis_common(input, SDL_FALSE, axis, value); else pointer_handle_axis_common_v1(input, time, axis, value); } static void pointer_handle_frame(void *data, struct wl_pointer *pointer) { struct SDL_WaylandInput *input = data; SDL_WindowData *window = input->pointer_focus; float x = input->pointer_curr_axis_info.x, y = input->pointer_curr_axis_info.y; /* clear pointer_curr_axis_info for next frame */ memset(&input->pointer_curr_axis_info, 0, sizeof input->pointer_curr_axis_info); if(x == 0.0f && y == 0.0f) return; else SDL_SendMouseWheel(window->sdlwindow, 0, x, y, SDL_MOUSEWHEEL_NORMAL); } static void pointer_handle_axis_source(void *data, struct wl_pointer *pointer, uint32_t axis_source) { /* unimplemented */ } static void pointer_handle_axis_stop(void *data, struct wl_pointer *pointer, uint32_t time, uint32_t axis) { /* unimplemented */ } static void pointer_handle_axis_discrete(void *data, struct wl_pointer *pointer, uint32_t axis, int32_t discrete) { struct SDL_WaylandInput *input = data; pointer_handle_axis_common(input, SDL_TRUE, axis, wl_fixed_from_int(discrete)); } static const struct wl_pointer_listener pointer_listener = { pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis, pointer_handle_frame, // Version 5 pointer_handle_axis_source, // Version 5 pointer_handle_axis_stop, // Version 5 pointer_handle_axis_discrete, // Version 5 }; static void touch_handler_down(void *data, struct wl_touch *touch, unsigned int serial, unsigned int timestamp, struct wl_surface *surface, int id, wl_fixed_t fx, wl_fixed_t fy) { SDL_WindowData *window_data = (SDL_WindowData *)wl_surface_get_user_data(surface); const double dblx = wl_fixed_to_double(fx); const double dbly = wl_fixed_to_double(fy); const float x = dblx / window_data->sdlwindow->w; const float y = dbly / window_data->sdlwindow->h; touch_add(id, x, y, surface); SDL_SendTouch(1, (SDL_FingerID)id, window_data->sdlwindow, SDL_TRUE, x, y, 1.0f); } static void touch_handler_up(void *data, struct wl_touch *touch, unsigned int serial, unsigned int timestamp, int id) { float x = 0, y = 0; struct wl_surface *surface = NULL; SDL_Window *window = NULL; touch_del(id, &x, &y, &surface); if (surface) { SDL_WindowData *window_data = (SDL_WindowData *)wl_surface_get_user_data(surface); window = window_data->sdlwindow; } SDL_SendTouch(1, (SDL_FingerID)id, window, SDL_FALSE, x, y, 0.0f); } static void touch_handler_motion(void *data, struct wl_touch *touch, unsigned int timestamp, int id, wl_fixed_t fx, wl_fixed_t fy) { SDL_WindowData *window_data = (SDL_WindowData *)wl_surface_get_user_data(touch_surface(id)); const double dblx = wl_fixed_to_double(fx); const double dbly = wl_fixed_to_double(fy); const float x = dblx / window_data->sdlwindow->w; const float y = dbly / window_data->sdlwindow->h; touch_update(id, x, y); SDL_SendTouchMotion(1, (SDL_FingerID)id, window_data->sdlwindow, x, y, 1.0f); } static void touch_handler_frame(void *data, struct wl_touch *touch) { } static void touch_handler_cancel(void *data, struct wl_touch *touch) { } static const struct wl_touch_listener touch_listener = { touch_handler_down, touch_handler_up, touch_handler_motion, touch_handler_frame, touch_handler_cancel, NULL, /* shape */ NULL, /* orientation */ }; static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) { struct SDL_WaylandInput *input = data; char *map_str; if (!data) { close(fd); return; } if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) { close(fd); return; } map_str = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0); if (map_str == MAP_FAILED) { close(fd); return; } input->xkb.keymap = WAYLAND_xkb_keymap_new_from_string(input->display->xkb_context, map_str, XKB_KEYMAP_FORMAT_TEXT_V1, 0); munmap(map_str, size); close(fd); if (!input->xkb.keymap) { fprintf(stderr, "failed to compile keymap\n"); return; } input->xkb.state = WAYLAND_xkb_state_new(input->xkb.keymap); if (!input->xkb.state) { fprintf(stderr, "failed to create XKB state\n"); WAYLAND_xkb_keymap_unref(input->xkb.keymap); input->xkb.keymap = NULL; return; } } static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface, struct wl_array *keys) { struct SDL_WaylandInput *input = data; SDL_WindowData *window; if (!surface) { /* enter event for a window we've just destroyed */ return; } window = wl_surface_get_user_data(surface); if (window) { input->keyboard_focus = window; window->keyboard_device = input; SDL_SetKeyboardFocus(window->sdlwindow); } } static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) { SDL_SetKeyboardFocus(NULL); } static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state_w) { struct SDL_WaylandInput *input = data; SDL_WindowData *window = input->keyboard_focus; enum wl_keyboard_key_state state = state_w; const xkb_keysym_t *syms; uint32_t scancode; char text[8]; int size; if (key < SDL_arraysize(xfree86_scancode_table2)) { scancode = xfree86_scancode_table2[key]; // TODO when do we get WL_KEYBOARD_KEY_STATE_REPEAT? if (scancode != SDL_SCANCODE_UNKNOWN) SDL_SendKeyboardKey(state == WL_KEYBOARD_KEY_STATE_PRESSED ? SDL_PRESSED : SDL_RELEASED, scancode); } if (!window || window->keyboard_device != input || !input->xkb.state) return; // TODO can this happen? if (WAYLAND_xkb_state_key_get_syms(input->xkb.state, key + 8, &syms) != 1) return; if (state) { size = WAYLAND_xkb_keysym_to_utf8(syms[0], text, sizeof text); if (size > 0) { text[size] = 0; Wayland_data_device_set_serial(input->data_device, serial); SDL_SendKeyboardText(text); } } } static void keyboard_handle_modifiers(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked, uint32_t group) { struct SDL_WaylandInput *input = data; WAYLAND_xkb_state_update_mask(input->xkb.state, mods_depressed, mods_latched, mods_locked, 0, 0, group); } static void keyboard_handle_repeat_info(void *data, struct wl_keyboard *wl_keyboard, int32_t rate, int32_t delay) { /* unimplemented */ } static const struct wl_keyboard_listener keyboard_listener = { keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers, keyboard_handle_repeat_info, // Version 4 }; static void seat_handle_capabilities(void *data, struct wl_seat *seat, enum wl_seat_capability caps) { struct SDL_WaylandInput *input = data; if ((caps & WL_SEAT_CAPABILITY_POINTER) && !input->pointer) { input->pointer = wl_seat_get_pointer(seat); memset(&input->pointer_curr_axis_info, 0, sizeof input->pointer_curr_axis_info); input->display->pointer = input->pointer; wl_pointer_set_user_data(input->pointer, input); wl_pointer_add_listener(input->pointer, &pointer_listener, input); } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && input->pointer) { wl_pointer_destroy(input->pointer); input->pointer = NULL; input->display->pointer = NULL; } if ((caps & WL_SEAT_CAPABILITY_TOUCH) && !input->touch) { SDL_AddTouch(1, SDL_TOUCH_DEVICE_DIRECT, "wayland_touch"); input->touch = wl_seat_get_touch(seat); wl_touch_set_user_data(input->touch, input); wl_touch_add_listener(input->touch, &touch_listener, input); } else if (!(caps & WL_SEAT_CAPABILITY_TOUCH) && input->touch) { SDL_DelTouch(1); wl_touch_destroy(input->touch); input->touch = NULL; } if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && !input->keyboard) { input->keyboard = wl_seat_get_keyboard(seat); wl_keyboard_set_user_data(input->keyboard, input); wl_keyboard_add_listener(input->keyboard, &keyboard_listener, input); } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && input->keyboard) { wl_keyboard_destroy(input->keyboard); input->keyboard = NULL; } } static void seat_handle_name(void *data, struct wl_seat *wl_seat, const char *name) { /* unimplemented */ } static const struct wl_seat_listener seat_listener = { seat_handle_capabilities, seat_handle_name, // Version 2 }; static void data_source_handle_target(void *data, struct wl_data_source *wl_data_source, const char *mime_type) { } static void data_source_handle_send(void *data, struct wl_data_source *wl_data_source, const char *mime_type, int32_t fd) { Wayland_data_source_send((SDL_WaylandDataSource *)data, mime_type, fd); } static void data_source_handle_cancelled(void *data, struct wl_data_source *wl_data_source) { Wayland_data_source_destroy(data); } static void data_source_handle_dnd_drop_performed(void *data, struct wl_data_source *wl_data_source) { } static void data_source_handle_dnd_finished(void *data, struct wl_data_source *wl_data_source) { } static void data_source_handle_action(void *data, struct wl_data_source *wl_data_source, uint32_t dnd_action) { } static const struct wl_data_source_listener data_source_listener = { data_source_handle_target, data_source_handle_send, data_source_handle_cancelled, data_source_handle_dnd_drop_performed, // Version 3 data_source_handle_dnd_finished, // Version 3 data_source_handle_action, // Version 3 }; SDL_WaylandDataSource* Wayland_data_source_create(_THIS) { SDL_WaylandDataSource *data_source = NULL; SDL_VideoData *driver_data = NULL; struct wl_data_source *id = NULL; if (_this == NULL || _this->driverdata == NULL) { SDL_SetError("Video driver uninitialized"); } else { driver_data = _this->driverdata; if (driver_data->data_device_manager != NULL) { id = wl_data_device_manager_create_data_source( driver_data->data_device_manager); } if (id == NULL) { SDL_SetError("Wayland unable to create data source"); } else { data_source = SDL_calloc(1, sizeof *data_source); if (data_source == NULL) { SDL_OutOfMemory(); wl_data_source_destroy(id); } else { WAYLAND_wl_list_init(&(data_source->mimes)); data_source->source = id; wl_data_source_set_user_data(id, data_source); wl_data_source_add_listener(id, &data_source_listener, data_source); } } } return data_source; } static void data_offer_handle_offer(void *data, struct wl_data_offer *wl_data_offer, const char *mime_type) { SDL_WaylandDataOffer *offer = data; Wayland_data_offer_add_mime(offer, mime_type); } static void data_offer_handle_source_actions(void *data, struct wl_data_offer *wl_data_offer, uint32_t source_actions) { } static void data_offer_handle_actions(void *data, struct wl_data_offer *wl_data_offer, uint32_t dnd_action) { } static const struct wl_data_offer_listener data_offer_listener = { data_offer_handle_offer, data_offer_handle_source_actions, // Version 3 data_offer_handle_actions, // Version 3 }; static void data_device_handle_data_offer(void *data, struct wl_data_device *wl_data_device, struct wl_data_offer *id) { SDL_WaylandDataOffer *data_offer = NULL; data_offer = SDL_calloc(1, sizeof *data_offer); if (data_offer == NULL) { SDL_OutOfMemory(); } else { data_offer->offer = id; data_offer->data_device = data; WAYLAND_wl_list_init(&(data_offer->mimes)); wl_data_offer_set_user_data(id, data_offer); wl_data_offer_add_listener(id, &data_offer_listener, data_offer); } } static void data_device_handle_enter(void *data, struct wl_data_device *wl_data_device, uint32_t serial, struct wl_surface *surface, wl_fixed_t x, wl_fixed_t y, struct wl_data_offer *id) { SDL_WaylandDataDevice *data_device = data; SDL_bool has_mime = SDL_FALSE; uint32_t dnd_action = WL_DATA_DEVICE_MANAGER_DND_ACTION_NONE; data_device->drag_serial = serial; if (id != NULL) { data_device->drag_offer = wl_data_offer_get_user_data(id); /* TODO: SDL Support more mime types */ has_mime = Wayland_data_offer_has_mime( data_device->drag_offer, FILE_MIME); /* If drag_mime is NULL this will decline the offer */ wl_data_offer_accept(id, serial, (has_mime == SDL_TRUE) ? FILE_MIME : NULL); /* SDL only supports "copy" style drag and drop */ if (has_mime == SDL_TRUE) { dnd_action = WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY; } if (wl_data_offer_get_version(data_device->drag_offer->offer) >= 3) { wl_data_offer_set_actions(data_device->drag_offer->offer, dnd_action, dnd_action); } } } static void data_device_handle_leave(void *data, struct wl_data_device *wl_data_device) { SDL_WaylandDataDevice *data_device = data; SDL_WaylandDataOffer *offer = NULL; if (data_device->selection_offer != NULL) { data_device->selection_offer = NULL; Wayland_data_offer_destroy(offer); } } static void data_device_handle_motion(void *data, struct wl_data_device *wl_data_device, uint32_t time, wl_fixed_t x, wl_fixed_t y) { } static void data_device_handle_drop(void *data, struct wl_data_device *wl_data_device) { SDL_WaylandDataDevice *data_device = data; void *buffer = NULL; size_t length = 0; const char *current_uri = NULL; const char *last_char = NULL; char *current_char = NULL; if (data_device->drag_offer != NULL) { /* TODO: SDL Support more mime types */ buffer = Wayland_data_offer_receive(data_device->drag_offer, &length, FILE_MIME, SDL_FALSE); /* uri-list */ current_uri = (const char *)buffer; last_char = (const char *)buffer + length; for (current_char = buffer; current_char < last_char; ++current_char) { if (*current_char == '\n' || *current_char == 0) { if (*current_uri != 0 && *current_uri != '#') { *current_char = 0; SDL_SendDropFile(NULL, current_uri); } current_uri = (const char *)current_char + 1; } } SDL_free(buffer); } } static void data_device_handle_selection(void *data, struct wl_data_device *wl_data_device, struct wl_data_offer *id) { SDL_WaylandDataDevice *data_device = data; SDL_WaylandDataOffer *offer = NULL; if (id != NULL) { offer = wl_data_offer_get_user_data(id); } if (data_device->selection_offer != offer) { Wayland_data_offer_destroy(data_device->selection_offer); data_device->selection_offer = offer; } SDL_SendClipboardUpdate(); } static const struct wl_data_device_listener data_device_listener = { data_device_handle_data_offer, data_device_handle_enter, data_device_handle_leave, data_device_handle_motion, data_device_handle_drop, data_device_handle_selection }; void Wayland_display_add_input(SDL_VideoData *d, uint32_t id, uint32_t version) { struct SDL_WaylandInput *input; SDL_WaylandDataDevice *data_device = NULL; input = SDL_calloc(1, sizeof *input); if (input == NULL) return; input->display = d; input->seat = wl_registry_bind(d->registry, id, &wl_seat_interface, SDL_min(5, version)); input->sx_w = wl_fixed_from_int(0); input->sy_w = wl_fixed_from_int(0); d->input = input; if (d->data_device_manager != NULL) { data_device = SDL_calloc(1, sizeof *data_device); if (data_device == NULL) { return; } data_device->data_device = wl_data_device_manager_get_data_device( d->data_device_manager, input->seat ); data_device->video_data = d; if (data_device->data_device == NULL) { SDL_free(data_device); } else { wl_data_device_set_user_data(data_device->data_device, data_device); wl_data_device_add_listener(data_device->data_device, &data_device_listener, data_device); input->data_device = data_device; } } wl_seat_add_listener(input->seat, &seat_listener, input); wl_seat_set_user_data(input->seat, input); WAYLAND_wl_display_flush(d->display); } void Wayland_display_destroy_input(SDL_VideoData *d) { struct SDL_WaylandInput *input = d->input; if (!input) return; if (input->data_device != NULL) { Wayland_data_device_clear_selection(input->data_device); if (input->data_device->selection_offer != NULL) { Wayland_data_offer_destroy(input->data_device->selection_offer); } if (input->data_device->drag_offer != NULL) { Wayland_data_offer_destroy(input->data_device->drag_offer); } if (input->data_device->data_device != NULL) { wl_data_device_release(input->data_device->data_device); } SDL_free(input->data_device); } if (input->keyboard) wl_keyboard_destroy(input->keyboard); if (input->pointer) wl_pointer_destroy(input->pointer); if (input->touch) { SDL_DelTouch(1); wl_touch_destroy(input->touch); } if (input->seat) wl_seat_destroy(input->seat); if (input->xkb.state) WAYLAND_xkb_state_unref(input->xkb.state); if (input->xkb.keymap) WAYLAND_xkb_keymap_unref(input->xkb.keymap); SDL_free(input); d->input = NULL; } SDL_WaylandDataDevice* Wayland_get_data_device(struct SDL_WaylandInput *input) { if (input == NULL) { return NULL; } return input->data_device; } /* !!! FIXME: just merge these into display_handle_global(). */ void Wayland_display_add_relative_pointer_manager(SDL_VideoData *d, uint32_t id) { d->relative_pointer_manager = wl_registry_bind(d->registry, id, &zwp_relative_pointer_manager_v1_interface, 1); } void Wayland_display_destroy_relative_pointer_manager(SDL_VideoData *d) { if (d->relative_pointer_manager) zwp_relative_pointer_manager_v1_destroy(d->relative_pointer_manager); } void Wayland_display_add_pointer_constraints(SDL_VideoData *d, uint32_t id) { d->pointer_constraints = wl_registry_bind(d->registry, id, &zwp_pointer_constraints_v1_interface, 1); } void Wayland_display_destroy_pointer_constraints(SDL_VideoData *d) { if (d->pointer_constraints) zwp_pointer_constraints_v1_destroy(d->pointer_constraints); } static void relative_pointer_handle_relative_motion(void *data, struct zwp_relative_pointer_v1 *pointer, uint32_t time_hi, uint32_t time_lo, wl_fixed_t dx_w, wl_fixed_t dy_w, wl_fixed_t dx_unaccel_w, wl_fixed_t dy_unaccel_w) { struct SDL_WaylandInput *input = data; SDL_VideoData *d = input->display; SDL_WindowData *window = input->pointer_focus; double dx_unaccel; double dy_unaccel; double dx; double dy; dx_unaccel = wl_fixed_to_double(dx_unaccel_w); dy_unaccel = wl_fixed_to_double(dy_unaccel_w); /* Add left over fraction from last event. */ dx_unaccel += input->dx_frac; dy_unaccel += input->dy_frac; input->dx_frac = modf(dx_unaccel, &dx); input->dy_frac = modf(dy_unaccel, &dy); if (input->pointer_focus && d->relative_mouse_mode) { SDL_SendMouseMotion(window->sdlwindow, 0, 1, (int)dx, (int)dy); } } static const struct zwp_relative_pointer_v1_listener relative_pointer_listener = { relative_pointer_handle_relative_motion, }; static void locked_pointer_locked(void *data, struct zwp_locked_pointer_v1 *locked_pointer) { } static void locked_pointer_unlocked(void *data, struct zwp_locked_pointer_v1 *locked_pointer) { } static const struct zwp_locked_pointer_v1_listener locked_pointer_listener = { locked_pointer_locked, locked_pointer_unlocked, }; static void lock_pointer_to_window(SDL_Window *window, struct SDL_WaylandInput *input) { SDL_WindowData *w = window->driverdata; SDL_VideoData *d = input->display; struct zwp_locked_pointer_v1 *locked_pointer; if (w->locked_pointer) return; locked_pointer = zwp_pointer_constraints_v1_lock_pointer(d->pointer_constraints, w->surface, input->pointer, NULL, ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT); zwp_locked_pointer_v1_add_listener(locked_pointer, &locked_pointer_listener, window); w->locked_pointer = locked_pointer; } int Wayland_input_lock_pointer(struct SDL_WaylandInput *input) { SDL_VideoDevice *vd = SDL_GetVideoDevice(); SDL_VideoData *d = input->display; SDL_Window *window; struct zwp_relative_pointer_v1 *relative_pointer; if (!d->relative_pointer_manager) return -1; if (!d->pointer_constraints) return -1; if (!input->pointer) return -1; if (!input->relative_pointer) { relative_pointer = zwp_relative_pointer_manager_v1_get_relative_pointer( d->relative_pointer_manager, input->pointer); zwp_relative_pointer_v1_add_listener(relative_pointer, &relative_pointer_listener, input); input->relative_pointer = relative_pointer; } for (window = vd->windows; window; window = window->next) lock_pointer_to_window(window, input); d->relative_mouse_mode = 1; return 0; } int Wayland_input_unlock_pointer(struct SDL_WaylandInput *input) { SDL_VideoDevice *vd = SDL_GetVideoDevice(); SDL_VideoData *d = input->display; SDL_Window *window; SDL_WindowData *w; for (window = vd->windows; window; window = window->next) { w = window->driverdata; if (w->locked_pointer) zwp_locked_pointer_v1_destroy(w->locked_pointer); w->locked_pointer = NULL; } zwp_relative_pointer_v1_destroy(input->relative_pointer); input->relative_pointer = NULL; d->relative_mouse_mode = 0; return 0; } static void confined_pointer_confined(void *data, struct zwp_confined_pointer_v1 *confined_pointer) { } static void confined_pointer_unconfined(void *data, struct zwp_confined_pointer_v1 *confined_pointer) { } static const struct zwp_confined_pointer_v1_listener confined_pointer_listener = { confined_pointer_confined, confined_pointer_unconfined, }; int Wayland_input_confine_pointer(SDL_Window *window, struct SDL_WaylandInput *input) { SDL_WindowData *w = window->driverdata; SDL_VideoData *d = input->display; struct zwp_confined_pointer_v1 *confined_pointer; if (!d->pointer_constraints) return -1; if (!input->pointer) return -1; /* A confine may already be active, in which case we should destroy it and * create a new one. */ if (input->confined_pointer) Wayland_input_unconfine_pointer(input); confined_pointer = zwp_pointer_constraints_v1_confine_pointer(d->pointer_constraints, w->surface, input->pointer, NULL, ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT); zwp_confined_pointer_v1_add_listener(confined_pointer, &confined_pointer_listener, window); input->confined_pointer = confined_pointer; return 0; } int Wayland_input_unconfine_pointer(struct SDL_WaylandInput *input) { if (input->confined_pointer) { zwp_confined_pointer_v1_destroy(input->confined_pointer); input->confined_pointer = NULL; } return 0; } #endif /* SDL_VIDEO_DRIVER_WAYLAND */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylandevents.c
C
apache-2.0
41,070
/* 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_waylandevents_h_ #define SDL_waylandevents_h_ #include "SDL_waylandvideo.h" #include "SDL_waylandwindow.h" #include "SDL_waylanddatamanager.h" struct SDL_WaylandInput; extern void Wayland_PumpEvents(_THIS); extern void Wayland_display_add_input(SDL_VideoData *d, uint32_t id, uint32_t version); extern void Wayland_display_destroy_input(SDL_VideoData *d); extern SDL_WaylandDataDevice* Wayland_get_data_device(struct SDL_WaylandInput *input); extern void Wayland_display_add_pointer_constraints(SDL_VideoData *d, uint32_t id); extern void Wayland_display_destroy_pointer_constraints(SDL_VideoData *d); extern int Wayland_input_lock_pointer(struct SDL_WaylandInput *input); extern int Wayland_input_unlock_pointer(struct SDL_WaylandInput *input); extern int Wayland_input_confine_pointer(SDL_Window *window, struct SDL_WaylandInput *input); extern int Wayland_input_unconfine_pointer(struct SDL_WaylandInput *input); extern void Wayland_display_add_relative_pointer_manager(SDL_VideoData *d, uint32_t id); extern void Wayland_display_destroy_relative_pointer_manager(SDL_VideoData *d); #endif /* SDL_waylandevents_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylandevents_c.h
C
apache-2.0
2,150
/* 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_VIDEO_DRIVER_WAYLAND #include <sys/types.h> #include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <limits.h> #include "../SDL_sysvideo.h" #include "SDL_mouse.h" #include "../../events/SDL_mouse_c.h" #include "SDL_waylandvideo.h" #include "SDL_waylandevents_c.h" #include "SDL_waylanddyn.h" #include "wayland-cursor.h" #include "SDL_assert.h" typedef struct { struct wl_buffer *buffer; struct wl_surface *surface; int hot_x, hot_y; int w, h; /* Either a preloaded cursor, or one we created ourselves */ struct wl_cursor *cursor; void *shm_data; } Wayland_CursorData; static int wayland_create_tmp_file(off_t size) { static const char template[] = "/sdl-shared-XXXXXX"; char *xdg_path; char tmp_path[PATH_MAX]; int fd; xdg_path = SDL_getenv("XDG_RUNTIME_DIR"); if (!xdg_path) { return -1; } SDL_strlcpy(tmp_path, xdg_path, PATH_MAX); SDL_strlcat(tmp_path, template, PATH_MAX); fd = mkostemp(tmp_path, O_CLOEXEC); if (fd < 0) return -1; if (ftruncate(fd, size) < 0) { close(fd); return -1; } return fd; } static void mouse_buffer_release(void *data, struct wl_buffer *buffer) { } static const struct wl_buffer_listener mouse_buffer_listener = { mouse_buffer_release }; static int create_buffer_from_shm(Wayland_CursorData *d, int width, int height, uint32_t format) { SDL_VideoDevice *vd = SDL_GetVideoDevice(); SDL_VideoData *data = (SDL_VideoData *) vd->driverdata; struct wl_shm_pool *shm_pool; int stride = width * 4; int size = stride * height; int shm_fd; shm_fd = wayland_create_tmp_file(size); if (shm_fd < 0) { return SDL_SetError("Creating mouse cursor buffer failed."); } d->shm_data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0); if (d->shm_data == MAP_FAILED) { d->shm_data = NULL; close (shm_fd); return SDL_SetError("mmap() failed."); } SDL_assert(d->shm_data != NULL); shm_pool = wl_shm_create_pool(data->shm, shm_fd, size); d->buffer = wl_shm_pool_create_buffer(shm_pool, 0, width, height, stride, format); wl_buffer_add_listener(d->buffer, &mouse_buffer_listener, d); wl_shm_pool_destroy (shm_pool); close (shm_fd); return 0; } static SDL_Cursor * Wayland_CreateCursor(SDL_Surface *surface, int hot_x, int hot_y) { SDL_Cursor *cursor; cursor = calloc(1, sizeof (*cursor)); if (cursor) { SDL_VideoDevice *vd = SDL_GetVideoDevice (); SDL_VideoData *wd = (SDL_VideoData *) vd->driverdata; Wayland_CursorData *data = calloc (1, sizeof (Wayland_CursorData)); if (!data) { SDL_OutOfMemory(); free(cursor); return NULL; } cursor->driverdata = (void *) data; /* Assume ARGB8888 */ SDL_assert(surface->format->format == SDL_PIXELFORMAT_ARGB8888); SDL_assert(surface->pitch == surface->w * 4); /* Allocate shared memory buffer for this cursor */ if (create_buffer_from_shm (data, surface->w, surface->h, WL_SHM_FORMAT_ARGB8888) < 0) { free (cursor->driverdata); free (cursor); return NULL; } SDL_memcpy(data->shm_data, surface->pixels, surface->h * surface->pitch); data->surface = wl_compositor_create_surface(wd->compositor); wl_surface_set_user_data(data->surface, NULL); data->hot_x = hot_x; data->hot_y = hot_y; data->w = surface->w; data->h = surface->h; } else { SDL_OutOfMemory(); } return cursor; } static SDL_Cursor * CreateCursorFromWlCursor(SDL_VideoData *d, struct wl_cursor *wlcursor) { SDL_Cursor *cursor; cursor = calloc(1, sizeof (*cursor)); if (cursor) { Wayland_CursorData *data = calloc (1, sizeof (Wayland_CursorData)); if (!data) { SDL_OutOfMemory(); free(cursor); return NULL; } cursor->driverdata = (void *) data; data->buffer = WAYLAND_wl_cursor_image_get_buffer(wlcursor->images[0]); data->surface = wl_compositor_create_surface(d->compositor); wl_surface_set_user_data(data->surface, NULL); data->hot_x = wlcursor->images[0]->hotspot_x; data->hot_y = wlcursor->images[0]->hotspot_y; data->w = wlcursor->images[0]->width; data->h = wlcursor->images[0]->height; data->cursor= wlcursor; } else { SDL_OutOfMemory (); } return cursor; } static SDL_Cursor * Wayland_CreateDefaultCursor() { SDL_VideoDevice *device = SDL_GetVideoDevice(); SDL_VideoData *data = device->driverdata; return CreateCursorFromWlCursor (data, WAYLAND_wl_cursor_theme_get_cursor(data->cursor_theme, "left_ptr")); } static SDL_Cursor * Wayland_CreateSystemCursor(SDL_SystemCursor id) { SDL_VideoDevice *vd = SDL_GetVideoDevice(); SDL_VideoData *d = vd->driverdata; struct wl_cursor *cursor = NULL; switch(id) { default: SDL_assert(0); return NULL; case SDL_SYSTEM_CURSOR_ARROW: cursor = WAYLAND_wl_cursor_theme_get_cursor(d->cursor_theme, "left_ptr"); break; case SDL_SYSTEM_CURSOR_IBEAM: cursor = WAYLAND_wl_cursor_theme_get_cursor(d->cursor_theme, "xterm"); break; case SDL_SYSTEM_CURSOR_WAIT: cursor = WAYLAND_wl_cursor_theme_get_cursor(d->cursor_theme, "watch"); break; case SDL_SYSTEM_CURSOR_CROSSHAIR: cursor = WAYLAND_wl_cursor_theme_get_cursor(d->cursor_theme, "hand1"); break; case SDL_SYSTEM_CURSOR_WAITARROW: cursor = WAYLAND_wl_cursor_theme_get_cursor(d->cursor_theme, "watch"); break; case SDL_SYSTEM_CURSOR_SIZENWSE: cursor = WAYLAND_wl_cursor_theme_get_cursor(d->cursor_theme, "hand1"); break; case SDL_SYSTEM_CURSOR_SIZENESW: cursor = WAYLAND_wl_cursor_theme_get_cursor(d->cursor_theme, "hand1"); break; case SDL_SYSTEM_CURSOR_SIZEWE: cursor = WAYLAND_wl_cursor_theme_get_cursor(d->cursor_theme, "hand1"); break; case SDL_SYSTEM_CURSOR_SIZENS: cursor = WAYLAND_wl_cursor_theme_get_cursor(d->cursor_theme, "hand1"); break; case SDL_SYSTEM_CURSOR_SIZEALL: cursor = WAYLAND_wl_cursor_theme_get_cursor(d->cursor_theme, "hand1"); break; case SDL_SYSTEM_CURSOR_NO: cursor = WAYLAND_wl_cursor_theme_get_cursor(d->cursor_theme, "xterm"); break; case SDL_SYSTEM_CURSOR_HAND: cursor = WAYLAND_wl_cursor_theme_get_cursor(d->cursor_theme, "hand1"); break; } return CreateCursorFromWlCursor(d, cursor); } static void Wayland_FreeCursor(SDL_Cursor *cursor) { Wayland_CursorData *d; if (!cursor) return; d = cursor->driverdata; /* Probably not a cursor we own */ if (!d) return; if (d->buffer && !d->cursor) wl_buffer_destroy(d->buffer); if (d->surface) wl_surface_destroy(d->surface); /* Not sure what's meant to happen to shm_data */ free (cursor->driverdata); SDL_free(cursor); } static int Wayland_ShowCursor(SDL_Cursor *cursor) { SDL_VideoDevice *vd = SDL_GetVideoDevice(); SDL_VideoData *d = vd->driverdata; struct wl_pointer *pointer = d->pointer; if (!pointer) return -1; if (cursor) { Wayland_CursorData *data = cursor->driverdata; wl_pointer_set_cursor (pointer, 0, data->surface, data->hot_x, data->hot_y); wl_surface_attach(data->surface, data->buffer, 0, 0); wl_surface_damage(data->surface, 0, 0, data->w, data->h); wl_surface_commit(data->surface); } else { wl_pointer_set_cursor (pointer, 0, NULL, 0, 0); } return 0; } static void Wayland_WarpMouse(SDL_Window *window, int x, int y) { SDL_Unsupported(); } static int Wayland_WarpMouseGlobal(int x, int y) { return SDL_Unsupported(); } static int Wayland_SetRelativeMouseMode(SDL_bool enabled) { SDL_VideoDevice *vd = SDL_GetVideoDevice(); SDL_VideoData *data = (SDL_VideoData *) vd->driverdata; if (enabled) return Wayland_input_lock_pointer(data->input); else return Wayland_input_unlock_pointer(data->input); } void Wayland_InitMouse(void) { SDL_Mouse *mouse = SDL_GetMouse(); mouse->CreateCursor = Wayland_CreateCursor; mouse->CreateSystemCursor = Wayland_CreateSystemCursor; mouse->ShowCursor = Wayland_ShowCursor; mouse->FreeCursor = Wayland_FreeCursor; mouse->WarpMouse = Wayland_WarpMouse; mouse->WarpMouseGlobal = Wayland_WarpMouseGlobal; mouse->SetRelativeMouseMode = Wayland_SetRelativeMouseMode; SDL_SetDefaultCursor(Wayland_CreateDefaultCursor()); } void Wayland_FiniMouse(void) { /* This effectively assumes that nobody else * touches SDL_Mouse which is effectively * a singleton */ } #endif /* SDL_VIDEO_DRIVER_WAYLAND */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylandmouse.c
C
apache-2.0
10,962
/* 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_mouse.h" #include "SDL_waylandvideo.h" #if SDL_VIDEO_DRIVER_WAYLAND extern void Wayland_InitMouse(void); extern void Wayland_FiniMouse(void); #endif
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylandmouse.h
C
apache-2.0
1,138
/* 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_VIDEO_DRIVER_WAYLAND && SDL_VIDEO_OPENGL_EGL #include "../SDL_sysvideo.h" #include "../../events/SDL_windowevents_c.h" #include "SDL_waylandvideo.h" #include "SDL_waylandopengles.h" #include "SDL_waylandwindow.h" #include "SDL_waylandevents_c.h" #include "SDL_waylanddyn.h" #include "xdg-shell-client-protocol.h" #include "xdg-shell-unstable-v6-client-protocol.h" /* EGL implementation of SDL OpenGL ES support */ int Wayland_GLES_LoadLibrary(_THIS, const char *path) { int ret; SDL_VideoData *data = (SDL_VideoData *) _this->driverdata; ret = SDL_EGL_LoadLibrary(_this, path, (NativeDisplayType) data->display, 0); Wayland_PumpEvents(_this); WAYLAND_wl_display_flush(data->display); return ret; } SDL_GLContext Wayland_GLES_CreateContext(_THIS, SDL_Window * window) { SDL_GLContext context; context = SDL_EGL_CreateContext(_this, ((SDL_WindowData *) window->driverdata)->egl_surface); WAYLAND_wl_display_flush( ((SDL_VideoData*)_this->driverdata)->display ); return context; } int Wayland_GLES_SwapWindow(_THIS, SDL_Window *window) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; if (SDL_EGL_SwapBuffers(_this, data->egl_surface) < 0) { return -1; } // Wayland-EGL forbids drawing calls in-between SwapBuffers and wl_egl_window_resize Wayland_HandlePendingResize(window); WAYLAND_wl_display_flush( data->waylandData->display ); return 0; } int Wayland_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context) { int ret; if (window && context) { ret = SDL_EGL_MakeCurrent(_this, ((SDL_WindowData *) window->driverdata)->egl_surface, context); } else { ret = SDL_EGL_MakeCurrent(_this, NULL, NULL); } WAYLAND_wl_display_flush( ((SDL_VideoData*)_this->driverdata)->display ); return ret; } void Wayland_GLES_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h) { SDL_WindowData *data; if (window->driverdata) { data = (SDL_WindowData *) window->driverdata; if (w) { *w = window->w * data->scale_factor; } if (h) { *h = window->h * data->scale_factor; } } } void Wayland_GLES_DeleteContext(_THIS, SDL_GLContext context) { SDL_EGL_DeleteContext(_this, context); WAYLAND_wl_display_flush( ((SDL_VideoData*)_this->driverdata)->display ); } #endif /* SDL_VIDEO_DRIVER_WAYLAND && SDL_VIDEO_OPENGL_EGL */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylandopengles.c
C
apache-2.0
3,501
/* 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_waylandopengles_h_ #define SDL_waylandopengles_h_ #include "../SDL_sysvideo.h" #include "../SDL_egl_c.h" typedef struct SDL_PrivateGLESData { int dummy; } SDL_PrivateGLESData; /* OpenGLES functions */ #define Wayland_GLES_GetAttribute SDL_EGL_GetAttribute #define Wayland_GLES_GetProcAddress SDL_EGL_GetProcAddress #define Wayland_GLES_UnloadLibrary SDL_EGL_UnloadLibrary #define Wayland_GLES_SetSwapInterval SDL_EGL_SetSwapInterval #define Wayland_GLES_GetSwapInterval SDL_EGL_GetSwapInterval extern int Wayland_GLES_LoadLibrary(_THIS, const char *path); extern SDL_GLContext Wayland_GLES_CreateContext(_THIS, SDL_Window * window); extern int Wayland_GLES_SwapWindow(_THIS, SDL_Window * window); extern int Wayland_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context); extern void Wayland_GLES_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h); extern void Wayland_GLES_DeleteContext(_THIS, SDL_GLContext context); #endif /* SDL_waylandopengles_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylandopengles.h
C
apache-2.0
2,008
/* 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. */ /* *INDENT-OFF* */ #ifndef SDL_WAYLAND_MODULE #define SDL_WAYLAND_MODULE(modname) #endif #ifndef SDL_WAYLAND_SYM #define SDL_WAYLAND_SYM(rc,fn,params) #endif #ifndef SDL_WAYLAND_INTERFACE #define SDL_WAYLAND_INTERFACE(iface) #endif SDL_WAYLAND_MODULE(WAYLAND_CLIENT) SDL_WAYLAND_SYM(void, wl_proxy_marshal, (struct wl_proxy *, uint32_t, ...)) SDL_WAYLAND_SYM(struct wl_proxy *, wl_proxy_create, (struct wl_proxy *, const struct wl_interface *)) SDL_WAYLAND_SYM(void, wl_proxy_destroy, (struct wl_proxy *)) SDL_WAYLAND_SYM(int, wl_proxy_add_listener, (struct wl_proxy *, void (**)(void), void *)) SDL_WAYLAND_SYM(void, wl_proxy_set_user_data, (struct wl_proxy *, void *)) SDL_WAYLAND_SYM(void *, wl_proxy_get_user_data, (struct wl_proxy *)) SDL_WAYLAND_SYM(uint32_t, wl_proxy_get_version, (struct wl_proxy *)) SDL_WAYLAND_SYM(uint32_t, wl_proxy_get_id, (struct wl_proxy *)) SDL_WAYLAND_SYM(const char *, wl_proxy_get_class, (struct wl_proxy *)) SDL_WAYLAND_SYM(void, wl_proxy_set_queue, (struct wl_proxy *, struct wl_event_queue *)) SDL_WAYLAND_SYM(struct wl_display *, wl_display_connect, (const char *)) SDL_WAYLAND_SYM(struct wl_display *, wl_display_connect_to_fd, (int)) SDL_WAYLAND_SYM(void, wl_display_disconnect, (struct wl_display *)) SDL_WAYLAND_SYM(int, wl_display_get_fd, (struct wl_display *)) SDL_WAYLAND_SYM(int, wl_display_dispatch, (struct wl_display *)) SDL_WAYLAND_SYM(int, wl_display_dispatch_queue, (struct wl_display *, struct wl_event_queue *)) SDL_WAYLAND_SYM(int, wl_display_dispatch_queue_pending, (struct wl_display *, struct wl_event_queue *)) SDL_WAYLAND_SYM(int, wl_display_dispatch_pending, (struct wl_display *)) SDL_WAYLAND_SYM(int, wl_display_get_error, (struct wl_display *)) SDL_WAYLAND_SYM(int, wl_display_flush, (struct wl_display *)) SDL_WAYLAND_SYM(int, wl_display_roundtrip, (struct wl_display *)) SDL_WAYLAND_SYM(struct wl_event_queue *, wl_display_create_queue, (struct wl_display *)) SDL_WAYLAND_SYM(void, wl_log_set_handler_client, (wl_log_func_t)) SDL_WAYLAND_SYM(void, wl_list_init, (struct wl_list *)) SDL_WAYLAND_SYM(void, wl_list_insert, (struct wl_list *, struct wl_list *) ) SDL_WAYLAND_SYM(void, wl_list_remove, (struct wl_list *)) SDL_WAYLAND_SYM(int, wl_list_length, (const struct wl_list *)) SDL_WAYLAND_SYM(int, wl_list_empty, (const struct wl_list *)) SDL_WAYLAND_SYM(void, wl_list_insert_list, (struct wl_list *, struct wl_list *)) /* These functions are available in Wayland >= 1.4 */ SDL_WAYLAND_MODULE(WAYLAND_CLIENT_1_4) SDL_WAYLAND_SYM(struct wl_proxy *, wl_proxy_marshal_constructor, (struct wl_proxy *, uint32_t opcode, const struct wl_interface *interface, ...)) SDL_WAYLAND_MODULE(WAYLAND_CLIENT_1_10) SDL_WAYLAND_SYM(struct wl_proxy *, wl_proxy_marshal_constructor_versioned, (struct wl_proxy *proxy, uint32_t opcode, const struct wl_interface *interface, uint32_t version, ...)) SDL_WAYLAND_INTERFACE(wl_seat_interface) SDL_WAYLAND_INTERFACE(wl_surface_interface) SDL_WAYLAND_INTERFACE(wl_shm_pool_interface) SDL_WAYLAND_INTERFACE(wl_buffer_interface) SDL_WAYLAND_INTERFACE(wl_registry_interface) SDL_WAYLAND_INTERFACE(wl_shell_surface_interface) SDL_WAYLAND_INTERFACE(wl_region_interface) SDL_WAYLAND_INTERFACE(wl_pointer_interface) SDL_WAYLAND_INTERFACE(wl_keyboard_interface) SDL_WAYLAND_INTERFACE(wl_compositor_interface) SDL_WAYLAND_INTERFACE(wl_output_interface) SDL_WAYLAND_INTERFACE(wl_shell_interface) SDL_WAYLAND_INTERFACE(wl_shm_interface) SDL_WAYLAND_INTERFACE(wl_data_device_interface) SDL_WAYLAND_INTERFACE(wl_data_source_interface) SDL_WAYLAND_INTERFACE(wl_data_offer_interface) SDL_WAYLAND_INTERFACE(wl_data_device_manager_interface) SDL_WAYLAND_MODULE(WAYLAND_EGL) SDL_WAYLAND_SYM(struct wl_egl_window *, wl_egl_window_create, (struct wl_surface *, int, int)) SDL_WAYLAND_SYM(void, wl_egl_window_destroy, (struct wl_egl_window *)) SDL_WAYLAND_SYM(void, wl_egl_window_resize, (struct wl_egl_window *, int, int, int, int)) SDL_WAYLAND_SYM(void, wl_egl_window_get_attached_size, (struct wl_egl_window *, int *, int *)) SDL_WAYLAND_MODULE(WAYLAND_CURSOR) SDL_WAYLAND_SYM(struct wl_cursor_theme *, wl_cursor_theme_load, (const char *, int , struct wl_shm *)) SDL_WAYLAND_SYM(void, wl_cursor_theme_destroy, (struct wl_cursor_theme *)) SDL_WAYLAND_SYM(struct wl_cursor *, wl_cursor_theme_get_cursor, (struct wl_cursor_theme *, const char *)) SDL_WAYLAND_SYM(struct wl_buffer *, wl_cursor_image_get_buffer, (struct wl_cursor_image *)) SDL_WAYLAND_SYM(int, wl_cursor_frame, (struct wl_cursor *, uint32_t)) SDL_WAYLAND_MODULE(WAYLAND_XKB) SDL_WAYLAND_SYM(int, xkb_state_key_get_syms, (struct xkb_state *, xkb_keycode_t, const xkb_keysym_t **)) SDL_WAYLAND_SYM(int, xkb_keysym_to_utf8, (xkb_keysym_t, char *, size_t) ) SDL_WAYLAND_SYM(struct xkb_keymap *, xkb_keymap_new_from_string, (struct xkb_context *, const char *, enum xkb_keymap_format, enum xkb_keymap_compile_flags)) SDL_WAYLAND_SYM(struct xkb_state *, xkb_state_new, (struct xkb_keymap *) ) SDL_WAYLAND_SYM(void, xkb_keymap_unref, (struct xkb_keymap *) ) SDL_WAYLAND_SYM(void, xkb_state_unref, (struct xkb_state *) ) SDL_WAYLAND_SYM(void, xkb_context_unref, (struct xkb_context *) ) SDL_WAYLAND_SYM(struct xkb_context *, xkb_context_new, (enum xkb_context_flags flags) ) SDL_WAYLAND_SYM(enum xkb_state_component, xkb_state_update_mask, (struct xkb_state *state,\ xkb_mod_mask_t depressed_mods,\ xkb_mod_mask_t latched_mods,\ xkb_mod_mask_t locked_mods,\ xkb_layout_index_t depressed_layout,\ xkb_layout_index_t latched_layout,\ xkb_layout_index_t locked_layout) ) #undef SDL_WAYLAND_MODULE #undef SDL_WAYLAND_SYM #undef SDL_WAYLAND_INTERFACE /* *INDENT-ON* */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylandsym.h
C
apache-2.0
6,716
/* 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. */ /* Contributed by Thomas Perl <thomas.perl@jollamobile.com> */ #include "../../SDL_internal.h" #ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH #include "SDL_mouse.h" #include "SDL_keyboard.h" #include "SDL_waylandtouch.h" #include "../../events/SDL_touch_c.h" struct SDL_WaylandTouch { struct qt_touch_extension *touch_extension; }; /** * Qt TouchPointState * adapted from qtbase/src/corelib/global/qnamespace.h **/ enum QtWaylandTouchPointState { QtWaylandTouchPointPressed = 0x01, QtWaylandTouchPointMoved = 0x02, /* Never sent by the server: QtWaylandTouchPointStationary = 0x04, */ QtWaylandTouchPointReleased = 0x08, }; static void touch_handle_touch(void *data, struct qt_touch_extension *qt_touch_extension, uint32_t time, uint32_t id, uint32_t state, int32_t x, int32_t y, int32_t normalized_x, int32_t normalized_y, int32_t width, int32_t height, uint32_t pressure, int32_t velocity_x, int32_t velocity_y, uint32_t flags, struct wl_array *rawdata) { /** * Event is assembled in QtWayland in TouchExtensionGlobal::postTouchEvent * (src/compositor/wayland_wrapper/qwltouch.cpp) **/ float FIXED_TO_FLOAT = 1. / 10000.; float xf = FIXED_TO_FLOAT * x; float yf = FIXED_TO_FLOAT * y; float PRESSURE_TO_FLOAT = 1. / 255.; float pressuref = PRESSURE_TO_FLOAT * pressure; uint32_t touchState = state & 0xFFFF; /* Other fields that are sent by the server (qwltouch.cpp), but not used at the moment can be decoded in this way: uint32_t sentPointCount = state >> 16; uint32_t touchFlags = flags & 0xFFFF; uint32_t capabilities = flags >> 16; */ SDL_Window* window = NULL; SDL_TouchID deviceId = 1; if (SDL_AddTouch(deviceId, SDL_TOUCH_DEVICE_DIRECT, "qt_touch_extension") < 0) { SDL_Log("error: can't add touch %s, %d", __FILE__, __LINE__); } /* FIXME: This should be the window the given wayland surface is associated * with, but how do we get the wayland surface? */ window = SDL_GetMouseFocus(); if (window == NULL) { window = SDL_GetKeyboardFocus(); } switch (touchState) { case QtWaylandTouchPointPressed: case QtWaylandTouchPointReleased: SDL_SendTouch(deviceId, (SDL_FingerID)id, window, (touchState == QtWaylandTouchPointPressed) ? SDL_TRUE : SDL_FALSE, xf, yf, pressuref); break; case QtWaylandTouchPointMoved: SDL_SendTouchMotion(deviceId, (SDL_FingerID)id, window, xf, yf, pressuref); break; default: /* Should not happen */ break; } } static void touch_handle_configure(void *data, struct qt_touch_extension *qt_touch_extension, uint32_t flags) { } /* wayland-qt-touch-extension.c BEGINS */ static const struct qt_touch_extension_listener touch_listener = { touch_handle_touch, touch_handle_configure, }; static const struct wl_interface *qt_touch_extension_types[] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, }; static const struct wl_message qt_touch_extension_requests[] = { { "dummy", "", qt_touch_extension_types + 0 }, }; static const struct wl_message qt_touch_extension_events[] = { { "touch", "uuuiiiiiiuiiua", qt_touch_extension_types + 0 }, { "configure", "u", qt_touch_extension_types + 0 }, }; WL_EXPORT const struct wl_interface qt_touch_extension_interface = { "qt_touch_extension", 1, 1, qt_touch_extension_requests, 2, qt_touch_extension_events, }; /* wayland-qt-touch-extension.c ENDS */ /* wayland-qt-windowmanager.c BEGINS */ static const struct wl_interface *qt_windowmanager_types[] = { NULL, NULL, }; static const struct wl_message qt_windowmanager_requests[] = { { "open_url", "us", qt_windowmanager_types + 0 }, }; static const struct wl_message qt_windowmanager_events[] = { { "hints", "i", qt_windowmanager_types + 0 }, { "quit", "", qt_windowmanager_types + 0 }, }; WL_EXPORT const struct wl_interface qt_windowmanager_interface = { "qt_windowmanager", 1, 1, qt_windowmanager_requests, 2, qt_windowmanager_events, }; /* wayland-qt-windowmanager.c ENDS */ /* wayland-qt-surface-extension.c BEGINS */ #ifndef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC extern const struct wl_interface wl_surface_interface; #endif static const struct wl_interface *qt_surface_extension_types[] = { NULL, NULL, &qt_extended_surface_interface, #ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC /* FIXME: Set this dynamically to (*WAYLAND_wl_surface_interface) ? * The value comes from auto generated code and does * not appear to actually be used anywhere */ NULL, #else &wl_surface_interface, #endif }; static const struct wl_message qt_surface_extension_requests[] = { { "get_extended_surface", "no", qt_surface_extension_types + 2 }, }; WL_EXPORT const struct wl_interface qt_surface_extension_interface = { "qt_surface_extension", 1, 1, qt_surface_extension_requests, 0, NULL, }; static const struct wl_message qt_extended_surface_requests[] = { { "update_generic_property", "sa", qt_surface_extension_types + 0 }, { "set_content_orientation", "i", qt_surface_extension_types + 0 }, { "set_window_flags", "i", qt_surface_extension_types + 0 }, }; static const struct wl_message qt_extended_surface_events[] = { { "onscreen_visibility", "i", qt_surface_extension_types + 0 }, { "set_generic_property", "sa", qt_surface_extension_types + 0 }, { "close", "", qt_surface_extension_types + 0 }, }; WL_EXPORT const struct wl_interface qt_extended_surface_interface = { "qt_extended_surface", 1, 3, qt_extended_surface_requests, 3, qt_extended_surface_events, }; /* wayland-qt-surface-extension.c ENDS */ void Wayland_touch_create(SDL_VideoData *data, uint32_t id) { struct SDL_WaylandTouch *touch; if (data->touch) { Wayland_touch_destroy(data); } /* !!! FIXME: check for failure, call SDL_OutOfMemory() */ data->touch = SDL_malloc(sizeof(struct SDL_WaylandTouch)); touch = data->touch; touch->touch_extension = wl_registry_bind(data->registry, id, &qt_touch_extension_interface, 1); qt_touch_extension_add_listener(touch->touch_extension, &touch_listener, data); } void Wayland_touch_destroy(SDL_VideoData *data) { if (data->touch) { struct SDL_WaylandTouch *touch = data->touch; if (touch->touch_extension) { qt_touch_extension_destroy(touch->touch_extension); } SDL_free(data->touch); data->touch = NULL; } } #endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylandtouch.c
C
apache-2.0
7,849
/* 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_waylandtouch_h_ #define SDL_waylandtouch_h_ #include "../../SDL_internal.h" #ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH #include "SDL_waylandvideo.h" #include <stdint.h> #include <stddef.h> #include "wayland-util.h" #include "SDL_waylanddyn.h" void Wayland_touch_create(SDL_VideoData *data, uint32_t id); void Wayland_touch_destroy(SDL_VideoData *data); struct qt_touch_extension; /* Autogenerated QT headers */ /* Support for Wayland with QmlCompositor as Server ================================================ The Wayland video driver has support for some additional features when using QtWayland's "qmlcompositor" as Wayland server. This is needed for touch input when running SDL applications under a qmlcompositor Wayland server. The files following headers have been generated from the Wayland XML Protocol Definition in QtWayland as follows: Clone QtWayland from Git: http://qt.gitorious.org/qt/qtwayland/ Generate headers and glue code: for extension in touch-extension surface-extension windowmanager; do wayland-scanner client-header < src/extensions/$extension.xml > wayland-qt-$extension.h wayland-scanner code < src/extensions/$extension.xml > wayland-qt-$extension.c done */ /* wayland-qt-surface-extension.h */ struct wl_client; struct wl_resource; struct qt_surface_extension; struct qt_extended_surface; extern const struct wl_interface qt_surface_extension_interface; extern const struct wl_interface qt_extended_surface_interface; #define QT_SURFACE_EXTENSION_GET_EXTENDED_SURFACE 0 static inline void qt_surface_extension_set_user_data(struct qt_surface_extension *qt_surface_extension, void *user_data) { wl_proxy_set_user_data((struct wl_proxy *) qt_surface_extension, user_data); } static inline void * qt_surface_extension_get_user_data(struct qt_surface_extension *qt_surface_extension) { return wl_proxy_get_user_data((struct wl_proxy *) qt_surface_extension); } static inline void qt_surface_extension_destroy(struct qt_surface_extension *qt_surface_extension) { WAYLAND_wl_proxy_destroy((struct wl_proxy *) qt_surface_extension); } static inline struct qt_extended_surface * qt_surface_extension_get_extended_surface(struct qt_surface_extension *qt_surface_extension, struct wl_surface *surface) { struct wl_proxy *id; id = wl_proxy_create((struct wl_proxy *) qt_surface_extension, &qt_extended_surface_interface); if (!id) return NULL; WAYLAND_wl_proxy_marshal((struct wl_proxy *) qt_surface_extension, QT_SURFACE_EXTENSION_GET_EXTENDED_SURFACE, id, surface); return (struct qt_extended_surface *) id; } #ifndef QT_EXTENDED_SURFACE_ORIENTATION_ENUM #define QT_EXTENDED_SURFACE_ORIENTATION_ENUM enum qt_extended_surface_orientation { QT_EXTENDED_SURFACE_ORIENTATION_PRIMARYORIENTATION = 0, QT_EXTENDED_SURFACE_ORIENTATION_PORTRAITORIENTATION = 1, QT_EXTENDED_SURFACE_ORIENTATION_LANDSCAPEORIENTATION = 2, QT_EXTENDED_SURFACE_ORIENTATION_INVERTEDPORTRAITORIENTATION = 4, QT_EXTENDED_SURFACE_ORIENTATION_INVERTEDLANDSCAPEORIENTATION = 8, }; #endif /* QT_EXTENDED_SURFACE_ORIENTATION_ENUM */ #ifndef QT_EXTENDED_SURFACE_WINDOWFLAG_ENUM #define QT_EXTENDED_SURFACE_WINDOWFLAG_ENUM enum qt_extended_surface_windowflag { QT_EXTENDED_SURFACE_WINDOWFLAG_OVERRIDESSYSTEMGESTURES = 1, QT_EXTENDED_SURFACE_WINDOWFLAG_STAYSONTOP = 2, }; #endif /* QT_EXTENDED_SURFACE_WINDOWFLAG_ENUM */ struct qt_extended_surface_listener { /** * onscreen_visibility - (none) * @visible: (none) */ void (*onscreen_visibility)(void *data, struct qt_extended_surface *qt_extended_surface, int32_t visible); /** * set_generic_property - (none) * @name: (none) * @value: (none) */ void (*set_generic_property)(void *data, struct qt_extended_surface *qt_extended_surface, const char *name, struct wl_array *value); /** * close - (none) */ void (*close)(void *data, struct qt_extended_surface *qt_extended_surface); }; static inline int qt_extended_surface_add_listener(struct qt_extended_surface *qt_extended_surface, const struct qt_extended_surface_listener *listener, void *data) { return wl_proxy_add_listener((struct wl_proxy *) qt_extended_surface, (void (**)(void)) listener, data); } #define QT_EXTENDED_SURFACE_UPDATE_GENERIC_PROPERTY 0 #define QT_EXTENDED_SURFACE_SET_CONTENT_ORIENTATION 1 #define QT_EXTENDED_SURFACE_SET_WINDOW_FLAGS 2 static inline void qt_extended_surface_set_user_data(struct qt_extended_surface *qt_extended_surface, void *user_data) { WAYLAND_wl_proxy_set_user_data((struct wl_proxy *) qt_extended_surface, user_data); } static inline void * qt_extended_surface_get_user_data(struct qt_extended_surface *qt_extended_surface) { return WAYLAND_wl_proxy_get_user_data((struct wl_proxy *) qt_extended_surface); } static inline void qt_extended_surface_destroy(struct qt_extended_surface *qt_extended_surface) { WAYLAND_wl_proxy_destroy((struct wl_proxy *) qt_extended_surface); } static inline void qt_extended_surface_update_generic_property(struct qt_extended_surface *qt_extended_surface, const char *name, struct wl_array *value) { WAYLAND_wl_proxy_marshal((struct wl_proxy *) qt_extended_surface, QT_EXTENDED_SURFACE_UPDATE_GENERIC_PROPERTY, name, value); } static inline void qt_extended_surface_set_content_orientation(struct qt_extended_surface *qt_extended_surface, int32_t orientation) { WAYLAND_wl_proxy_marshal((struct wl_proxy *) qt_extended_surface, QT_EXTENDED_SURFACE_SET_CONTENT_ORIENTATION, orientation); } static inline void qt_extended_surface_set_window_flags(struct qt_extended_surface *qt_extended_surface, int32_t flags) { WAYLAND_wl_proxy_marshal((struct wl_proxy *) qt_extended_surface, QT_EXTENDED_SURFACE_SET_WINDOW_FLAGS, flags); } /* wayland-qt-touch-extension.h */ extern const struct wl_interface qt_touch_extension_interface; #ifndef QT_TOUCH_EXTENSION_FLAGS_ENUM #define QT_TOUCH_EXTENSION_FLAGS_ENUM enum qt_touch_extension_flags { QT_TOUCH_EXTENSION_FLAGS_MOUSE_FROM_TOUCH = 0x1, }; #endif /* QT_TOUCH_EXTENSION_FLAGS_ENUM */ struct qt_touch_extension_listener { /** * touch - (none) * @time: (none) * @id: (none) * @state: (none) * @x: (none) * @y: (none) * @normalized_x: (none) * @normalized_y: (none) * @width: (none) * @height: (none) * @pressure: (none) * @velocity_x: (none) * @velocity_y: (none) * @flags: (none) * @rawdata: (none) */ void (*touch)(void *data, struct qt_touch_extension *qt_touch_extension, uint32_t time, uint32_t id, uint32_t state, int32_t x, int32_t y, int32_t normalized_x, int32_t normalized_y, int32_t width, int32_t height, uint32_t pressure, int32_t velocity_x, int32_t velocity_y, uint32_t flags, struct wl_array *rawdata); /** * configure - (none) * @flags: (none) */ void (*configure)(void *data, struct qt_touch_extension *qt_touch_extension, uint32_t flags); }; static inline int qt_touch_extension_add_listener(struct qt_touch_extension *qt_touch_extension, const struct qt_touch_extension_listener *listener, void *data) { return wl_proxy_add_listener((struct wl_proxy *) qt_touch_extension, (void (**)(void)) listener, data); } #define QT_TOUCH_EXTENSION_DUMMY 0 static inline void qt_touch_extension_set_user_data(struct qt_touch_extension *qt_touch_extension, void *user_data) { WAYLAND_wl_proxy_set_user_data((struct wl_proxy *) qt_touch_extension, user_data); } static inline void * qt_touch_extension_get_user_data(struct qt_touch_extension *qt_touch_extension) { return WAYLAND_wl_proxy_get_user_data((struct wl_proxy *) qt_touch_extension); } static inline void qt_touch_extension_destroy(struct qt_touch_extension *qt_touch_extension) { WAYLAND_wl_proxy_destroy((struct wl_proxy *) qt_touch_extension); } static inline void qt_touch_extension_dummy(struct qt_touch_extension *qt_touch_extension) { WAYLAND_wl_proxy_marshal((struct wl_proxy *) qt_touch_extension, QT_TOUCH_EXTENSION_DUMMY); } /* wayland-qt-windowmanager.h */ extern const struct wl_interface qt_windowmanager_interface; struct qt_windowmanager_listener { /** * hints - (none) * @show_is_fullscreen: (none) */ void (*hints)(void *data, struct qt_windowmanager *qt_windowmanager, int32_t show_is_fullscreen); /** * quit - (none) */ void (*quit)(void *data, struct qt_windowmanager *qt_windowmanager); }; static inline int qt_windowmanager_add_listener(struct qt_windowmanager *qt_windowmanager, const struct qt_windowmanager_listener *listener, void *data) { return wl_proxy_add_listener((struct wl_proxy *) qt_windowmanager, (void (**)(void)) listener, data); } #define QT_WINDOWMANAGER_OPEN_URL 0 static inline void qt_windowmanager_set_user_data(struct qt_windowmanager *qt_windowmanager, void *user_data) { WAYLAND_wl_proxy_set_user_data((struct wl_proxy *) qt_windowmanager, user_data); } static inline void * qt_windowmanager_get_user_data(struct qt_windowmanager *qt_windowmanager) { return WAYLAND_wl_proxy_get_user_data((struct wl_proxy *) qt_windowmanager); } static inline void qt_windowmanager_destroy(struct qt_windowmanager *qt_windowmanager) { WAYLAND_wl_proxy_destroy((struct wl_proxy *) qt_windowmanager); } static inline void qt_windowmanager_open_url(struct qt_windowmanager *qt_windowmanager, uint32_t remaining, const char *url) { WAYLAND_wl_proxy_marshal((struct wl_proxy *) qt_windowmanager, QT_WINDOWMANAGER_OPEN_URL, remaining, url); } #endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */ #endif /* SDL_waylandtouch_h_ */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylandtouch.h
C
apache-2.0
11,227
/* 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_VIDEO_DRIVER_WAYLAND #include "SDL_video.h" #include "SDL_mouse.h" #include "SDL_stdinc.h" #include "../../events/SDL_events_c.h" #include "SDL_waylandvideo.h" #include "SDL_waylandevents_c.h" #include "SDL_waylandwindow.h" #include "SDL_waylandopengles.h" #include "SDL_waylandmouse.h" #include "SDL_waylandtouch.h" #include "SDL_waylandclipboard.h" #include "SDL_waylandvulkan.h" #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <xkbcommon/xkbcommon.h> #include "SDL_waylanddyn.h" #include <wayland-util.h> #include "xdg-shell-client-protocol.h" #include "xdg-shell-unstable-v6-client-protocol.h" #include "xdg-decoration-unstable-v1-client-protocol.h" #include "org-kde-kwin-server-decoration-manager-client-protocol.h" #define WAYLANDVID_DRIVER_NAME "wayland" /* Initialization/Query functions */ static int Wayland_VideoInit(_THIS); static void Wayland_GetDisplayModes(_THIS, SDL_VideoDisplay *sdl_display); static int Wayland_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode); static void Wayland_VideoQuit(_THIS); /* Find out what class name we should use * Based on src/video/x11/SDL_x11video.c */ static char * get_classname() { /* !!! FIXME: this is probably wrong, albeit harmless in many common cases. From protocol spec: "The surface class identifies the general class of applications to which the surface belongs. A common convention is to use the file name (or the full path if it is a non-standard location) of the application's .desktop file as the class." */ char *spot; #if defined(__LINUX__) || defined(__FREEBSD__) char procfile[1024]; char linkfile[1024]; int linksize; #endif /* First allow environment variable override */ spot = SDL_getenv("SDL_VIDEO_WAYLAND_WMCLASS"); if (spot) { return SDL_strdup(spot); } else { /* Fallback to the "old" envvar */ spot = SDL_getenv("SDL_VIDEO_X11_WMCLASS"); if (spot) { return SDL_strdup(spot); } } /* Next look at the application's executable name */ #if defined(__LINUX__) || defined(__FREEBSD__) #if defined(__LINUX__) SDL_snprintf(procfile, SDL_arraysize(procfile), "/proc/%d/exe", getpid()); #elif defined(__FREEBSD__) SDL_snprintf(procfile, SDL_arraysize(procfile), "/proc/%d/file", getpid()); #else #error Where can we find the executable name? #endif linksize = readlink(procfile, linkfile, sizeof(linkfile) - 1); if (linksize > 0) { linkfile[linksize] = '\0'; spot = SDL_strrchr(linkfile, '/'); if (spot) { return SDL_strdup(spot + 1); } else { return SDL_strdup(linkfile); } } #endif /* __LINUX__ || __FREEBSD__ */ /* Finally use the default we've used forever */ return SDL_strdup("SDL_App"); } /* Wayland driver bootstrap functions */ static int Wayland_Available(void) { struct wl_display *display = NULL; if (SDL_WAYLAND_LoadSymbols()) { display = WAYLAND_wl_display_connect(NULL); if (display != NULL) { WAYLAND_wl_display_disconnect(display); } SDL_WAYLAND_UnloadSymbols(); } return (display != NULL); } static void Wayland_DeleteDevice(SDL_VideoDevice *device) { SDL_free(device); SDL_WAYLAND_UnloadSymbols(); } static SDL_VideoDevice * Wayland_CreateDevice(int devindex) { SDL_VideoDevice *device; if (!SDL_WAYLAND_LoadSymbols()) { return NULL; } /* Initialize all variables that we clean on shutdown */ device = SDL_calloc(1, sizeof(SDL_VideoDevice)); if (!device) { SDL_WAYLAND_UnloadSymbols(); SDL_OutOfMemory(); return NULL; } /* Set the function pointers */ device->VideoInit = Wayland_VideoInit; device->VideoQuit = Wayland_VideoQuit; device->SetDisplayMode = Wayland_SetDisplayMode; device->GetDisplayModes = Wayland_GetDisplayModes; device->GetWindowWMInfo = Wayland_GetWindowWMInfo; device->PumpEvents = Wayland_PumpEvents; device->GL_SwapWindow = Wayland_GLES_SwapWindow; device->GL_GetSwapInterval = Wayland_GLES_GetSwapInterval; device->GL_SetSwapInterval = Wayland_GLES_SetSwapInterval; device->GL_GetDrawableSize = Wayland_GLES_GetDrawableSize; device->GL_MakeCurrent = Wayland_GLES_MakeCurrent; device->GL_CreateContext = Wayland_GLES_CreateContext; device->GL_LoadLibrary = Wayland_GLES_LoadLibrary; device->GL_UnloadLibrary = Wayland_GLES_UnloadLibrary; device->GL_GetProcAddress = Wayland_GLES_GetProcAddress; device->GL_DeleteContext = Wayland_GLES_DeleteContext; device->CreateSDLWindow = Wayland_CreateWindow; device->ShowWindow = Wayland_ShowWindow; device->SetWindowFullscreen = Wayland_SetWindowFullscreen; device->MaximizeWindow = Wayland_MaximizeWindow; device->SetWindowGrab = Wayland_SetWindowGrab; device->RestoreWindow = Wayland_RestoreWindow; device->SetWindowBordered = Wayland_SetWindowBordered; device->SetWindowSize = Wayland_SetWindowSize; device->SetWindowTitle = Wayland_SetWindowTitle; device->DestroyWindow = Wayland_DestroyWindow; device->SetWindowHitTest = Wayland_SetWindowHitTest; device->SetClipboardText = Wayland_SetClipboardText; device->GetClipboardText = Wayland_GetClipboardText; device->HasClipboardText = Wayland_HasClipboardText; #if SDL_VIDEO_VULKAN device->Vulkan_LoadLibrary = Wayland_Vulkan_LoadLibrary; device->Vulkan_UnloadLibrary = Wayland_Vulkan_UnloadLibrary; device->Vulkan_GetInstanceExtensions = Wayland_Vulkan_GetInstanceExtensions; device->Vulkan_CreateSurface = Wayland_Vulkan_CreateSurface; device->Vulkan_GetDrawableSize = Wayland_Vulkan_GetDrawableSize; #endif device->free = Wayland_DeleteDevice; return device; } VideoBootStrap Wayland_bootstrap = { WAYLANDVID_DRIVER_NAME, "SDL Wayland video driver", Wayland_Available, Wayland_CreateDevice }; static void display_handle_geometry(void *data, struct wl_output *output, int x, int y, int physical_width, int physical_height, int subpixel, const char *make, const char *model, int transform) { SDL_VideoDisplay *display = data; display->name = SDL_strdup(model); } static void display_handle_mode(void *data, struct wl_output *output, uint32_t flags, int width, int height, int refresh) { SDL_DisplayMode mode; SDL_VideoDisplay *display = data; SDL_zero(mode); mode.format = SDL_PIXELFORMAT_RGB888; mode.w = width; mode.h = height; mode.refresh_rate = refresh / 1000; // mHz to Hz mode.driverdata = ((SDL_WaylandOutputData*)display->driverdata)->output; SDL_AddDisplayMode(display, &mode); if (flags & WL_OUTPUT_MODE_CURRENT) { display->current_mode = mode; display->desktop_mode = mode; } } static void display_handle_done(void *data, struct wl_output *output) { /* !!! FIXME: this will fail on any further property changes! */ SDL_VideoDisplay *display = data; SDL_AddVideoDisplay(display); wl_output_set_user_data(output, display->driverdata); SDL_free(display->name); SDL_free(display); } static void display_handle_scale(void *data, struct wl_output *output, int32_t factor) { SDL_VideoDisplay *display = data; ((SDL_WaylandOutputData*)display->driverdata)->scale_factor = factor; } static const struct wl_output_listener output_listener = { display_handle_geometry, display_handle_mode, display_handle_done, display_handle_scale }; static void Wayland_add_display(SDL_VideoData *d, uint32_t id) { struct wl_output *output; SDL_WaylandOutputData *data; SDL_VideoDisplay *display = SDL_malloc(sizeof *display); if (!display) { SDL_OutOfMemory(); return; } SDL_zero(*display); output = wl_registry_bind(d->registry, id, &wl_output_interface, 2); if (!output) { SDL_SetError("Failed to retrieve output."); SDL_free(display); return; } data = SDL_malloc(sizeof *data); data->output = output; data->scale_factor = 1.0; display->driverdata = data; wl_output_add_listener(output, &output_listener, display); } #ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH static void windowmanager_hints(void *data, struct qt_windowmanager *qt_windowmanager, int32_t show_is_fullscreen) { } static void windowmanager_quit(void *data, struct qt_windowmanager *qt_windowmanager) { SDL_SendQuit(); } static const struct qt_windowmanager_listener windowmanager_listener = { windowmanager_hints, windowmanager_quit, }; #endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */ static void handle_ping_zxdg_shell(void *data, struct zxdg_shell_v6 *zxdg, uint32_t serial) { zxdg_shell_v6_pong(zxdg, serial); } static const struct zxdg_shell_v6_listener shell_listener_zxdg = { handle_ping_zxdg_shell }; static void handle_ping_xdg_wm_base(void *data, struct xdg_wm_base *xdg, uint32_t serial) { xdg_wm_base_pong(xdg, serial); } static const struct xdg_wm_base_listener shell_listener_xdg = { handle_ping_xdg_wm_base }; static void display_handle_global(void *data, struct wl_registry *registry, uint32_t id, const char *interface, uint32_t version) { SDL_VideoData *d = data; /*printf("WAYLAND INTERFACE: %s\n", interface);*/ if (strcmp(interface, "wl_compositor") == 0) { d->compositor = wl_registry_bind(d->registry, id, &wl_compositor_interface, SDL_min(3, version)); } else if (strcmp(interface, "wl_output") == 0) { Wayland_add_display(d, id); } else if (strcmp(interface, "wl_seat") == 0) { Wayland_display_add_input(d, id, version); } else if (strcmp(interface, "xdg_wm_base") == 0) { d->shell.xdg = wl_registry_bind(d->registry, id, &xdg_wm_base_interface, 1); xdg_wm_base_add_listener(d->shell.xdg, &shell_listener_xdg, NULL); } else if (strcmp(interface, "zxdg_shell_v6") == 0) { d->shell.zxdg = wl_registry_bind(d->registry, id, &zxdg_shell_v6_interface, 1); zxdg_shell_v6_add_listener(d->shell.zxdg, &shell_listener_zxdg, NULL); } else if (strcmp(interface, "wl_shell") == 0) { d->shell.wl = wl_registry_bind(d->registry, id, &wl_shell_interface, 1); } else if (strcmp(interface, "wl_shm") == 0) { d->shm = wl_registry_bind(registry, id, &wl_shm_interface, 1); d->cursor_theme = WAYLAND_wl_cursor_theme_load(NULL, 32, d->shm); } else if (strcmp(interface, "zwp_relative_pointer_manager_v1") == 0) { Wayland_display_add_relative_pointer_manager(d, id); } else if (strcmp(interface, "zwp_pointer_constraints_v1") == 0) { Wayland_display_add_pointer_constraints(d, id); } else if (strcmp(interface, "wl_data_device_manager") == 0) { d->data_device_manager = wl_registry_bind(d->registry, id, &wl_data_device_manager_interface, SDL_min(3, version)); } else if (strcmp(interface, "zxdg_decoration_manager_v1") == 0) { d->decoration_manager = wl_registry_bind(d->registry, id, &zxdg_decoration_manager_v1_interface, 1); } else if (strcmp(interface, "org_kde_kwin_server_decoration_manager") == 0) { d->kwin_server_decoration_manager = wl_registry_bind(d->registry, id, &org_kde_kwin_server_decoration_manager_interface, 1); #ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH } else if (strcmp(interface, "qt_touch_extension") == 0) { Wayland_touch_create(d, id); } else if (strcmp(interface, "qt_surface_extension") == 0) { d->surface_extension = wl_registry_bind(registry, id, &qt_surface_extension_interface, 1); } else if (strcmp(interface, "qt_windowmanager") == 0) { d->windowmanager = wl_registry_bind(registry, id, &qt_windowmanager_interface, 1); qt_windowmanager_add_listener(d->windowmanager, &windowmanager_listener, d); #endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */ } } static void display_remove_global(void *data, struct wl_registry *registry, uint32_t id) {} static const struct wl_registry_listener registry_listener = { display_handle_global, display_remove_global }; int Wayland_VideoInit(_THIS) { SDL_VideoData *data = SDL_calloc(1, sizeof(*data)); if (data == NULL) return SDL_OutOfMemory(); _this->driverdata = data; data->xkb_context = WAYLAND_xkb_context_new(0); if (!data->xkb_context) { return SDL_SetError("Failed to create XKB context"); } data->display = WAYLAND_wl_display_connect(NULL); if (data->display == NULL) { return SDL_SetError("Failed to connect to a Wayland display"); } data->registry = wl_display_get_registry(data->display); if (data->registry == NULL) { return SDL_SetError("Failed to get the Wayland registry"); } wl_registry_add_listener(data->registry, &registry_listener, data); // First roundtrip to receive all registry objects. WAYLAND_wl_display_roundtrip(data->display); // Second roundtrip to receive all output events. WAYLAND_wl_display_roundtrip(data->display); Wayland_InitMouse(); /* Get the surface class name, usually the name of the application */ data->classname = get_classname(); WAYLAND_wl_display_flush(data->display); return 0; } static void Wayland_GetDisplayModes(_THIS, SDL_VideoDisplay *sdl_display) { // Nothing to do here, everything was already done in the wl_output // callbacks. } static int Wayland_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode) { return SDL_Unsupported(); } void Wayland_VideoQuit(_THIS) { SDL_VideoData *data = _this->driverdata; int i, j; Wayland_FiniMouse (); for (i = 0; i < _this->num_displays; ++i) { SDL_VideoDisplay *display = &_this->displays[i]; wl_output_destroy(((SDL_WaylandOutputData*)display->driverdata)->output); SDL_free(display->driverdata); display->driverdata = NULL; for (j = display->num_display_modes; j--;) { display->display_modes[j].driverdata = NULL; } display->desktop_mode.driverdata = NULL; } Wayland_display_destroy_input(data); Wayland_display_destroy_pointer_constraints(data); Wayland_display_destroy_relative_pointer_manager(data); if (data->xkb_context) { WAYLAND_xkb_context_unref(data->xkb_context); data->xkb_context = NULL; } #ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH if (data->windowmanager) qt_windowmanager_destroy(data->windowmanager); if (data->surface_extension) qt_surface_extension_destroy(data->surface_extension); Wayland_touch_destroy(data); #endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */ if (data->shm) wl_shm_destroy(data->shm); if (data->cursor_theme) WAYLAND_wl_cursor_theme_destroy(data->cursor_theme); if (data->shell.wl) wl_shell_destroy(data->shell.wl); if (data->shell.xdg) xdg_wm_base_destroy(data->shell.xdg); if (data->shell.zxdg) zxdg_shell_v6_destroy(data->shell.zxdg); if (data->compositor) wl_compositor_destroy(data->compositor); if (data->registry) wl_registry_destroy(data->registry); if (data->display) { WAYLAND_wl_display_flush(data->display); WAYLAND_wl_display_disconnect(data->display); } SDL_free(data->classname); SDL_free(data); _this->driverdata = NULL; } #endif /* SDL_VIDEO_DRIVER_WAYLAND */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylandvideo.c
C
apache-2.0
16,901
/* 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_waylandvideo_h_ #define SDL_waylandvideo_h_ /* !!! FIXME: xdg_wm_base is the stable replacement for zxdg_shell_v6. While it's !!! FIXME: harmless to leave it here, consider deleting the obsolete codepath !!! FIXME: soon, since Wayland (with xdg_wm_base) will probably be mainline !!! FIXME: by the time people are relying on this SDL target. It's available !!! FIXME: in Ubuntu 18.04 (and other distros). */ #define MESA_EGL_NO_X11_HEADERS #include <EGL/egl.h> #include "wayland-util.h" struct xkb_context; struct SDL_WaylandInput; #ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH struct SDL_WaylandTouch; struct qt_surface_extension; struct qt_windowmanager; #endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */ typedef struct { struct wl_display *display; int display_disconnected; struct wl_registry *registry; struct wl_compositor *compositor; struct wl_shm *shm; struct wl_cursor_theme *cursor_theme; struct wl_pointer *pointer; struct { struct xdg_wm_base *xdg; struct zxdg_shell_v6 *zxdg; struct wl_shell *wl; } shell; struct zwp_relative_pointer_manager_v1 *relative_pointer_manager; struct zwp_pointer_constraints_v1 *pointer_constraints; struct wl_data_device_manager *data_device_manager; struct zxdg_decoration_manager_v1 *decoration_manager; struct org_kde_kwin_server_decoration_manager *kwin_server_decoration_manager; EGLDisplay edpy; EGLContext context; EGLConfig econf; struct xkb_context *xkb_context; struct SDL_WaylandInput *input; #ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH struct SDL_WaylandTouch *touch; struct qt_surface_extension *surface_extension; struct qt_windowmanager *windowmanager; #endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */ char *classname; int relative_mouse_mode; } SDL_VideoData; typedef struct { struct wl_output *output; float scale_factor; } SDL_WaylandOutputData; #endif /* SDL_waylandvideo_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylandvideo.h
C
apache-2.0
2,993
/* 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. */ /* * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's * SDL_x11vulkan.c. */ #include "../../SDL_internal.h" #if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_WAYLAND #include "SDL_waylandvideo.h" #include "SDL_waylandwindow.h" #include "SDL_assert.h" #include "SDL_loadso.h" #include "SDL_waylandvulkan.h" #include "SDL_syswm.h" int Wayland_Vulkan_LoadLibrary(_THIS, const char *path) { VkExtensionProperties *extensions = NULL; Uint32 i, extensionCount = 0; SDL_bool hasSurfaceExtension = SDL_FALSE; SDL_bool hasWaylandSurfaceExtension = SDL_FALSE; PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL; if(_this->vulkan_config.loader_handle) return SDL_SetError("Vulkan already loaded"); /* Load the Vulkan loader library */ if(!path) path = SDL_getenv("SDL_VULKAN_LIBRARY"); if(!path) path = "libvulkan.so.1"; _this->vulkan_config.loader_handle = SDL_LoadObject(path); if(!_this->vulkan_config.loader_handle) return -1; SDL_strlcpy(_this->vulkan_config.loader_path, path, SDL_arraysize(_this->vulkan_config.loader_path)); vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)SDL_LoadFunction( _this->vulkan_config.loader_handle, "vkGetInstanceProcAddr"); if(!vkGetInstanceProcAddr) goto fail; _this->vulkan_config.vkGetInstanceProcAddr = (void *)vkGetInstanceProcAddr; _this->vulkan_config.vkEnumerateInstanceExtensionProperties = (void *)((PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr)( VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties"); if(!_this->vulkan_config.vkEnumerateInstanceExtensionProperties) goto fail; extensions = SDL_Vulkan_CreateInstanceExtensionsList( (PFN_vkEnumerateInstanceExtensionProperties) _this->vulkan_config.vkEnumerateInstanceExtensionProperties, &extensionCount); if(!extensions) goto fail; for(i = 0; i < extensionCount; i++) { if(SDL_strcmp(VK_KHR_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0) hasSurfaceExtension = SDL_TRUE; else if(SDL_strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0) hasWaylandSurfaceExtension = SDL_TRUE; } SDL_free(extensions); if(!hasSurfaceExtension) { SDL_SetError("Installed Vulkan doesn't implement the " VK_KHR_SURFACE_EXTENSION_NAME " extension"); goto fail; } else if(!hasWaylandSurfaceExtension) { SDL_SetError("Installed Vulkan doesn't implement the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME "extension"); goto fail; } return 0; fail: SDL_UnloadObject(_this->vulkan_config.loader_handle); _this->vulkan_config.loader_handle = NULL; return -1; } void Wayland_Vulkan_UnloadLibrary(_THIS) { if(_this->vulkan_config.loader_handle) { SDL_UnloadObject(_this->vulkan_config.loader_handle); _this->vulkan_config.loader_handle = NULL; } } SDL_bool Wayland_Vulkan_GetInstanceExtensions(_THIS, SDL_Window *window, unsigned *count, const char **names) { static const char *const extensionsForWayland[] = { VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME }; if(!_this->vulkan_config.loader_handle) { SDL_SetError("Vulkan is not loaded"); return SDL_FALSE; } return SDL_Vulkan_GetInstanceExtensions_Helper( count, names, SDL_arraysize(extensionsForWayland), extensionsForWayland); } void Wayland_Vulkan_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h) { SDL_WindowData *data; if (window->driverdata) { data = (SDL_WindowData *) window->driverdata; if (w) { *w = window->w * data->scale_factor; } if (h) { *h = window->h * data->scale_factor; } } } SDL_bool Wayland_Vulkan_CreateSurface(_THIS, SDL_Window *window, VkInstance instance, VkSurfaceKHR *surface) { SDL_WindowData *windowData = (SDL_WindowData *)window->driverdata; PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr; PFN_vkCreateWaylandSurfaceKHR vkCreateWaylandSurfaceKHR = (PFN_vkCreateWaylandSurfaceKHR)vkGetInstanceProcAddr( instance, "vkCreateWaylandSurfaceKHR"); VkWaylandSurfaceCreateInfoKHR createInfo; VkResult result; if(!_this->vulkan_config.loader_handle) { SDL_SetError("Vulkan is not loaded"); return SDL_FALSE; } if(!vkCreateWaylandSurfaceKHR) { SDL_SetError(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME " extension is not enabled in the Vulkan instance."); return SDL_FALSE; } SDL_zero(createInfo); createInfo.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR; createInfo.pNext = NULL; createInfo.flags = 0; createInfo.display = windowData->waylandData->display; createInfo.surface = windowData->surface; result = vkCreateWaylandSurfaceKHR(instance, &createInfo, NULL, surface); if(result != VK_SUCCESS) { SDL_SetError("vkCreateWaylandSurfaceKHR failed: %s", SDL_Vulkan_GetResultString(result)); return SDL_FALSE; } return SDL_TRUE; } #endif /* vim: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylandvulkan.c
C
apache-2.0
6,759
/* 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. */ /* * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's * SDL_x11vulkan.h. */ #include "../../SDL_internal.h" #ifndef SDL_waylandvulkan_h_ #define SDL_waylandvulkan_h_ #include "../SDL_vulkan_internal.h" #include "../SDL_sysvideo.h" #if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_WAYLAND int Wayland_Vulkan_LoadLibrary(_THIS, const char *path); void Wayland_Vulkan_UnloadLibrary(_THIS); SDL_bool Wayland_Vulkan_GetInstanceExtensions(_THIS, SDL_Window *window, unsigned *count, const char **names); void Wayland_Vulkan_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h); SDL_bool Wayland_Vulkan_CreateSurface(_THIS, SDL_Window *window, VkInstance instance, VkSurfaceKHR *surface); #endif #endif /* SDL_waylandvulkan_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylandvulkan.h
C
apache-2.0
1,961
/* 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_VIDEO_DRIVER_WAYLAND && SDL_VIDEO_OPENGL_EGL #include "../SDL_sysvideo.h" #include "../../events/SDL_windowevents_c.h" #include "../SDL_egl_c.h" #include "SDL_waylandevents_c.h" #include "SDL_waylandwindow.h" #include "SDL_waylandvideo.h" #include "SDL_waylandtouch.h" #include "SDL_waylanddyn.h" #include "SDL_hints.h" #include "xdg-shell-client-protocol.h" #include "xdg-shell-unstable-v6-client-protocol.h" #include "xdg-decoration-unstable-v1-client-protocol.h" #include "org-kde-kwin-server-decoration-manager-client-protocol.h" static float get_window_scale_factor(SDL_Window *window) { return ((SDL_WindowData*)window->driverdata)->scale_factor; } /* On modern desktops, we probably will use the xdg-shell protocol instead of wl_shell, but wl_shell might be useful on older Wayland installs that don't have the newer protocol, or embedded things that don't have a full window manager. */ static void handle_ping_wl_shell_surface(void *data, struct wl_shell_surface *shell_surface, uint32_t serial) { wl_shell_surface_pong(shell_surface, serial); } static void handle_configure_wl_shell_surface(void *data, struct wl_shell_surface *shell_surface, uint32_t edges, int32_t width, int32_t height) { SDL_WindowData *wind = (SDL_WindowData *)data; SDL_Window *window = wind->sdlwindow; /* wl_shell_surface spec states that this is a suggestion. Ignore if less than or greater than max/min size. */ if (width == 0 || height == 0) { return; } if (!(window->flags & SDL_WINDOW_FULLSCREEN)) { if ((window->flags & SDL_WINDOW_RESIZABLE)) { if (window->max_w > 0) { width = SDL_min(width, window->max_w); } width = SDL_max(width, window->min_w); if (window->max_h > 0) { height = SDL_min(height, window->max_h); } height = SDL_max(height, window->min_h); } else { return; } } wind->resize.width = width; wind->resize.height = height; wind->resize.pending = SDL_TRUE; if (!(window->flags & SDL_WINDOW_OPENGL)) { Wayland_HandlePendingResize(window); /* OpenGL windows handle this in SwapWindow */ } } static void handle_popup_done_wl_shell_surface(void *data, struct wl_shell_surface *shell_surface) { } static const struct wl_shell_surface_listener shell_surface_listener_wl = { handle_ping_wl_shell_surface, handle_configure_wl_shell_surface, handle_popup_done_wl_shell_surface }; static void handle_configure_zxdg_shell_surface(void *data, struct zxdg_surface_v6 *zxdg, uint32_t serial) { SDL_WindowData *wind = (SDL_WindowData *)data; SDL_Window *window = wind->sdlwindow; struct wl_region *region; if (!wind->shell_surface.zxdg.initial_configure_seen) { window->w = 0; window->h = 0; SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESIZED, wind->resize.width, wind->resize.height); window->w = wind->resize.width; window->h = wind->resize.height; wl_surface_set_buffer_scale(wind->surface, get_window_scale_factor(window)); if (wind->egl_window) { WAYLAND_wl_egl_window_resize(wind->egl_window, window->w * get_window_scale_factor(window), window->h * get_window_scale_factor(window), 0, 0); } zxdg_surface_v6_ack_configure(zxdg, serial); region = wl_compositor_create_region(wind->waylandData->compositor); wl_region_add(region, 0, 0, window->w, window->h); wl_surface_set_opaque_region(wind->surface, region); wl_region_destroy(region); wind->shell_surface.zxdg.initial_configure_seen = SDL_TRUE; } else { wind->resize.pending = SDL_TRUE; wind->resize.configure = SDL_TRUE; wind->resize.serial = serial; if (!(window->flags & SDL_WINDOW_OPENGL)) { Wayland_HandlePendingResize(window); /* OpenGL windows handle this in SwapWindow */ } } } static const struct zxdg_surface_v6_listener shell_surface_listener_zxdg = { handle_configure_zxdg_shell_surface }; static void handle_configure_zxdg_toplevel(void *data, struct zxdg_toplevel_v6 *zxdg_toplevel_v6, int32_t width, int32_t height, struct wl_array *states) { SDL_WindowData *wind = (SDL_WindowData *)data; SDL_Window *window = wind->sdlwindow; enum zxdg_toplevel_v6_state *state; SDL_bool fullscreen = SDL_FALSE; wl_array_for_each(state, states) { if (*state == ZXDG_TOPLEVEL_V6_STATE_FULLSCREEN) { fullscreen = SDL_TRUE; } } if (!fullscreen) { if (width == 0 || height == 0) { width = window->windowed.w; height = window->windowed.h; } /* zxdg_toplevel spec states that this is a suggestion. Ignore if less than or greater than max/min size. */ if ((window->flags & SDL_WINDOW_RESIZABLE)) { if (window->max_w > 0) { width = SDL_min(width, window->max_w); } width = SDL_max(width, window->min_w); if (window->max_h > 0) { height = SDL_min(height, window->max_h); } height = SDL_max(height, window->min_h); } else { wind->resize.width = window->w; wind->resize.height = window->h; return; } } if (width == 0 || height == 0) { wind->resize.width = window->w; wind->resize.height = window->h; return; } wind->resize.width = width; wind->resize.height = height; } static void handle_close_zxdg_toplevel(void *data, struct zxdg_toplevel_v6 *zxdg_toplevel_v6) { SDL_WindowData *window = (SDL_WindowData *)data; SDL_SendWindowEvent(window->sdlwindow, SDL_WINDOWEVENT_CLOSE, 0, 0); } static const struct zxdg_toplevel_v6_listener toplevel_listener_zxdg = { handle_configure_zxdg_toplevel, handle_close_zxdg_toplevel }; static void handle_configure_xdg_shell_surface(void *data, struct xdg_surface *xdg, uint32_t serial) { SDL_WindowData *wind = (SDL_WindowData *)data; SDL_Window *window = wind->sdlwindow; struct wl_region *region; if (!wind->shell_surface.xdg.initial_configure_seen) { window->w = 0; window->h = 0; SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESIZED, wind->resize.width, wind->resize.height); window->w = wind->resize.width; window->h = wind->resize.height; wl_surface_set_buffer_scale(wind->surface, get_window_scale_factor(window)); if (wind->egl_window) { WAYLAND_wl_egl_window_resize(wind->egl_window, window->w * get_window_scale_factor(window), window->h * get_window_scale_factor(window), 0, 0); } xdg_surface_ack_configure(xdg, serial); region = wl_compositor_create_region(wind->waylandData->compositor); wl_region_add(region, 0, 0, window->w, window->h); wl_surface_set_opaque_region(wind->surface, region); wl_region_destroy(region); wind->shell_surface.xdg.initial_configure_seen = SDL_TRUE; } else { wind->resize.pending = SDL_TRUE; wind->resize.configure = SDL_TRUE; wind->resize.serial = serial; if (!(window->flags & SDL_WINDOW_OPENGL)) { Wayland_HandlePendingResize(window); /* OpenGL windows handle this in SwapWindow */ } } } static const struct xdg_surface_listener shell_surface_listener_xdg = { handle_configure_xdg_shell_surface }; static void handle_configure_xdg_toplevel(void *data, struct xdg_toplevel *xdg_toplevel, int32_t width, int32_t height, struct wl_array *states) { SDL_WindowData *wind = (SDL_WindowData *)data; SDL_Window *window = wind->sdlwindow; enum xdg_toplevel_state *state; SDL_bool fullscreen = SDL_FALSE; wl_array_for_each(state, states) { if (*state == XDG_TOPLEVEL_STATE_FULLSCREEN) { fullscreen = SDL_TRUE; } } if (!fullscreen) { if (width == 0 || height == 0) { width = window->windowed.w; height = window->windowed.h; } /* xdg_toplevel spec states that this is a suggestion. Ignore if less than or greater than max/min size. */ if ((window->flags & SDL_WINDOW_RESIZABLE)) { if (window->max_w > 0) { width = SDL_min(width, window->max_w); } width = SDL_max(width, window->min_w); if (window->max_h > 0) { height = SDL_min(height, window->max_h); } height = SDL_max(height, window->min_h); } else { wind->resize.width = window->w; wind->resize.height = window->h; return; } } if (width == 0 || height == 0) { wind->resize.width = window->w; wind->resize.height = window->h; return; } wind->resize.width = width; wind->resize.height = height; } static void handle_close_xdg_toplevel(void *data, struct xdg_toplevel *xdg_toplevel) { SDL_WindowData *window = (SDL_WindowData *)data; SDL_SendWindowEvent(window->sdlwindow, SDL_WINDOWEVENT_CLOSE, 0, 0); } static const struct xdg_toplevel_listener toplevel_listener_xdg = { handle_configure_xdg_toplevel, handle_close_xdg_toplevel }; #ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH static void handle_onscreen_visibility(void *data, struct qt_extended_surface *qt_extended_surface, int32_t visible) { } static void handle_set_generic_property(void *data, struct qt_extended_surface *qt_extended_surface, const char *name, struct wl_array *value) { } static void handle_close(void *data, struct qt_extended_surface *qt_extended_surface) { SDL_WindowData *window = (SDL_WindowData *)data; SDL_SendWindowEvent(window->sdlwindow, SDL_WINDOWEVENT_CLOSE, 0, 0); } static const struct qt_extended_surface_listener extended_surface_listener = { handle_onscreen_visibility, handle_set_generic_property, handle_close, }; #endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */ static void update_scale_factor(SDL_WindowData *window) { float old_factor = window->scale_factor, new_factor = 0.0; int i; if (!(window->sdlwindow->flags & SDL_WINDOW_ALLOW_HIGHDPI)) { return; } if (!window->num_outputs) { new_factor = old_factor; } if (FULLSCREEN_VISIBLE(window->sdlwindow) && window->sdlwindow->fullscreen_mode.driverdata) { new_factor = ((SDL_WaylandOutputData*)(wl_output_get_user_data(window->sdlwindow->fullscreen_mode.driverdata)))->scale_factor; } for (i = 0; i < window->num_outputs; i++) { float factor = ((SDL_WaylandOutputData*)(wl_output_get_user_data(window->outputs[i])))->scale_factor; if (factor > new_factor) { new_factor = factor; } } if (new_factor != old_factor) { /* force the resize event to trigger, as the logical size didn't change */ window->resize.width = window->sdlwindow->w; window->resize.height = window->sdlwindow->h; window->resize.scale_factor = new_factor; window->resize.pending = SDL_TRUE; if (!(window->sdlwindow->flags & SDL_WINDOW_OPENGL)) { Wayland_HandlePendingResize(window->sdlwindow); /* OpenGL windows handle this in SwapWindow */ } } } static void handle_surface_enter(void *data, struct wl_surface *surface, struct wl_output *output) { SDL_WindowData *window = data; window->outputs = SDL_realloc(window->outputs, (window->num_outputs + 1) * sizeof *window->outputs); window->outputs[window->num_outputs++] = output; update_scale_factor(window); } static void handle_surface_leave(void *data, struct wl_surface *surface, struct wl_output *output) { SDL_WindowData *window = data; int i; for (i = 0; i < window->num_outputs; i++) { if (window->outputs[i] == output) { /* remove this one */ if (i == (window->num_outputs-1)) { window->outputs[i] = NULL; } else { SDL_memmove(&window->outputs[i], &window->outputs[i+1], sizeof (output) * ((window->num_outputs - i) - 1)); } window->num_outputs--; i--; } } if (window->num_outputs == 0) { SDL_free(window->outputs); window->outputs = NULL; } update_scale_factor(window); } static const struct wl_surface_listener surface_listener = { handle_surface_enter, handle_surface_leave }; SDL_bool Wayland_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; const Uint32 version = ((((Uint32) info->version.major) * 1000000) + (((Uint32) info->version.minor) * 10000) + (((Uint32) info->version.patch))); /* Before 2.0.6, it was possible to build an SDL with Wayland support (SDL_SysWMinfo will be large enough to hold Wayland info), but build your app against SDL headers that didn't have Wayland support (SDL_SysWMinfo could be smaller than Wayland needs. This would lead to an app properly using SDL_GetWindowWMInfo() but we'd accidentally overflow memory on the stack or heap. To protect against this, we've padded out the struct unconditionally in the headers and Wayland will just return an error for older apps using this function. Those apps will need to be recompiled against newer headers or not use Wayland, maybe by forcing SDL_VIDEODRIVER=x11. */ if (version < 2000006) { info->subsystem = SDL_SYSWM_UNKNOWN; SDL_SetError("Version must be 2.0.6 or newer"); return SDL_FALSE; } info->info.wl.display = data->waylandData->display; info->info.wl.surface = data->surface; info->info.wl.shell_surface = data->shell_surface.wl; info->subsystem = SDL_SYSWM_WAYLAND; return SDL_TRUE; } int Wayland_SetWindowHitTest(SDL_Window *window, SDL_bool enabled) { return 0; /* just succeed, the real work is done elsewhere. */ } static void SetFullscreen(_THIS, SDL_Window * window, struct wl_output *output) { const SDL_VideoData *viddata = (const SDL_VideoData *) _this->driverdata; SDL_WindowData *wind = window->driverdata; if (viddata->shell.xdg) { if (output) { xdg_toplevel_set_fullscreen(wind->shell_surface.xdg.roleobj.toplevel, output); } else { xdg_toplevel_unset_fullscreen(wind->shell_surface.xdg.roleobj.toplevel); } } else if (viddata->shell.zxdg) { if (output) { zxdg_toplevel_v6_set_fullscreen(wind->shell_surface.zxdg.roleobj.toplevel, output); } else { zxdg_toplevel_v6_unset_fullscreen(wind->shell_surface.zxdg.roleobj.toplevel); } } else { if (output) { wl_shell_surface_set_fullscreen(wind->shell_surface.wl, WL_SHELL_SURFACE_FULLSCREEN_METHOD_DEFAULT, 0, output); } else { wl_shell_surface_set_toplevel(wind->shell_surface.wl); } } WAYLAND_wl_display_flush( ((SDL_VideoData*)_this->driverdata)->display ); } void Wayland_ShowWindow(_THIS, SDL_Window *window) { struct wl_output *output = (struct wl_output *) window->fullscreen_mode.driverdata; SetFullscreen(_this, window, (window->flags & SDL_WINDOW_FULLSCREEN) ? output : NULL); } #ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH static void SDLCALL QtExtendedSurface_OnHintChanged(void *userdata, const char *name, const char *oldValue, const char *newValue) { struct qt_extended_surface *qt_extended_surface = userdata; if (name == NULL) { return; } if (strcmp(name, SDL_HINT_QTWAYLAND_CONTENT_ORIENTATION) == 0) { int32_t orientation = QT_EXTENDED_SURFACE_ORIENTATION_PRIMARYORIENTATION; if (newValue != NULL) { if (strcmp(newValue, "portrait") == 0) { orientation = QT_EXTENDED_SURFACE_ORIENTATION_PORTRAITORIENTATION; } else if (strcmp(newValue, "landscape") == 0) { orientation = QT_EXTENDED_SURFACE_ORIENTATION_LANDSCAPEORIENTATION; } else if (strcmp(newValue, "inverted-portrait") == 0) { orientation = QT_EXTENDED_SURFACE_ORIENTATION_INVERTEDPORTRAITORIENTATION; } else if (strcmp(newValue, "inverted-landscape") == 0) { orientation = QT_EXTENDED_SURFACE_ORIENTATION_INVERTEDLANDSCAPEORIENTATION; } } qt_extended_surface_set_content_orientation(qt_extended_surface, orientation); } else if (strcmp(name, SDL_HINT_QTWAYLAND_WINDOW_FLAGS) == 0) { uint32_t flags = 0; if (newValue != NULL) { char *tmp = strdup(newValue); char *saveptr = NULL; char *flag = strtok_r(tmp, " ", &saveptr); while (flag) { if (strcmp(flag, "OverridesSystemGestures") == 0) { flags |= QT_EXTENDED_SURFACE_WINDOWFLAG_OVERRIDESSYSTEMGESTURES; } else if (strcmp(flag, "StaysOnTop") == 0) { flags |= QT_EXTENDED_SURFACE_WINDOWFLAG_STAYSONTOP; } else if (strcmp(flag, "BypassWindowManager") == 0) { // See https://github.com/qtproject/qtwayland/commit/fb4267103d flags |= 4 /* QT_EXTENDED_SURFACE_WINDOWFLAG_BYPASSWINDOWMANAGER */; } flag = strtok_r(NULL, " ", &saveptr); } free(tmp); } qt_extended_surface_set_window_flags(qt_extended_surface, flags); } } static void QtExtendedSurface_Subscribe(struct qt_extended_surface *surface, const char *name) { SDL_AddHintCallback(name, QtExtendedSurface_OnHintChanged, surface); } static void QtExtendedSurface_Unsubscribe(struct qt_extended_surface *surface, const char *name) { SDL_DelHintCallback(name, QtExtendedSurface_OnHintChanged, surface); } #endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */ void Wayland_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * _display, SDL_bool fullscreen) { struct wl_output *output = ((SDL_WaylandOutputData*) _display->driverdata)->output; SetFullscreen(_this, window, fullscreen ? output : NULL); } void Wayland_RestoreWindow(_THIS, SDL_Window * window) { SDL_WindowData *wind = window->driverdata; const SDL_VideoData *viddata = (const SDL_VideoData *) _this->driverdata; if (viddata->shell.xdg) { } else if (viddata->shell.zxdg) { } else { wl_shell_surface_set_toplevel(wind->shell_surface.wl); } WAYLAND_wl_display_flush( ((SDL_VideoData*)_this->driverdata)->display ); } void Wayland_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered) { SDL_WindowData *wind = window->driverdata; const SDL_VideoData *viddata = (const SDL_VideoData *) _this->driverdata; if ((viddata->decoration_manager) && (wind->server_decoration)) { const enum zxdg_toplevel_decoration_v1_mode mode = bordered ? ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE : ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE; zxdg_toplevel_decoration_v1_set_mode(wind->server_decoration, mode); } else if ((viddata->kwin_server_decoration_manager) && (wind->kwin_server_decoration)) { const enum org_kde_kwin_server_decoration_manager_mode mode = bordered ? ORG_KDE_KWIN_SERVER_DECORATION_MANAGER_MODE_SERVER : ORG_KDE_KWIN_SERVER_DECORATION_MANAGER_MODE_NONE; org_kde_kwin_server_decoration_request_mode(wind->kwin_server_decoration, mode); } } void Wayland_MaximizeWindow(_THIS, SDL_Window * window) { SDL_WindowData *wind = window->driverdata; SDL_VideoData *viddata = (SDL_VideoData *) _this->driverdata; if (viddata->shell.xdg) { xdg_toplevel_set_maximized(wind->shell_surface.xdg.roleobj.toplevel); } else if (viddata->shell.zxdg) { zxdg_toplevel_v6_set_maximized(wind->shell_surface.zxdg.roleobj.toplevel); } else { wl_shell_surface_set_maximized(wind->shell_surface.wl, NULL); } WAYLAND_wl_display_flush( viddata->display ); } void Wayland_SetWindowGrab(_THIS, SDL_Window *window, SDL_bool grabbed) { SDL_VideoData *data = (SDL_VideoData *) _this->driverdata; if (grabbed) Wayland_input_confine_pointer(window, data->input); else Wayland_input_unconfine_pointer(data->input); } int Wayland_CreateWindow(_THIS, SDL_Window *window) { SDL_WindowData *data; SDL_VideoData *c; struct wl_region *region; data = SDL_calloc(1, sizeof *data); if (data == NULL) return SDL_OutOfMemory(); c = _this->driverdata; window->driverdata = data; if (!(window->flags & SDL_WINDOW_VULKAN)) { if (!(window->flags & SDL_WINDOW_OPENGL)) { SDL_GL_LoadLibrary(NULL); window->flags |= SDL_WINDOW_OPENGL; } } if (window->x == SDL_WINDOWPOS_UNDEFINED) { window->x = 0; } if (window->y == SDL_WINDOWPOS_UNDEFINED) { window->y = 0; } data->waylandData = c; data->sdlwindow = window; data->scale_factor = 1.0; if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) { int i; for (i=0; i < SDL_GetVideoDevice()->num_displays; i++) { float scale = ((SDL_WaylandOutputData*)SDL_GetVideoDevice()->displays[i].driverdata)->scale_factor; if (scale > data->scale_factor) { data->scale_factor = scale; } } } data->resize.pending = SDL_FALSE; data->resize.width = window->w; data->resize.height = window->h; data->resize.scale_factor = data->scale_factor; data->outputs = NULL; data->num_outputs = 0; data->surface = wl_compositor_create_surface(c->compositor); wl_surface_add_listener(data->surface, &surface_listener, data); if (c->shell.xdg) { data->shell_surface.xdg.surface = xdg_wm_base_get_xdg_surface(c->shell.xdg, data->surface); /* !!! FIXME: add popup role */ data->shell_surface.xdg.roleobj.toplevel = xdg_surface_get_toplevel(data->shell_surface.xdg.surface); xdg_toplevel_add_listener(data->shell_surface.xdg.roleobj.toplevel, &toplevel_listener_xdg, data); xdg_toplevel_set_app_id(data->shell_surface.xdg.roleobj.toplevel, c->classname); } else if (c->shell.zxdg) { data->shell_surface.zxdg.surface = zxdg_shell_v6_get_xdg_surface(c->shell.zxdg, data->surface); /* !!! FIXME: add popup role */ data->shell_surface.zxdg.roleobj.toplevel = zxdg_surface_v6_get_toplevel(data->shell_surface.zxdg.surface); zxdg_toplevel_v6_add_listener(data->shell_surface.zxdg.roleobj.toplevel, &toplevel_listener_zxdg, data); zxdg_toplevel_v6_set_app_id(data->shell_surface.zxdg.roleobj.toplevel, c->classname); } else { data->shell_surface.wl = wl_shell_get_shell_surface(c->shell.wl, data->surface); wl_shell_surface_set_class(data->shell_surface.wl, c->classname); } #ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH if (c->surface_extension) { data->extended_surface = qt_surface_extension_get_extended_surface( c->surface_extension, data->surface); QtExtendedSurface_Subscribe(data->extended_surface, SDL_HINT_QTWAYLAND_CONTENT_ORIENTATION); QtExtendedSurface_Subscribe(data->extended_surface, SDL_HINT_QTWAYLAND_WINDOW_FLAGS); } #endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */ if (window->flags & SDL_WINDOW_OPENGL) { data->egl_window = WAYLAND_wl_egl_window_create(data->surface, window->w * data->scale_factor, window->h * data->scale_factor); /* Create the GLES window surface */ data->egl_surface = SDL_EGL_CreateSurface(_this, (NativeWindowType) data->egl_window); if (data->egl_surface == EGL_NO_SURFACE) { return SDL_SetError("failed to create an EGL window surface"); } } if (c->shell.xdg) { if (data->shell_surface.xdg.surface) { xdg_surface_set_user_data(data->shell_surface.xdg.surface, data); xdg_surface_add_listener(data->shell_surface.xdg.surface, &shell_surface_listener_xdg, data); } } else if (c->shell.zxdg) { if (data->shell_surface.zxdg.surface) { zxdg_surface_v6_set_user_data(data->shell_surface.zxdg.surface, data); zxdg_surface_v6_add_listener(data->shell_surface.zxdg.surface, &shell_surface_listener_zxdg, data); } } else { if (data->shell_surface.wl) { wl_shell_surface_set_user_data(data->shell_surface.wl, data); wl_shell_surface_add_listener(data->shell_surface.wl, &shell_surface_listener_wl, data); } } #ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH if (data->extended_surface) { qt_extended_surface_set_user_data(data->extended_surface, data); qt_extended_surface_add_listener(data->extended_surface, &extended_surface_listener, data); } #endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */ if (c->decoration_manager && c->shell.xdg && data->shell_surface.xdg.surface) { data->server_decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(c->decoration_manager, data->shell_surface.xdg.roleobj.toplevel); if (data->server_decoration) { const SDL_bool bordered = (window->flags & SDL_WINDOW_BORDERLESS) == 0; const enum zxdg_toplevel_decoration_v1_mode mode = bordered ? ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE : ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE; zxdg_toplevel_decoration_v1_set_mode(data->server_decoration, mode); } } else if (c->kwin_server_decoration_manager) { data->kwin_server_decoration = org_kde_kwin_server_decoration_manager_create(c->kwin_server_decoration_manager, data->surface); if (data->kwin_server_decoration) { const SDL_bool bordered = (window->flags & SDL_WINDOW_BORDERLESS) == 0; const enum org_kde_kwin_server_decoration_manager_mode mode = bordered ? ORG_KDE_KWIN_SERVER_DECORATION_MANAGER_MODE_SERVER : ORG_KDE_KWIN_SERVER_DECORATION_MANAGER_MODE_NONE; org_kde_kwin_server_decoration_request_mode(data->kwin_server_decoration, mode); } } region = wl_compositor_create_region(c->compositor); wl_region_add(region, 0, 0, window->w, window->h); wl_surface_set_opaque_region(data->surface, region); wl_region_destroy(region); if (c->relative_mouse_mode) { Wayland_input_lock_pointer(c->input); } wl_surface_commit(data->surface); WAYLAND_wl_display_flush(c->display); /* we have to wait until the surface gets a "configure" event, or use of this surface will fail. This is a new rule for xdg_shell. */ if (c->shell.xdg) { if (data->shell_surface.xdg.surface) { while (!data->shell_surface.xdg.initial_configure_seen) { WAYLAND_wl_display_flush(c->display); WAYLAND_wl_display_dispatch(c->display); } } } else if (c->shell.zxdg) { if (data->shell_surface.zxdg.surface) { while (!data->shell_surface.zxdg.initial_configure_seen) { WAYLAND_wl_display_flush(c->display); WAYLAND_wl_display_dispatch(c->display); } } } return 0; } void Wayland_HandlePendingResize(SDL_Window *window) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; if (data->resize.pending) { struct wl_region *region; if (data->scale_factor != data->resize.scale_factor) { window->w = 0; window->h = 0; } SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESIZED, data->resize.width, data->resize.height); window->w = data->resize.width; window->h = data->resize.height; data->scale_factor = data->resize.scale_factor; wl_surface_set_buffer_scale(data->surface, data->scale_factor); if (data->egl_window) { WAYLAND_wl_egl_window_resize(data->egl_window, window->w * data->scale_factor, window->h * data->scale_factor, 0, 0); } if (data->resize.configure) { if (data->waylandData->shell.xdg) { xdg_surface_ack_configure(data->shell_surface.xdg.surface, data->resize.serial); } else if (data->waylandData->shell.zxdg) { zxdg_surface_v6_ack_configure(data->shell_surface.zxdg.surface, data->resize.serial); } data->resize.configure = SDL_FALSE; } region = wl_compositor_create_region(data->waylandData->compositor); wl_region_add(region, 0, 0, window->w, window->h); wl_surface_set_opaque_region(data->surface, region); wl_region_destroy(region); data->resize.pending = SDL_FALSE; } } void Wayland_SetWindowSize(_THIS, SDL_Window * window) { SDL_VideoData *data = _this->driverdata; SDL_WindowData *wind = window->driverdata; struct wl_region *region; wl_surface_set_buffer_scale(wind->surface, get_window_scale_factor(window)); if (wind->egl_window) { WAYLAND_wl_egl_window_resize(wind->egl_window, window->w * get_window_scale_factor(window), window->h * get_window_scale_factor(window), 0, 0); } region = wl_compositor_create_region(data->compositor); wl_region_add(region, 0, 0, window->w, window->h); wl_surface_set_opaque_region(wind->surface, region); wl_region_destroy(region); } void Wayland_SetWindowTitle(_THIS, SDL_Window * window) { SDL_WindowData *wind = window->driverdata; SDL_VideoData *viddata = (SDL_VideoData *) _this->driverdata; if (window->title != NULL) { if (viddata->shell.xdg) { xdg_toplevel_set_title(wind->shell_surface.xdg.roleobj.toplevel, window->title); } else if (viddata->shell.zxdg) { zxdg_toplevel_v6_set_title(wind->shell_surface.zxdg.roleobj.toplevel, window->title); } else { wl_shell_surface_set_title(wind->shell_surface.wl, window->title); } } WAYLAND_wl_display_flush( ((SDL_VideoData*)_this->driverdata)->display ); } void Wayland_DestroyWindow(_THIS, SDL_Window *window) { SDL_VideoData *data = _this->driverdata; SDL_WindowData *wind = window->driverdata; if (data) { if (wind->egl_surface) { SDL_EGL_DestroySurface(_this, wind->egl_surface); } if (wind->egl_window) { WAYLAND_wl_egl_window_destroy(wind->egl_window); } if (wind->server_decoration) { zxdg_toplevel_decoration_v1_destroy(wind->server_decoration); } if (wind->kwin_server_decoration) { org_kde_kwin_server_decoration_release(wind->kwin_server_decoration); } if (data->shell.xdg) { if (wind->shell_surface.xdg.roleobj.toplevel) { xdg_toplevel_destroy(wind->shell_surface.xdg.roleobj.toplevel); } if (wind->shell_surface.zxdg.surface) { xdg_surface_destroy(wind->shell_surface.xdg.surface); } } else if (data->shell.zxdg) { if (wind->shell_surface.zxdg.roleobj.toplevel) { zxdg_toplevel_v6_destroy(wind->shell_surface.zxdg.roleobj.toplevel); } if (wind->shell_surface.zxdg.surface) { zxdg_surface_v6_destroy(wind->shell_surface.zxdg.surface); } } else { if (wind->shell_surface.wl) { wl_shell_surface_destroy(wind->shell_surface.wl); } } #ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH if (wind->extended_surface) { QtExtendedSurface_Unsubscribe(wind->extended_surface, SDL_HINT_QTWAYLAND_CONTENT_ORIENTATION); QtExtendedSurface_Unsubscribe(wind->extended_surface, SDL_HINT_QTWAYLAND_WINDOW_FLAGS); qt_extended_surface_destroy(wind->extended_surface); } #endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */ wl_surface_destroy(wind->surface); SDL_free(wind); WAYLAND_wl_display_flush(data->display); } window->driverdata = NULL; } #endif /* SDL_VIDEO_DRIVER_WAYLAND && SDL_VIDEO_OPENGL_EGL */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylandwindow.c
C
apache-2.0
33,730
/* 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_waylandwindow_h_ #define SDL_waylandwindow_h_ #include "../SDL_sysvideo.h" #include "SDL_syswm.h" #include "../../events/SDL_touch_c.h" #include "SDL_waylandvideo.h" struct SDL_WaylandInput; typedef struct { struct zxdg_surface_v6 *surface; union { struct zxdg_toplevel_v6 *toplevel; struct zxdg_popup_v6 *popup; } roleobj; SDL_bool initial_configure_seen; } SDL_zxdg_shell_surface; typedef struct { struct xdg_surface *surface; union { struct xdg_toplevel *toplevel; struct xdg_popup *popup; } roleobj; SDL_bool initial_configure_seen; } SDL_xdg_shell_surface; typedef struct { SDL_Window *sdlwindow; SDL_VideoData *waylandData; struct wl_surface *surface; union { SDL_xdg_shell_surface xdg; SDL_zxdg_shell_surface zxdg; struct wl_shell_surface *wl; } shell_surface; struct wl_egl_window *egl_window; struct SDL_WaylandInput *keyboard_device; EGLSurface egl_surface; struct zwp_locked_pointer_v1 *locked_pointer; struct zxdg_toplevel_decoration_v1 *server_decoration; struct org_kde_kwin_server_decoration *kwin_server_decoration; #ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH struct qt_extended_surface *extended_surface; #endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */ struct { SDL_bool pending, configure; uint32_t serial; int width, height; float scale_factor; } resize; struct wl_output **outputs; int num_outputs; float scale_factor; } SDL_WindowData; extern void Wayland_ShowWindow(_THIS, SDL_Window *window); extern void Wayland_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * _display, SDL_bool fullscreen); extern void Wayland_MaximizeWindow(_THIS, SDL_Window * window); extern void Wayland_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed); extern void Wayland_RestoreWindow(_THIS, SDL_Window * window); extern void Wayland_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered); extern int Wayland_CreateWindow(_THIS, SDL_Window *window); extern void Wayland_SetWindowSize(_THIS, SDL_Window * window); extern void Wayland_SetWindowTitle(_THIS, SDL_Window * window); extern void Wayland_DestroyWindow(_THIS, SDL_Window *window); extern SDL_bool Wayland_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info); extern int Wayland_SetWindowHitTest(SDL_Window *window, SDL_bool enabled); extern void Wayland_HandlePendingResize(SDL_Window *window); #endif /* SDL_waylandwindow_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/wayland/SDL_waylandwindow.h
C
apache-2.0
3,638
/* 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_msctf_h_ #define SDL_msctf_h_ #include <unknwn.h> #define TF_INVALID_COOKIE (0xffffffff) #define TF_IPSINK_FLAG_ACTIVE 0x0001 #define TF_TMAE_UIELEMENTENABLEDONLY 0x00000004 typedef struct ITfThreadMgr ITfThreadMgr; typedef struct ITfDocumentMgr ITfDocumentMgr; typedef struct ITfClientId ITfClientId; typedef struct IEnumTfDocumentMgrs IEnumTfDocumentMgrs; typedef struct IEnumTfFunctionProviders IEnumTfFunctionProviders; typedef struct ITfFunctionProvider ITfFunctionProvider; typedef struct ITfCompartmentMgr ITfCompartmentMgr; typedef struct ITfContext ITfContext; typedef struct IEnumTfContexts IEnumTfContexts; typedef struct ITfUIElementSink ITfUIElementSink; typedef struct ITfUIElement ITfUIElement; typedef struct ITfUIElementMgr ITfUIElementMgr; typedef struct IEnumTfUIElements IEnumTfUIElements; typedef struct ITfThreadMgrEx ITfThreadMgrEx; typedef struct ITfCandidateListUIElement ITfCandidateListUIElement; typedef struct ITfReadingInformationUIElement ITfReadingInformationUIElement; typedef struct ITfInputProcessorProfileActivationSink ITfInputProcessorProfileActivationSink; typedef struct ITfSource ITfSource; typedef DWORD TfClientId; typedef DWORD TfEditCookie; typedef struct ITfThreadMgrVtbl { HRESULT (STDMETHODCALLTYPE *QueryInterface)(ITfThreadMgr *, REFIID, void **); ULONG (STDMETHODCALLTYPE *AddRef)(ITfThreadMgr *); ULONG (STDMETHODCALLTYPE *Release)(ITfThreadMgr *); HRESULT (STDMETHODCALLTYPE *Activate)(ITfThreadMgr *, TfClientId *); HRESULT (STDMETHODCALLTYPE *Deactivate)(ITfThreadMgr *); HRESULT (STDMETHODCALLTYPE *CreateDocumentMgr)(ITfThreadMgr *); HRESULT (STDMETHODCALLTYPE *EnumDocumentMgrs)(ITfThreadMgr *, IEnumTfDocumentMgrs **); HRESULT (STDMETHODCALLTYPE *GetFocus)(ITfThreadMgr *, ITfDocumentMgr **); HRESULT (STDMETHODCALLTYPE *SetFocus)(ITfThreadMgr *, ITfDocumentMgr *); HRESULT (STDMETHODCALLTYPE *AssociateFocus)(ITfThreadMgr *, HWND, ITfDocumentMgr *, ITfDocumentMgr **); HRESULT (STDMETHODCALLTYPE *IsThreadFocus)(ITfThreadMgr *, BOOL *); HRESULT (STDMETHODCALLTYPE *GetFunctionProvider)(ITfThreadMgr *, REFCLSID, ITfFunctionProvider **); HRESULT (STDMETHODCALLTYPE *EnumFunctionProviders)(ITfThreadMgr *, IEnumTfFunctionProviders **); HRESULT (STDMETHODCALLTYPE *GetGlobalCompartment)(ITfThreadMgr *, ITfCompartmentMgr **); } ITfThreadMgrVtbl; struct ITfThreadMgr { const struct ITfThreadMgrVtbl *lpVtbl; }; typedef struct ITfThreadMgrExVtbl { HRESULT (STDMETHODCALLTYPE *QueryInterface)(ITfThreadMgrEx *, REFIID, void **); ULONG (STDMETHODCALLTYPE *AddRef)(ITfThreadMgrEx *); ULONG (STDMETHODCALLTYPE *Release)(ITfThreadMgrEx *); HRESULT (STDMETHODCALLTYPE *Activate)(ITfThreadMgrEx *, TfClientId *); HRESULT (STDMETHODCALLTYPE *Deactivate)(ITfThreadMgrEx *); HRESULT (STDMETHODCALLTYPE *CreateDocumentMgr)(ITfThreadMgrEx *, ITfDocumentMgr **); HRESULT (STDMETHODCALLTYPE *EnumDocumentMgrs)(ITfThreadMgrEx *, IEnumTfDocumentMgrs **); HRESULT (STDMETHODCALLTYPE *GetFocus)(ITfThreadMgrEx *, ITfDocumentMgr **); HRESULT (STDMETHODCALLTYPE *SetFocus)(ITfThreadMgrEx *, ITfDocumentMgr *); HRESULT (STDMETHODCALLTYPE *AssociateFocus)(ITfThreadMgrEx *, ITfDocumentMgr *, ITfDocumentMgr **); HRESULT (STDMETHODCALLTYPE *IsThreadFocus)(ITfThreadMgrEx *, BOOL *); HRESULT (STDMETHODCALLTYPE *GetFunctionProvider)(ITfThreadMgrEx *, REFCLSID, ITfFunctionProvider **); HRESULT (STDMETHODCALLTYPE *EnumFunctionProviders)(ITfThreadMgrEx *, IEnumTfFunctionProviders **); HRESULT (STDMETHODCALLTYPE *GetGlobalCompartment)(ITfThreadMgrEx *, ITfCompartmentMgr **); HRESULT (STDMETHODCALLTYPE *ActivateEx)(ITfThreadMgrEx *, TfClientId *, DWORD); HRESULT (STDMETHODCALLTYPE *GetActiveFlags)(ITfThreadMgrEx *, DWORD *); } ITfThreadMgrExVtbl; struct ITfThreadMgrEx { const struct ITfThreadMgrExVtbl *lpVtbl; }; typedef struct ITfDocumentMgrVtbl { HRESULT (STDMETHODCALLTYPE *QueryInterface)(ITfDocumentMgr *, REFIID, void **); ULONG (STDMETHODCALLTYPE *AddRef)(ITfDocumentMgr *); ULONG (STDMETHODCALLTYPE *Release)(ITfDocumentMgr *); HRESULT (STDMETHODCALLTYPE *CreateContext)(ITfDocumentMgr *, TfClientId, DWORD, IUnknown *, ITfContext **, TfEditCookie *); HRESULT (STDMETHODCALLTYPE *Push)(ITfDocumentMgr *, ITfContext *); HRESULT (STDMETHODCALLTYPE *Pop)(ITfDocumentMgr *); HRESULT (STDMETHODCALLTYPE *GetTop)(ITfDocumentMgr *, ITfContext **); HRESULT (STDMETHODCALLTYPE *GetBase)(ITfDocumentMgr *, ITfContext **); HRESULT (STDMETHODCALLTYPE *EnumContexts)(ITfDocumentMgr *, IEnumTfContexts **); } ITfDocumentMgrVtbl; struct ITfDocumentMgr { const struct ITfDocumentMgrVtbl *lpVtbl; }; typedef struct ITfUIElementSinkVtbl { HRESULT (STDMETHODCALLTYPE *QueryInterface)(ITfUIElementSink *, REFIID, void **); ULONG (STDMETHODCALLTYPE *AddRef)(ITfUIElementSink *); ULONG (STDMETHODCALLTYPE *Release)(ITfUIElementSink *); HRESULT (STDMETHODCALLTYPE *BeginUIElement)(ITfUIElementSink *, DWORD, BOOL *); HRESULT (STDMETHODCALLTYPE *UpdateUIElement)(ITfUIElementSink *, DWORD); HRESULT (STDMETHODCALLTYPE *EndUIElement)(ITfUIElementSink *, DWORD); } ITfUIElementSinkVtbl; struct ITfUIElementSink { const struct ITfUIElementSinkVtbl *lpVtbl; }; typedef struct ITfUIElementMgrVtbl { HRESULT (STDMETHODCALLTYPE *QueryInterface)(ITfUIElementMgr *, REFIID, void **); ULONG (STDMETHODCALLTYPE *AddRef)(ITfUIElementMgr *); ULONG (STDMETHODCALLTYPE *Release)(ITfUIElementMgr *); HRESULT (STDMETHODCALLTYPE *BeginUIElement)(ITfUIElementMgr *, ITfUIElement *, BOOL *, DWORD *); HRESULT (STDMETHODCALLTYPE *UpdateUIElement)(ITfUIElementMgr *, DWORD); HRESULT (STDMETHODCALLTYPE *EndUIElement)(ITfUIElementMgr *, DWORD); HRESULT (STDMETHODCALLTYPE *GetUIElement)(ITfUIElementMgr *, DWORD, ITfUIElement **); HRESULT (STDMETHODCALLTYPE *EnumUIElements)(ITfUIElementMgr *, IEnumTfUIElements **); } ITfUIElementMgrVtbl; struct ITfUIElementMgr { const struct ITfUIElementMgrVtbl *lpVtbl; }; typedef struct ITfCandidateListUIElementVtbl { HRESULT (STDMETHODCALLTYPE *QueryInterface)(ITfCandidateListUIElement *, REFIID, void **); ULONG (STDMETHODCALLTYPE *AddRef)(ITfCandidateListUIElement *); ULONG (STDMETHODCALLTYPE *Release)(ITfCandidateListUIElement *); HRESULT (STDMETHODCALLTYPE *GetDescription)(ITfCandidateListUIElement *, BSTR *); HRESULT (STDMETHODCALLTYPE *GetGUID)(ITfCandidateListUIElement *, GUID *); HRESULT (STDMETHODCALLTYPE *Show)(ITfCandidateListUIElement *, BOOL); HRESULT (STDMETHODCALLTYPE *IsShown)(ITfCandidateListUIElement *, BOOL *); HRESULT (STDMETHODCALLTYPE *GetUpdatedFlags)(ITfCandidateListUIElement *, DWORD *); HRESULT (STDMETHODCALLTYPE *GetDocumentMgr)(ITfCandidateListUIElement *, ITfDocumentMgr **); HRESULT (STDMETHODCALLTYPE *GetCount)(ITfCandidateListUIElement *, UINT *); HRESULT (STDMETHODCALLTYPE *GetSelection)(ITfCandidateListUIElement *, UINT *); HRESULT (STDMETHODCALLTYPE *GetString)(ITfCandidateListUIElement *, UINT, BSTR *); HRESULT (STDMETHODCALLTYPE *GetPageIndex)(ITfCandidateListUIElement *, UINT *, UINT, UINT *); HRESULT (STDMETHODCALLTYPE *SetPageIndex)(ITfCandidateListUIElement *, UINT *, UINT); HRESULT (STDMETHODCALLTYPE *GetCurrentPage)(ITfCandidateListUIElement *, UINT *); } ITfCandidateListUIElementVtbl; struct ITfCandidateListUIElement { const struct ITfCandidateListUIElementVtbl *lpVtbl; }; typedef struct ITfReadingInformationUIElementVtbl { HRESULT (STDMETHODCALLTYPE *QueryInterface)(ITfReadingInformationUIElement *, REFIID, void **); ULONG (STDMETHODCALLTYPE *AddRef)(ITfReadingInformationUIElement *); ULONG (STDMETHODCALLTYPE *Release)(ITfReadingInformationUIElement *); HRESULT (STDMETHODCALLTYPE *GetDescription)(ITfReadingInformationUIElement *, BSTR *); HRESULT (STDMETHODCALLTYPE *GetGUID)(ITfReadingInformationUIElement *, GUID *); HRESULT (STDMETHODCALLTYPE *Show)(ITfReadingInformationUIElement *, BOOL); HRESULT (STDMETHODCALLTYPE *IsShown)(ITfReadingInformationUIElement *, BOOL *); HRESULT (STDMETHODCALLTYPE *GetUpdatedFlags)(ITfReadingInformationUIElement *, DWORD *); HRESULT (STDMETHODCALLTYPE *GetContext)(ITfReadingInformationUIElement *, ITfContext **); HRESULT (STDMETHODCALLTYPE *GetString)(ITfReadingInformationUIElement *, BSTR *); HRESULT (STDMETHODCALLTYPE *GetMaxReadingStringLength)(ITfReadingInformationUIElement *, UINT *); HRESULT (STDMETHODCALLTYPE *GetErrorIndex)(ITfReadingInformationUIElement *, UINT *); HRESULT (STDMETHODCALLTYPE *IsVerticalOrderPreferred)(ITfReadingInformationUIElement *, BOOL *); } ITfReadingInformationUIElementVtbl; struct ITfReadingInformationUIElement { const struct ITfReadingInformationUIElementVtbl *lpVtbl; }; typedef struct ITfUIElementVtbl { HRESULT (STDMETHODCALLTYPE *QueryInterface)(ITfUIElement *, REFIID, void **); ULONG (STDMETHODCALLTYPE *AddRef)(ITfUIElement *); ULONG (STDMETHODCALLTYPE *Release)(ITfUIElement *); HRESULT (STDMETHODCALLTYPE *GetDescription)(ITfUIElement *, BSTR *); HRESULT (STDMETHODCALLTYPE *GetGUID)(ITfUIElement *, GUID *); HRESULT (STDMETHODCALLTYPE *Show)(ITfUIElement *, BOOL); HRESULT (STDMETHODCALLTYPE *IsShown)(ITfUIElement *, BOOL *); } ITfUIElementVtbl; struct ITfUIElement { const struct ITfUIElementVtbl *lpVtbl; }; typedef struct ITfInputProcessorProfileActivationSinkVtbl { HRESULT (STDMETHODCALLTYPE *QueryInterface)(ITfInputProcessorProfileActivationSink *, REFIID, void **); ULONG (STDMETHODCALLTYPE *AddRef)(ITfInputProcessorProfileActivationSink *); ULONG (STDMETHODCALLTYPE *Release)(ITfInputProcessorProfileActivationSink *); HRESULT (STDMETHODCALLTYPE *OnActivated)(ITfInputProcessorProfileActivationSink *, DWORD, LANGID, REFCLSID, REFGUID, REFGUID, HKL, DWORD); } ITfInputProcessorProfileActivationSinkVtbl; struct ITfInputProcessorProfileActivationSink { const struct ITfInputProcessorProfileActivationSinkVtbl *lpVtbl; }; typedef struct ITfSourceVtbl { HRESULT (STDMETHODCALLTYPE *QueryInterface)(ITfSource *, REFIID, void **); ULONG (STDMETHODCALLTYPE *AddRef)(ITfSource *); ULONG (STDMETHODCALLTYPE *Release)(ITfSource *); HRESULT (STDMETHODCALLTYPE *AdviseSink)(ITfSource *, REFIID, IUnknown *, DWORD *); HRESULT (STDMETHODCALLTYPE *UnadviseSink)(ITfSource *, DWORD); } ITfSourceVtbl; struct ITfSource { const struct ITfSourceVtbl *lpVtbl; }; #endif /* SDL_msctf_h_ */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_msctf.h
C
apache-2.0
11,531
/* 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 VK_0 #define VK_0 '0' #define VK_1 '1' #define VK_2 '2' #define VK_3 '3' #define VK_4 '4' #define VK_5 '5' #define VK_6 '6' #define VK_7 '7' #define VK_8 '8' #define VK_9 '9' #define VK_A 'A' #define VK_B 'B' #define VK_C 'C' #define VK_D 'D' #define VK_E 'E' #define VK_F 'F' #define VK_G 'G' #define VK_H 'H' #define VK_I 'I' #define VK_J 'J' #define VK_K 'K' #define VK_L 'L' #define VK_M 'M' #define VK_N 'N' #define VK_O 'O' #define VK_P 'P' #define VK_Q 'Q' #define VK_R 'R' #define VK_S 'S' #define VK_T 'T' #define VK_U 'U' #define VK_V 'V' #define VK_W 'W' #define VK_X 'X' #define VK_Y 'Y' #define VK_Z 'Z' #endif /* VK_0 */ /* These keys haven't been defined, but were experimentally determined */ #define VK_SEMICOLON 0xBA #define VK_EQUALS 0xBB #define VK_COMMA 0xBC #define VK_MINUS 0xBD #define VK_PERIOD 0xBE #define VK_SLASH 0xBF #define VK_GRAVE 0xC0 #define VK_LBRACKET 0xDB #define VK_BACKSLASH 0xDC #define VK_RBRACKET 0xDD #define VK_APOSTROPHE 0xDE #define VK_BACKTICK 0xDF #define VK_OEM_102 0xE2 /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_vkeys.h
C
apache-2.0
2,179
/* 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_VIDEO_DRIVER_WINDOWS #include "SDL_windowsvideo.h" #include "SDL_windowswindow.h" #include "../../events/SDL_clipboardevents_c.h" #ifdef UNICODE #define TEXT_FORMAT CF_UNICODETEXT #else #define TEXT_FORMAT CF_TEXT #endif /* Get any application owned window handle for clipboard association */ static HWND GetWindowHandle(_THIS) { SDL_Window *window; window = _this->windows; if (window) { return ((SDL_WindowData *) window->driverdata)->hwnd; } return NULL; } int WIN_SetClipboardText(_THIS, const char *text) { SDL_VideoData *data = (SDL_VideoData *) _this->driverdata; int result = 0; if (OpenClipboard(GetWindowHandle(_this))) { HANDLE hMem; LPTSTR tstr; SIZE_T i, size; /* Convert the text from UTF-8 to Windows Unicode */ tstr = WIN_UTF8ToString(text); if (!tstr) { return -1; } /* Find out the size of the data */ for (size = 0, i = 0; tstr[i]; ++i, ++size) { if (tstr[i] == '\n' && (i == 0 || tstr[i-1] != '\r')) { /* We're going to insert a carriage return */ ++size; } } size = (size+1)*sizeof(*tstr); /* Save the data to the clipboard */ hMem = GlobalAlloc(GMEM_MOVEABLE, size); if (hMem) { LPTSTR dst = (LPTSTR)GlobalLock(hMem); if (dst) { /* Copy the text over, adding carriage returns as necessary */ for (i = 0; tstr[i]; ++i) { if (tstr[i] == '\n' && (i == 0 || tstr[i-1] != '\r')) { *dst++ = '\r'; } *dst++ = tstr[i]; } *dst = 0; GlobalUnlock(hMem); } EmptyClipboard(); if (!SetClipboardData(TEXT_FORMAT, hMem)) { result = WIN_SetError("Couldn't set clipboard data"); } data->clipboard_count = GetClipboardSequenceNumber(); } SDL_free(tstr); CloseClipboard(); } else { result = WIN_SetError("Couldn't open clipboard"); } return result; } char * WIN_GetClipboardText(_THIS) { char *text; text = NULL; if (IsClipboardFormatAvailable(TEXT_FORMAT) && OpenClipboard(GetWindowHandle(_this))) { HANDLE hMem; LPTSTR tstr; hMem = GetClipboardData(TEXT_FORMAT); if (hMem) { tstr = (LPTSTR)GlobalLock(hMem); text = WIN_StringToUTF8(tstr); GlobalUnlock(hMem); } else { WIN_SetError("Couldn't get clipboard data"); } CloseClipboard(); } if (!text) { text = SDL_strdup(""); } return text; } SDL_bool WIN_HasClipboardText(_THIS) { SDL_bool result = SDL_FALSE; char *text = WIN_GetClipboardText(_this); if (text) { result = text[0] != '\0' ? SDL_TRUE : SDL_FALSE; SDL_free(text); } return result; } void WIN_CheckClipboardUpdate(struct SDL_VideoData * data) { const DWORD count = GetClipboardSequenceNumber(); if (count != data->clipboard_count) { if (data->clipboard_count) { SDL_SendClipboardUpdate(); } data->clipboard_count = count; } } #endif /* SDL_VIDEO_DRIVER_WINDOWS */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsclipboard.c
C
apache-2.0
4,375
/* 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_windowsclipboard_h_ #define SDL_windowsclipboard_h_ /* Forward declaration */ struct SDL_VideoData; extern int WIN_SetClipboardText(_THIS, const char *text); extern char *WIN_GetClipboardText(_THIS); extern SDL_bool WIN_HasClipboardText(_THIS); extern void WIN_CheckClipboardUpdate(struct SDL_VideoData * data); #endif /* SDL_windowsclipboard_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsclipboard.h
C
apache-2.0
1,372
/* 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_VIDEO_DRIVER_WINDOWS #include "SDL_windowsvideo.h" #include "SDL_windowsshape.h" #include "SDL_system.h" #include "SDL_syswm.h" #include "SDL_timer.h" #include "SDL_vkeys.h" #include "SDL_hints.h" #include "../../events/SDL_events_c.h" #include "../../events/SDL_touch_c.h" #include "../../events/scancodes_windows.h" #include "SDL_assert.h" #include "SDL_hints.h" /* Dropfile support */ #include <shellapi.h> /* For GET_X_LPARAM, GET_Y_LPARAM. */ #include <windowsx.h> /* #define WMMSG_DEBUG */ #ifdef WMMSG_DEBUG #include <stdio.h> #include "wmmsg.h" #endif /* Masks for processing the windows KEYDOWN and KEYUP messages */ #define REPEATED_KEYMASK (1<<30) #define EXTENDED_KEYMASK (1<<24) #define VK_ENTER 10 /* Keypad Enter ... no VKEY defined? */ #ifndef VK_OEM_NEC_EQUAL #define VK_OEM_NEC_EQUAL 0x92 #endif /* Make sure XBUTTON stuff is defined that isn't in older Platform SDKs... */ #ifndef WM_XBUTTONDOWN #define WM_XBUTTONDOWN 0x020B #endif #ifndef WM_XBUTTONUP #define WM_XBUTTONUP 0x020C #endif #ifndef GET_XBUTTON_WPARAM #define GET_XBUTTON_WPARAM(w) (HIWORD(w)) #endif #ifndef WM_INPUT #define WM_INPUT 0x00ff #endif #ifndef WM_TOUCH #define WM_TOUCH 0x0240 #endif #ifndef WM_MOUSEHWHEEL #define WM_MOUSEHWHEEL 0x020E #endif #ifndef WM_POINTERUPDATE #define WM_POINTERUPDATE 0x0245 #endif #ifndef WM_UNICHAR #define WM_UNICHAR 0x0109 #endif static SDL_Scancode VKeytoScancode(WPARAM vkey) { switch (vkey) { /* Windows generates this virtual keycode for Keypad 5 when NumLock is off. case VK_CLEAR: return SDL_SCANCODE_CLEAR; */ case VK_LEFT: return SDL_SCANCODE_LEFT; case VK_UP: return SDL_SCANCODE_UP; case VK_RIGHT: return SDL_SCANCODE_RIGHT; case VK_DOWN: return SDL_SCANCODE_DOWN; case VK_MODECHANGE: return SDL_SCANCODE_MODE; case VK_SELECT: return SDL_SCANCODE_SELECT; case VK_EXECUTE: return SDL_SCANCODE_EXECUTE; case VK_HELP: return SDL_SCANCODE_HELP; case VK_PAUSE: return SDL_SCANCODE_PAUSE; case VK_NUMLOCK: return SDL_SCANCODE_NUMLOCKCLEAR; case VK_F13: return SDL_SCANCODE_F13; case VK_F14: return SDL_SCANCODE_F14; case VK_F15: return SDL_SCANCODE_F15; case VK_F16: return SDL_SCANCODE_F16; case VK_F17: return SDL_SCANCODE_F17; case VK_F18: return SDL_SCANCODE_F18; case VK_F19: return SDL_SCANCODE_F19; case VK_F20: return SDL_SCANCODE_F20; case VK_F21: return SDL_SCANCODE_F21; case VK_F22: return SDL_SCANCODE_F22; case VK_F23: return SDL_SCANCODE_F23; case VK_F24: return SDL_SCANCODE_F24; case VK_OEM_NEC_EQUAL: return SDL_SCANCODE_KP_EQUALS; case VK_BROWSER_BACK: return SDL_SCANCODE_AC_BACK; case VK_BROWSER_FORWARD: return SDL_SCANCODE_AC_FORWARD; case VK_BROWSER_REFRESH: return SDL_SCANCODE_AC_REFRESH; case VK_BROWSER_STOP: return SDL_SCANCODE_AC_STOP; case VK_BROWSER_SEARCH: return SDL_SCANCODE_AC_SEARCH; case VK_BROWSER_FAVORITES: return SDL_SCANCODE_AC_BOOKMARKS; case VK_BROWSER_HOME: return SDL_SCANCODE_AC_HOME; case VK_VOLUME_MUTE: return SDL_SCANCODE_AUDIOMUTE; case VK_VOLUME_DOWN: return SDL_SCANCODE_VOLUMEDOWN; case VK_VOLUME_UP: return SDL_SCANCODE_VOLUMEUP; case VK_MEDIA_NEXT_TRACK: return SDL_SCANCODE_AUDIONEXT; case VK_MEDIA_PREV_TRACK: return SDL_SCANCODE_AUDIOPREV; case VK_MEDIA_STOP: return SDL_SCANCODE_AUDIOSTOP; case VK_MEDIA_PLAY_PAUSE: return SDL_SCANCODE_AUDIOPLAY; case VK_LAUNCH_MAIL: return SDL_SCANCODE_MAIL; case VK_LAUNCH_MEDIA_SELECT: return SDL_SCANCODE_MEDIASELECT; case VK_OEM_102: return SDL_SCANCODE_NONUSBACKSLASH; case VK_ATTN: return SDL_SCANCODE_SYSREQ; case VK_CRSEL: return SDL_SCANCODE_CRSEL; case VK_EXSEL: return SDL_SCANCODE_EXSEL; case VK_OEM_CLEAR: return SDL_SCANCODE_CLEAR; case VK_LAUNCH_APP1: return SDL_SCANCODE_APP1; case VK_LAUNCH_APP2: return SDL_SCANCODE_APP2; default: return SDL_SCANCODE_UNKNOWN; } } static SDL_Scancode WindowsScanCodeToSDLScanCode(LPARAM lParam, WPARAM wParam) { SDL_Scancode code; int nScanCode = (lParam >> 16) & 0xFF; SDL_bool bIsExtended = (lParam & (1 << 24)) != 0; code = VKeytoScancode(wParam); if (code == SDL_SCANCODE_UNKNOWN && nScanCode <= 127) { code = windows_scancode_table[nScanCode]; if (bIsExtended) { switch (code) { case SDL_SCANCODE_RETURN: code = SDL_SCANCODE_KP_ENTER; break; case SDL_SCANCODE_LALT: code = SDL_SCANCODE_RALT; break; case SDL_SCANCODE_LCTRL: code = SDL_SCANCODE_RCTRL; break; case SDL_SCANCODE_SLASH: code = SDL_SCANCODE_KP_DIVIDE; break; case SDL_SCANCODE_CAPSLOCK: code = SDL_SCANCODE_KP_PLUS; break; default: break; } } else { switch (code) { case SDL_SCANCODE_HOME: code = SDL_SCANCODE_KP_7; break; case SDL_SCANCODE_UP: code = SDL_SCANCODE_KP_8; break; case SDL_SCANCODE_PAGEUP: code = SDL_SCANCODE_KP_9; break; case SDL_SCANCODE_LEFT: code = SDL_SCANCODE_KP_4; break; case SDL_SCANCODE_RIGHT: code = SDL_SCANCODE_KP_6; break; case SDL_SCANCODE_END: code = SDL_SCANCODE_KP_1; break; case SDL_SCANCODE_DOWN: code = SDL_SCANCODE_KP_2; break; case SDL_SCANCODE_PAGEDOWN: code = SDL_SCANCODE_KP_3; break; case SDL_SCANCODE_INSERT: code = SDL_SCANCODE_KP_0; break; case SDL_SCANCODE_DELETE: code = SDL_SCANCODE_KP_PERIOD; break; case SDL_SCANCODE_PRINTSCREEN: code = SDL_SCANCODE_KP_MULTIPLY; break; default: break; } } } return code; } static SDL_bool WIN_ShouldIgnoreFocusClick() { return !SDL_GetHintBoolean(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, SDL_FALSE); } static void WIN_CheckWParamMouseButton(SDL_bool bwParamMousePressed, SDL_bool bSDLMousePressed, SDL_WindowData *data, Uint8 button, SDL_MouseID mouseID) { if (data->focus_click_pending & SDL_BUTTON(button)) { /* Ignore the button click for activation */ if (!bwParamMousePressed) { data->focus_click_pending &= ~SDL_BUTTON(button); WIN_UpdateClipCursor(data->window); } if (WIN_ShouldIgnoreFocusClick()) { return; } } if (bwParamMousePressed && !bSDLMousePressed) { SDL_SendMouseButton(data->window, mouseID, SDL_PRESSED, button); } else if (!bwParamMousePressed && bSDLMousePressed) { SDL_SendMouseButton(data->window, mouseID, SDL_RELEASED, button); } } /* * Some windows systems fail to send a WM_LBUTTONDOWN sometimes, but each mouse move contains the current button state also * so this function reconciles our view of the world with the current buttons reported by windows */ static void WIN_CheckWParamMouseButtons(WPARAM wParam, SDL_WindowData *data, SDL_MouseID mouseID) { if (wParam != data->mouse_button_flags) { Uint32 mouseFlags = SDL_GetMouseState(NULL, NULL); WIN_CheckWParamMouseButton((wParam & MK_LBUTTON), (mouseFlags & SDL_BUTTON_LMASK), data, SDL_BUTTON_LEFT, mouseID); WIN_CheckWParamMouseButton((wParam & MK_MBUTTON), (mouseFlags & SDL_BUTTON_MMASK), data, SDL_BUTTON_MIDDLE, mouseID); WIN_CheckWParamMouseButton((wParam & MK_RBUTTON), (mouseFlags & SDL_BUTTON_RMASK), data, SDL_BUTTON_RIGHT, mouseID); WIN_CheckWParamMouseButton((wParam & MK_XBUTTON1), (mouseFlags & SDL_BUTTON_X1MASK), data, SDL_BUTTON_X1, mouseID); WIN_CheckWParamMouseButton((wParam & MK_XBUTTON2), (mouseFlags & SDL_BUTTON_X2MASK), data, SDL_BUTTON_X2, mouseID); data->mouse_button_flags = wParam; } } static void WIN_CheckRawMouseButtons(ULONG rawButtons, SDL_WindowData *data) { if (rawButtons != data->mouse_button_flags) { Uint32 mouseFlags = SDL_GetMouseState(NULL, NULL); if ((rawButtons & RI_MOUSE_BUTTON_1_DOWN)) WIN_CheckWParamMouseButton((rawButtons & RI_MOUSE_BUTTON_1_DOWN), (mouseFlags & SDL_BUTTON_LMASK), data, SDL_BUTTON_LEFT, 0); if ((rawButtons & RI_MOUSE_BUTTON_1_UP)) WIN_CheckWParamMouseButton(!(rawButtons & RI_MOUSE_BUTTON_1_UP), (mouseFlags & SDL_BUTTON_LMASK), data, SDL_BUTTON_LEFT, 0); if ((rawButtons & RI_MOUSE_BUTTON_2_DOWN)) WIN_CheckWParamMouseButton((rawButtons & RI_MOUSE_BUTTON_2_DOWN), (mouseFlags & SDL_BUTTON_RMASK), data, SDL_BUTTON_RIGHT, 0); if ((rawButtons & RI_MOUSE_BUTTON_2_UP)) WIN_CheckWParamMouseButton(!(rawButtons & RI_MOUSE_BUTTON_2_UP), (mouseFlags & SDL_BUTTON_RMASK), data, SDL_BUTTON_RIGHT, 0); if ((rawButtons & RI_MOUSE_BUTTON_3_DOWN)) WIN_CheckWParamMouseButton((rawButtons & RI_MOUSE_BUTTON_3_DOWN), (mouseFlags & SDL_BUTTON_MMASK), data, SDL_BUTTON_MIDDLE, 0); if ((rawButtons & RI_MOUSE_BUTTON_3_UP)) WIN_CheckWParamMouseButton(!(rawButtons & RI_MOUSE_BUTTON_3_UP), (mouseFlags & SDL_BUTTON_MMASK), data, SDL_BUTTON_MIDDLE, 0); if ((rawButtons & RI_MOUSE_BUTTON_4_DOWN)) WIN_CheckWParamMouseButton((rawButtons & RI_MOUSE_BUTTON_4_DOWN), (mouseFlags & SDL_BUTTON_X1MASK), data, SDL_BUTTON_X1, 0); if ((rawButtons & RI_MOUSE_BUTTON_4_UP)) WIN_CheckWParamMouseButton(!(rawButtons & RI_MOUSE_BUTTON_4_UP), (mouseFlags & SDL_BUTTON_X1MASK), data, SDL_BUTTON_X1, 0); if ((rawButtons & RI_MOUSE_BUTTON_5_DOWN)) WIN_CheckWParamMouseButton((rawButtons & RI_MOUSE_BUTTON_5_DOWN), (mouseFlags & SDL_BUTTON_X2MASK), data, SDL_BUTTON_X2, 0); if ((rawButtons & RI_MOUSE_BUTTON_5_UP)) WIN_CheckWParamMouseButton(!(rawButtons & RI_MOUSE_BUTTON_5_UP), (mouseFlags & SDL_BUTTON_X2MASK), data, SDL_BUTTON_X2, 0); data->mouse_button_flags = rawButtons; } } static void WIN_CheckAsyncMouseRelease(SDL_WindowData *data) { Uint32 mouseFlags; SHORT keyState; /* mouse buttons may have changed state here, we need to resync them, but we will get a WM_MOUSEMOVE right away which will fix things up if in non raw mode also */ mouseFlags = SDL_GetMouseState(NULL, NULL); keyState = GetAsyncKeyState(VK_LBUTTON); if (!(keyState & 0x8000)) { WIN_CheckWParamMouseButton(SDL_FALSE, (mouseFlags & SDL_BUTTON_LMASK), data, SDL_BUTTON_LEFT, 0); } keyState = GetAsyncKeyState(VK_RBUTTON); if (!(keyState & 0x8000)) { WIN_CheckWParamMouseButton(SDL_FALSE, (mouseFlags & SDL_BUTTON_RMASK), data, SDL_BUTTON_RIGHT, 0); } keyState = GetAsyncKeyState(VK_MBUTTON); if (!(keyState & 0x8000)) { WIN_CheckWParamMouseButton(SDL_FALSE, (mouseFlags & SDL_BUTTON_MMASK), data, SDL_BUTTON_MIDDLE, 0); } keyState = GetAsyncKeyState(VK_XBUTTON1); if (!(keyState & 0x8000)) { WIN_CheckWParamMouseButton(SDL_FALSE, (mouseFlags & SDL_BUTTON_X1MASK), data, SDL_BUTTON_X1, 0); } keyState = GetAsyncKeyState(VK_XBUTTON2); if (!(keyState & 0x8000)) { WIN_CheckWParamMouseButton(SDL_FALSE, (mouseFlags & SDL_BUTTON_X2MASK), data, SDL_BUTTON_X2, 0); } data->mouse_button_flags = 0; } static BOOL WIN_ConvertUTF32toUTF8(UINT32 codepoint, char * text) { if (codepoint <= 0x7F) { text[0] = (char) codepoint; text[1] = '\0'; } else if (codepoint <= 0x7FF) { text[0] = 0xC0 | (char) ((codepoint >> 6) & 0x1F); text[1] = 0x80 | (char) (codepoint & 0x3F); text[2] = '\0'; } else if (codepoint <= 0xFFFF) { text[0] = 0xE0 | (char) ((codepoint >> 12) & 0x0F); text[1] = 0x80 | (char) ((codepoint >> 6) & 0x3F); text[2] = 0x80 | (char) (codepoint & 0x3F); text[3] = '\0'; } else if (codepoint <= 0x10FFFF) { text[0] = 0xF0 | (char) ((codepoint >> 18) & 0x0F); text[1] = 0x80 | (char) ((codepoint >> 12) & 0x3F); text[2] = 0x80 | (char) ((codepoint >> 6) & 0x3F); text[3] = 0x80 | (char) (codepoint & 0x3F); text[4] = '\0'; } else { return SDL_FALSE; } return SDL_TRUE; } static SDL_bool ShouldGenerateWindowCloseOnAltF4(void) { return !SDL_GetHintBoolean(SDL_HINT_WINDOWS_NO_CLOSE_ON_ALT_F4, SDL_FALSE); } /* Win10 "Fall Creators Update" introduced the bug that SetCursorPos() (as used by SDL_WarpMouseInWindow()) doesn't reliably generate WM_MOUSEMOVE events anymore (see #3931) which breaks relative mouse mode via warping. This is used to implement a workaround.. */ static SDL_bool isWin10FCUorNewer = SDL_FALSE; /* We want to generate mouse events from mouse and pen, and touch events from touchscreens */ #define MI_WP_SIGNATURE 0xFF515700 #define MI_WP_SIGNATURE_MASK 0xFFFFFF00 #define IsTouchEvent(dw) ((dw) & MI_WP_SIGNATURE_MASK) == MI_WP_SIGNATURE typedef enum { SDL_MOUSE_EVENT_SOURCE_UNKNOWN, SDL_MOUSE_EVENT_SOURCE_MOUSE, SDL_MOUSE_EVENT_SOURCE_TOUCH, SDL_MOUSE_EVENT_SOURCE_PEN, } SDL_MOUSE_EVENT_SOURCE; static SDL_MOUSE_EVENT_SOURCE GetMouseMessageSource() { LPARAM extrainfo = GetMessageExtraInfo(); /* Mouse data (ignoring synthetic mouse events generated for touchscreens) */ /* Versions below Vista will set the low 7 bits to the Mouse ID and don't use bit 7: Check bits 8-32 for the signature (which will indicate a Tablet PC Pen or Touch Device). Only check bit 7 when Vista and up(Cleared=Pen, Set=Touch(which we need to filter out)), when the signature is set. The Mouse ID will be zero for an actual mouse. */ if (IsTouchEvent(extrainfo)) { if (extrainfo & 0x80) { return SDL_MOUSE_EVENT_SOURCE_TOUCH; } else { return SDL_MOUSE_EVENT_SOURCE_PEN; } } return SDL_MOUSE_EVENT_SOURCE_MOUSE; } LRESULT CALLBACK WIN_WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { SDL_WindowData *data; LRESULT returnCode = -1; /* Send a SDL_SYSWMEVENT if the application wants them */ if (SDL_GetEventState(SDL_SYSWMEVENT) == SDL_ENABLE) { SDL_SysWMmsg wmmsg; SDL_VERSION(&wmmsg.version); wmmsg.subsystem = SDL_SYSWM_WINDOWS; wmmsg.msg.win.hwnd = hwnd; wmmsg.msg.win.msg = msg; wmmsg.msg.win.wParam = wParam; wmmsg.msg.win.lParam = lParam; SDL_SendSysWMEvent(&wmmsg); } /* Get the window data for the window */ data = (SDL_WindowData *) GetProp(hwnd, TEXT("SDL_WindowData")); if (!data) { return CallWindowProc(DefWindowProc, hwnd, msg, wParam, lParam); } #ifdef WMMSG_DEBUG { char message[1024]; if (msg > MAX_WMMSG) { SDL_snprintf(message, sizeof(message), "Received windows message: %p UNKNOWN (%d) -- 0x%X, 0x%X\n", hwnd, msg, wParam, lParam); } else { SDL_snprintf(message, sizeof(message), "Received windows message: %p %s -- 0x%X, 0x%X\n", hwnd, wmtab[msg], wParam, lParam); } OutputDebugStringA(message); } #endif /* WMMSG_DEBUG */ if (IME_HandleMessage(hwnd, msg, wParam, &lParam, data->videodata)) return 0; switch (msg) { case WM_SHOWWINDOW: { if (wParam) { SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_SHOWN, 0, 0); } else { SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_HIDDEN, 0, 0); } } break; case WM_NCACTIVATE: { /* Don't immediately clip the cursor in case we're clicking minimize/maximize buttons */ data->skip_update_clipcursor = SDL_TRUE; } break; case WM_ACTIVATE: { POINT cursorPos; BOOL minimized; minimized = HIWORD(wParam); if (!minimized && (LOWORD(wParam) != WA_INACTIVE)) { /* Don't mark the window as shown if it's activated before being shown */ if (!IsWindowVisible(hwnd)) { break; } if (LOWORD(wParam) == WA_CLICKACTIVE) { if (GetAsyncKeyState(VK_LBUTTON)) { data->focus_click_pending |= SDL_BUTTON_LMASK; } if (GetAsyncKeyState(VK_RBUTTON)) { data->focus_click_pending |= SDL_BUTTON_RMASK; } if (GetAsyncKeyState(VK_MBUTTON)) { data->focus_click_pending |= SDL_BUTTON_MMASK; } if (GetAsyncKeyState(VK_XBUTTON1)) { data->focus_click_pending |= SDL_BUTTON_X1MASK; } if (GetAsyncKeyState(VK_XBUTTON2)) { data->focus_click_pending |= SDL_BUTTON_X2MASK; } } SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_SHOWN, 0, 0); if (SDL_GetKeyboardFocus() != data->window) { SDL_SetKeyboardFocus(data->window); } GetCursorPos(&cursorPos); ScreenToClient(hwnd, &cursorPos); SDL_SendMouseMotion(data->window, 0, 0, cursorPos.x, cursorPos.y); WIN_CheckAsyncMouseRelease(data); WIN_UpdateClipCursor(data->window); /* * FIXME: Update keyboard state */ WIN_CheckClipboardUpdate(data->videodata); SDL_ToggleModState(KMOD_CAPS, (GetKeyState(VK_CAPITAL) & 0x0001) != 0); SDL_ToggleModState(KMOD_NUM, (GetKeyState(VK_NUMLOCK) & 0x0001) != 0); } else { RECT rect; data->in_window_deactivation = SDL_TRUE; if (SDL_GetKeyboardFocus() == data->window) { SDL_SetKeyboardFocus(NULL); WIN_ResetDeadKeys(); } if (GetClipCursor(&rect) && SDL_memcmp(&rect, &data->cursor_clipped_rect, sizeof(rect)) == 0) { ClipCursor(NULL); SDL_zero(data->cursor_clipped_rect); } data->in_window_deactivation = SDL_FALSE; } } returnCode = 0; break; case WM_POINTERUPDATE: { data->last_pointer_update = lParam; break; } case WM_MOUSEMOVE: { SDL_Mouse *mouse = SDL_GetMouse(); if (!mouse->relative_mode || mouse->relative_mode_warp) { /* Only generate mouse events for real mouse */ if (GetMouseMessageSource() != SDL_MOUSE_EVENT_SOURCE_TOUCH && lParam != data->last_pointer_update) { SDL_SendMouseMotion(data->window, 0, 0, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); if (isWin10FCUorNewer && mouse->relative_mode_warp) { /* To work around #3931, Win10 bug introduced in Fall Creators Update, where SetCursorPos() (SDL_WarpMouseInWindow()) doesn't reliably generate mouse events anymore, after each windows mouse event generate a fake event for the middle of the window if relative_mode_warp is used */ int center_x = 0, center_y = 0; SDL_GetWindowSize(data->window, &center_x, &center_y); center_x /= 2; center_y /= 2; SDL_SendMouseMotion(data->window, 0, 0, center_x, center_y); } } } else { /* We still need to update focus */ SDL_SetMouseFocus(data->window); } } /* don't break here, fall through to check the wParam like the button presses */ case WM_LBUTTONUP: case WM_RBUTTONUP: case WM_MBUTTONUP: case WM_XBUTTONUP: case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: { SDL_Mouse *mouse = SDL_GetMouse(); if (!mouse->relative_mode || mouse->relative_mode_warp) { if (GetMouseMessageSource() != SDL_MOUSE_EVENT_SOURCE_TOUCH && lParam != data->last_pointer_update) { WIN_CheckWParamMouseButtons(wParam, data, 0); } } } break; case WM_INPUT: { SDL_Mouse *mouse = SDL_GetMouse(); HRAWINPUT hRawInput = (HRAWINPUT)lParam; RAWINPUT inp; UINT size = sizeof(inp); const SDL_bool isRelative = mouse->relative_mode || mouse->relative_mode_warp; const SDL_bool isCapture = ((data->window->flags & SDL_WINDOW_MOUSE_CAPTURE) != 0); if (!isRelative || mouse->focus != data->window) { if (!isCapture) { break; } } GetRawInputData(hRawInput, RID_INPUT, &inp, &size, sizeof(RAWINPUTHEADER)); /* Mouse data (ignoring synthetic mouse events generated for touchscreens) */ if (inp.header.dwType == RIM_TYPEMOUSE) { if (GetMouseMessageSource() == SDL_MOUSE_EVENT_SOURCE_TOUCH || (GetMessageExtraInfo() & 0x82) == 0x82) { break; } if (isRelative) { RAWMOUSE* rawmouse = &inp.data.mouse; if ((rawmouse->usFlags & 0x01) == MOUSE_MOVE_RELATIVE) { SDL_SendMouseMotion(data->window, 0, 1, (int)rawmouse->lLastX, (int)rawmouse->lLastY); } else if (rawmouse->lLastX || rawmouse->lLastY) { /* synthesize relative moves from the abs position */ static SDL_Point lastMousePoint; SDL_bool virtual_desktop = (rawmouse->usFlags & MOUSE_VIRTUAL_DESKTOP) ? SDL_TRUE : SDL_FALSE; int w = GetSystemMetrics(virtual_desktop ? SM_CXVIRTUALSCREEN : SM_CXSCREEN); int h = GetSystemMetrics(virtual_desktop ? SM_CYVIRTUALSCREEN : SM_CYSCREEN); int x = (int)(((float)rawmouse->lLastX / 65535.0f) * w); int y = (int)(((float)rawmouse->lLastY / 65535.0f) * h); if (lastMousePoint.x == 0 && lastMousePoint.y == 0) { lastMousePoint.x = x; lastMousePoint.y = y; } SDL_SendMouseMotion(data->window, 0, 1, (int)(x-lastMousePoint.x), (int)(y-lastMousePoint.y)); lastMousePoint.x = x; lastMousePoint.y = y; } WIN_CheckRawMouseButtons(rawmouse->usButtonFlags, data); } else if (isCapture) { /* we check for where Windows thinks the system cursor lives in this case, so we don't really lose mouse accel, etc. */ POINT pt; RECT hwndRect; HWND currentHnd; GetCursorPos(&pt); currentHnd = WindowFromPoint(pt); ScreenToClient(hwnd, &pt); GetClientRect(hwnd, &hwndRect); /* if in the window, WM_MOUSEMOVE, etc, will cover it. */ if(currentHnd != hwnd || pt.x < 0 || pt.y < 0 || pt.x > hwndRect.right || pt.y > hwndRect.right) { SDL_SendMouseMotion(data->window, 0, 0, (int)pt.x, (int)pt.y); SDL_SendMouseButton(data->window, 0, GetAsyncKeyState(VK_LBUTTON) & 0x8000 ? SDL_PRESSED : SDL_RELEASED, SDL_BUTTON_LEFT); SDL_SendMouseButton(data->window, 0, GetAsyncKeyState(VK_RBUTTON) & 0x8000 ? SDL_PRESSED : SDL_RELEASED, SDL_BUTTON_RIGHT); SDL_SendMouseButton(data->window, 0, GetAsyncKeyState(VK_MBUTTON) & 0x8000 ? SDL_PRESSED : SDL_RELEASED, SDL_BUTTON_MIDDLE); SDL_SendMouseButton(data->window, 0, GetAsyncKeyState(VK_XBUTTON1) & 0x8000 ? SDL_PRESSED : SDL_RELEASED, SDL_BUTTON_X1); SDL_SendMouseButton(data->window, 0, GetAsyncKeyState(VK_XBUTTON2) & 0x8000 ? SDL_PRESSED : SDL_RELEASED, SDL_BUTTON_X2); } } else { SDL_assert(0 && "Shouldn't happen"); } } } break; case WM_MOUSEWHEEL: case WM_MOUSEHWHEEL: { short amount = GET_WHEEL_DELTA_WPARAM(wParam); float fAmount = (float) amount / WHEEL_DELTA; if (msg == WM_MOUSEWHEEL) SDL_SendMouseWheel(data->window, 0, 0.0f, fAmount, SDL_MOUSEWHEEL_NORMAL); else SDL_SendMouseWheel(data->window, 0, fAmount, 0.0f, SDL_MOUSEWHEEL_NORMAL); } break; #ifdef WM_MOUSELEAVE case WM_MOUSELEAVE: if (SDL_GetMouseFocus() == data->window && !SDL_GetMouse()->relative_mode && !(data->window->flags & SDL_WINDOW_MOUSE_CAPTURE)) { if (!IsIconic(hwnd)) { SDL_Mouse *mouse; POINT cursorPos; GetCursorPos(&cursorPos); ScreenToClient(hwnd, &cursorPos); mouse = SDL_GetMouse(); if (!mouse->was_touch_mouse_events) { /* we're not a touch handler causing a mouse leave? */ SDL_SendMouseMotion(data->window, 0, 0, cursorPos.x, cursorPos.y); } else { /* touch handling? */ mouse->was_touch_mouse_events = SDL_FALSE; /* not anymore */ if (mouse->touch_mouse_events) { /* convert touch to mouse events */ SDL_SendMouseMotion(data->window, SDL_TOUCH_MOUSEID, 0, cursorPos.x, cursorPos.y); } else { /* normal handling */ SDL_SendMouseMotion(data->window, 0, 0, cursorPos.x, cursorPos.y); } } } SDL_SetMouseFocus(NULL); } returnCode = 0; break; #endif /* WM_MOUSELEAVE */ case WM_KEYDOWN: case WM_SYSKEYDOWN: { SDL_Scancode code = WindowsScanCodeToSDLScanCode(lParam, wParam); const Uint8 *keyboardState = SDL_GetKeyboardState(NULL); /* Detect relevant keyboard shortcuts */ if (keyboardState[SDL_SCANCODE_LALT] == SDL_PRESSED || keyboardState[SDL_SCANCODE_RALT] == SDL_PRESSED) { /* ALT+F4: Close window */ if (code == SDL_SCANCODE_F4 && ShouldGenerateWindowCloseOnAltF4()) { SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_CLOSE, 0, 0); } } if (code != SDL_SCANCODE_UNKNOWN) { SDL_SendKeyboardKey(SDL_PRESSED, code); } } returnCode = 0; break; case WM_SYSKEYUP: case WM_KEYUP: { SDL_Scancode code = WindowsScanCodeToSDLScanCode(lParam, wParam); const Uint8 *keyboardState = SDL_GetKeyboardState(NULL); if (code != SDL_SCANCODE_UNKNOWN) { if (code == SDL_SCANCODE_PRINTSCREEN && keyboardState[code] == SDL_RELEASED) { SDL_SendKeyboardKey(SDL_PRESSED, code); } SDL_SendKeyboardKey(SDL_RELEASED, code); } } returnCode = 0; break; case WM_UNICHAR: if (wParam == UNICODE_NOCHAR) { returnCode = 1; break; } /* otherwise fall through to below */ case WM_CHAR: { char text[5]; if (WIN_ConvertUTF32toUTF8((UINT32)wParam, text)) { SDL_SendKeyboardText(text); } } returnCode = 0; break; #ifdef WM_INPUTLANGCHANGE case WM_INPUTLANGCHANGE: { WIN_UpdateKeymap(); SDL_SendKeymapChangedEvent(); } returnCode = 1; break; #endif /* WM_INPUTLANGCHANGE */ case WM_NCLBUTTONDOWN: { data->in_title_click = SDL_TRUE; } break; case WM_CAPTURECHANGED: { data->in_title_click = SDL_FALSE; /* The mouse may have been released during a modal loop */ WIN_CheckAsyncMouseRelease(data); } break; #ifdef WM_GETMINMAXINFO case WM_GETMINMAXINFO: { MINMAXINFO *info; RECT size; int x, y; int w, h; int min_w, min_h; int max_w, max_h; BOOL constrain_max_size; if (SDL_IsShapedWindow(data->window)) { Win32_ResizeWindowShape(data->window); } /* If this is an expected size change, allow it */ if (data->expected_resize) { break; } /* Get the current position of our window */ GetWindowRect(hwnd, &size); x = size.left; y = size.top; /* Calculate current size of our window */ SDL_GetWindowSize(data->window, &w, &h); SDL_GetWindowMinimumSize(data->window, &min_w, &min_h); SDL_GetWindowMaximumSize(data->window, &max_w, &max_h); /* Store in min_w and min_h difference between current size and minimal size so we don't need to call AdjustWindowRectEx twice */ min_w -= w; min_h -= h; if (max_w && max_h) { max_w -= w; max_h -= h; constrain_max_size = TRUE; } else { constrain_max_size = FALSE; } if (!(SDL_GetWindowFlags(data->window) & SDL_WINDOW_BORDERLESS)) { LONG style = GetWindowLong(hwnd, GWL_STYLE); /* DJM - according to the docs for GetMenu(), the return value is undefined if hwnd is a child window. Apparently it's too difficult for MS to check inside their function, so I have to do it here. */ BOOL menu = (style & WS_CHILDWINDOW) ? FALSE : (GetMenu(hwnd) != NULL); size.top = 0; size.left = 0; size.bottom = h; size.right = w; AdjustWindowRectEx(&size, style, menu, 0); w = size.right - size.left; h = size.bottom - size.top; } /* Fix our size to the current size */ info = (MINMAXINFO *) lParam; if (SDL_GetWindowFlags(data->window) & SDL_WINDOW_RESIZABLE) { info->ptMinTrackSize.x = w + min_w; info->ptMinTrackSize.y = h + min_h; if (constrain_max_size) { info->ptMaxTrackSize.x = w + max_w; info->ptMaxTrackSize.y = h + max_h; } } else { info->ptMaxSize.x = w; info->ptMaxSize.y = h; info->ptMaxPosition.x = x; info->ptMaxPosition.y = y; info->ptMinTrackSize.x = w; info->ptMinTrackSize.y = h; info->ptMaxTrackSize.x = w; info->ptMaxTrackSize.y = h; } } returnCode = 0; break; #endif /* WM_GETMINMAXINFO */ case WM_WINDOWPOSCHANGING: if (data->expected_resize) { returnCode = 0; } break; case WM_WINDOWPOSCHANGED: { RECT rect; int x, y; int w, h; if (data->initializing || data->in_border_change) { break; } if (!GetClientRect(hwnd, &rect) || IsRectEmpty(&rect)) { break; } ClientToScreen(hwnd, (LPPOINT) & rect); ClientToScreen(hwnd, (LPPOINT) & rect + 1); WIN_UpdateClipCursor(data->window); x = rect.left; y = rect.top; SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_MOVED, x, y); w = rect.right - rect.left; h = rect.bottom - rect.top; SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_RESIZED, w, h); /* Forces a WM_PAINT event */ InvalidateRect(hwnd, NULL, FALSE); } break; case WM_SIZE: { switch (wParam) { case SIZE_MAXIMIZED: SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_RESTORED, 0, 0); SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_MAXIMIZED, 0, 0); break; case SIZE_MINIMIZED: SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_MINIMIZED, 0, 0); break; default: SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_RESTORED, 0, 0); break; } } break; case WM_SETCURSOR: { Uint16 hittest; hittest = LOWORD(lParam); if (hittest == HTCLIENT) { SetCursor(SDL_cursor); returnCode = TRUE; } else if (!g_WindowFrameUsableWhileCursorHidden && !SDL_cursor) { SetCursor(NULL); returnCode = TRUE; } } break; /* We were occluded, refresh our display */ case WM_PAINT: { RECT rect; if (GetUpdateRect(hwnd, &rect, FALSE)) { ValidateRect(hwnd, NULL); SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_EXPOSED, 0, 0); } } returnCode = 0; break; /* We'll do our own drawing, prevent flicker */ case WM_ERASEBKGND: { } return (1); case WM_SYSCOMMAND: { if ((wParam & 0xFFF0) == SC_KEYMENU) { return (0); } #if defined(SC_SCREENSAVE) || defined(SC_MONITORPOWER) /* Don't start the screensaver or blank the monitor in fullscreen apps */ if ((wParam & 0xFFF0) == SC_SCREENSAVE || (wParam & 0xFFF0) == SC_MONITORPOWER) { if (SDL_GetVideoDevice()->suspend_screensaver) { return (0); } } #endif /* System has screensaver support */ } break; case WM_CLOSE: { SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_CLOSE, 0, 0); } returnCode = 0; break; case WM_TOUCH: if (data->videodata->GetTouchInputInfo && data->videodata->CloseTouchInputHandle) { UINT i, num_inputs = LOWORD(wParam); SDL_bool isstack; PTOUCHINPUT inputs = SDL_small_alloc(TOUCHINPUT, num_inputs, &isstack); if (data->videodata->GetTouchInputInfo((HTOUCHINPUT)lParam, num_inputs, inputs, sizeof(TOUCHINPUT))) { RECT rect; float x, y; if (!GetClientRect(hwnd, &rect) || (rect.right == rect.left && rect.bottom == rect.top)) { if (inputs) { SDL_small_free(inputs, isstack); } break; } ClientToScreen(hwnd, (LPPOINT) & rect); ClientToScreen(hwnd, (LPPOINT) & rect + 1); rect.top *= 100; rect.left *= 100; rect.bottom *= 100; rect.right *= 100; for (i = 0; i < num_inputs; ++i) { PTOUCHINPUT input = &inputs[i]; const SDL_TouchID touchId = (SDL_TouchID)((size_t)input->hSource); /* TODO: Can we use GetRawInputDeviceInfo and HID info to determine if this is a direct or indirect touch device? */ if (SDL_AddTouch(touchId, SDL_TOUCH_DEVICE_DIRECT, "") < 0) { continue; } /* Get the normalized coordinates for the window */ x = (float)(input->x - rect.left)/(rect.right - rect.left); y = (float)(input->y - rect.top)/(rect.bottom - rect.top); if (input->dwFlags & TOUCHEVENTF_DOWN) { SDL_SendTouch(touchId, input->dwID, data->window, SDL_TRUE, x, y, 1.0f); } if (input->dwFlags & TOUCHEVENTF_MOVE) { SDL_SendTouchMotion(touchId, input->dwID, data->window, x, y, 1.0f); } if (input->dwFlags & TOUCHEVENTF_UP) { SDL_SendTouch(touchId, input->dwID, data->window, SDL_FALSE, x, y, 1.0f); } } } SDL_small_free(inputs, isstack); data->videodata->CloseTouchInputHandle((HTOUCHINPUT)lParam); return 0; } break; case WM_DROPFILES: { UINT i; HDROP drop = (HDROP) wParam; UINT count = DragQueryFile(drop, 0xFFFFFFFF, NULL, 0); for (i = 0; i < count; ++i) { SDL_bool isstack; UINT size = DragQueryFile(drop, i, NULL, 0) + 1; LPTSTR buffer = SDL_small_alloc(TCHAR, size, &isstack); if (buffer) { if (DragQueryFile(drop, i, buffer, size)) { char *file = WIN_StringToUTF8(buffer); SDL_SendDropFile(data->window, file); SDL_free(file); } SDL_small_free(buffer, isstack); } } SDL_SendDropComplete(data->window); DragFinish(drop); return 0; } break; case WM_NCCALCSIZE: { Uint32 window_flags = SDL_GetWindowFlags(data->window); if (wParam == TRUE && (window_flags & SDL_WINDOW_BORDERLESS) && !(window_flags & SDL_WINDOW_FULLSCREEN)) { /* When borderless, need to tell windows that the size of the non-client area is 0 */ if (!(window_flags & SDL_WINDOW_RESIZABLE)) { int w, h; NCCALCSIZE_PARAMS *params = (NCCALCSIZE_PARAMS *)lParam; w = data->window->windowed.w; h = data->window->windowed.h; params->rgrc[0].right = params->rgrc[0].left + w; params->rgrc[0].bottom = params->rgrc[0].top + h; } return 0; } } break; case WM_NCHITTEST: { SDL_Window *window = data->window; if (window->hit_test) { POINT winpoint = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; if (ScreenToClient(hwnd, &winpoint)) { const SDL_Point point = { (int) winpoint.x, (int) winpoint.y }; const SDL_HitTestResult rc = window->hit_test(window, &point, window->hit_test_data); switch (rc) { #define POST_HIT_TEST(ret) { SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_HIT_TEST, 0, 0); return ret; } case SDL_HITTEST_DRAGGABLE: POST_HIT_TEST(HTCAPTION); case SDL_HITTEST_RESIZE_TOPLEFT: POST_HIT_TEST(HTTOPLEFT); case SDL_HITTEST_RESIZE_TOP: POST_HIT_TEST(HTTOP); case SDL_HITTEST_RESIZE_TOPRIGHT: POST_HIT_TEST(HTTOPRIGHT); case SDL_HITTEST_RESIZE_RIGHT: POST_HIT_TEST(HTRIGHT); case SDL_HITTEST_RESIZE_BOTTOMRIGHT: POST_HIT_TEST(HTBOTTOMRIGHT); case SDL_HITTEST_RESIZE_BOTTOM: POST_HIT_TEST(HTBOTTOM); case SDL_HITTEST_RESIZE_BOTTOMLEFT: POST_HIT_TEST(HTBOTTOMLEFT); case SDL_HITTEST_RESIZE_LEFT: POST_HIT_TEST(HTLEFT); #undef POST_HIT_TEST case SDL_HITTEST_NORMAL: return HTCLIENT; } } /* If we didn't return, this will call DefWindowProc below. */ } } break; } /* If there's a window proc, assume it's going to handle messages */ if (data->wndproc) { return CallWindowProc(data->wndproc, hwnd, msg, wParam, lParam); } else if (returnCode >= 0) { return returnCode; } else { return CallWindowProc(DefWindowProc, hwnd, msg, wParam, lParam); } } static void WIN_UpdateClipCursorForWindows() { SDL_VideoDevice *_this = SDL_GetVideoDevice(); SDL_Window *window; Uint32 now = SDL_GetTicks(); const Uint32 CLIPCURSOR_UPDATE_INTERVAL_MS = 3000; if (_this) { for (window = _this->windows; window; window = window->next) { SDL_WindowData *data = (SDL_WindowData *)window->driverdata; if (data) { if (data->skip_update_clipcursor) { data->skip_update_clipcursor = SDL_FALSE; WIN_UpdateClipCursor(window); } else if ((now - data->last_updated_clipcursor) >= CLIPCURSOR_UPDATE_INTERVAL_MS) { WIN_UpdateClipCursor(window); } } } } } /* A message hook called before TranslateMessage() */ static SDL_WindowsMessageHook g_WindowsMessageHook = NULL; static void *g_WindowsMessageHookData = NULL; void SDL_SetWindowsMessageHook(SDL_WindowsMessageHook callback, void *userdata) { g_WindowsMessageHook = callback; g_WindowsMessageHookData = userdata; } void WIN_PumpEvents(_THIS) { const Uint8 *keystate; MSG msg; DWORD start_ticks = GetTickCount(); int new_messages = 0; if (g_WindowsEnableMessageLoop) { while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (g_WindowsMessageHook) { g_WindowsMessageHook(g_WindowsMessageHookData, msg.hwnd, msg.message, msg.wParam, msg.lParam); } /* Always translate the message in case it's a non-SDL window (e.g. with Qt integration) */ TranslateMessage(&msg); DispatchMessage(&msg); /* Make sure we don't busy loop here forever if there are lots of events coming in */ if (SDL_TICKS_PASSED(msg.time, start_ticks)) { /* We might get a few new messages generated by the Steam overlay or other application hooks In this case those messages will be processed before any pending input, so we want to continue after those messages. (thanks to Peter Deayton for his investigation here) */ const int MAX_NEW_MESSAGES = 3; ++new_messages; if (new_messages > MAX_NEW_MESSAGES) { break; } } } } /* Windows loses a shift KEYUP event when you have both pressed at once and let go of one. You won't get a KEYUP until both are released, and that keyup will only be for the second key you released. Take heroic measures and check the keystate as of the last handled event, and if we think a key is pressed when Windows doesn't, unstick it in SDL's state. */ keystate = SDL_GetKeyboardState(NULL); if ((keystate[SDL_SCANCODE_LSHIFT] == SDL_PRESSED) && !(GetKeyState(VK_LSHIFT) & 0x8000)) { SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_LSHIFT); } if ((keystate[SDL_SCANCODE_RSHIFT] == SDL_PRESSED) && !(GetKeyState(VK_RSHIFT) & 0x8000)) { SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_RSHIFT); } /* Update the clipping rect in case someone else has stolen it */ WIN_UpdateClipCursorForWindows(); } /* to work around #3931, a bug introduced in Win10 Fall Creators Update (build nr. 16299) we need to detect the windows version. this struct and the function below does that. usually this struct and the corresponding function (RtlGetVersion) are in <Ntddk.h> but here we just load it dynamically */ struct SDL_WIN_OSVERSIONINFOW { ULONG dwOSVersionInfoSize; ULONG dwMajorVersion; ULONG dwMinorVersion; ULONG dwBuildNumber; ULONG dwPlatformId; WCHAR szCSDVersion[128]; }; static SDL_bool IsWin10FCUorNewer(void) { HMODULE handle = GetModuleHandleW(L"ntdll.dll"); if (handle) { typedef LONG(WINAPI* RtlGetVersionPtr)(struct SDL_WIN_OSVERSIONINFOW*); RtlGetVersionPtr getVersionPtr = (RtlGetVersionPtr)GetProcAddress(handle, "RtlGetVersion"); if (getVersionPtr != NULL) { struct SDL_WIN_OSVERSIONINFOW info; SDL_zero(info); info.dwOSVersionInfoSize = sizeof(info); if (getVersionPtr(&info) == 0) { /* STATUS_SUCCESS == 0 */ if ((info.dwMajorVersion == 10 && info.dwMinorVersion == 0 && info.dwBuildNumber >= 16299) || (info.dwMajorVersion == 10 && info.dwMinorVersion > 0) || (info.dwMajorVersion > 10)) { return SDL_TRUE; } } } } return SDL_FALSE; } static int app_registered = 0; LPTSTR SDL_Appname = NULL; Uint32 SDL_Appstyle = 0; HINSTANCE SDL_Instance = NULL; /* Register the class for this application */ int SDL_RegisterApp(char *name, Uint32 style, void *hInst) { const char *hint; WNDCLASSEX wcex; TCHAR path[MAX_PATH]; /* Only do this once... */ if (app_registered) { ++app_registered; return (0); } if (!name && !SDL_Appname) { name = "SDL_app"; #if defined(CS_BYTEALIGNCLIENT) || defined(CS_OWNDC) SDL_Appstyle = (CS_BYTEALIGNCLIENT | CS_OWNDC); #endif SDL_Instance = hInst ? hInst : GetModuleHandle(NULL); } if (name) { SDL_Appname = WIN_UTF8ToString(name); SDL_Appstyle = style; SDL_Instance = hInst ? hInst : GetModuleHandle(NULL); } /* Register the application class */ wcex.cbSize = sizeof(WNDCLASSEX); wcex.hCursor = NULL; wcex.hIcon = NULL; wcex.hIconSm = NULL; wcex.lpszMenuName = NULL; wcex.lpszClassName = SDL_Appname; wcex.style = SDL_Appstyle; wcex.hbrBackground = NULL; wcex.lpfnWndProc = WIN_WindowProc; wcex.hInstance = SDL_Instance; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; hint = SDL_GetHint(SDL_HINT_WINDOWS_INTRESOURCE_ICON); if (hint && *hint) { wcex.hIcon = LoadIcon(SDL_Instance, MAKEINTRESOURCE(SDL_atoi(hint))); hint = SDL_GetHint(SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL); if (hint && *hint) { wcex.hIconSm = LoadIcon(SDL_Instance, MAKEINTRESOURCE(SDL_atoi(hint))); } } else { /* Use the first icon as a default icon, like in the Explorer */ GetModuleFileName(SDL_Instance, path, MAX_PATH); ExtractIconEx(path, 0, &wcex.hIcon, &wcex.hIconSm, 1); } if (!RegisterClassEx(&wcex)) { return SDL_SetError("Couldn't register application class"); } isWin10FCUorNewer = IsWin10FCUorNewer(); app_registered = 1; return 0; } /* Unregisters the windowclass registered in SDL_RegisterApp above. */ void SDL_UnregisterApp() { WNDCLASSEX wcex; /* SDL_RegisterApp might not have been called before */ if (!app_registered) { return; } --app_registered; if (app_registered == 0) { /* Check for any registered window classes. */ if (GetClassInfoEx(SDL_Instance, SDL_Appname, &wcex)) { UnregisterClass(SDL_Appname, SDL_Instance); if (wcex.hIcon) DestroyIcon(wcex.hIcon); if (wcex.hIconSm) DestroyIcon(wcex.hIconSm); } SDL_free(SDL_Appname); SDL_Appname = NULL; } } #endif /* SDL_VIDEO_DRIVER_WINDOWS */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsevents.c
C
apache-2.0
49,894
/* 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_windowsevents_h_ #define SDL_windowsevents_h_ extern LPTSTR SDL_Appname; extern Uint32 SDL_Appstyle; extern HINSTANCE SDL_Instance; extern LRESULT CALLBACK WIN_WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); extern void WIN_PumpEvents(_THIS); #endif /* SDL_windowsevents_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsevents.h
C
apache-2.0
1,354
/* 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_VIDEO_DRIVER_WINDOWS #include "SDL_windowsvideo.h" int WIN_CreateWindowFramebuffer(_THIS, SDL_Window * window, Uint32 * format, void ** pixels, int *pitch) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; SDL_bool isstack; size_t size; LPBITMAPINFO info; HBITMAP hbm; /* Free the old framebuffer surface */ if (data->mdc) { DeleteDC(data->mdc); } if (data->hbm) { DeleteObject(data->hbm); } /* Find out the format of the screen */ size = sizeof(BITMAPINFOHEADER) + 256 * sizeof (RGBQUAD); info = (LPBITMAPINFO)SDL_small_alloc(Uint8, size, &isstack); if (!info) { return SDL_OutOfMemory(); } SDL_memset(info, 0, size); info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); /* The second call to GetDIBits() fills in the bitfields */ hbm = CreateCompatibleBitmap(data->hdc, 1, 1); GetDIBits(data->hdc, hbm, 0, 0, NULL, info, DIB_RGB_COLORS); GetDIBits(data->hdc, hbm, 0, 0, NULL, info, DIB_RGB_COLORS); DeleteObject(hbm); *format = SDL_PIXELFORMAT_UNKNOWN; if (info->bmiHeader.biCompression == BI_BITFIELDS) { int bpp; Uint32 *masks; bpp = info->bmiHeader.biPlanes * info->bmiHeader.biBitCount; masks = (Uint32*)((Uint8*)info + info->bmiHeader.biSize); *format = SDL_MasksToPixelFormatEnum(bpp, masks[0], masks[1], masks[2], 0); } if (*format == SDL_PIXELFORMAT_UNKNOWN) { /* We'll use RGB format for now */ *format = SDL_PIXELFORMAT_RGB888; /* Create a new one */ SDL_memset(info, 0, size); info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); info->bmiHeader.biPlanes = 1; info->bmiHeader.biBitCount = 32; info->bmiHeader.biCompression = BI_RGB; } /* Fill in the size information */ *pitch = (((window->w * SDL_BYTESPERPIXEL(*format)) + 3) & ~3); info->bmiHeader.biWidth = window->w; info->bmiHeader.biHeight = -window->h; /* negative for topdown bitmap */ info->bmiHeader.biSizeImage = window->h * (*pitch); data->mdc = CreateCompatibleDC(data->hdc); data->hbm = CreateDIBSection(data->hdc, info, DIB_RGB_COLORS, pixels, NULL, 0); SDL_small_free(info, isstack); if (!data->hbm) { return WIN_SetError("Unable to create DIB"); } SelectObject(data->mdc, data->hbm); return 0; } int WIN_UpdateWindowFramebuffer(_THIS, SDL_Window * window, const SDL_Rect * rects, int numrects) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; int i; for (i = 0; i < numrects; ++i) { BitBlt(data->hdc, rects[i].x, rects[i].y, rects[i].w, rects[i].h, data->mdc, rects[i].x, rects[i].y, SRCCOPY); } return 0; } void WIN_DestroyWindowFramebuffer(_THIS, SDL_Window * window) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; if (!data) { /* The window wasn't fully initialized */ return; } if (data->mdc) { DeleteDC(data->mdc); data->mdc = NULL; } if (data->hbm) { DeleteObject(data->hbm); data->hbm = NULL; } } #endif /* SDL_VIDEO_DRIVER_WINDOWS */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsframebuffer.c
C
apache-2.0
4,215
/* 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" extern int WIN_CreateWindowFramebuffer(_THIS, SDL_Window * window, Uint32 * format, void ** pixels, int *pitch); extern int WIN_UpdateWindowFramebuffer(_THIS, SDL_Window * window, const SDL_Rect * rects, int numrects); extern void WIN_DestroyWindowFramebuffer(_THIS, SDL_Window * window); /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsframebuffer.h
C
apache-2.0
1,297
/* 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_VIDEO_DRIVER_WINDOWS #include "SDL_windowsvideo.h" #include "../../events/SDL_keyboard_c.h" #include "../../events/scancodes_windows.h" #include <imm.h> #include <oleauto.h> #ifndef SDL_DISABLE_WINDOWS_IME static void IME_Init(SDL_VideoData *videodata, HWND hwnd); static void IME_Enable(SDL_VideoData *videodata, HWND hwnd); static void IME_Disable(SDL_VideoData *videodata, HWND hwnd); static void IME_Quit(SDL_VideoData *videodata); #endif /* !SDL_DISABLE_WINDOWS_IME */ #ifndef MAPVK_VK_TO_VSC #define MAPVK_VK_TO_VSC 0 #endif #ifndef MAPVK_VSC_TO_VK #define MAPVK_VSC_TO_VK 1 #endif #ifndef MAPVK_VK_TO_CHAR #define MAPVK_VK_TO_CHAR 2 #endif /* Alphabetic scancodes for PC keyboards */ void WIN_InitKeyboard(_THIS) { SDL_VideoData *data = (SDL_VideoData *) _this->driverdata; data->ime_com_initialized = SDL_FALSE; data->ime_threadmgr = 0; data->ime_initialized = SDL_FALSE; data->ime_enabled = SDL_FALSE; data->ime_available = SDL_FALSE; data->ime_hwnd_main = 0; data->ime_hwnd_current = 0; data->ime_himc = 0; data->ime_composition[0] = 0; data->ime_readingstring[0] = 0; data->ime_cursor = 0; data->ime_candlist = SDL_FALSE; SDL_memset(data->ime_candidates, 0, sizeof(data->ime_candidates)); data->ime_candcount = 0; data->ime_candref = 0; data->ime_candsel = 0; data->ime_candpgsize = 0; data->ime_candlistindexbase = 0; data->ime_candvertical = SDL_TRUE; data->ime_dirty = SDL_FALSE; SDL_memset(&data->ime_rect, 0, sizeof(data->ime_rect)); SDL_memset(&data->ime_candlistrect, 0, sizeof(data->ime_candlistrect)); data->ime_winwidth = 0; data->ime_winheight = 0; data->ime_hkl = 0; data->ime_himm32 = 0; data->GetReadingString = 0; data->ShowReadingWindow = 0; data->ImmLockIMC = 0; data->ImmUnlockIMC = 0; data->ImmLockIMCC = 0; data->ImmUnlockIMCC = 0; data->ime_uiless = SDL_FALSE; data->ime_threadmgrex = 0; data->ime_uielemsinkcookie = TF_INVALID_COOKIE; data->ime_alpnsinkcookie = TF_INVALID_COOKIE; data->ime_openmodesinkcookie = TF_INVALID_COOKIE; data->ime_convmodesinkcookie = TF_INVALID_COOKIE; data->ime_uielemsink = 0; data->ime_ippasink = 0; WIN_UpdateKeymap(); SDL_SetScancodeName(SDL_SCANCODE_APPLICATION, "Menu"); SDL_SetScancodeName(SDL_SCANCODE_LGUI, "Left Windows"); SDL_SetScancodeName(SDL_SCANCODE_RGUI, "Right Windows"); /* Are system caps/num/scroll lock active? Set our state to match. */ SDL_ToggleModState(KMOD_CAPS, (GetKeyState(VK_CAPITAL) & 0x0001) != 0); SDL_ToggleModState(KMOD_NUM, (GetKeyState(VK_NUMLOCK) & 0x0001) != 0); } void WIN_UpdateKeymap() { int i; SDL_Scancode scancode; SDL_Keycode keymap[SDL_NUM_SCANCODES]; SDL_GetDefaultKeymap(keymap); for (i = 0; i < SDL_arraysize(windows_scancode_table); i++) { int vk; /* Make sure this scancode is a valid character scancode */ scancode = windows_scancode_table[i]; if (scancode == SDL_SCANCODE_UNKNOWN ) { continue; } /* If this key is one of the non-mappable keys, ignore it */ /* Not mapping numbers fixes the French layout, giving numeric keycodes for the number keys, which is the expected behavior */ if ((keymap[scancode] & SDLK_SCANCODE_MASK) || /* scancode == SDL_SCANCODE_GRAVE || */ /* Uncomment this line to re-enable the behavior of not mapping the "`"(grave) key to the users actual keyboard layout */ (scancode >= SDL_SCANCODE_1 && scancode <= SDL_SCANCODE_0) ) { continue; } vk = MapVirtualKey(i, MAPVK_VSC_TO_VK); if ( vk ) { int ch = (MapVirtualKey( vk, MAPVK_VK_TO_CHAR ) & 0x7FFF); if ( ch ) { if ( ch >= 'A' && ch <= 'Z' ) { keymap[scancode] = SDLK_a + ( ch - 'A' ); } else { keymap[scancode] = ch; } } } } SDL_SetKeymap(0, keymap, SDL_NUM_SCANCODES); } void WIN_QuitKeyboard(_THIS) { #ifndef SDL_DISABLE_WINDOWS_IME IME_Quit((SDL_VideoData *)_this->driverdata); #endif } void WIN_ResetDeadKeys() { /* if a deadkey has been typed, but not the next character (which the deadkey might modify), this tries to undo the effect pressing the deadkey. see: http://archives.miloush.net/michkap/archive/2006/09/10/748775.html */ BYTE keyboardState[256]; WCHAR buffer[16]; int keycode, scancode, result, i; GetKeyboardState(keyboardState); keycode = VK_SPACE; scancode = MapVirtualKey(keycode, MAPVK_VK_TO_VSC); if (scancode == 0) { /* the keyboard doesn't have this key */ return; } for (i = 0; i < 5; i++) { result = ToUnicode(keycode, scancode, keyboardState, (LPWSTR)buffer, 16, 0); if (result > 0) { /* success */ return; } } } void WIN_StartTextInput(_THIS) { #ifndef SDL_DISABLE_WINDOWS_IME SDL_Window *window; #endif WIN_ResetDeadKeys(); #ifndef SDL_DISABLE_WINDOWS_IME window = SDL_GetKeyboardFocus(); if (window) { HWND hwnd = ((SDL_WindowData *) window->driverdata)->hwnd; SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; SDL_GetWindowSize(window, &videodata->ime_winwidth, &videodata->ime_winheight); IME_Init(videodata, hwnd); IME_Enable(videodata, hwnd); } #endif /* !SDL_DISABLE_WINDOWS_IME */ } void WIN_StopTextInput(_THIS) { #ifndef SDL_DISABLE_WINDOWS_IME SDL_Window *window; #endif WIN_ResetDeadKeys(); #ifndef SDL_DISABLE_WINDOWS_IME window = SDL_GetKeyboardFocus(); if (window) { HWND hwnd = ((SDL_WindowData *) window->driverdata)->hwnd; SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; IME_Init(videodata, hwnd); IME_Disable(videodata, hwnd); } #endif /* !SDL_DISABLE_WINDOWS_IME */ } void WIN_SetTextInputRect(_THIS, SDL_Rect *rect) { SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; HIMC himc = 0; if (!rect) { SDL_InvalidParamError("rect"); return; } videodata->ime_rect = *rect; himc = ImmGetContext(videodata->ime_hwnd_current); if (himc) { COMPOSITIONFORM cf; cf.ptCurrentPos.x = videodata->ime_rect.x; cf.ptCurrentPos.y = videodata->ime_rect.y; cf.dwStyle = CFS_FORCE_POSITION; ImmSetCompositionWindow(himc, &cf); ImmReleaseContext(videodata->ime_hwnd_current, himc); } } #ifdef SDL_DISABLE_WINDOWS_IME SDL_bool IME_HandleMessage(HWND hwnd, UINT msg, WPARAM wParam, LPARAM *lParam, SDL_VideoData *videodata) { return SDL_FALSE; } void IME_Present(SDL_VideoData *videodata) { } #else #ifdef SDL_msctf_h_ #define USE_INIT_GUID #elif defined(__GNUC__) #define USE_INIT_GUID #endif #ifdef USE_INIT_GUID #undef DEFINE_GUID #define DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) static const GUID n = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} DEFINE_GUID(IID_ITfInputProcessorProfileActivationSink, 0x71C6E74E,0x0F28,0x11D8,0xA8,0x2A,0x00,0x06,0x5B,0x84,0x43,0x5C); DEFINE_GUID(IID_ITfUIElementSink, 0xEA1EA136,0x19DF,0x11D7,0xA6,0xD2,0x00,0x06,0x5B,0x84,0x43,0x5C); DEFINE_GUID(GUID_TFCAT_TIP_KEYBOARD, 0x34745C63,0xB2F0,0x4784,0x8B,0x67,0x5E,0x12,0xC8,0x70,0x1A,0x31); DEFINE_GUID(IID_ITfSource, 0x4EA48A35,0x60AE,0x446F,0x8F,0xD6,0xE6,0xA8,0xD8,0x24,0x59,0xF7); DEFINE_GUID(IID_ITfUIElementMgr, 0xEA1EA135,0x19DF,0x11D7,0xA6,0xD2,0x00,0x06,0x5B,0x84,0x43,0x5C); DEFINE_GUID(IID_ITfCandidateListUIElement, 0xEA1EA138,0x19DF,0x11D7,0xA6,0xD2,0x00,0x06,0x5B,0x84,0x43,0x5C); DEFINE_GUID(IID_ITfReadingInformationUIElement, 0xEA1EA139,0x19DF,0x11D7,0xA6,0xD2,0x00,0x06,0x5B,0x84,0x43,0x5C); DEFINE_GUID(IID_ITfThreadMgr, 0xAA80E801,0x2021,0x11D2,0x93,0xE0,0x00,0x60,0xB0,0x67,0xB8,0x6E); DEFINE_GUID(CLSID_TF_ThreadMgr, 0x529A9E6B,0x6587,0x4F23,0xAB,0x9E,0x9C,0x7D,0x68,0x3E,0x3C,0x50); DEFINE_GUID(IID_ITfThreadMgrEx, 0x3E90ADE3,0x7594,0x4CB0,0xBB,0x58,0x69,0x62,0x8F,0x5F,0x45,0x8C); #endif #define LANG_CHT MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL) #define LANG_CHS MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED) #define MAKEIMEVERSION(major,minor) ((DWORD) (((BYTE)(major) << 24) | ((BYTE)(minor) << 16) )) #define IMEID_VER(id) ((id) & 0xffff0000) #define IMEID_LANG(id) ((id) & 0x0000ffff) #define CHT_HKL_DAYI ((HKL)(UINT_PTR)0xE0060404) #define CHT_HKL_NEW_PHONETIC ((HKL)(UINT_PTR)0xE0080404) #define CHT_HKL_NEW_CHANG_JIE ((HKL)(UINT_PTR)0xE0090404) #define CHT_HKL_NEW_QUICK ((HKL)(UINT_PTR)0xE00A0404) #define CHT_HKL_HK_CANTONESE ((HKL)(UINT_PTR)0xE00B0404) #define CHT_IMEFILENAME1 "TINTLGNT.IME" #define CHT_IMEFILENAME2 "CINTLGNT.IME" #define CHT_IMEFILENAME3 "MSTCIPHA.IME" #define IMEID_CHT_VER42 (LANG_CHT | MAKEIMEVERSION(4, 2)) #define IMEID_CHT_VER43 (LANG_CHT | MAKEIMEVERSION(4, 3)) #define IMEID_CHT_VER44 (LANG_CHT | MAKEIMEVERSION(4, 4)) #define IMEID_CHT_VER50 (LANG_CHT | MAKEIMEVERSION(5, 0)) #define IMEID_CHT_VER51 (LANG_CHT | MAKEIMEVERSION(5, 1)) #define IMEID_CHT_VER52 (LANG_CHT | MAKEIMEVERSION(5, 2)) #define IMEID_CHT_VER60 (LANG_CHT | MAKEIMEVERSION(6, 0)) #define IMEID_CHT_VER_VISTA (LANG_CHT | MAKEIMEVERSION(7, 0)) #define CHS_HKL ((HKL)(UINT_PTR)0xE00E0804) #define CHS_IMEFILENAME1 "PINTLGNT.IME" #define CHS_IMEFILENAME2 "MSSCIPYA.IME" #define IMEID_CHS_VER41 (LANG_CHS | MAKEIMEVERSION(4, 1)) #define IMEID_CHS_VER42 (LANG_CHS | MAKEIMEVERSION(4, 2)) #define IMEID_CHS_VER53 (LANG_CHS | MAKEIMEVERSION(5, 3)) #define LANG() LOWORD((videodata->ime_hkl)) #define PRIMLANG() ((WORD)PRIMARYLANGID(LANG())) #define SUBLANG() SUBLANGID(LANG()) static void IME_UpdateInputLocale(SDL_VideoData *videodata); static void IME_ClearComposition(SDL_VideoData *videodata); static void IME_SetWindow(SDL_VideoData* videodata, HWND hwnd); static void IME_SetupAPI(SDL_VideoData *videodata); static DWORD IME_GetId(SDL_VideoData *videodata, UINT uIndex); static void IME_SendEditingEvent(SDL_VideoData *videodata); static void IME_DestroyTextures(SDL_VideoData *videodata); static SDL_bool UILess_SetupSinks(SDL_VideoData *videodata); static void UILess_ReleaseSinks(SDL_VideoData *videodata); static void UILess_EnableUIUpdates(SDL_VideoData *videodata); static void UILess_DisableUIUpdates(SDL_VideoData *videodata); static void IME_Init(SDL_VideoData *videodata, HWND hwnd) { if (videodata->ime_initialized) return; videodata->ime_hwnd_main = hwnd; if (SUCCEEDED(WIN_CoInitialize())) { videodata->ime_com_initialized = SDL_TRUE; CoCreateInstance(&CLSID_TF_ThreadMgr, NULL, CLSCTX_INPROC_SERVER, &IID_ITfThreadMgr, (LPVOID *)&videodata->ime_threadmgr); } videodata->ime_initialized = SDL_TRUE; videodata->ime_himm32 = SDL_LoadObject("imm32.dll"); if (!videodata->ime_himm32) { videodata->ime_available = SDL_FALSE; SDL_ClearError(); return; } videodata->ImmLockIMC = (LPINPUTCONTEXT2 (WINAPI *)(HIMC))SDL_LoadFunction(videodata->ime_himm32, "ImmLockIMC"); videodata->ImmUnlockIMC = (BOOL (WINAPI *)(HIMC))SDL_LoadFunction(videodata->ime_himm32, "ImmUnlockIMC"); videodata->ImmLockIMCC = (LPVOID (WINAPI *)(HIMCC))SDL_LoadFunction(videodata->ime_himm32, "ImmLockIMCC"); videodata->ImmUnlockIMCC = (BOOL (WINAPI *)(HIMCC))SDL_LoadFunction(videodata->ime_himm32, "ImmUnlockIMCC"); IME_SetWindow(videodata, hwnd); videodata->ime_himc = ImmGetContext(hwnd); ImmReleaseContext(hwnd, videodata->ime_himc); if (!videodata->ime_himc) { videodata->ime_available = SDL_FALSE; IME_Disable(videodata, hwnd); return; } videodata->ime_available = SDL_TRUE; IME_UpdateInputLocale(videodata); IME_SetupAPI(videodata); videodata->ime_uiless = UILess_SetupSinks(videodata); IME_UpdateInputLocale(videodata); IME_Disable(videodata, hwnd); } static void IME_Enable(SDL_VideoData *videodata, HWND hwnd) { if (!videodata->ime_initialized || !videodata->ime_hwnd_current) return; if (!videodata->ime_available) { IME_Disable(videodata, hwnd); return; } if (videodata->ime_hwnd_current == videodata->ime_hwnd_main) ImmAssociateContext(videodata->ime_hwnd_current, videodata->ime_himc); videodata->ime_enabled = SDL_TRUE; IME_UpdateInputLocale(videodata); UILess_EnableUIUpdates(videodata); } static void IME_Disable(SDL_VideoData *videodata, HWND hwnd) { if (!videodata->ime_initialized || !videodata->ime_hwnd_current) return; IME_ClearComposition(videodata); if (videodata->ime_hwnd_current == videodata->ime_hwnd_main) ImmAssociateContext(videodata->ime_hwnd_current, (HIMC)0); videodata->ime_enabled = SDL_FALSE; UILess_DisableUIUpdates(videodata); } static void IME_Quit(SDL_VideoData *videodata) { if (!videodata->ime_initialized) return; UILess_ReleaseSinks(videodata); if (videodata->ime_hwnd_main) ImmAssociateContext(videodata->ime_hwnd_main, videodata->ime_himc); videodata->ime_hwnd_main = 0; videodata->ime_himc = 0; if (videodata->ime_himm32) { SDL_UnloadObject(videodata->ime_himm32); videodata->ime_himm32 = 0; } if (videodata->ime_threadmgr) { videodata->ime_threadmgr->lpVtbl->Release(videodata->ime_threadmgr); videodata->ime_threadmgr = 0; } if (videodata->ime_com_initialized) { WIN_CoUninitialize(); videodata->ime_com_initialized = SDL_FALSE; } IME_DestroyTextures(videodata); videodata->ime_initialized = SDL_FALSE; } static void IME_GetReadingString(SDL_VideoData *videodata, HWND hwnd) { DWORD id = 0; HIMC himc = 0; WCHAR buffer[16]; WCHAR *s = buffer; DWORD len = 0; INT err = 0; BOOL vertical = FALSE; UINT maxuilen = 0; if (videodata->ime_uiless) return; videodata->ime_readingstring[0] = 0; id = IME_GetId(videodata, 0); if (!id) return; himc = ImmGetContext(hwnd); if (!himc) return; if (videodata->GetReadingString) { len = videodata->GetReadingString(himc, 0, 0, &err, &vertical, &maxuilen); if (len) { if (len > SDL_arraysize(buffer)) len = SDL_arraysize(buffer); len = videodata->GetReadingString(himc, len, s, &err, &vertical, &maxuilen); } SDL_wcslcpy(videodata->ime_readingstring, s, len); } else { LPINPUTCONTEXT2 lpimc = videodata->ImmLockIMC(himc); LPBYTE p = 0; s = 0; switch (id) { case IMEID_CHT_VER42: case IMEID_CHT_VER43: case IMEID_CHT_VER44: p = *(LPBYTE *)((LPBYTE)videodata->ImmLockIMCC(lpimc->hPrivate) + 24); if (!p) break; len = *(DWORD *)(p + 7*4 + 32*4); s = (WCHAR *)(p + 56); break; case IMEID_CHT_VER51: case IMEID_CHT_VER52: case IMEID_CHS_VER53: p = *(LPBYTE *)((LPBYTE)videodata->ImmLockIMCC(lpimc->hPrivate) + 4); if (!p) break; p = *(LPBYTE *)((LPBYTE)p + 1*4 + 5*4); if (!p) break; len = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16*2); s = (WCHAR *)(p + 1*4 + (16*2+2*4) + 5*4); break; case IMEID_CHS_VER41: { int offset = (IME_GetId(videodata, 1) >= 0x00000002) ? 8 : 7; p = *(LPBYTE *)((LPBYTE)videodata->ImmLockIMCC(lpimc->hPrivate) + offset * 4); if (!p) break; len = *(DWORD *)(p + 7*4 + 16*2*4); s = (WCHAR *)(p + 6*4 + 16*2*1); } break; case IMEID_CHS_VER42: p = *(LPBYTE *)((LPBYTE)videodata->ImmLockIMCC(lpimc->hPrivate) + 1*4 + 1*4 + 6*4); if (!p) break; len = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16*2); s = (WCHAR *)(p + 1*4 + (16*2+2*4) + 5*4); break; } if (s) { size_t size = SDL_min((size_t)(len + 1), SDL_arraysize(videodata->ime_readingstring)); SDL_wcslcpy(videodata->ime_readingstring, s, size); } videodata->ImmUnlockIMCC(lpimc->hPrivate); videodata->ImmUnlockIMC(himc); } ImmReleaseContext(hwnd, himc); IME_SendEditingEvent(videodata); } static void IME_InputLangChanged(SDL_VideoData *videodata) { UINT lang = PRIMLANG(); IME_UpdateInputLocale(videodata); if (!videodata->ime_uiless) videodata->ime_candlistindexbase = (videodata->ime_hkl == CHT_HKL_DAYI) ? 0 : 1; IME_SetupAPI(videodata); if (lang != PRIMLANG()) { IME_ClearComposition(videodata); } } static DWORD IME_GetId(SDL_VideoData *videodata, UINT uIndex) { static HKL hklprev = 0; static DWORD dwRet[2] = {0}; DWORD dwVerSize = 0; DWORD dwVerHandle = 0; LPVOID lpVerBuffer = 0; LPVOID lpVerData = 0; UINT cbVerData = 0; char szTemp[256]; HKL hkl = 0; DWORD dwLang = 0; if (uIndex >= sizeof(dwRet) / sizeof(dwRet[0])) return 0; hkl = videodata->ime_hkl; if (hklprev == hkl) return dwRet[uIndex]; hklprev = hkl; dwLang = ((DWORD_PTR)hkl & 0xffff); if (videodata->ime_uiless && LANG() == LANG_CHT) { dwRet[0] = IMEID_CHT_VER_VISTA; dwRet[1] = 0; return dwRet[0]; } if (hkl != CHT_HKL_NEW_PHONETIC && hkl != CHT_HKL_NEW_CHANG_JIE && hkl != CHT_HKL_NEW_QUICK && hkl != CHT_HKL_HK_CANTONESE && hkl != CHS_HKL) { dwRet[0] = dwRet[1] = 0; return dwRet[uIndex]; } if (ImmGetIMEFileNameA(hkl, szTemp, sizeof(szTemp) - 1) <= 0) { dwRet[0] = dwRet[1] = 0; return dwRet[uIndex]; } if (!videodata->GetReadingString) { #define LCID_INVARIANT MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT) if (CompareStringA(LCID_INVARIANT, NORM_IGNORECASE, szTemp, -1, CHT_IMEFILENAME1, -1) != 2 && CompareStringA(LCID_INVARIANT, NORM_IGNORECASE, szTemp, -1, CHT_IMEFILENAME2, -1) != 2 && CompareStringA(LCID_INVARIANT, NORM_IGNORECASE, szTemp, -1, CHT_IMEFILENAME3, -1) != 2 && CompareStringA(LCID_INVARIANT, NORM_IGNORECASE, szTemp, -1, CHS_IMEFILENAME1, -1) != 2 && CompareStringA(LCID_INVARIANT, NORM_IGNORECASE, szTemp, -1, CHS_IMEFILENAME2, -1) != 2) { dwRet[0] = dwRet[1] = 0; return dwRet[uIndex]; } #undef LCID_INVARIANT dwVerSize = GetFileVersionInfoSizeA(szTemp, &dwVerHandle); if (dwVerSize) { lpVerBuffer = SDL_malloc(dwVerSize); if (lpVerBuffer) { if (GetFileVersionInfoA(szTemp, dwVerHandle, dwVerSize, lpVerBuffer)) { if (VerQueryValueA(lpVerBuffer, "\\", &lpVerData, &cbVerData)) { #define pVerFixedInfo ((VS_FIXEDFILEINFO FAR*)lpVerData) DWORD dwVer = pVerFixedInfo->dwFileVersionMS; dwVer = (dwVer & 0x00ff0000) << 8 | (dwVer & 0x000000ff) << 16; if ((videodata->GetReadingString) || ((dwLang == LANG_CHT) && ( dwVer == MAKEIMEVERSION(4, 2) || dwVer == MAKEIMEVERSION(4, 3) || dwVer == MAKEIMEVERSION(4, 4) || dwVer == MAKEIMEVERSION(5, 0) || dwVer == MAKEIMEVERSION(5, 1) || dwVer == MAKEIMEVERSION(5, 2) || dwVer == MAKEIMEVERSION(6, 0))) || ((dwLang == LANG_CHS) && ( dwVer == MAKEIMEVERSION(4, 1) || dwVer == MAKEIMEVERSION(4, 2) || dwVer == MAKEIMEVERSION(5, 3)))) { dwRet[0] = dwVer | dwLang; dwRet[1] = pVerFixedInfo->dwFileVersionLS; SDL_free(lpVerBuffer); return dwRet[0]; } #undef pVerFixedInfo } } } SDL_free(lpVerBuffer); } } dwRet[0] = dwRet[1] = 0; return dwRet[uIndex]; } static void IME_SetupAPI(SDL_VideoData *videodata) { char ime_file[MAX_PATH + 1]; void* hime = 0; HKL hkl = 0; videodata->GetReadingString = 0; videodata->ShowReadingWindow = 0; if (videodata->ime_uiless) return; hkl = videodata->ime_hkl; if (ImmGetIMEFileNameA(hkl, ime_file, sizeof(ime_file) - 1) <= 0) return; hime = SDL_LoadObject(ime_file); if (!hime) return; videodata->GetReadingString = (UINT (WINAPI *)(HIMC, UINT, LPWSTR, PINT, BOOL*, PUINT)) SDL_LoadFunction(hime, "GetReadingString"); videodata->ShowReadingWindow = (BOOL (WINAPI *)(HIMC, BOOL)) SDL_LoadFunction(hime, "ShowReadingWindow"); if (videodata->ShowReadingWindow) { HIMC himc = ImmGetContext(videodata->ime_hwnd_current); if (himc) { videodata->ShowReadingWindow(himc, FALSE); ImmReleaseContext(videodata->ime_hwnd_current, himc); } } } static void IME_SetWindow(SDL_VideoData* videodata, HWND hwnd) { videodata->ime_hwnd_current = hwnd; if (videodata->ime_threadmgr) { struct ITfDocumentMgr *document_mgr = 0; if (SUCCEEDED(videodata->ime_threadmgr->lpVtbl->AssociateFocus(videodata->ime_threadmgr, hwnd, NULL, &document_mgr))) { if (document_mgr) document_mgr->lpVtbl->Release(document_mgr); } } } static void IME_UpdateInputLocale(SDL_VideoData *videodata) { static HKL hklprev = 0; videodata->ime_hkl = GetKeyboardLayout(0); if (hklprev == videodata->ime_hkl) return; hklprev = videodata->ime_hkl; switch (PRIMLANG()) { case LANG_CHINESE: videodata->ime_candvertical = SDL_TRUE; if (SUBLANG() == SUBLANG_CHINESE_SIMPLIFIED) videodata->ime_candvertical = SDL_FALSE; break; case LANG_JAPANESE: videodata->ime_candvertical = SDL_TRUE; break; case LANG_KOREAN: videodata->ime_candvertical = SDL_FALSE; break; } } static void IME_ClearComposition(SDL_VideoData *videodata) { HIMC himc = 0; if (!videodata->ime_initialized) return; himc = ImmGetContext(videodata->ime_hwnd_current); if (!himc) return; ImmNotifyIME(himc, NI_COMPOSITIONSTR, CPS_CANCEL, 0); if (videodata->ime_uiless) ImmSetCompositionString(himc, SCS_SETSTR, TEXT(""), sizeof(TCHAR), TEXT(""), sizeof(TCHAR)); ImmNotifyIME(himc, NI_CLOSECANDIDATE, 0, 0); ImmReleaseContext(videodata->ime_hwnd_current, himc); SDL_SendEditingText("", 0, 0); } static void IME_GetCompositionString(SDL_VideoData *videodata, HIMC himc, DWORD string) { LONG length = ImmGetCompositionStringW(himc, string, videodata->ime_composition, sizeof(videodata->ime_composition) - sizeof(videodata->ime_composition[0])); if (length < 0) length = 0; length /= sizeof(videodata->ime_composition[0]); videodata->ime_cursor = LOWORD(ImmGetCompositionStringW(himc, GCS_CURSORPOS, 0, 0)); if (videodata->ime_cursor < SDL_arraysize(videodata->ime_composition) && videodata->ime_composition[videodata->ime_cursor] == 0x3000) { int i; for (i = videodata->ime_cursor + 1; i < length; ++i) videodata->ime_composition[i - 1] = videodata->ime_composition[i]; --length; } videodata->ime_composition[length] = 0; } static void IME_SendInputEvent(SDL_VideoData *videodata) { char *s = 0; s = WIN_StringToUTF8(videodata->ime_composition); SDL_SendKeyboardText(s); SDL_free(s); videodata->ime_composition[0] = 0; videodata->ime_readingstring[0] = 0; videodata->ime_cursor = 0; } static void IME_SendEditingEvent(SDL_VideoData *videodata) { char *s = 0; WCHAR buffer[SDL_TEXTEDITINGEVENT_TEXT_SIZE]; const size_t size = SDL_arraysize(buffer); buffer[0] = 0; if (videodata->ime_readingstring[0]) { size_t len = SDL_min(SDL_wcslen(videodata->ime_composition), (size_t)videodata->ime_cursor); SDL_wcslcpy(buffer, videodata->ime_composition, len + 1); SDL_wcslcat(buffer, videodata->ime_readingstring, size); SDL_wcslcat(buffer, &videodata->ime_composition[len], size); } else { SDL_wcslcpy(buffer, videodata->ime_composition, size); } s = WIN_StringToUTF8(buffer); SDL_SendEditingText(s, videodata->ime_cursor + (int)SDL_wcslen(videodata->ime_readingstring), 0); SDL_free(s); } static void IME_AddCandidate(SDL_VideoData *videodata, UINT i, LPCWSTR candidate) { LPWSTR dst = videodata->ime_candidates[i]; *dst++ = (WCHAR)(TEXT('0') + ((i + videodata->ime_candlistindexbase) % 10)); if (videodata->ime_candvertical) *dst++ = TEXT(' '); while (*candidate && (SDL_arraysize(videodata->ime_candidates[i]) > (dst - videodata->ime_candidates[i]))) *dst++ = *candidate++; *dst = (WCHAR)'\0'; } static void IME_GetCandidateList(HIMC himc, SDL_VideoData *videodata) { LPCANDIDATELIST cand_list = 0; DWORD size = ImmGetCandidateListW(himc, 0, 0, 0); if (size) { cand_list = (LPCANDIDATELIST)SDL_malloc(size); if (cand_list) { size = ImmGetCandidateListW(himc, 0, cand_list, size); if (size) { UINT i, j; UINT page_start = 0; videodata->ime_candsel = cand_list->dwSelection; videodata->ime_candcount = cand_list->dwCount; if (LANG() == LANG_CHS && IME_GetId(videodata, 0)) { const UINT maxcandchar = 18; size_t cchars = 0; for (i = 0; i < videodata->ime_candcount; ++i) { size_t len = SDL_wcslen((LPWSTR)((DWORD_PTR)cand_list + cand_list->dwOffset[i])) + 1; if (len + cchars > maxcandchar) { if (i > cand_list->dwSelection) break; page_start = i; cchars = len; } else { cchars += len; } } videodata->ime_candpgsize = i - page_start; } else { videodata->ime_candpgsize = SDL_min(cand_list->dwPageSize, MAX_CANDLIST); if (videodata->ime_candpgsize > 0) { page_start = (cand_list->dwSelection / videodata->ime_candpgsize) * videodata->ime_candpgsize; } else { page_start = 0; } } SDL_memset(&videodata->ime_candidates, 0, sizeof(videodata->ime_candidates)); for (i = page_start, j = 0; (DWORD)i < cand_list->dwCount && j < (int)videodata->ime_candpgsize; i++, j++) { LPCWSTR candidate = (LPCWSTR)((DWORD_PTR)cand_list + cand_list->dwOffset[i]); IME_AddCandidate(videodata, j, candidate); } if (PRIMLANG() == LANG_KOREAN || (PRIMLANG() == LANG_CHT && !IME_GetId(videodata, 0))) videodata->ime_candsel = -1; } SDL_free(cand_list); } } } static void IME_ShowCandidateList(SDL_VideoData *videodata) { videodata->ime_dirty = SDL_TRUE; videodata->ime_candlist = SDL_TRUE; IME_DestroyTextures(videodata); IME_SendEditingEvent(videodata); } static void IME_HideCandidateList(SDL_VideoData *videodata) { videodata->ime_dirty = SDL_FALSE; videodata->ime_candlist = SDL_FALSE; IME_DestroyTextures(videodata); IME_SendEditingEvent(videodata); } SDL_bool IME_HandleMessage(HWND hwnd, UINT msg, WPARAM wParam, LPARAM *lParam, SDL_VideoData *videodata) { SDL_bool trap = SDL_FALSE; HIMC himc = 0; if (!videodata->ime_initialized || !videodata->ime_available || !videodata->ime_enabled) return SDL_FALSE; switch (msg) { case WM_INPUTLANGCHANGE: IME_InputLangChanged(videodata); break; case WM_IME_SETCONTEXT: *lParam = 0; break; case WM_IME_STARTCOMPOSITION: trap = SDL_TRUE; break; case WM_IME_COMPOSITION: trap = SDL_TRUE; himc = ImmGetContext(hwnd); if (*lParam & GCS_RESULTSTR) { IME_GetCompositionString(videodata, himc, GCS_RESULTSTR); IME_SendInputEvent(videodata); } if (*lParam & GCS_COMPSTR) { if (!videodata->ime_uiless) videodata->ime_readingstring[0] = 0; IME_GetCompositionString(videodata, himc, GCS_COMPSTR); IME_SendEditingEvent(videodata); } ImmReleaseContext(hwnd, himc); break; case WM_IME_ENDCOMPOSITION: videodata->ime_composition[0] = 0; videodata->ime_readingstring[0] = 0; videodata->ime_cursor = 0; SDL_SendEditingText("", 0, 0); break; case WM_IME_NOTIFY: switch (wParam) { case IMN_SETCONVERSIONMODE: case IMN_SETOPENSTATUS: IME_UpdateInputLocale(videodata); break; case IMN_OPENCANDIDATE: case IMN_CHANGECANDIDATE: if (videodata->ime_uiless) break; trap = SDL_TRUE; IME_ShowCandidateList(videodata); himc = ImmGetContext(hwnd); if (!himc) break; IME_GetCandidateList(himc, videodata); ImmReleaseContext(hwnd, himc); break; case IMN_CLOSECANDIDATE: trap = SDL_TRUE; IME_HideCandidateList(videodata); break; case IMN_PRIVATE: { DWORD dwId = IME_GetId(videodata, 0); IME_GetReadingString(videodata, hwnd); switch (dwId) { case IMEID_CHT_VER42: case IMEID_CHT_VER43: case IMEID_CHT_VER44: case IMEID_CHS_VER41: case IMEID_CHS_VER42: if (*lParam == 1 || *lParam == 2) trap = SDL_TRUE; break; case IMEID_CHT_VER50: case IMEID_CHT_VER51: case IMEID_CHT_VER52: case IMEID_CHT_VER60: case IMEID_CHS_VER53: if (*lParam == 16 || *lParam == 17 || *lParam == 26 || *lParam == 27 || *lParam == 28) trap = SDL_TRUE; break; } } break; default: trap = SDL_TRUE; break; } break; } return trap; } static void IME_CloseCandidateList(SDL_VideoData *videodata) { IME_HideCandidateList(videodata); videodata->ime_candcount = 0; SDL_memset(videodata->ime_candidates, 0, sizeof(videodata->ime_candidates)); } static void UILess_GetCandidateList(SDL_VideoData *videodata, ITfCandidateListUIElement *pcandlist) { UINT selection = 0; UINT count = 0; UINT page = 0; UINT pgcount = 0; DWORD pgstart = 0; DWORD pgsize = 0; UINT i, j; pcandlist->lpVtbl->GetSelection(pcandlist, &selection); pcandlist->lpVtbl->GetCount(pcandlist, &count); pcandlist->lpVtbl->GetCurrentPage(pcandlist, &page); videodata->ime_candsel = selection; videodata->ime_candcount = count; IME_ShowCandidateList(videodata); pcandlist->lpVtbl->GetPageIndex(pcandlist, 0, 0, &pgcount); if (pgcount > 0) { UINT *idxlist = SDL_malloc(sizeof(UINT) * pgcount); if (idxlist) { pcandlist->lpVtbl->GetPageIndex(pcandlist, idxlist, pgcount, &pgcount); pgstart = idxlist[page]; if (page < pgcount - 1) pgsize = SDL_min(count, idxlist[page + 1]) - pgstart; else pgsize = count - pgstart; SDL_free(idxlist); } } videodata->ime_candpgsize = SDL_min(pgsize, MAX_CANDLIST); videodata->ime_candsel = videodata->ime_candsel - pgstart; SDL_memset(videodata->ime_candidates, 0, sizeof(videodata->ime_candidates)); for (i = pgstart, j = 0; (DWORD)i < count && j < videodata->ime_candpgsize; i++, j++) { BSTR bstr; if (SUCCEEDED(pcandlist->lpVtbl->GetString(pcandlist, i, &bstr))) { if (bstr) { IME_AddCandidate(videodata, j, bstr); SysFreeString(bstr); } } } if (PRIMLANG() == LANG_KOREAN) videodata->ime_candsel = -1; } STDMETHODIMP_(ULONG) TSFSink_AddRef(TSFSink *sink) { return ++sink->refcount; } STDMETHODIMP_(ULONG) TSFSink_Release(TSFSink *sink) { --sink->refcount; if (sink->refcount == 0) { SDL_free(sink); return 0; } return sink->refcount; } STDMETHODIMP UIElementSink_QueryInterface(TSFSink *sink, REFIID riid, PVOID *ppv) { if (!ppv) return E_INVALIDARG; *ppv = 0; if (WIN_IsEqualIID(riid, &IID_IUnknown)) *ppv = (IUnknown *)sink; else if (WIN_IsEqualIID(riid, &IID_ITfUIElementSink)) *ppv = (ITfUIElementSink *)sink; if (*ppv) { TSFSink_AddRef(sink); return S_OK; } return E_NOINTERFACE; } ITfUIElement *UILess_GetUIElement(SDL_VideoData *videodata, DWORD dwUIElementId) { ITfUIElementMgr *puiem = 0; ITfUIElement *pelem = 0; ITfThreadMgrEx *threadmgrex = videodata->ime_threadmgrex; if (SUCCEEDED(threadmgrex->lpVtbl->QueryInterface(threadmgrex, &IID_ITfUIElementMgr, (LPVOID *)&puiem))) { puiem->lpVtbl->GetUIElement(puiem, dwUIElementId, &pelem); puiem->lpVtbl->Release(puiem); } return pelem; } STDMETHODIMP UIElementSink_BeginUIElement(TSFSink *sink, DWORD dwUIElementId, BOOL *pbShow) { ITfUIElement *element = UILess_GetUIElement((SDL_VideoData *)sink->data, dwUIElementId); ITfReadingInformationUIElement *preading = 0; ITfCandidateListUIElement *pcandlist = 0; SDL_VideoData *videodata = (SDL_VideoData *)sink->data; if (!element) return E_INVALIDARG; *pbShow = FALSE; if (SUCCEEDED(element->lpVtbl->QueryInterface(element, &IID_ITfReadingInformationUIElement, (LPVOID *)&preading))) { BSTR bstr; if (SUCCEEDED(preading->lpVtbl->GetString(preading, &bstr)) && bstr) { SysFreeString(bstr); } preading->lpVtbl->Release(preading); } else if (SUCCEEDED(element->lpVtbl->QueryInterface(element, &IID_ITfCandidateListUIElement, (LPVOID *)&pcandlist))) { videodata->ime_candref++; UILess_GetCandidateList(videodata, pcandlist); pcandlist->lpVtbl->Release(pcandlist); } return S_OK; } STDMETHODIMP UIElementSink_UpdateUIElement(TSFSink *sink, DWORD dwUIElementId) { ITfUIElement *element = UILess_GetUIElement((SDL_VideoData *)sink->data, dwUIElementId); ITfReadingInformationUIElement *preading = 0; ITfCandidateListUIElement *pcandlist = 0; SDL_VideoData *videodata = (SDL_VideoData *)sink->data; if (!element) return E_INVALIDARG; if (SUCCEEDED(element->lpVtbl->QueryInterface(element, &IID_ITfReadingInformationUIElement, (LPVOID *)&preading))) { BSTR bstr; if (SUCCEEDED(preading->lpVtbl->GetString(preading, &bstr)) && bstr) { WCHAR *s = (WCHAR *)bstr; SDL_wcslcpy(videodata->ime_readingstring, s, SDL_arraysize(videodata->ime_readingstring)); IME_SendEditingEvent(videodata); SysFreeString(bstr); } preading->lpVtbl->Release(preading); } else if (SUCCEEDED(element->lpVtbl->QueryInterface(element, &IID_ITfCandidateListUIElement, (LPVOID *)&pcandlist))) { UILess_GetCandidateList(videodata, pcandlist); pcandlist->lpVtbl->Release(pcandlist); } return S_OK; } STDMETHODIMP UIElementSink_EndUIElement(TSFSink *sink, DWORD dwUIElementId) { ITfUIElement *element = UILess_GetUIElement((SDL_VideoData *)sink->data, dwUIElementId); ITfReadingInformationUIElement *preading = 0; ITfCandidateListUIElement *pcandlist = 0; SDL_VideoData *videodata = (SDL_VideoData *)sink->data; if (!element) return E_INVALIDARG; if (SUCCEEDED(element->lpVtbl->QueryInterface(element, &IID_ITfReadingInformationUIElement, (LPVOID *)&preading))) { videodata->ime_readingstring[0] = 0; IME_SendEditingEvent(videodata); preading->lpVtbl->Release(preading); } if (SUCCEEDED(element->lpVtbl->QueryInterface(element, &IID_ITfCandidateListUIElement, (LPVOID *)&pcandlist))) { videodata->ime_candref--; if (videodata->ime_candref == 0) IME_CloseCandidateList(videodata); pcandlist->lpVtbl->Release(pcandlist); } return S_OK; } STDMETHODIMP IPPASink_QueryInterface(TSFSink *sink, REFIID riid, PVOID *ppv) { if (!ppv) return E_INVALIDARG; *ppv = 0; if (WIN_IsEqualIID(riid, &IID_IUnknown)) *ppv = (IUnknown *)sink; else if (WIN_IsEqualIID(riid, &IID_ITfInputProcessorProfileActivationSink)) *ppv = (ITfInputProcessorProfileActivationSink *)sink; if (*ppv) { TSFSink_AddRef(sink); return S_OK; } return E_NOINTERFACE; } STDMETHODIMP IPPASink_OnActivated(TSFSink *sink, DWORD dwProfileType, LANGID langid, REFCLSID clsid, REFGUID catid, REFGUID guidProfile, HKL hkl, DWORD dwFlags) { static const GUID TF_PROFILE_DAYI = { 0x037B2C25, 0x480C, 0x4D7F, { 0xB0, 0x27, 0xD6, 0xCA, 0x6B, 0x69, 0x78, 0x8A } }; SDL_VideoData *videodata = (SDL_VideoData *)sink->data; videodata->ime_candlistindexbase = WIN_IsEqualGUID(&TF_PROFILE_DAYI, guidProfile) ? 0 : 1; if (WIN_IsEqualIID(catid, &GUID_TFCAT_TIP_KEYBOARD) && (dwFlags & TF_IPSINK_FLAG_ACTIVE)) IME_InputLangChanged((SDL_VideoData *)sink->data); IME_HideCandidateList(videodata); return S_OK; } static void *vtUIElementSink[] = { (void *)(UIElementSink_QueryInterface), (void *)(TSFSink_AddRef), (void *)(TSFSink_Release), (void *)(UIElementSink_BeginUIElement), (void *)(UIElementSink_UpdateUIElement), (void *)(UIElementSink_EndUIElement) }; static void *vtIPPASink[] = { (void *)(IPPASink_QueryInterface), (void *)(TSFSink_AddRef), (void *)(TSFSink_Release), (void *)(IPPASink_OnActivated) }; static void UILess_EnableUIUpdates(SDL_VideoData *videodata) { ITfSource *source = 0; if (!videodata->ime_threadmgrex || videodata->ime_uielemsinkcookie != TF_INVALID_COOKIE) return; if (SUCCEEDED(videodata->ime_threadmgrex->lpVtbl->QueryInterface(videodata->ime_threadmgrex, &IID_ITfSource, (LPVOID *)&source))) { source->lpVtbl->AdviseSink(source, &IID_ITfUIElementSink, (IUnknown *)videodata->ime_uielemsink, &videodata->ime_uielemsinkcookie); source->lpVtbl->Release(source); } } static void UILess_DisableUIUpdates(SDL_VideoData *videodata) { ITfSource *source = 0; if (!videodata->ime_threadmgrex || videodata->ime_uielemsinkcookie == TF_INVALID_COOKIE) return; if (SUCCEEDED(videodata->ime_threadmgrex->lpVtbl->QueryInterface(videodata->ime_threadmgrex, &IID_ITfSource, (LPVOID *)&source))) { source->lpVtbl->UnadviseSink(source, videodata->ime_uielemsinkcookie); videodata->ime_uielemsinkcookie = TF_INVALID_COOKIE; source->lpVtbl->Release(source); } } static SDL_bool UILess_SetupSinks(SDL_VideoData *videodata) { TfClientId clientid = 0; SDL_bool result = SDL_FALSE; ITfSource *source = 0; if (FAILED(CoCreateInstance(&CLSID_TF_ThreadMgr, NULL, CLSCTX_INPROC_SERVER, &IID_ITfThreadMgrEx, (LPVOID *)&videodata->ime_threadmgrex))) return SDL_FALSE; if (FAILED(videodata->ime_threadmgrex->lpVtbl->ActivateEx(videodata->ime_threadmgrex, &clientid, TF_TMAE_UIELEMENTENABLEDONLY))) return SDL_FALSE; videodata->ime_uielemsink = SDL_malloc(sizeof(TSFSink)); videodata->ime_ippasink = SDL_malloc(sizeof(TSFSink)); videodata->ime_uielemsink->lpVtbl = vtUIElementSink; videodata->ime_uielemsink->refcount = 1; videodata->ime_uielemsink->data = videodata; videodata->ime_ippasink->lpVtbl = vtIPPASink; videodata->ime_ippasink->refcount = 1; videodata->ime_ippasink->data = videodata; if (SUCCEEDED(videodata->ime_threadmgrex->lpVtbl->QueryInterface(videodata->ime_threadmgrex, &IID_ITfSource, (LPVOID *)&source))) { if (SUCCEEDED(source->lpVtbl->AdviseSink(source, &IID_ITfUIElementSink, (IUnknown *)videodata->ime_uielemsink, &videodata->ime_uielemsinkcookie))) { if (SUCCEEDED(source->lpVtbl->AdviseSink(source, &IID_ITfInputProcessorProfileActivationSink, (IUnknown *)videodata->ime_ippasink, &videodata->ime_alpnsinkcookie))) { result = SDL_TRUE; } } source->lpVtbl->Release(source); } return result; } #define SAFE_RELEASE(p) \ { \ if (p) { \ (p)->lpVtbl->Release((p)); \ (p) = 0; \ } \ } static void UILess_ReleaseSinks(SDL_VideoData *videodata) { ITfSource *source = 0; if (videodata->ime_threadmgrex && SUCCEEDED(videodata->ime_threadmgrex->lpVtbl->QueryInterface(videodata->ime_threadmgrex, &IID_ITfSource, (LPVOID *)&source))) { source->lpVtbl->UnadviseSink(source, videodata->ime_uielemsinkcookie); source->lpVtbl->UnadviseSink(source, videodata->ime_alpnsinkcookie); SAFE_RELEASE(source); videodata->ime_threadmgrex->lpVtbl->Deactivate(videodata->ime_threadmgrex); SAFE_RELEASE(videodata->ime_threadmgrex); TSFSink_Release(videodata->ime_uielemsink); videodata->ime_uielemsink = 0; TSFSink_Release(videodata->ime_ippasink); videodata->ime_ippasink = 0; } } static void * StartDrawToBitmap(HDC hdc, HBITMAP *hhbm, int width, int height) { BITMAPINFO info; BITMAPINFOHEADER *infoHeader = &info.bmiHeader; BYTE *bits = NULL; if (hhbm) { SDL_zero(info); infoHeader->biSize = sizeof(BITMAPINFOHEADER); infoHeader->biWidth = width; infoHeader->biHeight = -1 * SDL_abs(height); infoHeader->biPlanes = 1; infoHeader->biBitCount = 32; infoHeader->biCompression = BI_RGB; *hhbm = CreateDIBSection(hdc, &info, DIB_RGB_COLORS, (void **)&bits, 0, 0); if (*hhbm) SelectObject(hdc, *hhbm); } return bits; } static void StopDrawToBitmap(HDC hdc, HBITMAP *hhbm) { if (hhbm && *hhbm) { DeleteObject(*hhbm); *hhbm = NULL; } } /* This draws only within the specified area and fills the entire region. */ static void DrawRect(HDC hdc, int left, int top, int right, int bottom, int pensize) { /* The case of no pen (PenSize = 0) is automatically taken care of. */ const int penadjust = (int)SDL_floor(pensize / 2.0f - 0.5f); left += pensize / 2; top += pensize / 2; right -= penadjust; bottom -= penadjust; Rectangle(hdc, left, top, right, bottom); } static void IME_DestroyTextures(SDL_VideoData *videodata) { } #define SDL_swap(a,b) { \ int c = (a); \ (a) = (b); \ (b) = c; \ } static void IME_PositionCandidateList(SDL_VideoData *videodata, SIZE size) { int left, top, right, bottom; SDL_bool ok = SDL_FALSE; int winw = videodata->ime_winwidth; int winh = videodata->ime_winheight; /* Bottom */ left = videodata->ime_rect.x; top = videodata->ime_rect.y + videodata->ime_rect.h; right = left + size.cx; bottom = top + size.cy; if (right >= winw) { left -= right - winw; right = winw; } if (bottom < winh) ok = SDL_TRUE; /* Top */ if (!ok) { left = videodata->ime_rect.x; top = videodata->ime_rect.y - size.cy; right = left + size.cx; bottom = videodata->ime_rect.y; if (right >= winw) { left -= right - winw; right = winw; } if (top >= 0) ok = SDL_TRUE; } /* Right */ if (!ok) { left = videodata->ime_rect.x + size.cx; top = 0; right = left + size.cx; bottom = size.cy; if (right < winw) ok = SDL_TRUE; } /* Left */ if (!ok) { left = videodata->ime_rect.x - size.cx; top = 0; right = videodata->ime_rect.x; bottom = size.cy; if (right >= 0) ok = SDL_TRUE; } /* Window too small, show at (0,0) */ if (!ok) { left = 0; top = 0; right = size.cx; bottom = size.cy; } videodata->ime_candlistrect.x = left; videodata->ime_candlistrect.y = top; videodata->ime_candlistrect.w = right - left; videodata->ime_candlistrect.h = bottom - top; } static void IME_RenderCandidateList(SDL_VideoData *videodata, HDC hdc) { int i, j; SIZE size = {0}; SIZE candsizes[MAX_CANDLIST]; SIZE maxcandsize = {0}; HBITMAP hbm = NULL; const int candcount = SDL_min(SDL_min(MAX_CANDLIST, videodata->ime_candcount), videodata->ime_candpgsize); SDL_bool vertical = videodata->ime_candvertical; const int listborder = 1; const int listpadding = 0; const int listbordercolor = RGB(0xB4, 0xC7, 0xAA); const int listfillcolor = RGB(255, 255, 255); const int candborder = 1; const int candpadding = 0; const int candmargin = 1; const COLORREF candbordercolor = RGB(255, 255, 255); const COLORREF candfillcolor = RGB(255, 255, 255); const COLORREF candtextcolor = RGB(0, 0, 0); const COLORREF selbordercolor = RGB(0x84, 0xAC, 0xDD); const COLORREF selfillcolor = RGB(0xD2, 0xE6, 0xFF); const COLORREF seltextcolor = RGB(0, 0, 0); const int horzcandspacing = 5; HPEN listpen = listborder != 0 ? CreatePen(PS_SOLID, listborder, listbordercolor) : (HPEN)GetStockObject(NULL_PEN); HBRUSH listbrush = CreateSolidBrush(listfillcolor); HPEN candpen = candborder != 0 ? CreatePen(PS_SOLID, candborder, candbordercolor) : (HPEN)GetStockObject(NULL_PEN); HBRUSH candbrush = CreateSolidBrush(candfillcolor); HPEN selpen = candborder != 0 ? CreatePen(PS_DOT, candborder, selbordercolor) : (HPEN)GetStockObject(NULL_PEN); HBRUSH selbrush = CreateSolidBrush(selfillcolor); HFONT font = CreateFont((int)(1 + videodata->ime_rect.h * 0.75f), 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_CHARACTER_PRECIS, CLIP_DEFAULT_PRECIS, PROOF_QUALITY, VARIABLE_PITCH | FF_SWISS, TEXT("Microsoft Sans Serif")); SetBkMode(hdc, TRANSPARENT); SelectObject(hdc, font); for (i = 0; i < candcount; ++i) { const WCHAR *s = videodata->ime_candidates[i]; if (!*s) break; GetTextExtentPoint32W(hdc, s, (int)SDL_wcslen(s), &candsizes[i]); maxcandsize.cx = SDL_max(maxcandsize.cx, candsizes[i].cx); maxcandsize.cy = SDL_max(maxcandsize.cy, candsizes[i].cy); } if (vertical) { size.cx = (listborder * 2) + (listpadding * 2) + (candmargin * 2) + (candborder * 2) + (candpadding * 2) + (maxcandsize.cx) ; size.cy = (listborder * 2) + (listpadding * 2) + ((candcount + 1) * candmargin) + (candcount * candborder * 2) + (candcount * candpadding * 2) + (candcount * maxcandsize.cy) ; } else { size.cx = (listborder * 2) + (listpadding * 2) + ((candcount + 1) * candmargin) + (candcount * candborder * 2) + (candcount * candpadding * 2) + ((candcount - 1) * horzcandspacing); ; for (i = 0; i < candcount; ++i) size.cx += candsizes[i].cx; size.cy = (listborder * 2) + (listpadding * 2) + (candmargin * 2) + (candborder * 2) + (candpadding * 2) + (maxcandsize.cy) ; } StartDrawToBitmap(hdc, &hbm, size.cx, size.cy); SelectObject(hdc, listpen); SelectObject(hdc, listbrush); DrawRect(hdc, 0, 0, size.cx, size.cy, listborder); SelectObject(hdc, candpen); SelectObject(hdc, candbrush); SetTextColor(hdc, candtextcolor); SetBkMode(hdc, TRANSPARENT); for (i = 0; i < candcount; ++i) { const WCHAR *s = videodata->ime_candidates[i]; int left, top, right, bottom; if (!*s) break; if (vertical) { left = listborder + listpadding + candmargin; top = listborder + listpadding + (i * candborder * 2) + (i * candpadding * 2) + ((i + 1) * candmargin) + (i * maxcandsize.cy); right = size.cx - listborder - listpadding - candmargin; bottom = top + maxcandsize.cy + (candpadding * 2) + (candborder * 2); } else { left = listborder + listpadding + (i * candborder * 2) + (i * candpadding * 2) + ((i + 1) * candmargin) + (i * horzcandspacing); for (j = 0; j < i; ++j) left += candsizes[j].cx; top = listborder + listpadding + candmargin; right = left + candsizes[i].cx + (candpadding * 2) + (candborder * 2); bottom = size.cy - listborder - listpadding - candmargin; } if (i == videodata->ime_candsel) { SelectObject(hdc, selpen); SelectObject(hdc, selbrush); SetTextColor(hdc, seltextcolor); } else { SelectObject(hdc, candpen); SelectObject(hdc, candbrush); SetTextColor(hdc, candtextcolor); } DrawRect(hdc, left, top, right, bottom, candborder); ExtTextOutW(hdc, left + candborder + candpadding, top + candborder + candpadding, 0, NULL, s, (int)SDL_wcslen(s), NULL); } StopDrawToBitmap(hdc, &hbm); DeleteObject(listpen); DeleteObject(listbrush); DeleteObject(candpen); DeleteObject(candbrush); DeleteObject(selpen); DeleteObject(selbrush); DeleteObject(font); IME_PositionCandidateList(videodata, size); } static void IME_Render(SDL_VideoData *videodata) { HDC hdc = CreateCompatibleDC(NULL); if (videodata->ime_candlist) IME_RenderCandidateList(videodata, hdc); DeleteDC(hdc); videodata->ime_dirty = SDL_FALSE; } void IME_Present(SDL_VideoData *videodata) { if (videodata->ime_dirty) IME_Render(videodata); /* FIXME: Need to show the IME bitmap */ } #endif /* SDL_DISABLE_WINDOWS_IME */ #endif /* SDL_VIDEO_DRIVER_WINDOWS */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowskeyboard.c
C
apache-2.0
53,027
/* 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_windowskeyboard_h_ #define SDL_windowskeyboard_h_ extern void WIN_InitKeyboard(_THIS); extern void WIN_UpdateKeymap(void); extern void WIN_QuitKeyboard(_THIS); extern void WIN_ResetDeadKeys(void); extern void WIN_StartTextInput(_THIS); extern void WIN_StopTextInput(_THIS); extern void WIN_SetTextInputRect(_THIS, SDL_Rect *rect); extern SDL_bool IME_HandleMessage(HWND hwnd, UINT msg, WPARAM wParam, LPARAM *lParam, struct SDL_VideoData *videodata); #endif /* SDL_windowskeyboard_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowskeyboard.h
C
apache-2.0
1,512
/* 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_VIDEO_DRIVER_WINDOWS #ifdef HAVE_LIMITS_H #include <limits.h> #else #ifndef SIZE_MAX #define SIZE_MAX ((size_t)-1) #endif #endif #include "../../core/windows/SDL_windows.h" #include "SDL_assert.h" #include "SDL_windowsvideo.h" #include "SDL_windowstaskdialog.h" #ifndef SS_EDITCONTROL #define SS_EDITCONTROL 0x2000 #endif #ifndef IDOK #define IDOK 1 #endif #ifndef IDCANCEL #define IDCANCEL 2 #endif /* Custom dialog return codes */ #define IDCLOSED 20 #define IDINVALPTRINIT 50 #define IDINVALPTRCOMMAND 51 #define IDINVALPTRSETFOCUS 52 #define IDINVALPTRDLGITEM 53 /* First button ID */ #define IDBUTTONINDEX0 100 #define DLGITEMTYPEBUTTON 0x0080 #define DLGITEMTYPESTATIC 0x0082 /* Windows only sends the lower 16 bits of the control ID when a button * gets clicked. There are also some predefined and custom IDs that lower * the available number further. 2^16 - 101 buttons should be enough for * everyone, no need to make the code more complex. */ #define MAX_BUTTONS (0xffff - 100) /* Display a Windows message box */ #pragma pack(push, 1) typedef struct { WORD dlgVer; WORD signature; DWORD helpID; DWORD exStyle; DWORD style; WORD cDlgItems; short x; short y; short cx; short cy; } DLGTEMPLATEEX; typedef struct { DWORD helpID; DWORD exStyle; DWORD style; short x; short y; short cx; short cy; DWORD id; } DLGITEMTEMPLATEEX; #pragma pack(pop) typedef struct { DLGTEMPLATEEX* lpDialog; Uint8 *data; size_t size; size_t used; WORD numbuttons; } WIN_DialogData; static SDL_bool GetButtonIndex(const SDL_MessageBoxData *messageboxdata, Uint32 flags, size_t *i) { for (*i = 0; *i < (size_t)messageboxdata->numbuttons; ++*i) { if (messageboxdata->buttons[*i].flags & flags) { return SDL_TRUE; } } return SDL_FALSE; } static INT_PTR MessageBoxDialogProc(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam) { const SDL_MessageBoxData *messageboxdata; size_t buttonindex; switch ( iMessage ) { case WM_INITDIALOG: if (lParam == 0) { EndDialog(hDlg, IDINVALPTRINIT); return TRUE; } messageboxdata = (const SDL_MessageBoxData *)lParam; SetWindowLongPtr(hDlg, GWLP_USERDATA, lParam); if (GetButtonIndex(messageboxdata, SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, &buttonindex)) { /* Focus on the first default return-key button */ HWND buttonctl = GetDlgItem(hDlg, (int)(IDBUTTONINDEX0 + buttonindex)); if (buttonctl == NULL) { EndDialog(hDlg, IDINVALPTRDLGITEM); } PostMessage(hDlg, WM_NEXTDLGCTL, (WPARAM)buttonctl, TRUE); } else { /* Give the focus to the dialog window instead */ SetFocus(hDlg); } return FALSE; case WM_SETFOCUS: messageboxdata = (const SDL_MessageBoxData *)GetWindowLongPtr(hDlg, GWLP_USERDATA); if (messageboxdata == NULL) { EndDialog(hDlg, IDINVALPTRSETFOCUS); return TRUE; } /* Let the default button be focused if there is one. Otherwise, prevent any initial focus. */ if (GetButtonIndex(messageboxdata, SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, &buttonindex)) { return FALSE; } return TRUE; case WM_COMMAND: messageboxdata = (const SDL_MessageBoxData *)GetWindowLongPtr(hDlg, GWLP_USERDATA); if (messageboxdata == NULL) { EndDialog(hDlg, IDINVALPTRCOMMAND); return TRUE; } /* Return the ID of the button that was pushed */ if (wParam == IDOK) { if (GetButtonIndex(messageboxdata, SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, &buttonindex)) { EndDialog(hDlg, IDBUTTONINDEX0 + buttonindex); } } else if (wParam == IDCANCEL) { if (GetButtonIndex(messageboxdata, SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT, &buttonindex)) { EndDialog(hDlg, IDBUTTONINDEX0 + buttonindex); } else { /* Closing of window was requested by user or system. It would be rude not to comply. */ EndDialog(hDlg, IDCLOSED); } } else if (wParam >= IDBUTTONINDEX0 && (int)wParam - IDBUTTONINDEX0 < messageboxdata->numbuttons) { EndDialog(hDlg, wParam); } return TRUE; default: break; } return FALSE; } static SDL_bool ExpandDialogSpace(WIN_DialogData *dialog, size_t space) { /* Growing memory in 64 KiB steps. */ const size_t sizestep = 0x10000; size_t size = dialog->size; if (size == 0) { /* Start with 4 KiB or a multiple of 64 KiB to fit the data. */ size = 0x1000; if (SIZE_MAX - sizestep < space) { size = space; } else if (space > size) { size = (space + sizestep) & ~(sizestep - 1); } } else if (SIZE_MAX - dialog->used < space) { SDL_OutOfMemory(); return SDL_FALSE; } else if (SIZE_MAX - (dialog->used + space) < sizestep) { /* Close to the maximum. */ size = dialog->used + space; } else if (size < dialog->used + space) { /* Round up to the next 64 KiB block. */ size = dialog->used + space; size += sizestep - size % sizestep; } if (size > dialog->size) { void *data = SDL_realloc(dialog->data, size); if (!data) { SDL_OutOfMemory(); return SDL_FALSE; } dialog->data = data; dialog->size = size; dialog->lpDialog = (DLGTEMPLATEEX*)dialog->data; } return SDL_TRUE; } static SDL_bool AlignDialogData(WIN_DialogData *dialog, size_t size) { size_t padding = (dialog->used % size); if (!ExpandDialogSpace(dialog, padding)) { return SDL_FALSE; } dialog->used += padding; return SDL_TRUE; } static SDL_bool AddDialogData(WIN_DialogData *dialog, const void *data, size_t size) { if (!ExpandDialogSpace(dialog, size)) { return SDL_FALSE; } SDL_memcpy(dialog->data+dialog->used, data, size); dialog->used += size; return SDL_TRUE; } static SDL_bool AddDialogString(WIN_DialogData *dialog, const char *string) { WCHAR *wstring; WCHAR *p; size_t count; SDL_bool status; if (!string) { string = ""; } wstring = WIN_UTF8ToString(string); if (!wstring) { return SDL_FALSE; } /* Find out how many characters we have, including null terminator */ count = 0; for (p = wstring; *p; ++p) { ++count; } ++count; status = AddDialogData(dialog, wstring, count*sizeof(WCHAR)); SDL_free(wstring); return status; } static int s_BaseUnitsX; static int s_BaseUnitsY; static void Vec2ToDLU(short *x, short *y) { SDL_assert(s_BaseUnitsX != 0); /* we init in WIN_ShowMessageBox(), which is the only public function... */ *x = MulDiv(*x, 4, s_BaseUnitsX); *y = MulDiv(*y, 8, s_BaseUnitsY); } static SDL_bool AddDialogControl(WIN_DialogData *dialog, WORD type, DWORD style, DWORD exStyle, int x, int y, int w, int h, int id, const char *caption, WORD ordinal) { DLGITEMTEMPLATEEX item; WORD marker = 0xFFFF; WORD extraData = 0; SDL_zero(item); item.style = style; item.exStyle = exStyle; item.x = x; item.y = y; item.cx = w; item.cy = h; item.id = id; Vec2ToDLU(&item.x, &item.y); Vec2ToDLU(&item.cx, &item.cy); if (!AlignDialogData(dialog, sizeof(DWORD))) { return SDL_FALSE; } if (!AddDialogData(dialog, &item, sizeof(item))) { return SDL_FALSE; } if (!AddDialogData(dialog, &marker, sizeof(marker))) { return SDL_FALSE; } if (!AddDialogData(dialog, &type, sizeof(type))) { return SDL_FALSE; } if (type == DLGITEMTYPEBUTTON || (type == DLGITEMTYPESTATIC && caption != NULL)) { if (!AddDialogString(dialog, caption)) { return SDL_FALSE; } } else { if (!AddDialogData(dialog, &marker, sizeof(marker))) { return SDL_FALSE; } if (!AddDialogData(dialog, &ordinal, sizeof(ordinal))) { return SDL_FALSE; } } if (!AddDialogData(dialog, &extraData, sizeof(extraData))) { return SDL_FALSE; } if (type == DLGITEMTYPEBUTTON) { dialog->numbuttons++; } ++dialog->lpDialog->cDlgItems; return SDL_TRUE; } static SDL_bool AddDialogStaticText(WIN_DialogData *dialog, int x, int y, int w, int h, const char *text) { DWORD style = WS_VISIBLE | WS_CHILD | SS_LEFT | SS_NOPREFIX | SS_EDITCONTROL | WS_GROUP; return AddDialogControl(dialog, DLGITEMTYPESTATIC, style, 0, x, y, w, h, -1, text, 0); } static SDL_bool AddDialogStaticIcon(WIN_DialogData *dialog, int x, int y, int w, int h, Uint16 ordinal) { DWORD style = WS_VISIBLE | WS_CHILD | SS_ICON | WS_GROUP; return AddDialogControl(dialog, DLGITEMTYPESTATIC, style, 0, x, y, w, h, -2, NULL, ordinal); } static SDL_bool AddDialogButton(WIN_DialogData *dialog, int x, int y, int w, int h, const char *text, int id, SDL_bool isDefault) { DWORD style = WS_VISIBLE | WS_CHILD | WS_TABSTOP; if (isDefault) { style |= BS_DEFPUSHBUTTON; } else { style |= BS_PUSHBUTTON; } /* The first button marks the start of the group. */ if (dialog->numbuttons == 0) { style |= WS_GROUP; } return AddDialogControl(dialog, DLGITEMTYPEBUTTON, style, 0, x, y, w, h, id, text, 0); } static void FreeDialogData(WIN_DialogData *dialog) { SDL_free(dialog->data); SDL_free(dialog); } static WIN_DialogData *CreateDialogData(int w, int h, const char *caption) { WIN_DialogData *dialog; DLGTEMPLATEEX dialogTemplate; WORD WordToPass; SDL_zero(dialogTemplate); dialogTemplate.dlgVer = 1; dialogTemplate.signature = 0xffff; dialogTemplate.style = (WS_CAPTION | DS_CENTER | DS_SHELLFONT); dialogTemplate.x = 0; dialogTemplate.y = 0; dialogTemplate.cx = w; dialogTemplate.cy = h; Vec2ToDLU(&dialogTemplate.cx, &dialogTemplate.cy); dialog = (WIN_DialogData *)SDL_calloc(1, sizeof(*dialog)); if (!dialog) { return NULL; } if (!AddDialogData(dialog, &dialogTemplate, sizeof(dialogTemplate))) { FreeDialogData(dialog); return NULL; } /* No menu */ WordToPass = 0; if (!AddDialogData(dialog, &WordToPass, 2)) { FreeDialogData(dialog); return NULL; } /* No custom class */ if (!AddDialogData(dialog, &WordToPass, 2)) { FreeDialogData(dialog); return NULL; } /* title */ if (!AddDialogString(dialog, caption)) { FreeDialogData(dialog); return NULL; } /* Font stuff */ { /* * We want to use the system messagebox font. */ BYTE ToPass; NONCLIENTMETRICSA NCM; NCM.cbSize = sizeof(NCM); SystemParametersInfoA(SPI_GETNONCLIENTMETRICS, 0, &NCM, 0); /* Font size - convert to logical font size for dialog parameter. */ { HDC ScreenDC = GetDC(NULL); int LogicalPixelsY = GetDeviceCaps(ScreenDC, LOGPIXELSY); if (!LogicalPixelsY) /* This can happen if the application runs out of GDI handles */ LogicalPixelsY = 72; WordToPass = (WORD)(-72 * NCM.lfMessageFont.lfHeight / LogicalPixelsY); ReleaseDC(NULL, ScreenDC); } if (!AddDialogData(dialog, &WordToPass, 2)) { FreeDialogData(dialog); return NULL; } /* Font weight */ WordToPass = (WORD)NCM.lfMessageFont.lfWeight; if (!AddDialogData(dialog, &WordToPass, 2)) { FreeDialogData(dialog); return NULL; } /* italic? */ ToPass = NCM.lfMessageFont.lfItalic; if (!AddDialogData(dialog, &ToPass, 1)) { FreeDialogData(dialog); return NULL; } /* charset? */ ToPass = NCM.lfMessageFont.lfCharSet; if (!AddDialogData(dialog, &ToPass, 1)) { FreeDialogData(dialog); return NULL; } /* font typeface. */ if (!AddDialogString(dialog, NCM.lfMessageFont.lfFaceName)) { FreeDialogData(dialog); return NULL; } } return dialog; } /* Escaping ampersands is necessary to disable mnemonics in dialog controls. * The caller provides a char** for dst and a size_t* for dstlen where the * address of the work buffer and its size will be stored. Their values must be * NULL and 0 on the first call. src is the string to be escaped. On error, the * function returns NULL and, on success, returns a pointer to the escaped * sequence as a read-only string that is valid until the next call or until the * work buffer is freed. Once all strings have been processed, it's the caller's * responsibilty to free the work buffer with SDL_free, even on errors. */ static const char *EscapeAmpersands(char **dst, size_t *dstlen, const char *src) { char *newdst; size_t ampcount = 0; size_t srclen = 0; if (src == NULL) { return NULL; } while (src[srclen]) { if (src[srclen] == '&') { ampcount++; } srclen++; } srclen++; if (ampcount == 0) { /* Nothing to do. */ return src; } if (SIZE_MAX - srclen < ampcount) { return NULL; } if (*dst == NULL || *dstlen < srclen + ampcount) { /* Allocating extra space in case the next strings are a bit longer. */ size_t extraspace = SIZE_MAX - (srclen + ampcount); if (extraspace > 512) { extraspace = 512; } *dstlen = srclen + ampcount + extraspace; SDL_free(*dst); *dst = NULL; newdst = SDL_malloc(*dstlen); if (newdst == NULL) { return NULL; } *dst = newdst; } else { newdst = *dst; } /* The escape character is the ampersand itself. */ while (srclen--) { if (*src == '&') { *newdst++ = '&'; } *newdst++ = *src++; } return *dst; } /* This function is called if a Task Dialog is unsupported. */ static int WIN_ShowOldMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid) { WIN_DialogData *dialog; int i, x, y, retval; HFONT DialogFont; SIZE Size; RECT TextSize; wchar_t* wmessage; TEXTMETRIC TM; HDC FontDC; INT_PTR result; char *ampescape = NULL; size_t ampescapesize = 0; Uint16 defbuttoncount = 0; Uint16 icon = 0; HWND ParentWindow = NULL; const int ButtonWidth = 88; const int ButtonHeight = 26; const int TextMargin = 16; const int ButtonMargin = 12; const int IconWidth = GetSystemMetrics(SM_CXICON); const int IconHeight = GetSystemMetrics(SM_CYICON); const int IconMargin = 20; if (messageboxdata->numbuttons > MAX_BUTTONS) { return SDL_SetError("Number of butons exceeds limit of %d", MAX_BUTTONS); } switch (messageboxdata->flags) { case SDL_MESSAGEBOX_ERROR: icon = (Uint16)(size_t)IDI_ERROR; break; case SDL_MESSAGEBOX_WARNING: icon = (Uint16)(size_t)IDI_WARNING; break; case SDL_MESSAGEBOX_INFORMATION: icon = (Uint16)(size_t)IDI_INFORMATION; break; } /* Jan 25th, 2013 - dant@fleetsa.com * * * I've tried to make this more reasonable, but I've run in to a lot * of nonsense. * * The original issue is the code was written in pixels and not * dialog units (DLUs). All DialogBox functions use DLUs, which * vary based on the selected font (yay). * * According to MSDN, the most reliable way to convert is via * MapDialogUnits, which requires an HWND, which we don't have * at time of template creation. * * We do however have: * The system font (DLU width 8 for me) * The font we select for the dialog (DLU width 6 for me) * * Based on experimentation, *neither* of these return the value * actually used. Stepping in to MapDialogUnits(), the conversion * is fairly clear, and uses 7 for me. * * As a result, some of this is hacky to ensure the sizing is * somewhat correct. * * Honestly, a long term solution is to use CreateWindow, not CreateDialog. * * * In order to get text dimensions we need to have a DC with the desired font. * I'm assuming a dialog box in SDL is rare enough we can to the create. */ FontDC = CreateCompatibleDC(0); { /* Create a duplicate of the font used in system message boxes. */ LOGFONT lf; NONCLIENTMETRICS NCM; NCM.cbSize = sizeof(NCM); SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, &NCM, 0); lf = NCM.lfMessageFont; DialogFont = CreateFontIndirect(&lf); } /* Select the font in to our DC */ SelectObject(FontDC, DialogFont); { /* Get the metrics to try and figure our DLU conversion. */ GetTextMetrics(FontDC, &TM); /* Calculation from the following documentation: * https://support.microsoft.com/en-gb/help/125681/how-to-calculate-dialog-base-units-with-non-system-based-font * This fixes bug 2137, dialog box calculation with a fixed-width system font */ { SIZE extent; GetTextExtentPoint32A(FontDC, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 52, &extent); s_BaseUnitsX = (extent.cx / 26 + 1) / 2; } /*s_BaseUnitsX = TM.tmAveCharWidth + 1;*/ s_BaseUnitsY = TM.tmHeight; } /* Measure the *pixel* size of the string. */ wmessage = WIN_UTF8ToString(messageboxdata->message); SDL_zero(TextSize); DrawText(FontDC, wmessage, -1, &TextSize, DT_CALCRECT | DT_LEFT | DT_NOPREFIX | DT_EDITCONTROL); /* Add margins and some padding for hangs, etc. */ TextSize.left += TextMargin; TextSize.right += TextMargin + 2; TextSize.top += TextMargin; TextSize.bottom += TextMargin + 2; /* Done with the DC, and the string */ DeleteDC(FontDC); SDL_free(wmessage); /* Increase the size of the dialog by some border spacing around the text. */ Size.cx = TextSize.right - TextSize.left; Size.cy = TextSize.bottom - TextSize.top; Size.cx += TextMargin * 2; Size.cy += TextMargin * 2; /* Make dialog wider and shift text over for the icon. */ if (icon) { Size.cx += IconMargin + IconWidth; TextSize.left += IconMargin + IconWidth; TextSize.right += IconMargin + IconWidth; } /* Ensure the size is wide enough for all of the buttons. */ if (Size.cx < messageboxdata->numbuttons * (ButtonWidth + ButtonMargin) + ButtonMargin) Size.cx = messageboxdata->numbuttons * (ButtonWidth + ButtonMargin) + ButtonMargin; /* Reset the height to the icon size if it is actually bigger than the text. */ if (icon && Size.cy < IconMargin * 2 + IconHeight) { Size.cy = IconMargin * 2 + IconHeight; } /* Add vertical space for the buttons and border. */ Size.cy += ButtonHeight + TextMargin; dialog = CreateDialogData(Size.cx, Size.cy, messageboxdata->title); if (!dialog) { return -1; } if (icon && ! AddDialogStaticIcon(dialog, IconMargin, IconMargin, IconWidth, IconHeight, icon)) { FreeDialogData(dialog); return -1; } if (!AddDialogStaticText(dialog, TextSize.left, TextSize.top, TextSize.right - TextSize.left, TextSize.bottom - TextSize.top, messageboxdata->message)) { FreeDialogData(dialog); return -1; } /* Align the buttons to the right/bottom. */ x = Size.cx - (ButtonWidth + ButtonMargin) * messageboxdata->numbuttons; y = Size.cy - ButtonHeight - ButtonMargin; for (i = 0; i < messageboxdata->numbuttons; i++) { SDL_bool isdefault = SDL_FALSE; const char *buttontext; const SDL_MessageBoxButtonData *sdlButton; /* We always have to create the dialog buttons from left to right * so that the tab order is correct. Select the info to use * depending on which order was requested. */ if (messageboxdata->flags & SDL_MESSAGEBOX_BUTTONS_LEFT_TO_RIGHT) { sdlButton = &messageboxdata->buttons[i]; } else { sdlButton = &messageboxdata->buttons[messageboxdata->numbuttons - 1 - i]; } if (sdlButton->flags & SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT) { defbuttoncount++; if (defbuttoncount == 1) { isdefault = SDL_TRUE; } } buttontext = EscapeAmpersands(&ampescape, &ampescapesize, sdlButton->text); /* Make sure to provide the correct ID to keep buttons indexed in the * same order as how they are in messageboxdata. */ if (buttontext == NULL || !AddDialogButton(dialog, x, y, ButtonWidth, ButtonHeight, buttontext, IDBUTTONINDEX0 + (int)(sdlButton - messageboxdata->buttons), isdefault)) { FreeDialogData(dialog); SDL_free(ampescape); return -1; } x += ButtonWidth + ButtonMargin; } SDL_free(ampescape); /* If we have a parent window, get the Instance and HWND for them * so that our little dialog gets exclusive focus at all times. */ if (messageboxdata->window) { ParentWindow = ((SDL_WindowData*)messageboxdata->window->driverdata)->hwnd; } result = DialogBoxIndirectParam(NULL, (DLGTEMPLATE*)dialog->lpDialog, ParentWindow, (DLGPROC)MessageBoxDialogProc, (LPARAM)messageboxdata); if (result >= IDBUTTONINDEX0 && result - IDBUTTONINDEX0 < messageboxdata->numbuttons) { *buttonid = messageboxdata->buttons[result - IDBUTTONINDEX0].buttonid; retval = 0; } else if (result == IDCLOSED) { /* Dialog window closed by user or system. */ /* This could use a special return code. */ retval = 0; *buttonid = -1; } else { if (result == 0) { SDL_SetError("Invalid parent window handle"); } else if (result == -1) { SDL_SetError("The message box encountered an error."); } else if (result == IDINVALPTRINIT || result == IDINVALPTRSETFOCUS || result == IDINVALPTRCOMMAND) { SDL_SetError("Invalid message box pointer in dialog procedure"); } else if (result == IDINVALPTRDLGITEM) { SDL_SetError("Couldn't find dialog control of the default enter-key button"); } else { SDL_SetError("An unknown error occured"); } retval = -1; } FreeDialogData(dialog); return retval; } /* TaskDialogIndirect procedure * This is because SDL targets Windows XP (0x501), so this is not defined in the platform SDK. */ typedef HRESULT(FAR WINAPI *TASKDIALOGINDIRECTPROC)(const TASKDIALOGCONFIG *pTaskConfig, int *pnButton, int *pnRadioButton, BOOL *pfVerificationFlagChecked); int WIN_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid) { HWND ParentWindow = NULL; wchar_t *wmessage; wchar_t *wtitle; TASKDIALOGCONFIG TaskConfig; TASKDIALOG_BUTTON *pButtons; TASKDIALOG_BUTTON *pButton; HMODULE hComctl32; TASKDIALOGINDIRECTPROC pfnTaskDialogIndirect; HRESULT hr; char *ampescape = NULL; size_t ampescapesize = 0; int nButton; int nCancelButton; int i; if (SIZE_MAX / sizeof(TASKDIALOG_BUTTON) < messageboxdata->numbuttons) { return SDL_OutOfMemory(); } /* If we cannot load comctl32.dll use the old messagebox! */ hComctl32 = LoadLibrary(TEXT("Comctl32.dll")); if (hComctl32 == NULL) { return WIN_ShowOldMessageBox(messageboxdata, buttonid); } /* If TaskDialogIndirect doesn't exist use the old messagebox! This will fail prior to Windows Vista. The manifest file in the application may require targeting version 6 of comctl32.dll, even when we use LoadLibrary here! If you don't want to bother with manifests, put this #pragma in your app's source code somewhere: pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") */ pfnTaskDialogIndirect = (TASKDIALOGINDIRECTPROC) GetProcAddress(hComctl32, "TaskDialogIndirect"); if (pfnTaskDialogIndirect == NULL) { FreeLibrary(hComctl32); return WIN_ShowOldMessageBox(messageboxdata, buttonid); } /* If we have a parent window, get the Instance and HWND for them so that our little dialog gets exclusive focus at all times. */ if (messageboxdata->window) { ParentWindow = ((SDL_WindowData *) messageboxdata->window->driverdata)->hwnd; } wmessage = WIN_UTF8ToString(messageboxdata->message); wtitle = WIN_UTF8ToString(messageboxdata->title); SDL_zero(TaskConfig); TaskConfig.cbSize = sizeof (TASKDIALOGCONFIG); TaskConfig.hwndParent = ParentWindow; TaskConfig.dwFlags = TDF_SIZE_TO_CONTENT; TaskConfig.pszWindowTitle = wtitle; if (messageboxdata->flags & SDL_MESSAGEBOX_ERROR) { TaskConfig.pszMainIcon = TD_ERROR_ICON; } else if (messageboxdata->flags & SDL_MESSAGEBOX_WARNING) { TaskConfig.pszMainIcon = TD_WARNING_ICON; } else if (messageboxdata->flags & SDL_MESSAGEBOX_INFORMATION) { TaskConfig.pszMainIcon = TD_INFORMATION_ICON; } else { TaskConfig.pszMainIcon = NULL; } TaskConfig.pszContent = wmessage; TaskConfig.cButtons = messageboxdata->numbuttons; pButtons = SDL_malloc(sizeof (TASKDIALOG_BUTTON) * messageboxdata->numbuttons); TaskConfig.nDefaultButton = 0; nCancelButton = 0; for (i = 0; i < messageboxdata->numbuttons; i++) { const char *buttontext; if (messageboxdata->flags & SDL_MESSAGEBOX_BUTTONS_LEFT_TO_RIGHT) { pButton = &pButtons[i]; } else { pButton = &pButtons[messageboxdata->numbuttons - 1 - i]; } if (messageboxdata->buttons[i].flags & SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT) { nCancelButton = messageboxdata->buttons[i].buttonid; pButton->nButtonID = IDCANCEL; } else { pButton->nButtonID = IDBUTTONINDEX0 + i; } buttontext = EscapeAmpersands(&ampescape, &ampescapesize, messageboxdata->buttons[i].text); if (buttontext == NULL) { int j; FreeLibrary(hComctl32); SDL_free(ampescape); SDL_free(wmessage); SDL_free(wtitle); for (j = 0; j < i; j++) { SDL_free((wchar_t *) pButtons[j].pszButtonText); } SDL_free(pButtons); return -1; } pButton->pszButtonText = WIN_UTF8ToString(buttontext); if (messageboxdata->buttons[i].flags & SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT) { TaskConfig.nDefaultButton = pButton->nButtonID; } } TaskConfig.pButtons = pButtons; /* Show the Task Dialog */ hr = pfnTaskDialogIndirect(&TaskConfig, &nButton, NULL, NULL); /* Free everything */ FreeLibrary(hComctl32); SDL_free(ampescape); SDL_free(wmessage); SDL_free(wtitle); for (i = 0; i < messageboxdata->numbuttons; i++) { SDL_free((wchar_t *) pButtons[i].pszButtonText); } SDL_free(pButtons); /* Check the Task Dialog was successful and give the result */ if (SUCCEEDED(hr)) { if (nButton == IDCANCEL) { *buttonid = nCancelButton; } else if (nButton >= IDBUTTONINDEX0 && nButton < IDBUTTONINDEX0 + messageboxdata->numbuttons) { *buttonid = messageboxdata->buttons[nButton - IDBUTTONINDEX0].buttonid; } else { *buttonid = -1; } return 0; } /* We failed showing the Task Dialog, use the old message box! */ return WIN_ShowOldMessageBox(messageboxdata, buttonid); } #endif /* SDL_VIDEO_DRIVER_WINDOWS */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsmessagebox.c
C
apache-2.0
29,373
/* 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_VIDEO_DRIVER_WINDOWS extern int WIN_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid); #endif /* SDL_VIDEO_DRIVER_WINDOWS */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsmessagebox.h
C
apache-2.0
1,165
/* 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_VIDEO_DRIVER_WINDOWS #include "SDL_windowsvideo.h" #include "../../../include/SDL_assert.h" /* Windows CE compatibility */ #ifndef CDS_FULLSCREEN #define CDS_FULLSCREEN 0 #endif /* #define DEBUG_MODES */ static void WIN_UpdateDisplayMode(_THIS, LPCTSTR deviceName, DWORD index, SDL_DisplayMode * mode) { SDL_DisplayModeData *data = (SDL_DisplayModeData *) mode->driverdata; HDC hdc; data->DeviceMode.dmFields = (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY | DM_DISPLAYFLAGS); if (index == ENUM_CURRENT_SETTINGS && (hdc = CreateDC(deviceName, NULL, NULL, NULL)) != NULL) { char bmi_data[sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD)]; LPBITMAPINFO bmi; HBITMAP hbm; int logical_width = GetDeviceCaps( hdc, HORZRES ); int logical_height = GetDeviceCaps( hdc, VERTRES ); mode->w = logical_width; mode->h = logical_height; SDL_zeroa(bmi_data); bmi = (LPBITMAPINFO) bmi_data; bmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); hbm = CreateCompatibleBitmap(hdc, 1, 1); GetDIBits(hdc, hbm, 0, 1, NULL, bmi, DIB_RGB_COLORS); GetDIBits(hdc, hbm, 0, 1, NULL, bmi, DIB_RGB_COLORS); DeleteObject(hbm); DeleteDC(hdc); if (bmi->bmiHeader.biCompression == BI_BITFIELDS) { switch (*(Uint32 *) bmi->bmiColors) { case 0x00FF0000: mode->format = SDL_PIXELFORMAT_RGB888; break; case 0x000000FF: mode->format = SDL_PIXELFORMAT_BGR888; break; case 0xF800: mode->format = SDL_PIXELFORMAT_RGB565; break; case 0x7C00: mode->format = SDL_PIXELFORMAT_RGB555; break; } } else if (bmi->bmiHeader.biBitCount == 8) { mode->format = SDL_PIXELFORMAT_INDEX8; } else if (bmi->bmiHeader.biBitCount == 4) { mode->format = SDL_PIXELFORMAT_INDEX4LSB; } } else if (mode->format == SDL_PIXELFORMAT_UNKNOWN) { /* FIXME: Can we tell what this will be? */ if ((data->DeviceMode.dmFields & DM_BITSPERPEL) == DM_BITSPERPEL) { switch (data->DeviceMode.dmBitsPerPel) { case 32: mode->format = SDL_PIXELFORMAT_RGB888; break; case 24: mode->format = SDL_PIXELFORMAT_RGB24; break; case 16: mode->format = SDL_PIXELFORMAT_RGB565; break; case 15: mode->format = SDL_PIXELFORMAT_RGB555; break; case 8: mode->format = SDL_PIXELFORMAT_INDEX8; break; case 4: mode->format = SDL_PIXELFORMAT_INDEX4LSB; break; } } } } static SDL_bool WIN_GetDisplayMode(_THIS, LPCTSTR deviceName, DWORD index, SDL_DisplayMode * mode) { SDL_DisplayModeData *data; DEVMODE devmode; devmode.dmSize = sizeof(devmode); devmode.dmDriverExtra = 0; if (!EnumDisplaySettings(deviceName, index, &devmode)) { return SDL_FALSE; } data = (SDL_DisplayModeData *) SDL_malloc(sizeof(*data)); if (!data) { return SDL_FALSE; } mode->driverdata = data; data->DeviceMode = devmode; mode->format = SDL_PIXELFORMAT_UNKNOWN; mode->w = data->DeviceMode.dmPelsWidth; mode->h = data->DeviceMode.dmPelsHeight; mode->refresh_rate = data->DeviceMode.dmDisplayFrequency; /* Fill in the mode information */ WIN_UpdateDisplayMode(_this, deviceName, index, mode); return SDL_TRUE; } static SDL_bool WIN_AddDisplay(_THIS, HMONITOR hMonitor, const MONITORINFOEX *info) { SDL_VideoDisplay display; SDL_DisplayData *displaydata; SDL_DisplayMode mode; DISPLAY_DEVICE device; #ifdef DEBUG_MODES SDL_Log("Display: %s\n", WIN_StringToUTF8(info->szDevice)); #endif if (!WIN_GetDisplayMode(_this, info->szDevice, ENUM_CURRENT_SETTINGS, &mode)) { return SDL_FALSE; } displaydata = (SDL_DisplayData *) SDL_malloc(sizeof(*displaydata)); if (!displaydata) { return SDL_FALSE; } SDL_memcpy(displaydata->DeviceName, info->szDevice, sizeof(displaydata->DeviceName)); displaydata->MonitorHandle = hMonitor; SDL_zero(display); device.cb = sizeof(device); if (EnumDisplayDevices(info->szDevice, 0, &device, 0)) { display.name = WIN_StringToUTF8(device.DeviceString); } display.desktop_mode = mode; display.current_mode = mode; display.driverdata = displaydata; SDL_AddVideoDisplay(&display); SDL_free(display.name); return SDL_TRUE; } typedef struct _WIN_AddDisplaysData { SDL_VideoDevice *video_device; SDL_bool want_primary; } WIN_AddDisplaysData; static BOOL CALLBACK WIN_AddDisplaysCallback(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) { WIN_AddDisplaysData *data = (WIN_AddDisplaysData*)dwData; MONITORINFOEX info; SDL_zero(info); info.cbSize = sizeof(info); if (GetMonitorInfo(hMonitor, (LPMONITORINFO)&info) != 0) { const SDL_bool is_primary = ((info.dwFlags & MONITORINFOF_PRIMARY) == MONITORINFOF_PRIMARY); if (is_primary == data->want_primary) { WIN_AddDisplay(data->video_device, hMonitor, &info); } } // continue enumeration return TRUE; } static void WIN_AddDisplays(_THIS) { WIN_AddDisplaysData callback_data; callback_data.video_device = _this; callback_data.want_primary = SDL_TRUE; EnumDisplayMonitors(NULL, NULL, WIN_AddDisplaysCallback, (LPARAM)&callback_data); callback_data.want_primary = SDL_FALSE; EnumDisplayMonitors(NULL, NULL, WIN_AddDisplaysCallback, (LPARAM)&callback_data); } int WIN_InitModes(_THIS) { WIN_AddDisplays(_this); if (_this->num_displays == 0) { return SDL_SetError("No displays available"); } return 0; } int WIN_GetDisplayBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect) { const SDL_DisplayData *data = (const SDL_DisplayData *)display->driverdata; MONITORINFO minfo; BOOL rc; SDL_zero(minfo); minfo.cbSize = sizeof(MONITORINFO); rc = GetMonitorInfo(data->MonitorHandle, &minfo); if (!rc) { return SDL_SetError("Couldn't find monitor data"); } rect->x = minfo.rcMonitor.left; rect->y = minfo.rcMonitor.top; rect->w = minfo.rcMonitor.right - minfo.rcMonitor.left; rect->h = minfo.rcMonitor.bottom - minfo.rcMonitor.top; return 0; } int WIN_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi_out, float * hdpi_out, float * vdpi_out) { const SDL_DisplayData *displaydata = (SDL_DisplayData *)display->driverdata; const SDL_VideoData *videodata = (SDL_VideoData *)display->device->driverdata; float hdpi = 0, vdpi = 0, ddpi = 0; if (videodata->GetDpiForMonitor) { UINT hdpi_uint, vdpi_uint; // Windows 8.1+ codepath if (videodata->GetDpiForMonitor(displaydata->MonitorHandle, MDT_EFFECTIVE_DPI, &hdpi_uint, &vdpi_uint) == S_OK) { // GetDpiForMonitor docs promise to return the same hdpi/vdpi hdpi = (float)hdpi_uint; vdpi = (float)hdpi_uint; ddpi = (float)hdpi_uint; } else { return SDL_SetError("GetDpiForMonitor failed"); } } else { // Window 8.0 and below: same DPI for all monitors. HDC hdc; int hdpi_int, vdpi_int, hpoints, vpoints, hpix, vpix; float hinches, vinches; hdc = GetDC(NULL); if (hdc == NULL) { return SDL_SetError("GetDC failed"); } hdpi_int = GetDeviceCaps(hdc, LOGPIXELSX); vdpi_int = GetDeviceCaps(hdc, LOGPIXELSY); ReleaseDC(NULL, hdc); hpoints = GetSystemMetrics(SM_CXVIRTUALSCREEN); vpoints = GetSystemMetrics(SM_CYVIRTUALSCREEN); hpix = MulDiv(hpoints, hdpi_int, 96); vpix = MulDiv(vpoints, vdpi_int, 96); hinches = (float)hpoints / 96.0f; vinches = (float)vpoints / 96.0f; hdpi = (float)hdpi_int; vdpi = (float)vdpi_int; ddpi = SDL_ComputeDiagonalDPI(hpix, vpix, hinches, vinches); } if (ddpi_out) { *ddpi_out = ddpi; } if (hdpi_out) { *hdpi_out = hdpi; } if (vdpi_out) { *vdpi_out = vdpi; } return ddpi != 0.0f ? 0 : SDL_SetError("Couldn't get DPI"); } int WIN_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect) { const SDL_DisplayData *data = (const SDL_DisplayData *)display->driverdata; MONITORINFO minfo; BOOL rc; SDL_zero(minfo); minfo.cbSize = sizeof(MONITORINFO); rc = GetMonitorInfo(data->MonitorHandle, &minfo); if (!rc) { return SDL_SetError("Couldn't find monitor data"); } rect->x = minfo.rcWork.left; rect->y = minfo.rcWork.top; rect->w = minfo.rcWork.right - minfo.rcWork.left; rect->h = minfo.rcWork.bottom - minfo.rcWork.top; return 0; } void WIN_GetDisplayModes(_THIS, SDL_VideoDisplay * display) { SDL_DisplayData *data = (SDL_DisplayData *) display->driverdata; DWORD i; SDL_DisplayMode mode; for (i = 0;; ++i) { if (!WIN_GetDisplayMode(_this, data->DeviceName, i, &mode)) { break; } if (SDL_ISPIXELFORMAT_INDEXED(mode.format)) { /* We don't support palettized modes now */ SDL_free(mode.driverdata); continue; } if (mode.format != SDL_PIXELFORMAT_UNKNOWN) { if (!SDL_AddDisplayMode(display, &mode)) { SDL_free(mode.driverdata); } } else { SDL_free(mode.driverdata); } } } int WIN_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode) { SDL_DisplayData *displaydata = (SDL_DisplayData *) display->driverdata; SDL_DisplayModeData *data = (SDL_DisplayModeData *) mode->driverdata; LONG status; if (mode->driverdata == display->desktop_mode.driverdata) { status = ChangeDisplaySettingsEx(displaydata->DeviceName, NULL, NULL, CDS_FULLSCREEN, NULL); } else { status = ChangeDisplaySettingsEx(displaydata->DeviceName, &data->DeviceMode, NULL, CDS_FULLSCREEN, NULL); } if (status != DISP_CHANGE_SUCCESSFUL) { const char *reason = "Unknown reason"; switch (status) { case DISP_CHANGE_BADFLAGS: reason = "DISP_CHANGE_BADFLAGS"; break; case DISP_CHANGE_BADMODE: reason = "DISP_CHANGE_BADMODE"; break; case DISP_CHANGE_BADPARAM: reason = "DISP_CHANGE_BADPARAM"; break; case DISP_CHANGE_FAILED: reason = "DISP_CHANGE_FAILED"; break; } return SDL_SetError("ChangeDisplaySettingsEx() failed: %s", reason); } EnumDisplaySettings(displaydata->DeviceName, ENUM_CURRENT_SETTINGS, &data->DeviceMode); WIN_UpdateDisplayMode(_this, displaydata->DeviceName, ENUM_CURRENT_SETTINGS, mode); return 0; } void WIN_QuitModes(_THIS) { /* All fullscreen windows should have restored modes by now */ } #endif /* SDL_VIDEO_DRIVER_WINDOWS */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsmodes.c
C
apache-2.0
12,482
/* 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_windowsmodes_h_ #define SDL_windowsmodes_h_ typedef struct { TCHAR DeviceName[32]; HMONITOR MonitorHandle; } SDL_DisplayData; typedef struct { DEVMODE DeviceMode; } SDL_DisplayModeData; extern int WIN_InitModes(_THIS); extern int WIN_GetDisplayBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect); extern int WIN_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect); extern int WIN_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi, float * hdpi, float * vdpi); extern void WIN_GetDisplayModes(_THIS, SDL_VideoDisplay * display); extern int WIN_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode); extern void WIN_QuitModes(_THIS); #endif /* SDL_windowsmodes_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsmodes.h
C
apache-2.0
1,763
/* 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_VIDEO_DRIVER_WINDOWS #include "SDL_assert.h" #include "SDL_windowsvideo.h" #include "../../events/SDL_mouse_c.h" HCURSOR SDL_cursor = NULL; static int rawInputEnableCount = 0; static int ToggleRawInput(SDL_bool enabled) { RAWINPUTDEVICE rawMouse = { 0x01, 0x02, 0, NULL }; /* Mouse: UsagePage = 1, Usage = 2 */ if (enabled) { rawInputEnableCount++; if (rawInputEnableCount > 1) { return 0; /* already done. */ } } else { if (rawInputEnableCount == 0) { return 0; /* already done. */ } rawInputEnableCount--; if (rawInputEnableCount > 0) { return 0; /* not time to disable yet */ } } if (!enabled) { rawMouse.dwFlags |= RIDEV_REMOVE; } /* (Un)register raw input for mice */ if (RegisterRawInputDevices(&rawMouse, 1, sizeof(RAWINPUTDEVICE)) == FALSE) { /* Only return an error when registering. If we unregister and fail, then it's probably that we unregistered twice. That's OK. */ if (enabled) { return SDL_Unsupported(); } } return 0; } static SDL_Cursor * WIN_CreateDefaultCursor() { SDL_Cursor *cursor; cursor = SDL_calloc(1, sizeof(*cursor)); if (cursor) { cursor->driverdata = LoadCursor(NULL, IDC_ARROW); } else { SDL_OutOfMemory(); } return cursor; } static SDL_Cursor * WIN_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y) { /* msdn says cursor mask has to be padded out to word alignment. Not sure if that means machine word or WORD, but this handles either case. */ const size_t pad = (sizeof (size_t) * 8); /* 32 or 64, or whatever. */ SDL_Cursor *cursor; HICON hicon; HDC hdc; BITMAPV4HEADER bmh; LPVOID pixels; LPVOID maskbits; size_t maskbitslen; SDL_bool isstack; ICONINFO ii; SDL_zero(bmh); bmh.bV4Size = sizeof(bmh); bmh.bV4Width = surface->w; bmh.bV4Height = -surface->h; /* Invert the image */ bmh.bV4Planes = 1; bmh.bV4BitCount = 32; bmh.bV4V4Compression = BI_BITFIELDS; bmh.bV4AlphaMask = 0xFF000000; bmh.bV4RedMask = 0x00FF0000; bmh.bV4GreenMask = 0x0000FF00; bmh.bV4BlueMask = 0x000000FF; maskbitslen = ((surface->w + (pad - (surface->w % pad))) / 8) * surface->h; maskbits = SDL_small_alloc(Uint8, maskbitslen, &isstack); if (maskbits == NULL) { SDL_OutOfMemory(); return NULL; } /* AND the cursor against full bits: no change. We already have alpha. */ SDL_memset(maskbits, 0xFF, maskbitslen); hdc = GetDC(NULL); SDL_zero(ii); ii.fIcon = FALSE; ii.xHotspot = (DWORD)hot_x; ii.yHotspot = (DWORD)hot_y; ii.hbmColor = CreateDIBSection(hdc, (BITMAPINFO*)&bmh, DIB_RGB_COLORS, &pixels, NULL, 0); ii.hbmMask = CreateBitmap(surface->w, surface->h, 1, 1, maskbits); ReleaseDC(NULL, hdc); SDL_small_free(maskbits, isstack); SDL_assert(surface->format->format == SDL_PIXELFORMAT_ARGB8888); SDL_assert(surface->pitch == surface->w * 4); SDL_memcpy(pixels, surface->pixels, surface->h * surface->pitch); hicon = CreateIconIndirect(&ii); DeleteObject(ii.hbmColor); DeleteObject(ii.hbmMask); if (!hicon) { WIN_SetError("CreateIconIndirect()"); return NULL; } cursor = SDL_calloc(1, sizeof(*cursor)); if (cursor) { cursor->driverdata = hicon; } else { DestroyIcon(hicon); SDL_OutOfMemory(); } return cursor; } static SDL_Cursor * WIN_CreateSystemCursor(SDL_SystemCursor id) { SDL_Cursor *cursor; LPCTSTR name; switch(id) { default: SDL_assert(0); return NULL; case SDL_SYSTEM_CURSOR_ARROW: name = IDC_ARROW; break; case SDL_SYSTEM_CURSOR_IBEAM: name = IDC_IBEAM; break; case SDL_SYSTEM_CURSOR_WAIT: name = IDC_WAIT; break; case SDL_SYSTEM_CURSOR_CROSSHAIR: name = IDC_CROSS; break; case SDL_SYSTEM_CURSOR_WAITARROW: name = IDC_WAIT; break; case SDL_SYSTEM_CURSOR_SIZENWSE: name = IDC_SIZENWSE; break; case SDL_SYSTEM_CURSOR_SIZENESW: name = IDC_SIZENESW; break; case SDL_SYSTEM_CURSOR_SIZEWE: name = IDC_SIZEWE; break; case SDL_SYSTEM_CURSOR_SIZENS: name = IDC_SIZENS; break; case SDL_SYSTEM_CURSOR_SIZEALL: name = IDC_SIZEALL; break; case SDL_SYSTEM_CURSOR_NO: name = IDC_NO; break; case SDL_SYSTEM_CURSOR_HAND: name = IDC_HAND; break; } cursor = SDL_calloc(1, sizeof(*cursor)); if (cursor) { HICON hicon; hicon = LoadCursor(NULL, name); cursor->driverdata = hicon; } else { SDL_OutOfMemory(); } return cursor; } static void WIN_FreeCursor(SDL_Cursor * cursor) { HICON hicon = (HICON)cursor->driverdata; DestroyIcon(hicon); SDL_free(cursor); } static int WIN_ShowCursor(SDL_Cursor * cursor) { if (cursor) { SDL_cursor = (HCURSOR)cursor->driverdata; } else { SDL_cursor = NULL; } if (SDL_GetMouseFocus() != NULL) { SetCursor(SDL_cursor); } return 0; } static void WIN_WarpMouse(SDL_Window * window, int x, int y) { SDL_WindowData *data = (SDL_WindowData *)window->driverdata; HWND hwnd = data->hwnd; POINT pt; /* Don't warp the mouse while we're doing a modal interaction */ if (data->in_title_click || data->focus_click_pending) { return; } pt.x = x; pt.y = y; ClientToScreen(hwnd, &pt); SetCursorPos(pt.x, pt.y); } static int WIN_WarpMouseGlobal(int x, int y) { POINT pt; pt.x = x; pt.y = y; SetCursorPos(pt.x, pt.y); return 0; } static int WIN_SetRelativeMouseMode(SDL_bool enabled) { return ToggleRawInput(enabled); } static int WIN_CaptureMouse(SDL_Window *window) { if (!window) { SDL_Window *focusWin = SDL_GetKeyboardFocus(); if (focusWin) { WIN_OnWindowEnter(SDL_GetVideoDevice(), focusWin); /* make sure WM_MOUSELEAVE messages are (re)enabled. */ } } /* While we were thinking of SetCapture() when designing this API in SDL, we didn't count on the fact that SetCapture() only tracks while the left mouse button is held down! Instead, we listen for raw mouse input and manually query the mouse when it leaves the window. :/ */ return ToggleRawInput(window != NULL); } static Uint32 WIN_GetGlobalMouseState(int *x, int *y) { Uint32 retval = 0; POINT pt = { 0, 0 }; GetCursorPos(&pt); *x = (int) pt.x; *y = (int) pt.y; retval |= GetAsyncKeyState(VK_LBUTTON) & 0x8000 ? SDL_BUTTON_LMASK : 0; retval |= GetAsyncKeyState(VK_RBUTTON) & 0x8000 ? SDL_BUTTON_RMASK : 0; retval |= GetAsyncKeyState(VK_MBUTTON) & 0x8000 ? SDL_BUTTON_MMASK : 0; retval |= GetAsyncKeyState(VK_XBUTTON1) & 0x8000 ? SDL_BUTTON_X1MASK : 0; retval |= GetAsyncKeyState(VK_XBUTTON2) & 0x8000 ? SDL_BUTTON_X2MASK : 0; return retval; } void WIN_InitMouse(_THIS) { SDL_Mouse *mouse = SDL_GetMouse(); mouse->CreateCursor = WIN_CreateCursor; mouse->CreateSystemCursor = WIN_CreateSystemCursor; mouse->ShowCursor = WIN_ShowCursor; mouse->FreeCursor = WIN_FreeCursor; mouse->WarpMouse = WIN_WarpMouse; mouse->WarpMouseGlobal = WIN_WarpMouseGlobal; mouse->SetRelativeMouseMode = WIN_SetRelativeMouseMode; mouse->CaptureMouse = WIN_CaptureMouse; mouse->GetGlobalMouseState = WIN_GetGlobalMouseState; SDL_SetDefaultCursor(WIN_CreateDefaultCursor()); } void WIN_QuitMouse(_THIS) { if (rawInputEnableCount) { /* force RAWINPUT off here. */ rawInputEnableCount = 1; ToggleRawInput(SDL_FALSE); } } #endif /* SDL_VIDEO_DRIVER_WINDOWS */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsmouse.c
C
apache-2.0
8,781
/* 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_windowsmouse_h_ #define SDL_windowsmouse_h_ extern HCURSOR SDL_cursor; extern void WIN_InitMouse(_THIS); extern void WIN_QuitMouse(_THIS); #endif /* SDL_windowsmouse_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsmouse.h
C
apache-2.0
1,195
/* 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_VIDEO_DRIVER_WINDOWS #include "SDL_assert.h" #include "SDL_loadso.h" #include "SDL_windowsvideo.h" #include "SDL_windowsopengles.h" #include "SDL_hints.h" /* WGL implementation of SDL OpenGL support */ #if SDL_VIDEO_OPENGL_WGL #include "SDL_opengl.h" #define DEFAULT_OPENGL "OPENGL32.DLL" #ifndef WGL_ARB_create_context #define WGL_ARB_create_context #define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091 #define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092 #define WGL_CONTEXT_LAYER_PLANE_ARB 0x2093 #define WGL_CONTEXT_FLAGS_ARB 0x2094 #define WGL_CONTEXT_DEBUG_BIT_ARB 0x0001 #define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x0002 #ifndef WGL_ARB_create_context_profile #define WGL_ARB_create_context_profile #define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126 #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001 #define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002 #endif #ifndef WGL_ARB_create_context_robustness #define WGL_ARB_create_context_robustness #define WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB 0x00000004 #define WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB 0x8256 #define WGL_NO_RESET_NOTIFICATION_ARB 0x8261 #define WGL_LOSE_CONTEXT_ON_RESET_ARB 0x8252 #endif #endif #ifndef WGL_EXT_create_context_es2_profile #define WGL_EXT_create_context_es2_profile #define WGL_CONTEXT_ES2_PROFILE_BIT_EXT 0x00000004 #endif #ifndef WGL_EXT_create_context_es_profile #define WGL_EXT_create_context_es_profile #define WGL_CONTEXT_ES_PROFILE_BIT_EXT 0x00000004 #endif #ifndef WGL_ARB_framebuffer_sRGB #define WGL_ARB_framebuffer_sRGB #define WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20A9 #endif #ifndef WGL_ARB_context_flush_control #define WGL_ARB_context_flush_control #define WGL_CONTEXT_RELEASE_BEHAVIOR_ARB 0x2097 #define WGL_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB 0x0000 #define WGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB 0x2098 #endif #ifndef WGL_ARB_create_context_no_error #define WGL_ARB_create_context_no_error #define WGL_CONTEXT_OPENGL_NO_ERROR_ARB 0x31B3 #endif typedef HGLRC(APIENTRYP PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC, HGLRC hShareContext, const int *attribList); int WIN_GL_LoadLibrary(_THIS, const char *path) { void *handle; if (path == NULL) { path = SDL_getenv("SDL_OPENGL_LIBRARY"); } if (path == NULL) { path = DEFAULT_OPENGL; } _this->gl_config.dll_handle = SDL_LoadObject(path); if (!_this->gl_config.dll_handle) { return -1; } SDL_strlcpy(_this->gl_config.driver_path, path, SDL_arraysize(_this->gl_config.driver_path)); /* Allocate OpenGL memory */ _this->gl_data = (struct SDL_GLDriverData *) SDL_calloc(1, sizeof(struct SDL_GLDriverData)); if (!_this->gl_data) { return SDL_OutOfMemory(); } /* Load function pointers */ handle = _this->gl_config.dll_handle; _this->gl_data->wglGetProcAddress = (void *(WINAPI *) (const char *)) SDL_LoadFunction(handle, "wglGetProcAddress"); _this->gl_data->wglCreateContext = (HGLRC(WINAPI *) (HDC)) SDL_LoadFunction(handle, "wglCreateContext"); _this->gl_data->wglDeleteContext = (BOOL(WINAPI *) (HGLRC)) SDL_LoadFunction(handle, "wglDeleteContext"); _this->gl_data->wglMakeCurrent = (BOOL(WINAPI *) (HDC, HGLRC)) SDL_LoadFunction(handle, "wglMakeCurrent"); _this->gl_data->wglShareLists = (BOOL(WINAPI *) (HGLRC, HGLRC)) SDL_LoadFunction(handle, "wglShareLists"); if (!_this->gl_data->wglGetProcAddress || !_this->gl_data->wglCreateContext || !_this->gl_data->wglDeleteContext || !_this->gl_data->wglMakeCurrent) { return SDL_SetError("Could not retrieve OpenGL functions"); } /* XXX Too sleazy? WIN_GL_InitExtensions looks for certain OpenGL extensions via SDL_GL_DeduceMaxSupportedESProfile. This uses SDL_GL_ExtensionSupported which in turn calls SDL_GL_GetProcAddress. However SDL_GL_GetProcAddress will fail if the library is not loaded; it checks for gl_config.driver_loaded > 0. To avoid this test failing, increment driver_loaded around the call to WIN_GLInitExtensions. Successful loading of the library is normally indicated by SDL_GL_LoadLibrary incrementing driver_loaded immediately after this function returns 0 to it. Alternatives to this are: - moving SDL_GL_DeduceMaxSupportedESProfile to both the WIN and X11 platforms while adding a function equivalent to SDL_GL_ExtensionSupported but which directly calls glGetProcAddress(). Having 3 copies of the SDL_GL_ExtensionSupported makes this alternative unattractive. - moving SDL_GL_DeduceMaxSupportedESProfile to a new file shared by the WIN and X11 platforms while adding a function equivalent to SDL_GL_ExtensionSupported. This is unattractive due to the number of project files that will need updating, plus there will be 2 copies of the SDL_GL_ExtensionSupported code. - Add a private equivalent of SDL_GL_ExtensionSupported to SDL_video.c. - Move the call to WIN_GL_InitExtensions back to WIN_CreateWindow and add a flag to gl_data to avoid multiple calls to this expensive function. This is probably the least objectionable alternative if this increment/decrement trick is unacceptable. Note that the driver_loaded > 0 check needs to remain in SDL_GL_ExtensionSupported and SDL_GL_GetProcAddress as they are public API functions. */ ++_this->gl_config.driver_loaded; WIN_GL_InitExtensions(_this); --_this->gl_config.driver_loaded; return 0; } void * WIN_GL_GetProcAddress(_THIS, const char *proc) { void *func; /* This is to pick up extensions */ func = _this->gl_data->wglGetProcAddress(proc); if (!func) { /* This is probably a normal GL function */ func = GetProcAddress(_this->gl_config.dll_handle, proc); } return func; } void WIN_GL_UnloadLibrary(_THIS) { SDL_UnloadObject(_this->gl_config.dll_handle); _this->gl_config.dll_handle = NULL; /* Free OpenGL memory */ SDL_free(_this->gl_data); _this->gl_data = NULL; } static void WIN_GL_SetupPixelFormat(_THIS, PIXELFORMATDESCRIPTOR * pfd) { SDL_zerop(pfd); pfd->nSize = sizeof(*pfd); pfd->nVersion = 1; pfd->dwFlags = (PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL); if (_this->gl_config.double_buffer) { pfd->dwFlags |= PFD_DOUBLEBUFFER; } if (_this->gl_config.stereo) { pfd->dwFlags |= PFD_STEREO; } pfd->iLayerType = PFD_MAIN_PLANE; pfd->iPixelType = PFD_TYPE_RGBA; pfd->cRedBits = _this->gl_config.red_size; pfd->cGreenBits = _this->gl_config.green_size; pfd->cBlueBits = _this->gl_config.blue_size; pfd->cAlphaBits = _this->gl_config.alpha_size; if (_this->gl_config.buffer_size) { pfd->cColorBits = _this->gl_config.buffer_size - _this->gl_config.alpha_size; } else { pfd->cColorBits = (pfd->cRedBits + pfd->cGreenBits + pfd->cBlueBits); } pfd->cAccumRedBits = _this->gl_config.accum_red_size; pfd->cAccumGreenBits = _this->gl_config.accum_green_size; pfd->cAccumBlueBits = _this->gl_config.accum_blue_size; pfd->cAccumAlphaBits = _this->gl_config.accum_alpha_size; pfd->cAccumBits = (pfd->cAccumRedBits + pfd->cAccumGreenBits + pfd->cAccumBlueBits + pfd->cAccumAlphaBits); pfd->cDepthBits = _this->gl_config.depth_size; pfd->cStencilBits = _this->gl_config.stencil_size; } /* Choose the closest pixel format that meets or exceeds the target. FIXME: Should we weight any particular attribute over any other? */ static int WIN_GL_ChoosePixelFormat(HDC hdc, PIXELFORMATDESCRIPTOR * target) { PIXELFORMATDESCRIPTOR pfd; int count, index, best = 0; unsigned int dist, best_dist = ~0U; count = DescribePixelFormat(hdc, 1, sizeof(pfd), NULL); for (index = 1; index <= count; index++) { if (!DescribePixelFormat(hdc, index, sizeof(pfd), &pfd)) { continue; } if ((pfd.dwFlags & target->dwFlags) != target->dwFlags) { continue; } if (pfd.iLayerType != target->iLayerType) { continue; } if (pfd.iPixelType != target->iPixelType) { continue; } dist = 0; if (pfd.cColorBits < target->cColorBits) { continue; } else { dist += (pfd.cColorBits - target->cColorBits); } if (pfd.cRedBits < target->cRedBits) { continue; } else { dist += (pfd.cRedBits - target->cRedBits); } if (pfd.cGreenBits < target->cGreenBits) { continue; } else { dist += (pfd.cGreenBits - target->cGreenBits); } if (pfd.cBlueBits < target->cBlueBits) { continue; } else { dist += (pfd.cBlueBits - target->cBlueBits); } if (pfd.cAlphaBits < target->cAlphaBits) { continue; } else { dist += (pfd.cAlphaBits - target->cAlphaBits); } if (pfd.cAccumBits < target->cAccumBits) { continue; } else { dist += (pfd.cAccumBits - target->cAccumBits); } if (pfd.cAccumRedBits < target->cAccumRedBits) { continue; } else { dist += (pfd.cAccumRedBits - target->cAccumRedBits); } if (pfd.cAccumGreenBits < target->cAccumGreenBits) { continue; } else { dist += (pfd.cAccumGreenBits - target->cAccumGreenBits); } if (pfd.cAccumBlueBits < target->cAccumBlueBits) { continue; } else { dist += (pfd.cAccumBlueBits - target->cAccumBlueBits); } if (pfd.cAccumAlphaBits < target->cAccumAlphaBits) { continue; } else { dist += (pfd.cAccumAlphaBits - target->cAccumAlphaBits); } if (pfd.cDepthBits < target->cDepthBits) { continue; } else { dist += (pfd.cDepthBits - target->cDepthBits); } if (pfd.cStencilBits < target->cStencilBits) { continue; } else { dist += (pfd.cStencilBits - target->cStencilBits); } if (dist < best_dist) { best = index; best_dist = dist; } } return best; } static SDL_bool HasExtension(const char *extension, const char *extensions) { const char *start; const char *where, *terminator; /* Extension names should not have spaces. */ where = SDL_strchr(extension, ' '); if (where || *extension == '\0') return SDL_FALSE; if (!extensions) return SDL_FALSE; /* It takes a bit of care to be fool-proof about parsing the * OpenGL extensions string. Don't be fooled by sub-strings, * etc. */ start = extensions; for (;;) { where = SDL_strstr(start, extension); if (!where) break; terminator = where + SDL_strlen(extension); if (where == start || *(where - 1) == ' ') if (*terminator == ' ' || *terminator == '\0') return SDL_TRUE; start = terminator; } return SDL_FALSE; } void WIN_GL_InitExtensions(_THIS) { const char *(WINAPI * wglGetExtensionsStringARB) (HDC) = 0; const char *extensions; HWND hwnd; HDC hdc; HGLRC hglrc; PIXELFORMATDESCRIPTOR pfd; if (!_this->gl_data) { return; } hwnd = CreateWindow(SDL_Appname, SDL_Appname, (WS_POPUP | WS_DISABLED), 0, 0, 10, 10, NULL, NULL, SDL_Instance, NULL); if (!hwnd) { return; } WIN_PumpEvents(_this); hdc = GetDC(hwnd); WIN_GL_SetupPixelFormat(_this, &pfd); SetPixelFormat(hdc, ChoosePixelFormat(hdc, &pfd), &pfd); hglrc = _this->gl_data->wglCreateContext(hdc); if (!hglrc) { return; } _this->gl_data->wglMakeCurrent(hdc, hglrc); wglGetExtensionsStringARB = (const char *(WINAPI *) (HDC)) _this->gl_data->wglGetProcAddress("wglGetExtensionsStringARB"); if (wglGetExtensionsStringARB) { extensions = wglGetExtensionsStringARB(hdc); } else { extensions = NULL; } /* Check for WGL_ARB_pixel_format */ _this->gl_data->HAS_WGL_ARB_pixel_format = SDL_FALSE; if (HasExtension("WGL_ARB_pixel_format", extensions)) { _this->gl_data->wglChoosePixelFormatARB = (BOOL(WINAPI *) (HDC, const int *, const FLOAT *, UINT, int *, UINT *)) WIN_GL_GetProcAddress(_this, "wglChoosePixelFormatARB"); _this->gl_data->wglGetPixelFormatAttribivARB = (BOOL(WINAPI *) (HDC, int, int, UINT, const int *, int *)) WIN_GL_GetProcAddress(_this, "wglGetPixelFormatAttribivARB"); if ((_this->gl_data->wglChoosePixelFormatARB != NULL) && (_this->gl_data->wglGetPixelFormatAttribivARB != NULL)) { _this->gl_data->HAS_WGL_ARB_pixel_format = SDL_TRUE; } } /* Check for WGL_EXT_swap_control */ _this->gl_data->HAS_WGL_EXT_swap_control_tear = SDL_FALSE; if (HasExtension("WGL_EXT_swap_control", extensions)) { _this->gl_data->wglSwapIntervalEXT = WIN_GL_GetProcAddress(_this, "wglSwapIntervalEXT"); _this->gl_data->wglGetSwapIntervalEXT = WIN_GL_GetProcAddress(_this, "wglGetSwapIntervalEXT"); if (HasExtension("WGL_EXT_swap_control_tear", extensions)) { _this->gl_data->HAS_WGL_EXT_swap_control_tear = SDL_TRUE; } } else { _this->gl_data->wglSwapIntervalEXT = NULL; _this->gl_data->wglGetSwapIntervalEXT = NULL; } /* Check for WGL_EXT_create_context_es2_profile */ if (HasExtension("WGL_EXT_create_context_es2_profile", extensions)) { SDL_GL_DeduceMaxSupportedESProfile( &_this->gl_data->es_profile_max_supported_version.major, &_this->gl_data->es_profile_max_supported_version.minor ); } /* Check for WGL_ARB_context_flush_control */ if (HasExtension("WGL_ARB_context_flush_control", extensions)) { _this->gl_data->HAS_WGL_ARB_context_flush_control = SDL_TRUE; } /* Check for WGL_ARB_create_context_robustness */ if (HasExtension("WGL_ARB_create_context_robustness", extensions)) { _this->gl_data->HAS_WGL_ARB_create_context_robustness = SDL_TRUE; } /* Check for WGL_ARB_create_context_no_error */ if (HasExtension("WGL_ARB_create_context_no_error", extensions)) { _this->gl_data->HAS_WGL_ARB_create_context_no_error = SDL_TRUE; } _this->gl_data->wglMakeCurrent(hdc, NULL); _this->gl_data->wglDeleteContext(hglrc); ReleaseDC(hwnd, hdc); DestroyWindow(hwnd); WIN_PumpEvents(_this); } static int WIN_GL_ChoosePixelFormatARB(_THIS, int *iAttribs, float *fAttribs) { HWND hwnd; HDC hdc; PIXELFORMATDESCRIPTOR pfd; HGLRC hglrc; int pixel_format = 0; unsigned int matching; hwnd = CreateWindow(SDL_Appname, SDL_Appname, (WS_POPUP | WS_DISABLED), 0, 0, 10, 10, NULL, NULL, SDL_Instance, NULL); WIN_PumpEvents(_this); hdc = GetDC(hwnd); WIN_GL_SetupPixelFormat(_this, &pfd); SetPixelFormat(hdc, ChoosePixelFormat(hdc, &pfd), &pfd); hglrc = _this->gl_data->wglCreateContext(hdc); if (hglrc) { _this->gl_data->wglMakeCurrent(hdc, hglrc); if (_this->gl_data->HAS_WGL_ARB_pixel_format) { _this->gl_data->wglChoosePixelFormatARB(hdc, iAttribs, fAttribs, 1, &pixel_format, &matching); } _this->gl_data->wglMakeCurrent(hdc, NULL); _this->gl_data->wglDeleteContext(hglrc); } ReleaseDC(hwnd, hdc); DestroyWindow(hwnd); WIN_PumpEvents(_this); return pixel_format; } /* actual work of WIN_GL_SetupWindow() happens here. */ static int WIN_GL_SetupWindowInternal(_THIS, SDL_Window * window) { HDC hdc = ((SDL_WindowData *) window->driverdata)->hdc; PIXELFORMATDESCRIPTOR pfd; int pixel_format = 0; int iAttribs[64]; int *iAttr; int *iAccelAttr; float fAttribs[1] = { 0 }; WIN_GL_SetupPixelFormat(_this, &pfd); /* setup WGL_ARB_pixel_format attribs */ iAttr = &iAttribs[0]; *iAttr++ = WGL_DRAW_TO_WINDOW_ARB; *iAttr++ = GL_TRUE; *iAttr++ = WGL_RED_BITS_ARB; *iAttr++ = _this->gl_config.red_size; *iAttr++ = WGL_GREEN_BITS_ARB; *iAttr++ = _this->gl_config.green_size; *iAttr++ = WGL_BLUE_BITS_ARB; *iAttr++ = _this->gl_config.blue_size; if (_this->gl_config.alpha_size) { *iAttr++ = WGL_ALPHA_BITS_ARB; *iAttr++ = _this->gl_config.alpha_size; } *iAttr++ = WGL_DOUBLE_BUFFER_ARB; *iAttr++ = _this->gl_config.double_buffer; *iAttr++ = WGL_DEPTH_BITS_ARB; *iAttr++ = _this->gl_config.depth_size; if (_this->gl_config.stencil_size) { *iAttr++ = WGL_STENCIL_BITS_ARB; *iAttr++ = _this->gl_config.stencil_size; } if (_this->gl_config.accum_red_size) { *iAttr++ = WGL_ACCUM_RED_BITS_ARB; *iAttr++ = _this->gl_config.accum_red_size; } if (_this->gl_config.accum_green_size) { *iAttr++ = WGL_ACCUM_GREEN_BITS_ARB; *iAttr++ = _this->gl_config.accum_green_size; } if (_this->gl_config.accum_blue_size) { *iAttr++ = WGL_ACCUM_BLUE_BITS_ARB; *iAttr++ = _this->gl_config.accum_blue_size; } if (_this->gl_config.accum_alpha_size) { *iAttr++ = WGL_ACCUM_ALPHA_BITS_ARB; *iAttr++ = _this->gl_config.accum_alpha_size; } if (_this->gl_config.stereo) { *iAttr++ = WGL_STEREO_ARB; *iAttr++ = GL_TRUE; } if (_this->gl_config.multisamplebuffers) { *iAttr++ = WGL_SAMPLE_BUFFERS_ARB; *iAttr++ = _this->gl_config.multisamplebuffers; } if (_this->gl_config.multisamplesamples) { *iAttr++ = WGL_SAMPLES_ARB; *iAttr++ = _this->gl_config.multisamplesamples; } if (_this->gl_config.framebuffer_srgb_capable) { *iAttr++ = WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB; *iAttr++ = _this->gl_config.framebuffer_srgb_capable; } /* We always choose either FULL or NO accel on Windows, because of flaky drivers. If the app didn't specify, we use FULL, because that's probably what they wanted (and if you didn't care and got FULL, that's a perfectly valid result in any case). */ *iAttr++ = WGL_ACCELERATION_ARB; iAccelAttr = iAttr; if (_this->gl_config.accelerated) { *iAttr++ = WGL_FULL_ACCELERATION_ARB; } else { *iAttr++ = WGL_NO_ACCELERATION_ARB; } *iAttr = 0; /* Choose and set the closest available pixel format */ pixel_format = WIN_GL_ChoosePixelFormatARB(_this, iAttribs, fAttribs); /* App said "don't care about accel" and FULL accel failed. Try NO. */ if ( ( !pixel_format ) && ( _this->gl_config.accelerated < 0 ) ) { *iAccelAttr = WGL_NO_ACCELERATION_ARB; pixel_format = WIN_GL_ChoosePixelFormatARB(_this, iAttribs, fAttribs); *iAccelAttr = WGL_FULL_ACCELERATION_ARB; /* if we try again. */ } if (!pixel_format) { pixel_format = WIN_GL_ChoosePixelFormat(hdc, &pfd); } if (!pixel_format) { return SDL_SetError("No matching GL pixel format available"); } if (!SetPixelFormat(hdc, pixel_format, &pfd)) { return WIN_SetError("SetPixelFormat()"); } return 0; } int WIN_GL_SetupWindow(_THIS, SDL_Window * window) { /* The current context is lost in here; save it and reset it. */ SDL_Window *current_win = SDL_GL_GetCurrentWindow(); SDL_GLContext current_ctx = SDL_GL_GetCurrentContext(); const int retval = WIN_GL_SetupWindowInternal(_this, window); WIN_GL_MakeCurrent(_this, current_win, current_ctx); return retval; } SDL_bool WIN_GL_UseEGL(_THIS) { SDL_assert(_this->gl_data != NULL); SDL_assert(_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES); return (SDL_GetHintBoolean(SDL_HINT_OPENGL_ES_DRIVER, SDL_FALSE) || _this->gl_config.major_version == 1 /* No WGL extension for OpenGL ES 1.x profiles. */ || _this->gl_config.major_version > _this->gl_data->es_profile_max_supported_version.major || (_this->gl_config.major_version == _this->gl_data->es_profile_max_supported_version.major && _this->gl_config.minor_version > _this->gl_data->es_profile_max_supported_version.minor)); } SDL_GLContext WIN_GL_CreateContext(_THIS, SDL_Window * window) { HDC hdc = ((SDL_WindowData *) window->driverdata)->hdc; HGLRC context, share_context; if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES && WIN_GL_UseEGL(_this)) { #if SDL_VIDEO_OPENGL_EGL /* Switch to EGL based functions */ WIN_GL_UnloadLibrary(_this); _this->GL_LoadLibrary = WIN_GLES_LoadLibrary; _this->GL_GetProcAddress = WIN_GLES_GetProcAddress; _this->GL_UnloadLibrary = WIN_GLES_UnloadLibrary; _this->GL_CreateContext = WIN_GLES_CreateContext; _this->GL_MakeCurrent = WIN_GLES_MakeCurrent; _this->GL_SetSwapInterval = WIN_GLES_SetSwapInterval; _this->GL_GetSwapInterval = WIN_GLES_GetSwapInterval; _this->GL_SwapWindow = WIN_GLES_SwapWindow; _this->GL_DeleteContext = WIN_GLES_DeleteContext; if (WIN_GLES_LoadLibrary(_this, NULL) != 0) { return NULL; } return WIN_GLES_CreateContext(_this, window); #else SDL_SetError("SDL not configured with EGL support"); return NULL; #endif } if (_this->gl_config.share_with_current_context) { share_context = (HGLRC)SDL_GL_GetCurrentContext(); } else { share_context = 0; } if (_this->gl_config.major_version < 3 && _this->gl_config.profile_mask == 0 && _this->gl_config.flags == 0) { /* Create legacy context */ context = _this->gl_data->wglCreateContext(hdc); if( share_context != 0 ) { _this->gl_data->wglShareLists(share_context, context); } } else { PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB; HGLRC temp_context = _this->gl_data->wglCreateContext(hdc); if (!temp_context) { SDL_SetError("Could not create GL context"); return NULL; } /* Make the context current */ if (WIN_GL_MakeCurrent(_this, window, temp_context) < 0) { WIN_GL_DeleteContext(_this, temp_context); return NULL; } wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) _this->gl_data-> wglGetProcAddress("wglCreateContextAttribsARB"); if (!wglCreateContextAttribsARB) { SDL_SetError("GL 3.x is not supported"); context = temp_context; } else { int attribs[15]; /* max 14 attributes plus terminator */ int iattr = 0; attribs[iattr++] = WGL_CONTEXT_MAJOR_VERSION_ARB; attribs[iattr++] = _this->gl_config.major_version; attribs[iattr++] = WGL_CONTEXT_MINOR_VERSION_ARB; attribs[iattr++] = _this->gl_config.minor_version; /* SDL profile bits match WGL profile bits */ if (_this->gl_config.profile_mask != 0) { attribs[iattr++] = WGL_CONTEXT_PROFILE_MASK_ARB; attribs[iattr++] = _this->gl_config.profile_mask; } /* SDL flags match WGL flags */ if (_this->gl_config.flags != 0) { attribs[iattr++] = WGL_CONTEXT_FLAGS_ARB; attribs[iattr++] = _this->gl_config.flags; } /* only set if wgl extension is available */ if (_this->gl_data->HAS_WGL_ARB_context_flush_control) { attribs[iattr++] = WGL_CONTEXT_RELEASE_BEHAVIOR_ARB; attribs[iattr++] = _this->gl_config.release_behavior ? WGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB : WGL_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB; } /* only set if wgl extension is available */ if (_this->gl_data->HAS_WGL_ARB_create_context_robustness) { attribs[iattr++] = WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB; attribs[iattr++] = _this->gl_config.reset_notification ? WGL_LOSE_CONTEXT_ON_RESET_ARB : WGL_NO_RESET_NOTIFICATION_ARB; } /* only set if wgl extension is available */ if (_this->gl_data->HAS_WGL_ARB_create_context_no_error) { attribs[iattr++] = WGL_CONTEXT_OPENGL_NO_ERROR_ARB; attribs[iattr++] = _this->gl_config.no_error; } attribs[iattr++] = 0; /* Create the GL 3.x context */ context = wglCreateContextAttribsARB(hdc, share_context, attribs); /* Delete the GL 2.x context */ _this->gl_data->wglDeleteContext(temp_context); } } if (!context) { WIN_SetError("Could not create GL context"); return NULL; } if (WIN_GL_MakeCurrent(_this, window, context) < 0) { WIN_GL_DeleteContext(_this, context); return NULL; } return context; } int WIN_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context) { HDC hdc; if (!_this->gl_data) { return SDL_SetError("OpenGL not initialized"); } /* sanity check that higher level handled this. */ SDL_assert(window || (!window && !context)); /* Some Windows drivers freak out if hdc is NULL, even when context is NULL, against spec. Since hdc is _supposed_ to be ignored if context is NULL, we either use the current GL window, or do nothing if we already have no current context. */ if (!window) { window = SDL_GL_GetCurrentWindow(); if (!window) { SDL_assert(SDL_GL_GetCurrentContext() == NULL); return 0; /* already done. */ } } hdc = ((SDL_WindowData *) window->driverdata)->hdc; if (!_this->gl_data->wglMakeCurrent(hdc, (HGLRC) context)) { return WIN_SetError("wglMakeCurrent()"); } return 0; } int WIN_GL_SetSwapInterval(_THIS, int interval) { if ((interval < 0) && (!_this->gl_data->HAS_WGL_EXT_swap_control_tear)) { return SDL_SetError("Negative swap interval unsupported in this GL"); } else if (_this->gl_data->wglSwapIntervalEXT) { if (_this->gl_data->wglSwapIntervalEXT(interval) != TRUE) { return WIN_SetError("wglSwapIntervalEXT()"); } } else { return SDL_Unsupported(); } return 0; } int WIN_GL_GetSwapInterval(_THIS) { int retval = 0; if (_this->gl_data->wglGetSwapIntervalEXT) { retval = _this->gl_data->wglGetSwapIntervalEXT(); } return retval; } int WIN_GL_SwapWindow(_THIS, SDL_Window * window) { HDC hdc = ((SDL_WindowData *) window->driverdata)->hdc; if (!SwapBuffers(hdc)) { return WIN_SetError("SwapBuffers()"); } return 0; } void WIN_GL_DeleteContext(_THIS, SDL_GLContext context) { if (!_this->gl_data) { return; } _this->gl_data->wglDeleteContext((HGLRC) context); } SDL_bool WIN_GL_SetPixelFormatFrom(_THIS, SDL_Window * fromWindow, SDL_Window * toWindow) { HDC hfromdc = ((SDL_WindowData *) fromWindow->driverdata)->hdc; HDC htodc = ((SDL_WindowData *) toWindow->driverdata)->hdc; BOOL result; /* get the pixel format of the fromWindow */ int pixel_format = GetPixelFormat(hfromdc); PIXELFORMATDESCRIPTOR pfd; SDL_memset(&pfd, 0, sizeof(pfd)); DescribePixelFormat(hfromdc, pixel_format, sizeof(pfd), &pfd); /* set the pixel format of the toWindow */ result = SetPixelFormat(htodc, pixel_format, &pfd); return result ? SDL_TRUE : SDL_FALSE; } #endif /* SDL_VIDEO_OPENGL_WGL */ #endif /* SDL_VIDEO_DRIVER_WINDOWS */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsopengl.c
C
apache-2.0
29,870
/* 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_windowsopengl_h_ #define SDL_windowsopengl_h_ #if SDL_VIDEO_OPENGL_WGL struct SDL_GLDriverData { SDL_bool HAS_WGL_ARB_pixel_format; SDL_bool HAS_WGL_EXT_swap_control_tear; SDL_bool HAS_WGL_ARB_context_flush_control; SDL_bool HAS_WGL_ARB_create_context_robustness; SDL_bool HAS_WGL_ARB_create_context_no_error; /* Max version of OpenGL ES context that can be created if the implementation supports WGL_EXT_create_context_es2_profile. major = minor = 0 when unsupported. */ struct { int major; int minor; } es_profile_max_supported_version; void *(WINAPI * wglGetProcAddress) (const char *proc); HGLRC(WINAPI * wglCreateContext) (HDC hdc); BOOL(WINAPI * wglDeleteContext) (HGLRC hglrc); BOOL(WINAPI * wglMakeCurrent) (HDC hdc, HGLRC hglrc); BOOL(WINAPI * wglShareLists) (HGLRC hglrc1, HGLRC hglrc2); BOOL(WINAPI * wglChoosePixelFormatARB) (HDC hdc, const int *piAttribIList, const FLOAT * pfAttribFList, UINT nMaxFormats, int *piFormats, UINT * nNumFormats); BOOL(WINAPI * wglGetPixelFormatAttribivARB) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues); BOOL (WINAPI * wglSwapIntervalEXT) (int interval); int (WINAPI * wglGetSwapIntervalEXT) (void); }; /* OpenGL functions */ extern int WIN_GL_LoadLibrary(_THIS, const char *path); extern void *WIN_GL_GetProcAddress(_THIS, const char *proc); extern void WIN_GL_UnloadLibrary(_THIS); extern SDL_bool WIN_GL_UseEGL(_THIS); extern int WIN_GL_SetupWindow(_THIS, SDL_Window * window); extern SDL_GLContext WIN_GL_CreateContext(_THIS, SDL_Window * window); extern int WIN_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context); extern int WIN_GL_SetSwapInterval(_THIS, int interval); extern int WIN_GL_GetSwapInterval(_THIS); extern int WIN_GL_SwapWindow(_THIS, SDL_Window * window); extern void WIN_GL_DeleteContext(_THIS, SDL_GLContext context); extern void WIN_GL_InitExtensions(_THIS); extern SDL_bool WIN_GL_SetPixelFormatFrom(_THIS, SDL_Window * fromWindow, SDL_Window * toWindow); #ifndef WGL_ARB_pixel_format #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000 #define WGL_DRAW_TO_WINDOW_ARB 0x2001 #define WGL_DRAW_TO_BITMAP_ARB 0x2002 #define WGL_ACCELERATION_ARB 0x2003 #define WGL_NEED_PALETTE_ARB 0x2004 #define WGL_NEED_SYSTEM_PALETTE_ARB 0x2005 #define WGL_SWAP_LAYER_BUFFERS_ARB 0x2006 #define WGL_SWAP_METHOD_ARB 0x2007 #define WGL_NUMBER_OVERLAYS_ARB 0x2008 #define WGL_NUMBER_UNDERLAYS_ARB 0x2009 #define WGL_TRANSPARENT_ARB 0x200A #define WGL_TRANSPARENT_RED_VALUE_ARB 0x2037 #define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038 #define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039 #define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A #define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B #define WGL_SHARE_DEPTH_ARB 0x200C #define WGL_SHARE_STENCIL_ARB 0x200D #define WGL_SHARE_ACCUM_ARB 0x200E #define WGL_SUPPORT_GDI_ARB 0x200F #define WGL_SUPPORT_OPENGL_ARB 0x2010 #define WGL_DOUBLE_BUFFER_ARB 0x2011 #define WGL_STEREO_ARB 0x2012 #define WGL_PIXEL_TYPE_ARB 0x2013 #define WGL_COLOR_BITS_ARB 0x2014 #define WGL_RED_BITS_ARB 0x2015 #define WGL_RED_SHIFT_ARB 0x2016 #define WGL_GREEN_BITS_ARB 0x2017 #define WGL_GREEN_SHIFT_ARB 0x2018 #define WGL_BLUE_BITS_ARB 0x2019 #define WGL_BLUE_SHIFT_ARB 0x201A #define WGL_ALPHA_BITS_ARB 0x201B #define WGL_ALPHA_SHIFT_ARB 0x201C #define WGL_ACCUM_BITS_ARB 0x201D #define WGL_ACCUM_RED_BITS_ARB 0x201E #define WGL_ACCUM_GREEN_BITS_ARB 0x201F #define WGL_ACCUM_BLUE_BITS_ARB 0x2020 #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021 #define WGL_DEPTH_BITS_ARB 0x2022 #define WGL_STENCIL_BITS_ARB 0x2023 #define WGL_AUX_BUFFERS_ARB 0x2024 #define WGL_NO_ACCELERATION_ARB 0x2025 #define WGL_GENERIC_ACCELERATION_ARB 0x2026 #define WGL_FULL_ACCELERATION_ARB 0x2027 #define WGL_SWAP_EXCHANGE_ARB 0x2028 #define WGL_SWAP_COPY_ARB 0x2029 #define WGL_SWAP_UNDEFINED_ARB 0x202A #define WGL_TYPE_RGBA_ARB 0x202B #define WGL_TYPE_COLORINDEX_ARB 0x202C #endif #ifndef WGL_ARB_multisample #define WGL_SAMPLE_BUFFERS_ARB 0x2041 #define WGL_SAMPLES_ARB 0x2042 #endif #endif /* SDL_VIDEO_OPENGL_WGL */ #endif /* SDL_windowsopengl_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsopengl.h
C
apache-2.0
6,061
/* 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_VIDEO_DRIVER_WINDOWS && SDL_VIDEO_OPENGL_EGL #include "SDL_windowsvideo.h" #include "SDL_windowsopengles.h" #include "SDL_windowsopengl.h" /* EGL implementation of SDL OpenGL support */ int WIN_GLES_LoadLibrary(_THIS, const char *path) { /* If the profile requested is not GL ES, switch over to WIN_GL functions */ if (_this->gl_config.profile_mask != SDL_GL_CONTEXT_PROFILE_ES) { #if SDL_VIDEO_OPENGL_WGL WIN_GLES_UnloadLibrary(_this); _this->GL_LoadLibrary = WIN_GL_LoadLibrary; _this->GL_GetProcAddress = WIN_GL_GetProcAddress; _this->GL_UnloadLibrary = WIN_GL_UnloadLibrary; _this->GL_CreateContext = WIN_GL_CreateContext; _this->GL_MakeCurrent = WIN_GL_MakeCurrent; _this->GL_SetSwapInterval = WIN_GL_SetSwapInterval; _this->GL_GetSwapInterval = WIN_GL_GetSwapInterval; _this->GL_SwapWindow = WIN_GL_SwapWindow; _this->GL_DeleteContext = WIN_GL_DeleteContext; return WIN_GL_LoadLibrary(_this, path); #else return SDL_SetError("SDL not configured with OpenGL/WGL support"); #endif } if (_this->egl_data == NULL) { return SDL_EGL_LoadLibrary(_this, NULL, EGL_DEFAULT_DISPLAY, 0); } return 0; } SDL_GLContext WIN_GLES_CreateContext(_THIS, SDL_Window * window) { SDL_GLContext context; SDL_WindowData *data = (SDL_WindowData *)window->driverdata; #if SDL_VIDEO_OPENGL_WGL if (_this->gl_config.profile_mask != SDL_GL_CONTEXT_PROFILE_ES) { /* Switch to WGL based functions */ WIN_GLES_UnloadLibrary(_this); _this->GL_LoadLibrary = WIN_GL_LoadLibrary; _this->GL_GetProcAddress = WIN_GL_GetProcAddress; _this->GL_UnloadLibrary = WIN_GL_UnloadLibrary; _this->GL_CreateContext = WIN_GL_CreateContext; _this->GL_MakeCurrent = WIN_GL_MakeCurrent; _this->GL_SetSwapInterval = WIN_GL_SetSwapInterval; _this->GL_GetSwapInterval = WIN_GL_GetSwapInterval; _this->GL_SwapWindow = WIN_GL_SwapWindow; _this->GL_DeleteContext = WIN_GL_DeleteContext; if (WIN_GL_LoadLibrary(_this, NULL) != 0) { return NULL; } return WIN_GL_CreateContext(_this, window); } #endif context = SDL_EGL_CreateContext(_this, data->egl_surface); return context; } void WIN_GLES_DeleteContext(_THIS, SDL_GLContext context) { SDL_EGL_DeleteContext(_this, context); WIN_GLES_UnloadLibrary(_this); } SDL_EGL_SwapWindow_impl(WIN) SDL_EGL_MakeCurrent_impl(WIN) int WIN_GLES_SetupWindow(_THIS, SDL_Window * window) { /* The current context is lost in here; save it and reset it. */ SDL_WindowData *windowdata = (SDL_WindowData *) window->driverdata; SDL_Window *current_win = SDL_GL_GetCurrentWindow(); SDL_GLContext current_ctx = SDL_GL_GetCurrentContext(); if (_this->egl_data == NULL) { if (SDL_EGL_LoadLibrary(_this, NULL, EGL_DEFAULT_DISPLAY, 0) < 0) { SDL_EGL_UnloadLibrary(_this); return -1; } } /* Create the GLES window surface */ windowdata->egl_surface = SDL_EGL_CreateSurface(_this, (NativeWindowType)windowdata->hwnd); if (windowdata->egl_surface == EGL_NO_SURFACE) { return SDL_SetError("Could not create GLES window surface"); } return WIN_GLES_MakeCurrent(_this, current_win, current_ctx); } #endif /* SDL_VIDEO_DRIVER_WINDOWS && SDL_VIDEO_OPENGL_EGL */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsopengles.c
C
apache-2.0
4,445
/* 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_winopengles_h_ #define SDL_winopengles_h_ #if SDL_VIDEO_OPENGL_EGL #include "../SDL_sysvideo.h" #include "../SDL_egl_c.h" /* OpenGLES functions */ #define WIN_GLES_GetAttribute SDL_EGL_GetAttribute #define WIN_GLES_GetProcAddress SDL_EGL_GetProcAddress #define WIN_GLES_UnloadLibrary SDL_EGL_UnloadLibrary #define WIN_GLES_GetSwapInterval SDL_EGL_GetSwapInterval #define WIN_GLES_SetSwapInterval SDL_EGL_SetSwapInterval extern int WIN_GLES_LoadLibrary(_THIS, const char *path); extern SDL_GLContext WIN_GLES_CreateContext(_THIS, SDL_Window * window); extern int WIN_GLES_SwapWindow(_THIS, SDL_Window * window); extern int WIN_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context); extern void WIN_GLES_DeleteContext(_THIS, SDL_GLContext context); extern int WIN_GLES_SetupWindow(_THIS, SDL_Window * window); #endif /* SDL_VIDEO_OPENGL_EGL */ #endif /* SDL_winopengles_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsopengles.h
C
apache-2.0
1,914
/* 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_VIDEO_DRIVER_WINDOWS #include "SDL_assert.h" #include "SDL_windowsshape.h" #include "SDL_windowsvideo.h" SDL_WindowShaper* Win32_CreateShaper(SDL_Window * window) { int resized_properly; SDL_WindowShaper* result = (SDL_WindowShaper *)SDL_malloc(sizeof(SDL_WindowShaper)); result->window = window; result->mode.mode = ShapeModeDefault; result->mode.parameters.binarizationCutoff = 1; result->userx = result->usery = 0; result->hasshape = SDL_FALSE; result->driverdata = (SDL_ShapeData*)SDL_malloc(sizeof(SDL_ShapeData)); ((SDL_ShapeData*)result->driverdata)->mask_tree = NULL; /* Put some driver-data here. */ window->shaper = result; resized_properly = Win32_ResizeWindowShape(window); if (resized_properly != 0) return NULL; return result; } static void CombineRectRegions(SDL_ShapeTree* node,void* closure) { HRGN mask_region = *((HRGN*)closure),temp_region = NULL; if(node->kind == OpaqueShape) { /* Win32 API regions exclude their outline, so we widen the region by one pixel in each direction to include the real outline. */ temp_region = CreateRectRgn(node->data.shape.x,node->data.shape.y,node->data.shape.x + node->data.shape.w + 1,node->data.shape.y + node->data.shape.h + 1); if(mask_region != NULL) { CombineRgn(mask_region,mask_region,temp_region,RGN_OR); DeleteObject(temp_region); } else *((HRGN*)closure) = temp_region; } } int Win32_SetWindowShape(SDL_WindowShaper *shaper,SDL_Surface *shape,SDL_WindowShapeMode *shape_mode) { SDL_ShapeData *data; HRGN mask_region = NULL; if( (shaper == NULL) || (shape == NULL) || ((shape->format->Amask == 0) && (shape_mode->mode != ShapeModeColorKey)) || (shape->w != shaper->window->w) || (shape->h != shaper->window->h) ) { return SDL_INVALID_SHAPE_ARGUMENT; } data = (SDL_ShapeData*)shaper->driverdata; if(data->mask_tree != NULL) SDL_FreeShapeTree(&data->mask_tree); data->mask_tree = SDL_CalculateShapeTree(*shape_mode,shape); SDL_TraverseShapeTree(data->mask_tree,&CombineRectRegions,&mask_region); SDL_assert(mask_region != NULL); SetWindowRgn(((SDL_WindowData *)(shaper->window->driverdata))->hwnd, mask_region, TRUE); return 0; } int Win32_ResizeWindowShape(SDL_Window *window) { SDL_ShapeData* data; if (window == NULL) return -1; data = (SDL_ShapeData *)window->shaper->driverdata; if (data == NULL) return -1; if(data->mask_tree != NULL) SDL_FreeShapeTree(&data->mask_tree); if(window->shaper->hasshape == SDL_TRUE) { window->shaper->userx = window->x; window->shaper->usery = window->y; SDL_SetWindowPosition(window,-1000,-1000); } return 0; } #endif /* SDL_VIDEO_DRIVER_WINDOWS */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsshape.c
C
apache-2.0
3,871
/* 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_windowsshape_h_ #define SDL_windowsshape_h_ #include "SDL_video.h" #include "SDL_shape.h" #include "../SDL_sysvideo.h" #include "../SDL_shape_internals.h" typedef struct { SDL_ShapeTree *mask_tree; } SDL_ShapeData; extern SDL_WindowShaper* Win32_CreateShaper(SDL_Window * window); extern int Win32_SetWindowShape(SDL_WindowShaper *shaper,SDL_Surface *shape,SDL_WindowShapeMode *shape_mode); extern int Win32_ResizeWindowShape(SDL_Window *window); #endif /* SDL_windowsshape_h_ */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsshape.h
C
apache-2.0
1,473
/* 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 <pshpack1.h> typedef HRESULT(CALLBACK *PFTASKDIALOGCALLBACK)(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, LONG_PTR lpRefData); enum _TASKDIALOG_FLAGS { TDF_ENABLE_HYPERLINKS = 0x0001, TDF_USE_HICON_MAIN = 0x0002, TDF_USE_HICON_FOOTER = 0x0004, TDF_ALLOW_DIALOG_CANCELLATION = 0x0008, TDF_USE_COMMAND_LINKS = 0x0010, TDF_USE_COMMAND_LINKS_NO_ICON = 0x0020, TDF_EXPAND_FOOTER_AREA = 0x0040, TDF_EXPANDED_BY_DEFAULT = 0x0080, TDF_VERIFICATION_FLAG_CHECKED = 0x0100, TDF_SHOW_PROGRESS_BAR = 0x0200, TDF_SHOW_MARQUEE_PROGRESS_BAR = 0x0400, TDF_CALLBACK_TIMER = 0x0800, TDF_POSITION_RELATIVE_TO_WINDOW = 0x1000, TDF_RTL_LAYOUT = 0x2000, TDF_NO_DEFAULT_RADIO_BUTTON = 0x4000, TDF_CAN_BE_MINIMIZED = 0x8000, //#if (NTDDI_VERSION >= NTDDI_WIN8) TDF_NO_SET_FOREGROUND = 0x00010000, // Don't call SetForegroundWindow() when activating the dialog //#endif // (NTDDI_VERSION >= NTDDI_WIN8) TDF_SIZE_TO_CONTENT = 0x01000000 // used by ShellMessageBox to emulate MessageBox sizing behavior }; typedef int TASKDIALOG_FLAGS; // Note: _TASKDIALOG_FLAGS is an int typedef enum _TASKDIALOG_MESSAGES { TDM_NAVIGATE_PAGE = WM_USER + 101, TDM_CLICK_BUTTON = WM_USER + 102, // wParam = Button ID TDM_SET_MARQUEE_PROGRESS_BAR = WM_USER + 103, // wParam = 0 (nonMarque) wParam != 0 (Marquee) TDM_SET_PROGRESS_BAR_STATE = WM_USER + 104, // wParam = new progress state TDM_SET_PROGRESS_BAR_RANGE = WM_USER + 105, // lParam = MAKELPARAM(nMinRange, nMaxRange) TDM_SET_PROGRESS_BAR_POS = WM_USER + 106, // wParam = new position TDM_SET_PROGRESS_BAR_MARQUEE = WM_USER + 107, // wParam = 0 (stop marquee), wParam != 0 (start marquee), lparam = speed (milliseconds between repaints) TDM_SET_ELEMENT_TEXT = WM_USER + 108, // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element text (LPCWSTR) TDM_CLICK_RADIO_BUTTON = WM_USER + 110, // wParam = Radio Button ID TDM_ENABLE_BUTTON = WM_USER + 111, // lParam = 0 (disable), lParam != 0 (enable), wParam = Button ID TDM_ENABLE_RADIO_BUTTON = WM_USER + 112, // lParam = 0 (disable), lParam != 0 (enable), wParam = Radio Button ID TDM_CLICK_VERIFICATION = WM_USER + 113, // wParam = 0 (unchecked), 1 (checked), lParam = 1 (set key focus) TDM_UPDATE_ELEMENT_TEXT = WM_USER + 114, // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element text (LPCWSTR) TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE = WM_USER + 115, // wParam = Button ID, lParam = 0 (elevation not required), lParam != 0 (elevation required) TDM_UPDATE_ICON = WM_USER + 116 // wParam = icon element (TASKDIALOG_ICON_ELEMENTS), lParam = new icon (hIcon if TDF_USE_HICON_* was set, PCWSTR otherwise) } TASKDIALOG_MESSAGES; typedef enum _TASKDIALOG_NOTIFICATIONS { TDN_CREATED = 0, TDN_NAVIGATED = 1, TDN_BUTTON_CLICKED = 2, // wParam = Button ID TDN_HYPERLINK_CLICKED = 3, // lParam = (LPCWSTR)pszHREF TDN_TIMER = 4, // wParam = Milliseconds since dialog created or timer reset TDN_DESTROYED = 5, TDN_RADIO_BUTTON_CLICKED = 6, // wParam = Radio Button ID TDN_DIALOG_CONSTRUCTED = 7, TDN_VERIFICATION_CLICKED = 8, // wParam = 1 if checkbox checked, 0 if not, lParam is unused and always 0 TDN_HELP = 9, TDN_EXPANDO_BUTTON_CLICKED = 10 // wParam = 0 (dialog is now collapsed), wParam != 0 (dialog is now expanded) } TASKDIALOG_NOTIFICATIONS; typedef struct _TASKDIALOG_BUTTON { int nButtonID; PCWSTR pszButtonText; } TASKDIALOG_BUTTON; typedef enum _TASKDIALOG_ELEMENTS { TDE_CONTENT, TDE_EXPANDED_INFORMATION, TDE_FOOTER, TDE_MAIN_INSTRUCTION } TASKDIALOG_ELEMENTS; typedef enum _TASKDIALOG_ICON_ELEMENTS { TDIE_ICON_MAIN, TDIE_ICON_FOOTER } TASKDIALOG_ICON_ELEMENTS; #define TD_WARNING_ICON MAKEINTRESOURCEW(-1) #define TD_ERROR_ICON MAKEINTRESOURCEW(-2) #define TD_INFORMATION_ICON MAKEINTRESOURCEW(-3) #define TD_SHIELD_ICON MAKEINTRESOURCEW(-4) enum _TASKDIALOG_COMMON_BUTTON_FLAGS { TDCBF_OK_BUTTON = 0x0001, // selected control return value IDOK TDCBF_YES_BUTTON = 0x0002, // selected control return value IDYES TDCBF_NO_BUTTON = 0x0004, // selected control return value IDNO TDCBF_CANCEL_BUTTON = 0x0008, // selected control return value IDCANCEL TDCBF_RETRY_BUTTON = 0x0010, // selected control return value IDRETRY TDCBF_CLOSE_BUTTON = 0x0020 // selected control return value IDCLOSE }; typedef int TASKDIALOG_COMMON_BUTTON_FLAGS; // Note: _TASKDIALOG_COMMON_BUTTON_FLAGS is an int typedef struct _TASKDIALOGCONFIG { UINT cbSize; HWND hwndParent; // incorrectly named, this is the owner window, not a parent. HINSTANCE hInstance; // used for MAKEINTRESOURCE() strings TASKDIALOG_FLAGS dwFlags; // TASKDIALOG_FLAGS (TDF_XXX) flags TASKDIALOG_COMMON_BUTTON_FLAGS dwCommonButtons; // TASKDIALOG_COMMON_BUTTON (TDCBF_XXX) flags PCWSTR pszWindowTitle; // string or MAKEINTRESOURCE() union { HICON hMainIcon; PCWSTR pszMainIcon; } /*DUMMYUNIONNAME*/; PCWSTR pszMainInstruction; PCWSTR pszContent; UINT cButtons; const TASKDIALOG_BUTTON *pButtons; int nDefaultButton; UINT cRadioButtons; const TASKDIALOG_BUTTON *pRadioButtons; int nDefaultRadioButton; PCWSTR pszVerificationText; PCWSTR pszExpandedInformation; PCWSTR pszExpandedControlText; PCWSTR pszCollapsedControlText; union { HICON hFooterIcon; PCWSTR pszFooterIcon; } /*DUMMYUNIONNAME2*/; PCWSTR pszFooter; PFTASKDIALOGCALLBACK pfCallback; LONG_PTR lpCallbackData; UINT cxWidth; // width of the Task Dialog's client area in DLU's. If 0, Task Dialog will calculate the ideal width. } TASKDIALOGCONFIG; #include <poppack.h>
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowstaskdialog.h
C
apache-2.0
7,169
/* 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_VIDEO_DRIVER_WINDOWS #include "SDL_main.h" #include "SDL_video.h" #include "SDL_hints.h" #include "SDL_mouse.h" #include "SDL_system.h" #include "../SDL_sysvideo.h" #include "../SDL_pixels_c.h" #include "SDL_windowsvideo.h" #include "SDL_windowsframebuffer.h" #include "SDL_windowsshape.h" #include "SDL_windowsvulkan.h" /* Initialization/Query functions */ static int WIN_VideoInit(_THIS); static void WIN_VideoQuit(_THIS); /* Hints */ SDL_bool g_WindowsEnableMessageLoop = SDL_TRUE; SDL_bool g_WindowFrameUsableWhileCursorHidden = SDL_TRUE; static void SDLCALL UpdateWindowsEnableMessageLoop(void *userdata, const char *name, const char *oldValue, const char *newValue) { if (newValue && *newValue == '0') { g_WindowsEnableMessageLoop = SDL_FALSE; } else { g_WindowsEnableMessageLoop = SDL_TRUE; } } static void SDLCALL UpdateWindowFrameUsableWhileCursorHidden(void *userdata, const char *name, const char *oldValue, const char *newValue) { if (newValue && *newValue == '0') { g_WindowFrameUsableWhileCursorHidden = SDL_FALSE; } else { g_WindowFrameUsableWhileCursorHidden = SDL_TRUE; } } static void WIN_SuspendScreenSaver(_THIS) { if (_this->suspend_screensaver) { SetThreadExecutionState(ES_CONTINUOUS | ES_DISPLAY_REQUIRED); } else { SetThreadExecutionState(ES_CONTINUOUS); } } /* Windows driver bootstrap functions */ static int WIN_Available(void) { return (1); } static void WIN_DeleteDevice(SDL_VideoDevice * device) { SDL_VideoData *data = (SDL_VideoData *) device->driverdata; SDL_UnregisterApp(); if (data->userDLL) { SDL_UnloadObject(data->userDLL); } if (data->shcoreDLL) { SDL_UnloadObject(data->shcoreDLL); } SDL_free(device->driverdata); SDL_free(device); } static SDL_VideoDevice * WIN_CreateDevice(int devindex) { SDL_VideoDevice *device; SDL_VideoData *data; SDL_RegisterApp(NULL, 0, NULL); /* Initialize all variables that we clean on shutdown */ device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice)); if (device) { data = (struct SDL_VideoData *) SDL_calloc(1, sizeof(SDL_VideoData)); } else { data = NULL; } if (!data) { SDL_free(device); SDL_OutOfMemory(); return NULL; } device->driverdata = data; data->userDLL = SDL_LoadObject("USER32.DLL"); if (data->userDLL) { data->CloseTouchInputHandle = (BOOL (WINAPI *)(HTOUCHINPUT)) SDL_LoadFunction(data->userDLL, "CloseTouchInputHandle"); data->GetTouchInputInfo = (BOOL (WINAPI *)(HTOUCHINPUT, UINT, PTOUCHINPUT, int)) SDL_LoadFunction(data->userDLL, "GetTouchInputInfo"); data->RegisterTouchWindow = (BOOL (WINAPI *)(HWND, ULONG)) SDL_LoadFunction(data->userDLL, "RegisterTouchWindow"); } else { SDL_ClearError(); } data->shcoreDLL = SDL_LoadObject("SHCORE.DLL"); if (data->shcoreDLL) { data->GetDpiForMonitor = (HRESULT (WINAPI *)(HMONITOR, MONITOR_DPI_TYPE, UINT *, UINT *)) SDL_LoadFunction(data->shcoreDLL, "GetDpiForMonitor"); } else { SDL_ClearError(); } /* Set the function pointers */ device->VideoInit = WIN_VideoInit; device->VideoQuit = WIN_VideoQuit; device->GetDisplayBounds = WIN_GetDisplayBounds; device->GetDisplayUsableBounds = WIN_GetDisplayUsableBounds; device->GetDisplayDPI = WIN_GetDisplayDPI; device->GetDisplayModes = WIN_GetDisplayModes; device->SetDisplayMode = WIN_SetDisplayMode; device->PumpEvents = WIN_PumpEvents; device->SuspendScreenSaver = WIN_SuspendScreenSaver; device->CreateSDLWindow = WIN_CreateWindow; device->CreateSDLWindowFrom = WIN_CreateWindowFrom; device->SetWindowTitle = WIN_SetWindowTitle; device->SetWindowIcon = WIN_SetWindowIcon; device->SetWindowPosition = WIN_SetWindowPosition; device->SetWindowSize = WIN_SetWindowSize; device->GetWindowBordersSize = WIN_GetWindowBordersSize; device->SetWindowOpacity = WIN_SetWindowOpacity; device->ShowWindow = WIN_ShowWindow; device->HideWindow = WIN_HideWindow; device->RaiseWindow = WIN_RaiseWindow; device->MaximizeWindow = WIN_MaximizeWindow; device->MinimizeWindow = WIN_MinimizeWindow; device->RestoreWindow = WIN_RestoreWindow; device->SetWindowBordered = WIN_SetWindowBordered; device->SetWindowResizable = WIN_SetWindowResizable; device->SetWindowFullscreen = WIN_SetWindowFullscreen; device->SetWindowGammaRamp = WIN_SetWindowGammaRamp; device->GetWindowGammaRamp = WIN_GetWindowGammaRamp; device->SetWindowGrab = WIN_SetWindowGrab; device->DestroyWindow = WIN_DestroyWindow; device->GetWindowWMInfo = WIN_GetWindowWMInfo; device->CreateWindowFramebuffer = WIN_CreateWindowFramebuffer; device->UpdateWindowFramebuffer = WIN_UpdateWindowFramebuffer; device->DestroyWindowFramebuffer = WIN_DestroyWindowFramebuffer; device->OnWindowEnter = WIN_OnWindowEnter; device->SetWindowHitTest = WIN_SetWindowHitTest; device->AcceptDragAndDrop = WIN_AcceptDragAndDrop; device->shape_driver.CreateShaper = Win32_CreateShaper; device->shape_driver.SetWindowShape = Win32_SetWindowShape; device->shape_driver.ResizeWindowShape = Win32_ResizeWindowShape; #if SDL_VIDEO_OPENGL_WGL device->GL_LoadLibrary = WIN_GL_LoadLibrary; device->GL_GetProcAddress = WIN_GL_GetProcAddress; device->GL_UnloadLibrary = WIN_GL_UnloadLibrary; device->GL_CreateContext = WIN_GL_CreateContext; device->GL_MakeCurrent = WIN_GL_MakeCurrent; device->GL_SetSwapInterval = WIN_GL_SetSwapInterval; device->GL_GetSwapInterval = WIN_GL_GetSwapInterval; device->GL_SwapWindow = WIN_GL_SwapWindow; device->GL_DeleteContext = WIN_GL_DeleteContext; #elif SDL_VIDEO_OPENGL_EGL /* Use EGL based functions */ device->GL_LoadLibrary = WIN_GLES_LoadLibrary; device->GL_GetProcAddress = WIN_GLES_GetProcAddress; device->GL_UnloadLibrary = WIN_GLES_UnloadLibrary; device->GL_CreateContext = WIN_GLES_CreateContext; device->GL_MakeCurrent = WIN_GLES_MakeCurrent; device->GL_SetSwapInterval = WIN_GLES_SetSwapInterval; device->GL_GetSwapInterval = WIN_GLES_GetSwapInterval; device->GL_SwapWindow = WIN_GLES_SwapWindow; device->GL_DeleteContext = WIN_GLES_DeleteContext; #endif #if SDL_VIDEO_VULKAN device->Vulkan_LoadLibrary = WIN_Vulkan_LoadLibrary; device->Vulkan_UnloadLibrary = WIN_Vulkan_UnloadLibrary; device->Vulkan_GetInstanceExtensions = WIN_Vulkan_GetInstanceExtensions; device->Vulkan_CreateSurface = WIN_Vulkan_CreateSurface; #endif device->StartTextInput = WIN_StartTextInput; device->StopTextInput = WIN_StopTextInput; device->SetTextInputRect = WIN_SetTextInputRect; device->SetClipboardText = WIN_SetClipboardText; device->GetClipboardText = WIN_GetClipboardText; device->HasClipboardText = WIN_HasClipboardText; device->free = WIN_DeleteDevice; return device; } VideoBootStrap WINDOWS_bootstrap = { "windows", "SDL Windows video driver", WIN_Available, WIN_CreateDevice }; int WIN_VideoInit(_THIS) { if (WIN_InitModes(_this) < 0) { return -1; } WIN_InitKeyboard(_this); WIN_InitMouse(_this); SDL_AddHintCallback(SDL_HINT_WINDOWS_ENABLE_MESSAGELOOP, UpdateWindowsEnableMessageLoop, NULL); SDL_AddHintCallback(SDL_HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN, UpdateWindowFrameUsableWhileCursorHidden, NULL); return 0; } void WIN_VideoQuit(_THIS) { WIN_QuitModes(_this); WIN_QuitKeyboard(_this); WIN_QuitMouse(_this); } #define D3D_DEBUG_INFO #include <d3d9.h> SDL_bool D3D_LoadDLL(void **pD3DDLL, IDirect3D9 **pDirect3D9Interface) { *pD3DDLL = SDL_LoadObject("D3D9.DLL"); if (*pD3DDLL) { typedef IDirect3D9 *(WINAPI *Direct3DCreate9_t) (UINT SDKVersion); Direct3DCreate9_t Direct3DCreate9Func; #ifdef USE_D3D9EX typedef HRESULT (WINAPI *Direct3DCreate9Ex_t)(UINT SDKVersion, IDirect3D9Ex **ppD3D); Direct3DCreate9Ex_t Direct3DCreate9ExFunc; Direct3DCreate9ExFunc = (Direct3DCreate9Ex_t)SDL_LoadFunction(*pD3DDLL, "Direct3DCreate9Ex"); if (Direct3DCreate9ExFunc) { IDirect3D9Ex *pDirect3D9ExInterface; HRESULT hr = Direct3DCreate9ExFunc(D3D_SDK_VERSION, &pDirect3D9ExInterface); if (SUCCEEDED(hr)) { const GUID IDirect3D9_GUID = { 0x81bdcbca, 0x64d4, 0x426d, { 0xae, 0x8d, 0xad, 0x1, 0x47, 0xf4, 0x27, 0x5c } }; hr = IDirect3D9Ex_QueryInterface(pDirect3D9ExInterface, &IDirect3D9_GUID, (void**)pDirect3D9Interface); IDirect3D9Ex_Release(pDirect3D9ExInterface); if (SUCCEEDED(hr)) { return SDL_TRUE; } } } #endif /* USE_D3D9EX */ Direct3DCreate9Func = (Direct3DCreate9_t)SDL_LoadFunction(*pD3DDLL, "Direct3DCreate9"); if (Direct3DCreate9Func) { *pDirect3D9Interface = Direct3DCreate9Func(D3D_SDK_VERSION); if (*pDirect3D9Interface) { return SDL_TRUE; } } SDL_UnloadObject(*pD3DDLL); *pD3DDLL = NULL; } *pDirect3D9Interface = NULL; return SDL_FALSE; } int SDL_Direct3D9GetAdapterIndex(int displayIndex) { void *pD3DDLL; IDirect3D9 *pD3D; if (!D3D_LoadDLL(&pD3DDLL, &pD3D)) { SDL_SetError("Unable to create Direct3D interface"); return D3DADAPTER_DEFAULT; } else { SDL_DisplayData *pData = (SDL_DisplayData *)SDL_GetDisplayDriverData(displayIndex); int adapterIndex = D3DADAPTER_DEFAULT; if (!pData) { SDL_SetError("Invalid display index"); adapterIndex = -1; /* make sure we return something invalid */ } else { char *displayName = WIN_StringToUTF8(pData->DeviceName); unsigned int count = IDirect3D9_GetAdapterCount(pD3D); unsigned int i; for (i=0; i<count; i++) { D3DADAPTER_IDENTIFIER9 id; IDirect3D9_GetAdapterIdentifier(pD3D, i, 0, &id); if (SDL_strcmp(id.DeviceName, displayName) == 0) { adapterIndex = i; break; } } SDL_free(displayName); } /* free up the D3D stuff we inited */ IDirect3D9_Release(pD3D); SDL_UnloadObject(pD3DDLL); return adapterIndex; } } #if HAVE_DXGI_H #define CINTERFACE #define COBJMACROS #include <dxgi.h> static SDL_bool DXGI_LoadDLL(void **pDXGIDLL, IDXGIFactory **pDXGIFactory) { *pDXGIDLL = SDL_LoadObject("DXGI.DLL"); if (*pDXGIDLL) { HRESULT (WINAPI *CreateDXGI)(REFIID riid, void **ppFactory); CreateDXGI = (HRESULT (WINAPI *) (REFIID, void**)) SDL_LoadFunction(*pDXGIDLL, "CreateDXGIFactory"); if (CreateDXGI) { GUID dxgiGUID = {0x7b7166ec,0x21c7,0x44ae,{0xb2,0x1a,0xc9,0xae,0x32,0x1a,0xe3,0x69}}; if (!SUCCEEDED(CreateDXGI(&dxgiGUID, (void**)pDXGIFactory))) { *pDXGIFactory = NULL; } } if (!*pDXGIFactory) { SDL_UnloadObject(*pDXGIDLL); *pDXGIDLL = NULL; return SDL_FALSE; } return SDL_TRUE; } else { *pDXGIFactory = NULL; return SDL_FALSE; } } #endif SDL_bool SDL_DXGIGetOutputInfo(int displayIndex, int *adapterIndex, int *outputIndex) { #if !HAVE_DXGI_H if (adapterIndex) *adapterIndex = -1; if (outputIndex) *outputIndex = -1; SDL_SetError("SDL was compiled without DXGI support due to missing dxgi.h header"); return SDL_FALSE; #else SDL_DisplayData *pData = (SDL_DisplayData *)SDL_GetDisplayDriverData(displayIndex); void *pDXGIDLL; char *displayName; int nAdapter, nOutput; IDXGIFactory *pDXGIFactory = NULL; IDXGIAdapter *pDXGIAdapter; IDXGIOutput* pDXGIOutput; if (!adapterIndex) { SDL_InvalidParamError("adapterIndex"); return SDL_FALSE; } if (!outputIndex) { SDL_InvalidParamError("outputIndex"); return SDL_FALSE; } *adapterIndex = -1; *outputIndex = -1; if (!pData) { SDL_SetError("Invalid display index"); return SDL_FALSE; } if (!DXGI_LoadDLL(&pDXGIDLL, &pDXGIFactory)) { SDL_SetError("Unable to create DXGI interface"); return SDL_FALSE; } displayName = WIN_StringToUTF8(pData->DeviceName); nAdapter = 0; while (*adapterIndex == -1 && SUCCEEDED(IDXGIFactory_EnumAdapters(pDXGIFactory, nAdapter, &pDXGIAdapter))) { nOutput = 0; while (*adapterIndex == -1 && SUCCEEDED(IDXGIAdapter_EnumOutputs(pDXGIAdapter, nOutput, &pDXGIOutput))) { DXGI_OUTPUT_DESC outputDesc; if (SUCCEEDED(IDXGIOutput_GetDesc(pDXGIOutput, &outputDesc))) { char *outputName = WIN_StringToUTF8(outputDesc.DeviceName); if (SDL_strcmp(outputName, displayName) == 0) { *adapterIndex = nAdapter; *outputIndex = nOutput; } SDL_free(outputName); } IDXGIOutput_Release(pDXGIOutput); nOutput++; } IDXGIAdapter_Release(pDXGIAdapter); nAdapter++; } SDL_free(displayName); /* free up the DXGI factory */ IDXGIFactory_Release(pDXGIFactory); SDL_UnloadObject(pDXGIDLL); if (*adapterIndex == -1) { return SDL_FALSE; } else { return SDL_TRUE; } #endif } #endif /* SDL_VIDEO_DRIVER_WINDOWS */ /* vim: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsvideo.c
C
apache-2.0
14,709
/* 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_windowsvideo_h_ #define SDL_windowsvideo_h_ #include "../../core/windows/SDL_windows.h" #include "../SDL_sysvideo.h" #if defined(_MSC_VER) && (_MSC_VER >= 1500) #include <msctf.h> #else #include "SDL_msctf.h" #endif #include <imm.h> #define MAX_CANDLIST 10 #define MAX_CANDLENGTH 256 #include "SDL_windowsclipboard.h" #include "SDL_windowsevents.h" #include "SDL_windowskeyboard.h" #include "SDL_windowsmodes.h" #include "SDL_windowsmouse.h" #include "SDL_windowsopengl.h" #include "SDL_windowsopengles.h" #include "SDL_windowswindow.h" #include "SDL_events.h" #include "SDL_loadso.h" #if WINVER < 0x0601 /* Touch input definitions */ #define TWF_FINETOUCH 1 #define TWF_WANTPALM 2 #define TOUCHEVENTF_MOVE 0x0001 #define TOUCHEVENTF_DOWN 0x0002 #define TOUCHEVENTF_UP 0x0004 DECLARE_HANDLE(HTOUCHINPUT); typedef struct _TOUCHINPUT { LONG x; LONG y; HANDLE hSource; DWORD dwID; DWORD dwFlags; DWORD dwMask; DWORD dwTime; ULONG_PTR dwExtraInfo; DWORD cxContact; DWORD cyContact; } TOUCHINPUT, *PTOUCHINPUT; #endif /* WINVER < 0x0601 */ #if WINVER < 0x0603 typedef enum MONITOR_DPI_TYPE { MDT_EFFECTIVE_DPI = 0, MDT_ANGULAR_DPI = 1, MDT_RAW_DPI = 2, MDT_DEFAULT = MDT_EFFECTIVE_DPI } MONITOR_DPI_TYPE; #endif /* WINVER < 0x0603 */ typedef BOOL (*PFNSHFullScreen)(HWND, DWORD); typedef void (*PFCoordTransform)(SDL_Window*, POINT*); typedef struct { void **lpVtbl; int refcount; void *data; } TSFSink; /* Definition from Win98DDK version of IMM.H */ typedef struct tagINPUTCONTEXT2 { HWND hWnd; BOOL fOpen; POINT ptStatusWndPos; POINT ptSoftKbdPos; DWORD fdwConversion; DWORD fdwSentence; union { LOGFONTA A; LOGFONTW W; } lfFont; COMPOSITIONFORM cfCompForm; CANDIDATEFORM cfCandForm[4]; HIMCC hCompStr; HIMCC hCandInfo; HIMCC hGuideLine; HIMCC hPrivate; DWORD dwNumMsgBuf; HIMCC hMsgBuf; DWORD fdwInit; DWORD dwReserve[3]; } INPUTCONTEXT2, *PINPUTCONTEXT2, NEAR *NPINPUTCONTEXT2, FAR *LPINPUTCONTEXT2; /* Private display data */ typedef struct SDL_VideoData { int render; DWORD clipboard_count; /* Touch input functions */ void* userDLL; BOOL (WINAPI *CloseTouchInputHandle)( HTOUCHINPUT ); BOOL (WINAPI *GetTouchInputInfo)( HTOUCHINPUT, UINT, PTOUCHINPUT, int ); BOOL (WINAPI *RegisterTouchWindow)( HWND, ULONG ); void* shcoreDLL; HRESULT (WINAPI *GetDpiForMonitor)( HMONITOR hmonitor, MONITOR_DPI_TYPE dpiType, UINT *dpiX, UINT *dpiY ); SDL_bool ime_com_initialized; struct ITfThreadMgr *ime_threadmgr; SDL_bool ime_initialized; SDL_bool ime_enabled; SDL_bool ime_available; HWND ime_hwnd_main; HWND ime_hwnd_current; HIMC ime_himc; WCHAR ime_composition[SDL_TEXTEDITINGEVENT_TEXT_SIZE]; WCHAR ime_readingstring[16]; int ime_cursor; SDL_bool ime_candlist; WCHAR ime_candidates[MAX_CANDLIST][MAX_CANDLENGTH]; DWORD ime_candcount; DWORD ime_candref; DWORD ime_candsel; UINT ime_candpgsize; int ime_candlistindexbase; SDL_bool ime_candvertical; SDL_bool ime_dirty; SDL_Rect ime_rect; SDL_Rect ime_candlistrect; int ime_winwidth; int ime_winheight; HKL ime_hkl; void* ime_himm32; UINT (WINAPI *GetReadingString)(HIMC himc, UINT uReadingBufLen, LPWSTR lpwReadingBuf, PINT pnErrorIndex, BOOL *pfIsVertical, PUINT puMaxReadingLen); BOOL (WINAPI *ShowReadingWindow)(HIMC himc, BOOL bShow); LPINPUTCONTEXT2 (WINAPI *ImmLockIMC)(HIMC himc); BOOL (WINAPI *ImmUnlockIMC)(HIMC himc); LPVOID (WINAPI *ImmLockIMCC)(HIMCC himcc); BOOL (WINAPI *ImmUnlockIMCC)(HIMCC himcc); SDL_bool ime_uiless; struct ITfThreadMgrEx *ime_threadmgrex; DWORD ime_uielemsinkcookie; DWORD ime_alpnsinkcookie; DWORD ime_openmodesinkcookie; DWORD ime_convmodesinkcookie; TSFSink *ime_uielemsink; TSFSink *ime_ippasink; } SDL_VideoData; extern SDL_bool g_WindowsEnableMessageLoop; extern SDL_bool g_WindowFrameUsableWhileCursorHidden; typedef struct IDirect3D9 IDirect3D9; extern SDL_bool D3D_LoadDLL( void **pD3DDLL, IDirect3D9 **pDirect3D9Interface ); #endif /* SDL_windowsvideo_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsvideo.h
C
apache-2.0
5,457
/* 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. */ /* * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's * SDL_x11vulkan.c. */ #include "../../SDL_internal.h" #if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_WINDOWS #include "SDL_windowsvideo.h" #include "SDL_windowswindow.h" #include "SDL_assert.h" #include "SDL_loadso.h" #include "SDL_windowsvulkan.h" #include "SDL_syswm.h" int WIN_Vulkan_LoadLibrary(_THIS, const char *path) { VkExtensionProperties *extensions = NULL; Uint32 extensionCount = 0; Uint32 i; SDL_bool hasSurfaceExtension = SDL_FALSE; SDL_bool hasWin32SurfaceExtension = SDL_FALSE; PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL; if(_this->vulkan_config.loader_handle) return SDL_SetError("Vulkan already loaded"); /* Load the Vulkan loader library */ if(!path) path = SDL_getenv("SDL_VULKAN_LIBRARY"); if(!path) path = "vulkan-1.dll"; _this->vulkan_config.loader_handle = SDL_LoadObject(path); if(!_this->vulkan_config.loader_handle) return -1; SDL_strlcpy(_this->vulkan_config.loader_path, path, SDL_arraysize(_this->vulkan_config.loader_path)); vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)SDL_LoadFunction( _this->vulkan_config.loader_handle, "vkGetInstanceProcAddr"); if(!vkGetInstanceProcAddr) goto fail; _this->vulkan_config.vkGetInstanceProcAddr = (void *)vkGetInstanceProcAddr; _this->vulkan_config.vkEnumerateInstanceExtensionProperties = (void *)((PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr)( VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties"); if(!_this->vulkan_config.vkEnumerateInstanceExtensionProperties) goto fail; extensions = SDL_Vulkan_CreateInstanceExtensionsList( (PFN_vkEnumerateInstanceExtensionProperties) _this->vulkan_config.vkEnumerateInstanceExtensionProperties, &extensionCount); if(!extensions) goto fail; for(i = 0; i < extensionCount; i++) { if(SDL_strcmp(VK_KHR_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0) hasSurfaceExtension = SDL_TRUE; else if(SDL_strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0) hasWin32SurfaceExtension = SDL_TRUE; } SDL_free(extensions); if(!hasSurfaceExtension) { SDL_SetError("Installed Vulkan doesn't implement the " VK_KHR_SURFACE_EXTENSION_NAME " extension"); goto fail; } else if(!hasWin32SurfaceExtension) { SDL_SetError("Installed Vulkan doesn't implement the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME "extension"); goto fail; } return 0; fail: SDL_UnloadObject(_this->vulkan_config.loader_handle); _this->vulkan_config.loader_handle = NULL; return -1; } void WIN_Vulkan_UnloadLibrary(_THIS) { if(_this->vulkan_config.loader_handle) { SDL_UnloadObject(_this->vulkan_config.loader_handle); _this->vulkan_config.loader_handle = NULL; } } SDL_bool WIN_Vulkan_GetInstanceExtensions(_THIS, SDL_Window *window, unsigned *count, const char **names) { static const char *const extensionsForWin32[] = { VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WIN32_SURFACE_EXTENSION_NAME }; if(!_this->vulkan_config.loader_handle) { SDL_SetError("Vulkan is not loaded"); return SDL_FALSE; } return SDL_Vulkan_GetInstanceExtensions_Helper( count, names, SDL_arraysize(extensionsForWin32), extensionsForWin32); } SDL_bool WIN_Vulkan_CreateSurface(_THIS, SDL_Window *window, VkInstance instance, VkSurfaceKHR *surface) { SDL_WindowData *windowData = (SDL_WindowData *)window->driverdata; PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr; PFN_vkCreateWin32SurfaceKHR vkCreateWin32SurfaceKHR = (PFN_vkCreateWin32SurfaceKHR)vkGetInstanceProcAddr( (VkInstance)instance, "vkCreateWin32SurfaceKHR"); VkWin32SurfaceCreateInfoKHR createInfo; VkResult result; if(!_this->vulkan_config.loader_handle) { SDL_SetError("Vulkan is not loaded"); return SDL_FALSE; } if(!vkCreateWin32SurfaceKHR) { SDL_SetError(VK_KHR_WIN32_SURFACE_EXTENSION_NAME " extension is not enabled in the Vulkan instance."); return SDL_FALSE; } createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; createInfo.pNext = NULL; createInfo.flags = 0; createInfo.hinstance = windowData->hinstance; createInfo.hwnd = windowData->hwnd; result = vkCreateWin32SurfaceKHR(instance, &createInfo, NULL, surface); if(result != VK_SUCCESS) { SDL_SetError("vkCreateWin32SurfaceKHR failed: %s", SDL_Vulkan_GetResultString(result)); return SDL_FALSE; } return SDL_TRUE; } #endif /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsvulkan.c
C
apache-2.0
6,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. */ /* * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's * SDL_x11vulkan.h. */ #include "../../SDL_internal.h" #ifndef SDL_windowsvulkan_h_ #define SDL_windowsvulkan_h_ #include "../SDL_vulkan_internal.h" #include "../SDL_sysvideo.h" #if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_WINDOWS int WIN_Vulkan_LoadLibrary(_THIS, const char *path); void WIN_Vulkan_UnloadLibrary(_THIS); SDL_bool WIN_Vulkan_GetInstanceExtensions(_THIS, SDL_Window *window, unsigned *count, const char **names); SDL_bool WIN_Vulkan_CreateSurface(_THIS, SDL_Window *window, VkInstance instance, VkSurfaceKHR *surface); #endif #endif /* SDL_windowsvulkan_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowsvulkan.h
C
apache-2.0
1,865
/* 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_VIDEO_DRIVER_WINDOWS #include "../../core/windows/SDL_windows.h" #include "SDL_assert.h" #include "../SDL_sysvideo.h" #include "../SDL_pixels_c.h" #include "../../events/SDL_keyboard_c.h" #include "../../events/SDL_mouse_c.h" #include "../../joystick/windows/SDL_rawinputjoystick_c.h" #include "SDL_windowsvideo.h" #include "SDL_windowswindow.h" #include "SDL_hints.h" #include "SDL_timer.h" /* Dropfile support */ #include <shellapi.h> /* This is included after SDL_windowsvideo.h, which includes windows.h */ #include "SDL_syswm.h" /* Windows CE compatibility */ #ifndef SWP_NOCOPYBITS #define SWP_NOCOPYBITS 0 #endif /* Fake window to help with DirectInput events. */ HWND SDL_HelperWindow = NULL; static WCHAR *SDL_HelperWindowClassName = TEXT("SDLHelperWindowInputCatcher"); static WCHAR *SDL_HelperWindowName = TEXT("SDLHelperWindowInputMsgWindow"); static ATOM SDL_HelperWindowClass = 0; /* For borderless Windows, still want the following flags: - WS_CAPTION: this seems to enable the Windows minimize animation - WS_SYSMENU: enables system context menu on task bar - WS_MINIMIZEBOX: window will respond to Windows minimize commands sent to all windows, such as windows key + m, shaking title bar, etc. This will also cause the task bar to overlap the window and other windowed behaviors, so only use this for windows that shouldn't appear to be fullscreen */ #define STYLE_BASIC (WS_CLIPSIBLINGS | WS_CLIPCHILDREN) #define STYLE_FULLSCREEN (WS_POPUP) #define STYLE_BORDERLESS (WS_POPUP) #define STYLE_BORDERLESS_WINDOWED (WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX) #define STYLE_NORMAL (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX) #define STYLE_RESIZABLE (WS_THICKFRAME | WS_MAXIMIZEBOX) #define STYLE_MASK (STYLE_FULLSCREEN | STYLE_BORDERLESS | STYLE_NORMAL | STYLE_RESIZABLE) static DWORD GetWindowStyle(SDL_Window * window) { DWORD style = 0; if (window->flags & SDL_WINDOW_FULLSCREEN) { style |= STYLE_FULLSCREEN; } else { if (window->flags & SDL_WINDOW_BORDERLESS) { /* SDL 2.1: This behavior more closely matches other platform where the window is borderless but still interacts with the window manager (e.g. task bar shows above it, it can be resized to fit within usable desktop area, etc.) so this should be the behavior for a future SDL release. If you want a borderless window the size of the desktop that looks like a fullscreen window, then you should use the SDL_WINDOW_FULLSCREEN_DESKTOP flag. */ if (SDL_GetHintBoolean("SDL_BORDERLESS_WINDOWED_STYLE", SDL_FALSE)) { style |= STYLE_BORDERLESS_WINDOWED; } else { style |= STYLE_BORDERLESS; } } else { style |= STYLE_NORMAL; } if (window->flags & SDL_WINDOW_RESIZABLE) { /* You can have a borderless resizable window, but Windows doesn't always draw it correctly, see https://bugzilla.libsdl.org/show_bug.cgi?id=4466 */ if (!(window->flags & SDL_WINDOW_BORDERLESS) || SDL_GetHintBoolean("SDL_BORDERLESS_RESIZABLE_STYLE", SDL_FALSE)) { style |= STYLE_RESIZABLE; } } /* Need to set initialize minimize style, or when we call ShowWindow with WS_MINIMIZE it will activate a random window */ if (window->flags & SDL_WINDOW_MINIMIZED) { style |= WS_MINIMIZE; } } return style; } static void WIN_AdjustWindowRectWithStyle(SDL_Window *window, DWORD style, BOOL menu, int *x, int *y, int *width, int *height, SDL_bool use_current) { RECT rect; rect.left = 0; rect.top = 0; rect.right = (use_current ? window->w : window->windowed.w); rect.bottom = (use_current ? window->h : window->windowed.h); /* borderless windows will have WM_NCCALCSIZE return 0 for the non-client area. When this happens, it looks like windows will send a resize message expanding the window client area to the previous window + chrome size, so shouldn't need to adjust the window size for the set styles. */ if (!(window->flags & SDL_WINDOW_BORDERLESS)) AdjustWindowRectEx(&rect, style, menu, 0); *x = (use_current ? window->x : window->windowed.x) + rect.left; *y = (use_current ? window->y : window->windowed.y) + rect.top; *width = (rect.right - rect.left); *height = (rect.bottom - rect.top); } static void WIN_AdjustWindowRect(SDL_Window *window, int *x, int *y, int *width, int *height, SDL_bool use_current) { SDL_WindowData *data = (SDL_WindowData *)window->driverdata; HWND hwnd = data->hwnd; DWORD style; BOOL menu; style = GetWindowLong(hwnd, GWL_STYLE); menu = (style & WS_CHILDWINDOW) ? FALSE : (GetMenu(hwnd) != NULL); WIN_AdjustWindowRectWithStyle(window, style, menu, x, y, width, height, use_current); } static void WIN_SetWindowPositionInternal(_THIS, SDL_Window * window, UINT flags) { SDL_WindowData *data = (SDL_WindowData *)window->driverdata; HWND hwnd = data->hwnd; HWND top; int x, y; int w, h; /* Figure out what the window area will be */ if (SDL_ShouldAllowTopmost() && ((window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_INPUT_FOCUS)) == (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_INPUT_FOCUS) || (window->flags & SDL_WINDOW_ALWAYS_ON_TOP))) { top = HWND_TOPMOST; } else { top = HWND_NOTOPMOST; } WIN_AdjustWindowRect(window, &x, &y, &w, &h, SDL_TRUE); data->expected_resize = SDL_TRUE; SetWindowPos(hwnd, top, x, y, w, h, flags); data->expected_resize = SDL_FALSE; } static int SetupWindowData(_THIS, SDL_Window * window, HWND hwnd, HWND parent, SDL_bool created) { SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata; SDL_WindowData *data; /* Allocate the window data */ data = (SDL_WindowData *) SDL_calloc(1, sizeof(*data)); if (!data) { return SDL_OutOfMemory(); } data->window = window; data->hwnd = hwnd; data->parent = parent; data->hdc = GetDC(hwnd); data->hinstance = (HINSTANCE) GetWindowLongPtr(hwnd, GWLP_HINSTANCE); data->created = created; data->mouse_button_flags = 0; data->last_pointer_update = (LPARAM)-1; data->videodata = videodata; data->initializing = SDL_TRUE; window->driverdata = data; /* Associate the data with the window */ if (!SetProp(hwnd, TEXT("SDL_WindowData"), data)) { ReleaseDC(hwnd, data->hdc); SDL_free(data); return WIN_SetError("SetProp() failed"); } /* Set up the window proc function */ #ifdef GWLP_WNDPROC data->wndproc = (WNDPROC) GetWindowLongPtr(hwnd, GWLP_WNDPROC); if (data->wndproc == WIN_WindowProc) { data->wndproc = NULL; } else { SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR) WIN_WindowProc); } #else data->wndproc = (WNDPROC) GetWindowLong(hwnd, GWL_WNDPROC); if (data->wndproc == WIN_WindowProc) { data->wndproc = NULL; } else { SetWindowLong(hwnd, GWL_WNDPROC, (LONG_PTR) WIN_WindowProc); } #endif /* Fill in the SDL window with the window data */ { RECT rect; if (GetClientRect(hwnd, &rect)) { int w = rect.right; int h = rect.bottom; if ((window->windowed.w && window->windowed.w != w) || (window->windowed.h && window->windowed.h != h)) { /* We tried to create a window larger than the desktop and Windows didn't allow it. Override! */ int x, y; /* Figure out what the window area will be */ WIN_AdjustWindowRect(window, &x, &y, &w, &h, SDL_FALSE); SetWindowPos(hwnd, HWND_NOTOPMOST, x, y, w, h, SWP_NOCOPYBITS | SWP_NOZORDER | SWP_NOACTIVATE); } else { window->w = w; window->h = h; } } } { POINT point; point.x = 0; point.y = 0; if (ClientToScreen(hwnd, &point)) { window->x = point.x; window->y = point.y; } } { DWORD style = GetWindowLong(hwnd, GWL_STYLE); if (style & WS_VISIBLE) { window->flags |= SDL_WINDOW_SHOWN; } else { window->flags &= ~SDL_WINDOW_SHOWN; } if (style & WS_POPUP) { window->flags |= SDL_WINDOW_BORDERLESS; } else { window->flags &= ~SDL_WINDOW_BORDERLESS; } if (style & WS_THICKFRAME) { window->flags |= SDL_WINDOW_RESIZABLE; } else { window->flags &= ~SDL_WINDOW_RESIZABLE; } #ifdef WS_MAXIMIZE if (style & WS_MAXIMIZE) { window->flags |= SDL_WINDOW_MAXIMIZED; } else #endif { window->flags &= ~SDL_WINDOW_MAXIMIZED; } #ifdef WS_MINIMIZE if (style & WS_MINIMIZE) { window->flags |= SDL_WINDOW_MINIMIZED; } else #endif { window->flags &= ~SDL_WINDOW_MINIMIZED; } } if (GetFocus() == hwnd) { window->flags |= SDL_WINDOW_INPUT_FOCUS; SDL_SetKeyboardFocus(data->window); if (window->flags & SDL_WINDOW_INPUT_GRABBED) { RECT rect; GetClientRect(hwnd, &rect); ClientToScreen(hwnd, (LPPOINT) & rect); ClientToScreen(hwnd, (LPPOINT) & rect + 1); ClipCursor(&rect); } } /* Enable multi-touch */ if (videodata->RegisterTouchWindow) { videodata->RegisterTouchWindow(hwnd, (TWF_FINETOUCH|TWF_WANTPALM)); } data->initializing = SDL_FALSE; /* All done! */ return 0; } int WIN_CreateWindow(_THIS, SDL_Window * window) { HWND hwnd, parent = NULL; DWORD style = STYLE_BASIC; int x, y; int w, h; if (window->flags & SDL_WINDOW_SKIP_TASKBAR) { parent = CreateWindow(SDL_Appname, TEXT(""), STYLE_BASIC, 0, 0, 32, 32, NULL, NULL, SDL_Instance, NULL); } style |= GetWindowStyle(window); /* Figure out what the window area will be */ WIN_AdjustWindowRectWithStyle(window, style, FALSE, &x, &y, &w, &h, SDL_FALSE); hwnd = CreateWindow(SDL_Appname, TEXT(""), style, x, y, w, h, parent, NULL, SDL_Instance, NULL); if (!hwnd) { return WIN_SetError("Couldn't create window"); } WIN_PumpEvents(_this); if (SetupWindowData(_this, window, hwnd, parent, SDL_TRUE) < 0) { DestroyWindow(hwnd); if (parent) { DestroyWindow(parent); } return -1; } /* Inform Windows of the frame change so we can respond to WM_NCCALCSIZE */ SetWindowPos(hwnd, NULL, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOSIZE | SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE); if (window->flags & SDL_WINDOW_MINIMIZED) { ShowWindow(hwnd, SW_SHOWMINNOACTIVE); } if (!(window->flags & SDL_WINDOW_OPENGL)) { return 0; } /* The rest of this macro mess is for OpenGL or OpenGL ES windows */ #if SDL_VIDEO_OPENGL_ES2 if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES #if SDL_VIDEO_OPENGL_WGL && (!_this->gl_data || WIN_GL_UseEGL(_this)) #endif /* SDL_VIDEO_OPENGL_WGL */ ) { #if SDL_VIDEO_OPENGL_EGL if (WIN_GLES_SetupWindow(_this, window) < 0) { WIN_DestroyWindow(_this, window); return -1; } return 0; #else return SDL_SetError("Could not create GLES window surface (EGL support not configured)"); #endif /* SDL_VIDEO_OPENGL_EGL */ } #endif /* SDL_VIDEO_OPENGL_ES2 */ #if SDL_VIDEO_OPENGL_WGL if (WIN_GL_SetupWindow(_this, window) < 0) { WIN_DestroyWindow(_this, window); return -1; } #else return SDL_SetError("Could not create GL window (WGL support not configured)"); #endif return 0; } int WIN_CreateWindowFrom(_THIS, SDL_Window * window, const void *data) { HWND hwnd = (HWND) data; LPTSTR title; int titleLen; SDL_bool isstack; /* Query the title from the existing window */ titleLen = GetWindowTextLength(hwnd); title = SDL_small_alloc(TCHAR, titleLen + 1, &isstack); if (title) { titleLen = GetWindowText(hwnd, title, titleLen + 1); } else { titleLen = 0; } if (titleLen > 0) { window->title = WIN_StringToUTF8(title); } if (title) { SDL_small_free(title, isstack); } if (SetupWindowData(_this, window, hwnd, GetParent(hwnd), SDL_FALSE) < 0) { return -1; } #if SDL_VIDEO_OPENGL_WGL { const char *hint = SDL_GetHint(SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT); if (hint) { /* This hint is a pointer (in string form) of the address of the window to share a pixel format with */ SDL_Window *otherWindow = NULL; SDL_sscanf(hint, "%p", (void**)&otherWindow); /* Do some error checking on the pointer */ if (otherWindow != NULL && otherWindow->magic == &_this->window_magic) { /* If the otherWindow has SDL_WINDOW_OPENGL set, set it for the new window as well */ if (otherWindow->flags & SDL_WINDOW_OPENGL) { window->flags |= SDL_WINDOW_OPENGL; if (!WIN_GL_SetPixelFormatFrom(_this, otherWindow, window)) { return -1; } } } } } #endif return 0; } void WIN_SetWindowTitle(_THIS, SDL_Window * window) { HWND hwnd = ((SDL_WindowData *) window->driverdata)->hwnd; LPTSTR title = WIN_UTF8ToString(window->title); SetWindowText(hwnd, title); SDL_free(title); } void WIN_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon) { HWND hwnd = ((SDL_WindowData *) window->driverdata)->hwnd; HICON hicon = NULL; BYTE *icon_bmp; int icon_len, mask_len, y; SDL_RWops *dst; SDL_bool isstack; /* Create temporary buffer for ICONIMAGE structure */ mask_len = (icon->h * (icon->w + 7)/8); icon_len = 40 + icon->h * icon->w * sizeof(Uint32) + mask_len; icon_bmp = SDL_small_alloc(BYTE, icon_len, &isstack); dst = SDL_RWFromMem(icon_bmp, icon_len); if (!dst) { SDL_small_free(icon_bmp, isstack); return; } /* Write the BITMAPINFO header */ SDL_WriteLE32(dst, 40); SDL_WriteLE32(dst, icon->w); SDL_WriteLE32(dst, icon->h * 2); SDL_WriteLE16(dst, 1); SDL_WriteLE16(dst, 32); SDL_WriteLE32(dst, BI_RGB); SDL_WriteLE32(dst, icon->h * icon->w * sizeof(Uint32)); SDL_WriteLE32(dst, 0); SDL_WriteLE32(dst, 0); SDL_WriteLE32(dst, 0); SDL_WriteLE32(dst, 0); /* Write the pixels upside down into the bitmap buffer */ SDL_assert(icon->format->format == SDL_PIXELFORMAT_ARGB8888); y = icon->h; while (y--) { Uint8 *src = (Uint8 *) icon->pixels + y * icon->pitch; SDL_RWwrite(dst, src, icon->w * sizeof(Uint32), 1); } /* Write the mask */ SDL_memset(icon_bmp + icon_len - mask_len, 0xFF, mask_len); hicon = CreateIconFromResource(icon_bmp, icon_len, TRUE, 0x00030000); SDL_RWclose(dst); SDL_small_free(icon_bmp, isstack); /* Set the icon for the window */ SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon); /* Set the icon in the task manager (should we do this?) */ SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon); } void WIN_SetWindowPosition(_THIS, SDL_Window * window) { WIN_SetWindowPositionInternal(_this, window, SWP_NOCOPYBITS | SWP_NOSIZE | SWP_NOACTIVATE); } void WIN_SetWindowSize(_THIS, SDL_Window * window) { WIN_SetWindowPositionInternal(_this, window, SWP_NOCOPYBITS | SWP_NOMOVE | SWP_NOACTIVATE); } int WIN_GetWindowBordersSize(_THIS, SDL_Window * window, int *top, int *left, int *bottom, int *right) { HWND hwnd = ((SDL_WindowData *) window->driverdata)->hwnd; RECT rcClient, rcWindow; POINT ptDiff; /* rcClient stores the size of the inner window, while rcWindow stores the outer size relative to the top-left * screen position; so the top/left values of rcClient are always {0,0} and bottom/right are {height,width} */ GetClientRect(hwnd, &rcClient); GetWindowRect(hwnd, &rcWindow); /* convert the top/left values to make them relative to * the window; they will end up being slightly negative */ ptDiff.y = rcWindow.top; ptDiff.x = rcWindow.left; ScreenToClient(hwnd, &ptDiff); rcWindow.top = ptDiff.y; rcWindow.left = ptDiff.x; /* convert the bottom/right values to make them relative to the window, * these will be slightly bigger than the inner width/height */ ptDiff.y = rcWindow.bottom; ptDiff.x = rcWindow.right; ScreenToClient(hwnd, &ptDiff); rcWindow.bottom = ptDiff.y; rcWindow.right = ptDiff.x; /* Now that both the inner and outer rects use the same coordinate system we can substract them to get the border size. * Keep in mind that the top/left coordinates of rcWindow are negative because the border lies slightly before {0,0}, * so switch them around because SDL2 wants them in positive. */ *top = rcClient.top - rcWindow.top; *left = rcClient.left - rcWindow.left; *bottom = rcWindow.bottom - rcClient.bottom; *right = rcWindow.right - rcClient.right; return 0; } void WIN_ShowWindow(_THIS, SDL_Window * window) { DWORD style; HWND hwnd; int nCmdShow; hwnd = ((SDL_WindowData *)window->driverdata)->hwnd; nCmdShow = SW_SHOW; style = GetWindowLong(hwnd, GWL_EXSTYLE); if (style & WS_EX_NOACTIVATE) { nCmdShow = SW_SHOWNOACTIVATE; } ShowWindow(hwnd, nCmdShow); } void WIN_HideWindow(_THIS, SDL_Window * window) { HWND hwnd = ((SDL_WindowData *) window->driverdata)->hwnd; ShowWindow(hwnd, SW_HIDE); } void WIN_RaiseWindow(_THIS, SDL_Window * window) { HWND hwnd = ((SDL_WindowData *) window->driverdata)->hwnd; SetForegroundWindow(hwnd); } void WIN_MaximizeWindow(_THIS, SDL_Window * window) { SDL_WindowData *data = (SDL_WindowData *)window->driverdata; HWND hwnd = data->hwnd; data->expected_resize = SDL_TRUE; ShowWindow(hwnd, SW_MAXIMIZE); data->expected_resize = SDL_FALSE; } void WIN_MinimizeWindow(_THIS, SDL_Window * window) { HWND hwnd = ((SDL_WindowData *) window->driverdata)->hwnd; ShowWindow(hwnd, SW_MINIMIZE); } void WIN_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered) { SDL_WindowData *data = (SDL_WindowData *)window->driverdata; HWND hwnd = data->hwnd; DWORD style; style = GetWindowLong(hwnd, GWL_STYLE); style &= ~STYLE_MASK; style |= GetWindowStyle(window); data->in_border_change = SDL_TRUE; SetWindowLong(hwnd, GWL_STYLE, style); WIN_SetWindowPositionInternal(_this, window, SWP_NOCOPYBITS | SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOACTIVATE); data->in_border_change = SDL_FALSE; } void WIN_SetWindowResizable(_THIS, SDL_Window * window, SDL_bool resizable) { SDL_WindowData *data = (SDL_WindowData *)window->driverdata; HWND hwnd = data->hwnd; DWORD style; style = GetWindowLong(hwnd, GWL_STYLE); style &= ~STYLE_MASK; style |= GetWindowStyle(window); SetWindowLong(hwnd, GWL_STYLE, style); } void WIN_RestoreWindow(_THIS, SDL_Window * window) { SDL_WindowData *data = (SDL_WindowData *)window->driverdata; HWND hwnd = data->hwnd; data->expected_resize = SDL_TRUE; ShowWindow(hwnd, SW_RESTORE); data->expected_resize = SDL_FALSE; } void WIN_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; HWND hwnd = data->hwnd; SDL_Rect bounds; DWORD style; HWND top; int x, y; int w, h; if (SDL_ShouldAllowTopmost() && ((window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_INPUT_FOCUS)) == (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_INPUT_FOCUS) || window->flags & SDL_WINDOW_ALWAYS_ON_TOP)) { top = HWND_TOPMOST; } else { top = HWND_NOTOPMOST; } style = GetWindowLong(hwnd, GWL_STYLE); style &= ~STYLE_MASK; style |= GetWindowStyle(window); WIN_GetDisplayBounds(_this, display, &bounds); if (fullscreen) { x = bounds.x; y = bounds.y; w = bounds.w; h = bounds.h; /* Unset the maximized flag. This fixes https://bugzilla.libsdl.org/show_bug.cgi?id=3215 */ if (style & WS_MAXIMIZE) { data->windowed_mode_was_maximized = SDL_TRUE; style &= ~WS_MAXIMIZE; } } else { BOOL menu; /* Restore window-maximization state, as applicable. Special care is taken to *not* do this if and when we're alt-tab'ing away (to some other window; as indicated by in_window_deactivation), otherwise https://bugzilla.libsdl.org/show_bug.cgi?id=3215 can reproduce! */ if (data->windowed_mode_was_maximized && !data->in_window_deactivation) { style |= WS_MAXIMIZE; data->windowed_mode_was_maximized = SDL_FALSE; } menu = (style & WS_CHILDWINDOW) ? FALSE : (GetMenu(hwnd) != NULL); WIN_AdjustWindowRectWithStyle(window, style, menu, &x, &y, &w, &h, SDL_FALSE); } SetWindowLong(hwnd, GWL_STYLE, style); data->expected_resize = SDL_TRUE; SetWindowPos(hwnd, top, x, y, w, h, SWP_NOCOPYBITS | SWP_NOACTIVATE); data->expected_resize = SDL_FALSE; } int WIN_SetWindowGammaRamp(_THIS, SDL_Window * window, const Uint16 * ramp) { SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); SDL_DisplayData *data = (SDL_DisplayData *) display->driverdata; HDC hdc; BOOL succeeded = FALSE; hdc = CreateDC(data->DeviceName, NULL, NULL, NULL); if (hdc) { succeeded = SetDeviceGammaRamp(hdc, (LPVOID)ramp); if (!succeeded) { WIN_SetError("SetDeviceGammaRamp()"); } DeleteDC(hdc); } return succeeded ? 0 : -1; } int WIN_GetWindowGammaRamp(_THIS, SDL_Window * window, Uint16 * ramp) { SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); SDL_DisplayData *data = (SDL_DisplayData *) display->driverdata; HDC hdc; BOOL succeeded = FALSE; hdc = CreateDC(data->DeviceName, NULL, NULL, NULL); if (hdc) { succeeded = GetDeviceGammaRamp(hdc, (LPVOID)ramp); if (!succeeded) { WIN_SetError("GetDeviceGammaRamp()"); } DeleteDC(hdc); } return succeeded ? 0 : -1; } void WIN_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed) { WIN_UpdateClipCursor(window); if (window->flags & SDL_WINDOW_FULLSCREEN) { UINT flags = SWP_NOCOPYBITS | SWP_NOMOVE | SWP_NOSIZE; if (!(window->flags & SDL_WINDOW_SHOWN)) { flags |= SWP_NOACTIVATE; } WIN_SetWindowPositionInternal(_this, window, flags); } } void WIN_DestroyWindow(_THIS, SDL_Window * window) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; if (data) { ReleaseDC(data->hwnd, data->hdc); RemoveProp(data->hwnd, TEXT("SDL_WindowData")); if (data->created) { DestroyWindow(data->hwnd); if (data->parent) { DestroyWindow(data->parent); } } else { /* Restore any original event handler... */ if (data->wndproc != NULL) { #ifdef GWLP_WNDPROC SetWindowLongPtr(data->hwnd, GWLP_WNDPROC, (LONG_PTR) data->wndproc); #else SetWindowLong(data->hwnd, GWL_WNDPROC, (LONG_PTR) data->wndproc); #endif } } SDL_free(data); } window->driverdata = NULL; } SDL_bool WIN_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info) { const SDL_WindowData *data = (const SDL_WindowData *) window->driverdata; if (info->version.major <= SDL_MAJOR_VERSION) { int versionnum = SDL_VERSIONNUM(info->version.major, info->version.minor, info->version.patch); info->subsystem = SDL_SYSWM_WINDOWS; info->info.win.window = data->hwnd; if (versionnum >= SDL_VERSIONNUM(2, 0, 4)) { info->info.win.hdc = data->hdc; } if (versionnum >= SDL_VERSIONNUM(2, 0, 5)) { info->info.win.hinstance = data->hinstance; } return SDL_TRUE; } else { SDL_SetError("Application not compiled with SDL %d.%d", SDL_MAJOR_VERSION, SDL_MINOR_VERSION); return SDL_FALSE; } } static LRESULT CALLBACK SDL_HelperWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { #if SDL_JOYSTICK_RAWINPUT if (RAWINPUT_WindowProc(hWnd, msg, wParam, lParam) == 0) { return 0; } #endif return DefWindowProc(hWnd, msg, wParam, lParam); } /* * Creates a HelperWindow used for DirectInput and RawInput events. */ int SDL_HelperWindowCreate(void) { HINSTANCE hInstance = GetModuleHandle(NULL); WNDCLASS wce; /* Make sure window isn't created twice. */ if (SDL_HelperWindow != NULL) { return 0; } /* Create the class. */ SDL_zero(wce); wce.lpfnWndProc = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_RAWINPUT, SDL_TRUE) ? SDL_HelperWindowProc : DefWindowProc; wce.lpszClassName = (LPCWSTR) SDL_HelperWindowClassName; wce.hInstance = hInstance; /* Register the class. */ SDL_HelperWindowClass = RegisterClass(&wce); if (SDL_HelperWindowClass == 0 && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) { return WIN_SetError("Unable to create Helper Window Class"); } /* Create the window. */ SDL_HelperWindow = CreateWindowEx(0, SDL_HelperWindowClassName, SDL_HelperWindowName, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, HWND_MESSAGE, NULL, hInstance, NULL); if (SDL_HelperWindow == NULL) { UnregisterClass(SDL_HelperWindowClassName, hInstance); return WIN_SetError("Unable to create Helper Window"); } return 0; } /* * Destroys the HelperWindow previously created with SDL_HelperWindowCreate. */ void SDL_HelperWindowDestroy(void) { HINSTANCE hInstance = GetModuleHandle(NULL); /* Destroy the window. */ if (SDL_HelperWindow != NULL) { if (DestroyWindow(SDL_HelperWindow) == 0) { WIN_SetError("Unable to destroy Helper Window"); return; } SDL_HelperWindow = NULL; } /* Unregister the class. */ if (SDL_HelperWindowClass != 0) { if ((UnregisterClass(SDL_HelperWindowClassName, hInstance)) == 0) { WIN_SetError("Unable to destroy Helper Window Class"); return; } SDL_HelperWindowClass = 0; } } void WIN_OnWindowEnter(_THIS, SDL_Window * window) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; if (!data || !data->hwnd) { /* The window wasn't fully initialized */ return; } if (window->flags & SDL_WINDOW_ALWAYS_ON_TOP) { WIN_SetWindowPositionInternal(_this, window, SWP_NOCOPYBITS | SWP_NOSIZE | SWP_NOACTIVATE); } #ifdef WM_MOUSELEAVE { TRACKMOUSEEVENT trackMouseEvent; trackMouseEvent.cbSize = sizeof(TRACKMOUSEEVENT); trackMouseEvent.dwFlags = TME_LEAVE; trackMouseEvent.hwndTrack = data->hwnd; TrackMouseEvent(&trackMouseEvent); } #endif /* WM_MOUSELEAVE */ } void WIN_UpdateClipCursor(SDL_Window *window) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; SDL_Mouse *mouse = SDL_GetMouse(); RECT rect, clipped_rect; if (data->in_title_click || data->focus_click_pending) { return; } if (data->skip_update_clipcursor) { return; } if (!GetClipCursor(&clipped_rect)) { return; } if ((mouse->relative_mode || (window->flags & SDL_WINDOW_INPUT_GRABBED)) && (window->flags & SDL_WINDOW_INPUT_FOCUS)) { if (mouse->relative_mode && !mouse->relative_mode_warp) { if (GetWindowRect(data->hwnd, &rect)) { LONG cx, cy; cx = (rect.left + rect.right) / 2; cy = (rect.top + rect.bottom) / 2; /* Make an absurdly small clip rect */ rect.left = cx - 1; rect.right = cx + 1; rect.top = cy - 1; rect.bottom = cy + 1; if (SDL_memcmp(&rect, &clipped_rect, sizeof(rect)) != 0) { if (ClipCursor(&rect)) { data->cursor_clipped_rect = rect; } } } } else { if (GetClientRect(data->hwnd, &rect) && !IsRectEmpty(&rect)) { ClientToScreen(data->hwnd, (LPPOINT) & rect); ClientToScreen(data->hwnd, (LPPOINT) & rect + 1); if (SDL_memcmp(&rect, &clipped_rect, sizeof(rect)) != 0) { if (ClipCursor(&rect)) { data->cursor_clipped_rect = rect; } } } } } else if (SDL_memcmp(&clipped_rect, &data->cursor_clipped_rect, sizeof(clipped_rect)) == 0) { ClipCursor(NULL); SDL_zero(data->cursor_clipped_rect); } data->last_updated_clipcursor = SDL_GetTicks(); } int WIN_SetWindowHitTest(SDL_Window *window, SDL_bool enabled) { return 0; /* just succeed, the real work is done elsewhere. */ } int WIN_SetWindowOpacity(_THIS, SDL_Window * window, float opacity) { const SDL_WindowData *data = (SDL_WindowData *) window->driverdata; const HWND hwnd = data->hwnd; const LONG style = GetWindowLong(hwnd, GWL_EXSTYLE); SDL_assert(style != 0); if (opacity == 1.0f) { /* want it fully opaque, just mark it unlayered if necessary. */ if (style & WS_EX_LAYERED) { if (SetWindowLong(hwnd, GWL_EXSTYLE, style & ~WS_EX_LAYERED) == 0) { return WIN_SetError("SetWindowLong()"); } } } else { const BYTE alpha = (BYTE) ((int) (opacity * 255.0f)); /* want it transparent, mark it layered if necessary. */ if ((style & WS_EX_LAYERED) == 0) { if (SetWindowLong(hwnd, GWL_EXSTYLE, style | WS_EX_LAYERED) == 0) { return WIN_SetError("SetWindowLong()"); } } if (SetLayeredWindowAttributes(hwnd, 0, alpha, LWA_ALPHA) == 0) { return WIN_SetError("SetLayeredWindowAttributes()"); } } return 0; } void WIN_AcceptDragAndDrop(SDL_Window * window, SDL_bool accept) { const SDL_WindowData *data = (SDL_WindowData *) window->driverdata; DragAcceptFiles(data->hwnd, accept ? TRUE : FALSE); } #endif /* SDL_VIDEO_DRIVER_WINDOWS */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/windows/SDL_windowswindow.c
C
apache-2.0
32,344