VirtualBox

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

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

frontends: init ATL, used for listener instantiation

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

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