VirtualBox

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

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

FE/SDL: fixed two potential races when terminating the VM

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