VirtualBox

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

Last change on this file since 17942 was 17737, checked in by vboxsync, 16 years ago

Main: rename IVirtualBox::machines2[] to machines[]

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

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