PolyWinCore.cpp 38 KB

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