VirtualBox

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

Last change on this file since 42018 was 41216, checked in by vboxsync, 13 years ago

Frontends: back out the Framebuffer cleanup, to be retried later

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

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