winWindow.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "platformWin32/platformWin32.h"
  24. #include "platformWin32/winConsole.h"
  25. #include "platformWin32/winDirectInput.h"
  26. #include "windowManager/win32/win32Window.h"
  27. #include "console/console.h"
  28. #include "console/engineAPI.h"
  29. #include "math/mRandom.h"
  30. #include "core/stream/fileStream.h"
  31. #include "T3D/resource.h"
  32. #include "gfx/gfxInit.h"
  33. #include "gfx/gfxDevice.h"
  34. #include "core/strings/unicode.h"
  35. #include "gui/core/guiCanvas.h"
  36. extern void createFontInit();
  37. extern void createFontShutdown();
  38. extern void installRedBookDevices();
  39. extern void handleRedBookCallback(U32, U32);
  40. static MRandomLCG sgPlatRandom;
  41. static bool sgQueueEvents;
  42. // is keyboard input a standard (non-changing) VK keycode
  43. #define dIsStandardVK(c) (((0x08 <= (c)) && ((c) <= 0x12)) || \
  44. ((c) == 0x1b) || \
  45. ((0x20 <= (c)) && ((c) <= 0x2e)) || \
  46. ((0x30 <= (c)) && ((c) <= 0x39)) || \
  47. ((0x41 <= (c)) && ((c) <= 0x5a)) || \
  48. ((0x70 <= (c)) && ((c) <= 0x7B)))
  49. extern InputObjectInstances DIK_to_Key( U8 dikCode );
  50. // static helper variables
  51. static HANDLE gMutexHandle = NULL;
  52. static bool sgDoubleByteEnabled = false;
  53. // track window states
  54. Win32PlatState winState;
  55. //-----------------------------------------------------------------------------------------------------------------------------------------------------------
  56. //
  57. // Microsoft Layer for Unicode
  58. // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/mslu/winprog/compiling_your_application_with_the_microsoft_layer_for_unicode.asp
  59. //
  60. //-----------------------------------------------------------------------------------------------------------------------------------------------------------
  61. #ifdef UNICODE
  62. HMODULE LoadUnicowsProc(void)
  63. {
  64. return(LoadLibraryA("unicows.dll"));
  65. }
  66. #ifdef _cplusplus
  67. extern "C" {
  68. #endif
  69. extern FARPROC _PfnLoadUnicows = (FARPROC) &LoadUnicowsProc;
  70. #ifdef _cplusplus
  71. }
  72. #endif
  73. #endif
  74. //--------------------------------------
  75. Win32PlatState::Win32PlatState()
  76. {
  77. log_fp = NULL;
  78. hinstOpenGL = NULL;
  79. hinstGLU = NULL;
  80. hinstOpenAL = NULL;
  81. appDC = NULL;
  82. appInstance = NULL;
  83. currentTime = 0;
  84. processId = 0;
  85. }
  86. //--------------------------------------
  87. bool Platform::excludeOtherInstances(const char *mutexName)
  88. {
  89. #ifdef UNICODE
  90. UTF16 b[512];
  91. convertUTF8toUTF16((UTF8 *)mutexName, b);
  92. gMutexHandle = CreateMutex(NULL, true, b);
  93. #else
  94. gMutexHandle = CreateMutex(NULL, true, mutexName);
  95. #endif
  96. if(!gMutexHandle)
  97. return false;
  98. if(GetLastError() == ERROR_ALREADY_EXISTS)
  99. {
  100. CloseHandle(gMutexHandle);
  101. gMutexHandle = NULL;
  102. return false;
  103. }
  104. return true;
  105. }
  106. void Platform::restartInstance()
  107. {
  108. STARTUPINFO si;
  109. PROCESS_INFORMATION pi;
  110. ZeroMemory( &si, sizeof(si) );
  111. si.cb = sizeof(si);
  112. ZeroMemory( &pi, sizeof(pi) );
  113. TCHAR cen_buf[2048];
  114. GetModuleFileName( NULL, cen_buf, 2047);
  115. // Start the child process.
  116. if( CreateProcess( cen_buf,
  117. NULL, // Command line
  118. NULL, // Process handle not inheritable
  119. NULL, // Thread handle not inheritable
  120. FALSE, // Set handle inheritance to FALSE
  121. 0, // No creation flags
  122. NULL, // Use parent's environment block
  123. NULL, // Use parent's starting directory
  124. &si, // Pointer to STARTUPINFO structure
  125. &pi ) // Pointer to PROCESS_INFORMATION structure
  126. != false )
  127. {
  128. WaitForInputIdle( pi.hProcess, 5000 );
  129. CloseHandle( pi.hProcess );
  130. CloseHandle( pi.hThread );
  131. }
  132. }
  133. ///just check if the app's global mutex exists, and if so,
  134. ///return true - otherwise, false. Should be called before ExcludeOther
  135. /// at very start of app execution.
  136. bool Platform::checkOtherInstances(const char *mutexName)
  137. {
  138. #ifdef TORQUE_MULTITHREAD
  139. HANDLE pMutex = NULL;
  140. #ifdef UNICODE
  141. UTF16 b[512];
  142. convertUTF8toUTF16((UTF8 *)mutexName, b);
  143. pMutex = CreateMutex(NULL, true, b);
  144. #else
  145. pMutex = CreateMutex(NULL, true, mutexName);
  146. #endif
  147. if(!pMutex)
  148. return false;
  149. if(GetLastError() == ERROR_ALREADY_EXISTS)
  150. {
  151. //another mutex of the same name exists
  152. //close ours
  153. CloseHandle(pMutex);
  154. pMutex = NULL;
  155. return true;
  156. }
  157. CloseHandle(pMutex);
  158. pMutex = NULL;
  159. #endif
  160. //we don;t care, always false
  161. return false;
  162. }
  163. #ifndef TORQUE_SDL
  164. //--------------------------------------
  165. void Platform::AlertOK(const char *windowTitle, const char *message)
  166. {
  167. ShowCursor(true);
  168. #ifdef UNICODE
  169. UTF16 m[1024], t[512];
  170. convertUTF8toUTF16((UTF8 *)windowTitle, t);
  171. convertUTF8toUTF16((UTF8 *)message, m);
  172. MessageBox(NULL, m, t, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TASKMODAL | MB_OK);
  173. #else
  174. MessageBox(NULL, message, windowTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TASKMODAL | MB_OK);
  175. #endif
  176. }
  177. //--------------------------------------
  178. bool Platform::AlertOKCancel(const char *windowTitle, const char *message)
  179. {
  180. ShowCursor(true);
  181. #ifdef UNICODE
  182. UTF16 m[1024], t[512];
  183. convertUTF8toUTF16((UTF8 *)windowTitle, t);
  184. convertUTF8toUTF16((UTF8 *)message, m);
  185. return MessageBox(NULL, m, t, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TASKMODAL | MB_OKCANCEL) == IDOK;
  186. #else
  187. return MessageBox(NULL, message, windowTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TASKMODAL | MB_OKCANCEL) == IDOK;
  188. #endif
  189. }
  190. //--------------------------------------
  191. bool Platform::AlertRetry(const char *windowTitle, const char *message)
  192. {
  193. ShowCursor(true);
  194. #ifdef UNICODE
  195. UTF16 m[1024], t[512];
  196. convertUTF8toUTF16((UTF8 *)windowTitle, t);
  197. convertUTF8toUTF16((UTF8 *)message, m);
  198. return (MessageBox(NULL, m, t, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TASKMODAL | MB_RETRYCANCEL) == IDRETRY);
  199. #else
  200. return (MessageBox(NULL, message, windowTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TASKMODAL | MB_RETRYCANCEL) == IDRETRY);
  201. #endif
  202. }
  203. Platform::ALERT_ASSERT_RESULT Platform::AlertAssert(const char *windowTitle, const char *message)
  204. {
  205. #ifndef TORQUE_TOOLS
  206. ShowCursor(true);
  207. #endif // TORQUE_TOOLS
  208. #ifdef UNICODE
  209. UTF16 messageUTF[1024], title[512];
  210. convertUTF8toUTF16((UTF8 *)windowTitle, title);
  211. convertUTF8toUTF16((UTF8 *)message, messageUTF);
  212. #else
  213. const char* messageUTF = message;
  214. const char* title = windowTitle;
  215. #endif
  216. // TODO: Change this to a custom dialog that has Exit, Ignore, Ignore All, and Debug buttons
  217. ALERT_ASSERT_RESULT alertResult = ALERT_ASSERT_DEBUG;
  218. int result = MessageBox(winState.appWindow, messageUTF, title, MB_ABORTRETRYIGNORE | MB_ICONSTOP | MB_DEFBUTTON2 | MB_TASKMODAL | MB_SETFOREGROUND);
  219. switch( result )
  220. {
  221. case IDABORT:
  222. alertResult = ALERT_ASSERT_EXIT;
  223. break;
  224. case IDIGNORE:
  225. alertResult = ALERT_ASSERT_IGNORE;
  226. break;
  227. default:
  228. case IDRETRY:
  229. alertResult = ALERT_ASSERT_DEBUG;
  230. break;
  231. }
  232. return alertResult;
  233. }
  234. #endif
  235. //--------------------------------------
  236. HIMC gIMEContext;
  237. static void InitInput()
  238. {
  239. #ifndef TORQUE_LIB
  240. #ifdef UNICODE
  241. //gIMEContext = ImmGetContext(getWin32WindowHandle());
  242. //ImmReleaseContext( getWin32WindowHandle(), gIMEContext );
  243. #endif
  244. #endif
  245. }
  246. //--------------------------------------
  247. void Platform::init()
  248. {
  249. Con::printf("Initializing platform...");
  250. // Set the platform variable for the scripts
  251. Con::setVariable( "$platform", "windows" );
  252. WinConsole::create();
  253. if ( !WinConsole::isEnabled() )
  254. Input::init();
  255. InitInput(); // in case DirectInput falls through
  256. installRedBookDevices();
  257. sgDoubleByteEnabled = GetSystemMetrics( SM_DBCSENABLED );
  258. sgQueueEvents = true;
  259. Con::printf("Done");
  260. }
  261. //--------------------------------------
  262. void Platform::shutdown()
  263. {
  264. sgQueueEvents = false;
  265. if(gMutexHandle)
  266. CloseHandle(gMutexHandle);
  267. Input::destroy();
  268. GFXDevice::destroy();
  269. WinConsole::destroy();
  270. UTF16ClearCache();
  271. }
  272. extern bool LinkConsoleFunctions;
  273. #ifndef TORQUE_SHARED
  274. extern S32 TorqueMain(S32 argc, const char **argv);
  275. //--------------------------------------
  276. static S32 run(S32 argc, const char **argv)
  277. {
  278. // Console hack to ensure consolefunctions get linked in
  279. LinkConsoleFunctions=true;
  280. createFontInit();
  281. S32 ret = TorqueMain(argc, argv);
  282. createFontShutdown();
  283. return ret;
  284. }
  285. //--------------------------------------
  286. S32 main(S32 argc, const char **argv)
  287. {
  288. winState.appInstance = GetModuleHandle(NULL);
  289. return run(argc, argv);
  290. }
  291. //--------------------------------------
  292. #include "app/mainLoop.h"
  293. S32 WINAPI WinMain( HINSTANCE hInstance, HINSTANCE, LPSTR lpszCmdLine, S32)
  294. {
  295. Vector<char *> argv( __FILE__, __LINE__ );
  296. enum { moduleNameSize = 256 };
  297. char moduleName[moduleNameSize];
  298. #ifdef TORQUE_UNICODE
  299. {
  300. TCHAR buf[ moduleNameSize ];
  301. GetModuleFileNameW( NULL, buf, moduleNameSize );
  302. convertUTF16toUTF8( buf, moduleName );
  303. }
  304. #else
  305. GetModuleFileNameA(NULL, moduleName, moduleNameSize);
  306. #endif
  307. argv.push_back(moduleName);
  308. for (const char* word,*ptr = lpszCmdLine; *ptr; )
  309. {
  310. // Eat white space
  311. for (; dIsspace(*ptr) && *ptr; ptr++)
  312. ;
  313. // Pick out the next word
  314. for (word = ptr; !dIsspace(*ptr) && *ptr; ptr++)
  315. ;
  316. // Add the word to the argument list.
  317. if (*word)
  318. {
  319. S32 len = ptr - word;
  320. char *arg = (char *) dMalloc(len + 1);
  321. dStrncpy(arg, word, len);
  322. arg[len] = 0;
  323. argv.push_back(arg);
  324. }
  325. }
  326. winState.appInstance = hInstance;
  327. S32 retVal = run(argv.size(), (const char **) argv.address());
  328. for(U32 j = 1; j < argv.size(); j++)
  329. dFree(argv[j]);
  330. return retVal;
  331. }
  332. #else //TORQUE_SHARED
  333. extern "C"
  334. {
  335. bool torque_engineinit(S32 argc, const char **argv);
  336. S32 torque_enginetick();
  337. S32 torque_getreturnstatus();
  338. bool torque_engineshutdown();
  339. };
  340. S32 TorqueMain(int argc, const char **argv)
  341. {
  342. if (!torque_engineinit(argc, argv))
  343. return 1;
  344. while(torque_enginetick())
  345. {
  346. }
  347. torque_engineshutdown();
  348. return torque_getreturnstatus();
  349. }
  350. extern "C" {
  351. TORQUE_API S32 torque_winmain( HINSTANCE hInstance, HINSTANCE, LPSTR lpszCmdLine, S32)
  352. {
  353. Vector<char *> argv( __FILE__, __LINE__ );
  354. enum { moduleNameSize = 256 };
  355. char moduleName[moduleNameSize];
  356. #ifdef TORQUE_UNICODE
  357. {
  358. TCHAR buf[ moduleNameSize ];
  359. GetModuleFileNameW( NULL, buf, moduleNameSize );
  360. convertUTF16toUTF8( buf, moduleName );
  361. }
  362. #else
  363. GetModuleFileNameA(NULL, moduleName, moduleNameSize);
  364. #endif
  365. argv.push_back(moduleName);
  366. for (const char* word,*ptr = lpszCmdLine; *ptr; )
  367. {
  368. // Eat white space
  369. for (; dIsspace(*ptr) && *ptr; ptr++)
  370. ;
  371. // Test for quotes
  372. bool withinQuotes = dIsquote(*ptr);
  373. if (!withinQuotes)
  374. {
  375. // Pick out the next word
  376. for (word = ptr; !dIsspace(*ptr) && *ptr; ptr++)
  377. ;
  378. }
  379. else
  380. {
  381. // Advance past the first quote. We don't want to include it.
  382. ptr++;
  383. // Pick out the next quote
  384. for (word = ptr; !dIsquote(*ptr) && *ptr; ptr++)
  385. ;
  386. }
  387. // Add the word to the argument list.
  388. if (*word)
  389. {
  390. S32 len = ptr - word;
  391. char *arg = (char *) dMalloc(len + 1);
  392. dStrncpy(arg, word, len);
  393. arg[len] = 0;
  394. argv.push_back(arg);
  395. }
  396. // If we had a quote, skip past it for the next arg
  397. if (withinQuotes && *ptr)
  398. {
  399. ptr++;
  400. }
  401. }
  402. winState.appInstance = hInstance;
  403. S32 retVal = TorqueMain(argv.size(), (const char **) argv.address());
  404. for(U32 j = 1; j < argv.size(); j++)
  405. dFree(argv[j]);
  406. return retVal;
  407. }
  408. } // extern "C"
  409. #endif
  410. //--------------------------------------
  411. F32 Platform::getRandom()
  412. {
  413. return sgPlatRandom.randF();
  414. }
  415. #ifndef TORQUE_SDL
  416. ////--------------------------------------
  417. /// Spawn the default Operating System web browser with a URL
  418. /// @param webAddress URL to pass to browser
  419. /// @return true if browser successfully spawned
  420. bool Platform::openWebBrowser( const char* webAddress )
  421. {
  422. static bool sHaveKey = false;
  423. static wchar_t sWebKey[512];
  424. char utf8WebKey[512];
  425. {
  426. HKEY regKey;
  427. DWORD size = sizeof( sWebKey );
  428. if ( RegOpenKeyEx( HKEY_CLASSES_ROOT, dT("\\http\\shell\\open\\command"), 0, KEY_QUERY_VALUE, &regKey ) != ERROR_SUCCESS )
  429. {
  430. Con::errorf( ConsoleLogEntry::General, "Platform::openWebBrowser - Failed to open the HKCR\\http registry key!!!");
  431. return( false );
  432. }
  433. if ( RegQueryValueEx( regKey, dT(""), NULL, NULL, (U8 *)sWebKey, &size ) != ERROR_SUCCESS )
  434. {
  435. Con::errorf( ConsoleLogEntry::General, "Platform::openWebBrowser - Failed to query the open command registry key!!!" );
  436. return( false );
  437. }
  438. RegCloseKey( regKey );
  439. sHaveKey = true;
  440. convertUTF16toUTF8(sWebKey,utf8WebKey);
  441. #ifdef UNICODE
  442. char *p = dStrstr((const char *)utf8WebKey, "%1");
  443. #else
  444. char *p = strstr( (const char *) sWebKey , "%1");
  445. #endif
  446. if (p) *p = 0;
  447. }
  448. STARTUPINFO si;
  449. dMemset( &si, 0, sizeof( si ) );
  450. si.cb = sizeof( si );
  451. char buf[1024];
  452. #ifdef UNICODE
  453. dSprintf( buf, sizeof( buf ), "%s %s", utf8WebKey, webAddress );
  454. UTF16 b[1024];
  455. convertUTF8toUTF16((UTF8 *)buf, b);
  456. #else
  457. dSprintf( buf, sizeof( buf ), "%s %s", sWebKey, webAddress );
  458. #endif
  459. //Con::errorf( ConsoleLogEntry::General, "** Web browser command = %s **", buf );
  460. PROCESS_INFORMATION pi;
  461. dMemset( &pi, 0, sizeof( pi ) );
  462. CreateProcess( NULL,
  463. #ifdef UNICODE
  464. b,
  465. #else
  466. buf,
  467. #endif
  468. NULL,
  469. NULL,
  470. false,
  471. CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP,
  472. NULL,
  473. NULL,
  474. &si,
  475. &pi );
  476. return( true );
  477. }
  478. #endif
  479. //--------------------------------------
  480. // Login password routines:
  481. //--------------------------------------
  482. #ifdef UNICODE
  483. static const UTF16* TorqueRegKey = dT("SOFTWARE\\GarageGames\\Torque");
  484. #else
  485. static const char* TorqueRegKey = "SOFTWARE\\GarageGames\\Torque";
  486. #endif
  487. const char* Platform::getLoginPassword()
  488. {
  489. HKEY regKey;
  490. char* returnString = NULL;
  491. if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, TorqueRegKey, 0, KEY_QUERY_VALUE, &regKey ) == ERROR_SUCCESS )
  492. {
  493. U8 buf[32];
  494. DWORD size = sizeof( buf );
  495. if ( RegQueryValueEx( regKey, dT("LoginPassword"), NULL, NULL, buf, &size ) == ERROR_SUCCESS )
  496. {
  497. returnString = Con::getReturnBuffer( size + 1 );
  498. dStrcpy( returnString, (const char*) buf, size + 1 );
  499. }
  500. RegCloseKey( regKey );
  501. }
  502. if ( returnString )
  503. return( returnString );
  504. else
  505. return( "" );
  506. }
  507. //--------------------------------------
  508. bool Platform::setLoginPassword( const char* password )
  509. {
  510. HKEY regKey;
  511. if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, TorqueRegKey, 0, KEY_WRITE, &regKey ) == ERROR_SUCCESS )
  512. {
  513. if ( RegSetValueEx( regKey, dT("LoginPassword"), 0, REG_SZ, (const U8*) password, dStrlen( password ) + 1 ) != ERROR_SUCCESS )
  514. Con::errorf( ConsoleLogEntry::General, "setLoginPassword - Failed to set the subkey value!" );
  515. RegCloseKey( regKey );
  516. return( true );
  517. }
  518. else
  519. Con::errorf( ConsoleLogEntry::General, "setLoginPassword - Failed to open the Torque registry key!" );
  520. return( false );
  521. }
  522. //--------------------------------------
  523. // Silly Korean registry key checker:
  524. //
  525. // NOTE: "Silly" refers to the nature of this hack, and is not intended
  526. // as commentary on Koreans as a nationality. Thank you for your
  527. // attention.
  528. //--------------------------------------
  529. DefineEngineFunction( isKoreanBuild, bool, ( ), , "isKoreanBuild()")
  530. {
  531. HKEY regKey;
  532. bool result = false;
  533. if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, TorqueRegKey, 0, KEY_QUERY_VALUE, &regKey ) == ERROR_SUCCESS )
  534. {
  535. DWORD val;
  536. DWORD size = sizeof( val );
  537. if ( RegQueryValueEx( regKey, dT("Korean"), NULL, NULL, (U8*) &val, &size ) == ERROR_SUCCESS )
  538. result = ( val > 0 );
  539. RegCloseKey( regKey );
  540. }
  541. return( result );
  542. }