VirtualBox

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

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

Main: XPCOM: Initial implementation of auto-startable "out-of-proc" VirtualBox component (VBoxSVC).

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

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