VirtualBox

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

最後變更 在這個檔案從24612是 24493,由 vboxsync 提交於 15 年 前

API/Machine,Session: add a force mount parameter to MountMedium and the associated other places

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

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