VirtualBox

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

Last change on this file since 1 was 1, checked in by vboxsync, 55 years ago

import

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

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