VirtualBox

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

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

backed out r77705 as it broke the builds (webservices)

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