VirtualBox

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

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

COM: missed pieces of scriptability support

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