VirtualBox

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

Last change on this file since 52918 was 51677, checked in by vboxsync, 11 years ago

VBoxSDL: option to run a separate VM process.

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

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