VirtualBox

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

Last change on this file since 20719 was 20627, checked in by vboxsync, 16 years ago

Hrmpf

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