VirtualBox

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

Last change on this file since 29776 was 29655, checked in by vboxsync, 15 years ago

FE/SDL: use the X11 keyboard library

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