VirtualBox

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

Last change on this file since 6438 was 6438, checked in by vboxsync, 17 years ago

-acpiterm => -termacpi

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