VirtualBox

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

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

SDL frontend: fixed starting SDL VMs using API

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