VirtualBox

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

Last change on this file since 10700 was 10678, checked in by vboxsync, 17 years ago

Build fix.

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