VirtualBox

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

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

cosmetical fix

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