VirtualBox

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

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

Frontends/VBoxSDL: use VirtualBoxClient object, and terminate VM as cleanly as possible if VBoxSVC becomes unavailable

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