VirtualBox

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

Last change on this file since 51371 was 51122, checked in by vboxsync, 11 years ago

FE/SDL: make lock keys work with recent SDL versions.

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

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