VirtualBox

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

Last change on this file since 42631 was 42472, checked in by vboxsync, 12 years ago

better help text

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