VirtualBox

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

Last change on this file since 28399 was 28205, checked in by vboxsync, 15 years ago

Main/VirtualBoxCallback: rename OnSnapshotDiscard to OnSnapshotDeleted for consistency, clean up wording and other minor issues

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