VirtualBox

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

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

Main/Snapshot: add a parameter to IMachine.takeSnapshot, returning the snapshot UUID, which is useful for finding the snapshot reliably (using the non-unique name is error prone), plus the necessary code adaptions everywhere.
Frontends/VBoxManage: add a feature for creating unique snapshot names (by appending a number or timestamp).

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