VirtualBox

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

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

Guest properties: initial commit of new interface

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette