VirtualBox

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

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

Main & All Frontends: Prototyped a bunch of Main API changes (IVirtualBoxErrorInfo extension for cascading errors; IMachine/IConsoleCallback extension to properly activate the console window; IVirtualBoxCallback::onExtraDataCanChange() support for error messages; minor IHost::createUSBDeviceFilter/removeUSBDeviceFilter corrections).

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

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