VirtualBox

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

Last change on this file since 18608 was 18494, checked in by vboxsync, 16 years ago

VBoxSDL: size_t and uintptr_t warnings.

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

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