PolyWinCore.cpp 37 KB

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