VirtualBox

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

Last change on this file since 4612 was 4486, checked in by vboxsync, 17 years ago

FE/SDL: added -boot n switch for temporarily booting from network

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