PolyWinCore.cpp 37 KB

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