VirtualBox

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

Last change on this file since 26753 was 26603, checked in by vboxsync, 15 years ago

Main: back out r57775

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

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