VirtualBox

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

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

some logs

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 140.5 KB
Line 
1/** @file
2 * VBox frontends: VBoxSDL (simple frontend based on SDL):
3 * Main code
4 */
5
6/*
7 * Copyright (C) 2006-2007 innotek GmbH
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License as published by the Free Software Foundation,
13 * in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
14 * distribution. VirtualBox OSE is distributed in the hope that it will
15 * be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * If you received this file as part of a commercial VirtualBox
18 * distribution, then only the terms of your commercial VirtualBox
19 * license agreement apply instead of the previous paragraph.
20 */
21
22/*******************************************************************************
23* Header Files *
24*******************************************************************************/
25#define LOG_GROUP LOG_GROUP_GUI
26
27#include <VBox/com/com.h>
28#include <VBox/com/string.h>
29#include <VBox/com/Guid.h>
30#include <VBox/com/ErrorInfo.h>
31#include <VBox/com/EventQueue.h>
32#include <VBox/com/VirtualBox.h>
33
34using namespace com;
35
36#if defined (__LINUX__)
37#include <X11/Xlib.h>
38#include <X11/cursorfont.h> /* for XC_left_ptr */
39#include <X11/Xcursor/Xcursor.h>
40#endif
41
42#include <SDL_syswm.h> /* for SDL_GetWMInfo() */
43
44#include "VBoxSDL.h"
45#include "Framebuffer.h"
46#include "Helper.h"
47
48#include <VBox/types.h>
49#include <VBox/err.h>
50#include <VBox/param.h>
51#include <VBox/log.h>
52#include <VBox/version.h>
53#include <iprt/path.h>
54#include <iprt/string.h>
55#include <iprt/runtime.h>
56#include <iprt/assert.h>
57#include <iprt/semaphore.h>
58#include <iprt/stream.h>
59#include <iprt/uuid.h>
60#include <iprt/ldr.h>
61#include <iprt/alloca.h>
62
63#include <signal.h>
64
65#include <vector>
66
67/* Xlib would re-define our enums */
68#undef True
69#undef False
70
71/*******************************************************************************
72* Defined Constants And Macros *
73*******************************************************************************/
74#ifdef VBOX_SECURELABEL
75/** extra data key for the secure label */
76#define VBOXSDL_SECURELABEL_EXTRADATA "VBoxSDL/SecureLabel"
77/** label area height in pixels */
78#define SECURE_LABEL_HEIGHT 20
79#endif
80
81/** Enables the rawr[0|3], patm, and casm options. */
82#define VBOXSDL_ADVANCED_OPTIONS
83
84/*******************************************************************************
85* Structures and Typedefs *
86*******************************************************************************/
87/** Pointer shape change event data strucure */
88struct PointerShapeChangeData
89{
90 PointerShapeChangeData (BOOL aVisible, BOOL aAlpha, ULONG aXHot, ULONG aYHot,
91 ULONG aWidth, ULONG aHeight, const uint8_t *aShape)
92 : visible (aVisible), alpha (aAlpha), xHot (aXHot), yHot (aYHot),
93 width (aWidth), height (aHeight), shape (NULL)
94 {
95 // make a copy of the shape
96 if (aShape)
97 {
98 uint32_t shapeSize = ((((aWidth + 7) / 8) * aHeight + 3) & ~3) + aWidth * 4 * aHeight;
99 shape = new uint8_t [shapeSize];
100 if (shape)
101 memcpy ((void *) shape, (void *) aShape, shapeSize);
102 }
103 }
104
105 ~PointerShapeChangeData()
106 {
107 if (shape) delete[] shape;
108 }
109
110 const BOOL visible;
111 const BOOL alpha;
112 const ULONG xHot;
113 const ULONG yHot;
114 const ULONG width;
115 const ULONG height;
116 const uint8_t *shape;
117};
118
119enum TitlebarMode
120{
121 TITLEBAR_NORMAL = 1,
122 TITLEBAR_STARTUP = 2,
123 TITLEBAR_SAVE = 3,
124 TITLEBAR_SNAPSHOT = 4
125};
126
127/*******************************************************************************
128* Internal Functions *
129*******************************************************************************/
130static bool UseAbsoluteMouse(void);
131static void ResetKeys(void);
132static void ProcessKey(SDL_KeyboardEvent *ev);
133static void InputGrabStart(void);
134static void InputGrabEnd(void);
135static void SendMouseEvent(int dz, int button, int down);
136static void UpdateTitlebar(TitlebarMode mode, uint32_t u32User = 0);
137static void SetPointerShape(const PointerShapeChangeData *data);
138static void HandleGuestCapsChanged(void);
139static int HandleHostKey(const SDL_KeyboardEvent *pEv);
140static Uint32 StartupTimer(Uint32 interval, void *param);
141static Uint32 ResizeTimer(Uint32 interval, void *param);
142
143
144/*******************************************************************************
145* Global Variables *
146*******************************************************************************/
147#if defined (DEBUG_dmik)
148// my mini kbd doesn't have RCTRL...
149static int gHostKeyMod = KMOD_RSHIFT;
150static int gHostKeySym1 = SDLK_RSHIFT;
151static int gHostKeySym2 = SDLK_UNKNOWN;
152#else
153static int gHostKeyMod = KMOD_RCTRL;
154static int gHostKeySym1 = SDLK_RCTRL;
155static int gHostKeySym2 = SDLK_UNKNOWN;
156#endif
157static BOOL gfGrabbed = FALSE;
158static BOOL gfGrabOnMouseClick = TRUE;
159static BOOL gfAllowFullscreenToggle = TRUE;
160static BOOL gfAbsoluteMouseHost = FALSE;
161static BOOL gfAbsoluteMouseGuest = FALSE;
162static BOOL gfGuestNeedsHostCursor = FALSE;
163static BOOL gfOffCursorActive = FALSE;
164static BOOL gfGuestNumLockPressed = FALSE;
165static BOOL gfGuestCapsLockPressed = FALSE;
166static BOOL gfGuestScrollLockPressed = FALSE;
167static int gcGuestNumLockAdaptions = 2;
168static int gcGuestCapsLockAdaptions = 2;
169
170/** modifier keypress status (scancode as index) */
171static uint8_t gaModifiersState[256];
172
173static ComPtr<IMachine> gMachine;
174static ComPtr<IConsole> gConsole;
175static ComPtr<IMachineDebugger> gMachineDebugger;
176static ComPtr<IKeyboard> gKeyboard;
177static ComPtr<IMouse> gMouse;
178static ComPtr<IDisplay> gDisplay;
179static ComPtr<IVRDPServer> gVrdpServer;
180static ComPtr<IProgress> gProgress;
181
182static VBoxSDLFB *gpFrameBuffer = NULL;
183static SDL_Cursor *gpDefaultCursor = NULL;
184#ifdef __LINUX__
185static Cursor gpDefaultOrigX11Cursor;
186#endif
187static SDL_Cursor *gpCustomCursor = NULL;
188static WMcursor *gpCustomOrigWMcursor = NULL;
189static SDL_Cursor *gpOffCursor = NULL;
190static SDL_TimerID gSdlResizeTimer = NULL;
191
192#ifdef __LINUX__
193static SDL_SysWMinfo gSdlInfo;
194#endif
195
196#ifdef VBOX_SECURELABEL
197#ifdef __WIN__
198#define LIBSDL_TTF_NAME "SDL_ttf"
199#else
200#define LIBSDL_TTF_NAME "libSDL_ttf"
201#endif
202RTLDRMOD gLibrarySDL_ttf = NIL_RTLDRMOD;
203#endif
204
205/**
206 * Callback handler for VirtualBox events
207 */
208class VBoxSDLCallback :
209 public IVirtualBoxCallback
210{
211public:
212 VBoxSDLCallback()
213 {
214#if defined (__WIN__)
215 refcnt = 0;
216#endif
217 }
218
219 virtual ~VBoxSDLCallback()
220 {
221 }
222
223#ifdef __WIN__
224 STDMETHOD_(ULONG, AddRef)()
225 {
226 return ::InterlockedIncrement(&refcnt);
227 }
228 STDMETHOD_(ULONG, Release)()
229 {
230 long cnt = ::InterlockedDecrement(&refcnt);
231 if (cnt == 0)
232 delete this;
233 return cnt;
234 }
235 STDMETHOD(QueryInterface)(REFIID riid , void **ppObj)
236 {
237 if (riid == IID_IUnknown)
238 {
239 *ppObj = this;
240 AddRef();
241 return S_OK;
242 }
243 if (riid == IID_IVirtualBoxCallback)
244 {
245 *ppObj = this;
246 AddRef();
247 return S_OK;
248 }
249 *ppObj = NULL;
250 return E_NOINTERFACE;
251 }
252#endif
253
254 NS_DECL_ISUPPORTS
255
256 STDMETHOD(OnMachineStateChange)(INPTR GUIDPARAM machineId, MachineState_T state)
257 {
258 return S_OK;
259 }
260
261 STDMETHOD(OnMachineDataChange)(INPTR GUIDPARAM machineId)
262 {
263 return S_OK;
264 }
265
266 STDMETHOD(OnExtraDataCanChange)(INPTR GUIDPARAM machineId, INPTR BSTR key, INPTR BSTR value,
267 BSTR *error, BOOL *changeAllowed)
268 {
269 /* we never disagree */
270 if (!changeAllowed)
271 return E_INVALIDARG;
272 *changeAllowed = TRUE;
273 return S_OK;
274 }
275
276 STDMETHOD(OnExtraDataChange)(INPTR GUIDPARAM machineId, INPTR BSTR key, INPTR BSTR value)
277 {
278#ifdef VBOX_SECURELABEL
279 Assert(key);
280 if (gMachine)
281 {
282 /*
283 * check if we're interested in the message
284 */
285 Guid ourGuid;
286 Guid messageGuid = machineId;
287 gMachine->COMGETTER(Id)(ourGuid.asOutParam());
288 if (ourGuid == messageGuid)
289 {
290 Bstr keyString = key;
291 if (keyString && keyString == VBOXSDL_SECURELABEL_EXTRADATA)
292 {
293 /*
294 * Notify SDL thread of the string update
295 */
296 SDL_Event event = {0};
297 event.type = SDL_USEREVENT;
298 event.user.type = SDL_USER_EVENT_SECURELABEL_UPDATE;
299 int rc = SDL_PushEvent(&event);
300 NOREF(rc);
301 AssertMsg(!rc, ("SDL_PushEvent returned with SDL error '%s'\n", SDL_GetError()));
302 }
303 }
304 }
305#endif /* VBOX_SECURELABEL */
306 return S_OK;
307 }
308
309 STDMETHOD(OnMediaRegistered) (INPTR GUIDPARAM mediaId, DeviceType_T mediaType,
310 BOOL registered)
311 {
312 NOREF (mediaId);
313 NOREF (mediaType);
314 NOREF (registered);
315 return S_OK;
316 }
317
318 STDMETHOD(OnMachineRegistered)(INPTR GUIDPARAM machineId, BOOL registered)
319 {
320 return S_OK;
321 }
322
323 STDMETHOD(OnSessionStateChange)(INPTR GUIDPARAM machineId, SessionState_T state)
324 {
325 return S_OK;
326 }
327
328 STDMETHOD(OnSnapshotTaken) (INPTR GUIDPARAM aMachineId, INPTR GUIDPARAM aSnapshotId)
329 {
330 return S_OK;
331 }
332
333 STDMETHOD(OnSnapshotDiscarded) (INPTR GUIDPARAM aMachineId, INPTR GUIDPARAM aSnapshotId)
334 {
335 return S_OK;
336 }
337
338 STDMETHOD(OnSnapshotChange) (INPTR GUIDPARAM aMachineId, INPTR GUIDPARAM aSnapshotId)
339 {
340 return S_OK;
341 }
342
343private:
344#ifdef __WIN__
345 long refcnt;
346#endif
347
348};
349
350/**
351 * Callback handler for machine events
352 */
353class VBoxSDLConsoleCallback :
354 public IConsoleCallback
355{
356public:
357 VBoxSDLConsoleCallback() : m_fIgnorePowerOffEvents(false)
358 {
359#if defined (__WIN__)
360 refcnt = 0;
361#endif
362 }
363
364 virtual ~VBoxSDLConsoleCallback()
365 {
366 }
367
368#ifdef __WIN__
369 STDMETHOD_(ULONG, AddRef)()
370 {
371 return ::InterlockedIncrement(&refcnt);
372 }
373 STDMETHOD_(ULONG, Release)()
374 {
375 long cnt = ::InterlockedDecrement(&refcnt);
376 if (cnt == 0)
377 delete this;
378 return cnt;
379 }
380 STDMETHOD(QueryInterface)(REFIID riid , void **ppObj)
381 {
382 if (riid == IID_IUnknown)
383 {
384 *ppObj = this;
385 AddRef();
386 return S_OK;
387 }
388 if (riid == IID_IConsoleCallback)
389 {
390 *ppObj = this;
391 AddRef();
392 return S_OK;
393 }
394 *ppObj = NULL;
395 return E_NOINTERFACE;
396 }
397#endif
398
399 NS_DECL_ISUPPORTS
400
401 STDMETHOD(OnMousePointerShapeChange) (BOOL visible, BOOL alpha, ULONG xHot, ULONG yHot,
402 ULONG width, ULONG height, BYTE *shape)
403 {
404 PointerShapeChangeData *data;
405 data = new PointerShapeChangeData (visible, alpha, xHot, yHot, width, height,
406 shape);
407 Assert (data);
408 if (!data)
409 return E_FAIL;
410
411 SDL_Event event = {0};
412 event.type = SDL_USEREVENT;
413 event.user.type = SDL_USER_EVENT_POINTER_CHANGE;
414 event.user.data1 = data;
415
416 int rc = SDL_PushEvent (&event);
417 AssertMsg(!rc, ("SDL_PushEvent returned with SDL error '%s'\n", SDL_GetError()));
418 if (rc)
419 delete data;
420
421 return S_OK;
422 }
423
424 STDMETHOD(OnMouseCapabilityChange)(BOOL supportsAbsolute, BOOL needsHostCursor)
425 {
426 LogFlow(("OnMouseCapabilityChange: supportsAbsolute = %d\n", supportsAbsolute));
427 gfAbsoluteMouseGuest = supportsAbsolute;
428 gfGuestNeedsHostCursor = needsHostCursor;
429
430 SDL_Event event = {0};
431 event.type = SDL_USEREVENT;
432 event.user.type = SDL_USER_EVENT_GUEST_CAP_CHANGED;
433
434 int rc = SDL_PushEvent (&event);
435 NOREF(rc);
436 AssertMsg(!rc, ("SDL_PushEvent returned with SDL error '%s'\n", SDL_GetError()));
437 return S_OK;
438 }
439
440 STDMETHOD(OnStateChange)(MachineState_T machineState)
441 {
442 LogFlow(("OnStateChange: machineState = %d (%s)\n", machineState, GetStateName(machineState)));
443 SDL_Event event = {0};
444
445 if ( machineState == MachineState_Aborted
446 || (machineState == MachineState_Saved && !m_fIgnorePowerOffEvents)
447 || (machineState == MachineState_PoweredOff && !m_fIgnorePowerOffEvents))
448 {
449 /*
450 * We have to inform the SDL thread that the application has be terminated
451 */
452 event.type = SDL_USEREVENT;
453 event.user.type = SDL_USER_EVENT_TERMINATE;
454 event.user.code = machineState == MachineState_Aborted
455 ? VBOXSDL_TERM_ABEND
456 : VBOXSDL_TERM_NORMAL;
457 }
458 else
459 {
460 /*
461 * Inform the SDL thread to refresh the titlebar
462 */
463 event.type = SDL_USEREVENT;
464 event.user.type = SDL_USER_EVENT_UPDATE_TITLEBAR;
465 }
466
467 int rc = SDL_PushEvent(&event);
468 NOREF(rc);
469 AssertMsg(!rc, ("SDL_PushEvent returned with SDL error '%s'\n", SDL_GetError()));
470 return S_OK;
471 }
472
473 STDMETHOD(OnAdditionsStateChange)()
474 {
475 return S_OK;
476 }
477
478 STDMETHOD(OnKeyboardLedsChange)(BOOL fNumLock, BOOL fCapsLock, BOOL fScrollLock)
479 {
480 /* Don't bother the guest with NumLock scancodes if he doesn't set the NumLock LED */
481 if (gfGuestNumLockPressed != fNumLock)
482 gcGuestNumLockAdaptions = 2;
483 if (gfGuestCapsLockPressed != fCapsLock)
484 gcGuestCapsLockAdaptions = 2;
485 gfGuestNumLockPressed = fNumLock;
486 gfGuestCapsLockPressed = fCapsLock;
487 gfGuestScrollLockPressed = fScrollLock;
488 return S_OK;
489 }
490
491 STDMETHOD(OnUSBDeviceStateChange)(IUSBDevice *device, BOOL attached,
492 IVirtualBoxErrorInfo *message)
493 {
494 return S_OK;
495 }
496
497 STDMETHOD(OnRuntimeError)(BOOL fFatal, INPTR BSTR id, INPTR BSTR message)
498 {
499 MachineState_T machineState;
500 gMachine->COMGETTER(State)(&machineState);
501 const char *pszType;
502 bool fPaused = machineState == MachineState_Paused;
503 if (fFatal)
504 pszType = "FATAL ERROR";
505 else if (machineState == MachineState_Paused)
506 pszType = "Non-fatal ERROR";
507 else
508 pszType = "WARNING";
509 RTPrintf("\n%s: ** %lS **\n%lS\n%s\n", pszType, id, message,
510 fPaused ? "The VM was paused. Continue with HostKey + P after you solved the problem.\n" : "");
511 return S_OK;
512 }
513
514 STDMETHOD(OnCanShowWindow)(BOOL *canShow)
515 {
516 if (!canShow)
517 return E_POINTER;
518#if defined (__LINUX__)
519 /// @todo see the big comment in Frontends/VirtualBox/src/VBoxVMListBoxItem::switchTo()
520 *canShow = FALSE;
521#else
522 SDL_SysWMinfo info;
523 SDL_VERSION(&info.version);
524 *canShow = !!SDL_GetWMInfo(&info);
525#endif
526 return S_OK;
527 }
528
529 STDMETHOD(OnShowWindow) (ULONG64 *winId)
530 {
531 SDL_SysWMinfo info;
532 SDL_VERSION(&info.version);
533 if (SDL_GetWMInfo(&info))
534 {
535#if defined (__LINUX__)
536 *winId = (ULONG64) info.info.x11.window;
537#elif defined (__WIN__)
538 *winId = (ULONG64) info.window;
539#else
540 AssertFailed();
541 return E_FAIL;
542#endif
543 return S_OK;
544 }
545 AssertFailed();
546 return E_FAIL;
547 }
548
549 static const char *GetStateName(MachineState_T machineState)
550 {
551 switch (machineState)
552 {
553 case MachineState_InvalidMachineState: return "InvalidMachineState";
554 case MachineState_Running: return "Running";
555 case MachineState_Restoring: return "Restoring";
556 case MachineState_Starting: return "Starting";
557 case MachineState_PoweredOff: return "PoweredOff";
558 case MachineState_Saved: return "Saved";
559 case MachineState_Aborted: return "Aborted";
560 case MachineState_Stopping: return "Stopping";
561 default: return "no idea";
562 }
563 }
564
565 void ignorePowerOffEvents(bool fIgnore)
566 {
567 m_fIgnorePowerOffEvents = fIgnore;
568 }
569
570private:
571#ifdef __WIN__
572 long refcnt;
573#endif
574 bool m_fIgnorePowerOffEvents;
575};
576
577#ifdef VBOX_WITH_XPCOM
578NS_DECL_CLASSINFO(VBoxSDLCallback)
579NS_IMPL_ISUPPORTS1_CI(VBoxSDLCallback, IVirtualBoxCallback)
580NS_DECL_CLASSINFO(VBoxSDLConsoleCallback)
581NS_IMPL_ISUPPORTS1_CI(VBoxSDLConsoleCallback, IConsoleCallback)
582#endif /* VBOX_WITH_XPCOM */
583
584static void show_usage()
585{
586 RTPrintf("Usage:\n"
587 " -vm <id|name> Virtual machine to start, either UUID or name\n"
588 " -hda <file> Set temporary first hard disk to file\n"
589 " -fda <file> Set temporary first floppy disk to file\n"
590 " -cdrom <file> Set temporary CDROM/DVD to file/device ('none' to unmount)\n"
591 " -boot <a|c|d> Set temporary boot device (a = floppy, c = first hard disk, d = DVD)\n"
592 " -m <size> Set temporary memory size in megabytes\n"
593 " -vram <size> Set temporary size of video memory in megabytes\n"
594 " -fullscreen Start VM in fullscreen mode\n"
595 " -fixedmode <w> <h> <bpp> Use a fixed SDL video mode with given width, height and bits per pixel\n"
596 " -nofstoggle Forbid switching to/from fullscreen mode\n"
597 " -noresize Make the SDL frame non resizable\n"
598 " -nohostkey Disable hostkey\n"
599 " -nograbonclick Disable mouse/keyboard grabbing on mouse click w/o additions\n"
600 " -detecthostkey Get the hostkey identifier and modifier state\n"
601 " -hostkey <key> {<key2>} <mod> Set the host key to the values obtained using -detecthostkey\n"
602#if defined(__LINUX__) || defined(__DARWIN__) /** @todo UNIXISH_TAP stuff out of main and up to Config.kmk! */
603 " -tapdev<1-N> <dev> Use existing persistent TAP device with the given name\n"
604 " -tapfd<1-N> <fd> Use existing TAP device, don't allocate\n"
605#endif
606#ifdef VBOX_VRDP
607 " -vrdp <port> Listen for VRDP connections on port (default if not specified)\n"
608#endif
609 " -discardstate Discard saved state (if present) and revert to last snapshot (if present)\n"
610#ifdef VBOX_SECURELABEL
611 " -securelabel Display a secure VM label at the top of the screen\n"
612 " -seclabelfnt TrueType (.ttf) font file for secure session label\n"
613 " -seclabelsiz Font point size for secure session label (default 12)\n"
614 " -seclabelfgcol <rgb> Secure label text color RGB value in 6 digit hexadecimal (eg: FFFF00)\n"
615 " -seclabelbgcol <rgb> Secure label background color RGB value in 6 digit hexadecimal (eg: FF0000)\n"
616#endif
617#ifdef VBOXSDL_ADVANCED_OPTIONS
618 " -[no]rawr0 Enable or disable raw ring 3\n"
619 " -[no]rawr3 Enable or disable raw ring 0\n"
620 " -[no]patm Enable or disable PATM\n"
621 " -[no]csam Enable or disable CSAM\n"
622 " -[no]hwvirtex Permit or deny the usage of VMX/SVN\n"
623#endif
624 "\n");
625}
626
627static void PrintError(const char *pszName, const BSTR pwszDescr, const BSTR pwszComponent=NULL)
628{
629 const char *pszFile, *pszFunc, *pszStat;
630 char pszBuffer[1024];
631 com::ErrorInfo info;
632
633 RTStrPrintf(pszBuffer, sizeof(pszBuffer), "%lS", pwszDescr);
634
635 RTPrintf("\n%s! Error info:\n", pszName);
636 if ( (pszFile = strstr(pszBuffer, "At '"))
637 && (pszFunc = strstr(pszBuffer, ") in "))
638 && (pszStat = strstr(pszBuffer, "VBox status code: ")))
639 RTPrintf(" %.*s %.*s\n In%.*s %s",
640 pszFile-pszBuffer, pszBuffer,
641 pszFunc-pszFile+1, pszFile,
642 pszStat-pszFunc-4, pszFunc+4,
643 pszStat);
644 else
645 RTPrintf("%s\n", pszBuffer);
646
647 if (pwszComponent)
648 RTPrintf("(component %lS).\n", pwszComponent);
649
650 RTPrintf("\n");
651}
652
653#ifdef __LINUX__
654/**
655 * Custom signal handler. Currently it is only used to release modifier
656 * keys when receiving the USR1 signal. When switching VTs, we might not
657 * get release events for Ctrl-Alt and in case a savestate is performed
658 * on the new VT, the VM will be saved with modifier keys stuck. This is
659 * annoying enough for introducing this hack.
660 */
661void signal_handler(int sig, siginfo_t *info, void *secret)
662{
663 /* only SIGUSR1 is interesting */
664 if (sig == SIGUSR1)
665 {
666 /* just release the modifiers */
667 ResetKeys();
668 }
669}
670#endif /* __LINUX__ */
671
672/** entry point */
673int main(int argc, char *argv[])
674{
675 /*
676 * Before we do *anything*, we initialize the runtime.
677 */
678 int rcRT = RTR3Init(true, ~(size_t)0);
679 if (VBOX_FAILURE(rcRT))
680 {
681 RTPrintf("Error: RTR3Init failed rcRC=%d\n", rcRT);
682 return 1;
683 }
684
685#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 LogRel(("VBoxSDL: NUM lock initially %s, CAPS lock initially %s\n",
1849 !!(SDL_GetModState() & KMOD_NUM) ? "ON" : "OFF",
1850 !!(SDL_GetModState() & KMOD_CAPS) ? "ON" : "OFF"));
1851
1852 /* start regular timer so we don't starve in the event loop */
1853 SDL_TimerID sdlTimer;
1854 sdlTimer = SDL_AddTimer(100, StartupTimer, NULL);
1855
1856 /* loop until the powerup processing is done */
1857 MachineState_T machineState;
1858 do
1859 {
1860 rc = gMachine->COMGETTER(State)(&machineState);
1861 if ( rc == S_OK
1862 && ( machineState == MachineState_Starting
1863 || machineState == MachineState_Restoring))
1864 {
1865 /*
1866 * wait for the next event. This is uncritical as
1867 * power up guarantees to change the machine state
1868 * to either running or aborted and a machine state
1869 * change will send us an event. However, we have to
1870 * service the XPCOM event queue!
1871 */
1872#ifdef USE_XPCOM_QUEUE_THREAD
1873 if (!fXPCOMEventThreadSignaled)
1874 {
1875 signalXPCOMEventQueueThread();
1876 fXPCOMEventThreadSignaled = true;
1877 }
1878#endif
1879 /*
1880 * Wait for SDL events.
1881 */
1882 if (SDL_WaitEvent(&event))
1883 {
1884 switch (event.type)
1885 {
1886 /*
1887 * Timer event. Used to have the titlebar updated.
1888 */
1889 case SDL_USER_EVENT_TIMER:
1890 {
1891 /*
1892 * Update the title bar.
1893 */
1894 UpdateTitlebar(TITLEBAR_STARTUP);
1895 break;
1896 }
1897
1898 /*
1899 * User specific resize event.
1900 */
1901 case SDL_USER_EVENT_RESIZE:
1902 {
1903 LogFlow(("SDL_USER_EVENT_RESIZE\n"));
1904 gpFrameBuffer->resizeGuest();
1905 /* notify the display that the resize has been completed */
1906 gDisplay->ResizeCompleted(0);
1907 break;
1908 }
1909
1910#ifdef USE_XPCOM_QUEUE_THREAD
1911 /*
1912 * User specific XPCOM event queue event
1913 */
1914 case SDL_USER_EVENT_XPCOM_EVENTQUEUE:
1915 {
1916 LogFlow(("SDL_USER_EVENT_XPCOM_EVENTQUEUE: processing XPCOM event queue...\n"));
1917 eventQ->ProcessPendingEvents();
1918 signalXPCOMEventQueueThread();
1919 break;
1920 }
1921#endif /* USE_XPCOM_QUEUE_THREAD */
1922
1923 /*
1924 * Termination event from the on state change callback.
1925 */
1926 case SDL_USER_EVENT_TERMINATE:
1927 {
1928 if (event.user.code != VBOXSDL_TERM_NORMAL)
1929 {
1930 com::ProgressErrorInfo info(gProgress);
1931 if (info.isBasicAvailable())
1932 PrintError("Failed to power up VM", info.getText().raw());
1933 else
1934 RTPrintf("Error: failed to power up VM! No error text available.\n");
1935 }
1936 fTerminateDuringStartup = true;
1937 break;
1938 }
1939
1940 default:
1941 {
1942 LogBird(("VBoxSDL: Unknown SDL event %d (pre)\n", event.type));
1943 break;
1944 }
1945 }
1946
1947 }
1948 }
1949 } while ( rc == S_OK
1950 && ( machineState == MachineState_Starting
1951 || machineState == MachineState_Restoring));
1952
1953 /* kill the timer again */
1954 SDL_RemoveTimer(sdlTimer);
1955 sdlTimer = 0;
1956
1957 /* are we supposed to terminate the process? */
1958 if (fTerminateDuringStartup)
1959 goto leave;
1960
1961 /* did the power up succeed? */
1962 if (machineState != MachineState_Running)
1963 {
1964 com::ProgressErrorInfo info(gProgress);
1965 if (info.isBasicAvailable())
1966 PrintError("Failed to power up VM", info.getText().raw());
1967 else
1968 RTPrintf("Error: failed to power up VM! No error text available (rc = 0x%x state = %d)\n", rc, machineState);
1969 goto leave;
1970 }
1971
1972 // accept power off events from now on because we're running
1973 // note that there's a possible race condition here...
1974 consoleCallback->ignorePowerOffEvents(false);
1975
1976 rc = gConsole->COMGETTER(Keyboard)(gKeyboard.asOutParam());
1977 if (!gKeyboard)
1978 {
1979 RTPrintf("Error: could not get keyboard object!\n");
1980 goto leave;
1981 }
1982 gConsole->COMGETTER(Mouse)(gMouse.asOutParam());
1983 if (!gMouse)
1984 {
1985 RTPrintf("Error: could not get mouse object!\n");
1986 goto leave;
1987 }
1988
1989 UpdateTitlebar(TITLEBAR_NORMAL);
1990
1991 /*
1992 * Enable keyboard repeats
1993 */
1994 SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
1995
1996 /*
1997 * Main event loop
1998 */
1999#ifdef USE_XPCOM_QUEUE_THREAD
2000 if (!fXPCOMEventThreadSignaled)
2001 {
2002 signalXPCOMEventQueueThread();
2003 }
2004#endif
2005 LogFlow(("VBoxSDL: Entering big event loop\n"));
2006 while (SDL_WaitEvent(&event))
2007 {
2008 switch (event.type)
2009 {
2010 /*
2011 * The screen needs to be repainted.
2012 */
2013 case SDL_VIDEOEXPOSE:
2014 {
2015 /// @todo that somehow doesn't seem to work!
2016 gpFrameBuffer->repaint();
2017 break;
2018 }
2019
2020 /*
2021 * Keyboard events.
2022 */
2023 case SDL_KEYDOWN:
2024 case SDL_KEYUP:
2025 {
2026 SDLKey ksym = event.key.keysym.sym;
2027
2028 switch (enmHKeyState)
2029 {
2030 case HKEYSTATE_NORMAL:
2031 {
2032 if ( event.type == SDL_KEYDOWN
2033 && ksym != SDLK_UNKNOWN
2034 && (ksym == gHostKeySym1 || ksym == gHostKeySym2))
2035 {
2036 EvHKeyDown1 = event;
2037 enmHKeyState = ksym == gHostKeySym1 ? HKEYSTATE_DOWN_1ST
2038 : HKEYSTATE_DOWN_2ND;
2039 break;
2040 }
2041 ProcessKey(&event.key);
2042 break;
2043 }
2044
2045 case HKEYSTATE_DOWN_1ST:
2046 case HKEYSTATE_DOWN_2ND:
2047 {
2048 if (gHostKeySym2 != SDLK_UNKNOWN)
2049 {
2050 if ( event.type == SDL_KEYDOWN
2051 && ksym != SDLK_UNKNOWN
2052 && ( enmHKeyState == HKEYSTATE_DOWN_1ST && ksym == gHostKeySym2
2053 || enmHKeyState == HKEYSTATE_DOWN_2ND && ksym == gHostKeySym1))
2054 {
2055 EvHKeyDown2 = event;
2056 enmHKeyState = HKEYSTATE_DOWN;
2057 break;
2058 }
2059 enmHKeyState = event.type == SDL_KEYUP ? HKEYSTATE_NORMAL
2060 : HKEYSTATE_NOT_IT;
2061 ProcessKey(&EvHKeyDown1.key);
2062 ProcessKey(&event.key);
2063 break;
2064 }
2065 /* fall through if no two-key sequence is used */
2066 }
2067
2068 case HKEYSTATE_DOWN:
2069 {
2070 if (event.type == SDL_KEYDOWN)
2071 {
2072 /* potential host key combination, try execute it */
2073 int rc = HandleHostKey(&event.key);
2074 if (rc == VINF_SUCCESS)
2075 {
2076 enmHKeyState = HKEYSTATE_USED;
2077 break;
2078 }
2079 if (VBOX_SUCCESS(rc))
2080 goto leave;
2081 }
2082 else /* SDL_KEYUP */
2083 {
2084 if ( ksym != SDLK_UNKNOWN
2085 && (ksym == gHostKeySym1 || ksym == gHostKeySym2))
2086 {
2087 /* toggle grabbing state */
2088 if (!gfGrabbed)
2089 InputGrabStart();
2090 else
2091 InputGrabEnd();
2092
2093 /* SDL doesn't always reset the keystates, correct it */
2094 ResetKeys();
2095 enmHKeyState = HKEYSTATE_NORMAL;
2096 break;
2097 }
2098 }
2099
2100 /* not host key */
2101 enmHKeyState = HKEYSTATE_NOT_IT;
2102 ProcessKey(&EvHKeyDown1.key);
2103 if (gHostKeySym2 != SDLK_UNKNOWN)
2104 ProcessKey(&EvHKeyDown2.key);
2105 ProcessKey(&event.key);
2106 break;
2107 }
2108
2109 case HKEYSTATE_USED:
2110 {
2111 if ((SDL_GetModState() & ~(KMOD_MODE | KMOD_NUM | KMOD_RESERVED)) == 0)
2112 enmHKeyState = HKEYSTATE_NORMAL;
2113 if (event.type == SDL_KEYDOWN)
2114 {
2115 int rc = HandleHostKey(&event.key);
2116 if (VBOX_SUCCESS(rc) && rc != VINF_SUCCESS)
2117 goto leave;
2118 }
2119 break;
2120 }
2121
2122 default:
2123 AssertMsgFailed(("enmHKeyState=%d\n", enmHKeyState));
2124 /* fall thru */
2125 case HKEYSTATE_NOT_IT:
2126 {
2127 if ((SDL_GetModState() & ~(KMOD_MODE | KMOD_NUM | KMOD_RESERVED)) == 0)
2128 enmHKeyState = HKEYSTATE_NORMAL;
2129 ProcessKey(&event.key);
2130 break;
2131 }
2132 } /* state switch */
2133 break;
2134 }
2135
2136 /*
2137 * The window was closed.
2138 */
2139 case SDL_QUIT:
2140 {
2141 goto leave;
2142 break;
2143 }
2144
2145 /*
2146 * The mouse has moved
2147 */
2148 case SDL_MOUSEMOTION:
2149 {
2150 if (gfGrabbed || UseAbsoluteMouse())
2151 {
2152 SendMouseEvent(0, 0, 0);
2153 }
2154 break;
2155 }
2156
2157 /*
2158 * A mouse button has been clicked or released.
2159 */
2160 case SDL_MOUSEBUTTONDOWN:
2161 case SDL_MOUSEBUTTONUP:
2162 {
2163 SDL_MouseButtonEvent *bev = &event.button;
2164 /* don't grab on mouse click if we have guest additions */
2165 if (!gfGrabbed && !UseAbsoluteMouse() && gfGrabOnMouseClick)
2166 {
2167 if (event.type == SDL_MOUSEBUTTONDOWN && (bev->state & SDL_BUTTON_LMASK))
2168 {
2169 /* start grabbing all events */
2170 InputGrabStart();
2171 }
2172 }
2173 else if (gfGrabbed || UseAbsoluteMouse())
2174 {
2175 int dz = bev->button == SDL_BUTTON_WHEELUP
2176 ? -1
2177 : bev->button == SDL_BUTTON_WHEELDOWN
2178 ? +1
2179 : 0;
2180
2181 /* end host key combination (CTRL+MouseButton) */
2182 switch (enmHKeyState)
2183 {
2184 case HKEYSTATE_DOWN_1ST:
2185 case HKEYSTATE_DOWN_2ND:
2186 enmHKeyState = HKEYSTATE_NOT_IT;
2187 ProcessKey(&EvHKeyDown1.key);
2188 break;
2189 case HKEYSTATE_DOWN:
2190 enmHKeyState = HKEYSTATE_NOT_IT;
2191 ProcessKey(&EvHKeyDown1.key);
2192 if (gHostKeySym2 != SDLK_UNKNOWN)
2193 ProcessKey(&EvHKeyDown2.key);
2194 break;
2195 default:
2196 break;
2197 }
2198
2199 SendMouseEvent(dz, event.type == SDL_MOUSEBUTTONDOWN, bev->button);
2200 }
2201 break;
2202 }
2203
2204 /*
2205 * The window has gained or lost focus.
2206 */
2207 case SDL_ACTIVEEVENT:
2208 {
2209 /*
2210 * There is a strange behaviour in SDL when running without a window
2211 * manager: When SDL_WM_GrabInput(SDL_GRAB_ON) is called we receive two
2212 * consecutive events SDL_ACTIVEEVENTs (input lost, input gained).
2213 * Asking SDL_GetAppState() seems the better choice.
2214 */
2215 if (gfGrabbed && (SDL_GetAppState() & SDL_APPINPUTFOCUS) == 0)
2216 {
2217 /*
2218 * another window has stolen the (keyboard) input focus
2219 */
2220 InputGrabEnd();
2221 }
2222 break;
2223 }
2224
2225 /*
2226 * The SDL window was resized
2227 */
2228 case SDL_VIDEORESIZE:
2229 {
2230 if (gDisplay)
2231 {
2232#ifdef VBOX_SECURELABEL
2233 uResizeWidth = event.resize.w;
2234 uResizeHeight = RT_MAX(0, event.resize.h - SECURE_LABEL_HEIGHT);
2235#else
2236 uResizeHeight = event.resize.h;
2237#endif
2238 if (gSdlResizeTimer)
2239 SDL_RemoveTimer(gSdlResizeTimer);
2240 gSdlResizeTimer = SDL_AddTimer(300, ResizeTimer, NULL);
2241 }
2242 break;
2243 }
2244
2245 /*
2246 * User specific update event.
2247 */
2248 /** @todo use a common user event handler so that SDL_PeepEvents() won't
2249 * possibly remove other events in the queue!
2250 */
2251 case SDL_USER_EVENT_UPDATERECT:
2252 {
2253 /*
2254 * Decode event parameters.
2255 */
2256 #define DECODEX(event) ((intptr_t)(event).user.data1 >> 16)
2257 #define DECODEY(event) ((intptr_t)(event).user.data1 & 0xFFFF)
2258 #define DECODEW(event) ((intptr_t)(event).user.data2 >> 16)
2259 #define DECODEH(event) ((intptr_t)(event).user.data2 & 0xFFFF)
2260 int x = DECODEX(event);
2261 int y = DECODEY(event);
2262 int w = DECODEW(event);
2263 int h = DECODEH(event);
2264 LogFlow(("SDL_USER_EVENT_UPDATERECT: x = %d, y = %d, w = %d, h = %d\n",
2265 x, y, w, h));
2266
2267 Assert(gpFrameBuffer);
2268 gpFrameBuffer->update(x, y, w, h, true /* fGuestRelative */);
2269
2270 #undef DECODEX
2271 #undef DECODEY
2272 #undef DECODEW
2273 #undef DECODEH
2274 break;
2275 }
2276
2277 /*
2278 * User event: Window resize done
2279 */
2280 case SDL_USER_EVENT_WINDOW_RESIZE_DONE:
2281 {
2282 /**
2283 * @todo This is a workaround for synchronization problems between EMT and the
2284 * SDL main thread. It can happen that the SDL thread already starts a
2285 * new resize operation while the EMT is still busy with the old one
2286 * leading to a deadlock. Therefore we call SetVideoModeHint only once
2287 * when the mouse button was released.
2288 */
2289 /* communicate the resize event to the guest */
2290 gDisplay->SetVideoModeHint(uResizeWidth, uResizeHeight, 0, 0);
2291 break;
2292
2293 }
2294
2295 /*
2296 * User specific resize event.
2297 */
2298 case SDL_USER_EVENT_RESIZE:
2299 {
2300 LogFlow(("SDL_USER_EVENT_RESIZE\n"));
2301 gpFrameBuffer->resizeGuest();
2302 /* notify the display that the resize has been completed */
2303 gDisplay->ResizeCompleted(0);
2304 break;
2305 }
2306
2307#ifdef USE_XPCOM_QUEUE_THREAD
2308 /*
2309 * User specific XPCOM event queue event
2310 */
2311 case SDL_USER_EVENT_XPCOM_EVENTQUEUE:
2312 {
2313 LogFlow(("SDL_USER_EVENT_XPCOM_EVENTQUEUE: processing XPCOM event queue...\n"));
2314 eventQ->ProcessPendingEvents();
2315 signalXPCOMEventQueueThread();
2316 break;
2317 }
2318#endif /* USE_XPCOM_QUEUE_THREAD */
2319
2320 /*
2321 * User specific update title bar notification event
2322 */
2323 case SDL_USER_EVENT_UPDATE_TITLEBAR:
2324 {
2325 UpdateTitlebar(TITLEBAR_NORMAL);
2326 break;
2327 }
2328
2329 /*
2330 * User specific termination event
2331 */
2332 case SDL_USER_EVENT_TERMINATE:
2333 {
2334 if (event.user.code != VBOXSDL_TERM_NORMAL)
2335 RTPrintf("Error: VM terminated abnormally!\n");
2336 goto leave;
2337 }
2338
2339#ifdef VBOX_SECURELABEL
2340 /*
2341 * User specific secure label update event
2342 */
2343 case SDL_USER_EVENT_SECURELABEL_UPDATE:
2344 {
2345 /*
2346 * Query the new label text
2347 */
2348 Bstr key = VBOXSDL_SECURELABEL_EXTRADATA;
2349 Bstr label;
2350 gMachine->GetExtraData(key, label.asOutParam());
2351 Utf8Str labelUtf8 = label;
2352 /*
2353 * Now update the label
2354 */
2355 gpFrameBuffer->setSecureLabelText(labelUtf8.raw());
2356 break;
2357 }
2358#endif /* VBOX_SECURELABEL */
2359
2360 /*
2361 * User specific pointer shape change event
2362 */
2363 case SDL_USER_EVENT_POINTER_CHANGE:
2364 {
2365 PointerShapeChangeData *data = (PointerShapeChangeData *) event.user.data1;
2366 SetPointerShape (data);
2367 delete data;
2368 break;
2369 }
2370
2371 /*
2372 * User specific guest capabilities changed
2373 */
2374 case SDL_USER_EVENT_GUEST_CAP_CHANGED:
2375 {
2376 HandleGuestCapsChanged();
2377 break;
2378 }
2379
2380 default:
2381 {
2382 LogBird(("unknown SDL event %d\n", event.type));
2383 break;
2384 }
2385 }
2386 }
2387
2388leave:
2389 LogFlow(("leaving...\n"));
2390#if defined(VBOX_WITH_XPCOM) && !defined(__DARWIN__) && !defined(__OS2__)
2391 /* make sure the XPCOM event queue thread doesn't do anything harmful */
2392 terminateXPCOMQueueThread();
2393#endif /* VBOX_WITH_XPCOM */
2394
2395#ifdef VBOX_VRDP
2396 if (gVrdpServer)
2397 rc = gVrdpServer->COMSETTER(Enabled)(FALSE);
2398#endif
2399
2400 /*
2401 * Get the machine state.
2402 */
2403 if (gMachine)
2404 gMachine->COMGETTER(State)(&machineState);
2405 else
2406 machineState = MachineState_Aborted;
2407
2408 /*
2409 * Turn off the VM if it's running
2410 */
2411 if ( gConsole
2412 && machineState == MachineState_Running)
2413 {
2414 consoleCallback->ignorePowerOffEvents(true);
2415 rc = gConsole->PowerDown();
2416 if (FAILED(rc))
2417 {
2418 com::ErrorInfo info;
2419 if (info.isFullAvailable())
2420 PrintError("Failed to power down VM",
2421 info.getText().raw(), info.getComponent().raw());
2422 else
2423 RTPrintf("Failed to power down virtual machine! No error information available (rc = 0x%x).\n", rc);
2424 break;
2425 }
2426 }
2427
2428 /*
2429 * Now we discard all settings so that our changes will
2430 * not be flushed to the permanent configuration
2431 */
2432 if ( gMachine
2433 && machineState != MachineState_Saved)
2434 {
2435 rc = gMachine->DiscardSettings();
2436 AssertComRC(rc);
2437 }
2438
2439 /* close the session */
2440 if (sessionOpened)
2441 {
2442 rc = session->Close();
2443 AssertComRC(rc);
2444 }
2445
2446 /* restore the default cursor and free the custom one if any */
2447 if (gpDefaultCursor)
2448 {
2449#ifdef __LINUX__
2450 Cursor pDefaultTempX11Cursor = *(Cursor*)gpDefaultCursor->wm_cursor;
2451 *(Cursor*)gpDefaultCursor->wm_cursor = gpDefaultOrigX11Cursor;
2452#endif /* __LNUX__ */
2453 SDL_SetCursor(gpDefaultCursor);
2454#ifdef __LINUX__
2455 XFreeCursor(gSdlInfo.info.x11.display, pDefaultTempX11Cursor);
2456#endif /* __LINUX__ */
2457 }
2458
2459 if (gpCustomCursor)
2460 {
2461 WMcursor *pCustomTempWMCursor = gpCustomCursor->wm_cursor;
2462 gpCustomCursor->wm_cursor = gpCustomOrigWMcursor;
2463 SDL_FreeCursor(gpCustomCursor);
2464 if (pCustomTempWMCursor)
2465 {
2466#if defined (__WIN__)
2467 ::DestroyCursor(*(HCURSOR *) pCustomTempWMCursor);
2468#elif defined (__LINUX__)
2469 XFreeCursor(gSdlInfo.info.x11.display, *(Cursor *) pCustomTempWMCursor);
2470#endif
2471 free(pCustomTempWMCursor);
2472 }
2473 }
2474
2475 LogFlow(("Releasing mouse, keyboard, vrdpserver, display, console...\n"));
2476 if (gDisplay)
2477 gDisplay->SetupInternalFramebuffer(0);
2478 gMouse = NULL;
2479 gKeyboard = NULL;
2480 gVrdpServer = NULL;
2481 gDisplay = NULL;
2482 gConsole = NULL;
2483 gMachineDebugger = NULL;
2484 gProgress = NULL;
2485 // we can only uninitialize SDL here because it is not threadsafe
2486 if (gpFrameBuffer)
2487 {
2488 LogFlow(("Releasing framebuffer...\n"));
2489 gpFrameBuffer->uninit();
2490 gpFrameBuffer->Release();
2491 }
2492#ifdef VBOX_SECURELABEL
2493 /* must do this after destructing the framebuffer */
2494 if (gLibrarySDL_ttf)
2495 RTLdrClose(gLibrarySDL_ttf);
2496#endif
2497 LogFlow(("Releasing machine, session...\n"));
2498 gMachine = NULL;
2499 session = NULL;
2500 LogFlow(("Releasing callback handlers...\n"));
2501 if (callback)
2502 callback->Release();
2503 if (consoleCallback)
2504 consoleCallback->Release();
2505
2506 LogFlow(("Releasing VirtualBox object...\n"));
2507 virtualBox = NULL;
2508
2509 // end "all-stuff" scope
2510 ////////////////////////////////////////////////////////////////////////////
2511 }
2512 while (0);
2513
2514 LogFlow(("Uninitializing COM...\n"));
2515 com::Shutdown();
2516
2517 LogFlow(("Returning from main()!\n"));
2518 RTLogFlush(NULL);
2519 return FAILED (rc) ? 1 : 0;
2520}
2521
2522/**
2523 * Returns whether the absolute mouse is in use, i.e. both host
2524 * and guest have opted to enable it.
2525 *
2526 * @returns bool Flag whether the absolute mouse is in use
2527 */
2528static bool UseAbsoluteMouse(void)
2529{
2530 return (gfAbsoluteMouseHost && gfAbsoluteMouseGuest);
2531}
2532
2533#if defined(__DARWIN__)
2534/**
2535 * Fallback keycode conversion using SDL symbols.
2536 *
2537 * This is used to catch keycodes that's missing from the translation table.
2538 *
2539 * @returns XT scancode
2540 * @param ev SDL scancode
2541 */
2542static uint16_t Keyevent2KeycodeFallback(const SDL_KeyboardEvent *ev)
2543{
2544 const SDLKey sym = ev->keysym.sym;
2545 Log(("SDL key event: sym=%d scancode=%#x unicode=%#x\n",
2546 sym, ev->keysym.scancode, ev->keysym.unicode));
2547 switch (sym)
2548 { /* set 1 scan code */
2549 case SDLK_ESCAPE: return 0x01;
2550 case SDLK_EXCLAIM:
2551 case SDLK_1: return 0x02;
2552 case SDLK_AT:
2553 case SDLK_2: return 0x03;
2554 case SDLK_HASH:
2555 case SDLK_3: return 0x04;
2556 case SDLK_DOLLAR:
2557 case SDLK_4: return 0x05;
2558 /* % */
2559 case SDLK_5: return 0x06;
2560 case SDLK_CARET:
2561 case SDLK_6: return 0x07;
2562 case SDLK_AMPERSAND:
2563 case SDLK_7: return 0x08;
2564 case SDLK_ASTERISK:
2565 case SDLK_8: return 0x09;
2566 case SDLK_LEFTPAREN:
2567 case SDLK_9: return 0x0a;
2568 case SDLK_RIGHTPAREN:
2569 case SDLK_0: return 0x0b;
2570 case SDLK_UNDERSCORE:
2571 case SDLK_MINUS: return 0x0c;
2572 case SDLK_EQUALS:
2573 case SDLK_PLUS: return 0x0d;
2574 case SDLK_BACKSPACE: return 0x0e;
2575 case SDLK_TAB: return 0x0f;
2576 case SDLK_q: return 0x10;
2577 case SDLK_w: return 0x11;
2578 case SDLK_e: return 0x12;
2579 case SDLK_r: return 0x13;
2580 case SDLK_t: return 0x14;
2581 case SDLK_y: return 0x15;
2582 case SDLK_u: return 0x16;
2583 case SDLK_i: return 0x17;
2584 case SDLK_o: return 0x18;
2585 case SDLK_p: return 0x19;
2586 case SDLK_LEFTBRACKET: return 0x1a;
2587 case SDLK_RIGHTBRACKET: return 0x1b;
2588 case SDLK_RETURN: return 0x1c;
2589 case SDLK_KP_ENTER: return 0x1c | 0x100;
2590 case SDLK_LCTRL: return 0x1d;
2591 case SDLK_RCTRL: return 0x1d | 0x100;
2592 case SDLK_a: return 0x1e;
2593 case SDLK_s: return 0x1f;
2594 case SDLK_d: return 0x20;
2595 case SDLK_f: return 0x21;
2596 case SDLK_g: return 0x22;
2597 case SDLK_h: return 0x23;
2598 case SDLK_j: return 0x24;
2599 case SDLK_k: return 0x25;
2600 case SDLK_l: return 0x26;
2601 case SDLK_COLON:
2602 case SDLK_SEMICOLON: return 0x27;
2603 case SDLK_QUOTEDBL:
2604 case SDLK_QUOTE: return 0x28;
2605 case SDLK_BACKQUOTE: return 0x29;
2606 case SDLK_LSHIFT: return 0x2a;
2607 case SDLK_BACKSLASH: return 0x2b;
2608 case SDLK_z: return 0x2c;
2609 case SDLK_x: return 0x2d;
2610 case SDLK_c: return 0x2e;
2611 case SDLK_v: return 0x2f;
2612 case SDLK_b: return 0x30;
2613 case SDLK_n: return 0x31;
2614 case SDLK_m: return 0x32;
2615 case SDLK_LESS:
2616 case SDLK_COMMA: return 0x33;
2617 case SDLK_GREATER:
2618 case SDLK_PERIOD: return 0x34;
2619 case SDLK_KP_DIVIDE: /*??*/
2620 case SDLK_QUESTION:
2621 case SDLK_SLASH: return 0x35;
2622 case SDLK_RSHIFT: return 0x36;
2623 case SDLK_KP_MULTIPLY:
2624 case SDLK_PRINT: return 0x37; /* fixme */
2625 case SDLK_LALT: return 0x38;
2626 case SDLK_MODE: /* alt gr*/
2627 case SDLK_RALT: return 0x38 | 0x100;
2628 case SDLK_SPACE: return 0x39;
2629 case SDLK_CAPSLOCK: return 0x3a;
2630 case SDLK_F1: return 0x3b;
2631 case SDLK_F2: return 0x3c;
2632 case SDLK_F3: return 0x3d;
2633 case SDLK_F4: return 0x3e;
2634 case SDLK_F5: return 0x3f;
2635 case SDLK_F6: return 0x40;
2636 case SDLK_F7: return 0x41;
2637 case SDLK_F8: return 0x42;
2638 case SDLK_F9: return 0x43;
2639 case SDLK_F10: return 0x44;
2640 case SDLK_PAUSE: return 0x45; /* not right */
2641 case SDLK_NUMLOCK: return 0x45;
2642 case SDLK_SCROLLOCK: return 0x46;
2643 case SDLK_KP7: return 0x47;
2644 case SDLK_HOME: return 0x47 | 0x100;
2645 case SDLK_KP8: return 0x48;
2646 case SDLK_UP: return 0x48 | 0x100;
2647 case SDLK_KP9: return 0x49;
2648 case SDLK_PAGEUP: return 0x49 | 0x100;
2649 case SDLK_KP_MINUS: return 0x4a;
2650 case SDLK_KP4: return 0x4b;
2651 case SDLK_LEFT: return 0x4b | 0x100;
2652 case SDLK_KP5: return 0x4c;
2653 case SDLK_KP6: return 0x4d;
2654 case SDLK_RIGHT: return 0x4d | 0x100;
2655 case SDLK_KP_PLUS: return 0x4e;
2656 case SDLK_KP1: return 0x4f;
2657 case SDLK_END: return 0x4f | 0x100;
2658 case SDLK_KP2: return 0x50;
2659 case SDLK_DOWN: return 0x50 | 0x100;
2660 case SDLK_KP3: return 0x51;
2661 case SDLK_PAGEDOWN: return 0x51 | 0x100;
2662 case SDLK_KP0: return 0x52;
2663 case SDLK_INSERT: return 0x52 | 0x100;
2664 case SDLK_KP_PERIOD: return 0x53;
2665 case SDLK_DELETE: return 0x53 | 0x100;
2666 case SDLK_SYSREQ: return 0x54;
2667 case SDLK_F11: return 0x57;
2668 case SDLK_F12: return 0x58;
2669 case SDLK_F13: return 0x5b;
2670 case SDLK_LMETA:
2671 case SDLK_LSUPER: return 0x5b | 0x100;
2672 case SDLK_F14: return 0x5c;
2673 case SDLK_RMETA:
2674 case SDLK_RSUPER: return 0x5c | 0x100;
2675 case SDLK_F15: return 0x5d;
2676 case SDLK_MENU: return 0x5d | 0x100;
2677#if 0
2678 case SDLK_CLEAR: return 0x;
2679 case SDLK_KP_EQUALS: return 0x;
2680 case SDLK_COMPOSE: return 0x;
2681 case SDLK_HELP: return 0x;
2682 case SDLK_BREAK: return 0x;
2683 case SDLK_POWER: return 0x;
2684 case SDLK_EURO: return 0x;
2685 case SDLK_UNDO: return 0x;
2686#endif
2687 default:
2688 Log(("Unhandled sdl key event: sym=%d scancode=%#x unicode=%#x\n",
2689 ev->keysym.sym, ev->keysym.scancode, ev->keysym.unicode));
2690 return 0;
2691 }
2692}
2693#endif /* __DARWIN__ */
2694
2695/**
2696 * Converts an SDL keyboard eventcode to a XT scancode.
2697 *
2698 * @returns XT scancode
2699 * @param ev SDL scancode
2700 */
2701static uint16_t Keyevent2Keycode(const SDL_KeyboardEvent *ev)
2702{
2703 // start with the scancode determined by SDL
2704 int keycode = ev->keysym.scancode;
2705
2706#ifdef __LINUX__
2707 // workaround for SDL keyboard translation issues on Linux
2708 // keycodes > 0x100 are sent as 0xe0 keycode
2709 static const uint16_t x_keycode_to_pc_keycode[61] =
2710 {
2711 0x47|0x100, /* 97 Home */
2712 0x48|0x100, /* 98 Up */
2713 0x49|0x100, /* 99 PgUp */
2714 0x4b|0x100, /* 100 Left */
2715 0x4c, /* 101 KP-5 */
2716 0x4d|0x100, /* 102 Right */
2717 0x4f|0x100, /* 103 End */
2718 0x50|0x100, /* 104 Down */
2719 0x51|0x100, /* 105 PgDn */
2720 0x52|0x100, /* 106 Ins */
2721 0x53|0x100, /* 107 Del */
2722 0x1c|0x100, /* 108 Enter */
2723 0x1d|0x100, /* 109 Ctrl-R */
2724 0x0, /* 110 Pause */
2725 0x37|0x100, /* 111 Print */
2726 0x35|0x100, /* 112 Divide */
2727 0x38|0x100, /* 113 Alt-R */
2728 0x46|0x100, /* 114 Break */
2729 0x5b|0x100, /* 115 Win Left */
2730 0x5c|0x100, /* 116 Win Right */
2731 0x5d|0x100, /* 117 Win Menu */
2732 0x0, /* 118 */
2733 0x0, /* 119 */
2734 0x0, /* 120 */
2735 0xf1, /* 121 Korean Hangul to Latin?? */
2736 0xf2, /* 122 Korean Hangul to Hanja?? */
2737 0x0, /* 123 */
2738 0x0, /* 124 */
2739 0x0, /* 125 */
2740 0x0, /* 126 */
2741 0x0, /* 127 */
2742 0x0, /* 128 */
2743 0x79, /* 129 Japanese Henkan */
2744 0x0, /* 130 */
2745 0x7b, /* 131 Japanese Muhenkan */
2746 0x0, /* 132 */
2747 0x7d, /* 133 Japanese Yen */
2748 0x7e, /* 134 Brazilian keypad */
2749 0x0, /* 135 */
2750 0x47, /* 136 KP_7 */
2751 0x48, /* 137 KP_8 */
2752 0x49, /* 138 KP_9 */
2753 0x4b, /* 139 KP_4 */
2754 0x4c, /* 140 KP_5 */
2755 0x4d, /* 141 KP_6 */
2756 0x4f, /* 142 KP_1 */
2757 0x50, /* 143 KP_2 */
2758 0x51, /* 144 KP_3 */
2759 0x52, /* 145 KP_0 */
2760 0x53, /* 146 KP_. */
2761 0x47, /* 147 KP_HOME */
2762 0x48, /* 148 KP_UP */
2763 0x49, /* 149 KP_PgUp */
2764 0x4b, /* 150 KP_Left */
2765 0x4c, /* 151 KP_ */
2766 0x4d, /* 152 KP_Right */
2767 0x4f, /* 153 KP_End */
2768 0x50, /* 154 KP_Down */
2769 0x51, /* 155 KP_PgDn */
2770 0x52, /* 156 KP_Ins */
2771 0x53, /* 157 KP_Del */
2772 };
2773
2774 if (keycode < 9)
2775 {
2776 keycode = 0;
2777 }
2778 else if (keycode < 97)
2779 {
2780 // just an offset (Xorg MIN_KEYCODE)
2781 keycode -= 8;
2782 }
2783 else if (keycode < 158)
2784 {
2785 // apply conversion table
2786 keycode = x_keycode_to_pc_keycode[keycode - 97];
2787 }
2788 else if (keycode == 208)
2789 {
2790 // Japanese Hiragana to Katakana
2791 keycode = 0x70;
2792 }
2793 else if (keycode == 211)
2794 {
2795 // Japanese backslash/underscore and Brazilian backslash/question mark
2796 keycode = 0x73;
2797 }
2798 else
2799 {
2800 keycode = 0;
2801 }
2802
2803#elif defined(__DARWIN__)
2804 /* This is derived partially from SDL_QuartzKeys.h and partially from testing. */
2805 static const uint16_t s_aMacToSet1[] =
2806 {
2807 /* set-1 SDL_QuartzKeys.h */
2808 0x1e, /* QZ_a 0x00 */
2809 0x1f, /* QZ_s 0x01 */
2810 0x20, /* QZ_d 0x02 */
2811 0x21, /* QZ_f 0x03 */
2812 0x23, /* QZ_h 0x04 */
2813 0x22, /* QZ_g 0x05 */
2814 0x2c, /* QZ_z 0x06 */
2815 0x2d, /* QZ_x 0x07 */
2816 0x2e, /* QZ_c 0x08 */
2817 0x2f, /* QZ_v 0x09 */
2818 0x56, /* between lshift and z. 'INT 1'? */
2819 0x30, /* QZ_b 0x0B */
2820 0x10, /* QZ_q 0x0C */
2821 0x11, /* QZ_w 0x0D */
2822 0x12, /* QZ_e 0x0E */
2823 0x13, /* QZ_r 0x0F */
2824 0x15, /* QZ_y 0x10 */
2825 0x14, /* QZ_t 0x11 */
2826 0x02, /* QZ_1 0x12 */
2827 0x03, /* QZ_2 0x13 */
2828 0x04, /* QZ_3 0x14 */
2829 0x05, /* QZ_4 0x15 */
2830 0x07, /* QZ_6 0x16 */
2831 0x06, /* QZ_5 0x17 */
2832 0x0d, /* QZ_EQUALS 0x18 */
2833 0x0a, /* QZ_9 0x19 */
2834 0x08, /* QZ_7 0x1A */
2835 0x0c, /* QZ_MINUS 0x1B */
2836 0x09, /* QZ_8 0x1C */
2837 0x0b, /* QZ_0 0x1D */
2838 0x1b, /* QZ_RIGHTBRACKET 0x1E */
2839 0x18, /* QZ_o 0x1F */
2840 0x16, /* QZ_u 0x20 */
2841 0x1a, /* QZ_LEFTBRACKET 0x21 */
2842 0x17, /* QZ_i 0x22 */
2843 0x19, /* QZ_p 0x23 */
2844 0x1c, /* QZ_RETURN 0x24 */
2845 0x26, /* QZ_l 0x25 */
2846 0x24, /* QZ_j 0x26 */
2847 0x28, /* QZ_QUOTE 0x27 */
2848 0x25, /* QZ_k 0x28 */
2849 0x27, /* QZ_SEMICOLON 0x29 */
2850 0x2b, /* QZ_BACKSLASH 0x2A */
2851 0x33, /* QZ_COMMA 0x2B */
2852 0x35, /* QZ_SLASH 0x2C */
2853 0x31, /* QZ_n 0x2D */
2854 0x32, /* QZ_m 0x2E */
2855 0x34, /* QZ_PERIOD 0x2F */
2856 0x0f, /* QZ_TAB 0x30 */
2857 0x39, /* QZ_SPACE 0x31 */
2858 0x29, /* QZ_BACKQUOTE 0x32 */
2859 0x0e, /* QZ_BACKSPACE 0x33 */
2860 0x9c, /* QZ_IBOOK_ENTER 0x34 */
2861 0x01, /* QZ_ESCAPE 0x35 */
2862 0x5c|0x100, /* QZ_RMETA 0x36 */
2863 0x5b|0x100, /* QZ_LMETA 0x37 */
2864 0x2a, /* QZ_LSHIFT 0x38 */
2865 0x3a, /* QZ_CAPSLOCK 0x39 */
2866 0x38, /* QZ_LALT 0x3A */
2867 0x1d, /* QZ_LCTRL 0x3B */
2868 0x36, /* QZ_RSHIFT 0x3C */
2869 0x38|0x100, /* QZ_RALT 0x3D */
2870 0x1d|0x100, /* QZ_RCTRL 0x3E */
2871 0, /* */
2872 0, /* */
2873 0x53, /* QZ_KP_PERIOD 0x41 */
2874 0, /* */
2875 0x37, /* QZ_KP_MULTIPLY 0x43 */
2876 0, /* */
2877 0x4e, /* QZ_KP_PLUS 0x45 */
2878 0, /* */
2879 0x45, /* QZ_NUMLOCK 0x47 */
2880 0, /* */
2881 0, /* */
2882 0, /* */
2883 0x35|0x100, /* QZ_KP_DIVIDE 0x4B */
2884 0x1c|0x100, /* QZ_KP_ENTER 0x4C */
2885 0, /* */
2886 0x4a, /* QZ_KP_MINUS 0x4E */
2887 0, /* */
2888 0, /* */
2889 0x0d/*?*/, /* QZ_KP_EQUALS 0x51 */
2890 0x52, /* QZ_KP0 0x52 */
2891 0x4f, /* QZ_KP1 0x53 */
2892 0x50, /* QZ_KP2 0x54 */
2893 0x51, /* QZ_KP3 0x55 */
2894 0x4b, /* QZ_KP4 0x56 */
2895 0x4c, /* QZ_KP5 0x57 */
2896 0x4d, /* QZ_KP6 0x58 */
2897 0x47, /* QZ_KP7 0x59 */
2898 0, /* */
2899 0x48, /* QZ_KP8 0x5B */
2900 0x49, /* QZ_KP9 0x5C */
2901 0, /* */
2902 0, /* */
2903 0, /* */
2904 0x3f, /* QZ_F5 0x60 */
2905 0x40, /* QZ_F6 0x61 */
2906 0x41, /* QZ_F7 0x62 */
2907 0x3d, /* QZ_F3 0x63 */
2908 0x42, /* QZ_F8 0x64 */
2909 0x43, /* QZ_F9 0x65 */
2910 0, /* */
2911 0x57, /* QZ_F11 0x67 */
2912 0, /* */
2913 0x37|0x100, /* QZ_PRINT / F13 0x69 */
2914 0x63, /* QZ_F16 0x6A */
2915 0x46, /* QZ_SCROLLOCK 0x6B */
2916 0, /* */
2917 0x44, /* QZ_F10 0x6D */
2918 0x5d|0x100, /* */
2919 0x58, /* QZ_F12 0x6F */
2920 0, /* */
2921 0/* 0xe1,0x1d,0x45*/, /* QZ_PAUSE 0x71 */
2922 0x52|0x100, /* QZ_INSERT / HELP 0x72 */
2923 0x47|0x100, /* QZ_HOME 0x73 */
2924 0x49|0x100, /* QZ_PAGEUP 0x74 */
2925 0x53|0x100, /* QZ_DELETE 0x75 */
2926 0x3e, /* QZ_F4 0x76 */
2927 0x4f|0x100, /* QZ_END 0x77 */
2928 0x3c, /* QZ_F2 0x78 */
2929 0x51|0x100, /* QZ_PAGEDOWN 0x79 */
2930 0x3b, /* QZ_F1 0x7A */
2931 0x4b|0x100, /* QZ_LEFT 0x7B */
2932 0x4d|0x100, /* QZ_RIGHT 0x7C */
2933 0x50|0x100, /* QZ_DOWN 0x7D */
2934 0x48|0x100, /* QZ_UP 0x7E */
2935 0x5e|0x100, /* QZ_POWER 0x7F */ /* have different break key! */
2936 };
2937
2938 if (keycode == 0)
2939 {
2940 /* This could be a modifier or it could be 'a'. */
2941 switch (ev->keysym.sym)
2942 {
2943 case SDLK_LSHIFT: keycode = 0x2a; break;
2944 case SDLK_RSHIFT: keycode = 0x36; break;
2945 case SDLK_LCTRL: keycode = 0x1d; break;
2946 case SDLK_RCTRL: keycode = 0x1d | 0x100; break;
2947 case SDLK_LALT: keycode = 0x38; break;
2948 case SDLK_MODE: /* alt gr */
2949 case SDLK_RALT: keycode = 0x38 | 0x100; break;
2950 case SDLK_RMETA:
2951 case SDLK_RSUPER: keycode = 0x5c | 0x100; break;
2952 case SDLK_LMETA:
2953 case SDLK_LSUPER: keycode = 0x5b | 0x100; break;
2954 /* Sssumes normal key. */
2955 default: keycode = s_aMacToSet1[keycode]; break;
2956 }
2957 }
2958 else
2959 {
2960 if ((unsigned)keycode < RT_ELEMENTS(s_aMacToSet1))
2961 keycode = s_aMacToSet1[keycode];
2962 else
2963 keycode = 0;
2964 if (!keycode)
2965 {
2966#ifdef DEBUG_bird
2967 RTPrintf("Untranslated: keycode=%#x (%d)\n", keycode, keycode);
2968#endif
2969 keycode = Keyevent2KeycodeFallback(ev);
2970 }
2971 }
2972#ifdef DEBUG_bird
2973 RTPrintf("scancode=%#x -> %#x\n", ev->keysym.scancode, keycode);
2974#endif
2975
2976#endif /* __DARWIN__ */
2977 return keycode;
2978}
2979
2980/**
2981 * Releases any modifier keys that are currently in pressed state.
2982 */
2983static void ResetKeys(void)
2984{
2985 int i;
2986
2987 if (!gKeyboard)
2988 return;
2989
2990 for(i = 0; i < 256; i++)
2991 {
2992 if (gaModifiersState[i])
2993 {
2994 if (i & 0x80)
2995 gKeyboard->PutScancode(0xe0);
2996 gKeyboard->PutScancode(i | 0x80);
2997 gaModifiersState[i] = 0;
2998 }
2999 }
3000}
3001
3002/**
3003 * Keyboard event handler.
3004 *
3005 * @param ev SDL keyboard event.
3006 */
3007static void ProcessKey(SDL_KeyboardEvent *ev)
3008{
3009#if defined(DEBUG) || defined(VBOX_WITH_STATISTICS)
3010 if (gMachineDebugger && ev->type == SDL_KEYDOWN)
3011 {
3012 // first handle the debugger hotkeys
3013 uint8_t *keystate = SDL_GetKeyState(NULL);
3014#if 0
3015 // CTRL+ALT+Fn is not free on Linux hosts with Xorg ..
3016 if (keystate[SDLK_LALT] && !keystate[SDLK_LCTRL])
3017#else
3018 if (keystate[SDLK_LALT] && keystate[SDLK_LCTRL])
3019#endif
3020 {
3021 switch (ev->keysym.sym)
3022 {
3023 // pressing CTRL+ALT+F11 dumps the statistics counter
3024 case SDLK_F12:
3025 RTPrintf("ResetStats\n"); /* Visual feedback in console window */
3026 gMachineDebugger->ResetStats();
3027 break;
3028 // pressing CTRL+ALT+F12 resets all statistics counter
3029 case SDLK_F11:
3030 gMachineDebugger->DumpStats();
3031 RTPrintf("DumpStats\n"); /* Vistual feedback in console window */
3032 break;
3033 default:
3034 break;
3035 }
3036 }
3037#if 1
3038 else if (keystate[SDLK_LALT] && !keystate[SDLK_LCTRL])
3039 {
3040 switch (ev->keysym.sym)
3041 {
3042 // pressing Alt-F12 toggles the supervisor recompiler
3043 case SDLK_F12:
3044 {
3045 BOOL recompileSupervisor;
3046 gMachineDebugger->COMGETTER(RecompileSupervisor)(&recompileSupervisor);
3047 gMachineDebugger->COMSETTER(RecompileSupervisor)(!recompileSupervisor);
3048 break;
3049 }
3050 // pressing Alt-F11 toggles the user recompiler
3051 case SDLK_F11:
3052 {
3053 BOOL recompileUser;
3054 gMachineDebugger->COMGETTER(RecompileUser)(&recompileUser);
3055 gMachineDebugger->COMSETTER(RecompileUser)(!recompileUser);
3056 break;
3057 }
3058 // pressing Alt-F10 toggles the patch manager
3059 case SDLK_F10:
3060 {
3061 BOOL patmEnabled;
3062 gMachineDebugger->COMGETTER(PATMEnabled)(&patmEnabled);
3063 gMachineDebugger->COMSETTER(PATMEnabled)(!patmEnabled);
3064 break;
3065 }
3066 // pressing Alt-F9 toggles CSAM
3067 case SDLK_F9:
3068 {
3069 BOOL csamEnabled;
3070 gMachineDebugger->COMGETTER(CSAMEnabled)(&csamEnabled);
3071 gMachineDebugger->COMSETTER(CSAMEnabled)(!csamEnabled);
3072 break;
3073 }
3074 // pressing Alt-F8 toggles singlestepping mode
3075 case SDLK_F8:
3076 {
3077 BOOL singlestepEnabled;
3078 gMachineDebugger->COMGETTER(Singlestep)(&singlestepEnabled);
3079 gMachineDebugger->COMSETTER(Singlestep)(!singlestepEnabled);
3080 break;
3081 }
3082 default:
3083 break;
3084 }
3085 }
3086#endif
3087 // pressing Ctrl-F12 toggles the logger
3088 else if ((keystate[SDLK_RCTRL] || keystate[SDLK_LCTRL]) && ev->keysym.sym == SDLK_F12)
3089 {
3090 BOOL logEnabled = TRUE;
3091 gMachineDebugger->COMGETTER(LogEnabled)(&logEnabled);
3092 gMachineDebugger->COMSETTER(LogEnabled)(!logEnabled);
3093#ifdef DEBUG_bird
3094 return;
3095#endif
3096 }
3097 // pressing F12 sets a logmark
3098 else if (ev->keysym.sym == SDLK_F12)
3099 {
3100 RTLogPrintf("****** LOGGING MARK ******\n");
3101 RTLogFlush(NULL);
3102 }
3103 // now update the titlebar flags
3104 UpdateTitlebar(TITLEBAR_NORMAL);
3105 }
3106#endif // DEBUG || VBOX_WITH_STATISTICS
3107
3108 // the pause key is the weirdest, needs special handling
3109 if (ev->keysym.sym == SDLK_PAUSE)
3110 {
3111 int v = 0;
3112 if (ev->type == SDL_KEYUP)
3113 v |= 0x80;
3114 gKeyboard->PutScancode(0xe1);
3115 gKeyboard->PutScancode(0x1d | v);
3116 gKeyboard->PutScancode(0x45 | v);
3117 return;
3118 }
3119
3120 /*
3121 * Perform SDL key event to scancode conversion
3122 */
3123 int keycode = Keyevent2Keycode(ev);
3124
3125 switch(keycode)
3126 {
3127 case 0x00:
3128 {
3129 /* sent when leaving window: reset the modifiers state */
3130 ResetKeys();
3131 return;
3132 }
3133
3134 case 0x2a: /* Left Shift */
3135 case 0x36: /* Right Shift */
3136 case 0x1d: /* Left CTRL */
3137 case 0x1d|0x100: /* Right CTRL */
3138 case 0x38: /* Left ALT */
3139 case 0x38|0x100: /* Right ALT */
3140 {
3141 if (ev->type == SDL_KEYUP)
3142 gaModifiersState[keycode] = 0;
3143 else
3144 gaModifiersState[keycode] = 1;
3145 break;
3146 }
3147
3148 case 0x45: /* Num Lock */
3149 case 0x3a: /* Caps Lock */
3150 {
3151 /*
3152 * SDL generates a KEYDOWN event if the lock key is active and a KEYUP event
3153 * if the lock key is inactive. See SDL_DISABLE_LOCK_KEYS.
3154 */
3155 if (ev->type == SDL_KEYDOWN || ev->type == SDL_KEYUP)
3156 {
3157 gKeyboard->PutScancode(keycode);
3158 gKeyboard->PutScancode(keycode | 0x80);
3159 }
3160 return;
3161 }
3162 }
3163
3164 if (ev->type != SDL_KEYDOWN)
3165 {
3166 /*
3167 * Some keyboards (e.g. the one of mine T60) don't send a NumLock scan code on every
3168 * press of the key. Both the guest and the host should agree on the NumLock state.
3169 * If they differ, we try to alter the guest NumLock state by sending the NumLock key
3170 * scancode. We will get a feedback through the KBD_CMD_SET_LEDS command if the guest
3171 * tries to set/clear the NumLock LED. If a (silly) guest doesn't change the LED, don't
3172 * bother him with NumLock scancodes. At least our BIOS, Linux and Windows handle the
3173 * NumLock LED well.
3174 */
3175 if ( gcGuestNumLockAdaptions
3176 && (gfGuestNumLockPressed ^ !!(SDL_GetModState() & KMOD_NUM)))
3177 {
3178 gcGuestNumLockAdaptions--;
3179 gKeyboard->PutScancode(0x45);
3180 gKeyboard->PutScancode(0x45 | 0x80);
3181 }
3182 if ( gcGuestCapsLockAdaptions
3183 && (gfGuestCapsLockPressed ^ !!(SDL_GetModState() & KMOD_CAPS)))
3184 {
3185 gcGuestCapsLockAdaptions--;
3186 gKeyboard->PutScancode(0x3a);
3187 gKeyboard->PutScancode(0x3a | 0x80);
3188 }
3189 }
3190
3191 /*
3192 * Now we send the event. Apply extended and release prefixes.
3193 */
3194 if (keycode & 0x100)
3195 gKeyboard->PutScancode(0xe0);
3196
3197 gKeyboard->PutScancode(ev->type == SDL_KEYUP ? (keycode & 0x7f) | 0x80
3198 : (keycode & 0x7f));
3199}
3200
3201#ifdef __DARWIN__
3202#include <Carbon/Carbon.h>
3203__BEGIN_DECLS
3204/* Private interface in 10.3 and later. */
3205typedef int CGSConnection;
3206typedef enum
3207{
3208 kCGSGlobalHotKeyEnable = 0,
3209 kCGSGlobalHotKeyDisable,
3210 kCGSGlobalHotKeyInvalid = -1 /* bird */
3211} CGSGlobalHotKeyOperatingMode;
3212extern CGSConnection _CGSDefaultConnection(void);
3213extern CGError CGSGetGlobalHotKeyOperatingMode(CGSConnection Connection, CGSGlobalHotKeyOperatingMode *enmMode);
3214extern CGError CGSSetGlobalHotKeyOperatingMode(CGSConnection Connection, CGSGlobalHotKeyOperatingMode enmMode);
3215__END_DECLS
3216
3217/** Keeping track of whether we disabled the hotkeys or not. */
3218static bool g_fHotKeysDisabled = false;
3219/** Whether we've connected or not. */
3220static bool g_fConnectedToCGS = false;
3221/** Cached connection. */
3222static CGSConnection g_CGSConnection;
3223
3224/**
3225 * Disables or enabled global hot keys.
3226 */
3227static void DisableGlobalHotKeys(bool fDisable)
3228{
3229 if (!g_fConnectedToCGS)
3230 {
3231 g_CGSConnection = _CGSDefaultConnection();
3232 g_fConnectedToCGS = true;
3233 }
3234
3235 /* get current mode. */
3236 CGSGlobalHotKeyOperatingMode enmMode = kCGSGlobalHotKeyInvalid;
3237 CGSGetGlobalHotKeyOperatingMode(g_CGSConnection, &enmMode);
3238
3239 /* calc new mode. */
3240 if (fDisable)
3241 {
3242 if (enmMode != kCGSGlobalHotKeyEnable)
3243 return;
3244 enmMode = kCGSGlobalHotKeyDisable;
3245 }
3246 else
3247 {
3248 if ( enmMode != kCGSGlobalHotKeyDisable
3249 /*|| !g_fHotKeysDisabled*/)
3250 return;
3251 enmMode = kCGSGlobalHotKeyEnable;
3252 }
3253
3254 /* try set it and check the actual result. */
3255 CGSSetGlobalHotKeyOperatingMode(g_CGSConnection, enmMode);
3256 CGSGlobalHotKeyOperatingMode enmNewMode = kCGSGlobalHotKeyInvalid;
3257 CGSGetGlobalHotKeyOperatingMode(g_CGSConnection, &enmNewMode);
3258 if (enmNewMode == enmMode)
3259 g_fHotKeysDisabled = enmMode == kCGSGlobalHotKeyDisable;
3260}
3261#endif /* __DARWIN__ */
3262
3263/**
3264 * Start grabbing the mouse.
3265 */
3266static void InputGrabStart(void)
3267{
3268#ifdef __DARWIN__
3269 DisableGlobalHotKeys(true);
3270#endif
3271 if (!gfGuestNeedsHostCursor)
3272 SDL_ShowCursor(SDL_DISABLE);
3273 SDL_WM_GrabInput(SDL_GRAB_ON);
3274 // dummy read to avoid moving the mouse
3275 SDL_GetRelativeMouseState(NULL, NULL);
3276 gfGrabbed = TRUE;
3277 UpdateTitlebar(TITLEBAR_NORMAL);
3278}
3279
3280/**
3281 * End mouse grabbing.
3282 */
3283static void InputGrabEnd(void)
3284{
3285 SDL_WM_GrabInput(SDL_GRAB_OFF);
3286 if (!gfGuestNeedsHostCursor)
3287 SDL_ShowCursor(SDL_ENABLE);
3288#ifdef __DARWIN__
3289 DisableGlobalHotKeys(false);
3290#endif
3291 gfGrabbed = FALSE;
3292 UpdateTitlebar(TITLEBAR_NORMAL);
3293}
3294
3295/**
3296 * Query mouse position and button state from SDL and send to the VM
3297 *
3298 * @param dz Relative mouse wheel movement
3299 */
3300static void SendMouseEvent(int dz, int down, int button)
3301{
3302 int x, y, state, buttons;
3303 bool abs;
3304
3305 /*
3306 * If supported and we're not in grabbed mode, we'll use the absolute mouse.
3307 * If we are in grabbed mode and the guest is not able to draw the mouse cursor
3308 * itself, we have to use absolute coordinates, otherwise the host cursor and
3309 * the coordinates the guest thinks the mouse is at could get out-of-sync. From
3310 * the SDL mailing list:
3311 *
3312 * "The event processing is usually asynchronous and so somewhat delayed, and
3313 * SDL_GetMouseState is returning the immediate mouse state. So at the time you
3314 * call SDL_GetMouseState, the "button" is already up."
3315 */
3316 abs = (UseAbsoluteMouse() && !gfGrabbed) || gfGuestNeedsHostCursor;
3317
3318 /* only used if abs == TRUE */
3319 int xMin = gpFrameBuffer->getXOffset();
3320 int yMin = gpFrameBuffer->getYOffset();
3321 int xMax = xMin + (int)gpFrameBuffer->getGuestXRes();
3322 int yMax = yMin + (int)gpFrameBuffer->getGuestYRes();
3323
3324 state = abs ? SDL_GetMouseState(&x, &y) : SDL_GetRelativeMouseState(&x, &y);
3325
3326 /*
3327 * process buttons
3328 */
3329 buttons = 0;
3330 if (state & SDL_BUTTON(SDL_BUTTON_LEFT))
3331 buttons |= MouseButtonState_LeftButton;
3332 if (state & SDL_BUTTON(SDL_BUTTON_RIGHT))
3333 buttons |= MouseButtonState_RightButton;
3334 if (state & SDL_BUTTON(SDL_BUTTON_MIDDLE))
3335 buttons |= MouseButtonState_MiddleButton;
3336
3337 if (abs)
3338 {
3339 /*
3340 * Check if the mouse event is inside the guest area. This solves the
3341 * following problem: Some guests switch off the VBox hardware mouse
3342 * cursor and draw the mouse cursor itself instead. Moving the mouse
3343 * outside the guest area then leads to annoying mouse hangs if we
3344 * don't pass mouse motion events into the guest.
3345 */
3346 if (x < xMin || y < yMin || x > xMax || y > yMax)
3347 {
3348 /*
3349 * Cursor outside of valid guest area (outside window or in secure
3350 * label area. Don't allow any mouse button press.
3351 */
3352 button = 0;
3353
3354 /*
3355 * Release any pressed button.
3356 */
3357#if 0
3358 /* disabled on customers request */
3359 buttons &= ~(MouseButtonState_LeftButton |
3360 MouseButtonState_MiddleButton |
3361 MouseButtonState_RightButton);
3362#endif
3363
3364 /*
3365 * Prevent negative coordinates.
3366 */
3367 if (x < xMin) x = xMin;
3368 if (x > xMax) x = xMax;
3369 if (y < yMin) y = yMin;
3370 if (y > yMax) y = yMax;
3371
3372 if (!gpOffCursor)
3373 {
3374 gpOffCursor = SDL_GetCursor(); /* Cursor image */
3375 gfOffCursorActive = SDL_ShowCursor(-1); /* enabled / disabled */
3376 SDL_SetCursor(gpDefaultCursor);
3377 SDL_ShowCursor (SDL_ENABLE);
3378 }
3379 }
3380 else
3381 {
3382 if (gpOffCursor)
3383 {
3384 /*
3385 * We just entered the valid guest area. Restore the guest mouse
3386 * cursor.
3387 */
3388 SDL_SetCursor(gpOffCursor);
3389 SDL_ShowCursor(gfOffCursorActive ? SDL_ENABLE : SDL_DISABLE);
3390 gpOffCursor = NULL;
3391 }
3392 }
3393 }
3394
3395 /*
3396 * Button was pressed but that press is not reflected in the button state?
3397 */
3398 if (down && !(state & SDL_BUTTON(button)))
3399 {
3400 /*
3401 * It can happen that a mouse up event follows a mouse down event immediately
3402 * and we see the events when the bit in the button state is already cleared
3403 * again. In that case we simulate the mouse down event.
3404 */
3405 int tmp_button = 0;
3406 switch (button)
3407 {
3408 case SDL_BUTTON_LEFT: tmp_button = MouseButtonState_LeftButton; break;
3409 case SDL_BUTTON_MIDDLE: tmp_button = MouseButtonState_MiddleButton; break;
3410 case SDL_BUTTON_RIGHT: tmp_button = MouseButtonState_RightButton; break;
3411 }
3412
3413 if (abs)
3414 {
3415 /**
3416 * @todo
3417 * PutMouseEventAbsolute() expects x and y starting from 1,1.
3418 * should we do the increment internally in PutMouseEventAbsolute()
3419 * or state it in PutMouseEventAbsolute() docs?
3420 */
3421 gMouse->PutMouseEventAbsolute(x + 1 - xMin,
3422 y + 1 - yMin,
3423 dz, buttons | tmp_button);
3424 }
3425 else
3426 {
3427 gMouse->PutMouseEvent(0, 0, dz, buttons | tmp_button);
3428 }
3429 }
3430
3431 // now send the mouse event
3432 if (abs)
3433 {
3434 /**
3435 * @todo
3436 * PutMouseEventAbsolute() expects x and y starting from 1,1.
3437 * should we do the increment internally in PutMouseEventAbsolute()
3438 * or state it in PutMouseEventAbsolute() docs?
3439 */
3440 gMouse->PutMouseEventAbsolute(x + 1 - xMin,
3441 y + 1 - yMin,
3442 dz, buttons);
3443 }
3444 else
3445 {
3446 gMouse->PutMouseEvent(x, y, dz, buttons);
3447 }
3448}
3449
3450/**
3451 * Resets the VM
3452 */
3453void ResetVM(void)
3454{
3455 if (gConsole)
3456 gConsole->Reset();
3457}
3458
3459/**
3460 * Initiates a saved state and updates the titlebar with progress information
3461 */
3462void SaveState(void)
3463{
3464 ResetKeys();
3465 RTThreadYield();
3466 if (gfGrabbed)
3467 InputGrabEnd();
3468 RTThreadYield();
3469 UpdateTitlebar(TITLEBAR_SAVE);
3470 gProgress = NULL;
3471 HRESULT rc = gConsole->SaveState(gProgress.asOutParam());
3472 if (FAILED(S_OK))
3473 {
3474 RTPrintf("Error saving state! rc = 0x%x\n", rc);
3475 return;
3476 }
3477 Assert(gProgress);
3478
3479 /*
3480 * Wait for the operation to be completed and work
3481 * the title bar in the mean while.
3482 */
3483 LONG cPercent = 0;
3484#ifndef __DARWIN__ /* don't break the other guys yet. */
3485 for (;;)
3486 {
3487 BOOL fCompleted = false;
3488 rc = gProgress->COMGETTER(Completed)(&fCompleted);
3489 if (FAILED(rc) || fCompleted)
3490 break;
3491 LONG cPercentNow;
3492 rc = gProgress->COMGETTER(Percent)(&cPercentNow);
3493 if (FAILED(rc))
3494 break;
3495 if (cPercentNow != cPercent)
3496 {
3497 UpdateTitlebar(TITLEBAR_SAVE, cPercent);
3498 cPercent = cPercentNow;
3499 }
3500
3501 /* wait */
3502 rc = gProgress->WaitForCompletion(100);
3503 if (FAILED(rc))
3504 break;
3505 /// @todo process gui events.
3506 }
3507
3508#else /* new loop which processes GUI events while saving. */
3509
3510 /* start regular timer so we don't starve in the event loop */
3511 SDL_TimerID sdlTimer;
3512 sdlTimer = SDL_AddTimer(100, StartupTimer, NULL);
3513
3514 for (;;)
3515 {
3516 /*
3517 * Check for completion.
3518 */
3519 BOOL fCompleted = false;
3520 rc = gProgress->COMGETTER(Completed)(&fCompleted);
3521 if (FAILED(rc) || fCompleted)
3522 break;
3523 LONG cPercentNow;
3524 rc = gProgress->COMGETTER(Percent)(&cPercentNow);
3525 if (FAILED(rc))
3526 break;
3527 if (cPercentNow != cPercent)
3528 {
3529 UpdateTitlebar(TITLEBAR_SAVE, cPercent);
3530 cPercent = cPercentNow;
3531 }
3532
3533 /*
3534 * Wait for and process GUI a event.
3535 * This is necessary for XPCOM IPC and for updating the
3536 * title bar on the Mac.
3537 */
3538 SDL_Event event;
3539 if (SDL_WaitEvent(&event))
3540 {
3541 switch (event.type)
3542 {
3543 /*
3544 * Timer event preventing us from getting stuck.
3545 */
3546 case SDL_USER_EVENT_TIMER:
3547 break;
3548
3549#ifdef USE_XPCOM_QUEUE_THREAD
3550 /*
3551 * User specific XPCOM event queue event
3552 */
3553 case SDL_USER_EVENT_XPCOM_EVENTQUEUE:
3554 {
3555 LogFlow(("SDL_USER_EVENT_XPCOM_EVENTQUEUE: processing XPCOM event queue...\n"));
3556 eventQ->ProcessPendingEvents();
3557 signalXPCOMEventQueueThread();
3558 break;
3559 }
3560#endif /* USE_XPCOM_QUEUE_THREAD */
3561
3562
3563 /*
3564 * Ignore all other events.
3565 */
3566 case SDL_USER_EVENT_RESIZE:
3567 case SDL_USER_EVENT_TERMINATE:
3568 default:
3569 break;
3570 }
3571 }
3572 }
3573
3574 /* kill the timer */
3575 SDL_RemoveTimer(sdlTimer);
3576 sdlTimer = 0;
3577
3578#endif /* __DARWIN__ */
3579
3580 /*
3581 * What's the result of the operation?
3582 */
3583 HRESULT lrc;
3584 rc = gProgress->COMGETTER(ResultCode)(&lrc);
3585 if (FAILED(rc))
3586 lrc = ~0;
3587 if (!lrc)
3588 {
3589 UpdateTitlebar(TITLEBAR_SAVE, 100);
3590 RTThreadYield();
3591 RTPrintf("Saved the state successfully.\n");
3592 }
3593 else
3594 RTPrintf("Error saving state, lrc=%d (%#x)\n", lrc, lrc);
3595}
3596
3597/**
3598 * Build the titlebar string
3599 */
3600static void UpdateTitlebar(TitlebarMode mode, uint32_t u32User)
3601{
3602 static char szTitle[1024] = {0};
3603
3604 /* back up current title */
3605 char szPrevTitle[1024];
3606 strcpy(szPrevTitle, szTitle);
3607
3608
3609 strcpy(szTitle, "innotek VirtualBox - ");
3610
3611 Bstr name;
3612 gMachine->COMGETTER(Name)(name.asOutParam());
3613 if (name)
3614 strcat(szTitle, Utf8Str(name).raw());
3615 else
3616 strcat(szTitle, "<noname>");
3617
3618
3619 /* which mode are we in? */
3620 switch (mode)
3621 {
3622 case TITLEBAR_NORMAL:
3623 {
3624 MachineState_T machineState;
3625 gMachine->COMGETTER(State)(&machineState);
3626 if (machineState == MachineState_Paused)
3627 strcat(szTitle, " - [Paused]");
3628
3629 if (gfGrabbed)
3630 strcat(szTitle, " - [Input captured]");
3631
3632 // do we have a debugger interface
3633 if (gMachineDebugger)
3634 {
3635#if defined(DEBUG) || defined(VBOX_WITH_STATISTICS)
3636 // query the machine state
3637 BOOL recompileSupervisor = FALSE;
3638 BOOL recompileUser = FALSE;
3639 BOOL patmEnabled = FALSE;
3640 BOOL csamEnabled = FALSE;
3641 BOOL singlestepEnabled = FALSE;
3642 BOOL logEnabled = FALSE;
3643 BOOL hwVirtEnabled = FALSE;
3644 ULONG virtualTimeRate = 100;
3645 gMachineDebugger->COMGETTER(RecompileSupervisor)(&recompileSupervisor);
3646 gMachineDebugger->COMGETTER(RecompileUser)(&recompileUser);
3647 gMachineDebugger->COMGETTER(PATMEnabled)(&patmEnabled);
3648 gMachineDebugger->COMGETTER(CSAMEnabled)(&csamEnabled);
3649 gMachineDebugger->COMGETTER(LogEnabled)(&logEnabled);
3650 gMachineDebugger->COMGETTER(Singlestep)(&singlestepEnabled);
3651 gMachineDebugger->COMGETTER(HWVirtExEnabled)(&hwVirtEnabled);
3652 gMachineDebugger->COMGETTER(VirtualTimeRate)(&virtualTimeRate);
3653 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
3654 " [STEP=%d CS=%d PAT=%d RR0=%d RR3=%d LOG=%d HWVirt=%d",
3655 singlestepEnabled == TRUE, csamEnabled == TRUE, patmEnabled == TRUE,
3656 recompileSupervisor == FALSE, recompileUser == FALSE,
3657 logEnabled == TRUE, hwVirtEnabled == TRUE);
3658 char *psz = strchr(szTitle, '\0');
3659 if (virtualTimeRate != 100)
3660 RTStrPrintf(psz, &szTitle[sizeof(szTitle)] - psz, " WD=%d%%]", virtualTimeRate);
3661 else
3662 RTStrPrintf(psz, &szTitle[sizeof(szTitle)] - psz, "]");
3663#else
3664 BOOL hwVirtEnabled = FALSE;
3665 gMachineDebugger->COMGETTER(HWVirtExEnabled)(&hwVirtEnabled);
3666 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
3667 "%s", hwVirtEnabled ? " (HWVirtEx)" : "");
3668#endif /* DEBUG */
3669 }
3670 break;
3671 }
3672
3673 case TITLEBAR_STARTUP:
3674 {
3675 /*
3676 * Format it.
3677 */
3678 MachineState_T machineState;
3679 gMachine->COMGETTER(State)(&machineState);
3680 if (machineState == MachineState_Starting)
3681 strcat(szTitle, " - Starting...");
3682 else if (machineState == MachineState_Restoring)
3683 {
3684 LONG cPercentNow;
3685 HRESULT rc = gProgress->COMGETTER(Percent)(&cPercentNow);
3686 if (SUCCEEDED(rc))
3687 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
3688 " - Restoring %d%%...", (int)cPercentNow);
3689 else
3690 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
3691 " - Restoring...");
3692 }
3693 /* ignore other states, we could already be in running or aborted state */
3694 break;
3695 }
3696
3697 case TITLEBAR_SAVE:
3698 {
3699 AssertMsg(u32User >= 0 && u32User <= 100, ("%d\n", u32User));
3700 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
3701 " - Saving %d%%...", u32User);
3702 break;
3703 }
3704
3705 case TITLEBAR_SNAPSHOT:
3706 {
3707 AssertMsg(u32User >= 0 && u32User <= 100, ("%d\n", u32User));
3708 RTStrPrintf(szTitle + strlen(szTitle), sizeof(szTitle) - strlen(szTitle),
3709 " - Taking snapshot %d%%...", u32User);
3710 break;
3711 }
3712
3713 default:
3714 RTPrintf("Error: Invalid title bar mode %d!\n", mode);
3715 return;
3716 }
3717
3718 /*
3719 * Don't update if it didn't change.
3720 */
3721 if (strcmp(szTitle, szPrevTitle) == 0)
3722 return;
3723
3724 /*
3725 * Set the new title
3726 */
3727#ifdef VBOX_WIN32_UI
3728 setUITitle(szTitle);
3729#else
3730 SDL_WM_SetCaption(szTitle, "innotek VirtualBox");
3731#endif
3732}
3733
3734#if 0
3735static void vbox_show_shape (unsigned short w, unsigned short h,
3736 uint32_t bg, const uint8_t *image)
3737{
3738 size_t x, y;
3739 unsigned short pitch;
3740 const uint32_t *color;
3741 const uint8_t *mask;
3742 size_t size_mask;
3743
3744 mask = image;
3745 pitch = (w + 7) / 8;
3746 size_mask = (pitch * h + 3) & ~3;
3747
3748 color = (const uint32_t *) (image + size_mask);
3749
3750 printf ("show_shape %dx%d pitch %d size mask %d\n",
3751 w, h, pitch, size_mask);
3752 for (y = 0; y < h; ++y, mask += pitch, color += w)
3753 {
3754 for (x = 0; x < w; ++x) {
3755 if (mask[x / 8] & (1 << (7 - (x % 8))))
3756 printf (" ");
3757 else
3758 {
3759 uint32_t c = color[x];
3760 if (c == bg)
3761 printf ("Y");
3762 else
3763 printf ("X");
3764 }
3765 }
3766 printf ("\n");
3767 }
3768}
3769#endif
3770
3771/**
3772 * Sets the pointer shape according to parameters.
3773 * Must be called only from the main SDL thread.
3774 */
3775static void SetPointerShape (const PointerShapeChangeData *data)
3776{
3777 /*
3778 * don't allow to change the pointer shape if we are outside the valid
3779 * guest area. In that case set standard mouse pointer is set and should
3780 * not get overridden.
3781 */
3782 if (gpOffCursor)
3783 return;
3784
3785 if (data->shape)
3786 {
3787 bool ok = false;
3788
3789 uint32_t andMaskSize = (data->width + 7) / 8 * data->height;
3790 uint32_t srcShapePtrScan = data->width * 4;
3791
3792 const uint8_t *srcAndMaskPtr = data->shape;
3793 const uint8_t *srcShapePtr = data->shape + ((andMaskSize + 3) & ~3);
3794
3795#if 0
3796 /* pointer debugging code */
3797 // vbox_show_shape(data->width, data->height, 0, data->shape);
3798 uint32_t shapeSize = ((((data->width + 7) / 8) * data->height + 3) & ~3) + data->width * 4 * data->height;
3799 printf("visible: %d\n", data->visible);
3800 printf("width = %d\n", data->width);
3801 printf("height = %d\n", data->height);
3802 printf("alpha = %d\n", data->alpha);
3803 printf("xhot = %d\n", data->xHot);
3804 printf("yhot = %d\n", data->yHot);
3805 printf("uint8_t pointerdata[] = { ");
3806 for (uint32_t i = 0; i < shapeSize; i++)
3807 {
3808 printf("0x%x, ", data->shape[i]);
3809 }
3810 printf("};\n");
3811#endif
3812
3813#if defined (__WIN__)
3814
3815 BITMAPV5HEADER bi;
3816 HBITMAP hBitmap;
3817 void *lpBits;
3818 HCURSOR hAlphaCursor = NULL;
3819
3820 ::ZeroMemory (&bi, sizeof (BITMAPV5HEADER));
3821 bi.bV5Size = sizeof (BITMAPV5HEADER);
3822 bi.bV5Width = data->width;
3823 bi.bV5Height = - (LONG) data->height;
3824 bi.bV5Planes = 1;
3825 bi.bV5BitCount = 32;
3826 bi.bV5Compression = BI_BITFIELDS;
3827 // specifiy a supported 32 BPP alpha format for Windows XP
3828 bi.bV5RedMask = 0x00FF0000;
3829 bi.bV5GreenMask = 0x0000FF00;
3830 bi.bV5BlueMask = 0x000000FF;
3831 if (data->alpha)
3832 bi.bV5AlphaMask = 0xFF000000;
3833 else
3834 bi.bV5AlphaMask = 0;
3835
3836 HDC hdc = ::GetDC (NULL);
3837
3838 // create the DIB section with an alpha channel
3839 hBitmap = ::CreateDIBSection (hdc, (BITMAPINFO *) &bi, DIB_RGB_COLORS,
3840 (void **) &lpBits, NULL, (DWORD) 0);
3841
3842 ::ReleaseDC (NULL, hdc);
3843
3844 HBITMAP hMonoBitmap = NULL;
3845 if (data->alpha)
3846 {
3847 // create an empty mask bitmap
3848 hMonoBitmap = ::CreateBitmap (data->width, data->height, 1, 1, NULL);
3849 }
3850 else
3851 {
3852 /* Word aligned AND mask. Will be allocated and created if necessary. */
3853 uint8_t *pu8AndMaskWordAligned = NULL;
3854
3855 /* Width in bytes of the original AND mask scan line. */
3856 uint32_t cbAndMaskScan = (data->width + 7) / 8;
3857
3858 if (cbAndMaskScan & 1)
3859 {
3860 /* Original AND mask is not word aligned. */
3861
3862 /* Allocate memory for aligned AND mask. */
3863 pu8AndMaskWordAligned = (uint8_t *)RTMemTmpAllocZ ((cbAndMaskScan + 1) * data->height);
3864
3865 Assert(pu8AndMaskWordAligned);
3866
3867 if (pu8AndMaskWordAligned)
3868 {
3869 /* According to MSDN the padding bits must be 0.
3870 * Compute the bit mask to set padding bits to 0 in the last byte of original AND mask.
3871 */
3872 uint32_t u32PaddingBits = cbAndMaskScan * 8 - data->width;
3873 Assert(u32PaddingBits < 8);
3874 uint8_t u8LastBytesPaddingMask = (uint8_t)(0xFF << u32PaddingBits);
3875
3876 Log(("u8LastBytesPaddingMask = %02X, aligned w = %d, width = %d, cbAndMaskScan = %d\n",
3877 u8LastBytesPaddingMask, (cbAndMaskScan + 1) * 8, data->width, cbAndMaskScan));
3878
3879 uint8_t *src = (uint8_t *)srcAndMaskPtr;
3880 uint8_t *dst = pu8AndMaskWordAligned;
3881
3882 unsigned i;
3883 for (i = 0; i < data->height; i++)
3884 {
3885 memcpy (dst, src, cbAndMaskScan);
3886
3887 dst[cbAndMaskScan - 1] &= u8LastBytesPaddingMask;
3888
3889 src += cbAndMaskScan;
3890 dst += cbAndMaskScan + 1;
3891 }
3892 }
3893 }
3894
3895 // create the AND mask bitmap
3896 hMonoBitmap = ::CreateBitmap (data->width, data->height, 1, 1,
3897 pu8AndMaskWordAligned? pu8AndMaskWordAligned: srcAndMaskPtr);
3898
3899 if (pu8AndMaskWordAligned)
3900 {
3901 RTMemTmpFree (pu8AndMaskWordAligned);
3902 }
3903 }
3904
3905 Assert (hBitmap);
3906 Assert (hMonoBitmap);
3907 if (hBitmap && hMonoBitmap)
3908 {
3909 DWORD *dstShapePtr = (DWORD *) lpBits;
3910
3911 for (uint32_t y = 0; y < data->height; y ++)
3912 {
3913 memcpy (dstShapePtr, srcShapePtr, srcShapePtrScan);
3914 srcShapePtr += srcShapePtrScan;
3915 dstShapePtr += data->width;
3916 }
3917
3918 ICONINFO ii;
3919 ii.fIcon = FALSE;
3920 ii.xHotspot = data->xHot;
3921 ii.yHotspot = data->yHot;
3922 ii.hbmMask = hMonoBitmap;
3923 ii.hbmColor = hBitmap;
3924
3925 hAlphaCursor = ::CreateIconIndirect (&ii);
3926 Assert (hAlphaCursor);
3927 if (hAlphaCursor)
3928 {
3929 // here we do a dirty trick by substituting a Window Manager's
3930 // cursor handle with the handle we created
3931
3932 WMcursor *pCustomTempWMCursor = gpCustomCursor->wm_cursor;
3933
3934 // see SDL12/src/video/wincommon/SDL_sysmouse.c
3935 void *wm_cursor = malloc (sizeof (HCURSOR) + sizeof (uint8_t *) * 2);
3936 *(HCURSOR *) wm_cursor = hAlphaCursor;
3937
3938 gpCustomCursor->wm_cursor = (WMcursor *) wm_cursor;
3939 SDL_SetCursor (gpCustomCursor);
3940 SDL_ShowCursor (SDL_ENABLE);
3941
3942 if (pCustomTempWMCursor)
3943 {
3944 ::DestroyCursor (* (HCURSOR *) pCustomTempWMCursor);
3945 free (pCustomTempWMCursor);
3946 }
3947
3948 ok = true;
3949 }
3950 }
3951
3952 if (hMonoBitmap)
3953 ::DeleteObject (hMonoBitmap);
3954 if (hBitmap)
3955 ::DeleteObject (hBitmap);
3956
3957#elif defined (__LINUX__)
3958
3959 XcursorImage *img = XcursorImageCreate (data->width, data->height);
3960 Assert (img);
3961 if (img)
3962 {
3963 img->xhot = data->xHot;
3964 img->yhot = data->yHot;
3965
3966 XcursorPixel *dstShapePtr = img->pixels;
3967
3968 for (uint32_t y = 0; y < data->height; y ++)
3969 {
3970 memcpy (dstShapePtr, srcShapePtr, srcShapePtrScan);
3971
3972 if (!data->alpha)
3973 {
3974 // convert AND mask to the alpha channel
3975 uint8_t byte = 0;
3976 for (uint32_t x = 0; x < data->width; x ++)
3977 {
3978 if (!(x % 8))
3979 byte = *(srcAndMaskPtr ++);
3980 else
3981 byte <<= 1;
3982
3983 if (byte & 0x80)
3984 {
3985 // Linux doesn't support inverted pixels (XOR ops,
3986 // to be exact) in cursor shapes, so we detect such
3987 // pixels and always replace them with black ones to
3988 // make them visible at least over light colors
3989 if (dstShapePtr [x] & 0x00FFFFFF)
3990 dstShapePtr [x] = 0xFF000000;
3991 else
3992 dstShapePtr [x] = 0x00000000;
3993 }
3994 else
3995 dstShapePtr [x] |= 0xFF000000;
3996 }
3997 }
3998
3999 srcShapePtr += srcShapePtrScan;
4000 dstShapePtr += data->width;
4001 }
4002
4003 Cursor cur = XcursorImageLoadCursor (gSdlInfo.info.x11.display, img);
4004 Assert (cur);
4005 if (cur)
4006 {
4007 // here we do a dirty trick by substituting a Window Manager's
4008 // cursor handle with the handle we created
4009
4010 WMcursor *pCustomTempWMCursor = gpCustomCursor->wm_cursor;
4011
4012 // see SDL12/src/video/x11/SDL_x11mouse.c
4013 void *wm_cursor = malloc (sizeof (Cursor));
4014 *(Cursor *) wm_cursor = cur;
4015
4016 gpCustomCursor->wm_cursor = (WMcursor *) wm_cursor;
4017 SDL_SetCursor (gpCustomCursor);
4018 SDL_ShowCursor (SDL_ENABLE);
4019
4020 if (pCustomTempWMCursor)
4021 {
4022 XFreeCursor (gSdlInfo.info.x11.display, *(Cursor *) pCustomTempWMCursor);
4023 free (pCustomTempWMCursor);
4024 }
4025
4026 ok = true;
4027 }
4028
4029 XcursorImageDestroy (img);
4030 }
4031
4032#endif
4033
4034 if (!ok)
4035 {
4036 SDL_SetCursor (gpDefaultCursor);
4037 SDL_ShowCursor (SDL_ENABLE);
4038 }
4039 }
4040 else
4041 {
4042 if (data->visible)
4043 SDL_ShowCursor (SDL_ENABLE);
4044 else if (gfAbsoluteMouseGuest)
4045 /* Don't disable the cursor if the guest additions are not active (anymore) */
4046 SDL_ShowCursor (SDL_DISABLE);
4047 }
4048}
4049
4050/**
4051 * Handle changed mouse capabilities
4052 */
4053static void HandleGuestCapsChanged(void)
4054{
4055 if (!gfAbsoluteMouseGuest)
4056 {
4057 // Cursor could be overwritten by the guest tools
4058 SDL_SetCursor(gpDefaultCursor);
4059 SDL_ShowCursor (SDL_ENABLE);
4060 gpOffCursor = NULL;
4061 }
4062 if (gMouse && UseAbsoluteMouse())
4063 {
4064 // Actually switch to absolute coordinates
4065 if (gfGrabbed)
4066 InputGrabEnd();
4067 gMouse->PutMouseEventAbsolute(-1, -1, 0, 0);
4068 }
4069}
4070
4071/**
4072 * Handles a host key down event
4073 */
4074static int HandleHostKey(const SDL_KeyboardEvent *pEv)
4075{
4076 /*
4077 * Revalidate the host key modifier
4078 */
4079 if ((SDL_GetModState() & ~(KMOD_MODE | KMOD_NUM | KMOD_RESERVED)) != gHostKeyMod)
4080 return VERR_NOT_SUPPORTED;
4081
4082 /*
4083 * What was pressed?
4084 */
4085 switch (pEv->keysym.sym)
4086 {
4087 /* Control-Alt-Delete */
4088 case SDLK_DELETE:
4089 {
4090 gKeyboard->PutCAD();
4091 break;
4092 }
4093
4094 /*
4095 * Fullscreen / Windowed toggle.
4096 */
4097 case SDLK_f:
4098 {
4099 if (gfAllowFullscreenToggle)
4100 {
4101 /*
4102 * We have to pause/resume the machine during this
4103 * process because there might be a short moment
4104 * without a valid framebuffer
4105 */
4106 MachineState_T machineState;
4107 gMachine->COMGETTER(State)(&machineState);
4108 if (machineState == MachineState_Running)
4109 gConsole->Pause();
4110 gpFrameBuffer->setFullscreen(!gpFrameBuffer->getFullscreen());
4111 if (machineState == MachineState_Running)
4112 gConsole->Resume();
4113
4114 /*
4115 * We have switched from/to fullscreen, so request a full
4116 * screen repaint, just to be sure.
4117 */
4118 gDisplay->InvalidateAndUpdate();
4119 }
4120 break;
4121 }
4122
4123 /*
4124 * Pause / Resume toggle.
4125 */
4126 case SDLK_p:
4127 {
4128 MachineState_T machineState;
4129 gMachine->COMGETTER(State)(&machineState);
4130 if (machineState == MachineState_Running)
4131 {
4132 if (gfGrabbed)
4133 InputGrabEnd();
4134 gConsole->Pause();
4135 }
4136 else if (machineState == MachineState_Paused)
4137 {
4138 gConsole->Resume();
4139 }
4140 UpdateTitlebar(TITLEBAR_NORMAL);
4141 break;
4142 }
4143
4144 /*
4145 * Reset the VM
4146 */
4147 case SDLK_r:
4148 {
4149 ResetVM();
4150 break;
4151 }
4152
4153 /*
4154 * Terminate the VM
4155 */
4156 case SDLK_q:
4157 {
4158 return VINF_EM_TERMINATE;
4159 break;
4160 }
4161
4162 /*
4163 * Save the machine's state and exit
4164 */
4165 case SDLK_s:
4166 {
4167 SaveState();
4168 return VINF_EM_TERMINATE;
4169 }
4170
4171 case SDLK_h:
4172 {
4173 if (gConsole)
4174 gConsole->PowerButton();
4175 break;
4176 }
4177
4178 /*
4179 * Perform an online snapshot. Continue operation.
4180 */
4181 case SDLK_n:
4182 {
4183 RTThreadYield();
4184 ULONG cSnapshots = 0;
4185 gMachine->COMGETTER(SnapshotCount)(&cSnapshots);
4186 char pszSnapshotName[20];
4187 RTStrPrintf(pszSnapshotName, sizeof(pszSnapshotName), "Snapshot %d", cSnapshots + 1);
4188 gProgress = NULL;
4189 HRESULT rc;
4190 CHECK_ERROR(gConsole, TakeSnapshot(Bstr(pszSnapshotName), Bstr("Taken by VBoxSDL"),
4191 gProgress.asOutParam()));
4192 if (FAILED(rc))
4193 {
4194 RTPrintf("Error taking snapshot! rc = 0x%x\n", rc);
4195 /* continue operation */
4196 return VINF_SUCCESS;
4197 }
4198 /*
4199 * Wait for the operation to be completed and work
4200 * the title bar in the mean while.
4201 */
4202 LONG cPercent = 0;
4203 for (;;)
4204 {
4205 BOOL fCompleted = false;
4206 rc = gProgress->COMGETTER(Completed)(&fCompleted);
4207 if (FAILED(rc) || fCompleted)
4208 break;
4209 LONG cPercentNow;
4210 rc = gProgress->COMGETTER(Percent)(&cPercentNow);
4211 if (FAILED(rc))
4212 break;
4213 if (cPercentNow != cPercent)
4214 {
4215 UpdateTitlebar(TITLEBAR_SNAPSHOT, cPercent);
4216 cPercent = cPercentNow;
4217 }
4218
4219 /* wait */
4220 rc = gProgress->WaitForCompletion(100);
4221 if (FAILED(rc))
4222 break;
4223 /// @todo process gui events.
4224 }
4225
4226 /* continue operation */
4227 return VINF_SUCCESS;
4228 }
4229
4230 case SDLK_F1: case SDLK_F2: case SDLK_F3:
4231 case SDLK_F4: case SDLK_F5: case SDLK_F6:
4232 case SDLK_F7: case SDLK_F8: case SDLK_F9:
4233 case SDLK_F10: case SDLK_F11: case SDLK_F12:
4234 {
4235 /* send Ctrl-Alt-Fx to guest */
4236 static LONG keySequence[] = {
4237 0x1d, // Ctrl down
4238 0x38, // Alt down
4239 0x00, // Fx down (placeholder)
4240 0x00, // Fx up (placeholder)
4241 0xb8, // Alt up
4242 0x9d // Ctrl up
4243 };
4244
4245 /* put in the right Fx key */
4246 keySequence[2] = Keyevent2Keycode(pEv);
4247 keySequence[3] = keySequence[2] + 0x80;
4248
4249 gKeyboard->PutScancodes(keySequence, ELEMENTS(keySequence), NULL);
4250 return VINF_SUCCESS;
4251 }
4252
4253 /*
4254 * Not a host key combination.
4255 * Indicate this by returning false.
4256 */
4257 default:
4258 return VERR_NOT_SUPPORTED;
4259 }
4260
4261 return VINF_SUCCESS;
4262}
4263
4264/**
4265 * Timer callback function for startup processing
4266 */
4267static Uint32 StartupTimer(Uint32 interval, void *param)
4268{
4269 /* post message so we can do something in the startup loop */
4270 SDL_Event event = {0};
4271 event.type = SDL_USEREVENT;
4272 event.user.type = SDL_USER_EVENT_TIMER;
4273 SDL_PushEvent(&event);
4274 return interval;
4275}
4276
4277/**
4278 * Timer callback function to check if resizing is finished
4279 */
4280static Uint32 ResizeTimer(Uint32 interval, void *param)
4281{
4282 /* post message so the window is actually resized */
4283 SDL_Event event = {0};
4284 event.type = SDL_USEREVENT;
4285 event.user.type = SDL_USER_EVENT_WINDOW_RESIZE_DONE;
4286 SDL_PushEvent(&event);
4287 /* one-shot */
4288 return 0;
4289}
Note: See TracBrowser for help on using the repository browser.

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