VirtualBox

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

Last change on this file since 63298 was 63298, checked in by vboxsync, 9 years ago

VBoxSDL: warnings

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

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