VirtualBox

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

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

FE/SDL: Printf to stderr on runtime error as long as we don't have a better mechanism.

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

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