VirtualBox

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

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

Main: reworked listener objects creation, fixes Win problems with events, few cleanups

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