VirtualBox

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

Last change on this file since 10430 was 10430, checked in by vboxsync, 17 years ago

VBoxSDL: added -nohostkeys parameter to disable dedicated hostkey combinations (customer demanded feature)

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