VirtualBox

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

Last change on this file since 3820 was 3669, checked in by vboxsync, 18 years ago

replace underscore symbols in VBoxBFE/ and VBoxSDL/

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

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