VirtualBox

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

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

Main & All Frontends: Improved console window activation helper APIs (still no success on X11, works well on Win32, the old method of activation is disabled).

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