VirtualBox

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

Last change on this file since 96407 was 96407, checked in by vboxsync, 2 years ago

scm copyright and license note update

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