VirtualBox

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

Last change on this file since 7389 was 7379, checked in by vboxsync, 17 years ago

VBoxManage, VBoxSDL: Added support for user notification about settings file auto-conversion (#2705). Added -convertSettings* command line switches to control how auto-converted settings are saved.

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