<commit_before>/*************************************************************************/
/*  os_windows.cpp                                                       */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2017 <NAME>, <NAME>.                 */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "os_windows.h"

#include "drivers/gles3/rasterizer_gles3.h"
#include "drivers/windows/dir_access_windows.h"
#include "drivers/windows/file_access_windows.h"
#include "drivers/windows/mutex_windows.h"
#include "drivers/windows/rw_lock_windows.h"
#include "drivers/windows/semaphore_windows.h"
#include "drivers/windows/thread_windows.h"
#include "io/marshalls.h"
#include "joypad.h"
#include "lang_table.h"
#include "main/main.h"
#include "packet_peer_udp_winsock.h"
#include "servers/audio_server.h"
#include "servers/visual/visual_server_raster.h"
#include "servers/visual/visual_server_wrap_mt.h"
#include "stream_peer_winsock.h"
#include "tcp_server_winsock.h"
#include "version_generated.gen.h"
#include "windows_terminal_logger.h"

#include <process.h>
#include <regstr.h>
#include <shlobj.h>

static const WORD MAX_CONSOLE_LINES = 1500;

extern "C" {
#ifdef _MSC_VER
_declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
#else
__attribute__((visibility("default"))) DWORD NvOptimusEnablement = 0x00000001;
#endif
}

// Workaround mingw-w64 < 4.0 bug
#ifndef WM_TOUCH
#define WM_TOUCH 576
#endif

extern HINSTANCE godot_hinstance;

void RedirectIOToConsole() {

	int hConHandle;

	intptr_t lStdHandle;

	CONSOLE_SCREEN_BUFFER_INFO coninfo;

	FILE *fp;

	// allocate a console for this app

	AllocConsole();

	// set the screen buffer to be big enough to let us scroll text

	GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),

			&coninfo);

	coninfo.dwSize.Y = MAX_CONSOLE_LINES;

	SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),

			coninfo.dwSize);

	// redirect unbuffered STDOUT to the console

	lStdHandle = (intptr_t)GetStdHandle(STD_OUTPUT_HANDLE);

	hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);

	fp = _fdopen(hConHandle, "w");

	*stdout = *fp;

	setvbuf(stdout, NULL, _IONBF, 0);

	// redirect unbuffered STDIN to the console

	lStdHandle = (intptr_t)GetStdHandle(STD_INPUT_HANDLE);

	hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);

	fp = _fdopen(hConHandle, "r");

	*stdin = *fp;

	setvbuf(stdin, NULL, _IONBF, 0);

	// redirect unbuffered STDERR to the console

	lStdHandle = (intptr_t)GetStdHandle(STD_ERROR_HANDLE);

	hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);

	fp = _fdopen(hConHandle, "w");

	*stderr = *fp;

	setvbuf(stderr, NULL, _IONBF, 0);

	// make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog

	// point to console as well
}

int OS_Windows::get_video_driver_count() const {

	return 1;
}
const char *OS_Windows::get_video_driver_name(int p_driver) const {

	return "GLES3";
}

int OS_Windows::get_audio_driver_count() const {

	return AudioDriverManager::get_driver_count();
}
const char *OS_Windows::get_audio_driver_name(int p_driver) const {

	AudioDriver *driver = AudioDriverManager::get_driver(p_driver);
	ERR_FAIL_COND_V(!driver, "");
	return AudioDriverManager::get_driver(p_driver)->get_name();
}

void OS_Windows::initialize_core() {

	crash_handler.initialize();

	last_button_state = 0;

	//RedirectIOToConsole();
	maximized = false;
	minimized = false;
	borderless = false;

	ThreadWindows::make_default();
	SemaphoreWindows::make_default();
	MutexWindows::make_default();
	RWLockWindows::make_default();

	FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_RESOURCES);
	FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_USERDATA);
	FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_FILESYSTEM);
	//FileAccessBufferedFA<FileAccessWindows>::make_default();
	DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_RESOURCES);
	DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_USERDATA);
	DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_FILESYSTEM);

	TCPServerWinsock::make_default();
	StreamPeerWinsock::make_default();
	PacketPeerUDPWinsock::make_default();

	// We need to know how often the clock is updated
	if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
		ticks_per_second = 1000;
	// If timeAtGameStart is 0 then we get the time since
	// the start of the computer when we call GetGameTime()
	ticks_start = 0;
	ticks_start = get_ticks_usec();

	process_map = memnew((Map<ProcessID, ProcessInfo>));

	IP_Unix::make_default();

	cursor_shape = CURSOR_ARROW;
}

bool OS_Windows::can_draw() const {

	return !minimized;
};

#define MI_WP_SIGNATURE 0xFF515700
#define SIGNATURE_MASK 0xFFFFFF00
#define IsPenEvent(dw) (((dw)&SIGNATURE_MASK) == MI_WP_SIGNATURE)

void OS_Windows::_touch_event(bool p_pressed, int p_x, int p_y, int idx) {

	Ref<InputEventScreenTouch> event;
	event.instance();
	event->set_index(idx);
	event->set_pressed(p_pressed);
	event->set_position(Vector2(p_x, p_y));

	if (main_loop) {
		input->parse_input_event(event);
	}
};

void OS_Windows::_drag_event(int p_x, int p_y, int idx) {

	Ref<InputEventScreenDrag> event;
	event.instance();
	event->set_index(idx);
	event->set_position(Vector2(p_x, p_y));

	if (main_loop)
		input->parse_input_event(event);
};

LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {

	switch (uMsg) // Check For Windows Messages
	{
		case WM_SETFOCUS: {
			window_has_focus = true;
			// Re-capture cursor if we're in one of the capture modes
			if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
				SetCapture(hWnd);
			}
			break;
		}
		case WM_KILLFOCUS: {
			window_has_focus = false;

			// Release capture if we're in one of the capture modes
			if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
				ReleaseCapture();
			}
			break;
		}
		case WM_ACTIVATE: // Watch For Window Activate Message
		{
			minimized = HIWORD(wParam) != 0;
			if (!main_loop) {
				return 0;
			};
			if (LOWORD(wParam) == WA_ACTIVE || LOWORD(wParam) == WA_CLICKACTIVE) {

				main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
				alt_mem = false;
				control_mem = false;
				shift_mem = false;
				if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
					RECT clipRect;
					GetClientRect(hWnd, &clipRect);
					ClientToScreen(hWnd, (POINT *)&clipRect.left);
					ClientToScreen(hWnd, (POINT *)&clipRect.right);
					ClipCursor(&clipRect);
					SetCapture(hWnd);
				}
			} else {
				main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
				alt_mem = false;
			};

			return 0; // Return To The Message Loop
		}

		case WM_PAINT:

			Main::force_redraw();
			break;

		case WM_SYSCOMMAND: // Intercept System Commands
		{
			switch (wParam) // Check System Calls
			{
				case SC_SCREENSAVE: // Screensaver Trying To Start?
				case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
					return 0; // Prevent From Happening
				case SC_KEYMENU:
					if ((lParam >> 16) <= 0)
						return 0;
			}
			break; // Exit
		}

		case WM_CLOSE: // Did We Receive A Close Message?
		{
			if (main_loop)
				main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
			//force_quit=true;
			return 0; // Jump Back
		}
		case WM_MOUSELEAVE: {

			old_invalid = true;
			outside = true;
			if (main_loop && mouse_mode != MOUSE_MODE_CAPTURED)
				main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
			if (input)
				input->set_mouse_in_window(false);

		} break;
		case WM_MOUSEMOVE: {

			if (outside) {
				//mouse enter

				if (main_loop && mouse_mode != MOUSE_MODE_CAPTURED)
					main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
				if (input)
					input->set_mouse_in_window(true);

				CursorShape c = cursor_shape;
				cursor_shape = CURSOR_MAX;
				set_cursor_shape(c);
				outside = false;

				//Once-Off notification, must call again....
				TRACKMOUSEEVENT tme;
				tme.cbSize = sizeof(TRACKMOUSEEVENT);
				tme.dwFlags = TME_LEAVE;
				tme.hwndTrack = hWnd;
				tme.dwHoverTime = HOVER_DEFAULT;
				TrackMouseEvent(&tme);
			}

			// Don't calculate relative mouse movement if we don't have focus in CAPTURED mode.
			if (!window_has_focus && mouse_mode == MOUSE_MODE_CAPTURED)
				break;
			/*
			LPARAM extra = GetMessageExtraInfo();
			if (IsPenEvent(extra)) {

				int idx = extra & 0x7f;
				_drag_event(idx, uMsg, wParam, lParam);
				if (idx != 0) {
					return 0;
				};
				// fallthrough for mouse event
			};
			*/

			Ref<InputEventMouseMotion> mm;
			mm.instance();

			mm->set_control((wParam & MK_CONTROL) != 0);
			mm->set_shift((wParam & MK_SHIFT) != 0);
			mm->set_alt(alt_mem);

			int bmask = 0;
			bmask |= (wParam & MK_LBUTTON) ? (1 << 0) : 0;
			bmask |= (wParam & MK_RBUTTON) ? (1 << 1) : 0;
			bmask |= (wParam & MK_MBUTTON) ? (1 << 2) : 0;
			mm->set_button_mask(bmask);

			last_button_state = mm->get_button_mask();
			/*mm->get_button_mask()|=(wParam&MK_XBUTTON1)?(1<<5):0;
			mm->get_button_mask()|=(wParam&MK_XBUTTON2)?(1<<6):0;*/
			mm->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));

			if (mouse_mode == MOUSE_MODE_CAPTURED) {

				Point2i c(video_mode.width / 2, video_mode.height / 2);
				old_x = c.x;
				old_y = c.y;

				if (mm->get_position() == c) {
					center = c;
					return 0;
				}

				Point2i ncenter = mm->get_position();
				center = ncenter;
				POINT pos = { (int)c.x, (int)c.y };
				ClientToScreen(hWnd, &pos);
				SetCursorPos(pos.x, pos.y);
			}

			input->set_mouse_position(mm->get_position());
			mm->set_speed(input->get_last_mouse_speed());

			if (old_invalid) {

				old_x = mm->get_position().x;
				old_y = mm->get_position().y;
				old_invalid = false;
			}

			mm->set_relative(Vector2(mm->get_position() - Vector2(old_x, old_y)));
			old_x = mm->get_position().x;
			old_y = mm->get_position().y;
			if (window_has_focus && main_loop)
				input->parse_input_event(mm);

		} break;
		case WM_LBUTTONDOWN:
		case WM_LBUTTONUP:
		case WM_MBUTTONDOWN:
		case WM_MBUTTONUP:
		case WM_RBUTTONDOWN:
		case WM_RBUTTONUP:
		case WM_MOUSEWHEEL:
		case WM_MOUSEHWHEEL:
		case WM_LBUTTONDBLCLK:
		case WM_RBUTTONDBLCLK:
			/*case WM_XBUTTONDOWN:
		case WM_XBUTTONUP: */ {

				/*
			LPARAM extra = GetMessageExtraInfo();
			if (IsPenEvent(extra)) {

				int idx = extra & 0x7f;
				_touch_event(idx, uMsg, wParam, lParam);
				if (idx != 0) {
					return 0;
				};
				// fallthrough for mouse event
			};
			*/

				Ref<InputEventMouseButton> mb;
				mb.instance();

				switch (uMsg) {
					case WM_LBUTTONDOWN: {
						mb->set_pressed(true);
						mb->set_button_index(1);
					} break;
					case WM_LBUTTONUP: {
						mb->set_pressed(false);
						mb->set_button_index(1);
					} break;
					case WM_MBUTTONDOWN: {
						mb->set_pressed(true);
						mb->set_button_index(3);

					} break;
					case WM_MBUTTONUP: {
						mb->set_pressed(false);
						mb->set_button_index(3);
					} break;
					case WM_RBUTTONDOWN: {
						mb->set_pressed(true);
						mb->set_button_index(2);
					} break;
					case WM_RBUTTONUP: {
						mb->set_pressed(false);
						mb->set_button_index(2);
					} break;
					case WM_LBUTTONDBLCLK: {

						mb->set_pressed(true);
						mb->set_button_index(1);
						mb->set_doubleclick(true);
					} break;
					case WM_RBUTTONDBLCLK: {

						mb->set_pressed(true);
						mb->set_button_index(2);
						mb->set_doubleclick(true);
					} break;
					case WM_MOUSEWHEEL: {

						mb->set_pressed(true);
						int motion = (short)HIWORD(wParam);
						if (!motion)
							return 0;

						if (motion > 0)
							mb->set_button_index(BUTTON_WHEEL_UP);
						else
							mb->set_button_index(BUTTON_WHEEL_DOWN);

					} break;
					case WM_MOUSEHWHEEL: {

						mb->set_pressed(true);
						int motion = (short)HIWORD(wParam);
						if (!motion)
							return 0;

						if (motion < 0) {
							mb->set_button_index(BUTTON_WHEEL_LEFT);
							mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA));
						} else {
							mb->set_button_index(BUTTON_WHEEL_RIGHT);
							mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA));
						}
					} break;
					/*
				case WM_XBUTTONDOWN: {
					mb->is_pressed()=true;
					mb->get_button_index()=(HIWORD(wParam)==XBUTTON1)?6:7;
				} break;
				case WM_XBUTTONUP:
					mb->is_pressed()=true;
					mb->get_button_index()=(HIWORD(wParam)==XBUTTON1)?6:7;
				} break;*/
					default: { return 0; }
				}

				mb->set_control((wParam & MK_CONTROL) != 0);
				mb->set_shift((wParam & MK_SHIFT) != 0);
				mb->set_alt(alt_mem);
				//mb->get_alt()=(wParam&MK_MENU)!=0;
				int bmask = 0;
				bmask |= (wParam & MK_LBUTTON) ? (1 << 0) : 0;
				bmask |= (wParam & MK_RBUTTON) ? (1 << 1) : 0;
				bmask |= (wParam & MK_MBUTTON) ? (1 << 2) : 0;
				mb->set_button_mask(bmask);

				last_button_state = mb->get_button_mask();
				/*
			mb->get_button_mask()|=(wParam&MK_XBUTTON1)?(1<<5):0;
			mb->get_button_mask()|=(wParam&MK_XBUTTON2)?(1<<6):0;*/
				mb->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));

				if (mouse_mode == MOUSE_MODE_CAPTURED) {

					mb->set_position(Vector2(old_x, old_y));
				}

				if (uMsg != WM_MOUSEWHEEL) {
					if (mb->is_pressed()) {

						if (++pressrc > 0)
							SetCapture(hWnd);
					} else {

						if (--pressrc <= 0) {
							ReleaseCapture();
							pressrc = 0;
						}
					}
				} else if (mouse_mode != MOUSE_MODE_CAPTURED) {
					// for reasons unknown to mankind, wheel comes in screen cordinates
					POINT coords;
					coords.x = mb->get_position().x;
					coords.y = mb->get_position().y;

					ScreenToClient(hWnd, &coords);

					mb->set_position(Vector2(coords.x, coords.y));
				}

				mb->set_global_position(mb->get_position());

				if (main_loop) {
					input->parse_input_event(mb);
					if (mb->is_pressed() && mb->get_button_index() > 3) {
						//send release for mouse wheel
						Ref<InputEventMouseButton> mbd = mb->duplicate();
						mbd->set_pressed(false);
						input->parse_input_event(mbd);
					}
				}
			}
			break;

		case WM_SIZE: {
			int window_w = LOWORD(lParam);
			int window_h = HIWORD(lParam);
			if (window_w > 0 && window_h > 0) {
				video_mode.width = window_w;
				video_mode.height = window_h;
			}
			//return 0;								// Jump Back
		} break;

		case WM_ENTERSIZEMOVE: {
			move_timer_id = SetTimer(hWnd, 1, USER_TIMER_MINIMUM, (TIMERPROC)NULL);
		} break;
		case WM_EXITSIZEMOVE: {
			KillTimer(hWnd, move_timer_id);
		} break;
		case WM_TIMER: {
			if (wParam == move_timer_id) {
				process_key_events();
				Main::iteration();
			}
		} break;

		case WM_SYSKEYDOWN:
		case WM_SYSKEYUP:
		case WM_KEYUP:
		case WM_KEYDOWN: {

			if (wParam == VK_SHIFT)
				shift_mem = uMsg == WM_KEYDOWN;
			if (wParam == VK_CONTROL)
				control_mem = uMsg == WM_KEYDOWN;
			if (wParam == VK_MENU) {
				alt_mem = (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN);
				if (lParam & (1 << 24))
					gr_mem = alt_mem;
			}

			/*
			if (wParam==VK_WIN) TODO wtf is this?
				meta_mem=uMsg==WM_KEYDOWN;
			*/

		} //fallthrough
		case WM_CHAR: {

			ERR_BREAK(key_event_pos >= KEY_EVENT_BUFFER_SIZE);

			// Make sure we don't include modifiers for the modifier key itself.
			KeyEvent ke;
			ke.shift = (wParam != VK_SHIFT) ? shift_mem : false;
			ke.alt = (!(wParam == VK_MENU && (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN))) ? alt_mem : false;
			ke.control = (wParam != VK_CONTROL) ? control_mem : false;
			ke.meta = meta_mem;
			ke.uMsg = uMsg;

			if (ke.uMsg == WM_SYSKEYDOWN)
				ke.uMsg = WM_KEYDOWN;
			if (ke.uMsg == WM_SYSKEYUP)
				ke.uMsg = WM_KEYUP;

			/*if (ke.uMsg==WM_KEYDOWN && alt_mem && uMsg!=WM_SYSKEYDOWN) {
				//altgr hack for intl keyboards, not sure how good it is
				//windows is weeeeird
				ke.mod_state.alt=false;
				ke.mod_state.control=false;
				print_line("")
			}*/

			ke.wParam = wParam;
			ke.lParam = lParam;
			key_event_buffer[key_event_pos++] = ke;

		} break;
		case WM_INPUTLANGCHANGEREQUEST: {

			print_line("input lang change");
		} break;

#if WINVER >= 0x0601 // for windows 7
		case WM_TOUCH: {

			BOOL bHandled = FALSE;
			UINT cInputs = LOWORD(wParam);
			PTOUCHINPUT pInputs = memnew_arr(TOUCHINPUT, cInputs);
			if (pInputs) {
				if (GetTouchInputInfo((HTOUCHINPUT)lParam, cInputs, pInputs, sizeof(TOUCHINPUT))) {
					for (UINT i = 0; i < cInputs; i++) {
						TOUCHINPUT ti = pInputs[i];
						//do something with each touch input entry
						if (ti.dwFlags & TOUCHEVENTF_MOVE) {

							_drag_event(ti.x / 100, ti.y / 100, ti.dwID);
						} else if (ti.dwFlags & (TOUCHEVENTF_UP | TOUCHEVENTF_DOWN)) {

							_touch_event(ti.dwFlags & TOUCHEVENTF_DOWN != 0, ti.x / 100, ti.y / 100, ti.dwID);
						};
					}
					bHandled = TRUE;
				} else {
					/* handle the error here */
				}
				memdelete_arr(pInputs);
			} else {
				/* handle the error here, probably out of memory */
			}
			if (bHandled) {
				CloseTouchInputHandle((HTOUCHINPUT)lParam);
				return 0;
			};

		} break;

#endif
		case WM_DEVICECHANGE: {

			joypad->probe_joypads();
		} break;
		case WM_SETCURSOR: {
			if (LOWORD(lParam) == HTCLIENT) {
				if (window_has_focus && (mouse_mode == MOUSE_MODE_HIDDEN || mouse_mode == MOUSE_MODE_CAPTURED)) {
					//Hide the cursor
					if (hCursor == NULL)
						hCursor = SetCursor(NULL);
					else
						SetCursor(NULL);
				} else {
					if (hCursor != NULL) {
						SetCursor(hCursor);
						hCursor = NULL;
					}
				}
			}

		} break;
		case WM_DROPFILES: {

			HDROP hDropInfo = (HDROP)wParam;
			const int buffsize = 4096;
			wchar_t buf[buffsize];

			int fcount = DragQueryFileW(hDropInfo, 0xFFFFFFFF, NULL, 0);

			Vector<String> files;

			for (int i = 0; i < fcount; i++) {

				DragQueryFileW(hDropInfo, i, buf, buffsize);
				String file = buf;
				files.push_back(file);
			}

			if (files.size() && main_loop) {
				main_loop->drop_files(files, 0);
			}

		} break;

		default: {

			if (user_proc) {

				return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
			};
		};
	}

	return DefWindowProcW(hWnd, uMsg, wParam, lParam);
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {

	OS_Windows *os_win = static_cast<OS_Windows *>(OS::get_singleton());
	if (os_win)
		return os_win->WndProc(hWnd, uMsg, wParam, lParam);
	else
		return DefWindowProcW(hWnd, uMsg, wParam, lParam);
}

void OS_Windows::process_key_events() {

	for (int i = 0; i < key_event_pos; i++) {

		KeyEvent &ke = key_event_buffer[i];
		switch (ke.uMsg) {

			case WM_CHAR: {
				if ((i == 0 && ke.uMsg == WM_CHAR) || (i > 0 && key_event_buffer[i - 1].uMsg == WM_CHAR)) {
					Ref<InputEventKey> k;
					k.instance();

					k->set_shift(ke.shift);
					k->set_alt(ke.alt);
					k->set_control(ke.control);
					k->set_metakey(ke.meta);
					k->set_pressed(true);
					k->set_scancode(KeyMappingWindows::get_keysym(ke.wParam));
					k->set_unicode(ke.wParam);
					if (k->get_unicode() && gr_mem) {
						k->set_alt(false);
						k->set_control(false);
					}

					if (k->get_unicode() < 32)
						k->set_unicode(0);

					input->parse_input_event(k);
				}

				//do nothing
			} break;
			case WM_KEYUP:
			case WM_KEYDOWN: {

				Ref<InputEventKey> k;
				k.instance();

				k->set_shift(ke.shift);
				k->set_alt(ke.alt);
				k->set_control(ke.control);
				k->set_metakey(ke.meta);

				k->set_pressed(ke.uMsg == WM_KEYDOWN);

				if ((ke.lParam & (1 << 24)) && (ke.wParam == VK_RETURN)) {
					// Special case for Numpad Enter key
					k->set_scancode(KEY_KP_ENTER);
				} else {
					k->set_scancode(KeyMappingWindows::get_keysym(ke.wParam));
				}

				if (i + 1 < key_event_pos && key_event_buffer[i + 1].uMsg == WM_CHAR) {
					k->set_unicode(key_event_buffer[i + 1].wParam);
				}
				if (k->get_unicode() && gr_mem) {
					k->set_alt(false);
					k->set_control(false);
				}

				if (k->get_unicode() < 32)
					k->set_unicode(0);

				k->set_echo((ke.uMsg == WM_KEYDOWN && (ke.lParam & (1 << 30))));

				input->parse_input_event(k);

			} break;
		}
	}

	key_event_pos = 0;
}

enum _MonitorDpiType {
	MDT_Effective_DPI = 0,
	MDT_Angular_DPI = 1,
	MDT_Raw_DPI = 2,
	MDT_Default = MDT_Effective_DPI
};

static int QueryDpiForMonitor(HMONITOR hmon, _MonitorDpiType dpiType = MDT_Default) {

	int dpiX = 96, dpiY = 96;

	static HMODULE Shcore = NULL;
	typedef HRESULT(WINAPI * GetDPIForMonitor_t)(HMONITOR hmonitor, _MonitorDpiType dpiType, UINT * dpiX, UINT * dpiY);
	static GetDPIForMonitor_t getDPIForMonitor = NULL;

	if (Shcore == NULL) {
		Shcore = LoadLibraryW(L"Shcore.dll");
		getDPIForMonitor = Shcore ? (GetDPIForMonitor_t)GetProcAddress(Shcore, "GetDpiForMonitor") : NULL;

		if ((Shcore == NULL) || (getDPIForMonitor == NULL)) {
			if (Shcore)
				FreeLibrary(Shcore);
			Shcore = (HMODULE)INVALID_HANDLE_VALUE;
		}
	}

	UINT x = 0, y = 0;
	HRESULT hr = E_FAIL;
	bool bSet = false;
	if (hmon && (Shcore != (HMODULE)INVALID_HANDLE_VALUE)) {
		hr = getDPIForMonitor(hmon, dpiType /*MDT_Effective_DPI*/, &x, &y);
		if (SUCCEEDED(hr) && (x > 0) && (y > 0)) {

			dpiX = (int)x;
			dpiY = (int)y;
		}
	} else {
		static int overallX = 0, overallY = 0;
		if (overallX <= 0 || overallY <= 0) {
			HDC hdc = GetDC(NULL);
			if (hdc) {
				overallX = GetDeviceCaps(hdc, LOGPIXELSX);
				overallY = GetDeviceCaps(hdc, LOGPIXELSY);
				ReleaseDC(NULL, hdc);
			}
		}
		if (overallX > 0 && overallY > 0) {
			dpiX = overallX;
			dpiY = overallY;
		}
	}

	return (dpiX + dpiY) / 2;
}

typedef enum _SHC_PROCESS_DPI_AWARENESS {
	SHC_PROCESS_DPI_UNAWARE = 0,
	SHC_PROCESS_SYSTEM_DPI_AWARE = 1,
	SHC_PROCESS_PER_MONITOR_DPI_AWARE = 2
} SHC_PROCESS_DPI_AWARENESS;

void OS_Windows::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {

	main_loop = NULL;
	outside = true;
	window_has_focus = true;
	WNDCLASSEXW wc;

	if (is_hidpi_allowed()) {
		HMODULE Shcore = LoadLibraryW(L"Shcore.dll");

		if (Shcore != NULL) {
			typedef HRESULT(WINAPI * SetProcessDpiAwareness_t)(SHC_PROCESS_DPI_AWARENESS);

			SetProcessDpiAwareness_t SetProcessDpiAwareness = (SetProcessDpiAwareness_t)GetProcAddress(Shcore, "SetProcessDpiAwareness");

			if (SetProcessDpiAwareness) {
				SetProcessDpiAwareness(SHC_PROCESS_SYSTEM_DPI_AWARE);
			}
		}
	}

	video_mode = p_desired;
	//printf("**************** desired %s, mode %s\n", p_desired.fullscreen?"true":"false", video_mode.fullscreen?"true":"false");
	RECT WindowRect;

	WindowRect.left = 0;
	WindowRect.right = video_mode.width;
	WindowRect.top = 0;
	WindowRect.bottom = video_mode.height;

	memset(&wc, 0, sizeof(WNDCLASSEXW));
	wc.cbSize = sizeof(WNDCLASSEXW);
	wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_DBLCLKS;
	wc.lpfnWndProc = (WNDPROC)::WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	//wc.hInstance = hInstance;
	wc.hInstance = godot_hinstance ? godot_hinstance : GetModuleHandle(NULL);
	wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
	wc.hCursor = NULL; //LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = NULL;
	wc.lpszMenuName = NULL;
	wc.lpszClassName = L"Engine";

	if (!RegisterClassExW(&wc)) {
		MessageBox(NULL, "Failed To Register The Window Class.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
		return; // Return
	}

	pre_fs_valid = true;
	if (video_mode.fullscreen) {

		DEVMODE current;
		memset(&current, 0, sizeof(current));
		EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &current);

		WindowRect.right = current.dmPelsWidth;
		WindowRect.bottom = current.dmPelsHeight;

		/*  DEVMODE dmScreenSettings;
		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));
		dmScreenSettings.dmSize=sizeof(dmScreenSettings);
		dmScreenSettings.dmPelsWidth	= video_mode.width;
		dmScreenSettings.dmPelsHeight	= video_mode.height;
		dmScreenSettings.dmBitsPerPel	= current.dmBitsPerPel;
		dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

		LONG err = ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN);
		if (err!=DISP_CHANGE_SUCCESSFUL) {

			video_mode.fullscreen=false;
		}*/
		pre_fs_valid = false;
	}

	DWORD dwExStyle;
	DWORD dwStyle;

	if (video_mode.fullscreen || video_mode.borderless_window) {

		dwExStyle = WS_EX_APPWINDOW;
		dwStyle = WS_POPUP;

	} else {
		dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
		dwStyle = WS_OVERLAPPEDWINDOW;
		if (!video_mode.resizable) {
			dwStyle &= ~WS_THICKFRAME;
			dwStyle &= ~WS_MAXIMIZEBOX;
		}
	}

	AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);

	char *windowid = getenv("GODOT_WINDOWID");
	if (windowid) {

// strtoull on mingw
#ifdef MINGW_ENABLED
		hWnd = (HWND)strtoull(windowid, NULL, 0);
#else
		hWnd = (HWND)_strtoui64(windowid, NULL, 0);
#endif
		SetLastError(0);
		user_proc = (WNDPROC)GetWindowLongPtr(hWnd, GWLP_WNDPROC);
		SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)(WNDPROC)::WndProc);
		DWORD le = GetLastError();
		if (user_proc == 0 && le != 0) {

			printf("Error setting WNDPROC: %li\n", le);
		};
		LONG_PTR proc = GetWindowLongPtr(hWnd, GWLP_WNDPROC);

		RECT rect;
		if (!GetClientRect(hWnd, &rect)) {
			MessageBoxW(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
			return; // Return FALSE
		};
		video_mode.width = rect.right;
		video_mode.height = rect.bottom;
		video_mode.fullscreen = false;
	} else {

		hWnd = CreateWindowExW(
				dwExStyle,
				L"Engine", L"",
				dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
				(GetSystemMetrics(SM_CXSCREEN) - WindowRect.right) / 2,
				(GetSystemMetrics(SM_CYSCREEN) - WindowRect.bottom) / 2,
				WindowRect.right - WindowRect.left,
				WindowRect.bottom - WindowRect.top,
				NULL, NULL, hInstance, NULL);
		if (!hWnd) {
			MessageBoxW(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
			return; // Return FALSE
		}
	};

#if defined(OPENGL_ENABLED)
	gl_context = memnew(ContextGL_Win(hWnd, true));
	gl_context->initialize();

	RasterizerGLES3::register_config();

	RasterizerGLES3::make_current();
#endif

	visual_server = memnew(VisualServerRaster);
	if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {

		visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD));
	}

	if (!is_no_window_mode_enabled()) {
		ShowWindow(hWnd, SW_SHOW); // Show The Window
		SetForegroundWindow(hWnd); // Slightly Higher Priority
		SetFocus(hWnd); // Sets Keyboard Focus To
	}

	/*
		DEVMODE dmScreenSettings;					// Device Mode
		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));		// Makes Sure Memory's Cleared
		dmScreenSettings.dmSize=sizeof(dmScreenSettings);		// Size Of The Devmode Structure
		dmScreenSettings.dmPelsWidth	= width;			// Selected Screen Width
		dmScreenSettings.dmPelsHeight	= height;			// Selected Screen Height
		dmScreenSettings.dmBitsPerPel	= bits;				// Selected Bits Per Pixel
		dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
		if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)




  */
	visual_server->init();

	input = memnew(InputDefault);
	joypad = memnew(JoypadWindows(input, &hWnd));

	power_manager = memnew(PowerWindows);

	AudioDriverManager::initialize(p_audio_driver);

	TRACKMOUSEEVENT tme;
	tme.cbSize = sizeof(TRACKMOUSEEVENT);
	tme.dwFlags = TME_LEAVE;
	tme.hwndTrack = hWnd;
	tme.dwHoverTime = HOVER_DEFAULT;
	TrackMouseEvent(&tme);

	//RegisterTouchWindow(hWnd, 0); // Windows 7

	_ensure_user_data_dir();

	DragAcceptFiles(hWnd, true);

	move_timer_id = 1;
}

void OS_Windows::set_clipboard(const String &p_text) {

	if (!OpenClipboard(hWnd)) {
		ERR_EXPLAIN("Unable to open clipboard.");
		ERR_FAIL();
	};
	EmptyClipboard();

	HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, (p_text.length() + 1) * sizeof(CharType));
	if (mem == NULL) {
		ERR_EXPLAIN("Unable to allocate memory for clipboard contents.");
		ERR_FAIL();
	};
	LPWSTR lptstrCopy = (LPWSTR)GlobalLock(mem);
	memcpy(lptstrCopy, p_text.c_str(), (p_text.length() + 1) * sizeof(CharType));
	//memset((lptstrCopy + p_text.length()), 0, sizeof(CharType));
	GlobalUnlock(mem);

	SetClipboardData(CF_UNICODETEXT, mem);

	// set the CF_TEXT version (not needed?)
	CharString utf8 = p_text.utf8();
	mem = GlobalAlloc(GMEM_MOVEABLE, utf8.length() + 1);
	if (mem == NULL) {
		ERR_EXPLAIN("Unable to allocate memory for clipboard contents.");
		ERR_FAIL();<commit_msg>Fixed white screen on editor/game startup by moving window displaying to a bit later phase<commit_after>/*************************************************************************/
/*  os_windows.cpp                                                       */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2017 <NAME>, <NAME>.                 */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "os_windows.h"

#include "drivers/gles3/rasterizer_gles3.h"
#include "drivers/windows/dir_access_windows.h"
#include "drivers/windows/file_access_windows.h"
#include "drivers/windows/mutex_windows.h"
#include "drivers/windows/rw_lock_windows.h"
#include "drivers/windows/semaphore_windows.h"
#include "drivers/windows/thread_windows.h"
#include "io/marshalls.h"
#include "joypad.h"
#include "lang_table.h"
#include "main/main.h"
#include "packet_peer_udp_winsock.h"
#include "servers/audio_server.h"
#include "servers/visual/visual_server_raster.h"
#include "servers/visual/visual_server_wrap_mt.h"
#include "stream_peer_winsock.h"
#include "tcp_server_winsock.h"
#include "version_generated.gen.h"
#include "windows_terminal_logger.h"

#include <process.h>
#include <regstr.h>
#include <shlobj.h>

static const WORD MAX_CONSOLE_LINES = 1500;

extern "C" {
#ifdef _MSC_VER
_declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
#else
__attribute__((visibility("default"))) DWORD NvOptimusEnablement = 0x00000001;
#endif
}

// Workaround mingw-w64 < 4.0 bug
#ifndef WM_TOUCH
#define WM_TOUCH 576
#endif

extern HINSTANCE godot_hinstance;

void RedirectIOToConsole() {

	int hConHandle;

	intptr_t lStdHandle;

	CONSOLE_SCREEN_BUFFER_INFO coninfo;

	FILE *fp;

	// allocate a console for this app

	AllocConsole();

	// set the screen buffer to be big enough to let us scroll text

	GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),

			&coninfo);

	coninfo.dwSize.Y = MAX_CONSOLE_LINES;

	SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),

			coninfo.dwSize);

	// redirect unbuffered STDOUT to the console

	lStdHandle = (intptr_t)GetStdHandle(STD_OUTPUT_HANDLE);

	hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);

	fp = _fdopen(hConHandle, "w");

	*stdout = *fp;

	setvbuf(stdout, NULL, _IONBF, 0);

	// redirect unbuffered STDIN to the console

	lStdHandle = (intptr_t)GetStdHandle(STD_INPUT_HANDLE);

	hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);

	fp = _fdopen(hConHandle, "r");

	*stdin = *fp;

	setvbuf(stdin, NULL, _IONBF, 0);

	// redirect unbuffered STDERR to the console

	lStdHandle = (intptr_t)GetStdHandle(STD_ERROR_HANDLE);

	hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);

	fp = _fdopen(hConHandle, "w");

	*stderr = *fp;

	setvbuf(stderr, NULL, _IONBF, 0);

	// make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog

	// point to console as well
}

int OS_Windows::get_video_driver_count() const {

	return 1;
}
const char *OS_Windows::get_video_driver_name(int p_driver) const {

	return "GLES3";
}

int OS_Windows::get_audio_driver_count() const {

	return AudioDriverManager::get_driver_count();
}
const char *OS_Windows::get_audio_driver_name(int p_driver) const {

	AudioDriver *driver = AudioDriverManager::get_driver(p_driver);
	ERR_FAIL_COND_V(!driver, "");
	return AudioDriverManager::get_driver(p_driver)->get_name();
}

void OS_Windows::initialize_core() {

	crash_handler.initialize();

	last_button_state = 0;

	//RedirectIOToConsole();
	maximized = false;
	minimized = false;
	borderless = false;

	ThreadWindows::make_default();
	SemaphoreWindows::make_default();
	MutexWindows::make_default();
	RWLockWindows::make_default();

	FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_RESOURCES);
	FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_USERDATA);
	FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_FILESYSTEM);
	//FileAccessBufferedFA<FileAccessWindows>::make_default();
	DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_RESOURCES);
	DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_USERDATA);
	DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_FILESYSTEM);

	TCPServerWinsock::make_default();
	StreamPeerWinsock::make_default();
	PacketPeerUDPWinsock::make_default();

	// We need to know how often the clock is updated
	if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
		ticks_per_second = 1000;
	// If timeAtGameStart is 0 then we get the time since
	// the start of the computer when we call GetGameTime()
	ticks_start = 0;
	ticks_start = get_ticks_usec();

	process_map = memnew((Map<ProcessID, ProcessInfo>));

	IP_Unix::make_default();

	cursor_shape = CURSOR_ARROW;
}

bool OS_Windows::can_draw() const {

	return !minimized;
};

#define MI_WP_SIGNATURE 0xFF515700
#define SIGNATURE_MASK 0xFFFFFF00
#define IsPenEvent(dw) (((dw)&SIGNATURE_MASK) == MI_WP_SIGNATURE)

void OS_Windows::_touch_event(bool p_pressed, int p_x, int p_y, int idx) {

	Ref<InputEventScreenTouch> event;
	event.instance();
	event->set_index(idx);
	event->set_pressed(p_pressed);
	event->set_position(Vector2(p_x, p_y));

	if (main_loop) {
		input->parse_input_event(event);
	}
};

void OS_Windows::_drag_event(int p_x, int p_y, int idx) {

	Ref<InputEventScreenDrag> event;
	event.instance();
	event->set_index(idx);
	event->set_position(Vector2(p_x, p_y));

	if (main_loop)
		input->parse_input_event(event);
};

LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {

	switch (uMsg) // Check For Windows Messages
	{
		case WM_SETFOCUS: {
			window_has_focus = true;
			// Re-capture cursor if we're in one of the capture modes
			if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
				SetCapture(hWnd);
			}
			break;
		}
		case WM_KILLFOCUS: {
			window_has_focus = false;

			// Release capture if we're in one of the capture modes
			if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
				ReleaseCapture();
			}
			break;
		}
		case WM_ACTIVATE: // Watch For Window Activate Message
		{
			minimized = HIWORD(wParam) != 0;
			if (!main_loop) {
				return 0;
			};
			if (LOWORD(wParam) == WA_ACTIVE || LOWORD(wParam) == WA_CLICKACTIVE) {

				main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
				alt_mem = false;
				control_mem = false;
				shift_mem = false;
				if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
					RECT clipRect;
					GetClientRect(hWnd, &clipRect);
					ClientToScreen(hWnd, (POINT *)&clipRect.left);
					ClientToScreen(hWnd, (POINT *)&clipRect.right);
					ClipCursor(&clipRect);
					SetCapture(hWnd);
				}
			} else {
				main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
				alt_mem = false;
			};

			return 0; // Return To The Message Loop
		}

		case WM_PAINT:

			Main::force_redraw();
			break;

		case WM_SYSCOMMAND: // Intercept System Commands
		{
			switch (wParam) // Check System Calls
			{
				case SC_SCREENSAVE: // Screensaver Trying To Start?
				case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
					return 0; // Prevent From Happening
				case SC_KEYMENU:
					if ((lParam >> 16) <= 0)
						return 0;
			}
			break; // Exit
		}

		case WM_CLOSE: // Did We Receive A Close Message?
		{
			if (main_loop)
				main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
			//force_quit=true;
			return 0; // Jump Back
		}
		case WM_MOUSELEAVE: {

			old_invalid = true;
			outside = true;
			if (main_loop && mouse_mode != MOUSE_MODE_CAPTURED)
				main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
			if (input)
				input->set_mouse_in_window(false);

		} break;
		case WM_MOUSEMOVE: {

			if (outside) {
				//mouse enter

				if (main_loop && mouse_mode != MOUSE_MODE_CAPTURED)
					main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
				if (input)
					input->set_mouse_in_window(true);

				CursorShape c = cursor_shape;
				cursor_shape = CURSOR_MAX;
				set_cursor_shape(c);
				outside = false;

				//Once-Off notification, must call again....
				TRACKMOUSEEVENT tme;
				tme.cbSize = sizeof(TRACKMOUSEEVENT);
				tme.dwFlags = TME_LEAVE;
				tme.hwndTrack = hWnd;
				tme.dwHoverTime = HOVER_DEFAULT;
				TrackMouseEvent(&tme);
			}

			// Don't calculate relative mouse movement if we don't have focus in CAPTURED mode.
			if (!window_has_focus && mouse_mode == MOUSE_MODE_CAPTURED)
				break;
			/*
			LPARAM extra = GetMessageExtraInfo();
			if (IsPenEvent(extra)) {

				int idx = extra & 0x7f;
				_drag_event(idx, uMsg, wParam, lParam);
				if (idx != 0) {
					return 0;
				};
				// fallthrough for mouse event
			};
			*/

			Ref<InputEventMouseMotion> mm;
			mm.instance();

			mm->set_control((wParam & MK_CONTROL) != 0);
			mm->set_shift((wParam & MK_SHIFT) != 0);
			mm->set_alt(alt_mem);

			int bmask = 0;
			bmask |= (wParam & MK_LBUTTON) ? (1 << 0) : 0;
			bmask |= (wParam & MK_RBUTTON) ? (1 << 1) : 0;
			bmask |= (wParam & MK_MBUTTON) ? (1 << 2) : 0;
			mm->set_button_mask(bmask);

			last_button_state = mm->get_button_mask();
			/*mm->get_button_mask()|=(wParam&MK_XBUTTON1)?(1<<5):0;
			mm->get_button_mask()|=(wParam&MK_XBUTTON2)?(1<<6):0;*/
			mm->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));

			if (mouse_mode == MOUSE_MODE_CAPTURED) {

				Point2i c(video_mode.width / 2, video_mode.height / 2);
				old_x = c.x;
				old_y = c.y;

				if (mm->get_position() == c) {
					center = c;
					return 0;
				}

				Point2i ncenter = mm->get_position();
				center = ncenter;
				POINT pos = { (int)c.x, (int)c.y };
				ClientToScreen(hWnd, &pos);
				SetCursorPos(pos.x, pos.y);
			}

			input->set_mouse_position(mm->get_position());
			mm->set_speed(input->get_last_mouse_speed());

			if (old_invalid) {

				old_x = mm->get_position().x;
				old_y = mm->get_position().y;
				old_invalid = false;
			}

			mm->set_relative(Vector2(mm->get_position() - Vector2(old_x, old_y)));
			old_x = mm->get_position().x;
			old_y = mm->get_position().y;
			if (window_has_focus && main_loop)
				input->parse_input_event(mm);

		} break;
		case WM_LBUTTONDOWN:
		case WM_LBUTTONUP:
		case WM_MBUTTONDOWN:
		case WM_MBUTTONUP:
		case WM_RBUTTONDOWN:
		case WM_RBUTTONUP:
		case WM_MOUSEWHEEL:
		case WM_MOUSEHWHEEL:
		case WM_LBUTTONDBLCLK:
		case WM_RBUTTONDBLCLK:
			/*case WM_XBUTTONDOWN:
		case WM_XBUTTONUP: */ {

				/*
			LPARAM extra = GetMessageExtraInfo();
			if (IsPenEvent(extra)) {

				int idx = extra & 0x7f;
				_touch_event(idx, uMsg, wParam, lParam);
				if (idx != 0) {
					return 0;
				};
				// fallthrough for mouse event
			};
			*/

				Ref<InputEventMouseButton> mb;
				mb.instance();

				switch (uMsg) {
					case WM_LBUTTONDOWN: {
						mb->set_pressed(true);
						mb->set_button_index(1);
					} break;
					case WM_LBUTTONUP: {
						mb->set_pressed(false);
						mb->set_button_index(1);
					} break;
					case WM_MBUTTONDOWN: {
						mb->set_pressed(true);
						mb->set_button_index(3);

					} break;
					case WM_MBUTTONUP: {
						mb->set_pressed(false);
						mb->set_button_index(3);
					} break;
					case WM_RBUTTONDOWN: {
						mb->set_pressed(true);
						mb->set_button_index(2);
					} break;
					case WM_RBUTTONUP: {
						mb->set_pressed(false);
						mb->set_button_index(2);
					} break;
					case WM_LBUTTONDBLCLK: {

						mb->set_pressed(true);
						mb->set_button_index(1);
						mb->set_doubleclick(true);
					} break;
					case WM_RBUTTONDBLCLK: {

						mb->set_pressed(true);
						mb->set_button_index(2);
						mb->set_doubleclick(true);
					} break;
					case WM_MOUSEWHEEL: {

						mb->set_pressed(true);
						int motion = (short)HIWORD(wParam);
						if (!motion)
							return 0;

						if (motion > 0)
							mb->set_button_index(BUTTON_WHEEL_UP);
						else
							mb->set_button_index(BUTTON_WHEEL_DOWN);

					} break;
					case WM_MOUSEHWHEEL: {

						mb->set_pressed(true);
						int motion = (short)HIWORD(wParam);
						if (!motion)
							return 0;

						if (motion < 0) {
							mb->set_button_index(BUTTON_WHEEL_LEFT);
							mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA));
						} else {
							mb->set_button_index(BUTTON_WHEEL_RIGHT);
							mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA));
						}
					} break;
					/*
				case WM_XBUTTONDOWN: {
					mb->is_pressed()=true;
					mb->get_button_index()=(HIWORD(wParam)==XBUTTON1)?6:7;
				} break;
				case WM_XBUTTONUP:
					mb->is_pressed()=true;
					mb->get_button_index()=(HIWORD(wParam)==XBUTTON1)?6:7;
				} break;*/
					default: { return 0; }
				}

				mb->set_control((wParam & MK_CONTROL) != 0);
				mb->set_shift((wParam & MK_SHIFT) != 0);
				mb->set_alt(alt_mem);
				//mb->get_alt()=(wParam&MK_MENU)!=0;
				int bmask = 0;
				bmask |= (wParam & MK_LBUTTON) ? (1 << 0) : 0;
				bmask |= (wParam & MK_RBUTTON) ? (1 << 1) : 0;
				bmask |= (wParam & MK_MBUTTON) ? (1 << 2) : 0;
				mb->set_button_mask(bmask);

				last_button_state = mb->get_button_mask();
				/*
			mb->get_button_mask()|=(wParam&MK_XBUTTON1)?(1<<5):0;
			mb->get_button_mask()|=(wParam&MK_XBUTTON2)?(1<<6):0;*/
				mb->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));

				if (mouse_mode == MOUSE_MODE_CAPTURED) {

					mb->set_position(Vector2(old_x, old_y));
				}

				if (uMsg != WM_MOUSEWHEEL) {
					if (mb->is_pressed()) {

						if (++pressrc > 0)
							SetCapture(hWnd);
					} else {

						if (--pressrc <= 0) {
							ReleaseCapture();
							pressrc = 0;
						}
					}
				} else if (mouse_mode != MOUSE_MODE_CAPTURED) {
					// for reasons unknown to mankind, wheel comes in screen cordinates
					POINT coords;
					coords.x = mb->get_position().x;
					coords.y = mb->get_position().y;

					ScreenToClient(hWnd, &coords);

					mb->set_position(Vector2(coords.x, coords.y));
				}

				mb->set_global_position(mb->get_position());

				if (main_loop) {
					input->parse_input_event(mb);
					if (mb->is_pressed() && mb->get_button_index() > 3) {
						//send release for mouse wheel
						Ref<InputEventMouseButton> mbd = mb->duplicate();
						mbd->set_pressed(false);
						input->parse_input_event(mbd);
					}
				}
			}
			break;

		case WM_SIZE: {
			int window_w = LOWORD(lParam);
			int window_h = HIWORD(lParam);
			if (window_w > 0 && window_h > 0) {
				video_mode.width = window_w;
				video_mode.height = window_h;
			}
			//return 0;								// Jump Back
		} break;

		case WM_ENTERSIZEMOVE: {
			move_timer_id = SetTimer(hWnd, 1, USER_TIMER_MINIMUM, (TIMERPROC)NULL);
		} break;
		case WM_EXITSIZEMOVE: {
			KillTimer(hWnd, move_timer_id);
		} break;
		case WM_TIMER: {
			if (wParam == move_timer_id) {
				process_key_events();
				Main::iteration();
			}
		} break;

		case WM_SYSKEYDOWN:
		case WM_SYSKEYUP:
		case WM_KEYUP:
		case WM_KEYDOWN: {

			if (wParam == VK_SHIFT)
				shift_mem = uMsg == WM_KEYDOWN;
			if (wParam == VK_CONTROL)
				control_mem = uMsg == WM_KEYDOWN;
			if (wParam == VK_MENU) {
				alt_mem = (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN);
				if (lParam & (1 << 24))
					gr_mem = alt_mem;
			}

			/*
			if (wParam==VK_WIN) TODO wtf is this?
				meta_mem=uMsg==WM_KEYDOWN;
			*/

		} //fallthrough
		case WM_CHAR: {

			ERR_BREAK(key_event_pos >= KEY_EVENT_BUFFER_SIZE);

			// Make sure we don't include modifiers for the modifier key itself.
			KeyEvent ke;
			ke.shift = (wParam != VK_SHIFT) ? shift_mem : false;
			ke.alt = (!(wParam == VK_MENU && (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN))) ? alt_mem : false;
			ke.control = (wParam != VK_CONTROL) ? control_mem : false;
			ke.meta = meta_mem;
			ke.uMsg = uMsg;

			if (ke.uMsg == WM_SYSKEYDOWN)
				ke.uMsg = WM_KEYDOWN;
			if (ke.uMsg == WM_SYSKEYUP)
				ke.uMsg = WM_KEYUP;

			/*if (ke.uMsg==WM_KEYDOWN && alt_mem && uMsg!=WM_SYSKEYDOWN) {
				//altgr hack for intl keyboards, not sure how good it is
				//windows is weeeeird
				ke.mod_state.alt=false;
				ke.mod_state.control=false;
				print_line("")
			}*/

			ke.wParam = wParam;
			ke.lParam = lParam;
			key_event_buffer[key_event_pos++] = ke;

		} break;
		case WM_INPUTLANGCHANGEREQUEST: {

			print_line("input lang change");
		} break;

#if WINVER >= 0x0601 // for windows 7
		case WM_TOUCH: {

			BOOL bHandled = FALSE;
			UINT cInputs = LOWORD(wParam);
			PTOUCHINPUT pInputs = memnew_arr(TOUCHINPUT, cInputs);
			if (pInputs) {
				if (GetTouchInputInfo((HTOUCHINPUT)lParam, cInputs, pInputs, sizeof(TOUCHINPUT))) {
					for (UINT i = 0; i < cInputs; i++) {
						TOUCHINPUT ti = pInputs[i];
						//do something with each touch input entry
						if (ti.dwFlags & TOUCHEVENTF_MOVE) {

							_drag_event(ti.x / 100, ti.y / 100, ti.dwID);
						} else if (ti.dwFlags & (TOUCHEVENTF_UP | TOUCHEVENTF_DOWN)) {

							_touch_event(ti.dwFlags & TOUCHEVENTF_DOWN != 0, ti.x / 100, ti.y / 100, ti.dwID);
						};
					}
					bHandled = TRUE;
				} else {
					/* handle the error here */
				}
				memdelete_arr(pInputs);
			} else {
				/* handle the error here, probably out of memory */
			}
			if (bHandled) {
				CloseTouchInputHandle((HTOUCHINPUT)lParam);
				return 0;
			};

		} break;

#endif
		case WM_DEVICECHANGE: {

			joypad->probe_joypads();
		} break;
		case WM_SETCURSOR: {
			if (LOWORD(lParam) == HTCLIENT) {
				if (window_has_focus && (mouse_mode == MOUSE_MODE_HIDDEN || mouse_mode == MOUSE_MODE_CAPTURED)) {
					//Hide the cursor
					if (hCursor == NULL)
						hCursor = SetCursor(NULL);
					else
						SetCursor(NULL);
				} else {
					if (hCursor != NULL) {
						SetCursor(hCursor);
						hCursor = NULL;
					}
				}
			}

		} break;
		case WM_DROPFILES: {

			HDROP hDropInfo = (HDROP)wParam;
			const int buffsize = 4096;
			wchar_t buf[buffsize];

			int fcount = DragQueryFileW(hDropInfo, 0xFFFFFFFF, NULL, 0);

			Vector<String> files;

			for (int i = 0; i < fcount; i++) {

				DragQueryFileW(hDropInfo, i, buf, buffsize);
				String file = buf;
				files.push_back(file);
			}

			if (files.size() && main_loop) {
				main_loop->drop_files(files, 0);
			}

		} break;

		default: {

			if (user_proc) {

				return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
			};
		};
	}

	return DefWindowProcW(hWnd, uMsg, wParam, lParam);
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {

	OS_Windows *os_win = static_cast<OS_Windows *>(OS::get_singleton());
	if (os_win)
		return os_win->WndProc(hWnd, uMsg, wParam, lParam);
	else
		return DefWindowProcW(hWnd, uMsg, wParam, lParam);
}

void OS_Windows::process_key_events() {

	for (int i = 0; i < key_event_pos; i++) {

		KeyEvent &ke = key_event_buffer[i];
		switch (ke.uMsg) {

			case WM_CHAR: {
				if ((i == 0 && ke.uMsg == WM_CHAR) || (i > 0 && key_event_buffer[i - 1].uMsg == WM_CHAR)) {
					Ref<InputEventKey> k;
					k.instance();

					k->set_shift(ke.shift);
					k->set_alt(ke.alt);
					k->set_control(ke.control);
					k->set_metakey(ke.meta);
					k->set_pressed(true);
					k->set_scancode(KeyMappingWindows::get_keysym(ke.wParam));
					k->set_unicode(ke.wParam);
					if (k->get_unicode() && gr_mem) {
						k->set_alt(false);
						k->set_control(false);
					}

					if (k->get_unicode() < 32)
						k->set_unicode(0);

					input->parse_input_event(k);
				}

				//do nothing
			} break;
			case WM_KEYUP:
			case WM_KEYDOWN: {

				Ref<InputEventKey> k;
				k.instance();

				k->set_shift(ke.shift);
				k->set_alt(ke.alt);
				k->set_control(ke.control);
				k->set_metakey(ke.meta);

				k->set_pressed(ke.uMsg == WM_KEYDOWN);

				if ((ke.lParam & (1 << 24)) && (ke.wParam == VK_RETURN)) {
					// Special case for Numpad Enter key
					k->set_scancode(KEY_KP_ENTER);
				} else {
					k->set_scancode(KeyMappingWindows::get_keysym(ke.wParam));
				}

				if (i + 1 < key_event_pos && key_event_buffer[i + 1].uMsg == WM_CHAR) {
					k->set_unicode(key_event_buffer[i + 1].wParam);
				}
				if (k->get_unicode() && gr_mem) {
					k->set_alt(false);
					k->set_control(false);
				}

				if (k->get_unicode() < 32)
					k->set_unicode(0);

				k->set_echo((ke.uMsg == WM_KEYDOWN && (ke.lParam & (1 << 30))));

				input->parse_input_event(k);

			} break;
		}
	}

	key_event_pos = 0;
}

enum _MonitorDpiType {
	MDT_Effective_DPI = 0,
	MDT_Angular_DPI = 1,
	MDT_Raw_DPI = 2,
	MDT_Default = MDT_Effective_DPI
};

static int QueryDpiForMonitor(HMONITOR hmon, _MonitorDpiType dpiType = MDT_Default) {

	int dpiX = 96, dpiY = 96;

	static HMODULE Shcore = NULL;
	typedef HRESULT(WINAPI * GetDPIForMonitor_t)(HMONITOR hmonitor, _MonitorDpiType dpiType, UINT * dpiX, UINT * dpiY);
	static GetDPIForMonitor_t getDPIForMonitor = NULL;

	if (Shcore == NULL) {
		Shcore = LoadLibraryW(L"Shcore.dll");
		getDPIForMonitor = Shcore ? (GetDPIForMonitor_t)GetProcAddress(Shcore, "GetDpiForMonitor") : NULL;

		if ((Shcore == NULL) || (getDPIForMonitor == NULL)) {
			if (Shcore)
				FreeLibrary(Shcore);
			Shcore = (HMODULE)INVALID_HANDLE_VALUE;
		}
	}

	UINT x = 0, y = 0;
	HRESULT hr = E_FAIL;
	bool bSet = false;
	if (hmon && (Shcore != (HMODULE)INVALID_HANDLE_VALUE)) {
		hr = getDPIForMonitor(hmon, dpiType /*MDT_Effective_DPI*/, &x, &y);
		if (SUCCEEDED(hr) && (x > 0) && (y > 0)) {

			dpiX = (int)x;
			dpiY = (int)y;
		}
	} else {
		static int overallX = 0, overallY = 0;
		if (overallX <= 0 || overallY <= 0) {
			HDC hdc = GetDC(NULL);
			if (hdc) {
				overallX = GetDeviceCaps(hdc, LOGPIXELSX);
				overallY = GetDeviceCaps(hdc, LOGPIXELSY);
				ReleaseDC(NULL, hdc);
			}
		}
		if (overallX > 0 && overallY > 0) {
			dpiX = overallX;
			dpiY = overallY;
		}
	}

	return (dpiX + dpiY) / 2;
}

typedef enum _SHC_PROCESS_DPI_AWARENESS {
	SHC_PROCESS_DPI_UNAWARE = 0,
	SHC_PROCESS_SYSTEM_DPI_AWARE = 1,
	SHC_PROCESS_PER_MONITOR_DPI_AWARE = 2
} SHC_PROCESS_DPI_AWARENESS;

void OS_Windows::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {

	main_loop = NULL;
	outside = true;
	window_has_focus = true;
	WNDCLASSEXW wc;

	if (is_hidpi_allowed()) {
		HMODULE Shcore = LoadLibraryW(L"Shcore.dll");

		if (Shcore != NULL) {
			typedef HRESULT(WINAPI * SetProcessDpiAwareness_t)(SHC_PROCESS_DPI_AWARENESS);

			SetProcessDpiAwareness_t SetProcessDpiAwareness = (SetProcessDpiAwareness_t)GetProcAddress(Shcore, "SetProcessDpiAwareness");

			if (SetProcessDpiAwareness) {
				SetProcessDpiAwareness(SHC_PROCESS_SYSTEM_DPI_AWARE);
			}
		}
	}

	video_mode = p_desired;
	//printf("**************** desired %s, mode %s\n", p_desired.fullscreen?"true":"false", video_mode.fullscreen?"true":"false");
	RECT WindowRect;

	WindowRect.left = 0;
	WindowRect.right = video_mode.width;
	WindowRect.top = 0;
	WindowRect.bottom = video_mode.height;

	memset(&wc, 0, sizeof(WNDCLASSEXW));
	wc.cbSize = sizeof(WNDCLASSEXW);
	wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_DBLCLKS;
	wc.lpfnWndProc = (WNDPROC)::WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	//wc.hInstance = hInstance;
	wc.hInstance = godot_hinstance ? godot_hinstance : GetModuleHandle(NULL);
	wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
	wc.hCursor = NULL; //LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = NULL;
	wc.lpszMenuName = NULL;
	wc.lpszClassName = L"Engine";

	if (!RegisterClassExW(&wc)) {
		MessageBox(NULL, "Failed To Register The Window Class.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
		return; // Return
	}

	pre_fs_valid = true;
	if (video_mode.fullscreen) {

		DEVMODE current;
		memset(&current, 0, sizeof(current));
		EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &current);

		WindowRect.right = current.dmPelsWidth;
		WindowRect.bottom = current.dmPelsHeight;

		/*  DEVMODE dmScreenSettings;
		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));
		dmScreenSettings.dmSize=sizeof(dmScreenSettings);
		dmScreenSettings.dmPelsWidth	= video_mode.width;
		dmScreenSettings.dmPelsHeight	= video_mode.height;
		dmScreenSettings.dmBitsPerPel	= current.dmBitsPerPel;
		dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

		LONG err = ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN);
		if (err!=DISP_CHANGE_SUCCESSFUL) {

			video_mode.fullscreen=false;
		}*/
		pre_fs_valid = false;
	}

	DWORD dwExStyle;
	DWORD dwStyle;

	if (video_mode.fullscreen || video_mode.borderless_window) {

		dwExStyle = WS_EX_APPWINDOW;
		dwStyle = WS_POPUP;

	} else {
		dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
		dwStyle = WS_OVERLAPPEDWINDOW;
		if (!video_mode.resizable) {
			dwStyle &= ~WS_THICKFRAME;
			dwStyle &= ~WS_MAXIMIZEBOX;
		}
	}

	AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);

	char *windowid = getenv("GODOT_WINDOWID");
	if (windowid) {

// strtoull on mingw
#ifdef MINGW_ENABLED
		hWnd = (HWND)strtoull(windowid, NULL, 0);
#else
		hWnd = (HWND)_strtoui64(windowid, NULL, 0);
#endif
		SetLastError(0);
		user_proc = (WNDPROC)GetWindowLongPtr(hWnd, GWLP_WNDPROC);
		SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)(WNDPROC)::WndProc);
		DWORD le = GetLastError();
		if (user_proc == 0 && le != 0) {

			printf("Error setting WNDPROC: %li\n", le);
		};
		LONG_PTR proc = GetWindowLongPtr(hWnd, GWLP_WNDPROC);

		RECT rect;
		if (!GetClientRect(hWnd, &rect)) {
			MessageBoxW(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
			return; // Return FALSE
		};
		video_mode.width = rect.right;
		video_mode.height = rect.bottom;
		video_mode.fullscreen = false;
	} else {

		hWnd = CreateWindowExW(
				dwExStyle,
				L"Engine", L"",
				dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
				(GetSystemMetrics(SM_CXSCREEN) - WindowRect.right) / 2,
				(GetSystemMetrics(SM_CYSCREEN) - WindowRect.bottom) / 2,
				WindowRect.right - WindowRect.left,
				WindowRect.bottom - WindowRect.top,
				NULL, NULL, hInstance, NULL);
		if (!hWnd) {
			MessageBoxW(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
			return; // Return FALSE
		}
	};

#if defined(OPENGL_ENABLED)
	gl_context = memnew(ContextGL_Win(hWnd, true));
	gl_context->initialize();

	RasterizerGLES3::register_config();

	RasterizerGLES3::make_current();
#endif

	visual_server = memnew(VisualServerRaster);
	if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {

		visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD));
	}

	/*
		DEVMODE dmScreenSettings;					// Device Mode
		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));		// Makes Sure Memory's Cleared
		dmScreenSettings.dmSize=sizeof(dmScreenSettings);		// Size Of The Devmode Structure
		dmScreenSettings.dmPelsWidth	= width;			// Selected Screen Width
		dmScreenSettings.dmPelsHeight	= height;			// Selected Screen Height
		dmScreenSettings.dmBitsPerPel	= bits;				// Selected Bits Per Pixel
		dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
		if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)




  */
	visual_server->init();

	input = memnew(InputDefault);
	joypad = memnew(JoypadWindows(input, &hWnd));

	power_manager = memnew(PowerWindows);

	AudioDriverManager::initialize(p_audio_driver);

	TRACKMOUSEEVENT tme;
	tme.cbSize = sizeof(TRACKMOUSEEVENT);
	tme.dwFlags = TME_LEAVE;
	tme.hwndTrack = hWnd;
	tme.dwHoverTime = HOVER_DEFAULT;
	TrackMouseEvent(&tme);

	//RegisterTouchWindow(hWnd, 0); // Windows 7

	_ensure_user_data_dir();

	DragAcceptFiles(hWnd, true);

	move_timer_id = 1;

	if (!is_no_window_mode_enabled()) {
		ShowWindow(hWnd, SW_SHOW); // Show The Window
		SetForegroundWindow(hWnd); // Slightly Higher Priority
		SetFocus(hWnd); // Sets Keyboard Focus To
	}
}

void OS_Windows::set_clipboard(const String &p_text) {

	if (!OpenClipboard(hWnd)) {
		ERR_EXPLAIN("Unable to open clipboard.");
		ERR_FAIL();
	};
	EmptyClipboard();

	HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, (p_text.length() + 1) * sizeof(CharType));
	if (mem == NULL) {
		ERR_EXPLAIN("Unable to allocate memory for clipboard contents.");
		ERR_FAIL();
	};
	LPWSTR lptstrCopy = (LPWSTR)GlobalLock(mem);
	memcpy(lptstrCopy, p_text.c_str(), (p_text.length() + 1) * sizeof(CharType));
	//memset((lptstrCopy + p_text.length()), 0, sizeof(CharType));
	GlobalUnlock(mem);

	SetClipboardData(CF_UNICODETEXT, mem);

	// set the CF_TEXT version (not needed?)
	CharString utf8 = p_text.utf8();
	mem = GlobalAlloc(GMEM_MOVEABLE, utf8.length() + 1);
	if (mem == NULL) {
		ERR_EXPLAIN("Unable to allocate memory for clipboard contents.");
		ERR_FAIL();
{'fraction_non_alphanumeric': 0.14021607448097317, 'fraction_numerical': 0.008928423253729858, 'mean_word_length': 3.5218370103556955, 'pattern_counts': {'":': 4, '<': 123, '<?xml version=': 0, '>': 317, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 6, 'word_list_counts': {'cursed_substrings.json': 26, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6622903', 'n_tokens_mistral': 26264, 'n_tokens_neox': 22222, 'n_words': 4337}