VirtualBox

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

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

added a couple of missing Id headers

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

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