VirtualBox

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

Last change on this file since 98304 was 98304, checked in by vboxsync, 2 years ago

FE/SDL. bugref:9449. Removing more SDL 1.2 bits.

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