VirtualBox

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

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

Main/VirtualBox+Medium: resurrect the feature of changing the medium UUID when opening the image, which allows to resolve duplicate UUIDs without using external tools. Also fixes Medium::setIDs, which wasn't correctly working.
Frontends/*: corresponding changes.

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