VirtualBox

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

Last change on this file since 16021 was 15533, checked in by vboxsync, 16 years ago

Main: rip out obsolete TAPFileDescriptor, TAPSetupApplication, TAPTerminateApplication attributes; plus subsequent VBoxSDL changes

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette