VirtualBox

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

Last change on this file since 81156 was 80824, checked in by vboxsync, 5 years ago

Main: bugref:9341: The "environment" parameter in the IMachine::launchVMProcess renamed to "environmentChanges" and changed the type from wstring to "safearray of wstrings"

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

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