VirtualBox

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

Last change on this file since 44249 was 44039, checked in by vboxsync, 12 years ago

Main: renavation com::Guid class. PR5744

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