VirtualBox

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

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

Main: have Machine::MountMedium() behave like AttachDevice (use IMedium* pointer instead of UUID); add missing saveSettings calls there

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

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