VirtualBox

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

Last change on this file since 55543 was 55543, checked in by vboxsync, 10 years ago

Frontends: use approvals for VBoxEventType_OnCanShowWindow, workaround for VBoxEventType_OnShowWindow.

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