VirtualBox

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

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

gcc-4.7 fixes

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

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