VirtualBox

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

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

VBoxSDL: cleanup to get X11 dependencies right

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

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