VirtualBox

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

Last change on this file since 29218 was 28960, checked in by vboxsync, 15 years ago

Frontends: Use VBOX_E_DONT_CALL_AGAIN with IConsoleCallback.

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