VirtualBox

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

Last change on this file since 22480 was 22305, checked in by vboxsync, 15 years ago

Main: generic callback wrappers mechanism

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

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