VirtualBox

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

Last change on this file since 86648 was 86648, checked in by vboxsync, 4 years ago

bugref:9781. Added the placeholder @@VBOX_COND_GUEST_VERSION[>(required version)]@@. Updated the templates. Removed the obsolete function getGuestOSConditional().

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