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_internal.h"
#ifndef SDL_windowswindow_h_
#define SDL_windowswindow_h_
#if SDL_VIDEO_OPENGL_EGL
#include "../SDL_egl_c.h"
#endif
typedef struct
{
SDL_Window *window;
HWND hwnd;
HWND parent;
HDC hdc;
HDC mdc;
HINSTANCE hinstance;
HBITMAP hbm;
WNDPROC wndproc;
SDL_bool created;
WPARAM mouse_button_flags;
LPARAM last_pointer_update;
SDL_bool initializing;
SDL_bool expected_resize;
SDL_bool in_border_change;
SDL_bool in_title_click;
Uint8 focus_click_pending;
SDL_bool skip_update_clipcursor;
Uint32 last_updated_clipcursor;
SDL_bool windowed_mode_was_maximized;
SDL_bool in_window_deactivation;
RECT cursor_clipped_rect;
struct SDL_VideoData *videodata;
#if SDL_VIDEO_OPENGL_EGL
EGLSurface egl_surface;
#endif
} SDL_WindowData;
extern int WIN_CreateWindow(_THIS, SDL_Window * window);
extern int WIN_CreateWindowFrom(_THIS, SDL_Window * window, const void *data);
extern void WIN_SetWindowTitle(_THIS, SDL_Window * window);
extern void WIN_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon);
extern void WIN_SetWindowPosition(_THIS, SDL_Window * window);
extern void WIN_SetWindowSize(_THIS, SDL_Window * window);
extern int WIN_GetWindowBordersSize(_THIS, SDL_Window * window, int *top, int *left, int *bottom, int *right);
extern int WIN_SetWindowOpacity(_THIS, SDL_Window * window, float opacity);
extern void WIN_ShowWindow(_THIS, SDL_Window * window);
extern void WIN_HideWindow(_THIS, SDL_Window * window);
extern void WIN_RaiseWindow(_THIS, SDL_Window * window);
extern void WIN_MaximizeWindow(_THIS, SDL_Window * window);
extern void WIN_MinimizeWindow(_THIS, SDL_Window * window);
extern void WIN_RestoreWindow(_THIS, SDL_Window * window);
extern void WIN_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered);
extern void WIN_SetWindowResizable(_THIS, SDL_Window * window, SDL_bool resizable);
extern void WIN_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen);
extern int WIN_SetWindowGammaRamp(_THIS, SDL_Window * window, const Uint16 * ramp);
extern int WIN_GetWindowGammaRamp(_THIS, SDL_Window * window, Uint16 * ramp);
extern void WIN_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed);
extern void WIN_DestroyWindow(_THIS, SDL_Window * window);
extern SDL_bool WIN_GetWindowWMInfo(_THIS, SDL_Window * window,
struct SDL_SysWMinfo *info);
extern void WIN_OnWindowEnter(_THIS, SDL_Window * window);
extern void WIN_UpdateClipCursor(SDL_Window *window);
extern int WIN_SetWindowHitTest(SDL_Window *window, SDL_bool enabled);
extern void WIN_AcceptDragAndDrop(SDL_Window * window, SDL_bool accept);
#endif /* SDL_windowswindow_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/windows/SDL_windowswindow.h | C | apache-2.0 | 3,755 |
/*
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.
*/
#define MAX_WMMSG (sizeof(wmtab)/sizeof(wmtab[0]))
char *wmtab[] = {
"WM_NULL",
"WM_CREATE",
"WM_DESTROY",
"WM_MOVE",
"UNKNOWN (4)",
"WM_SIZE",
"WM_ACTIVATE",
"WM_SETFOCUS",
"WM_KILLFOCUS",
"UNKNOWN (9)",
"WM_ENABLE",
"WM_SETREDRAW",
"WM_SETTEXT",
"WM_GETTEXT",
"WM_GETTEXTLENGTH",
"WM_PAINT",
"WM_CLOSE",
"WM_QUERYENDSESSION",
"WM_QUIT",
"WM_QUERYOPEN",
"WM_ERASEBKGND",
"WM_SYSCOLORCHANGE",
"WM_ENDSESSION",
"UNKNOWN (23)",
"WM_SHOWWINDOW",
"UNKNOWN (25)",
"WM_SETTINGCHANGE",
"WM_DEVMODECHANGE",
"WM_ACTIVATEAPP",
"WM_FONTCHANGE",
"WM_TIMECHANGE",
"WM_CANCELMODE",
"WM_SETCURSOR",
"WM_MOUSEACTIVATE",
"WM_CHILDACTIVATE",
"WM_QUEUESYNC",
"WM_GETMINMAXINFO",
"UNKNOWN (37)",
"WM_PAINTICON",
"WM_ICONERASEBKGND",
"WM_NEXTDLGCTL",
"UNKNOWN (41)",
"WM_SPOOLERSTATUS",
"WM_DRAWITEM",
"WM_MEASUREITEM",
"WM_DELETEITEM",
"WM_VKEYTOITEM",
"WM_CHARTOITEM",
"WM_SETFONT",
"WM_GETFONT",
"WM_SETHOTKEY",
"WM_GETHOTKEY",
"UNKNOWN (52)",
"UNKNOWN (53)",
"UNKNOWN (54)",
"WM_QUERYDRAGICON",
"UNKNOWN (56)",
"WM_COMPAREITEM",
"UNKNOWN (58)",
"UNKNOWN (59)",
"UNKNOWN (60)",
"WM_GETOBJECT",
"UNKNOWN (62)",
"UNKNOWN (63)",
"UNKNOWN (64)",
"WM_COMPACTING",
"UNKNOWN (66)",
"UNKNOWN (67)",
"WM_COMMNOTIFY",
"UNKNOWN (69)",
"WM_WINDOWPOSCHANGING",
"WM_WINDOWPOSCHANGED",
"WM_POWER",
"UNKNOWN (73)",
"WM_COPYDATA",
"WM_CANCELJOURNAL",
"UNKNOWN (76)",
"UNKNOWN (77)",
"WM_NOTIFY",
"UNKNOWN (79)",
"WM_INPUTLANGCHANGEREQUEST",
"WM_INPUTLANGCHANGE",
"WM_TCARD",
"WM_HELP",
"WM_USERCHANGED",
"WM_NOTIFYFORMAT",
"UNKNOWN (86)",
"UNKNOWN (87)",
"UNKNOWN (88)",
"UNKNOWN (89)",
"UNKNOWN (90)",
"UNKNOWN (91)",
"UNKNOWN (92)",
"UNKNOWN (93)",
"UNKNOWN (94)",
"UNKNOWN (95)",
"UNKNOWN (96)",
"UNKNOWN (97)",
"UNKNOWN (98)",
"UNKNOWN (99)",
"UNKNOWN (100)",
"UNKNOWN (101)",
"UNKNOWN (102)",
"UNKNOWN (103)",
"UNKNOWN (104)",
"UNKNOWN (105)",
"UNKNOWN (106)",
"UNKNOWN (107)",
"UNKNOWN (108)",
"UNKNOWN (109)",
"UNKNOWN (110)",
"UNKNOWN (111)",
"UNKNOWN (112)",
"UNKNOWN (113)",
"UNKNOWN (114)",
"UNKNOWN (115)",
"UNKNOWN (116)",
"UNKNOWN (117)",
"UNKNOWN (118)",
"UNKNOWN (119)",
"UNKNOWN (120)",
"UNKNOWN (121)",
"UNKNOWN (122)",
"WM_CONTEXTMENU",
"WM_STYLECHANGING",
"WM_STYLECHANGED",
"WM_DISPLAYCHANGE",
"WM_GETICON",
"WM_SETICON",
"WM_NCCREATE",
"WM_NCDESTROY",
"WM_NCCALCSIZE",
"WM_NCHITTEST",
"WM_NCPAINT",
"WM_NCACTIVATE",
"WM_GETDLGCODE",
"WM_SYNCPAINT",
"UNKNOWN (137)",
"UNKNOWN (138)",
"UNKNOWN (139)",
"UNKNOWN (140)",
"UNKNOWN (141)",
"UNKNOWN (142)",
"UNKNOWN (143)",
"UNKNOWN (144)",
"UNKNOWN (145)",
"UNKNOWN (146)",
"UNKNOWN (147)",
"UNKNOWN (148)",
"UNKNOWN (149)",
"UNKNOWN (150)",
"UNKNOWN (151)",
"UNKNOWN (152)",
"UNKNOWN (153)",
"UNKNOWN (154)",
"UNKNOWN (155)",
"UNKNOWN (156)",
"UNKNOWN (157)",
"UNKNOWN (158)",
"UNKNOWN (159)",
"WM_NCMOUSEMOVE",
"WM_NCLBUTTONDOWN",
"WM_NCLBUTTONUP",
"WM_NCLBUTTONDBLCLK",
"WM_NCRBUTTONDOWN",
"WM_NCRBUTTONUP",
"WM_NCRBUTTONDBLCLK",
"WM_NCMBUTTONDOWN",
"WM_NCMBUTTONUP",
"WM_NCMBUTTONDBLCLK",
"UNKNOWN (170)",
"WM_NCXBUTTONDOWN",
"WM_NCXBUTTONUP",
"WM_NCXBUTTONDBLCLK",
"WM_NCUAHDRAWCAPTION",
"WM_NCUAHDRAWFRAME",
"UNKNOWN (176)",
"UNKNOWN (177)",
"UNKNOWN (178)",
"UNKNOWN (179)",
"UNKNOWN (180)",
"UNKNOWN (181)",
"UNKNOWN (182)",
"UNKNOWN (183)",
"UNKNOWN (184)",
"UNKNOWN (185)",
"UNKNOWN (186)",
"UNKNOWN (187)",
"UNKNOWN (188)",
"UNKNOWN (189)",
"UNKNOWN (190)",
"UNKNOWN (191)",
"UNKNOWN (192)",
"UNKNOWN (193)",
"UNKNOWN (194)",
"UNKNOWN (195)",
"UNKNOWN (196)",
"UNKNOWN (197)",
"UNKNOWN (198)",
"UNKNOWN (199)",
"UNKNOWN (200)",
"UNKNOWN (201)",
"UNKNOWN (202)",
"UNKNOWN (203)",
"UNKNOWN (204)",
"UNKNOWN (205)",
"UNKNOWN (206)",
"UNKNOWN (207)",
"UNKNOWN (208)",
"UNKNOWN (209)",
"UNKNOWN (210)",
"UNKNOWN (211)",
"UNKNOWN (212)",
"UNKNOWN (213)",
"UNKNOWN (214)",
"UNKNOWN (215)",
"UNKNOWN (216)",
"UNKNOWN (217)",
"UNKNOWN (218)",
"UNKNOWN (219)",
"UNKNOWN (220)",
"UNKNOWN (221)",
"UNKNOWN (222)",
"UNKNOWN (223)",
"UNKNOWN (224)",
"UNKNOWN (225)",
"UNKNOWN (226)",
"UNKNOWN (227)",
"UNKNOWN (228)",
"UNKNOWN (229)",
"UNKNOWN (230)",
"UNKNOWN (231)",
"UNKNOWN (232)",
"UNKNOWN (233)",
"UNKNOWN (234)",
"UNKNOWN (235)",
"UNKNOWN (236)",
"UNKNOWN (237)",
"UNKNOWN (238)",
"UNKNOWN (239)",
"UNKNOWN (240)",
"UNKNOWN (241)",
"UNKNOWN (242)",
"UNKNOWN (243)",
"UNKNOWN (244)",
"UNKNOWN (245)",
"UNKNOWN (246)",
"UNKNOWN (247)",
"UNKNOWN (248)",
"UNKNOWN (249)",
"UNKNOWN (250)",
"UNKNOWN (251)",
"UNKNOWN (252)",
"UNKNOWN (253)",
"UNKNOWN (254)",
"WM_INPUT",
"WM_KEYDOWN",
"WM_KEYUP",
"WM_CHAR",
"WM_DEADCHAR",
"WM_SYSKEYDOWN",
"WM_SYSKEYUP",
"WM_SYSCHAR",
"WM_SYSDEADCHAR",
"WM_KEYLAST",
"UNKNOWN (265)",
"UNKNOWN (266)",
"UNKNOWN (267)",
"UNKNOWN (268)",
"UNKNOWN (269)",
"UNKNOWN (270)",
"UNKNOWN (271)",
"WM_INITDIALOG",
"WM_COMMAND",
"WM_SYSCOMMAND",
"WM_TIMER",
"WM_HSCROLL",
"WM_VSCROLL",
"WM_INITMENU",
"WM_INITMENUPOPUP",
"UNKNOWN (280)",
"WM_GESTURE",
"UNKNOWN (282)",
"UNKNOWN (283)",
"UNKNOWN (284)",
"UNKNOWN (285)",
"UNKNOWN (286)",
"WM_MENUSELECT",
"WM_MENUCHAR",
"WM_ENTERIDLE",
"WM_MENURBUTTONUP",
"WM_MENUDRAG",
"WM_MENUGETOBJECT",
"WM_UNINITMENUPOPUP",
"WM_MENUCOMMAND",
"UNKNOWN (295)",
"UNKNOWN (296)",
"UNKNOWN (297)",
"UNKNOWN (298)",
"UNKNOWN (299)",
"UNKNOWN (300)",
"UNKNOWN (301)",
"UNKNOWN (302)",
"UNKNOWN (303)",
"UNKNOWN (304)",
"UNKNOWN (305)",
"WM_CTLCOLORMSGBOX",
"WM_CTLCOLOREDIT",
"WM_CTLCOLORLISTBOX",
"WM_CTLCOLORBTN",
"WM_CTLCOLORDLG",
"WM_CTLCOLORSCROLLBAR",
"WM_CTLCOLORSTATIC",
"UNKNOWN (313)",
"UNKNOWN (314)",
"UNKNOWN (315)",
"UNKNOWN (316)",
"UNKNOWN (317)",
"UNKNOWN (318)",
"UNKNOWN (319)",
"UNKNOWN (320)",
"UNKNOWN (321)",
"UNKNOWN (322)",
"UNKNOWN (323)",
"UNKNOWN (324)",
"UNKNOWN (325)",
"UNKNOWN (326)",
"UNKNOWN (327)",
"UNKNOWN (328)",
"UNKNOWN (329)",
"UNKNOWN (330)",
"UNKNOWN (331)",
"UNKNOWN (332)",
"UNKNOWN (333)",
"UNKNOWN (334)",
"UNKNOWN (335)",
"UNKNOWN (336)",
"UNKNOWN (337)",
"UNKNOWN (338)",
"UNKNOWN (339)",
"UNKNOWN (340)",
"UNKNOWN (341)",
"UNKNOWN (342)",
"UNKNOWN (343)",
"UNKNOWN (344)",
"UNKNOWN (345)",
"UNKNOWN (346)",
"UNKNOWN (347)",
"UNKNOWN (348)",
"UNKNOWN (349)",
"UNKNOWN (350)",
"UNKNOWN (351)",
"UNKNOWN (352)",
"UNKNOWN (353)",
"UNKNOWN (354)",
"UNKNOWN (355)",
"UNKNOWN (356)",
"UNKNOWN (357)",
"UNKNOWN (358)",
"UNKNOWN (359)",
"UNKNOWN (360)",
"UNKNOWN (361)",
"UNKNOWN (362)",
"UNKNOWN (363)",
"UNKNOWN (364)",
"UNKNOWN (365)",
"UNKNOWN (366)",
"UNKNOWN (367)",
"UNKNOWN (368)",
"UNKNOWN (369)",
"UNKNOWN (370)",
"UNKNOWN (371)",
"UNKNOWN (372)",
"UNKNOWN (373)",
"UNKNOWN (374)",
"UNKNOWN (375)",
"UNKNOWN (376)",
"UNKNOWN (377)",
"UNKNOWN (378)",
"UNKNOWN (379)",
"UNKNOWN (380)",
"UNKNOWN (381)",
"UNKNOWN (382)",
"UNKNOWN (383)",
"UNKNOWN (384)",
"UNKNOWN (385)",
"UNKNOWN (386)",
"UNKNOWN (387)",
"UNKNOWN (388)",
"UNKNOWN (389)",
"UNKNOWN (390)",
"UNKNOWN (391)",
"UNKNOWN (392)",
"UNKNOWN (393)",
"UNKNOWN (394)",
"UNKNOWN (395)",
"UNKNOWN (396)",
"UNKNOWN (397)",
"UNKNOWN (398)",
"UNKNOWN (399)",
"UNKNOWN (400)",
"UNKNOWN (401)",
"UNKNOWN (402)",
"UNKNOWN (403)",
"UNKNOWN (404)",
"UNKNOWN (405)",
"UNKNOWN (406)",
"UNKNOWN (407)",
"UNKNOWN (408)",
"UNKNOWN (409)",
"UNKNOWN (410)",
"UNKNOWN (411)",
"UNKNOWN (412)",
"UNKNOWN (413)",
"UNKNOWN (414)",
"UNKNOWN (415)",
"UNKNOWN (416)",
"UNKNOWN (417)",
"UNKNOWN (418)",
"UNKNOWN (419)",
"UNKNOWN (420)",
"UNKNOWN (421)",
"UNKNOWN (422)",
"UNKNOWN (423)",
"UNKNOWN (424)",
"UNKNOWN (425)",
"UNKNOWN (426)",
"UNKNOWN (427)",
"UNKNOWN (428)",
"UNKNOWN (429)",
"UNKNOWN (430)",
"UNKNOWN (431)",
"UNKNOWN (432)",
"UNKNOWN (433)",
"UNKNOWN (434)",
"UNKNOWN (435)",
"UNKNOWN (436)",
"UNKNOWN (437)",
"UNKNOWN (438)",
"UNKNOWN (439)",
"UNKNOWN (440)",
"UNKNOWN (441)",
"UNKNOWN (442)",
"UNKNOWN (443)",
"UNKNOWN (444)",
"UNKNOWN (445)",
"UNKNOWN (446)",
"UNKNOWN (447)",
"UNKNOWN (448)",
"UNKNOWN (449)",
"UNKNOWN (450)",
"UNKNOWN (451)",
"UNKNOWN (452)",
"UNKNOWN (453)",
"UNKNOWN (454)",
"UNKNOWN (455)",
"UNKNOWN (456)",
"UNKNOWN (457)",
"UNKNOWN (458)",
"UNKNOWN (459)",
"UNKNOWN (460)",
"UNKNOWN (461)",
"UNKNOWN (462)",
"UNKNOWN (463)",
"UNKNOWN (464)",
"UNKNOWN (465)",
"UNKNOWN (466)",
"UNKNOWN (467)",
"UNKNOWN (468)",
"UNKNOWN (469)",
"UNKNOWN (470)",
"UNKNOWN (471)",
"UNKNOWN (472)",
"UNKNOWN (473)",
"UNKNOWN (474)",
"UNKNOWN (475)",
"UNKNOWN (476)",
"UNKNOWN (477)",
"UNKNOWN (478)",
"UNKNOWN (479)",
"UNKNOWN (480)",
"UNKNOWN (481)",
"UNKNOWN (482)",
"UNKNOWN (483)",
"UNKNOWN (484)",
"UNKNOWN (485)",
"UNKNOWN (486)",
"UNKNOWN (487)",
"UNKNOWN (488)",
"UNKNOWN (489)",
"UNKNOWN (490)",
"UNKNOWN (491)",
"UNKNOWN (492)",
"UNKNOWN (493)",
"UNKNOWN (494)",
"UNKNOWN (495)",
"UNKNOWN (496)",
"UNKNOWN (497)",
"UNKNOWN (498)",
"UNKNOWN (499)",
"UNKNOWN (500)",
"UNKNOWN (501)",
"UNKNOWN (502)",
"UNKNOWN (503)",
"UNKNOWN (504)",
"UNKNOWN (505)",
"UNKNOWN (506)",
"UNKNOWN (507)",
"UNKNOWN (508)",
"UNKNOWN (509)",
"UNKNOWN (510)",
"UNKNOWN (511)",
"WM_MOUSEMOVE",
"WM_LBUTTONDOWN",
"WM_LBUTTONUP",
"WM_LBUTTONDBLCLK",
"WM_RBUTTONDOWN",
"WM_RBUTTONUP",
"WM_RBUTTONDBLCLK",
"WM_MBUTTONDOWN",
"WM_MBUTTONUP",
"WM_MOUSELAST",
"WM_MOUSEWHEEL",
"WM_XBUTTONDOWN",
"WM_XBUTTONUP",
"UNKNOWN (525)",
"UNKNOWN (526)",
"UNKNOWN (527)",
"WM_PARENTNOTIFY",
"WM_ENTERMENULOOP",
"WM_EXITMENULOOP",
"WM_NEXTMENU",
"WM_SIZING",
"WM_CAPTURECHANGED",
"WM_MOVING",
"UNKNOWN (535)",
"WM_POWERBROADCAST",
"WM_DEVICECHANGE",
"UNKNOWN (538)",
"UNKNOWN (539)",
"UNKNOWN (540)",
"UNKNOWN (541)",
"UNKNOWN (542)",
"UNKNOWN (543)",
"WM_MDICREATE",
"WM_MDIDESTROY",
"WM_MDIACTIVATE",
"WM_MDIRESTORE",
"WM_MDINEXT",
"WM_MDIMAXIMIZE",
"WM_MDITILE",
"WM_MDICASCADE",
"WM_MDIICONARRANGE",
"WM_MDIGETACTIVE",
"UNKNOWN (554)",
"UNKNOWN (555)",
"UNKNOWN (556)",
"UNKNOWN (557)",
"UNKNOWN (558)",
"UNKNOWN (559)",
"WM_MDISETMENU",
"WM_ENTERSIZEMOVE",
"WM_EXITSIZEMOVE",
"WM_DROPFILES",
"WM_MDIREFRESHMENU",
"UNKNOWN (565)",
"UNKNOWN (566)",
"UNKNOWN (567)",
"WM_POINTERDEVICECHANGE",
"WM_POINTERDEVICEINRANGE",
"WM_POINTERDEVICEOUTOFRANGE",
"UNKNOWN (571)",
"UNKNOWN (572)",
"UNKNOWN (573)",
"UNKNOWN (574)",
"UNKNOWN (575)",
"WM_TOUCH",
"WM_NCPOINTERUPDATE",
"WM_NCPOINTERDOWN",
"WM_NCPOINTERUP",
"UNKNOWN (580)",
"WM_POINTERUPDATE",
"WM_POINTERDOWN",
"WM_POINTERUP",
"WM_POINTERENTER",
"WM_POINTERLEAVE",
"WM_POINTERACTIVATE",
"WM_POINTERCAPTURECHANGED",
"WM_TOUCHHITTESTING",
"WM_POINTERWHEEL",
"WM_POINTERHWHEEL",
"DM_POINTERHITTEST",
"UNKNOWN (592)",
"UNKNOWN (593)",
"UNKNOWN (594)",
"UNKNOWN (595)",
"UNKNOWN (596)",
"UNKNOWN (597)",
"UNKNOWN (598)",
"UNKNOWN (599)",
"UNKNOWN (600)",
"UNKNOWN (601)",
"UNKNOWN (602)",
"UNKNOWN (603)",
"UNKNOWN (604)",
"UNKNOWN (605)",
"UNKNOWN (606)",
"UNKNOWN (607)",
"UNKNOWN (608)",
"UNKNOWN (609)",
"UNKNOWN (610)",
"UNKNOWN (611)",
"UNKNOWN (612)",
"UNKNOWN (613)",
"UNKNOWN (614)",
"UNKNOWN (615)",
"UNKNOWN (616)",
"UNKNOWN (617)",
"UNKNOWN (618)",
"UNKNOWN (619)",
"UNKNOWN (620)",
"UNKNOWN (621)",
"UNKNOWN (622)",
"UNKNOWN (623)",
"UNKNOWN (624)",
"UNKNOWN (625)",
"UNKNOWN (626)",
"UNKNOWN (627)",
"UNKNOWN (628)",
"UNKNOWN (629)",
"UNKNOWN (630)",
"UNKNOWN (631)",
"UNKNOWN (632)",
"UNKNOWN (633)",
"UNKNOWN (634)",
"UNKNOWN (635)",
"UNKNOWN (636)",
"UNKNOWN (637)",
"UNKNOWN (638)",
"UNKNOWN (639)",
"UNKNOWN (640)",
"WM_IME_SETCONTEXT",
"WM_IME_NOTIFY",
"WM_IME_CONTROL",
"WM_IME_COMPOSITIONFULL",
"WM_IME_SELECT",
"WM_IME_CHAR",
"UNKNOWN (647)",
"WM_IME_REQUEST",
"UNKNOWN (649)",
"UNKNOWN (650)",
"UNKNOWN (651)",
"UNKNOWN (652)",
"UNKNOWN (653)",
"UNKNOWN (654)",
"UNKNOWN (655)",
"WM_IME_KEYDOWN",
"WM_IME_KEYUP",
"UNKNOWN (658)",
"UNKNOWN (659)",
"UNKNOWN (660)",
"UNKNOWN (661)",
"UNKNOWN (662)",
"UNKNOWN (663)",
"UNKNOWN (664)",
"UNKNOWN (665)",
"UNKNOWN (666)",
"UNKNOWN (667)",
"UNKNOWN (668)",
"UNKNOWN (669)",
"UNKNOWN (670)",
"UNKNOWN (671)",
"WM_NCMOUSEHOVER",
"WM_MOUSEHOVER",
"WM_NCMOUSELEAVE",
"WM_MOUSELEAVE",
"UNKNOWN (676)",
"UNKNOWN (677)",
"UNKNOWN (678)",
"UNKNOWN (679)",
"UNKNOWN (680)",
"UNKNOWN (681)",
"UNKNOWN (682)",
"UNKNOWN (683)",
"UNKNOWN (684)",
"UNKNOWN (685)",
"UNKNOWN (686)",
"UNKNOWN (687)",
"UNKNOWN (688)",
"WM_WTSSESSION_CHANGE",
"UNKNOWN (690)",
"UNKNOWN (691)",
"UNKNOWN (692)",
"UNKNOWN (693)",
"UNKNOWN (694)",
"UNKNOWN (695)",
"UNKNOWN (696)",
"UNKNOWN (697)",
"UNKNOWN (698)",
"UNKNOWN (699)",
"UNKNOWN (700)",
"UNKNOWN (701)",
"UNKNOWN (702)",
"UNKNOWN (703)",
"UNKNOWN (704)",
"UNKNOWN (705)",
"UNKNOWN (706)",
"UNKNOWN (707)",
"UNKNOWN (708)",
"UNKNOWN (709)",
"UNKNOWN (710)",
"UNKNOWN (711)",
"UNKNOWN (712)",
"UNKNOWN (713)",
"UNKNOWN (714)",
"UNKNOWN (715)",
"UNKNOWN (716)",
"UNKNOWN (717)",
"UNKNOWN (718)",
"UNKNOWN (719)",
"UNKNOWN (720)",
"UNKNOWN (721)",
"UNKNOWN (722)",
"UNKNOWN (723)",
"UNKNOWN (724)",
"UNKNOWN (725)",
"UNKNOWN (726)",
"UNKNOWN (727)",
"UNKNOWN (728)",
"UNKNOWN (729)",
"UNKNOWN (730)",
"UNKNOWN (731)",
"UNKNOWN (732)",
"UNKNOWN (733)",
"UNKNOWN (734)",
"UNKNOWN (735)",
"WM_DPICHANGED",
"UNKNOWN (737)",
"UNKNOWN (738)",
"UNKNOWN (739)",
"UNKNOWN (740)",
"UNKNOWN (741)",
"UNKNOWN (742)",
"UNKNOWN (743)",
"UNKNOWN (744)",
"UNKNOWN (745)",
"UNKNOWN (746)",
"UNKNOWN (747)",
"UNKNOWN (748)",
"UNKNOWN (749)",
"UNKNOWN (750)",
"UNKNOWN (751)",
"UNKNOWN (752)",
"UNKNOWN (753)",
"UNKNOWN (754)",
"UNKNOWN (755)",
"UNKNOWN (756)",
"UNKNOWN (757)",
"UNKNOWN (758)",
"UNKNOWN (759)",
"UNKNOWN (760)",
"UNKNOWN (761)",
"UNKNOWN (762)",
"UNKNOWN (763)",
"UNKNOWN (764)",
"UNKNOWN (765)",
"UNKNOWN (766)",
"UNKNOWN (767)",
"WM_CUT",
"WM_COPY",
"WM_PASTE",
"WM_CLEAR",
"WM_UNDO",
"WM_RENDERFORMAT",
"WM_RENDERALLFORMATS",
"WM_DESTROYCLIPBOARD",
"WM_DRAWCLIPBOARD",
"WM_PAINTCLIPBOARD",
"WM_VSCROLLCLIPBOARD",
"WM_SIZECLIPBOARD",
"WM_ASKCBFORMATNAME",
"WM_CHANGECBCHAIN",
"WM_HSCROLLCLIPBOARD",
"WM_QUERYNEWPALETTE",
"WM_PALETTEISCHANGING",
"WM_PALETTECHANGED",
"WM_HOTKEY",
"UNKNOWN (787)",
"UNKNOWN (788)",
"UNKNOWN (789)",
"UNKNOWN (790)",
"WM_PRINT",
"WM_PRINTCLIENT",
"WM_APPCOMMAND",
"WM_THEMECHANGED",
"UNKNOWN (795)",
"UNKNOWN (796)",
"WM_CLIPBOARDUPDATE",
"WM_DWMCOMPOSITIONCHANGED",
"WM_DWMNCRENDERINGCHANGED",
"WM_DWMCOLORIZATIONCOLORCHANGED",
"WM_DWMWINDOWMAXIMIZEDCHANGE",
"UNKNOWN (802)",
"WM_DWMSENDICONICTHUMBNAIL",
"UNKNOWN (804)",
"UNKNOWN (805)",
"WM_DWMSENDICONICLIVEPREVIEWBITMAP",
"UNKNOWN (807)",
"UNKNOWN (808)",
"UNKNOWN (809)",
"UNKNOWN (810)",
"UNKNOWN (811)",
"UNKNOWN (812)",
"UNKNOWN (813)",
"UNKNOWN (814)",
"UNKNOWN (815)",
"UNKNOWN (816)",
"UNKNOWN (817)",
"UNKNOWN (818)",
"UNKNOWN (819)",
"UNKNOWN (820)",
"UNKNOWN (821)",
"UNKNOWN (822)",
"UNKNOWN (823)",
"UNKNOWN (824)",
"UNKNOWN (825)",
"UNKNOWN (826)",
"UNKNOWN (827)",
"UNKNOWN (828)",
"UNKNOWN (829)",
"UNKNOWN (830)",
"WM_GETTITLEBARINFOEX",
"UNKNOWN (832)",
"UNKNOWN (833)",
"UNKNOWN (834)",
"UNKNOWN (835)",
"UNKNOWN (836)",
"UNKNOWN (837)",
"UNKNOWN (838)",
"UNKNOWN (839)",
"UNKNOWN (840)",
"UNKNOWN (841)",
"UNKNOWN (842)",
"UNKNOWN (843)",
"UNKNOWN (844)",
"UNKNOWN (845)",
"UNKNOWN (846)",
"UNKNOWN (847)",
"UNKNOWN (848)",
"UNKNOWN (849)",
"UNKNOWN (850)",
"UNKNOWN (851)",
"UNKNOWN (852)",
"UNKNOWN (853)",
"UNKNOWN (854)",
"UNKNOWN (855)",
"WM_HANDHELDFIRST",
"UNKNOWN (857)",
"UNKNOWN (858)",
"UNKNOWN (859)",
"UNKNOWN (860)",
"UNKNOWN (861)",
"UNKNOWN (862)",
"WM_HANDHELDLAST",
"WM_AFXFIRST",
"UNKNOWN (865)",
"UNKNOWN (866)",
"UNKNOWN (867)",
"UNKNOWN (868)",
"UNKNOWN (869)",
"UNKNOWN (870)",
"UNKNOWN (871)",
"UNKNOWN (872)",
"UNKNOWN (873)",
"UNKNOWN (874)",
"UNKNOWN (875)",
"UNKNOWN (876)",
"UNKNOWN (877)",
"UNKNOWN (878)",
"UNKNOWN (879)",
"UNKNOWN (880)",
"UNKNOWN (881)",
"UNKNOWN (882)",
"UNKNOWN (883)",
"UNKNOWN (884)",
"UNKNOWN (885)",
"UNKNOWN (886)",
"UNKNOWN (887)",
"UNKNOWN (888)",
"UNKNOWN (889)",
"UNKNOWN (890)",
"UNKNOWN (891)",
"UNKNOWN (892)",
"UNKNOWN (893)",
"UNKNOWN (894)",
"WM_AFXLAST",
"WM_PENWINFIRST",
"UNKNOWN (897)",
"UNKNOWN (898)",
"UNKNOWN (899)",
"UNKNOWN (900)",
"UNKNOWN (901)",
"UNKNOWN (902)",
"UNKNOWN (903)",
"UNKNOWN (904)",
"UNKNOWN (905)",
"UNKNOWN (906)",
"UNKNOWN (907)",
"UNKNOWN (908)",
"UNKNOWN (909)",
"UNKNOWN (910)",
"WM_PENWINLAST",
"UNKNOWN (912)",
"UNKNOWN (913)",
"UNKNOWN (914)",
"UNKNOWN (915)",
"UNKNOWN (916)",
"UNKNOWN (917)",
"UNKNOWN (918)",
"UNKNOWN (919)",
"UNKNOWN (920)",
"UNKNOWN (921)",
"UNKNOWN (922)",
"UNKNOWN (923)",
"UNKNOWN (924)",
"UNKNOWN (925)",
"UNKNOWN (926)",
"UNKNOWN (927)",
"UNKNOWN (928)",
"UNKNOWN (929)",
"UNKNOWN (930)",
"UNKNOWN (931)",
"UNKNOWN (932)",
"UNKNOWN (933)",
"UNKNOWN (934)",
"UNKNOWN (935)",
"UNKNOWN (936)",
"UNKNOWN (937)",
"UNKNOWN (938)",
"UNKNOWN (939)",
"UNKNOWN (940)",
"UNKNOWN (941)",
"UNKNOWN (942)",
"UNKNOWN (943)",
"UNKNOWN (944)",
"UNKNOWN (945)",
"UNKNOWN (946)",
"UNKNOWN (947)",
"UNKNOWN (948)",
"UNKNOWN (949)",
"UNKNOWN (950)",
"UNKNOWN (951)",
"UNKNOWN (952)",
"UNKNOWN (953)",
"UNKNOWN (954)",
"UNKNOWN (955)",
"UNKNOWN (956)",
"UNKNOWN (957)",
"UNKNOWN (958)",
"UNKNOWN (959)",
"UNKNOWN (960)",
"UNKNOWN (961)",
"UNKNOWN (962)",
"UNKNOWN (963)",
"UNKNOWN (964)",
"UNKNOWN (965)",
"UNKNOWN (966)",
"UNKNOWN (967)",
"UNKNOWN (968)",
"UNKNOWN (969)",
"UNKNOWN (970)",
"UNKNOWN (971)",
"UNKNOWN (972)",
"UNKNOWN (973)",
"UNKNOWN (974)",
"UNKNOWN (975)",
"UNKNOWN (976)",
"UNKNOWN (977)",
"UNKNOWN (978)",
"UNKNOWN (979)",
"UNKNOWN (980)",
"UNKNOWN (981)",
"UNKNOWN (982)",
"UNKNOWN (983)",
"UNKNOWN (984)",
"UNKNOWN (985)",
"UNKNOWN (986)",
"UNKNOWN (987)",
"UNKNOWN (988)",
"UNKNOWN (989)",
"UNKNOWN (990)",
"UNKNOWN (991)",
"UNKNOWN (992)",
"UNKNOWN (993)",
"UNKNOWN (994)",
"UNKNOWN (995)",
"UNKNOWN (996)",
"UNKNOWN (997)",
"UNKNOWN (998)",
"UNKNOWN (999)",
"UNKNOWN (1000)",
"UNKNOWN (1001)",
"UNKNOWN (1002)",
"UNKNOWN (1003)",
"UNKNOWN (1004)",
"UNKNOWN (1005)",
"UNKNOWN (1006)",
"UNKNOWN (1007)",
"UNKNOWN (1008)",
"UNKNOWN (1009)",
"UNKNOWN (1010)",
"UNKNOWN (1011)",
"UNKNOWN (1012)",
"UNKNOWN (1013)",
"UNKNOWN (1014)",
"UNKNOWN (1015)",
"UNKNOWN (1016)",
"UNKNOWN (1017)",
"UNKNOWN (1018)",
"UNKNOWN (1019)",
"UNKNOWN (1020)",
"UNKNOWN (1021)",
"UNKNOWN (1022)",
"UNKNOWN (1023)",
"WM_USER"
};
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/windows/wmmsg.h | C | apache-2.0 | 22,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_WINRT
/*
* Windows includes:
*/
#include <Windows.h>
using namespace Windows::UI::Core;
using Windows::UI::Core::CoreCursor;
/*
* SDL includes:
*/
#include "SDL_winrtevents_c.h"
#include "../../core/winrt/SDL_winrtapp_common.h"
#include "../../core/winrt/SDL_winrtapp_direct3d.h"
#include "../../core/winrt/SDL_winrtapp_xaml.h"
#include "SDL_assert.h"
#include "SDL_system.h"
extern "C" {
#include "../../thread/SDL_systhread.h"
#include "../SDL_sysvideo.h"
#include "../../events/SDL_events_c.h"
}
/* Forward declarations */
static void WINRT_YieldXAMLThread();
/* Global event management */
void
WINRT_PumpEvents(_THIS)
{
if (SDL_WinRTGlobalApp) {
SDL_WinRTGlobalApp->PumpEvents();
} else if (WINRT_XAMLWasEnabled) {
WINRT_YieldXAMLThread();
}
}
/* XAML Thread management */
enum SDL_XAMLAppThreadState
{
ThreadState_NotLaunched = 0,
ThreadState_Running,
ThreadState_Yielding
};
static SDL_XAMLAppThreadState _threadState = ThreadState_NotLaunched;
static SDL_Thread * _XAMLThread = nullptr;
static SDL_mutex * _mutex = nullptr;
static SDL_cond * _cond = nullptr;
static void
WINRT_YieldXAMLThread()
{
SDL_LockMutex(_mutex);
SDL_assert(_threadState == ThreadState_Running);
_threadState = ThreadState_Yielding;
SDL_UnlockMutex(_mutex);
SDL_CondSignal(_cond);
SDL_LockMutex(_mutex);
while (_threadState != ThreadState_Running) {
SDL_CondWait(_cond, _mutex);
}
SDL_UnlockMutex(_mutex);
}
static int
WINRT_XAMLThreadMain(void * userdata)
{
// TODO, WinRT: pass the C-style main() a reasonably realistic
// representation of command line arguments.
int argc = 0;
char **argv = NULL;
return WINRT_SDLAppEntryPoint(argc, argv);
}
void
WINRT_CycleXAMLThread(void)
{
switch (_threadState) {
case ThreadState_NotLaunched:
{
_cond = SDL_CreateCond();
_mutex = SDL_CreateMutex();
_threadState = ThreadState_Running;
_XAMLThread = SDL_CreateThreadInternal(WINRT_XAMLThreadMain, "SDL/XAML App Thread", 0, nullptr);
SDL_LockMutex(_mutex);
while (_threadState != ThreadState_Yielding) {
SDL_CondWait(_cond, _mutex);
}
SDL_UnlockMutex(_mutex);
break;
}
case ThreadState_Running:
{
SDL_assert(false);
break;
}
case ThreadState_Yielding:
{
SDL_LockMutex(_mutex);
SDL_assert(_threadState == ThreadState_Yielding);
_threadState = ThreadState_Running;
SDL_UnlockMutex(_mutex);
SDL_CondSignal(_cond);
SDL_LockMutex(_mutex);
while (_threadState != ThreadState_Yielding) {
SDL_CondWait(_cond, _mutex);
}
SDL_UnlockMutex(_mutex);
}
}
}
#endif /* SDL_VIDEO_DRIVER_WINRT */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/winrt/SDL_winrtevents.cpp | C++ | apache-2.0 | 3,963 |
/*
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_config.h"
extern "C" {
#include "../SDL_sysvideo.h"
}
/*
* Internal-use, C-style functions:
*/
#ifdef __cplusplus
extern "C" {
#endif
extern void WINRT_InitTouch(_THIS);
extern void WINRT_PumpEvents(_THIS);
#ifdef __cplusplus
}
#endif
/*
* Internal-use, C++/CX functions:
*/
#ifdef __cplusplus_winrt
/* Pointers (Mice, Touch, etc.) */
typedef enum {
NormalizeZeroToOne,
TransformToSDLWindowSize
} WINRT_CursorNormalizationType;
extern Windows::Foundation::Point WINRT_TransformCursorPosition(SDL_Window * window,
Windows::Foundation::Point rawPosition,
WINRT_CursorNormalizationType normalization);
extern Uint8 WINRT_GetSDLButtonForPointerPoint(Windows::UI::Input::PointerPoint ^pt);
extern void WINRT_ProcessPointerPressedEvent(SDL_Window *window, Windows::UI::Input::PointerPoint ^pointerPoint);
extern void WINRT_ProcessPointerMovedEvent(SDL_Window *window, Windows::UI::Input::PointerPoint ^pointerPoint);
extern void WINRT_ProcessPointerReleasedEvent(SDL_Window *window, Windows::UI::Input::PointerPoint ^pointerPoint);
extern void WINRT_ProcessPointerEnteredEvent(SDL_Window *window, Windows::UI::Input::PointerPoint ^pointerPoint);
extern void WINRT_ProcessPointerExitedEvent(SDL_Window *window, Windows::UI::Input::PointerPoint ^pointerPoint);
extern void WINRT_ProcessPointerWheelChangedEvent(SDL_Window *window, Windows::UI::Input::PointerPoint ^pointerPoint);
extern void WINRT_ProcessMouseMovedEvent(SDL_Window * window, Windows::Devices::Input::MouseEventArgs ^args);
/* Keyboard */
extern void WINRT_ProcessKeyDownEvent(Windows::UI::Core::KeyEventArgs ^args);
extern void WINRT_ProcessKeyUpEvent(Windows::UI::Core::KeyEventArgs ^args);
extern void WINRT_ProcessCharacterReceivedEvent(Windows::UI::Core::CharacterReceivedEventArgs ^args);
#if NTDDI_VERSION >= NTDDI_WIN10
extern SDL_bool WINRT_HasScreenKeyboardSupport(_THIS);
extern void WINRT_ShowScreenKeyboard(_THIS, SDL_Window *window);
extern void WINRT_HideScreenKeyboard(_THIS, SDL_Window *window);
extern SDL_bool WINRT_IsScreenKeyboardShown(_THIS, SDL_Window *window);
#endif // NTDDI_VERSION >= ...
/* XAML Thread Management */
extern void WINRT_CycleXAMLThread(void);
#endif // ifdef __cplusplus_winrt
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/winrt/SDL_winrtevents_c.h | C | apache-2.0 | 3,320 |
/*
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_WINRT
/* Windows includes */
#include <roapi.h>
#include <windows.foundation.h>
#include <windows.system.h>
/* SDL includes */
extern "C" {
#include "SDL_mouse.h"
#include "../SDL_sysvideo.h"
}
#include "SDL_winrtvideo_cpp.h"
/* Game Bar events can come in off the main thread. Use the following
WinRT CoreDispatcher to deal with them on SDL's thread.
*/
static Platform::WeakReference WINRT_MainThreadDispatcher;
/* Win10's initial SDK (the 10.0.10240.0 release) does not include references
to Game Bar APIs, as the Game Bar was released via Win10 10.0.10586.0.
Declare its WinRT/COM interface here, to allow compilation with earlier
Windows SDKs.
*/
MIDL_INTERFACE("1DB9A292-CC78-4173-BE45-B61E67283EA7")
IGameBarStatics_ : public IInspectable
{
public:
virtual HRESULT STDMETHODCALLTYPE add_VisibilityChanged(
__FIEventHandler_1_IInspectable *handler,
Windows::Foundation::EventRegistrationToken *token) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_VisibilityChanged(
Windows::Foundation::EventRegistrationToken token) = 0;
virtual HRESULT STDMETHODCALLTYPE add_IsInputRedirectedChanged(
__FIEventHandler_1_IInspectable *handler,
Windows::Foundation::EventRegistrationToken *token) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_IsInputRedirectedChanged(
Windows::Foundation::EventRegistrationToken token) = 0;
virtual HRESULT STDMETHODCALLTYPE get_Visible(
boolean *value) = 0;
virtual HRESULT STDMETHODCALLTYPE get_IsInputRedirected(
boolean *value) = 0;
};
/* Declare the game bar's COM GUID */
static GUID IID_IGameBarStatics_ = { MAKELONG(0xA292, 0x1DB9), 0xCC78, 0x4173, { 0xBE, 0x45, 0xB6, 0x1E, 0x67, 0x28, 0x3E, 0xA7 } };
/* Retrieves a pointer to the game bar, or NULL if it is not available.
If a pointer is returned, it's ->Release() method must be called
after the caller has finished using it.
*/
static IGameBarStatics_ *
WINRT_GetGameBar()
{
wchar_t *wClassName = L"Windows.Gaming.UI.GameBar";
HSTRING hClassName;
IActivationFactory *pActivationFactory = NULL;
IGameBarStatics_ *pGameBar = NULL;
HRESULT hr;
hr = ::WindowsCreateString(wClassName, (UINT32)wcslen(wClassName), &hClassName);
if (FAILED(hr)) {
goto done;
}
hr = Windows::Foundation::GetActivationFactory(hClassName, &pActivationFactory);
if (FAILED(hr)) {
goto done;
}
pActivationFactory->QueryInterface(IID_IGameBarStatics_, (void **) &pGameBar);
done:
if (pActivationFactory) {
pActivationFactory->Release();
}
if (hClassName) {
::WindowsDeleteString(hClassName);
}
return pGameBar;
}
static void
WINRT_HandleGameBarIsInputRedirected_MainThread()
{
IGameBarStatics_ *gameBar;
boolean isInputRedirected = 0;
if (!WINRT_MainThreadDispatcher) {
/* The game bar event handler has been deregistered! */
return;
}
gameBar = WINRT_GetGameBar();
if (!gameBar) {
/* Shouldn't happen, but just in case... */
return;
}
if (SUCCEEDED(gameBar->get_IsInputRedirected(&isInputRedirected))) {
if ( ! isInputRedirected) {
/* Input-control is now back to the SDL app. Restore the cursor,
in case Windows does not (it does not in either Win10
10.0.10240.0 or 10.0.10586.0, maybe later version(s) too.
*/
SDL_Cursor *cursor = SDL_GetCursor();
SDL_SetCursor(cursor);
}
}
gameBar->Release();
}
static void
WINRT_HandleGameBarIsInputRedirected_NonMainThread(Platform::Object ^ o1, Platform::Object ^o2)
{
Windows::UI::Core::CoreDispatcher ^dispatcher = WINRT_MainThreadDispatcher.Resolve<Windows::UI::Core::CoreDispatcher>();
if (dispatcher) {
dispatcher->RunAsync(
Windows::UI::Core::CoreDispatcherPriority::Normal,
ref new Windows::UI::Core::DispatchedHandler(&WINRT_HandleGameBarIsInputRedirected_MainThread));
}
}
void
WINRT_InitGameBar(_THIS)
{
SDL_VideoData *driverdata = (SDL_VideoData *)_this->driverdata;
IGameBarStatics_ *gameBar = WINRT_GetGameBar();
if (gameBar) {
/* GameBar.IsInputRedirected events can come in via something other than
the main/SDL thread.
Get a WinRT 'CoreDispatcher' that can be used to call back into the
SDL thread.
*/
WINRT_MainThreadDispatcher = Windows::UI::Core::CoreWindow::GetForCurrentThread()->Dispatcher;
Windows::Foundation::EventHandler<Platform::Object ^> ^handler = \
ref new Windows::Foundation::EventHandler<Platform::Object ^>(&WINRT_HandleGameBarIsInputRedirected_NonMainThread);
__FIEventHandler_1_IInspectable * pHandler = reinterpret_cast<__FIEventHandler_1_IInspectable *>(handler);
gameBar->add_IsInputRedirectedChanged(pHandler, &driverdata->gameBarIsInputRedirectedToken);
gameBar->Release();
}
}
void
WINRT_QuitGameBar(_THIS)
{
SDL_VideoData *driverdata;
IGameBarStatics_ *gameBar;
if (!_this || !_this->driverdata) {
return;
}
gameBar = WINRT_GetGameBar();
if (!gameBar) {
return;
}
driverdata = (SDL_VideoData *)_this->driverdata;
if (driverdata->gameBarIsInputRedirectedToken.Value) {
gameBar->remove_IsInputRedirectedChanged(driverdata->gameBarIsInputRedirectedToken);
driverdata->gameBarIsInputRedirectedToken.Value = 0;
}
WINRT_MainThreadDispatcher = nullptr;
gameBar->Release();
}
#endif /* SDL_VIDEO_DRIVER_WINRT */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/winrt/SDL_winrtgamebar.cpp | C++ | apache-2.0 | 6,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.
*/
#include "SDL_config.h"
#ifndef SDL_winrtgamebar_h_
#define SDL_winrtgamebar_h_
#ifdef __cplusplus
/* These are exported as C++ functions, rather than C, to fix a compilation
bug with MSVC 2013, for Windows 8.x builds. */
extern void WINRT_InitGameBar(_THIS);
extern void WINRT_QuitGameBar(_THIS);
#endif
#endif /* SDL_winrtgamebar_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/winrt/SDL_winrtgamebar_cpp.h | C | apache-2.0 | 1,319 |
/*
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_WINRT
/* Windows-specific includes */
#include <Windows.h>
#include <agile.h>
/* SDL-specific includes */
#include "SDL.h"
#include "SDL_winrtevents_c.h"
extern "C" {
#include "../../events/scancodes_windows.h"
#include "../../events/SDL_keyboard_c.h"
}
static SDL_Scancode WinRT_Official_Keycodes[] = {
SDL_SCANCODE_UNKNOWN, /* VirtualKey.None -- 0 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.LeftButton -- 1 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.RightButton -- 2 */
SDL_SCANCODE_CANCEL, /* VirtualKey.Cancel -- 3 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.MiddleButton -- 4 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.XButton1 -- 5 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.XButton2 -- 6 */
SDL_SCANCODE_UNKNOWN, /* -- 7 */
SDL_SCANCODE_BACKSPACE, /* VirtualKey.Back -- 8 */
SDL_SCANCODE_TAB, /* VirtualKey.Tab -- 9 */
SDL_SCANCODE_UNKNOWN, /* -- 10 */
SDL_SCANCODE_UNKNOWN, /* -- 11 */
SDL_SCANCODE_CLEAR, /* VirtualKey.Clear -- 12 */
SDL_SCANCODE_RETURN, /* VirtualKey.Enter -- 13 */
SDL_SCANCODE_UNKNOWN, /* -- 14 */
SDL_SCANCODE_UNKNOWN, /* -- 15 */
SDL_SCANCODE_LSHIFT, /* VirtualKey.Shift -- 16 */
SDL_SCANCODE_LCTRL, /* VirtualKey.Control -- 17 */
SDL_SCANCODE_MENU, /* VirtualKey.Menu -- 18 */
SDL_SCANCODE_PAUSE, /* VirtualKey.Pause -- 19 */
SDL_SCANCODE_CAPSLOCK, /* VirtualKey.CapitalLock -- 20 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.Kana or VirtualKey.Hangul -- 21 */
SDL_SCANCODE_UNKNOWN, /* -- 22 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.Junja -- 23 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.Final -- 24 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.Hanja or VirtualKey.Kanji -- 25 */
SDL_SCANCODE_UNKNOWN, /* -- 26 */
SDL_SCANCODE_ESCAPE, /* VirtualKey.Escape -- 27 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.Convert -- 28 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.NonConvert -- 29 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.Accept -- 30 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.ModeChange -- 31 (maybe SDL_SCANCODE_MODE ?) */
SDL_SCANCODE_SPACE, /* VirtualKey.Space -- 32 */
SDL_SCANCODE_PAGEUP, /* VirtualKey.PageUp -- 33 */
SDL_SCANCODE_PAGEDOWN, /* VirtualKey.PageDown -- 34 */
SDL_SCANCODE_END, /* VirtualKey.End -- 35 */
SDL_SCANCODE_HOME, /* VirtualKey.Home -- 36 */
SDL_SCANCODE_LEFT, /* VirtualKey.Left -- 37 */
SDL_SCANCODE_UP, /* VirtualKey.Up -- 38 */
SDL_SCANCODE_RIGHT, /* VirtualKey.Right -- 39 */
SDL_SCANCODE_DOWN, /* VirtualKey.Down -- 40 */
SDL_SCANCODE_SELECT, /* VirtualKey.Select -- 41 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.Print -- 42 (maybe SDL_SCANCODE_PRINTSCREEN ?) */
SDL_SCANCODE_EXECUTE, /* VirtualKey.Execute -- 43 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.Snapshot -- 44 */
SDL_SCANCODE_INSERT, /* VirtualKey.Insert -- 45 */
SDL_SCANCODE_DELETE, /* VirtualKey.Delete -- 46 */
SDL_SCANCODE_HELP, /* VirtualKey.Help -- 47 */
SDL_SCANCODE_0, /* VirtualKey.Number0 -- 48 */
SDL_SCANCODE_1, /* VirtualKey.Number1 -- 49 */
SDL_SCANCODE_2, /* VirtualKey.Number2 -- 50 */
SDL_SCANCODE_3, /* VirtualKey.Number3 -- 51 */
SDL_SCANCODE_4, /* VirtualKey.Number4 -- 52 */
SDL_SCANCODE_5, /* VirtualKey.Number5 -- 53 */
SDL_SCANCODE_6, /* VirtualKey.Number6 -- 54 */
SDL_SCANCODE_7, /* VirtualKey.Number7 -- 55 */
SDL_SCANCODE_8, /* VirtualKey.Number8 -- 56 */
SDL_SCANCODE_9, /* VirtualKey.Number9 -- 57 */
SDL_SCANCODE_UNKNOWN, /* -- 58 */
SDL_SCANCODE_UNKNOWN, /* -- 59 */
SDL_SCANCODE_UNKNOWN, /* -- 60 */
SDL_SCANCODE_UNKNOWN, /* -- 61 */
SDL_SCANCODE_UNKNOWN, /* -- 62 */
SDL_SCANCODE_UNKNOWN, /* -- 63 */
SDL_SCANCODE_UNKNOWN, /* -- 64 */
SDL_SCANCODE_A, /* VirtualKey.A -- 65 */
SDL_SCANCODE_B, /* VirtualKey.B -- 66 */
SDL_SCANCODE_C, /* VirtualKey.C -- 67 */
SDL_SCANCODE_D, /* VirtualKey.D -- 68 */
SDL_SCANCODE_E, /* VirtualKey.E -- 69 */
SDL_SCANCODE_F, /* VirtualKey.F -- 70 */
SDL_SCANCODE_G, /* VirtualKey.G -- 71 */
SDL_SCANCODE_H, /* VirtualKey.H -- 72 */
SDL_SCANCODE_I, /* VirtualKey.I -- 73 */
SDL_SCANCODE_J, /* VirtualKey.J -- 74 */
SDL_SCANCODE_K, /* VirtualKey.K -- 75 */
SDL_SCANCODE_L, /* VirtualKey.L -- 76 */
SDL_SCANCODE_M, /* VirtualKey.M -- 77 */
SDL_SCANCODE_N, /* VirtualKey.N -- 78 */
SDL_SCANCODE_O, /* VirtualKey.O -- 79 */
SDL_SCANCODE_P, /* VirtualKey.P -- 80 */
SDL_SCANCODE_Q, /* VirtualKey.Q -- 81 */
SDL_SCANCODE_R, /* VirtualKey.R -- 82 */
SDL_SCANCODE_S, /* VirtualKey.S -- 83 */
SDL_SCANCODE_T, /* VirtualKey.T -- 84 */
SDL_SCANCODE_U, /* VirtualKey.U -- 85 */
SDL_SCANCODE_V, /* VirtualKey.V -- 86 */
SDL_SCANCODE_W, /* VirtualKey.W -- 87 */
SDL_SCANCODE_X, /* VirtualKey.X -- 88 */
SDL_SCANCODE_Y, /* VirtualKey.Y -- 89 */
SDL_SCANCODE_Z, /* VirtualKey.Z -- 90 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.LeftWindows -- 91 (maybe SDL_SCANCODE_APPLICATION or SDL_SCANCODE_LGUI ?) */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.RightWindows -- 92 (maybe SDL_SCANCODE_APPLICATION or SDL_SCANCODE_RGUI ?) */
SDL_SCANCODE_APPLICATION, /* VirtualKey.Application -- 93 */
SDL_SCANCODE_UNKNOWN, /* -- 94 */
SDL_SCANCODE_SLEEP, /* VirtualKey.Sleep -- 95 */
SDL_SCANCODE_KP_0, /* VirtualKey.NumberPad0 -- 96 */
SDL_SCANCODE_KP_1, /* VirtualKey.NumberPad1 -- 97 */
SDL_SCANCODE_KP_2, /* VirtualKey.NumberPad2 -- 98 */
SDL_SCANCODE_KP_3, /* VirtualKey.NumberPad3 -- 99 */
SDL_SCANCODE_KP_4, /* VirtualKey.NumberPad4 -- 100 */
SDL_SCANCODE_KP_5, /* VirtualKey.NumberPad5 -- 101 */
SDL_SCANCODE_KP_6, /* VirtualKey.NumberPad6 -- 102 */
SDL_SCANCODE_KP_7, /* VirtualKey.NumberPad7 -- 103 */
SDL_SCANCODE_KP_8, /* VirtualKey.NumberPad8 -- 104 */
SDL_SCANCODE_KP_9, /* VirtualKey.NumberPad9 -- 105 */
SDL_SCANCODE_KP_MULTIPLY, /* VirtualKey.Multiply -- 106 */
SDL_SCANCODE_KP_PLUS, /* VirtualKey.Add -- 107 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.Separator -- 108 */
SDL_SCANCODE_KP_MINUS, /* VirtualKey.Subtract -- 109 */
SDL_SCANCODE_UNKNOWN, /* VirtualKey.Decimal -- 110 (maybe SDL_SCANCODE_DECIMALSEPARATOR, SDL_SCANCODE_KP_DECIMAL, or SDL_SCANCODE_KP_PERIOD ?) */
SDL_SCANCODE_KP_DIVIDE, /* VirtualKey.Divide -- 111 */
SDL_SCANCODE_F1, /* VirtualKey.F1 -- 112 */
SDL_SCANCODE_F2, /* VirtualKey.F2 -- 113 */
SDL_SCANCODE_F3, /* VirtualKey.F3 -- 114 */
SDL_SCANCODE_F4, /* VirtualKey.F4 -- 115 */
SDL_SCANCODE_F5, /* VirtualKey.F5 -- 116 */
SDL_SCANCODE_F6, /* VirtualKey.F6 -- 117 */
SDL_SCANCODE_F7, /* VirtualKey.F7 -- 118 */
SDL_SCANCODE_F8, /* VirtualKey.F8 -- 119 */
SDL_SCANCODE_F9, /* VirtualKey.F9 -- 120 */
SDL_SCANCODE_F10, /* VirtualKey.F10 -- 121 */
SDL_SCANCODE_F11, /* VirtualKey.F11 -- 122 */
SDL_SCANCODE_F12, /* VirtualKey.F12 -- 123 */
SDL_SCANCODE_F13, /* VirtualKey.F13 -- 124 */
SDL_SCANCODE_F14, /* VirtualKey.F14 -- 125 */
SDL_SCANCODE_F15, /* VirtualKey.F15 -- 126 */
SDL_SCANCODE_F16, /* VirtualKey.F16 -- 127 */
SDL_SCANCODE_F17, /* VirtualKey.F17 -- 128 */
SDL_SCANCODE_F18, /* VirtualKey.F18 -- 129 */
SDL_SCANCODE_F19, /* VirtualKey.F19 -- 130 */
SDL_SCANCODE_F20, /* VirtualKey.F20 -- 131 */
SDL_SCANCODE_F21, /* VirtualKey.F21 -- 132 */
SDL_SCANCODE_F22, /* VirtualKey.F22 -- 133 */
SDL_SCANCODE_F23, /* VirtualKey.F23 -- 134 */
SDL_SCANCODE_F24, /* VirtualKey.F24 -- 135 */
SDL_SCANCODE_UNKNOWN, /* -- 136 */
SDL_SCANCODE_UNKNOWN, /* -- 137 */
SDL_SCANCODE_UNKNOWN, /* -- 138 */
SDL_SCANCODE_UNKNOWN, /* -- 139 */
SDL_SCANCODE_UNKNOWN, /* -- 140 */
SDL_SCANCODE_UNKNOWN, /* -- 141 */
SDL_SCANCODE_UNKNOWN, /* -- 142 */
SDL_SCANCODE_UNKNOWN, /* -- 143 */
SDL_SCANCODE_NUMLOCKCLEAR, /* VirtualKey.NumberKeyLock -- 144 */
SDL_SCANCODE_SCROLLLOCK, /* VirtualKey.Scroll -- 145 */
SDL_SCANCODE_UNKNOWN, /* -- 146 */
SDL_SCANCODE_UNKNOWN, /* -- 147 */
SDL_SCANCODE_UNKNOWN, /* -- 148 */
SDL_SCANCODE_UNKNOWN, /* -- 149 */
SDL_SCANCODE_UNKNOWN, /* -- 150 */
SDL_SCANCODE_UNKNOWN, /* -- 151 */
SDL_SCANCODE_UNKNOWN, /* -- 152 */
SDL_SCANCODE_UNKNOWN, /* -- 153 */
SDL_SCANCODE_UNKNOWN, /* -- 154 */
SDL_SCANCODE_UNKNOWN, /* -- 155 */
SDL_SCANCODE_UNKNOWN, /* -- 156 */
SDL_SCANCODE_UNKNOWN, /* -- 157 */
SDL_SCANCODE_UNKNOWN, /* -- 158 */
SDL_SCANCODE_UNKNOWN, /* -- 159 */
SDL_SCANCODE_LSHIFT, /* VirtualKey.LeftShift -- 160 */
SDL_SCANCODE_RSHIFT, /* VirtualKey.RightShift -- 161 */
SDL_SCANCODE_LCTRL, /* VirtualKey.LeftControl -- 162 */
SDL_SCANCODE_RCTRL, /* VirtualKey.RightControl -- 163 */
SDL_SCANCODE_MENU, /* VirtualKey.LeftMenu -- 164 */
SDL_SCANCODE_MENU, /* VirtualKey.RightMenu -- 165 */
SDL_SCANCODE_AC_BACK, /* VirtualKey.GoBack -- 166 : The go back key. */
SDL_SCANCODE_AC_FORWARD, /* VirtualKey.GoForward -- 167 : The go forward key. */
SDL_SCANCODE_AC_REFRESH, /* VirtualKey.Refresh -- 168 : The refresh key. */
SDL_SCANCODE_AC_STOP, /* VirtualKey.Stop -- 169 : The stop key. */
SDL_SCANCODE_AC_SEARCH, /* VirtualKey.Search -- 170 : The search key. */
SDL_SCANCODE_AC_BOOKMARKS, /* VirtualKey.Favorites -- 171 : The favorites key. */
SDL_SCANCODE_AC_HOME /* VirtualKey.GoHome -- 172 : The go home key. */
};
/* Attempt to translate a keycode that isn't listed in WinRT's VirtualKey enum.
*/
static SDL_Scancode
WINRT_TranslateUnofficialKeycode(int keycode)
{
switch (keycode) {
case 173: return SDL_SCANCODE_MUTE; /* VK_VOLUME_MUTE */
case 174: return SDL_SCANCODE_VOLUMEDOWN; /* VK_VOLUME_DOWN */
case 175: return SDL_SCANCODE_VOLUMEUP; /* VK_VOLUME_UP */
case 176: return SDL_SCANCODE_AUDIONEXT; /* VK_MEDIA_NEXT_TRACK */
case 177: return SDL_SCANCODE_AUDIOPREV; /* VK_MEDIA_PREV_TRACK */
// case 178: return ; /* VK_MEDIA_STOP */
case 179: return SDL_SCANCODE_AUDIOPLAY; /* VK_MEDIA_PLAY_PAUSE */
case 180: return SDL_SCANCODE_MAIL; /* VK_LAUNCH_MAIL */
case 181: return SDL_SCANCODE_MEDIASELECT; /* VK_LAUNCH_MEDIA_SELECT */
// case 182: return ; /* VK_LAUNCH_APP1 */
case 183: return SDL_SCANCODE_CALCULATOR; /* VK_LAUNCH_APP2 */
// case 184: return ; /* ... reserved ... */
// case 185: return ; /* ... reserved ... */
case 186: return SDL_SCANCODE_SEMICOLON; /* VK_OEM_1, ';:' key on US standard keyboards */
case 187: return SDL_SCANCODE_EQUALS; /* VK_OEM_PLUS */
case 188: return SDL_SCANCODE_COMMA; /* VK_OEM_COMMA */
case 189: return SDL_SCANCODE_MINUS; /* VK_OEM_MINUS */
case 190: return SDL_SCANCODE_PERIOD; /* VK_OEM_PERIOD */
case 191: return SDL_SCANCODE_SLASH; /* VK_OEM_2, '/?' key on US standard keyboards */
case 192: return SDL_SCANCODE_GRAVE; /* VK_OEM_3, '`~' key on US standard keyboards */
// ?
// ... reserved or unassigned ...
// ?
case 219: return SDL_SCANCODE_LEFTBRACKET; /* VK_OEM_4, '[{' key on US standard keyboards */
case 220: return SDL_SCANCODE_BACKSLASH; /* VK_OEM_5, '\|' key on US standard keyboards */
case 221: return SDL_SCANCODE_RIGHTBRACKET; /* VK_OEM_6, ']}' key on US standard keyboards */
case 222: return SDL_SCANCODE_APOSTROPHE; /* VK_OEM_7, 'single/double quote' on US standard keyboards */
default: break;
}
return SDL_SCANCODE_UNKNOWN;
}
static SDL_Scancode
WINRT_TranslateKeycode(int keycode, unsigned int nativeScancode)
{
// TODO, WinRT: try filling out the WinRT keycode table as much as possible, using the Win32 table for interpretation hints
SDL_Scancode scancode = SDL_SCANCODE_UNKNOWN;
/* HACK ALERT: At least one VirtualKey constant (Shift) with a left/right
* designation might not get reported with its correct handedness, however
* its hardware scan code can fill in the gaps. If this is detected,
* use the hardware scan code to try telling if the left, or the right
* side's key was used.
*
* If Microsoft ever allows MapVirtualKey or MapVirtualKeyEx to be used
* in WinRT apps, or something similar to these (it doesn't appear to be,
* at least not for Windows [Phone] 8/8.1, as of Oct 24, 2014), then this
* hack might become deprecated, or obsolete.
*/
if (nativeScancode < SDL_arraysize(windows_scancode_table)) {
switch (keycode) {
case 16: // VirtualKey.Shift
switch (windows_scancode_table[nativeScancode]) {
case SDL_SCANCODE_LSHIFT:
case SDL_SCANCODE_RSHIFT:
return windows_scancode_table[nativeScancode];
}
break;
// Add others, as necessary.
//
// Unfortunately, this hack doesn't seem to work in determining
// handedness with Control keys.
default:
break;
}
}
/* Try to get a documented, WinRT, 'VirtualKey' next (as documented at
http://msdn.microsoft.com/en-us/library/windows/apps/windows.system.virtualkey.aspx ).
If that fails, fall back to a Win32 virtual key.
If that fails, attempt to fall back to a scancode-derived key.
*/
if (keycode < SDL_arraysize(WinRT_Official_Keycodes)) {
scancode = WinRT_Official_Keycodes[keycode];
}
if (scancode == SDL_SCANCODE_UNKNOWN) {
scancode = WINRT_TranslateUnofficialKeycode(keycode);
}
if (scancode == SDL_SCANCODE_UNKNOWN) {
if (nativeScancode < SDL_arraysize(windows_scancode_table)) {
scancode = windows_scancode_table[nativeScancode];
}
}
/*
if (scancode == SDL_SCANCODE_UNKNOWN) {
SDL_Log("WinRT TranslateKeycode, unknown keycode=%d\n", (int)keycode);
}
*/
return scancode;
}
void
WINRT_ProcessKeyDownEvent(Windows::UI::Core::KeyEventArgs ^args)
{
SDL_Scancode sdlScancode = WINRT_TranslateKeycode((int)args->VirtualKey, args->KeyStatus.ScanCode);
#if 0
SDL_Keycode keycode = SDL_GetKeyFromScancode(sdlScancode);
SDL_Log("key down, handled=%s, ext?=%s, released?=%s, menu key down?=%s, "
"repeat count=%d, native scan code=0x%x, was down?=%s, vkey=%d, "
"sdl scan code=%d (%s), sdl key code=%d (%s)\n",
(args->Handled ? "1" : "0"),
(args->KeyStatus.IsExtendedKey ? "1" : "0"),
(args->KeyStatus.IsKeyReleased ? "1" : "0"),
(args->KeyStatus.IsMenuKeyDown ? "1" : "0"),
args->KeyStatus.RepeatCount,
args->KeyStatus.ScanCode,
(args->KeyStatus.WasKeyDown ? "1" : "0"),
args->VirtualKey,
sdlScancode,
SDL_GetScancodeName(sdlScancode),
keycode,
SDL_GetKeyName(keycode));
//args->Handled = true;
#endif
SDL_SendKeyboardKey(SDL_PRESSED, sdlScancode);
}
void
WINRT_ProcessKeyUpEvent(Windows::UI::Core::KeyEventArgs ^args)
{
SDL_Scancode sdlScancode = WINRT_TranslateKeycode((int)args->VirtualKey, args->KeyStatus.ScanCode);
#if 0
SDL_Keycode keycode = SDL_GetKeyFromScancode(sdlScancode);
SDL_Log("key up, handled=%s, ext?=%s, released?=%s, menu key down?=%s, "
"repeat count=%d, native scan code=0x%x, was down?=%s, vkey=%d, "
"sdl scan code=%d (%s), sdl key code=%d (%s)\n",
(args->Handled ? "1" : "0"),
(args->KeyStatus.IsExtendedKey ? "1" : "0"),
(args->KeyStatus.IsKeyReleased ? "1" : "0"),
(args->KeyStatus.IsMenuKeyDown ? "1" : "0"),
args->KeyStatus.RepeatCount,
args->KeyStatus.ScanCode,
(args->KeyStatus.WasKeyDown ? "1" : "0"),
args->VirtualKey,
sdlScancode,
SDL_GetScancodeName(sdlScancode),
keycode,
SDL_GetKeyName(keycode));
//args->Handled = true;
#endif
SDL_SendKeyboardKey(SDL_RELEASED, sdlScancode);
}
void
WINRT_ProcessCharacterReceivedEvent(Windows::UI::Core::CharacterReceivedEventArgs ^args)
{
wchar_t src_ucs2[2];
char dest_utf8[16];
int result;
/* Setup src */
src_ucs2[0] = args->KeyCode;
src_ucs2[1] = L'\0';
/* Convert the text, then send an SDL_TEXTINPUT event. */
result = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)&src_ucs2, -1, (LPSTR)dest_utf8, sizeof(dest_utf8), NULL, NULL);
if (result > 0) {
SDL_SendKeyboardText(dest_utf8);
}
}
#if NTDDI_VERSION >= NTDDI_WIN10
SDL_bool WINRT_HasScreenKeyboardSupport(_THIS)
{
return SDL_TRUE;
}
void WINRT_ShowScreenKeyboard(_THIS, SDL_Window *window)
{
using namespace Windows::UI::ViewManagement;
InputPane ^ inputPane = InputPane::GetForCurrentView();
if (inputPane) {
inputPane->TryShow();
}
}
void WINRT_HideScreenKeyboard(_THIS, SDL_Window *window)
{
using namespace Windows::UI::ViewManagement;
InputPane ^ inputPane = InputPane::GetForCurrentView();
if (inputPane) {
inputPane->TryHide();
}
}
SDL_bool WINRT_IsScreenKeyboardShown(_THIS, SDL_Window *window)
{
using namespace Windows::UI::ViewManagement;
InputPane ^ inputPane = InputPane::GetForCurrentView();
if (inputPane) {
// dludwig@pobox.com: checking inputPane->Visible doesn't seem to detect visibility,
// at least not on the Windows Phone 10.0.10240.0 emulator. Checking
// the size of inputPane->OccludedRect, however, does seem to work.
Windows::Foundation::Rect rect = inputPane->OccludedRect;
if (rect.Width > 0 && rect.Height > 0) {
return SDL_TRUE;
}
}
return SDL_FALSE;
}
#endif // NTDDI_VERSION >= ...
#endif // SDL_VIDEO_DRIVER_WINRT
| YifuLiu/AliOS-Things | components/SDL2/src/video/winrt/SDL_winrtkeyboard.cpp | C++ | apache-2.0 | 20,288 |
/*
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_WINRT
extern "C" {
#include "SDL_messagebox.h"
#include "../../core/windows/SDL_windows.h"
}
#include "SDL_winrtevents_c.h"
#include <windows.ui.popups.h>
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::UI::Popups;
static String ^
WINRT_UTF8ToPlatformString(const char * str)
{
wchar_t * wstr = WIN_UTF8ToString(str);
String ^ rtstr = ref new String(wstr);
SDL_free(wstr);
return rtstr;
}
extern "C" int
WINRT_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
{
#if (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) && (NTDDI_VERSION == NTDDI_WIN8)
/* Sadly, Windows Phone 8 doesn't include the MessageDialog class that
* Windows 8.x/RT does, even though MSDN's reference documentation for
* Windows Phone 8 mentions it.
*
* The .NET runtime on Windows Phone 8 does, however, include a
* MessageBox class. Perhaps this could be called, somehow?
*/
return SDL_SetError("SDL_messagebox support is not available for Windows Phone 8.0");
#else
SDL_VideoDevice *_this = SDL_GetVideoDevice();
#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
const int maxbuttons = 2;
const char * platform = "Windows Phone 8.1+";
#else
const int maxbuttons = 3;
const char * platform = "Windows 8.x";
#endif
if (messageboxdata->numbuttons > maxbuttons) {
return SDL_SetError("WinRT's MessageDialog only supports %d buttons, at most, on %s. %d were requested.",
maxbuttons, platform, messageboxdata->numbuttons);
}
/* Build a MessageDialog object and its buttons */
MessageDialog ^ dialog = ref new MessageDialog(WINRT_UTF8ToPlatformString(messageboxdata->message));
dialog->Title = WINRT_UTF8ToPlatformString(messageboxdata->title);
for (int 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];
}
UICommand ^ button = ref new UICommand(WINRT_UTF8ToPlatformString(sdlButton->text));
button->Id = safe_cast<IntPtr>((int)(sdlButton - messageboxdata->buttons));
dialog->Commands->Append(button);
if (sdlButton->flags & SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT) {
dialog->CancelCommandIndex = i;
}
if (sdlButton->flags & SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT) {
dialog->DefaultCommandIndex = i;
}
}
/* Display the MessageDialog, then wait for it to be closed */
/* TODO, WinRT: Find a way to redraw MessageDialog instances if a GPU device-reset occurs during the following event-loop */
auto operation = dialog->ShowAsync();
while (operation->Status == Windows::Foundation::AsyncStatus::Started) {
WINRT_PumpEvents(_this);
}
/* Retrieve results from the MessageDialog and process them accordingly */
if (operation->Status != Windows::Foundation::AsyncStatus::Completed) {
return SDL_SetError("An unknown error occurred in displaying the WinRT MessageDialog");
}
if (buttonid) {
IntPtr results = safe_cast<IntPtr>((int)(operation->GetResults()->Id));
int clicked_index = results.ToInt32();
*buttonid = messageboxdata->buttons[clicked_index].buttonid;
}
return 0;
#endif /* if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP / else */
}
#endif /* SDL_VIDEO_DRIVER_WINRT */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/winrt/SDL_winrtmessagebox.cpp | C++ | apache-2.0 | 4,602 |
/*
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_WINRT
extern int WINRT_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid);
#endif /* SDL_VIDEO_DRIVER_WINRT */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/winrt/SDL_winrtmessagebox.h | C | apache-2.0 | 1,163 |
/*
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_WINRT
/*
* Windows includes:
*/
#include <Windows.h>
#include <windows.ui.core.h>
using namespace Windows::UI::Core;
using Windows::UI::Core::CoreCursor;
/*
* SDL includes:
*/
extern "C" {
#include "SDL_assert.h"
#include "../../events/SDL_mouse_c.h"
#include "../../events/SDL_touch_c.h"
#include "../SDL_sysvideo.h"
#include "SDL_events.h"
}
#include "../../core/winrt/SDL_winrtapp_direct3d.h"
#include "SDL_winrtvideo_cpp.h"
#include "SDL_winrtmouse_c.h"
extern "C" SDL_bool WINRT_UsingRelativeMouseMode = SDL_FALSE;
static SDL_Cursor *
WINRT_CreateSystemCursor(SDL_SystemCursor id)
{
SDL_Cursor *cursor;
CoreCursorType cursorType = CoreCursorType::Arrow;
switch(id)
{
default:
SDL_assert(0);
return NULL;
case SDL_SYSTEM_CURSOR_ARROW: cursorType = CoreCursorType::Arrow; break;
case SDL_SYSTEM_CURSOR_IBEAM: cursorType = CoreCursorType::IBeam; break;
case SDL_SYSTEM_CURSOR_WAIT: cursorType = CoreCursorType::Wait; break;
case SDL_SYSTEM_CURSOR_CROSSHAIR: cursorType = CoreCursorType::Cross; break;
case SDL_SYSTEM_CURSOR_WAITARROW: cursorType = CoreCursorType::Wait; break;
case SDL_SYSTEM_CURSOR_SIZENWSE: cursorType = CoreCursorType::SizeNorthwestSoutheast; break;
case SDL_SYSTEM_CURSOR_SIZENESW: cursorType = CoreCursorType::SizeNortheastSouthwest; break;
case SDL_SYSTEM_CURSOR_SIZEWE: cursorType = CoreCursorType::SizeWestEast; break;
case SDL_SYSTEM_CURSOR_SIZENS: cursorType = CoreCursorType::SizeNorthSouth; break;
case SDL_SYSTEM_CURSOR_SIZEALL: cursorType = CoreCursorType::SizeAll; break;
case SDL_SYSTEM_CURSOR_NO: cursorType = CoreCursorType::UniversalNo; break;
case SDL_SYSTEM_CURSOR_HAND: cursorType = CoreCursorType::Hand; break;
}
cursor = (SDL_Cursor *) SDL_calloc(1, sizeof(*cursor));
if (cursor) {
/* Create a pointer to a COM reference to a cursor. The extra
pointer is used (on top of the COM reference) to allow the cursor
to be referenced by the SDL_cursor's driverdata field, which is
a void pointer.
*/
CoreCursor ^* theCursor = new CoreCursor^(nullptr);
*theCursor = ref new CoreCursor(cursorType, 0);
cursor->driverdata = (void *) theCursor;
} else {
SDL_OutOfMemory();
}
return cursor;
}
static SDL_Cursor *
WINRT_CreateDefaultCursor()
{
return WINRT_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
}
static void
WINRT_FreeCursor(SDL_Cursor * cursor)
{
if (cursor->driverdata) {
CoreCursor ^* theCursor = (CoreCursor ^*) cursor->driverdata;
*theCursor = nullptr; // Release the COM reference to the CoreCursor
delete theCursor; // Delete the pointer to the COM reference
}
SDL_free(cursor);
}
static int
WINRT_ShowCursor(SDL_Cursor * cursor)
{
// TODO, WinRT, XAML: make WINRT_ShowCursor work when XAML support is enabled.
if ( ! CoreWindow::GetForCurrentThread()) {
return 0;
}
CoreWindow ^ coreWindow = CoreWindow::GetForCurrentThread();
if (cursor) {
CoreCursor ^* theCursor = (CoreCursor ^*) cursor->driverdata;
coreWindow->PointerCursor = *theCursor;
} else {
// HACK ALERT: TL;DR - Hiding the cursor in WinRT/UWP apps is weird, and
// a Win32-style cursor resource file must be directly included in apps,
// otherwise hiding the cursor will cause mouse-motion data to never be
// received.
//
// Here's the lengthy explanation:
//
// There are two ways to hide a cursor in WinRT/UWP apps.
// Both involve setting the WinRT CoreWindow's (which is somewhat analogous
// to a Win32 HWND) 'PointerCursor' property.
//
// The first way to hide a cursor sets PointerCursor to nullptr. This
// is, arguably, the easiest to implement for an app. It does have an
// unfortunate side-effect: it'll prevent mouse-motion events from being
// sent to the app (via CoreWindow).
//
// The second way to hide a cursor sets PointerCursor to a transparent
// cursor. This allows mouse-motion events to be sent to the app, but is
// more difficult to set up, as:
// 1. WinRT/UWP, while providing a few stock cursors, does not provide
// a completely transparent cursor.
// 2. WinRT/UWP allows apps to provide custom-built cursors, but *ONLY*
// if they are linked directly inside the app, via Win32-style
// cursor resource files. APIs to create cursors at runtime are
// not provided to apps, and attempting to link-to or use Win32
// cursor-creation APIs could cause an app to fail Windows Store
// certification.
//
// SDL can use either means of hiding the cursor. It provides a Win32-style
// set of cursor resource files in its source distribution, inside
// src/main/winrt/. If those files are linked to an SDL-for-WinRT/UWP app
// (by including them in a MSVC project, for example), SDL will attempt to
// use those, if and when the cursor is hidden via SDL APIs. If those
// files are not linked in, SDL will attempt to hide the cursor via the
// 'set PointerCursor to nullptr' means (which, if you recall, causes
// mouse-motion data to NOT be sent to the app!).
//
// Tech notes:
// - SDL's blank cursor resource uses a resource ID of 5000.
// - SDL's cursor resources consist of the following two files:
// - src/main/winrt/SDL2-WinRTResource_BlankCursor.cur -- cursor pixel data
// - src/main/winrt/SDL2-WinRTResources.rc -- declares the cursor resource, and its ID (of 5000)
//
const unsigned int win32CursorResourceID = 5000;
CoreCursor ^ blankCursor = ref new CoreCursor(CoreCursorType::Custom, win32CursorResourceID);
// Set 'PointerCursor' to 'blankCursor' in a way that shouldn't throw
// an exception if the app hasn't loaded that resource.
ABI::Windows::UI::Core::ICoreCursor * iblankCursor = reinterpret_cast<ABI::Windows::UI::Core::ICoreCursor *>(blankCursor);
ABI::Windows::UI::Core::ICoreWindow * icoreWindow = reinterpret_cast<ABI::Windows::UI::Core::ICoreWindow *>(coreWindow);
HRESULT hr = icoreWindow->put_PointerCursor(iblankCursor);
if (FAILED(hr)) {
// The app doesn't contain the cursor resource, or some other error
// occurred. Just use the other, but mouse-motion-preventing, means of
// hiding the cursor.
coreWindow->PointerCursor = nullptr;
}
}
return 0;
}
static int
WINRT_SetRelativeMouseMode(SDL_bool enabled)
{
WINRT_UsingRelativeMouseMode = enabled;
return 0;
}
void
WINRT_InitMouse(_THIS)
{
SDL_Mouse *mouse = SDL_GetMouse();
/* DLudwig, Dec 3, 2012: WinRT does not currently provide APIs for
the following features, AFAIK:
- custom cursors (multiple system cursors are, however, available)
- programmatically moveable cursors
*/
#if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
//mouse->CreateCursor = WINRT_CreateCursor;
mouse->CreateSystemCursor = WINRT_CreateSystemCursor;
mouse->ShowCursor = WINRT_ShowCursor;
mouse->FreeCursor = WINRT_FreeCursor;
//mouse->WarpMouse = WINRT_WarpMouse;
mouse->SetRelativeMouseMode = WINRT_SetRelativeMouseMode;
SDL_SetDefaultCursor(WINRT_CreateDefaultCursor());
#endif
}
void
WINRT_QuitMouse(_THIS)
{
}
#endif /* SDL_VIDEO_DRIVER_WINRT */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/winrt/SDL_winrtmouse.cpp | C++ | apache-2.0 | 8,739 |
/*
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_config.h"
#ifndef SDL_winrtmouse_h_
#define SDL_winrtmouse_h_
#ifdef __cplusplus
extern "C" {
#endif
extern void WINRT_InitMouse(_THIS);
extern void WINRT_QuitMouse(_THIS);
extern SDL_bool WINRT_UsingRelativeMouseMode;
#ifdef __cplusplus
}
#endif
#endif /* SDL_winrtmouse_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/winrt/SDL_winrtmouse_c.h | C | apache-2.0 | 1,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_WINRT && SDL_VIDEO_OPENGL_EGL
/* EGL implementation of SDL OpenGL support */
#include "SDL_winrtvideo_cpp.h"
extern "C" {
#include "SDL_winrtopengles.h"
#include "SDL_loadso.h"
#include "../SDL_egl_c.h"
}
/* Windows includes */
#include <wrl/client.h>
using namespace Windows::UI::Core;
/* ANGLE/WinRT constants */
static const int ANGLE_D3D_FEATURE_LEVEL_ANY = 0;
#define EGL_PLATFORM_ANGLE_ANGLE 0x3202
#define EGL_PLATFORM_ANGLE_TYPE_ANGLE 0x3203
#define EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE 0x3204
#define EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE 0x3205
#define EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE 0x3208
#define EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE 0x3209
#define EGL_PLATFORM_ANGLE_DEVICE_TYPE_WARP_ANGLE 0x320B
#define EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE 0x320F
#define EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER 0x320B
/*
* SDL/EGL top-level implementation
*/
extern "C" int
WINRT_GLES_LoadLibrary(_THIS, const char *path)
{
SDL_VideoData *video_data = (SDL_VideoData *)_this->driverdata;
if (SDL_EGL_LoadLibrary(_this, path, EGL_DEFAULT_DISPLAY, 0) != 0) {
return -1;
}
/* Load ANGLE/WinRT-specific functions */
CreateWinrtEglWindow_Old_Function CreateWinrtEglWindow = (CreateWinrtEglWindow_Old_Function) SDL_LoadFunction(_this->egl_data->egl_dll_handle, "CreateWinrtEglWindow");
if (CreateWinrtEglWindow) {
/* 'CreateWinrtEglWindow' was found, which means that an an older
* version of ANGLE/WinRT is being used. Continue setting up EGL,
* as appropriate to this version of ANGLE.
*/
/* Create an ANGLE/WinRT EGL-window */
/* TODO, WinRT: check for XAML usage before accessing the CoreWindow, as not doing so could lead to a crash */
CoreWindow ^ native_win = CoreWindow::GetForCurrentThread();
Microsoft::WRL::ComPtr<IUnknown> cpp_win = reinterpret_cast<IUnknown *>(native_win);
HRESULT result = CreateWinrtEglWindow(cpp_win, ANGLE_D3D_FEATURE_LEVEL_ANY, &(video_data->winrtEglWindow));
if (FAILED(result)) {
return -1;
}
/* Call eglGetDisplay and eglInitialize as appropriate. On other
* platforms, this would probably get done by SDL_EGL_LoadLibrary,
* however ANGLE/WinRT's current implementation (as of Mar 22, 2014) of
* eglGetDisplay requires that a C++ object be passed into it, so the
* call will be made in this file, a C++ file, instead.
*/
Microsoft::WRL::ComPtr<IUnknown> cpp_display = video_data->winrtEglWindow;
_this->egl_data->egl_display = ((eglGetDisplay_Old_Function)_this->egl_data->eglGetDisplay)(cpp_display);
if (!_this->egl_data->egl_display) {
return SDL_EGL_SetError("Could not get Windows 8.0 EGL display", "eglGetDisplay");
}
if (_this->egl_data->eglInitialize(_this->egl_data->egl_display, NULL, NULL) != EGL_TRUE) {
return SDL_EGL_SetError("Could not initialize Windows 8.0 EGL", "eglInitialize");
}
} else {
/* Declare some ANGLE/EGL initialization property-sets, as suggested by
* MSOpenTech's ANGLE-for-WinRT template apps:
*/
const EGLint defaultDisplayAttributes[] =
{
EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE,
EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, EGL_TRUE,
EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_TRUE,
EGL_NONE,
};
const EGLint fl9_3DisplayAttributes[] =
{
EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE,
EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, 9,
EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, 3,
EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, EGL_TRUE,
EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_TRUE,
EGL_NONE,
};
const EGLint warpDisplayAttributes[] =
{
EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE,
EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_DEVICE_TYPE_WARP_ANGLE,
EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, EGL_TRUE,
EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_TRUE,
EGL_NONE,
};
/* 'CreateWinrtEglWindow' was NOT found, which either means that a
* newer version of ANGLE/WinRT is being used, or that we don't have
* a valid copy of ANGLE.
*
* Try loading ANGLE as if it were the newer version.
*/
eglGetPlatformDisplayEXT_Function eglGetPlatformDisplayEXT = (eglGetPlatformDisplayEXT_Function)_this->egl_data->eglGetProcAddress("eglGetPlatformDisplayEXT");
if (!eglGetPlatformDisplayEXT) {
return SDL_EGL_SetError("Could not retrieve ANGLE/WinRT display function(s)", "eglGetProcAddress");
}
#if (WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP)
/* Try initializing EGL at D3D11 Feature Level 10_0+ (which is not
* supported on WinPhone 8.x.
*/
_this->egl_data->egl_display = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, defaultDisplayAttributes);
if (!_this->egl_data->egl_display) {
return SDL_EGL_SetError("Could not get EGL display for Direct3D 10_0+", "eglGetPlatformDisplayEXT");
}
if (_this->egl_data->eglInitialize(_this->egl_data->egl_display, NULL, NULL) != EGL_TRUE)
#endif
{
/* Try initializing EGL at D3D11 Feature Level 9_3, in case the
* 10_0 init fails, or we're on Windows Phone (which only supports
* 9_3).
*/
_this->egl_data->egl_display = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, fl9_3DisplayAttributes);
if (!_this->egl_data->egl_display) {
return SDL_EGL_SetError("Could not get EGL display for Direct3D 9_3", "eglGetPlatformDisplayEXT");
}
if (_this->egl_data->eglInitialize(_this->egl_data->egl_display, NULL, NULL) != EGL_TRUE) {
/* Try initializing EGL at D3D11 Feature Level 11_0 on WARP
* (a Windows-provided, software rasterizer) if all else fails.
*/
_this->egl_data->egl_display = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, warpDisplayAttributes);
if (!_this->egl_data->egl_display) {
return SDL_EGL_SetError("Could not get EGL display for Direct3D WARP", "eglGetPlatformDisplayEXT");
}
if (_this->egl_data->eglInitialize(_this->egl_data->egl_display, NULL, NULL) != EGL_TRUE) {
return SDL_EGL_SetError("Could not initialize WinRT 8.x+ EGL", "eglInitialize");
}
}
}
}
return 0;
}
extern "C" void
WINRT_GLES_UnloadLibrary(_THIS)
{
SDL_VideoData *video_data = (SDL_VideoData *)_this->driverdata;
/* Release SDL's own COM reference to the ANGLE/WinRT IWinrtEglWindow */
if (video_data->winrtEglWindow) {
video_data->winrtEglWindow->Release();
video_data->winrtEglWindow = nullptr;
}
/* Perform the bulk of the unloading */
SDL_EGL_UnloadLibrary(_this);
}
extern "C" {
SDL_EGL_CreateContext_impl(WINRT)
SDL_EGL_SwapWindow_impl(WINRT)
SDL_EGL_MakeCurrent_impl(WINRT)
}
#endif /* SDL_VIDEO_DRIVER_WINRT && SDL_VIDEO_OPENGL_EGL */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/winrt/SDL_winrtopengles.cpp | C++ | apache-2.0 | 8,644 |
/*
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_config.h"
#ifndef SDL_winrtopengles_h_
#define SDL_winrtopengles_h_
#if SDL_VIDEO_DRIVER_WINRT && SDL_VIDEO_OPENGL_EGL
#include "../SDL_sysvideo.h"
#include "../SDL_egl_c.h"
/* OpenGLES functions */
#define WINRT_GLES_GetAttribute SDL_EGL_GetAttribute
#define WINRT_GLES_GetProcAddress SDL_EGL_GetProcAddress
#define WINRT_GLES_SetSwapInterval SDL_EGL_SetSwapInterval
#define WINRT_GLES_GetSwapInterval SDL_EGL_GetSwapInterval
#define WINRT_GLES_DeleteContext SDL_EGL_DeleteContext
extern int WINRT_GLES_LoadLibrary(_THIS, const char *path);
extern void WINRT_GLES_UnloadLibrary(_THIS);
extern SDL_GLContext WINRT_GLES_CreateContext(_THIS, SDL_Window * window);
extern int WINRT_GLES_SwapWindow(_THIS, SDL_Window * window);
extern int WINRT_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
#ifdef __cplusplus
/* Typedefs for ANGLE/WinRT's C++-based native-display and native-window types,
* which are used when calling eglGetDisplay and eglCreateWindowSurface.
*/
typedef Microsoft::WRL::ComPtr<IUnknown> WINRT_EGLNativeWindowType_Old;
/* Function pointer typedefs for 'old' ANGLE/WinRT's functions, which may
* require that C++ objects be passed in:
*/
typedef EGLDisplay (EGLAPIENTRY *eglGetDisplay_Old_Function)(WINRT_EGLNativeWindowType_Old);
typedef EGLSurface (EGLAPIENTRY *eglCreateWindowSurface_Old_Function)(EGLDisplay, EGLConfig, WINRT_EGLNativeWindowType_Old, const EGLint *);
typedef HRESULT (EGLAPIENTRY *CreateWinrtEglWindow_Old_Function)(Microsoft::WRL::ComPtr<IUnknown>, int, IUnknown ** result);
#endif /* __cplusplus */
/* Function pointer typedefs for 'new' ANGLE/WinRT functions, which, unlike
* the old functions, do not require C++ support and work with plain C.
*/
typedef EGLDisplay (EGLAPIENTRY *eglGetPlatformDisplayEXT_Function)(EGLenum, void *, const EGLint *);
#endif /* SDL_VIDEO_DRIVER_WINRT && SDL_VIDEO_OPENGL_EGL */
#endif /* SDL_winrtopengles_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/winrt/SDL_winrtopengles.h | C | apache-2.0 | 2,912 |
/*
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_WINRT
/* SDL includes */
#include "SDL_winrtevents_c.h"
#include "SDL_winrtmouse_c.h"
#include "SDL_winrtvideo_cpp.h"
#include "SDL_assert.h"
#include "SDL_system.h"
extern "C" {
#include "../SDL_sysvideo.h"
#include "../../events/SDL_events_c.h"
#include "../../events/SDL_mouse_c.h"
#include "../../events/SDL_touch_c.h"
}
/* File-specific globals: */
static SDL_TouchID WINRT_TouchID = 1;
void
WINRT_InitTouch(_THIS)
{
SDL_AddTouch(WINRT_TouchID, SDL_TOUCH_DEVICE_DIRECT, "");
}
//
// Applies necessary geometric transformations to raw cursor positions:
//
Windows::Foundation::Point
WINRT_TransformCursorPosition(SDL_Window * window,
Windows::Foundation::Point rawPosition,
WINRT_CursorNormalizationType normalization)
{
using namespace Windows::UI::Core;
using namespace Windows::Graphics::Display;
if (!window) {
return rawPosition;
}
SDL_WindowData * windowData = (SDL_WindowData *) window->driverdata;
if (windowData->coreWindow == nullptr) {
// For some reason, the window isn't associated with a CoreWindow.
// This might end up being the case as XAML support is extended.
// For now, if there's no CoreWindow attached to the SDL_Window,
// don't do any transforms.
// TODO, WinRT: make sure touch input coordinate ranges are correct when using XAML support
return rawPosition;
}
// The CoreWindow can only be accessed on certain thread(s).
SDL_assert(CoreWindow::GetForCurrentThread() != nullptr);
CoreWindow ^ nativeWindow = windowData->coreWindow.Get();
Windows::Foundation::Point outputPosition;
// Compute coordinates normalized from 0..1.
// If the coordinates need to be sized to the SDL window,
// we'll do that after.
#if (WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP) || (NTDDI_VERSION > NTDDI_WIN8)
outputPosition.X = rawPosition.X / nativeWindow->Bounds.Width;
outputPosition.Y = rawPosition.Y / nativeWindow->Bounds.Height;
#else
switch (WINRT_DISPLAY_PROPERTY(CurrentOrientation))
{
case DisplayOrientations::Portrait:
outputPosition.X = rawPosition.X / nativeWindow->Bounds.Width;
outputPosition.Y = rawPosition.Y / nativeWindow->Bounds.Height;
break;
case DisplayOrientations::PortraitFlipped:
outputPosition.X = 1.0f - (rawPosition.X / nativeWindow->Bounds.Width);
outputPosition.Y = 1.0f - (rawPosition.Y / nativeWindow->Bounds.Height);
break;
case DisplayOrientations::Landscape:
outputPosition.X = rawPosition.Y / nativeWindow->Bounds.Height;
outputPosition.Y = 1.0f - (rawPosition.X / nativeWindow->Bounds.Width);
break;
case DisplayOrientations::LandscapeFlipped:
outputPosition.X = 1.0f - (rawPosition.Y / nativeWindow->Bounds.Height);
outputPosition.Y = rawPosition.X / nativeWindow->Bounds.Width;
break;
default:
break;
}
#endif
if (normalization == TransformToSDLWindowSize) {
outputPosition.X *= ((float32) window->w);
outputPosition.Y *= ((float32) window->h);
}
return outputPosition;
}
static inline int
_lround(float arg)
{
if (arg >= 0.0f) {
return (int)floor(arg + 0.5f);
} else {
return (int)ceil(arg - 0.5f);
}
}
Uint8
WINRT_GetSDLButtonForPointerPoint(Windows::UI::Input::PointerPoint ^pt)
{
using namespace Windows::UI::Input;
#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
return SDL_BUTTON_LEFT;
#else
switch (pt->Properties->PointerUpdateKind)
{
case PointerUpdateKind::LeftButtonPressed:
case PointerUpdateKind::LeftButtonReleased:
return SDL_BUTTON_LEFT;
case PointerUpdateKind::RightButtonPressed:
case PointerUpdateKind::RightButtonReleased:
return SDL_BUTTON_RIGHT;
case PointerUpdateKind::MiddleButtonPressed:
case PointerUpdateKind::MiddleButtonReleased:
return SDL_BUTTON_MIDDLE;
case PointerUpdateKind::XButton1Pressed:
case PointerUpdateKind::XButton1Released:
return SDL_BUTTON_X1;
case PointerUpdateKind::XButton2Pressed:
case PointerUpdateKind::XButton2Released:
return SDL_BUTTON_X2;
default:
break;
}
#endif
return 0;
}
//const char *
//WINRT_ConvertPointerUpdateKindToString(Windows::UI::Input::PointerUpdateKind kind)
//{
// using namespace Windows::UI::Input;
//
// switch (kind)
// {
// case PointerUpdateKind::Other:
// return "Other";
// case PointerUpdateKind::LeftButtonPressed:
// return "LeftButtonPressed";
// case PointerUpdateKind::LeftButtonReleased:
// return "LeftButtonReleased";
// case PointerUpdateKind::RightButtonPressed:
// return "RightButtonPressed";
// case PointerUpdateKind::RightButtonReleased:
// return "RightButtonReleased";
// case PointerUpdateKind::MiddleButtonPressed:
// return "MiddleButtonPressed";
// case PointerUpdateKind::MiddleButtonReleased:
// return "MiddleButtonReleased";
// case PointerUpdateKind::XButton1Pressed:
// return "XButton1Pressed";
// case PointerUpdateKind::XButton1Released:
// return "XButton1Released";
// case PointerUpdateKind::XButton2Pressed:
// return "XButton2Pressed";
// case PointerUpdateKind::XButton2Released:
// return "XButton2Released";
// }
//
// return "";
//}
static bool
WINRT_IsTouchEvent(Windows::UI::Input::PointerPoint ^pointerPoint)
{
#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
return true;
#else
using namespace Windows::Devices::Input;
switch (pointerPoint->PointerDevice->PointerDeviceType) {
case PointerDeviceType::Touch:
case PointerDeviceType::Pen:
return true;
default:
return false;
}
#endif
}
void WINRT_ProcessPointerPressedEvent(SDL_Window *window, Windows::UI::Input::PointerPoint ^pointerPoint)
{
if (!window) {
return;
}
Uint8 button = WINRT_GetSDLButtonForPointerPoint(pointerPoint);
if ( ! WINRT_IsTouchEvent(pointerPoint)) {
SDL_SendMouseButton(window, 0, SDL_PRESSED, button);
} else {
Windows::Foundation::Point normalizedPoint = WINRT_TransformCursorPosition(window, pointerPoint->Position, NormalizeZeroToOne);
Windows::Foundation::Point windowPoint = WINRT_TransformCursorPosition(window, pointerPoint->Position, TransformToSDLWindowSize);
SDL_SendTouch(
WINRT_TouchID,
(SDL_FingerID) pointerPoint->PointerId,
window,
SDL_TRUE,
normalizedPoint.X,
normalizedPoint.Y,
pointerPoint->Properties->Pressure);
}
}
void
WINRT_ProcessPointerMovedEvent(SDL_Window *window, Windows::UI::Input::PointerPoint ^pointerPoint)
{
if (!window || WINRT_UsingRelativeMouseMode) {
return;
}
Windows::Foundation::Point normalizedPoint = WINRT_TransformCursorPosition(window, pointerPoint->Position, NormalizeZeroToOne);
Windows::Foundation::Point windowPoint = WINRT_TransformCursorPosition(window, pointerPoint->Position, TransformToSDLWindowSize);
if ( ! WINRT_IsTouchEvent(pointerPoint)) {
SDL_SendMouseMotion(window, 0, 0, (int)windowPoint.X, (int)windowPoint.Y);
} else {
SDL_SendTouchMotion(
WINRT_TouchID,
(SDL_FingerID) pointerPoint->PointerId,
window,
normalizedPoint.X,
normalizedPoint.Y,
pointerPoint->Properties->Pressure);
}
}
void WINRT_ProcessPointerReleasedEvent(SDL_Window *window, Windows::UI::Input::PointerPoint ^pointerPoint)
{
if (!window) {
return;
}
Uint8 button = WINRT_GetSDLButtonForPointerPoint(pointerPoint);
if (!WINRT_IsTouchEvent(pointerPoint)) {
SDL_SendMouseButton(window, 0, SDL_RELEASED, button);
} else {
Windows::Foundation::Point normalizedPoint = WINRT_TransformCursorPosition(window, pointerPoint->Position, NormalizeZeroToOne);
SDL_SendTouch(
WINRT_TouchID,
(SDL_FingerID) pointerPoint->PointerId,
window,
SDL_FALSE,
normalizedPoint.X,
normalizedPoint.Y,
pointerPoint->Properties->Pressure);
}
}
void WINRT_ProcessPointerEnteredEvent(SDL_Window *window, Windows::UI::Input::PointerPoint ^pointerPoint)
{
if (!window) {
return;
}
if (!WINRT_IsTouchEvent(pointerPoint)) {
SDL_SetMouseFocus(window);
}
}
void WINRT_ProcessPointerExitedEvent(SDL_Window *window, Windows::UI::Input::PointerPoint ^pointerPoint)
{
if (!window) {
return;
}
if (!WINRT_IsTouchEvent(pointerPoint)) {
SDL_SetMouseFocus(NULL);
}
}
void
WINRT_ProcessPointerWheelChangedEvent(SDL_Window *window, Windows::UI::Input::PointerPoint ^pointerPoint)
{
if (!window) {
return;
}
float motion = (float) pointerPoint->Properties->MouseWheelDelta / WHEEL_DELTA;
SDL_SendMouseWheel(window, 0, 0, (float) motion, SDL_MOUSEWHEEL_NORMAL);
}
void
WINRT_ProcessMouseMovedEvent(SDL_Window * window, Windows::Devices::Input::MouseEventArgs ^args)
{
if (!window || !WINRT_UsingRelativeMouseMode) {
return;
}
// DLudwig, 2012-12-28: On some systems, namely Visual Studio's Windows
// Simulator, as well as Windows 8 in a Parallels 8 VM, MouseEventArgs'
// MouseDelta field often reports very large values. More information
// on this can be found at the following pages on MSDN:
// - http://social.msdn.microsoft.com/Forums/en-US/winappswithnativecode/thread/a3c789fa-f1c5-49c4-9c0a-7db88d0f90f8
// - https://connect.microsoft.com/VisualStudio/Feedback/details/756515
//
// The values do not appear to be as large when running on some systems,
// most notably a Surface RT. Furthermore, the values returned by
// CoreWindow's PointerMoved event, and sent to this class' OnPointerMoved
// method, do not ever appear to be large, even when MouseEventArgs'
// MouseDelta is reporting to the contrary.
//
// On systems with the large-values behavior, it appears that the values
// get reported as if the screen's size is 65536 units in both the X and Y
// dimensions. This can be viewed by using Windows' now-private, "Raw Input"
// APIs. (GetRawInputData, RegisterRawInputDevices, WM_INPUT, etc.)
//
// MSDN's documentation on MouseEventArgs' MouseDelta field (at
// http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.input.mouseeventargs.mousedelta ),
// does not seem to indicate (to me) that its values should be so large. It
// says that its values should be a "change in screen location". I could
// be misinterpreting this, however a post on MSDN from a Microsoft engineer (see:
// http://social.msdn.microsoft.com/Forums/en-US/winappswithnativecode/thread/09a9868e-95bb-4858-ba1a-cb4d2c298d62 ),
// indicates that these values are in DIPs, which is the same unit used
// by CoreWindow's PointerMoved events (via the Position field in its CurrentPoint
// property. See http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.input.pointerpoint.position.aspx
// for details.)
//
// To note, PointerMoved events are sent a 'RawPosition' value (via the
// CurrentPoint property in MouseEventArgs), however these do not seem
// to exhibit the same large-value behavior.
//
// The values passed via PointerMoved events can't always be used for relative
// mouse motion, unfortunately. Its values are bound to the cursor's position,
// which stops when it hits one of the screen's edges. This can be a problem in
// first person shooters, whereby it is normal for mouse motion to travel far
// along any one axis for a period of time. MouseMoved events do not have the
// screen-bounding limitation, and can be used regardless of where the system's
// cursor is.
//
// One possible workaround would be to programmatically set the cursor's
// position to the screen's center (when SDL's relative mouse mode is enabled),
// however WinRT does not yet seem to have the ability to set the cursor's
// position via a public API. Win32 did this via an API call, SetCursorPos,
// however WinRT makes this function be private. Apps that use it won't get
// approved for distribution in the Windows Store. I've yet to be able to find
// a suitable, store-friendly counterpart for WinRT.
//
// There may be some room for a workaround whereby OnPointerMoved's values
// are compared to the values from OnMouseMoved in order to detect
// when this bug is active. A suitable transformation could then be made to
// OnMouseMoved's values. For now, however, the system-reported values are sent
// to SDL with minimal transformation: from native screen coordinates (in DIPs)
// to SDL window coordinates.
//
const Windows::Foundation::Point mouseDeltaInDIPs((float)args->MouseDelta.X, (float)args->MouseDelta.Y);
const Windows::Foundation::Point mouseDeltaInSDLWindowCoords = WINRT_TransformCursorPosition(window, mouseDeltaInDIPs, TransformToSDLWindowSize);
SDL_SendMouseMotion(
window,
0,
1,
_lround(mouseDeltaInSDLWindowCoords.X),
_lround(mouseDeltaInSDLWindowCoords.Y));
}
#endif // SDL_VIDEO_DRIVER_WINRT
| YifuLiu/AliOS-Things | components/SDL2/src/video/winrt/SDL_winrtpointerinput.cpp | C++ | apache-2.0 | 14,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.
*/
#include "../../SDL_internal.h"
#if SDL_VIDEO_DRIVER_WINRT
/* WinRT SDL video driver implementation
Initial work on this was done by David Ludwig (dludwig@pobox.com), and
was based off of SDL's "dummy" video driver.
*/
/* Windows includes */
#include <agile.h>
#include <windows.graphics.display.h>
#include <windows.system.display.h>
#include <dxgi.h>
#include <dxgi1_2.h>
using namespace Windows::ApplicationModel::Core;
using namespace Windows::Foundation;
using namespace Windows::Graphics::Display;
using namespace Windows::UI::Core;
using namespace Windows::UI::ViewManagement;
/* [re]declare Windows GUIDs locally, to limit the amount of external lib(s) SDL has to link to */
static const GUID IID_IDisplayRequest = { 0xe5732044, 0xf49f, 0x4b60, { 0x8d, 0xd4, 0x5e, 0x7e, 0x3a, 0x63, 0x2a, 0xc0 } };
static const GUID IID_IDXGIFactory2 = { 0x50c83a1c, 0xe072, 0x4c48, { 0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, 0xd0 } };
/* SDL includes */
extern "C" {
#include "SDL_video.h"
#include "SDL_mouse.h"
#include "../SDL_sysvideo.h"
#include "../SDL_pixels_c.h"
#include "../../events/SDL_events_c.h"
#include "../../render/SDL_sysrender.h"
#include "SDL_syswm.h"
#include "SDL_winrtopengles.h"
#include "../../core/windows/SDL_windows.h"
}
#include "../../core/winrt/SDL_winrtapp_direct3d.h"
#include "../../core/winrt/SDL_winrtapp_xaml.h"
#include "SDL_winrtvideo_cpp.h"
#include "SDL_winrtevents_c.h"
#include "SDL_winrtgamebar_cpp.h"
#include "SDL_winrtmouse_c.h"
#include "SDL_main.h"
#include "SDL_system.h"
/* Initialization/Query functions */
static int WINRT_VideoInit(_THIS);
static int WINRT_InitModes(_THIS);
static int WINRT_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode);
static void WINRT_VideoQuit(_THIS);
/* Window functions */
static int WINRT_CreateWindow(_THIS, SDL_Window * window);
static void WINRT_SetWindowSize(_THIS, SDL_Window * window);
static void WINRT_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen);
static void WINRT_DestroyWindow(_THIS, SDL_Window * window);
static SDL_bool WINRT_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info);
/* Misc functions */
static ABI::Windows::System::Display::IDisplayRequest * WINRT_CreateDisplayRequest(_THIS);
extern void WINRT_SuspendScreenSaver(_THIS);
/* SDL-internal globals: */
SDL_Window * WINRT_GlobalSDLWindow = NULL;
/* WinRT driver bootstrap functions */
static int
WINRT_Available(void)
{
return (1);
}
static void
WINRT_DeleteDevice(SDL_VideoDevice * device)
{
if (device->driverdata) {
SDL_VideoData * video_data = (SDL_VideoData *)device->driverdata;
if (video_data->winrtEglWindow) {
video_data->winrtEglWindow->Release();
}
SDL_free(video_data);
}
SDL_free(device);
}
static SDL_VideoDevice *
WINRT_CreateDevice(int devindex)
{
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) {
SDL_OutOfMemory();
return (0);
}
data = (SDL_VideoData *) SDL_calloc(1, sizeof(SDL_VideoData));
if (!data) {
SDL_OutOfMemory();
SDL_free(device);
return (0);
}
device->driverdata = data;
/* Set the function pointers */
device->VideoInit = WINRT_VideoInit;
device->VideoQuit = WINRT_VideoQuit;
device->CreateSDLWindow = WINRT_CreateWindow;
device->SetWindowSize = WINRT_SetWindowSize;
device->SetWindowFullscreen = WINRT_SetWindowFullscreen;
device->DestroyWindow = WINRT_DestroyWindow;
device->SetDisplayMode = WINRT_SetDisplayMode;
device->PumpEvents = WINRT_PumpEvents;
device->GetWindowWMInfo = WINRT_GetWindowWMInfo;
device->SuspendScreenSaver = WINRT_SuspendScreenSaver;
#if NTDDI_VERSION >= NTDDI_WIN10
device->HasScreenKeyboardSupport = WINRT_HasScreenKeyboardSupport;
device->ShowScreenKeyboard = WINRT_ShowScreenKeyboard;
device->HideScreenKeyboard = WINRT_HideScreenKeyboard;
device->IsScreenKeyboardShown = WINRT_IsScreenKeyboardShown;
#endif
#ifdef SDL_VIDEO_OPENGL_EGL
device->GL_LoadLibrary = WINRT_GLES_LoadLibrary;
device->GL_GetProcAddress = WINRT_GLES_GetProcAddress;
device->GL_UnloadLibrary = WINRT_GLES_UnloadLibrary;
device->GL_CreateContext = WINRT_GLES_CreateContext;
device->GL_MakeCurrent = WINRT_GLES_MakeCurrent;
device->GL_SetSwapInterval = WINRT_GLES_SetSwapInterval;
device->GL_GetSwapInterval = WINRT_GLES_GetSwapInterval;
device->GL_SwapWindow = WINRT_GLES_SwapWindow;
device->GL_DeleteContext = WINRT_GLES_DeleteContext;
#endif
device->free = WINRT_DeleteDevice;
return device;
}
#define WINRTVID_DRIVER_NAME "winrt"
VideoBootStrap WINRT_bootstrap = {
WINRTVID_DRIVER_NAME, "SDL WinRT video driver",
WINRT_Available, WINRT_CreateDevice
};
int
WINRT_VideoInit(_THIS)
{
SDL_VideoData * driverdata = (SDL_VideoData *) _this->driverdata;
if (WINRT_InitModes(_this) < 0) {
return -1;
}
WINRT_InitMouse(_this);
WINRT_InitTouch(_this);
WINRT_InitGameBar(_this);
if (driverdata) {
/* Initialize screensaver-disabling support */
driverdata->displayRequest = WINRT_CreateDisplayRequest(_this);
}
return 0;
}
extern "C"
Uint32 D3D11_DXGIFormatToSDLPixelFormat(DXGI_FORMAT dxgiFormat);
static void
WINRT_DXGIModeToSDLDisplayMode(const DXGI_MODE_DESC * dxgiMode, SDL_DisplayMode * sdlMode)
{
SDL_zerop(sdlMode);
sdlMode->w = dxgiMode->Width;
sdlMode->h = dxgiMode->Height;
sdlMode->refresh_rate = dxgiMode->RefreshRate.Numerator / dxgiMode->RefreshRate.Denominator;
sdlMode->format = D3D11_DXGIFormatToSDLPixelFormat(dxgiMode->Format);
}
static int
WINRT_AddDisplaysForOutput (_THIS, IDXGIAdapter1 * dxgiAdapter1, int outputIndex)
{
HRESULT hr;
IDXGIOutput * dxgiOutput = NULL;
DXGI_OUTPUT_DESC dxgiOutputDesc;
SDL_VideoDisplay display;
char * displayName = NULL;
UINT numModes;
DXGI_MODE_DESC * dxgiModes = NULL;
int functionResult = -1; /* -1 for failure, 0 for success */
DXGI_MODE_DESC modeToMatch, closestMatch;
SDL_zero(display);
hr = dxgiAdapter1->EnumOutputs(outputIndex, &dxgiOutput);
if (FAILED(hr)) {
if (hr != DXGI_ERROR_NOT_FOUND) {
WIN_SetErrorFromHRESULT(__FUNCTION__ ", IDXGIAdapter1::EnumOutputs failed", hr);
}
goto done;
}
hr = dxgiOutput->GetDesc(&dxgiOutputDesc);
if (FAILED(hr)) {
WIN_SetErrorFromHRESULT(__FUNCTION__ ", IDXGIOutput::GetDesc failed", hr);
goto done;
}
SDL_zero(modeToMatch);
modeToMatch.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
modeToMatch.Width = (dxgiOutputDesc.DesktopCoordinates.right - dxgiOutputDesc.DesktopCoordinates.left);
modeToMatch.Height = (dxgiOutputDesc.DesktopCoordinates.bottom - dxgiOutputDesc.DesktopCoordinates.top);
hr = dxgiOutput->FindClosestMatchingMode(&modeToMatch, &closestMatch, NULL);
if (hr == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE) {
/* DXGI_ERROR_NOT_CURRENTLY_AVAILABLE gets returned by IDXGIOutput::FindClosestMatchingMode
when running under the Windows Simulator, which uses Remote Desktop (formerly known as Terminal
Services) under the hood. According to the MSDN docs for the similar function,
IDXGIOutput::GetDisplayModeList, DXGI_ERROR_NOT_CURRENTLY_AVAILABLE is returned if and
when an app is run under a Terminal Services session, hence the assumption.
In this case, just add an SDL display mode, with approximated values.
*/
SDL_DisplayMode mode;
SDL_zero(mode);
display.name = "Windows Simulator / Terminal Services Display";
mode.w = (dxgiOutputDesc.DesktopCoordinates.right - dxgiOutputDesc.DesktopCoordinates.left);
mode.h = (dxgiOutputDesc.DesktopCoordinates.bottom - dxgiOutputDesc.DesktopCoordinates.top);
mode.format = DXGI_FORMAT_B8G8R8A8_UNORM;
mode.refresh_rate = 0; /* Display mode is unknown, so just fill in zero, as specified by SDL's header files */
display.desktop_mode = mode;
display.current_mode = mode;
if ( ! SDL_AddDisplayMode(&display, &mode)) {
goto done;
}
} else if (FAILED(hr)) {
WIN_SetErrorFromHRESULT(__FUNCTION__ ", IDXGIOutput::FindClosestMatchingMode failed", hr);
goto done;
} else {
displayName = WIN_StringToUTF8(dxgiOutputDesc.DeviceName);
display.name = displayName;
WINRT_DXGIModeToSDLDisplayMode(&closestMatch, &display.desktop_mode);
display.current_mode = display.desktop_mode;
hr = dxgiOutput->GetDisplayModeList(DXGI_FORMAT_B8G8R8A8_UNORM, 0, &numModes, NULL);
if (FAILED(hr)) {
if (hr == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE) {
// TODO, WinRT: make sure display mode(s) are added when using Terminal Services / Windows Simulator
}
WIN_SetErrorFromHRESULT(__FUNCTION__ ", IDXGIOutput::GetDisplayModeList [get mode list size] failed", hr);
goto done;
}
dxgiModes = (DXGI_MODE_DESC *)SDL_calloc(numModes, sizeof(DXGI_MODE_DESC));
if ( ! dxgiModes) {
SDL_OutOfMemory();
goto done;
}
hr = dxgiOutput->GetDisplayModeList(DXGI_FORMAT_B8G8R8A8_UNORM, 0, &numModes, dxgiModes);
if (FAILED(hr)) {
WIN_SetErrorFromHRESULT(__FUNCTION__ ", IDXGIOutput::GetDisplayModeList [get mode contents] failed", hr);
goto done;
}
for (UINT i = 0; i < numModes; ++i) {
SDL_DisplayMode sdlMode;
WINRT_DXGIModeToSDLDisplayMode(&dxgiModes[i], &sdlMode);
SDL_AddDisplayMode(&display, &sdlMode);
}
}
if (SDL_AddVideoDisplay(&display) < 0) {
goto done;
}
functionResult = 0; /* 0 for Success! */
done:
if (dxgiModes) {
SDL_free(dxgiModes);
}
if (dxgiOutput) {
dxgiOutput->Release();
}
if (displayName) {
SDL_free(displayName);
}
return functionResult;
}
static int
WINRT_AddDisplaysForAdapter (_THIS, IDXGIFactory2 * dxgiFactory2, int adapterIndex)
{
HRESULT hr;
IDXGIAdapter1 * dxgiAdapter1;
hr = dxgiFactory2->EnumAdapters1(adapterIndex, &dxgiAdapter1);
if (FAILED(hr)) {
if (hr != DXGI_ERROR_NOT_FOUND) {
WIN_SetErrorFromHRESULT(__FUNCTION__ ", IDXGIFactory1::EnumAdapters1() failed", hr);
}
return -1;
}
for (int outputIndex = 0; ; ++outputIndex) {
if (WINRT_AddDisplaysForOutput(_this, dxgiAdapter1, outputIndex) < 0) {
/* HACK: The Windows App Certification Kit 10.0 can fail, when
running the Store Apps' test, "Direct3D Feature Test". The
certification kit's error is:
"Application App was not running at the end of the test. It likely crashed or was terminated for having become unresponsive."
This was caused by SDL/WinRT's DXGI failing to report any
outputs. Attempts to get the 1st display-output from the
1st display-adapter can fail, with IDXGIAdapter::EnumOutputs
returning DXGI_ERROR_NOT_FOUND. This could be a bug in Windows,
the Windows App Certification Kit, or possibly in SDL/WinRT's
display detection code. Either way, try to detect when this
happens, and use a hackish means to create a reasonable-as-possible
'display mode'. -- DavidL
*/
if (adapterIndex == 0 && outputIndex == 0) {
SDL_VideoDisplay display;
SDL_DisplayMode mode;
#if SDL_WINRT_USE_APPLICATIONVIEW
ApplicationView ^ appView = ApplicationView::GetForCurrentView();
#endif
CoreWindow ^ coreWin = CoreWindow::GetForCurrentThread();
SDL_zero(display);
SDL_zero(mode);
display.name = "DXGI Display-detection Workaround";
/* HACK: ApplicationView's VisibleBounds property, appeared, via testing, to
give a better approximation of display-size, than did CoreWindow's
Bounds property, insofar that ApplicationView::VisibleBounds seems like
it will, at least some of the time, give the full display size (during the
failing test), whereas CoreWindow might not. -- DavidL
*/
#if (NTDDI_VERSION >= NTDDI_WIN10) || (SDL_WINRT_USE_APPLICATIONVIEW && WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
mode.w = WINRT_DIPS_TO_PHYSICAL_PIXELS(appView->VisibleBounds.Width);
mode.h = WINRT_DIPS_TO_PHYSICAL_PIXELS(appView->VisibleBounds.Height);
#else
/* On platform(s) that do not support VisibleBounds, such as Windows 8.1,
fall back to CoreWindow's Bounds property.
*/
mode.w = WINRT_DIPS_TO_PHYSICAL_PIXELS(coreWin->Bounds.Width);
mode.h = WINRT_DIPS_TO_PHYSICAL_PIXELS(coreWin->Bounds.Height);
#endif
mode.format = DXGI_FORMAT_B8G8R8A8_UNORM;
mode.refresh_rate = 0; /* Display mode is unknown, so just fill in zero, as specified by SDL's header files */
display.desktop_mode = mode;
display.current_mode = mode;
if ((SDL_AddDisplayMode(&display, &mode) < 0) ||
(SDL_AddVideoDisplay(&display) < 0))
{
return SDL_SetError("Failed to apply DXGI Display-detection workaround");
}
}
break;
}
}
dxgiAdapter1->Release();
return 0;
}
int
WINRT_InitModes(_THIS)
{
/* HACK: Initialize a single display, for whatever screen the app's
CoreApplicationView is on.
TODO, WinRT: Try initializing multiple displays, one for each monitor.
Appropriate WinRT APIs for this seem elusive, though. -- DavidL
*/
HRESULT hr;
IDXGIFactory2 * dxgiFactory2 = NULL;
hr = CreateDXGIFactory1(IID_IDXGIFactory2, (void **)&dxgiFactory2);
if (FAILED(hr)) {
WIN_SetErrorFromHRESULT(__FUNCTION__ ", CreateDXGIFactory1() failed", hr);
return -1;
}
for (int adapterIndex = 0; ; ++adapterIndex) {
if (WINRT_AddDisplaysForAdapter(_this, dxgiFactory2, adapterIndex) < 0) {
break;
}
}
return 0;
}
static int
WINRT_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode)
{
return 0;
}
void
WINRT_VideoQuit(_THIS)
{
SDL_VideoData * driverdata = (SDL_VideoData *) _this->driverdata;
if (driverdata && driverdata->displayRequest) {
driverdata->displayRequest->Release();
driverdata->displayRequest = NULL;
}
WINRT_QuitGameBar(_this);
WINRT_QuitMouse(_this);
}
static const Uint32 WINRT_DetectableFlags =
SDL_WINDOW_MAXIMIZED |
SDL_WINDOW_FULLSCREEN_DESKTOP |
SDL_WINDOW_SHOWN |
SDL_WINDOW_HIDDEN |
SDL_WINDOW_MOUSE_FOCUS;
extern "C" Uint32
WINRT_DetectWindowFlags(SDL_Window * window)
{
Uint32 latestFlags = 0;
SDL_WindowData * data = (SDL_WindowData *) window->driverdata;
bool is_fullscreen = false;
#if SDL_WINRT_USE_APPLICATIONVIEW
if (data->appView) {
is_fullscreen = data->appView->IsFullScreen;
}
#elif (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) || (NTDDI_VERSION == NTDDI_WIN8)
is_fullscreen = true;
#endif
if (data->coreWindow.Get()) {
if (is_fullscreen) {
SDL_VideoDisplay * display = SDL_GetDisplayForWindow(window);
int w = WINRT_DIPS_TO_PHYSICAL_PIXELS(data->coreWindow->Bounds.Width);
int h = WINRT_DIPS_TO_PHYSICAL_PIXELS(data->coreWindow->Bounds.Height);
#if (WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP) || (NTDDI_VERSION > NTDDI_WIN8)
// On all WinRT platforms, except for WinPhone 8.0, rotate the
// window size. This is needed to properly calculate
// fullscreen vs. maximized.
const DisplayOrientations currentOrientation = WINRT_DISPLAY_PROPERTY(CurrentOrientation);
switch (currentOrientation) {
#if (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
case DisplayOrientations::Landscape:
case DisplayOrientations::LandscapeFlipped:
#else
case DisplayOrientations::Portrait:
case DisplayOrientations::PortraitFlipped:
#endif
{
int tmp = w;
w = h;
h = tmp;
} break;
}
#endif
if (display->desktop_mode.w != w || display->desktop_mode.h != h) {
latestFlags |= SDL_WINDOW_MAXIMIZED;
} else {
latestFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
}
}
if (data->coreWindow->Visible) {
latestFlags |= SDL_WINDOW_SHOWN;
} else {
latestFlags |= SDL_WINDOW_HIDDEN;
}
#if (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) && (NTDDI_VERSION < NTDDI_WINBLUE)
// data->coreWindow->PointerPosition is not supported on WinPhone 8.0
latestFlags |= SDL_WINDOW_MOUSE_FOCUS;
#else
if (data->coreWindow->Visible && data->coreWindow->Bounds.Contains(data->coreWindow->PointerPosition)) {
latestFlags |= SDL_WINDOW_MOUSE_FOCUS;
}
#endif
}
return latestFlags;
}
// TODO, WinRT: consider removing WINRT_UpdateWindowFlags, and just calling WINRT_DetectWindowFlags as-appropriate (with appropriate calls to SDL_SendWindowEvent)
void
WINRT_UpdateWindowFlags(SDL_Window * window, Uint32 mask)
{
mask &= WINRT_DetectableFlags;
if (window) {
Uint32 apply = WINRT_DetectWindowFlags(window);
if ((apply & mask) & SDL_WINDOW_FULLSCREEN) {
window->last_fullscreen_flags = window->flags; // seems necessary to programmatically un-fullscreen, via SDL APIs
}
window->flags = (window->flags & ~mask) | (apply & mask);
}
}
static bool
WINRT_IsCoreWindowActive(CoreWindow ^ coreWindow)
{
/* WinRT does not appear to offer API(s) to determine window-activation state,
at least not that I am aware of in Win8 - Win10. As such, SDL tracks this
itself, via window-activation events.
If there *is* an API to track this, it should probably get used instead
of the following hack (that uses "SDLHelperWindowActivationState").
-- DavidL.
*/
if (coreWindow->CustomProperties->HasKey("SDLHelperWindowActivationState")) {
CoreWindowActivationState activationState = \
safe_cast<CoreWindowActivationState>(coreWindow->CustomProperties->Lookup("SDLHelperWindowActivationState"));
return (activationState != CoreWindowActivationState::Deactivated);
}
/* Assume that non-SDL tracked windows are active, although this should
probably be avoided, if possible.
This might not even be possible, in normal SDL use, at least as of
this writing (Dec 22, 2015; via latest hg.libsdl.org/SDL clone) -- DavidL
*/
return true;
}
int
WINRT_CreateWindow(_THIS, SDL_Window * window)
{
// Make sure that only one window gets created, at least until multimonitor
// support is added.
if (WINRT_GlobalSDLWindow != NULL) {
SDL_SetError("WinRT only supports one window");
return -1;
}
SDL_WindowData *data = new SDL_WindowData; /* use 'new' here as SDL_WindowData may use WinRT/C++ types */
if (!data) {
SDL_OutOfMemory();
return -1;
}
window->driverdata = data;
data->sdlWindow = window;
/* To note, when XAML support is enabled, access to the CoreWindow will not
be possible, at least not via the SDL/XAML thread. Attempts to access it
from there will throw exceptions. As such, the SDL_WindowData's
'coreWindow' field will only be set (to a non-null value) if XAML isn't
enabled.
*/
if (!WINRT_XAMLWasEnabled) {
data->coreWindow = CoreWindow::GetForCurrentThread();
#if SDL_WINRT_USE_APPLICATIONVIEW
data->appView = ApplicationView::GetForCurrentView();
#endif
}
/* Make note of the requested window flags, before they start getting changed. */
const Uint32 requestedFlags = window->flags;
#if SDL_VIDEO_OPENGL_EGL
/* Setup the EGL surface, but only if OpenGL ES 2 was requested. */
if (!(window->flags & SDL_WINDOW_OPENGL)) {
/* OpenGL ES 2 wasn't requested. Don't set up an EGL surface. */
data->egl_surface = EGL_NO_SURFACE;
} else {
/* OpenGL ES 2 was reuqested. Set up an EGL surface. */
SDL_VideoData * video_data = (SDL_VideoData *)_this->driverdata;
/* Call SDL_EGL_ChooseConfig and eglCreateWindowSurface directly,
* rather than via SDL_EGL_CreateSurface, as older versions of
* ANGLE/WinRT may require that a C++ object, ComPtr<IUnknown>,
* be passed into eglCreateWindowSurface.
*/
if (SDL_EGL_ChooseConfig(_this) != 0) {
char buf[512];
SDL_snprintf(buf, sizeof(buf), "SDL_EGL_ChooseConfig failed: %s", SDL_GetError());
return SDL_SetError("%s", buf);
}
if (video_data->winrtEglWindow) { /* ... is the 'old' version of ANGLE/WinRT being used? */
/* Attempt to create a window surface using older versions of
* ANGLE/WinRT:
*/
Microsoft::WRL::ComPtr<IUnknown> cpp_winrtEglWindow = video_data->winrtEglWindow;
data->egl_surface = ((eglCreateWindowSurface_Old_Function)_this->egl_data->eglCreateWindowSurface)(
_this->egl_data->egl_display,
_this->egl_data->egl_config,
cpp_winrtEglWindow, NULL);
if (data->egl_surface == NULL) {
return SDL_EGL_SetError("unable to create EGL native-window surface", "eglCreateWindowSurface");
}
} else if (data->coreWindow.Get() != nullptr) {
/* Attempt to create a window surface using newer versions of
* ANGLE/WinRT:
*/
IInspectable * coreWindowAsIInspectable = reinterpret_cast<IInspectable *>(data->coreWindow.Get());
data->egl_surface = _this->egl_data->eglCreateWindowSurface(
_this->egl_data->egl_display,
_this->egl_data->egl_config,
coreWindowAsIInspectable,
NULL);
if (data->egl_surface == NULL) {
return SDL_EGL_SetError("unable to create EGL native-window surface", "eglCreateWindowSurface");
}
} else {
return SDL_SetError("No supported means to create an EGL window surface are available");
}
}
#endif
/* Determine as many flags dynamically, as possible. */
window->flags =
SDL_WINDOW_BORDERLESS |
SDL_WINDOW_RESIZABLE;
#if SDL_VIDEO_OPENGL_EGL
if (data->egl_surface) {
window->flags |= SDL_WINDOW_OPENGL;
}
#endif
if (WINRT_XAMLWasEnabled) {
/* TODO, WinRT: set SDL_Window size, maybe position too, from XAML control */
window->x = 0;
window->y = 0;
window->flags |= SDL_WINDOW_SHOWN;
SDL_SetMouseFocus(NULL); // TODO: detect this
SDL_SetKeyboardFocus(NULL); // TODO: detect this
} else {
/* WinRT 8.x apps seem to live in an environment where the OS controls the
app's window size, with some apps being fullscreen, depending on
user choice of various things. For now, just adapt the SDL_Window to
whatever Windows set-up as the native-window's geometry.
*/
window->x = WINRT_DIPS_TO_PHYSICAL_PIXELS(data->coreWindow->Bounds.Left);
window->y = WINRT_DIPS_TO_PHYSICAL_PIXELS(data->coreWindow->Bounds.Top);
#if NTDDI_VERSION < NTDDI_WIN10
/* On WinRT 8.x / pre-Win10, just use the size we were given. */
window->w = WINRT_DIPS_TO_PHYSICAL_PIXELS(data->coreWindow->Bounds.Width);
window->h = WINRT_DIPS_TO_PHYSICAL_PIXELS(data->coreWindow->Bounds.Height);
#else
/* On Windows 10, we occasionally get control over window size. For windowed
mode apps, try this.
*/
bool didSetSize = false;
if (!(requestedFlags & SDL_WINDOW_FULLSCREEN)) {
const Windows::Foundation::Size size(WINRT_PHYSICAL_PIXELS_TO_DIPS(window->w),
WINRT_PHYSICAL_PIXELS_TO_DIPS(window->h));
didSetSize = data->appView->TryResizeView(size);
}
if (!didSetSize) {
/* We either weren't able to set the window size, or a request for
fullscreen was made. Get window-size info from the OS.
*/
window->w = WINRT_DIPS_TO_PHYSICAL_PIXELS(data->coreWindow->Bounds.Width);
window->h = WINRT_DIPS_TO_PHYSICAL_PIXELS(data->coreWindow->Bounds.Height);
}
#endif
WINRT_UpdateWindowFlags(
window,
0xffffffff /* Update any window flag(s) that WINRT_UpdateWindow can handle */
);
/* Try detecting if the window is active */
bool isWindowActive = WINRT_IsCoreWindowActive(data->coreWindow.Get());
if (isWindowActive) {
SDL_SetKeyboardFocus(window);
}
}
/* Make sure the WinRT app's IFramworkView can post events on
behalf of SDL:
*/
WINRT_GlobalSDLWindow = window;
/* All done! */
return 0;
}
void
WINRT_SetWindowSize(_THIS, SDL_Window * window)
{
#if NTDDI_VERSION >= NTDDI_WIN10
SDL_WindowData * data = (SDL_WindowData *)window->driverdata;
const Windows::Foundation::Size size(WINRT_PHYSICAL_PIXELS_TO_DIPS(window->w),
WINRT_PHYSICAL_PIXELS_TO_DIPS(window->h));
data->appView->TryResizeView(size); // TODO, WinRT: return failure (to caller?) from TryResizeView()
#endif
}
void
WINRT_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen)
{
#if NTDDI_VERSION >= NTDDI_WIN10
SDL_WindowData * data = (SDL_WindowData *)window->driverdata;
bool isWindowActive = WINRT_IsCoreWindowActive(data->coreWindow.Get());
if (isWindowActive) {
if (fullscreen) {
if (!data->appView->IsFullScreenMode) {
data->appView->TryEnterFullScreenMode(); // TODO, WinRT: return failure (to caller?) from TryEnterFullScreenMode()
}
} else {
if (data->appView->IsFullScreenMode) {
data->appView->ExitFullScreenMode();
}
}
}
#endif
}
void
WINRT_DestroyWindow(_THIS, SDL_Window * window)
{
SDL_WindowData * data = (SDL_WindowData *) window->driverdata;
if (WINRT_GlobalSDLWindow == window) {
WINRT_GlobalSDLWindow = NULL;
}
if (data) {
// Delete the internal window data:
delete data;
data = NULL;
window->driverdata = NULL;
}
}
SDL_bool
WINRT_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info)
{
SDL_WindowData * data = (SDL_WindowData *) window->driverdata;
if (info->version.major <= SDL_MAJOR_VERSION) {
info->subsystem = SDL_SYSWM_WINRT;
info->info.winrt.window = reinterpret_cast<IInspectable *>(data->coreWindow.Get());
return SDL_TRUE;
} else {
SDL_SetError("Application not compiled with SDL %d.%d",
SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
return SDL_FALSE;
}
return SDL_FALSE;
}
static ABI::Windows::System::Display::IDisplayRequest *
WINRT_CreateDisplayRequest(_THIS)
{
/* Setup a WinRT DisplayRequest object, usable for enabling/disabling screensaver requests */
wchar_t *wClassName = L"Windows.System.Display.DisplayRequest";
HSTRING hClassName;
IActivationFactory *pActivationFactory = NULL;
IInspectable * pDisplayRequestRaw = nullptr;
ABI::Windows::System::Display::IDisplayRequest * pDisplayRequest = nullptr;
HRESULT hr;
hr = ::WindowsCreateString(wClassName, (UINT32)wcslen(wClassName), &hClassName);
if (FAILED(hr)) {
goto done;
}
hr = Windows::Foundation::GetActivationFactory(hClassName, &pActivationFactory);
if (FAILED(hr)) {
goto done;
}
hr = pActivationFactory->ActivateInstance(&pDisplayRequestRaw);
if (FAILED(hr)) {
goto done;
}
hr = pDisplayRequestRaw->QueryInterface(IID_IDisplayRequest, (void **) &pDisplayRequest);
if (FAILED(hr)) {
goto done;
}
done:
if (pDisplayRequestRaw) {
pDisplayRequestRaw->Release();
}
if (pActivationFactory) {
pActivationFactory->Release();
}
if (hClassName) {
::WindowsDeleteString(hClassName);
}
return pDisplayRequest;
}
void
WINRT_SuspendScreenSaver(_THIS)
{
SDL_VideoData *driverdata = (SDL_VideoData *)_this->driverdata;
if (driverdata && driverdata->displayRequest) {
ABI::Windows::System::Display::IDisplayRequest * displayRequest = (ABI::Windows::System::Display::IDisplayRequest *) driverdata->displayRequest;
if (_this->suspend_screensaver) {
displayRequest->RequestActive();
} else {
displayRequest->RequestRelease();
}
}
}
#endif /* SDL_VIDEO_DRIVER_WINRT */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/winrt/SDL_winrtvideo.cpp | C++ | apache-2.0 | 30,613 |
/*
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.
*/
/* Windows includes: */
#include <windows.h>
#ifdef __cplusplus_winrt
#include <agile.h>
#endif
/* SDL includes: */
#include "SDL_video.h"
#include "SDL_events.h"
#if NTDDI_VERSION >= NTDDI_WINBLUE /* ApplicationView's functionality only becomes
useful for SDL in Win[Phone] 8.1 and up.
Plus, it is not available at all in WinPhone 8.0. */
#define SDL_WINRT_USE_APPLICATIONVIEW 1
#endif
extern "C" {
#include "../SDL_sysvideo.h"
#include "../SDL_egl_c.h"
}
/* Private display data */
typedef struct SDL_VideoData {
/* An object created by ANGLE/WinRT (OpenGL ES 2 for WinRT) that gets
* passed to eglGetDisplay and eglCreateWindowSurface:
*/
IUnknown *winrtEglWindow;
/* Event token(s), for unregistering WinRT event handler(s).
These are just a struct with a 64-bit integer inside them
*/
Windows::Foundation::EventRegistrationToken gameBarIsInputRedirectedToken;
/* A WinRT DisplayRequest, used for implementing SDL_*ScreenSaver() functions.
* This is really a pointer to a 'ABI::Windows::System::Display::IDisplayRequest *',
* It's casted to 'IUnknown *', to help with building SDL.
*/
IUnknown *displayRequest;
} SDL_VideoData;
/* The global, WinRT, SDL Window.
For now, SDL/WinRT only supports one window (due to platform limitations of
WinRT.
*/
extern SDL_Window * WINRT_GlobalSDLWindow;
/* Updates one or more SDL_Window flags, by querying the OS' native windowing APIs.
SDL_Window flags that can be updated should be specified in 'mask'.
*/
extern void WINRT_UpdateWindowFlags(SDL_Window * window, Uint32 mask);
extern "C" Uint32 WINRT_DetectWindowFlags(SDL_Window * window); /* detects flags w/o applying them */
/* Display mode internals */
//typedef struct
//{
// Windows::Graphics::Display::DisplayOrientations currentOrientation;
//} SDL_DisplayModeData;
#ifdef __cplusplus_winrt
/* A convenience macro to get a WinRT display property */
#if NTDDI_VERSION > NTDDI_WIN8
#define WINRT_DISPLAY_PROPERTY(NAME) (Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->NAME)
#else
#define WINRT_DISPLAY_PROPERTY(NAME) (Windows::Graphics::Display::DisplayProperties::NAME)
#endif
/* Converts DIPS to/from physical pixels */
#define WINRT_DIPS_TO_PHYSICAL_PIXELS(DIPS) ((int)(0.5f + (((float)(DIPS) * (float)WINRT_DISPLAY_PROPERTY(LogicalDpi)) / 96.f)))
#define WINRT_PHYSICAL_PIXELS_TO_DIPS(PHYSPIX) (((float)(PHYSPIX) * 96.f)/WINRT_DISPLAY_PROPERTY(LogicalDpi))
/* Internal window data */
struct SDL_WindowData
{
SDL_Window *sdlWindow;
Platform::Agile<Windows::UI::Core::CoreWindow> coreWindow;
#ifdef SDL_VIDEO_OPENGL_EGL
EGLSurface egl_surface;
#endif
#if SDL_WINRT_USE_APPLICATIONVIEW
Windows::UI::ViewManagement::ApplicationView ^ appView;
#endif
};
#endif // ifdef __cplusplus_winrt
| YifuLiu/AliOS-Things | components/SDL2/src/video/winrt/SDL_winrtvideo_cpp.h | C | apache-2.0 | 3,835 |
/*
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_X11
#include <limits.h> /* For INT_MAX */
#include "SDL_events.h"
#include "SDL_x11video.h"
#include "SDL_timer.h"
/* If you don't support UTF-8, you might use XA_STRING here */
#ifdef X_HAVE_UTF8_STRING
#define TEXT_FORMAT X11_XInternAtom(display, "UTF8_STRING", False)
#else
#define TEXT_FORMAT XA_STRING
#endif
/* Get any application owned window handle for clipboard association */
static Window
GetWindow(_THIS)
{
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
/* We create an unmapped window that exists just to manage the clipboard,
since X11 selection data is tied to a specific window and dies with it.
We create the window on demand, so apps that don't use the clipboard
don't have to keep an unnecessary resource around. */
if (data->clipboard_window == None) {
Display *dpy = data->display;
Window parent = RootWindow(dpy, DefaultScreen(dpy));
XSetWindowAttributes xattr;
data->clipboard_window = X11_XCreateWindow(dpy, parent, -10, -10, 1, 1, 0,
CopyFromParent, InputOnly,
CopyFromParent, 0, &xattr);
X11_XFlush(data->display);
}
return data->clipboard_window;
}
/* We use our own cut-buffer for intermediate storage instead of
XA_CUT_BUFFER0 because their use isn't really defined for holding UTF8. */
Atom
X11_GetSDLCutBufferClipboardType(Display *display)
{
return X11_XInternAtom(display, "SDL_CUTBUFFER", False);
}
int
X11_SetClipboardText(_THIS, const char *text)
{
Display *display = ((SDL_VideoData *) _this->driverdata)->display;
Atom format;
Window window;
Atom XA_CLIPBOARD = X11_XInternAtom(display, "CLIPBOARD", 0);
/* Get the SDL window that will own the selection */
window = GetWindow(_this);
if (window == None) {
return SDL_SetError("Couldn't find a window to own the selection");
}
/* Save the selection on the root window */
format = TEXT_FORMAT;
X11_XChangeProperty(display, DefaultRootWindow(display),
X11_GetSDLCutBufferClipboardType(display), format, 8, PropModeReplace,
(const unsigned char *)text, SDL_strlen(text));
if (XA_CLIPBOARD != None &&
X11_XGetSelectionOwner(display, XA_CLIPBOARD) != window) {
X11_XSetSelectionOwner(display, XA_CLIPBOARD, window, CurrentTime);
}
if (X11_XGetSelectionOwner(display, XA_PRIMARY) != window) {
X11_XSetSelectionOwner(display, XA_PRIMARY, window, CurrentTime);
}
return 0;
}
char *
X11_GetClipboardText(_THIS)
{
SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
Display *display = videodata->display;
Atom format;
Window window;
Window owner;
Atom selection;
Atom seln_type;
int seln_format;
unsigned long nbytes;
unsigned long overflow;
unsigned char *src;
char *text;
Uint32 waitStart;
Uint32 waitElapsed;
Atom XA_CLIPBOARD = X11_XInternAtom(display, "CLIPBOARD", 0);
if (XA_CLIPBOARD == None) {
SDL_SetError("Couldn't access X clipboard");
return SDL_strdup("");
}
text = NULL;
/* Get the window that holds the selection */
window = GetWindow(_this);
format = TEXT_FORMAT;
owner = X11_XGetSelectionOwner(display, XA_CLIPBOARD);
if (owner == None) {
/* Fall back to ancient X10 cut-buffers which do not support UTF8 strings*/
owner = DefaultRootWindow(display);
selection = XA_CUT_BUFFER0;
format = XA_STRING;
} else if (owner == window) {
owner = DefaultRootWindow(display);
selection = X11_GetSDLCutBufferClipboardType(display);
} else {
/* Request that the selection owner copy the data to our window */
owner = window;
selection = X11_XInternAtom(display, "SDL_SELECTION", False);
X11_XConvertSelection(display, XA_CLIPBOARD, format, selection, owner,
CurrentTime);
/* When using synergy on Linux and when data has been put in the clipboard
on the remote (Windows anyway) machine then selection_waiting may never
be set to False. Time out after a while. */
waitStart = SDL_GetTicks();
videodata->selection_waiting = SDL_TRUE;
while (videodata->selection_waiting) {
SDL_PumpEvents();
waitElapsed = SDL_GetTicks() - waitStart;
/* Wait one second for a clipboard response. */
if (waitElapsed > 1000) {
videodata->selection_waiting = SDL_FALSE;
SDL_SetError("Clipboard timeout");
/* We need to set the clipboard text so that next time we won't
timeout, otherwise we will hang on every call to this function. */
X11_SetClipboardText(_this, "");
return SDL_strdup("");
}
}
}
if (X11_XGetWindowProperty(display, owner, selection, 0, INT_MAX/4, False,
format, &seln_type, &seln_format, &nbytes, &overflow, &src)
== Success) {
if (seln_type == format) {
text = (char *)SDL_malloc(nbytes+1);
if (text) {
SDL_memcpy(text, src, nbytes);
text[nbytes] = '\0';
}
}
X11_XFree(src);
}
if (!text) {
text = SDL_strdup("");
}
return text;
}
SDL_bool
X11_HasClipboardText(_THIS)
{
SDL_bool result = SDL_FALSE;
char *text = X11_GetClipboardText(_this);
if (text) {
result = text[0] != '\0' ? SDL_TRUE : SDL_FALSE;
SDL_free(text);
}
return result;
}
#endif /* SDL_VIDEO_DRIVER_X11 */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11clipboard.c | C | apache-2.0 | 6,741 |
/*
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_x11clipboard_h_
#define SDL_x11clipboard_h_
extern int X11_SetClipboardText(_THIS, const char *text);
extern char *X11_GetClipboardText(_THIS);
extern SDL_bool X11_HasClipboardText(_THIS);
extern Atom X11_GetSDLCutBufferClipboardType(Display *display);
#endif /* SDL_x11clipboard_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11clipboard.h | C | apache-2.0 | 1,308 |
/*
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_X11
#define DEBUG_DYNAMIC_X11 0
#include "SDL_x11dyn.h"
#if DEBUG_DYNAMIC_X11
#include <stdio.h>
#endif
#ifdef SDL_VIDEO_DRIVER_X11_DYNAMIC
#include "SDL_name.h"
#include "SDL_loadso.h"
typedef struct
{
void *lib;
const char *libname;
} x11dynlib;
#ifndef SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT
#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT NULL
#endif
#ifndef SDL_VIDEO_DRIVER_X11_DYNAMIC_XCURSOR
#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XCURSOR NULL
#endif
#ifndef SDL_VIDEO_DRIVER_X11_DYNAMIC_XINERAMA
#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XINERAMA NULL
#endif
#ifndef SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2
#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2 NULL
#endif
#ifndef SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR
#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR NULL
#endif
#ifndef SDL_VIDEO_DRIVER_X11_DYNAMIC_XSS
#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XSS NULL
#endif
#ifndef SDL_VIDEO_DRIVER_X11_DYNAMIC_XVIDMODE
#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XVIDMODE NULL
#endif
static x11dynlib x11libs[] = {
{NULL, SDL_VIDEO_DRIVER_X11_DYNAMIC},
{NULL, SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT},
{NULL, SDL_VIDEO_DRIVER_X11_DYNAMIC_XCURSOR},
{NULL, SDL_VIDEO_DRIVER_X11_DYNAMIC_XINERAMA},
{NULL, SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2},
{NULL, SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR},
{NULL, SDL_VIDEO_DRIVER_X11_DYNAMIC_XSS},
{NULL, SDL_VIDEO_DRIVER_X11_DYNAMIC_XVIDMODE}
};
static void *
X11_GetSym(const char *fnname, int *pHasModule)
{
int i;
void *fn = NULL;
for (i = 0; i < SDL_TABLESIZE(x11libs); i++) {
if (x11libs[i].lib != NULL) {
fn = SDL_LoadFunction(x11libs[i].lib, fnname);
if (fn != NULL)
break;
}
}
#if DEBUG_DYNAMIC_X11
if (fn != NULL)
printf("X11: Found '%s' in %s (%p)\n", fnname, x11libs[i].libname, fn);
else
printf("X11: Symbol '%s' NOT FOUND!\n", fnname);
#endif
if (fn == NULL)
*pHasModule = 0; /* kill this module. */
return fn;
}
#endif /* SDL_VIDEO_DRIVER_X11_DYNAMIC */
/* Define all the function pointers and wrappers... */
#define SDL_X11_SYM(rc,fn,params,args,ret) SDL_DYNX11FN_##fn X11_##fn = NULL;
#include "SDL_x11sym.h"
/* Annoying varargs entry point... */
#ifdef X_HAVE_UTF8_STRING
SDL_DYNX11FN_XCreateIC X11_XCreateIC = NULL;
SDL_DYNX11FN_XGetICValues X11_XGetICValues = NULL;
#endif
/* These SDL_X11_HAVE_* flags are here whether you have dynamic X11 or not. */
#define SDL_X11_MODULE(modname) int SDL_X11_HAVE_##modname = 0;
#include "SDL_x11sym.h"
static int x11_load_refcount = 0;
void
SDL_X11_UnloadSymbols(void)
{
/* Don't actually unload if more than one module is using the libs... */
if (x11_load_refcount > 0) {
if (--x11_load_refcount == 0) {
int i;
/* set all the function pointers to NULL. */
#define SDL_X11_MODULE(modname) SDL_X11_HAVE_##modname = 0;
#define SDL_X11_SYM(rc,fn,params,args,ret) X11_##fn = NULL;
#include "SDL_x11sym.h"
#ifdef X_HAVE_UTF8_STRING
X11_XCreateIC = NULL;
X11_XGetICValues = NULL;
#endif
#ifdef SDL_VIDEO_DRIVER_X11_DYNAMIC
for (i = 0; i < SDL_TABLESIZE(x11libs); i++) {
if (x11libs[i].lib != NULL) {
SDL_UnloadObject(x11libs[i].lib);
x11libs[i].lib = NULL;
}
}
#endif
}
}
}
/* returns non-zero if all needed symbols were loaded. */
int
SDL_X11_LoadSymbols(void)
{
int rc = 1; /* always succeed if not using Dynamic X11 stuff. */
/* deal with multiple modules (dga, x11, etc) needing these symbols... */
if (x11_load_refcount++ == 0) {
#ifdef SDL_VIDEO_DRIVER_X11_DYNAMIC
int i;
int *thismod = NULL;
for (i = 0; i < SDL_TABLESIZE(x11libs); i++) {
if (x11libs[i].libname != NULL) {
x11libs[i].lib = SDL_LoadObject(x11libs[i].libname);
}
}
#define SDL_X11_MODULE(modname) SDL_X11_HAVE_##modname = 1; /* default yes */
#include "SDL_x11sym.h"
#define SDL_X11_MODULE(modname) thismod = &SDL_X11_HAVE_##modname;
#define SDL_X11_SYM(a,fn,x,y,z) X11_##fn = (SDL_DYNX11FN_##fn) X11_GetSym(#fn,thismod);
#include "SDL_x11sym.h"
#ifdef X_HAVE_UTF8_STRING
X11_XCreateIC = (SDL_DYNX11FN_XCreateIC)
X11_GetSym("XCreateIC", &SDL_X11_HAVE_UTF8);
X11_XGetICValues = (SDL_DYNX11FN_XGetICValues)
X11_GetSym("XGetICValues", &SDL_X11_HAVE_UTF8);
#endif
if (SDL_X11_HAVE_BASEXLIB) {
/* all required symbols loaded. */
SDL_ClearError();
} else {
/* in case something got loaded... */
SDL_X11_UnloadSymbols();
rc = 0;
}
#else /* no dynamic X11 */
#define SDL_X11_MODULE(modname) SDL_X11_HAVE_##modname = 1; /* default yes */
#define SDL_X11_SYM(a,fn,x,y,z) X11_##fn = (SDL_DYNX11FN_##fn) fn;
#include "SDL_x11sym.h"
#ifdef X_HAVE_UTF8_STRING
X11_XCreateIC = XCreateIC;
X11_XGetICValues = XGetICValues;
#endif
#endif
}
return rc;
}
#endif /* SDL_VIDEO_DRIVER_X11 */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11dyn.c | C | apache-2.0 | 6,142 |
/*
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_x11dyn_h_
#define SDL_x11dyn_h_
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#if SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM
#include <X11/XKBlib.h>
#endif
/* Apparently some X11 systems can't include this multiple times... */
#ifndef SDL_INCLUDED_XLIBINT_H
#define SDL_INCLUDED_XLIBINT_H 1
#include <X11/Xlibint.h>
#endif
#include <X11/Xproto.h>
#include <X11/extensions/Xext.h>
#include <X11/extensions/extutil.h>
#ifndef NO_SHARED_MEMORY
#include <sys/ipc.h>
#include <sys/shm.h>
#include <X11/extensions/XShm.h>
#endif
#if SDL_VIDEO_DRIVER_X11_XCURSOR
#include <X11/Xcursor/Xcursor.h>
#endif
#if SDL_VIDEO_DRIVER_X11_XDBE
#include <X11/extensions/Xdbe.h>
#endif
#if SDL_VIDEO_DRIVER_X11_XINERAMA
#include <X11/extensions/Xinerama.h>
#endif
#if SDL_VIDEO_DRIVER_X11_XINPUT2
#include <X11/extensions/XInput2.h>
#endif
#if SDL_VIDEO_DRIVER_X11_XRANDR
#include <X11/extensions/Xrandr.h>
#endif
#if SDL_VIDEO_DRIVER_X11_XSCRNSAVER
#include <X11/extensions/scrnsaver.h>
#endif
#if SDL_VIDEO_DRIVER_X11_XSHAPE
#include <X11/extensions/shape.h>
#endif
#if SDL_VIDEO_DRIVER_X11_XVIDMODE
#include <X11/extensions/xf86vmode.h>
#endif
#ifdef __cplusplus
extern "C"
{
#endif
/* evil function signatures... */
typedef Bool(*SDL_X11_XESetWireToEventRetType) (Display *, XEvent *, xEvent *);
typedef int (*SDL_X11_XSynchronizeRetType) (Display *);
typedef Status(*SDL_X11_XESetEventToWireRetType) (Display *, XEvent *, xEvent *);
int SDL_X11_LoadSymbols(void);
void SDL_X11_UnloadSymbols(void);
/* Declare all the function pointers and wrappers... */
#define SDL_X11_SYM(rc,fn,params,args,ret) \
typedef rc (*SDL_DYNX11FN_##fn) params; \
extern SDL_DYNX11FN_##fn X11_##fn;
#include "SDL_x11sym.h"
/* Annoying varargs entry point... */
#ifdef X_HAVE_UTF8_STRING
typedef XIC(*SDL_DYNX11FN_XCreateIC) (XIM,...);
typedef char *(*SDL_DYNX11FN_XGetICValues) (XIC, ...);
extern SDL_DYNX11FN_XCreateIC X11_XCreateIC;
extern SDL_DYNX11FN_XGetICValues X11_XGetICValues;
#endif
/* These SDL_X11_HAVE_* flags are here whether you have dynamic X11 or not. */
#define SDL_X11_MODULE(modname) extern int SDL_X11_HAVE_##modname;
#include "SDL_x11sym.h"
#ifdef __cplusplus
}
#endif
#endif /* !defined SDL_x11dyn_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11dyn.h | C | apache-2.0 | 3,278 |
/*
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_X11
#include <sys/types.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h>
#include <limits.h> /* For INT_MAX */
#include "SDL_x11video.h"
#include "SDL_x11touch.h"
#include "SDL_x11xinput2.h"
#include "../../core/unix/SDL_poll.h"
#include "../../events/SDL_events_c.h"
#include "../../events/SDL_mouse_c.h"
#include "../../events/SDL_touch_c.h"
#include "SDL_hints.h"
#include "SDL_timer.h"
#include "SDL_syswm.h"
#include "SDL_assert.h"
#include <stdio.h>
/*#define DEBUG_XEVENTS*/
#ifndef _NET_WM_MOVERESIZE_SIZE_TOPLEFT
#define _NET_WM_MOVERESIZE_SIZE_TOPLEFT 0
#endif
#ifndef _NET_WM_MOVERESIZE_SIZE_TOP
#define _NET_WM_MOVERESIZE_SIZE_TOP 1
#endif
#ifndef _NET_WM_MOVERESIZE_SIZE_TOPRIGHT
#define _NET_WM_MOVERESIZE_SIZE_TOPRIGHT 2
#endif
#ifndef _NET_WM_MOVERESIZE_SIZE_RIGHT
#define _NET_WM_MOVERESIZE_SIZE_RIGHT 3
#endif
#ifndef _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT
#define _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT 4
#endif
#ifndef _NET_WM_MOVERESIZE_SIZE_BOTTOM
#define _NET_WM_MOVERESIZE_SIZE_BOTTOM 5
#endif
#ifndef _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT
#define _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT 6
#endif
#ifndef _NET_WM_MOVERESIZE_SIZE_LEFT
#define _NET_WM_MOVERESIZE_SIZE_LEFT 7
#endif
#ifndef _NET_WM_MOVERESIZE_MOVE
#define _NET_WM_MOVERESIZE_MOVE 8
#endif
typedef struct {
unsigned char *data;
int format, count;
Atom type;
} SDL_x11Prop;
/* Reads property
Must call X11_XFree on results
*/
static void X11_ReadProperty(SDL_x11Prop *p, Display *disp, Window w, Atom prop)
{
unsigned char *ret=NULL;
Atom type;
int fmt;
unsigned long count;
unsigned long bytes_left;
int bytes_fetch = 0;
do {
if (ret != 0) X11_XFree(ret);
X11_XGetWindowProperty(disp, w, prop, 0, bytes_fetch, False, AnyPropertyType, &type, &fmt, &count, &bytes_left, &ret);
bytes_fetch += bytes_left;
} while (bytes_left != 0);
p->data=ret;
p->format=fmt;
p->count=count;
p->type=type;
}
/* Find text-uri-list in a list of targets and return it's atom
if available, else return None */
static Atom X11_PickTarget(Display *disp, Atom list[], int list_count)
{
Atom request = None;
char *name;
int i;
for (i=0; i < list_count && request == None; i++) {
name = X11_XGetAtomName(disp, list[i]);
if ((SDL_strcmp("text/uri-list", name) == 0) || (SDL_strcmp("text/plain", name) == 0)) {
request = list[i];
}
X11_XFree(name);
}
return request;
}
/* Wrapper for X11_PickTarget for a maximum of three targets, a special
case in the Xdnd protocol */
static Atom X11_PickTargetFromAtoms(Display *disp, Atom a0, Atom a1, Atom a2)
{
int count=0;
Atom atom[3];
if (a0 != None) atom[count++] = a0;
if (a1 != None) atom[count++] = a1;
if (a2 != None) atom[count++] = a2;
return X11_PickTarget(disp, atom, count);
}
struct KeyRepeatCheckData
{
XEvent *event;
SDL_bool found;
};
static Bool X11_KeyRepeatCheckIfEvent(Display *display, XEvent *chkev,
XPointer arg)
{
struct KeyRepeatCheckData *d = (struct KeyRepeatCheckData *) arg;
if (chkev->type == KeyPress &&
chkev->xkey.keycode == d->event->xkey.keycode &&
chkev->xkey.time - d->event->xkey.time < 2)
d->found = SDL_TRUE;
return False;
}
/* Check to see if this is a repeated key.
(idea shamelessly lifted from GII -- thanks guys! :)
*/
static SDL_bool X11_KeyRepeat(Display *display, XEvent *event)
{
XEvent dummyev;
struct KeyRepeatCheckData d;
d.event = event;
d.found = SDL_FALSE;
if (X11_XPending(display))
X11_XCheckIfEvent(display, &dummyev, X11_KeyRepeatCheckIfEvent,
(XPointer) &d);
return d.found;
}
static SDL_bool
X11_IsWheelEvent(Display * display,XEvent * event,int * xticks,int * yticks)
{
/* according to the xlib docs, no specific mouse wheel events exist.
However, the defacto standard is that the vertical wheel is X buttons
4 (up) and 5 (down) and a horizontal wheel is 6 (left) and 7 (right). */
/* Xlib defines "Button1" through 5, so we just use literals here. */
switch (event->xbutton.button) {
case 4: *yticks = 1; return SDL_TRUE;
case 5: *yticks = -1; return SDL_TRUE;
case 6: *xticks = 1; return SDL_TRUE;
case 7: *xticks = -1; return SDL_TRUE;
default: break;
}
return SDL_FALSE;
}
/* Decodes URI escape sequences in string buf of len bytes
(excluding the terminating NULL byte) in-place. Since
URI-encoded characters take three times the space of
normal characters, this should not be an issue.
Returns the number of decoded bytes that wound up in
the buffer, excluding the terminating NULL byte.
The buffer is guaranteed to be NULL-terminated but
may contain embedded NULL bytes.
On error, -1 is returned.
*/
static int X11_URIDecode(char *buf, int len) {
int ri, wi, di;
char decode = '\0';
if (buf == NULL || len < 0) {
errno = EINVAL;
return -1;
}
if (len == 0) {
len = SDL_strlen(buf);
}
for (ri = 0, wi = 0, di = 0; ri < len && wi < len; ri += 1) {
if (di == 0) {
/* start decoding */
if (buf[ri] == '%') {
decode = '\0';
di += 1;
continue;
}
/* normal write */
buf[wi] = buf[ri];
wi += 1;
continue;
} else if (di == 1 || di == 2) {
char off = '\0';
char isa = buf[ri] >= 'a' && buf[ri] <= 'f';
char isA = buf[ri] >= 'A' && buf[ri] <= 'F';
char isn = buf[ri] >= '0' && buf[ri] <= '9';
if (!(isa || isA || isn)) {
/* not a hexadecimal */
int sri;
for (sri = ri - di; sri <= ri; sri += 1) {
buf[wi] = buf[sri];
wi += 1;
}
di = 0;
continue;
}
/* itsy bitsy magicsy */
if (isn) {
off = 0 - '0';
} else if (isa) {
off = 10 - 'a';
} else if (isA) {
off = 10 - 'A';
}
decode |= (buf[ri] + off) << (2 - di) * 4;
if (di == 2) {
buf[wi] = decode;
wi += 1;
di = 0;
} else {
di += 1;
}
continue;
}
}
buf[wi] = '\0';
return wi;
}
/* Convert URI to local filename
return filename if possible, else NULL
*/
static char* X11_URIToLocal(char* uri) {
char *file = NULL;
SDL_bool local;
if (memcmp(uri,"file:/",6) == 0) uri += 6; /* local file? */
else if (strstr(uri,":/") != NULL) return file; /* wrong scheme */
local = uri[0] != '/' || (uri[0] != '\0' && uri[1] == '/');
/* got a hostname? */
if (!local && uri[0] == '/' && uri[2] != '/') {
char* hostname_end = strchr(uri+1, '/');
if (hostname_end != NULL) {
char hostname[ 257 ];
if (gethostname(hostname, 255) == 0) {
hostname[ 256 ] = '\0';
if (memcmp(uri+1, hostname, hostname_end - (uri+1)) == 0) {
uri = hostname_end + 1;
local = SDL_TRUE;
}
}
}
}
if (local) {
file = uri;
/* Convert URI escape sequences to real characters */
X11_URIDecode(file, 0);
if (uri[1] == '/') {
file++;
} else {
file--;
}
}
return file;
}
#if SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS
static void X11_HandleGenericEvent(SDL_VideoData *videodata, XEvent *xev)
{
/* event is a union, so cookie == &event, but this is type safe. */
XGenericEventCookie *cookie = &xev->xcookie;
if (X11_XGetEventData(videodata->display, cookie)) {
X11_HandleXinput2Event(videodata, cookie);
/* Send a SDL_SYSWMEVENT if the application wants them.
* Since event data is only available until XFreeEventData is called,
* the *only* way for an application to access it is to register an event filter/watcher
* and do all the processing on the SDL_SYSWMEVENT inside the callback. */
if (SDL_GetEventState(SDL_SYSWMEVENT) == SDL_ENABLE) {
SDL_SysWMmsg wmmsg;
SDL_VERSION(&wmmsg.version);
wmmsg.subsystem = SDL_SYSWM_X11;
wmmsg.msg.x11.event = *xev;
SDL_SendSysWMEvent(&wmmsg);
}
X11_XFreeEventData(videodata->display, cookie);
}
}
#endif /* SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS */
static unsigned
X11_GetNumLockModifierMask(_THIS)
{
SDL_VideoData *viddata = (SDL_VideoData *) _this->driverdata;
Display *display = viddata->display;
unsigned num_mask = 0;
int i, j;
XModifierKeymap *xmods;
unsigned n;
xmods = X11_XGetModifierMapping(display);
n = xmods->max_keypermod;
for(i = 3; i < 8; i++) {
for(j = 0; j < n; j++) {
KeyCode kc = xmods->modifiermap[i * n + j];
if (viddata->key_layout[kc] == SDL_SCANCODE_NUMLOCKCLEAR) {
num_mask = 1 << i;
break;
}
}
}
X11_XFreeModifiermap(xmods);
return num_mask;
}
static void
X11_ReconcileKeyboardState(_THIS)
{
SDL_VideoData *viddata = (SDL_VideoData *) _this->driverdata;
Display *display = viddata->display;
char keys[32];
int keycode;
Window junk_window;
int x, y;
unsigned int mask;
const Uint8 *keyboardState;
X11_XQueryKeymap(display, keys);
/* Sync up the keyboard modifier state */
if (X11_XQueryPointer(display, DefaultRootWindow(display), &junk_window, &junk_window, &x, &y, &x, &y, &mask)) {
SDL_ToggleModState(KMOD_CAPS, (mask & LockMask) != 0);
SDL_ToggleModState(KMOD_NUM, (mask & X11_GetNumLockModifierMask(_this)) != 0);
}
keyboardState = SDL_GetKeyboardState(0);
for (keycode = 0; keycode < 256; ++keycode) {
SDL_Scancode scancode = viddata->key_layout[keycode];
SDL_bool x11KeyPressed = (keys[keycode / 8] & (1 << (keycode % 8))) != 0;
SDL_bool sdlKeyPressed = keyboardState[scancode] == SDL_PRESSED;
if (x11KeyPressed && !sdlKeyPressed) {
SDL_SendKeyboardKey(SDL_PRESSED, scancode);
} else if (!x11KeyPressed && sdlKeyPressed) {
SDL_SendKeyboardKey(SDL_RELEASED, scancode);
}
}
}
static void
X11_DispatchFocusIn(_THIS, SDL_WindowData *data)
{
#ifdef DEBUG_XEVENTS
printf("window %p: Dispatching FocusIn\n", data);
#endif
SDL_SetKeyboardFocus(data->window);
X11_ReconcileKeyboardState(_this);
#ifdef X_HAVE_UTF8_STRING
if (data->ic) {
X11_XSetICFocus(data->ic);
}
#endif
#ifdef SDL_USE_IME
SDL_IME_SetFocus(SDL_TRUE);
#endif
}
static void
X11_DispatchFocusOut(_THIS, SDL_WindowData *data)
{
#ifdef DEBUG_XEVENTS
printf("window %p: Dispatching FocusOut\n", data);
#endif
/* If another window has already processed a focus in, then don't try to
* remove focus here. Doing so will incorrectly remove focus from that
* window, and the focus lost event for this window will have already
* been dispatched anyway. */
if (data->window == SDL_GetKeyboardFocus()) {
SDL_SetKeyboardFocus(NULL);
}
#ifdef X_HAVE_UTF8_STRING
if (data->ic) {
X11_XUnsetICFocus(data->ic);
}
#endif
#ifdef SDL_USE_IME
SDL_IME_SetFocus(SDL_FALSE);
#endif
}
static void
X11_DispatchMapNotify(SDL_WindowData *data)
{
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_RESTORED, 0, 0);
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_SHOWN, 0, 0);
}
static void
X11_DispatchUnmapNotify(SDL_WindowData *data)
{
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_HIDDEN, 0, 0);
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_MINIMIZED, 0, 0);
}
static void
InitiateWindowMove(_THIS, const SDL_WindowData *data, const SDL_Point *point)
{
SDL_VideoData *viddata = (SDL_VideoData *) _this->driverdata;
SDL_Window* window = data->window;
Display *display = viddata->display;
XEvent evt;
/* !!! FIXME: we need to regrab this if necessary when the drag is done. */
X11_XUngrabPointer(display, 0L);
X11_XFlush(display);
evt.xclient.type = ClientMessage;
evt.xclient.window = data->xwindow;
evt.xclient.message_type = X11_XInternAtom(display, "_NET_WM_MOVERESIZE", True);
evt.xclient.format = 32;
evt.xclient.data.l[0] = window->x + point->x;
evt.xclient.data.l[1] = window->y + point->y;
evt.xclient.data.l[2] = _NET_WM_MOVERESIZE_MOVE;
evt.xclient.data.l[3] = Button1;
evt.xclient.data.l[4] = 0;
X11_XSendEvent(display, DefaultRootWindow(display), False, SubstructureRedirectMask | SubstructureNotifyMask, &evt);
X11_XSync(display, 0);
}
static void
InitiateWindowResize(_THIS, const SDL_WindowData *data, const SDL_Point *point, int direction)
{
SDL_VideoData *viddata = (SDL_VideoData *) _this->driverdata;
SDL_Window* window = data->window;
Display *display = viddata->display;
XEvent evt;
if (direction < _NET_WM_MOVERESIZE_SIZE_TOPLEFT || direction > _NET_WM_MOVERESIZE_SIZE_LEFT)
return;
/* !!! FIXME: we need to regrab this if necessary when the drag is done. */
X11_XUngrabPointer(display, 0L);
X11_XFlush(display);
evt.xclient.type = ClientMessage;
evt.xclient.window = data->xwindow;
evt.xclient.message_type = X11_XInternAtom(display, "_NET_WM_MOVERESIZE", True);
evt.xclient.format = 32;
evt.xclient.data.l[0] = window->x + point->x;
evt.xclient.data.l[1] = window->y + point->y;
evt.xclient.data.l[2] = direction;
evt.xclient.data.l[3] = Button1;
evt.xclient.data.l[4] = 0;
X11_XSendEvent(display, DefaultRootWindow(display), False, SubstructureRedirectMask | SubstructureNotifyMask, &evt);
X11_XSync(display, 0);
}
static SDL_bool
ProcessHitTest(_THIS, const SDL_WindowData *data, const XEvent *xev)
{
SDL_Window *window = data->window;
if (window->hit_test) {
const SDL_Point point = { xev->xbutton.x, xev->xbutton.y };
const SDL_HitTestResult rc = window->hit_test(window, &point, window->hit_test_data);
static const int directions[] = {
_NET_WM_MOVERESIZE_SIZE_TOPLEFT, _NET_WM_MOVERESIZE_SIZE_TOP,
_NET_WM_MOVERESIZE_SIZE_TOPRIGHT, _NET_WM_MOVERESIZE_SIZE_RIGHT,
_NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT, _NET_WM_MOVERESIZE_SIZE_BOTTOM,
_NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT, _NET_WM_MOVERESIZE_SIZE_LEFT
};
switch (rc) {
case SDL_HITTEST_DRAGGABLE:
InitiateWindowMove(_this, data, &point);
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:
InitiateWindowResize(_this, data, &point, directions[rc - SDL_HITTEST_RESIZE_TOPLEFT]);
return SDL_TRUE;
default: return SDL_FALSE;
}
}
return SDL_FALSE;
}
static void
X11_UpdateUserTime(SDL_WindowData *data, const unsigned long latest)
{
if (latest && (latest != data->user_time)) {
SDL_VideoData *videodata = data->videodata;
Display *display = videodata->display;
X11_XChangeProperty(display, data->xwindow, videodata->_NET_WM_USER_TIME,
XA_CARDINAL, 32, PropModeReplace,
(const unsigned char *) &latest, 1);
#ifdef DEBUG_XEVENTS
printf("window %p: updating _NET_WM_USER_TIME to %lu\n", data, latest);
#endif
data->user_time = latest;
}
}
static void
X11_HandleClipboardEvent(_THIS, const XEvent *xevent)
{
SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
Display *display = videodata->display;
SDL_assert(videodata->clipboard_window != None);
SDL_assert(xevent->xany.window == videodata->clipboard_window);
switch (xevent->type) {
/* Copy the selection from our own CUTBUFFER to the requested property */
case SelectionRequest: {
const XSelectionRequestEvent *req = &xevent->xselectionrequest;
XEvent sevent;
int seln_format;
unsigned long nbytes;
unsigned long overflow;
unsigned char *seln_data;
#ifdef DEBUG_XEVENTS
printf("window CLIPBOARD: SelectionRequest (requestor = %ld, target = %ld)\n",
req->requestor, req->target);
#endif
SDL_zero(sevent);
sevent.xany.type = SelectionNotify;
sevent.xselection.selection = req->selection;
sevent.xselection.target = None;
sevent.xselection.property = None; /* tell them no by default */
sevent.xselection.requestor = req->requestor;
sevent.xselection.time = req->time;
/* !!! FIXME: We were probably storing this on the root window
because an SDL window might go away...? but we don't have to do
this now (or ever, really). */
if (X11_XGetWindowProperty(display, DefaultRootWindow(display),
X11_GetSDLCutBufferClipboardType(display), 0, INT_MAX/4, False, req->target,
&sevent.xselection.target, &seln_format, &nbytes,
&overflow, &seln_data) == Success) {
/* !!! FIXME: cache atoms */
Atom XA_TARGETS = X11_XInternAtom(display, "TARGETS", 0);
if (sevent.xselection.target == req->target) {
X11_XChangeProperty(display, req->requestor, req->property,
sevent.xselection.target, seln_format, PropModeReplace,
seln_data, nbytes);
sevent.xselection.property = req->property;
} else if (XA_TARGETS == req->target) {
Atom SupportedFormats[] = { XA_TARGETS, sevent.xselection.target };
X11_XChangeProperty(display, req->requestor, req->property,
XA_ATOM, 32, PropModeReplace,
(unsigned char*)SupportedFormats,
SDL_arraysize(SupportedFormats));
sevent.xselection.property = req->property;
sevent.xselection.target = XA_TARGETS;
}
X11_XFree(seln_data);
}
X11_XSendEvent(display, req->requestor, False, 0, &sevent);
X11_XSync(display, False);
}
break;
case SelectionNotify: {
#ifdef DEBUG_XEVENTS
printf("window CLIPBOARD: SelectionNotify (requestor = %ld, target = %ld)\n",
xevent->xselection.requestor, xevent->xselection.target);
#endif
videodata->selection_waiting = SDL_FALSE;
}
break;
case SelectionClear: {
/* !!! FIXME: cache atoms */
Atom XA_CLIPBOARD = X11_XInternAtom(display, "CLIPBOARD", 0);
#ifdef DEBUG_XEVENTS
printf("window CLIPBOARD: SelectionClear (requestor = %ld, target = %ld)\n",
xevent->xselection.requestor, xevent->xselection.target);
#endif
if (xevent->xselectionclear.selection == XA_PRIMARY ||
(XA_CLIPBOARD != None && xevent->xselectionclear.selection == XA_CLIPBOARD)) {
SDL_SendClipboardUpdate();
}
}
break;
}
}
static void
X11_DispatchEvent(_THIS)
{
SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
Display *display;
SDL_WindowData *data;
XEvent xevent;
int orig_event_type;
KeyCode orig_keycode;
XClientMessageEvent m;
int i;
if (!videodata) {
return;
}
display = videodata->display;
SDL_zero(xevent); /* valgrind fix. --ryan. */
X11_XNextEvent(display, &xevent);
/* Save the original keycode for dead keys, which are filtered out by
the XFilterEvent() call below.
*/
orig_event_type = xevent.type;
if (orig_event_type == KeyPress || orig_event_type == KeyRelease) {
orig_keycode = xevent.xkey.keycode;
} else {
orig_keycode = 0;
}
/* filter events catchs XIM events and sends them to the correct handler */
if (X11_XFilterEvent(&xevent, None) == True) {
#if 0
printf("Filtered event type = %d display = %d window = %d\n",
xevent.type, xevent.xany.display, xevent.xany.window);
#endif
/* Make sure dead key press/release events are sent */
/* But only if we're using one of the DBus IMEs, otherwise
some XIM IMEs will generate duplicate events */
if (orig_keycode) {
#if defined(HAVE_IBUS_IBUS_H) || defined(HAVE_FCITX)
SDL_Scancode scancode = videodata->key_layout[orig_keycode];
videodata->filter_code = orig_keycode;
videodata->filter_time = xevent.xkey.time;
if (orig_event_type == KeyPress) {
SDL_SendKeyboardKey(SDL_PRESSED, scancode);
} else {
SDL_SendKeyboardKey(SDL_RELEASED, scancode);
}
#endif
}
return;
}
#if SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS
if(xevent.type == GenericEvent) {
X11_HandleGenericEvent(videodata, &xevent);
return;
}
#endif
/* 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_X11;
wmmsg.msg.x11.event = xevent;
SDL_SendSysWMEvent(&wmmsg);
}
#if 0
printf("type = %d display = %d window = %d\n",
xevent.type, xevent.xany.display, xevent.xany.window);
#endif
if ((videodata->clipboard_window != None) &&
(videodata->clipboard_window == xevent.xany.window)) {
X11_HandleClipboardEvent(_this, &xevent);
return;
}
data = NULL;
if (videodata && videodata->windowlist) {
for (i = 0; i < videodata->numwindows; ++i) {
if ((videodata->windowlist[i] != NULL) &&
(videodata->windowlist[i]->xwindow == xevent.xany.window)) {
data = videodata->windowlist[i];
break;
}
}
}
if (!data) {
/* The window for KeymapNotify, etc events is 0 */
if (xevent.type == KeymapNotify) {
if (SDL_GetKeyboardFocus() != NULL) {
X11_ReconcileKeyboardState(_this);
}
} else if (xevent.type == MappingNotify) {
/* Has the keyboard layout changed? */
const int request = xevent.xmapping.request;
#ifdef DEBUG_XEVENTS
printf("window %p: MappingNotify!\n", data);
#endif
if ((request == MappingKeyboard) || (request == MappingModifier)) {
X11_XRefreshKeyboardMapping(&xevent.xmapping);
}
X11_UpdateKeymap(_this);
SDL_SendKeymapChangedEvent();
}
return;
}
switch (xevent.type) {
/* Gaining mouse coverage? */
case EnterNotify:{
SDL_Mouse *mouse = SDL_GetMouse();
#ifdef DEBUG_XEVENTS
printf("window %p: EnterNotify! (%d,%d,%d)\n", data,
xevent.xcrossing.x,
xevent.xcrossing.y,
xevent.xcrossing.mode);
if (xevent.xcrossing.mode == NotifyGrab)
printf("Mode: NotifyGrab\n");
if (xevent.xcrossing.mode == NotifyUngrab)
printf("Mode: NotifyUngrab\n");
#endif
SDL_SetMouseFocus(data->window);
mouse->last_x = xevent.xcrossing.x;
mouse->last_y = xevent.xcrossing.y;
if (!mouse->relative_mode) {
SDL_SendMouseMotion(data->window, 0, 0, xevent.xcrossing.x, xevent.xcrossing.y);
}
}
break;
/* Losing mouse coverage? */
case LeaveNotify:{
#ifdef DEBUG_XEVENTS
printf("window %p: LeaveNotify! (%d,%d,%d)\n", data,
xevent.xcrossing.x,
xevent.xcrossing.y,
xevent.xcrossing.mode);
if (xevent.xcrossing.mode == NotifyGrab)
printf("Mode: NotifyGrab\n");
if (xevent.xcrossing.mode == NotifyUngrab)
printf("Mode: NotifyUngrab\n");
#endif
if (!SDL_GetMouse()->relative_mode) {
SDL_SendMouseMotion(data->window, 0, 0, xevent.xcrossing.x, xevent.xcrossing.y);
}
if (xevent.xcrossing.mode != NotifyGrab &&
xevent.xcrossing.mode != NotifyUngrab &&
xevent.xcrossing.detail != NotifyInferior) {
SDL_SetMouseFocus(NULL);
}
}
break;
/* Gaining input focus? */
case FocusIn:{
if (xevent.xfocus.mode == NotifyGrab || xevent.xfocus.mode == NotifyUngrab) {
/* Someone is handling a global hotkey, ignore it */
#ifdef DEBUG_XEVENTS
printf("window %p: FocusIn (NotifyGrab/NotifyUngrab, ignoring)\n", data);
#endif
break;
}
if (xevent.xfocus.detail == NotifyInferior || xevent.xfocus.detail == NotifyPointer) {
#ifdef DEBUG_XEVENTS
printf("window %p: FocusIn (NotifyInferior/NotifyPointer, ignoring)\n", data);
#endif
break;
}
#ifdef DEBUG_XEVENTS
printf("window %p: FocusIn!\n", data);
#endif
if (!videodata->last_mode_change_deadline) /* no recent mode changes */
{
data->pending_focus = PENDING_FOCUS_NONE;
data->pending_focus_time = 0;
X11_DispatchFocusIn(_this, data);
}
else
{
data->pending_focus = PENDING_FOCUS_IN;
data->pending_focus_time = SDL_GetTicks() + PENDING_FOCUS_TIME;
}
data->last_focus_event_time = SDL_GetTicks();
}
break;
/* Losing input focus? */
case FocusOut:{
if (xevent.xfocus.mode == NotifyGrab || xevent.xfocus.mode == NotifyUngrab) {
/* Someone is handling a global hotkey, ignore it */
#ifdef DEBUG_XEVENTS
printf("window %p: FocusOut (NotifyGrab/NotifyUngrab, ignoring)\n", data);
#endif
break;
}
if (xevent.xfocus.detail == NotifyInferior || xevent.xfocus.detail == NotifyPointer) {
/* We still have focus if a child gets focus. We also don't
care about the position of the pointer when the keyboard
focus changed. */
#ifdef DEBUG_XEVENTS
printf("window %p: FocusOut (NotifyInferior/NotifyPointer, ignoring)\n", data);
#endif
break;
}
#ifdef DEBUG_XEVENTS
printf("window %p: FocusOut!\n", data);
#endif
if (!videodata->last_mode_change_deadline) /* no recent mode changes */
{
data->pending_focus = PENDING_FOCUS_NONE;
data->pending_focus_time = 0;
X11_DispatchFocusOut(_this, data);
}
else
{
data->pending_focus = PENDING_FOCUS_OUT;
data->pending_focus_time = SDL_GetTicks() + PENDING_FOCUS_TIME;
}
}
break;
/* Key press? */
case KeyPress:{
KeyCode keycode = xevent.xkey.keycode;
KeySym keysym = NoSymbol;
char text[SDL_TEXTINPUTEVENT_TEXT_SIZE];
Status status = 0;
SDL_bool handled_by_ime = SDL_FALSE;
#ifdef DEBUG_XEVENTS
printf("window %p: KeyPress (X11 keycode = 0x%X)\n", data, xevent.xkey.keycode);
#endif
#if 1
if (videodata->key_layout[keycode] == SDL_SCANCODE_UNKNOWN && keycode) {
int min_keycode, max_keycode;
X11_XDisplayKeycodes(display, &min_keycode, &max_keycode);
keysym = X11_KeyCodeToSym(_this, keycode, xevent.xkey.state >> 13);
fprintf(stderr,
"The key you just pressed is not recognized by SDL. To help get this fixed, please report this to the SDL forums/mailing list <https://discourse.libsdl.org/> X11 KeyCode %d (%d), X11 KeySym 0x%lX (%s).\n",
keycode, keycode - min_keycode, keysym,
X11_XKeysymToString(keysym));
}
#endif
/* */
SDL_zeroa(text);
#ifdef X_HAVE_UTF8_STRING
if (data->ic) {
X11_Xutf8LookupString(data->ic, &xevent.xkey, text, sizeof(text),
&keysym, &status);
} else {
X11_XLookupString(&xevent.xkey, text, sizeof(text), &keysym, NULL);
}
#else
X11_XLookupString(&xevent.xkey, text, sizeof(text), &keysym, NULL);
#endif
#ifdef SDL_USE_IME
if(SDL_GetEventState(SDL_TEXTINPUT) == SDL_ENABLE){
handled_by_ime = SDL_IME_ProcessKeyEvent(keysym, keycode);
}
#endif
if (!handled_by_ime) {
/* Don't send the key if it looks like a duplicate of a filtered key sent by an IME */
if (xevent.xkey.keycode != videodata->filter_code || xevent.xkey.time != videodata->filter_time) {
SDL_SendKeyboardKey(SDL_PRESSED, videodata->key_layout[keycode]);
}
if(*text) {
SDL_SendKeyboardText(text);
}
}
X11_UpdateUserTime(data, xevent.xkey.time);
}
break;
/* Key release? */
case KeyRelease:{
KeyCode keycode = xevent.xkey.keycode;
#ifdef DEBUG_XEVENTS
printf("window %p: KeyRelease (X11 keycode = 0x%X)\n", data, xevent.xkey.keycode);
#endif
if (X11_KeyRepeat(display, &xevent)) {
/* We're about to get a repeated key down, ignore the key up */
break;
}
SDL_SendKeyboardKey(SDL_RELEASED, videodata->key_layout[keycode]);
}
break;
/* Have we been iconified? */
case UnmapNotify:{
#ifdef DEBUG_XEVENTS
printf("window %p: UnmapNotify!\n", data);
#endif
X11_DispatchUnmapNotify(data);
}
break;
/* Have we been restored? */
case MapNotify:{
#ifdef DEBUG_XEVENTS
printf("window %p: MapNotify!\n", data);
#endif
X11_DispatchMapNotify(data);
}
break;
/* Have we been resized or moved? */
case ConfigureNotify:{
#ifdef DEBUG_XEVENTS
printf("window %p: ConfigureNotify! (position: %d,%d, size: %dx%d)\n", data,
xevent.xconfigure.x, xevent.xconfigure.y,
xevent.xconfigure.width, xevent.xconfigure.height);
#endif
/* Real configure notify events are relative to the parent, synthetic events are absolute. */
if (!xevent.xconfigure.send_event) {
unsigned int NumChildren;
Window ChildReturn, Root, Parent;
Window * Children;
/* Translate these coodinates back to relative to root */
X11_XQueryTree(data->videodata->display, xevent.xconfigure.window, &Root, &Parent, &Children, &NumChildren);
X11_XTranslateCoordinates(xevent.xconfigure.display,
Parent, DefaultRootWindow(xevent.xconfigure.display),
xevent.xconfigure.x, xevent.xconfigure.y,
&xevent.xconfigure.x, &xevent.xconfigure.y,
&ChildReturn);
}
if (xevent.xconfigure.x != data->last_xconfigure.x ||
xevent.xconfigure.y != data->last_xconfigure.y) {
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_MOVED,
xevent.xconfigure.x, xevent.xconfigure.y);
#ifdef SDL_USE_IME
if(SDL_GetEventState(SDL_TEXTINPUT) == SDL_ENABLE){
/* Update IME candidate list position */
SDL_IME_UpdateTextRect(NULL);
}
#endif
}
if (xevent.xconfigure.width != data->last_xconfigure.width ||
xevent.xconfigure.height != data->last_xconfigure.height) {
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_RESIZED,
xevent.xconfigure.width,
xevent.xconfigure.height);
}
data->last_xconfigure = xevent.xconfigure;
}
break;
/* Have we been requested to quit (or another client message?) */
case ClientMessage:{
static int xdnd_version=0;
if (xevent.xclient.message_type == videodata->XdndEnter) {
SDL_bool use_list = xevent.xclient.data.l[1] & 1;
data->xdnd_source = xevent.xclient.data.l[0];
xdnd_version = (xevent.xclient.data.l[1] >> 24);
#ifdef DEBUG_XEVENTS
printf("XID of source window : %ld\n", data->xdnd_source);
printf("Protocol version to use : %d\n", xdnd_version);
printf("More then 3 data types : %d\n", (int) use_list);
#endif
if (use_list) {
/* fetch conversion targets */
SDL_x11Prop p;
X11_ReadProperty(&p, display, data->xdnd_source, videodata->XdndTypeList);
/* pick one */
data->xdnd_req = X11_PickTarget(display, (Atom*)p.data, p.count);
X11_XFree(p.data);
} else {
/* pick from list of three */
data->xdnd_req = X11_PickTargetFromAtoms(display, xevent.xclient.data.l[2], xevent.xclient.data.l[3], xevent.xclient.data.l[4]);
}
}
else if (xevent.xclient.message_type == videodata->XdndPosition) {
#ifdef DEBUG_XEVENTS
Atom act= videodata->XdndActionCopy;
if(xdnd_version >= 2) {
act = xevent.xclient.data.l[4];
}
printf("Action requested by user is : %s\n", X11_XGetAtomName(display , act));
#endif
/* reply with status */
memset(&m, 0, sizeof(XClientMessageEvent));
m.type = ClientMessage;
m.display = xevent.xclient.display;
m.window = xevent.xclient.data.l[0];
m.message_type = videodata->XdndStatus;
m.format=32;
m.data.l[0] = data->xwindow;
m.data.l[1] = (data->xdnd_req != None);
m.data.l[2] = 0; /* specify an empty rectangle */
m.data.l[3] = 0;
m.data.l[4] = videodata->XdndActionCopy; /* we only accept copying anyway */
X11_XSendEvent(display, xevent.xclient.data.l[0], False, NoEventMask, (XEvent*)&m);
X11_XFlush(display);
}
else if(xevent.xclient.message_type == videodata->XdndDrop) {
if (data->xdnd_req == None) {
/* say again - not interested! */
memset(&m, 0, sizeof(XClientMessageEvent));
m.type = ClientMessage;
m.display = xevent.xclient.display;
m.window = xevent.xclient.data.l[0];
m.message_type = videodata->XdndFinished;
m.format=32;
m.data.l[0] = data->xwindow;
m.data.l[1] = 0;
m.data.l[2] = None; /* fail! */
X11_XSendEvent(display, xevent.xclient.data.l[0], False, NoEventMask, (XEvent*)&m);
} else {
/* convert */
if(xdnd_version >= 1) {
X11_XConvertSelection(display, videodata->XdndSelection, data->xdnd_req, videodata->PRIMARY, data->xwindow, xevent.xclient.data.l[2]);
} else {
X11_XConvertSelection(display, videodata->XdndSelection, data->xdnd_req, videodata->PRIMARY, data->xwindow, CurrentTime);
}
}
}
else if ((xevent.xclient.message_type == videodata->WM_PROTOCOLS) &&
(xevent.xclient.format == 32) &&
(xevent.xclient.data.l[0] == videodata->_NET_WM_PING)) {
Window root = DefaultRootWindow(display);
#ifdef DEBUG_XEVENTS
printf("window %p: _NET_WM_PING\n", data);
#endif
xevent.xclient.window = root;
X11_XSendEvent(display, root, False, SubstructureRedirectMask | SubstructureNotifyMask, &xevent);
break;
}
else if ((xevent.xclient.message_type == videodata->WM_PROTOCOLS) &&
(xevent.xclient.format == 32) &&
(xevent.xclient.data.l[0] == videodata->WM_DELETE_WINDOW)) {
#ifdef DEBUG_XEVENTS
printf("window %p: WM_DELETE_WINDOW\n", data);
#endif
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_CLOSE, 0, 0);
break;
}
else if ((xevent.xclient.message_type == videodata->WM_PROTOCOLS) &&
(xevent.xclient.format == 32) &&
(xevent.xclient.data.l[0] == videodata->WM_TAKE_FOCUS)) {
#ifdef DEBUG_XEVENTS
printf("window %p: WM_TAKE_FOCUS\n", data);
#endif
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_TAKE_FOCUS, 0, 0);
break;
}
}
break;
/* Do we need to refresh ourselves? */
case Expose:{
#ifdef DEBUG_XEVENTS
printf("window %p: Expose (count = %d)\n", data, xevent.xexpose.count);
#endif
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_EXPOSED, 0, 0);
}
break;
case MotionNotify:{
SDL_Mouse *mouse = SDL_GetMouse();
if(!mouse->relative_mode || mouse->relative_mode_warp) {
#ifdef DEBUG_MOTION
printf("window %p: X11 motion: %d,%d\n", data, xevent.xmotion.x, xevent.xmotion.y);
#endif
SDL_SendMouseMotion(data->window, 0, 0, xevent.xmotion.x, xevent.xmotion.y);
}
}
break;
case ButtonPress:{
int xticks = 0, yticks = 0;
#ifdef DEBUG_XEVENTS
printf("window %p: ButtonPress (X11 button = %d)\n", data, xevent.xbutton.button);
#endif
if (X11_IsWheelEvent(display,&xevent,&xticks, &yticks)) {
SDL_SendMouseWheel(data->window, 0, (float) xticks, (float) yticks, SDL_MOUSEWHEEL_NORMAL);
} else {
SDL_bool ignore_click = SDL_FALSE;
int button = xevent.xbutton.button;
if(button == Button1) {
if (ProcessHitTest(_this, data, &xevent)) {
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_HIT_TEST, 0, 0);
break; /* don't pass this event on to app. */
}
}
else if(button > 7) {
/* X button values 4-7 are used for scrolling, so X1 is 8, X2 is 9, ...
=> subtract (8-SDL_BUTTON_X1) to get value SDL expects */
button -= (8-SDL_BUTTON_X1);
}
if (data->last_focus_event_time) {
const int X11_FOCUS_CLICK_TIMEOUT = 10;
if (!SDL_TICKS_PASSED(SDL_GetTicks(), data->last_focus_event_time + X11_FOCUS_CLICK_TIMEOUT)) {
ignore_click = !SDL_GetHintBoolean(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, SDL_FALSE);
}
data->last_focus_event_time = 0;
}
if (!ignore_click) {
SDL_SendMouseButton(data->window, 0, SDL_PRESSED, button);
}
}
X11_UpdateUserTime(data, xevent.xbutton.time);
}
break;
case ButtonRelease:{
int button = xevent.xbutton.button;
/* The X server sends a Release event for each Press for wheels. Ignore them. */
int xticks = 0, yticks = 0;
#ifdef DEBUG_XEVENTS
printf("window %p: ButtonRelease (X11 button = %d)\n", data, xevent.xbutton.button);
#endif
if (!X11_IsWheelEvent(display, &xevent, &xticks, &yticks)) {
if (button > 7) {
/* see explanation at case ButtonPress */
button -= (8-SDL_BUTTON_X1);
}
SDL_SendMouseButton(data->window, 0, SDL_RELEASED, button);
}
}
break;
case PropertyNotify:{
#ifdef DEBUG_XEVENTS
unsigned char *propdata;
int status, real_format;
Atom real_type;
unsigned long items_read, items_left;
char *name = X11_XGetAtomName(display, xevent.xproperty.atom);
if (name) {
printf("window %p: PropertyNotify: %s %s time=%lu\n", data, name, (xevent.xproperty.state == PropertyDelete) ? "deleted" : "changed", xevent.xproperty.time);
X11_XFree(name);
}
status = X11_XGetWindowProperty(display, data->xwindow, xevent.xproperty.atom, 0L, 8192L, False, AnyPropertyType, &real_type, &real_format, &items_read, &items_left, &propdata);
if (status == Success && items_read > 0) {
if (real_type == XA_INTEGER) {
int *values = (int *)propdata;
printf("{");
for (i = 0; i < items_read; i++) {
printf(" %d", values[i]);
}
printf(" }\n");
} else if (real_type == XA_CARDINAL) {
if (real_format == 32) {
Uint32 *values = (Uint32 *)propdata;
printf("{");
for (i = 0; i < items_read; i++) {
printf(" %d", values[i]);
}
printf(" }\n");
} else if (real_format == 16) {
Uint16 *values = (Uint16 *)propdata;
printf("{");
for (i = 0; i < items_read; i++) {
printf(" %d", values[i]);
}
printf(" }\n");
} else if (real_format == 8) {
Uint8 *values = (Uint8 *)propdata;
printf("{");
for (i = 0; i < items_read; i++) {
printf(" %d", values[i]);
}
printf(" }\n");
}
} else if (real_type == XA_STRING ||
real_type == videodata->UTF8_STRING) {
printf("{ \"%s\" }\n", propdata);
} else if (real_type == XA_ATOM) {
Atom *atoms = (Atom *)propdata;
printf("{");
for (i = 0; i < items_read; i++) {
char *atomname = X11_XGetAtomName(display, atoms[i]);
if (atomname) {
printf(" %s", atomname);
X11_XFree(atomname);
}
}
printf(" }\n");
} else {
char *atomname = X11_XGetAtomName(display, real_type);
printf("Unknown type: %ld (%s)\n", real_type, atomname ? atomname : "UNKNOWN");
if (atomname) {
X11_XFree(atomname);
}
}
}
if (status == Success) {
X11_XFree(propdata);
}
#endif /* DEBUG_XEVENTS */
/* Take advantage of this moment to make sure user_time has a
valid timestamp from the X server, so if we later try to
raise/restore this window, _NET_ACTIVE_WINDOW can have a
non-zero timestamp, even if there's never been a mouse or
key press to this window so far. Note that we don't try to
set _NET_WM_USER_TIME here, though. That's only for legit
user interaction with the window. */
if (!data->user_time) {
data->user_time = xevent.xproperty.time;
}
if (xevent.xproperty.atom == data->videodata->_NET_WM_STATE) {
/* Get the new state from the window manager.
Compositing window managers can alter visibility of windows
without ever mapping / unmapping them, so we handle that here,
because they use the NETWM protocol to notify us of changes.
*/
const Uint32 flags = X11_GetNetWMState(_this, xevent.xproperty.window);
const Uint32 changed = flags ^ data->window->flags;
if ((changed & SDL_WINDOW_HIDDEN) || (changed & SDL_WINDOW_FULLSCREEN)) {
if (flags & SDL_WINDOW_HIDDEN) {
X11_DispatchUnmapNotify(data);
} else {
X11_DispatchMapNotify(data);
}
}
if (changed & SDL_WINDOW_MAXIMIZED) {
if (flags & SDL_WINDOW_MAXIMIZED) {
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_MAXIMIZED, 0, 0);
} else {
SDL_SendWindowEvent(data->window, SDL_WINDOWEVENT_RESTORED, 0, 0);
}
}
} else if (xevent.xproperty.atom == videodata->XKLAVIER_STATE) {
/* Hack for Ubuntu 12.04 (etc) that doesn't send MappingNotify
events when the keyboard layout changes (for example,
changing from English to French on the menubar's keyboard
icon). Since it changes the XKLAVIER_STATE property, we
notice and reinit our keymap here. This might not be the
right approach, but it seems to work. */
X11_UpdateKeymap(_this);
SDL_SendKeymapChangedEvent();
} else if (xevent.xproperty.atom == videodata->_NET_FRAME_EXTENTS) {
Atom type;
int format;
unsigned long nitems, bytes_after;
unsigned char *property;
if (X11_XGetWindowProperty(display, data->xwindow, videodata->_NET_FRAME_EXTENTS, 0, 16, 0, XA_CARDINAL, &type, &format, &nitems, &bytes_after, &property) == Success) {
if (type != None && nitems == 4) {
data->border_left = (int) ((long*)property)[0];
data->border_right = (int) ((long*)property)[1];
data->border_top = (int) ((long*)property)[2];
data->border_bottom = (int) ((long*)property)[3];
}
X11_XFree(property);
#ifdef DEBUG_XEVENTS
printf("New _NET_FRAME_EXTENTS: left=%d right=%d, top=%d, bottom=%d\n", data->border_left, data->border_right, data->border_top, data->border_bottom);
#endif
}
}
}
break;
case SelectionNotify: {
Atom target = xevent.xselection.target;
#ifdef DEBUG_XEVENTS
printf("window %p: SelectionNotify (requestor = %ld, target = %ld)\n", data,
xevent.xselection.requestor, xevent.xselection.target);
#endif
if (target == data->xdnd_req) {
/* read data */
SDL_x11Prop p;
X11_ReadProperty(&p, display, data->xwindow, videodata->PRIMARY);
if (p.format == 8) {
char* saveptr = NULL;
char* name = X11_XGetAtomName(display, target);
char *token = SDL_strtokr((char *) p.data, "\r\n", &saveptr);
while (token != NULL) {
if (SDL_strcmp("text/plain", name)==0) {
SDL_SendDropText(data->window, token);
} else if (SDL_strcmp("text/uri-list", name)==0) {
char *fn = X11_URIToLocal(token);
if (fn) {
SDL_SendDropFile(data->window, fn);
}
}
token = SDL_strtokr(NULL, "\r\n", &saveptr);
}
SDL_SendDropComplete(data->window);
}
X11_XFree(p.data);
/* send reply */
SDL_memset(&m, 0, sizeof(XClientMessageEvent));
m.type = ClientMessage;
m.display = display;
m.window = data->xdnd_source;
m.message_type = videodata->XdndFinished;
m.format = 32;
m.data.l[0] = data->xwindow;
m.data.l[1] = 1;
m.data.l[2] = videodata->XdndActionCopy;
X11_XSendEvent(display, data->xdnd_source, False, NoEventMask, (XEvent*)&m);
X11_XSync(display, False);
}
}
break;
default:{
#ifdef DEBUG_XEVENTS
printf("window %p: Unhandled event %d\n", data, xevent.type);
#endif
}
break;
}
}
static void
X11_HandleFocusChanges(_THIS)
{
SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
int i;
if (videodata && videodata->windowlist) {
for (i = 0; i < videodata->numwindows; ++i) {
SDL_WindowData *data = videodata->windowlist[i];
if (data && data->pending_focus != PENDING_FOCUS_NONE) {
Uint32 now = SDL_GetTicks();
if (SDL_TICKS_PASSED(now, data->pending_focus_time)) {
if (data->pending_focus == PENDING_FOCUS_IN) {
X11_DispatchFocusIn(_this, data);
} else {
X11_DispatchFocusOut(_this, data);
}
data->pending_focus = PENDING_FOCUS_NONE;
}
}
}
}
}
/* Ack! X11_XPending() actually performs a blocking read if no events available */
static int
X11_Pending(Display * display)
{
/* Flush the display connection and look to see if events are queued */
X11_XFlush(display);
if (X11_XEventsQueued(display, QueuedAlready)) {
return (1);
}
/* More drastic measures are required -- see if X is ready to talk */
if (SDL_IOReady(ConnectionNumber(display), SDL_FALSE, 0)) {
return (X11_XPending(display));
}
/* Oh well, nothing is ready .. */
return (0);
}
void
X11_PumpEvents(_THIS)
{
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
if (data->last_mode_change_deadline) {
if (SDL_TICKS_PASSED(SDL_GetTicks(), data->last_mode_change_deadline)) {
data->last_mode_change_deadline = 0; /* assume we're done. */
}
}
/* Update activity every 30 seconds to prevent screensaver */
if (_this->suspend_screensaver) {
const Uint32 now = SDL_GetTicks();
if (!data->screensaver_activity ||
SDL_TICKS_PASSED(now, data->screensaver_activity + 30000)) {
X11_XResetScreenSaver(data->display);
#if SDL_USE_LIBDBUS
SDL_DBus_ScreensaverTickle();
#endif
data->screensaver_activity = now;
}
}
/* Keep processing pending events */
while (X11_Pending(data->display)) {
X11_DispatchEvent(_this);
}
#ifdef SDL_USE_IME
if(SDL_GetEventState(SDL_TEXTINPUT) == SDL_ENABLE){
SDL_IME_PumpEvents();
}
#endif
/* FIXME: Only need to do this when there are pending focus changes */
X11_HandleFocusChanges(_this);
}
void
X11_SuspendScreenSaver(_THIS)
{
#if SDL_VIDEO_DRIVER_X11_XSCRNSAVER
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
int dummy;
int major_version, minor_version;
#endif /* SDL_VIDEO_DRIVER_X11_XSCRNSAVER */
#if SDL_USE_LIBDBUS
if (SDL_DBus_ScreensaverInhibit(_this->suspend_screensaver)) {
return;
}
if (_this->suspend_screensaver) {
SDL_DBus_ScreensaverTickle();
}
#endif
#if SDL_VIDEO_DRIVER_X11_XSCRNSAVER
if (SDL_X11_HAVE_XSS) {
/* X11_XScreenSaverSuspend was introduced in MIT-SCREEN-SAVER 1.1 */
if (!X11_XScreenSaverQueryExtension(data->display, &dummy, &dummy) ||
!X11_XScreenSaverQueryVersion(data->display,
&major_version, &minor_version) ||
major_version < 1 || (major_version == 1 && minor_version < 1)) {
return;
}
X11_XScreenSaverSuspend(data->display, _this->suspend_screensaver);
X11_XResetScreenSaver(data->display);
}
#endif
}
#endif /* SDL_VIDEO_DRIVER_X11 */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11events.c | C | apache-2.0 | 54,895 |
/*
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_x11events_h_
#define SDL_x11events_h_
extern void X11_PumpEvents(_THIS);
extern void X11_SuspendScreenSaver(_THIS);
#endif /* SDL_x11events_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11events.h | C | apache-2.0 | 1,168 |
/*
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_X11
#include "SDL_x11video.h"
#include "SDL_x11framebuffer.h"
#ifndef NO_SHARED_MEMORY
/* Shared memory error handler routine */
static int shm_error;
static int (*X_handler)(Display *, XErrorEvent *) = NULL;
static int shm_errhandler(Display *d, XErrorEvent *e)
{
if ( e->error_code == BadAccess ) {
shm_error = True;
return(0);
} else
return(X_handler(d,e));
}
static SDL_bool have_mitshm(Display *dpy)
{
/* Only use shared memory on local X servers */
return X11_XShmQueryExtension(dpy) ? SDL_X11_HAVE_SHM : SDL_FALSE;
}
#endif /* !NO_SHARED_MEMORY */
int
X11_CreateWindowFramebuffer(_THIS, SDL_Window * window, Uint32 * format,
void ** pixels, int *pitch)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
XGCValues gcv;
XVisualInfo vinfo;
/* Free the old framebuffer surface */
X11_DestroyWindowFramebuffer(_this, window);
/* Create the graphics context for drawing */
gcv.graphics_exposures = False;
data->gc = X11_XCreateGC(display, data->xwindow, GCGraphicsExposures, &gcv);
if (!data->gc) {
return SDL_SetError("Couldn't create graphics context");
}
/* Find out the pixel format and depth */
if (X11_GetVisualInfoFromVisual(display, data->visual, &vinfo) < 0) {
return SDL_SetError("Couldn't get window visual information");
}
*format = X11_GetPixelFormatFromVisualInfo(display, &vinfo);
if (*format == SDL_PIXELFORMAT_UNKNOWN) {
return SDL_SetError("Unknown window pixel format");
}
/* Calculate pitch */
*pitch = (((window->w * SDL_BYTESPERPIXEL(*format)) + 3) & ~3);
/* Create the actual image */
#ifndef NO_SHARED_MEMORY
if (have_mitshm(display)) {
XShmSegmentInfo *shminfo = &data->shminfo;
shminfo->shmid = shmget(IPC_PRIVATE, window->h*(*pitch), IPC_CREAT | 0777);
if ( shminfo->shmid >= 0 ) {
shminfo->shmaddr = (char *)shmat(shminfo->shmid, 0, 0);
shminfo->readOnly = False;
if ( shminfo->shmaddr != (char *)-1 ) {
shm_error = False;
X_handler = X11_XSetErrorHandler(shm_errhandler);
X11_XShmAttach(display, shminfo);
X11_XSync(display, False);
X11_XSetErrorHandler(X_handler);
if ( shm_error )
shmdt(shminfo->shmaddr);
} else {
shm_error = True;
}
shmctl(shminfo->shmid, IPC_RMID, NULL);
} else {
shm_error = True;
}
if (!shm_error) {
data->ximage = X11_XShmCreateImage(display, data->visual,
vinfo.depth, ZPixmap,
shminfo->shmaddr, shminfo,
window->w, window->h);
if (!data->ximage) {
X11_XShmDetach(display, shminfo);
X11_XSync(display, False);
shmdt(shminfo->shmaddr);
} else {
/* Done! */
data->use_mitshm = SDL_TRUE;
*pixels = shminfo->shmaddr;
return 0;
}
}
}
#endif /* not NO_SHARED_MEMORY */
*pixels = SDL_malloc(window->h*(*pitch));
if (*pixels == NULL) {
return SDL_OutOfMemory();
}
data->ximage = X11_XCreateImage(display, data->visual,
vinfo.depth, ZPixmap, 0, (char *)(*pixels),
window->w, window->h, 32, 0);
if (!data->ximage) {
SDL_free(*pixels);
return SDL_SetError("Couldn't create XImage");
}
return 0;
}
int
X11_UpdateWindowFramebuffer(_THIS, SDL_Window * window, const SDL_Rect * rects,
int numrects)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
int i;
int x, y, w ,h;
#ifndef NO_SHARED_MEMORY
if (data->use_mitshm) {
for (i = 0; i < numrects; ++i) {
x = rects[i].x;
y = rects[i].y;
w = rects[i].w;
h = rects[i].h;
if (w <= 0 || h <= 0 || (x + w) <= 0 || (y + h) <= 0) {
/* Clipped? */
continue;
}
if (x < 0)
{
x += w;
w += rects[i].x;
}
if (y < 0)
{
y += h;
h += rects[i].y;
}
if (x + w > window->w)
w = window->w - x;
if (y + h > window->h)
h = window->h - y;
X11_XShmPutImage(display, data->xwindow, data->gc, data->ximage,
x, y, x, y, w, h, False);
}
}
else
#endif /* !NO_SHARED_MEMORY */
{
for (i = 0; i < numrects; ++i) {
x = rects[i].x;
y = rects[i].y;
w = rects[i].w;
h = rects[i].h;
if (w <= 0 || h <= 0 || (x + w) <= 0 || (y + h) <= 0) {
/* Clipped? */
continue;
}
if (x < 0)
{
x += w;
w += rects[i].x;
}
if (y < 0)
{
y += h;
h += rects[i].y;
}
if (x + w > window->w)
w = window->w - x;
if (y + h > window->h)
h = window->h - y;
X11_XPutImage(display, data->xwindow, data->gc, data->ximage,
x, y, x, y, w, h);
}
}
X11_XSync(display, False);
return 0;
}
void
X11_DestroyWindowFramebuffer(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display;
if (!data) {
/* The window wasn't fully initialized */
return;
}
display = data->videodata->display;
if (data->ximage) {
XDestroyImage(data->ximage);
#ifndef NO_SHARED_MEMORY
if (data->use_mitshm) {
X11_XShmDetach(display, &data->shminfo);
X11_XSync(display, False);
shmdt(data->shminfo.shmaddr);
data->use_mitshm = SDL_FALSE;
}
#endif /* !NO_SHARED_MEMORY */
data->ximage = NULL;
}
if (data->gc) {
X11_XFreeGC(display, data->gc);
data->gc = NULL;
}
}
#endif /* SDL_VIDEO_DRIVER_X11 */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11framebuffer.c | C | apache-2.0 | 7,525 |
/*
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_x11framebuffer_h_
#define SDL_x11framebuffer_h_
#include "../../SDL_internal.h"
extern int X11_CreateWindowFramebuffer(_THIS, SDL_Window * window,
Uint32 * format,
void ** pixels, int *pitch);
extern int X11_UpdateWindowFramebuffer(_THIS, SDL_Window * window,
const SDL_Rect * rects, int numrects);
extern void X11_DestroyWindowFramebuffer(_THIS, SDL_Window * window);
#endif /* SDL_x11framebuffer_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11framebuffer.h | C | apache-2.0 | 1,513 |
/*
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_X11
#include "SDL_x11video.h"
#include "../../events/SDL_keyboard_c.h"
#include "../../events/scancodes_darwin.h"
#include "../../events/scancodes_xfree86.h"
#include <X11/keysym.h>
#include <X11/XKBlib.h>
#include "imKStoUCS.h"
#ifdef X_HAVE_UTF8_STRING
#include <locale.h>
#endif
/* *INDENT-OFF* */
static const struct {
KeySym keysym;
SDL_Scancode scancode;
} KeySymToSDLScancode[] = {
{ XK_Return, SDL_SCANCODE_RETURN },
{ XK_Escape, SDL_SCANCODE_ESCAPE },
{ XK_BackSpace, SDL_SCANCODE_BACKSPACE },
{ XK_Tab, SDL_SCANCODE_TAB },
{ XK_Caps_Lock, SDL_SCANCODE_CAPSLOCK },
{ XK_F1, SDL_SCANCODE_F1 },
{ XK_F2, SDL_SCANCODE_F2 },
{ XK_F3, SDL_SCANCODE_F3 },
{ XK_F4, SDL_SCANCODE_F4 },
{ XK_F5, SDL_SCANCODE_F5 },
{ XK_F6, SDL_SCANCODE_F6 },
{ XK_F7, SDL_SCANCODE_F7 },
{ XK_F8, SDL_SCANCODE_F8 },
{ XK_F9, SDL_SCANCODE_F9 },
{ XK_F10, SDL_SCANCODE_F10 },
{ XK_F11, SDL_SCANCODE_F11 },
{ XK_F12, SDL_SCANCODE_F12 },
{ XK_Print, SDL_SCANCODE_PRINTSCREEN },
{ XK_Scroll_Lock, SDL_SCANCODE_SCROLLLOCK },
{ XK_Pause, SDL_SCANCODE_PAUSE },
{ XK_Insert, SDL_SCANCODE_INSERT },
{ XK_Home, SDL_SCANCODE_HOME },
{ XK_Prior, SDL_SCANCODE_PAGEUP },
{ XK_Delete, SDL_SCANCODE_DELETE },
{ XK_End, SDL_SCANCODE_END },
{ XK_Next, SDL_SCANCODE_PAGEDOWN },
{ XK_Right, SDL_SCANCODE_RIGHT },
{ XK_Left, SDL_SCANCODE_LEFT },
{ XK_Down, SDL_SCANCODE_DOWN },
{ XK_Up, SDL_SCANCODE_UP },
{ XK_Num_Lock, SDL_SCANCODE_NUMLOCKCLEAR },
{ XK_KP_Divide, SDL_SCANCODE_KP_DIVIDE },
{ XK_KP_Multiply, SDL_SCANCODE_KP_MULTIPLY },
{ XK_KP_Subtract, SDL_SCANCODE_KP_MINUS },
{ XK_KP_Add, SDL_SCANCODE_KP_PLUS },
{ XK_KP_Enter, SDL_SCANCODE_KP_ENTER },
{ XK_KP_Delete, SDL_SCANCODE_KP_PERIOD },
{ XK_KP_End, SDL_SCANCODE_KP_1 },
{ XK_KP_Down, SDL_SCANCODE_KP_2 },
{ XK_KP_Next, SDL_SCANCODE_KP_3 },
{ XK_KP_Left, SDL_SCANCODE_KP_4 },
{ XK_KP_Begin, SDL_SCANCODE_KP_5 },
{ XK_KP_Right, SDL_SCANCODE_KP_6 },
{ XK_KP_Home, SDL_SCANCODE_KP_7 },
{ XK_KP_Up, SDL_SCANCODE_KP_8 },
{ XK_KP_Prior, SDL_SCANCODE_KP_9 },
{ XK_KP_Insert, SDL_SCANCODE_KP_0 },
{ XK_KP_Decimal, SDL_SCANCODE_KP_PERIOD },
{ XK_KP_1, SDL_SCANCODE_KP_1 },
{ XK_KP_2, SDL_SCANCODE_KP_2 },
{ XK_KP_3, SDL_SCANCODE_KP_3 },
{ XK_KP_4, SDL_SCANCODE_KP_4 },
{ XK_KP_5, SDL_SCANCODE_KP_5 },
{ XK_KP_6, SDL_SCANCODE_KP_6 },
{ XK_KP_7, SDL_SCANCODE_KP_7 },
{ XK_KP_8, SDL_SCANCODE_KP_8 },
{ XK_KP_9, SDL_SCANCODE_KP_9 },
{ XK_KP_0, SDL_SCANCODE_KP_0 },
{ XK_KP_Decimal, SDL_SCANCODE_KP_PERIOD },
{ XK_Hyper_R, SDL_SCANCODE_APPLICATION },
{ XK_KP_Equal, SDL_SCANCODE_KP_EQUALS },
{ XK_F13, SDL_SCANCODE_F13 },
{ XK_F14, SDL_SCANCODE_F14 },
{ XK_F15, SDL_SCANCODE_F15 },
{ XK_F16, SDL_SCANCODE_F16 },
{ XK_F17, SDL_SCANCODE_F17 },
{ XK_F18, SDL_SCANCODE_F18 },
{ XK_F19, SDL_SCANCODE_F19 },
{ XK_F20, SDL_SCANCODE_F20 },
{ XK_F21, SDL_SCANCODE_F21 },
{ XK_F22, SDL_SCANCODE_F22 },
{ XK_F23, SDL_SCANCODE_F23 },
{ XK_F24, SDL_SCANCODE_F24 },
{ XK_Execute, SDL_SCANCODE_EXECUTE },
{ XK_Help, SDL_SCANCODE_HELP },
{ XK_Menu, SDL_SCANCODE_MENU },
{ XK_Select, SDL_SCANCODE_SELECT },
{ XK_Cancel, SDL_SCANCODE_STOP },
{ XK_Redo, SDL_SCANCODE_AGAIN },
{ XK_Undo, SDL_SCANCODE_UNDO },
{ XK_Find, SDL_SCANCODE_FIND },
{ XK_KP_Separator, SDL_SCANCODE_KP_COMMA },
{ XK_Sys_Req, SDL_SCANCODE_SYSREQ },
{ XK_Control_L, SDL_SCANCODE_LCTRL },
{ XK_Shift_L, SDL_SCANCODE_LSHIFT },
{ XK_Alt_L, SDL_SCANCODE_LALT },
{ XK_Meta_L, SDL_SCANCODE_LGUI },
{ XK_Super_L, SDL_SCANCODE_LGUI },
{ XK_Control_R, SDL_SCANCODE_RCTRL },
{ XK_Shift_R, SDL_SCANCODE_RSHIFT },
{ XK_Alt_R, SDL_SCANCODE_RALT },
{ XK_ISO_Level3_Shift, SDL_SCANCODE_RALT },
{ XK_Meta_R, SDL_SCANCODE_RGUI },
{ XK_Super_R, SDL_SCANCODE_RGUI },
{ XK_Mode_switch, SDL_SCANCODE_MODE },
{ XK_period, SDL_SCANCODE_PERIOD },
{ XK_comma, SDL_SCANCODE_COMMA },
{ XK_slash, SDL_SCANCODE_SLASH },
{ XK_backslash, SDL_SCANCODE_BACKSLASH },
{ XK_minus, SDL_SCANCODE_MINUS },
{ XK_equal, SDL_SCANCODE_EQUALS },
{ XK_space, SDL_SCANCODE_SPACE },
{ XK_grave, SDL_SCANCODE_GRAVE },
{ XK_apostrophe, SDL_SCANCODE_APOSTROPHE },
{ XK_bracketleft, SDL_SCANCODE_LEFTBRACKET },
{ XK_bracketright, SDL_SCANCODE_RIGHTBRACKET },
};
static const struct
{
SDL_Scancode const *table;
int table_size;
} scancode_set[] = {
{ darwin_scancode_table, SDL_arraysize(darwin_scancode_table) },
{ xfree86_scancode_table, SDL_arraysize(xfree86_scancode_table) },
{ xfree86_scancode_table2, SDL_arraysize(xfree86_scancode_table2) },
{ xvnc_scancode_table, SDL_arraysize(xvnc_scancode_table) },
};
/* *INDENT-OFF* */
/* This function only works for keyboards in US QWERTY layout */
static SDL_Scancode
X11_KeyCodeToSDLScancode(_THIS, KeyCode keycode)
{
KeySym keysym;
int i;
keysym = X11_KeyCodeToSym(_this, keycode, 0);
if (keysym == NoSymbol) {
return SDL_SCANCODE_UNKNOWN;
}
if (keysym >= XK_a && keysym <= XK_z) {
return SDL_SCANCODE_A + (keysym - XK_a);
}
if (keysym >= XK_A && keysym <= XK_Z) {
return SDL_SCANCODE_A + (keysym - XK_A);
}
if (keysym == XK_0) {
return SDL_SCANCODE_0;
}
if (keysym >= XK_1 && keysym <= XK_9) {
return SDL_SCANCODE_1 + (keysym - XK_1);
}
for (i = 0; i < SDL_arraysize(KeySymToSDLScancode); ++i) {
if (keysym == KeySymToSDLScancode[i].keysym) {
return KeySymToSDLScancode[i].scancode;
}
}
return SDL_SCANCODE_UNKNOWN;
}
static Uint32
X11_KeyCodeToUcs4(_THIS, KeyCode keycode, unsigned char group)
{
KeySym keysym = X11_KeyCodeToSym(_this, keycode, group);
if (keysym == NoSymbol) {
return 0;
}
return X11_KeySymToUcs4(keysym);
}
KeySym
X11_KeyCodeToSym(_THIS, KeyCode keycode, unsigned char group)
{
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
KeySym keysym;
#if SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM
if (data->xkb) {
int num_groups = XkbKeyNumGroups(data->xkb, keycode);
unsigned char info = XkbKeyGroupInfo(data->xkb, keycode);
if (num_groups && group >= num_groups) {
int action = XkbOutOfRangeGroupAction(info);
if (action == XkbRedirectIntoRange) {
if ((group = XkbOutOfRangeGroupNumber(info)) >= num_groups) {
group = 0;
}
} else if (action == XkbClampIntoRange) {
group = num_groups - 1;
} else {
group %= num_groups;
}
}
keysym = X11_XkbKeycodeToKeysym(data->display, keycode, group, 0);
} else {
keysym = X11_XKeycodeToKeysym(data->display, keycode, 0);
}
#else
keysym = X11_XKeycodeToKeysym(data->display, keycode, 0);
#endif
return keysym;
}
int
X11_InitKeyboard(_THIS)
{
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
int i = 0;
int j = 0;
int min_keycode, max_keycode;
struct {
SDL_Scancode scancode;
KeySym keysym;
int value;
} fingerprint[] = {
{ SDL_SCANCODE_HOME, XK_Home, 0 },
{ SDL_SCANCODE_PAGEUP, XK_Prior, 0 },
{ SDL_SCANCODE_UP, XK_Up, 0 },
{ SDL_SCANCODE_LEFT, XK_Left, 0 },
{ SDL_SCANCODE_DELETE, XK_Delete, 0 },
{ SDL_SCANCODE_KP_ENTER, XK_KP_Enter, 0 },
};
int best_distance;
int best_index;
int distance;
Bool xkb_repeat = 0;
XKeyboardState values = { .global_auto_repeat = AutoRepeatModeOff };
X11_XGetKeyboardControl(data->display, &values);
if (values.global_auto_repeat != AutoRepeatModeOn)
X11_XAutoRepeatOn(data->display);
#if SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM
{
int xkb_major = XkbMajorVersion;
int xkb_minor = XkbMinorVersion;
if (X11_XkbQueryExtension(data->display, NULL, NULL, NULL, &xkb_major, &xkb_minor)) {
data->xkb = X11_XkbGetMap(data->display, XkbAllClientInfoMask, XkbUseCoreKbd);
}
/* This will remove KeyRelease events for held keys */
X11_XkbSetDetectableAutoRepeat(data->display, True, &xkb_repeat);
}
#endif
/* Open a connection to the X input manager */
#ifdef X_HAVE_UTF8_STRING
if (SDL_X11_HAVE_UTF8) {
/* Set the locale, and call XSetLocaleModifiers before XOpenIM so that
Compose keys will work correctly. */
char *prev_locale = setlocale(LC_ALL, NULL);
char *prev_xmods = X11_XSetLocaleModifiers(NULL);
const char *new_xmods = "";
const char *env_xmods = SDL_getenv("XMODIFIERS");
SDL_bool has_dbus_ime_support = SDL_FALSE;
if (prev_locale) {
prev_locale = SDL_strdup(prev_locale);
}
if (prev_xmods) {
prev_xmods = SDL_strdup(prev_xmods);
}
/* IBus resends some key events that were filtered by XFilterEvents
when it is used via XIM which causes issues. Prevent this by forcing
@im=none if XMODIFIERS contains @im=ibus. IBus can still be used via
the DBus implementation, which also has support for pre-editing. */
if (env_xmods && SDL_strstr(env_xmods, "@im=ibus") != NULL) {
has_dbus_ime_support = SDL_TRUE;
}
if (env_xmods && SDL_strstr(env_xmods, "@im=fcitx") != NULL) {
has_dbus_ime_support = SDL_TRUE;
}
if (has_dbus_ime_support || !xkb_repeat) {
new_xmods = "@im=none";
}
setlocale(LC_ALL, "");
X11_XSetLocaleModifiers(new_xmods);
data->im = X11_XOpenIM(data->display, NULL, data->classname, data->classname);
/* Reset the locale + X locale modifiers back to how they were,
locale first because the X locale modifiers depend on it. */
setlocale(LC_ALL, prev_locale);
X11_XSetLocaleModifiers(prev_xmods);
if (prev_locale) {
SDL_free(prev_locale);
}
if (prev_xmods) {
SDL_free(prev_xmods);
}
}
#endif
/* Try to determine which scancodes are being used based on fingerprint */
best_distance = SDL_arraysize(fingerprint) + 1;
best_index = -1;
X11_XDisplayKeycodes(data->display, &min_keycode, &max_keycode);
for (i = 0; i < SDL_arraysize(fingerprint); ++i) {
fingerprint[i].value =
X11_XKeysymToKeycode(data->display, fingerprint[i].keysym) -
min_keycode;
}
for (i = 0; i < SDL_arraysize(scancode_set); ++i) {
/* Make sure the scancode set isn't too big */
if ((max_keycode - min_keycode + 1) <= scancode_set[i].table_size) {
continue;
}
distance = 0;
for (j = 0; j < SDL_arraysize(fingerprint); ++j) {
if (fingerprint[j].value < 0
|| fingerprint[j].value >= scancode_set[i].table_size) {
distance += 1;
} else if (scancode_set[i].table[fingerprint[j].value] != fingerprint[j].scancode) {
distance += 1;
}
}
if (distance < best_distance) {
best_distance = distance;
best_index = i;
}
}
if (best_index >= 0 && best_distance <= 2) {
#ifdef DEBUG_KEYBOARD
printf("Using scancode set %d, min_keycode = %d, max_keycode = %d, table_size = %d\n", best_index, min_keycode, max_keycode, scancode_set[best_index].table_size);
#endif
SDL_memcpy(&data->key_layout[min_keycode], scancode_set[best_index].table,
sizeof(SDL_Scancode) * scancode_set[best_index].table_size);
} else {
SDL_Keycode keymap[SDL_NUM_SCANCODES];
printf
("Keyboard layout unknown, please report the following to the SDL forums/mailing list (https://discourse.libsdl.org/):\n");
/* Determine key_layout - only works on US QWERTY layout */
SDL_GetDefaultKeymap(keymap);
for (i = min_keycode; i <= max_keycode; ++i) {
KeySym sym;
sym = X11_KeyCodeToSym(_this, (KeyCode) i, 0);
if (sym != NoSymbol) {
SDL_Scancode scancode;
printf("code = %d, sym = 0x%X (%s) ", i - min_keycode,
(unsigned int) sym, X11_XKeysymToString(sym));
scancode = X11_KeyCodeToSDLScancode(_this, i);
data->key_layout[i] = scancode;
if (scancode == SDL_SCANCODE_UNKNOWN) {
printf("scancode not found\n");
} else {
printf("scancode = %d (%s)\n", scancode, SDL_GetScancodeName(scancode));
}
}
}
}
X11_UpdateKeymap(_this);
SDL_SetScancodeName(SDL_SCANCODE_APPLICATION, "Menu");
#ifdef SDL_USE_IME
SDL_IME_Init();
#endif
return 0;
}
void
X11_UpdateKeymap(_THIS)
{
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
int i;
SDL_Scancode scancode;
SDL_Keycode keymap[SDL_NUM_SCANCODES];
unsigned char group = 0;
SDL_GetDefaultKeymap(keymap);
#if SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM
if (data->xkb) {
XkbStateRec state;
X11_XkbGetUpdatedMap(data->display, XkbAllClientInfoMask, data->xkb);
if (X11_XkbGetState(data->display, XkbUseCoreKbd, &state) == Success) {
group = state.group;
}
}
#endif
for (i = 0; i < SDL_arraysize(data->key_layout); i++) {
Uint32 key;
/* Make sure this is a valid scancode */
scancode = data->key_layout[i];
if (scancode == SDL_SCANCODE_UNKNOWN) {
continue;
}
/* See if there is a UCS keycode for this scancode */
key = X11_KeyCodeToUcs4(_this, (KeyCode)i, group);
if (key) {
keymap[scancode] = key;
} else {
SDL_Scancode keyScancode = X11_KeyCodeToSDLScancode(_this, (KeyCode)i);
switch (keyScancode) {
case SDL_SCANCODE_RETURN:
keymap[scancode] = SDLK_RETURN;
break;
case SDL_SCANCODE_ESCAPE:
keymap[scancode] = SDLK_ESCAPE;
break;
case SDL_SCANCODE_BACKSPACE:
keymap[scancode] = SDLK_BACKSPACE;
break;
case SDL_SCANCODE_TAB:
keymap[scancode] = SDLK_TAB;
break;
case SDL_SCANCODE_DELETE:
keymap[scancode] = SDLK_DELETE;
break;
default:
keymap[scancode] = SDL_SCANCODE_TO_KEYCODE(keyScancode);
break;
}
}
}
SDL_SetKeymap(0, keymap, SDL_NUM_SCANCODES);
}
void
X11_QuitKeyboard(_THIS)
{
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
#if SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM
if (data->xkb) {
X11_XkbFreeKeyboard(data->xkb, 0, True);
data->xkb = NULL;
}
#endif
#ifdef SDL_USE_IME
SDL_IME_Quit();
#endif
}
static void
X11_ResetXIM(_THIS)
{
#ifdef X_HAVE_UTF8_STRING
SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
int i;
if (videodata && videodata->windowlist) {
for (i = 0; i < videodata->numwindows; ++i) {
SDL_WindowData *data = videodata->windowlist[i];
if (data && data->ic) {
/* Clear any partially entered dead keys */
char *contents = X11_Xutf8ResetIC(data->ic);
if (contents) {
X11_XFree(contents);
}
}
}
}
#endif
}
void
X11_StartTextInput(_THIS)
{
X11_ResetXIM(_this);
}
void
X11_StopTextInput(_THIS)
{
X11_ResetXIM(_this);
#ifdef SDL_USE_IME
SDL_IME_Reset();
#endif
}
void
X11_SetTextInputRect(_THIS, SDL_Rect *rect)
{
if (!rect) {
SDL_InvalidParamError("rect");
return;
}
#ifdef SDL_USE_IME
SDL_IME_UpdateTextRect(rect);
#endif
}
#endif /* SDL_VIDEO_DRIVER_X11 */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11keyboard.c | C | apache-2.0 | 17,358 |
/*
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_x11keyboard_h_
#define SDL_x11keyboard_h_
extern int X11_InitKeyboard(_THIS);
extern void X11_UpdateKeymap(_THIS);
extern void X11_QuitKeyboard(_THIS);
extern void X11_StartTextInput(_THIS);
extern void X11_StopTextInput(_THIS);
extern void X11_SetTextInputRect(_THIS, SDL_Rect *rect);
extern KeySym X11_KeyCodeToSym(_THIS, KeyCode, unsigned char group);
#endif /* SDL_x11keyboard_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11keyboard.h | C | apache-2.0 | 1,409 |
/*
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_X11
#include "SDL.h"
#include "SDL_x11video.h"
#include "SDL_x11dyn.h"
#include "SDL_assert.h"
#include "SDL_x11messagebox.h"
#include <X11/keysym.h>
#include <locale.h>
#define SDL_FORK_MESSAGEBOX 1
#define SDL_SET_LOCALE 1
#if SDL_FORK_MESSAGEBOX
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
#endif
#define MAX_BUTTONS 8 /* Maximum number of buttons supported */
#define MIN_BUTTON_WIDTH 64 /* Minimum button width */
#define MIN_DIALOG_WIDTH 200 /* Minimum dialog width */
#define MIN_DIALOG_HEIGHT 100 /* Minimum dialog height */
static const char g_MessageBoxFontLatin1[] = "-*-*-medium-r-normal--0-120-*-*-p-0-iso8859-1";
static const char g_MessageBoxFont[] = "-*-*-medium-r-normal--*-120-*-*-*-*-*-*";
static const SDL_MessageBoxColor g_default_colors[ SDL_MESSAGEBOX_COLOR_MAX ] = {
{ 56, 54, 53 }, /* SDL_MESSAGEBOX_COLOR_BACKGROUND, */
{ 209, 207, 205 }, /* SDL_MESSAGEBOX_COLOR_TEXT, */
{ 140, 135, 129 }, /* SDL_MESSAGEBOX_COLOR_BUTTON_BORDER, */
{ 105, 102, 99 }, /* SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND, */
{ 205, 202, 53 }, /* SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED, */
};
#define SDL_MAKE_RGB( _r, _g, _b ) ( ( ( Uint32 )( _r ) << 16 ) | \
( ( Uint32 )( _g ) << 8 ) | \
( ( Uint32 )( _b ) ) )
typedef struct SDL_MessageBoxButtonDataX11 {
int x, y; /* Text position */
int length; /* Text length */
int text_width; /* Text width */
SDL_Rect rect; /* Rectangle for entire button */
const SDL_MessageBoxButtonData *buttondata; /* Button data from caller */
} SDL_MessageBoxButtonDataX11;
typedef struct TextLineData {
int width; /* Width of this text line */
int length; /* String length of this text line */
const char *text; /* Text for this line */
} TextLineData;
typedef struct SDL_MessageBoxDataX11
{
Display *display;
int screen;
Window window;
#if SDL_VIDEO_DRIVER_X11_XDBE
XdbeBackBuffer buf;
SDL_bool xdbe; /* Whether Xdbe is present or not */
#endif
long event_mask;
Atom wm_protocols;
Atom wm_delete_message;
int dialog_width; /* Dialog box width. */
int dialog_height; /* Dialog box height. */
XFontSet font_set; /* for UTF-8 systems */
XFontStruct *font_struct; /* Latin1 (ASCII) fallback. */
int xtext, ytext; /* Text position to start drawing at. */
int numlines; /* Count of Text lines. */
int text_height; /* Height for text lines. */
TextLineData *linedata;
int *pbuttonid; /* Pointer to user return buttonid value. */
int button_press_index; /* Index into buttondata/buttonpos for button which is pressed (or -1). */
int mouse_over_index; /* Index into buttondata/buttonpos for button mouse is over (or -1). */
int numbuttons; /* Count of buttons. */
const SDL_MessageBoxButtonData *buttondata;
SDL_MessageBoxButtonDataX11 buttonpos[ MAX_BUTTONS ];
Uint32 color[ SDL_MESSAGEBOX_COLOR_MAX ];
const SDL_MessageBoxData *messageboxdata;
} SDL_MessageBoxDataX11;
/* Maximum helper for ints. */
static SDL_INLINE int
IntMax( int a, int b )
{
return ( a > b ) ? a : b;
}
/* Return width and height for a string. */
static void
GetTextWidthHeight( SDL_MessageBoxDataX11 *data, const char *str, int nbytes, int *pwidth, int *pheight )
{
if (SDL_X11_HAVE_UTF8) {
XRectangle overall_ink, overall_logical;
X11_Xutf8TextExtents(data->font_set, str, nbytes, &overall_ink, &overall_logical);
*pwidth = overall_logical.width;
*pheight = overall_logical.height;
} else {
XCharStruct text_structure;
int font_direction, font_ascent, font_descent;
X11_XTextExtents( data->font_struct, str, nbytes,
&font_direction, &font_ascent, &font_descent,
&text_structure );
*pwidth = text_structure.width;
*pheight = text_structure.ascent + text_structure.descent;
}
}
/* Return index of button if position x,y is contained therein. */
static int
GetHitButtonIndex( SDL_MessageBoxDataX11 *data, int x, int y )
{
int i;
int numbuttons = data->numbuttons;
SDL_MessageBoxButtonDataX11 *buttonpos = data->buttonpos;
for ( i = 0; i < numbuttons; i++ ) {
SDL_Rect *rect = &buttonpos[ i ].rect;
if ( ( x >= rect->x ) &&
( x <= ( rect->x + rect->w ) ) &&
( y >= rect->y ) &&
( y <= ( rect->y + rect->h ) ) ) {
return i;
}
}
return -1;
}
/* Initialize SDL_MessageBoxData structure and Display, etc. */
static int
X11_MessageBoxInit( SDL_MessageBoxDataX11 *data, const SDL_MessageBoxData * messageboxdata, int * pbuttonid )
{
int i;
int numbuttons = messageboxdata->numbuttons;
const SDL_MessageBoxButtonData *buttondata = messageboxdata->buttons;
const SDL_MessageBoxColor *colorhints;
if ( numbuttons > MAX_BUTTONS ) {
return SDL_SetError("Too many buttons (%d max allowed)", MAX_BUTTONS);
}
data->dialog_width = MIN_DIALOG_WIDTH;
data->dialog_height = MIN_DIALOG_HEIGHT;
data->messageboxdata = messageboxdata;
data->buttondata = buttondata;
data->numbuttons = numbuttons;
data->pbuttonid = pbuttonid;
data->display = X11_XOpenDisplay( NULL );
if ( !data->display ) {
return SDL_SetError("Couldn't open X11 display");
}
if (SDL_X11_HAVE_UTF8) {
char **missing = NULL;
int num_missing = 0;
data->font_set = X11_XCreateFontSet(data->display, g_MessageBoxFont,
&missing, &num_missing, NULL);
if ( missing != NULL ) {
X11_XFreeStringList(missing);
}
if ( data->font_set == NULL ) {
return SDL_SetError("Couldn't load font %s", g_MessageBoxFont);
}
} else {
data->font_struct = X11_XLoadQueryFont( data->display, g_MessageBoxFontLatin1 );
if ( data->font_struct == NULL ) {
return SDL_SetError("Couldn't load font %s", g_MessageBoxFontLatin1);
}
}
if ( messageboxdata->colorScheme ) {
colorhints = messageboxdata->colorScheme->colors;
} else {
colorhints = g_default_colors;
}
/* Convert our SDL_MessageBoxColor r,g,b values to packed RGB format. */
for ( i = 0; i < SDL_MESSAGEBOX_COLOR_MAX; i++ ) {
data->color[ i ] = SDL_MAKE_RGB( colorhints[ i ].r, colorhints[ i ].g, colorhints[ i ].b );
}
return 0;
}
static int
CountLinesOfText(const char *text)
{
int retval = 0;
while (text && *text) {
const char *lf = SDL_strchr(text, '\n');
retval++; /* even without an endline, this counts as a line. */
text = lf ? lf + 1 : NULL;
}
return retval;
}
/* Calculate and initialize text and button locations. */
static int
X11_MessageBoxInitPositions( SDL_MessageBoxDataX11 *data )
{
int i;
int ybuttons;
int text_width_max = 0;
int button_text_height = 0;
int button_width = MIN_BUTTON_WIDTH;
const SDL_MessageBoxData *messageboxdata = data->messageboxdata;
/* Go over text and break linefeeds into separate lines. */
if ( messageboxdata->message && messageboxdata->message[ 0 ] ) {
const char *text = messageboxdata->message;
const int linecount = CountLinesOfText(text);
TextLineData *plinedata = (TextLineData *) SDL_malloc(sizeof (TextLineData) * linecount);
if (!plinedata) {
return SDL_OutOfMemory();
}
data->linedata = plinedata;
data->numlines = linecount;
for ( i = 0; i < linecount; i++, plinedata++ ) {
const char *lf = SDL_strchr( text, '\n' );
const int length = lf ? ( lf - text ) : SDL_strlen( text );
int height;
plinedata->text = text;
GetTextWidthHeight( data, text, length, &plinedata->width, &height );
/* Text and widths are the largest we've ever seen. */
data->text_height = IntMax( data->text_height, height );
text_width_max = IntMax( text_width_max, plinedata->width );
plinedata->length = length;
if (lf && (lf > text) && (lf[-1] == '\r')) {
plinedata->length--;
}
text += length + 1;
/* Break if there are no more linefeeds. */
if ( !lf )
break;
}
/* Bump up the text height slightly. */
data->text_height += 2;
}
/* Loop through all buttons and calculate the button widths and height. */
for ( i = 0; i < data->numbuttons; i++ ) {
int height;
data->buttonpos[ i ].buttondata = &data->buttondata[ i ];
data->buttonpos[ i ].length = SDL_strlen( data->buttondata[ i ].text );
GetTextWidthHeight( data, data->buttondata[ i ].text, SDL_strlen( data->buttondata[ i ].text ),
&data->buttonpos[ i ].text_width, &height );
button_width = IntMax( button_width, data->buttonpos[ i ].text_width );
button_text_height = IntMax( button_text_height, height );
}
if ( data->numlines ) {
/* x,y for this line of text. */
data->xtext = data->text_height;
data->ytext = data->text_height + data->text_height;
/* Bump button y down to bottom of text. */
ybuttons = 3 * data->ytext / 2 + ( data->numlines - 1 ) * data->text_height;
/* Bump the dialog box width and height up if needed. */
data->dialog_width = IntMax( data->dialog_width, 2 * data->xtext + text_width_max );
data->dialog_height = IntMax( data->dialog_height, ybuttons );
} else {
/* Button y starts at height of button text. */
ybuttons = button_text_height;
}
if ( data->numbuttons ) {
int x, y;
int width_of_buttons;
int button_spacing = button_text_height;
int button_height = 2 * button_text_height;
/* Bump button width up a bit. */
button_width += button_text_height;
/* Get width of all buttons lined up. */
width_of_buttons = data->numbuttons * button_width + ( data->numbuttons - 1 ) * button_spacing;
/* Bump up dialog width and height if buttons are wider than text. */
data->dialog_width = IntMax( data->dialog_width, width_of_buttons + 2 * button_spacing );
data->dialog_height = IntMax( data->dialog_height, ybuttons + 2 * button_height );
/* Location for first button. */
if ( messageboxdata->flags & SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT ) {
x = data->dialog_width - ( data->dialog_width - width_of_buttons ) / 2 - ( button_width + button_spacing );
} else {
x = ( data->dialog_width - width_of_buttons ) / 2;
}
y = ybuttons + ( data->dialog_height - ybuttons - button_height ) / 2;
for ( i = 0; i < data->numbuttons; i++ ) {
/* Button coordinates. */
data->buttonpos[ i ].rect.x = x;
data->buttonpos[ i ].rect.y = y;
data->buttonpos[ i ].rect.w = button_width;
data->buttonpos[ i ].rect.h = button_height;
/* Button text coordinates. */
data->buttonpos[ i ].x = x + ( button_width - data->buttonpos[ i ].text_width ) / 2;
data->buttonpos[ i ].y = y + ( button_height - button_text_height - 1 ) / 2 + button_text_height;
/* Scoot over for next button. */
if ( messageboxdata->flags & SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT ) {
x -= button_width + button_spacing;
} else {
x += button_width + button_spacing;
}
}
}
return 0;
}
/* Free SDL_MessageBoxData data. */
static void
X11_MessageBoxShutdown( SDL_MessageBoxDataX11 *data )
{
if ( data->font_set != NULL ) {
X11_XFreeFontSet( data->display, data->font_set );
data->font_set = NULL;
}
if ( data->font_struct != NULL ) {
X11_XFreeFont( data->display, data->font_struct );
data->font_struct = NULL;
}
#if SDL_VIDEO_DRIVER_X11_XDBE
if ( SDL_X11_HAVE_XDBE && data->xdbe ) {
X11_XdbeDeallocateBackBufferName(data->display, data->buf);
}
#endif
if ( data->display ) {
if ( data->window != None ) {
X11_XWithdrawWindow( data->display, data->window, data->screen );
X11_XDestroyWindow( data->display, data->window );
data->window = None;
}
X11_XCloseDisplay( data->display );
data->display = NULL;
}
SDL_free(data->linedata);
}
/* Create and set up our X11 dialog box indow. */
static int
X11_MessageBoxCreateWindow( SDL_MessageBoxDataX11 *data )
{
int x, y;
XSizeHints *sizehints;
XSetWindowAttributes wnd_attr;
Atom _NET_WM_WINDOW_TYPE, _NET_WM_WINDOW_TYPE_DIALOG, _NET_WM_NAME;
Display *display = data->display;
SDL_WindowData *windowdata = NULL;
const SDL_MessageBoxData *messageboxdata = data->messageboxdata;
char *title_locale = NULL;
if ( messageboxdata->window ) {
SDL_DisplayData *displaydata =
(SDL_DisplayData *) SDL_GetDisplayForWindow(messageboxdata->window)->driverdata;
windowdata = (SDL_WindowData *)messageboxdata->window->driverdata;
data->screen = displaydata->screen;
} else {
data->screen = DefaultScreen( display );
}
data->event_mask = ExposureMask |
ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask |
StructureNotifyMask | FocusChangeMask | PointerMotionMask;
wnd_attr.event_mask = data->event_mask;
data->window = X11_XCreateWindow(
display, RootWindow(display, data->screen),
0, 0,
data->dialog_width, data->dialog_height,
0, CopyFromParent, InputOutput, CopyFromParent,
CWEventMask, &wnd_attr );
if ( data->window == None ) {
return SDL_SetError("Couldn't create X window");
}
if ( windowdata ) {
Atom _NET_WM_STATE = X11_XInternAtom(display, "_NET_WM_STATE", False);
Atom stateatoms[16];
size_t statecount = 0;
/* Set some message-boxy window states when attached to a parent window... */
/* we skip the taskbar since this will pop to the front when the parent window is clicked in the taskbar, etc */
stateatoms[statecount++] = X11_XInternAtom(display, "_NET_WM_STATE_SKIP_TASKBAR", False);
stateatoms[statecount++] = X11_XInternAtom(display, "_NET_WM_STATE_SKIP_PAGER", False);
stateatoms[statecount++] = X11_XInternAtom(display, "_NET_WM_STATE_FOCUSED", False);
stateatoms[statecount++] = X11_XInternAtom(display, "_NET_WM_STATE_MODAL", False);
SDL_assert(statecount <= SDL_arraysize(stateatoms));
X11_XChangeProperty(display, data->window, _NET_WM_STATE, XA_ATOM, 32,
PropModeReplace, (unsigned char *)stateatoms, statecount);
/* http://tronche.com/gui/x/icccm/sec-4.html#WM_TRANSIENT_FOR */
X11_XSetTransientForHint( display, data->window, windowdata->xwindow );
}
X11_XStoreName( display, data->window, messageboxdata->title );
_NET_WM_NAME = X11_XInternAtom(display, "_NET_WM_NAME", False);
title_locale = SDL_iconv_utf8_locale(messageboxdata->title);
if (title_locale) {
XTextProperty titleprop;
Status status = X11_XStringListToTextProperty(&title_locale, 1, &titleprop);
SDL_free(title_locale);
if (status) {
X11_XSetTextProperty(display, data->window, &titleprop, XA_WM_NAME);
X11_XFree(titleprop.value);
}
}
#ifdef X_HAVE_UTF8_STRING
if (SDL_X11_HAVE_UTF8) {
XTextProperty titleprop;
Status status = X11_Xutf8TextListToTextProperty(display, (char **) &messageboxdata->title, 1,
XUTF8StringStyle, &titleprop);
if (status == Success) {
X11_XSetTextProperty(display, data->window, &titleprop,
_NET_WM_NAME);
X11_XFree(titleprop.value);
}
}
#endif
/* Let the window manager know this is a dialog box */
_NET_WM_WINDOW_TYPE = X11_XInternAtom(display, "_NET_WM_WINDOW_TYPE", False);
_NET_WM_WINDOW_TYPE_DIALOG = X11_XInternAtom(display, "_NET_WM_WINDOW_TYPE_DIALOG", False);
X11_XChangeProperty(display, data->window, _NET_WM_WINDOW_TYPE, XA_ATOM, 32,
PropModeReplace,
(unsigned char *)&_NET_WM_WINDOW_TYPE_DIALOG, 1);
/* Allow the window to be deleted by the window manager */
data->wm_protocols = X11_XInternAtom( display, "WM_PROTOCOLS", False );
data->wm_delete_message = X11_XInternAtom( display, "WM_DELETE_WINDOW", False );
X11_XSetWMProtocols( display, data->window, &data->wm_delete_message, 1 );
if ( windowdata ) {
XWindowAttributes attrib;
Window dummy;
X11_XGetWindowAttributes(display, windowdata->xwindow, &attrib);
x = attrib.x + ( attrib.width - data->dialog_width ) / 2;
y = attrib.y + ( attrib.height - data->dialog_height ) / 3 ;
X11_XTranslateCoordinates(display, windowdata->xwindow, RootWindow(display, data->screen), x, y, &x, &y, &dummy);
} else {
const SDL_VideoDevice *dev = SDL_GetVideoDevice();
if ((dev) && (dev->displays) && (dev->num_displays > 0)) {
const SDL_VideoDisplay *dpy = &dev->displays[0];
const SDL_DisplayData *dpydata = (SDL_DisplayData *) dpy->driverdata;
x = dpydata->x + (( dpy->current_mode.w - data->dialog_width ) / 2);
y = dpydata->y + (( dpy->current_mode.h - data->dialog_height ) / 3);
} else { /* oh well. This will misposition on a multi-head setup. Init first next time. */
x = ( DisplayWidth( display, data->screen ) - data->dialog_width ) / 2;
y = ( DisplayHeight( display, data->screen ) - data->dialog_height ) / 3 ;
}
}
X11_XMoveWindow( display, data->window, x, y );
sizehints = X11_XAllocSizeHints();
if ( sizehints ) {
sizehints->flags = USPosition | USSize | PMaxSize | PMinSize;
sizehints->x = x;
sizehints->y = y;
sizehints->width = data->dialog_width;
sizehints->height = data->dialog_height;
sizehints->min_width = sizehints->max_width = data->dialog_width;
sizehints->min_height = sizehints->max_height = data->dialog_height;
X11_XSetWMNormalHints( display, data->window, sizehints );
X11_XFree( sizehints );
}
X11_XMapRaised( display, data->window );
#if SDL_VIDEO_DRIVER_X11_XDBE
/* Initialise a back buffer for double buffering */
if (SDL_X11_HAVE_XDBE) {
int xdbe_major, xdbe_minor;
if (X11_XdbeQueryExtension(display, &xdbe_major, &xdbe_minor) != 0) {
data->xdbe = SDL_TRUE;
data->buf = X11_XdbeAllocateBackBufferName(display, data->window, XdbeUndefined);
} else {
data->xdbe = SDL_FALSE;
}
}
#endif
return 0;
}
/* Draw our message box. */
static void
X11_MessageBoxDraw( SDL_MessageBoxDataX11 *data, GC ctx )
{
int i;
Drawable window = data->window;
Display *display = data->display;
#if SDL_VIDEO_DRIVER_X11_XDBE
if (SDL_X11_HAVE_XDBE && data->xdbe) {
window = data->buf;
X11_XdbeBeginIdiom(data->display);
}
#endif
X11_XSetForeground( display, ctx, data->color[ SDL_MESSAGEBOX_COLOR_BACKGROUND ] );
X11_XFillRectangle( display, window, ctx, 0, 0, data->dialog_width, data->dialog_height );
X11_XSetForeground( display, ctx, data->color[ SDL_MESSAGEBOX_COLOR_TEXT ] );
for ( i = 0; i < data->numlines; i++ ) {
TextLineData *plinedata = &data->linedata[ i ];
if (SDL_X11_HAVE_UTF8) {
X11_Xutf8DrawString( display, window, data->font_set, ctx,
data->xtext, data->ytext + i * data->text_height,
plinedata->text, plinedata->length );
} else {
X11_XDrawString( display, window, ctx,
data->xtext, data->ytext + i * data->text_height,
plinedata->text, plinedata->length );
}
}
for ( i = 0; i < data->numbuttons; i++ ) {
SDL_MessageBoxButtonDataX11 *buttondatax11 = &data->buttonpos[ i ];
const SDL_MessageBoxButtonData *buttondata = buttondatax11->buttondata;
int border = ( buttondata->flags & SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT ) ? 2 : 0;
int offset = ( ( data->mouse_over_index == i ) && ( data->button_press_index == data->mouse_over_index ) ) ? 1 : 0;
X11_XSetForeground( display, ctx, data->color[ SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND ] );
X11_XFillRectangle( display, window, ctx,
buttondatax11->rect.x - border, buttondatax11->rect.y - border,
buttondatax11->rect.w + 2 * border, buttondatax11->rect.h + 2 * border );
X11_XSetForeground( display, ctx, data->color[ SDL_MESSAGEBOX_COLOR_BUTTON_BORDER ] );
X11_XDrawRectangle( display, window, ctx,
buttondatax11->rect.x, buttondatax11->rect.y,
buttondatax11->rect.w, buttondatax11->rect.h );
X11_XSetForeground( display, ctx, ( data->mouse_over_index == i ) ?
data->color[ SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED ] :
data->color[ SDL_MESSAGEBOX_COLOR_TEXT ] );
if (SDL_X11_HAVE_UTF8) {
X11_Xutf8DrawString( display, window, data->font_set, ctx,
buttondatax11->x + offset,
buttondatax11->y + offset,
buttondata->text, buttondatax11->length );
} else {
X11_XDrawString( display, window, ctx,
buttondatax11->x + offset, buttondatax11->y + offset,
buttondata->text, buttondatax11->length );
}
}
#if SDL_VIDEO_DRIVER_X11_XDBE
if (SDL_X11_HAVE_XDBE && data->xdbe) {
XdbeSwapInfo swap_info;
swap_info.swap_window = data->window;
swap_info.swap_action = XdbeUndefined;
X11_XdbeSwapBuffers(data->display, &swap_info, 1);
X11_XdbeEndIdiom(data->display);
}
#endif
}
static Bool
X11_MessageBoxEventTest(Display *display, XEvent *event, XPointer arg)
{
const SDL_MessageBoxDataX11 *data = (const SDL_MessageBoxDataX11 *) arg;
return ((event->xany.display == data->display) && (event->xany.window == data->window)) ? True : False;
}
/* Loop and handle message box event messages until something kills it. */
static int
X11_MessageBoxLoop( SDL_MessageBoxDataX11 *data )
{
GC ctx;
XGCValues ctx_vals;
SDL_bool close_dialog = SDL_FALSE;
SDL_bool has_focus = SDL_TRUE;
KeySym last_key_pressed = XK_VoidSymbol;
unsigned long gcflags = GCForeground | GCBackground;
SDL_zero(ctx_vals);
ctx_vals.foreground = data->color[ SDL_MESSAGEBOX_COLOR_BACKGROUND ];
ctx_vals.background = data->color[ SDL_MESSAGEBOX_COLOR_BACKGROUND ];
if (!SDL_X11_HAVE_UTF8) {
gcflags |= GCFont;
ctx_vals.font = data->font_struct->fid;
}
ctx = X11_XCreateGC( data->display, data->window, gcflags, &ctx_vals );
if ( ctx == None ) {
return SDL_SetError("Couldn't create graphics context");
}
data->button_press_index = -1; /* Reset what button is currently depressed. */
data->mouse_over_index = -1; /* Reset what button the mouse is over. */
while( !close_dialog ) {
XEvent e;
SDL_bool draw = SDL_TRUE;
/* can't use XWindowEvent() because it can't handle ClientMessage events. */
/* can't use XNextEvent() because we only want events for this window. */
X11_XIfEvent( data->display, &e, X11_MessageBoxEventTest, (XPointer) data );
/* If X11_XFilterEvent returns True, then some input method has filtered the
event, and the client should discard the event. */
if ( ( e.type != Expose ) && X11_XFilterEvent( &e, None ) )
continue;
switch( e.type ) {
case Expose:
if ( e.xexpose.count > 0 ) {
draw = SDL_FALSE;
}
break;
case FocusIn:
/* Got focus. */
has_focus = SDL_TRUE;
break;
case FocusOut:
/* lost focus. Reset button and mouse info. */
has_focus = SDL_FALSE;
data->button_press_index = -1;
data->mouse_over_index = -1;
break;
case MotionNotify:
if ( has_focus ) {
/* Mouse moved... */
const int previndex = data->mouse_over_index;
data->mouse_over_index = GetHitButtonIndex( data, e.xbutton.x, e.xbutton.y );
if (data->mouse_over_index == previndex) {
draw = SDL_FALSE;
}
}
break;
case ClientMessage:
if ( e.xclient.message_type == data->wm_protocols &&
e.xclient.format == 32 &&
e.xclient.data.l[ 0 ] == data->wm_delete_message ) {
close_dialog = SDL_TRUE;
}
break;
case KeyPress:
/* Store key press - we make sure in key release that we got both. */
last_key_pressed = X11_XLookupKeysym( &e.xkey, 0 );
break;
case KeyRelease: {
Uint32 mask = 0;
KeySym key = X11_XLookupKeysym( &e.xkey, 0 );
/* If this is a key release for something we didn't get the key down for, then bail. */
if ( key != last_key_pressed )
break;
if ( key == XK_Escape )
mask = SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT;
else if ( ( key == XK_Return ) || ( key == XK_KP_Enter ) )
mask = SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT;
if ( mask ) {
int i;
/* Look for first button with this mask set, and return it if found. */
for ( i = 0; i < data->numbuttons; i++ ) {
SDL_MessageBoxButtonDataX11 *buttondatax11 = &data->buttonpos[ i ];
if ( buttondatax11->buttondata->flags & mask ) {
*data->pbuttonid = buttondatax11->buttondata->buttonid;
close_dialog = SDL_TRUE;
break;
}
}
}
break;
}
case ButtonPress:
data->button_press_index = -1;
if ( e.xbutton.button == Button1 ) {
/* Find index of button they clicked on. */
data->button_press_index = GetHitButtonIndex( data, e.xbutton.x, e.xbutton.y );
}
break;
case ButtonRelease:
/* If button is released over the same button that was clicked down on, then return it. */
if ( ( e.xbutton.button == Button1 ) && ( data->button_press_index >= 0 ) ) {
int button = GetHitButtonIndex( data, e.xbutton.x, e.xbutton.y );
if ( data->button_press_index == button ) {
SDL_MessageBoxButtonDataX11 *buttondatax11 = &data->buttonpos[ button ];
*data->pbuttonid = buttondatax11->buttondata->buttonid;
close_dialog = SDL_TRUE;
}
}
data->button_press_index = -1;
break;
}
if ( draw ) {
/* Draw our dialog box. */
X11_MessageBoxDraw( data, ctx );
}
}
X11_XFreeGC( data->display, ctx );
return 0;
}
static int
X11_ShowMessageBoxImpl(const SDL_MessageBoxData *messageboxdata, int *buttonid)
{
int ret;
SDL_MessageBoxDataX11 data;
#if SDL_SET_LOCALE
char *origlocale;
#endif
SDL_zero(data);
if ( !SDL_X11_LoadSymbols() )
return -1;
#if SDL_SET_LOCALE
origlocale = setlocale(LC_ALL, NULL);
if (origlocale != NULL) {
origlocale = SDL_strdup(origlocale);
if (origlocale == NULL) {
return SDL_OutOfMemory();
}
setlocale(LC_ALL, "");
}
#endif
/* This code could get called from multiple threads maybe? */
X11_XInitThreads();
/* Initialize the return buttonid value to -1 (for error or dialogbox closed). */
*buttonid = -1;
/* Init and display the message box. */
ret = X11_MessageBoxInit( &data, messageboxdata, buttonid );
if ( ret != -1 ) {
ret = X11_MessageBoxInitPositions( &data );
if ( ret != -1 ) {
ret = X11_MessageBoxCreateWindow( &data );
if ( ret != -1 ) {
ret = X11_MessageBoxLoop( &data );
}
}
}
X11_MessageBoxShutdown( &data );
#if SDL_SET_LOCALE
if (origlocale) {
setlocale(LC_ALL, origlocale);
SDL_free(origlocale);
}
#endif
return ret;
}
/* Display an x11 message box. */
int
X11_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
{
#if SDL_FORK_MESSAGEBOX
/* Use a child process to protect against setlocale(). Annoying. */
pid_t pid;
int fds[2];
int status = 0;
if (pipe(fds) == -1) {
return X11_ShowMessageBoxImpl(messageboxdata, buttonid); /* oh well. */
}
pid = fork();
if (pid == -1) { /* failed */
close(fds[0]);
close(fds[1]);
return X11_ShowMessageBoxImpl(messageboxdata, buttonid); /* oh well. */
} else if (pid == 0) { /* we're the child */
int exitcode = 0;
close(fds[0]);
status = X11_ShowMessageBoxImpl(messageboxdata, buttonid);
if (write(fds[1], &status, sizeof (int)) != sizeof (int))
exitcode = 1;
else if (write(fds[1], buttonid, sizeof (int)) != sizeof (int))
exitcode = 1;
close(fds[1]);
_exit(exitcode); /* don't run atexit() stuff, static destructors, etc. */
} else { /* we're the parent */
pid_t rc;
close(fds[1]);
do {
rc = waitpid(pid, &status, 0);
} while ((rc == -1) && (errno == EINTR));
SDL_assert(rc == pid); /* not sure what to do if this fails. */
if ((rc == -1) || (!WIFEXITED(status)) || (WEXITSTATUS(status) != 0)) {
return SDL_SetError("msgbox child process failed");
}
if (read(fds[0], &status, sizeof (int)) != sizeof (int))
status = -1;
else if (read(fds[0], buttonid, sizeof (int)) != sizeof (int))
status = -1;
close(fds[0]);
return status;
}
#else
return X11_ShowMessageBoxImpl(messageboxdata, buttonid);
#endif
}
#endif /* SDL_VIDEO_DRIVER_X11 */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11messagebox.c | C | apache-2.0 | 32,448 |
/*
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_x11messagebox_h_
#define SDL_x11messagebox_h_
#if SDL_VIDEO_DRIVER_X11
extern int X11_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid);
#endif /* SDL_VIDEO_DRIVER_X11 */
#endif /* SDL_x11messagebox_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11messagebox.h | C | apache-2.0 | 1,219 |
/*
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_X11
#include "SDL_hints.h"
#include "SDL_x11video.h"
#include "SDL_timer.h"
#include "edid.h"
/* #define X11MODES_DEBUG */
/* I'm becoming more and more convinced that the application should never
* use XRandR, and it's the window manager's responsibility to track and
* manage display modes for fullscreen windows. Right now XRandR is completely
* broken with respect to window manager behavior on every window manager that
* I can find. For example, on Unity 3D if you show a fullscreen window while
* the resolution is changing (within ~250 ms) your window will retain the
* fullscreen state hint but be decorated and windowed.
*
* However, many people swear by it, so let them swear at it. :)
*/
/* #define XRANDR_DISABLED_BY_DEFAULT */
static int
get_visualinfo(Display * display, int screen, XVisualInfo * vinfo)
{
const char *visual_id = SDL_getenv("SDL_VIDEO_X11_VISUALID");
int depth;
/* Look for an exact visual, if requested */
if (visual_id) {
XVisualInfo *vi, template;
int nvis;
SDL_zero(template);
template.visualid = SDL_strtol(visual_id, NULL, 0);
vi = X11_XGetVisualInfo(display, VisualIDMask, &template, &nvis);
if (vi) {
*vinfo = *vi;
X11_XFree(vi);
return 0;
}
}
depth = DefaultDepth(display, screen);
if ((X11_UseDirectColorVisuals() &&
X11_XMatchVisualInfo(display, screen, depth, DirectColor, vinfo)) ||
X11_XMatchVisualInfo(display, screen, depth, TrueColor, vinfo) ||
X11_XMatchVisualInfo(display, screen, depth, PseudoColor, vinfo) ||
X11_XMatchVisualInfo(display, screen, depth, StaticColor, vinfo)) {
return 0;
}
return -1;
}
int
X11_GetVisualInfoFromVisual(Display * display, Visual * visual, XVisualInfo * vinfo)
{
XVisualInfo *vi;
int nvis;
vinfo->visualid = X11_XVisualIDFromVisual(visual);
vi = X11_XGetVisualInfo(display, VisualIDMask, vinfo, &nvis);
if (vi) {
*vinfo = *vi;
X11_XFree(vi);
return 0;
}
return -1;
}
Uint32
X11_GetPixelFormatFromVisualInfo(Display * display, XVisualInfo * vinfo)
{
if (vinfo->class == DirectColor || vinfo->class == TrueColor) {
int bpp;
Uint32 Rmask, Gmask, Bmask, Amask;
Rmask = vinfo->visual->red_mask;
Gmask = vinfo->visual->green_mask;
Bmask = vinfo->visual->blue_mask;
if (vinfo->depth == 32) {
Amask = (0xFFFFFFFF & ~(Rmask | Gmask | Bmask));
} else {
Amask = 0;
}
bpp = vinfo->depth;
if (bpp == 24) {
int i, n;
XPixmapFormatValues *p = X11_XListPixmapFormats(display, &n);
if (p) {
for (i = 0; i < n; ++i) {
if (p[i].depth == 24) {
bpp = p[i].bits_per_pixel;
break;
}
}
X11_XFree(p);
}
}
return SDL_MasksToPixelFormatEnum(bpp, Rmask, Gmask, Bmask, Amask);
}
if (vinfo->class == PseudoColor || vinfo->class == StaticColor) {
switch (vinfo->depth) {
case 8:
return SDL_PIXELTYPE_INDEX8;
case 4:
if (BitmapBitOrder(display) == LSBFirst) {
return SDL_PIXELFORMAT_INDEX4LSB;
} else {
return SDL_PIXELFORMAT_INDEX4MSB;
}
/* break; -Wunreachable-code-break */
case 1:
if (BitmapBitOrder(display) == LSBFirst) {
return SDL_PIXELFORMAT_INDEX1LSB;
} else {
return SDL_PIXELFORMAT_INDEX1MSB;
}
/* break; -Wunreachable-code-break */
}
}
return SDL_PIXELFORMAT_UNKNOWN;
}
#if SDL_VIDEO_DRIVER_X11_XINERAMA
static SDL_bool
CheckXinerama(Display * display, int *major, int *minor)
{
int event_base = 0;
int error_base = 0;
/* Default the extension not available */
*major = *minor = 0;
/* Allow environment override */
if (!SDL_GetHintBoolean(SDL_HINT_VIDEO_X11_XINERAMA, SDL_TRUE)) {
#ifdef X11MODES_DEBUG
printf("Xinerama disabled due to hint\n");
#endif
return SDL_FALSE;
}
if (!SDL_X11_HAVE_XINERAMA) {
#ifdef X11MODES_DEBUG
printf("Xinerama support not available\n");
#endif
return SDL_FALSE;
}
/* Query the extension version */
if (!X11_XineramaQueryExtension(display, &event_base, &error_base) ||
!X11_XineramaQueryVersion(display, major, minor) ||
!X11_XineramaIsActive(display)) {
#ifdef X11MODES_DEBUG
printf("Xinerama not active on the display\n");
#endif
return SDL_FALSE;
}
#ifdef X11MODES_DEBUG
printf("Xinerama available at version %d.%d!\n", *major, *minor);
#endif
return SDL_TRUE;
}
/* !!! FIXME: remove this later. */
/* we have a weird bug where XineramaQueryScreens() throws an X error, so this
is here to help track it down (and not crash, too!). */
static SDL_bool xinerama_triggered_error = SDL_FALSE;
static int
X11_XineramaFailed(Display * d, XErrorEvent * e)
{
xinerama_triggered_error = SDL_TRUE;
fprintf(stderr, "XINERAMA X ERROR: type=%d serial=%lu err=%u req=%u minor=%u\n",
e->type, e->serial, (unsigned int) e->error_code,
(unsigned int) e->request_code, (unsigned int) e->minor_code);
fflush(stderr);
return 0;
}
#endif /* SDL_VIDEO_DRIVER_X11_XINERAMA */
#if SDL_VIDEO_DRIVER_X11_XRANDR
static SDL_bool
CheckXRandR(Display * display, int *major, int *minor)
{
/* Default the extension not available */
*major = *minor = 0;
/* Allow environment override */
#ifdef XRANDR_DISABLED_BY_DEFAULT
if (!SDL_GetHintBoolean(SDL_HINT_VIDEO_X11_XRANDR, SDL_FALSE)) {
#ifdef X11MODES_DEBUG
printf("XRandR disabled by default due to window manager issues\n");
#endif
return SDL_FALSE;
}
#else
if (!SDL_GetHintBoolean(SDL_HINT_VIDEO_X11_XRANDR, SDL_TRUE)) {
#ifdef X11MODES_DEBUG
printf("XRandR disabled due to hint\n");
#endif
return SDL_FALSE;
}
#endif /* XRANDR_ENABLED_BY_DEFAULT */
if (!SDL_X11_HAVE_XRANDR) {
#ifdef X11MODES_DEBUG
printf("XRandR support not available\n");
#endif
return SDL_FALSE;
}
/* Query the extension version */
*major = 1; *minor = 3; /* we want 1.3 */
if (!X11_XRRQueryVersion(display, major, minor)) {
#ifdef X11MODES_DEBUG
printf("XRandR not active on the display\n");
#endif
*major = *minor = 0;
return SDL_FALSE;
}
#ifdef X11MODES_DEBUG
printf("XRandR available at version %d.%d!\n", *major, *minor);
#endif
return SDL_TRUE;
}
#define XRANDR_ROTATION_LEFT (1 << 1)
#define XRANDR_ROTATION_RIGHT (1 << 3)
static int
CalculateXRandRRefreshRate(const XRRModeInfo *info)
{
return (info->hTotal && info->vTotal) ?
round(((double)info->dotClock / (double)(info->hTotal * info->vTotal))) : 0;
}
static SDL_bool
SetXRandRModeInfo(Display *display, XRRScreenResources *res, RRCrtc crtc,
RRMode modeID, SDL_DisplayMode *mode)
{
int i;
for (i = 0; i < res->nmode; ++i) {
const XRRModeInfo *info = &res->modes[i];
if (info->id == modeID) {
XRRCrtcInfo *crtcinfo;
Rotation rotation = 0;
crtcinfo = X11_XRRGetCrtcInfo(display, res, crtc);
if (crtcinfo) {
rotation = crtcinfo->rotation;
X11_XRRFreeCrtcInfo(crtcinfo);
}
if (rotation & (XRANDR_ROTATION_LEFT|XRANDR_ROTATION_RIGHT)) {
mode->w = info->height;
mode->h = info->width;
} else {
mode->w = info->width;
mode->h = info->height;
}
mode->refresh_rate = CalculateXRandRRefreshRate(info);
((SDL_DisplayModeData*)mode->driverdata)->xrandr_mode = modeID;
#ifdef X11MODES_DEBUG
printf("XRandR mode %d: %dx%d@%dHz\n", (int) modeID, mode->w, mode->h, mode->refresh_rate);
#endif
return SDL_TRUE;
}
}
return SDL_FALSE;
}
static void
SetXRandRDisplayName(Display *dpy, Atom EDID, char *name, const size_t namelen, RROutput output, const unsigned long widthmm, const unsigned long heightmm)
{
/* See if we can get the EDID data for the real monitor name */
int inches;
int nprop;
Atom *props = X11_XRRListOutputProperties(dpy, output, &nprop);
int i;
for (i = 0; i < nprop; ++i) {
unsigned char *prop;
int actual_format;
unsigned long nitems, bytes_after;
Atom actual_type;
if (props[i] == EDID) {
if (X11_XRRGetOutputProperty(dpy, output, props[i], 0, 100, False,
False, AnyPropertyType, &actual_type,
&actual_format, &nitems, &bytes_after,
&prop) == Success) {
MonitorInfo *info = decode_edid(prop);
if (info) {
#ifdef X11MODES_DEBUG
printf("Found EDID data for %s\n", name);
dump_monitor_info(info);
#endif
SDL_strlcpy(name, info->dsc_product_name, namelen);
free(info);
}
X11_XFree(prop);
}
break;
}
}
if (props) {
X11_XFree(props);
}
inches = (int)((SDL_sqrtf(widthmm * widthmm + heightmm * heightmm) / 25.4f) + 0.5f);
if (*name && inches) {
const size_t len = SDL_strlen(name);
SDL_snprintf(&name[len], namelen-len, " %d\"", inches);
}
#ifdef X11MODES_DEBUG
printf("Display name: %s\n", name);
#endif
}
static int
X11_InitModes_XRandR(_THIS)
{
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
Display *dpy = data->display;
const int screencount = ScreenCount(dpy);
const int default_screen = DefaultScreen(dpy);
RROutput primary = X11_XRRGetOutputPrimary(dpy, RootWindow(dpy, default_screen));
Atom EDID = X11_XInternAtom(dpy, "EDID", False);
XRRScreenResources *res = NULL;
Uint32 pixelformat;
XVisualInfo vinfo;
XPixmapFormatValues *pixmapformats;
int looking_for_primary;
int scanline_pad;
int output;
int screen, i, n;
for (looking_for_primary = 1; looking_for_primary >= 0; looking_for_primary--) {
for (screen = 0; screen < screencount; screen++) {
/* we want the primary output first, and then skipped later. */
if (looking_for_primary && (screen != default_screen)) {
continue;
}
if (get_visualinfo(dpy, screen, &vinfo) < 0) {
continue; /* uh, skip this screen? */
}
pixelformat = X11_GetPixelFormatFromVisualInfo(dpy, &vinfo);
if (SDL_ISPIXELFORMAT_INDEXED(pixelformat)) {
continue; /* Palettized video modes are no longer supported */
}
scanline_pad = SDL_BYTESPERPIXEL(pixelformat) * 8;
pixmapformats = X11_XListPixmapFormats(dpy, &n);
if (pixmapformats) {
for (i = 0; i < n; ++i) {
if (pixmapformats[i].depth == vinfo.depth) {
scanline_pad = pixmapformats[i].scanline_pad;
break;
}
}
X11_XFree(pixmapformats);
}
res = X11_XRRGetScreenResourcesCurrent(dpy, RootWindow(dpy, screen));
if (!res || res->noutput == 0) {
if (res) {
X11_XRRFreeScreenResources(res);
}
res = X11_XRRGetScreenResources(dpy, RootWindow(dpy, screen));
if (!res) {
continue;
}
}
for (output = 0; output < res->noutput; output++) {
XRROutputInfo *output_info;
int display_x, display_y;
unsigned long display_mm_width, display_mm_height;
SDL_DisplayData *displaydata;
char display_name[128];
SDL_DisplayMode mode;
SDL_DisplayModeData *modedata;
SDL_VideoDisplay display;
RRMode modeID;
RRCrtc output_crtc;
XRRCrtcInfo *crtc;
/* The primary output _should_ always be sorted first, but just in case... */
if ((looking_for_primary && (res->outputs[output] != primary)) ||
(!looking_for_primary && (screen == default_screen) && (res->outputs[output] == primary))) {
continue;
}
output_info = X11_XRRGetOutputInfo(dpy, res, res->outputs[output]);
if (!output_info || !output_info->crtc || output_info->connection == RR_Disconnected) {
X11_XRRFreeOutputInfo(output_info);
continue;
}
SDL_strlcpy(display_name, output_info->name, sizeof(display_name));
display_mm_width = output_info->mm_width;
display_mm_height = output_info->mm_height;
output_crtc = output_info->crtc;
X11_XRRFreeOutputInfo(output_info);
crtc = X11_XRRGetCrtcInfo(dpy, res, output_crtc);
if (!crtc) {
continue;
}
SDL_zero(mode);
modeID = crtc->mode;
mode.w = crtc->width;
mode.h = crtc->height;
mode.format = pixelformat;
display_x = crtc->x;
display_y = crtc->y;
X11_XRRFreeCrtcInfo(crtc);
displaydata = (SDL_DisplayData *) SDL_calloc(1, sizeof(*displaydata));
if (!displaydata) {
return SDL_OutOfMemory();
}
modedata = (SDL_DisplayModeData *) SDL_calloc(1, sizeof(SDL_DisplayModeData));
if (!modedata) {
SDL_free(displaydata);
return SDL_OutOfMemory();
}
modedata->xrandr_mode = modeID;
mode.driverdata = modedata;
displaydata->screen = screen;
displaydata->visual = vinfo.visual;
displaydata->depth = vinfo.depth;
displaydata->hdpi = display_mm_width ? (((float) mode.w) * 25.4f / display_mm_width) : 0.0f;
displaydata->vdpi = display_mm_height ? (((float) mode.h) * 25.4f / display_mm_height) : 0.0f;
displaydata->ddpi = SDL_ComputeDiagonalDPI(mode.w, mode.h, ((float) display_mm_width) / 25.4f,((float) display_mm_height) / 25.4f);
displaydata->scanline_pad = scanline_pad;
displaydata->x = display_x;
displaydata->y = display_y;
displaydata->use_xrandr = 1;
displaydata->xrandr_output = res->outputs[output];
SetXRandRModeInfo(dpy, res, output_crtc, modeID, &mode);
SetXRandRDisplayName(dpy, EDID, display_name, sizeof (display_name), res->outputs[output], display_mm_width, display_mm_height);
SDL_zero(display);
if (*display_name) {
display.name = display_name;
}
display.desktop_mode = mode;
display.current_mode = mode;
display.driverdata = displaydata;
SDL_AddVideoDisplay(&display);
}
X11_XRRFreeScreenResources(res);
}
}
if (_this->num_displays == 0) {
return SDL_SetError("No available displays");
}
return 0;
}
#endif /* SDL_VIDEO_DRIVER_X11_XRANDR */
#if SDL_VIDEO_DRIVER_X11_XVIDMODE
static SDL_bool
CheckVidMode(Display * display, int *major, int *minor)
{
int vm_event, vm_error = -1;
/* Default the extension not available */
*major = *minor = 0;
/* Allow environment override */
if (!SDL_GetHintBoolean(SDL_HINT_VIDEO_X11_XVIDMODE, SDL_TRUE)) {
#ifdef X11MODES_DEBUG
printf("XVidMode disabled due to hint\n");
#endif
return SDL_FALSE;
}
if (!SDL_X11_HAVE_XVIDMODE) {
#ifdef X11MODES_DEBUG
printf("XVidMode support not available\n");
#endif
return SDL_FALSE;
}
/* Query the extension version */
if (!X11_XF86VidModeQueryExtension(display, &vm_event, &vm_error)
|| !X11_XF86VidModeQueryVersion(display, major, minor)) {
#ifdef X11MODES_DEBUG
printf("XVidMode not active on the display\n");
#endif
return SDL_FALSE;
}
#ifdef X11MODES_DEBUG
printf("XVidMode available at version %d.%d!\n", *major, *minor);
#endif
return SDL_TRUE;
}
static
Bool XF86VidModeGetModeInfo(Display * dpy, int scr,
XF86VidModeModeInfo* info)
{
Bool retval;
int dotclock;
XF86VidModeModeLine l;
SDL_zerop(info);
SDL_zero(l);
retval = X11_XF86VidModeGetModeLine(dpy, scr, &dotclock, &l);
info->dotclock = dotclock;
info->hdisplay = l.hdisplay;
info->hsyncstart = l.hsyncstart;
info->hsyncend = l.hsyncend;
info->htotal = l.htotal;
info->hskew = l.hskew;
info->vdisplay = l.vdisplay;
info->vsyncstart = l.vsyncstart;
info->vsyncend = l.vsyncend;
info->vtotal = l.vtotal;
info->flags = l.flags;
info->privsize = l.privsize;
info->private = l.private;
return retval;
}
static int
CalculateXVidModeRefreshRate(const XF86VidModeModeInfo * info)
{
return (info->htotal
&& info->vtotal) ? (1000 * info->dotclock / (info->htotal *
info->vtotal)) : 0;
}
static SDL_bool
SetXVidModeModeInfo(const XF86VidModeModeInfo *info, SDL_DisplayMode *mode)
{
mode->w = info->hdisplay;
mode->h = info->vdisplay;
mode->refresh_rate = CalculateXVidModeRefreshRate(info);
((SDL_DisplayModeData*)mode->driverdata)->vm_mode = *info;
return SDL_TRUE;
}
#endif /* SDL_VIDEO_DRIVER_X11_XVIDMODE */
int
X11_InitModes(_THIS)
{
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
int snum, screen, screencount = 0;
#if SDL_VIDEO_DRIVER_X11_XINERAMA
int xinerama_major, xinerama_minor;
int use_xinerama = 0;
XineramaScreenInfo *xinerama = NULL;
#endif
#if SDL_VIDEO_DRIVER_X11_XRANDR
int xrandr_major, xrandr_minor;
#endif
#if SDL_VIDEO_DRIVER_X11_XVIDMODE
int vm_major, vm_minor;
int use_vidmode = 0;
#endif
/* XRandR is the One True Modern Way to do this on X11. If it's enabled and
available, don't even look at other ways of doing things. */
#if SDL_VIDEO_DRIVER_X11_XRANDR
/* require at least XRandR v1.3 */
if (CheckXRandR(data->display, &xrandr_major, &xrandr_minor) &&
(xrandr_major >= 2 || (xrandr_major == 1 && xrandr_minor >= 3))) {
if (X11_InitModes_XRandR(_this) == 0)
return 0;
}
#endif /* SDL_VIDEO_DRIVER_X11_XRANDR */
/* !!! FIXME: eventually remove support for Xinerama and XVidMode (everything below here). */
/* This is a workaround for some apps (UnrealEngine4, for example) until
we sort out the ramifications of removing XVidMode support outright.
This block should be removed with the XVidMode support. */
{
if (SDL_GetHintBoolean("SDL_VIDEO_X11_REQUIRE_XRANDR", SDL_FALSE)) {
#if SDL_VIDEO_DRIVER_X11_XRANDR
return SDL_SetError("XRandR support is required but not available");
#else
return SDL_SetError("XRandR support is required but not built into SDL!");
#endif
}
}
#if SDL_VIDEO_DRIVER_X11_XINERAMA
/* Query Xinerama extention
* NOTE: This works with Nvidia Twinview correctly, but you need version 302.17 (released on June 2012)
* or newer of the Nvidia binary drivers
*/
if (CheckXinerama(data->display, &xinerama_major, &xinerama_minor)) {
int (*handler) (Display *, XErrorEvent *);
X11_XSync(data->display, False);
handler = X11_XSetErrorHandler(X11_XineramaFailed);
xinerama = X11_XineramaQueryScreens(data->display, &screencount);
X11_XSync(data->display, False);
X11_XSetErrorHandler(handler);
if (xinerama_triggered_error) {
xinerama = 0;
}
if (xinerama) {
use_xinerama = xinerama_major * 100 + xinerama_minor;
}
}
if (!xinerama) {
screencount = ScreenCount(data->display);
}
#else
screencount = ScreenCount(data->display);
#endif /* SDL_VIDEO_DRIVER_X11_XINERAMA */
#if SDL_VIDEO_DRIVER_X11_XVIDMODE
if (CheckVidMode(data->display, &vm_major, &vm_minor)) {
use_vidmode = vm_major * 100 + vm_minor;
}
#endif /* SDL_VIDEO_DRIVER_X11_XVIDMODE */
for (snum = 0; snum < screencount; ++snum) {
XVisualInfo vinfo;
SDL_VideoDisplay display;
SDL_DisplayData *displaydata;
SDL_DisplayMode mode;
SDL_DisplayModeData *modedata;
XPixmapFormatValues *pixmapFormats;
char display_name[128];
int i, n;
/* Re-order screens to always put default screen first */
if (snum == 0) {
screen = DefaultScreen(data->display);
} else if (snum == DefaultScreen(data->display)) {
screen = 0;
} else {
screen = snum;
}
#if SDL_VIDEO_DRIVER_X11_XINERAMA
if (xinerama) {
if (get_visualinfo(data->display, 0, &vinfo) < 0) {
continue;
}
} else {
if (get_visualinfo(data->display, screen, &vinfo) < 0) {
continue;
}
}
#else
if (get_visualinfo(data->display, screen, &vinfo) < 0) {
continue;
}
#endif
displaydata = (SDL_DisplayData *) SDL_calloc(1, sizeof(*displaydata));
if (!displaydata) {
continue;
}
display_name[0] = '\0';
mode.format = X11_GetPixelFormatFromVisualInfo(data->display, &vinfo);
if (SDL_ISPIXELFORMAT_INDEXED(mode.format)) {
/* We don't support palettized modes now */
SDL_free(displaydata);
continue;
}
#if SDL_VIDEO_DRIVER_X11_XINERAMA
if (xinerama) {
mode.w = xinerama[screen].width;
mode.h = xinerama[screen].height;
} else {
mode.w = DisplayWidth(data->display, screen);
mode.h = DisplayHeight(data->display, screen);
}
#else
mode.w = DisplayWidth(data->display, screen);
mode.h = DisplayHeight(data->display, screen);
#endif
mode.refresh_rate = 0;
modedata = (SDL_DisplayModeData *) SDL_calloc(1, sizeof(SDL_DisplayModeData));
if (!modedata) {
SDL_free(displaydata);
continue;
}
mode.driverdata = modedata;
#if SDL_VIDEO_DRIVER_X11_XINERAMA
/* Most of SDL's calls to X11 are unwaware of Xinerama, and to X11 standard calls, when Xinerama is active,
* there's only one screen available. So we force the screen number to zero and
* let Xinerama specific code handle specific functionality using displaydata->xinerama_info
*/
if (use_xinerama) {
displaydata->screen = 0;
displaydata->use_xinerama = use_xinerama;
displaydata->xinerama_info = xinerama[screen];
displaydata->xinerama_screen = screen;
}
else displaydata->screen = screen;
#else
displaydata->screen = screen;
#endif
displaydata->visual = vinfo.visual;
displaydata->depth = vinfo.depth;
/* We use the displaydata screen index here so that this works
for both the Xinerama case, where we get the overall DPI,
and the regular X11 screen info case. */
displaydata->hdpi = (float)DisplayWidth(data->display, displaydata->screen) * 25.4f /
DisplayWidthMM(data->display, displaydata->screen);
displaydata->vdpi = (float)DisplayHeight(data->display, displaydata->screen) * 25.4f /
DisplayHeightMM(data->display, displaydata->screen);
displaydata->ddpi = SDL_ComputeDiagonalDPI(DisplayWidth(data->display, displaydata->screen),
DisplayHeight(data->display, displaydata->screen),
(float)DisplayWidthMM(data->display, displaydata->screen) / 25.4f,
(float)DisplayHeightMM(data->display, displaydata->screen) / 25.4f);
displaydata->scanline_pad = SDL_BYTESPERPIXEL(mode.format) * 8;
pixmapFormats = X11_XListPixmapFormats(data->display, &n);
if (pixmapFormats) {
for (i = 0; i < n; ++i) {
if (pixmapFormats[i].depth == displaydata->depth) {
displaydata->scanline_pad = pixmapFormats[i].scanline_pad;
break;
}
}
X11_XFree(pixmapFormats);
}
#if SDL_VIDEO_DRIVER_X11_XINERAMA
if (use_xinerama) {
displaydata->x = xinerama[screen].x_org;
displaydata->y = xinerama[screen].y_org;
}
else
#endif
{
displaydata->x = 0;
displaydata->y = 0;
}
#if SDL_VIDEO_DRIVER_X11_XVIDMODE
if (!displaydata->use_xrandr &&
#if SDL_VIDEO_DRIVER_X11_XINERAMA
/* XVidMode only works on the screen at the origin */
(!displaydata->use_xinerama ||
(displaydata->x == 0 && displaydata->y == 0)) &&
#endif
use_vidmode) {
displaydata->use_vidmode = use_vidmode;
if (displaydata->use_xinerama) {
displaydata->vidmode_screen = 0;
} else {
displaydata->vidmode_screen = screen;
}
XF86VidModeGetModeInfo(data->display, displaydata->vidmode_screen, &modedata->vm_mode);
}
#endif /* SDL_VIDEO_DRIVER_X11_XVIDMODE */
SDL_zero(display);
if (*display_name) {
display.name = display_name;
}
display.desktop_mode = mode;
display.current_mode = mode;
display.driverdata = displaydata;
SDL_AddVideoDisplay(&display);
}
#if SDL_VIDEO_DRIVER_X11_XINERAMA
if (xinerama) X11_XFree(xinerama);
#endif
if (_this->num_displays == 0) {
return SDL_SetError("No available displays");
}
return 0;
}
void
X11_GetDisplayModes(_THIS, SDL_VideoDisplay * sdl_display)
{
Display *display = ((SDL_VideoData *) _this->driverdata)->display;
SDL_DisplayData *data = (SDL_DisplayData *) sdl_display->driverdata;
#if SDL_VIDEO_DRIVER_X11_XVIDMODE
int nmodes;
XF86VidModeModeInfo ** modes;
#endif
SDL_DisplayMode mode;
/* Unfortunately X11 requires the window to be created with the correct
* visual and depth ahead of time, but the SDL API allows you to create
* a window before setting the fullscreen display mode. This means that
* we have to use the same format for all windows and all display modes.
* (or support recreating the window with a new visual behind the scenes)
*/
mode.format = sdl_display->current_mode.format;
mode.driverdata = NULL;
#if SDL_VIDEO_DRIVER_X11_XINERAMA
if (data->use_xinerama) {
int screen_w;
int screen_h;
screen_w = DisplayWidth(display, data->screen);
screen_h = DisplayHeight(display, data->screen);
if (data->use_vidmode && !data->xinerama_info.x_org && !data->xinerama_info.y_org &&
(screen_w > data->xinerama_info.width || screen_h > data->xinerama_info.height)) {
SDL_DisplayModeData *modedata;
/* Add the full (both screens combined) xinerama mode only on the display that starts at 0,0
* if we're using vidmode.
*/
mode.w = screen_w;
mode.h = screen_h;
mode.refresh_rate = 0;
modedata = (SDL_DisplayModeData *) SDL_calloc(1, sizeof(SDL_DisplayModeData));
if (modedata) {
*modedata = *(SDL_DisplayModeData *)sdl_display->desktop_mode.driverdata;
}
mode.driverdata = modedata;
if (!SDL_AddDisplayMode(sdl_display, &mode)) {
SDL_free(modedata);
}
}
else if (!data->use_xrandr)
{
SDL_DisplayModeData *modedata;
/* Add the current mode of each monitor otherwise if we can't get them from xrandr */
mode.w = data->xinerama_info.width;
mode.h = data->xinerama_info.height;
mode.refresh_rate = 0;
modedata = (SDL_DisplayModeData *) SDL_calloc(1, sizeof(SDL_DisplayModeData));
if (modedata) {
*modedata = *(SDL_DisplayModeData *)sdl_display->desktop_mode.driverdata;
}
mode.driverdata = modedata;
if (!SDL_AddDisplayMode(sdl_display, &mode)) {
SDL_free(modedata);
}
}
}
#endif /* SDL_VIDEO_DRIVER_X11_XINERAMA */
#if SDL_VIDEO_DRIVER_X11_XRANDR
if (data->use_xrandr) {
XRRScreenResources *res;
res = X11_XRRGetScreenResources (display, RootWindow(display, data->screen));
if (res) {
SDL_DisplayModeData *modedata;
XRROutputInfo *output_info;
int i;
output_info = X11_XRRGetOutputInfo(display, res, data->xrandr_output);
if (output_info && output_info->connection != RR_Disconnected) {
for (i = 0; i < output_info->nmode; ++i) {
modedata = (SDL_DisplayModeData *) SDL_calloc(1, sizeof(SDL_DisplayModeData));
if (!modedata) {
continue;
}
mode.driverdata = modedata;
if (!SetXRandRModeInfo(display, res, output_info->crtc, output_info->modes[i], &mode) ||
!SDL_AddDisplayMode(sdl_display, &mode)) {
SDL_free(modedata);
}
}
}
X11_XRRFreeOutputInfo(output_info);
X11_XRRFreeScreenResources(res);
}
return;
}
#endif /* SDL_VIDEO_DRIVER_X11_XRANDR */
#if SDL_VIDEO_DRIVER_X11_XVIDMODE
if (data->use_vidmode &&
X11_XF86VidModeGetAllModeLines(display, data->vidmode_screen, &nmodes, &modes)) {
int i;
SDL_DisplayModeData *modedata;
#ifdef X11MODES_DEBUG
printf("VidMode modes: (unsorted)\n");
for (i = 0; i < nmodes; ++i) {
printf("Mode %d: %d x %d @ %d, flags: 0x%x\n", i,
modes[i]->hdisplay, modes[i]->vdisplay,
CalculateXVidModeRefreshRate(modes[i]), modes[i]->flags);
}
#endif
for (i = 0; i < nmodes; ++i) {
modedata = (SDL_DisplayModeData *) SDL_calloc(1, sizeof(SDL_DisplayModeData));
if (!modedata) {
continue;
}
mode.driverdata = modedata;
if (!SetXVidModeModeInfo(modes[i], &mode) || !SDL_AddDisplayMode(sdl_display, &mode)) {
SDL_free(modedata);
}
}
X11_XFree(modes);
return;
}
#endif /* SDL_VIDEO_DRIVER_X11_XVIDMODE */
if (!data->use_xrandr && !data->use_vidmode) {
SDL_DisplayModeData *modedata;
/* Add the desktop mode */
mode = sdl_display->desktop_mode;
modedata = (SDL_DisplayModeData *) SDL_calloc(1, sizeof(SDL_DisplayModeData));
if (modedata) {
*modedata = *(SDL_DisplayModeData *)sdl_display->desktop_mode.driverdata;
}
mode.driverdata = modedata;
if (!SDL_AddDisplayMode(sdl_display, &mode)) {
SDL_free(modedata);
}
}
}
int
X11_SetDisplayMode(_THIS, SDL_VideoDisplay * sdl_display, SDL_DisplayMode * mode)
{
SDL_VideoData *viddata = (SDL_VideoData *) _this->driverdata;
Display *display = viddata->display;
SDL_DisplayData *data = (SDL_DisplayData *) sdl_display->driverdata;
SDL_DisplayModeData *modedata = (SDL_DisplayModeData *)mode->driverdata;
viddata->last_mode_change_deadline = SDL_GetTicks() + (PENDING_FOCUS_TIME * 2);
#if SDL_VIDEO_DRIVER_X11_XRANDR
if (data->use_xrandr) {
XRRScreenResources *res;
XRROutputInfo *output_info;
XRRCrtcInfo *crtc;
Status status;
res = X11_XRRGetScreenResources (display, RootWindow(display, data->screen));
if (!res) {
return SDL_SetError("Couldn't get XRandR screen resources");
}
output_info = X11_XRRGetOutputInfo(display, res, data->xrandr_output);
if (!output_info || output_info->connection == RR_Disconnected) {
X11_XRRFreeScreenResources(res);
return SDL_SetError("Couldn't get XRandR output info");
}
crtc = X11_XRRGetCrtcInfo(display, res, output_info->crtc);
if (!crtc) {
X11_XRRFreeOutputInfo(output_info);
X11_XRRFreeScreenResources(res);
return SDL_SetError("Couldn't get XRandR crtc info");
}
status = X11_XRRSetCrtcConfig (display, res, output_info->crtc, CurrentTime,
crtc->x, crtc->y, modedata->xrandr_mode, crtc->rotation,
&data->xrandr_output, 1);
X11_XRRFreeCrtcInfo(crtc);
X11_XRRFreeOutputInfo(output_info);
X11_XRRFreeScreenResources(res);
if (status != Success) {
return SDL_SetError("X11_XRRSetCrtcConfig failed");
}
}
#endif /* SDL_VIDEO_DRIVER_X11_XRANDR */
#if SDL_VIDEO_DRIVER_X11_XVIDMODE
if (data->use_vidmode) {
X11_XF86VidModeSwitchToMode(display, data->vidmode_screen, &modedata->vm_mode);
}
#endif /* SDL_VIDEO_DRIVER_X11_XVIDMODE */
return 0;
}
void
X11_QuitModes(_THIS)
{
}
int
X11_GetDisplayBounds(_THIS, SDL_VideoDisplay * sdl_display, SDL_Rect * rect)
{
SDL_DisplayData *data = (SDL_DisplayData *) sdl_display->driverdata;
rect->x = data->x;
rect->y = data->y;
rect->w = sdl_display->current_mode.w;
rect->h = sdl_display->current_mode.h;
#if SDL_VIDEO_DRIVER_X11_XINERAMA
/* Get the real current bounds of the display */
if (data->use_xinerama) {
Display *display = ((SDL_VideoData *) _this->driverdata)->display;
int screencount;
XineramaScreenInfo *xinerama = X11_XineramaQueryScreens(display, &screencount);
if (xinerama) {
rect->x = xinerama[data->xinerama_screen].x_org;
rect->y = xinerama[data->xinerama_screen].y_org;
X11_XFree(xinerama);
}
}
#endif /* SDL_VIDEO_DRIVER_X11_XINERAMA */
return 0;
}
int
X11_GetDisplayDPI(_THIS, SDL_VideoDisplay * sdl_display, float * ddpi, float * hdpi, float * vdpi)
{
SDL_DisplayData *data = (SDL_DisplayData *) sdl_display->driverdata;
if (ddpi) {
*ddpi = data->ddpi;
}
if (hdpi) {
*hdpi = data->hdpi;
}
if (vdpi) {
*vdpi = data->vdpi;
}
return data->ddpi != 0.0f ? 0 : SDL_SetError("Couldn't get DPI");
}
int
X11_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * sdl_display, SDL_Rect * rect)
{
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
Display *display = data->display;
Atom _NET_WORKAREA;
int status, real_format;
int retval = -1;
Atom real_type;
unsigned long items_read = 0, items_left = 0;
unsigned char *propdata = NULL;
if (X11_GetDisplayBounds(_this, sdl_display, rect) < 0) {
return -1;
}
_NET_WORKAREA = X11_XInternAtom(display, "_NET_WORKAREA", False);
status = X11_XGetWindowProperty(display, DefaultRootWindow(display),
_NET_WORKAREA, 0L, 4L, False, XA_CARDINAL,
&real_type, &real_format, &items_read,
&items_left, &propdata);
if ((status == Success) && (items_read >= 4)) {
const long *p = (long*) propdata;
const SDL_Rect usable = { (int)p[0], (int)p[1], (int)p[2], (int)p[3] };
retval = 0;
if (!SDL_IntersectRect(rect, &usable, rect)) {
SDL_zerop(rect);
}
}
if (propdata) {
X11_XFree(propdata);
}
return retval;
}
#endif /* SDL_VIDEO_DRIVER_X11 */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11modes.c | C | apache-2.0 | 37,649 |
/*
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_x11modes_h_
#define SDL_x11modes_h_
typedef struct
{
int screen;
Visual *visual;
int depth;
int scanline_pad;
int x;
int y;
float ddpi;
float hdpi;
float vdpi;
int use_xinerama;
int use_xrandr;
int use_vidmode;
#if SDL_VIDEO_DRIVER_X11_XINERAMA
XineramaScreenInfo xinerama_info;
int xinerama_screen;
#endif
#if SDL_VIDEO_DRIVER_X11_XRANDR
RROutput xrandr_output;
#endif
#if SDL_VIDEO_DRIVER_X11_XVIDMODE
int vidmode_screen;
#endif
} SDL_DisplayData;
typedef struct
{
#if SDL_VIDEO_DRIVER_X11_XRANDR
RRMode xrandr_mode;
#endif
#if SDL_VIDEO_DRIVER_X11_XVIDMODE
XF86VidModeModeInfo vm_mode;
#endif
} SDL_DisplayModeData;
extern int X11_InitModes(_THIS);
extern void X11_GetDisplayModes(_THIS, SDL_VideoDisplay * display);
extern int X11_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode);
extern void X11_QuitModes(_THIS);
/* Some utility functions for working with visuals */
extern int X11_GetVisualInfoFromVisual(Display * display, Visual * visual,
XVisualInfo * vinfo);
extern Uint32 X11_GetPixelFormatFromVisualInfo(Display * display,
XVisualInfo * vinfo);
extern int X11_GetDisplayBounds(_THIS, SDL_VideoDisplay * sdl_display, SDL_Rect * rect);
extern int X11_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * sdl_display, SDL_Rect * rect);
extern int X11_GetDisplayDPI(_THIS, SDL_VideoDisplay * sdl_display, float * ddpi, float * hdpi, float * vdpi);
#endif /* SDL_x11modes_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11modes.h | C | apache-2.0 | 2,597 |
/*
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_X11
#include <X11/cursorfont.h>
#include "SDL_assert.h"
#include "SDL_x11video.h"
#include "SDL_x11mouse.h"
#include "SDL_x11xinput2.h"
#include "../../events/SDL_mouse_c.h"
/* FIXME: Find a better place to put this... */
static Cursor x11_empty_cursor = None;
static Display *
GetDisplay(void)
{
return ((SDL_VideoData *)SDL_GetVideoDevice()->driverdata)->display;
}
static Cursor
X11_CreateEmptyCursor()
{
if (x11_empty_cursor == None) {
Display *display = GetDisplay();
char data[1];
XColor color;
Pixmap pixmap;
SDL_zeroa(data);
color.red = color.green = color.blue = 0;
pixmap = X11_XCreateBitmapFromData(display, DefaultRootWindow(display),
data, 1, 1);
if (pixmap) {
x11_empty_cursor = X11_XCreatePixmapCursor(display, pixmap, pixmap,
&color, &color, 0, 0);
X11_XFreePixmap(display, pixmap);
}
}
return x11_empty_cursor;
}
static void
X11_DestroyEmptyCursor(void)
{
if (x11_empty_cursor != None) {
X11_XFreeCursor(GetDisplay(), x11_empty_cursor);
x11_empty_cursor = None;
}
}
static SDL_Cursor *
X11_CreateDefaultCursor()
{
SDL_Cursor *cursor;
cursor = SDL_calloc(1, sizeof(*cursor));
if (cursor) {
/* None is used to indicate the default cursor */
cursor->driverdata = (void*)None;
} else {
SDL_OutOfMemory();
}
return cursor;
}
#if SDL_VIDEO_DRIVER_X11_XCURSOR
static Cursor
X11_CreateXCursorCursor(SDL_Surface * surface, int hot_x, int hot_y)
{
Display *display = GetDisplay();
Cursor cursor = None;
XcursorImage *image;
image = X11_XcursorImageCreate(surface->w, surface->h);
if (!image) {
SDL_OutOfMemory();
return None;
}
image->xhot = hot_x;
image->yhot = hot_y;
image->delay = 0;
SDL_assert(surface->format->format == SDL_PIXELFORMAT_ARGB8888);
SDL_assert(surface->pitch == surface->w * 4);
SDL_memcpy(image->pixels, surface->pixels, surface->h * surface->pitch);
cursor = X11_XcursorImageLoadCursor(display, image);
X11_XcursorImageDestroy(image);
return cursor;
}
#endif /* SDL_VIDEO_DRIVER_X11_XCURSOR */
static Cursor
X11_CreatePixmapCursor(SDL_Surface * surface, int hot_x, int hot_y)
{
Display *display = GetDisplay();
XColor fg, bg;
Cursor cursor = None;
Uint32 *ptr;
Uint8 *data_bits, *mask_bits;
Pixmap data_pixmap, mask_pixmap;
int x, y;
unsigned int rfg, gfg, bfg, rbg, gbg, bbg, fgBits, bgBits;
unsigned int width_bytes = ((surface->w + 7) & ~7) / 8;
data_bits = SDL_calloc(1, surface->h * width_bytes);
if (!data_bits) {
SDL_OutOfMemory();
return None;
}
mask_bits = SDL_calloc(1, surface->h * width_bytes);
if (!mask_bits) {
SDL_free(data_bits);
SDL_OutOfMemory();
return None;
}
/* Code below assumes ARGB pixel format */
SDL_assert(surface->format->format == SDL_PIXELFORMAT_ARGB8888);
rfg = gfg = bfg = rbg = gbg = bbg = fgBits = bgBits = 0;
for (y = 0; y < surface->h; ++y) {
ptr = (Uint32 *)((Uint8 *)surface->pixels + y * surface->pitch);
for (x = 0; x < surface->w; ++x) {
int alpha = (*ptr >> 24) & 0xff;
int red = (*ptr >> 16) & 0xff;
int green = (*ptr >> 8) & 0xff;
int blue = (*ptr >> 0) & 0xff;
if (alpha > 25) {
mask_bits[y * width_bytes + x / 8] |= (0x01 << (x % 8));
if ((red + green + blue) > 0x40) {
fgBits++;
rfg += red;
gfg += green;
bfg += blue;
data_bits[y * width_bytes + x / 8] |= (0x01 << (x % 8));
} else {
bgBits++;
rbg += red;
gbg += green;
bbg += blue;
}
}
++ptr;
}
}
if (fgBits) {
fg.red = rfg * 257 / fgBits;
fg.green = gfg * 257 / fgBits;
fg.blue = bfg * 257 / fgBits;
}
else fg.red = fg.green = fg.blue = 0;
if (bgBits) {
bg.red = rbg * 257 / bgBits;
bg.green = gbg * 257 / bgBits;
bg.blue = bbg * 257 / bgBits;
}
else bg.red = bg.green = bg.blue = 0;
data_pixmap = X11_XCreateBitmapFromData(display, DefaultRootWindow(display),
(char*)data_bits,
surface->w, surface->h);
mask_pixmap = X11_XCreateBitmapFromData(display, DefaultRootWindow(display),
(char*)mask_bits,
surface->w, surface->h);
cursor = X11_XCreatePixmapCursor(display, data_pixmap, mask_pixmap,
&fg, &bg, hot_x, hot_y);
X11_XFreePixmap(display, data_pixmap);
X11_XFreePixmap(display, mask_pixmap);
return cursor;
}
static SDL_Cursor *
X11_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y)
{
SDL_Cursor *cursor;
cursor = SDL_calloc(1, sizeof(*cursor));
if (cursor) {
Cursor x11_cursor = None;
#if SDL_VIDEO_DRIVER_X11_XCURSOR
if (SDL_X11_HAVE_XCURSOR) {
x11_cursor = X11_CreateXCursorCursor(surface, hot_x, hot_y);
}
#endif
if (x11_cursor == None) {
x11_cursor = X11_CreatePixmapCursor(surface, hot_x, hot_y);
}
cursor->driverdata = (void*)x11_cursor;
} else {
SDL_OutOfMemory();
}
return cursor;
}
static SDL_Cursor *
X11_CreateSystemCursor(SDL_SystemCursor id)
{
SDL_Cursor *cursor;
unsigned int shape;
switch(id)
{
default:
SDL_assert(0);
return NULL;
/* X Font Cursors reference: */
/* http://tronche.com/gui/x/xlib/appendix/b/ */
case SDL_SYSTEM_CURSOR_ARROW: shape = XC_left_ptr; break;
case SDL_SYSTEM_CURSOR_IBEAM: shape = XC_xterm; break;
case SDL_SYSTEM_CURSOR_WAIT: shape = XC_watch; break;
case SDL_SYSTEM_CURSOR_CROSSHAIR: shape = XC_tcross; break;
case SDL_SYSTEM_CURSOR_WAITARROW: shape = XC_watch; break;
case SDL_SYSTEM_CURSOR_SIZENWSE: shape = XC_fleur; break;
case SDL_SYSTEM_CURSOR_SIZENESW: shape = XC_fleur; break;
case SDL_SYSTEM_CURSOR_SIZEWE: shape = XC_sb_h_double_arrow; break;
case SDL_SYSTEM_CURSOR_SIZENS: shape = XC_sb_v_double_arrow; break;
case SDL_SYSTEM_CURSOR_SIZEALL: shape = XC_fleur; break;
case SDL_SYSTEM_CURSOR_NO: shape = XC_pirate; break;
case SDL_SYSTEM_CURSOR_HAND: shape = XC_hand2; break;
}
cursor = SDL_calloc(1, sizeof(*cursor));
if (cursor) {
Cursor x11_cursor;
x11_cursor = X11_XCreateFontCursor(GetDisplay(), shape);
cursor->driverdata = (void*)x11_cursor;
} else {
SDL_OutOfMemory();
}
return cursor;
}
static void
X11_FreeCursor(SDL_Cursor * cursor)
{
Cursor x11_cursor = (Cursor)cursor->driverdata;
if (x11_cursor != None) {
X11_XFreeCursor(GetDisplay(), x11_cursor);
}
SDL_free(cursor);
}
static int
X11_ShowCursor(SDL_Cursor * cursor)
{
Cursor x11_cursor = 0;
if (cursor) {
x11_cursor = (Cursor)cursor->driverdata;
} else {
x11_cursor = X11_CreateEmptyCursor();
}
/* FIXME: Is there a better way than this? */
{
SDL_VideoDevice *video = SDL_GetVideoDevice();
Display *display = GetDisplay();
SDL_Window *window;
SDL_WindowData *data;
for (window = video->windows; window; window = window->next) {
data = (SDL_WindowData *)window->driverdata;
if (x11_cursor != None) {
X11_XDefineCursor(display, data->xwindow, x11_cursor);
} else {
X11_XUndefineCursor(display, data->xwindow);
}
}
X11_XFlush(display);
}
return 0;
}
static void
WarpMouseInternal(Window xwindow, const int x, const int y)
{
SDL_VideoData *videodata = (SDL_VideoData *) SDL_GetVideoDevice()->driverdata;
Display *display = videodata->display;
X11_XWarpPointer(display, None, xwindow, 0, 0, 0, 0, x, y);
X11_XSync(display, False);
videodata->global_mouse_changed = SDL_TRUE;
}
static void
X11_WarpMouse(SDL_Window * window, int x, int y)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
WarpMouseInternal(data->xwindow, x, y);
}
static int
X11_WarpMouseGlobal(int x, int y)
{
WarpMouseInternal(DefaultRootWindow(GetDisplay()), x, y);
return 0;
}
static int
X11_SetRelativeMouseMode(SDL_bool enabled)
{
#if SDL_VIDEO_DRIVER_X11_XINPUT2
if(X11_Xinput2IsInitialized())
return 0;
#else
SDL_Unsupported();
#endif
return -1;
}
static int
X11_CaptureMouse(SDL_Window *window)
{
Display *display = GetDisplay();
if (window) {
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
const unsigned int mask = ButtonPressMask | ButtonReleaseMask | PointerMotionMask | FocusChangeMask;
const int rc = X11_XGrabPointer(display, data->xwindow, False,
mask, GrabModeAsync, GrabModeAsync,
None, None, CurrentTime);
if (rc != GrabSuccess) {
return SDL_SetError("X server refused mouse capture");
}
} else {
X11_XUngrabPointer(display, CurrentTime);
}
X11_XSync(display, False);
return 0;
}
static Uint32
X11_GetGlobalMouseState(int *x, int *y)
{
SDL_VideoData *videodata = (SDL_VideoData *) SDL_GetVideoDevice()->driverdata;
Display *display = GetDisplay();
const int num_screens = SDL_GetNumVideoDisplays();
int i;
/* !!! FIXME: should we XSync() here first? */
#if !SDL_VIDEO_DRIVER_X11_XINPUT2
videodata->global_mouse_changed = SDL_TRUE;
#endif
/* check if we have this cached since XInput last saw the mouse move. */
/* !!! FIXME: can we just calculate this from XInput's events? */
if (videodata->global_mouse_changed) {
for (i = 0; i < num_screens; i++) {
SDL_DisplayData *data = (SDL_DisplayData *) SDL_GetDisplayDriverData(i);
if (data != NULL) {
Window root, child;
int rootx, rooty, winx, winy;
unsigned int mask;
if (X11_XQueryPointer(display, RootWindow(display, data->screen), &root, &child, &rootx, &rooty, &winx, &winy, &mask)) {
XWindowAttributes root_attrs;
Uint32 buttons = 0;
buttons |= (mask & Button1Mask) ? SDL_BUTTON_LMASK : 0;
buttons |= (mask & Button2Mask) ? SDL_BUTTON_MMASK : 0;
buttons |= (mask & Button3Mask) ? SDL_BUTTON_RMASK : 0;
/* SDL_DisplayData->x,y point to screen origin, and adding them to mouse coordinates relative to root window doesn't do the right thing
* (observed on dual monitor setup with primary display being the rightmost one - mouse was offset to the right).
*
* Adding root position to root-relative coordinates seems to be a better way to get absolute position. */
X11_XGetWindowAttributes(display, root, &root_attrs);
videodata->global_mouse_position.x = root_attrs.x + rootx;
videodata->global_mouse_position.y = root_attrs.y + rooty;
videodata->global_mouse_buttons = buttons;
videodata->global_mouse_changed = SDL_FALSE;
break;
}
}
}
}
SDL_assert(!videodata->global_mouse_changed); /* The pointer wasn't on any X11 screen?! */
*x = videodata->global_mouse_position.x;
*y = videodata->global_mouse_position.y;
return videodata->global_mouse_buttons;
}
void
X11_InitMouse(_THIS)
{
SDL_Mouse *mouse = SDL_GetMouse();
mouse->CreateCursor = X11_CreateCursor;
mouse->CreateSystemCursor = X11_CreateSystemCursor;
mouse->ShowCursor = X11_ShowCursor;
mouse->FreeCursor = X11_FreeCursor;
mouse->WarpMouse = X11_WarpMouse;
mouse->WarpMouseGlobal = X11_WarpMouseGlobal;
mouse->SetRelativeMouseMode = X11_SetRelativeMouseMode;
mouse->CaptureMouse = X11_CaptureMouse;
mouse->GetGlobalMouseState = X11_GetGlobalMouseState;
SDL_SetDefaultCursor(X11_CreateDefaultCursor());
}
void
X11_QuitMouse(_THIS)
{
X11_DestroyEmptyCursor();
}
#endif /* SDL_VIDEO_DRIVER_X11 */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11mouse.c | C | apache-2.0 | 13,736 |
/*
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_x11mouse_h_
#define SDL_x11mouse_h_
extern void X11_InitMouse(_THIS);
extern void X11_QuitMouse(_THIS);
#endif /* SDL_x11mouse_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11mouse.h | C | apache-2.0 | 1,155 |
/*
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_X11
#include "SDL_x11video.h"
#include "SDL_assert.h"
#include "SDL_hints.h"
/* GLX implementation of SDL OpenGL support */
#if SDL_VIDEO_OPENGL_GLX
#include "SDL_loadso.h"
#include "SDL_x11opengles.h"
#if defined(__IRIX__) || defined(__NetBSD__) || defined(__OpenBSD__)
/*
* IRIX doesn't have a GL library versioning system.
* NetBSD and OpenBSD have different GL library versions depending on how
* the library was installed.
*/
#define DEFAULT_OPENGL "libGL.so"
#elif defined(__MACOSX__)
#define DEFAULT_OPENGL "/opt/X11/lib/libGL.1.dylib"
#elif defined(__QNXNTO__)
#define DEFAULT_OPENGL "libGL.so.3"
#else
#define DEFAULT_OPENGL "libGL.so.1"
#endif
#ifndef GLX_NONE_EXT
#define GLX_NONE_EXT 0x8000
#endif
#ifndef GLX_ARB_multisample
#define GLX_ARB_multisample
#define GLX_SAMPLE_BUFFERS_ARB 100000
#define GLX_SAMPLES_ARB 100001
#endif
#ifndef GLX_EXT_visual_rating
#define GLX_EXT_visual_rating
#define GLX_VISUAL_CAVEAT_EXT 0x20
#define GLX_NONE_EXT 0x8000
#define GLX_SLOW_VISUAL_EXT 0x8001
#define GLX_NON_CONFORMANT_VISUAL_EXT 0x800D
#endif
#ifndef GLX_EXT_visual_info
#define GLX_EXT_visual_info
#define GLX_X_VISUAL_TYPE_EXT 0x22
#define GLX_DIRECT_COLOR_EXT 0x8003
#endif
#ifndef GLX_ARB_create_context
#define GLX_ARB_create_context
#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
#define GLX_CONTEXT_FLAGS_ARB 0x2094
#define GLX_CONTEXT_DEBUG_BIT_ARB 0x0001
#define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x0002
/* Typedef for the GL 3.0 context creation function */
typedef GLXContext(*PFNGLXCREATECONTEXTATTRIBSARBPROC) (Display * dpy,
GLXFBConfig config,
GLXContext
share_context,
Bool direct,
const int
*attrib_list);
#endif
#ifndef GLX_ARB_create_context_profile
#define GLX_ARB_create_context_profile
#define GLX_CONTEXT_PROFILE_MASK_ARB 0x9126
#define GLX_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
#define GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
#endif
#ifndef GLX_ARB_create_context_robustness
#define GLX_ARB_create_context_robustness
#define GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB 0x00000004
#define GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB 0x8256
#define GLX_NO_RESET_NOTIFICATION_ARB 0x8261
#define GLX_LOSE_CONTEXT_ON_RESET_ARB 0x8252
#endif
#ifndef GLX_EXT_create_context_es2_profile
#define GLX_EXT_create_context_es2_profile
#ifndef GLX_CONTEXT_ES2_PROFILE_BIT_EXT
#define GLX_CONTEXT_ES2_PROFILE_BIT_EXT 0x00000002
#endif
#endif
#ifndef GLX_ARB_framebuffer_sRGB
#define GLX_ARB_framebuffer_sRGB
#ifndef GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB
#define GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20B2
#endif
#endif
#ifndef GLX_ARB_create_context_no_error
#define GLX_ARB_create_context_no_error
#ifndef GLX_CONTEXT_OPENGL_NO_ERROR_ARB
#define GLX_CONTEXT_OPENGL_NO_ERROR_ARB 0x31B3
#endif
#endif
#ifndef GLX_EXT_swap_control
#define GLX_SWAP_INTERVAL_EXT 0x20F1
#define GLX_MAX_SWAP_INTERVAL_EXT 0x20F2
#endif
#ifndef GLX_EXT_swap_control_tear
#define GLX_LATE_SWAPS_TEAR_EXT 0x20F3
#endif
#ifndef GLX_ARB_context_flush_control
#define GLX_ARB_context_flush_control
#define GLX_CONTEXT_RELEASE_BEHAVIOR_ARB 0x2097
#define GLX_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB 0x0000
#define GLX_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB 0x2098
#endif
#define OPENGL_REQUIRES_DLOPEN
#if defined(OPENGL_REQUIRES_DLOPEN) && defined(SDL_LOADSO_DLOPEN)
#include <dlfcn.h>
#define GL_LoadObject(X) dlopen(X, (RTLD_NOW|RTLD_GLOBAL))
#define GL_LoadFunction dlsym
#define GL_UnloadObject dlclose
#else
#define GL_LoadObject SDL_LoadObject
#define GL_LoadFunction SDL_LoadFunction
#define GL_UnloadObject SDL_UnloadObject
#endif
static void X11_GL_InitExtensions(_THIS);
int
X11_GL_LoadLibrary(_THIS, const char *path)
{
Display *display;
void *handle;
if (_this->gl_data) {
return SDL_SetError("OpenGL context already created");
}
/* Load the OpenGL library */
if (path == NULL) {
path = SDL_getenv("SDL_OPENGL_LIBRARY");
}
if (path == NULL) {
path = DEFAULT_OPENGL;
}
_this->gl_config.dll_handle = GL_LoadObject(path);
if (!_this->gl_config.dll_handle) {
#if defined(OPENGL_REQUIRES_DLOPEN) && defined(SDL_LOADSO_DLOPEN)
SDL_SetError("Failed loading %s: %s", path, dlerror());
#endif
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->glXQueryExtension =
(Bool (*)(Display *, int *, int *))
GL_LoadFunction(handle, "glXQueryExtension");
_this->gl_data->glXGetProcAddress =
(void *(*)(const GLubyte *))
GL_LoadFunction(handle, "glXGetProcAddressARB");
_this->gl_data->glXChooseVisual =
(XVisualInfo * (*)(Display *, int, int *))
X11_GL_GetProcAddress(_this, "glXChooseVisual");
_this->gl_data->glXCreateContext =
(GLXContext(*)(Display *, XVisualInfo *, GLXContext, int))
X11_GL_GetProcAddress(_this, "glXCreateContext");
_this->gl_data->glXDestroyContext =
(void (*)(Display *, GLXContext))
X11_GL_GetProcAddress(_this, "glXDestroyContext");
_this->gl_data->glXMakeCurrent =
(int (*)(Display *, GLXDrawable, GLXContext))
X11_GL_GetProcAddress(_this, "glXMakeCurrent");
_this->gl_data->glXSwapBuffers =
(void (*)(Display *, GLXDrawable))
X11_GL_GetProcAddress(_this, "glXSwapBuffers");
_this->gl_data->glXQueryDrawable =
(void (*)(Display*,GLXDrawable,int,unsigned int*))
X11_GL_GetProcAddress(_this, "glXQueryDrawable");
if (!_this->gl_data->glXQueryExtension ||
!_this->gl_data->glXChooseVisual ||
!_this->gl_data->glXCreateContext ||
!_this->gl_data->glXDestroyContext ||
!_this->gl_data->glXMakeCurrent ||
!_this->gl_data->glXSwapBuffers) {
return SDL_SetError("Could not retrieve OpenGL functions");
}
display = ((SDL_VideoData *) _this->driverdata)->display;
if (!_this->gl_data->glXQueryExtension(display, &_this->gl_data->errorBase, &_this->gl_data->eventBase)) {
return SDL_SetError("GLX is not supported");
}
/* Initialize extensions */
/* See lengthy comment about the inc/dec in
../windows/SDL_windowsopengl.c. */
++_this->gl_config.driver_loaded;
X11_GL_InitExtensions(_this);
--_this->gl_config.driver_loaded;
/* If we need a GL ES context and there's no
* GLX_EXT_create_context_es2_profile extension, switch over to X11_GLES functions
*/
if (((_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) ||
SDL_GetHintBoolean(SDL_HINT_VIDEO_X11_FORCE_EGL, SDL_FALSE)) &&
X11_GL_UseEGL(_this) ) {
#if SDL_VIDEO_OPENGL_EGL
X11_GL_UnloadLibrary(_this);
/* Better avoid conflicts! */
if (_this->gl_config.dll_handle != NULL ) {
GL_UnloadObject(_this->gl_config.dll_handle);
_this->gl_config.dll_handle = NULL;
}
_this->GL_LoadLibrary = X11_GLES_LoadLibrary;
_this->GL_GetProcAddress = X11_GLES_GetProcAddress;
_this->GL_UnloadLibrary = X11_GLES_UnloadLibrary;
_this->GL_CreateContext = X11_GLES_CreateContext;
_this->GL_MakeCurrent = X11_GLES_MakeCurrent;
_this->GL_SetSwapInterval = X11_GLES_SetSwapInterval;
_this->GL_GetSwapInterval = X11_GLES_GetSwapInterval;
_this->GL_SwapWindow = X11_GLES_SwapWindow;
_this->GL_DeleteContext = X11_GLES_DeleteContext;
return X11_GLES_LoadLibrary(_this, NULL);
#else
return SDL_SetError("SDL not configured with EGL support");
#endif
}
return 0;
}
void *
X11_GL_GetProcAddress(_THIS, const char *proc)
{
if (_this->gl_data->glXGetProcAddress) {
return _this->gl_data->glXGetProcAddress((const GLubyte *) proc);
}
return GL_LoadFunction(_this->gl_config.dll_handle, proc);
}
void
X11_GL_UnloadLibrary(_THIS)
{
/* Don't actually unload the library, since it may have registered
* X11 shutdown hooks, per the notes at:
* http://dri.sourceforge.net/doc/DRIuserguide.html
*/
#if 0
GL_UnloadObject(_this->gl_config.dll_handle);
_this->gl_config.dll_handle = NULL;
#endif
/* Free OpenGL memory */
SDL_free(_this->gl_data);
_this->gl_data = NULL;
}
static SDL_bool
HasExtension(const char *extension, const char *extensions)
{
const char *start;
const char *where, *terminator;
if (!extensions)
return SDL_FALSE;
/* Extension names should not have spaces. */
where = SDL_strchr(extension, ' ');
if (where || *extension == '\0')
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;
}
static void
X11_GL_InitExtensions(_THIS)
{
Display *display = ((SDL_VideoData *) _this->driverdata)->display;
const int screen = DefaultScreen(display);
XVisualInfo *vinfo = NULL;
Window w = 0;
GLXContext prev_ctx = 0;
GLXDrawable prev_drawable = 0;
GLXContext context = 0;
const char *(*glXQueryExtensionsStringFunc) (Display *, int);
const char *extensions;
vinfo = X11_GL_GetVisual(_this, display, screen);
if (vinfo) {
GLXContext (*glXGetCurrentContextFunc) (void) =
(GLXContext(*)(void))
X11_GL_GetProcAddress(_this, "glXGetCurrentContext");
GLXDrawable (*glXGetCurrentDrawableFunc) (void) =
(GLXDrawable(*)(void))
X11_GL_GetProcAddress(_this, "glXGetCurrentDrawable");
if (glXGetCurrentContextFunc && glXGetCurrentDrawableFunc) {
XSetWindowAttributes xattr;
prev_ctx = glXGetCurrentContextFunc();
prev_drawable = glXGetCurrentDrawableFunc();
xattr.background_pixel = 0;
xattr.border_pixel = 0;
xattr.colormap =
X11_XCreateColormap(display, RootWindow(display, screen),
vinfo->visual, AllocNone);
w = X11_XCreateWindow(display, RootWindow(display, screen), 0, 0,
32, 32, 0, vinfo->depth, InputOutput, vinfo->visual,
(CWBackPixel | CWBorderPixel | CWColormap), &xattr);
context = _this->gl_data->glXCreateContext(display, vinfo,
NULL, True);
if (context) {
_this->gl_data->glXMakeCurrent(display, w, context);
}
}
X11_XFree(vinfo);
}
glXQueryExtensionsStringFunc =
(const char *(*)(Display *, int)) X11_GL_GetProcAddress(_this,
"glXQueryExtensionsString");
if (glXQueryExtensionsStringFunc) {
extensions = glXQueryExtensionsStringFunc(display, screen);
} else {
extensions = NULL;
}
/* Check for GLX_EXT_swap_control(_tear) */
_this->gl_data->HAS_GLX_EXT_swap_control_tear = SDL_FALSE;
if (HasExtension("GLX_EXT_swap_control", extensions)) {
_this->gl_data->glXSwapIntervalEXT =
(void (*)(Display*,GLXDrawable,int))
X11_GL_GetProcAddress(_this, "glXSwapIntervalEXT");
if (HasExtension("GLX_EXT_swap_control_tear", extensions)) {
_this->gl_data->HAS_GLX_EXT_swap_control_tear = SDL_TRUE;
}
}
/* Check for GLX_MESA_swap_control */
if (HasExtension("GLX_MESA_swap_control", extensions)) {
_this->gl_data->glXSwapIntervalMESA =
(int(*)(int)) X11_GL_GetProcAddress(_this, "glXSwapIntervalMESA");
_this->gl_data->glXGetSwapIntervalMESA =
(int(*)(void)) X11_GL_GetProcAddress(_this,
"glXGetSwapIntervalMESA");
}
/* Check for GLX_SGI_swap_control */
if (HasExtension("GLX_SGI_swap_control", extensions)) {
_this->gl_data->glXSwapIntervalSGI =
(int (*)(int)) X11_GL_GetProcAddress(_this, "glXSwapIntervalSGI");
}
/* Check for GLX_ARB_create_context */
if (HasExtension("GLX_ARB_create_context", extensions)) {
_this->gl_data->glXCreateContextAttribsARB =
(GLXContext (*)(Display*,GLXFBConfig,GLXContext,Bool,const int *))
X11_GL_GetProcAddress(_this, "glXCreateContextAttribsARB");
_this->gl_data->glXChooseFBConfig =
(GLXFBConfig *(*)(Display *, int, const int *, int *))
X11_GL_GetProcAddress(_this, "glXChooseFBConfig");
}
/* Check for GLX_EXT_visual_rating */
if (HasExtension("GLX_EXT_visual_rating", extensions)) {
_this->gl_data->HAS_GLX_EXT_visual_rating = SDL_TRUE;
}
/* Check for GLX_EXT_visual_info */
if (HasExtension("GLX_EXT_visual_info", extensions)) {
_this->gl_data->HAS_GLX_EXT_visual_info = SDL_TRUE;
}
/* Check for GLX_EXT_create_context_es2_profile */
if (HasExtension("GLX_EXT_create_context_es2_profile", extensions)) {
/* this wants to call glGetString(), so it needs a context. */
/* !!! FIXME: it would be nice not to make a context here though! */
if (context) {
SDL_GL_DeduceMaxSupportedESProfile(
&_this->gl_data->es_profile_max_supported_version.major,
&_this->gl_data->es_profile_max_supported_version.minor
);
}
}
/* Check for GLX_ARB_context_flush_control */
if (HasExtension("GLX_ARB_context_flush_control", extensions)) {
_this->gl_data->HAS_GLX_ARB_context_flush_control = SDL_TRUE;
}
/* Check for GLX_ARB_create_context_robustness */
if (HasExtension("GLX_ARB_create_context_robustness", extensions)) {
_this->gl_data->HAS_GLX_ARB_create_context_robustness = SDL_TRUE;
}
/* Check for GLX_ARB_create_context_no_error */
if (HasExtension("GLX_ARB_create_context_no_error", extensions)) {
_this->gl_data->HAS_GLX_ARB_create_context_no_error = SDL_TRUE;
}
if (context) {
_this->gl_data->glXMakeCurrent(display, None, NULL);
_this->gl_data->glXDestroyContext(display, context);
if (prev_ctx && prev_drawable) {
_this->gl_data->glXMakeCurrent(display, prev_drawable, prev_ctx);
}
}
if (w) {
X11_XDestroyWindow(display, w);
}
X11_PumpEvents(_this);
}
/* glXChooseVisual and glXChooseFBConfig have some small differences in
* the attribute encoding, it can be chosen with the for_FBConfig parameter.
* Some targets fail if you use GLX_X_VISUAL_TYPE_EXT/GLX_DIRECT_COLOR_EXT,
* so it gets specified last if used and is pointed to by *_pvistypeattr.
* In case of failure, if that pointer is not NULL, set that pointer to None
* and try again.
*/
static int
X11_GL_GetAttributes(_THIS, Display * display, int screen, int * attribs, int size, Bool for_FBConfig, int **_pvistypeattr)
{
int i = 0;
const int MAX_ATTRIBUTES = 64;
int *pvistypeattr = NULL;
/* assert buffer is large enough to hold all SDL attributes. */
SDL_assert(size >= MAX_ATTRIBUTES);
/* Setup our GLX attributes according to the gl_config. */
if( for_FBConfig ) {
attribs[i++] = GLX_RENDER_TYPE;
attribs[i++] = GLX_RGBA_BIT;
} else {
attribs[i++] = GLX_RGBA;
}
attribs[i++] = GLX_RED_SIZE;
attribs[i++] = _this->gl_config.red_size;
attribs[i++] = GLX_GREEN_SIZE;
attribs[i++] = _this->gl_config.green_size;
attribs[i++] = GLX_BLUE_SIZE;
attribs[i++] = _this->gl_config.blue_size;
if (_this->gl_config.alpha_size) {
attribs[i++] = GLX_ALPHA_SIZE;
attribs[i++] = _this->gl_config.alpha_size;
}
if (_this->gl_config.double_buffer) {
attribs[i++] = GLX_DOUBLEBUFFER;
if( for_FBConfig ) {
attribs[i++] = True;
}
}
attribs[i++] = GLX_DEPTH_SIZE;
attribs[i++] = _this->gl_config.depth_size;
if (_this->gl_config.stencil_size) {
attribs[i++] = GLX_STENCIL_SIZE;
attribs[i++] = _this->gl_config.stencil_size;
}
if (_this->gl_config.accum_red_size) {
attribs[i++] = GLX_ACCUM_RED_SIZE;
attribs[i++] = _this->gl_config.accum_red_size;
}
if (_this->gl_config.accum_green_size) {
attribs[i++] = GLX_ACCUM_GREEN_SIZE;
attribs[i++] = _this->gl_config.accum_green_size;
}
if (_this->gl_config.accum_blue_size) {
attribs[i++] = GLX_ACCUM_BLUE_SIZE;
attribs[i++] = _this->gl_config.accum_blue_size;
}
if (_this->gl_config.accum_alpha_size) {
attribs[i++] = GLX_ACCUM_ALPHA_SIZE;
attribs[i++] = _this->gl_config.accum_alpha_size;
}
if (_this->gl_config.stereo) {
attribs[i++] = GLX_STEREO;
if( for_FBConfig ) {
attribs[i++] = True;
}
}
if (_this->gl_config.multisamplebuffers) {
attribs[i++] = GLX_SAMPLE_BUFFERS_ARB;
attribs[i++] = _this->gl_config.multisamplebuffers;
}
if (_this->gl_config.multisamplesamples) {
attribs[i++] = GLX_SAMPLES_ARB;
attribs[i++] = _this->gl_config.multisamplesamples;
}
if (_this->gl_config.framebuffer_srgb_capable) {
attribs[i++] = GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB;
attribs[i++] = True; /* always needed, for_FBConfig or not! */
}
if (_this->gl_config.accelerated >= 0 &&
_this->gl_data->HAS_GLX_EXT_visual_rating) {
attribs[i++] = GLX_VISUAL_CAVEAT_EXT;
attribs[i++] = _this->gl_config.accelerated ? GLX_NONE_EXT :
GLX_SLOW_VISUAL_EXT;
}
/* If we're supposed to use DirectColor visuals, and we've got the
EXT_visual_info extension, then add GLX_X_VISUAL_TYPE_EXT. */
if (X11_UseDirectColorVisuals() &&
_this->gl_data->HAS_GLX_EXT_visual_info) {
pvistypeattr = &attribs[i];
attribs[i++] = GLX_X_VISUAL_TYPE_EXT;
attribs[i++] = GLX_DIRECT_COLOR_EXT;
}
attribs[i++] = None;
SDL_assert(i <= MAX_ATTRIBUTES);
if (_pvistypeattr) {
*_pvistypeattr = pvistypeattr;
}
return i;
}
XVisualInfo *
X11_GL_GetVisual(_THIS, Display * display, int screen)
{
/* 64 seems nice. */
int attribs[64];
XVisualInfo *vinfo;
int *pvistypeattr = NULL;
if (!_this->gl_data) {
/* The OpenGL library wasn't loaded, SDL_GetError() should have info */
return NULL;
}
X11_GL_GetAttributes(_this, display, screen, attribs, 64, SDL_FALSE, &pvistypeattr);
vinfo = _this->gl_data->glXChooseVisual(display, screen, attribs);
if (!vinfo && (pvistypeattr != NULL)) {
*pvistypeattr = None;
vinfo = _this->gl_data->glXChooseVisual(display, screen, attribs);
}
if (!vinfo) {
SDL_SetError("Couldn't find matching GLX visual");
}
return vinfo;
}
static int (*handler) (Display *, XErrorEvent *) = NULL;
static const char *errorHandlerOperation = NULL;
static int errorBase = 0;
static int errorCode = 0;
static int
X11_GL_ErrorHandler(Display * d, XErrorEvent * e)
{
char *x11_error = NULL;
char x11_error_locale[256];
errorCode = e->error_code;
if (X11_XGetErrorText(d, errorCode, x11_error_locale, sizeof(x11_error_locale)) == Success)
{
x11_error = SDL_iconv_string("UTF-8", "", x11_error_locale, SDL_strlen(x11_error_locale)+1);
}
if (x11_error)
{
SDL_SetError("Could not %s: %s", errorHandlerOperation, x11_error);
SDL_free(x11_error);
}
else
{
SDL_SetError("Could not %s: %i (Base %i)", errorHandlerOperation, errorCode, errorBase);
}
return (0);
}
SDL_bool
X11_GL_UseEGL(_THIS)
{
SDL_assert(_this->gl_data != NULL);
if (SDL_GetHintBoolean(SDL_HINT_VIDEO_X11_FORCE_EGL, SDL_FALSE))
{
/* use of EGL has been requested, even for desktop GL */
return SDL_TRUE;
}
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 GLX 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
X11_GL_CreateContext(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
int screen =
((SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata)->screen;
XWindowAttributes xattr;
XVisualInfo v, *vinfo;
int n;
GLXContext context = NULL, share_context;
if (_this->gl_config.share_with_current_context) {
share_context = (GLXContext)SDL_GL_GetCurrentContext();
} else {
share_context = NULL;
}
/* We do this to create a clean separation between X and GLX errors. */
X11_XSync(display, False);
errorHandlerOperation = "create GL context";
errorBase = _this->gl_data->errorBase;
errorCode = Success;
handler = X11_XSetErrorHandler(X11_GL_ErrorHandler);
X11_XGetWindowAttributes(display, data->xwindow, &xattr);
v.screen = screen;
v.visualid = X11_XVisualIDFromVisual(xattr.visual);
vinfo = X11_XGetVisualInfo(display, VisualScreenMask | VisualIDMask, &v, &n);
if (vinfo) {
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->glXCreateContext(display, vinfo, share_context, True);
} else {
/* max 14 attributes plus terminator */
int attribs[15] = {
GLX_CONTEXT_MAJOR_VERSION_ARB,
_this->gl_config.major_version,
GLX_CONTEXT_MINOR_VERSION_ARB,
_this->gl_config.minor_version,
0
};
int iattr = 4;
/* SDL profile bits match GLX profile bits */
if( _this->gl_config.profile_mask != 0 ) {
attribs[iattr++] = GLX_CONTEXT_PROFILE_MASK_ARB;
attribs[iattr++] = _this->gl_config.profile_mask;
}
/* SDL flags match GLX flags */
if( _this->gl_config.flags != 0 ) {
attribs[iattr++] = GLX_CONTEXT_FLAGS_ARB;
attribs[iattr++] = _this->gl_config.flags;
}
/* only set if glx extension is available */
if( _this->gl_data->HAS_GLX_ARB_context_flush_control ) {
attribs[iattr++] = GLX_CONTEXT_RELEASE_BEHAVIOR_ARB;
attribs[iattr++] =
_this->gl_config.release_behavior ?
GLX_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB :
GLX_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB;
}
/* only set if glx extension is available */
if( _this->gl_data->HAS_GLX_ARB_create_context_robustness ) {
attribs[iattr++] = GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB;
attribs[iattr++] =
_this->gl_config.reset_notification ?
GLX_LOSE_CONTEXT_ON_RESET_ARB :
GLX_NO_RESET_NOTIFICATION_ARB;
}
/* only set if glx extension is available */
if( _this->gl_data->HAS_GLX_ARB_create_context_no_error ) {
attribs[iattr++] = GLX_CONTEXT_OPENGL_NO_ERROR_ARB;
attribs[iattr++] = _this->gl_config.no_error;
}
attribs[iattr++] = 0;
/* Get a pointer to the context creation function for GL 3.0 */
if (!_this->gl_data->glXCreateContextAttribsARB) {
SDL_SetError("OpenGL 3.0 and later are not supported by this system");
} else {
int glxAttribs[64];
/* Create a GL 3.x context */
GLXFBConfig *framebuffer_config = NULL;
int fbcount = 0;
int *pvistypeattr = NULL;
X11_GL_GetAttributes(_this,display,screen,glxAttribs,64,SDL_TRUE,&pvistypeattr);
if (_this->gl_data->glXChooseFBConfig) {
framebuffer_config = _this->gl_data->glXChooseFBConfig(display,
DefaultScreen(display), glxAttribs,
&fbcount);
if (!framebuffer_config && (pvistypeattr != NULL)) {
*pvistypeattr = None;
framebuffer_config = _this->gl_data->glXChooseFBConfig(display,
DefaultScreen(display), glxAttribs,
&fbcount);
}
if (framebuffer_config) {
context = _this->gl_data->glXCreateContextAttribsARB(display,
framebuffer_config[0],
share_context, True, attribs);
X11_XFree(framebuffer_config);
}
}
}
}
X11_XFree(vinfo);
}
X11_XSync(display, False);
X11_XSetErrorHandler(handler);
if (!context) {
if (errorCode == Success) {
SDL_SetError("Could not create GL context");
}
return NULL;
}
if (X11_GL_MakeCurrent(_this, window, context) < 0) {
X11_GL_DeleteContext(_this, context);
return NULL;
}
return context;
}
int
X11_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context)
{
Display *display = ((SDL_VideoData *) _this->driverdata)->display;
Window drawable =
(context ? ((SDL_WindowData *) window->driverdata)->xwindow : None);
GLXContext glx_context = (GLXContext) context;
int rc;
if (!_this->gl_data) {
return SDL_SetError("OpenGL not initialized");
}
/* We do this to create a clean separation between X and GLX errors. */
X11_XSync(display, False);
errorHandlerOperation = "make GL context current";
errorBase = _this->gl_data->errorBase;
errorCode = Success;
handler = X11_XSetErrorHandler(X11_GL_ErrorHandler);
rc = _this->gl_data->glXMakeCurrent(display, drawable, glx_context);
X11_XSetErrorHandler(handler);
if (errorCode != Success) { /* uhoh, an X error was thrown! */
return -1; /* the error handler called SDL_SetError() already. */
} else if (!rc) { /* glXMakeCurrent() failed without throwing an X error */
return SDL_SetError("Unable to make GL context current");
}
return 0;
}
/*
0 is a valid argument to glXSwapInterval(MESA|EXT) and setting it to 0
will undo the effect of a previous call with a value that is greater
than zero (or at least that is what the docs say). OTOH, 0 is an invalid
argument to glXSwapIntervalSGI and it returns an error if you call it
with 0 as an argument.
*/
static int swapinterval = 0;
int
X11_GL_SetSwapInterval(_THIS, int interval)
{
int status = -1;
if ((interval < 0) && (!_this->gl_data->HAS_GLX_EXT_swap_control_tear)) {
SDL_SetError("Negative swap interval unsupported in this GL");
} else if (_this->gl_data->glXSwapIntervalEXT) {
Display *display = ((SDL_VideoData *) _this->driverdata)->display;
const SDL_WindowData *windowdata = (SDL_WindowData *)
SDL_GL_GetCurrentWindow()->driverdata;
Window drawable = windowdata->xwindow;
/*
* This is a workaround for a bug in NVIDIA drivers. Bug has been reported
* and will be fixed in a future release (probably 319.xx).
*
* There's a bug where glXSetSwapIntervalEXT ignores updates because
* it has the wrong value cached. To work around it, we just run a no-op
* update to the current value.
*/
int currentInterval = X11_GL_GetSwapInterval(_this);
_this->gl_data->glXSwapIntervalEXT(display, drawable, currentInterval);
_this->gl_data->glXSwapIntervalEXT(display, drawable, interval);
status = 0;
swapinterval = interval;
} else if (_this->gl_data->glXSwapIntervalMESA) {
status = _this->gl_data->glXSwapIntervalMESA(interval);
if (status != 0) {
SDL_SetError("glXSwapIntervalMESA failed");
} else {
swapinterval = interval;
}
} else if (_this->gl_data->glXSwapIntervalSGI) {
status = _this->gl_data->glXSwapIntervalSGI(interval);
if (status != 0) {
SDL_SetError("glXSwapIntervalSGI failed");
} else {
swapinterval = interval;
}
} else {
SDL_Unsupported();
}
return status;
}
int
X11_GL_GetSwapInterval(_THIS)
{
if (_this->gl_data->glXSwapIntervalEXT) {
Display *display = ((SDL_VideoData *) _this->driverdata)->display;
const SDL_WindowData *windowdata = (SDL_WindowData *)
SDL_GL_GetCurrentWindow()->driverdata;
Window drawable = windowdata->xwindow;
unsigned int allow_late_swap_tearing = 0;
unsigned int interval = 0;
if (_this->gl_data->HAS_GLX_EXT_swap_control_tear) {
_this->gl_data->glXQueryDrawable(display, drawable,
GLX_LATE_SWAPS_TEAR_EXT,
&allow_late_swap_tearing);
}
_this->gl_data->glXQueryDrawable(display, drawable,
GLX_SWAP_INTERVAL_EXT, &interval);
if ((allow_late_swap_tearing) && (interval > 0)) {
return -((int) interval);
}
return (int) interval;
} else if (_this->gl_data->glXGetSwapIntervalMESA) {
return _this->gl_data->glXGetSwapIntervalMESA();
} else {
return swapinterval;
}
}
int
X11_GL_SwapWindow(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
_this->gl_data->glXSwapBuffers(display, data->xwindow);
return 0;
}
void
X11_GL_DeleteContext(_THIS, SDL_GLContext context)
{
Display *display = ((SDL_VideoData *) _this->driverdata)->display;
GLXContext glx_context = (GLXContext) context;
if (!_this->gl_data) {
return;
}
_this->gl_data->glXDestroyContext(display, glx_context);
X11_XSync(display, False);
}
#endif /* SDL_VIDEO_OPENGL_GLX */
#endif /* SDL_VIDEO_DRIVER_X11 */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11opengl.c | C | apache-2.0 | 33,335 |
/*
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_x11opengl_h_
#define SDL_x11opengl_h_
#if SDL_VIDEO_OPENGL_GLX
#include "SDL_opengl.h"
#include <GL/glx.h>
struct SDL_GLDriverData
{
int errorBase, eventBase;
SDL_bool HAS_GLX_EXT_visual_rating;
SDL_bool HAS_GLX_EXT_visual_info;
SDL_bool HAS_GLX_EXT_swap_control_tear;
SDL_bool HAS_GLX_ARB_context_flush_control;
SDL_bool HAS_GLX_ARB_create_context_robustness;
SDL_bool HAS_GLX_ARB_create_context_no_error;
/* Max version of OpenGL ES context that can be created if the
implementation supports GLX_EXT_create_context_es2_profile.
major = minor = 0 when unsupported.
*/
struct {
int major;
int minor;
} es_profile_max_supported_version;
Bool (*glXQueryExtension) (Display*,int*,int*);
void *(*glXGetProcAddress) (const GLubyte*);
XVisualInfo *(*glXChooseVisual) (Display*,int,int*);
GLXContext (*glXCreateContext) (Display*,XVisualInfo*,GLXContext,Bool);
GLXContext (*glXCreateContextAttribsARB) (Display*,GLXFBConfig,GLXContext,Bool,const int *);
GLXFBConfig *(*glXChooseFBConfig) (Display*,int,const int *,int *);
void (*glXDestroyContext) (Display*, GLXContext);
Bool(*glXMakeCurrent) (Display*,GLXDrawable,GLXContext);
void (*glXSwapBuffers) (Display*, GLXDrawable);
void (*glXQueryDrawable) (Display*,GLXDrawable,int,unsigned int*);
void (*glXSwapIntervalEXT) (Display*,GLXDrawable,int);
int (*glXSwapIntervalSGI) (int);
int (*glXSwapIntervalMESA) (int);
int (*glXGetSwapIntervalMESA) (void);
};
/* OpenGL functions */
extern int X11_GL_LoadLibrary(_THIS, const char *path);
extern void *X11_GL_GetProcAddress(_THIS, const char *proc);
extern void X11_GL_UnloadLibrary(_THIS);
extern SDL_bool X11_GL_UseEGL(_THIS);
extern XVisualInfo *X11_GL_GetVisual(_THIS, Display * display, int screen);
extern SDL_GLContext X11_GL_CreateContext(_THIS, SDL_Window * window);
extern int X11_GL_MakeCurrent(_THIS, SDL_Window * window,
SDL_GLContext context);
extern int X11_GL_SetSwapInterval(_THIS, int interval);
extern int X11_GL_GetSwapInterval(_THIS);
extern int X11_GL_SwapWindow(_THIS, SDL_Window * window);
extern void X11_GL_DeleteContext(_THIS, SDL_GLContext context);
#endif /* SDL_VIDEO_OPENGL_GLX */
#endif /* SDL_x11opengl_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11opengl.h | C | apache-2.0 | 3,321 |
/*
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_X11 && SDL_VIDEO_OPENGL_EGL
#include "SDL_hints.h"
#include "SDL_x11video.h"
#include "SDL_x11opengles.h"
#include "SDL_x11opengl.h"
/* EGL implementation of SDL OpenGL support */
int
X11_GLES_LoadLibrary(_THIS, const char *path)
{
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
/* If the profile requested is not GL ES, switch over to X11_GL functions */
if ((_this->gl_config.profile_mask != SDL_GL_CONTEXT_PROFILE_ES) &&
!SDL_GetHintBoolean(SDL_HINT_VIDEO_X11_FORCE_EGL, SDL_FALSE)) {
#if SDL_VIDEO_OPENGL_GLX
X11_GLES_UnloadLibrary(_this);
_this->GL_LoadLibrary = X11_GL_LoadLibrary;
_this->GL_GetProcAddress = X11_GL_GetProcAddress;
_this->GL_UnloadLibrary = X11_GL_UnloadLibrary;
_this->GL_CreateContext = X11_GL_CreateContext;
_this->GL_MakeCurrent = X11_GL_MakeCurrent;
_this->GL_SetSwapInterval = X11_GL_SetSwapInterval;
_this->GL_GetSwapInterval = X11_GL_GetSwapInterval;
_this->GL_SwapWindow = X11_GL_SwapWindow;
_this->GL_DeleteContext = X11_GL_DeleteContext;
return X11_GL_LoadLibrary(_this, path);
#else
return SDL_SetError("SDL not configured with OpenGL/GLX support");
#endif
}
return SDL_EGL_LoadLibrary(_this, path, (NativeDisplayType) data->display, 0);
}
XVisualInfo *
X11_GLES_GetVisual(_THIS, Display * display, int screen)
{
XVisualInfo *egl_visualinfo = NULL;
EGLint visual_id;
XVisualInfo vi_in;
int out_count;
if (!_this->egl_data) {
/* The EGL library wasn't loaded, SDL_GetError() should have info */
return NULL;
}
if (_this->egl_data->eglGetConfigAttrib(_this->egl_data->egl_display,
_this->egl_data->egl_config,
EGL_NATIVE_VISUAL_ID,
&visual_id) == EGL_FALSE || !visual_id) {
/* Use the default visual when all else fails */
vi_in.screen = screen;
egl_visualinfo = X11_XGetVisualInfo(display,
VisualScreenMask,
&vi_in, &out_count);
} else {
vi_in.screen = screen;
vi_in.visualid = visual_id;
egl_visualinfo = X11_XGetVisualInfo(display, VisualScreenMask | VisualIDMask, &vi_in, &out_count);
}
return egl_visualinfo;
}
SDL_GLContext
X11_GLES_CreateContext(_THIS, SDL_Window * window)
{
SDL_GLContext context;
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
X11_XSync(display, False);
context = SDL_EGL_CreateContext(_this, data->egl_surface);
X11_XSync(display, False);
return context;
}
SDL_EGL_SwapWindow_impl(X11)
SDL_EGL_MakeCurrent_impl(X11)
#endif /* SDL_VIDEO_DRIVER_X11 && SDL_VIDEO_OPENGL_EGL */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11opengles.c | C | apache-2.0 | 3,950 |
/*
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_x11opengles_h_
#define SDL_x11opengles_h_
#if SDL_VIDEO_OPENGL_EGL
#include "../SDL_sysvideo.h"
#include "../SDL_egl_c.h"
typedef struct SDL_PrivateGLESData
{
/* 1401 If the struct-declaration-list contains no named members, the behavior is undefined. */
/* warning: empty struct has size 0 in C, size 1 in C++ [-Wc++-compat] */
int dummy;
} SDL_PrivateGLESData;
/* OpenGLES functions */
#define X11_GLES_GetAttribute SDL_EGL_GetAttribute
#define X11_GLES_GetProcAddress SDL_EGL_GetProcAddress
#define X11_GLES_UnloadLibrary SDL_EGL_UnloadLibrary
#define X11_GLES_SetSwapInterval SDL_EGL_SetSwapInterval
#define X11_GLES_GetSwapInterval SDL_EGL_GetSwapInterval
#define X11_GLES_DeleteContext SDL_EGL_DeleteContext
extern int X11_GLES_LoadLibrary(_THIS, const char *path);
extern XVisualInfo *X11_GLES_GetVisual(_THIS, Display * display, int screen);
extern SDL_GLContext X11_GLES_CreateContext(_THIS, SDL_Window * window);
extern int X11_GLES_SwapWindow(_THIS, SDL_Window * window);
extern int X11_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
#endif /* SDL_VIDEO_OPENGL_EGL */
#endif /* SDL_x11opengles_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11opengles.h | C | apache-2.0 | 2,167 |
/*
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_X11
#include "SDL_assert.h"
#include "SDL_x11video.h"
#include "SDL_x11shape.h"
#include "SDL_x11window.h"
#include "../SDL_shape_internals.h"
SDL_WindowShaper*
X11_CreateShaper(SDL_Window* window) {
SDL_WindowShaper* result = NULL;
SDL_ShapeData* data = NULL;
int resized_properly;
#if SDL_VIDEO_DRIVER_X11_XSHAPE
if (SDL_X11_HAVE_XSHAPE) { /* Make sure X server supports it. */
result = malloc(sizeof(SDL_WindowShaper));
result->window = window;
result->mode.mode = ShapeModeDefault;
result->mode.parameters.binarizationCutoff = 1;
result->userx = result->usery = 0;
data = SDL_malloc(sizeof(SDL_ShapeData));
result->driverdata = data;
data->bitmapsize = 0;
data->bitmap = NULL;
window->shaper = result;
resized_properly = X11_ResizeWindowShape(window);
SDL_assert(resized_properly == 0);
}
#endif
return result;
}
int
X11_ResizeWindowShape(SDL_Window* window) {
SDL_ShapeData* data = window->shaper->driverdata;
unsigned int bitmapsize = window->w / 8;
SDL_assert(data != NULL);
if(window->w % 8 > 0)
bitmapsize += 1;
bitmapsize *= window->h;
if(data->bitmapsize != bitmapsize || data->bitmap == NULL) {
data->bitmapsize = bitmapsize;
if(data->bitmap != NULL)
free(data->bitmap);
data->bitmap = malloc(data->bitmapsize);
if(data->bitmap == NULL) {
return SDL_SetError("Could not allocate memory for shaped-window bitmap.");
}
}
memset(data->bitmap,0,data->bitmapsize);
window->shaper->userx = window->x;
window->shaper->usery = window->y;
SDL_SetWindowPosition(window,-1000,-1000);
return 0;
}
int
X11_SetWindowShape(SDL_WindowShaper *shaper,SDL_Surface *shape,SDL_WindowShapeMode *shape_mode) {
SDL_ShapeData *data = NULL;
SDL_WindowData *windowdata = NULL;
Pixmap shapemask;
if(shaper == NULL || shape == NULL || shaper->driverdata == NULL)
return -1;
#if SDL_VIDEO_DRIVER_X11_XSHAPE
if(shape->format->Amask == 0 && SDL_SHAPEMODEALPHA(shape_mode->mode))
return -2;
if(shape->w != shaper->window->w || shape->h != shaper->window->h)
return -3;
data = shaper->driverdata;
/* Assume that shaper->alphacutoff already has a value, because SDL_SetWindowShape() should have given it one. */
SDL_CalculateShapeBitmap(shaper->mode,shape,data->bitmap,8);
windowdata = (SDL_WindowData*)(shaper->window->driverdata);
shapemask = X11_XCreateBitmapFromData(windowdata->videodata->display,windowdata->xwindow,data->bitmap,shaper->window->w,shaper->window->h);
X11_XShapeCombineMask(windowdata->videodata->display,windowdata->xwindow, ShapeBounding, 0, 0,shapemask, ShapeSet);
X11_XSync(windowdata->videodata->display,False);
X11_XFreePixmap(windowdata->videodata->display,shapemask);
#endif
return 0;
}
#endif /* SDL_VIDEO_DRIVER_X11 */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11shape.c | C | apache-2.0 | 3,966 |
/*
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_x11shape_h_
#define SDL_x11shape_h_
#include "SDL_video.h"
#include "SDL_shape.h"
#include "../SDL_sysvideo.h"
typedef struct {
void* bitmap;
Uint32 bitmapsize;
} SDL_ShapeData;
extern SDL_WindowShaper* X11_CreateShaper(SDL_Window* window);
extern int X11_ResizeWindowShape(SDL_Window* window);
extern int X11_SetWindowShape(SDL_WindowShaper *shaper,SDL_Surface *shape,SDL_WindowShapeMode *shapeMode);
#endif /* SDL_x11shape_h_ */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11shape.h | C | apache-2.0 | 1,427 |
/*
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_X11_MODULE
#define SDL_X11_MODULE(modname)
#endif
#ifndef SDL_X11_SYM
#define SDL_X11_SYM(rc,fn,params,args,ret)
#endif
SDL_X11_MODULE(BASEXLIB)
SDL_X11_SYM(XSizeHints*,XAllocSizeHints,(void),(),return)
SDL_X11_SYM(XWMHints*,XAllocWMHints,(void),(),return)
SDL_X11_SYM(XClassHint*,XAllocClassHint,(void),(),return)
SDL_X11_SYM(int,XAutoRepeatOn,(Display* a),(a),return)
SDL_X11_SYM(int,XAutoRepeatOff,(Display* a),(a),return)
SDL_X11_SYM(int,XChangePointerControl,(Display* a,Bool b,Bool c,int d,int e,int f),(a,b,c,d,e,f),return)
SDL_X11_SYM(int,XChangeProperty,(Display* a,Window b,Atom c,Atom d,int e,int f,_Xconst unsigned char* g,int h),(a,b,c,d,e,f,g,h),return)
SDL_X11_SYM(Bool,XCheckIfEvent,(Display* a,XEvent *b,Bool (*c)(Display*,XEvent*,XPointer),XPointer d),(a,b,c,d),return)
SDL_X11_SYM(int,XClearWindow,(Display* a,Window b),(a,b),return)
SDL_X11_SYM(int,XCloseDisplay,(Display* a),(a),return)
SDL_X11_SYM(int,XConvertSelection,(Display* a,Atom b,Atom c,Atom d,Window e,Time f),(a,b,c,d,e,f),return)
SDL_X11_SYM(Pixmap,XCreateBitmapFromData,(Display *dpy,Drawable d,_Xconst char *data,unsigned int width,unsigned int height),(dpy,d,data,width,height),return)
SDL_X11_SYM(Colormap,XCreateColormap,(Display* a,Window b,Visual* c,int d),(a,b,c,d),return)
SDL_X11_SYM(Cursor,XCreatePixmapCursor,(Display* a,Pixmap b,Pixmap c,XColor* d,XColor* e,unsigned int f,unsigned int g),(a,b,c,d,e,f,g),return)
SDL_X11_SYM(Cursor,XCreateFontCursor,(Display* a,unsigned int b),(a,b),return)
SDL_X11_SYM(XFontSet,XCreateFontSet,(Display* a, _Xconst char* b, char*** c, int* d, char** e),(a,b,c,d,e),return)
SDL_X11_SYM(GC,XCreateGC,(Display* a,Drawable b,unsigned long c,XGCValues* d),(a,b,c,d),return)
SDL_X11_SYM(XImage*,XCreateImage,(Display* a,Visual* b,unsigned int c,int d,int e,char* f,unsigned int g,unsigned int h,int i,int j),(a,b,c,d,e,f,g,h,i,j),return)
SDL_X11_SYM(Window,XCreateWindow,(Display* a,Window b,int c,int d,unsigned int e,unsigned int f,unsigned int g,int h,unsigned int i,Visual* j,unsigned long k,XSetWindowAttributes* l),(a,b,c,d,e,f,g,h,i,j,k,l),return)
SDL_X11_SYM(int,XDefineCursor,(Display* a,Window b,Cursor c),(a,b,c),return)
SDL_X11_SYM(int,XDeleteProperty,(Display* a,Window b,Atom c),(a,b,c),return)
SDL_X11_SYM(int,XDestroyWindow,(Display* a,Window b),(a,b),return)
SDL_X11_SYM(int,XDisplayKeycodes,(Display* a,int* b,int* c),(a,b,c),return)
SDL_X11_SYM(int,XDrawRectangle,(Display* a,Drawable b,GC c,int d,int e,unsigned int f,unsigned int g),(a,b,c,d,e,f,g),return)
SDL_X11_SYM(char*,XDisplayName,(_Xconst char* a),(a),return)
SDL_X11_SYM(int,XDrawString,(Display* a,Drawable b,GC c,int d,int e,_Xconst char* f,int g),(a,b,c,d,e,f,g),return)
SDL_X11_SYM(int,XEventsQueued,(Display* a,int b),(a,b),return)
SDL_X11_SYM(int,XFillRectangle,(Display* a,Drawable b,GC c,int d,int e,unsigned int f,unsigned int g),(a,b,c,d,e,f,g),return)
SDL_X11_SYM(Bool,XFilterEvent,(XEvent *event,Window w),(event,w),return)
SDL_X11_SYM(int,XFlush,(Display* a),(a),return)
SDL_X11_SYM(int,XFree,(void*a),(a),return)
SDL_X11_SYM(int,XFreeCursor,(Display* a,Cursor b),(a,b),return)
SDL_X11_SYM(void,XFreeFontSet,(Display* a, XFontSet b),(a,b),)
SDL_X11_SYM(int,XFreeGC,(Display* a,GC b),(a,b),return)
SDL_X11_SYM(int,XFreeFont,(Display* a, XFontStruct* b),(a,b),return)
SDL_X11_SYM(int,XFreeModifiermap,(XModifierKeymap* a),(a),return)
SDL_X11_SYM(int,XFreePixmap,(Display* a,Pixmap b),(a,b),return)
SDL_X11_SYM(void,XFreeStringList,(char** a),(a),)
SDL_X11_SYM(char*,XGetAtomName,(Display *a,Atom b),(a,b),return)
SDL_X11_SYM(int,XGetInputFocus,(Display *a,Window *b,int *c),(a,b,c),return)
SDL_X11_SYM(int,XGetErrorDatabaseText,(Display* a,_Xconst char* b,_Xconst char* c,_Xconst char* d,char* e,int f),(a,b,c,d,e,f),return)
SDL_X11_SYM(XModifierKeymap*,XGetModifierMapping,(Display* a),(a),return)
SDL_X11_SYM(int,XGetKeyboardControl,(Display* a, XKeyboardState* b),(a,b),return)
SDL_X11_SYM(int,XGetPointerControl,(Display* a,int* b,int* c,int* d),(a,b,c,d),return)
SDL_X11_SYM(Window,XGetSelectionOwner,(Display* a,Atom b),(a,b),return)
SDL_X11_SYM(XVisualInfo*,XGetVisualInfo,(Display* a,long b,XVisualInfo* c,int* d),(a,b,c,d),return)
SDL_X11_SYM(Status,XGetWindowAttributes,(Display* a,Window b,XWindowAttributes* c),(a,b,c),return)
SDL_X11_SYM(int,XGetWindowProperty,(Display* a,Window b,Atom c,long d,long e,Bool f,Atom g,Atom* h,int* i,unsigned long* j,unsigned long *k,unsigned char **l),(a,b,c,d,e,f,g,h,i,j,k,l),return)
SDL_X11_SYM(XWMHints*,XGetWMHints,(Display* a,Window b),(a,b),return)
SDL_X11_SYM(Status,XGetWMNormalHints,(Display *a,Window b, XSizeHints *c, long *d),(a,b,c,d),return)
SDL_X11_SYM(int,XIfEvent,(Display* a,XEvent *b,Bool (*c)(Display*,XEvent*,XPointer),XPointer d),(a,b,c,d),return)
SDL_X11_SYM(int,XGrabKeyboard,(Display* a,Window b,Bool c,int d,int e,Time f),(a,b,c,d,e,f),return)
SDL_X11_SYM(int,XGrabPointer,(Display* a,Window b,Bool c,unsigned int d,int e,int f,Window g,Cursor h,Time i),(a,b,c,d,e,f,g,h,i),return)
SDL_X11_SYM(int,XGrabServer,(Display* a),(a),return)
SDL_X11_SYM(Status,XIconifyWindow,(Display* a,Window b,int c),(a,b,c),return)
SDL_X11_SYM(KeyCode,XKeysymToKeycode,(Display* a,KeySym b),(a,b),return)
SDL_X11_SYM(char*,XKeysymToString,(KeySym a),(a),return)
SDL_X11_SYM(int,XInstallColormap,(Display* a,Colormap b),(a,b),return)
SDL_X11_SYM(Atom,XInternAtom,(Display* a,_Xconst char* b,Bool c),(a,b,c),return)
SDL_X11_SYM(XPixmapFormatValues*,XListPixmapFormats,(Display* a,int* b),(a,b),return)
SDL_X11_SYM(XFontStruct*,XLoadQueryFont,(Display* a,_Xconst char* b),(a,b),return)
SDL_X11_SYM(KeySym,XLookupKeysym,(XKeyEvent* a,int b),(a,b),return)
SDL_X11_SYM(int,XLookupString,(XKeyEvent* a,char* b,int c,KeySym* d,XComposeStatus* e),(a,b,c,d,e),return)
SDL_X11_SYM(int,XMapRaised,(Display* a,Window b),(a,b),return)
SDL_X11_SYM(Status,XMatchVisualInfo,(Display* a,int b,int c,int d,XVisualInfo* e),(a,b,c,d,e),return)
SDL_X11_SYM(int,XMissingExtension,(Display* a,_Xconst char* b),(a,b),return)
SDL_X11_SYM(int,XMoveWindow,(Display* a,Window b,int c,int d),(a,b,c,d),return)
SDL_X11_SYM(int,XNextEvent,(Display* a,XEvent* b),(a,b),return)
SDL_X11_SYM(Display*,XOpenDisplay,(_Xconst char* a),(a),return)
SDL_X11_SYM(Status,XInitThreads,(void),(),return)
SDL_X11_SYM(int,XPeekEvent,(Display* a,XEvent* b),(a,b),return)
SDL_X11_SYM(int,XPending,(Display* a),(a),return)
SDL_X11_SYM(int,XPutImage,(Display* a,Drawable b,GC c,XImage* d,int e,int f,int g,int h,unsigned int i,unsigned int j),(a,b,c,d,e,f,g,h,i,j),return)
SDL_X11_SYM(int,XQueryKeymap,(Display* a,char *b),(a,b),return)
SDL_X11_SYM(Bool,XQueryPointer,(Display* a,Window b,Window* c,Window* d,int* e,int* f,int* g,int* h,unsigned int* i),(a,b,c,d,e,f,g,h,i),return)
SDL_X11_SYM(int,XRaiseWindow,(Display* a,Window b),(a,b),return)
SDL_X11_SYM(int,XReparentWindow,(Display* a,Window b,Window c,int d,int e),(a,b,c,d,e),return)
SDL_X11_SYM(int,XResetScreenSaver,(Display* a),(a),return)
SDL_X11_SYM(int,XResizeWindow,(Display* a,Window b,unsigned int c,unsigned int d),(a,b,c,d),return)
SDL_X11_SYM(int,XSelectInput,(Display* a,Window b,long c),(a,b,c),return)
SDL_X11_SYM(Status,XSendEvent,(Display* a,Window b,Bool c,long d,XEvent* e),(a,b,c,d,e),return)
SDL_X11_SYM(XErrorHandler,XSetErrorHandler,(XErrorHandler a),(a),return)
SDL_X11_SYM(int,XSetForeground,(Display* a,GC b,unsigned long c),(a,b,c),return)
SDL_X11_SYM(XIOErrorHandler,XSetIOErrorHandler,(XIOErrorHandler a),(a),return)
SDL_X11_SYM(int,XSetInputFocus,(Display *a,Window b,int c,Time d),(a,b,c,d),return)
SDL_X11_SYM(int,XSetSelectionOwner,(Display* a,Atom b,Window c,Time d),(a,b,c,d),return)
SDL_X11_SYM(int,XSetTransientForHint,(Display* a,Window b,Window c),(a,b,c),return)
SDL_X11_SYM(void,XSetTextProperty,(Display* a,Window b,XTextProperty* c,Atom d),(a,b,c,d),)
SDL_X11_SYM(int,XSetWindowBackground,(Display* a,Window b,unsigned long c),(a,b,c),return)
SDL_X11_SYM(void,XSetWMProperties,(Display* a,Window b,XTextProperty* c,XTextProperty* d,char** e,int f,XSizeHints* g,XWMHints* h,XClassHint* i),(a,b,c,d,e,f,g,h,i),)
SDL_X11_SYM(void,XSetWMNormalHints,(Display* a,Window b,XSizeHints* c),(a,b,c),)
SDL_X11_SYM(Status,XSetWMProtocols,(Display* a,Window b,Atom* c,int d),(a,b,c,d),return)
SDL_X11_SYM(int,XStoreColors,(Display* a,Colormap b,XColor* c,int d),(a,b,c,d),return)
SDL_X11_SYM(int,XStoreName,(Display* a,Window b,_Xconst char* c),(a,b,c),return)
SDL_X11_SYM(Status,XStringListToTextProperty,(char** a,int b,XTextProperty* c),(a,b,c),return)
SDL_X11_SYM(int,XSync,(Display* a,Bool b),(a,b),return)
SDL_X11_SYM(int,XTextExtents,(XFontStruct* a,_Xconst char* b,int c,int* d,int* e,int* f,XCharStruct* g),(a,b,c,d,e,f,g),return)
SDL_X11_SYM(Bool,XTranslateCoordinates,(Display *a,Window b,Window c,int d,int e,int* f,int* g,Window* h),(a,b,c,d,e,f,g,h),return)
SDL_X11_SYM(int,XUndefineCursor,(Display* a,Window b),(a,b),return)
SDL_X11_SYM(int,XUngrabKeyboard,(Display* a,Time b),(a,b),return)
SDL_X11_SYM(int,XUngrabPointer,(Display* a,Time b),(a,b),return)
SDL_X11_SYM(int,XUngrabServer,(Display* a),(a),return)
SDL_X11_SYM(int,XUninstallColormap,(Display* a,Colormap b),(a,b),return)
SDL_X11_SYM(int,XUnloadFont,(Display* a,Font b),(a,b),return)
SDL_X11_SYM(int,XWarpPointer,(Display* a,Window b,Window c,int d,int e,unsigned int f,unsigned int g,int h,int i),(a,b,c,d,e,f,g,h,i),return)
SDL_X11_SYM(int,XWindowEvent,(Display* a,Window b,long c,XEvent* d),(a,b,c,d),return)
SDL_X11_SYM(Status,XWithdrawWindow,(Display* a,Window b,int c),(a,b,c),return)
SDL_X11_SYM(VisualID,XVisualIDFromVisual,(Visual* a),(a),return)
#if SDL_VIDEO_DRIVER_X11_CONST_PARAM_XEXTADDDISPLAY
SDL_X11_SYM(XExtDisplayInfo*,XextAddDisplay,(XExtensionInfo* a,Display* b,_Xconst char* c,XExtensionHooks* d,int e,XPointer f),(a,b,c,d,e,f),return)
#else
SDL_X11_SYM(XExtDisplayInfo*,XextAddDisplay,(XExtensionInfo* a,Display* b,char* c,XExtensionHooks* d,int e,XPointer f),(a,b,c,d,e,f),return)
#endif
SDL_X11_SYM(XExtensionInfo*,XextCreateExtension,(void),(),return)
SDL_X11_SYM(void,XextDestroyExtension,(XExtensionInfo* a),(a),)
SDL_X11_SYM(XExtDisplayInfo*,XextFindDisplay,(XExtensionInfo* a,Display* b),(a,b),return)
SDL_X11_SYM(int,XextRemoveDisplay,(XExtensionInfo* a,Display* b),(a,b),return)
SDL_X11_SYM(Bool,XQueryExtension,(Display* a,_Xconst char* b,int* c,int* d,int* e),(a,b,c,d,e),return)
SDL_X11_SYM(char *,XDisplayString,(Display* a),(a),return)
SDL_X11_SYM(int,XGetErrorText,(Display* a,int b,char* c,int d),(a,b,c,d),return)
SDL_X11_SYM(void,_XEatData,(Display* a,unsigned long b),(a,b),)
SDL_X11_SYM(void,_XFlush,(Display* a),(a),)
SDL_X11_SYM(void,_XFlushGCCache,(Display* a,GC b),(a,b),)
SDL_X11_SYM(int,_XRead,(Display* a,char* b,long c),(a,b,c),return)
SDL_X11_SYM(void,_XReadPad,(Display* a,char* b,long c),(a,b,c),)
SDL_X11_SYM(void,_XSend,(Display* a,_Xconst char* b,long c),(a,b,c),)
SDL_X11_SYM(Status,_XReply,(Display* a,xReply* b,int c,Bool d),(a,b,c,d),return)
SDL_X11_SYM(unsigned long,_XSetLastRequestRead,(Display* a,xGenericReply* b),(a,b),return)
SDL_X11_SYM(SDL_X11_XSynchronizeRetType,XSynchronize,(Display* a,Bool b),(a,b),return)
SDL_X11_SYM(SDL_X11_XESetWireToEventRetType,XESetWireToEvent,(Display* a,int b,SDL_X11_XESetWireToEventRetType c),(a,b,c),return)
SDL_X11_SYM(SDL_X11_XESetEventToWireRetType,XESetEventToWire,(Display* a,int b,SDL_X11_XESetEventToWireRetType c),(a,b,c),return)
SDL_X11_SYM(void,XRefreshKeyboardMapping,(XMappingEvent *a),(a),)
SDL_X11_SYM(int,XQueryTree,(Display* a,Window b,Window* c,Window* d,Window** e,unsigned int* f),(a,b,c,d,e,f),return)
#if SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS
SDL_X11_SYM(Bool,XGetEventData,(Display* a,XGenericEventCookie* b),(a,b),return)
SDL_X11_SYM(void,XFreeEventData,(Display* a,XGenericEventCookie* b),(a,b),)
#endif
#if SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM
SDL_X11_SYM(Bool,XkbQueryExtension,(Display* a,int * b,int * c,int * d,int * e, int *f),(a,b,c,d,e,f),return)
#if NeedWidePrototypes
SDL_X11_SYM(KeySym,XkbKeycodeToKeysym,(Display* a,unsigned int b,int c,int d),(a,b,c,d),return)
#else
SDL_X11_SYM(KeySym,XkbKeycodeToKeysym,(Display* a,KeyCode b,int c,int d),(a,b,c,d),return)
#endif
SDL_X11_SYM(Status,XkbGetState,(Display* a,unsigned int b,XkbStatePtr c),(a,b,c),return)
SDL_X11_SYM(Status,XkbGetUpdatedMap,(Display* a,unsigned int b,XkbDescPtr c),(a,b,c),return)
SDL_X11_SYM(XkbDescPtr,XkbGetMap,(Display* a,unsigned int b,unsigned int c),(a,b,c),return)
SDL_X11_SYM(void,XkbFreeClientMap,(XkbDescPtr a,unsigned int b, Bool c),(a,b,c),)
SDL_X11_SYM(void,XkbFreeKeyboard,(XkbDescPtr a,unsigned int b, Bool c),(a,b,c),)
SDL_X11_SYM(Bool,XkbSetDetectableAutoRepeat,(Display* a, Bool b, Bool* c),(a,b,c),return)
#endif
#if NeedWidePrototypes
SDL_X11_SYM(KeySym,XKeycodeToKeysym,(Display* a,unsigned int b,int c),(a,b,c),return)
#else
SDL_X11_SYM(KeySym,XKeycodeToKeysym,(Display* a,KeyCode b,int c),(a,b,c),return)
#endif
#ifdef X_HAVE_UTF8_STRING
SDL_X11_MODULE(UTF8)
SDL_X11_SYM(int,Xutf8TextListToTextProperty,(Display* a,char** b,int c,XICCEncodingStyle d,XTextProperty* e),(a,b,c,d,e),return)
SDL_X11_SYM(int,Xutf8LookupString,(XIC a,XKeyPressedEvent* b,char* c,int d,KeySym* e,Status* f),(a,b,c,d,e,f),return)
/* SDL_X11_SYM(XIC,XCreateIC,(XIM, ...),return) !!! ARGH! */
SDL_X11_SYM(void,XDestroyIC,(XIC a),(a),)
/* SDL_X11_SYM(char*,XGetICValues,(XIC, ...),return) !!! ARGH! */
SDL_X11_SYM(void,XSetICFocus,(XIC a),(a),)
SDL_X11_SYM(void,XUnsetICFocus,(XIC a),(a),)
SDL_X11_SYM(XIM,XOpenIM,(Display* a,struct _XrmHashBucketRec* b,char* c,char* d),(a,b,c,d),return)
SDL_X11_SYM(Status,XCloseIM,(XIM a),(a),return)
SDL_X11_SYM(void,Xutf8DrawString,(Display *a, Drawable b, XFontSet c, GC d, int e, int f, _Xconst char *g, int h),(a,b,c,d,e,f,g,h),)
SDL_X11_SYM(int,Xutf8TextExtents,(XFontSet a, _Xconst char* b, int c, XRectangle* d, XRectangle* e),(a,b,c,d,e),return)
SDL_X11_SYM(char*,XSetLocaleModifiers,(const char *a),(a),return)
SDL_X11_SYM(char*,Xutf8ResetIC,(XIC a),(a),return)
#endif
#ifndef NO_SHARED_MEMORY
SDL_X11_MODULE(SHM)
SDL_X11_SYM(Status,XShmAttach,(Display* a,XShmSegmentInfo* b),(a,b),return)
SDL_X11_SYM(Status,XShmDetach,(Display* a,XShmSegmentInfo* b),(a,b),return)
SDL_X11_SYM(Status,XShmPutImage,(Display* a,Drawable b,GC c,XImage* d,int e,int f,int g,int h,unsigned int i,unsigned int j,Bool k),(a,b,c,d,e,f,g,h,i,j,k),return)
SDL_X11_SYM(XImage*,XShmCreateImage,(Display* a,Visual* b,unsigned int c,int d,char* e,XShmSegmentInfo* f,unsigned int g,unsigned int h),(a,b,c,d,e,f,g,h),return)
SDL_X11_SYM(Pixmap,XShmCreatePixmap,(Display *a,Drawable b,char* c,XShmSegmentInfo* d, unsigned int e, unsigned int f, unsigned int g),(a,b,c,d,e,f,g),return)
SDL_X11_SYM(Bool,XShmQueryExtension,(Display* a),(a),return)
#endif
/*
* Not required...these only exist in code in headers on some 64-bit platforms,
* and are removed via macros elsewhere, so it's safe for them to be missing.
*/
#ifdef LONG64
SDL_X11_MODULE(IO_32BIT)
SDL_X11_SYM(int,_XData32,(Display *dpy,register _Xconst long *data,unsigned len),(dpy,data,len),return)
SDL_X11_SYM(void,_XRead32,(Display *dpy,register long *data,long len),(dpy,data,len),)
#endif
/*
* These only show up on some variants of Unix.
*/
#if defined(__osf__)
SDL_X11_MODULE(OSF_ENTRY_POINTS)
SDL_X11_SYM(void,_SmtBufferOverflow,(Display *dpy,register smtDisplayPtr p),(dpy,p),)
SDL_X11_SYM(void,_SmtIpError,(Display *dpy,register smtDisplayPtr p,int i),(dpy,p,i),)
SDL_X11_SYM(int,ipAllocateData,(ChannelPtr a,IPCard b,IPDataPtr * c),(a,b,c),return)
SDL_X11_SYM(int,ipUnallocateAndSendData,(ChannelPtr a,IPCard b),(a,b),return)
#endif
/* XCursor support */
#if SDL_VIDEO_DRIVER_X11_XCURSOR
SDL_X11_MODULE(XCURSOR)
SDL_X11_SYM(XcursorImage*,XcursorImageCreate,(int a,int b),(a,b),return)
SDL_X11_SYM(void,XcursorImageDestroy,(XcursorImage *a),(a),)
SDL_X11_SYM(Cursor,XcursorImageLoadCursor,(Display *a,const XcursorImage *b),(a,b),return)
#endif
/* Xdbe support */
#if SDL_VIDEO_DRIVER_X11_XDBE
SDL_X11_MODULE(XDBE)
SDL_X11_SYM(Status,XdbeQueryExtension,(Display *dpy,int *major_version_return,int *minor_version_return),(dpy,major_version_return,minor_version_return),return)
SDL_X11_SYM(XdbeBackBuffer,XdbeAllocateBackBufferName,(Display *dpy,Window window,XdbeSwapAction swap_action),(dpy,window,swap_action),return)
SDL_X11_SYM(Status,XdbeDeallocateBackBufferName,(Display *dpy,XdbeBackBuffer buffer),(dpy,buffer),return)
SDL_X11_SYM(Status,XdbeSwapBuffers,(Display *dpy,XdbeSwapInfo *swap_info,int num_windows),(dpy,swap_info,num_windows),return)
SDL_X11_SYM(Status,XdbeBeginIdiom,(Display *dpy),(dpy),return)
SDL_X11_SYM(Status,XdbeEndIdiom,(Display *dpy),(dpy),return)
SDL_X11_SYM(XdbeScreenVisualInfo*,XdbeGetVisualInfo,(Display *dpy,Drawable *screen_specifiers,int *num_screens),(dpy,screen_specifiers,num_screens),return)
SDL_X11_SYM(void,XdbeFreeVisualInfo,(XdbeScreenVisualInfo *visual_info),(visual_info),)
SDL_X11_SYM(XdbeBackBufferAttributes*,XdbeGetBackBufferAttributes,(Display *dpy,XdbeBackBuffer buffer),(dpy,buffer),return)
#endif
/* Xinerama support */
#if SDL_VIDEO_DRIVER_X11_XINERAMA
SDL_X11_MODULE(XINERAMA)
SDL_X11_SYM(Bool,XineramaIsActive,(Display *a),(a),return)
SDL_X11_SYM(Bool,XineramaQueryExtension,(Display *a,int *b,int *c),(a,b,c),return)
SDL_X11_SYM(Status,XineramaQueryVersion,(Display *a,int *b,int *c),(a,b,c),return)
SDL_X11_SYM(XineramaScreenInfo*,XineramaQueryScreens,(Display *a, int *b),(a,b),return)
#endif
/* XInput2 support for multiple mice, tablets, etc. */
#if SDL_VIDEO_DRIVER_X11_XINPUT2
SDL_X11_MODULE(XINPUT2)
SDL_X11_SYM(XIDeviceInfo*,XIQueryDevice,(Display *a,int b,int *c),(a,b,c),return)
SDL_X11_SYM(void,XIFreeDeviceInfo,(XIDeviceInfo *a),(a),)
SDL_X11_SYM(int,XISelectEvents,(Display *a,Window b,XIEventMask *c,int d),(a,b,c,d),return)
SDL_X11_SYM(Status,XIQueryVersion,(Display *a,int *b,int *c),(a,b,c),return)
SDL_X11_SYM(XIEventMask*,XIGetSelectedEvents,(Display *a,Window b,int *c),(a,b,c),return)
#endif
/* XRandR support */
#if SDL_VIDEO_DRIVER_X11_XRANDR
SDL_X11_MODULE(XRANDR)
SDL_X11_SYM(Status,XRRQueryVersion,(Display *dpy,int *major_versionp,int *minor_versionp),(dpy,major_versionp,minor_versionp),return)
SDL_X11_SYM(XRRScreenConfiguration *,XRRGetScreenInfo,(Display *dpy,Drawable draw),(dpy,draw),return)
SDL_X11_SYM(SizeID,XRRConfigCurrentConfiguration,(XRRScreenConfiguration *config,Rotation *rotation),(config,rotation),return)
SDL_X11_SYM(short,XRRConfigCurrentRate,(XRRScreenConfiguration *config),(config),return)
SDL_X11_SYM(short *,XRRConfigRates,(XRRScreenConfiguration *config,int sizeID,int *nrates),(config,sizeID,nrates),return)
SDL_X11_SYM(XRRScreenSize *,XRRConfigSizes,(XRRScreenConfiguration *config,int *nsizes),(config,nsizes),return)
SDL_X11_SYM(Status,XRRSetScreenConfigAndRate,(Display *dpy,XRRScreenConfiguration *config,Drawable draw,int size_index,Rotation rotation,short rate,Time timestamp),(dpy,config,draw,size_index,rotation,rate,timestamp),return)
SDL_X11_SYM(void,XRRFreeScreenConfigInfo,(XRRScreenConfiguration *config),(config),)
SDL_X11_SYM(void,XRRSetScreenSize,(Display *dpy, Window window,int width, int height,int mmWidth, int mmHeight),(dpy,window,width,height,mmWidth,mmHeight),)
SDL_X11_SYM(Status,XRRGetScreenSizeRange,(Display *dpy, Window window,int *minWidth, int *minHeight, int *maxWidth, int *maxHeight),(dpy,window,minWidth,minHeight,maxWidth,maxHeight),return)
SDL_X11_SYM(XRRScreenResources *,XRRGetScreenResources,(Display *dpy, Window window),(dpy, window),return)
SDL_X11_SYM(XRRScreenResources *,XRRGetScreenResourcesCurrent,(Display *dpy, Window window),(dpy, window),return)
SDL_X11_SYM(void,XRRFreeScreenResources,(XRRScreenResources *resources),(resources),)
SDL_X11_SYM(XRROutputInfo *,XRRGetOutputInfo,(Display *dpy, XRRScreenResources *resources, RROutput output),(dpy,resources,output),return)
SDL_X11_SYM(void,XRRFreeOutputInfo,(XRROutputInfo *outputInfo),(outputInfo),)
SDL_X11_SYM(XRRCrtcInfo *,XRRGetCrtcInfo,(Display *dpy, XRRScreenResources *resources, RRCrtc crtc),(dpy,resources,crtc),return)
SDL_X11_SYM(void,XRRFreeCrtcInfo,(XRRCrtcInfo *crtcInfo),(crtcInfo),)
SDL_X11_SYM(Status,XRRSetCrtcConfig,(Display *dpy, XRRScreenResources *resources, RRCrtc crtc, Time timestamp, int x, int y, RRMode mode, Rotation rotation, RROutput *outputs, int noutputs),(dpy,resources,crtc,timestamp,x,y,mode,rotation,outputs,noutputs),return)
SDL_X11_SYM(Atom*,XRRListOutputProperties,(Display *dpy, RROutput output, int *nprop),(dpy,output,nprop),return)
SDL_X11_SYM(XRRPropertyInfo*,XRRQueryOutputProperty,(Display *dpy,RROutput output, Atom property),(dpy,output,property),return)
SDL_X11_SYM(int,XRRGetOutputProperty,(Display *dpy,RROutput output, Atom property, long offset, long length, Bool _delete, Bool pending, Atom req_type, Atom *actual_type, int *actual_format, unsigned long *nitems, unsigned long *bytes_after, unsigned char **prop),(dpy,output,property,offset,length, _delete, pending, req_type, actual_type, actual_format, nitems, bytes_after, prop),return)
SDL_X11_SYM(RROutput,XRRGetOutputPrimary,(Display *dpy,Window window),(dpy,window),return)
#endif
/* MIT-SCREEN-SAVER support */
#if SDL_VIDEO_DRIVER_X11_XSCRNSAVER
SDL_X11_MODULE(XSS)
SDL_X11_SYM(Bool,XScreenSaverQueryExtension,(Display *dpy,int *event_base,int *error_base),(dpy,event_base,error_base),return)
SDL_X11_SYM(Status,XScreenSaverQueryVersion,(Display *dpy,int *major_versionp,int *minor_versionp),(dpy,major_versionp,minor_versionp),return)
SDL_X11_SYM(void,XScreenSaverSuspend,(Display *dpy,Bool suspend),(dpy,suspend),return)
#endif
#if SDL_VIDEO_DRIVER_X11_XSHAPE
SDL_X11_MODULE(XSHAPE)
SDL_X11_SYM(void,XShapeCombineMask,(Display *dpy,Window dest,int dest_kind,int x_off,int y_off,Pixmap src,int op),(dpy,dest,dest_kind,x_off,y_off,src,op),)
#endif
#if SDL_VIDEO_DRIVER_X11_XVIDMODE
SDL_X11_MODULE(XVIDMODE)
SDL_X11_SYM(Bool,XF86VidModeGetAllModeLines,(Display *a,int b,int *c,XF86VidModeModeInfo ***d),(a,b,c,d),return)
SDL_X11_SYM(Bool,XF86VidModeGetModeLine,(Display *a,int b,int *c,XF86VidModeModeLine *d),(a,b,c,d),return)
SDL_X11_SYM(Bool,XF86VidModeGetViewPort,(Display *a,int b,int *c,int *d),(a,b,c,d),return)
SDL_X11_SYM(Bool,XF86VidModeQueryExtension,(Display *a,int *b,int *c),(a,b,c),return)
SDL_X11_SYM(Bool,XF86VidModeQueryVersion,(Display *a,int *b,int *c),(a,b,c),return)
SDL_X11_SYM(Bool,XF86VidModeSwitchToMode,(Display *a,int b,XF86VidModeModeInfo *c),(a,b,c),return)
SDL_X11_SYM(Bool,XF86VidModeLockModeSwitch,(Display *a,int b,int c),(a,b,c),return)
#endif
#undef SDL_X11_MODULE
#undef SDL_X11_SYM
/* *INDENT-ON* */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11sym.h | C | apache-2.0 | 23,484 |
/*
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_X11
#include "SDL_x11video.h"
#include "SDL_x11touch.h"
#include "SDL_x11xinput2.h"
#include "../../events/SDL_touch_c.h"
void
X11_InitTouch(_THIS)
{
if (X11_Xinput2IsMultitouchSupported()) {
X11_InitXinput2Multitouch(_this);
}
}
void
X11_QuitTouch(_THIS)
{
SDL_TouchQuit();
}
void
X11_ResetTouch(_THIS)
{
X11_QuitTouch(_this);
X11_InitTouch(_this);
}
#endif /* SDL_VIDEO_DRIVER_X11 */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11touch.c | C | apache-2.0 | 1,449 |
/*
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_x11touch_h_
#define SDL_x11touch_h_
extern void X11_InitTouch(_THIS);
extern void X11_QuitTouch(_THIS);
extern void X11_ResetTouch(_THIS);
#endif /* SDL_x11touch_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11touch.h | C | apache-2.0 | 1,190 |
/*
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_X11
#include <unistd.h> /* For getpid() and readlink() */
#include "SDL_video.h"
#include "SDL_mouse.h"
#include "SDL_timer.h"
#include "SDL_hints.h"
#include "../SDL_sysvideo.h"
#include "../SDL_pixels_c.h"
#include "SDL_x11video.h"
#include "SDL_x11framebuffer.h"
#include "SDL_x11shape.h"
#include "SDL_x11touch.h"
#include "SDL_x11xinput2.h"
#if SDL_VIDEO_OPENGL_EGL
#include "SDL_x11opengles.h"
#endif
#include "SDL_x11vulkan.h"
/* Initialization/Query functions */
static int X11_VideoInit(_THIS);
static void X11_VideoQuit(_THIS);
/* Find out what class name we should use */
static char *
get_classname()
{
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_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");
}
/* X11 driver bootstrap functions */
static int
X11_Available(void)
{
Display *display = NULL;
if (SDL_X11_LoadSymbols()) {
display = X11_XOpenDisplay(NULL);
if (display != NULL) {
X11_XCloseDisplay(display);
}
SDL_X11_UnloadSymbols();
}
return (display != NULL);
}
static void
X11_DeleteDevice(SDL_VideoDevice * device)
{
SDL_VideoData *data = (SDL_VideoData *) device->driverdata;
if (device->vulkan_config.loader_handle) {
device->Vulkan_UnloadLibrary(device);
}
if (data->display) {
X11_XCloseDisplay(data->display);
}
SDL_free(data->windowlist);
SDL_free(device->driverdata);
SDL_free(device);
SDL_X11_UnloadSymbols();
}
/* An error handler to reset the vidmode and then call the default handler. */
static SDL_bool safety_net_triggered = SDL_FALSE;
static int (*orig_x11_errhandler) (Display *, XErrorEvent *) = NULL;
static int
X11_SafetyNetErrHandler(Display * d, XErrorEvent * e)
{
SDL_VideoDevice *device = NULL;
/* if we trigger an error in our error handler, don't try again. */
if (!safety_net_triggered) {
safety_net_triggered = SDL_TRUE;
device = SDL_GetVideoDevice();
if (device != NULL) {
int i;
for (i = 0; i < device->num_displays; i++) {
SDL_VideoDisplay *display = &device->displays[i];
if (SDL_memcmp(&display->current_mode, &display->desktop_mode,
sizeof (SDL_DisplayMode)) != 0) {
X11_SetDisplayMode(device, display, &display->desktop_mode);
}
}
}
}
if (orig_x11_errhandler != NULL) {
return orig_x11_errhandler(d, e); /* probably terminate. */
}
return 0;
}
static SDL_VideoDevice *
X11_CreateDevice(int devindex)
{
SDL_VideoDevice *device;
SDL_VideoData *data;
const char *display = NULL; /* Use the DISPLAY environment variable */
if (!SDL_X11_LoadSymbols()) {
return NULL;
}
/* Need for threading gl calls. This is also required for the proprietary
nVidia driver to be threaded. */
X11_XInitThreads();
/* Initialize all variables that we clean on shutdown */
device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice));
if (!device) {
SDL_OutOfMemory();
return NULL;
}
data = (struct SDL_VideoData *) SDL_calloc(1, sizeof(SDL_VideoData));
if (!data) {
SDL_free(device);
SDL_OutOfMemory();
return NULL;
}
device->driverdata = data;
data->global_mouse_changed = SDL_TRUE;
/* FIXME: Do we need this?
if ( (SDL_strncmp(X11_XDisplayName(display), ":", 1) == 0) ||
(SDL_strncmp(X11_XDisplayName(display), "unix:", 5) == 0) ) {
local_X11 = 1;
} else {
local_X11 = 0;
}
*/
data->display = X11_XOpenDisplay(display);
#ifdef SDL_VIDEO_DRIVER_X11_DYNAMIC
/* On some systems if linking without -lX11, it fails and you get following message.
* Xlib: connection to ":0.0" refused by server
* Xlib: XDM authorization key matches an existing client!
*
* It succeeds if retrying 1 second later
* or if running xhost +localhost on shell.
*/
if (data->display == NULL) {
SDL_Delay(1000);
data->display = X11_XOpenDisplay(display);
}
#endif
if (data->display == NULL) {
SDL_free(device->driverdata);
SDL_free(device);
SDL_SetError("Couldn't open X11 display");
return NULL;
}
#ifdef X11_DEBUG
X11_XSynchronize(data->display, True);
#endif
/* Hook up an X11 error handler to recover the desktop resolution. */
safety_net_triggered = SDL_FALSE;
orig_x11_errhandler = X11_XSetErrorHandler(X11_SafetyNetErrHandler);
/* Set the function pointers */
device->VideoInit = X11_VideoInit;
device->VideoQuit = X11_VideoQuit;
device->ResetTouch = X11_ResetTouch;
device->GetDisplayModes = X11_GetDisplayModes;
device->GetDisplayBounds = X11_GetDisplayBounds;
device->GetDisplayUsableBounds = X11_GetDisplayUsableBounds;
device->GetDisplayDPI = X11_GetDisplayDPI;
device->SetDisplayMode = X11_SetDisplayMode;
device->SuspendScreenSaver = X11_SuspendScreenSaver;
device->PumpEvents = X11_PumpEvents;
device->CreateSDLWindow = X11_CreateWindow;
device->CreateSDLWindowFrom = X11_CreateWindowFrom;
device->SetWindowTitle = X11_SetWindowTitle;
device->SetWindowIcon = X11_SetWindowIcon;
device->SetWindowPosition = X11_SetWindowPosition;
device->SetWindowSize = X11_SetWindowSize;
device->SetWindowMinimumSize = X11_SetWindowMinimumSize;
device->SetWindowMaximumSize = X11_SetWindowMaximumSize;
device->GetWindowBordersSize = X11_GetWindowBordersSize;
device->SetWindowOpacity = X11_SetWindowOpacity;
device->SetWindowModalFor = X11_SetWindowModalFor;
device->SetWindowInputFocus = X11_SetWindowInputFocus;
device->ShowWindow = X11_ShowWindow;
device->HideWindow = X11_HideWindow;
device->RaiseWindow = X11_RaiseWindow;
device->MaximizeWindow = X11_MaximizeWindow;
device->MinimizeWindow = X11_MinimizeWindow;
device->RestoreWindow = X11_RestoreWindow;
device->SetWindowBordered = X11_SetWindowBordered;
device->SetWindowResizable = X11_SetWindowResizable;
device->SetWindowFullscreen = X11_SetWindowFullscreen;
device->SetWindowGammaRamp = X11_SetWindowGammaRamp;
device->SetWindowGrab = X11_SetWindowGrab;
device->DestroyWindow = X11_DestroyWindow;
device->CreateWindowFramebuffer = X11_CreateWindowFramebuffer;
device->UpdateWindowFramebuffer = X11_UpdateWindowFramebuffer;
device->DestroyWindowFramebuffer = X11_DestroyWindowFramebuffer;
device->GetWindowWMInfo = X11_GetWindowWMInfo;
device->SetWindowHitTest = X11_SetWindowHitTest;
device->AcceptDragAndDrop = X11_AcceptDragAndDrop;
device->shape_driver.CreateShaper = X11_CreateShaper;
device->shape_driver.SetWindowShape = X11_SetWindowShape;
device->shape_driver.ResizeWindowShape = X11_ResizeWindowShape;
#if SDL_VIDEO_OPENGL_GLX
device->GL_LoadLibrary = X11_GL_LoadLibrary;
device->GL_GetProcAddress = X11_GL_GetProcAddress;
device->GL_UnloadLibrary = X11_GL_UnloadLibrary;
device->GL_CreateContext = X11_GL_CreateContext;
device->GL_MakeCurrent = X11_GL_MakeCurrent;
device->GL_SetSwapInterval = X11_GL_SetSwapInterval;
device->GL_GetSwapInterval = X11_GL_GetSwapInterval;
device->GL_SwapWindow = X11_GL_SwapWindow;
device->GL_DeleteContext = X11_GL_DeleteContext;
#endif
#if SDL_VIDEO_OPENGL_EGL
#if SDL_VIDEO_OPENGL_GLX
if (SDL_GetHintBoolean(SDL_HINT_VIDEO_X11_FORCE_EGL, SDL_FALSE)) {
#endif
device->GL_LoadLibrary = X11_GLES_LoadLibrary;
device->GL_GetProcAddress = X11_GLES_GetProcAddress;
device->GL_UnloadLibrary = X11_GLES_UnloadLibrary;
device->GL_CreateContext = X11_GLES_CreateContext;
device->GL_MakeCurrent = X11_GLES_MakeCurrent;
device->GL_SetSwapInterval = X11_GLES_SetSwapInterval;
device->GL_GetSwapInterval = X11_GLES_GetSwapInterval;
device->GL_SwapWindow = X11_GLES_SwapWindow;
device->GL_DeleteContext = X11_GLES_DeleteContext;
#if SDL_VIDEO_OPENGL_GLX
}
#endif
#endif
device->SetClipboardText = X11_SetClipboardText;
device->GetClipboardText = X11_GetClipboardText;
device->HasClipboardText = X11_HasClipboardText;
device->StartTextInput = X11_StartTextInput;
device->StopTextInput = X11_StopTextInput;
device->SetTextInputRect = X11_SetTextInputRect;
device->free = X11_DeleteDevice;
#if SDL_VIDEO_VULKAN
device->Vulkan_LoadLibrary = X11_Vulkan_LoadLibrary;
device->Vulkan_UnloadLibrary = X11_Vulkan_UnloadLibrary;
device->Vulkan_GetInstanceExtensions = X11_Vulkan_GetInstanceExtensions;
device->Vulkan_CreateSurface = X11_Vulkan_CreateSurface;
#endif
return device;
}
VideoBootStrap X11_bootstrap = {
"x11", "SDL X11 video driver",
X11_Available, X11_CreateDevice
};
static int (*handler) (Display *, XErrorEvent *) = NULL;
static int
X11_CheckWindowManagerErrorHandler(Display * d, XErrorEvent * e)
{
if (e->error_code == BadWindow) {
return (0);
} else {
return (handler(d, e));
}
}
static void
X11_CheckWindowManager(_THIS)
{
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
Display *display = data->display;
Atom _NET_SUPPORTING_WM_CHECK;
int status, real_format;
Atom real_type;
unsigned long items_read = 0, items_left = 0;
unsigned char *propdata = NULL;
Window wm_window = 0;
#ifdef DEBUG_WINDOW_MANAGER
char *wm_name;
#endif
/* Set up a handler to gracefully catch errors */
X11_XSync(display, False);
handler = X11_XSetErrorHandler(X11_CheckWindowManagerErrorHandler);
_NET_SUPPORTING_WM_CHECK = X11_XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False);
status = X11_XGetWindowProperty(display, DefaultRootWindow(display), _NET_SUPPORTING_WM_CHECK, 0L, 1L, False, XA_WINDOW, &real_type, &real_format, &items_read, &items_left, &propdata);
if (status == Success) {
if (items_read) {
wm_window = ((Window*)propdata)[0];
}
if (propdata) {
X11_XFree(propdata);
propdata = NULL;
}
}
if (wm_window) {
status = X11_XGetWindowProperty(display, wm_window, _NET_SUPPORTING_WM_CHECK, 0L, 1L, False, XA_WINDOW, &real_type, &real_format, &items_read, &items_left, &propdata);
if (status != Success || !items_read || wm_window != ((Window*)propdata)[0]) {
wm_window = None;
}
if (status == Success && propdata) {
X11_XFree(propdata);
propdata = NULL;
}
}
/* Reset the error handler, we're done checking */
X11_XSync(display, False);
X11_XSetErrorHandler(handler);
if (!wm_window) {
#ifdef DEBUG_WINDOW_MANAGER
printf("Couldn't get _NET_SUPPORTING_WM_CHECK property\n");
#endif
return;
}
data->net_wm = SDL_TRUE;
#ifdef DEBUG_WINDOW_MANAGER
wm_name = X11_GetWindowTitle(_this, wm_window);
printf("Window manager: %s\n", wm_name);
SDL_free(wm_name);
#endif
}
int
X11_VideoInit(_THIS)
{
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
/* Get the window class name, usually the name of the application */
data->classname = get_classname();
/* Get the process PID to be associated to the window */
data->pid = getpid();
/* I have no idea how random this actually is, or has to be. */
data->window_group = (XID) (((size_t) data->pid) ^ ((size_t) _this));
/* Look up some useful Atoms */
#define GET_ATOM(X) data->X = X11_XInternAtom(data->display, #X, False)
GET_ATOM(WM_PROTOCOLS);
GET_ATOM(WM_DELETE_WINDOW);
GET_ATOM(WM_TAKE_FOCUS);
GET_ATOM(_NET_WM_STATE);
GET_ATOM(_NET_WM_STATE_HIDDEN);
GET_ATOM(_NET_WM_STATE_FOCUSED);
GET_ATOM(_NET_WM_STATE_MAXIMIZED_VERT);
GET_ATOM(_NET_WM_STATE_MAXIMIZED_HORZ);
GET_ATOM(_NET_WM_STATE_FULLSCREEN);
GET_ATOM(_NET_WM_STATE_ABOVE);
GET_ATOM(_NET_WM_STATE_SKIP_TASKBAR);
GET_ATOM(_NET_WM_STATE_SKIP_PAGER);
GET_ATOM(_NET_WM_ALLOWED_ACTIONS);
GET_ATOM(_NET_WM_ACTION_FULLSCREEN);
GET_ATOM(_NET_WM_NAME);
GET_ATOM(_NET_WM_ICON_NAME);
GET_ATOM(_NET_WM_ICON);
GET_ATOM(_NET_WM_PING);
GET_ATOM(_NET_WM_WINDOW_OPACITY);
GET_ATOM(_NET_WM_USER_TIME);
GET_ATOM(_NET_ACTIVE_WINDOW);
GET_ATOM(_NET_FRAME_EXTENTS);
GET_ATOM(UTF8_STRING);
GET_ATOM(PRIMARY);
GET_ATOM(XdndEnter);
GET_ATOM(XdndPosition);
GET_ATOM(XdndStatus);
GET_ATOM(XdndTypeList);
GET_ATOM(XdndActionCopy);
GET_ATOM(XdndDrop);
GET_ATOM(XdndFinished);
GET_ATOM(XdndSelection);
GET_ATOM(XKLAVIER_STATE);
/* Detect the window manager */
X11_CheckWindowManager(_this);
if (X11_InitModes(_this) < 0) {
return -1;
}
X11_InitXinput2(_this);
if (X11_InitKeyboard(_this) != 0) {
return -1;
}
X11_InitMouse(_this);
X11_InitTouch(_this);
#if SDL_USE_LIBDBUS
SDL_DBus_Init();
#endif
return 0;
}
void
X11_VideoQuit(_THIS)
{
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
if (data->clipboard_window) {
X11_XDestroyWindow(data->display, data->clipboard_window);
}
SDL_free(data->classname);
#ifdef X_HAVE_UTF8_STRING
if (data->im) {
X11_XCloseIM(data->im);
}
#endif
X11_QuitModes(_this);
X11_QuitKeyboard(_this);
X11_QuitMouse(_this);
X11_QuitTouch(_this);
/* !!! FIXME: other subsystems use D-Bus, so we shouldn't quit it here;
have SDL.c do this at a higher level, or add refcounting. */
#if SDL_USE_LIBDBUS
SDL_DBus_Quit();
#endif
}
SDL_bool
X11_UseDirectColorVisuals(void)
{
return SDL_getenv("SDL_VIDEO_X11_NODIRECTCOLOR") ? SDL_FALSE : SDL_TRUE;
}
#endif /* SDL_VIDEO_DRIVER_X11 */
/* vim: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11video.c | C | apache-2.0 | 15,844 |
/*
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_x11video_h_
#define SDL_x11video_h_
#include "SDL_keycode.h"
#include "../SDL_sysvideo.h"
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#if SDL_VIDEO_DRIVER_X11_XCURSOR
#include <X11/Xcursor/Xcursor.h>
#endif
#if SDL_VIDEO_DRIVER_X11_XDBE
#include <X11/extensions/Xdbe.h>
#endif
#if SDL_VIDEO_DRIVER_X11_XINERAMA
#include <X11/extensions/Xinerama.h>
#endif
#if SDL_VIDEO_DRIVER_X11_XINPUT2
#include <X11/extensions/XInput2.h>
#endif
#if SDL_VIDEO_DRIVER_X11_XRANDR
#include <X11/extensions/Xrandr.h>
#endif
#if SDL_VIDEO_DRIVER_X11_XSCRNSAVER
#include <X11/extensions/scrnsaver.h>
#endif
#if SDL_VIDEO_DRIVER_X11_XSHAPE
#include <X11/extensions/shape.h>
#endif
#if SDL_VIDEO_DRIVER_X11_XVIDMODE
#include <X11/extensions/xf86vmode.h>
#endif
#include "../../core/linux/SDL_dbus.h"
#include "../../core/linux/SDL_ime.h"
#include "SDL_x11dyn.h"
#include "SDL_x11clipboard.h"
#include "SDL_x11events.h"
#include "SDL_x11keyboard.h"
#include "SDL_x11modes.h"
#include "SDL_x11mouse.h"
#include "SDL_x11opengl.h"
#include "SDL_x11window.h"
#include "SDL_x11vulkan.h"
/* Private display data */
typedef struct SDL_VideoData
{
Display *display;
char *classname;
pid_t pid;
XIM im;
Uint32 screensaver_activity;
int numwindows;
SDL_WindowData **windowlist;
int windowlistlength;
XID window_group;
Window clipboard_window;
/* This is true for ICCCM2.0-compliant window managers */
SDL_bool net_wm;
/* Useful atoms */
Atom WM_PROTOCOLS;
Atom WM_DELETE_WINDOW;
Atom WM_TAKE_FOCUS;
Atom _NET_WM_STATE;
Atom _NET_WM_STATE_HIDDEN;
Atom _NET_WM_STATE_FOCUSED;
Atom _NET_WM_STATE_MAXIMIZED_VERT;
Atom _NET_WM_STATE_MAXIMIZED_HORZ;
Atom _NET_WM_STATE_FULLSCREEN;
Atom _NET_WM_STATE_ABOVE;
Atom _NET_WM_STATE_SKIP_TASKBAR;
Atom _NET_WM_STATE_SKIP_PAGER;
Atom _NET_WM_ALLOWED_ACTIONS;
Atom _NET_WM_ACTION_FULLSCREEN;
Atom _NET_WM_NAME;
Atom _NET_WM_ICON_NAME;
Atom _NET_WM_ICON;
Atom _NET_WM_PING;
Atom _NET_WM_WINDOW_OPACITY;
Atom _NET_WM_USER_TIME;
Atom _NET_ACTIVE_WINDOW;
Atom _NET_FRAME_EXTENTS;
Atom UTF8_STRING;
Atom PRIMARY;
Atom XdndEnter;
Atom XdndPosition;
Atom XdndStatus;
Atom XdndTypeList;
Atom XdndActionCopy;
Atom XdndDrop;
Atom XdndFinished;
Atom XdndSelection;
Atom XKLAVIER_STATE;
SDL_Scancode key_layout[256];
SDL_bool selection_waiting;
SDL_bool broken_pointer_grab; /* true if XGrabPointer seems unreliable. */
Uint32 last_mode_change_deadline;
SDL_bool global_mouse_changed;
SDL_Point global_mouse_position;
Uint32 global_mouse_buttons;
#if SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM
XkbDescPtr xkb;
#endif
KeyCode filter_code;
Time filter_time;
#if SDL_VIDEO_VULKAN
/* Vulkan variables only valid if _this->vulkan_config.loader_handle is not NULL */
void *vulkan_xlib_xcb_library;
PFN_XGetXCBConnection vulkan_XGetXCBConnection;
#endif
} SDL_VideoData;
extern SDL_bool X11_UseDirectColorVisuals(void);
#endif /* SDL_x11video_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11video.h | C | apache-2.0 | 4,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_VULKAN && SDL_VIDEO_DRIVER_X11
#include "SDL_x11video.h"
#include "SDL_assert.h"
#include "SDL_loadso.h"
#include "SDL_x11vulkan.h"
#include <X11/Xlib.h>
/*#include <xcb/xcb.h>*/
/*
typedef uint32_t xcb_window_t;
typedef uint32_t xcb_visualid_t;
*/
int X11_Vulkan_LoadLibrary(_THIS, const char *path)
{
SDL_VideoData *videoData = (SDL_VideoData *)_this->driverdata;
VkExtensionProperties *extensions = NULL;
Uint32 extensionCount = 0;
SDL_bool hasSurfaceExtension = SDL_FALSE;
SDL_bool hasXlibSurfaceExtension = SDL_FALSE;
SDL_bool hasXCBSurfaceExtension = SDL_FALSE;
PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL;
Uint32 i;
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_XCB_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0)
hasXCBSurfaceExtension = SDL_TRUE;
else if(SDL_strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0)
hasXlibSurfaceExtension = SDL_TRUE;
}
SDL_free(extensions);
if(!hasSurfaceExtension)
{
SDL_SetError("Installed Vulkan doesn't implement the "
VK_KHR_SURFACE_EXTENSION_NAME " extension");
goto fail;
}
if(hasXlibSurfaceExtension)
{
videoData->vulkan_xlib_xcb_library = NULL;
}
else if(!hasXCBSurfaceExtension)
{
SDL_SetError("Installed Vulkan doesn't implement either the "
VK_KHR_XCB_SURFACE_EXTENSION_NAME "extension or the "
VK_KHR_XLIB_SURFACE_EXTENSION_NAME " extension");
goto fail;
}
else
{
const char *libX11XCBLibraryName = SDL_getenv("SDL_X11_XCB_LIBRARY");
if(!libX11XCBLibraryName)
libX11XCBLibraryName = "libX11-xcb.so";
videoData->vulkan_xlib_xcb_library = SDL_LoadObject(libX11XCBLibraryName);
if(!videoData->vulkan_xlib_xcb_library)
goto fail;
videoData->vulkan_XGetXCBConnection =
SDL_LoadFunction(videoData->vulkan_xlib_xcb_library, "XGetXCBConnection");
if(!videoData->vulkan_XGetXCBConnection)
{
SDL_UnloadObject(videoData->vulkan_xlib_xcb_library);
goto fail;
}
}
return 0;
fail:
SDL_UnloadObject(_this->vulkan_config.loader_handle);
_this->vulkan_config.loader_handle = NULL;
return -1;
}
void X11_Vulkan_UnloadLibrary(_THIS)
{
SDL_VideoData *videoData = (SDL_VideoData *)_this->driverdata;
if(_this->vulkan_config.loader_handle)
{
if(videoData->vulkan_xlib_xcb_library)
SDL_UnloadObject(videoData->vulkan_xlib_xcb_library);
SDL_UnloadObject(_this->vulkan_config.loader_handle);
_this->vulkan_config.loader_handle = NULL;
}
}
SDL_bool X11_Vulkan_GetInstanceExtensions(_THIS,
SDL_Window *window,
unsigned *count,
const char **names)
{
SDL_VideoData *videoData = (SDL_VideoData *)_this->driverdata;
if(!_this->vulkan_config.loader_handle)
{
SDL_SetError("Vulkan is not loaded");
return SDL_FALSE;
}
if(videoData->vulkan_xlib_xcb_library)
{
static const char *const extensionsForXCB[] = {
VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_XCB_SURFACE_EXTENSION_NAME,
};
return SDL_Vulkan_GetInstanceExtensions_Helper(
count, names, SDL_arraysize(extensionsForXCB), extensionsForXCB);
}
else
{
static const char *const extensionsForXlib[] = {
VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_XLIB_SURFACE_EXTENSION_NAME,
};
return SDL_Vulkan_GetInstanceExtensions_Helper(
count, names, SDL_arraysize(extensionsForXlib), extensionsForXlib);
}
}
SDL_bool X11_Vulkan_CreateSurface(_THIS,
SDL_Window *window,
VkInstance instance,
VkSurfaceKHR *surface)
{
SDL_VideoData *videoData = (SDL_VideoData *)_this->driverdata;
SDL_WindowData *windowData = (SDL_WindowData *)window->driverdata;
PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr;
if(!_this->vulkan_config.loader_handle)
{
SDL_SetError("Vulkan is not loaded");
return SDL_FALSE;
}
vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr;
if(videoData->vulkan_xlib_xcb_library)
{
PFN_vkCreateXcbSurfaceKHR vkCreateXcbSurfaceKHR =
(PFN_vkCreateXcbSurfaceKHR)vkGetInstanceProcAddr(instance,
"vkCreateXcbSurfaceKHR");
VkXcbSurfaceCreateInfoKHR createInfo;
VkResult result;
if(!vkCreateXcbSurfaceKHR)
{
SDL_SetError(VK_KHR_XCB_SURFACE_EXTENSION_NAME
" extension is not enabled in the Vulkan instance.");
return SDL_FALSE;
}
SDL_zero(createInfo);
createInfo.sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR;
createInfo.connection = videoData->vulkan_XGetXCBConnection(videoData->display);
if(!createInfo.connection)
{
SDL_SetError("XGetXCBConnection failed");
return SDL_FALSE;
}
createInfo.window = (xcb_window_t)windowData->xwindow;
result = vkCreateXcbSurfaceKHR(instance, &createInfo,
NULL, surface);
if(result != VK_SUCCESS)
{
SDL_SetError("vkCreateXcbSurfaceKHR failed: %s", SDL_Vulkan_GetResultString(result));
return SDL_FALSE;
}
return SDL_TRUE;
}
else
{
PFN_vkCreateXlibSurfaceKHR vkCreateXlibSurfaceKHR =
(PFN_vkCreateXlibSurfaceKHR)vkGetInstanceProcAddr(instance,
"vkCreateXlibSurfaceKHR");
VkXlibSurfaceCreateInfoKHR createInfo;
VkResult result;
if(!vkCreateXlibSurfaceKHR)
{
SDL_SetError(VK_KHR_XLIB_SURFACE_EXTENSION_NAME
" extension is not enabled in the Vulkan instance.");
return SDL_FALSE;
}
SDL_zero(createInfo);
createInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
createInfo.dpy = videoData->display;
createInfo.window = (xcb_window_t)windowData->xwindow;
result = vkCreateXlibSurfaceKHR(instance, &createInfo,
NULL, surface);
if(result != VK_SUCCESS)
{
SDL_SetError("vkCreateXlibSurfaceKHR 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/x11/SDL_x11vulkan.c | C | apache-2.0 | 9,310 |
/*
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_x11vulkan_h_
#define SDL_x11vulkan_h_
#include "../SDL_vulkan_internal.h"
#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_X11
/*typedef struct xcb_connection_t xcb_connection_t;*/
typedef xcb_connection_t *(*PFN_XGetXCBConnection)(Display *dpy);
int X11_Vulkan_LoadLibrary(_THIS, const char *path);
void X11_Vulkan_UnloadLibrary(_THIS);
SDL_bool X11_Vulkan_GetInstanceExtensions(_THIS,
SDL_Window *window,
unsigned *count,
const char **names);
SDL_bool X11_Vulkan_CreateSurface(_THIS,
SDL_Window *window,
VkInstance instance,
VkSurfaceKHR *surface);
#endif
#endif /* SDL_x11vulkan_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11vulkan.h | C | apache-2.0 | 1,834 |
/*
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_X11
#include "SDL_assert.h"
#include "SDL_hints.h"
#include "../SDL_sysvideo.h"
#include "../SDL_pixels_c.h"
#include "../../events/SDL_keyboard_c.h"
#include "../../events/SDL_mouse_c.h"
#include "SDL_x11video.h"
#include "SDL_x11mouse.h"
#include "SDL_x11shape.h"
#include "SDL_x11xinput2.h"
#if SDL_VIDEO_OPENGL_EGL
#include "SDL_x11opengles.h"
#endif
#include "SDL_timer.h"
#include "SDL_syswm.h"
#define _NET_WM_STATE_REMOVE 0l
#define _NET_WM_STATE_ADD 1l
static Bool isMapNotify(Display *dpy, XEvent *ev, XPointer win)
{
return ev->type == MapNotify && ev->xmap.window == *((Window*)win);
}
static Bool isUnmapNotify(Display *dpy, XEvent *ev, XPointer win)
{
return ev->type == UnmapNotify && ev->xunmap.window == *((Window*)win);
}
/*
static Bool isConfigureNotify(Display *dpy, XEvent *ev, XPointer win)
{
return ev->type == ConfigureNotify && ev->xconfigure.window == *((Window*)win);
}
static Bool
X11_XIfEventTimeout(Display *display, XEvent *event_return, Bool (*predicate)(), XPointer arg, int timeoutMS)
{
Uint32 start = SDL_GetTicks();
while (!X11_XCheckIfEvent(display, event_return, predicate, arg)) {
if (SDL_TICKS_PASSED(SDL_GetTicks(), start + timeoutMS)) {
return False;
}
}
return True;
}
*/
static SDL_bool
X11_IsWindowLegacyFullscreen(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
return (data->fswindow != 0);
}
static SDL_bool
X11_IsWindowMapped(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
XWindowAttributes attr;
X11_XGetWindowAttributes(videodata->display, data->xwindow, &attr);
if (attr.map_state != IsUnmapped) {
return SDL_TRUE;
} else {
return SDL_FALSE;
}
}
#if 0
static SDL_bool
X11_IsActionAllowed(SDL_Window *window, Atom action)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Atom _NET_WM_ALLOWED_ACTIONS = data->videodata->_NET_WM_ALLOWED_ACTIONS;
Atom type;
Display *display = data->videodata->display;
int form;
unsigned long remain;
unsigned long len, i;
Atom *list;
SDL_bool ret = SDL_FALSE;
if (X11_XGetWindowProperty(display, data->xwindow, _NET_WM_ALLOWED_ACTIONS, 0, 1024, False, XA_ATOM, &type, &form, &len, &remain, (unsigned char **)&list) == Success)
{
for (i=0; i<len; ++i)
{
if (list[i] == action) {
ret = SDL_TRUE;
break;
}
}
X11_XFree(list);
}
return ret;
}
#endif /* 0 */
void
X11_SetNetWMState(_THIS, Window xwindow, Uint32 flags)
{
SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
Display *display = videodata->display;
/* !!! FIXME: just dereference videodata below instead of copying to locals. */
Atom _NET_WM_STATE = videodata->_NET_WM_STATE;
/* Atom _NET_WM_STATE_HIDDEN = videodata->_NET_WM_STATE_HIDDEN; */
Atom _NET_WM_STATE_FOCUSED = videodata->_NET_WM_STATE_FOCUSED;
Atom _NET_WM_STATE_MAXIMIZED_VERT = videodata->_NET_WM_STATE_MAXIMIZED_VERT;
Atom _NET_WM_STATE_MAXIMIZED_HORZ = videodata->_NET_WM_STATE_MAXIMIZED_HORZ;
Atom _NET_WM_STATE_FULLSCREEN = videodata->_NET_WM_STATE_FULLSCREEN;
Atom _NET_WM_STATE_ABOVE = videodata->_NET_WM_STATE_ABOVE;
Atom _NET_WM_STATE_SKIP_TASKBAR = videodata->_NET_WM_STATE_SKIP_TASKBAR;
Atom _NET_WM_STATE_SKIP_PAGER = videodata->_NET_WM_STATE_SKIP_PAGER;
Atom atoms[16];
int count = 0;
/* The window manager sets this property, we shouldn't set it.
If we did, this would indicate to the window manager that we don't
actually want to be mapped during X11_XMapRaised(), which would be bad.
*
if (flags & SDL_WINDOW_HIDDEN) {
atoms[count++] = _NET_WM_STATE_HIDDEN;
}
*/
if (flags & SDL_WINDOW_ALWAYS_ON_TOP) {
atoms[count++] = _NET_WM_STATE_ABOVE;
}
if (flags & SDL_WINDOW_SKIP_TASKBAR) {
atoms[count++] = _NET_WM_STATE_SKIP_TASKBAR;
atoms[count++] = _NET_WM_STATE_SKIP_PAGER;
}
if (flags & SDL_WINDOW_INPUT_FOCUS) {
atoms[count++] = _NET_WM_STATE_FOCUSED;
}
if (flags & SDL_WINDOW_MAXIMIZED) {
atoms[count++] = _NET_WM_STATE_MAXIMIZED_VERT;
atoms[count++] = _NET_WM_STATE_MAXIMIZED_HORZ;
}
if (flags & SDL_WINDOW_FULLSCREEN) {
atoms[count++] = _NET_WM_STATE_FULLSCREEN;
}
SDL_assert(count <= SDL_arraysize(atoms));
if (count > 0) {
X11_XChangeProperty(display, xwindow, _NET_WM_STATE, XA_ATOM, 32,
PropModeReplace, (unsigned char *)atoms, count);
} else {
X11_XDeleteProperty(display, xwindow, _NET_WM_STATE);
}
}
Uint32
X11_GetNetWMState(_THIS, Window xwindow)
{
SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
Display *display = videodata->display;
Atom _NET_WM_STATE = videodata->_NET_WM_STATE;
Atom _NET_WM_STATE_HIDDEN = videodata->_NET_WM_STATE_HIDDEN;
Atom _NET_WM_STATE_FOCUSED = videodata->_NET_WM_STATE_FOCUSED;
Atom _NET_WM_STATE_MAXIMIZED_VERT = videodata->_NET_WM_STATE_MAXIMIZED_VERT;
Atom _NET_WM_STATE_MAXIMIZED_HORZ = videodata->_NET_WM_STATE_MAXIMIZED_HORZ;
Atom _NET_WM_STATE_FULLSCREEN = videodata->_NET_WM_STATE_FULLSCREEN;
Atom actualType;
int actualFormat;
unsigned long i, numItems, bytesAfter;
unsigned char *propertyValue = NULL;
long maxLength = 1024;
Uint32 flags = 0;
if (X11_XGetWindowProperty(display, xwindow, _NET_WM_STATE,
0l, maxLength, False, XA_ATOM, &actualType,
&actualFormat, &numItems, &bytesAfter,
&propertyValue) == Success) {
Atom *atoms = (Atom *) propertyValue;
int maximized = 0;
int fullscreen = 0;
for (i = 0; i < numItems; ++i) {
if (atoms[i] == _NET_WM_STATE_HIDDEN) {
flags |= SDL_WINDOW_HIDDEN;
} else if (atoms[i] == _NET_WM_STATE_FOCUSED) {
flags |= SDL_WINDOW_INPUT_FOCUS;
} else if (atoms[i] == _NET_WM_STATE_MAXIMIZED_VERT) {
maximized |= 1;
} else if (atoms[i] == _NET_WM_STATE_MAXIMIZED_HORZ) {
maximized |= 2;
} else if ( atoms[i] == _NET_WM_STATE_FULLSCREEN) {
fullscreen = 1;
}
}
if (maximized == 3) {
flags |= SDL_WINDOW_MAXIMIZED;
}
if (fullscreen == 1) {
flags |= SDL_WINDOW_FULLSCREEN;
}
/* If the window is unmapped, numItems will be zero and _NET_WM_STATE_HIDDEN
* will not be set. Do an additional check to see if the window is unmapped
* and mark it as SDL_WINDOW_HIDDEN if it is.
*/
{
XWindowAttributes attr;
SDL_memset(&attr,0,sizeof(attr));
X11_XGetWindowAttributes(videodata->display, xwindow, &attr);
if (attr.map_state == IsUnmapped) {
flags |= SDL_WINDOW_HIDDEN;
}
}
X11_XFree(propertyValue);
}
/* FIXME, check the size hints for resizable */
/* flags |= SDL_WINDOW_RESIZABLE; */
return flags;
}
static int
SetupWindowData(_THIS, SDL_Window * window, Window w, BOOL created)
{
SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
SDL_WindowData *data;
int numwindows = videodata->numwindows;
int windowlistlength = videodata->windowlistlength;
SDL_WindowData **windowlist = videodata->windowlist;
/* Allocate the window data */
data = (SDL_WindowData *) SDL_calloc(1, sizeof(*data));
if (!data) {
return SDL_OutOfMemory();
}
data->window = window;
data->xwindow = w;
#ifdef X_HAVE_UTF8_STRING
if (SDL_X11_HAVE_UTF8 && videodata->im) {
data->ic =
X11_XCreateIC(videodata->im, XNClientWindow, w, XNFocusWindow, w,
XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
NULL);
}
#endif
data->created = created;
data->videodata = videodata;
/* Associate the data with the window */
if (numwindows < windowlistlength) {
windowlist[numwindows] = data;
videodata->numwindows++;
} else {
windowlist =
(SDL_WindowData **) SDL_realloc(windowlist,
(numwindows +
1) * sizeof(*windowlist));
if (!windowlist) {
SDL_free(data);
return SDL_OutOfMemory();
}
windowlist[numwindows] = data;
videodata->numwindows++;
videodata->windowlistlength++;
videodata->windowlist = windowlist;
}
/* Fill in the SDL window with the window data */
{
XWindowAttributes attrib;
X11_XGetWindowAttributes(data->videodata->display, w, &attrib);
window->x = attrib.x;
window->y = attrib.y;
window->w = attrib.width;
window->h = attrib.height;
if (attrib.map_state != IsUnmapped) {
window->flags |= SDL_WINDOW_SHOWN;
} else {
window->flags &= ~SDL_WINDOW_SHOWN;
}
data->visual = attrib.visual;
data->colormap = attrib.colormap;
}
window->flags |= X11_GetNetWMState(_this, w);
{
Window FocalWindow;
int RevertTo=0;
X11_XGetInputFocus(data->videodata->display, &FocalWindow, &RevertTo);
if (FocalWindow==w)
{
window->flags |= SDL_WINDOW_INPUT_FOCUS;
}
if (window->flags & SDL_WINDOW_INPUT_FOCUS) {
SDL_SetKeyboardFocus(data->window);
}
if (window->flags & SDL_WINDOW_INPUT_GRABBED) {
/* Tell x11 to clip mouse */
}
}
/* All done! */
window->driverdata = data;
return 0;
}
static void
SetWindowBordered(Display *display, int screen, Window window, SDL_bool border)
{
/*
* this code used to check for KWM_WIN_DECORATION, but KDE hasn't
* supported it for years and years. It now respects _MOTIF_WM_HINTS.
* Gnome is similar: just use the Motif atom.
*/
Atom WM_HINTS = X11_XInternAtom(display, "_MOTIF_WM_HINTS", True);
if (WM_HINTS != None) {
/* Hints used by Motif compliant window managers */
struct
{
unsigned long flags;
unsigned long functions;
unsigned long decorations;
long input_mode;
unsigned long status;
} MWMHints = {
(1L << 1), 0, border ? 1 : 0, 0, 0
};
X11_XChangeProperty(display, window, WM_HINTS, WM_HINTS, 32,
PropModeReplace, (unsigned char *) &MWMHints,
sizeof(MWMHints) / sizeof(long));
} else { /* set the transient hints instead, if necessary */
X11_XSetTransientForHint(display, window, RootWindow(display, screen));
}
}
int
X11_CreateWindow(_THIS, SDL_Window * window)
{
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
SDL_DisplayData *displaydata =
(SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata;
SDL_WindowData *windowdata;
Display *display = data->display;
int screen = displaydata->screen;
Visual *visual;
int depth;
XSetWindowAttributes xattr;
Window w;
XSizeHints *sizehints;
XWMHints *wmhints;
XClassHint *classhints;
Atom _NET_WM_BYPASS_COMPOSITOR;
Atom _NET_WM_WINDOW_TYPE;
Atom wintype;
const char *wintype_name = NULL;
long compositor = 1;
Atom _NET_WM_PID;
long fevent = 0;
#if SDL_VIDEO_OPENGL_GLX || SDL_VIDEO_OPENGL_EGL
const char *forced_visual_id = SDL_GetHint(SDL_HINT_VIDEO_X11_WINDOW_VISUALID);
if (forced_visual_id != NULL && forced_visual_id[0] != '\0')
{
XVisualInfo *vi, template;
int nvis;
SDL_zero(template);
template.visualid = SDL_strtol(forced_visual_id, NULL, 0);
vi = X11_XGetVisualInfo(display, VisualIDMask, &template, &nvis);
if (vi) {
visual = vi->visual;
depth = vi->depth;
X11_XFree(vi);
}
else
{
return -1;
}
}
else if ((window->flags & SDL_WINDOW_OPENGL) &&
!SDL_getenv("SDL_VIDEO_X11_VISUALID")) {
XVisualInfo *vinfo = NULL;
#if SDL_VIDEO_OPENGL_EGL
if (((_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) ||
SDL_GetHintBoolean(SDL_HINT_VIDEO_X11_FORCE_EGL, SDL_FALSE))
#if SDL_VIDEO_OPENGL_GLX
&& ( !_this->gl_data || X11_GL_UseEGL(_this) )
#endif
) {
vinfo = X11_GLES_GetVisual(_this, display, screen);
} else
#endif
{
#if SDL_VIDEO_OPENGL_GLX
vinfo = X11_GL_GetVisual(_this, display, screen);
#endif
}
if (!vinfo) {
return -1;
}
visual = vinfo->visual;
depth = vinfo->depth;
X11_XFree(vinfo);
} else
#endif
{
visual = displaydata->visual;
depth = displaydata->depth;
}
xattr.override_redirect = ((window->flags & SDL_WINDOW_TOOLTIP) || (window->flags & SDL_WINDOW_POPUP_MENU)) ? True : False;
xattr.background_pixmap = None;
xattr.border_pixel = 0;
if (visual->class == DirectColor) {
XColor *colorcells;
int i;
int ncolors;
int rmax, gmax, bmax;
int rmask, gmask, bmask;
int rshift, gshift, bshift;
xattr.colormap =
X11_XCreateColormap(display, RootWindow(display, screen),
visual, AllocAll);
/* If we can't create a colormap, then we must die */
if (!xattr.colormap) {
return SDL_SetError("Could not create writable colormap");
}
/* OK, we got a colormap, now fill it in as best as we can */
colorcells = SDL_malloc(visual->map_entries * sizeof(XColor));
if (!colorcells) {
return SDL_OutOfMemory();
}
ncolors = visual->map_entries;
rmax = 0xffff;
gmax = 0xffff;
bmax = 0xffff;
rshift = 0;
rmask = visual->red_mask;
while (0 == (rmask & 1)) {
rshift++;
rmask >>= 1;
}
gshift = 0;
gmask = visual->green_mask;
while (0 == (gmask & 1)) {
gshift++;
gmask >>= 1;
}
bshift = 0;
bmask = visual->blue_mask;
while (0 == (bmask & 1)) {
bshift++;
bmask >>= 1;
}
/* build the color table pixel values */
for (i = 0; i < ncolors; i++) {
Uint32 red = (rmax * i) / (ncolors - 1);
Uint32 green = (gmax * i) / (ncolors - 1);
Uint32 blue = (bmax * i) / (ncolors - 1);
Uint32 rbits = (rmask * i) / (ncolors - 1);
Uint32 gbits = (gmask * i) / (ncolors - 1);
Uint32 bbits = (bmask * i) / (ncolors - 1);
Uint32 pix =
(rbits << rshift) | (gbits << gshift) | (bbits << bshift);
colorcells[i].pixel = pix;
colorcells[i].red = red;
colorcells[i].green = green;
colorcells[i].blue = blue;
colorcells[i].flags = DoRed | DoGreen | DoBlue;
}
X11_XStoreColors(display, xattr.colormap, colorcells, ncolors);
SDL_free(colorcells);
} else {
xattr.colormap =
X11_XCreateColormap(display, RootWindow(display, screen),
visual, AllocNone);
}
w = X11_XCreateWindow(display, RootWindow(display, screen),
window->x, window->y, window->w, window->h,
0, depth, InputOutput, visual,
(CWOverrideRedirect | CWBackPixmap | CWBorderPixel |
CWColormap), &xattr);
if (!w) {
return SDL_SetError("Couldn't create window");
}
SetWindowBordered(display, screen, w,
(window->flags & SDL_WINDOW_BORDERLESS) == 0);
sizehints = X11_XAllocSizeHints();
/* Setup the normal size hints */
sizehints->flags = 0;
if (!(window->flags & SDL_WINDOW_RESIZABLE)) {
sizehints->min_width = sizehints->max_width = window->w;
sizehints->min_height = sizehints->max_height = window->h;
sizehints->flags |= (PMaxSize | PMinSize);
}
sizehints->x = window->x;
sizehints->y = window->y;
sizehints->flags |= USPosition;
/* Setup the input hints so we get keyboard input */
wmhints = X11_XAllocWMHints();
wmhints->input = True;
wmhints->window_group = data->window_group;
wmhints->flags = InputHint | WindowGroupHint;
/* Setup the class hints so we can get an icon (AfterStep) */
classhints = X11_XAllocClassHint();
classhints->res_name = data->classname;
classhints->res_class = data->classname;
/* Set the size, input and class hints, and define WM_CLIENT_MACHINE and WM_LOCALE_NAME */
X11_XSetWMProperties(display, w, NULL, NULL, NULL, 0, sizehints, wmhints, classhints);
X11_XFree(sizehints);
X11_XFree(wmhints);
X11_XFree(classhints);
/* Set the PID related to the window for the given hostname, if possible */
if (data->pid > 0) {
long pid = (long) data->pid;
_NET_WM_PID = X11_XInternAtom(display, "_NET_WM_PID", False);
X11_XChangeProperty(display, w, _NET_WM_PID, XA_CARDINAL, 32, PropModeReplace,
(unsigned char *) &pid, 1);
}
/* Set the window manager state */
X11_SetNetWMState(_this, w, window->flags);
compositor = 2; /* don't disable compositing except for "normal" windows */
if (window->flags & SDL_WINDOW_UTILITY) {
wintype_name = "_NET_WM_WINDOW_TYPE_UTILITY";
} else if (window->flags & SDL_WINDOW_TOOLTIP) {
wintype_name = "_NET_WM_WINDOW_TYPE_TOOLTIP";
} else if (window->flags & SDL_WINDOW_POPUP_MENU) {
wintype_name = "_NET_WM_WINDOW_TYPE_POPUP_MENU";
} else {
wintype_name = "_NET_WM_WINDOW_TYPE_NORMAL";
compositor = 1; /* disable compositing for "normal" windows */
}
/* Let the window manager know what type of window we are. */
_NET_WM_WINDOW_TYPE = X11_XInternAtom(display, "_NET_WM_WINDOW_TYPE", False);
wintype = X11_XInternAtom(display, wintype_name, False);
X11_XChangeProperty(display, w, _NET_WM_WINDOW_TYPE, XA_ATOM, 32,
PropModeReplace, (unsigned char *)&wintype, 1);
if (SDL_GetHintBoolean(SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR, SDL_TRUE)) {
_NET_WM_BYPASS_COMPOSITOR = X11_XInternAtom(display, "_NET_WM_BYPASS_COMPOSITOR", False);
X11_XChangeProperty(display, w, _NET_WM_BYPASS_COMPOSITOR, XA_CARDINAL, 32,
PropModeReplace,
(unsigned char *)&compositor, 1);
}
{
Atom protocols[3];
int proto_count = 0;
protocols[proto_count++] = data->WM_DELETE_WINDOW; /* Allow window to be deleted by the WM */
protocols[proto_count++] = data->WM_TAKE_FOCUS; /* Since we will want to set input focus explicitly */
/* Default to using ping if there is no hint */
if (SDL_GetHintBoolean(SDL_HINT_VIDEO_X11_NET_WM_PING, SDL_TRUE)) {
protocols[proto_count++] = data->_NET_WM_PING; /* Respond so WM knows we're alive */
}
SDL_assert(proto_count <= sizeof(protocols) / sizeof(protocols[0]));
X11_XSetWMProtocols(display, w, protocols, proto_count);
}
if (SetupWindowData(_this, window, w, SDL_TRUE) < 0) {
X11_XDestroyWindow(display, w);
return -1;
}
windowdata = (SDL_WindowData *) window->driverdata;
#if SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 || SDL_VIDEO_OPENGL_EGL
if ((window->flags & SDL_WINDOW_OPENGL) &&
((_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) ||
SDL_GetHintBoolean(SDL_HINT_VIDEO_X11_FORCE_EGL, SDL_FALSE))
#if SDL_VIDEO_OPENGL_GLX
&& ( !_this->gl_data || X11_GL_UseEGL(_this) )
#endif
) {
#if SDL_VIDEO_OPENGL_EGL
if (!_this->egl_data) {
return -1;
}
/* Create the GLES window surface */
windowdata->egl_surface = SDL_EGL_CreateSurface(_this, (NativeWindowType) w);
if (windowdata->egl_surface == EGL_NO_SURFACE) {
return SDL_SetError("Could not create GLES window surface");
}
#else
return SDL_SetError("Could not create GLES window surface (EGL support not configured)");
#endif /* SDL_VIDEO_OPENGL_EGL */
}
#endif
#ifdef X_HAVE_UTF8_STRING
if (SDL_X11_HAVE_UTF8 && windowdata->ic) {
X11_XGetICValues(windowdata->ic, XNFilterEvents, &fevent, NULL);
}
#endif
X11_Xinput2SelectTouch(_this, window);
X11_XSelectInput(display, w,
(FocusChangeMask | EnterWindowMask | LeaveWindowMask |
ExposureMask | ButtonPressMask | ButtonReleaseMask |
PointerMotionMask | KeyPressMask | KeyReleaseMask |
PropertyChangeMask | StructureNotifyMask |
KeymapStateMask | fevent));
X11_XFlush(display);
return 0;
}
int
X11_CreateWindowFrom(_THIS, SDL_Window * window, const void *data)
{
Window w = (Window) data;
window->title = X11_GetWindowTitle(_this, w);
if (SetupWindowData(_this, window, w, SDL_FALSE) < 0) {
return -1;
}
return 0;
}
char *
X11_GetWindowTitle(_THIS, Window xwindow)
{
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
Display *display = data->display;
int status, real_format;
Atom real_type;
unsigned long items_read, items_left;
unsigned char *propdata;
char *title = NULL;
status = X11_XGetWindowProperty(display, xwindow, data->_NET_WM_NAME,
0L, 8192L, False, data->UTF8_STRING, &real_type, &real_format,
&items_read, &items_left, &propdata);
if (status == Success && propdata) {
title = SDL_strdup(SDL_static_cast(char*, propdata));
X11_XFree(propdata);
} else {
status = X11_XGetWindowProperty(display, xwindow, XA_WM_NAME,
0L, 8192L, False, XA_STRING, &real_type, &real_format,
&items_read, &items_left, &propdata);
if (status == Success && propdata) {
title = SDL_iconv_string("UTF-8", "", SDL_static_cast(char*, propdata), items_read+1);
X11_XFree(propdata);
} else {
title = SDL_strdup("");
}
}
return title;
}
void
X11_SetWindowTitle(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
XTextProperty titleprop;
Status status;
const char *title = window->title ? window->title : "";
char *title_locale = NULL;
#ifdef X_HAVE_UTF8_STRING
Atom _NET_WM_NAME = data->videodata->_NET_WM_NAME;
#endif
title_locale = SDL_iconv_utf8_locale(title);
if (!title_locale) {
SDL_OutOfMemory();
return;
}
status = X11_XStringListToTextProperty(&title_locale, 1, &titleprop);
SDL_free(title_locale);
if (status) {
X11_XSetTextProperty(display, data->xwindow, &titleprop, XA_WM_NAME);
X11_XFree(titleprop.value);
}
#ifdef X_HAVE_UTF8_STRING
if (SDL_X11_HAVE_UTF8) {
status = X11_Xutf8TextListToTextProperty(display, (char **) &title, 1,
XUTF8StringStyle, &titleprop);
if (status == Success) {
X11_XSetTextProperty(display, data->xwindow, &titleprop,
_NET_WM_NAME);
X11_XFree(titleprop.value);
}
}
#endif
X11_XFlush(display);
}
void
X11_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
Atom _NET_WM_ICON = data->videodata->_NET_WM_ICON;
if (icon) {
int propsize;
long *propdata;
/* Set the _NET_WM_ICON property */
SDL_assert(icon->format->format == SDL_PIXELFORMAT_ARGB8888);
propsize = 2 + (icon->w * icon->h);
propdata = SDL_malloc(propsize * sizeof(long));
if (propdata) {
int x, y;
Uint32 *src;
long *dst;
propdata[0] = icon->w;
propdata[1] = icon->h;
dst = &propdata[2];
for (y = 0; y < icon->h; ++y) {
src = (Uint32*)((Uint8*)icon->pixels + y * icon->pitch);
for (x = 0; x < icon->w; ++x) {
*dst++ = *src++;
}
}
X11_XChangeProperty(display, data->xwindow, _NET_WM_ICON, XA_CARDINAL,
32, PropModeReplace, (unsigned char *) propdata,
propsize);
}
SDL_free(propdata);
} else {
X11_XDeleteProperty(display, data->xwindow, _NET_WM_ICON);
}
X11_XFlush(display);
}
void
X11_SetWindowPosition(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
unsigned int childCount;
Window childReturn, root, parent;
Window* children;
XWindowAttributes attrs;
int orig_x, orig_y;
Uint32 timeout;
X11_XSync(display, False);
X11_XQueryTree(display, data->xwindow, &root, &parent, &children, &childCount);
X11_XGetWindowAttributes(display, data->xwindow, &attrs);
X11_XTranslateCoordinates(display, parent, DefaultRootWindow(display),
attrs.x, attrs.y, &orig_x, &orig_y, &childReturn);
/*Attempt to move the window*/
X11_XMoveWindow(display, data->xwindow, window->x - data->border_left, window->y - data->border_top);
/* Wait a brief time to see if the window manager decided to let this move happen.
If the window changes at all, even to an unexpected value, we break out. */
timeout = SDL_GetTicks() + 100;
while (SDL_TRUE) {
int x, y;
X11_XSync(display, False);
X11_XGetWindowAttributes(display, data->xwindow, &attrs);
X11_XTranslateCoordinates(display, parent, DefaultRootWindow(display),
attrs.x, attrs.y, &x, &y, &childReturn);
if ((x != orig_x) || (y != orig_y)) {
window->x = x;
window->y = y;
break; /* window moved, time to go. */
} else if ((x == window->x) && (y == window->y)) {
break; /* we're at the place we wanted to be anyhow, drop out. */
}
if (SDL_TICKS_PASSED(SDL_GetTicks(), timeout)) {
break;
}
SDL_Delay(10);
}
}
void
X11_SetWindowMinimumSize(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
if (window->flags & SDL_WINDOW_RESIZABLE) {
XSizeHints *sizehints = X11_XAllocSizeHints();
long userhints;
X11_XGetWMNormalHints(display, data->xwindow, sizehints, &userhints);
sizehints->min_width = window->min_w;
sizehints->min_height = window->min_h;
sizehints->flags |= PMinSize;
X11_XSetWMNormalHints(display, data->xwindow, sizehints);
X11_XFree(sizehints);
/* See comment in X11_SetWindowSize. */
X11_XResizeWindow(display, data->xwindow, window->w, window->h);
X11_XMoveWindow(display, data->xwindow, window->x - data->border_left, window->y - data->border_top);
X11_XRaiseWindow(display, data->xwindow);
}
X11_XFlush(display);
}
void
X11_SetWindowMaximumSize(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
if (window->flags & SDL_WINDOW_RESIZABLE) {
XSizeHints *sizehints = X11_XAllocSizeHints();
long userhints;
X11_XGetWMNormalHints(display, data->xwindow, sizehints, &userhints);
sizehints->max_width = window->max_w;
sizehints->max_height = window->max_h;
sizehints->flags |= PMaxSize;
X11_XSetWMNormalHints(display, data->xwindow, sizehints);
X11_XFree(sizehints);
/* See comment in X11_SetWindowSize. */
X11_XResizeWindow(display, data->xwindow, window->w, window->h);
X11_XMoveWindow(display, data->xwindow, window->x - data->border_left, window->y - data->border_top);
X11_XRaiseWindow(display, data->xwindow);
}
X11_XFlush(display);
}
void
X11_SetWindowSize(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
XWindowAttributes attrs;
int orig_w, orig_h;
Uint32 timeout;
X11_XSync(display, False);
X11_XGetWindowAttributes(display, data->xwindow, &attrs);
orig_w = attrs.width;
orig_h = attrs.height;
if (SDL_IsShapedWindow(window)) {
X11_ResizeWindowShape(window);
}
if (!(window->flags & SDL_WINDOW_RESIZABLE)) {
/* Apparently, if the X11 Window is set to a 'non-resizable' window, you cannot resize it using the X11_XResizeWindow, thus
we must set the size hints to adjust the window size. */
XSizeHints *sizehints = X11_XAllocSizeHints();
long userhints;
X11_XGetWMNormalHints(display, data->xwindow, sizehints, &userhints);
sizehints->min_width = sizehints->max_width = window->w;
sizehints->min_height = sizehints->max_height = window->h;
sizehints->flags |= PMinSize | PMaxSize;
X11_XSetWMNormalHints(display, data->xwindow, sizehints);
X11_XFree(sizehints);
/* From Pierre-Loup:
WMs each have their little quirks with that. When you change the
size hints, they get a ConfigureNotify event with the
WM_NORMAL_SIZE_HINTS Atom. They all save the hints then, but they
don't all resize the window right away to enforce the new hints.
Some of them resize only after:
- A user-initiated move or resize
- A code-initiated move or resize
- Hiding & showing window (Unmap & map)
The following move & resize seems to help a lot of WMs that didn't
properly update after the hints were changed. We don't do a
hide/show, because there are supposedly subtle problems with doing so
and transitioning from windowed to fullscreen in Unity.
*/
X11_XResizeWindow(display, data->xwindow, window->w, window->h);
X11_XMoveWindow(display, data->xwindow, window->x - data->border_left, window->y - data->border_top);
X11_XRaiseWindow(display, data->xwindow);
} else {
X11_XResizeWindow(display, data->xwindow, window->w, window->h);
}
/* Wait a brief time to see if the window manager decided to let this resize happen.
If the window changes at all, even to an unexpected value, we break out. */
timeout = SDL_GetTicks() + 100;
while (SDL_TRUE) {
X11_XSync(display, False);
X11_XGetWindowAttributes(display, data->xwindow, &attrs);
if ((attrs.width != orig_w) || (attrs.height != orig_h)) {
window->w = attrs.width;
window->h = attrs.height;
break; /* window changed, time to go. */
} else if ((attrs.width == window->w) && (attrs.height == window->h)) {
break; /* we're at the place we wanted to be anyhow, drop out. */
}
if (SDL_TICKS_PASSED(SDL_GetTicks(), timeout)) {
break;
}
SDL_Delay(10);
}
}
int
X11_GetWindowBordersSize(_THIS, SDL_Window * window, int *top, int *left, int *bottom, int *right)
{
SDL_WindowData *data = (SDL_WindowData *)window->driverdata;
*left = data->border_left;
*right = data->border_right;
*top = data->border_top;
*bottom = data->border_bottom;
return 0;
}
int
X11_SetWindowOpacity(_THIS, SDL_Window * window, float opacity)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
Atom _NET_WM_WINDOW_OPACITY = data->videodata->_NET_WM_WINDOW_OPACITY;
if (opacity == 1.0f) {
X11_XDeleteProperty(display, data->xwindow, _NET_WM_WINDOW_OPACITY);
} else {
const Uint32 FullyOpaque = 0xFFFFFFFF;
const long alpha = (long) ((double)opacity * (double)FullyOpaque);
X11_XChangeProperty(display, data->xwindow, _NET_WM_WINDOW_OPACITY, XA_CARDINAL, 32,
PropModeReplace, (unsigned char *)&alpha, 1);
}
return 0;
}
int
X11_SetWindowModalFor(_THIS, SDL_Window * modal_window, SDL_Window * parent_window) {
SDL_WindowData *data = (SDL_WindowData *) modal_window->driverdata;
SDL_WindowData *parent_data = (SDL_WindowData *) parent_window->driverdata;
Display *display = data->videodata->display;
X11_XSetTransientForHint(display, data->xwindow, parent_data->xwindow);
return 0;
}
int
X11_SetWindowInputFocus(_THIS, SDL_Window * window)
{
if (X11_IsWindowMapped(_this, window)) {
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
X11_XSetInputFocus(display, data->xwindow, RevertToNone, CurrentTime);
X11_XFlush(display);
return 0;
}
return -1;
}
void
X11_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered)
{
const SDL_bool focused = ((window->flags & SDL_WINDOW_INPUT_FOCUS) != 0);
const SDL_bool visible = ((window->flags & SDL_WINDOW_HIDDEN) == 0);
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
SDL_DisplayData *displaydata =
(SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata;
Display *display = data->videodata->display;
XEvent event;
SetWindowBordered(display, displaydata->screen, data->xwindow, bordered);
X11_XFlush(display);
if (visible) {
XWindowAttributes attr;
do {
X11_XSync(display, False);
X11_XGetWindowAttributes(display, data->xwindow, &attr);
} while (attr.map_state != IsViewable);
if (focused) {
X11_XSetInputFocus(display, data->xwindow, RevertToParent, CurrentTime);
}
}
/* make sure these don't make it to the real event queue if they fired here. */
X11_XSync(display, False);
X11_XCheckIfEvent(display, &event, &isUnmapNotify, (XPointer)&data->xwindow);
X11_XCheckIfEvent(display, &event, &isMapNotify, (XPointer)&data->xwindow);
}
void
X11_SetWindowResizable(_THIS, SDL_Window * window, SDL_bool resizable)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
XSizeHints *sizehints = X11_XAllocSizeHints();
long userhints;
X11_XGetWMNormalHints(display, data->xwindow, sizehints, &userhints);
if (resizable) {
/* FIXME: Is there a better way to get max window size from X? -flibit */
const int maxsize = 0x7FFFFFFF;
sizehints->min_width = window->min_w;
sizehints->min_height = window->min_h;
sizehints->max_width = (window->max_w == 0) ? maxsize : window->max_w;
sizehints->max_height = (window->max_h == 0) ? maxsize : window->max_h;
} else {
sizehints->min_width = window->w;
sizehints->min_height = window->h;
sizehints->max_width = window->w;
sizehints->max_height = window->h;
}
sizehints->flags |= PMinSize | PMaxSize;
X11_XSetWMNormalHints(display, data->xwindow, sizehints);
X11_XFree(sizehints);
/* See comment in X11_SetWindowSize. */
X11_XResizeWindow(display, data->xwindow, window->w, window->h);
X11_XMoveWindow(display, data->xwindow, window->x - data->border_left, window->y - data->border_top);
X11_XRaiseWindow(display, data->xwindow);
X11_XFlush(display);
}
void
X11_ShowWindow(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
XEvent event;
if (!X11_IsWindowMapped(_this, window)) {
X11_XMapRaised(display, data->xwindow);
/* Blocking wait for "MapNotify" event.
* We use X11_XIfEvent because pXWindowEvent takes a mask rather than a type,
* and XCheckTypedWindowEvent doesn't block */
if(!(window->flags & SDL_WINDOW_FOREIGN))
X11_XIfEvent(display, &event, &isMapNotify, (XPointer)&data->xwindow);
X11_XFlush(display);
}
if (!data->videodata->net_wm) {
/* no WM means no FocusIn event, which confuses us. Force it. */
X11_XSetInputFocus(display, data->xwindow, RevertToNone, CurrentTime);
X11_XFlush(display);
}
}
void
X11_HideWindow(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
SDL_DisplayData *displaydata = (SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata;
Display *display = data->videodata->display;
XEvent event;
if (X11_IsWindowMapped(_this, window)) {
X11_XWithdrawWindow(display, data->xwindow, displaydata->screen);
/* Blocking wait for "UnmapNotify" event */
if(!(window->flags & SDL_WINDOW_FOREIGN))
X11_XIfEvent(display, &event, &isUnmapNotify, (XPointer)&data->xwindow);
X11_XFlush(display);
}
}
static void
SetWindowActive(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
SDL_DisplayData *displaydata =
(SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata;
Display *display = data->videodata->display;
Atom _NET_ACTIVE_WINDOW = data->videodata->_NET_ACTIVE_WINDOW;
if (X11_IsWindowMapped(_this, window)) {
XEvent e;
/*printf("SDL Window %p: sending _NET_ACTIVE_WINDOW with timestamp %lu\n", window, data->user_time);*/
SDL_zero(e);
e.xany.type = ClientMessage;
e.xclient.message_type = _NET_ACTIVE_WINDOW;
e.xclient.format = 32;
e.xclient.window = data->xwindow;
e.xclient.data.l[0] = 1; /* source indication. 1 = application */
e.xclient.data.l[1] = data->user_time;
e.xclient.data.l[2] = 0;
X11_XSendEvent(display, RootWindow(display, displaydata->screen), 0,
SubstructureNotifyMask | SubstructureRedirectMask, &e);
X11_XFlush(display);
}
}
void
X11_RaiseWindow(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
X11_XRaiseWindow(display, data->xwindow);
SetWindowActive(_this, window);
X11_XFlush(display);
}
static void
SetWindowMaximized(_THIS, SDL_Window * window, SDL_bool maximized)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
SDL_DisplayData *displaydata =
(SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata;
Display *display = data->videodata->display;
Atom _NET_WM_STATE = data->videodata->_NET_WM_STATE;
Atom _NET_WM_STATE_MAXIMIZED_VERT = data->videodata->_NET_WM_STATE_MAXIMIZED_VERT;
Atom _NET_WM_STATE_MAXIMIZED_HORZ = data->videodata->_NET_WM_STATE_MAXIMIZED_HORZ;
if (maximized) {
window->flags |= SDL_WINDOW_MAXIMIZED;
} else {
window->flags &= ~SDL_WINDOW_MAXIMIZED;
}
if (X11_IsWindowMapped(_this, window)) {
XEvent e;
SDL_zero(e);
e.xany.type = ClientMessage;
e.xclient.message_type = _NET_WM_STATE;
e.xclient.format = 32;
e.xclient.window = data->xwindow;
e.xclient.data.l[0] =
maximized ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
e.xclient.data.l[1] = _NET_WM_STATE_MAXIMIZED_VERT;
e.xclient.data.l[2] = _NET_WM_STATE_MAXIMIZED_HORZ;
e.xclient.data.l[3] = 0l;
X11_XSendEvent(display, RootWindow(display, displaydata->screen), 0,
SubstructureNotifyMask | SubstructureRedirectMask, &e);
} else {
X11_SetNetWMState(_this, data->xwindow, window->flags);
}
X11_XFlush(display);
}
void
X11_MaximizeWindow(_THIS, SDL_Window * window)
{
SetWindowMaximized(_this, window, SDL_TRUE);
}
void
X11_MinimizeWindow(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
SDL_DisplayData *displaydata =
(SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata;
Display *display = data->videodata->display;
X11_XIconifyWindow(display, data->xwindow, displaydata->screen);
X11_XFlush(display);
}
void
X11_RestoreWindow(_THIS, SDL_Window * window)
{
SetWindowMaximized(_this, window, SDL_FALSE);
X11_ShowWindow(_this, window);
SetWindowActive(_this, window);
}
/* This asks the Window Manager to handle fullscreen for us. This is the modern way. */
static void
X11_SetWindowFullscreenViaWM(_THIS, SDL_Window * window, SDL_VideoDisplay * _display, SDL_bool fullscreen)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
SDL_DisplayData *displaydata = (SDL_DisplayData *) _display->driverdata;
Display *display = data->videodata->display;
Atom _NET_WM_STATE = data->videodata->_NET_WM_STATE;
Atom _NET_WM_STATE_FULLSCREEN = data->videodata->_NET_WM_STATE_FULLSCREEN;
if (X11_IsWindowMapped(_this, window)) {
XEvent e;
if (!(window->flags & SDL_WINDOW_RESIZABLE)) {
/* Compiz refuses fullscreen toggle if we're not resizable, so update the hints so we
can be resized to the fullscreen resolution (or reset so we're not resizable again) */
XSizeHints *sizehints = X11_XAllocSizeHints();
long flags = 0;
X11_XGetWMNormalHints(display, data->xwindow, sizehints, &flags);
/* set the resize flags on */
if (fullscreen) {
/* we are going fullscreen so turn the flags off */
sizehints->flags &= ~(PMinSize | PMaxSize);
} else {
/* Reset the min/max width height to make the window non-resizable again */
sizehints->flags |= PMinSize | PMaxSize;
sizehints->min_width = sizehints->max_width = window->windowed.w;
sizehints->min_height = sizehints->max_height = window->windowed.h;
}
X11_XSetWMNormalHints(display, data->xwindow, sizehints);
X11_XFree(sizehints);
}
SDL_zero(e);
e.xany.type = ClientMessage;
e.xclient.message_type = _NET_WM_STATE;
e.xclient.format = 32;
e.xclient.window = data->xwindow;
e.xclient.data.l[0] =
fullscreen ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
e.xclient.data.l[1] = _NET_WM_STATE_FULLSCREEN;
e.xclient.data.l[3] = 0l;
X11_XSendEvent(display, RootWindow(display, displaydata->screen), 0,
SubstructureNotifyMask | SubstructureRedirectMask, &e);
/* Fullscreen windows sometimes end up being marked maximized by
window managers. Force it back to how we expect it to be. */
if (!fullscreen && ((window->flags & SDL_WINDOW_MAXIMIZED) == 0)) {
SDL_zero(e);
e.xany.type = ClientMessage;
e.xclient.message_type = _NET_WM_STATE;
e.xclient.format = 32;
e.xclient.window = data->xwindow;
e.xclient.data.l[0] = _NET_WM_STATE_REMOVE;
e.xclient.data.l[1] = data->videodata->_NET_WM_STATE_MAXIMIZED_VERT;
e.xclient.data.l[2] = data->videodata->_NET_WM_STATE_MAXIMIZED_HORZ;
e.xclient.data.l[3] = 0l;
X11_XSendEvent(display, RootWindow(display, displaydata->screen), 0,
SubstructureNotifyMask | SubstructureRedirectMask, &e);
}
} else {
Uint32 flags;
flags = window->flags;
if (fullscreen) {
flags |= SDL_WINDOW_FULLSCREEN;
} else {
flags &= ~SDL_WINDOW_FULLSCREEN;
}
X11_SetNetWMState(_this, data->xwindow, flags);
}
if (data->visual->class == DirectColor) {
if ( fullscreen ) {
X11_XInstallColormap(display, data->colormap);
} else {
X11_XUninstallColormap(display, data->colormap);
}
}
X11_XFlush(display);
}
/* This handles fullscreen itself, outside the Window Manager. */
static void
X11_BeginWindowFullscreenLegacy(_THIS, SDL_Window * window, SDL_VideoDisplay * _display)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
SDL_DisplayData *displaydata = (SDL_DisplayData *) _display->driverdata;
Visual *visual = data->visual;
Display *display = data->videodata->display;
const int screen = displaydata->screen;
Window root = RootWindow(display, screen);
const int def_vis = (visual == DefaultVisual(display, screen));
unsigned long xattrmask = 0;
XSetWindowAttributes xattr;
XEvent ev;
SDL_Rect rect;
if ( data->fswindow ) {
return; /* already fullscreen, I hope. */
}
X11_GetDisplayBounds(_this, _display, &rect);
SDL_zero(xattr);
xattr.override_redirect = True;
xattrmask |= CWOverrideRedirect;
xattr.background_pixel = def_vis ? BlackPixel(display, screen) : 0;
xattrmask |= CWBackPixel;
xattr.border_pixel = 0;
xattrmask |= CWBorderPixel;
xattr.colormap = data->colormap;
xattrmask |= CWColormap;
data->fswindow = X11_XCreateWindow(display, root,
rect.x, rect.y, rect.w, rect.h, 0,
displaydata->depth, InputOutput,
visual, xattrmask, &xattr);
X11_XSelectInput(display, data->fswindow, StructureNotifyMask);
X11_XSetWindowBackground(display, data->fswindow, 0);
X11_XInstallColormap(display, data->colormap);
X11_XClearWindow(display, data->fswindow);
X11_XMapRaised(display, data->fswindow);
/* Make sure the fswindow is in view by warping mouse to the corner */
X11_XUngrabPointer(display, CurrentTime);
X11_XWarpPointer(display, None, root, 0, 0, 0, 0, rect.x, rect.y);
/* Wait to be mapped, filter Unmap event out if it arrives. */
X11_XIfEvent(display, &ev, &isMapNotify, (XPointer)&data->fswindow);
X11_XCheckIfEvent(display, &ev, &isUnmapNotify, (XPointer)&data->fswindow);
#if SDL_VIDEO_DRIVER_X11_XVIDMODE
if ( displaydata->use_vidmode ) {
X11_XF86VidModeLockModeSwitch(display, screen, True);
}
#endif
SetWindowBordered(display, displaydata->screen, data->xwindow, SDL_FALSE);
/* Center actual window within our cover-the-screen window. */
X11_XReparentWindow(display, data->xwindow, data->fswindow,
(rect.w - window->w) / 2, (rect.h - window->h) / 2);
/* Move the mouse to the upper left to make sure it's on-screen */
X11_XWarpPointer(display, None, root, 0, 0, 0, 0, rect.x, rect.y);
/* Center mouse in the fullscreen window. */
rect.x += (rect.w / 2);
rect.y += (rect.h / 2);
X11_XWarpPointer(display, None, root, 0, 0, 0, 0, rect.x, rect.y);
/* Wait to be mapped, filter Unmap event out if it arrives. */
X11_XIfEvent(display, &ev, &isMapNotify, (XPointer)&data->xwindow);
X11_XCheckIfEvent(display, &ev, &isUnmapNotify, (XPointer)&data->xwindow);
SDL_UpdateWindowGrab(window);
}
static void
X11_EndWindowFullscreenLegacy(_THIS, SDL_Window * window, SDL_VideoDisplay * _display)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
SDL_DisplayData *displaydata = (SDL_DisplayData *) _display->driverdata;
Display *display = data->videodata->display;
const int screen = displaydata->screen;
Window root = RootWindow(display, screen);
Window fswindow = data->fswindow;
XEvent ev;
if (!data->fswindow) {
return; /* already not fullscreen, I hope. */
}
data->fswindow = None;
#if SDL_VIDEO_DRIVER_X11_VIDMODE
if ( displaydata->use_vidmode ) {
X11_XF86VidModeLockModeSwitch(display, screen, False);
}
#endif
SDL_UpdateWindowGrab(window);
X11_XReparentWindow(display, data->xwindow, root, window->x, window->y);
/* flush these events so they don't confuse normal event handling */
X11_XSync(display, False);
X11_XCheckIfEvent(display, &ev, &isMapNotify, (XPointer)&data->xwindow);
X11_XCheckIfEvent(display, &ev, &isUnmapNotify, (XPointer)&data->xwindow);
SetWindowBordered(display, screen, data->xwindow,
(window->flags & SDL_WINDOW_BORDERLESS) == 0);
X11_XWithdrawWindow(display, fswindow, screen);
/* Wait to be unmapped. */
X11_XIfEvent(display, &ev, &isUnmapNotify, (XPointer)&fswindow);
X11_XDestroyWindow(display, fswindow);
}
void
X11_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * _display, SDL_bool fullscreen)
{
/* !!! FIXME: SDL_Hint? */
SDL_bool legacy = SDL_FALSE;
const char *env = SDL_getenv("SDL_VIDEO_X11_LEGACY_FULLSCREEN");
if (env) {
legacy = SDL_atoi(env);
} else {
SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
SDL_DisplayData *displaydata = (SDL_DisplayData *) _display->driverdata;
if ( displaydata->use_vidmode ) {
legacy = SDL_TRUE; /* the new stuff only works with XRandR. */
} else if ( !videodata->net_wm ) {
legacy = SDL_TRUE; /* The window manager doesn't support it */
} else {
/* !!! FIXME: look at the window manager name, and blacklist certain ones? */
/* http://stackoverflow.com/questions/758648/find-the-name-of-the-x-window-manager */
legacy = SDL_FALSE; /* try the new way. */
}
}
if (legacy) {
if (fullscreen) {
X11_BeginWindowFullscreenLegacy(_this, window, _display);
} else {
X11_EndWindowFullscreenLegacy(_this, window, _display);
}
} else {
X11_SetWindowFullscreenViaWM(_this, window, _display, fullscreen);
}
}
int
X11_SetWindowGammaRamp(_THIS, SDL_Window * window, const Uint16 * ramp)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
Visual *visual = data->visual;
Colormap colormap = data->colormap;
XColor *colorcells;
int ncolors;
int rmask, gmask, bmask;
int rshift, gshift, bshift;
int i;
if (visual->class != DirectColor) {
return SDL_SetError("Window doesn't have DirectColor visual");
}
ncolors = visual->map_entries;
colorcells = SDL_malloc(ncolors * sizeof(XColor));
if (!colorcells) {
return SDL_OutOfMemory();
}
rshift = 0;
rmask = visual->red_mask;
while (0 == (rmask & 1)) {
rshift++;
rmask >>= 1;
}
gshift = 0;
gmask = visual->green_mask;
while (0 == (gmask & 1)) {
gshift++;
gmask >>= 1;
}
bshift = 0;
bmask = visual->blue_mask;
while (0 == (bmask & 1)) {
bshift++;
bmask >>= 1;
}
/* build the color table pixel values */
for (i = 0; i < ncolors; i++) {
Uint32 rbits = (rmask * i) / (ncolors - 1);
Uint32 gbits = (gmask * i) / (ncolors - 1);
Uint32 bbits = (bmask * i) / (ncolors - 1);
Uint32 pix = (rbits << rshift) | (gbits << gshift) | (bbits << bshift);
colorcells[i].pixel = pix;
colorcells[i].red = ramp[(0 * 256) + i];
colorcells[i].green = ramp[(1 * 256) + i];
colorcells[i].blue = ramp[(2 * 256) + i];
colorcells[i].flags = DoRed | DoGreen | DoBlue;
}
X11_XStoreColors(display, colormap, colorcells, ncolors);
X11_XFlush(display);
SDL_free(colorcells);
return 0;
}
void
X11_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
SDL_bool oldstyle_fullscreen;
SDL_bool grab_keyboard;
/* ICCCM2.0-compliant window managers can handle fullscreen windows
If we're using XVidMode to change resolution we need to confine
the cursor so we don't pan around the virtual desktop.
*/
oldstyle_fullscreen = X11_IsWindowLegacyFullscreen(_this, window);
if (oldstyle_fullscreen || grabbed) {
/* Try to grab the mouse */
if (!data->videodata->broken_pointer_grab) {
const unsigned int mask = ButtonPressMask | ButtonReleaseMask | PointerMotionMask | FocusChangeMask;
int attempts;
int result;
/* Try for up to 5000ms (5s) to grab. If it still fails, stop trying. */
for (attempts = 0; attempts < 100; attempts++) {
result = X11_XGrabPointer(display, data->xwindow, True, mask, GrabModeAsync,
GrabModeAsync, data->xwindow, None, CurrentTime);
if (result == GrabSuccess) {
break;
}
SDL_Delay(50);
}
if (result != GrabSuccess) {
SDL_LogWarn(SDL_LOG_CATEGORY_VIDEO, "The X server refused to let us grab the mouse. You might experience input bugs.");
data->videodata->broken_pointer_grab = SDL_TRUE; /* don't try again. */
}
}
/* Raise the window if we grab the mouse */
X11_XRaiseWindow(display, data->xwindow);
/* Now grab the keyboard */
if (SDL_GetHintBoolean(SDL_HINT_GRAB_KEYBOARD, SDL_FALSE)) {
grab_keyboard = SDL_TRUE;
} else {
/* We need to do this with the old style override_redirect
fullscreen window otherwise we won't get keyboard focus.
*/
grab_keyboard = oldstyle_fullscreen;
}
if (grab_keyboard) {
X11_XGrabKeyboard(display, data->xwindow, True, GrabModeAsync,
GrabModeAsync, CurrentTime);
}
} else {
X11_XUngrabPointer(display, CurrentTime);
X11_XUngrabKeyboard(display, CurrentTime);
}
X11_XSync(display, False);
}
void
X11_DestroyWindow(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
if (data) {
SDL_VideoData *videodata = (SDL_VideoData *) data->videodata;
Display *display = videodata->display;
int numwindows = videodata->numwindows;
SDL_WindowData **windowlist = videodata->windowlist;
int i;
if (windowlist) {
for (i = 0; i < numwindows; ++i) {
if (windowlist[i] && (windowlist[i]->window == window)) {
windowlist[i] = windowlist[numwindows - 1];
windowlist[numwindows - 1] = NULL;
videodata->numwindows--;
break;
}
}
}
#ifdef X_HAVE_UTF8_STRING
if (data->ic) {
X11_XDestroyIC(data->ic);
}
#endif
if (data->created) {
X11_XDestroyWindow(display, data->xwindow);
X11_XFlush(display);
}
SDL_free(data);
}
window->driverdata = NULL;
}
SDL_bool
X11_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display;
if (!data) {
/* This sometimes happens in SDL_IBus_UpdateTextRect() while creating the window */
SDL_SetError("Window not initialized");
return SDL_FALSE;
}
display = data->videodata->display;
if (info->version.major == SDL_MAJOR_VERSION &&
info->version.minor == SDL_MINOR_VERSION) {
info->subsystem = SDL_SYSWM_X11;
info->info.x11.display = display;
info->info.x11.window = data->xwindow;
return SDL_TRUE;
} else {
SDL_SetError("Application not compiled with SDL %d.%d",
SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
return SDL_FALSE;
}
}
int
X11_SetWindowHitTest(SDL_Window *window, SDL_bool enabled)
{
return 0; /* just succeed, the real work is done elsewhere. */
}
void
X11_AcceptDragAndDrop(SDL_Window * window, SDL_bool accept)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
Atom XdndAware = X11_XInternAtom(display, "XdndAware", False);
if (accept) {
Atom xdnd_version = 5;
X11_XChangeProperty(display, data->xwindow, XdndAware, XA_ATOM, 32,
PropModeReplace, (unsigned char*)&xdnd_version, 1);
} else {
X11_XDeleteProperty(display, data->xwindow, XdndAware);
}
}
#endif /* SDL_VIDEO_DRIVER_X11 */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11window.c | C | apache-2.0 | 58,350 |
/*
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_x11window_h_
#define SDL_x11window_h_
/* We need to queue the focus in/out changes because they may occur during
video mode changes and we can respond to them by triggering more mode
changes.
*/
#define PENDING_FOCUS_TIME 200
#if SDL_VIDEO_OPENGL_EGL
#include <EGL/egl.h>
#endif
typedef enum
{
PENDING_FOCUS_NONE,
PENDING_FOCUS_IN,
PENDING_FOCUS_OUT
} PendingFocusEnum;
typedef struct
{
SDL_Window *window;
Window xwindow;
Window fswindow; /* used if we can't have the WM handle fullscreen. */
Visual *visual;
Colormap colormap;
#ifndef NO_SHARED_MEMORY
/* MIT shared memory extension information */
SDL_bool use_mitshm;
XShmSegmentInfo shminfo;
#endif
XImage *ximage;
GC gc;
XIC ic;
SDL_bool created;
int border_left;
int border_right;
int border_top;
int border_bottom;
Uint32 last_focus_event_time;
PendingFocusEnum pending_focus;
Uint32 pending_focus_time;
XConfigureEvent last_xconfigure;
struct SDL_VideoData *videodata;
unsigned long user_time;
Atom xdnd_req;
Window xdnd_source;
#if SDL_VIDEO_OPENGL_EGL
EGLSurface egl_surface;
#endif
} SDL_WindowData;
extern void X11_SetNetWMState(_THIS, Window xwindow, Uint32 flags);
extern Uint32 X11_GetNetWMState(_THIS, Window xwindow);
extern int X11_CreateWindow(_THIS, SDL_Window * window);
extern int X11_CreateWindowFrom(_THIS, SDL_Window * window, const void *data);
extern char *X11_GetWindowTitle(_THIS, Window xwindow);
extern void X11_SetWindowTitle(_THIS, SDL_Window * window);
extern void X11_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon);
extern void X11_SetWindowPosition(_THIS, SDL_Window * window);
extern void X11_SetWindowMinimumSize(_THIS, SDL_Window * window);
extern void X11_SetWindowMaximumSize(_THIS, SDL_Window * window);
extern int X11_GetWindowBordersSize(_THIS, SDL_Window * window, int *top, int *left, int *bottom, int *right);
extern int X11_SetWindowOpacity(_THIS, SDL_Window * window, float opacity);
extern int X11_SetWindowModalFor(_THIS, SDL_Window * modal_window, SDL_Window * parent_window);
extern int X11_SetWindowInputFocus(_THIS, SDL_Window * window);
extern void X11_SetWindowSize(_THIS, SDL_Window * window);
extern void X11_ShowWindow(_THIS, SDL_Window * window);
extern void X11_HideWindow(_THIS, SDL_Window * window);
extern void X11_RaiseWindow(_THIS, SDL_Window * window);
extern void X11_MaximizeWindow(_THIS, SDL_Window * window);
extern void X11_MinimizeWindow(_THIS, SDL_Window * window);
extern void X11_RestoreWindow(_THIS, SDL_Window * window);
extern void X11_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered);
extern void X11_SetWindowResizable(_THIS, SDL_Window * window, SDL_bool resizable);
extern void X11_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen);
extern int X11_SetWindowGammaRamp(_THIS, SDL_Window * window, const Uint16 * ramp);
extern void X11_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed);
extern void X11_DestroyWindow(_THIS, SDL_Window * window);
extern SDL_bool X11_GetWindowWMInfo(_THIS, SDL_Window * window,
struct SDL_SysWMinfo *info);
extern int X11_SetWindowHitTest(SDL_Window *window, SDL_bool enabled);
extern void X11_AcceptDragAndDrop(SDL_Window * window, SDL_bool accept);
#endif /* SDL_x11window_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11window.h | C | apache-2.0 | 4,421 |
/*
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_X11
#include "SDL_x11video.h"
#include "SDL_x11xinput2.h"
#include "../../events/SDL_mouse_c.h"
#include "../../events/SDL_touch_c.h"
#define MAX_AXIS 16
#if SDL_VIDEO_DRIVER_X11_XINPUT2
static int xinput2_initialized = 0;
#if SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH
static int xinput2_multitouch_supported = 0;
#endif
/* Opcode returned X11_XQueryExtension
* It will be used in event processing
* to know that the event came from
* this extension */
static int xinput2_opcode;
static void parse_valuators(const double *input_values, const unsigned char *mask,int mask_len,
double *output_values,int output_values_len) {
int i = 0,z = 0;
int top = mask_len * 8;
if (top > MAX_AXIS)
top = MAX_AXIS;
SDL_memset(output_values,0,output_values_len * sizeof(double));
for (; i < top && z < output_values_len; i++) {
if (XIMaskIsSet(mask, i)) {
const int value = (int) *input_values;
output_values[z] = value;
input_values++;
}
z++;
}
}
static int
query_xinput2_version(Display *display, int major, int minor)
{
/* We don't care if this fails, so long as it sets major/minor on it's way out the door. */
X11_XIQueryVersion(display, &major, &minor);
return ((major * 1000) + minor);
}
static SDL_bool
xinput2_version_atleast(const int version, const int wantmajor, const int wantminor)
{
return ( version >= ((wantmajor * 1000) + wantminor) );
}
#if SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH
static SDL_Window *
xinput2_get_sdlwindow(SDL_VideoData *videodata, Window window)
{
int i;
for (i = 0; i < videodata->numwindows; i++) {
SDL_WindowData *d = videodata->windowlist[i];
if (d->xwindow == window) {
return d->window;
}
}
return NULL;
}
static void
xinput2_normalize_touch_coordinates(SDL_Window *window, double in_x, double in_y, float *out_x, float *out_y)
{
if (window) {
if (window->w == 1) {
*out_x = 0.5f;
} else {
*out_x = in_x / (window->w - 1);
}
if (window->h == 1) {
*out_y = 0.5f;
} else {
*out_y = in_y / (window->h - 1);
}
} else {
// couldn't find the window...
*out_x = in_x;
*out_y = in_y;
}
}
#endif /* SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH */
#endif /* SDL_VIDEO_DRIVER_X11_XINPUT2 */
void
X11_InitXinput2(_THIS)
{
#if SDL_VIDEO_DRIVER_X11_XINPUT2
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
int version = 0;
XIEventMask eventmask;
unsigned char mask[3] = { 0,0,0 };
int event, err;
/*
* Initialize XInput 2
* According to http://who-t.blogspot.com/2009/05/xi2-recipes-part-1.html its better
* to inform Xserver what version of Xinput we support.The server will store the version we support.
* "As XI2 progresses it becomes important that you use this call as the server may treat the client
* differently depending on the supported version".
*
* FIXME:event and err are not needed but if not passed X11_XQueryExtension returns SegmentationFault
*/
if (!SDL_X11_HAVE_XINPUT2 ||
!X11_XQueryExtension(data->display, "XInputExtension", &xinput2_opcode, &event, &err)) {
return; /* X server does not have XInput at all */
}
/* We need at least 2.2 for Multitouch, 2.0 otherwise. */
version = query_xinput2_version(data->display, 2, 2);
if (!xinput2_version_atleast(version, 2, 0)) {
return; /* X server does not support the version we want at all. */
}
xinput2_initialized = 1;
#if SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH /* Multitouch needs XInput 2.2 */
xinput2_multitouch_supported = xinput2_version_atleast(version, 2, 2);
#endif
/* Enable Raw motion events for this display */
eventmask.deviceid = XIAllMasterDevices;
eventmask.mask_len = sizeof(mask);
eventmask.mask = mask;
XISetMask(mask, XI_RawMotion);
XISetMask(mask, XI_RawButtonPress);
XISetMask(mask, XI_RawButtonRelease);
if (X11_XISelectEvents(data->display,DefaultRootWindow(data->display),&eventmask,1) != Success) {
return;
}
#endif
}
int
X11_HandleXinput2Event(SDL_VideoData *videodata,XGenericEventCookie *cookie)
{
#if SDL_VIDEO_DRIVER_X11_XINPUT2
if(cookie->extension != xinput2_opcode) {
return 0;
}
switch(cookie->evtype) {
case XI_RawMotion: {
const XIRawEvent *rawev = (const XIRawEvent*)cookie->data;
SDL_Mouse *mouse = SDL_GetMouse();
double relative_coords[2];
static Time prev_time = 0;
static double prev_rel_coords[2];
videodata->global_mouse_changed = SDL_TRUE;
if (!mouse->relative_mode || mouse->relative_mode_warp) {
return 0;
}
parse_valuators(rawev->raw_values,rawev->valuators.mask,
rawev->valuators.mask_len,relative_coords,2);
if ((rawev->time == prev_time) && (relative_coords[0] == prev_rel_coords[0]) && (relative_coords[1] == prev_rel_coords[1])) {
return 0; /* duplicate event, drop it. */
}
SDL_SendMouseMotion(mouse->focus,mouse->mouseID,1,(int)relative_coords[0],(int)relative_coords[1]);
prev_rel_coords[0] = relative_coords[0];
prev_rel_coords[1] = relative_coords[1];
prev_time = rawev->time;
return 1;
}
break;
case XI_RawButtonPress:
case XI_RawButtonRelease:
videodata->global_mouse_changed = SDL_TRUE;
break;
#if SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH
/* With multitouch, register to receive XI_Motion (which desctivates MotionNotify),
* so that we can distinguish real mouse motions from synthetic one. */
case XI_Motion: {
const XIDeviceEvent *xev = (const XIDeviceEvent *) cookie->data;
int pointer_emulated = (xev->flags & XIPointerEmulated);
if (! pointer_emulated) {
SDL_Mouse *mouse = SDL_GetMouse();
if(!mouse->relative_mode || mouse->relative_mode_warp) {
SDL_Window *window = xinput2_get_sdlwindow(videodata, xev->event);
if (window) {
SDL_SendMouseMotion(window, 0, 0, xev->event_x, xev->event_y);
}
}
}
return 1;
}
break;
case XI_TouchBegin: {
const XIDeviceEvent *xev = (const XIDeviceEvent *) cookie->data;
float x, y;
SDL_Window *window = xinput2_get_sdlwindow(videodata, xev->event);
xinput2_normalize_touch_coordinates(window, xev->event_x, xev->event_y, &x, &y);
SDL_SendTouch(xev->sourceid, xev->detail, window, SDL_TRUE, x, y, 1.0);
return 1;
}
break;
case XI_TouchEnd: {
const XIDeviceEvent *xev = (const XIDeviceEvent *) cookie->data;
float x, y;
SDL_Window *window = xinput2_get_sdlwindow(videodata, xev->event);
xinput2_normalize_touch_coordinates(window, xev->event_x, xev->event_y, &x, &y);
SDL_SendTouch(xev->sourceid, xev->detail, window, SDL_FALSE, x, y, 1.0);
return 1;
}
break;
case XI_TouchUpdate: {
const XIDeviceEvent *xev = (const XIDeviceEvent *) cookie->data;
float x, y;
SDL_Window *window = xinput2_get_sdlwindow(videodata, xev->event);
xinput2_normalize_touch_coordinates(window, xev->event_x, xev->event_y, &x, &y);
SDL_SendTouchMotion(xev->sourceid, xev->detail, window, x, y, 1.0);
return 1;
}
break;
#endif
}
#endif
return 0;
}
void
X11_InitXinput2Multitouch(_THIS)
{
#if SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH
SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
XIDeviceInfo *info;
int ndevices,i,j;
info = X11_XIQueryDevice(data->display, XIAllDevices, &ndevices);
for (i = 0; i < ndevices; i++) {
XIDeviceInfo *dev = &info[i];
for (j = 0; j < dev->num_classes; j++) {
SDL_TouchID touchId;
SDL_TouchDeviceType touchType;
XIAnyClassInfo *class = dev->classes[j];
XITouchClassInfo *t = (XITouchClassInfo*)class;
/* Only touch devices */
if (class->type != XITouchClass)
continue;
if (t->mode == XIDependentTouch) {
touchType = SDL_TOUCH_DEVICE_INDIRECT_RELATIVE;
} else { /* XIDirectTouch */
touchType = SDL_TOUCH_DEVICE_DIRECT;
}
touchId = t->sourceid;
SDL_AddTouch(touchId, touchType, dev->name);
}
}
X11_XIFreeDeviceInfo(info);
#endif
}
void
X11_Xinput2SelectTouch(_THIS, SDL_Window *window)
{
#if SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH
SDL_VideoData *data = NULL;
XIEventMask eventmask;
unsigned char mask[4] = { 0, 0, 0, 0 };
SDL_WindowData *window_data = NULL;
if (!X11_Xinput2IsMultitouchSupported()) {
return;
}
data = (SDL_VideoData *) _this->driverdata;
window_data = (SDL_WindowData*)window->driverdata;
eventmask.deviceid = XIAllMasterDevices;
eventmask.mask_len = sizeof(mask);
eventmask.mask = mask;
XISetMask(mask, XI_TouchBegin);
XISetMask(mask, XI_TouchUpdate);
XISetMask(mask, XI_TouchEnd);
XISetMask(mask, XI_Motion);
X11_XISelectEvents(data->display,window_data->xwindow,&eventmask,1);
#endif
}
int
X11_Xinput2IsInitialized()
{
#if SDL_VIDEO_DRIVER_X11_XINPUT2
return xinput2_initialized;
#else
return 0;
#endif
}
int
X11_Xinput2IsMultitouchSupported()
{
#if SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH
return xinput2_initialized && xinput2_multitouch_supported;
#else
return 0;
#endif
}
#endif /* SDL_VIDEO_DRIVER_X11 */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11xinput2.c | C | apache-2.0 | 11,181 |
/*
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_x11xinput2_h_
#define SDL_x11xinput2_h_
#ifndef SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS
/* Define XGenericEventCookie as forward declaration when
*xinput2 is not available in order to compile */
struct XGenericEventCookie;
typedef struct XGenericEventCookie XGenericEventCookie;
#endif
extern void X11_InitXinput2(_THIS);
extern void X11_InitXinput2Multitouch(_THIS);
extern int X11_HandleXinput2Event(SDL_VideoData *videodata,XGenericEventCookie *cookie);
extern int X11_Xinput2IsInitialized(void);
extern int X11_Xinput2IsMultitouchSupported(void);
extern void X11_Xinput2SelectTouch(_THIS, SDL_Window *window);
#endif /* SDL_x11xinput2_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/SDL_x11xinput2.h | C | apache-2.0 | 1,674 |
/*
* Copyright 2007 Red Hat, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* on the rights to use, copy, modify, merge, publish, distribute, sub
* license, and/or sell copies of the Software, and to permit persons to whom
* the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* Author: Soren Sandmann <sandmann@redhat.com> */
#include "../../SDL_internal.h"
#include "SDL_stdinc.h"
#include "edid.h"
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdio.h>
#define TRUE 1
#define FALSE 0
static int
get_bit (int in, int bit)
{
return (in & (1 << bit)) >> bit;
}
static int
get_bits (int in, int begin, int end)
{
int mask = (1 << (end - begin + 1)) - 1;
return (in >> begin) & mask;
}
static int
decode_header (const uchar *edid)
{
if (memcmp (edid, "\x00\xff\xff\xff\xff\xff\xff\x00", 8) == 0)
return TRUE;
return FALSE;
}
static int
decode_vendor_and_product_identification (const uchar *edid, MonitorInfo *info)
{
int is_model_year;
/* Manufacturer Code */
info->manufacturer_code[0] = get_bits (edid[0x08], 2, 6);
info->manufacturer_code[1] = get_bits (edid[0x08], 0, 1) << 3;
info->manufacturer_code[1] |= get_bits (edid[0x09], 5, 7);
info->manufacturer_code[2] = get_bits (edid[0x09], 0, 4);
info->manufacturer_code[3] = '\0';
info->manufacturer_code[0] += 'A' - 1;
info->manufacturer_code[1] += 'A' - 1;
info->manufacturer_code[2] += 'A' - 1;
/* Product Code */
info->product_code = edid[0x0b] << 8 | edid[0x0a];
/* Serial Number */
info->serial_number =
edid[0x0c] | edid[0x0d] << 8 | edid[0x0e] << 16 | edid[0x0f] << 24;
/* Week and Year */
is_model_year = FALSE;
switch (edid[0x10])
{
case 0x00:
info->production_week = -1;
break;
case 0xff:
info->production_week = -1;
is_model_year = TRUE;
break;
default:
info->production_week = edid[0x10];
break;
}
if (is_model_year)
{
info->production_year = -1;
info->model_year = 1990 + edid[0x11];
}
else
{
info->production_year = 1990 + edid[0x11];
info->model_year = -1;
}
return TRUE;
}
static int
decode_edid_version (const uchar *edid, MonitorInfo *info)
{
info->major_version = edid[0x12];
info->minor_version = edid[0x13];
return TRUE;
}
static int
decode_display_parameters (const uchar *edid, MonitorInfo *info)
{
/* Digital vs Analog */
info->is_digital = get_bit (edid[0x14], 7);
if (info->is_digital)
{
int bits;
static const int bit_depth[8] =
{
-1, 6, 8, 10, 12, 14, 16, -1
};
static const Interface interfaces[6] =
{
UNDEFINED, DVI, HDMI_A, HDMI_B, MDDI, DISPLAY_PORT
};
bits = get_bits (edid[0x14], 4, 6);
info->ad.digital.bits_per_primary = bit_depth[bits];
bits = get_bits (edid[0x14], 0, 3);
if (bits <= 5)
info->ad.digital.interface = interfaces[bits];
else
info->ad.digital.interface = UNDEFINED;
}
else
{
int bits = get_bits (edid[0x14], 5, 6);
static const double levels[][3] =
{
{ 0.7, 0.3, 1.0 },
{ 0.714, 0.286, 1.0 },
{ 1.0, 0.4, 1.4 },
{ 0.7, 0.0, 0.7 },
};
info->ad.analog.video_signal_level = levels[bits][0];
info->ad.analog.sync_signal_level = levels[bits][1];
info->ad.analog.total_signal_level = levels[bits][2];
info->ad.analog.blank_to_black = get_bit (edid[0x14], 4);
info->ad.analog.separate_hv_sync = get_bit (edid[0x14], 3);
info->ad.analog.composite_sync_on_h = get_bit (edid[0x14], 2);
info->ad.analog.composite_sync_on_green = get_bit (edid[0x14], 1);
info->ad.analog.serration_on_vsync = get_bit (edid[0x14], 0);
}
/* Screen Size / Aspect Ratio */
if (edid[0x15] == 0 && edid[0x16] == 0)
{
info->width_mm = -1;
info->height_mm = -1;
info->aspect_ratio = -1.0;
}
else if (edid[0x16] == 0)
{
info->width_mm = -1;
info->height_mm = -1;
info->aspect_ratio = 100.0 / (edid[0x15] + 99);
}
else if (edid[0x15] == 0)
{
info->width_mm = -1;
info->height_mm = -1;
info->aspect_ratio = 100.0 / (edid[0x16] + 99);
info->aspect_ratio = 1/info->aspect_ratio; /* portrait */
}
else
{
info->width_mm = 10 * edid[0x15];
info->height_mm = 10 * edid[0x16];
}
/* Gamma */
if (edid[0x17] == 0xFF)
info->gamma = -1.0;
else
info->gamma = (edid[0x17] + 100.0) / 100.0;
/* Features */
info->standby = get_bit (edid[0x18], 7);
info->suspend = get_bit (edid[0x18], 6);
info->active_off = get_bit (edid[0x18], 5);
if (info->is_digital)
{
info->ad.digital.rgb444 = TRUE;
if (get_bit (edid[0x18], 3))
info->ad.digital.ycrcb444 = 1;
if (get_bit (edid[0x18], 4))
info->ad.digital.ycrcb422 = 1;
}
else
{
int bits = get_bits (edid[0x18], 3, 4);
ColorType color_type[4] =
{
MONOCHROME, RGB, OTHER_COLOR, UNDEFINED_COLOR
};
info->ad.analog.color_type = color_type[bits];
}
info->srgb_is_standard = get_bit (edid[0x18], 2);
/* In 1.3 this is called "has preferred timing" */
info->preferred_timing_includes_native = get_bit (edid[0x18], 1);
/* FIXME: In 1.3 this indicates whether the monitor accepts GTF */
info->continuous_frequency = get_bit (edid[0x18], 0);
return TRUE;
}
static double
decode_fraction (int high, int low)
{
double result = 0.0;
int i;
high = (high << 2) | low;
for (i = 0; i < 10; ++i)
result += get_bit (high, i) * SDL_pow (2, i - 10);
return result;
}
static int
decode_color_characteristics (const uchar *edid, MonitorInfo *info)
{
info->red_x = decode_fraction (edid[0x1b], get_bits (edid[0x19], 6, 7));
info->red_y = decode_fraction (edid[0x1c], get_bits (edid[0x19], 5, 4));
info->green_x = decode_fraction (edid[0x1d], get_bits (edid[0x19], 2, 3));
info->green_y = decode_fraction (edid[0x1e], get_bits (edid[0x19], 0, 1));
info->blue_x = decode_fraction (edid[0x1f], get_bits (edid[0x1a], 6, 7));
info->blue_y = decode_fraction (edid[0x20], get_bits (edid[0x1a], 4, 5));
info->white_x = decode_fraction (edid[0x21], get_bits (edid[0x1a], 2, 3));
info->white_y = decode_fraction (edid[0x22], get_bits (edid[0x1a], 0, 1));
return TRUE;
}
static int
decode_established_timings (const uchar *edid, MonitorInfo *info)
{
static const Timing established[][8] =
{
{
{ 800, 600, 60 },
{ 800, 600, 56 },
{ 640, 480, 75 },
{ 640, 480, 72 },
{ 640, 480, 67 },
{ 640, 480, 60 },
{ 720, 400, 88 },
{ 720, 400, 70 }
},
{
{ 1280, 1024, 75 },
{ 1024, 768, 75 },
{ 1024, 768, 70 },
{ 1024, 768, 60 },
{ 1024, 768, 87 },
{ 832, 624, 75 },
{ 800, 600, 75 },
{ 800, 600, 72 }
},
{
{ 0, 0, 0 },
{ 0, 0, 0 },
{ 0, 0, 0 },
{ 0, 0, 0 },
{ 0, 0, 0 },
{ 0, 0, 0 },
{ 0, 0, 0 },
{ 1152, 870, 75 }
},
};
int i, j, idx;
idx = 0;
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 8; ++j)
{
int byte = edid[0x23 + i];
if (get_bit (byte, j) && established[i][j].frequency != 0)
info->established[idx++] = established[i][j];
}
}
return TRUE;
}
static int
decode_standard_timings (const uchar *edid, MonitorInfo *info)
{
int i;
for (i = 0; i < 8; i++)
{
int first = edid[0x26 + 2 * i];
int second = edid[0x27 + 2 * i];
if (first != 0x01 && second != 0x01)
{
int w = 8 * (first + 31);
int h = 0;
switch (get_bits (second, 6, 7))
{
case 0x00: h = (w / 16) * 10; break;
case 0x01: h = (w / 4) * 3; break;
case 0x02: h = (w / 5) * 4; break;
case 0x03: h = (w / 16) * 9; break;
}
info->standard[i].width = w;
info->standard[i].height = h;
info->standard[i].frequency = get_bits (second, 0, 5) + 60;
}
}
return TRUE;
}
static void
decode_lf_string (const uchar *s, int n_chars, char *result)
{
int i;
for (i = 0; i < n_chars; ++i)
{
if (s[i] == 0x0a)
{
*result++ = '\0';
break;
}
else if (s[i] == 0x00)
{
/* Convert embedded 0's to spaces */
*result++ = ' ';
}
else
{
*result++ = s[i];
}
}
}
static void
decode_display_descriptor (const uchar *desc,
MonitorInfo *info)
{
switch (desc[0x03])
{
case 0xFC:
decode_lf_string (desc + 5, 13, info->dsc_product_name);
break;
case 0xFF:
decode_lf_string (desc + 5, 13, info->dsc_serial_number);
break;
case 0xFE:
decode_lf_string (desc + 5, 13, info->dsc_string);
break;
case 0xFD:
/* Range Limits */
break;
case 0xFB:
/* Color Point */
break;
case 0xFA:
/* Timing Identifications */
break;
case 0xF9:
/* Color Management */
break;
case 0xF8:
/* Timing Codes */
break;
case 0xF7:
/* Established Timings */
break;
case 0x10:
break;
}
}
static void
decode_detailed_timing (const uchar *timing,
DetailedTiming *detailed)
{
int bits;
StereoType stereo[] =
{
NO_STEREO, NO_STEREO, FIELD_RIGHT, FIELD_LEFT,
TWO_WAY_RIGHT_ON_EVEN, TWO_WAY_LEFT_ON_EVEN,
FOUR_WAY_INTERLEAVED, SIDE_BY_SIDE
};
detailed->pixel_clock = (timing[0x00] | timing[0x01] << 8) * 10000;
detailed->h_addr = timing[0x02] | ((timing[0x04] & 0xf0) << 4);
detailed->h_blank = timing[0x03] | ((timing[0x04] & 0x0f) << 8);
detailed->v_addr = timing[0x05] | ((timing[0x07] & 0xf0) << 4);
detailed->v_blank = timing[0x06] | ((timing[0x07] & 0x0f) << 8);
detailed->h_front_porch = timing[0x08] | get_bits (timing[0x0b], 6, 7) << 8;
detailed->h_sync = timing[0x09] | get_bits (timing[0x0b], 4, 5) << 8;
detailed->v_front_porch =
get_bits (timing[0x0a], 4, 7) | get_bits (timing[0x0b], 2, 3) << 4;
detailed->v_sync =
get_bits (timing[0x0a], 0, 3) | get_bits (timing[0x0b], 0, 1) << 4;
detailed->width_mm = timing[0x0c] | get_bits (timing[0x0e], 4, 7) << 8;
detailed->height_mm = timing[0x0d] | get_bits (timing[0x0e], 0, 3) << 8;
detailed->right_border = timing[0x0f];
detailed->top_border = timing[0x10];
detailed->interlaced = get_bit (timing[0x11], 7);
/* Stereo */
bits = get_bits (timing[0x11], 5, 6) << 1 | get_bit (timing[0x11], 0);
detailed->stereo = stereo[bits];
/* Sync */
bits = timing[0x11];
detailed->digital_sync = get_bit (bits, 4);
if (detailed->digital_sync)
{
detailed->ad.digital.composite = !get_bit (bits, 3);
if (detailed->ad.digital.composite)
{
detailed->ad.digital.serrations = get_bit (bits, 2);
detailed->ad.digital.negative_vsync = FALSE;
}
else
{
detailed->ad.digital.serrations = FALSE;
detailed->ad.digital.negative_vsync = !get_bit (bits, 2);
}
detailed->ad.digital.negative_hsync = !get_bit (bits, 0);
}
else
{
detailed->ad.analog.bipolar = get_bit (bits, 3);
detailed->ad.analog.serrations = get_bit (bits, 2);
detailed->ad.analog.sync_on_green = !get_bit (bits, 1);
}
}
static int
decode_descriptors (const uchar *edid, MonitorInfo *info)
{
int i;
int timing_idx;
timing_idx = 0;
for (i = 0; i < 4; ++i)
{
int index = 0x36 + i * 18;
if (edid[index + 0] == 0x00 && edid[index + 1] == 0x00)
{
decode_display_descriptor (edid + index, info);
}
else
{
decode_detailed_timing (
edid + index, &(info->detailed_timings[timing_idx++]));
}
}
info->n_detailed_timings = timing_idx;
return TRUE;
}
static void
decode_check_sum (const uchar *edid,
MonitorInfo *info)
{
int i;
uchar check = 0;
for (i = 0; i < 128; ++i)
check += edid[i];
info->checksum = check;
}
MonitorInfo *
decode_edid (const uchar *edid)
{
MonitorInfo *info = calloc (1, sizeof (MonitorInfo));
decode_check_sum (edid, info);
if (!decode_header (edid) ||
!decode_vendor_and_product_identification (edid, info) ||
!decode_edid_version (edid, info) ||
!decode_display_parameters (edid, info) ||
!decode_color_characteristics (edid, info) ||
!decode_established_timings (edid, info) ||
!decode_standard_timings (edid, info) ||
!decode_descriptors (edid, info)) {
free(info);
return NULL;
}
return info;
}
static const char *
yesno (int v)
{
return v? "yes" : "no";
}
void
dump_monitor_info (MonitorInfo *info)
{
int i;
printf ("Checksum: %d (%s)\n",
info->checksum, info->checksum? "incorrect" : "correct");
printf ("Manufacturer Code: %s\n", info->manufacturer_code);
printf ("Product Code: 0x%x\n", info->product_code);
printf ("Serial Number: %u\n", info->serial_number);
if (info->production_week != -1)
printf ("Production Week: %d\n", info->production_week);
else
printf ("Production Week: unspecified\n");
if (info->production_year != -1)
printf ("Production Year: %d\n", info->production_year);
else
printf ("Production Year: unspecified\n");
if (info->model_year != -1)
printf ("Model Year: %d\n", info->model_year);
else
printf ("Model Year: unspecified\n");
printf ("EDID revision: %d.%d\n", info->major_version, info->minor_version);
printf ("Display is %s\n", info->is_digital? "digital" : "analog");
if (info->is_digital)
{
const char *interface;
if (info->ad.digital.bits_per_primary != -1)
printf ("Bits Per Primary: %d\n", info->ad.digital.bits_per_primary);
else
printf ("Bits Per Primary: undefined\n");
switch (info->ad.digital.interface)
{
case DVI: interface = "DVI"; break;
case HDMI_A: interface = "HDMI-a"; break;
case HDMI_B: interface = "HDMI-b"; break;
case MDDI: interface = "MDDI"; break;
case DISPLAY_PORT: interface = "DisplayPort"; break;
case UNDEFINED: interface = "undefined"; break;
default: interface = "unknown"; break;
}
printf ("Interface: %s\n", interface);
printf ("RGB 4:4:4: %s\n", yesno (info->ad.digital.rgb444));
printf ("YCrCb 4:4:4: %s\n", yesno (info->ad.digital.ycrcb444));
printf ("YCrCb 4:2:2: %s\n", yesno (info->ad.digital.ycrcb422));
}
else
{
const char *s;
printf ("Video Signal Level: %f\n", info->ad.analog.video_signal_level);
printf ("Sync Signal Level: %f\n", info->ad.analog.sync_signal_level);
printf ("Total Signal Level: %f\n", info->ad.analog.total_signal_level);
printf ("Blank to Black: %s\n",
yesno (info->ad.analog.blank_to_black));
printf ("Separate HV Sync: %s\n",
yesno (info->ad.analog.separate_hv_sync));
printf ("Composite Sync on H: %s\n",
yesno (info->ad.analog.composite_sync_on_h));
printf ("Serration on VSync: %s\n",
yesno (info->ad.analog.serration_on_vsync));
switch (info->ad.analog.color_type)
{
case UNDEFINED_COLOR: s = "undefined"; break;
case MONOCHROME: s = "monochrome"; break;
case RGB: s = "rgb"; break;
case OTHER_COLOR: s = "other color"; break;
default: s = "unknown"; break;
};
printf ("Color: %s\n", s);
}
if (info->width_mm == -1)
printf ("Width: undefined\n");
else
printf ("Width: %d mm\n", info->width_mm);
if (info->height_mm == -1)
printf ("Height: undefined\n");
else
printf ("Height: %d mm\n", info->height_mm);
if (info->aspect_ratio > 0)
printf ("Aspect Ratio: %f\n", info->aspect_ratio);
else
printf ("Aspect Ratio: undefined\n");
if (info->gamma >= 0)
printf ("Gamma: %f\n", info->gamma);
else
printf ("Gamma: undefined\n");
printf ("Standby: %s\n", yesno (info->standby));
printf ("Suspend: %s\n", yesno (info->suspend));
printf ("Active Off: %s\n", yesno (info->active_off));
printf ("SRGB is Standard: %s\n", yesno (info->srgb_is_standard));
printf ("Preferred Timing Includes Native: %s\n",
yesno (info->preferred_timing_includes_native));
printf ("Continuous Frequency: %s\n", yesno (info->continuous_frequency));
printf ("Red X: %f\n", info->red_x);
printf ("Red Y: %f\n", info->red_y);
printf ("Green X: %f\n", info->green_x);
printf ("Green Y: %f\n", info->green_y);
printf ("Blue X: %f\n", info->blue_x);
printf ("Blue Y: %f\n", info->blue_y);
printf ("White X: %f\n", info->white_x);
printf ("White Y: %f\n", info->white_y);
printf ("Established Timings:\n");
for (i = 0; i < 24; ++i)
{
Timing *timing = &(info->established[i]);
if (timing->frequency == 0)
break;
printf (" %d x %d @ %d Hz\n",
timing->width, timing->height, timing->frequency);
}
printf ("Standard Timings:\n");
for (i = 0; i < 8; ++i)
{
Timing *timing = &(info->standard[i]);
if (timing->frequency == 0)
break;
printf (" %d x %d @ %d Hz\n",
timing->width, timing->height, timing->frequency);
}
for (i = 0; i < info->n_detailed_timings; ++i)
{
DetailedTiming *timing = &(info->detailed_timings[i]);
const char *s;
printf ("Timing%s: \n",
(i == 0 && info->preferred_timing_includes_native)?
" (Preferred)" : "");
printf (" Pixel Clock: %d\n", timing->pixel_clock);
printf (" H Addressable: %d\n", timing->h_addr);
printf (" H Blank: %d\n", timing->h_blank);
printf (" H Front Porch: %d\n", timing->h_front_porch);
printf (" H Sync: %d\n", timing->h_sync);
printf (" V Addressable: %d\n", timing->v_addr);
printf (" V Blank: %d\n", timing->v_blank);
printf (" V Front Porch: %d\n", timing->v_front_porch);
printf (" V Sync: %d\n", timing->v_sync);
printf (" Width: %d mm\n", timing->width_mm);
printf (" Height: %d mm\n", timing->height_mm);
printf (" Right Border: %d\n", timing->right_border);
printf (" Top Border: %d\n", timing->top_border);
switch (timing->stereo)
{
default:
case NO_STEREO: s = "No Stereo"; break;
case FIELD_RIGHT: s = "Field Sequential, Right on Sync"; break;
case FIELD_LEFT: s = "Field Sequential, Left on Sync"; break;
case TWO_WAY_RIGHT_ON_EVEN: s = "Two-way, Right on Even"; break;
case TWO_WAY_LEFT_ON_EVEN: s = "Two-way, Left on Even"; break;
case FOUR_WAY_INTERLEAVED: s = "Four-way Interleaved"; break;
case SIDE_BY_SIDE: s = "Side-by-Side"; break;
}
printf (" Stereo: %s\n", s);
if (timing->digital_sync)
{
printf (" Digital Sync:\n");
printf (" composite: %s\n", yesno (timing->ad.digital.composite));
printf (" serrations: %s\n", yesno (timing->ad.digital.serrations));
printf (" negative vsync: %s\n",
yesno (timing->ad.digital.negative_vsync));
printf (" negative hsync: %s\n",
yesno (timing->ad.digital.negative_hsync));
}
else
{
printf (" Analog Sync:\n");
printf (" bipolar: %s\n", yesno (timing->ad.analog.bipolar));
printf (" serrations: %s\n", yesno (timing->ad.analog.serrations));
printf (" sync on green: %s\n", yesno (
timing->ad.analog.sync_on_green));
}
}
printf ("Detailed Product information:\n");
printf (" Product Name: %s\n", info->dsc_product_name);
printf (" Serial Number: %s\n", info->dsc_serial_number);
printf (" Unspecified String: %s\n", info->dsc_string);
}
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/edid-parse.c | C | apache-2.0 | 19,841 |
typedef unsigned char uchar;
typedef struct MonitorInfo MonitorInfo;
typedef struct Timing Timing;
typedef struct DetailedTiming DetailedTiming;
typedef enum
{
UNDEFINED,
DVI,
HDMI_A,
HDMI_B,
MDDI,
DISPLAY_PORT
} Interface;
typedef enum
{
UNDEFINED_COLOR,
MONOCHROME,
RGB,
OTHER_COLOR
} ColorType;
typedef enum
{
NO_STEREO,
FIELD_RIGHT,
FIELD_LEFT,
TWO_WAY_RIGHT_ON_EVEN,
TWO_WAY_LEFT_ON_EVEN,
FOUR_WAY_INTERLEAVED,
SIDE_BY_SIDE
} StereoType;
struct Timing
{
int width;
int height;
int frequency;
};
struct DetailedTiming
{
int pixel_clock;
int h_addr;
int h_blank;
int h_sync;
int h_front_porch;
int v_addr;
int v_blank;
int v_sync;
int v_front_porch;
int width_mm;
int height_mm;
int right_border;
int top_border;
int interlaced;
StereoType stereo;
int digital_sync;
union
{
struct
{
int bipolar;
int serrations;
int sync_on_green;
} analog;
struct
{
int composite;
int serrations;
int negative_vsync;
int negative_hsync;
} digital;
} ad;
};
struct MonitorInfo
{
int checksum;
char manufacturer_code[4];
int product_code;
unsigned int serial_number;
int production_week; /* -1 if not specified */
int production_year; /* -1 if not specified */
int model_year; /* -1 if not specified */
int major_version;
int minor_version;
int is_digital;
union
{
struct
{
int bits_per_primary;
Interface interface;
int rgb444;
int ycrcb444;
int ycrcb422;
} digital;
struct
{
double video_signal_level;
double sync_signal_level;
double total_signal_level;
int blank_to_black;
int separate_hv_sync;
int composite_sync_on_h;
int composite_sync_on_green;
int serration_on_vsync;
ColorType color_type;
} analog;
} ad;
int width_mm; /* -1 if not specified */
int height_mm; /* -1 if not specified */
double aspect_ratio; /* -1.0 if not specififed */
double gamma; /* -1.0 if not specified */
int standby;
int suspend;
int active_off;
int srgb_is_standard;
int preferred_timing_includes_native;
int continuous_frequency;
double red_x;
double red_y;
double green_x;
double green_y;
double blue_x;
double blue_y;
double white_x;
double white_y;
Timing established[24]; /* Terminated by 0x0x0 */
Timing standard[8];
int n_detailed_timings;
DetailedTiming detailed_timings[4]; /* If monitor has a preferred
* mode, it is the first one
* (whether it has, is
* determined by the
* preferred_timing_includes
* bit.
*/
/* Optional product description */
char dsc_serial_number[14];
char dsc_product_name[14];
char dsc_string[14]; /* Unspecified ASCII data */
};
MonitorInfo *decode_edid (const uchar *data);
void dump_monitor_info (MonitorInfo *info);
char * make_display_name (const char *output_name,
const MonitorInfo *info);
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/edid.h | C | apache-2.0 | 3,215 |
/*
Copyright (C) 2003-2006,2008 Jamey Sharp, Josh Triplett
Copyright © 2009 Red Hat, Inc.
Copyright 1990-1992,1999,2000,2004,2009,2010 Oracle and/or its affiliates.
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next
paragraph) shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include "../../SDL_internal.h"
#if SDL_VIDEO_DRIVER_X11
#include <X11/X.h>
#include "imKStoUCS.h"
static unsigned short const keysym_to_unicode_1a1_1ff[] = {
0x0104, 0x02d8, 0x0141, 0x0000, 0x013d, 0x015a, 0x0000, /* 0x01a0-0x01a7 */
0x0000, 0x0160, 0x015e, 0x0164, 0x0179, 0x0000, 0x017d, 0x017b, /* 0x01a8-0x01af */
0x0000, 0x0105, 0x02db, 0x0142, 0x0000, 0x013e, 0x015b, 0x02c7, /* 0x01b0-0x01b7 */
0x0000, 0x0161, 0x015f, 0x0165, 0x017a, 0x02dd, 0x017e, 0x017c, /* 0x01b8-0x01bf */
0x0154, 0x0000, 0x0000, 0x0102, 0x0000, 0x0139, 0x0106, 0x0000, /* 0x01c0-0x01c7 */
0x010c, 0x0000, 0x0118, 0x0000, 0x011a, 0x0000, 0x0000, 0x010e, /* 0x01c8-0x01cf */
0x0110, 0x0143, 0x0147, 0x0000, 0x0000, 0x0150, 0x0000, 0x0000, /* 0x01d0-0x01d7 */
0x0158, 0x016e, 0x0000, 0x0170, 0x0000, 0x0000, 0x0162, 0x0000, /* 0x01d8-0x01df */
0x0155, 0x0000, 0x0000, 0x0103, 0x0000, 0x013a, 0x0107, 0x0000, /* 0x01e0-0x01e7 */
0x010d, 0x0000, 0x0119, 0x0000, 0x011b, 0x0000, 0x0000, 0x010f, /* 0x01e8-0x01ef */
0x0111, 0x0144, 0x0148, 0x0000, 0x0000, 0x0151, 0x0000, 0x0000, /* 0x01f0-0x01f7 */
0x0159, 0x016f, 0x0000, 0x0171, 0x0000, 0x0000, 0x0163, 0x02d9 /* 0x01f8-0x01ff */
};
static unsigned short const keysym_to_unicode_2a1_2fe[] = {
0x0126, 0x0000, 0x0000, 0x0000, 0x0000, 0x0124, 0x0000, /* 0x02a0-0x02a7 */
0x0000, 0x0130, 0x0000, 0x011e, 0x0134, 0x0000, 0x0000, 0x0000, /* 0x02a8-0x02af */
0x0000, 0x0127, 0x0000, 0x0000, 0x0000, 0x0000, 0x0125, 0x0000, /* 0x02b0-0x02b7 */
0x0000, 0x0131, 0x0000, 0x011f, 0x0135, 0x0000, 0x0000, 0x0000, /* 0x02b8-0x02bf */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x010a, 0x0108, 0x0000, /* 0x02c0-0x02c7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x02c8-0x02cf */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0120, 0x0000, 0x0000, /* 0x02d0-0x02d7 */
0x011c, 0x0000, 0x0000, 0x0000, 0x0000, 0x016c, 0x015c, 0x0000, /* 0x02d8-0x02df */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x010b, 0x0109, 0x0000, /* 0x02e0-0x02e7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x02e8-0x02ef */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0121, 0x0000, 0x0000, /* 0x02f0-0x02f7 */
0x011d, 0x0000, 0x0000, 0x0000, 0x0000, 0x016d, 0x015d /* 0x02f8-0x02ff */
};
static unsigned short const keysym_to_unicode_3a2_3fe[] = {
0x0138, 0x0156, 0x0000, 0x0128, 0x013b, 0x0000, /* 0x03a0-0x03a7 */
0x0000, 0x0000, 0x0112, 0x0122, 0x0166, 0x0000, 0x0000, 0x0000, /* 0x03a8-0x03af */
0x0000, 0x0000, 0x0000, 0x0157, 0x0000, 0x0129, 0x013c, 0x0000, /* 0x03b0-0x03b7 */
0x0000, 0x0000, 0x0113, 0x0123, 0x0167, 0x014a, 0x0000, 0x014b, /* 0x03b8-0x03bf */
0x0100, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x012e, /* 0x03c0-0x03c7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0116, 0x0000, 0x0000, 0x012a, /* 0x03c8-0x03cf */
0x0000, 0x0145, 0x014c, 0x0136, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x03d0-0x03d7 */
0x0000, 0x0172, 0x0000, 0x0000, 0x0000, 0x0168, 0x016a, 0x0000, /* 0x03d8-0x03df */
0x0101, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x012f, /* 0x03e0-0x03e7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0117, 0x0000, 0x0000, 0x012b, /* 0x03e8-0x03ef */
0x0000, 0x0146, 0x014d, 0x0137, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x03f0-0x03f7 */
0x0000, 0x0173, 0x0000, 0x0000, 0x0000, 0x0169, 0x016b /* 0x03f8-0x03ff */
};
static unsigned short const keysym_to_unicode_4a1_4df[] = {
0x3002, 0x3008, 0x3009, 0x3001, 0x30fb, 0x30f2, 0x30a1, /* 0x04a0-0x04a7 */
0x30a3, 0x30a5, 0x30a7, 0x30a9, 0x30e3, 0x30e5, 0x30e7, 0x30c3, /* 0x04a8-0x04af */
0x30fc, 0x30a2, 0x30a4, 0x30a6, 0x30a8, 0x30aa, 0x30ab, 0x30ad, /* 0x04b0-0x04b7 */
0x30af, 0x30b1, 0x30b3, 0x30b5, 0x30b7, 0x30b9, 0x30bb, 0x30bd, /* 0x04b8-0x04bf */
0x30bf, 0x30c1, 0x30c4, 0x30c6, 0x30c8, 0x30ca, 0x30cb, 0x30cc, /* 0x04c0-0x04c7 */
0x30cd, 0x30ce, 0x30cf, 0x30d2, 0x30d5, 0x30d8, 0x30db, 0x30de, /* 0x04c8-0x04cf */
0x30df, 0x30e0, 0x30e1, 0x30e2, 0x30e4, 0x30e6, 0x30e8, 0x30e9, /* 0x04d0-0x04d7 */
0x30ea, 0x30eb, 0x30ec, 0x30ed, 0x30ef, 0x30f3, 0x309b, 0x309c /* 0x04d8-0x04df */
};
static unsigned short const keysym_to_unicode_590_5fe[] = {
0x06f0, 0x06f1, 0x06f2, 0x06f3, 0x06f4, 0x06f5, 0x06f6, 0x06f7, /* 0x0590-0x0597 */
0x06f8, 0x06f9, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x0598-0x059f */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x066a, 0x0670, 0x0679, /* 0x05a0-0x05a7 */
0x067e, 0x0686, 0x0688, 0x0691, 0x060c, 0x0000, 0x06d4, 0x0000, /* 0x05ac-0x05af */
0x0660, 0x0661, 0x0662, 0x0663, 0x0664, 0x0665, 0x0666, 0x0667, /* 0x05b0-0x05b7 */
0x0668, 0x0669, 0x0000, 0x061b, 0x0000, 0x0000, 0x0000, 0x061f, /* 0x05b8-0x05bf */
0x0000, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627, /* 0x05c0-0x05c7 */
0x0628, 0x0629, 0x062a, 0x062b, 0x062c, 0x062d, 0x062e, 0x062f, /* 0x05c8-0x05cf */
0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x0637, /* 0x05d0-0x05d7 */
0x0638, 0x0639, 0x063a, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x05d8-0x05df */
0x0640, 0x0641, 0x0642, 0x0643, 0x0644, 0x0645, 0x0646, 0x0647, /* 0x05e0-0x05e7 */
0x0648, 0x0649, 0x064a, 0x064b, 0x064c, 0x064d, 0x064e, 0x064f, /* 0x05e8-0x05ef */
0x0650, 0x0651, 0x0652, 0x0653, 0x0654, 0x0655, 0x0698, 0x06a4, /* 0x05f0-0x05f7 */
0x06a9, 0x06af, 0x06ba, 0x06be, 0x06cc, 0x06d2, 0x06c1 /* 0x05f8-0x05fe */
};
static unsigned short keysym_to_unicode_680_6ff[] = {
0x0492, 0x0496, 0x049a, 0x049c, 0x04a2, 0x04ae, 0x04b0, 0x04b2, /* 0x0680-0x0687 */
0x04b6, 0x04b8, 0x04ba, 0x0000, 0x04d8, 0x04e2, 0x04e8, 0x04ee, /* 0x0688-0x068f */
0x0493, 0x0497, 0x049b, 0x049d, 0x04a3, 0x04af, 0x04b1, 0x04b3, /* 0x0690-0x0697 */
0x04b7, 0x04b9, 0x04bb, 0x0000, 0x04d9, 0x04e3, 0x04e9, 0x04ef, /* 0x0698-0x069f */
0x0000, 0x0452, 0x0453, 0x0451, 0x0454, 0x0455, 0x0456, 0x0457, /* 0x06a0-0x06a7 */
0x0458, 0x0459, 0x045a, 0x045b, 0x045c, 0x0491, 0x045e, 0x045f, /* 0x06a8-0x06af */
0x2116, 0x0402, 0x0403, 0x0401, 0x0404, 0x0405, 0x0406, 0x0407, /* 0x06b0-0x06b7 */
0x0408, 0x0409, 0x040a, 0x040b, 0x040c, 0x0490, 0x040e, 0x040f, /* 0x06b8-0x06bf */
0x044e, 0x0430, 0x0431, 0x0446, 0x0434, 0x0435, 0x0444, 0x0433, /* 0x06c0-0x06c7 */
0x0445, 0x0438, 0x0439, 0x043a, 0x043b, 0x043c, 0x043d, 0x043e, /* 0x06c8-0x06cf */
0x043f, 0x044f, 0x0440, 0x0441, 0x0442, 0x0443, 0x0436, 0x0432, /* 0x06d0-0x06d7 */
0x044c, 0x044b, 0x0437, 0x0448, 0x044d, 0x0449, 0x0447, 0x044a, /* 0x06d8-0x06df */
0x042e, 0x0410, 0x0411, 0x0426, 0x0414, 0x0415, 0x0424, 0x0413, /* 0x06e0-0x06e7 */
0x0425, 0x0418, 0x0419, 0x041a, 0x041b, 0x041c, 0x041d, 0x041e, /* 0x06e8-0x06ef */
0x041f, 0x042f, 0x0420, 0x0421, 0x0422, 0x0423, 0x0416, 0x0412, /* 0x06f0-0x06f7 */
0x042c, 0x042b, 0x0417, 0x0428, 0x042d, 0x0429, 0x0427, 0x042a /* 0x06f8-0x06ff */
};
static unsigned short const keysym_to_unicode_7a1_7f9[] = {
0x0386, 0x0388, 0x0389, 0x038a, 0x03aa, 0x0000, 0x038c, /* 0x07a0-0x07a7 */
0x038e, 0x03ab, 0x0000, 0x038f, 0x0000, 0x0000, 0x0385, 0x2015, /* 0x07a8-0x07af */
0x0000, 0x03ac, 0x03ad, 0x03ae, 0x03af, 0x03ca, 0x0390, 0x03cc, /* 0x07b0-0x07b7 */
0x03cd, 0x03cb, 0x03b0, 0x03ce, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x07b8-0x07bf */
0x0000, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, /* 0x07c0-0x07c7 */
0x0398, 0x0399, 0x039a, 0x039b, 0x039c, 0x039d, 0x039e, 0x039f, /* 0x07c8-0x07cf */
0x03a0, 0x03a1, 0x03a3, 0x0000, 0x03a4, 0x03a5, 0x03a6, 0x03a7, /* 0x07d0-0x07d7 */
0x03a8, 0x03a9, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x07d8-0x07df */
0x0000, 0x03b1, 0x03b2, 0x03b3, 0x03b4, 0x03b5, 0x03b6, 0x03b7, /* 0x07e0-0x07e7 */
0x03b8, 0x03b9, 0x03ba, 0x03bb, 0x03bc, 0x03bd, 0x03be, 0x03bf, /* 0x07e8-0x07ef */
0x03c0, 0x03c1, 0x03c3, 0x03c2, 0x03c4, 0x03c5, 0x03c6, 0x03c7, /* 0x07f0-0x07f7 */
0x03c8, 0x03c9 /* 0x07f8-0x07ff */
};
static unsigned short const keysym_to_unicode_8a4_8fe[] = {
0x2320, 0x2321, 0x0000, 0x231c, /* 0x08a0-0x08a7 */
0x231d, 0x231e, 0x231f, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x08a8-0x08af */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x08b0-0x08b7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x2264, 0x2260, 0x2265, 0x222b, /* 0x08b8-0x08bf */
0x2234, 0x0000, 0x221e, 0x0000, 0x0000, 0x2207, 0x0000, 0x0000, /* 0x08c0-0x08c7 */
0x2245, 0x2246, 0x0000, 0x0000, 0x0000, 0x0000, 0x21d2, 0x0000, /* 0x08c8-0x08cf */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x221a, 0x0000, /* 0x08d0-0x08d7 */
0x0000, 0x0000, 0x2282, 0x2283, 0x2229, 0x222a, 0x2227, 0x2228, /* 0x08d8-0x08df */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x08e0-0x08e7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x2202, /* 0x08e8-0x08ef */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0192, 0x0000, /* 0x08f0-0x08f7 */
0x0000, 0x0000, 0x0000, 0x2190, 0x2191, 0x2192, 0x2193 /* 0x08f8-0x08ff */
};
static unsigned short const keysym_to_unicode_9df_9f8[] = {
0x2422, /* 0x09d8-0x09df */
0x2666, 0x25a6, 0x2409, 0x240c, 0x240d, 0x240a, 0x0000, 0x0000, /* 0x09e0-0x09e7 */
0x240a, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, 0x2500, /* 0x09e8-0x09ef */
0x0000, 0x0000, 0x0000, 0x0000, 0x251c, 0x2524, 0x2534, 0x252c, /* 0x09f0-0x09f7 */
0x2502 /* 0x09f8-0x09ff */
};
static unsigned short const keysym_to_unicode_aa1_afe[] = {
0x2003, 0x2002, 0x2004, 0x2005, 0x2007, 0x2008, 0x2009, /* 0x0aa0-0x0aa7 */
0x200a, 0x2014, 0x2013, 0x0000, 0x0000, 0x0000, 0x2026, 0x2025, /* 0x0aa8-0x0aaf */
0x2153, 0x2154, 0x2155, 0x2156, 0x2157, 0x2158, 0x2159, 0x215a, /* 0x0ab0-0x0ab7 */
0x2105, 0x0000, 0x0000, 0x2012, 0x2039, 0x2024, 0x203a, 0x0000, /* 0x0ab8-0x0abf */
0x0000, 0x0000, 0x0000, 0x215b, 0x215c, 0x215d, 0x215e, 0x0000, /* 0x0ac0-0x0ac7 */
0x0000, 0x2122, 0x2120, 0x0000, 0x25c1, 0x25b7, 0x25cb, 0x25ad, /* 0x0ac8-0x0acf */
0x2018, 0x2019, 0x201c, 0x201d, 0x211e, 0x2030, 0x2032, 0x2033, /* 0x0ad0-0x0ad7 */
0x0000, 0x271d, 0x0000, 0x220e, 0x25c2, 0x2023, 0x25cf, 0x25ac, /* 0x0ad8-0x0adf */
0x25e6, 0x25ab, 0x25ae, 0x25b5, 0x25bf, 0x2606, 0x2022, 0x25aa, /* 0x0ae0-0x0ae7 */
0x25b4, 0x25be, 0x261a, 0x261b, 0x2663, 0x2666, 0x2665, 0x0000, /* 0x0ae8-0x0aef */
0x2720, 0x2020, 0x2021, 0x2713, 0x2612, 0x266f, 0x266d, 0x2642, /* 0x0af0-0x0af7 */
0x2640, 0x2121, 0x2315, 0x2117, 0x2038, 0x201a, 0x201e /* 0x0af8-0x0aff */
};
/* none of the APL keysyms match the Unicode characters */
static unsigned short const keysym_to_unicode_cdf_cfa[] = {
0x2017, /* 0x0cd8-0x0cdf */
0x05d0, 0x05d1, 0x05d2, 0x05d3, 0x05d4, 0x05d5, 0x05d6, 0x05d7, /* 0x0ce0-0x0ce7 */
0x05d8, 0x05d9, 0x05da, 0x05db, 0x05dc, 0x05dd, 0x05de, 0x05df, /* 0x0ce8-0x0cef */
0x05e0, 0x05e1, 0x05e2, 0x05e3, 0x05e4, 0x05e5, 0x05e6, 0x05e7, /* 0x0cf0-0x0cf7 */
0x05e8, 0x05e9, 0x05ea /* 0x0cf8-0x0cff */
};
static unsigned short const keysym_to_unicode_da1_df9[] = {
0x0e01, 0x0e02, 0x0e03, 0x0e04, 0x0e05, 0x0e06, 0x0e07, /* 0x0da0-0x0da7 */
0x0e08, 0x0e09, 0x0e0a, 0x0e0b, 0x0e0c, 0x0e0d, 0x0e0e, 0x0e0f, /* 0x0da8-0x0daf */
0x0e10, 0x0e11, 0x0e12, 0x0e13, 0x0e14, 0x0e15, 0x0e16, 0x0e17, /* 0x0db0-0x0db7 */
0x0e18, 0x0e19, 0x0e1a, 0x0e1b, 0x0e1c, 0x0e1d, 0x0e1e, 0x0e1f, /* 0x0db8-0x0dbf */
0x0e20, 0x0e21, 0x0e22, 0x0e23, 0x0e24, 0x0e25, 0x0e26, 0x0e27, /* 0x0dc0-0x0dc7 */
0x0e28, 0x0e29, 0x0e2a, 0x0e2b, 0x0e2c, 0x0e2d, 0x0e2e, 0x0e2f, /* 0x0dc8-0x0dcf */
0x0e30, 0x0e31, 0x0e32, 0x0e33, 0x0e34, 0x0e35, 0x0e36, 0x0e37, /* 0x0dd0-0x0dd7 */
0x0e38, 0x0e39, 0x0e3a, 0x0000, 0x0000, 0x0000, 0x0e3e, 0x0e3f, /* 0x0dd8-0x0ddf */
0x0e40, 0x0e41, 0x0e42, 0x0e43, 0x0e44, 0x0e45, 0x0e46, 0x0e47, /* 0x0de0-0x0de7 */
0x0e48, 0x0e49, 0x0e4a, 0x0e4b, 0x0e4c, 0x0e4d, 0x0000, 0x0000, /* 0x0de8-0x0def */
0x0e50, 0x0e51, 0x0e52, 0x0e53, 0x0e54, 0x0e55, 0x0e56, 0x0e57, /* 0x0df0-0x0df7 */
0x0e58, 0x0e59 /* 0x0df8-0x0dff */
};
static unsigned short const keysym_to_unicode_ea0_eff[] = {
0x0000, 0x1101, 0x1101, 0x11aa, 0x1102, 0x11ac, 0x11ad, 0x1103, /* 0x0ea0-0x0ea7 */
0x1104, 0x1105, 0x11b0, 0x11b1, 0x11b2, 0x11b3, 0x11b4, 0x11b5, /* 0x0ea8-0x0eaf */
0x11b6, 0x1106, 0x1107, 0x1108, 0x11b9, 0x1109, 0x110a, 0x110b, /* 0x0eb0-0x0eb7 */
0x110c, 0x110d, 0x110e, 0x110f, 0x1110, 0x1111, 0x1112, 0x1161, /* 0x0eb8-0x0ebf */
0x1162, 0x1163, 0x1164, 0x1165, 0x1166, 0x1167, 0x1168, 0x1169, /* 0x0ec0-0x0ec7 */
0x116a, 0x116b, 0x116c, 0x116d, 0x116e, 0x116f, 0x1170, 0x1171, /* 0x0ec8-0x0ecf */
0x1172, 0x1173, 0x1174, 0x1175, 0x11a8, 0x11a9, 0x11aa, 0x11ab, /* 0x0ed0-0x0ed7 */
0x11ac, 0x11ad, 0x11ae, 0x11af, 0x11b0, 0x11b1, 0x11b2, 0x11b3, /* 0x0ed8-0x0edf */
0x11b4, 0x11b5, 0x11b6, 0x11b7, 0x11b8, 0x11b9, 0x11ba, 0x11bb, /* 0x0ee0-0x0ee7 */
0x11bc, 0x11bd, 0x11be, 0x11bf, 0x11c0, 0x11c1, 0x11c2, 0x0000, /* 0x0ee8-0x0eef */
0x0000, 0x0000, 0x1140, 0x0000, 0x0000, 0x1159, 0x119e, 0x0000, /* 0x0ef0-0x0ef7 */
0x11eb, 0x0000, 0x11f9, 0x0000, 0x0000, 0x0000, 0x0000, 0x20a9, /* 0x0ef8-0x0eff */
};
static unsigned short keysym_to_unicode_12a1_12fe[] = {
0x1e02, 0x1e03, 0x0000, 0x0000, 0x0000, 0x1e0a, 0x0000, /* 0x12a0-0x12a7 */
0x1e80, 0x0000, 0x1e82, 0x1e0b, 0x1ef2, 0x0000, 0x0000, 0x0000, /* 0x12a8-0x12af */
0x1e1e, 0x1e1f, 0x0000, 0x0000, 0x1e40, 0x1e41, 0x0000, 0x1e56, /* 0x12b0-0x12b7 */
0x1e81, 0x1e57, 0x1e83, 0x1e60, 0x1ef3, 0x1e84, 0x1e85, 0x1e61, /* 0x12b8-0x12bf */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x12c0-0x12c7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x12c8-0x12cf */
0x0174, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1e6a, /* 0x12d0-0x12d7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0176, 0x0000, /* 0x12d8-0x12df */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x12e0-0x12e7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x12e8-0x12ef */
0x0175, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1e6b, /* 0x12f0-0x12f7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0177 /* 0x12f0-0x12ff */
};
static unsigned short const keysym_to_unicode_13bc_13be[] = {
0x0152, 0x0153, 0x0178 /* 0x13b8-0x13bf */
};
static unsigned short keysym_to_unicode_14a1_14ff[] = {
0x2741, 0x00a7, 0x0589, 0x0029, 0x0028, 0x00bb, 0x00ab, /* 0x14a0-0x14a7 */
0x2014, 0x002e, 0x055d, 0x002c, 0x2013, 0x058a, 0x2026, 0x055c, /* 0x14a8-0x14af */
0x055b, 0x055e, 0x0531, 0x0561, 0x0532, 0x0562, 0x0533, 0x0563, /* 0x14b0-0x14b7 */
0x0534, 0x0564, 0x0535, 0x0565, 0x0536, 0x0566, 0x0537, 0x0567, /* 0x14b8-0x14bf */
0x0538, 0x0568, 0x0539, 0x0569, 0x053a, 0x056a, 0x053b, 0x056b, /* 0x14c0-0x14c7 */
0x053c, 0x056c, 0x053d, 0x056d, 0x053e, 0x056e, 0x053f, 0x056f, /* 0x14c8-0x14cf */
0x0540, 0x0570, 0x0541, 0x0571, 0x0542, 0x0572, 0x0543, 0x0573, /* 0x14d0-0x14d7 */
0x0544, 0x0574, 0x0545, 0x0575, 0x0546, 0x0576, 0x0547, 0x0577, /* 0x14d8-0x14df */
0x0548, 0x0578, 0x0549, 0x0579, 0x054a, 0x057a, 0x054b, 0x057b, /* 0x14e0-0x14e7 */
0x054c, 0x057c, 0x054d, 0x057d, 0x054e, 0x057e, 0x054f, 0x057f, /* 0x14e8-0x14ef */
0x0550, 0x0580, 0x0551, 0x0581, 0x0552, 0x0582, 0x0553, 0x0583, /* 0x14f0-0x14f7 */
0x0554, 0x0584, 0x0555, 0x0585, 0x0556, 0x0586, 0x2019, 0x0027, /* 0x14f8-0x14ff */
};
static unsigned short keysym_to_unicode_15d0_15f6[] = {
0x10d0, 0x10d1, 0x10d2, 0x10d3, 0x10d4, 0x10d5, 0x10d6, 0x10d7, /* 0x15d0-0x15d7 */
0x10d8, 0x10d9, 0x10da, 0x10db, 0x10dc, 0x10dd, 0x10de, 0x10df, /* 0x15d8-0x15df */
0x10e0, 0x10e1, 0x10e2, 0x10e3, 0x10e4, 0x10e5, 0x10e6, 0x10e7, /* 0x15e0-0x15e7 */
0x10e8, 0x10e9, 0x10ea, 0x10eb, 0x10ec, 0x10ed, 0x10ee, 0x10ef, /* 0x15e8-0x15ef */
0x10f0, 0x10f1, 0x10f2, 0x10f3, 0x10f4, 0x10f5, 0x10f6 /* 0x15f0-0x15f7 */
};
static unsigned short keysym_to_unicode_16a0_16f6[] = {
0x0000, 0x0000, 0xf0a2, 0x1e8a, 0x0000, 0xf0a5, 0x012c, 0xf0a7, /* 0x16a0-0x16a7 */
0xf0a8, 0x01b5, 0x01e6, 0x0000, 0x0000, 0x0000, 0x0000, 0x019f, /* 0x16a8-0x16af */
0x0000, 0x0000, 0xf0b2, 0x1e8b, 0x01d1, 0xf0b5, 0x012d, 0xf0b7, /* 0x16b0-0x16b7 */
0xf0b8, 0x01b6, 0x01e7, 0x0000, 0x0000, 0x01d2, 0x0000, 0x0275, /* 0x16b8-0x16bf */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x018f, 0x0000, /* 0x16c0-0x16c7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x16c8-0x16cf */
0x0000, 0x1e36, 0xf0d2, 0xf0d3, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x16d0-0x16d7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x16d8-0x16df */
0x0000, 0x1e37, 0xf0e2, 0xf0e3, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x16e0-0x16e7 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* 0x16e8-0x16ef */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0259 /* 0x16f0-0x16f6 */
};
static unsigned short const keysym_to_unicode_1e9f_1eff[] = {
0x0303,
0x1ea0, 0x1ea1, 0x1ea2, 0x1ea3, 0x1ea4, 0x1ea5, 0x1ea6, 0x1ea7, /* 0x1ea0-0x1ea7 */
0x1ea8, 0x1ea9, 0x1eaa, 0x1eab, 0x1eac, 0x1ead, 0x1eae, 0x1eaf, /* 0x1ea8-0x1eaf */
0x1eb0, 0x1eb1, 0x1eb2, 0x1eb3, 0x1eb4, 0x1eb5, 0x1eb6, 0x1eb7, /* 0x1eb0-0x1eb7 */
0x1eb8, 0x1eb9, 0x1eba, 0x1ebb, 0x1ebc, 0x1ebd, 0x1ebe, 0x1ebf, /* 0x1eb8-0x1ebf */
0x1ec0, 0x1ec1, 0x1ec2, 0x1ec3, 0x1ec4, 0x1ec5, 0x1ec6, 0x1ec7, /* 0x1ec0-0x1ec7 */
0x1ec8, 0x1ec9, 0x1eca, 0x1ecb, 0x1ecc, 0x1ecd, 0x1ece, 0x1ecf, /* 0x1ec8-0x1ecf */
0x1ed0, 0x1ed1, 0x1ed2, 0x1ed3, 0x1ed4, 0x1ed5, 0x1ed6, 0x1ed7, /* 0x1ed0-0x1ed7 */
0x1ed8, 0x1ed9, 0x1eda, 0x1edb, 0x1edc, 0x1edd, 0x1ede, 0x1edf, /* 0x1ed8-0x1edf */
0x1ee0, 0x1ee1, 0x1ee2, 0x1ee3, 0x1ee4, 0x1ee5, 0x1ee6, 0x1ee7, /* 0x1ee0-0x1ee7 */
0x1ee8, 0x1ee9, 0x1eea, 0x1eeb, 0x1eec, 0x1eed, 0x1eee, 0x1eef, /* 0x1ee8-0x1eef */
0x1ef0, 0x1ef1, 0x0300, 0x0301, 0x1ef4, 0x1ef5, 0x1ef6, 0x1ef7, /* 0x1ef0-0x1ef7 */
0x1ef8, 0x1ef9, 0x01a0, 0x01a1, 0x01af, 0x01b0, 0x0309, 0x0323 /* 0x1ef8-0x1eff */
};
static unsigned short const keysym_to_unicode_20a0_20ac[] = {
0x20a0, 0x20a1, 0x20a2, 0x20a3, 0x20a4, 0x20a5, 0x20a6, 0x20a7, /* 0x20a0-0x20a7 */
0x20a8, 0x20a9, 0x20aa, 0x20ab, 0x20ac /* 0x20a8-0x20af */
};
unsigned int
X11_KeySymToUcs4(KeySym keysym)
{
/* 'Unicode keysym' */
if ((keysym & 0xff000000) == 0x01000000)
return (keysym & 0x00ffffff);
if (keysym > 0 && keysym < 0x100)
return keysym;
else if (keysym > 0x1a0 && keysym < 0x200)
return keysym_to_unicode_1a1_1ff[keysym - 0x1a1];
else if (keysym > 0x2a0 && keysym < 0x2ff)
return keysym_to_unicode_2a1_2fe[keysym - 0x2a1];
else if (keysym > 0x3a1 && keysym < 0x3ff)
return keysym_to_unicode_3a2_3fe[keysym - 0x3a2];
else if (keysym > 0x4a0 && keysym < 0x4e0)
return keysym_to_unicode_4a1_4df[keysym - 0x4a1];
else if (keysym > 0x589 && keysym < 0x5ff)
return keysym_to_unicode_590_5fe[keysym - 0x590];
else if (keysym > 0x67f && keysym < 0x700)
return keysym_to_unicode_680_6ff[keysym - 0x680];
else if (keysym > 0x7a0 && keysym < 0x7fa)
return keysym_to_unicode_7a1_7f9[keysym - 0x7a1];
else if (keysym > 0x8a3 && keysym < 0x8ff)
return keysym_to_unicode_8a4_8fe[keysym - 0x8a4];
else if (keysym > 0x9de && keysym < 0x9f9)
return keysym_to_unicode_9df_9f8[keysym - 0x9df];
else if (keysym > 0xaa0 && keysym < 0xaff)
return keysym_to_unicode_aa1_afe[keysym - 0xaa1];
else if (keysym > 0xcde && keysym < 0xcfb)
return keysym_to_unicode_cdf_cfa[keysym - 0xcdf];
else if (keysym > 0xda0 && keysym < 0xdfa)
return keysym_to_unicode_da1_df9[keysym - 0xda1];
else if (keysym > 0xe9f && keysym < 0xf00)
return keysym_to_unicode_ea0_eff[keysym - 0xea0];
else if (keysym > 0x12a0 && keysym < 0x12ff)
return keysym_to_unicode_12a1_12fe[keysym - 0x12a1];
else if (keysym > 0x13bb && keysym < 0x13bf)
return keysym_to_unicode_13bc_13be[keysym - 0x13bc];
else if (keysym > 0x14a0 && keysym < 0x1500)
return keysym_to_unicode_14a1_14ff[keysym - 0x14a1];
else if (keysym > 0x15cf && keysym < 0x15f7)
return keysym_to_unicode_15d0_15f6[keysym - 0x15d0];
else if (keysym > 0x169f && keysym < 0x16f7)
return keysym_to_unicode_16a0_16f6[keysym - 0x16a0];
else if (keysym > 0x1e9e && keysym < 0x1f00)
return keysym_to_unicode_1e9f_1eff[keysym - 0x1e9f];
else if (keysym > 0x209f && keysym < 0x20ad)
return keysym_to_unicode_20a0_20ac[keysym - 0x20a0];
else
return 0;
}
#endif /* SDL_VIDEO_DRIVER_X11 */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/imKStoUCS.c | C | apache-2.0 | 22,525 |
#ifndef _imKStoUCS_h
#define _imKStoUCS_h
/*
Copyright (C) 2003-2006,2008 Jamey Sharp, Josh Triplett
Copyright © 2009 Red Hat, Inc.
Copyright 1990-1992,1999,2000,2004,2009,2010 Oracle and/or its affiliates.
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next
paragraph) shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
extern unsigned int X11_KeySymToUcs4(KeySym keysym);
#endif /* _imKStoUCS_h */
| YifuLiu/AliOS-Things | components/SDL2/src/video/x11/imKStoUCS.h | C | apache-2.0 | 1,372 |
// Copyright 2016 Adrien Descamps
// Distributed under BSD 3-Clause License
#include "../../SDL_internal.h"
#if SDL_HAVE_YUV
#include "yuv_rgb.h"
#include "SDL_cpuinfo.h"
/*#include <x86intrin.h>*/
#define PRECISION 6
#define PRECISION_FACTOR (1<<PRECISION)
typedef struct
{
uint8_t y_shift;
int16_t matrix[3][3];
} RGB2YUVParam;
// |Y| |y_shift| |matrix[0][0] matrix[0][1] matrix[0][2]| |R|
// |U| = | 128 | + 1/PRECISION_FACTOR * |matrix[1][0] matrix[1][1] matrix[1][2]| * |G|
// |V| | 128 | |matrix[2][0] matrix[2][1] matrix[2][2]| |B|
typedef struct
{
uint8_t y_shift;
int16_t y_factor;
int16_t v_r_factor;
int16_t u_g_factor;
int16_t v_g_factor;
int16_t u_b_factor;
} YUV2RGBParam;
// |R| |y_factor 0 v_r_factor| |Y-y_shift|
// |G| = 1/PRECISION_FACTOR * |y_factor u_g_factor v_g_factor| * | U-128 |
// |B| |y_factor u_b_factor 0 | | V-128 |
#define V(value) (int16_t)((value*PRECISION_FACTOR)+0.5)
// for ITU-T T.871, values can be found in section 7
// for ITU-R BT.601-7 values are derived from equations in sections 2.5.1-2.5.3, assuming RGB is encoded using full range ([0-1]<->[0-255])
// for ITU-R BT.709-6 values are derived from equations in sections 3.2-3.4, assuming RGB is encoded using full range ([0-1]<->[0-255])
// all values are rounded to the fourth decimal
static const YUV2RGBParam YUV2RGB[3] = {
// ITU-T T.871 (JPEG)
{/*.y_shift=*/ 0, /*.y_factor=*/ V(1.0), /*.v_r_factor=*/ V(1.402), /*.u_g_factor=*/ -V(0.3441), /*.v_g_factor=*/ -V(0.7141), /*.u_b_factor=*/ V(1.772)},
// ITU-R BT.601-7
{/*.y_shift=*/ 16, /*.y_factor=*/ V(1.1644), /*.v_r_factor=*/ V(1.596), /*.u_g_factor=*/ -V(0.3918), /*.v_g_factor=*/ -V(0.813), /*.u_b_factor=*/ V(2.0172)},
// ITU-R BT.709-6
{/*.y_shift=*/ 16, /*.y_factor=*/ V(1.1644), /*.v_r_factor=*/ V(1.7927), /*.u_g_factor=*/ -V(0.2132), /*.v_g_factor=*/ -V(0.5329), /*.u_b_factor=*/ V(2.1124)}
};
static const RGB2YUVParam RGB2YUV[3] = {
// ITU-T T.871 (JPEG)
{/*.y_shift=*/ 0, /*.matrix=*/ {{V(0.299), V(0.587), V(0.114)}, {-V(0.1687), -V(0.3313), V(0.5)}, {V(0.5), -V(0.4187), -V(0.0813)}}},
// ITU-R BT.601-7
{/*.y_shift=*/ 16, /*.matrix=*/ {{V(0.2568), V(0.5041), V(0.0979)}, {-V(0.1482), -V(0.291), V(0.4392)}, {V(0.4392), -V(0.3678), -V(0.0714)}}},
// ITU-R BT.709-6
{/*.y_shift=*/ 16, /*.matrix=*/ {{V(0.1826), V(0.6142), V(0.062)}, {-V(0.1006), -V(0.3386), V(0.4392)}, {V(0.4392), -V(0.3989), -V(0.0403)}}}
};
/* The various layouts of YUV data we support */
#define YUV_FORMAT_420 1
#define YUV_FORMAT_422 2
#define YUV_FORMAT_NV12 3
/* The various formats of RGB pixel that we support */
#define RGB_FORMAT_RGB565 1
#define RGB_FORMAT_RGB24 2
#define RGB_FORMAT_RGBA 3
#define RGB_FORMAT_BGRA 4
#define RGB_FORMAT_ARGB 5
#define RGB_FORMAT_ABGR 6
// divide by PRECISION_FACTOR and clamp to [0:255] interval
// input must be in the [-128*PRECISION_FACTOR:384*PRECISION_FACTOR] range
static uint8_t clampU8(int32_t v)
{
static const uint8_t lut[512] =
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,
47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,
91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,
159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,
225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255
};
return lut[(v+128*PRECISION_FACTOR)>>PRECISION];
}
#define STD_FUNCTION_NAME yuv420_rgb565_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_RGB565
#include "yuv_rgb_std_func.h"
#define STD_FUNCTION_NAME yuv420_rgb24_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_RGB24
#include "yuv_rgb_std_func.h"
#define STD_FUNCTION_NAME yuv420_rgba_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_RGBA
#include "yuv_rgb_std_func.h"
#define STD_FUNCTION_NAME yuv420_bgra_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_BGRA
#include "yuv_rgb_std_func.h"
#define STD_FUNCTION_NAME yuv420_argb_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_ARGB
#include "yuv_rgb_std_func.h"
#define STD_FUNCTION_NAME yuv420_abgr_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_ABGR
#include "yuv_rgb_std_func.h"
#define STD_FUNCTION_NAME yuv422_rgb565_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_RGB565
#include "yuv_rgb_std_func.h"
#define STD_FUNCTION_NAME yuv422_rgb24_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_RGB24
#include "yuv_rgb_std_func.h"
#define STD_FUNCTION_NAME yuv422_rgba_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_RGBA
#include "yuv_rgb_std_func.h"
#define STD_FUNCTION_NAME yuv422_bgra_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_BGRA
#include "yuv_rgb_std_func.h"
#define STD_FUNCTION_NAME yuv422_argb_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_ARGB
#include "yuv_rgb_std_func.h"
#define STD_FUNCTION_NAME yuv422_abgr_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_ABGR
#include "yuv_rgb_std_func.h"
#define STD_FUNCTION_NAME yuvnv12_rgb565_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_RGB565
#include "yuv_rgb_std_func.h"
#define STD_FUNCTION_NAME yuvnv12_rgb24_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_RGB24
#include "yuv_rgb_std_func.h"
#define STD_FUNCTION_NAME yuvnv12_rgba_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_RGBA
#include "yuv_rgb_std_func.h"
#define STD_FUNCTION_NAME yuvnv12_bgra_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_BGRA
#include "yuv_rgb_std_func.h"
#define STD_FUNCTION_NAME yuvnv12_argb_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_ARGB
#include "yuv_rgb_std_func.h"
#define STD_FUNCTION_NAME yuvnv12_abgr_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_ABGR
#include "yuv_rgb_std_func.h"
void rgb24_yuv420_std(
uint32_t width, uint32_t height,
const uint8_t *RGB, uint32_t RGB_stride,
uint8_t *Y, uint8_t *U, uint8_t *V, uint32_t Y_stride, uint32_t UV_stride,
YCbCrType yuv_type)
{
const RGB2YUVParam *const param = &(RGB2YUV[yuv_type]);
uint32_t x, y;
for(y=0; y<(height-1); y+=2)
{
const uint8_t *rgb_ptr1=RGB+y*RGB_stride,
*rgb_ptr2=RGB+(y+1)*RGB_stride;
uint8_t *y_ptr1=Y+y*Y_stride,
*y_ptr2=Y+(y+1)*Y_stride,
*u_ptr=U+(y/2)*UV_stride,
*v_ptr=V+(y/2)*UV_stride;
for(x=0; x<(width-1); x+=2)
{
// compute yuv for the four pixels, u and v values are summed
int32_t y_tmp, u_tmp, v_tmp;
y_tmp = param->matrix[0][0]*rgb_ptr1[0] + param->matrix[0][1]*rgb_ptr1[1] + param->matrix[0][2]*rgb_ptr1[2];
u_tmp = param->matrix[1][0]*rgb_ptr1[0] + param->matrix[1][1]*rgb_ptr1[1] + param->matrix[1][2]*rgb_ptr1[2];
v_tmp = param->matrix[2][0]*rgb_ptr1[0] + param->matrix[2][1]*rgb_ptr1[1] + param->matrix[2][2]*rgb_ptr1[2];
y_ptr1[0]=clampU8(y_tmp+((param->y_shift)<<PRECISION));
y_tmp = param->matrix[0][0]*rgb_ptr1[3] + param->matrix[0][1]*rgb_ptr1[4] + param->matrix[0][2]*rgb_ptr1[5];
u_tmp += param->matrix[1][0]*rgb_ptr1[3] + param->matrix[1][1]*rgb_ptr1[4] + param->matrix[1][2]*rgb_ptr1[5];
v_tmp += param->matrix[2][0]*rgb_ptr1[3] + param->matrix[2][1]*rgb_ptr1[4] + param->matrix[2][2]*rgb_ptr1[5];
y_ptr1[1]=clampU8(y_tmp+((param->y_shift)<<PRECISION));
y_tmp = param->matrix[0][0]*rgb_ptr2[0] + param->matrix[0][1]*rgb_ptr2[1] + param->matrix[0][2]*rgb_ptr2[2];
u_tmp += param->matrix[1][0]*rgb_ptr2[0] + param->matrix[1][1]*rgb_ptr2[1] + param->matrix[1][2]*rgb_ptr2[2];
v_tmp += param->matrix[2][0]*rgb_ptr2[0] + param->matrix[2][1]*rgb_ptr2[1] + param->matrix[2][2]*rgb_ptr2[2];
y_ptr2[0]=clampU8(y_tmp+((param->y_shift)<<PRECISION));
y_tmp = param->matrix[0][0]*rgb_ptr2[3] + param->matrix[0][1]*rgb_ptr2[4] + param->matrix[0][2]*rgb_ptr2[5];
u_tmp += param->matrix[1][0]*rgb_ptr2[3] + param->matrix[1][1]*rgb_ptr2[4] + param->matrix[1][2]*rgb_ptr2[5];
v_tmp += param->matrix[2][0]*rgb_ptr2[3] + param->matrix[2][1]*rgb_ptr2[4] + param->matrix[2][2]*rgb_ptr2[5];
y_ptr2[1]=clampU8(y_tmp+((param->y_shift)<<PRECISION));
u_ptr[0] = clampU8(u_tmp/4+(128<<PRECISION));
v_ptr[0] = clampU8(v_tmp/4+(128<<PRECISION));
rgb_ptr1 += 6;
rgb_ptr2 += 6;
y_ptr1 += 2;
y_ptr2 += 2;
u_ptr += 1;
v_ptr += 1;
}
}
}
#ifdef __SSE2__
#define SSE_FUNCTION_NAME yuv420_rgb565_sse
#define STD_FUNCTION_NAME yuv420_rgb565_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_RGB565
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv420_rgb565_sseu
#define STD_FUNCTION_NAME yuv420_rgb565_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_RGB565
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv420_rgb24_sse
#define STD_FUNCTION_NAME yuv420_rgb24_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_RGB24
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv420_rgb24_sseu
#define STD_FUNCTION_NAME yuv420_rgb24_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_RGB24
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv420_rgba_sse
#define STD_FUNCTION_NAME yuv420_rgba_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_RGBA
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv420_rgba_sseu
#define STD_FUNCTION_NAME yuv420_rgba_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_RGBA
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv420_bgra_sse
#define STD_FUNCTION_NAME yuv420_bgra_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_BGRA
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv420_bgra_sseu
#define STD_FUNCTION_NAME yuv420_bgra_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_BGRA
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv420_argb_sse
#define STD_FUNCTION_NAME yuv420_argb_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_ARGB
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv420_argb_sseu
#define STD_FUNCTION_NAME yuv420_argb_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_ARGB
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv420_abgr_sse
#define STD_FUNCTION_NAME yuv420_abgr_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_ABGR
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv420_abgr_sseu
#define STD_FUNCTION_NAME yuv420_abgr_std
#define YUV_FORMAT YUV_FORMAT_420
#define RGB_FORMAT RGB_FORMAT_ABGR
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv422_rgb565_sse
#define STD_FUNCTION_NAME yuv422_rgb565_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_RGB565
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv422_rgb565_sseu
#define STD_FUNCTION_NAME yuv422_rgb565_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_RGB565
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv422_rgb24_sse
#define STD_FUNCTION_NAME yuv422_rgb24_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_RGB24
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv422_rgb24_sseu
#define STD_FUNCTION_NAME yuv422_rgb24_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_RGB24
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv422_rgba_sse
#define STD_FUNCTION_NAME yuv422_rgba_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_RGBA
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv422_rgba_sseu
#define STD_FUNCTION_NAME yuv422_rgba_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_RGBA
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv422_bgra_sse
#define STD_FUNCTION_NAME yuv422_bgra_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_BGRA
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv422_bgra_sseu
#define STD_FUNCTION_NAME yuv422_bgra_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_BGRA
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv422_argb_sse
#define STD_FUNCTION_NAME yuv422_argb_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_ARGB
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv422_argb_sseu
#define STD_FUNCTION_NAME yuv422_argb_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_ARGB
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv422_abgr_sse
#define STD_FUNCTION_NAME yuv422_abgr_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_ABGR
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuv422_abgr_sseu
#define STD_FUNCTION_NAME yuv422_abgr_std
#define YUV_FORMAT YUV_FORMAT_422
#define RGB_FORMAT RGB_FORMAT_ABGR
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuvnv12_rgb565_sse
#define STD_FUNCTION_NAME yuvnv12_rgb565_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_RGB565
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuvnv12_rgb565_sseu
#define STD_FUNCTION_NAME yuvnv12_rgb565_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_RGB565
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuvnv12_rgb24_sse
#define STD_FUNCTION_NAME yuvnv12_rgb24_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_RGB24
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuvnv12_rgb24_sseu
#define STD_FUNCTION_NAME yuvnv12_rgb24_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_RGB24
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuvnv12_rgba_sse
#define STD_FUNCTION_NAME yuvnv12_rgba_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_RGBA
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuvnv12_rgba_sseu
#define STD_FUNCTION_NAME yuvnv12_rgba_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_RGBA
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuvnv12_bgra_sse
#define STD_FUNCTION_NAME yuvnv12_bgra_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_BGRA
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuvnv12_bgra_sseu
#define STD_FUNCTION_NAME yuvnv12_bgra_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_BGRA
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuvnv12_argb_sse
#define STD_FUNCTION_NAME yuvnv12_argb_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_ARGB
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuvnv12_argb_sseu
#define STD_FUNCTION_NAME yuvnv12_argb_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_ARGB
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuvnv12_abgr_sse
#define STD_FUNCTION_NAME yuvnv12_abgr_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_ABGR
#define SSE_ALIGNED
#include "yuv_rgb_sse_func.h"
#define SSE_FUNCTION_NAME yuvnv12_abgr_sseu
#define STD_FUNCTION_NAME yuvnv12_abgr_std
#define YUV_FORMAT YUV_FORMAT_NV12
#define RGB_FORMAT RGB_FORMAT_ABGR
#include "yuv_rgb_sse_func.h"
#define UNPACK_RGB24_32_STEP1(RGB1, RGB2, RGB3, RGB4, RGB5, RGB6, R1, R2, G1, G2, B1, B2) \
R1 = _mm_unpacklo_epi8(RGB1, RGB4); \
R2 = _mm_unpackhi_epi8(RGB1, RGB4); \
G1 = _mm_unpacklo_epi8(RGB2, RGB5); \
G2 = _mm_unpackhi_epi8(RGB2, RGB5); \
B1 = _mm_unpacklo_epi8(RGB3, RGB6); \
B2 = _mm_unpackhi_epi8(RGB3, RGB6);
#define UNPACK_RGB24_32_STEP2(RGB1, RGB2, RGB3, RGB4, RGB5, RGB6, R1, R2, G1, G2, B1, B2) \
RGB1 = _mm_unpacklo_epi8(R1, G2); \
RGB2 = _mm_unpackhi_epi8(R1, G2); \
RGB3 = _mm_unpacklo_epi8(R2, B1); \
RGB4 = _mm_unpackhi_epi8(R2, B1); \
RGB5 = _mm_unpacklo_epi8(G1, B2); \
RGB6 = _mm_unpackhi_epi8(G1, B2); \
#define UNPACK_RGB24_32(RGB1, RGB2, RGB3, RGB4, RGB5, RGB6, R1, R2, G1, G2, B1, B2) \
UNPACK_RGB24_32_STEP1(RGB1, RGB2, RGB3, RGB4, RGB5, RGB6, R1, R2, G1, G2, B1, B2) \
UNPACK_RGB24_32_STEP2(RGB1, RGB2, RGB3, RGB4, RGB5, RGB6, R1, R2, G1, G2, B1, B2) \
UNPACK_RGB24_32_STEP1(RGB1, RGB2, RGB3, RGB4, RGB5, RGB6, R1, R2, G1, G2, B1, B2) \
UNPACK_RGB24_32_STEP2(RGB1, RGB2, RGB3, RGB4, RGB5, RGB6, R1, R2, G1, G2, B1, B2) \
UNPACK_RGB24_32_STEP1(RGB1, RGB2, RGB3, RGB4, RGB5, RGB6, R1, R2, G1, G2, B1, B2) \
#define RGB2YUV_16(R, G, B, Y, U, V) \
Y = _mm_add_epi16(_mm_mullo_epi16(R, _mm_set1_epi16(param->matrix[0][0])), \
_mm_mullo_epi16(G, _mm_set1_epi16(param->matrix[0][1]))); \
Y = _mm_add_epi16(Y, _mm_mullo_epi16(B, _mm_set1_epi16(param->matrix[0][2]))); \
Y = _mm_add_epi16(Y, _mm_set1_epi16((param->y_shift)<<PRECISION)); \
Y = _mm_srai_epi16(Y, PRECISION); \
U = _mm_add_epi16(_mm_mullo_epi16(R, _mm_set1_epi16(param->matrix[1][0])), \
_mm_mullo_epi16(G, _mm_set1_epi16(param->matrix[1][1]))); \
U = _mm_add_epi16(U, _mm_mullo_epi16(B, _mm_set1_epi16(param->matrix[1][2]))); \
U = _mm_add_epi16(U, _mm_set1_epi16(128<<PRECISION)); \
U = _mm_srai_epi16(U, PRECISION); \
V = _mm_add_epi16(_mm_mullo_epi16(R, _mm_set1_epi16(param->matrix[2][0])), \
_mm_mullo_epi16(G, _mm_set1_epi16(param->matrix[2][1]))); \
V = _mm_add_epi16(V, _mm_mullo_epi16(B, _mm_set1_epi16(param->matrix[2][2]))); \
V = _mm_add_epi16(V, _mm_set1_epi16(128<<PRECISION)); \
V = _mm_srai_epi16(V, PRECISION);
#define RGB2YUV_32 \
__m128i r1, r2, b1, b2, g1, g2; \
__m128i r_16, g_16, b_16; \
__m128i y1_16, y2_16, u1_16, u2_16, v1_16, v2_16, y, u1, u2, v1, v2, u1_tmp, u2_tmp, v1_tmp, v2_tmp; \
__m128i rgb1 = LOAD_SI128((const __m128i*)(rgb_ptr1)), \
rgb2 = LOAD_SI128((const __m128i*)(rgb_ptr1+16)), \
rgb3 = LOAD_SI128((const __m128i*)(rgb_ptr1+32)), \
rgb4 = LOAD_SI128((const __m128i*)(rgb_ptr2)), \
rgb5 = LOAD_SI128((const __m128i*)(rgb_ptr2+16)), \
rgb6 = LOAD_SI128((const __m128i*)(rgb_ptr2+32)); \
/* unpack rgb24 data to r, g and b data in separate channels*/ \
UNPACK_RGB24_32(rgb1, rgb2, rgb3, rgb4, rgb5, rgb6, r1, r2, g1, g2, b1, b2) \
/* process pixels of first line */ \
r_16 = _mm_unpacklo_epi8(r1, _mm_setzero_si128()); \
g_16 = _mm_unpacklo_epi8(g1, _mm_setzero_si128()); \
b_16 = _mm_unpacklo_epi8(b1, _mm_setzero_si128()); \
RGB2YUV_16(r_16, g_16, b_16, y1_16, u1_16, v1_16) \
r_16 = _mm_unpackhi_epi8(r1, _mm_setzero_si128()); \
g_16 = _mm_unpackhi_epi8(g1, _mm_setzero_si128()); \
b_16 = _mm_unpackhi_epi8(b1, _mm_setzero_si128()); \
RGB2YUV_16(r_16, g_16, b_16, y2_16, u2_16, v2_16) \
y = _mm_packus_epi16(y1_16, y2_16); \
u1 = _mm_packus_epi16(u1_16, u2_16); \
v1 = _mm_packus_epi16(v1_16, v2_16); \
/* save Y values */ \
SAVE_SI128((__m128i*)(y_ptr1), y); \
/* process pixels of second line */ \
r_16 = _mm_unpacklo_epi8(r2, _mm_setzero_si128()); \
g_16 = _mm_unpacklo_epi8(g2, _mm_setzero_si128()); \
b_16 = _mm_unpacklo_epi8(b2, _mm_setzero_si128()); \
RGB2YUV_16(r_16, g_16, b_16, y1_16, u1_16, v1_16) \
r_16 = _mm_unpackhi_epi8(r2, _mm_setzero_si128()); \
g_16 = _mm_unpackhi_epi8(g2, _mm_setzero_si128()); \
b_16 = _mm_unpackhi_epi8(b2, _mm_setzero_si128()); \
RGB2YUV_16(r_16, g_16, b_16, y2_16, u2_16, v2_16) \
y = _mm_packus_epi16(y1_16, y2_16); \
u2 = _mm_packus_epi16(u1_16, u2_16); \
v2 = _mm_packus_epi16(v1_16, v2_16); \
/* save Y values */ \
SAVE_SI128((__m128i*)(y_ptr2), y); \
/* vertical subsampling of u/v values */ \
u1_tmp = _mm_avg_epu8(u1, u2); \
v1_tmp = _mm_avg_epu8(v1, v2); \
/* do the same again with next data */ \
rgb1 = LOAD_SI128((const __m128i*)(rgb_ptr1+48)); \
rgb2 = LOAD_SI128((const __m128i*)(rgb_ptr1+64)); \
rgb3 = LOAD_SI128((const __m128i*)(rgb_ptr1+80)); \
rgb4 = LOAD_SI128((const __m128i*)(rgb_ptr2+48)); \
rgb5 = LOAD_SI128((const __m128i*)(rgb_ptr2+64)); \
rgb6 = LOAD_SI128((const __m128i*)(rgb_ptr2+80)); \
/* unpack rgb24 data to r, g and b data in separate channels*/ \
UNPACK_RGB24_32(rgb1, rgb2, rgb3, rgb4, rgb5, rgb6, r1, r2, g1, g2, b1, b2) \
/* process pixels of first line */ \
r_16 = _mm_unpacklo_epi8(r1, _mm_setzero_si128()); \
g_16 = _mm_unpacklo_epi8(g1, _mm_setzero_si128()); \
b_16 = _mm_unpacklo_epi8(b1, _mm_setzero_si128()); \
RGB2YUV_16(r_16, g_16, b_16, y1_16, u1_16, v1_16) \
r_16 = _mm_unpackhi_epi8(r1, _mm_setzero_si128()); \
g_16 = _mm_unpackhi_epi8(g1, _mm_setzero_si128()); \
b_16 = _mm_unpackhi_epi8(b1, _mm_setzero_si128()); \
RGB2YUV_16(r_16, g_16, b_16, y2_16, u2_16, v2_16) \
y = _mm_packus_epi16(y1_16, y2_16); \
u1 = _mm_packus_epi16(u1_16, u2_16); \
v1 = _mm_packus_epi16(v1_16, v2_16); \
/* save Y values */ \
SAVE_SI128((__m128i*)(y_ptr1+16), y); \
/* process pixels of second line */ \
r_16 = _mm_unpacklo_epi8(r2, _mm_setzero_si128()); \
g_16 = _mm_unpacklo_epi8(g2, _mm_setzero_si128()); \
b_16 = _mm_unpacklo_epi8(b2, _mm_setzero_si128()); \
RGB2YUV_16(r_16, g_16, b_16, y1_16, u1_16, v1_16) \
r_16 = _mm_unpackhi_epi8(r2, _mm_setzero_si128()); \
g_16 = _mm_unpackhi_epi8(g2, _mm_setzero_si128()); \
b_16 = _mm_unpackhi_epi8(b2, _mm_setzero_si128()); \
RGB2YUV_16(r_16, g_16, b_16, y2_16, u2_16, v2_16) \
y = _mm_packus_epi16(y1_16, y2_16); \
u2 = _mm_packus_epi16(u1_16, u2_16); \
v2 = _mm_packus_epi16(v1_16, v2_16); \
/* save Y values */ \
SAVE_SI128((__m128i*)(y_ptr2+16), y); \
/* vertical subsampling of u/v values */ \
u2_tmp = _mm_avg_epu8(u1, u2); \
v2_tmp = _mm_avg_epu8(v1, v2); \
/* horizontal subsampling of u/v values */ \
u1 = _mm_packus_epi16(_mm_srl_epi16(u1_tmp, _mm_cvtsi32_si128(8)), _mm_srl_epi16(u2_tmp, _mm_cvtsi32_si128(8))); \
v1 = _mm_packus_epi16(_mm_srl_epi16(v1_tmp, _mm_cvtsi32_si128(8)), _mm_srl_epi16(v2_tmp, _mm_cvtsi32_si128(8))); \
u2 = _mm_packus_epi16(_mm_and_si128(u1_tmp, _mm_set1_epi16(0xFF)), _mm_and_si128(u2_tmp, _mm_set1_epi16(0xFF))); \
v2 = _mm_packus_epi16(_mm_and_si128(v1_tmp, _mm_set1_epi16(0xFF)), _mm_and_si128(v2_tmp, _mm_set1_epi16(0xFF))); \
u1 = _mm_avg_epu8(u1, u2); \
v1 = _mm_avg_epu8(v1, v2); \
SAVE_SI128((__m128i*)(u_ptr), u1); \
SAVE_SI128((__m128i*)(v_ptr), v1);
void rgb24_yuv420_sse(uint32_t width, uint32_t height,
const uint8_t *RGB, uint32_t RGB_stride,
uint8_t *Y, uint8_t *U, uint8_t *V, uint32_t Y_stride, uint32_t UV_stride,
YCbCrType yuv_type)
{
#define LOAD_SI128 _mm_load_si128
#define SAVE_SI128 _mm_stream_si128
const RGB2YUVParam *const param = &(RGB2YUV[yuv_type]);
uint32_t xpos, ypos;
for(ypos=0; ypos<(height-1); ypos+=2)
{
const uint8_t *rgb_ptr1=RGB+ypos*RGB_stride,
*rgb_ptr2=RGB+(ypos+1)*RGB_stride;
uint8_t *y_ptr1=Y+ypos*Y_stride,
*y_ptr2=Y+(ypos+1)*Y_stride,
*u_ptr=U+(ypos/2)*UV_stride,
*v_ptr=V+(ypos/2)*UV_stride;
for(xpos=0; xpos<(width-31); xpos+=32)
{
RGB2YUV_32
rgb_ptr1+=96;
rgb_ptr2+=96;
y_ptr1+=32;
y_ptr2+=32;
u_ptr+=16;
v_ptr+=16;
}
}
#undef LOAD_SI128
#undef SAVE_SI128
}
void rgb24_yuv420_sseu(uint32_t width, uint32_t height,
const uint8_t *RGB, uint32_t RGB_stride,
uint8_t *Y, uint8_t *U, uint8_t *V, uint32_t Y_stride, uint32_t UV_stride,
YCbCrType yuv_type)
{
#define LOAD_SI128 _mm_loadu_si128
#define SAVE_SI128 _mm_storeu_si128
const RGB2YUVParam *const param = &(RGB2YUV[yuv_type]);
uint32_t xpos, ypos;
for(ypos=0; ypos<(height-1); ypos+=2)
{
const uint8_t *rgb_ptr1=RGB+ypos*RGB_stride,
*rgb_ptr2=RGB+(ypos+1)*RGB_stride;
uint8_t *y_ptr1=Y+ypos*Y_stride,
*y_ptr2=Y+(ypos+1)*Y_stride,
*u_ptr=U+(ypos/2)*UV_stride,
*v_ptr=V+(ypos/2)*UV_stride;
for(xpos=0; xpos<(width-31); xpos+=32)
{
RGB2YUV_32
rgb_ptr1+=96;
rgb_ptr2+=96;
y_ptr1+=32;
y_ptr2+=32;
u_ptr+=16;
v_ptr+=16;
}
}
#undef LOAD_SI128
#undef SAVE_SI128
}
#endif //__SSE2__
#endif /* SDL_HAVE_YUV */
| YifuLiu/AliOS-Things | components/SDL2/src/video/yuv2rgb/yuv_rgb.c | C | apache-2.0 | 25,673 |
// Copyright 2016 Adrien Descamps
// Distributed under BSD 3-Clause License
// Provide optimized functions to convert images from 8bits yuv420 to rgb24 format
// There are a few slightly different variations of the YCbCr color space with different parameters that
// change the conversion matrix.
// The three most common YCbCr color space, defined by BT.601, BT.709 and JPEG standard are implemented here.
// See the respective standards for details
// The matrix values used are derived from http://www.equasys.de/colorconversion.html
// YUV420 is stored as three separate channels, with U and V (Cb and Cr) subsampled by a 2 factor
// For conversion from yuv to rgb, no interpolation is done, and the same UV value are used for 4 rgb pixels. This
// is suboptimal for image quality, but by far the fastest method.
// For all methods, width and height should be even, if not, the last row/column of the result image won't be affected.
// For sse methods, if the width if not divisable by 32, the last (width%32) pixels of each line won't be affected.
#include "SDL_stdinc.h"
/*#include <stdint.h>*/
typedef enum
{
YCBCR_JPEG,
YCBCR_601,
YCBCR_709
} YCbCrType;
// yuv to rgb, standard c implementation
void yuv420_rgb565_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv420_rgb24_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv420_rgba_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv420_bgra_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv420_argb_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv420_abgr_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_rgb565_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_rgb24_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_rgba_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_bgra_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_argb_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_abgr_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_rgb565_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_rgb24_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_rgba_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_bgra_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_argb_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_abgr_std(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
// yuv to rgb, sse implementation
// pointers must be 16 byte aligned, and strides must be divisable by 16
void yuv420_rgb565_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv420_rgb24_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv420_rgba_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv420_bgra_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv420_argb_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv420_abgr_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_rgb565_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_rgb24_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_rgba_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_bgra_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_argb_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_abgr_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_rgb565_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_rgb24_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_rgba_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_bgra_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_argb_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_abgr_sse(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
// yuv to rgb, sse implementation
// pointers do not need to be 16 byte aligned
void yuv420_rgb565_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv420_rgb24_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv420_rgba_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv420_bgra_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv420_argb_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv420_abgr_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_rgb565_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_rgb24_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_rgba_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_bgra_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_argb_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuv422_abgr_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_rgb565_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_rgb24_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_rgba_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_bgra_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_argb_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
void yuvnv12_abgr_sseu(
uint32_t width, uint32_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
uint8_t *rgb, uint32_t rgb_stride,
YCbCrType yuv_type);
// rgb to yuv, standard c implementation
void rgb24_yuv420_std(
uint32_t width, uint32_t height,
const uint8_t *rgb, uint32_t rgb_stride,
uint8_t *y, uint8_t *u, uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
YCbCrType yuv_type);
// rgb to yuv, sse implementation
// pointers must be 16 byte aligned, and strides must be divisible by 16
void rgb24_yuv420_sse(
uint32_t width, uint32_t height,
const uint8_t *rgb, uint32_t rgb_stride,
uint8_t *y, uint8_t *u, uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
YCbCrType yuv_type);
// rgb to yuv, sse implementation
// pointers do not need to be 16 byte aligned
void rgb24_yuv420_sseu(
uint32_t width, uint32_t height,
const uint8_t *rgb, uint32_t rgb_stride,
uint8_t *y, uint8_t *u, uint8_t *v, uint32_t y_stride, uint32_t uv_stride,
YCbCrType yuv_type);
| YifuLiu/AliOS-Things | components/SDL2/src/video/yuv2rgb/yuv_rgb.h | C | apache-2.0 | 13,746 |
// Copyright 2016 Adrien Descamps
// Distributed under BSD 3-Clause License
/* You need to define the following macros before including this file:
SSE_FUNCTION_NAME
STD_FUNCTION_NAME
YUV_FORMAT
RGB_FORMAT
*/
/* You may define the following macro, which affects generated code:
SSE_ALIGNED
*/
#ifdef SSE_ALIGNED
/* Unaligned instructions seem faster, even on aligned data? */
/*
#define LOAD_SI128 _mm_load_si128
#define SAVE_SI128 _mm_stream_si128
*/
#define LOAD_SI128 _mm_loadu_si128
#define SAVE_SI128 _mm_storeu_si128
#else
#define LOAD_SI128 _mm_loadu_si128
#define SAVE_SI128 _mm_storeu_si128
#endif
#define UV2RGB_16(U,V,R1,G1,B1,R2,G2,B2) \
r_tmp = _mm_mullo_epi16(V, _mm_set1_epi16(param->v_r_factor)); \
g_tmp = _mm_add_epi16( \
_mm_mullo_epi16(U, _mm_set1_epi16(param->u_g_factor)), \
_mm_mullo_epi16(V, _mm_set1_epi16(param->v_g_factor))); \
b_tmp = _mm_mullo_epi16(U, _mm_set1_epi16(param->u_b_factor)); \
R1 = _mm_unpacklo_epi16(r_tmp, r_tmp); \
G1 = _mm_unpacklo_epi16(g_tmp, g_tmp); \
B1 = _mm_unpacklo_epi16(b_tmp, b_tmp); \
R2 = _mm_unpackhi_epi16(r_tmp, r_tmp); \
G2 = _mm_unpackhi_epi16(g_tmp, g_tmp); \
B2 = _mm_unpackhi_epi16(b_tmp, b_tmp); \
#define ADD_Y2RGB_16(Y1,Y2,R1,G1,B1,R2,G2,B2) \
Y1 = _mm_mullo_epi16(_mm_sub_epi16(Y1, _mm_set1_epi16(param->y_shift)), _mm_set1_epi16(param->y_factor)); \
Y2 = _mm_mullo_epi16(_mm_sub_epi16(Y2, _mm_set1_epi16(param->y_shift)), _mm_set1_epi16(param->y_factor)); \
\
R1 = _mm_srai_epi16(_mm_add_epi16(R1, Y1), PRECISION); \
G1 = _mm_srai_epi16(_mm_add_epi16(G1, Y1), PRECISION); \
B1 = _mm_srai_epi16(_mm_add_epi16(B1, Y1), PRECISION); \
R2 = _mm_srai_epi16(_mm_add_epi16(R2, Y2), PRECISION); \
G2 = _mm_srai_epi16(_mm_add_epi16(G2, Y2), PRECISION); \
B2 = _mm_srai_epi16(_mm_add_epi16(B2, Y2), PRECISION); \
#define PACK_RGB565_32(R1, R2, G1, G2, B1, B2, RGB1, RGB2, RGB3, RGB4) \
{ \
__m128i red_mask, tmp1, tmp2, tmp3, tmp4; \
\
red_mask = _mm_set1_epi16((short)0xF800); \
RGB1 = _mm_and_si128(_mm_unpacklo_epi8(_mm_setzero_si128(), R1), red_mask); \
RGB2 = _mm_and_si128(_mm_unpackhi_epi8(_mm_setzero_si128(), R1), red_mask); \
RGB3 = _mm_and_si128(_mm_unpacklo_epi8(_mm_setzero_si128(), R2), red_mask); \
RGB4 = _mm_and_si128(_mm_unpackhi_epi8(_mm_setzero_si128(), R2), red_mask); \
tmp1 = _mm_slli_epi16(_mm_srli_epi16(_mm_unpacklo_epi8(G1, _mm_setzero_si128()), 2), 5); \
tmp2 = _mm_slli_epi16(_mm_srli_epi16(_mm_unpackhi_epi8(G1, _mm_setzero_si128()), 2), 5); \
tmp3 = _mm_slli_epi16(_mm_srli_epi16(_mm_unpacklo_epi8(G2, _mm_setzero_si128()), 2), 5); \
tmp4 = _mm_slli_epi16(_mm_srli_epi16(_mm_unpackhi_epi8(G2, _mm_setzero_si128()), 2), 5); \
RGB1 = _mm_or_si128(RGB1, tmp1); \
RGB2 = _mm_or_si128(RGB2, tmp2); \
RGB3 = _mm_or_si128(RGB3, tmp3); \
RGB4 = _mm_or_si128(RGB4, tmp4); \
tmp1 = _mm_srli_epi16(_mm_unpacklo_epi8(B1, _mm_setzero_si128()), 3); \
tmp2 = _mm_srli_epi16(_mm_unpackhi_epi8(B1, _mm_setzero_si128()), 3); \
tmp3 = _mm_srli_epi16(_mm_unpacklo_epi8(B2, _mm_setzero_si128()), 3); \
tmp4 = _mm_srli_epi16(_mm_unpackhi_epi8(B2, _mm_setzero_si128()), 3); \
RGB1 = _mm_or_si128(RGB1, tmp1); \
RGB2 = _mm_or_si128(RGB2, tmp2); \
RGB3 = _mm_or_si128(RGB3, tmp3); \
RGB4 = _mm_or_si128(RGB4, tmp4); \
}
#define PACK_RGB24_32_STEP1(R1, R2, G1, G2, B1, B2, RGB1, RGB2, RGB3, RGB4, RGB5, RGB6) \
RGB1 = _mm_packus_epi16(_mm_and_si128(R1,_mm_set1_epi16(0xFF)), _mm_and_si128(R2,_mm_set1_epi16(0xFF))); \
RGB2 = _mm_packus_epi16(_mm_and_si128(G1,_mm_set1_epi16(0xFF)), _mm_and_si128(G2,_mm_set1_epi16(0xFF))); \
RGB3 = _mm_packus_epi16(_mm_and_si128(B1,_mm_set1_epi16(0xFF)), _mm_and_si128(B2,_mm_set1_epi16(0xFF))); \
RGB4 = _mm_packus_epi16(_mm_srli_epi16(R1,8), _mm_srli_epi16(R2,8)); \
RGB5 = _mm_packus_epi16(_mm_srli_epi16(G1,8), _mm_srli_epi16(G2,8)); \
RGB6 = _mm_packus_epi16(_mm_srli_epi16(B1,8), _mm_srli_epi16(B2,8)); \
#define PACK_RGB24_32_STEP2(R1, R2, G1, G2, B1, B2, RGB1, RGB2, RGB3, RGB4, RGB5, RGB6) \
R1 = _mm_packus_epi16(_mm_and_si128(RGB1,_mm_set1_epi16(0xFF)), _mm_and_si128(RGB2,_mm_set1_epi16(0xFF))); \
R2 = _mm_packus_epi16(_mm_and_si128(RGB3,_mm_set1_epi16(0xFF)), _mm_and_si128(RGB4,_mm_set1_epi16(0xFF))); \
G1 = _mm_packus_epi16(_mm_and_si128(RGB5,_mm_set1_epi16(0xFF)), _mm_and_si128(RGB6,_mm_set1_epi16(0xFF))); \
G2 = _mm_packus_epi16(_mm_srli_epi16(RGB1,8), _mm_srli_epi16(RGB2,8)); \
B1 = _mm_packus_epi16(_mm_srli_epi16(RGB3,8), _mm_srli_epi16(RGB4,8)); \
B2 = _mm_packus_epi16(_mm_srli_epi16(RGB5,8), _mm_srli_epi16(RGB6,8)); \
#define PACK_RGB24_32(R1, R2, G1, G2, B1, B2, RGB1, RGB2, RGB3, RGB4, RGB5, RGB6) \
PACK_RGB24_32_STEP1(R1, R2, G1, G2, B1, B2, RGB1, RGB2, RGB3, RGB4, RGB5, RGB6) \
PACK_RGB24_32_STEP2(R1, R2, G1, G2, B1, B2, RGB1, RGB2, RGB3, RGB4, RGB5, RGB6) \
PACK_RGB24_32_STEP1(R1, R2, G1, G2, B1, B2, RGB1, RGB2, RGB3, RGB4, RGB5, RGB6) \
PACK_RGB24_32_STEP2(R1, R2, G1, G2, B1, B2, RGB1, RGB2, RGB3, RGB4, RGB5, RGB6) \
PACK_RGB24_32_STEP1(R1, R2, G1, G2, B1, B2, RGB1, RGB2, RGB3, RGB4, RGB5, RGB6) \
#define PACK_RGBA_32(R1, R2, G1, G2, B1, B2, A1, A2, RGB1, RGB2, RGB3, RGB4, RGB5, RGB6, RGB7, RGB8) \
{ \
__m128i lo_ab, hi_ab, lo_gr, hi_gr; \
\
lo_ab = _mm_unpacklo_epi8( A1, B1 ); \
hi_ab = _mm_unpackhi_epi8( A1, B1 ); \
lo_gr = _mm_unpacklo_epi8( G1, R1 ); \
hi_gr = _mm_unpackhi_epi8( G1, R1 ); \
RGB1 = _mm_unpacklo_epi16( lo_ab, lo_gr ); \
RGB2 = _mm_unpackhi_epi16( lo_ab, lo_gr ); \
RGB3 = _mm_unpacklo_epi16( hi_ab, hi_gr ); \
RGB4 = _mm_unpackhi_epi16( hi_ab, hi_gr ); \
\
lo_ab = _mm_unpacklo_epi8( A2, B2 ); \
hi_ab = _mm_unpackhi_epi8( A2, B2 ); \
lo_gr = _mm_unpacklo_epi8( G2, R2 ); \
hi_gr = _mm_unpackhi_epi8( G2, R2 ); \
RGB5 = _mm_unpacklo_epi16( lo_ab, lo_gr ); \
RGB6 = _mm_unpackhi_epi16( lo_ab, lo_gr ); \
RGB7 = _mm_unpacklo_epi16( hi_ab, hi_gr ); \
RGB8 = _mm_unpackhi_epi16( hi_ab, hi_gr ); \
}
#if RGB_FORMAT == RGB_FORMAT_RGB565
#define PACK_PIXEL \
__m128i rgb_1, rgb_2, rgb_3, rgb_4, rgb_5, rgb_6, rgb_7, rgb_8; \
\
PACK_RGB565_32(r_8_11, r_8_12, g_8_11, g_8_12, b_8_11, b_8_12, rgb_1, rgb_2, rgb_3, rgb_4) \
\
PACK_RGB565_32(r_8_21, r_8_22, g_8_21, g_8_22, b_8_21, b_8_22, rgb_5, rgb_6, rgb_7, rgb_8) \
#elif RGB_FORMAT == RGB_FORMAT_RGB24
#define PACK_PIXEL \
__m128i rgb_1, rgb_2, rgb_3, rgb_4, rgb_5, rgb_6; \
__m128i rgb_7, rgb_8, rgb_9, rgb_10, rgb_11, rgb_12; \
\
PACK_RGB24_32(r_8_11, r_8_12, g_8_11, g_8_12, b_8_11, b_8_12, rgb_1, rgb_2, rgb_3, rgb_4, rgb_5, rgb_6) \
\
PACK_RGB24_32(r_8_21, r_8_22, g_8_21, g_8_22, b_8_21, b_8_22, rgb_7, rgb_8, rgb_9, rgb_10, rgb_11, rgb_12) \
#elif RGB_FORMAT == RGB_FORMAT_RGBA
#define PACK_PIXEL \
__m128i rgb_1, rgb_2, rgb_3, rgb_4, rgb_5, rgb_6, rgb_7, rgb_8; \
__m128i rgb_9, rgb_10, rgb_11, rgb_12, rgb_13, rgb_14, rgb_15, rgb_16; \
__m128i a = _mm_set1_epi8((char)0xFF); \
\
PACK_RGBA_32(r_8_11, r_8_12, g_8_11, g_8_12, b_8_11, b_8_12, a, a, rgb_1, rgb_2, rgb_3, rgb_4, rgb_5, rgb_6, rgb_7, rgb_8) \
\
PACK_RGBA_32(r_8_21, r_8_22, g_8_21, g_8_22, b_8_21, b_8_22, a, a, rgb_9, rgb_10, rgb_11, rgb_12, rgb_13, rgb_14, rgb_15, rgb_16) \
#elif RGB_FORMAT == RGB_FORMAT_BGRA
#define PACK_PIXEL \
__m128i rgb_1, rgb_2, rgb_3, rgb_4, rgb_5, rgb_6, rgb_7, rgb_8; \
__m128i rgb_9, rgb_10, rgb_11, rgb_12, rgb_13, rgb_14, rgb_15, rgb_16; \
__m128i a = _mm_set1_epi8((char)0xFF); \
\
PACK_RGBA_32(b_8_11, b_8_12, g_8_11, g_8_12, r_8_11, r_8_12, a, a, rgb_1, rgb_2, rgb_3, rgb_4, rgb_5, rgb_6, rgb_7, rgb_8) \
\
PACK_RGBA_32(b_8_21, b_8_22, g_8_21, g_8_22, r_8_21, r_8_22, a, a, rgb_9, rgb_10, rgb_11, rgb_12, rgb_13, rgb_14, rgb_15, rgb_16) \
#elif RGB_FORMAT == RGB_FORMAT_ARGB
#define PACK_PIXEL \
__m128i rgb_1, rgb_2, rgb_3, rgb_4, rgb_5, rgb_6, rgb_7, rgb_8; \
__m128i rgb_9, rgb_10, rgb_11, rgb_12, rgb_13, rgb_14, rgb_15, rgb_16; \
__m128i a = _mm_set1_epi8((char)0xFF); \
\
PACK_RGBA_32(a, a, r_8_11, r_8_12, g_8_11, g_8_12, b_8_11, b_8_12, rgb_1, rgb_2, rgb_3, rgb_4, rgb_5, rgb_6, rgb_7, rgb_8) \
\
PACK_RGBA_32(a, a, r_8_21, r_8_22, g_8_21, g_8_22, b_8_21, b_8_22, rgb_9, rgb_10, rgb_11, rgb_12, rgb_13, rgb_14, rgb_15, rgb_16) \
#elif RGB_FORMAT == RGB_FORMAT_ABGR
#define PACK_PIXEL \
__m128i rgb_1, rgb_2, rgb_3, rgb_4, rgb_5, rgb_6, rgb_7, rgb_8; \
__m128i rgb_9, rgb_10, rgb_11, rgb_12, rgb_13, rgb_14, rgb_15, rgb_16; \
__m128i a = _mm_set1_epi8((char)0xFF); \
\
PACK_RGBA_32(a, a, b_8_11, b_8_12, g_8_11, g_8_12, r_8_11, r_8_12, rgb_1, rgb_2, rgb_3, rgb_4, rgb_5, rgb_6, rgb_7, rgb_8) \
\
PACK_RGBA_32(a, a, b_8_21, b_8_22, g_8_21, g_8_22, r_8_21, r_8_22, rgb_9, rgb_10, rgb_11, rgb_12, rgb_13, rgb_14, rgb_15, rgb_16) \
#else
#error PACK_PIXEL unimplemented
#endif
#if RGB_FORMAT == RGB_FORMAT_RGB565
#define SAVE_LINE1 \
SAVE_SI128((__m128i*)(rgb_ptr1), rgb_1); \
SAVE_SI128((__m128i*)(rgb_ptr1+16), rgb_2); \
SAVE_SI128((__m128i*)(rgb_ptr1+32), rgb_3); \
SAVE_SI128((__m128i*)(rgb_ptr1+48), rgb_4); \
#define SAVE_LINE2 \
SAVE_SI128((__m128i*)(rgb_ptr2), rgb_5); \
SAVE_SI128((__m128i*)(rgb_ptr2+16), rgb_6); \
SAVE_SI128((__m128i*)(rgb_ptr2+32), rgb_7); \
SAVE_SI128((__m128i*)(rgb_ptr2+48), rgb_8); \
#elif RGB_FORMAT == RGB_FORMAT_RGB24
#define SAVE_LINE1 \
SAVE_SI128((__m128i*)(rgb_ptr1), rgb_1); \
SAVE_SI128((__m128i*)(rgb_ptr1+16), rgb_2); \
SAVE_SI128((__m128i*)(rgb_ptr1+32), rgb_3); \
SAVE_SI128((__m128i*)(rgb_ptr1+48), rgb_4); \
SAVE_SI128((__m128i*)(rgb_ptr1+64), rgb_5); \
SAVE_SI128((__m128i*)(rgb_ptr1+80), rgb_6); \
#define SAVE_LINE2 \
SAVE_SI128((__m128i*)(rgb_ptr2), rgb_7); \
SAVE_SI128((__m128i*)(rgb_ptr2+16), rgb_8); \
SAVE_SI128((__m128i*)(rgb_ptr2+32), rgb_9); \
SAVE_SI128((__m128i*)(rgb_ptr2+48), rgb_10); \
SAVE_SI128((__m128i*)(rgb_ptr2+64), rgb_11); \
SAVE_SI128((__m128i*)(rgb_ptr2+80), rgb_12); \
#elif RGB_FORMAT == RGB_FORMAT_RGBA || RGB_FORMAT == RGB_FORMAT_BGRA || \
RGB_FORMAT == RGB_FORMAT_ARGB || RGB_FORMAT == RGB_FORMAT_ABGR
#define SAVE_LINE1 \
SAVE_SI128((__m128i*)(rgb_ptr1), rgb_1); \
SAVE_SI128((__m128i*)(rgb_ptr1+16), rgb_2); \
SAVE_SI128((__m128i*)(rgb_ptr1+32), rgb_3); \
SAVE_SI128((__m128i*)(rgb_ptr1+48), rgb_4); \
SAVE_SI128((__m128i*)(rgb_ptr1+64), rgb_5); \
SAVE_SI128((__m128i*)(rgb_ptr1+80), rgb_6); \
SAVE_SI128((__m128i*)(rgb_ptr1+96), rgb_7); \
SAVE_SI128((__m128i*)(rgb_ptr1+112), rgb_8); \
#define SAVE_LINE2 \
SAVE_SI128((__m128i*)(rgb_ptr2), rgb_9); \
SAVE_SI128((__m128i*)(rgb_ptr2+16), rgb_10); \
SAVE_SI128((__m128i*)(rgb_ptr2+32), rgb_11); \
SAVE_SI128((__m128i*)(rgb_ptr2+48), rgb_12); \
SAVE_SI128((__m128i*)(rgb_ptr2+64), rgb_13); \
SAVE_SI128((__m128i*)(rgb_ptr2+80), rgb_14); \
SAVE_SI128((__m128i*)(rgb_ptr2+96), rgb_15); \
SAVE_SI128((__m128i*)(rgb_ptr2+112), rgb_16); \
#else
#error SAVE_LINE unimplemented
#endif
#if YUV_FORMAT == YUV_FORMAT_420
#define READ_Y(y_ptr) \
y = LOAD_SI128((const __m128i*)(y_ptr)); \
#define READ_UV \
u = LOAD_SI128((const __m128i*)(u_ptr)); \
v = LOAD_SI128((const __m128i*)(v_ptr)); \
#elif YUV_FORMAT == YUV_FORMAT_422
#define READ_Y(y_ptr) \
{ \
__m128i y1, y2; \
y1 = _mm_srli_epi16(_mm_slli_epi16(LOAD_SI128((const __m128i*)(y_ptr)), 8), 8); \
y2 = _mm_srli_epi16(_mm_slli_epi16(LOAD_SI128((const __m128i*)(y_ptr+16)), 8), 8); \
y = _mm_packus_epi16(y1, y2); \
}
#define READ_UV \
{ \
__m128i u1, u2, u3, u4, v1, v2, v3, v4; \
u1 = _mm_srli_epi32(_mm_slli_epi32(LOAD_SI128((const __m128i*)(u_ptr)), 24), 24); \
u2 = _mm_srli_epi32(_mm_slli_epi32(LOAD_SI128((const __m128i*)(u_ptr+16)), 24), 24); \
u3 = _mm_srli_epi32(_mm_slli_epi32(LOAD_SI128((const __m128i*)(u_ptr+32)), 24), 24); \
u4 = _mm_srli_epi32(_mm_slli_epi32(LOAD_SI128((const __m128i*)(u_ptr+48)), 24), 24); \
u = _mm_packus_epi16(_mm_packs_epi32(u1, u2), _mm_packs_epi32(u3, u4)); \
v1 = _mm_srli_epi32(_mm_slli_epi32(LOAD_SI128((const __m128i*)(v_ptr)), 24), 24); \
v2 = _mm_srli_epi32(_mm_slli_epi32(LOAD_SI128((const __m128i*)(v_ptr+16)), 24), 24); \
v3 = _mm_srli_epi32(_mm_slli_epi32(LOAD_SI128((const __m128i*)(v_ptr+32)), 24), 24); \
v4 = _mm_srli_epi32(_mm_slli_epi32(LOAD_SI128((const __m128i*)(v_ptr+48)), 24), 24); \
v = _mm_packus_epi16(_mm_packs_epi32(v1, v2), _mm_packs_epi32(v3, v4)); \
}
#elif YUV_FORMAT == YUV_FORMAT_NV12
#define READ_Y(y_ptr) \
y = LOAD_SI128((const __m128i*)(y_ptr)); \
#define READ_UV \
{ \
__m128i u1, u2, v1, v2; \
u1 = _mm_srli_epi16(_mm_slli_epi16(LOAD_SI128((const __m128i*)(u_ptr)), 8), 8); \
u2 = _mm_srli_epi16(_mm_slli_epi16(LOAD_SI128((const __m128i*)(u_ptr+16)), 8), 8); \
u = _mm_packus_epi16(u1, u2); \
v1 = _mm_srli_epi16(_mm_slli_epi16(LOAD_SI128((const __m128i*)(v_ptr)), 8), 8); \
v2 = _mm_srli_epi16(_mm_slli_epi16(LOAD_SI128((const __m128i*)(v_ptr+16)), 8), 8); \
v = _mm_packus_epi16(v1, v2); \
}
#else
#error READ_UV unimplemented
#endif
#define YUV2RGB_32 \
__m128i r_tmp, g_tmp, b_tmp; \
__m128i r_16_1, g_16_1, b_16_1, r_16_2, g_16_2, b_16_2; \
__m128i r_uv_16_1, g_uv_16_1, b_uv_16_1, r_uv_16_2, g_uv_16_2, b_uv_16_2; \
__m128i y_16_1, y_16_2; \
__m128i y, u, v, u_16, v_16; \
__m128i r_8_11, g_8_11, b_8_11, r_8_21, g_8_21, b_8_21; \
__m128i r_8_12, g_8_12, b_8_12, r_8_22, g_8_22, b_8_22; \
\
READ_UV \
\
/* process first 16 pixels of first line */\
u_16 = _mm_unpacklo_epi8(u, _mm_setzero_si128()); \
v_16 = _mm_unpacklo_epi8(v, _mm_setzero_si128()); \
u_16 = _mm_add_epi16(u_16, _mm_set1_epi16(-128)); \
v_16 = _mm_add_epi16(v_16, _mm_set1_epi16(-128)); \
\
UV2RGB_16(u_16, v_16, r_16_1, g_16_1, b_16_1, r_16_2, g_16_2, b_16_2) \
r_uv_16_1=r_16_1; g_uv_16_1=g_16_1; b_uv_16_1=b_16_1; \
r_uv_16_2=r_16_2; g_uv_16_2=g_16_2; b_uv_16_2=b_16_2; \
\
READ_Y(y_ptr1) \
y_16_1 = _mm_unpacklo_epi8(y, _mm_setzero_si128()); \
y_16_2 = _mm_unpackhi_epi8(y, _mm_setzero_si128()); \
\
ADD_Y2RGB_16(y_16_1, y_16_2, r_16_1, g_16_1, b_16_1, r_16_2, g_16_2, b_16_2) \
\
r_8_11 = _mm_packus_epi16(r_16_1, r_16_2); \
g_8_11 = _mm_packus_epi16(g_16_1, g_16_2); \
b_8_11 = _mm_packus_epi16(b_16_1, b_16_2); \
\
/* process first 16 pixels of second line */\
r_16_1=r_uv_16_1; g_16_1=g_uv_16_1; b_16_1=b_uv_16_1; \
r_16_2=r_uv_16_2; g_16_2=g_uv_16_2; b_16_2=b_uv_16_2; \
\
READ_Y(y_ptr2) \
y_16_1 = _mm_unpacklo_epi8(y, _mm_setzero_si128()); \
y_16_2 = _mm_unpackhi_epi8(y, _mm_setzero_si128()); \
\
ADD_Y2RGB_16(y_16_1, y_16_2, r_16_1, g_16_1, b_16_1, r_16_2, g_16_2, b_16_2) \
\
r_8_21 = _mm_packus_epi16(r_16_1, r_16_2); \
g_8_21 = _mm_packus_epi16(g_16_1, g_16_2); \
b_8_21 = _mm_packus_epi16(b_16_1, b_16_2); \
\
/* process last 16 pixels of first line */\
u_16 = _mm_unpackhi_epi8(u, _mm_setzero_si128()); \
v_16 = _mm_unpackhi_epi8(v, _mm_setzero_si128()); \
u_16 = _mm_add_epi16(u_16, _mm_set1_epi16(-128)); \
v_16 = _mm_add_epi16(v_16, _mm_set1_epi16(-128)); \
\
UV2RGB_16(u_16, v_16, r_16_1, g_16_1, b_16_1, r_16_2, g_16_2, b_16_2) \
r_uv_16_1=r_16_1; g_uv_16_1=g_16_1; b_uv_16_1=b_16_1; \
r_uv_16_2=r_16_2; g_uv_16_2=g_16_2; b_uv_16_2=b_16_2; \
\
READ_Y(y_ptr1+16*y_pixel_stride) \
y_16_1 = _mm_unpacklo_epi8(y, _mm_setzero_si128()); \
y_16_2 = _mm_unpackhi_epi8(y, _mm_setzero_si128()); \
\
ADD_Y2RGB_16(y_16_1, y_16_2, r_16_1, g_16_1, b_16_1, r_16_2, g_16_2, b_16_2) \
\
r_8_12 = _mm_packus_epi16(r_16_1, r_16_2); \
g_8_12 = _mm_packus_epi16(g_16_1, g_16_2); \
b_8_12 = _mm_packus_epi16(b_16_1, b_16_2); \
\
/* process last 16 pixels of second line */\
r_16_1=r_uv_16_1; g_16_1=g_uv_16_1; b_16_1=b_uv_16_1; \
r_16_2=r_uv_16_2; g_16_2=g_uv_16_2; b_16_2=b_uv_16_2; \
\
READ_Y(y_ptr2+16*y_pixel_stride) \
y_16_1 = _mm_unpacklo_epi8(y, _mm_setzero_si128()); \
y_16_2 = _mm_unpackhi_epi8(y, _mm_setzero_si128()); \
\
ADD_Y2RGB_16(y_16_1, y_16_2, r_16_1, g_16_1, b_16_1, r_16_2, g_16_2, b_16_2) \
\
r_8_22 = _mm_packus_epi16(r_16_1, r_16_2); \
g_8_22 = _mm_packus_epi16(g_16_1, g_16_2); \
b_8_22 = _mm_packus_epi16(b_16_1, b_16_2); \
\
void SSE_FUNCTION_NAME(uint32_t width, uint32_t height,
const uint8_t *Y, const uint8_t *U, const uint8_t *V, uint32_t Y_stride, uint32_t UV_stride,
uint8_t *RGB, uint32_t RGB_stride,
YCbCrType yuv_type)
{
const YUV2RGBParam *const param = &(YUV2RGB[yuv_type]);
#if YUV_FORMAT == YUV_FORMAT_420
const int y_pixel_stride = 1;
const int uv_pixel_stride = 1;
const int uv_x_sample_interval = 2;
const int uv_y_sample_interval = 2;
#elif YUV_FORMAT == YUV_FORMAT_422
const int y_pixel_stride = 2;
const int uv_pixel_stride = 4;
const int uv_x_sample_interval = 2;
const int uv_y_sample_interval = 1;
#elif YUV_FORMAT == YUV_FORMAT_NV12
const int y_pixel_stride = 1;
const int uv_pixel_stride = 2;
const int uv_x_sample_interval = 2;
const int uv_y_sample_interval = 2;
#endif
#if RGB_FORMAT == RGB_FORMAT_RGB565
const int rgb_pixel_stride = 2;
#elif RGB_FORMAT == RGB_FORMAT_RGB24
const int rgb_pixel_stride = 3;
#elif RGB_FORMAT == RGB_FORMAT_RGBA || RGB_FORMAT == RGB_FORMAT_BGRA || \
RGB_FORMAT == RGB_FORMAT_ARGB || RGB_FORMAT == RGB_FORMAT_ABGR
const int rgb_pixel_stride = 4;
#else
#error Unknown RGB pixel size
#endif
if (width >= 32) {
uint32_t xpos, ypos;
for(ypos=0; ypos<(height-(uv_y_sample_interval-1)); ypos+=uv_y_sample_interval)
{
const uint8_t *y_ptr1=Y+ypos*Y_stride,
*y_ptr2=Y+(ypos+1)*Y_stride,
*u_ptr=U+(ypos/uv_y_sample_interval)*UV_stride,
*v_ptr=V+(ypos/uv_y_sample_interval)*UV_stride;
uint8_t *rgb_ptr1=RGB+ypos*RGB_stride,
*rgb_ptr2=RGB+(ypos+1)*RGB_stride;
for(xpos=0; xpos<(width-31); xpos+=32)
{
YUV2RGB_32
{
PACK_PIXEL
SAVE_LINE1
if (uv_y_sample_interval > 1)
{
SAVE_LINE2
}
}
y_ptr1+=32*y_pixel_stride;
y_ptr2+=32*y_pixel_stride;
u_ptr+=32*uv_pixel_stride/uv_x_sample_interval;
v_ptr+=32*uv_pixel_stride/uv_x_sample_interval;
rgb_ptr1+=32*rgb_pixel_stride;
rgb_ptr2+=32*rgb_pixel_stride;
}
}
/* Catch the last line, if needed */
if (uv_y_sample_interval == 2 && ypos == (height-1))
{
const uint8_t *y_ptr=Y+ypos*Y_stride,
*u_ptr=U+(ypos/uv_y_sample_interval)*UV_stride,
*v_ptr=V+(ypos/uv_y_sample_interval)*UV_stride;
uint8_t *rgb_ptr=RGB+ypos*RGB_stride;
STD_FUNCTION_NAME(width, 1, y_ptr, u_ptr, v_ptr, Y_stride, UV_stride, rgb_ptr, RGB_stride, yuv_type);
}
}
/* Catch the right column, if needed */
{
int converted = (width & ~31);
if (converted != width)
{
const uint8_t *y_ptr=Y+converted*y_pixel_stride,
*u_ptr=U+converted*uv_pixel_stride/uv_x_sample_interval,
*v_ptr=V+converted*uv_pixel_stride/uv_x_sample_interval;
uint8_t *rgb_ptr=RGB+converted*rgb_pixel_stride;
STD_FUNCTION_NAME(width-converted, height, y_ptr, u_ptr, v_ptr, Y_stride, UV_stride, rgb_ptr, RGB_stride, yuv_type);
}
}
}
#undef SSE_FUNCTION_NAME
#undef STD_FUNCTION_NAME
#undef YUV_FORMAT
#undef RGB_FORMAT
#undef SSE_ALIGNED
#undef LOAD_SI128
#undef SAVE_SI128
#undef UV2RGB_16
#undef ADD_Y2RGB_16
#undef PACK_RGB24_32_STEP1
#undef PACK_RGB24_32_STEP2
#undef PACK_RGB24_32
#undef PACK_RGBA_32
#undef PACK_PIXEL
#undef SAVE_LINE1
#undef SAVE_LINE2
#undef READ_Y
#undef READ_UV
#undef YUV2RGB_32
| YifuLiu/AliOS-Things | components/SDL2/src/video/yuv2rgb/yuv_rgb_sse_func.h | C | apache-2.0 | 19,011 |
// Copyright 2016 Adrien Descamps
// Distributed under BSD 3-Clause License
/* You need to define the following macros before including this file:
STD_FUNCTION_NAME
YUV_FORMAT
RGB_FORMAT
*/
#if RGB_FORMAT == RGB_FORMAT_RGB565
#define PACK_PIXEL(rgb_ptr) \
*(Uint16 *)rgb_ptr = \
((((Uint16)clampU8(y_tmp+r_tmp)) << 8 ) & 0xF800) | \
((((Uint16)clampU8(y_tmp+g_tmp)) << 3) & 0x07E0) | \
(((Uint16)clampU8(y_tmp+b_tmp)) >> 3); \
rgb_ptr += 2; \
#elif RGB_FORMAT == RGB_FORMAT_RGB24
#define PACK_PIXEL(rgb_ptr) \
rgb_ptr[0] = clampU8(y_tmp+r_tmp); \
rgb_ptr[1] = clampU8(y_tmp+g_tmp); \
rgb_ptr[2] = clampU8(y_tmp+b_tmp); \
rgb_ptr += 3; \
#elif RGB_FORMAT == RGB_FORMAT_RGBA
#define PACK_PIXEL(rgb_ptr) \
*(Uint32 *)rgb_ptr = \
(((Uint32)clampU8(y_tmp+r_tmp)) << 24) | \
(((Uint32)clampU8(y_tmp+g_tmp)) << 16) | \
(((Uint32)clampU8(y_tmp+b_tmp)) << 8) | \
0x000000FF; \
rgb_ptr += 4; \
#elif RGB_FORMAT == RGB_FORMAT_BGRA
#define PACK_PIXEL(rgb_ptr) \
*(Uint32 *)rgb_ptr = \
(((Uint32)clampU8(y_tmp+b_tmp)) << 24) | \
(((Uint32)clampU8(y_tmp+g_tmp)) << 16) | \
(((Uint32)clampU8(y_tmp+r_tmp)) << 8) | \
0x000000FF; \
rgb_ptr += 4; \
#elif RGB_FORMAT == RGB_FORMAT_ARGB
#define PACK_PIXEL(rgb_ptr) \
*(Uint32 *)rgb_ptr = \
0xFF000000 | \
(((Uint32)clampU8(y_tmp+r_tmp)) << 16) | \
(((Uint32)clampU8(y_tmp+g_tmp)) << 8) | \
(((Uint32)clampU8(y_tmp+b_tmp)) << 0); \
rgb_ptr += 4; \
#elif RGB_FORMAT == RGB_FORMAT_ABGR
#define PACK_PIXEL(rgb_ptr) \
*(Uint32 *)rgb_ptr = \
0xFF000000 | \
(((Uint32)clampU8(y_tmp+b_tmp)) << 16) | \
(((Uint32)clampU8(y_tmp+g_tmp)) << 8) | \
(((Uint32)clampU8(y_tmp+r_tmp)) << 0); \
rgb_ptr += 4; \
#else
#error PACK_PIXEL unimplemented
#endif
void STD_FUNCTION_NAME(
uint32_t width, uint32_t height,
const uint8_t *Y, const uint8_t *U, const uint8_t *V, uint32_t Y_stride, uint32_t UV_stride,
uint8_t *RGB, uint32_t RGB_stride,
YCbCrType yuv_type)
{
const YUV2RGBParam *const param = &(YUV2RGB[yuv_type]);
#if YUV_FORMAT == YUV_FORMAT_420
#define y_pixel_stride 1
#define uv_pixel_stride 1
#define uv_x_sample_interval 2
#define uv_y_sample_interval 2
#elif YUV_FORMAT == YUV_FORMAT_422
#define y_pixel_stride 2
#define uv_pixel_stride 4
#define uv_x_sample_interval 2
#define uv_y_sample_interval 1
#elif YUV_FORMAT == YUV_FORMAT_NV12
#define y_pixel_stride 1
#define uv_pixel_stride 2
#define uv_x_sample_interval 2
#define uv_y_sample_interval 2
#endif
uint32_t x, y;
for(y=0; y<(height-(uv_y_sample_interval-1)); y+=uv_y_sample_interval)
{
const uint8_t *y_ptr1=Y+y*Y_stride,
*y_ptr2=Y+(y+1)*Y_stride,
*u_ptr=U+(y/uv_y_sample_interval)*UV_stride,
*v_ptr=V+(y/uv_y_sample_interval)*UV_stride;
uint8_t *rgb_ptr1=RGB+y*RGB_stride;
#if uv_y_sample_interval > 1
uint8_t *rgb_ptr2=RGB+(y+1)*RGB_stride;
#endif
for(x=0; x<(width-(uv_x_sample_interval-1)); x+=uv_x_sample_interval)
{
// Compute U and V contributions, common to the four pixels
int32_t u_tmp = ((*u_ptr)-128);
int32_t v_tmp = ((*v_ptr)-128);
int32_t r_tmp = (v_tmp*param->v_r_factor);
int32_t g_tmp = (u_tmp*param->u_g_factor + v_tmp*param->v_g_factor);
int32_t b_tmp = (u_tmp*param->u_b_factor);
// Compute the Y contribution for each pixel
int32_t y_tmp = ((y_ptr1[0]-param->y_shift)*param->y_factor);
PACK_PIXEL(rgb_ptr1);
y_tmp = ((y_ptr1[y_pixel_stride]-param->y_shift)*param->y_factor);
PACK_PIXEL(rgb_ptr1);
#if uv_y_sample_interval > 1
y_tmp = ((y_ptr2[0]-param->y_shift)*param->y_factor);
PACK_PIXEL(rgb_ptr2);
y_tmp = ((y_ptr2[y_pixel_stride]-param->y_shift)*param->y_factor);
PACK_PIXEL(rgb_ptr2);
#endif
y_ptr1+=2*y_pixel_stride;
y_ptr2+=2*y_pixel_stride;
u_ptr+=2*uv_pixel_stride/uv_x_sample_interval;
v_ptr+=2*uv_pixel_stride/uv_x_sample_interval;
}
/* Catch the last pixel, if needed */
if (uv_x_sample_interval == 2 && x == (width-1))
{
// Compute U and V contributions, common to the four pixels
int32_t u_tmp = ((*u_ptr)-128);
int32_t v_tmp = ((*v_ptr)-128);
int32_t r_tmp = (v_tmp*param->v_r_factor);
int32_t g_tmp = (u_tmp*param->u_g_factor + v_tmp*param->v_g_factor);
int32_t b_tmp = (u_tmp*param->u_b_factor);
// Compute the Y contribution for each pixel
int32_t y_tmp = ((y_ptr1[0]-param->y_shift)*param->y_factor);
PACK_PIXEL(rgb_ptr1);
#if uv_y_sample_interval > 1
y_tmp = ((y_ptr2[0]-param->y_shift)*param->y_factor);
PACK_PIXEL(rgb_ptr2);
#endif
}
}
/* Catch the last line, if needed */
if (uv_y_sample_interval == 2 && y == (height-1))
{
const uint8_t *y_ptr1=Y+y*Y_stride,
*u_ptr=U+(y/uv_y_sample_interval)*UV_stride,
*v_ptr=V+(y/uv_y_sample_interval)*UV_stride;
uint8_t *rgb_ptr1=RGB+y*RGB_stride;
for(x=0; x<(width-(uv_x_sample_interval-1)); x+=uv_x_sample_interval)
{
// Compute U and V contributions, common to the four pixels
int32_t u_tmp = ((*u_ptr)-128);
int32_t v_tmp = ((*v_ptr)-128);
int32_t r_tmp = (v_tmp*param->v_r_factor);
int32_t g_tmp = (u_tmp*param->u_g_factor + v_tmp*param->v_g_factor);
int32_t b_tmp = (u_tmp*param->u_b_factor);
// Compute the Y contribution for each pixel
int32_t y_tmp = ((y_ptr1[0]-param->y_shift)*param->y_factor);
PACK_PIXEL(rgb_ptr1);
y_tmp = ((y_ptr1[y_pixel_stride]-param->y_shift)*param->y_factor);
PACK_PIXEL(rgb_ptr1);
y_ptr1+=2*y_pixel_stride;
u_ptr+=2*uv_pixel_stride/uv_x_sample_interval;
v_ptr+=2*uv_pixel_stride/uv_x_sample_interval;
}
/* Catch the last pixel, if needed */
if (uv_x_sample_interval == 2 && x == (width-1))
{
// Compute U and V contributions, common to the four pixels
int32_t u_tmp = ((*u_ptr)-128);
int32_t v_tmp = ((*v_ptr)-128);
int32_t r_tmp = (v_tmp*param->v_r_factor);
int32_t g_tmp = (u_tmp*param->u_g_factor + v_tmp*param->v_g_factor);
int32_t b_tmp = (u_tmp*param->u_b_factor);
// Compute the Y contribution for each pixel
int32_t y_tmp = ((y_ptr1[0]-param->y_shift)*param->y_factor);
PACK_PIXEL(rgb_ptr1);
}
}
#undef y_pixel_stride
#undef uv_pixel_stride
#undef uv_x_sample_interval
#undef uv_y_sample_interval
}
#undef STD_FUNCTION_NAME
#undef YUV_FORMAT
#undef RGB_FORMAT
#undef PACK_PIXEL
| YifuLiu/AliOS-Things | components/SDL2/src/video/yuv2rgb/yuv_rgb_std_func.h | C | apache-2.0 | 6,333 |
cmake_minimum_required(VERSION 2.8.11)
project(SDL2 C)
# Global settings for all of the test targets
# FIXME: is this wrong?
remove_definitions(-DUSING_GENERATED_CONFIG_H)
link_libraries(SDL2_test SDL2-static)
# FIXME: Parent directory CMakeLists.txt only sets these for mingw/cygwin,
# but we need them for VS as well.
if(WINDOWS)
link_libraries(SDL2main)
add_definitions(-Dmain=SDL_main)
endif()
add_executable(checkkeys checkkeys.c)
add_executable(loopwave loopwave.c)
add_executable(loopwavequeue loopwavequeue.c)
add_executable(testresample testresample.c)
add_executable(testaudioinfo testaudioinfo.c)
file(GLOB TESTAUTOMATION_SOURCE_FILES testautomation*.c)
add_executable(testautomation ${TESTAUTOMATION_SOURCE_FILES})
add_executable(testmultiaudio testmultiaudio.c)
add_executable(testaudiohotplug testaudiohotplug.c)
add_executable(testaudiocapture testaudiocapture.c)
add_executable(testatomic testatomic.c)
add_executable(testintersections testintersections.c)
add_executable(testrelative testrelative.c)
add_executable(testhittesting testhittesting.c)
add_executable(testdraw2 testdraw2.c)
add_executable(testdrawchessboard testdrawchessboard.c)
add_executable(testdropfile testdropfile.c)
add_executable(testerror testerror.c)
add_executable(testfile testfile.c)
add_executable(testgamecontroller testgamecontroller.c)
add_executable(testgesture testgesture.c)
add_executable(testgl2 testgl2.c)
add_executable(testgles testgles.c)
add_executable(testgles2 testgles2.c)
add_executable(testhaptic testhaptic.c)
add_executable(testhotplug testhotplug.c)
add_executable(testrumble testrumble.c)
add_executable(testthread testthread.c)
add_executable(testiconv testiconv.c)
add_executable(testime testime.c)
add_executable(testjoystick testjoystick.c)
add_executable(testkeys testkeys.c)
add_executable(testloadso testloadso.c)
add_executable(testlock testlock.c)
if(APPLE)
add_executable(testnative testnative.c
testnativecocoa.m
testnativex11.c)
elseif(WINDOWS)
add_executable(testnative testnative.c testnativew32.c)
elseif(UNIX)
add_executable(testnative testnative.c testnativex11.c)
endif()
add_executable(testoverlay2 testoverlay2.c testyuv_cvt.c)
add_executable(testplatform testplatform.c)
add_executable(testpower testpower.c)
add_executable(testfilesystem testfilesystem.c)
add_executable(testrendertarget testrendertarget.c)
add_executable(testscale testscale.c)
add_executable(testsem testsem.c)
add_executable(testshader testshader.c)
add_executable(testshape testshape.c)
add_executable(testsprite2 testsprite2.c)
add_executable(testspriteminimal testspriteminimal.c)
add_executable(teststreaming teststreaming.c)
add_executable(testtimer testtimer.c)
add_executable(testver testver.c)
add_executable(testviewport testviewport.c)
add_executable(testwm2 testwm2.c)
add_executable(testyuv testyuv.c testyuv_cvt.c)
add_executable(torturethread torturethread.c)
add_executable(testrendercopyex testrendercopyex.c)
add_executable(testmessage testmessage.c)
add_executable(testdisplayinfo testdisplayinfo.c)
add_executable(testqsort testqsort.c)
add_executable(testbounds testbounds.c)
add_executable(testcustomcursor testcustomcursor.c)
add_executable(controllermap controllermap.c)
add_executable(testvulkan testvulkan.c)
add_executable(testoffscreen testoffscreen.c)
# HACK: Dummy target to cause the resource files to be copied to the build directory.
# Need to make it an executable so we can use the TARGET_FILE_DIR generator expression.
# This is needed so they get copied to the correct Debug/Release subdirectory in Xcode.
file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/resources_dummy.c "int main(int argc, const char **argv){ return 1; }\n")
add_executable(SDL2_test_resoureces ${CMAKE_CURRENT_BINARY_DIR}/resources_dummy.c)
file(GLOB RESOURCE_FILES *.bmp *.wav moose.dat utf8.txt)
foreach(RESOURCE_FILE ${RESOURCE_FILES})
add_custom_command(TARGET SDL2_test_resoureces POST_BUILD COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${RESOURCE_FILE} $<TARGET_FILE_DIR:SDL2_test_resoureces>)
endforeach(RESOURCE_FILE)
file(COPY ${RESOURCE_FILES} DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
# TODO: Might be easier to make all targets depend on the resources...?
set(NEEDS_RESOURCES
testscale
testrendercopyex
controllermap
testyuv
testgamecontroller
testshape
testshader
testnative
testspriteminimal
testautomation
testcustomcursor
testrendertarget
testsprite2
loopwave
loopwavequeue
testresample
testaudiohotplug
testmultiaudio
)
foreach(APP IN LISTS NEEDS_RESOURCES)
add_dependencies(${APP} SDL2_test_resoureces)
if(APPLE)
# Make sure resource files get installed into macOS/iOS .app bundles.
target_sources(${APP} PRIVATE "${RESOURCE_FILES}")
set_target_properties(${APP} PROPERTIES RESOURCE "${RESOURCE_FILES}")
endif()
endforeach()
# Set Apple App ID / Bundle ID. This is needed to launch apps on some Apple
# platforms (iOS, for example).
if(APPLE)
if(${CMAKE_VERSION} VERSION_LESS "3.7.0")
# CMake's 'BUILDSYSTEM_TARGETS' property is only available in
# CMake 3.7 and above.
message(WARNING "Unable to set Bundle ID for Apple .app builds due to old CMake (pre 3.7).")
else()
get_property(TARGETS DIRECTORY ${CMAKE_CURRENT_LIST_DIR} PROPERTY BUILDSYSTEM_TARGETS)
foreach(CURRENT_TARGET IN LISTS TARGETS)
get_property(TARGET_TYPE TARGET ${CURRENT_TARGET} PROPERTY TYPE)
if(TARGET_TYPE STREQUAL "EXECUTABLE")
set_target_properties("${CURRENT_TARGET}" PROPERTIES
MACOSX_BUNDLE_GUI_IDENTIFIER "org.libsdl.${CURRENT_TARGET}"
MACOSX_BUNDLE_BUNDLE_VERSION "${SDL_VERSION}"
MACOSX_BUNDLE_SHORT_VERSION_STRING "${SDL_VERSION}"
)
endif()
endforeach()
endif()
endif()
| YifuLiu/AliOS-Things | components/SDL2/test/CMakeLists.txt | CMake | apache-2.0 | 5,975 |
# Makefile to build the SDL tests
srcdir = @srcdir@
CC = @CC@
EXE = @EXE@
CFLAGS = @CFLAGS@ -g
LIBS = @LIBS@
TARGETS = \
checkkeys$(EXE) \
controllermap$(EXE) \
loopwave$(EXE) \
loopwavequeue$(EXE) \
testatomic$(EXE) \
testaudiocapture$(EXE) \
testaudiohotplug$(EXE) \
testaudioinfo$(EXE) \
testautomation$(EXE) \
testbounds$(EXE) \
testcustomcursor$(EXE) \
testdisplayinfo$(EXE) \
testdraw2$(EXE) \
testdrawchessboard$(EXE) \
testdropfile$(EXE) \
testerror$(EXE) \
testfile$(EXE) \
testfilesystem$(EXE) \
testgamecontroller$(EXE) \
testgesture$(EXE) \
testhaptic$(EXE) \
testhittesting$(EXE) \
testhotplug$(EXE) \
testiconv$(EXE) \
testime$(EXE) \
testintersections$(EXE) \
testjoystick$(EXE) \
testkeys$(EXE) \
testloadso$(EXE) \
testlocale$(EXE) \
testlock$(EXE) \
testmessage$(EXE) \
testmultiaudio$(EXE) \
testnative$(EXE) \
testoverlay2$(EXE) \
testplatform$(EXE) \
testpower$(EXE) \
testqsort$(EXE) \
testrelative$(EXE) \
testrendercopyex$(EXE) \
testrendertarget$(EXE) \
testresample$(EXE) \
testrumble$(EXE) \
testscale$(EXE) \
testsem$(EXE) \
testsensor$(EXE) \
testshape$(EXE) \
testsprite2$(EXE) \
testspriteminimal$(EXE) \
teststreaming$(EXE) \
testthread$(EXE) \
testtimer$(EXE) \
testver$(EXE) \
testviewport$(EXE) \
testvulkan$(EXE) \
testwm2$(EXE) \
testyuv$(EXE) \
torturethread$(EXE) \
@OPENGL_TARGETS@ += testgl2$(EXE) testshader$(EXE)
@OPENGLES1_TARGETS@ += testgles$(EXE)
@OPENGLES2_TARGETS@ += testgles2$(EXE)
all: Makefile $(TARGETS) copydatafiles
Makefile: $(srcdir)/Makefile.in
$(SHELL) config.status $@
checkkeys$(EXE): $(srcdir)/checkkeys.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
loopwave$(EXE): $(srcdir)/loopwave.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
loopwavequeue$(EXE): $(srcdir)/loopwavequeue.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testresample$(EXE): $(srcdir)/testresample.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testaudioinfo$(EXE): $(srcdir)/testaudioinfo.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testautomation$(EXE): $(srcdir)/testautomation.c \
$(srcdir)/testautomation_audio.c \
$(srcdir)/testautomation_clipboard.c \
$(srcdir)/testautomation_events.c \
$(srcdir)/testautomation_keyboard.c \
$(srcdir)/testautomation_main.c \
$(srcdir)/testautomation_mouse.c \
$(srcdir)/testautomation_pixels.c \
$(srcdir)/testautomation_platform.c \
$(srcdir)/testautomation_rect.c \
$(srcdir)/testautomation_render.c \
$(srcdir)/testautomation_rwops.c \
$(srcdir)/testautomation_sdltest.c \
$(srcdir)/testautomation_stdlib.c \
$(srcdir)/testautomation_surface.c \
$(srcdir)/testautomation_syswm.c \
$(srcdir)/testautomation_timer.c \
$(srcdir)/testautomation_video.c \
$(srcdir)/testautomation_hints.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testmultiaudio$(EXE): $(srcdir)/testmultiaudio.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testaudiohotplug$(EXE): $(srcdir)/testaudiohotplug.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testaudiocapture$(EXE): $(srcdir)/testaudiocapture.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testatomic$(EXE): $(srcdir)/testatomic.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testintersections$(EXE): $(srcdir)/testintersections.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testrelative$(EXE): $(srcdir)/testrelative.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testhittesting$(EXE): $(srcdir)/testhittesting.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testdraw2$(EXE): $(srcdir)/testdraw2.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testdrawchessboard$(EXE): $(srcdir)/testdrawchessboard.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testdropfile$(EXE): $(srcdir)/testdropfile.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testerror$(EXE): $(srcdir)/testerror.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testfile$(EXE): $(srcdir)/testfile.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testgamecontroller$(EXE): $(srcdir)/testgamecontroller.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testgesture$(EXE): $(srcdir)/testgesture.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @MATHLIB@
testgl2$(EXE): $(srcdir)/testgl2.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @MATHLIB@
testgles$(EXE): $(srcdir)/testgles.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @GLESLIB@ @MATHLIB@
testgles2$(EXE): $(srcdir)/testgles2.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @MATHLIB@
testhaptic$(EXE): $(srcdir)/testhaptic.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testhotplug$(EXE): $(srcdir)/testhotplug.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testrumble$(EXE): $(srcdir)/testrumble.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testthread$(EXE): $(srcdir)/testthread.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testiconv$(EXE): $(srcdir)/testiconv.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testime$(EXE): $(srcdir)/testime.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @SDL_TTF_LIB@
testjoystick$(EXE): $(srcdir)/testjoystick.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testkeys$(EXE): $(srcdir)/testkeys.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testloadso$(EXE): $(srcdir)/testloadso.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testlock$(EXE): $(srcdir)/testlock.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
ifeq (@ISMACOSX@,true)
testnative$(EXE): $(srcdir)/testnative.c \
$(srcdir)/testnativecocoa.m \
$(srcdir)/testnativex11.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) -framework Cocoa @XLIB@
endif
ifeq (@ISWINDOWS@,true)
testnative$(EXE): $(srcdir)/testnative.c \
$(srcdir)/testnativew32.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
endif
ifeq (@ISUNIX@,true)
testnative$(EXE): $(srcdir)/testnative.c \
$(srcdir)/testnativex11.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @XLIB@
endif
#there's probably a better way of doing this
ifeq (@ISMACOSX@,false)
ifeq (@ISWINDOWS@,false)
ifeq (@ISUNIX@,false)
testnative$(EXE): ;
endif
endif
endif
testoverlay2$(EXE): $(srcdir)/testoverlay2.c $(srcdir)/testyuv_cvt.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testplatform$(EXE): $(srcdir)/testplatform.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testpower$(EXE): $(srcdir)/testpower.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testfilesystem$(EXE): $(srcdir)/testfilesystem.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testrendertarget$(EXE): $(srcdir)/testrendertarget.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testscale$(EXE): $(srcdir)/testscale.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testsem$(EXE): $(srcdir)/testsem.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testsensor$(EXE): $(srcdir)/testsensor.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testshader$(EXE): $(srcdir)/testshader.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @GLLIB@ @MATHLIB@
testshape$(EXE): $(srcdir)/testshape.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testsprite2$(EXE): $(srcdir)/testsprite2.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testspriteminimal$(EXE): $(srcdir)/testspriteminimal.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @MATHLIB@
teststreaming$(EXE): $(srcdir)/teststreaming.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @MATHLIB@
testtimer$(EXE): $(srcdir)/testtimer.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testver$(EXE): $(srcdir)/testver.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testviewport$(EXE): $(srcdir)/testviewport.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testwm2$(EXE): $(srcdir)/testwm2.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testyuv$(EXE): $(srcdir)/testyuv.c $(srcdir)/testyuv_cvt.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
torturethread$(EXE): $(srcdir)/torturethread.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testrendercopyex$(EXE): $(srcdir)/testrendercopyex.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @MATHLIB@
testmessage$(EXE): $(srcdir)/testmessage.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testdisplayinfo$(EXE): $(srcdir)/testdisplayinfo.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testqsort$(EXE): $(srcdir)/testqsort.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testbounds$(EXE): $(srcdir)/testbounds.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testcustomcursor$(EXE): $(srcdir)/testcustomcursor.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
controllermap$(EXE): $(srcdir)/controllermap.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testvulkan$(EXE): $(srcdir)/testvulkan.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testlocale$(EXE): $(srcdir)/testlocale.c
$(CC) -o $@ $? $(CFLAGS) $(LIBS)
clean:
rm -f $(TARGETS)
distclean: clean
rm -f Makefile
rm -f config.status config.cache config.log
rm -rf $(srcdir)/autom4te*
%.bmp: $(srcdir)/%.bmp
cp $< $@
%.wav: $(srcdir)/%.wav
cp $< $@
%.dat: $(srcdir)/%.dat
cp $< $@
copydatafiles: copybmpfiles copywavfiles copydatfiles
.PHONY : copydatafiles
copybmpfiles: $(foreach bmp,$(wildcard $(srcdir)/*.bmp),$(notdir $(bmp)))
.PHONY : copybmpfiles
copywavfiles: $(foreach wav,$(wildcard $(srcdir)/*.wav),$(notdir $(wav)))
.PHONY : copywavfiles
copydatfiles: $(foreach dat,$(wildcard $(srcdir)/*.dat),$(notdir $(dat)))
.PHONY : copydatfiles
| YifuLiu/AliOS-Things | components/SDL2/test/Makefile.in | Makefile | apache-2.0 | 8,580 |
# Configure paths for SDL
# Sam Lantinga 9/21/99
# stolen from Manish Singh
# stolen back from Frank Belew
# stolen from Manish Singh
# Shamelessly stolen from Owen Taylor
# serial 1
dnl AM_PATH_SDL([MINIMUM-VERSION, [ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]])
dnl Test for SDL, and define SDL_CFLAGS and SDL_LIBS
dnl
AC_DEFUN([AM_PATH_SDL2],
[dnl
dnl Get the cflags and libraries from the sdl2-config script
dnl
AC_ARG_WITH(sdl-prefix,[ --with-sdl-prefix=PFX Prefix where SDL is installed (optional)],
sdl_prefix="$withval", sdl_prefix="")
AC_ARG_WITH(sdl-exec-prefix,[ --with-sdl-exec-prefix=PFX Exec prefix where SDL is installed (optional)],
sdl_exec_prefix="$withval", sdl_exec_prefix="")
AC_ARG_ENABLE(sdltest, [ --disable-sdltest Do not try to compile and run a test SDL program],
, enable_sdltest=yes)
min_sdl_version=ifelse([$1], ,0.9.0,$1)
if test "x$sdl_prefix$sdl_exec_prefix" = x ; then
PKG_CHECK_MODULES([SDL], [sdl2 >= $min_sdl_version],
[sdl_pc=yes],
[sdl_pc=no])
else
sdl_pc=no
if test x$sdl_exec_prefix != x ; then
sdl_config_args="$sdl_config_args --exec-prefix=$sdl_exec_prefix"
if test x${SDL_CONFIG+set} != xset ; then
SDL_CONFIG=$sdl_exec_prefix/bin/sdl2-config
fi
fi
if test x$sdl_prefix != x ; then
sdl_config_args="$sdl_config_args --prefix=$sdl_prefix"
if test x${SDL_CONFIG+set} != xset ; then
SDL_CONFIG=$sdl_prefix/bin/sdl2-config
fi
fi
fi
if test "x$sdl_pc" = xyes ; then
no_sdl=""
SDL_CONFIG="pkg-config sdl2"
else
as_save_PATH="$PATH"
if test "x$prefix" != xNONE && test "$cross_compiling" != yes; then
PATH="$prefix/bin:$prefix/usr/bin:$PATH"
fi
AC_PATH_PROG(SDL_CONFIG, sdl2-config, no, [$PATH])
PATH="$as_save_PATH"
AC_MSG_CHECKING(for SDL - version >= $min_sdl_version)
no_sdl=""
if test "$SDL_CONFIG" = "no" ; then
no_sdl=yes
else
SDL_CFLAGS=`$SDL_CONFIG $sdl_config_args --cflags`
SDL_LIBS=`$SDL_CONFIG $sdl_config_args --libs`
sdl_major_version=`$SDL_CONFIG $sdl_config_args --version | \
sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'`
sdl_minor_version=`$SDL_CONFIG $sdl_config_args --version | \
sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'`
sdl_micro_version=`$SDL_CONFIG $sdl_config_args --version | \
sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'`
if test "x$enable_sdltest" = "xyes" ; then
ac_save_CFLAGS="$CFLAGS"
ac_save_CXXFLAGS="$CXXFLAGS"
ac_save_LIBS="$LIBS"
CFLAGS="$CFLAGS $SDL_CFLAGS"
CXXFLAGS="$CXXFLAGS $SDL_CFLAGS"
LIBS="$LIBS $SDL_LIBS"
dnl
dnl Now check if the installed SDL is sufficiently new. (Also sanity
dnl checks the results of sdl2-config to some extent
dnl
rm -f conf.sdltest
AC_TRY_RUN([
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SDL.h"
char*
my_strdup (char *str)
{
char *new_str;
if (str)
{
new_str = (char *)malloc ((strlen (str) + 1) * sizeof(char));
strcpy (new_str, str);
}
else
new_str = NULL;
return new_str;
}
int main (int argc, char *argv[])
{
int major, minor, micro;
char *tmp_version;
/* This hangs on some systems (?)
system ("touch conf.sdltest");
*/
{ FILE *fp = fopen("conf.sdltest", "a"); if ( fp ) fclose(fp); }
/* HP/UX 9 (%@#!) writes to sscanf strings */
tmp_version = my_strdup("$min_sdl_version");
if (sscanf(tmp_version, "%d.%d.%d", &major, &minor, µ) != 3) {
printf("%s, bad version string\n", "$min_sdl_version");
exit(1);
}
if (($sdl_major_version > major) ||
(($sdl_major_version == major) && ($sdl_minor_version > minor)) ||
(($sdl_major_version == major) && ($sdl_minor_version == minor) && ($sdl_micro_version >= micro)))
{
return 0;
}
else
{
printf("\n*** 'sdl2-config --version' returned %d.%d.%d, but the minimum version\n", $sdl_major_version, $sdl_minor_version, $sdl_micro_version);
printf("*** of SDL required is %d.%d.%d. If sdl2-config is correct, then it is\n", major, minor, micro);
printf("*** best to upgrade to the required version.\n");
printf("*** If sdl2-config was wrong, set the environment variable SDL_CONFIG\n");
printf("*** to point to the correct copy of sdl2-config, and remove the file\n");
printf("*** config.cache before re-running configure\n");
return 1;
}
}
],, no_sdl=yes,[echo $ac_n "cross compiling; assumed OK... $ac_c"])
CFLAGS="$ac_save_CFLAGS"
CXXFLAGS="$ac_save_CXXFLAGS"
LIBS="$ac_save_LIBS"
fi
fi
if test "x$no_sdl" = x ; then
AC_MSG_RESULT(yes)
else
AC_MSG_RESULT(no)
fi
fi
if test "x$no_sdl" = x ; then
ifelse([$2], , :, [$2])
else
if test "$SDL_CONFIG" = "no" ; then
echo "*** The sdl2-config script installed by SDL could not be found"
echo "*** If SDL was installed in PREFIX, make sure PREFIX/bin is in"
echo "*** your path, or set the SDL_CONFIG environment variable to the"
echo "*** full path to sdl2-config."
else
if test -f conf.sdltest ; then
:
else
echo "*** Could not run SDL test program, checking why..."
CFLAGS="$CFLAGS $SDL_CFLAGS"
CXXFLAGS="$CXXFLAGS $SDL_CFLAGS"
LIBS="$LIBS $SDL_LIBS"
AC_TRY_LINK([
#include <stdio.h>
#include "SDL.h"
int main(int argc, char *argv[])
{ return 0; }
#undef main
#define main K_and_R_C_main
], [ return 0; ],
[ echo "*** The test program compiled, but did not run. This usually means"
echo "*** that the run-time linker is not finding SDL or finding the wrong"
echo "*** version of SDL. If it is not finding SDL, you'll need to set your"
echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point"
echo "*** to the installed location Also, make sure you have run ldconfig if that"
echo "*** is required on your system"
echo "***"
echo "*** If you have an old version installed, it is best to remove it, although"
echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH"],
[ echo "*** The test program failed to compile or link. See the file config.log for the"
echo "*** exact error that occured. This usually means SDL was incorrectly installed"
echo "*** or that you have moved SDL since it was installed. In the latter case, you"
echo "*** may want to edit the sdl2-config script: $SDL_CONFIG" ])
CFLAGS="$ac_save_CFLAGS"
CXXFLAGS="$ac_save_CXXFLAGS"
LIBS="$ac_save_LIBS"
fi
fi
SDL_CFLAGS=""
SDL_LIBS=""
ifelse([$3], , :, [$3])
fi
AC_SUBST(SDL_CFLAGS)
AC_SUBST(SDL_LIBS)
rm -f conf.sdltest
])
# pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*-
# serial 1 (pkg-config-0.24)
#
# Copyright © 2004 Scott James Remnant <scott@netsplit.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# PKG_PROG_PKG_CONFIG([MIN-VERSION])
# ----------------------------------
AC_DEFUN([PKG_PROG_PKG_CONFIG],
[m4_pattern_forbid([^_?PKG_[A-Z_]+$])
m4_pattern_allow([^PKG_CONFIG(_PATH)?$])
AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])
AC_ARG_VAR([PKG_CONFIG_PATH], [directories to add to pkg-config's search path])
AC_ARG_VAR([PKG_CONFIG_LIBDIR], [path overriding pkg-config's built-in search path])
if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
AC_PATH_TOOL([PKG_CONFIG], [pkg-config])
fi
if test -n "$PKG_CONFIG"; then
_pkg_min_version=m4_default([$1], [0.9.0])
AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version])
if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
AC_MSG_RESULT([yes])
else
AC_MSG_RESULT([no])
PKG_CONFIG=""
fi
fi[]dnl
])# PKG_PROG_PKG_CONFIG
# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
#
# Check to see whether a particular set of modules exists. Similar
# to PKG_CHECK_MODULES(), but does not set variables or print errors.
#
# Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG])
# only at the first occurence in configure.ac, so if the first place
# it's called might be skipped (such as if it is within an "if", you
# have to call PKG_CHECK_EXISTS manually
# --------------------------------------------------------------
AC_DEFUN([PKG_CHECK_EXISTS],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
if test -n "$PKG_CONFIG" && \
AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then
m4_default([$2], [:])
m4_ifvaln([$3], [else
$3])dnl
fi])
# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
# ---------------------------------------------
m4_define([_PKG_CONFIG],
[if test -n "$$1"; then
pkg_cv_[]$1="$$1"
elif test -n "$PKG_CONFIG"; then
PKG_CHECK_EXISTS([$3],
[pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`],
[pkg_failed=yes])
else
pkg_failed=untried
fi[]dnl
])# _PKG_CONFIG
# _PKG_SHORT_ERRORS_SUPPORTED
# -----------------------------
AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])
if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
_pkg_short_errors_supported=yes
else
_pkg_short_errors_supported=no
fi[]dnl
])# _PKG_SHORT_ERRORS_SUPPORTED
# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
# [ACTION-IF-NOT-FOUND])
#
#
# Note that if there is a possibility the first call to
# PKG_CHECK_MODULES might not happen, you should be sure to include an
# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
#
#
# --------------------------------------------------------------
AC_DEFUN([PKG_CHECK_MODULES],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl
AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl
pkg_failed=no
AC_MSG_CHECKING([for $1])
_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2])
_PKG_CONFIG([$1][_LIBS], [libs], [$2])
m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS
and $1[]_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.])
if test $pkg_failed = yes; then
AC_MSG_RESULT([no])
_PKG_SHORT_ERRORS_SUPPORTED
if test $_pkg_short_errors_supported = yes; then
$1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors "$2" 2>&1`
else
$1[]_PKG_ERRORS=`$PKG_CONFIG --print-errors "$2" 2>&1`
fi
# Put the nasty error message in config.log where it belongs
echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD
m4_default([$4], [AC_MSG_ERROR(
[Package requirements ($2) were not met:
$$1_PKG_ERRORS
Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.
_PKG_TEXT])dnl
])
elif test $pkg_failed = untried; then
AC_MSG_RESULT([no])
m4_default([$4], [AC_MSG_FAILURE(
[The pkg-config script could not be found or is too old. Make sure it
is in your PATH or set the PKG_CONFIG environment variable to the full
path to pkg-config.
_PKG_TEXT
To get pkg-config, see <http://pkg-config.freedesktop.org/>.])dnl
])
else
$1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS
$1[]_LIBS=$pkg_cv_[]$1[]_LIBS
AC_MSG_RESULT([yes])
$3
fi[]dnl
])# PKG_CHECK_MODULES
| YifuLiu/AliOS-Things | components/SDL2/test/acinclude.m4 | M4Sugar | apache-2.0 | 12,406 |
#!/bin/sh
#
# Regenerate configuration files
cp acinclude.m4 aclocal.m4
found=false
for autoconf in autoconf autoconf259 autoconf-2.59
do if which $autoconf >/dev/null 2>&1; then $autoconf && found=true; break; fi
done
if test x$found = xfalse; then
echo "Couldn't find autoconf, aborting"
exit 1
fi
| YifuLiu/AliOS-Things | components/SDL2/test/autogen.sh | Shell | apache-2.0 | 308 |
/*
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.
*/
/* Simple program: Loop, watching keystrokes
Note that you need to call SDL_PollEvent() or SDL_WaitEvent() to
pump the event loop and catch keystrokes.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL.h"
int done;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_Quit();
exit(rc);
}
static void
print_string(char **text, size_t *maxlen, const char *fmt, ...)
{
int len;
va_list ap;
va_start(ap, fmt);
len = SDL_vsnprintf(*text, *maxlen, fmt, ap);
if (len > 0) {
*text += len;
if ( ((size_t) len) < *maxlen ) {
*maxlen -= (size_t) len;
} else {
*maxlen = 0;
}
}
va_end(ap);
}
static void
print_modifiers(char **text, size_t *maxlen)
{
int mod;
print_string(text, maxlen, " modifiers:");
mod = SDL_GetModState();
if (!mod) {
print_string(text, maxlen, " (none)");
return;
}
if (mod & KMOD_LSHIFT)
print_string(text, maxlen, " LSHIFT");
if (mod & KMOD_RSHIFT)
print_string(text, maxlen, " RSHIFT");
if (mod & KMOD_LCTRL)
print_string(text, maxlen, " LCTRL");
if (mod & KMOD_RCTRL)
print_string(text, maxlen, " RCTRL");
if (mod & KMOD_LALT)
print_string(text, maxlen, " LALT");
if (mod & KMOD_RALT)
print_string(text, maxlen, " RALT");
if (mod & KMOD_LGUI)
print_string(text, maxlen, " LGUI");
if (mod & KMOD_RGUI)
print_string(text, maxlen, " RGUI");
if (mod & KMOD_NUM)
print_string(text, maxlen, " NUM");
if (mod & KMOD_CAPS)
print_string(text, maxlen, " CAPS");
if (mod & KMOD_MODE)
print_string(text, maxlen, " MODE");
}
static void
PrintModifierState()
{
char message[512];
char *spot;
size_t left;
spot = message;
left = sizeof(message);
print_modifiers(&spot, &left);
SDL_Log("Initial state:%s\n", message);
}
static void
PrintKey(SDL_Keysym * sym, SDL_bool pressed, SDL_bool repeat)
{
char message[512];
char *spot;
size_t left;
spot = message;
left = sizeof(message);
/* Print the keycode, name and state */
if (sym->sym) {
print_string(&spot, &left,
"Key %s: scancode %d = %s, keycode 0x%08X = %s ",
pressed ? "pressed " : "released",
sym->scancode,
SDL_GetScancodeName(sym->scancode),
sym->sym, SDL_GetKeyName(sym->sym));
} else {
print_string(&spot, &left,
"Unknown Key (scancode %d = %s) %s ",
sym->scancode,
SDL_GetScancodeName(sym->scancode),
pressed ? "pressed " : "released");
}
print_modifiers(&spot, &left);
if (repeat) {
print_string(&spot, &left, " (repeat)");
}
SDL_Log("%s\n", message);
}
static void
PrintText(char *eventtype, char *text)
{
char *spot, expanded[1024];
expanded[0] = '\0';
for ( spot = text; *spot; ++spot )
{
size_t length = SDL_strlen(expanded);
SDL_snprintf(expanded + length, sizeof(expanded) - length, "\\x%.2x", (unsigned char)*spot);
}
SDL_Log("%s Text (%s): \"%s%s\"\n", eventtype, expanded, *text == '"' ? "\\" : "", text);
}
void
loop()
{
SDL_Event event;
/* Check for events */
/*SDL_WaitEvent(&event); emscripten does not like waiting*/
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN:
case SDL_KEYUP:
PrintKey(&event.key.keysym, (event.key.state == SDL_PRESSED) ? SDL_TRUE : SDL_FALSE, (event.key.repeat) ? SDL_TRUE : SDL_FALSE);
break;
case SDL_TEXTEDITING:
PrintText("EDIT", event.text.text);
break;
case SDL_TEXTINPUT:
PrintText("INPUT", event.text.text);
break;
case SDL_MOUSEBUTTONDOWN:
/* Left button quits the app, other buttons toggles text input */
if (event.button.button == SDL_BUTTON_LEFT) {
done = 1;
} else {
if (SDL_IsTextInputActive()) {
SDL_Log("Stopping text input\n");
SDL_StopTextInput();
} else {
SDL_Log("Starting text input\n");
SDL_StartTextInput();
}
}
break;
case SDL_QUIT:
done = 1;
break;
default:
break;
}
}
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char *argv[])
{
SDL_Window *window;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize SDL */
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return (1);
}
/* Set 640x480 video mode */
window = SDL_CreateWindow("CheckKeys Test",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
640, 480, 0);
if (!window) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create 640x480 window: %s\n",
SDL_GetError());
quit(2);
}
#if __IPHONEOS__
/* Creating the context creates the view, which we need to show keyboard */
SDL_GL_CreateContext(window);
#endif
SDL_StartTextInput();
/* Print initial modifier state */
SDL_PumpEvents();
PrintModifierState();
/* Watch keystrokes */
done = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
loop();
}
#endif
SDL_Quit();
return (0);
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/checkkeys.c | C | apache-2.0 | 6,370 |
dnl Process this file with autoconf to produce a configure script.
AC_INIT(README)
dnl Detect the canonical build and host environments
AC_CONFIG_AUX_DIRS($srcdir/../build-scripts)
AC_CANONICAL_HOST
dnl Check for tools
AC_PROG_CC
dnl Check for compiler environment
AC_C_CONST
dnl We only care about this for building testnative at the moment, so these
dnl values shouldn't be considered absolute truth.
dnl (Haiku, for example, sets none of these.)
ISUNIX="false"
ISWINDOWS="false"
ISMACOSX="false"
dnl Figure out which math library to use
case "$host" in
*-*-cygwin* | *-*-mingw32*)
ISWINDOWS="true"
EXE=".exe"
MATHLIB=""
SYS_GL_LIBS="-lopengl32"
;;
*-*-haiku*)
EXE=""
MATHLIB=""
SYS_GL_LIBS="-lGL"
;;
*-*-darwin* )
ISMACOSX="true"
EXE=""
MATHLIB=""
SYS_GL_LIBS="-Wl,-framework,OpenGL"
;;
*-*-aix*)
ISUNIX="true"
EXE=""
if test x$ac_cv_prog_gcc = xyes; then
CFLAGS="-mthreads"
fi
SYS_GL_LIBS=""
;;
*-*-mint*)
EXE=""
MATHLIB=""
AC_PATH_PROG(OSMESA_CONFIG, osmesa-config, no)
if test "x$OSMESA_CONFIG" = "xyes"; then
OSMESA_CFLAGS=`$OSMESA_CONFIG --cflags`
OSMESA_LIBS=`$OSMESA_CONFIG --libs`
CFLAGS="$CFLAGS $OSMESA_CFLAGS"
SYS_GL_LIBS="$OSMESA_LIBS"
else
SYS_GL_LIBS="-lOSMesa"
fi
;;
*-*-qnx*)
EXE=""
MATHLIB=""
SYS_GL_LIBS="-lGLES_CM"
;;
*-*-emscripten* )
dnl This should really be .js, but we need to specify extra flags when compiling to js
EXE=".bc"
MATHLIB=""
SYS_GL_LIBS=""
;;
*-*-riscos* )
EXE=",e1f"
MATHLIB=""
SYS_GL_LIBS=""
;;
*)
dnl Oh well, call it Unix...
ISUNIX="true"
EXE=""
MATHLIB="-lm"
SYS_GL_LIBS="-lGL"
;;
esac
AC_SUBST(EXE)
AC_SUBST(MATHLIB)
AC_SUBST(ISMACOSX)
AC_SUBST(ISWINDOWS)
AC_SUBST(ISUNIX)
dnl Check for SDL
SDL_VERSION=2.0.0
AM_PATH_SDL2($SDL_VERSION,
:,
AC_MSG_ERROR([*** SDL version $SDL_VERSION not found!])
)
CFLAGS="$CFLAGS $SDL_CFLAGS"
LIBS="$LIBS -lSDL2_test $SDL_LIBS"
dnl Check for X11 path, needed for OpenGL on some systems
AC_PATH_X
if test x$have_x = xyes; then
if test x$ac_x_includes = xno || test "x$ac_x_includes" = xNone || test "x$ac_x_includes" = x; then
:
else
CFLAGS="$CFLAGS -I$ac_x_includes"
fi
if test x$ac_x_libraries = xno || test "x$ac_x_libraries" = xNone; then
:
else
if test "x$ac_x_libraries" = x; then
XPATH=""
XLIB="-lX11"
else
XPATH="-L$ac_x_libraries"
XLIB="-L$ac_x_libraries -lX11"
fi
fi
fi
dnl Check for OpenGL
AC_MSG_CHECKING(for OpenGL support)
have_opengl=no
AC_TRY_COMPILE([
#include "SDL_opengl.h"
#ifndef SDL_VIDEO_OPENGL
#error SDL_VIDEO_OPENGL
#endif
],[
],[
have_opengl=yes
])
AC_MSG_RESULT($have_opengl)
dnl Check for OpenGL ES
AC_MSG_CHECKING(for OpenGL ES support)
have_opengles=no
AC_TRY_COMPILE([
#include "SDL_opengles.h"
#ifndef SDL_VIDEO_OPENGL_ES
#error SDL_VIDEO_OPENGL_ES
#endif
],[
],[
have_opengles=yes
])
AC_MSG_RESULT($have_opengles)
dnl Check for OpenGL ES2
AC_MSG_CHECKING(for OpenGL ES2 support)
have_opengles2=no
AC_TRY_COMPILE([
#include "SDL_opengles2.h"
#ifndef SDL_VIDEO_OPENGL_ES2
#error SDL_VIDEO_OPENGL_ES2
#endif
],[
],[
have_opengles2=yes
])
AC_MSG_RESULT($have_opengles2)
GLLIB=""
GLESLIB=""
GLES2LIB=""
OPENGLES1_TARGETS="UNUSED"
OPENGLES2_TARGETS="UNUSED"
OPENGL_TARGETS="UNUSED"
if test x$have_opengles = xyes; then
CFLAGS="$CFLAGS -DHAVE_OPENGLES"
GLESLIB="$XPATH -lGLESv1_CM"
OPENGLES1_TARGETS="TARGETS"
fi
if test x$have_opengles2 = xyes; then
CFLAGS="$CFLAGS -DHAVE_OPENGLES2"
#GLES2LIB="$XPATH -lGLESv2"
OPENGLES2_TARGETS="TARGETS"
fi
if test x$have_opengl = xyes; then
CFLAGS="$CFLAGS -DHAVE_OPENGL"
GLLIB="$XPATH $SYS_GL_LIBS"
OPENGL_TARGETS="TARGETS"
fi
AC_SUBST(OPENGLES1_TARGETS)
AC_SUBST(OPENGLES2_TARGETS)
AC_SUBST(OPENGL_TARGETS)
AC_SUBST(GLLIB)
AC_SUBST(GLESLIB)
AC_SUBST(GLES2LIB)
AC_SUBST(XLIB)
dnl Check for SDL_ttf
AC_CHECK_LIB(SDL2_ttf, TTF_Init, have_SDL_ttf=yes)
if test x$have_SDL_ttf = xyes; then
CFLAGS="$CFLAGS -DHAVE_SDL_TTF"
SDL_TTF_LIB="-lSDL2_ttf"
fi
AC_SUBST(SDL_TTF_LIB)
dnl Finally create all the generated files
AC_OUTPUT([Makefile])
| YifuLiu/AliOS-Things | components/SDL2/test/configure.ac | M4Sugar | apache-2.0 | 4,564 |
/*
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.
*/
/* Game controller mapping generator */
/* Gabriel Jacobo <gabomdq@gmail.com> */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SDL.h"
#ifndef SDL_JOYSTICK_DISABLED
/* Define this for verbose output while mapping controllers */
#define DEBUG_CONTROLLERMAP
#ifdef __IPHONEOS__
#define SCREEN_WIDTH 320
#define SCREEN_HEIGHT 480
#else
#define SCREEN_WIDTH 512
#define SCREEN_HEIGHT 320
#endif
#define MARKER_BUTTON 1
#define MARKER_AXIS 2
enum
{
SDL_CONTROLLER_BINDING_AXIS_LEFTX_NEGATIVE,
SDL_CONTROLLER_BINDING_AXIS_LEFTX_POSITIVE,
SDL_CONTROLLER_BINDING_AXIS_LEFTY_NEGATIVE,
SDL_CONTROLLER_BINDING_AXIS_LEFTY_POSITIVE,
SDL_CONTROLLER_BINDING_AXIS_RIGHTX_NEGATIVE,
SDL_CONTROLLER_BINDING_AXIS_RIGHTX_POSITIVE,
SDL_CONTROLLER_BINDING_AXIS_RIGHTY_NEGATIVE,
SDL_CONTROLLER_BINDING_AXIS_RIGHTY_POSITIVE,
SDL_CONTROLLER_BINDING_AXIS_TRIGGERLEFT,
SDL_CONTROLLER_BINDING_AXIS_TRIGGERRIGHT,
SDL_CONTROLLER_BINDING_AXIS_MAX,
};
#define BINDING_COUNT (SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_MAX)
static struct
{
int x, y;
double angle;
int marker;
} s_arrBindingDisplay[BINDING_COUNT] = {
{ 387, 167, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_A */
{ 431, 132, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_B */
{ 342, 132, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_X */
{ 389, 101, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_Y */
{ 174, 132, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_BACK */
{ 233, 132, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_GUIDE */
{ 289, 132, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_START */
{ 75, 154, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_LEFTSTICK */
{ 305, 230, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_RIGHTSTICK */
{ 77, 40, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_LEFTSHOULDER */
{ 396, 36, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_RIGHTSHOULDER */
{ 154, 188, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_DPAD_UP */
{ 154, 249, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_DPAD_DOWN */
{ 116, 217, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_DPAD_LEFT */
{ 186, 217, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_DPAD_RIGHT */
{ 74, 153, 270.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_LEFTX_NEGATIVE */
{ 74, 153, 90.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_LEFTX_POSITIVE */
{ 74, 153, 0.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_LEFTY_NEGATIVE */
{ 74, 153, 180.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_LEFTY_POSITIVE */
{ 306, 231, 270.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_RIGHTX_NEGATIVE */
{ 306, 231, 90.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_RIGHTX_POSITIVE */
{ 306, 231, 0.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_RIGHTY_NEGATIVE */
{ 306, 231, 180.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_RIGHTY_POSITIVE */
{ 91, -20, 180.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_TRIGGERLEFT */
{ 375, -20, 180.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_TRIGGERRIGHT */
};
static int s_arrBindingOrder[BINDING_COUNT] = {
SDL_CONTROLLER_BUTTON_A,
SDL_CONTROLLER_BUTTON_B,
SDL_CONTROLLER_BUTTON_Y,
SDL_CONTROLLER_BUTTON_X,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_LEFTX_NEGATIVE,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_LEFTX_POSITIVE,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_LEFTY_NEGATIVE,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_LEFTY_POSITIVE,
SDL_CONTROLLER_BUTTON_LEFTSTICK,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_RIGHTX_NEGATIVE,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_RIGHTX_POSITIVE,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_RIGHTY_NEGATIVE,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_RIGHTY_POSITIVE,
SDL_CONTROLLER_BUTTON_RIGHTSTICK,
SDL_CONTROLLER_BUTTON_LEFTSHOULDER,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_TRIGGERLEFT,
SDL_CONTROLLER_BUTTON_RIGHTSHOULDER,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_TRIGGERRIGHT,
SDL_CONTROLLER_BUTTON_DPAD_UP,
SDL_CONTROLLER_BUTTON_DPAD_RIGHT,
SDL_CONTROLLER_BUTTON_DPAD_DOWN,
SDL_CONTROLLER_BUTTON_DPAD_LEFT,
SDL_CONTROLLER_BUTTON_BACK,
SDL_CONTROLLER_BUTTON_GUIDE,
SDL_CONTROLLER_BUTTON_START,
};
typedef struct
{
SDL_GameControllerBindType bindType;
union
{
int button;
struct {
int axis;
int axis_min;
int axis_max;
} axis;
struct {
int hat;
int hat_mask;
} hat;
} value;
SDL_bool committed;
} SDL_GameControllerExtendedBind;
static SDL_GameControllerExtendedBind s_arrBindings[BINDING_COUNT];
typedef struct
{
SDL_bool m_bMoving;
int m_nLastValue;
int m_nStartingValue;
int m_nFarthestValue;
} AxisState;
static int s_nNumAxes;
static AxisState *s_arrAxisState;
static int s_iCurrentBinding;
static Uint32 s_unPendingAdvanceTime;
static SDL_bool s_bBindingComplete;
static SDL_Window *window;
static SDL_bool done = SDL_FALSE;
SDL_Texture *
LoadTexture(SDL_Renderer *renderer, const char *file, SDL_bool transparent)
{
SDL_Surface *temp;
SDL_Texture *texture;
/* Load the sprite image */
temp = SDL_LoadBMP(file);
if (temp == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s", file, SDL_GetError());
return NULL;
}
/* Set transparent pixel as the pixel at (0,0) */
if (transparent) {
if (temp->format->palette) {
SDL_SetColorKey(temp, SDL_TRUE, *(Uint8 *) temp->pixels);
}
}
/* Create textures from the image */
texture = SDL_CreateTextureFromSurface(renderer, temp);
if (!texture) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture: %s\n", SDL_GetError());
SDL_FreeSurface(temp);
return NULL;
}
SDL_FreeSurface(temp);
/* We're ready to roll. :) */
return texture;
}
static int
StandardizeAxisValue(int nValue)
{
if (nValue > SDL_JOYSTICK_AXIS_MAX/2) {
return SDL_JOYSTICK_AXIS_MAX;
} else if (nValue < SDL_JOYSTICK_AXIS_MIN/2) {
return SDL_JOYSTICK_AXIS_MIN;
} else {
return 0;
}
}
static void
SetCurrentBinding(int iBinding)
{
int iIndex;
SDL_GameControllerExtendedBind *pBinding;
if (iBinding < 0) {
return;
}
if (iBinding == BINDING_COUNT) {
s_bBindingComplete = SDL_TRUE;
return;
}
s_iCurrentBinding = iBinding;
pBinding = &s_arrBindings[s_arrBindingOrder[s_iCurrentBinding]];
SDL_zerop(pBinding);
for (iIndex = 0; iIndex < s_nNumAxes; ++iIndex) {
s_arrAxisState[iIndex].m_nFarthestValue = s_arrAxisState[iIndex].m_nStartingValue;
}
s_unPendingAdvanceTime = 0;
}
static SDL_bool
BBindingContainsBinding(const SDL_GameControllerExtendedBind *pBindingA, const SDL_GameControllerExtendedBind *pBindingB)
{
if (pBindingA->bindType != pBindingB->bindType)
{
return SDL_FALSE;
}
switch (pBindingA->bindType)
{
case SDL_CONTROLLER_BINDTYPE_AXIS:
if (pBindingA->value.axis.axis != pBindingB->value.axis.axis) {
return SDL_FALSE;
}
if (!pBindingA->committed) {
return SDL_FALSE;
}
{
int minA = SDL_min(pBindingA->value.axis.axis_min, pBindingA->value.axis.axis_max);
int maxA = SDL_max(pBindingA->value.axis.axis_min, pBindingA->value.axis.axis_max);
int minB = SDL_min(pBindingB->value.axis.axis_min, pBindingB->value.axis.axis_max);
int maxB = SDL_max(pBindingB->value.axis.axis_min, pBindingB->value.axis.axis_max);
return (minA <= minB && maxA >= maxB);
}
/* Not reached */
default:
return SDL_memcmp(pBindingA, pBindingB, sizeof(*pBindingA)) == 0;
}
}
static void
ConfigureBinding(const SDL_GameControllerExtendedBind *pBinding)
{
SDL_GameControllerExtendedBind *pCurrent;
int iIndex;
int iCurrentElement = s_arrBindingOrder[s_iCurrentBinding];
/* Do we already have this binding? */
for (iIndex = 0; iIndex < SDL_arraysize(s_arrBindings); ++iIndex) {
pCurrent = &s_arrBindings[iIndex];
if (BBindingContainsBinding(pCurrent, pBinding)) {
if (iIndex == SDL_CONTROLLER_BUTTON_A && iCurrentElement != SDL_CONTROLLER_BUTTON_B) {
/* Skip to the next binding */
SetCurrentBinding(s_iCurrentBinding + 1);
return;
}
if (iIndex == SDL_CONTROLLER_BUTTON_B) {
/* Go back to the previous binding */
SetCurrentBinding(s_iCurrentBinding - 1);
return;
}
/* Already have this binding, ignore it */
return;
}
}
#ifdef DEBUG_CONTROLLERMAP
switch ( pBinding->bindType )
{
case SDL_CONTROLLER_BINDTYPE_NONE:
break;
case SDL_CONTROLLER_BINDTYPE_BUTTON:
SDL_Log("Configuring button binding for button %d\n", pBinding->value.button);
break;
case SDL_CONTROLLER_BINDTYPE_AXIS:
SDL_Log("Configuring axis binding for axis %d %d/%d committed = %s\n", pBinding->value.axis.axis, pBinding->value.axis.axis_min, pBinding->value.axis.axis_max, pBinding->committed ? "true" : "false");
break;
case SDL_CONTROLLER_BINDTYPE_HAT:
SDL_Log("Configuring hat binding for hat %d %d\n", pBinding->value.hat.hat, pBinding->value.hat.hat_mask);
break;
}
#endif /* DEBUG_CONTROLLERMAP */
/* Should the new binding override the existing one? */
pCurrent = &s_arrBindings[iCurrentElement];
if (pCurrent->bindType != SDL_CONTROLLER_BINDTYPE_NONE) {
SDL_bool bNativeDPad, bCurrentDPad;
SDL_bool bNativeAxis, bCurrentAxis;
bNativeDPad = (iCurrentElement == SDL_CONTROLLER_BUTTON_DPAD_UP ||
iCurrentElement == SDL_CONTROLLER_BUTTON_DPAD_DOWN ||
iCurrentElement == SDL_CONTROLLER_BUTTON_DPAD_LEFT ||
iCurrentElement == SDL_CONTROLLER_BUTTON_DPAD_RIGHT);
bCurrentDPad = (pCurrent->bindType == SDL_CONTROLLER_BINDTYPE_HAT);
if (bNativeDPad && bCurrentDPad) {
/* We already have a binding of the type we want, ignore the new one */
return;
}
bNativeAxis = (iCurrentElement >= SDL_CONTROLLER_BUTTON_MAX);
bCurrentAxis = (pCurrent->bindType == SDL_CONTROLLER_BINDTYPE_AXIS);
if (bNativeAxis == bCurrentAxis &&
(pBinding->bindType != SDL_CONTROLLER_BINDTYPE_AXIS ||
pBinding->value.axis.axis != pCurrent->value.axis.axis)) {
/* We already have a binding of the type we want, ignore the new one */
return;
}
}
*pCurrent = *pBinding;
if (pBinding->committed) {
s_unPendingAdvanceTime = SDL_GetTicks();
} else {
s_unPendingAdvanceTime = 0;
}
}
static SDL_bool
BMergeAxisBindings(int iIndex)
{
SDL_GameControllerExtendedBind *pBindingA = &s_arrBindings[iIndex];
SDL_GameControllerExtendedBind *pBindingB = &s_arrBindings[iIndex+1];
if (pBindingA->bindType == SDL_CONTROLLER_BINDTYPE_AXIS &&
pBindingB->bindType == SDL_CONTROLLER_BINDTYPE_AXIS &&
pBindingA->value.axis.axis == pBindingB->value.axis.axis) {
if (pBindingA->value.axis.axis_min == pBindingB->value.axis.axis_min) {
pBindingA->value.axis.axis_min = pBindingA->value.axis.axis_max;
pBindingA->value.axis.axis_max = pBindingB->value.axis.axis_max;
pBindingB->bindType = SDL_CONTROLLER_BINDTYPE_NONE;
return SDL_TRUE;
}
}
return SDL_FALSE;
}
static void
WatchJoystick(SDL_Joystick * joystick)
{
SDL_Renderer *screen = NULL;
SDL_Texture *background, *button, *axis, *marker;
const char *name = NULL;
SDL_Event event;
SDL_Rect dst;
Uint8 alpha=200, alpha_step = -1;
Uint32 alpha_ticks = 0;
SDL_JoystickID nJoystickID;
screen = SDL_CreateRenderer(window, -1, 0);
if (screen == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError());
return;
}
background = LoadTexture(screen, "controllermap.bmp", SDL_FALSE);
button = LoadTexture(screen, "button.bmp", SDL_TRUE);
axis = LoadTexture(screen, "axis.bmp", SDL_TRUE);
SDL_RaiseWindow(window);
/* scale for platforms that don't give you the window size you asked for. */
SDL_RenderSetLogicalSize(screen, SCREEN_WIDTH, SCREEN_HEIGHT);
/* Print info about the joystick we are watching */
name = SDL_JoystickName(joystick);
SDL_Log("Watching joystick %d: (%s)\n", SDL_JoystickInstanceID(joystick),
name ? name : "Unknown Joystick");
SDL_Log("Joystick has %d axes, %d hats, %d balls, and %d buttons\n",
SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));
SDL_Log("\n\n\
====================================================================================\n\
Press the buttons on your controller when indicated\n\
(Your controller may look different than the picture)\n\
If you want to correct a mistake, press backspace or the back button on your device\n\
To skip a button, press SPACE or click/touch the screen\n\
To exit, press ESC\n\
====================================================================================\n");
nJoystickID = SDL_JoystickInstanceID(joystick);
s_nNumAxes = SDL_JoystickNumAxes(joystick);
s_arrAxisState = (AxisState *)SDL_calloc(s_nNumAxes, sizeof(*s_arrAxisState));
/* Skip any spurious events at start */
while (SDL_PollEvent(&event) > 0) {
continue;
}
/* Loop, getting joystick events! */
while (!done && !s_bBindingComplete) {
int iElement = s_arrBindingOrder[s_iCurrentBinding];
switch (s_arrBindingDisplay[iElement].marker) {
case MARKER_AXIS:
marker = axis;
break;
case MARKER_BUTTON:
marker = button;
break;
default:
break;
}
dst.x = s_arrBindingDisplay[iElement].x;
dst.y = s_arrBindingDisplay[iElement].y;
SDL_QueryTexture(marker, NULL, NULL, &dst.w, &dst.h);
if (SDL_GetTicks() - alpha_ticks > 5) {
alpha_ticks = SDL_GetTicks();
alpha += alpha_step;
if (alpha == 255) {
alpha_step = -1;
}
if (alpha < 128) {
alpha_step = 1;
}
}
SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE);
SDL_RenderClear(screen);
SDL_RenderCopy(screen, background, NULL, NULL);
SDL_SetTextureAlphaMod(marker, alpha);
SDL_SetTextureColorMod(marker, 10, 255, 21);
SDL_RenderCopyEx(screen, marker, NULL, &dst, s_arrBindingDisplay[iElement].angle, NULL, SDL_FLIP_NONE);
SDL_RenderPresent(screen);
while (SDL_PollEvent(&event) > 0) {
switch (event.type) {
case SDL_JOYDEVICEREMOVED:
if (event.jaxis.which == nJoystickID) {
done = SDL_TRUE;
}
break;
case SDL_JOYAXISMOTION:
if (event.jaxis.which == nJoystickID) {
const int MAX_ALLOWED_JITTER = SDL_JOYSTICK_AXIS_MAX / 80; /* ShanWan PS3 controller needed 96 */
AxisState *pAxisState = &s_arrAxisState[event.jaxis.axis];
int nValue = event.jaxis.value;
int nCurrentDistance, nFarthestDistance;
if (!pAxisState->m_bMoving) {
Sint16 nInitialValue;
pAxisState->m_bMoving = SDL_JoystickGetAxisInitialState(joystick, event.jaxis.axis, &nInitialValue);
pAxisState->m_nLastValue = nValue;
pAxisState->m_nStartingValue = nInitialValue;
pAxisState->m_nFarthestValue = nInitialValue;
} else if (SDL_abs(nValue - pAxisState->m_nLastValue) <= MAX_ALLOWED_JITTER) {
break;
} else {
pAxisState->m_nLastValue = nValue;
}
nCurrentDistance = SDL_abs(nValue - pAxisState->m_nStartingValue);
nFarthestDistance = SDL_abs(pAxisState->m_nFarthestValue - pAxisState->m_nStartingValue);
if (nCurrentDistance > nFarthestDistance) {
pAxisState->m_nFarthestValue = nValue;
nFarthestDistance = SDL_abs(pAxisState->m_nFarthestValue - pAxisState->m_nStartingValue);
}
#ifdef DEBUG_CONTROLLERMAP
SDL_Log("AXIS %d nValue %d nCurrentDistance %d nFarthestDistance %d\n", event.jaxis.axis, nValue, nCurrentDistance, nFarthestDistance);
#endif
if (nFarthestDistance >= 16000) {
/* If we've gone out far enough and started to come back, let's bind this axis */
SDL_bool bCommitBinding = (nCurrentDistance <= 10000) ? SDL_TRUE : SDL_FALSE;
SDL_GameControllerExtendedBind binding;
SDL_zero(binding);
binding.bindType = SDL_CONTROLLER_BINDTYPE_AXIS;
binding.value.axis.axis = event.jaxis.axis;
binding.value.axis.axis_min = StandardizeAxisValue(pAxisState->m_nStartingValue);
binding.value.axis.axis_max = StandardizeAxisValue(pAxisState->m_nFarthestValue);
binding.committed = bCommitBinding;
ConfigureBinding(&binding);
}
}
break;
case SDL_JOYHATMOTION:
if (event.jhat.which == nJoystickID) {
if (event.jhat.value != SDL_HAT_CENTERED) {
SDL_GameControllerExtendedBind binding;
#ifdef DEBUG_CONTROLLERMAP
SDL_Log("HAT %d %d\n", event.jhat.hat, event.jhat.value);
#endif
SDL_zero(binding);
binding.bindType = SDL_CONTROLLER_BINDTYPE_HAT;
binding.value.hat.hat = event.jhat.hat;
binding.value.hat.hat_mask = event.jhat.value;
binding.committed = SDL_TRUE;
ConfigureBinding(&binding);
}
}
break;
case SDL_JOYBALLMOTION:
break;
case SDL_JOYBUTTONDOWN:
if (event.jbutton.which == nJoystickID) {
SDL_GameControllerExtendedBind binding;
#ifdef DEBUG_CONTROLLERMAP
SDL_Log("BUTTON %d\n", event.jbutton.button);
#endif
SDL_zero(binding);
binding.bindType = SDL_CONTROLLER_BINDTYPE_BUTTON;
binding.value.button = event.jbutton.button;
binding.committed = SDL_TRUE;
ConfigureBinding(&binding);
}
break;
case SDL_FINGERDOWN:
case SDL_MOUSEBUTTONDOWN:
/* Skip this step */
SetCurrentBinding(s_iCurrentBinding + 1);
break;
case SDL_KEYDOWN:
if (event.key.keysym.sym == SDLK_BACKSPACE || event.key.keysym.sym == SDLK_AC_BACK) {
SetCurrentBinding(s_iCurrentBinding - 1);
break;
}
if (event.key.keysym.sym == SDLK_SPACE) {
SetCurrentBinding(s_iCurrentBinding + 1);
break;
}
if ((event.key.keysym.sym != SDLK_ESCAPE)) {
break;
}
/* Fall through to signal quit */
case SDL_QUIT:
done = SDL_TRUE;
break;
default:
break;
}
}
SDL_Delay(15);
/* Wait 100 ms for joystick events to stop coming in,
in case a controller sends multiple events for a single control (e.g. axis and button for trigger)
*/
if (s_unPendingAdvanceTime && SDL_GetTicks() - s_unPendingAdvanceTime >= 100) {
SetCurrentBinding(s_iCurrentBinding + 1);
}
}
if (s_bBindingComplete) {
char mapping[1024];
char trimmed_name[128];
char *spot;
int iIndex;
char pszElement[12];
SDL_strlcpy(trimmed_name, name, SDL_arraysize(trimmed_name));
while (SDL_isspace(trimmed_name[0])) {
SDL_memmove(&trimmed_name[0], &trimmed_name[1], SDL_strlen(trimmed_name));
}
while (trimmed_name[0] && SDL_isspace(trimmed_name[SDL_strlen(trimmed_name) - 1])) {
trimmed_name[SDL_strlen(trimmed_name) - 1] = '\0';
}
while ((spot = SDL_strchr(trimmed_name, ',')) != NULL) {
SDL_memmove(spot, spot + 1, SDL_strlen(spot));
}
/* Initialize mapping with GUID and name */
SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), mapping, SDL_arraysize(mapping));
SDL_strlcat(mapping, ",", SDL_arraysize(mapping));
SDL_strlcat(mapping, trimmed_name, SDL_arraysize(mapping));
SDL_strlcat(mapping, ",", SDL_arraysize(mapping));
SDL_strlcat(mapping, "platform:", SDL_arraysize(mapping));
SDL_strlcat(mapping, SDL_GetPlatform(), SDL_arraysize(mapping));
SDL_strlcat(mapping, ",", SDL_arraysize(mapping));
for (iIndex = 0; iIndex < SDL_arraysize(s_arrBindings); ++iIndex) {
SDL_GameControllerExtendedBind *pBinding = &s_arrBindings[iIndex];
if (pBinding->bindType == SDL_CONTROLLER_BINDTYPE_NONE) {
continue;
}
if (iIndex < SDL_CONTROLLER_BUTTON_MAX) {
SDL_GameControllerButton eButton = (SDL_GameControllerButton)iIndex;
SDL_strlcat(mapping, SDL_GameControllerGetStringForButton(eButton), SDL_arraysize(mapping));
} else {
const char *pszAxisName;
switch (iIndex - SDL_CONTROLLER_BUTTON_MAX) {
case SDL_CONTROLLER_BINDING_AXIS_LEFTX_NEGATIVE:
if (!BMergeAxisBindings(iIndex)) {
SDL_strlcat(mapping, "-", SDL_arraysize(mapping));
}
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_LEFTX);
break;
case SDL_CONTROLLER_BINDING_AXIS_LEFTX_POSITIVE:
SDL_strlcat(mapping, "+", SDL_arraysize(mapping));
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_LEFTX);
break;
case SDL_CONTROLLER_BINDING_AXIS_LEFTY_NEGATIVE:
if (!BMergeAxisBindings(iIndex)) {
SDL_strlcat(mapping, "-", SDL_arraysize(mapping));
}
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_LEFTY);
break;
case SDL_CONTROLLER_BINDING_AXIS_LEFTY_POSITIVE:
SDL_strlcat(mapping, "+", SDL_arraysize(mapping));
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_LEFTY);
break;
case SDL_CONTROLLER_BINDING_AXIS_RIGHTX_NEGATIVE:
if (!BMergeAxisBindings(iIndex)) {
SDL_strlcat(mapping, "-", SDL_arraysize(mapping));
}
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_RIGHTX);
break;
case SDL_CONTROLLER_BINDING_AXIS_RIGHTX_POSITIVE:
SDL_strlcat(mapping, "+", SDL_arraysize(mapping));
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_RIGHTX);
break;
case SDL_CONTROLLER_BINDING_AXIS_RIGHTY_NEGATIVE:
if (!BMergeAxisBindings(iIndex)) {
SDL_strlcat(mapping, "-", SDL_arraysize(mapping));
}
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_RIGHTY);
break;
case SDL_CONTROLLER_BINDING_AXIS_RIGHTY_POSITIVE:
SDL_strlcat(mapping, "+", SDL_arraysize(mapping));
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_RIGHTY);
break;
case SDL_CONTROLLER_BINDING_AXIS_TRIGGERLEFT:
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_TRIGGERLEFT);
break;
case SDL_CONTROLLER_BINDING_AXIS_TRIGGERRIGHT:
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_TRIGGERRIGHT);
break;
}
SDL_strlcat(mapping, pszAxisName, SDL_arraysize(mapping));
}
SDL_strlcat(mapping, ":", SDL_arraysize(mapping));
pszElement[0] = '\0';
switch (pBinding->bindType) {
case SDL_CONTROLLER_BINDTYPE_BUTTON:
SDL_snprintf(pszElement, sizeof(pszElement), "b%d", pBinding->value.button);
break;
case SDL_CONTROLLER_BINDTYPE_AXIS:
if (pBinding->value.axis.axis_min == 0 && pBinding->value.axis.axis_max == SDL_JOYSTICK_AXIS_MIN) {
/* The negative half axis */
SDL_snprintf(pszElement, sizeof(pszElement), "-a%d", pBinding->value.axis.axis);
} else if (pBinding->value.axis.axis_min == 0 && pBinding->value.axis.axis_max == SDL_JOYSTICK_AXIS_MAX) {
/* The positive half axis */
SDL_snprintf(pszElement, sizeof(pszElement), "+a%d", pBinding->value.axis.axis);
} else {
SDL_snprintf(pszElement, sizeof(pszElement), "a%d", pBinding->value.axis.axis);
if (pBinding->value.axis.axis_min > pBinding->value.axis.axis_max) {
/* Invert the axis */
SDL_strlcat(pszElement, "~", SDL_arraysize(pszElement));
}
}
break;
case SDL_CONTROLLER_BINDTYPE_HAT:
SDL_snprintf(pszElement, sizeof(pszElement), "h%d.%d", pBinding->value.hat.hat, pBinding->value.hat.hat_mask);
break;
default:
SDL_assert(!"Unknown bind type");
break;
}
SDL_strlcat(mapping, pszElement, SDL_arraysize(mapping));
SDL_strlcat(mapping, ",", SDL_arraysize(mapping));
}
SDL_Log("Mapping:\n\n%s\n\n", mapping);
/* Print to stdout as well so the user can cat the output somewhere */
printf("%s\n", mapping);
}
SDL_free(s_arrAxisState);
s_arrAxisState = NULL;
SDL_DestroyRenderer(screen);
}
int
main(int argc, char *argv[])
{
const char *name;
int i;
SDL_Joystick *joystick;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize SDL (Note: video is required to start event loop) */
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
exit(1);
}
/* Create a window to display joystick axis position */
window = SDL_CreateWindow("Game Controller Map", SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH,
SCREEN_HEIGHT, 0);
if (window == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError());
return 2;
}
while (SDL_NumJoysticks() == 0) {
SDL_Event event;
while (SDL_PollEvent(&event) > 0) {
switch (event.type) {
case SDL_KEYDOWN:
if ((event.key.keysym.sym != SDLK_ESCAPE)) {
break;
}
/* Fall through to signal quit */
case SDL_QUIT:
done = SDL_TRUE;
break;
default:
break;
}
}
}
/* Print information about the joysticks */
SDL_Log("There are %d joysticks attached\n", SDL_NumJoysticks());
for (i = 0; i < SDL_NumJoysticks(); ++i) {
name = SDL_JoystickNameForIndex(i);
SDL_Log("Joystick %d: %s\n", i, name ? name : "Unknown Joystick");
joystick = SDL_JoystickOpen(i);
if (joystick == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_JoystickOpen(%d) failed: %s\n", i,
SDL_GetError());
} else {
char guid[64];
SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick),
guid, sizeof (guid));
SDL_Log(" axes: %d\n", SDL_JoystickNumAxes(joystick));
SDL_Log(" balls: %d\n", SDL_JoystickNumBalls(joystick));
SDL_Log(" hats: %d\n", SDL_JoystickNumHats(joystick));
SDL_Log(" buttons: %d\n", SDL_JoystickNumButtons(joystick));
SDL_Log("instance id: %d\n", SDL_JoystickInstanceID(joystick));
SDL_Log(" guid: %s\n", guid);
SDL_Log(" VID/PID: 0x%.4x/0x%.4x\n", SDL_JoystickGetVendor(joystick), SDL_JoystickGetProduct(joystick));
SDL_JoystickClose(joystick);
}
}
joystick = SDL_JoystickOpen(0);
if (joystick == NULL) {
SDL_Log("Couldn't open joystick 0: %s\n", SDL_GetError());
} else {
WatchJoystick(joystick);
SDL_JoystickClose(joystick);
}
SDL_DestroyWindow(window);
SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK);
return 0;
}
#else
int
main(int argc, char *argv[])
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL compiled without Joystick support.\n");
return 1;
}
#endif
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/controllermap.c | C | apache-2.0 | 31,259 |
Module['arguments'] = ['0'];
//Gamepads don't appear until a button is pressed and the joystick/gamepad tests expect one to be connected
Module['preRun'].push(function()
{
Module['print']("Waiting for gamepad...");
Module['addRunDependency']("gamepad");
window.addEventListener('gamepadconnected', function()
{
//OK, got one
Module['removeRunDependency']("gamepad");
}, false);
//chrome
if(!!navigator.webkitGetGamepads)
{
var timeout = function()
{
if(navigator.webkitGetGamepads()[0] !== undefined)
Module['removeRunDependency']("gamepad");
else
setTimeout(timeout, 100);
}
setTimeout(timeout, 100);
}
});
| YifuLiu/AliOS-Things | components/SDL2/test/emscripten/joystick-pre.js | JavaScript | apache-2.0 | 749 |
#!/bin/sh
#
# Build Universal binaries on Mac OS X, thanks Ryan!
#
# Usage: ./configure CC="sh gcc-fat.sh" && make && rm -rf ppc x86
# PowerPC compiler flags (10.2 runtime compatibility)
GCC_COMPILE_PPC="gcc-3.3 -arch ppc \
-DMAC_OS_X_VERSION_MIN_REQUIRED=1020 \
-nostdinc \
-F/Developer/SDKs/MacOSX10.2.8.sdk/System/Library/Frameworks \
-I/Developer/SDKs/MacOSX10.2.8.sdk/usr/include/gcc/darwin/3.3 \
-isystem /Developer/SDKs/MacOSX10.2.8.sdk/usr/include"
GCC_LINK_PPC="\
-L/Developer/SDKs/MacOSX10.2.8.sdk/usr/lib/gcc/darwin/3.3 \
-F/Developer/SDKs/MacOSX10.2.8.sdk/System/Library/Frameworks \
-Wl,-syslibroot,/Developer/SDKs/MacOSX10.2.8.sdk"
# Intel compiler flags (10.4 runtime compatibility)
GCC_COMPILE_X86="gcc-4.0 -arch i386 -mmacosx-version-min=10.4 \
-DMAC_OS_X_VERSION_MIN_REQUIRED=1040 \
-nostdinc \
-F/Developer/SDKs/MacOSX10.4u.sdk/System/Library/Frameworks \
-I/Developer/SDKs/MacOSX10.4u.sdk/usr/lib/gcc/i686-apple-darwin8/4.0.1/include \
-isystem /Developer/SDKs/MacOSX10.4u.sdk/usr/include"
GCC_LINK_X86="\
-L/Developer/SDKs/MacOSX10.4u.sdk/usr/lib/gcc/i686-apple-darwin8/4.0.0 \
-Wl,-syslibroot,/Developer/SDKs/MacOSX10.4u.sdk"
# Output both PowerPC and Intel object files
args="$*"
compile=yes
link=yes
while test x$1 != x; do
case $1 in
--version) exec gcc $1;;
-v) exec gcc $1;;
-V) exec gcc $1;;
-print-prog-name=*) exec gcc $1;;
-print-search-dirs) exec gcc $1;;
-E) GCC_COMPILE_PPC="$GCC_COMPILE_PPC -E"
GCC_COMPILE_X86="$GCC_COMPILE_X86 -E"
compile=no; link=no;;
-c) link=no;;
-o) output=$2;;
*.c|*.cc|*.cpp|*.S) source=$1;;
esac
shift
done
if test x$link = xyes; then
GCC_COMPILE_PPC="$GCC_COMPILE_PPC $GCC_LINK_PPC"
GCC_COMPILE_X86="$GCC_COMPILE_X86 $GCC_LINK_X86"
fi
if test x"$output" = x; then
if test x$link = xyes; then
output=a.out
elif test x$compile = xyes; then
output=`echo $source | sed -e 's|.*/||' -e 's|\(.*\)\.[^\.]*|\1|'`.o
fi
fi
if test x"$output" != x; then
dir=ppc/`dirname $output`
if test -d $dir; then
:
else
mkdir -p $dir
fi
fi
set -- $args
while test x$1 != x; do
if test -f "ppc/$1" && test "$1" != "$output"; then
ppc_args="$ppc_args ppc/$1"
else
ppc_args="$ppc_args $1"
fi
shift
done
$GCC_COMPILE_PPC $ppc_args || exit $?
if test x"$output" != x; then
cp $output ppc/$output
fi
if test x"$output" != x; then
dir=x86/`dirname $output`
if test -d $dir; then
:
else
mkdir -p $dir
fi
fi
set -- $args
while test x$1 != x; do
if test -f "x86/$1" && test "$1" != "$output"; then
x86_args="$x86_args x86/$1"
else
x86_args="$x86_args $1"
fi
shift
done
$GCC_COMPILE_X86 $x86_args || exit $?
if test x"$output" != x; then
cp $output x86/$output
fi
if test x"$output" != x; then
lipo -create -o $output ppc/$output x86/$output
fi
| YifuLiu/AliOS-Things | components/SDL2/test/gcc-fat.sh | Shell | apache-2.0 | 2,966 |
/*
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.
*/
/* Program to load a wave file and loop playing it using SDL audio */
/* loopwaves.c is much more robust in handling WAVE files --
This is only for simple WAVEs
*/
#include "SDL_config.h"
#include <stdio.h>
#include <stdlib.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL.h"
static struct
{
SDL_AudioSpec spec;
Uint8 *sound; /* Pointer to wave data */
Uint32 soundlen; /* Length of wave data */
int soundpos; /* Current play position */
} wave;
static SDL_AudioDeviceID device;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_Quit();
exit(rc);
}
static void
close_audio()
{
if (device != 0) {
SDL_CloseAudioDevice(device);
device = 0;
}
}
static void
open_audio()
{
/* Initialize fillerup() variables */
device = SDL_OpenAudioDevice(NULL, SDL_FALSE, &wave.spec, NULL, 0);
if (!device) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open audio: %s\n", SDL_GetError());
SDL_FreeWAV(wave.sound);
quit(2);
}
/* Let the audio run */
SDL_PauseAudioDevice(device, SDL_FALSE);
}
static void reopen_audio()
{
close_audio();
open_audio();
}
void SDLCALL
fillerup(void *unused, Uint8 * stream, int len)
{
Uint8 *waveptr;
int waveleft;
/* Set up the pointers */
waveptr = wave.sound + wave.soundpos;
waveleft = wave.soundlen - wave.soundpos;
/* Go! */
while (waveleft <= len) {
SDL_memcpy(stream, waveptr, waveleft);
stream += waveleft;
len -= waveleft;
waveptr = wave.sound;
waveleft = wave.soundlen;
wave.soundpos = 0;
}
SDL_memcpy(stream, waveptr, len);
wave.soundpos += len;
}
static int done = 0;
#ifdef __EMSCRIPTEN__
void
loop()
{
if(done || (SDL_GetAudioDeviceStatus(device) != SDL_AUDIO_PLAYING))
emscripten_cancel_main_loop();
}
#endif
int
main(int argc, char *argv[])
{
int i;
char filename[4096];
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Load the SDL library */
if (SDL_Init(SDL_INIT_AUDIO|SDL_INIT_EVENTS) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return (1);
}
if (argc > 1) {
SDL_strlcpy(filename, argv[1], sizeof(filename));
} else {
SDL_strlcpy(filename, "sample.wav", sizeof(filename));
}
/* Load the wave file into memory */
if (SDL_LoadWAV(filename, &wave.spec, &wave.sound, &wave.soundlen) == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s\n", filename, SDL_GetError());
quit(1);
}
wave.spec.callback = fillerup;
/* Show the list of available drivers */
SDL_Log("Available audio drivers:");
for (i = 0; i < SDL_GetNumAudioDrivers(); ++i) {
SDL_Log("%i: %s", i, SDL_GetAudioDriver(i));
}
SDL_Log("Using audio driver: %s\n", SDL_GetCurrentAudioDriver());
open_audio();
SDL_FlushEvents(SDL_AUDIODEVICEADDED, SDL_AUDIODEVICEREMOVED);
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
SDL_Event event;
while (SDL_PollEvent(&event) > 0) {
if (event.type == SDL_QUIT) {
done = 1;
}
if ((event.type == SDL_AUDIODEVICEADDED && !event.adevice.iscapture) ||
(event.type == SDL_AUDIODEVICEREMOVED && !event.adevice.iscapture && event.adevice.which == device)) {
reopen_audio();
}
}
SDL_Delay(100);
}
#endif
/* Clean up on signal */
close_audio();
SDL_FreeWAV(wave.sound);
SDL_Quit();
return (0);
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/loopwave.c | C | apache-2.0 | 4,308 |
/*
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.
*/
/* Program to load a wave file and loop playing it using SDL sound queueing */
#include <stdio.h>
#include <stdlib.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL.h"
#if HAVE_SIGNAL_H
#include <signal.h>
#endif
static struct
{
SDL_AudioSpec spec;
Uint8 *sound; /* Pointer to wave data */
Uint32 soundlen; /* Length of wave data */
} wave;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_Quit();
exit(rc);
}
static int done = 0;
void
poked(int sig)
{
done = 1;
}
void
loop()
{
#ifdef __EMSCRIPTEN__
if (done || (SDL_GetAudioStatus() != SDL_AUDIO_PLAYING)) {
emscripten_cancel_main_loop();
}
else
#endif
{
/* The device from SDL_OpenAudio() is always device #1. */
const Uint32 queued = SDL_GetQueuedAudioSize(1);
SDL_Log("Device has %u bytes queued.\n", (unsigned int) queued);
if (queued <= 8192) { /* time to requeue the whole thing? */
if (SDL_QueueAudio(1, wave.sound, wave.soundlen) == 0) {
SDL_Log("Device queued %u more bytes.\n", (unsigned int) wave.soundlen);
} else {
SDL_Log("Device FAILED to queue %u more bytes: %s\n", (unsigned int) wave.soundlen, SDL_GetError());
}
}
}
}
int
main(int argc, char *argv[])
{
char filename[4096];
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Load the SDL library */
if (SDL_Init(SDL_INIT_AUDIO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return (1);
}
if (argc > 1) {
SDL_strlcpy(filename, argv[1], sizeof(filename));
} else {
SDL_strlcpy(filename, "sample.wav", sizeof(filename));
}
/* Load the wave file into memory */
if (SDL_LoadWAV(filename, &wave.spec, &wave.sound, &wave.soundlen) == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s\n", filename, SDL_GetError());
quit(1);
}
wave.spec.callback = NULL; /* we'll push audio. */
#if HAVE_SIGNAL_H
/* Set the signals */
#ifdef SIGHUP
signal(SIGHUP, poked);
#endif
signal(SIGINT, poked);
#ifdef SIGQUIT
signal(SIGQUIT, poked);
#endif
signal(SIGTERM, poked);
#endif /* HAVE_SIGNAL_H */
/* Initialize fillerup() variables */
if (SDL_OpenAudio(&wave.spec, NULL) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open audio: %s\n", SDL_GetError());
SDL_FreeWAV(wave.sound);
quit(2);
}
/*static x[99999]; SDL_QueueAudio(1, x, sizeof (x));*/
/* Let the audio run */
SDL_PauseAudio(0);
done = 0;
/* Note that we stuff the entire audio buffer into the queue in one
shot. Most apps would want to feed it a little at a time, as it
plays, but we're going for simplicity here. */
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done && (SDL_GetAudioStatus() == SDL_AUDIO_PLAYING))
{
loop();
SDL_Delay(100); /* let it play for awhile. */
}
#endif
/* Clean up on signal */
SDL_CloseAudio();
SDL_FreeWAV(wave.sound);
SDL_Quit();
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/loopwavequeue.c | C | apache-2.0 | 3,805 |
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# GNU Makefile based on shared rules provided by the Native Client SDK.
# See README.Makefiles for more details.
VALID_TOOLCHAINS := pnacl
# NACL_SDK_ROOT ?= $(abspath $(CURDIR)/../../..)
include $(NACL_SDK_ROOT)/tools/common.mk
TARGET = sdl_app
DEPS = ppapi_simple nacl_io
# ppapi_simple and SDL2 end up being listed twice due to dependency solving issues -- Gabriel
LIBS = SDL2_test SDL2 ppapi_simple SDL2main SDL2 $(DEPS) ppapi_gles2 ppapi_cpp ppapi pthread
CFLAGS := -Wall
SOURCES ?= testgles2.c
# Build rules generated by macros from common.mk:
# Overriden macro from NACL SDK to be able to customize the library search path -- Gabriel
# Specific Link Macro
#
# $1 = Target Name
# $2 = List of inputs
# $3 = List of libs
# $4 = List of deps
# $5 = List of lib dirs
# $6 = Other Linker Args
#
# For debugging, we translate the pre-finalized .bc file.
#
define LINKER_RULE
all: $(1).pexe
$(1)_x86_32.nexe : $(1).bc
$(call LOG,TRANSLATE,$$@,$(PNACL_TRANSLATE) --allow-llvm-bitcode-input -arch x86-32 $$^ -o $$@)
$(1)_x86_64.nexe : $(1).bc
$(call LOG,TRANSLATE,$$@,$(PNACL_TRANSLATE) --allow-llvm-bitcode-input -arch x86-64 $$^ -o $$@)
$(1)_arm.nexe : $(1).bc
$(call LOG,TRANSLATE,$$@,$(PNACL_TRANSLATE) --allow-llvm-bitcode-input -arch arm $$^ -o $$@)
$(1).pexe: $(1).bc
$(call LOG,FINALIZE,$$@,$(PNACL_FINALIZE) -o $$@ $$^)
$(1).bc: $(2) $(foreach dep,$(4),$(STAMPDIR)/$(dep).stamp)
$(call LOG,LINK,$$@,$(PNACL_LINK) -o $$@ $(2) $(PNACL_LDFLAGS) $(foreach path,$(5),-L$(path)/pnacl/$(CONFIG)) -L./lib $(foreach lib,$(3),-l$(lib)) $(6))
endef
$(foreach dep,$(DEPS),$(eval $(call DEPEND_RULE,$(dep))))
$(foreach src,$(SOURCES),$(eval $(call COMPILE_RULE,$(src),$(CFLAGS))))
ifeq ($(CONFIG),Release)
$(eval $(call LINK_RULE,$(TARGET)_unstripped,$(SOURCES),$(LIBS),$(DEPS)))
$(eval $(call STRIP_RULE,$(TARGET),$(TARGET)_unstripped))
else
$(eval $(call LINK_RULE,$(TARGET),$(SOURCES),$(LIBS),$(DEPS)))
endif
$(eval $(call NMF_RULE,$(TARGET),))
| YifuLiu/AliOS-Things | components/SDL2/test/nacl/Makefile | Makefile | apache-2.0 | 2,130 |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
function makeURL(toolchain, config) {
return 'index.html?tc=' + toolchain + '&config=' + config;
}
function createWindow(url) {
console.log('loading ' + url);
chrome.app.window.create(url, {
width: 1024,
height: 800,
frame: 'none'
});
}
function onLaunched(launchData) {
// Send and XHR to get the URL to load from a configuration file.
// Normally you won't need to do this; just call:
//
// chrome.app.window.create('<your url>', {...});
//
// In the SDK we want to be able to load different URLs (for different
// toolchain/config combinations) from the commandline, so we to read
// this information from the file "run_package_config".
var xhr = new XMLHttpRequest();
xhr.open('GET', 'run_package_config', true);
xhr.onload = function() {
var toolchain_config = this.responseText.split(' ');
createWindow(makeURL.apply(null, toolchain_config));
};
xhr.onerror = function() {
// Can't find the config file, just load the default.
createWindow('index.html');
};
xhr.send();
}
chrome.app.runtime.onLaunched.addListener(onLaunched);
| YifuLiu/AliOS-Things | components/SDL2/test/nacl/background.js | JavaScript | apache-2.0 | 1,272 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Set to true when the Document is loaded IFF "test=true" is in the query
// string.
var isTest = false;
// Set to true when loading a "Release" NaCl module, false when loading a
// "Debug" NaCl module.
var isRelease = true;
// Javascript module pattern:
// see http://en.wikipedia.org/wiki/Unobtrusive_JavaScript#Namespaces
// In essence, we define an anonymous function which is immediately called and
// returns a new object. The new object contains only the exported definitions;
// all other definitions in the anonymous function are inaccessible to external
// code.
var common = (function() {
function isHostToolchain(tool) {
return tool == 'win' || tool == 'linux' || tool == 'mac';
}
/**
* Return the mime type for NaCl plugin.
*
* @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc.
* @return {string} The mime-type for the kind of NaCl plugin matching
* the given toolchain.
*/
function mimeTypeForTool(tool) {
// For NaCl modules use application/x-nacl.
var mimetype = 'application/x-nacl';
if (isHostToolchain(tool)) {
// For non-NaCl PPAPI plugins use the x-ppapi-debug/release
// mime type.
if (isRelease)
mimetype = 'application/x-ppapi-release';
else
mimetype = 'application/x-ppapi-debug';
} else if (tool == 'pnacl') {
mimetype = 'application/x-pnacl';
}
return mimetype;
}
/**
* Check if the browser supports NaCl plugins.
*
* @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc.
* @return {bool} True if the browser supports the type of NaCl plugin
* produced by the given toolchain.
*/
function browserSupportsNaCl(tool) {
// Assume host toolchains always work with the given browser.
// The below mime-type checking might not work with
// --register-pepper-plugins.
if (isHostToolchain(tool)) {
return true;
}
var mimetype = mimeTypeForTool(tool);
return navigator.mimeTypes[mimetype] !== undefined;
}
/**
* Inject a script into the DOM, and call a callback when it is loaded.
*
* @param {string} url The url of the script to load.
* @param {Function} onload The callback to call when the script is loaded.
* @param {Function} onerror The callback to call if the script fails to load.
*/
function injectScript(url, onload, onerror) {
var scriptEl = document.createElement('script');
scriptEl.type = 'text/javascript';
scriptEl.src = url;
scriptEl.onload = onload;
if (onerror) {
scriptEl.addEventListener('error', onerror, false);
}
document.head.appendChild(scriptEl);
}
/**
* Run all tests for this example.
*
* @param {Object} moduleEl The module DOM element.
*/
function runTests(moduleEl) {
console.log('runTests()');
common.tester = new Tester();
// All NaCl SDK examples are OK if the example exits cleanly; (i.e. the
// NaCl module returns 0 or calls exit(0)).
//
// Without this exception, the browser_tester thinks that the module
// has crashed.
common.tester.exitCleanlyIsOK();
common.tester.addAsyncTest('loaded', function(test) {
test.pass();
});
if (typeof window.addTests !== 'undefined') {
window.addTests();
}
common.tester.waitFor(moduleEl);
common.tester.run();
}
/**
* Create the Native Client <embed> element as a child of the DOM element
* named "listener".
*
* @param {string} name The name of the example.
* @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc.
* @param {string} path Directory name where .nmf file can be found.
* @param {number} width The width to create the plugin.
* @param {number} height The height to create the plugin.
* @param {Object} attrs Dictionary of attributes to set on the module.
*/
function createNaClModule(name, tool, path, width, height, attrs) {
var moduleEl = document.createElement('embed');
moduleEl.setAttribute('name', 'nacl_module');
moduleEl.setAttribute('id', 'nacl_module');
moduleEl.setAttribute('width', width);
moduleEl.setAttribute('height', height);
moduleEl.setAttribute('path', path);
moduleEl.setAttribute('src', path + '/' + name + '.nmf');
// Add any optional arguments
if (attrs) {
for (var key in attrs) {
moduleEl.setAttribute(key, attrs[key]);
}
}
var mimetype = mimeTypeForTool(tool);
moduleEl.setAttribute('type', mimetype);
// The <EMBED> element is wrapped inside a <DIV>, which has both a 'load'
// and a 'message' event listener attached. This wrapping method is used
// instead of attaching the event listeners directly to the <EMBED> element
// to ensure that the listeners are active before the NaCl module 'load'
// event fires.
var listenerDiv = document.getElementById('listener');
listenerDiv.appendChild(moduleEl);
// Request the offsetTop property to force a relayout. As of Apr 10, 2014
// this is needed if the module is being loaded on a Chrome App's
// background page (see crbug.com/350445).
moduleEl.offsetTop;
// Host plugins don't send a moduleDidLoad message. We'll fake it here.
var isHost = isHostToolchain(tool);
if (isHost) {
window.setTimeout(function() {
moduleEl.readyState = 1;
moduleEl.dispatchEvent(new CustomEvent('loadstart'));
moduleEl.readyState = 4;
moduleEl.dispatchEvent(new CustomEvent('load'));
moduleEl.dispatchEvent(new CustomEvent('loadend'));
}, 100); // 100 ms
}
// This is code that is only used to test the SDK.
if (isTest) {
var loadNaClTest = function() {
injectScript('nacltest.js', function() {
runTests(moduleEl);
});
};
// Try to load test.js for the example. Whether or not it exists, load
// nacltest.js.
injectScript('test.js', loadNaClTest, loadNaClTest);
}
}
/**
* Add the default "load" and "message" event listeners to the element with
* id "listener".
*
* The "load" event is sent when the module is successfully loaded. The
* "message" event is sent when the naclModule posts a message using
* PPB_Messaging.PostMessage() (in C) or pp::Instance().PostMessage() (in
* C++).
*/
function attachDefaultListeners() {
var listenerDiv = document.getElementById('listener');
listenerDiv.addEventListener('load', moduleDidLoad, true);
listenerDiv.addEventListener('message', handleMessage, true);
listenerDiv.addEventListener('error', handleError, true);
listenerDiv.addEventListener('crash', handleCrash, true);
if (typeof window.attachListeners !== 'undefined') {
window.attachListeners();
}
}
/**
* Called when the NaCl module fails to load.
*
* This event listener is registered in createNaClModule above.
*/
function handleError(event) {
// We can't use common.naclModule yet because the module has not been
// loaded.
var moduleEl = document.getElementById('nacl_module');
updateStatus('ERROR [' + moduleEl.lastError + ']');
}
/**
* Called when the Browser can not communicate with the Module
*
* This event listener is registered in attachDefaultListeners above.
*/
function handleCrash(event) {
if (common.naclModule.exitStatus == -1) {
updateStatus('CRASHED');
} else {
updateStatus('EXITED [' + common.naclModule.exitStatus + ']');
}
if (typeof window.handleCrash !== 'undefined') {
window.handleCrash(common.naclModule.lastError);
}
}
/**
* Called when the NaCl module is loaded.
*
* This event listener is registered in attachDefaultListeners above.
*/
function moduleDidLoad() {
common.naclModule = document.getElementById('nacl_module');
updateStatus('RUNNING');
if (typeof window.moduleDidLoad !== 'undefined') {
window.moduleDidLoad();
}
}
/**
* Hide the NaCl module's embed element.
*
* We don't want to hide by default; if we do, it is harder to determine that
* a plugin failed to load. Instead, call this function inside the example's
* "moduleDidLoad" function.
*
*/
function hideModule() {
// Setting common.naclModule.style.display = "None" doesn't work; the
// module will no longer be able to receive postMessages.
common.naclModule.style.height = '0';
}
/**
* Remove the NaCl module from the page.
*/
function removeModule() {
common.naclModule.parentNode.removeChild(common.naclModule);
common.naclModule = null;
}
/**
* Return true when |s| starts with the string |prefix|.
*
* @param {string} s The string to search.
* @param {string} prefix The prefix to search for in |s|.
*/
function startsWith(s, prefix) {
// indexOf would search the entire string, lastIndexOf(p, 0) only checks at
// the first index. See: http://stackoverflow.com/a/4579228
return s.lastIndexOf(prefix, 0) === 0;
}
/** Maximum length of logMessageArray. */
var kMaxLogMessageLength = 20;
/** An array of messages to display in the element with id "log". */
var logMessageArray = [];
/**
* Add a message to an element with id "log".
*
* This function is used by the default "log:" message handler.
*
* @param {string} message The message to log.
*/
function logMessage(message) {
logMessageArray.push(message);
if (logMessageArray.length > kMaxLogMessageLength)
logMessageArray.shift();
document.getElementById('log').textContent = logMessageArray.join('\n');
console.log(message);
}
/**
*/
var defaultMessageTypes = {
'alert': alert,
'log': logMessage
};
/**
* Called when the NaCl module sends a message to JavaScript (via
* PPB_Messaging.PostMessage())
*
* This event listener is registered in createNaClModule above.
*
* @param {Event} message_event A message event. message_event.data contains
* the data sent from the NaCl module.
*/
function handleMessage(message_event) {
if (typeof message_event.data === 'string') {
for (var type in defaultMessageTypes) {
if (defaultMessageTypes.hasOwnProperty(type)) {
if (startsWith(message_event.data, type + ':')) {
func = defaultMessageTypes[type];
func(message_event.data.slice(type.length + 1));
return;
}
}
}
}
if (typeof window.handleMessage !== 'undefined') {
window.handleMessage(message_event);
return;
}
logMessage('Unhandled message: ' + message_event.data);
}
/**
* Called when the DOM content has loaded; i.e. the page's document is fully
* parsed. At this point, we can safely query any elements in the document via
* document.querySelector, document.getElementById, etc.
*
* @param {string} name The name of the example.
* @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc.
* @param {string} path Directory name where .nmf file can be found.
* @param {number} width The width to create the plugin.
* @param {number} height The height to create the plugin.
* @param {Object} attrs Optional dictionary of additional attributes.
*/
function domContentLoaded(name, tool, path, width, height, attrs) {
// If the page loads before the Native Client module loads, then set the
// status message indicating that the module is still loading. Otherwise,
// do not change the status message.
updateStatus('Page loaded.');
if (!browserSupportsNaCl(tool)) {
updateStatus(
'Browser does not support NaCl (' + tool + '), or NaCl is disabled');
} else if (common.naclModule == null) {
updateStatus('Creating embed: ' + tool);
// We use a non-zero sized embed to give Chrome space to place the bad
// plug-in graphic, if there is a problem.
width = typeof width !== 'undefined' ? width : 200;
height = typeof height !== 'undefined' ? height : 200;
attachDefaultListeners();
createNaClModule(name, tool, path, width, height, attrs);
} else {
// It's possible that the Native Client module onload event fired
// before the page's onload event. In this case, the status message
// will reflect 'SUCCESS', but won't be displayed. This call will
// display the current message.
updateStatus('Waiting.');
}
}
/** Saved text to display in the element with id 'statusField'. */
var statusText = 'NO-STATUSES';
/**
* Set the global status message. If the element with id 'statusField'
* exists, then set its HTML to the status message as well.
*
* @param {string} opt_message The message to set. If null or undefined, then
* set element 'statusField' to the message from the last call to
* updateStatus.
*/
function updateStatus(opt_message) {
if (opt_message) {
statusText = opt_message;
}
var statusField = document.getElementById('statusField');
if (statusField) {
statusField.innerHTML = statusText;
}
}
// The symbols to export.
return {
/** A reference to the NaCl module, once it is loaded. */
naclModule: null,
attachDefaultListeners: attachDefaultListeners,
domContentLoaded: domContentLoaded,
createNaClModule: createNaClModule,
hideModule: hideModule,
removeModule: removeModule,
logMessage: logMessage,
updateStatus: updateStatus
};
}());
// Listen for the DOM content to be loaded. This event is fired when parsing of
// the page's document has finished.
document.addEventListener('DOMContentLoaded', function() {
var body = document.body;
// The data-* attributes on the body can be referenced via body.dataset.
if (body.dataset) {
var loadFunction;
if (!body.dataset.customLoad) {
loadFunction = common.domContentLoaded;
} else if (typeof window.domContentLoaded !== 'undefined') {
loadFunction = window.domContentLoaded;
}
// From https://developer.mozilla.org/en-US/docs/DOM/window.location
var searchVars = {};
if (window.location.search.length > 1) {
var pairs = window.location.search.substr(1).split('&');
for (var key_ix = 0; key_ix < pairs.length; key_ix++) {
var keyValue = pairs[key_ix].split('=');
searchVars[unescape(keyValue[0])] =
keyValue.length > 1 ? unescape(keyValue[1]) : '';
}
}
if (loadFunction) {
var toolchains = body.dataset.tools.split(' ');
var configs = body.dataset.configs.split(' ');
var attrs = {};
if (body.dataset.attrs) {
var attr_list = body.dataset.attrs.split(' ');
for (var key in attr_list) {
var attr = attr_list[key].split('=');
var key = attr[0];
var value = attr[1];
attrs[key] = value;
}
}
var tc = toolchains.indexOf(searchVars.tc) !== -1 ?
searchVars.tc : toolchains[0];
// If the config value is included in the search vars, use that.
// Otherwise default to Release if it is valid, or the first value if
// Release is not valid.
if (configs.indexOf(searchVars.config) !== -1)
var config = searchVars.config;
else if (configs.indexOf('Release') !== -1)
var config = 'Release';
else
var config = configs[0];
var pathFormat = body.dataset.path;
var path = pathFormat.replace('{tc}', tc).replace('{config}', config);
isTest = searchVars.test === 'true';
isRelease = path.toLowerCase().indexOf('release') != -1;
loadFunction(body.dataset.name, tc, path, body.dataset.width,
body.dataset.height, attrs);
}
}
});
| YifuLiu/AliOS-Things | components/SDL2/test/nacl/common.js | JavaScript | apache-2.0 | 15,989 |
<!DOCTYPE html>
<html>
<!--
Copyright (c) 2012 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<head>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="-1">
<title>SDL NACL Test</title>
<script type="text/javascript" src="common.js"></script>
</head>
<body data-width="640" data-height="640" data-name="sdl_app" data-tools="pnacl" data-configs="Debug Release" data-path="{tc}/{config}">
<h1>SDL NACL Test</h1>
<h2>Status: <code id="statusField">NO-STATUS</code></h2>
<!-- The NaCl plugin will be embedded inside the element with id "listener".
See common.js.-->
<div id="listener"></div>
</body>
</html>
| YifuLiu/AliOS-Things | components/SDL2/test/nacl/index.html | HTML | apache-2.0 | 755 |
/*
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.
*/
#include <stdio.h>
#include "SDL.h"
/*
Absolutely basic tests just to see if we get the expected value
after calling each function.
*/
static
char *
tf(SDL_bool tf)
{
static char *t = "TRUE";
static char *f = "FALSE";
if (tf)
{
return t;
}
return f;
}
static
void RunBasicTest()
{
int value;
SDL_SpinLock lock = 0;
SDL_atomic_t v;
SDL_bool tfret = SDL_FALSE;
SDL_Log("\nspin lock---------------------------------------\n\n");
SDL_AtomicLock(&lock);
SDL_Log("AtomicLock lock=%d\n", lock);
SDL_AtomicUnlock(&lock);
SDL_Log("AtomicUnlock lock=%d\n", lock);
SDL_Log("\natomic -----------------------------------------\n\n");
SDL_AtomicSet(&v, 0);
tfret = SDL_AtomicSet(&v, 10) == 0 ? SDL_TRUE : SDL_FALSE;
SDL_Log("AtomicSet(10) tfret=%s val=%d\n", tf(tfret), SDL_AtomicGet(&v));
tfret = SDL_AtomicAdd(&v, 10) == 10 ? SDL_TRUE : SDL_FALSE;
SDL_Log("AtomicAdd(10) tfret=%s val=%d\n", tf(tfret), SDL_AtomicGet(&v));
SDL_AtomicSet(&v, 0);
SDL_AtomicIncRef(&v);
tfret = (SDL_AtomicGet(&v) == 1) ? SDL_TRUE : SDL_FALSE;
SDL_Log("AtomicIncRef() tfret=%s val=%d\n", tf(tfret), SDL_AtomicGet(&v));
SDL_AtomicIncRef(&v);
tfret = (SDL_AtomicGet(&v) == 2) ? SDL_TRUE : SDL_FALSE;
SDL_Log("AtomicIncRef() tfret=%s val=%d\n", tf(tfret), SDL_AtomicGet(&v));
tfret = (SDL_AtomicDecRef(&v) == SDL_FALSE) ? SDL_TRUE : SDL_FALSE;
SDL_Log("AtomicDecRef() tfret=%s val=%d\n", tf(tfret), SDL_AtomicGet(&v));
tfret = (SDL_AtomicDecRef(&v) == SDL_TRUE) ? SDL_TRUE : SDL_FALSE;
SDL_Log("AtomicDecRef() tfret=%s val=%d\n", tf(tfret), SDL_AtomicGet(&v));
SDL_AtomicSet(&v, 10);
tfret = (SDL_AtomicCAS(&v, 0, 20) == SDL_FALSE) ? SDL_TRUE : SDL_FALSE;
SDL_Log("AtomicCAS() tfret=%s val=%d\n", tf(tfret), SDL_AtomicGet(&v));
value = SDL_AtomicGet(&v);
tfret = (SDL_AtomicCAS(&v, value, 20) == SDL_TRUE) ? SDL_TRUE : SDL_FALSE;
SDL_Log("AtomicCAS() tfret=%s val=%d\n", tf(tfret), SDL_AtomicGet(&v));
}
/**************************************************************************/
/* Atomic operation test
* Adapted with permission from code by Michael Davidsaver at:
* http://bazaar.launchpad.net/~mdavidsaver/epics-base/atomic/revision/12105#src/libCom/test/epicsAtomicTest.c
* Original copyright 2010 Brookhaven Science Associates as operator of Brookhaven National Lab
* http://www.aps.anl.gov/epics/license/open.php
*/
/* Tests semantics of atomic operations. Also a stress test
* to see if they are really atomic.
*
* Several threads adding to the same variable.
* at the end the value is compared with the expected
* and with a non-atomic counter.
*/
/* Number of concurrent incrementers */
#define NThreads 2
#define CountInc 100
#define VALBITS (sizeof(atomicValue)*8)
#define atomicValue int
#define CountTo ((atomicValue)((unsigned int)(1<<(VALBITS-1))-1))
#define NInter (CountTo/CountInc/NThreads)
#define Expect (CountTo-NInter*CountInc*NThreads)
enum {
CountTo_GreaterThanZero = CountTo > 0,
};
SDL_COMPILE_TIME_ASSERT(size, CountTo_GreaterThanZero); /* check for rollover */
static SDL_atomic_t good = { 42 };
static atomicValue bad = 42;
static SDL_atomic_t threadsRunning;
static SDL_sem *threadDone;
static
int SDLCALL adder(void* junk)
{
unsigned long N=NInter;
SDL_Log("Thread subtracting %d %lu times\n",CountInc,N);
while (N--) {
SDL_AtomicAdd(&good, -CountInc);
bad-=CountInc;
}
SDL_AtomicAdd(&threadsRunning, -1);
SDL_SemPost(threadDone);
return 0;
}
static
void runAdder(void)
{
Uint32 start, end;
int T=NThreads;
start = SDL_GetTicks();
threadDone = SDL_CreateSemaphore(0);
SDL_AtomicSet(&threadsRunning, NThreads);
while (T--)
SDL_CreateThread(adder, "Adder", NULL);
while (SDL_AtomicGet(&threadsRunning) > 0)
SDL_SemWait(threadDone);
SDL_DestroySemaphore(threadDone);
end = SDL_GetTicks();
SDL_Log("Finished in %f sec\n", (end - start) / 1000.f);
}
static
void RunEpicTest()
{
int b;
atomicValue v;
SDL_Log("\nepic test---------------------------------------\n\n");
SDL_Log("Size asserted to be >= 32-bit\n");
SDL_assert(sizeof(atomicValue)>=4);
SDL_Log("Check static initializer\n");
v=SDL_AtomicGet(&good);
SDL_assert(v==42);
SDL_assert(bad==42);
SDL_Log("Test negative values\n");
SDL_AtomicSet(&good, -5);
v=SDL_AtomicGet(&good);
SDL_assert(v==-5);
SDL_Log("Verify maximum value\n");
SDL_AtomicSet(&good, CountTo);
v=SDL_AtomicGet(&good);
SDL_assert(v==CountTo);
SDL_Log("Test compare and exchange\n");
b=SDL_AtomicCAS(&good, 500, 43);
SDL_assert(!b); /* no swap since CountTo!=500 */
v=SDL_AtomicGet(&good);
SDL_assert(v==CountTo); /* ensure no swap */
b=SDL_AtomicCAS(&good, CountTo, 44);
SDL_assert(!!b); /* will swap */
v=SDL_AtomicGet(&good);
SDL_assert(v==44);
SDL_Log("Test Add\n");
v=SDL_AtomicAdd(&good, 1);
SDL_assert(v==44);
v=SDL_AtomicGet(&good);
SDL_assert(v==45);
v=SDL_AtomicAdd(&good, 10);
SDL_assert(v==45);
v=SDL_AtomicGet(&good);
SDL_assert(v==55);
SDL_Log("Test Add (Negative values)\n");
v=SDL_AtomicAdd(&good, -20);
SDL_assert(v==55);
v=SDL_AtomicGet(&good);
SDL_assert(v==35);
v=SDL_AtomicAdd(&good, -50); /* crossing zero down */
SDL_assert(v==35);
v=SDL_AtomicGet(&good);
SDL_assert(v==-15);
v=SDL_AtomicAdd(&good, 30); /* crossing zero up */
SDL_assert(v==-15);
v=SDL_AtomicGet(&good);
SDL_assert(v==15);
SDL_Log("Reset before count down test\n");
SDL_AtomicSet(&good, CountTo);
v=SDL_AtomicGet(&good);
SDL_assert(v==CountTo);
bad=CountTo;
SDL_assert(bad==CountTo);
SDL_Log("Counting down from %d, Expect %d remaining\n",CountTo,Expect);
runAdder();
v=SDL_AtomicGet(&good);
SDL_Log("Atomic %d Non-Atomic %d\n",v,bad);
SDL_assert(v==Expect);
SDL_assert(bad!=Expect);
}
/* End atomic operation test */
/**************************************************************************/
/**************************************************************************/
/* Lock-free FIFO test */
/* This is useful to test the impact of another thread locking the queue
entirely for heavy-weight manipulation.
*/
#define TEST_SPINLOCK_FIFO
#define NUM_READERS 4
#define NUM_WRITERS 4
#define EVENTS_PER_WRITER 1000000
/* The number of entries must be a power of 2 */
#define MAX_ENTRIES 256
#define WRAP_MASK (MAX_ENTRIES-1)
typedef struct
{
SDL_atomic_t sequence;
SDL_Event event;
} SDL_EventQueueEntry;
typedef struct
{
SDL_EventQueueEntry entries[MAX_ENTRIES];
char cache_pad1[SDL_CACHELINE_SIZE-((sizeof(SDL_EventQueueEntry)*MAX_ENTRIES)%SDL_CACHELINE_SIZE)];
SDL_atomic_t enqueue_pos;
char cache_pad2[SDL_CACHELINE_SIZE-sizeof(SDL_atomic_t)];
SDL_atomic_t dequeue_pos;
char cache_pad3[SDL_CACHELINE_SIZE-sizeof(SDL_atomic_t)];
#ifdef TEST_SPINLOCK_FIFO
SDL_SpinLock lock;
SDL_atomic_t rwcount;
SDL_atomic_t watcher;
char cache_pad4[SDL_CACHELINE_SIZE-sizeof(SDL_SpinLock)-2*sizeof(SDL_atomic_t)];
#endif
SDL_atomic_t active;
/* Only needed for the mutex test */
SDL_mutex *mutex;
} SDL_EventQueue;
static void InitEventQueue(SDL_EventQueue *queue)
{
int i;
for (i = 0; i < MAX_ENTRIES; ++i) {
SDL_AtomicSet(&queue->entries[i].sequence, i);
}
SDL_AtomicSet(&queue->enqueue_pos, 0);
SDL_AtomicSet(&queue->dequeue_pos, 0);
#ifdef TEST_SPINLOCK_FIFO
queue->lock = 0;
SDL_AtomicSet(&queue->rwcount, 0);
SDL_AtomicSet(&queue->watcher, 0);
#endif
SDL_AtomicSet(&queue->active, 1);
}
static SDL_bool EnqueueEvent_LockFree(SDL_EventQueue *queue, const SDL_Event *event)
{
SDL_EventQueueEntry *entry;
unsigned queue_pos;
unsigned entry_seq;
int delta;
SDL_bool status;
#ifdef TEST_SPINLOCK_FIFO
/* This is a gate so an external thread can lock the queue */
SDL_AtomicLock(&queue->lock);
SDL_assert(SDL_AtomicGet(&queue->watcher) == 0);
SDL_AtomicIncRef(&queue->rwcount);
SDL_AtomicUnlock(&queue->lock);
#endif
queue_pos = (unsigned)SDL_AtomicGet(&queue->enqueue_pos);
for ( ; ; ) {
entry = &queue->entries[queue_pos & WRAP_MASK];
entry_seq = (unsigned)SDL_AtomicGet(&entry->sequence);
delta = (int)(entry_seq - queue_pos);
if (delta == 0) {
/* The entry and the queue position match, try to increment the queue position */
if (SDL_AtomicCAS(&queue->enqueue_pos, (int)queue_pos, (int)(queue_pos+1))) {
/* We own the object, fill it! */
entry->event = *event;
SDL_AtomicSet(&entry->sequence, (int)(queue_pos + 1));
status = SDL_TRUE;
break;
}
} else if (delta < 0) {
/* We ran into an old queue entry, which means it still needs to be dequeued */
status = SDL_FALSE;
break;
} else {
/* We ran into a new queue entry, get the new queue position */
queue_pos = (unsigned)SDL_AtomicGet(&queue->enqueue_pos);
}
}
#ifdef TEST_SPINLOCK_FIFO
SDL_AtomicDecRef(&queue->rwcount);
#endif
return status;
}
static SDL_bool DequeueEvent_LockFree(SDL_EventQueue *queue, SDL_Event *event)
{
SDL_EventQueueEntry *entry;
unsigned queue_pos;
unsigned entry_seq;
int delta;
SDL_bool status;
#ifdef TEST_SPINLOCK_FIFO
/* This is a gate so an external thread can lock the queue */
SDL_AtomicLock(&queue->lock);
SDL_assert(SDL_AtomicGet(&queue->watcher) == 0);
SDL_AtomicIncRef(&queue->rwcount);
SDL_AtomicUnlock(&queue->lock);
#endif
queue_pos = (unsigned)SDL_AtomicGet(&queue->dequeue_pos);
for ( ; ; ) {
entry = &queue->entries[queue_pos & WRAP_MASK];
entry_seq = (unsigned)SDL_AtomicGet(&entry->sequence);
delta = (int)(entry_seq - (queue_pos + 1));
if (delta == 0) {
/* The entry and the queue position match, try to increment the queue position */
if (SDL_AtomicCAS(&queue->dequeue_pos, (int)queue_pos, (int)(queue_pos+1))) {
/* We own the object, fill it! */
*event = entry->event;
SDL_AtomicSet(&entry->sequence, (int)(queue_pos+MAX_ENTRIES));
status = SDL_TRUE;
break;
}
} else if (delta < 0) {
/* We ran into an old queue entry, which means we've hit empty */
status = SDL_FALSE;
break;
} else {
/* We ran into a new queue entry, get the new queue position */
queue_pos = (unsigned)SDL_AtomicGet(&queue->dequeue_pos);
}
}
#ifdef TEST_SPINLOCK_FIFO
SDL_AtomicDecRef(&queue->rwcount);
#endif
return status;
}
static SDL_bool EnqueueEvent_Mutex(SDL_EventQueue *queue, const SDL_Event *event)
{
SDL_EventQueueEntry *entry;
unsigned queue_pos;
unsigned entry_seq;
int delta;
SDL_bool status = SDL_FALSE;
SDL_LockMutex(queue->mutex);
queue_pos = (unsigned)queue->enqueue_pos.value;
entry = &queue->entries[queue_pos & WRAP_MASK];
entry_seq = (unsigned)entry->sequence.value;
delta = (int)(entry_seq - queue_pos);
if (delta == 0) {
++queue->enqueue_pos.value;
/* We own the object, fill it! */
entry->event = *event;
entry->sequence.value = (int)(queue_pos + 1);
status = SDL_TRUE;
} else if (delta < 0) {
/* We ran into an old queue entry, which means it still needs to be dequeued */
} else {
SDL_Log("ERROR: mutex failed!\n");
}
SDL_UnlockMutex(queue->mutex);
return status;
}
static SDL_bool DequeueEvent_Mutex(SDL_EventQueue *queue, SDL_Event *event)
{
SDL_EventQueueEntry *entry;
unsigned queue_pos;
unsigned entry_seq;
int delta;
SDL_bool status = SDL_FALSE;
SDL_LockMutex(queue->mutex);
queue_pos = (unsigned)queue->dequeue_pos.value;
entry = &queue->entries[queue_pos & WRAP_MASK];
entry_seq = (unsigned)entry->sequence.value;
delta = (int)(entry_seq - (queue_pos + 1));
if (delta == 0) {
++queue->dequeue_pos.value;
/* We own the object, fill it! */
*event = entry->event;
entry->sequence.value = (int)(queue_pos + MAX_ENTRIES);
status = SDL_TRUE;
} else if (delta < 0) {
/* We ran into an old queue entry, which means we've hit empty */
} else {
SDL_Log("ERROR: mutex failed!\n");
}
SDL_UnlockMutex(queue->mutex);
return status;
}
static SDL_sem *writersDone;
static SDL_sem *readersDone;
static SDL_atomic_t writersRunning;
static SDL_atomic_t readersRunning;
typedef struct
{
SDL_EventQueue *queue;
int index;
char padding1[SDL_CACHELINE_SIZE-(sizeof(SDL_EventQueue*)+sizeof(int))%SDL_CACHELINE_SIZE];
int waits;
SDL_bool lock_free;
char padding2[SDL_CACHELINE_SIZE-sizeof(int)-sizeof(SDL_bool)];
} WriterData;
typedef struct
{
SDL_EventQueue *queue;
int counters[NUM_WRITERS];
int waits;
SDL_bool lock_free;
char padding[SDL_CACHELINE_SIZE-(sizeof(SDL_EventQueue*)+sizeof(int)*NUM_WRITERS+sizeof(int)+sizeof(SDL_bool))%SDL_CACHELINE_SIZE];
} ReaderData;
static int SDLCALL FIFO_Writer(void* _data)
{
WriterData *data = (WriterData *)_data;
SDL_EventQueue *queue = data->queue;
int i;
SDL_Event event;
event.type = SDL_USEREVENT;
event.user.windowID = 0;
event.user.code = 0;
event.user.data1 = data;
event.user.data2 = NULL;
if (data->lock_free) {
for (i = 0; i < EVENTS_PER_WRITER; ++i) {
event.user.code = i;
while (!EnqueueEvent_LockFree(queue, &event)) {
++data->waits;
SDL_Delay(0);
}
}
} else {
for (i = 0; i < EVENTS_PER_WRITER; ++i) {
event.user.code = i;
while (!EnqueueEvent_Mutex(queue, &event)) {
++data->waits;
SDL_Delay(0);
}
}
}
SDL_AtomicAdd(&writersRunning, -1);
SDL_SemPost(writersDone);
return 0;
}
static int SDLCALL FIFO_Reader(void* _data)
{
ReaderData *data = (ReaderData *)_data;
SDL_EventQueue *queue = data->queue;
SDL_Event event;
if (data->lock_free) {
for ( ; ; ) {
if (DequeueEvent_LockFree(queue, &event)) {
WriterData *writer = (WriterData*)event.user.data1;
++data->counters[writer->index];
} else if (SDL_AtomicGet(&queue->active)) {
++data->waits;
SDL_Delay(0);
} else {
/* We drained the queue, we're done! */
break;
}
}
} else {
for ( ; ; ) {
if (DequeueEvent_Mutex(queue, &event)) {
WriterData *writer = (WriterData*)event.user.data1;
++data->counters[writer->index];
} else if (SDL_AtomicGet(&queue->active)) {
++data->waits;
SDL_Delay(0);
} else {
/* We drained the queue, we're done! */
break;
}
}
}
SDL_AtomicAdd(&readersRunning, -1);
SDL_SemPost(readersDone);
return 0;
}
#ifdef TEST_SPINLOCK_FIFO
/* This thread periodically locks the queue for no particular reason */
static int SDLCALL FIFO_Watcher(void* _data)
{
SDL_EventQueue *queue = (SDL_EventQueue *)_data;
while (SDL_AtomicGet(&queue->active)) {
SDL_AtomicLock(&queue->lock);
SDL_AtomicIncRef(&queue->watcher);
while (SDL_AtomicGet(&queue->rwcount) > 0) {
SDL_Delay(0);
}
/* Do queue manipulation here... */
SDL_AtomicDecRef(&queue->watcher);
SDL_AtomicUnlock(&queue->lock);
/* Wait a bit... */
SDL_Delay(1);
}
return 0;
}
#endif /* TEST_SPINLOCK_FIFO */
static void RunFIFOTest(SDL_bool lock_free)
{
SDL_EventQueue queue;
WriterData writerData[NUM_WRITERS];
ReaderData readerData[NUM_READERS];
Uint32 start, end;
int i, j;
int grand_total;
char textBuffer[1024];
size_t len;
SDL_Log("\nFIFO test---------------------------------------\n\n");
SDL_Log("Mode: %s\n", lock_free ? "LockFree" : "Mutex");
readersDone = SDL_CreateSemaphore(0);
writersDone = SDL_CreateSemaphore(0);
SDL_memset(&queue, 0xff, sizeof(queue));
InitEventQueue(&queue);
if (!lock_free) {
queue.mutex = SDL_CreateMutex();
}
start = SDL_GetTicks();
#ifdef TEST_SPINLOCK_FIFO
/* Start a monitoring thread */
if (lock_free) {
SDL_CreateThread(FIFO_Watcher, "FIFOWatcher", &queue);
}
#endif
/* Start the readers first */
SDL_Log("Starting %d readers\n", NUM_READERS);
SDL_zeroa(readerData);
SDL_AtomicSet(&readersRunning, NUM_READERS);
for (i = 0; i < NUM_READERS; ++i) {
char name[64];
SDL_snprintf(name, sizeof (name), "FIFOReader%d", i);
readerData[i].queue = &queue;
readerData[i].lock_free = lock_free;
SDL_CreateThread(FIFO_Reader, name, &readerData[i]);
}
/* Start up the writers */
SDL_Log("Starting %d writers\n", NUM_WRITERS);
SDL_zeroa(writerData);
SDL_AtomicSet(&writersRunning, NUM_WRITERS);
for (i = 0; i < NUM_WRITERS; ++i) {
char name[64];
SDL_snprintf(name, sizeof (name), "FIFOWriter%d", i);
writerData[i].queue = &queue;
writerData[i].index = i;
writerData[i].lock_free = lock_free;
SDL_CreateThread(FIFO_Writer, name, &writerData[i]);
}
/* Wait for the writers */
while (SDL_AtomicGet(&writersRunning) > 0) {
SDL_SemWait(writersDone);
}
/* Shut down the queue so readers exit */
SDL_AtomicSet(&queue.active, 0);
/* Wait for the readers */
while (SDL_AtomicGet(&readersRunning) > 0) {
SDL_SemWait(readersDone);
}
end = SDL_GetTicks();
SDL_DestroySemaphore(readersDone);
SDL_DestroySemaphore(writersDone);
if (!lock_free) {
SDL_DestroyMutex(queue.mutex);
}
SDL_Log("Finished in %f sec\n", (end - start) / 1000.f);
SDL_Log("\n");
for (i = 0; i < NUM_WRITERS; ++i) {
SDL_Log("Writer %d wrote %d events, had %d waits\n", i, EVENTS_PER_WRITER, writerData[i].waits);
}
SDL_Log("Writers wrote %d total events\n", NUM_WRITERS*EVENTS_PER_WRITER);
/* Print a breakdown of which readers read messages from which writer */
SDL_Log("\n");
grand_total = 0;
for (i = 0; i < NUM_READERS; ++i) {
int total = 0;
for (j = 0; j < NUM_WRITERS; ++j) {
total += readerData[i].counters[j];
}
grand_total += total;
SDL_Log("Reader %d read %d events, had %d waits\n", i, total, readerData[i].waits);
SDL_snprintf(textBuffer, sizeof(textBuffer), " { ");
for (j = 0; j < NUM_WRITERS; ++j) {
if (j > 0) {
len = SDL_strlen(textBuffer);
SDL_snprintf(textBuffer + len, sizeof(textBuffer) - len, ", ");
}
len = SDL_strlen(textBuffer);
SDL_snprintf(textBuffer + len, sizeof(textBuffer) - len, "%d", readerData[i].counters[j]);
}
len = SDL_strlen(textBuffer);
SDL_snprintf(textBuffer + len, sizeof(textBuffer) - len, " }\n");
SDL_Log("%s", textBuffer);
}
SDL_Log("Readers read %d total events\n", grand_total);
}
/* End FIFO test */
/**************************************************************************/
int
main(int argc, char *argv[])
{
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
RunBasicTest();
RunEpicTest();
/* This test is really slow, so don't run it by default */
#if 0
RunFIFOTest(SDL_FALSE);
#endif
RunFIFOTest(SDL_TRUE);
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testatomic.c | C | apache-2.0 | 20,680 |
/*
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.
*/
#include "SDL.h"
#include <stdlib.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
static SDL_Window *window = NULL;
static SDL_Renderer *renderer = NULL;
static SDL_AudioSpec spec;
static SDL_AudioDeviceID devid_in = 0;
static SDL_AudioDeviceID devid_out = 0;
static void
loop()
{
SDL_bool please_quit = SDL_FALSE;
SDL_Event e;
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
please_quit = SDL_TRUE;
} else if (e.type == SDL_KEYDOWN) {
if (e.key.keysym.sym == SDLK_ESCAPE) {
please_quit = SDL_TRUE;
}
} else if (e.type == SDL_MOUSEBUTTONDOWN) {
if (e.button.button == 1) {
SDL_PauseAudioDevice(devid_out, SDL_TRUE);
SDL_PauseAudioDevice(devid_in, SDL_FALSE);
}
} else if (e.type == SDL_MOUSEBUTTONUP) {
if (e.button.button == 1) {
SDL_PauseAudioDevice(devid_in, SDL_TRUE);
SDL_PauseAudioDevice(devid_out, SDL_FALSE);
}
}
}
if (SDL_GetAudioDeviceStatus(devid_in) == SDL_AUDIO_PLAYING) {
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
} else {
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
}
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
if (please_quit) {
/* stop playing back, quit. */
SDL_Log("Shutting down.\n");
SDL_PauseAudioDevice(devid_in, 1);
SDL_CloseAudioDevice(devid_in);
SDL_PauseAudioDevice(devid_out, 1);
SDL_CloseAudioDevice(devid_out);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
#ifdef __EMSCRIPTEN__
emscripten_cancel_main_loop();
#endif
exit(0);
}
/* Note that it would be easier to just have a one-line function that
calls SDL_QueueAudio() as a capture device callback, but we're
trying to test the API, so we use SDL_DequeueAudio() here. */
while (SDL_TRUE) {
Uint8 buf[1024];
const Uint32 br = SDL_DequeueAudio(devid_in, buf, sizeof (buf));
SDL_QueueAudio(devid_out, buf, br);
if (br < sizeof (buf)) {
break;
}
}
}
int
main(int argc, char **argv)
{
/* (argv[1] == NULL means "open default device.") */
const char *devname = argv[1];
SDL_AudioSpec wanted;
int devcount;
int i;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Load the SDL library */
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return (1);
}
window = SDL_CreateWindow("testaudiocapture", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 320, 240, 0);
renderer = SDL_CreateRenderer(window, -1, 0);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
SDL_Log("Using audio driver: %s\n", SDL_GetCurrentAudioDriver());
devcount = SDL_GetNumAudioDevices(SDL_TRUE);
for (i = 0; i < devcount; i++) {
SDL_Log(" Capture device #%d: '%s'\n", i, SDL_GetAudioDeviceName(i, SDL_TRUE));
}
SDL_zero(wanted);
wanted.freq = 44100;
wanted.format = AUDIO_F32SYS;
wanted.channels = 1;
wanted.samples = 4096;
wanted.callback = NULL;
SDL_zero(spec);
/* DirectSound can fail in some instances if you open the same hardware
for both capture and output and didn't open the output end first,
according to the docs, so if you're doing something like this, always
open your capture devices second in case you land in those bizarre
circumstances. */
SDL_Log("Opening default playback device...\n");
devid_out = SDL_OpenAudioDevice(NULL, SDL_FALSE, &wanted, &spec, SDL_AUDIO_ALLOW_ANY_CHANGE);
if (!devid_out) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open an audio device for playback: %s!\n", SDL_GetError());
SDL_Quit();
exit(1);
}
SDL_Log("Opening capture device %s%s%s...\n",
devname ? "'" : "",
devname ? devname : "[[default]]",
devname ? "'" : "");
devid_in = SDL_OpenAudioDevice(argv[1], SDL_TRUE, &spec, &spec, 0);
if (!devid_in) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open an audio device for capture: %s!\n", SDL_GetError());
SDL_Quit();
exit(1);
}
SDL_Log("Ready! Hold down mouse or finger to record!\n");
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (1) { loop(); SDL_Delay(16); }
#endif
return 0;
}
| YifuLiu/AliOS-Things | components/SDL2/test/testaudiocapture.c | C | apache-2.0 | 5,185 |
/*
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.
*/
/* Program to test hotplugging of audio devices */
#include "SDL_config.h"
#include <stdio.h>
#include <stdlib.h>
#if HAVE_SIGNAL_H
#include <signal.h>
#endif
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL.h"
static SDL_AudioSpec spec;
static Uint8 *sound = NULL; /* Pointer to wave data */
static Uint32 soundlen = 0; /* Length of wave data */
static int posindex = 0;
static Uint32 positions[64];
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_Quit();
exit(rc);
}
void SDLCALL
fillerup(void *_pos, Uint8 * stream, int len)
{
Uint32 pos = *((Uint32 *) _pos);
Uint8 *waveptr;
int waveleft;
/* Set up the pointers */
waveptr = sound + pos;
waveleft = soundlen - pos;
/* Go! */
while (waveleft <= len) {
SDL_memcpy(stream, waveptr, waveleft);
stream += waveleft;
len -= waveleft;
waveptr = sound;
waveleft = soundlen;
pos = 0;
}
SDL_memcpy(stream, waveptr, len);
pos += len;
*((Uint32 *) _pos) = pos;
}
static int done = 0;
void
poked(int sig)
{
done = 1;
}
static const char*
devtypestr(int iscapture)
{
return iscapture ? "capture" : "output";
}
static void
iteration()
{
SDL_Event e;
SDL_AudioDeviceID dev;
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
done = 1;
} else if (e.type == SDL_KEYUP) {
if (e.key.keysym.sym == SDLK_ESCAPE)
done = 1;
} else if (e.type == SDL_AUDIODEVICEADDED) {
int index = e.adevice.which;
int iscapture = e.adevice.iscapture;
const char *name = SDL_GetAudioDeviceName(index, iscapture);
if (name != NULL)
SDL_Log("New %s audio device at index %u: %s\n", devtypestr(iscapture), (unsigned int) index, name);
else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Got new %s device at index %u, but failed to get the name: %s\n",
devtypestr(iscapture), (unsigned int) index, SDL_GetError());
continue;
}
if (!iscapture) {
positions[posindex] = 0;
spec.userdata = &positions[posindex++];
spec.callback = fillerup;
dev = SDL_OpenAudioDevice(name, 0, &spec, NULL, 0);
if (!dev) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open '%s': %s\n", name, SDL_GetError());
} else {
SDL_Log("Opened '%s' as %u\n", name, (unsigned int) dev);
SDL_PauseAudioDevice(dev, 0);
}
}
} else if (e.type == SDL_AUDIODEVICEREMOVED) {
dev = (SDL_AudioDeviceID) e.adevice.which;
SDL_Log("%s device %u removed.\n", devtypestr(e.adevice.iscapture), (unsigned int) dev);
SDL_CloseAudioDevice(dev);
}
}
}
#ifdef __EMSCRIPTEN__
void
loop()
{
if(done)
emscripten_cancel_main_loop();
else
iteration();
}
#endif
int
main(int argc, char *argv[])
{
int i;
char filename[4096];
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Load the SDL library */
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return (1);
}
/* Some targets (Mac CoreAudio) need an event queue for audio hotplug, so make and immediately hide a window. */
SDL_MinimizeWindow(SDL_CreateWindow("testaudiohotplug", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0));
if (argc > 1) {
SDL_strlcpy(filename, argv[1], sizeof(filename));
} else {
SDL_strlcpy(filename, "sample.wav", sizeof(filename));
}
/* Load the wave file into memory */
if (SDL_LoadWAV(filename, &spec, &sound, &soundlen) == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s\n", filename, SDL_GetError());
quit(1);
}
#if HAVE_SIGNAL_H
/* Set the signals */
#ifdef SIGHUP
signal(SIGHUP, poked);
#endif
signal(SIGINT, poked);
#ifdef SIGQUIT
signal(SIGQUIT, poked);
#endif
signal(SIGTERM, poked);
#endif /* HAVE_SIGNAL_H */
/* Show the list of available drivers */
SDL_Log("Available audio drivers:");
for (i = 0; i < SDL_GetNumAudioDrivers(); ++i) {
SDL_Log("%i: %s", i, SDL_GetAudioDriver(i));
}
SDL_Log("Select a driver with the SDL_AUDIODRIVER environment variable.\n");
SDL_Log("Using audio driver: %s\n", SDL_GetCurrentAudioDriver());
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
SDL_Delay(100);
iteration();
}
#endif
/* Clean up on signal */
/* Quit audio first, then free WAV. This prevents access violations in the audio threads. */
SDL_QuitSubSystem(SDL_INIT_AUDIO);
SDL_FreeWAV(sound);
SDL_Quit();
return (0);
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testaudiohotplug.c | C | apache-2.0 | 5,579 |
/*
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.
*/
#include <stdio.h>
#include "SDL.h"
static void
print_devices(int iscapture)
{
const char *typestr = ((iscapture) ? "capture" : "output");
int n = SDL_GetNumAudioDevices(iscapture);
SDL_Log("Found %d %s device%s:\n", n, typestr, n != 1 ? "s" : "");
if (n == -1)
SDL_Log(" Driver can't detect specific %s devices.\n\n", typestr);
else if (n == 0)
SDL_Log(" No %s devices found.\n\n", typestr);
else {
int i;
for (i = 0; i < n; i++) {
const char *name = SDL_GetAudioDeviceName(i, iscapture);
if (name != NULL)
SDL_Log(" %d: %s\n", i, name);
else
SDL_Log(" %d Error: %s\n", i, SDL_GetError());
}
SDL_Log("\n");
}
}
int
main(int argc, char **argv)
{
int n;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Load the SDL library */
if (SDL_Init(SDL_INIT_AUDIO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return (1);
}
/* Print available audio drivers */
n = SDL_GetNumAudioDrivers();
if (n == 0) {
SDL_Log("No built-in audio drivers\n\n");
} else {
int i;
SDL_Log("Built-in audio drivers:\n");
for (i = 0; i < n; ++i) {
SDL_Log(" %d: %s\n", i, SDL_GetAudioDriver(i));
}
SDL_Log("Select a driver with the SDL_AUDIODRIVER environment variable.\n");
}
SDL_Log("Using audio driver: %s\n\n", SDL_GetCurrentAudioDriver());
print_devices(0);
print_devices(1);
SDL_Quit();
return 0;
}
| YifuLiu/AliOS-Things | components/SDL2/test/testaudioinfo.c | C | apache-2.0 | 2,101 |
/*
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.
*/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "SDL.h"
#include "SDL_test.h"
#include "testautomation_suites.h"
static SDLTest_CommonState *state;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDLTest_CommonQuit(state);
exit(rc);
}
int
main(int argc, char *argv[])
{
int result;
int testIterations = 1;
Uint64 userExecKey = 0;
char *userRunSeed = NULL;
char *filter = NULL;
int i, done;
SDL_Event event;
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
/* Parse commandline */
for (i = 1; i < argc;) {
int consumed;
consumed = SDLTest_CommonArg(state, i);
if (consumed == 0) {
consumed = -1;
if (SDL_strcasecmp(argv[i], "--iterations") == 0) {
if (argv[i + 1]) {
testIterations = SDL_atoi(argv[i + 1]);
if (testIterations < 1) testIterations = 1;
consumed = 2;
}
}
else if (SDL_strcasecmp(argv[i], "--execKey") == 0) {
if (argv[i + 1]) {
SDL_sscanf(argv[i + 1], "%"SDL_PRIu64, &userExecKey);
consumed = 2;
}
}
else if (SDL_strcasecmp(argv[i], "--seed") == 0) {
if (argv[i + 1]) {
userRunSeed = SDL_strdup(argv[i + 1]);
consumed = 2;
}
}
else if (SDL_strcasecmp(argv[i], "--filter") == 0) {
if (argv[i + 1]) {
filter = SDL_strdup(argv[i + 1]);
consumed = 2;
}
}
}
if (consumed < 0) {
static const char *options[] = { "[--iterations #]", "[--execKey #]", "[--seed string]", "[--filter suite_name|test_name]", NULL };
SDLTest_CommonLogUsage(state, argv[0], options);
quit(1);
}
i += consumed;
}
/* Initialize common state */
if (!SDLTest_CommonInit(state)) {
quit(2);
}
/* Create the windows, initialize the renderers */
for (i = 0; i < state->num_windows; ++i) {
SDL_Renderer *renderer = state->renderers[i];
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(renderer);
}
/* Call Harness */
result = SDLTest_RunSuites(testSuites, (const char *)userRunSeed, userExecKey, (const char *)filter, testIterations);
/* Empty event queue */
done = 0;
for (i=0; i<100; i++) {
while (SDL_PollEvent(&event)) {
SDLTest_CommonEvent(state, &event, &done);
}
SDL_Delay(10);
}
/* Clean up */
SDL_free(userRunSeed);
SDL_free(filter);
/* Shutdown everything */
quit(result);
return(result);
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation.c | C | apache-2.0 | 3,408 |
/**
* Original code: automated SDL audio test written by Edgar Simo "bobbens"
* New/updated tests: aschiffler at ferzkopp dot net
*/
/* quiet windows compiler warnings */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include "SDL.h"
#include "SDL_test.h"
/* ================= Test Case Implementation ================== */
/* Fixture */
void
_audioSetUp(void *arg)
{
/* Start SDL audio subsystem */
int ret = SDL_InitSubSystem( SDL_INIT_AUDIO );
SDLTest_AssertPass("Call to SDL_InitSubSystem(SDL_INIT_AUDIO)");
SDLTest_AssertCheck(ret==0, "Check result from SDL_InitSubSystem(SDL_INIT_AUDIO)");
if (ret != 0) {
SDLTest_LogError("%s", SDL_GetError());
}
}
void
_audioTearDown(void *arg)
{
/* Remove a possibly created file from SDL disk writer audio driver; ignore errors */
remove("sdlaudio.raw");
SDLTest_AssertPass("Cleanup of test files completed");
}
/* Global counter for callback invocation */
int _audio_testCallbackCounter;
/* Global accumulator for total callback length */
int _audio_testCallbackLength;
/* Test callback function */
void SDLCALL _audio_testCallback(void *userdata, Uint8 *stream, int len)
{
/* track that callback was called */
_audio_testCallbackCounter++;
_audio_testCallbackLength += len;
}
/* Test case functions */
/**
* \brief Stop and restart audio subsystem
*
* \sa https://wiki.libsdl.org/SDL_QuitSubSystem
* \sa https://wiki.libsdl.org/SDL_InitSubSystem
*/
int audio_quitInitAudioSubSystem()
{
/* Stop SDL audio subsystem */
SDL_QuitSubSystem( SDL_INIT_AUDIO );
SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
/* Restart audio again */
_audioSetUp(NULL);
return TEST_COMPLETED;
}
/**
* \brief Start and stop audio directly
*
* \sa https://wiki.libsdl.org/SDL_InitAudio
* \sa https://wiki.libsdl.org/SDL_QuitAudio
*/
int audio_initQuitAudio()
{
int result;
int i, iMax;
const char* audioDriver;
/* Stop SDL audio subsystem */
SDL_QuitSubSystem( SDL_INIT_AUDIO );
SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
/* Loop over all available audio drivers */
iMax = SDL_GetNumAudioDrivers();
SDLTest_AssertPass("Call to SDL_GetNumAudioDrivers()");
SDLTest_AssertCheck(iMax > 0, "Validate number of audio drivers; expected: >0 got: %d", iMax);
for (i = 0; i < iMax; i++) {
audioDriver = SDL_GetAudioDriver(i);
SDLTest_AssertPass("Call to SDL_GetAudioDriver(%d)", i);
SDLTest_AssertCheck(audioDriver != NULL, "Audio driver name is not NULL");
SDLTest_AssertCheck(audioDriver[0] != '\0', "Audio driver name is not empty; got: %s", audioDriver);
/* Call Init */
result = SDL_AudioInit(audioDriver);
SDLTest_AssertPass("Call to SDL_AudioInit('%s')", audioDriver);
SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0 got: %d", result);
/* Call Quit */
SDL_AudioQuit();
SDLTest_AssertPass("Call to SDL_AudioQuit()");
}
/* NULL driver specification */
audioDriver = NULL;
/* Call Init */
result = SDL_AudioInit(audioDriver);
SDLTest_AssertPass("Call to SDL_AudioInit(NULL)");
SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0 got: %d", result);
/* Call Quit */
SDL_AudioQuit();
SDLTest_AssertPass("Call to SDL_AudioQuit()");
/* Restart audio again */
_audioSetUp(NULL);
return TEST_COMPLETED;
}
/**
* \brief Start, open, close and stop audio
*
* \sa https://wiki.libsdl.org/SDL_InitAudio
* \sa https://wiki.libsdl.org/SDL_OpenAudio
* \sa https://wiki.libsdl.org/SDL_CloseAudio
* \sa https://wiki.libsdl.org/SDL_QuitAudio
*/
int audio_initOpenCloseQuitAudio()
{
int result, expectedResult;
int i, iMax, j, k;
const char* audioDriver;
SDL_AudioSpec desired;
/* Stop SDL audio subsystem */
SDL_QuitSubSystem( SDL_INIT_AUDIO );
SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
/* Loop over all available audio drivers */
iMax = SDL_GetNumAudioDrivers();
SDLTest_AssertPass("Call to SDL_GetNumAudioDrivers()");
SDLTest_AssertCheck(iMax > 0, "Validate number of audio drivers; expected: >0 got: %d", iMax);
for (i = 0; i < iMax; i++) {
audioDriver = SDL_GetAudioDriver(i);
SDLTest_AssertPass("Call to SDL_GetAudioDriver(%d)", i);
SDLTest_AssertCheck(audioDriver != NULL, "Audio driver name is not NULL");
SDLTest_AssertCheck(audioDriver[0] != '\0', "Audio driver name is not empty; got: %s", audioDriver);
/* Change specs */
for (j = 0; j < 2; j++) {
/* Call Init */
result = SDL_AudioInit(audioDriver);
SDLTest_AssertPass("Call to SDL_AudioInit('%s')", audioDriver);
SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0 got: %d", result);
/* Set spec */
SDL_memset(&desired, 0, sizeof(desired));
switch (j) {
case 0:
/* Set standard desired spec */
desired.freq = 22050;
desired.format = AUDIO_S16SYS;
desired.channels = 2;
desired.samples = 4096;
desired.callback = _audio_testCallback;
desired.userdata = NULL;
case 1:
/* Set custom desired spec */
desired.freq = 48000;
desired.format = AUDIO_F32SYS;
desired.channels = 2;
desired.samples = 2048;
desired.callback = _audio_testCallback;
desired.userdata = NULL;
break;
}
/* Call Open (maybe multiple times) */
for (k=0; k <= j; k++) {
result = SDL_OpenAudio(&desired, NULL);
SDLTest_AssertPass("Call to SDL_OpenAudio(desired_spec_%d, NULL), call %d", j, k+1);
expectedResult = (k==0) ? 0 : -1;
SDLTest_AssertCheck(result == expectedResult, "Verify return value; expected: %d, got: %d", expectedResult, result);
}
/* Call Close (maybe multiple times) */
for (k=0; k <= j; k++) {
SDL_CloseAudio();
SDLTest_AssertPass("Call to SDL_CloseAudio(), call %d", k+1);
}
/* Call Quit (maybe multiple times) */
for (k=0; k <= j; k++) {
SDL_AudioQuit();
SDLTest_AssertPass("Call to SDL_AudioQuit(), call %d", k+1);
}
} /* spec loop */
} /* driver loop */
/* Restart audio again */
_audioSetUp(NULL);
return TEST_COMPLETED;
}
/**
* \brief Pause and unpause audio
*
* \sa https://wiki.libsdl.org/SDL_PauseAudio
*/
int audio_pauseUnpauseAudio()
{
int result;
int i, iMax, j, k, l;
int totalDelay;
int pause_on;
int originalCounter;
const char* audioDriver;
SDL_AudioSpec desired;
/* Stop SDL audio subsystem */
SDL_QuitSubSystem( SDL_INIT_AUDIO );
SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
/* Loop over all available audio drivers */
iMax = SDL_GetNumAudioDrivers();
SDLTest_AssertPass("Call to SDL_GetNumAudioDrivers()");
SDLTest_AssertCheck(iMax > 0, "Validate number of audio drivers; expected: >0 got: %d", iMax);
for (i = 0; i < iMax; i++) {
audioDriver = SDL_GetAudioDriver(i);
SDLTest_AssertPass("Call to SDL_GetAudioDriver(%d)", i);
SDLTest_AssertCheck(audioDriver != NULL, "Audio driver name is not NULL");
SDLTest_AssertCheck(audioDriver[0] != '\0', "Audio driver name is not empty; got: %s", audioDriver);
/* Change specs */
for (j = 0; j < 2; j++) {
/* Call Init */
result = SDL_AudioInit(audioDriver);
SDLTest_AssertPass("Call to SDL_AudioInit('%s')", audioDriver);
SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0 got: %d", result);
/* Set spec */
SDL_memset(&desired, 0, sizeof(desired));
switch (j) {
case 0:
/* Set standard desired spec */
desired.freq = 22050;
desired.format = AUDIO_S16SYS;
desired.channels = 2;
desired.samples = 4096;
desired.callback = _audio_testCallback;
desired.userdata = NULL;
case 1:
/* Set custom desired spec */
desired.freq = 48000;
desired.format = AUDIO_F32SYS;
desired.channels = 2;
desired.samples = 2048;
desired.callback = _audio_testCallback;
desired.userdata = NULL;
break;
}
/* Call Open */
result = SDL_OpenAudio(&desired, NULL);
SDLTest_AssertPass("Call to SDL_OpenAudio(desired_spec_%d, NULL)", j);
SDLTest_AssertCheck(result == 0, "Verify return value; expected: 0 got: %d", result);
/* Start and stop audio multiple times */
for (l=0; l<3; l++) {
SDLTest_Log("Pause/Unpause iteration: %d", l+1);
/* Reset callback counters */
_audio_testCallbackCounter = 0;
_audio_testCallbackLength = 0;
/* Un-pause audio to start playing (maybe multiple times) */
pause_on = 0;
for (k=0; k <= j; k++) {
SDL_PauseAudio(pause_on);
SDLTest_AssertPass("Call to SDL_PauseAudio(%d), call %d", pause_on, k+1);
}
/* Wait for callback */
totalDelay = 0;
do {
SDL_Delay(10);
totalDelay += 10;
}
while (_audio_testCallbackCounter == 0 && totalDelay < 1000);
SDLTest_AssertCheck(_audio_testCallbackCounter > 0, "Verify callback counter; expected: >0 got: %d", _audio_testCallbackCounter);
SDLTest_AssertCheck(_audio_testCallbackLength > 0, "Verify callback length; expected: >0 got: %d", _audio_testCallbackLength);
/* Pause audio to stop playing (maybe multiple times) */
for (k=0; k <= j; k++) {
pause_on = (k==0) ? 1 : SDLTest_RandomIntegerInRange(99, 9999);
SDL_PauseAudio(pause_on);
SDLTest_AssertPass("Call to SDL_PauseAudio(%d), call %d", pause_on, k+1);
}
/* Ensure callback is not called again */
originalCounter = _audio_testCallbackCounter;
SDL_Delay(totalDelay + 10);
SDLTest_AssertCheck(originalCounter == _audio_testCallbackCounter, "Verify callback counter; expected: %d, got: %d", originalCounter, _audio_testCallbackCounter);
}
/* Call Close */
SDL_CloseAudio();
SDLTest_AssertPass("Call to SDL_CloseAudio()");
/* Call Quit */
SDL_AudioQuit();
SDLTest_AssertPass("Call to SDL_AudioQuit()");
} /* spec loop */
} /* driver loop */
/* Restart audio again */
_audioSetUp(NULL);
return TEST_COMPLETED;
}
/**
* \brief Enumerate and name available audio devices (output and capture).
*
* \sa https://wiki.libsdl.org/SDL_GetNumAudioDevices
* \sa https://wiki.libsdl.org/SDL_GetAudioDeviceName
*/
int audio_enumerateAndNameAudioDevices()
{
int t, tt;
int i, n, nn;
const char *name, *nameAgain;
/* Iterate over types: t=0 output device, t=1 input/capture device */
for (t=0; t<2; t++) {
/* Get number of devices. */
n = SDL_GetNumAudioDevices(t);
SDLTest_AssertPass("Call to SDL_GetNumAudioDevices(%i)", t);
SDLTest_Log("Number of %s devices < 0, reported as %i", (t) ? "capture" : "output", n);
SDLTest_AssertCheck(n >= 0, "Validate result is >= 0, got: %i", n);
/* Variation of non-zero type */
if (t==1) {
tt = t + SDLTest_RandomIntegerInRange(1,10);
nn = SDL_GetNumAudioDevices(tt);
SDLTest_AssertCheck(n==nn, "Verify result from SDL_GetNumAudioDevices(%i), expected same number of audio devices %i, got %i", tt, n, nn);
nn = SDL_GetNumAudioDevices(-tt);
SDLTest_AssertCheck(n==nn, "Verify result from SDL_GetNumAudioDevices(%i), expected same number of audio devices %i, got %i", -tt, n, nn);
}
/* List devices. */
if (n>0) {
for (i=0; i<n; i++) {
name = SDL_GetAudioDeviceName(i, t);
SDLTest_AssertPass("Call to SDL_GetAudioDeviceName(%i, %i)", i, t);
SDLTest_AssertCheck(name != NULL, "Verify result from SDL_GetAudioDeviceName(%i, %i) is not NULL", i, t);
if (name != NULL) {
SDLTest_AssertCheck(name[0] != '\0', "verify result from SDL_GetAudioDeviceName(%i, %i) is not empty, got: '%s'", i, t, name);
if (t==1) {
/* Also try non-zero type */
tt = t + SDLTest_RandomIntegerInRange(1,10);
nameAgain = SDL_GetAudioDeviceName(i, tt);
SDLTest_AssertCheck(nameAgain != NULL, "Verify result from SDL_GetAudioDeviceName(%i, %i) is not NULL", i, tt);
if (nameAgain != NULL) {
SDLTest_AssertCheck(nameAgain[0] != '\0', "Verify result from SDL_GetAudioDeviceName(%i, %i) is not empty, got: '%s'", i, tt, nameAgain);
SDLTest_AssertCheck(SDL_strcmp(name, nameAgain)==0,
"Verify SDL_GetAudioDeviceName(%i, %i) and SDL_GetAudioDeviceName(%i %i) return the same string",
i, t, i, tt);
}
}
}
}
}
}
return TEST_COMPLETED;
}
/**
* \brief Negative tests around enumeration and naming of audio devices.
*
* \sa https://wiki.libsdl.org/SDL_GetNumAudioDevices
* \sa https://wiki.libsdl.org/SDL_GetAudioDeviceName
*/
int audio_enumerateAndNameAudioDevicesNegativeTests()
{
int t;
int i, j, no, nc;
const char *name;
/* Get number of devices. */
no = SDL_GetNumAudioDevices(0);
SDLTest_AssertPass("Call to SDL_GetNumAudioDevices(0)");
nc = SDL_GetNumAudioDevices(1);
SDLTest_AssertPass("Call to SDL_GetNumAudioDevices(1)");
/* Invalid device index when getting name */
for (t=0; t<2; t++) {
/* Negative device index */
i = SDLTest_RandomIntegerInRange(-10,-1);
name = SDL_GetAudioDeviceName(i, t);
SDLTest_AssertPass("Call to SDL_GetAudioDeviceName(%i, %i)", i, t);
SDLTest_AssertCheck(name == NULL, "Check SDL_GetAudioDeviceName(%i, %i) result NULL, expected NULL, got: %s", i, t, (name == NULL) ? "NULL" : name);
/* Device index past range */
for (j=0; j<3; j++) {
i = (t) ? nc+j : no+j;
name = SDL_GetAudioDeviceName(i, t);
SDLTest_AssertPass("Call to SDL_GetAudioDeviceName(%i, %i)", i, t);
SDLTest_AssertCheck(name == NULL, "Check SDL_GetAudioDeviceName(%i, %i) result, expected: NULL, got: %s", i, t, (name == NULL) ? "NULL" : name);
}
/* Capture index past capture range but within output range */
if ((no>0) && (no>nc) && (t==1)) {
i = no-1;
name = SDL_GetAudioDeviceName(i, t);
SDLTest_AssertPass("Call to SDL_GetAudioDeviceName(%i, %i)", i, t);
SDLTest_AssertCheck(name == NULL, "Check SDL_GetAudioDeviceName(%i, %i) result, expected: NULL, got: %s", i, t, (name == NULL) ? "NULL" : name);
}
}
return TEST_COMPLETED;
}
/**
* \brief Checks available audio driver names.
*
* \sa https://wiki.libsdl.org/SDL_GetNumAudioDrivers
* \sa https://wiki.libsdl.org/SDL_GetAudioDriver
*/
int audio_printAudioDrivers()
{
int i, n;
const char *name;
/* Get number of drivers */
n = SDL_GetNumAudioDrivers();
SDLTest_AssertPass("Call to SDL_GetNumAudioDrivers()");
SDLTest_AssertCheck(n>=0, "Verify number of audio drivers >= 0, got: %i", n);
/* List drivers. */
if (n>0)
{
for (i=0; i<n; i++) {
name = SDL_GetAudioDriver(i);
SDLTest_AssertPass("Call to SDL_GetAudioDriver(%i)", i);
SDLTest_AssertCheck(name != NULL, "Verify returned name is not NULL");
if (name != NULL) {
SDLTest_AssertCheck(name[0] != '\0', "Verify returned name is not empty, got: '%s'", name);
}
}
}
return TEST_COMPLETED;
}
/**
* \brief Checks current audio driver name with initialized audio.
*
* \sa https://wiki.libsdl.org/SDL_GetCurrentAudioDriver
*/
int audio_printCurrentAudioDriver()
{
/* Check current audio driver */
const char *name = SDL_GetCurrentAudioDriver();
SDLTest_AssertPass("Call to SDL_GetCurrentAudioDriver()");
SDLTest_AssertCheck(name != NULL, "Verify returned name is not NULL");
if (name != NULL) {
SDLTest_AssertCheck(name[0] != '\0', "Verify returned name is not empty, got: '%s'", name);
}
return TEST_COMPLETED;
}
/* Definition of all formats, channels, and frequencies used to test audio conversions */
const int _numAudioFormats = 18;
SDL_AudioFormat _audioFormats[] = { AUDIO_S8, AUDIO_U8, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_S16SYS, AUDIO_S16, AUDIO_U16LSB,
AUDIO_U16MSB, AUDIO_U16SYS, AUDIO_U16, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_S32SYS, AUDIO_S32,
AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_F32SYS, AUDIO_F32 };
char *_audioFormatsVerbose[] = { "AUDIO_S8", "AUDIO_U8", "AUDIO_S16LSB", "AUDIO_S16MSB", "AUDIO_S16SYS", "AUDIO_S16", "AUDIO_U16LSB",
"AUDIO_U16MSB", "AUDIO_U16SYS", "AUDIO_U16", "AUDIO_S32LSB", "AUDIO_S32MSB", "AUDIO_S32SYS", "AUDIO_S32",
"AUDIO_F32LSB", "AUDIO_F32MSB", "AUDIO_F32SYS", "AUDIO_F32" };
const int _numAudioChannels = 4;
Uint8 _audioChannels[] = { 1, 2, 4, 6 };
const int _numAudioFrequencies = 4;
int _audioFrequencies[] = { 11025, 22050, 44100, 48000 };
/**
* \brief Builds various audio conversion structures
*
* \sa https://wiki.libsdl.org/SDL_BuildAudioCVT
*/
int audio_buildAudioCVT()
{
int result;
SDL_AudioCVT cvt;
SDL_AudioSpec spec1;
SDL_AudioSpec spec2;
int i, ii, j, jj, k, kk;
/* No conversion needed */
spec1.format = AUDIO_S16LSB;
spec1.channels = 2;
spec1.freq = 22050;
result = SDL_BuildAudioCVT(&cvt, spec1.format, spec1.channels, spec1.freq,
spec1.format, spec1.channels, spec1.freq);
SDLTest_AssertPass("Call to SDL_BuildAudioCVT(spec1 ==> spec1)");
SDLTest_AssertCheck(result == 0, "Verify result value; expected: 0, got: %i", result);
/* Typical conversion */
spec1.format = AUDIO_S8;
spec1.channels = 1;
spec1.freq = 22050;
spec2.format = AUDIO_S16LSB;
spec2.channels = 2;
spec2.freq = 44100;
result = SDL_BuildAudioCVT(&cvt, spec1.format, spec1.channels, spec1.freq,
spec2.format, spec2.channels, spec2.freq);
SDLTest_AssertPass("Call to SDL_BuildAudioCVT(spec1 ==> spec2)");
SDLTest_AssertCheck(result == 1, "Verify result value; expected: 1, got: %i", result);
/* All source conversions with random conversion targets, allow 'null' conversions */
for (i = 0; i < _numAudioFormats; i++) {
for (j = 0; j < _numAudioChannels; j++) {
for (k = 0; k < _numAudioFrequencies; k++) {
spec1.format = _audioFormats[i];
spec1.channels = _audioChannels[j];
spec1.freq = _audioFrequencies[k];
ii = SDLTest_RandomIntegerInRange(0, _numAudioFormats - 1);
jj = SDLTest_RandomIntegerInRange(0, _numAudioChannels - 1);
kk = SDLTest_RandomIntegerInRange(0, _numAudioFrequencies - 1);
spec2.format = _audioFormats[ii];
spec2.channels = _audioChannels[jj];
spec2.freq = _audioFrequencies[kk];
result = SDL_BuildAudioCVT(&cvt, spec1.format, spec1.channels, spec1.freq,
spec2.format, spec2.channels, spec2.freq);
SDLTest_AssertPass("Call to SDL_BuildAudioCVT(format[%i]=%s(%i),channels[%i]=%i,freq[%i]=%i ==> format[%i]=%s(%i),channels[%i]=%i,freq[%i]=%i)",
i, _audioFormatsVerbose[i], spec1.format, j, spec1.channels, k, spec1.freq, ii, _audioFormatsVerbose[ii], spec2.format, jj, spec2.channels, kk, spec2.freq);
SDLTest_AssertCheck(result == 0 || result == 1, "Verify result value; expected: 0 or 1, got: %i", result);
if (result<0) {
SDLTest_LogError("%s", SDL_GetError());
} else {
SDLTest_AssertCheck(cvt.len_mult > 0, "Verify that cvt.len_mult value; expected: >0, got: %i", cvt.len_mult);
}
}
}
}
return TEST_COMPLETED;
}
/**
* \brief Checkes calls with invalid input to SDL_BuildAudioCVT
*
* \sa https://wiki.libsdl.org/SDL_BuildAudioCVT
*/
int audio_buildAudioCVTNegative()
{
const char *expectedError = "Parameter 'cvt' is invalid";
const char *error;
int result;
SDL_AudioCVT cvt;
SDL_AudioSpec spec1;
SDL_AudioSpec spec2;
int i;
char message[256];
/* Valid format */
spec1.format = AUDIO_S8;
spec1.channels = 1;
spec1.freq = 22050;
spec2.format = AUDIO_S16LSB;
spec2.channels = 2;
spec2.freq = 44100;
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
/* NULL input for CVT buffer */
result = SDL_BuildAudioCVT((SDL_AudioCVT *)NULL, spec1.format, spec1.channels, spec1.freq,
spec2.format, spec2.channels, spec2.freq);
SDLTest_AssertPass("Call to SDL_BuildAudioCVT(NULL,...)");
SDLTest_AssertCheck(result == -1, "Verify result value; expected: -1, got: %i", result);
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
if (error != NULL) {
SDLTest_AssertCheck(SDL_strcmp(error, expectedError) == 0,
"Validate error message, expected: '%s', got: '%s'", expectedError, error);
}
/* Invalid conversions */
for (i = 1; i < 64; i++) {
/* Valid format to start with */
spec1.format = AUDIO_S8;
spec1.channels = 1;
spec1.freq = 22050;
spec2.format = AUDIO_S16LSB;
spec2.channels = 2;
spec2.freq = 44100;
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
/* Set various invalid format inputs */
SDL_strlcpy(message, "Invalid: ", 256);
if (i & 1) {
SDL_strlcat(message, " spec1.format", 256);
spec1.format = 0;
}
if (i & 2) {
SDL_strlcat(message, " spec1.channels", 256);
spec1.channels = 0;
}
if (i & 4) {
SDL_strlcat(message, " spec1.freq", 256);
spec1.freq = 0;
}
if (i & 8) {
SDL_strlcat(message, " spec2.format", 256);
spec2.format = 0;
}
if (i & 16) {
SDL_strlcat(message, " spec2.channels", 256);
spec2.channels = 0;
}
if (i & 32) {
SDL_strlcat(message, " spec2.freq", 256);
spec2.freq = 0;
}
SDLTest_Log("%s", message);
result = SDL_BuildAudioCVT(&cvt, spec1.format, spec1.channels, spec1.freq,
spec2.format, spec2.channels, spec2.freq);
SDLTest_AssertPass("Call to SDL_BuildAudioCVT(spec1 ==> spec2)");
SDLTest_AssertCheck(result == -1, "Verify result value; expected: -1, got: %i", result);
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL && error[0] != '\0', "Validate that error message was not NULL or empty");
}
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
return TEST_COMPLETED;
}
/**
* \brief Checks current audio status.
*
* \sa https://wiki.libsdl.org/SDL_GetAudioStatus
*/
int audio_getAudioStatus()
{
SDL_AudioStatus result;
/* Check current audio status */
result = SDL_GetAudioStatus();
SDLTest_AssertPass("Call to SDL_GetAudioStatus()");
SDLTest_AssertCheck(result == SDL_AUDIO_STOPPED || result == SDL_AUDIO_PLAYING || result == SDL_AUDIO_PAUSED,
"Verify returned value; expected: STOPPED (%i) | PLAYING (%i) | PAUSED (%i), got: %i",
SDL_AUDIO_STOPPED, SDL_AUDIO_PLAYING, SDL_AUDIO_PAUSED, result);
return TEST_COMPLETED;
}
/**
* \brief Opens, checks current audio status, and closes a device.
*
* \sa https://wiki.libsdl.org/SDL_GetAudioStatus
*/
int audio_openCloseAndGetAudioStatus()
{
SDL_AudioStatus result;
int i;
int count;
char *device;
SDL_AudioDeviceID id;
SDL_AudioSpec desired, obtained;
/* Get number of devices. */
count = SDL_GetNumAudioDevices(0);
SDLTest_AssertPass("Call to SDL_GetNumAudioDevices(0)");
if (count > 0) {
for (i = 0; i < count; i++) {
/* Get device name */
device = (char *)SDL_GetAudioDeviceName(i, 0);
SDLTest_AssertPass("SDL_GetAudioDeviceName(%i,0)", i);
SDLTest_AssertCheck(device != NULL, "Validate device name is not NULL; got: %s", (device != NULL) ? device : "NULL");
if (device == NULL) return TEST_ABORTED;
/* Set standard desired spec */
desired.freq=22050;
desired.format=AUDIO_S16SYS;
desired.channels=2;
desired.samples=4096;
desired.callback=_audio_testCallback;
desired.userdata=NULL;
/* Open device */
id = SDL_OpenAudioDevice((const char *)device, 0, &desired, &obtained, SDL_AUDIO_ALLOW_ANY_CHANGE);
SDLTest_AssertPass("SDL_OpenAudioDevice('%s',...)", device);
SDLTest_AssertCheck(id > 1, "Validate device ID; expected: >=2, got: %i", id);
if (id > 1) {
/* Check device audio status */
result = SDL_GetAudioDeviceStatus(id);
SDLTest_AssertPass("Call to SDL_GetAudioDeviceStatus()");
SDLTest_AssertCheck(result == SDL_AUDIO_STOPPED || result == SDL_AUDIO_PLAYING || result == SDL_AUDIO_PAUSED,
"Verify returned value; expected: STOPPED (%i) | PLAYING (%i) | PAUSED (%i), got: %i",
SDL_AUDIO_STOPPED, SDL_AUDIO_PLAYING, SDL_AUDIO_PAUSED, result);
/* Close device again */
SDL_CloseAudioDevice(id);
SDLTest_AssertPass("Call to SDL_CloseAudioDevice()");
}
}
} else {
SDLTest_Log("No devices to test with");
}
return TEST_COMPLETED;
}
/**
* \brief Locks and unlocks open audio device.
*
* \sa https://wiki.libsdl.org/SDL_LockAudioDevice
* \sa https://wiki.libsdl.org/SDL_UnlockAudioDevice
*/
int audio_lockUnlockOpenAudioDevice()
{
int i;
int count;
char *device;
SDL_AudioDeviceID id;
SDL_AudioSpec desired, obtained;
/* Get number of devices. */
count = SDL_GetNumAudioDevices(0);
SDLTest_AssertPass("Call to SDL_GetNumAudioDevices(0)");
if (count > 0) {
for (i = 0; i < count; i++) {
/* Get device name */
device = (char *)SDL_GetAudioDeviceName(i, 0);
SDLTest_AssertPass("SDL_GetAudioDeviceName(%i,0)", i);
SDLTest_AssertCheck(device != NULL, "Validate device name is not NULL; got: %s", (device != NULL) ? device : "NULL");
if (device == NULL) return TEST_ABORTED;
/* Set standard desired spec */
desired.freq=22050;
desired.format=AUDIO_S16SYS;
desired.channels=2;
desired.samples=4096;
desired.callback=_audio_testCallback;
desired.userdata=NULL;
/* Open device */
id = SDL_OpenAudioDevice((const char *)device, 0, &desired, &obtained, SDL_AUDIO_ALLOW_ANY_CHANGE);
SDLTest_AssertPass("SDL_OpenAudioDevice('%s',...)", device);
SDLTest_AssertCheck(id > 1, "Validate device ID; expected: >=2, got: %i", id);
if (id > 1) {
/* Lock to protect callback */
SDL_LockAudioDevice(id);
SDLTest_AssertPass("SDL_LockAudioDevice(%i)", id);
/* Simulate callback processing */
SDL_Delay(10);
SDLTest_Log("Simulate callback processing - delay");
/* Unlock again */
SDL_UnlockAudioDevice(id);
SDLTest_AssertPass("SDL_UnlockAudioDevice(%i)", id);
/* Close device again */
SDL_CloseAudioDevice(id);
SDLTest_AssertPass("Call to SDL_CloseAudioDevice()");
}
}
} else {
SDLTest_Log("No devices to test with");
}
return TEST_COMPLETED;
}
/**
* \brief Convert audio using various conversion structures
*
* \sa https://wiki.libsdl.org/SDL_BuildAudioCVT
* \sa https://wiki.libsdl.org/SDL_ConvertAudio
*/
int audio_convertAudio()
{
int result;
SDL_AudioCVT cvt;
SDL_AudioSpec spec1;
SDL_AudioSpec spec2;
int c;
char message[128];
int i, ii, j, jj, k, kk, l, ll;
/* Iterate over bitmask that determines which parameters are modified in the conversion */
for (c = 1; c < 8; c++) {
SDL_strlcpy(message, "Changing:", 128);
if (c & 1) {
SDL_strlcat(message, " Format", 128);
}
if (c & 2) {
SDL_strlcat(message, " Channels", 128);
}
if (c & 4) {
SDL_strlcat(message, " Frequencies", 128);
}
SDLTest_Log("%s", message);
/* All source conversions with random conversion targets */
for (i = 0; i < _numAudioFormats; i++) {
for (j = 0; j < _numAudioChannels; j++) {
for (k = 0; k < _numAudioFrequencies; k++) {
spec1.format = _audioFormats[i];
spec1.channels = _audioChannels[j];
spec1.freq = _audioFrequencies[k];
/* Ensure we have a different target format */
do {
if (c & 1) {
ii = SDLTest_RandomIntegerInRange(0, _numAudioFormats - 1);
} else {
ii = 1;
}
if (c & 2) {
jj = SDLTest_RandomIntegerInRange(0, _numAudioChannels - 1);
} else {
jj= j;
}
if (c & 4) {
kk = SDLTest_RandomIntegerInRange(0, _numAudioFrequencies - 1);
} else {
kk = k;
}
} while ((i == ii) && (j == jj) && (k == kk));
spec2.format = _audioFormats[ii];
spec2.channels = _audioChannels[jj];
spec2.freq = _audioFrequencies[kk];
result = SDL_BuildAudioCVT(&cvt, spec1.format, spec1.channels, spec1.freq,
spec2.format, spec2.channels, spec2.freq);
SDLTest_AssertPass("Call to SDL_BuildAudioCVT(format[%i]=%s(%i),channels[%i]=%i,freq[%i]=%i ==> format[%i]=%s(%i),channels[%i]=%i,freq[%i]=%i)",
i, _audioFormatsVerbose[i], spec1.format, j, spec1.channels, k, spec1.freq, ii, _audioFormatsVerbose[ii], spec2.format, jj, spec2.channels, kk, spec2.freq);
SDLTest_AssertCheck(result == 1, "Verify result value; expected: 1, got: %i", result);
if (result != 1) {
SDLTest_LogError("%s", SDL_GetError());
} else {
SDLTest_AssertCheck(cvt.len_mult > 0, "Verify that cvt.len_mult value; expected: >0, got: %i", cvt.len_mult);
if (cvt.len_mult < 1) return TEST_ABORTED;
/* Create some random data to convert */
l = 64;
ll = l * cvt.len_mult;
SDLTest_Log("Creating dummy sample buffer of %i length (%i bytes)", l, ll);
cvt.len = l;
cvt.buf = (Uint8 *)SDL_malloc(ll);
SDLTest_AssertCheck(cvt.buf != NULL, "Check data buffer to convert is not NULL");
if (cvt.buf == NULL) return TEST_ABORTED;
/* Convert the data */
result = SDL_ConvertAudio(&cvt);
SDLTest_AssertPass("Call to SDL_ConvertAudio()");
SDLTest_AssertCheck(result == 0, "Verify result value; expected: 0; got: %i", result);
SDLTest_AssertCheck(cvt.buf != NULL, "Verify conversion buffer is not NULL");
SDLTest_AssertCheck(cvt.len_ratio > 0.0, "Verify conversion length ratio; expected: >0; got: %f", cvt.len_ratio);
/* Free converted buffer */
SDL_free(cvt.buf);
cvt.buf = NULL;
}
}
}
}
}
return TEST_COMPLETED;
}
/**
* \brief Opens, checks current connected status, and closes a device.
*
* \sa https://wiki.libsdl.org/SDL_AudioDeviceConnected
*/
int audio_openCloseAudioDeviceConnected()
{
int result = -1;
int i;
int count;
char *device;
SDL_AudioDeviceID id;
SDL_AudioSpec desired, obtained;
/* Get number of devices. */
count = SDL_GetNumAudioDevices(0);
SDLTest_AssertPass("Call to SDL_GetNumAudioDevices(0)");
if (count > 0) {
for (i = 0; i < count; i++) {
/* Get device name */
device = (char *)SDL_GetAudioDeviceName(i, 0);
SDLTest_AssertPass("SDL_GetAudioDeviceName(%i,0)", i);
SDLTest_AssertCheck(device != NULL, "Validate device name is not NULL; got: %s", (device != NULL) ? device : "NULL");
if (device == NULL) return TEST_ABORTED;
/* Set standard desired spec */
desired.freq=22050;
desired.format=AUDIO_S16SYS;
desired.channels=2;
desired.samples=4096;
desired.callback=_audio_testCallback;
desired.userdata=NULL;
/* Open device */
id = SDL_OpenAudioDevice((const char *)device, 0, &desired, &obtained, SDL_AUDIO_ALLOW_ANY_CHANGE);
SDLTest_AssertPass("SDL_OpenAudioDevice('%s',...)", device);
SDLTest_AssertCheck(id > 1, "Validate device ID; expected: >1, got: %i", id);
if (id > 1) {
/* TODO: enable test code when function is available in SDL2 */
#ifdef AUDIODEVICECONNECTED_DEFINED
/* Get connected status */
result = SDL_AudioDeviceConnected(id);
SDLTest_AssertPass("Call to SDL_AudioDeviceConnected()");
#endif
SDLTest_AssertCheck(result == 1, "Verify returned value; expected: 1; got: %i", result);
/* Close device again */
SDL_CloseAudioDevice(id);
SDLTest_AssertPass("Call to SDL_CloseAudioDevice()");
}
}
} else {
SDLTest_Log("No devices to test with");
}
return TEST_COMPLETED;
}
/* ================= Test Case References ================== */
/* Audio test cases */
static const SDLTest_TestCaseReference audioTest1 =
{ (SDLTest_TestCaseFp)audio_enumerateAndNameAudioDevices, "audio_enumerateAndNameAudioDevices", "Enumerate and name available audio devices (output and capture)", TEST_ENABLED };
static const SDLTest_TestCaseReference audioTest2 =
{ (SDLTest_TestCaseFp)audio_enumerateAndNameAudioDevicesNegativeTests, "audio_enumerateAndNameAudioDevicesNegativeTests", "Negative tests around enumeration and naming of audio devices.", TEST_ENABLED };
static const SDLTest_TestCaseReference audioTest3 =
{ (SDLTest_TestCaseFp)audio_printAudioDrivers, "audio_printAudioDrivers", "Checks available audio driver names.", TEST_ENABLED };
static const SDLTest_TestCaseReference audioTest4 =
{ (SDLTest_TestCaseFp)audio_printCurrentAudioDriver, "audio_printCurrentAudioDriver", "Checks current audio driver name with initialized audio.", TEST_ENABLED };
static const SDLTest_TestCaseReference audioTest5 =
{ (SDLTest_TestCaseFp)audio_buildAudioCVT, "audio_buildAudioCVT", "Builds various audio conversion structures.", TEST_ENABLED };
static const SDLTest_TestCaseReference audioTest6 =
{ (SDLTest_TestCaseFp)audio_buildAudioCVTNegative, "audio_buildAudioCVTNegative", "Checks calls with invalid input to SDL_BuildAudioCVT", TEST_ENABLED };
static const SDLTest_TestCaseReference audioTest7 =
{ (SDLTest_TestCaseFp)audio_getAudioStatus, "audio_getAudioStatus", "Checks current audio status.", TEST_ENABLED };
static const SDLTest_TestCaseReference audioTest8 =
{ (SDLTest_TestCaseFp)audio_openCloseAndGetAudioStatus, "audio_openCloseAndGetAudioStatus", "Opens and closes audio device and get audio status.", TEST_ENABLED };
static const SDLTest_TestCaseReference audioTest9 =
{ (SDLTest_TestCaseFp)audio_lockUnlockOpenAudioDevice, "audio_lockUnlockOpenAudioDevice", "Locks and unlocks an open audio device.", TEST_ENABLED };
/* TODO: enable test when SDL_ConvertAudio segfaults on cygwin have been fixed. */
/* For debugging, test case can be run manually using --filter audio_convertAudio */
static const SDLTest_TestCaseReference audioTest10 =
{ (SDLTest_TestCaseFp)audio_convertAudio, "audio_convertAudio", "Convert audio using available formats.", TEST_DISABLED };
/* TODO: enable test when SDL_AudioDeviceConnected has been implemented. */
static const SDLTest_TestCaseReference audioTest11 =
{ (SDLTest_TestCaseFp)audio_openCloseAudioDeviceConnected, "audio_openCloseAudioDeviceConnected", "Opens and closes audio device and get connected status.", TEST_DISABLED };
static const SDLTest_TestCaseReference audioTest12 =
{ (SDLTest_TestCaseFp)audio_quitInitAudioSubSystem, "audio_quitInitAudioSubSystem", "Quit and re-init audio subsystem.", TEST_ENABLED };
static const SDLTest_TestCaseReference audioTest13 =
{ (SDLTest_TestCaseFp)audio_initQuitAudio, "audio_initQuitAudio", "Init and quit audio drivers directly.", TEST_ENABLED };
static const SDLTest_TestCaseReference audioTest14 =
{ (SDLTest_TestCaseFp)audio_initOpenCloseQuitAudio, "audio_initOpenCloseQuitAudio", "Cycle through init, open, close and quit with various audio specs.", TEST_ENABLED };
static const SDLTest_TestCaseReference audioTest15 =
{ (SDLTest_TestCaseFp)audio_pauseUnpauseAudio, "audio_pauseUnpauseAudio", "Pause and Unpause audio for various audio specs while testing callback.", TEST_ENABLED };
/* Sequence of Audio test cases */
static const SDLTest_TestCaseReference *audioTests[] = {
&audioTest1, &audioTest2, &audioTest3, &audioTest4, &audioTest5, &audioTest6,
&audioTest7, &audioTest8, &audioTest9, &audioTest10, &audioTest11,
&audioTest12, &audioTest13, &audioTest14, &audioTest15, NULL
};
/* Audio test suite (global) */
SDLTest_TestSuiteReference audioTestSuite = {
"Audio",
_audioSetUp,
audioTests,
_audioTearDown
};
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_audio.c | C | apache-2.0 | 38,582 |
/**
* New/updated tests: aschiffler at ferzkopp dot net
*/
#include <stdio.h>
#include <string.h>
#include "SDL.h"
#include "SDL_test.h"
/* ================= Test Case Implementation ================== */
/* Test case functions */
/**
* \brief Check call to SDL_HasClipboardText
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_HasClipboardText
*/
int
clipboard_testHasClipboardText(void *arg)
{
SDL_bool result;
result = SDL_HasClipboardText();
SDLTest_AssertPass("Call to SDL_HasClipboardText succeeded");
return TEST_COMPLETED;
}
/**
* \brief Check call to SDL_GetClipboardText
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_GetClipboardText
*/
int
clipboard_testGetClipboardText(void *arg)
{
char *charResult;
charResult = SDL_GetClipboardText();
SDLTest_AssertPass("Call to SDL_GetClipboardText succeeded");
SDL_free(charResult);
return TEST_COMPLETED;
}
/**
* \brief Check call to SDL_SetClipboardText
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_SetClipboardText
*/
int
clipboard_testSetClipboardText(void *arg)
{
char *textRef = SDLTest_RandomAsciiString();
char *text = SDL_strdup(textRef);
int result;
result = SDL_SetClipboardText((const char *)text);
SDLTest_AssertPass("Call to SDL_SetClipboardText succeeded");
SDLTest_AssertCheck(
result == 0,
"Validate SDL_SetClipboardText result, expected 0, got %i",
result);
SDLTest_AssertCheck(
SDL_strcmp(textRef, text) == 0,
"Verify SDL_SetClipboardText did not modify input string, expected '%s', got '%s'",
textRef, text);
/* Cleanup */
SDL_free(textRef);
SDL_free(text);
return TEST_COMPLETED;
}
/**
* \brief End-to-end test of SDL_xyzClipboardText functions
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_HasClipboardText
* http://wiki.libsdl.org/moin.cgi/SDL_GetClipboardText
* http://wiki.libsdl.org/moin.cgi/SDL_SetClipboardText
*/
int
clipboard_testClipboardTextFunctions(void *arg)
{
char *textRef = SDLTest_RandomAsciiString();
char *text = SDL_strdup(textRef);
SDL_bool boolResult;
int intResult;
char *charResult;
/* Clear clipboard text state */
boolResult = SDL_HasClipboardText();
SDLTest_AssertPass("Call to SDL_HasClipboardText succeeded");
if (boolResult == SDL_TRUE) {
intResult = SDL_SetClipboardText((const char *)NULL);
SDLTest_AssertPass("Call to SDL_SetClipboardText(NULL) succeeded");
SDLTest_AssertCheck(
intResult == 0,
"Verify result from SDL_SetClipboardText(NULL), expected 0, got %i",
intResult);
charResult = SDL_GetClipboardText();
SDLTest_AssertPass("Call to SDL_GetClipboardText succeeded");
SDL_free(charResult);
boolResult = SDL_HasClipboardText();
SDLTest_AssertPass("Call to SDL_HasClipboardText succeeded");
SDLTest_AssertCheck(
boolResult == SDL_FALSE,
"Verify SDL_HasClipboardText returned SDL_FALSE, got %s",
(boolResult) ? "SDL_TRUE" : "SDL_FALSE");
}
/* Empty clipboard */
charResult = SDL_GetClipboardText();
SDLTest_AssertPass("Call to SDL_GetClipboardText succeeded");
SDLTest_AssertCheck(
charResult != NULL,
"Verify SDL_GetClipboardText did not return NULL");
SDLTest_AssertCheck(
charResult[0] == '\0',
"Verify SDL_GetClipboardText returned string with length 0, got length %i",
(int) SDL_strlen(charResult));
intResult = SDL_SetClipboardText((const char *)text);
SDLTest_AssertPass("Call to SDL_SetClipboardText succeeded");
SDLTest_AssertCheck(
intResult == 0,
"Verify result from SDL_SetClipboardText(NULL), expected 0, got %i",
intResult);
SDLTest_AssertCheck(
SDL_strcmp(textRef, text) == 0,
"Verify SDL_SetClipboardText did not modify input string, expected '%s', got '%s'",
textRef, text);
boolResult = SDL_HasClipboardText();
SDLTest_AssertPass("Call to SDL_HasClipboardText succeeded");
SDLTest_AssertCheck(
boolResult == SDL_TRUE,
"Verify SDL_HasClipboardText returned SDL_TRUE, got %s",
(boolResult) ? "SDL_TRUE" : "SDL_FALSE");
SDL_free(charResult);
charResult = SDL_GetClipboardText();
SDLTest_AssertPass("Call to SDL_GetClipboardText succeeded");
SDLTest_AssertCheck(
SDL_strcmp(textRef, charResult) == 0,
"Verify SDL_GetClipboardText returned correct string, expected '%s', got '%s'",
textRef, charResult);
/* Cleanup */
SDL_free(textRef);
SDL_free(text);
SDL_free(charResult);
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Clipboard test cases */
static const SDLTest_TestCaseReference clipboardTest1 =
{ (SDLTest_TestCaseFp)clipboard_testHasClipboardText, "clipboard_testHasClipboardText", "Check call to SDL_HasClipboardText", TEST_ENABLED };
static const SDLTest_TestCaseReference clipboardTest2 =
{ (SDLTest_TestCaseFp)clipboard_testGetClipboardText, "clipboard_testGetClipboardText", "Check call to SDL_GetClipboardText", TEST_ENABLED };
static const SDLTest_TestCaseReference clipboardTest3 =
{ (SDLTest_TestCaseFp)clipboard_testSetClipboardText, "clipboard_testSetClipboardText", "Check call to SDL_SetClipboardText", TEST_ENABLED };
static const SDLTest_TestCaseReference clipboardTest4 =
{ (SDLTest_TestCaseFp)clipboard_testClipboardTextFunctions, "clipboard_testClipboardTextFunctions", "End-to-end test of SDL_xyzClipboardText functions", TEST_ENABLED };
/* Sequence of Clipboard test cases */
static const SDLTest_TestCaseReference *clipboardTests[] = {
&clipboardTest1, &clipboardTest2, &clipboardTest3, &clipboardTest4, NULL
};
/* Clipboard test suite (global) */
SDLTest_TestSuiteReference clipboardTestSuite = {
"Clipboard",
NULL,
clipboardTests,
NULL
};
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_clipboard.c | C | apache-2.0 | 5,958 |
/**
* Events test suite
*/
#include <stdio.h>
#include "SDL.h"
#include "SDL_test.h"
/* ================= Test Case Implementation ================== */
/* Test case functions */
/* Flag indicating if the userdata should be checked */
int _userdataCheck = 0;
/* Userdata value to check */
int _userdataValue = 0;
/* Flag indicating that the filter was called */
int _eventFilterCalled = 0;
/* Userdata values for event */
int _userdataValue1 = 1;
int _userdataValue2 = 2;
/* Event filter that sets some flags and optionally checks userdata */
int SDLCALL _events_sampleNullEventFilter(void *userdata, SDL_Event *event)
{
_eventFilterCalled = 1;
if (_userdataCheck != 0) {
SDLTest_AssertCheck(userdata != NULL, "Check userdata pointer, expected: non-NULL, got: %s", (userdata != NULL) ? "non-NULL" : "NULL");
if (userdata != NULL) {
SDLTest_AssertCheck(*(int *)userdata == _userdataValue, "Check userdata value, expected: %i, got: %i", _userdataValue, *(int *)userdata);
}
}
return 0;
}
/**
* @brief Test pumping and peeking events.
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_PumpEvents
* @sa http://wiki.libsdl.org/moin.cgi/SDL_PollEvent
*/
int
events_pushPumpAndPollUserevent(void *arg)
{
SDL_Event event1;
SDL_Event event2;
int result;
/* Create user event */
event1.type = SDL_USEREVENT;
event1.user.code = SDLTest_RandomSint32();
event1.user.data1 = (void *)&_userdataValue1;
event1.user.data2 = (void *)&_userdataValue2;
/* Push a user event onto the queue and force queue update */
SDL_PushEvent(&event1);
SDLTest_AssertPass("Call to SDL_PushEvent()");
SDL_PumpEvents();
SDLTest_AssertPass("Call to SDL_PumpEvents()");
/* Poll for user event */
result = SDL_PollEvent(&event2);
SDLTest_AssertPass("Call to SDL_PollEvent()");
SDLTest_AssertCheck(result == 1, "Check result from SDL_PollEvent, expected: 1, got: %d", result);
return TEST_COMPLETED;
}
/**
* @brief Adds and deletes an event watch function with NULL userdata
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_AddEventWatch
* @sa http://wiki.libsdl.org/moin.cgi/SDL_DelEventWatch
*
*/
int
events_addDelEventWatch(void *arg)
{
SDL_Event event;
/* Create user event */
event.type = SDL_USEREVENT;
event.user.code = SDLTest_RandomSint32();
event.user.data1 = (void *)&_userdataValue1;
event.user.data2 = (void *)&_userdataValue2;
/* Disable userdata check */
_userdataCheck = 0;
/* Reset event filter call tracker */
_eventFilterCalled = 0;
/* Add watch */
SDL_AddEventWatch(_events_sampleNullEventFilter, NULL);
SDLTest_AssertPass("Call to SDL_AddEventWatch()");
/* Push a user event onto the queue and force queue update */
SDL_PushEvent(&event);
SDLTest_AssertPass("Call to SDL_PushEvent()");
SDL_PumpEvents();
SDLTest_AssertPass("Call to SDL_PumpEvents()");
SDLTest_AssertCheck(_eventFilterCalled == 1, "Check that event filter was called");
/* Delete watch */
SDL_DelEventWatch(_events_sampleNullEventFilter, NULL);
SDLTest_AssertPass("Call to SDL_DelEventWatch()");
/* Push a user event onto the queue and force queue update */
_eventFilterCalled = 0;
SDL_PushEvent(&event);
SDLTest_AssertPass("Call to SDL_PushEvent()");
SDL_PumpEvents();
SDLTest_AssertPass("Call to SDL_PumpEvents()");
SDLTest_AssertCheck(_eventFilterCalled == 0, "Check that event filter was NOT called");
return TEST_COMPLETED;
}
/**
* @brief Adds and deletes an event watch function with userdata
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_AddEventWatch
* @sa http://wiki.libsdl.org/moin.cgi/SDL_DelEventWatch
*
*/
int
events_addDelEventWatchWithUserdata(void *arg)
{
SDL_Event event;
/* Create user event */
event.type = SDL_USEREVENT;
event.user.code = SDLTest_RandomSint32();
event.user.data1 = (void *)&_userdataValue1;
event.user.data2 = (void *)&_userdataValue2;
/* Enable userdata check and set a value to check */
_userdataCheck = 1;
_userdataValue = SDLTest_RandomIntegerInRange(-1024, 1024);
/* Reset event filter call tracker */
_eventFilterCalled = 0;
/* Add watch */
SDL_AddEventWatch(_events_sampleNullEventFilter, (void *)&_userdataValue);
SDLTest_AssertPass("Call to SDL_AddEventWatch()");
/* Push a user event onto the queue and force queue update */
SDL_PushEvent(&event);
SDLTest_AssertPass("Call to SDL_PushEvent()");
SDL_PumpEvents();
SDLTest_AssertPass("Call to SDL_PumpEvents()");
SDLTest_AssertCheck(_eventFilterCalled == 1, "Check that event filter was called");
/* Delete watch */
SDL_DelEventWatch(_events_sampleNullEventFilter, (void *)&_userdataValue);
SDLTest_AssertPass("Call to SDL_DelEventWatch()");
/* Push a user event onto the queue and force queue update */
_eventFilterCalled = 0;
SDL_PushEvent(&event);
SDLTest_AssertPass("Call to SDL_PushEvent()");
SDL_PumpEvents();
SDLTest_AssertPass("Call to SDL_PumpEvents()");
SDLTest_AssertCheck(_eventFilterCalled == 0, "Check that event filter was NOT called");
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Events test cases */
static const SDLTest_TestCaseReference eventsTest1 =
{ (SDLTest_TestCaseFp)events_pushPumpAndPollUserevent, "events_pushPumpAndPollUserevent", "Pushes, pumps and polls a user event", TEST_ENABLED };
static const SDLTest_TestCaseReference eventsTest2 =
{ (SDLTest_TestCaseFp)events_addDelEventWatch, "events_addDelEventWatch", "Adds and deletes an event watch function with NULL userdata", TEST_ENABLED };
static const SDLTest_TestCaseReference eventsTest3 =
{ (SDLTest_TestCaseFp)events_addDelEventWatchWithUserdata, "events_addDelEventWatchWithUserdata", "Adds and deletes an event watch function with userdata", TEST_ENABLED };
/* Sequence of Events test cases */
static const SDLTest_TestCaseReference *eventsTests[] = {
&eventsTest1, &eventsTest2, &eventsTest3, NULL
};
/* Events test suite (global) */
SDLTest_TestSuiteReference eventsTestSuite = {
"Events",
NULL,
eventsTests,
NULL
};
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_events.c | C | apache-2.0 | 6,167 |
/**
* Hints test suite
*/
#include <stdio.h>
#include "SDL.h"
#include "SDL_test.h"
const int _numHintsEnum = 25;
char* _HintsEnum[] =
{
SDL_HINT_ACCELEROMETER_AS_JOYSTICK,
SDL_HINT_FRAMEBUFFER_ACCELERATION,
SDL_HINT_GAMECONTROLLERCONFIG,
SDL_HINT_GRAB_KEYBOARD,
SDL_HINT_IDLE_TIMER_DISABLED,
SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS,
SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK,
SDL_HINT_MOUSE_RELATIVE_MODE_WARP,
SDL_HINT_ORIENTATIONS,
SDL_HINT_RENDER_DIRECT3D_THREADSAFE,
SDL_HINT_RENDER_DRIVER,
SDL_HINT_RENDER_OPENGL_SHADERS,
SDL_HINT_RENDER_SCALE_QUALITY,
SDL_HINT_RENDER_VSYNC,
SDL_HINT_TIMER_RESOLUTION,
SDL_HINT_VIDEO_ALLOW_SCREENSAVER,
SDL_HINT_VIDEO_HIGHDPI_DISABLED,
SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES,
SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS,
SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT,
SDL_HINT_VIDEO_WIN_D3DCOMPILER,
SDL_HINT_VIDEO_X11_XINERAMA,
SDL_HINT_VIDEO_X11_XRANDR,
SDL_HINT_VIDEO_X11_XVIDMODE,
SDL_HINT_XINPUT_ENABLED,
};
char* _HintsVerbose[] =
{
"SDL_HINT_ACCELEROMETER_AS_JOYSTICK",
"SDL_HINT_FRAMEBUFFER_ACCELERATION",
"SDL_HINT_GAMECONTROLLERCONFIG",
"SDL_HINT_GRAB_KEYBOARD",
"SDL_HINT_IDLE_TIMER_DISABLED",
"SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS",
"SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK",
"SDL_HINT_MOUSE_RELATIVE_MODE_WARP",
"SDL_HINT_ORIENTATIONS",
"SDL_HINT_RENDER_DIRECT3D_THREADSAFE",
"SDL_HINT_RENDER_DRIVER",
"SDL_HINT_RENDER_OPENGL_SHADERS",
"SDL_HINT_RENDER_SCALE_QUALITY",
"SDL_HINT_RENDER_VSYNC",
"SDL_HINT_TIMER_RESOLUTION",
"SDL_HINT_VIDEO_ALLOW_SCREENSAVER",
"SDL_HINT_VIDEO_HIGHDPI_DISABLED",
"SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES",
"SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS",
"SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT",
"SDL_HINT_VIDEO_WIN_D3DCOMPILER",
"SDL_HINT_VIDEO_X11_XINERAMA",
"SDL_HINT_VIDEO_X11_XRANDR",
"SDL_HINT_VIDEO_X11_XVIDMODE",
"SDL_HINT_XINPUT_ENABLED"
};
/* Test case functions */
/**
* @brief Call to SDL_GetHint
*/
int
hints_getHint(void *arg)
{
char *result1;
char *result2;
int i;
for (i=0; i<_numHintsEnum; i++) {
result1 = (char *)SDL_GetHint((char*)_HintsEnum[i]);
SDLTest_AssertPass("Call to SDL_GetHint(%s) - using define definition", (char*)_HintsEnum[i]);
result2 = (char *)SDL_GetHint((char *)_HintsVerbose[i]);
SDLTest_AssertPass("Call to SDL_GetHint(%s) - using string definition", (char*)_HintsVerbose[i]);
SDLTest_AssertCheck(
(result1 == NULL && result2 == NULL) || (SDL_strcmp(result1, result2) == 0),
"Verify returned values are equal; got: result1='%s' result2='%s",
(result1 == NULL) ? "null" : result1,
(result2 == NULL) ? "null" : result2);
}
return TEST_COMPLETED;
}
/**
* @brief Call to SDL_SetHint
*/
int
hints_setHint(void *arg)
{
char *originalValue;
char *value;
char *testValue;
SDL_bool result;
int i, j;
/* Create random values to set */
value = SDLTest_RandomAsciiStringOfSize(10);
for (i=0; i<_numHintsEnum; i++) {
/* Capture current value */
originalValue = (char *)SDL_GetHint((char*)_HintsEnum[i]);
SDLTest_AssertPass("Call to SDL_GetHint(%s)", (char*)_HintsEnum[i]);
/* Set value (twice) */
for (j=1; j<=2; j++) {
result = SDL_SetHint((char*)_HintsEnum[i], value);
SDLTest_AssertPass("Call to SDL_SetHint(%s, %s) (iteration %i)", (char*)_HintsEnum[i], value, j);
SDLTest_AssertCheck(
result == SDL_TRUE || result == SDL_FALSE,
"Verify valid result was returned, got: %i",
(int)result);
testValue = (char *)SDL_GetHint((char*)_HintsEnum[i]);
SDLTest_AssertPass("Call to SDL_GetHint(%s) - using string definition", (char*)_HintsVerbose[i]);
SDLTest_AssertCheck(
(SDL_strcmp(value, testValue) == 0),
"Verify returned value equals set value; got: testValue='%s' value='%s",
(testValue == NULL) ? "null" : testValue,
value);
}
/* Reset original value */
result = SDL_SetHint((char*)_HintsEnum[i], originalValue);
SDLTest_AssertPass("Call to SDL_SetHint(%s, originalValue)", (char*)_HintsEnum[i]);
SDLTest_AssertCheck(
result == SDL_TRUE || result == SDL_FALSE,
"Verify valid result was returned, got: %i",
(int)result);
}
SDL_free(value);
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Hints test cases */
static const SDLTest_TestCaseReference hintsTest1 =
{ (SDLTest_TestCaseFp)hints_getHint, "hints_getHint", "Call to SDL_GetHint", TEST_ENABLED };
static const SDLTest_TestCaseReference hintsTest2 =
{ (SDLTest_TestCaseFp)hints_setHint, "hints_setHint", "Call to SDL_SetHint", TEST_ENABLED };
/* Sequence of Hints test cases */
static const SDLTest_TestCaseReference *hintsTests[] = {
&hintsTest1, &hintsTest2, NULL
};
/* Hints test suite (global) */
SDLTest_TestSuiteReference hintsTestSuite = {
"Hints",
NULL,
hintsTests,
NULL
};
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_hints.c | C | apache-2.0 | 5,125 |
/**
* Keyboard test suite
*/
#include <stdio.h>
#include <limits.h>
#include "SDL_config.h"
#include "SDL.h"
#include "SDL_test.h"
/* ================= Test Case Implementation ================== */
/* Test case functions */
/**
* @brief Check call to SDL_GetKeyboardState with and without numkeys reference.
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_GetKeyboardState
*/
int
keyboard_getKeyboardState(void *arg)
{
int numkeys;
Uint8 *state;
/* Case where numkeys pointer is NULL */
state = (Uint8 *)SDL_GetKeyboardState(NULL);
SDLTest_AssertPass("Call to SDL_GetKeyboardState(NULL)");
SDLTest_AssertCheck(state != NULL, "Validate that return value from SDL_GetKeyboardState is not NULL");
/* Case where numkeys pointer is not NULL */
numkeys = -1;
state = (Uint8 *)SDL_GetKeyboardState(&numkeys);
SDLTest_AssertPass("Call to SDL_GetKeyboardState(&numkeys)");
SDLTest_AssertCheck(state != NULL, "Validate that return value from SDL_GetKeyboardState is not NULL");
SDLTest_AssertCheck(numkeys >= 0, "Validate that value of numkeys is >= 0, got: %i", numkeys);
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetKeyboardFocus
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_GetKeyboardFocus
*/
int
keyboard_getKeyboardFocus(void *arg)
{
SDL_Window* window;
/* Call, but ignore return value */
window = SDL_GetKeyboardFocus();
SDLTest_AssertPass("Call to SDL_GetKeyboardFocus()");
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetKeyFromName for known, unknown and invalid name.
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_GetKeyFromName
*/
int
keyboard_getKeyFromName(void *arg)
{
SDL_Keycode result;
/* Case where Key is known, 1 character input */
result = SDL_GetKeyFromName("A");
SDLTest_AssertPass("Call to SDL_GetKeyFromName(known/single)");
SDLTest_AssertCheck(result == SDLK_a, "Verify result from call, expected: %i, got: %i", SDLK_a, result);
/* Case where Key is known, 2 character input */
result = SDL_GetKeyFromName("F1");
SDLTest_AssertPass("Call to SDL_GetKeyFromName(known/double)");
SDLTest_AssertCheck(result == SDLK_F1, "Verify result from call, expected: %i, got: %i", SDLK_F1, result);
/* Case where Key is known, 3 character input */
result = SDL_GetKeyFromName("End");
SDLTest_AssertPass("Call to SDL_GetKeyFromName(known/triple)");
SDLTest_AssertCheck(result == SDLK_END, "Verify result from call, expected: %i, got: %i", SDLK_END, result);
/* Case where Key is known, 4 character input */
result = SDL_GetKeyFromName("Find");
SDLTest_AssertPass("Call to SDL_GetKeyFromName(known/quad)");
SDLTest_AssertCheck(result == SDLK_FIND, "Verify result from call, expected: %i, got: %i", SDLK_FIND, result);
/* Case where Key is known, multiple character input */
result = SDL_GetKeyFromName("AudioStop");
SDLTest_AssertPass("Call to SDL_GetKeyFromName(known/multi)");
SDLTest_AssertCheck(result == SDLK_AUDIOSTOP, "Verify result from call, expected: %i, got: %i", SDLK_AUDIOSTOP, result);
/* Case where Key is unknown */
result = SDL_GetKeyFromName("NotThere");
SDLTest_AssertPass("Call to SDL_GetKeyFromName(unknown)");
SDLTest_AssertCheck(result == SDLK_UNKNOWN, "Verify result from call is UNKNOWN, expected: %i, got: %i", SDLK_UNKNOWN, result);
/* Case where input is NULL/invalid */
result = SDL_GetKeyFromName(NULL);
SDLTest_AssertPass("Call to SDL_GetKeyFromName(NULL)");
SDLTest_AssertCheck(result == SDLK_UNKNOWN, "Verify result from call is UNKNOWN, expected: %i, got: %i", SDLK_UNKNOWN, result);
return TEST_COMPLETED;
}
/*
* Local helper to check for the invalid scancode error message
*/
void
_checkInvalidScancodeError()
{
const char *expectedError = "Parameter 'scancode' is invalid";
const char *error;
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
if (error != NULL) {
SDLTest_AssertCheck(SDL_strcmp(error, expectedError) == 0,
"Validate error message, expected: '%s', got: '%s'", expectedError, error);
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
}
}
/**
* @brief Check call to SDL_GetKeyFromScancode
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_GetKeyFromScancode
*/
int
keyboard_getKeyFromScancode(void *arg)
{
SDL_Keycode result;
/* Case where input is valid */
result = SDL_GetKeyFromScancode(SDL_SCANCODE_A);
SDLTest_AssertPass("Call to SDL_GetKeyFromScancode(valid)");
SDLTest_AssertCheck(result == SDLK_a, "Verify result from call, expected: %i, got: %i", SDLK_a, result);
/* Case where input is zero */
result = SDL_GetKeyFromScancode(0);
SDLTest_AssertPass("Call to SDL_GetKeyFromScancode(0)");
SDLTest_AssertCheck(result == SDLK_UNKNOWN, "Verify result from call is UNKNOWN, expected: %i, got: %i", SDLK_UNKNOWN, result);
/* Clear error message */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
/* Case where input is invalid (too small) */
result = SDL_GetKeyFromScancode(-999);
SDLTest_AssertPass("Call to SDL_GetKeyFromScancode(-999)");
SDLTest_AssertCheck(result == SDLK_UNKNOWN, "Verify result from call is UNKNOWN, expected: %i, got: %i", SDLK_UNKNOWN, result);
_checkInvalidScancodeError();
/* Case where input is invalid (too big) */
result = SDL_GetKeyFromScancode(999);
SDLTest_AssertPass("Call to SDL_GetKeyFromScancode(999)");
SDLTest_AssertCheck(result == SDLK_UNKNOWN, "Verify result from call is UNKNOWN, expected: %i, got: %i", SDLK_UNKNOWN, result);
_checkInvalidScancodeError();
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetKeyName
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_GetKeyName
*/
int
keyboard_getKeyName(void *arg)
{
char *result;
char *expected;
/* Case where key has a 1 character name */
expected = "3";
result = (char *)SDL_GetKeyName(SDLK_3);
SDLTest_AssertPass("Call to SDL_GetKeyName()");
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: %s, got: %s", expected, result);
/* Case where key has a 2 character name */
expected = "F1";
result = (char *)SDL_GetKeyName(SDLK_F1);
SDLTest_AssertPass("Call to SDL_GetKeyName()");
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: %s, got: %s", expected, result);
/* Case where key has a 3 character name */
expected = "Cut";
result = (char *)SDL_GetKeyName(SDLK_CUT);
SDLTest_AssertPass("Call to SDL_GetKeyName()");
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: %s, got: %s", expected, result);
/* Case where key has a 4 character name */
expected = "Down";
result = (char *)SDL_GetKeyName(SDLK_DOWN);
SDLTest_AssertPass("Call to SDL_GetKeyName()");
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: %s, got: %s", expected, result);
/* Case where key has a N character name */
expected = "BrightnessUp";
result = (char *)SDL_GetKeyName(SDLK_BRIGHTNESSUP);
SDLTest_AssertPass("Call to SDL_GetKeyName()");
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: %s, got: %s", expected, result);
/* Case where key has a N character name with space */
expected = "Keypad MemStore";
result = (char *)SDL_GetKeyName(SDLK_KP_MEMSTORE);
SDLTest_AssertPass("Call to SDL_GetKeyName()");
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: %s, got: %s", expected, result);
return TEST_COMPLETED;
}
/**
* @brief SDL_GetScancodeName negative cases
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_GetScancodeName
*/
int
keyboard_getScancodeNameNegative(void *arg)
{
SDL_Scancode scancode;
char *result;
char *expected = "";
/* Clear error message */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
/* Out-of-bounds scancode */
scancode = (SDL_Scancode)SDL_NUM_SCANCODES;
result = (char *)SDL_GetScancodeName(scancode);
SDLTest_AssertPass("Call to SDL_GetScancodeName(%d/large)", scancode);
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: '%s', got: '%s'", expected, result);
_checkInvalidScancodeError();
return TEST_COMPLETED;
}
/**
* @brief SDL_GetKeyName negative cases
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_GetKeyName
*/
int
keyboard_getKeyNameNegative(void *arg)
{
SDL_Keycode keycode;
char *result;
char *expected = "";
/* Unknown keycode */
keycode = SDLK_UNKNOWN;
result = (char *)SDL_GetKeyName(keycode);
SDLTest_AssertPass("Call to SDL_GetKeyName(%d/unknown)", keycode);
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: '%s', got: '%s'", expected, result);
/* Clear error message */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
/* Negative keycode */
keycode = (SDL_Keycode)SDLTest_RandomIntegerInRange(-255, -1);
result = (char *)SDL_GetKeyName(keycode);
SDLTest_AssertPass("Call to SDL_GetKeyName(%d/negative)", keycode);
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: '%s', got: '%s'", expected, result);
_checkInvalidScancodeError();
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetModState and SDL_SetModState
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_GetModState
* @sa http://wiki.libsdl.org/moin.cgi/SDL_SetModState
*/
int
keyboard_getSetModState(void *arg)
{
SDL_Keymod result;
SDL_Keymod currentState;
SDL_Keymod newState;
SDL_Keymod allStates =
KMOD_NONE |
KMOD_LSHIFT |
KMOD_RSHIFT |
KMOD_LCTRL |
KMOD_RCTRL |
KMOD_LALT |
KMOD_RALT |
KMOD_LGUI |
KMOD_RGUI |
KMOD_NUM |
KMOD_CAPS |
KMOD_MODE |
KMOD_RESERVED;
/* Get state, cache for later reset */
result = SDL_GetModState();
SDLTest_AssertPass("Call to SDL_GetModState()");
SDLTest_AssertCheck(/*result >= 0 &&*/ result <= allStates, "Verify result from call is valid, expected: 0 <= result <= %i, got: %i", allStates, result);
currentState = result;
/* Set random state */
newState = SDLTest_RandomIntegerInRange(0, allStates);
SDL_SetModState(newState);
SDLTest_AssertPass("Call to SDL_SetModState(%i)", newState);
result = SDL_GetModState();
SDLTest_AssertPass("Call to SDL_GetModState()");
SDLTest_AssertCheck(result == newState, "Verify result from call is valid, expected: %i, got: %i", newState, result);
/* Set zero state */
SDL_SetModState(0);
SDLTest_AssertPass("Call to SDL_SetModState(0)");
result = SDL_GetModState();
SDLTest_AssertPass("Call to SDL_GetModState()");
SDLTest_AssertCheck(result == 0, "Verify result from call is valid, expected: 0, got: %i", result);
/* Revert back to cached current state if needed */
if (currentState != 0) {
SDL_SetModState(currentState);
SDLTest_AssertPass("Call to SDL_SetModState(%i)", currentState);
result = SDL_GetModState();
SDLTest_AssertPass("Call to SDL_GetModState()");
SDLTest_AssertCheck(result == currentState, "Verify result from call is valid, expected: %i, got: %i", currentState, result);
}
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_StartTextInput and SDL_StopTextInput
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_StartTextInput
* @sa http://wiki.libsdl.org/moin.cgi/SDL_StopTextInput
*/
int
keyboard_startStopTextInput(void *arg)
{
/* Start-Stop */
SDL_StartTextInput();
SDLTest_AssertPass("Call to SDL_StartTextInput()");
SDL_StopTextInput();
SDLTest_AssertPass("Call to SDL_StopTextInput()");
/* Stop-Start */
SDL_StartTextInput();
SDLTest_AssertPass("Call to SDL_StartTextInput()");
/* Start-Start */
SDL_StartTextInput();
SDLTest_AssertPass("Call to SDL_StartTextInput()");
/* Stop-Stop */
SDL_StopTextInput();
SDLTest_AssertPass("Call to SDL_StopTextInput()");
SDL_StopTextInput();
SDLTest_AssertPass("Call to SDL_StopTextInput()");
return TEST_COMPLETED;
}
/* Internal function to test SDL_SetTextInputRect */
void _testSetTextInputRect(SDL_Rect refRect)
{
SDL_Rect testRect;
testRect = refRect;
SDL_SetTextInputRect(&testRect);
SDLTest_AssertPass("Call to SDL_SetTextInputRect with refRect(x:%i,y:%i,w:%i,h:%i)", refRect.x, refRect.y, refRect.w, refRect.h);
SDLTest_AssertCheck(
(refRect.x == testRect.x) && (refRect.y == testRect.y) && (refRect.w == testRect.w) && (refRect.h == testRect.h),
"Check that input data was not modified, expected: x:%i,y:%i,w:%i,h:%i, got: x:%i,y:%i,w:%i,h:%i",
refRect.x, refRect.y, refRect.w, refRect.h,
testRect.x, testRect.y, testRect.w, testRect.h);
}
/**
* @brief Check call to SDL_SetTextInputRect
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_SetTextInputRect
*/
int
keyboard_setTextInputRect(void *arg)
{
SDL_Rect refRect;
/* Normal visible refRect, origin inside */
refRect.x = SDLTest_RandomIntegerInRange(1, 50);
refRect.y = SDLTest_RandomIntegerInRange(1, 50);
refRect.w = SDLTest_RandomIntegerInRange(10, 50);
refRect.h = SDLTest_RandomIntegerInRange(10, 50);
_testSetTextInputRect(refRect);
/* Normal visible refRect, origin 0,0 */
refRect.x = 0;
refRect.y = 0;
refRect.w = SDLTest_RandomIntegerInRange(10, 50);
refRect.h = SDLTest_RandomIntegerInRange(10, 50);
_testSetTextInputRect(refRect);
/* 1Pixel refRect */
refRect.x = SDLTest_RandomIntegerInRange(10, 50);
refRect.y = SDLTest_RandomIntegerInRange(10, 50);
refRect.w = 1;
refRect.h = 1;
_testSetTextInputRect(refRect);
/* 0pixel refRect */
refRect.x = 1;
refRect.y = 1;
refRect.w = 1;
refRect.h = 0;
_testSetTextInputRect(refRect);
/* 0pixel refRect */
refRect.x = 1;
refRect.y = 1;
refRect.w = 0;
refRect.h = 1;
_testSetTextInputRect(refRect);
/* 0pixel refRect */
refRect.x = 1;
refRect.y = 1;
refRect.w = 0;
refRect.h = 0;
_testSetTextInputRect(refRect);
/* 0pixel refRect */
refRect.x = 0;
refRect.y = 0;
refRect.w = 0;
refRect.h = 0;
_testSetTextInputRect(refRect);
/* negative refRect */
refRect.x = SDLTest_RandomIntegerInRange(-200, -100);
refRect.y = SDLTest_RandomIntegerInRange(-200, -100);
refRect.w = 50;
refRect.h = 50;
_testSetTextInputRect(refRect);
/* oversized refRect */
refRect.x = SDLTest_RandomIntegerInRange(1, 50);
refRect.y = SDLTest_RandomIntegerInRange(1, 50);
refRect.w = 5000;
refRect.h = 5000;
_testSetTextInputRect(refRect);
/* NULL refRect */
SDL_SetTextInputRect(NULL);
SDLTest_AssertPass("Call to SDL_SetTextInputRect(NULL)");
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_SetTextInputRect with invalid data
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_SetTextInputRect
*/
int
keyboard_setTextInputRectNegative(void *arg)
{
/* Some platforms set also an error message; prepare for checking it */
#if SDL_VIDEO_DRIVER_WINDOWS || SDL_VIDEO_DRIVER_ANDROID || SDL_VIDEO_DRIVER_COCOA
const char *expectedError = "Parameter 'rect' is invalid";
const char *error;
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
#endif
/* NULL refRect */
SDL_SetTextInputRect(NULL);
SDLTest_AssertPass("Call to SDL_SetTextInputRect(NULL)");
/* Some platforms set also an error message; so check it */
#if SDL_VIDEO_DRIVER_WINDOWS || SDL_VIDEO_DRIVER_ANDROID || SDL_VIDEO_DRIVER_COCOA
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
if (error != NULL) {
SDLTest_AssertCheck(SDL_strcmp(error, expectedError) == 0,
"Validate error message, expected: '%s', got: '%s'", expectedError, error);
}
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
#endif
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetScancodeFromKey
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_GetScancodeFromKey
* @sa http://wiki.libsdl.org/moin.cgi/SDL_Keycode
*/
int
keyboard_getScancodeFromKey(void *arg)
{
SDL_Scancode scancode;
/* Regular key */
scancode = SDL_GetScancodeFromKey(SDLK_4);
SDLTest_AssertPass("Call to SDL_GetScancodeFromKey(SDLK_4)");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_4, "Validate return value from SDL_GetScancodeFromKey, expected: %i, got: %i", SDL_SCANCODE_4, scancode);
/* Virtual key */
scancode = SDL_GetScancodeFromKey(SDLK_PLUS);
SDLTest_AssertPass("Call to SDL_GetScancodeFromKey(SDLK_PLUS)");
SDLTest_AssertCheck(scancode == 0, "Validate return value from SDL_GetScancodeFromKey, expected: 0, got: %i", scancode);
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetScancodeFromName
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_GetScancodeFromName
* @sa http://wiki.libsdl.org/moin.cgi/SDL_Keycode
*/
int
keyboard_getScancodeFromName(void *arg)
{
SDL_Scancode scancode;
/* Regular key, 1 character, first name in list */
scancode = SDL_GetScancodeFromName("A");
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('A')");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_A, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_A, scancode);
/* Regular key, 1 character */
scancode = SDL_GetScancodeFromName("4");
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('4')");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_4, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_4, scancode);
/* Regular key, 2 characters */
scancode = SDL_GetScancodeFromName("F1");
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('F1')");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_F1, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_F1, scancode);
/* Regular key, 3 characters */
scancode = SDL_GetScancodeFromName("End");
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('End')");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_END, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_END, scancode);
/* Regular key, 4 characters */
scancode = SDL_GetScancodeFromName("Find");
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('Find')");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_FIND, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_FIND, scancode);
/* Regular key, several characters */
scancode = SDL_GetScancodeFromName("Backspace");
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('Backspace')");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_BACKSPACE, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_BACKSPACE, scancode);
/* Regular key, several characters with space */
scancode = SDL_GetScancodeFromName("Keypad Enter");
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('Keypad Enter')");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_KP_ENTER, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_KP_ENTER, scancode);
/* Regular key, last name in list */
scancode = SDL_GetScancodeFromName("Sleep");
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('Sleep')");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_SLEEP, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_SLEEP, scancode);
return TEST_COMPLETED;
}
/*
* Local helper to check for the invalid scancode error message
*/
void
_checkInvalidNameError()
{
const char *expectedError = "Parameter 'name' is invalid";
const char *error;
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
if (error != NULL) {
SDLTest_AssertCheck(SDL_strcmp(error, expectedError) == 0,
"Validate error message, expected: '%s', got: '%s'", expectedError, error);
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
}
}
/**
* @brief Check call to SDL_GetScancodeFromName with invalid data
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_GetScancodeFromName
* @sa http://wiki.libsdl.org/moin.cgi/SDL_Keycode
*/
int
keyboard_getScancodeFromNameNegative(void *arg)
{
char *name;
SDL_Scancode scancode;
/* Clear error message */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
/* Random string input */
name = SDLTest_RandomAsciiStringOfSize(32);
SDLTest_Assert(name != NULL, "Check that random name is not NULL");
if (name == NULL) {
return TEST_ABORTED;
}
scancode = SDL_GetScancodeFromName((const char *)name);
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('%s')", name);
SDL_free(name);
SDLTest_AssertCheck(scancode == SDL_SCANCODE_UNKNOWN, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_UNKNOWN, scancode);
_checkInvalidNameError();
/* Zero length string input */
name = "";
scancode = SDL_GetScancodeFromName((const char *)name);
SDLTest_AssertPass("Call to SDL_GetScancodeFromName(NULL)");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_UNKNOWN, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_UNKNOWN, scancode);
_checkInvalidNameError();
/* NULL input */
name = NULL;
scancode = SDL_GetScancodeFromName((const char *)name);
SDLTest_AssertPass("Call to SDL_GetScancodeFromName(NULL)");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_UNKNOWN, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_UNKNOWN, scancode);
_checkInvalidNameError();
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Keyboard test cases */
static const SDLTest_TestCaseReference keyboardTest1 =
{ (SDLTest_TestCaseFp)keyboard_getKeyboardState, "keyboard_getKeyboardState", "Check call to SDL_GetKeyboardState with and without numkeys reference", TEST_ENABLED };
static const SDLTest_TestCaseReference keyboardTest2 =
{ (SDLTest_TestCaseFp)keyboard_getKeyboardFocus, "keyboard_getKeyboardFocus", "Check call to SDL_GetKeyboardFocus", TEST_ENABLED };
static const SDLTest_TestCaseReference keyboardTest3 =
{ (SDLTest_TestCaseFp)keyboard_getKeyFromName, "keyboard_getKeyFromName", "Check call to SDL_GetKeyFromName for known, unknown and invalid name", TEST_ENABLED };
static const SDLTest_TestCaseReference keyboardTest4 =
{ (SDLTest_TestCaseFp)keyboard_getKeyFromScancode, "keyboard_getKeyFromScancode", "Check call to SDL_GetKeyFromScancode", TEST_ENABLED };
static const SDLTest_TestCaseReference keyboardTest5 =
{ (SDLTest_TestCaseFp)keyboard_getKeyName, "keyboard_getKeyName", "Check call to SDL_GetKeyName", TEST_ENABLED };
static const SDLTest_TestCaseReference keyboardTest6 =
{ (SDLTest_TestCaseFp)keyboard_getSetModState, "keyboard_getSetModState", "Check call to SDL_GetModState and SDL_SetModState", TEST_ENABLED };
static const SDLTest_TestCaseReference keyboardTest7 =
{ (SDLTest_TestCaseFp)keyboard_startStopTextInput, "keyboard_startStopTextInput", "Check call to SDL_StartTextInput and SDL_StopTextInput", TEST_ENABLED };
static const SDLTest_TestCaseReference keyboardTest8 =
{ (SDLTest_TestCaseFp)keyboard_setTextInputRect, "keyboard_setTextInputRect", "Check call to SDL_SetTextInputRect", TEST_ENABLED };
static const SDLTest_TestCaseReference keyboardTest9 =
{ (SDLTest_TestCaseFp)keyboard_setTextInputRectNegative, "keyboard_setTextInputRectNegative", "Check call to SDL_SetTextInputRect with invalid data", TEST_ENABLED };
static const SDLTest_TestCaseReference keyboardTest10 =
{ (SDLTest_TestCaseFp)keyboard_getScancodeFromKey, "keyboard_getScancodeFromKey", "Check call to SDL_GetScancodeFromKey", TEST_ENABLED };
static const SDLTest_TestCaseReference keyboardTest11 =
{ (SDLTest_TestCaseFp)keyboard_getScancodeFromName, "keyboard_getScancodeFromName", "Check call to SDL_GetScancodeFromName", TEST_ENABLED };
static const SDLTest_TestCaseReference keyboardTest12 =
{ (SDLTest_TestCaseFp)keyboard_getScancodeFromNameNegative, "keyboard_getScancodeFromNameNegative", "Check call to SDL_GetScancodeFromName with invalid data", TEST_ENABLED };
static const SDLTest_TestCaseReference keyboardTest13 =
{ (SDLTest_TestCaseFp)keyboard_getKeyNameNegative, "keyboard_getKeyNameNegative", "Check call to SDL_GetKeyName with invalid data", TEST_ENABLED };
static const SDLTest_TestCaseReference keyboardTest14 =
{ (SDLTest_TestCaseFp)keyboard_getScancodeNameNegative, "keyboard_getScancodeNameNegative", "Check call to SDL_GetScancodeName with invalid data", TEST_ENABLED };
/* Sequence of Keyboard test cases */
static const SDLTest_TestCaseReference *keyboardTests[] = {
&keyboardTest1, &keyboardTest2, &keyboardTest3, &keyboardTest4, &keyboardTest5, &keyboardTest6,
&keyboardTest7, &keyboardTest8, &keyboardTest9, &keyboardTest10, &keyboardTest11, &keyboardTest12,
&keyboardTest13, &keyboardTest14, NULL
};
/* Keyboard test suite (global) */
SDLTest_TestSuiteReference keyboardTestSuite = {
"Keyboard",
NULL,
keyboardTests,
NULL
};
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_keyboard.c | C | apache-2.0 | 26,515 |
/**
* Automated SDL subsystems management test.
*
* Written by J�rgen Tjern� "jorgenpt"
*
* Released under Public Domain.
*/
#include "SDL.h"
#include "SDL_test.h"
/* !
* \brief Tests SDL_Init() and SDL_Quit() of Joystick and Haptic subsystems
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_Init
* http://wiki.libsdl.org/moin.cgi/SDL_Quit
*/
static int main_testInitQuitJoystickHaptic (void *arg)
{
#if defined SDL_JOYSTICK_DISABLED || defined SDL_HAPTIC_DISABLED
return TEST_SKIPPED;
#else
int enabled_subsystems;
int initialized_subsystems = SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC;
SDLTest_AssertCheck( SDL_Init(initialized_subsystems) == 0, "SDL_Init multiple systems." );
enabled_subsystems = SDL_WasInit(initialized_subsystems);
SDLTest_AssertCheck( enabled_subsystems == initialized_subsystems, "SDL_WasInit(SDL_INIT_EVERYTHING) contains all systems (%i)", enabled_subsystems );
SDL_Quit();
enabled_subsystems = SDL_WasInit(initialized_subsystems);
SDLTest_AssertCheck( enabled_subsystems == 0, "SDL_Quit should shut down everything (%i)", enabled_subsystems );
return TEST_COMPLETED;
#endif
}
/* !
* \brief Tests SDL_InitSubSystem() and SDL_QuitSubSystem()
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_Init
* http://wiki.libsdl.org/moin.cgi/SDL_Quit
*/
static int main_testInitQuitSubSystem (void *arg)
{
#if defined SDL_JOYSTICK_DISABLED || defined SDL_HAPTIC_DISABLED || defined SDL_GAMECONTROLLER_DISABLED
return TEST_SKIPPED;
#else
int i;
int subsystems[] = { SDL_INIT_JOYSTICK, SDL_INIT_HAPTIC, SDL_INIT_GAMECONTROLLER };
for (i = 0; i < SDL_arraysize(subsystems); ++i) {
int initialized_system;
int subsystem = subsystems[i];
SDLTest_AssertCheck( (SDL_WasInit(subsystem) & subsystem) == 0, "SDL_WasInit(%x) before init should be false", subsystem );
SDLTest_AssertCheck( SDL_InitSubSystem(subsystem) == 0, "SDL_InitSubSystem(%x)", subsystem );
initialized_system = SDL_WasInit(subsystem);
SDLTest_AssertCheck( (initialized_system & subsystem) != 0, "SDL_WasInit(%x) should be true (%x)", subsystem, initialized_system );
SDL_QuitSubSystem(subsystem);
SDLTest_AssertCheck( (SDL_WasInit(subsystem) & subsystem) == 0, "SDL_WasInit(%x) after shutdown should be false", subsystem );
}
return TEST_COMPLETED;
#endif
}
const int joy_and_controller = SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER;
static int main_testImpliedJoystickInit (void *arg)
{
#if defined SDL_JOYSTICK_DISABLED || defined SDL_GAMECONTROLLER_DISABLED
return TEST_SKIPPED;
#else
int initialized_system;
/* First initialize the controller */
SDLTest_AssertCheck( (SDL_WasInit(joy_and_controller) & joy_and_controller) == 0, "SDL_WasInit() before init should be false for joystick & controller" );
SDLTest_AssertCheck( SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) == 0, "SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER)" );
/* Then make sure this implicitly initialized the joystick subsystem */
initialized_system = SDL_WasInit(joy_and_controller);
SDLTest_AssertCheck( (initialized_system & joy_and_controller) == joy_and_controller, "SDL_WasInit() should be true for joystick & controller (%x)", initialized_system );
/* Then quit the controller, and make sure that implicitly also quits the */
/* joystick subsystem */
SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
initialized_system = SDL_WasInit(joy_and_controller);
SDLTest_AssertCheck( (initialized_system & joy_and_controller) == 0, "SDL_WasInit() should be false for joystick & controller (%x)", initialized_system );
return TEST_COMPLETED;
#endif
}
static int main_testImpliedJoystickQuit (void *arg)
{
#if defined SDL_JOYSTICK_DISABLED || defined SDL_GAMECONTROLLER_DISABLED
return TEST_SKIPPED;
#else
int initialized_system;
/* First initialize the controller and the joystick (explicitly) */
SDLTest_AssertCheck( (SDL_WasInit(joy_and_controller) & joy_and_controller) == 0, "SDL_WasInit() before init should be false for joystick & controller" );
SDLTest_AssertCheck( SDL_InitSubSystem(SDL_INIT_JOYSTICK) == 0, "SDL_InitSubSystem(SDL_INIT_JOYSTICK)" );
SDLTest_AssertCheck( SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) == 0, "SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER)" );
/* Then make sure they're both initialized properly */
initialized_system = SDL_WasInit(joy_and_controller);
SDLTest_AssertCheck( (initialized_system & joy_and_controller) == joy_and_controller, "SDL_WasInit() should be true for joystick & controller (%x)", initialized_system );
/* Then quit the controller, and make sure that it does NOT quit the */
/* explicitly initialized joystick subsystem. */
SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
initialized_system = SDL_WasInit(joy_and_controller);
SDLTest_AssertCheck( (initialized_system & joy_and_controller) == SDL_INIT_JOYSTICK, "SDL_WasInit() should be false for joystick & controller (%x)", initialized_system );
SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
return TEST_COMPLETED;
#endif
}
static const SDLTest_TestCaseReference mainTest1 =
{ (SDLTest_TestCaseFp)main_testInitQuitJoystickHaptic, "main_testInitQuitJoystickHaptic", "Tests SDL_Init/Quit of Joystick and Haptic subsystem", TEST_ENABLED};
static const SDLTest_TestCaseReference mainTest2 =
{ (SDLTest_TestCaseFp)main_testInitQuitSubSystem, "main_testInitQuitSubSystem", "Tests SDL_InitSubSystem/QuitSubSystem", TEST_ENABLED};
static const SDLTest_TestCaseReference mainTest3 =
{ (SDLTest_TestCaseFp)main_testImpliedJoystickInit, "main_testImpliedJoystickInit", "Tests that init for gamecontroller properly implies joystick", TEST_ENABLED};
static const SDLTest_TestCaseReference mainTest4 =
{ (SDLTest_TestCaseFp)main_testImpliedJoystickQuit, "main_testImpliedJoystickQuit", "Tests that quit for gamecontroller doesn't quit joystick if you inited it explicitly", TEST_ENABLED};
/* Sequence of Main test cases */
static const SDLTest_TestCaseReference *mainTests[] = {
&mainTest1,
&mainTest2,
&mainTest3,
&mainTest4,
NULL
};
/* Main test suite (global) */
SDLTest_TestSuiteReference mainTestSuite = {
"Main",
NULL,
mainTests,
NULL
};
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_main.c | C | apache-2.0 | 6,343 |
/**
* Mouse test suite
*/
#include <stdio.h>
#include <limits.h>
#include "SDL.h"
#include "SDL_test.h"
/* ================= Test Case Implementation ================== */
/* Test case functions */
/* Helper to evaluate state returned from SDL_GetMouseState */
int _mouseStateCheck(Uint32 state)
{
return (state == 0) ||
(state == SDL_BUTTON(SDL_BUTTON_LEFT)) ||
(state == SDL_BUTTON(SDL_BUTTON_MIDDLE)) ||
(state == SDL_BUTTON(SDL_BUTTON_RIGHT)) ||
(state == SDL_BUTTON(SDL_BUTTON_X1)) ||
(state == SDL_BUTTON(SDL_BUTTON_X2));
}
/**
* @brief Check call to SDL_GetMouseState
*
*/
int
mouse_getMouseState(void *arg)
{
int x;
int y;
Uint32 state;
/* Pump some events to update mouse state */
SDL_PumpEvents();
SDLTest_AssertPass("Call to SDL_PumpEvents()");
/* Case where x, y pointer is NULL */
state = SDL_GetMouseState(NULL, NULL);
SDLTest_AssertPass("Call to SDL_GetMouseState(NULL, NULL)");
SDLTest_AssertCheck(_mouseStateCheck(state), "Validate state returned from function, got: %i", state);
/* Case where x pointer is not NULL */
x = INT_MIN;
state = SDL_GetMouseState(&x, NULL);
SDLTest_AssertPass("Call to SDL_GetMouseState(&x, NULL)");
SDLTest_AssertCheck(x > INT_MIN, "Validate that value of x is > INT_MIN, got: %i", x);
SDLTest_AssertCheck(_mouseStateCheck(state), "Validate state returned from function, got: %i", state);
/* Case where y pointer is not NULL */
y = INT_MIN;
state = SDL_GetMouseState(NULL, &y);
SDLTest_AssertPass("Call to SDL_GetMouseState(NULL, &y)");
SDLTest_AssertCheck(y > INT_MIN, "Validate that value of y is > INT_MIN, got: %i", y);
SDLTest_AssertCheck(_mouseStateCheck(state), "Validate state returned from function, got: %i", state);
/* Case where x and y pointer is not NULL */
x = INT_MIN;
y = INT_MIN;
state = SDL_GetMouseState(&x, &y);
SDLTest_AssertPass("Call to SDL_GetMouseState(&x, &y)");
SDLTest_AssertCheck(x > INT_MIN, "Validate that value of x is > INT_MIN, got: %i", x);
SDLTest_AssertCheck(y > INT_MIN, "Validate that value of y is > INT_MIN, got: %i", y);
SDLTest_AssertCheck(_mouseStateCheck(state), "Validate state returned from function, got: %i", state);
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetRelativeMouseState
*
*/
int
mouse_getRelativeMouseState(void *arg)
{
int x;
int y;
Uint32 state;
/* Pump some events to update mouse state */
SDL_PumpEvents();
SDLTest_AssertPass("Call to SDL_PumpEvents()");
/* Case where x, y pointer is NULL */
state = SDL_GetRelativeMouseState(NULL, NULL);
SDLTest_AssertPass("Call to SDL_GetRelativeMouseState(NULL, NULL)");
SDLTest_AssertCheck(_mouseStateCheck(state), "Validate state returned from function, got: %i", state);
/* Case where x pointer is not NULL */
x = INT_MIN;
state = SDL_GetRelativeMouseState(&x, NULL);
SDLTest_AssertPass("Call to SDL_GetRelativeMouseState(&x, NULL)");
SDLTest_AssertCheck(x > INT_MIN, "Validate that value of x is > INT_MIN, got: %i", x);
SDLTest_AssertCheck(_mouseStateCheck(state), "Validate state returned from function, got: %i", state);
/* Case where y pointer is not NULL */
y = INT_MIN;
state = SDL_GetRelativeMouseState(NULL, &y);
SDLTest_AssertPass("Call to SDL_GetRelativeMouseState(NULL, &y)");
SDLTest_AssertCheck(y > INT_MIN, "Validate that value of y is > INT_MIN, got: %i", y);
SDLTest_AssertCheck(_mouseStateCheck(state), "Validate state returned from function, got: %i", state);
/* Case where x and y pointer is not NULL */
x = INT_MIN;
y = INT_MIN;
state = SDL_GetRelativeMouseState(&x, &y);
SDLTest_AssertPass("Call to SDL_GetRelativeMouseState(&x, &y)");
SDLTest_AssertCheck(x > INT_MIN, "Validate that value of x is > INT_MIN, got: %i", x);
SDLTest_AssertCheck(y > INT_MIN, "Validate that value of y is > INT_MIN, got: %i", y);
SDLTest_AssertCheck(_mouseStateCheck(state), "Validate state returned from function, got: %i", state);
return TEST_COMPLETED;
}
/* XPM definition of mouse Cursor */
static const char *_mouseArrowData[] = {
/* pixels */
"X ",
"XX ",
"X.X ",
"X..X ",
"X...X ",
"X....X ",
"X.....X ",
"X......X ",
"X.......X ",
"X........X ",
"X.....XXXXX ",
"X..X..X ",
"X.X X..X ",
"XX X..X ",
"X X..X ",
" X..X ",
" X..X ",
" X..X ",
" XX ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" "
};
/* Helper that creates a new mouse cursor from an XPM */
static SDL_Cursor *_initArrowCursor(const char *image[])
{
SDL_Cursor *cursor;
int i, row, col;
Uint8 data[4*32];
Uint8 mask[4*32];
i = -1;
for ( row=0; row<32; ++row ) {
for ( col=0; col<32; ++col ) {
if ( col % 8 ) {
data[i] <<= 1;
mask[i] <<= 1;
} else {
++i;
data[i] = mask[i] = 0;
}
switch (image[row][col]) {
case 'X':
data[i] |= 0x01;
mask[i] |= 0x01;
break;
case '.':
mask[i] |= 0x01;
break;
case ' ':
break;
}
}
}
cursor = SDL_CreateCursor(data, mask, 32, 32, 0, 0);
return cursor;
}
/**
* @brief Check call to SDL_CreateCursor and SDL_FreeCursor
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_CreateCursor
* @sa http://wiki.libsdl.org/moin.cgi/SDL_FreeCursor
*/
int
mouse_createFreeCursor(void *arg)
{
SDL_Cursor *cursor;
/* Create a cursor */
cursor = _initArrowCursor(_mouseArrowData);
SDLTest_AssertPass("Call to SDL_CreateCursor()");
SDLTest_AssertCheck(cursor != NULL, "Validate result from SDL_CreateCursor() is not NULL");
if (cursor == NULL) {
return TEST_ABORTED;
}
/* Free cursor again */
SDL_FreeCursor(cursor);
SDLTest_AssertPass("Call to SDL_FreeCursor()");
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_CreateColorCursor and SDL_FreeCursor
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_CreateColorCursor
* @sa http://wiki.libsdl.org/moin.cgi/SDL_FreeCursor
*/
int
mouse_createFreeColorCursor(void *arg)
{
SDL_Surface *face;
SDL_Cursor *cursor;
/* Get sample surface */
face = SDLTest_ImageFace();
SDLTest_AssertCheck(face != NULL, "Validate sample input image is not NULL");
if (face == NULL) return TEST_ABORTED;
/* Create a color cursor from surface */
cursor = SDL_CreateColorCursor(face, 0, 0);
SDLTest_AssertPass("Call to SDL_CreateColorCursor()");
SDLTest_AssertCheck(cursor != NULL, "Validate result from SDL_CreateColorCursor() is not NULL");
if (cursor == NULL) {
SDL_FreeSurface(face);
return TEST_ABORTED;
}
/* Free cursor again */
SDL_FreeCursor(cursor);
SDLTest_AssertPass("Call to SDL_FreeCursor()");
/* Clean up */
SDL_FreeSurface(face);
return TEST_COMPLETED;
}
/* Helper that changes cursor visibility */
void _changeCursorVisibility(int state)
{
int oldState;
int newState;
int result;
oldState = SDL_ShowCursor(SDL_QUERY);
SDLTest_AssertPass("Call to SDL_ShowCursor(SDL_QUERY)");
result = SDL_ShowCursor(state);
SDLTest_AssertPass("Call to SDL_ShowCursor(%s)", (state == SDL_ENABLE) ? "SDL_ENABLE" : "SDL_DISABLE");
SDLTest_AssertCheck(result == oldState, "Validate result from SDL_ShowCursor(%s), expected: %i, got: %i",
(state == SDL_ENABLE) ? "SDL_ENABLE" : "SDL_DISABLE", oldState, result);
newState = SDL_ShowCursor(SDL_QUERY);
SDLTest_AssertPass("Call to SDL_ShowCursor(SDL_QUERY)");
SDLTest_AssertCheck(state == newState, "Validate new state, expected: %i, got: %i",
state, newState);
}
/**
* @brief Check call to SDL_ShowCursor
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_ShowCursor
*/
int
mouse_showCursor(void *arg)
{
int currentState;
/* Get current state */
currentState = SDL_ShowCursor(SDL_QUERY);
SDLTest_AssertPass("Call to SDL_ShowCursor(SDL_QUERY)");
SDLTest_AssertCheck(currentState == SDL_DISABLE || currentState == SDL_ENABLE,
"Validate result is %i or %i, got: %i", SDL_DISABLE, SDL_ENABLE, currentState);
if (currentState == SDL_DISABLE) {
/* Show the cursor, then hide it again */
_changeCursorVisibility(SDL_ENABLE);
_changeCursorVisibility(SDL_DISABLE);
} else if (currentState == SDL_ENABLE) {
/* Hide the cursor, then show it again */
_changeCursorVisibility(SDL_DISABLE);
_changeCursorVisibility(SDL_ENABLE);
} else {
return TEST_ABORTED;
}
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_SetCursor
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_SetCursor
*/
int
mouse_setCursor(void *arg)
{
SDL_Cursor *cursor;
/* Create a cursor */
cursor = _initArrowCursor(_mouseArrowData);
SDLTest_AssertPass("Call to SDL_CreateCursor()");
SDLTest_AssertCheck(cursor != NULL, "Validate result from SDL_CreateCursor() is not NULL");
if (cursor == NULL) {
return TEST_ABORTED;
}
/* Set the arrow cursor */
SDL_SetCursor(cursor);
SDLTest_AssertPass("Call to SDL_SetCursor(cursor)");
/* Force redraw */
SDL_SetCursor(NULL);
SDLTest_AssertPass("Call to SDL_SetCursor(NULL)");
/* Free cursor again */
SDL_FreeCursor(cursor);
SDLTest_AssertPass("Call to SDL_FreeCursor()");
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetCursor
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_GetCursor
*/
int
mouse_getCursor(void *arg)
{
SDL_Cursor *cursor;
/* Get current cursor */
cursor = SDL_GetCursor();
SDLTest_AssertPass("Call to SDL_GetCursor()");
SDLTest_AssertCheck(cursor != NULL, "Validate result from SDL_GetCursor() is not NULL");
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetRelativeMouseMode and SDL_SetRelativeMouseMode
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_GetRelativeMouseMode
* @sa http://wiki.libsdl.org/moin.cgi/SDL_SetRelativeMouseMode
*/
int
mouse_getSetRelativeMouseMode(void *arg)
{
int result;
int i;
SDL_bool initialState;
SDL_bool currentState;
/* Capture original state so we can revert back to it later */
initialState = SDL_GetRelativeMouseMode();
SDLTest_AssertPass("Call to SDL_GetRelativeMouseMode()");
/* Repeat twice to check D->D transition */
for (i=0; i<2; i++) {
/* Disable - should always be supported */
result = SDL_SetRelativeMouseMode(SDL_FALSE);
SDLTest_AssertPass("Call to SDL_SetRelativeMouseMode(FALSE)");
SDLTest_AssertCheck(result == 0, "Validate result value from SDL_SetRelativeMouseMode, expected: 0, got: %i", result);
currentState = SDL_GetRelativeMouseMode();
SDLTest_AssertPass("Call to SDL_GetRelativeMouseMode()");
SDLTest_AssertCheck(currentState == SDL_FALSE, "Validate current state is FALSE, got: %i", currentState);
}
/* Repeat twice to check D->E->E transition */
for (i=0; i<2; i++) {
/* Enable - may not be supported */
result = SDL_SetRelativeMouseMode(SDL_TRUE);
SDLTest_AssertPass("Call to SDL_SetRelativeMouseMode(TRUE)");
if (result != -1) {
SDLTest_AssertCheck(result == 0, "Validate result value from SDL_SetRelativeMouseMode, expected: 0, got: %i", result);
currentState = SDL_GetRelativeMouseMode();
SDLTest_AssertPass("Call to SDL_GetRelativeMouseMode()");
SDLTest_AssertCheck(currentState == SDL_TRUE, "Validate current state is TRUE, got: %i", currentState);
}
}
/* Disable to check E->D transition */
result = SDL_SetRelativeMouseMode(SDL_FALSE);
SDLTest_AssertPass("Call to SDL_SetRelativeMouseMode(FALSE)");
SDLTest_AssertCheck(result == 0, "Validate result value from SDL_SetRelativeMouseMode, expected: 0, got: %i", result);
currentState = SDL_GetRelativeMouseMode();
SDLTest_AssertPass("Call to SDL_GetRelativeMouseMode()");
SDLTest_AssertCheck(currentState == SDL_FALSE, "Validate current state is FALSE, got: %i", currentState);
/* Revert to original state - ignore result */
result = SDL_SetRelativeMouseMode(initialState);
return TEST_COMPLETED;
}
#define MOUSE_TESTWINDOW_WIDTH 320
#define MOUSE_TESTWINDOW_HEIGHT 200
/**
* Creates a test window
*/
SDL_Window *_createMouseSuiteTestWindow()
{
int posX = 100, posY = 100, width = MOUSE_TESTWINDOW_WIDTH, height = MOUSE_TESTWINDOW_HEIGHT;
SDL_Window *window;
window = SDL_CreateWindow("mouse_createMouseSuiteTestWindow", posX, posY, width, height, 0);
SDLTest_AssertPass("SDL_CreateWindow()");
SDLTest_AssertCheck(window != NULL, "Check SDL_CreateWindow result");
return window;
}
/*
* Destroy test window
*/
void _destroyMouseSuiteTestWindow(SDL_Window *window)
{
if (window != NULL) {
SDL_DestroyWindow(window);
window = NULL;
SDLTest_AssertPass("SDL_DestroyWindow()");
}
}
/**
* @brief Check call to SDL_WarpMouseInWindow
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_WarpMouseInWindow
*/
int
mouse_warpMouseInWindow(void *arg)
{
const int w = MOUSE_TESTWINDOW_WIDTH, h = MOUSE_TESTWINDOW_HEIGHT;
int numPositions = 6;
int xPositions[6];
int yPositions[6];
int x, y, i, j;
SDL_Window *window;
xPositions[0] = -1;
xPositions[1] = 0;
xPositions[2] = 1;
xPositions[3] = w-1;
xPositions[4] = w;
xPositions[5] = w+1;
yPositions[0] = -1;
yPositions[1] = 0;
yPositions[2] = 1;
yPositions[3] = h-1;
yPositions[4] = h;
yPositions[5] = h+1;
/* Create test window */
window = _createMouseSuiteTestWindow();
if (window == NULL) return TEST_ABORTED;
/* Mouse to random position inside window */
x = SDLTest_RandomIntegerInRange(1, w-1);
y = SDLTest_RandomIntegerInRange(1, h-1);
SDL_WarpMouseInWindow(window, x, y);
SDLTest_AssertPass("SDL_WarpMouseInWindow(...,%i,%i)", x, y);
/* Same position again */
SDL_WarpMouseInWindow(window, x, y);
SDLTest_AssertPass("SDL_WarpMouseInWindow(...,%i,%i)", x, y);
/* Mouse to various boundary positions */
for (i=0; i<numPositions; i++) {
for (j=0; j<numPositions; j++) {
x = xPositions[i];
y = yPositions[j];
SDL_WarpMouseInWindow(window, x, y);
SDLTest_AssertPass("SDL_WarpMouseInWindow(...,%i,%i)", x, y);
/* TODO: add tracking of events and check that each call generates a mouse motion event */
SDL_PumpEvents();
SDLTest_AssertPass("SDL_PumpEvents()");
}
}
/* Clean up test window */
_destroyMouseSuiteTestWindow(window);
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetMouseFocus
*
* @sa http://wiki.libsdl.org/moin.cgi/SDL_GetMouseFocus
*/
int
mouse_getMouseFocus(void *arg)
{
const int w = MOUSE_TESTWINDOW_WIDTH, h = MOUSE_TESTWINDOW_HEIGHT;
int x, y;
SDL_Window *window;
SDL_Window *focusWindow;
/* Get focus - focus non-deterministic */
focusWindow = SDL_GetMouseFocus();
SDLTest_AssertPass("SDL_GetMouseFocus()");
/* Create test window */
window = _createMouseSuiteTestWindow();
if (window == NULL) return TEST_ABORTED;
/* Mouse to random position inside window */
x = SDLTest_RandomIntegerInRange(1, w-1);
y = SDLTest_RandomIntegerInRange(1, h-1);
SDL_WarpMouseInWindow(window, x, y);
SDLTest_AssertPass("SDL_WarpMouseInWindow(...,%i,%i)", x, y);
/* Pump events to update focus state */
SDL_PumpEvents();
SDLTest_AssertPass("SDL_PumpEvents()");
/* Get focus with explicit window setup - focus deterministic */
focusWindow = SDL_GetMouseFocus();
SDLTest_AssertPass("SDL_GetMouseFocus()");
SDLTest_AssertCheck (focusWindow != NULL, "Check returned window value is not NULL");
SDLTest_AssertCheck (focusWindow == window, "Check returned window value is test window");
/* Mouse to random position outside window */
x = SDLTest_RandomIntegerInRange(-9, -1);
y = SDLTest_RandomIntegerInRange(-9, -1);
SDL_WarpMouseInWindow(window, x, y);
SDLTest_AssertPass("SDL_WarpMouseInWindow(...,%i,%i)", x, y);
/* Clean up test window */
_destroyMouseSuiteTestWindow(window);
/* Pump events to update focus state */
SDL_PumpEvents();
SDLTest_AssertPass("SDL_PumpEvents()");
/* Get focus for non-existing window */
focusWindow = SDL_GetMouseFocus();
SDLTest_AssertPass("SDL_GetMouseFocus()");
SDLTest_AssertCheck (focusWindow == NULL, "Check returned window value is NULL");
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Mouse test cases */
static const SDLTest_TestCaseReference mouseTest1 =
{ (SDLTest_TestCaseFp)mouse_getMouseState, "mouse_getMouseState", "Check call to SDL_GetMouseState", TEST_ENABLED };
static const SDLTest_TestCaseReference mouseTest2 =
{ (SDLTest_TestCaseFp)mouse_getRelativeMouseState, "mouse_getRelativeMouseState", "Check call to SDL_GetRelativeMouseState", TEST_ENABLED };
static const SDLTest_TestCaseReference mouseTest3 =
{ (SDLTest_TestCaseFp)mouse_createFreeCursor, "mouse_createFreeCursor", "Check call to SDL_CreateCursor and SDL_FreeCursor", TEST_ENABLED };
static const SDLTest_TestCaseReference mouseTest4 =
{ (SDLTest_TestCaseFp)mouse_showCursor, "mouse_showCursor", "Check call to SDL_ShowCursor", TEST_ENABLED };
static const SDLTest_TestCaseReference mouseTest5 =
{ (SDLTest_TestCaseFp)mouse_setCursor, "mouse_setCursor", "Check call to SDL_SetCursor", TEST_ENABLED };
static const SDLTest_TestCaseReference mouseTest6 =
{ (SDLTest_TestCaseFp)mouse_getCursor, "mouse_getCursor", "Check call to SDL_GetCursor", TEST_ENABLED };
static const SDLTest_TestCaseReference mouseTest7 =
{ (SDLTest_TestCaseFp)mouse_warpMouseInWindow, "mouse_warpMouseInWindow", "Check call to SDL_WarpMouseInWindow", TEST_ENABLED };
static const SDLTest_TestCaseReference mouseTest8 =
{ (SDLTest_TestCaseFp)mouse_getMouseFocus, "mouse_getMouseFocus", "Check call to SDL_getMouseFocus", TEST_ENABLED };
static const SDLTest_TestCaseReference mouseTest9 =
{ (SDLTest_TestCaseFp)mouse_createFreeColorCursor, "mouse_createFreeColorCursor", "Check call to SDL_CreateColorCursor and SDL_FreeCursor", TEST_ENABLED };
static const SDLTest_TestCaseReference mouseTest10 =
{ (SDLTest_TestCaseFp)mouse_getSetRelativeMouseMode, "mouse_getSetRelativeMouseMode", "Check call to SDL_GetRelativeMouseMode and SDL_SetRelativeMouseMode", TEST_ENABLED };
/* Sequence of Mouse test cases */
static const SDLTest_TestCaseReference *mouseTests[] = {
&mouseTest1, &mouseTest2, &mouseTest3, &mouseTest4, &mouseTest5, &mouseTest6,
&mouseTest7, &mouseTest8, &mouseTest9, &mouseTest10, NULL
};
/* Mouse test suite (global) */
SDLTest_TestSuiteReference mouseTestSuite = {
"Mouse",
NULL,
mouseTests,
NULL
};
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_mouse.c | C | apache-2.0 | 19,996 |
/**
* Pixels test suite
*/
#include <stdio.h>
#include "SDL.h"
#include "SDL_test.h"
/* Test case functions */
/* Definition of all RGB formats used to test pixel conversions */
const int _numRGBPixelFormats = 31;
Uint32 _RGBPixelFormats[] =
{
SDL_PIXELFORMAT_INDEX1LSB,
SDL_PIXELFORMAT_INDEX1MSB,
SDL_PIXELFORMAT_INDEX4LSB,
SDL_PIXELFORMAT_INDEX4MSB,
SDL_PIXELFORMAT_INDEX8,
SDL_PIXELFORMAT_RGB332,
SDL_PIXELFORMAT_RGB444,
SDL_PIXELFORMAT_BGR444,
SDL_PIXELFORMAT_RGB555,
SDL_PIXELFORMAT_BGR555,
SDL_PIXELFORMAT_ARGB4444,
SDL_PIXELFORMAT_RGBA4444,
SDL_PIXELFORMAT_ABGR4444,
SDL_PIXELFORMAT_BGRA4444,
SDL_PIXELFORMAT_ARGB1555,
SDL_PIXELFORMAT_RGBA5551,
SDL_PIXELFORMAT_ABGR1555,
SDL_PIXELFORMAT_BGRA5551,
SDL_PIXELFORMAT_RGB565,
SDL_PIXELFORMAT_BGR565,
SDL_PIXELFORMAT_RGB24,
SDL_PIXELFORMAT_BGR24,
SDL_PIXELFORMAT_RGB888,
SDL_PIXELFORMAT_RGBX8888,
SDL_PIXELFORMAT_BGR888,
SDL_PIXELFORMAT_BGRX8888,
SDL_PIXELFORMAT_ARGB8888,
SDL_PIXELFORMAT_RGBA8888,
SDL_PIXELFORMAT_ABGR8888,
SDL_PIXELFORMAT_BGRA8888,
SDL_PIXELFORMAT_ARGB2101010
};
char* _RGBPixelFormatsVerbose[] =
{
"SDL_PIXELFORMAT_INDEX1LSB",
"SDL_PIXELFORMAT_INDEX1MSB",
"SDL_PIXELFORMAT_INDEX4LSB",
"SDL_PIXELFORMAT_INDEX4MSB",
"SDL_PIXELFORMAT_INDEX8",
"SDL_PIXELFORMAT_RGB332",
"SDL_PIXELFORMAT_RGB444",
"SDL_PIXELFORMAT_BGR444",
"SDL_PIXELFORMAT_RGB555",
"SDL_PIXELFORMAT_BGR555",
"SDL_PIXELFORMAT_ARGB4444",
"SDL_PIXELFORMAT_RGBA4444",
"SDL_PIXELFORMAT_ABGR4444",
"SDL_PIXELFORMAT_BGRA4444",
"SDL_PIXELFORMAT_ARGB1555",
"SDL_PIXELFORMAT_RGBA5551",
"SDL_PIXELFORMAT_ABGR1555",
"SDL_PIXELFORMAT_BGRA5551",
"SDL_PIXELFORMAT_RGB565",
"SDL_PIXELFORMAT_BGR565",
"SDL_PIXELFORMAT_RGB24",
"SDL_PIXELFORMAT_BGR24",
"SDL_PIXELFORMAT_RGB888",
"SDL_PIXELFORMAT_RGBX8888",
"SDL_PIXELFORMAT_BGR888",
"SDL_PIXELFORMAT_BGRX8888",
"SDL_PIXELFORMAT_ARGB8888",
"SDL_PIXELFORMAT_RGBA8888",
"SDL_PIXELFORMAT_ABGR8888",
"SDL_PIXELFORMAT_BGRA8888",
"SDL_PIXELFORMAT_ARGB2101010"
};
/* Definition of all Non-RGB formats used to test pixel conversions */
const int _numNonRGBPixelFormats = 7;
Uint32 _nonRGBPixelFormats[] =
{
SDL_PIXELFORMAT_YV12,
SDL_PIXELFORMAT_IYUV,
SDL_PIXELFORMAT_YUY2,
SDL_PIXELFORMAT_UYVY,
SDL_PIXELFORMAT_YVYU,
SDL_PIXELFORMAT_NV12,
SDL_PIXELFORMAT_NV21
};
char* _nonRGBPixelFormatsVerbose[] =
{
"SDL_PIXELFORMAT_YV12",
"SDL_PIXELFORMAT_IYUV",
"SDL_PIXELFORMAT_YUY2",
"SDL_PIXELFORMAT_UYVY",
"SDL_PIXELFORMAT_YVYU",
"SDL_PIXELFORMAT_NV12",
"SDL_PIXELFORMAT_NV21"
};
/* Definition of some invalid formats for negative tests */
const int _numInvalidPixelFormats = 2;
Uint32 _invalidPixelFormats[] =
{
0xfffffffe,
0xffffffff
};
char* _invalidPixelFormatsVerbose[] =
{
"SDL_PIXELFORMAT_UNKNOWN",
"SDL_PIXELFORMAT_UNKNOWN"
};
/* Test case functions */
/**
* @brief Call to SDL_AllocFormat and SDL_FreeFormat
*
* @sa http://wiki.libsdl.org/moin.fcg/SDL_AllocFormat
* @sa http://wiki.libsdl.org/moin.fcg/SDL_FreeFormat
*/
int
pixels_allocFreeFormat(void *arg)
{
const char *unknownFormat = "SDL_PIXELFORMAT_UNKNOWN";
const char *expectedError = "Parameter 'format' is invalid";
const char *error;
int i;
Uint32 format;
Uint32 masks;
SDL_PixelFormat* result;
/* Blank/unknown format */
format = 0;
SDLTest_Log("RGB Format: %s (%u)", unknownFormat, format);
/* Allocate format */
result = SDL_AllocFormat(format);
SDLTest_AssertPass("Call to SDL_AllocFormat()");
SDLTest_AssertCheck(result != NULL, "Verify result is not NULL");
if (result != NULL) {
SDLTest_AssertCheck(result->format == format, "Verify value of result.format; expected: %u, got %u", format, result->format);
SDLTest_AssertCheck(result->BitsPerPixel == 0, "Verify value of result.BitsPerPixel; expected: 0, got %u", result->BitsPerPixel);
SDLTest_AssertCheck(result->BytesPerPixel == 0, "Verify value of result.BytesPerPixel; expected: 0, got %u", result->BytesPerPixel);
masks = result->Rmask | result->Gmask | result->Bmask | result->Amask;
SDLTest_AssertCheck(masks == 0, "Verify value of result.[RGBA]mask combined; expected: 0, got %u", masks);
/* Deallocate again */
SDL_FreeFormat(result);
SDLTest_AssertPass("Call to SDL_FreeFormat()");
}
/* RGB formats */
for (i = 0; i < _numRGBPixelFormats; i++) {
format = _RGBPixelFormats[i];
SDLTest_Log("RGB Format: %s (%u)", _RGBPixelFormatsVerbose[i], format);
/* Allocate format */
result = SDL_AllocFormat(format);
SDLTest_AssertPass("Call to SDL_AllocFormat()");
SDLTest_AssertCheck(result != NULL, "Verify result is not NULL");
if (result != NULL) {
SDLTest_AssertCheck(result->format == format, "Verify value of result.format; expected: %u, got %u", format, result->format);
SDLTest_AssertCheck(result->BitsPerPixel > 0, "Verify value of result.BitsPerPixel; expected: >0, got %u", result->BitsPerPixel);
SDLTest_AssertCheck(result->BytesPerPixel > 0, "Verify value of result.BytesPerPixel; expected: >0, got %u", result->BytesPerPixel);
if (result->palette != NULL) {
masks = result->Rmask | result->Gmask | result->Bmask | result->Amask;
SDLTest_AssertCheck(masks > 0, "Verify value of result.[RGBA]mask combined; expected: >0, got %u", masks);
}
/* Deallocate again */
SDL_FreeFormat(result);
SDLTest_AssertPass("Call to SDL_FreeFormat()");
}
}
/* Non-RGB formats */
for (i = 0; i < _numNonRGBPixelFormats; i++) {
format = _nonRGBPixelFormats[i];
SDLTest_Log("non-RGB Format: %s (%u)", _nonRGBPixelFormatsVerbose[i], format);
/* Try to allocate format */
result = SDL_AllocFormat(format);
SDLTest_AssertPass("Call to SDL_AllocFormat()");
SDLTest_AssertCheck(result == NULL, "Verify result is NULL");
}
/* Negative cases */
/* Invalid Formats */
for (i = 0; i < _numInvalidPixelFormats; i++) {
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
format = _invalidPixelFormats[i];
result = SDL_AllocFormat(format);
SDLTest_AssertPass("Call to SDL_AllocFormat(%u)", format);
SDLTest_AssertCheck(result == NULL, "Verify result is NULL");
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
if (error != NULL) {
SDLTest_AssertCheck(SDL_strcmp(error, expectedError) == 0,
"Validate error message, expected: '%s', got: '%s'", expectedError, error);
}
}
/* Invalid free pointer */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
SDL_FreeFormat(NULL);
SDLTest_AssertPass("Call to SDL_FreeFormat(NULL)");
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
if (error != NULL) {
SDLTest_AssertCheck(SDL_strcmp(error, expectedError) == 0,
"Validate error message, expected: '%s', got: '%s'", expectedError, error);
}
return TEST_COMPLETED;
}
/**
* @brief Call to SDL_GetPixelFormatName
*
* @sa http://wiki.libsdl.org/moin.fcg/SDL_GetPixelFormatName
*/
int
pixels_getPixelFormatName(void *arg)
{
const char *unknownFormat = "SDL_PIXELFORMAT_UNKNOWN";
const char *error;
int i;
Uint32 format;
char* result;
/* Blank/undefined format */
format = 0;
SDLTest_Log("RGB Format: %s (%u)", unknownFormat, format);
/* Get name of format */
result = (char *)SDL_GetPixelFormatName(format);
SDLTest_AssertPass("Call to SDL_GetPixelFormatName()");
SDLTest_AssertCheck(result != NULL, "Verify result is not NULL");
if (result != NULL) {
SDLTest_AssertCheck(result[0] != '\0', "Verify result is non-empty");
SDLTest_AssertCheck(SDL_strcmp(result, unknownFormat) == 0,
"Verify result text; expected: %s, got %s", unknownFormat, result);
}
/* RGB formats */
for (i = 0; i < _numRGBPixelFormats; i++) {
format = _RGBPixelFormats[i];
SDLTest_Log("RGB Format: %s (%u)", _RGBPixelFormatsVerbose[i], format);
/* Get name of format */
result = (char *)SDL_GetPixelFormatName(format);
SDLTest_AssertPass("Call to SDL_GetPixelFormatName()");
SDLTest_AssertCheck(result != NULL, "Verify result is not NULL");
if (result != NULL) {
SDLTest_AssertCheck(result[0] != '\0', "Verify result is non-empty");
SDLTest_AssertCheck(SDL_strcmp(result, _RGBPixelFormatsVerbose[i]) == 0,
"Verify result text; expected: %s, got %s", _RGBPixelFormatsVerbose[i], result);
}
}
/* Non-RGB formats */
for (i = 0; i < _numNonRGBPixelFormats; i++) {
format = _nonRGBPixelFormats[i];
SDLTest_Log("non-RGB Format: %s (%u)", _nonRGBPixelFormatsVerbose[i], format);
/* Get name of format */
result = (char *)SDL_GetPixelFormatName(format);
SDLTest_AssertPass("Call to SDL_GetPixelFormatName()");
SDLTest_AssertCheck(result != NULL, "Verify result is not NULL");
if (result != NULL) {
SDLTest_AssertCheck(result[0] != '\0', "Verify result is non-empty");
SDLTest_AssertCheck(SDL_strcmp(result, _nonRGBPixelFormatsVerbose[i]) == 0,
"Verify result text; expected: %s, got %s", _nonRGBPixelFormatsVerbose[i], result);
}
}
/* Negative cases */
/* Invalid Formats */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
for (i = 0; i < _numInvalidPixelFormats; i++) {
format = _invalidPixelFormats[i];
result = (char *)SDL_GetPixelFormatName(format);
SDLTest_AssertPass("Call to SDL_GetPixelFormatName(%u)", format);
SDLTest_AssertCheck(result != NULL, "Verify result is not NULL");
if (result != NULL) {
SDLTest_AssertCheck(result[0] != '\0',
"Verify result is non-empty; got: %s", result);
SDLTest_AssertCheck(SDL_strcmp(result, _invalidPixelFormatsVerbose[i]) == 0,
"Validate name is UNKNOWN, expected: '%s', got: '%s'", _invalidPixelFormatsVerbose[i], result);
}
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error == NULL || error[0] == '\0', "Validate that error message is empty");
}
return TEST_COMPLETED;
}
/**
* @brief Call to SDL_AllocPalette and SDL_FreePalette
*
* @sa http://wiki.libsdl.org/moin.fcg/SDL_AllocPalette
* @sa http://wiki.libsdl.org/moin.fcg/SDL_FreePalette
*/
int
pixels_allocFreePalette(void *arg)
{
const char *expectedError1 = "Parameter 'ncolors' is invalid";
const char *expectedError2 = "Parameter 'palette' is invalid";
const char *error;
int variation;
int i;
int ncolors;
SDL_Palette* result;
/* Allocate palette */
for (variation = 1; variation <= 3; variation++) {
switch (variation) {
/* Just one color */
case 1:
ncolors = 1;
break;
/* Two colors */
case 2:
ncolors = 2;
break;
/* More than two colors */
case 3:
ncolors = SDLTest_RandomIntegerInRange(8, 16);
break;
}
result = SDL_AllocPalette(ncolors);
SDLTest_AssertPass("Call to SDL_AllocPalette(%d)", ncolors);
SDLTest_AssertCheck(result != NULL, "Verify result is not NULL");
if (result != NULL) {
SDLTest_AssertCheck(result->ncolors == ncolors, "Verify value of result.ncolors; expected: %u, got %u", ncolors, result->ncolors);
if (result->ncolors > 0) {
SDLTest_AssertCheck(result->colors != NULL, "Verify value of result.colors is not NULL");
if (result->colors != NULL) {
for(i = 0; i < result->ncolors; i++) {
SDLTest_AssertCheck(result->colors[i].r == 255, "Verify value of result.colors[%d].r; expected: 255, got %u", i, result->colors[i].r);
SDLTest_AssertCheck(result->colors[i].g == 255, "Verify value of result.colors[%d].g; expected: 255, got %u", i, result->colors[i].g);
SDLTest_AssertCheck(result->colors[i].b == 255, "Verify value of result.colors[%d].b; expected: 255, got %u", i, result->colors[i].b);
}
}
}
/* Deallocate again */
SDL_FreePalette(result);
SDLTest_AssertPass("Call to SDL_FreePalette()");
}
}
/* Negative cases */
/* Invalid number of colors */
for (ncolors = 0; ncolors > -3; ncolors--) {
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
result = SDL_AllocPalette(ncolors);
SDLTest_AssertPass("Call to SDL_AllocPalette(%d)", ncolors);
SDLTest_AssertCheck(result == NULL, "Verify result is NULL");
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
if (error != NULL) {
SDLTest_AssertCheck(SDL_strcmp(error, expectedError1) == 0,
"Validate error message, expected: '%s', got: '%s'", expectedError1, error);
}
}
/* Invalid free pointer */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
SDL_FreePalette(NULL);
SDLTest_AssertPass("Call to SDL_FreePalette(NULL)");
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
if (error != NULL) {
SDLTest_AssertCheck(SDL_strcmp(error, expectedError2) == 0,
"Validate error message, expected: '%s', got: '%s'", expectedError2, error);
}
return TEST_COMPLETED;
}
/**
* @brief Call to SDL_CalculateGammaRamp
*
* @sa http://wiki.libsdl.org/moin.fcg/SDL_CalculateGammaRamp
*/
int
pixels_calcGammaRamp(void *arg)
{
const char *expectedError1 = "Parameter 'gamma' is invalid";
const char *expectedError2 = "Parameter 'ramp' is invalid";
const char *error;
float gamma;
Uint16 *ramp;
int variation;
int i;
int changed;
Uint16 magic = 0xbeef;
/* Allocate temp ramp array and fill with some value */
ramp = (Uint16 *)SDL_malloc(256 * sizeof(Uint16));
SDLTest_AssertCheck(ramp != NULL, "Validate temp ramp array could be allocated");
if (ramp == NULL) return TEST_ABORTED;
/* Make call with different gamma values */
for (variation = 0; variation < 4; variation++) {
switch (variation) {
/* gamma = 0 all black */
case 0:
gamma = 0.0f;
break;
/* gamma = 1 identity */
case 1:
gamma = 1.0f;
break;
/* gamma = [0.2,0.8] normal range */
case 2:
gamma = 0.2f + 0.8f * SDLTest_RandomUnitFloat();
break;
/* gamma = >1.1 non-standard range */
case 3:
gamma = 1.1f + SDLTest_RandomUnitFloat();
break;
}
/* Make call and check that values were updated */
for (i = 0; i < 256; i++) ramp[i] = magic;
SDL_CalculateGammaRamp(gamma, ramp);
SDLTest_AssertPass("Call to SDL_CalculateGammaRamp(%f)", gamma);
changed = 0;
for (i = 0; i < 256; i++) if (ramp[i] != magic) changed++;
SDLTest_AssertCheck(changed > 250, "Validate that ramp was calculated; expected: >250 values changed, got: %d values changed", changed);
/* Additional value checks for some cases */
i = SDLTest_RandomIntegerInRange(64,192);
switch (variation) {
case 0:
SDLTest_AssertCheck(ramp[i] == 0, "Validate value at position %d; expected: 0, got: %d", i, ramp[i]);
break;
case 1:
SDLTest_AssertCheck(ramp[i] == ((i << 8) | i), "Validate value at position %d; expected: %d, got: %d", i, (i << 8) | i, ramp[i]);
break;
case 2:
case 3:
SDLTest_AssertCheck(ramp[i] > 0, "Validate value at position %d; expected: >0, got: %d", i, ramp[i]);
break;
}
}
/* Negative cases */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
gamma = -1;
for (i=0; i<256; i++) ramp[i] = magic;
SDL_CalculateGammaRamp(gamma, ramp);
SDLTest_AssertPass("Call to SDL_CalculateGammaRamp(%f)", gamma);
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
if (error != NULL) {
SDLTest_AssertCheck(SDL_strcmp(error, expectedError1) == 0,
"Validate error message, expected: '%s', got: '%s'", expectedError1, error);
}
changed = 0;
for (i = 0; i < 256; i++) if (ramp[i] != magic) changed++;
SDLTest_AssertCheck(changed ==0, "Validate that ramp unchanged; expected: 0 values changed got: %d values changed", changed);
SDL_CalculateGammaRamp(0.5f, NULL);
SDLTest_AssertPass("Call to SDL_CalculateGammaRamp(0.5,NULL)");
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
if (error != NULL) {
SDLTest_AssertCheck(SDL_strcmp(error, expectedError2) == 0,
"Validate error message, expected: '%s', got: '%s'", expectedError2, error);
}
/* Cleanup */
SDL_free(ramp);
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Pixels test cases */
static const SDLTest_TestCaseReference pixelsTest1 =
{ (SDLTest_TestCaseFp)pixels_allocFreeFormat, "pixels_allocFreeFormat", "Call to SDL_AllocFormat and SDL_FreeFormat", TEST_ENABLED };
static const SDLTest_TestCaseReference pixelsTest2 =
{ (SDLTest_TestCaseFp)pixels_allocFreePalette, "pixels_allocFreePalette", "Call to SDL_AllocPalette and SDL_FreePalette", TEST_ENABLED };
static const SDLTest_TestCaseReference pixelsTest3 =
{ (SDLTest_TestCaseFp)pixels_calcGammaRamp, "pixels_calcGammaRamp", "Call to SDL_CalculateGammaRamp", TEST_ENABLED };
static const SDLTest_TestCaseReference pixelsTest4 =
{ (SDLTest_TestCaseFp)pixels_getPixelFormatName, "pixels_getPixelFormatName", "Call to SDL_GetPixelFormatName", TEST_ENABLED };
/* Sequence of Pixels test cases */
static const SDLTest_TestCaseReference *pixelsTests[] = {
&pixelsTest1, &pixelsTest2, &pixelsTest3, &pixelsTest4, NULL
};
/* Pixels test suite (global) */
SDLTest_TestSuiteReference pixelsTestSuite = {
"Pixels",
NULL,
pixelsTests,
NULL
};
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_pixels.c | C | apache-2.0 | 18,303 |
/**
* Original code: automated SDL platform test written by Edgar Simo "bobbens"
* Extended and updated by aschiffler at ferzkopp dot net
*/
#include <stdio.h>
#include "SDL.h"
#include "SDL_test.h"
/* ================= Test Case Implementation ================== */
/* Helper functions */
/**
* @brief Compare sizes of types.
*
* @note Watcom C flags these as Warning 201: "Unreachable code" if you just
* compare them directly, so we push it through a function to keep the
* compiler quiet. --ryan.
*/
static int _compareSizeOfType( size_t sizeoftype, size_t hardcodetype )
{
return sizeoftype != hardcodetype;
}
/* Test case functions */
/**
* @brief Tests type sizes.
*/
int platform_testTypes(void *arg)
{
int ret;
ret = _compareSizeOfType( sizeof(Uint8), 1 );
SDLTest_AssertCheck( ret == 0, "sizeof(Uint8) = %lu, expected 1", (unsigned long)sizeof(Uint8) );
ret = _compareSizeOfType( sizeof(Uint16), 2 );
SDLTest_AssertCheck( ret == 0, "sizeof(Uint16) = %lu, expected 2", (unsigned long)sizeof(Uint16) );
ret = _compareSizeOfType( sizeof(Uint32), 4 );
SDLTest_AssertCheck( ret == 0, "sizeof(Uint32) = %lu, expected 4", (unsigned long)sizeof(Uint32) );
ret = _compareSizeOfType( sizeof(Uint64), 8 );
SDLTest_AssertCheck( ret == 0, "sizeof(Uint64) = %lu, expected 8", (unsigned long)sizeof(Uint64) );
return TEST_COMPLETED;
}
/**
* @brief Tests platform endianness and SDL_SwapXY functions.
*/
int platform_testEndianessAndSwap(void *arg)
{
int real_byteorder;
Uint16 value = 0x1234;
Uint16 value16 = 0xCDAB;
Uint16 swapped16 = 0xABCD;
Uint32 value32 = 0xEFBEADDE;
Uint32 swapped32 = 0xDEADBEEF;
Uint64 value64, swapped64;
value64 = 0xEFBEADDE;
value64 <<= 32;
value64 |= 0xCDAB3412;
swapped64 = 0x1234ABCD;
swapped64 <<= 32;
swapped64 |= 0xDEADBEEF;
if ((*((char *) &value) >> 4) == 0x1) {
real_byteorder = SDL_BIG_ENDIAN;
} else {
real_byteorder = SDL_LIL_ENDIAN;
}
/* Test endianness. */
SDLTest_AssertCheck( real_byteorder == SDL_BYTEORDER,
"Machine detected as %s endian, appears to be %s endian.",
(SDL_BYTEORDER == SDL_LIL_ENDIAN) ? "little" : "big",
(real_byteorder == SDL_LIL_ENDIAN) ? "little" : "big" );
/* Test 16 swap. */
SDLTest_AssertCheck( SDL_Swap16(value16) == swapped16,
"SDL_Swap16(): 16 bit swapped: 0x%X => 0x%X",
value16, SDL_Swap16(value16) );
/* Test 32 swap. */
SDLTest_AssertCheck( SDL_Swap32(value32) == swapped32,
"SDL_Swap32(): 32 bit swapped: 0x%X => 0x%X",
value32, SDL_Swap32(value32) );
/* Test 64 swap. */
SDLTest_AssertCheck( SDL_Swap64(value64) == swapped64,
"SDL_Swap64(): 64 bit swapped: 0x%"SDL_PRIX64" => 0x%"SDL_PRIX64,
value64, SDL_Swap64(value64) );
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_GetXYZ() functions
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_GetPlatform
* http://wiki.libsdl.org/moin.cgi/SDL_GetCPUCount
* http://wiki.libsdl.org/moin.cgi/SDL_GetCPUCacheLineSize
* http://wiki.libsdl.org/moin.cgi/SDL_GetRevision
* http://wiki.libsdl.org/moin.cgi/SDL_GetRevisionNumber
*/
int platform_testGetFunctions (void *arg)
{
char *platform;
char *revision;
int ret;
size_t len;
platform = (char *)SDL_GetPlatform();
SDLTest_AssertPass("SDL_GetPlatform()");
SDLTest_AssertCheck(platform != NULL, "SDL_GetPlatform() != NULL");
if (platform != NULL) {
len = SDL_strlen(platform);
SDLTest_AssertCheck(len > 0,
"SDL_GetPlatform(): expected non-empty platform, was platform: '%s', len: %i",
platform,
(int) len);
}
ret = SDL_GetCPUCount();
SDLTest_AssertPass("SDL_GetCPUCount()");
SDLTest_AssertCheck(ret > 0,
"SDL_GetCPUCount(): expected count > 0, was: %i",
ret);
ret = SDL_GetCPUCacheLineSize();
SDLTest_AssertPass("SDL_GetCPUCacheLineSize()");
SDLTest_AssertCheck(ret >= 0,
"SDL_GetCPUCacheLineSize(): expected size >= 0, was: %i",
ret);
revision = (char *)SDL_GetRevision();
SDLTest_AssertPass("SDL_GetRevision()");
SDLTest_AssertCheck(revision != NULL, "SDL_GetRevision() != NULL");
ret = SDL_GetRevisionNumber();
SDLTest_AssertPass("SDL_GetRevisionNumber()");
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_HasXYZ() functions
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_Has3DNow
* http://wiki.libsdl.org/moin.cgi/SDL_HasAltiVec
* http://wiki.libsdl.org/moin.cgi/SDL_HasMMX
* http://wiki.libsdl.org/moin.cgi/SDL_HasRDTSC
* http://wiki.libsdl.org/moin.cgi/SDL_HasSSE
* http://wiki.libsdl.org/moin.cgi/SDL_HasSSE2
* http://wiki.libsdl.org/moin.cgi/SDL_HasSSE3
* http://wiki.libsdl.org/moin.cgi/SDL_HasSSE41
* http://wiki.libsdl.org/moin.cgi/SDL_HasSSE42
* http://wiki.libsdl.org/moin.cgi/SDL_HasAVX
*/
int platform_testHasFunctions (void *arg)
{
int ret;
/* TODO: independently determine and compare values as well */
ret = SDL_HasRDTSC();
SDLTest_AssertPass("SDL_HasRDTSC()");
ret = SDL_HasAltiVec();
SDLTest_AssertPass("SDL_HasAltiVec()");
ret = SDL_HasMMX();
SDLTest_AssertPass("SDL_HasMMX()");
ret = SDL_Has3DNow();
SDLTest_AssertPass("SDL_Has3DNow()");
ret = SDL_HasSSE();
SDLTest_AssertPass("SDL_HasSSE()");
ret = SDL_HasSSE2();
SDLTest_AssertPass("SDL_HasSSE2()");
ret = SDL_HasSSE3();
SDLTest_AssertPass("SDL_HasSSE3()");
ret = SDL_HasSSE41();
SDLTest_AssertPass("SDL_HasSSE41()");
ret = SDL_HasSSE42();
SDLTest_AssertPass("SDL_HasSSE42()");
ret = SDL_HasAVX();
SDLTest_AssertPass("SDL_HasAVX()");
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_GetVersion
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_GetVersion
*/
int platform_testGetVersion(void *arg)
{
SDL_version linked;
int major = SDL_MAJOR_VERSION;
int minor = SDL_MINOR_VERSION;
SDL_GetVersion(&linked);
SDLTest_AssertCheck( linked.major >= major,
"SDL_GetVersion(): returned major %i (>= %i)",
linked.major,
major);
SDLTest_AssertCheck( linked.minor >= minor,
"SDL_GetVersion(): returned minor %i (>= %i)",
linked.minor,
minor);
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_VERSION macro
*/
int platform_testSDLVersion(void *arg)
{
SDL_version compiled;
int major = SDL_MAJOR_VERSION;
int minor = SDL_MINOR_VERSION;
SDL_VERSION(&compiled);
SDLTest_AssertCheck( compiled.major >= major,
"SDL_VERSION() returned major %i (>= %i)",
compiled.major,
major);
SDLTest_AssertCheck( compiled.minor >= minor,
"SDL_VERSION() returned minor %i (>= %i)",
compiled.minor,
minor);
return TEST_COMPLETED;
}
/* !
* \brief Tests default SDL_Init
*/
int platform_testDefaultInit(void *arg)
{
int ret;
int subsystem;
subsystem = SDL_WasInit(SDL_INIT_EVERYTHING);
SDLTest_AssertCheck( subsystem != 0,
"SDL_WasInit(0): returned %i, expected != 0",
subsystem);
ret = SDL_Init(SDL_WasInit(SDL_INIT_EVERYTHING));
SDLTest_AssertCheck( ret == 0,
"SDL_Init(0): returned %i, expected 0, error: %s",
ret,
SDL_GetError());
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_Get/Set/ClearError
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_GetError
* http://wiki.libsdl.org/moin.cgi/SDL_SetError
* http://wiki.libsdl.org/moin.cgi/SDL_ClearError
*/
int platform_testGetSetClearError(void *arg)
{
int result;
const char *testError = "Testing";
char *lastError;
size_t len;
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError != NULL,
"SDL_GetError() != NULL");
if (lastError != NULL)
{
len = SDL_strlen(lastError);
SDLTest_AssertCheck(len == 0,
"SDL_GetError(): no message expected, len: %i", (int) len);
}
result = SDL_SetError("%s", testError);
SDLTest_AssertPass("SDL_SetError()");
SDLTest_AssertCheck(result == -1, "SDL_SetError: expected -1, got: %i", result);
lastError = (char *)SDL_GetError();
SDLTest_AssertCheck(lastError != NULL,
"SDL_GetError() != NULL");
if (lastError != NULL)
{
len = SDL_strlen(lastError);
SDLTest_AssertCheck(len == SDL_strlen(testError),
"SDL_GetError(): expected message len %i, was len: %i",
(int) SDL_strlen(testError),
(int) len);
SDLTest_AssertCheck(SDL_strcmp(lastError, testError) == 0,
"SDL_GetError(): expected message %s, was message: %s",
testError,
lastError);
}
/* Clean up */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_SetError with empty input
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_SetError
*/
int platform_testSetErrorEmptyInput(void *arg)
{
int result;
const char *testError = "";
char *lastError;
size_t len;
result = SDL_SetError("%s", testError);
SDLTest_AssertPass("SDL_SetError()");
SDLTest_AssertCheck(result == -1, "SDL_SetError: expected -1, got: %i", result);
lastError = (char *)SDL_GetError();
SDLTest_AssertCheck(lastError != NULL,
"SDL_GetError() != NULL");
if (lastError != NULL)
{
len = SDL_strlen(lastError);
SDLTest_AssertCheck(len == SDL_strlen(testError),
"SDL_GetError(): expected message len %i, was len: %i",
(int) SDL_strlen(testError),
(int) len);
SDLTest_AssertCheck(SDL_strcmp(lastError, testError) == 0,
"SDL_GetError(): expected message '%s', was message: '%s'",
testError,
lastError);
}
/* Clean up */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_SetError with invalid input
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_SetError
*/
int platform_testSetErrorInvalidInput(void *arg)
{
int result;
const char *invalidError = NULL;
const char *probeError = "Testing";
char *lastError;
size_t len;
/* Reset */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
/* Check for no-op */
result = SDL_SetError("%s", invalidError);
SDLTest_AssertPass("SDL_SetError()");
SDLTest_AssertCheck(result == -1, "SDL_SetError: expected -1, got: %i", result);
lastError = (char *)SDL_GetError();
SDLTest_AssertCheck(lastError != NULL,
"SDL_GetError() != NULL");
if (lastError != NULL)
{
len = SDL_strlen(lastError);
SDLTest_AssertCheck(len == 0,
"SDL_GetError(): expected message len 0, was len: %i",
(int) len);
}
/* Set */
result = SDL_SetError("%s", probeError);
SDLTest_AssertPass("SDL_SetError('%s')", probeError);
SDLTest_AssertCheck(result == -1, "SDL_SetError: expected -1, got: %i", result);
/* Check for no-op */
result = SDL_SetError("%s", invalidError);
SDLTest_AssertPass("SDL_SetError(NULL)");
SDLTest_AssertCheck(result == -1, "SDL_SetError: expected -1, got: %i", result);
lastError = (char *)SDL_GetError();
SDLTest_AssertCheck(lastError != NULL,
"SDL_GetError() != NULL");
if (lastError != NULL)
{
len = SDL_strlen(lastError);
SDLTest_AssertCheck(len == 0,
"SDL_GetError(): expected message len 0, was len: %i",
(int) len);
}
/* Reset */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
/* Set and check */
result = SDL_SetError("%s", probeError);
SDLTest_AssertPass("SDL_SetError()");
SDLTest_AssertCheck(result == -1, "SDL_SetError: expected -1, got: %i", result);
lastError = (char *)SDL_GetError();
SDLTest_AssertCheck(lastError != NULL,
"SDL_GetError() != NULL");
if (lastError != NULL)
{
len = SDL_strlen(lastError);
SDLTest_AssertCheck(len == SDL_strlen(probeError),
"SDL_GetError(): expected message len %i, was len: %i",
(int) SDL_strlen(probeError),
(int) len);
SDLTest_AssertCheck(SDL_strcmp(lastError, probeError) == 0,
"SDL_GetError(): expected message '%s', was message: '%s'",
probeError,
lastError);
}
/* Clean up */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_GetPowerInfo
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_GetPowerInfo
*/
int platform_testGetPowerInfo(void *arg)
{
SDL_PowerState state;
SDL_PowerState stateAgain;
int secs;
int secsAgain;
int pct;
int pctAgain;
state = SDL_GetPowerInfo(&secs, &pct);
SDLTest_AssertPass("SDL_GetPowerInfo()");
SDLTest_AssertCheck(
state==SDL_POWERSTATE_UNKNOWN ||
state==SDL_POWERSTATE_ON_BATTERY ||
state==SDL_POWERSTATE_NO_BATTERY ||
state==SDL_POWERSTATE_CHARGING ||
state==SDL_POWERSTATE_CHARGED,
"SDL_GetPowerInfo(): state %i is one of the expected values",
(int)state);
if (state==SDL_POWERSTATE_ON_BATTERY)
{
SDLTest_AssertCheck(
secs >= 0,
"SDL_GetPowerInfo(): on battery, secs >= 0, was: %i",
secs);
SDLTest_AssertCheck(
(pct >= 0) && (pct <= 100),
"SDL_GetPowerInfo(): on battery, pct=[0,100], was: %i",
pct);
}
if (state==SDL_POWERSTATE_UNKNOWN ||
state==SDL_POWERSTATE_NO_BATTERY)
{
SDLTest_AssertCheck(
secs == -1,
"SDL_GetPowerInfo(): no battery, secs == -1, was: %i",
secs);
SDLTest_AssertCheck(
pct == -1,
"SDL_GetPowerInfo(): no battery, pct == -1, was: %i",
pct);
}
/* Partial return value variations */
stateAgain = SDL_GetPowerInfo(&secsAgain, NULL);
SDLTest_AssertCheck(
state==stateAgain,
"State %i returned when only 'secs' requested",
stateAgain);
SDLTest_AssertCheck(
secs==secsAgain,
"Value %i matches when only 'secs' requested",
secsAgain);
stateAgain = SDL_GetPowerInfo(NULL, &pctAgain);
SDLTest_AssertCheck(
state==stateAgain,
"State %i returned when only 'pct' requested",
stateAgain);
SDLTest_AssertCheck(
pct==pctAgain,
"Value %i matches when only 'pct' requested",
pctAgain);
stateAgain = SDL_GetPowerInfo(NULL, NULL);
SDLTest_AssertCheck(
state==stateAgain,
"State %i returned when no value requested",
stateAgain);
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Platform test cases */
static const SDLTest_TestCaseReference platformTest1 =
{ (SDLTest_TestCaseFp)platform_testTypes, "platform_testTypes", "Tests predefined types", TEST_ENABLED};
static const SDLTest_TestCaseReference platformTest2 =
{ (SDLTest_TestCaseFp)platform_testEndianessAndSwap, "platform_testEndianessAndSwap", "Tests endianess and swap functions", TEST_ENABLED};
static const SDLTest_TestCaseReference platformTest3 =
{ (SDLTest_TestCaseFp)platform_testGetFunctions, "platform_testGetFunctions", "Tests various SDL_GetXYZ functions", TEST_ENABLED};
static const SDLTest_TestCaseReference platformTest4 =
{ (SDLTest_TestCaseFp)platform_testHasFunctions, "platform_testHasFunctions", "Tests various SDL_HasXYZ functions", TEST_ENABLED};
static const SDLTest_TestCaseReference platformTest5 =
{ (SDLTest_TestCaseFp)platform_testGetVersion, "platform_testGetVersion", "Tests SDL_GetVersion function", TEST_ENABLED};
static const SDLTest_TestCaseReference platformTest6 =
{ (SDLTest_TestCaseFp)platform_testSDLVersion, "platform_testSDLVersion", "Tests SDL_VERSION macro", TEST_ENABLED};
static const SDLTest_TestCaseReference platformTest7 =
{ (SDLTest_TestCaseFp)platform_testDefaultInit, "platform_testDefaultInit", "Tests default SDL_Init", TEST_ENABLED};
static const SDLTest_TestCaseReference platformTest8 =
{ (SDLTest_TestCaseFp)platform_testGetSetClearError, "platform_testGetSetClearError", "Tests SDL_Get/Set/ClearError", TEST_ENABLED};
static const SDLTest_TestCaseReference platformTest9 =
{ (SDLTest_TestCaseFp)platform_testSetErrorEmptyInput, "platform_testSetErrorEmptyInput", "Tests SDL_SetError with empty input", TEST_ENABLED};
static const SDLTest_TestCaseReference platformTest10 =
{ (SDLTest_TestCaseFp)platform_testSetErrorInvalidInput, "platform_testSetErrorInvalidInput", "Tests SDL_SetError with invalid input", TEST_ENABLED};
static const SDLTest_TestCaseReference platformTest11 =
{ (SDLTest_TestCaseFp)platform_testGetPowerInfo, "platform_testGetPowerInfo", "Tests SDL_GetPowerInfo function", TEST_ENABLED };
/* Sequence of Platform test cases */
static const SDLTest_TestCaseReference *platformTests[] = {
&platformTest1,
&platformTest2,
&platformTest3,
&platformTest4,
&platformTest5,
&platformTest6,
&platformTest7,
&platformTest8,
&platformTest9,
&platformTest10,
&platformTest11,
NULL
};
/* Platform test suite (global) */
SDLTest_TestSuiteReference platformTestSuite = {
"Platform",
NULL,
platformTests,
NULL
};
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_platform.c | C | apache-2.0 | 17,533 |
/**
* Original code: automated SDL rect test written by Edgar Simo "bobbens"
* New/updated tests: aschiffler at ferzkopp dot net
*/
#include <stdio.h>
#include "SDL.h"
#include "SDL_test.h"
/* ================= Test Case Implementation ================== */
/* Helper functions */
/* !
* \brief Private helper to check SDL_IntersectRectAndLine results
*/
void _validateIntersectRectAndLineResults(
SDL_bool intersection, SDL_bool expectedIntersection,
SDL_Rect *rect, SDL_Rect * refRect,
int x1, int y1, int x2, int y2,
int x1Ref, int y1Ref, int x2Ref, int y2Ref)
{
SDLTest_AssertCheck(intersection == expectedIntersection,
"Check for correct intersection result: expected %s, got %s intersecting rect (%d,%d,%d,%d) with line (%d,%d - %d,%d)",
(expectedIntersection == SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE",
(intersection == SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE",
refRect->x, refRect->y, refRect->w, refRect->h,
x1Ref, y1Ref, x2Ref, y2Ref);
SDLTest_AssertCheck(rect->x == refRect->x && rect->y == refRect->y && rect->w == refRect->w && rect->h == refRect->h,
"Check that source rectangle was not modified: got (%d,%d,%d,%d) expected (%d,%d,%d,%d)",
rect->x, rect->y, rect->w, rect->h,
refRect->x, refRect->y, refRect->w, refRect->h);
SDLTest_AssertCheck(x1 == x1Ref && y1 == y1Ref && x2 == x2Ref && y2 == y2Ref,
"Check if line was incorrectly clipped or modified: got (%d,%d - %d,%d) expected (%d,%d - %d,%d)",
x1, y1, x2, y2,
x1Ref, y1Ref, x2Ref, y2Ref);
}
/* Test case functions */
/* !
* \brief Tests SDL_IntersectRectAndLine() clipping cases
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_IntersectRectAndLine
*/
int
rect_testIntersectRectAndLine (void *arg)
{
SDL_Rect refRect = { 0, 0, 32, 32 };
SDL_Rect rect;
int x1, y1;
int x2, y2;
SDL_bool intersected;
int xLeft = -SDLTest_RandomIntegerInRange(1, refRect.w);
int xRight = refRect.w + SDLTest_RandomIntegerInRange(1, refRect.w);
int yTop = -SDLTest_RandomIntegerInRange(1, refRect.h);
int yBottom = refRect.h + SDLTest_RandomIntegerInRange(1, refRect.h);
x1 = xLeft;
y1 = 15;
x2 = xRight;
y2 = 15;
rect = refRect;
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, &y2);
_validateIntersectRectAndLineResults(intersected, SDL_TRUE, &rect, &refRect, x1, y1, x2, y2, 0, 15, 31, 15);
x1 = 15;
y1 = yTop;
x2 = 15;
y2 = yBottom;
rect = refRect;
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, &y2);
_validateIntersectRectAndLineResults(intersected, SDL_TRUE, &rect, &refRect, x1, y1, x2, y2, 15, 0, 15, 31);
x1 = -refRect.w;
y1 = -refRect.h;
x2 = 2*refRect.w;
y2 = 2*refRect.h;
rect = refRect;
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, &y2);
_validateIntersectRectAndLineResults(intersected, SDL_TRUE, &rect, &refRect, x1, y1, x2, y2, 0, 0, 31, 31);
x1 = 2*refRect.w;
y1 = 2*refRect.h;
x2 = -refRect.w;
y2 = -refRect.h;
rect = refRect;
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, &y2);
_validateIntersectRectAndLineResults(intersected, SDL_TRUE, &rect, &refRect, x1, y1, x2, y2, 31, 31, 0, 0);
x1 = -1;
y1 = 32;
x2 = 32;
y2 = -1;
rect = refRect;
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, &y2);
_validateIntersectRectAndLineResults(intersected, SDL_TRUE, &rect, &refRect, x1, y1, x2, y2, 0, 31, 31, 0);
x1 = 32;
y1 = -1;
x2 = -1;
y2 = 32;
rect = refRect;
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, &y2);
_validateIntersectRectAndLineResults(intersected, SDL_TRUE, &rect, &refRect, x1, y1, x2, y2, 31, 0, 0, 31);
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_IntersectRectAndLine() non-clipping case line inside
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_IntersectRectAndLine
*/
int
rect_testIntersectRectAndLineInside (void *arg)
{
SDL_Rect refRect = { 0, 0, 32, 32 };
SDL_Rect rect;
int x1, y1;
int x2, y2;
SDL_bool intersected;
int xmin = refRect.x;
int xmax = refRect.x + refRect.w - 1;
int ymin = refRect.y;
int ymax = refRect.y + refRect.h - 1;
int x1Ref = SDLTest_RandomIntegerInRange(xmin + 1, xmax - 1);
int y1Ref = SDLTest_RandomIntegerInRange(ymin + 1, ymax - 1);
int x2Ref = SDLTest_RandomIntegerInRange(xmin + 1, xmax - 1);
int y2Ref = SDLTest_RandomIntegerInRange(ymin + 1, ymax - 1);
x1 = x1Ref;
y1 = y1Ref;
x2 = x2Ref;
y2 = y2Ref;
rect = refRect;
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, &y2);
_validateIntersectRectAndLineResults(intersected, SDL_TRUE, &rect, &refRect, x1, y1, x2, y2, x1Ref, y1Ref, x2Ref, y2Ref);
x1 = x1Ref;
y1 = y1Ref;
x2 = xmax;
y2 = ymax;
rect = refRect;
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, &y2);
_validateIntersectRectAndLineResults(intersected, SDL_TRUE, &rect, &refRect, x1, y1, x2, y2, x1Ref, y1Ref, xmax, ymax);
x1 = xmin;
y1 = ymin;
x2 = x2Ref;
y2 = y2Ref;
rect = refRect;
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, &y2);
_validateIntersectRectAndLineResults(intersected, SDL_TRUE, &rect, &refRect, x1, y1, x2, y2, xmin, ymin, x2Ref, y2Ref);
x1 = xmin;
y1 = ymin;
x2 = xmax;
y2 = ymax;
rect = refRect;
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, &y2);
_validateIntersectRectAndLineResults(intersected, SDL_TRUE, &rect, &refRect, x1, y1, x2, y2, xmin, ymin, xmax, ymax);
x1 = xmin;
y1 = ymax;
x2 = xmax;
y2 = ymin;
rect = refRect;
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, &y2);
_validateIntersectRectAndLineResults(intersected, SDL_TRUE, &rect, &refRect, x1, y1, x2, y2, xmin, ymax, xmax, ymin);
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_IntersectRectAndLine() non-clipping cases outside
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_IntersectRectAndLine
*/
int
rect_testIntersectRectAndLineOutside (void *arg)
{
SDL_Rect refRect = { 0, 0, 32, 32 };
SDL_Rect rect;
int x1, y1;
int x2, y2;
SDL_bool intersected;
int xLeft = -SDLTest_RandomIntegerInRange(1, refRect.w);
int xRight = refRect.w + SDLTest_RandomIntegerInRange(1, refRect.w);
int yTop = -SDLTest_RandomIntegerInRange(1, refRect.h);
int yBottom = refRect.h + SDLTest_RandomIntegerInRange(1, refRect.h);
x1 = xLeft;
y1 = 0;
x2 = xLeft;
y2 = 31;
rect = refRect;
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, &y2);
_validateIntersectRectAndLineResults(intersected, SDL_FALSE, &rect, &refRect, x1, y1, x2, y2, xLeft, 0, xLeft, 31);
x1 = xRight;
y1 = 0;
x2 = xRight;
y2 = 31;
rect = refRect;
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, &y2);
_validateIntersectRectAndLineResults(intersected, SDL_FALSE, &rect, &refRect, x1, y1, x2, y2, xRight, 0, xRight, 31);
x1 = 0;
y1 = yTop;
x2 = 31;
y2 = yTop;
rect = refRect;
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, &y2);
_validateIntersectRectAndLineResults(intersected, SDL_FALSE, &rect, &refRect, x1, y1, x2, y2, 0, yTop, 31, yTop);
x1 = 0;
y1 = yBottom;
x2 = 31;
y2 = yBottom;
rect = refRect;
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, &y2);
_validateIntersectRectAndLineResults(intersected, SDL_FALSE, &rect, &refRect, x1, y1, x2, y2, 0, yBottom, 31, yBottom);
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_IntersectRectAndLine() with empty rectangle
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_IntersectRectAndLine
*/
int
rect_testIntersectRectAndLineEmpty (void *arg)
{
SDL_Rect refRect;
SDL_Rect rect;
int x1, y1, x1Ref, y1Ref;
int x2, y2, x2Ref, y2Ref;
SDL_bool intersected;
refRect.x = SDLTest_RandomIntegerInRange(1, 1024);
refRect.y = SDLTest_RandomIntegerInRange(1, 1024);
refRect.w = 0;
refRect.h = 0;
x1Ref = refRect.x;
y1Ref = refRect.y;
x2Ref = SDLTest_RandomIntegerInRange(1, 1024);
y2Ref = SDLTest_RandomIntegerInRange(1, 1024);
x1 = x1Ref;
y1 = y1Ref;
x2 = x2Ref;
y2 = y2Ref;
rect = refRect;
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, &y2);
_validateIntersectRectAndLineResults(intersected, SDL_FALSE, &rect, &refRect, x1, y1, x2, y2, x1Ref, y1Ref, x2Ref, y2Ref);
return TEST_COMPLETED;
}
/* !
* \brief Negative tests against SDL_IntersectRectAndLine() with invalid parameters
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_IntersectRectAndLine
*/
int
rect_testIntersectRectAndLineParam (void *arg)
{
SDL_Rect rect = { 0, 0, 32, 32 };
int x1 = rect.w / 2;
int y1 = rect.h / 2;
int x2 = x1;
int y2 = 2 * rect.h;
SDL_bool intersected;
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, &y2);
SDLTest_AssertCheck(intersected == SDL_TRUE, "Check that intersection result was SDL_TRUE");
intersected = SDL_IntersectRectAndLine((SDL_Rect *)NULL, &x1, &y1, &x2, &y2);
SDLTest_AssertCheck(intersected == SDL_FALSE, "Check that function returns SDL_FALSE when 1st parameter is NULL");
intersected = SDL_IntersectRectAndLine(&rect, (int *)NULL, &y1, &x2, &y2);
SDLTest_AssertCheck(intersected == SDL_FALSE, "Check that function returns SDL_FALSE when 2nd parameter is NULL");
intersected = SDL_IntersectRectAndLine(&rect, &x1, (int *)NULL, &x2, &y2);
SDLTest_AssertCheck(intersected == SDL_FALSE, "Check that function returns SDL_FALSE when 3rd parameter is NULL");
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, (int *)NULL, &y2);
SDLTest_AssertCheck(intersected == SDL_FALSE, "Check that function returns SDL_FALSE when 4th parameter is NULL");
intersected = SDL_IntersectRectAndLine(&rect, &x1, &y1, &x2, (int *)NULL);
SDLTest_AssertCheck(intersected == SDL_FALSE, "Check that function returns SDL_FALSE when 5th parameter is NULL");
intersected = SDL_IntersectRectAndLine((SDL_Rect *)NULL, (int *)NULL, (int *)NULL, (int *)NULL, (int *)NULL);
SDLTest_AssertCheck(intersected == SDL_FALSE, "Check that function returns SDL_FALSE when all parameters are NULL");
return TEST_COMPLETED;
}
/* !
* \brief Private helper to check SDL_HasIntersection results
*/
void _validateHasIntersectionResults(
SDL_bool intersection, SDL_bool expectedIntersection,
SDL_Rect *rectA, SDL_Rect *rectB, SDL_Rect *refRectA, SDL_Rect *refRectB)
{
SDLTest_AssertCheck(intersection == expectedIntersection,
"Check intersection result: expected %s, got %s intersecting A (%d,%d,%d,%d) with B (%d,%d,%d,%d)",
(expectedIntersection == SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE",
(intersection == SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE",
rectA->x, rectA->y, rectA->w, rectA->h,
rectB->x, rectB->y, rectB->w, rectB->h);
SDLTest_AssertCheck(rectA->x == refRectA->x && rectA->y == refRectA->y && rectA->w == refRectA->w && rectA->h == refRectA->h,
"Check that source rectangle A was not modified: got (%d,%d,%d,%d) expected (%d,%d,%d,%d)",
rectA->x, rectA->y, rectA->w, rectA->h,
refRectA->x, refRectA->y, refRectA->w, refRectA->h);
SDLTest_AssertCheck(rectB->x == refRectB->x && rectB->y == refRectB->y && rectB->w == refRectB->w && rectB->h == refRectB->h,
"Check that source rectangle B was not modified: got (%d,%d,%d,%d) expected (%d,%d,%d,%d)",
rectB->x, rectB->y, rectB->w, rectB->h,
refRectB->x, refRectB->y, refRectB->w, refRectB->h);
}
/* !
* \brief Private helper to check SDL_IntersectRect results
*/
void _validateIntersectRectResults(
SDL_bool intersection, SDL_bool expectedIntersection,
SDL_Rect *rectA, SDL_Rect *rectB, SDL_Rect *refRectA, SDL_Rect *refRectB,
SDL_Rect *result, SDL_Rect *expectedResult)
{
_validateHasIntersectionResults(intersection, expectedIntersection, rectA, rectB, refRectA, refRectB);
if (result && expectedResult) {
SDLTest_AssertCheck(result->x == expectedResult->x && result->y == expectedResult->y && result->w == expectedResult->w && result->h == expectedResult->h,
"Check that intersection of rectangles A (%d,%d,%d,%d) and B (%d,%d,%d,%d) was correctly calculated, got (%d,%d,%d,%d) expected (%d,%d,%d,%d)",
rectA->x, rectA->y, rectA->w, rectA->h,
rectB->x, rectB->y, rectB->w, rectB->h,
result->x, result->y, result->w, result->h,
expectedResult->x, expectedResult->y, expectedResult->w, expectedResult->h);
}
}
/* !
* \brief Private helper to check SDL_UnionRect results
*/
void _validateUnionRectResults(
SDL_Rect *rectA, SDL_Rect *rectB, SDL_Rect *refRectA, SDL_Rect *refRectB,
SDL_Rect *result, SDL_Rect *expectedResult)
{
SDLTest_AssertCheck(rectA->x == refRectA->x && rectA->y == refRectA->y && rectA->w == refRectA->w && rectA->h == refRectA->h,
"Check that source rectangle A was not modified: got (%d,%d,%d,%d) expected (%d,%d,%d,%d)",
rectA->x, rectA->y, rectA->w, rectA->h,
refRectA->x, refRectA->y, refRectA->w, refRectA->h);
SDLTest_AssertCheck(rectB->x == refRectB->x && rectB->y == refRectB->y && rectB->w == refRectB->w && rectB->h == refRectB->h,
"Check that source rectangle B was not modified: got (%d,%d,%d,%d) expected (%d,%d,%d,%d)",
rectB->x, rectB->y, rectB->w, rectB->h,
refRectB->x, refRectB->y, refRectB->w, refRectB->h);
SDLTest_AssertCheck(result->x == expectedResult->x && result->y == expectedResult->y && result->w == expectedResult->w && result->h == expectedResult->h,
"Check that union of rectangles A (%d,%d,%d,%d) and B (%d,%d,%d,%d) was correctly calculated, got (%d,%d,%d,%d) expected (%d,%d,%d,%d)",
rectA->x, rectA->y, rectA->w, rectA->h,
rectB->x, rectB->y, rectB->w, rectB->h,
result->x, result->y, result->w, result->h,
expectedResult->x, expectedResult->y, expectedResult->w, expectedResult->h);
}
/* !
* \brief Private helper to check SDL_RectEmpty results
*/
void _validateRectEmptyResults(
SDL_bool empty, SDL_bool expectedEmpty,
SDL_Rect *rect, SDL_Rect *refRect)
{
SDLTest_AssertCheck(empty == expectedEmpty,
"Check for correct empty result: expected %s, got %s testing (%d,%d,%d,%d)",
(expectedEmpty == SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE",
(empty == SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE",
rect->x, rect->y, rect->w, rect->h);
SDLTest_AssertCheck(rect->x == refRect->x && rect->y == refRect->y && rect->w == refRect->w && rect->h == refRect->h,
"Check that source rectangle was not modified: got (%d,%d,%d,%d) expected (%d,%d,%d,%d)",
rect->x, rect->y, rect->w, rect->h,
refRect->x, refRect->y, refRect->w, refRect->h);
}
/* !
* \brief Private helper to check SDL_RectEquals results
*/
void _validateRectEqualsResults(
SDL_bool equals, SDL_bool expectedEquals,
SDL_Rect *rectA, SDL_Rect *rectB, SDL_Rect *refRectA, SDL_Rect *refRectB)
{
SDLTest_AssertCheck(equals == expectedEquals,
"Check for correct equals result: expected %s, got %s testing (%d,%d,%d,%d) and (%d,%d,%d,%d)",
(expectedEquals == SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE",
(equals == SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE",
rectA->x, rectA->y, rectA->w, rectA->h,
rectB->x, rectB->y, rectB->w, rectB->h);
SDLTest_AssertCheck(rectA->x == refRectA->x && rectA->y == refRectA->y && rectA->w == refRectA->w && rectA->h == refRectA->h,
"Check that source rectangle A was not modified: got (%d,%d,%d,%d) expected (%d,%d,%d,%d)",
rectA->x, rectA->y, rectA->w, rectA->h,
refRectA->x, refRectA->y, refRectA->w, refRectA->h);
SDLTest_AssertCheck(rectB->x == refRectB->x && rectB->y == refRectB->y && rectB->w == refRectB->w && rectB->h == refRectB->h,
"Check that source rectangle B was not modified: got (%d,%d,%d,%d) expected (%d,%d,%d,%d)",
rectB->x, rectB->y, rectB->w, rectB->h,
refRectB->x, refRectB->y, refRectB->w, refRectB->h);
}
/* !
* \brief Tests SDL_IntersectRect() with B fully inside A
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_IntersectRect
*/
int rect_testIntersectRectInside (void *arg)
{
SDL_Rect refRectA = { 0, 0, 32, 32 };
SDL_Rect refRectB;
SDL_Rect rectA;
SDL_Rect rectB;
SDL_Rect result;
SDL_bool intersection;
/* rectB fully contained in rectA */
refRectB.x = 0;
refRectB.y = 0;
refRectB.w = SDLTest_RandomIntegerInRange(refRectA.x + 1, refRectA.x + refRectA.w - 1);
refRectB.h = SDLTest_RandomIntegerInRange(refRectA.y + 1, refRectA.y + refRectA.h - 1);
rectA = refRectA;
rectB = refRectB;
intersection = SDL_IntersectRect(&rectA, &rectB, &result);
_validateIntersectRectResults(intersection, SDL_TRUE, &rectA, &rectB, &refRectA, &refRectB, &result, &refRectB);
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_IntersectRect() with B fully outside A
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_IntersectRect
*/
int rect_testIntersectRectOutside (void *arg)
{
SDL_Rect refRectA = { 0, 0, 32, 32 };
SDL_Rect refRectB;
SDL_Rect rectA;
SDL_Rect rectB;
SDL_Rect result;
SDL_bool intersection;
/* rectB fully outside of rectA */
refRectB.x = refRectA.x + refRectA.w + SDLTest_RandomIntegerInRange(1, 10);
refRectB.y = refRectA.y + refRectA.h + SDLTest_RandomIntegerInRange(1, 10);
refRectB.w = refRectA.w;
refRectB.h = refRectA.h;
rectA = refRectA;
rectB = refRectB;
intersection = SDL_IntersectRect(&rectA, &rectB, &result);
_validateIntersectRectResults(intersection, SDL_FALSE, &rectA, &rectB, &refRectA, &refRectB, (SDL_Rect *)NULL, (SDL_Rect *)NULL);
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_IntersectRect() with B partially intersecting A
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_IntersectRect
*/
int rect_testIntersectRectPartial (void *arg)
{
SDL_Rect refRectA = { 0, 0, 32, 32 };
SDL_Rect refRectB;
SDL_Rect rectA;
SDL_Rect rectB;
SDL_Rect result;
SDL_Rect expectedResult;
SDL_bool intersection;
/* rectB partially contained in rectA */
refRectB.x = SDLTest_RandomIntegerInRange(refRectA.x + 1, refRectA.x + refRectA.w - 1);
refRectB.y = SDLTest_RandomIntegerInRange(refRectA.y + 1, refRectA.y + refRectA.h - 1);
refRectB.w = refRectA.w;
refRectB.h = refRectA.h;
rectA = refRectA;
rectB = refRectB;
expectedResult.x = refRectB.x;
expectedResult.y = refRectB.y;
expectedResult.w = refRectA.w - refRectB.x;
expectedResult.h = refRectA.h - refRectB.y;
intersection = SDL_IntersectRect(&rectA, &rectB, &result);
_validateIntersectRectResults(intersection, SDL_TRUE, &rectA, &rectB, &refRectA, &refRectB, &result, &expectedResult);
/* rectB right edge */
refRectB.x = rectA.w - 1;
refRectB.y = rectA.y;
refRectB.w = SDLTest_RandomIntegerInRange(1, refRectA.w - 1);
refRectB.h = SDLTest_RandomIntegerInRange(1, refRectA.h - 1);
rectA = refRectA;
rectB = refRectB;
expectedResult.x = refRectB.x;
expectedResult.y = refRectB.y;
expectedResult.w = 1;
expectedResult.h = refRectB.h;
intersection = SDL_IntersectRect(&rectA, &rectB, &result);
_validateIntersectRectResults(intersection, SDL_TRUE, &rectA, &rectB, &refRectA, &refRectB, &result, &expectedResult);
/* rectB left edge */
refRectB.x = 1 - rectA.w;
refRectB.y = rectA.y;
refRectB.w = refRectA.w;
refRectB.h = SDLTest_RandomIntegerInRange(1, refRectA.h - 1);
rectA = refRectA;
rectB = refRectB;
expectedResult.x = 0;
expectedResult.y = refRectB.y;
expectedResult.w = 1;
expectedResult.h = refRectB.h;
intersection = SDL_IntersectRect(&rectA, &rectB, &result);
_validateIntersectRectResults(intersection, SDL_TRUE, &rectA, &rectB, &refRectA, &refRectB, &result, &expectedResult);
/* rectB bottom edge */
refRectB.x = rectA.x;
refRectB.y = rectA.h - 1;
refRectB.w = SDLTest_RandomIntegerInRange(1, refRectA.w - 1);
refRectB.h = SDLTest_RandomIntegerInRange(1, refRectA.h - 1);
rectA = refRectA;
rectB = refRectB;
expectedResult.x = refRectB.x;
expectedResult.y = refRectB.y;
expectedResult.w = refRectB.w;
expectedResult.h = 1;
intersection = SDL_IntersectRect(&rectA, &rectB, &result);
_validateIntersectRectResults(intersection, SDL_TRUE, &rectA, &rectB, &refRectA, &refRectB, &result, &expectedResult);
/* rectB top edge */
refRectB.x = rectA.x;
refRectB.y = 1 - rectA.h;
refRectB.w = SDLTest_RandomIntegerInRange(1, refRectA.w - 1);
refRectB.h = rectA.h;
rectA = refRectA;
rectB = refRectB;
expectedResult.x = refRectB.x;
expectedResult.y = 0;
expectedResult.w = refRectB.w;
expectedResult.h = 1;
intersection = SDL_IntersectRect(&rectA, &rectB, &result);
_validateIntersectRectResults(intersection, SDL_TRUE, &rectA, &rectB, &refRectA, &refRectB, &result, &expectedResult);
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_IntersectRect() with 1x1 pixel sized rectangles
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_IntersectRect
*/
int rect_testIntersectRectPoint (void *arg)
{
SDL_Rect refRectA = { 0, 0, 1, 1 };
SDL_Rect refRectB = { 0, 0, 1, 1 };
SDL_Rect rectA;
SDL_Rect rectB;
SDL_Rect result;
SDL_bool intersection;
int offsetX, offsetY;
/* intersecting pixels */
refRectA.x = SDLTest_RandomIntegerInRange(1, 100);
refRectA.y = SDLTest_RandomIntegerInRange(1, 100);
refRectB.x = refRectA.x;
refRectB.y = refRectA.y;
rectA = refRectA;
rectB = refRectB;
intersection = SDL_IntersectRect(&rectA, &rectB, &result);
_validateIntersectRectResults(intersection, SDL_TRUE, &rectA, &rectB, &refRectA, &refRectB, &result, &refRectA);
/* non-intersecting pixels cases */
for (offsetX = -1; offsetX <= 1; offsetX++) {
for (offsetY = -1; offsetY <= 1; offsetY++) {
if (offsetX != 0 || offsetY != 0) {
refRectA.x = SDLTest_RandomIntegerInRange(1, 100);
refRectA.y = SDLTest_RandomIntegerInRange(1, 100);
refRectB.x = refRectA.x;
refRectB.y = refRectA.y;
refRectB.x += offsetX;
refRectB.y += offsetY;
rectA = refRectA;
rectB = refRectB;
intersection = SDL_IntersectRect(&rectA, &rectB, &result);
_validateIntersectRectResults(intersection, SDL_FALSE, &rectA, &rectB, &refRectA, &refRectB, (SDL_Rect *)NULL, (SDL_Rect *)NULL);
}
}
}
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_IntersectRect() with empty rectangles
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_IntersectRect
*/
int rect_testIntersectRectEmpty (void *arg)
{
SDL_Rect refRectA;
SDL_Rect refRectB;
SDL_Rect rectA;
SDL_Rect rectB;
SDL_Rect result;
SDL_bool intersection;
SDL_bool empty;
/* Rect A empty */
result.w = SDLTest_RandomIntegerInRange(1, 100);
result.h = SDLTest_RandomIntegerInRange(1, 100);
refRectA.x = SDLTest_RandomIntegerInRange(1, 100);
refRectA.y = SDLTest_RandomIntegerInRange(1, 100);
refRectA.w = SDLTest_RandomIntegerInRange(1, 100);
refRectA.h = SDLTest_RandomIntegerInRange(1, 100);
refRectB = refRectA;
refRectA.w = 0;
refRectA.h = 0;
rectA = refRectA;
rectB = refRectB;
intersection = SDL_IntersectRect(&rectA, &rectB, &result);
_validateIntersectRectResults(intersection, SDL_FALSE, &rectA, &rectB, &refRectA, &refRectB, (SDL_Rect *)NULL, (SDL_Rect *)NULL);
empty = (SDL_bool)SDL_RectEmpty(&result);
SDLTest_AssertCheck(empty == SDL_TRUE, "Validate result is empty Rect; got: %s", (empty == SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE");
/* Rect B empty */
result.w = SDLTest_RandomIntegerInRange(1, 100);
result.h = SDLTest_RandomIntegerInRange(1, 100);
refRectA.x = SDLTest_RandomIntegerInRange(1, 100);
refRectA.y = SDLTest_RandomIntegerInRange(1, 100);
refRectA.w = SDLTest_RandomIntegerInRange(1, 100);
refRectA.h = SDLTest_RandomIntegerInRange(1, 100);
refRectB = refRectA;
refRectB.w = 0;
refRectB.h = 0;
rectA = refRectA;
rectB = refRectB;
intersection = SDL_IntersectRect(&rectA, &rectB, &result);
_validateIntersectRectResults(intersection, SDL_FALSE, &rectA, &rectB, &refRectA, &refRectB, (SDL_Rect *)NULL, (SDL_Rect *)NULL);
empty = (SDL_bool)SDL_RectEmpty(&result);
SDLTest_AssertCheck(empty == SDL_TRUE, "Validate result is empty Rect; got: %s", (empty == SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE");
/* Rect A and B empty */
result.w = SDLTest_RandomIntegerInRange(1, 100);
result.h = SDLTest_RandomIntegerInRange(1, 100);
refRectA.x = SDLTest_RandomIntegerInRange(1, 100);
refRectA.y = SDLTest_RandomIntegerInRange(1, 100);
refRectA.w = SDLTest_RandomIntegerInRange(1, 100);
refRectA.h = SDLTest_RandomIntegerInRange(1, 100);
refRectB = refRectA;
refRectA.w = 0;
refRectA.h = 0;
refRectB.w = 0;
refRectB.h = 0;
rectA = refRectA;
rectB = refRectB;
intersection = SDL_IntersectRect(&rectA, &rectB, &result);
_validateIntersectRectResults(intersection, SDL_FALSE, &rectA, &rectB, &refRectA, &refRectB, (SDL_Rect *)NULL, (SDL_Rect *)NULL);
empty = (SDL_bool)SDL_RectEmpty(&result);
SDLTest_AssertCheck(empty == SDL_TRUE, "Validate result is empty Rect; got: %s", (empty == SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE");
return TEST_COMPLETED;
}
/* !
* \brief Negative tests against SDL_IntersectRect() with invalid parameters
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_IntersectRect
*/
int rect_testIntersectRectParam(void *arg)
{
SDL_Rect rectA;
SDL_Rect rectB;
SDL_Rect result;
SDL_bool intersection;
/* invalid parameter combinations */
intersection = SDL_IntersectRect((SDL_Rect *)NULL, &rectB, &result);
SDLTest_AssertCheck(intersection == SDL_FALSE, "Check that function returns SDL_FALSE when 1st parameter is NULL");
intersection = SDL_IntersectRect(&rectA, (SDL_Rect *)NULL, &result);
SDLTest_AssertCheck(intersection == SDL_FALSE, "Check that function returns SDL_FALSE when 2st parameter is NULL");
intersection = SDL_IntersectRect(&rectA, &rectB, (SDL_Rect *)NULL);
SDLTest_AssertCheck(intersection == SDL_FALSE, "Check that function returns SDL_FALSE when 3st parameter is NULL");
intersection = SDL_IntersectRect((SDL_Rect *)NULL, (SDL_Rect *)NULL, &result);
SDLTest_AssertCheck(intersection == SDL_FALSE, "Check that function returns SDL_FALSE when 1st and 2nd parameters are NULL");
intersection = SDL_IntersectRect((SDL_Rect *)NULL, &rectB, (SDL_Rect *)NULL);
SDLTest_AssertCheck(intersection == SDL_FALSE, "Check that function returns SDL_FALSE when 1st and 3rd parameters are NULL ");
intersection = SDL_IntersectRect((SDL_Rect *)NULL, (SDL_Rect *)NULL, (SDL_Rect *)NULL);
SDLTest_AssertCheck(intersection == SDL_FALSE, "Check that function returns SDL_FALSE when all parameters are NULL");
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_HasIntersection() with B fully inside A
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_HasIntersection
*/
int rect_testHasIntersectionInside (void *arg)
{
SDL_Rect refRectA = { 0, 0, 32, 32 };
SDL_Rect refRectB;
SDL_Rect rectA;
SDL_Rect rectB;
SDL_bool intersection;
/* rectB fully contained in rectA */
refRectB.x = 0;
refRectB.y = 0;
refRectB.w = SDLTest_RandomIntegerInRange(refRectA.x + 1, refRectA.x + refRectA.w - 1);
refRectB.h = SDLTest_RandomIntegerInRange(refRectA.y + 1, refRectA.y + refRectA.h - 1);
rectA = refRectA;
rectB = refRectB;
intersection = SDL_HasIntersection(&rectA, &rectB);
_validateHasIntersectionResults(intersection, SDL_TRUE, &rectA, &rectB, &refRectA, &refRectB);
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_HasIntersection() with B fully outside A
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_HasIntersection
*/
int rect_testHasIntersectionOutside (void *arg)
{
SDL_Rect refRectA = { 0, 0, 32, 32 };
SDL_Rect refRectB;
SDL_Rect rectA;
SDL_Rect rectB;
SDL_bool intersection;
/* rectB fully outside of rectA */
refRectB.x = refRectA.x + refRectA.w + SDLTest_RandomIntegerInRange(1, 10);
refRectB.y = refRectA.y + refRectA.h + SDLTest_RandomIntegerInRange(1, 10);
refRectB.w = refRectA.w;
refRectB.h = refRectA.h;
rectA = refRectA;
rectB = refRectB;
intersection = SDL_HasIntersection(&rectA, &rectB);
_validateHasIntersectionResults(intersection, SDL_FALSE, &rectA, &rectB, &refRectA, &refRectB);
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_HasIntersection() with B partially intersecting A
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_HasIntersection
*/
int rect_testHasIntersectionPartial (void *arg)
{
SDL_Rect refRectA = { 0, 0, 32, 32 };
SDL_Rect refRectB;
SDL_Rect rectA;
SDL_Rect rectB;
SDL_bool intersection;
/* rectB partially contained in rectA */
refRectB.x = SDLTest_RandomIntegerInRange(refRectA.x + 1, refRectA.x + refRectA.w - 1);
refRectB.y = SDLTest_RandomIntegerInRange(refRectA.y + 1, refRectA.y + refRectA.h - 1);
refRectB.w = refRectA.w;
refRectB.h = refRectA.h;
rectA = refRectA;
rectB = refRectB;
intersection = SDL_HasIntersection(&rectA, &rectB);
_validateHasIntersectionResults(intersection, SDL_TRUE, &rectA, &rectB, &refRectA, &refRectB);
/* rectB right edge */
refRectB.x = rectA.w - 1;
refRectB.y = rectA.y;
refRectB.w = SDLTest_RandomIntegerInRange(1, refRectA.w - 1);
refRectB.h = SDLTest_RandomIntegerInRange(1, refRectA.h - 1);
rectA = refRectA;
rectB = refRectB;
intersection = SDL_HasIntersection(&rectA, &rectB);
_validateHasIntersectionResults(intersection, SDL_TRUE, &rectA, &rectB, &refRectA, &refRectB);
/* rectB left edge */
refRectB.x = 1 - rectA.w;
refRectB.y = rectA.y;
refRectB.w = refRectA.w;
refRectB.h = SDLTest_RandomIntegerInRange(1, refRectA.h - 1);
rectA = refRectA;
rectB = refRectB;
intersection = SDL_HasIntersection(&rectA, &rectB);
_validateHasIntersectionResults(intersection, SDL_TRUE, &rectA, &rectB, &refRectA, &refRectB);
/* rectB bottom edge */
refRectB.x = rectA.x;
refRectB.y = rectA.h - 1;
refRectB.w = SDLTest_RandomIntegerInRange(1, refRectA.w - 1);
refRectB.h = SDLTest_RandomIntegerInRange(1, refRectA.h - 1);
rectA = refRectA;
rectB = refRectB;
intersection = SDL_HasIntersection(&rectA, &rectB);
_validateHasIntersectionResults(intersection, SDL_TRUE, &rectA, &rectB, &refRectA, &refRectB);
/* rectB top edge */
refRectB.x = rectA.x;
refRectB.y = 1 - rectA.h;
refRectB.w = SDLTest_RandomIntegerInRange(1, refRectA.w - 1);
refRectB.h = rectA.h;
rectA = refRectA;
rectB = refRectB;
intersection = SDL_HasIntersection(&rectA, &rectB);
_validateHasIntersectionResults(intersection, SDL_TRUE, &rectA, &rectB, &refRectA, &refRectB);
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_HasIntersection() with 1x1 pixel sized rectangles
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_HasIntersection
*/
int rect_testHasIntersectionPoint (void *arg)
{
SDL_Rect refRectA = { 0, 0, 1, 1 };
SDL_Rect refRectB = { 0, 0, 1, 1 };
SDL_Rect rectA;
SDL_Rect rectB;
SDL_bool intersection;
int offsetX, offsetY;
/* intersecting pixels */
refRectA.x = SDLTest_RandomIntegerInRange(1, 100);
refRectA.y = SDLTest_RandomIntegerInRange(1, 100);
refRectB.x = refRectA.x;
refRectB.y = refRectA.y;
rectA = refRectA;
rectB = refRectB;
intersection = SDL_HasIntersection(&rectA, &rectB);
_validateHasIntersectionResults(intersection, SDL_TRUE, &rectA, &rectB, &refRectA, &refRectB);
/* non-intersecting pixels cases */
for (offsetX = -1; offsetX <= 1; offsetX++) {
for (offsetY = -1; offsetY <= 1; offsetY++) {
if (offsetX != 0 || offsetY != 0) {
refRectA.x = SDLTest_RandomIntegerInRange(1, 100);
refRectA.y = SDLTest_RandomIntegerInRange(1, 100);
refRectB.x = refRectA.x;
refRectB.y = refRectA.y;
refRectB.x += offsetX;
refRectB.y += offsetY;
rectA = refRectA;
rectB = refRectB;
intersection = SDL_HasIntersection(&rectA, &rectB);
_validateHasIntersectionResults(intersection, SDL_FALSE, &rectA, &rectB, &refRectA, &refRectB);
}
}
}
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_HasIntersection() with empty rectangles
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_HasIntersection
*/
int rect_testHasIntersectionEmpty (void *arg)
{
SDL_Rect refRectA;
SDL_Rect refRectB;
SDL_Rect rectA;
SDL_Rect rectB;
SDL_bool intersection;
/* Rect A empty */
refRectA.x = SDLTest_RandomIntegerInRange(1, 100);
refRectA.y = SDLTest_RandomIntegerInRange(1, 100);
refRectA.w = SDLTest_RandomIntegerInRange(1, 100);
refRectA.h = SDLTest_RandomIntegerInRange(1, 100);
refRectB = refRectA;
refRectA.w = 0;
refRectA.h = 0;
rectA = refRectA;
rectB = refRectB;
intersection = SDL_HasIntersection(&rectA, &rectB);
_validateHasIntersectionResults(intersection, SDL_FALSE, &rectA, &rectB, &refRectA, &refRectB);
/* Rect B empty */
refRectA.x = SDLTest_RandomIntegerInRange(1, 100);
refRectA.y = SDLTest_RandomIntegerInRange(1, 100);
refRectA.w = SDLTest_RandomIntegerInRange(1, 100);
refRectA.h = SDLTest_RandomIntegerInRange(1, 100);
refRectB = refRectA;
refRectB.w = 0;
refRectB.h = 0;
rectA = refRectA;
rectB = refRectB;
intersection = SDL_HasIntersection(&rectA, &rectB);
_validateHasIntersectionResults(intersection, SDL_FALSE, &rectA, &rectB, &refRectA, &refRectB);
/* Rect A and B empty */
refRectA.x = SDLTest_RandomIntegerInRange(1, 100);
refRectA.y = SDLTest_RandomIntegerInRange(1, 100);
refRectA.w = SDLTest_RandomIntegerInRange(1, 100);
refRectA.h = SDLTest_RandomIntegerInRange(1, 100);
refRectB = refRectA;
refRectA.w = 0;
refRectA.h = 0;
refRectB.w = 0;
refRectB.h = 0;
rectA = refRectA;
rectB = refRectB;
intersection = SDL_HasIntersection(&rectA, &rectB);
_validateHasIntersectionResults(intersection, SDL_FALSE, &rectA, &rectB, &refRectA, &refRectB);
return TEST_COMPLETED;
}
/* !
* \brief Negative tests against SDL_HasIntersection() with invalid parameters
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_HasIntersection
*/
int rect_testHasIntersectionParam(void *arg)
{
SDL_Rect rectA;
SDL_Rect rectB;
SDL_bool intersection;
/* invalid parameter combinations */
intersection = SDL_HasIntersection((SDL_Rect *)NULL, &rectB);
SDLTest_AssertCheck(intersection == SDL_FALSE, "Check that function returns SDL_FALSE when 1st parameter is NULL");
intersection = SDL_HasIntersection(&rectA, (SDL_Rect *)NULL);
SDLTest_AssertCheck(intersection == SDL_FALSE, "Check that function returns SDL_FALSE when 2st parameter is NULL");
intersection = SDL_HasIntersection((SDL_Rect *)NULL, (SDL_Rect *)NULL);
SDLTest_AssertCheck(intersection == SDL_FALSE, "Check that function returns SDL_FALSE when all parameters are NULL");
return TEST_COMPLETED;
}
/* !
* \brief Test SDL_EnclosePoints() without clipping
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_EnclosePoints
*/
int rect_testEnclosePoints(void *arg)
{
const int numPoints = 16;
SDL_Point refPoints[16];
SDL_Point points[16];
SDL_Rect result;
SDL_bool anyEnclosed;
SDL_bool anyEnclosedNoResult;
SDL_bool expectedEnclosed = SDL_TRUE;
int newx, newy;
int minx = 0, maxx = 0, miny = 0, maxy = 0;
int i;
/* Create input data, tracking result */
for (i=0; i<numPoints; i++) {
newx = SDLTest_RandomIntegerInRange(-1024, 1024);
newy = SDLTest_RandomIntegerInRange(-1024, 1024);
refPoints[i].x = newx;
refPoints[i].y = newy;
points[i].x = newx;
points[i].y = newy;
if (i==0) {
minx = newx;
maxx = newx;
miny = newy;
maxy = newy;
} else {
if (newx < minx) minx = newx;
if (newx > maxx) maxx = newx;
if (newy < miny) miny = newy;
if (newy > maxy) maxy = newy;
}
}
/* Call function and validate - special case: no result requested */
anyEnclosedNoResult = SDL_EnclosePoints((const SDL_Point *)points, numPoints, (const SDL_Rect *)NULL, (SDL_Rect *)NULL);
SDLTest_AssertCheck(expectedEnclosed==anyEnclosedNoResult,
"Check expected return value %s, got %s",
(expectedEnclosed==SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE",
(anyEnclosedNoResult==SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE");
for (i=0; i<numPoints; i++) {
SDLTest_AssertCheck(refPoints[i].x==points[i].x && refPoints[i].y==points[i].y,
"Check that source point %i was not modified: expected (%i,%i) actual (%i,%i)",
i, refPoints[i].x, refPoints[i].y, points[i].x, points[i].y);
}
/* Call function and validate */
anyEnclosed = SDL_EnclosePoints((const SDL_Point *)points, numPoints, (const SDL_Rect *)NULL, &result);
SDLTest_AssertCheck(expectedEnclosed==anyEnclosed,
"Check return value %s, got %s",
(expectedEnclosed==SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE",
(anyEnclosed==SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE");
for (i=0; i<numPoints; i++) {
SDLTest_AssertCheck(refPoints[i].x==points[i].x && refPoints[i].y==points[i].y,
"Check that source point %i was not modified: expected (%i,%i) actual (%i,%i)",
i, refPoints[i].x, refPoints[i].y, points[i].x, points[i].y);
}
SDLTest_AssertCheck(result.x==minx && result.y==miny && result.w==(maxx - minx + 1) && result.h==(maxy - miny + 1),
"Resulting enclosing rectangle incorrect: expected (%i,%i - %i,%i), actual (%i,%i - %i,%i)",
minx, miny, maxx, maxy, result.x, result.y, result.x + result.w - 1, result.y + result.h - 1);
return TEST_COMPLETED;
}
/* !
* \brief Test SDL_EnclosePoints() with repeated input points
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_EnclosePoints
*/
int rect_testEnclosePointsRepeatedInput(void *arg)
{
const int numPoints = 8;
const int halfPoints = 4;
SDL_Point refPoints[8];
SDL_Point points[8];
SDL_Rect result;
SDL_bool anyEnclosed;
SDL_bool anyEnclosedNoResult;
SDL_bool expectedEnclosed = SDL_TRUE;
int newx, newy;
int minx = 0, maxx = 0, miny = 0, maxy = 0;
int i;
/* Create input data, tracking result */
for (i=0; i<numPoints; i++) {
if (i < halfPoints) {
newx = SDLTest_RandomIntegerInRange(-1024, 1024);
newy = SDLTest_RandomIntegerInRange(-1024, 1024);
} else {
newx = refPoints[i-halfPoints].x;
newy = refPoints[i-halfPoints].y;
}
refPoints[i].x = newx;
refPoints[i].y = newy;
points[i].x = newx;
points[i].y = newy;
if (i==0) {
minx = newx;
maxx = newx;
miny = newy;
maxy = newy;
} else {
if (newx < minx) minx = newx;
if (newx > maxx) maxx = newx;
if (newy < miny) miny = newy;
if (newy > maxy) maxy = newy;
}
}
/* Call function and validate - special case: no result requested */
anyEnclosedNoResult = SDL_EnclosePoints((const SDL_Point *)points, numPoints, (const SDL_Rect *)NULL, (SDL_Rect *)NULL);
SDLTest_AssertCheck(expectedEnclosed==anyEnclosedNoResult,
"Check return value %s, got %s",
(expectedEnclosed==SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE",
(anyEnclosedNoResult==SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE");
for (i=0; i<numPoints; i++) {
SDLTest_AssertCheck(refPoints[i].x==points[i].x && refPoints[i].y==points[i].y,
"Check that source point %i was not modified: expected (%i,%i) actual (%i,%i)",
i, refPoints[i].x, refPoints[i].y, points[i].x, points[i].y);
}
/* Call function and validate */
anyEnclosed = SDL_EnclosePoints((const SDL_Point *)points, numPoints, (const SDL_Rect *)NULL, &result);
SDLTest_AssertCheck(expectedEnclosed==anyEnclosed,
"Check return value %s, got %s",
(expectedEnclosed==SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE",
(anyEnclosed==SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE");
for (i=0; i<numPoints; i++) {
SDLTest_AssertCheck(refPoints[i].x==points[i].x && refPoints[i].y==points[i].y,
"Check that source point %i was not modified: expected (%i,%i) actual (%i,%i)",
i, refPoints[i].x, refPoints[i].y, points[i].x, points[i].y);
}
SDLTest_AssertCheck(result.x==minx && result.y==miny && result.w==(maxx - minx + 1) && result.h==(maxy - miny + 1),
"Check resulting enclosing rectangle: expected (%i,%i - %i,%i), actual (%i,%i - %i,%i)",
minx, miny, maxx, maxy, result.x, result.y, result.x + result.w - 1, result.y + result.h - 1);
return TEST_COMPLETED;
}
/* !
* \brief Test SDL_EnclosePoints() with clipping
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_EnclosePoints
*/
int rect_testEnclosePointsWithClipping(void *arg)
{
const int numPoints = 16;
SDL_Point refPoints[16];
SDL_Point points[16];
SDL_Rect refClip;
SDL_Rect clip;
SDL_Rect result;
SDL_bool anyEnclosed;
SDL_bool anyEnclosedNoResult;
SDL_bool expectedEnclosed = SDL_FALSE;
int newx, newy;
int minx = 0, maxx = 0, miny = 0, maxy = 0;
int i;
/* Setup clipping rectangle */
refClip.x = SDLTest_RandomIntegerInRange(-1024, 1024);
refClip.y = SDLTest_RandomIntegerInRange(-1024, 1024);
refClip.w = SDLTest_RandomIntegerInRange(1, 1024);
refClip.h = SDLTest_RandomIntegerInRange(1, 1024);
/* Create input data, tracking result */
for (i=0; i<numPoints; i++) {
newx = SDLTest_RandomIntegerInRange(-1024, 1024);
newy = SDLTest_RandomIntegerInRange(-1024, 1024);
refPoints[i].x = newx;
refPoints[i].y = newy;
points[i].x = newx;
points[i].y = newy;
if ((newx>=refClip.x) && (newx<(refClip.x + refClip.w)) &&
(newy>=refClip.y) && (newy<(refClip.y + refClip.h))) {
if (expectedEnclosed==SDL_FALSE) {
minx = newx;
maxx = newx;
miny = newy;
maxy = newy;
} else {
if (newx < minx) minx = newx;
if (newx > maxx) maxx = newx;
if (newy < miny) miny = newy;
if (newy > maxy) maxy = newy;
}
expectedEnclosed = SDL_TRUE;
}
}
/* Call function and validate - special case: no result requested */
clip = refClip;
anyEnclosedNoResult = SDL_EnclosePoints((const SDL_Point *)points, numPoints, (const SDL_Rect *)&clip, (SDL_Rect *)NULL);
SDLTest_AssertCheck(expectedEnclosed==anyEnclosedNoResult,
"Expected return value %s, got %s",
(expectedEnclosed==SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE",
(anyEnclosedNoResult==SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE");
for (i=0; i<numPoints; i++) {
SDLTest_AssertCheck(refPoints[i].x==points[i].x && refPoints[i].y==points[i].y,
"Check that source point %i was not modified: expected (%i,%i) actual (%i,%i)",
i, refPoints[i].x, refPoints[i].y, points[i].x, points[i].y);
}
SDLTest_AssertCheck(refClip.x==clip.x && refClip.y==clip.y && refClip.w==clip.w && refClip.h==clip.h,
"Check that source clipping rectangle was not modified");
/* Call function and validate */
anyEnclosed = SDL_EnclosePoints((const SDL_Point *)points, numPoints, (const SDL_Rect *)&clip, &result);
SDLTest_AssertCheck(expectedEnclosed==anyEnclosed,
"Check return value %s, got %s",
(expectedEnclosed==SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE",
(anyEnclosed==SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE");
for (i=0; i<numPoints; i++) {
SDLTest_AssertCheck(refPoints[i].x==points[i].x && refPoints[i].y==points[i].y,
"Check that source point %i was not modified: expected (%i,%i) actual (%i,%i)",
i, refPoints[i].x, refPoints[i].y, points[i].x, points[i].y);
}
SDLTest_AssertCheck(refClip.x==clip.x && refClip.y==clip.y && refClip.w==clip.w && refClip.h==clip.h,
"Check that source clipping rectangle was not modified");
if (expectedEnclosed==SDL_TRUE) {
SDLTest_AssertCheck(result.x==minx && result.y==miny && result.w==(maxx - minx + 1) && result.h==(maxy - miny + 1),
"Check resulting enclosing rectangle: expected (%i,%i - %i,%i), actual (%i,%i - %i,%i)",
minx, miny, maxx, maxy, result.x, result.y, result.x + result.w - 1, result.y + result.h - 1);
}
/* Empty clipping rectangle */
clip.w = 0;
clip.h = 0;
expectedEnclosed = SDL_FALSE;
anyEnclosed = SDL_EnclosePoints((const SDL_Point *)points, numPoints, (const SDL_Rect *)&clip, &result);
SDLTest_AssertCheck(expectedEnclosed==anyEnclosed,
"Check return value %s, got %s",
(expectedEnclosed==SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE",
(anyEnclosed==SDL_TRUE) ? "SDL_TRUE" : "SDL_FALSE");
return TEST_COMPLETED;
}
/* !
* \brief Negative tests against SDL_EnclosePoints() with invalid parameters
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_EnclosePoints
*/
int rect_testEnclosePointsParam(void *arg)
{
SDL_Point points[1];
int count;
SDL_Rect clip;
SDL_Rect result;
SDL_bool anyEnclosed;
/* invalid parameter combinations */
anyEnclosed = SDL_EnclosePoints((SDL_Point *)NULL, 1, (const SDL_Rect *)&clip, &result);
SDLTest_AssertCheck(anyEnclosed == SDL_FALSE, "Check that functions returns SDL_FALSE when 1st parameter is NULL");
anyEnclosed = SDL_EnclosePoints((const SDL_Point *)points, 0, (const SDL_Rect *)&clip, &result);
SDLTest_AssertCheck(anyEnclosed == SDL_FALSE, "Check that functions returns SDL_FALSE when 2nd parameter is 0");
count = SDLTest_RandomIntegerInRange(-100, -1);
anyEnclosed = SDL_EnclosePoints((const SDL_Point *)points, count, (const SDL_Rect *)&clip, &result);
SDLTest_AssertCheck(anyEnclosed == SDL_FALSE, "Check that functions returns SDL_FALSE when 2nd parameter is %i (negative)", count);
anyEnclosed = SDL_EnclosePoints((SDL_Point *)NULL, 0, (const SDL_Rect *)&clip, &result);
SDLTest_AssertCheck(anyEnclosed == SDL_FALSE, "Check that functions returns SDL_FALSE when 1st parameter is NULL and 2nd parameter was 0");
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_UnionRect() where rect B is outside rect A
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_UnionRect
*/
int rect_testUnionRectOutside(void *arg)
{
SDL_Rect refRectA, refRectB;
SDL_Rect rectA, rectB;
SDL_Rect expectedResult;
SDL_Rect result;
int minx, maxx, miny, maxy;
int dx, dy;
/* Union 1x1 outside */
for (dx = -1; dx < 2; dx++) {
for (dy = -1; dy < 2; dy++) {
if ((dx != 0) || (dy != 0)) {
refRectA.x=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.y=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.w=1;
refRectA.h=1;
refRectB.x=SDLTest_RandomIntegerInRange(-1024, 1024) + dx*2048;
refRectB.y=SDLTest_RandomIntegerInRange(-1024, 1024) + dx*2048;
refRectB.w=1;
refRectB.h=1;
minx = (refRectA.x<refRectB.x) ? refRectA.x : refRectB.x;
maxx = (refRectA.x>refRectB.x) ? refRectA.x : refRectB.x;
miny = (refRectA.y<refRectB.y) ? refRectA.y : refRectB.y;
maxy = (refRectA.y>refRectB.y) ? refRectA.y : refRectB.y;
expectedResult.x = minx;
expectedResult.y = miny;
expectedResult.w = maxx - minx + 1;
expectedResult.h = maxy - miny + 1;
rectA = refRectA;
rectB = refRectB;
SDL_UnionRect(&rectA, &rectB, &result);
_validateUnionRectResults(&rectA, &rectB, &refRectA, &refRectB, &result, &expectedResult);
}
}
}
/* Union outside overlap */
for (dx = -1; dx < 2; dx++) {
for (dy = -1; dy < 2; dy++) {
if ((dx != 0) || (dy != 0)) {
refRectA.x=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.y=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.w=SDLTest_RandomIntegerInRange(256, 512);
refRectA.h=SDLTest_RandomIntegerInRange(256, 512);
refRectB.x=refRectA.x + 1 + dx*2;
refRectB.y=refRectA.y + 1 + dy*2;
refRectB.w=refRectA.w - 2;
refRectB.h=refRectA.h - 2;
expectedResult = refRectA;
if (dx == -1) expectedResult.x--;
if (dy == -1) expectedResult.y--;
if ((dx == 1) || (dx == -1)) expectedResult.w++;
if ((dy == 1) || (dy == -1)) expectedResult.h++;
rectA = refRectA;
rectB = refRectB;
SDL_UnionRect(&rectA, &rectB, &result);
_validateUnionRectResults(&rectA, &rectB, &refRectA, &refRectB, &result, &expectedResult);
}
}
}
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_UnionRect() where rect A or rect B are empty
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_UnionRect
*/
int rect_testUnionRectEmpty(void *arg)
{
SDL_Rect refRectA, refRectB;
SDL_Rect rectA, rectB;
SDL_Rect expectedResult;
SDL_Rect result;
/* A empty */
refRectA.x=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.y=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.w=0;
refRectA.h=0;
refRectB.x=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectB.y=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectB.w=SDLTest_RandomIntegerInRange(1, 1024);
refRectB.h=SDLTest_RandomIntegerInRange(1, 1024);
expectedResult = refRectB;
rectA = refRectA;
rectB = refRectB;
SDL_UnionRect(&rectA, &rectB, &result);
_validateUnionRectResults(&rectA, &rectB, &refRectA, &refRectB, &result, &expectedResult);
/* B empty */
refRectA.x=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.y=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.w=SDLTest_RandomIntegerInRange(1, 1024);
refRectA.h=SDLTest_RandomIntegerInRange(1, 1024);
refRectB.x=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectB.y=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectB.w=0;
refRectB.h=0;
expectedResult = refRectA;
rectA = refRectA;
rectB = refRectB;
SDL_UnionRect(&rectA, &rectB, &result);
_validateUnionRectResults(&rectA, &rectB, &refRectA, &refRectB, &result, &expectedResult);
/* A and B empty */
refRectA.x=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.y=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.w=0;
refRectA.h=0;
refRectB.x=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectB.y=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectB.w=0;
refRectB.h=0;
result.x=0;
result.y=0;
result.w=0;
result.h=0;
expectedResult = result;
rectA = refRectA;
rectB = refRectB;
SDL_UnionRect(&rectA, &rectB, &result);
_validateUnionRectResults(&rectA, &rectB, &refRectA, &refRectB, &result, &expectedResult);
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_UnionRect() where rect B is inside rect A
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_UnionRect
*/
int rect_testUnionRectInside(void *arg)
{
SDL_Rect refRectA, refRectB;
SDL_Rect rectA, rectB;
SDL_Rect expectedResult;
SDL_Rect result;
int dx, dy;
/* Union 1x1 with itself */
refRectA.x=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.y=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.w=1;
refRectA.h=1;
expectedResult = refRectA;
rectA = refRectA;
SDL_UnionRect(&rectA, &rectA, &result);
_validateUnionRectResults(&rectA, &rectA, &refRectA, &refRectA, &result, &expectedResult);
/* Union 1x1 somewhere inside */
refRectA.x=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.y=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.w=SDLTest_RandomIntegerInRange(256, 1024);
refRectA.h=SDLTest_RandomIntegerInRange(256, 1024);
refRectB.x=refRectA.x + 1 + SDLTest_RandomIntegerInRange(1, refRectA.w - 2);
refRectB.y=refRectA.y + 1 + SDLTest_RandomIntegerInRange(1, refRectA.h - 2);
refRectB.w=1;
refRectB.h=1;
expectedResult = refRectA;
rectA = refRectA;
rectB = refRectB;
SDL_UnionRect(&rectA, &rectB, &result);
_validateUnionRectResults(&rectA, &rectB, &refRectA, &refRectB, &result, &expectedResult);
/* Union inside with edges modified */
for (dx = -1; dx < 2; dx++) {
for (dy = -1; dy < 2; dy++) {
if ((dx != 0) || (dy != 0)) {
refRectA.x=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.y=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.w=SDLTest_RandomIntegerInRange(256, 1024);
refRectA.h=SDLTest_RandomIntegerInRange(256, 1024);
refRectB = refRectA;
if (dx == -1) refRectB.x++;
if ((dx == 1) || (dx == -1)) refRectB.w--;
if (dy == -1) refRectB.y++;
if ((dy == 1) || (dy == -1)) refRectB.h--;
expectedResult = refRectA;
rectA = refRectA;
rectB = refRectB;
SDL_UnionRect(&rectA, &rectB, &result);
_validateUnionRectResults(&rectA, &rectB, &refRectA, &refRectB, &result, &expectedResult);
}
}
}
return TEST_COMPLETED;
}
/* !
* \brief Negative tests against SDL_UnionRect() with invalid parameters
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_UnionRect
*/
int rect_testUnionRectParam(void *arg)
{
SDL_Rect rectA, rectB;
SDL_Rect result;
/* invalid parameter combinations */
SDL_UnionRect((SDL_Rect *)NULL, &rectB, &result);
SDLTest_AssertPass("Check that function returns when 1st parameter is NULL");
SDL_UnionRect(&rectA, (SDL_Rect *)NULL, &result);
SDLTest_AssertPass("Check that function returns when 2nd parameter is NULL");
SDL_UnionRect(&rectA, &rectB, (SDL_Rect *)NULL);
SDLTest_AssertPass("Check that function returns when 3rd parameter is NULL");
SDL_UnionRect((SDL_Rect *)NULL, &rectB, (SDL_Rect *)NULL);
SDLTest_AssertPass("Check that function returns when 1st and 3rd parameter are NULL");
SDL_UnionRect(&rectA, (SDL_Rect *)NULL, (SDL_Rect *)NULL);
SDLTest_AssertPass("Check that function returns when 2nd and 3rd parameter are NULL");
SDL_UnionRect((SDL_Rect *)NULL, (SDL_Rect *)NULL, (SDL_Rect *)NULL);
SDLTest_AssertPass("Check that function returns when all parameters are NULL");
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_RectEmpty() with various inputs
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RectEmpty
*/
int rect_testRectEmpty(void *arg)
{
SDL_Rect refRect;
SDL_Rect rect;
SDL_bool expectedResult;
SDL_bool result;
int w, h;
/* Non-empty case */
refRect.x=SDLTest_RandomIntegerInRange(-1024, 1024);
refRect.y=SDLTest_RandomIntegerInRange(-1024, 1024);
refRect.w=SDLTest_RandomIntegerInRange(256, 1024);
refRect.h=SDLTest_RandomIntegerInRange(256, 1024);
expectedResult = SDL_FALSE;
rect = refRect;
result = (SDL_bool)SDL_RectEmpty((const SDL_Rect *)&rect);
_validateRectEmptyResults(result, expectedResult, &rect, &refRect);
/* Empty case */
for (w=-1; w<2; w++) {
for (h=-1; h<2; h++) {
if ((w != 1) || (h != 1)) {
refRect.x=SDLTest_RandomIntegerInRange(-1024, 1024);
refRect.y=SDLTest_RandomIntegerInRange(-1024, 1024);
refRect.w=w;
refRect.h=h;
expectedResult = SDL_TRUE;
rect = refRect;
result = (SDL_bool)SDL_RectEmpty((const SDL_Rect *)&rect);
_validateRectEmptyResults(result, expectedResult, &rect, &refRect);
}
}
}
return TEST_COMPLETED;
}
/* !
* \brief Negative tests against SDL_RectEmpty() with invalid parameters
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RectEmpty
*/
int rect_testRectEmptyParam(void *arg)
{
SDL_bool result;
/* invalid parameter combinations */
result = (SDL_bool)SDL_RectEmpty((const SDL_Rect *)NULL);
SDLTest_AssertCheck(result == SDL_TRUE, "Check that function returns TRUE when 1st parameter is NULL");
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_RectEquals() with various inputs
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RectEquals
*/
int rect_testRectEquals(void *arg)
{
SDL_Rect refRectA;
SDL_Rect refRectB;
SDL_Rect rectA;
SDL_Rect rectB;
SDL_bool expectedResult;
SDL_bool result;
/* Equals */
refRectA.x=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.y=SDLTest_RandomIntegerInRange(-1024, 1024);
refRectA.w=SDLTest_RandomIntegerInRange(1, 1024);
refRectA.h=SDLTest_RandomIntegerInRange(1, 1024);
refRectB = refRectA;
expectedResult = SDL_TRUE;
rectA = refRectA;
rectB = refRectB;
result = (SDL_bool)SDL_RectEquals((const SDL_Rect *)&rectA, (const SDL_Rect *)&rectB);
_validateRectEqualsResults(result, expectedResult, &rectA, &rectB, &refRectA, &refRectB);
return TEST_COMPLETED;
}
/* !
* \brief Negative tests against SDL_RectEquals() with invalid parameters
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RectEquals
*/
int rect_testRectEqualsParam(void *arg)
{
SDL_Rect rectA;
SDL_Rect rectB;
SDL_bool result;
/* data setup */
rectA.x=SDLTest_RandomIntegerInRange(-1024, 1024);
rectA.y=SDLTest_RandomIntegerInRange(-1024, 1024);
rectA.w=SDLTest_RandomIntegerInRange(1, 1024);
rectA.h=SDLTest_RandomIntegerInRange(1, 1024);
rectB.x=SDLTest_RandomIntegerInRange(-1024, 1024);
rectB.y=SDLTest_RandomIntegerInRange(-1024, 1024);
rectB.w=SDLTest_RandomIntegerInRange(1, 1024);
rectB.h=SDLTest_RandomIntegerInRange(1, 1024);
/* invalid parameter combinations */
result = (SDL_bool)SDL_RectEquals((const SDL_Rect *)NULL, (const SDL_Rect *)&rectB);
SDLTest_AssertCheck(result == SDL_FALSE, "Check that function returns SDL_FALSE when 1st parameter is NULL");
result = (SDL_bool)SDL_RectEquals((const SDL_Rect *)&rectA, (const SDL_Rect *)NULL);
SDLTest_AssertCheck(result == SDL_FALSE, "Check that function returns SDL_FALSE when 2nd parameter is NULL");
result = (SDL_bool)SDL_RectEquals((const SDL_Rect *)NULL, (const SDL_Rect *)NULL);
SDLTest_AssertCheck(result == SDL_FALSE, "Check that function returns SDL_FALSE when 1st and 2nd parameter are NULL");
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Rect test cases */
/* SDL_IntersectRectAndLine */
static const SDLTest_TestCaseReference rectTest1 =
{ (SDLTest_TestCaseFp)rect_testIntersectRectAndLine,"rect_testIntersectRectAndLine", "Tests SDL_IntersectRectAndLine clipping cases", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest2 =
{ (SDLTest_TestCaseFp)rect_testIntersectRectAndLineInside, "rect_testIntersectRectAndLineInside", "Tests SDL_IntersectRectAndLine with line fully contained in rect", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest3 =
{ (SDLTest_TestCaseFp)rect_testIntersectRectAndLineOutside, "rect_testIntersectRectAndLineOutside", "Tests SDL_IntersectRectAndLine with line fully outside of rect", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest4 =
{ (SDLTest_TestCaseFp)rect_testIntersectRectAndLineEmpty, "rect_testIntersectRectAndLineEmpty", "Tests SDL_IntersectRectAndLine with empty rectangle ", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest5 =
{ (SDLTest_TestCaseFp)rect_testIntersectRectAndLineParam, "rect_testIntersectRectAndLineParam", "Negative tests against SDL_IntersectRectAndLine with invalid parameters", TEST_ENABLED };
/* SDL_IntersectRect */
static const SDLTest_TestCaseReference rectTest6 =
{ (SDLTest_TestCaseFp)rect_testIntersectRectInside, "rect_testIntersectRectInside", "Tests SDL_IntersectRect with B fully contained in A", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest7 =
{ (SDLTest_TestCaseFp)rect_testIntersectRectOutside, "rect_testIntersectRectOutside", "Tests SDL_IntersectRect with B fully outside of A", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest8 =
{ (SDLTest_TestCaseFp)rect_testIntersectRectPartial, "rect_testIntersectRectPartial", "Tests SDL_IntersectRect with B partially intersecting A", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest9 =
{ (SDLTest_TestCaseFp)rect_testIntersectRectPoint, "rect_testIntersectRectPoint", "Tests SDL_IntersectRect with 1x1 sized rectangles", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest10 =
{ (SDLTest_TestCaseFp)rect_testIntersectRectEmpty, "rect_testIntersectRectEmpty", "Tests SDL_IntersectRect with empty rectangles", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest11 =
{ (SDLTest_TestCaseFp)rect_testIntersectRectParam, "rect_testIntersectRectParam", "Negative tests against SDL_IntersectRect with invalid parameters", TEST_ENABLED };
/* SDL_HasIntersection */
static const SDLTest_TestCaseReference rectTest12 =
{ (SDLTest_TestCaseFp)rect_testHasIntersectionInside, "rect_testHasIntersectionInside", "Tests SDL_HasIntersection with B fully contained in A", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest13 =
{ (SDLTest_TestCaseFp)rect_testHasIntersectionOutside, "rect_testHasIntersectionOutside", "Tests SDL_HasIntersection with B fully outside of A", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest14 =
{ (SDLTest_TestCaseFp)rect_testHasIntersectionPartial,"rect_testHasIntersectionPartial", "Tests SDL_HasIntersection with B partially intersecting A", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest15 =
{ (SDLTest_TestCaseFp)rect_testHasIntersectionPoint, "rect_testHasIntersectionPoint", "Tests SDL_HasIntersection with 1x1 sized rectangles", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest16 =
{ (SDLTest_TestCaseFp)rect_testHasIntersectionEmpty, "rect_testHasIntersectionEmpty", "Tests SDL_HasIntersection with empty rectangles", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest17 =
{ (SDLTest_TestCaseFp)rect_testHasIntersectionParam, "rect_testHasIntersectionParam", "Negative tests against SDL_HasIntersection with invalid parameters", TEST_ENABLED };
/* SDL_EnclosePoints */
static const SDLTest_TestCaseReference rectTest18 =
{ (SDLTest_TestCaseFp)rect_testEnclosePoints, "rect_testEnclosePoints", "Tests SDL_EnclosePoints without clipping", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest19 =
{ (SDLTest_TestCaseFp)rect_testEnclosePointsWithClipping, "rect_testEnclosePointsWithClipping", "Tests SDL_EnclosePoints with clipping", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest20 =
{ (SDLTest_TestCaseFp)rect_testEnclosePointsRepeatedInput, "rect_testEnclosePointsRepeatedInput", "Tests SDL_EnclosePoints with repeated input", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest21 =
{ (SDLTest_TestCaseFp)rect_testEnclosePointsParam, "rect_testEnclosePointsParam", "Negative tests against SDL_EnclosePoints with invalid parameters", TEST_ENABLED };
/* SDL_UnionRect */
static const SDLTest_TestCaseReference rectTest22 =
{ (SDLTest_TestCaseFp)rect_testUnionRectInside, "rect_testUnionRectInside", "Tests SDL_UnionRect where rect B is inside rect A", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest23 =
{ (SDLTest_TestCaseFp)rect_testUnionRectOutside, "rect_testUnionRectOutside", "Tests SDL_UnionRect where rect B is outside rect A", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest24 =
{ (SDLTest_TestCaseFp)rect_testUnionRectEmpty, "rect_testUnionRectEmpty", "Tests SDL_UnionRect where rect A or rect B are empty", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest25 =
{ (SDLTest_TestCaseFp)rect_testUnionRectParam, "rect_testUnionRectParam", "Negative tests against SDL_UnionRect with invalid parameters", TEST_ENABLED };
/* SDL_RectEmpty */
static const SDLTest_TestCaseReference rectTest26 =
{ (SDLTest_TestCaseFp)rect_testRectEmpty, "rect_testRectEmpty", "Tests SDL_RectEmpty with various inputs", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest27 =
{ (SDLTest_TestCaseFp)rect_testRectEmptyParam, "rect_testRectEmptyParam", "Negative tests against SDL_RectEmpty with invalid parameters", TEST_ENABLED };
/* SDL_RectEquals */
static const SDLTest_TestCaseReference rectTest28 =
{ (SDLTest_TestCaseFp)rect_testRectEquals, "rect_testRectEquals", "Tests SDL_RectEquals with various inputs", TEST_ENABLED };
static const SDLTest_TestCaseReference rectTest29 =
{ (SDLTest_TestCaseFp)rect_testRectEqualsParam, "rect_testRectEqualsParam", "Negative tests against SDL_RectEquals with invalid parameters", TEST_ENABLED };
/* !
* \brief Sequence of Rect test cases; functions that handle simple rectangles including overlaps and merges.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/CategoryRect
*/
static const SDLTest_TestCaseReference *rectTests[] = {
&rectTest1, &rectTest2, &rectTest3, &rectTest4, &rectTest5, &rectTest6, &rectTest7, &rectTest8, &rectTest9, &rectTest10, &rectTest11, &rectTest12, &rectTest13, &rectTest14,
&rectTest15, &rectTest16, &rectTest17, &rectTest18, &rectTest19, &rectTest20, &rectTest21, &rectTest22, &rectTest23, &rectTest24, &rectTest25, &rectTest26, &rectTest27,
&rectTest28, &rectTest29, NULL
};
/* Rect test suite (global) */
SDLTest_TestSuiteReference rectTestSuite = {
"Rect",
NULL,
rectTests,
NULL
};
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_rect.c | C | apache-2.0 | 67,080 |
/**
* Original code: automated SDL platform test written by Edgar Simo "bobbens"
* Extended and extensively updated by aschiffler at ferzkopp dot net
*/
#include <stdio.h>
#include "SDL.h"
#include "SDL_test.h"
/* ================= Test Case Implementation ================== */
#define TESTRENDER_SCREEN_W 80
#define TESTRENDER_SCREEN_H 60
#define RENDER_COMPARE_FORMAT SDL_PIXELFORMAT_ARGB8888
#define RENDER_COMPARE_AMASK 0xff000000 /**< Alpha bit mask. */
#define RENDER_COMPARE_RMASK 0x00ff0000 /**< Red bit mask. */
#define RENDER_COMPARE_GMASK 0x0000ff00 /**< Green bit mask. */
#define RENDER_COMPARE_BMASK 0x000000ff /**< Blue bit mask. */
#define ALLOWABLE_ERROR_OPAQUE 0
#define ALLOWABLE_ERROR_BLENDED 64
/* Test window and renderer */
SDL_Window *window = NULL;
SDL_Renderer *renderer = NULL;
/* Prototypes for helper functions */
static int _clearScreen (void);
static void _compare(SDL_Surface *reference, int allowable_error);
static int _hasTexAlpha(void);
static int _hasTexColor(void);
static SDL_Texture *_loadTestFace(void);
static int _hasBlendModes(void);
static int _hasDrawColor(void);
static int _isSupported(int code);
/**
* Create software renderer for tests
*/
void InitCreateRenderer(void *arg)
{
int posX = 100, posY = 100, width = 320, height = 240;
renderer = NULL;
window = SDL_CreateWindow("render_testCreateRenderer", posX, posY, width, height, 0);
SDLTest_AssertPass("SDL_CreateWindow()");
SDLTest_AssertCheck(window != NULL, "Check SDL_CreateWindow result");
if (window == NULL) {
return;
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDLTest_AssertPass("SDL_CreateRenderer()");
SDLTest_AssertCheck(renderer != 0, "Check SDL_CreateRenderer result");
if (renderer == NULL) {
SDL_DestroyWindow(window);
return;
}
}
/*
* Destroy renderer for tests
*/
void CleanupDestroyRenderer(void *arg)
{
if (renderer != NULL) {
SDL_DestroyRenderer(renderer);
renderer = NULL;
SDLTest_AssertPass("SDL_DestroyRenderer()");
}
if (window != NULL) {
SDL_DestroyWindow(window);
window = NULL;
SDLTest_AssertPass("SDL_DestroyWindow");
}
}
/**
* @brief Tests call to SDL_GetNumRenderDrivers
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_GetNumRenderDrivers
*/
int
render_testGetNumRenderDrivers(void *arg)
{
int n;
n = SDL_GetNumRenderDrivers();
SDLTest_AssertCheck(n >= 1, "Number of renderers >= 1, reported as %i", n);
return TEST_COMPLETED;
}
/**
* @brief Tests the SDL primitives for rendering.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_SetRenderDrawColor
* http://wiki.libsdl.org/moin.cgi/SDL_RenderFillRect
* http://wiki.libsdl.org/moin.cgi/SDL_RenderDrawLine
*
*/
int render_testPrimitives (void *arg)
{
int ret;
int x, y;
SDL_Rect rect;
SDL_Surface *referenceSurface = NULL;
int checkFailCount1;
int checkFailCount2;
/* Clear surface. */
_clearScreen();
/* Need drawcolor or just skip test. */
SDLTest_AssertCheck(_hasDrawColor(), "_hasDrawColor");
/* Draw a rectangle. */
rect.x = 40;
rect.y = 0;
rect.w = 40;
rect.h = 80;
ret = SDL_SetRenderDrawColor(renderer, 13, 73, 200, SDL_ALPHA_OPAQUE );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret);
ret = SDL_RenderFillRect(renderer, &rect );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderFillRect, expected: 0, got: %i", ret);
/* Draw a rectangle. */
rect.x = 10;
rect.y = 10;
rect.w = 60;
rect.h = 40;
ret = SDL_SetRenderDrawColor(renderer, 200, 0, 100, SDL_ALPHA_OPAQUE );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret);
ret = SDL_RenderFillRect(renderer, &rect );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderFillRect, expected: 0, got: %i", ret);
/* Draw some points like so:
* X.X.X.X..
* .X.X.X.X.
* X.X.X.X.. */
checkFailCount1 = 0;
checkFailCount2 = 0;
for (y=0; y<3; y++) {
for (x = y % 2; x<TESTRENDER_SCREEN_W; x+=2) {
ret = SDL_SetRenderDrawColor(renderer, x*y, x*y/2, x*y/3, SDL_ALPHA_OPAQUE );
if (ret != 0) checkFailCount1++;
ret = SDL_RenderDrawPoint(renderer, x, y );
if (ret != 0) checkFailCount2++;
}
}
SDLTest_AssertCheck(checkFailCount1 == 0, "Validate results from calls to SDL_SetRenderDrawColor, expected: 0, got: %i", checkFailCount1);
SDLTest_AssertCheck(checkFailCount2 == 0, "Validate results from calls to SDL_RenderDrawPoint, expected: 0, got: %i", checkFailCount2);
/* Draw some lines. */
ret = SDL_SetRenderDrawColor(renderer, 0, 255, 0, SDL_ALPHA_OPAQUE );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor");
ret = SDL_RenderDrawLine(renderer, 0, 30, TESTRENDER_SCREEN_W, 30 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderDrawLine, expected: 0, got: %i", ret);
ret = SDL_SetRenderDrawColor(renderer, 55, 55, 5, SDL_ALPHA_OPAQUE );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret);
ret = SDL_RenderDrawLine(renderer, 40, 30, 40, 60 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderDrawLine, expected: 0, got: %i", ret);
ret = SDL_SetRenderDrawColor(renderer, 5, 105, 105, SDL_ALPHA_OPAQUE );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret);
ret = SDL_RenderDrawLine(renderer, 0, 0, 29, 29 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderDrawLine, expected: 0, got: %i", ret);
ret = SDL_RenderDrawLine(renderer, 29, 30, 0, 59 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderDrawLine, expected: 0, got: %i", ret);
ret = SDL_RenderDrawLine(renderer, 79, 0, 50, 29 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderDrawLine, expected: 0, got: %i", ret);
ret = SDL_RenderDrawLine(renderer, 79, 59, 50, 30 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderDrawLine, expected: 0, got: %i", ret);
/* Make current */
SDL_RenderPresent(renderer);
/* See if it's the same. */
referenceSurface = SDLTest_ImagePrimitives();
_compare(referenceSurface, ALLOWABLE_ERROR_OPAQUE );
/* Clean up. */
SDL_FreeSurface(referenceSurface);
referenceSurface = NULL;
return TEST_COMPLETED;
}
/**
* @brief Tests the SDL primitives with alpha for rendering.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_SetRenderDrawColor
* http://wiki.libsdl.org/moin.cgi/SDL_SetRenderDrawBlendMode
* http://wiki.libsdl.org/moin.cgi/SDL_RenderFillRect
*/
int render_testPrimitivesBlend (void *arg)
{
int ret;
int i, j;
SDL_Rect rect;
SDL_Surface *referenceSurface = NULL;
int checkFailCount1;
int checkFailCount2;
int checkFailCount3;
/* Clear surface. */
_clearScreen();
/* Need drawcolor and blendmode or just skip test. */
SDLTest_AssertCheck(_hasDrawColor(), "_hasDrawColor");
SDLTest_AssertCheck(_hasBlendModes(), "_hasBlendModes");
/* Create some rectangles for each blend mode. */
ret = SDL_SetRenderDrawColor(renderer, 255, 255, 255, 0 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret);
ret = SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_NONE );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawBlendMode, expected: 0, got: %i", ret);
ret = SDL_RenderFillRect(renderer, NULL );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderFillRect, expected: 0, got: %i", ret);
rect.x = 10;
rect.y = 25;
rect.w = 40;
rect.h = 25;
ret = SDL_SetRenderDrawColor(renderer, 240, 10, 10, 75 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret);
ret = SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_ADD );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawBlendMode, expected: 0, got: %i", ret);
ret = SDL_RenderFillRect(renderer, &rect );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderFillRect, expected: 0, got: %i", ret);
rect.x = 30;
rect.y = 40;
rect.w = 45;
rect.h = 15;
ret = SDL_SetRenderDrawColor(renderer, 10, 240, 10, 100 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret);
ret = SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawBlendMode, expected: 0, got: %i", ret);
ret = SDL_RenderFillRect(renderer, &rect );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderFillRect, expected: 0, got: %i", ret);
rect.x = 25;
rect.y = 25;
rect.w = 25;
rect.h = 25;
ret = SDL_SetRenderDrawColor(renderer, 10, 10, 240, 125 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret);
ret = SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_NONE );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawBlendMode, expected: 0, got: %i", ret);
ret = SDL_RenderFillRect(renderer, &rect );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderFillRect, expected: 0, got: %i", ret);
/* Draw blended lines, lines for everyone. */
checkFailCount1 = 0;
checkFailCount2 = 0;
checkFailCount3 = 0;
for (i=0; i<TESTRENDER_SCREEN_W; i+=2) {
ret = SDL_SetRenderDrawColor(renderer, 60+2*i, 240-2*i, 50, 3*i );
if (ret != 0) checkFailCount1++;
ret = SDL_SetRenderDrawBlendMode(renderer,(((i/2)%3)==0) ? SDL_BLENDMODE_BLEND :
(((i/2)%3)==1) ? SDL_BLENDMODE_ADD : SDL_BLENDMODE_NONE );
if (ret != 0) checkFailCount2++;
ret = SDL_RenderDrawLine(renderer, 0, 0, i, 59 );
if (ret != 0) checkFailCount3++;
}
SDLTest_AssertCheck(checkFailCount1 == 0, "Validate results from calls to SDL_SetRenderDrawColor, expected: 0, got: %i", checkFailCount1);
SDLTest_AssertCheck(checkFailCount2 == 0, "Validate results from calls to SDL_SetRenderDrawBlendMode, expected: 0, got: %i", checkFailCount2);
SDLTest_AssertCheck(checkFailCount3 == 0, "Validate results from calls to SDL_RenderDrawLine, expected: 0, got: %i", checkFailCount3);
checkFailCount1 = 0;
checkFailCount2 = 0;
checkFailCount3 = 0;
for (i=0; i<TESTRENDER_SCREEN_H; i+=2) {
ret = SDL_SetRenderDrawColor(renderer, 60+2*i, 240-2*i, 50, 3*i );
if (ret != 0) checkFailCount1++;
ret = SDL_SetRenderDrawBlendMode(renderer,(((i/2)%3)==0) ? SDL_BLENDMODE_BLEND :
(((i/2)%3)==1) ? SDL_BLENDMODE_ADD : SDL_BLENDMODE_NONE );
if (ret != 0) checkFailCount2++;
ret = SDL_RenderDrawLine(renderer, 0, 0, 79, i );
if (ret != 0) checkFailCount3++;
}
SDLTest_AssertCheck(checkFailCount1 == 0, "Validate results from calls to SDL_SetRenderDrawColor, expected: 0, got: %i", checkFailCount1);
SDLTest_AssertCheck(checkFailCount2 == 0, "Validate results from calls to SDL_SetRenderDrawBlendMode, expected: 0, got: %i", checkFailCount2);
SDLTest_AssertCheck(checkFailCount3 == 0, "Validate results from calls to SDL_RenderDrawLine, expected: 0, got: %i", checkFailCount3);
/* Draw points. */
checkFailCount1 = 0;
checkFailCount2 = 0;
checkFailCount3 = 0;
for (j=0; j<TESTRENDER_SCREEN_H; j+=3) {
for (i=0; i<TESTRENDER_SCREEN_W; i+=3) {
ret = SDL_SetRenderDrawColor(renderer, j*4, i*3, j*4, i*3 );
if (ret != 0) checkFailCount1++;
ret = SDL_SetRenderDrawBlendMode(renderer, ((((i+j)/3)%3)==0) ? SDL_BLENDMODE_BLEND :
((((i+j)/3)%3)==1) ? SDL_BLENDMODE_ADD : SDL_BLENDMODE_NONE );
if (ret != 0) checkFailCount2++;
ret = SDL_RenderDrawPoint(renderer, i, j );
if (ret != 0) checkFailCount3++;
}
}
SDLTest_AssertCheck(checkFailCount1 == 0, "Validate results from calls to SDL_SetRenderDrawColor, expected: 0, got: %i", checkFailCount1);
SDLTest_AssertCheck(checkFailCount2 == 0, "Validate results from calls to SDL_SetRenderDrawBlendMode, expected: 0, got: %i", checkFailCount2);
SDLTest_AssertCheck(checkFailCount3 == 0, "Validate results from calls to SDL_RenderDrawPoint, expected: 0, got: %i", checkFailCount3);
/* Make current */
SDL_RenderPresent(renderer);
/* See if it's the same. */
referenceSurface = SDLTest_ImagePrimitivesBlend();
_compare(referenceSurface, ALLOWABLE_ERROR_BLENDED );
/* Clean up. */
SDL_FreeSurface(referenceSurface);
referenceSurface = NULL;
return TEST_COMPLETED;
}
/**
* @brief Tests some blitting routines.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RenderCopy
* http://wiki.libsdl.org/moin.cgi/SDL_DestroyTexture
*/
int
render_testBlit(void *arg)
{
int ret;
SDL_Rect rect;
SDL_Texture *tface;
SDL_Surface *referenceSurface = NULL;
Uint32 tformat;
int taccess, tw, th;
int i, j, ni, nj;
int checkFailCount1;
/* Clear surface. */
_clearScreen();
/* Need drawcolor or just skip test. */
SDLTest_AssertCheck(_hasDrawColor(), "_hasDrawColor)");
/* Create face surface. */
tface = _loadTestFace();
SDLTest_AssertCheck(tface != NULL, "Verify _loadTestFace() result");
if (tface == NULL) {
return TEST_ABORTED;
}
/* Constant values. */
ret = SDL_QueryTexture(tface, &tformat, &taccess, &tw, &th);
SDLTest_AssertCheck(ret == 0, "Verify result from SDL_QueryTexture, expected 0, got %i", ret);
rect.w = tw;
rect.h = th;
ni = TESTRENDER_SCREEN_W - tw;
nj = TESTRENDER_SCREEN_H - th;
/* Loop blit. */
checkFailCount1 = 0;
for (j=0; j <= nj; j+=4) {
for (i=0; i <= ni; i+=4) {
/* Blitting. */
rect.x = i;
rect.y = j;
ret = SDL_RenderCopy(renderer, tface, NULL, &rect );
if (ret != 0) checkFailCount1++;
}
}
SDLTest_AssertCheck(checkFailCount1 == 0, "Validate results from calls to SDL_RenderCopy, expected: 0, got: %i", checkFailCount1);
/* Make current */
SDL_RenderPresent(renderer);
/* See if it's the same */
referenceSurface = SDLTest_ImageBlit();
_compare(referenceSurface, ALLOWABLE_ERROR_OPAQUE );
/* Clean up. */
SDL_DestroyTexture( tface );
SDL_FreeSurface(referenceSurface);
referenceSurface = NULL;
return TEST_COMPLETED;
}
/**
* @brief Blits doing color tests.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_SetTextureColorMod
* http://wiki.libsdl.org/moin.cgi/SDL_RenderCopy
* http://wiki.libsdl.org/moin.cgi/SDL_DestroyTexture
*/
int
render_testBlitColor (void *arg)
{
int ret;
SDL_Rect rect;
SDL_Texture *tface;
SDL_Surface *referenceSurface = NULL;
Uint32 tformat;
int taccess, tw, th;
int i, j, ni, nj;
int checkFailCount1;
int checkFailCount2;
/* Clear surface. */
_clearScreen();
/* Create face surface. */
tface = _loadTestFace();
SDLTest_AssertCheck(tface != NULL, "Verify _loadTestFace() result");
if (tface == NULL) {
return TEST_ABORTED;
}
/* Constant values. */
ret = SDL_QueryTexture(tface, &tformat, &taccess, &tw, &th);
SDLTest_AssertCheck(ret == 0, "Verify result from SDL_QueryTexture, expected 0, got %i", ret);
rect.w = tw;
rect.h = th;
ni = TESTRENDER_SCREEN_W - tw;
nj = TESTRENDER_SCREEN_H - th;
/* Test blitting with color mod. */
checkFailCount1 = 0;
checkFailCount2 = 0;
for (j=0; j <= nj; j+=4) {
for (i=0; i <= ni; i+=4) {
/* Set color mod. */
ret = SDL_SetTextureColorMod( tface, (255/nj)*j, (255/ni)*i, (255/nj)*j );
if (ret != 0) checkFailCount1++;
/* Blitting. */
rect.x = i;
rect.y = j;
ret = SDL_RenderCopy(renderer, tface, NULL, &rect );
if (ret != 0) checkFailCount2++;
}
}
SDLTest_AssertCheck(checkFailCount1 == 0, "Validate results from calls to SDL_SetTextureColorMod, expected: 0, got: %i", checkFailCount1);
SDLTest_AssertCheck(checkFailCount2 == 0, "Validate results from calls to SDL_RenderCopy, expected: 0, got: %i", checkFailCount2);
/* Make current */
SDL_RenderPresent(renderer);
/* See if it's the same. */
referenceSurface = SDLTest_ImageBlitColor();
_compare(referenceSurface, ALLOWABLE_ERROR_OPAQUE );
/* Clean up. */
SDL_DestroyTexture( tface );
SDL_FreeSurface(referenceSurface);
referenceSurface = NULL;
return TEST_COMPLETED;
}
/**
* @brief Tests blitting with alpha.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_SetTextureAlphaMod
* http://wiki.libsdl.org/moin.cgi/SDL_RenderCopy
* http://wiki.libsdl.org/moin.cgi/SDL_DestroyTexture
*/
int
render_testBlitAlpha (void *arg)
{
int ret;
SDL_Rect rect;
SDL_Texture *tface;
SDL_Surface *referenceSurface = NULL;
Uint32 tformat;
int taccess, tw, th;
int i, j, ni, nj;
int checkFailCount1;
int checkFailCount2;
/* Clear surface. */
_clearScreen();
/* Need alpha or just skip test. */
SDLTest_AssertCheck(_hasTexAlpha(), "_hasTexAlpha");
/* Create face surface. */
tface = _loadTestFace();
SDLTest_AssertCheck(tface != NULL, "Verify _loadTestFace() result");
if (tface == NULL) {
return TEST_ABORTED;
}
/* Constant values. */
ret = SDL_QueryTexture(tface, &tformat, &taccess, &tw, &th);
SDLTest_AssertCheck(ret == 0, "Verify result from SDL_QueryTexture, expected 0, got %i", ret);
rect.w = tw;
rect.h = th;
ni = TESTRENDER_SCREEN_W - tw;
nj = TESTRENDER_SCREEN_H - th;
/* Test blitting with alpha mod. */
checkFailCount1 = 0;
checkFailCount2 = 0;
for (j=0; j <= nj; j+=4) {
for (i=0; i <= ni; i+=4) {
/* Set alpha mod. */
ret = SDL_SetTextureAlphaMod( tface, (255/ni)*i );
if (ret != 0) checkFailCount1++;
/* Blitting. */
rect.x = i;
rect.y = j;
ret = SDL_RenderCopy(renderer, tface, NULL, &rect );
if (ret != 0) checkFailCount2++;
}
}
SDLTest_AssertCheck(checkFailCount1 == 0, "Validate results from calls to SDL_SetTextureAlphaMod, expected: 0, got: %i", checkFailCount1);
SDLTest_AssertCheck(checkFailCount2 == 0, "Validate results from calls to SDL_RenderCopy, expected: 0, got: %i", checkFailCount2);
/* Make current */
SDL_RenderPresent(renderer);
/* See if it's the same. */
referenceSurface = SDLTest_ImageBlitAlpha();
_compare(referenceSurface, ALLOWABLE_ERROR_BLENDED );
/* Clean up. */
SDL_DestroyTexture( tface );
SDL_FreeSurface(referenceSurface);
referenceSurface = NULL;
return TEST_COMPLETED;
}
/* Helper functions */
/**
* @brief Tests a blend mode.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_SetTextureBlendMode
* http://wiki.libsdl.org/moin.cgi/SDL_RenderCopy
*/
static void
_testBlitBlendMode( SDL_Texture * tface, int mode )
{
int ret;
Uint32 tformat;
int taccess, tw, th;
int i, j, ni, nj;
SDL_Rect rect;
int checkFailCount1;
int checkFailCount2;
/* Clear surface. */
_clearScreen();
/* Constant values. */
ret = SDL_QueryTexture(tface, &tformat, &taccess, &tw, &th);
SDLTest_AssertCheck(ret == 0, "Verify result from SDL_QueryTexture, expected 0, got %i", ret);
rect.w = tw;
rect.h = th;
ni = TESTRENDER_SCREEN_W - tw;
nj = TESTRENDER_SCREEN_H - th;
/* Test blend mode. */
checkFailCount1 = 0;
checkFailCount2 = 0;
for (j=0; j <= nj; j+=4) {
for (i=0; i <= ni; i+=4) {
/* Set blend mode. */
ret = SDL_SetTextureBlendMode( tface, (SDL_BlendMode)mode );
if (ret != 0) checkFailCount1++;
/* Blitting. */
rect.x = i;
rect.y = j;
ret = SDL_RenderCopy(renderer, tface, NULL, &rect );
if (ret != 0) checkFailCount2++;
}
}
SDLTest_AssertCheck(checkFailCount1 == 0, "Validate results from calls to SDL_SetTextureBlendMode, expected: 0, got: %i", checkFailCount1);
SDLTest_AssertCheck(checkFailCount2 == 0, "Validate results from calls to SDL_RenderCopy, expected: 0, got: %i", checkFailCount2);
}
/**
* @brief Tests some more blitting routines.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_SetTextureColorMod
* http://wiki.libsdl.org/moin.cgi/SDL_SetTextureAlphaMod
* http://wiki.libsdl.org/moin.cgi/SDL_SetTextureBlendMode
* http://wiki.libsdl.org/moin.cgi/SDL_DestroyTexture
*/
int
render_testBlitBlend (void *arg)
{
int ret;
SDL_Rect rect;
SDL_Texture *tface;
SDL_Surface *referenceSurface = NULL;
Uint32 tformat;
int taccess, tw, th;
int i, j, ni, nj;
int mode;
int checkFailCount1;
int checkFailCount2;
int checkFailCount3;
int checkFailCount4;
SDLTest_AssertCheck(_hasBlendModes(), "_hasBlendModes");
SDLTest_AssertCheck(_hasTexColor(), "_hasTexColor");
SDLTest_AssertCheck(_hasTexAlpha(), "_hasTexAlpha");
/* Create face surface. */
tface = _loadTestFace();
SDLTest_AssertCheck(tface != NULL, "Verify _loadTestFace() result");
if (tface == NULL) {
return TEST_ABORTED;
}
/* Constant values. */
ret = SDL_QueryTexture(tface, &tformat, &taccess, &tw, &th);
SDLTest_AssertCheck(ret == 0, "Verify result from SDL_QueryTexture, expected 0, got %i", ret);
rect.w = tw;
rect.h = th;
ni = TESTRENDER_SCREEN_W - tw;
nj = TESTRENDER_SCREEN_H - th;
/* Set alpha mod. */
ret = SDL_SetTextureAlphaMod( tface, 100 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetTextureAlphaMod, expected: 0, got: %i", ret);
/* Test None. */
_testBlitBlendMode( tface, SDL_BLENDMODE_NONE );
referenceSurface = SDLTest_ImageBlitBlendNone();
/* Make current and compare */
SDL_RenderPresent(renderer);
_compare(referenceSurface, ALLOWABLE_ERROR_OPAQUE );
SDL_FreeSurface(referenceSurface);
referenceSurface = NULL;
/* Test Blend. */
_testBlitBlendMode( tface, SDL_BLENDMODE_BLEND );
referenceSurface = SDLTest_ImageBlitBlend();
/* Make current and compare */
SDL_RenderPresent(renderer);
_compare(referenceSurface, ALLOWABLE_ERROR_BLENDED );
SDL_FreeSurface(referenceSurface);
referenceSurface = NULL;
/* Test Add. */
_testBlitBlendMode( tface, SDL_BLENDMODE_ADD );
referenceSurface = SDLTest_ImageBlitBlendAdd();
/* Make current and compare */
SDL_RenderPresent(renderer);
_compare(referenceSurface, ALLOWABLE_ERROR_BLENDED );
SDL_FreeSurface(referenceSurface);
referenceSurface = NULL;
/* Test Mod. */
_testBlitBlendMode( tface, SDL_BLENDMODE_MOD);
referenceSurface = SDLTest_ImageBlitBlendMod();
/* Make current and compare */
SDL_RenderPresent(renderer);
_compare(referenceSurface, ALLOWABLE_ERROR_BLENDED );
SDL_FreeSurface(referenceSurface);
referenceSurface = NULL;
/* Clear surface. */
_clearScreen();
/* Loop blit. */
checkFailCount1 = 0;
checkFailCount2 = 0;
checkFailCount3 = 0;
checkFailCount4 = 0;
for (j=0; j <= nj; j+=4) {
for (i=0; i <= ni; i+=4) {
/* Set color mod. */
ret = SDL_SetTextureColorMod( tface, (255/nj)*j, (255/ni)*i, (255/nj)*j );
if (ret != 0) checkFailCount1++;
/* Set alpha mod. */
ret = SDL_SetTextureAlphaMod( tface, (100/ni)*i );
if (ret != 0) checkFailCount2++;
/* Crazy blending mode magic. */
mode = (i/4*j/4) % 4;
if (mode==0) mode = SDL_BLENDMODE_NONE;
else if (mode==1) mode = SDL_BLENDMODE_BLEND;
else if (mode==2) mode = SDL_BLENDMODE_ADD;
else if (mode==3) mode = SDL_BLENDMODE_MOD;
ret = SDL_SetTextureBlendMode( tface, (SDL_BlendMode)mode );
if (ret != 0) checkFailCount3++;
/* Blitting. */
rect.x = i;
rect.y = j;
ret = SDL_RenderCopy(renderer, tface, NULL, &rect );
if (ret != 0) checkFailCount4++;
}
}
SDLTest_AssertCheck(checkFailCount1 == 0, "Validate results from calls to SDL_SetTextureColorMod, expected: 0, got: %i", checkFailCount1);
SDLTest_AssertCheck(checkFailCount2 == 0, "Validate results from calls to SDL_SetTextureAlphaMod, expected: 0, got: %i", checkFailCount2);
SDLTest_AssertCheck(checkFailCount3 == 0, "Validate results from calls to SDL_SetTextureBlendMode, expected: 0, got: %i", checkFailCount3);
SDLTest_AssertCheck(checkFailCount4 == 0, "Validate results from calls to SDL_RenderCopy, expected: 0, got: %i", checkFailCount4);
/* Clean up. */
SDL_DestroyTexture( tface );
/* Make current */
SDL_RenderPresent(renderer);
/* Check to see if final image matches. */
referenceSurface = SDLTest_ImageBlitBlendAll();
_compare(referenceSurface, ALLOWABLE_ERROR_BLENDED);
SDL_FreeSurface(referenceSurface);
referenceSurface = NULL;
return TEST_COMPLETED;
}
/**
* @brief Checks to see if functionality is supported. Helper function.
*/
static int
_isSupported( int code )
{
return (code == 0);
}
/**
* @brief Test to see if we can vary the draw color. Helper function.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_SetRenderDrawColor
* http://wiki.libsdl.org/moin.cgi/SDL_GetRenderDrawColor
*/
static int
_hasDrawColor (void)
{
int ret, fail;
Uint8 r, g, b, a;
fail = 0;
/* Set color. */
ret = SDL_SetRenderDrawColor(renderer, 100, 100, 100, 100 );
if (!_isSupported(ret))
fail = 1;
ret = SDL_GetRenderDrawColor(renderer, &r, &g, &b, &a );
if (!_isSupported(ret))
fail = 1;
/* Restore natural. */
ret = SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE );
if (!_isSupported(ret))
fail = 1;
/* Something failed, consider not available. */
if (fail)
return 0;
/* Not set properly, consider failed. */
else if ((r != 100) || (g != 100) || (b != 100) || (a != 100))
return 0;
return 1;
}
/**
* @brief Test to see if we can vary the blend mode. Helper function.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_SetRenderDrawBlendMode
* http://wiki.libsdl.org/moin.cgi/SDL_GetRenderDrawBlendMode
*/
static int
_hasBlendModes (void)
{
int fail;
int ret;
SDL_BlendMode mode;
fail = 0;
ret = SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND );
if (!_isSupported(ret))
fail = 1;
ret = SDL_GetRenderDrawBlendMode(renderer, &mode );
if (!_isSupported(ret))
fail = 1;
ret = (mode != SDL_BLENDMODE_BLEND);
if (!_isSupported(ret))
fail = 1;
ret = SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_ADD );
if (!_isSupported(ret))
fail = 1;
ret = SDL_GetRenderDrawBlendMode(renderer, &mode );
if (!_isSupported(ret))
fail = 1;
ret = (mode != SDL_BLENDMODE_ADD);
if (!_isSupported(ret))
fail = 1;
ret = SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_MOD );
if (!_isSupported(ret))
fail = 1;
ret = SDL_GetRenderDrawBlendMode(renderer, &mode );
if (!_isSupported(ret))
fail = 1;
ret = (mode != SDL_BLENDMODE_MOD);
if (!_isSupported(ret))
fail = 1;
ret = SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_NONE );
if (!_isSupported(ret))
fail = 1;
ret = SDL_GetRenderDrawBlendMode(renderer, &mode );
if (!_isSupported(ret))
fail = 1;
ret = (mode != SDL_BLENDMODE_NONE);
if (!_isSupported(ret))
fail = 1;
return !fail;
}
/**
* @brief Loads the test image 'Face' as texture. Helper function.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_CreateTextureFromSurface
*/
static SDL_Texture *
_loadTestFace(void)
{
SDL_Surface *face;
SDL_Texture *tface;
face = SDLTest_ImageFace();
if (face == NULL) {
return NULL;
}
tface = SDL_CreateTextureFromSurface(renderer, face);
if (tface == NULL) {
SDLTest_LogError("SDL_CreateTextureFromSurface() failed with error: %s", SDL_GetError());
}
SDL_FreeSurface(face);
return tface;
}
/**
* @brief Test to see if can set texture color mode. Helper function.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_SetTextureColorMod
* http://wiki.libsdl.org/moin.cgi/SDL_GetTextureColorMod
* http://wiki.libsdl.org/moin.cgi/SDL_DestroyTexture
*/
static int
_hasTexColor (void)
{
int fail;
int ret;
SDL_Texture *tface;
Uint8 r, g, b;
/* Get test face. */
tface = _loadTestFace();
if (tface == NULL)
return 0;
/* See if supported. */
fail = 0;
ret = SDL_SetTextureColorMod( tface, 100, 100, 100 );
if (!_isSupported(ret))
fail = 1;
ret = SDL_GetTextureColorMod( tface, &r, &g, &b );
if (!_isSupported(ret))
fail = 1;
/* Clean up. */
SDL_DestroyTexture( tface );
if (fail)
return 0;
else if ((r != 100) || (g != 100) || (b != 100))
return 0;
return 1;
}
/**
* @brief Test to see if we can vary the alpha of the texture. Helper function.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_SetTextureAlphaMod
* http://wiki.libsdl.org/moin.cgi/SDL_GetTextureAlphaMod
* http://wiki.libsdl.org/moin.cgi/SDL_DestroyTexture
*/
static int
_hasTexAlpha(void)
{
int fail;
int ret;
SDL_Texture *tface;
Uint8 a;
/* Get test face. */
tface = _loadTestFace();
if (tface == NULL)
return 0;
/* See if supported. */
fail = 0;
ret = SDL_SetTextureAlphaMod( tface, 100 );
if (!_isSupported(ret))
fail = 1;
ret = SDL_GetTextureAlphaMod( tface, &a );
if (!_isSupported(ret))
fail = 1;
/* Clean up. */
SDL_DestroyTexture( tface );
if (fail)
return 0;
else if (a != 100)
return 0;
return 1;
}
/**
* @brief Compares screen pixels with image pixels. Helper function.
*
* @param s Image to compare against.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RenderReadPixels
* http://wiki.libsdl.org/moin.cgi/SDL_CreateRGBSurfaceFrom
* http://wiki.libsdl.org/moin.cgi/SDL_FreeSurface
*/
static void
_compare(SDL_Surface *referenceSurface, int allowable_error)
{
int result;
SDL_Rect rect;
Uint8 *pixels;
SDL_Surface *testSurface;
/* Read pixels. */
pixels = (Uint8 *)SDL_malloc(4*TESTRENDER_SCREEN_W*TESTRENDER_SCREEN_H);
SDLTest_AssertCheck(pixels != NULL, "Validate allocated temp pixel buffer");
if (pixels == NULL) return;
/* Explicitly specify the rect in case the window isn't the expected size... */
rect.x = 0;
rect.y = 0;
rect.w = TESTRENDER_SCREEN_W;
rect.h = TESTRENDER_SCREEN_H;
result = SDL_RenderReadPixels(renderer, &rect, RENDER_COMPARE_FORMAT, pixels, 80*4 );
SDLTest_AssertCheck(result == 0, "Validate result from SDL_RenderReadPixels, expected: 0, got: %i", result);
/* Create surface. */
testSurface = SDL_CreateRGBSurfaceFrom(pixels, TESTRENDER_SCREEN_W, TESTRENDER_SCREEN_H, 32, TESTRENDER_SCREEN_W*4,
RENDER_COMPARE_RMASK, RENDER_COMPARE_GMASK, RENDER_COMPARE_BMASK, RENDER_COMPARE_AMASK);
SDLTest_AssertCheck(testSurface != NULL, "Verify result from SDL_CreateRGBSurfaceFrom is not NULL");
/* Compare surface. */
result = SDLTest_CompareSurfaces( testSurface, referenceSurface, allowable_error );
SDLTest_AssertCheck(result == 0, "Validate result from SDLTest_CompareSurfaces, expected: 0, got: %i", result);
/* Clean up. */
SDL_free(pixels);
SDL_FreeSurface(testSurface);
}
/**
* @brief Clears the screen. Helper function.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_SetRenderDrawColor
* http://wiki.libsdl.org/moin.cgi/SDL_RenderClear
* http://wiki.libsdl.org/moin.cgi/SDL_RenderPresent
* http://wiki.libsdl.org/moin.cgi/SDL_SetRenderDrawBlendMode
*/
static int
_clearScreen(void)
{
int ret;
/* Set color. */
ret = SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret);
/* Clear screen. */
ret = SDL_RenderClear(renderer);
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_RenderClear, expected: 0, got: %i", ret);
/* Make current */
SDL_RenderPresent(renderer);
/* Set defaults. */
ret = SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_NONE );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawBlendMode, expected: 0, got: %i", ret);
ret = SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE );
SDLTest_AssertCheck(ret == 0, "Validate result from SDL_SetRenderDrawColor, expected: 0, got: %i", ret);
return 0;
}
/* ================= Test References ================== */
/* Render test cases */
static const SDLTest_TestCaseReference renderTest1 =
{ (SDLTest_TestCaseFp)render_testGetNumRenderDrivers, "render_testGetNumRenderDrivers", "Tests call to SDL_GetNumRenderDrivers", TEST_ENABLED };
static const SDLTest_TestCaseReference renderTest2 =
{ (SDLTest_TestCaseFp)render_testPrimitives, "render_testPrimitives", "Tests rendering primitives", TEST_ENABLED };
/* TODO: rewrite test case, define new test data and re-enable; current implementation fails */
static const SDLTest_TestCaseReference renderTest3 =
{ (SDLTest_TestCaseFp)render_testPrimitivesBlend, "render_testPrimitivesBlend", "Tests rendering primitives with blending", TEST_DISABLED };
static const SDLTest_TestCaseReference renderTest4 =
{ (SDLTest_TestCaseFp)render_testBlit, "render_testBlit", "Tests blitting", TEST_ENABLED };
static const SDLTest_TestCaseReference renderTest5 =
{ (SDLTest_TestCaseFp)render_testBlitColor, "render_testBlitColor", "Tests blitting with color", TEST_ENABLED };
/* TODO: rewrite test case, define new test data and re-enable; current implementation fails */
static const SDLTest_TestCaseReference renderTest6 =
{ (SDLTest_TestCaseFp)render_testBlitAlpha, "render_testBlitAlpha", "Tests blitting with alpha", TEST_DISABLED };
/* TODO: rewrite test case, define new test data and re-enable; current implementation fails */
static const SDLTest_TestCaseReference renderTest7 =
{ (SDLTest_TestCaseFp)render_testBlitBlend, "render_testBlitBlend", "Tests blitting with blending", TEST_DISABLED };
/* Sequence of Render test cases */
static const SDLTest_TestCaseReference *renderTests[] = {
&renderTest1, &renderTest2, &renderTest3, &renderTest4, &renderTest5, &renderTest6, &renderTest7, NULL
};
/* Render test suite (global) */
SDLTest_TestSuiteReference renderTestSuite = {
"Render",
InitCreateRenderer,
renderTests,
CleanupDestroyRenderer
};
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_render.c | C | apache-2.0 | 34,596 |
/**
* Automated SDL_RWops test.
*
* Original code written by Edgar Simo "bobbens"
* Ported by Markus Kauppila (markus.kauppila@gmail.com)
* Updated and extended for SDL_test by aschiffler at ferzkopp dot net
*
* Released under Public Domain.
*/
/* quiet windows compiler warnings */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include "SDL.h"
#include "SDL_test.h"
/* ================= Test Case Implementation ================== */
const char* RWopsReadTestFilename = "rwops_read";
const char* RWopsWriteTestFilename = "rwops_write";
const char* RWopsAlphabetFilename = "rwops_alphabet";
static const char RWopsHelloWorldTestString[] = "Hello World!";
static const char RWopsHelloWorldCompString[] = "Hello World!";
static const char RWopsAlphabetString[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/* Fixture */
void
RWopsSetUp(void *arg)
{
size_t fileLen;
FILE *handle;
size_t writtenLen;
int result;
/* Clean up from previous runs (if any); ignore errors */
remove(RWopsReadTestFilename);
remove(RWopsWriteTestFilename);
remove(RWopsAlphabetFilename);
/* Create a test file */
handle = fopen(RWopsReadTestFilename, "w");
SDLTest_AssertCheck(handle != NULL, "Verify creation of file '%s' returned non NULL handle", RWopsReadTestFilename);
if (handle == NULL) return;
/* Write some known text into it */
fileLen = SDL_strlen(RWopsHelloWorldTestString);
writtenLen = fwrite(RWopsHelloWorldTestString, 1, fileLen, handle);
SDLTest_AssertCheck(fileLen == writtenLen, "Verify number of written bytes, expected %i, got %i", (int) fileLen, (int) writtenLen);
result = fclose(handle);
SDLTest_AssertCheck(result == 0, "Verify result from fclose, expected 0, got %i", result);
/* Create a second test file */
handle = fopen(RWopsAlphabetFilename, "w");
SDLTest_AssertCheck(handle != NULL, "Verify creation of file '%s' returned non NULL handle", RWopsAlphabetFilename);
if (handle == NULL) return;
/* Write alphabet text into it */
fileLen = SDL_strlen(RWopsAlphabetString);
writtenLen = fwrite(RWopsAlphabetString, 1, fileLen, handle);
SDLTest_AssertCheck(fileLen == writtenLen, "Verify number of written bytes, expected %i, got %i", (int) fileLen, (int) writtenLen);
result = fclose(handle);
SDLTest_AssertCheck(result == 0, "Verify result from fclose, expected 0, got %i", result);
SDLTest_AssertPass("Creation of test file completed");
}
void
RWopsTearDown(void *arg)
{
int result;
/* Remove the created files to clean up; ignore errors for write filename */
result = remove(RWopsReadTestFilename);
SDLTest_AssertCheck(result == 0, "Verify result from remove(%s), expected 0, got %i", RWopsReadTestFilename, result);
remove(RWopsWriteTestFilename);
result = remove(RWopsAlphabetFilename);
SDLTest_AssertCheck(result == 0, "Verify result from remove(%s), expected 0, got %i", RWopsAlphabetFilename, result);
SDLTest_AssertPass("Cleanup of test files completed");
}
/**
* @brief Makes sure parameters work properly. Local helper function.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RWseek
* http://wiki.libsdl.org/moin.cgi/SDL_RWread
*/
void
_testGenericRWopsValidations(SDL_RWops *rw, int write)
{
char buf[sizeof(RWopsHelloWorldTestString)];
Sint64 i;
size_t s;
int seekPos = SDLTest_RandomIntegerInRange(4, 8);
/* Clear buffer */
SDL_zeroa(buf);
/* Set to start. */
i = SDL_RWseek(rw, 0, RW_SEEK_SET );
SDLTest_AssertPass("Call to SDL_RWseek succeeded");
SDLTest_AssertCheck(i == (Sint64)0, "Verify seek to 0 with SDL_RWseek (RW_SEEK_SET), expected 0, got %"SDL_PRIs64, i);
/* Test write. */
s = SDL_RWwrite(rw, RWopsHelloWorldTestString, sizeof(RWopsHelloWorldTestString)-1, 1);
SDLTest_AssertPass("Call to SDL_RWwrite succeeded");
if (write) {
SDLTest_AssertCheck(s == (size_t)1, "Verify result of writing one byte with SDL_RWwrite, expected 1, got %i", (int) s);
}
else {
SDLTest_AssertCheck(s == (size_t)0, "Verify result of writing with SDL_RWwrite, expected: 0, got %i", (int) s);
}
/* Test seek to random position */
i = SDL_RWseek( rw, seekPos, RW_SEEK_SET );
SDLTest_AssertPass("Call to SDL_RWseek succeeded");
SDLTest_AssertCheck(i == (Sint64)seekPos, "Verify seek to %i with SDL_RWseek (RW_SEEK_SET), expected %i, got %"SDL_PRIs64, seekPos, seekPos, i);
/* Test seek back to start */
i = SDL_RWseek(rw, 0, RW_SEEK_SET );
SDLTest_AssertPass("Call to SDL_RWseek succeeded");
SDLTest_AssertCheck(i == (Sint64)0, "Verify seek to 0 with SDL_RWseek (RW_SEEK_SET), expected 0, got %"SDL_PRIs64, i);
/* Test read */
s = SDL_RWread( rw, buf, 1, sizeof(RWopsHelloWorldTestString)-1 );
SDLTest_AssertPass("Call to SDL_RWread succeeded");
SDLTest_AssertCheck(
s == (size_t)(sizeof(RWopsHelloWorldTestString)-1),
"Verify result from SDL_RWread, expected %i, got %i",
(int) (sizeof(RWopsHelloWorldTestString)-1),
(int) s);
SDLTest_AssertCheck(
SDL_memcmp(buf, RWopsHelloWorldTestString, sizeof(RWopsHelloWorldTestString)-1 ) == 0,
"Verify read bytes match expected string, expected '%s', got '%s'", RWopsHelloWorldTestString, buf);
/* More seek tests. */
i = SDL_RWseek( rw, -4, RW_SEEK_CUR );
SDLTest_AssertPass("Call to SDL_RWseek(...,-4,RW_SEEK_CUR) succeeded");
SDLTest_AssertCheck(
i == (Sint64)(sizeof(RWopsHelloWorldTestString)-5),
"Verify seek to -4 with SDL_RWseek (RW_SEEK_CUR), expected %i, got %i",
(int) (sizeof(RWopsHelloWorldTestString)-5),
(int) i);
i = SDL_RWseek( rw, -1, RW_SEEK_END );
SDLTest_AssertPass("Call to SDL_RWseek(...,-1,RW_SEEK_END) succeeded");
SDLTest_AssertCheck(
i == (Sint64)(sizeof(RWopsHelloWorldTestString)-2),
"Verify seek to -1 with SDL_RWseek (RW_SEEK_END), expected %i, got %i",
(int) (sizeof(RWopsHelloWorldTestString)-2),
(int) i);
/* Invalid whence seek */
i = SDL_RWseek( rw, 0, 999 );
SDLTest_AssertPass("Call to SDL_RWseek(...,0,invalid_whence) succeeded");
SDLTest_AssertCheck(
i == (Sint64)(-1),
"Verify seek with SDL_RWseek (invalid_whence); expected: -1, got %i",
(int) i);
}
/* !
* Negative test for SDL_RWFromFile parameters
*
* \sa http://wiki.libsdl.org/moin.cgi/SDL_RWFromFile
*
*/
int
rwops_testParamNegative (void)
{
SDL_RWops *rwops;
/* These should all fail. */
rwops = SDL_RWFromFile(NULL, NULL);
SDLTest_AssertPass("Call to SDL_RWFromFile(NULL, NULL) succeeded");
SDLTest_AssertCheck(rwops == NULL, "Verify SDL_RWFromFile(NULL, NULL) returns NULL");
rwops = SDL_RWFromFile(NULL, "ab+");
SDLTest_AssertPass("Call to SDL_RWFromFile(NULL, \"ab+\") succeeded");
SDLTest_AssertCheck(rwops == NULL, "Verify SDL_RWFromFile(NULL, \"ab+\") returns NULL");
rwops = SDL_RWFromFile(NULL, "sldfkjsldkfj");
SDLTest_AssertPass("Call to SDL_RWFromFile(NULL, \"sldfkjsldkfj\") succeeded");
SDLTest_AssertCheck(rwops == NULL, "Verify SDL_RWFromFile(NULL, \"sldfkjsldkfj\") returns NULL");
rwops = SDL_RWFromFile("something", "");
SDLTest_AssertPass("Call to SDL_RWFromFile(\"something\", \"\") succeeded");
SDLTest_AssertCheck(rwops == NULL, "Verify SDL_RWFromFile(\"something\", \"\") returns NULL");
rwops = SDL_RWFromFile("something", NULL);
SDLTest_AssertPass("Call to SDL_RWFromFile(\"something\", NULL) succeeded");
SDLTest_AssertCheck(rwops == NULL, "Verify SDL_RWFromFile(\"something\", NULL) returns NULL");
rwops = SDL_RWFromMem((void *)NULL, 10);
SDLTest_AssertPass("Call to SDL_RWFromMem(NULL, 10) succeeded");
SDLTest_AssertCheck(rwops == NULL, "Verify SDL_RWFromMem(NULL, 10) returns NULL");
rwops = SDL_RWFromMem((void *)RWopsAlphabetString, 0);
SDLTest_AssertPass("Call to SDL_RWFromMem(data, 0) succeeded");
SDLTest_AssertCheck(rwops == NULL, "Verify SDL_RWFromMem(data, 0) returns NULL");
rwops = SDL_RWFromConstMem((const void *)RWopsAlphabetString, 0);
SDLTest_AssertPass("Call to SDL_RWFromConstMem(data, 0) succeeded");
SDLTest_AssertCheck(rwops == NULL, "Verify SDL_RWFromConstMem(data, 0) returns NULL");
return TEST_COMPLETED;
}
/**
* @brief Tests opening from memory.
*
* \sa http://wiki.libsdl.org/moin.cgi/SDL_RWFromMem
* \sa http://wiki.libsdl.org/moin.cgi/SDL_RWClose
*/
int
rwops_testMem (void)
{
char mem[sizeof(RWopsHelloWorldTestString)];
SDL_RWops *rw;
int result;
/* Clear buffer */
SDL_zeroa(mem);
/* Open */
rw = SDL_RWFromMem(mem, sizeof(RWopsHelloWorldTestString)-1);
SDLTest_AssertPass("Call to SDL_RWFromMem() succeeded");
SDLTest_AssertCheck(rw != NULL, "Verify opening memory with SDL_RWFromMem does not return NULL");
/* Bail out if NULL */
if (rw == NULL) return TEST_ABORTED;
/* Check type */
SDLTest_AssertCheck(rw->type == SDL_RWOPS_MEMORY, "Verify RWops type is SDL_RWOPS_MEMORY; expected: %d, got: %d", SDL_RWOPS_MEMORY, rw->type);
/* Run generic tests */
_testGenericRWopsValidations(rw, 1);
/* Close */
result = SDL_RWclose(rw);
SDLTest_AssertPass("Call to SDL_RWclose() succeeded");
SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);
return TEST_COMPLETED;
}
/**
* @brief Tests opening from memory.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RWFromConstMem
* http://wiki.libsdl.org/moin.cgi/SDL_RWClose
*/
int
rwops_testConstMem (void)
{
SDL_RWops *rw;
int result;
/* Open handle */
rw = SDL_RWFromConstMem( RWopsHelloWorldCompString, sizeof(RWopsHelloWorldCompString)-1 );
SDLTest_AssertPass("Call to SDL_RWFromConstMem() succeeded");
SDLTest_AssertCheck(rw != NULL, "Verify opening memory with SDL_RWFromConstMem does not return NULL");
/* Bail out if NULL */
if (rw == NULL) return TEST_ABORTED;
/* Check type */
SDLTest_AssertCheck(rw->type == SDL_RWOPS_MEMORY_RO, "Verify RWops type is SDL_RWOPS_MEMORY_RO; expected: %d, got: %d", SDL_RWOPS_MEMORY_RO, rw->type);
/* Run generic tests */
_testGenericRWopsValidations( rw, 0 );
/* Close handle */
result = SDL_RWclose(rw);
SDLTest_AssertPass("Call to SDL_RWclose() succeeded");
SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);
return TEST_COMPLETED;
}
/**
* @brief Tests reading from file.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RWFromFile
* http://wiki.libsdl.org/moin.cgi/SDL_RWClose
*/
int
rwops_testFileRead(void)
{
SDL_RWops *rw;
int result;
/* Read test. */
rw = SDL_RWFromFile(RWopsReadTestFilename, "r");
SDLTest_AssertPass("Call to SDL_RWFromFile(..,\"r\") succeeded");
SDLTest_AssertCheck(rw != NULL, "Verify opening file with SDL_RWFromFile in read mode does not return NULL");
/* Bail out if NULL */
if (rw == NULL) return TEST_ABORTED;
/* Check type */
#if defined(__ANDROID__)
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_STDFILE || rw->type == SDL_RWOPS_JNIFILE,
"Verify RWops type is SDL_RWOPS_STDFILE or SDL_RWOPS_JNIFILE; expected: %d|%d, got: %d", SDL_RWOPS_STDFILE, SDL_RWOPS_JNIFILE, rw->type);
#elif defined(__WIN32__)
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_WINFILE,
"Verify RWops type is SDL_RWOPS_WINFILE; expected: %d, got: %d", SDL_RWOPS_WINFILE, rw->type);
#else
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_STDFILE,
"Verify RWops type is SDL_RWOPS_STDFILE; expected: %d, got: %d", SDL_RWOPS_STDFILE, rw->type);
#endif
/* Run generic tests */
_testGenericRWopsValidations( rw, 0 );
/* Close handle */
result = SDL_RWclose(rw);
SDLTest_AssertPass("Call to SDL_RWclose() succeeded");
SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);
return TEST_COMPLETED;
}
/**
* @brief Tests writing from file.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RWFromFile
* http://wiki.libsdl.org/moin.cgi/SDL_RWClose
*/
int
rwops_testFileWrite(void)
{
SDL_RWops *rw;
int result;
/* Write test. */
rw = SDL_RWFromFile(RWopsWriteTestFilename, "w+");
SDLTest_AssertPass("Call to SDL_RWFromFile(..,\"w+\") succeeded");
SDLTest_AssertCheck(rw != NULL, "Verify opening file with SDL_RWFromFile in write mode does not return NULL");
/* Bail out if NULL */
if (rw == NULL) return TEST_ABORTED;
/* Check type */
#if defined(__ANDROID__)
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_STDFILE || rw->type == SDL_RWOPS_JNIFILE,
"Verify RWops type is SDL_RWOPS_STDFILE or SDL_RWOPS_JNIFILE; expected: %d|%d, got: %d", SDL_RWOPS_STDFILE, SDL_RWOPS_JNIFILE, rw->type);
#elif defined(__WIN32__)
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_WINFILE,
"Verify RWops type is SDL_RWOPS_WINFILE; expected: %d, got: %d", SDL_RWOPS_WINFILE, rw->type);
#else
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_STDFILE,
"Verify RWops type is SDL_RWOPS_STDFILE; expected: %d, got: %d", SDL_RWOPS_STDFILE, rw->type);
#endif
/* Run generic tests */
_testGenericRWopsValidations( rw, 1 );
/* Close handle */
result = SDL_RWclose(rw);
SDLTest_AssertPass("Call to SDL_RWclose() succeeded");
SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);
return TEST_COMPLETED;
}
/**
* @brief Tests reading from file handle
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RWFromFP
* http://wiki.libsdl.org/moin.cgi/SDL_RWClose
*
*/
int
rwops_testFPRead(void)
{
FILE *fp;
SDL_RWops *rw;
int result;
/* Run read tests. */
fp = fopen(RWopsReadTestFilename, "r");
SDLTest_AssertCheck(fp != NULL, "Verify handle from opening file '%s' in read mode is not NULL", RWopsReadTestFilename);
/* Bail out if NULL */
if (fp == NULL) return TEST_ABORTED;
/* Open */
rw = SDL_RWFromFP( fp, SDL_TRUE );
SDLTest_AssertPass("Call to SDL_RWFromFP() succeeded");
SDLTest_AssertCheck(rw != NULL, "Verify opening file with SDL_RWFromFP in read mode does not return NULL");
/* Bail out if NULL */
if (rw == NULL) {
fclose(fp);
return TEST_ABORTED;
}
/* Check type */
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_STDFILE,
"Verify RWops type is SDL_RWOPS_STDFILE; expected: %d, got: %d", SDL_RWOPS_STDFILE, rw->type);
/* Run generic tests */
_testGenericRWopsValidations( rw, 0 );
/* Close handle - does fclose() */
result = SDL_RWclose(rw);
SDLTest_AssertPass("Call to SDL_RWclose() succeeded");
SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);
return TEST_COMPLETED;
}
/**
* @brief Tests writing to file handle
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RWFromFP
* http://wiki.libsdl.org/moin.cgi/SDL_RWClose
*
*/
int
rwops_testFPWrite(void)
{
FILE *fp;
SDL_RWops *rw;
int result;
/* Run write tests. */
fp = fopen(RWopsWriteTestFilename, "w+");
SDLTest_AssertCheck(fp != NULL, "Verify handle from opening file '%s' in write mode is not NULL", RWopsWriteTestFilename);
/* Bail out if NULL */
if (fp == NULL) return TEST_ABORTED;
/* Open */
rw = SDL_RWFromFP( fp, SDL_TRUE );
SDLTest_AssertPass("Call to SDL_RWFromFP() succeeded");
SDLTest_AssertCheck(rw != NULL, "Verify opening file with SDL_RWFromFP in write mode does not return NULL");
/* Bail out if NULL */
if (rw == NULL) {
fclose(fp);
return TEST_ABORTED;
}
/* Check type */
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_STDFILE,
"Verify RWops type is SDL_RWOPS_STDFILE; expected: %d, got: %d", SDL_RWOPS_STDFILE, rw->type);
/* Run generic tests */
_testGenericRWopsValidations( rw, 1 );
/* Close handle - does fclose() */
result = SDL_RWclose(rw);
SDLTest_AssertPass("Call to SDL_RWclose() succeeded");
SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);
return TEST_COMPLETED;
}
/**
* @brief Tests alloc and free RW context.
*
* \sa http://wiki.libsdl.org/moin.cgi/SDL_AllocRW
* \sa http://wiki.libsdl.org/moin.cgi/SDL_FreeRW
*/
int
rwops_testAllocFree (void)
{
/* Allocate context */
SDL_RWops *rw = SDL_AllocRW();
SDLTest_AssertPass("Call to SDL_AllocRW() succeeded");
SDLTest_AssertCheck(rw != NULL, "Validate result from SDL_AllocRW() is not NULL");
if (rw==NULL) return TEST_ABORTED;
/* Check type */
SDLTest_AssertCheck(
rw->type == SDL_RWOPS_UNKNOWN,
"Verify RWops type is SDL_RWOPS_UNKNOWN; expected: %d, got: %d", SDL_RWOPS_UNKNOWN, rw->type);
/* Free context again */
SDL_FreeRW(rw);
SDLTest_AssertPass("Call to SDL_FreeRW() succeeded");
return TEST_COMPLETED;
}
/**
* @brief Compare memory and file reads
*
* \sa http://wiki.libsdl.org/moin.cgi/SDL_RWFromMem
* \sa http://wiki.libsdl.org/moin.cgi/SDL_RWFromFile
*/
int
rwops_testCompareRWFromMemWithRWFromFile(void)
{
int slen = 26;
char buffer_file[27];
char buffer_mem[27];
size_t rv_file;
size_t rv_mem;
Uint64 sv_file;
Uint64 sv_mem;
SDL_RWops* rwops_file;
SDL_RWops* rwops_mem;
int size;
int result;
for (size=5; size<10; size++)
{
/* Terminate buffer */
buffer_file[slen] = 0;
buffer_mem[slen] = 0;
/* Read/seek from memory */
rwops_mem = SDL_RWFromMem((void *)RWopsAlphabetString, slen);
SDLTest_AssertPass("Call to SDL_RWFromMem()");
rv_mem = SDL_RWread(rwops_mem, buffer_mem, size, 6);
SDLTest_AssertPass("Call to SDL_RWread(mem, size=%d)", size);
sv_mem = SDL_RWseek(rwops_mem, 0, SEEK_END);
SDLTest_AssertPass("Call to SDL_RWseek(mem,SEEK_END)");
result = SDL_RWclose(rwops_mem);
SDLTest_AssertPass("Call to SDL_RWclose(mem)");
SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);
/* Read/see from file */
rwops_file = SDL_RWFromFile(RWopsAlphabetFilename, "r");
SDLTest_AssertPass("Call to SDL_RWFromFile()");
rv_file = SDL_RWread(rwops_file, buffer_file, size, 6);
SDLTest_AssertPass("Call to SDL_RWread(file, size=%d)", size);
sv_file = SDL_RWseek(rwops_file, 0, SEEK_END);
SDLTest_AssertPass("Call to SDL_RWseek(file,SEEK_END)");
result = SDL_RWclose(rwops_file);
SDLTest_AssertPass("Call to SDL_RWclose(file)");
SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);
/* Compare */
SDLTest_AssertCheck(rv_mem == rv_file, "Verify returned read blocks matches for mem and file reads; got: rv_mem=%d rv_file=%d", (int) rv_mem, (int) rv_file);
SDLTest_AssertCheck(sv_mem == sv_file, "Verify SEEK_END position matches for mem and file seeks; got: sv_mem=%d sv_file=%d", (int) sv_mem, (int) sv_file);
SDLTest_AssertCheck(buffer_mem[slen] == 0, "Verify mem buffer termination; expected: 0, got: %d", buffer_mem[slen]);
SDLTest_AssertCheck(buffer_file[slen] == 0, "Verify file buffer termination; expected: 0, got: %d", buffer_file[slen]);
SDLTest_AssertCheck(
SDL_strncmp(buffer_mem, RWopsAlphabetString, slen) == 0,
"Verify mem buffer contain alphabet string; expected: %s, got: %s", RWopsAlphabetString, buffer_mem);
SDLTest_AssertCheck(
SDL_strncmp(buffer_file, RWopsAlphabetString, slen) == 0,
"Verify file buffer contain alphabet string; expected: %s, got: %s", RWopsAlphabetString, buffer_file);
}
return TEST_COMPLETED;
}
/**
* @brief Tests writing and reading from file using endian aware functions.
*
* \sa
* http://wiki.libsdl.org/moin.cgi/SDL_RWFromFile
* http://wiki.libsdl.org/moin.cgi/SDL_RWClose
* http://wiki.libsdl.org/moin.cgi/SDL_ReadBE16
* http://wiki.libsdl.org/moin.cgi/SDL_WriteBE16
*/
int
rwops_testFileWriteReadEndian(void)
{
SDL_RWops *rw;
Sint64 result;
int mode;
size_t objectsWritten;
Uint16 BE16value;
Uint32 BE32value;
Uint64 BE64value;
Uint16 LE16value;
Uint32 LE32value;
Uint64 LE64value;
Uint16 BE16test;
Uint32 BE32test;
Uint64 BE64test;
Uint16 LE16test;
Uint32 LE32test;
Uint64 LE64test;
int cresult;
for (mode = 0; mode < 3; mode++) {
/* Create test data */
switch (mode) {
case 0:
SDLTest_Log("All 0 values");
BE16value = 0;
BE32value = 0;
BE64value = 0;
LE16value = 0;
LE32value = 0;
LE64value = 0;
break;
case 1:
SDLTest_Log("All 1 values");
BE16value = 1;
BE32value = 1;
BE64value = 1;
LE16value = 1;
LE32value = 1;
LE64value = 1;
break;
case 2:
SDLTest_Log("Random values");
BE16value = SDLTest_RandomUint16();
BE32value = SDLTest_RandomUint32();
BE64value = SDLTest_RandomUint64();
LE16value = SDLTest_RandomUint16();
LE32value = SDLTest_RandomUint32();
LE64value = SDLTest_RandomUint64();
break;
}
/* Write test. */
rw = SDL_RWFromFile(RWopsWriteTestFilename, "w+");
SDLTest_AssertPass("Call to SDL_RWFromFile(..,\"w+\")");
SDLTest_AssertCheck(rw != NULL, "Verify opening file with SDL_RWFromFile in write mode does not return NULL");
/* Bail out if NULL */
if (rw == NULL) return TEST_ABORTED;
/* Write test data */
objectsWritten = SDL_WriteBE16(rw, BE16value);
SDLTest_AssertPass("Call to SDL_WriteBE16()");
SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", (int) objectsWritten);
objectsWritten = SDL_WriteBE32(rw, BE32value);
SDLTest_AssertPass("Call to SDL_WriteBE32()");
SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", (int) objectsWritten);
objectsWritten = SDL_WriteBE64(rw, BE64value);
SDLTest_AssertPass("Call to SDL_WriteBE64()");
SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", (int) objectsWritten);
objectsWritten = SDL_WriteLE16(rw, LE16value);
SDLTest_AssertPass("Call to SDL_WriteLE16()");
SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", (int) objectsWritten);
objectsWritten = SDL_WriteLE32(rw, LE32value);
SDLTest_AssertPass("Call to SDL_WriteLE32()");
SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", (int) objectsWritten);
objectsWritten = SDL_WriteLE64(rw, LE64value);
SDLTest_AssertPass("Call to SDL_WriteLE64()");
SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", (int) objectsWritten);
/* Test seek to start */
result = SDL_RWseek( rw, 0, RW_SEEK_SET );
SDLTest_AssertPass("Call to SDL_RWseek succeeded");
SDLTest_AssertCheck(result == 0, "Verify result from position 0 with SDL_RWseek, expected 0, got %i", (int) result);
/* Read test data */
BE16test = SDL_ReadBE16(rw);
SDLTest_AssertPass("Call to SDL_ReadBE16()");
SDLTest_AssertCheck(BE16test == BE16value, "Validate return value from SDL_ReadBE16, expected: %hu, got: %hu", BE16value, BE16test);
BE32test = SDL_ReadBE32(rw);
SDLTest_AssertPass("Call to SDL_ReadBE32()");
SDLTest_AssertCheck(BE32test == BE32value, "Validate return value from SDL_ReadBE32, expected: %u, got: %u", BE32value, BE32test);
BE64test = SDL_ReadBE64(rw);
SDLTest_AssertPass("Call to SDL_ReadBE64()");
SDLTest_AssertCheck(BE64test == BE64value, "Validate return value from SDL_ReadBE64, expected: %"SDL_PRIu64", got: %"SDL_PRIu64, BE64value, BE64test);
LE16test = SDL_ReadLE16(rw);
SDLTest_AssertPass("Call to SDL_ReadLE16()");
SDLTest_AssertCheck(LE16test == LE16value, "Validate return value from SDL_ReadLE16, expected: %hu, got: %hu", LE16value, LE16test);
LE32test = SDL_ReadLE32(rw);
SDLTest_AssertPass("Call to SDL_ReadLE32()");
SDLTest_AssertCheck(LE32test == LE32value, "Validate return value from SDL_ReadLE32, expected: %u, got: %u", LE32value, LE32test);
LE64test = SDL_ReadLE64(rw);
SDLTest_AssertPass("Call to SDL_ReadLE64()");
SDLTest_AssertCheck(LE64test == LE64value, "Validate return value from SDL_ReadLE64, expected: %"SDL_PRIu64", got: %"SDL_PRIu64, LE64value, LE64test);
/* Close handle */
cresult = SDL_RWclose(rw);
SDLTest_AssertPass("Call to SDL_RWclose() succeeded");
SDLTest_AssertCheck(cresult == 0, "Verify result value is 0; got: %d", cresult);
}
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* RWops test cases */
static const SDLTest_TestCaseReference rwopsTest1 =
{ (SDLTest_TestCaseFp)rwops_testParamNegative, "rwops_testParamNegative", "Negative test for SDL_RWFromFile parameters", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest2 =
{ (SDLTest_TestCaseFp)rwops_testMem, "rwops_testMem", "Tests opening from memory", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest3 =
{ (SDLTest_TestCaseFp)rwops_testConstMem, "rwops_testConstMem", "Tests opening from (const) memory", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest4 =
{ (SDLTest_TestCaseFp)rwops_testFileRead, "rwops_testFileRead", "Tests reading from a file", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest5 =
{ (SDLTest_TestCaseFp)rwops_testFileWrite, "rwops_testFileWrite", "Test writing to a file", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest6 =
{ (SDLTest_TestCaseFp)rwops_testFPRead, "rwops_testFPRead", "Test reading from file pointer", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest7 =
{ (SDLTest_TestCaseFp)rwops_testFPWrite, "rwops_testFPWrite", "Test writing to file pointer", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest8 =
{ (SDLTest_TestCaseFp)rwops_testAllocFree, "rwops_testAllocFree", "Test alloc and free of RW context", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest9 =
{ (SDLTest_TestCaseFp)rwops_testFileWriteReadEndian, "rwops_testFileWriteReadEndian", "Test writing and reading via the Endian aware functions", TEST_ENABLED };
static const SDLTest_TestCaseReference rwopsTest10 =
{ (SDLTest_TestCaseFp)rwops_testCompareRWFromMemWithRWFromFile, "rwops_testCompareRWFromMemWithRWFromFile", "Compare RWFromMem and RWFromFile RWops for read and seek", TEST_ENABLED };
/* Sequence of RWops test cases */
static const SDLTest_TestCaseReference *rwopsTests[] = {
&rwopsTest1, &rwopsTest2, &rwopsTest3, &rwopsTest4, &rwopsTest5, &rwopsTest6,
&rwopsTest7, &rwopsTest8, &rwopsTest9, &rwopsTest10, NULL
};
/* RWops test suite (global) */
SDLTest_TestSuiteReference rwopsTestSuite = {
"RWops",
RWopsSetUp,
rwopsTests,
RWopsTearDown
};
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_rwops.c | C | apache-2.0 | 26,863 |
/**
* SDL_test test suite
*/
#include <limits.h>
/* Visual Studio 2008 doesn't have stdint.h */
#if defined(_MSC_VER) && _MSC_VER <= 1500
#define UINT8_MAX _UI8_MAX
#define UINT16_MAX _UI16_MAX
#define UINT32_MAX _UI32_MAX
#define INT64_MIN _I64_MIN
#define INT64_MAX _I64_MAX
#define UINT64_MAX _UI64_MAX
#else
#include <stdint.h>
#endif
#include <stdio.h>
#include <float.h>
#include <ctype.h>
#include "SDL.h"
#include "SDL_test.h"
/* Test case functions */
/* Forward declarations for internal harness functions */
extern char *SDLTest_GenerateRunSeed(const int length);
/**
* @brief Calls to SDLTest_GenerateRunSeed()
*/
int
sdltest_generateRunSeed(void *arg)
{
char* result;
size_t i, l;
int j;
for (i = 1; i <= 10; i += 3) {
result = SDLTest_GenerateRunSeed((const int)i);
SDLTest_AssertPass("Call to SDLTest_GenerateRunSeed()");
SDLTest_AssertCheck(result != NULL, "Verify returned value is not NULL");
if (result != NULL) {
l = SDL_strlen(result);
SDLTest_AssertCheck(l == i, "Verify length of returned value is %d, got: %d", (int) i, (int) l);
SDL_free(result);
}
}
/* Negative cases */
for (j = -2; j <= 0; j++) {
result = SDLTest_GenerateRunSeed((const int)j);
SDLTest_AssertPass("Call to SDLTest_GenerateRunSeed()");
SDLTest_AssertCheck(result == NULL, "Verify returned value is not NULL");
}
return TEST_COMPLETED;
}
/**
* @brief Calls to SDLTest_GetFuzzerInvocationCount()
*/
int
sdltest_getFuzzerInvocationCount(void *arg)
{
Uint8 result;
int fuzzerCount1, fuzzerCount2;
fuzzerCount1 = SDLTest_GetFuzzerInvocationCount();
SDLTest_AssertPass("Call to SDLTest_GetFuzzerInvocationCount()");
SDLTest_AssertCheck(fuzzerCount1 >= 0, "Verify returned value, expected: >=0, got: %d", fuzzerCount1);
result = SDLTest_RandomUint8();
SDLTest_AssertPass("Call to SDLTest_RandomUint8(), returned %d", result);
fuzzerCount2 = SDLTest_GetFuzzerInvocationCount();
SDLTest_AssertPass("Call to SDLTest_GetFuzzerInvocationCount()");
SDLTest_AssertCheck(fuzzerCount2 > fuzzerCount1, "Verify returned value, expected: >%d, got: %d", fuzzerCount1, fuzzerCount2);
return TEST_COMPLETED;
}
/**
* @brief Calls to random number generators
*/
int
sdltest_randomNumber(void *arg)
{
Sint64 result;
Uint64 uresult;
double dresult;
Uint64 umax;
Sint64 min, max;
result = (Sint64)SDLTest_RandomUint8();
umax = (1 << 8) - 1;
SDLTest_AssertPass("Call to SDLTest_RandomUint8");
SDLTest_AssertCheck(result >= 0 && result <= (Sint64)umax, "Verify result value, expected: [0,%"SDL_PRIu64"], got: %"SDL_PRIs64, umax, result);
result = (Sint64)SDLTest_RandomSint8();
min = 0 - (1 << 7);
max = (1 << 7) - 1;
SDLTest_AssertPass("Call to SDLTest_RandomSint8");
SDLTest_AssertCheck(result >= min && result <= max, "Verify result value, expected: [%"SDL_PRIs64",%"SDL_PRIs64"], got: %"SDL_PRIs64, min, max, result);
result = (Sint64)SDLTest_RandomUint16();
umax = (1 << 16) - 1;
SDLTest_AssertPass("Call to SDLTest_RandomUint16");
SDLTest_AssertCheck(result >= 0 && result <= (Sint64)umax, "Verify result value, expected: [0,%"SDL_PRIu64"], got: %"SDL_PRIs64, umax, result);
result = (Sint64)SDLTest_RandomSint16();
min = 0 - (1 << 15);
max = (1 << 15) - 1;
SDLTest_AssertPass("Call to SDLTest_RandomSint16");
SDLTest_AssertCheck(result >= min && result <= max, "Verify result value, expected: [%"SDL_PRIs64",%"SDL_PRIs64"], got: %"SDL_PRIs64, min, max, result);
result = (Sint64)SDLTest_RandomUint32();
umax = ((Uint64)1 << 32) - 1;
SDLTest_AssertPass("Call to SDLTest_RandomUint32");
SDLTest_AssertCheck(result >= 0 && result <= (Sint64)umax, "Verify result value, expected: [0,%"SDL_PRIu64"], got: %"SDL_PRIs64, umax, result);
result = (Sint64)SDLTest_RandomSint32();
min = 0 - ((Sint64)1 << 31);
max = ((Sint64)1 << 31) - 1;
SDLTest_AssertPass("Call to SDLTest_RandomSint32");
SDLTest_AssertCheck(result >= min && result <= max, "Verify result value, expected: [%"SDL_PRIs64",%"SDL_PRIs64"], got: %"SDL_PRIs64, min, max, result);
uresult = SDLTest_RandomUint64();
SDLTest_AssertPass("Call to SDLTest_RandomUint64");
result = SDLTest_RandomSint64();
SDLTest_AssertPass("Call to SDLTest_RandomSint64");
dresult = (double)SDLTest_RandomUnitFloat();
SDLTest_AssertPass("Call to SDLTest_RandomUnitFloat");
SDLTest_AssertCheck(dresult >= 0.0 && dresult < 1.0, "Verify result value, expected: [0.0,1.0[, got: %e", dresult);
dresult = (double)SDLTest_RandomFloat();
SDLTest_AssertPass("Call to SDLTest_RandomFloat");
SDLTest_AssertCheck(dresult >= (double)(-FLT_MAX) && dresult <= (double)FLT_MAX, "Verify result value, expected: [%e,%e], got: %e", (double)(-FLT_MAX), (double)FLT_MAX, dresult);
dresult = (double)SDLTest_RandomUnitDouble();
SDLTest_AssertPass("Call to SDLTest_RandomUnitDouble");
SDLTest_AssertCheck(dresult >= 0.0 && dresult < 1.0, "Verify result value, expected: [0.0,1.0[, got: %e", dresult);
dresult = SDLTest_RandomDouble();
SDLTest_AssertPass("Call to SDLTest_RandomDouble");
return TEST_COMPLETED;
}
/*
* @brief Calls to random boundary number generators for Uint8
*/
int
sdltest_randomBoundaryNumberUint8(void *arg)
{
const char *expectedError = "That operation is not supported";
char *lastError;
Uint64 uresult;
/* Clean error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
/* RandomUintXBoundaryValue(10, 10, SDL_TRUE) returns 10 */
uresult = (Uint64)SDLTest_RandomUint8BoundaryValue(10, 10, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint8BoundaryValue");
SDLTest_AssertCheck(
uresult == 10,
"Validate result value for parameters (10,10,SDL_TRUE); expected: 10, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(10, 11, SDL_TRUE) returns 10, 11 */
uresult = (Uint64)SDLTest_RandomUint8BoundaryValue(10, 11, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint8BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11,
"Validate result value for parameters (10,11,SDL_TRUE); expected: 10|11, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(10, 12, SDL_TRUE) returns 10, 11, 12 */
uresult = (Uint64)SDLTest_RandomUint8BoundaryValue(10, 12, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint8BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11 || uresult == 12,
"Validate result value for parameters (10,12,SDL_TRUE); expected: 10|11|12, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(10, 13, SDL_TRUE) returns 10, 11, 12, 13 */
uresult = (Uint64)SDLTest_RandomUint8BoundaryValue(10, 13, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint8BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11 || uresult == 12 || uresult == 13,
"Validate result value for parameters (10,13,SDL_TRUE); expected: 10|11|12|13, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(10, 20, SDL_TRUE) returns 10, 11, 19 or 20 */
uresult = (Uint64)SDLTest_RandomUint8BoundaryValue(10, 20, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint8BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11 || uresult == 19 || uresult == 20,
"Validate result value for parameters (10,20,SDL_TRUE); expected: 10|11|19|20, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(20, 10, SDL_TRUE) returns 10, 11, 19 or 20 */
uresult = (Uint64)SDLTest_RandomUint8BoundaryValue(20, 10, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint8BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11 || uresult == 19 || uresult == 20,
"Validate result value for parameters (20,10,SDL_TRUE); expected: 10|11|19|20, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(1, 20, SDL_FALSE) returns 0, 21 */
uresult = (Uint64)SDLTest_RandomUint8BoundaryValue(1, 20, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint8BoundaryValue");
SDLTest_AssertCheck(
uresult == 0 || uresult == 21,
"Validate result value for parameters (1,20,SDL_FALSE); expected: 0|21, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(0, 99, SDL_FALSE) returns 100 */
uresult = (Uint64)SDLTest_RandomUint8BoundaryValue(0, 99, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint8BoundaryValue");
SDLTest_AssertCheck(
uresult == 100,
"Validate result value for parameters (0,99,SDL_FALSE); expected: 100, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(1, 0xff, SDL_FALSE) returns 0 (no error) */
uresult = (Uint64)SDLTest_RandomUint8BoundaryValue(1, 255, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint8BoundaryValue");
SDLTest_AssertCheck(
uresult == 0,
"Validate result value for parameters (1,255,SDL_FALSE); expected: 0, got: %"SDL_PRIs64, uresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
/* RandomUintXBoundaryValue(0, 0xfe, SDL_FALSE) returns 0xff (no error) */
uresult = (Uint64)SDLTest_RandomUint8BoundaryValue(0, 254, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint8BoundaryValue");
SDLTest_AssertCheck(
uresult == 0xff,
"Validate result value for parameters (0,254,SDL_FALSE); expected: 0xff, got: %"SDL_PRIs64, uresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
/* RandomUintXBoundaryValue(0, 0xff, SDL_FALSE) returns 0 (sets error) */
uresult = (Uint64)SDLTest_RandomUint8BoundaryValue(0, 255, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint8BoundaryValue");
SDLTest_AssertCheck(
uresult == 0,
"Validate result value for parameters(0,255,SDL_FALSE); expected: 0, got: %"SDL_PRIs64, uresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError != NULL && SDL_strcmp(lastError, expectedError) == 0,
"SDL_GetError(): expected message '%s', was message: '%s'",
expectedError,
lastError);
/* Clear error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
return TEST_COMPLETED;
}
/*
* @brief Calls to random boundary number generators for Uint16
*/
int
sdltest_randomBoundaryNumberUint16(void *arg)
{
const char *expectedError = "That operation is not supported";
char *lastError;
Uint64 uresult;
/* Clean error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
/* RandomUintXBoundaryValue(10, 10, SDL_TRUE) returns 10 */
uresult = (Uint64)SDLTest_RandomUint16BoundaryValue(10, 10, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint16BoundaryValue");
SDLTest_AssertCheck(
uresult == 10,
"Validate result value for parameters (10,10,SDL_TRUE); expected: 10, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(10, 11, SDL_TRUE) returns 10, 11 */
uresult = (Uint64)SDLTest_RandomUint16BoundaryValue(10, 11, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint16BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11,
"Validate result value for parameters (10,11,SDL_TRUE); expected: 10|11, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(10, 12, SDL_TRUE) returns 10, 11, 12 */
uresult = (Uint64)SDLTest_RandomUint16BoundaryValue(10, 12, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint16BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11 || uresult == 12,
"Validate result value for parameters (10,12,SDL_TRUE); expected: 10|11|12, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(10, 13, SDL_TRUE) returns 10, 11, 12, 13 */
uresult = (Uint64)SDLTest_RandomUint16BoundaryValue(10, 13, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint16BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11 || uresult == 12 || uresult == 13,
"Validate result value for parameters (10,13,SDL_TRUE); expected: 10|11|12|13, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(10, 20, SDL_TRUE) returns 10, 11, 19 or 20 */
uresult = (Uint64)SDLTest_RandomUint16BoundaryValue(10, 20, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint16BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11 || uresult == 19 || uresult == 20,
"Validate result value for parameters (10,20,SDL_TRUE); expected: 10|11|19|20, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(20, 10, SDL_TRUE) returns 10, 11, 19 or 20 */
uresult = (Uint64)SDLTest_RandomUint16BoundaryValue(20, 10, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint16BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11 || uresult == 19 || uresult == 20,
"Validate result value for parameters (20,10,SDL_TRUE); expected: 10|11|19|20, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(1, 20, SDL_FALSE) returns 0, 21 */
uresult = (Uint64)SDLTest_RandomUint16BoundaryValue(1, 20, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint16BoundaryValue");
SDLTest_AssertCheck(
uresult == 0 || uresult == 21,
"Validate result value for parameters (1,20,SDL_FALSE); expected: 0|21, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(0, 99, SDL_FALSE) returns 100 */
uresult = (Uint64)SDLTest_RandomUint16BoundaryValue(0, 99, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint16BoundaryValue");
SDLTest_AssertCheck(
uresult == 100,
"Validate result value for parameters (0,99,SDL_FALSE); expected: 100, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(1, 0xffff, SDL_FALSE) returns 0 (no error) */
uresult = (Uint64)SDLTest_RandomUint16BoundaryValue(1, 0xffff, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint16BoundaryValue");
SDLTest_AssertCheck(
uresult == 0,
"Validate result value for parameters (1,0xffff,SDL_FALSE); expected: 0, got: %"SDL_PRIs64, uresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
/* RandomUintXBoundaryValue(0, 0xfffe, SDL_FALSE) returns 0xffff (no error) */
uresult = (Uint64)SDLTest_RandomUint16BoundaryValue(0, 0xfffe, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint16BoundaryValue");
SDLTest_AssertCheck(
uresult == 0xffff,
"Validate result value for parameters (0,0xfffe,SDL_FALSE); expected: 0xffff, got: %"SDL_PRIs64, uresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
/* RandomUintXBoundaryValue(0, 0xffff, SDL_FALSE) returns 0 (sets error) */
uresult = (Uint64)SDLTest_RandomUint16BoundaryValue(0, 0xffff, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint16BoundaryValue");
SDLTest_AssertCheck(
uresult == 0,
"Validate result value for parameters(0,0xffff,SDL_FALSE); expected: 0, got: %"SDL_PRIs64, uresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError != NULL && SDL_strcmp(lastError, expectedError) == 0,
"SDL_GetError(): expected message '%s', was message: '%s'",
expectedError,
lastError);
/* Clear error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
return TEST_COMPLETED;
}
/*
* @brief Calls to random boundary number generators for Uint32
*/
int
sdltest_randomBoundaryNumberUint32(void *arg)
{
const char *expectedError = "That operation is not supported";
char *lastError;
Uint64 uresult;
/* Clean error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
/* RandomUintXBoundaryValue(10, 10, SDL_TRUE) returns 10 */
uresult = (Uint64)SDLTest_RandomUint32BoundaryValue(10, 10, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint32BoundaryValue");
SDLTest_AssertCheck(
uresult == 10,
"Validate result value for parameters (10,10,SDL_TRUE); expected: 10, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(10, 11, SDL_TRUE) returns 10, 11 */
uresult = (Uint64)SDLTest_RandomUint32BoundaryValue(10, 11, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint32BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11,
"Validate result value for parameters (10,11,SDL_TRUE); expected: 10|11, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(10, 12, SDL_TRUE) returns 10, 11, 12 */
uresult = (Uint64)SDLTest_RandomUint32BoundaryValue(10, 12, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint32BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11 || uresult == 12,
"Validate result value for parameters (10,12,SDL_TRUE); expected: 10|11|12, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(10, 13, SDL_TRUE) returns 10, 11, 12, 13 */
uresult = (Uint64)SDLTest_RandomUint32BoundaryValue(10, 13, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint32BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11 || uresult == 12 || uresult == 13,
"Validate result value for parameters (10,13,SDL_TRUE); expected: 10|11|12|13, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(10, 20, SDL_TRUE) returns 10, 11, 19 or 20 */
uresult = (Uint64)SDLTest_RandomUint32BoundaryValue(10, 20, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint32BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11 || uresult == 19 || uresult == 20,
"Validate result value for parameters (10,20,SDL_TRUE); expected: 10|11|19|20, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(20, 10, SDL_TRUE) returns 10, 11, 19 or 20 */
uresult = (Uint64)SDLTest_RandomUint32BoundaryValue(20, 10, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint32BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11 || uresult == 19 || uresult == 20,
"Validate result value for parameters (20,10,SDL_TRUE); expected: 10|11|19|20, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(1, 20, SDL_FALSE) returns 0, 21 */
uresult = (Uint64)SDLTest_RandomUint32BoundaryValue(1, 20, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint32BoundaryValue");
SDLTest_AssertCheck(
uresult == 0 || uresult == 21,
"Validate result value for parameters (1,20,SDL_FALSE); expected: 0|21, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(0, 99, SDL_FALSE) returns 100 */
uresult = (Uint64)SDLTest_RandomUint32BoundaryValue(0, 99, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint32BoundaryValue");
SDLTest_AssertCheck(
uresult == 100,
"Validate result value for parameters (0,99,SDL_FALSE); expected: 100, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(1, 0xffffffff, SDL_FALSE) returns 0 (no error) */
uresult = (Uint64)SDLTest_RandomUint32BoundaryValue(1, 0xffffffff, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint32BoundaryValue");
SDLTest_AssertCheck(
uresult == 0,
"Validate result value for parameters (1,0xffffffff,SDL_FALSE); expected: 0, got: %"SDL_PRIs64, uresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
/* RandomUintXBoundaryValue(0, 0xfffffffe, SDL_FALSE) returns 0xffffffff (no error) */
uresult = (Uint64)SDLTest_RandomUint32BoundaryValue(0, 0xfffffffe, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint32BoundaryValue");
SDLTest_AssertCheck(
uresult == 0xffffffff,
"Validate result value for parameters (0,0xfffffffe,SDL_FALSE); expected: 0xffffffff, got: %"SDL_PRIs64, uresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
/* RandomUintXBoundaryValue(0, 0xffffffff, SDL_FALSE) returns 0 (sets error) */
uresult = (Uint64)SDLTest_RandomUint32BoundaryValue(0, 0xffffffff, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint32BoundaryValue");
SDLTest_AssertCheck(
uresult == 0,
"Validate result value for parameters(0,0xffffffff,SDL_FALSE); expected: 0, got: %"SDL_PRIs64, uresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError != NULL && SDL_strcmp(lastError, expectedError) == 0,
"SDL_GetError(): expected message '%s', was message: '%s'",
expectedError,
lastError);
/* Clear error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
return TEST_COMPLETED;
}
/*
* @brief Calls to random boundary number generators for Uint64
*/
int
sdltest_randomBoundaryNumberUint64(void *arg)
{
const char *expectedError = "That operation is not supported";
char *lastError;
Uint64 uresult;
/* Clean error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
/* RandomUintXBoundaryValue(10, 10, SDL_TRUE) returns 10 */
uresult = (Uint64)SDLTest_RandomUint64BoundaryValue(10, 10, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint64BoundaryValue");
SDLTest_AssertCheck(
uresult == 10,
"Validate result value for parameters (10,10,SDL_TRUE); expected: 10, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(10, 11, SDL_TRUE) returns 10, 11 */
uresult = (Uint64)SDLTest_RandomUint64BoundaryValue(10, 11, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint64BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11,
"Validate result value for parameters (10,11,SDL_TRUE); expected: 10|11, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(10, 12, SDL_TRUE) returns 10, 11, 12 */
uresult = (Uint64)SDLTest_RandomUint64BoundaryValue(10, 12, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint64BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11 || uresult == 12,
"Validate result value for parameters (10,12,SDL_TRUE); expected: 10|11|12, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(10, 13, SDL_TRUE) returns 10, 11, 12, 13 */
uresult = (Uint64)SDLTest_RandomUint64BoundaryValue(10, 13, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint64BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11 || uresult == 12 || uresult == 13,
"Validate result value for parameters (10,13,SDL_TRUE); expected: 10|11|12|13, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(10, 20, SDL_TRUE) returns 10, 11, 19 or 20 */
uresult = (Uint64)SDLTest_RandomUint64BoundaryValue(10, 20, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint64BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11 || uresult == 19 || uresult == 20,
"Validate result value for parameters (10,20,SDL_TRUE); expected: 10|11|19|20, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(20, 10, SDL_TRUE) returns 10, 11, 19 or 20 */
uresult = (Uint64)SDLTest_RandomUint64BoundaryValue(20, 10, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomUint64BoundaryValue");
SDLTest_AssertCheck(
uresult == 10 || uresult == 11 || uresult == 19 || uresult == 20,
"Validate result value for parameters (20,10,SDL_TRUE); expected: 10|11|19|20, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(1, 20, SDL_FALSE) returns 0, 21 */
uresult = (Uint64)SDLTest_RandomUint64BoundaryValue(1, 20, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint64BoundaryValue");
SDLTest_AssertCheck(
uresult == 0 || uresult == 21,
"Validate result value for parameters (1,20,SDL_FALSE); expected: 0|21, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(0, 99, SDL_FALSE) returns 100 */
uresult = (Uint64)SDLTest_RandomUint64BoundaryValue(0, 99, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint64BoundaryValue");
SDLTest_AssertCheck(
uresult == 100,
"Validate result value for parameters (0,99,SDL_FALSE); expected: 100, got: %"SDL_PRIs64, uresult);
/* RandomUintXBoundaryValue(1, 0xffffffffffffffff, SDL_FALSE) returns 0 (no error) */
uresult = (Uint64)SDLTest_RandomUint64BoundaryValue(1, (Uint64)0xffffffffffffffffULL, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint64BoundaryValue");
SDLTest_AssertCheck(
uresult == 0,
"Validate result value for parameters (1,0xffffffffffffffff,SDL_FALSE); expected: 0, got: %"SDL_PRIs64, uresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
/* RandomUintXBoundaryValue(0, 0xfffffffffffffffe, SDL_FALSE) returns 0xffffffffffffffff (no error) */
uresult = (Uint64)SDLTest_RandomUint64BoundaryValue(0, (Uint64)0xfffffffffffffffeULL, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint64BoundaryValue");
SDLTest_AssertCheck(
uresult == (Uint64)0xffffffffffffffffULL,
"Validate result value for parameters (0,0xfffffffffffffffe,SDL_FALSE); expected: 0xffffffffffffffff, got: %"SDL_PRIs64, uresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
/* RandomUintXBoundaryValue(0, 0xffffffffffffffff, SDL_FALSE) returns 0 (sets error) */
uresult = (Uint64)SDLTest_RandomUint64BoundaryValue(0, (Uint64)0xffffffffffffffffULL, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomUint64BoundaryValue");
SDLTest_AssertCheck(
uresult == 0,
"Validate result value for parameters(0,0xffffffffffffffff,SDL_FALSE); expected: 0, got: %"SDL_PRIs64, uresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError != NULL && SDL_strcmp(lastError, expectedError) == 0,
"SDL_GetError(): expected message '%s', was message: '%s'",
expectedError,
lastError);
/* Clear error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
return TEST_COMPLETED;
}
/*
* @brief Calls to random boundary number generators for Sint8
*/
int
sdltest_randomBoundaryNumberSint8(void *arg)
{
const char *expectedError = "That operation is not supported";
char *lastError;
Sint64 sresult;
/* Clean error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
/* RandomSintXBoundaryValue(10, 10, SDL_TRUE) returns 10 */
sresult = (Sint64)SDLTest_RandomSint8BoundaryValue(10, 10, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint8BoundaryValue");
SDLTest_AssertCheck(
sresult == 10,
"Validate result value for parameters (10,10,SDL_TRUE); expected: 10, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(10, 11, SDL_TRUE) returns 10, 11 */
sresult = (Sint64)SDLTest_RandomSint8BoundaryValue(10, 11, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint8BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11,
"Validate result value for parameters (10,11,SDL_TRUE); expected: 10|11, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(10, 12, SDL_TRUE) returns 10, 11, 12 */
sresult = (Sint64)SDLTest_RandomSint8BoundaryValue(10, 12, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint8BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11 || sresult == 12,
"Validate result value for parameters (10,12,SDL_TRUE); expected: 10|11|12, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(10, 13, SDL_TRUE) returns 10, 11, 12, 13 */
sresult = (Sint64)SDLTest_RandomSint8BoundaryValue(10, 13, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint8BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11 || sresult == 12 || sresult == 13,
"Validate result value for parameters (10,13,SDL_TRUE); expected: 10|11|12|13, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(10, 20, SDL_TRUE) returns 10, 11, 19 or 20 */
sresult = (Sint64)SDLTest_RandomSint8BoundaryValue(10, 20, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint8BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11 || sresult == 19 || sresult == 20,
"Validate result value for parameters (10,20,SDL_TRUE); expected: 10|11|19|20, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(20, 10, SDL_TRUE) returns 10, 11, 19 or 20 */
sresult = (Sint64)SDLTest_RandomSint8BoundaryValue(20, 10, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint8BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11 || sresult == 19 || sresult == 20,
"Validate result value for parameters (20,10,SDL_TRUE); expected: 10|11|19|20, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(1, 20, SDL_FALSE) returns 0, 21 */
sresult = (Sint64)SDLTest_RandomSint8BoundaryValue(1, 20, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint8BoundaryValue");
SDLTest_AssertCheck(
sresult == 0 || sresult == 21,
"Validate result value for parameters (1,20,SDL_FALSE); expected: 0|21, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(SCHAR_MIN, 99, SDL_FALSE) returns 100 */
sresult = (Sint64)SDLTest_RandomSint8BoundaryValue(SCHAR_MIN, 99, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint8BoundaryValue");
SDLTest_AssertCheck(
sresult == 100,
"Validate result value for parameters (SCHAR_MIN,99,SDL_FALSE); expected: 100, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(SCHAR_MIN + 1, SCHAR_MAX, SDL_FALSE) returns SCHAR_MIN (no error) */
sresult = (Sint64)SDLTest_RandomSint8BoundaryValue(SCHAR_MIN + 1, SCHAR_MAX, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint8BoundaryValue");
SDLTest_AssertCheck(
sresult == SCHAR_MIN,
"Validate result value for parameters (SCHAR_MIN + 1,SCHAR_MAX,SDL_FALSE); expected: %d, got: %"SDL_PRIs64, SCHAR_MIN, sresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
/* RandomSintXBoundaryValue(SCHAR_MIN, SCHAR_MAX - 1, SDL_FALSE) returns SCHAR_MAX (no error) */
sresult = (Sint64)SDLTest_RandomSint8BoundaryValue(SCHAR_MIN, SCHAR_MAX -1, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint8BoundaryValue");
SDLTest_AssertCheck(
sresult == SCHAR_MAX,
"Validate result value for parameters (SCHAR_MIN,SCHAR_MAX - 1,SDL_FALSE); expected: %d, got: %"SDL_PRIs64, SCHAR_MAX, sresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
/* RandomSintXBoundaryValue(SCHAR_MIN, SCHAR_MAX, SDL_FALSE) returns SCHAR_MIN (sets error) */
sresult = (Sint64)SDLTest_RandomSint8BoundaryValue(SCHAR_MIN, SCHAR_MAX, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint8BoundaryValue");
SDLTest_AssertCheck(
sresult == SCHAR_MIN,
"Validate result value for parameters(SCHAR_MIN,SCHAR_MAX,SDL_FALSE); expected: %d, got: %"SDL_PRIs64, SCHAR_MIN, sresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError != NULL && SDL_strcmp(lastError, expectedError) == 0,
"SDL_GetError(): expected message '%s', was message: '%s'",
expectedError,
lastError);
/* Clear error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
return TEST_COMPLETED;
}
/*
* @brief Calls to random boundary number generators for Sint16
*/
int
sdltest_randomBoundaryNumberSint16(void *arg)
{
const char *expectedError = "That operation is not supported";
char *lastError;
Sint64 sresult;
/* Clean error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
/* RandomSintXBoundaryValue(10, 10, SDL_TRUE) returns 10 */
sresult = (Sint64)SDLTest_RandomSint16BoundaryValue(10, 10, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint16BoundaryValue");
SDLTest_AssertCheck(
sresult == 10,
"Validate result value for parameters (10,10,SDL_TRUE); expected: 10, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(10, 11, SDL_TRUE) returns 10, 11 */
sresult = (Sint64)SDLTest_RandomSint16BoundaryValue(10, 11, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint16BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11,
"Validate result value for parameters (10,11,SDL_TRUE); expected: 10|11, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(10, 12, SDL_TRUE) returns 10, 11, 12 */
sresult = (Sint64)SDLTest_RandomSint16BoundaryValue(10, 12, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint16BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11 || sresult == 12,
"Validate result value for parameters (10,12,SDL_TRUE); expected: 10|11|12, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(10, 13, SDL_TRUE) returns 10, 11, 12, 13 */
sresult = (Sint64)SDLTest_RandomSint16BoundaryValue(10, 13, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint16BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11 || sresult == 12 || sresult == 13,
"Validate result value for parameters (10,13,SDL_TRUE); expected: 10|11|12|13, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(10, 20, SDL_TRUE) returns 10, 11, 19 or 20 */
sresult = (Sint64)SDLTest_RandomSint16BoundaryValue(10, 20, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint16BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11 || sresult == 19 || sresult == 20,
"Validate result value for parameters (10,20,SDL_TRUE); expected: 10|11|19|20, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(20, 10, SDL_TRUE) returns 10, 11, 19 or 20 */
sresult = (Sint64)SDLTest_RandomSint16BoundaryValue(20, 10, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint16BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11 || sresult == 19 || sresult == 20,
"Validate result value for parameters (20,10,SDL_TRUE); expected: 10|11|19|20, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(1, 20, SDL_FALSE) returns 0, 21 */
sresult = (Sint64)SDLTest_RandomSint16BoundaryValue(1, 20, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint16BoundaryValue");
SDLTest_AssertCheck(
sresult == 0 || sresult == 21,
"Validate result value for parameters (1,20,SDL_FALSE); expected: 0|21, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(SHRT_MIN, 99, SDL_FALSE) returns 100 */
sresult = (Sint64)SDLTest_RandomSint16BoundaryValue(SHRT_MIN, 99, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint16BoundaryValue");
SDLTest_AssertCheck(
sresult == 100,
"Validate result value for parameters (SHRT_MIN,99,SDL_FALSE); expected: 100, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(SHRT_MIN + 1, SHRT_MAX, SDL_FALSE) returns SHRT_MIN (no error) */
sresult = (Sint64)SDLTest_RandomSint16BoundaryValue(SHRT_MIN + 1, SHRT_MAX, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint16BoundaryValue");
SDLTest_AssertCheck(
sresult == SHRT_MIN,
"Validate result value for parameters (SHRT_MIN+1,SHRT_MAX,SDL_FALSE); expected: %d, got: %"SDL_PRIs64, SHRT_MIN, sresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
/* RandomSintXBoundaryValue(SHRT_MIN, SHRT_MAX - 1, SDL_FALSE) returns SHRT_MAX (no error) */
sresult = (Sint64)SDLTest_RandomSint16BoundaryValue(SHRT_MIN, SHRT_MAX - 1, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint16BoundaryValue");
SDLTest_AssertCheck(
sresult == SHRT_MAX,
"Validate result value for parameters (SHRT_MIN,SHRT_MAX - 1,SDL_FALSE); expected: %d, got: %"SDL_PRIs64, SHRT_MAX, sresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
/* RandomSintXBoundaryValue(SHRT_MIN, SHRT_MAX, SDL_FALSE) returns 0 (sets error) */
sresult = (Sint64)SDLTest_RandomSint16BoundaryValue(SHRT_MIN, SHRT_MAX, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint16BoundaryValue");
SDLTest_AssertCheck(
sresult == SHRT_MIN,
"Validate result value for parameters(SHRT_MIN,SHRT_MAX,SDL_FALSE); expected: %d, got: %"SDL_PRIs64, SHRT_MIN, sresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError != NULL && SDL_strcmp(lastError, expectedError) == 0,
"SDL_GetError(): expected message '%s', was message: '%s'",
expectedError,
lastError);
/* Clear error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
return TEST_COMPLETED;
}
/*
* @brief Calls to random boundary number generators for Sint32
*/
int
sdltest_randomBoundaryNumberSint32(void *arg)
{
const char *expectedError = "That operation is not supported";
char *lastError;
Sint64 sresult;
#if ((ULONG_MAX) == (UINT_MAX))
Sint32 long_min = LONG_MIN;
Sint32 long_max = LONG_MAX;
#else
Sint32 long_min = INT_MIN;
Sint32 long_max = INT_MAX;
#endif
/* Clean error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
/* RandomSintXBoundaryValue(10, 10, SDL_TRUE) returns 10 */
sresult = (Sint64)SDLTest_RandomSint32BoundaryValue(10, 10, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint32BoundaryValue");
SDLTest_AssertCheck(
sresult == 10,
"Validate result value for parameters (10,10,SDL_TRUE); expected: 10, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(10, 11, SDL_TRUE) returns 10, 11 */
sresult = (Sint64)SDLTest_RandomSint32BoundaryValue(10, 11, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint32BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11,
"Validate result value for parameters (10,11,SDL_TRUE); expected: 10|11, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(10, 12, SDL_TRUE) returns 10, 11, 12 */
sresult = (Sint64)SDLTest_RandomSint32BoundaryValue(10, 12, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint32BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11 || sresult == 12,
"Validate result value for parameters (10,12,SDL_TRUE); expected: 10|11|12, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(10, 13, SDL_TRUE) returns 10, 11, 12, 13 */
sresult = (Sint64)SDLTest_RandomSint32BoundaryValue(10, 13, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint32BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11 || sresult == 12 || sresult == 13,
"Validate result value for parameters (10,13,SDL_TRUE); expected: 10|11|12|13, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(10, 20, SDL_TRUE) returns 10, 11, 19 or 20 */
sresult = (Sint64)SDLTest_RandomSint32BoundaryValue(10, 20, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint32BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11 || sresult == 19 || sresult == 20,
"Validate result value for parameters (10,20,SDL_TRUE); expected: 10|11|19|20, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(20, 10, SDL_TRUE) returns 10, 11, 19 or 20 */
sresult = (Sint64)SDLTest_RandomSint32BoundaryValue(20, 10, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint32BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11 || sresult == 19 || sresult == 20,
"Validate result value for parameters (20,10,SDL_TRUE); expected: 10|11|19|20, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(1, 20, SDL_FALSE) returns 0, 21 */
sresult = (Sint64)SDLTest_RandomSint32BoundaryValue(1, 20, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint32BoundaryValue");
SDLTest_AssertCheck(
sresult == 0 || sresult == 21,
"Validate result value for parameters (1,20,SDL_FALSE); expected: 0|21, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(LONG_MIN, 99, SDL_FALSE) returns 100 */
sresult = (Sint64)SDLTest_RandomSint32BoundaryValue(long_min, 99, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint32BoundaryValue");
SDLTest_AssertCheck(
sresult == 100,
"Validate result value for parameters (LONG_MIN,99,SDL_FALSE); expected: 100, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(LONG_MIN + 1, LONG_MAX, SDL_FALSE) returns LONG_MIN (no error) */
sresult = (Sint64)SDLTest_RandomSint32BoundaryValue(long_min + 1, long_max, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint32BoundaryValue");
SDLTest_AssertCheck(
sresult == long_min,
"Validate result value for parameters (LONG_MIN+1,LONG_MAX,SDL_FALSE); expected: %d, got: %"SDL_PRIs64, long_min, sresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
/* RandomSintXBoundaryValue(LONG_MIN, LONG_MAX - 1, SDL_FALSE) returns LONG_MAX (no error) */
sresult = (Sint64)SDLTest_RandomSint32BoundaryValue(long_min, long_max - 1, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint32BoundaryValue");
SDLTest_AssertCheck(
sresult == long_max,
"Validate result value for parameters (LONG_MIN,LONG_MAX - 1,SDL_FALSE); expected: %d, got: %"SDL_PRIs64, long_max, sresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
/* RandomSintXBoundaryValue(LONG_MIN, LONG_MAX, SDL_FALSE) returns 0 (sets error) */
sresult = (Sint64)SDLTest_RandomSint32BoundaryValue(long_min, long_max, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint32BoundaryValue");
SDLTest_AssertCheck(
sresult == long_min,
"Validate result value for parameters(LONG_MIN,LONG_MAX,SDL_FALSE); expected: %d, got: %"SDL_PRIs64, long_min, sresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError != NULL && SDL_strcmp(lastError, expectedError) == 0,
"SDL_GetError(): expected message '%s', was message: '%s'",
expectedError,
lastError);
/* Clear error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
return TEST_COMPLETED;
}
/*
* @brief Calls to random boundary number generators for Sint64
*/
int
sdltest_randomBoundaryNumberSint64(void *arg)
{
const char *expectedError = "That operation is not supported";
char *lastError;
Sint64 sresult;
/* Clean error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
/* RandomSintXBoundaryValue(10, 10, SDL_TRUE) returns 10 */
sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(10, 10, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint64BoundaryValue");
SDLTest_AssertCheck(
sresult == 10,
"Validate result value for parameters (10,10,SDL_TRUE); expected: 10, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(10, 11, SDL_TRUE) returns 10, 11 */
sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(10, 11, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint64BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11,
"Validate result value for parameters (10,11,SDL_TRUE); expected: 10|11, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(10, 12, SDL_TRUE) returns 10, 11, 12 */
sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(10, 12, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint64BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11 || sresult == 12,
"Validate result value for parameters (10,12,SDL_TRUE); expected: 10|11|12, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(10, 13, SDL_TRUE) returns 10, 11, 12, 13 */
sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(10, 13, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint64BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11 || sresult == 12 || sresult == 13,
"Validate result value for parameters (10,13,SDL_TRUE); expected: 10|11|12|13, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(10, 20, SDL_TRUE) returns 10, 11, 19 or 20 */
sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(10, 20, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint64BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11 || sresult == 19 || sresult == 20,
"Validate result value for parameters (10,20,SDL_TRUE); expected: 10|11|19|20, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(20, 10, SDL_TRUE) returns 10, 11, 19 or 20 */
sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(20, 10, SDL_TRUE);
SDLTest_AssertPass("Call to SDLTest_RandomSint64BoundaryValue");
SDLTest_AssertCheck(
sresult == 10 || sresult == 11 || sresult == 19 || sresult == 20,
"Validate result value for parameters (20,10,SDL_TRUE); expected: 10|11|19|20, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(1, 20, SDL_FALSE) returns 0, 21 */
sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(1, 20, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint64BoundaryValue");
SDLTest_AssertCheck(
sresult == 0 || sresult == 21,
"Validate result value for parameters (1,20,SDL_FALSE); expected: 0|21, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(LLONG_MIN, 99, SDL_FALSE) returns 100 */
sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(INT64_MIN, 99, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint64BoundaryValue");
SDLTest_AssertCheck(
sresult == 100,
"Validate result value for parameters (LLONG_MIN,99,SDL_FALSE); expected: 100, got: %"SDL_PRIs64, sresult);
/* RandomSintXBoundaryValue(LLONG_MIN + 1, LLONG_MAX, SDL_FALSE) returns LLONG_MIN (no error) */
sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(INT64_MIN + 1, INT64_MAX, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint64BoundaryValue");
SDLTest_AssertCheck(
sresult == INT64_MIN,
"Validate result value for parameters (LLONG_MIN+1,LLONG_MAX,SDL_FALSE); expected: %"SDL_PRIs64", got: %"SDL_PRIs64, INT64_MIN, sresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
/* RandomSintXBoundaryValue(LLONG_MIN, LLONG_MAX - 1, SDL_FALSE) returns LLONG_MAX (no error) */
sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(INT64_MIN, INT64_MAX - 1, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint64BoundaryValue");
SDLTest_AssertCheck(
sresult == INT64_MAX,
"Validate result value for parameters (LLONG_MIN,LLONG_MAX - 1,SDL_FALSE); expected: %"SDL_PRIs64", got: %"SDL_PRIs64, INT64_MAX, sresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
/* RandomSintXBoundaryValue(LLONG_MIN, LLONG_MAX, SDL_FALSE) returns 0 (sets error) */
sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(INT64_MIN, INT64_MAX, SDL_FALSE);
SDLTest_AssertPass("Call to SDLTest_RandomSint64BoundaryValue");
SDLTest_AssertCheck(
sresult == INT64_MIN,
"Validate result value for parameters(LLONG_MIN,LLONG_MAX,SDL_FALSE); expected: %"SDL_PRIs64", got: %"SDL_PRIs64, INT64_MIN, sresult);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError != NULL && SDL_strcmp(lastError, expectedError) == 0,
"SDL_GetError(): expected message '%s', was message: '%s'",
expectedError,
lastError);
/* Clear error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
return TEST_COMPLETED;
}
/**
* @brief Calls to SDLTest_RandomIntegerInRange
*/
int
sdltest_randomIntegerInRange(void *arg)
{
Sint32 min, max;
Sint32 result;
#if ((ULONG_MAX) == (UINT_MAX))
Sint32 long_min = LONG_MIN;
Sint32 long_max = LONG_MAX;
#else
Sint32 long_min = INT_MIN;
Sint32 long_max = INT_MAX;
#endif
/* Standard range */
min = (Sint32)SDLTest_RandomSint16();
max = min + (Sint32)SDLTest_RandomUint8() + 2;
result = SDLTest_RandomIntegerInRange(min, max);
SDLTest_AssertPass("Call to SDLTest_RandomIntegerInRange(min,max)");
SDLTest_AssertCheck(min <= result && result <= max, "Validated returned value; expected: [%d,%d], got: %d", min, max, result);
/* One Range */
min = (Sint32)SDLTest_RandomSint16();
max = min + 1;
result = SDLTest_RandomIntegerInRange(min, max);
SDLTest_AssertPass("Call to SDLTest_RandomIntegerInRange(min,min+1)");
SDLTest_AssertCheck(min <= result && result <= max, "Validated returned value; expected: [%d,%d], got: %d", min, max, result);
/* Zero range */
min = (Sint32)SDLTest_RandomSint16();
max = min;
result = SDLTest_RandomIntegerInRange(min, max);
SDLTest_AssertPass("Call to SDLTest_RandomIntegerInRange(min,min)");
SDLTest_AssertCheck(min == result, "Validated returned value; expected: %d, got: %d", min, result);
/* Zero range at zero */
min = 0;
max = 0;
result = SDLTest_RandomIntegerInRange(min, max);
SDLTest_AssertPass("Call to SDLTest_RandomIntegerInRange(0,0)");
SDLTest_AssertCheck(result == 0, "Validated returned value; expected: 0, got: %d", result);
/* Swapped min-max */
min = (Sint32)SDLTest_RandomSint16();
max = min + (Sint32)SDLTest_RandomUint8() + 2;
result = SDLTest_RandomIntegerInRange(max, min);
SDLTest_AssertPass("Call to SDLTest_RandomIntegerInRange(max,min)");
SDLTest_AssertCheck(min <= result && result <= max, "Validated returned value; expected: [%d,%d], got: %d", min, max, result);
/* Range with min at integer limit */
min = long_min;
max = long_max + (Sint32)SDLTest_RandomSint16();
result = SDLTest_RandomIntegerInRange(min, max);
SDLTest_AssertPass("Call to SDLTest_RandomIntegerInRange(SINT32_MIN,...)");
SDLTest_AssertCheck(min <= result && result <= max, "Validated returned value; expected: [%d,%d], got: %d", min, max, result);
/* Range with max at integer limit */
min = long_min - (Sint32)SDLTest_RandomSint16();
max = long_max;
result = SDLTest_RandomIntegerInRange(min, max);
SDLTest_AssertPass("Call to SDLTest_RandomIntegerInRange(...,SINT32_MAX)");
SDLTest_AssertCheck(min <= result && result <= max, "Validated returned value; expected: [%d,%d], got: %d", min, max, result);
/* Full integer range */
min = long_min;
max = long_max;
result = SDLTest_RandomIntegerInRange(min, max);
SDLTest_AssertPass("Call to SDLTest_RandomIntegerInRange(SINT32_MIN,SINT32_MAX)");
SDLTest_AssertCheck(min <= result && result <= max, "Validated returned value; expected: [%d,%d], got: %d", min, max, result);
return TEST_COMPLETED;
}
/**
* @brief Calls to SDLTest_RandomAsciiString
*/
int
sdltest_randomAsciiString(void *arg)
{
char* result;
size_t len;
int nonAsciiCharacters;
size_t i;
result = SDLTest_RandomAsciiString();
SDLTest_AssertPass("Call to SDLTest_RandomAsciiString()");
SDLTest_AssertCheck(result != NULL, "Validate that result is not NULL");
if (result != NULL) {
len = SDL_strlen(result);
SDLTest_AssertCheck(len >= 1 && len <= 255, "Validate that result length; expected: len=[1,255], got: %d", (int) len);
nonAsciiCharacters = 0;
for (i=0; i<len; i++) {
if (iscntrl(result[i])) {
nonAsciiCharacters++;
}
}
SDLTest_AssertCheck(nonAsciiCharacters == 0, "Validate that result does not contain non-Ascii characters, got: %d", nonAsciiCharacters);
if (nonAsciiCharacters) {
SDLTest_LogError("Invalid result from generator: '%s'", result);
}
SDL_free(result);
}
return TEST_COMPLETED;
}
/**
* @brief Calls to SDLTest_RandomAsciiStringWithMaximumLength
*/
int
sdltest_randomAsciiStringWithMaximumLength(void *arg)
{
const char* expectedError = "Parameter 'maxLength' is invalid";
char* lastError;
char* result;
size_t targetLen;
size_t len;
int nonAsciiCharacters;
size_t i;
targetLen = 16 + SDLTest_RandomUint8();
result = SDLTest_RandomAsciiStringWithMaximumLength((int) targetLen);
SDLTest_AssertPass("Call to SDLTest_RandomAsciiStringWithMaximumLength(%d)", (int) targetLen);
SDLTest_AssertCheck(result != NULL, "Validate that result is not NULL");
if (result != NULL) {
len = SDL_strlen(result);
SDLTest_AssertCheck(len >= 1 && len <= targetLen, "Validate that result length; expected: len=[1,%d], got: %d", (int) targetLen, (int) len);
nonAsciiCharacters = 0;
for (i=0; i<len; i++) {
if (iscntrl(result[i])) {
nonAsciiCharacters++;
}
}
SDLTest_AssertCheck(nonAsciiCharacters == 0, "Validate that result does not contain non-Ascii characters, got: %d", nonAsciiCharacters);
if (nonAsciiCharacters) {
SDLTest_LogError("Invalid result from generator: '%s'", result);
}
SDL_free(result);
}
/* Negative test */
targetLen = 0;
result = SDLTest_RandomAsciiStringWithMaximumLength((int) targetLen);
SDLTest_AssertPass("Call to SDLTest_RandomAsciiStringWithMaximumLength(%d)", (int) targetLen);
SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError != NULL && SDL_strcmp(lastError, expectedError) == 0,
"SDL_GetError(): expected message '%s', was message: '%s'",
expectedError,
lastError);
/* Clear error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
return TEST_COMPLETED;
}
/**
* @brief Calls to SDLTest_RandomAsciiStringOfSize
*/
int
sdltest_randomAsciiStringOfSize(void *arg)
{
const char* expectedError = "Parameter 'size' is invalid";
char* lastError;
char* result;
size_t targetLen;
size_t len;
int nonAsciiCharacters;
size_t i;
/* Positive test */
targetLen = 16 + SDLTest_RandomUint8();
result = SDLTest_RandomAsciiStringOfSize((int) targetLen);
SDLTest_AssertPass("Call to SDLTest_RandomAsciiStringOfSize(%d)", (int) targetLen);
SDLTest_AssertCheck(result != NULL, "Validate that result is not NULL");
if (result != NULL) {
len = SDL_strlen(result);
SDLTest_AssertCheck(len == targetLen, "Validate that result length; expected: len=%d, got: %d", (int) targetLen, (int) len);
nonAsciiCharacters = 0;
for (i=0; i<len; i++) {
if (iscntrl(result[i])) {
nonAsciiCharacters++;
}
}
SDLTest_AssertCheck(nonAsciiCharacters == 0, "Validate that result does not contain non-ASCII characters, got: %d", nonAsciiCharacters);
if (nonAsciiCharacters) {
SDLTest_LogError("Invalid result from generator: '%s'", result);
}
SDL_free(result);
}
/* Negative test */
targetLen = 0;
result = SDLTest_RandomAsciiStringOfSize((int) targetLen);
SDLTest_AssertPass("Call to SDLTest_RandomAsciiStringOfSize(%d)", (int) targetLen);
SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError != NULL && SDL_strcmp(lastError, expectedError) == 0,
"SDL_GetError(): expected message '%s', was message: '%s'",
expectedError,
lastError);
/* Clear error messages */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* SDL_test test cases */
static const SDLTest_TestCaseReference sdltestTest1 =
{ (SDLTest_TestCaseFp)sdltest_getFuzzerInvocationCount, "sdltest_getFuzzerInvocationCount", "Call to sdltest_GetFuzzerInvocationCount", TEST_ENABLED };
static const SDLTest_TestCaseReference sdltestTest2 =
{ (SDLTest_TestCaseFp)sdltest_randomNumber, "sdltest_randomNumber", "Calls to random number generators", TEST_ENABLED };
static const SDLTest_TestCaseReference sdltestTest3 =
{ (SDLTest_TestCaseFp)sdltest_randomBoundaryNumberUint8, "sdltest_randomBoundaryNumberUint8", "Calls to random boundary number generators for Uint8", TEST_ENABLED };
static const SDLTest_TestCaseReference sdltestTest4 =
{ (SDLTest_TestCaseFp)sdltest_randomBoundaryNumberUint16, "sdltest_randomBoundaryNumberUint16", "Calls to random boundary number generators for Uint16", TEST_ENABLED };
static const SDLTest_TestCaseReference sdltestTest5 =
{ (SDLTest_TestCaseFp)sdltest_randomBoundaryNumberUint32, "sdltest_randomBoundaryNumberUint32", "Calls to random boundary number generators for Uint32", TEST_ENABLED };
static const SDLTest_TestCaseReference sdltestTest6 =
{ (SDLTest_TestCaseFp)sdltest_randomBoundaryNumberUint64, "sdltest_randomBoundaryNumberUint64", "Calls to random boundary number generators for Uint64", TEST_ENABLED };
static const SDLTest_TestCaseReference sdltestTest7 =
{ (SDLTest_TestCaseFp)sdltest_randomBoundaryNumberSint8, "sdltest_randomBoundaryNumberSint8", "Calls to random boundary number generators for Sint8", TEST_ENABLED };
static const SDLTest_TestCaseReference sdltestTest8 =
{ (SDLTest_TestCaseFp)sdltest_randomBoundaryNumberSint16, "sdltest_randomBoundaryNumberSint16", "Calls to random boundary number generators for Sint16", TEST_ENABLED };
static const SDLTest_TestCaseReference sdltestTest9 =
{ (SDLTest_TestCaseFp)sdltest_randomBoundaryNumberSint32, "sdltest_randomBoundaryNumberSint32", "Calls to random boundary number generators for Sint32", TEST_ENABLED };
static const SDLTest_TestCaseReference sdltestTest10 =
{ (SDLTest_TestCaseFp)sdltest_randomBoundaryNumberSint64, "sdltest_randomBoundaryNumberSint64", "Calls to random boundary number generators for Sint64", TEST_ENABLED };
static const SDLTest_TestCaseReference sdltestTest11 =
{ (SDLTest_TestCaseFp)sdltest_randomIntegerInRange, "sdltest_randomIntegerInRange", "Calls to ranged random number generator", TEST_ENABLED };
static const SDLTest_TestCaseReference sdltestTest12 =
{ (SDLTest_TestCaseFp)sdltest_randomAsciiString, "sdltest_randomAsciiString", "Calls to default ASCII string generator", TEST_ENABLED };
static const SDLTest_TestCaseReference sdltestTest13 =
{ (SDLTest_TestCaseFp)sdltest_randomAsciiStringWithMaximumLength, "sdltest_randomAsciiStringWithMaximumLength", "Calls to random maximum length ASCII string generator", TEST_ENABLED };
static const SDLTest_TestCaseReference sdltestTest14 =
{ (SDLTest_TestCaseFp)sdltest_randomAsciiStringOfSize, "sdltest_randomAsciiStringOfSize", "Calls to fixed size ASCII string generator", TEST_ENABLED };
static const SDLTest_TestCaseReference sdltestTest15 =
{ (SDLTest_TestCaseFp)sdltest_generateRunSeed, "sdltest_generateRunSeed", "Checks internal harness function SDLTest_GenerateRunSeed", TEST_ENABLED };
/* Sequence of SDL_test test cases */
static const SDLTest_TestCaseReference *sdltestTests[] = {
&sdltestTest1, &sdltestTest2, &sdltestTest3, &sdltestTest4, &sdltestTest5, &sdltestTest6,
&sdltestTest7, &sdltestTest8, &sdltestTest9, &sdltestTest10, &sdltestTest11, &sdltestTest12,
&sdltestTest13, &sdltestTest14, &sdltestTest15, NULL
};
/* SDL_test test suite (global) */
SDLTest_TestSuiteReference sdltestTestSuite = {
"SDLtest",
NULL,
sdltestTests,
NULL
};
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_sdltest.c | C | apache-2.0 | 60,393 |
/**
* Standard C library routine test suite
*/
#include <stdio.h>
#include "SDL.h"
#include "SDL_test.h"
/* Test case functions */
/**
* @brief Call to SDL_strlcpy
*/
#undef SDL_strlcpy
int
stdlib_strlcpy(void *arg)
{
size_t result;
char text[1024];
const char *expected;
result = SDL_strlcpy(text, "foo", sizeof(text));
expected = "foo";
SDLTest_AssertPass("Call to SDL_strlcpy(\"foo\")");
SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), (int) result);
result = SDL_strlcpy(text, "foo", 2);
expected = "f";
SDLTest_AssertPass("Call to SDL_strlcpy(\"foo\") with buffer size 2");
SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
SDLTest_AssertCheck(result == 3, "Check result value, expected: 3, got: %d", (int) result);
return TEST_COMPLETED;
}
/**
* @brief Call to SDL_snprintf
*/
#undef SDL_snprintf
int
stdlib_snprintf(void *arg)
{
int result;
char text[1024];
const char *expected;
result = SDL_snprintf(text, sizeof(text), "%s", "foo");
expected = "foo";
SDLTest_AssertPass("Call to SDL_snprintf(\"%%s\", \"foo\")");
SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
result = SDL_snprintf(text, 2, "%s", "foo");
expected = "f";
SDLTest_AssertPass("Call to SDL_snprintf(\"%%s\", \"foo\") with buffer size 2");
SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
SDLTest_AssertCheck(result == 3, "Check result value, expected: 3, got: %d", result);
result = SDL_snprintf(NULL, 0, "%s", "foo");
SDLTest_AssertCheck(result == 3, "Check result value, expected: 3, got: %d", result);
result = SDL_snprintf(text, sizeof(text), "%f", 1.0);
expected = "1.000000";
SDLTest_AssertPass("Call to SDL_snprintf(\"%%f\", 1.0)");
SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
result = SDL_snprintf(text, sizeof(text), "%.f", 1.0);
expected = "1";
SDLTest_AssertPass("Call to SDL_snprintf(\"%%.f\", 1.0)");
SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
result = SDL_snprintf(text, sizeof(text), "%#.f", 1.0);
expected = "1.";
SDLTest_AssertPass("Call to SDL_snprintf(\"%%#.f\", 1.0)");
SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
result = SDL_snprintf(text, sizeof(text), "%f", 1.0 + 1.0 / 3.0);
expected = "1.333333";
SDLTest_AssertPass("Call to SDL_snprintf(\"%%f\", 1.0 + 1.0 / 3.0)");
SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
result = SDL_snprintf(text, sizeof(text), "%+f", 1.0 + 1.0 / 3.0);
expected = "+1.333333";
SDLTest_AssertPass("Call to SDL_snprintf(\"%%+f\", 1.0 + 1.0 / 3.0)");
SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
result = SDL_snprintf(text, sizeof(text), "%.2f", 1.0 + 1.0 / 3.0);
expected = "1.33";
SDLTest_AssertPass("Call to SDL_snprintf(\"%%.2f\", 1.0 + 1.0 / 3.0)");
SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
result = SDL_snprintf(text, sizeof(text), "%6.2f", 1.0 + 1.0 / 3.0);
expected = " 1.33";
SDLTest_AssertPass("Call to SDL_snprintf(\"%%6.2f\", 1.0 + 1.0 / 3.0)");
SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: '%s', got: '%s'", expected, text);
SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
result = SDL_snprintf(text, sizeof(text), "%06.2f", 1.0 + 1.0 / 3.0);
expected = "001.33";
SDLTest_AssertPass("Call to SDL_snprintf(\"%%06.2f\", 1.0 + 1.0 / 3.0)");
SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: '%s', got: '%s'", expected, text);
SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
result = SDL_snprintf(text, 5, "%06.2f", 1.0 + 1.0 / 3.0);
expected = "001.";
SDLTest_AssertPass("Call to SDL_snprintf(\"%%06.2f\", 1.0 + 1.0 / 3.0) with buffer size 5");
SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: '%s', got: '%s'", expected, text);
SDLTest_AssertCheck(result == 6, "Check result value, expected: 6, got: %d", result);
return TEST_COMPLETED;
}
/**
* @brief Call to SDL_getenv and SDL_setenv
*/
int
stdlib_getsetenv(void *arg)
{
const int nameLen = 16;
char name[17];
int counter;
int result;
char * value1;
char * value2;
char * expected;
int overwrite;
char * text;
/* Create a random name. This tests SDL_getenv, since we need to */
/* make sure the variable is not set yet (it shouldn't). */
do {
for(counter = 0; counter < nameLen; counter++) {
name[counter] = (char)SDLTest_RandomIntegerInRange(65, 90);
}
name[nameLen] = '\0';
text = SDL_getenv(name);
SDLTest_AssertPass("Call to SDL_getenv('%s')", name);
if (text != NULL) {
SDLTest_Log("Expected: NULL, Got: '%s' (%i)", text, (int) SDL_strlen(text));
}
} while (text != NULL);
/* Create random values to set */
value1 = SDLTest_RandomAsciiStringOfSize(10);
value2 = SDLTest_RandomAsciiStringOfSize(10);
/* Set value 1 without overwrite */
overwrite = 0;
expected = value1;
result = SDL_setenv(name, value1, overwrite);
SDLTest_AssertPass("Call to SDL_setenv('%s','%s', %i)", name, value1, overwrite);
SDLTest_AssertCheck(result == 0, "Check result, expected: 0, got: %i", result);
/* Check value */
text = SDL_getenv(name);
SDLTest_AssertPass("Call to SDL_getenv('%s')", name);
SDLTest_AssertCheck(text != NULL, "Verify returned text is not NULL");
if (text != NULL) {
SDLTest_AssertCheck(
SDL_strcmp(text, expected) == 0,
"Verify returned text, expected: %s, got: %s",
expected,
text);
}
/* Set value 2 with overwrite */
overwrite = 1;
expected = value2;
result = SDL_setenv(name, value2, overwrite);
SDLTest_AssertPass("Call to SDL_setenv('%s','%s', %i)", name, value2, overwrite);
SDLTest_AssertCheck(result == 0, "Check result, expected: 0, got: %i", result);
/* Check value */
text = SDL_getenv(name);
SDLTest_AssertPass("Call to SDL_getenv('%s')", name);
SDLTest_AssertCheck(text != NULL, "Verify returned text is not NULL");
if (text != NULL) {
SDLTest_AssertCheck(
SDL_strcmp(text, expected) == 0,
"Verify returned text, expected: %s, got: %s",
expected,
text);
}
/* Set value 1 without overwrite */
overwrite = 0;
expected = value2;
result = SDL_setenv(name, value1, overwrite);
SDLTest_AssertPass("Call to SDL_setenv('%s','%s', %i)", name, value1, overwrite);
SDLTest_AssertCheck(result == 0, "Check result, expected: 0, got: %i", result);
/* Check value */
text = SDL_getenv(name);
SDLTest_AssertPass("Call to SDL_getenv('%s')", name);
SDLTest_AssertCheck(text != NULL, "Verify returned text is not NULL");
if (text != NULL) {
SDLTest_AssertCheck(
SDL_strcmp(text, expected) == 0,
"Verify returned text, expected: %s, got: %s",
expected,
text);
}
/* Set value 1 without overwrite */
overwrite = 1;
expected = value1;
result = SDL_setenv(name, value1, overwrite);
SDLTest_AssertPass("Call to SDL_setenv('%s','%s', %i)", name, value1, overwrite);
SDLTest_AssertCheck(result == 0, "Check result, expected: 0, got: %i", result);
/* Check value */
text = SDL_getenv(name);
SDLTest_AssertPass("Call to SDL_getenv('%s')", name);
SDLTest_AssertCheck(text != NULL, "Verify returned text is not NULL");
if (text != NULL) {
SDLTest_AssertCheck(
SDL_strcmp(text, expected) == 0,
"Verify returned text, expected: %s, got: %s",
expected,
text);
}
/* Negative cases */
for (overwrite=0; overwrite <= 1; overwrite++) {
result = SDL_setenv(NULL, value1, overwrite);
SDLTest_AssertPass("Call to SDL_setenv(NULL,'%s', %i)", value1, overwrite);
SDLTest_AssertCheck(result == -1, "Check result, expected: -1, got: %i", result);
result = SDL_setenv("", value1, overwrite);
SDLTest_AssertPass("Call to SDL_setenv('','%s', %i)", value1, overwrite);
SDLTest_AssertCheck(result == -1, "Check result, expected: -1, got: %i", result);
result = SDL_setenv("=", value1, overwrite);
SDLTest_AssertPass("Call to SDL_setenv('=','%s', %i)", value1, overwrite);
SDLTest_AssertCheck(result == -1, "Check result, expected: -1, got: %i", result);
result = SDL_setenv(name, NULL, overwrite);
SDLTest_AssertPass("Call to SDL_setenv('%s', NULL, %i)", name, overwrite);
SDLTest_AssertCheck(result == -1, "Check result, expected: -1, got: %i", result);
}
/* Clean up */
SDL_free(value1);
SDL_free(value2);
return TEST_COMPLETED;
}
/**
* @brief Call to SDL_sscanf
*/
#undef SDL_sscanf
int
stdlib_sscanf(void *arg)
{
int output;
int result;
int expected_output;
int expected_result;
expected_output = output = 123;
expected_result = -1;
result = SDL_sscanf("", "%i", &output);
SDLTest_AssertPass("Call to SDL_sscanf(\"\", \"%%i\", &output)");
SDLTest_AssertCheck(expected_output == output, "Check output, expected: %i, got: %i", expected_output, output);
SDLTest_AssertCheck(expected_result == result, "Check return value, expected: %i, got: %i", expected_result, result);
expected_output = output = 123;
expected_result = 0;
result = SDL_sscanf("a", "%i", &output);
SDLTest_AssertPass("Call to SDL_sscanf(\"a\", \"%%i\", &output)");
SDLTest_AssertCheck(expected_output == output, "Check output, expected: %i, got: %i", expected_output, output);
SDLTest_AssertCheck(expected_result == result, "Check return value, expected: %i, got: %i", expected_result, result);
output = 123;
expected_output = 2;
expected_result = 1;
result = SDL_sscanf("2", "%i", &output);
SDLTest_AssertPass("Call to SDL_sscanf(\"2\", \"%%i\", &output)");
SDLTest_AssertCheck(expected_output == output, "Check output, expected: %i, got: %i", expected_output, output);
SDLTest_AssertCheck(expected_result == result, "Check return value, expected: %i, got: %i", expected_result, result);
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Standard C routine test cases */
static const SDLTest_TestCaseReference stdlibTest1 =
{ (SDLTest_TestCaseFp)stdlib_strlcpy, "stdlib_strlcpy", "Call to SDL_strlcpy", TEST_ENABLED };
static const SDLTest_TestCaseReference stdlibTest2 =
{ (SDLTest_TestCaseFp)stdlib_snprintf, "stdlib_snprintf", "Call to SDL_snprintf", TEST_ENABLED };
static const SDLTest_TestCaseReference stdlibTest3 =
{ (SDLTest_TestCaseFp)stdlib_getsetenv, "stdlib_getsetenv", "Call to SDL_getenv and SDL_setenv", TEST_ENABLED };
static const SDLTest_TestCaseReference stdlibTest4 =
{ (SDLTest_TestCaseFp)stdlib_sscanf, "stdlib_sscanf", "Call to SDL_sscanf", TEST_ENABLED };
/* Sequence of Standard C routine test cases */
static const SDLTest_TestCaseReference *stdlibTests[] = {
&stdlibTest1, &stdlibTest2, &stdlibTest3, &stdlibTest4, NULL
};
/* Standard C routine test suite (global) */
SDLTest_TestSuiteReference stdlibTestSuite = {
"Stdlib",
NULL,
stdlibTests,
NULL
};
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_stdlib.c | C | apache-2.0 | 12,593 |
/**
* Reference to all test suites.
*
*/
#ifndef _testsuites_h
#define _testsuites_h
#include "SDL_test.h"
/* Test collections */
extern SDLTest_TestSuiteReference audioTestSuite;
extern SDLTest_TestSuiteReference clipboardTestSuite;
extern SDLTest_TestSuiteReference eventsTestSuite;
extern SDLTest_TestSuiteReference keyboardTestSuite;
extern SDLTest_TestSuiteReference mainTestSuite;
extern SDLTest_TestSuiteReference mouseTestSuite;
extern SDLTest_TestSuiteReference pixelsTestSuite;
extern SDLTest_TestSuiteReference platformTestSuite;
extern SDLTest_TestSuiteReference rectTestSuite;
extern SDLTest_TestSuiteReference renderTestSuite;
extern SDLTest_TestSuiteReference rwopsTestSuite;
extern SDLTest_TestSuiteReference sdltestTestSuite;
extern SDLTest_TestSuiteReference stdlibTestSuite;
extern SDLTest_TestSuiteReference surfaceTestSuite;
extern SDLTest_TestSuiteReference syswmTestSuite;
extern SDLTest_TestSuiteReference timerTestSuite;
extern SDLTest_TestSuiteReference videoTestSuite;
extern SDLTest_TestSuiteReference hintsTestSuite;
/* All test suites */
SDLTest_TestSuiteReference *testSuites[] = {
&audioTestSuite,
&clipboardTestSuite,
&eventsTestSuite,
&keyboardTestSuite,
&mainTestSuite,
&mouseTestSuite,
&pixelsTestSuite,
&platformTestSuite,
&rectTestSuite,
&renderTestSuite,
&rwopsTestSuite,
&sdltestTestSuite,
&stdlibTestSuite,
&surfaceTestSuite,
&syswmTestSuite,
&timerTestSuite,
&videoTestSuite,
&hintsTestSuite,
NULL
};
#endif
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_suites.h | C | apache-2.0 | 1,535 |
/**
* Original code: automated SDL surface test written by Edgar Simo "bobbens"
* Adapted/rewritten for test lib by Andreas Schiffler
*/
/* Supress C4996 VS compiler warnings for unlink() */
#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_NONSTDC_NO_DEPRECATE
#include <stdio.h>
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <sys/stat.h>
#include "SDL.h"
#include "SDL_test.h"
#ifdef __MACOSX__
#include <unistd.h> /* For unlink() */
#endif
/* ================= Test Case Implementation ================== */
/* Shared test surface */
static SDL_Surface *referenceSurface = NULL;
static SDL_Surface *testSurface = NULL;
/* Helper functions for the test cases */
#define TEST_SURFACE_WIDTH testSurface->w
#define TEST_SURFACE_HEIGHT testSurface->h
/* Fixture */
/* Create a 32-bit writable surface for blitting tests */
void
_surfaceSetUp(void *arg)
{
int result;
SDL_BlendMode blendMode = SDL_BLENDMODE_NONE;
SDL_BlendMode currentBlendMode;
Uint32 rmask, gmask, bmask, amask;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
rmask = 0xff000000;
gmask = 0x00ff0000;
bmask = 0x0000ff00;
amask = 0x000000ff;
#else
rmask = 0x000000ff;
gmask = 0x0000ff00;
bmask = 0x00ff0000;
amask = 0xff000000;
#endif
referenceSurface = SDLTest_ImageBlit(); /* For size info */
testSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, referenceSurface->w, referenceSurface->h, 32, rmask, gmask, bmask, amask);
SDLTest_AssertCheck(testSurface != NULL, "Check that testSurface is not NULL");
if (testSurface != NULL) {
/* Disable blend mode for target surface */
result = SDL_SetSurfaceBlendMode(testSurface, blendMode);
SDLTest_AssertCheck(result == 0, "Validate result from SDL_SetSurfaceBlendMode, expected: 0, got: %i", result);
result = SDL_GetSurfaceBlendMode(testSurface, ¤tBlendMode);
SDLTest_AssertCheck(result == 0, "Validate result from SDL_GetSurfaceBlendMode, expected: 0, got: %i", result);
SDLTest_AssertCheck(currentBlendMode == blendMode, "Validate blendMode, expected: %i, got: %i", blendMode, currentBlendMode);
}
}
void
_surfaceTearDown(void *arg)
{
SDL_FreeSurface(referenceSurface);
referenceSurface = NULL;
SDL_FreeSurface(testSurface);
testSurface = NULL;
}
/**
* Helper that clears the test surface
*/
void _clearTestSurface()
{
int ret;
Uint32 color;
/* Clear surface. */
color = SDL_MapRGBA( testSurface->format, 0, 0, 0, 0);
SDLTest_AssertPass("Call to SDL_MapRGBA()");
ret = SDL_FillRect( testSurface, NULL, color);
SDLTest_AssertPass("Call to SDL_FillRect()");
SDLTest_AssertCheck(ret == 0, "Verify result from SDL_FillRect, expected: 0, got: %i", ret);
}
/**
* Helper that blits in a specific blend mode, -1 for basic blitting, -2 for color mod, -3 for alpha mod, -4 for mixed blend modes.
*/
void _testBlitBlendMode(int mode)
{
int ret;
int i, j, ni, nj;
SDL_Surface *face;
SDL_Rect rect;
int nmode;
SDL_BlendMode bmode;
int checkFailCount1;
int checkFailCount2;
int checkFailCount3;
int checkFailCount4;
/* Check test surface */
SDLTest_AssertCheck(testSurface != NULL, "Verify testSurface is not NULL");
if (testSurface == NULL) return;
/* Create sample surface */
face = SDLTest_ImageFace();
SDLTest_AssertCheck(face != NULL, "Verify face surface is not NULL");
if (face == NULL) return;
/* Reset alpha modulation */
ret = SDL_SetSurfaceAlphaMod(face, 255);
SDLTest_AssertPass("Call to SDL_SetSurfaceAlphaMod()");
SDLTest_AssertCheck(ret == 0, "Verify result from SDL_SetSurfaceAlphaMod(), expected: 0, got: %i", ret);
/* Reset color modulation */
ret = SDL_SetSurfaceColorMod(face, 255, 255, 255);
SDLTest_AssertPass("Call to SDL_SetSurfaceColorMod()");
SDLTest_AssertCheck(ret == 0, "Verify result from SDL_SetSurfaceColorMod(), expected: 0, got: %i", ret);
/* Reset color key */
ret = SDL_SetColorKey(face, SDL_FALSE, 0);
SDLTest_AssertPass("Call to SDL_SetColorKey()");
SDLTest_AssertCheck(ret == 0, "Verify result from SDL_SetColorKey(), expected: 0, got: %i", ret);
/* Clear the test surface */
_clearTestSurface();
/* Target rect size */
rect.w = face->w;
rect.h = face->h;
/* Steps to take */
ni = testSurface->w - face->w;
nj = testSurface->h - face->h;
/* Optionally set blend mode. */
if (mode >= 0) {
ret = SDL_SetSurfaceBlendMode( face, (SDL_BlendMode)mode );
SDLTest_AssertPass("Call to SDL_SetSurfaceBlendMode()");
SDLTest_AssertCheck(ret == 0, "Verify result from SDL_SetSurfaceBlendMode(..., %i), expected: 0, got: %i", mode, ret);
}
/* Test blend mode. */
checkFailCount1 = 0;
checkFailCount2 = 0;
checkFailCount3 = 0;
checkFailCount4 = 0;
for (j=0; j <= nj; j+=4) {
for (i=0; i <= ni; i+=4) {
if (mode == -2) {
/* Set color mod. */
ret = SDL_SetSurfaceColorMod( face, (255/nj)*j, (255/ni)*i, (255/nj)*j );
if (ret != 0) checkFailCount2++;
}
else if (mode == -3) {
/* Set alpha mod. */
ret = SDL_SetSurfaceAlphaMod( face, (255/ni)*i );
if (ret != 0) checkFailCount3++;
}
else if (mode == -4) {
/* Crazy blending mode magic. */
nmode = (i/4*j/4) % 4;
if (nmode==0) {
bmode = SDL_BLENDMODE_NONE;
} else if (nmode==1) {
bmode = SDL_BLENDMODE_BLEND;
} else if (nmode==2) {
bmode = SDL_BLENDMODE_ADD;
} else if (nmode==3) {
bmode = SDL_BLENDMODE_MOD;
}
ret = SDL_SetSurfaceBlendMode( face, bmode );
if (ret != 0) checkFailCount4++;
}
/* Blitting. */
rect.x = i;
rect.y = j;
ret = SDL_BlitSurface( face, NULL, testSurface, &rect );
if (ret != 0) checkFailCount1++;
}
}
SDLTest_AssertCheck(checkFailCount1 == 0, "Validate results from calls to SDL_BlitSurface, expected: 0, got: %i", checkFailCount1);
SDLTest_AssertCheck(checkFailCount2 == 0, "Validate results from calls to SDL_SetSurfaceColorMod, expected: 0, got: %i", checkFailCount2);
SDLTest_AssertCheck(checkFailCount3 == 0, "Validate results from calls to SDL_SetSurfaceAlphaMod, expected: 0, got: %i", checkFailCount3);
SDLTest_AssertCheck(checkFailCount4 == 0, "Validate results from calls to SDL_SetSurfaceBlendMode, expected: 0, got: %i", checkFailCount4);
/* Clean up */
SDL_FreeSurface(face);
face = NULL;
}
/* Helper to check that a file exists */
void
_AssertFileExist(const char *filename)
{
struct stat st;
int ret = stat(filename, &st);
SDLTest_AssertCheck(ret == 0, "Verify file '%s' exists", filename);
}
/* Test case functions */
/**
* @brief Tests sprite saving and loading
*/
int
surface_testSaveLoadBitmap(void *arg)
{
int ret;
const char *sampleFilename = "testSaveLoadBitmap.bmp";
SDL_Surface *face;
SDL_Surface *rface;
/* Create sample surface */
face = SDLTest_ImageFace();
SDLTest_AssertCheck(face != NULL, "Verify face surface is not NULL");
if (face == NULL) return TEST_ABORTED;
/* Delete test file; ignore errors */
unlink(sampleFilename);
/* Save a surface */
ret = SDL_SaveBMP(face, sampleFilename);
SDLTest_AssertPass("Call to SDL_SaveBMP()");
SDLTest_AssertCheck(ret == 0, "Verify result from SDL_SaveBMP, expected: 0, got: %i", ret);
_AssertFileExist(sampleFilename);
/* Load a surface */
rface = SDL_LoadBMP(sampleFilename);
SDLTest_AssertPass("Call to SDL_LoadBMP()");
SDLTest_AssertCheck(rface != NULL, "Verify result from SDL_LoadBMP is not NULL");
if (rface != NULL) {
SDLTest_AssertCheck(face->w == rface->w, "Verify width of loaded surface, expected: %i, got: %i", face->w, rface->w);
SDLTest_AssertCheck(face->h == rface->h, "Verify height of loaded surface, expected: %i, got: %i", face->h, rface->h);
}
/* Delete test file; ignore errors */
unlink(sampleFilename);
/* Clean up */
SDL_FreeSurface(face);
face = NULL;
SDL_FreeSurface(rface);
rface = NULL;
return TEST_COMPLETED;
}
/* !
* Tests surface conversion.
*/
int
surface_testSurfaceConversion(void *arg)
{
SDL_Surface *rface = NULL, *face = NULL;
int ret = 0;
/* Create sample surface */
face = SDLTest_ImageFace();
SDLTest_AssertCheck(face != NULL, "Verify face surface is not NULL");
if (face == NULL)
return TEST_ABORTED;
/* Set transparent pixel as the pixel at (0,0) */
if (face->format->palette) {
ret = SDL_SetColorKey(face, SDL_RLEACCEL, *(Uint8 *) face->pixels);
SDLTest_AssertPass("Call to SDL_SetColorKey()");
SDLTest_AssertCheck(ret == 0, "Verify result from SDL_SetColorKey, expected: 0, got: %i", ret);
}
/* Convert to 32 bit to compare. */
rface = SDL_ConvertSurface( face, testSurface->format, 0 );
SDLTest_AssertPass("Call to SDL_ConvertSurface()");
SDLTest_AssertCheck(rface != NULL, "Verify result from SDL_ConvertSurface is not NULL");
/* Compare surface. */
ret = SDLTest_CompareSurfaces( rface, face, 0 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDLTest_CompareSurfaces, expected: 0, got: %i", ret);
/* Clean up. */
SDL_FreeSurface(face);
face = NULL;
SDL_FreeSurface(rface);
rface = NULL;
return TEST_COMPLETED;
}
/* !
* Tests surface conversion across all pixel formats.
*/
int
surface_testCompleteSurfaceConversion(void *arg)
{
Uint32 pixel_formats[] = {
SDL_PIXELFORMAT_INDEX8,
SDL_PIXELFORMAT_RGB332,
SDL_PIXELFORMAT_RGB444,
SDL_PIXELFORMAT_BGR444,
SDL_PIXELFORMAT_RGB555,
SDL_PIXELFORMAT_BGR555,
SDL_PIXELFORMAT_ARGB4444,
SDL_PIXELFORMAT_RGBA4444,
SDL_PIXELFORMAT_ABGR4444,
SDL_PIXELFORMAT_BGRA4444,
SDL_PIXELFORMAT_ARGB1555,
SDL_PIXELFORMAT_RGBA5551,
SDL_PIXELFORMAT_ABGR1555,
SDL_PIXELFORMAT_BGRA5551,
SDL_PIXELFORMAT_RGB565,
SDL_PIXELFORMAT_BGR565,
SDL_PIXELFORMAT_RGB24,
SDL_PIXELFORMAT_BGR24,
SDL_PIXELFORMAT_RGB888,
SDL_PIXELFORMAT_RGBX8888,
SDL_PIXELFORMAT_BGR888,
SDL_PIXELFORMAT_BGRX8888,
SDL_PIXELFORMAT_ARGB8888,
SDL_PIXELFORMAT_RGBA8888,
SDL_PIXELFORMAT_ABGR8888,
SDL_PIXELFORMAT_BGRA8888,
SDL_PIXELFORMAT_ARGB2101010,
};
SDL_Surface *face = NULL, *cvt1, *cvt2, *final;
SDL_PixelFormat *fmt1, *fmt2;
int i, j, ret = 0;
/* Create sample surface */
face = SDLTest_ImageFace();
SDLTest_AssertCheck(face != NULL, "Verify face surface is not NULL");
if (face == NULL)
return TEST_ABORTED;
/* Set transparent pixel as the pixel at (0,0) */
if (face->format->palette) {
ret = SDL_SetColorKey(face, SDL_RLEACCEL, *(Uint8 *) face->pixels);
SDLTest_AssertPass("Call to SDL_SetColorKey()");
SDLTest_AssertCheck(ret == 0, "Verify result from SDL_SetColorKey, expected: 0, got: %i", ret);
}
for ( i = 0; i < SDL_arraysize(pixel_formats); ++i ) {
for ( j = 0; j < SDL_arraysize(pixel_formats); ++j ) {
fmt1 = SDL_AllocFormat(pixel_formats[i]);
SDL_assert(fmt1 != NULL);
cvt1 = SDL_ConvertSurface(face, fmt1, 0);
SDL_assert(cvt1 != NULL);
fmt2 = SDL_AllocFormat(pixel_formats[j]);
SDL_assert(fmt1 != NULL);
cvt2 = SDL_ConvertSurface(cvt1, fmt2, 0);
SDL_assert(cvt2 != NULL);
if ( fmt1->BytesPerPixel == face->format->BytesPerPixel &&
fmt2->BytesPerPixel == face->format->BytesPerPixel &&
(fmt1->Amask != 0) == (face->format->Amask != 0) &&
(fmt2->Amask != 0) == (face->format->Amask != 0) ) {
final = SDL_ConvertSurface( cvt2, face->format, 0 );
SDL_assert(final != NULL);
/* Compare surface. */
ret = SDLTest_CompareSurfaces( face, final, 0 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDLTest_CompareSurfaces, expected: 0, got: %i", ret);
SDL_FreeSurface(final);
}
SDL_FreeSurface(cvt1);
SDL_FreeFormat(fmt1);
SDL_FreeSurface(cvt2);
SDL_FreeFormat(fmt2);
}
}
/* Clean up. */
SDL_FreeSurface( face );
return TEST_COMPLETED;
}
/**
* @brief Tests sprite loading. A failure case.
*/
int
surface_testLoadFailure(void *arg)
{
SDL_Surface *face = SDL_LoadBMP("nonexistant.bmp");
SDLTest_AssertCheck(face == NULL, "SDL_CreateLoadBmp");
return TEST_COMPLETED;
}
/**
* @brief Tests some blitting routines.
*/
int
surface_testBlit(void *arg)
{
int ret;
SDL_Surface *compareSurface;
/* Basic blitting */
_testBlitBlendMode(-1);
/* Verify result by comparing surfaces */
compareSurface = SDLTest_ImageBlit();
ret = SDLTest_CompareSurfaces( testSurface, compareSurface, 0 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDLTest_CompareSurfaces, expected: 0, got: %i", ret);
/* Clean up. */
SDL_FreeSurface(compareSurface);
return TEST_COMPLETED;
}
/**
* @brief Tests some blitting routines with color mod
*/
int
surface_testBlitColorMod(void *arg)
{
int ret;
SDL_Surface *compareSurface;
/* Basic blitting with color mod */
_testBlitBlendMode(-2);
/* Verify result by comparing surfaces */
compareSurface = SDLTest_ImageBlitColor();
ret = SDLTest_CompareSurfaces( testSurface, compareSurface, 0 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDLTest_CompareSurfaces, expected: 0, got: %i", ret);
/* Clean up. */
SDL_FreeSurface(compareSurface);
return TEST_COMPLETED;
}
/**
* @brief Tests some blitting routines with alpha mod
*/
int
surface_testBlitAlphaMod(void *arg)
{
int ret;
SDL_Surface *compareSurface;
/* Basic blitting with alpha mod */
_testBlitBlendMode(-3);
/* Verify result by comparing surfaces */
compareSurface = SDLTest_ImageBlitAlpha();
ret = SDLTest_CompareSurfaces( testSurface, compareSurface, 0 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDLTest_CompareSurfaces, expected: 0, got: %i", ret);
/* Clean up. */
SDL_FreeSurface(compareSurface);
return TEST_COMPLETED;
}
/**
* @brief Tests some more blitting routines.
*/
int
surface_testBlitBlendNone(void *arg)
{
int ret;
SDL_Surface *compareSurface;
/* Basic blitting */
_testBlitBlendMode(SDL_BLENDMODE_NONE);
/* Verify result by comparing surfaces */
compareSurface = SDLTest_ImageBlitBlendNone();
ret = SDLTest_CompareSurfaces( testSurface, compareSurface, 0 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDLTest_CompareSurfaces, expected: 0, got: %i", ret);
/* Clean up. */
SDL_FreeSurface(compareSurface);
return TEST_COMPLETED;
}
/**
* @brief Tests some more blitting routines.
*/
int
surface_testBlitBlendBlend(void *arg)
{
int ret;
SDL_Surface *compareSurface;
/* Blend blitting */
_testBlitBlendMode(SDL_BLENDMODE_BLEND);
/* Verify result by comparing surfaces */
compareSurface = SDLTest_ImageBlitBlend();
ret = SDLTest_CompareSurfaces( testSurface, compareSurface, 0 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDLTest_CompareSurfaces, expected: 0, got: %i", ret);
/* Clean up. */
SDL_FreeSurface(compareSurface);
return TEST_COMPLETED;
}
/**
* @brief Tests some more blitting routines.
*/
int
surface_testBlitBlendAdd(void *arg)
{
int ret;
SDL_Surface *compareSurface;
/* Add blitting */
_testBlitBlendMode(SDL_BLENDMODE_ADD);
/* Verify result by comparing surfaces */
compareSurface = SDLTest_ImageBlitBlendAdd();
ret = SDLTest_CompareSurfaces( testSurface, compareSurface, 0 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDLTest_CompareSurfaces, expected: 0, got: %i", ret);
/* Clean up. */
SDL_FreeSurface(compareSurface);
return TEST_COMPLETED;
}
/**
* @brief Tests some more blitting routines.
*/
int
surface_testBlitBlendMod(void *arg)
{
int ret;
SDL_Surface *compareSurface;
/* Mod blitting */
_testBlitBlendMode(SDL_BLENDMODE_MOD);
/* Verify result by comparing surfaces */
compareSurface = SDLTest_ImageBlitBlendMod();
ret = SDLTest_CompareSurfaces( testSurface, compareSurface, 0 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDLTest_CompareSurfaces, expected: 0, got: %i", ret);
/* Clean up. */
SDL_FreeSurface(compareSurface);
return TEST_COMPLETED;
}
/**
* @brief Tests some more blitting routines with loop
*/
int
surface_testBlitBlendLoop(void *arg) {
int ret;
SDL_Surface *compareSurface;
/* All blitting modes */
_testBlitBlendMode(-4);
/* Verify result by comparing surfaces */
compareSurface = SDLTest_ImageBlitBlendAll();
ret = SDLTest_CompareSurfaces( testSurface, compareSurface, 0 );
SDLTest_AssertCheck(ret == 0, "Validate result from SDLTest_CompareSurfaces, expected: 0, got: %i", ret);
/* Clean up. */
SDL_FreeSurface(compareSurface);
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Surface test cases */
static const SDLTest_TestCaseReference surfaceTest1 =
{ (SDLTest_TestCaseFp)surface_testSaveLoadBitmap, "surface_testSaveLoadBitmap", "Tests sprite saving and loading.", TEST_ENABLED};
static const SDLTest_TestCaseReference surfaceTest2 =
{ (SDLTest_TestCaseFp)surface_testBlit, "surface_testBlit", "Tests basic blitting.", TEST_ENABLED};
static const SDLTest_TestCaseReference surfaceTest3 =
{ (SDLTest_TestCaseFp)surface_testBlitBlendNone, "surface_testBlitBlendNone", "Tests blitting routines with none blending mode.", TEST_ENABLED};
static const SDLTest_TestCaseReference surfaceTest4 =
{ (SDLTest_TestCaseFp)surface_testLoadFailure, "surface_testLoadFailure", "Tests sprite loading. A failure case.", TEST_ENABLED};
static const SDLTest_TestCaseReference surfaceTest5 =
{ (SDLTest_TestCaseFp)surface_testSurfaceConversion, "surface_testSurfaceConversion", "Tests surface conversion.", TEST_ENABLED};
static const SDLTest_TestCaseReference surfaceTest6 =
{ (SDLTest_TestCaseFp)surface_testCompleteSurfaceConversion, "surface_testCompleteSurfaceConversion", "Tests surface conversion across all pixel formats", TEST_ENABLED};
static const SDLTest_TestCaseReference surfaceTest7 =
{ (SDLTest_TestCaseFp)surface_testBlitColorMod, "surface_testBlitColorMod", "Tests some blitting routines with color mod.", TEST_ENABLED};
static const SDLTest_TestCaseReference surfaceTest8 =
{ (SDLTest_TestCaseFp)surface_testBlitAlphaMod, "surface_testBlitAlphaMod", "Tests some blitting routines with alpha mod.", TEST_ENABLED};
/* TODO: rewrite test case, define new test data and re-enable; current implementation fails */
static const SDLTest_TestCaseReference surfaceTest9 =
{ (SDLTest_TestCaseFp)surface_testBlitBlendLoop, "surface_testBlitBlendLoop", "Test blitting routines with various blending modes", TEST_DISABLED};
/* TODO: rewrite test case, define new test data and re-enable; current implementation fails */
static const SDLTest_TestCaseReference surfaceTest10 =
{ (SDLTest_TestCaseFp)surface_testBlitBlendBlend, "surface_testBlitBlendBlend", "Tests blitting routines with blend blending mode.", TEST_DISABLED};
/* TODO: rewrite test case, define new test data and re-enable; current implementation fails */
static const SDLTest_TestCaseReference surfaceTest11 =
{ (SDLTest_TestCaseFp)surface_testBlitBlendAdd, "surface_testBlitBlendAdd", "Tests blitting routines with add blending mode.", TEST_DISABLED};
static const SDLTest_TestCaseReference surfaceTest12 =
{ (SDLTest_TestCaseFp)surface_testBlitBlendMod, "surface_testBlitBlendMod", "Tests blitting routines with mod blending mode.", TEST_ENABLED};
/* Sequence of Surface test cases */
static const SDLTest_TestCaseReference *surfaceTests[] = {
&surfaceTest1, &surfaceTest2, &surfaceTest3, &surfaceTest4, &surfaceTest5,
&surfaceTest6, &surfaceTest7, &surfaceTest8, &surfaceTest9, &surfaceTest10,
&surfaceTest11, &surfaceTest12, NULL
};
/* Surface test suite (global) */
SDLTest_TestSuiteReference surfaceTestSuite = {
"Surface",
_surfaceSetUp,
surfaceTests,
_surfaceTearDown
};
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_surface.c | C | apache-2.0 | 20,674 |
/**
* SysWM test suite
*/
#include <stdio.h>
#include "SDL.h"
#include "SDL_syswm.h"
#include "SDL_test.h"
/* Test case functions */
/**
* @brief Call to SDL_GetWindowWMInfo
*/
int
syswm_getWindowWMInfo(void *arg)
{
SDL_bool result;
SDL_Window *window;
SDL_SysWMinfo info;
window = SDL_CreateWindow("", 0, 0, 0, 0, SDL_WINDOW_HIDDEN);
SDLTest_AssertPass("Call to SDL_CreateWindow()");
SDLTest_AssertCheck(window != NULL, "Check that value returned from SDL_CreateWindow is not NULL");
if (window == NULL) {
return TEST_ABORTED;
}
/* Initialize info structure with SDL version info */
SDL_VERSION(&info.version);
/* Make call */
result = SDL_GetWindowWMInfo(window, &info);
SDLTest_AssertPass("Call to SDL_GetWindowWMInfo()");
SDLTest_Log((result == SDL_TRUE) ? "Got window information" : "Couldn't get window information");
SDL_DestroyWindow(window);
SDLTest_AssertPass("Call to SDL_DestroyWindow()");
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* SysWM test cases */
static const SDLTest_TestCaseReference syswmTest1 =
{ (SDLTest_TestCaseFp)syswm_getWindowWMInfo, "syswm_getWindowWMInfo", "Call to SDL_GetWindowWMInfo", TEST_ENABLED };
/* Sequence of SysWM test cases */
static const SDLTest_TestCaseReference *syswmTests[] = {
&syswmTest1, NULL
};
/* SysWM test suite (global) */
SDLTest_TestSuiteReference syswmTestSuite = {
"SysWM",
NULL,
syswmTests,
NULL
};
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_syswm.c | C | apache-2.0 | 1,489 |
/**
* Timer test suite
*/
#include <stdio.h>
#include "SDL.h"
#include "SDL_test.h"
/* Flag indicating if the param should be checked */
int _paramCheck = 0;
/* Userdata value to check */
int _paramValue = 0;
/* Flag indicating that the callback was called */
int _timerCallbackCalled = 0;
/* Fixture */
void
_timerSetUp(void *arg)
{
/* Start SDL timer subsystem */
int ret = SDL_InitSubSystem( SDL_INIT_TIMER );
SDLTest_AssertPass("Call to SDL_InitSubSystem(SDL_INIT_TIMER)");
SDLTest_AssertCheck(ret==0, "Check result from SDL_InitSubSystem(SDL_INIT_TIMER)");
if (ret != 0) {
SDLTest_LogError("%s", SDL_GetError());
}
}
/* Test case functions */
/**
* @brief Call to SDL_GetPerformanceCounter
*/
int
timer_getPerformanceCounter(void *arg)
{
Uint64 result;
result = SDL_GetPerformanceCounter();
SDLTest_AssertPass("Call to SDL_GetPerformanceCounter()");
SDLTest_AssertCheck(result > 0, "Check result value, expected: >0, got: %"SDL_PRIu64, result);
return TEST_COMPLETED;
}
/**
* @brief Call to SDL_GetPerformanceFrequency
*/
int
timer_getPerformanceFrequency(void *arg)
{
Uint64 result;
result = SDL_GetPerformanceFrequency();
SDLTest_AssertPass("Call to SDL_GetPerformanceFrequency()");
SDLTest_AssertCheck(result > 0, "Check result value, expected: >0, got: %"SDL_PRIu64, result);
return TEST_COMPLETED;
}
/**
* @brief Call to SDL_Delay and SDL_GetTicks
*/
int
timer_delayAndGetTicks(void *arg)
{
const Uint32 testDelay = 100;
const Uint32 marginOfError = 25;
Uint32 result;
Uint32 result2;
Uint32 difference;
/* Zero delay */
SDL_Delay(0);
SDLTest_AssertPass("Call to SDL_Delay(0)");
/* Non-zero delay */
SDL_Delay(1);
SDLTest_AssertPass("Call to SDL_Delay(1)");
SDL_Delay(SDLTest_RandomIntegerInRange(5, 15));
SDLTest_AssertPass("Call to SDL_Delay()");
/* Get ticks count - should be non-zero by now */
result = SDL_GetTicks();
SDLTest_AssertPass("Call to SDL_GetTicks()");
SDLTest_AssertCheck(result > 0, "Check result value, expected: >0, got: %d", result);
/* Delay a bit longer and measure ticks and verify difference */
SDL_Delay(testDelay);
SDLTest_AssertPass("Call to SDL_Delay(%d)", testDelay);
result2 = SDL_GetTicks();
SDLTest_AssertPass("Call to SDL_GetTicks()");
SDLTest_AssertCheck(result2 > 0, "Check result value, expected: >0, got: %d", result2);
difference = result2 - result;
SDLTest_AssertCheck(difference > (testDelay - marginOfError), "Check difference, expected: >%d, got: %d", testDelay - marginOfError, difference);
SDLTest_AssertCheck(difference < (testDelay + marginOfError), "Check difference, expected: <%d, got: %d", testDelay + marginOfError, difference);
return TEST_COMPLETED;
}
/* Test callback */
Uint32 SDLCALL _timerTestCallback(Uint32 interval, void *param)
{
_timerCallbackCalled = 1;
if (_paramCheck != 0) {
SDLTest_AssertCheck(param != NULL, "Check param pointer, expected: non-NULL, got: %s", (param != NULL) ? "non-NULL" : "NULL");
if (param != NULL) {
SDLTest_AssertCheck(*(int *)param == _paramValue, "Check param value, expected: %i, got: %i", _paramValue, *(int *)param);
}
}
return 0;
}
/**
* @brief Call to SDL_AddTimer and SDL_RemoveTimer
*/
int
timer_addRemoveTimer(void *arg)
{
SDL_TimerID id;
SDL_bool result;
int param;
/* Reset state */
_paramCheck = 0;
_timerCallbackCalled = 0;
/* Set timer with a long delay */
id = SDL_AddTimer(10000, _timerTestCallback, NULL);
SDLTest_AssertPass("Call to SDL_AddTimer(10000,...)");
SDLTest_AssertCheck(id > 0, "Check result value, expected: >0, got: %d", id);
/* Remove timer again and check that callback was not called */
result = SDL_RemoveTimer(id);
SDLTest_AssertPass("Call to SDL_RemoveTimer()");
SDLTest_AssertCheck(result == SDL_TRUE, "Check result value, expected: %i, got: %i", SDL_TRUE, result);
SDLTest_AssertCheck(_timerCallbackCalled == 0, "Check callback WAS NOT called, expected: 0, got: %i", _timerCallbackCalled);
/* Try to remove timer again (should be a NOOP) */
result = SDL_RemoveTimer(id);
SDLTest_AssertPass("Call to SDL_RemoveTimer()");
SDLTest_AssertCheck(result == SDL_FALSE, "Check result value, expected: %i, got: %i", SDL_FALSE, result);
/* Reset state */
param = SDLTest_RandomIntegerInRange(-1024, 1024);
_paramCheck = 1;
_paramValue = param;
_timerCallbackCalled = 0;
/* Set timer with a short delay */
id = SDL_AddTimer(10, _timerTestCallback, (void *)¶m);
SDLTest_AssertPass("Call to SDL_AddTimer(10, param)");
SDLTest_AssertCheck(id > 0, "Check result value, expected: >0, got: %d", id);
/* Wait to let timer trigger callback */
SDL_Delay(100);
SDLTest_AssertPass("Call to SDL_Delay(100)");
/* Remove timer again and check that callback was called */
result = SDL_RemoveTimer(id);
SDLTest_AssertPass("Call to SDL_RemoveTimer()");
SDLTest_AssertCheck(result == SDL_FALSE, "Check result value, expected: %i, got: %i", SDL_FALSE, result);
SDLTest_AssertCheck(_timerCallbackCalled == 1, "Check callback WAS called, expected: 1, got: %i", _timerCallbackCalled);
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Timer test cases */
static const SDLTest_TestCaseReference timerTest1 =
{ (SDLTest_TestCaseFp)timer_getPerformanceCounter, "timer_getPerformanceCounter", "Call to SDL_GetPerformanceCounter", TEST_ENABLED };
static const SDLTest_TestCaseReference timerTest2 =
{ (SDLTest_TestCaseFp)timer_getPerformanceFrequency, "timer_getPerformanceFrequency", "Call to SDL_GetPerformanceFrequency", TEST_ENABLED };
static const SDLTest_TestCaseReference timerTest3 =
{ (SDLTest_TestCaseFp)timer_delayAndGetTicks, "timer_delayAndGetTicks", "Call to SDL_Delay and SDL_GetTicks", TEST_ENABLED };
static const SDLTest_TestCaseReference timerTest4 =
{ (SDLTest_TestCaseFp)timer_addRemoveTimer, "timer_addRemoveTimer", "Call to SDL_AddTimer and SDL_RemoveTimer", TEST_ENABLED };
/* Sequence of Timer test cases */
static const SDLTest_TestCaseReference *timerTests[] = {
&timerTest1, &timerTest2, &timerTest3, &timerTest4, NULL
};
/* Timer test suite (global) */
SDLTest_TestSuiteReference timerTestSuite = {
"Timer",
_timerSetUp,
timerTests,
NULL
};
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_timer.c | C | apache-2.0 | 6,351 |
/**
* Video test suite
*/
#include <stdio.h>
#include <string.h>
/* Visual Studio 2008 doesn't have stdint.h */
#if defined(_MSC_VER) && _MSC_VER <= 1500
#define UINT8_MAX ~(Uint8)0
#define UINT16_MAX ~(Uint16)0
#define UINT32_MAX ~(Uint32)0
#define UINT64_MAX ~(Uint64)0
#else
#include <stdint.h>
#endif
#include "SDL.h"
#include "SDL_test.h"
/* Private helpers */
/*
* Create a test window
*/
SDL_Window *_createVideoSuiteTestWindow(const char *title)
{
SDL_Window* window;
int x, y, w, h;
SDL_WindowFlags flags;
/* Standard window */
x = SDLTest_RandomIntegerInRange(1, 100);
y = SDLTest_RandomIntegerInRange(1, 100);
w = SDLTest_RandomIntegerInRange(320, 1024);
h = SDLTest_RandomIntegerInRange(320, 768);
flags = SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_BORDERLESS;
window = SDL_CreateWindow(title, x, y, w, h, flags);
SDLTest_AssertPass("Call to SDL_CreateWindow('Title',%d,%d,%d,%d,%d)", x, y, w, h, flags);
SDLTest_AssertCheck(window != NULL, "Validate that returned window struct is not NULL");
return window;
}
/*
* Destroy test window
*/
void _destroyVideoSuiteTestWindow(SDL_Window *window)
{
if (window != NULL) {
SDL_DestroyWindow(window);
window = NULL;
SDLTest_AssertPass("Call to SDL_DestroyWindow()");
}
}
/* Test case functions */
/**
* @brief Enable and disable screensaver while checking state
*/
int
video_enableDisableScreensaver(void *arg)
{
SDL_bool initialResult;
SDL_bool result;
/* Get current state and proceed according to current state */
initialResult = SDL_IsScreenSaverEnabled();
SDLTest_AssertPass("Call to SDL_IsScreenSaverEnabled()");
if (initialResult == SDL_TRUE) {
/* Currently enabled: disable first, then enable again */
/* Disable screensaver and check */
SDL_DisableScreenSaver();
SDLTest_AssertPass("Call to SDL_DisableScreenSaver()");
result = SDL_IsScreenSaverEnabled();
SDLTest_AssertPass("Call to SDL_IsScreenSaverEnabled()");
SDLTest_AssertCheck(result == SDL_FALSE, "Verify result from SDL_IsScreenSaverEnabled, expected: %i, got: %i", SDL_FALSE, result);
/* Enable screensaver and check */
SDL_EnableScreenSaver();
SDLTest_AssertPass("Call to SDL_EnableScreenSaver()");
result = SDL_IsScreenSaverEnabled();
SDLTest_AssertPass("Call to SDL_IsScreenSaverEnabled()");
SDLTest_AssertCheck(result == SDL_TRUE, "Verify result from SDL_IsScreenSaverEnabled, expected: %i, got: %i", SDL_TRUE, result);
} else {
/* Currently disabled: enable first, then disable again */
/* Enable screensaver and check */
SDL_EnableScreenSaver();
SDLTest_AssertPass("Call to SDL_EnableScreenSaver()");
result = SDL_IsScreenSaverEnabled();
SDLTest_AssertPass("Call to SDL_IsScreenSaverEnabled()");
SDLTest_AssertCheck(result == SDL_TRUE, "Verify result from SDL_IsScreenSaverEnabled, expected: %i, got: %i", SDL_TRUE, result);
/* Disable screensaver and check */
SDL_DisableScreenSaver();
SDLTest_AssertPass("Call to SDL_DisableScreenSaver()");
result = SDL_IsScreenSaverEnabled();
SDLTest_AssertPass("Call to SDL_IsScreenSaverEnabled()");
SDLTest_AssertCheck(result == SDL_FALSE, "Verify result from SDL_IsScreenSaverEnabled, expected: %i, got: %i", SDL_FALSE, result);
}
return TEST_COMPLETED;
}
/**
* @brief Tests the functionality of the SDL_CreateWindow function using different positions
*/
int
video_createWindowVariousPositions(void *arg)
{
SDL_Window* window;
const char* title = "video_createWindowVariousPositions Test Window";
int x, y, w, h;
int xVariation, yVariation;
for (xVariation = 0; xVariation < 6; xVariation++) {
for (yVariation = 0; yVariation < 6; yVariation++) {
switch(xVariation) {
case 0:
/* Zero X Position */
x = 0;
break;
case 1:
/* Random X position inside screen */
x = SDLTest_RandomIntegerInRange(1, 100);
break;
case 2:
/* Random X position outside screen (positive) */
x = SDLTest_RandomIntegerInRange(10000, 11000);
break;
case 3:
/* Random X position outside screen (negative) */
x = SDLTest_RandomIntegerInRange(-1000, -100);
break;
case 4:
/* Centered X position */
x = SDL_WINDOWPOS_CENTERED;
break;
case 5:
/* Undefined X position */
x = SDL_WINDOWPOS_UNDEFINED;
break;
}
switch(yVariation) {
case 0:
/* Zero X Position */
y = 0;
break;
case 1:
/* Random X position inside screen */
y = SDLTest_RandomIntegerInRange(1, 100);
break;
case 2:
/* Random X position outside screen (positive) */
y = SDLTest_RandomIntegerInRange(10000, 11000);
break;
case 3:
/* Random Y position outside screen (negative) */
y = SDLTest_RandomIntegerInRange(-1000, -100);
break;
case 4:
/* Centered Y position */
y = SDL_WINDOWPOS_CENTERED;
break;
case 5:
/* Undefined Y position */
y = SDL_WINDOWPOS_UNDEFINED;
break;
}
w = SDLTest_RandomIntegerInRange(32, 96);
h = SDLTest_RandomIntegerInRange(32, 96);
window = SDL_CreateWindow(title, x, y, w, h, SDL_WINDOW_SHOWN);
SDLTest_AssertPass("Call to SDL_CreateWindow('Title',%d,%d,%d,%d,SHOWN)", x, y, w, h);
SDLTest_AssertCheck(window != NULL, "Validate that returned window struct is not NULL");
/* Clean up */
_destroyVideoSuiteTestWindow(window);
}
}
return TEST_COMPLETED;
}
/**
* @brief Tests the functionality of the SDL_CreateWindow function using different sizes
*/
int
video_createWindowVariousSizes(void *arg)
{
SDL_Window* window;
const char* title = "video_createWindowVariousSizes Test Window";
int x, y, w, h;
int wVariation, hVariation;
x = SDLTest_RandomIntegerInRange(1, 100);
y = SDLTest_RandomIntegerInRange(1, 100);
for (wVariation = 0; wVariation < 3; wVariation++) {
for (hVariation = 0; hVariation < 3; hVariation++) {
switch(wVariation) {
case 0:
/* Width of 1 */
w = 1;
break;
case 1:
/* Random "normal" width */
w = SDLTest_RandomIntegerInRange(320, 1920);
break;
case 2:
/* Random "large" width */
w = SDLTest_RandomIntegerInRange(2048, 4095);
break;
}
switch(hVariation) {
case 0:
/* Height of 1 */
h = 1;
break;
case 1:
/* Random "normal" height */
h = SDLTest_RandomIntegerInRange(320, 1080);
break;
case 2:
/* Random "large" height */
h = SDLTest_RandomIntegerInRange(2048, 4095);
break;
}
window = SDL_CreateWindow(title, x, y, w, h, SDL_WINDOW_SHOWN);
SDLTest_AssertPass("Call to SDL_CreateWindow('Title',%d,%d,%d,%d,SHOWN)", x, y, w, h);
SDLTest_AssertCheck(window != NULL, "Validate that returned window struct is not NULL");
/* Clean up */
_destroyVideoSuiteTestWindow(window);
}
}
return TEST_COMPLETED;
}
/**
* @brief Tests the functionality of the SDL_CreateWindow function using different flags
*/
int
video_createWindowVariousFlags(void *arg)
{
SDL_Window* window;
const char* title = "video_createWindowVariousFlags Test Window";
int x, y, w, h;
int fVariation;
SDL_WindowFlags flags;
/* Standard window */
x = SDLTest_RandomIntegerInRange(1, 100);
y = SDLTest_RandomIntegerInRange(1, 100);
w = SDLTest_RandomIntegerInRange(320, 1024);
h = SDLTest_RandomIntegerInRange(320, 768);
for (fVariation = 0; fVariation < 13; fVariation++) {
switch(fVariation) {
case 0:
flags = SDL_WINDOW_FULLSCREEN;
/* Skip - blanks screen; comment out next line to run test */
continue;
break;
case 1:
flags = SDL_WINDOW_FULLSCREEN_DESKTOP;
/* Skip - blanks screen; comment out next line to run test */
continue;
break;
case 2:
flags = SDL_WINDOW_OPENGL;
break;
case 3:
flags = SDL_WINDOW_SHOWN;
break;
case 4:
flags = SDL_WINDOW_HIDDEN;
break;
case 5:
flags = SDL_WINDOW_BORDERLESS;
break;
case 6:
flags = SDL_WINDOW_RESIZABLE;
break;
case 7:
flags = SDL_WINDOW_MINIMIZED;
break;
case 8:
flags = SDL_WINDOW_MAXIMIZED;
break;
case 9:
flags = SDL_WINDOW_INPUT_GRABBED;
break;
case 10:
flags = SDL_WINDOW_INPUT_FOCUS;
break;
case 11:
flags = SDL_WINDOW_MOUSE_FOCUS;
break;
case 12:
flags = SDL_WINDOW_FOREIGN;
break;
}
window = SDL_CreateWindow(title, x, y, w, h, flags);
SDLTest_AssertPass("Call to SDL_CreateWindow('Title',%d,%d,%d,%d,%d)", x, y, w, h, flags);
SDLTest_AssertCheck(window != NULL, "Validate that returned window struct is not NULL");
/* Clean up */
_destroyVideoSuiteTestWindow(window);
}
return TEST_COMPLETED;
}
/**
* @brief Tests the functionality of the SDL_GetWindowFlags function
*/
int
video_getWindowFlags(void *arg)
{
SDL_Window* window;
const char* title = "video_getWindowFlags Test Window";
SDL_WindowFlags flags;
Uint32 actualFlags;
/* Reliable flag set always set in test window */
flags = SDL_WINDOW_SHOWN;
/* Call against new test window */
window = _createVideoSuiteTestWindow(title);
if (window != NULL) {
actualFlags = SDL_GetWindowFlags(window);
SDLTest_AssertPass("Call to SDL_GetWindowFlags()");
SDLTest_AssertCheck((flags & actualFlags) == flags, "Verify returned value has flags %d set, got: %d", flags, actualFlags);
}
/* Clean up */
_destroyVideoSuiteTestWindow(window);
return TEST_COMPLETED;
}
/**
* @brief Tests the functionality of the SDL_GetNumDisplayModes function
*/
int
video_getNumDisplayModes(void *arg)
{
int result;
int displayNum;
int i;
/* Get number of displays */
displayNum = SDL_GetNumVideoDisplays();
SDLTest_AssertPass("Call to SDL_GetNumVideoDisplays()");
/* Make call for each display */
for (i=0; i<displayNum; i++) {
result = SDL_GetNumDisplayModes(i);
SDLTest_AssertPass("Call to SDL_GetNumDisplayModes(%d)", i);
SDLTest_AssertCheck(result >= 1, "Validate returned value from function; expected: >=1; got: %d", result);
}
return TEST_COMPLETED;
}
/**
* @brief Tests negative call to SDL_GetNumDisplayModes function
*/
int
video_getNumDisplayModesNegative(void *arg)
{
int result;
int displayNum;
int displayIndex;
/* Get number of displays */
displayNum = SDL_GetNumVideoDisplays();
SDLTest_AssertPass("Call to SDL_GetNumVideoDisplays()");
/* Invalid boundary values */
displayIndex = SDLTest_RandomSint32BoundaryValue(0, displayNum, SDL_FALSE);
result = SDL_GetNumDisplayModes(displayIndex);
SDLTest_AssertPass("Call to SDL_GetNumDisplayModes(%d=out-of-bounds/boundary)", displayIndex);
SDLTest_AssertCheck(result < 0, "Validate returned value from function; expected: <0; got: %d", result);
/* Large (out-of-bounds) display index */
displayIndex = SDLTest_RandomIntegerInRange(-2000, -1000);
result = SDL_GetNumDisplayModes(displayIndex);
SDLTest_AssertPass("Call to SDL_GetNumDisplayModes(%d=out-of-bounds/large negative)", displayIndex);
SDLTest_AssertCheck(result < 0, "Validate returned value from function; expected: <0; got: %d", result);
displayIndex = SDLTest_RandomIntegerInRange(1000, 2000);
result = SDL_GetNumDisplayModes(displayIndex);
SDLTest_AssertPass("Call to SDL_GetNumDisplayModes(%d=out-of-bounds/large positive)", displayIndex);
SDLTest_AssertCheck(result < 0, "Validate returned value from function; expected: <0; got: %d", result);
return TEST_COMPLETED;
}
/**
* @brief Tests the functionality of the SDL_GetClosestDisplayMode function against current resolution
*/
int
video_getClosestDisplayModeCurrentResolution(void *arg)
{
int result;
SDL_DisplayMode current;
SDL_DisplayMode target;
SDL_DisplayMode closest;
SDL_DisplayMode* dResult;
int displayNum;
int i;
int variation;
/* Get number of displays */
displayNum = SDL_GetNumVideoDisplays();
SDLTest_AssertPass("Call to SDL_GetNumVideoDisplays()");
/* Make calls for each display */
for (i=0; i<displayNum; i++) {
SDLTest_Log("Testing against display: %d", i);
/* Get first display mode to get a sane resolution; this should always work */
result = SDL_GetDisplayMode(i, 0, ¤t);
SDLTest_AssertPass("Call to SDL_GetDisplayMode()");
SDLTest_AssertCheck(result == 0, "Verify return value, expected: 0, got: %d", result);
if (result != 0) {
return TEST_ABORTED;
}
/* Set the desired resolution equals to current resolution */
target.w = current.w;
target.h = current.h;
for (variation = 0; variation < 8; variation ++) {
/* Vary constraints on other query parameters */
target.format = (variation & 1) ? current.format : 0;
target.refresh_rate = (variation & 2) ? current.refresh_rate : 0;
target.driverdata = (variation & 4) ? current.driverdata : 0;
/* Make call */
dResult = SDL_GetClosestDisplayMode(i, &target, &closest);
SDLTest_AssertPass("Call to SDL_GetClosestDisplayMode(target=current/variation%d)", variation);
SDLTest_AssertCheck(dResult != NULL, "Verify returned value is not NULL");
/* Check that one gets the current resolution back again */
SDLTest_AssertCheck(closest.w == current.w, "Verify returned width matches current width; expected: %d, got: %d", current.w, closest.w);
SDLTest_AssertCheck(closest.h == current.h, "Verify returned height matches current height; expected: %d, got: %d", current.h, closest.h);
SDLTest_AssertCheck(closest.w == dResult->w, "Verify return value matches assigned value; expected: %d, got: %d", closest.w, dResult->w);
SDLTest_AssertCheck(closest.h == dResult->h, "Verify return value matches assigned value; expected: %d, got: %d", closest.h, dResult->h);
}
}
return TEST_COMPLETED;
}
/**
* @brief Tests the functionality of the SDL_GetClosestDisplayMode function against random resolution
*/
int
video_getClosestDisplayModeRandomResolution(void *arg)
{
SDL_DisplayMode target;
SDL_DisplayMode closest;
SDL_DisplayMode* dResult;
int displayNum;
int i;
int variation;
/* Get number of displays */
displayNum = SDL_GetNumVideoDisplays();
SDLTest_AssertPass("Call to SDL_GetNumVideoDisplays()");
/* Make calls for each display */
for (i=0; i<displayNum; i++) {
SDLTest_Log("Testing against display: %d", i);
for (variation = 0; variation < 16; variation ++) {
/* Set random constraints */
target.w = (variation & 1) ? SDLTest_RandomIntegerInRange(1, 4096) : 0;
target.h = (variation & 2) ? SDLTest_RandomIntegerInRange(1, 4096) : 0;
target.format = (variation & 4) ? SDLTest_RandomIntegerInRange(1, 10) : 0;
target.refresh_rate = (variation & 8) ? SDLTest_RandomIntegerInRange(25, 120) : 0;
target.driverdata = 0;
/* Make call; may or may not find anything, so don't validate any further */
dResult = SDL_GetClosestDisplayMode(i, &target, &closest);
SDLTest_AssertPass("Call to SDL_GetClosestDisplayMode(target=random/variation%d)", variation);
}
}
return TEST_COMPLETED;
}
/**
* @brief Tests call to SDL_GetWindowBrightness
*
* @sa http://wiki.libsdl.org/moin.fcg/SDL_GetWindowBrightness
*/
int
video_getWindowBrightness(void *arg)
{
SDL_Window* window;
const char* title = "video_getWindowBrightness Test Window";
float result;
/* Call against new test window */
window = _createVideoSuiteTestWindow(title);
if (window != NULL) {
result = SDL_GetWindowBrightness(window);
SDLTest_AssertPass("Call to SDL_GetWindowBrightness()");
SDLTest_AssertCheck(result >= 0.0 && result <= 1.0, "Validate range of result value; expected: [0.0, 1.0], got: %f", result);
}
/* Clean up */
_destroyVideoSuiteTestWindow(window);
return TEST_COMPLETED;
}
/**
* @brief Tests call to SDL_GetWindowBrightness with invalid input
*
* @sa http://wiki.libsdl.org/moin.fcg/SDL_GetWindowBrightness
*/
int
video_getWindowBrightnessNegative(void *arg)
{
const char *invalidWindowError = "Invalid window";
char *lastError;
float result;
/* Call against invalid window */
result = SDL_GetWindowBrightness(NULL);
SDLTest_AssertPass("Call to SDL_GetWindowBrightness(window=NULL)");
SDLTest_AssertCheck(result == 1.0, "Validate result value; expected: 1.0, got: %f", result);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError != NULL, "Verify error message is not NULL");
if (lastError != NULL) {
SDLTest_AssertCheck(SDL_strcmp(lastError, invalidWindowError) == 0,
"SDL_GetError(): expected message '%s', was message: '%s'",
invalidWindowError,
lastError);
}
return TEST_COMPLETED;
}
/**
* @brief Tests call to SDL_GetWindowDisplayMode
*
* @sa http://wiki.libsdl.org/moin.fcg/SDL_GetWindowDisplayMode
*/
int
video_getWindowDisplayMode(void *arg)
{
SDL_Window* window;
const char* title = "video_getWindowDisplayMode Test Window";
SDL_DisplayMode mode;
int result;
/* Invalidate part of the mode content so we can check values later */
mode.w = -1;
mode.h = -1;
mode.refresh_rate = -1;
/* Call against new test window */
window = _createVideoSuiteTestWindow(title);
if (window != NULL) {
result = SDL_GetWindowDisplayMode(window, &mode);
SDLTest_AssertPass("Call to SDL_GetWindowDisplayMode()");
SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0, got: %d", result);
SDLTest_AssertCheck(mode.w > 0, "Validate mode.w content; expected: >0, got: %d", mode.w);
SDLTest_AssertCheck(mode.h > 0, "Validate mode.h content; expected: >0, got: %d", mode.h);
SDLTest_AssertCheck(mode.refresh_rate > 0, "Validate mode.refresh_rate content; expected: >0, got: %d", mode.refresh_rate);
}
/* Clean up */
_destroyVideoSuiteTestWindow(window);
return TEST_COMPLETED;
}
/* Helper function that checks for an 'Invalid window' error */
void _checkInvalidWindowError()
{
const char *invalidWindowError = "Invalid window";
char *lastError;
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError != NULL, "Verify error message is not NULL");
if (lastError != NULL) {
SDLTest_AssertCheck(SDL_strcmp(lastError, invalidWindowError) == 0,
"SDL_GetError(): expected message '%s', was message: '%s'",
invalidWindowError,
lastError);
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
}
}
/**
* @brief Tests call to SDL_GetWindowDisplayMode with invalid input
*
* @sa http://wiki.libsdl.org/moin.fcg/SDL_GetWindowDisplayMode
*/
int
video_getWindowDisplayModeNegative(void *arg)
{
const char *expectedError = "Parameter 'mode' is invalid";
char *lastError;
SDL_Window* window;
const char* title = "video_getWindowDisplayModeNegative Test Window";
SDL_DisplayMode mode;
int result;
/* Call against new test window */
window = _createVideoSuiteTestWindow(title);
if (window != NULL) {
result = SDL_GetWindowDisplayMode(window, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowDisplayMode(...,mode=NULL)");
SDLTest_AssertCheck(result == -1, "Validate result value; expected: -1, got: %d", result);
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError != NULL, "Verify error message is not NULL");
if (lastError != NULL) {
SDLTest_AssertCheck(SDL_strcmp(lastError, expectedError) == 0,
"SDL_GetError(): expected message '%s', was message: '%s'",
expectedError,
lastError);
}
}
/* Clean up */
_destroyVideoSuiteTestWindow(window);
/* Call against invalid window */
result = SDL_GetWindowDisplayMode(NULL, &mode);
SDLTest_AssertPass("Call to SDL_GetWindowDisplayMode(window=NULL,...)");
SDLTest_AssertCheck(result == -1, "Validate result value; expected: -1, got: %d", result);
_checkInvalidWindowError();
return TEST_COMPLETED;
}
/**
* @brief Tests call to SDL_GetWindowGammaRamp
*
* @sa http://wiki.libsdl.org/moin.fcg/SDL_GetWindowGammaRamp
*/
int
video_getWindowGammaRamp(void *arg)
{
SDL_Window* window;
const char* title = "video_getWindowGammaRamp Test Window";
Uint16 red[256];
Uint16 green[256];
Uint16 blue[256];
int result;
/* Call against new test window */
window = _createVideoSuiteTestWindow(title);
if (window == NULL) return TEST_ABORTED;
/* Retrieve no channel */
result = SDL_GetWindowGammaRamp(window, NULL, NULL, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowGammaRamp(all NULL)");
SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0, got: %d", result);
/* Retrieve single channel */
result = SDL_GetWindowGammaRamp(window, red, NULL, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowGammaRamp(r)");
SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0, got: %d", result);
result = SDL_GetWindowGammaRamp(window, NULL, green, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowGammaRamp(g)");
SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0, got: %d", result);
result = SDL_GetWindowGammaRamp(window, NULL, NULL, blue);
SDLTest_AssertPass("Call to SDL_GetWindowGammaRamp(b)");
SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0, got: %d", result);
/* Retrieve two channels */
result = SDL_GetWindowGammaRamp(window, red, green, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowGammaRamp(r, g)");
SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0, got: %d", result);
result = SDL_GetWindowGammaRamp(window, NULL, green, blue);
SDLTest_AssertPass("Call to SDL_GetWindowGammaRamp(g,b)");
SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0, got: %d", result);
result = SDL_GetWindowGammaRamp(window, red, NULL, blue);
SDLTest_AssertPass("Call to SDL_GetWindowGammaRamp(r,b)");
SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0, got: %d", result);
/* Retrieve all channels */
result = SDL_GetWindowGammaRamp(window, red, green, blue);
SDLTest_AssertPass("Call to SDL_GetWindowGammaRamp(r,g,b)");
SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0, got: %d", result);
/* Clean up */
_destroyVideoSuiteTestWindow(window);
return TEST_COMPLETED;
}
/**
* @brief Tests call to SDL_GetWindowGammaRamp with invalid input
*
* @sa http://wiki.libsdl.org/moin.fcg/SDL_GetWindowGammaRamp
*/
int
video_getWindowGammaRampNegative(void *arg)
{
Uint16 red[256];
Uint16 green[256];
Uint16 blue[256];
int result;
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
/* Call against invalid window */
result = SDL_GetWindowGammaRamp(NULL, red, green, blue);
SDLTest_AssertPass("Call to SDL_GetWindowGammaRamp(window=NULL,r,g,b)");
SDLTest_AssertCheck(result == -1, "Validate result value; expected: -1, got: %i", result);
_checkInvalidWindowError();
return TEST_COMPLETED;
}
/* Helper for setting and checking the window grab state */
void
_setAndCheckWindowGrabState(SDL_Window* window, SDL_bool desiredState)
{
SDL_bool currentState;
/* Set state */
SDL_SetWindowGrab(window, desiredState);
SDLTest_AssertPass("Call to SDL_SetWindowGrab(%s)", (desiredState == SDL_FALSE) ? "SDL_FALSE" : "SDL_TRUE");
/* Get and check state */
currentState = SDL_GetWindowGrab(window);
SDLTest_AssertPass("Call to SDL_GetWindowGrab()");
SDLTest_AssertCheck(
currentState == desiredState,
"Validate returned state; expected: %s, got: %s",
(desiredState == SDL_FALSE) ? "SDL_FALSE" : "SDL_TRUE",
(currentState == SDL_FALSE) ? "SDL_FALSE" : "SDL_TRUE");
}
/**
* @brief Tests call to SDL_GetWindowGrab and SDL_SetWindowGrab
*
* @sa http://wiki.libsdl.org/moin.fcg/SDL_GetWindowGrab
* @sa http://wiki.libsdl.org/moin.fcg/SDL_SetWindowGrab
*/
int
video_getSetWindowGrab(void *arg)
{
const char* title = "video_getSetWindowGrab Test Window";
SDL_Window* window;
SDL_bool originalState, dummyState, currentState, desiredState;
/* Call against new test window */
window = _createVideoSuiteTestWindow(title);
if (window == NULL) return TEST_ABORTED;
/* Get state */
originalState = SDL_GetWindowGrab(window);
SDLTest_AssertPass("Call to SDL_GetWindowGrab()");
/* F */
_setAndCheckWindowGrabState(window, SDL_FALSE);
/* F --> F */
_setAndCheckWindowGrabState(window, SDL_FALSE);
/* F --> T */
_setAndCheckWindowGrabState(window, SDL_TRUE);
/* T --> T */
_setAndCheckWindowGrabState(window, SDL_TRUE);
/* T --> F */
_setAndCheckWindowGrabState(window, SDL_FALSE);
/* Negative tests */
dummyState = SDL_GetWindowGrab(NULL);
SDLTest_AssertPass("Call to SDL_GetWindowGrab(window=NULL)");
_checkInvalidWindowError();
SDL_SetWindowGrab(NULL, SDL_FALSE);
SDLTest_AssertPass("Call to SDL_SetWindowGrab(window=NULL,SDL_FALSE)");
_checkInvalidWindowError();
SDL_SetWindowGrab(NULL, SDL_TRUE);
SDLTest_AssertPass("Call to SDL_SetWindowGrab(window=NULL,SDL_FALSE)");
_checkInvalidWindowError();
/* State should still be F */
desiredState = SDL_FALSE;
currentState = SDL_GetWindowGrab(window);
SDLTest_AssertPass("Call to SDL_GetWindowGrab()");
SDLTest_AssertCheck(
currentState == desiredState,
"Validate returned state; expected: %s, got: %s",
(desiredState == SDL_FALSE) ? "SDL_FALSE" : "SDL_TRUE",
(currentState == SDL_FALSE) ? "SDL_FALSE" : "SDL_TRUE");
/* Restore state */
_setAndCheckWindowGrabState(window, originalState);
/* Clean up */
_destroyVideoSuiteTestWindow(window);
return TEST_COMPLETED;
}
/**
* @brief Tests call to SDL_GetWindowID and SDL_GetWindowFromID
*
* @sa http://wiki.libsdl.org/moin.fcg/SDL_GetWindowID
* @sa http://wiki.libsdl.org/moin.fcg/SDL_SetWindowFromID
*/
int
video_getWindowId(void *arg)
{
const char* title = "video_getWindowId Test Window";
SDL_Window* window;
SDL_Window* result;
Uint32 id, randomId;
/* Call against new test window */
window = _createVideoSuiteTestWindow(title);
if (window == NULL) return TEST_ABORTED;
/* Get ID */
id = SDL_GetWindowID(window);
SDLTest_AssertPass("Call to SDL_GetWindowID()");
/* Get window from ID */
result = SDL_GetWindowFromID(id);
SDLTest_AssertPass("Call to SDL_GetWindowID(%d)", id);
SDLTest_AssertCheck(result == window, "Verify result matches window pointer");
/* Get window from random large ID, no result check */
randomId = SDLTest_RandomIntegerInRange(UINT8_MAX,UINT16_MAX);
result = SDL_GetWindowFromID(randomId);
SDLTest_AssertPass("Call to SDL_GetWindowID(%d/random_large)", randomId);
/* Get window from 0 and Uint32 max ID, no result check */
result = SDL_GetWindowFromID(0);
SDLTest_AssertPass("Call to SDL_GetWindowID(0)");
result = SDL_GetWindowFromID(UINT32_MAX);
SDLTest_AssertPass("Call to SDL_GetWindowID(UINT32_MAX)");
/* Clean up */
_destroyVideoSuiteTestWindow(window);
/* Get window from ID for closed window */
result = SDL_GetWindowFromID(id);
SDLTest_AssertPass("Call to SDL_GetWindowID(%d/closed_window)", id);
SDLTest_AssertCheck(result == NULL, "Verify result is NULL");
/* Negative test */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
id = SDL_GetWindowID(NULL);
SDLTest_AssertPass("Call to SDL_GetWindowID(window=NULL)");
_checkInvalidWindowError();
return TEST_COMPLETED;
}
/**
* @brief Tests call to SDL_GetWindowPixelFormat
*
* @sa http://wiki.libsdl.org/moin.fcg/SDL_GetWindowPixelFormat
*/
int
video_getWindowPixelFormat(void *arg)
{
const char* title = "video_getWindowPixelFormat Test Window";
SDL_Window* window;
Uint32 format;
/* Call against new test window */
window = _createVideoSuiteTestWindow(title);
if (window == NULL) return TEST_ABORTED;
/* Get format */
format = SDL_GetWindowPixelFormat(window);
SDLTest_AssertPass("Call to SDL_GetWindowPixelFormat()");
SDLTest_AssertCheck(format != SDL_PIXELFORMAT_UNKNOWN, "Verify that returned format is valid; expected: != %d, got: %d", SDL_PIXELFORMAT_UNKNOWN, format);
/* Clean up */
_destroyVideoSuiteTestWindow(window);
/* Negative test */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
format = SDL_GetWindowPixelFormat(NULL);
SDLTest_AssertPass("Call to SDL_GetWindowPixelFormat(window=NULL)");
_checkInvalidWindowError();
return TEST_COMPLETED;
}
/**
* @brief Tests call to SDL_GetWindowPosition and SDL_SetWindowPosition
*
* @sa http://wiki.libsdl.org/moin.fcg/SDL_GetWindowPosition
* @sa http://wiki.libsdl.org/moin.fcg/SDL_SetWindowPosition
*/
int
video_getSetWindowPosition(void *arg)
{
const char* title = "video_getSetWindowPosition Test Window";
SDL_Window* window;
int xVariation, yVariation;
int referenceX, referenceY;
int currentX, currentY;
int desiredX, desiredY;
/* Call against new test window */
window = _createVideoSuiteTestWindow(title);
if (window == NULL) return TEST_ABORTED;
for (xVariation = 0; xVariation < 4; xVariation++) {
for (yVariation = 0; yVariation < 4; yVariation++) {
switch(xVariation) {
case 0:
/* Zero X Position */
desiredX = 0;
break;
case 1:
/* Random X position inside screen */
desiredX = SDLTest_RandomIntegerInRange(1, 100);
break;
case 2:
/* Random X position outside screen (positive) */
desiredX = SDLTest_RandomIntegerInRange(10000, 11000);
break;
case 3:
/* Random X position outside screen (negative) */
desiredX = SDLTest_RandomIntegerInRange(-1000, -100);
break;
}
switch(yVariation) {
case 0:
/* Zero X Position */
desiredY = 0;
break;
case 1:
/* Random X position inside screen */
desiredY = SDLTest_RandomIntegerInRange(1, 100);
break;
case 2:
/* Random X position outside screen (positive) */
desiredY = SDLTest_RandomIntegerInRange(10000, 11000);
break;
case 3:
/* Random Y position outside screen (negative) */
desiredY = SDLTest_RandomIntegerInRange(-1000, -100);
break;
}
/* Set position */
SDL_SetWindowPosition(window, desiredX, desiredY);
SDLTest_AssertPass("Call to SDL_SetWindowPosition(...,%d,%d)", desiredX, desiredY);
/* Get position */
currentX = desiredX + 1;
currentY = desiredY + 1;
SDL_GetWindowPosition(window, ¤tX, ¤tY);
SDLTest_AssertPass("Call to SDL_GetWindowPosition()");
SDLTest_AssertCheck(desiredX == currentX, "Verify returned X position; expected: %d, got: %d", desiredX, currentX);
SDLTest_AssertCheck(desiredY == currentY, "Verify returned Y position; expected: %d, got: %d", desiredY, currentY);
/* Get position X */
currentX = desiredX + 1;
SDL_GetWindowPosition(window, ¤tX, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowPosition(&y=NULL)");
SDLTest_AssertCheck(desiredX == currentX, "Verify returned X position; expected: %d, got: %d", desiredX, currentX);
/* Get position Y */
currentY = desiredY + 1;
SDL_GetWindowPosition(window, NULL, ¤tY);
SDLTest_AssertPass("Call to SDL_GetWindowPosition(&x=NULL)");
SDLTest_AssertCheck(desiredY == currentY, "Verify returned Y position; expected: %d, got: %d", desiredY, currentY);
}
}
/* Dummy call with both pointers NULL */
SDL_GetWindowPosition(window, NULL, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowPosition(&x=NULL,&y=NULL)");
/* Clean up */
_destroyVideoSuiteTestWindow(window);
/* Set some 'magic' value for later check that nothing was changed */
referenceX = SDLTest_RandomSint32();
referenceY = SDLTest_RandomSint32();
currentX = referenceX;
currentY = referenceY;
desiredX = SDLTest_RandomSint32();
desiredY = SDLTest_RandomSint32();
/* Negative tests */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
SDL_GetWindowPosition(NULL, ¤tX, ¤tY);
SDLTest_AssertPass("Call to SDL_GetWindowPosition(window=NULL)");
SDLTest_AssertCheck(
currentX == referenceX && currentY == referenceY,
"Verify that content of X and Y pointers has not been modified; expected: %d,%d; got: %d,%d",
referenceX, referenceY,
currentX, currentY);
_checkInvalidWindowError();
SDL_GetWindowPosition(NULL, NULL, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowPosition(NULL, NULL, NULL)");
_checkInvalidWindowError();
SDL_SetWindowPosition(NULL, desiredX, desiredY);
SDLTest_AssertPass("Call to SDL_SetWindowPosition(window=NULL)");
_checkInvalidWindowError();
return TEST_COMPLETED;
}
/* Helper function that checks for an 'Invalid parameter' error */
void _checkInvalidParameterError()
{
const char *invalidParameterError = "Parameter";
char *lastError;
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError != NULL, "Verify error message is not NULL");
if (lastError != NULL) {
SDLTest_AssertCheck(SDL_strncmp(lastError, invalidParameterError, SDL_strlen(invalidParameterError)) == 0,
"SDL_GetError(): expected message starts with '%s', was message: '%s'",
invalidParameterError,
lastError);
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
}
}
/**
* @brief Tests call to SDL_GetWindowSize and SDL_SetWindowSize
*
* @sa http://wiki.libsdl.org/moin.fcg/SDL_GetWindowSize
* @sa http://wiki.libsdl.org/moin.fcg/SDL_SetWindowSize
*/
int
video_getSetWindowSize(void *arg)
{
const char* title = "video_getSetWindowSize Test Window";
SDL_Window* window;
int result;
SDL_Rect display;
int maxwVariation, maxhVariation;
int wVariation, hVariation;
int referenceW, referenceH;
int currentW, currentH;
int desiredW, desiredH;
/* Get display bounds for size range */
result = SDL_GetDisplayBounds(0, &display);
SDLTest_AssertPass("SDL_GetDisplayBounds()");
SDLTest_AssertCheck(result == 0, "Verify return value; expected: 0, got: %d", result);
if (result != 0) return TEST_ABORTED;
/* Call against new test window */
window = _createVideoSuiteTestWindow(title);
if (window == NULL) return TEST_ABORTED;
#ifdef __WIN32__
/* Platform clips window size to screen size */
maxwVariation = 4;
maxhVariation = 4;
#else
/* Platform allows window size >= screen size */
maxwVariation = 5;
maxhVariation = 5;
#endif
for (wVariation = 0; wVariation < maxwVariation; wVariation++) {
for (hVariation = 0; hVariation < maxhVariation; hVariation++) {
switch(wVariation) {
case 0:
/* 1 Pixel Wide */
desiredW = 1;
break;
case 1:
/* Random width inside screen */
desiredW = SDLTest_RandomIntegerInRange(1, 100);
break;
case 2:
/* Width 1 pixel smaller than screen */
desiredW = display.w - 1;
break;
case 3:
/* Width at screen size */
desiredW = display.w;
break;
case 4:
/* Width 1 pixel larger than screen */
desiredW = display.w + 1;
break;
}
switch(hVariation) {
case 0:
/* 1 Pixel High */
desiredH = 1;
break;
case 1:
/* Random height inside screen */
desiredH = SDLTest_RandomIntegerInRange(1, 100);
break;
case 2:
/* Height 1 pixel smaller than screen */
desiredH = display.h - 1;
break;
case 3:
/* Height at screen size */
desiredH = display.h;
break;
case 4:
/* Height 1 pixel larger than screen */
desiredH = display.h + 1;
break;
}
/* Set size */
SDL_SetWindowSize(window, desiredW, desiredH);
SDLTest_AssertPass("Call to SDL_SetWindowSize(...,%d,%d)", desiredW, desiredH);
/* Get size */
currentW = desiredW + 1;
currentH = desiredH + 1;
SDL_GetWindowSize(window, ¤tW, ¤tH);
SDLTest_AssertPass("Call to SDL_GetWindowSize()");
SDLTest_AssertCheck(desiredW == currentW, "Verify returned width; expected: %d, got: %d", desiredW, currentW);
SDLTest_AssertCheck(desiredH == currentH, "Verify returned height; expected: %d, got: %d", desiredH, currentH);
/* Get just width */
currentW = desiredW + 1;
SDL_GetWindowSize(window, ¤tW, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowSize(&h=NULL)");
SDLTest_AssertCheck(desiredW == currentW, "Verify returned width; expected: %d, got: %d", desiredW, currentW);
/* Get just height */
currentH = desiredH + 1;
SDL_GetWindowSize(window, NULL, ¤tH);
SDLTest_AssertPass("Call to SDL_GetWindowSize(&w=NULL)");
SDLTest_AssertCheck(desiredH == currentH, "Verify returned height; expected: %d, got: %d", desiredH, currentH);
}
}
/* Dummy call with both pointers NULL */
SDL_GetWindowSize(window, NULL, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowSize(&w=NULL,&h=NULL)");
/* Negative tests for parameter input */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
for (desiredH = -2; desiredH < 2; desiredH++) {
for (desiredW = -2; desiredW < 2; desiredW++) {
if (desiredW <= 0 || desiredH <= 0) {
SDL_SetWindowSize(window, desiredW, desiredH);
SDLTest_AssertPass("Call to SDL_SetWindowSize(...,%d,%d)", desiredW, desiredH);
_checkInvalidParameterError();
}
}
}
/* Clean up */
_destroyVideoSuiteTestWindow(window);
/* Set some 'magic' value for later check that nothing was changed */
referenceW = SDLTest_RandomSint32();
referenceH = SDLTest_RandomSint32();
currentW = referenceW;
currentH = referenceH;
desiredW = SDLTest_RandomSint32();
desiredH = SDLTest_RandomSint32();
/* Negative tests for window input */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
SDL_GetWindowSize(NULL, ¤tW, ¤tH);
SDLTest_AssertPass("Call to SDL_GetWindowSize(window=NULL)");
SDLTest_AssertCheck(
currentW == referenceW && currentH == referenceH,
"Verify that content of W and H pointers has not been modified; expected: %d,%d; got: %d,%d",
referenceW, referenceH,
currentW, currentH);
_checkInvalidWindowError();
SDL_GetWindowSize(NULL, NULL, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowSize(NULL, NULL, NULL)");
_checkInvalidWindowError();
SDL_SetWindowSize(NULL, desiredW, desiredH);
SDLTest_AssertPass("Call to SDL_SetWindowSize(window=NULL)");
_checkInvalidWindowError();
return TEST_COMPLETED;
}
/**
* @brief Tests call to SDL_GetWindowMinimumSize and SDL_SetWindowMinimumSize
*
*/
int
video_getSetWindowMinimumSize(void *arg)
{
const char* title = "video_getSetWindowMinimumSize Test Window";
SDL_Window* window;
int result;
SDL_Rect display;
int wVariation, hVariation;
int referenceW, referenceH;
int currentW, currentH;
int desiredW, desiredH;
/* Get display bounds for size range */
result = SDL_GetDisplayBounds(0, &display);
SDLTest_AssertPass("SDL_GetDisplayBounds()");
SDLTest_AssertCheck(result == 0, "Verify return value; expected: 0, got: %d", result);
if (result != 0) return TEST_ABORTED;
/* Call against new test window */
window = _createVideoSuiteTestWindow(title);
if (window == NULL) return TEST_ABORTED;
for (wVariation = 0; wVariation < 5; wVariation++) {
for (hVariation = 0; hVariation < 5; hVariation++) {
switch(wVariation) {
case 0:
/* 1 Pixel Wide */
desiredW = 1;
break;
case 1:
/* Random width inside screen */
desiredW = SDLTest_RandomIntegerInRange(2, display.w - 1);
break;
case 2:
/* Width at screen size */
desiredW = display.w;
break;
}
switch(hVariation) {
case 0:
/* 1 Pixel High */
desiredH = 1;
break;
case 1:
/* Random height inside screen */
desiredH = SDLTest_RandomIntegerInRange(2, display.h - 1);
break;
case 2:
/* Height at screen size */
desiredH = display.h;
break;
case 4:
/* Height 1 pixel larger than screen */
desiredH = display.h + 1;
break;
}
/* Set size */
SDL_SetWindowMinimumSize(window, desiredW, desiredH);
SDLTest_AssertPass("Call to SDL_SetWindowMinimumSize(...,%d,%d)", desiredW, desiredH);
/* Get size */
currentW = desiredW + 1;
currentH = desiredH + 1;
SDL_GetWindowMinimumSize(window, ¤tW, ¤tH);
SDLTest_AssertPass("Call to SDL_GetWindowMinimumSize()");
SDLTest_AssertCheck(desiredW == currentW, "Verify returned width; expected: %d, got: %d", desiredW, currentW);
SDLTest_AssertCheck(desiredH == currentH, "Verify returned height; expected: %d, got: %d", desiredH, currentH);
/* Get just width */
currentW = desiredW + 1;
SDL_GetWindowMinimumSize(window, ¤tW, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowMinimumSize(&h=NULL)");
SDLTest_AssertCheck(desiredW == currentW, "Verify returned width; expected: %d, got: %d", desiredW, currentH);
/* Get just height */
currentH = desiredH + 1;
SDL_GetWindowMinimumSize(window, NULL, ¤tH);
SDLTest_AssertPass("Call to SDL_GetWindowMinimumSize(&w=NULL)");
SDLTest_AssertCheck(desiredH == currentH, "Verify returned height; expected: %d, got: %d", desiredW, currentH);
}
}
/* Dummy call with both pointers NULL */
SDL_GetWindowMinimumSize(window, NULL, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowMinimumSize(&w=NULL,&h=NULL)");
/* Negative tests for parameter input */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
for (desiredH = -2; desiredH < 2; desiredH++) {
for (desiredW = -2; desiredW < 2; desiredW++) {
if (desiredW <= 0 || desiredH <= 0) {
SDL_SetWindowMinimumSize(window, desiredW, desiredH);
SDLTest_AssertPass("Call to SDL_SetWindowMinimumSize(...,%d,%d)", desiredW, desiredH);
_checkInvalidParameterError();
}
}
}
/* Clean up */
_destroyVideoSuiteTestWindow(window);
/* Set some 'magic' value for later check that nothing was changed */
referenceW = SDLTest_RandomSint32();
referenceH = SDLTest_RandomSint32();
currentW = referenceW;
currentH = referenceH;
desiredW = SDLTest_RandomSint32();
desiredH = SDLTest_RandomSint32();
/* Negative tests for window input */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
SDL_GetWindowMinimumSize(NULL, ¤tW, ¤tH);
SDLTest_AssertPass("Call to SDL_GetWindowMinimumSize(window=NULL)");
SDLTest_AssertCheck(
currentW == referenceW && currentH == referenceH,
"Verify that content of W and H pointers has not been modified; expected: %d,%d; got: %d,%d",
referenceW, referenceH,
currentW, currentH);
_checkInvalidWindowError();
SDL_GetWindowMinimumSize(NULL, NULL, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowMinimumSize(NULL, NULL, NULL)");
_checkInvalidWindowError();
SDL_SetWindowMinimumSize(NULL, desiredW, desiredH);
SDLTest_AssertPass("Call to SDL_SetWindowMinimumSize(window=NULL)");
_checkInvalidWindowError();
return TEST_COMPLETED;
}
/**
* @brief Tests call to SDL_GetWindowMaximumSize and SDL_SetWindowMaximumSize
*
*/
int
video_getSetWindowMaximumSize(void *arg)
{
const char* title = "video_getSetWindowMaximumSize Test Window";
SDL_Window* window;
int result;
SDL_Rect display;
int wVariation, hVariation;
int referenceW, referenceH;
int currentW, currentH;
int desiredW, desiredH;
/* Get display bounds for size range */
result = SDL_GetDisplayBounds(0, &display);
SDLTest_AssertPass("SDL_GetDisplayBounds()");
SDLTest_AssertCheck(result == 0, "Verify return value; expected: 0, got: %d", result);
if (result != 0) return TEST_ABORTED;
/* Call against new test window */
window = _createVideoSuiteTestWindow(title);
if (window == NULL) return TEST_ABORTED;
for (wVariation = 0; wVariation < 3; wVariation++) {
for (hVariation = 0; hVariation < 3; hVariation++) {
switch(wVariation) {
case 0:
/* 1 Pixel Wide */
desiredW = 1;
break;
case 1:
/* Random width inside screen */
desiredW = SDLTest_RandomIntegerInRange(2, display.w - 1);
break;
case 2:
/* Width at screen size */
desiredW = display.w;
break;
}
switch(hVariation) {
case 0:
/* 1 Pixel High */
desiredH = 1;
break;
case 1:
/* Random height inside screen */
desiredH = SDLTest_RandomIntegerInRange(2, display.h - 1);
break;
case 2:
/* Height at screen size */
desiredH = display.h;
break;
}
/* Set size */
SDL_SetWindowMaximumSize(window, desiredW, desiredH);
SDLTest_AssertPass("Call to SDL_SetWindowMaximumSize(...,%d,%d)", desiredW, desiredH);
/* Get size */
currentW = desiredW + 1;
currentH = desiredH + 1;
SDL_GetWindowMaximumSize(window, ¤tW, ¤tH);
SDLTest_AssertPass("Call to SDL_GetWindowMaximumSize()");
SDLTest_AssertCheck(desiredW == currentW, "Verify returned width; expected: %d, got: %d", desiredW, currentW);
SDLTest_AssertCheck(desiredH == currentH, "Verify returned height; expected: %d, got: %d", desiredH, currentH);
/* Get just width */
currentW = desiredW + 1;
SDL_GetWindowMaximumSize(window, ¤tW, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowMaximumSize(&h=NULL)");
SDLTest_AssertCheck(desiredW == currentW, "Verify returned width; expected: %d, got: %d", desiredW, currentH);
/* Get just height */
currentH = desiredH + 1;
SDL_GetWindowMaximumSize(window, NULL, ¤tH);
SDLTest_AssertPass("Call to SDL_GetWindowMaximumSize(&w=NULL)");
SDLTest_AssertCheck(desiredH == currentH, "Verify returned height; expected: %d, got: %d", desiredW, currentH);
}
}
/* Dummy call with both pointers NULL */
SDL_GetWindowMaximumSize(window, NULL, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowMaximumSize(&w=NULL,&h=NULL)");
/* Negative tests for parameter input */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
for (desiredH = -2; desiredH < 2; desiredH++) {
for (desiredW = -2; desiredW < 2; desiredW++) {
if (desiredW <= 0 || desiredH <= 0) {
SDL_SetWindowMaximumSize(window, desiredW, desiredH);
SDLTest_AssertPass("Call to SDL_SetWindowMaximumSize(...,%d,%d)", desiredW, desiredH);
_checkInvalidParameterError();
}
}
}
/* Clean up */
_destroyVideoSuiteTestWindow(window);
/* Set some 'magic' value for later check that nothing was changed */
referenceW = SDLTest_RandomSint32();
referenceH = SDLTest_RandomSint32();
currentW = referenceW;
currentH = referenceH;
desiredW = SDLTest_RandomSint32();
desiredH = SDLTest_RandomSint32();
/* Negative tests */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
SDL_GetWindowMaximumSize(NULL, ¤tW, ¤tH);
SDLTest_AssertPass("Call to SDL_GetWindowMaximumSize(window=NULL)");
SDLTest_AssertCheck(
currentW == referenceW && currentH == referenceH,
"Verify that content of W and H pointers has not been modified; expected: %d,%d; got: %d,%d",
referenceW, referenceH,
currentW, currentH);
_checkInvalidWindowError();
SDL_GetWindowMaximumSize(NULL, NULL, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowMaximumSize(NULL, NULL, NULL)");
_checkInvalidWindowError();
SDL_SetWindowMaximumSize(NULL, desiredW, desiredH);
SDLTest_AssertPass("Call to SDL_SetWindowMaximumSize(window=NULL)");
_checkInvalidWindowError();
return TEST_COMPLETED;
}
/**
* @brief Tests call to SDL_SetWindowData and SDL_GetWindowData
*
* @sa http://wiki.libsdl.org/moin.fcg/SDL_SetWindowData
* @sa http://wiki.libsdl.org/moin.fcg/SDL_GetWindowData
*/
int
video_getSetWindowData(void *arg)
{
int returnValue = TEST_COMPLETED;
const char* title = "video_setGetWindowData Test Window";
SDL_Window* window;
const char *referenceName = "TestName";
const char *name = "TestName";
const char *referenceName2 = "TestName2";
const char *name2 = "TestName2";
int datasize;
char *referenceUserdata = NULL;
char *userdata = NULL;
char *referenceUserdata2 = NULL;
char *userdata2 = NULL;
char *result;
int iteration;
/* Call against new test window */
window = _createVideoSuiteTestWindow(title);
if (window == NULL) return TEST_ABORTED;
/* Create testdata */
datasize = SDLTest_RandomIntegerInRange(1, 32);
referenceUserdata = SDLTest_RandomAsciiStringOfSize(datasize);
if (referenceUserdata == NULL) {
returnValue = TEST_ABORTED;
goto cleanup;
}
userdata = SDL_strdup(referenceUserdata);
if (userdata == NULL) {
returnValue = TEST_ABORTED;
goto cleanup;
}
datasize = SDLTest_RandomIntegerInRange(1, 32);
referenceUserdata2 = SDLTest_RandomAsciiStringOfSize(datasize);
if (referenceUserdata2 == NULL) {
returnValue = TEST_ABORTED;
goto cleanup;
}
userdata2 = (char *)SDL_strdup(referenceUserdata2);
if (userdata2 == NULL) {
returnValue = TEST_ABORTED;
goto cleanup;
}
/* Get non-existent data */
result = (char *)SDL_GetWindowData(window, name);
SDLTest_AssertPass("Call to SDL_GetWindowData(..,%s)", name);
SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
SDLTest_AssertCheck(SDL_strcmp(referenceName, name) == 0, "Validate that name was not changed, expected: %s, got: %s", referenceName, name);
/* Set data */
result = (char *)SDL_SetWindowData(window, name, userdata);
SDLTest_AssertPass("Call to SDL_SetWindowData(...%s,%s)", name, userdata);
SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
SDLTest_AssertCheck(SDL_strcmp(referenceName, name) == 0, "Validate that name was not changed, expected: %s, got: %s", referenceName, name);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata, userdata) == 0, "Validate that userdata was not changed, expected: %s, got: %s", referenceUserdata, userdata);
/* Get data (twice) */
for (iteration = 1; iteration <= 2; iteration++) {
result = (char *)SDL_GetWindowData(window, name);
SDLTest_AssertPass("Call to SDL_GetWindowData(..,%s) [iteration %d]", name, iteration);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata, result) == 0, "Validate that correct result was returned; expected: %s, got: %s", referenceUserdata, result);
SDLTest_AssertCheck(SDL_strcmp(referenceName, name) == 0, "Validate that name was not changed, expected: %s, got: %s", referenceName, name);
}
/* Set data again twice */
for (iteration = 1; iteration <= 2; iteration++) {
result = (char *)SDL_SetWindowData(window, name, userdata);
SDLTest_AssertPass("Call to SDL_SetWindowData(...%s,%s) [iteration %d]", name, userdata, iteration);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata, result) == 0, "Validate that correct result was returned; expected: %s, got: %s", referenceUserdata, result);
SDLTest_AssertCheck(SDL_strcmp(referenceName, name) == 0, "Validate that name was not changed, expected: %s, got: %s", referenceName, name);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata, userdata) == 0, "Validate that userdata was not changed, expected: %s, got: %s", referenceUserdata, userdata);
}
/* Get data again */
result = (char *)SDL_GetWindowData(window, name);
SDLTest_AssertPass("Call to SDL_GetWindowData(..,%s) [again]", name);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata, result) == 0, "Validate that correct result was returned; expected: %s, got: %s", referenceUserdata, result);
SDLTest_AssertCheck(SDL_strcmp(referenceName, name) == 0, "Validate that name was not changed, expected: %s, got: %s", referenceName, name);
/* Set data with new data */
result = (char *)SDL_SetWindowData(window, name, userdata2);
SDLTest_AssertPass("Call to SDL_SetWindowData(...%s,%s) [new userdata]", name, userdata2);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata, result) == 0, "Validate that correct result was returned; expected: %s, got: %s", referenceUserdata, result);
SDLTest_AssertCheck(SDL_strcmp(referenceName, name) == 0, "Validate that name was not changed, expected: %s, got: %s", referenceName, name);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata, userdata) == 0, "Validate that userdata was not changed, expected: %s, got: %s", referenceUserdata, userdata);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata2, userdata2) == 0, "Validate that userdata2 was not changed, expected: %s, got: %s", referenceUserdata2, userdata2);
/* Set data with new data again */
result = (char *)SDL_SetWindowData(window, name, userdata2);
SDLTest_AssertPass("Call to SDL_SetWindowData(...%s,%s) [new userdata again]", name, userdata2);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata2, result) == 0, "Validate that correct result was returned; expected: %s, got: %s", referenceUserdata2, result);
SDLTest_AssertCheck(SDL_strcmp(referenceName, name) == 0, "Validate that name was not changed, expected: %s, got: %s", referenceName, name);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata, userdata) == 0, "Validate that userdata was not changed, expected: %s, got: %s", referenceUserdata, userdata);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata2, userdata2) == 0, "Validate that userdata2 was not changed, expected: %s, got: %s", referenceUserdata2, userdata2);
/* Get new data */
result = (char *)SDL_GetWindowData(window, name);
SDLTest_AssertPass("Call to SDL_GetWindowData(..,%s)", name);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata2, result) == 0, "Validate that correct result was returned; expected: %s, got: %s", referenceUserdata2, result);
SDLTest_AssertCheck(SDL_strcmp(referenceName, name) == 0, "Validate that name was not changed, expected: %s, got: %s", referenceName, name);
/* Set data with NULL to clear */
result = (char *)SDL_SetWindowData(window, name, NULL);
SDLTest_AssertPass("Call to SDL_SetWindowData(...%s,NULL)", name);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata2, result) == 0, "Validate that correct result was returned; expected: %s, got: %s", referenceUserdata2, result);
SDLTest_AssertCheck(SDL_strcmp(referenceName, name) == 0, "Validate that name was not changed, expected: %s, got: %s", referenceName, name);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata, userdata) == 0, "Validate that userdata was not changed, expected: %s, got: %s", referenceUserdata, userdata);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata2, userdata2) == 0, "Validate that userdata2 was not changed, expected: %s, got: %s", referenceUserdata2, userdata2);
/* Set data with NULL to clear again */
result = (char *)SDL_SetWindowData(window, name, NULL);
SDLTest_AssertPass("Call to SDL_SetWindowData(...%s,NULL) [again]", name);
SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
SDLTest_AssertCheck(SDL_strcmp(referenceName, name) == 0, "Validate that name was not changed, expected: %s, got: %s", referenceName, name);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata, userdata) == 0, "Validate that userdata was not changed, expected: %s, got: %s", referenceUserdata, userdata);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata2, userdata2) == 0, "Validate that userdata2 was not changed, expected: %s, got: %s", referenceUserdata2, userdata2);
/* Get non-existent data */
result = (char *)SDL_GetWindowData(window, name);
SDLTest_AssertPass("Call to SDL_GetWindowData(..,%s)", name);
SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
SDLTest_AssertCheck(SDL_strcmp(referenceName, name) == 0, "Validate that name was not changed, expected: %s, got: %s", referenceName, name);
/* Get non-existent data new name */
result = (char *)SDL_GetWindowData(window, name2);
SDLTest_AssertPass("Call to SDL_GetWindowData(..,%s)", name2);
SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
SDLTest_AssertCheck(SDL_strcmp(referenceName2, name2) == 0, "Validate that name2 was not changed, expected: %s, got: %s", referenceName2, name2);
/* Set data (again) */
result = (char *)SDL_SetWindowData(window, name, userdata);
SDLTest_AssertPass("Call to SDL_SetWindowData(...%s,%s) [again, after clear]", name, userdata);
SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
SDLTest_AssertCheck(SDL_strcmp(referenceName, name) == 0, "Validate that name was not changed, expected: %s, got: %s", referenceName, name);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata, userdata) == 0, "Validate that userdata was not changed, expected: %s, got: %s", referenceUserdata, userdata);
/* Get data (again) */
result = (char *)SDL_GetWindowData(window, name);
SDLTest_AssertPass("Call to SDL_GetWindowData(..,%s) [again, after clear]", name);
SDLTest_AssertCheck(SDL_strcmp(referenceUserdata, result) == 0, "Validate that correct result was returned; expected: %s, got: %s", referenceUserdata, result);
SDLTest_AssertCheck(SDL_strcmp(referenceName, name) == 0, "Validate that name was not changed, expected: %s, got: %s", referenceName, name);
/* Negative test */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
/* Set with invalid window */
result = (char *)SDL_SetWindowData(NULL, name, userdata);
SDLTest_AssertPass("Call to SDL_SetWindowData(window=NULL)");
SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
_checkInvalidWindowError();
/* Set data with NULL name, valid userdata */
result = (char *)SDL_SetWindowData(window, NULL, userdata);
SDLTest_AssertPass("Call to SDL_SetWindowData(name=NULL)");
SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
_checkInvalidParameterError();
/* Set data with empty name, valid userdata */
result = (char *)SDL_SetWindowData(window, "", userdata);
SDLTest_AssertPass("Call to SDL_SetWindowData(name='')");
SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
_checkInvalidParameterError();
/* Set data with NULL name, NULL userdata */
result = (char *)SDL_SetWindowData(window, NULL, NULL);
SDLTest_AssertPass("Call to SDL_SetWindowData(name=NULL,userdata=NULL)");
SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
_checkInvalidParameterError();
/* Set data with empty name, NULL userdata */
result = (char *)SDL_SetWindowData(window, "", NULL);
SDLTest_AssertPass("Call to SDL_SetWindowData(name='',userdata=NULL)");
SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
_checkInvalidParameterError();
/* Get with invalid window */
result = (char *)SDL_GetWindowData(NULL, name);
SDLTest_AssertPass("Call to SDL_GetWindowData(window=NULL)");
SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
_checkInvalidWindowError();
/* Get data with NULL name */
result = (char *)SDL_GetWindowData(window, NULL);
SDLTest_AssertPass("Call to SDL_GetWindowData(name=NULL)");
SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
_checkInvalidParameterError();
/* Get data with empty name */
result = (char *)SDL_GetWindowData(window, "");
SDLTest_AssertPass("Call to SDL_GetWindowData(name='')");
SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
_checkInvalidParameterError();
/* Clean up */
_destroyVideoSuiteTestWindow(window);
cleanup:
SDL_free(referenceUserdata);
SDL_free(referenceUserdata2);
SDL_free(userdata);
SDL_free(userdata2);
return returnValue;
}
/* ================= Test References ================== */
/* Video test cases */
static const SDLTest_TestCaseReference videoTest1 =
{ (SDLTest_TestCaseFp)video_enableDisableScreensaver, "video_enableDisableScreensaver", "Enable and disable screenaver while checking state", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest2 =
{ (SDLTest_TestCaseFp)video_createWindowVariousPositions, "video_createWindowVariousPositions", "Create windows at various locations", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest3 =
{ (SDLTest_TestCaseFp)video_createWindowVariousSizes, "video_createWindowVariousSizes", "Create windows with various sizes", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest4 =
{ (SDLTest_TestCaseFp)video_createWindowVariousFlags, "video_createWindowVariousFlags", "Create windows using various flags", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest5 =
{ (SDLTest_TestCaseFp)video_getWindowFlags, "video_getWindowFlags", "Get window flags set during SDL_CreateWindow", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest6 =
{ (SDLTest_TestCaseFp)video_getNumDisplayModes, "video_getNumDisplayModes", "Use SDL_GetNumDisplayModes function to get number of display modes", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest7 =
{ (SDLTest_TestCaseFp)video_getNumDisplayModesNegative, "video_getNumDisplayModesNegative", "Negative tests for SDL_GetNumDisplayModes", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest8 =
{ (SDLTest_TestCaseFp)video_getClosestDisplayModeCurrentResolution, "video_getClosestDisplayModeCurrentResolution", "Use function to get closes match to requested display mode for current resolution", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest9 =
{ (SDLTest_TestCaseFp)video_getClosestDisplayModeRandomResolution, "video_getClosestDisplayModeRandomResolution", "Use function to get closes match to requested display mode for random resolution", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest10 =
{ (SDLTest_TestCaseFp)video_getWindowBrightness, "video_getWindowBrightness", "Get window brightness", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest11 =
{ (SDLTest_TestCaseFp)video_getWindowBrightnessNegative, "video_getWindowBrightnessNegative", "Get window brightness with invalid input", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest12 =
{ (SDLTest_TestCaseFp)video_getWindowDisplayMode, "video_getWindowDisplayMode", "Get window display mode", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest13 =
{ (SDLTest_TestCaseFp)video_getWindowDisplayModeNegative, "video_getWindowDisplayModeNegative", "Get window display mode with invalid input", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest14 =
{ (SDLTest_TestCaseFp)video_getWindowGammaRamp, "video_getWindowGammaRamp", "Get window gamma ramp", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest15 =
{ (SDLTest_TestCaseFp)video_getWindowGammaRampNegative, "video_getWindowGammaRampNegative", "Get window gamma ramp against invalid input", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest16 =
{ (SDLTest_TestCaseFp)video_getSetWindowGrab, "video_getSetWindowGrab", "Checks SDL_GetWindowGrab and SDL_SetWindowGrab positive and negative cases", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest17 =
{ (SDLTest_TestCaseFp)video_getWindowId, "video_getWindowId", "Checks SDL_GetWindowID and SDL_GetWindowFromID", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest18 =
{ (SDLTest_TestCaseFp)video_getWindowPixelFormat, "video_getWindowPixelFormat", "Checks SDL_GetWindowPixelFormat", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest19 =
{ (SDLTest_TestCaseFp)video_getSetWindowPosition, "video_getSetWindowPosition", "Checks SDL_GetWindowPosition and SDL_SetWindowPosition positive and negative cases", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest20 =
{ (SDLTest_TestCaseFp)video_getSetWindowSize, "video_getSetWindowSize", "Checks SDL_GetWindowSize and SDL_SetWindowSize positive and negative cases", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest21 =
{ (SDLTest_TestCaseFp)video_getSetWindowMinimumSize, "video_getSetWindowMinimumSize", "Checks SDL_GetWindowMinimumSize and SDL_SetWindowMinimumSize positive and negative cases", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest22 =
{ (SDLTest_TestCaseFp)video_getSetWindowMaximumSize, "video_getSetWindowMaximumSize", "Checks SDL_GetWindowMaximumSize and SDL_SetWindowMaximumSize positive and negative cases", TEST_ENABLED };
static const SDLTest_TestCaseReference videoTest23 =
{ (SDLTest_TestCaseFp)video_getSetWindowData, "video_getSetWindowData", "Checks SDL_SetWindowData and SDL_GetWindowData positive and negative cases", TEST_ENABLED };
/* Sequence of Video test cases */
static const SDLTest_TestCaseReference *videoTests[] = {
&videoTest1, &videoTest2, &videoTest3, &videoTest4, &videoTest5, &videoTest6,
&videoTest7, &videoTest8, &videoTest9, &videoTest10, &videoTest11, &videoTest12,
&videoTest13, &videoTest14, &videoTest15, &videoTest16, &videoTest17,
&videoTest18, &videoTest19, &videoTest20, &videoTest21, &videoTest22,
&videoTest23, NULL
};
/* Video test suite (global) */
SDLTest_TestSuiteReference videoTestSuite = {
"Video",
NULL,
videoTests,
NULL
};
| YifuLiu/AliOS-Things | components/SDL2/test/testautomation_video.c | C | apache-2.0 | 65,630 |
/*
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.
*/
#include "SDL.h"
int main(int argc, char **argv)
{
int total, i;
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
SDL_Log("SDL_Init(SDL_INIT_VIDEO) failed: %s", SDL_GetError());
return 1;
}
total = SDL_GetNumVideoDisplays();
for (i = 0; i < total; i++) {
SDL_Rect bounds = { -1,-1,-1,-1 }, usable = { -1,-1,-1,-1 };
SDL_GetDisplayBounds(i, &bounds);
SDL_GetDisplayUsableBounds(i, &usable);
SDL_Log("Display #%d ('%s'): bounds={(%d,%d),%dx%d}, usable={(%d,%d),%dx%d}",
i, SDL_GetDisplayName(i),
bounds.x, bounds.y, bounds.w, bounds.h,
usable.x, usable.y, usable.w, usable.h);
}
SDL_Quit();
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testbounds.c | C | apache-2.0 | 1,163 |
/*
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.
*/
#include <stdlib.h>
#include <stdio.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL_test_common.h"
/* Stolen from the mailing list */
/* Creates a new mouse cursor from an XPM */
/* XPM */
static const char *arrow[] = {
/* width height num_colors chars_per_pixel */
" 32 32 3 1",
/* colors */
"X c #000000",
". c #ffffff",
" c None",
/* pixels */
"X ",
"XX ",
"X.X ",
"X..X ",
"X...X ",
"X....X ",
"X.....X ",
"X......X ",
"X.......X ",
"X........X ",
"X.....XXXXX ",
"X..X..X ",
"X.X X..X ",
"XX X..X ",
"X X..X ",
" X..X ",
" X..X ",
" X..X ",
" XX ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
"0,0"
};
static SDL_Cursor*
init_color_cursor(const char *file)
{
SDL_Cursor *cursor = NULL;
SDL_Surface *surface = SDL_LoadBMP(file);
if (surface) {
if (surface->format->palette) {
SDL_SetColorKey(surface, 1, *(Uint8 *) surface->pixels);
} else {
switch (surface->format->BitsPerPixel) {
case 15:
SDL_SetColorKey(surface, 1, (*(Uint16 *)surface->pixels) & 0x00007FFF);
break;
case 16:
SDL_SetColorKey(surface, 1, *(Uint16 *)surface->pixels);
break;
case 24:
SDL_SetColorKey(surface, 1, (*(Uint32 *)surface->pixels) & 0x00FFFFFF);
break;
case 32:
SDL_SetColorKey(surface, 1, *(Uint32 *)surface->pixels);
break;
}
}
cursor = SDL_CreateColorCursor(surface, 0, 0);
SDL_FreeSurface(surface);
}
return cursor;
}
static SDL_Cursor*
init_system_cursor(const char *image[])
{
int i, row, col;
Uint8 data[4*32];
Uint8 mask[4*32];
int hot_x, hot_y;
i = -1;
for (row=0; row<32; ++row) {
for (col=0; col<32; ++col) {
if (col % 8) {
data[i] <<= 1;
mask[i] <<= 1;
} else {
++i;
data[i] = mask[i] = 0;
}
switch (image[4+row][col]) {
case 'X':
data[i] |= 0x01;
mask[i] |= 0x01;
break;
case '.':
mask[i] |= 0x01;
break;
case ' ':
break;
}
}
}
sscanf(image[4+row], "%d,%d", &hot_x, &hot_y);
return SDL_CreateCursor(data, mask, 32, 32, hot_x, hot_y);
}
static SDLTest_CommonState *state;
int done;
static SDL_Cursor *cursors[1+SDL_NUM_SYSTEM_CURSORS];
static int current_cursor;
static int show_cursor;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDLTest_CommonQuit(state);
exit(rc);
}
void
loop()
{
int i;
SDL_Event event;
/* Check for events */
while (SDL_PollEvent(&event)) {
SDLTest_CommonEvent(state, &event, &done);
if (event.type == SDL_MOUSEBUTTONDOWN) {
if (event.button.button == SDL_BUTTON_LEFT) {
++current_cursor;
if (current_cursor == SDL_arraysize(cursors)) {
current_cursor = 0;
}
SDL_SetCursor(cursors[current_cursor]);
} else {
show_cursor = !show_cursor;
SDL_ShowCursor(show_cursor);
}
}
}
for (i = 0; i < state->num_windows; ++i) {
SDL_Renderer *renderer = state->renderers[i];
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
}
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char *argv[])
{
int i;
const char *color_cursor = NULL;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
for (i = 1; i < argc;) {
int consumed;
consumed = SDLTest_CommonArg(state, i);
if (consumed == 0) {
color_cursor = argv[i];
break;
}
if (consumed < 0) {
SDLTest_CommonLogUsage(state, argv[0], NULL);
quit(1);
}
i += consumed;
}
if (!SDLTest_CommonInit(state)) {
quit(2);
}
for (i = 0; i < state->num_windows; ++i) {
SDL_Renderer *renderer = state->renderers[i];
SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
SDL_RenderClear(renderer);
}
if (color_cursor) {
cursors[0] = init_color_cursor(color_cursor);
} else {
cursors[0] = init_system_cursor(arrow);
}
if (!cursors[0]) {
SDL_Log("Error, couldn't create cursor\n");
quit(2);
}
for (i = 0; i < SDL_NUM_SYSTEM_CURSORS; ++i) {
cursors[1+i] = SDL_CreateSystemCursor((SDL_SystemCursor)i);
if (!cursors[1+i]) {
SDL_Log("Error, couldn't create system cursor %d\n", i);
quit(2);
}
}
SDL_SetCursor(cursors[0]);
/* Main render loop */
done = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
loop();
}
#endif
for (i = 0; i < SDL_arraysize(cursors); ++i) {
SDL_FreeCursor(cursors[i]);
}
quit(0);
/* keep the compiler happy ... */
return(0);
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testcustomcursor.c | C | apache-2.0 | 6,778 |
/*
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.
*/
/* Program to test querying of display info */
#include "SDL.h"
#include <stdio.h>
#include <stdlib.h>
static void
print_mode(const char *prefix, const SDL_DisplayMode *mode)
{
if (!mode)
return;
SDL_Log("%s: fmt=%s w=%d h=%d refresh=%d\n",
prefix, SDL_GetPixelFormatName(mode->format),
mode->w, mode->h, mode->refresh_rate);
}
int
main(int argc, char *argv[])
{
SDL_DisplayMode mode;
int num_displays, dpy;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Load the SDL library */
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return 1;
}
SDL_Log("Using video target '%s'.\n", SDL_GetCurrentVideoDriver());
num_displays = SDL_GetNumVideoDisplays();
SDL_Log("See %d displays.\n", num_displays);
for (dpy = 0; dpy < num_displays; dpy++) {
const int num_modes = SDL_GetNumDisplayModes(dpy);
SDL_Rect rect = { 0, 0, 0, 0 };
float ddpi, hdpi, vdpi;
int m;
SDL_GetDisplayBounds(dpy, &rect);
SDL_Log("%d: \"%s\" (%dx%d, (%d, %d)), %d modes.\n", dpy, SDL_GetDisplayName(dpy), rect.w, rect.h, rect.x, rect.y, num_modes);
if (SDL_GetDisplayDPI(dpy, &ddpi, &hdpi, &vdpi) == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, " DPI: failed to query (%s)\n", SDL_GetError());
} else {
SDL_Log(" DPI: ddpi=%f; hdpi=%f; vdpi=%f\n", ddpi, hdpi, vdpi);
}
if (SDL_GetCurrentDisplayMode(dpy, &mode) == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, " CURRENT: failed to query (%s)\n", SDL_GetError());
} else {
print_mode("CURRENT", &mode);
}
if (SDL_GetDesktopDisplayMode(dpy, &mode) == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, " DESKTOP: failed to query (%s)\n", SDL_GetError());
} else {
print_mode("DESKTOP", &mode);
}
for (m = 0; m < num_modes; m++) {
if (SDL_GetDisplayMode(dpy, m, &mode) == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, " MODE %d: failed to query (%s)\n", m, SDL_GetError());
} else {
char prefix[64];
SDL_snprintf(prefix, sizeof (prefix), " MODE %d", m);
print_mode(prefix, &mode);
}
}
SDL_Log("\n");
}
SDL_Quit();
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testdisplayinfo.c | C | apache-2.0 | 3,002 |
/*
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.
*/
/* Simple program: draw as many random objects on the screen as possible */
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL_test_common.h"
#define NUM_OBJECTS 100
static SDLTest_CommonState *state;
static int num_objects;
static SDL_bool cycle_color;
static SDL_bool cycle_alpha;
static int cycle_direction = 1;
static int current_alpha = 255;
static int current_color = 255;
static SDL_BlendMode blendMode = SDL_BLENDMODE_NONE;
int done;
void
DrawPoints(SDL_Renderer * renderer)
{
int i;
int x, y;
SDL_Rect viewport;
/* Query the sizes */
SDL_RenderGetViewport(renderer, &viewport);
for (i = 0; i < num_objects * 4; ++i) {
/* Cycle the color and alpha, if desired */
if (cycle_color) {
current_color += cycle_direction;
if (current_color < 0) {
current_color = 0;
cycle_direction = -cycle_direction;
}
if (current_color > 255) {
current_color = 255;
cycle_direction = -cycle_direction;
}
}
if (cycle_alpha) {
current_alpha += cycle_direction;
if (current_alpha < 0) {
current_alpha = 0;
cycle_direction = -cycle_direction;
}
if (current_alpha > 255) {
current_alpha = 255;
cycle_direction = -cycle_direction;
}
}
SDL_SetRenderDrawColor(renderer, 255, (Uint8) current_color,
(Uint8) current_color, (Uint8) current_alpha);
x = rand() % viewport.w;
y = rand() % viewport.h;
SDL_RenderDrawPoint(renderer, x, y);
}
}
void
DrawLines(SDL_Renderer * renderer)
{
int i;
int x1, y1, x2, y2;
SDL_Rect viewport;
/* Query the sizes */
SDL_RenderGetViewport(renderer, &viewport);
for (i = 0; i < num_objects; ++i) {
/* Cycle the color and alpha, if desired */
if (cycle_color) {
current_color += cycle_direction;
if (current_color < 0) {
current_color = 0;
cycle_direction = -cycle_direction;
}
if (current_color > 255) {
current_color = 255;
cycle_direction = -cycle_direction;
}
}
if (cycle_alpha) {
current_alpha += cycle_direction;
if (current_alpha < 0) {
current_alpha = 0;
cycle_direction = -cycle_direction;
}
if (current_alpha > 255) {
current_alpha = 255;
cycle_direction = -cycle_direction;
}
}
SDL_SetRenderDrawColor(renderer, 255, (Uint8) current_color,
(Uint8) current_color, (Uint8) current_alpha);
if (i == 0) {
SDL_RenderDrawLine(renderer, 0, 0, viewport.w - 1, viewport.h - 1);
SDL_RenderDrawLine(renderer, 0, viewport.h - 1, viewport.w - 1, 0);
SDL_RenderDrawLine(renderer, 0, viewport.h / 2, viewport.w - 1, viewport.h / 2);
SDL_RenderDrawLine(renderer, viewport.w / 2, 0, viewport.w / 2, viewport.h - 1);
} else {
x1 = (rand() % (viewport.w*2)) - viewport.w;
x2 = (rand() % (viewport.w*2)) - viewport.w;
y1 = (rand() % (viewport.h*2)) - viewport.h;
y2 = (rand() % (viewport.h*2)) - viewport.h;
SDL_RenderDrawLine(renderer, x1, y1, x2, y2);
}
}
}
void
DrawRects(SDL_Renderer * renderer)
{
int i;
SDL_Rect rect;
SDL_Rect viewport;
/* Query the sizes */
SDL_RenderGetViewport(renderer, &viewport);
for (i = 0; i < num_objects / 4; ++i) {
/* Cycle the color and alpha, if desired */
if (cycle_color) {
current_color += cycle_direction;
if (current_color < 0) {
current_color = 0;
cycle_direction = -cycle_direction;
}
if (current_color > 255) {
current_color = 255;
cycle_direction = -cycle_direction;
}
}
if (cycle_alpha) {
current_alpha += cycle_direction;
if (current_alpha < 0) {
current_alpha = 0;
cycle_direction = -cycle_direction;
}
if (current_alpha > 255) {
current_alpha = 255;
cycle_direction = -cycle_direction;
}
}
SDL_SetRenderDrawColor(renderer, 255, (Uint8) current_color,
(Uint8) current_color, (Uint8) current_alpha);
rect.w = rand() % (viewport.h / 2);
rect.h = rand() % (viewport.h / 2);
rect.x = (rand() % (viewport.w*2) - viewport.w) - (rect.w / 2);
rect.y = (rand() % (viewport.h*2) - viewport.h) - (rect.h / 2);
SDL_RenderFillRect(renderer, &rect);
}
}
void
loop()
{
int i;
SDL_Event event;
/* Check for events */
while (SDL_PollEvent(&event)) {
SDLTest_CommonEvent(state, &event, &done);
}
for (i = 0; i < state->num_windows; ++i) {
SDL_Renderer *renderer = state->renderers[i];
if (state->windows[i] == NULL)
continue;
SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
SDL_RenderClear(renderer);
DrawRects(renderer);
DrawLines(renderer);
DrawPoints(renderer);
SDL_RenderPresent(renderer);
}
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char *argv[])
{
int i;
Uint32 then, now, frames;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize parameters */
num_objects = NUM_OBJECTS;
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
for (i = 1; i < argc;) {
int consumed;
consumed = SDLTest_CommonArg(state, i);
if (consumed == 0) {
consumed = -1;
if (SDL_strcasecmp(argv[i], "--blend") == 0) {
if (argv[i + 1]) {
if (SDL_strcasecmp(argv[i + 1], "none") == 0) {
blendMode = SDL_BLENDMODE_NONE;
consumed = 2;
} else if (SDL_strcasecmp(argv[i + 1], "blend") == 0) {
blendMode = SDL_BLENDMODE_BLEND;
consumed = 2;
} else if (SDL_strcasecmp(argv[i + 1], "add") == 0) {
blendMode = SDL_BLENDMODE_ADD;
consumed = 2;
} else if (SDL_strcasecmp(argv[i + 1], "mod") == 0) {
blendMode = SDL_BLENDMODE_MOD;
consumed = 2;
}
}
} else if (SDL_strcasecmp(argv[i], "--cyclecolor") == 0) {
cycle_color = SDL_TRUE;
consumed = 1;
} else if (SDL_strcasecmp(argv[i], "--cyclealpha") == 0) {
cycle_alpha = SDL_TRUE;
consumed = 1;
} else if (SDL_isdigit(*argv[i])) {
num_objects = SDL_atoi(argv[i]);
consumed = 1;
}
}
if (consumed < 0) {
static const char *options[] = { "[--blend none|blend|add|mod]", "[--cyclecolor]", "[--cyclealpha]", NULL };
SDLTest_CommonLogUsage(state, argv[0], options);
return 1;
}
i += consumed;
}
if (!SDLTest_CommonInit(state)) {
return 2;
}
/* Create the windows and initialize the renderers */
for (i = 0; i < state->num_windows; ++i) {
SDL_Renderer *renderer = state->renderers[i];
SDL_SetRenderDrawBlendMode(renderer, blendMode);
SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
SDL_RenderClear(renderer);
}
srand((unsigned int)time(NULL));
/* Main render loop */
frames = 0;
then = SDL_GetTicks();
done = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
++frames;
loop();
}
#endif
SDLTest_CommonQuit(state);
/* Print out some timing information */
now = SDL_GetTicks();
if (now > then) {
double fps = ((double) frames * 1000) / (now - then);
SDL_Log("%2.2f frames per second\n", fps);
}
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testdraw2.c | C | apache-2.0 | 9,125 |