VirtualBox

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

Last change on this file since 16316 was 16151, checked in by vboxsync, 16 years ago

fixed SDL copyright message

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

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