os_windows.cpp 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281
  1. /*************************************************************************/
  2. /* os_windows.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. // Must include Winsock before windows.h (included by os_windows.h)
  31. #include "drivers/unix/net_socket_posix.h"
  32. #include "os_windows.h"
  33. #include "core/io/marshalls.h"
  34. #include "core/version_generated.gen.h"
  35. #include "drivers/gles2/rasterizer_gles2.h"
  36. #include "drivers/gles3/rasterizer_gles3.h"
  37. #include "drivers/windows/dir_access_windows.h"
  38. #include "drivers/windows/file_access_windows.h"
  39. #include "drivers/windows/mutex_windows.h"
  40. #include "drivers/windows/rw_lock_windows.h"
  41. #include "drivers/windows/semaphore_windows.h"
  42. #include "drivers/windows/thread_windows.h"
  43. #include "joypad_windows.h"
  44. #include "lang_table.h"
  45. #include "main/main.h"
  46. #include "servers/audio_server.h"
  47. #include "servers/visual/visual_server_raster.h"
  48. #include "servers/visual/visual_server_wrap_mt.h"
  49. #include "windows_terminal_logger.h"
  50. #include <avrt.h>
  51. #include <direct.h>
  52. #include <knownfolders.h>
  53. #include <process.h>
  54. #include <regstr.h>
  55. #include <shlobj.h>
  56. static const WORD MAX_CONSOLE_LINES = 1500;
  57. extern "C" {
  58. __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  59. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  60. }
  61. // Workaround mingw-w64 < 4.0 bug
  62. #ifndef WM_TOUCH
  63. #define WM_TOUCH 576
  64. #endif
  65. typedef struct {
  66. int count;
  67. int screen;
  68. Size2 size;
  69. } EnumSizeData;
  70. typedef struct {
  71. int count;
  72. int screen;
  73. Point2 pos;
  74. } EnumPosData;
  75. static BOOL CALLBACK _MonitorEnumProcSize(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  76. EnumSizeData *data = (EnumSizeData *)dwData;
  77. if (data->count == data->screen) {
  78. data->size.x = lprcMonitor->right - lprcMonitor->left;
  79. data->size.y = lprcMonitor->bottom - lprcMonitor->top;
  80. }
  81. data->count++;
  82. return TRUE;
  83. }
  84. #ifdef DEBUG_ENABLED
  85. static String format_error_message(DWORD id) {
  86. LPWSTR messageBuffer = NULL;
  87. size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  88. NULL, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, NULL);
  89. String msg = "Error " + itos(id) + ": " + String(messageBuffer, size);
  90. LocalFree(messageBuffer);
  91. return msg;
  92. }
  93. #endif // DEBUG_ENABLED
  94. extern HINSTANCE godot_hinstance;
  95. void RedirectIOToConsole() {
  96. int hConHandle;
  97. intptr_t lStdHandle;
  98. CONSOLE_SCREEN_BUFFER_INFO coninfo;
  99. FILE *fp;
  100. // allocate a console for this app
  101. AllocConsole();
  102. // set the screen buffer to be big enough to let us scroll text
  103. GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),
  104. &coninfo);
  105. coninfo.dwSize.Y = MAX_CONSOLE_LINES;
  106. SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),
  107. coninfo.dwSize);
  108. // redirect unbuffered STDOUT to the console
  109. lStdHandle = (intptr_t)GetStdHandle(STD_OUTPUT_HANDLE);
  110. hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  111. fp = _fdopen(hConHandle, "w");
  112. *stdout = *fp;
  113. setvbuf(stdout, NULL, _IONBF, 0);
  114. // redirect unbuffered STDIN to the console
  115. lStdHandle = (intptr_t)GetStdHandle(STD_INPUT_HANDLE);
  116. hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  117. fp = _fdopen(hConHandle, "r");
  118. *stdin = *fp;
  119. setvbuf(stdin, NULL, _IONBF, 0);
  120. // redirect unbuffered STDERR to the console
  121. lStdHandle = (intptr_t)GetStdHandle(STD_ERROR_HANDLE);
  122. hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  123. fp = _fdopen(hConHandle, "w");
  124. *stderr = *fp;
  125. setvbuf(stderr, NULL, _IONBF, 0);
  126. // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
  127. // point to console as well
  128. }
  129. BOOL WINAPI HandlerRoutine(_In_ DWORD dwCtrlType) {
  130. if (ScriptDebugger::get_singleton() == NULL)
  131. return FALSE;
  132. switch (dwCtrlType) {
  133. case CTRL_C_EVENT:
  134. ScriptDebugger::get_singleton()->set_depth(-1);
  135. ScriptDebugger::get_singleton()->set_lines_left(1);
  136. return TRUE;
  137. default:
  138. return FALSE;
  139. }
  140. }
  141. void OS_Windows::initialize_debugging() {
  142. SetConsoleCtrlHandler(HandlerRoutine, TRUE);
  143. }
  144. void OS_Windows::initialize_core() {
  145. crash_handler.initialize();
  146. last_button_state = 0;
  147. //RedirectIOToConsole();
  148. maximized = false;
  149. minimized = false;
  150. borderless = false;
  151. ThreadWindows::make_default();
  152. SemaphoreWindows::make_default();
  153. MutexWindows::make_default();
  154. RWLockWindows::make_default();
  155. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_RESOURCES);
  156. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_USERDATA);
  157. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_FILESYSTEM);
  158. //FileAccessBufferedFA<FileAccessWindows>::make_default();
  159. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_RESOURCES);
  160. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_USERDATA);
  161. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_FILESYSTEM);
  162. NetSocketPosix::make_default();
  163. // We need to know how often the clock is updated
  164. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
  165. ticks_per_second = 1000;
  166. // If timeAtGameStart is 0 then we get the time since
  167. // the start of the computer when we call GetGameTime()
  168. ticks_start = 0;
  169. ticks_start = get_ticks_usec();
  170. // set minimum resolution for periodic timers, otherwise Sleep(n) may wait at least as
  171. // long as the windows scheduler resolution (~16-30ms) even for calls like Sleep(1)
  172. timeBeginPeriod(1);
  173. process_map = memnew((Map<ProcessID, ProcessInfo>));
  174. IP_Unix::make_default();
  175. cursor_shape = CURSOR_ARROW;
  176. }
  177. bool OS_Windows::can_draw() const {
  178. return !minimized;
  179. };
  180. #define MI_WP_SIGNATURE 0xFF515700
  181. #define SIGNATURE_MASK 0xFFFFFF00
  182. // Keeping the name suggested by Microsoft, but this macro really answers:
  183. // Is this mouse event emulated from touch or pen input?
  184. #define IsPenEvent(dw) (((dw)&SIGNATURE_MASK) == MI_WP_SIGNATURE)
  185. // This one tells whether the event comes from touchscreen (and not from pen)
  186. #define IsTouchEvent(dw) (IsPenEvent(dw) && ((dw)&0x80))
  187. void OS_Windows::_touch_event(bool p_pressed, float p_x, float p_y, int idx) {
  188. // Defensive
  189. if (touch_state.has(idx) == p_pressed)
  190. return;
  191. if (p_pressed) {
  192. touch_state.insert(idx, Vector2(p_x, p_y));
  193. } else {
  194. touch_state.erase(idx);
  195. }
  196. Ref<InputEventScreenTouch> event;
  197. event.instance();
  198. event->set_index(idx);
  199. event->set_pressed(p_pressed);
  200. event->set_position(Vector2(p_x, p_y));
  201. if (main_loop) {
  202. input->accumulate_input_event(event);
  203. }
  204. };
  205. void OS_Windows::_drag_event(float p_x, float p_y, int idx) {
  206. Map<int, Vector2>::Element *curr = touch_state.find(idx);
  207. // Defensive
  208. if (!curr)
  209. return;
  210. if (curr->get() == Vector2(p_x, p_y))
  211. return;
  212. Ref<InputEventScreenDrag> event;
  213. event.instance();
  214. event->set_index(idx);
  215. event->set_position(Vector2(p_x, p_y));
  216. event->set_relative(Vector2(p_x, p_y) - curr->get());
  217. if (main_loop)
  218. input->accumulate_input_event(event);
  219. curr->get() = Vector2(p_x, p_y);
  220. };
  221. LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  222. if (drop_events) {
  223. if (user_proc) {
  224. return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
  225. } else {
  226. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  227. }
  228. };
  229. switch (uMsg) // Check For Windows Messages
  230. {
  231. case WM_SETFOCUS: {
  232. window_has_focus = true;
  233. // Restore mouse mode
  234. _set_mouse_mode_impl(mouse_mode);
  235. break;
  236. }
  237. case WM_KILLFOCUS: {
  238. window_has_focus = false;
  239. // Release capture unconditionally because it can be set due to dragging, in addition to captured mode
  240. ReleaseCapture();
  241. // Release every touch to avoid sticky points
  242. for (Map<int, Vector2>::Element *E = touch_state.front(); E; E = E->next()) {
  243. _touch_event(false, E->get().x, E->get().y, E->key());
  244. }
  245. touch_state.clear();
  246. break;
  247. }
  248. case WM_ACTIVATE: // Watch For Window Activate Message
  249. {
  250. minimized = HIWORD(wParam) != 0;
  251. if (!main_loop) {
  252. return 0;
  253. };
  254. if (LOWORD(wParam) == WA_ACTIVE || LOWORD(wParam) == WA_CLICKACTIVE) {
  255. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
  256. alt_mem = false;
  257. control_mem = false;
  258. shift_mem = false;
  259. } else { // WM_INACTIVE
  260. input->release_pressed_events();
  261. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  262. alt_mem = false;
  263. };
  264. return 0; // Return To The Message Loop
  265. }
  266. case WM_GETMINMAXINFO: {
  267. if (video_mode.resizable && !video_mode.fullscreen) {
  268. Size2 decor = get_real_window_size() - get_window_size(); // Size of window decorations
  269. MINMAXINFO *min_max_info = (MINMAXINFO *)lParam;
  270. if (min_size != Size2()) {
  271. min_max_info->ptMinTrackSize.x = min_size.x + decor.x;
  272. min_max_info->ptMinTrackSize.y = min_size.y + decor.y;
  273. }
  274. if (max_size != Size2()) {
  275. min_max_info->ptMaxTrackSize.x = max_size.x + decor.x;
  276. min_max_info->ptMaxTrackSize.y = max_size.y + decor.y;
  277. }
  278. return 0;
  279. } else {
  280. break;
  281. }
  282. }
  283. case WM_PAINT:
  284. Main::force_redraw();
  285. break;
  286. case WM_SYSCOMMAND: // Intercept System Commands
  287. {
  288. switch (wParam) // Check System Calls
  289. {
  290. case SC_SCREENSAVE: // Screensaver Trying To Start?
  291. case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
  292. return 0; // Prevent From Happening
  293. case SC_KEYMENU:
  294. if ((lParam >> 16) <= 0)
  295. return 0;
  296. }
  297. break; // Exit
  298. }
  299. case WM_CLOSE: // Did We Receive A Close Message?
  300. {
  301. if (main_loop)
  302. main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  303. //force_quit=true;
  304. return 0; // Jump Back
  305. }
  306. case WM_MOUSELEAVE: {
  307. old_invalid = true;
  308. outside = true;
  309. if (main_loop && mouse_mode != MOUSE_MODE_CAPTURED)
  310. main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
  311. } break;
  312. case WM_INPUT: {
  313. if (mouse_mode != MOUSE_MODE_CAPTURED || !use_raw_input) {
  314. break;
  315. }
  316. UINT dwSize;
  317. GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER));
  318. LPBYTE lpb = new BYTE[dwSize];
  319. if (lpb == NULL) {
  320. return 0;
  321. }
  322. if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize)
  323. OutputDebugString(TEXT("GetRawInputData does not return correct size !\n"));
  324. RAWINPUT *raw = (RAWINPUT *)lpb;
  325. if (raw->header.dwType == RIM_TYPEMOUSE) {
  326. Ref<InputEventMouseMotion> mm;
  327. mm.instance();
  328. mm->set_control(control_mem);
  329. mm->set_shift(shift_mem);
  330. mm->set_alt(alt_mem);
  331. mm->set_button_mask(last_button_state);
  332. Point2i c(video_mode.width / 2, video_mode.height / 2);
  333. // centering just so it works as before
  334. POINT pos = { (int)c.x, (int)c.y };
  335. ClientToScreen(hWnd, &pos);
  336. SetCursorPos(pos.x, pos.y);
  337. mm->set_position(c);
  338. mm->set_global_position(c);
  339. input->set_mouse_position(c);
  340. mm->set_speed(Vector2(0, 0));
  341. if (raw->data.mouse.usFlags == MOUSE_MOVE_RELATIVE) {
  342. mm->set_relative(Vector2(raw->data.mouse.lLastX, raw->data.mouse.lLastY));
  343. } else if (raw->data.mouse.usFlags == MOUSE_MOVE_ABSOLUTE) {
  344. int nScreenWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN);
  345. int nScreenHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN);
  346. int nScreenLeft = GetSystemMetrics(SM_XVIRTUALSCREEN);
  347. int nScreenTop = GetSystemMetrics(SM_YVIRTUALSCREEN);
  348. Vector2 abs_pos(
  349. (double(raw->data.mouse.lLastX) - 65536.0 / (nScreenWidth)) * nScreenWidth / 65536.0 + nScreenLeft,
  350. (double(raw->data.mouse.lLastY) - 65536.0 / (nScreenHeight)) * nScreenHeight / 65536.0 + nScreenTop);
  351. POINT coords; //client coords
  352. coords.x = abs_pos.x;
  353. coords.y = abs_pos.y;
  354. ScreenToClient(hWnd, &coords);
  355. mm->set_relative(Vector2(coords.x - old_x, coords.y - old_y));
  356. old_x = coords.x;
  357. old_y = coords.y;
  358. /*Input.mi.dx = (int)((((double)(pos.x)-nScreenLeft) * 65536) / nScreenWidth + 65536 / (nScreenWidth));
  359. Input.mi.dy = (int)((((double)(pos.y)-nScreenTop) * 65536) / nScreenHeight + 65536 / (nScreenHeight));
  360. */
  361. }
  362. if (window_has_focus && main_loop && mm->get_relative() != Vector2())
  363. input->accumulate_input_event(mm);
  364. }
  365. delete[] lpb;
  366. } break;
  367. case WM_MOUSEMOVE: {
  368. if (mouse_mode == MOUSE_MODE_CAPTURED && use_raw_input) {
  369. break;
  370. }
  371. if (input->is_emulating_mouse_from_touch()) {
  372. // Universal translation enabled; ignore OS translation
  373. LPARAM extra = GetMessageExtraInfo();
  374. if (IsTouchEvent(extra)) {
  375. break;
  376. }
  377. }
  378. if (outside) {
  379. //mouse enter
  380. if (main_loop && mouse_mode != MOUSE_MODE_CAPTURED)
  381. main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
  382. CursorShape c = cursor_shape;
  383. cursor_shape = CURSOR_MAX;
  384. set_cursor_shape(c);
  385. outside = false;
  386. //Once-Off notification, must call again....
  387. TRACKMOUSEEVENT tme;
  388. tme.cbSize = sizeof(TRACKMOUSEEVENT);
  389. tme.dwFlags = TME_LEAVE;
  390. tme.hwndTrack = hWnd;
  391. tme.dwHoverTime = HOVER_DEFAULT;
  392. TrackMouseEvent(&tme);
  393. }
  394. // Don't calculate relative mouse movement if we don't have focus in CAPTURED mode.
  395. if (!window_has_focus && mouse_mode == MOUSE_MODE_CAPTURED)
  396. break;
  397. Ref<InputEventMouseMotion> mm;
  398. mm.instance();
  399. mm->set_control((wParam & MK_CONTROL) != 0);
  400. mm->set_shift((wParam & MK_SHIFT) != 0);
  401. mm->set_alt(alt_mem);
  402. mm->set_button_mask(last_button_state);
  403. mm->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
  404. mm->set_global_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
  405. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  406. Point2i c(video_mode.width / 2, video_mode.height / 2);
  407. old_x = c.x;
  408. old_y = c.y;
  409. if (mm->get_position() == c) {
  410. center = c;
  411. return 0;
  412. }
  413. Point2i ncenter = mm->get_position();
  414. center = ncenter;
  415. POINT pos = { (int)c.x, (int)c.y };
  416. ClientToScreen(hWnd, &pos);
  417. SetCursorPos(pos.x, pos.y);
  418. }
  419. input->set_mouse_position(mm->get_position());
  420. mm->set_speed(input->get_last_mouse_speed());
  421. if (old_invalid) {
  422. old_x = mm->get_position().x;
  423. old_y = mm->get_position().y;
  424. old_invalid = false;
  425. }
  426. mm->set_relative(Vector2(mm->get_position() - Vector2(old_x, old_y)));
  427. old_x = mm->get_position().x;
  428. old_y = mm->get_position().y;
  429. if (window_has_focus && main_loop)
  430. input->accumulate_input_event(mm);
  431. } break;
  432. case WM_LBUTTONDOWN:
  433. case WM_LBUTTONUP:
  434. if (input->is_emulating_mouse_from_touch()) {
  435. // Universal translation enabled; ignore OS translations for left button
  436. LPARAM extra = GetMessageExtraInfo();
  437. if (IsTouchEvent(extra)) {
  438. break;
  439. }
  440. }
  441. FALLTHROUGH;
  442. case WM_MBUTTONDOWN:
  443. case WM_MBUTTONUP:
  444. case WM_RBUTTONDOWN:
  445. case WM_RBUTTONUP:
  446. case WM_MOUSEWHEEL:
  447. case WM_MOUSEHWHEEL:
  448. case WM_LBUTTONDBLCLK:
  449. case WM_MBUTTONDBLCLK:
  450. case WM_RBUTTONDBLCLK:
  451. case WM_XBUTTONDBLCLK:
  452. case WM_XBUTTONDOWN:
  453. case WM_XBUTTONUP: {
  454. Ref<InputEventMouseButton> mb;
  455. mb.instance();
  456. switch (uMsg) {
  457. case WM_LBUTTONDOWN: {
  458. mb->set_pressed(true);
  459. mb->set_button_index(1);
  460. } break;
  461. case WM_LBUTTONUP: {
  462. mb->set_pressed(false);
  463. mb->set_button_index(1);
  464. } break;
  465. case WM_MBUTTONDOWN: {
  466. mb->set_pressed(true);
  467. mb->set_button_index(3);
  468. } break;
  469. case WM_MBUTTONUP: {
  470. mb->set_pressed(false);
  471. mb->set_button_index(3);
  472. } break;
  473. case WM_RBUTTONDOWN: {
  474. mb->set_pressed(true);
  475. mb->set_button_index(2);
  476. } break;
  477. case WM_RBUTTONUP: {
  478. mb->set_pressed(false);
  479. mb->set_button_index(2);
  480. } break;
  481. case WM_LBUTTONDBLCLK: {
  482. mb->set_pressed(true);
  483. mb->set_button_index(1);
  484. mb->set_doubleclick(true);
  485. } break;
  486. case WM_RBUTTONDBLCLK: {
  487. mb->set_pressed(true);
  488. mb->set_button_index(2);
  489. mb->set_doubleclick(true);
  490. } break;
  491. case WM_MBUTTONDBLCLK: {
  492. mb->set_pressed(true);
  493. mb->set_button_index(3);
  494. mb->set_doubleclick(true);
  495. } break;
  496. case WM_MOUSEWHEEL: {
  497. mb->set_pressed(true);
  498. int motion = (short)HIWORD(wParam);
  499. if (!motion)
  500. return 0;
  501. if (motion > 0)
  502. mb->set_button_index(BUTTON_WHEEL_UP);
  503. else
  504. mb->set_button_index(BUTTON_WHEEL_DOWN);
  505. } break;
  506. case WM_MOUSEHWHEEL: {
  507. mb->set_pressed(true);
  508. int motion = (short)HIWORD(wParam);
  509. if (!motion)
  510. return 0;
  511. if (motion < 0) {
  512. mb->set_button_index(BUTTON_WHEEL_LEFT);
  513. mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA));
  514. } else {
  515. mb->set_button_index(BUTTON_WHEEL_RIGHT);
  516. mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA));
  517. }
  518. } break;
  519. case WM_XBUTTONDOWN: {
  520. mb->set_pressed(true);
  521. if (HIWORD(wParam) == XBUTTON1)
  522. mb->set_button_index(BUTTON_XBUTTON1);
  523. else
  524. mb->set_button_index(BUTTON_XBUTTON2);
  525. } break;
  526. case WM_XBUTTONUP: {
  527. mb->set_pressed(false);
  528. if (HIWORD(wParam) == XBUTTON1)
  529. mb->set_button_index(BUTTON_XBUTTON1);
  530. else
  531. mb->set_button_index(BUTTON_XBUTTON2);
  532. } break;
  533. case WM_XBUTTONDBLCLK: {
  534. mb->set_pressed(true);
  535. if (HIWORD(wParam) == XBUTTON1)
  536. mb->set_button_index(BUTTON_XBUTTON1);
  537. else
  538. mb->set_button_index(BUTTON_XBUTTON2);
  539. mb->set_doubleclick(true);
  540. } break;
  541. default: {
  542. return 0;
  543. }
  544. }
  545. mb->set_control((wParam & MK_CONTROL) != 0);
  546. mb->set_shift((wParam & MK_SHIFT) != 0);
  547. mb->set_alt(alt_mem);
  548. //mb->get_alt()=(wParam&MK_MENU)!=0;
  549. if (mb->is_pressed())
  550. last_button_state |= (1 << (mb->get_button_index() - 1));
  551. else
  552. last_button_state &= ~(1 << (mb->get_button_index() - 1));
  553. mb->set_button_mask(last_button_state);
  554. mb->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
  555. if (mouse_mode == MOUSE_MODE_CAPTURED && !use_raw_input) {
  556. mb->set_position(Vector2(old_x, old_y));
  557. }
  558. if (uMsg != WM_MOUSEWHEEL && uMsg != WM_MOUSEHWHEEL) {
  559. if (mb->is_pressed()) {
  560. if (++pressrc > 0 && mouse_mode != MOUSE_MODE_CAPTURED)
  561. SetCapture(hWnd);
  562. } else {
  563. if (--pressrc <= 0) {
  564. if (mouse_mode != MOUSE_MODE_CAPTURED) {
  565. ReleaseCapture();
  566. }
  567. pressrc = 0;
  568. }
  569. }
  570. } else {
  571. // for reasons unknown to mankind, wheel comes in screen coordinates
  572. POINT coords;
  573. coords.x = mb->get_position().x;
  574. coords.y = mb->get_position().y;
  575. ScreenToClient(hWnd, &coords);
  576. mb->set_position(Vector2(coords.x, coords.y));
  577. }
  578. mb->set_global_position(mb->get_position());
  579. if (main_loop) {
  580. input->accumulate_input_event(mb);
  581. if (mb->is_pressed() && mb->get_button_index() > 3 && mb->get_button_index() < 8) {
  582. //send release for mouse wheel
  583. Ref<InputEventMouseButton> mbd = mb->duplicate();
  584. last_button_state &= ~(1 << (mbd->get_button_index() - 1));
  585. mbd->set_button_mask(last_button_state);
  586. mbd->set_pressed(false);
  587. input->accumulate_input_event(mbd);
  588. }
  589. }
  590. } break;
  591. case WM_MOVE: {
  592. if (!IsIconic(hWnd)) {
  593. int x = LOWORD(lParam);
  594. int y = HIWORD(lParam);
  595. last_pos = Point2(x, y);
  596. }
  597. } break;
  598. case WM_SIZE: {
  599. // Ignore size when a SIZE_MINIMIZED event is triggered
  600. if (wParam != SIZE_MINIMIZED) {
  601. int window_w = LOWORD(lParam);
  602. int window_h = HIWORD(lParam);
  603. if (window_w > 0 && window_h > 0 && !preserve_window_size) {
  604. video_mode.width = window_w;
  605. video_mode.height = window_h;
  606. } else {
  607. preserve_window_size = false;
  608. set_window_size(Size2(video_mode.width, video_mode.height));
  609. }
  610. }
  611. if (wParam == SIZE_MAXIMIZED) {
  612. maximized = true;
  613. minimized = false;
  614. } else if (wParam == SIZE_MINIMIZED) {
  615. maximized = false;
  616. minimized = true;
  617. } else if (wParam == SIZE_RESTORED) {
  618. maximized = false;
  619. minimized = false;
  620. }
  621. if (is_layered_allowed() && layered_window) {
  622. DeleteObject(hBitmap);
  623. RECT r;
  624. GetWindowRect(hWnd, &r);
  625. dib_size = Size2i(r.right - r.left, r.bottom - r.top);
  626. BITMAPINFO bmi;
  627. ZeroMemory(&bmi, sizeof(BITMAPINFO));
  628. bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
  629. bmi.bmiHeader.biWidth = dib_size.x;
  630. bmi.bmiHeader.biHeight = dib_size.y;
  631. bmi.bmiHeader.biPlanes = 1;
  632. bmi.bmiHeader.biBitCount = 32;
  633. bmi.bmiHeader.biCompression = BI_RGB;
  634. bmi.bmiHeader.biSizeImage = dib_size.x * dib_size.y * 4;
  635. hBitmap = CreateDIBSection(hDC_dib, &bmi, DIB_RGB_COLORS, (void **)&dib_data, NULL, 0x0);
  636. SelectObject(hDC_dib, hBitmap);
  637. ZeroMemory(dib_data, dib_size.x * dib_size.y * 4);
  638. }
  639. //return 0; // Jump Back
  640. } break;
  641. case WM_ENTERSIZEMOVE: {
  642. input->release_pressed_events();
  643. move_timer_id = SetTimer(hWnd, 1, USER_TIMER_MINIMUM, (TIMERPROC)NULL);
  644. } break;
  645. case WM_EXITSIZEMOVE: {
  646. KillTimer(hWnd, move_timer_id);
  647. } break;
  648. case WM_TIMER: {
  649. if (wParam == move_timer_id) {
  650. process_key_events();
  651. if (!Main::is_iterating()) {
  652. Main::iteration();
  653. }
  654. }
  655. } break;
  656. case WM_SYSKEYDOWN:
  657. case WM_SYSKEYUP:
  658. case WM_KEYUP:
  659. case WM_KEYDOWN: {
  660. if (wParam == VK_SHIFT)
  661. shift_mem = uMsg == WM_KEYDOWN;
  662. if (wParam == VK_CONTROL)
  663. control_mem = uMsg == WM_KEYDOWN;
  664. if (wParam == VK_MENU) {
  665. alt_mem = (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN);
  666. if (lParam & (1 << 24))
  667. gr_mem = alt_mem;
  668. }
  669. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  670. // When SetCapture is used, ALT+F4 hotkey is ignored by Windows, so handle it ourselves
  671. if (wParam == VK_F4 && alt_mem && (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN)) {
  672. if (main_loop)
  673. main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  674. }
  675. }
  676. /*
  677. if (wParam==VK_WIN) TODO wtf is this?
  678. meta_mem=uMsg==WM_KEYDOWN;
  679. */
  680. FALLTHROUGH;
  681. }
  682. case WM_CHAR: {
  683. ERR_BREAK(key_event_pos >= KEY_EVENT_BUFFER_SIZE);
  684. // Make sure we don't include modifiers for the modifier key itself.
  685. KeyEvent ke;
  686. ke.shift = (wParam != VK_SHIFT) ? shift_mem : false;
  687. ke.alt = (!(wParam == VK_MENU && (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN))) ? alt_mem : false;
  688. ke.control = (wParam != VK_CONTROL) ? control_mem : false;
  689. ke.meta = meta_mem;
  690. ke.uMsg = uMsg;
  691. if (ke.uMsg == WM_SYSKEYDOWN)
  692. ke.uMsg = WM_KEYDOWN;
  693. if (ke.uMsg == WM_SYSKEYUP)
  694. ke.uMsg = WM_KEYUP;
  695. ke.wParam = wParam;
  696. ke.lParam = lParam;
  697. key_event_buffer[key_event_pos++] = ke;
  698. } break;
  699. case WM_INPUTLANGCHANGEREQUEST: {
  700. // FIXME: Do something?
  701. } break;
  702. case WM_TOUCH: {
  703. BOOL bHandled = FALSE;
  704. UINT cInputs = LOWORD(wParam);
  705. PTOUCHINPUT pInputs = memnew_arr(TOUCHINPUT, cInputs);
  706. if (pInputs) {
  707. if (GetTouchInputInfo((HTOUCHINPUT)lParam, cInputs, pInputs, sizeof(TOUCHINPUT))) {
  708. for (UINT i = 0; i < cInputs; i++) {
  709. TOUCHINPUT ti = pInputs[i];
  710. POINT touch_pos = {
  711. TOUCH_COORD_TO_PIXEL(ti.x),
  712. TOUCH_COORD_TO_PIXEL(ti.y),
  713. };
  714. ScreenToClient(hWnd, &touch_pos);
  715. //do something with each touch input entry
  716. if (ti.dwFlags & TOUCHEVENTF_MOVE) {
  717. _drag_event(touch_pos.x, touch_pos.y, ti.dwID);
  718. } else if (ti.dwFlags & (TOUCHEVENTF_UP | TOUCHEVENTF_DOWN)) {
  719. _touch_event(ti.dwFlags & TOUCHEVENTF_DOWN, touch_pos.x, touch_pos.y, ti.dwID);
  720. };
  721. }
  722. bHandled = TRUE;
  723. } else {
  724. /* handle the error here */
  725. }
  726. memdelete_arr(pInputs);
  727. } else {
  728. /* handle the error here, probably out of memory */
  729. }
  730. if (bHandled) {
  731. CloseTouchInputHandle((HTOUCHINPUT)lParam);
  732. return 0;
  733. };
  734. } break;
  735. case WM_DEVICECHANGE: {
  736. joypad->probe_joypads();
  737. } break;
  738. case WM_SETCURSOR: {
  739. if (LOWORD(lParam) == HTCLIENT) {
  740. if (window_has_focus && (mouse_mode == MOUSE_MODE_HIDDEN || mouse_mode == MOUSE_MODE_CAPTURED)) {
  741. //Hide the cursor
  742. if (hCursor == NULL)
  743. hCursor = SetCursor(NULL);
  744. else
  745. SetCursor(NULL);
  746. } else {
  747. if (hCursor != NULL) {
  748. CursorShape c = cursor_shape;
  749. cursor_shape = CURSOR_MAX;
  750. set_cursor_shape(c);
  751. hCursor = NULL;
  752. }
  753. }
  754. }
  755. } break;
  756. case WM_DROPFILES: {
  757. HDROP hDropInfo = (HDROP)wParam;
  758. const int buffsize = 4096;
  759. wchar_t buf[buffsize];
  760. int fcount = DragQueryFileW(hDropInfo, 0xFFFFFFFF, NULL, 0);
  761. Vector<String> files;
  762. for (int i = 0; i < fcount; i++) {
  763. DragQueryFileW(hDropInfo, i, buf, buffsize);
  764. String file = buf;
  765. files.push_back(file);
  766. }
  767. if (files.size() && main_loop) {
  768. main_loop->drop_files(files, 0);
  769. }
  770. } break;
  771. default: {
  772. if (user_proc) {
  773. return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
  774. };
  775. };
  776. }
  777. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  778. }
  779. LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  780. OS_Windows *os_win = static_cast<OS_Windows *>(OS::get_singleton());
  781. if (os_win)
  782. return os_win->WndProc(hWnd, uMsg, wParam, lParam);
  783. else
  784. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  785. }
  786. void OS_Windows::process_key_events() {
  787. for (int i = 0; i < key_event_pos; i++) {
  788. KeyEvent &ke = key_event_buffer[i];
  789. switch (ke.uMsg) {
  790. case WM_CHAR: {
  791. if ((i == 0 && ke.uMsg == WM_CHAR) || (i > 0 && key_event_buffer[i - 1].uMsg == WM_CHAR)) {
  792. Ref<InputEventKey> k;
  793. k.instance();
  794. k->set_shift(ke.shift);
  795. k->set_alt(ke.alt);
  796. k->set_control(ke.control);
  797. k->set_metakey(ke.meta);
  798. k->set_pressed(true);
  799. k->set_scancode(KeyMappingWindows::get_keysym(ke.wParam));
  800. k->set_unicode(ke.wParam);
  801. if (k->get_unicode() && gr_mem) {
  802. k->set_alt(false);
  803. k->set_control(false);
  804. }
  805. if (k->get_unicode() < 32)
  806. k->set_unicode(0);
  807. input->accumulate_input_event(k);
  808. }
  809. //do nothing
  810. } break;
  811. case WM_KEYUP:
  812. case WM_KEYDOWN: {
  813. Ref<InputEventKey> k;
  814. k.instance();
  815. k->set_shift(ke.shift);
  816. k->set_alt(ke.alt);
  817. k->set_control(ke.control);
  818. k->set_metakey(ke.meta);
  819. k->set_pressed(ke.uMsg == WM_KEYDOWN);
  820. if ((ke.lParam & (1 << 24)) && (ke.wParam == VK_RETURN)) {
  821. // Special case for Numpad Enter key
  822. k->set_scancode(KEY_KP_ENTER);
  823. } else {
  824. k->set_scancode(KeyMappingWindows::get_keysym(ke.wParam));
  825. }
  826. if (i + 1 < key_event_pos && key_event_buffer[i + 1].uMsg == WM_CHAR) {
  827. k->set_unicode(key_event_buffer[i + 1].wParam);
  828. }
  829. if (k->get_unicode() && gr_mem) {
  830. k->set_alt(false);
  831. k->set_control(false);
  832. }
  833. if (k->get_unicode() < 32)
  834. k->set_unicode(0);
  835. k->set_echo((ke.uMsg == WM_KEYDOWN && (ke.lParam & (1 << 30))));
  836. input->accumulate_input_event(k);
  837. } break;
  838. }
  839. }
  840. key_event_pos = 0;
  841. }
  842. enum _MonitorDpiType {
  843. MDT_Effective_DPI = 0,
  844. MDT_Angular_DPI = 1,
  845. MDT_Raw_DPI = 2,
  846. MDT_Default = MDT_Effective_DPI
  847. };
  848. static int QueryDpiForMonitor(HMONITOR hmon, _MonitorDpiType dpiType = MDT_Default) {
  849. int dpiX = 96, dpiY = 96;
  850. static HMODULE Shcore = NULL;
  851. typedef HRESULT(WINAPI * GetDPIForMonitor_t)(HMONITOR hmonitor, _MonitorDpiType dpiType, UINT * dpiX, UINT * dpiY);
  852. static GetDPIForMonitor_t getDPIForMonitor = NULL;
  853. if (Shcore == NULL) {
  854. Shcore = LoadLibraryW(L"Shcore.dll");
  855. getDPIForMonitor = Shcore ? (GetDPIForMonitor_t)GetProcAddress(Shcore, "GetDpiForMonitor") : NULL;
  856. if ((Shcore == NULL) || (getDPIForMonitor == NULL)) {
  857. if (Shcore)
  858. FreeLibrary(Shcore);
  859. Shcore = (HMODULE)INVALID_HANDLE_VALUE;
  860. }
  861. }
  862. UINT x = 0, y = 0;
  863. HRESULT hr = E_FAIL;
  864. if (hmon && (Shcore != (HMODULE)INVALID_HANDLE_VALUE)) {
  865. hr = getDPIForMonitor(hmon, dpiType /*MDT_Effective_DPI*/, &x, &y);
  866. if (SUCCEEDED(hr) && (x > 0) && (y > 0)) {
  867. dpiX = (int)x;
  868. dpiY = (int)y;
  869. }
  870. } else {
  871. static int overallX = 0, overallY = 0;
  872. if (overallX <= 0 || overallY <= 0) {
  873. HDC hdc = GetDC(NULL);
  874. if (hdc) {
  875. overallX = GetDeviceCaps(hdc, LOGPIXELSX);
  876. overallY = GetDeviceCaps(hdc, LOGPIXELSY);
  877. ReleaseDC(NULL, hdc);
  878. }
  879. }
  880. if (overallX > 0 && overallY > 0) {
  881. dpiX = overallX;
  882. dpiY = overallY;
  883. }
  884. }
  885. return (dpiX + dpiY) / 2;
  886. }
  887. typedef enum _SHC_PROCESS_DPI_AWARENESS {
  888. SHC_PROCESS_DPI_UNAWARE = 0,
  889. SHC_PROCESS_SYSTEM_DPI_AWARE = 1,
  890. SHC_PROCESS_PER_MONITOR_DPI_AWARE = 2
  891. } SHC_PROCESS_DPI_AWARENESS;
  892. int OS_Windows::get_current_video_driver() const {
  893. return video_driver_index;
  894. }
  895. Error OS_Windows::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  896. main_loop = NULL;
  897. outside = true;
  898. window_has_focus = true;
  899. WNDCLASSEXW wc;
  900. if (is_hidpi_allowed()) {
  901. HMODULE Shcore = LoadLibraryW(L"Shcore.dll");
  902. if (Shcore != NULL) {
  903. typedef HRESULT(WINAPI * SetProcessDpiAwareness_t)(SHC_PROCESS_DPI_AWARENESS);
  904. SetProcessDpiAwareness_t SetProcessDpiAwareness = (SetProcessDpiAwareness_t)GetProcAddress(Shcore, "SetProcessDpiAwareness");
  905. if (SetProcessDpiAwareness) {
  906. SetProcessDpiAwareness(SHC_PROCESS_SYSTEM_DPI_AWARE);
  907. }
  908. }
  909. }
  910. video_mode = p_desired;
  911. //printf("**************** desired %s, mode %s\n", p_desired.fullscreen?"true":"false", video_mode.fullscreen?"true":"false");
  912. RECT WindowRect;
  913. WindowRect.left = 0;
  914. WindowRect.right = video_mode.width;
  915. WindowRect.top = 0;
  916. WindowRect.bottom = video_mode.height;
  917. memset(&wc, 0, sizeof(WNDCLASSEXW));
  918. wc.cbSize = sizeof(WNDCLASSEXW);
  919. wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_DBLCLKS;
  920. wc.lpfnWndProc = (WNDPROC)::WndProc;
  921. wc.cbClsExtra = 0;
  922. wc.cbWndExtra = 0;
  923. //wc.hInstance = hInstance;
  924. wc.hInstance = godot_hinstance ? godot_hinstance : GetModuleHandle(NULL);
  925. wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
  926. wc.hCursor = NULL; //LoadCursor(NULL, IDC_ARROW);
  927. wc.hbrBackground = NULL;
  928. wc.lpszMenuName = NULL;
  929. wc.lpszClassName = L"Engine";
  930. if (!RegisterClassExW(&wc)) {
  931. MessageBox(NULL, "Failed To Register The Window Class.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
  932. return ERR_UNAVAILABLE;
  933. }
  934. use_raw_input = true;
  935. RAWINPUTDEVICE Rid[1];
  936. Rid[0].usUsagePage = 0x01;
  937. Rid[0].usUsage = 0x02;
  938. Rid[0].dwFlags = 0;
  939. Rid[0].hwndTarget = 0;
  940. if (RegisterRawInputDevices(Rid, 1, sizeof(Rid[0])) == FALSE) {
  941. //registration failed.
  942. use_raw_input = false;
  943. }
  944. pre_fs_valid = true;
  945. if (video_mode.fullscreen) {
  946. /* this returns DPI unaware size, commenting
  947. DEVMODE current;
  948. memset(&current, 0, sizeof(current));
  949. EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &current);
  950. WindowRect.right = current.dmPelsWidth;
  951. WindowRect.bottom = current.dmPelsHeight;
  952. */
  953. EnumSizeData data = { 0, 0, Size2() };
  954. EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcSize, (LPARAM)&data);
  955. WindowRect.right = data.size.width;
  956. WindowRect.bottom = data.size.height;
  957. /* DEVMODE dmScreenSettings;
  958. memset(&dmScreenSettings,0,sizeof(dmScreenSettings));
  959. dmScreenSettings.dmSize=sizeof(dmScreenSettings);
  960. dmScreenSettings.dmPelsWidth = video_mode.width;
  961. dmScreenSettings.dmPelsHeight = video_mode.height;
  962. dmScreenSettings.dmBitsPerPel = current.dmBitsPerPel;
  963. dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
  964. LONG err = ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN);
  965. if (err!=DISP_CHANGE_SUCCESSFUL) {
  966. video_mode.fullscreen=false;
  967. }*/
  968. pre_fs_valid = false;
  969. }
  970. DWORD dwExStyle;
  971. DWORD dwStyle;
  972. if (video_mode.fullscreen || video_mode.borderless_window) {
  973. dwExStyle = WS_EX_APPWINDOW;
  974. dwStyle = WS_POPUP;
  975. } else {
  976. dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
  977. dwStyle = WS_OVERLAPPEDWINDOW;
  978. if (!video_mode.resizable) {
  979. dwStyle &= ~WS_THICKFRAME;
  980. dwStyle &= ~WS_MAXIMIZEBOX;
  981. }
  982. }
  983. AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);
  984. char *windowid;
  985. #ifdef MINGW_ENABLED
  986. windowid = getenv("GODOT_WINDOWID");
  987. #else
  988. size_t len;
  989. _dupenv_s(&windowid, &len, "GODOT_WINDOWID");
  990. #endif
  991. if (windowid) {
  992. // strtoull on mingw
  993. #ifdef MINGW_ENABLED
  994. hWnd = (HWND)strtoull(windowid, NULL, 0);
  995. #else
  996. hWnd = (HWND)_strtoui64(windowid, NULL, 0);
  997. #endif
  998. free(windowid);
  999. SetLastError(0);
  1000. user_proc = (WNDPROC)GetWindowLongPtr(hWnd, GWLP_WNDPROC);
  1001. SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)(WNDPROC)::WndProc);
  1002. DWORD le = GetLastError();
  1003. if (user_proc == 0 && le != 0) {
  1004. printf("Error setting WNDPROC: %li\n", le);
  1005. };
  1006. GetWindowLongPtr(hWnd, GWLP_WNDPROC);
  1007. RECT rect;
  1008. if (!GetClientRect(hWnd, &rect)) {
  1009. MessageBoxW(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
  1010. return ERR_UNAVAILABLE;
  1011. };
  1012. video_mode.width = rect.right;
  1013. video_mode.height = rect.bottom;
  1014. video_mode.fullscreen = false;
  1015. } else {
  1016. hWnd = CreateWindowExW(
  1017. dwExStyle,
  1018. L"Engine", L"",
  1019. dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
  1020. (GetSystemMetrics(SM_CXSCREEN) - WindowRect.right) / 2,
  1021. (GetSystemMetrics(SM_CYSCREEN) - WindowRect.bottom) / 2,
  1022. WindowRect.right - WindowRect.left,
  1023. WindowRect.bottom - WindowRect.top,
  1024. NULL, NULL, hInstance, NULL);
  1025. if (!hWnd) {
  1026. MessageBoxW(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
  1027. return ERR_UNAVAILABLE;
  1028. }
  1029. };
  1030. if (video_mode.always_on_top) {
  1031. SetWindowPos(hWnd, video_mode.always_on_top ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
  1032. }
  1033. #if defined(OPENGL_ENABLED)
  1034. bool gles3_context = true;
  1035. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  1036. gles3_context = false;
  1037. }
  1038. bool editor = Engine::get_singleton()->is_editor_hint();
  1039. bool gl_initialization_error = false;
  1040. gl_context = NULL;
  1041. while (!gl_context) {
  1042. gl_context = memnew(ContextGL_Windows(hWnd, gles3_context));
  1043. if (gl_context->initialize() != OK) {
  1044. memdelete(gl_context);
  1045. gl_context = NULL;
  1046. if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2") || editor) {
  1047. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  1048. gl_initialization_error = true;
  1049. break;
  1050. }
  1051. p_video_driver = VIDEO_DRIVER_GLES2;
  1052. gles3_context = false;
  1053. } else {
  1054. gl_initialization_error = true;
  1055. break;
  1056. }
  1057. }
  1058. }
  1059. while (true) {
  1060. if (gles3_context) {
  1061. if (RasterizerGLES3::is_viable() == OK) {
  1062. RasterizerGLES3::register_config();
  1063. RasterizerGLES3::make_current();
  1064. break;
  1065. } else {
  1066. if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2") || editor) {
  1067. p_video_driver = VIDEO_DRIVER_GLES2;
  1068. gles3_context = false;
  1069. continue;
  1070. } else {
  1071. gl_initialization_error = true;
  1072. break;
  1073. }
  1074. }
  1075. } else {
  1076. if (RasterizerGLES2::is_viable() == OK) {
  1077. RasterizerGLES2::register_config();
  1078. RasterizerGLES2::make_current();
  1079. break;
  1080. } else {
  1081. gl_initialization_error = true;
  1082. break;
  1083. }
  1084. }
  1085. }
  1086. if (gl_initialization_error) {
  1087. OS::get_singleton()->alert("Your video card driver does not support any of the supported OpenGL versions.\n"
  1088. "Please update your drivers or if you have a very old or integrated GPU upgrade it.",
  1089. "Unable to initialize Video driver");
  1090. return ERR_UNAVAILABLE;
  1091. }
  1092. video_driver_index = p_video_driver;
  1093. gl_context->set_use_vsync(video_mode.use_vsync);
  1094. #endif
  1095. visual_server = memnew(VisualServerRaster);
  1096. if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {
  1097. visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD));
  1098. }
  1099. visual_server->init();
  1100. input = memnew(InputDefault);
  1101. joypad = memnew(JoypadWindows(input, &hWnd));
  1102. power_manager = memnew(PowerWindows);
  1103. camera_server = memnew(CameraWindows);
  1104. AudioDriverManager::initialize(p_audio_driver);
  1105. TRACKMOUSEEVENT tme;
  1106. tme.cbSize = sizeof(TRACKMOUSEEVENT);
  1107. tme.dwFlags = TME_LEAVE;
  1108. tme.hwndTrack = hWnd;
  1109. tme.dwHoverTime = HOVER_DEFAULT;
  1110. TrackMouseEvent(&tme);
  1111. RegisterTouchWindow(hWnd, 0);
  1112. _ensure_user_data_dir();
  1113. DragAcceptFiles(hWnd, true);
  1114. move_timer_id = 1;
  1115. if (!is_no_window_mode_enabled()) {
  1116. ShowWindow(hWnd, SW_SHOW); // Show The Window
  1117. SetForegroundWindow(hWnd); // Slightly Higher Priority
  1118. SetFocus(hWnd); // Sets Keyboard Focus To
  1119. }
  1120. if (p_desired.layered) {
  1121. set_window_per_pixel_transparency_enabled(true);
  1122. }
  1123. // IME
  1124. im_himc = ImmGetContext(hWnd);
  1125. ImmReleaseContext(hWnd, im_himc);
  1126. im_position = Vector2();
  1127. set_ime_active(false);
  1128. if (!OS::get_singleton()->is_in_low_processor_usage_mode()) {
  1129. //SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
  1130. SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
  1131. DWORD index = 0;
  1132. HANDLE handle = AvSetMmThreadCharacteristics("Games", &index);
  1133. if (handle)
  1134. AvSetMmThreadPriority(handle, AVRT_PRIORITY_CRITICAL);
  1135. // This is needed to make sure that background work does not starve the main thread.
  1136. // This is only setting priority of this thread, not the whole process.
  1137. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  1138. }
  1139. update_real_mouse_position();
  1140. return OK;
  1141. }
  1142. void OS_Windows::set_clipboard(const String &p_text) {
  1143. // Convert LF line endings to CRLF in clipboard content
  1144. // Otherwise, line endings won't be visible when pasted in other software
  1145. String text = p_text.replace("\n", "\r\n");
  1146. if (!OpenClipboard(hWnd)) {
  1147. ERR_FAIL_MSG("Unable to open clipboard.");
  1148. }
  1149. EmptyClipboard();
  1150. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, (text.length() + 1) * sizeof(CharType));
  1151. ERR_FAIL_COND_MSG(mem == NULL, "Unable to allocate memory for clipboard contents.");
  1152. LPWSTR lptstrCopy = (LPWSTR)GlobalLock(mem);
  1153. memcpy(lptstrCopy, text.c_str(), (text.length() + 1) * sizeof(CharType));
  1154. GlobalUnlock(mem);
  1155. SetClipboardData(CF_UNICODETEXT, mem);
  1156. // set the CF_TEXT version (not needed?)
  1157. CharString utf8 = text.utf8();
  1158. mem = GlobalAlloc(GMEM_MOVEABLE, utf8.length() + 1);
  1159. ERR_FAIL_COND_MSG(mem == NULL, "Unable to allocate memory for clipboard contents.");
  1160. LPTSTR ptr = (LPTSTR)GlobalLock(mem);
  1161. memcpy(ptr, utf8.get_data(), utf8.length());
  1162. ptr[utf8.length()] = 0;
  1163. GlobalUnlock(mem);
  1164. SetClipboardData(CF_TEXT, mem);
  1165. CloseClipboard();
  1166. };
  1167. String OS_Windows::get_clipboard() const {
  1168. String ret;
  1169. if (!OpenClipboard(hWnd)) {
  1170. ERR_FAIL_V_MSG("", "Unable to open clipboard.");
  1171. };
  1172. if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
  1173. HGLOBAL mem = GetClipboardData(CF_UNICODETEXT);
  1174. if (mem != NULL) {
  1175. LPWSTR ptr = (LPWSTR)GlobalLock(mem);
  1176. if (ptr != NULL) {
  1177. ret = String((CharType *)ptr);
  1178. GlobalUnlock(mem);
  1179. };
  1180. };
  1181. } else if (IsClipboardFormatAvailable(CF_TEXT)) {
  1182. HGLOBAL mem = GetClipboardData(CF_UNICODETEXT);
  1183. if (mem != NULL) {
  1184. LPTSTR ptr = (LPTSTR)GlobalLock(mem);
  1185. if (ptr != NULL) {
  1186. ret.parse_utf8((const char *)ptr);
  1187. GlobalUnlock(mem);
  1188. };
  1189. };
  1190. };
  1191. CloseClipboard();
  1192. return ret;
  1193. };
  1194. void OS_Windows::delete_main_loop() {
  1195. if (main_loop)
  1196. memdelete(main_loop);
  1197. main_loop = NULL;
  1198. }
  1199. void OS_Windows::set_main_loop(MainLoop *p_main_loop) {
  1200. input->set_main_loop(p_main_loop);
  1201. main_loop = p_main_loop;
  1202. }
  1203. void OS_Windows::finalize() {
  1204. #ifdef WINMIDI_ENABLED
  1205. driver_midi.close();
  1206. #endif
  1207. if (main_loop)
  1208. memdelete(main_loop);
  1209. main_loop = NULL;
  1210. memdelete(joypad);
  1211. memdelete(input);
  1212. memdelete(camera_server);
  1213. touch_state.clear();
  1214. cursors_cache.clear();
  1215. visual_server->finish();
  1216. memdelete(visual_server);
  1217. #ifdef OPENGL_ENABLED
  1218. if (gl_context)
  1219. memdelete(gl_context);
  1220. #endif
  1221. if (user_proc) {
  1222. SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)user_proc);
  1223. };
  1224. }
  1225. void OS_Windows::finalize_core() {
  1226. timeEndPeriod(1);
  1227. memdelete(process_map);
  1228. NetSocketPosix::cleanup();
  1229. }
  1230. void OS_Windows::alert(const String &p_alert, const String &p_title) {
  1231. if (!is_no_window_mode_enabled())
  1232. MessageBoxW(NULL, p_alert.c_str(), p_title.c_str(), MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
  1233. else
  1234. print_line("ALERT: " + p_alert);
  1235. }
  1236. void OS_Windows::set_mouse_mode(MouseMode p_mode) {
  1237. if (mouse_mode == p_mode)
  1238. return;
  1239. _set_mouse_mode_impl(p_mode);
  1240. mouse_mode = p_mode;
  1241. }
  1242. void OS_Windows::_set_mouse_mode_impl(MouseMode p_mode) {
  1243. if (p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_CONFINED) {
  1244. RECT clipRect;
  1245. GetClientRect(hWnd, &clipRect);
  1246. ClientToScreen(hWnd, (POINT *)&clipRect.left);
  1247. ClientToScreen(hWnd, (POINT *)&clipRect.right);
  1248. ClipCursor(&clipRect);
  1249. if (p_mode == MOUSE_MODE_CAPTURED) {
  1250. center = Point2i(video_mode.width / 2, video_mode.height / 2);
  1251. POINT pos = { (int)center.x, (int)center.y };
  1252. ClientToScreen(hWnd, &pos);
  1253. SetCursorPos(pos.x, pos.y);
  1254. SetCapture(hWnd);
  1255. }
  1256. } else {
  1257. ReleaseCapture();
  1258. ClipCursor(NULL);
  1259. }
  1260. if (p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_HIDDEN) {
  1261. hCursor = SetCursor(NULL);
  1262. } else {
  1263. CursorShape c = cursor_shape;
  1264. cursor_shape = CURSOR_MAX;
  1265. set_cursor_shape(c);
  1266. }
  1267. }
  1268. OS_Windows::MouseMode OS_Windows::get_mouse_mode() const {
  1269. return mouse_mode;
  1270. }
  1271. void OS_Windows::warp_mouse_position(const Point2 &p_to) {
  1272. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  1273. old_x = p_to.x;
  1274. old_y = p_to.y;
  1275. } else {
  1276. POINT p;
  1277. p.x = p_to.x;
  1278. p.y = p_to.y;
  1279. ClientToScreen(hWnd, &p);
  1280. SetCursorPos(p.x, p.y);
  1281. }
  1282. }
  1283. Point2 OS_Windows::get_mouse_position() const {
  1284. return Point2(old_x, old_y);
  1285. }
  1286. void OS_Windows::update_real_mouse_position() {
  1287. POINT mouse_pos;
  1288. if (GetCursorPos(&mouse_pos) && ScreenToClient(hWnd, &mouse_pos)) {
  1289. if (mouse_pos.x > 0 && mouse_pos.y > 0 && mouse_pos.x <= video_mode.width && mouse_pos.y <= video_mode.height) {
  1290. old_x = mouse_pos.x;
  1291. old_y = mouse_pos.y;
  1292. old_invalid = false;
  1293. input->set_mouse_position(Point2i(mouse_pos.x, mouse_pos.y));
  1294. }
  1295. }
  1296. }
  1297. int OS_Windows::get_mouse_button_state() const {
  1298. return last_button_state;
  1299. }
  1300. void OS_Windows::set_window_title(const String &p_title) {
  1301. SetWindowTextW(hWnd, p_title.c_str());
  1302. }
  1303. void OS_Windows::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  1304. }
  1305. OS::VideoMode OS_Windows::get_video_mode(int p_screen) const {
  1306. return video_mode;
  1307. }
  1308. void OS_Windows::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  1309. }
  1310. static BOOL CALLBACK _MonitorEnumProcCount(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1311. int *data = (int *)dwData;
  1312. (*data)++;
  1313. return TRUE;
  1314. }
  1315. int OS_Windows::get_screen_count() const {
  1316. int data = 0;
  1317. EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcCount, (LPARAM)&data);
  1318. return data;
  1319. }
  1320. typedef struct {
  1321. int count;
  1322. int screen;
  1323. HMONITOR monitor;
  1324. } EnumScreenData;
  1325. static BOOL CALLBACK _MonitorEnumProcScreen(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1326. EnumScreenData *data = (EnumScreenData *)dwData;
  1327. if (data->monitor == hMonitor) {
  1328. data->screen = data->count;
  1329. }
  1330. data->count++;
  1331. return TRUE;
  1332. }
  1333. int OS_Windows::get_current_screen() const {
  1334. EnumScreenData data = { 0, 0, MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST) };
  1335. EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcScreen, (LPARAM)&data);
  1336. return data.screen;
  1337. }
  1338. void OS_Windows::set_current_screen(int p_screen) {
  1339. Vector2 ofs = get_window_position() - get_screen_position(get_current_screen());
  1340. set_window_position(ofs + get_screen_position(p_screen));
  1341. }
  1342. static BOOL CALLBACK _MonitorEnumProcPos(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1343. EnumPosData *data = (EnumPosData *)dwData;
  1344. if (data->count == data->screen) {
  1345. data->pos.x = lprcMonitor->left;
  1346. data->pos.y = lprcMonitor->top;
  1347. }
  1348. data->count++;
  1349. return TRUE;
  1350. }
  1351. Point2 OS_Windows::get_screen_position(int p_screen) const {
  1352. EnumPosData data = { 0, p_screen == -1 ? get_current_screen() : p_screen, Point2() };
  1353. EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcPos, (LPARAM)&data);
  1354. return data.pos;
  1355. }
  1356. Size2 OS_Windows::get_screen_size(int p_screen) const {
  1357. EnumSizeData data = { 0, p_screen == -1 ? get_current_screen() : p_screen, Size2() };
  1358. EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcSize, (LPARAM)&data);
  1359. return data.size;
  1360. }
  1361. typedef struct {
  1362. int count;
  1363. int screen;
  1364. int dpi;
  1365. } EnumDpiData;
  1366. static BOOL CALLBACK _MonitorEnumProcDpi(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1367. EnumDpiData *data = (EnumDpiData *)dwData;
  1368. if (data->count == data->screen) {
  1369. data->dpi = QueryDpiForMonitor(hMonitor);
  1370. }
  1371. data->count++;
  1372. return TRUE;
  1373. }
  1374. int OS_Windows::get_screen_dpi(int p_screen) const {
  1375. EnumDpiData data = { 0, p_screen == -1 ? get_current_screen() : p_screen, 72 };
  1376. EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcDpi, (LPARAM)&data);
  1377. return data.dpi;
  1378. }
  1379. Point2 OS_Windows::get_window_position() const {
  1380. if (minimized) {
  1381. return last_pos;
  1382. }
  1383. RECT r;
  1384. GetWindowRect(hWnd, &r);
  1385. return Point2(r.left, r.top);
  1386. }
  1387. void OS_Windows::set_window_position(const Point2 &p_position) {
  1388. if (video_mode.fullscreen) return;
  1389. RECT r;
  1390. GetWindowRect(hWnd, &r);
  1391. MoveWindow(hWnd, p_position.x, p_position.y, r.right - r.left, r.bottom - r.top, TRUE);
  1392. // Don't let the mouse leave the window when moved
  1393. if (mouse_mode == MOUSE_MODE_CONFINED) {
  1394. RECT rect;
  1395. GetClientRect(hWnd, &rect);
  1396. ClientToScreen(hWnd, (POINT *)&rect.left);
  1397. ClientToScreen(hWnd, (POINT *)&rect.right);
  1398. ClipCursor(&rect);
  1399. }
  1400. last_pos = p_position;
  1401. update_real_mouse_position();
  1402. }
  1403. Size2 OS_Windows::get_window_size() const {
  1404. if (minimized) {
  1405. return Size2(video_mode.width, video_mode.height);
  1406. }
  1407. RECT r;
  1408. if (GetClientRect(hWnd, &r)) { // Only area inside of window border
  1409. return Size2(r.right - r.left, r.bottom - r.top);
  1410. }
  1411. return Size2();
  1412. }
  1413. Size2 OS_Windows::get_max_window_size() const {
  1414. return max_size;
  1415. }
  1416. Size2 OS_Windows::get_min_window_size() const {
  1417. return min_size;
  1418. }
  1419. void OS_Windows::set_min_window_size(const Size2 p_size) {
  1420. if ((p_size != Size2()) && (max_size != Size2()) && ((p_size.x > max_size.x) || (p_size.y > max_size.y))) {
  1421. ERR_PRINT("Minimum window size can't be larger than maximum window size!");
  1422. return;
  1423. }
  1424. min_size = p_size;
  1425. }
  1426. void OS_Windows::set_max_window_size(const Size2 p_size) {
  1427. if ((p_size != Size2()) && ((p_size.x < min_size.x) || (p_size.y < min_size.y))) {
  1428. ERR_PRINT("Maximum window size can't be smaller than minimum window size!");
  1429. return;
  1430. }
  1431. max_size = p_size;
  1432. }
  1433. Size2 OS_Windows::get_real_window_size() const {
  1434. RECT r;
  1435. if (GetWindowRect(hWnd, &r)) { // Includes area of the window border
  1436. return Size2(r.right - r.left, r.bottom - r.top);
  1437. }
  1438. return Size2();
  1439. }
  1440. void OS_Windows::set_window_size(const Size2 p_size) {
  1441. int w = p_size.width;
  1442. int h = p_size.height;
  1443. video_mode.width = w;
  1444. video_mode.height = h;
  1445. if (video_mode.fullscreen) {
  1446. return;
  1447. }
  1448. RECT rect;
  1449. GetWindowRect(hWnd, &rect);
  1450. if (!video_mode.borderless_window) {
  1451. RECT crect;
  1452. GetClientRect(hWnd, &crect);
  1453. w += (rect.right - rect.left) - (crect.right - crect.left);
  1454. h += (rect.bottom - rect.top) - (crect.bottom - crect.top);
  1455. }
  1456. MoveWindow(hWnd, rect.left, rect.top, w, h, TRUE);
  1457. // Don't let the mouse leave the window when resizing to a smaller resolution
  1458. if (mouse_mode == MOUSE_MODE_CONFINED) {
  1459. RECT crect;
  1460. GetClientRect(hWnd, &crect);
  1461. ClientToScreen(hWnd, (POINT *)&crect.left);
  1462. ClientToScreen(hWnd, (POINT *)&crect.right);
  1463. ClipCursor(&crect);
  1464. }
  1465. }
  1466. void OS_Windows::set_window_fullscreen(bool p_enabled) {
  1467. if (video_mode.fullscreen == p_enabled)
  1468. return;
  1469. if (layered_window)
  1470. set_window_per_pixel_transparency_enabled(false);
  1471. if (p_enabled) {
  1472. if (pre_fs_valid) {
  1473. GetWindowRect(hWnd, &pre_fs_rect);
  1474. }
  1475. int cs = get_current_screen();
  1476. Point2 pos = get_screen_position(cs);
  1477. Size2 size = get_screen_size(cs);
  1478. video_mode.fullscreen = true;
  1479. _update_window_style(false);
  1480. MoveWindow(hWnd, pos.x, pos.y, size.width, size.height, TRUE);
  1481. } else {
  1482. RECT rect;
  1483. video_mode.fullscreen = false;
  1484. if (pre_fs_valid) {
  1485. rect = pre_fs_rect;
  1486. } else {
  1487. rect.left = 0;
  1488. rect.right = video_mode.width;
  1489. rect.top = 0;
  1490. rect.bottom = video_mode.height;
  1491. }
  1492. _update_window_style(false);
  1493. MoveWindow(hWnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
  1494. pre_fs_valid = true;
  1495. }
  1496. }
  1497. bool OS_Windows::is_window_fullscreen() const {
  1498. return video_mode.fullscreen;
  1499. }
  1500. void OS_Windows::set_window_resizable(bool p_enabled) {
  1501. if (video_mode.resizable == p_enabled)
  1502. return;
  1503. video_mode.resizable = p_enabled;
  1504. _update_window_style();
  1505. }
  1506. bool OS_Windows::is_window_resizable() const {
  1507. return video_mode.resizable;
  1508. }
  1509. void OS_Windows::set_window_minimized(bool p_enabled) {
  1510. if (p_enabled) {
  1511. maximized = false;
  1512. minimized = true;
  1513. ShowWindow(hWnd, SW_MINIMIZE);
  1514. } else {
  1515. ShowWindow(hWnd, SW_RESTORE);
  1516. maximized = false;
  1517. minimized = false;
  1518. }
  1519. }
  1520. bool OS_Windows::is_window_minimized() const {
  1521. return minimized;
  1522. }
  1523. void OS_Windows::set_window_maximized(bool p_enabled) {
  1524. if (p_enabled) {
  1525. maximized = true;
  1526. minimized = false;
  1527. ShowWindow(hWnd, SW_MAXIMIZE);
  1528. } else {
  1529. ShowWindow(hWnd, SW_RESTORE);
  1530. maximized = false;
  1531. minimized = false;
  1532. }
  1533. }
  1534. bool OS_Windows::is_window_maximized() const {
  1535. return maximized;
  1536. }
  1537. void OS_Windows::set_window_always_on_top(bool p_enabled) {
  1538. if (video_mode.always_on_top == p_enabled)
  1539. return;
  1540. video_mode.always_on_top = p_enabled;
  1541. _update_window_style();
  1542. }
  1543. bool OS_Windows::is_window_always_on_top() const {
  1544. return video_mode.always_on_top;
  1545. }
  1546. void OS_Windows::set_console_visible(bool p_enabled) {
  1547. if (console_visible == p_enabled)
  1548. return;
  1549. ShowWindow(GetConsoleWindow(), p_enabled ? SW_SHOW : SW_HIDE);
  1550. console_visible = p_enabled;
  1551. }
  1552. bool OS_Windows::is_console_visible() const {
  1553. return console_visible;
  1554. }
  1555. bool OS_Windows::get_window_per_pixel_transparency_enabled() const {
  1556. if (!is_layered_allowed()) return false;
  1557. return layered_window;
  1558. }
  1559. void OS_Windows::set_window_per_pixel_transparency_enabled(bool p_enabled) {
  1560. if (!is_layered_allowed()) return;
  1561. if (layered_window != p_enabled) {
  1562. if (p_enabled) {
  1563. set_borderless_window(true);
  1564. //enable per-pixel alpha
  1565. hDC_dib = CreateCompatibleDC(GetDC(hWnd));
  1566. SetWindowLong(hWnd, GWL_EXSTYLE, GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  1567. RECT r;
  1568. GetWindowRect(hWnd, &r);
  1569. dib_size = Size2(r.right - r.left, r.bottom - r.top);
  1570. BITMAPINFO bmi;
  1571. ZeroMemory(&bmi, sizeof(BITMAPINFO));
  1572. bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
  1573. bmi.bmiHeader.biWidth = dib_size.x;
  1574. bmi.bmiHeader.biHeight = dib_size.y;
  1575. bmi.bmiHeader.biPlanes = 1;
  1576. bmi.bmiHeader.biBitCount = 32;
  1577. bmi.bmiHeader.biCompression = BI_RGB;
  1578. bmi.bmiHeader.biSizeImage = dib_size.x * dib_size.y * 4;
  1579. hBitmap = CreateDIBSection(hDC_dib, &bmi, DIB_RGB_COLORS, (void **)&dib_data, NULL, 0x0);
  1580. SelectObject(hDC_dib, hBitmap);
  1581. ZeroMemory(dib_data, dib_size.x * dib_size.y * 4);
  1582. layered_window = true;
  1583. } else {
  1584. //disable per-pixel alpha
  1585. layered_window = false;
  1586. SetWindowLong(hWnd, GWL_EXSTYLE, GetWindowLong(hWnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  1587. //cleanup
  1588. DeleteObject(hBitmap);
  1589. DeleteDC(hDC_dib);
  1590. }
  1591. }
  1592. }
  1593. uint8_t *OS_Windows::get_layered_buffer_data() {
  1594. return (is_layered_allowed() && layered_window) ? dib_data : NULL;
  1595. }
  1596. Size2 OS_Windows::get_layered_buffer_size() {
  1597. return (is_layered_allowed() && layered_window) ? dib_size : Size2();
  1598. }
  1599. void OS_Windows::swap_layered_buffer() {
  1600. if (is_layered_allowed() && layered_window) {
  1601. //premultiply alpha
  1602. for (int y = 0; y < dib_size.y; y++) {
  1603. for (int x = 0; x < dib_size.x; x++) {
  1604. float alpha = (float)dib_data[y * (int)dib_size.x * 4 + x * 4 + 3] / (float)0xFF;
  1605. dib_data[y * (int)dib_size.x * 4 + x * 4 + 0] *= alpha;
  1606. dib_data[y * (int)dib_size.x * 4 + x * 4 + 1] *= alpha;
  1607. dib_data[y * (int)dib_size.x * 4 + x * 4 + 2] *= alpha;
  1608. }
  1609. }
  1610. //swap layered window buffer
  1611. POINT ptSrc = { 0, 0 };
  1612. SIZE sizeWnd = { (long)dib_size.x, (long)dib_size.y };
  1613. BLENDFUNCTION bf;
  1614. bf.BlendOp = AC_SRC_OVER;
  1615. bf.BlendFlags = 0;
  1616. bf.AlphaFormat = AC_SRC_ALPHA;
  1617. bf.SourceConstantAlpha = 0xFF;
  1618. UpdateLayeredWindow(hWnd, NULL, NULL, &sizeWnd, hDC_dib, &ptSrc, 0, &bf, ULW_ALPHA);
  1619. }
  1620. }
  1621. void OS_Windows::set_borderless_window(bool p_borderless) {
  1622. if (video_mode.borderless_window == p_borderless)
  1623. return;
  1624. if (!p_borderless && layered_window)
  1625. set_window_per_pixel_transparency_enabled(false);
  1626. video_mode.borderless_window = p_borderless;
  1627. preserve_window_size = true;
  1628. _update_window_style();
  1629. }
  1630. bool OS_Windows::get_borderless_window() {
  1631. return video_mode.borderless_window;
  1632. }
  1633. void OS_Windows::_update_window_style(bool repaint) {
  1634. if (video_mode.fullscreen || video_mode.borderless_window) {
  1635. SetWindowLongPtr(hWnd, GWL_STYLE, WS_SYSMENU | WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE);
  1636. } else {
  1637. if (video_mode.resizable) {
  1638. SetWindowLongPtr(hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE);
  1639. } else {
  1640. SetWindowLongPtr(hWnd, GWL_STYLE, WS_CAPTION | WS_MINIMIZEBOX | WS_POPUPWINDOW | WS_VISIBLE);
  1641. }
  1642. }
  1643. SetWindowPos(hWnd, video_mode.always_on_top ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE);
  1644. if (repaint) {
  1645. RECT rect;
  1646. GetWindowRect(hWnd, &rect);
  1647. MoveWindow(hWnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
  1648. }
  1649. }
  1650. Error OS_Windows::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  1651. String path = p_path;
  1652. if (!FileAccess::exists(path)) {
  1653. //this code exists so gdnative can load .dll files from within the executable path
  1654. path = get_executable_path().get_base_dir().plus_file(p_path.get_file());
  1655. }
  1656. typedef DLL_DIRECTORY_COOKIE(WINAPI * PAddDllDirectory)(PCWSTR);
  1657. typedef BOOL(WINAPI * PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE);
  1658. PAddDllDirectory add_dll_directory = (PAddDllDirectory)GetProcAddress(GetModuleHandle("kernel32.dll"), "AddDllDirectory");
  1659. PRemoveDllDirectory remove_dll_directory = (PRemoveDllDirectory)GetProcAddress(GetModuleHandle("kernel32.dll"), "RemoveDllDirectory");
  1660. bool has_dll_directory_api = ((add_dll_directory != NULL) && (remove_dll_directory != NULL));
  1661. DLL_DIRECTORY_COOKIE cookie = NULL;
  1662. if (p_also_set_library_path && has_dll_directory_api) {
  1663. cookie = add_dll_directory(path.get_base_dir().c_str());
  1664. }
  1665. p_library_handle = (void *)LoadLibraryExW(path.c_str(), NULL, (p_also_set_library_path && has_dll_directory_api) ? LOAD_LIBRARY_SEARCH_DEFAULT_DIRS : 0);
  1666. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ", error: " + format_error_message(GetLastError()) + ".");
  1667. if (cookie) {
  1668. remove_dll_directory(cookie);
  1669. }
  1670. return OK;
  1671. }
  1672. Error OS_Windows::close_dynamic_library(void *p_library_handle) {
  1673. if (!FreeLibrary((HMODULE)p_library_handle)) {
  1674. return FAILED;
  1675. }
  1676. return OK;
  1677. }
  1678. Error OS_Windows::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  1679. p_symbol_handle = (void *)GetProcAddress((HMODULE)p_library_handle, p_name.utf8().get_data());
  1680. if (!p_symbol_handle) {
  1681. if (!p_optional) {
  1682. ERR_FAIL_V_MSG(ERR_CANT_RESOLVE, "Can't resolve symbol " + p_name + ", error: " + String::num(GetLastError()) + ".");
  1683. } else {
  1684. return ERR_CANT_RESOLVE;
  1685. }
  1686. }
  1687. return OK;
  1688. }
  1689. void OS_Windows::request_attention() {
  1690. FLASHWINFO info;
  1691. info.cbSize = sizeof(FLASHWINFO);
  1692. info.hwnd = hWnd;
  1693. info.dwFlags = FLASHW_TRAY;
  1694. info.dwTimeout = 0;
  1695. info.uCount = 2;
  1696. FlashWindowEx(&info);
  1697. }
  1698. String OS_Windows::get_name() const {
  1699. return "Windows";
  1700. }
  1701. OS::Date OS_Windows::get_date(bool utc) const {
  1702. SYSTEMTIME systemtime;
  1703. if (utc)
  1704. GetSystemTime(&systemtime);
  1705. else
  1706. GetLocalTime(&systemtime);
  1707. Date date;
  1708. date.day = systemtime.wDay;
  1709. date.month = Month(systemtime.wMonth);
  1710. date.weekday = Weekday(systemtime.wDayOfWeek);
  1711. date.year = systemtime.wYear;
  1712. date.dst = false;
  1713. return date;
  1714. }
  1715. OS::Time OS_Windows::get_time(bool utc) const {
  1716. SYSTEMTIME systemtime;
  1717. if (utc)
  1718. GetSystemTime(&systemtime);
  1719. else
  1720. GetLocalTime(&systemtime);
  1721. Time time;
  1722. time.hour = systemtime.wHour;
  1723. time.min = systemtime.wMinute;
  1724. time.sec = systemtime.wSecond;
  1725. return time;
  1726. }
  1727. OS::TimeZoneInfo OS_Windows::get_time_zone_info() const {
  1728. TIME_ZONE_INFORMATION info;
  1729. bool daylight = false;
  1730. if (GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT)
  1731. daylight = true;
  1732. TimeZoneInfo ret;
  1733. if (daylight) {
  1734. ret.name = info.DaylightName;
  1735. } else {
  1736. ret.name = info.StandardName;
  1737. }
  1738. // Bias value returned by GetTimeZoneInformation is inverted of what we expect
  1739. // For example on GMT-3 GetTimeZoneInformation return a Bias of 180, so invert the value to get -180
  1740. ret.bias = -info.Bias;
  1741. return ret;
  1742. }
  1743. uint64_t OS_Windows::get_unix_time() const {
  1744. FILETIME ft;
  1745. SYSTEMTIME st;
  1746. GetSystemTime(&st);
  1747. SystemTimeToFileTime(&st, &ft);
  1748. SYSTEMTIME ep;
  1749. ep.wYear = 1970;
  1750. ep.wMonth = 1;
  1751. ep.wDayOfWeek = 4;
  1752. ep.wDay = 1;
  1753. ep.wHour = 0;
  1754. ep.wMinute = 0;
  1755. ep.wSecond = 0;
  1756. ep.wMilliseconds = 0;
  1757. FILETIME fep;
  1758. SystemTimeToFileTime(&ep, &fep);
  1759. // Type punning through unions (rather than pointer cast) as per:
  1760. // https://docs.microsoft.com/en-us/windows/desktop/api/minwinbase/ns-minwinbase-filetime#remarks
  1761. ULARGE_INTEGER ft_punning;
  1762. ft_punning.LowPart = ft.dwLowDateTime;
  1763. ft_punning.HighPart = ft.dwHighDateTime;
  1764. ULARGE_INTEGER fep_punning;
  1765. fep_punning.LowPart = fep.dwLowDateTime;
  1766. fep_punning.HighPart = fep.dwHighDateTime;
  1767. return (ft_punning.QuadPart - fep_punning.QuadPart) / 10000000;
  1768. };
  1769. uint64_t OS_Windows::get_system_time_secs() const {
  1770. return get_system_time_msecs() / 1000;
  1771. }
  1772. uint64_t OS_Windows::get_system_time_msecs() const {
  1773. const uint64_t WINDOWS_TICK = 10000;
  1774. const uint64_t MSEC_TO_UNIX_EPOCH = 11644473600000LL;
  1775. SYSTEMTIME st;
  1776. GetSystemTime(&st);
  1777. FILETIME ft;
  1778. SystemTimeToFileTime(&st, &ft);
  1779. uint64_t ret;
  1780. ret = ft.dwHighDateTime;
  1781. ret <<= 32;
  1782. ret |= ft.dwLowDateTime;
  1783. return (uint64_t)(ret / WINDOWS_TICK - MSEC_TO_UNIX_EPOCH);
  1784. }
  1785. void OS_Windows::delay_usec(uint32_t p_usec) const {
  1786. if (p_usec < 1000)
  1787. Sleep(1);
  1788. else
  1789. Sleep(p_usec / 1000);
  1790. }
  1791. uint64_t OS_Windows::get_ticks_usec() const {
  1792. uint64_t ticks;
  1793. uint64_t time;
  1794. // This is the number of clock ticks since start
  1795. if (!QueryPerformanceCounter((LARGE_INTEGER *)&ticks))
  1796. ticks = (UINT64)timeGetTime();
  1797. // Divide by frequency to get the time in seconds
  1798. time = ticks * 1000000L / ticks_per_second;
  1799. // Subtract the time at game start to get
  1800. // the time since the game started
  1801. time -= ticks_start;
  1802. return time;
  1803. }
  1804. void OS_Windows::process_events() {
  1805. MSG msg;
  1806. if (!drop_events) {
  1807. joypad->process_joypads();
  1808. }
  1809. while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
  1810. TranslateMessage(&msg);
  1811. DispatchMessageW(&msg);
  1812. }
  1813. if (!drop_events) {
  1814. process_key_events();
  1815. input->flush_accumulated_events();
  1816. }
  1817. }
  1818. void OS_Windows::set_cursor_shape(CursorShape p_shape) {
  1819. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  1820. if (cursor_shape == p_shape)
  1821. return;
  1822. if (mouse_mode != MOUSE_MODE_VISIBLE && mouse_mode != MOUSE_MODE_CONFINED) {
  1823. cursor_shape = p_shape;
  1824. return;
  1825. }
  1826. static const LPCTSTR win_cursors[CURSOR_MAX] = {
  1827. IDC_ARROW,
  1828. IDC_IBEAM,
  1829. IDC_HAND, //finger
  1830. IDC_CROSS,
  1831. IDC_WAIT,
  1832. IDC_APPSTARTING,
  1833. IDC_ARROW,
  1834. IDC_ARROW,
  1835. IDC_NO,
  1836. IDC_SIZENS,
  1837. IDC_SIZEWE,
  1838. IDC_SIZENESW,
  1839. IDC_SIZENWSE,
  1840. IDC_SIZEALL,
  1841. IDC_SIZENS,
  1842. IDC_SIZEWE,
  1843. IDC_HELP
  1844. };
  1845. if (cursors[p_shape] != NULL) {
  1846. SetCursor(cursors[p_shape]);
  1847. } else {
  1848. SetCursor(LoadCursor(hInstance, win_cursors[p_shape]));
  1849. }
  1850. cursor_shape = p_shape;
  1851. }
  1852. OS::CursorShape OS_Windows::get_cursor_shape() const {
  1853. return cursor_shape;
  1854. }
  1855. void OS_Windows::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  1856. if (p_cursor.is_valid()) {
  1857. Map<CursorShape, Vector<Variant> >::Element *cursor_c = cursors_cache.find(p_shape);
  1858. if (cursor_c) {
  1859. if (cursor_c->get()[0] == p_cursor && cursor_c->get()[1] == p_hotspot) {
  1860. set_cursor_shape(p_shape);
  1861. return;
  1862. }
  1863. cursors_cache.erase(p_shape);
  1864. }
  1865. Ref<Texture> texture = p_cursor;
  1866. Ref<AtlasTexture> atlas_texture = p_cursor;
  1867. Ref<Image> image;
  1868. Size2 texture_size;
  1869. Rect2 atlas_rect;
  1870. if (texture.is_valid()) {
  1871. image = texture->get_data();
  1872. }
  1873. if (!image.is_valid() && atlas_texture.is_valid()) {
  1874. texture = atlas_texture->get_atlas();
  1875. atlas_rect.size.width = texture->get_width();
  1876. atlas_rect.size.height = texture->get_height();
  1877. atlas_rect.position.x = atlas_texture->get_region().position.x;
  1878. atlas_rect.position.y = atlas_texture->get_region().position.y;
  1879. texture_size.width = atlas_texture->get_region().size.x;
  1880. texture_size.height = atlas_texture->get_region().size.y;
  1881. } else if (image.is_valid()) {
  1882. texture_size.width = texture->get_width();
  1883. texture_size.height = texture->get_height();
  1884. }
  1885. ERR_FAIL_COND(!texture.is_valid());
  1886. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  1887. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  1888. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  1889. image = texture->get_data();
  1890. ERR_FAIL_COND(!image.is_valid());
  1891. UINT image_size = texture_size.width * texture_size.height;
  1892. // Create the BITMAP with alpha channel
  1893. COLORREF *buffer = (COLORREF *)memalloc(sizeof(COLORREF) * image_size);
  1894. image->lock();
  1895. for (UINT index = 0; index < image_size; index++) {
  1896. int row_index = floor(index / texture_size.width) + atlas_rect.position.y;
  1897. int column_index = (index % int(texture_size.width)) + atlas_rect.position.x;
  1898. if (atlas_texture.is_valid()) {
  1899. column_index = MIN(column_index, atlas_rect.size.width - 1);
  1900. row_index = MIN(row_index, atlas_rect.size.height - 1);
  1901. }
  1902. *(buffer + index) = image->get_pixel(column_index, row_index).to_argb32();
  1903. }
  1904. image->unlock();
  1905. // Using 4 channels, so 4 * 8 bits
  1906. HBITMAP bitmap = CreateBitmap(texture_size.width, texture_size.height, 1, 4 * 8, buffer);
  1907. COLORREF clrTransparent = -1;
  1908. // Create the AND and XOR masks for the bitmap
  1909. HBITMAP hAndMask = NULL;
  1910. HBITMAP hXorMask = NULL;
  1911. GetMaskBitmaps(bitmap, clrTransparent, hAndMask, hXorMask);
  1912. if (NULL == hAndMask || NULL == hXorMask) {
  1913. memfree(buffer);
  1914. DeleteObject(bitmap);
  1915. return;
  1916. }
  1917. // Finally, create the icon
  1918. ICONINFO iconinfo;
  1919. iconinfo.fIcon = FALSE;
  1920. iconinfo.xHotspot = p_hotspot.x;
  1921. iconinfo.yHotspot = p_hotspot.y;
  1922. iconinfo.hbmMask = hAndMask;
  1923. iconinfo.hbmColor = hXorMask;
  1924. if (cursors[p_shape])
  1925. DestroyIcon(cursors[p_shape]);
  1926. cursors[p_shape] = CreateIconIndirect(&iconinfo);
  1927. Vector<Variant> params;
  1928. params.push_back(p_cursor);
  1929. params.push_back(p_hotspot);
  1930. cursors_cache.insert(p_shape, params);
  1931. if (p_shape == cursor_shape) {
  1932. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  1933. SetCursor(cursors[p_shape]);
  1934. }
  1935. }
  1936. if (hAndMask != NULL) {
  1937. DeleteObject(hAndMask);
  1938. }
  1939. if (hXorMask != NULL) {
  1940. DeleteObject(hXorMask);
  1941. }
  1942. memfree(buffer);
  1943. DeleteObject(bitmap);
  1944. } else {
  1945. // Reset to default system cursor
  1946. if (cursors[p_shape]) {
  1947. DestroyIcon(cursors[p_shape]);
  1948. cursors[p_shape] = NULL;
  1949. }
  1950. CursorShape c = cursor_shape;
  1951. cursor_shape = CURSOR_MAX;
  1952. set_cursor_shape(c);
  1953. cursors_cache.erase(p_shape);
  1954. }
  1955. }
  1956. void OS_Windows::GetMaskBitmaps(HBITMAP hSourceBitmap, COLORREF clrTransparent, OUT HBITMAP &hAndMaskBitmap, OUT HBITMAP &hXorMaskBitmap) {
  1957. // Get the system display DC
  1958. HDC hDC = GetDC(NULL);
  1959. // Create helper DC
  1960. HDC hMainDC = CreateCompatibleDC(hDC);
  1961. HDC hAndMaskDC = CreateCompatibleDC(hDC);
  1962. HDC hXorMaskDC = CreateCompatibleDC(hDC);
  1963. // Get the dimensions of the source bitmap
  1964. BITMAP bm;
  1965. GetObject(hSourceBitmap, sizeof(BITMAP), &bm);
  1966. // Create the mask bitmaps
  1967. hAndMaskBitmap = CreateCompatibleBitmap(hDC, bm.bmWidth, bm.bmHeight); // color
  1968. hXorMaskBitmap = CreateCompatibleBitmap(hDC, bm.bmWidth, bm.bmHeight); // color
  1969. // Release the system display DC
  1970. ReleaseDC(NULL, hDC);
  1971. // Select the bitmaps to helper DC
  1972. HBITMAP hOldMainBitmap = (HBITMAP)SelectObject(hMainDC, hSourceBitmap);
  1973. HBITMAP hOldAndMaskBitmap = (HBITMAP)SelectObject(hAndMaskDC, hAndMaskBitmap);
  1974. HBITMAP hOldXorMaskBitmap = (HBITMAP)SelectObject(hXorMaskDC, hXorMaskBitmap);
  1975. // Assign the monochrome AND mask bitmap pixels so that a pixels of the source bitmap
  1976. // with 'clrTransparent' will be white pixels of the monochrome bitmap
  1977. SetBkColor(hMainDC, clrTransparent);
  1978. BitBlt(hAndMaskDC, 0, 0, bm.bmWidth, bm.bmHeight, hMainDC, 0, 0, SRCCOPY);
  1979. // Assign the color XOR mask bitmap pixels so that a pixels of the source bitmap
  1980. // with 'clrTransparent' will be black and rest the pixels same as corresponding
  1981. // pixels of the source bitmap
  1982. SetBkColor(hXorMaskDC, RGB(0, 0, 0));
  1983. SetTextColor(hXorMaskDC, RGB(255, 255, 255));
  1984. BitBlt(hXorMaskDC, 0, 0, bm.bmWidth, bm.bmHeight, hAndMaskDC, 0, 0, SRCCOPY);
  1985. BitBlt(hXorMaskDC, 0, 0, bm.bmWidth, bm.bmHeight, hMainDC, 0, 0, SRCAND);
  1986. // Deselect bitmaps from the helper DC
  1987. SelectObject(hMainDC, hOldMainBitmap);
  1988. SelectObject(hAndMaskDC, hOldAndMaskBitmap);
  1989. SelectObject(hXorMaskDC, hOldXorMaskBitmap);
  1990. // Delete the helper DC
  1991. DeleteDC(hXorMaskDC);
  1992. DeleteDC(hAndMaskDC);
  1993. DeleteDC(hMainDC);
  1994. }
  1995. 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, bool read_stderr, Mutex *p_pipe_mutex) {
  1996. if (p_blocking && r_pipe) {
  1997. String argss;
  1998. argss = "\"\"" + p_path + "\"";
  1999. for (const List<String>::Element *E = p_arguments.front(); E; E = E->next()) {
  2000. argss += " \"" + E->get() + "\"";
  2001. }
  2002. argss += "\"";
  2003. if (read_stderr) {
  2004. argss += " 2>&1"; // Read stderr too
  2005. }
  2006. FILE *f = _wpopen(argss.c_str(), L"r");
  2007. ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
  2008. char buf[65535];
  2009. while (fgets(buf, 65535, f)) {
  2010. if (p_pipe_mutex) {
  2011. p_pipe_mutex->lock();
  2012. }
  2013. (*r_pipe) += buf;
  2014. if (p_pipe_mutex) {
  2015. p_pipe_mutex->unlock();
  2016. }
  2017. }
  2018. int rv = _pclose(f);
  2019. if (r_exitcode)
  2020. *r_exitcode = rv;
  2021. return OK;
  2022. }
  2023. String cmdline = "\"" + p_path + "\"";
  2024. const List<String>::Element *I = p_arguments.front();
  2025. while (I) {
  2026. cmdline += " \"" + I->get() + "\"";
  2027. I = I->next();
  2028. };
  2029. ProcessInfo pi;
  2030. ZeroMemory(&pi.si, sizeof(pi.si));
  2031. pi.si.cb = sizeof(pi.si);
  2032. ZeroMemory(&pi.pi, sizeof(pi.pi));
  2033. LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si;
  2034. Vector<CharType> modstr; //windows wants to change this no idea why
  2035. modstr.resize(cmdline.size());
  2036. for (int i = 0; i < cmdline.size(); i++)
  2037. modstr.write[i] = cmdline[i];
  2038. int ret = CreateProcessW(NULL, modstr.ptrw(), NULL, NULL, 0, NORMAL_PRIORITY_CLASS & CREATE_NO_WINDOW, NULL, NULL, si_w, &pi.pi);
  2039. ERR_FAIL_COND_V(ret == 0, ERR_CANT_FORK);
  2040. if (p_blocking) {
  2041. DWORD ret2 = WaitForSingleObject(pi.pi.hProcess, INFINITE);
  2042. if (r_exitcode)
  2043. *r_exitcode = ret2;
  2044. CloseHandle(pi.pi.hProcess);
  2045. CloseHandle(pi.pi.hThread);
  2046. } else {
  2047. ProcessID pid = pi.pi.dwProcessId;
  2048. if (r_child_id) {
  2049. *r_child_id = pid;
  2050. };
  2051. process_map->insert(pid, pi);
  2052. };
  2053. return OK;
  2054. };
  2055. Error OS_Windows::kill(const ProcessID &p_pid) {
  2056. ERR_FAIL_COND_V(!process_map->has(p_pid), FAILED);
  2057. const PROCESS_INFORMATION pi = (*process_map)[p_pid].pi;
  2058. process_map->erase(p_pid);
  2059. const int ret = TerminateProcess(pi.hProcess, 0);
  2060. CloseHandle(pi.hProcess);
  2061. CloseHandle(pi.hThread);
  2062. return ret != 0 ? OK : FAILED;
  2063. };
  2064. int OS_Windows::get_process_id() const {
  2065. return _getpid();
  2066. }
  2067. Error OS_Windows::set_cwd(const String &p_cwd) {
  2068. if (_wchdir(p_cwd.c_str()) != 0)
  2069. return ERR_CANT_OPEN;
  2070. return OK;
  2071. }
  2072. String OS_Windows::get_executable_path() const {
  2073. wchar_t bufname[4096];
  2074. GetModuleFileNameW(NULL, bufname, 4096);
  2075. String s = bufname;
  2076. return s;
  2077. }
  2078. void OS_Windows::set_native_icon(const String &p_filename) {
  2079. FileAccess *f = FileAccess::open(p_filename, FileAccess::READ);
  2080. ERR_FAIL_COND_MSG(!f, "Cannot open file with icon '" + p_filename + "'.");
  2081. ICONDIR *icon_dir = (ICONDIR *)memalloc(sizeof(ICONDIR));
  2082. int pos = 0;
  2083. icon_dir->idReserved = f->get_32();
  2084. pos += sizeof(WORD);
  2085. f->seek(pos);
  2086. icon_dir->idType = f->get_32();
  2087. pos += sizeof(WORD);
  2088. f->seek(pos);
  2089. ERR_FAIL_COND_MSG(icon_dir->idType != 1, "Invalid icon file format!");
  2090. icon_dir->idCount = f->get_32();
  2091. pos += sizeof(WORD);
  2092. f->seek(pos);
  2093. icon_dir = (ICONDIR *)memrealloc(icon_dir, 3 * sizeof(WORD) + icon_dir->idCount * sizeof(ICONDIRENTRY));
  2094. f->get_buffer((uint8_t *)&icon_dir->idEntries[0], icon_dir->idCount * sizeof(ICONDIRENTRY));
  2095. int small_icon_index = -1; // Select 16x16 with largest color count
  2096. int small_icon_cc = 0;
  2097. int big_icon_index = -1; // Select largest
  2098. int big_icon_width = 16;
  2099. int big_icon_cc = 0;
  2100. for (int i = 0; i < icon_dir->idCount; i++) {
  2101. int colors = (icon_dir->idEntries[i].bColorCount == 0) ? 32768 : icon_dir->idEntries[i].bColorCount;
  2102. int width = (icon_dir->idEntries[i].bWidth == 0) ? 256 : icon_dir->idEntries[i].bWidth;
  2103. if (width == 16) {
  2104. if (colors >= small_icon_cc) {
  2105. small_icon_index = i;
  2106. small_icon_cc = colors;
  2107. }
  2108. }
  2109. if (width >= big_icon_width) {
  2110. if (colors >= big_icon_cc) {
  2111. big_icon_index = i;
  2112. big_icon_width = width;
  2113. big_icon_cc = colors;
  2114. }
  2115. }
  2116. }
  2117. ERR_FAIL_COND_MSG(big_icon_index == -1, "No valid icons found!");
  2118. if (small_icon_index == -1) {
  2119. WARN_PRINTS("No small icon found, reusing " + itos(big_icon_width) + "x" + itos(big_icon_width) + " @" + itos(big_icon_cc) + " icon!");
  2120. small_icon_index = big_icon_index;
  2121. small_icon_cc = big_icon_cc;
  2122. }
  2123. // Read the big icon
  2124. DWORD bytecount_big = icon_dir->idEntries[big_icon_index].dwBytesInRes;
  2125. Vector<uint8_t> data_big;
  2126. data_big.resize(bytecount_big);
  2127. pos = icon_dir->idEntries[big_icon_index].dwImageOffset;
  2128. f->seek(pos);
  2129. f->get_buffer((uint8_t *)&data_big.write[0], bytecount_big);
  2130. HICON icon_big = CreateIconFromResource((PBYTE)&data_big.write[0], bytecount_big, TRUE, 0x00030000);
  2131. ERR_FAIL_COND_MSG(!icon_big, "Could not create " + itos(big_icon_width) + "x" + itos(big_icon_width) + " @" + itos(big_icon_cc) + " icon, error: " + format_error_message(GetLastError()) + ".");
  2132. // Read the small icon
  2133. DWORD bytecount_small = icon_dir->idEntries[small_icon_index].dwBytesInRes;
  2134. Vector<uint8_t> data_small;
  2135. data_small.resize(bytecount_small);
  2136. pos = icon_dir->idEntries[small_icon_index].dwImageOffset;
  2137. f->seek(pos);
  2138. f->get_buffer((uint8_t *)&data_small.write[0], bytecount_small);
  2139. HICON icon_small = CreateIconFromResource((PBYTE)&data_small.write[0], bytecount_small, TRUE, 0x00030000);
  2140. ERR_FAIL_COND_MSG(!icon_small, "Could not create 16x16 @" + itos(small_icon_cc) + " icon, error: " + format_error_message(GetLastError()) + ".");
  2141. // Online tradition says to be sure last error is cleared and set the small icon first
  2142. int err = 0;
  2143. SetLastError(err);
  2144. SendMessage(hWnd, WM_SETICON, ICON_SMALL, (LPARAM)icon_small);
  2145. err = GetLastError();
  2146. ERR_FAIL_COND_MSG(err, "Error setting ICON_SMALL: " + format_error_message(err) + ".");
  2147. SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM)icon_big);
  2148. err = GetLastError();
  2149. ERR_FAIL_COND_MSG(err, "Error setting ICON_BIG: " + format_error_message(err) + ".");
  2150. memdelete(f);
  2151. memdelete(icon_dir);
  2152. }
  2153. void OS_Windows::set_icon(const Ref<Image> &p_icon) {
  2154. ERR_FAIL_COND(!p_icon.is_valid());
  2155. Ref<Image> icon = p_icon->duplicate();
  2156. if (icon->get_format() != Image::FORMAT_RGBA8)
  2157. icon->convert(Image::FORMAT_RGBA8);
  2158. int w = icon->get_width();
  2159. int h = icon->get_height();
  2160. /* Create temporary bitmap buffer */
  2161. int icon_len = 40 + h * w * 4;
  2162. Vector<BYTE> v;
  2163. v.resize(icon_len);
  2164. BYTE *icon_bmp = v.ptrw();
  2165. encode_uint32(40, &icon_bmp[0]);
  2166. encode_uint32(w, &icon_bmp[4]);
  2167. encode_uint32(h * 2, &icon_bmp[8]);
  2168. encode_uint16(1, &icon_bmp[12]);
  2169. encode_uint16(32, &icon_bmp[14]);
  2170. encode_uint32(BI_RGB, &icon_bmp[16]);
  2171. encode_uint32(w * h * 4, &icon_bmp[20]);
  2172. encode_uint32(0, &icon_bmp[24]);
  2173. encode_uint32(0, &icon_bmp[28]);
  2174. encode_uint32(0, &icon_bmp[32]);
  2175. encode_uint32(0, &icon_bmp[36]);
  2176. uint8_t *wr = &icon_bmp[40];
  2177. PoolVector<uint8_t>::Read r = icon->get_data().read();
  2178. for (int i = 0; i < h; i++) {
  2179. for (int j = 0; j < w; j++) {
  2180. const uint8_t *rpx = &r[((h - i - 1) * w + j) * 4];
  2181. uint8_t *wpx = &wr[(i * w + j) * 4];
  2182. wpx[0] = rpx[2];
  2183. wpx[1] = rpx[1];
  2184. wpx[2] = rpx[0];
  2185. wpx[3] = rpx[3];
  2186. }
  2187. }
  2188. HICON hicon = CreateIconFromResource(icon_bmp, icon_len, TRUE, 0x00030000);
  2189. /* Set the icon for the window */
  2190. SendMessage(hWnd, WM_SETICON, ICON_SMALL, (LPARAM)hicon);
  2191. /* Set the icon in the task manager (should we do this?) */
  2192. SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM)hicon);
  2193. }
  2194. bool OS_Windows::has_environment(const String &p_var) const {
  2195. #ifdef MINGW_ENABLED
  2196. return _wgetenv(p_var.c_str()) != NULL;
  2197. #else
  2198. wchar_t *env;
  2199. size_t len;
  2200. _wdupenv_s(&env, &len, p_var.c_str());
  2201. const bool has_env = env != NULL;
  2202. free(env);
  2203. return has_env;
  2204. #endif
  2205. };
  2206. String OS_Windows::get_environment(const String &p_var) const {
  2207. wchar_t wval[0x7Fff]; // MSDN says 32767 char is the maximum
  2208. int wlen = GetEnvironmentVariableW(p_var.c_str(), wval, 0x7Fff);
  2209. if (wlen > 0) {
  2210. return wval;
  2211. }
  2212. return "";
  2213. }
  2214. bool OS_Windows::set_environment(const String &p_var, const String &p_value) const {
  2215. return (bool)SetEnvironmentVariableW(p_var.c_str(), p_value.c_str());
  2216. }
  2217. String OS_Windows::get_stdin_string(bool p_block) {
  2218. if (p_block) {
  2219. char buff[1024];
  2220. return fgets(buff, 1024, stdin);
  2221. };
  2222. return String();
  2223. }
  2224. void OS_Windows::enable_for_stealing_focus(ProcessID pid) {
  2225. AllowSetForegroundWindow(pid);
  2226. }
  2227. void OS_Windows::move_window_to_foreground() {
  2228. SetForegroundWindow(hWnd);
  2229. }
  2230. Error OS_Windows::shell_open(String p_uri) {
  2231. ShellExecuteW(NULL, L"open", p_uri.c_str(), NULL, NULL, SW_SHOWNORMAL);
  2232. return OK;
  2233. }
  2234. String OS_Windows::get_locale() const {
  2235. const _WinLocale *wl = &_win_locales[0];
  2236. LANGID langid = GetUserDefaultUILanguage();
  2237. String neutral;
  2238. int lang = langid & ((1 << 9) - 1);
  2239. int sublang = langid & ~((1 << 9) - 1);
  2240. while (wl->locale) {
  2241. if (wl->main_lang == lang && wl->sublang == SUBLANG_NEUTRAL)
  2242. neutral = wl->locale;
  2243. if (lang == wl->main_lang && sublang == wl->sublang)
  2244. return wl->locale;
  2245. wl++;
  2246. }
  2247. if (neutral != "")
  2248. return neutral;
  2249. return "en";
  2250. }
  2251. // We need this because GetSystemInfo() is unreliable on WOW64
  2252. // see https://msdn.microsoft.com/en-us/library/windows/desktop/ms724381(v=vs.85).aspx
  2253. // Taken from MSDN
  2254. typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
  2255. LPFN_ISWOW64PROCESS fnIsWow64Process;
  2256. BOOL is_wow64() {
  2257. BOOL wow64 = FALSE;
  2258. fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
  2259. if (fnIsWow64Process) {
  2260. if (!fnIsWow64Process(GetCurrentProcess(), &wow64)) {
  2261. wow64 = FALSE;
  2262. }
  2263. }
  2264. return wow64;
  2265. }
  2266. int OS_Windows::get_processor_count() const {
  2267. SYSTEM_INFO sysinfo;
  2268. if (is_wow64())
  2269. GetNativeSystemInfo(&sysinfo);
  2270. else
  2271. GetSystemInfo(&sysinfo);
  2272. return sysinfo.dwNumberOfProcessors;
  2273. }
  2274. OS::LatinKeyboardVariant OS_Windows::get_latin_keyboard_variant() const {
  2275. unsigned long azerty[] = {
  2276. 0x00020401, // Arabic (102) AZERTY
  2277. 0x0001080c, // Belgian (Comma)
  2278. 0x0000080c, // Belgian French
  2279. 0x0000040c, // French
  2280. 0 // <--- STOP MARK
  2281. };
  2282. unsigned long qwertz[] = {
  2283. 0x0000041a, // Croation
  2284. 0x00000405, // Czech
  2285. 0x00000407, // German
  2286. 0x00010407, // German (IBM)
  2287. 0x0000040e, // Hungarian
  2288. 0x0000046e, // Luxembourgish
  2289. 0x00010415, // Polish (214)
  2290. 0x00000418, // Romanian (Legacy)
  2291. 0x0000081a, // Serbian (Latin)
  2292. 0x0000041b, // Slovak
  2293. 0x00000424, // Slovenian
  2294. 0x0001042e, // Sorbian Extended
  2295. 0x0002042e, // Sorbian Standard
  2296. 0x0000042e, // Sorbian Standard (Legacy)
  2297. 0x0000100c, // Swiss French
  2298. 0x00000807, // Swiss German
  2299. 0 // <--- STOP MARK
  2300. };
  2301. unsigned long dvorak[] = {
  2302. 0x00010409, // US-Dvorak
  2303. 0x00030409, // US-Dvorak for left hand
  2304. 0x00040409, // US-Dvorak for right hand
  2305. 0 // <--- STOP MARK
  2306. };
  2307. char name[KL_NAMELENGTH + 1];
  2308. name[0] = 0;
  2309. GetKeyboardLayoutNameA(name);
  2310. unsigned long hex = strtoul(name, NULL, 16);
  2311. int i = 0;
  2312. while (azerty[i] != 0) {
  2313. if (azerty[i] == hex) return LATIN_KEYBOARD_AZERTY;
  2314. i++;
  2315. }
  2316. i = 0;
  2317. while (qwertz[i] != 0) {
  2318. if (qwertz[i] == hex) return LATIN_KEYBOARD_QWERTZ;
  2319. i++;
  2320. }
  2321. i = 0;
  2322. while (dvorak[i] != 0) {
  2323. if (dvorak[i] == hex) return LATIN_KEYBOARD_DVORAK;
  2324. i++;
  2325. }
  2326. return LATIN_KEYBOARD_QWERTY;
  2327. }
  2328. void OS_Windows::release_rendering_thread() {
  2329. gl_context->release_current();
  2330. }
  2331. void OS_Windows::make_rendering_thread() {
  2332. gl_context->make_current();
  2333. }
  2334. void OS_Windows::swap_buffers() {
  2335. gl_context->swap_buffers();
  2336. }
  2337. void OS_Windows::force_process_input() {
  2338. process_events(); // get rid of pending events
  2339. }
  2340. void OS_Windows::run() {
  2341. if (!main_loop)
  2342. return;
  2343. main_loop->init();
  2344. while (!force_quit) {
  2345. process_events(); // get rid of pending events
  2346. if (Main::iteration())
  2347. break;
  2348. };
  2349. main_loop->finish();
  2350. }
  2351. MainLoop *OS_Windows::get_main_loop() const {
  2352. return main_loop;
  2353. }
  2354. String OS_Windows::get_config_path() const {
  2355. if (has_environment("XDG_CONFIG_HOME")) { // unlikely, but after all why not?
  2356. return get_environment("XDG_CONFIG_HOME");
  2357. } else if (has_environment("APPDATA")) {
  2358. return get_environment("APPDATA");
  2359. } else {
  2360. return ".";
  2361. }
  2362. }
  2363. String OS_Windows::get_data_path() const {
  2364. if (has_environment("XDG_DATA_HOME")) {
  2365. return get_environment("XDG_DATA_HOME");
  2366. } else {
  2367. return get_config_path();
  2368. }
  2369. }
  2370. String OS_Windows::get_cache_path() const {
  2371. if (has_environment("XDG_CACHE_HOME")) {
  2372. return get_environment("XDG_CACHE_HOME");
  2373. } else if (has_environment("TEMP")) {
  2374. return get_environment("TEMP");
  2375. } else {
  2376. return get_config_path();
  2377. }
  2378. }
  2379. // Get properly capitalized engine name for system paths
  2380. String OS_Windows::get_godot_dir_name() const {
  2381. return String(VERSION_SHORT_NAME).capitalize();
  2382. }
  2383. String OS_Windows::get_system_dir(SystemDir p_dir) const {
  2384. KNOWNFOLDERID id;
  2385. switch (p_dir) {
  2386. case SYSTEM_DIR_DESKTOP: {
  2387. id = FOLDERID_Desktop;
  2388. } break;
  2389. case SYSTEM_DIR_DCIM: {
  2390. id = FOLDERID_Pictures;
  2391. } break;
  2392. case SYSTEM_DIR_DOCUMENTS: {
  2393. id = FOLDERID_Documents;
  2394. } break;
  2395. case SYSTEM_DIR_DOWNLOADS: {
  2396. id = FOLDERID_Downloads;
  2397. } break;
  2398. case SYSTEM_DIR_MOVIES: {
  2399. id = FOLDERID_Videos;
  2400. } break;
  2401. case SYSTEM_DIR_MUSIC: {
  2402. id = FOLDERID_Music;
  2403. } break;
  2404. case SYSTEM_DIR_PICTURES: {
  2405. id = FOLDERID_Pictures;
  2406. } break;
  2407. case SYSTEM_DIR_RINGTONES: {
  2408. id = FOLDERID_Music;
  2409. } break;
  2410. }
  2411. PWSTR szPath;
  2412. HRESULT res = SHGetKnownFolderPath(id, 0, NULL, &szPath);
  2413. ERR_FAIL_COND_V(res != S_OK, String());
  2414. String path = String(szPath);
  2415. CoTaskMemFree(szPath);
  2416. return path;
  2417. }
  2418. String OS_Windows::get_user_data_dir() const {
  2419. String appname = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/name"));
  2420. if (appname != "") {
  2421. bool use_custom_dir = ProjectSettings::get_singleton()->get("application/config/use_custom_user_dir");
  2422. if (use_custom_dir) {
  2423. String custom_dir = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/custom_user_dir_name"), true);
  2424. if (custom_dir == "") {
  2425. custom_dir = appname;
  2426. }
  2427. return get_data_path().plus_file(custom_dir).replace("\\", "/");
  2428. } else {
  2429. return get_data_path().plus_file(get_godot_dir_name()).plus_file("app_userdata").plus_file(appname).replace("\\", "/");
  2430. }
  2431. }
  2432. return ProjectSettings::get_singleton()->get_resource_path();
  2433. }
  2434. String OS_Windows::get_unique_id() const {
  2435. HW_PROFILE_INFO HwProfInfo;
  2436. ERR_FAIL_COND_V(!GetCurrentHwProfile(&HwProfInfo), "");
  2437. return String(HwProfInfo.szHwProfileGuid);
  2438. }
  2439. void OS_Windows::set_ime_active(const bool p_active) {
  2440. if (p_active) {
  2441. ImmAssociateContext(hWnd, im_himc);
  2442. set_ime_position(im_position);
  2443. } else {
  2444. ImmAssociateContext(hWnd, (HIMC)0);
  2445. }
  2446. }
  2447. void OS_Windows::set_ime_position(const Point2 &p_pos) {
  2448. im_position = p_pos;
  2449. HIMC himc = ImmGetContext(hWnd);
  2450. if (himc == (HIMC)0)
  2451. return;
  2452. COMPOSITIONFORM cps;
  2453. cps.dwStyle = CFS_FORCE_POSITION;
  2454. cps.ptCurrentPos.x = im_position.x;
  2455. cps.ptCurrentPos.y = im_position.y;
  2456. ImmSetCompositionWindow(himc, &cps);
  2457. ImmReleaseContext(hWnd, himc);
  2458. }
  2459. bool OS_Windows::is_joy_known(int p_device) {
  2460. return input->is_joy_mapped(p_device);
  2461. }
  2462. String OS_Windows::get_joy_guid(int p_device) const {
  2463. return input->get_joy_guid_remapped(p_device);
  2464. }
  2465. void OS_Windows::_set_use_vsync(bool p_enable) {
  2466. if (gl_context)
  2467. gl_context->set_use_vsync(p_enable);
  2468. }
  2469. /*
  2470. bool OS_Windows::is_vsync_enabled() const {
  2471. if (gl_context)
  2472. return gl_context->is_using_vsync();
  2473. return true;
  2474. }*/
  2475. OS::PowerState OS_Windows::get_power_state() {
  2476. return power_manager->get_power_state();
  2477. }
  2478. int OS_Windows::get_power_seconds_left() {
  2479. return power_manager->get_power_seconds_left();
  2480. }
  2481. int OS_Windows::get_power_percent_left() {
  2482. return power_manager->get_power_percent_left();
  2483. }
  2484. bool OS_Windows::_check_internal_feature_support(const String &p_feature) {
  2485. return p_feature == "pc";
  2486. }
  2487. void OS_Windows::disable_crash_handler() {
  2488. crash_handler.disable();
  2489. }
  2490. bool OS_Windows::is_disable_crash_handler() const {
  2491. return crash_handler.is_disabled();
  2492. }
  2493. void OS_Windows::process_and_drop_events() {
  2494. drop_events = true;
  2495. process_events();
  2496. drop_events = false;
  2497. }
  2498. Error OS_Windows::move_to_trash(const String &p_path) {
  2499. SHFILEOPSTRUCTW sf;
  2500. WCHAR *from = new WCHAR[p_path.length() + 2];
  2501. wcscpy_s(from, p_path.length() + 1, p_path.c_str());
  2502. from[p_path.length() + 1] = 0;
  2503. sf.hwnd = hWnd;
  2504. sf.wFunc = FO_DELETE;
  2505. sf.pFrom = from;
  2506. sf.pTo = NULL;
  2507. sf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
  2508. sf.fAnyOperationsAborted = FALSE;
  2509. sf.hNameMappings = NULL;
  2510. sf.lpszProgressTitle = NULL;
  2511. int ret = SHFileOperationW(&sf);
  2512. delete[] from;
  2513. if (ret) {
  2514. ERR_PRINTS("SHFileOperation error: " + itos(ret));
  2515. return FAILED;
  2516. }
  2517. return OK;
  2518. }
  2519. OS_Windows::OS_Windows(HINSTANCE _hInstance) {
  2520. drop_events = false;
  2521. key_event_pos = 0;
  2522. layered_window = false;
  2523. hBitmap = NULL;
  2524. force_quit = false;
  2525. alt_mem = false;
  2526. gr_mem = false;
  2527. shift_mem = false;
  2528. control_mem = false;
  2529. meta_mem = false;
  2530. minimized = false;
  2531. console_visible = IsWindowVisible(GetConsoleWindow());
  2532. hInstance = _hInstance;
  2533. pressrc = 0;
  2534. old_invalid = true;
  2535. mouse_mode = MOUSE_MODE_VISIBLE;
  2536. #ifdef STDOUT_FILE
  2537. stdo = fopen("stdout.txt", "wb");
  2538. #endif
  2539. user_proc = NULL;
  2540. #ifdef WASAPI_ENABLED
  2541. AudioDriverManager::add_driver(&driver_wasapi);
  2542. #endif
  2543. #ifdef XAUDIO2_ENABLED
  2544. AudioDriverManager::add_driver(&driver_xaudio2);
  2545. #endif
  2546. Vector<Logger *> loggers;
  2547. loggers.push_back(memnew(WindowsTerminalLogger));
  2548. _set_logger(memnew(CompositeLogger(loggers)));
  2549. }
  2550. OS_Windows::~OS_Windows() {
  2551. if (is_layered_allowed() && layered_window) {
  2552. DeleteObject(hBitmap);
  2553. DeleteDC(hDC_dib);
  2554. }
  2555. #ifdef STDOUT_FILE
  2556. fclose(stdo);
  2557. #endif
  2558. }