os_windows.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457
  1. /*************************************************************************/
  2. /* os_windows.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* http://www.godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* */
  10. /* Permission is hereby granted, free of charge, to any person obtaining */
  11. /* a copy of this software and associated documentation files (the */
  12. /* "Software"), to deal in the Software without restriction, including */
  13. /* without limitation the rights to use, copy, modify, merge, publish, */
  14. /* distribute, sublicense, and/or sell copies of the Software, and to */
  15. /* permit persons to whom the Software is furnished to do so, subject to */
  16. /* the following conditions: */
  17. /* */
  18. /* The above copyright notice and this permission notice shall be */
  19. /* included in all copies or substantial portions of the Software. */
  20. /* */
  21. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  22. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  23. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  24. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  25. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  26. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  27. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  28. /*************************************************************************/
  29. #include "os_windows.h"
  30. #include "drivers/gles3/rasterizer_gles3.h"
  31. #include "os/memory_pool_dynamic_static.h"
  32. #include "drivers/windows/thread_windows.h"
  33. #include "drivers/windows/semaphore_windows.h"
  34. #include "drivers/windows/mutex_windows.h"
  35. #include "main/main.h"
  36. #include "drivers/windows/file_access_windows.h"
  37. #include "drivers/windows/dir_access_windows.h"
  38. #include "servers/visual/visual_server_raster.h"
  39. #include "servers/audio/audio_server_sw.h"
  40. //#include "servers/visual/visual_server_wrap_mt.h"
  41. #include "tcp_server_winsock.h"
  42. #include "packet_peer_udp_winsock.h"
  43. #include "stream_peer_winsock.h"
  44. #include "lang_table.h"
  45. #include "os/memory_pool_dynamic_prealloc.h"
  46. #include "globals.h"
  47. #include "io/marshalls.h"
  48. #include "joystick.h"
  49. #include "shlobj.h"
  50. #include <regstr.h>
  51. #include <process.h>
  52. static const WORD MAX_CONSOLE_LINES = 1500;
  53. extern "C" {
  54. #ifdef _MSC_VER
  55. _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
  56. #else
  57. __attribute__((visibility("default"))) DWORD NvOptimusEnablement = 0x00000001;
  58. #endif
  59. }
  60. #ifndef WM_MOUSEHWHEEL
  61. #define WM_MOUSEHWHEEL 0x020e
  62. #endif
  63. //#define STDOUT_FILE
  64. extern HINSTANCE godot_hinstance;
  65. void RedirectIOToConsole() {
  66. int hConHandle;
  67. intptr_t lStdHandle;
  68. CONSOLE_SCREEN_BUFFER_INFO coninfo;
  69. FILE *fp;
  70. // allocate a console for this app
  71. AllocConsole();
  72. // set the screen buffer to be big enough to let us scroll text
  73. GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),
  74. &coninfo);
  75. coninfo.dwSize.Y = MAX_CONSOLE_LINES;
  76. SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),
  77. coninfo.dwSize);
  78. // redirect unbuffered STDOUT to the console
  79. lStdHandle = (intptr_t)GetStdHandle(STD_OUTPUT_HANDLE);
  80. hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  81. fp = _fdopen( hConHandle, "w" );
  82. *stdout = *fp;
  83. setvbuf( stdout, NULL, _IONBF, 0 );
  84. // redirect unbuffered STDIN to the console
  85. lStdHandle = (intptr_t)GetStdHandle(STD_INPUT_HANDLE);
  86. hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  87. fp = _fdopen( hConHandle, "r" );
  88. *stdin = *fp;
  89. setvbuf( stdin, NULL, _IONBF, 0 );
  90. // redirect unbuffered STDERR to the console
  91. lStdHandle = (intptr_t)GetStdHandle(STD_ERROR_HANDLE);
  92. hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  93. fp = _fdopen( hConHandle, "w" );
  94. *stderr = *fp;
  95. setvbuf( stderr, NULL, _IONBF, 0 );
  96. // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
  97. // point to console as well
  98. }
  99. int OS_Windows::get_video_driver_count() const {
  100. return 1;
  101. }
  102. const char * OS_Windows::get_video_driver_name(int p_driver) const {
  103. return "GLES2";
  104. }
  105. OS::VideoMode OS_Windows::get_default_video_mode() const {
  106. return VideoMode(1024,600,false);
  107. }
  108. int OS_Windows::get_audio_driver_count() const {
  109. return AudioDriverManagerSW::get_driver_count();
  110. }
  111. const char * OS_Windows::get_audio_driver_name(int p_driver) const {
  112. AudioDriverSW* driver = AudioDriverManagerSW::get_driver(p_driver);
  113. ERR_FAIL_COND_V( !driver, "" );
  114. return AudioDriverManagerSW::get_driver(p_driver)->get_name();
  115. }
  116. static MemoryPoolDynamic *mempool_dynamic=NULL;
  117. void OS_Windows::initialize_core() {
  118. last_button_state=0;
  119. //RedirectIOToConsole();
  120. maximized=false;
  121. minimized=false;
  122. borderless=false;
  123. ThreadWindows::make_default();
  124. SemaphoreWindows::make_default();
  125. MutexWindows::make_default();
  126. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_RESOURCES);
  127. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_USERDATA);
  128. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_FILESYSTEM);
  129. //FileAccessBufferedFA<FileAccessWindows>::make_default();
  130. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_RESOURCES);
  131. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_USERDATA);
  132. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_FILESYSTEM);
  133. TCPServerWinsock::make_default();
  134. StreamPeerWinsock::make_default();
  135. PacketPeerUDPWinsock::make_default();
  136. #if 1
  137. mempool_dynamic = memnew( MemoryPoolDynamicStatic );
  138. #else
  139. #define DYNPOOL_SIZE 4*1024*1024
  140. void * buffer = malloc( DYNPOOL_SIZE );
  141. mempool_dynamic = memnew( MemoryPoolDynamicPrealloc(buffer,DYNPOOL_SIZE) );
  142. #endif
  143. // We need to know how often the clock is updated
  144. if( !QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second) )
  145. ticks_per_second = 1000;
  146. // If timeAtGameStart is 0 then we get the time since
  147. // the start of the computer when we call GetGameTime()
  148. ticks_start = 0;
  149. ticks_start = get_ticks_usec();
  150. process_map = memnew((Map<ProcessID, ProcessInfo>));
  151. IP_Unix::make_default();
  152. cursor_shape=CURSOR_ARROW;
  153. }
  154. bool OS_Windows::can_draw() const {
  155. return !minimized;
  156. };
  157. #define MI_WP_SIGNATURE 0xFF515700
  158. #define SIGNATURE_MASK 0xFFFFFF00
  159. #define IsPenEvent(dw) (((dw) & SIGNATURE_MASK) == MI_WP_SIGNATURE)
  160. void OS_Windows::_touch_event(bool p_pressed, int p_x, int p_y, int idx) {
  161. InputEvent event;
  162. event.type = InputEvent::SCREEN_TOUCH;
  163. event.ID=++last_id;
  164. event.screen_touch.index = idx;
  165. event.screen_touch.pressed = p_pressed;
  166. event.screen_touch.x=p_x;
  167. event.screen_touch.y=p_y;
  168. if (main_loop) {
  169. input->parse_input_event(event);
  170. }
  171. };
  172. void OS_Windows::_drag_event(int p_x, int p_y, int idx) {
  173. InputEvent event;
  174. event.type = InputEvent::SCREEN_DRAG;
  175. event.ID=++last_id;
  176. event.screen_drag.index = idx;
  177. event.screen_drag.x=p_x;
  178. event.screen_drag.y=p_y;
  179. if (main_loop)
  180. input->parse_input_event(event);
  181. };
  182. LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
  183. switch (uMsg) // Check For Windows Messages
  184. {
  185. case WM_ACTIVATE: // Watch For Window Activate Message
  186. {
  187. minimized = HIWORD(wParam) != 0;
  188. if (!main_loop) {
  189. return 0;
  190. };
  191. if (LOWORD(wParam) == WA_ACTIVE || LOWORD(wParam) == WA_CLICKACTIVE) {
  192. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
  193. alt_mem=false;
  194. control_mem=false;
  195. shift_mem=false;
  196. if (mouse_mode==MOUSE_MODE_CAPTURED) {
  197. RECT clipRect;
  198. GetClientRect(hWnd, &clipRect);
  199. ClientToScreen(hWnd, (POINT*) &clipRect.left);
  200. ClientToScreen(hWnd, (POINT*) &clipRect.right);
  201. ClipCursor(&clipRect);
  202. SetCapture(hWnd);
  203. }
  204. } else {
  205. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  206. alt_mem=false;
  207. };
  208. return 0; // Return To The Message Loop
  209. }
  210. case WM_PAINT:
  211. Main::force_redraw();
  212. break;
  213. case WM_SYSCOMMAND: // Intercept System Commands
  214. {
  215. switch (wParam) // Check System Calls
  216. {
  217. case SC_SCREENSAVE: // Screensaver Trying To Start?
  218. case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
  219. return 0; // Prevent From Happening
  220. case SC_KEYMENU:
  221. if ((lParam>>16)<=0)
  222. return 0;
  223. }
  224. break; // Exit
  225. }
  226. case WM_CLOSE: // Did We Receive A Close Message?
  227. {
  228. if (main_loop)
  229. main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  230. //force_quit=true;
  231. return 0; // Jump Back
  232. }
  233. case WM_MOUSELEAVE: {
  234. old_invalid=true;
  235. outside=true;
  236. if (main_loop && mouse_mode!=MOUSE_MODE_CAPTURED)
  237. main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
  238. if (input)
  239. input->set_mouse_in_window(false);
  240. } break;
  241. case WM_MOUSEMOVE: {
  242. if (outside) {
  243. //mouse enter
  244. if (main_loop && mouse_mode!=MOUSE_MODE_CAPTURED)
  245. main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
  246. if (input)
  247. input->set_mouse_in_window(true);
  248. CursorShape c=cursor_shape;
  249. cursor_shape=CURSOR_MAX;
  250. set_cursor_shape(c);
  251. outside=false;
  252. //Once-Off notification, must call again....
  253. TRACKMOUSEEVENT tme;
  254. tme.cbSize=sizeof(TRACKMOUSEEVENT);
  255. tme.dwFlags=TME_LEAVE;
  256. tme.hwndTrack=hWnd;
  257. tme.dwHoverTime=HOVER_DEFAULT;
  258. TrackMouseEvent(&tme);
  259. }
  260. /*
  261. LPARAM extra = GetMessageExtraInfo();
  262. if (IsPenEvent(extra)) {
  263. int idx = extra & 0x7f;
  264. _drag_event(idx, uMsg, wParam, lParam);
  265. if (idx != 0) {
  266. return 0;
  267. };
  268. // fallthrough for mouse event
  269. };
  270. */
  271. InputEvent event;
  272. event.type=InputEvent::MOUSE_MOTION;
  273. event.ID=++last_id;
  274. InputEventMouseMotion &mm=event.mouse_motion;
  275. mm.mod.control=(wParam&MK_CONTROL)!=0;
  276. mm.mod.shift=(wParam&MK_SHIFT)!=0;
  277. mm.mod.alt=alt_mem;
  278. mm.button_mask|=(wParam&MK_LBUTTON)?(1<<0):0;
  279. mm.button_mask|=(wParam&MK_RBUTTON)?(1<<1):0;
  280. mm.button_mask|=(wParam&MK_MBUTTON)?(1<<2):0;
  281. last_button_state=mm.button_mask;
  282. /*mm.button_mask|=(wParam&MK_XBUTTON1)?(1<<5):0;
  283. mm.button_mask|=(wParam&MK_XBUTTON2)?(1<<6):0;*/
  284. mm.x=GET_X_LPARAM(lParam);
  285. mm.y=GET_Y_LPARAM(lParam);
  286. if (mouse_mode==MOUSE_MODE_CAPTURED) {
  287. Point2i c(video_mode.width/2,video_mode.height/2);
  288. if (Point2i(mm.x,mm.y)==c) {
  289. center=c;
  290. return 0;
  291. }
  292. Point2i ncenter(mm.x,mm.y);
  293. mm.x = old_x + (mm.x-center.x);
  294. mm.y = old_y + (mm.y-center.y);
  295. center=ncenter;
  296. POINT pos = { (int) c.x, (int) c.y };
  297. ClientToScreen(hWnd, &pos);
  298. SetCursorPos(pos.x, pos.y);
  299. }
  300. input->set_mouse_pos(Point2(mm.x,mm.y));
  301. mm.speed_x=input->get_mouse_speed().x;
  302. mm.speed_y=input->get_mouse_speed().y;
  303. if (old_invalid) {
  304. old_x=mm.x;
  305. old_y=mm.y;
  306. old_invalid=false;
  307. }
  308. mm.relative_x=mm.x-old_x;
  309. mm.relative_y=mm.y-old_y;
  310. old_x=mm.x;
  311. old_y=mm.y;
  312. if (main_loop)
  313. input->parse_input_event(event);
  314. } break;
  315. case WM_LBUTTONDOWN:
  316. case WM_LBUTTONUP:
  317. case WM_MBUTTONDOWN:
  318. case WM_MBUTTONUP:
  319. case WM_RBUTTONDOWN:
  320. case WM_RBUTTONUP:
  321. case WM_MOUSEWHEEL:
  322. case WM_MOUSEHWHEEL:
  323. case WM_LBUTTONDBLCLK:
  324. case WM_RBUTTONDBLCLK:
  325. /*case WM_XBUTTONDOWN:
  326. case WM_XBUTTONUP: */{
  327. /*
  328. LPARAM extra = GetMessageExtraInfo();
  329. if (IsPenEvent(extra)) {
  330. int idx = extra & 0x7f;
  331. _touch_event(idx, uMsg, wParam, lParam);
  332. if (idx != 0) {
  333. return 0;
  334. };
  335. // fallthrough for mouse event
  336. };
  337. */
  338. InputEvent event;
  339. event.type=InputEvent::MOUSE_BUTTON;
  340. event.ID=++last_id;
  341. InputEventMouseButton &mb=event.mouse_button;
  342. switch (uMsg) {
  343. case WM_LBUTTONDOWN: {
  344. mb.pressed=true;
  345. mb.button_index=1;
  346. } break;
  347. case WM_LBUTTONUP: {
  348. mb.pressed=false;
  349. mb.button_index=1;
  350. } break;
  351. case WM_MBUTTONDOWN: {
  352. mb.pressed=true;
  353. mb.button_index=3;
  354. } break;
  355. case WM_MBUTTONUP: {
  356. mb.pressed=false;
  357. mb.button_index=3;
  358. } break;
  359. case WM_RBUTTONDOWN: {
  360. mb.pressed=true;
  361. mb.button_index=2;
  362. } break;
  363. case WM_RBUTTONUP: {
  364. mb.pressed=false;
  365. mb.button_index=2;
  366. } break;
  367. case WM_LBUTTONDBLCLK: {
  368. mb.pressed=true;
  369. mb.button_index=1;
  370. mb.doubleclick = true;
  371. } break;
  372. case WM_RBUTTONDBLCLK: {
  373. mb.pressed=true;
  374. mb.button_index=2;
  375. mb.doubleclick = true;
  376. } break;
  377. case WM_MOUSEWHEEL: {
  378. mb.pressed=true;
  379. int motion = (short)HIWORD(wParam);
  380. if (!motion)
  381. return 0;
  382. if (motion>0)
  383. mb.button_index= BUTTON_WHEEL_UP;
  384. else
  385. mb.button_index= BUTTON_WHEEL_DOWN;
  386. } break;
  387. case WM_MOUSEHWHEEL: {
  388. mb.pressed = true;
  389. int motion = (short)HIWORD(wParam);
  390. if (!motion)
  391. return 0;
  392. if (motion<0)
  393. mb.button_index = BUTTON_WHEEL_LEFT;
  394. else
  395. mb.button_index = BUTTON_WHEEL_RIGHT;
  396. } break;
  397. /*
  398. case WM_XBUTTONDOWN: {
  399. mb.pressed=true;
  400. mb.button_index=(HIWORD(wParam)==XBUTTON1)?6:7;
  401. } break;
  402. case WM_XBUTTONUP:
  403. mb.pressed=true;
  404. mb.button_index=(HIWORD(wParam)==XBUTTON1)?6:7;
  405. } break;*/
  406. default: { return 0; }
  407. }
  408. mb.mod.control=(wParam&MK_CONTROL)!=0;
  409. mb.mod.shift=(wParam&MK_SHIFT)!=0;
  410. mb.mod.alt=alt_mem;
  411. //mb.mod.alt=(wParam&MK_MENU)!=0;
  412. mb.button_mask|=(wParam&MK_LBUTTON)?(1<<0):0;
  413. mb.button_mask|=(wParam&MK_RBUTTON)?(1<<1):0;
  414. mb.button_mask|=(wParam&MK_MBUTTON)?(1<<2):0;
  415. last_button_state=mb.button_mask;
  416. /*
  417. mb.button_mask|=(wParam&MK_XBUTTON1)?(1<<5):0;
  418. mb.button_mask|=(wParam&MK_XBUTTON2)?(1<<6):0;*/
  419. mb.x=GET_X_LPARAM(lParam);
  420. mb.y=GET_Y_LPARAM(lParam);
  421. if (mouse_mode==MOUSE_MODE_CAPTURED) {
  422. mb.x=old_x;
  423. mb.y=old_y;
  424. }
  425. mb.global_x=mb.x;
  426. mb.global_y=mb.y;
  427. if (uMsg != WM_MOUSEWHEEL) {
  428. if (mb.pressed) {
  429. if (++pressrc>0)
  430. SetCapture(hWnd);
  431. } else {
  432. if (--pressrc<=0) {
  433. ReleaseCapture();
  434. pressrc=0;
  435. }
  436. }
  437. } else if (mouse_mode!=MOUSE_MODE_CAPTURED) {
  438. // for reasons unknown to mankind, wheel comes in screen cordinates
  439. POINT coords;
  440. coords.x = mb.x;
  441. coords.y = mb.y;
  442. ScreenToClient(hWnd, &coords);
  443. mb.x = coords.x;
  444. mb.y = coords.y;
  445. }
  446. if (main_loop) {
  447. input->parse_input_event(event);
  448. if (mb.pressed && mb.button_index>3) {
  449. //send release for mouse wheel
  450. mb.pressed=false;
  451. event.ID=++last_id;
  452. input->parse_input_event(event);
  453. }
  454. }
  455. } break;
  456. case WM_SIZE: {
  457. int window_w = LOWORD(lParam);
  458. int window_h = HIWORD(lParam);
  459. if (window_w > 0 && window_h > 0) {
  460. video_mode.width = window_w;
  461. video_mode.height = window_h;
  462. }
  463. //return 0; // Jump Back
  464. } break;
  465. case WM_ENTERSIZEMOVE: {
  466. move_timer_id = SetTimer(hWnd, 1, USER_TIMER_MINIMUM,(TIMERPROC) NULL);
  467. } break;
  468. case WM_EXITSIZEMOVE: {
  469. KillTimer(hWnd, move_timer_id);
  470. } break;
  471. case WM_TIMER: {
  472. if (wParam == move_timer_id) {
  473. process_key_events();
  474. Main::iteration();
  475. }
  476. } break;
  477. case WM_SYSKEYDOWN:
  478. case WM_SYSKEYUP:
  479. case WM_KEYUP:
  480. case WM_KEYDOWN: {
  481. if (wParam==VK_SHIFT)
  482. shift_mem=uMsg==WM_KEYDOWN;
  483. if (wParam==VK_CONTROL)
  484. control_mem=uMsg==WM_KEYDOWN;
  485. if (wParam==VK_MENU) {
  486. alt_mem=(uMsg==WM_KEYDOWN || uMsg==WM_SYSKEYDOWN);
  487. if (lParam&(1<<24))
  488. gr_mem=alt_mem;
  489. }
  490. //if (wParam==VK_WIN) TODO wtf is this?
  491. // meta_mem=uMsg==WM_KEYDOWN;
  492. } //fallthrough
  493. case WM_CHAR: {
  494. ERR_BREAK(key_event_pos >= KEY_EVENT_BUFFER_SIZE);
  495. // Make sure we don't include modifiers for the modifier key itself.
  496. KeyEvent ke;
  497. ke.mod_state.shift= (wParam != VK_SHIFT) ? shift_mem : false;
  498. ke.mod_state.alt= (! (wParam == VK_MENU && (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN))) ? alt_mem : false;
  499. ke.mod_state.control= (wParam != VK_CONTROL) ? control_mem : false;
  500. ke.mod_state.meta=meta_mem;
  501. ke.uMsg=uMsg;
  502. if (ke.uMsg==WM_SYSKEYDOWN)
  503. ke.uMsg=WM_KEYDOWN;
  504. if (ke.uMsg==WM_SYSKEYUP)
  505. ke.uMsg=WM_KEYUP;
  506. /*if (ke.uMsg==WM_KEYDOWN && alt_mem && uMsg!=WM_SYSKEYDOWN) {
  507. //altgr hack for intl keyboards, not sure how good it is
  508. //windows is weeeeird
  509. ke.mod_state.alt=false;
  510. ke.mod_state.control=false;
  511. print_line("")
  512. }*/
  513. ke.wParam=wParam;
  514. ke.lParam=lParam;
  515. key_event_buffer[key_event_pos++]=ke;
  516. } break;
  517. case WM_INPUTLANGCHANGEREQUEST: {
  518. print_line("input lang change");
  519. } break;
  520. #if WINVER >= 0x0700 // for windows 7
  521. case WM_TOUCH: {
  522. BOOL bHandled = FALSE;
  523. UINT cInputs = LOWORD(wParam);
  524. PTOUCHINPUT pInputs = memnew_arr(TOUCHINPUT, cInputs);
  525. if (pInputs){
  526. if (GetTouchInputInfo((HTOUCHINPUT)lParam, cInputs, pInputs, sizeof(TOUCHINPUT))){
  527. for (UINT i=0; i < cInputs; i++){
  528. TOUCHINPUT ti = pInputs[i];
  529. //do something with each touch input entry
  530. if (ti.dwFlags & TOUCHEVENTF_MOVE) {
  531. _drag_event(ti.x / 100, ti.y / 100, ti.dwID);
  532. } else if (ti.dwFlags & (TOUCHEVENTF_UP | TOUCHEVENTF_DOWN)) {
  533. _touch_event(ti.dwFlags & TOUCHEVENTF_DOWN != 0, ti.x / 100, ti.y / 100, ti.dwID);
  534. };
  535. }
  536. bHandled = TRUE;
  537. }else{
  538. /* handle the error here */
  539. }
  540. memdelete_arr(pInputs);
  541. }else{
  542. /* handle the error here, probably out of memory */
  543. }
  544. if (bHandled) {
  545. CloseTouchInputHandle((HTOUCHINPUT)lParam);
  546. return 0;
  547. };
  548. } break;
  549. #endif
  550. case WM_DEVICECHANGE: {
  551. joystick->probe_joysticks();
  552. } break;
  553. case WM_SETCURSOR: {
  554. if(LOWORD(lParam) == HTCLIENT) {
  555. if(mouse_mode == MOUSE_MODE_HIDDEN || mouse_mode == MOUSE_MODE_CAPTURED) {
  556. //Hide the cursor
  557. if(hCursor == NULL)
  558. hCursor = SetCursor(NULL);
  559. else
  560. SetCursor(NULL);
  561. }
  562. else {
  563. if(hCursor != NULL) {
  564. SetCursor(hCursor);
  565. hCursor = NULL;
  566. }
  567. }
  568. }
  569. } break;
  570. case WM_DROPFILES: {
  571. HDROP hDropInfo = NULL;
  572. hDropInfo = (HDROP) wParam;
  573. const int buffsize=4096;
  574. wchar_t buf[buffsize];
  575. int fcount = DragQueryFileW(hDropInfo, 0xFFFFFFFF,NULL,0);
  576. Vector<String> files;
  577. for(int i=0;i<fcount;i++) {
  578. DragQueryFileW(hDropInfo, i, buf, buffsize);
  579. String file=buf;
  580. files.push_back(file);
  581. }
  582. if (files.size() && main_loop) {
  583. main_loop->drop_files(files,0);
  584. }
  585. } break;
  586. default: {
  587. if (user_proc) {
  588. return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
  589. };
  590. };
  591. }
  592. return DefWindowProcW(hWnd,uMsg,wParam,lParam);
  593. }
  594. LRESULT CALLBACK WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
  595. OS_Windows *os_win = static_cast<OS_Windows*>(OS::get_singleton());
  596. if (os_win)
  597. return os_win->WndProc(hWnd,uMsg,wParam,lParam);
  598. else
  599. return DefWindowProcW(hWnd,uMsg,wParam,lParam);
  600. }
  601. void OS_Windows::process_key_events() {
  602. for(int i=0;i<key_event_pos;i++) {
  603. KeyEvent &ke = key_event_buffer[i];
  604. switch(ke.uMsg) {
  605. case WM_CHAR: {
  606. if ((i==0 && ke.uMsg==WM_CHAR) || (i>0 && key_event_buffer[i-1].uMsg==WM_CHAR))
  607. {
  608. InputEvent event;
  609. event.type=InputEvent::KEY;
  610. event.ID=++last_id;
  611. InputEventKey &k=event.key;
  612. k.mod=ke.mod_state;
  613. k.pressed=true;
  614. k.scancode=KeyMappingWindows::get_keysym(ke.wParam);
  615. k.unicode=ke.wParam;
  616. if (k.unicode && gr_mem) {
  617. k.mod.alt=false;
  618. k.mod.control=false;
  619. }
  620. if (k.unicode<32)
  621. k.unicode=0;
  622. input->parse_input_event(event);
  623. }
  624. //do nothing
  625. } break;
  626. case WM_KEYUP:
  627. case WM_KEYDOWN: {
  628. InputEvent event;
  629. event.type=InputEvent::KEY;
  630. event.ID=++last_id;
  631. InputEventKey &k=event.key;
  632. k.mod=ke.mod_state;
  633. k.pressed=(ke.uMsg==WM_KEYDOWN);
  634. k.scancode=KeyMappingWindows::get_keysym(ke.wParam);
  635. if (i+1 < key_event_pos && key_event_buffer[i+1].uMsg==WM_CHAR)
  636. k.unicode=key_event_buffer[i+1].wParam;
  637. if (k.unicode && gr_mem) {
  638. k.mod.alt=false;
  639. k.mod.control=false;
  640. }
  641. if (k.unicode<32)
  642. k.unicode=0;
  643. k.echo=(ke.uMsg==WM_KEYDOWN && (ke.lParam&(1<<30)));
  644. input->parse_input_event(event);
  645. } break;
  646. }
  647. }
  648. key_event_pos=0;
  649. }
  650. enum _MonitorDpiType
  651. {
  652. MDT_Effective_DPI = 0,
  653. MDT_Angular_DPI = 1,
  654. MDT_Raw_DPI = 2,
  655. MDT_Default = MDT_Effective_DPI
  656. };
  657. static int QueryDpiForMonitor(HMONITOR hmon, _MonitorDpiType dpiType= MDT_Default)
  658. {
  659. int dpiX = 96, dpiY = 96;
  660. static HMODULE Shcore = NULL;
  661. typedef HRESULT (WINAPI* GetDPIForMonitor_t)(HMONITOR hmonitor, _MonitorDpiType dpiType, UINT *dpiX, UINT *dpiY);
  662. static GetDPIForMonitor_t getDPIForMonitor = NULL;
  663. if (Shcore == NULL)
  664. {
  665. Shcore = LoadLibraryW(L"Shcore.dll");
  666. getDPIForMonitor = Shcore ? (GetDPIForMonitor_t)GetProcAddress(Shcore, "GetDpiForMonitor") : NULL;
  667. if ((Shcore == NULL) || (getDPIForMonitor == NULL))
  668. {
  669. if (Shcore)
  670. FreeLibrary(Shcore);
  671. Shcore = (HMODULE)INVALID_HANDLE_VALUE;
  672. }
  673. }
  674. UINT x = 0, y = 0;
  675. HRESULT hr = E_FAIL;
  676. bool bSet = false;
  677. if (hmon && (Shcore != (HMODULE)INVALID_HANDLE_VALUE))
  678. {
  679. hr = getDPIForMonitor(hmon, dpiType/*MDT_Effective_DPI*/, &x, &y);
  680. if (SUCCEEDED(hr) && (x > 0) && (y > 0))
  681. {
  682. dpiX = (int)x;
  683. dpiY = (int)y;
  684. }
  685. }
  686. else
  687. {
  688. static int overallX = 0, overallY = 0;
  689. if (overallX <= 0 || overallY <= 0)
  690. {
  691. HDC hdc = GetDC(NULL);
  692. if (hdc)
  693. {
  694. overallX = GetDeviceCaps(hdc, LOGPIXELSX);
  695. overallY = GetDeviceCaps(hdc, LOGPIXELSY);
  696. ReleaseDC(NULL, hdc);
  697. }
  698. }
  699. if (overallX > 0 && overallY > 0)
  700. {
  701. dpiX = overallX; dpiY = overallY;
  702. }
  703. }
  704. return (dpiX+dpiY)/2;
  705. }
  706. BOOL CALLBACK OS_Windows::MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  707. OS_Windows *self=(OS_Windows*)OS::get_singleton();
  708. MonitorInfo minfo;
  709. minfo.hMonitor=hMonitor;
  710. minfo.hdcMonitor=hdcMonitor;
  711. minfo.rect.pos.x=lprcMonitor->left;
  712. minfo.rect.pos.y=lprcMonitor->top;
  713. minfo.rect.size.x=lprcMonitor->right - lprcMonitor->left;
  714. minfo.rect.size.y=lprcMonitor->bottom - lprcMonitor->top;
  715. minfo.dpi = QueryDpiForMonitor(hMonitor);
  716. self->monitor_info.push_back(minfo);
  717. return TRUE;
  718. }
  719. void OS_Windows::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) {
  720. main_loop=NULL;
  721. outside=true;
  722. WNDCLASSEXW wc;
  723. video_mode=p_desired;
  724. //printf("**************** desired %s, mode %s\n", p_desired.fullscreen?"true":"false", video_mode.fullscreen?"true":"false");
  725. RECT WindowRect;
  726. WindowRect.left=0;
  727. WindowRect.right=video_mode.width;
  728. WindowRect.top=0;
  729. WindowRect.bottom=video_mode.height;
  730. memset(&wc,0,sizeof(WNDCLASSEXW));
  731. wc.cbSize=sizeof(WNDCLASSEXW);
  732. wc.style= CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_DBLCLKS;
  733. wc.lpfnWndProc = (WNDPROC)::WndProc;
  734. wc.cbClsExtra = 0;
  735. wc.cbWndExtra= 0;
  736. //wc.hInstance = hInstance;
  737. wc.hInstance = godot_hinstance ? godot_hinstance : GetModuleHandle(NULL);
  738. wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
  739. wc.hCursor = NULL;//LoadCursor(NULL, IDC_ARROW);
  740. wc.hbrBackground = NULL;
  741. wc.lpszMenuName = NULL;
  742. wc.lpszClassName = L"Engine";
  743. if (!RegisterClassExW(&wc)) {
  744. MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
  745. return; // Return
  746. }
  747. EnumDisplayMonitors(NULL,NULL,MonitorEnumProc,0);
  748. print_line("DETECTED MONITORS: "+itos(monitor_info.size()));
  749. pre_fs_valid=true;
  750. if (video_mode.fullscreen) {
  751. DEVMODE current;
  752. memset(&current,0,sizeof(current));
  753. EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &current);
  754. WindowRect.right = current.dmPelsWidth;
  755. WindowRect.bottom = current.dmPelsHeight;
  756. /* DEVMODE dmScreenSettings;
  757. memset(&dmScreenSettings,0,sizeof(dmScreenSettings));
  758. dmScreenSettings.dmSize=sizeof(dmScreenSettings);
  759. dmScreenSettings.dmPelsWidth = video_mode.width;
  760. dmScreenSettings.dmPelsHeight = video_mode.height;
  761. dmScreenSettings.dmBitsPerPel = current.dmBitsPerPel;
  762. dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
  763. LONG err = ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN);
  764. if (err!=DISP_CHANGE_SUCCESSFUL) {
  765. video_mode.fullscreen=false;
  766. }*/
  767. pre_fs_valid=false;
  768. }
  769. DWORD dwExStyle;
  770. DWORD dwStyle;
  771. if (video_mode.fullscreen||video_mode.borderless_window) {
  772. dwExStyle=WS_EX_APPWINDOW;
  773. dwStyle=WS_POPUP;
  774. } else {
  775. dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
  776. dwStyle=WS_OVERLAPPEDWINDOW;
  777. if (!video_mode.resizable) {
  778. dwStyle &= ~WS_THICKFRAME;
  779. dwStyle &= ~WS_MAXIMIZEBOX;
  780. }
  781. }
  782. AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);
  783. char* windowid = getenv("GODOT_WINDOWID");
  784. if (windowid) {
  785. // strtoull on mingw
  786. #ifdef MINGW_ENABLED
  787. hWnd = (HWND)strtoull(windowid, NULL, 0);
  788. #else
  789. hWnd = (HWND)_strtoui64(windowid, NULL, 0);
  790. #endif
  791. SetLastError(0);
  792. user_proc = (WNDPROC)GetWindowLongPtr(hWnd, GWLP_WNDPROC);
  793. SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)(WNDPROC)::WndProc);
  794. DWORD le = GetLastError();
  795. if (user_proc == 0 && le != 0) {
  796. printf("Error setting WNDPROC: %li\n", le);
  797. };
  798. LONG_PTR proc = GetWindowLongPtr(hWnd, GWLP_WNDPROC);
  799. RECT rect;
  800. if (!GetClientRect(hWnd, &rect)) {
  801. MessageBoxW(NULL,L"Window Creation Error.",L"ERROR",MB_OK|MB_ICONEXCLAMATION);
  802. return; // Return FALSE
  803. };
  804. video_mode.width = rect.right;
  805. video_mode.height = rect.bottom;
  806. video_mode.fullscreen = false;
  807. } else {
  808. if (!(hWnd=CreateWindowExW(dwExStyle,L"Engine",L"", dwStyle|WS_CLIPSIBLINGS|WS_CLIPCHILDREN, (GetSystemMetrics(SM_CXSCREEN)-WindowRect.right)/2, (GetSystemMetrics(SM_CYSCREEN)-WindowRect.bottom)/2, WindowRect.right-WindowRect.left,WindowRect.bottom-WindowRect.top, NULL,NULL, hInstance,NULL))) {
  809. MessageBoxW(NULL,L"Window Creation Error.",L"ERROR",MB_OK|MB_ICONEXCLAMATION);
  810. return; // Return FALSE
  811. }
  812. };
  813. #if defined(OPENGL_ENABLED)
  814. gl_context = memnew( ContextGL_Win(hWnd,true) );
  815. gl_context->initialize();
  816. RasterizerGLES3::register_config();
  817. RasterizerGLES3::make_current();
  818. #else
  819. // FIXME: Does DX support still work now that rasterizer is no longer used?
  820. #ifdef DX9_ENABLED
  821. rasterizer = memnew( RasterizerDX9(hWnd) );
  822. #endif
  823. #endif
  824. visual_server = memnew( VisualServerRaster );
  825. // FIXME: Reimplement threaded rendering? Or remove?
  826. // if (get_render_thread_mode()!=RENDER_THREAD_UNSAFE) {
  827. //
  828. // visual_server =memnew(VisualServerWrapMT(visual_server,get_render_thread_mode()==RENDER_SEPARATE_THREAD));
  829. // }
  830. //
  831. physics_server = memnew( PhysicsServerSW );
  832. physics_server->init();
  833. physics_2d_server = Physics2DServerWrapMT::init_server<Physics2DServerSW>();
  834. physics_2d_server->init();
  835. if (!is_no_window_mode_enabled()) {
  836. ShowWindow(hWnd,SW_SHOW); // Show The Window
  837. SetForegroundWindow(hWnd); // Slightly Higher Priority
  838. SetFocus(hWnd); // Sets Keyboard Focus To
  839. }
  840. /*
  841. DEVMODE dmScreenSettings; // Device Mode
  842. memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
  843. dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure
  844. dmScreenSettings.dmPelsWidth = width; // Selected Screen Width
  845. dmScreenSettings.dmPelsHeight = height; // Selected Screen Height
  846. dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel
  847. dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
  848. if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
  849. */
  850. visual_server->init();
  851. input = memnew( InputDefault );
  852. joystick = memnew (joystick_windows(input, &hWnd));
  853. AudioDriverManagerSW::get_driver(p_audio_driver)->set_singleton();
  854. if (AudioDriverManagerSW::get_driver(p_audio_driver)->init()!=OK) {
  855. ERR_PRINT("Initializing audio failed.");
  856. }
  857. sample_manager = memnew( SampleManagerMallocSW );
  858. audio_server = memnew( AudioServerSW(sample_manager) );
  859. audio_server->init();
  860. spatial_sound_server = memnew( SpatialSoundServerSW );
  861. spatial_sound_server->init();
  862. spatial_sound_2d_server = memnew( SpatialSound2DServerSW );
  863. spatial_sound_2d_server->init();
  864. TRACKMOUSEEVENT tme;
  865. tme.cbSize=sizeof(TRACKMOUSEEVENT);
  866. tme.dwFlags=TME_LEAVE;
  867. tme.hwndTrack=hWnd;
  868. tme.dwHoverTime=HOVER_DEFAULT;
  869. TrackMouseEvent(&tme);
  870. //RegisterTouchWindow(hWnd, 0); // Windows 7
  871. _ensure_data_dir();
  872. DragAcceptFiles(hWnd,true);
  873. move_timer_id = 1;
  874. }
  875. void OS_Windows::set_clipboard(const String& p_text) {
  876. if (!OpenClipboard(hWnd)) {
  877. ERR_EXPLAIN("Unable to open clipboard.");
  878. ERR_FAIL();
  879. };
  880. EmptyClipboard();
  881. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, (p_text.length() + 1) * sizeof(CharType));
  882. if (mem == NULL) {
  883. ERR_EXPLAIN("Unable to allocate memory for clipboard contents.");
  884. ERR_FAIL();
  885. };
  886. LPWSTR lptstrCopy = (LPWSTR)GlobalLock(mem);
  887. memcpy(lptstrCopy, p_text.c_str(), (p_text.length() + 1) * sizeof(CharType));
  888. //memset((lptstrCopy + p_text.length()), 0, sizeof(CharType));
  889. GlobalUnlock(mem);
  890. SetClipboardData(CF_UNICODETEXT, mem);
  891. // set the CF_TEXT version (not needed?)
  892. CharString utf8 = p_text.utf8();
  893. mem = GlobalAlloc(GMEM_MOVEABLE, utf8.length() + 1);
  894. if (mem == NULL) {
  895. ERR_EXPLAIN("Unable to allocate memory for clipboard contents.");
  896. ERR_FAIL();
  897. };
  898. LPTSTR ptr = (LPTSTR)GlobalLock(mem);
  899. memcpy(ptr, utf8.get_data(), utf8.length());
  900. ptr[utf8.length()] = 0;
  901. GlobalUnlock(mem);
  902. SetClipboardData(CF_TEXT, mem);
  903. CloseClipboard();
  904. };
  905. String OS_Windows::get_clipboard() const {
  906. String ret;
  907. if (!OpenClipboard(hWnd)) {
  908. ERR_EXPLAIN("Unable to open clipboard.");
  909. ERR_FAIL_V("");
  910. };
  911. if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
  912. HGLOBAL mem = GetClipboardData(CF_UNICODETEXT);
  913. if (mem != NULL) {
  914. LPWSTR ptr = (LPWSTR)GlobalLock(mem);
  915. if (ptr != NULL) {
  916. ret = String((CharType*)ptr);
  917. GlobalUnlock(mem);
  918. };
  919. };
  920. } else if (IsClipboardFormatAvailable(CF_TEXT)) {
  921. HGLOBAL mem = GetClipboardData(CF_UNICODETEXT);
  922. if (mem != NULL) {
  923. LPTSTR ptr = (LPTSTR)GlobalLock(mem);
  924. if (ptr != NULL) {
  925. ret.parse_utf8((const char*)ptr);
  926. GlobalUnlock(mem);
  927. };
  928. };
  929. };
  930. CloseClipboard();
  931. return ret;
  932. };
  933. void OS_Windows::delete_main_loop() {
  934. if (main_loop)
  935. memdelete(main_loop);
  936. main_loop=NULL;
  937. }
  938. void OS_Windows::set_main_loop( MainLoop * p_main_loop ) {
  939. input->set_main_loop(p_main_loop);
  940. main_loop=p_main_loop;
  941. }
  942. void OS_Windows::finalize() {
  943. if(main_loop)
  944. memdelete(main_loop);
  945. main_loop=NULL;
  946. memdelete(joystick);
  947. memdelete(input);
  948. visual_server->finish();
  949. memdelete(visual_server);
  950. #ifdef OPENGL_ENABLED
  951. if (gl_context)
  952. memdelete(gl_context);
  953. #endif
  954. if (rasterizer)
  955. memdelete(rasterizer);
  956. if (user_proc) {
  957. SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)user_proc);
  958. };
  959. spatial_sound_server->finish();
  960. memdelete(spatial_sound_server);
  961. spatial_sound_2d_server->finish();
  962. memdelete(spatial_sound_2d_server);
  963. //if (debugger_connection_console) {
  964. // memdelete(debugger_connection_console);
  965. //}
  966. memdelete(sample_manager);
  967. audio_server->finish();
  968. memdelete(audio_server);
  969. physics_server->finish();
  970. memdelete(physics_server);
  971. physics_2d_server->finish();
  972. memdelete(physics_2d_server);
  973. monitor_info.clear();
  974. }
  975. void OS_Windows::finalize_core() {
  976. memdelete(process_map);
  977. if (mempool_dynamic)
  978. memdelete( mempool_dynamic );
  979. TCPServerWinsock::cleanup();
  980. StreamPeerWinsock::cleanup();
  981. }
  982. void OS_Windows::vprint(const char* p_format, va_list p_list, bool p_stderr) {
  983. const unsigned int BUFFER_SIZE = 16384;
  984. char buf[BUFFER_SIZE+1]; // +1 for the terminating character
  985. int len = vsnprintf(buf,BUFFER_SIZE,p_format,p_list);
  986. if (len<=0)
  987. return;
  988. if(len >= BUFFER_SIZE)
  989. len = BUFFER_SIZE; // Output is too big, will be truncated
  990. buf[len]=0;
  991. int wlen = MultiByteToWideChar(CP_UTF8,0,buf,len,NULL,0);
  992. if (wlen<0)
  993. return;
  994. wchar_t *wbuf = (wchar_t*)malloc((len+1)*sizeof(wchar_t));
  995. MultiByteToWideChar(CP_UTF8,0,buf,len,wbuf,wlen);
  996. wbuf[wlen]=0;
  997. // Recent MinGW and MSVC compilers seem to disagree on the case here
  998. #ifdef __MINGW32__
  999. if (p_stderr)
  1000. fwprintf(stderr, L"%S", wbuf);
  1001. else
  1002. wprintf(L"%S", wbuf);
  1003. #else // MSVC
  1004. if (p_stderr)
  1005. fwprintf(stderr, L"%s", wbuf);
  1006. else
  1007. wprintf(L"%s", wbuf);
  1008. #endif
  1009. #ifdef STDOUT_FILE
  1010. //vwfprintf(stdo,p_format,p_list);
  1011. #endif
  1012. free(wbuf);
  1013. fflush(stdout);
  1014. };
  1015. void OS_Windows::alert(const String& p_alert,const String& p_title) {
  1016. if (!is_no_window_mode_enabled())
  1017. MessageBoxW(NULL, p_alert.c_str(), p_title.c_str(), MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
  1018. else
  1019. print_line("ALERT: "+p_alert);
  1020. }
  1021. void OS_Windows::set_mouse_mode(MouseMode p_mode) {
  1022. if (mouse_mode==p_mode)
  1023. return;
  1024. mouse_mode=p_mode;
  1025. if (p_mode==MOUSE_MODE_CAPTURED) {
  1026. RECT clipRect;
  1027. GetClientRect(hWnd, &clipRect);
  1028. ClientToScreen(hWnd, (POINT*) &clipRect.left);
  1029. ClientToScreen(hWnd, (POINT*) &clipRect.right);
  1030. ClipCursor(&clipRect);
  1031. SetCapture(hWnd);
  1032. center=Point2i(video_mode.width/2,video_mode.height/2);
  1033. POINT pos = { (int) center.x, (int) center.y };
  1034. ClientToScreen(hWnd, &pos);
  1035. SetCursorPos(pos.x, pos.y);
  1036. } else {
  1037. ReleaseCapture();
  1038. ClipCursor(NULL);
  1039. }
  1040. if (p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_HIDDEN) {
  1041. hCursor = SetCursor(NULL);
  1042. } else {
  1043. SetCursor(hCursor);
  1044. }
  1045. }
  1046. OS_Windows::MouseMode OS_Windows::get_mouse_mode() const{
  1047. return mouse_mode;
  1048. }
  1049. void OS_Windows::warp_mouse_pos(const Point2& p_to) {
  1050. if (mouse_mode==MOUSE_MODE_CAPTURED) {
  1051. old_x=p_to.x;
  1052. old_y=p_to.y;
  1053. } else {
  1054. POINT p;
  1055. p.x=p_to.x;
  1056. p.y=p_to.y;
  1057. ClientToScreen(hWnd,&p);
  1058. SetCursorPos(p.x,p.y);
  1059. }
  1060. }
  1061. Point2 OS_Windows::get_mouse_pos() const {
  1062. return Point2(old_x, old_y);
  1063. }
  1064. int OS_Windows::get_mouse_button_state() const {
  1065. return last_button_state;
  1066. }
  1067. void OS_Windows::set_window_title(const String& p_title) {
  1068. SetWindowTextW(hWnd,p_title.c_str());
  1069. }
  1070. void OS_Windows::set_video_mode(const VideoMode& p_video_mode,int p_screen) {
  1071. }
  1072. OS::VideoMode OS_Windows::get_video_mode(int p_screen) const {
  1073. return video_mode;
  1074. }
  1075. void OS_Windows::get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen) const {
  1076. }
  1077. int OS_Windows::get_screen_count() const {
  1078. return monitor_info.size();
  1079. }
  1080. int OS_Windows::get_current_screen() const{
  1081. HMONITOR monitor = MonitorFromWindow(hWnd,MONITOR_DEFAULTTONEAREST);
  1082. for(int i=0;i<monitor_info.size();i++) {
  1083. if (monitor_info[i].hMonitor==monitor)
  1084. return i;
  1085. }
  1086. return 0;
  1087. }
  1088. void OS_Windows::set_current_screen(int p_screen){
  1089. ERR_FAIL_INDEX(p_screen,monitor_info.size());
  1090. Vector2 ofs = get_window_position() - get_screen_position(get_current_screen());
  1091. set_window_position(ofs+get_screen_position(p_screen));
  1092. }
  1093. Point2 OS_Windows::get_screen_position(int p_screen) const{
  1094. ERR_FAIL_INDEX_V(p_screen,monitor_info.size(),Point2());
  1095. return Vector2( monitor_info[p_screen].rect.pos );
  1096. }
  1097. Size2 OS_Windows::get_screen_size(int p_screen) const{
  1098. ERR_FAIL_INDEX_V(p_screen,monitor_info.size(),Point2());
  1099. return Vector2( monitor_info[p_screen].rect.size );
  1100. }
  1101. int OS_Windows::get_screen_dpi(int p_screen) const {
  1102. ERR_FAIL_INDEX_V(p_screen,monitor_info.size(),72);
  1103. UINT dpix,dpiy;
  1104. return monitor_info[p_screen].dpi;
  1105. }
  1106. Point2 OS_Windows::get_window_position() const{
  1107. RECT r;
  1108. GetWindowRect(hWnd,&r);
  1109. return Point2(r.left,r.top);
  1110. }
  1111. void OS_Windows::set_window_position(const Point2& p_position){
  1112. if (video_mode.fullscreen) return;
  1113. RECT r;
  1114. GetWindowRect(hWnd,&r);
  1115. MoveWindow(hWnd,p_position.x,p_position.y,r.right-r.left,r.bottom-r.top,TRUE);
  1116. }
  1117. Size2 OS_Windows::get_window_size() const{
  1118. RECT r;
  1119. GetClientRect(hWnd,&r);
  1120. return Vector2(r.right-r.left,r.bottom-r.top);
  1121. }
  1122. void OS_Windows::set_window_size(const Size2 p_size){
  1123. video_mode.width=p_size.width;
  1124. video_mode.height=p_size.height;
  1125. if (video_mode.fullscreen) {
  1126. return;
  1127. }
  1128. RECT crect;
  1129. GetClientRect(hWnd,&crect);
  1130. RECT rect;
  1131. GetWindowRect(hWnd,&rect);
  1132. int dx = (rect.right-rect.left)-(crect.right-crect.left);
  1133. int dy = (rect.bottom-rect.top)-(crect.bottom-crect.top);
  1134. rect.right=rect.left+p_size.width+dx;
  1135. rect.bottom=rect.top+p_size.height+dy;
  1136. //print_line("PRE: "+itos(rect.left)+","+itos(rect.top)+","+itos(rect.right-rect.left)+","+itos(rect.bottom-rect.top));
  1137. /*if (video_mode.resizable) {
  1138. AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE);
  1139. } else {
  1140. AdjustWindowRect(&rect, WS_CAPTION | WS_POPUPWINDOW, FALSE);
  1141. }*/
  1142. //print_line("POST: "+itos(rect.left)+","+itos(rect.top)+","+itos(rect.right-rect.left)+","+itos(rect.bottom-rect.top));
  1143. MoveWindow(hWnd,rect.left,rect.top,rect.right-rect.left,rect.bottom-rect.top,TRUE);
  1144. }
  1145. void OS_Windows::set_window_fullscreen(bool p_enabled){
  1146. if (video_mode.fullscreen==p_enabled)
  1147. return;
  1148. if (p_enabled) {
  1149. if (pre_fs_valid) {
  1150. GetWindowRect(hWnd,&pre_fs_rect);
  1151. //print_line("A: "+itos(pre_fs_rect.left)+","+itos(pre_fs_rect.top)+","+itos(pre_fs_rect.right-pre_fs_rect.left)+","+itos(pre_fs_rect.bottom-pre_fs_rect.top));
  1152. //MapWindowPoints(hWnd, GetParent(hWnd), (LPPOINT) &pre_fs_rect, 2);
  1153. //print_line("B: "+itos(pre_fs_rect.left)+","+itos(pre_fs_rect.top)+","+itos(pre_fs_rect.right-pre_fs_rect.left)+","+itos(pre_fs_rect.bottom-pre_fs_rect.top));
  1154. }
  1155. int cs = get_current_screen();
  1156. Point2 pos = get_screen_position(cs);
  1157. Size2 size = get_screen_size(cs);
  1158. /* r.left = pos.x;
  1159. r.top = pos.y;
  1160. r.bottom = pos.y+size.y;
  1161. r.right = pos.x+size.x;
  1162. */
  1163. SetWindowLongPtr(hWnd, GWL_STYLE,
  1164. WS_SYSMENU | WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE);
  1165. MoveWindow(hWnd, pos.x, pos.y, size.width, size.height, TRUE);
  1166. video_mode.fullscreen=true;
  1167. } else {
  1168. RECT rect;
  1169. if (pre_fs_valid) {
  1170. rect=pre_fs_rect;
  1171. } else {
  1172. rect.left=0;
  1173. rect.right=video_mode.width;
  1174. rect.top=0;
  1175. rect.bottom=video_mode.height;
  1176. }
  1177. if (video_mode.resizable) {
  1178. SetWindowLongPtr(hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE);
  1179. //AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE);
  1180. MoveWindow(hWnd, rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top, TRUE);
  1181. } else {
  1182. SetWindowLongPtr(hWnd, GWL_STYLE, WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE);
  1183. //AdjustWindowRect(&rect, WS_CAPTION | WS_POPUPWINDOW, FALSE);
  1184. MoveWindow(hWnd, rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top, TRUE);
  1185. }
  1186. video_mode.fullscreen=false;
  1187. pre_fs_valid=true;
  1188. /*
  1189. DWORD dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
  1190. DWORD dwStyle=WS_OVERLAPPEDWINDOW;
  1191. if (!video_mode.resizable) {
  1192. dwStyle &= ~WS_THICKFRAME;
  1193. dwStyle &= ~WS_MAXIMIZEBOX;
  1194. }
  1195. AdjustWindowRectEx(&pre_fs_rect, dwStyle, FALSE, dwExStyle);
  1196. video_mode.fullscreen=false;
  1197. video_mode.width=pre_fs_rect.right-pre_fs_rect.left;
  1198. video_mode.height=pre_fs_rect.bottom-pre_fs_rect.top;
  1199. */
  1200. }
  1201. // MoveWindow(hWnd,r.left,r.top,p_size.x,p_size.y,TRUE);
  1202. }
  1203. bool OS_Windows::is_window_fullscreen() const{
  1204. return video_mode.fullscreen;
  1205. }
  1206. void OS_Windows::set_window_resizable(bool p_enabled){
  1207. if (video_mode.resizable==p_enabled)
  1208. return;
  1209. /*
  1210. GetWindowRect(hWnd,&pre_fs_rect);
  1211. DWORD dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
  1212. DWORD dwStyle=WS_OVERLAPPEDWINDOW;
  1213. if (!p_enabled) {
  1214. dwStyle &= ~WS_THICKFRAME;
  1215. dwStyle &= ~WS_MAXIMIZEBOX;
  1216. }
  1217. AdjustWindowRectEx(&pre_fs_rect, dwStyle, FALSE, dwExStyle);
  1218. */
  1219. if (!video_mode.fullscreen) {
  1220. if (p_enabled) {
  1221. SetWindowLongPtr(hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE);
  1222. } else {
  1223. SetWindowLongPtr(hWnd, GWL_STYLE, WS_CAPTION | WS_MINIMIZEBOX | WS_POPUPWINDOW | WS_VISIBLE);
  1224. }
  1225. RECT rect;
  1226. GetWindowRect(hWnd,&rect);
  1227. MoveWindow(hWnd, rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top, TRUE);
  1228. }
  1229. video_mode.resizable=p_enabled;
  1230. }
  1231. bool OS_Windows::is_window_resizable() const{
  1232. return video_mode.resizable;
  1233. }
  1234. void OS_Windows::set_window_minimized(bool p_enabled){
  1235. if (p_enabled) {
  1236. maximized=false;
  1237. minimized=true;
  1238. ShowWindow(hWnd,SW_MINIMIZE);
  1239. } else {
  1240. ShowWindow(hWnd,SW_RESTORE);
  1241. maximized=false;
  1242. minimized=false;
  1243. }
  1244. }
  1245. bool OS_Windows::is_window_minimized() const{
  1246. return minimized;
  1247. }
  1248. void OS_Windows::set_window_maximized(bool p_enabled){
  1249. if (p_enabled) {
  1250. maximized=true;
  1251. minimized=false;
  1252. ShowWindow(hWnd,SW_MAXIMIZE);
  1253. } else {
  1254. ShowWindow(hWnd,SW_RESTORE);
  1255. maximized=false;
  1256. minimized=false;
  1257. }
  1258. }
  1259. bool OS_Windows::is_window_maximized() const{
  1260. return maximized;
  1261. }
  1262. void OS_Windows::set_borderless_window(int p_borderless) {
  1263. video_mode.borderless_window = p_borderless;
  1264. }
  1265. bool OS_Windows::get_borderless_window() {
  1266. return video_mode.borderless_window;
  1267. }
  1268. void OS_Windows::request_attention() {
  1269. FLASHWINFO info;
  1270. info.cbSize = sizeof(FLASHWINFO);
  1271. info.hwnd = hWnd;
  1272. info.dwFlags = FLASHW_TRAY;
  1273. info.dwTimeout = 0;
  1274. info.uCount = 2;
  1275. FlashWindowEx(&info);
  1276. }
  1277. void OS_Windows::print_error(const char* p_function, const char* p_file, int p_line, const char* p_code, const char* p_rationale, ErrorType p_type) {
  1278. HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE);
  1279. if (!hCon || hCon == INVALID_HANDLE_VALUE) {
  1280. const char* err_details;
  1281. if (p_rationale && p_rationale[0])
  1282. err_details = p_rationale;
  1283. else
  1284. err_details = p_code;
  1285. switch(p_type) {
  1286. case ERR_ERROR:
  1287. print("ERROR: %s: %s\n", p_function, err_details);
  1288. print(" At: %s:%i\n", p_file, p_line);
  1289. break;
  1290. case ERR_WARNING:
  1291. print("WARNING: %s: %s\n", p_function, err_details);
  1292. print(" At: %s:%i\n", p_file, p_line);
  1293. break;
  1294. case ERR_SCRIPT:
  1295. print("SCRIPT ERROR: %s: %s\n", p_function, err_details);
  1296. print(" At: %s:%i\n", p_file, p_line);
  1297. break;
  1298. case ERR_SHADER:
  1299. print("SHADER ERROR: %s: %s\n", p_function, err_details);
  1300. print(" At: %s:%i\n", p_file, p_line);
  1301. break;
  1302. }
  1303. } else {
  1304. CONSOLE_SCREEN_BUFFER_INFO sbi; //original
  1305. GetConsoleScreenBufferInfo(hCon, &sbi);
  1306. WORD current_fg = sbi.wAttributes & (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
  1307. WORD current_bg = sbi.wAttributes & (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY);
  1308. uint32_t basecol = 0;
  1309. switch(p_type) {
  1310. case ERR_ERROR: basecol = FOREGROUND_RED; break;
  1311. case ERR_WARNING: basecol = FOREGROUND_RED | FOREGROUND_GREEN; break;
  1312. case ERR_SCRIPT: basecol = FOREGROUND_RED | FOREGROUND_BLUE; break;
  1313. case ERR_SHADER: basecol = FOREGROUND_GREEN | FOREGROUND_BLUE; break;
  1314. }
  1315. basecol |= current_bg;
  1316. if (p_rationale && p_rationale[0]) {
  1317. SetConsoleTextAttribute(hCon, basecol | FOREGROUND_INTENSITY);
  1318. switch(p_type) {
  1319. case ERR_ERROR: print("ERROR: "); break;
  1320. case ERR_WARNING: print("WARNING: "); break;
  1321. case ERR_SCRIPT: print("SCRIPT ERROR: "); break;
  1322. case ERR_SHADER: print("SHADER ERROR: "); break;
  1323. }
  1324. SetConsoleTextAttribute(hCon, current_fg | current_bg | FOREGROUND_INTENSITY);
  1325. print("%s\n", p_rationale);
  1326. SetConsoleTextAttribute(hCon, basecol);
  1327. switch (p_type) {
  1328. case ERR_ERROR: print(" At: "); break;
  1329. case ERR_WARNING: print(" At: "); break;
  1330. case ERR_SCRIPT: print(" At: "); break;
  1331. case ERR_SHADER: print(" At: "); break;
  1332. }
  1333. SetConsoleTextAttribute(hCon, current_fg | current_bg);
  1334. print("%s:%i\n", p_file, p_line);
  1335. } else {
  1336. SetConsoleTextAttribute(hCon, basecol | FOREGROUND_INTENSITY);
  1337. switch(p_type) {
  1338. case ERR_ERROR: print("ERROR: %s: ", p_function); break;
  1339. case ERR_WARNING: print("WARNING: %s: ", p_function); break;
  1340. case ERR_SCRIPT: print("SCRIPT ERROR: %s: ", p_function); break;
  1341. case ERR_SHADER: print("SCRIPT ERROR: %s: ", p_function); break;
  1342. }
  1343. SetConsoleTextAttribute(hCon, current_fg | current_bg | FOREGROUND_INTENSITY);
  1344. print("%s\n", p_code);
  1345. SetConsoleTextAttribute(hCon, basecol);
  1346. switch (p_type) {
  1347. case ERR_ERROR: print(" At: "); break;
  1348. case ERR_WARNING: print(" At: "); break;
  1349. case ERR_SCRIPT: print(" At: "); break;
  1350. case ERR_SHADER: print(" At: "); break;
  1351. }
  1352. SetConsoleTextAttribute(hCon, current_fg | current_bg);
  1353. print("%s:%i\n", p_file, p_line);
  1354. }
  1355. SetConsoleTextAttribute(hCon, sbi.wAttributes);
  1356. }
  1357. }
  1358. String OS_Windows::get_name() {
  1359. return "Windows";
  1360. }
  1361. OS::Date OS_Windows::get_date(bool utc) const {
  1362. SYSTEMTIME systemtime;
  1363. if (utc)
  1364. GetSystemTime(&systemtime);
  1365. else
  1366. GetLocalTime(&systemtime);
  1367. Date date;
  1368. date.day=systemtime.wDay;
  1369. date.month=Month(systemtime.wMonth);
  1370. date.weekday=Weekday(systemtime.wDayOfWeek);
  1371. date.year=systemtime.wYear;
  1372. date.dst=false;
  1373. return date;
  1374. }
  1375. OS::Time OS_Windows::get_time(bool utc) const {
  1376. SYSTEMTIME systemtime;
  1377. if (utc)
  1378. GetSystemTime(&systemtime);
  1379. else
  1380. GetLocalTime(&systemtime);
  1381. Time time;
  1382. time.hour=systemtime.wHour;
  1383. time.min=systemtime.wMinute;
  1384. time.sec=systemtime.wSecond;
  1385. return time;
  1386. }
  1387. OS::TimeZoneInfo OS_Windows::get_time_zone_info() const {
  1388. TIME_ZONE_INFORMATION info;
  1389. bool daylight = false;
  1390. if (GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT)
  1391. daylight = true;
  1392. TimeZoneInfo ret;
  1393. if (daylight) {
  1394. ret.name = info.DaylightName;
  1395. } else {
  1396. ret.name = info.StandardName;
  1397. }
  1398. ret.bias = info.Bias;
  1399. return ret;
  1400. }
  1401. uint64_t OS_Windows::get_unix_time() const {
  1402. FILETIME ft;
  1403. SYSTEMTIME st;
  1404. GetSystemTime(&st);
  1405. SystemTimeToFileTime(&st, &ft);
  1406. SYSTEMTIME ep;
  1407. ep.wYear = 1970;
  1408. ep.wMonth = 1;
  1409. ep.wDayOfWeek = 4;
  1410. ep.wDay = 1;
  1411. ep.wHour = 0;
  1412. ep.wMinute = 0;
  1413. ep.wSecond = 0;
  1414. ep.wMilliseconds = 0;
  1415. FILETIME fep;
  1416. SystemTimeToFileTime(&ep, &fep);
  1417. return (*(uint64_t*)&ft - *(uint64_t*)&fep) / 10000000;
  1418. };
  1419. uint64_t OS_Windows::get_system_time_secs() const {
  1420. const uint64_t WINDOWS_TICK = 10000000;
  1421. const uint64_t SEC_TO_UNIX_EPOCH = 11644473600LL;
  1422. SYSTEMTIME st;
  1423. GetSystemTime(&st);
  1424. FILETIME ft;
  1425. SystemTimeToFileTime(&st,&ft);
  1426. uint64_t ret;
  1427. ret=ft.dwHighDateTime;
  1428. ret<<=32;
  1429. ret|=ft.dwLowDateTime;
  1430. return (uint64_t)(ret / WINDOWS_TICK - SEC_TO_UNIX_EPOCH);
  1431. }
  1432. void OS_Windows::delay_usec(uint32_t p_usec) const {
  1433. if (p_usec < 1000)
  1434. Sleep(1);
  1435. else
  1436. Sleep(p_usec / 1000);
  1437. }
  1438. uint64_t OS_Windows::get_ticks_usec() const {
  1439. uint64_t ticks;
  1440. uint64_t time;
  1441. // This is the number of clock ticks since start
  1442. if( !QueryPerformanceCounter((LARGE_INTEGER *)&ticks) )
  1443. ticks = (UINT64)timeGetTime();
  1444. // Divide by frequency to get the time in seconds
  1445. time = ticks * 1000000L / ticks_per_second;
  1446. // Subtract the time at game start to get
  1447. // the time since the game started
  1448. time -= ticks_start;
  1449. return time;
  1450. }
  1451. void OS_Windows::process_events() {
  1452. MSG msg;
  1453. last_id = joystick->process_joysticks(last_id);
  1454. while(PeekMessageW(&msg,NULL,0,0,PM_REMOVE)) {
  1455. TranslateMessage(&msg);
  1456. DispatchMessageW(&msg);
  1457. }
  1458. process_key_events();
  1459. }
  1460. void OS_Windows::set_cursor_shape(CursorShape p_shape) {
  1461. ERR_FAIL_INDEX(p_shape,CURSOR_MAX);
  1462. if (cursor_shape==p_shape)
  1463. return;
  1464. static const LPCTSTR win_cursors[CURSOR_MAX]={
  1465. IDC_ARROW,
  1466. IDC_IBEAM,
  1467. IDC_HAND,//finger
  1468. IDC_CROSS,
  1469. IDC_WAIT,
  1470. IDC_APPSTARTING,
  1471. IDC_ARROW,
  1472. IDC_ARROW,
  1473. IDC_NO,
  1474. IDC_SIZENS,
  1475. IDC_SIZEWE,
  1476. IDC_SIZENESW,
  1477. IDC_SIZENWSE,
  1478. IDC_SIZEALL,
  1479. IDC_SIZENS,
  1480. IDC_SIZEWE,
  1481. IDC_HELP
  1482. };
  1483. SetCursor(LoadCursor(hInstance,win_cursors[p_shape]));
  1484. cursor_shape=p_shape;
  1485. }
  1486. Error OS_Windows::execute(const String& p_path, const List<String>& p_arguments,bool p_blocking,ProcessID *r_child_id,String* r_pipe,int *r_exitcode) {
  1487. if (p_blocking && r_pipe) {
  1488. String argss;
  1489. argss="\"\""+p_path+"\"";
  1490. for(int i=0;i<p_arguments.size();i++) {
  1491. argss+=String(" \"")+p_arguments[i]+"\"";
  1492. }
  1493. // print_line("ARGS: "+argss);
  1494. //argss+"\"";
  1495. //argss+=" 2>nul";
  1496. FILE* f=_wpopen(argss.c_str(),L"r");
  1497. ERR_FAIL_COND_V(!f,ERR_CANT_OPEN);
  1498. char buf[65535];
  1499. while(fgets(buf,65535,f)) {
  1500. (*r_pipe)+=buf;
  1501. }
  1502. int rv = _pclose(f);
  1503. if (r_exitcode)
  1504. *r_exitcode=rv;
  1505. return OK;
  1506. }
  1507. String cmdline = "\""+p_path+"\"";
  1508. const List<String>::Element* I = p_arguments.front();
  1509. while (I) {
  1510. cmdline += " \""+I->get() + "\"";
  1511. I = I->next();
  1512. };
  1513. //cmdline+="\"";
  1514. ProcessInfo pi;
  1515. ZeroMemory( &pi.si, sizeof(pi.si) );
  1516. pi.si.cb = sizeof(pi.si);
  1517. ZeroMemory( &pi.pi, sizeof(pi.pi) );
  1518. LPSTARTUPINFOW si_w = (LPSTARTUPINFOW) &pi.si;
  1519. print_line("running cmdline: "+cmdline);
  1520. Vector<CharType> modstr; //windows wants to change this no idea why
  1521. modstr.resize(cmdline.size());
  1522. for(int i=0;i<cmdline.size();i++)
  1523. modstr[i]=cmdline[i];
  1524. int ret = CreateProcessW(NULL, modstr.ptr(), NULL, NULL, 0, NORMAL_PRIORITY_CLASS, NULL, NULL, si_w, &pi.pi);
  1525. ERR_FAIL_COND_V(ret == 0, ERR_CANT_FORK);
  1526. if (p_blocking) {
  1527. DWORD ret = WaitForSingleObject(pi.pi.hProcess, INFINITE);
  1528. if (r_exitcode)
  1529. *r_exitcode=ret;
  1530. } else {
  1531. ProcessID pid = pi.pi.dwProcessId;
  1532. if (r_child_id) {
  1533. *r_child_id = pid;
  1534. };
  1535. process_map->insert(pid, pi);
  1536. };
  1537. return OK;
  1538. };
  1539. Error OS_Windows::kill(const ProcessID& p_pid) {
  1540. HANDLE h;
  1541. if (process_map->has(p_pid)) {
  1542. h = (*process_map)[p_pid].pi.hProcess;
  1543. process_map->erase(p_pid);
  1544. } else {
  1545. ERR_FAIL_COND_V(!process_map->has(p_pid), FAILED);
  1546. };
  1547. int ret = TerminateProcess(h, 0);
  1548. return ret != 0?OK:FAILED;
  1549. };
  1550. int OS_Windows::get_process_ID() const {
  1551. return _getpid();
  1552. }
  1553. Error OS_Windows::set_cwd(const String& p_cwd) {
  1554. if (_wchdir(p_cwd.c_str())!=0)
  1555. return ERR_CANT_OPEN;
  1556. return OK;
  1557. }
  1558. String OS_Windows::get_executable_path() const {
  1559. wchar_t bufname[4096];
  1560. GetModuleFileNameW(NULL,bufname,4096);
  1561. String s= bufname;
  1562. print_line("EXEC PATHP??: "+s);
  1563. return s;
  1564. }
  1565. void OS_Windows::set_icon(const Image& p_icon) {
  1566. Image icon=p_icon;
  1567. if (icon.get_format()!=Image::FORMAT_RGBA8)
  1568. icon.convert(Image::FORMAT_RGBA8);
  1569. int w = icon.get_width();
  1570. int h = icon.get_height();
  1571. /* Create temporary bitmap buffer */
  1572. int icon_len = 40 + h * w * 4;
  1573. Vector<BYTE> v;
  1574. v.resize(icon_len);
  1575. BYTE *icon_bmp = &v[0];
  1576. encode_uint32(40,&icon_bmp[0]);
  1577. encode_uint32(w,&icon_bmp[4]);
  1578. encode_uint32(h*2,&icon_bmp[8]);
  1579. encode_uint16(1,&icon_bmp[12]);
  1580. encode_uint16(32,&icon_bmp[14]);
  1581. encode_uint32(BI_RGB,&icon_bmp[16]);
  1582. encode_uint32(w*h*4,&icon_bmp[20]);
  1583. encode_uint32(0,&icon_bmp[24]);
  1584. encode_uint32(0,&icon_bmp[28]);
  1585. encode_uint32(0,&icon_bmp[32]);
  1586. encode_uint32(0,&icon_bmp[36]);
  1587. uint8_t *wr=&icon_bmp[40];
  1588. PoolVector<uint8_t>::Read r= icon.get_data().read();
  1589. for(int i=0;i<h;i++) {
  1590. for(int j=0;j<w;j++) {
  1591. const uint8_t *rpx = &r[((h-i-1)*w+j)*4];
  1592. uint8_t *wpx = &wr[(i*w+j)*4];
  1593. wpx[0]=rpx[2];
  1594. wpx[1]=rpx[1];
  1595. wpx[2]=rpx[0];
  1596. wpx[3]=rpx[3];
  1597. }
  1598. }
  1599. HICON hicon = CreateIconFromResource(icon_bmp, icon_len, TRUE, 0x00030000);
  1600. /* Set the icon for the window */
  1601. SendMessage(hWnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  1602. /* Set the icon in the task manager (should we do this?) */
  1603. SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  1604. }
  1605. bool OS_Windows::has_environment(const String& p_var) const {
  1606. return getenv(p_var.utf8().get_data()) != NULL;
  1607. };
  1608. String OS_Windows::get_environment(const String& p_var) const {
  1609. wchar_t wval[0x7Fff]; // MSDN says 32767 char is the maximum
  1610. int wlen = GetEnvironmentVariableW(p_var.c_str(),wval,0x7Fff);
  1611. if ( wlen > 0 ) {
  1612. return wval;
  1613. }
  1614. return "";
  1615. }
  1616. String OS_Windows::get_stdin_string(bool p_block) {
  1617. if (p_block) {
  1618. char buff[1024];
  1619. return fgets(buff,1024,stdin);
  1620. };
  1621. return String();
  1622. }
  1623. void OS_Windows::enable_for_stealing_focus(ProcessID pid) {
  1624. AllowSetForegroundWindow(pid);
  1625. }
  1626. void OS_Windows::move_window_to_foreground() {
  1627. SetForegroundWindow(hWnd);
  1628. }
  1629. Error OS_Windows::shell_open(String p_uri) {
  1630. ShellExecuteW(NULL, L"open", p_uri.c_str(), NULL, NULL, SW_SHOWNORMAL);
  1631. return OK;
  1632. }
  1633. String OS_Windows::get_locale() const {
  1634. const _WinLocale *wl = &_win_locales[0];
  1635. LANGID langid = GetUserDefaultUILanguage();
  1636. String neutral;
  1637. int lang = langid&((1<<9)-1);
  1638. int sublang = langid&~((1<<9)-1);
  1639. while(wl->locale) {
  1640. if (wl->main_lang==lang && wl->sublang==SUBLANG_NEUTRAL)
  1641. neutral=wl->locale;
  1642. if (lang==wl->main_lang && sublang==wl->sublang)
  1643. return wl->locale;
  1644. wl++;
  1645. }
  1646. if (neutral!="")
  1647. return neutral;
  1648. return "en";
  1649. }
  1650. OS::LatinKeyboardVariant OS_Windows::get_latin_keyboard_variant() const {
  1651. unsigned long azerty[] = {
  1652. 0x00020401, // Arabic (102) AZERTY
  1653. 0x0001080c, // Belgian (Comma)
  1654. 0x0000080c, // Belgian French
  1655. 0x0000040c, // French
  1656. 0 // <--- STOP MARK
  1657. };
  1658. unsigned long qwertz[] = {
  1659. 0x0000041a, // Croation
  1660. 0x00000405, // Czech
  1661. 0x00000407, // German
  1662. 0x00010407, // German (IBM)
  1663. 0x0000040e, // Hungarian
  1664. 0x0000046e, // Luxembourgish
  1665. 0x00010415, // Polish (214)
  1666. 0x00000418, // Romanian (Legacy)
  1667. 0x0000081a, // Serbian (Latin)
  1668. 0x0000041b, // Slovak
  1669. 0x00000424, // Slovenian
  1670. 0x0001042e, // Sorbian Extended
  1671. 0x0002042e, // Sorbian Standard
  1672. 0x0000042e, // Sorbian Standard (Legacy)
  1673. 0x0000100c, // Swiss French
  1674. 0x00000807, // Swiss German
  1675. 0 // <--- STOP MARK
  1676. };
  1677. unsigned long dvorak[] = {
  1678. 0x00010409, // US-Dvorak
  1679. 0x00030409, // US-Dvorak for left hand
  1680. 0x00040409, // US-Dvorak for right hand
  1681. 0 // <--- STOP MARK
  1682. };
  1683. char name[ KL_NAMELENGTH + 1 ]; name[0] = 0;
  1684. GetKeyboardLayoutNameA( name );
  1685. unsigned long hex = strtoul(name, NULL, 16);
  1686. int i=0;
  1687. while( azerty[i] != 0 ) {
  1688. if (azerty[i] == hex) return LATIN_KEYBOARD_AZERTY;
  1689. i++;
  1690. }
  1691. i = 0;
  1692. while( qwertz[i] != 0 ) {
  1693. if (qwertz[i] == hex) return LATIN_KEYBOARD_QWERTZ;
  1694. i++;
  1695. }
  1696. i = 0;
  1697. while( dvorak[i] != 0 ) {
  1698. if (dvorak[i] == hex) return LATIN_KEYBOARD_DVORAK;
  1699. i++;
  1700. }
  1701. return LATIN_KEYBOARD_QWERTY;
  1702. }
  1703. void OS_Windows::release_rendering_thread() {
  1704. gl_context->release_current();
  1705. }
  1706. void OS_Windows::make_rendering_thread() {
  1707. gl_context->make_current();
  1708. }
  1709. void OS_Windows::swap_buffers() {
  1710. gl_context->swap_buffers();
  1711. }
  1712. void OS_Windows::run() {
  1713. if (!main_loop)
  1714. return;
  1715. main_loop->init();
  1716. uint64_t last_ticks=get_ticks_usec();
  1717. int frames=0;
  1718. uint64_t frame=0;
  1719. while (!force_quit) {
  1720. process_events(); // get rid of pending events
  1721. if (Main::iteration()==true)
  1722. break;
  1723. };
  1724. main_loop->finish();
  1725. }
  1726. MainLoop *OS_Windows::get_main_loop() const {
  1727. return main_loop;
  1728. }
  1729. String OS_Windows::get_system_dir(SystemDir p_dir) const {
  1730. int id;
  1731. switch(p_dir) {
  1732. case SYSTEM_DIR_DESKTOP: {
  1733. id=CSIDL_DESKTOPDIRECTORY;
  1734. } break;
  1735. case SYSTEM_DIR_DCIM: {
  1736. id=CSIDL_MYPICTURES;
  1737. } break;
  1738. case SYSTEM_DIR_DOCUMENTS: {
  1739. id=CSIDL_PERSONAL;
  1740. } break;
  1741. case SYSTEM_DIR_DOWNLOADS: {
  1742. id=0x000C ;
  1743. } break;
  1744. case SYSTEM_DIR_MOVIES: {
  1745. id=CSIDL_MYVIDEO;
  1746. } break;
  1747. case SYSTEM_DIR_MUSIC: {
  1748. id=CSIDL_MYMUSIC;
  1749. } break;
  1750. case SYSTEM_DIR_PICTURES: {
  1751. id=CSIDL_MYPICTURES;
  1752. } break;
  1753. case SYSTEM_DIR_RINGTONES: {
  1754. id=CSIDL_MYMUSIC;
  1755. } break;
  1756. }
  1757. WCHAR szPath[MAX_PATH];
  1758. HRESULT res = SHGetFolderPathW(NULL,id,NULL,0,szPath);
  1759. ERR_FAIL_COND_V(res!=S_OK,String());
  1760. return String(szPath);
  1761. }
  1762. String OS_Windows::get_data_dir() const {
  1763. String an = get_safe_application_name();
  1764. if (an!="") {
  1765. if (has_environment("APPDATA")) {
  1766. bool use_godot = GlobalConfig::get_singleton()->get("application/use_shared_user_dir");
  1767. if (!use_godot)
  1768. return (OS::get_singleton()->get_environment("APPDATA")+"/"+an).replace("\\","/");
  1769. else
  1770. return (OS::get_singleton()->get_environment("APPDATA")+"/Godot/app_userdata/"+an).replace("\\","/");
  1771. }
  1772. }
  1773. return GlobalConfig::get_singleton()->get_resource_path();
  1774. }
  1775. bool OS_Windows::is_joy_known(int p_device) {
  1776. return input->is_joy_mapped(p_device);
  1777. }
  1778. String OS_Windows::get_joy_guid(int p_device) const {
  1779. return input->get_joy_guid_remapped(p_device);
  1780. }
  1781. void OS_Windows::set_use_vsync(bool p_enable) {
  1782. if (gl_context)
  1783. gl_context->set_use_vsync(p_enable);
  1784. }
  1785. bool OS_Windows::is_vsync_enabled() const{
  1786. if (gl_context)
  1787. return gl_context->is_using_vsync();
  1788. return true;
  1789. }
  1790. OS_Windows::OS_Windows(HINSTANCE _hInstance) {
  1791. key_event_pos=0;
  1792. force_quit=false;
  1793. alt_mem=false;
  1794. gr_mem=false;
  1795. shift_mem=false;
  1796. control_mem=false;
  1797. meta_mem=false;
  1798. minimized = false;
  1799. hInstance=_hInstance;
  1800. pressrc=0;
  1801. old_invalid=true;
  1802. last_id=0;
  1803. mouse_mode=MOUSE_MODE_VISIBLE;
  1804. #ifdef STDOUT_FILE
  1805. stdo=fopen("stdout.txt","wb");
  1806. #endif
  1807. user_proc = NULL;
  1808. #ifdef RTAUDIO_ENABLED
  1809. AudioDriverManagerSW::add_driver(&driver_rtaudio);
  1810. #endif
  1811. #ifdef XAUDIO2_ENABLED
  1812. AudioDriverManagerSW::add_driver(&driver_xaudio2);
  1813. #endif
  1814. }
  1815. OS_Windows::~OS_Windows()
  1816. {
  1817. #ifdef STDOUT_FILE
  1818. fclose(stdo);
  1819. #endif
  1820. }