PolyWinCore.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  1. /*
  2. Copyright (C) 2011 by Ivan Safrin
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in
  10. all copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17. THE SOFTWARE.
  18. */
  19. #include "PolyWinCore.h"
  20. #include "PolyGLHeaders.h"
  21. #include "PolyCoreInput.h"
  22. #include "PolyCoreServices.h"
  23. #include "PolyInputEvent.h"
  24. #include "PolyGLRenderer.h"
  25. #include "PolyGLSLShaderModule.h"
  26. #include "PolyLogger.h"
  27. #include "PolyThreaded.h"
  28. #include <direct.h>
  29. #include <stdlib.h>
  30. #include <stdio.h>
  31. #include <shlobj.h>
  32. #include <shellapi.h>
  33. #include <commdlg.h>
  34. #if defined(_MINGW)
  35. #ifndef MAPVK_VSC_TO_VK_EX
  36. #define MAPVK_VSC_TO_VK_EX 3
  37. #endif
  38. #else
  39. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = NULL;
  40. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = NULL;
  41. #endif
  42. using namespace Polycode;
  43. long getThreadID() {
  44. return 0;
  45. }
  46. extern Win32Core *core;
  47. void ClientResize(HWND hWnd, int nWidth, int nHeight)
  48. {
  49. RECT rcClient, rcWindow;
  50. POINT ptDiff;
  51. GetClientRect(hWnd, &rcClient);
  52. GetWindowRect(hWnd, &rcWindow);
  53. ptDiff.x = (rcWindow.right - rcWindow.left) - rcClient.right;
  54. ptDiff.y = (rcWindow.bottom - rcWindow.top) - rcClient.bottom;
  55. MoveWindow(hWnd,rcWindow.left, rcWindow.top, nWidth + ptDiff.x, nHeight + ptDiff.y, TRUE);
  56. }
  57. void Core::getScreenInfo(int *width, int *height, int *hz) {
  58. DEVMODE mode = {}; // Zero initialize
  59. mode.dmSize = sizeof(DEVMODE);
  60. EnumDisplaySettings(0, ENUM_CURRENT_SETTINGS, &mode);
  61. // Store the current display settings.
  62. if (width) *width = mode.dmPelsWidth;
  63. if (height) *height = mode.dmPelsHeight;
  64. if (hz) *hz = mode.dmDisplayFrequency;
  65. }
  66. Win32Core::Win32Core(PolycodeViewBase *view, int _xRes, int _yRes, bool fullScreen, bool vSync, int aaLevel, int anisotropyLevel, int frameRate, int monitorIndex, bool retinaSupport)
  67. : Core(_xRes, _yRes, fullScreen, vSync, aaLevel, anisotropyLevel, frameRate, monitorIndex) {
  68. hWnd = *((HWND*)view->windowData);
  69. core = this;
  70. hasCopyDataString = false;
  71. scaleFactor = 1.0;
  72. char *buffer = _getcwd(NULL, 0);
  73. defaultWorkingDirectory = String(buffer);
  74. free(buffer);
  75. WCHAR path[MAX_PATH];
  76. if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, path))) {
  77. userHomeDirectory = String(path);
  78. }
  79. initKeymap();
  80. initGamepad();
  81. initTouch();
  82. hDC = NULL;
  83. hRC = NULL;
  84. PixelFormat = 0;
  85. this->aaLevel = 999;
  86. lastMouseX = -1;
  87. lastMouseY = -1;
  88. eventMutex = createMutex();
  89. isFullScreen = fullScreen;
  90. renderer = new OpenGLRenderer();
  91. services->setRenderer(renderer);
  92. renderer->setBackingResolutionScale(scaleFactor, scaleFactor);
  93. setVideoMode(xRes, yRes, fullScreen, vSync, aaLevel, anisotropyLevel);
  94. WSADATA WsaData;
  95. if(WSAStartup( MAKEWORD(2,2), &WsaData ) != NO_ERROR ){
  96. Logger::log("Error initializing sockets!\n");
  97. }
  98. ((OpenGLRenderer*)renderer)->Init();
  99. wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");
  100. wglGetSwapIntervalEXT = (PFNWGLGETSWAPINTERVALEXTPROC) wglGetProcAddress("wglGetSwapIntervalEXT");
  101. LARGE_INTEGER li;
  102. QueryPerformanceFrequency(&li);
  103. pcFreq = double(li.QuadPart)/1000.0;
  104. setVSync(vSync);
  105. CoreServices::getInstance()->installModule(new GLSLShaderModule());
  106. }
  107. Number Win32Core::getBackingXRes() {
  108. return getXRes() *scaleFactor;
  109. }
  110. Number Win32Core::getBackingYRes() {
  111. return getYRes() *scaleFactor;
  112. }
  113. Win32Core::~Win32Core() {
  114. shutdownGamepad();
  115. destroyContext();
  116. }
  117. void Win32Core::enableMouse(bool newval) {
  118. ShowCursor(newval);
  119. Core::enableMouse(newval);
  120. }
  121. void Win32Core::captureMouse(bool newval) {
  122. // Capture the mouse in the window holding
  123. // our polycode screen.
  124. if (newval){
  125. RECT rect;
  126. GetWindowRect(core->hWnd, &rect);
  127. RECT crect;
  128. RECT arect;
  129. GetClientRect(core->hWnd, &crect);
  130. arect = crect;
  131. AdjustWindowRectEx(&arect, WS_CAPTION | WS_BORDER, FALSE, 0);
  132. rect.left += (crect.left - arect.left);
  133. rect.right += (crect.right - arect.right);
  134. rect.top += (crect.top - arect.top);
  135. rect.bottom += (crect.bottom - arect.bottom);
  136. ClipCursor(&rect);
  137. }
  138. else {
  139. ClipCursor(NULL);
  140. }
  141. Core::captureMouse(newval);
  142. }
  143. void Win32Core::warpCursor(int x, int y) {
  144. POINT point;
  145. point.x = x;
  146. point.y = y;
  147. ClientToScreen(hWnd, &point);
  148. SetCursorPos(point.x,point.y);
  149. lastMouseX = x;
  150. lastMouseY = y;
  151. }
  152. unsigned int Win32Core::getTicks() {
  153. LARGE_INTEGER li;
  154. QueryPerformanceCounter(&li);
  155. return (unsigned int)(li.QuadPart / pcFreq);
  156. }
  157. void Win32Core::Render() {
  158. renderer->BeginRender();
  159. services->Render();
  160. renderer->EndRender();
  161. SwapBuffers(hDC);
  162. }
  163. bool Win32Core::systemUpdate() {
  164. if(!running)
  165. return false;
  166. captureMouse(Core::mouseCaptured);
  167. doSleep();
  168. checkEvents();
  169. Gamepad_processEvents();
  170. updateCore();
  171. return running;
  172. }
  173. void Win32Core::setVSync(bool vSyncVal) {
  174. if(wglSwapIntervalEXT) {
  175. if(vSyncVal) {
  176. wglSwapIntervalEXT(1);
  177. } else {
  178. wglSwapIntervalEXT(0);
  179. }
  180. }
  181. }
  182. void Win32Core::setVideoMode(int xRes, int yRes, bool fullScreen, bool vSync, int aaLevel, int anisotropyLevel, bool retinaSupport) {
  183. bool resetContext = false;
  184. if(aaLevel != this->aaLevel) {
  185. resetContext = true;
  186. }
  187. bool wasFullscreen = this->fullScreen;
  188. this->xRes = xRes;
  189. this->yRes = yRes;
  190. this->fullScreen = fullScreen;
  191. this->aaLevel = aaLevel;
  192. if(fullScreen) {
  193. SetWindowLong(hWnd, GWL_STYLE, WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP);
  194. ShowWindow(hWnd, SW_SHOW);
  195. MoveWindow(hWnd, 0, 0, xRes, yRes, TRUE);
  196. DEVMODE dmScreenSettings; // Device Mode
  197. memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
  198. dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure
  199. dmScreenSettings.dmPelsWidth = xRes; // Selected Screen Width
  200. dmScreenSettings.dmPelsHeight = yRes; // Selected Screen Height
  201. dmScreenSettings.dmBitsPerPel = 32; // Selected Bits Per Pixel
  202. dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
  203. ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN);
  204. //SetWindowPos(hWnd, NULL, 0, 0, xRes, yRes, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
  205. } else {
  206. RECT rect;
  207. rect.left = 0;
  208. rect.top = 0;
  209. rect.right = xRes;
  210. rect.bottom = yRes;
  211. SetWindowLongPtr(hWnd, GWL_STYLE, WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE);
  212. AdjustWindowRect(&rect, WS_CAPTION | WS_POPUPWINDOW, FALSE);
  213. MoveWindow(hWnd, 0, 0, rect.right-rect.left, rect.bottom-rect.top, TRUE);
  214. ChangeDisplaySettings(0, 0);
  215. }
  216. isFullScreen = fullScreen;
  217. if(resetContext) {
  218. initContext(false, 0);
  219. if(aaLevel > 0) {
  220. initMultisample(aaLevel);
  221. }
  222. }
  223. setVSync(vSync);
  224. renderer->setAnisotropyAmount(anisotropyLevel);
  225. renderer->Resize(xRes, yRes);
  226. core->dispatchEvent(new Event(), Core::EVENT_CORE_RESIZE);
  227. }
  228. void Win32Core::initContext(bool usePixelFormat, unsigned int pixelFormat) {
  229. destroyContext();
  230. memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)) ;
  231. pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
  232. pfd.nVersion = 1 ;
  233. pfd.dwFlags = PFD_DOUBLEBUFFER |
  234. PFD_SUPPORT_OPENGL |
  235. PFD_DRAW_TO_WINDOW ;
  236. pfd.iPixelType = PFD_TYPE_RGBA ;
  237. pfd.cColorBits = 24;
  238. pfd.cDepthBits = 16;
  239. pfd.cAccumBlueBits = 8;
  240. pfd.cAccumRedBits = 8;
  241. pfd.cAccumGreenBits = 8;
  242. pfd.cAccumAlphaBits = 8;
  243. pfd.cAccumBits = 24;
  244. pfd.iLayerType = PFD_MAIN_PLANE ;
  245. if (!(hDC=GetDC(hWnd))) // Did We Get A Device Context?
  246. {
  247. Logger::log("Can't Create A GL Device Context.\n");
  248. return; // Return FALSE
  249. }
  250. if(usePixelFormat) {
  251. PixelFormat = pixelFormat;
  252. } else {
  253. if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format?
  254. {
  255. Logger::log("Can't Find A Suitable PixelFormat.\n");
  256. return; // Return FALSE
  257. }
  258. }
  259. Logger::log("Setting format: %d\n", PixelFormat);
  260. if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format?
  261. {
  262. Logger::log("Can't Set The PixelFormat: %d.\n", PixelFormat);
  263. return; // Return FALSE
  264. }
  265. if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering Context?
  266. {
  267. Logger::log("Can't Create A GL Rendering Context.\n");
  268. return; // Return FALSE
  269. }
  270. if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context
  271. {
  272. Logger::log("Can't Activate The GL Rendering Context.\n");
  273. return; // Return FALSE
  274. }
  275. }
  276. void Win32Core::destroyContext() {
  277. if(hDC == NULL)
  278. return;
  279. wglMakeCurrent (hDC, 0);
  280. wglDeleteContext(hRC);
  281. hRC = 0;
  282. ReleaseDC (hWnd, hDC);
  283. hDC = 0;
  284. if (isFullScreen)
  285. ChangeDisplaySettings (NULL,0);
  286. }
  287. void Win32Core::initMultisample(int numSamples) {
  288. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB =
  289. (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
  290. if (!wglChoosePixelFormatARB) {
  291. Logger::log("Multisampling not supported!\n");
  292. return;
  293. }
  294. int pixelFormat;
  295. UINT numFormats;
  296. float fAttributes[] = {0,0};
  297. int iAttributes[] = { WGL_DRAW_TO_WINDOW_ARB,GL_TRUE,
  298. WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
  299. WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
  300. WGL_COLOR_BITS_ARB,24,
  301. WGL_DEPTH_BITS_ARB,24,
  302. WGL_DOUBLE_BUFFER_ARB,GL_TRUE,
  303. WGL_ACCUM_GREEN_BITS_ARB, 8,
  304. WGL_ACCUM_RED_BITS_ARB, 8,
  305. WGL_ACCUM_BLUE_BITS_ARB, 8,
  306. WGL_ACCUM_ALPHA_BITS_ARB, 8,
  307. WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
  308. WGL_SAMPLES_ARB, numSamples ,
  309. 0,0};
  310. if(!wglChoosePixelFormatARB(hDC,iAttributes,fAttributes,1,&pixelFormat,&numFormats)) {
  311. Logger::log("Invalid pixel format chosen\n");
  312. return;
  313. }
  314. // initContext(true, pixelFormat);
  315. glEnable(GL_MULTISAMPLE_ARB);
  316. }
  317. void Win32Core::initKeymap() {
  318. for (int i=0; i<1024; ++i )
  319. keyMap[i] = KEY_UNKNOWN;
  320. keyMap[VK_BACK] = KEY_BACKSPACE;
  321. keyMap[VK_TAB] = KEY_TAB;
  322. keyMap[VK_CLEAR] = KEY_CLEAR;
  323. keyMap[VK_RETURN] = KEY_RETURN;
  324. keyMap[VK_PAUSE] = KEY_PAUSE;
  325. keyMap[VK_ESCAPE] = KEY_ESCAPE;
  326. keyMap[VK_SPACE] = KEY_SPACE;
  327. keyMap[VK_APOSTROPHE] = KEY_QUOTE;
  328. keyMap[VK_COMMA] = KEY_COMMA;
  329. keyMap[VK_MINUS] = KEY_MINUS;
  330. keyMap[VK_PERIOD] = KEY_PERIOD;
  331. keyMap[VK_SLASH] = KEY_SLASH;
  332. keyMap[VK_0] = KEY_0;
  333. keyMap[VK_1] = KEY_1;
  334. keyMap[VK_2] = KEY_2;
  335. keyMap[VK_3] = KEY_3;
  336. keyMap[VK_4] = KEY_4;
  337. keyMap[VK_5] = KEY_5;
  338. keyMap[VK_6] = KEY_6;
  339. keyMap[VK_7] = KEY_7;
  340. keyMap[VK_8] = KEY_8;
  341. keyMap[VK_9] = KEY_9;
  342. keyMap[VK_SEMICOLON] = KEY_SEMICOLON;
  343. keyMap[VK_EQUALS] = KEY_EQUALS;
  344. keyMap[VK_LBRACKET] = KEY_LEFTBRACKET;
  345. keyMap[VK_BACKSLASH] = KEY_BACKSLASH;
  346. keyMap[VK_OEM_102] = KEY_LESS;
  347. keyMap[VK_RBRACKET] = KEY_RIGHTBRACKET;
  348. keyMap[VK_GRAVE] = KEY_BACKQUOTE;
  349. keyMap[VK_BACKTICK] = KEY_BACKQUOTE;
  350. keyMap[VK_A] = KEY_a;
  351. keyMap[VK_B] = KEY_b;
  352. keyMap[VK_C] = KEY_c;
  353. keyMap[VK_D] = KEY_d;
  354. keyMap[VK_E] = KEY_e;
  355. keyMap[VK_F] = KEY_f;
  356. keyMap[VK_G] = KEY_g;
  357. keyMap[VK_H] = KEY_h;
  358. keyMap[VK_I] = KEY_i;
  359. keyMap[VK_J] = KEY_j;
  360. keyMap[VK_K] = KEY_k;
  361. keyMap[VK_L] = KEY_l;
  362. keyMap[VK_M] = KEY_m;
  363. keyMap[VK_N] = KEY_n;
  364. keyMap[VK_O] = KEY_o;
  365. keyMap[VK_P] = KEY_p;
  366. keyMap[VK_Q] = KEY_q;
  367. keyMap[VK_R] = KEY_r;
  368. keyMap[VK_S] = KEY_s;
  369. keyMap[VK_T] = KEY_t;
  370. keyMap[VK_U] = KEY_u;
  371. keyMap[VK_V] = KEY_v;
  372. keyMap[VK_W] = KEY_w;
  373. keyMap[VK_X] = KEY_x;
  374. keyMap[VK_Y] = KEY_y;
  375. keyMap[VK_Z] = KEY_z;
  376. keyMap[VK_DELETE] = KEY_DELETE;
  377. keyMap[VK_NUMPAD0] = KEY_KP0;
  378. keyMap[VK_NUMPAD1] = KEY_KP1;
  379. keyMap[VK_NUMPAD2] = KEY_KP2;
  380. keyMap[VK_NUMPAD3] = KEY_KP3;
  381. keyMap[VK_NUMPAD4] = KEY_KP4;
  382. keyMap[VK_NUMPAD5] = KEY_KP5;
  383. keyMap[VK_NUMPAD6] = KEY_KP6;
  384. keyMap[VK_NUMPAD7] = KEY_KP7;
  385. keyMap[VK_NUMPAD8] = KEY_KP8;
  386. keyMap[VK_NUMPAD9] = KEY_KP9;
  387. keyMap[VK_DECIMAL] = KEY_KP_PERIOD;
  388. keyMap[VK_DIVIDE] = KEY_KP_DIVIDE;
  389. keyMap[VK_MULTIPLY] = KEY_KP_MULTIPLY;
  390. keyMap[VK_SUBTRACT] = KEY_KP_MINUS;
  391. keyMap[VK_ADD] = KEY_KP_PLUS;
  392. keyMap[VK_UP] = KEY_UP;
  393. keyMap[VK_DOWN] = KEY_DOWN;
  394. keyMap[VK_RIGHT] = KEY_RIGHT;
  395. keyMap[VK_LEFT] = KEY_LEFT;
  396. keyMap[VK_INSERT] = KEY_INSERT;
  397. keyMap[VK_HOME] = KEY_HOME;
  398. keyMap[VK_END] = KEY_END;
  399. keyMap[VK_PRIOR] = KEY_PAGEUP;
  400. keyMap[VK_NEXT] = KEY_PAGEDOWN;
  401. keyMap[VK_F1] = KEY_F1;
  402. keyMap[VK_F2] = KEY_F2;
  403. keyMap[VK_F3] = KEY_F3;
  404. keyMap[VK_F4] = KEY_F4;
  405. keyMap[VK_F5] = KEY_F5;
  406. keyMap[VK_F6] = KEY_F6;
  407. keyMap[VK_F7] = KEY_F7;
  408. keyMap[VK_F8] = KEY_F8;
  409. keyMap[VK_F9] = KEY_F9;
  410. keyMap[VK_F10] = KEY_F10;
  411. keyMap[VK_F11] = KEY_F11;
  412. keyMap[VK_F12] = KEY_F12;
  413. keyMap[VK_F13] = KEY_F13;
  414. keyMap[VK_F14] = KEY_F14;
  415. keyMap[VK_F15] = KEY_F15;
  416. keyMap[VK_NUMLOCK] = KEY_NUMLOCK;
  417. keyMap[VK_CAPITAL] = KEY_CAPSLOCK;
  418. keyMap[VK_SCROLL] = KEY_SCROLLOCK;
  419. keyMap[VK_RSHIFT] = KEY_RSHIFT;
  420. keyMap[VK_LSHIFT] = KEY_LSHIFT;
  421. keyMap[VK_RCONTROL] = KEY_RCTRL;
  422. keyMap[VK_LCONTROL] = KEY_LCTRL;
  423. keyMap[VK_RMENU] = KEY_RALT;
  424. keyMap[VK_LMENU] = KEY_LALT;
  425. keyMap[VK_RWIN] = KEY_RSUPER;
  426. keyMap[VK_LWIN] = KEY_LSUPER;
  427. keyMap[VK_HELP] = KEY_HELP;
  428. keyMap[VK_SNAPSHOT] = KEY_PRINT;
  429. keyMap[VK_CANCEL] = KEY_BREAK;
  430. keyMap[VK_APPS] = KEY_MENU;
  431. }
  432. void Win32Core::handleViewResize(int width, int height) {
  433. this->xRes = width;
  434. this->yRes = height;
  435. renderer->Resize(width, height);
  436. dispatchEvent(new Event(), EVENT_CORE_RESIZE);
  437. }
  438. PolyKEY Win32Core::mapKey(LPARAM lParam, WPARAM wParam) {
  439. switch (wParam) {
  440. case VK_CONTROL:
  441. if ( lParam&EXTENDED_KEYMASK )
  442. wParam = VK_RCONTROL;
  443. else
  444. wParam = VK_LCONTROL;
  445. break;
  446. case VK_MENU:
  447. if ( lParam&EXTENDED_KEYMASK )
  448. wParam = VK_RMENU;
  449. else
  450. wParam = VK_LMENU;
  451. break;
  452. case VK_SHIFT:
  453. // Use MapVirtualKey to determine whether it's LSHIFT or RSHIFT by scancode.
  454. UINT scancode = (lParam & 0x00ff0000) >> 16;
  455. wParam = MapVirtualKey(scancode, MAPVK_VSC_TO_VK_EX);
  456. break;
  457. }
  458. return keyMap[(unsigned int)wParam];
  459. }
  460. void Win32Core::handleKeyDown(LPARAM lParam, WPARAM wParam, wchar_t unicodeChar) {
  461. lockMutex(eventMutex);
  462. Win32Event newEvent;
  463. newEvent.eventGroup = Win32Event::INPUT_EVENT;
  464. newEvent.eventCode = InputEvent::EVENT_KEYDOWN;
  465. newEvent.keyCode = mapKey(lParam, wParam);
  466. newEvent.unicodeChar = unicodeChar;
  467. win32Events.push_back(newEvent);
  468. unlockMutex(eventMutex);
  469. }
  470. void Win32Core::handleKeyUp(LPARAM lParam, WPARAM wParam) {
  471. lockMutex(eventMutex);
  472. Win32Event newEvent;
  473. newEvent.eventGroup = Win32Event::INPUT_EVENT;
  474. newEvent.eventCode = InputEvent::EVENT_KEYUP;
  475. newEvent.keyCode = mapKey(lParam, wParam);
  476. newEvent.unicodeChar = 0;
  477. win32Events.push_back(newEvent);
  478. unlockMutex(eventMutex);
  479. }
  480. #ifndef NO_TOUCH_API
  481. void Win32Core::handleTouchEvent(LPARAM lParam, WPARAM wParam) {
  482. // Bail out now if multitouch is not available on this system
  483. if ( hasMultiTouch == false )
  484. {
  485. return;
  486. }
  487. lockMutex(eventMutex);
  488. int iNumContacts = LOWORD(wParam);
  489. HTOUCHINPUT hInput = (HTOUCHINPUT)lParam;
  490. TOUCHINPUT *pInputs = new TOUCHINPUT[iNumContacts];
  491. if(pInputs != NULL) {
  492. if(GetTouchInputInfoFunc(hInput, iNumContacts, pInputs, sizeof(TOUCHINPUT))) {
  493. std::vector<TouchInfo> touches;
  494. for(int i = 0; i < iNumContacts; i++) {
  495. TOUCHINPUT ti = pInputs[i];
  496. TouchInfo touchInfo;
  497. touchInfo.id = (int) ti.dwID;
  498. POINT pt;
  499. pt.x = TOUCH_COORD_TO_PIXEL(ti.x);
  500. pt.y = TOUCH_COORD_TO_PIXEL(ti.y);
  501. ScreenToClient(hWnd, &pt);
  502. touchInfo.position.x = pt.x;
  503. touchInfo.position.y = pt.y;
  504. touches.push_back(touchInfo);
  505. }
  506. for(int i = 0; i < iNumContacts; i++) {
  507. TOUCHINPUT ti = pInputs[i];
  508. if (ti.dwFlags & TOUCHEVENTF_UP) {
  509. Win32Event newEvent;
  510. newEvent.eventGroup = Win32Event::INPUT_EVENT;
  511. newEvent.eventCode = InputEvent::EVENT_TOUCHES_ENDED;
  512. newEvent.touches = touches;
  513. newEvent.touch = touches[i];
  514. win32Events.push_back(newEvent);
  515. } else if(ti.dwFlags & TOUCHEVENTF_MOVE) {
  516. Win32Event newEvent;
  517. newEvent.eventGroup = Win32Event::INPUT_EVENT;
  518. newEvent.eventCode = InputEvent::EVENT_TOUCHES_MOVED;
  519. newEvent.touches = touches;
  520. newEvent.touch = touches[i];
  521. win32Events.push_back(newEvent);
  522. } else if(ti.dwFlags & TOUCHEVENTF_DOWN) {
  523. Win32Event newEvent;
  524. newEvent.eventGroup = Win32Event::INPUT_EVENT;
  525. newEvent.eventCode = InputEvent::EVENT_TOUCHES_BEGAN;
  526. newEvent.touches = touches;
  527. newEvent.touch = touches[i];
  528. win32Events.push_back(newEvent);
  529. }
  530. }
  531. }
  532. }
  533. unlockMutex(eventMutex);
  534. }
  535. #endif
  536. void Win32Core::handleMouseMove(LPARAM lParam, WPARAM wParam) {
  537. lockMutex(eventMutex);
  538. Win32Event newEvent;
  539. newEvent.eventGroup = Win32Event::INPUT_EVENT;
  540. newEvent.eventCode = InputEvent::EVENT_MOUSEMOVE;
  541. newEvent.mouseX = GET_X_LPARAM(lParam);
  542. newEvent.mouseY = GET_Y_LPARAM(lParam);
  543. win32Events.push_back(newEvent);
  544. unlockMutex(eventMutex);
  545. }
  546. void Win32Core::handleMouseWheel(LPARAM lParam, WPARAM wParam) {
  547. lockMutex(eventMutex);
  548. Win32Event newEvent;
  549. newEvent.eventGroup = Win32Event::INPUT_EVENT;
  550. newEvent.mouseX = GET_X_LPARAM(lParam);
  551. newEvent.mouseY = GET_Y_LPARAM(lParam);
  552. int zDelta = GET_WHEEL_DELTA_WPARAM(wParam);
  553. if(zDelta < 0)
  554. newEvent.eventCode = InputEvent::EVENT_MOUSEWHEEL_DOWN;
  555. else
  556. newEvent.eventCode = InputEvent::EVENT_MOUSEWHEEL_UP;
  557. win32Events.push_back(newEvent);
  558. unlockMutex(eventMutex);
  559. }
  560. void Win32Core::handleMouseDown(int mouseCode,LPARAM lParam, WPARAM wParam) {
  561. lockMutex(eventMutex);
  562. Win32Event newEvent;
  563. newEvent.eventGroup = Win32Event::INPUT_EVENT;
  564. newEvent.mouseX = GET_X_LPARAM(lParam);
  565. newEvent.mouseY = GET_Y_LPARAM(lParam);
  566. newEvent.eventCode = InputEvent::EVENT_MOUSEDOWN;
  567. newEvent.mouseButton = mouseCode;
  568. win32Events.push_back(newEvent);
  569. unlockMutex(eventMutex);
  570. }
  571. void Win32Core::handleMouseUp(int mouseCode,LPARAM lParam, WPARAM wParam) {
  572. lockMutex(eventMutex);
  573. Win32Event newEvent;
  574. newEvent.eventGroup = Win32Event::INPUT_EVENT;
  575. newEvent.mouseX = GET_X_LPARAM(lParam);
  576. newEvent.mouseY = GET_Y_LPARAM(lParam);
  577. newEvent.eventCode = InputEvent::EVENT_MOUSEUP;
  578. newEvent.mouseButton = mouseCode;
  579. win32Events.push_back(newEvent);
  580. unlockMutex(eventMutex);
  581. }
  582. bool Win32Core::checkSpecialKeyEvents(PolyKEY key) {
  583. if(key == KEY_a && (input->getKeyState(KEY_LCTRL) || input->getKeyState(KEY_RCTRL))) {
  584. dispatchEvent(new Event(), Core::EVENT_SELECT_ALL);
  585. return true;
  586. }
  587. if(key == KEY_c && (input->getKeyState(KEY_LCTRL) || input->getKeyState(KEY_RCTRL))) {
  588. dispatchEvent(new Event(), Core::EVENT_COPY);
  589. return true;
  590. }
  591. if(key == KEY_x && (input->getKeyState(KEY_LCTRL) || input->getKeyState(KEY_RCTRL))) {
  592. dispatchEvent(new Event(), Core::EVENT_CUT);
  593. return true;
  594. }
  595. if(key == KEY_y && (input->getKeyState(KEY_LCTRL) || input->getKeyState(KEY_RCTRL))) {
  596. dispatchEvent(new Event(), Core::EVENT_REDO);
  597. return true;
  598. }
  599. if(key == KEY_z && (input->getKeyState(KEY_LCTRL) || input->getKeyState(KEY_RCTRL))) {
  600. dispatchEvent(new Event(), Core::EVENT_UNDO);
  601. return true;
  602. }
  603. if(key == KEY_v && (input->getKeyState(KEY_LCTRL) || input->getKeyState(KEY_RCTRL))) {
  604. dispatchEvent(new Event(), Core::EVENT_PASTE);
  605. return true;
  606. }
  607. return false;
  608. }
  609. void Win32Core::checkEvents() {
  610. lockMutex(eventMutex);
  611. Win32Event event;
  612. for(int i=0; i < win32Events.size(); i++) {
  613. event = win32Events[i];
  614. switch(event.eventGroup) {
  615. case Win32Event::INPUT_EVENT:
  616. switch(event.eventCode) {
  617. case InputEvent::EVENT_TOUCHES_BEGAN:
  618. input->touchesBegan(event.touch, event.touches, getTicks());
  619. break;
  620. case InputEvent::EVENT_TOUCHES_ENDED:
  621. input->touchesEnded(event.touch, event.touches, getTicks());
  622. break;
  623. case InputEvent::EVENT_TOUCHES_MOVED:
  624. input->touchesMoved(event.touch, event.touches, getTicks());
  625. break;
  626. case InputEvent::EVENT_MOUSEMOVE:
  627. input->setDeltaPosition(event.mouseX - lastMouseX , event.mouseY - lastMouseY);
  628. lastMouseX = event.mouseX;
  629. lastMouseY = event.mouseY;
  630. input->setMousePosition(event.mouseX, event.mouseY, getTicks());
  631. break;
  632. case InputEvent::EVENT_MOUSEDOWN:
  633. input->setMouseButtonState(event.mouseButton, true, getTicks());
  634. break;
  635. case InputEvent::EVENT_MOUSEUP:
  636. input->setMouseButtonState(event.mouseButton, false, getTicks());
  637. break;
  638. case InputEvent::EVENT_MOUSEWHEEL_UP:
  639. input->mouseWheelUp(getTicks());
  640. break;
  641. case InputEvent::EVENT_MOUSEWHEEL_DOWN:
  642. input->mouseWheelDown(getTicks());
  643. break;
  644. case InputEvent::EVENT_KEYDOWN:
  645. if(!checkSpecialKeyEvents((event.keyCode))) {
  646. input->setKeyState(event.keyCode, (char)event.unicodeChar, true, getTicks());
  647. }
  648. break;
  649. case InputEvent::EVENT_KEYUP:
  650. input->setKeyState(event.keyCode, (char)event.unicodeChar, false, getTicks());
  651. break;
  652. }
  653. break;
  654. }
  655. }
  656. win32Events.clear();
  657. unlockMutex(eventMutex);
  658. }
  659. void Win32Core::handleAxisChange(GamepadDeviceEntry * device, int axisIndex, DWORD value) {
  660. if (axisIndex < 0 || axisIndex >= (int) device->numAxes) {
  661. return;
  662. }
  663. Gamepad_devicePrivate *devicePrivate = device->privateData;
  664. float floatVal = (value - devicePrivate->axisRanges[axisIndex][0]) / (float) (devicePrivate->axisRanges[axisIndex][1] - devicePrivate->axisRanges[axisIndex][0]) * 2.0f - 1.0f;
  665. input->joystickAxisMoved(axisIndex, floatVal, device->deviceID);
  666. }
  667. void Win32Core::handleButtonChange(GamepadDeviceEntry * device, DWORD lastValue, DWORD value) {
  668. Gamepad_devicePrivate *devicePrivate = device->privateData;
  669. unsigned int buttonIndex;
  670. for (buttonIndex = 0; buttonIndex < device->numButtons; buttonIndex++) {
  671. if ((lastValue ^ value) & (1 << buttonIndex)) {
  672. if(!!(value & (1 << buttonIndex))) {
  673. input->joystickButtonDown(buttonIndex, device->deviceID);
  674. } else {
  675. input->joystickButtonUp(buttonIndex, device->deviceID);
  676. }
  677. }
  678. }
  679. }
  680. static void povToXY(DWORD pov, int * outX, int * outY) {
  681. if (pov == JOY_POVCENTERED) {
  682. *outX = *outY = 0;
  683. } else {
  684. if (pov > JOY_POVFORWARD && pov < JOY_POVBACKWARD) {
  685. *outX = 1;
  686. } else if (pov > JOY_POVBACKWARD) {
  687. *outX = -1;
  688. } else {
  689. *outX = 0;
  690. }
  691. if (pov > JOY_POVLEFT || pov < JOY_POVRIGHT) {
  692. *outY = -1;
  693. } else if (pov > JOY_POVRIGHT && pov < JOY_POVLEFT) {
  694. *outY = 1;
  695. } else {
  696. *outY = 0;
  697. }
  698. }
  699. }
  700. void Win32Core::handlePOVChange(GamepadDeviceEntry * device, DWORD lastValue, DWORD value) {
  701. Gamepad_devicePrivate *devicePrivate = device->privateData;
  702. int lastX, lastY, newX, newY;
  703. if (devicePrivate->povXAxisIndex == -1 || devicePrivate->povYAxisIndex == -1) {
  704. return;
  705. }
  706. povToXY(lastValue, &lastX, &lastY);
  707. povToXY(value, &newX, &newY);
  708. if (newX != lastX) {
  709. input->joystickAxisMoved(devicePrivate->povXAxisIndex, newX, device->deviceID);
  710. }
  711. if (newY != lastY) {
  712. input->joystickAxisMoved(devicePrivate->povYAxisIndex, newY, device->deviceID);
  713. }
  714. }
  715. void Win32Core::Gamepad_processEvents() {
  716. if(getTicks() > lastGamepadDetect + 3000) {
  717. detectGamepads();
  718. }
  719. unsigned int deviceIndex;
  720. JOYINFOEX info;
  721. MMRESULT result;
  722. GamepadDeviceEntry * device;
  723. Gamepad_devicePrivate * devicePrivate;
  724. for (deviceIndex = 0; deviceIndex < gamepads.size(); deviceIndex++) {
  725. device = gamepads[deviceIndex];
  726. devicePrivate = device->privateData;
  727. info.dwSize = sizeof(info);
  728. info.dwFlags = JOY_RETURNALL;
  729. result = joyGetPosEx(devicePrivate->joystickID, &info);
  730. if (result == JOYERR_UNPLUGGED) {
  731. input->removeJoystick(device->deviceID);
  732. gamepads.erase(gamepads.begin() + deviceIndex);
  733. } else if (result == JOYERR_NOERROR) {
  734. if (info.dwXpos != devicePrivate->lastState.dwXpos) {
  735. handleAxisChange(device, devicePrivate->xAxisIndex, info.dwXpos);
  736. }
  737. if (info.dwYpos != devicePrivate->lastState.dwYpos) {
  738. handleAxisChange(device, devicePrivate->yAxisIndex, info.dwYpos);
  739. }
  740. if (info.dwZpos != devicePrivate->lastState.dwZpos) {
  741. handleAxisChange(device, devicePrivate->zAxisIndex, info.dwZpos);
  742. }
  743. if (info.dwRpos != devicePrivate->lastState.dwRpos) {
  744. handleAxisChange(device, devicePrivate->rAxisIndex, info.dwRpos);
  745. }
  746. if (info.dwUpos != devicePrivate->lastState.dwUpos) {
  747. handleAxisChange(device, devicePrivate->uAxisIndex, info.dwUpos);
  748. }
  749. if (info.dwVpos != devicePrivate->lastState.dwVpos) {
  750. handleAxisChange(device, devicePrivate->vAxisIndex, info.dwVpos);
  751. }
  752. if (info.dwPOV != devicePrivate->lastState.dwPOV) {
  753. handlePOVChange(device, devicePrivate->lastState.dwPOV, info.dwPOV);
  754. }
  755. if (info.dwButtons != devicePrivate->lastState.dwButtons) {
  756. handleButtonChange(device, devicePrivate->lastState.dwButtons, info.dwButtons);
  757. }
  758. devicePrivate->lastState = info;
  759. }
  760. }
  761. }
  762. void Win32Core::detectGamepads() {
  763. lastGamepadDetect = getTicks();
  764. unsigned int numPadsSupported;
  765. unsigned int deviceIndex, deviceIndex2;
  766. JOYINFOEX info;
  767. JOYCAPS caps;
  768. bool duplicate;
  769. Gamepad_devicePrivate * deviceRecordPrivate;
  770. UINT joystickID;
  771. int axisIndex;
  772. numPadsSupported = joyGetNumDevs();
  773. for (deviceIndex = 0; deviceIndex < numPadsSupported; deviceIndex++) {
  774. info.dwSize = sizeof(info);
  775. info.dwFlags = JOY_RETURNALL;
  776. joystickID = JOYSTICKID1 + deviceIndex;
  777. if (joyGetPosEx(joystickID, &info) == JOYERR_NOERROR &&
  778. joyGetDevCaps(joystickID, &caps, sizeof(JOYCAPS)) == JOYERR_NOERROR) {
  779. duplicate = false;
  780. for (deviceIndex2 = 0; deviceIndex2 < gamepads.size(); deviceIndex2++) {
  781. if (((Gamepad_devicePrivate *) gamepads[deviceIndex2]->privateData)->joystickID == joystickID) {
  782. duplicate = true;
  783. break;
  784. }
  785. }
  786. if (duplicate) {
  787. continue;
  788. }
  789. GamepadDeviceEntry *deviceRecord = new GamepadDeviceEntry();
  790. deviceRecord->deviceID = nextDeviceID++;
  791. // deviceRecord->description = getDeviceDescription(joystickID, caps);
  792. // deviceRecord->vendorID = caps.wMid;
  793. // deviceRecord->productID = caps.wPid;
  794. deviceRecord->numAxes = caps.wNumAxes + ((caps.wCaps & JOYCAPS_HASPOV) ? 2 : 0);
  795. deviceRecord->numButtons = caps.wNumButtons;
  796. // deviceRecord->axisStates = calloc(sizeof(float), deviceRecord->numAxes);
  797. // deviceRecord->buttonStates = calloc(sizeof(bool), deviceRecord->numButtons);
  798. // deviceRecord->eventDispatcher = EventDispatcher_create(deviceRecord);
  799. // devices = realloc(devices, sizeof(struct Gamepad_device *) * (numDevices + 1));
  800. gamepads.push_back(deviceRecord);
  801. deviceRecordPrivate = new Gamepad_devicePrivate();
  802. deviceRecordPrivate->joystickID = joystickID;
  803. deviceRecordPrivate->lastState = info;
  804. deviceRecordPrivate->xAxisIndex = 0;
  805. deviceRecordPrivate->yAxisIndex = 1;
  806. axisIndex = 2;
  807. deviceRecordPrivate->zAxisIndex = (caps.wCaps & JOYCAPS_HASZ) ? axisIndex++ : -1;
  808. deviceRecordPrivate->rAxisIndex = (caps.wCaps & JOYCAPS_HASR) ? axisIndex++ : -1;
  809. deviceRecordPrivate->uAxisIndex = (caps.wCaps & JOYCAPS_HASU) ? axisIndex++ : -1;
  810. deviceRecordPrivate->vAxisIndex = (caps.wCaps & JOYCAPS_HASV) ? axisIndex++ : -1;
  811. deviceRecordPrivate->axisRanges = (UINT (*)[2]) malloc(sizeof(UINT[2]) * axisIndex);
  812. deviceRecordPrivate->axisRanges[0][0] = caps.wXmin;
  813. deviceRecordPrivate->axisRanges[0][1] = caps.wXmax;
  814. deviceRecordPrivate->axisRanges[1][0] = caps.wYmin;
  815. deviceRecordPrivate->axisRanges[1][1] = caps.wYmax;
  816. if (deviceRecordPrivate->zAxisIndex != -1) {
  817. deviceRecordPrivate->axisRanges[deviceRecordPrivate->zAxisIndex][0] = caps.wZmin;
  818. deviceRecordPrivate->axisRanges[deviceRecordPrivate->zAxisIndex][1] = caps.wZmax;
  819. }
  820. if (deviceRecordPrivate->rAxisIndex != -1) {
  821. deviceRecordPrivate->axisRanges[deviceRecordPrivate->rAxisIndex][0] = caps.wRmin;
  822. deviceRecordPrivate->axisRanges[deviceRecordPrivate->rAxisIndex][1] = caps.wRmax;
  823. }
  824. if (deviceRecordPrivate->uAxisIndex != -1) {
  825. deviceRecordPrivate->axisRanges[deviceRecordPrivate->uAxisIndex][0] = caps.wUmin;
  826. deviceRecordPrivate->axisRanges[deviceRecordPrivate->uAxisIndex][1] = caps.wUmax;
  827. }
  828. if (deviceRecordPrivate->vAxisIndex != -1) {
  829. deviceRecordPrivate->axisRanges[deviceRecordPrivate->vAxisIndex][0] = caps.wVmin;
  830. deviceRecordPrivate->axisRanges[deviceRecordPrivate->vAxisIndex][1] = caps.wVmax;
  831. }
  832. deviceRecordPrivate->povXAxisIndex = (caps.wCaps & JOYCAPS_HASPOV) ? axisIndex++ : -1;
  833. deviceRecordPrivate->povYAxisIndex = (caps.wCaps & JOYCAPS_HASPOV) ? axisIndex++ : -1;
  834. deviceRecord->privateData = deviceRecordPrivate;
  835. input->addJoystick(deviceRecord->deviceID);
  836. }
  837. }
  838. }
  839. void Win32Core::initGamepad() {
  840. nextDeviceID = 0;
  841. detectGamepads();
  842. }
  843. void Win32Core::shutdownGamepad() {
  844. }
  845. void Win32Core::initTouch() {
  846. #ifdef NO_TOUCH_API
  847. hasMultiTouch = false;
  848. #else
  849. // Check for windows multitouch support at runtime
  850. // This could be done easily during preprocessing but would require building
  851. // multiple releases of polycode for both winxp/vista and win7
  852. GetTouchInputInfoFunc = (GetTouchInputInfoType) GetProcAddress(GetModuleHandle(TEXT("user32")), "GetTouchInputInfo");
  853. // If the above multitouch functions were found, then set a flag so we don't
  854. // have to check again later
  855. hasMultiTouch = ( GetTouchInputInfoFunc == NULL ) ? false : true;
  856. if(hasMultiTouch) {
  857. RegisterTouchWindow(hWnd, 0);
  858. }
  859. #endif
  860. }
  861. DWORD WINAPI Win32LaunchThread(LPVOID data) {
  862. Threaded *threaded = (Threaded*)data;
  863. threaded->runThread();
  864. return 1;
  865. }
  866. void Win32Core::createThread(Threaded *target) {
  867. Core::createThread(target);
  868. DWORD dwGenericThread;
  869. HANDLE handle = CreateThread(NULL,0,Win32LaunchThread,target,0,&dwGenericThread);
  870. }
  871. void Win32Core::lockMutex(CoreMutex *mutex) {
  872. WaitForSingleObject(((Win32Mutex*)mutex)->winMutex,INFINITE);
  873. }
  874. void Win32Core::unlockMutex(CoreMutex *mutex) {
  875. ReleaseMutex(((Win32Mutex*)mutex)->winMutex);
  876. }
  877. void Win32Core::platformSleep(int msecs) {
  878. Sleep(msecs);
  879. }
  880. CoreMutex *Win32Core::createMutex() {
  881. Win32Mutex *newMutex = new Win32Mutex();
  882. newMutex->winMutex = CreateMutex( NULL, FALSE, NULL);
  883. return newMutex;
  884. }
  885. std::vector<Polycode::Rectangle> Win32Core::getVideoModes() {
  886. std::vector<Polycode::Rectangle> retVector;
  887. return retVector;
  888. }
  889. String Win32Core::executeExternalCommand(String command, String args, String inDirectory) {
  890. String execInDirectory = inDirectory;
  891. if(inDirectory == "") {
  892. execInDirectory = defaultWorkingDirectory;
  893. }
  894. String cmdString = "cd \""+execInDirectory+"\" & "+command+" "+args;
  895. char psBuffer[128];
  896. FILE *pPipe;
  897. if((pPipe = _popen(cmdString.c_str(), "rt" )) == NULL) {
  898. return "";
  899. }
  900. String retString;
  901. while(fgets(psBuffer, 128, pPipe)) {
  902. retString += String(psBuffer);
  903. }
  904. _pclose(pPipe);
  905. return retString;
  906. }
  907. String Win32Core::openFolderPicker() {
  908. TCHAR szDir[2048];
  909. BROWSEINFO bInfo;
  910. bInfo.hwndOwner = hWnd;
  911. bInfo.pidlRoot = NULL;
  912. bInfo.pszDisplayName = szDir;
  913. bInfo.lpszTitle = L"Choose a folder";
  914. bInfo.ulFlags = BIF_USENEWUI;
  915. bInfo.lpfn = NULL;
  916. bInfo.lParam = 0;
  917. bInfo.iImage = -1;
  918. LPITEMIDLIST lpItem = SHBrowseForFolder( &bInfo);
  919. if( lpItem != NULL ) {
  920. SHGetPathFromIDList(lpItem, szDir );
  921. return String(szDir);
  922. }
  923. return "";
  924. }
  925. std::vector<String> Win32Core::openFilePicker(std::vector<CoreFileExtension> extensions, bool allowMultiple) {
  926. OPENFILENAME ofn;
  927. wchar_t fBuffer[2048];
  928. wchar_t filterString[2048];
  929. ZeroMemory(&ofn, sizeof(OPENFILENAME));
  930. ofn.lStructSize = sizeof ( ofn );
  931. ofn.hwndOwner = hWnd ;
  932. ofn.lpstrFile = fBuffer;
  933. ofn.lpstrFile[0] = '\0';
  934. ofn.nMaxFile = sizeof( fBuffer );
  935. if(extensions.size() > 0) {
  936. int offset = 0;
  937. for(int i =0; i < extensions.size(); i++) {
  938. // filterString += extensions[i].description+"\0*."+extensions[i].extension+"\0";
  939. memcpy(filterString+offset, extensions[i].description.getWDataWithEncoding(String::ENCODING_UTF8), extensions[i].description.length() * sizeof(wchar_t));
  940. offset += extensions[i].description.length();
  941. filterString[offset] = '\0';
  942. offset++;
  943. filterString[offset] = '*';
  944. offset++;
  945. filterString[offset] = '.';
  946. offset++;
  947. memcpy(filterString+offset, extensions[i].extension.getWDataWithEncoding(String::ENCODING_UTF8), extensions[i].extension.length() * sizeof(wchar_t));
  948. offset += extensions[i].extension.length();
  949. filterString[offset] = '\0';
  950. offset++;
  951. }
  952. filterString[offset] = '\0';
  953. ofn.lpstrFilter = filterString;
  954. ofn.nFilterIndex = 1;
  955. } else {
  956. ofn.lpstrFilter = NULL;
  957. }
  958. ofn.lpstrFileTitle = NULL;
  959. ofn.nMaxFileTitle = 0;
  960. ofn.lpstrInitialDir=NULL;
  961. if(allowMultiple) {
  962. ofn.Flags = OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST|OFN_EXPLORER;
  963. } else {
  964. ofn.Flags = OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST|OFN_ALLOWMULTISELECT|OFN_EXPLORER;
  965. }
  966. std::vector<String> retVec;
  967. if(GetOpenFileName(&ofn)) {
  968. if(allowMultiple) {
  969. } else {
  970. retVec.push_back(String(fBuffer));
  971. }
  972. }
  973. SetCurrentDirectory(defaultWorkingDirectory.getWDataWithEncoding(String::ENCODING_UTF8));
  974. for(int i=0; i < retVec.size(); i++) {
  975. retVec[i] = retVec[i].replace("\\", "/");
  976. }
  977. return retVec;
  978. }
  979. String Win32Core::saveFilePicker(std::vector<CoreFileExtension> extensions) {
  980. OPENFILENAME ofn;
  981. wchar_t fBuffer[2048];
  982. wchar_t filterString[2048];
  983. ZeroMemory(&ofn, sizeof(OPENFILENAME));
  984. ofn.lStructSize = sizeof (ofn);
  985. ofn.hwndOwner = hWnd;
  986. ofn.lpstrFile = fBuffer;
  987. ofn.lpstrFile[0] = '\0';
  988. ofn.nMaxFile = sizeof(fBuffer);
  989. if (extensions.size() > 0) {
  990. int offset = 0;
  991. for (int i = 0; i < extensions.size(); i++) {
  992. // filterString += extensions[i].description+"\0*."+extensions[i].extension+"\0";
  993. memcpy(filterString + offset, extensions[i].description.getWDataWithEncoding(String::ENCODING_UTF8), extensions[i].description.length() * sizeof(wchar_t));
  994. offset += extensions[i].description.length();
  995. filterString[offset] = '\0';
  996. offset++;
  997. filterString[offset] = '*';
  998. offset++;
  999. filterString[offset] = '.';
  1000. offset++;
  1001. memcpy(filterString + offset, extensions[i].extension.getWDataWithEncoding(String::ENCODING_UTF8), extensions[i].extension.length() * sizeof(wchar_t));
  1002. offset += extensions[i].extension.length();
  1003. filterString[offset] = '\0';
  1004. offset++;
  1005. }
  1006. filterString[offset] = '\0';
  1007. ofn.lpstrFilter = filterString;
  1008. ofn.nFilterIndex = 1;
  1009. }
  1010. else {
  1011. ofn.lpstrFilter = NULL;
  1012. }
  1013. ofn.lpstrFileTitle = NULL;
  1014. ofn.nMaxFileTitle = 0;
  1015. ofn.lpstrInitialDir = NULL;
  1016. ofn.Flags = OFN_PATHMUSTEXIST | OFN_EXPLORER;
  1017. std::vector<String> retVec;
  1018. String retPath = "";
  1019. if (GetSaveFileName(&ofn)) {
  1020. retPath = String(fBuffer);
  1021. }
  1022. SetCurrentDirectory(defaultWorkingDirectory.getWDataWithEncoding(String::ENCODING_UTF8));
  1023. retPath = retPath.replace("\\", "/");
  1024. return retPath;
  1025. }
  1026. void Win32Core::createFolder(const String& folderPath) {
  1027. String path = folderPath;
  1028. CreateDirectory(path.getWDataWithEncoding(String::ENCODING_UTF8), NULL);
  1029. }
  1030. void Win32Core::openURL(String url) {
  1031. ShellExecute(NULL, L"open", url.getWDataWithEncoding(String::ENCODING_UTF8), NULL, NULL, SW_SHOWNORMAL);
  1032. }
  1033. String error_to_string(const DWORD a_error_code)
  1034. {
  1035. // Get the last windows error message.
  1036. wchar_t msg_buf[1025] = { 0 };
  1037. // Get the error message for our os code.
  1038. if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
  1039. 0,
  1040. a_error_code,
  1041. 0,
  1042. msg_buf,
  1043. sizeof(msg_buf) - 1,
  1044. 0))
  1045. {
  1046. return String(msg_buf);
  1047. }
  1048. return String("Failed to get error message");
  1049. }
  1050. void Win32Core::copyDiskItem(const String& itemPath, const String& destItemPath) {
  1051. SHFILEOPSTRUCT op;
  1052. ZeroMemory(&op, sizeof(SHFILEOPSTRUCT));
  1053. String fromPath = itemPath.replace("/", "\\");
  1054. String toPath =destItemPath.replace("/", "\\");
  1055. fromPath.append('\0');
  1056. toPath.append('\0');
  1057. printf("Copying %s to %s\n", fromPath.c_str(), toPath.c_str());
  1058. op.hwnd = hWnd;
  1059. op.wFunc = FO_COPY;
  1060. op.pFrom = fromPath.getWDataWithEncoding(String::ENCODING_UTF8);
  1061. op.pTo = toPath.getWDataWithEncoding(String::ENCODING_UTF8);
  1062. op.fFlags = FOF_NOCONFIRMATION | FOF_SILENT | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR;
  1063. int ret = SHFileOperation(&op);
  1064. if(ret != 0) {
  1065. String err = error_to_string(ret);
  1066. printf("COPY ERROR: %s\n", err.c_str());
  1067. }
  1068. }
  1069. void Win32Core::moveDiskItem(const String& itemPath, const String& destItemPath) {
  1070. SHFILEOPSTRUCT op;
  1071. ZeroMemory(&op, sizeof(SHFILEOPSTRUCT));
  1072. String fromPath = itemPath.replace("/", "\\");
  1073. String toPath =destItemPath.replace("/", "\\");
  1074. fromPath.append('\0');
  1075. toPath.append('\0');
  1076. printf("Moving %s to %s\n", fromPath.c_str(), toPath.c_str());
  1077. op.hwnd = hWnd;
  1078. op.wFunc = FO_MOVE;
  1079. op.pFrom = fromPath.getWDataWithEncoding(String::ENCODING_UTF8);
  1080. op.pTo = toPath.getWDataWithEncoding(String::ENCODING_UTF8);
  1081. op.fFlags = FOF_NOCONFIRMATION | FOF_SILENT | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR;
  1082. int ret = SHFileOperation(&op);
  1083. if(ret != 0) {
  1084. String err = error_to_string(ret);
  1085. printf("MOVE ERROR: %s\n", err.c_str());
  1086. }
  1087. }
  1088. void Win32Core::removeDiskItem(const String& itemPath) {
  1089. SHFILEOPSTRUCT op;
  1090. ZeroMemory(&op, sizeof(SHFILEOPSTRUCT));
  1091. String fromPath = itemPath.replace("/", "\\");
  1092. fromPath.append('\0');
  1093. op.hwnd = hWnd;
  1094. op.wFunc = FO_DELETE;
  1095. op.pFrom = fromPath.getWDataWithEncoding(String::ENCODING_UTF8);
  1096. op.fFlags = FOF_NOCONFIRMATION | FOF_SILENT | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR;
  1097. int ret = SHFileOperation(&op);
  1098. if(ret != 0) {
  1099. String err = error_to_string(ret);
  1100. printf("COPY ERROR: %s\n", err.c_str());
  1101. }
  1102. }
  1103. void Win32Core::setCursor(int cursorType) {
  1104. HCURSOR cursor;
  1105. switch(cursorType) {
  1106. case CURSOR_ARROW:
  1107. cursor = LoadCursor(NULL, IDC_ARROW);
  1108. break;
  1109. case CURSOR_TEXT:
  1110. cursor = LoadCursor(NULL, IDC_IBEAM);
  1111. break;
  1112. case CURSOR_POINTER:
  1113. cursor = LoadCursor(NULL, IDC_HAND);
  1114. break;
  1115. case CURSOR_CROSSHAIR:
  1116. cursor = LoadCursor(NULL, IDC_CROSS);
  1117. break;
  1118. case CURSOR_RESIZE_LEFT_RIGHT:
  1119. cursor = LoadCursor(NULL, IDC_SIZEWE);
  1120. break;
  1121. case CURSOR_RESIZE_UP_DOWN:
  1122. cursor = LoadCursor(NULL, IDC_SIZENS);
  1123. break;
  1124. case CURSOR_OPEN_HAND:
  1125. cursor = LoadCursor(NULL, IDC_SIZEALL);
  1126. break;
  1127. default:
  1128. cursor = LoadCursor(NULL, IDC_ARROW);
  1129. break;
  1130. }
  1131. SetCursor(cursor);
  1132. SetClassLongPtr(hWnd, GCLP_HCURSOR, (DWORD)cursor);
  1133. }
  1134. void Win32Core::copyStringToClipboard(const String& str) {
  1135. String _tmp = str;
  1136. std::wstring wstr = _tmp.getWDataWithEncoding(String::ENCODING_UTF8);
  1137. const size_t len = ((wstr.size()+1) * sizeof(wchar_t));
  1138. HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, len);
  1139. memcpy(GlobalLock(hMem), (char*)wstr.c_str(), len);
  1140. GlobalUnlock(hMem);
  1141. OpenClipboard(0);
  1142. EmptyClipboard();
  1143. SetClipboardData(CF_UNICODETEXT, hMem);
  1144. CloseClipboard();
  1145. }
  1146. String Win32Core::getClipboardString() {
  1147. OpenClipboard(0);
  1148. HANDLE clip0 = GetClipboardData(CF_UNICODETEXT);
  1149. HANDLE h= GlobalLock(clip0);
  1150. wchar_t* c = (wchar_t*) clip0;
  1151. String retString = String(c);
  1152. GlobalUnlock(clip0);
  1153. return retString;
  1154. }