VirtualBox

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

Last change on this file since 3603 was 3300, checked in by vboxsync, 18 years ago

FE/SDL: fixed dropping of XPCOM events; make ShowConsoleWindow work

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