VirtualBox

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

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

use openMedium instead of findMedium

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