VirtualBox

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

Last change on this file since 12986 was 12449, checked in by vboxsync, 16 years ago

+changed IFramebuffer interface to report id of associated window if there's one
+changed sdl/qt3/qt4 frontends's interface implementations to report this id
+added VBoxSharedCrOpenGL hgcm service
(VBoxManage.exe setextradata lvm_winxp_sp2 VBoxInternal/Devices/VMMDev/0/LUN#0/Config/crOpenGLEnabled 1)
+changed crserver to be launched from vmmdev by guest request
+added hgcm call to supply desired window id to render spu
+changed guest icd driver to initialize hgcm and cause tcpip listener startup on host
+fixed spu finalization
+fixed q3 startup, again :)

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