VirtualBox

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

Last change on this file since 29437 was 29431, checked in by vboxsync, 15 years ago

Frontends/VBoxSDL: get rid of usage for long deleted options

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 173.4 KB
Line 
1/** @file
2 * VBox frontends: VBoxSDL (simple frontend based on SDL):
3 * Main code
4 */
5
6/*
7 * Copyright (C) 2006-2010 Oracle Corporation
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
18/*******************************************************************************
19* Header Files *
20*******************************************************************************/
21#define LOG_GROUP LOG_GROUP_GUI
22
23#include <VBox/com/com.h>
24#include <VBox/com/string.h>
25#include <VBox/com/Guid.h>
26#include <VBox/com/array.h>
27#include <VBox/com/ErrorInfo.h>
28#include <VBox/com/errorprint.h>
29
30#include <VBox/com/EventQueue.h>
31#include <VBox/com/VirtualBox.h>
32
33using namespace com;
34
35#if defined(VBOXSDL_WITH_X11)
36# include <X11/Xlib.h>
37# include <X11/cursorfont.h> /* for XC_left_ptr */
38# if !defined(VBOX_WITHOUT_XCURSOR)
39# include <X11/Xcursor/Xcursor.h>
40# endif
41# include <unistd.h>
42#endif
43
44#ifndef RT_OS_DARWIN
45#include <SDL_syswm.h> /* for SDL_GetWMInfo() */
46#endif
47
48#include "VBoxSDL.h"
49#include "Framebuffer.h"
50#include "Helper.h"
51
52#include <VBox/types.h>
53#include <VBox/err.h>
54#include <VBox/param.h>
55#include <VBox/log.h>
56#include <VBox/version.h>
57#include <VBox/VBoxVideo.h>
58
59#include <iprt/alloca.h>
60#include <iprt/asm.h>
61#include <iprt/assert.h>
62#include <iprt/env.h>
63#include <iprt/file.h>
64#include <iprt/ldr.h>
65#include <iprt/initterm.h>
66#include <iprt/path.h>
67#include <iprt/process.h>
68#include <iprt/semaphore.h>
69#include <iprt/string.h>
70#include <iprt/stream.h>
71#include <iprt/uuid.h>
72
73#include <signal.h>
74
75#include <vector>
76#include <list>
77
78/* Xlib would re-define our enums */
79#undef True
80#undef False
81
82/*******************************************************************************
83* Defined Constants And Macros *
84*******************************************************************************/
85#ifdef VBOX_SECURELABEL
86/** extra data key for the secure label */
87#define VBOXSDL_SECURELABEL_EXTRADATA "VBoxSDL/SecureLabel"
88/** label area height in pixels */
89#define SECURE_LABEL_HEIGHT 20
90#endif
91
92/** Enables the rawr[0|3], patm, and casm options. */
93#define VBOXSDL_ADVANCED_OPTIONS
94
95/*******************************************************************************
96* Structures and Typedefs *
97*******************************************************************************/
98/** Pointer shape change event data strucure */
99struct PointerShapeChangeData
100{
101 PointerShapeChangeData(BOOL aVisible, BOOL aAlpha, ULONG aXHot, ULONG aYHot,
102 ULONG aWidth, ULONG aHeight, const uint8_t *aShape)
103 : visible(aVisible), alpha(aAlpha), xHot(aXHot), yHot(aYHot),
104 width(aWidth), height(aHeight), shape(NULL)
105 {
106 // make a copy of the shape
107 if (aShape)
108 {
109 uint32_t shapeSize = ((((aWidth + 7) / 8) * aHeight + 3) & ~3) + aWidth * 4 * aHeight;
110 shape = new uint8_t [shapeSize];
111 if (shape)
112 memcpy((void *)shape, (void *)aShape, shapeSize);
113 }
114 }
115
116 ~PointerShapeChangeData()
117 {
118 if (shape) delete[] shape;
119 }
120
121 const BOOL visible;
122 const BOOL alpha;
123 const ULONG xHot;
124 const ULONG yHot;
125 const ULONG width;
126 const ULONG height;
127 const uint8_t *shape;
128};
129
130enum TitlebarMode
131{
132 TITLEBAR_NORMAL = 1,
133 TITLEBAR_STARTUP = 2,
134 TITLEBAR_SAVE = 3,
135 TITLEBAR_SNAPSHOT = 4
136};
137
138/*******************************************************************************
139* Internal Functions *
140*******************************************************************************/
141static bool UseAbsoluteMouse(void);
142static void ResetKeys(void);
143static void ProcessKey(SDL_KeyboardEvent *ev);
144static void InputGrabStart(void);
145static void InputGrabEnd(void);
146static void SendMouseEvent(VBoxSDLFB *fb, int dz, int button, int down);
147static void UpdateTitlebar(TitlebarMode mode, uint32_t u32User = 0);
148static void SetPointerShape(const PointerShapeChangeData *data);
149static void HandleGuestCapsChanged(void);
150static int HandleHostKey(const SDL_KeyboardEvent *pEv);
151static Uint32 StartupTimer(Uint32 interval, void *param);
152static Uint32 ResizeTimer(Uint32 interval, void *param);
153static Uint32 QuitTimer(Uint32 interval, void *param);
154static int WaitSDLEvent(SDL_Event *event);
155static void SetFullscreen(bool enable);
156#ifdef VBOX_WITH_SDL13
157static VBoxSDLFB * getFbFromWinId(SDL_WindowID id);
158#endif
159
160
161/*******************************************************************************
162* Global Variables *
163*******************************************************************************/
164static int gHostKeyMod = KMOD_RCTRL;
165static int gHostKeySym1 = SDLK_RCTRL;
166static int gHostKeySym2 = SDLK_UNKNOWN;
167static const char *gHostKeyDisabledCombinations = "";
168static const char *gpszPidFile;
169static BOOL gfGrabbed = FALSE;
170static BOOL gfGrabOnMouseClick = TRUE;
171static BOOL gfFullscreenResize = FALSE;
172static BOOL gfIgnoreNextResize = FALSE;
173static BOOL gfAllowFullscreenToggle = TRUE;
174static BOOL gfAbsoluteMouseHost = FALSE;
175static BOOL gfAbsoluteMouseGuest = FALSE;
176static BOOL gfRelativeMouseGuest = TRUE;
177static BOOL gfGuestNeedsHostCursor = FALSE;
178static BOOL gfOffCursorActive = FALSE;
179static BOOL gfGuestNumLockPressed = FALSE;
180static BOOL gfGuestCapsLockPressed = FALSE;
181static BOOL gfGuestScrollLockPressed = FALSE;
182static BOOL gfACPITerm = FALSE;
183static BOOL gfXCursorEnabled = FALSE;
184static int gcGuestNumLockAdaptions = 2;
185static int gcGuestCapsLockAdaptions = 2;
186static uint32_t gmGuestNormalXRes;
187static uint32_t gmGuestNormalYRes;
188
189/** modifier keypress status (scancode as index) */
190static uint8_t gaModifiersState[256];
191
192static ComPtr<IMachine> gMachine;
193static ComPtr<IConsole> gConsole;
194static ComPtr<IMachineDebugger> gMachineDebugger;
195static ComPtr<IKeyboard> gKeyboard;
196static ComPtr<IMouse> gMouse;
197static ComPtr<IDisplay> gDisplay;
198static ComPtr<IVRDPServer> gVrdpServer;
199static ComPtr<IProgress> gProgress;
200
201static ULONG gcMonitors = 1;
202static VBoxSDLFB *gpFramebuffer[64];
203static SDL_Cursor *gpDefaultCursor = NULL;
204#ifdef VBOXSDL_WITH_X11
205static Cursor gpDefaultOrigX11Cursor;
206#ifdef RT_OS_LINUX
207static BOOL guseEvdevKeymap = FALSE;
208#endif
209#endif
210static SDL_Cursor *gpCustomCursor = NULL;
211#ifndef VBOX_WITH_SDL13
212static WMcursor *gpCustomOrigWMcursor = NULL;
213#endif
214static SDL_Cursor *gpOffCursor = NULL;
215static SDL_TimerID gSdlResizeTimer = NULL;
216static SDL_TimerID gSdlQuitTimer = NULL;
217
218#if defined(VBOXSDL_WITH_X11) && !defined(VBOX_WITH_SDL13)
219static SDL_SysWMinfo gSdlInfo;
220#endif
221
222#ifdef VBOX_SECURELABEL
223#ifdef RT_OS_WINDOWS
224#define LIBSDL_TTF_NAME "SDL_ttf"
225#else
226#define LIBSDL_TTF_NAME "libSDL_ttf-2.0.so.0"
227#endif
228RTLDRMOD gLibrarySDL_ttf = NIL_RTLDRMOD;
229#endif
230
231static RTSEMEVENT g_EventSemSDLEvents;
232static volatile int32_t g_cNotifyUpdateEventsPending;
233
234/**
235 * Callback handler for VirtualBox events
236 */
237class VBoxSDLCallback :
238 VBOX_SCRIPTABLE_IMPL(IVirtualBoxCallback)
239{
240public:
241 VBoxSDLCallback()
242 {
243#if defined(RT_OS_WINDOWS)
244 refcnt = 0;
245#endif
246 }
247
248 virtual ~VBoxSDLCallback()
249 {
250 }
251
252#ifdef RT_OS_WINDOWS
253 STDMETHOD_(ULONG, AddRef)()
254 {
255 return ::InterlockedIncrement(&refcnt);
256 }
257 STDMETHOD_(ULONG, Release)()
258 {
259 long cnt = ::InterlockedDecrement(&refcnt);
260 if (cnt == 0)
261 delete this;
262 return cnt;
263 }
264#endif
265 VBOX_SCRIPTABLE_DISPATCH_IMPL(IVirtualBoxCallback)
266
267 NS_DECL_ISUPPORTS
268
269 STDMETHOD(OnMachineStateChange)(IN_BSTR machineId, MachineState_T state)
270 {
271 return VBOX_E_DONT_CALL_AGAIN;
272 }
273
274 STDMETHOD(OnMachineDataChange)(IN_BSTR machineId)
275 {
276 return VBOX_E_DONT_CALL_AGAIN;
277 }
278
279 STDMETHOD(OnExtraDataCanChange)(IN_BSTR machineId, IN_BSTR key, IN_BSTR value,
280 BSTR *error, BOOL *changeAllowed)
281 {
282 /* we never disagree */
283 if (!changeAllowed)
284 return E_INVALIDARG;
285 *changeAllowed = TRUE;
286 return VBOX_E_DONT_CALL_AGAIN;
287 }
288
289 STDMETHOD(OnExtraDataChange)(IN_BSTR machineId, IN_BSTR key, IN_BSTR value)
290 {
291#ifdef VBOX_SECURELABEL
292 Assert(key);
293 if (gMachine)
294 {
295 /*
296 * check if we're interested in the message
297 */
298 Bstr ourGuid;
299 gMachine->COMGETTER(Id)(ourGuid.asOutParam());
300 if (ourGuid == machineId)
301 {
302 Bstr keyString = key;
303 if (keyString && keyString == VBOXSDL_SECURELABEL_EXTRADATA)
304 {
305 /*
306 * Notify SDL thread of the string update
307 */
308 SDL_Event event = {0};
309 event.type = SDL_USEREVENT;
310 event.user.type = SDL_USER_EVENT_SECURELABEL_UPDATE;
311 PushSDLEventForSure(&event);
312 }
313 }
314 }
315 return S_OK;
316#else
317 return VBOX_E_DONT_CALL_AGAIN;
318#endif /* VBOX_SECURELABEL */
319 }
320
321 STDMETHOD(OnMediumRegistered)(IN_BSTR mediaId, DeviceType_T mediaType,
322 BOOL registered)
323 {
324 NOREF(mediaId);
325 NOREF(mediaType);
326 NOREF(registered);
327 return VBOX_E_DONT_CALL_AGAIN;
328 }
329
330 STDMETHOD(OnMachineRegistered)(IN_BSTR machineId, BOOL registered)
331 {
332 return VBOX_E_DONT_CALL_AGAIN;
333 }
334
335 STDMETHOD(OnSessionStateChange)(IN_BSTR machineId, SessionState_T state)
336 {
337 return VBOX_E_DONT_CALL_AGAIN;
338 }
339
340 STDMETHOD(OnSnapshotTaken)(IN_BSTR aMachineId, IN_BSTR aSnapshotId)
341 {
342 return VBOX_E_DONT_CALL_AGAIN;
343 }
344
345 STDMETHOD(OnSnapshotDeleted)(IN_BSTR aMachineId, IN_BSTR aSnapshotId)
346 {
347 return VBOX_E_DONT_CALL_AGAIN;
348 }
349
350 STDMETHOD(OnSnapshotChange)(IN_BSTR aMachineId, IN_BSTR aSnapshotId)
351 {
352 return VBOX_E_DONT_CALL_AGAIN;
353 }
354
355 STDMETHOD(OnGuestPropertyChange)(IN_BSTR machineId, IN_BSTR key, IN_BSTR value, IN_BSTR flags)
356 {
357 return VBOX_E_DONT_CALL_AGAIN;
358 }
359
360private:
361#ifdef RT_OS_WINDOWS
362 long refcnt;
363#endif
364
365};
366
367/**
368 * Callback handler for machine events
369 */
370class VBoxSDLConsoleCallback :
371 VBOX_SCRIPTABLE_IMPL(IConsoleCallback)
372{
373public:
374 VBoxSDLConsoleCallback() : m_fIgnorePowerOffEvents(false)
375 {
376#if defined(RT_OS_WINDOWS)
377 refcnt = 0;
378#endif
379 }
380
381 virtual ~VBoxSDLConsoleCallback()
382 {
383 }
384
385#ifdef RT_OS_WINDOWS
386 STDMETHOD_(ULONG, AddRef)()
387 {
388 return ::InterlockedIncrement(&refcnt);
389 }
390 STDMETHOD_(ULONG, Release)()
391 {
392 long cnt = ::InterlockedDecrement(&refcnt);
393 if (cnt == 0)
394 delete this;
395 return cnt;
396 }
397#endif
398 VBOX_SCRIPTABLE_DISPATCH_IMPL(IConsoleCallback)
399
400 NS_DECL_ISUPPORTS
401
402 STDMETHOD(OnMousePointerShapeChange)(BOOL visible, BOOL alpha, ULONG xHot, ULONG yHot,
403 ULONG width, ULONG height, BYTE *shape)
404 {
405 PointerShapeChangeData *data;
406 data = new PointerShapeChangeData(visible, alpha, xHot, yHot, width, height,
407 shape);
408 Assert(data);
409 if (!data)
410 return E_FAIL;
411
412 SDL_Event event = {0};
413 event.type = SDL_USEREVENT;
414 event.user.type = SDL_USER_EVENT_POINTER_CHANGE;
415 event.user.data1 = data;
416
417 int rc = PushSDLEventForSure(&event);
418 if (rc)
419 delete data;
420
421 return S_OK;
422 }
423
424 STDMETHOD(OnMouseCapabilityChange)(BOOL supportsAbsolute, BOOL supportsRelative, BOOL needsHostCursor)
425 {
426 LogFlow(("OnMouseCapabilityChange: supportsAbsolute = %d, supportsRelative = %d, needsHostCursor = %d\n",
427 supportsAbsolute, supportsRelative, needsHostCursor));
428 gfAbsoluteMouseGuest = supportsAbsolute;
429 gfRelativeMouseGuest = supportsRelative;
430 gfGuestNeedsHostCursor = needsHostCursor;
431
432 SDL_Event event = {0};
433 event.type = SDL_USEREVENT;
434 event.user.type = SDL_USER_EVENT_GUEST_CAP_CHANGED;
435
436 PushSDLEventForSure(&event);
437 return S_OK;
438 }
439
440 STDMETHOD(OnKeyboardLedsChange)(BOOL fNumLock, BOOL fCapsLock, BOOL fScrollLock)
441 {
442 /* Don't bother the guest with NumLock scancodes if he doesn't set the NumLock LED */
443 if (gfGuestNumLockPressed != fNumLock)
444 gcGuestNumLockAdaptions = 2;
445 if (gfGuestCapsLockPressed != fCapsLock)
446 gcGuestCapsLockAdaptions = 2;
447 gfGuestNumLockPressed = fNumLock;
448 gfGuestCapsLockPressed = fCapsLock;
449 gfGuestScrollLockPressed = fScrollLock;
450 return S_OK;
451 }
452
453 STDMETHOD(OnStateChange)(MachineState_T machineState)
454 {
455 LogFlow(("OnStateChange: machineState = %d (%s)\n", machineState, GetStateName(machineState)));
456 SDL_Event event = {0};
457
458 if ( machineState == MachineState_Aborted
459 || machineState == MachineState_Teleported
460 || (machineState == MachineState_Saved && !m_fIgnorePowerOffEvents)
461 || (machineState == MachineState_PoweredOff && !m_fIgnorePowerOffEvents)
462 )
463 {
464 /*
465 * We have to inform the SDL thread that the application has be terminated
466 */
467 event.type = SDL_USEREVENT;
468 event.user.type = SDL_USER_EVENT_TERMINATE;
469 event.user.code = machineState == MachineState_Aborted
470 ? VBOXSDL_TERM_ABEND
471 : VBOXSDL_TERM_NORMAL;
472 }
473 else
474 {
475 /*
476 * Inform the SDL thread to refresh the titlebar
477 */
478 event.type = SDL_USEREVENT;
479 event.user.type = SDL_USER_EVENT_UPDATE_TITLEBAR;
480 }
481
482 PushSDLEventForSure(&event);
483 return S_OK;
484 }
485
486 STDMETHOD(OnAdditionsStateChange)()
487 {
488 return VBOX_E_DONT_CALL_AGAIN;
489 }
490
491 STDMETHOD(OnNetworkAdapterChange)(INetworkAdapter *aNetworkAdapter)
492 {
493 return VBOX_E_DONT_CALL_AGAIN;
494 }
495
496 STDMETHOD(OnSerialPortChange)(ISerialPort *aSerialPort)
497 {
498 return VBOX_E_DONT_CALL_AGAIN;
499 }
500
501 STDMETHOD(OnParallelPortChange)(IParallelPort *aParallelPort)
502 {
503 return VBOX_E_DONT_CALL_AGAIN;
504 }
505
506 STDMETHOD(OnVRDPServerChange)()
507 {
508 return VBOX_E_DONT_CALL_AGAIN;
509 }
510
511 STDMETHOD(OnRemoteDisplayInfoChange)()
512 {
513 return VBOX_E_DONT_CALL_AGAIN;
514 }
515
516 STDMETHOD(OnUSBControllerChange)()
517 {
518 return VBOX_E_DONT_CALL_AGAIN;
519 }
520
521 STDMETHOD(OnUSBDeviceStateChange)(IUSBDevice *aDevice, BOOL aAttached,
522 IVirtualBoxErrorInfo *aError)
523 {
524 return VBOX_E_DONT_CALL_AGAIN;
525 }
526
527 STDMETHOD(OnSharedFolderChange)(Scope_T aScope)
528 {
529 return VBOX_E_DONT_CALL_AGAIN;
530 }
531
532 STDMETHOD(OnStorageControllerChange)()
533 {
534 return VBOX_E_DONT_CALL_AGAIN;
535 }
536
537 STDMETHOD(OnMediumChange)(IMediumAttachment * /*aMediumAttachment*/)
538 {
539 return VBOX_E_DONT_CALL_AGAIN;
540 }
541
542 STDMETHOD(OnCPUChange)(ULONG /*aCPU*/, BOOL /* aRemove */)
543 {
544 return VBOX_E_DONT_CALL_AGAIN;
545 }
546
547 STDMETHOD(OnRuntimeError)(BOOL fFatal, IN_BSTR id, IN_BSTR message)
548 {
549 MachineState_T machineState;
550 gMachine->COMGETTER(State)(&machineState);
551 const char *pszType;
552 bool fPaused = machineState == MachineState_Paused;
553 if (fFatal)
554 pszType = "FATAL ERROR";
555 else if (machineState == MachineState_Paused)
556 pszType = "Non-fatal ERROR";
557 else
558 pszType = "WARNING";
559 RTPrintf("\n%s: ** %lS **\n%lS\n%s\n", pszType, id, message,
560 fPaused ? "The VM was paused. Continue with HostKey + P after you solved the problem.\n" : "");
561 return S_OK;
562 }
563
564 STDMETHOD(OnCanShowWindow)(BOOL *canShow)
565 {
566 if (!canShow)
567 return E_POINTER;
568#ifdef RT_OS_DARWIN
569 /* SDL feature not available on Quartz */
570 *canShow = TRUE;
571#else
572 SDL_SysWMinfo info;
573 SDL_VERSION(&info.version);
574 *canShow = !!SDL_GetWMInfo(&info);
575#endif
576 return S_OK;
577 }
578
579 STDMETHOD(OnShowWindow)(ULONG64 *winId)
580 {
581#ifndef RT_OS_DARWIN
582 SDL_SysWMinfo info;
583 SDL_VERSION(&info.version);
584 if (SDL_GetWMInfo(&info))
585 {
586#if defined(VBOXSDL_WITH_X11)
587 *winId = (ULONG64)info.info.x11.wmwindow;
588#elif defined(RT_OS_WINDOWS)
589 *winId = (ULONG64)info.window;
590#else
591 AssertFailed();
592 return E_FAIL;
593#endif
594 return S_OK;
595 }
596#endif /* !RT_OS_DARWIN */
597 AssertFailed();
598 return E_FAIL;
599 }
600
601 static const char *GetStateName(MachineState_T machineState)
602 {
603 switch (machineState)
604 {
605 case MachineState_Null: return "<null>";
606 case MachineState_PoweredOff: return "PoweredOff";
607 case MachineState_Saved: return "Saved";
608 case MachineState_Teleported: return "Teleported";
609 case MachineState_Aborted: return "Aborted";
610 case MachineState_Running: return "Running";
611 case MachineState_Teleporting: return "Teleporting";
612 case MachineState_LiveSnapshotting: return "LiveSnapshotting";
613 case MachineState_Paused: return "Paused";
614 case MachineState_Stuck: return "GuruMeditation";
615 case MachineState_Starting: return "Starting";
616 case MachineState_Stopping: return "Stopping";
617 case MachineState_Saving: return "Saving";
618 case MachineState_Restoring: return "Restoring";
619 case MachineState_TeleportingPausedVM: return "TeleportingPausedVM";
620 case MachineState_TeleportingIn: return "TeleportingIn";
621 case MachineState_RestoringSnapshot: return "RestoringSnapshot";
622 case MachineState_DeletingSnapshot: return "DeletingSnapshot";
623 case MachineState_SettingUp: return "SettingUp";
624 default: return "no idea";
625 }
626 }
627
628 void ignorePowerOffEvents(bool fIgnore)
629 {
630 m_fIgnorePowerOffEvents = fIgnore;
631 }
632
633private:
634#ifdef RT_OS_WINDOWS
635 long refcnt;
636#endif
637 bool m_fIgnorePowerOffEvents;
638};
639
640#ifdef VBOX_WITH_XPCOM
641NS_DECL_CLASSINFO(VBoxSDLCallback)
642NS_IMPL_ISUPPORTS1_CI(VBoxSDLCallback, IVirtualBoxCallback)
643NS_DECL_CLASSINFO(VBoxSDLConsoleCallback)
644NS_IMPL_ISUPPORTS1_CI(VBoxSDLConsoleCallback, IConsoleCallback)
645#endif /* VBOX_WITH_XPCOM */
646
647static void show_usage()
648{
649 RTPrintf("Usage:\n"
650 " --startvm <uuid|name> Virtual machine to start, either UUID or name\n"
651 " --hda <file> Set temporary first hard disk to file\n"
652 " --fda <file> Set temporary first floppy disk to file\n"
653 " --cdrom <file> Set temporary CDROM/DVD to file/device ('none' to unmount)\n"
654 " --boot <a|c|d|n> Set temporary boot device (a = floppy, c = 1st HD, d = DVD, n = network)\n"
655 " --memory <size> Set temporary memory size in megabytes\n"
656 " --vram <size> Set temporary size of video memory in megabytes\n"
657 " --fullscreen Start VM in fullscreen mode\n"
658 " --fullscreenresize Resize the guest on fullscreen\n"
659 " --fixedmode <w> <h> <bpp> Use a fixed SDL video mode with given width, height and bits per pixel\n"
660 " --nofstoggle Forbid switching to/from fullscreen mode\n"
661 " --noresize Make the SDL frame non resizable\n"
662 " --nohostkey Disable all hostkey combinations\n"
663 " --nohostkeys ... Disable specific hostkey combinations, see below for valid keys\n"
664 " --nograbonclick Disable mouse/keyboard grabbing on mouse click w/o additions\n"
665 " --detecthostkey Get the hostkey identifier and modifier state\n"
666 " --hostkey <key> {<key2>} <mod> Set the host key to the values obtained using --detecthostkey\n"
667 " --termacpi Send an ACPI power button event when closing the window\n"
668#if defined(RT_OS_LINUX)
669 " --evdevkeymap Use evdev keycode map\n"
670#endif
671#ifdef VBOX_WITH_VRDP
672 " --vrdp <ports> Listen for VRDP connections on one of specified ports (default if not specified)\n"
673#endif
674 " --discardstate Discard saved state (if present) and revert to last snapshot (if present)\n"
675#ifdef VBOX_SECURELABEL
676 " --securelabel Display a secure VM label at the top of the screen\n"
677 " --seclabelfnt TrueType (.ttf) font file for secure session label\n"
678 " --seclabelsiz Font point size for secure session label (default 12)\n"
679 " --seclabelofs Font offset within the secure label (default 0)\n"
680 " --seclabelfgcol <rgb> Secure label text color RGB value in 6 digit hexadecimal (eg: FFFF00)\n"
681 " --seclabelbgcol <rgb> Secure label background color RGB value in 6 digit hexadecimal (eg: FF0000)\n"
682#endif
683#ifdef VBOXSDL_ADVANCED_OPTIONS
684 " --[no]rawr0 Enable or disable raw ring 3\n"
685 " --[no]rawr3 Enable or disable raw ring 0\n"
686 " --[no]patm Enable or disable PATM\n"
687 " --[no]csam Enable or disable CSAM\n"
688 " --[no]hwvirtex Permit or deny the usage of VT-x/AMD-V\n"
689#endif
690 "\n"
691 "Key bindings:\n"
692 " <hostkey> + f Switch to full screen / restore to previous view\n"
693 " h Press ACPI power button\n"
694 " n Take a snapshot and continue execution\n"
695 " p Pause / resume execution\n"
696 " q Power off\n"
697 " r VM reset\n"
698 " s Save state and power off\n"
699 " <del> Send <ctrl><alt><del>\n"
700 " <F1>...<F12> Send <ctrl><alt><Fx>\n"
701#if defined(DEBUG) || defined(VBOX_WITH_STATISTICS)
702 "\n"
703 "Further key bindings useful for debugging:\n"
704 " LCtrl + Alt + F12 Reset statistics counter\n"
705 " LCtrl + Alt + F11 Dump statistics to logfile\n"
706 " Alt + F12 Toggle R0 recompiler\n"
707 " Alt + F11 Toggle R3 recompiler\n"
708 " Alt + F10 Toggle PATM\n"
709 " Alt + F9 Toggle CSAM\n"
710 " Alt + F8 Toggle single step mode\n"
711 " LCtrl/RCtrl + F12 Toggle logger\n"
712 " F12 Write log marker to logfile\n"
713#endif
714 "\n");
715}
716
717static void PrintError(const char *pszName, CBSTR pwszDescr, CBSTR pwszComponent=NULL)
718{
719 const char *pszFile, *pszFunc, *pszStat;
720 char pszBuffer[1024];
721 com::ErrorInfo info;
722
723 RTStrPrintf(pszBuffer, sizeof(pszBuffer), "%lS", pwszDescr);
724
725 RTPrintf("\n%s! Error info:\n", pszName);
726 if ( (pszFile = strstr(pszBuffer, "At '"))
727 && (pszFunc = strstr(pszBuffer, ") in "))
728 && (pszStat = strstr(pszBuffer, "VBox status code: ")))
729 RTPrintf(" %.*s %.*s\n In%.*s %s",
730 pszFile-pszBuffer, pszBuffer,
731 pszFunc-pszFile+1, pszFile,
732 pszStat-pszFunc-4, pszFunc+4,
733 pszStat);
734 else
735 RTPrintf("%s\n", pszBuffer);
736
737 if (pwszComponent)
738 RTPrintf("(component %lS).\n", pwszComponent);
739
740 RTPrintf("\n");
741}
742
743#ifdef VBOXSDL_WITH_X11
744/**
745 * Custom signal handler. Currently it is only used to release modifier
746 * keys when receiving the USR1 signal. When switching VTs, we might not
747 * get release events for Ctrl-Alt and in case a savestate is performed
748 * on the new VT, the VM will be saved with modifier keys stuck. This is
749 * annoying enough for introducing this hack.
750 */
751void signal_handler_SIGUSR1(int sig, siginfo_t *info, void *secret)
752{
753 /* only SIGUSR1 is interesting */
754 if (sig == SIGUSR1)
755 {
756 /* just release the modifiers */
757 ResetKeys();
758 }
759}
760
761/**
762 * Custom signal handler for catching exit events.
763 */
764void signal_handler_SIGINT(int sig)
765{
766 if (gpszPidFile)
767 RTFileDelete(gpszPidFile);
768 signal(SIGINT, SIG_DFL);
769 signal(SIGQUIT, SIG_DFL);
770 signal(SIGSEGV, SIG_DFL);
771 kill(getpid(), sig);
772}
773#endif /* VBOXSDL_WITH_X11 */
774
775/** entry point */
776extern "C"
777DECLEXPORT(int) TrustedMain(int argc, char **argv, char **envp)
778{
779#ifdef VBOXSDL_WITH_X11
780 /*
781 * Lock keys on SDL behave different from normal keys: A KeyPress event is generated
782 * if the lock mode gets active and a keyRelease event is genereated if the lock mode
783 * gets inactive, that is KeyPress and KeyRelease are sent when pressing the lock key
784 * to change the mode. The current lock mode is reflected in SDL_GetModState().
785 *
786 * Debian patched libSDL to make the lock keys behave like normal keys generating a
787 * KeyPress/KeyRelease event if the lock key was pressed/released. But the lock status
788 * is not reflected in the mod status anymore. We disable the Debian-specific extension
789 * to ensure a defined environment and work around the missing KeyPress/KeyRelease
790 * events in ProcessKeys().
791 */
792 RTEnvSet("SDL_DISABLE_LOCK_KEYS", "1");
793#endif
794
795 /*
796 * the hostkey detection mode is unrelated to VM processing, so handle it before
797 * we initialize anything COM related
798 */
799 if (argc == 2 && ( !strcmp(argv[1], "-detecthostkey")
800 || !strcmp(argv[1], "--detecthostkey")))
801 {
802 int rc = SDL_InitSubSystem(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_NOPARACHUTE);
803 if (rc != 0)
804 {
805 RTPrintf("Error: SDL_InitSubSystem failed with message '%s'\n", SDL_GetError());
806 return 1;
807 }
808 /* we need a video window for the keyboard stuff to work */
809 if (!SDL_SetVideoMode(640, 480, 16, SDL_SWSURFACE))
810 {
811 RTPrintf("Error: could not set SDL video mode\n");
812 return 1;
813 }
814
815 RTPrintf("Please hit one or two function key(s) to get the --hostkey value...\n");
816
817 SDL_Event event1;
818 while (SDL_WaitEvent(&event1))
819 {
820 if (event1.type == SDL_KEYDOWN)
821 {
822 SDL_Event event2;
823 unsigned mod = SDL_GetModState() & ~(KMOD_MODE | KMOD_NUM | KMOD_RESERVED);
824 while (SDL_WaitEvent(&event2))
825 {
826 if (event2.type == SDL_KEYDOWN || event2.type == SDL_KEYUP)
827 {
828 /* pressed additional host key */
829 RTPrintf("--hostkey %d", event1.key.keysym.sym);
830 if (event2.type == SDL_KEYDOWN)
831 {
832 RTPrintf(" %d", event2.key.keysym.sym);
833 RTPrintf(" %d\n", SDL_GetModState() & ~(KMOD_MODE | KMOD_NUM | KMOD_RESERVED));
834 }
835 else
836 {
837 RTPrintf(" %d\n", mod);
838 }
839 /* we're done */
840 break;
841 }
842 }
843 /* we're down */
844 break;
845 }
846 }
847 SDL_Quit();
848 return 1;
849 }
850
851 HRESULT rc;
852 int vrc;
853 Guid uuidVM;
854 char *vmName = NULL;
855 DeviceType_T bootDevice = DeviceType_Null;
856 uint32_t memorySize = 0;
857 uint32_t vramSize = 0;
858 VBoxSDLCallback *cbVBoxImpl = NULL;
859 /* wrapper around above object */
860 ComPtr<IVirtualBoxCallback> callback;
861 VBoxSDLConsoleCallback *cbConsoleImpl = NULL;
862 ComPtr<IConsoleCallback> consoleCallback;
863
864 bool fFullscreen = false;
865 bool fResizable = true;
866#ifdef USE_XPCOM_QUEUE_THREAD
867 bool fXPCOMEventThreadSignaled = false;
868#endif
869 char *hdaFile = NULL;
870 char *cdromFile = NULL;
871 char *fdaFile = NULL;
872#ifdef VBOX_WITH_VRDP
873 const char *portVRDP = NULL;
874#endif
875 bool fDiscardState = false;
876#ifdef VBOX_SECURELABEL
877 BOOL fSecureLabel = false;
878 uint32_t secureLabelPointSize = 12;
879 uint32_t secureLabelFontOffs = 0;
880 char *secureLabelFontFile = NULL;
881 uint32_t secureLabelColorFG = 0x0000FF00;
882 uint32_t secureLabelColorBG = 0x00FFFF00;
883#endif
884#ifdef VBOXSDL_ADVANCED_OPTIONS
885 unsigned fRawR0 = ~0U;
886 unsigned fRawR3 = ~0U;
887 unsigned fPATM = ~0U;
888 unsigned fCSAM = ~0U;
889 unsigned fHWVirt = ~0U;
890 uint32_t u32WarpDrive = 0;
891#endif
892#ifdef VBOX_WIN32_UI
893 bool fWin32UI = true;
894 uint64_t winId = 0;
895#endif
896 bool fShowSDLConfig = false;
897 uint32_t fixedWidth = ~(uint32_t)0;
898 uint32_t fixedHeight = ~(uint32_t)0;
899 uint32_t fixedBPP = ~(uint32_t)0;
900 uint32_t uResizeWidth = ~(uint32_t)0;
901 uint32_t uResizeHeight = ~(uint32_t)0;
902
903 /* The damned GOTOs forces this to be up here - totally out of place. */
904 /*
905 * Host key handling.
906 *
907 * The golden rule is that host-key combinations should not be seen
908 * by the guest. For instance a CAD should not have any extra RCtrl down
909 * and RCtrl up around itself. Nor should a resume be followed by a Ctrl-P
910 * that could encourage applications to start printing.
911 *
912 * We must not confuse the hostkey processing into any release sequences
913 * either, the host key is supposed to be explicitly pressing one key.
914 *
915 * Quick state diagram:
916 *
917 * host key down alone
918 * (Normal) ---------------
919 * ^ ^ |
920 * | | v host combination key down
921 * | | (Host key down) ----------------
922 * | | host key up v | |
923 * | |-------------- | other key down v host combination key down
924 * | | (host key used) -------------
925 * | | | ^ |
926 * | (not host key)-- | |---------------
927 * | | | | |
928 * | | ---- other |
929 * | modifiers = 0 v v
930 * -----------------------------------------------
931 */
932 enum HKEYSTATE
933 {
934 /** The initial and most common state, pass keystrokes to the guest.
935 * Next state: HKEYSTATE_DOWN
936 * Prev state: Any */
937 HKEYSTATE_NORMAL = 1,
938 /** The first host key was pressed down
939 */
940 HKEYSTATE_DOWN_1ST,
941 /** The second host key was pressed down (if gHostKeySym2 != SDLK_UNKNOWN)
942 */
943 HKEYSTATE_DOWN_2ND,
944 /** The host key has been pressed down.
945 * Prev state: HKEYSTATE_NORMAL
946 * Next state: HKEYSTATE_NORMAL - host key up, capture toggle.
947 * Next state: HKEYSTATE_USED - host key combination down.
948 * Next state: HKEYSTATE_NOT_IT - non-host key combination down.
949 */
950 HKEYSTATE_DOWN,
951 /** A host key combination was pressed.
952 * Prev state: HKEYSTATE_DOWN
953 * Next state: HKEYSTATE_NORMAL - when modifiers are all 0
954 */
955 HKEYSTATE_USED,
956 /** A non-host key combination was attempted. Send hostkey down to the
957 * guest and continue until all modifiers have been released.
958 * Prev state: HKEYSTATE_DOWN
959 * Next state: HKEYSTATE_NORMAL - when modifiers are all 0
960 */
961 HKEYSTATE_NOT_IT
962 } enmHKeyState = HKEYSTATE_NORMAL;
963 /** The host key down event which we have been hiding from the guest.
964 * Used when going from HKEYSTATE_DOWN to HKEYSTATE_NOT_IT. */
965 SDL_Event EvHKeyDown1;
966 SDL_Event EvHKeyDown2;
967
968 LogFlow(("SDL GUI started\n"));
969 RTPrintf(VBOX_PRODUCT " SDL GUI version %s\n"
970 "(C) 2005-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
971 "All rights reserved.\n\n",
972 VBOX_VERSION_STRING);
973
974 // less than one parameter is not possible
975 if (argc < 2)
976 {
977 show_usage();
978 return 1;
979 }
980
981 // command line argument parsing stuff
982 for (int curArg = 1; curArg < argc; curArg++)
983 {
984 if ( !strcmp(argv[curArg], "--vm")
985 || !strcmp(argv[curArg], "-vm")
986 || !strcmp(argv[curArg], "--startvm")
987 || !strcmp(argv[curArg], "-startvm")
988 || !strcmp(argv[curArg], "-s")
989 )
990 {
991 if (++curArg >= argc)
992 {
993 RTPrintf("Error: VM not specified (UUID or name)!\n");
994 return 1;
995 }
996 // first check if a UUID was supplied
997 if (RT_FAILURE(RTUuidFromStr(uuidVM.ptr(), argv[curArg])))
998 {
999 LogFlow(("invalid UUID format, assuming it's a VM name\n"));
1000 vmName = argv[curArg];
1001 }
1002 }
1003 else if ( !strcmp(argv[curArg], "--comment")
1004 || !strcmp(argv[curArg], "-comment"))
1005 {
1006 if (++curArg >= argc)
1007 {
1008 RTPrintf("Error: missing argument for comment!\n");
1009 return 1;
1010 }
1011 }
1012 else if ( !strcmp(argv[curArg], "--boot")
1013 || !strcmp(argv[curArg], "-boot"))
1014 {
1015 if (++curArg >= argc)
1016 {
1017 RTPrintf("Error: missing argument for boot drive!\n");
1018 return 1;
1019 }
1020 switch (argv[curArg][0])
1021 {
1022 case 'a':
1023 {
1024 bootDevice = DeviceType_Floppy;
1025 break;
1026 }
1027
1028 case 'c':
1029 {
1030 bootDevice = DeviceType_HardDisk;
1031 break;
1032 }
1033
1034 case 'd':
1035 {
1036 bootDevice = DeviceType_DVD;
1037 break;
1038 }
1039
1040 case 'n':
1041 {
1042 bootDevice = DeviceType_Network;
1043 break;
1044 }
1045
1046 default:
1047 {
1048 RTPrintf("Error: wrong argument for boot drive!\n");
1049 return 1;
1050 }
1051 }
1052 }
1053 else if ( !strcmp(argv[curArg], "--memory")
1054 || !strcmp(argv[curArg], "-memory")
1055 || !strcmp(argv[curArg], "-m"))
1056 {
1057 if (++curArg >= argc)
1058 {
1059 RTPrintf("Error: missing argument for memory size!\n");
1060 return 1;
1061 }
1062 memorySize = atoi(argv[curArg]);
1063 }
1064 else if ( !strcmp(argv[curArg], "--vram")
1065 || !strcmp(argv[curArg], "-vram"))
1066 {
1067 if (++curArg >= argc)
1068 {
1069 RTPrintf("Error: missing argument for vram size!\n");
1070 return 1;
1071 }
1072 vramSize = atoi(argv[curArg]);
1073 }
1074 else if ( !strcmp(argv[curArg], "--fullscreen")
1075 || !strcmp(argv[curArg], "-fullscreen"))
1076 {
1077 fFullscreen = true;
1078 }
1079 else if ( !strcmp(argv[curArg], "--fullscreenresize")
1080 || !strcmp(argv[curArg], "-fullscreenresize"))
1081 {
1082 gfFullscreenResize = true;
1083#ifdef VBOXSDL_WITH_X11
1084 RTEnvSet("SDL_VIDEO_X11_VIDMODE", "0");
1085#endif
1086 }
1087 else if ( !strcmp(argv[curArg], "--fixedmode")
1088 || !strcmp(argv[curArg], "-fixedmode"))
1089 {
1090 /* three parameters follow */
1091 if (curArg + 3 >= argc)
1092 {
1093 RTPrintf("Error: missing arguments for fixed video mode!\n");
1094 return 1;
1095 }
1096 fixedWidth = atoi(argv[++curArg]);
1097 fixedHeight = atoi(argv[++curArg]);
1098 fixedBPP = atoi(argv[++curArg]);
1099 }
1100 else if ( !strcmp(argv[curArg], "--nofstoggle")
1101 || !strcmp(argv[curArg], "-nofstoggle"))
1102 {
1103 gfAllowFullscreenToggle = FALSE;
1104 }
1105 else if ( !strcmp(argv[curArg], "--noresize")
1106 || !strcmp(argv[curArg], "-noresize"))
1107 {
1108 fResizable = false;
1109 }
1110 else if ( !strcmp(argv[curArg], "--nohostkey")
1111 || !strcmp(argv[curArg], "-nohostkey"))
1112 {
1113 gHostKeyMod = 0;
1114 gHostKeySym1 = 0;
1115 }
1116 else if ( !strcmp(argv[curArg], "--nohostkeys")
1117 || !strcmp(argv[curArg], "-nohostkeys"))
1118 {
1119 if (++curArg >= argc)
1120 {
1121 RTPrintf("Error: missing a string of disabled hostkey combinations\n");
1122 return 1;
1123 }
1124 gHostKeyDisabledCombinations = argv[curArg];
1125 size_t cch = strlen(gHostKeyDisabledCombinations);
1126 for (size_t i = 0; i < cch; i++)
1127 {
1128 if (!strchr("fhnpqrs", gHostKeyDisabledCombinations[i]))
1129 {
1130 RTPrintf("Error: <hostkey> + '%c' is not a valid combination\n",
1131 gHostKeyDisabledCombinations[i]);
1132 return 1;
1133 }
1134 }
1135 }
1136 else if ( !strcmp(argv[curArg], "--nograbonclick")
1137 || !strcmp(argv[curArg], "-nograbonclick"))
1138 {
1139 gfGrabOnMouseClick = FALSE;
1140 }
1141 else if ( !strcmp(argv[curArg], "--termacpi")
1142 || !strcmp(argv[curArg], "-termacpi"))
1143 {
1144 gfACPITerm = TRUE;
1145 }
1146 else if ( !strcmp(argv[curArg], "--pidfile")
1147 || !strcmp(argv[curArg], "-pidfile"))
1148 {
1149 if (++curArg >= argc)
1150 {
1151 RTPrintf("Error: missing file name for --pidfile!\n");
1152 return 1;
1153 }
1154 gpszPidFile = argv[curArg];
1155 }
1156 else if ( !strcmp(argv[curArg], "--hda")
1157 || !strcmp(argv[curArg], "-hda"))
1158 {
1159 if (++curArg >= argc)
1160 {
1161 RTPrintf("Error: missing file name for first hard disk!\n");
1162 return 1;
1163 }
1164 /* resolve it. */
1165 if (RTPathExists(argv[curArg]))
1166 hdaFile = RTPathRealDup(argv[curArg]);
1167 if (!hdaFile)
1168 {
1169 RTPrintf("Error: The path to the specified harddisk, '%s', could not be resolved.\n", argv[curArg]);
1170 return 1;
1171 }
1172 }
1173 else if ( !strcmp(argv[curArg], "--fda")
1174 || !strcmp(argv[curArg], "-fda"))
1175 {
1176 if (++curArg >= argc)
1177 {
1178 RTPrintf("Error: missing file/device name for first floppy disk!\n");
1179 return 1;
1180 }
1181 /* resolve it. */
1182 if (RTPathExists(argv[curArg]))
1183 fdaFile = RTPathRealDup(argv[curArg]);
1184 if (!fdaFile)
1185 {
1186 RTPrintf("Error: The path to the specified floppy disk, '%s', could not be resolved.\n", argv[curArg]);
1187 return 1;
1188 }
1189 }
1190 else if ( !strcmp(argv[curArg], "--cdrom")
1191 || !strcmp(argv[curArg], "-cdrom"))
1192 {
1193 if (++curArg >= argc)
1194 {
1195 RTPrintf("Error: missing file/device name for cdrom!\n");
1196 return 1;
1197 }
1198 /* resolve it. */
1199 if (RTPathExists(argv[curArg]))
1200 cdromFile = RTPathRealDup(argv[curArg]);
1201 if (!cdromFile)
1202 {
1203 RTPrintf("Error: The path to the specified cdrom, '%s', could not be resolved.\n", argv[curArg]);
1204 return 1;
1205 }
1206 }
1207#if defined(RT_OS_LINUX) && defined(VBOXSDL_WITH_X11)
1208 else if ( !strcmp(argv[curArg], "--evdevkeymap")
1209 || !strcmp(argv[curArg], "-evdevkeymap"))
1210 {
1211 guseEvdevKeymap = TRUE;
1212 }
1213#endif /* RT_OS_LINUX */
1214#ifdef VBOX_WITH_VRDP
1215 else if ( !strcmp(argv[curArg], "--vrdp")
1216 || !strcmp(argv[curArg], "-vrdp"))
1217 {
1218 // start with the standard VRDP port
1219 portVRDP = "0";
1220
1221 // is there another argument
1222 if (argc > (curArg + 1))
1223 {
1224 curArg++;
1225 portVRDP = argv[curArg];
1226 LogFlow(("Using non standard VRDP port %s\n", portVRDP));
1227 }
1228 }
1229#endif /* VBOX_WITH_VRDP */
1230 else if ( !strcmp(argv[curArg], "--discardstate")
1231 || !strcmp(argv[curArg], "-discardstate"))
1232 {
1233 fDiscardState = true;
1234 }
1235#ifdef VBOX_SECURELABEL
1236 else if ( !strcmp(argv[curArg], "--securelabel")
1237 || !strcmp(argv[curArg], "-securelabel"))
1238 {
1239 fSecureLabel = true;
1240 LogFlow(("Secure labelling turned on\n"));
1241 }
1242 else if ( !strcmp(argv[curArg], "--seclabelfnt")
1243 || !strcmp(argv[curArg], "-seclabelfnt"))
1244 {
1245 if (++curArg >= argc)
1246 {
1247 RTPrintf("Error: missing font file name for secure label!\n");
1248 return 1;
1249 }
1250 secureLabelFontFile = argv[curArg];
1251 }
1252 else if ( !strcmp(argv[curArg], "--seclabelsiz")
1253 || !strcmp(argv[curArg], "-seclabelsiz"))
1254 {
1255 if (++curArg >= argc)
1256 {
1257 RTPrintf("Error: missing font point size for secure label!\n");
1258 return 1;
1259 }
1260 secureLabelPointSize = atoi(argv[curArg]);
1261 }
1262 else if ( !strcmp(argv[curArg], "--seclabelofs")
1263 || !strcmp(argv[curArg], "-seclabelofs"))
1264 {
1265 if (++curArg >= argc)
1266 {
1267 RTPrintf("Error: missing font pixel offset for secure label!\n");
1268 return 1;
1269 }
1270 secureLabelFontOffs = atoi(argv[curArg]);
1271 }
1272 else if ( !strcmp(argv[curArg], "--seclabelfgcol")
1273 || !strcmp(argv[curArg], "-seclabelfgcol"))
1274 {
1275 if (++curArg >= argc)
1276 {
1277 RTPrintf("Error: missing text color value for secure label!\n");
1278 return 1;
1279 }
1280 sscanf(argv[curArg], "%X", &secureLabelColorFG);
1281 }
1282 else if ( !strcmp(argv[curArg], "--seclabelbgcol")
1283 || !strcmp(argv[curArg], "-seclabelbgcol"))
1284 {
1285 if (++curArg >= argc)
1286 {
1287 RTPrintf("Error: missing background color value for secure label!\n");
1288 return 1;
1289 }
1290 sscanf(argv[curArg], "%X", &secureLabelColorBG);
1291 }
1292#endif
1293#ifdef VBOXSDL_ADVANCED_OPTIONS
1294 else if ( !strcmp(argv[curArg], "--rawr0")
1295 || !strcmp(argv[curArg], "-rawr0"))
1296 fRawR0 = true;
1297 else if ( !strcmp(argv[curArg], "--norawr0")
1298 || !strcmp(argv[curArg], "-norawr0"))
1299 fRawR0 = false;
1300 else if ( !strcmp(argv[curArg], "--rawr3")
1301 || !strcmp(argv[curArg], "-rawr3"))
1302 fRawR3 = true;
1303 else if ( !strcmp(argv[curArg], "--norawr3")
1304 || !strcmp(argv[curArg], "-norawr3"))
1305 fRawR3 = false;
1306 else if ( !strcmp(argv[curArg], "--patm")
1307 || !strcmp(argv[curArg], "-patm"))
1308 fPATM = true;
1309 else if ( !strcmp(argv[curArg], "--nopatm")
1310 || !strcmp(argv[curArg], "-nopatm"))
1311 fPATM = false;
1312 else if ( !strcmp(argv[curArg], "--csam")
1313 || !strcmp(argv[curArg], "-csam"))
1314 fCSAM = true;
1315 else if ( !strcmp(argv[curArg], "--nocsam")
1316 || !strcmp(argv[curArg], "-nocsam"))
1317 fCSAM = false;
1318 else if ( !strcmp(argv[curArg], "--hwvirtex")
1319 || !strcmp(argv[curArg], "-hwvirtex"))
1320 fHWVirt = true;
1321 else if ( !strcmp(argv[curArg], "--nohwvirtex")
1322 || !strcmp(argv[curArg], "-nohwvirtex"))
1323 fHWVirt = false;
1324 else if ( !strcmp(argv[curArg], "--warpdrive")
1325 || !strcmp(argv[curArg], "-warpdrive"))
1326 {
1327 if (++curArg >= argc)
1328 {
1329 RTPrintf("Error: missing the rate value for the --warpdrive option!\n");
1330 return 1;
1331 }
1332 u32WarpDrive = RTStrToUInt32(argv[curArg]);
1333 if (u32WarpDrive < 2 || u32WarpDrive > 20000)
1334 {
1335 RTPrintf("Error: the warp drive rate is restricted to [2..20000]. (%d)\n", u32WarpDrive);
1336 return 1;
1337 }
1338 }
1339#endif /* VBOXSDL_ADVANCED_OPTIONS */
1340#ifdef VBOX_WIN32_UI
1341 else if ( !strcmp(argv[curArg], "--win32ui")
1342 || !strcmp(argv[curArg], "-win32ui"))
1343 fWin32UI = true;
1344#endif
1345 else if ( !strcmp(argv[curArg], "--showsdlconfig")
1346 || !strcmp(argv[curArg], "-showsdlconfig"))
1347 fShowSDLConfig = true;
1348 else if ( !strcmp(argv[curArg], "--hostkey")
1349 || !strcmp(argv[curArg], "-hostkey"))
1350 {
1351 if (++curArg + 1 >= argc)
1352 {
1353 RTPrintf("Error: not enough arguments for host keys!\n");
1354 return 1;
1355 }
1356 gHostKeySym1 = atoi(argv[curArg++]);
1357 if (curArg + 1 < argc && (argv[curArg+1][0] == '0' || atoi(argv[curArg+1]) > 0))
1358 {
1359 /* two-key sequence as host key specified */
1360 gHostKeySym2 = atoi(argv[curArg++]);
1361 }
1362 gHostKeyMod = atoi(argv[curArg]);
1363 }
1364 /* just show the help screen */
1365 else
1366 {
1367 if ( strcmp(argv[curArg], "-h")
1368 && strcmp(argv[curArg], "-help")
1369 && strcmp(argv[curArg], "--help"))
1370 RTPrintf("Error: unrecognized switch '%s'\n", argv[curArg]);
1371 show_usage();
1372 return 1;
1373 }
1374 }
1375
1376 rc = com::Initialize();
1377 if (FAILED(rc))
1378 {
1379 RTPrintf("Error: COM initialization failed, rc = 0x%x!\n", rc);
1380 return 1;
1381 }
1382
1383 /* NOTE: do not convert the following scope to a "do {} while (0);", as
1384 * this would make it all too tempting to use "break;" incorrectly - it
1385 * would skip over the cleanup. */
1386 {
1387 // scopes all the stuff till shutdown
1388 ////////////////////////////////////////////////////////////////////////////
1389
1390 ComPtr <IVirtualBox> virtualBox;
1391 ComPtr <ISession> session;
1392 bool sessionOpened = false;
1393 EventQueue* eventQ = com::EventQueue::getMainEventQueue();
1394 const CLSID sessionID = CLSID_Session;
1395
1396 rc = virtualBox.createLocalObject(CLSID_VirtualBox);
1397 if (FAILED(rc))
1398 {
1399 com::ErrorInfo info;
1400 if (info.isFullAvailable())
1401 PrintError("Failed to create VirtualBox object",
1402 info.getText().raw(), info.getComponent().raw());
1403 else
1404 RTPrintf("Failed to create VirtualBox object! No error information available (rc = 0x%x).\n", rc);
1405 goto leave;
1406 }
1407 rc = session.createInprocObject(sessionID);
1408 if (FAILED(rc))
1409 {
1410 RTPrintf("Failed to create session object, rc = 0x%x!\n", rc);
1411 goto leave;
1412 }
1413
1414 /*
1415 * Do we have a name but no UUID?
1416 */
1417 if (vmName && uuidVM.isEmpty())
1418 {
1419 ComPtr<IMachine> aMachine;
1420 Bstr bstrVMName = vmName;
1421 rc = virtualBox->FindMachine(bstrVMName, aMachine.asOutParam());
1422 if ((rc == S_OK) && aMachine)
1423 {
1424 Bstr id;
1425 aMachine->COMGETTER(Id)(id.asOutParam());
1426 uuidVM = Guid(id);
1427 }
1428 else
1429 {
1430 RTPrintf("Error: machine with the given ID not found!\n");
1431 goto leave;
1432 }
1433 }
1434 else if (uuidVM.isEmpty())
1435 {
1436 RTPrintf("Error: no machine specified!\n");
1437 goto leave;
1438 }
1439
1440 /* create SDL event semaphore */
1441 vrc = RTSemEventCreate(&g_EventSemSDLEvents);
1442 AssertReleaseRC(vrc);
1443
1444 rc = virtualBox->OpenSession(session, uuidVM.toUtf16());
1445 if (FAILED(rc))
1446 {
1447 com::ErrorInfo info;
1448 if (info.isFullAvailable())
1449 PrintError("Could not open VirtualBox session",
1450 info.getText().raw(), info.getComponent().raw());
1451 goto leave;
1452 }
1453 if (!session)
1454 {
1455 RTPrintf("Could not open VirtualBox session!\n");
1456 goto leave;
1457 }
1458 sessionOpened = true;
1459 // get the VM we're dealing with
1460 session->COMGETTER(Machine)(gMachine.asOutParam());
1461 if (!gMachine)
1462 {
1463 com::ErrorInfo info;
1464 if (info.isFullAvailable())
1465 PrintError("Cannot start VM!",
1466 info.getText().raw(), info.getComponent().raw());
1467 else
1468 RTPrintf("Error: given machine not found!\n");
1469 goto leave;
1470 }
1471 // get the VM console
1472 session->COMGETTER(Console)(gConsole.asOutParam());
1473 if (!gConsole)
1474 {
1475 RTPrintf("Given console not found!\n");
1476 goto leave;
1477 }
1478
1479 /*
1480 * Are we supposed to use a different hard disk file?
1481 */
1482 if (hdaFile)
1483 {
1484 /*
1485 * Strategy: iterate through all registered hard disk
1486 * and see if one of them points to the same file. If
1487 * so, assign it. If not, register a new image and assign
1488 * it to the VM.
1489 */
1490 Bstr hdaFileBstr = hdaFile;
1491 ComPtr<IMedium> hardDisk;
1492 virtualBox->FindHardDisk(hdaFileBstr, hardDisk.asOutParam());
1493 if (!hardDisk)
1494 {
1495 /* we've not found the image */
1496 RTPrintf("Adding hard disk '%S'...\n", hdaFile);
1497 virtualBox->OpenHardDisk(hdaFileBstr, AccessMode_ReadWrite, false, Bstr(""), false, Bstr(""), hardDisk.asOutParam());
1498 }
1499 /* do we have the right image now? */
1500 if (hardDisk)
1501 {
1502 /*
1503 * Go and attach it!
1504 */
1505 Bstr uuidHD;
1506 Bstr storageCtlName;
1507 hardDisk->COMGETTER(Id)(uuidHD.asOutParam());
1508
1509 /* get the first IDE controller to attach the harddisk to
1510 * and if there is none, add one temporarily
1511 */
1512 {
1513 ComPtr<IStorageController> storageCtl;
1514 com::SafeIfaceArray<IStorageController> aStorageControllers;
1515 CHECK_ERROR(gMachine, COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(aStorageControllers)));
1516 for (size_t i = 0; i < aStorageControllers.size(); ++ i)
1517 {
1518 StorageBus_T storageBus = StorageBus_Null;
1519
1520 CHECK_ERROR(aStorageControllers[i], COMGETTER(Bus)(&storageBus));
1521 if (storageBus == StorageBus_IDE)
1522 {
1523 storageCtl = aStorageControllers[i];
1524 break;
1525 }
1526 }
1527
1528 if (storageCtl)
1529 {
1530 CHECK_ERROR(storageCtl, COMGETTER(Name)(storageCtlName.asOutParam()));
1531 gMachine->DetachDevice(storageCtlName, 0, 0);
1532 }
1533 else
1534 {
1535 storageCtlName = "IDE Controller";
1536 CHECK_ERROR(gMachine, AddStorageController(storageCtlName,
1537 StorageBus_IDE,
1538 storageCtl.asOutParam()));
1539 }
1540 }
1541
1542 gMachine->AttachDevice(storageCtlName, 0, 0, DeviceType_HardDisk, uuidHD);
1543 /// @todo why is this attachment saved?
1544 }
1545 else
1546 {
1547 RTPrintf("Error: failed to mount the specified hard disk image!\n");
1548 goto leave;
1549 }
1550 }
1551
1552 /*
1553 * Mount a floppy if requested.
1554 */
1555 if (fdaFile)
1556 do
1557 {
1558 ComPtr<IMedium> floppyMedium;
1559
1560 /* unmount? */
1561 if (!strcmp(fdaFile, "none"))
1562 {
1563 /* nothing to do, NULL object will cause unmount */
1564 }
1565 else
1566 {
1567 Bstr medium = fdaFile;
1568
1569 /* Assume it's a host drive name */
1570 ComPtr <IHost> host;
1571 CHECK_ERROR_BREAK(virtualBox, COMGETTER(Host)(host.asOutParam()));
1572 rc = host->FindHostFloppyDrive(medium, floppyMedium.asOutParam());
1573 if (FAILED(rc))
1574 {
1575 /* try to find an existing one */
1576 rc = virtualBox->FindFloppyImage(medium, floppyMedium.asOutParam());
1577 if (FAILED(rc))
1578 {
1579 /* try to add to the list */
1580 RTPrintf("Adding floppy image '%S'...\n", fdaFile);
1581 CHECK_ERROR_BREAK(virtualBox, OpenFloppyImage(medium, Bstr(),
1582 floppyMedium.asOutParam()));
1583 }
1584 }
1585 }
1586
1587 Bstr id;
1588 Bstr storageCtlName;
1589 floppyMedium->COMGETTER(Id)(id.asOutParam());
1590
1591 /* get the first floppy controller to attach the floppy to
1592 * and if there is none, add one temporarily
1593 */
1594 {
1595 ComPtr<IStorageController> storageCtl;
1596 com::SafeIfaceArray<IStorageController> aStorageControllers;
1597 CHECK_ERROR(gMachine, COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(aStorageControllers)));
1598 for (size_t i = 0; i < aStorageControllers.size(); ++ i)
1599 {
1600 StorageBus_T storageBus = StorageBus_Null;
1601
1602 CHECK_ERROR(aStorageControllers[i], COMGETTER(Bus)(&storageBus));
1603 if (storageBus == StorageBus_Floppy)
1604 {
1605 storageCtl = aStorageControllers[i];
1606 break;
1607 }
1608 }
1609
1610 if (storageCtl)
1611 {
1612 ComPtr<IMediumAttachment> floppyAttachment;
1613
1614 CHECK_ERROR(storageCtl, COMGETTER(Name)(storageCtlName.asOutParam()));
1615 rc = gMachine->GetMediumAttachment(storageCtlName, 0, 0, floppyAttachment.asOutParam());
1616 if (FAILED(rc))
1617 CHECK_ERROR(gMachine, AttachDevice(storageCtlName, 0, 0,
1618 DeviceType_Floppy, NULL));
1619 }
1620 else
1621 {
1622 storageCtlName = "Floppy Controller";
1623 CHECK_ERROR(gMachine, AddStorageController(storageCtlName,
1624 StorageBus_Floppy,
1625 storageCtl.asOutParam()));
1626 CHECK_ERROR(gMachine, AttachDevice(storageCtlName, 0, 0,
1627 DeviceType_Floppy, NULL));
1628 }
1629 }
1630
1631 CHECK_ERROR(gMachine, MountMedium(storageCtlName, 0, 0, id, FALSE /* aForce */));
1632 }
1633 while (0);
1634 if (FAILED(rc))
1635 goto leave;
1636
1637 /*
1638 * Mount a CD-ROM if requested.
1639 */
1640 if (cdromFile)
1641 do
1642 {
1643 ComPtr<IMedium> dvdMedium;
1644
1645 /* unmount? */
1646 if (!strcmp(cdromFile, "none"))
1647 {
1648 /* nothing to do, NULL object will cause unmount */
1649 }
1650 else
1651 {
1652 Bstr medium = cdromFile;
1653
1654 /* Assume it's a host drive name */
1655 ComPtr <IHost> host;
1656 CHECK_ERROR_BREAK(virtualBox, COMGETTER(Host)(host.asOutParam()));
1657 rc = host->FindHostDVDDrive(medium,dvdMedium.asOutParam());
1658 if (FAILED(rc))
1659 {
1660 /* try to find an existing one */
1661 rc = virtualBox->FindDVDImage(medium, dvdMedium.asOutParam());
1662 if (FAILED(rc))
1663 {
1664 /* try to add to the list */
1665 RTPrintf("Adding ISO image '%S'...\n", cdromFile);
1666 CHECK_ERROR_BREAK(virtualBox, OpenDVDImage(medium, Bstr(),
1667 dvdMedium.asOutParam()));
1668 }
1669 }
1670 }
1671
1672 Bstr id;
1673 Bstr storageCtlName;
1674 dvdMedium->COMGETTER(Id)(id.asOutParam());
1675
1676 /* get the first IDE controller to attach the DVD Drive to
1677 * and if there is none, add one temporarily
1678 */
1679 {
1680 ComPtr<IStorageController> storageCtl;
1681 com::SafeIfaceArray<IStorageController> aStorageControllers;
1682 CHECK_ERROR(gMachine, COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(aStorageControllers)));
1683 for (size_t i = 0; i < aStorageControllers.size(); ++ i)
1684 {
1685 StorageBus_T storageBus = StorageBus_Null;
1686
1687 CHECK_ERROR(aStorageControllers[i], COMGETTER(Bus)(&storageBus));
1688 if (storageBus == StorageBus_IDE)
1689 {
1690 storageCtl = aStorageControllers[i];
1691 break;
1692 }
1693 }
1694
1695 if (storageCtl)
1696 {
1697 ComPtr<IMediumAttachment> dvdAttachment;
1698
1699 CHECK_ERROR(storageCtl, COMGETTER(Name)(storageCtlName.asOutParam()));
1700 gMachine->DetachDevice(storageCtlName, 1, 0);
1701 CHECK_ERROR(gMachine, AttachDevice(storageCtlName, 1, 0,
1702 DeviceType_DVD, NULL));
1703 }
1704 else
1705 {
1706 storageCtlName = "IDE Controller";
1707 CHECK_ERROR(gMachine, AddStorageController(storageCtlName,
1708 StorageBus_IDE,
1709 storageCtl.asOutParam()));
1710 CHECK_ERROR(gMachine, AttachDevice(storageCtlName, 1, 0,
1711 DeviceType_DVD, NULL));
1712 }
1713 }
1714
1715 CHECK_ERROR(gMachine, MountMedium(storageCtlName, 1, 0, id, FALSE /*aForce */));
1716 }
1717 while (0);
1718 if (FAILED(rc))
1719 goto leave;
1720
1721 if (fDiscardState)
1722 {
1723 /*
1724 * If the machine is currently saved,
1725 * discard the saved state first.
1726 */
1727 MachineState_T machineState;
1728 gMachine->COMGETTER(State)(&machineState);
1729 if (machineState == MachineState_Saved)
1730 {
1731 CHECK_ERROR(gConsole, ForgetSavedState(true));
1732 }
1733 /*
1734 * If there are snapshots, discard the current state,
1735 * i.e. revert to the last snapshot.
1736 */
1737 ULONG cSnapshots;
1738 gMachine->COMGETTER(SnapshotCount)(&cSnapshots);
1739 if (cSnapshots)
1740 {
1741 gProgress = NULL;
1742
1743 ComPtr<ISnapshot> pCurrentSnapshot;
1744 CHECK_ERROR(gMachine, COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam()));
1745 if (FAILED(rc))
1746 goto leave;
1747
1748 CHECK_ERROR(gConsole, RestoreSnapshot(pCurrentSnapshot, gProgress.asOutParam()));
1749 rc = gProgress->WaitForCompletion(-1);
1750 }
1751 }
1752
1753 // get the machine debugger (does not have to be there)
1754 gConsole->COMGETTER(Debugger)(gMachineDebugger.asOutParam());
1755 if (gMachineDebugger)
1756 {
1757 Log(("Machine debugger available!\n"));
1758 }
1759 gConsole->COMGETTER(Display)(gDisplay.asOutParam());
1760 if (!gDisplay)
1761 {
1762 RTPrintf("Error: could not get display object!\n");
1763 goto leave;
1764 }
1765
1766 // set the boot drive
1767 if (bootDevice != DeviceType_Null)
1768 {
1769 rc = gMachine->SetBootOrder(1, bootDevice);
1770 if (rc != S_OK)
1771 {
1772 RTPrintf("Error: could not set boot device, using default.\n");
1773 }
1774 }
1775
1776 // set the memory size if not default
1777 if (memorySize)
1778 {
1779 rc = gMachine->COMSETTER(MemorySize)(memorySize);
1780 if (rc != S_OK)
1781 {
1782 ULONG ramSize = 0;
1783 gMachine->COMGETTER(MemorySize)(&ramSize);
1784 RTPrintf("Error: could not set memory size, using current setting of %d MBytes\n", ramSize);
1785 }
1786 }
1787
1788 if (vramSize)
1789 {
1790 rc = gMachine->COMSETTER(VRAMSize)(vramSize);
1791 if (rc != S_OK)
1792 {
1793 gMachine->COMGETTER(VRAMSize)((ULONG*)&vramSize);
1794 RTPrintf("Error: could not set VRAM size, using current setting of %d MBytes\n", vramSize);
1795 }
1796 }
1797
1798 // we're always able to process absolute mouse events and we prefer that
1799 gfAbsoluteMouseHost = TRUE;
1800
1801#ifdef VBOX_WIN32_UI
1802 if (fWin32UI)
1803 {
1804 /* initialize the Win32 user interface inside which SDL will be embedded */
1805 if (initUI(fResizable, winId))
1806 return 1;
1807 }
1808#endif
1809
1810 /* static initialization of the SDL stuff */
1811 if (!VBoxSDLFB::init(fShowSDLConfig))
1812 goto leave;
1813
1814 gMachine->COMGETTER(MonitorCount)(&gcMonitors);
1815 if (gcMonitors > 64)
1816 gcMonitors = 64;
1817
1818 for (unsigned i = 0; i < gcMonitors; i++)
1819 {
1820 // create our SDL framebuffer instance
1821 gpFramebuffer[i] = new VBoxSDLFB(i, fFullscreen, fResizable, fShowSDLConfig, false,
1822 fixedWidth, fixedHeight, fixedBPP);
1823
1824 if (!gpFramebuffer[i])
1825 {
1826 RTPrintf("Error: could not create framebuffer object!\n");
1827 goto leave;
1828 }
1829 }
1830
1831#ifdef VBOX_WIN32_UI
1832 gpFramebuffer[0]->setWinId(winId);
1833#endif
1834
1835 for (unsigned i = 0; i < gcMonitors; i++)
1836 {
1837 if (!gpFramebuffer[i]->initialized())
1838 goto leave;
1839 gpFramebuffer[i]->AddRef();
1840 if (fFullscreen)
1841 SetFullscreen(true);
1842 }
1843
1844#ifdef VBOX_SECURELABEL
1845 if (fSecureLabel)
1846 {
1847 if (!secureLabelFontFile)
1848 {
1849 RTPrintf("Error: no font file specified for secure label!\n");
1850 goto leave;
1851 }
1852 /* load the SDL_ttf library and get the required imports */
1853 vrc = RTLdrLoad(LIBSDL_TTF_NAME, &gLibrarySDL_ttf);
1854 if (RT_SUCCESS(vrc))
1855 vrc = RTLdrGetSymbol(gLibrarySDL_ttf, "TTF_Init", (void**)&pTTF_Init);
1856 if (RT_SUCCESS(vrc))
1857 vrc = RTLdrGetSymbol(gLibrarySDL_ttf, "TTF_OpenFont", (void**)&pTTF_OpenFont);
1858 if (RT_SUCCESS(vrc))
1859 vrc = RTLdrGetSymbol(gLibrarySDL_ttf, "TTF_RenderUTF8_Solid", (void**)&pTTF_RenderUTF8_Solid);
1860 if (RT_SUCCESS(vrc))
1861 {
1862 /* silently ignore errors here */
1863 vrc = RTLdrGetSymbol(gLibrarySDL_ttf, "TTF_RenderUTF8_Blended", (void**)&pTTF_RenderUTF8_Blended);
1864 if (RT_FAILURE(vrc))
1865 pTTF_RenderUTF8_Blended = NULL;
1866 vrc = VINF_SUCCESS;
1867 }
1868 if (RT_SUCCESS(vrc))
1869 vrc = RTLdrGetSymbol(gLibrarySDL_ttf, "TTF_CloseFont", (void**)&pTTF_CloseFont);
1870 if (RT_SUCCESS(vrc))
1871 vrc = RTLdrGetSymbol(gLibrarySDL_ttf, "TTF_Quit", (void**)&pTTF_Quit);
1872 if (RT_SUCCESS(vrc))
1873 vrc = gpFramebuffer[0]->initSecureLabel(SECURE_LABEL_HEIGHT, secureLabelFontFile, secureLabelPointSize, secureLabelFontOffs);
1874 if (RT_FAILURE(vrc))
1875 {
1876 RTPrintf("Error: could not initialize secure labeling: rc = %Rrc\n", vrc);
1877 goto leave;
1878 }
1879 Bstr key = VBOXSDL_SECURELABEL_EXTRADATA;
1880 Bstr label;
1881 gMachine->GetExtraData(key, label.asOutParam());
1882 Utf8Str labelUtf8 = label;
1883 /*
1884 * Now update the label
1885 */
1886 gpFramebuffer[0]->setSecureLabelColor(secureLabelColorFG, secureLabelColorBG);
1887 gpFramebuffer[0]->setSecureLabelText(labelUtf8.raw());
1888 }
1889#endif
1890
1891#ifdef VBOXSDL_WITH_X11
1892 /* NOTE1: We still want Ctrl-C to work, so we undo the SDL redirections.
1893 * NOTE2: We have to remove the PidFile if this file exists. */
1894 signal(SIGINT, signal_handler_SIGINT);
1895 signal(SIGQUIT, signal_handler_SIGINT);
1896 signal(SIGSEGV, signal_handler_SIGINT);
1897#endif
1898
1899
1900 for (ULONG i = 0; i < gcMonitors; i++)
1901 {
1902 // register our framebuffer
1903 rc = gDisplay->SetFramebuffer(i, gpFramebuffer[i]);
1904 if (FAILED(rc))
1905 {
1906 RTPrintf("Error: could not register framebuffer object!\n");
1907 goto leave;
1908 }
1909 IFramebuffer *dummyFb;
1910 LONG xOrigin, yOrigin;
1911 rc = gDisplay->GetFramebuffer(i, &dummyFb, &xOrigin, &yOrigin);
1912 gpFramebuffer[i]->setOrigin(xOrigin, yOrigin);
1913 }
1914
1915 // register a callback for global events
1916 cbVBoxImpl = new VBoxSDLCallback();
1917 rc = createCallbackWrapper((IVirtualBoxCallback*)cbVBoxImpl, callback.asOutParam());
1918 if (FAILED(rc))
1919 goto leave;
1920 virtualBox->RegisterCallback(callback);
1921
1922 // register a callback for machine events
1923 cbConsoleImpl = new VBoxSDLConsoleCallback();
1924 rc = createCallbackWrapper((IConsoleCallback*)cbConsoleImpl, consoleCallback.asOutParam());
1925 if (FAILED(rc))
1926 goto leave;
1927 gConsole->RegisterCallback(consoleCallback);
1928 // until we've tried to to start the VM, ignore power off events
1929 cbConsoleImpl->ignorePowerOffEvents(true);
1930
1931#ifdef VBOX_WITH_VRDP
1932 if (portVRDP)
1933 {
1934 rc = gMachine->COMGETTER(VRDPServer)(gVrdpServer.asOutParam());
1935 AssertMsg((rc == S_OK) && gVrdpServer, ("Could not get VRDP Server! rc = 0x%x\n", rc));
1936 if (gVrdpServer)
1937 {
1938 // has a non standard VRDP port been requested?
1939 if (portVRDP > 0)
1940 {
1941 Bstr bstr = portVRDP;
1942 rc = gVrdpServer->COMSETTER(Ports)(bstr);
1943 if (rc != S_OK)
1944 {
1945 RTPrintf("Error: could not set VRDP port! rc = 0x%x\n", rc);
1946 goto leave;
1947 }
1948 }
1949 // now enable VRDP
1950 rc = gVrdpServer->COMSETTER(Enabled)(TRUE);
1951 if (rc != S_OK)
1952 {
1953 RTPrintf("Error: could not enable VRDP server! rc = 0x%x\n", rc);
1954 goto leave;
1955 }
1956 }
1957 }
1958#endif
1959
1960 rc = E_FAIL;
1961#ifdef VBOXSDL_ADVANCED_OPTIONS
1962 if (fRawR0 != ~0U)
1963 {
1964 if (!gMachineDebugger)
1965 {
1966 RTPrintf("Error: No debugger object; -%srawr0 cannot be executed!\n", fRawR0 ? "" : "no");
1967 goto leave;
1968 }
1969 gMachineDebugger->COMSETTER(RecompileSupervisor)(!fRawR0);
1970 }
1971 if (fRawR3 != ~0U)
1972 {
1973 if (!gMachineDebugger)
1974 {
1975 RTPrintf("Error: No debugger object; -%srawr3 cannot be executed!\n", fRawR0 ? "" : "no");
1976 goto leave;
1977 }
1978 gMachineDebugger->COMSETTER(RecompileUser)(!fRawR3);
1979 }
1980 if (fPATM != ~0U)
1981 {
1982 if (!gMachineDebugger)
1983 {
1984 RTPrintf("Error: No debugger object; -%spatm cannot be executed!\n", fRawR0 ? "" : "no");
1985 goto leave;
1986 }
1987 gMachineDebugger->COMSETTER(PATMEnabled)(fPATM);
1988 }
1989 if (fCSAM != ~0U)
1990 {
1991 if (!gMachineDebugger)
1992 {
1993 RTPrintf("Error: No debugger object; -%scsam cannot be executed!\n", fRawR0 ? "" : "no");
1994 goto leave;
1995 }
1996 gMachineDebugger->COMSETTER(CSAMEnabled)(fCSAM);
1997 }
1998 if (fHWVirt != ~0U)
1999 {
2000 gMachine->SetHWVirtExProperty(HWVirtExPropertyType_Enabled, fHWVirt);
2001 }
2002 if (u32WarpDrive != 0)
2003 {
2004 if (!gMachineDebugger)
2005 {
2006 RTPrintf("Error: No debugger object; --warpdrive %d cannot be executed!\n", u32WarpDrive);
2007 goto leave;
2008 }
2009 gMachineDebugger->COMSETTER(VirtualTimeRate)(u32WarpDrive);
2010 }
2011#endif /* VBOXSDL_ADVANCED_OPTIONS */
2012
2013 /* start with something in the titlebar */
2014 UpdateTitlebar(TITLEBAR_NORMAL);
2015
2016 /* memorize the default cursor */
2017 gpDefaultCursor = SDL_GetCursor();
2018
2019#if !defined(VBOX_WITH_SDL13)
2020# if defined(VBOXSDL_WITH_X11)
2021 /* Get Window Manager info. We only need the X11 display. */
2022 SDL_VERSION(&gSdlInfo.version);
2023 if (!SDL_GetWMInfo(&gSdlInfo))
2024 RTPrintf("Error: could not get SDL Window Manager info -- no Xcursor support!\n");
2025 else
2026 gfXCursorEnabled = TRUE;
2027
2028# if !defined(VBOX_WITHOUT_XCURSOR)
2029 /* SDL uses its own (plain) default cursor. Use the left arrow cursor instead which might look
2030 * much better if a mouse cursor theme is installed. */
2031 if (gfXCursorEnabled)
2032 {
2033 gpDefaultOrigX11Cursor = *(Cursor*)gpDefaultCursor->wm_cursor;
2034 *(Cursor*)gpDefaultCursor->wm_cursor = XCreateFontCursor(gSdlInfo.info.x11.display, XC_left_ptr);
2035 SDL_SetCursor(gpDefaultCursor);
2036 }
2037# endif
2038# endif /* VBOXSDL_WITH_X11 */
2039
2040 /* create a fake empty cursor */
2041 {
2042 uint8_t cursorData[1] = {0};
2043 gpCustomCursor = SDL_CreateCursor(cursorData, cursorData, 8, 1, 0, 0);
2044 gpCustomOrigWMcursor = gpCustomCursor->wm_cursor;
2045 gpCustomCursor->wm_cursor = NULL;
2046 }
2047#endif /* !VBOX_WITH_SDL13 */
2048
2049 /*
2050 * Register our user signal handler.
2051 */
2052#ifdef VBOXSDL_WITH_X11
2053 struct sigaction sa;
2054 sa.sa_sigaction = signal_handler_SIGUSR1;
2055 sigemptyset(&sa.sa_mask);
2056 sa.sa_flags = SA_RESTART | SA_SIGINFO;
2057 sigaction(SIGUSR1, &sa, NULL);
2058#endif /* VBOXSDL_WITH_X11 */
2059
2060 /*
2061 * Start the VM execution thread. This has to be done
2062 * asynchronously as powering up can take some time
2063 * (accessing devices such as the host DVD drive). In
2064 * the meantime, we have to service the SDL event loop.
2065 */
2066 SDL_Event event;
2067
2068 LogFlow(("Powering up the VM...\n"));
2069 rc = gConsole->PowerUp(gProgress.asOutParam());
2070 if (rc != S_OK)
2071 {
2072 com::ErrorInfo info(gConsole);
2073 if (info.isBasicAvailable())
2074 PrintError("Failed to power up VM", info.getText().raw());
2075 else
2076 RTPrintf("Error: failed to power up VM! No error text available.\n");
2077 goto leave;
2078 }
2079
2080#ifdef USE_XPCOM_QUEUE_THREAD
2081 /*
2082 * Before we starting to do stuff, we have to launch the XPCOM
2083 * event queue thread. It will wait for events and send messages
2084 * to the SDL thread. After having done this, we should fairly
2085 * quickly start to process the SDL event queue as an XPCOM
2086 * event storm might arrive. Stupid SDL has a ridiculously small
2087 * event queue buffer!
2088 */
2089 startXPCOMEventQueueThread(eventQ->getSelectFD());
2090#endif /* USE_XPCOM_QUEUE_THREAD */
2091
2092 /* termination flag */
2093 bool fTerminateDuringStartup;
2094 fTerminateDuringStartup = false;
2095
2096 LogRel(("VBoxSDL: NUM lock initially %s, CAPS lock initially %s\n",
2097 !!(SDL_GetModState() & KMOD_NUM) ? "ON" : "OFF",
2098 !!(SDL_GetModState() & KMOD_CAPS) ? "ON" : "OFF"));
2099
2100 /* start regular timer so we don't starve in the event loop */
2101 SDL_TimerID sdlTimer;
2102 sdlTimer = SDL_AddTimer(100, StartupTimer, NULL);
2103
2104 /* loop until the powerup processing is done */
2105 MachineState_T machineState;
2106 do
2107 {
2108 rc = gMachine->COMGETTER(State)(&machineState);
2109 if ( rc == S_OK
2110 && ( machineState == MachineState_Starting
2111 || machineState == MachineState_Restoring
2112 || machineState == MachineState_TeleportingIn
2113 )
2114 )
2115 {
2116 /*
2117 * wait for the next event. This is uncritical as
2118 * power up guarantees to change the machine state
2119 * to either running or aborted and a machine state
2120 * change will send us an event. However, we have to
2121 * service the XPCOM event queue!
2122 */
2123#ifdef USE_XPCOM_QUEUE_THREAD
2124 if (!fXPCOMEventThreadSignaled)
2125 {
2126 signalXPCOMEventQueueThread();
2127 fXPCOMEventThreadSignaled = true;
2128 }
2129#endif
2130 /*
2131 * Wait for SDL events.
2132 */
2133 if (WaitSDLEvent(&event))
2134 {
2135 switch (event.type)
2136 {
2137 /*
2138 * Timer event. Used to have the titlebar updated.
2139 */
2140 case SDL_USER_EVENT_TIMER:
2141 {
2142 /*
2143 * Update the title bar.
2144 */
2145 UpdateTitlebar(TITLEBAR_STARTUP);
2146 break;
2147 }
2148
2149 /*
2150 * User specific resize event.
2151 */
2152 case SDL_USER_EVENT_RESIZE:
2153 {
2154 LogFlow(("SDL_USER_EVENT_RESIZE\n"));
2155 IFramebuffer *dummyFb;
2156 LONG xOrigin, yOrigin;
2157 gpFramebuffer[event.user.code]->resizeGuest();
2158 /* update xOrigin, yOrigin -> mouse */
2159 rc = gDisplay->GetFramebuffer(event.user.code, &dummyFb, &xOrigin, &yOrigin);
2160 gpFramebuffer[event.user.code]->setOrigin(xOrigin, yOrigin);
2161 /* notify the display that the resize has been completed */
2162 gDisplay->ResizeCompleted(event.user.code);
2163 break;
2164 }
2165
2166#ifdef USE_XPCOM_QUEUE_THREAD
2167 /*
2168 * User specific XPCOM event queue event
2169 */
2170 case SDL_USER_EVENT_XPCOM_EVENTQUEUE:
2171 {
2172 LogFlow(("SDL_USER_EVENT_XPCOM_EVENTQUEUE: processing XPCOM event queue...\n"));
2173 eventQ->processEventQueue(0);
2174 signalXPCOMEventQueueThread();
2175 break;
2176 }
2177#endif /* USE_XPCOM_QUEUE_THREAD */
2178
2179 /*
2180 * Termination event from the on state change callback.
2181 */
2182 case SDL_USER_EVENT_TERMINATE:
2183 {
2184 if (event.user.code != VBOXSDL_TERM_NORMAL)
2185 {
2186 com::ProgressErrorInfo info(gProgress);
2187 if (info.isBasicAvailable())
2188 PrintError("Failed to power up VM", info.getText().raw());
2189 else
2190 RTPrintf("Error: failed to power up VM! No error text available.\n");
2191 }
2192 fTerminateDuringStartup = true;
2193 break;
2194 }
2195
2196 default:
2197 {
2198 LogBird(("VBoxSDL: Unknown SDL event %d (pre)\n", event.type));
2199 break;
2200 }
2201 }
2202
2203 }
2204 }
2205 eventQ->processEventQueue(0);
2206 } while ( rc == S_OK
2207 && ( machineState == MachineState_Starting
2208 || machineState == MachineState_Restoring
2209 || machineState == MachineState_TeleportingIn
2210 )
2211 );
2212
2213 /* kill the timer again */
2214 SDL_RemoveTimer(sdlTimer);
2215 sdlTimer = 0;
2216
2217 /* are we supposed to terminate the process? */
2218 if (fTerminateDuringStartup)
2219 goto leave;
2220
2221 /* did the power up succeed? */
2222 if (machineState != MachineState_Running)
2223 {
2224 com::ProgressErrorInfo info(gProgress);
2225 if (info.isBasicAvailable())
2226 PrintError("Failed to power up VM", info.getText().raw());
2227 else
2228 RTPrintf("Error: failed to power up VM! No error text available (rc = 0x%x state = %d)\n", rc, machineState);
2229 goto leave;
2230 }
2231
2232 // accept power off events from now on because we're running
2233 // note that there's a possible race condition here...
2234 cbConsoleImpl->ignorePowerOffEvents(false);
2235
2236 rc = gConsole->COMGETTER(Keyboard)(gKeyboard.asOutParam());
2237 if (!gKeyboard)
2238 {
2239 RTPrintf("Error: could not get keyboard object!\n");
2240 goto leave;
2241 }
2242 gConsole->COMGETTER(Mouse)(gMouse.asOutParam());
2243 if (!gMouse)
2244 {
2245 RTPrintf("Error: could not get mouse object!\n");
2246 goto leave;
2247 }
2248
2249 UpdateTitlebar(TITLEBAR_NORMAL);
2250
2251 /*
2252 * Enable keyboard repeats
2253 */
2254 SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
2255
2256 /*
2257 * Create PID file.
2258 */
2259 if (gpszPidFile)
2260 {
2261 char szBuf[32];
2262 const char *pcszLf = "\n";
2263 RTFILE PidFile;
2264 RTFileOpen(&PidFile, gpszPidFile, RTFILE_O_WRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_NONE);
2265 RTStrFormatNumber(szBuf, RTProcSelf(), 10, 0, 0, 0);
2266 RTFileWrite(PidFile, szBuf, strlen(szBuf), NULL);
2267 RTFileWrite(PidFile, pcszLf, strlen(pcszLf), NULL);
2268 RTFileClose(PidFile);
2269 }
2270
2271 /*
2272 * Main event loop
2273 */
2274#ifdef USE_XPCOM_QUEUE_THREAD
2275 if (!fXPCOMEventThreadSignaled)
2276 {
2277 signalXPCOMEventQueueThread();
2278 }
2279#endif
2280 LogFlow(("VBoxSDL: Entering big event loop\n"));
2281 while (WaitSDLEvent(&event))
2282 {
2283 switch (event.type)
2284 {
2285 /*
2286 * The screen needs to be repainted.
2287 */
2288#ifdef VBOX_WITH_SDL13
2289 case SDL_WINDOWEVENT:
2290 {
2291 switch (event.window.event)
2292 {
2293 case SDL_WINDOWEVENT_EXPOSED:
2294 {
2295 VBoxSDLFB *fb = getFbFromWinId(event.window.windowID);
2296 if (fb)
2297 fb->repaint();
2298 break;
2299 }
2300 case SDL_WINDOWEVENT_FOCUS_GAINED:
2301 {
2302 break;
2303 }
2304 default:
2305 break;
2306 }
2307 }
2308#else
2309 case SDL_VIDEOEXPOSE:
2310 {
2311 gpFramebuffer[0]->repaint();
2312 break;
2313 }
2314#endif
2315
2316 /*
2317 * Keyboard events.
2318 */
2319 case SDL_KEYDOWN:
2320 case SDL_KEYUP:
2321 {
2322 SDLKey ksym = event.key.keysym.sym;
2323
2324 switch (enmHKeyState)
2325 {
2326 case HKEYSTATE_NORMAL:
2327 {
2328 if ( event.type == SDL_KEYDOWN
2329 && ksym != SDLK_UNKNOWN
2330 && (ksym == gHostKeySym1 || ksym == gHostKeySym2))
2331 {
2332 EvHKeyDown1 = event;
2333 enmHKeyState = ksym == gHostKeySym1 ? HKEYSTATE_DOWN_1ST
2334 : HKEYSTATE_DOWN_2ND;
2335 break;
2336 }
2337 ProcessKey(&event.key);
2338 break;
2339 }
2340
2341 case HKEYSTATE_DOWN_1ST:
2342 case HKEYSTATE_DOWN_2ND:
2343 {
2344 if (gHostKeySym2 != SDLK_UNKNOWN)
2345 {
2346 if ( event.type == SDL_KEYDOWN
2347 && ksym != SDLK_UNKNOWN
2348 && ( (enmHKeyState == HKEYSTATE_DOWN_1ST && ksym == gHostKeySym2)
2349 || (enmHKeyState == HKEYSTATE_DOWN_2ND && ksym == gHostKeySym1)))
2350 {
2351 EvHKeyDown2 = event;
2352 enmHKeyState = HKEYSTATE_DOWN;
2353 break;
2354 }
2355 enmHKeyState = event.type == SDL_KEYUP ? HKEYSTATE_NORMAL
2356 : HKEYSTATE_NOT_IT;
2357 ProcessKey(&EvHKeyDown1.key);
2358 /* ugly hack: Some guests (e.g. mstsc.exe on Windows XP)
2359 * expect a small delay between two key events. 5ms work
2360 * reliable here so use 10ms to be on the safe side. A
2361 * better but more complicated fix would be to introduce
2362 * a new state and don't wait here. */
2363 RTThreadSleep(10);
2364 ProcessKey(&event.key);
2365 break;
2366 }
2367 /* fall through if no two-key sequence is used */
2368 }
2369
2370 case HKEYSTATE_DOWN:
2371 {
2372 if (event.type == SDL_KEYDOWN)
2373 {
2374 /* potential host key combination, try execute it */
2375 int irc = HandleHostKey(&event.key);
2376 if (irc == VINF_SUCCESS)
2377 {
2378 enmHKeyState = HKEYSTATE_USED;
2379 break;
2380 }
2381 if (RT_SUCCESS(irc))
2382 goto leave;
2383 }
2384 else /* SDL_KEYUP */
2385 {
2386 if ( ksym != SDLK_UNKNOWN
2387 && (ksym == gHostKeySym1 || ksym == gHostKeySym2))
2388 {
2389 /* toggle grabbing state */
2390 if (!gfGrabbed)
2391 InputGrabStart();
2392 else
2393 InputGrabEnd();
2394
2395 /* SDL doesn't always reset the keystates, correct it */
2396 ResetKeys();
2397 enmHKeyState = HKEYSTATE_NORMAL;
2398 break;
2399 }
2400 }
2401
2402 /* not host key */
2403 enmHKeyState = HKEYSTATE_NOT_IT;
2404 ProcessKey(&EvHKeyDown1.key);
2405 /* see the comment for the 2-key case above */
2406 RTThreadSleep(10);
2407 if (gHostKeySym2 != SDLK_UNKNOWN)
2408 {
2409 ProcessKey(&EvHKeyDown2.key);
2410 /* see the comment for the 2-key case above */
2411 RTThreadSleep(10);
2412 }
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 && gfRelativeMouseGuest)
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 && gfRelativeMouseGuest)
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, or can't handle relative reporting, we have to use absolute
3934 * coordinates, otherwise the host cursor and
3935 * the coordinates the guest thinks the mouse is at could get out-of-sync. From
3936 * the SDL mailing list:
3937 *
3938 * "The event processing is usually asynchronous and so somewhat delayed, and
3939 * SDL_GetMouseState is returning the immediate mouse state. So at the time you
3940 * call SDL_GetMouseState, the "button" is already up."
3941 */
3942 abs = (UseAbsoluteMouse() && !gfGrabbed)
3943 || gfGuestNeedsHostCursor
3944 || !gfRelativeMouseGuest;
3945
3946 /* only used if abs == TRUE */
3947 int xOrigin = fb->getOriginX();
3948 int yOrigin = fb->getOriginY();
3949 int xMin = fb->getXOffset() + xOrigin;
3950 int yMin = fb->getYOffset() + yOrigin;
3951 int xMax = xMin + (int)fb->getGuestXRes();
3952 int yMax = yMin + (int)fb->getGuestYRes();
3953
3954 state = abs ? SDL_GetMouseState(
3955#ifdef VBOX_WITH_SDL13
3956 0,
3957#endif
3958 &x, &y)
3959 : SDL_GetRelativeMouseState(
3960#ifdef VBOX_WITH_SDL13
3961 0,
3962#endif
3963 &x, &y);
3964
3965 /*
3966 * process buttons
3967 */
3968 buttons = 0;
3969 if (state & SDL_BUTTON(SDL_BUTTON_LEFT))
3970 buttons |= MouseButtonState_LeftButton;
3971 if (state & SDL_BUTTON(SDL_BUTTON_RIGHT))
3972 buttons |= MouseButtonState_RightButton;
3973 if (state & SDL_BUTTON(SDL_BUTTON_MIDDLE))
3974 buttons |= MouseButtonState_MiddleButton;
3975
3976 if (abs)
3977 {
3978 x += xOrigin;
3979 y += yOrigin;
3980
3981 /*
3982 * Check if the mouse event is inside the guest area. This solves the
3983 * following problem: Some guests switch off the VBox hardware mouse
3984 * cursor and draw the mouse cursor itself instead. Moving the mouse
3985 * outside the guest area then leads to annoying mouse hangs if we
3986 * don't pass mouse motion events into the guest.
3987 */
3988 if (x < xMin || y < yMin || x > xMax || y > yMax)
3989 {
3990 /*
3991 * Cursor outside of valid guest area (outside window or in secure
3992 * label area. Don't allow any mouse button press.
3993 */
3994 button = 0;
3995
3996 /*
3997 * Release any pressed button.
3998 */
3999#if 0
4000 /* disabled on customers request */
4001 buttons &= ~(MouseButtonState_LeftButton |
4002 MouseButtonState_MiddleButton |
4003 MouseButtonState_RightButton);
4004#endif
4005
4006 /*
4007 * Prevent negative coordinates.
4008 */
4009 if (x < xMin) x = xMin;
4010 if (x > xMax) x = xMax;
4011 if (y < yMin) y = yMin;
4012 if (y > yMax) y = yMax;
4013
4014 if (!gpOffCursor)
4015 {
4016 gpOffCursor = SDL_GetCursor(); /* Cursor image */
4017 gfOffCursorActive = SDL_ShowCursor(-1); /* enabled / disabled */
4018 SDL_SetCursor(gpDefaultCursor);
4019 SDL_ShowCursor(SDL_ENABLE);
4020 }
4021 }
4022 else
4023 {
4024 if (gpOffCursor)
4025 {
4026 /*
4027 * We just entered the valid guest area. Restore the guest mouse
4028 * cursor.
4029 */
4030 SDL_SetCursor(gpOffCursor);
4031 SDL_ShowCursor(gfOffCursorActive ? SDL_ENABLE : SDL_DISABLE);
4032 gpOffCursor = NULL;
4033 }
4034 }
4035 }
4036
4037 /*
4038 * Button was pressed but that press is not reflected in the button state?
4039 */
4040 if (down && !(state & SDL_BUTTON(button)))
4041 {
4042 /*
4043 * It can happen that a mouse up event follows a mouse down event immediately
4044 * and we see the events when the bit in the button state is already cleared
4045 * again. In that case we simulate the mouse down event.
4046 */
4047 int tmp_button = 0;
4048 switch (button)
4049 {
4050 case SDL_BUTTON_LEFT: tmp_button = MouseButtonState_LeftButton; break;
4051 case SDL_BUTTON_MIDDLE: tmp_button = MouseButtonState_MiddleButton; break;
4052 case SDL_BUTTON_RIGHT: tmp_button = MouseButtonState_RightButton; break;
4053 }
4054
4055 if (abs)
4056 {
4057 /**
4058 * @todo
4059 * PutMouseEventAbsolute() expects x and y starting from 1,1.
4060 * should we do the increment internally in PutMouseEventAbsolute()
4061 * or state it in PutMouseEventAbsolute() docs?
4062 */
4063 gMouse->PutMouseEventAbsolute(x + 1 - xMin + xOrigin,
4064 y + 1 - yMin + yOrigin,
4065 dz, 0 /* horizontal scroll wheel */,
4066 buttons | tmp_button);
4067 }
4068 else
4069 {
4070 gMouse->PutMouseEvent(0, 0, dz,
4071 0 /* horizontal scroll wheel */,
4072 buttons | tmp_button);
4073 }
4074 }
4075
4076 // now send the mouse event
4077 if (abs)
4078 {
4079 /**
4080 * @todo
4081 * PutMouseEventAbsolute() expects x and y starting from 1,1.
4082 * should we do the increment internally in PutMouseEventAbsolute()
4083 * or state it in PutMouseEventAbsolute() docs?
4084 */
4085 gMouse->PutMouseEventAbsolute(x + 1 - xMin + xOrigin,
4086 y + 1 - yMin + yOrigin,
4087 dz, 0 /* Horizontal wheel */, buttons);
4088 }
4089 else
4090 {
4091 gMouse->PutMouseEvent(x, y, dz, 0 /* Horizontal wheel */, buttons);
4092 }
4093}
4094
4095/**
4096 * Resets the VM
4097 */
4098void ResetVM(void)
4099{
4100 if (gConsole)
4101 gConsole->Reset();
4102}
4103
4104/**
4105 * Initiates a saved state and updates the titlebar with progress information
4106 */
4107void SaveState(void)
4108{
4109 ResetKeys();
4110 RTThreadYield();
4111 if (gfGrabbed)
4112 InputGrabEnd();
4113 RTThreadYield();
4114 UpdateTitlebar(TITLEBAR_SAVE);
4115 gProgress = NULL;
4116 HRESULT rc = gConsole->SaveState(gProgress.asOutParam());
4117 if (FAILED(S_OK))
4118 {
4119 RTPrintf("Error saving state! rc = 0x%x\n", rc);
4120 return;
4121 }
4122 Assert(gProgress);
4123
4124 /*
4125 * Wait for the operation to be completed and work
4126 * the title bar in the mean while.
4127 */
4128 ULONG cPercent = 0;
4129#ifndef RT_OS_DARWIN /* don't break the other guys yet. */
4130 for (;;)
4131 {
4132 BOOL fCompleted = false;
4133 rc = gProgress->COMGETTER(Completed)(&fCompleted);
4134 if (FAILED(rc) || fCompleted)
4135 break;
4136 ULONG cPercentNow;
4137 rc = gProgress->COMGETTER(Percent)(&cPercentNow);
4138 if (FAILED(rc))
4139 break;
4140 if (cPercentNow != cPercent)
4141 {
4142 UpdateTitlebar(TITLEBAR_SAVE, cPercent);
4143 cPercent = cPercentNow;
4144 }
4145
4146 /* wait */
4147 rc = gProgress->WaitForCompletion(100);
4148 if (FAILED(rc))
4149 break;
4150 /// @todo process gui events.
4151 }
4152
4153#else /* new loop which processes GUI events while saving. */
4154
4155 /* start regular timer so we don't starve in the event loop */
4156 SDL_TimerID sdlTimer;
4157 sdlTimer = SDL_AddTimer(100, StartupTimer, NULL);
4158
4159 for (;;)
4160 {
4161 /*
4162 * Check for completion.
4163 */
4164 BOOL fCompleted = false;
4165 rc = gProgress->COMGETTER(Completed)(&fCompleted);
4166 if (FAILED(rc) || fCompleted)
4167 break;
4168 ULONG cPercentNow;
4169 rc = gProgress->COMGETTER(Percent)(&cPercentNow);
4170 if (FAILED(rc))
4171 break;
4172 if (cPercentNow != cPercent)
4173 {
4174 UpdateTitlebar(TITLEBAR_SAVE, cPercent);
4175 cPercent = cPercentNow;
4176 }
4177
4178 /*
4179 * Wait for and process GUI a event.
4180 * This is necessary for XPCOM IPC and for updating the
4181 * title bar on the Mac.
4182 */
4183 SDL_Event event;
4184 if (WaitSDLEvent(&event))
4185 {
4186 switch (event.type)
4187 {
4188 /*
4189 * Timer event preventing us from getting stuck.
4190 */
4191 case SDL_USER_EVENT_TIMER:
4192 break;
4193
4194#ifdef USE_XPCOM_QUEUE_THREAD
4195 /*
4196 * User specific XPCOM event queue event
4197 */
4198 case SDL_USER_EVENT_XPCOM_EVENTQUEUE:
4199 {
4200 LogFlow(("SDL_USER_EVENT_XPCOM_EVENTQUEUE: processing XPCOM event queue...\n"));
4201 eventQ->ProcessPendingEvents();
4202 signalXPCOMEventQueueThread();
4203 break;
4204 }
4205#endif /* USE_XPCOM_QUEUE_THREAD */
4206
4207
4208 /*
4209 * Ignore all other events.
4210 */
4211 case SDL_USER_EVENT_RESIZE:
4212 case SDL_USER_EVENT_TERMINATE:
4213 default:
4214 break;
4215 }
4216 }
4217 }
4218
4219 /* kill the timer */
4220 SDL_RemoveTimer(sdlTimer);
4221 sdlTimer = 0;
4222
4223#endif /* RT_OS_DARWIN */
4224
4225 /*
4226 * What's the result of the operation?
4227 */
4228 LONG lrc;
4229 rc = gProgress->COMGETTER(ResultCode)(&lrc);
4230 if (FAILED(rc))
4231 lrc = ~0;
4232 if (!lrc)
4233 {
4234 UpdateTitlebar(TITLEBAR_SAVE, 100);
4235 RTThreadYield();
4236 RTPrintf("Saved the state successfully.\n");
4237 }
4238 else
4239 RTPrintf("Error saving state, lrc=%d (%#x)\n", lrc, lrc);
4240}
4241
4242/**
4243 * Build the titlebar string
4244 */
4245static void UpdateTitlebar(TitlebarMode mode, uint32_t u32User)
4246{
4247 static char szTitle[1024] = {0};
4248
4249 /* back up current title */
4250 char szPrevTitle[1024];
4251 strcpy(szPrevTitle, szTitle);
4252
4253 Bstr name;
4254 gMachine->COMGETTER(Name)(name.asOutParam());
4255
4256 RTStrPrintf(szTitle, sizeof(szTitle), "%s - " VBOX_PRODUCT,
4257 name ? Utf8Str(name).raw() : "<noname>");
4258
4259 /* which mode are we in? */
4260 switch (mode)
4261 {
4262 case TITLEBAR_NORMAL:
4263 {
4264 MachineState_T machineState;
4265 gMachine->COMGETTER(State)(&machineState);
4266 if (machineState == MachineState_Paused)
4267 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle), " - [Paused]");
4268
4269 if (gfGrabbed)
4270 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle), " - [Input captured]");
4271
4272#if defined(DEBUG) || defined(VBOX_WITH_STATISTICS)
4273 // do we have a debugger interface
4274 if (gMachineDebugger)
4275 {
4276 // query the machine state
4277 BOOL recompileSupervisor = FALSE;
4278 BOOL recompileUser = FALSE;
4279 BOOL patmEnabled = FALSE;
4280 BOOL csamEnabled = FALSE;
4281 BOOL singlestepEnabled = FALSE;
4282 BOOL logEnabled = FALSE;
4283 BOOL hwVirtEnabled = FALSE;
4284 ULONG virtualTimeRate = 100;
4285 gMachineDebugger->COMGETTER(RecompileSupervisor)(&recompileSupervisor);
4286 gMachineDebugger->COMGETTER(RecompileUser)(&recompileUser);
4287 gMachineDebugger->COMGETTER(PATMEnabled)(&patmEnabled);
4288 gMachineDebugger->COMGETTER(CSAMEnabled)(&csamEnabled);
4289 gMachineDebugger->COMGETTER(LogEnabled)(&logEnabled);
4290 gMachineDebugger->COMGETTER(Singlestep)(&singlestepEnabled);
4291 gMachineDebugger->COMGETTER(HWVirtExEnabled)(&hwVirtEnabled);
4292 gMachineDebugger->COMGETTER(VirtualTimeRate)(&virtualTimeRate);
4293 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4294 " [STEP=%d CS=%d PAT=%d RR0=%d RR3=%d LOG=%d HWVirt=%d",
4295 singlestepEnabled == TRUE, csamEnabled == TRUE, patmEnabled == TRUE,
4296 recompileSupervisor == FALSE, recompileUser == FALSE,
4297 logEnabled == TRUE, hwVirtEnabled == TRUE);
4298 char *psz = strchr(szTitle, '\0');
4299 if (virtualTimeRate != 100)
4300 RTStrPrintf(psz, &szTitle[sizeof(szTitle)] - psz, " WD=%d%%]", virtualTimeRate);
4301 else
4302 RTStrPrintf(psz, &szTitle[sizeof(szTitle)] - psz, "]");
4303 }
4304#endif /* DEBUG || VBOX_WITH_STATISTICS */
4305 break;
4306 }
4307
4308 case TITLEBAR_STARTUP:
4309 {
4310 /*
4311 * Format it.
4312 */
4313 MachineState_T machineState;
4314 gMachine->COMGETTER(State)(&machineState);
4315 if (machineState == MachineState_Starting)
4316 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4317 " - Starting...");
4318 else if (machineState == MachineState_Restoring)
4319 {
4320 ULONG cPercentNow;
4321 HRESULT rc = gProgress->COMGETTER(Percent)(&cPercentNow);
4322 if (SUCCEEDED(rc))
4323 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4324 " - Restoring %d%%...", (int)cPercentNow);
4325 else
4326 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4327 " - Restoring...");
4328 }
4329 else if (machineState == MachineState_TeleportingIn)
4330 {
4331 ULONG cPercentNow;
4332 HRESULT rc = gProgress->COMGETTER(Percent)(&cPercentNow);
4333 if (SUCCEEDED(rc))
4334 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4335 " - Teleporting %d%%...", (int)cPercentNow);
4336 else
4337 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4338 " - Teleporting...");
4339 }
4340 /* ignore other states, we could already be in running or aborted state */
4341 break;
4342 }
4343
4344 case TITLEBAR_SAVE:
4345 {
4346 AssertMsg(u32User <= 100, ("%d\n", u32User));
4347 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4348 " - Saving %d%%...", u32User);
4349 break;
4350 }
4351
4352 case TITLEBAR_SNAPSHOT:
4353 {
4354 AssertMsg(u32User <= 100, ("%d\n", u32User));
4355 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
4356 " - Taking snapshot %d%%...", u32User);
4357 break;
4358 }
4359
4360 default:
4361 RTPrintf("Error: Invalid title bar mode %d!\n", mode);
4362 return;
4363 }
4364
4365 /*
4366 * Don't update if it didn't change.
4367 */
4368 if (!strcmp(szTitle, szPrevTitle))
4369 return;
4370
4371 /*
4372 * Set the new title
4373 */
4374#ifdef VBOX_WIN32_UI
4375 setUITitle(szTitle);
4376#else
4377 SDL_WM_SetCaption(szTitle, VBOX_PRODUCT);
4378#endif
4379}
4380
4381#if 0
4382static void vbox_show_shape (unsigned short w, unsigned short h,
4383 uint32_t bg, const uint8_t *image)
4384{
4385 size_t x, y;
4386 unsigned short pitch;
4387 const uint32_t *color;
4388 const uint8_t *mask;
4389 size_t size_mask;
4390
4391 mask = image;
4392 pitch = (w + 7) / 8;
4393 size_mask = (pitch * h + 3) & ~3;
4394
4395 color = (const uint32_t *)(image + size_mask);
4396
4397 printf("show_shape %dx%d pitch %d size mask %d\n",
4398 w, h, pitch, size_mask);
4399 for (y = 0; y < h; ++y, mask += pitch, color += w)
4400 {
4401 for (x = 0; x < w; ++x) {
4402 if (mask[x / 8] & (1 << (7 - (x % 8))))
4403 printf(" ");
4404 else
4405 {
4406 uint32_t c = color[x];
4407 if (c == bg)
4408 printf("Y");
4409 else
4410 printf("X");
4411 }
4412 }
4413 printf("\n");
4414 }
4415}
4416#endif
4417
4418/**
4419 * Sets the pointer shape according to parameters.
4420 * Must be called only from the main SDL thread.
4421 */
4422static void SetPointerShape(const PointerShapeChangeData *data)
4423{
4424 /*
4425 * don't allow to change the pointer shape if we are outside the valid
4426 * guest area. In that case set standard mouse pointer is set and should
4427 * not get overridden.
4428 */
4429 if (gpOffCursor)
4430 return;
4431
4432 if (data->shape)
4433 {
4434 bool ok = false;
4435
4436 uint32_t andMaskSize = (data->width + 7) / 8 * data->height;
4437 uint32_t srcShapePtrScan = data->width * 4;
4438
4439 const uint8_t *srcAndMaskPtr = data->shape;
4440 const uint8_t *srcShapePtr = data->shape + ((andMaskSize + 3) & ~3);
4441
4442#if 0
4443 /* pointer debugging code */
4444 // vbox_show_shape(data->width, data->height, 0, data->shape);
4445 uint32_t shapeSize = ((((data->width + 7) / 8) * data->height + 3) & ~3) + data->width * 4 * data->height;
4446 printf("visible: %d\n", data->visible);
4447 printf("width = %d\n", data->width);
4448 printf("height = %d\n", data->height);
4449 printf("alpha = %d\n", data->alpha);
4450 printf("xhot = %d\n", data->xHot);
4451 printf("yhot = %d\n", data->yHot);
4452 printf("uint8_t pointerdata[] = { ");
4453 for (uint32_t i = 0; i < shapeSize; i++)
4454 {
4455 printf("0x%x, ", data->shape[i]);
4456 }
4457 printf("};\n");
4458#endif
4459
4460#if defined(RT_OS_WINDOWS)
4461
4462 BITMAPV5HEADER bi;
4463 HBITMAP hBitmap;
4464 void *lpBits;
4465 HCURSOR hAlphaCursor = NULL;
4466
4467 ::ZeroMemory(&bi, sizeof(BITMAPV5HEADER));
4468 bi.bV5Size = sizeof(BITMAPV5HEADER);
4469 bi.bV5Width = data->width;
4470 bi.bV5Height = -(LONG)data->height;
4471 bi.bV5Planes = 1;
4472 bi.bV5BitCount = 32;
4473 bi.bV5Compression = BI_BITFIELDS;
4474 // specifiy a supported 32 BPP alpha format for Windows XP
4475 bi.bV5RedMask = 0x00FF0000;
4476 bi.bV5GreenMask = 0x0000FF00;
4477 bi.bV5BlueMask = 0x000000FF;
4478 if (data->alpha)
4479 bi.bV5AlphaMask = 0xFF000000;
4480 else
4481 bi.bV5AlphaMask = 0;
4482
4483 HDC hdc = ::GetDC(NULL);
4484
4485 // create the DIB section with an alpha channel
4486 hBitmap = ::CreateDIBSection(hdc, (BITMAPINFO *)&bi, DIB_RGB_COLORS,
4487 (void **)&lpBits, NULL, (DWORD)0);
4488
4489 ::ReleaseDC(NULL, hdc);
4490
4491 HBITMAP hMonoBitmap = NULL;
4492 if (data->alpha)
4493 {
4494 // create an empty mask bitmap
4495 hMonoBitmap = ::CreateBitmap(data->width, data->height, 1, 1, NULL);
4496 }
4497 else
4498 {
4499 /* Word aligned AND mask. Will be allocated and created if necessary. */
4500 uint8_t *pu8AndMaskWordAligned = NULL;
4501
4502 /* Width in bytes of the original AND mask scan line. */
4503 uint32_t cbAndMaskScan = (data->width + 7) / 8;
4504
4505 if (cbAndMaskScan & 1)
4506 {
4507 /* Original AND mask is not word aligned. */
4508
4509 /* Allocate memory for aligned AND mask. */
4510 pu8AndMaskWordAligned = (uint8_t *)RTMemTmpAllocZ((cbAndMaskScan + 1) * data->height);
4511
4512 Assert(pu8AndMaskWordAligned);
4513
4514 if (pu8AndMaskWordAligned)
4515 {
4516 /* According to MSDN the padding bits must be 0.
4517 * Compute the bit mask to set padding bits to 0 in the last byte of original AND mask.
4518 */
4519 uint32_t u32PaddingBits = cbAndMaskScan * 8 - data->width;
4520 Assert(u32PaddingBits < 8);
4521 uint8_t u8LastBytesPaddingMask = (uint8_t)(0xFF << u32PaddingBits);
4522
4523 Log(("u8LastBytesPaddingMask = %02X, aligned w = %d, width = %d, cbAndMaskScan = %d\n",
4524 u8LastBytesPaddingMask, (cbAndMaskScan + 1) * 8, data->width, cbAndMaskScan));
4525
4526 uint8_t *src = (uint8_t *)srcAndMaskPtr;
4527 uint8_t *dst = pu8AndMaskWordAligned;
4528
4529 unsigned i;
4530 for (i = 0; i < data->height; i++)
4531 {
4532 memcpy(dst, src, cbAndMaskScan);
4533
4534 dst[cbAndMaskScan - 1] &= u8LastBytesPaddingMask;
4535
4536 src += cbAndMaskScan;
4537 dst += cbAndMaskScan + 1;
4538 }
4539 }
4540 }
4541
4542 // create the AND mask bitmap
4543 hMonoBitmap = ::CreateBitmap(data->width, data->height, 1, 1,
4544 pu8AndMaskWordAligned? pu8AndMaskWordAligned: srcAndMaskPtr);
4545
4546 if (pu8AndMaskWordAligned)
4547 {
4548 RTMemTmpFree(pu8AndMaskWordAligned);
4549 }
4550 }
4551
4552 Assert(hBitmap);
4553 Assert(hMonoBitmap);
4554 if (hBitmap && hMonoBitmap)
4555 {
4556 DWORD *dstShapePtr = (DWORD *)lpBits;
4557
4558 for (uint32_t y = 0; y < data->height; y ++)
4559 {
4560 memcpy(dstShapePtr, srcShapePtr, srcShapePtrScan);
4561 srcShapePtr += srcShapePtrScan;
4562 dstShapePtr += data->width;
4563 }
4564
4565 ICONINFO ii;
4566 ii.fIcon = FALSE;
4567 ii.xHotspot = data->xHot;
4568 ii.yHotspot = data->yHot;
4569 ii.hbmMask = hMonoBitmap;
4570 ii.hbmColor = hBitmap;
4571
4572 hAlphaCursor = ::CreateIconIndirect(&ii);
4573 Assert(hAlphaCursor);
4574 if (hAlphaCursor)
4575 {
4576 // here we do a dirty trick by substituting a Window Manager's
4577 // cursor handle with the handle we created
4578
4579 WMcursor *pCustomTempWMCursor = gpCustomCursor->wm_cursor;
4580
4581 // see SDL12/src/video/wincommon/SDL_sysmouse.c
4582 void *wm_cursor = malloc(sizeof(HCURSOR) + sizeof(uint8_t *) * 2);
4583 *(HCURSOR *)wm_cursor = hAlphaCursor;
4584
4585 gpCustomCursor->wm_cursor = (WMcursor *)wm_cursor;
4586 SDL_SetCursor(gpCustomCursor);
4587 SDL_ShowCursor(SDL_ENABLE);
4588
4589 if (pCustomTempWMCursor)
4590 {
4591 ::DestroyCursor(*(HCURSOR *)pCustomTempWMCursor);
4592 free(pCustomTempWMCursor);
4593 }
4594
4595 ok = true;
4596 }
4597 }
4598
4599 if (hMonoBitmap)
4600 ::DeleteObject(hMonoBitmap);
4601 if (hBitmap)
4602 ::DeleteObject(hBitmap);
4603
4604#elif defined(VBOXSDL_WITH_X11) && !defined(VBOX_WITHOUT_XCURSOR)
4605
4606 if (gfXCursorEnabled)
4607 {
4608 XcursorImage *img = XcursorImageCreate(data->width, data->height);
4609 Assert(img);
4610 if (img)
4611 {
4612 img->xhot = data->xHot;
4613 img->yhot = data->yHot;
4614
4615 XcursorPixel *dstShapePtr = img->pixels;
4616
4617 for (uint32_t y = 0; y < data->height; y ++)
4618 {
4619 memcpy(dstShapePtr, srcShapePtr, srcShapePtrScan);
4620
4621 if (!data->alpha)
4622 {
4623 // convert AND mask to the alpha channel
4624 uint8_t byte = 0;
4625 for (uint32_t x = 0; x < data->width; x ++)
4626 {
4627 if (!(x % 8))
4628 byte = *(srcAndMaskPtr ++);
4629 else
4630 byte <<= 1;
4631
4632 if (byte & 0x80)
4633 {
4634 // Linux doesn't support inverted pixels (XOR ops,
4635 // to be exact) in cursor shapes, so we detect such
4636 // pixels and always replace them with black ones to
4637 // make them visible at least over light colors
4638 if (dstShapePtr [x] & 0x00FFFFFF)
4639 dstShapePtr [x] = 0xFF000000;
4640 else
4641 dstShapePtr [x] = 0x00000000;
4642 }
4643 else
4644 dstShapePtr [x] |= 0xFF000000;
4645 }
4646 }
4647
4648 srcShapePtr += srcShapePtrScan;
4649 dstShapePtr += data->width;
4650 }
4651
4652#ifndef VBOX_WITH_SDL13
4653 Cursor cur = XcursorImageLoadCursor(gSdlInfo.info.x11.display, img);
4654 Assert(cur);
4655 if (cur)
4656 {
4657 // here we do a dirty trick by substituting a Window Manager's
4658 // cursor handle with the handle we created
4659
4660 WMcursor *pCustomTempWMCursor = gpCustomCursor->wm_cursor;
4661
4662 // see SDL12/src/video/x11/SDL_x11mouse.c
4663 void *wm_cursor = malloc(sizeof(Cursor));
4664 *(Cursor *)wm_cursor = cur;
4665
4666 gpCustomCursor->wm_cursor = (WMcursor *)wm_cursor;
4667 SDL_SetCursor(gpCustomCursor);
4668 SDL_ShowCursor(SDL_ENABLE);
4669
4670 if (pCustomTempWMCursor)
4671 {
4672 XFreeCursor(gSdlInfo.info.x11.display, *(Cursor *)pCustomTempWMCursor);
4673 free(pCustomTempWMCursor);
4674 }
4675
4676 ok = true;
4677 }
4678#endif
4679 }
4680 XcursorImageDestroy(img);
4681 }
4682
4683#endif /* VBOXSDL_WITH_X11 && !VBOX_WITHOUT_XCURSOR */
4684
4685 if (!ok)
4686 {
4687 SDL_SetCursor(gpDefaultCursor);
4688 SDL_ShowCursor(SDL_ENABLE);
4689 }
4690 }
4691 else
4692 {
4693 if (data->visible)
4694 SDL_ShowCursor(SDL_ENABLE);
4695 else if (gfAbsoluteMouseGuest)
4696 /* Don't disable the cursor if the guest additions are not active (anymore) */
4697 SDL_ShowCursor(SDL_DISABLE);
4698 }
4699}
4700
4701/**
4702 * Handle changed mouse capabilities
4703 */
4704static void HandleGuestCapsChanged(void)
4705{
4706 if (!gfAbsoluteMouseGuest)
4707 {
4708 // Cursor could be overwritten by the guest tools
4709 SDL_SetCursor(gpDefaultCursor);
4710 SDL_ShowCursor(SDL_ENABLE);
4711 gpOffCursor = NULL;
4712 }
4713 if (gMouse && UseAbsoluteMouse())
4714 {
4715 // Actually switch to absolute coordinates
4716 if (gfGrabbed)
4717 InputGrabEnd();
4718 gMouse->PutMouseEventAbsolute(-1, -1, 0, 0, 0);
4719 }
4720}
4721
4722/**
4723 * Handles a host key down event
4724 */
4725static int HandleHostKey(const SDL_KeyboardEvent *pEv)
4726{
4727 /*
4728 * Revalidate the host key modifier
4729 */
4730 if ((SDL_GetModState() & ~(KMOD_MODE | KMOD_NUM | KMOD_RESERVED)) != gHostKeyMod)
4731 return VERR_NOT_SUPPORTED;
4732
4733 /*
4734 * What was pressed?
4735 */
4736 switch (pEv->keysym.sym)
4737 {
4738 /* Control-Alt-Delete */
4739 case SDLK_DELETE:
4740 {
4741 gKeyboard->PutCAD();
4742 break;
4743 }
4744
4745 /*
4746 * Fullscreen / Windowed toggle.
4747 */
4748 case SDLK_f:
4749 {
4750 if ( strchr(gHostKeyDisabledCombinations, 'f')
4751 || !gfAllowFullscreenToggle)
4752 return VERR_NOT_SUPPORTED;
4753
4754 /*
4755 * We have to pause/resume the machine during this
4756 * process because there might be a short moment
4757 * without a valid framebuffer
4758 */
4759 MachineState_T machineState;
4760 gMachine->COMGETTER(State)(&machineState);
4761 bool fPauseIt = machineState == MachineState_Running
4762 || machineState == MachineState_Teleporting
4763 || machineState == MachineState_LiveSnapshotting;
4764 if (fPauseIt)
4765 gConsole->Pause();
4766 SetFullscreen(!gpFramebuffer[0]->getFullscreen());
4767 if (fPauseIt)
4768 gConsole->Resume();
4769
4770 /*
4771 * We have switched from/to fullscreen, so request a full
4772 * screen repaint, just to be sure.
4773 */
4774 gDisplay->InvalidateAndUpdate();
4775 break;
4776 }
4777
4778 /*
4779 * Pause / Resume toggle.
4780 */
4781 case SDLK_p:
4782 {
4783 if (strchr(gHostKeyDisabledCombinations, 'p'))
4784 return VERR_NOT_SUPPORTED;
4785
4786 MachineState_T machineState;
4787 gMachine->COMGETTER(State)(&machineState);
4788 if ( machineState == MachineState_Running
4789 || machineState == MachineState_Teleporting
4790 || machineState == MachineState_LiveSnapshotting
4791 )
4792 {
4793 if (gfGrabbed)
4794 InputGrabEnd();
4795 gConsole->Pause();
4796 }
4797 else if (machineState == MachineState_Paused)
4798 {
4799 gConsole->Resume();
4800 }
4801 UpdateTitlebar(TITLEBAR_NORMAL);
4802 break;
4803 }
4804
4805 /*
4806 * Reset the VM
4807 */
4808 case SDLK_r:
4809 {
4810 if (strchr(gHostKeyDisabledCombinations, 'r'))
4811 return VERR_NOT_SUPPORTED;
4812
4813 ResetVM();
4814 break;
4815 }
4816
4817 /*
4818 * Terminate the VM
4819 */
4820 case SDLK_q:
4821 {
4822 if (strchr(gHostKeyDisabledCombinations, 'q'))
4823 return VERR_NOT_SUPPORTED;
4824
4825 return VINF_EM_TERMINATE;
4826 }
4827
4828 /*
4829 * Save the machine's state and exit
4830 */
4831 case SDLK_s:
4832 {
4833 if (strchr(gHostKeyDisabledCombinations, 's'))
4834 return VERR_NOT_SUPPORTED;
4835
4836 SaveState();
4837 return VINF_EM_TERMINATE;
4838 }
4839
4840 case SDLK_h:
4841 {
4842 if (strchr(gHostKeyDisabledCombinations, 'h'))
4843 return VERR_NOT_SUPPORTED;
4844
4845 if (gConsole)
4846 gConsole->PowerButton();
4847 break;
4848 }
4849
4850 /*
4851 * Perform an online snapshot. Continue operation.
4852 */
4853 case SDLK_n:
4854 {
4855 if (strchr(gHostKeyDisabledCombinations, 'n'))
4856 return VERR_NOT_SUPPORTED;
4857
4858 RTThreadYield();
4859 ULONG cSnapshots = 0;
4860 gMachine->COMGETTER(SnapshotCount)(&cSnapshots);
4861 char pszSnapshotName[20];
4862 RTStrPrintf(pszSnapshotName, sizeof(pszSnapshotName), "Snapshot %d", cSnapshots + 1);
4863 gProgress = NULL;
4864 HRESULT rc;
4865 CHECK_ERROR(gConsole, TakeSnapshot(Bstr(pszSnapshotName), Bstr("Taken by VBoxSDL"),
4866 gProgress.asOutParam()));
4867 if (FAILED(rc))
4868 {
4869 RTPrintf("Error taking snapshot! rc = 0x%x\n", rc);
4870 /* continue operation */
4871 return VINF_SUCCESS;
4872 }
4873 /*
4874 * Wait for the operation to be completed and work
4875 * the title bar in the mean while.
4876 */
4877 ULONG cPercent = 0;
4878 for (;;)
4879 {
4880 BOOL fCompleted = false;
4881 rc = gProgress->COMGETTER(Completed)(&fCompleted);
4882 if (FAILED(rc) || fCompleted)
4883 break;
4884 ULONG cPercentNow;
4885 rc = gProgress->COMGETTER(Percent)(&cPercentNow);
4886 if (FAILED(rc))
4887 break;
4888 if (cPercentNow != cPercent)
4889 {
4890 UpdateTitlebar(TITLEBAR_SNAPSHOT, cPercent);
4891 cPercent = cPercentNow;
4892 }
4893
4894 /* wait */
4895 rc = gProgress->WaitForCompletion(100);
4896 if (FAILED(rc))
4897 break;
4898 /// @todo process gui events.
4899 }
4900
4901 /* continue operation */
4902 return VINF_SUCCESS;
4903 }
4904
4905 case SDLK_F1: case SDLK_F2: case SDLK_F3:
4906 case SDLK_F4: case SDLK_F5: case SDLK_F6:
4907 case SDLK_F7: case SDLK_F8: case SDLK_F9:
4908 case SDLK_F10: case SDLK_F11: case SDLK_F12:
4909 {
4910 // /* send Ctrl-Alt-Fx to guest */
4911 com::SafeArray<LONG> keys(6);
4912
4913 keys[0] = 0x1d; // Ctrl down
4914 keys[1] = 0x38; // Alt down
4915 keys[2] = Keyevent2Keycode(pEv); // Fx down
4916 keys[3] = keys[2] + 0x80; // Fx up
4917 keys[4] = 0xb8; // Alt up
4918 keys[5] = 0x9d; // Ctrl up
4919
4920 gKeyboard->PutScancodes(ComSafeArrayAsInParam(keys), NULL);
4921 return VINF_SUCCESS;
4922 }
4923
4924 /*
4925 * Not a host key combination.
4926 * Indicate this by returning false.
4927 */
4928 default:
4929 return VERR_NOT_SUPPORTED;
4930 }
4931
4932 return VINF_SUCCESS;
4933}
4934
4935/**
4936 * Timer callback function for startup processing
4937 */
4938static Uint32 StartupTimer(Uint32 interval, void *param)
4939{
4940 /* post message so we can do something in the startup loop */
4941 SDL_Event event = {0};
4942 event.type = SDL_USEREVENT;
4943 event.user.type = SDL_USER_EVENT_TIMER;
4944 SDL_PushEvent(&event);
4945 RTSemEventSignal(g_EventSemSDLEvents);
4946 return interval;
4947}
4948
4949/**
4950 * Timer callback function to check if resizing is finished
4951 */
4952static Uint32 ResizeTimer(Uint32 interval, void *param)
4953{
4954 /* post message so the window is actually resized */
4955 SDL_Event event = {0};
4956 event.type = SDL_USEREVENT;
4957 event.user.type = SDL_USER_EVENT_WINDOW_RESIZE_DONE;
4958 PushSDLEventForSure(&event);
4959 /* one-shot */
4960 return 0;
4961}
4962
4963/**
4964 * Timer callback function to check if an ACPI power button event was handled by the guest.
4965 */
4966static Uint32 QuitTimer(Uint32 interval, void *param)
4967{
4968 BOOL fHandled = FALSE;
4969
4970 gSdlQuitTimer = NULL;
4971 if (gConsole)
4972 {
4973 int rc = gConsole->GetPowerButtonHandled(&fHandled);
4974 LogRel(("QuitTimer: rc=%d handled=%d\n", rc, fHandled));
4975 if (RT_FAILURE(rc) || !fHandled)
4976 {
4977 /* event was not handled, power down the guest */
4978 gfACPITerm = FALSE;
4979 SDL_Event event = {0};
4980 event.type = SDL_QUIT;
4981 PushSDLEventForSure(&event);
4982 }
4983 }
4984 /* one-shot */
4985 return 0;
4986}
4987
4988/**
4989 * Wait for the next SDL event. Don't use SDL_WaitEvent since this function
4990 * calls SDL_Delay(10) if the event queue is empty.
4991 */
4992static int WaitSDLEvent(SDL_Event *event)
4993{
4994 for (;;)
4995 {
4996 int rc = SDL_PollEvent(event);
4997 if (rc == 1)
4998 {
4999#ifdef USE_XPCOM_QUEUE_THREAD
5000 if (event->type == SDL_USER_EVENT_XPCOM_EVENTQUEUE)
5001 consumedXPCOMUserEvent();
5002#endif
5003 return 1;
5004 }
5005 /* Immediately wake up if new SDL events are available. This does not
5006 * work for internal SDL events. Don't wait more than 10ms. */
5007 RTSemEventWait(g_EventSemSDLEvents, 10);
5008 }
5009}
5010
5011/**
5012 * Ensure that an SDL event is really enqueued. Try multiple times if necessary.
5013 */
5014int PushSDLEventForSure(SDL_Event *event)
5015{
5016 int ntries = 10;
5017 for (; ntries > 0; ntries--)
5018 {
5019 int rc = SDL_PushEvent(event);
5020 RTSemEventSignal(g_EventSemSDLEvents);
5021#ifdef VBOX_WITH_SDL13
5022 if (rc == 1)
5023#else
5024 if (rc == 0)
5025#endif
5026 return 0;
5027 Log(("PushSDLEventForSure: waiting for 2ms (rc = %d)\n", rc));
5028 RTThreadSleep(2);
5029 }
5030 LogRel(("WARNING: Failed to enqueue SDL event %d.%d!\n",
5031 event->type, event->type == SDL_USEREVENT ? event->user.type : 0));
5032 return -1;
5033}
5034
5035#ifdef VBOXSDL_WITH_X11
5036/**
5037 * Special SDL_PushEvent function for NotifyUpdate events. These events may occur in bursts
5038 * so make sure they don't flood the SDL event queue.
5039 */
5040void PushNotifyUpdateEvent(SDL_Event *event)
5041{
5042 int rc = SDL_PushEvent(event);
5043#ifdef VBOX_WITH_SDL13
5044 bool fSuccess = (rc == 1);
5045#else
5046 bool fSuccess = (rc == 0);
5047#endif
5048
5049 RTSemEventSignal(g_EventSemSDLEvents);
5050 AssertMsg(fSuccess, ("SDL_PushEvent returned SDL error\n"));
5051 /* A global counter is faster than SDL_PeepEvents() */
5052 if (fSuccess)
5053 ASMAtomicIncS32(&g_cNotifyUpdateEventsPending);
5054 /* In order to not flood the SDL event queue, yield the CPU or (if there are already many
5055 * events queued) even sleep */
5056 if (g_cNotifyUpdateEventsPending > 96)
5057 {
5058 /* Too many NotifyUpdate events, sleep for a small amount to give the main thread time
5059 * to handle these events. The SDL queue can hold up to 128 events. */
5060 Log(("PushNotifyUpdateEvent: Sleep 1ms\n"));
5061 RTThreadSleep(1);
5062 }
5063 else
5064 RTThreadYield();
5065}
5066#endif /* VBOXSDL_WITH_X11 */
5067
5068/**
5069 *
5070 */
5071static void SetFullscreen(bool enable)
5072{
5073 if (enable == gpFramebuffer[0]->getFullscreen())
5074 return;
5075
5076 if (!gfFullscreenResize)
5077 {
5078 /*
5079 * The old/default way: SDL will resize the host to fit the guest screen resolution.
5080 */
5081 gpFramebuffer[0]->setFullscreen(enable);
5082 }
5083 else
5084 {
5085 /*
5086 * The alternate way: Switch to fullscreen with the host screen resolution and adapt
5087 * the guest screen resolution to the host window geometry.
5088 */
5089 uint32_t NewWidth = 0, NewHeight = 0;
5090 if (enable)
5091 {
5092 /* switch to fullscreen */
5093 gmGuestNormalXRes = gpFramebuffer[0]->getGuestXRes();
5094 gmGuestNormalYRes = gpFramebuffer[0]->getGuestYRes();
5095 gpFramebuffer[0]->getFullscreenGeometry(&NewWidth, &NewHeight);
5096 }
5097 else
5098 {
5099 /* switch back to saved geometry */
5100 NewWidth = gmGuestNormalXRes;
5101 NewHeight = gmGuestNormalYRes;
5102 }
5103 if (NewWidth != 0 && NewHeight != 0)
5104 {
5105 gpFramebuffer[0]->setFullscreen(enable);
5106 gfIgnoreNextResize = TRUE;
5107 gDisplay->SetVideoModeHint(NewWidth, NewHeight, 0, 0);
5108 }
5109 }
5110}
5111
5112#ifdef VBOX_WITH_SDL13
5113static VBoxSDLFB * getFbFromWinId(SDL_WindowID id)
5114{
5115 for (unsigned i = 0; i < gcMonitors; i++)
5116 if (gpFramebuffer[i]->hasWindow(id))
5117 return gpFramebuffer[i];
5118
5119 return NULL;
5120}
5121#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