VirtualBox

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

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

Main: Added IVirtualBox::findHardDisk().
VBoxSDL: Fixed so that .vmdk images can be passed using the -hda switch.

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