PolyWinCore.cpp 38 KB

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