VirtualBox

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

Last change on this file since 51606 was 51547, checked in by vboxsync, 11 years ago

VBoxSDL: new IFramebuffer interface cleanup.

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