VirtualBox

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

Last change on this file since 52936 was 52922, checked in by vboxsync, 11 years ago

VBoxSDL: update the mouse pointer when starting with a separate VM.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 179.6 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 ComPtr<IMousePointerShape> mps;
2397 gpMouse->COMGETTER(PointerShape)(mps.asOutParam());
2398 if (!mps.isNull())
2399 {
2400 BOOL visible, alpha;
2401 ULONG hotX, hotY, width, height;
2402 com::SafeArray <BYTE> shape;
2403
2404 mps->COMGETTER(Visible)(&visible);
2405 mps->COMGETTER(Alpha)(&alpha);
2406 mps->COMGETTER(HotX)(&hotX);
2407 mps->COMGETTER(HotY)(&hotY);
2408 mps->COMGETTER(Width)(&width);
2409 mps->COMGETTER(Height)(&height);
2410 mps->COMGETTER(Shape)(ComSafeArrayAsOutParam(shape));
2411
2412 if (shape.size() > 0)
2413 {
2414 PointerShapeChangeData data(visible, alpha, hotX, hotY, width, height,
2415 ComSafeArrayAsInParam(shape));
2416 SetPointerShape(&data);
2417 }
2418 }
2419 }
2420
2421 UpdateTitlebar(TITLEBAR_NORMAL);
2422
2423 /*
2424 * Enable keyboard repeats
2425 */
2426 SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
2427
2428 /*
2429 * Create PID file.
2430 */
2431 if (gpszPidFile)
2432 {
2433 char szBuf[32];
2434 const char *pcszLf = "\n";
2435 RTFILE PidFile;
2436 RTFileOpen(&PidFile, gpszPidFile, RTFILE_O_WRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_NONE);
2437 RTStrFormatNumber(szBuf, RTProcSelf(), 10, 0, 0, 0);
2438 RTFileWrite(PidFile, szBuf, strlen(szBuf), NULL);
2439 RTFileWrite(PidFile, pcszLf, strlen(pcszLf), NULL);
2440 RTFileClose(PidFile);
2441 }
2442
2443 /*
2444 * Main event loop
2445 */
2446#ifdef USE_XPCOM_QUEUE_THREAD
2447 if (!fXPCOMEventThreadSignaled)
2448 {
2449 signalXPCOMEventQueueThread();
2450 }
2451#endif
2452 LogFlow(("VBoxSDL: Entering big event loop\n"));
2453 while (WaitSDLEvent(&event))
2454 {
2455 switch (event.type)
2456 {
2457 /*
2458 * The screen needs to be repainted.
2459 */
2460#ifdef VBOX_WITH_SDL13
2461 case SDL_WINDOWEVENT:
2462 {
2463 switch (event.window.event)
2464 {
2465 case SDL_WINDOWEVENT_EXPOSED:
2466 {
2467 VBoxSDLFB *fb = getFbFromWinId(event.window.windowID);
2468 if (fb)
2469 fb->repaint();
2470 break;
2471 }
2472 case SDL_WINDOWEVENT_FOCUS_GAINED:
2473 {
2474 break;
2475 }
2476 default:
2477 break;
2478 }
2479 }
2480#else
2481 case SDL_VIDEOEXPOSE:
2482 {
2483 gpFramebuffer[0]->repaint();
2484 break;
2485 }
2486#endif
2487
2488 /*
2489 * Keyboard events.
2490 */
2491 case SDL_KEYDOWN:
2492 case SDL_KEYUP:
2493 {
2494 SDLKey ksym = event.key.keysym.sym;
2495
2496 switch (enmHKeyState)
2497 {
2498 case HKEYSTATE_NORMAL:
2499 {
2500 if ( event.type == SDL_KEYDOWN
2501 && ksym != SDLK_UNKNOWN
2502 && (ksym == gHostKeySym1 || ksym == gHostKeySym2))
2503 {
2504 EvHKeyDown1 = event;
2505 enmHKeyState = ksym == gHostKeySym1 ? HKEYSTATE_DOWN_1ST
2506 : HKEYSTATE_DOWN_2ND;
2507 break;
2508 }
2509 ProcessKey(&event.key);
2510 break;
2511 }
2512
2513 case HKEYSTATE_DOWN_1ST:
2514 case HKEYSTATE_DOWN_2ND:
2515 {
2516 if (gHostKeySym2 != SDLK_UNKNOWN)
2517 {
2518 if ( event.type == SDL_KEYDOWN
2519 && ksym != SDLK_UNKNOWN
2520 && ( (enmHKeyState == HKEYSTATE_DOWN_1ST && ksym == gHostKeySym2)
2521 || (enmHKeyState == HKEYSTATE_DOWN_2ND && ksym == gHostKeySym1)))
2522 {
2523 EvHKeyDown2 = event;
2524 enmHKeyState = HKEYSTATE_DOWN;
2525 break;
2526 }
2527 enmHKeyState = event.type == SDL_KEYUP ? HKEYSTATE_NORMAL
2528 : HKEYSTATE_NOT_IT;
2529 ProcessKey(&EvHKeyDown1.key);
2530 /* ugly hack: Some guests (e.g. mstsc.exe on Windows XP)
2531 * expect a small delay between two key events. 5ms work
2532 * reliable here so use 10ms to be on the safe side. A
2533 * better but more complicated fix would be to introduce
2534 * a new state and don't wait here. */
2535 RTThreadSleep(10);
2536 ProcessKey(&event.key);
2537 break;
2538 }
2539 /* fall through if no two-key sequence is used */
2540 }
2541
2542 case HKEYSTATE_DOWN:
2543 {
2544 if (event.type == SDL_KEYDOWN)
2545 {
2546 /* potential host key combination, try execute it */
2547 int irc = HandleHostKey(&event.key);
2548 if (irc == VINF_SUCCESS)
2549 {
2550 enmHKeyState = HKEYSTATE_USED;
2551 break;
2552 }
2553 if (RT_SUCCESS(irc))
2554 goto leave;
2555 }
2556 else /* SDL_KEYUP */
2557 {
2558 if ( ksym != SDLK_UNKNOWN
2559 && (ksym == gHostKeySym1 || ksym == gHostKeySym2))
2560 {
2561 /* toggle grabbing state */
2562 if (!gfGrabbed)
2563 InputGrabStart();
2564 else
2565 InputGrabEnd();
2566
2567 /* SDL doesn't always reset the keystates, correct it */
2568 ResetKeys();
2569 enmHKeyState = HKEYSTATE_NORMAL;
2570 break;
2571 }
2572 }
2573
2574 /* not host key */
2575 enmHKeyState = HKEYSTATE_NOT_IT;
2576 ProcessKey(&EvHKeyDown1.key);
2577 /* see the comment for the 2-key case above */
2578 RTThreadSleep(10);
2579 if (gHostKeySym2 != SDLK_UNKNOWN)
2580 {
2581 ProcessKey(&EvHKeyDown2.key);
2582 /* see the comment for the 2-key case above */
2583 RTThreadSleep(10);
2584 }
2585 ProcessKey(&event.key);
2586 break;
2587 }
2588
2589 case HKEYSTATE_USED:
2590 {
2591 if ((SDL_GetModState() & ~(KMOD_MODE | KMOD_NUM | KMOD_RESERVED)) == 0)
2592 enmHKeyState = HKEYSTATE_NORMAL;
2593 if (event.type == SDL_KEYDOWN)
2594 {
2595 int irc = HandleHostKey(&event.key);
2596 if (RT_SUCCESS(irc) && irc != VINF_SUCCESS)
2597 goto leave;
2598 }
2599 break;
2600 }
2601
2602 default:
2603 AssertMsgFailed(("enmHKeyState=%d\n", enmHKeyState));
2604 /* fall thru */
2605 case HKEYSTATE_NOT_IT:
2606 {
2607 if ((SDL_GetModState() & ~(KMOD_MODE | KMOD_NUM | KMOD_RESERVED)) == 0)
2608 enmHKeyState = HKEYSTATE_NORMAL;
2609 ProcessKey(&event.key);
2610 break;
2611 }
2612 } /* state switch */
2613 break;
2614 }
2615
2616 /*
2617 * The window was closed.
2618 */
2619 case SDL_QUIT:
2620 {
2621 if (!gfACPITerm || gSdlQuitTimer)
2622 goto leave;
2623 if (gpConsole)
2624 gpConsole->PowerButton();
2625 gSdlQuitTimer = SDL_AddTimer(1000, QuitTimer, NULL);
2626 break;
2627 }
2628
2629 /*
2630 * The mouse has moved
2631 */
2632 case SDL_MOUSEMOTION:
2633 {
2634 if (gfGrabbed || UseAbsoluteMouse())
2635 {
2636 VBoxSDLFB *fb;
2637#ifdef VBOX_WITH_SDL13
2638 fb = getFbFromWinId(event.motion.windowID);
2639#else
2640 fb = gpFramebuffer[0];
2641#endif
2642 SendMouseEvent(fb, 0, 0, 0);
2643 }
2644 break;
2645 }
2646
2647 /*
2648 * A mouse button has been clicked or released.
2649 */
2650 case SDL_MOUSEBUTTONDOWN:
2651 case SDL_MOUSEBUTTONUP:
2652 {
2653 SDL_MouseButtonEvent *bev = &event.button;
2654 /* don't grab on mouse click if we have guest additions */
2655 if (!gfGrabbed && !UseAbsoluteMouse() && gfGrabOnMouseClick)
2656 {
2657 if (event.type == SDL_MOUSEBUTTONDOWN && (bev->state & SDL_BUTTON_LMASK))
2658 {
2659 /* start grabbing all events */
2660 InputGrabStart();
2661 }
2662 }
2663 else if (gfGrabbed || UseAbsoluteMouse())
2664 {
2665 int dz = bev->button == SDL_BUTTON_WHEELUP
2666 ? -1
2667 : bev->button == SDL_BUTTON_WHEELDOWN
2668 ? +1
2669 : 0;
2670
2671 /* end host key combination (CTRL+MouseButton) */
2672 switch (enmHKeyState)
2673 {
2674 case HKEYSTATE_DOWN_1ST:
2675 case HKEYSTATE_DOWN_2ND:
2676 enmHKeyState = HKEYSTATE_NOT_IT;
2677 ProcessKey(&EvHKeyDown1.key);
2678 /* ugly hack: small delay to ensure that the key event is
2679 * actually handled _prior_ to the mouse click event */
2680 RTThreadSleep(20);
2681 break;
2682 case HKEYSTATE_DOWN:
2683 enmHKeyState = HKEYSTATE_NOT_IT;
2684 ProcessKey(&EvHKeyDown1.key);
2685 if (gHostKeySym2 != SDLK_UNKNOWN)
2686 ProcessKey(&EvHKeyDown2.key);
2687 /* ugly hack: small delay to ensure that the key event is
2688 * actually handled _prior_ to the mouse click event */
2689 RTThreadSleep(20);
2690 break;
2691 default:
2692 break;
2693 }
2694
2695 VBoxSDLFB *fb;
2696#ifdef VBOX_WITH_SDL13
2697 fb = getFbFromWinId(event.button.windowID);
2698#else
2699 fb = gpFramebuffer[0];
2700#endif
2701 SendMouseEvent(fb, dz, event.type == SDL_MOUSEBUTTONDOWN, bev->button);
2702 }
2703 break;
2704 }
2705
2706 /*
2707 * The window has gained or lost focus.
2708 */
2709 case SDL_ACTIVEEVENT:
2710 {
2711 /*
2712 * There is a strange behaviour in SDL when running without a window
2713 * manager: When SDL_WM_GrabInput(SDL_GRAB_ON) is called we receive two
2714 * consecutive events SDL_ACTIVEEVENTs (input lost, input gained).
2715 * Asking SDL_GetAppState() seems the better choice.
2716 */
2717 if (gfGrabbed && (SDL_GetAppState() & SDL_APPINPUTFOCUS) == 0)
2718 {
2719 /*
2720 * another window has stolen the (keyboard) input focus
2721 */
2722 InputGrabEnd();
2723 }
2724 break;
2725 }
2726
2727 /*
2728 * The SDL window was resized
2729 */
2730 case SDL_VIDEORESIZE:
2731 {
2732 if (gpDisplay)
2733 {
2734 if (gfIgnoreNextResize)
2735 {
2736 gfIgnoreNextResize = FALSE;
2737 break;
2738 }
2739 uResizeWidth = event.resize.w;
2740#ifdef VBOX_SECURELABEL
2741 if (fSecureLabel)
2742 uResizeHeight = RT_MAX(0, event.resize.h - SECURE_LABEL_HEIGHT);
2743 else
2744#endif
2745 uResizeHeight = event.resize.h;
2746 if (gSdlResizeTimer)
2747 SDL_RemoveTimer(gSdlResizeTimer);
2748 gSdlResizeTimer = SDL_AddTimer(300, ResizeTimer, NULL);
2749 }
2750 break;
2751 }
2752
2753 /*
2754 * User specific update event.
2755 */
2756 /** @todo use a common user event handler so that SDL_PeepEvents() won't
2757 * possibly remove other events in the queue!
2758 */
2759 case SDL_USER_EVENT_UPDATERECT:
2760 {
2761 /*
2762 * Decode event parameters.
2763 */
2764 ASMAtomicDecS32(&g_cNotifyUpdateEventsPending);
2765 #define DECODEX(event) (int)((intptr_t)(event).user.data1 >> 16)
2766 #define DECODEY(event) (int)((intptr_t)(event).user.data1 & 0xFFFF)
2767 #define DECODEW(event) (int)((intptr_t)(event).user.data2 >> 16)
2768 #define DECODEH(event) (int)((intptr_t)(event).user.data2 & 0xFFFF)
2769 int x = DECODEX(event);
2770 int y = DECODEY(event);
2771 int w = DECODEW(event);
2772 int h = DECODEH(event);
2773 LogFlow(("SDL_USER_EVENT_UPDATERECT: x = %d, y = %d, w = %d, h = %d\n",
2774 x, y, w, h));
2775
2776 Assert(gpFramebuffer[event.user.code]);
2777 gpFramebuffer[event.user.code]->update(x, y, w, h, true /* fGuestRelative */);
2778
2779 #undef DECODEX
2780 #undef DECODEY
2781 #undef DECODEW
2782 #undef DECODEH
2783 break;
2784 }
2785
2786 /*
2787 * User event: Window resize done
2788 */
2789 case SDL_USER_EVENT_WINDOW_RESIZE_DONE:
2790 {
2791 /**
2792 * @todo This is a workaround for synchronization problems between EMT and the
2793 * SDL main thread. It can happen that the SDL thread already starts a
2794 * new resize operation while the EMT is still busy with the old one
2795 * leading to a deadlock. Therefore we call SetVideoModeHint only once
2796 * when the mouse button was released.
2797 */
2798 /* communicate the resize event to the guest */
2799 gpDisplay->SetVideoModeHint(0 /*=display*/, true /*=enabled*/, false /*=changeOrigin*/,
2800 0 /*=originX*/, 0 /*=originY*/,
2801 uResizeWidth, uResizeHeight, 0 /*=don't change bpp*/);
2802 break;
2803
2804 }
2805
2806 /*
2807 * User specific framebuffer change event.
2808 */
2809 case SDL_USER_EVENT_NOTIFYCHANGE:
2810 {
2811 LogFlow(("SDL_USER_EVENT_NOTIFYCHANGE\n"));
2812 LONG xOrigin, yOrigin;
2813 gpFramebuffer[event.user.code]->notifyChange(event.user.code);
2814 /* update xOrigin, yOrigin -> mouse */
2815 ULONG dummy;
2816 rc = gpDisplay->GetScreenResolution(event.user.code, &dummy, &dummy, &dummy, &xOrigin, &yOrigin);
2817 gpFramebuffer[event.user.code]->setOrigin(xOrigin, yOrigin);
2818 break;
2819 }
2820
2821#ifdef USE_XPCOM_QUEUE_THREAD
2822 /*
2823 * User specific XPCOM event queue event
2824 */
2825 case SDL_USER_EVENT_XPCOM_EVENTQUEUE:
2826 {
2827 LogFlow(("SDL_USER_EVENT_XPCOM_EVENTQUEUE: processing XPCOM event queue...\n"));
2828 eventQ->processEventQueue(0);
2829 signalXPCOMEventQueueThread();
2830 break;
2831 }
2832#endif /* USE_XPCOM_QUEUE_THREAD */
2833
2834 /*
2835 * User specific update title bar notification event
2836 */
2837 case SDL_USER_EVENT_UPDATE_TITLEBAR:
2838 {
2839 UpdateTitlebar(TITLEBAR_NORMAL);
2840 break;
2841 }
2842
2843 /*
2844 * User specific termination event
2845 */
2846 case SDL_USER_EVENT_TERMINATE:
2847 {
2848 if (event.user.code != VBOXSDL_TERM_NORMAL)
2849 RTPrintf("Error: VM terminated abnormally!\n");
2850 goto leave;
2851 }
2852
2853#ifdef VBOX_SECURELABEL
2854 /*
2855 * User specific secure label update event
2856 */
2857 case SDL_USER_EVENT_SECURELABEL_UPDATE:
2858 {
2859 /*
2860 * Query the new label text
2861 */
2862 Bstr bstrLabel;
2863 gpMachine->GetExtraData(Bstr(VBOXSDL_SECURELABEL_EXTRADATA).raw(), bstrLabel.asOutParam());
2864 Utf8Str labelUtf8(bstrLabel);
2865 /*
2866 * Now update the label
2867 */
2868 gpFramebuffer[0]->setSecureLabelText(labelUtf8.c_str());
2869 break;
2870 }
2871#endif /* VBOX_SECURELABEL */
2872
2873 /*
2874 * User specific pointer shape change event
2875 */
2876 case SDL_USER_EVENT_POINTER_CHANGE:
2877 {
2878 PointerShapeChangeData *data = (PointerShapeChangeData *)event.user.data1;
2879 SetPointerShape (data);
2880 delete data;
2881 break;
2882 }
2883
2884 /*
2885 * User specific guest capabilities changed
2886 */
2887 case SDL_USER_EVENT_GUEST_CAP_CHANGED:
2888 {
2889 HandleGuestCapsChanged();
2890 break;
2891 }
2892
2893 default:
2894 {
2895 LogBird(("unknown SDL event %d\n", event.type));
2896 break;
2897 }
2898 }
2899 }
2900
2901leave:
2902 if (gpszPidFile)
2903 RTFileDelete(gpszPidFile);
2904
2905 LogFlow(("leaving...\n"));
2906#if defined(VBOX_WITH_XPCOM) && !defined(RT_OS_DARWIN) && !defined(RT_OS_OS2)
2907 /* make sure the XPCOM event queue thread doesn't do anything harmful */
2908 terminateXPCOMQueueThread();
2909#endif /* VBOX_WITH_XPCOM */
2910
2911 if (gpVRDEServer)
2912 rc = gpVRDEServer->COMSETTER(Enabled)(FALSE);
2913
2914 /*
2915 * Get the machine state.
2916 */
2917 if (gpMachine)
2918 gpMachine->COMGETTER(State)(&machineState);
2919 else
2920 machineState = MachineState_Aborted;
2921
2922 if (!fSeparate)
2923 {
2924 /*
2925 * Turn off the VM if it's running
2926 */
2927 if ( gpConsole
2928 && ( machineState == MachineState_Running
2929 || machineState == MachineState_Teleporting
2930 || machineState == MachineState_LiveSnapshotting
2931 /** @todo power off paused VMs too? */
2932 )
2933 )
2934 do
2935 {
2936 pConsoleListener->getWrapped()->ignorePowerOffEvents(true);
2937 ComPtr<IProgress> pProgress;
2938 CHECK_ERROR_BREAK(gpConsole, PowerDown(pProgress.asOutParam()));
2939 CHECK_ERROR_BREAK(pProgress, WaitForCompletion(-1));
2940 BOOL completed;
2941 CHECK_ERROR_BREAK(pProgress, COMGETTER(Completed)(&completed));
2942 ASSERT(completed);
2943 LONG hrc;
2944 CHECK_ERROR_BREAK(pProgress, COMGETTER(ResultCode)(&hrc));
2945 if (FAILED(hrc))
2946 {
2947 com::ErrorInfo info;
2948 if (info.isFullAvailable())
2949 PrintError("Failed to power down VM",
2950 info.getText().raw(), info.getComponent().raw());
2951 else
2952 RTPrintf("Failed to power down virtual machine! No error information available (rc = 0x%x).\n", hrc);
2953 break;
2954 }
2955 } while (0);
2956 }
2957
2958 /* unregister Console listener */
2959 if (pConsoleListener)
2960 {
2961 ComPtr<IEventSource> pES;
2962 CHECK_ERROR(gpConsole, COMGETTER(EventSource)(pES.asOutParam()));
2963 if (!pES.isNull())
2964 CHECK_ERROR(pES, UnregisterListener(pConsoleListener));
2965 pConsoleListener.setNull();
2966 }
2967
2968 /*
2969 * Now we discard all settings so that our changes will
2970 * not be flushed to the permanent configuration
2971 */
2972 if ( gpMachine
2973 && machineState != MachineState_Saved)
2974 {
2975 rc = gpMachine->DiscardSettings();
2976 AssertMsg(SUCCEEDED(rc), ("DiscardSettings %Rhrc, machineState %d\n", rc, machineState));
2977 }
2978
2979 /* close the session */
2980 if (sessionOpened)
2981 {
2982 rc = pSession->UnlockMachine();
2983 AssertComRC(rc);
2984 }
2985
2986#ifndef VBOX_WITH_SDL13
2987 /* restore the default cursor and free the custom one if any */
2988 if (gpDefaultCursor)
2989 {
2990# ifdef VBOXSDL_WITH_X11
2991 Cursor pDefaultTempX11Cursor = 0;
2992 if (gfXCursorEnabled)
2993 {
2994 pDefaultTempX11Cursor = *(Cursor*)gpDefaultCursor->wm_cursor;
2995 *(Cursor*)gpDefaultCursor->wm_cursor = gpDefaultOrigX11Cursor;
2996 }
2997# endif /* VBOXSDL_WITH_X11 */
2998 SDL_SetCursor(gpDefaultCursor);
2999# if defined(VBOXSDL_WITH_X11) && !defined(VBOX_WITHOUT_XCURSOR)
3000 if (gfXCursorEnabled)
3001 XFreeCursor(gSdlInfo.info.x11.display, pDefaultTempX11Cursor);
3002# endif /* VBOXSDL_WITH_X11 && !VBOX_WITHOUT_XCURSOR */
3003 }
3004
3005 if (gpCustomCursor)
3006 {
3007 WMcursor *pCustomTempWMCursor = gpCustomCursor->wm_cursor;
3008 gpCustomCursor->wm_cursor = gpCustomOrigWMcursor;
3009 SDL_FreeCursor(gpCustomCursor);
3010 if (pCustomTempWMCursor)
3011 {
3012# if defined(RT_OS_WINDOWS)
3013 ::DestroyCursor(*(HCURSOR *)pCustomTempWMCursor);
3014# elif defined(VBOXSDL_WITH_X11) && !defined(VBOX_WITHOUT_XCURSOR)
3015 if (gfXCursorEnabled)
3016 XFreeCursor(gSdlInfo.info.x11.display, *(Cursor *)pCustomTempWMCursor);
3017# endif /* VBOXSDL_WITH_X11 && !VBOX_WITHOUT_XCURSOR */
3018 free(pCustomTempWMCursor);
3019 }
3020 }
3021#endif
3022
3023 LogFlow(("Releasing mouse, keyboard, remote desktop server, display, console...\n"));
3024 if (gpDisplay)
3025 {
3026 for (unsigned i = 0; i < gcMonitors; i++)
3027 gpDisplay->DetachFramebuffer(i);
3028 }
3029
3030 gpMouse = NULL;
3031 gpKeyboard = NULL;
3032 gpVRDEServer = NULL;
3033 gpDisplay = NULL;
3034 gpConsole = NULL;
3035 gpMachineDebugger = NULL;
3036 gpProgress = NULL;
3037 // we can only uninitialize SDL here because it is not threadsafe
3038
3039 for (unsigned i = 0; i < gcMonitors; i++)
3040 {
3041 if (gpFramebuffer[i])
3042 {
3043 LogFlow(("Releasing framebuffer...\n"));
3044 gpFramebuffer[i]->Release();
3045 gpFramebuffer[i] = NULL;
3046 }
3047 }
3048
3049 VBoxSDLFB::uninit();
3050
3051#ifdef VBOX_SECURELABEL
3052 /* must do this after destructing the framebuffer */
3053 if (gLibrarySDL_ttf)
3054 RTLdrClose(gLibrarySDL_ttf);
3055#endif
3056
3057 /* VirtualBox (server) listener unregistration. */
3058 if (pVBoxListener)
3059 {
3060 ComPtr<IEventSource> pES;
3061 CHECK_ERROR(pVirtualBox, COMGETTER(EventSource)(pES.asOutParam()));
3062 if (!pES.isNull())
3063 CHECK_ERROR(pES, UnregisterListener(pVBoxListener));
3064 pVBoxListener.setNull();
3065 }
3066
3067 /* VirtualBoxClient listener unregistration. */
3068 if (pVBoxClientListener)
3069 {
3070 ComPtr<IEventSource> pES;
3071 CHECK_ERROR(pVirtualBoxClient, COMGETTER(EventSource)(pES.asOutParam()));
3072 if (!pES.isNull())
3073 CHECK_ERROR(pES, UnregisterListener(pVBoxClientListener));
3074 pVBoxClientListener.setNull();
3075 }
3076
3077 LogFlow(("Releasing machine, session...\n"));
3078 gpMachine = NULL;
3079 pSession = NULL;
3080 LogFlow(("Releasing VirtualBox object...\n"));
3081 pVirtualBox = NULL;
3082 LogFlow(("Releasing VirtualBoxClient object...\n"));
3083 pVirtualBoxClient = NULL;
3084
3085 // end "all-stuff" scope
3086 ////////////////////////////////////////////////////////////////////////////
3087 }
3088
3089 /* Must be before com::Shutdown() */
3090 LogFlow(("Uninitializing COM...\n"));
3091 com::Shutdown();
3092
3093 LogFlow(("Returning from main()!\n"));
3094 RTLogFlush(NULL);
3095 return FAILED(rc) ? 1 : 0;
3096}
3097
3098static RTEXITCODE readPasswordFile(const char *pszFilename, com::Utf8Str *pPasswd)
3099{
3100 size_t cbFile;
3101 char szPasswd[512];
3102 int vrc = VINF_SUCCESS;
3103 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
3104 bool fStdIn = !strcmp(pszFilename, "stdin");
3105 PRTSTREAM pStrm;
3106 if (!fStdIn)
3107 vrc = RTStrmOpen(pszFilename, "r", &pStrm);
3108 else
3109 pStrm = g_pStdIn;
3110 if (RT_SUCCESS(vrc))
3111 {
3112 vrc = RTStrmReadEx(pStrm, szPasswd, sizeof(szPasswd)-1, &cbFile);
3113 if (RT_SUCCESS(vrc))
3114 {
3115 if (cbFile >= sizeof(szPasswd)-1)
3116 {
3117 RTPrintf("Provided password in file '%s' is too long\n", pszFilename);
3118 rcExit = RTEXITCODE_FAILURE;
3119 }
3120 else
3121 {
3122 unsigned i;
3123 for (i = 0; i < cbFile && !RT_C_IS_CNTRL(szPasswd[i]); i++)
3124 ;
3125 szPasswd[i] = '\0';
3126 *pPasswd = szPasswd;
3127 }
3128 }
3129 else
3130 {
3131 RTPrintf("Cannot read password from file '%s': %Rrc\n", pszFilename, vrc);
3132 rcExit = RTEXITCODE_FAILURE;
3133 }
3134 if (!fStdIn)
3135 RTStrmClose(pStrm);
3136 }
3137 else
3138 {
3139 RTPrintf("Cannot open password file '%s' (%Rrc)\n", pszFilename, vrc);
3140 rcExit = RTEXITCODE_FAILURE;
3141 }
3142
3143 return rcExit;
3144}
3145
3146static RTEXITCODE settingsPasswordFile(ComPtr<IVirtualBox> virtualBox, const char *pszFilename)
3147{
3148 com::Utf8Str passwd;
3149 RTEXITCODE rcExit = readPasswordFile(pszFilename, &passwd);
3150 if (rcExit == RTEXITCODE_SUCCESS)
3151 {
3152 int rc;
3153 CHECK_ERROR(virtualBox, SetSettingsSecret(com::Bstr(passwd).raw()));
3154 if (FAILED(rc))
3155 rcExit = RTEXITCODE_FAILURE;
3156 }
3157
3158 return rcExit;
3159}
3160
3161#ifndef VBOX_WITH_HARDENING
3162/**
3163 * Main entry point
3164 */
3165int main(int argc, char **argv)
3166{
3167#ifdef Q_WS_X11
3168 if (!XInitThreads())
3169 return 1;
3170#endif
3171 /*
3172 * Before we do *anything*, we initialize the runtime.
3173 */
3174 int rc = RTR3InitExe(argc, &argv, RTR3INIT_FLAGS_SUPLIB);
3175 if (RT_FAILURE(rc))
3176 return RTMsgInitFailure(rc);
3177 return TrustedMain(argc, argv, NULL);
3178}
3179#endif /* !VBOX_WITH_HARDENING */
3180
3181
3182/**
3183 * Returns whether the absolute mouse is in use, i.e. both host
3184 * and guest have opted to enable it.
3185 *
3186 * @returns bool Flag whether the absolute mouse is in use
3187 */
3188static bool UseAbsoluteMouse(void)
3189{
3190 return (gfAbsoluteMouseHost && gfAbsoluteMouseGuest);
3191}
3192
3193#if defined(RT_OS_DARWIN) || defined(RT_OS_OS2)
3194/**
3195 * Fallback keycode conversion using SDL symbols.
3196 *
3197 * This is used to catch keycodes that's missing from the translation table.
3198 *
3199 * @returns XT scancode
3200 * @param ev SDL scancode
3201 */
3202static uint16_t Keyevent2KeycodeFallback(const SDL_KeyboardEvent *ev)
3203{
3204 const SDLKey sym = ev->keysym.sym;
3205 Log(("SDL key event: sym=%d scancode=%#x unicode=%#x\n",
3206 sym, ev->keysym.scancode, ev->keysym.unicode));
3207 switch (sym)
3208 { /* set 1 scan code */
3209 case SDLK_ESCAPE: return 0x01;
3210 case SDLK_EXCLAIM:
3211 case SDLK_1: return 0x02;
3212 case SDLK_AT:
3213 case SDLK_2: return 0x03;
3214 case SDLK_HASH:
3215 case SDLK_3: return 0x04;
3216 case SDLK_DOLLAR:
3217 case SDLK_4: return 0x05;
3218 /* % */
3219 case SDLK_5: return 0x06;
3220 case SDLK_CARET:
3221 case SDLK_6: return 0x07;
3222 case SDLK_AMPERSAND:
3223 case SDLK_7: return 0x08;
3224 case SDLK_ASTERISK:
3225 case SDLK_8: return 0x09;
3226 case SDLK_LEFTPAREN:
3227 case SDLK_9: return 0x0a;
3228 case SDLK_RIGHTPAREN:
3229 case SDLK_0: return 0x0b;
3230 case SDLK_UNDERSCORE:
3231 case SDLK_MINUS: return 0x0c;
3232 case SDLK_EQUALS:
3233 case SDLK_PLUS: return 0x0d;
3234 case SDLK_BACKSPACE: return 0x0e;
3235 case SDLK_TAB: return 0x0f;
3236 case SDLK_q: return 0x10;
3237 case SDLK_w: return 0x11;
3238 case SDLK_e: return 0x12;
3239 case SDLK_r: return 0x13;
3240 case SDLK_t: return 0x14;
3241 case SDLK_y: return 0x15;
3242 case SDLK_u: return 0x16;
3243 case SDLK_i: return 0x17;
3244 case SDLK_o: return 0x18;
3245 case SDLK_p: return 0x19;
3246 case SDLK_LEFTBRACKET: return 0x1a;
3247 case SDLK_RIGHTBRACKET: return 0x1b;
3248 case SDLK_RETURN: return 0x1c;
3249 case SDLK_KP_ENTER: return 0x1c | 0x100;
3250 case SDLK_LCTRL: return 0x1d;
3251 case SDLK_RCTRL: return 0x1d | 0x100;
3252 case SDLK_a: return 0x1e;
3253 case SDLK_s: return 0x1f;
3254 case SDLK_d: return 0x20;
3255 case SDLK_f: return 0x21;
3256 case SDLK_g: return 0x22;
3257 case SDLK_h: return 0x23;
3258 case SDLK_j: return 0x24;
3259 case SDLK_k: return 0x25;
3260 case SDLK_l: return 0x26;
3261 case SDLK_COLON:
3262 case SDLK_SEMICOLON: return 0x27;
3263 case SDLK_QUOTEDBL:
3264 case SDLK_QUOTE: return 0x28;
3265 case SDLK_BACKQUOTE: return 0x29;
3266 case SDLK_LSHIFT: return 0x2a;
3267 case SDLK_BACKSLASH: return 0x2b;
3268 case SDLK_z: return 0x2c;
3269 case SDLK_x: return 0x2d;
3270 case SDLK_c: return 0x2e;
3271 case SDLK_v: return 0x2f;
3272 case SDLK_b: return 0x30;
3273 case SDLK_n: return 0x31;
3274 case SDLK_m: return 0x32;
3275 case SDLK_LESS:
3276 case SDLK_COMMA: return 0x33;
3277 case SDLK_GREATER:
3278 case SDLK_PERIOD: return 0x34;
3279 case SDLK_KP_DIVIDE: /*??*/
3280 case SDLK_QUESTION:
3281 case SDLK_SLASH: return 0x35;
3282 case SDLK_RSHIFT: return 0x36;
3283 case SDLK_KP_MULTIPLY:
3284 case SDLK_PRINT: return 0x37; /* fixme */
3285 case SDLK_LALT: return 0x38;
3286 case SDLK_MODE: /* alt gr*/
3287 case SDLK_RALT: return 0x38 | 0x100;
3288 case SDLK_SPACE: return 0x39;
3289 case SDLK_CAPSLOCK: return 0x3a;
3290 case SDLK_F1: return 0x3b;
3291 case SDLK_F2: return 0x3c;
3292 case SDLK_F3: return 0x3d;
3293 case SDLK_F4: return 0x3e;
3294 case SDLK_F5: return 0x3f;
3295 case SDLK_F6: return 0x40;
3296 case SDLK_F7: return 0x41;
3297 case SDLK_F8: return 0x42;
3298 case SDLK_F9: return 0x43;
3299 case SDLK_F10: return 0x44;
3300 case SDLK_PAUSE: return 0x45; /* not right */
3301 case SDLK_NUMLOCK: return 0x45;
3302 case SDLK_SCROLLOCK: return 0x46;
3303 case SDLK_KP7: return 0x47;
3304 case SDLK_HOME: return 0x47 | 0x100;
3305 case SDLK_KP8: return 0x48;
3306 case SDLK_UP: return 0x48 | 0x100;
3307 case SDLK_KP9: return 0x49;
3308 case SDLK_PAGEUP: return 0x49 | 0x100;
3309 case SDLK_KP_MINUS: return 0x4a;
3310 case SDLK_KP4: return 0x4b;
3311 case SDLK_LEFT: return 0x4b | 0x100;
3312 case SDLK_KP5: return 0x4c;
3313 case SDLK_KP6: return 0x4d;
3314 case SDLK_RIGHT: return 0x4d | 0x100;
3315 case SDLK_KP_PLUS: return 0x4e;
3316 case SDLK_KP1: return 0x4f;
3317 case SDLK_END: return 0x4f | 0x100;
3318 case SDLK_KP2: return 0x50;
3319 case SDLK_DOWN: return 0x50 | 0x100;
3320 case SDLK_KP3: return 0x51;
3321 case SDLK_PAGEDOWN: return 0x51 | 0x100;
3322 case SDLK_KP0: return 0x52;
3323 case SDLK_INSERT: return 0x52 | 0x100;
3324 case SDLK_KP_PERIOD: return 0x53;
3325 case SDLK_DELETE: return 0x53 | 0x100;
3326 case SDLK_SYSREQ: return 0x54;
3327 case SDLK_F11: return 0x57;
3328 case SDLK_F12: return 0x58;
3329 case SDLK_F13: return 0x5b;
3330 case SDLK_LMETA:
3331 case SDLK_LSUPER: return 0x5b | 0x100;
3332 case SDLK_F14: return 0x5c;
3333 case SDLK_RMETA:
3334 case SDLK_RSUPER: return 0x5c | 0x100;
3335 case SDLK_F15: return 0x5d;
3336 case SDLK_MENU: return 0x5d | 0x100;
3337#if 0
3338 case SDLK_CLEAR: return 0x;
3339 case SDLK_KP_EQUALS: return 0x;
3340 case SDLK_COMPOSE: return 0x;
3341 case SDLK_HELP: return 0x;
3342 case SDLK_BREAK: return 0x;
3343 case SDLK_POWER: return 0x;
3344 case SDLK_EURO: return 0x;
3345 case SDLK_UNDO: return 0x;
3346#endif
3347 default:
3348 Log(("Unhandled sdl key event: sym=%d scancode=%#x unicode=%#x\n",
3349 ev->keysym.sym, ev->keysym.scancode, ev->keysym.unicode));
3350 return 0;
3351 }
3352}
3353#endif /* RT_OS_DARWIN */
3354
3355/**
3356 * Converts an SDL keyboard eventcode to a XT scancode.
3357 *
3358 * @returns XT scancode
3359 * @param ev SDL scancode
3360 */
3361static uint16_t Keyevent2Keycode(const SDL_KeyboardEvent *ev)
3362{
3363 // start with the scancode determined by SDL
3364 int keycode = ev->keysym.scancode;
3365
3366#ifdef VBOXSDL_WITH_X11
3367# ifdef VBOX_WITH_SDL13
3368
3369 switch (ev->keysym.sym)
3370 {
3371 case SDLK_ESCAPE: return 0x01;
3372 case SDLK_EXCLAIM:
3373 case SDLK_1: return 0x02;
3374 case SDLK_AT:
3375 case SDLK_2: return 0x03;
3376 case SDLK_HASH:
3377 case SDLK_3: return 0x04;
3378 case SDLK_DOLLAR:
3379 case SDLK_4: return 0x05;
3380 /* % */
3381 case SDLK_5: return 0x06;
3382 case SDLK_CARET:
3383 case SDLK_6: return 0x07;
3384 case SDLK_AMPERSAND:
3385 case SDLK_7: return 0x08;
3386 case SDLK_ASTERISK:
3387 case SDLK_8: return 0x09;
3388 case SDLK_LEFTPAREN:
3389 case SDLK_9: return 0x0a;
3390 case SDLK_RIGHTPAREN:
3391 case SDLK_0: return 0x0b;
3392 case SDLK_UNDERSCORE:
3393 case SDLK_MINUS: return 0x0c;
3394 case SDLK_PLUS: return 0x0d;
3395 case SDLK_BACKSPACE: return 0x0e;
3396 case SDLK_TAB: return 0x0f;
3397 case SDLK_q: return 0x10;
3398 case SDLK_w: return 0x11;
3399 case SDLK_e: return 0x12;
3400 case SDLK_r: return 0x13;
3401 case SDLK_t: return 0x14;
3402 case SDLK_y: return 0x15;
3403 case SDLK_u: return 0x16;
3404 case SDLK_i: return 0x17;
3405 case SDLK_o: return 0x18;
3406 case SDLK_p: return 0x19;
3407 case SDLK_RETURN: return 0x1c;
3408 case SDLK_KP_ENTER: return 0x1c | 0x100;
3409 case SDLK_LCTRL: return 0x1d;
3410 case SDLK_RCTRL: return 0x1d | 0x100;
3411 case SDLK_a: return 0x1e;
3412 case SDLK_s: return 0x1f;
3413 case SDLK_d: return 0x20;
3414 case SDLK_f: return 0x21;
3415 case SDLK_g: return 0x22;
3416 case SDLK_h: return 0x23;
3417 case SDLK_j: return 0x24;
3418 case SDLK_k: return 0x25;
3419 case SDLK_l: return 0x26;
3420 case SDLK_COLON: return 0x27;
3421 case SDLK_QUOTEDBL:
3422 case SDLK_QUOTE: return 0x28;
3423 case SDLK_BACKQUOTE: return 0x29;
3424 case SDLK_LSHIFT: return 0x2a;
3425 case SDLK_z: return 0x2c;
3426 case SDLK_x: return 0x2d;
3427 case SDLK_c: return 0x2e;
3428 case SDLK_v: return 0x2f;
3429 case SDLK_b: return 0x30;
3430 case SDLK_n: return 0x31;
3431 case SDLK_m: return 0x32;
3432 case SDLK_LESS: return 0x33;
3433 case SDLK_GREATER: return 0x34;
3434 case SDLK_KP_DIVIDE: /*??*/
3435 case SDLK_QUESTION: return 0x35;
3436 case SDLK_RSHIFT: return 0x36;
3437 case SDLK_KP_MULTIPLY:
3438 case SDLK_PRINT: return 0x37; /* fixme */
3439 case SDLK_LALT: return 0x38;
3440 case SDLK_MODE: /* alt gr*/
3441 case SDLK_RALT: return 0x38 | 0x100;
3442 case SDLK_SPACE: return 0x39;
3443 case SDLK_CAPSLOCK: return 0x3a;
3444 case SDLK_F1: return 0x3b;
3445 case SDLK_F2: return 0x3c;
3446 case SDLK_F3: return 0x3d;
3447 case SDLK_F4: return 0x3e;
3448 case SDLK_F5: return 0x3f;
3449 case SDLK_F6: return 0x40;
3450 case SDLK_F7: return 0x41;
3451 case SDLK_F8: return 0x42;
3452 case SDLK_F9: return 0x43;
3453 case SDLK_F10: return 0x44;
3454 case SDLK_PAUSE: return 0x45; /* not right */
3455 case SDLK_NUMLOCK: return 0x45;
3456 case SDLK_SCROLLOCK: return 0x46;
3457 case SDLK_KP7: return 0x47;
3458 case SDLK_HOME: return 0x47 | 0x100;
3459 case SDLK_KP8: return 0x48;
3460 case SDLK_UP: return 0x48 | 0x100;
3461 case SDLK_KP9: return 0x49;
3462 case SDLK_PAGEUP: return 0x49 | 0x100;
3463 case SDLK_KP_MINUS: return 0x4a;
3464 case SDLK_KP4: return 0x4b;
3465 case SDLK_LEFT: return 0x4b | 0x100;
3466 case SDLK_KP5: return 0x4c;
3467 case SDLK_KP6: return 0x4d;
3468 case SDLK_RIGHT: return 0x4d | 0x100;
3469 case SDLK_KP_PLUS: return 0x4e;
3470 case SDLK_KP1: return 0x4f;
3471 case SDLK_END: return 0x4f | 0x100;
3472 case SDLK_KP2: return 0x50;
3473 case SDLK_DOWN: return 0x50 | 0x100;
3474 case SDLK_KP3: return 0x51;
3475 case SDLK_PAGEDOWN: return 0x51 | 0x100;
3476 case SDLK_KP0: return 0x52;
3477 case SDLK_INSERT: return 0x52 | 0x100;
3478 case SDLK_KP_PERIOD: return 0x53;
3479 case SDLK_DELETE: return 0x53 | 0x100;
3480 case SDLK_SYSREQ: return 0x54;
3481 case SDLK_F11: return 0x57;
3482 case SDLK_F12: return 0x58;
3483 case SDLK_F13: return 0x5b;
3484 case SDLK_F14: return 0x5c;
3485 case SDLK_F15: return 0x5d;
3486 case SDLK_MENU: return 0x5d | 0x100;
3487 default:
3488 return 0;
3489 }
3490# else
3491 keycode = X11DRV_KeyEvent(gSdlInfo.info.x11.display, keycode);
3492# endif
3493#elif defined(RT_OS_DARWIN)
3494 /* This is derived partially from SDL_QuartzKeys.h and partially from testing. */
3495 static const uint16_t s_aMacToSet1[] =
3496 {
3497 /* set-1 SDL_QuartzKeys.h */
3498 0x1e, /* QZ_a 0x00 */
3499 0x1f, /* QZ_s 0x01 */
3500 0x20, /* QZ_d 0x02 */
3501 0x21, /* QZ_f 0x03 */
3502 0x23, /* QZ_h 0x04 */
3503 0x22, /* QZ_g 0x05 */
3504 0x2c, /* QZ_z 0x06 */
3505 0x2d, /* QZ_x 0x07 */
3506 0x2e, /* QZ_c 0x08 */
3507 0x2f, /* QZ_v 0x09 */
3508 0x56, /* between lshift and z. 'INT 1'? */
3509 0x30, /* QZ_b 0x0B */
3510 0x10, /* QZ_q 0x0C */
3511 0x11, /* QZ_w 0x0D */
3512 0x12, /* QZ_e 0x0E */
3513 0x13, /* QZ_r 0x0F */
3514 0x15, /* QZ_y 0x10 */
3515 0x14, /* QZ_t 0x11 */
3516 0x02, /* QZ_1 0x12 */
3517 0x03, /* QZ_2 0x13 */
3518 0x04, /* QZ_3 0x14 */
3519 0x05, /* QZ_4 0x15 */
3520 0x07, /* QZ_6 0x16 */
3521 0x06, /* QZ_5 0x17 */
3522 0x0d, /* QZ_EQUALS 0x18 */
3523 0x0a, /* QZ_9 0x19 */
3524 0x08, /* QZ_7 0x1A */
3525 0x0c, /* QZ_MINUS 0x1B */
3526 0x09, /* QZ_8 0x1C */
3527 0x0b, /* QZ_0 0x1D */
3528 0x1b, /* QZ_RIGHTBRACKET 0x1E */
3529 0x18, /* QZ_o 0x1F */
3530 0x16, /* QZ_u 0x20 */
3531 0x1a, /* QZ_LEFTBRACKET 0x21 */
3532 0x17, /* QZ_i 0x22 */
3533 0x19, /* QZ_p 0x23 */
3534 0x1c, /* QZ_RETURN 0x24 */
3535 0x26, /* QZ_l 0x25 */
3536 0x24, /* QZ_j 0x26 */
3537 0x28, /* QZ_QUOTE 0x27 */
3538 0x25, /* QZ_k 0x28 */
3539 0x27, /* QZ_SEMICOLON 0x29 */
3540 0x2b, /* QZ_BACKSLASH 0x2A */
3541 0x33, /* QZ_COMMA 0x2B */
3542 0x35, /* QZ_SLASH 0x2C */
3543 0x31, /* QZ_n 0x2D */
3544 0x32, /* QZ_m 0x2E */
3545 0x34, /* QZ_PERIOD 0x2F */
3546 0x0f, /* QZ_TAB 0x30 */
3547 0x39, /* QZ_SPACE 0x31 */
3548 0x29, /* QZ_BACKQUOTE 0x32 */
3549 0x0e, /* QZ_BACKSPACE 0x33 */
3550 0x9c, /* QZ_IBOOK_ENTER 0x34 */
3551 0x01, /* QZ_ESCAPE 0x35 */
3552 0x5c|0x100, /* QZ_RMETA 0x36 */
3553 0x5b|0x100, /* QZ_LMETA 0x37 */
3554 0x2a, /* QZ_LSHIFT 0x38 */
3555 0x3a, /* QZ_CAPSLOCK 0x39 */
3556 0x38, /* QZ_LALT 0x3A */
3557 0x1d, /* QZ_LCTRL 0x3B */
3558 0x36, /* QZ_RSHIFT 0x3C */
3559 0x38|0x100, /* QZ_RALT 0x3D */
3560 0x1d|0x100, /* QZ_RCTRL 0x3E */
3561 0, /* */
3562 0, /* */
3563 0x53, /* QZ_KP_PERIOD 0x41 */
3564 0, /* */
3565 0x37, /* QZ_KP_MULTIPLY 0x43 */
3566 0, /* */
3567 0x4e, /* QZ_KP_PLUS 0x45 */
3568 0, /* */
3569 0x45, /* QZ_NUMLOCK 0x47 */
3570 0, /* */
3571 0, /* */
3572 0, /* */
3573 0x35|0x100, /* QZ_KP_DIVIDE 0x4B */
3574 0x1c|0x100, /* QZ_KP_ENTER 0x4C */
3575 0, /* */
3576 0x4a, /* QZ_KP_MINUS 0x4E */
3577 0, /* */
3578 0, /* */
3579 0x0d/*?*/, /* QZ_KP_EQUALS 0x51 */
3580 0x52, /* QZ_KP0 0x52 */
3581 0x4f, /* QZ_KP1 0x53 */
3582 0x50, /* QZ_KP2 0x54 */
3583 0x51, /* QZ_KP3 0x55 */
3584 0x4b, /* QZ_KP4 0x56 */
3585 0x4c, /* QZ_KP5 0x57 */
3586 0x4d, /* QZ_KP6 0x58 */
3587 0x47, /* QZ_KP7 0x59 */
3588 0, /* */
3589 0x48, /* QZ_KP8 0x5B */
3590 0x49, /* QZ_KP9 0x5C */
3591 0, /* */
3592 0, /* */
3593 0, /* */
3594 0x3f, /* QZ_F5 0x60 */
3595 0x40, /* QZ_F6 0x61 */
3596 0x41, /* QZ_F7 0x62 */
3597 0x3d, /* QZ_F3 0x63 */
3598 0x42, /* QZ_F8 0x64 */
3599 0x43, /* QZ_F9 0x65 */
3600 0, /* */
3601 0x57, /* QZ_F11 0x67 */
3602 0, /* */
3603 0x37|0x100, /* QZ_PRINT / F13 0x69 */
3604 0x63, /* QZ_F16 0x6A */
3605 0x46, /* QZ_SCROLLOCK 0x6B */
3606 0, /* */
3607 0x44, /* QZ_F10 0x6D */
3608 0x5d|0x100, /* */
3609 0x58, /* QZ_F12 0x6F */
3610 0, /* */
3611 0/* 0xe1,0x1d,0x45*/, /* QZ_PAUSE 0x71 */
3612 0x52|0x100, /* QZ_INSERT / HELP 0x72 */
3613 0x47|0x100, /* QZ_HOME 0x73 */
3614 0x49|0x100, /* QZ_PAGEUP 0x74 */
3615 0x53|0x100, /* QZ_DELETE 0x75 */
3616 0x3e, /* QZ_F4 0x76 */
3617 0x4f|0x100, /* QZ_END 0x77 */
3618 0x3c, /* QZ_F2 0x78 */
3619 0x51|0x100, /* QZ_PAGEDOWN 0x79 */
3620 0x3b, /* QZ_F1 0x7A */
3621 0x4b|0x100, /* QZ_LEFT 0x7B */
3622 0x4d|0x100, /* QZ_RIGHT 0x7C */
3623 0x50|0x100, /* QZ_DOWN 0x7D */
3624 0x48|0x100, /* QZ_UP 0x7E */
3625 0x5e|0x100, /* QZ_POWER 0x7F */ /* have different break key! */
3626 };
3627
3628 if (keycode == 0)
3629 {
3630 /* This could be a modifier or it could be 'a'. */
3631 switch (ev->keysym.sym)
3632 {
3633 case SDLK_LSHIFT: keycode = 0x2a; break;
3634 case SDLK_RSHIFT: keycode = 0x36; break;
3635 case SDLK_LCTRL: keycode = 0x1d; break;
3636 case SDLK_RCTRL: keycode = 0x1d | 0x100; break;
3637 case SDLK_LALT: keycode = 0x38; break;
3638 case SDLK_MODE: /* alt gr */
3639 case SDLK_RALT: keycode = 0x38 | 0x100; break;
3640 case SDLK_RMETA:
3641 case SDLK_RSUPER: keycode = 0x5c | 0x100; break;
3642 case SDLK_LMETA:
3643 case SDLK_LSUPER: keycode = 0x5b | 0x100; break;
3644 /* Assumes normal key. */
3645 default: keycode = s_aMacToSet1[keycode]; break;
3646 }
3647 }
3648 else
3649 {
3650 if ((unsigned)keycode < RT_ELEMENTS(s_aMacToSet1))
3651 keycode = s_aMacToSet1[keycode];
3652 else
3653 keycode = 0;
3654 if (!keycode)
3655 {
3656#ifdef DEBUG_bird
3657 RTPrintf("Untranslated: keycode=%#x (%d)\n", keycode, keycode);
3658#endif
3659 keycode = Keyevent2KeycodeFallback(ev);
3660 }
3661 }
3662#ifdef DEBUG_bird
3663 RTPrintf("scancode=%#x -> %#x\n", ev->keysym.scancode, keycode);
3664#endif
3665
3666#elif RT_OS_OS2
3667 keycode = Keyevent2KeycodeFallback(ev);
3668#endif /* RT_OS_DARWIN */
3669 return keycode;
3670}
3671
3672/**
3673 * Releases any modifier keys that are currently in pressed state.
3674 */
3675static void ResetKeys(void)
3676{
3677 int i;
3678
3679 if (!gpKeyboard)
3680 return;
3681
3682 for(i = 0; i < 256; i++)
3683 {
3684 if (gaModifiersState[i])
3685 {
3686 if (i & 0x80)
3687 gpKeyboard->PutScancode(0xe0);
3688 gpKeyboard->PutScancode(i | 0x80);
3689 gaModifiersState[i] = 0;
3690 }
3691 }
3692}
3693
3694/**
3695 * Keyboard event handler.
3696 *
3697 * @param ev SDL keyboard event.
3698 */
3699static void ProcessKey(SDL_KeyboardEvent *ev)
3700{
3701#if (defined(DEBUG) || defined(VBOX_WITH_STATISTICS)) && !defined(VBOX_WITH_SDL13)
3702 if (gpMachineDebugger && ev->type == SDL_KEYDOWN)
3703 {
3704 // first handle the debugger hotkeys
3705 uint8_t *keystate = SDL_GetKeyState(NULL);
3706#if 0
3707 // CTRL+ALT+Fn is not free on Linux hosts with Xorg ..
3708 if (keystate[SDLK_LALT] && !keystate[SDLK_LCTRL])
3709#else
3710 if (keystate[SDLK_LALT] && keystate[SDLK_LCTRL])
3711#endif
3712 {
3713 switch (ev->keysym.sym)
3714 {
3715 // pressing CTRL+ALT+F11 dumps the statistics counter
3716 case SDLK_F12:
3717 RTPrintf("ResetStats\n"); /* Visual feedback in console window */
3718 gpMachineDebugger->ResetStats(NULL);
3719 break;
3720 // pressing CTRL+ALT+F12 resets all statistics counter
3721 case SDLK_F11:
3722 gpMachineDebugger->DumpStats(NULL);
3723 RTPrintf("DumpStats\n"); /* Vistual feedback in console window */
3724 break;
3725 default:
3726 break;
3727 }
3728 }
3729#if 1
3730 else if (keystate[SDLK_LALT] && !keystate[SDLK_LCTRL])
3731 {
3732 switch (ev->keysym.sym)
3733 {
3734 // pressing Alt-F12 toggles the supervisor recompiler
3735 case SDLK_F12:
3736 {
3737 BOOL recompileSupervisor;
3738 gpMachineDebugger->COMGETTER(RecompileSupervisor)(&recompileSupervisor);
3739 gpMachineDebugger->COMSETTER(RecompileSupervisor)(!recompileSupervisor);
3740 break;
3741 }
3742 // pressing Alt-F11 toggles the user recompiler
3743 case SDLK_F11:
3744 {
3745 BOOL recompileUser;
3746 gpMachineDebugger->COMGETTER(RecompileUser)(&recompileUser);
3747 gpMachineDebugger->COMSETTER(RecompileUser)(!recompileUser);
3748 break;
3749 }
3750 // pressing Alt-F10 toggles the patch manager
3751 case SDLK_F10:
3752 {
3753 BOOL patmEnabled;
3754 gpMachineDebugger->COMGETTER(PATMEnabled)(&patmEnabled);
3755 gpMachineDebugger->COMSETTER(PATMEnabled)(!patmEnabled);
3756 break;
3757 }
3758 // pressing Alt-F9 toggles CSAM
3759 case SDLK_F9:
3760 {
3761 BOOL csamEnabled;
3762 gpMachineDebugger->COMGETTER(CSAMEnabled)(&csamEnabled);
3763 gpMachineDebugger->COMSETTER(CSAMEnabled)(!csamEnabled);
3764 break;
3765 }
3766 // pressing Alt-F8 toggles singlestepping mode
3767 case SDLK_F8:
3768 {
3769 BOOL singlestepEnabled;
3770 gpMachineDebugger->COMGETTER(SingleStep)(&singlestepEnabled);
3771 gpMachineDebugger->COMSETTER(SingleStep)(!singlestepEnabled);
3772 break;
3773 }
3774 default:
3775 break;
3776 }
3777 }
3778#endif
3779 // pressing Ctrl-F12 toggles the logger
3780 else if ((keystate[SDLK_RCTRL] || keystate[SDLK_LCTRL]) && ev->keysym.sym == SDLK_F12)
3781 {
3782 BOOL logEnabled = TRUE;
3783 gpMachineDebugger->COMGETTER(LogEnabled)(&logEnabled);
3784 gpMachineDebugger->COMSETTER(LogEnabled)(!logEnabled);
3785#ifdef DEBUG_bird
3786 return;
3787#endif
3788 }
3789 // pressing F12 sets a logmark
3790 else if (ev->keysym.sym == SDLK_F12)
3791 {
3792 RTLogPrintf("****** LOGGING MARK ******\n");
3793 RTLogFlush(NULL);
3794 }
3795 // now update the titlebar flags
3796 UpdateTitlebar(TITLEBAR_NORMAL);
3797 }
3798#endif // DEBUG || VBOX_WITH_STATISTICS
3799
3800 // the pause key is the weirdest, needs special handling
3801 if (ev->keysym.sym == SDLK_PAUSE)
3802 {
3803 int v = 0;
3804 if (ev->type == SDL_KEYUP)
3805 v |= 0x80;
3806 gpKeyboard->PutScancode(0xe1);
3807 gpKeyboard->PutScancode(0x1d | v);
3808 gpKeyboard->PutScancode(0x45 | v);
3809 return;
3810 }
3811
3812 /*
3813 * Perform SDL key event to scancode conversion
3814 */
3815 int keycode = Keyevent2Keycode(ev);
3816
3817 switch(keycode)
3818 {
3819 case 0x00:
3820 {
3821 /* sent when leaving window: reset the modifiers state */
3822 ResetKeys();
3823 return;
3824 }
3825
3826 case 0x2a: /* Left Shift */
3827 case 0x36: /* Right Shift */
3828 case 0x1d: /* Left CTRL */
3829 case 0x1d|0x100: /* Right CTRL */
3830 case 0x38: /* Left ALT */
3831 case 0x38|0x100: /* Right ALT */
3832 {
3833 if (ev->type == SDL_KEYUP)
3834 gaModifiersState[keycode & ~0x100] = 0;
3835 else
3836 gaModifiersState[keycode & ~0x100] = 1;
3837 break;
3838 }
3839
3840 case 0x45: /* Num Lock */
3841 case 0x3a: /* Caps Lock */
3842 {
3843 /*
3844 * SDL generates a KEYDOWN event if the lock key is active and a KEYUP event
3845 * if the lock key is inactive. See SDL_DISABLE_LOCK_KEYS.
3846 */
3847 if (ev->type == SDL_KEYDOWN || ev->type == SDL_KEYUP)
3848 {
3849 gpKeyboard->PutScancode(keycode);
3850 gpKeyboard->PutScancode(keycode | 0x80);
3851 }
3852 return;
3853 }
3854 }
3855
3856 if (ev->type != SDL_KEYDOWN)
3857 {
3858 /*
3859 * Some keyboards (e.g. the one of mine T60) don't send a NumLock scan code on every
3860 * press of the key. Both the guest and the host should agree on the NumLock state.
3861 * If they differ, we try to alter the guest NumLock state by sending the NumLock key
3862 * scancode. We will get a feedback through the KBD_CMD_SET_LEDS command if the guest
3863 * tries to set/clear the NumLock LED. If a (silly) guest doesn't change the LED, don't
3864 * bother him with NumLock scancodes. At least our BIOS, Linux and Windows handle the
3865 * NumLock LED well.
3866 */
3867 if ( gcGuestNumLockAdaptions
3868 && (gfGuestNumLockPressed ^ !!(SDL_GetModState() & KMOD_NUM)))
3869 {
3870 gcGuestNumLockAdaptions--;
3871 gpKeyboard->PutScancode(0x45);
3872 gpKeyboard->PutScancode(0x45 | 0x80);
3873 }
3874 if ( gcGuestCapsLockAdaptions
3875 && (gfGuestCapsLockPressed ^ !!(SDL_GetModState() & KMOD_CAPS)))
3876 {
3877 gcGuestCapsLockAdaptions--;
3878 gpKeyboard->PutScancode(0x3a);
3879 gpKeyboard->PutScancode(0x3a | 0x80);
3880 }
3881 }
3882
3883 /*
3884 * Now we send the event. Apply extended and release prefixes.
3885 */
3886 if (keycode & 0x100)
3887 gpKeyboard->PutScancode(0xe0);
3888
3889 gpKeyboard->PutScancode(ev->type == SDL_KEYUP ? (keycode & 0x7f) | 0x80
3890 : (keycode & 0x7f));
3891}
3892
3893#ifdef RT_OS_DARWIN
3894#include <Carbon/Carbon.h>
3895RT_C_DECLS_BEGIN
3896/* Private interface in 10.3 and later. */
3897typedef int CGSConnection;
3898typedef enum
3899{
3900 kCGSGlobalHotKeyEnable = 0,
3901 kCGSGlobalHotKeyDisable,
3902 kCGSGlobalHotKeyInvalid = -1 /* bird */
3903} CGSGlobalHotKeyOperatingMode;
3904extern CGSConnection _CGSDefaultConnection(void);
3905extern CGError CGSGetGlobalHotKeyOperatingMode(CGSConnection Connection, CGSGlobalHotKeyOperatingMode *enmMode);
3906extern CGError CGSSetGlobalHotKeyOperatingMode(CGSConnection Connection, CGSGlobalHotKeyOperatingMode enmMode);
3907RT_C_DECLS_END
3908
3909/** Keeping track of whether we disabled the hotkeys or not. */
3910static bool g_fHotKeysDisabled = false;
3911/** Whether we've connected or not. */
3912static bool g_fConnectedToCGS = false;
3913/** Cached connection. */
3914static CGSConnection g_CGSConnection;
3915
3916/**
3917 * Disables or enabled global hot keys.
3918 */
3919static void DisableGlobalHotKeys(bool fDisable)
3920{
3921 if (!g_fConnectedToCGS)
3922 {
3923 g_CGSConnection = _CGSDefaultConnection();
3924 g_fConnectedToCGS = true;
3925 }
3926
3927 /* get current mode. */
3928 CGSGlobalHotKeyOperatingMode enmMode = kCGSGlobalHotKeyInvalid;
3929 CGSGetGlobalHotKeyOperatingMode(g_CGSConnection, &enmMode);
3930
3931 /* calc new mode. */
3932 if (fDisable)
3933 {
3934 if (enmMode != kCGSGlobalHotKeyEnable)
3935 return;
3936 enmMode = kCGSGlobalHotKeyDisable;
3937 }
3938 else
3939 {
3940 if ( enmMode != kCGSGlobalHotKeyDisable
3941 /*|| !g_fHotKeysDisabled*/)
3942 return;
3943 enmMode = kCGSGlobalHotKeyEnable;
3944 }
3945
3946 /* try set it and check the actual result. */
3947 CGSSetGlobalHotKeyOperatingMode(g_CGSConnection, enmMode);
3948 CGSGlobalHotKeyOperatingMode enmNewMode = kCGSGlobalHotKeyInvalid;
3949 CGSGetGlobalHotKeyOperatingMode(g_CGSConnection, &enmNewMode);
3950 if (enmNewMode == enmMode)
3951 g_fHotKeysDisabled = enmMode == kCGSGlobalHotKeyDisable;
3952}
3953#endif /* RT_OS_DARWIN */
3954
3955/**
3956 * Start grabbing the mouse.
3957 */
3958static void InputGrabStart(void)
3959{
3960#ifdef RT_OS_DARWIN
3961 DisableGlobalHotKeys(true);
3962#endif
3963 if (!gfGuestNeedsHostCursor && gfRelativeMouseGuest)
3964 SDL_ShowCursor(SDL_DISABLE);
3965 SDL_WM_GrabInput(SDL_GRAB_ON);
3966 // dummy read to avoid moving the mouse
3967 SDL_GetRelativeMouseState(
3968#ifdef VBOX_WITH_SDL13
3969 0,
3970#endif
3971 NULL, NULL);
3972 gfGrabbed = TRUE;
3973 UpdateTitlebar(TITLEBAR_NORMAL);
3974}
3975
3976/**
3977 * End mouse grabbing.
3978 */
3979static void InputGrabEnd(void)
3980{
3981 SDL_WM_GrabInput(SDL_GRAB_OFF);
3982 if (!gfGuestNeedsHostCursor && gfRelativeMouseGuest)
3983 SDL_ShowCursor(SDL_ENABLE);
3984#ifdef RT_OS_DARWIN
3985 DisableGlobalHotKeys(false);
3986#endif
3987 gfGrabbed = FALSE;
3988 UpdateTitlebar(TITLEBAR_NORMAL);
3989}
3990
3991/**
3992 * Query mouse position and button state from SDL and send to the VM
3993 *
3994 * @param dz Relative mouse wheel movement
3995 */
3996static void SendMouseEvent(VBoxSDLFB *fb, int dz, int down, int button)
3997{
3998 int x, y, state, buttons;
3999 bool abs;
4000
4001#ifdef VBOX_WITH_SDL13
4002 if (!fb)
4003 {
4004 SDL_GetMouseState(0, &x, &y);
4005 RTPrintf("MouseEvent: Cannot find fb mouse = %d,%d\n", x, y);
4006 return;
4007 }
4008#else
4009 AssertRelease(fb != NULL);
4010#endif
4011
4012 /*
4013 * If supported and we're not in grabbed mode, we'll use the absolute mouse.
4014 * If we are in grabbed mode and the guest is not able to draw the mouse cursor
4015 * itself, or can't handle relative reporting, we have to use absolute
4016 * coordinates, otherwise the host cursor and
4017 * the coordinates the guest thinks the mouse is at could get out-of-sync. From
4018 * the SDL mailing list:
4019 *
4020 * "The event processing is usually asynchronous and so somewhat delayed, and
4021 * SDL_GetMouseState is returning the immediate mouse state. So at the time you
4022 * call SDL_GetMouseState, the "button" is already up."
4023 */
4024 abs = (UseAbsoluteMouse() && !gfGrabbed)
4025 || gfGuestNeedsHostCursor
4026 || !gfRelativeMouseGuest;
4027
4028 /* only used if abs == TRUE */
4029 int xOrigin = fb->getOriginX();
4030 int yOrigin = fb->getOriginY();
4031 int xMin = fb->getXOffset() + xOrigin;
4032 int yMin = fb->getYOffset() + yOrigin;
4033 int xMax = xMin + (int)fb->getGuestXRes();
4034 int yMax = yMin + (int)fb->getGuestYRes();
4035
4036 state = abs ? SDL_GetMouseState(
4037#ifdef VBOX_WITH_SDL13
4038 0,
4039#endif
4040 &x, &y)
4041 : SDL_GetRelativeMouseState(
4042#ifdef VBOX_WITH_SDL13
4043 0,
4044#endif
4045 &x, &y);
4046
4047 /*
4048 * process buttons
4049 */
4050 buttons = 0;
4051 if (state & SDL_BUTTON(SDL_BUTTON_LEFT))
4052 buttons |= MouseButtonState_LeftButton;
4053 if (state & SDL_BUTTON(SDL_BUTTON_RIGHT))
4054 buttons |= MouseButtonState_RightButton;
4055 if (state & SDL_BUTTON(SDL_BUTTON_MIDDLE))
4056 buttons |= MouseButtonState_MiddleButton;
4057
4058 if (abs)
4059 {
4060 x += xOrigin;
4061 y += yOrigin;
4062
4063 /*
4064 * Check if the mouse event is inside the guest area. This solves the
4065 * following problem: Some guests switch off the VBox hardware mouse
4066 * cursor and draw the mouse cursor itself instead. Moving the mouse
4067 * outside the guest area then leads to annoying mouse hangs if we
4068 * don't pass mouse motion events into the guest.
4069 */
4070 if (x < xMin || y < yMin || x > xMax || y > yMax)
4071 {
4072 /*
4073 * Cursor outside of valid guest area (outside window or in secure
4074 * label area. Don't allow any mouse button press.
4075 */
4076 button = 0;
4077
4078 /*
4079 * Release any pressed button.
4080 */
4081#if 0
4082 /* disabled on customers request */
4083 buttons &= ~(MouseButtonState_LeftButton |
4084 MouseButtonState_MiddleButton |
4085 MouseButtonState_RightButton);
4086#endif
4087
4088 /*
4089 * Prevent negative coordinates.
4090 */
4091 if (x < xMin) x = xMin;
4092 if (x > xMax) x = xMax;
4093 if (y < yMin) y = yMin;
4094 if (y > yMax) y = yMax;
4095
4096 if (!gpOffCursor)
4097 {
4098 gpOffCursor = SDL_GetCursor(); /* Cursor image */
4099 gfOffCursorActive = SDL_ShowCursor(-1); /* enabled / disabled */
4100 SDL_SetCursor(gpDefaultCursor);
4101 SDL_ShowCursor(SDL_ENABLE);
4102 }
4103 }
4104 else
4105 {
4106 if (gpOffCursor)
4107 {
4108 /*
4109 * We just entered the valid guest area. Restore the guest mouse
4110 * cursor.
4111 */
4112 SDL_SetCursor(gpOffCursor);
4113 SDL_ShowCursor(gfOffCursorActive ? SDL_ENABLE : SDL_DISABLE);
4114 gpOffCursor = NULL;
4115 }
4116 }
4117 }
4118
4119 /*
4120 * Button was pressed but that press is not reflected in the button state?
4121 */
4122 if (down && !(state & SDL_BUTTON(button)))
4123 {
4124 /*
4125 * It can happen that a mouse up event follows a mouse down event immediately
4126 * and we see the events when the bit in the button state is already cleared
4127 * again. In that case we simulate the mouse down event.
4128 */
4129 int tmp_button = 0;
4130 switch (button)
4131 {
4132 case SDL_BUTTON_LEFT: tmp_button = MouseButtonState_LeftButton; break;
4133 case SDL_BUTTON_MIDDLE: tmp_button = MouseButtonState_MiddleButton; break;
4134 case SDL_BUTTON_RIGHT: tmp_button = MouseButtonState_RightButton; break;
4135 }
4136
4137 if (abs)
4138 {
4139 /**
4140 * @todo
4141 * PutMouseEventAbsolute() expects x and y starting from 1,1.
4142 * should we do the increment internally in PutMouseEventAbsolute()
4143 * or state it in PutMouseEventAbsolute() docs?
4144 */
4145 gpMouse->PutMouseEventAbsolute(x + 1 - xMin + xOrigin,
4146 y + 1 - yMin + yOrigin,
4147 dz, 0 /* horizontal scroll wheel */,
4148 buttons | tmp_button);
4149 }
4150 else
4151 {
4152 gpMouse->PutMouseEvent(0, 0, dz,
4153 0 /* horizontal scroll wheel */,
4154 buttons | tmp_button);
4155 }
4156 }
4157
4158 // now send the mouse event
4159 if (abs)
4160 {
4161 /**
4162 * @todo
4163 * PutMouseEventAbsolute() expects x and y starting from 1,1.
4164 * should we do the increment internally in PutMouseEventAbsolute()
4165 * or state it in PutMouseEventAbsolute() docs?
4166 */
4167 gpMouse->PutMouseEventAbsolute(x + 1 - xMin + xOrigin,
4168 y + 1 - yMin + yOrigin,
4169 dz, 0 /* Horizontal wheel */, buttons);
4170 }
4171 else
4172 {
4173 gpMouse->PutMouseEvent(x, y, dz, 0 /* Horizontal wheel */, buttons);
4174 }
4175}
4176
4177/**
4178 * Resets the VM
4179 */
4180void ResetVM(void)
4181{
4182 if (gpConsole)
4183 gpConsole->Reset();
4184}
4185
4186/**
4187 * Initiates a saved state and updates the titlebar with progress information
4188 */
4189void SaveState(void)
4190{
4191 ResetKeys();
4192 RTThreadYield();
4193 if (gfGrabbed)
4194 InputGrabEnd();
4195 RTThreadYield();
4196 UpdateTitlebar(TITLEBAR_SAVE);
4197 gpProgress = NULL;
4198 HRESULT rc = gpConsole->SaveState(gpProgress.asOutParam());
4199 if (FAILED(rc))
4200 {
4201 RTPrintf("Error saving state! rc = 0x%x\n", rc);
4202 return;
4203 }
4204 Assert(gpProgress);
4205
4206 /*
4207 * Wait for the operation to be completed and work
4208 * the title bar in the mean while.
4209 */
4210 ULONG cPercent = 0;
4211#ifndef RT_OS_DARWIN /* don't break the other guys yet. */
4212 for (;;)
4213 {
4214 BOOL fCompleted = false;
4215 rc = gpProgress->COMGETTER(Completed)(&fCompleted);
4216 if (FAILED(rc) || fCompleted)
4217 break;
4218 ULONG cPercentNow;
4219 rc = gpProgress->COMGETTER(Percent)(&cPercentNow);
4220 if (FAILED(rc))
4221 break;
4222 if (cPercentNow != cPercent)
4223 {
4224 UpdateTitlebar(TITLEBAR_SAVE, cPercent);
4225 cPercent = cPercentNow;
4226 }
4227
4228 /* wait */
4229 rc = gpProgress->WaitForCompletion(100);
4230 if (FAILED(rc))
4231 break;
4232 /// @todo process gui events.
4233 }
4234
4235#else /* new loop which processes GUI events while saving. */
4236
4237 /* start regular timer so we don't starve in the event loop */
4238 SDL_TimerID sdlTimer;
4239 sdlTimer = SDL_AddTimer(100, StartupTimer, NULL);
4240
4241 for (;;)
4242 {
4243 /*
4244 * Check for completion.
4245 */
4246 BOOL fCompleted = false;
4247 rc = gpProgress->COMGETTER(Completed)(&fCompleted);
4248 if (FAILED(rc) || fCompleted)
4249 break;
4250 ULONG cPercentNow;
4251 rc = gpProgress->COMGETTER(Percent)(&cPercentNow);
4252 if (FAILED(rc))
4253 break;
4254 if (cPercentNow != cPercent)
4255 {
4256 UpdateTitlebar(TITLEBAR_SAVE, cPercent);
4257 cPercent = cPercentNow;
4258 }
4259
4260 /*
4261 * Wait for and process GUI a event.
4262 * This is necessary for XPCOM IPC and for updating the
4263 * title bar on the Mac.
4264 */
4265 SDL_Event event;
4266 if (WaitSDLEvent(&event))
4267 {
4268 switch (event.type)
4269 {
4270 /*
4271 * Timer event preventing us from getting stuck.
4272 */
4273 case SDL_USER_EVENT_TIMER:
4274 break;
4275
4276#ifdef USE_XPCOM_QUEUE_THREAD
4277 /*
4278 * User specific XPCOM event queue event
4279 */
4280 case SDL_USER_EVENT_XPCOM_EVENTQUEUE:
4281 {
4282 LogFlow(("SDL_USER_EVENT_XPCOM_EVENTQUEUE: processing XPCOM event queue...\n"));
4283 eventQ->ProcessPendingEvents();
4284 signalXPCOMEventQueueThread();
4285 break;
4286 }
4287#endif /* USE_XPCOM_QUEUE_THREAD */
4288
4289
4290 /*
4291 * Ignore all other events.
4292 */
4293 case SDL_USER_EVENT_NOTIFYCHANGE:
4294 case SDL_USER_EVENT_TERMINATE:
4295 default:
4296 break;
4297 }
4298 }
4299 }
4300
4301 /* kill the timer */
4302 SDL_RemoveTimer(sdlTimer);
4303 sdlTimer = 0;
4304
4305#endif /* RT_OS_DARWIN */
4306
4307 /*
4308 * What's the result of the operation?
4309 */
4310 LONG lrc;
4311 rc = gpProgress->COMGETTER(ResultCode)(&lrc);
4312 if (FAILED(rc))
4313 lrc = ~0;
4314 if (!lrc)
4315 {
4316 UpdateTitlebar(TITLEBAR_SAVE, 100);
4317 RTThreadYield();
4318 RTPrintf("Saved the state successfully.\n");
4319 }
4320 else
4321 RTPrintf("Error saving state, lrc=%d (%#x)\n", lrc, lrc);
4322}
4323
4324/**
4325 * Build the titlebar string
4326 */
4327static void UpdateTitlebar(TitlebarMode mode, uint32_t u32User)
4328{
4329 static char szTitle[1024] = {0};
4330
4331 /* back up current title */
4332 char szPrevTitle[1024];
4333 strcpy(szPrevTitle, szTitle);
4334
4335 Bstr bstrName;
4336 gpMachine->COMGETTER(Name)(bstrName.asOutParam());
4337
4338 RTStrPrintf(szTitle, sizeof(szTitle), "%s - " VBOX_PRODUCT,
4339 !bstrName.isEmpty() ? Utf8Str(bstrName).c_str() : "<noname>");
4340
4341 /* which mode are we in? */
4342 switch (mode)
4343 {
4344 case TITLEBAR_NORMAL:
4345 {
4346 MachineState_T machineState;
4347 gpMachine->COMGETTER(State)(&machineState);
4348 if (machineState == MachineState_Paused)
4349 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle), " - [Paused]");
4350
4351 if (gfGrabbed)
4352 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle), " - [Input captured]");
4353
4354#if defined(DEBUG) || defined(VBOX_WITH_STATISTICS)
4355 // do we have a debugger interface
4356 if (gpMachineDebugger)
4357 {
4358 // query the machine state
4359 BOOL recompileSupervisor = FALSE;
4360 BOOL recompileUser = FALSE;
4361 BOOL patmEnabled = FALSE;
4362 BOOL csamEnabled = FALSE;
4363 BOOL singlestepEnabled = FALSE;
4364 BOOL logEnabled = FALSE;
4365 BOOL hwVirtEnabled = FALSE;
4366 ULONG virtualTimeRate = 100;
4367 gpMachineDebugger->COMGETTER(RecompileSupervisor)(&recompileSupervisor);
4368 gpMachineDebugger->COMGETTER(RecompileUser)(&recompileUser);
4369 gpMachineDebugger->COMGETTER(PATMEnabled)(&patmEnabled);
4370 gpMachineDebugger->COMGETTER(CSAMEnabled)(&csamEnabled);
4371 gpMachineDebugger->COMGETTER(LogEnabled)(&logEnabled);
4372 gpMachineDebugger->COMGETTER(SingleStep)(&singlestepEnabled);
4373 gpMachineDebugger->COMGETTER(HWVirtExEnabled)(&hwVirtEnabled);
4374 gpMachineDebugger->COMGETTER(VirtualTimeRate)(&virtualTimeRate);
4375 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4376 " [STEP=%d CS=%d PAT=%d RR0=%d RR3=%d LOG=%d HWVirt=%d",
4377 singlestepEnabled == TRUE, csamEnabled == TRUE, patmEnabled == TRUE,
4378 recompileSupervisor == FALSE, recompileUser == FALSE,
4379 logEnabled == TRUE, hwVirtEnabled == TRUE);
4380 char *psz = strchr(szTitle, '\0');
4381 if (virtualTimeRate != 100)
4382 RTStrPrintf(psz, &szTitle[sizeof(szTitle)] - psz, " WD=%d%%]", virtualTimeRate);
4383 else
4384 RTStrPrintf(psz, &szTitle[sizeof(szTitle)] - psz, "]");
4385 }
4386#endif /* DEBUG || VBOX_WITH_STATISTICS */
4387 break;
4388 }
4389
4390 case TITLEBAR_STARTUP:
4391 {
4392 /*
4393 * Format it.
4394 */
4395 MachineState_T machineState;
4396 gpMachine->COMGETTER(State)(&machineState);
4397 if (machineState == MachineState_Starting)
4398 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4399 " - Starting...");
4400 else if (machineState == MachineState_Restoring)
4401 {
4402 ULONG cPercentNow;
4403 HRESULT rc = gpProgress->COMGETTER(Percent)(&cPercentNow);
4404 if (SUCCEEDED(rc))
4405 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4406 " - Restoring %d%%...", (int)cPercentNow);
4407 else
4408 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4409 " - Restoring...");
4410 }
4411 else if (machineState == MachineState_TeleportingIn)
4412 {
4413 ULONG cPercentNow;
4414 HRESULT rc = gpProgress->COMGETTER(Percent)(&cPercentNow);
4415 if (SUCCEEDED(rc))
4416 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4417 " - Teleporting %d%%...", (int)cPercentNow);
4418 else
4419 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4420 " - Teleporting...");
4421 }
4422 /* ignore other states, we could already be in running or aborted state */
4423 break;
4424 }
4425
4426 case TITLEBAR_SAVE:
4427 {
4428 AssertMsg(u32User <= 100, ("%d\n", u32User));
4429 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4430 " - Saving %d%%...", u32User);
4431 break;
4432 }
4433
4434 case TITLEBAR_SNAPSHOT:
4435 {
4436 AssertMsg(u32User <= 100, ("%d\n", u32User));
4437 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4438 " - Taking snapshot %d%%...", u32User);
4439 break;
4440 }
4441
4442 default:
4443 RTPrintf("Error: Invalid title bar mode %d!\n", mode);
4444 return;
4445 }
4446
4447 /*
4448 * Don't update if it didn't change.
4449 */
4450 if (!strcmp(szTitle, szPrevTitle))
4451 return;
4452
4453 /*
4454 * Set the new title
4455 */
4456#ifdef VBOX_WIN32_UI
4457 setUITitle(szTitle);
4458#else
4459 SDL_WM_SetCaption(szTitle, VBOX_PRODUCT);
4460#endif
4461}
4462
4463#if 0
4464static void vbox_show_shape(unsigned short w, unsigned short h,
4465 uint32_t bg, const uint8_t *image)
4466{
4467 size_t x, y;
4468 unsigned short pitch;
4469 const uint32_t *color;
4470 const uint8_t *mask;
4471 size_t size_mask;
4472
4473 mask = image;
4474 pitch = (w + 7) / 8;
4475 size_mask = (pitch * h + 3) & ~3;
4476
4477 color = (const uint32_t *)(image + size_mask);
4478
4479 printf("show_shape %dx%d pitch %d size mask %d\n",
4480 w, h, pitch, size_mask);
4481 for (y = 0; y < h; ++y, mask += pitch, color += w)
4482 {
4483 for (x = 0; x < w; ++x) {
4484 if (mask[x / 8] & (1 << (7 - (x % 8))))
4485 printf(" ");
4486 else
4487 {
4488 uint32_t c = color[x];
4489 if (c == bg)
4490 printf("Y");
4491 else
4492 printf("X");
4493 }
4494 }
4495 printf("\n");
4496 }
4497}
4498#endif
4499
4500/**
4501 * Sets the pointer shape according to parameters.
4502 * Must be called only from the main SDL thread.
4503 */
4504static void SetPointerShape(const PointerShapeChangeData *data)
4505{
4506 /*
4507 * don't allow to change the pointer shape if we are outside the valid
4508 * guest area. In that case set standard mouse pointer is set and should
4509 * not get overridden.
4510 */
4511 if (gpOffCursor)
4512 return;
4513
4514 if (data->shape.size() > 0)
4515 {
4516 bool ok = false;
4517
4518 uint32_t andMaskSize = (data->width + 7) / 8 * data->height;
4519 uint32_t srcShapePtrScan = data->width * 4;
4520
4521 const uint8_t* shape = data->shape.raw();
4522 const uint8_t *srcAndMaskPtr = shape;
4523 const uint8_t *srcShapePtr = shape + ((andMaskSize + 3) & ~3);
4524
4525#if 0
4526 /* pointer debugging code */
4527 // vbox_show_shape(data->width, data->height, 0, data->shape);
4528 uint32_t shapeSize = ((((data->width + 7) / 8) * data->height + 3) & ~3) + data->width * 4 * data->height;
4529 printf("visible: %d\n", data->visible);
4530 printf("width = %d\n", data->width);
4531 printf("height = %d\n", data->height);
4532 printf("alpha = %d\n", data->alpha);
4533 printf("xhot = %d\n", data->xHot);
4534 printf("yhot = %d\n", data->yHot);
4535 printf("uint8_t pointerdata[] = { ");
4536 for (uint32_t i = 0; i < shapeSize; i++)
4537 {
4538 printf("0x%x, ", data->shape[i]);
4539 }
4540 printf("};\n");
4541#endif
4542
4543#if defined(RT_OS_WINDOWS)
4544
4545 BITMAPV5HEADER bi;
4546 HBITMAP hBitmap;
4547 void *lpBits;
4548 HCURSOR hAlphaCursor = NULL;
4549
4550 ::ZeroMemory(&bi, sizeof(BITMAPV5HEADER));
4551 bi.bV5Size = sizeof(BITMAPV5HEADER);
4552 bi.bV5Width = data->width;
4553 bi.bV5Height = -(LONG)data->height;
4554 bi.bV5Planes = 1;
4555 bi.bV5BitCount = 32;
4556 bi.bV5Compression = BI_BITFIELDS;
4557 // specify a supported 32 BPP alpha format for Windows XP
4558 bi.bV5RedMask = 0x00FF0000;
4559 bi.bV5GreenMask = 0x0000FF00;
4560 bi.bV5BlueMask = 0x000000FF;
4561 if (data->alpha)
4562 bi.bV5AlphaMask = 0xFF000000;
4563 else
4564 bi.bV5AlphaMask = 0;
4565
4566 HDC hdc = ::GetDC(NULL);
4567
4568 // create the DIB section with an alpha channel
4569 hBitmap = ::CreateDIBSection(hdc, (BITMAPINFO *)&bi, DIB_RGB_COLORS,
4570 (void **)&lpBits, NULL, (DWORD)0);
4571
4572 ::ReleaseDC(NULL, hdc);
4573
4574 HBITMAP hMonoBitmap = NULL;
4575 if (data->alpha)
4576 {
4577 // create an empty mask bitmap
4578 hMonoBitmap = ::CreateBitmap(data->width, data->height, 1, 1, NULL);
4579 }
4580 else
4581 {
4582 /* Word aligned AND mask. Will be allocated and created if necessary. */
4583 uint8_t *pu8AndMaskWordAligned = NULL;
4584
4585 /* Width in bytes of the original AND mask scan line. */
4586 uint32_t cbAndMaskScan = (data->width + 7) / 8;
4587
4588 if (cbAndMaskScan & 1)
4589 {
4590 /* Original AND mask is not word aligned. */
4591
4592 /* Allocate memory for aligned AND mask. */
4593 pu8AndMaskWordAligned = (uint8_t *)RTMemTmpAllocZ((cbAndMaskScan + 1) * data->height);
4594
4595 Assert(pu8AndMaskWordAligned);
4596
4597 if (pu8AndMaskWordAligned)
4598 {
4599 /* According to MSDN the padding bits must be 0.
4600 * Compute the bit mask to set padding bits to 0 in the last byte of original AND mask.
4601 */
4602 uint32_t u32PaddingBits = cbAndMaskScan * 8 - data->width;
4603 Assert(u32PaddingBits < 8);
4604 uint8_t u8LastBytesPaddingMask = (uint8_t)(0xFF << u32PaddingBits);
4605
4606 Log(("u8LastBytesPaddingMask = %02X, aligned w = %d, width = %d, cbAndMaskScan = %d\n",
4607 u8LastBytesPaddingMask, (cbAndMaskScan + 1) * 8, data->width, cbAndMaskScan));
4608
4609 uint8_t *src = (uint8_t *)srcAndMaskPtr;
4610 uint8_t *dst = pu8AndMaskWordAligned;
4611
4612 unsigned i;
4613 for (i = 0; i < data->height; i++)
4614 {
4615 memcpy(dst, src, cbAndMaskScan);
4616
4617 dst[cbAndMaskScan - 1] &= u8LastBytesPaddingMask;
4618
4619 src += cbAndMaskScan;
4620 dst += cbAndMaskScan + 1;
4621 }
4622 }
4623 }
4624
4625 // create the AND mask bitmap
4626 hMonoBitmap = ::CreateBitmap(data->width, data->height, 1, 1,
4627 pu8AndMaskWordAligned? pu8AndMaskWordAligned: srcAndMaskPtr);
4628
4629 if (pu8AndMaskWordAligned)
4630 {
4631 RTMemTmpFree(pu8AndMaskWordAligned);
4632 }
4633 }
4634
4635 Assert(hBitmap);
4636 Assert(hMonoBitmap);
4637 if (hBitmap && hMonoBitmap)
4638 {
4639 DWORD *dstShapePtr = (DWORD *)lpBits;
4640
4641 for (uint32_t y = 0; y < data->height; y ++)
4642 {
4643 memcpy(dstShapePtr, srcShapePtr, srcShapePtrScan);
4644 srcShapePtr += srcShapePtrScan;
4645 dstShapePtr += data->width;
4646 }
4647
4648 ICONINFO ii;
4649 ii.fIcon = FALSE;
4650 ii.xHotspot = data->xHot;
4651 ii.yHotspot = data->yHot;
4652 ii.hbmMask = hMonoBitmap;
4653 ii.hbmColor = hBitmap;
4654
4655 hAlphaCursor = ::CreateIconIndirect(&ii);
4656 Assert(hAlphaCursor);
4657 if (hAlphaCursor)
4658 {
4659 // here we do a dirty trick by substituting a Window Manager's
4660 // cursor handle with the handle we created
4661
4662 WMcursor *pCustomTempWMCursor = gpCustomCursor->wm_cursor;
4663
4664 // see SDL12/src/video/wincommon/SDL_sysmouse.c
4665 void *wm_cursor = malloc(sizeof(HCURSOR) + sizeof(uint8_t *) * 2);
4666 *(HCURSOR *)wm_cursor = hAlphaCursor;
4667
4668 gpCustomCursor->wm_cursor = (WMcursor *)wm_cursor;
4669 SDL_SetCursor(gpCustomCursor);
4670 SDL_ShowCursor(SDL_ENABLE);
4671
4672 if (pCustomTempWMCursor)
4673 {
4674 ::DestroyCursor(*(HCURSOR *)pCustomTempWMCursor);
4675 free(pCustomTempWMCursor);
4676 }
4677
4678 ok = true;
4679 }
4680 }
4681
4682 if (hMonoBitmap)
4683 ::DeleteObject(hMonoBitmap);
4684 if (hBitmap)
4685 ::DeleteObject(hBitmap);
4686
4687#elif defined(VBOXSDL_WITH_X11) && !defined(VBOX_WITHOUT_XCURSOR)
4688
4689 if (gfXCursorEnabled)
4690 {
4691 XcursorImage *img = XcursorImageCreate(data->width, data->height);
4692 Assert(img);
4693 if (img)
4694 {
4695 img->xhot = data->xHot;
4696 img->yhot = data->yHot;
4697
4698 XcursorPixel *dstShapePtr = img->pixels;
4699
4700 for (uint32_t y = 0; y < data->height; y ++)
4701 {
4702 memcpy(dstShapePtr, srcShapePtr, srcShapePtrScan);
4703
4704 if (!data->alpha)
4705 {
4706 // convert AND mask to the alpha channel
4707 uint8_t byte = 0;
4708 for (uint32_t x = 0; x < data->width; x ++)
4709 {
4710 if (!(x % 8))
4711 byte = *(srcAndMaskPtr ++);
4712 else
4713 byte <<= 1;
4714
4715 if (byte & 0x80)
4716 {
4717 // Linux doesn't support inverted pixels (XOR ops,
4718 // to be exact) in cursor shapes, so we detect such
4719 // pixels and always replace them with black ones to
4720 // make them visible at least over light colors
4721 if (dstShapePtr [x] & 0x00FFFFFF)
4722 dstShapePtr [x] = 0xFF000000;
4723 else
4724 dstShapePtr [x] = 0x00000000;
4725 }
4726 else
4727 dstShapePtr [x] |= 0xFF000000;
4728 }
4729 }
4730
4731 srcShapePtr += srcShapePtrScan;
4732 dstShapePtr += data->width;
4733 }
4734
4735#ifndef VBOX_WITH_SDL13
4736 Cursor cur = XcursorImageLoadCursor(gSdlInfo.info.x11.display, img);
4737 Assert(cur);
4738 if (cur)
4739 {
4740 // here we do a dirty trick by substituting a Window Manager's
4741 // cursor handle with the handle we created
4742
4743 WMcursor *pCustomTempWMCursor = gpCustomCursor->wm_cursor;
4744
4745 // see SDL12/src/video/x11/SDL_x11mouse.c
4746 void *wm_cursor = malloc(sizeof(Cursor));
4747 *(Cursor *)wm_cursor = cur;
4748
4749 gpCustomCursor->wm_cursor = (WMcursor *)wm_cursor;
4750 SDL_SetCursor(gpCustomCursor);
4751 SDL_ShowCursor(SDL_ENABLE);
4752
4753 if (pCustomTempWMCursor)
4754 {
4755 XFreeCursor(gSdlInfo.info.x11.display, *(Cursor *)pCustomTempWMCursor);
4756 free(pCustomTempWMCursor);
4757 }
4758
4759 ok = true;
4760 }
4761#endif
4762 }
4763 XcursorImageDestroy(img);
4764 }
4765
4766#endif /* VBOXSDL_WITH_X11 && !VBOX_WITHOUT_XCURSOR */
4767
4768 if (!ok)
4769 {
4770 SDL_SetCursor(gpDefaultCursor);
4771 SDL_ShowCursor(SDL_ENABLE);
4772 }
4773 }
4774 else
4775 {
4776 if (data->visible)
4777 SDL_ShowCursor(SDL_ENABLE);
4778 else if (gfAbsoluteMouseGuest)
4779 /* Don't disable the cursor if the guest additions are not active (anymore) */
4780 SDL_ShowCursor(SDL_DISABLE);
4781 }
4782}
4783
4784/**
4785 * Handle changed mouse capabilities
4786 */
4787static void HandleGuestCapsChanged(void)
4788{
4789 if (!gfAbsoluteMouseGuest)
4790 {
4791 // Cursor could be overwritten by the guest tools
4792 SDL_SetCursor(gpDefaultCursor);
4793 SDL_ShowCursor(SDL_ENABLE);
4794 gpOffCursor = NULL;
4795 }
4796 if (gpMouse && UseAbsoluteMouse())
4797 {
4798 // Actually switch to absolute coordinates
4799 if (gfGrabbed)
4800 InputGrabEnd();
4801 gpMouse->PutMouseEventAbsolute(-1, -1, 0, 0, 0);
4802 }
4803}
4804
4805/**
4806 * Handles a host key down event
4807 */
4808static int HandleHostKey(const SDL_KeyboardEvent *pEv)
4809{
4810 /*
4811 * Revalidate the host key modifier
4812 */
4813 if ((SDL_GetModState() & ~(KMOD_MODE | KMOD_NUM | KMOD_RESERVED)) != gHostKeyMod)
4814 return VERR_NOT_SUPPORTED;
4815
4816 /*
4817 * What was pressed?
4818 */
4819 switch (pEv->keysym.sym)
4820 {
4821 /* Control-Alt-Delete */
4822 case SDLK_DELETE:
4823 {
4824 gpKeyboard->PutCAD();
4825 break;
4826 }
4827
4828 /*
4829 * Fullscreen / Windowed toggle.
4830 */
4831 case SDLK_f:
4832 {
4833 if ( strchr(gHostKeyDisabledCombinations, 'f')
4834 || !gfAllowFullscreenToggle)
4835 return VERR_NOT_SUPPORTED;
4836
4837 /*
4838 * We have to pause/resume the machine during this
4839 * process because there might be a short moment
4840 * without a valid framebuffer
4841 */
4842 MachineState_T machineState;
4843 gpMachine->COMGETTER(State)(&machineState);
4844 bool fPauseIt = machineState == MachineState_Running
4845 || machineState == MachineState_Teleporting
4846 || machineState == MachineState_LiveSnapshotting;
4847 if (fPauseIt)
4848 gpConsole->Pause();
4849 SetFullscreen(!gpFramebuffer[0]->getFullscreen());
4850 if (fPauseIt)
4851 gpConsole->Resume();
4852
4853 /*
4854 * We have switched from/to fullscreen, so request a full
4855 * screen repaint, just to be sure.
4856 */
4857 gpDisplay->InvalidateAndUpdate();
4858 break;
4859 }
4860
4861 /*
4862 * Pause / Resume toggle.
4863 */
4864 case SDLK_p:
4865 {
4866 if (strchr(gHostKeyDisabledCombinations, 'p'))
4867 return VERR_NOT_SUPPORTED;
4868
4869 MachineState_T machineState;
4870 gpMachine->COMGETTER(State)(&machineState);
4871 if ( machineState == MachineState_Running
4872 || machineState == MachineState_Teleporting
4873 || machineState == MachineState_LiveSnapshotting
4874 )
4875 {
4876 if (gfGrabbed)
4877 InputGrabEnd();
4878 gpConsole->Pause();
4879 }
4880 else if (machineState == MachineState_Paused)
4881 {
4882 gpConsole->Resume();
4883 }
4884 UpdateTitlebar(TITLEBAR_NORMAL);
4885 break;
4886 }
4887
4888 /*
4889 * Reset the VM
4890 */
4891 case SDLK_r:
4892 {
4893 if (strchr(gHostKeyDisabledCombinations, 'r'))
4894 return VERR_NOT_SUPPORTED;
4895
4896 ResetVM();
4897 break;
4898 }
4899
4900 /*
4901 * Terminate the VM
4902 */
4903 case SDLK_q:
4904 {
4905 if (strchr(gHostKeyDisabledCombinations, 'q'))
4906 return VERR_NOT_SUPPORTED;
4907
4908 return VINF_EM_TERMINATE;
4909 }
4910
4911 /*
4912 * Save the machine's state and exit
4913 */
4914 case SDLK_s:
4915 {
4916 if (strchr(gHostKeyDisabledCombinations, 's'))
4917 return VERR_NOT_SUPPORTED;
4918
4919 SaveState();
4920 return VINF_EM_TERMINATE;
4921 }
4922
4923 case SDLK_h:
4924 {
4925 if (strchr(gHostKeyDisabledCombinations, 'h'))
4926 return VERR_NOT_SUPPORTED;
4927
4928 if (gpConsole)
4929 gpConsole->PowerButton();
4930 break;
4931 }
4932
4933 /*
4934 * Perform an online snapshot. Continue operation.
4935 */
4936 case SDLK_n:
4937 {
4938 if (strchr(gHostKeyDisabledCombinations, 'n'))
4939 return VERR_NOT_SUPPORTED;
4940
4941 RTThreadYield();
4942 ULONG cSnapshots = 0;
4943 gpMachine->COMGETTER(SnapshotCount)(&cSnapshots);
4944 char pszSnapshotName[20];
4945 RTStrPrintf(pszSnapshotName, sizeof(pszSnapshotName), "Snapshot %d", cSnapshots + 1);
4946 gpProgress = NULL;
4947 HRESULT rc;
4948 CHECK_ERROR(gpConsole, TakeSnapshot(Bstr(pszSnapshotName).raw(),
4949 Bstr("Taken by VBoxSDL").raw(),
4950 gpProgress.asOutParam()));
4951 if (FAILED(rc))
4952 {
4953 RTPrintf("Error taking snapshot! rc = 0x%x\n", rc);
4954 /* continue operation */
4955 return VINF_SUCCESS;
4956 }
4957 /*
4958 * Wait for the operation to be completed and work
4959 * the title bar in the mean while.
4960 */
4961 ULONG cPercent = 0;
4962 for (;;)
4963 {
4964 BOOL fCompleted = false;
4965 rc = gpProgress->COMGETTER(Completed)(&fCompleted);
4966 if (FAILED(rc) || fCompleted)
4967 break;
4968 ULONG cPercentNow;
4969 rc = gpProgress->COMGETTER(Percent)(&cPercentNow);
4970 if (FAILED(rc))
4971 break;
4972 if (cPercentNow != cPercent)
4973 {
4974 UpdateTitlebar(TITLEBAR_SNAPSHOT, cPercent);
4975 cPercent = cPercentNow;
4976 }
4977
4978 /* wait */
4979 rc = gpProgress->WaitForCompletion(100);
4980 if (FAILED(rc))
4981 break;
4982 /// @todo process gui events.
4983 }
4984
4985 /* continue operation */
4986 return VINF_SUCCESS;
4987 }
4988
4989 case SDLK_F1: case SDLK_F2: case SDLK_F3:
4990 case SDLK_F4: case SDLK_F5: case SDLK_F6:
4991 case SDLK_F7: case SDLK_F8: case SDLK_F9:
4992 case SDLK_F10: case SDLK_F11: case SDLK_F12:
4993 {
4994 // /* send Ctrl-Alt-Fx to guest */
4995 com::SafeArray<LONG> keys(6);
4996
4997 keys[0] = 0x1d; // Ctrl down
4998 keys[1] = 0x38; // Alt down
4999 keys[2] = Keyevent2Keycode(pEv); // Fx down
5000 keys[3] = keys[2] + 0x80; // Fx up
5001 keys[4] = 0xb8; // Alt up
5002 keys[5] = 0x9d; // Ctrl up
5003
5004 gpKeyboard->PutScancodes(ComSafeArrayAsInParam(keys), NULL);
5005 return VINF_SUCCESS;
5006 }
5007
5008 /*
5009 * Not a host key combination.
5010 * Indicate this by returning false.
5011 */
5012 default:
5013 return VERR_NOT_SUPPORTED;
5014 }
5015
5016 return VINF_SUCCESS;
5017}
5018
5019/**
5020 * Timer callback function for startup processing
5021 */
5022static Uint32 StartupTimer(Uint32 interval, void *param)
5023{
5024 /* post message so we can do something in the startup loop */
5025 SDL_Event event = {0};
5026 event.type = SDL_USEREVENT;
5027 event.user.type = SDL_USER_EVENT_TIMER;
5028 SDL_PushEvent(&event);
5029 RTSemEventSignal(g_EventSemSDLEvents);
5030 return interval;
5031}
5032
5033/**
5034 * Timer callback function to check if resizing is finished
5035 */
5036static Uint32 ResizeTimer(Uint32 interval, void *param)
5037{
5038 /* post message so the window is actually resized */
5039 SDL_Event event = {0};
5040 event.type = SDL_USEREVENT;
5041 event.user.type = SDL_USER_EVENT_WINDOW_RESIZE_DONE;
5042 PushSDLEventForSure(&event);
5043 /* one-shot */
5044 return 0;
5045}
5046
5047/**
5048 * Timer callback function to check if an ACPI power button event was handled by the guest.
5049 */
5050static Uint32 QuitTimer(Uint32 interval, void *param)
5051{
5052 BOOL fHandled = FALSE;
5053
5054 gSdlQuitTimer = NULL;
5055 if (gpConsole)
5056 {
5057 int rc = gpConsole->GetPowerButtonHandled(&fHandled);
5058 LogRel(("QuitTimer: rc=%d handled=%d\n", rc, fHandled));
5059 if (RT_FAILURE(rc) || !fHandled)
5060 {
5061 /* event was not handled, power down the guest */
5062 gfACPITerm = FALSE;
5063 SDL_Event event = {0};
5064 event.type = SDL_QUIT;
5065 PushSDLEventForSure(&event);
5066 }
5067 }
5068 /* one-shot */
5069 return 0;
5070}
5071
5072/**
5073 * Wait for the next SDL event. Don't use SDL_WaitEvent since this function
5074 * calls SDL_Delay(10) if the event queue is empty.
5075 */
5076static int WaitSDLEvent(SDL_Event *event)
5077{
5078 for (;;)
5079 {
5080 int rc = SDL_PollEvent(event);
5081 if (rc == 1)
5082 {
5083#ifdef USE_XPCOM_QUEUE_THREAD
5084 if (event->type == SDL_USER_EVENT_XPCOM_EVENTQUEUE)
5085 consumedXPCOMUserEvent();
5086#endif
5087 return 1;
5088 }
5089 /* Immediately wake up if new SDL events are available. This does not
5090 * work for internal SDL events. Don't wait more than 10ms. */
5091 RTSemEventWait(g_EventSemSDLEvents, 10);
5092 }
5093}
5094
5095/**
5096 * Ensure that an SDL event is really enqueued. Try multiple times if necessary.
5097 */
5098int PushSDLEventForSure(SDL_Event *event)
5099{
5100 int ntries = 10;
5101 for (; ntries > 0; ntries--)
5102 {
5103 int rc = SDL_PushEvent(event);
5104 RTSemEventSignal(g_EventSemSDLEvents);
5105#ifdef VBOX_WITH_SDL13
5106 if (rc == 1)
5107#else
5108 if (rc == 0)
5109#endif
5110 return 0;
5111 Log(("PushSDLEventForSure: waiting for 2ms (rc = %d)\n", rc));
5112 RTThreadSleep(2);
5113 }
5114 LogRel(("WARNING: Failed to enqueue SDL event %d.%d!\n",
5115 event->type, event->type == SDL_USEREVENT ? event->user.type : 0));
5116 return -1;
5117}
5118
5119#ifdef VBOXSDL_WITH_X11
5120/**
5121 * Special SDL_PushEvent function for NotifyUpdate events. These events may occur in bursts
5122 * so make sure they don't flood the SDL event queue.
5123 */
5124void PushNotifyUpdateEvent(SDL_Event *event)
5125{
5126 int rc = SDL_PushEvent(event);
5127#ifdef VBOX_WITH_SDL13
5128 bool fSuccess = (rc == 1);
5129#else
5130 bool fSuccess = (rc == 0);
5131#endif
5132
5133 RTSemEventSignal(g_EventSemSDLEvents);
5134 AssertMsg(fSuccess, ("SDL_PushEvent returned SDL error\n"));
5135 /* A global counter is faster than SDL_PeepEvents() */
5136 if (fSuccess)
5137 ASMAtomicIncS32(&g_cNotifyUpdateEventsPending);
5138 /* In order to not flood the SDL event queue, yield the CPU or (if there are already many
5139 * events queued) even sleep */
5140 if (g_cNotifyUpdateEventsPending > 96)
5141 {
5142 /* Too many NotifyUpdate events, sleep for a small amount to give the main thread time
5143 * to handle these events. The SDL queue can hold up to 128 events. */
5144 Log(("PushNotifyUpdateEvent: Sleep 1ms\n"));
5145 RTThreadSleep(1);
5146 }
5147 else
5148 RTThreadYield();
5149}
5150#endif /* VBOXSDL_WITH_X11 */
5151
5152/**
5153 *
5154 */
5155static void SetFullscreen(bool enable)
5156{
5157 if (enable == gpFramebuffer[0]->getFullscreen())
5158 return;
5159
5160 if (!gfFullscreenResize)
5161 {
5162 /*
5163 * The old/default way: SDL will resize the host to fit the guest screen resolution.
5164 */
5165 gpFramebuffer[0]->setFullscreen(enable);
5166 }
5167 else
5168 {
5169 /*
5170 * The alternate way: Switch to fullscreen with the host screen resolution and adapt
5171 * the guest screen resolution to the host window geometry.
5172 */
5173 uint32_t NewWidth = 0, NewHeight = 0;
5174 if (enable)
5175 {
5176 /* switch to fullscreen */
5177 gmGuestNormalXRes = gpFramebuffer[0]->getGuestXRes();
5178 gmGuestNormalYRes = gpFramebuffer[0]->getGuestYRes();
5179 gpFramebuffer[0]->getFullscreenGeometry(&NewWidth, &NewHeight);
5180 }
5181 else
5182 {
5183 /* switch back to saved geometry */
5184 NewWidth = gmGuestNormalXRes;
5185 NewHeight = gmGuestNormalYRes;
5186 }
5187 if (NewWidth != 0 && NewHeight != 0)
5188 {
5189 gpFramebuffer[0]->setFullscreen(enable);
5190 gfIgnoreNextResize = TRUE;
5191 gpDisplay->SetVideoModeHint(0 /*=display*/, true /*=enabled*/,
5192 false /*=changeOrigin*/, 0 /*=originX*/, 0 /*=originY*/,
5193 NewWidth, NewHeight, 0 /*don't change bpp*/);
5194 }
5195 }
5196}
5197
5198#ifdef VBOX_WITH_SDL13
5199static VBoxSDLFB * getFbFromWinId(SDL_WindowID id)
5200{
5201 for (unsigned i = 0; i < gcMonitors; i++)
5202 if (gpFramebuffer[i]->hasWindow(id))
5203 return gpFramebuffer[i];
5204
5205 return NULL;
5206}
5207#endif
Note: See TracBrowser for help on using the repository browser.

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