PolyWinCore.cpp 37 KB

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