VirtualBox

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

Last change on this file since 649 was 614, checked in by vboxsync, 18 years ago

Darwin port (hope I didn't mess up anything, am very Zzzzz...)

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

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