VirtualBox

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

Last change on this file since 71356 was 69500, checked in by vboxsync, 7 years ago

*: scm --update-copyright-year

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