VirtualBox

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

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

Never use static instances of CComModule as it messes up the log filename by using VBoxRT.dll before it's initialized.

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