VirtualBox

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

Last change on this file since 33590 was 33590, checked in by vboxsync, 14 years ago

VRDE: removed VBOX_WITH_VRDP from source code, also some obsolete code removed.

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