VirtualBox

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

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

VBoxSDL: Fixed: Floppy/DVD image operations were case sensitive on Win32 (defect #1940).

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