VirtualBox

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

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

VBOX_WITHOUT_XCURSOR for solaris.

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

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