VirtualBox

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

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

bugfix: RTPathReal presumes that the path exists!

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