VirtualBox

source: vbox/trunk/src/VBox/Frontends/VBoxSDL/VBoxSDL.cpp@ 81916

Last change on this file since 81916 was 81537, checked in by vboxsync, 5 years ago

FE/VBoxSDL: Added first support for SDL2 (by setting VBOX_WITH_SDL2). Very rough / hacky by now and needs more testing first before enabling by default. Also fixed non-starting with SDL 1.2.x on Windows hosts.

Known limitations / todos when running with SDL 2 for now:

  • No alpha channel support for cursors.
  • No mouse wheel support.
  • Desktop geometry handling needs a revamp for multi monitor setups.
  • Check / revamp dirty rectangle blitting.
  • OpenGL renderer needs testing wrt texture blitting.
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 182.2 KB
Line 
1/* $Id: VBoxSDL.cpp 81537 2019-10-25 11:46:30Z vboxsync $ */
2/** @file
3 * VBox frontends: VBoxSDL (simple frontend based on SDL):
4 * Main code
5 */
6
7/*
8 * Copyright (C) 2006-2019 Oracle Corporation
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 */
18
19
20/*********************************************************************************************************************************
21* Header Files *
22*********************************************************************************************************************************/
23#define LOG_GROUP LOG_GROUP_GUI
24
25#include <VBox/com/com.h>
26#include <VBox/com/string.h>
27#include <VBox/com/Guid.h>
28#include <VBox/com/array.h>
29#include <VBox/com/ErrorInfo.h>
30#include <VBox/com/errorprint.h>
31
32#include <VBox/com/NativeEventQueue.h>
33#include <VBox/com/VirtualBox.h>
34
35using namespace com;
36
37#if defined(VBOXSDL_WITH_X11)
38# include <VBox/VBoxKeyboard.h>
39
40# include <X11/Xlib.h>
41# include <X11/cursorfont.h> /* for XC_left_ptr */
42# if !defined(VBOX_WITHOUT_XCURSOR)
43# include <X11/Xcursor/Xcursor.h>
44# endif
45# include <unistd.h>
46#endif
47
48#include "VBoxSDL.h"
49
50#ifdef _MSC_VER
51# pragma warning(push)
52# pragma warning(disable: 4121) /* warning C4121: 'SDL_SysWMmsg' : alignment of a member was sensitive to packing*/
53#endif
54#ifndef RT_OS_DARWIN
55# include <SDL_syswm.h> /* for SDL_GetWMInfo() */
56#endif
57#ifdef _MSC_VER
58# pragma warning(pop)
59#endif
60
61#include "Framebuffer.h"
62#include "Helper.h"
63
64#include <VBox/types.h>
65#include <VBox/err.h>
66#include <VBox/param.h>
67#include <VBox/log.h>
68#include <VBox/version.h>
69#include <VBoxVideo.h>
70#include <VBox/com/listeners.h>
71
72#include <iprt/alloca.h>
73#include <iprt/asm.h>
74#include <iprt/assert.h>
75#include <iprt/ctype.h>
76#include <iprt/env.h>
77#include <iprt/file.h>
78#include <iprt/ldr.h>
79#include <iprt/initterm.h>
80#include <iprt/message.h>
81#include <iprt/path.h>
82#include <iprt/process.h>
83#include <iprt/semaphore.h>
84#include <iprt/string.h>
85#include <iprt/stream.h>
86#include <iprt/uuid.h>
87
88#include <signal.h>
89
90#include <vector>
91#include <list>
92
93#include "PasswordInput.h"
94
95/* Xlib would re-define our enums */
96#undef True
97#undef False
98
99
100/*********************************************************************************************************************************
101* Defined Constants And Macros *
102*********************************************************************************************************************************/
103#ifdef VBOX_SECURELABEL
104/** extra data key for the secure label */
105#define VBOXSDL_SECURELABEL_EXTRADATA "VBoxSDL/SecureLabel"
106/** label area height in pixels */
107#define SECURE_LABEL_HEIGHT 20
108#endif
109
110/** Enables the rawr[0|3], patm, and casm options. */
111#define VBOXSDL_ADVANCED_OPTIONS
112
113
114/*********************************************************************************************************************************
115* Structures and Typedefs *
116*********************************************************************************************************************************/
117/** Pointer shape change event data structure */
118struct PointerShapeChangeData
119{
120 PointerShapeChangeData(BOOL aVisible, BOOL aAlpha, ULONG aXHot, ULONG aYHot,
121 ULONG aWidth, ULONG aHeight, ComSafeArrayIn(BYTE,pShape))
122 : visible(aVisible), alpha(aAlpha), xHot(aXHot), yHot(aYHot),
123 width(aWidth), height(aHeight)
124 {
125 // make a copy of the shape
126 com::SafeArray<BYTE> aShape(ComSafeArrayInArg(pShape));
127 size_t cbShapeSize = aShape.size();
128 if (cbShapeSize > 0)
129 {
130 shape.resize(cbShapeSize);
131 ::memcpy(shape.raw(), aShape.raw(), cbShapeSize);
132 }
133 }
134
135 ~PointerShapeChangeData()
136 {
137 }
138
139 const BOOL visible;
140 const BOOL alpha;
141 const ULONG xHot;
142 const ULONG yHot;
143 const ULONG width;
144 const ULONG height;
145 com::SafeArray<BYTE> shape;
146};
147
148enum TitlebarMode
149{
150 TITLEBAR_NORMAL = 1,
151 TITLEBAR_STARTUP = 2,
152 TITLEBAR_SAVE = 3,
153 TITLEBAR_SNAPSHOT = 4
154};
155
156
157/*********************************************************************************************************************************
158* Internal Functions *
159*********************************************************************************************************************************/
160static bool UseAbsoluteMouse(void);
161static void ResetKeys(void);
162static void ProcessKey(SDL_KeyboardEvent *ev);
163static void InputGrabStart(void);
164static void InputGrabEnd(void);
165static void SendMouseEvent(VBoxSDLFB *fb, int dz, int button, int down);
166static void UpdateTitlebar(TitlebarMode mode, uint32_t u32User = 0);
167static void SetPointerShape(const PointerShapeChangeData *data);
168static void HandleGuestCapsChanged(void);
169static int HandleHostKey(const SDL_KeyboardEvent *pEv);
170static Uint32 StartupTimer(Uint32 interval, void *param);
171static Uint32 ResizeTimer(Uint32 interval, void *param);
172static Uint32 QuitTimer(Uint32 interval, void *param);
173static int WaitSDLEvent(SDL_Event *event);
174static void SetFullscreen(bool enable);
175
176#ifdef VBOX_WITH_SDL2
177static VBoxSDLFB *getFbFromWinId(Uint32 id);
178#endif
179
180
181/*********************************************************************************************************************************
182* Global Variables *
183*********************************************************************************************************************************/
184static int gHostKeyMod = KMOD_RCTRL;
185static int gHostKeySym1 = SDLK_RCTRL;
186static int gHostKeySym2 = SDLK_UNKNOWN;
187static const char *gHostKeyDisabledCombinations = "";
188static const char *gpszPidFile;
189static BOOL gfGrabbed = FALSE;
190static BOOL gfGrabOnMouseClick = TRUE;
191static BOOL gfFullscreenResize = FALSE;
192static BOOL gfIgnoreNextResize = FALSE;
193static BOOL gfAllowFullscreenToggle = TRUE;
194static BOOL gfAbsoluteMouseHost = FALSE;
195static BOOL gfAbsoluteMouseGuest = FALSE;
196static BOOL gfRelativeMouseGuest = TRUE;
197static BOOL gfGuestNeedsHostCursor = FALSE;
198static BOOL gfOffCursorActive = FALSE;
199static BOOL gfGuestNumLockPressed = FALSE;
200static BOOL gfGuestCapsLockPressed = FALSE;
201static BOOL gfGuestScrollLockPressed = FALSE;
202static BOOL gfACPITerm = FALSE;
203static BOOL gfXCursorEnabled = FALSE;
204static int gcGuestNumLockAdaptions = 2;
205static int gcGuestCapsLockAdaptions = 2;
206static uint32_t gmGuestNormalXRes;
207static uint32_t gmGuestNormalYRes;
208
209/** modifier keypress status (scancode as index) */
210static uint8_t gaModifiersState[256];
211
212static ComPtr<IMachine> gpMachine;
213static ComPtr<IConsole> gpConsole;
214static ComPtr<IMachineDebugger> gpMachineDebugger;
215static ComPtr<IKeyboard> gpKeyboard;
216static ComPtr<IMouse> gpMouse;
217ComPtr<IDisplay> gpDisplay;
218static ComPtr<IVRDEServer> gpVRDEServer;
219static ComPtr<IProgress> gpProgress;
220
221static ULONG gcMonitors = 1;
222static ComObjPtr<VBoxSDLFB> gpFramebuffer[64];
223static Bstr gaFramebufferId[64];
224static SDL_Cursor *gpDefaultCursor = NULL;
225#ifdef VBOXSDL_WITH_X11
226static Cursor gpDefaultOrigX11Cursor;
227#endif
228static SDL_Cursor *gpCustomCursor = NULL;
229#ifndef VBOX_WITH_SDL2
230static WMcursor *gpCustomOrigWMcursor = NULL;
231#endif
232static SDL_Cursor *gpOffCursor = NULL;
233static SDL_TimerID gSdlResizeTimer = NULL;
234static SDL_TimerID gSdlQuitTimer = NULL;
235
236#if defined(VBOXSDL_WITH_X11) && !defined(VBOX_WITH_SDL2)
237static SDL_SysWMinfo gSdlInfo;
238#endif
239
240#ifdef VBOX_SECURELABEL
241#ifdef RT_OS_WINDOWS
242#define LIBSDL_TTF_NAME "SDL_ttf"
243#else
244#define LIBSDL_TTF_NAME "libSDL_ttf-2.0.so.0"
245#endif
246RTLDRMOD gLibrarySDL_ttf = NIL_RTLDRMOD;
247#endif
248
249static RTSEMEVENT g_EventSemSDLEvents;
250static volatile int32_t g_cNotifyUpdateEventsPending;
251
252/**
253 * Event handler for VirtualBoxClient events
254 */
255class VBoxSDLClientEventListener
256{
257public:
258 VBoxSDLClientEventListener()
259 {
260 }
261
262 virtual ~VBoxSDLClientEventListener()
263 {
264 }
265
266 HRESULT init()
267 {
268 return S_OK;
269 }
270
271 void uninit()
272 {
273 }
274
275 STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent * aEvent)
276 {
277 switch (aType)
278 {
279 case VBoxEventType_OnVBoxSVCAvailabilityChanged:
280 {
281 ComPtr<IVBoxSVCAvailabilityChangedEvent> pVSACEv = aEvent;
282 Assert(pVSACEv);
283 BOOL fAvailable = FALSE;
284 pVSACEv->COMGETTER(Available)(&fAvailable);
285 if (!fAvailable)
286 {
287 LogRel(("VBoxSDL: VBoxSVC became unavailable, exiting.\n"));
288 RTPrintf("VBoxSVC became unavailable, exiting.\n");
289 /* Send QUIT event to terminate the VM as cleanly as possible
290 * given that VBoxSVC is no longer present. */
291 SDL_Event event = {0};
292 event.type = SDL_QUIT;
293 PushSDLEventForSure(&event);
294 }
295 break;
296 }
297
298 default:
299 AssertFailed();
300 }
301
302 return S_OK;
303 }
304};
305
306/**
307 * Event handler for VirtualBox (server) events
308 */
309class VBoxSDLEventListener
310{
311public:
312 VBoxSDLEventListener()
313 {
314 }
315
316 virtual ~VBoxSDLEventListener()
317 {
318 }
319
320 HRESULT init()
321 {
322 return S_OK;
323 }
324
325 void uninit()
326 {
327 }
328
329 STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent * aEvent)
330 {
331 RT_NOREF(aEvent);
332 switch (aType)
333 {
334 case VBoxEventType_OnExtraDataChanged:
335 {
336#ifdef VBOX_SECURELABEL
337 ComPtr<IExtraDataChangedEvent> pEDCEv = aEvent;
338 Assert(pEDCEv);
339 Bstr bstrMachineId;
340 pEDCEv->COMGETTER(MachineId)(bstrMachineId.asOutParam());
341 if (gpMachine)
342 {
343 /*
344 * check if we're interested in the message
345 */
346 Bstr bstrOurId;
347 gpMachine->COMGETTER(Id)(bstrOurId.asOutParam());
348 if (bstrOurId == bstrMachineId)
349 {
350 Bstr bstrKey;
351 pEDCEv->COMGETTER(Key)(bstrKey.asOutParam());
352 if (bstrKey == VBOXSDL_SECURELABEL_EXTRADATA)
353 {
354 /*
355 * Notify SDL thread of the string update
356 */
357 SDL_Event event = {0};
358 event.type = SDL_USEREVENT;
359 event.user.type = SDL_USER_EVENT_SECURELABEL_UPDATE;
360 PushSDLEventForSure(&event);
361 }
362 }
363 }
364#endif
365 break;
366 }
367
368 default:
369 AssertFailed();
370 }
371
372 return S_OK;
373 }
374};
375
376/**
377 * Event handler for Console events
378 */
379class VBoxSDLConsoleEventListener
380{
381public:
382 VBoxSDLConsoleEventListener() : m_fIgnorePowerOffEvents(false)
383 {
384 }
385
386 virtual ~VBoxSDLConsoleEventListener()
387 {
388 }
389
390 HRESULT init()
391 {
392 return S_OK;
393 }
394
395 void uninit()
396 {
397 }
398
399 STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent * aEvent)
400 {
401 // likely all this double copy is now excessive, and we can just use existing event object
402 /// @todo eliminate it
403 switch (aType)
404 {
405 case VBoxEventType_OnMousePointerShapeChanged:
406 {
407 ComPtr<IMousePointerShapeChangedEvent> pMPSCEv = aEvent;
408 Assert(pMPSCEv);
409 PointerShapeChangeData *data;
410 BOOL visible, alpha;
411 ULONG xHot, yHot, width, height;
412 com::SafeArray<BYTE> shape;
413
414 pMPSCEv->COMGETTER(Visible)(&visible);
415 pMPSCEv->COMGETTER(Alpha)(&alpha);
416 pMPSCEv->COMGETTER(Xhot)(&xHot);
417 pMPSCEv->COMGETTER(Yhot)(&yHot);
418 pMPSCEv->COMGETTER(Width)(&width);
419 pMPSCEv->COMGETTER(Height)(&height);
420 pMPSCEv->COMGETTER(Shape)(ComSafeArrayAsOutParam(shape));
421 data = new PointerShapeChangeData(visible, alpha, xHot, yHot, width, height,
422 ComSafeArrayAsInParam(shape));
423 Assert(data);
424 if (!data)
425 break;
426
427 SDL_Event event = {0};
428 event.type = SDL_USEREVENT;
429 event.user.type = SDL_USER_EVENT_POINTER_CHANGE;
430 event.user.data1 = data;
431
432 int rc = PushSDLEventForSure(&event);
433 if (rc)
434 delete data;
435
436 break;
437 }
438 case VBoxEventType_OnMouseCapabilityChanged:
439 {
440 ComPtr<IMouseCapabilityChangedEvent> pMCCEv = aEvent;
441 Assert(pMCCEv);
442 pMCCEv->COMGETTER(SupportsAbsolute)(&gfAbsoluteMouseGuest);
443 pMCCEv->COMGETTER(SupportsRelative)(&gfRelativeMouseGuest);
444 pMCCEv->COMGETTER(NeedsHostCursor)(&gfGuestNeedsHostCursor);
445 SDL_Event event = {0};
446 event.type = SDL_USEREVENT;
447 event.user.type = SDL_USER_EVENT_GUEST_CAP_CHANGED;
448
449 PushSDLEventForSure(&event);
450 break;
451 }
452 case VBoxEventType_OnKeyboardLedsChanged:
453 {
454 ComPtr<IKeyboardLedsChangedEvent> pCLCEv = aEvent;
455 Assert(pCLCEv);
456 BOOL fNumLock, fCapsLock, fScrollLock;
457 pCLCEv->COMGETTER(NumLock)(&fNumLock);
458 pCLCEv->COMGETTER(CapsLock)(&fCapsLock);
459 pCLCEv->COMGETTER(ScrollLock)(&fScrollLock);
460 /* Don't bother the guest with NumLock scancodes if he doesn't set the NumLock LED */
461 if (gfGuestNumLockPressed != fNumLock)
462 gcGuestNumLockAdaptions = 2;
463 if (gfGuestCapsLockPressed != fCapsLock)
464 gcGuestCapsLockAdaptions = 2;
465 gfGuestNumLockPressed = fNumLock;
466 gfGuestCapsLockPressed = fCapsLock;
467 gfGuestScrollLockPressed = fScrollLock;
468 break;
469 }
470
471 case VBoxEventType_OnStateChanged:
472 {
473 ComPtr<IStateChangedEvent> pSCEv = aEvent;
474 Assert(pSCEv);
475 MachineState_T machineState;
476 pSCEv->COMGETTER(State)(&machineState);
477 LogFlow(("OnStateChange: machineState = %d (%s)\n", machineState, GetStateName(machineState)));
478 SDL_Event event = {0};
479
480 if ( machineState == MachineState_Aborted
481 || machineState == MachineState_Teleported
482 || (machineState == MachineState_Saved && !m_fIgnorePowerOffEvents)
483 || (machineState == MachineState_PoweredOff && !m_fIgnorePowerOffEvents)
484 )
485 {
486 /*
487 * We have to inform the SDL thread that the application has be terminated
488 */
489 event.type = SDL_USEREVENT;
490 event.user.type = SDL_USER_EVENT_TERMINATE;
491 event.user.code = machineState == MachineState_Aborted
492 ? VBOXSDL_TERM_ABEND
493 : VBOXSDL_TERM_NORMAL;
494 }
495 else
496 {
497 /*
498 * Inform the SDL thread to refresh the titlebar
499 */
500 event.type = SDL_USEREVENT;
501 event.user.type = SDL_USER_EVENT_UPDATE_TITLEBAR;
502 }
503
504 PushSDLEventForSure(&event);
505 break;
506 }
507
508 case VBoxEventType_OnRuntimeError:
509 {
510 ComPtr<IRuntimeErrorEvent> pRTEEv = aEvent;
511 Assert(pRTEEv);
512 BOOL fFatal;
513
514 pRTEEv->COMGETTER(Fatal)(&fFatal);
515 MachineState_T machineState;
516 gpMachine->COMGETTER(State)(&machineState);
517 const char *pszType;
518 bool fPaused = machineState == MachineState_Paused;
519 if (fFatal)
520 pszType = "FATAL ERROR";
521 else if (machineState == MachineState_Paused)
522 pszType = "Non-fatal ERROR";
523 else
524 pszType = "WARNING";
525 Bstr bstrId, bstrMessage;
526 pRTEEv->COMGETTER(Id)(bstrId.asOutParam());
527 pRTEEv->COMGETTER(Message)(bstrMessage.asOutParam());
528 RTPrintf("\n%s: ** %ls **\n%ls\n%s\n", pszType, bstrId.raw(), bstrMessage.raw(),
529 fPaused ? "The VM was paused. Continue with HostKey + P after you solved the problem.\n" : "");
530 break;
531 }
532
533 case VBoxEventType_OnCanShowWindow:
534 {
535 ComPtr<ICanShowWindowEvent> pCSWEv = aEvent;
536 Assert(pCSWEv);
537#ifdef RT_OS_DARWIN
538 /* SDL feature not available on Quartz */
539#else
540 bool fCanShow = false;
541
542# ifdef VBOX_WITH_SDL2
543 Uint32 winId = 0;
544
545 VBoxSDLFB *fb = getFbFromWinId(winId);
546
547 SDL_SysWMinfo info;
548 SDL_VERSION(&info.version);
549 if (SDL_GetWindowWMInfo(fb->getWindow(), &info))
550 fCanShow = true;
551# else
552 SDL_SysWMinfo info;
553 SDL_VERSION(&info.version);
554 if (!SDL_GetWMInfo(&info))
555 fCanShow = false;
556 else
557 fCanShow = true;
558# endif /* VBOX_WITH_SDL2 */
559
560 if (fCanShow)
561 pCSWEv->AddApproval(NULL);
562 else
563 pCSWEv->AddVeto(NULL);
564#endif
565 break;
566 }
567
568 case VBoxEventType_OnShowWindow:
569 {
570 ComPtr<IShowWindowEvent> pSWEv = aEvent;
571 Assert(pSWEv);
572 LONG64 winId = 0;
573 pSWEv->COMGETTER(WinId)(&winId);
574 if (winId != 0)
575 break; /* WinId already set by some other listener. */
576#ifndef RT_OS_DARWIN
577 SDL_SysWMinfo info;
578 SDL_VERSION(&info.version);
579# ifdef VBOX_WITH_SDL2
580 VBoxSDLFB *fb = getFbFromWinId(winId);
581 if (SDL_GetWindowWMInfo(fb->getWindow(), &info))
582# else
583 if (SDL_GetWMInfo(&info))
584# endif /* VBOX_WITH_SDL2 */
585 {
586# if defined(VBOXSDL_WITH_X11)
587 pSWEv->COMSETTER(WinId)((LONG64)info.info.x11.wmwindow);
588# elif defined(RT_OS_WINDOWS)
589# ifdef VBOX_WITH_SDL2
590 pSWEv->COMSETTER(WinId)((intptr_t)info.info.win.window);
591# else
592 pSWEv->COMSETTER(WinId)((intptr_t)info.window);
593# endif /* VBOX_WITH_SDL2 */
594# else /* !RT_OS_WINDOWS */
595 AssertFailed();
596# endif
597 }
598#endif /* !RT_OS_DARWIN */
599 break;
600 }
601
602 default:
603 AssertFailed();
604 }
605 return S_OK;
606 }
607
608 static const char *GetStateName(MachineState_T machineState)
609 {
610 switch (machineState)
611 {
612 case MachineState_Null: return "<null>";
613 case MachineState_PoweredOff: return "PoweredOff";
614 case MachineState_Saved: return "Saved";
615 case MachineState_Teleported: return "Teleported";
616 case MachineState_Aborted: return "Aborted";
617 case MachineState_Running: return "Running";
618 case MachineState_Teleporting: return "Teleporting";
619 case MachineState_LiveSnapshotting: return "LiveSnapshotting";
620 case MachineState_Paused: return "Paused";
621 case MachineState_Stuck: return "GuruMeditation";
622 case MachineState_Starting: return "Starting";
623 case MachineState_Stopping: return "Stopping";
624 case MachineState_Saving: return "Saving";
625 case MachineState_Restoring: return "Restoring";
626 case MachineState_TeleportingPausedVM: return "TeleportingPausedVM";
627 case MachineState_TeleportingIn: return "TeleportingIn";
628 case MachineState_RestoringSnapshot: return "RestoringSnapshot";
629 case MachineState_DeletingSnapshot: return "DeletingSnapshot";
630 case MachineState_SettingUp: return "SettingUp";
631 default: return "no idea";
632 }
633 }
634
635 void ignorePowerOffEvents(bool fIgnore)
636 {
637 m_fIgnorePowerOffEvents = fIgnore;
638 }
639
640private:
641 bool m_fIgnorePowerOffEvents;
642};
643
644typedef ListenerImpl<VBoxSDLClientEventListener> VBoxSDLClientEventListenerImpl;
645typedef ListenerImpl<VBoxSDLEventListener> VBoxSDLEventListenerImpl;
646typedef ListenerImpl<VBoxSDLConsoleEventListener> VBoxSDLConsoleEventListenerImpl;
647
648static void show_usage()
649{
650 RTPrintf("Usage:\n"
651 " --startvm <uuid|name> Virtual machine to start, either UUID or name\n"
652 " --separate Run a separate VM process or attach to a running VM\n"
653 " --hda <file> Set temporary first hard disk to file\n"
654 " --fda <file> Set temporary first floppy disk to file\n"
655 " --cdrom <file> Set temporary CDROM/DVD to file/device ('none' to unmount)\n"
656 " --boot <a|c|d|n> Set temporary boot device (a = floppy, c = 1st HD, d = DVD, n = network)\n"
657 " --memory <size> Set temporary memory size in megabytes\n"
658 " --vram <size> Set temporary size of video memory in megabytes\n"
659 " --fullscreen Start VM in fullscreen mode\n"
660 " --fullscreenresize Resize the guest on fullscreen\n"
661 " --fixedmode <w> <h> <bpp> Use a fixed SDL video mode with given width, height and bits per pixel\n"
662 " --nofstoggle Forbid switching to/from fullscreen mode\n"
663 " --noresize Make the SDL frame non resizable\n"
664 " --nohostkey Disable all hostkey combinations\n"
665 " --nohostkeys ... Disable specific hostkey combinations, see below for valid keys\n"
666 " --nograbonclick Disable mouse/keyboard grabbing on mouse click w/o additions\n"
667 " --detecthostkey Get the hostkey identifier and modifier state\n"
668 " --hostkey <key> {<key2>} <mod> Set the host key to the values obtained using --detecthostkey\n"
669 " --termacpi Send an ACPI power button event when closing the window\n"
670 " --vrdp <ports> Listen for VRDP connections on one of specified ports (default if not specified)\n"
671 " --discardstate Discard saved state (if present) and revert to last snapshot (if present)\n"
672 " --settingspw <pw> Specify the settings password\n"
673 " --settingspwfile <file> Specify a file containing the settings password\n"
674#ifdef VBOX_SECURELABEL
675 " --securelabel Display a secure VM label at the top of the screen\n"
676 " --seclabelfnt TrueType (.ttf) font file for secure session label\n"
677 " --seclabelsiz Font point size for secure session label (default 12)\n"
678 " --seclabelofs Font offset within the secure label (default 0)\n"
679 " --seclabelfgcol <rgb> Secure label text color RGB value in 6 digit hexadecimal (eg: FFFF00)\n"
680 " --seclabelbgcol <rgb> Secure label background color RGB value in 6 digit hexadecimal (eg: FF0000)\n"
681#endif
682#ifdef VBOXSDL_ADVANCED_OPTIONS
683 " --[no]rawr0 Enable or disable raw ring 3\n"
684 " --[no]rawr3 Enable or disable raw ring 0\n"
685 " --[no]patm Enable or disable PATM\n"
686 " --[no]csam Enable or disable CSAM\n"
687 " --[no]hwvirtex Permit or deny the usage of VT-x/AMD-V\n"
688#endif
689 "\n"
690 "Key bindings:\n"
691 " <hostkey> + f Switch to full screen / restore to previous view\n"
692 " h Press ACPI power button\n"
693 " n Take a snapshot and continue execution\n"
694 " p Pause / resume execution\n"
695 " q Power off\n"
696 " r VM reset\n"
697 " s Save state and power off\n"
698 " <del> Send <ctrl><alt><del>\n"
699 " <F1>...<F12> Send <ctrl><alt><Fx>\n"
700#if defined(DEBUG) || defined(VBOX_WITH_STATISTICS)
701 "\n"
702 "Further key bindings useful for debugging:\n"
703 " LCtrl + Alt + F12 Reset statistics counter\n"
704 " LCtrl + Alt + F11 Dump statistics to logfile\n"
705 " Alt + F12 Toggle R0 recompiler\n"
706 " Alt + F11 Toggle R3 recompiler\n"
707 " Alt + F10 Toggle PATM\n"
708 " Alt + F9 Toggle CSAM\n"
709 " Alt + F8 Toggle single step mode\n"
710 " LCtrl/RCtrl + F12 Toggle logger\n"
711 " F12 Write log marker to logfile\n"
712#endif
713 "\n");
714}
715
716static void PrintError(const char *pszName, CBSTR pwszDescr, CBSTR pwszComponent=NULL)
717{
718 const char *pszFile, *pszFunc, *pszStat;
719 char pszBuffer[1024];
720 com::ErrorInfo info;
721
722 RTStrPrintf(pszBuffer, sizeof(pszBuffer), "%ls", pwszDescr);
723
724 RTPrintf("\n%s! Error info:\n", pszName);
725 if ( (pszFile = strstr(pszBuffer, "At '"))
726 && (pszFunc = strstr(pszBuffer, ") in "))
727 && (pszStat = strstr(pszBuffer, "VBox status code: ")))
728 RTPrintf(" %.*s %.*s\n In%.*s %s",
729 pszFile-pszBuffer, pszBuffer,
730 pszFunc-pszFile+1, pszFile,
731 pszStat-pszFunc-4, pszFunc+4,
732 pszStat);
733 else
734 RTPrintf("%s\n", pszBuffer);
735
736 if (pwszComponent)
737 RTPrintf("(component %ls).\n", pwszComponent);
738
739 RTPrintf("\n");
740}
741
742#ifdef VBOXSDL_WITH_X11
743/**
744 * Custom signal handler. Currently it is only used to release modifier
745 * keys when receiving the USR1 signal. When switching VTs, we might not
746 * get release events for Ctrl-Alt and in case a savestate is performed
747 * on the new VT, the VM will be saved with modifier keys stuck. This is
748 * annoying enough for introducing this hack.
749 */
750void signal_handler_SIGUSR1(int sig, siginfo_t *info, void *secret)
751{
752 RT_NOREF(info, secret);
753
754 /* only SIGUSR1 is interesting */
755 if (sig == SIGUSR1)
756 {
757 /* just release the modifiers */
758 ResetKeys();
759 }
760}
761
762/**
763 * Custom signal handler for catching exit events.
764 */
765void signal_handler_SIGINT(int sig)
766{
767 if (gpszPidFile)
768 RTFileDelete(gpszPidFile);
769 signal(SIGINT, SIG_DFL);
770 signal(SIGQUIT, SIG_DFL);
771 signal(SIGSEGV, SIG_DFL);
772 kill(getpid(), sig);
773}
774#endif /* VBOXSDL_WITH_X11 */
775
776
777/** entry point */
778extern "C"
779DECLEXPORT(int) TrustedMain(int argc, char **argv, char **envp)
780{
781 RT_NOREF(envp);
782#ifdef RT_OS_WINDOWS
783 ATL::CComModule _Module; /* Required internally by ATL (constructor records instance in global variable). */
784#endif
785
786#ifdef Q_WS_X11
787 if (!XInitThreads())
788 return 1;
789#endif
790#ifdef VBOXSDL_WITH_X11
791 /*
792 * Lock keys on SDL behave different from normal keys: A KeyPress event is generated
793 * if the lock mode gets active and a keyRelease event is generated if the lock mode
794 * gets inactive, that is KeyPress and KeyRelease are sent when pressing the lock key
795 * to change the mode. The current lock mode is reflected in SDL_GetModState().
796 *
797 * Debian patched libSDL to make the lock keys behave like normal keys
798 * generating a KeyPress/KeyRelease event if the lock key was
799 * pressed/released. With the new behaviour, the lock status is not
800 * reflected in the mod status anymore, but the user can request the old
801 * behaviour by setting an environment variable. To confuse matters further
802 * version 1.2.14 (fortunately including the Debian packaged versions)
803 * adopted the Debian behaviour officially, but inverted the meaning of the
804 * environment variable to select the new behaviour, keeping the old as the
805 * default. We disable the new behaviour to ensure a defined environment
806 * and work around the missing KeyPress/KeyRelease events in ProcessKeys().
807 */
808 {
809 const SDL_version *pVersion = SDL_Linked_Version();
810 if ( SDL_VERSIONNUM(pVersion->major, pVersion->minor, pVersion->patch)
811 < SDL_VERSIONNUM(1, 2, 14))
812 RTEnvSet("SDL_DISABLE_LOCK_KEYS", "1");
813 }
814#endif
815
816 /*
817 * the hostkey detection mode is unrelated to VM processing, so handle it before
818 * we initialize anything COM related
819 */
820 if (argc == 2 && ( !strcmp(argv[1], "-detecthostkey")
821 || !strcmp(argv[1], "--detecthostkey")))
822 {
823 Uint32 fInitSubSystem = SDL_INIT_VIDEO | SDL_INIT_TIMER;
824#ifndef VBOX_WITH_SDL2
825 fInitSubSystem |= SDL_INIT_NOPARACHUTE;
826#endif
827 int rc = SDL_InitSubSystem(fInitSubSystem);
828 if (rc != 0)
829 {
830 RTPrintf("Error: SDL_InitSubSystem failed with message '%s'\n", SDL_GetError());
831 return 1;
832 }
833 /* we need a video window for the keyboard stuff to work */
834#ifndef VBOX_WITH_SDL2 /** @todo Is this correct? */
835 if (!SDL_SetVideoMode(640, 480, 16, SDL_SWSURFACE))
836 {
837 RTPrintf("Error: could not set SDL video mode\n");
838 return 1;
839 }
840#endif
841 RTPrintf("Please hit one or two function key(s) to get the --hostkey value...\n");
842
843 SDL_Event event1;
844 while (SDL_WaitEvent(&event1))
845 {
846 if (event1.type == SDL_KEYDOWN)
847 {
848 SDL_Event event2;
849 unsigned mod = SDL_GetModState() & ~(KMOD_MODE | KMOD_NUM | KMOD_RESERVED);
850 while (SDL_WaitEvent(&event2))
851 {
852 if (event2.type == SDL_KEYDOWN || event2.type == SDL_KEYUP)
853 {
854 /* pressed additional host key */
855 RTPrintf("--hostkey %d", event1.key.keysym.sym);
856 if (event2.type == SDL_KEYDOWN)
857 {
858 RTPrintf(" %d", event2.key.keysym.sym);
859 RTPrintf(" %d\n", SDL_GetModState() & ~(KMOD_MODE | KMOD_NUM | KMOD_RESERVED));
860 }
861 else
862 {
863 RTPrintf(" %d\n", mod);
864 }
865 /* we're done */
866 break;
867 }
868 }
869 /* we're down */
870 break;
871 }
872 }
873 SDL_Quit();
874 return 1;
875 }
876
877 HRESULT rc;
878 int vrc;
879 Guid uuidVM;
880 char *vmName = NULL;
881 bool fSeparate = false;
882 DeviceType_T bootDevice = DeviceType_Null;
883 uint32_t memorySize = 0;
884 uint32_t vramSize = 0;
885 ComPtr<IEventListener> pVBoxClientListener;
886 ComPtr<IEventListener> pVBoxListener;
887 ComObjPtr<VBoxSDLConsoleEventListenerImpl> pConsoleListener;
888
889 bool fFullscreen = false;
890 bool fResizable = true;
891#ifdef USE_XPCOM_QUEUE_THREAD
892 bool fXPCOMEventThreadSignaled = false;
893#endif
894 const char *pcszHdaFile = NULL;
895 const char *pcszCdromFile = NULL;
896 const char *pcszFdaFile = NULL;
897 const char *pszPortVRDP = NULL;
898 bool fDiscardState = false;
899 const char *pcszSettingsPw = NULL;
900 const char *pcszSettingsPwFile = NULL;
901#ifdef VBOX_SECURELABEL
902 BOOL fSecureLabel = false;
903 uint32_t secureLabelPointSize = 12;
904 uint32_t secureLabelFontOffs = 0;
905 char *secureLabelFontFile = NULL;
906 uint32_t secureLabelColorFG = 0x0000FF00;
907 uint32_t secureLabelColorBG = 0x00FFFF00;
908#endif
909#ifdef VBOXSDL_ADVANCED_OPTIONS
910 unsigned fRawR0 = ~0U;
911 unsigned fRawR3 = ~0U;
912 unsigned fPATM = ~0U;
913 unsigned fCSAM = ~0U;
914 unsigned fHWVirt = ~0U;
915 uint32_t u32WarpDrive = 0;
916#endif
917#ifdef VBOX_WIN32_UI
918 bool fWin32UI = true;
919 int64_t winId = 0;
920#endif
921 bool fShowSDLConfig = false;
922 uint32_t fixedWidth = ~(uint32_t)0;
923 uint32_t fixedHeight = ~(uint32_t)0;
924 uint32_t fixedBPP = ~(uint32_t)0;
925 uint32_t uResizeWidth = ~(uint32_t)0;
926 uint32_t uResizeHeight = ~(uint32_t)0;
927
928 /* The damned GOTOs forces this to be up here - totally out of place. */
929 /*
930 * Host key handling.
931 *
932 * The golden rule is that host-key combinations should not be seen
933 * by the guest. For instance a CAD should not have any extra RCtrl down
934 * and RCtrl up around itself. Nor should a resume be followed by a Ctrl-P
935 * that could encourage applications to start printing.
936 *
937 * We must not confuse the hostkey processing into any release sequences
938 * either, the host key is supposed to be explicitly pressing one key.
939 *
940 * Quick state diagram:
941 *
942 * host key down alone
943 * (Normal) ---------------
944 * ^ ^ |
945 * | | v host combination key down
946 * | | (Host key down) ----------------
947 * | | host key up v | |
948 * | |-------------- | other key down v host combination key down
949 * | | (host key used) -------------
950 * | | | ^ |
951 * | (not host key)-- | |---------------
952 * | | | | |
953 * | | ---- other |
954 * | modifiers = 0 v v
955 * -----------------------------------------------
956 */
957 enum HKEYSTATE
958 {
959 /** The initial and most common state, pass keystrokes to the guest.
960 * Next state: HKEYSTATE_DOWN
961 * Prev state: Any */
962 HKEYSTATE_NORMAL = 1,
963 /** The first host key was pressed down
964 */
965 HKEYSTATE_DOWN_1ST,
966 /** The second host key was pressed down (if gHostKeySym2 != SDLK_UNKNOWN)
967 */
968 HKEYSTATE_DOWN_2ND,
969 /** The host key has been pressed down.
970 * Prev state: HKEYSTATE_NORMAL
971 * Next state: HKEYSTATE_NORMAL - host key up, capture toggle.
972 * Next state: HKEYSTATE_USED - host key combination down.
973 * Next state: HKEYSTATE_NOT_IT - non-host key combination down.
974 */
975 HKEYSTATE_DOWN,
976 /** A host key combination was pressed.
977 * Prev state: HKEYSTATE_DOWN
978 * Next state: HKEYSTATE_NORMAL - when modifiers are all 0
979 */
980 HKEYSTATE_USED,
981 /** A non-host key combination was attempted. Send hostkey down to the
982 * guest and continue until all modifiers have been released.
983 * Prev state: HKEYSTATE_DOWN
984 * Next state: HKEYSTATE_NORMAL - when modifiers are all 0
985 */
986 HKEYSTATE_NOT_IT
987 } enmHKeyState = HKEYSTATE_NORMAL;
988 /** The host key down event which we have been hiding from the guest.
989 * Used when going from HKEYSTATE_DOWN to HKEYSTATE_NOT_IT. */
990 SDL_Event EvHKeyDown1;
991 SDL_Event EvHKeyDown2;
992
993 LogFlow(("SDL GUI started\n"));
994 RTPrintf(VBOX_PRODUCT " SDL GUI version %s\n"
995 "(C) 2005-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
996 "All rights reserved.\n\n",
997 VBOX_VERSION_STRING);
998
999 // less than one parameter is not possible
1000 if (argc < 2)
1001 {
1002 show_usage();
1003 return 1;
1004 }
1005
1006 // command line argument parsing stuff
1007 for (int curArg = 1; curArg < argc; curArg++)
1008 {
1009 if ( !strcmp(argv[curArg], "--vm")
1010 || !strcmp(argv[curArg], "-vm")
1011 || !strcmp(argv[curArg], "--startvm")
1012 || !strcmp(argv[curArg], "-startvm")
1013 || !strcmp(argv[curArg], "-s")
1014 )
1015 {
1016 if (++curArg >= argc)
1017 {
1018 RTPrintf("Error: VM not specified (UUID or name)!\n");
1019 return 1;
1020 }
1021 // first check if a UUID was supplied
1022 uuidVM = argv[curArg];
1023
1024 if (!uuidVM.isValid())
1025 {
1026 LogFlow(("invalid UUID format, assuming it's a VM name\n"));
1027 vmName = argv[curArg];
1028 }
1029 else if (uuidVM.isZero())
1030 {
1031 RTPrintf("Error: UUID argument is zero!\n");
1032 return 1;
1033 }
1034 }
1035 else if ( !strcmp(argv[curArg], "--separate")
1036 || !strcmp(argv[curArg], "-separate"))
1037 {
1038 fSeparate = true;
1039 }
1040 else if ( !strcmp(argv[curArg], "--comment")
1041 || !strcmp(argv[curArg], "-comment"))
1042 {
1043 if (++curArg >= argc)
1044 {
1045 RTPrintf("Error: missing argument for comment!\n");
1046 return 1;
1047 }
1048 }
1049 else if ( !strcmp(argv[curArg], "--boot")
1050 || !strcmp(argv[curArg], "-boot"))
1051 {
1052 if (++curArg >= argc)
1053 {
1054 RTPrintf("Error: missing argument for boot drive!\n");
1055 return 1;
1056 }
1057 switch (argv[curArg][0])
1058 {
1059 case 'a':
1060 {
1061 bootDevice = DeviceType_Floppy;
1062 break;
1063 }
1064
1065 case 'c':
1066 {
1067 bootDevice = DeviceType_HardDisk;
1068 break;
1069 }
1070
1071 case 'd':
1072 {
1073 bootDevice = DeviceType_DVD;
1074 break;
1075 }
1076
1077 case 'n':
1078 {
1079 bootDevice = DeviceType_Network;
1080 break;
1081 }
1082
1083 default:
1084 {
1085 RTPrintf("Error: wrong argument for boot drive!\n");
1086 return 1;
1087 }
1088 }
1089 }
1090 else if ( !strcmp(argv[curArg], "--detecthostkey")
1091 || !strcmp(argv[curArg], "-detecthostkey"))
1092 {
1093 RTPrintf("Error: please specify \"%s\" without any additional parameters!\n",
1094 argv[curArg]);
1095 return 1;
1096 }
1097 else if ( !strcmp(argv[curArg], "--memory")
1098 || !strcmp(argv[curArg], "-memory")
1099 || !strcmp(argv[curArg], "-m"))
1100 {
1101 if (++curArg >= argc)
1102 {
1103 RTPrintf("Error: missing argument for memory size!\n");
1104 return 1;
1105 }
1106 memorySize = atoi(argv[curArg]);
1107 }
1108 else if ( !strcmp(argv[curArg], "--vram")
1109 || !strcmp(argv[curArg], "-vram"))
1110 {
1111 if (++curArg >= argc)
1112 {
1113 RTPrintf("Error: missing argument for vram size!\n");
1114 return 1;
1115 }
1116 vramSize = atoi(argv[curArg]);
1117 }
1118 else if ( !strcmp(argv[curArg], "--fullscreen")
1119 || !strcmp(argv[curArg], "-fullscreen"))
1120 {
1121 fFullscreen = true;
1122 }
1123 else if ( !strcmp(argv[curArg], "--fullscreenresize")
1124 || !strcmp(argv[curArg], "-fullscreenresize"))
1125 {
1126 gfFullscreenResize = true;
1127#ifdef VBOXSDL_WITH_X11
1128 RTEnvSet("SDL_VIDEO_X11_VIDMODE", "0");
1129#endif
1130 }
1131 else if ( !strcmp(argv[curArg], "--fixedmode")
1132 || !strcmp(argv[curArg], "-fixedmode"))
1133 {
1134 /* three parameters follow */
1135 if (curArg + 3 >= argc)
1136 {
1137 RTPrintf("Error: missing arguments for fixed video mode!\n");
1138 return 1;
1139 }
1140 fixedWidth = atoi(argv[++curArg]);
1141 fixedHeight = atoi(argv[++curArg]);
1142 fixedBPP = atoi(argv[++curArg]);
1143 }
1144 else if ( !strcmp(argv[curArg], "--nofstoggle")
1145 || !strcmp(argv[curArg], "-nofstoggle"))
1146 {
1147 gfAllowFullscreenToggle = FALSE;
1148 }
1149 else if ( !strcmp(argv[curArg], "--noresize")
1150 || !strcmp(argv[curArg], "-noresize"))
1151 {
1152 fResizable = false;
1153 }
1154 else if ( !strcmp(argv[curArg], "--nohostkey")
1155 || !strcmp(argv[curArg], "-nohostkey"))
1156 {
1157 gHostKeyMod = 0;
1158 gHostKeySym1 = 0;
1159 }
1160 else if ( !strcmp(argv[curArg], "--nohostkeys")
1161 || !strcmp(argv[curArg], "-nohostkeys"))
1162 {
1163 if (++curArg >= argc)
1164 {
1165 RTPrintf("Error: missing a string of disabled hostkey combinations\n");
1166 return 1;
1167 }
1168 gHostKeyDisabledCombinations = argv[curArg];
1169 size_t cch = strlen(gHostKeyDisabledCombinations);
1170 for (size_t i = 0; i < cch; i++)
1171 {
1172 if (!strchr("fhnpqrs", gHostKeyDisabledCombinations[i]))
1173 {
1174 RTPrintf("Error: <hostkey> + '%c' is not a valid combination\n",
1175 gHostKeyDisabledCombinations[i]);
1176 return 1;
1177 }
1178 }
1179 }
1180 else if ( !strcmp(argv[curArg], "--nograbonclick")
1181 || !strcmp(argv[curArg], "-nograbonclick"))
1182 {
1183 gfGrabOnMouseClick = FALSE;
1184 }
1185 else if ( !strcmp(argv[curArg], "--termacpi")
1186 || !strcmp(argv[curArg], "-termacpi"))
1187 {
1188 gfACPITerm = TRUE;
1189 }
1190 else if ( !strcmp(argv[curArg], "--pidfile")
1191 || !strcmp(argv[curArg], "-pidfile"))
1192 {
1193 if (++curArg >= argc)
1194 {
1195 RTPrintf("Error: missing file name for --pidfile!\n");
1196 return 1;
1197 }
1198 gpszPidFile = argv[curArg];
1199 }
1200 else if ( !strcmp(argv[curArg], "--hda")
1201 || !strcmp(argv[curArg], "-hda"))
1202 {
1203 if (++curArg >= argc)
1204 {
1205 RTPrintf("Error: missing file name for first hard disk!\n");
1206 return 1;
1207 }
1208 /* resolve it. */
1209 if (RTPathExists(argv[curArg]))
1210 pcszHdaFile = RTPathRealDup(argv[curArg]);
1211 if (!pcszHdaFile)
1212 {
1213 RTPrintf("Error: The path to the specified harddisk, '%s', could not be resolved.\n", argv[curArg]);
1214 return 1;
1215 }
1216 }
1217 else if ( !strcmp(argv[curArg], "--fda")
1218 || !strcmp(argv[curArg], "-fda"))
1219 {
1220 if (++curArg >= argc)
1221 {
1222 RTPrintf("Error: missing file/device name for first floppy disk!\n");
1223 return 1;
1224 }
1225 /* resolve it. */
1226 if (RTPathExists(argv[curArg]))
1227 pcszFdaFile = RTPathRealDup(argv[curArg]);
1228 if (!pcszFdaFile)
1229 {
1230 RTPrintf("Error: The path to the specified floppy disk, '%s', could not be resolved.\n", argv[curArg]);
1231 return 1;
1232 }
1233 }
1234 else if ( !strcmp(argv[curArg], "--cdrom")
1235 || !strcmp(argv[curArg], "-cdrom"))
1236 {
1237 if (++curArg >= argc)
1238 {
1239 RTPrintf("Error: missing file/device name for cdrom!\n");
1240 return 1;
1241 }
1242 /* resolve it. */
1243 if (RTPathExists(argv[curArg]))
1244 pcszCdromFile = RTPathRealDup(argv[curArg]);
1245 if (!pcszCdromFile)
1246 {
1247 RTPrintf("Error: The path to the specified cdrom, '%s', could not be resolved.\n", argv[curArg]);
1248 return 1;
1249 }
1250 }
1251 else if ( !strcmp(argv[curArg], "--vrdp")
1252 || !strcmp(argv[curArg], "-vrdp"))
1253 {
1254 // start with the standard VRDP port
1255 pszPortVRDP = "0";
1256
1257 // is there another argument
1258 if (argc > (curArg + 1))
1259 {
1260 curArg++;
1261 pszPortVRDP = argv[curArg];
1262 LogFlow(("Using non standard VRDP port %s\n", pszPortVRDP));
1263 }
1264 }
1265 else if ( !strcmp(argv[curArg], "--discardstate")
1266 || !strcmp(argv[curArg], "-discardstate"))
1267 {
1268 fDiscardState = true;
1269 }
1270 else if (!strcmp(argv[curArg], "--settingspw"))
1271 {
1272 if (++curArg >= argc)
1273 {
1274 RTPrintf("Error: missing password");
1275 return 1;
1276 }
1277 pcszSettingsPw = argv[curArg];
1278 }
1279 else if (!strcmp(argv[curArg], "--settingspwfile"))
1280 {
1281 if (++curArg >= argc)
1282 {
1283 RTPrintf("Error: missing password file\n");
1284 return 1;
1285 }
1286 pcszSettingsPwFile = argv[curArg];
1287 }
1288#ifdef VBOX_SECURELABEL
1289 else if ( !strcmp(argv[curArg], "--securelabel")
1290 || !strcmp(argv[curArg], "-securelabel"))
1291 {
1292 fSecureLabel = true;
1293 LogFlow(("Secure labelling turned on\n"));
1294 }
1295 else if ( !strcmp(argv[curArg], "--seclabelfnt")
1296 || !strcmp(argv[curArg], "-seclabelfnt"))
1297 {
1298 if (++curArg >= argc)
1299 {
1300 RTPrintf("Error: missing font file name for secure label!\n");
1301 return 1;
1302 }
1303 secureLabelFontFile = argv[curArg];
1304 }
1305 else if ( !strcmp(argv[curArg], "--seclabelsiz")
1306 || !strcmp(argv[curArg], "-seclabelsiz"))
1307 {
1308 if (++curArg >= argc)
1309 {
1310 RTPrintf("Error: missing font point size for secure label!\n");
1311 return 1;
1312 }
1313 secureLabelPointSize = atoi(argv[curArg]);
1314 }
1315 else if ( !strcmp(argv[curArg], "--seclabelofs")
1316 || !strcmp(argv[curArg], "-seclabelofs"))
1317 {
1318 if (++curArg >= argc)
1319 {
1320 RTPrintf("Error: missing font pixel offset for secure label!\n");
1321 return 1;
1322 }
1323 secureLabelFontOffs = atoi(argv[curArg]);
1324 }
1325 else if ( !strcmp(argv[curArg], "--seclabelfgcol")
1326 || !strcmp(argv[curArg], "-seclabelfgcol"))
1327 {
1328 if (++curArg >= argc)
1329 {
1330 RTPrintf("Error: missing text color value for secure label!\n");
1331 return 1;
1332 }
1333 sscanf(argv[curArg], "%X", &secureLabelColorFG);
1334 }
1335 else if ( !strcmp(argv[curArg], "--seclabelbgcol")
1336 || !strcmp(argv[curArg], "-seclabelbgcol"))
1337 {
1338 if (++curArg >= argc)
1339 {
1340 RTPrintf("Error: missing background color value for secure label!\n");
1341 return 1;
1342 }
1343 sscanf(argv[curArg], "%X", &secureLabelColorBG);
1344 }
1345#endif
1346#ifdef VBOXSDL_ADVANCED_OPTIONS
1347 else if ( !strcmp(argv[curArg], "--rawr0")
1348 || !strcmp(argv[curArg], "-rawr0"))
1349 fRawR0 = true;
1350 else if ( !strcmp(argv[curArg], "--norawr0")
1351 || !strcmp(argv[curArg], "-norawr0"))
1352 fRawR0 = false;
1353 else if ( !strcmp(argv[curArg], "--rawr3")
1354 || !strcmp(argv[curArg], "-rawr3"))
1355 fRawR3 = true;
1356 else if ( !strcmp(argv[curArg], "--norawr3")
1357 || !strcmp(argv[curArg], "-norawr3"))
1358 fRawR3 = false;
1359 else if ( !strcmp(argv[curArg], "--patm")
1360 || !strcmp(argv[curArg], "-patm"))
1361 fPATM = true;
1362 else if ( !strcmp(argv[curArg], "--nopatm")
1363 || !strcmp(argv[curArg], "-nopatm"))
1364 fPATM = false;
1365 else if ( !strcmp(argv[curArg], "--csam")
1366 || !strcmp(argv[curArg], "-csam"))
1367 fCSAM = true;
1368 else if ( !strcmp(argv[curArg], "--nocsam")
1369 || !strcmp(argv[curArg], "-nocsam"))
1370 fCSAM = false;
1371 else if ( !strcmp(argv[curArg], "--hwvirtex")
1372 || !strcmp(argv[curArg], "-hwvirtex"))
1373 fHWVirt = true;
1374 else if ( !strcmp(argv[curArg], "--nohwvirtex")
1375 || !strcmp(argv[curArg], "-nohwvirtex"))
1376 fHWVirt = false;
1377 else if ( !strcmp(argv[curArg], "--warpdrive")
1378 || !strcmp(argv[curArg], "-warpdrive"))
1379 {
1380 if (++curArg >= argc)
1381 {
1382 RTPrintf("Error: missing the rate value for the --warpdrive option!\n");
1383 return 1;
1384 }
1385 u32WarpDrive = RTStrToUInt32(argv[curArg]);
1386 if (u32WarpDrive < 2 || u32WarpDrive > 20000)
1387 {
1388 RTPrintf("Error: the warp drive rate is restricted to [2..20000]. (%d)\n", u32WarpDrive);
1389 return 1;
1390 }
1391 }
1392#endif /* VBOXSDL_ADVANCED_OPTIONS */
1393#ifdef VBOX_WIN32_UI
1394 else if ( !strcmp(argv[curArg], "--win32ui")
1395 || !strcmp(argv[curArg], "-win32ui"))
1396 fWin32UI = true;
1397#endif
1398 else if ( !strcmp(argv[curArg], "--showsdlconfig")
1399 || !strcmp(argv[curArg], "-showsdlconfig"))
1400 fShowSDLConfig = true;
1401 else if ( !strcmp(argv[curArg], "--hostkey")
1402 || !strcmp(argv[curArg], "-hostkey"))
1403 {
1404 if (++curArg + 1 >= argc)
1405 {
1406 RTPrintf("Error: not enough arguments for host keys!\n");
1407 return 1;
1408 }
1409 gHostKeySym1 = atoi(argv[curArg++]);
1410 if (curArg + 1 < argc && (argv[curArg+1][0] == '0' || atoi(argv[curArg+1]) > 0))
1411 {
1412 /* two-key sequence as host key specified */
1413 gHostKeySym2 = atoi(argv[curArg++]);
1414 }
1415 gHostKeyMod = atoi(argv[curArg]);
1416 }
1417 /* just show the help screen */
1418 else
1419 {
1420 if ( strcmp(argv[curArg], "-h")
1421 && strcmp(argv[curArg], "-help")
1422 && strcmp(argv[curArg], "--help"))
1423 RTPrintf("Error: unrecognized switch '%s'\n", argv[curArg]);
1424 show_usage();
1425 return 1;
1426 }
1427 }
1428
1429 rc = com::Initialize();
1430#ifdef VBOX_WITH_XPCOM
1431 if (rc == NS_ERROR_FILE_ACCESS_DENIED)
1432 {
1433 char szHome[RTPATH_MAX] = "";
1434 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
1435 RTPrintf("Failed to initialize COM because the global settings directory '%s' is not accessible!\n", szHome);
1436 return 1;
1437 }
1438#endif
1439 if (FAILED(rc))
1440 {
1441 RTPrintf("Error: COM initialization failed (rc=%Rhrc)!\n", rc);
1442 return 1;
1443 }
1444
1445 /* NOTE: do not convert the following scope to a "do {} while (0);", as
1446 * this would make it all too tempting to use "break;" incorrectly - it
1447 * would skip over the cleanup. */
1448 {
1449 // scopes all the stuff till shutdown
1450 ////////////////////////////////////////////////////////////////////////////
1451
1452 ComPtr<IVirtualBoxClient> pVirtualBoxClient;
1453 ComPtr<IVirtualBox> pVirtualBox;
1454 ComPtr<ISession> pSession;
1455 bool sessionOpened = false;
1456 NativeEventQueue* eventQ = com::NativeEventQueue::getMainEventQueue();
1457
1458 ComPtr<IMachine> pMachine;
1459
1460 rc = pVirtualBoxClient.createInprocObject(CLSID_VirtualBoxClient);
1461 if (FAILED(rc))
1462 {
1463 com::ErrorInfo info;
1464 if (info.isFullAvailable())
1465 PrintError("Failed to create VirtualBoxClient object",
1466 info.getText().raw(), info.getComponent().raw());
1467 else
1468 RTPrintf("Failed to create VirtualBoxClient object! No error information available (rc=%Rhrc).\n", rc);
1469 goto leave;
1470 }
1471
1472 rc = pVirtualBoxClient->COMGETTER(VirtualBox)(pVirtualBox.asOutParam());
1473 if (FAILED(rc))
1474 {
1475 RTPrintf("Failed to get VirtualBox object (rc=%Rhrc)!\n", rc);
1476 goto leave;
1477 }
1478 rc = pVirtualBoxClient->COMGETTER(Session)(pSession.asOutParam());
1479 if (FAILED(rc))
1480 {
1481 RTPrintf("Failed to get session object (rc=%Rhrc)!\n", rc);
1482 goto leave;
1483 }
1484
1485 if (pcszSettingsPw)
1486 {
1487 CHECK_ERROR(pVirtualBox, SetSettingsSecret(Bstr(pcszSettingsPw).raw()));
1488 if (FAILED(rc))
1489 goto leave;
1490 }
1491 else if (pcszSettingsPwFile)
1492 {
1493 int rcExit = settingsPasswordFile(pVirtualBox, pcszSettingsPwFile);
1494 if (rcExit != RTEXITCODE_SUCCESS)
1495 goto leave;
1496 }
1497
1498 /*
1499 * Do we have a UUID?
1500 */
1501 if (uuidVM.isValid())
1502 {
1503 rc = pVirtualBox->FindMachine(uuidVM.toUtf16().raw(), pMachine.asOutParam());
1504 if (FAILED(rc) || !pMachine)
1505 {
1506 RTPrintf("Error: machine with the given ID not found!\n");
1507 goto leave;
1508 }
1509 }
1510 else if (vmName)
1511 {
1512 /*
1513 * Do we have a name but no UUID?
1514 */
1515 rc = pVirtualBox->FindMachine(Bstr(vmName).raw(), pMachine.asOutParam());
1516 if ((rc == S_OK) && pMachine)
1517 {
1518 Bstr bstrId;
1519 pMachine->COMGETTER(Id)(bstrId.asOutParam());
1520 uuidVM = Guid(bstrId);
1521 }
1522 else
1523 {
1524 RTPrintf("Error: machine with the given name not found!\n");
1525 RTPrintf("Check if this VM has been corrupted and is now inaccessible.");
1526 goto leave;
1527 }
1528 }
1529
1530 /* create SDL event semaphore */
1531 vrc = RTSemEventCreate(&g_EventSemSDLEvents);
1532 AssertReleaseRC(vrc);
1533
1534 rc = pVirtualBoxClient->CheckMachineError(pMachine);
1535 if (FAILED(rc))
1536 {
1537 com::ErrorInfo info;
1538 if (info.isFullAvailable())
1539 PrintError("The VM has errors",
1540 info.getText().raw(), info.getComponent().raw());
1541 else
1542 RTPrintf("Failed to check for VM errors! No error information available (rc=%Rhrc).\n", rc);
1543 goto leave;
1544 }
1545
1546 if (fSeparate)
1547 {
1548 MachineState_T machineState = MachineState_Null;
1549 pMachine->COMGETTER(State)(&machineState);
1550 if ( machineState == MachineState_Running
1551 || machineState == MachineState_Teleporting
1552 || machineState == MachineState_LiveSnapshotting
1553 || machineState == MachineState_Paused
1554 || machineState == MachineState_TeleportingPausedVM
1555 )
1556 {
1557 RTPrintf("VM is already running.\n");
1558 }
1559 else
1560 {
1561 ComPtr<IProgress> progress;
1562 rc = pMachine->LaunchVMProcess(pSession, Bstr("headless").raw(), ComSafeArrayNullInParam(), progress.asOutParam());
1563 if (SUCCEEDED(rc) && !progress.isNull())
1564 {
1565 RTPrintf("Waiting for VM to power on...\n");
1566 rc = progress->WaitForCompletion(-1);
1567 if (SUCCEEDED(rc))
1568 {
1569 BOOL completed = true;
1570 rc = progress->COMGETTER(Completed)(&completed);
1571 if (SUCCEEDED(rc))
1572 {
1573 LONG iRc;
1574 rc = progress->COMGETTER(ResultCode)(&iRc);
1575 if (SUCCEEDED(rc))
1576 {
1577 if (FAILED(iRc))
1578 {
1579 ProgressErrorInfo info(progress);
1580 com::GluePrintErrorInfo(info);
1581 }
1582 else
1583 {
1584 RTPrintf("VM has been successfully started.\n");
1585 /* LaunchVMProcess obtains a shared lock on the machine.
1586 * Unlock it here, because the lock will be obtained below
1587 * in the common code path as for already running VM.
1588 */
1589 pSession->UnlockMachine();
1590 }
1591 }
1592 }
1593 }
1594 }
1595 }
1596 if (FAILED(rc))
1597 {
1598 RTPrintf("Error: failed to power up VM! No error text available.\n");
1599 goto leave;
1600 }
1601
1602 rc = pMachine->LockMachine(pSession, LockType_Shared);
1603 }
1604 else
1605 {
1606 pSession->COMSETTER(Name)(Bstr("GUI/SDL").raw());
1607 rc = pMachine->LockMachine(pSession, LockType_VM);
1608 }
1609
1610 if (FAILED(rc))
1611 {
1612 com::ErrorInfo info;
1613 if (info.isFullAvailable())
1614 PrintError("Could not open VirtualBox session",
1615 info.getText().raw(), info.getComponent().raw());
1616 goto leave;
1617 }
1618 if (!pSession)
1619 {
1620 RTPrintf("Could not open VirtualBox session!\n");
1621 goto leave;
1622 }
1623 sessionOpened = true;
1624 // get the mutable VM we're dealing with
1625 pSession->COMGETTER(Machine)(gpMachine.asOutParam());
1626 if (!gpMachine)
1627 {
1628 com::ErrorInfo info;
1629 if (info.isFullAvailable())
1630 PrintError("Cannot start VM!",
1631 info.getText().raw(), info.getComponent().raw());
1632 else
1633 RTPrintf("Error: given machine not found!\n");
1634 goto leave;
1635 }
1636
1637 // get the VM console
1638 pSession->COMGETTER(Console)(gpConsole.asOutParam());
1639 if (!gpConsole)
1640 {
1641 RTPrintf("Given console not found!\n");
1642 goto leave;
1643 }
1644
1645 /*
1646 * Are we supposed to use a different hard disk file?
1647 */
1648 if (pcszHdaFile)
1649 {
1650 ComPtr<IMedium> pMedium;
1651
1652 /*
1653 * Strategy: if any registered hard disk points to the same file,
1654 * assign it. If not, register a new image and assign it to the VM.
1655 */
1656 Bstr bstrHdaFile(pcszHdaFile);
1657 pVirtualBox->OpenMedium(bstrHdaFile.raw(), DeviceType_HardDisk,
1658 AccessMode_ReadWrite, FALSE /* fForceNewUuid */,
1659 pMedium.asOutParam());
1660 if (!pMedium)
1661 {
1662 /* we've not found the image */
1663 RTPrintf("Adding hard disk '%s'...\n", pcszHdaFile);
1664 pVirtualBox->OpenMedium(bstrHdaFile.raw(), DeviceType_HardDisk,
1665 AccessMode_ReadWrite, FALSE /* fForceNewUuid */,
1666 pMedium.asOutParam());
1667 }
1668 /* do we have the right image now? */
1669 if (pMedium)
1670 {
1671 Bstr bstrSCName;
1672
1673 /* get the first IDE controller to attach the harddisk to
1674 * and if there is none, add one temporarily */
1675 {
1676 ComPtr<IStorageController> pStorageCtl;
1677 com::SafeIfaceArray<IStorageController> aStorageControllers;
1678 CHECK_ERROR(gpMachine, COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(aStorageControllers)));
1679 for (size_t i = 0; i < aStorageControllers.size(); ++ i)
1680 {
1681 StorageBus_T storageBus = StorageBus_Null;
1682
1683 CHECK_ERROR(aStorageControllers[i], COMGETTER(Bus)(&storageBus));
1684 if (storageBus == StorageBus_IDE)
1685 {
1686 pStorageCtl = aStorageControllers[i];
1687 break;
1688 }
1689 }
1690
1691 if (pStorageCtl)
1692 {
1693 CHECK_ERROR(pStorageCtl, COMGETTER(Name)(bstrSCName.asOutParam()));
1694 gpMachine->DetachDevice(bstrSCName.raw(), 0, 0);
1695 }
1696 else
1697 {
1698 bstrSCName = "IDE Controller";
1699 CHECK_ERROR(gpMachine, AddStorageController(bstrSCName.raw(),
1700 StorageBus_IDE,
1701 pStorageCtl.asOutParam()));
1702 }
1703 }
1704
1705 CHECK_ERROR(gpMachine, AttachDevice(bstrSCName.raw(), 0, 0,
1706 DeviceType_HardDisk, pMedium));
1707 /// @todo why is this attachment saved?
1708 }
1709 else
1710 {
1711 RTPrintf("Error: failed to mount the specified hard disk image!\n");
1712 goto leave;
1713 }
1714 }
1715
1716 /*
1717 * Mount a floppy if requested.
1718 */
1719 if (pcszFdaFile)
1720 do
1721 {
1722 ComPtr<IMedium> pMedium;
1723
1724 /* unmount? */
1725 if (!strcmp(pcszFdaFile, "none"))
1726 {
1727 /* nothing to do, NULL object will cause unmount */
1728 }
1729 else
1730 {
1731 Bstr bstrFdaFile(pcszFdaFile);
1732
1733 /* Assume it's a host drive name */
1734 ComPtr<IHost> pHost;
1735 CHECK_ERROR_BREAK(pVirtualBox, COMGETTER(Host)(pHost.asOutParam()));
1736 rc = pHost->FindHostFloppyDrive(bstrFdaFile.raw(),
1737 pMedium.asOutParam());
1738 if (FAILED(rc))
1739 {
1740 /* try to find an existing one */
1741 rc = pVirtualBox->OpenMedium(bstrFdaFile.raw(),
1742 DeviceType_Floppy,
1743 AccessMode_ReadWrite,
1744 FALSE /* fForceNewUuid */,
1745 pMedium.asOutParam());
1746 if (FAILED(rc))
1747 {
1748 /* try to add to the list */
1749 RTPrintf("Adding floppy image '%s'...\n", pcszFdaFile);
1750 CHECK_ERROR_BREAK(pVirtualBox,
1751 OpenMedium(bstrFdaFile.raw(),
1752 DeviceType_Floppy,
1753 AccessMode_ReadWrite,
1754 FALSE /* fForceNewUuid */,
1755 pMedium.asOutParam()));
1756 }
1757 }
1758 }
1759
1760 Bstr bstrSCName;
1761
1762 /* get the first floppy controller to attach the floppy to
1763 * and if there is none, add one temporarily */
1764 {
1765 ComPtr<IStorageController> pStorageCtl;
1766 com::SafeIfaceArray<IStorageController> aStorageControllers;
1767 CHECK_ERROR(gpMachine, COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(aStorageControllers)));
1768 for (size_t i = 0; i < aStorageControllers.size(); ++ i)
1769 {
1770 StorageBus_T storageBus = StorageBus_Null;
1771
1772 CHECK_ERROR(aStorageControllers[i], COMGETTER(Bus)(&storageBus));
1773 if (storageBus == StorageBus_Floppy)
1774 {
1775 pStorageCtl = aStorageControllers[i];
1776 break;
1777 }
1778 }
1779
1780 if (pStorageCtl)
1781 {
1782 CHECK_ERROR(pStorageCtl, COMGETTER(Name)(bstrSCName.asOutParam()));
1783 gpMachine->DetachDevice(bstrSCName.raw(), 0, 0);
1784 }
1785 else
1786 {
1787 bstrSCName = "Floppy Controller";
1788 CHECK_ERROR(gpMachine, AddStorageController(bstrSCName.raw(),
1789 StorageBus_Floppy,
1790 pStorageCtl.asOutParam()));
1791 }
1792 }
1793
1794 CHECK_ERROR(gpMachine, AttachDevice(bstrSCName.raw(), 0, 0,
1795 DeviceType_Floppy, pMedium));
1796 }
1797 while (0);
1798 if (FAILED(rc))
1799 goto leave;
1800
1801 /*
1802 * Mount a CD-ROM if requested.
1803 */
1804 if (pcszCdromFile)
1805 do
1806 {
1807 ComPtr<IMedium> pMedium;
1808
1809 /* unmount? */
1810 if (!strcmp(pcszCdromFile, "none"))
1811 {
1812 /* nothing to do, NULL object will cause unmount */
1813 }
1814 else
1815 {
1816 Bstr bstrCdromFile(pcszCdromFile);
1817
1818 /* Assume it's a host drive name */
1819 ComPtr<IHost> pHost;
1820 CHECK_ERROR_BREAK(pVirtualBox, COMGETTER(Host)(pHost.asOutParam()));
1821 rc = pHost->FindHostDVDDrive(bstrCdromFile.raw(), pMedium.asOutParam());
1822 if (FAILED(rc))
1823 {
1824 /* try to find an existing one */
1825 rc = pVirtualBox->OpenMedium(bstrCdromFile.raw(),
1826 DeviceType_DVD,
1827 AccessMode_ReadWrite,
1828 FALSE /* fForceNewUuid */,
1829 pMedium.asOutParam());
1830 if (FAILED(rc))
1831 {
1832 /* try to add to the list */
1833 RTPrintf("Adding ISO image '%s'...\n", pcszCdromFile);
1834 CHECK_ERROR_BREAK(pVirtualBox,
1835 OpenMedium(bstrCdromFile.raw(),
1836 DeviceType_DVD,
1837 AccessMode_ReadWrite,
1838 FALSE /* fForceNewUuid */,
1839 pMedium.asOutParam()));
1840 }
1841 }
1842 }
1843
1844 Bstr bstrSCName;
1845
1846 /* get the first IDE controller to attach the DVD drive to
1847 * and if there is none, add one temporarily */
1848 {
1849 ComPtr<IStorageController> pStorageCtl;
1850 com::SafeIfaceArray<IStorageController> aStorageControllers;
1851 CHECK_ERROR(gpMachine, COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(aStorageControllers)));
1852 for (size_t i = 0; i < aStorageControllers.size(); ++ i)
1853 {
1854 StorageBus_T storageBus = StorageBus_Null;
1855
1856 CHECK_ERROR(aStorageControllers[i], COMGETTER(Bus)(&storageBus));
1857 if (storageBus == StorageBus_IDE)
1858 {
1859 pStorageCtl = aStorageControllers[i];
1860 break;
1861 }
1862 }
1863
1864 if (pStorageCtl)
1865 {
1866 CHECK_ERROR(pStorageCtl, COMGETTER(Name)(bstrSCName.asOutParam()));
1867 gpMachine->DetachDevice(bstrSCName.raw(), 1, 0);
1868 }
1869 else
1870 {
1871 bstrSCName = "IDE Controller";
1872 CHECK_ERROR(gpMachine, AddStorageController(bstrSCName.raw(),
1873 StorageBus_IDE,
1874 pStorageCtl.asOutParam()));
1875 }
1876 }
1877
1878 CHECK_ERROR(gpMachine, AttachDevice(bstrSCName.raw(), 1, 0,
1879 DeviceType_DVD, pMedium));
1880 }
1881 while (0);
1882 if (FAILED(rc))
1883 goto leave;
1884
1885 if (fDiscardState)
1886 {
1887 /*
1888 * If the machine is currently saved,
1889 * discard the saved state first.
1890 */
1891 MachineState_T machineState;
1892 gpMachine->COMGETTER(State)(&machineState);
1893 if (machineState == MachineState_Saved)
1894 {
1895 CHECK_ERROR(gpMachine, DiscardSavedState(true /* fDeleteFile */));
1896 }
1897 /*
1898 * If there are snapshots, discard the current state,
1899 * i.e. revert to the last snapshot.
1900 */
1901 ULONG cSnapshots;
1902 gpMachine->COMGETTER(SnapshotCount)(&cSnapshots);
1903 if (cSnapshots)
1904 {
1905 gpProgress = NULL;
1906
1907 ComPtr<ISnapshot> pCurrentSnapshot;
1908 CHECK_ERROR(gpMachine, COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam()));
1909 if (FAILED(rc))
1910 goto leave;
1911
1912 CHECK_ERROR(gpMachine, RestoreSnapshot(pCurrentSnapshot, gpProgress.asOutParam()));
1913 rc = gpProgress->WaitForCompletion(-1);
1914 }
1915 }
1916
1917 // get the machine debugger (does not have to be there)
1918 gpConsole->COMGETTER(Debugger)(gpMachineDebugger.asOutParam());
1919 if (gpMachineDebugger)
1920 {
1921 Log(("Machine debugger available!\n"));
1922 }
1923 gpConsole->COMGETTER(Display)(gpDisplay.asOutParam());
1924 if (!gpDisplay)
1925 {
1926 RTPrintf("Error: could not get display object!\n");
1927 goto leave;
1928 }
1929
1930 // set the boot drive
1931 if (bootDevice != DeviceType_Null)
1932 {
1933 rc = gpMachine->SetBootOrder(1, bootDevice);
1934 if (rc != S_OK)
1935 {
1936 RTPrintf("Error: could not set boot device, using default.\n");
1937 }
1938 }
1939
1940 // set the memory size if not default
1941 if (memorySize)
1942 {
1943 rc = gpMachine->COMSETTER(MemorySize)(memorySize);
1944 if (rc != S_OK)
1945 {
1946 ULONG ramSize = 0;
1947 gpMachine->COMGETTER(MemorySize)(&ramSize);
1948 RTPrintf("Error: could not set memory size, using current setting of %d MBytes\n", ramSize);
1949 }
1950 }
1951
1952 if (vramSize)
1953 {
1954 rc = gpMachine->COMSETTER(VRAMSize)(vramSize);
1955 if (rc != S_OK)
1956 {
1957 gpMachine->COMGETTER(VRAMSize)((ULONG*)&vramSize);
1958 RTPrintf("Error: could not set VRAM size, using current setting of %d MBytes\n", vramSize);
1959 }
1960 }
1961
1962 // we're always able to process absolute mouse events and we prefer that
1963 gfAbsoluteMouseHost = TRUE;
1964
1965#ifdef VBOX_WIN32_UI
1966 if (fWin32UI)
1967 {
1968 /* initialize the Win32 user interface inside which SDL will be embedded */
1969 if (initUI(fResizable, winId))
1970 return 1;
1971 }
1972#endif
1973
1974 /* static initialization of the SDL stuff */
1975 if (!VBoxSDLFB::init(fShowSDLConfig))
1976 goto leave;
1977
1978 gpMachine->COMGETTER(MonitorCount)(&gcMonitors);
1979 if (gcMonitors > 64)
1980 gcMonitors = 64;
1981
1982 for (unsigned i = 0; i < gcMonitors; i++)
1983 {
1984 // create our SDL framebuffer instance
1985 gpFramebuffer[i].createObject();
1986 rc = gpFramebuffer[i]->init(i, fFullscreen, fResizable, fShowSDLConfig, false,
1987 fixedWidth, fixedHeight, fixedBPP, fSeparate);
1988 if (FAILED(rc))
1989 {
1990 RTPrintf("Error: could not create framebuffer object!\n");
1991 goto leave;
1992 }
1993 }
1994
1995#ifdef VBOX_WIN32_UI
1996 gpFramebuffer[0]->setWinId(winId);
1997#endif
1998
1999 for (unsigned i = 0; i < gcMonitors; i++)
2000 {
2001 if (!gpFramebuffer[i]->initialized())
2002 goto leave;
2003 gpFramebuffer[i]->AddRef();
2004 if (fFullscreen)
2005 SetFullscreen(true);
2006 }
2007
2008#ifdef VBOX_SECURELABEL
2009 if (fSecureLabel)
2010 {
2011 if (!secureLabelFontFile)
2012 {
2013 RTPrintf("Error: no font file specified for secure label!\n");
2014 goto leave;
2015 }
2016 /* load the SDL_ttf library and get the required imports */
2017 vrc = RTLdrLoadSystem(LIBSDL_TTF_NAME, true /*fNoUnload*/, &gLibrarySDL_ttf);
2018 if (RT_SUCCESS(vrc))
2019 vrc = RTLdrGetSymbol(gLibrarySDL_ttf, "TTF_Init", (void**)&pTTF_Init);
2020 if (RT_SUCCESS(vrc))
2021 vrc = RTLdrGetSymbol(gLibrarySDL_ttf, "TTF_OpenFont", (void**)&pTTF_OpenFont);
2022 if (RT_SUCCESS(vrc))
2023 vrc = RTLdrGetSymbol(gLibrarySDL_ttf, "TTF_RenderUTF8_Solid", (void**)&pTTF_RenderUTF8_Solid);
2024 if (RT_SUCCESS(vrc))
2025 {
2026 /* silently ignore errors here */
2027 vrc = RTLdrGetSymbol(gLibrarySDL_ttf, "TTF_RenderUTF8_Blended", (void**)&pTTF_RenderUTF8_Blended);
2028 if (RT_FAILURE(vrc))
2029 pTTF_RenderUTF8_Blended = NULL;
2030 vrc = VINF_SUCCESS;
2031 }
2032 if (RT_SUCCESS(vrc))
2033 vrc = RTLdrGetSymbol(gLibrarySDL_ttf, "TTF_CloseFont", (void**)&pTTF_CloseFont);
2034 if (RT_SUCCESS(vrc))
2035 vrc = RTLdrGetSymbol(gLibrarySDL_ttf, "TTF_Quit", (void**)&pTTF_Quit);
2036 if (RT_SUCCESS(vrc))
2037 vrc = gpFramebuffer[0]->initSecureLabel(SECURE_LABEL_HEIGHT, secureLabelFontFile, secureLabelPointSize, secureLabelFontOffs);
2038 if (RT_FAILURE(vrc))
2039 {
2040 RTPrintf("Error: could not initialize secure labeling: rc = %Rrc\n", vrc);
2041 goto leave;
2042 }
2043 Bstr bstrLabel;
2044 gpMachine->GetExtraData(Bstr(VBOXSDL_SECURELABEL_EXTRADATA).raw(), bstrLabel.asOutParam());
2045 Utf8Str labelUtf8(bstrLabel);
2046 /*
2047 * Now update the label
2048 */
2049 gpFramebuffer[0]->setSecureLabelColor(secureLabelColorFG, secureLabelColorBG);
2050 gpFramebuffer[0]->setSecureLabelText(labelUtf8.c_str());
2051 }
2052#endif
2053
2054#ifdef VBOXSDL_WITH_X11
2055 /* NOTE1: We still want Ctrl-C to work, so we undo the SDL redirections.
2056 * NOTE2: We have to remove the PidFile if this file exists. */
2057 signal(SIGINT, signal_handler_SIGINT);
2058 signal(SIGQUIT, signal_handler_SIGINT);
2059 signal(SIGSEGV, signal_handler_SIGINT);
2060#endif
2061
2062
2063 for (ULONG i = 0; i < gcMonitors; i++)
2064 {
2065 // register our framebuffer
2066 rc = gpDisplay->AttachFramebuffer(i, gpFramebuffer[i], gaFramebufferId[i].asOutParam());
2067 if (FAILED(rc))
2068 {
2069 RTPrintf("Error: could not register framebuffer object!\n");
2070 goto leave;
2071 }
2072 ULONG dummy;
2073 LONG xOrigin, yOrigin;
2074 GuestMonitorStatus_T monitorStatus;
2075 rc = gpDisplay->GetScreenResolution(i, &dummy, &dummy, &dummy, &xOrigin, &yOrigin, &monitorStatus);
2076 gpFramebuffer[i]->setOrigin(xOrigin, yOrigin);
2077 }
2078
2079 {
2080 // register listener for VirtualBoxClient events
2081 ComPtr<IEventSource> pES;
2082 CHECK_ERROR(pVirtualBoxClient, COMGETTER(EventSource)(pES.asOutParam()));
2083 ComObjPtr<VBoxSDLClientEventListenerImpl> listener;
2084 listener.createObject();
2085 listener->init(new VBoxSDLClientEventListener());
2086 pVBoxClientListener = listener;
2087 com::SafeArray<VBoxEventType_T> eventTypes;
2088 eventTypes.push_back(VBoxEventType_OnVBoxSVCAvailabilityChanged);
2089 CHECK_ERROR(pES, RegisterListener(pVBoxClientListener, ComSafeArrayAsInParam(eventTypes), true));
2090 }
2091
2092 {
2093 // register listener for VirtualBox (server) events
2094 ComPtr<IEventSource> pES;
2095 CHECK_ERROR(pVirtualBox, COMGETTER(EventSource)(pES.asOutParam()));
2096 ComObjPtr<VBoxSDLEventListenerImpl> listener;
2097 listener.createObject();
2098 listener->init(new VBoxSDLEventListener());
2099 pVBoxListener = listener;
2100 com::SafeArray<VBoxEventType_T> eventTypes;
2101 eventTypes.push_back(VBoxEventType_OnExtraDataChanged);
2102 CHECK_ERROR(pES, RegisterListener(pVBoxListener, ComSafeArrayAsInParam(eventTypes), true));
2103 }
2104
2105 {
2106 // register listener for Console events
2107 ComPtr<IEventSource> pES;
2108 CHECK_ERROR(gpConsole, COMGETTER(EventSource)(pES.asOutParam()));
2109 pConsoleListener.createObject();
2110 pConsoleListener->init(new VBoxSDLConsoleEventListener());
2111 com::SafeArray<VBoxEventType_T> eventTypes;
2112 eventTypes.push_back(VBoxEventType_OnMousePointerShapeChanged);
2113 eventTypes.push_back(VBoxEventType_OnMouseCapabilityChanged);
2114 eventTypes.push_back(VBoxEventType_OnKeyboardLedsChanged);
2115 eventTypes.push_back(VBoxEventType_OnStateChanged);
2116 eventTypes.push_back(VBoxEventType_OnRuntimeError);
2117 eventTypes.push_back(VBoxEventType_OnCanShowWindow);
2118 eventTypes.push_back(VBoxEventType_OnShowWindow);
2119 CHECK_ERROR(pES, RegisterListener(pConsoleListener, ComSafeArrayAsInParam(eventTypes), true));
2120 // until we've tried to to start the VM, ignore power off events
2121 pConsoleListener->getWrapped()->ignorePowerOffEvents(true);
2122 }
2123
2124 if (pszPortVRDP)
2125 {
2126 rc = gpMachine->COMGETTER(VRDEServer)(gpVRDEServer.asOutParam());
2127 AssertMsg((rc == S_OK) && gpVRDEServer, ("Could not get VRDP Server! rc = 0x%x\n", rc));
2128 if (gpVRDEServer)
2129 {
2130 // has a non standard VRDP port been requested?
2131 if (strcmp(pszPortVRDP, "0"))
2132 {
2133 rc = gpVRDEServer->SetVRDEProperty(Bstr("TCP/Ports").raw(), Bstr(pszPortVRDP).raw());
2134 if (rc != S_OK)
2135 {
2136 RTPrintf("Error: could not set VRDP port! rc = 0x%x\n", rc);
2137 goto leave;
2138 }
2139 }
2140 // now enable VRDP
2141 rc = gpVRDEServer->COMSETTER(Enabled)(TRUE);
2142 if (rc != S_OK)
2143 {
2144 RTPrintf("Error: could not enable VRDP server! rc = 0x%x\n", rc);
2145 goto leave;
2146 }
2147 }
2148 }
2149
2150 rc = E_FAIL;
2151#ifdef VBOXSDL_ADVANCED_OPTIONS
2152 if (fRawR0 != ~0U)
2153 {
2154 if (!gpMachineDebugger)
2155 {
2156 RTPrintf("Error: No debugger object; -%srawr0 cannot be executed!\n", fRawR0 ? "" : "no");
2157 goto leave;
2158 }
2159 gpMachineDebugger->COMSETTER(RecompileSupervisor)(!fRawR0);
2160 }
2161 if (fRawR3 != ~0U)
2162 {
2163 if (!gpMachineDebugger)
2164 {
2165 RTPrintf("Error: No debugger object; -%srawr3 cannot be executed!\n", fRawR3 ? "" : "no");
2166 goto leave;
2167 }
2168 gpMachineDebugger->COMSETTER(RecompileUser)(!fRawR3);
2169 }
2170 if (fPATM != ~0U)
2171 {
2172 if (!gpMachineDebugger)
2173 {
2174 RTPrintf("Error: No debugger object; -%spatm cannot be executed!\n", fPATM ? "" : "no");
2175 goto leave;
2176 }
2177 gpMachineDebugger->COMSETTER(PATMEnabled)(fPATM);
2178 }
2179 if (fCSAM != ~0U)
2180 {
2181 if (!gpMachineDebugger)
2182 {
2183 RTPrintf("Error: No debugger object; -%scsam cannot be executed!\n", fCSAM ? "" : "no");
2184 goto leave;
2185 }
2186 gpMachineDebugger->COMSETTER(CSAMEnabled)(fCSAM);
2187 }
2188 if (fHWVirt != ~0U)
2189 {
2190 gpMachine->SetHWVirtExProperty(HWVirtExPropertyType_Enabled, fHWVirt);
2191 }
2192 if (u32WarpDrive != 0)
2193 {
2194 if (!gpMachineDebugger)
2195 {
2196 RTPrintf("Error: No debugger object; --warpdrive %d cannot be executed!\n", u32WarpDrive);
2197 goto leave;
2198 }
2199 gpMachineDebugger->COMSETTER(VirtualTimeRate)(u32WarpDrive);
2200 }
2201#endif /* VBOXSDL_ADVANCED_OPTIONS */
2202
2203 /* start with something in the titlebar */
2204 UpdateTitlebar(TITLEBAR_NORMAL);
2205
2206 /* memorize the default cursor */
2207 gpDefaultCursor = SDL_GetCursor();
2208
2209#if !defined(VBOX_WITH_SDL2)
2210# if defined(VBOXSDL_WITH_X11)
2211 /* Get Window Manager info. We only need the X11 display. */
2212 SDL_VERSION(&gSdlInfo.version);
2213 if (!SDL_GetWMInfo(&gSdlInfo))
2214 RTPrintf("Error: could not get SDL Window Manager info -- no Xcursor support!\n");
2215 else
2216 gfXCursorEnabled = TRUE;
2217
2218# if !defined(VBOX_WITHOUT_XCURSOR)
2219 /* SDL uses its own (plain) default cursor. Use the left arrow cursor instead which might look
2220 * much better if a mouse cursor theme is installed. */
2221 if (gfXCursorEnabled)
2222 {
2223 gpDefaultOrigX11Cursor = *(Cursor*)gpDefaultCursor->wm_cursor;
2224 *(Cursor*)gpDefaultCursor->wm_cursor = XCreateFontCursor(gSdlInfo.info.x11.display, XC_left_ptr);
2225 SDL_SetCursor(gpDefaultCursor);
2226 }
2227# endif
2228 /* Initialise the keyboard */
2229 X11DRV_InitKeyboard(gSdlInfo.info.x11.display, NULL, NULL, NULL, NULL);
2230# endif /* VBOXSDL_WITH_X11 */
2231
2232 /* create a fake empty cursor */
2233 {
2234 uint8_t cursorData[1] = {0};
2235 gpCustomCursor = SDL_CreateCursor(cursorData, cursorData, 8, 1, 0, 0);
2236 gpCustomOrigWMcursor = gpCustomCursor->wm_cursor;
2237 gpCustomCursor->wm_cursor = NULL;
2238 }
2239#endif /* !VBOX_WITH_SDL2 */
2240
2241 /*
2242 * Register our user signal handler.
2243 */
2244#ifdef VBOXSDL_WITH_X11
2245 struct sigaction sa;
2246 sa.sa_sigaction = signal_handler_SIGUSR1;
2247 sigemptyset(&sa.sa_mask);
2248 sa.sa_flags = SA_RESTART | SA_SIGINFO;
2249 sigaction(SIGUSR1, &sa, NULL);
2250#endif /* VBOXSDL_WITH_X11 */
2251
2252 /*
2253 * Start the VM execution thread. This has to be done
2254 * asynchronously as powering up can take some time
2255 * (accessing devices such as the host DVD drive). In
2256 * the meantime, we have to service the SDL event loop.
2257 */
2258 SDL_Event event;
2259
2260 if (!fSeparate)
2261 {
2262 LogFlow(("Powering up the VM...\n"));
2263 rc = gpConsole->PowerUp(gpProgress.asOutParam());
2264 if (rc != S_OK)
2265 {
2266 com::ErrorInfo info(gpConsole, COM_IIDOF(IConsole));
2267 if (info.isBasicAvailable())
2268 PrintError("Failed to power up VM", info.getText().raw());
2269 else
2270 RTPrintf("Error: failed to power up VM! No error text available.\n");
2271 goto leave;
2272 }
2273 }
2274
2275#ifdef USE_XPCOM_QUEUE_THREAD
2276 /*
2277 * Before we starting to do stuff, we have to launch the XPCOM
2278 * event queue thread. It will wait for events and send messages
2279 * to the SDL thread. After having done this, we should fairly
2280 * quickly start to process the SDL event queue as an XPCOM
2281 * event storm might arrive. Stupid SDL has a ridiculously small
2282 * event queue buffer!
2283 */
2284 startXPCOMEventQueueThread(eventQ->getSelectFD());
2285#endif /* USE_XPCOM_QUEUE_THREAD */
2286
2287 /* termination flag */
2288 bool fTerminateDuringStartup;
2289 fTerminateDuringStartup = false;
2290
2291 LogRel(("VBoxSDL: NUM lock initially %s, CAPS lock initially %s\n",
2292 !!(SDL_GetModState() & KMOD_NUM) ? "ON" : "OFF",
2293 !!(SDL_GetModState() & KMOD_CAPS) ? "ON" : "OFF"));
2294
2295 /* start regular timer so we don't starve in the event loop */
2296 SDL_TimerID sdlTimer;
2297 sdlTimer = SDL_AddTimer(100, StartupTimer, NULL);
2298
2299 /* loop until the powerup processing is done */
2300 MachineState_T machineState;
2301 do
2302 {
2303 rc = gpMachine->COMGETTER(State)(&machineState);
2304 if ( rc == S_OK
2305 && ( machineState == MachineState_Starting
2306 || machineState == MachineState_Restoring
2307 || machineState == MachineState_TeleportingIn
2308 )
2309 )
2310 {
2311 /*
2312 * wait for the next event. This is uncritical as
2313 * power up guarantees to change the machine state
2314 * to either running or aborted and a machine state
2315 * change will send us an event. However, we have to
2316 * service the XPCOM event queue!
2317 */
2318#ifdef USE_XPCOM_QUEUE_THREAD
2319 if (!fXPCOMEventThreadSignaled)
2320 {
2321 signalXPCOMEventQueueThread();
2322 fXPCOMEventThreadSignaled = true;
2323 }
2324#endif
2325 /*
2326 * Wait for SDL events.
2327 */
2328 if (WaitSDLEvent(&event))
2329 {
2330 switch (event.type)
2331 {
2332 /*
2333 * Timer event. Used to have the titlebar updated.
2334 */
2335 case SDL_USER_EVENT_TIMER:
2336 {
2337 /*
2338 * Update the title bar.
2339 */
2340 UpdateTitlebar(TITLEBAR_STARTUP);
2341 break;
2342 }
2343
2344 /*
2345 * User specific framebuffer change event.
2346 */
2347 case SDL_USER_EVENT_NOTIFYCHANGE:
2348 {
2349 LogFlow(("SDL_USER_EVENT_NOTIFYCHANGE\n"));
2350 LONG xOrigin, yOrigin;
2351 gpFramebuffer[event.user.code]->notifyChange(event.user.code);
2352 /* update xOrigin, yOrigin -> mouse */
2353 ULONG dummy;
2354 GuestMonitorStatus_T monitorStatus;
2355 rc = gpDisplay->GetScreenResolution(event.user.code, &dummy, &dummy, &dummy, &xOrigin, &yOrigin, &monitorStatus);
2356 gpFramebuffer[event.user.code]->setOrigin(xOrigin, yOrigin);
2357 break;
2358 }
2359
2360#ifdef USE_XPCOM_QUEUE_THREAD
2361 /*
2362 * User specific XPCOM event queue event
2363 */
2364 case SDL_USER_EVENT_XPCOM_EVENTQUEUE:
2365 {
2366 LogFlow(("SDL_USER_EVENT_XPCOM_EVENTQUEUE: processing XPCOM event queue...\n"));
2367 eventQ->processEventQueue(0);
2368 signalXPCOMEventQueueThread();
2369 break;
2370 }
2371#endif /* USE_XPCOM_QUEUE_THREAD */
2372
2373 /*
2374 * Termination event from the on state change callback.
2375 */
2376 case SDL_USER_EVENT_TERMINATE:
2377 {
2378 if (event.user.code != VBOXSDL_TERM_NORMAL)
2379 {
2380 com::ProgressErrorInfo info(gpProgress);
2381 if (info.isBasicAvailable())
2382 PrintError("Failed to power up VM", info.getText().raw());
2383 else
2384 RTPrintf("Error: failed to power up VM! No error text available.\n");
2385 }
2386 fTerminateDuringStartup = true;
2387 break;
2388 }
2389
2390 default:
2391 {
2392 Log8(("VBoxSDL: Unknown SDL event %d (pre)\n", event.type));
2393 break;
2394 }
2395 }
2396
2397 }
2398 }
2399 eventQ->processEventQueue(0);
2400 } while ( rc == S_OK
2401 && ( machineState == MachineState_Starting
2402 || machineState == MachineState_Restoring
2403 || machineState == MachineState_TeleportingIn
2404 )
2405 );
2406
2407 /* kill the timer again */
2408 SDL_RemoveTimer(sdlTimer);
2409 sdlTimer = 0;
2410
2411 /* are we supposed to terminate the process? */
2412 if (fTerminateDuringStartup)
2413 goto leave;
2414
2415 /* did the power up succeed? */
2416 if (machineState != MachineState_Running)
2417 {
2418 com::ProgressErrorInfo info(gpProgress);
2419 if (info.isBasicAvailable())
2420 PrintError("Failed to power up VM", info.getText().raw());
2421 else
2422 RTPrintf("Error: failed to power up VM! No error text available (rc = 0x%x state = %d)\n", rc, machineState);
2423 goto leave;
2424 }
2425
2426 // accept power off events from now on because we're running
2427 // note that there's a possible race condition here...
2428 pConsoleListener->getWrapped()->ignorePowerOffEvents(false);
2429
2430 rc = gpConsole->COMGETTER(Keyboard)(gpKeyboard.asOutParam());
2431 if (!gpKeyboard)
2432 {
2433 RTPrintf("Error: could not get keyboard object!\n");
2434 goto leave;
2435 }
2436 gpConsole->COMGETTER(Mouse)(gpMouse.asOutParam());
2437 if (!gpMouse)
2438 {
2439 RTPrintf("Error: could not get mouse object!\n");
2440 goto leave;
2441 }
2442
2443 if (fSeparate && gpMouse)
2444 {
2445 LogFlow(("Fetching mouse caps\n"));
2446
2447 /* Fetch current mouse status, etc */
2448 gpMouse->COMGETTER(AbsoluteSupported)(&gfAbsoluteMouseGuest);
2449 gpMouse->COMGETTER(RelativeSupported)(&gfRelativeMouseGuest);
2450 gpMouse->COMGETTER(NeedsHostCursor)(&gfGuestNeedsHostCursor);
2451
2452 HandleGuestCapsChanged();
2453
2454 ComPtr<IMousePointerShape> mps;
2455 gpMouse->COMGETTER(PointerShape)(mps.asOutParam());
2456 if (!mps.isNull())
2457 {
2458 BOOL visible, alpha;
2459 ULONG hotX, hotY, width, height;
2460 com::SafeArray <BYTE> shape;
2461
2462 mps->COMGETTER(Visible)(&visible);
2463 mps->COMGETTER(Alpha)(&alpha);
2464 mps->COMGETTER(HotX)(&hotX);
2465 mps->COMGETTER(HotY)(&hotY);
2466 mps->COMGETTER(Width)(&width);
2467 mps->COMGETTER(Height)(&height);
2468 mps->COMGETTER(Shape)(ComSafeArrayAsOutParam(shape));
2469
2470 if (shape.size() > 0)
2471 {
2472 PointerShapeChangeData data(visible, alpha, hotX, hotY, width, height,
2473 ComSafeArrayAsInParam(shape));
2474 SetPointerShape(&data);
2475 }
2476 }
2477 }
2478
2479 UpdateTitlebar(TITLEBAR_NORMAL);
2480
2481#ifdef VBOX_WITH_SDL2
2482 /* Key repeats are enabled by default on SDL2. */
2483#else
2484 /*
2485 * Enable keyboard repeats
2486 */
2487 SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
2488#endif
2489
2490 /*
2491 * Create PID file.
2492 */
2493 if (gpszPidFile)
2494 {
2495 char szBuf[32];
2496 const char *pcszLf = "\n";
2497 RTFILE PidFile;
2498 RTFileOpen(&PidFile, gpszPidFile, RTFILE_O_WRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_NONE);
2499 RTStrFormatNumber(szBuf, RTProcSelf(), 10, 0, 0, 0);
2500 RTFileWrite(PidFile, szBuf, strlen(szBuf), NULL);
2501 RTFileWrite(PidFile, pcszLf, strlen(pcszLf), NULL);
2502 RTFileClose(PidFile);
2503 }
2504
2505 /*
2506 * Main event loop
2507 */
2508#ifdef USE_XPCOM_QUEUE_THREAD
2509 if (!fXPCOMEventThreadSignaled)
2510 {
2511 signalXPCOMEventQueueThread();
2512 }
2513#endif
2514 LogFlow(("VBoxSDL: Entering big event loop\n"));
2515 while (WaitSDLEvent(&event))
2516 {
2517 switch (event.type)
2518 {
2519 /*
2520 * The screen needs to be repainted.
2521 */
2522#ifdef VBOX_WITH_SDL2
2523 case SDL_WINDOWEVENT:
2524 {
2525 switch (event.window.event)
2526 {
2527 case SDL_WINDOWEVENT_EXPOSED:
2528 {
2529 VBoxSDLFB *fb = getFbFromWinId(event.window.windowID);
2530 if (fb)
2531 fb->repaint();
2532 break;
2533 }
2534 case SDL_WINDOWEVENT_FOCUS_GAINED:
2535 {
2536 break;
2537 }
2538 case SDL_WINDOWEVENT_FOCUS_LOST:
2539 {
2540 break;
2541 }
2542 case SDL_WINDOWEVENT_RESIZED:
2543 {
2544 if (gpDisplay)
2545 {
2546 if (gfIgnoreNextResize)
2547 {
2548 gfIgnoreNextResize = FALSE;
2549 break;
2550 }
2551 uResizeWidth = event.window.data1;
2552#ifdef VBOX_SECURELABEL
2553 if (fSecureLabel)
2554 uResizeHeight = RT_MAX(0, event.window.data2 - SECURE_LABEL_HEIGHT);
2555 else
2556#endif
2557 uResizeHeight = event.window.data2;
2558 if (gSdlResizeTimer)
2559 SDL_RemoveTimer(gSdlResizeTimer);
2560 gSdlResizeTimer = SDL_AddTimer(300, ResizeTimer, NULL);
2561 }
2562 break;
2563 }
2564 default:
2565 break;
2566 }
2567 }
2568#else
2569 case SDL_VIDEOEXPOSE:
2570 {
2571 gpFramebuffer[0]->repaint();
2572 break;
2573 }
2574#endif
2575
2576 /*
2577 * Keyboard events.
2578 */
2579 case SDL_KEYDOWN:
2580 case SDL_KEYUP:
2581 {
2582#ifdef VBOX_WITH_SDL2
2583 SDL_Keycode ksym = event.key.keysym.sym;
2584#else
2585 SDLKey ksym = event.key.keysym.sym;
2586#endif
2587 switch (enmHKeyState)
2588 {
2589 case HKEYSTATE_NORMAL:
2590 {
2591 if ( event.type == SDL_KEYDOWN
2592 && ksym != SDLK_UNKNOWN
2593 && (ksym == gHostKeySym1 || ksym == gHostKeySym2))
2594 {
2595 EvHKeyDown1 = event;
2596 enmHKeyState = ksym == gHostKeySym1 ? HKEYSTATE_DOWN_1ST
2597 : HKEYSTATE_DOWN_2ND;
2598 break;
2599 }
2600 ProcessKey(&event.key);
2601 break;
2602 }
2603
2604 case HKEYSTATE_DOWN_1ST:
2605 case HKEYSTATE_DOWN_2ND:
2606 {
2607 if (gHostKeySym2 != SDLK_UNKNOWN)
2608 {
2609 if ( event.type == SDL_KEYDOWN
2610 && ksym != SDLK_UNKNOWN
2611 && ( (enmHKeyState == HKEYSTATE_DOWN_1ST && ksym == gHostKeySym2)
2612 || (enmHKeyState == HKEYSTATE_DOWN_2ND && ksym == gHostKeySym1)))
2613 {
2614 EvHKeyDown2 = event;
2615 enmHKeyState = HKEYSTATE_DOWN;
2616 break;
2617 }
2618 enmHKeyState = event.type == SDL_KEYUP ? HKEYSTATE_NORMAL
2619 : HKEYSTATE_NOT_IT;
2620 ProcessKey(&EvHKeyDown1.key);
2621 /* ugly hack: Some guests (e.g. mstsc.exe on Windows XP)
2622 * expect a small delay between two key events. 5ms work
2623 * reliable here so use 10ms to be on the safe side. A
2624 * better but more complicated fix would be to introduce
2625 * a new state and don't wait here. */
2626 RTThreadSleep(10);
2627 ProcessKey(&event.key);
2628 break;
2629 }
2630 }
2631 RT_FALL_THRU();
2632
2633 case HKEYSTATE_DOWN:
2634 {
2635 if (event.type == SDL_KEYDOWN)
2636 {
2637 /* potential host key combination, try execute it */
2638 int irc = HandleHostKey(&event.key);
2639 if (irc == VINF_SUCCESS)
2640 {
2641 enmHKeyState = HKEYSTATE_USED;
2642 break;
2643 }
2644 if (RT_SUCCESS(irc))
2645 goto leave;
2646 }
2647 else /* SDL_KEYUP */
2648 {
2649 if ( ksym != SDLK_UNKNOWN
2650 && (ksym == gHostKeySym1 || ksym == gHostKeySym2))
2651 {
2652 /* toggle grabbing state */
2653 if (!gfGrabbed)
2654 InputGrabStart();
2655 else
2656 InputGrabEnd();
2657
2658 /* SDL doesn't always reset the keystates, correct it */
2659 ResetKeys();
2660 enmHKeyState = HKEYSTATE_NORMAL;
2661 break;
2662 }
2663 }
2664
2665 /* not host key */
2666 enmHKeyState = HKEYSTATE_NOT_IT;
2667 ProcessKey(&EvHKeyDown1.key);
2668 /* see the comment for the 2-key case above */
2669 RTThreadSleep(10);
2670 if (gHostKeySym2 != SDLK_UNKNOWN)
2671 {
2672 ProcessKey(&EvHKeyDown2.key);
2673 /* see the comment for the 2-key case above */
2674 RTThreadSleep(10);
2675 }
2676 ProcessKey(&event.key);
2677 break;
2678 }
2679
2680 case HKEYSTATE_USED:
2681 {
2682 if ((SDL_GetModState() & ~(KMOD_MODE | KMOD_NUM | KMOD_RESERVED)) == 0)
2683 enmHKeyState = HKEYSTATE_NORMAL;
2684 if (event.type == SDL_KEYDOWN)
2685 {
2686 int irc = HandleHostKey(&event.key);
2687 if (RT_SUCCESS(irc) && irc != VINF_SUCCESS)
2688 goto leave;
2689 }
2690 break;
2691 }
2692
2693 default:
2694 AssertMsgFailed(("enmHKeyState=%d\n", enmHKeyState));
2695 RT_FALL_THRU();
2696 case HKEYSTATE_NOT_IT:
2697 {
2698 if ((SDL_GetModState() & ~(KMOD_MODE | KMOD_NUM | KMOD_RESERVED)) == 0)
2699 enmHKeyState = HKEYSTATE_NORMAL;
2700 ProcessKey(&event.key);
2701 break;
2702 }
2703 } /* state switch */
2704 break;
2705 }
2706
2707 /*
2708 * The window was closed.
2709 */
2710 case SDL_QUIT:
2711 {
2712 if (!gfACPITerm || gSdlQuitTimer)
2713 goto leave;
2714 if (gpConsole)
2715 gpConsole->PowerButton();
2716 gSdlQuitTimer = SDL_AddTimer(1000, QuitTimer, NULL);
2717 break;
2718 }
2719
2720 /*
2721 * The mouse has moved
2722 */
2723 case SDL_MOUSEMOTION:
2724 {
2725 if (gfGrabbed || UseAbsoluteMouse())
2726 {
2727 VBoxSDLFB *fb;
2728#ifdef VBOX_WITH_SDL2
2729 fb = getFbFromWinId(event.motion.windowID);
2730#else
2731 fb = gpFramebuffer[0];
2732#endif
2733 AssertPtrBreak(fb);
2734 SendMouseEvent(fb, 0, 0, 0);
2735 }
2736 break;
2737 }
2738
2739 /*
2740 * A mouse button has been clicked or released.
2741 */
2742 case SDL_MOUSEBUTTONDOWN:
2743 case SDL_MOUSEBUTTONUP:
2744 {
2745 SDL_MouseButtonEvent *bev = &event.button;
2746 /* don't grab on mouse click if we have guest additions */
2747 if (!gfGrabbed && !UseAbsoluteMouse() && gfGrabOnMouseClick)
2748 {
2749 if (event.type == SDL_MOUSEBUTTONDOWN && (bev->state & SDL_BUTTON_LMASK))
2750 {
2751 /* start grabbing all events */
2752 InputGrabStart();
2753 }
2754 }
2755 else if (gfGrabbed || UseAbsoluteMouse())
2756 {
2757#ifdef VBOX_WITH_SDL2
2758 int dz = 0; /** @todo Implement mouse wheel support with SDL2 (event SDL_MOUSEWHEEL). */
2759#else
2760 int dz = bev->button == SDL_BUTTON_WHEELUP
2761 ? -1
2762 : bev->button == SDL_BUTTON_WHEELDOWN
2763 ? +1
2764 : 0;
2765#endif
2766 /* end host key combination (CTRL+MouseButton) */
2767 switch (enmHKeyState)
2768 {
2769 case HKEYSTATE_DOWN_1ST:
2770 case HKEYSTATE_DOWN_2ND:
2771 enmHKeyState = HKEYSTATE_NOT_IT;
2772 ProcessKey(&EvHKeyDown1.key);
2773 /* ugly hack: small delay to ensure that the key event is
2774 * actually handled _prior_ to the mouse click event */
2775 RTThreadSleep(20);
2776 break;
2777 case HKEYSTATE_DOWN:
2778 enmHKeyState = HKEYSTATE_NOT_IT;
2779 ProcessKey(&EvHKeyDown1.key);
2780 if (gHostKeySym2 != SDLK_UNKNOWN)
2781 ProcessKey(&EvHKeyDown2.key);
2782 /* ugly hack: small delay to ensure that the key event is
2783 * actually handled _prior_ to the mouse click event */
2784 RTThreadSleep(20);
2785 break;
2786 default:
2787 break;
2788 }
2789
2790 VBoxSDLFB *fb;
2791#ifdef VBOX_WITH_SDL2
2792 fb = getFbFromWinId(event.button.windowID);
2793#else
2794 fb = gpFramebuffer[0];
2795#endif
2796 AssertPtrBreak(fb);
2797 SendMouseEvent(fb, dz, event.type == SDL_MOUSEBUTTONDOWN, bev->button);
2798 }
2799 break;
2800 }
2801
2802#ifndef VBOX_WITH_SDL2
2803 /*
2804 * The window has gained or lost focus.
2805 */
2806 case SDL_ACTIVEEVENT: /** @todo Needs to be also fixed with SDL2? Check! */
2807 {
2808 /*
2809 * There is a strange behaviour in SDL when running without a window
2810 * manager: When SDL_WM_GrabInput(SDL_GRAB_ON) is called we receive two
2811 * consecutive events SDL_ACTIVEEVENTs (input lost, input gained).
2812 * Asking SDL_GetAppState() seems the better choice.
2813 */
2814 if (gfGrabbed && (SDL_GetAppState() & SDL_APPINPUTFOCUS) == 0)
2815 {
2816 /*
2817 * another window has stolen the (keyboard) input focus
2818 */
2819 InputGrabEnd();
2820 }
2821 break;
2822 }
2823
2824 /*
2825 * The SDL window was resized.
2826 * For SDL2 this is done in SDL_WINDOWEVENT.
2827 */
2828 case SDL_VIDEORESIZE:
2829 {
2830 if (gpDisplay)
2831 {
2832 if (gfIgnoreNextResize)
2833 {
2834 gfIgnoreNextResize = FALSE;
2835 break;
2836 }
2837 uResizeWidth = event.resize.w;
2838#ifdef VBOX_SECURELABEL
2839 if (fSecureLabel)
2840 uResizeHeight = RT_MAX(0, event.resize.h - SECURE_LABEL_HEIGHT);
2841 else
2842#endif
2843 uResizeHeight = event.resize.h;
2844 if (gSdlResizeTimer)
2845 SDL_RemoveTimer(gSdlResizeTimer);
2846 gSdlResizeTimer = SDL_AddTimer(300, ResizeTimer, NULL);
2847 }
2848 break;
2849 }
2850#endif
2851
2852 /*
2853 * User specific update event.
2854 */
2855 /** @todo use a common user event handler so that SDL_PeepEvents() won't
2856 * possibly remove other events in the queue!
2857 */
2858 case SDL_USER_EVENT_UPDATERECT:
2859 {
2860 /*
2861 * Decode event parameters.
2862 */
2863 ASMAtomicDecS32(&g_cNotifyUpdateEventsPending);
2864 #define DECODEX(event) (int)((intptr_t)(event).user.data1 >> 16)
2865 #define DECODEY(event) (int)((intptr_t)(event).user.data1 & 0xFFFF)
2866 #define DECODEW(event) (int)((intptr_t)(event).user.data2 >> 16)
2867 #define DECODEH(event) (int)((intptr_t)(event).user.data2 & 0xFFFF)
2868 int x = DECODEX(event);
2869 int y = DECODEY(event);
2870 int w = DECODEW(event);
2871 int h = DECODEH(event);
2872 LogFlow(("SDL_USER_EVENT_UPDATERECT: x = %d, y = %d, w = %d, h = %d\n",
2873 x, y, w, h));
2874
2875 Assert(gpFramebuffer[event.user.code]);
2876 gpFramebuffer[event.user.code]->update(x, y, w, h, true /* fGuestRelative */);
2877
2878 #undef DECODEX
2879 #undef DECODEY
2880 #undef DECODEW
2881 #undef DECODEH
2882 break;
2883 }
2884
2885 /*
2886 * User event: Window resize done
2887 */
2888 case SDL_USER_EVENT_WINDOW_RESIZE_DONE:
2889 {
2890 /**
2891 * @todo This is a workaround for synchronization problems between EMT and the
2892 * SDL main thread. It can happen that the SDL thread already starts a
2893 * new resize operation while the EMT is still busy with the old one
2894 * leading to a deadlock. Therefore we call SetVideoModeHint only once
2895 * when the mouse button was released.
2896 */
2897 /* communicate the resize event to the guest */
2898 gpDisplay->SetVideoModeHint(0 /*=display*/, true /*=enabled*/, false /*=changeOrigin*/,
2899 0 /*=originX*/, 0 /*=originY*/,
2900 uResizeWidth, uResizeHeight, 0 /*=don't change bpp*/, true /*=notify*/);
2901 break;
2902
2903 }
2904
2905 /*
2906 * User specific framebuffer change event.
2907 */
2908 case SDL_USER_EVENT_NOTIFYCHANGE:
2909 {
2910 LogFlow(("SDL_USER_EVENT_NOTIFYCHANGE\n"));
2911 LONG xOrigin, yOrigin;
2912 gpFramebuffer[event.user.code]->notifyChange(event.user.code);
2913 /* update xOrigin, yOrigin -> mouse */
2914 ULONG dummy;
2915 GuestMonitorStatus_T monitorStatus;
2916 rc = gpDisplay->GetScreenResolution(event.user.code, &dummy, &dummy, &dummy, &xOrigin, &yOrigin, &monitorStatus);
2917 gpFramebuffer[event.user.code]->setOrigin(xOrigin, yOrigin);
2918 break;
2919 }
2920
2921#ifdef USE_XPCOM_QUEUE_THREAD
2922 /*
2923 * User specific XPCOM event queue event
2924 */
2925 case SDL_USER_EVENT_XPCOM_EVENTQUEUE:
2926 {
2927 LogFlow(("SDL_USER_EVENT_XPCOM_EVENTQUEUE: processing XPCOM event queue...\n"));
2928 eventQ->processEventQueue(0);
2929 signalXPCOMEventQueueThread();
2930 break;
2931 }
2932#endif /* USE_XPCOM_QUEUE_THREAD */
2933
2934 /*
2935 * User specific update title bar notification event
2936 */
2937 case SDL_USER_EVENT_UPDATE_TITLEBAR:
2938 {
2939 UpdateTitlebar(TITLEBAR_NORMAL);
2940 break;
2941 }
2942
2943 /*
2944 * User specific termination event
2945 */
2946 case SDL_USER_EVENT_TERMINATE:
2947 {
2948 if (event.user.code != VBOXSDL_TERM_NORMAL)
2949 RTPrintf("Error: VM terminated abnormally!\n");
2950 goto leave;
2951 }
2952
2953#ifdef VBOX_SECURELABEL
2954 /*
2955 * User specific secure label update event
2956 */
2957 case SDL_USER_EVENT_SECURELABEL_UPDATE:
2958 {
2959 /*
2960 * Query the new label text
2961 */
2962 Bstr bstrLabel;
2963 gpMachine->GetExtraData(Bstr(VBOXSDL_SECURELABEL_EXTRADATA).raw(), bstrLabel.asOutParam());
2964 Utf8Str labelUtf8(bstrLabel);
2965 /*
2966 * Now update the label
2967 */
2968 gpFramebuffer[0]->setSecureLabelText(labelUtf8.c_str());
2969 break;
2970 }
2971#endif /* VBOX_SECURELABEL */
2972
2973 /*
2974 * User specific pointer shape change event
2975 */
2976 case SDL_USER_EVENT_POINTER_CHANGE:
2977 {
2978 PointerShapeChangeData *data = (PointerShapeChangeData *)event.user.data1;
2979 SetPointerShape (data);
2980 delete data;
2981 break;
2982 }
2983
2984 /*
2985 * User specific guest capabilities changed
2986 */
2987 case SDL_USER_EVENT_GUEST_CAP_CHANGED:
2988 {
2989 HandleGuestCapsChanged();
2990 break;
2991 }
2992
2993 default:
2994 {
2995 Log8(("unknown SDL event %d\n", event.type));
2996 break;
2997 }
2998 }
2999 }
3000
3001leave:
3002 if (gpszPidFile)
3003 RTFileDelete(gpszPidFile);
3004
3005 LogFlow(("leaving...\n"));
3006#if defined(VBOX_WITH_XPCOM) && !defined(RT_OS_DARWIN) && !defined(RT_OS_OS2)
3007 /* make sure the XPCOM event queue thread doesn't do anything harmful */
3008 terminateXPCOMQueueThread();
3009#endif /* VBOX_WITH_XPCOM */
3010
3011 if (gpVRDEServer)
3012 rc = gpVRDEServer->COMSETTER(Enabled)(FALSE);
3013
3014 /*
3015 * Get the machine state.
3016 */
3017 if (gpMachine)
3018 gpMachine->COMGETTER(State)(&machineState);
3019 else
3020 machineState = MachineState_Aborted;
3021
3022 if (!fSeparate)
3023 {
3024 /*
3025 * Turn off the VM if it's running
3026 */
3027 if ( gpConsole
3028 && ( machineState == MachineState_Running
3029 || machineState == MachineState_Teleporting
3030 || machineState == MachineState_LiveSnapshotting
3031 /** @todo power off paused VMs too? */
3032 )
3033 )
3034 do
3035 {
3036 pConsoleListener->getWrapped()->ignorePowerOffEvents(true);
3037 ComPtr<IProgress> pProgress;
3038 CHECK_ERROR_BREAK(gpConsole, PowerDown(pProgress.asOutParam()));
3039 CHECK_ERROR_BREAK(pProgress, WaitForCompletion(-1));
3040 BOOL completed;
3041 CHECK_ERROR_BREAK(pProgress, COMGETTER(Completed)(&completed));
3042 ASSERT(completed);
3043 LONG hrc;
3044 CHECK_ERROR_BREAK(pProgress, COMGETTER(ResultCode)(&hrc));
3045 if (FAILED(hrc))
3046 {
3047 com::ErrorInfo info;
3048 if (info.isFullAvailable())
3049 PrintError("Failed to power down VM",
3050 info.getText().raw(), info.getComponent().raw());
3051 else
3052 RTPrintf("Failed to power down virtual machine! No error information available (rc = 0x%x).\n", hrc);
3053 break;
3054 }
3055 } while (0);
3056 }
3057
3058 /* unregister Console listener */
3059 if (pConsoleListener)
3060 {
3061 ComPtr<IEventSource> pES;
3062 CHECK_ERROR(gpConsole, COMGETTER(EventSource)(pES.asOutParam()));
3063 if (!pES.isNull())
3064 CHECK_ERROR(pES, UnregisterListener(pConsoleListener));
3065 pConsoleListener.setNull();
3066 }
3067
3068 /*
3069 * Now we discard all settings so that our changes will
3070 * not be flushed to the permanent configuration
3071 */
3072 if ( gpMachine
3073 && machineState != MachineState_Saved)
3074 {
3075 rc = gpMachine->DiscardSettings();
3076 AssertMsg(SUCCEEDED(rc), ("DiscardSettings %Rhrc, machineState %d\n", rc, machineState));
3077 }
3078
3079 /* close the session */
3080 if (sessionOpened)
3081 {
3082 rc = pSession->UnlockMachine();
3083 AssertComRC(rc);
3084 }
3085
3086#ifndef VBOX_WITH_SDL2
3087 /* restore the default cursor and free the custom one if any */
3088 if (gpDefaultCursor)
3089 {
3090# ifdef VBOXSDL_WITH_X11
3091 Cursor pDefaultTempX11Cursor = 0;
3092 if (gfXCursorEnabled)
3093 {
3094 pDefaultTempX11Cursor = *(Cursor*)gpDefaultCursor->wm_cursor;
3095 *(Cursor*)gpDefaultCursor->wm_cursor = gpDefaultOrigX11Cursor;
3096 }
3097# endif /* VBOXSDL_WITH_X11 */
3098 SDL_SetCursor(gpDefaultCursor);
3099# if defined(VBOXSDL_WITH_X11) && !defined(VBOX_WITHOUT_XCURSOR)
3100 if (gfXCursorEnabled)
3101 XFreeCursor(gSdlInfo.info.x11.display, pDefaultTempX11Cursor);
3102# endif /* VBOXSDL_WITH_X11 && !VBOX_WITHOUT_XCURSOR */
3103 }
3104
3105 if (gpCustomCursor)
3106 {
3107 WMcursor *pCustomTempWMCursor = gpCustomCursor->wm_cursor;
3108 gpCustomCursor->wm_cursor = gpCustomOrigWMcursor;
3109 SDL_FreeCursor(gpCustomCursor);
3110 if (pCustomTempWMCursor)
3111 {
3112# if defined(RT_OS_WINDOWS)
3113 ::DestroyCursor(*(HCURSOR *)pCustomTempWMCursor);
3114# elif defined(VBOXSDL_WITH_X11) && !defined(VBOX_WITHOUT_XCURSOR)
3115 if (gfXCursorEnabled)
3116 XFreeCursor(gSdlInfo.info.x11.display, *(Cursor *)pCustomTempWMCursor);
3117# endif /* VBOXSDL_WITH_X11 && !VBOX_WITHOUT_XCURSOR */
3118 free(pCustomTempWMCursor);
3119 }
3120 }
3121#endif
3122
3123 LogFlow(("Releasing mouse, keyboard, remote desktop server, display, console...\n"));
3124 if (gpDisplay)
3125 {
3126 for (unsigned i = 0; i < gcMonitors; i++)
3127 gpDisplay->DetachFramebuffer(i, gaFramebufferId[i].raw());
3128 }
3129
3130 gpMouse = NULL;
3131 gpKeyboard = NULL;
3132 gpVRDEServer = NULL;
3133 gpDisplay = NULL;
3134 gpConsole = NULL;
3135 gpMachineDebugger = NULL;
3136 gpProgress = NULL;
3137 // we can only uninitialize SDL here because it is not threadsafe
3138
3139 for (unsigned i = 0; i < gcMonitors; i++)
3140 {
3141 if (gpFramebuffer[i])
3142 {
3143 LogFlow(("Releasing framebuffer...\n"));
3144 gpFramebuffer[i]->Release();
3145 gpFramebuffer[i] = NULL;
3146 }
3147 }
3148
3149 VBoxSDLFB::uninit();
3150
3151#ifdef VBOX_SECURELABEL
3152 /* must do this after destructing the framebuffer */
3153 if (gLibrarySDL_ttf)
3154 RTLdrClose(gLibrarySDL_ttf);
3155#endif
3156
3157 /* VirtualBox (server) listener unregistration. */
3158 if (pVBoxListener)
3159 {
3160 ComPtr<IEventSource> pES;
3161 CHECK_ERROR(pVirtualBox, COMGETTER(EventSource)(pES.asOutParam()));
3162 if (!pES.isNull())
3163 CHECK_ERROR(pES, UnregisterListener(pVBoxListener));
3164 pVBoxListener.setNull();
3165 }
3166
3167 /* VirtualBoxClient listener unregistration. */
3168 if (pVBoxClientListener)
3169 {
3170 ComPtr<IEventSource> pES;
3171 CHECK_ERROR(pVirtualBoxClient, COMGETTER(EventSource)(pES.asOutParam()));
3172 if (!pES.isNull())
3173 CHECK_ERROR(pES, UnregisterListener(pVBoxClientListener));
3174 pVBoxClientListener.setNull();
3175 }
3176
3177 LogFlow(("Releasing machine, session...\n"));
3178 gpMachine = NULL;
3179 pSession = NULL;
3180 LogFlow(("Releasing VirtualBox object...\n"));
3181 pVirtualBox = NULL;
3182 LogFlow(("Releasing VirtualBoxClient object...\n"));
3183 pVirtualBoxClient = NULL;
3184
3185 // end "all-stuff" scope
3186 ////////////////////////////////////////////////////////////////////////////
3187 }
3188
3189 /* Must be before com::Shutdown() */
3190 LogFlow(("Uninitializing COM...\n"));
3191 com::Shutdown();
3192
3193 LogFlow(("Returning from main()!\n"));
3194 RTLogFlush(NULL);
3195 return FAILED(rc) ? 1 : 0;
3196}
3197
3198#ifndef VBOX_WITH_HARDENING
3199/**
3200 * Main entry point
3201 */
3202int main(int argc, char **argv)
3203{
3204#ifdef Q_WS_X11
3205 if (!XInitThreads())
3206 return 1;
3207#endif
3208 /*
3209 * Before we do *anything*, we initialize the runtime.
3210 */
3211 int rc = RTR3InitExe(argc, &argv, RTR3INIT_FLAGS_SUPLIB);
3212 if (RT_FAILURE(rc))
3213 return RTMsgInitFailure(rc);
3214 return TrustedMain(argc, argv, NULL);
3215}
3216#endif /* !VBOX_WITH_HARDENING */
3217
3218
3219/**
3220 * Returns whether the absolute mouse is in use, i.e. both host
3221 * and guest have opted to enable it.
3222 *
3223 * @returns bool Flag whether the absolute mouse is in use
3224 */
3225static bool UseAbsoluteMouse(void)
3226{
3227 return (gfAbsoluteMouseHost && gfAbsoluteMouseGuest);
3228}
3229
3230#if defined(RT_OS_DARWIN) || defined(RT_OS_OS2)
3231/**
3232 * Fallback keycode conversion using SDL symbols.
3233 *
3234 * This is used to catch keycodes that's missing from the translation table.
3235 *
3236 * @returns XT scancode
3237 * @param ev SDL scancode
3238 */
3239static uint16_t Keyevent2KeycodeFallback(const SDL_KeyboardEvent *ev)
3240{
3241 const SDLKey sym = ev->keysym.sym;
3242 Log(("SDL key event: sym=%d scancode=%#x unicode=%#x\n",
3243 sym, ev->keysym.scancode, ev->keysym.unicode));
3244 switch (sym)
3245 { /* set 1 scan code */
3246 case SDLK_ESCAPE: return 0x01;
3247 case SDLK_EXCLAIM:
3248 case SDLK_1: return 0x02;
3249 case SDLK_AT:
3250 case SDLK_2: return 0x03;
3251 case SDLK_HASH:
3252 case SDLK_3: return 0x04;
3253 case SDLK_DOLLAR:
3254 case SDLK_4: return 0x05;
3255 /* % */
3256 case SDLK_5: return 0x06;
3257 case SDLK_CARET:
3258 case SDLK_6: return 0x07;
3259 case SDLK_AMPERSAND:
3260 case SDLK_7: return 0x08;
3261 case SDLK_ASTERISK:
3262 case SDLK_8: return 0x09;
3263 case SDLK_LEFTPAREN:
3264 case SDLK_9: return 0x0a;
3265 case SDLK_RIGHTPAREN:
3266 case SDLK_0: return 0x0b;
3267 case SDLK_UNDERSCORE:
3268 case SDLK_MINUS: return 0x0c;
3269 case SDLK_EQUALS:
3270 case SDLK_PLUS: return 0x0d;
3271 case SDLK_BACKSPACE: return 0x0e;
3272 case SDLK_TAB: return 0x0f;
3273 case SDLK_q: return 0x10;
3274 case SDLK_w: return 0x11;
3275 case SDLK_e: return 0x12;
3276 case SDLK_r: return 0x13;
3277 case SDLK_t: return 0x14;
3278 case SDLK_y: return 0x15;
3279 case SDLK_u: return 0x16;
3280 case SDLK_i: return 0x17;
3281 case SDLK_o: return 0x18;
3282 case SDLK_p: return 0x19;
3283 case SDLK_LEFTBRACKET: return 0x1a;
3284 case SDLK_RIGHTBRACKET: return 0x1b;
3285 case SDLK_RETURN: return 0x1c;
3286 case SDLK_KP_ENTER: return 0x1c | 0x100;
3287 case SDLK_LCTRL: return 0x1d;
3288 case SDLK_RCTRL: return 0x1d | 0x100;
3289 case SDLK_a: return 0x1e;
3290 case SDLK_s: return 0x1f;
3291 case SDLK_d: return 0x20;
3292 case SDLK_f: return 0x21;
3293 case SDLK_g: return 0x22;
3294 case SDLK_h: return 0x23;
3295 case SDLK_j: return 0x24;
3296 case SDLK_k: return 0x25;
3297 case SDLK_l: return 0x26;
3298 case SDLK_COLON:
3299 case SDLK_SEMICOLON: return 0x27;
3300 case SDLK_QUOTEDBL:
3301 case SDLK_QUOTE: return 0x28;
3302 case SDLK_BACKQUOTE: return 0x29;
3303 case SDLK_LSHIFT: return 0x2a;
3304 case SDLK_BACKSLASH: return 0x2b;
3305 case SDLK_z: return 0x2c;
3306 case SDLK_x: return 0x2d;
3307 case SDLK_c: return 0x2e;
3308 case SDLK_v: return 0x2f;
3309 case SDLK_b: return 0x30;
3310 case SDLK_n: return 0x31;
3311 case SDLK_m: return 0x32;
3312 case SDLK_LESS:
3313 case SDLK_COMMA: return 0x33;
3314 case SDLK_GREATER:
3315 case SDLK_PERIOD: return 0x34;
3316 case SDLK_KP_DIVIDE: /*??*/
3317 case SDLK_QUESTION:
3318 case SDLK_SLASH: return 0x35;
3319 case SDLK_RSHIFT: return 0x36;
3320 case SDLK_KP_MULTIPLY:
3321 case SDLK_PRINT: return 0x37; /* fixme */
3322 case SDLK_LALT: return 0x38;
3323 case SDLK_MODE: /* alt gr*/
3324 case SDLK_RALT: return 0x38 | 0x100;
3325 case SDLK_SPACE: return 0x39;
3326 case SDLK_CAPSLOCK: return 0x3a;
3327 case SDLK_F1: return 0x3b;
3328 case SDLK_F2: return 0x3c;
3329 case SDLK_F3: return 0x3d;
3330 case SDLK_F4: return 0x3e;
3331 case SDLK_F5: return 0x3f;
3332 case SDLK_F6: return 0x40;
3333 case SDLK_F7: return 0x41;
3334 case SDLK_F8: return 0x42;
3335 case SDLK_F9: return 0x43;
3336 case SDLK_F10: return 0x44;
3337 case SDLK_PAUSE: return 0x45; /* not right */
3338 case SDLK_NUMLOCK: return 0x45;
3339 case SDLK_SCROLLOCK: return 0x46;
3340 case SDLK_KP7: return 0x47;
3341 case SDLK_HOME: return 0x47 | 0x100;
3342 case SDLK_KP8: return 0x48;
3343 case SDLK_UP: return 0x48 | 0x100;
3344 case SDLK_KP9: return 0x49;
3345 case SDLK_PAGEUP: return 0x49 | 0x100;
3346 case SDLK_KP_MINUS: return 0x4a;
3347 case SDLK_KP4: return 0x4b;
3348 case SDLK_LEFT: return 0x4b | 0x100;
3349 case SDLK_KP5: return 0x4c;
3350 case SDLK_KP6: return 0x4d;
3351 case SDLK_RIGHT: return 0x4d | 0x100;
3352 case SDLK_KP_PLUS: return 0x4e;
3353 case SDLK_KP1: return 0x4f;
3354 case SDLK_END: return 0x4f | 0x100;
3355 case SDLK_KP2: return 0x50;
3356 case SDLK_DOWN: return 0x50 | 0x100;
3357 case SDLK_KP3: return 0x51;
3358 case SDLK_PAGEDOWN: return 0x51 | 0x100;
3359 case SDLK_KP0: return 0x52;
3360 case SDLK_INSERT: return 0x52 | 0x100;
3361 case SDLK_KP_PERIOD: return 0x53;
3362 case SDLK_DELETE: return 0x53 | 0x100;
3363 case SDLK_SYSREQ: return 0x54;
3364 case SDLK_F11: return 0x57;
3365 case SDLK_F12: return 0x58;
3366 case SDLK_F13: return 0x5b;
3367 case SDLK_LMETA:
3368 case SDLK_LSUPER: return 0x5b | 0x100;
3369 case SDLK_F14: return 0x5c;
3370 case SDLK_RMETA:
3371 case SDLK_RSUPER: return 0x5c | 0x100;
3372 case SDLK_F15: return 0x5d;
3373 case SDLK_MENU: return 0x5d | 0x100;
3374#if 0
3375 case SDLK_CLEAR: return 0x;
3376 case SDLK_KP_EQUALS: return 0x;
3377 case SDLK_COMPOSE: return 0x;
3378 case SDLK_HELP: return 0x;
3379 case SDLK_BREAK: return 0x;
3380 case SDLK_POWER: return 0x;
3381 case SDLK_EURO: return 0x;
3382 case SDLK_UNDO: return 0x;
3383#endif
3384 default:
3385 Log(("Unhandled sdl key event: sym=%d scancode=%#x unicode=%#x\n",
3386 ev->keysym.sym, ev->keysym.scancode, ev->keysym.unicode));
3387 return 0;
3388 }
3389}
3390#endif /* RT_OS_DARWIN */
3391
3392/**
3393 * Converts an SDL keyboard eventcode to a XT scancode.
3394 *
3395 * @returns XT scancode
3396 * @param ev SDL scancode
3397 */
3398static uint16_t Keyevent2Keycode(const SDL_KeyboardEvent *ev)
3399{
3400 // start with the scancode determined by SDL
3401 int keycode = ev->keysym.scancode;
3402
3403#ifdef VBOXSDL_WITH_X11
3404# ifdef VBOX_WITH_SDL2
3405
3406 switch (ev->keysym.sym)
3407 {
3408 case SDLK_ESCAPE: return 0x01;
3409 case SDLK_EXCLAIM:
3410 case SDLK_1: return 0x02;
3411 case SDLK_AT:
3412 case SDLK_2: return 0x03;
3413 case SDLK_HASH:
3414 case SDLK_3: return 0x04;
3415 case SDLK_DOLLAR:
3416 case SDLK_4: return 0x05;
3417 /* % */
3418 case SDLK_5: return 0x06;
3419 case SDLK_CARET:
3420 case SDLK_6: return 0x07;
3421 case SDLK_AMPERSAND:
3422 case SDLK_7: return 0x08;
3423 case SDLK_ASTERISK:
3424 case SDLK_8: return 0x09;
3425 case SDLK_LEFTPAREN:
3426 case SDLK_9: return 0x0a;
3427 case SDLK_RIGHTPAREN:
3428 case SDLK_0: return 0x0b;
3429 case SDLK_UNDERSCORE:
3430 case SDLK_MINUS: return 0x0c;
3431 case SDLK_PLUS: return 0x0d;
3432 case SDLK_BACKSPACE: return 0x0e;
3433 case SDLK_TAB: return 0x0f;
3434 case SDLK_q: return 0x10;
3435 case SDLK_w: return 0x11;
3436 case SDLK_e: return 0x12;
3437 case SDLK_r: return 0x13;
3438 case SDLK_t: return 0x14;
3439 case SDLK_y: return 0x15;
3440 case SDLK_u: return 0x16;
3441 case SDLK_i: return 0x17;
3442 case SDLK_o: return 0x18;
3443 case SDLK_p: return 0x19;
3444 case SDLK_RETURN: return 0x1c;
3445 case SDLK_KP_ENTER: return 0x1c | 0x100;
3446 case SDLK_LCTRL: return 0x1d;
3447 case SDLK_RCTRL: return 0x1d | 0x100;
3448 case SDLK_a: return 0x1e;
3449 case SDLK_s: return 0x1f;
3450 case SDLK_d: return 0x20;
3451 case SDLK_f: return 0x21;
3452 case SDLK_g: return 0x22;
3453 case SDLK_h: return 0x23;
3454 case SDLK_j: return 0x24;
3455 case SDLK_k: return 0x25;
3456 case SDLK_l: return 0x26;
3457 case SDLK_COLON: return 0x27;
3458 case SDLK_QUOTEDBL:
3459 case SDLK_QUOTE: return 0x28;
3460 case SDLK_BACKQUOTE: return 0x29;
3461 case SDLK_LSHIFT: return 0x2a;
3462 case SDLK_z: return 0x2c;
3463 case SDLK_x: return 0x2d;
3464 case SDLK_c: return 0x2e;
3465 case SDLK_v: return 0x2f;
3466 case SDLK_b: return 0x30;
3467 case SDLK_n: return 0x31;
3468 case SDLK_m: return 0x32;
3469 case SDLK_LESS: return 0x33;
3470 case SDLK_GREATER: return 0x34;
3471 case SDLK_KP_DIVIDE: /*??*/
3472 case SDLK_QUESTION: return 0x35;
3473 case SDLK_RSHIFT: return 0x36;
3474 case SDLK_KP_MULTIPLY:
3475 case SDLK_PRINT: return 0x37; /* fixme */
3476 case SDLK_LALT: return 0x38;
3477 case SDLK_MODE: /* alt gr*/
3478 case SDLK_RALT: return 0x38 | 0x100;
3479 case SDLK_SPACE: return 0x39;
3480 case SDLK_CAPSLOCK: return 0x3a;
3481 case SDLK_F1: return 0x3b;
3482 case SDLK_F2: return 0x3c;
3483 case SDLK_F3: return 0x3d;
3484 case SDLK_F4: return 0x3e;
3485 case SDLK_F5: return 0x3f;
3486 case SDLK_F6: return 0x40;
3487 case SDLK_F7: return 0x41;
3488 case SDLK_F8: return 0x42;
3489 case SDLK_F9: return 0x43;
3490 case SDLK_F10: return 0x44;
3491 case SDLK_PAUSE: return 0x45; /* not right */
3492 case SDLK_NUMLOCK: return 0x45;
3493 case SDLK_SCROLLOCK: return 0x46;
3494 case SDLK_KP7: return 0x47;
3495 case SDLK_HOME: return 0x47 | 0x100;
3496 case SDLK_KP8: return 0x48;
3497 case SDLK_UP: return 0x48 | 0x100;
3498 case SDLK_KP9: return 0x49;
3499 case SDLK_PAGEUP: return 0x49 | 0x100;
3500 case SDLK_KP_MINUS: return 0x4a;
3501 case SDLK_KP4: return 0x4b;
3502 case SDLK_LEFT: return 0x4b | 0x100;
3503 case SDLK_KP5: return 0x4c;
3504 case SDLK_KP6: return 0x4d;
3505 case SDLK_RIGHT: return 0x4d | 0x100;
3506 case SDLK_KP_PLUS: return 0x4e;
3507 case SDLK_KP1: return 0x4f;
3508 case SDLK_END: return 0x4f | 0x100;
3509 case SDLK_KP2: return 0x50;
3510 case SDLK_DOWN: return 0x50 | 0x100;
3511 case SDLK_KP3: return 0x51;
3512 case SDLK_PAGEDOWN: return 0x51 | 0x100;
3513 case SDLK_KP0: return 0x52;
3514 case SDLK_INSERT: return 0x52 | 0x100;
3515 case SDLK_KP_PERIOD: return 0x53;
3516 case SDLK_DELETE: return 0x53 | 0x100;
3517 case SDLK_SYSREQ: return 0x54;
3518 case SDLK_F11: return 0x57;
3519 case SDLK_F12: return 0x58;
3520 case SDLK_F13: return 0x5b;
3521 case SDLK_F14: return 0x5c;
3522 case SDLK_F15: return 0x5d;
3523 case SDLK_MENU: return 0x5d | 0x100;
3524 default:
3525 return 0;
3526 }
3527# else
3528 keycode = X11DRV_KeyEvent(gSdlInfo.info.x11.display, keycode);
3529# endif
3530#elif defined(RT_OS_DARWIN)
3531 /* This is derived partially from SDL_QuartzKeys.h and partially from testing. */
3532 static const uint16_t s_aMacToSet1[] =
3533 {
3534 /* set-1 SDL_QuartzKeys.h */
3535 0x1e, /* QZ_a 0x00 */
3536 0x1f, /* QZ_s 0x01 */
3537 0x20, /* QZ_d 0x02 */
3538 0x21, /* QZ_f 0x03 */
3539 0x23, /* QZ_h 0x04 */
3540 0x22, /* QZ_g 0x05 */
3541 0x2c, /* QZ_z 0x06 */
3542 0x2d, /* QZ_x 0x07 */
3543 0x2e, /* QZ_c 0x08 */
3544 0x2f, /* QZ_v 0x09 */
3545 0x56, /* between lshift and z. 'INT 1'? */
3546 0x30, /* QZ_b 0x0B */
3547 0x10, /* QZ_q 0x0C */
3548 0x11, /* QZ_w 0x0D */
3549 0x12, /* QZ_e 0x0E */
3550 0x13, /* QZ_r 0x0F */
3551 0x15, /* QZ_y 0x10 */
3552 0x14, /* QZ_t 0x11 */
3553 0x02, /* QZ_1 0x12 */
3554 0x03, /* QZ_2 0x13 */
3555 0x04, /* QZ_3 0x14 */
3556 0x05, /* QZ_4 0x15 */
3557 0x07, /* QZ_6 0x16 */
3558 0x06, /* QZ_5 0x17 */
3559 0x0d, /* QZ_EQUALS 0x18 */
3560 0x0a, /* QZ_9 0x19 */
3561 0x08, /* QZ_7 0x1A */
3562 0x0c, /* QZ_MINUS 0x1B */
3563 0x09, /* QZ_8 0x1C */
3564 0x0b, /* QZ_0 0x1D */
3565 0x1b, /* QZ_RIGHTBRACKET 0x1E */
3566 0x18, /* QZ_o 0x1F */
3567 0x16, /* QZ_u 0x20 */
3568 0x1a, /* QZ_LEFTBRACKET 0x21 */
3569 0x17, /* QZ_i 0x22 */
3570 0x19, /* QZ_p 0x23 */
3571 0x1c, /* QZ_RETURN 0x24 */
3572 0x26, /* QZ_l 0x25 */
3573 0x24, /* QZ_j 0x26 */
3574 0x28, /* QZ_QUOTE 0x27 */
3575 0x25, /* QZ_k 0x28 */
3576 0x27, /* QZ_SEMICOLON 0x29 */
3577 0x2b, /* QZ_BACKSLASH 0x2A */
3578 0x33, /* QZ_COMMA 0x2B */
3579 0x35, /* QZ_SLASH 0x2C */
3580 0x31, /* QZ_n 0x2D */
3581 0x32, /* QZ_m 0x2E */
3582 0x34, /* QZ_PERIOD 0x2F */
3583 0x0f, /* QZ_TAB 0x30 */
3584 0x39, /* QZ_SPACE 0x31 */
3585 0x29, /* QZ_BACKQUOTE 0x32 */
3586 0x0e, /* QZ_BACKSPACE 0x33 */
3587 0x9c, /* QZ_IBOOK_ENTER 0x34 */
3588 0x01, /* QZ_ESCAPE 0x35 */
3589 0x5c|0x100, /* QZ_RMETA 0x36 */
3590 0x5b|0x100, /* QZ_LMETA 0x37 */
3591 0x2a, /* QZ_LSHIFT 0x38 */
3592 0x3a, /* QZ_CAPSLOCK 0x39 */
3593 0x38, /* QZ_LALT 0x3A */
3594 0x1d, /* QZ_LCTRL 0x3B */
3595 0x36, /* QZ_RSHIFT 0x3C */
3596 0x38|0x100, /* QZ_RALT 0x3D */
3597 0x1d|0x100, /* QZ_RCTRL 0x3E */
3598 0, /* */
3599 0, /* */
3600 0x53, /* QZ_KP_PERIOD 0x41 */
3601 0, /* */
3602 0x37, /* QZ_KP_MULTIPLY 0x43 */
3603 0, /* */
3604 0x4e, /* QZ_KP_PLUS 0x45 */
3605 0, /* */
3606 0x45, /* QZ_NUMLOCK 0x47 */
3607 0, /* */
3608 0, /* */
3609 0, /* */
3610 0x35|0x100, /* QZ_KP_DIVIDE 0x4B */
3611 0x1c|0x100, /* QZ_KP_ENTER 0x4C */
3612 0, /* */
3613 0x4a, /* QZ_KP_MINUS 0x4E */
3614 0, /* */
3615 0, /* */
3616 0x0d/*?*/, /* QZ_KP_EQUALS 0x51 */
3617 0x52, /* QZ_KP0 0x52 */
3618 0x4f, /* QZ_KP1 0x53 */
3619 0x50, /* QZ_KP2 0x54 */
3620 0x51, /* QZ_KP3 0x55 */
3621 0x4b, /* QZ_KP4 0x56 */
3622 0x4c, /* QZ_KP5 0x57 */
3623 0x4d, /* QZ_KP6 0x58 */
3624 0x47, /* QZ_KP7 0x59 */
3625 0, /* */
3626 0x48, /* QZ_KP8 0x5B */
3627 0x49, /* QZ_KP9 0x5C */
3628 0, /* */
3629 0, /* */
3630 0, /* */
3631 0x3f, /* QZ_F5 0x60 */
3632 0x40, /* QZ_F6 0x61 */
3633 0x41, /* QZ_F7 0x62 */
3634 0x3d, /* QZ_F3 0x63 */
3635 0x42, /* QZ_F8 0x64 */
3636 0x43, /* QZ_F9 0x65 */
3637 0, /* */
3638 0x57, /* QZ_F11 0x67 */
3639 0, /* */
3640 0x37|0x100, /* QZ_PRINT / F13 0x69 */
3641 0x63, /* QZ_F16 0x6A */
3642 0x46, /* QZ_SCROLLOCK 0x6B */
3643 0, /* */
3644 0x44, /* QZ_F10 0x6D */
3645 0x5d|0x100, /* */
3646 0x58, /* QZ_F12 0x6F */
3647 0, /* */
3648 0/* 0xe1,0x1d,0x45*/, /* QZ_PAUSE 0x71 */
3649 0x52|0x100, /* QZ_INSERT / HELP 0x72 */
3650 0x47|0x100, /* QZ_HOME 0x73 */
3651 0x49|0x100, /* QZ_PAGEUP 0x74 */
3652 0x53|0x100, /* QZ_DELETE 0x75 */
3653 0x3e, /* QZ_F4 0x76 */
3654 0x4f|0x100, /* QZ_END 0x77 */
3655 0x3c, /* QZ_F2 0x78 */
3656 0x51|0x100, /* QZ_PAGEDOWN 0x79 */
3657 0x3b, /* QZ_F1 0x7A */
3658 0x4b|0x100, /* QZ_LEFT 0x7B */
3659 0x4d|0x100, /* QZ_RIGHT 0x7C */
3660 0x50|0x100, /* QZ_DOWN 0x7D */
3661 0x48|0x100, /* QZ_UP 0x7E */
3662 0x5e|0x100, /* QZ_POWER 0x7F */ /* have different break key! */
3663 };
3664
3665 if (keycode == 0)
3666 {
3667 /* This could be a modifier or it could be 'a'. */
3668 switch (ev->keysym.sym)
3669 {
3670 case SDLK_LSHIFT: keycode = 0x2a; break;
3671 case SDLK_RSHIFT: keycode = 0x36; break;
3672 case SDLK_LCTRL: keycode = 0x1d; break;
3673 case SDLK_RCTRL: keycode = 0x1d | 0x100; break;
3674 case SDLK_LALT: keycode = 0x38; break;
3675 case SDLK_MODE: /* alt gr */
3676 case SDLK_RALT: keycode = 0x38 | 0x100; break;
3677 case SDLK_RMETA:
3678 case SDLK_RSUPER: keycode = 0x5c | 0x100; break;
3679 case SDLK_LMETA:
3680 case SDLK_LSUPER: keycode = 0x5b | 0x100; break;
3681 /* Assumes normal key. */
3682 default: keycode = s_aMacToSet1[keycode]; break;
3683 }
3684 }
3685 else
3686 {
3687 if ((unsigned)keycode < RT_ELEMENTS(s_aMacToSet1))
3688 keycode = s_aMacToSet1[keycode];
3689 else
3690 keycode = 0;
3691 if (!keycode)
3692 {
3693# ifdef DEBUG_bird
3694 RTPrintf("Untranslated: keycode=%#x (%d)\n", keycode, keycode);
3695# endif
3696 keycode = Keyevent2KeycodeFallback(ev);
3697 }
3698 }
3699# ifdef DEBUG_bird
3700 RTPrintf("scancode=%#x -> %#x\n", ev->keysym.scancode, keycode);
3701# endif
3702
3703#elif defined(RT_OS_OS2)
3704 keycode = Keyevent2KeycodeFallback(ev);
3705#endif /* RT_OS_DARWIN */
3706 return keycode;
3707}
3708
3709/**
3710 * Releases any modifier keys that are currently in pressed state.
3711 */
3712static void ResetKeys(void)
3713{
3714 int i;
3715
3716 if (!gpKeyboard)
3717 return;
3718
3719 for(i = 0; i < 256; i++)
3720 {
3721 if (gaModifiersState[i])
3722 {
3723 if (i & 0x80)
3724 gpKeyboard->PutScancode(0xe0);
3725 gpKeyboard->PutScancode(i | 0x80);
3726 gaModifiersState[i] = 0;
3727 }
3728 }
3729}
3730
3731/**
3732 * Keyboard event handler.
3733 *
3734 * @param ev SDL keyboard event.
3735 */
3736static void ProcessKey(SDL_KeyboardEvent *ev)
3737{
3738#if (defined(DEBUG) || defined(VBOX_WITH_STATISTICS)) && !defined(VBOX_WITH_SDL2)
3739 if (gpMachineDebugger && ev->type == SDL_KEYDOWN)
3740 {
3741 // first handle the debugger hotkeys
3742 uint8_t *keystate = SDL_GetKeyState(NULL);
3743#if 0
3744 // CTRL+ALT+Fn is not free on Linux hosts with Xorg ..
3745 if (keystate[SDLK_LALT] && !keystate[SDLK_LCTRL])
3746#else
3747 if (keystate[SDLK_LALT] && keystate[SDLK_LCTRL])
3748#endif
3749 {
3750 switch (ev->keysym.sym)
3751 {
3752 // pressing CTRL+ALT+F11 dumps the statistics counter
3753 case SDLK_F12:
3754 RTPrintf("ResetStats\n"); /* Visual feedback in console window */
3755 gpMachineDebugger->ResetStats(NULL);
3756 break;
3757 // pressing CTRL+ALT+F12 resets all statistics counter
3758 case SDLK_F11:
3759 gpMachineDebugger->DumpStats(NULL);
3760 RTPrintf("DumpStats\n"); /* Vistual feedback in console window */
3761 break;
3762 default:
3763 break;
3764 }
3765 }
3766#if 1
3767 else if (keystate[SDLK_LALT] && !keystate[SDLK_LCTRL])
3768 {
3769 switch (ev->keysym.sym)
3770 {
3771 // pressing Alt-F12 toggles the supervisor recompiler
3772 case SDLK_F12:
3773 {
3774 BOOL recompileSupervisor;
3775 gpMachineDebugger->COMGETTER(RecompileSupervisor)(&recompileSupervisor);
3776 gpMachineDebugger->COMSETTER(RecompileSupervisor)(!recompileSupervisor);
3777 break;
3778 }
3779 // pressing Alt-F11 toggles the user recompiler
3780 case SDLK_F11:
3781 {
3782 BOOL recompileUser;
3783 gpMachineDebugger->COMGETTER(RecompileUser)(&recompileUser);
3784 gpMachineDebugger->COMSETTER(RecompileUser)(!recompileUser);
3785 break;
3786 }
3787 // pressing Alt-F10 toggles the patch manager
3788 case SDLK_F10:
3789 {
3790 BOOL patmEnabled;
3791 gpMachineDebugger->COMGETTER(PATMEnabled)(&patmEnabled);
3792 gpMachineDebugger->COMSETTER(PATMEnabled)(!patmEnabled);
3793 break;
3794 }
3795 // pressing Alt-F9 toggles CSAM
3796 case SDLK_F9:
3797 {
3798 BOOL csamEnabled;
3799 gpMachineDebugger->COMGETTER(CSAMEnabled)(&csamEnabled);
3800 gpMachineDebugger->COMSETTER(CSAMEnabled)(!csamEnabled);
3801 break;
3802 }
3803 // pressing Alt-F8 toggles singlestepping mode
3804 case SDLK_F8:
3805 {
3806 BOOL singlestepEnabled;
3807 gpMachineDebugger->COMGETTER(SingleStep)(&singlestepEnabled);
3808 gpMachineDebugger->COMSETTER(SingleStep)(!singlestepEnabled);
3809 break;
3810 }
3811 default:
3812 break;
3813 }
3814 }
3815#endif
3816 // pressing Ctrl-F12 toggles the logger
3817 else if ((keystate[SDLK_RCTRL] || keystate[SDLK_LCTRL]) && ev->keysym.sym == SDLK_F12)
3818 {
3819 BOOL logEnabled = TRUE;
3820 gpMachineDebugger->COMGETTER(LogEnabled)(&logEnabled);
3821 gpMachineDebugger->COMSETTER(LogEnabled)(!logEnabled);
3822#ifdef DEBUG_bird
3823 return;
3824#endif
3825 }
3826 // pressing F12 sets a logmark
3827 else if (ev->keysym.sym == SDLK_F12)
3828 {
3829 RTLogPrintf("****** LOGGING MARK ******\n");
3830 RTLogFlush(NULL);
3831 }
3832 // now update the titlebar flags
3833 UpdateTitlebar(TITLEBAR_NORMAL);
3834 }
3835#endif // DEBUG || VBOX_WITH_STATISTICS
3836
3837 // the pause key is the weirdest, needs special handling
3838 if (ev->keysym.sym == SDLK_PAUSE)
3839 {
3840 int v = 0;
3841 if (ev->type == SDL_KEYUP)
3842 v |= 0x80;
3843 gpKeyboard->PutScancode(0xe1);
3844 gpKeyboard->PutScancode(0x1d | v);
3845 gpKeyboard->PutScancode(0x45 | v);
3846 return;
3847 }
3848
3849 /*
3850 * Perform SDL key event to scancode conversion
3851 */
3852 int keycode = Keyevent2Keycode(ev);
3853
3854 switch(keycode)
3855 {
3856 case 0x00:
3857 {
3858 /* sent when leaving window: reset the modifiers state */
3859 ResetKeys();
3860 return;
3861 }
3862
3863 case 0x2a: /* Left Shift */
3864 case 0x36: /* Right Shift */
3865 case 0x1d: /* Left CTRL */
3866 case 0x1d|0x100: /* Right CTRL */
3867 case 0x38: /* Left ALT */
3868 case 0x38|0x100: /* Right ALT */
3869 {
3870 if (ev->type == SDL_KEYUP)
3871 gaModifiersState[keycode & ~0x100] = 0;
3872 else
3873 gaModifiersState[keycode & ~0x100] = 1;
3874 break;
3875 }
3876
3877 case 0x45: /* Num Lock */
3878 case 0x3a: /* Caps Lock */
3879 {
3880 /*
3881 * SDL generates a KEYDOWN event if the lock key is active and a KEYUP event
3882 * if the lock key is inactive. See SDL_DISABLE_LOCK_KEYS.
3883 */
3884 if (ev->type == SDL_KEYDOWN || ev->type == SDL_KEYUP)
3885 {
3886 gpKeyboard->PutScancode(keycode);
3887 gpKeyboard->PutScancode(keycode | 0x80);
3888 }
3889 return;
3890 }
3891 }
3892
3893 if (ev->type != SDL_KEYDOWN)
3894 {
3895 /*
3896 * Some keyboards (e.g. the one of mine T60) don't send a NumLock scan code on every
3897 * press of the key. Both the guest and the host should agree on the NumLock state.
3898 * If they differ, we try to alter the guest NumLock state by sending the NumLock key
3899 * scancode. We will get a feedback through the KBD_CMD_SET_LEDS command if the guest
3900 * tries to set/clear the NumLock LED. If a (silly) guest doesn't change the LED, don't
3901 * bother him with NumLock scancodes. At least our BIOS, Linux and Windows handle the
3902 * NumLock LED well.
3903 */
3904 if ( gcGuestNumLockAdaptions
3905 && (gfGuestNumLockPressed ^ !!(SDL_GetModState() & KMOD_NUM)))
3906 {
3907 gcGuestNumLockAdaptions--;
3908 gpKeyboard->PutScancode(0x45);
3909 gpKeyboard->PutScancode(0x45 | 0x80);
3910 }
3911 if ( gcGuestCapsLockAdaptions
3912 && (gfGuestCapsLockPressed ^ !!(SDL_GetModState() & KMOD_CAPS)))
3913 {
3914 gcGuestCapsLockAdaptions--;
3915 gpKeyboard->PutScancode(0x3a);
3916 gpKeyboard->PutScancode(0x3a | 0x80);
3917 }
3918 }
3919
3920 /*
3921 * Now we send the event. Apply extended and release prefixes.
3922 */
3923 if (keycode & 0x100)
3924 gpKeyboard->PutScancode(0xe0);
3925
3926 gpKeyboard->PutScancode(ev->type == SDL_KEYUP ? (keycode & 0x7f) | 0x80
3927 : (keycode & 0x7f));
3928}
3929
3930#ifdef RT_OS_DARWIN
3931#include <Carbon/Carbon.h>
3932RT_C_DECLS_BEGIN
3933/* Private interface in 10.3 and later. */
3934typedef int CGSConnection;
3935typedef enum
3936{
3937 kCGSGlobalHotKeyEnable = 0,
3938 kCGSGlobalHotKeyDisable,
3939 kCGSGlobalHotKeyInvalid = -1 /* bird */
3940} CGSGlobalHotKeyOperatingMode;
3941extern CGSConnection _CGSDefaultConnection(void);
3942extern CGError CGSGetGlobalHotKeyOperatingMode(CGSConnection Connection, CGSGlobalHotKeyOperatingMode *enmMode);
3943extern CGError CGSSetGlobalHotKeyOperatingMode(CGSConnection Connection, CGSGlobalHotKeyOperatingMode enmMode);
3944RT_C_DECLS_END
3945
3946/** Keeping track of whether we disabled the hotkeys or not. */
3947static bool g_fHotKeysDisabled = false;
3948/** Whether we've connected or not. */
3949static bool g_fConnectedToCGS = false;
3950/** Cached connection. */
3951static CGSConnection g_CGSConnection;
3952
3953/**
3954 * Disables or enabled global hot keys.
3955 */
3956static void DisableGlobalHotKeys(bool fDisable)
3957{
3958 if (!g_fConnectedToCGS)
3959 {
3960 g_CGSConnection = _CGSDefaultConnection();
3961 g_fConnectedToCGS = true;
3962 }
3963
3964 /* get current mode. */
3965 CGSGlobalHotKeyOperatingMode enmMode = kCGSGlobalHotKeyInvalid;
3966 CGSGetGlobalHotKeyOperatingMode(g_CGSConnection, &enmMode);
3967
3968 /* calc new mode. */
3969 if (fDisable)
3970 {
3971 if (enmMode != kCGSGlobalHotKeyEnable)
3972 return;
3973 enmMode = kCGSGlobalHotKeyDisable;
3974 }
3975 else
3976 {
3977 if ( enmMode != kCGSGlobalHotKeyDisable
3978 /*|| !g_fHotKeysDisabled*/)
3979 return;
3980 enmMode = kCGSGlobalHotKeyEnable;
3981 }
3982
3983 /* try set it and check the actual result. */
3984 CGSSetGlobalHotKeyOperatingMode(g_CGSConnection, enmMode);
3985 CGSGlobalHotKeyOperatingMode enmNewMode = kCGSGlobalHotKeyInvalid;
3986 CGSGetGlobalHotKeyOperatingMode(g_CGSConnection, &enmNewMode);
3987 if (enmNewMode == enmMode)
3988 g_fHotKeysDisabled = enmMode == kCGSGlobalHotKeyDisable;
3989}
3990#endif /* RT_OS_DARWIN */
3991
3992/**
3993 * Start grabbing the mouse.
3994 */
3995static void InputGrabStart(void)
3996{
3997#ifdef RT_OS_DARWIN
3998 DisableGlobalHotKeys(true);
3999#endif
4000 if (!gfGuestNeedsHostCursor && gfRelativeMouseGuest)
4001 SDL_ShowCursor(SDL_DISABLE);
4002#ifdef VBOX_WITH_SDL2
4003 SDL_SetRelativeMouseMode(SDL_TRUE);
4004#else
4005 SDL_WM_GrabInput(SDL_GRAB_ON);
4006 // dummy read to avoid moving the mouse
4007 SDL_GetRelativeMouseState(NULL, NULL);
4008#endif
4009 gfGrabbed = TRUE;
4010 UpdateTitlebar(TITLEBAR_NORMAL);
4011}
4012
4013/**
4014 * End mouse grabbing.
4015 */
4016static void InputGrabEnd(void)
4017{
4018#ifdef VBOX_WITH_SDL2
4019 SDL_SetRelativeMouseMode(SDL_FALSE);
4020#else
4021 SDL_WM_GrabInput(SDL_GRAB_OFF);
4022#endif
4023 if (!gfGuestNeedsHostCursor && gfRelativeMouseGuest)
4024 SDL_ShowCursor(SDL_ENABLE);
4025#ifdef RT_OS_DARWIN
4026 DisableGlobalHotKeys(false);
4027#endif
4028 gfGrabbed = FALSE;
4029 UpdateTitlebar(TITLEBAR_NORMAL);
4030}
4031
4032/**
4033 * Query mouse position and button state from SDL and send to the VM
4034 *
4035 * @param dz Relative mouse wheel movement
4036 */
4037static void SendMouseEvent(VBoxSDLFB *fb, int dz, int down, int button)
4038{
4039 int x, y, state, buttons;
4040 bool abs;
4041
4042#ifdef VBOX_WITH_SDL2
4043 if (!fb)
4044 {
4045 SDL_GetMouseState(&x, &y);
4046 RTPrintf("MouseEvent: Cannot find fb mouse = %d,%d\n", x, y);
4047 return;
4048 }
4049#else
4050 AssertRelease(fb != NULL);
4051#endif
4052
4053 /*
4054 * If supported and we're not in grabbed mode, we'll use the absolute mouse.
4055 * If we are in grabbed mode and the guest is not able to draw the mouse cursor
4056 * itself, or can't handle relative reporting, we have to use absolute
4057 * coordinates, otherwise the host cursor and
4058 * the coordinates the guest thinks the mouse is at could get out-of-sync. From
4059 * the SDL mailing list:
4060 *
4061 * "The event processing is usually asynchronous and so somewhat delayed, and
4062 * SDL_GetMouseState is returning the immediate mouse state. So at the time you
4063 * call SDL_GetMouseState, the "button" is already up."
4064 */
4065 abs = (UseAbsoluteMouse() && !gfGrabbed)
4066 || gfGuestNeedsHostCursor
4067 || !gfRelativeMouseGuest;
4068
4069 /* only used if abs == TRUE */
4070 int xOrigin = fb->getOriginX();
4071 int yOrigin = fb->getOriginY();
4072 int xMin = fb->getXOffset() + xOrigin;
4073 int yMin = fb->getYOffset() + yOrigin;
4074 int xMax = xMin + (int)fb->getGuestXRes();
4075 int yMax = yMin + (int)fb->getGuestYRes();
4076
4077 state = abs ? SDL_GetMouseState(&x, &y)
4078 : SDL_GetRelativeMouseState(&x, &y);
4079
4080 /*
4081 * process buttons
4082 */
4083 buttons = 0;
4084 if (state & SDL_BUTTON(SDL_BUTTON_LEFT))
4085 buttons |= MouseButtonState_LeftButton;
4086 if (state & SDL_BUTTON(SDL_BUTTON_RIGHT))
4087 buttons |= MouseButtonState_RightButton;
4088 if (state & SDL_BUTTON(SDL_BUTTON_MIDDLE))
4089 buttons |= MouseButtonState_MiddleButton;
4090
4091 if (abs)
4092 {
4093 x += xOrigin;
4094 y += yOrigin;
4095
4096 /*
4097 * Check if the mouse event is inside the guest area. This solves the
4098 * following problem: Some guests switch off the VBox hardware mouse
4099 * cursor and draw the mouse cursor itself instead. Moving the mouse
4100 * outside the guest area then leads to annoying mouse hangs if we
4101 * don't pass mouse motion events into the guest.
4102 */
4103 if (x < xMin || y < yMin || x > xMax || y > yMax)
4104 {
4105 /*
4106 * Cursor outside of valid guest area (outside window or in secure
4107 * label area. Don't allow any mouse button press.
4108 */
4109 button = 0;
4110
4111 /*
4112 * Release any pressed button.
4113 */
4114#if 0
4115 /* disabled on customers request */
4116 buttons &= ~(MouseButtonState_LeftButton |
4117 MouseButtonState_MiddleButton |
4118 MouseButtonState_RightButton);
4119#endif
4120
4121 /*
4122 * Prevent negative coordinates.
4123 */
4124 if (x < xMin) x = xMin;
4125 if (x > xMax) x = xMax;
4126 if (y < yMin) y = yMin;
4127 if (y > yMax) y = yMax;
4128
4129 if (!gpOffCursor)
4130 {
4131 gpOffCursor = SDL_GetCursor(); /* Cursor image */
4132 gfOffCursorActive = SDL_ShowCursor(-1); /* enabled / disabled */
4133 SDL_SetCursor(gpDefaultCursor);
4134 SDL_ShowCursor(SDL_ENABLE);
4135 }
4136 }
4137 else
4138 {
4139 if (gpOffCursor)
4140 {
4141 /*
4142 * We just entered the valid guest area. Restore the guest mouse
4143 * cursor.
4144 */
4145 SDL_SetCursor(gpOffCursor);
4146 SDL_ShowCursor(gfOffCursorActive ? SDL_ENABLE : SDL_DISABLE);
4147 gpOffCursor = NULL;
4148 }
4149 }
4150 }
4151
4152 /*
4153 * Button was pressed but that press is not reflected in the button state?
4154 */
4155 if (down && !(state & SDL_BUTTON(button)))
4156 {
4157 /*
4158 * It can happen that a mouse up event follows a mouse down event immediately
4159 * and we see the events when the bit in the button state is already cleared
4160 * again. In that case we simulate the mouse down event.
4161 */
4162 int tmp_button = 0;
4163 switch (button)
4164 {
4165 case SDL_BUTTON_LEFT: tmp_button = MouseButtonState_LeftButton; break;
4166 case SDL_BUTTON_MIDDLE: tmp_button = MouseButtonState_MiddleButton; break;
4167 case SDL_BUTTON_RIGHT: tmp_button = MouseButtonState_RightButton; break;
4168 }
4169
4170 if (abs)
4171 {
4172 /**
4173 * @todo
4174 * PutMouseEventAbsolute() expects x and y starting from 1,1.
4175 * should we do the increment internally in PutMouseEventAbsolute()
4176 * or state it in PutMouseEventAbsolute() docs?
4177 */
4178 gpMouse->PutMouseEventAbsolute(x + 1 - xMin + xOrigin,
4179 y + 1 - yMin + yOrigin,
4180 dz, 0 /* horizontal scroll wheel */,
4181 buttons | tmp_button);
4182 }
4183 else
4184 {
4185 gpMouse->PutMouseEvent(0, 0, dz,
4186 0 /* horizontal scroll wheel */,
4187 buttons | tmp_button);
4188 }
4189 }
4190
4191 // now send the mouse event
4192 if (abs)
4193 {
4194 /**
4195 * @todo
4196 * PutMouseEventAbsolute() expects x and y starting from 1,1.
4197 * should we do the increment internally in PutMouseEventAbsolute()
4198 * or state it in PutMouseEventAbsolute() docs?
4199 */
4200 gpMouse->PutMouseEventAbsolute(x + 1 - xMin + xOrigin,
4201 y + 1 - yMin + yOrigin,
4202 dz, 0 /* Horizontal wheel */, buttons);
4203 }
4204 else
4205 {
4206 gpMouse->PutMouseEvent(x, y, dz, 0 /* Horizontal wheel */, buttons);
4207 }
4208}
4209
4210/**
4211 * Resets the VM
4212 */
4213void ResetVM(void)
4214{
4215 if (gpConsole)
4216 gpConsole->Reset();
4217}
4218
4219/**
4220 * Initiates a saved state and updates the titlebar with progress information
4221 */
4222void SaveState(void)
4223{
4224 ResetKeys();
4225 RTThreadYield();
4226 if (gfGrabbed)
4227 InputGrabEnd();
4228 RTThreadYield();
4229 UpdateTitlebar(TITLEBAR_SAVE);
4230 gpProgress = NULL;
4231 HRESULT rc = gpMachine->SaveState(gpProgress.asOutParam());
4232 if (FAILED(rc))
4233 {
4234 RTPrintf("Error saving state! rc = 0x%x\n", rc);
4235 return;
4236 }
4237 Assert(gpProgress);
4238
4239 /*
4240 * Wait for the operation to be completed and work
4241 * the title bar in the mean while.
4242 */
4243 ULONG cPercent = 0;
4244#ifndef RT_OS_DARWIN /* don't break the other guys yet. */
4245 for (;;)
4246 {
4247 BOOL fCompleted = false;
4248 rc = gpProgress->COMGETTER(Completed)(&fCompleted);
4249 if (FAILED(rc) || fCompleted)
4250 break;
4251 ULONG cPercentNow;
4252 rc = gpProgress->COMGETTER(Percent)(&cPercentNow);
4253 if (FAILED(rc))
4254 break;
4255 if (cPercentNow != cPercent)
4256 {
4257 UpdateTitlebar(TITLEBAR_SAVE, cPercent);
4258 cPercent = cPercentNow;
4259 }
4260
4261 /* wait */
4262 rc = gpProgress->WaitForCompletion(100);
4263 if (FAILED(rc))
4264 break;
4265 /// @todo process gui events.
4266 }
4267
4268#else /* new loop which processes GUI events while saving. */
4269
4270 /* start regular timer so we don't starve in the event loop */
4271 SDL_TimerID sdlTimer;
4272 sdlTimer = SDL_AddTimer(100, StartupTimer, NULL);
4273
4274 for (;;)
4275 {
4276 /*
4277 * Check for completion.
4278 */
4279 BOOL fCompleted = false;
4280 rc = gpProgress->COMGETTER(Completed)(&fCompleted);
4281 if (FAILED(rc) || fCompleted)
4282 break;
4283 ULONG cPercentNow;
4284 rc = gpProgress->COMGETTER(Percent)(&cPercentNow);
4285 if (FAILED(rc))
4286 break;
4287 if (cPercentNow != cPercent)
4288 {
4289 UpdateTitlebar(TITLEBAR_SAVE, cPercent);
4290 cPercent = cPercentNow;
4291 }
4292
4293 /*
4294 * Wait for and process GUI a event.
4295 * This is necessary for XPCOM IPC and for updating the
4296 * title bar on the Mac.
4297 */
4298 SDL_Event event;
4299 if (WaitSDLEvent(&event))
4300 {
4301 switch (event.type)
4302 {
4303 /*
4304 * Timer event preventing us from getting stuck.
4305 */
4306 case SDL_USER_EVENT_TIMER:
4307 break;
4308
4309#ifdef USE_XPCOM_QUEUE_THREAD
4310 /*
4311 * User specific XPCOM event queue event
4312 */
4313 case SDL_USER_EVENT_XPCOM_EVENTQUEUE:
4314 {
4315 LogFlow(("SDL_USER_EVENT_XPCOM_EVENTQUEUE: processing XPCOM event queue...\n"));
4316 eventQ->ProcessPendingEvents();
4317 signalXPCOMEventQueueThread();
4318 break;
4319 }
4320#endif /* USE_XPCOM_QUEUE_THREAD */
4321
4322
4323 /*
4324 * Ignore all other events.
4325 */
4326 case SDL_USER_EVENT_NOTIFYCHANGE:
4327 case SDL_USER_EVENT_TERMINATE:
4328 default:
4329 break;
4330 }
4331 }
4332 }
4333
4334 /* kill the timer */
4335 SDL_RemoveTimer(sdlTimer);
4336 sdlTimer = 0;
4337
4338#endif /* RT_OS_DARWIN */
4339
4340 /*
4341 * What's the result of the operation?
4342 */
4343 LONG lrc;
4344 rc = gpProgress->COMGETTER(ResultCode)(&lrc);
4345 if (FAILED(rc))
4346 lrc = ~0;
4347 if (!lrc)
4348 {
4349 UpdateTitlebar(TITLEBAR_SAVE, 100);
4350 RTThreadYield();
4351 RTPrintf("Saved the state successfully.\n");
4352 }
4353 else
4354 RTPrintf("Error saving state, lrc=%d (%#x)\n", lrc, lrc);
4355}
4356
4357/**
4358 * Build the titlebar string
4359 */
4360static void UpdateTitlebar(TitlebarMode mode, uint32_t u32User)
4361{
4362 static char szTitle[1024] = {0};
4363
4364 /* back up current title */
4365 char szPrevTitle[1024];
4366 strcpy(szPrevTitle, szTitle);
4367
4368 Bstr bstrName;
4369 gpMachine->COMGETTER(Name)(bstrName.asOutParam());
4370
4371 RTStrPrintf(szTitle, sizeof(szTitle), "%s - " VBOX_PRODUCT,
4372 !bstrName.isEmpty() ? Utf8Str(bstrName).c_str() : "<noname>");
4373
4374 /* which mode are we in? */
4375 switch (mode)
4376 {
4377 case TITLEBAR_NORMAL:
4378 {
4379 MachineState_T machineState;
4380 gpMachine->COMGETTER(State)(&machineState);
4381 if (machineState == MachineState_Paused)
4382 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle), " - [Paused]");
4383
4384 if (gfGrabbed)
4385 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle), " - [Input captured]");
4386
4387#if defined(DEBUG) || defined(VBOX_WITH_STATISTICS)
4388 // do we have a debugger interface
4389 if (gpMachineDebugger)
4390 {
4391 // query the machine state
4392 BOOL recompileSupervisor = FALSE;
4393 BOOL recompileUser = FALSE;
4394 BOOL patmEnabled = FALSE;
4395 BOOL csamEnabled = FALSE;
4396 BOOL singlestepEnabled = FALSE;
4397 BOOL logEnabled = FALSE;
4398 BOOL hwVirtEnabled = FALSE;
4399 ULONG virtualTimeRate = 100;
4400 gpMachineDebugger->COMGETTER(RecompileSupervisor)(&recompileSupervisor);
4401 gpMachineDebugger->COMGETTER(RecompileUser)(&recompileUser);
4402 gpMachineDebugger->COMGETTER(PATMEnabled)(&patmEnabled);
4403 gpMachineDebugger->COMGETTER(CSAMEnabled)(&csamEnabled);
4404 gpMachineDebugger->COMGETTER(LogEnabled)(&logEnabled);
4405 gpMachineDebugger->COMGETTER(SingleStep)(&singlestepEnabled);
4406 gpMachineDebugger->COMGETTER(HWVirtExEnabled)(&hwVirtEnabled);
4407 gpMachineDebugger->COMGETTER(VirtualTimeRate)(&virtualTimeRate);
4408 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4409 " [STEP=%d CS=%d PAT=%d RR0=%d RR3=%d LOG=%d HWVirt=%d",
4410 singlestepEnabled == TRUE, csamEnabled == TRUE, patmEnabled == TRUE,
4411 recompileSupervisor == FALSE, recompileUser == FALSE,
4412 logEnabled == TRUE, hwVirtEnabled == TRUE);
4413 char *psz = strchr(szTitle, '\0');
4414 if (virtualTimeRate != 100)
4415 RTStrPrintf(psz, &szTitle[sizeof(szTitle)] - psz, " WD=%d%%]", virtualTimeRate);
4416 else
4417 RTStrPrintf(psz, &szTitle[sizeof(szTitle)] - psz, "]");
4418 }
4419#endif /* DEBUG || VBOX_WITH_STATISTICS */
4420 break;
4421 }
4422
4423 case TITLEBAR_STARTUP:
4424 {
4425 /*
4426 * Format it.
4427 */
4428 MachineState_T machineState;
4429 gpMachine->COMGETTER(State)(&machineState);
4430 if (machineState == MachineState_Starting)
4431 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4432 " - Starting...");
4433 else if (machineState == MachineState_Restoring)
4434 {
4435 ULONG cPercentNow;
4436 HRESULT rc = gpProgress->COMGETTER(Percent)(&cPercentNow);
4437 if (SUCCEEDED(rc))
4438 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4439 " - Restoring %d%%...", (int)cPercentNow);
4440 else
4441 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4442 " - Restoring...");
4443 }
4444 else if (machineState == MachineState_TeleportingIn)
4445 {
4446 ULONG cPercentNow;
4447 HRESULT rc = gpProgress->COMGETTER(Percent)(&cPercentNow);
4448 if (SUCCEEDED(rc))
4449 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4450 " - Teleporting %d%%...", (int)cPercentNow);
4451 else
4452 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4453 " - Teleporting...");
4454 }
4455 /* ignore other states, we could already be in running or aborted state */
4456 break;
4457 }
4458
4459 case TITLEBAR_SAVE:
4460 {
4461 AssertMsg(u32User <= 100, ("%d\n", u32User));
4462 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4463 " - Saving %d%%...", u32User);
4464 break;
4465 }
4466
4467 case TITLEBAR_SNAPSHOT:
4468 {
4469 AssertMsg(u32User <= 100, ("%d\n", u32User));
4470 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4471 " - Taking snapshot %d%%...", u32User);
4472 break;
4473 }
4474
4475 default:
4476 RTPrintf("Error: Invalid title bar mode %d!\n", mode);
4477 return;
4478 }
4479
4480 /*
4481 * Don't update if it didn't change.
4482 */
4483 if (!strcmp(szTitle, szPrevTitle))
4484 return;
4485
4486 /*
4487 * Set the new title
4488 */
4489#ifdef VBOX_WIN32_UI
4490 setUITitle(szTitle);
4491#else
4492# ifdef VBOX_WITH_SDL2
4493 for (unsigned i = 0; i < gcMonitors; i++)
4494 gpFramebuffer[i]->setWindowTitle(szTitle);
4495# else
4496 SDL_WM_SetCaption(szTitle, VBOX_PRODUCT);
4497# endif
4498#endif
4499}
4500
4501#if 0
4502static void vbox_show_shape(unsigned short w, unsigned short h,
4503 uint32_t bg, const uint8_t *image)
4504{
4505 size_t x, y;
4506 unsigned short pitch;
4507 const uint32_t *color;
4508 const uint8_t *mask;
4509 size_t size_mask;
4510
4511 mask = image;
4512 pitch = (w + 7) / 8;
4513 size_mask = (pitch * h + 3) & ~3;
4514
4515 color = (const uint32_t *)(image + size_mask);
4516
4517 printf("show_shape %dx%d pitch %d size mask %d\n",
4518 w, h, pitch, size_mask);
4519 for (y = 0; y < h; ++y, mask += pitch, color += w)
4520 {
4521 for (x = 0; x < w; ++x) {
4522 if (mask[x / 8] & (1 << (7 - (x % 8))))
4523 printf(" ");
4524 else
4525 {
4526 uint32_t c = color[x];
4527 if (c == bg)
4528 printf("Y");
4529 else
4530 printf("X");
4531 }
4532 }
4533 printf("\n");
4534 }
4535}
4536#endif
4537
4538/**
4539 * Sets the pointer shape according to parameters.
4540 * Must be called only from the main SDL thread.
4541 */
4542static void SetPointerShape(const PointerShapeChangeData *data)
4543{
4544 /*
4545 * don't allow to change the pointer shape if we are outside the valid
4546 * guest area. In that case set standard mouse pointer is set and should
4547 * not get overridden.
4548 */
4549 if (gpOffCursor)
4550 return;
4551
4552 if (data->shape.size() > 0)
4553 {
4554 bool ok = false;
4555
4556 uint32_t andMaskSize = (data->width + 7) / 8 * data->height;
4557 uint32_t srcShapePtrScan = data->width * 4;
4558
4559 const uint8_t* shape = data->shape.raw();
4560 const uint8_t *srcAndMaskPtr = shape;
4561 const uint8_t *srcShapePtr = shape + ((andMaskSize + 3) & ~3);
4562
4563#if 0
4564 /* pointer debugging code */
4565 // vbox_show_shape(data->width, data->height, 0, data->shape);
4566 uint32_t shapeSize = ((((data->width + 7) / 8) * data->height + 3) & ~3) + data->width * 4 * data->height;
4567 printf("visible: %d\n", data->visible);
4568 printf("width = %d\n", data->width);
4569 printf("height = %d\n", data->height);
4570 printf("alpha = %d\n", data->alpha);
4571 printf("xhot = %d\n", data->xHot);
4572 printf("yhot = %d\n", data->yHot);
4573 printf("uint8_t pointerdata[] = { ");
4574 for (uint32_t i = 0; i < shapeSize; i++)
4575 {
4576 printf("0x%x, ", data->shape[i]);
4577 }
4578 printf("};\n");
4579#endif
4580
4581#if defined(RT_OS_WINDOWS)
4582
4583 BITMAPV5HEADER bi;
4584 HBITMAP hBitmap;
4585 void *lpBits;
4586
4587 ::ZeroMemory(&bi, sizeof(BITMAPV5HEADER));
4588 bi.bV5Size = sizeof(BITMAPV5HEADER);
4589 bi.bV5Width = data->width;
4590 bi.bV5Height = -(LONG)data->height;
4591 bi.bV5Planes = 1;
4592 bi.bV5BitCount = 32;
4593 bi.bV5Compression = BI_BITFIELDS;
4594 // specify a supported 32 BPP alpha format for Windows XP
4595 bi.bV5RedMask = 0x00FF0000;
4596 bi.bV5GreenMask = 0x0000FF00;
4597 bi.bV5BlueMask = 0x000000FF;
4598 if (data->alpha)
4599 bi.bV5AlphaMask = 0xFF000000;
4600 else
4601 bi.bV5AlphaMask = 0;
4602
4603 HDC hdc = ::GetDC(NULL);
4604
4605 // create the DIB section with an alpha channel
4606 hBitmap = ::CreateDIBSection(hdc, (BITMAPINFO *)&bi, DIB_RGB_COLORS,
4607 (void **)&lpBits, NULL, (DWORD)0);
4608
4609 ::ReleaseDC(NULL, hdc);
4610
4611 HBITMAP hMonoBitmap = NULL;
4612 if (data->alpha)
4613 {
4614 // create an empty mask bitmap
4615 hMonoBitmap = ::CreateBitmap(data->width, data->height, 1, 1, NULL);
4616 }
4617 else
4618 {
4619 /* Word aligned AND mask. Will be allocated and created if necessary. */
4620 uint8_t *pu8AndMaskWordAligned = NULL;
4621
4622 /* Width in bytes of the original AND mask scan line. */
4623 uint32_t cbAndMaskScan = (data->width + 7) / 8;
4624
4625 if (cbAndMaskScan & 1)
4626 {
4627 /* Original AND mask is not word aligned. */
4628
4629 /* Allocate memory for aligned AND mask. */
4630 pu8AndMaskWordAligned = (uint8_t *)RTMemTmpAllocZ((cbAndMaskScan + 1) * data->height);
4631
4632 Assert(pu8AndMaskWordAligned);
4633
4634 if (pu8AndMaskWordAligned)
4635 {
4636 /* According to MSDN the padding bits must be 0.
4637 * Compute the bit mask to set padding bits to 0 in the last byte of original AND mask.
4638 */
4639 uint32_t u32PaddingBits = cbAndMaskScan * 8 - data->width;
4640 Assert(u32PaddingBits < 8);
4641 uint8_t u8LastBytesPaddingMask = (uint8_t)(0xFF << u32PaddingBits);
4642
4643 Log(("u8LastBytesPaddingMask = %02X, aligned w = %d, width = %d, cbAndMaskScan = %d\n",
4644 u8LastBytesPaddingMask, (cbAndMaskScan + 1) * 8, data->width, cbAndMaskScan));
4645
4646 uint8_t *src = (uint8_t *)srcAndMaskPtr;
4647 uint8_t *dst = pu8AndMaskWordAligned;
4648
4649 unsigned i;
4650 for (i = 0; i < data->height; i++)
4651 {
4652 memcpy(dst, src, cbAndMaskScan);
4653
4654 dst[cbAndMaskScan - 1] &= u8LastBytesPaddingMask;
4655
4656 src += cbAndMaskScan;
4657 dst += cbAndMaskScan + 1;
4658 }
4659 }
4660 }
4661
4662 // create the AND mask bitmap
4663 hMonoBitmap = ::CreateBitmap(data->width, data->height, 1, 1,
4664 pu8AndMaskWordAligned? pu8AndMaskWordAligned: srcAndMaskPtr);
4665
4666 if (pu8AndMaskWordAligned)
4667 {
4668 RTMemTmpFree(pu8AndMaskWordAligned);
4669 }
4670 }
4671
4672 Assert(hBitmap);
4673 Assert(hMonoBitmap);
4674 if (hBitmap && hMonoBitmap)
4675 {
4676 DWORD *dstShapePtr = (DWORD *)lpBits;
4677
4678 for (uint32_t y = 0; y < data->height; y ++)
4679 {
4680 memcpy(dstShapePtr, srcShapePtr, srcShapePtrScan);
4681 srcShapePtr += srcShapePtrScan;
4682 dstShapePtr += data->width;
4683 }
4684
4685#ifndef VBOX_WITH_SDL2 /** @BUGBUG Implement alpha cursor support handling. */
4686 ICONINFO ii;
4687 ii.fIcon = FALSE;
4688 ii.xHotspot = data->xHot;
4689 ii.yHotspot = data->yHot;
4690 ii.hbmMask = hMonoBitmap;
4691 ii.hbmColor = hBitmap;
4692
4693 HCURSOR hAlphaCursor = ::CreateIconIndirect(&ii);
4694 Assert(hAlphaCursor);
4695 if (hAlphaCursor)
4696 {
4697 // here we do a dirty trick by substituting a Window Manager's
4698 // cursor handle with the handle we created
4699
4700 WMcursor *pCustomTempWMCursor = gpCustomCursor->wm_cursor;
4701 // see SDL12/src/video/wincommon/SDL_sysmouse.c
4702 void *wm_cursor = malloc(sizeof(HCURSOR) + sizeof(uint8_t *) * 2);
4703 *(HCURSOR *)wm_cursor = hAlphaCursor;
4704
4705 gpCustomCursor->wm_cursor = (WMcursor *)wm_cursor;
4706 SDL_SetCursor(gpCustomCursor);
4707 SDL_ShowCursor(SDL_ENABLE);
4708
4709 if (pCustomTempWMCursor)
4710 {
4711 ::DestroyCursor(*(HCURSOR *)pCustomTempWMCursor);
4712 free(pCustomTempWMCursor);
4713 }
4714
4715 ok = true;
4716 }
4717#endif
4718 }
4719
4720 if (hMonoBitmap)
4721 ::DeleteObject(hMonoBitmap);
4722 if (hBitmap)
4723 ::DeleteObject(hBitmap);
4724
4725#elif defined(VBOXSDL_WITH_X11) && !defined(VBOX_WITHOUT_XCURSOR)
4726
4727 if (gfXCursorEnabled)
4728 {
4729 XcursorImage *img = XcursorImageCreate(data->width, data->height);
4730 Assert(img);
4731 if (img)
4732 {
4733 img->xhot = data->xHot;
4734 img->yhot = data->yHot;
4735
4736 XcursorPixel *dstShapePtr = img->pixels;
4737
4738 for (uint32_t y = 0; y < data->height; y ++)
4739 {
4740 memcpy(dstShapePtr, srcShapePtr, srcShapePtrScan);
4741
4742 if (!data->alpha)
4743 {
4744 // convert AND mask to the alpha channel
4745 uint8_t byte = 0;
4746 for (uint32_t x = 0; x < data->width; x ++)
4747 {
4748 if (!(x % 8))
4749 byte = *(srcAndMaskPtr ++);
4750 else
4751 byte <<= 1;
4752
4753 if (byte & 0x80)
4754 {
4755 // Linux doesn't support inverted pixels (XOR ops,
4756 // to be exact) in cursor shapes, so we detect such
4757 // pixels and always replace them with black ones to
4758 // make them visible at least over light colors
4759 if (dstShapePtr [x] & 0x00FFFFFF)
4760 dstShapePtr [x] = 0xFF000000;
4761 else
4762 dstShapePtr [x] = 0x00000000;
4763 }
4764 else
4765 dstShapePtr [x] |= 0xFF000000;
4766 }
4767 }
4768
4769 srcShapePtr += srcShapePtrScan;
4770 dstShapePtr += data->width;
4771 }
4772
4773#ifndef VBOX_WITH_SDL2
4774 Cursor cur = XcursorImageLoadCursor(gSdlInfo.info.x11.display, img);
4775 Assert(cur);
4776 if (cur)
4777 {
4778 // here we do a dirty trick by substituting a Window Manager's
4779 // cursor handle with the handle we created
4780
4781 WMcursor *pCustomTempWMCursor = gpCustomCursor->wm_cursor;
4782
4783 // see SDL12/src/video/x11/SDL_x11mouse.c
4784 void *wm_cursor = malloc(sizeof(Cursor));
4785 *(Cursor *)wm_cursor = cur;
4786
4787 gpCustomCursor->wm_cursor = (WMcursor *)wm_cursor;
4788 SDL_SetCursor(gpCustomCursor);
4789 SDL_ShowCursor(SDL_ENABLE);
4790
4791 if (pCustomTempWMCursor)
4792 {
4793 XFreeCursor(gSdlInfo.info.x11.display, *(Cursor *)pCustomTempWMCursor);
4794 free(pCustomTempWMCursor);
4795 }
4796
4797 ok = true;
4798 }
4799#endif
4800 }
4801 XcursorImageDestroy(img);
4802 }
4803
4804#endif /* VBOXSDL_WITH_X11 && !VBOX_WITHOUT_XCURSOR */
4805
4806 if (!ok)
4807 {
4808 SDL_SetCursor(gpDefaultCursor);
4809 SDL_ShowCursor(SDL_ENABLE);
4810 }
4811 }
4812 else
4813 {
4814 if (data->visible)
4815 SDL_ShowCursor(SDL_ENABLE);
4816 else if (gfAbsoluteMouseGuest)
4817 /* Don't disable the cursor if the guest additions are not active (anymore) */
4818 SDL_ShowCursor(SDL_DISABLE);
4819 }
4820}
4821
4822/**
4823 * Handle changed mouse capabilities
4824 */
4825static void HandleGuestCapsChanged(void)
4826{
4827 if (!gfAbsoluteMouseGuest)
4828 {
4829 // Cursor could be overwritten by the guest tools
4830 SDL_SetCursor(gpDefaultCursor);
4831 SDL_ShowCursor(SDL_ENABLE);
4832 gpOffCursor = NULL;
4833 }
4834 if (gpMouse && UseAbsoluteMouse())
4835 {
4836 // Actually switch to absolute coordinates
4837 if (gfGrabbed)
4838 InputGrabEnd();
4839 gpMouse->PutMouseEventAbsolute(-1, -1, 0, 0, 0);
4840 }
4841}
4842
4843/**
4844 * Handles a host key down event
4845 */
4846static int HandleHostKey(const SDL_KeyboardEvent *pEv)
4847{
4848 /*
4849 * Revalidate the host key modifier
4850 */
4851 if ((SDL_GetModState() & ~(KMOD_MODE | KMOD_NUM | KMOD_RESERVED)) != gHostKeyMod)
4852 return VERR_NOT_SUPPORTED;
4853
4854 /*
4855 * What was pressed?
4856 */
4857 switch (pEv->keysym.sym)
4858 {
4859 /* Control-Alt-Delete */
4860 case SDLK_DELETE:
4861 {
4862 gpKeyboard->PutCAD();
4863 break;
4864 }
4865
4866 /*
4867 * Fullscreen / Windowed toggle.
4868 */
4869 case SDLK_f:
4870 {
4871 if ( strchr(gHostKeyDisabledCombinations, 'f')
4872 || !gfAllowFullscreenToggle)
4873 return VERR_NOT_SUPPORTED;
4874
4875 /*
4876 * We have to pause/resume the machine during this
4877 * process because there might be a short moment
4878 * without a valid framebuffer
4879 */
4880 MachineState_T machineState;
4881 gpMachine->COMGETTER(State)(&machineState);
4882 bool fPauseIt = machineState == MachineState_Running
4883 || machineState == MachineState_Teleporting
4884 || machineState == MachineState_LiveSnapshotting;
4885 if (fPauseIt)
4886 gpConsole->Pause();
4887 SetFullscreen(!gpFramebuffer[0]->getFullscreen());
4888 if (fPauseIt)
4889 gpConsole->Resume();
4890
4891 /*
4892 * We have switched from/to fullscreen, so request a full
4893 * screen repaint, just to be sure.
4894 */
4895 gpDisplay->InvalidateAndUpdate();
4896 break;
4897 }
4898
4899 /*
4900 * Pause / Resume toggle.
4901 */
4902 case SDLK_p:
4903 {
4904 if (strchr(gHostKeyDisabledCombinations, 'p'))
4905 return VERR_NOT_SUPPORTED;
4906
4907 MachineState_T machineState;
4908 gpMachine->COMGETTER(State)(&machineState);
4909 if ( machineState == MachineState_Running
4910 || machineState == MachineState_Teleporting
4911 || machineState == MachineState_LiveSnapshotting
4912 )
4913 {
4914 if (gfGrabbed)
4915 InputGrabEnd();
4916 gpConsole->Pause();
4917 }
4918 else if (machineState == MachineState_Paused)
4919 {
4920 gpConsole->Resume();
4921 }
4922 UpdateTitlebar(TITLEBAR_NORMAL);
4923 break;
4924 }
4925
4926 /*
4927 * Reset the VM
4928 */
4929 case SDLK_r:
4930 {
4931 if (strchr(gHostKeyDisabledCombinations, 'r'))
4932 return VERR_NOT_SUPPORTED;
4933
4934 ResetVM();
4935 break;
4936 }
4937
4938 /*
4939 * Terminate the VM
4940 */
4941 case SDLK_q:
4942 {
4943 if (strchr(gHostKeyDisabledCombinations, 'q'))
4944 return VERR_NOT_SUPPORTED;
4945
4946 return VINF_EM_TERMINATE;
4947 }
4948
4949 /*
4950 * Save the machine's state and exit
4951 */
4952 case SDLK_s:
4953 {
4954 if (strchr(gHostKeyDisabledCombinations, 's'))
4955 return VERR_NOT_SUPPORTED;
4956
4957 SaveState();
4958 return VINF_EM_TERMINATE;
4959 }
4960
4961 case SDLK_h:
4962 {
4963 if (strchr(gHostKeyDisabledCombinations, 'h'))
4964 return VERR_NOT_SUPPORTED;
4965
4966 if (gpConsole)
4967 gpConsole->PowerButton();
4968 break;
4969 }
4970
4971 /*
4972 * Perform an online snapshot. Continue operation.
4973 */
4974 case SDLK_n:
4975 {
4976 if (strchr(gHostKeyDisabledCombinations, 'n'))
4977 return VERR_NOT_SUPPORTED;
4978
4979 RTThreadYield();
4980 ULONG cSnapshots = 0;
4981 gpMachine->COMGETTER(SnapshotCount)(&cSnapshots);
4982 char pszSnapshotName[20];
4983 RTStrPrintf(pszSnapshotName, sizeof(pszSnapshotName), "Snapshot %d", cSnapshots + 1);
4984 gpProgress = NULL;
4985 HRESULT rc;
4986 Bstr snapId;
4987 CHECK_ERROR(gpMachine, TakeSnapshot(Bstr(pszSnapshotName).raw(),
4988 Bstr("Taken by VBoxSDL").raw(),
4989 TRUE, snapId.asOutParam(),
4990 gpProgress.asOutParam()));
4991 if (FAILED(rc))
4992 {
4993 RTPrintf("Error taking snapshot! rc = 0x%x\n", rc);
4994 /* continue operation */
4995 return VINF_SUCCESS;
4996 }
4997 /*
4998 * Wait for the operation to be completed and work
4999 * the title bar in the mean while.
5000 */
5001 ULONG cPercent = 0;
5002 for (;;)
5003 {
5004 BOOL fCompleted = false;
5005 rc = gpProgress->COMGETTER(Completed)(&fCompleted);
5006 if (FAILED(rc) || fCompleted)
5007 break;
5008 ULONG cPercentNow;
5009 rc = gpProgress->COMGETTER(Percent)(&cPercentNow);
5010 if (FAILED(rc))
5011 break;
5012 if (cPercentNow != cPercent)
5013 {
5014 UpdateTitlebar(TITLEBAR_SNAPSHOT, cPercent);
5015 cPercent = cPercentNow;
5016 }
5017
5018 /* wait */
5019 rc = gpProgress->WaitForCompletion(100);
5020 if (FAILED(rc))
5021 break;
5022 /// @todo process gui events.
5023 }
5024
5025 /* continue operation */
5026 return VINF_SUCCESS;
5027 }
5028
5029 case SDLK_F1: case SDLK_F2: case SDLK_F3:
5030 case SDLK_F4: case SDLK_F5: case SDLK_F6:
5031 case SDLK_F7: case SDLK_F8: case SDLK_F9:
5032 case SDLK_F10: case SDLK_F11: case SDLK_F12:
5033 {
5034 // /* send Ctrl-Alt-Fx to guest */
5035 com::SafeArray<LONG> keys(6);
5036
5037 keys[0] = 0x1d; // Ctrl down
5038 keys[1] = 0x38; // Alt down
5039 keys[2] = Keyevent2Keycode(pEv); // Fx down
5040 keys[3] = keys[2] + 0x80; // Fx up
5041 keys[4] = 0xb8; // Alt up
5042 keys[5] = 0x9d; // Ctrl up
5043
5044 gpKeyboard->PutScancodes(ComSafeArrayAsInParam(keys), NULL);
5045 return VINF_SUCCESS;
5046 }
5047
5048 /*
5049 * Not a host key combination.
5050 * Indicate this by returning false.
5051 */
5052 default:
5053 return VERR_NOT_SUPPORTED;
5054 }
5055
5056 return VINF_SUCCESS;
5057}
5058
5059/**
5060 * Timer callback function for startup processing
5061 */
5062static Uint32 StartupTimer(Uint32 interval, void *param)
5063{
5064 RT_NOREF(param);
5065
5066 /* post message so we can do something in the startup loop */
5067 SDL_Event event = {0};
5068 event.type = SDL_USEREVENT;
5069 event.user.type = SDL_USER_EVENT_TIMER;
5070 SDL_PushEvent(&event);
5071 RTSemEventSignal(g_EventSemSDLEvents);
5072 return interval;
5073}
5074
5075/**
5076 * Timer callback function to check if resizing is finished
5077 */
5078static Uint32 ResizeTimer(Uint32 interval, void *param)
5079{
5080 RT_NOREF(interval, param);
5081
5082 /* post message so the window is actually resized */
5083 SDL_Event event = {0};
5084 event.type = SDL_USEREVENT;
5085 event.user.type = SDL_USER_EVENT_WINDOW_RESIZE_DONE;
5086 PushSDLEventForSure(&event);
5087 /* one-shot */
5088 return 0;
5089}
5090
5091/**
5092 * Timer callback function to check if an ACPI power button event was handled by the guest.
5093 */
5094static Uint32 QuitTimer(Uint32 interval, void *param)
5095{
5096 RT_NOREF(interval, param);
5097
5098 BOOL fHandled = FALSE;
5099
5100 gSdlQuitTimer = NULL;
5101 if (gpConsole)
5102 {
5103 int rc = gpConsole->GetPowerButtonHandled(&fHandled);
5104 LogRel(("QuitTimer: rc=%d handled=%d\n", rc, fHandled));
5105 if (RT_FAILURE(rc) || !fHandled)
5106 {
5107 /* event was not handled, power down the guest */
5108 gfACPITerm = FALSE;
5109 SDL_Event event = {0};
5110 event.type = SDL_QUIT;
5111 PushSDLEventForSure(&event);
5112 }
5113 }
5114 /* one-shot */
5115 return 0;
5116}
5117
5118/**
5119 * Wait for the next SDL event. Don't use SDL_WaitEvent since this function
5120 * calls SDL_Delay(10) if the event queue is empty.
5121 */
5122static int WaitSDLEvent(SDL_Event *event)
5123{
5124 for (;;)
5125 {
5126 int rc = SDL_PollEvent(event);
5127 if (rc == 1)
5128 {
5129#ifdef USE_XPCOM_QUEUE_THREAD
5130 if (event->type == SDL_USER_EVENT_XPCOM_EVENTQUEUE)
5131 consumedXPCOMUserEvent();
5132#endif
5133 return 1;
5134 }
5135 /* Immediately wake up if new SDL events are available. This does not
5136 * work for internal SDL events. Don't wait more than 10ms. */
5137 RTSemEventWait(g_EventSemSDLEvents, 10);
5138 }
5139}
5140
5141/**
5142 * Ensure that an SDL event is really enqueued. Try multiple times if necessary.
5143 */
5144int PushSDLEventForSure(SDL_Event *event)
5145{
5146 int ntries = 10;
5147 for (; ntries > 0; ntries--)
5148 {
5149 int rc = SDL_PushEvent(event);
5150 RTSemEventSignal(g_EventSemSDLEvents);
5151#ifdef VBOX_WITH_SDL2
5152 if (rc == 1)
5153#else
5154 if (rc == 0)
5155#endif
5156 return 0;
5157 Log(("PushSDLEventForSure: waiting for 2ms (rc = %d)\n", rc));
5158 RTThreadSleep(2);
5159 }
5160 LogRel(("WARNING: Failed to enqueue SDL event %d.%d!\n",
5161 event->type, event->type == SDL_USEREVENT ? event->user.type : 0));
5162 return -1;
5163}
5164
5165#ifdef VBOXSDL_WITH_X11
5166/**
5167 * Special SDL_PushEvent function for NotifyUpdate events. These events may occur in bursts
5168 * so make sure they don't flood the SDL event queue.
5169 */
5170void PushNotifyUpdateEvent(SDL_Event *event)
5171{
5172 int rc = SDL_PushEvent(event);
5173#ifdef VBOX_WITH_SDL2
5174 bool fSuccess = (rc == 1);
5175#else
5176 bool fSuccess = (rc == 0);
5177#endif
5178
5179 RTSemEventSignal(g_EventSemSDLEvents);
5180 AssertMsg(fSuccess, ("SDL_PushEvent returned SDL error\n"));
5181 /* A global counter is faster than SDL_PeepEvents() */
5182 if (fSuccess)
5183 ASMAtomicIncS32(&g_cNotifyUpdateEventsPending);
5184 /* In order to not flood the SDL event queue, yield the CPU or (if there are already many
5185 * events queued) even sleep */
5186 if (g_cNotifyUpdateEventsPending > 96)
5187 {
5188 /* Too many NotifyUpdate events, sleep for a small amount to give the main thread time
5189 * to handle these events. The SDL queue can hold up to 128 events. */
5190 Log(("PushNotifyUpdateEvent: Sleep 1ms\n"));
5191 RTThreadSleep(1);
5192 }
5193 else
5194 RTThreadYield();
5195}
5196#endif /* VBOXSDL_WITH_X11 */
5197
5198/**
5199 *
5200 */
5201static void SetFullscreen(bool enable)
5202{
5203 if (enable == gpFramebuffer[0]->getFullscreen())
5204 return;
5205
5206 if (!gfFullscreenResize)
5207 {
5208 /*
5209 * The old/default way: SDL will resize the host to fit the guest screen resolution.
5210 */
5211 gpFramebuffer[0]->setFullscreen(enable);
5212 }
5213 else
5214 {
5215 /*
5216 * The alternate way: Switch to fullscreen with the host screen resolution and adapt
5217 * the guest screen resolution to the host window geometry.
5218 */
5219 uint32_t NewWidth = 0, NewHeight = 0;
5220 if (enable)
5221 {
5222 /* switch to fullscreen */
5223 gmGuestNormalXRes = gpFramebuffer[0]->getGuestXRes();
5224 gmGuestNormalYRes = gpFramebuffer[0]->getGuestYRes();
5225 gpFramebuffer[0]->getFullscreenGeometry(&NewWidth, &NewHeight);
5226 }
5227 else
5228 {
5229 /* switch back to saved geometry */
5230 NewWidth = gmGuestNormalXRes;
5231 NewHeight = gmGuestNormalYRes;
5232 }
5233 if (NewWidth != 0 && NewHeight != 0)
5234 {
5235 gpFramebuffer[0]->setFullscreen(enable);
5236 gfIgnoreNextResize = TRUE;
5237 gpDisplay->SetVideoModeHint(0 /*=display*/, true /*=enabled*/,
5238 false /*=changeOrigin*/, 0 /*=originX*/, 0 /*=originY*/,
5239 NewWidth, NewHeight, 0 /*don't change bpp*/, true /*=notify*/);
5240 }
5241 }
5242}
5243
5244#ifdef VBOX_WITH_SDL2
5245static VBoxSDLFB *getFbFromWinId(Uint32 id)
5246{
5247 for (unsigned i = 0; i < gcMonitors; i++)
5248 if (gpFramebuffer[i]->hasWindow(id))
5249 return gpFramebuffer[i];
5250
5251 return NULL;
5252}
5253#endif
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette