VirtualBox

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

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

Backed out r35359

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