VirtualBox

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

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

made Qt4 the default GUI; VBOX_VRDP => VBOX_WITH_VRDP; VBOX_HGCM => VBOX_WITH_HGCM; Makefile cleanup

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

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