VirtualBox

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

Last change on this file since 48520 was 48137, checked in by vboxsync, 11 years ago

FE/Qt and FE/SDL: always call XInitThreads() before any other Xlib calls.

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