VirtualBox

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

Last change on this file since 18761 was 18751, checked in by vboxsync, 16 years ago

Frontends/SDL: double-dash command line options

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