VirtualBox

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

Last change on this file since 7266 was 7207, checked in by vboxsync, 17 years ago

Main: Reworked enums to avoid 1) weird duplication of enum name when referring to enum values in cross-platform code; 2) possible clashes on Win32 due to putting identifiers like Paused or Disabled to the global namespace (via C enums). In the new style, enums are used like this: a) USBDeviceState_T v = USBDeviceState_Busy from cross-platform non-Qt code; b) KUSBDeviceState v = KUSBDeviceState_Busy from Qt code; c) USBDeviceState v = USBDeviceState_Busy from plain Win32 and d) PRUInt32 USBDeviceState v = USBDeviceState::Busy from plain XPCOM.

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

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