VirtualBox

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

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

Main, frontends: unsigned long long -> long long

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

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