VirtualBox

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

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

FE/Common/VBoxKeyboard: try to use XKB to determine the keyboard layout as well, and by default

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