VirtualBox

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

Last change on this file since 20554 was 20436, checked in by vboxsync, 16 years ago

Windows build fix

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