1 /*************************************************************************/
2 /*  app.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 //
31 // This file demonstrates how to initialize EGL in a Windows Store app, using ICoreWindow.
32 //
33 
34 #include "app.h"
35 
36 #include "core/os/dir_access.h"
37 #include "core/os/file_access.h"
38 #include "core/os/keyboard.h"
39 
40 #include "main/main.h"
41 
42 #include "platform/windows/key_mapping_win.h"
43 
44 #include <collection.h>
45 
46 using namespace Windows::ApplicationModel::Core;
47 using namespace Windows::ApplicationModel::Activation;
48 using namespace Windows::UI::Core;
49 using namespace Windows::UI::Input;
50 using namespace Windows::Devices::Input;
51 using namespace Windows::UI::Xaml::Input;
52 using namespace Windows::Foundation;
53 using namespace Windows::Graphics::Display;
54 using namespace Windows::System;
55 using namespace Windows::System::Threading::Core;
56 using namespace Microsoft::WRL;
57 
58 using namespace GodotWinRT;
59 
60 // Helper to convert a length in device-independent pixels (DIPs) to a length in physical pixels.
ConvertDipsToPixels(float dips,float dpi)61 inline float ConvertDipsToPixels(float dips, float dpi) {
62 	static const float dipsPerInch = 96.0f;
63 	return floor(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.
64 }
65 
66 // Implementation of the IFrameworkViewSource interface, necessary to run our app.
67 ref class GodotWinrtViewSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource {
68 public:
69 	virtual Windows::ApplicationModel::Core::IFrameworkView ^ CreateView() {
70 		return ref new App();
71 	}
72 };
73 
74 // The main function creates an IFrameworkViewSource for our app, and runs the app.
75 [Platform::MTAThread] int main(Platform::Array<Platform::String ^> ^) {
76 	auto godotApplicationSource = ref new GodotWinrtViewSource();
77 	CoreApplication::Run(godotApplicationSource);
78 	return 0;
79 }
80 
App()81 App::App() :
82 		mWindowClosed(false),
83 		mWindowVisible(true),
84 		mWindowWidth(0),
85 		mWindowHeight(0),
86 		mEglDisplay(EGL_NO_DISPLAY),
87 		mEglContext(EGL_NO_CONTEXT),
88 		mEglSurface(EGL_NO_SURFACE),
89 		number_of_contacts(0) {
90 }
91 
92 // The first method called when the IFrameworkView is being created.
93 void App::Initialize(CoreApplicationView ^ applicationView) {
94 	// Register event handlers for app lifecycle. This example includes Activated, so that we
95 	// can make the CoreWindow active and start rendering on the window.
96 	applicationView->Activated +=
97 			ref new TypedEventHandler<CoreApplicationView ^, IActivatedEventArgs ^>(this, &App::OnActivated);
98 
99 	// Logic for other event handlers could go here.
100 	// Information about the Suspending and Resuming event handlers can be found here:
101 	// http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh994930.aspx
102 
103 	os = new OSWinrt;
104 }
105 
106 // Called when the CoreWindow object is created (or re-created).
107 void App::SetWindow(CoreWindow ^ p_window) {
108 	window = p_window;
109 	window->VisibilityChanged +=
110 			ref new TypedEventHandler<CoreWindow ^, VisibilityChangedEventArgs ^>(this, &App::OnVisibilityChanged);
111 
112 	window->Closed +=
113 			ref new TypedEventHandler<CoreWindow ^, CoreWindowEventArgs ^>(this, &App::OnWindowClosed);
114 
115 	window->SizeChanged +=
116 			ref new TypedEventHandler<CoreWindow ^, WindowSizeChangedEventArgs ^>(this, &App::OnWindowSizeChanged);
117 
118 #if !(WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
119 	// Disable all pointer visual feedback for better performance when touching.
120 	// This is not supported on Windows Phone applications.
121 	auto pointerVisualizationSettings = PointerVisualizationSettings::GetForCurrentView();
122 	pointerVisualizationSettings->IsContactFeedbackEnabled = false;
123 	pointerVisualizationSettings->IsBarrelButtonFeedbackEnabled = false;
124 #endif
125 
126 	window->PointerPressed +=
127 			ref new TypedEventHandler<CoreWindow ^, PointerEventArgs ^>(this, &App::OnPointerPressed);
128 	window->PointerMoved +=
129 			ref new TypedEventHandler<CoreWindow ^, PointerEventArgs ^>(this, &App::OnPointerMoved);
130 	window->PointerReleased +=
131 			ref new TypedEventHandler<CoreWindow ^, PointerEventArgs ^>(this, &App::OnPointerReleased);
132 	window->PointerWheelChanged +=
133 			ref new TypedEventHandler<CoreWindow ^, PointerEventArgs ^>(this, &App::OnPointerWheelChanged);
134 
135 	mouseChangedNotifier = SignalNotifier::AttachToEvent(L"os_mouse_mode_changed", ref new SignalHandler(
136 																						   this, &App::OnMouseModeChanged));
137 
138 	mouseChangedNotifier->Enable();
139 
140 	window->CharacterReceived +=
141 			ref new TypedEventHandler<CoreWindow ^, CharacterReceivedEventArgs ^>(this, &App::OnCharacterReceived);
142 	window->KeyDown +=
143 			ref new TypedEventHandler<CoreWindow ^, KeyEventArgs ^>(this, &App::OnKeyDown);
144 	window->KeyUp +=
145 			ref new TypedEventHandler<CoreWindow ^, KeyEventArgs ^>(this, &App::OnKeyUp);
146 
147 	unsigned int argc;
148 	char **argv = get_command_line(&argc);
149 
150 	Main::setup("winrt", argc, argv, false);
151 
152 	// The CoreWindow has been created, so EGL can be initialized.
153 	ContextEGL *context = memnew(ContextEGL(window));
154 	os->set_gl_context(context);
155 	UpdateWindowSize(Size(window->Bounds.Width, window->Bounds.Height));
156 
157 	Main::setup2();
158 }
159 
160 static int _get_button(Windows::UI::Input::PointerPoint ^ pt) {
161 
162 	using namespace Windows::UI::Input;
163 
164 #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
165 	return BUTTON_LEFT;
166 #else
167 	switch (pt->Properties->PointerUpdateKind) {
168 		case PointerUpdateKind::LeftButtonPressed:
169 		case PointerUpdateKind::LeftButtonReleased:
170 			return BUTTON_LEFT;
171 
172 		case PointerUpdateKind::RightButtonPressed:
173 		case PointerUpdateKind::RightButtonReleased:
174 			return BUTTON_RIGHT;
175 
176 		case PointerUpdateKind::MiddleButtonPressed:
177 		case PointerUpdateKind::MiddleButtonReleased:
178 			return BUTTON_MIDDLE;
179 
180 		case PointerUpdateKind::XButton1Pressed:
181 		case PointerUpdateKind::XButton1Released:
182 			return BUTTON_WHEEL_UP;
183 
184 		case PointerUpdateKind::XButton2Pressed:
185 		case PointerUpdateKind::XButton2Released:
186 			return BUTTON_WHEEL_DOWN;
187 
188 		default:
189 			break;
190 	}
191 #endif
192 
193 	return 0;
194 };
195 
196 static bool _is_touch(Windows::UI::Input::PointerPoint ^ pointerPoint) {
197 #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
198 	return true;
199 #else
200 	using namespace Windows::Devices::Input;
201 	switch (pointerPoint->PointerDevice->PointerDeviceType) {
202 		case PointerDeviceType::Touch:
203 		case PointerDeviceType::Pen:
204 			return true;
205 		default:
206 			return false;
207 	}
208 #endif
209 }
210 
211 static Windows::Foundation::Point _get_pixel_position(CoreWindow ^ window, Windows::Foundation::Point rawPosition, OS *os) {
212 
213 	Windows::Foundation::Point outputPosition;
214 
215 // Compute coordinates normalized from 0..1.
216 // If the coordinates need to be sized to the SDL window,
217 // we'll do that after.
218 #if 1 || WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
219 	outputPosition.X = rawPosition.X / window->Bounds.Width;
220 	outputPosition.Y = rawPosition.Y / window->Bounds.Height;
221 #else
222 	switch (DisplayProperties::CurrentOrientation) {
223 		case DisplayOrientations::Portrait:
224 			outputPosition.X = rawPosition.X / window->Bounds.Width;
225 			outputPosition.Y = rawPosition.Y / window->Bounds.Height;
226 			break;
227 		case DisplayOrientations::PortraitFlipped:
228 			outputPosition.X = 1.0f - (rawPosition.X / window->Bounds.Width);
229 			outputPosition.Y = 1.0f - (rawPosition.Y / window->Bounds.Height);
230 			break;
231 		case DisplayOrientations::Landscape:
232 			outputPosition.X = rawPosition.Y / window->Bounds.Height;
233 			outputPosition.Y = 1.0f - (rawPosition.X / window->Bounds.Width);
234 			break;
235 		case DisplayOrientations::LandscapeFlipped:
236 			outputPosition.X = 1.0f - (rawPosition.Y / window->Bounds.Height);
237 			outputPosition.Y = rawPosition.X / window->Bounds.Width;
238 			break;
239 		default:
240 			break;
241 	}
242 #endif
243 
244 	OS::VideoMode vm = os->get_video_mode();
245 	outputPosition.X *= vm.width;
246 	outputPosition.Y *= vm.height;
247 
248 	return outputPosition;
249 };
250 
_get_finger(uint32_t p_touch_id)251 static int _get_finger(uint32_t p_touch_id) {
252 
253 	return p_touch_id % 31; // for now
254 };
255 
256 void App::pointer_event(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args, bool p_pressed, bool p_is_wheel) {
257 
258 	Windows::UI::Input::PointerPoint ^ point = args->CurrentPoint;
259 	Windows::Foundation::Point pos = _get_pixel_position(window, point->Position, os);
260 	int but = _get_button(point);
261 	if (_is_touch(point)) {
262 
263 		InputEvent event;
264 		event.type = InputEvent::SCREEN_TOUCH;
265 		event.device = 0;
266 		event.screen_touch.pressed = p_pressed;
267 		event.screen_touch.x = pos.X;
268 		event.screen_touch.y = pos.Y;
269 		event.screen_touch.index = _get_finger(point->PointerId);
270 
271 		last_touch_x[event.screen_touch.index] = pos.X;
272 		last_touch_y[event.screen_touch.index] = pos.Y;
273 
274 		os->input_event(event);
275 		if (number_of_contacts > 1)
276 			return;
277 
278 	}; // fallthrought of sorts
279 
280 	InputEvent event;
281 	event.type = InputEvent::MOUSE_BUTTON;
282 	event.device = 0;
283 	event.mouse_button.pressed = p_pressed;
284 	event.mouse_button.button_index = but;
285 	event.mouse_button.x = pos.X;
286 	event.mouse_button.y = pos.Y;
287 	event.mouse_button.global_x = pos.X;
288 	event.mouse_button.global_y = pos.Y;
289 
290 	if (p_is_wheel) {
291 		if (point->Properties->MouseWheelDelta > 0) {
292 			event.mouse_button.button_index = point->Properties->IsHorizontalMouseWheel ? BUTTON_WHEEL_RIGHT : BUTTON_WHEEL_UP;
293 		} else if (point->Properties->MouseWheelDelta < 0) {
294 			event.mouse_button.button_index = point->Properties->IsHorizontalMouseWheel ? BUTTON_WHEEL_LEFT : BUTTON_WHEEL_DOWN;
295 		}
296 	}
297 
298 	last_touch_x[31] = pos.X;
299 	last_touch_y[31] = pos.Y;
300 
301 	os->input_event(event);
302 };
303 
304 void App::OnPointerPressed(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args) {
305 
306 	number_of_contacts++;
307 	pointer_event(sender, args, true);
308 };
309 
310 void App::OnPointerReleased(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args) {
311 
312 	number_of_contacts--;
313 	pointer_event(sender, args, false);
314 };
315 
316 void App::OnPointerWheelChanged(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args) {
317 
318 	pointer_event(sender, args, true, true);
319 }
320 
321 void App::OnMouseModeChanged(Windows::System::Threading::Core::SignalNotifier ^ signalNotifier, bool timedOut) {
322 
323 	OS::MouseMode mode = os->get_mouse_mode();
324 	SignalNotifier ^ notifier = mouseChangedNotifier;
325 
326 	window->Dispatcher->RunAsync(
327 			CoreDispatcherPriority::High,
328 			ref new DispatchedHandler(
__anoncf75d2040102() 329 					[mode, notifier, this]() {
330 						if (mode == OS::MOUSE_MODE_CAPTURED) {
331 
332 							this->MouseMovedToken = MouseDevice::GetForCurrentView()->MouseMoved +=
333 									ref new TypedEventHandler<MouseDevice ^, MouseEventArgs ^>(this, &App::OnMouseMoved);
334 
335 						} else {
336 
337 							MouseDevice::GetForCurrentView()->MouseMoved -= MouseMovedToken;
338 						}
339 
340 						notifier->Enable();
341 					}));
342 
343 	ResetEvent(os->mouse_mode_changed);
344 }
345 
346 void App::OnPointerMoved(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args) {
347 
348 	Windows::UI::Input::PointerPoint ^ point = args->CurrentPoint;
349 	Windows::Foundation::Point pos = _get_pixel_position(window, point->Position, os);
350 
351 	if (point->IsInContact && _is_touch(point)) {
352 
353 		InputEvent event;
354 		event.type = InputEvent::SCREEN_DRAG;
355 		event.device = 0;
356 		event.screen_drag.x = pos.X;
357 		event.screen_drag.y = pos.Y;
358 		event.screen_drag.index = _get_finger(point->PointerId);
359 		event.screen_drag.relative_x = event.screen_drag.x - last_touch_x[event.screen_drag.index];
360 		event.screen_drag.relative_y = event.screen_drag.y - last_touch_y[event.screen_drag.index];
361 
362 		os->input_event(event);
363 		if (number_of_contacts > 1)
364 			return;
365 
366 	}; // fallthrought of sorts
367 
368 	// In case the mouse grabbed, MouseMoved will handle this
369 	if (os->get_mouse_mode() == OS::MouseMode::MOUSE_MODE_CAPTURED)
370 		return;
371 
372 	InputEvent event;
373 	event.type = InputEvent::MOUSE_MOTION;
374 	event.device = 0;
375 	event.mouse_motion.x = pos.X;
376 	event.mouse_motion.y = pos.Y;
377 	event.mouse_motion.global_x = pos.X;
378 	event.mouse_motion.global_y = pos.Y;
379 	event.mouse_motion.relative_x = pos.X - last_touch_x[31];
380 	event.mouse_motion.relative_y = pos.Y - last_touch_y[31];
381 
382 	last_mouse_pos = pos;
383 
384 	os->input_event(event);
385 }
386 
387 void App::OnMouseMoved(MouseDevice ^ mouse_device, MouseEventArgs ^ args) {
388 
389 	// In case the mouse isn't grabbed, PointerMoved will handle this
390 	if (os->get_mouse_mode() != OS::MouseMode::MOUSE_MODE_CAPTURED)
391 		return;
392 
393 	Windows::Foundation::Point pos;
394 	pos.X = last_mouse_pos.X + args->MouseDelta.X;
395 	pos.Y = last_mouse_pos.Y + args->MouseDelta.Y;
396 
397 	InputEvent event;
398 	event.type = InputEvent::MOUSE_MOTION;
399 	event.device = 0;
400 	event.mouse_motion.x = pos.X;
401 	event.mouse_motion.y = pos.Y;
402 	event.mouse_motion.global_x = pos.X;
403 	event.mouse_motion.global_y = pos.Y;
404 	event.mouse_motion.relative_x = args->MouseDelta.X;
405 	event.mouse_motion.relative_y = args->MouseDelta.Y;
406 
407 	last_mouse_pos = pos;
408 
409 	os->input_event(event);
410 }
411 
412 void App::key_event(Windows::UI::Core::CoreWindow ^ sender, bool p_pressed, Windows::UI::Core::KeyEventArgs ^ key_args, Windows::UI::Core::CharacterReceivedEventArgs ^ char_args) {
413 
414 	OSWinrt::KeyEvent ke;
415 
416 	InputModifierState mod;
417 	mod.meta = false;
418 	mod.command = false;
419 	mod.control = sender->GetAsyncKeyState(VirtualKey::Control) == CoreVirtualKeyStates::Down;
420 	mod.alt = sender->GetAsyncKeyState(VirtualKey::Menu) == CoreVirtualKeyStates::Down;
421 	mod.shift = sender->GetAsyncKeyState(VirtualKey::Shift) == CoreVirtualKeyStates::Down;
422 	ke.mod_state = mod;
423 
424 	ke.pressed = p_pressed;
425 
426 	if (key_args != nullptr) {
427 
428 		ke.type = OSWinrt::KeyEvent::MessageType::KEY_EVENT_MESSAGE;
429 		ke.unicode = 0;
430 		ke.scancode = KeyMappingWindows::get_keysym((unsigned int)key_args->VirtualKey);
431 		ke.echo = (!p_pressed && !key_args->KeyStatus.IsKeyReleased) || (p_pressed && key_args->KeyStatus.WasKeyDown);
432 
433 	} else {
434 
435 		ke.type = OSWinrt::KeyEvent::MessageType::CHAR_EVENT_MESSAGE;
436 		ke.unicode = char_args->KeyCode;
437 		ke.scancode = 0;
438 		ke.echo = (!p_pressed && !char_args->KeyStatus.IsKeyReleased) || (p_pressed && char_args->KeyStatus.WasKeyDown);
439 	}
440 
441 	os->queue_key_event(ke);
442 }
443 void App::OnKeyDown(CoreWindow ^ sender, KeyEventArgs ^ args) {
444 	key_event(sender, true, args);
445 }
446 
447 void App::OnKeyUp(CoreWindow ^ sender, KeyEventArgs ^ args) {
448 	key_event(sender, false, args);
449 }
450 
451 void App::OnCharacterReceived(CoreWindow ^ sender, CharacterReceivedEventArgs ^ args) {
452 	key_event(sender, true, nullptr, args);
453 }
454 
455 // Initializes scene resources
456 void App::Load(Platform::String ^ entryPoint) {
457 }
458 
459 // This method is called after the window becomes active.
Run()460 void App::Run() {
461 	if (Main::start())
462 		os->run();
463 }
464 
465 // Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView
466 // class is torn down while the app is in the foreground.
Uninitialize()467 void App::Uninitialize() {
468 	Main::cleanup();
469 	delete os;
470 }
471 
472 // Application lifecycle event handler.
473 void App::OnActivated(CoreApplicationView ^ applicationView, IActivatedEventArgs ^ args) {
474 	// Run() won't start until the CoreWindow is activated.
475 	CoreWindow::GetForCurrentThread()->Activate();
476 }
477 
478 // Window event handlers.
479 void App::OnVisibilityChanged(CoreWindow ^ sender, VisibilityChangedEventArgs ^ args) {
480 	mWindowVisible = args->Visible;
481 }
482 
483 void App::OnWindowClosed(CoreWindow ^ sender, CoreWindowEventArgs ^ args) {
484 	mWindowClosed = true;
485 }
486 
487 void App::OnWindowSizeChanged(CoreWindow ^ sender, WindowSizeChangedEventArgs ^ args) {
488 #if (WINAPI_FAMILY == WINAPI_FAMILY_PC_APP)
489 	// On Windows 8.1, apps are resized when they are snapped alongside other apps, or when the device is rotated.
490 	// The default framebuffer will be automatically resized when either of these occur.
491 	// In particular, on a 90 degree rotation, the default framebuffer's width and height will switch.
492 	UpdateWindowSize(args->Size);
493 #else if (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
494 	// On Windows Phone 8.1, the window size changes when the device is rotated.
495 	// The default framebuffer will not be automatically resized when this occurs.
496 	// It is therefore up to the app to handle rotation-specific logic in its rendering code.
497 	//os->screen_size_changed();
498 	UpdateWindowSize(args->Size);
499 #endif
500 }
501 
UpdateWindowSize(Size size)502 void App::UpdateWindowSize(Size size) {
503 	float dpi;
504 #if (WINAPI_FAMILY == WINAPI_FAMILY_PC_APP)
505 	DisplayInformation ^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
506 	dpi = currentDisplayInformation->LogicalDpi;
507 #else if (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
508 	dpi = DisplayProperties::LogicalDpi;
509 #endif
510 	Size pixelSize(ConvertDipsToPixels(size.Width, dpi), ConvertDipsToPixels(size.Height, dpi));
511 
512 	mWindowWidth = static_cast<GLsizei>(pixelSize.Width);
513 	mWindowHeight = static_cast<GLsizei>(pixelSize.Height);
514 
515 	OS::VideoMode vm;
516 	vm.width = mWindowWidth;
517 	vm.height = mWindowHeight;
518 	vm.fullscreen = true;
519 	vm.resizable = false;
520 	os->set_video_mode(vm);
521 }
522 
get_command_line(unsigned int * out_argc)523 char **App::get_command_line(unsigned int *out_argc) {
524 
525 	static char *fail_cl[] = { "-path", "game", NULL };
526 	*out_argc = 2;
527 
528 	FILE *f = _wfopen(L"__cl__.cl", L"rb");
529 
530 	if (f == NULL) {
531 
532 		wprintf(L"Couldn't open command line file.");
533 		return fail_cl;
534 	}
535 
536 #define READ_LE_4(v) ((int)(##v[3] & 0xFF) << 24) | ((int)(##v[2] & 0xFF) << 16) | ((int)(##v[1] & 0xFF) << 8) | ((int)(##v[0] & 0xFF))
537 #define CMD_MAX_LEN 65535
538 
539 	uint8_t len[4];
540 	int r = fread(len, sizeof(uint8_t), 4, f);
541 
542 	Platform::Collections::Vector<Platform::String ^> cl;
543 
544 	if (r < 4) {
545 		fclose(f);
546 		wprintf(L"Wrong cmdline length.");
547 		return (fail_cl);
548 	}
549 
550 	int argc = READ_LE_4(len);
551 
552 	for (int i = 0; i < argc; i++) {
553 
554 		r = fread(len, sizeof(uint8_t), 4, f);
555 
556 		if (r < 4) {
557 			fclose(f);
558 			wprintf(L"Wrong cmdline param length.");
559 			return (fail_cl);
560 		}
561 
562 		int strlen = READ_LE_4(len);
563 
564 		if (strlen > CMD_MAX_LEN) {
565 			fclose(f);
566 			wprintf(L"Wrong command length.");
567 			return (fail_cl);
568 		}
569 
570 		char *arg = new char[strlen + 1];
571 		r = fread(arg, sizeof(char), strlen, f);
572 		arg[strlen] = '\0';
573 
574 		if (r == strlen) {
575 
576 			int warg_size = MultiByteToWideChar(CP_UTF8, 0, arg, -1, NULL, 0);
577 			wchar_t *warg = new wchar_t[warg_size];
578 
579 			MultiByteToWideChar(CP_UTF8, 0, arg, -1, warg, warg_size);
580 
581 			cl.Append(ref new Platform::String(warg, warg_size));
582 
583 		} else {
584 
585 			delete[] arg;
586 			fclose(f);
587 			wprintf(L"Error reading command.");
588 			return (fail_cl);
589 		}
590 	}
591 
592 #undef READ_LE_4
593 #undef CMD_MAX_LEN
594 
595 	fclose(f);
596 
597 	char **ret = new char *[cl.Size + 1];
598 
599 	for (int i = 0; i < cl.Size; i++) {
600 
601 		int arg_size = WideCharToMultiByte(CP_UTF8, 0, cl.GetAt(i)->Data(), -1, NULL, 0, NULL, NULL);
602 		char *arg = new char[arg_size];
603 
604 		WideCharToMultiByte(CP_UTF8, 0, cl.GetAt(i)->Data(), -1, arg, arg_size, NULL, NULL);
605 
606 		ret[i] = arg;
607 	}
608 	ret[cl.Size] = NULL;
609 	*out_argc = cl.Size;
610 
611 	return ret;
612 }
613