VirtualBox

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

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

FE/SDL: added support for Japanese and Brazilian keyboards

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