VirtualBox

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

Last change on this file since 4076 was 4071, checked in by vboxsync, 17 years ago

Biggest check-in ever. New source code headers for all (C) innotek files.

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

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