VirtualBox

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

Last change on this file since 3120 was 3120, checked in by vboxsync, 18 years ago

two typos

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

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