VirtualBox

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

Last change on this file since 35740 was 35726, checked in by vboxsync, 13 years ago

VBoxSDL: remove excessive listener release

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 169.9 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.setNull();
2763 }
2764
2765 /*
2766 * Now we discard all settings so that our changes will
2767 * not be flushed to the permanent configuration
2768 */
2769 if ( gpMachine
2770 && machineState != MachineState_Saved)
2771 {
2772 rc = gpMachine->DiscardSettings();
2773 AssertComRC(rc);
2774 }
2775
2776 /* close the session */
2777 if (sessionOpened)
2778 {
2779 rc = pSession->UnlockMachine();
2780 AssertComRC(rc);
2781 }
2782
2783#ifndef VBOX_WITH_SDL13
2784 /* restore the default cursor and free the custom one if any */
2785 if (gpDefaultCursor)
2786 {
2787# ifdef VBOXSDL_WITH_X11
2788 Cursor pDefaultTempX11Cursor = 0;
2789 if (gfXCursorEnabled)
2790 {
2791 pDefaultTempX11Cursor = *(Cursor*)gpDefaultCursor->wm_cursor;
2792 *(Cursor*)gpDefaultCursor->wm_cursor = gpDefaultOrigX11Cursor;
2793 }
2794# endif /* VBOXSDL_WITH_X11 */
2795 SDL_SetCursor(gpDefaultCursor);
2796# if defined(VBOXSDL_WITH_X11) && !defined(VBOX_WITHOUT_XCURSOR)
2797 if (gfXCursorEnabled)
2798 XFreeCursor(gSdlInfo.info.x11.display, pDefaultTempX11Cursor);
2799# endif /* VBOXSDL_WITH_X11 && !VBOX_WITHOUT_XCURSOR */
2800 }
2801
2802 if (gpCustomCursor)
2803 {
2804 WMcursor *pCustomTempWMCursor = gpCustomCursor->wm_cursor;
2805 gpCustomCursor->wm_cursor = gpCustomOrigWMcursor;
2806 SDL_FreeCursor(gpCustomCursor);
2807 if (pCustomTempWMCursor)
2808 {
2809# if defined(RT_OS_WINDOWS)
2810 ::DestroyCursor(*(HCURSOR *)pCustomTempWMCursor);
2811# elif defined(VBOXSDL_WITH_X11) && !defined(VBOX_WITHOUT_XCURSOR)
2812 if (gfXCursorEnabled)
2813 XFreeCursor(gSdlInfo.info.x11.display, *(Cursor *)pCustomTempWMCursor);
2814# endif /* VBOXSDL_WITH_X11 && !VBOX_WITHOUT_XCURSOR */
2815 free(pCustomTempWMCursor);
2816 }
2817 }
2818#endif
2819
2820 LogFlow(("Releasing mouse, keyboard, remote desktop server, display, console...\n"));
2821 if (gpDisplay)
2822 {
2823 for (unsigned i = 0; i < gcMonitors; i++)
2824 gpDisplay->SetFramebuffer(i, NULL);
2825 }
2826
2827 gpMouse = NULL;
2828 gpKeyboard = NULL;
2829 gpVRDEServer = NULL;
2830 gpDisplay = NULL;
2831 gpConsole = NULL;
2832 gpMachineDebugger = NULL;
2833 gpProgress = NULL;
2834 // we can only uninitialize SDL here because it is not threadsafe
2835
2836 for (unsigned i = 0; i < gcMonitors; i++)
2837 {
2838 if (gpFramebuffer[i])
2839 {
2840 LogFlow(("Releasing framebuffer...\n"));
2841 gpFramebuffer[i]->Release();
2842 gpFramebuffer[i] = NULL;
2843 }
2844 }
2845
2846 VBoxSDLFB::uninit();
2847
2848#ifdef VBOX_SECURELABEL
2849 /* must do this after destructing the framebuffer */
2850 if (gLibrarySDL_ttf)
2851 RTLdrClose(gLibrarySDL_ttf);
2852#endif
2853
2854 /* VirtualBox (server) listener unregistration. */
2855 if (pVBoxListener)
2856 {
2857 ComPtr<IEventSource> pES;
2858 CHECK_ERROR(pVirtualBox, COMGETTER(EventSource)(pES.asOutParam()));
2859 if (!pES.isNull())
2860 CHECK_ERROR(pES, UnregisterListener(pVBoxListener));
2861 pVBoxListener.setNull();
2862 }
2863
2864 /* VirtualBoxClient listener unregistration. */
2865 if (pVBoxClientListener)
2866 {
2867 ComPtr<IEventSource> pES;
2868 CHECK_ERROR(pVirtualBoxClient, COMGETTER(EventSource)(pES.asOutParam()));
2869 if (!pES.isNull())
2870 CHECK_ERROR(pES, UnregisterListener(pVBoxClientListener));
2871 pVBoxClientListener.setNull();
2872 }
2873
2874 LogFlow(("Releasing machine, session...\n"));
2875 gpMachine = NULL;
2876 pSession = NULL;
2877 LogFlow(("Releasing VirtualBox object...\n"));
2878 pVirtualBox = NULL;
2879 LogFlow(("Releasing VirtualBoxClient object...\n"));
2880 pVirtualBoxClient = NULL;
2881
2882 // end "all-stuff" scope
2883 ////////////////////////////////////////////////////////////////////////////
2884 }
2885
2886 /* Must be before com::Shutdown() */
2887 LogFlow(("Uninitializing COM...\n"));
2888 com::Shutdown();
2889
2890 LogFlow(("Returning from main()!\n"));
2891 RTLogFlush(NULL);
2892 return FAILED(rc) ? 1 : 0;
2893}
2894
2895
2896#ifndef VBOX_WITH_HARDENING
2897/**
2898 * Main entry point
2899 */
2900int main(int argc, char **argv)
2901{
2902 /*
2903 * Before we do *anything*, we initialize the runtime.
2904 */
2905 int rcRT = RTR3InitAndSUPLib();
2906 if (RT_FAILURE(rcRT))
2907 {
2908 RTPrintf("Error: RTR3Init failed rcRC=%d\n", rcRT);
2909 return 1;
2910 }
2911 return TrustedMain(argc, argv, NULL);
2912}
2913#endif /* !VBOX_WITH_HARDENING */
2914
2915
2916/**
2917 * Returns whether the absolute mouse is in use, i.e. both host
2918 * and guest have opted to enable it.
2919 *
2920 * @returns bool Flag whether the absolute mouse is in use
2921 */
2922static bool UseAbsoluteMouse(void)
2923{
2924 return (gfAbsoluteMouseHost && gfAbsoluteMouseGuest);
2925}
2926
2927#if defined(RT_OS_DARWIN) || defined(RT_OS_OS2)
2928/**
2929 * Fallback keycode conversion using SDL symbols.
2930 *
2931 * This is used to catch keycodes that's missing from the translation table.
2932 *
2933 * @returns XT scancode
2934 * @param ev SDL scancode
2935 */
2936static uint16_t Keyevent2KeycodeFallback(const SDL_KeyboardEvent *ev)
2937{
2938 const SDLKey sym = ev->keysym.sym;
2939 Log(("SDL key event: sym=%d scancode=%#x unicode=%#x\n",
2940 sym, ev->keysym.scancode, ev->keysym.unicode));
2941 switch (sym)
2942 { /* set 1 scan code */
2943 case SDLK_ESCAPE: return 0x01;
2944 case SDLK_EXCLAIM:
2945 case SDLK_1: return 0x02;
2946 case SDLK_AT:
2947 case SDLK_2: return 0x03;
2948 case SDLK_HASH:
2949 case SDLK_3: return 0x04;
2950 case SDLK_DOLLAR:
2951 case SDLK_4: return 0x05;
2952 /* % */
2953 case SDLK_5: return 0x06;
2954 case SDLK_CARET:
2955 case SDLK_6: return 0x07;
2956 case SDLK_AMPERSAND:
2957 case SDLK_7: return 0x08;
2958 case SDLK_ASTERISK:
2959 case SDLK_8: return 0x09;
2960 case SDLK_LEFTPAREN:
2961 case SDLK_9: return 0x0a;
2962 case SDLK_RIGHTPAREN:
2963 case SDLK_0: return 0x0b;
2964 case SDLK_UNDERSCORE:
2965 case SDLK_MINUS: return 0x0c;
2966 case SDLK_EQUALS:
2967 case SDLK_PLUS: return 0x0d;
2968 case SDLK_BACKSPACE: return 0x0e;
2969 case SDLK_TAB: return 0x0f;
2970 case SDLK_q: return 0x10;
2971 case SDLK_w: return 0x11;
2972 case SDLK_e: return 0x12;
2973 case SDLK_r: return 0x13;
2974 case SDLK_t: return 0x14;
2975 case SDLK_y: return 0x15;
2976 case SDLK_u: return 0x16;
2977 case SDLK_i: return 0x17;
2978 case SDLK_o: return 0x18;
2979 case SDLK_p: return 0x19;
2980 case SDLK_LEFTBRACKET: return 0x1a;
2981 case SDLK_RIGHTBRACKET: return 0x1b;
2982 case SDLK_RETURN: return 0x1c;
2983 case SDLK_KP_ENTER: return 0x1c | 0x100;
2984 case SDLK_LCTRL: return 0x1d;
2985 case SDLK_RCTRL: return 0x1d | 0x100;
2986 case SDLK_a: return 0x1e;
2987 case SDLK_s: return 0x1f;
2988 case SDLK_d: return 0x20;
2989 case SDLK_f: return 0x21;
2990 case SDLK_g: return 0x22;
2991 case SDLK_h: return 0x23;
2992 case SDLK_j: return 0x24;
2993 case SDLK_k: return 0x25;
2994 case SDLK_l: return 0x26;
2995 case SDLK_COLON:
2996 case SDLK_SEMICOLON: return 0x27;
2997 case SDLK_QUOTEDBL:
2998 case SDLK_QUOTE: return 0x28;
2999 case SDLK_BACKQUOTE: return 0x29;
3000 case SDLK_LSHIFT: return 0x2a;
3001 case SDLK_BACKSLASH: return 0x2b;
3002 case SDLK_z: return 0x2c;
3003 case SDLK_x: return 0x2d;
3004 case SDLK_c: return 0x2e;
3005 case SDLK_v: return 0x2f;
3006 case SDLK_b: return 0x30;
3007 case SDLK_n: return 0x31;
3008 case SDLK_m: return 0x32;
3009 case SDLK_LESS:
3010 case SDLK_COMMA: return 0x33;
3011 case SDLK_GREATER:
3012 case SDLK_PERIOD: return 0x34;
3013 case SDLK_KP_DIVIDE: /*??*/
3014 case SDLK_QUESTION:
3015 case SDLK_SLASH: return 0x35;
3016 case SDLK_RSHIFT: return 0x36;
3017 case SDLK_KP_MULTIPLY:
3018 case SDLK_PRINT: return 0x37; /* fixme */
3019 case SDLK_LALT: return 0x38;
3020 case SDLK_MODE: /* alt gr*/
3021 case SDLK_RALT: return 0x38 | 0x100;
3022 case SDLK_SPACE: return 0x39;
3023 case SDLK_CAPSLOCK: return 0x3a;
3024 case SDLK_F1: return 0x3b;
3025 case SDLK_F2: return 0x3c;
3026 case SDLK_F3: return 0x3d;
3027 case SDLK_F4: return 0x3e;
3028 case SDLK_F5: return 0x3f;
3029 case SDLK_F6: return 0x40;
3030 case SDLK_F7: return 0x41;
3031 case SDLK_F8: return 0x42;
3032 case SDLK_F9: return 0x43;
3033 case SDLK_F10: return 0x44;
3034 case SDLK_PAUSE: return 0x45; /* not right */
3035 case SDLK_NUMLOCK: return 0x45;
3036 case SDLK_SCROLLOCK: return 0x46;
3037 case SDLK_KP7: return 0x47;
3038 case SDLK_HOME: return 0x47 | 0x100;
3039 case SDLK_KP8: return 0x48;
3040 case SDLK_UP: return 0x48 | 0x100;
3041 case SDLK_KP9: return 0x49;
3042 case SDLK_PAGEUP: return 0x49 | 0x100;
3043 case SDLK_KP_MINUS: return 0x4a;
3044 case SDLK_KP4: return 0x4b;
3045 case SDLK_LEFT: return 0x4b | 0x100;
3046 case SDLK_KP5: return 0x4c;
3047 case SDLK_KP6: return 0x4d;
3048 case SDLK_RIGHT: return 0x4d | 0x100;
3049 case SDLK_KP_PLUS: return 0x4e;
3050 case SDLK_KP1: return 0x4f;
3051 case SDLK_END: return 0x4f | 0x100;
3052 case SDLK_KP2: return 0x50;
3053 case SDLK_DOWN: return 0x50 | 0x100;
3054 case SDLK_KP3: return 0x51;
3055 case SDLK_PAGEDOWN: return 0x51 | 0x100;
3056 case SDLK_KP0: return 0x52;
3057 case SDLK_INSERT: return 0x52 | 0x100;
3058 case SDLK_KP_PERIOD: return 0x53;
3059 case SDLK_DELETE: return 0x53 | 0x100;
3060 case SDLK_SYSREQ: return 0x54;
3061 case SDLK_F11: return 0x57;
3062 case SDLK_F12: return 0x58;
3063 case SDLK_F13: return 0x5b;
3064 case SDLK_LMETA:
3065 case SDLK_LSUPER: return 0x5b | 0x100;
3066 case SDLK_F14: return 0x5c;
3067 case SDLK_RMETA:
3068 case SDLK_RSUPER: return 0x5c | 0x100;
3069 case SDLK_F15: return 0x5d;
3070 case SDLK_MENU: return 0x5d | 0x100;
3071#if 0
3072 case SDLK_CLEAR: return 0x;
3073 case SDLK_KP_EQUALS: return 0x;
3074 case SDLK_COMPOSE: return 0x;
3075 case SDLK_HELP: return 0x;
3076 case SDLK_BREAK: return 0x;
3077 case SDLK_POWER: return 0x;
3078 case SDLK_EURO: return 0x;
3079 case SDLK_UNDO: return 0x;
3080#endif
3081 default:
3082 Log(("Unhandled sdl key event: sym=%d scancode=%#x unicode=%#x\n",
3083 ev->keysym.sym, ev->keysym.scancode, ev->keysym.unicode));
3084 return 0;
3085 }
3086}
3087#endif /* RT_OS_DARWIN */
3088
3089/**
3090 * Converts an SDL keyboard eventcode to a XT scancode.
3091 *
3092 * @returns XT scancode
3093 * @param ev SDL scancode
3094 */
3095static uint16_t Keyevent2Keycode(const SDL_KeyboardEvent *ev)
3096{
3097 // start with the scancode determined by SDL
3098 int keycode = ev->keysym.scancode;
3099
3100#ifdef VBOXSDL_WITH_X11
3101# ifdef VBOX_WITH_SDL13
3102
3103 switch (ev->keysym.sym)
3104 {
3105 case SDLK_ESCAPE: return 0x01;
3106 case SDLK_EXCLAIM:
3107 case SDLK_1: return 0x02;
3108 case SDLK_AT:
3109 case SDLK_2: return 0x03;
3110 case SDLK_HASH:
3111 case SDLK_3: return 0x04;
3112 case SDLK_DOLLAR:
3113 case SDLK_4: return 0x05;
3114 /* % */
3115 case SDLK_5: return 0x06;
3116 case SDLK_CARET:
3117 case SDLK_6: return 0x07;
3118 case SDLK_AMPERSAND:
3119 case SDLK_7: return 0x08;
3120 case SDLK_ASTERISK:
3121 case SDLK_8: return 0x09;
3122 case SDLK_LEFTPAREN:
3123 case SDLK_9: return 0x0a;
3124 case SDLK_RIGHTPAREN:
3125 case SDLK_0: return 0x0b;
3126 case SDLK_UNDERSCORE:
3127 case SDLK_MINUS: return 0x0c;
3128 case SDLK_PLUS: return 0x0d;
3129 case SDLK_BACKSPACE: return 0x0e;
3130 case SDLK_TAB: return 0x0f;
3131 case SDLK_q: return 0x10;
3132 case SDLK_w: return 0x11;
3133 case SDLK_e: return 0x12;
3134 case SDLK_r: return 0x13;
3135 case SDLK_t: return 0x14;
3136 case SDLK_y: return 0x15;
3137 case SDLK_u: return 0x16;
3138 case SDLK_i: return 0x17;
3139 case SDLK_o: return 0x18;
3140 case SDLK_p: return 0x19;
3141 case SDLK_RETURN: return 0x1c;
3142 case SDLK_KP_ENTER: return 0x1c | 0x100;
3143 case SDLK_LCTRL: return 0x1d;
3144 case SDLK_RCTRL: return 0x1d | 0x100;
3145 case SDLK_a: return 0x1e;
3146 case SDLK_s: return 0x1f;
3147 case SDLK_d: return 0x20;
3148 case SDLK_f: return 0x21;
3149 case SDLK_g: return 0x22;
3150 case SDLK_h: return 0x23;
3151 case SDLK_j: return 0x24;
3152 case SDLK_k: return 0x25;
3153 case SDLK_l: return 0x26;
3154 case SDLK_COLON: return 0x27;
3155 case SDLK_QUOTEDBL:
3156 case SDLK_QUOTE: return 0x28;
3157 case SDLK_BACKQUOTE: return 0x29;
3158 case SDLK_LSHIFT: return 0x2a;
3159 case SDLK_z: return 0x2c;
3160 case SDLK_x: return 0x2d;
3161 case SDLK_c: return 0x2e;
3162 case SDLK_v: return 0x2f;
3163 case SDLK_b: return 0x30;
3164 case SDLK_n: return 0x31;
3165 case SDLK_m: return 0x32;
3166 case SDLK_LESS: return 0x33;
3167 case SDLK_GREATER: return 0x34;
3168 case SDLK_KP_DIVIDE: /*??*/
3169 case SDLK_QUESTION: return 0x35;
3170 case SDLK_RSHIFT: return 0x36;
3171 case SDLK_KP_MULTIPLY:
3172 case SDLK_PRINT: return 0x37; /* fixme */
3173 case SDLK_LALT: return 0x38;
3174 case SDLK_MODE: /* alt gr*/
3175 case SDLK_RALT: return 0x38 | 0x100;
3176 case SDLK_SPACE: return 0x39;
3177 case SDLK_CAPSLOCK: return 0x3a;
3178 case SDLK_F1: return 0x3b;
3179 case SDLK_F2: return 0x3c;
3180 case SDLK_F3: return 0x3d;
3181 case SDLK_F4: return 0x3e;
3182 case SDLK_F5: return 0x3f;
3183 case SDLK_F6: return 0x40;
3184 case SDLK_F7: return 0x41;
3185 case SDLK_F8: return 0x42;
3186 case SDLK_F9: return 0x43;
3187 case SDLK_F10: return 0x44;
3188 case SDLK_PAUSE: return 0x45; /* not right */
3189 case SDLK_NUMLOCK: return 0x45;
3190 case SDLK_SCROLLOCK: return 0x46;
3191 case SDLK_KP7: return 0x47;
3192 case SDLK_HOME: return 0x47 | 0x100;
3193 case SDLK_KP8: return 0x48;
3194 case SDLK_UP: return 0x48 | 0x100;
3195 case SDLK_KP9: return 0x49;
3196 case SDLK_PAGEUP: return 0x49 | 0x100;
3197 case SDLK_KP_MINUS: return 0x4a;
3198 case SDLK_KP4: return 0x4b;
3199 case SDLK_LEFT: return 0x4b | 0x100;
3200 case SDLK_KP5: return 0x4c;
3201 case SDLK_KP6: return 0x4d;
3202 case SDLK_RIGHT: return 0x4d | 0x100;
3203 case SDLK_KP_PLUS: return 0x4e;
3204 case SDLK_KP1: return 0x4f;
3205 case SDLK_END: return 0x4f | 0x100;
3206 case SDLK_KP2: return 0x50;
3207 case SDLK_DOWN: return 0x50 | 0x100;
3208 case SDLK_KP3: return 0x51;
3209 case SDLK_PAGEDOWN: return 0x51 | 0x100;
3210 case SDLK_KP0: return 0x52;
3211 case SDLK_INSERT: return 0x52 | 0x100;
3212 case SDLK_KP_PERIOD: return 0x53;
3213 case SDLK_DELETE: return 0x53 | 0x100;
3214 case SDLK_SYSREQ: return 0x54;
3215 case SDLK_F11: return 0x57;
3216 case SDLK_F12: return 0x58;
3217 case SDLK_F13: return 0x5b;
3218 case SDLK_F14: return 0x5c;
3219 case SDLK_F15: return 0x5d;
3220 case SDLK_MENU: return 0x5d | 0x100;
3221 default:
3222 return 0;
3223 }
3224# else
3225 keycode = X11DRV_KeyEvent(gSdlInfo.info.x11.display, keycode);
3226# endif
3227#elif defined(RT_OS_DARWIN)
3228 /* This is derived partially from SDL_QuartzKeys.h and partially from testing. */
3229 static const uint16_t s_aMacToSet1[] =
3230 {
3231 /* set-1 SDL_QuartzKeys.h */
3232 0x1e, /* QZ_a 0x00 */
3233 0x1f, /* QZ_s 0x01 */
3234 0x20, /* QZ_d 0x02 */
3235 0x21, /* QZ_f 0x03 */
3236 0x23, /* QZ_h 0x04 */
3237 0x22, /* QZ_g 0x05 */
3238 0x2c, /* QZ_z 0x06 */
3239 0x2d, /* QZ_x 0x07 */
3240 0x2e, /* QZ_c 0x08 */
3241 0x2f, /* QZ_v 0x09 */
3242 0x56, /* between lshift and z. 'INT 1'? */
3243 0x30, /* QZ_b 0x0B */
3244 0x10, /* QZ_q 0x0C */
3245 0x11, /* QZ_w 0x0D */
3246 0x12, /* QZ_e 0x0E */
3247 0x13, /* QZ_r 0x0F */
3248 0x15, /* QZ_y 0x10 */
3249 0x14, /* QZ_t 0x11 */
3250 0x02, /* QZ_1 0x12 */
3251 0x03, /* QZ_2 0x13 */
3252 0x04, /* QZ_3 0x14 */
3253 0x05, /* QZ_4 0x15 */
3254 0x07, /* QZ_6 0x16 */
3255 0x06, /* QZ_5 0x17 */
3256 0x0d, /* QZ_EQUALS 0x18 */
3257 0x0a, /* QZ_9 0x19 */
3258 0x08, /* QZ_7 0x1A */
3259 0x0c, /* QZ_MINUS 0x1B */
3260 0x09, /* QZ_8 0x1C */
3261 0x0b, /* QZ_0 0x1D */
3262 0x1b, /* QZ_RIGHTBRACKET 0x1E */
3263 0x18, /* QZ_o 0x1F */
3264 0x16, /* QZ_u 0x20 */
3265 0x1a, /* QZ_LEFTBRACKET 0x21 */
3266 0x17, /* QZ_i 0x22 */
3267 0x19, /* QZ_p 0x23 */
3268 0x1c, /* QZ_RETURN 0x24 */
3269 0x26, /* QZ_l 0x25 */
3270 0x24, /* QZ_j 0x26 */
3271 0x28, /* QZ_QUOTE 0x27 */
3272 0x25, /* QZ_k 0x28 */
3273 0x27, /* QZ_SEMICOLON 0x29 */
3274 0x2b, /* QZ_BACKSLASH 0x2A */
3275 0x33, /* QZ_COMMA 0x2B */
3276 0x35, /* QZ_SLASH 0x2C */
3277 0x31, /* QZ_n 0x2D */
3278 0x32, /* QZ_m 0x2E */
3279 0x34, /* QZ_PERIOD 0x2F */
3280 0x0f, /* QZ_TAB 0x30 */
3281 0x39, /* QZ_SPACE 0x31 */
3282 0x29, /* QZ_BACKQUOTE 0x32 */
3283 0x0e, /* QZ_BACKSPACE 0x33 */
3284 0x9c, /* QZ_IBOOK_ENTER 0x34 */
3285 0x01, /* QZ_ESCAPE 0x35 */
3286 0x5c|0x100, /* QZ_RMETA 0x36 */
3287 0x5b|0x100, /* QZ_LMETA 0x37 */
3288 0x2a, /* QZ_LSHIFT 0x38 */
3289 0x3a, /* QZ_CAPSLOCK 0x39 */
3290 0x38, /* QZ_LALT 0x3A */
3291 0x1d, /* QZ_LCTRL 0x3B */
3292 0x36, /* QZ_RSHIFT 0x3C */
3293 0x38|0x100, /* QZ_RALT 0x3D */
3294 0x1d|0x100, /* QZ_RCTRL 0x3E */
3295 0, /* */
3296 0, /* */
3297 0x53, /* QZ_KP_PERIOD 0x41 */
3298 0, /* */
3299 0x37, /* QZ_KP_MULTIPLY 0x43 */
3300 0, /* */
3301 0x4e, /* QZ_KP_PLUS 0x45 */
3302 0, /* */
3303 0x45, /* QZ_NUMLOCK 0x47 */
3304 0, /* */
3305 0, /* */
3306 0, /* */
3307 0x35|0x100, /* QZ_KP_DIVIDE 0x4B */
3308 0x1c|0x100, /* QZ_KP_ENTER 0x4C */
3309 0, /* */
3310 0x4a, /* QZ_KP_MINUS 0x4E */
3311 0, /* */
3312 0, /* */
3313 0x0d/*?*/, /* QZ_KP_EQUALS 0x51 */
3314 0x52, /* QZ_KP0 0x52 */
3315 0x4f, /* QZ_KP1 0x53 */
3316 0x50, /* QZ_KP2 0x54 */
3317 0x51, /* QZ_KP3 0x55 */
3318 0x4b, /* QZ_KP4 0x56 */
3319 0x4c, /* QZ_KP5 0x57 */
3320 0x4d, /* QZ_KP6 0x58 */
3321 0x47, /* QZ_KP7 0x59 */
3322 0, /* */
3323 0x48, /* QZ_KP8 0x5B */
3324 0x49, /* QZ_KP9 0x5C */
3325 0, /* */
3326 0, /* */
3327 0, /* */
3328 0x3f, /* QZ_F5 0x60 */
3329 0x40, /* QZ_F6 0x61 */
3330 0x41, /* QZ_F7 0x62 */
3331 0x3d, /* QZ_F3 0x63 */
3332 0x42, /* QZ_F8 0x64 */
3333 0x43, /* QZ_F9 0x65 */
3334 0, /* */
3335 0x57, /* QZ_F11 0x67 */
3336 0, /* */
3337 0x37|0x100, /* QZ_PRINT / F13 0x69 */
3338 0x63, /* QZ_F16 0x6A */
3339 0x46, /* QZ_SCROLLOCK 0x6B */
3340 0, /* */
3341 0x44, /* QZ_F10 0x6D */
3342 0x5d|0x100, /* */
3343 0x58, /* QZ_F12 0x6F */
3344 0, /* */
3345 0/* 0xe1,0x1d,0x45*/, /* QZ_PAUSE 0x71 */
3346 0x52|0x100, /* QZ_INSERT / HELP 0x72 */
3347 0x47|0x100, /* QZ_HOME 0x73 */
3348 0x49|0x100, /* QZ_PAGEUP 0x74 */
3349 0x53|0x100, /* QZ_DELETE 0x75 */
3350 0x3e, /* QZ_F4 0x76 */
3351 0x4f|0x100, /* QZ_END 0x77 */
3352 0x3c, /* QZ_F2 0x78 */
3353 0x51|0x100, /* QZ_PAGEDOWN 0x79 */
3354 0x3b, /* QZ_F1 0x7A */
3355 0x4b|0x100, /* QZ_LEFT 0x7B */
3356 0x4d|0x100, /* QZ_RIGHT 0x7C */
3357 0x50|0x100, /* QZ_DOWN 0x7D */
3358 0x48|0x100, /* QZ_UP 0x7E */
3359 0x5e|0x100, /* QZ_POWER 0x7F */ /* have different break key! */
3360 };
3361
3362 if (keycode == 0)
3363 {
3364 /* This could be a modifier or it could be 'a'. */
3365 switch (ev->keysym.sym)
3366 {
3367 case SDLK_LSHIFT: keycode = 0x2a; break;
3368 case SDLK_RSHIFT: keycode = 0x36; break;
3369 case SDLK_LCTRL: keycode = 0x1d; break;
3370 case SDLK_RCTRL: keycode = 0x1d | 0x100; break;
3371 case SDLK_LALT: keycode = 0x38; break;
3372 case SDLK_MODE: /* alt gr */
3373 case SDLK_RALT: keycode = 0x38 | 0x100; break;
3374 case SDLK_RMETA:
3375 case SDLK_RSUPER: keycode = 0x5c | 0x100; break;
3376 case SDLK_LMETA:
3377 case SDLK_LSUPER: keycode = 0x5b | 0x100; break;
3378 /* Assumes normal key. */
3379 default: keycode = s_aMacToSet1[keycode]; break;
3380 }
3381 }
3382 else
3383 {
3384 if ((unsigned)keycode < RT_ELEMENTS(s_aMacToSet1))
3385 keycode = s_aMacToSet1[keycode];
3386 else
3387 keycode = 0;
3388 if (!keycode)
3389 {
3390#ifdef DEBUG_bird
3391 RTPrintf("Untranslated: keycode=%#x (%d)\n", keycode, keycode);
3392#endif
3393 keycode = Keyevent2KeycodeFallback(ev);
3394 }
3395 }
3396#ifdef DEBUG_bird
3397 RTPrintf("scancode=%#x -> %#x\n", ev->keysym.scancode, keycode);
3398#endif
3399
3400#elif RT_OS_OS2
3401 keycode = Keyevent2KeycodeFallback(ev);
3402#endif /* RT_OS_DARWIN */
3403 return keycode;
3404}
3405
3406/**
3407 * Releases any modifier keys that are currently in pressed state.
3408 */
3409static void ResetKeys(void)
3410{
3411 int i;
3412
3413 if (!gpKeyboard)
3414 return;
3415
3416 for(i = 0; i < 256; i++)
3417 {
3418 if (gaModifiersState[i])
3419 {
3420 if (i & 0x80)
3421 gpKeyboard->PutScancode(0xe0);
3422 gpKeyboard->PutScancode(i | 0x80);
3423 gaModifiersState[i] = 0;
3424 }
3425 }
3426}
3427
3428/**
3429 * Keyboard event handler.
3430 *
3431 * @param ev SDL keyboard event.
3432 */
3433static void ProcessKey(SDL_KeyboardEvent *ev)
3434{
3435#if (defined(DEBUG) || defined(VBOX_WITH_STATISTICS)) && !defined(VBOX_WITH_SDL13)
3436 if (gpMachineDebugger && ev->type == SDL_KEYDOWN)
3437 {
3438 // first handle the debugger hotkeys
3439 uint8_t *keystate = SDL_GetKeyState(NULL);
3440#if 0
3441 // CTRL+ALT+Fn is not free on Linux hosts with Xorg ..
3442 if (keystate[SDLK_LALT] && !keystate[SDLK_LCTRL])
3443#else
3444 if (keystate[SDLK_LALT] && keystate[SDLK_LCTRL])
3445#endif
3446 {
3447 switch (ev->keysym.sym)
3448 {
3449 // pressing CTRL+ALT+F11 dumps the statistics counter
3450 case SDLK_F12:
3451 RTPrintf("ResetStats\n"); /* Visual feedback in console window */
3452 gpMachineDebugger->ResetStats(NULL);
3453 break;
3454 // pressing CTRL+ALT+F12 resets all statistics counter
3455 case SDLK_F11:
3456 gpMachineDebugger->DumpStats(NULL);
3457 RTPrintf("DumpStats\n"); /* Vistual feedback in console window */
3458 break;
3459 default:
3460 break;
3461 }
3462 }
3463#if 1
3464 else if (keystate[SDLK_LALT] && !keystate[SDLK_LCTRL])
3465 {
3466 switch (ev->keysym.sym)
3467 {
3468 // pressing Alt-F12 toggles the supervisor recompiler
3469 case SDLK_F12:
3470 {
3471 BOOL recompileSupervisor;
3472 gpMachineDebugger->COMGETTER(RecompileSupervisor)(&recompileSupervisor);
3473 gpMachineDebugger->COMSETTER(RecompileSupervisor)(!recompileSupervisor);
3474 break;
3475 }
3476 // pressing Alt-F11 toggles the user recompiler
3477 case SDLK_F11:
3478 {
3479 BOOL recompileUser;
3480 gpMachineDebugger->COMGETTER(RecompileUser)(&recompileUser);
3481 gpMachineDebugger->COMSETTER(RecompileUser)(!recompileUser);
3482 break;
3483 }
3484 // pressing Alt-F10 toggles the patch manager
3485 case SDLK_F10:
3486 {
3487 BOOL patmEnabled;
3488 gpMachineDebugger->COMGETTER(PATMEnabled)(&patmEnabled);
3489 gpMachineDebugger->COMSETTER(PATMEnabled)(!patmEnabled);
3490 break;
3491 }
3492 // pressing Alt-F9 toggles CSAM
3493 case SDLK_F9:
3494 {
3495 BOOL csamEnabled;
3496 gpMachineDebugger->COMGETTER(CSAMEnabled)(&csamEnabled);
3497 gpMachineDebugger->COMSETTER(CSAMEnabled)(!csamEnabled);
3498 break;
3499 }
3500 // pressing Alt-F8 toggles singlestepping mode
3501 case SDLK_F8:
3502 {
3503 BOOL singlestepEnabled;
3504 gpMachineDebugger->COMGETTER(Singlestep)(&singlestepEnabled);
3505 gpMachineDebugger->COMSETTER(Singlestep)(!singlestepEnabled);
3506 break;
3507 }
3508 default:
3509 break;
3510 }
3511 }
3512#endif
3513 // pressing Ctrl-F12 toggles the logger
3514 else if ((keystate[SDLK_RCTRL] || keystate[SDLK_LCTRL]) && ev->keysym.sym == SDLK_F12)
3515 {
3516 BOOL logEnabled = TRUE;
3517 gpMachineDebugger->COMGETTER(LogEnabled)(&logEnabled);
3518 gpMachineDebugger->COMSETTER(LogEnabled)(!logEnabled);
3519#ifdef DEBUG_bird
3520 return;
3521#endif
3522 }
3523 // pressing F12 sets a logmark
3524 else if (ev->keysym.sym == SDLK_F12)
3525 {
3526 RTLogPrintf("****** LOGGING MARK ******\n");
3527 RTLogFlush(NULL);
3528 }
3529 // now update the titlebar flags
3530 UpdateTitlebar(TITLEBAR_NORMAL);
3531 }
3532#endif // DEBUG || VBOX_WITH_STATISTICS
3533
3534 // the pause key is the weirdest, needs special handling
3535 if (ev->keysym.sym == SDLK_PAUSE)
3536 {
3537 int v = 0;
3538 if (ev->type == SDL_KEYUP)
3539 v |= 0x80;
3540 gpKeyboard->PutScancode(0xe1);
3541 gpKeyboard->PutScancode(0x1d | v);
3542 gpKeyboard->PutScancode(0x45 | v);
3543 return;
3544 }
3545
3546 /*
3547 * Perform SDL key event to scancode conversion
3548 */
3549 int keycode = Keyevent2Keycode(ev);
3550
3551 switch(keycode)
3552 {
3553 case 0x00:
3554 {
3555 /* sent when leaving window: reset the modifiers state */
3556 ResetKeys();
3557 return;
3558 }
3559
3560 case 0x2a: /* Left Shift */
3561 case 0x36: /* Right Shift */
3562 case 0x1d: /* Left CTRL */
3563 case 0x1d|0x100: /* Right CTRL */
3564 case 0x38: /* Left ALT */
3565 case 0x38|0x100: /* Right ALT */
3566 {
3567 if (ev->type == SDL_KEYUP)
3568 gaModifiersState[keycode & ~0x100] = 0;
3569 else
3570 gaModifiersState[keycode & ~0x100] = 1;
3571 break;
3572 }
3573
3574 case 0x45: /* Num Lock */
3575 case 0x3a: /* Caps Lock */
3576 {
3577 /*
3578 * SDL generates a KEYDOWN event if the lock key is active and a KEYUP event
3579 * if the lock key is inactive. See SDL_DISABLE_LOCK_KEYS.
3580 */
3581 if (ev->type == SDL_KEYDOWN || ev->type == SDL_KEYUP)
3582 {
3583 gpKeyboard->PutScancode(keycode);
3584 gpKeyboard->PutScancode(keycode | 0x80);
3585 }
3586 return;
3587 }
3588 }
3589
3590 if (ev->type != SDL_KEYDOWN)
3591 {
3592 /*
3593 * Some keyboards (e.g. the one of mine T60) don't send a NumLock scan code on every
3594 * press of the key. Both the guest and the host should agree on the NumLock state.
3595 * If they differ, we try to alter the guest NumLock state by sending the NumLock key
3596 * scancode. We will get a feedback through the KBD_CMD_SET_LEDS command if the guest
3597 * tries to set/clear the NumLock LED. If a (silly) guest doesn't change the LED, don't
3598 * bother him with NumLock scancodes. At least our BIOS, Linux and Windows handle the
3599 * NumLock LED well.
3600 */
3601 if ( gcGuestNumLockAdaptions
3602 && (gfGuestNumLockPressed ^ !!(SDL_GetModState() & KMOD_NUM)))
3603 {
3604 gcGuestNumLockAdaptions--;
3605 gpKeyboard->PutScancode(0x45);
3606 gpKeyboard->PutScancode(0x45 | 0x80);
3607 }
3608 if ( gcGuestCapsLockAdaptions
3609 && (gfGuestCapsLockPressed ^ !!(SDL_GetModState() & KMOD_CAPS)))
3610 {
3611 gcGuestCapsLockAdaptions--;
3612 gpKeyboard->PutScancode(0x3a);
3613 gpKeyboard->PutScancode(0x3a | 0x80);
3614 }
3615 }
3616
3617 /*
3618 * Now we send the event. Apply extended and release prefixes.
3619 */
3620 if (keycode & 0x100)
3621 gpKeyboard->PutScancode(0xe0);
3622
3623 gpKeyboard->PutScancode(ev->type == SDL_KEYUP ? (keycode & 0x7f) | 0x80
3624 : (keycode & 0x7f));
3625}
3626
3627#ifdef RT_OS_DARWIN
3628#include <Carbon/Carbon.h>
3629RT_C_DECLS_BEGIN
3630/* Private interface in 10.3 and later. */
3631typedef int CGSConnection;
3632typedef enum
3633{
3634 kCGSGlobalHotKeyEnable = 0,
3635 kCGSGlobalHotKeyDisable,
3636 kCGSGlobalHotKeyInvalid = -1 /* bird */
3637} CGSGlobalHotKeyOperatingMode;
3638extern CGSConnection _CGSDefaultConnection(void);
3639extern CGError CGSGetGlobalHotKeyOperatingMode(CGSConnection Connection, CGSGlobalHotKeyOperatingMode *enmMode);
3640extern CGError CGSSetGlobalHotKeyOperatingMode(CGSConnection Connection, CGSGlobalHotKeyOperatingMode enmMode);
3641RT_C_DECLS_END
3642
3643/** Keeping track of whether we disabled the hotkeys or not. */
3644static bool g_fHotKeysDisabled = false;
3645/** Whether we've connected or not. */
3646static bool g_fConnectedToCGS = false;
3647/** Cached connection. */
3648static CGSConnection g_CGSConnection;
3649
3650/**
3651 * Disables or enabled global hot keys.
3652 */
3653static void DisableGlobalHotKeys(bool fDisable)
3654{
3655 if (!g_fConnectedToCGS)
3656 {
3657 g_CGSConnection = _CGSDefaultConnection();
3658 g_fConnectedToCGS = true;
3659 }
3660
3661 /* get current mode. */
3662 CGSGlobalHotKeyOperatingMode enmMode = kCGSGlobalHotKeyInvalid;
3663 CGSGetGlobalHotKeyOperatingMode(g_CGSConnection, &enmMode);
3664
3665 /* calc new mode. */
3666 if (fDisable)
3667 {
3668 if (enmMode != kCGSGlobalHotKeyEnable)
3669 return;
3670 enmMode = kCGSGlobalHotKeyDisable;
3671 }
3672 else
3673 {
3674 if ( enmMode != kCGSGlobalHotKeyDisable
3675 /*|| !g_fHotKeysDisabled*/)
3676 return;
3677 enmMode = kCGSGlobalHotKeyEnable;
3678 }
3679
3680 /* try set it and check the actual result. */
3681 CGSSetGlobalHotKeyOperatingMode(g_CGSConnection, enmMode);
3682 CGSGlobalHotKeyOperatingMode enmNewMode = kCGSGlobalHotKeyInvalid;
3683 CGSGetGlobalHotKeyOperatingMode(g_CGSConnection, &enmNewMode);
3684 if (enmNewMode == enmMode)
3685 g_fHotKeysDisabled = enmMode == kCGSGlobalHotKeyDisable;
3686}
3687#endif /* RT_OS_DARWIN */
3688
3689/**
3690 * Start grabbing the mouse.
3691 */
3692static void InputGrabStart(void)
3693{
3694#ifdef RT_OS_DARWIN
3695 DisableGlobalHotKeys(true);
3696#endif
3697 if (!gfGuestNeedsHostCursor && gfRelativeMouseGuest)
3698 SDL_ShowCursor(SDL_DISABLE);
3699 SDL_WM_GrabInput(SDL_GRAB_ON);
3700 // dummy read to avoid moving the mouse
3701 SDL_GetRelativeMouseState(
3702#ifdef VBOX_WITH_SDL13
3703 0,
3704#endif
3705 NULL, NULL);
3706 gfGrabbed = TRUE;
3707 UpdateTitlebar(TITLEBAR_NORMAL);
3708}
3709
3710/**
3711 * End mouse grabbing.
3712 */
3713static void InputGrabEnd(void)
3714{
3715 SDL_WM_GrabInput(SDL_GRAB_OFF);
3716 if (!gfGuestNeedsHostCursor && gfRelativeMouseGuest)
3717 SDL_ShowCursor(SDL_ENABLE);
3718#ifdef RT_OS_DARWIN
3719 DisableGlobalHotKeys(false);
3720#endif
3721 gfGrabbed = FALSE;
3722 UpdateTitlebar(TITLEBAR_NORMAL);
3723}
3724
3725/**
3726 * Query mouse position and button state from SDL and send to the VM
3727 *
3728 * @param dz Relative mouse wheel movement
3729 */
3730static void SendMouseEvent(VBoxSDLFB *fb, int dz, int down, int button)
3731{
3732 int x, y, state, buttons;
3733 bool abs;
3734
3735#ifdef VBOX_WITH_SDL13
3736 if (!fb)
3737 {
3738 SDL_GetMouseState(0, &x, &y);
3739 RTPrintf("MouseEvent: Cannot find fb mouse = %d,%d\n", x, y);
3740 return;
3741 }
3742#else
3743 AssertRelease(fb != NULL);
3744#endif
3745
3746 /*
3747 * If supported and we're not in grabbed mode, we'll use the absolute mouse.
3748 * If we are in grabbed mode and the guest is not able to draw the mouse cursor
3749 * itself, or can't handle relative reporting, we have to use absolute
3750 * coordinates, otherwise the host cursor and
3751 * the coordinates the guest thinks the mouse is at could get out-of-sync. From
3752 * the SDL mailing list:
3753 *
3754 * "The event processing is usually asynchronous and so somewhat delayed, and
3755 * SDL_GetMouseState is returning the immediate mouse state. So at the time you
3756 * call SDL_GetMouseState, the "button" is already up."
3757 */
3758 abs = (UseAbsoluteMouse() && !gfGrabbed)
3759 || gfGuestNeedsHostCursor
3760 || !gfRelativeMouseGuest;
3761
3762 /* only used if abs == TRUE */
3763 int xOrigin = fb->getOriginX();
3764 int yOrigin = fb->getOriginY();
3765 int xMin = fb->getXOffset() + xOrigin;
3766 int yMin = fb->getYOffset() + yOrigin;
3767 int xMax = xMin + (int)fb->getGuestXRes();
3768 int yMax = yMin + (int)fb->getGuestYRes();
3769
3770 state = abs ? SDL_GetMouseState(
3771#ifdef VBOX_WITH_SDL13
3772 0,
3773#endif
3774 &x, &y)
3775 : SDL_GetRelativeMouseState(
3776#ifdef VBOX_WITH_SDL13
3777 0,
3778#endif
3779 &x, &y);
3780
3781 /*
3782 * process buttons
3783 */
3784 buttons = 0;
3785 if (state & SDL_BUTTON(SDL_BUTTON_LEFT))
3786 buttons |= MouseButtonState_LeftButton;
3787 if (state & SDL_BUTTON(SDL_BUTTON_RIGHT))
3788 buttons |= MouseButtonState_RightButton;
3789 if (state & SDL_BUTTON(SDL_BUTTON_MIDDLE))
3790 buttons |= MouseButtonState_MiddleButton;
3791
3792 if (abs)
3793 {
3794 x += xOrigin;
3795 y += yOrigin;
3796
3797 /*
3798 * Check if the mouse event is inside the guest area. This solves the
3799 * following problem: Some guests switch off the VBox hardware mouse
3800 * cursor and draw the mouse cursor itself instead. Moving the mouse
3801 * outside the guest area then leads to annoying mouse hangs if we
3802 * don't pass mouse motion events into the guest.
3803 */
3804 if (x < xMin || y < yMin || x > xMax || y > yMax)
3805 {
3806 /*
3807 * Cursor outside of valid guest area (outside window or in secure
3808 * label area. Don't allow any mouse button press.
3809 */
3810 button = 0;
3811
3812 /*
3813 * Release any pressed button.
3814 */
3815#if 0
3816 /* disabled on customers request */
3817 buttons &= ~(MouseButtonState_LeftButton |
3818 MouseButtonState_MiddleButton |
3819 MouseButtonState_RightButton);
3820#endif
3821
3822 /*
3823 * Prevent negative coordinates.
3824 */
3825 if (x < xMin) x = xMin;
3826 if (x > xMax) x = xMax;
3827 if (y < yMin) y = yMin;
3828 if (y > yMax) y = yMax;
3829
3830 if (!gpOffCursor)
3831 {
3832 gpOffCursor = SDL_GetCursor(); /* Cursor image */
3833 gfOffCursorActive = SDL_ShowCursor(-1); /* enabled / disabled */
3834 SDL_SetCursor(gpDefaultCursor);
3835 SDL_ShowCursor(SDL_ENABLE);
3836 }
3837 }
3838 else
3839 {
3840 if (gpOffCursor)
3841 {
3842 /*
3843 * We just entered the valid guest area. Restore the guest mouse
3844 * cursor.
3845 */
3846 SDL_SetCursor(gpOffCursor);
3847 SDL_ShowCursor(gfOffCursorActive ? SDL_ENABLE : SDL_DISABLE);
3848 gpOffCursor = NULL;
3849 }
3850 }
3851 }
3852
3853 /*
3854 * Button was pressed but that press is not reflected in the button state?
3855 */
3856 if (down && !(state & SDL_BUTTON(button)))
3857 {
3858 /*
3859 * It can happen that a mouse up event follows a mouse down event immediately
3860 * and we see the events when the bit in the button state is already cleared
3861 * again. In that case we simulate the mouse down event.
3862 */
3863 int tmp_button = 0;
3864 switch (button)
3865 {
3866 case SDL_BUTTON_LEFT: tmp_button = MouseButtonState_LeftButton; break;
3867 case SDL_BUTTON_MIDDLE: tmp_button = MouseButtonState_MiddleButton; break;
3868 case SDL_BUTTON_RIGHT: tmp_button = MouseButtonState_RightButton; break;
3869 }
3870
3871 if (abs)
3872 {
3873 /**
3874 * @todo
3875 * PutMouseEventAbsolute() expects x and y starting from 1,1.
3876 * should we do the increment internally in PutMouseEventAbsolute()
3877 * or state it in PutMouseEventAbsolute() docs?
3878 */
3879 gpMouse->PutMouseEventAbsolute(x + 1 - xMin + xOrigin,
3880 y + 1 - yMin + yOrigin,
3881 dz, 0 /* horizontal scroll wheel */,
3882 buttons | tmp_button);
3883 }
3884 else
3885 {
3886 gpMouse->PutMouseEvent(0, 0, dz,
3887 0 /* horizontal scroll wheel */,
3888 buttons | tmp_button);
3889 }
3890 }
3891
3892 // now send the mouse event
3893 if (abs)
3894 {
3895 /**
3896 * @todo
3897 * PutMouseEventAbsolute() expects x and y starting from 1,1.
3898 * should we do the increment internally in PutMouseEventAbsolute()
3899 * or state it in PutMouseEventAbsolute() docs?
3900 */
3901 gpMouse->PutMouseEventAbsolute(x + 1 - xMin + xOrigin,
3902 y + 1 - yMin + yOrigin,
3903 dz, 0 /* Horizontal wheel */, buttons);
3904 }
3905 else
3906 {
3907 gpMouse->PutMouseEvent(x, y, dz, 0 /* Horizontal wheel */, buttons);
3908 }
3909}
3910
3911/**
3912 * Resets the VM
3913 */
3914void ResetVM(void)
3915{
3916 if (gpConsole)
3917 gpConsole->Reset();
3918}
3919
3920/**
3921 * Initiates a saved state and updates the titlebar with progress information
3922 */
3923void SaveState(void)
3924{
3925 ResetKeys();
3926 RTThreadYield();
3927 if (gfGrabbed)
3928 InputGrabEnd();
3929 RTThreadYield();
3930 UpdateTitlebar(TITLEBAR_SAVE);
3931 gpProgress = NULL;
3932 HRESULT rc = gpConsole->SaveState(gpProgress.asOutParam());
3933 if (FAILED(rc))
3934 {
3935 RTPrintf("Error saving state! rc = 0x%x\n", rc);
3936 return;
3937 }
3938 Assert(gpProgress);
3939
3940 /*
3941 * Wait for the operation to be completed and work
3942 * the title bar in the mean while.
3943 */
3944 ULONG cPercent = 0;
3945#ifndef RT_OS_DARWIN /* don't break the other guys yet. */
3946 for (;;)
3947 {
3948 BOOL fCompleted = false;
3949 rc = gpProgress->COMGETTER(Completed)(&fCompleted);
3950 if (FAILED(rc) || fCompleted)
3951 break;
3952 ULONG cPercentNow;
3953 rc = gpProgress->COMGETTER(Percent)(&cPercentNow);
3954 if (FAILED(rc))
3955 break;
3956 if (cPercentNow != cPercent)
3957 {
3958 UpdateTitlebar(TITLEBAR_SAVE, cPercent);
3959 cPercent = cPercentNow;
3960 }
3961
3962 /* wait */
3963 rc = gpProgress->WaitForCompletion(100);
3964 if (FAILED(rc))
3965 break;
3966 /// @todo process gui events.
3967 }
3968
3969#else /* new loop which processes GUI events while saving. */
3970
3971 /* start regular timer so we don't starve in the event loop */
3972 SDL_TimerID sdlTimer;
3973 sdlTimer = SDL_AddTimer(100, StartupTimer, NULL);
3974
3975 for (;;)
3976 {
3977 /*
3978 * Check for completion.
3979 */
3980 BOOL fCompleted = false;
3981 rc = gpProgress->COMGETTER(Completed)(&fCompleted);
3982 if (FAILED(rc) || fCompleted)
3983 break;
3984 ULONG cPercentNow;
3985 rc = gpProgress->COMGETTER(Percent)(&cPercentNow);
3986 if (FAILED(rc))
3987 break;
3988 if (cPercentNow != cPercent)
3989 {
3990 UpdateTitlebar(TITLEBAR_SAVE, cPercent);
3991 cPercent = cPercentNow;
3992 }
3993
3994 /*
3995 * Wait for and process GUI a event.
3996 * This is necessary for XPCOM IPC and for updating the
3997 * title bar on the Mac.
3998 */
3999 SDL_Event event;
4000 if (WaitSDLEvent(&event))
4001 {
4002 switch (event.type)
4003 {
4004 /*
4005 * Timer event preventing us from getting stuck.
4006 */
4007 case SDL_USER_EVENT_TIMER:
4008 break;
4009
4010#ifdef USE_XPCOM_QUEUE_THREAD
4011 /*
4012 * User specific XPCOM event queue event
4013 */
4014 case SDL_USER_EVENT_XPCOM_EVENTQUEUE:
4015 {
4016 LogFlow(("SDL_USER_EVENT_XPCOM_EVENTQUEUE: processing XPCOM event queue...\n"));
4017 eventQ->ProcessPendingEvents();
4018 signalXPCOMEventQueueThread();
4019 break;
4020 }
4021#endif /* USE_XPCOM_QUEUE_THREAD */
4022
4023
4024 /*
4025 * Ignore all other events.
4026 */
4027 case SDL_USER_EVENT_RESIZE:
4028 case SDL_USER_EVENT_TERMINATE:
4029 default:
4030 break;
4031 }
4032 }
4033 }
4034
4035 /* kill the timer */
4036 SDL_RemoveTimer(sdlTimer);
4037 sdlTimer = 0;
4038
4039#endif /* RT_OS_DARWIN */
4040
4041 /*
4042 * What's the result of the operation?
4043 */
4044 LONG lrc;
4045 rc = gpProgress->COMGETTER(ResultCode)(&lrc);
4046 if (FAILED(rc))
4047 lrc = ~0;
4048 if (!lrc)
4049 {
4050 UpdateTitlebar(TITLEBAR_SAVE, 100);
4051 RTThreadYield();
4052 RTPrintf("Saved the state successfully.\n");
4053 }
4054 else
4055 RTPrintf("Error saving state, lrc=%d (%#x)\n", lrc, lrc);
4056}
4057
4058/**
4059 * Build the titlebar string
4060 */
4061static void UpdateTitlebar(TitlebarMode mode, uint32_t u32User)
4062{
4063 static char szTitle[1024] = {0};
4064
4065 /* back up current title */
4066 char szPrevTitle[1024];
4067 strcpy(szPrevTitle, szTitle);
4068
4069 Bstr bstrName;
4070 gpMachine->COMGETTER(Name)(bstrName.asOutParam());
4071
4072 RTStrPrintf(szTitle, sizeof(szTitle), "%s - " VBOX_PRODUCT,
4073 !bstrName.isEmpty() ? Utf8Str(bstrName).c_str() : "<noname>");
4074
4075 /* which mode are we in? */
4076 switch (mode)
4077 {
4078 case TITLEBAR_NORMAL:
4079 {
4080 MachineState_T machineState;
4081 gpMachine->COMGETTER(State)(&machineState);
4082 if (machineState == MachineState_Paused)
4083 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle), " - [Paused]");
4084
4085 if (gfGrabbed)
4086 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle), " - [Input captured]");
4087
4088#if defined(DEBUG) || defined(VBOX_WITH_STATISTICS)
4089 // do we have a debugger interface
4090 if (gpMachineDebugger)
4091 {
4092 // query the machine state
4093 BOOL recompileSupervisor = FALSE;
4094 BOOL recompileUser = FALSE;
4095 BOOL patmEnabled = FALSE;
4096 BOOL csamEnabled = FALSE;
4097 BOOL singlestepEnabled = FALSE;
4098 BOOL logEnabled = FALSE;
4099 BOOL hwVirtEnabled = FALSE;
4100 ULONG virtualTimeRate = 100;
4101 gpMachineDebugger->COMGETTER(RecompileSupervisor)(&recompileSupervisor);
4102 gpMachineDebugger->COMGETTER(RecompileUser)(&recompileUser);
4103 gpMachineDebugger->COMGETTER(PATMEnabled)(&patmEnabled);
4104 gpMachineDebugger->COMGETTER(CSAMEnabled)(&csamEnabled);
4105 gpMachineDebugger->COMGETTER(LogEnabled)(&logEnabled);
4106 gpMachineDebugger->COMGETTER(Singlestep)(&singlestepEnabled);
4107 gpMachineDebugger->COMGETTER(HWVirtExEnabled)(&hwVirtEnabled);
4108 gpMachineDebugger->COMGETTER(VirtualTimeRate)(&virtualTimeRate);
4109 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4110 " [STEP=%d CS=%d PAT=%d RR0=%d RR3=%d LOG=%d HWVirt=%d",
4111 singlestepEnabled == TRUE, csamEnabled == TRUE, patmEnabled == TRUE,
4112 recompileSupervisor == FALSE, recompileUser == FALSE,
4113 logEnabled == TRUE, hwVirtEnabled == TRUE);
4114 char *psz = strchr(szTitle, '\0');
4115 if (virtualTimeRate != 100)
4116 RTStrPrintf(psz, &szTitle[sizeof(szTitle)] - psz, " WD=%d%%]", virtualTimeRate);
4117 else
4118 RTStrPrintf(psz, &szTitle[sizeof(szTitle)] - psz, "]");
4119 }
4120#endif /* DEBUG || VBOX_WITH_STATISTICS */
4121 break;
4122 }
4123
4124 case TITLEBAR_STARTUP:
4125 {
4126 /*
4127 * Format it.
4128 */
4129 MachineState_T machineState;
4130 gpMachine->COMGETTER(State)(&machineState);
4131 if (machineState == MachineState_Starting)
4132 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4133 " - Starting...");
4134 else if (machineState == MachineState_Restoring)
4135 {
4136 ULONG cPercentNow;
4137 HRESULT rc = gpProgress->COMGETTER(Percent)(&cPercentNow);
4138 if (SUCCEEDED(rc))
4139 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4140 " - Restoring %d%%...", (int)cPercentNow);
4141 else
4142 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4143 " - Restoring...");
4144 }
4145 else if (machineState == MachineState_TeleportingIn)
4146 {
4147 ULONG cPercentNow;
4148 HRESULT rc = gpProgress->COMGETTER(Percent)(&cPercentNow);
4149 if (SUCCEEDED(rc))
4150 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4151 " - Teleporting %d%%...", (int)cPercentNow);
4152 else
4153 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4154 " - Teleporting...");
4155 }
4156 /* ignore other states, we could already be in running or aborted state */
4157 break;
4158 }
4159
4160 case TITLEBAR_SAVE:
4161 {
4162 AssertMsg(u32User <= 100, ("%d\n", u32User));
4163 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4164 " - Saving %d%%...", u32User);
4165 break;
4166 }
4167
4168 case TITLEBAR_SNAPSHOT:
4169 {
4170 AssertMsg(u32User <= 100, ("%d\n", u32User));
4171 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4172 " - Taking snapshot %d%%...", u32User);
4173 break;
4174 }
4175
4176 default:
4177 RTPrintf("Error: Invalid title bar mode %d!\n", mode);
4178 return;
4179 }
4180
4181 /*
4182 * Don't update if it didn't change.
4183 */
4184 if (!strcmp(szTitle, szPrevTitle))
4185 return;
4186
4187 /*
4188 * Set the new title
4189 */
4190#ifdef VBOX_WIN32_UI
4191 setUITitle(szTitle);
4192#else
4193 SDL_WM_SetCaption(szTitle, VBOX_PRODUCT);
4194#endif
4195}
4196
4197#if 0
4198static void vbox_show_shape(unsigned short w, unsigned short h,
4199 uint32_t bg, const uint8_t *image)
4200{
4201 size_t x, y;
4202 unsigned short pitch;
4203 const uint32_t *color;
4204 const uint8_t *mask;
4205 size_t size_mask;
4206
4207 mask = image;
4208 pitch = (w + 7) / 8;
4209 size_mask = (pitch * h + 3) & ~3;
4210
4211 color = (const uint32_t *)(image + size_mask);
4212
4213 printf("show_shape %dx%d pitch %d size mask %d\n",
4214 w, h, pitch, size_mask);
4215 for (y = 0; y < h; ++y, mask += pitch, color += w)
4216 {
4217 for (x = 0; x < w; ++x) {
4218 if (mask[x / 8] & (1 << (7 - (x % 8))))
4219 printf(" ");
4220 else
4221 {
4222 uint32_t c = color[x];
4223 if (c == bg)
4224 printf("Y");
4225 else
4226 printf("X");
4227 }
4228 }
4229 printf("\n");
4230 }
4231}
4232#endif
4233
4234/**
4235 * Sets the pointer shape according to parameters.
4236 * Must be called only from the main SDL thread.
4237 */
4238static void SetPointerShape(const PointerShapeChangeData *data)
4239{
4240 /*
4241 * don't allow to change the pointer shape if we are outside the valid
4242 * guest area. In that case set standard mouse pointer is set and should
4243 * not get overridden.
4244 */
4245 if (gpOffCursor)
4246 return;
4247
4248 if (data->shape.size() > 0)
4249 {
4250 bool ok = false;
4251
4252 uint32_t andMaskSize = (data->width + 7) / 8 * data->height;
4253 uint32_t srcShapePtrScan = data->width * 4;
4254
4255 const uint8_t* shape = data->shape.raw();
4256 const uint8_t *srcAndMaskPtr = shape;
4257 const uint8_t *srcShapePtr = shape + ((andMaskSize + 3) & ~3);
4258
4259#if 0
4260 /* pointer debugging code */
4261 // vbox_show_shape(data->width, data->height, 0, data->shape);
4262 uint32_t shapeSize = ((((data->width + 7) / 8) * data->height + 3) & ~3) + data->width * 4 * data->height;
4263 printf("visible: %d\n", data->visible);
4264 printf("width = %d\n", data->width);
4265 printf("height = %d\n", data->height);
4266 printf("alpha = %d\n", data->alpha);
4267 printf("xhot = %d\n", data->xHot);
4268 printf("yhot = %d\n", data->yHot);
4269 printf("uint8_t pointerdata[] = { ");
4270 for (uint32_t i = 0; i < shapeSize; i++)
4271 {
4272 printf("0x%x, ", data->shape[i]);
4273 }
4274 printf("};\n");
4275#endif
4276
4277#if defined(RT_OS_WINDOWS)
4278
4279 BITMAPV5HEADER bi;
4280 HBITMAP hBitmap;
4281 void *lpBits;
4282 HCURSOR hAlphaCursor = NULL;
4283
4284 ::ZeroMemory(&bi, sizeof(BITMAPV5HEADER));
4285 bi.bV5Size = sizeof(BITMAPV5HEADER);
4286 bi.bV5Width = data->width;
4287 bi.bV5Height = -(LONG)data->height;
4288 bi.bV5Planes = 1;
4289 bi.bV5BitCount = 32;
4290 bi.bV5Compression = BI_BITFIELDS;
4291 // specify a supported 32 BPP alpha format for Windows XP
4292 bi.bV5RedMask = 0x00FF0000;
4293 bi.bV5GreenMask = 0x0000FF00;
4294 bi.bV5BlueMask = 0x000000FF;
4295 if (data->alpha)
4296 bi.bV5AlphaMask = 0xFF000000;
4297 else
4298 bi.bV5AlphaMask = 0;
4299
4300 HDC hdc = ::GetDC(NULL);
4301
4302 // create the DIB section with an alpha channel
4303 hBitmap = ::CreateDIBSection(hdc, (BITMAPINFO *)&bi, DIB_RGB_COLORS,
4304 (void **)&lpBits, NULL, (DWORD)0);
4305
4306 ::ReleaseDC(NULL, hdc);
4307
4308 HBITMAP hMonoBitmap = NULL;
4309 if (data->alpha)
4310 {
4311 // create an empty mask bitmap
4312 hMonoBitmap = ::CreateBitmap(data->width, data->height, 1, 1, NULL);
4313 }
4314 else
4315 {
4316 /* Word aligned AND mask. Will be allocated and created if necessary. */
4317 uint8_t *pu8AndMaskWordAligned = NULL;
4318
4319 /* Width in bytes of the original AND mask scan line. */
4320 uint32_t cbAndMaskScan = (data->width + 7) / 8;
4321
4322 if (cbAndMaskScan & 1)
4323 {
4324 /* Original AND mask is not word aligned. */
4325
4326 /* Allocate memory for aligned AND mask. */
4327 pu8AndMaskWordAligned = (uint8_t *)RTMemTmpAllocZ((cbAndMaskScan + 1) * data->height);
4328
4329 Assert(pu8AndMaskWordAligned);
4330
4331 if (pu8AndMaskWordAligned)
4332 {
4333 /* According to MSDN the padding bits must be 0.
4334 * Compute the bit mask to set padding bits to 0 in the last byte of original AND mask.
4335 */
4336 uint32_t u32PaddingBits = cbAndMaskScan * 8 - data->width;
4337 Assert(u32PaddingBits < 8);
4338 uint8_t u8LastBytesPaddingMask = (uint8_t)(0xFF << u32PaddingBits);
4339
4340 Log(("u8LastBytesPaddingMask = %02X, aligned w = %d, width = %d, cbAndMaskScan = %d\n",
4341 u8LastBytesPaddingMask, (cbAndMaskScan + 1) * 8, data->width, cbAndMaskScan));
4342
4343 uint8_t *src = (uint8_t *)srcAndMaskPtr;
4344 uint8_t *dst = pu8AndMaskWordAligned;
4345
4346 unsigned i;
4347 for (i = 0; i < data->height; i++)
4348 {
4349 memcpy(dst, src, cbAndMaskScan);
4350
4351 dst[cbAndMaskScan - 1] &= u8LastBytesPaddingMask;
4352
4353 src += cbAndMaskScan;
4354 dst += cbAndMaskScan + 1;
4355 }
4356 }
4357 }
4358
4359 // create the AND mask bitmap
4360 hMonoBitmap = ::CreateBitmap(data->width, data->height, 1, 1,
4361 pu8AndMaskWordAligned? pu8AndMaskWordAligned: srcAndMaskPtr);
4362
4363 if (pu8AndMaskWordAligned)
4364 {
4365 RTMemTmpFree(pu8AndMaskWordAligned);
4366 }
4367 }
4368
4369 Assert(hBitmap);
4370 Assert(hMonoBitmap);
4371 if (hBitmap && hMonoBitmap)
4372 {
4373 DWORD *dstShapePtr = (DWORD *)lpBits;
4374
4375 for (uint32_t y = 0; y < data->height; y ++)
4376 {
4377 memcpy(dstShapePtr, srcShapePtr, srcShapePtrScan);
4378 srcShapePtr += srcShapePtrScan;
4379 dstShapePtr += data->width;
4380 }
4381
4382 ICONINFO ii;
4383 ii.fIcon = FALSE;
4384 ii.xHotspot = data->xHot;
4385 ii.yHotspot = data->yHot;
4386 ii.hbmMask = hMonoBitmap;
4387 ii.hbmColor = hBitmap;
4388
4389 hAlphaCursor = ::CreateIconIndirect(&ii);
4390 Assert(hAlphaCursor);
4391 if (hAlphaCursor)
4392 {
4393 // here we do a dirty trick by substituting a Window Manager's
4394 // cursor handle with the handle we created
4395
4396 WMcursor *pCustomTempWMCursor = gpCustomCursor->wm_cursor;
4397
4398 // see SDL12/src/video/wincommon/SDL_sysmouse.c
4399 void *wm_cursor = malloc(sizeof(HCURSOR) + sizeof(uint8_t *) * 2);
4400 *(HCURSOR *)wm_cursor = hAlphaCursor;
4401
4402 gpCustomCursor->wm_cursor = (WMcursor *)wm_cursor;
4403 SDL_SetCursor(gpCustomCursor);
4404 SDL_ShowCursor(SDL_ENABLE);
4405
4406 if (pCustomTempWMCursor)
4407 {
4408 ::DestroyCursor(*(HCURSOR *)pCustomTempWMCursor);
4409 free(pCustomTempWMCursor);
4410 }
4411
4412 ok = true;
4413 }
4414 }
4415
4416 if (hMonoBitmap)
4417 ::DeleteObject(hMonoBitmap);
4418 if (hBitmap)
4419 ::DeleteObject(hBitmap);
4420
4421#elif defined(VBOXSDL_WITH_X11) && !defined(VBOX_WITHOUT_XCURSOR)
4422
4423 if (gfXCursorEnabled)
4424 {
4425 XcursorImage *img = XcursorImageCreate(data->width, data->height);
4426 Assert(img);
4427 if (img)
4428 {
4429 img->xhot = data->xHot;
4430 img->yhot = data->yHot;
4431
4432 XcursorPixel *dstShapePtr = img->pixels;
4433
4434 for (uint32_t y = 0; y < data->height; y ++)
4435 {
4436 memcpy(dstShapePtr, srcShapePtr, srcShapePtrScan);
4437
4438 if (!data->alpha)
4439 {
4440 // convert AND mask to the alpha channel
4441 uint8_t byte = 0;
4442 for (uint32_t x = 0; x < data->width; x ++)
4443 {
4444 if (!(x % 8))
4445 byte = *(srcAndMaskPtr ++);
4446 else
4447 byte <<= 1;
4448
4449 if (byte & 0x80)
4450 {
4451 // Linux doesn't support inverted pixels (XOR ops,
4452 // to be exact) in cursor shapes, so we detect such
4453 // pixels and always replace them with black ones to
4454 // make them visible at least over light colors
4455 if (dstShapePtr [x] & 0x00FFFFFF)
4456 dstShapePtr [x] = 0xFF000000;
4457 else
4458 dstShapePtr [x] = 0x00000000;
4459 }
4460 else
4461 dstShapePtr [x] |= 0xFF000000;
4462 }
4463 }
4464
4465 srcShapePtr += srcShapePtrScan;
4466 dstShapePtr += data->width;
4467 }
4468
4469#ifndef VBOX_WITH_SDL13
4470 Cursor cur = XcursorImageLoadCursor(gSdlInfo.info.x11.display, img);
4471 Assert(cur);
4472 if (cur)
4473 {
4474 // here we do a dirty trick by substituting a Window Manager's
4475 // cursor handle with the handle we created
4476
4477 WMcursor *pCustomTempWMCursor = gpCustomCursor->wm_cursor;
4478
4479 // see SDL12/src/video/x11/SDL_x11mouse.c
4480 void *wm_cursor = malloc(sizeof(Cursor));
4481 *(Cursor *)wm_cursor = cur;
4482
4483 gpCustomCursor->wm_cursor = (WMcursor *)wm_cursor;
4484 SDL_SetCursor(gpCustomCursor);
4485 SDL_ShowCursor(SDL_ENABLE);
4486
4487 if (pCustomTempWMCursor)
4488 {
4489 XFreeCursor(gSdlInfo.info.x11.display, *(Cursor *)pCustomTempWMCursor);
4490 free(pCustomTempWMCursor);
4491 }
4492
4493 ok = true;
4494 }
4495#endif
4496 }
4497 XcursorImageDestroy(img);
4498 }
4499
4500#endif /* VBOXSDL_WITH_X11 && !VBOX_WITHOUT_XCURSOR */
4501
4502 if (!ok)
4503 {
4504 SDL_SetCursor(gpDefaultCursor);
4505 SDL_ShowCursor(SDL_ENABLE);
4506 }
4507 }
4508 else
4509 {
4510 if (data->visible)
4511 SDL_ShowCursor(SDL_ENABLE);
4512 else if (gfAbsoluteMouseGuest)
4513 /* Don't disable the cursor if the guest additions are not active (anymore) */
4514 SDL_ShowCursor(SDL_DISABLE);
4515 }
4516}
4517
4518/**
4519 * Handle changed mouse capabilities
4520 */
4521static void HandleGuestCapsChanged(void)
4522{
4523 if (!gfAbsoluteMouseGuest)
4524 {
4525 // Cursor could be overwritten by the guest tools
4526 SDL_SetCursor(gpDefaultCursor);
4527 SDL_ShowCursor(SDL_ENABLE);
4528 gpOffCursor = NULL;
4529 }
4530 if (gpMouse && UseAbsoluteMouse())
4531 {
4532 // Actually switch to absolute coordinates
4533 if (gfGrabbed)
4534 InputGrabEnd();
4535 gpMouse->PutMouseEventAbsolute(-1, -1, 0, 0, 0);
4536 }
4537}
4538
4539/**
4540 * Handles a host key down event
4541 */
4542static int HandleHostKey(const SDL_KeyboardEvent *pEv)
4543{
4544 /*
4545 * Revalidate the host key modifier
4546 */
4547 if ((SDL_GetModState() & ~(KMOD_MODE | KMOD_NUM | KMOD_RESERVED)) != gHostKeyMod)
4548 return VERR_NOT_SUPPORTED;
4549
4550 /*
4551 * What was pressed?
4552 */
4553 switch (pEv->keysym.sym)
4554 {
4555 /* Control-Alt-Delete */
4556 case SDLK_DELETE:
4557 {
4558 gpKeyboard->PutCAD();
4559 break;
4560 }
4561
4562 /*
4563 * Fullscreen / Windowed toggle.
4564 */
4565 case SDLK_f:
4566 {
4567 if ( strchr(gHostKeyDisabledCombinations, 'f')
4568 || !gfAllowFullscreenToggle)
4569 return VERR_NOT_SUPPORTED;
4570
4571 /*
4572 * We have to pause/resume the machine during this
4573 * process because there might be a short moment
4574 * without a valid framebuffer
4575 */
4576 MachineState_T machineState;
4577 gpMachine->COMGETTER(State)(&machineState);
4578 bool fPauseIt = machineState == MachineState_Running
4579 || machineState == MachineState_Teleporting
4580 || machineState == MachineState_LiveSnapshotting;
4581 if (fPauseIt)
4582 gpConsole->Pause();
4583 SetFullscreen(!gpFramebuffer[0]->getFullscreen());
4584 if (fPauseIt)
4585 gpConsole->Resume();
4586
4587 /*
4588 * We have switched from/to fullscreen, so request a full
4589 * screen repaint, just to be sure.
4590 */
4591 gpDisplay->InvalidateAndUpdate();
4592 break;
4593 }
4594
4595 /*
4596 * Pause / Resume toggle.
4597 */
4598 case SDLK_p:
4599 {
4600 if (strchr(gHostKeyDisabledCombinations, 'p'))
4601 return VERR_NOT_SUPPORTED;
4602
4603 MachineState_T machineState;
4604 gpMachine->COMGETTER(State)(&machineState);
4605 if ( machineState == MachineState_Running
4606 || machineState == MachineState_Teleporting
4607 || machineState == MachineState_LiveSnapshotting
4608 )
4609 {
4610 if (gfGrabbed)
4611 InputGrabEnd();
4612 gpConsole->Pause();
4613 }
4614 else if (machineState == MachineState_Paused)
4615 {
4616 gpConsole->Resume();
4617 }
4618 UpdateTitlebar(TITLEBAR_NORMAL);
4619 break;
4620 }
4621
4622 /*
4623 * Reset the VM
4624 */
4625 case SDLK_r:
4626 {
4627 if (strchr(gHostKeyDisabledCombinations, 'r'))
4628 return VERR_NOT_SUPPORTED;
4629
4630 ResetVM();
4631 break;
4632 }
4633
4634 /*
4635 * Terminate the VM
4636 */
4637 case SDLK_q:
4638 {
4639 if (strchr(gHostKeyDisabledCombinations, 'q'))
4640 return VERR_NOT_SUPPORTED;
4641
4642 return VINF_EM_TERMINATE;
4643 }
4644
4645 /*
4646 * Save the machine's state and exit
4647 */
4648 case SDLK_s:
4649 {
4650 if (strchr(gHostKeyDisabledCombinations, 's'))
4651 return VERR_NOT_SUPPORTED;
4652
4653 SaveState();
4654 return VINF_EM_TERMINATE;
4655 }
4656
4657 case SDLK_h:
4658 {
4659 if (strchr(gHostKeyDisabledCombinations, 'h'))
4660 return VERR_NOT_SUPPORTED;
4661
4662 if (gpConsole)
4663 gpConsole->PowerButton();
4664 break;
4665 }
4666
4667 /*
4668 * Perform an online snapshot. Continue operation.
4669 */
4670 case SDLK_n:
4671 {
4672 if (strchr(gHostKeyDisabledCombinations, 'n'))
4673 return VERR_NOT_SUPPORTED;
4674
4675 RTThreadYield();
4676 ULONG cSnapshots = 0;
4677 gpMachine->COMGETTER(SnapshotCount)(&cSnapshots);
4678 char pszSnapshotName[20];
4679 RTStrPrintf(pszSnapshotName, sizeof(pszSnapshotName), "Snapshot %d", cSnapshots + 1);
4680 gpProgress = NULL;
4681 HRESULT rc;
4682 CHECK_ERROR(gpConsole, TakeSnapshot(Bstr(pszSnapshotName).raw(),
4683 Bstr("Taken by VBoxSDL").raw(),
4684 gpProgress.asOutParam()));
4685 if (FAILED(rc))
4686 {
4687 RTPrintf("Error taking snapshot! rc = 0x%x\n", rc);
4688 /* continue operation */
4689 return VINF_SUCCESS;
4690 }
4691 /*
4692 * Wait for the operation to be completed and work
4693 * the title bar in the mean while.
4694 */
4695 ULONG cPercent = 0;
4696 for (;;)
4697 {
4698 BOOL fCompleted = false;
4699 rc = gpProgress->COMGETTER(Completed)(&fCompleted);
4700 if (FAILED(rc) || fCompleted)
4701 break;
4702 ULONG cPercentNow;
4703 rc = gpProgress->COMGETTER(Percent)(&cPercentNow);
4704 if (FAILED(rc))
4705 break;
4706 if (cPercentNow != cPercent)
4707 {
4708 UpdateTitlebar(TITLEBAR_SNAPSHOT, cPercent);
4709 cPercent = cPercentNow;
4710 }
4711
4712 /* wait */
4713 rc = gpProgress->WaitForCompletion(100);
4714 if (FAILED(rc))
4715 break;
4716 /// @todo process gui events.
4717 }
4718
4719 /* continue operation */
4720 return VINF_SUCCESS;
4721 }
4722
4723 case SDLK_F1: case SDLK_F2: case SDLK_F3:
4724 case SDLK_F4: case SDLK_F5: case SDLK_F6:
4725 case SDLK_F7: case SDLK_F8: case SDLK_F9:
4726 case SDLK_F10: case SDLK_F11: case SDLK_F12:
4727 {
4728 // /* send Ctrl-Alt-Fx to guest */
4729 com::SafeArray<LONG> keys(6);
4730
4731 keys[0] = 0x1d; // Ctrl down
4732 keys[1] = 0x38; // Alt down
4733 keys[2] = Keyevent2Keycode(pEv); // Fx down
4734 keys[3] = keys[2] + 0x80; // Fx up
4735 keys[4] = 0xb8; // Alt up
4736 keys[5] = 0x9d; // Ctrl up
4737
4738 gpKeyboard->PutScancodes(ComSafeArrayAsInParam(keys), NULL);
4739 return VINF_SUCCESS;
4740 }
4741
4742 /*
4743 * Not a host key combination.
4744 * Indicate this by returning false.
4745 */
4746 default:
4747 return VERR_NOT_SUPPORTED;
4748 }
4749
4750 return VINF_SUCCESS;
4751}
4752
4753/**
4754 * Timer callback function for startup processing
4755 */
4756static Uint32 StartupTimer(Uint32 interval, void *param)
4757{
4758 /* post message so we can do something in the startup loop */
4759 SDL_Event event = {0};
4760 event.type = SDL_USEREVENT;
4761 event.user.type = SDL_USER_EVENT_TIMER;
4762 SDL_PushEvent(&event);
4763 RTSemEventSignal(g_EventSemSDLEvents);
4764 return interval;
4765}
4766
4767/**
4768 * Timer callback function to check if resizing is finished
4769 */
4770static Uint32 ResizeTimer(Uint32 interval, void *param)
4771{
4772 /* post message so the window is actually resized */
4773 SDL_Event event = {0};
4774 event.type = SDL_USEREVENT;
4775 event.user.type = SDL_USER_EVENT_WINDOW_RESIZE_DONE;
4776 PushSDLEventForSure(&event);
4777 /* one-shot */
4778 return 0;
4779}
4780
4781/**
4782 * Timer callback function to check if an ACPI power button event was handled by the guest.
4783 */
4784static Uint32 QuitTimer(Uint32 interval, void *param)
4785{
4786 BOOL fHandled = FALSE;
4787
4788 gSdlQuitTimer = NULL;
4789 if (gpConsole)
4790 {
4791 int rc = gpConsole->GetPowerButtonHandled(&fHandled);
4792 LogRel(("QuitTimer: rc=%d handled=%d\n", rc, fHandled));
4793 if (RT_FAILURE(rc) || !fHandled)
4794 {
4795 /* event was not handled, power down the guest */
4796 gfACPITerm = FALSE;
4797 SDL_Event event = {0};
4798 event.type = SDL_QUIT;
4799 PushSDLEventForSure(&event);
4800 }
4801 }
4802 /* one-shot */
4803 return 0;
4804}
4805
4806/**
4807 * Wait for the next SDL event. Don't use SDL_WaitEvent since this function
4808 * calls SDL_Delay(10) if the event queue is empty.
4809 */
4810static int WaitSDLEvent(SDL_Event *event)
4811{
4812 for (;;)
4813 {
4814 int rc = SDL_PollEvent(event);
4815 if (rc == 1)
4816 {
4817#ifdef USE_XPCOM_QUEUE_THREAD
4818 if (event->type == SDL_USER_EVENT_XPCOM_EVENTQUEUE)
4819 consumedXPCOMUserEvent();
4820#endif
4821 return 1;
4822 }
4823 /* Immediately wake up if new SDL events are available. This does not
4824 * work for internal SDL events. Don't wait more than 10ms. */
4825 RTSemEventWait(g_EventSemSDLEvents, 10);
4826 }
4827}
4828
4829/**
4830 * Ensure that an SDL event is really enqueued. Try multiple times if necessary.
4831 */
4832int PushSDLEventForSure(SDL_Event *event)
4833{
4834 int ntries = 10;
4835 for (; ntries > 0; ntries--)
4836 {
4837 int rc = SDL_PushEvent(event);
4838 RTSemEventSignal(g_EventSemSDLEvents);
4839#ifdef VBOX_WITH_SDL13
4840 if (rc == 1)
4841#else
4842 if (rc == 0)
4843#endif
4844 return 0;
4845 Log(("PushSDLEventForSure: waiting for 2ms (rc = %d)\n", rc));
4846 RTThreadSleep(2);
4847 }
4848 LogRel(("WARNING: Failed to enqueue SDL event %d.%d!\n",
4849 event->type, event->type == SDL_USEREVENT ? event->user.type : 0));
4850 return -1;
4851}
4852
4853#ifdef VBOXSDL_WITH_X11
4854/**
4855 * Special SDL_PushEvent function for NotifyUpdate events. These events may occur in bursts
4856 * so make sure they don't flood the SDL event queue.
4857 */
4858void PushNotifyUpdateEvent(SDL_Event *event)
4859{
4860 int rc = SDL_PushEvent(event);
4861#ifdef VBOX_WITH_SDL13
4862 bool fSuccess = (rc == 1);
4863#else
4864 bool fSuccess = (rc == 0);
4865#endif
4866
4867 RTSemEventSignal(g_EventSemSDLEvents);
4868 AssertMsg(fSuccess, ("SDL_PushEvent returned SDL error\n"));
4869 /* A global counter is faster than SDL_PeepEvents() */
4870 if (fSuccess)
4871 ASMAtomicIncS32(&g_cNotifyUpdateEventsPending);
4872 /* In order to not flood the SDL event queue, yield the CPU or (if there are already many
4873 * events queued) even sleep */
4874 if (g_cNotifyUpdateEventsPending > 96)
4875 {
4876 /* Too many NotifyUpdate events, sleep for a small amount to give the main thread time
4877 * to handle these events. The SDL queue can hold up to 128 events. */
4878 Log(("PushNotifyUpdateEvent: Sleep 1ms\n"));
4879 RTThreadSleep(1);
4880 }
4881 else
4882 RTThreadYield();
4883}
4884#endif /* VBOXSDL_WITH_X11 */
4885
4886/**
4887 *
4888 */
4889static void SetFullscreen(bool enable)
4890{
4891 if (enable == gpFramebuffer[0]->getFullscreen())
4892 return;
4893
4894 if (!gfFullscreenResize)
4895 {
4896 /*
4897 * The old/default way: SDL will resize the host to fit the guest screen resolution.
4898 */
4899 gpFramebuffer[0]->setFullscreen(enable);
4900 }
4901 else
4902 {
4903 /*
4904 * The alternate way: Switch to fullscreen with the host screen resolution and adapt
4905 * the guest screen resolution to the host window geometry.
4906 */
4907 uint32_t NewWidth = 0, NewHeight = 0;
4908 if (enable)
4909 {
4910 /* switch to fullscreen */
4911 gmGuestNormalXRes = gpFramebuffer[0]->getGuestXRes();
4912 gmGuestNormalYRes = gpFramebuffer[0]->getGuestYRes();
4913 gpFramebuffer[0]->getFullscreenGeometry(&NewWidth, &NewHeight);
4914 }
4915 else
4916 {
4917 /* switch back to saved geometry */
4918 NewWidth = gmGuestNormalXRes;
4919 NewHeight = gmGuestNormalYRes;
4920 }
4921 if (NewWidth != 0 && NewHeight != 0)
4922 {
4923 gpFramebuffer[0]->setFullscreen(enable);
4924 gfIgnoreNextResize = TRUE;
4925 gpDisplay->SetVideoModeHint(NewWidth, NewHeight, 0, 0);
4926 }
4927 }
4928}
4929
4930#ifdef VBOX_WITH_SDL13
4931static VBoxSDLFB * getFbFromWinId(SDL_WindowID id)
4932{
4933 for (unsigned i = 0; i < gcMonitors; i++)
4934 if (gpFramebuffer[i]->hasWindow(id))
4935 return gpFramebuffer[i];
4936
4937 return NULL;
4938}
4939#endif
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use