VirtualBox

source: vbox/trunk/src/VBox/Frontends/VirtualBox/src/VBoxConsoleView.cpp@ 9203

Last change on this file since 9203 was 9076, checked in by vboxsync, 16 years ago

Frontends/VirtualBox and VirtualBox4: revert r31170 until after 1.6.2

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 121.0 KB
Line 
1/** @file
2 *
3 * VBox frontends: Qt GUI ("VirtualBox"):
4 * VBoxConsoleView class implementation
5 */
6
7/*
8 * Copyright (C) 22006-2007 Sun Microsystems, Inc.
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 *
18 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
19 * Clara, CA 95054 USA or visit http://www.sun.com if you need
20 * additional information or have any questions.
21 */
22
23#include "VBoxConsoleView.h"
24#include "VBoxConsoleWnd.h"
25#include "VBoxUtils.h"
26
27#include "VBoxFrameBuffer.h"
28#include "VBoxGlobal.h"
29#include "VBoxProblemReporter.h"
30
31#ifdef Q_WS_PM
32#include "QIHotKeyEdit.h"
33#endif
34
35#include <qapplication.h>
36#include <qstatusbar.h>
37#include <qlabel.h>
38#include <qpainter.h>
39#include <qpixmap.h>
40#include <qimage.h>
41#include <qbitmap.h>
42#include <qcursor.h>
43#include <qthread.h>
44
45#include <qmenudata.h>
46#include <qmenubar.h>
47#include <qwidgetlist.h>
48#include <qtimer.h>
49
50#ifdef Q_WS_WIN
51// VBox/cdefs.h defines these:
52#undef LOWORD
53#undef HIWORD
54#undef LOBYTE
55#undef HIBYTE
56#include <windows.h>
57#endif
58
59#ifdef Q_WS_X11
60// We need to capture some X11 events directly which
61// requires the XEvent structure to be defined. However,
62// including the Xlib header file will cause some nasty
63// conflicts with Qt. Therefore we use the following hack
64// to redefine those conflicting identifiers.
65#define XK_XKB_KEYS
66#define XK_MISCELLANY
67#include <X11/Xlib.h>
68#include <X11/Xutil.h>
69#include <X11/XKBlib.h>
70#include <X11/keysym.h>
71#ifdef KeyPress
72const int XFocusOut = FocusOut;
73const int XFocusIn = FocusIn;
74const int XKeyPress = KeyPress;
75const int XKeyRelease = KeyRelease;
76#undef KeyRelease
77#undef KeyPress
78#undef FocusOut
79#undef FocusIn
80#endif
81#include "XKeyboard.h"
82#ifndef VBOX_WITHOUT_XCURSOR
83# include <X11/Xcursor/Xcursor.h>
84#endif
85#endif // Q_WS_X11
86
87#if defined (Q_WS_MAC)
88# include "DarwinKeyboard.h"
89# include "DarwinCursor.h"
90# ifdef VBOX_WITH_HACKED_QT
91# include "QIApplication.h"
92# endif
93# include <VBox/err.h>
94#endif /* defined (Q_WS_MAC) */
95
96#if defined (Q_WS_WIN32)
97
98static HHOOK gKbdHook = NULL;
99static VBoxConsoleView *gView = 0;
100
101LRESULT CALLBACK VBoxConsoleView::lowLevelKeyboardProc (int nCode,
102 WPARAM wParam, LPARAM lParam)
103{
104 Assert (gView);
105 if (gView && nCode == HC_ACTION &&
106 gView->winLowKeyboardEvent (wParam, *(KBDLLHOOKSTRUCT *) lParam))
107 return 1;
108
109 return CallNextHookEx (NULL, nCode, wParam, lParam);
110}
111
112#endif
113
114#if defined (Q_WS_MAC)
115
116# ifndef VBOX_WITH_HACKED_QT
117/**
118 * Event handler callback for Mac OS X.
119 */
120/* static */
121pascal OSStatus VBoxConsoleView::darwinEventHandlerProc (EventHandlerCallRef inHandlerCallRef,
122 EventRef inEvent, void *inUserData)
123{
124 VBoxConsoleView *view = (VBoxConsoleView *)inUserData;
125 UInt32 EventClass = ::GetEventClass (inEvent);
126 if (EventClass == kEventClassKeyboard)
127 {
128 if (view->darwinKeyboardEvent (inEvent))
129 return 0;
130 }
131 /*
132 * Command-H and Command-Q aren't properly disabled yet, and it's still
133 * possible to use the left command key to invoke them when the keyboard
134 * is captured. We discard the events these if the keyboard is captured
135 * as a half measure to prevent unexpected behaviour. However, we don't
136 * get any key down/up events, so these combinations are dead to the guest...
137 */
138 else if (EventClass == kEventClassCommand)
139 {
140 if (view->mKbdCaptured)
141 return 0;
142 }
143 return ::CallNextEventHandler (inHandlerCallRef, inEvent);
144}
145
146# else /* VBOX_WITH_HACKED_QT */
147
148/**
149 * Event handler callback for Mac OS X.
150 */
151/* static */
152bool VBoxConsoleView::macEventFilter (EventRef inEvent, void *inUserData)
153{
154 VBoxConsoleView *view = static_cast<VBoxConsoleView *> (inUserData);
155 UInt32 eventClass = ::GetEventClass (inEvent);
156 UInt32 eventKind = ::GetEventKind (inEvent);
157
158 /* For debugging events */
159 /*
160 if (!(eventKind == kEventWindowActivated ||
161 eventClass == 0x63757465))
162 ::DarwinDebugPrintEvent ("view: ", inEvent);
163 */
164
165 /* Not sure but this seems an triggered event if the spotlight searchbar is
166 * displayed. So flag that the host key isn't pressed alone. */
167 if (eventClass == 'cgs ' && eventKind == 0x15 &&
168 view->mIsHostkeyPressed)
169 view->mIsHostkeyAlone = false;
170
171 if (eventClass == kEventClassKeyboard)
172 {
173 if (view->darwinKeyboardEvent (inEvent))
174 return true;
175 }
176 return false;
177}
178# endif /* VBOX_WITH_HACKED_QT */
179
180#endif /* Q_WS_MAC */
181
182/** Guest mouse pointer shape change event. */
183class MousePointerChangeEvent : public QEvent
184{
185public:
186 MousePointerChangeEvent (bool visible, bool alpha, uint xhot, uint yhot,
187 uint width, uint height,
188 const uchar *shape) :
189 QEvent ((QEvent::Type) VBoxDefs::MousePointerChangeEventType),
190 vis (visible), alph (alpha), xh (xhot), yh (yhot), w (width), h (height),
191 data (NULL)
192 {
193 // make a copy of shape
194 uint dataSize = ((((width + 7) / 8 * height) + 3) & ~3) + width * 4 * height;
195
196 if (shape) {
197 data = new uchar [dataSize];
198 memcpy ((void *) data, (void *) shape, dataSize);
199 }
200 }
201 ~MousePointerChangeEvent()
202 {
203 if (data) delete[] data;
204 }
205 bool isVisible() const { return vis; }
206 bool hasAlpha() const { return alph; }
207 uint xHot() const { return xh; }
208 uint yHot() const { return yh; }
209 uint width() const { return w; }
210 uint height() const { return h; }
211 const uchar *shapeData() const { return data; }
212private:
213 bool vis, alph;
214 uint xh, yh, w, h;
215 const uchar *data;
216};
217
218/** Guest mouse absolute positioning capability change event. */
219class MouseCapabilityEvent : public QEvent
220{
221public:
222 MouseCapabilityEvent (bool supportsAbsolute, bool needsHostCursor) :
223 QEvent ((QEvent::Type) VBoxDefs::MouseCapabilityEventType),
224 can_abs (supportsAbsolute),
225 needs_host_cursor (needsHostCursor) {}
226 bool supportsAbsolute() const { return can_abs; }
227 bool needsHostCursor() const { return needs_host_cursor; }
228private:
229 bool can_abs;
230 bool needs_host_cursor;
231};
232
233/** Machine state change. */
234class StateChangeEvent : public QEvent
235{
236public:
237 StateChangeEvent (KMachineState state) :
238 QEvent ((QEvent::Type) VBoxDefs::MachineStateChangeEventType),
239 s (state) {}
240 KMachineState machineState() const { return s; }
241private:
242 KMachineState s;
243};
244
245/** Guest Additions property changes. */
246class GuestAdditionsEvent : public QEvent
247{
248public:
249 GuestAdditionsEvent (const QString &aOsTypeId,
250 const QString &aAddVersion,
251 bool aAddActive,
252 bool aSupportsSeamless,
253 bool aSupportsGraphics) :
254 QEvent ((QEvent::Type) VBoxDefs::AdditionsStateChangeEventType),
255 mOsTypeId (aOsTypeId), mAddVersion (aAddVersion),
256 mAddActive (aAddActive), mSupportsSeamless (aSupportsSeamless),
257 mSupportsGraphics (aSupportsGraphics) {}
258 const QString &osTypeId() const { return mOsTypeId; }
259 const QString &additionVersion() const { return mAddVersion; }
260 bool additionActive() const { return mAddActive; }
261 bool supportsSeamless() const { return mSupportsSeamless; }
262 bool supportsGraphics() const { return mSupportsGraphics; }
263private:
264 QString mOsTypeId;
265 QString mAddVersion;
266 bool mAddActive;
267 bool mSupportsSeamless;
268 bool mSupportsGraphics;
269};
270
271/** DVD/FD change event */
272class MediaChangeEvent : public QEvent
273{
274public:
275 MediaChangeEvent (VBoxDefs::DiskType aType)
276 : QEvent ((QEvent::Type) VBoxDefs::MediaChangeEventType)
277 , mType (aType) {}
278 VBoxDefs::DiskType diskType() const { return mType; }
279private:
280 VBoxDefs::DiskType mType;
281};
282
283/** Menu activation event */
284class ActivateMenuEvent : public QEvent
285{
286public:
287 ActivateMenuEvent (QMenuData *menuData, uint index) :
288 QEvent ((QEvent::Type) VBoxDefs::ActivateMenuEventType),
289 md (menuData), i (index) {}
290 QMenuData *menuData() const { return md; }
291 uint index() const { return i; }
292private:
293 QMenuData *md;
294 uint i;
295};
296
297/** VM Runtime error event */
298class RuntimeErrorEvent : public QEvent
299{
300public:
301 RuntimeErrorEvent (bool aFatal, const QString &aErrorID,
302 const QString &aMessage) :
303 QEvent ((QEvent::Type) VBoxDefs::RuntimeErrorEventType),
304 mFatal (aFatal), mErrorID (aErrorID), mMessage (aMessage) {}
305 bool fatal() const { return mFatal; }
306 QString errorID() const { return mErrorID; }
307 QString message() const { return mMessage; }
308private:
309 bool mFatal;
310 QString mErrorID;
311 QString mMessage;
312};
313
314/** Modifier key change event */
315class ModifierKeyChangeEvent : public QEvent
316{
317public:
318 ModifierKeyChangeEvent (bool fNumLock, bool fCapsLock, bool fScrollLock) :
319 QEvent ((QEvent::Type) VBoxDefs::ModifierKeyChangeEventType),
320 mNumLock (fNumLock), mCapsLock (fCapsLock), mScrollLock (fScrollLock) {}
321 bool numLock() const { return mNumLock; }
322 bool capsLock() const { return mCapsLock; }
323 bool scrollLock() const { return mScrollLock; }
324private:
325 bool mNumLock, mCapsLock, mScrollLock;
326};
327
328/** Network adapter change event */
329class NetworkAdapterChangeEvent : public QEvent
330{
331public:
332 NetworkAdapterChangeEvent (INetworkAdapter *aAdapter) :
333 QEvent ((QEvent::Type) VBoxDefs::NetworkAdapterChangeEventType),
334 mAdapter (aAdapter) {}
335 INetworkAdapter* networkAdapter() { return mAdapter; }
336private:
337 INetworkAdapter *mAdapter;
338};
339
340/** USB controller state change event */
341class USBControllerStateChangeEvent : public QEvent
342{
343public:
344 USBControllerStateChangeEvent()
345 : QEvent ((QEvent::Type) VBoxDefs::USBCtlStateChangeEventType) {}
346};
347
348/** USB device state change event */
349class USBDeviceStateChangeEvent : public QEvent
350{
351public:
352 USBDeviceStateChangeEvent (const CUSBDevice &aDevice, bool aAttached,
353 const CVirtualBoxErrorInfo &aError) :
354 QEvent ((QEvent::Type) VBoxDefs::USBDeviceStateChangeEventType),
355 mDevice (aDevice), mAttached (aAttached), mError (aError) {}
356 CUSBDevice device() const { return mDevice; }
357 bool attached() const { return mAttached; }
358 CVirtualBoxErrorInfo error() const { return mError; }
359private:
360 CUSBDevice mDevice;
361 bool mAttached;
362 CVirtualBoxErrorInfo mError;
363};
364
365//
366// VBoxConsoleCallback class
367/////////////////////////////////////////////////////////////////////////////
368
369class VBoxConsoleCallback : public IConsoleCallback
370{
371public:
372
373 VBoxConsoleCallback (VBoxConsoleView *v) {
374#if defined (Q_WS_WIN)
375 mRefCnt = 0;
376#endif
377 mView = v;
378 }
379
380 virtual ~VBoxConsoleCallback() {}
381
382 NS_DECL_ISUPPORTS
383
384#if defined (Q_WS_WIN)
385 STDMETHOD_(ULONG, AddRef)() {
386 return ::InterlockedIncrement (&mRefCnt);
387 }
388 STDMETHOD_(ULONG, Release)()
389 {
390 long cnt = ::InterlockedDecrement (&mRefCnt);
391 if (cnt == 0)
392 delete this;
393 return cnt;
394 }
395 STDMETHOD(QueryInterface) (REFIID riid , void **ppObj)
396 {
397 if (riid == IID_IUnknown) {
398 *ppObj = this;
399 AddRef();
400 return S_OK;
401 }
402 if (riid == IID_IConsoleCallback) {
403 *ppObj = this;
404 AddRef();
405 return S_OK;
406 }
407 *ppObj = NULL;
408 return E_NOINTERFACE;
409 }
410#endif
411
412 STDMETHOD(OnMousePointerShapeChange) (BOOL visible, BOOL alpha,
413 ULONG xhot, ULONG yhot,
414 ULONG width, ULONG height,
415 BYTE *shape)
416 {
417 QApplication::postEvent (mView,
418 new MousePointerChangeEvent (visible, alpha,
419 xhot, yhot,
420 width, height, shape));
421 return S_OK;
422 }
423
424 STDMETHOD(OnMouseCapabilityChange)(BOOL supportsAbsolute, BOOL needsHostCursor)
425 {
426 QApplication::postEvent (mView,
427 new MouseCapabilityEvent (supportsAbsolute,
428 needsHostCursor));
429 return S_OK;
430 }
431
432 STDMETHOD(OnKeyboardLedsChange)(BOOL fNumLock, BOOL fCapsLock, BOOL fScrollLock)
433 {
434 QApplication::postEvent (mView,
435 new ModifierKeyChangeEvent (fNumLock, fCapsLock,
436 fScrollLock));
437 return S_OK;
438 }
439
440 STDMETHOD(OnStateChange)(MachineState_T machineState)
441 {
442 LogFlowFunc (("machineState=%d\n", machineState));
443 QApplication::postEvent (mView,
444 new StateChangeEvent ((KMachineState) machineState));
445 return S_OK;
446 }
447
448 STDMETHOD(OnAdditionsStateChange)()
449 {
450 CGuest guest = mView->console().GetGuest();
451 LogFlowFunc (("ver=%s, active=%d\n",
452 guest.GetAdditionsVersion().latin1(),
453 guest.GetAdditionsActive()));
454 QApplication::postEvent (mView,
455 new GuestAdditionsEvent (
456 guest.GetOSTypeId(),
457 guest.GetAdditionsVersion(),
458 guest.GetAdditionsActive(),
459 guest.GetSupportsSeamless(),
460 guest.GetSupportsGraphics()));
461 return S_OK;
462 }
463
464 STDMETHOD(OnDVDDriveChange)()
465 {
466 LogFlowFunc (("DVD Drive changed\n"));
467 QApplication::postEvent (mView, new MediaChangeEvent (VBoxDefs::CD));
468 return S_OK;
469 }
470
471 STDMETHOD(OnFloppyDriveChange)()
472 {
473 LogFlowFunc (("Floppy Drive changed\n"));
474 QApplication::postEvent (mView, new MediaChangeEvent (VBoxDefs::FD));
475 return S_OK;
476 }
477
478 STDMETHOD(OnNetworkAdapterChange) (INetworkAdapter *aNetworkAdapter)
479 {
480 QApplication::postEvent (mView,
481 new NetworkAdapterChangeEvent (aNetworkAdapter));
482 return S_OK;
483 }
484
485 STDMETHOD(OnSerialPortChange) (ISerialPort *aSerialPort)
486 {
487 NOREF(aSerialPort);
488 return S_OK;
489 }
490
491 STDMETHOD(OnParallelPortChange) (IParallelPort *aParallelPort)
492 {
493 NOREF(aParallelPort);
494 return S_OK;
495 }
496
497 STDMETHOD(OnVRDPServerChange)()
498 {
499 return S_OK;
500 }
501
502 STDMETHOD(OnUSBControllerChange)()
503 {
504 QApplication::postEvent (mView,
505 new USBControllerStateChangeEvent());
506 return S_OK;
507 }
508
509 STDMETHOD(OnUSBDeviceStateChange)(IUSBDevice *aDevice, BOOL aAttached,
510 IVirtualBoxErrorInfo *aError)
511 {
512 QApplication::postEvent (mView,
513 new USBDeviceStateChangeEvent (
514 CUSBDevice (aDevice),
515 bool (aAttached),
516 CVirtualBoxErrorInfo (aError)));
517 return S_OK;
518 }
519
520 STDMETHOD(OnSharedFolderChange) (Scope_T aScope)
521 {
522 NOREF(aScope);
523 QApplication::postEvent (mView,
524 new QEvent ((QEvent::Type)
525 VBoxDefs::SharedFolderChangeEventType));
526 return S_OK;
527 }
528
529 STDMETHOD(OnRuntimeError)(BOOL fatal, IN_BSTRPARAM id, IN_BSTRPARAM message)
530 {
531 QApplication::postEvent (mView,
532 new RuntimeErrorEvent (!!fatal,
533 QString::fromUcs2 (id),
534 QString::fromUcs2 (message)));
535 return S_OK;
536 }
537
538 STDMETHOD(OnCanShowWindow) (BOOL *canShow)
539 {
540 if (!canShow)
541 return E_POINTER;
542
543 /* as long as there is VBoxConsoleView (which creates/destroys us), it
544 * can be shown */
545 *canShow = TRUE;
546 return S_OK;
547 }
548
549 STDMETHOD(OnShowWindow) (ULONG64 *winId)
550 {
551 if (!winId)
552 return E_POINTER;
553
554#if defined (Q_WS_MAC)
555 /*
556 * Let's try the simple approach first - grab the focus.
557 * Getting a window out of the dock (minimized or whatever it's called)
558 * needs to be done on the GUI thread, so post it a note.
559 */
560 *winId = 0;
561 if (!mView)
562 return S_OK;
563
564 ProcessSerialNumber psn = { 0, kCurrentProcess };
565 OSErr rc = ::SetFrontProcess (&psn);
566 if (!rc)
567 QApplication::postEvent (mView, new QEvent ((QEvent::Type)VBoxDefs::ShowWindowEventType));
568 else
569 {
570 /*
571 * It failed for some reason, send the other process our PSN so it can try.
572 * (This is just a precaution should Mac OS X start imposing the same sensible
573 * focus stealing restrictions that other window managers implement.)
574 */
575 AssertMsgFailed(("SetFrontProcess -> %#x\n", rc));
576 if (::GetCurrentProcess (&psn))
577 *winId = RT_MAKE_U64 (psn.lowLongOfPSN, psn.highLongOfPSN);
578 }
579
580#else
581 /* Return the ID of the top-level console window. */
582 *winId = (ULONG64) mView->topLevelWidget()->winId();
583#endif
584
585 return S_OK;
586 }
587
588protected:
589
590 VBoxConsoleView *mView;
591
592#if defined (Q_WS_WIN)
593private:
594 long mRefCnt;
595#endif
596};
597
598#if !defined (Q_WS_WIN)
599NS_DECL_CLASSINFO (VBoxConsoleCallback)
600NS_IMPL_THREADSAFE_ISUPPORTS1_CI (VBoxConsoleCallback, IConsoleCallback)
601#endif
602
603//
604// VBoxConsoleView class
605/////////////////////////////////////////////////////////////////////////////
606
607/** @class VBoxConsoleView
608 *
609 * The VBoxConsoleView class is a widget that implements a console
610 * for the running virtual machine.
611 */
612
613VBoxConsoleView::VBoxConsoleView (VBoxConsoleWnd *mainWnd,
614 const CConsole &console,
615 VBoxDefs::RenderMode rm,
616 QWidget *parent, const char *name, WFlags f)
617 : QScrollView (parent, name, f | WStaticContents | WNoAutoErase)
618 , mMainWnd (mainWnd)
619 , mConsole (console)
620 , gs (vboxGlobal().settings())
621 , mAttached (false)
622 , mKbdCaptured (false)
623 , mMouseCaptured (false)
624 , mMouseAbsolute (false)
625 , mMouseIntegration (true)
626 , mDisableAutoCapture (false)
627 , mIsHostkeyPressed (false)
628 , mIsHostkeyAlone (false)
629 , mIgnoreMainwndResize (true)
630 , mAutoresizeGuest (false)
631 , mDoResize (false)
632 , mGuestSupportsGraphics (false)
633 , mNumLock (false)
634 , mScrollLock (false)
635 , mCapsLock (false)
636 , muNumLockAdaptionCnt (2)
637 , muCapsLockAdaptionCnt (2)
638 , mode (rm)
639#if defined(Q_WS_WIN)
640 , mAlphaCursor (NULL)
641#endif
642#if defined(Q_WS_MAC)
643# ifndef VBOX_WITH_HACKED_QT
644 , mDarwinEventHandlerRef (NULL)
645# endif
646 , mDarwinKeyModifiers (0)
647 , mVirtualBoxLogo (NULL)
648#endif
649 , mDesktopGeo (DesktopGeo_Invalid)
650{
651 Assert (!mConsole.isNull() &&
652 !mConsole.GetDisplay().isNull() &&
653 !mConsole.GetKeyboard().isNull() &&
654 !mConsole.GetMouse().isNull());
655
656#ifdef Q_WS_MAC
657 /* Overlay logo for the dock icon */
658 mVirtualBoxLogo = ::DarwinQPixmapFromMimeSourceToCGImage ("VirtualBox_cube_42px.png");
659#endif
660
661 /* enable MouseMove events */
662 viewport()->setMouseTracking (true);
663
664 /*
665 * QScrollView does the below on its own, but let's do it anyway
666 * for the case it will not do it in the future.
667 */
668 viewport()->installEventFilter (this);
669
670 /* to fix some focus issues */
671 mMainWnd->menuBar()->installEventFilter (this);
672
673 /* we want to be notified on some parent's events */
674 mMainWnd->installEventFilter (this);
675
676#ifdef Q_WS_X11
677 /* initialize the X keyboard subsystem */
678 initXKeyboard (this->x11Display());
679#endif
680
681 ::memset (mPressedKeys, 0, SIZEOF_ARRAY (mPressedKeys));
682
683 resize_hint_timer = new QTimer (this);
684 connect (resize_hint_timer, SIGNAL (timeout()),
685 this, SLOT (doResizeHint()));
686
687 /* setup rendering */
688
689 CDisplay display = mConsole.GetDisplay();
690 Assert (!display.isNull());
691
692 mFrameBuf = 0;
693
694 LogFlowFunc (("Rendering mode: %d\n", mode));
695
696 switch (mode)
697 {
698#if defined (VBOX_GUI_USE_QIMAGE)
699 case VBoxDefs::QImageMode:
700 mFrameBuf = new VBoxQImageFrameBuffer (this);
701 break;
702#endif
703#if defined (VBOX_GUI_USE_SDL)
704 case VBoxDefs::SDLMode:
705# ifdef Q_WS_X11
706 /* This is somehow necessary to prevent strange X11 warnings on
707 * i386 and segfaults on x86_64. */
708 XFlush(this->x11Display());
709# endif
710 mFrameBuf = new VBoxSDLFrameBuffer (this);
711 /*
712 * disable scrollbars because we cannot correctly draw in a
713 * scrolled window using SDL
714 */
715 horizontalScrollBar()->setEnabled (false);
716 verticalScrollBar()->setEnabled (false);
717 break;
718#endif
719#if defined (VBOX_GUI_USE_DDRAW)
720 case VBoxDefs::DDRAWMode:
721 mFrameBuf = new VBoxDDRAWFrameBuffer (this);
722 break;
723#endif
724#if defined (VBOX_GUI_USE_QUARTZ2D)
725 case VBoxDefs::Quartz2DMode:
726 mFrameBuf = new VBoxQuartz2DFrameBuffer (this);
727 break;
728#endif
729 default:
730 AssertReleaseMsgFailed (("Render mode must be valid: %d\n", mode));
731 LogRel (("Invalid render mode: %d\n", mode));
732 qApp->exit (1);
733 break;
734 }
735
736#if defined (VBOX_GUI_USE_DDRAW)
737 if (!mFrameBuf || mFrameBuf->address() == NULL)
738 {
739 if (mFrameBuf)
740 delete mFrameBuf;
741 mode = VBoxDefs::QImageMode;
742 mFrameBuf = new VBoxQImageFrameBuffer (this);
743 }
744#endif
745
746 if (mFrameBuf)
747 {
748 mFrameBuf->AddRef();
749 display.RegisterExternalFramebuffer (CFramebuffer (mFrameBuf));
750 }
751
752 /* setup the callback */
753 mCallback = CConsoleCallback (new VBoxConsoleCallback (this));
754 mConsole.RegisterCallback (mCallback);
755 AssertWrapperOk (mConsole);
756
757 viewport()->setEraseColor (black);
758
759 setSizePolicy (QSizePolicy (QSizePolicy::Maximum, QSizePolicy::Maximum));
760 setMaximumSize (sizeHint());
761
762 setFocusPolicy (WheelFocus);
763
764 /* Remember the desktop geometry and register for geometry change
765 events for telling the guest about video modes we like. */
766
767 QString desktopGeometry = vboxGlobal().settings()
768 .publicProperty ("GUI/MaxGuestResolution");
769 if ((desktopGeometry == QString::null) ||
770 (desktopGeometry == "auto"))
771 setDesktopGeometry (DesktopGeo_Automatic, 0, 0);
772 else if (desktopGeometry == "any")
773 setDesktopGeometry (DesktopGeo_Any, 0, 0);
774 else
775 {
776 int width = desktopGeometry.section (',', 0, 0).toInt();
777 int height = desktopGeometry.section (',', 1, 1).toInt();
778 setDesktopGeometry (DesktopGeo_Fixed, width, height);
779 }
780 connect (QApplication::desktop(), SIGNAL (resized (int)),
781 this, SLOT (doResizeDesktop (int)));
782
783#if defined (VBOX_GUI_DEBUG) && defined (VBOX_GUI_FRAMEBUF_STAT)
784 VMCPUTimer::calibrate (200);
785#endif
786
787#if defined (Q_WS_WIN)
788 gView = this;
789#endif
790
791#if defined (Q_WS_PM)
792 bool ok = VBoxHlpInstallKbdHook (0, winId(), UM_PREACCEL_CHAR);
793 Assert (ok);
794 NOREF (ok);
795#endif
796
797#ifdef Q_WS_MAC
798 DarwinCursorClearHandle (&mDarwinCursor);
799#endif
800}
801
802VBoxConsoleView::~VBoxConsoleView()
803{
804#if defined (Q_WS_PM)
805 bool ok = VBoxHlpUninstallKbdHook (0, winId(), UM_PREACCEL_CHAR);
806 Assert (ok);
807 NOREF (ok);
808#endif
809
810#if defined (Q_WS_WIN)
811 if (gKbdHook)
812 UnhookWindowsHookEx (gKbdHook);
813 gView = 0;
814 if (mAlphaCursor)
815 DestroyIcon (mAlphaCursor);
816#endif
817
818 if (mFrameBuf)
819 {
820 /* detach our framebuffer from Display */
821 CDisplay display = mConsole.GetDisplay();
822 Assert (!display.isNull());
823 display.SetupInternalFramebuffer (0);
824 /* release the reference */
825 mFrameBuf->Release();
826 }
827
828 mConsole.UnregisterCallback (mCallback);
829
830#ifdef Q_WS_MAC
831 CGImageRelease (mVirtualBoxLogo);
832#endif
833}
834
835//
836// Public members
837/////////////////////////////////////////////////////////////////////////////
838
839QSize VBoxConsoleView::sizeHint() const
840{
841 return QSize (mFrameBuf->width() + frameWidth() * 2,
842 mFrameBuf->height() + frameWidth() * 2);
843}
844
845/**
846 * Attaches this console view to the managed virtual machine.
847 *
848 * @note This method is not really necessary these days -- the only place where
849 * it gets called is VBoxConsole::openView(), right after powering the
850 * VM up. We leave it as is just in case attaching/detaching will become
851 * necessary some day (there are useful attached checks everywhere in the
852 * code).
853 */
854void VBoxConsoleView::attach()
855{
856 if (!mAttached)
857 {
858 mAttached = true;
859 }
860}
861
862/**
863 * Detaches this console view from the VM. Must be called to indicate
864 * that the virtual machine managed by this instance will be no more valid
865 * after this call.
866 *
867 * @note This method is not really necessary these days -- the only place where
868 * it gets called is VBoxConsole::closeView(), when the VM is powered
869 * down, before deleting VBoxConsoleView. We leave it as is just in case
870 * attaching/detaching will become necessary some day (there are useful
871 * attached checks everywhere in the code).
872 */
873void VBoxConsoleView::detach()
874{
875 if (mAttached)
876 {
877 /* reuse the focus event handler to uncapture everything */
878 focusEvent (false);
879 mAttached = false;
880 }
881}
882
883/**
884 * Resizes the toplevel widget to fit the console view w/o scrollbars.
885 * If adjustPosition is true and such resize is not possible (because the
886 * console view size is lagrer then the available screen space) the toplevel
887 * widget is resized and moved to become as large as possible while staying
888 * fully visible.
889 */
890void VBoxConsoleView::normalizeGeometry (bool adjustPosition /* = false */)
891{
892 /* Make no normalizeGeometry in case we are in manual resize
893 * mode or main window is maximized */
894 if (mMainWnd->isMaximized() || mMainWnd->isFullScreen())
895 return;
896
897 QWidget *tlw = topLevelWidget();
898
899 /* calculate client window offsets */
900 QRect fr = tlw->frameGeometry();
901 QRect r = tlw->geometry();
902 int dl = r.left() - fr.left();
903 int dt = r.top() - fr.top();
904 int dr = fr.right() - r.right();
905 int db = fr.bottom() - r.bottom();
906
907 /* get the best size w/o scroll bars */
908 QSize s = tlw->sizeHint();
909
910 /* resize the frame to fit the contents */
911 s -= tlw->size();
912 fr.rRight() += s.width();
913 fr.rBottom() += s.height();
914
915 if (adjustPosition)
916 {
917 QRect ar = QApplication::desktop()->availableGeometry (tlw->pos());
918 fr = VBoxGlobal::normalizeGeometry (
919 fr, ar, mode != VBoxDefs::SDLMode /* canResize */);
920 }
921
922#if 0
923 /* center the frame on the desktop */
924 fr.moveCenter (ar.center());
925#endif
926
927 /* finally, set the frame geometry */
928 tlw->setGeometry (fr.left() + dl, fr.top() + dt,
929 fr.width() - dl - dr, fr.height() - dt - db);
930}
931
932/**
933 * Pauses or resumes the VM execution.
934 */
935bool VBoxConsoleView::pause (bool on)
936{
937 /* QAction::setOn() emits the toggled() signal, so avoid recursion when
938 * QAction::setOn() is called from VBoxConsoleWnd::updateMachineState() */
939 if (isPaused() == on)
940 return true;
941
942 if (on)
943 mConsole.Pause();
944 else
945 mConsole.Resume();
946
947 bool ok = mConsole.isOk();
948 if (!ok)
949 {
950 if (on)
951 vboxProblem().cannotPauseMachine (mConsole);
952 else
953 vboxProblem().cannotResumeMachine (mConsole);
954 }
955
956 return ok;
957}
958
959/**
960 * Temporarily disables the mouse integration (or enables it back).
961 */
962void VBoxConsoleView::setMouseIntegrationEnabled (bool enabled)
963{
964 if (mMouseIntegration == enabled)
965 return;
966
967 if (mMouseAbsolute)
968 captureMouse (!enabled, false);
969
970 /* Hiding host cursor in case we are entering mouse integration
971 * mode until it's shape is set to the guest cursor shape in
972 * OnMousePointerShapeChange event handler.
973 *
974 * This is necessary to avoid double-cursor issue when both the
975 * guest and the host cursors are displayed in one place one-above-one.
976 *
977 * This is a workaround because the correct decision is to notify
978 * the Guest Additions about we are entering the mouse integration
979 * mode. The GuestOS should hide it's cursor to allow using of
980 * host cursor for the guest's manipulation.
981 *
982 * This notification is not possible right now due to there is
983 * no the required API. */
984 if (enabled)
985 viewport()->setCursor (QCursor (BlankCursor));
986
987 mMouseIntegration = enabled;
988
989 emitMouseStateChanged();
990}
991
992void VBoxConsoleView::setAutoresizeGuest (bool on)
993{
994 if (mAutoresizeGuest != on)
995 {
996 mAutoresizeGuest = on;
997
998 maybeRestrictMinimumSize();
999
1000 if (mGuestSupportsGraphics && mAutoresizeGuest)
1001 doResizeHint();
1002 }
1003}
1004
1005/**
1006 * This method is called by VBoxConsoleWnd after it does everything necessary
1007 * on its side to go to or from fullscreen, but before it is shown.
1008 */
1009void VBoxConsoleView::onFullscreenChange (bool /* on */)
1010{
1011 /* Nothing to do here so far */
1012}
1013
1014/**
1015 * Notify the console scroll-view about the console-window is opened.
1016 */
1017void VBoxConsoleView::onViewOpened()
1018{
1019 /* Variable mIgnoreMainwndResize was initially "true" to ignore QT
1020 * initial resize event in case of auto-resize feature is on.
1021 * Currently, initial resize event is already processed, so we set
1022 * mIgnoreMainwndResize to "false" to process all further resize
1023 * events as user-initiated window resize events. */
1024 mIgnoreMainwndResize = false;
1025}
1026
1027//
1028// Protected Events
1029/////////////////////////////////////////////////////////////////////////////
1030
1031bool VBoxConsoleView::event (QEvent *e)
1032{
1033 if (mAttached)
1034 {
1035 switch (e->type())
1036 {
1037 case QEvent::FocusIn:
1038 {
1039 if (isRunning())
1040 focusEvent (true);
1041 break;
1042 }
1043 case QEvent::FocusOut:
1044 {
1045 if (isRunning())
1046 focusEvent (false);
1047 else
1048 {
1049 /* release the host key and all other pressed keys too even
1050 * when paused (otherwise, we will get stuck keys in the
1051 * guest when doing sendChangedKeyStates() on resume because
1052 * key presses were already recorded in mPressedKeys but key
1053 * releases will most likely not reach us but the new focus
1054 * window instead). */
1055 releaseAllPressedKeys (true /* aReleaseHostKey */);
1056 }
1057 break;
1058 }
1059
1060 case VBoxDefs::ResizeEventType:
1061 {
1062 bool oldIgnoreMainwndResize = mIgnoreMainwndResize;
1063 mIgnoreMainwndResize = true;
1064
1065 VBoxResizeEvent *re = (VBoxResizeEvent *) e;
1066 LogFlow (("VBoxDefs::ResizeEventType: %d x %d x %d bpp\n",
1067 re->width(), re->height(), re->bitsPerPixel()));
1068
1069 /* do frame buffer dependent resize */
1070 mFrameBuf->resizeEvent (re);
1071 viewport()->unsetCursor();
1072
1073 /* This event appears in case of guest video was changed
1074 * for somehow even without video resolution change.
1075 * In this last case the host VM window will not be resized
1076 * according this event and the host mouse cursor which was
1077 * unset to default here will not be hidden in capture state.
1078 * So it is necessary to perform updateMouseClipping() for
1079 * the guest resize event if the mouse cursor was captured. */
1080 if (mMouseCaptured)
1081 updateMouseClipping();
1082
1083 /* apply maximum size restriction */
1084 setMaximumSize (sizeHint());
1085
1086 maybeRestrictMinimumSize();
1087
1088 /* resize the guest canvas */
1089 resizeContents (re->width(), re->height());
1090 /* let our toplevel widget calculate its sizeHint properly */
1091 QApplication::sendPostedEvents (0, QEvent::LayoutHint);
1092
1093 normalizeGeometry (true /* adjustPosition */);
1094
1095 /* report to the VM thread that we finished resizing */
1096 mConsole.GetDisplay().ResizeCompleted (0);
1097
1098 mIgnoreMainwndResize = oldIgnoreMainwndResize;
1099
1100 /* update geometry after entering fullscreen | seamless */
1101 if (mMainWnd->isTrueFullscreen() || mMainWnd->isTrueSeamless())
1102 updateGeometry();
1103
1104 /* make sure that all posted signals are processed */
1105 qApp->processEvents();
1106
1107 /* emit a signal about guest was resized */
1108 emit resizeHintDone();
1109
1110 return true;
1111 }
1112
1113#if !defined (Q_WS_WIN) && !defined (Q_WS_PM)
1114 /* see VBox[QImage|SDL]FrameBuffer::NotifyUpdate(). */
1115 case VBoxDefs::RepaintEventType:
1116 {
1117 VBoxRepaintEvent *re = (VBoxRepaintEvent *) e;
1118 viewport()->repaint (re->x() - contentsX(),
1119 re->y() - contentsY(),
1120 re->width(), re->height(), false);
1121 /* mConsole.GetDisplay().UpdateCompleted(); - the event was acked already */
1122 return true;
1123 }
1124#endif
1125
1126 case VBoxDefs::SetRegionEventType:
1127 {
1128 VBoxSetRegionEvent *sre = (VBoxSetRegionEvent*) e;
1129 if (mMainWnd->isTrueSeamless() &&
1130 sre->region() != mLastVisibleRegion)
1131 {
1132 mLastVisibleRegion = sre->region();
1133 mMainWnd->setMask (sre->region());
1134 }
1135 else if (!mLastVisibleRegion.isNull() &&
1136 !mMainWnd->isTrueSeamless())
1137 mLastVisibleRegion = QRegion();
1138 return true;
1139 }
1140
1141 case VBoxDefs::MousePointerChangeEventType:
1142 {
1143 MousePointerChangeEvent *me = (MousePointerChangeEvent *) e;
1144 /* change cursor shape only when mouse integration is
1145 * supported (change mouse shape type event may arrive after
1146 * mouse capability change that disables integration */
1147 if (mMouseAbsolute)
1148 setPointerShape (me);
1149 return true;
1150 }
1151 case VBoxDefs::MouseCapabilityEventType:
1152 {
1153 MouseCapabilityEvent *me = (MouseCapabilityEvent *) e;
1154 if (mMouseAbsolute != me->supportsAbsolute())
1155 {
1156 mMouseAbsolute = me->supportsAbsolute();
1157 /* correct the mouse capture state and reset the cursor
1158 * to the default shape if necessary */
1159 if (mMouseAbsolute)
1160 {
1161 CMouse mouse = mConsole.GetMouse();
1162 mouse.PutMouseEventAbsolute (-1, -1, 0, 0);
1163 captureMouse (false, false);
1164 }
1165 else
1166 viewport()->unsetCursor();
1167 emitMouseStateChanged();
1168 vboxProblem().remindAboutMouseIntegration (mMouseAbsolute);
1169 }
1170 if (me->needsHostCursor())
1171 mMainWnd->setMouseIntegrationLocked (false);
1172 return true;
1173 }
1174
1175 case VBoxDefs::ModifierKeyChangeEventType:
1176 {
1177 ModifierKeyChangeEvent *me = (ModifierKeyChangeEvent* )e;
1178 if (me->numLock() != mNumLock)
1179 muNumLockAdaptionCnt = 2;
1180 if (me->capsLock() != mCapsLock)
1181 muCapsLockAdaptionCnt = 2;
1182 mNumLock = me->numLock();
1183 mCapsLock = me->capsLock();
1184 mScrollLock = me->scrollLock();
1185 return true;
1186 }
1187
1188 case VBoxDefs::MachineStateChangeEventType:
1189 {
1190 StateChangeEvent *me = (StateChangeEvent *) e;
1191 LogFlowFunc (("MachineStateChangeEventType: state=%d\n",
1192 me->machineState()));
1193 onStateChange (me->machineState());
1194 emit machineStateChanged (me->machineState());
1195 return true;
1196 }
1197
1198 case VBoxDefs::AdditionsStateChangeEventType:
1199 {
1200 GuestAdditionsEvent *ge = (GuestAdditionsEvent *) e;
1201 LogFlowFunc (("AdditionsStateChangeEventType\n"));
1202
1203 mGuestSupportsGraphics = ge->supportsGraphics();
1204
1205 maybeRestrictMinimumSize();
1206
1207 emit additionsStateChanged (ge->additionVersion(),
1208 ge->additionActive(),
1209 ge->supportsSeamless(),
1210 ge->supportsGraphics());
1211 return true;
1212 }
1213
1214 case VBoxDefs::MediaChangeEventType:
1215 {
1216 MediaChangeEvent *mce = (MediaChangeEvent *) e;
1217 LogFlowFunc (("MediaChangeEvent\n"));
1218
1219 emit mediaChanged (mce->diskType());
1220 return true;
1221 }
1222
1223 case VBoxDefs::ActivateMenuEventType:
1224 {
1225 ActivateMenuEvent *ame = (ActivateMenuEvent *) e;
1226 ame->menuData()->activateItemAt (ame->index());
1227
1228 /*
1229 * The main window and its children can be destroyed at this
1230 * point (if, for example, the activated menu item closes the
1231 * main window). Detect this situation to prevent calls to
1232 * destroyed widgets.
1233 */
1234 QWidgetList *list = QApplication::topLevelWidgets();
1235 bool destroyed = list->find (mMainWnd) < 0;
1236 delete list;
1237 if (!destroyed && mMainWnd->statusBar())
1238 mMainWnd->statusBar()->clear();
1239
1240 return true;
1241 }
1242
1243 case VBoxDefs::NetworkAdapterChangeEventType:
1244 {
1245 /* no specific adapter information stored in this
1246 * event is currently used */
1247 emit networkStateChange();
1248 return true;
1249 }
1250
1251 case VBoxDefs::USBCtlStateChangeEventType:
1252 {
1253 emit usbStateChange();
1254 return true;
1255 }
1256
1257 case VBoxDefs::USBDeviceStateChangeEventType:
1258 {
1259 USBDeviceStateChangeEvent *ue = (USBDeviceStateChangeEvent *)e;
1260
1261 bool success = ue->error().isNull();
1262
1263 if (!success)
1264 {
1265 if (ue->attached())
1266 vboxProblem().cannotAttachUSBDevice (
1267 mConsole,
1268 vboxGlobal().details (ue->device()), ue->error());
1269 else
1270 vboxProblem().cannotDetachUSBDevice (
1271 mConsole,
1272 vboxGlobal().details (ue->device()), ue->error());
1273 }
1274
1275 emit usbStateChange();
1276
1277 return true;
1278 }
1279
1280 case VBoxDefs::SharedFolderChangeEventType:
1281 {
1282 emit sharedFoldersChanged();
1283 return true;
1284 }
1285
1286 case VBoxDefs::RuntimeErrorEventType:
1287 {
1288 RuntimeErrorEvent *ee = (RuntimeErrorEvent *) e;
1289 vboxProblem().showRuntimeError (mConsole, ee->fatal(),
1290 ee->errorID(), ee->message());
1291 return true;
1292 }
1293
1294 case QEvent::KeyPress:
1295 case QEvent::KeyRelease:
1296 {
1297 QKeyEvent *ke = (QKeyEvent *) e;
1298
1299#ifdef Q_WS_PM
1300 /// @todo temporary solution to send Alt+Tab and friends to
1301 // the guest. The proper solution is to write a keyboard
1302 // driver that will steal these combos from the host (it's
1303 // impossible to do so using hooks on OS/2).
1304
1305 if (mIsHostkeyPressed)
1306 {
1307 bool pressed = e->type() == QEvent::KeyPress;
1308 CKeyboard keyboard = mConsole.GetKeyboard();
1309
1310 /* whether the host key is Shift so that it will modify
1311 * the hot key values? Note that we don't distinguish
1312 * between left and right shift here (too much hassle) */
1313 const bool kShift = (gs.hostKey() == VK_SHIFT ||
1314 gs.hostKey() == VK_LSHIFT) &&
1315 (ke->state() & ShiftButton);
1316 /* define hot keys according to the Shift state */
1317 const int kAltTab = kShift ? Key_Exclam : Key_1;
1318 const int kAltShiftTab = kShift ? Key_At : Key_2;
1319 const int kCtrlEsc = kShift ? Key_AsciiTilde : Key_QuoteLeft;
1320
1321 /* Simulate Alt+Tab on Host+1 and Alt+Shift+Tab on Host+2 */
1322 if (ke->key() == kAltTab || ke->key() == kAltShiftTab)
1323 {
1324 if (pressed)
1325 {
1326 /* Send the Alt press to the guest */
1327 if (!(mPressedKeysCopy [0x38] & IsKeyPressed))
1328 {
1329 /* store the press in *Copy to have it automatically
1330 * released when the Host key is released */
1331 mPressedKeysCopy [0x38] |= IsKeyPressed;
1332 keyboard.PutScancode (0x38);
1333 }
1334
1335 /* Make sure Shift is pressed if it's Key_2 and released
1336 * if it's Key_1 */
1337 if (ke->key() == kAltTab &&
1338 (mPressedKeysCopy [0x2A] & IsKeyPressed))
1339 {
1340 mPressedKeysCopy [0x2A] &= ~IsKeyPressed;
1341 keyboard.PutScancode (0xAA);
1342 }
1343 else
1344 if (ke->key() == kAltShiftTab &&
1345 !(mPressedKeysCopy [0x2A] & IsKeyPressed))
1346 {
1347 mPressedKeysCopy [0x2A] |= IsKeyPressed;
1348 keyboard.PutScancode (0x2A);
1349 }
1350 }
1351
1352 keyboard.PutScancode (pressed ? 0x0F : 0x8F);
1353
1354 ke->accept();
1355 return true;
1356 }
1357
1358 /* Simulate Ctrl+Esc on Host+Tilde */
1359 if (ke->key() == kCtrlEsc)
1360 {
1361 /* Send the Ctrl press to the guest */
1362 if (pressed && !(mPressedKeysCopy [0x1d] & IsKeyPressed))
1363 {
1364 /* store the press in *Copy to have it automatically
1365 * released when the Host key is released */
1366 mPressedKeysCopy [0x1d] |= IsKeyPressed;
1367 keyboard.PutScancode (0x1d);
1368 }
1369
1370 keyboard.PutScancode (pressed ? 0x01 : 0x81);
1371
1372 ke->accept();
1373 return true;
1374 }
1375 }
1376
1377 /* fall through to normal processing */
1378
1379#endif /* Q_WS_PM */
1380
1381 if (mIsHostkeyPressed && e->type() == QEvent::KeyPress)
1382 {
1383 if (ke->key() >= Key_F1 && ke->key() <= Key_F12)
1384 {
1385 LONG combo [6];
1386 combo [0] = 0x1d; /* Ctrl down */
1387 combo [1] = 0x38; /* Alt down */
1388 combo [4] = 0xb8; /* Alt up */
1389 combo [5] = 0x9d; /* Ctrl up */
1390 if (ke->key() >= Key_F1 && ke->key() <= Key_F10)
1391 {
1392 combo [2] = 0x3b + (ke->key() - Key_F1); /* F1-F10 down */
1393 combo [3] = 0xbb + (ke->key() - Key_F1); /* F1-F10 up */
1394 }
1395 /* some scan slice */
1396 else if (ke->key() >= Key_F11 && ke->key() <= Key_F12)
1397 {
1398 combo [2] = 0x57 + (ke->key() - Key_F11); /* F11-F12 down */
1399 combo [3] = 0xd7 + (ke->key() - Key_F11); /* F11-F12 up */
1400 }
1401 else
1402 Assert (0);
1403
1404 CKeyboard keyboard = mConsole.GetKeyboard();
1405 keyboard.PutScancodes (combo, 6);
1406 }
1407 else if (ke->key() == Key_Home)
1408 {
1409 /* activate the main menu */
1410 if (mMainWnd->isTrueSeamless() || mMainWnd->isTrueFullscreen())
1411 mMainWnd->popupMainMenu (mMouseCaptured);
1412 else
1413 mMainWnd->menuBar()->setFocus();
1414 }
1415 else
1416 {
1417 /* process hot keys not processed in keyEvent()
1418 * (as in case of non-alphanumeric keys) */
1419 processHotKey (QKeySequence (ke->key()),
1420 mMainWnd->menuBar());
1421 }
1422 }
1423 else if (!mIsHostkeyPressed && e->type() == QEvent::KeyRelease)
1424 {
1425 /* Show a possible warning on key release which seems to
1426 * be more expected by the end user */
1427
1428 if (isPaused())
1429 {
1430 /* if the reminder is disabled we pass the event to
1431 * Qt to enable normal keyboard functionality
1432 * (for example, menu access with Alt+Letter) */
1433 if (!vboxProblem().remindAboutPausedVMInput())
1434 break;
1435 }
1436 }
1437
1438 ke->accept();
1439 return true;
1440 }
1441
1442#ifdef Q_WS_MAC
1443 /* posted OnShowWindow */
1444 case VBoxDefs::ShowWindowEventType:
1445 {
1446 /*
1447 * Dunno what Qt3 thinks a window that has minimized to the dock
1448 * should be - it is not hidden, neither is it minimized. OTOH it is
1449 * marked shown and visible, but not activated. This latter isn't of
1450 * much help though, since at this point nothing is marked activated.
1451 * I might have overlooked something, but I'm buggered what if I know
1452 * what. So, I'll just always show & activate the stupid window to
1453 * make it get out of the dock when the user wishes to show a VM.
1454 */
1455 topLevelWidget()->show();
1456 topLevelWidget()->setActiveWindow();
1457 return true;
1458 }
1459#endif
1460 default:
1461 break;
1462 }
1463 }
1464
1465 return QScrollView::event (e);
1466}
1467
1468bool VBoxConsoleView::eventFilter (QObject *watched, QEvent *e)
1469{
1470 if (mAttached && watched == viewport())
1471 {
1472 switch (e->type())
1473 {
1474 case QEvent::MouseMove:
1475 case QEvent::MouseButtonPress:
1476 case QEvent::MouseButtonDblClick:
1477 case QEvent::MouseButtonRelease:
1478 {
1479 QMouseEvent *me = (QMouseEvent *) e;
1480 if (mouseEvent (me->type(), me->pos(), me->globalPos(),
1481 me->button(), me->state(), me->stateAfter(),
1482 0, Horizontal))
1483 return true; /* stop further event handling */
1484 break;
1485 }
1486 case QEvent::Wheel:
1487 {
1488 QWheelEvent *we = (QWheelEvent *) e;
1489 if (mouseEvent (we->type(), we->pos(), we->globalPos(),
1490 NoButton, we->state(), we->state(),
1491 we->delta(), we->orientation()))
1492 return true; /* stop further event handling */
1493 break;
1494 }
1495 case QEvent::Resize:
1496 {
1497 if (mMouseCaptured)
1498 updateMouseClipping();
1499 }
1500 default:
1501 break;
1502 }
1503 }
1504 else if (watched == mMainWnd)
1505 {
1506 switch (e->type())
1507 {
1508#if defined (Q_WS_WIN32)
1509#if defined (VBOX_GUI_USE_DDRAW)
1510 case QEvent::Move:
1511 {
1512 /*
1513 * notification from our parent that it has moved. We need this
1514 * in order to possibly adjust the direct screen blitting.
1515 */
1516 if (mFrameBuf)
1517 mFrameBuf->moveEvent ((QMoveEvent *) e);
1518 break;
1519 }
1520#endif
1521 /*
1522 * install/uninstall low-level kbd hook on every
1523 * activation/deactivation to:
1524 * a) avoid excess hook calls when we're not active and
1525 * b) be always in front of any other possible hooks
1526 */
1527 case QEvent::WindowActivate:
1528 {
1529 gKbdHook = SetWindowsHookEx (WH_KEYBOARD_LL, lowLevelKeyboardProc,
1530 GetModuleHandle (NULL), 0);
1531 AssertMsg (gKbdHook, ("SetWindowsHookEx(): err=%d", GetLastError()));
1532 break;
1533 }
1534 case QEvent::WindowDeactivate:
1535 {
1536 if (gKbdHook)
1537 {
1538 UnhookWindowsHookEx (gKbdHook);
1539 gKbdHook = NULL;
1540 }
1541 break;
1542 }
1543#endif /* defined (Q_WS_WIN32) */
1544#if defined (Q_WS_MAC)
1545 /*
1546 * Install/remove the keyboard event handler.
1547 */
1548 case QEvent::WindowActivate:
1549 darwinGrabKeyboardEvents (true);
1550 break;
1551 case QEvent::WindowDeactivate:
1552 darwinGrabKeyboardEvents (false);
1553 break;
1554#endif /* defined (Q_WS_MAC) */
1555 case QEvent::Resize:
1556 {
1557 /* Set the "guest needs to resize" hint. This hint is acted upon
1558 * when (and only when) the autoresize property is "true". */
1559 mDoResize = mGuestSupportsGraphics || mMainWnd->isTrueFullscreen();
1560 if (!mIgnoreMainwndResize &&
1561 mGuestSupportsGraphics && mAutoresizeGuest)
1562 resize_hint_timer->start (300, TRUE);
1563 break;
1564 }
1565
1566 default:
1567 break;
1568 }
1569 }
1570 else if (watched == mMainWnd->menuBar())
1571 {
1572 /*
1573 * sometimes when we press ESC in the menu it brings the
1574 * focus away (Qt bug?) causing no widget to have a focus,
1575 * or holds the focus itself, instead of returning the focus
1576 * to the console window. here we fix this.
1577 */
1578 switch (e->type())
1579 {
1580 case QEvent::FocusOut:
1581 {
1582 if (qApp->focusWidget() == 0)
1583 setFocus();
1584 break;
1585 }
1586 case QEvent::KeyPress:
1587 {
1588 QKeyEvent *ke = (QKeyEvent *) e;
1589 if (ke->key() == Key_Escape && !(ke->state() & KeyButtonMask))
1590 if (mMainWnd->menuBar()->hasFocus())
1591 setFocus();
1592 break;
1593 }
1594 default:
1595 break;
1596 }
1597 }
1598
1599 return QScrollView::eventFilter (watched, e);
1600}
1601
1602#if defined(Q_WS_WIN32)
1603
1604/**
1605 * Low-level keyboard event handler,
1606 * @return
1607 * true to indicate that the message is processed and false otherwise
1608 */
1609bool VBoxConsoleView::winLowKeyboardEvent (UINT msg, const KBDLLHOOKSTRUCT &event)
1610{
1611#if 0
1612 LogFlow (("### vkCode=%08X, scanCode=%08X, flags=%08X, dwExtraInfo=%08X (mKbdCaptured=%d)\n",
1613 event.vkCode, event.scanCode, event.flags, event.dwExtraInfo, mKbdCaptured));
1614 char buf [256];
1615 sprintf (buf, "### vkCode=%08X, scanCode=%08X, flags=%08X, dwExtraInfo=%08X",
1616 event.vkCode, event.scanCode, event.flags, event.dwExtraInfo);
1617 mMainWnd->statusBar()->message (buf);
1618#endif
1619
1620 /* Sometimes it happens that Win inserts additional events on some key
1621 * press/release. For example, it prepends ALT_GR in German layout with
1622 * the VK_LCONTROL vkey with curious 0x21D scan code (seems to be necessary
1623 * to specially treat ALT_GR to enter additional chars to regular apps).
1624 * These events are definitely unwanted in VM, so filter them out. */
1625 if (hasFocus() && (event.scanCode & ~0xFF))
1626 return true;
1627
1628 if (!mKbdCaptured)
1629 return false;
1630
1631 /* it's possible that a key has been pressed while the keyboard was not
1632 * captured, but is being released under the capture. Detect this situation
1633 * and return false to let Windows process the message normally and update
1634 * its key state table (to avoid the stuck key effect). */
1635 uint8_t what_pressed = (event.flags & 0x01) && (event.vkCode != VK_RSHIFT)
1636 ? IsExtKeyPressed
1637 : IsKeyPressed;
1638 if ((event.flags & 0x80) /* released */ &&
1639 ((event.vkCode == gs.hostKey() && !hostkey_in_capture) ||
1640 (mPressedKeys [event.scanCode] & (IsKbdCaptured | what_pressed)) == what_pressed))
1641 return false;
1642
1643 MSG message;
1644 message.hwnd = winId();
1645 message.message = msg;
1646 message.wParam = event.vkCode;
1647 message.lParam =
1648 1 |
1649 (event.scanCode & 0xFF) << 16 |
1650 (event.flags & 0xFF) << 24;
1651
1652 /* Windows sets here the extended bit when the Right Shift key is pressed,
1653 * which is totally wrong. Undo it. */
1654 if (event.vkCode == VK_RSHIFT)
1655 message.lParam &= ~0x1000000;
1656
1657 /* we suppose here that this hook is always called on the main GUI thread */
1658 return winEvent (&message);
1659}
1660
1661/**
1662 * Get Win32 messages before they are passed to Qt. This allows us to get
1663 * the keyboard events directly and bypass the harmful Qt translation. A
1664 * return value of @c true indicates to Qt that the event has been handled.
1665 */
1666bool VBoxConsoleView::winEvent (MSG *msg)
1667{
1668 if (!mAttached || ! (
1669 msg->message == WM_KEYDOWN || msg->message == WM_SYSKEYDOWN ||
1670 msg->message == WM_KEYUP || msg->message == WM_SYSKEYUP
1671 ))
1672 return false;
1673
1674 /* check for the special flag possibly set at the end of this function */
1675 if (msg->lParam & (0x1 << 25))
1676 {
1677 msg->lParam &= ~(0x1 << 25);
1678 return false;
1679 }
1680
1681#if 0
1682 char buf [256];
1683 sprintf (buf, "WM_%04X: vk=%04X rep=%05d scan=%02X ext=%01d rzv=%01X ctx=%01d prev=%01d tran=%01d",
1684 msg->message, msg->wParam,
1685 (msg->lParam & 0xFFFF),
1686 ((msg->lParam >> 16) & 0xFF),
1687 ((msg->lParam >> 24) & 0x1),
1688 ((msg->lParam >> 25) & 0xF),
1689 ((msg->lParam >> 29) & 0x1),
1690 ((msg->lParam >> 30) & 0x1),
1691 ((msg->lParam >> 31) & 0x1));
1692 mMainWnd->statusBar()->message (buf);
1693 LogFlow (("%s\n", buf));
1694#endif
1695
1696 int scan = (msg->lParam >> 16) & 0x7F;
1697 /* scancodes 0x80 and 0x00 are ignored */
1698 if (!scan)
1699 return true;
1700
1701 int vkey = msg->wParam;
1702
1703 /* When one of the SHIFT keys is held and one of the cursor movement
1704 * keys is pressed, Windows duplicates SHIFT press/release messages,
1705 * but with the virtual key code set to 0xFF. These virtual keys are also
1706 * sent in some other situations (Pause, PrtScn, etc.). Ignore such
1707 * messages. */
1708 if (vkey == 0xFF)
1709 return true;
1710
1711 int flags = 0;
1712 if (msg->lParam & 0x1000000)
1713 flags |= KeyExtended;
1714 if (!(msg->lParam & 0x80000000))
1715 flags |= KeyPressed;
1716
1717 switch (vkey)
1718 {
1719 case VK_SHIFT:
1720 case VK_CONTROL:
1721 case VK_MENU:
1722 {
1723 /* overcome stupid Win32 modifier key generalization */
1724 int keyscan = scan;
1725 if (flags & KeyExtended)
1726 keyscan |= 0xE000;
1727 switch (keyscan)
1728 {
1729 case 0x002A: vkey = VK_LSHIFT; break;
1730 case 0x0036: vkey = VK_RSHIFT; break;
1731 case 0x001D: vkey = VK_LCONTROL; break;
1732 case 0xE01D: vkey = VK_RCONTROL; break;
1733 case 0x0038: vkey = VK_LMENU; break;
1734 case 0xE038: vkey = VK_RMENU; break;
1735 }
1736 break;
1737 }
1738 case VK_NUMLOCK:
1739 /* Win32 sets the extended bit for the NumLock key. Reset it. */
1740 flags &= ~KeyExtended;
1741 break;
1742 case VK_SNAPSHOT:
1743 flags |= KeyPrint;
1744 break;
1745 case VK_PAUSE:
1746 flags |= KeyPause;
1747 break;
1748 }
1749
1750 bool result = keyEvent (vkey, scan, flags);
1751 if (!result && mKbdCaptured)
1752 {
1753 /* keyEvent() returned that it didn't process the message, but since the
1754 * keyboard is captured, we don't want to pass it to Windows. We just want
1755 * to let Qt process the message (to handle non-alphanumeric <HOST>+key
1756 * shortcuts for example). So send it direcltly to the window with the
1757 * special flag in the reserved area of lParam (to avoid recursion). */
1758 ::SendMessage (msg->hwnd, msg->message,
1759 msg->wParam, msg->lParam | (0x1 << 25));
1760 return true;
1761 }
1762
1763 /* These special keys have to be handled by Windows as well to update the
1764 * internal modifier state and to enable/disable the keyboard LED */
1765 if (vkey == VK_NUMLOCK || vkey == VK_CAPITAL)
1766 return false;
1767
1768 return result;
1769}
1770
1771#elif defined (Q_WS_PM)
1772
1773/**
1774 * Get PM messages before they are passed to Qt. This allows us to get
1775 * the keyboard events directly and bypass the harmful Qt translation. A
1776 * return value of @c true indicates to Qt that the event has been handled.
1777 */
1778bool VBoxConsoleView::pmEvent (QMSG *aMsg)
1779{
1780 if (!mAttached)
1781 return false;
1782
1783 if (aMsg->msg == UM_PREACCEL_CHAR)
1784 {
1785 /* we are inside the input hook */
1786
1787 /* let the message go through the normal system pipeline */
1788 if (!mKbdCaptured)
1789 return false;
1790 }
1791
1792 if (aMsg->msg != WM_CHAR &&
1793 aMsg->msg != UM_PREACCEL_CHAR)
1794 return false;
1795
1796 /* check for the special flag possibly set at the end of this function */
1797 if (SHORT2FROMMP (aMsg->mp2) & 0x8000)
1798 {
1799 aMsg->mp2 = MPFROM2SHORT (SHORT1FROMMP (aMsg->mp2),
1800 SHORT2FROMMP (aMsg->mp2) & ~0x8000);
1801 return false;
1802 }
1803
1804#if 0
1805 {
1806 char buf [256];
1807 sprintf (buf, "*** %s: f=%04X rep=%03d scan=%02X ch=%04X vk=%04X",
1808 (aMsg->msg == WM_CHAR ? "WM_CHAR" : "UM_PREACCEL_CHAR"),
1809 SHORT1FROMMP (aMsg->mp1), CHAR3FROMMP (aMsg->mp1),
1810 CHAR4FROMMP (aMsg->mp1), SHORT1FROMMP (aMsg->mp2),
1811 SHORT2FROMMP (aMsg->mp2));
1812 mMainWnd->statusBar()->message (buf);
1813 LogFlow (("%s\n", buf));
1814 }
1815#endif
1816
1817 USHORT ch = SHORT1FROMMP (aMsg->mp2);
1818 USHORT f = SHORT1FROMMP (aMsg->mp1);
1819
1820 int scan = (unsigned int) CHAR4FROMMP (aMsg->mp1);
1821 if (!scan || scan > 0x7F)
1822 return true;
1823
1824 int vkey = QIHotKeyEdit::virtualKey (aMsg);
1825
1826 int flags = 0;
1827
1828 if ((ch & 0xFF) == 0xE0)
1829 {
1830 flags |= KeyExtended;
1831 scan = ch >> 8;
1832 }
1833 else if (scan == 0x5C && (ch & 0xFF) == '/')
1834 {
1835 /* this is the '/' key on the keypad */
1836 scan = 0x35;
1837 flags |= KeyExtended;
1838 }
1839 else
1840 {
1841 /* For some keys, the scan code passed in QMSG is a pseudo scan
1842 * code. We replace it with a real hardware scan code, according to
1843 * http://www.computer-engineering.org/ps2keyboard/scancodes1.html.
1844 * Also detect Pause and PrtScn and set flags. */
1845 switch (vkey)
1846 {
1847 case VK_ENTER: scan = 0x1C; flags |= KeyExtended; break;
1848 case VK_CTRL: scan = 0x1D; flags |= KeyExtended; break;
1849 case VK_ALTGRAF: scan = 0x38; flags |= KeyExtended; break;
1850 case VK_LWIN: scan = 0x5B; flags |= KeyExtended; break;
1851 case VK_RWIN: scan = 0x5C; flags |= KeyExtended; break;
1852 case VK_WINMENU: scan = 0x5D; flags |= KeyExtended; break;
1853 case VK_FORWARD: scan = 0x69; flags |= KeyExtended; break;
1854 case VK_BACKWARD: scan = 0x6A; flags |= KeyExtended; break;
1855#if 0
1856 /// @todo this would send 0xE0 0x46 0xE0 0xC6. It's not fully
1857 // clear what is more correct
1858 case VK_BREAK: scan = 0x46; flags |= KeyExtended; break;
1859#else
1860 case VK_BREAK: scan = 0; flags |= KeyPause; break;
1861#endif
1862 case VK_PAUSE: scan = 0; flags |= KeyPause; break;
1863 case VK_PRINTSCRN: scan = 0; flags |= KeyPrint; break;
1864 default:;
1865 }
1866 }
1867
1868 if (!(f & KC_KEYUP))
1869 flags |= KeyPressed;
1870
1871 bool result = keyEvent (vkey, scan, flags);
1872 if (!result && mKbdCaptured)
1873 {
1874 /* keyEvent() returned that it didn't process the message, but since the
1875 * keyboard is captured, we don't want to pass it to PM. We just want
1876 * to let Qt process the message (to handle non-alphanumeric <HOST>+key
1877 * shortcuts for example). So send it direcltly to the window with the
1878 * special flag in the reserved area of lParam (to avoid recursion). */
1879 ::WinSendMsg (aMsg->hwnd, WM_CHAR,
1880 aMsg->mp1,
1881 MPFROM2SHORT (SHORT1FROMMP (aMsg->mp2),
1882 SHORT2FROMMP (aMsg->mp2) | 0x8000));
1883 return true;
1884 }
1885 return result;
1886}
1887
1888#elif defined(Q_WS_X11)
1889
1890/**
1891 * This routine gets X11 events before they are processed by Qt. This is
1892 * used for our platform specific keyboard implementation. A return value
1893 * of TRUE indicates that the event has been processed by us.
1894 */
1895bool VBoxConsoleView::x11Event (XEvent *event)
1896{
1897 static WINEKEYBOARDINFO wineKeyboardInfo;
1898
1899 switch (event->type)
1900 {
1901 /* We have to handle XFocusOut right here as this event is not passed
1902 * to VBoxConsoleView::event(). Handling this event is important for
1903 * releasing the keyboard before the screen saver gets active. */
1904 case XFocusOut:
1905 case XFocusIn:
1906 if (isRunning())
1907 focusEvent (event->type == XFocusIn);
1908 return false;
1909 case XKeyPress:
1910 case XKeyRelease:
1911 if (mAttached)
1912 break;
1913 /* else fall through */
1914 /// @todo (AH) later, we might want to handle these as well
1915 case KeymapNotify:
1916 case MappingNotify:
1917 default:
1918 return false; /* pass the event to Qt */
1919 }
1920
1921 /* perform the mega-complex translation using the wine algorithms */
1922 handleXKeyEvent (this->x11Display(), event, &wineKeyboardInfo);
1923
1924#if 0
1925 char buf [256];
1926 sprintf (buf, "pr=%d kc=%08X st=%08X fl=%08lX scan=%04X",
1927 event->type == XKeyPress ? 1 : 0, event->xkey.keycode,
1928 event->xkey.state, wineKeyboardInfo.dwFlags, wineKeyboardInfo.wScan);
1929 mMainWnd->statusBar()->message (buf);
1930 LogFlow (("### %s\n", buf));
1931#endif
1932
1933 int scan = wineKeyboardInfo.wScan & 0x7F;
1934 // scancodes 0x00 (no valid translation) and 0x80 are ignored
1935 if (!scan)
1936 return true;
1937
1938 KeySym ks = ::XKeycodeToKeysym (event->xkey.display, event->xkey.keycode, 0);
1939
1940 int flags = 0;
1941 if (wineKeyboardInfo.dwFlags & 0x0001)
1942 flags |= KeyExtended;
1943 if (event->type == XKeyPress)
1944 flags |= KeyPressed;
1945
1946 switch (ks)
1947 {
1948 case XK_Num_Lock:
1949 // Wine sets the extended bit for the NumLock key. Reset it.
1950 flags &= ~KeyExtended;
1951 break;
1952 case XK_Print:
1953 flags |= KeyPrint;
1954 break;
1955 case XK_Pause:
1956 flags |= KeyPause;
1957 break;
1958 }
1959
1960 return keyEvent (ks, scan, flags);
1961}
1962
1963#elif defined (Q_WS_MAC)
1964
1965/**
1966 * Invoked by VBoxConsoleView::darwinEventHandlerProc / VBoxConsoleView::macEventFilter when
1967 * it receives a raw keyboard event.
1968 *
1969 * @param inEvent The keyboard event.
1970 *
1971 * @return true if the key was processed, false if it wasn't processed and should be passed on.
1972 */
1973bool VBoxConsoleView::darwinKeyboardEvent (EventRef inEvent)
1974{
1975 bool ret = false;
1976 UInt32 EventKind = ::GetEventKind (inEvent);
1977 if (EventKind != kEventRawKeyModifiersChanged)
1978 {
1979 /* convert keycode to set 1 scan code. */
1980 UInt32 keyCode = ~0U;
1981 ::GetEventParameter (inEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof (keyCode), NULL, &keyCode);
1982 unsigned scanCode = ::DarwinKeycodeToSet1Scancode (keyCode);
1983 if (scanCode)
1984 {
1985 /* calc flags. */
1986 int flags = 0;
1987 if (EventKind != kEventRawKeyUp)
1988 flags |= KeyPressed;
1989 if (scanCode & VBOXKEY_EXTENDED)
1990 flags |= KeyExtended;
1991 /** @todo KeyPause, KeyPrint. */
1992 scanCode &= VBOXKEY_SCANCODE_MASK;
1993
1994 /* get the unicode string (if present). */
1995 AssertCompileSize (wchar_t, 2);
1996 AssertCompileSize (UniChar, 2);
1997 UInt32 cbWritten = 0;
1998 wchar_t ucs[8];
1999 if (::GetEventParameter (inEvent, kEventParamKeyUnicodes, typeUnicodeText, NULL,
2000 sizeof (ucs), &cbWritten, &ucs[0]) != 0)
2001 cbWritten = 0;
2002 ucs[cbWritten / sizeof(wchar_t)] = 0; /* The api doesn't terminate it. */
2003
2004 ret = keyEvent (keyCode, scanCode, flags, ucs[0] ? ucs : NULL);
2005 }
2006 }
2007 else
2008 {
2009 /* May contain multiple modifier changes, kind of annoying. */
2010 UInt32 newMask = 0;
2011 ::GetEventParameter (inEvent, kEventParamKeyModifiers, typeUInt32, NULL,
2012 sizeof (newMask), NULL, &newMask);
2013 newMask = ::DarwinAdjustModifierMask (newMask);
2014 UInt32 changed = newMask ^ mDarwinKeyModifiers;
2015 if (changed)
2016 {
2017 for (UInt32 bit = 0; bit < 32; bit++)
2018 {
2019 if (!(changed & (1 << bit)))
2020 continue;
2021 unsigned scanCode = ::DarwinModifierMaskToSet1Scancode (1 << bit);
2022 if (!scanCode)
2023 continue;
2024 unsigned keyCode = ::DarwinModifierMaskToDarwinKeycode (1 << bit);
2025 Assert (keyCode);
2026
2027 if (!(scanCode & VBOXKEY_LOCK))
2028 {
2029 unsigned flags = (newMask & (1 << bit)) ? KeyPressed : 0;
2030 if (scanCode & VBOXKEY_EXTENDED)
2031 flags |= KeyExtended;
2032 scanCode &= VBOXKEY_SCANCODE_MASK;
2033 ret |= keyEvent (keyCode, scanCode & 0xff, flags);
2034 }
2035 else
2036 {
2037 unsigned flags = 0;
2038 if (scanCode & VBOXKEY_EXTENDED)
2039 flags |= KeyExtended;
2040 scanCode &= VBOXKEY_SCANCODE_MASK;
2041 keyEvent (keyCode, scanCode, flags | KeyPressed);
2042 keyEvent (keyCode, scanCode, flags);
2043 }
2044 }
2045 }
2046
2047 mDarwinKeyModifiers = newMask;
2048
2049 /* Always return true here because we'll otherwise getting a Qt event
2050 we don't want and that will only cause the Pause warning to pop up. */
2051 ret = true;
2052 }
2053
2054 return ret;
2055}
2056
2057
2058/**
2059 * Installs or removes the keyboard event handler.
2060 *
2061 * @param fGrab True if we're to grab the events, false if we're not to.
2062 */
2063void VBoxConsoleView::darwinGrabKeyboardEvents (bool fGrab)
2064{
2065 if (fGrab)
2066 {
2067 ::SetMouseCoalescingEnabled (false, NULL); //??
2068 ::CGSetLocalEventsSuppressionInterval (0.0); //??
2069
2070#ifndef VBOX_WITH_HACKED_QT
2071
2072 EventTypeSpec eventTypes[6];
2073 eventTypes[0].eventClass = kEventClassKeyboard;
2074 eventTypes[0].eventKind = kEventRawKeyDown;
2075 eventTypes[1].eventClass = kEventClassKeyboard;
2076 eventTypes[1].eventKind = kEventRawKeyUp;
2077 eventTypes[2].eventClass = kEventClassKeyboard;
2078 eventTypes[2].eventKind = kEventRawKeyRepeat;
2079 eventTypes[3].eventClass = kEventClassKeyboard;
2080 eventTypes[3].eventKind = kEventRawKeyModifiersChanged;
2081 /* For ignorning Command-H and Command-Q which aren't affected by the
2082 * global hotkey stuff (doesn't work well): */
2083 eventTypes[4].eventClass = kEventClassCommand;
2084 eventTypes[4].eventKind = kEventCommandProcess;
2085 eventTypes[5].eventClass = kEventClassCommand;
2086 eventTypes[5].eventKind = kEventCommandUpdateStatus;
2087
2088 EventHandlerUPP eventHandler = ::NewEventHandlerUPP (VBoxConsoleView::darwinEventHandlerProc);
2089
2090 mDarwinEventHandlerRef = NULL;
2091 ::InstallApplicationEventHandler (eventHandler, RT_ELEMENTS (eventTypes), &eventTypes[0],
2092 this, &mDarwinEventHandlerRef);
2093 ::DisposeEventHandlerUPP (eventHandler);
2094
2095#else /* VBOX_WITH_HACKED_QT */
2096 ((QIApplication *)qApp)->setEventFilter (VBoxConsoleView::macEventFilter, this);
2097#endif /* VBOX_WITH_HACKED_QT */
2098
2099 ::DarwinGrabKeyboard (false);
2100 }
2101 else
2102 {
2103 ::DarwinReleaseKeyboard();
2104#ifndef VBOX_WITH_HACKED_QT
2105 if (mDarwinEventHandlerRef)
2106 {
2107 ::RemoveEventHandler (mDarwinEventHandlerRef);
2108 mDarwinEventHandlerRef = NULL;
2109 }
2110#else
2111 ((QIApplication *)qApp)->setEventFilter (NULL, NULL);
2112#endif
2113 }
2114}
2115
2116#endif // defined (Q_WS_WIN)
2117
2118//
2119// Private members
2120/////////////////////////////////////////////////////////////////////////////
2121
2122/**
2123 * Called on every focus change and also to forcibly capture/uncapture the
2124 * input in situations similar to gaining or losing focus.
2125 *
2126 * @param aHasFocus true if the window got focus and false otherwise.
2127 * @param aReleaseHostKey true to release the host key (used only when
2128 * @a aHasFocus is false.
2129 */
2130void VBoxConsoleView::focusEvent (bool aHasFocus,
2131 bool aReleaseHostKey /* = true */)
2132{
2133 if (aHasFocus)
2134 {
2135#ifdef RT_OS_WINDOWS
2136 if ( !mDisableAutoCapture && gs.autoCapture()
2137 && GetAncestor (winId(), GA_ROOT) == GetForegroundWindow())
2138#else
2139 if (!mDisableAutoCapture && gs.autoCapture())
2140#endif /* RT_OS_WINDOWS */
2141 {
2142 captureKbd (true);
2143/// @todo (dmik)
2144// the below is for the mouse auto-capture. disabled for now. in order to
2145// properly support it, we need to know when *all* mouse buttons are
2146// released after we got focus, and grab the mouse only after then.
2147// btw, the similar would be good the for keyboard auto-capture, too.
2148// if (!(mMouseAbsolute && mMouseIntegration))
2149// captureMouse (true);
2150 }
2151
2152 /* reset the single-time disable capture flag */
2153 if (mDisableAutoCapture)
2154 mDisableAutoCapture = false;
2155 }
2156 else
2157 {
2158 captureMouse (false);
2159 captureKbd (false, false);
2160 releaseAllPressedKeys (aReleaseHostKey);
2161 }
2162}
2163
2164/**
2165 * Synchronize the views of the host and the guest to the modifier keys.
2166 * This function will add up to 6 additional keycodes to codes.
2167 *
2168 * @param codes pointer to keycodes which are sent to the keyboard
2169 * @param count pointer to the keycodes counter
2170 */
2171void VBoxConsoleView::fixModifierState (LONG *codes, uint *count)
2172{
2173#if defined(Q_WS_X11)
2174
2175 Window wDummy1, wDummy2;
2176 int iDummy3, iDummy4, iDummy5, iDummy6;
2177 unsigned uMask;
2178 unsigned uKeyMaskNum = 0, uKeyMaskCaps = 0, uKeyMaskScroll = 0;
2179
2180 uKeyMaskCaps = LockMask;
2181 XModifierKeymap* map = XGetModifierMapping(qt_xdisplay());
2182 KeyCode keyCodeNum = XKeysymToKeycode(qt_xdisplay(), XK_Num_Lock);
2183 KeyCode keyCodeScroll = XKeysymToKeycode(qt_xdisplay(), XK_Scroll_Lock);
2184
2185 for (int i = 0; i < 8; i++)
2186 {
2187 if ( keyCodeNum != NoSymbol
2188 && map->modifiermap[map->max_keypermod * i] == keyCodeNum)
2189 uKeyMaskNum = 1 << i;
2190 else if ( keyCodeScroll != NoSymbol
2191 && map->modifiermap[map->max_keypermod * i] == keyCodeScroll)
2192 uKeyMaskScroll = 1 << i;
2193 }
2194 XQueryPointer(qt_xdisplay(), DefaultRootWindow(qt_xdisplay()), &wDummy1, &wDummy2,
2195 &iDummy3, &iDummy4, &iDummy5, &iDummy6, &uMask);
2196 XFreeModifiermap(map);
2197
2198 if (muNumLockAdaptionCnt && (mNumLock ^ !!(uMask & uKeyMaskNum)))
2199 {
2200 muNumLockAdaptionCnt--;
2201 codes[(*count)++] = 0x45;
2202 codes[(*count)++] = 0x45 | 0x80;
2203 }
2204 if (muCapsLockAdaptionCnt && (mCapsLock ^ !!(uMask & uKeyMaskCaps)))
2205 {
2206 muCapsLockAdaptionCnt--;
2207 codes[(*count)++] = 0x3a;
2208 codes[(*count)++] = 0x3a | 0x80;
2209 }
2210
2211#elif defined(Q_WS_WIN32)
2212
2213 if (muNumLockAdaptionCnt && (mNumLock ^ !!(GetKeyState(VK_NUMLOCK))))
2214 {
2215 muNumLockAdaptionCnt--;
2216 codes[(*count)++] = 0x45;
2217 codes[(*count)++] = 0x45 | 0x80;
2218 }
2219 if (muCapsLockAdaptionCnt && (mCapsLock ^ !!(GetKeyState(VK_CAPITAL))))
2220 {
2221 muCapsLockAdaptionCnt--;
2222 codes[(*count)++] = 0x3a;
2223 codes[(*count)++] = 0x3a | 0x80;
2224 }
2225
2226#elif defined(Q_WS_MAC)
2227
2228 /* if (muNumLockAdaptionCnt) ... - NumLock isn't implemented by Mac OS X so ignore it. */
2229 if (muCapsLockAdaptionCnt && (mCapsLock ^ !!(::GetCurrentEventKeyModifiers() & alphaLock)))
2230 {
2231 muCapsLockAdaptionCnt--;
2232 codes[(*count)++] = 0x3a;
2233 codes[(*count)++] = 0x3a | 0x80;
2234 }
2235
2236#else
2237
2238#warning Adapt VBoxConsoleView::fixModifierState
2239
2240#endif
2241
2242
2243}
2244
2245/**
2246 * Called on enter/exit seamless/fullscreen mode.
2247 */
2248void VBoxConsoleView::toggleFSMode (const QSize &aSize)
2249{
2250 if ((mGuestSupportsGraphics && mAutoresizeGuest) ||
2251 mMainWnd->isTrueFullscreen())
2252 {
2253 QSize newSize;
2254 if (aSize.isValid())
2255 {
2256 mNormalSize = aSize;
2257 newSize = maximumSize();
2258 }
2259 else
2260 newSize = mNormalSize;
2261 doResizeHint (newSize);
2262 }
2263}
2264
2265/**
2266 * Get the current available desktop geometry for the console/framebuffer
2267 *
2268 * @returns the geometry. An empty rectangle means unrestricted.
2269 */
2270QRect VBoxConsoleView::desktopGeometry()
2271{
2272 QRect rc;
2273 switch (mDesktopGeo)
2274 {
2275 case DesktopGeo_Fixed:
2276 case DesktopGeo_Automatic:
2277 rc = QRect (0, 0,
2278 RT_MAX (mDesktopGeometry.width(), mLastSizeHint.width()),
2279 RT_MAX (mDesktopGeometry.height(), mLastSizeHint.height()));
2280 break;
2281 case DesktopGeo_Any:
2282 rc = QRect (0, 0, 0, 0);
2283 break;
2284 default:
2285 AssertMsgFailed (("Bad geometry type %d\n", mDesktopGeo));
2286 }
2287 return rc;
2288}
2289
2290bool VBoxConsoleView::isAutoresizeGuestActive()
2291{
2292 return mGuestSupportsGraphics && mAutoresizeGuest;
2293}
2294
2295/**
2296 * Called on every key press and release (while in focus).
2297 *
2298 * @param aKey virtual scan code (virtual key on Win32 and KeySym on X11)
2299 * @param aScan hardware scan code
2300 * @param aFlags flags, a combination of Key* constants
2301 * @param aUniKey Unicode translation of the key. Optional.
2302 *
2303 * @return true to consume the event and false to pass it to Qt
2304 */
2305bool VBoxConsoleView::keyEvent (int aKey, uint8_t aScan, int aFlags,
2306 wchar_t *aUniKey/* = NULL*/)
2307{
2308#if 0
2309 {
2310 char buf [256];
2311 sprintf (buf, "aKey=%08X aScan=%02X aFlags=%08X",
2312 aKey, aScan, aFlags);
2313 mMainWnd->statusBar()->message (buf);
2314 }
2315#endif
2316
2317 const bool isHostKey = aKey == gs.hostKey();
2318
2319 LONG buf [16];
2320 LONG *codes = buf;
2321 uint count = 0;
2322 uint8_t whatPressed = 0;
2323
2324 if (!isHostKey && !mIsHostkeyPressed)
2325 {
2326 if (aFlags & KeyPrint)
2327 {
2328 static LONG PrintMake[] = { 0xE0, 0x2A, 0xE0, 0x37 };
2329 static LONG PrintBreak[] = { 0xE0, 0xB7, 0xE0, 0xAA };
2330 if (aFlags & KeyPressed)
2331 {
2332 codes = PrintMake;
2333 count = SIZEOF_ARRAY (PrintMake);
2334 }
2335 else
2336 {
2337 codes = PrintBreak;
2338 count = SIZEOF_ARRAY (PrintBreak);
2339 }
2340 }
2341 else if (aFlags & KeyPause)
2342 {
2343 if (aFlags & KeyPressed)
2344 {
2345 static LONG Pause[] = { 0xE1, 0x1D, 0x45, 0xE1, 0x9D, 0xC5 };
2346 codes = Pause;
2347 count = SIZEOF_ARRAY (Pause);
2348 }
2349 else
2350 {
2351 /* Pause shall not produce a break code */
2352 return true;
2353 }
2354 }
2355 else
2356 {
2357 if (aFlags & KeyPressed)
2358 {
2359 /* Check if the guest has the same view on the modifier keys (NumLock,
2360 * CapsLock, ScrollLock) as the X server. If not, send KeyPress events
2361 * to synchronize the state. */
2362 fixModifierState (codes, &count);
2363 }
2364
2365 /* Check if it's C-A-D */
2366 if (aScan == 0x53 /* Del */ &&
2367 ((mPressedKeys [0x38] & IsKeyPressed) /* Alt */ ||
2368 (mPressedKeys [0x38] & IsExtKeyPressed)) &&
2369 ((mPressedKeys [0x1d] & IsKeyPressed) /* Ctrl */ ||
2370 (mPressedKeys [0x1d] & IsExtKeyPressed)))
2371 {
2372 /* Use the C-A-D combination as a last resort to get the
2373 * keyboard and mouse back to the host when the user forgets
2374 * the Host Key. Note that it's always possible to send C-A-D
2375 * to the guest using the Host+Del combination. BTW, it would
2376 * be preferrable to completely ignore C-A-D in guests, but
2377 * that's not possible because we cannot predict what other
2378 * keys will be pressed next when one of C, A, D is held. */
2379
2380 if (isRunning() && mKbdCaptured)
2381 {
2382 captureKbd (false);
2383 if (!(mMouseAbsolute && mMouseIntegration))
2384 captureMouse (false);
2385 }
2386
2387 return true;
2388 }
2389
2390 /* process the scancode and update the table of pressed keys */
2391 whatPressed = IsKeyPressed;
2392
2393 if (aFlags & KeyExtended)
2394 {
2395 codes [count++] = 0xE0;
2396 whatPressed = IsExtKeyPressed;
2397 }
2398
2399 if (aFlags & KeyPressed)
2400 {
2401 codes [count++] = aScan;
2402 mPressedKeys [aScan] |= whatPressed;
2403 }
2404 else
2405 {
2406 /* if we haven't got this key's press message, we ignore its
2407 * release */
2408 if (!(mPressedKeys [aScan] & whatPressed))
2409 return true;
2410 codes [count++] = aScan | 0x80;
2411 mPressedKeys [aScan] &= ~whatPressed;
2412 }
2413
2414 if (mKbdCaptured)
2415 mPressedKeys [aScan] |= IsKbdCaptured;
2416 else
2417 mPressedKeys [aScan] &= ~IsKbdCaptured;
2418 }
2419 }
2420 else
2421 {
2422 /* currently this is used in winLowKeyboardEvent() only */
2423 hostkey_in_capture = mKbdCaptured;
2424 }
2425
2426 bool emitSignal = false;
2427 int hotkey = 0;
2428
2429 /* process the host key */
2430 if (aFlags & KeyPressed)
2431 {
2432 if (isHostKey)
2433 {
2434 if (!mIsHostkeyPressed)
2435 {
2436 mIsHostkeyPressed = mIsHostkeyAlone = true;
2437 if (isRunning())
2438 saveKeyStates();
2439 emitSignal = true;
2440 }
2441 }
2442 else
2443 {
2444 if (mIsHostkeyPressed)
2445 {
2446 if (mIsHostkeyAlone)
2447 {
2448 hotkey = aKey;
2449 mIsHostkeyAlone = false;
2450 }
2451 }
2452 }
2453 }
2454 else
2455 {
2456 if (isHostKey)
2457 {
2458 if (mIsHostkeyPressed)
2459 {
2460 mIsHostkeyPressed = false;
2461
2462 if (mIsHostkeyAlone)
2463 {
2464 if (isPaused())
2465 {
2466 vboxProblem().remindAboutPausedVMInput();
2467 }
2468 else
2469 if (isRunning())
2470 {
2471 bool captured = mKbdCaptured;
2472 bool ok = true;
2473 if (!captured)
2474 {
2475 /* temporarily disable auto capture that will take
2476 * place after this dialog is dismissed because
2477 * the capture state is to be defined by the
2478 * dialog result itself */
2479 mDisableAutoCapture = true;
2480 bool autoConfirmed = false;
2481 ok = vboxProblem().confirmInputCapture (&autoConfirmed);
2482 if (autoConfirmed)
2483 mDisableAutoCapture = false;
2484 /* otherwise, the disable flag will be reset in
2485 * the next console view's foucs in event (since
2486 * may happen asynchronously on some platforms,
2487 * after we return from this code) */
2488 }
2489
2490 if (ok)
2491 {
2492 captureKbd (!captured, false);
2493 if (!(mMouseAbsolute && mMouseIntegration))
2494 {
2495#ifdef Q_WS_X11
2496 /* make sure that pending FocusOut events from the
2497 * previous message box are handled, otherwise the
2498 * mouse is immediately ungrabbed. */
2499 qApp->processEvents();
2500#endif
2501 captureMouse (mKbdCaptured);
2502 }
2503 }
2504 }
2505 }
2506
2507 if (isRunning())
2508 sendChangedKeyStates();
2509
2510 emitSignal = true;
2511 }
2512 }
2513 else
2514 {
2515 if (mIsHostkeyPressed)
2516 mIsHostkeyAlone = false;
2517 }
2518 }
2519
2520 /* emit the keyboard state change signal */
2521 if (emitSignal)
2522 emitKeyboardStateChanged();
2523
2524 /* Process Host+<key> shortcuts. currently, <key> is limited to
2525 * alphanumeric chars. Other Host+<key> combinations are handled in
2526 * event(). */
2527 if (hotkey)
2528 {
2529 bool processed = false;
2530#if defined (Q_WS_WIN32)
2531 NOREF(aUniKey);
2532 int n = GetKeyboardLayoutList (0, NULL);
2533 Assert (n);
2534 HKL *list = new HKL [n];
2535 GetKeyboardLayoutList (n, list);
2536 for (int i = 0; i < n && !processed; i++)
2537 {
2538 wchar_t ch;
2539 static BYTE keys [256] = {0};
2540 if (!ToUnicodeEx (hotkey, 0, keys, &ch, 1, 0, list [i]) == 1)
2541 ch = 0;
2542 if (ch)
2543 processed = processHotKey (QKeySequence (UNICODE_ACCEL +
2544 QChar (ch).upper().unicode()),
2545 mMainWnd->menuBar());
2546 }
2547 delete[] list;
2548#elif defined (Q_WS_X11)
2549 NOREF(aUniKey);
2550 Display *display = x11Display();
2551 int keysyms_per_keycode = getKeysymsPerKeycode();
2552 KeyCode kc = XKeysymToKeycode (display, aKey);
2553 // iterate over the first level (not shifted) keysyms in every group
2554 for (int i = 0; i < keysyms_per_keycode && !processed; i += 2)
2555 {
2556 KeySym ks = XKeycodeToKeysym (display, kc, i);
2557 char ch = 0;
2558 if (!XkbTranslateKeySym (display, &ks, 0, &ch, 1, NULL) == 1)
2559 ch = 0;
2560 if (ch)
2561 {
2562 QChar c = QString::fromLocal8Bit (&ch, 1) [0];
2563 processed = processHotKey (QKeySequence (UNICODE_ACCEL +
2564 c.upper().unicode()),
2565 mMainWnd->menuBar());
2566 }
2567 }
2568#elif defined (Q_WS_MAC)
2569 if (aUniKey && aUniKey [0] && !aUniKey [1])
2570 processed = processHotKey (QKeySequence (UNICODE_ACCEL +
2571 QChar (aUniKey [0]).upper().unicode()),
2572 mMainWnd->menuBar());
2573
2574 /* Don't consider the hot key as pressed since the guest never saw
2575 * it. (probably a generic thing) */
2576 mPressedKeys [aScan] &= ~whatPressed;
2577#endif
2578
2579 /* grab the key from Qt if processed, or pass it to Qt otherwise
2580 * in order to process non-alphanumeric keys in event(), after they are
2581 * converted to Qt virtual keys. */
2582 return processed;
2583 }
2584
2585 /* no more to do, if the host key is in action or the VM is paused */
2586 if (mIsHostkeyPressed || isHostKey || isPaused())
2587 {
2588 /* grab the key from Qt and from VM if it's a host key,
2589 * otherwise just pass it to Qt */
2590 return isHostKey;
2591 }
2592
2593 CKeyboard keyboard = mConsole.GetKeyboard();
2594 Assert (!keyboard.isNull());
2595
2596#if defined (Q_WS_WIN32)
2597 /* send pending WM_PAINT events */
2598 ::UpdateWindow (viewport()->winId());
2599#endif
2600
2601#if 0
2602 {
2603 char buf [256];
2604 sprintf (buf, "*** SCANS: ");
2605 for (uint i = 0; i < count; ++ i)
2606 sprintf (buf + strlen (buf), "%02X ", codes [i]);
2607 mMainWnd->statusBar()->message (buf);
2608 LogFlow (("%s\n", buf));
2609 }
2610#endif
2611
2612 keyboard.PutScancodes (codes, count);
2613
2614 /* grab the key from Qt */
2615 return true;
2616}
2617
2618/**
2619 * Called on every mouse/wheel move and button press/release.
2620 *
2621 * @return true to consume the event and false to pass it to Qt
2622 */
2623bool VBoxConsoleView::mouseEvent (int aType, const QPoint &aPos,
2624 const QPoint &aGlobalPos, ButtonState aButton,
2625 ButtonState aState, ButtonState aStateAfter,
2626 int aWheelDelta, Orientation aWheelDir)
2627{
2628#if 0
2629 char buf [256];
2630 sprintf (buf,
2631 "MOUSE: type=%03d x=%03d y=%03d btn=%03d st=%08X stAfter=%08X "
2632 "wdelta=%03d wdir=%03d",
2633 aType, aPos.x(), aPos.y(), aButton, aState, aStateAfter,
2634 aWheelDelta, aWheelDir);
2635 mMainWnd->statusBar()->message (buf);
2636#else
2637 Q_UNUSED (aButton);
2638 Q_UNUSED (aState);
2639#endif
2640
2641 int state = 0;
2642 if (aStateAfter & LeftButton)
2643 state |= KMouseButtonState_LeftButton;
2644 if (aStateAfter & RightButton)
2645 state |= KMouseButtonState_RightButton;
2646 if (aStateAfter & MidButton)
2647 state |= KMouseButtonState_MiddleButton;
2648
2649 int wheel = 0;
2650 if (aWheelDir == Vertical)
2651 {
2652 /* the absolute value of wheel delta is 120 units per every wheel
2653 * move; positive deltas correspond to counterclockwize rotations
2654 * (usually up), negative -- to clockwize (usually down). */
2655 wheel = - (aWheelDelta / 120);
2656 }
2657
2658 if (mMouseCaptured)
2659 {
2660#ifdef Q_WS_WIN32
2661 /* send pending WM_PAINT events */
2662 ::UpdateWindow (viewport()->winId());
2663#endif
2664
2665 CMouse mouse = mConsole.GetMouse();
2666 mouse.PutMouseEvent (aGlobalPos.x() - mLastPos.x(),
2667 aGlobalPos.y() - mLastPos.y(),
2668 wheel, state);
2669
2670#if defined (Q_WS_MAC)
2671 /*
2672 * Keep the mouse from leaving the widget.
2673 *
2674 * This is a bit tricky to get right because if it escapes we won't necessarily
2675 * get mouse events any longer and can warp it back. So, we keep safety zone
2676 * of up to 300 pixels around the borders of the widget to prevent this from
2677 * happening. Also, the mouse is warped back to the center of the widget.
2678 *
2679 * (Note, aPos seems to be unreliable, it caused endless recursion here at one points...)
2680 * (Note, synergy and other remote clients might not like this cursor warping.)
2681 */
2682 QRect rect = viewport()->visibleRect();
2683 QPoint pw = viewport()->mapToGlobal (viewport()->pos());
2684 rect.moveBy (pw.x(), pw.y());
2685
2686 QRect dpRect = QApplication::desktop()->screenGeometry (viewport());
2687 if (rect.intersects (dpRect))
2688 rect = rect.intersect (dpRect);
2689
2690 int wsafe = rect.width() / 6;
2691 rect.setWidth (rect.width() - wsafe * 2);
2692 rect.setLeft (rect.left() + wsafe);
2693
2694 int hsafe = rect.height() / 6;
2695 rect.setWidth (rect.height() - hsafe * 2);
2696 rect.setTop (rect.top() + hsafe);
2697
2698 if (rect.contains (aGlobalPos, true))
2699 mLastPos = aGlobalPos;
2700 else
2701 {
2702 mLastPos = rect.center();
2703 QCursor::setPos (mLastPos);
2704 }
2705
2706#else /* !Q_WS_MAC */
2707
2708 /* "jerk" the mouse by bringing it to the opposite side
2709 * to simulate the endless moving */
2710
2711#ifdef Q_WS_WIN32
2712 int we = viewport()->width() - 1;
2713 int he = viewport()->height() - 1;
2714 QPoint p = aPos;
2715 if (aPos.x() == 0)
2716 p.setX (we - 1);
2717 else if (aPos.x() == we)
2718 p.setX (1);
2719 if (aPos.y() == 0 )
2720 p.setY (he - 1);
2721 else if (aPos.y() == he)
2722 p.setY (1);
2723
2724 if (p != aPos)
2725 {
2726 mLastPos = viewport()->mapToGlobal (p);
2727 QCursor::setPos (mLastPos);
2728 }
2729 else
2730 {
2731 mLastPos = aGlobalPos;
2732 }
2733#else
2734 int we = QApplication::desktop()->width() - 1;
2735 int he = QApplication::desktop()->height() - 1;
2736 QPoint p = aGlobalPos;
2737 if (aGlobalPos.x() == 0)
2738 p.setX (we - 1);
2739 else if (aGlobalPos.x() == we)
2740 p.setX( 1 );
2741 if (aGlobalPos.y() == 0)
2742 p.setY (he - 1);
2743 else if (aGlobalPos.y() == he)
2744 p.setY (1);
2745
2746 if (p != aGlobalPos)
2747 {
2748 mLastPos = p;
2749 QCursor::setPos (mLastPos);
2750 }
2751 else
2752 {
2753 mLastPos = aGlobalPos;
2754 }
2755#endif
2756#endif /* !Q_WS_MAC */
2757 return true; /* stop further event handling */
2758 }
2759 else /* !mMouseCaptured */
2760 {
2761#ifdef Q_WS_MAC
2762 /* Update the mouse cursor; this is a bit excessive really... */
2763 if (!DarwinCursorIsNull (&mDarwinCursor))
2764 DarwinCursorSet (&mDarwinCursor);
2765#endif
2766 if (mMainWnd->isTrueFullscreen())
2767 {
2768 if (mode != VBoxDefs::SDLMode)
2769 {
2770 /* try to automatically scroll the guest canvas if the
2771 * mouse is on the screen border */
2772 /// @todo (r=dmik) better use a timer for autoscroll
2773 QRect scrGeo = QApplication::desktop()->screenGeometry (this);
2774 int dx = 0, dy = 0;
2775 if (scrGeo.width() < contentsWidth())
2776 {
2777 if (scrGeo.rLeft() == aGlobalPos.x()) dx = -1;
2778 if (scrGeo.rRight() == aGlobalPos.x()) dx = +1;
2779 }
2780 if (scrGeo.height() < contentsHeight())
2781 {
2782 if (scrGeo.rTop() == aGlobalPos.y()) dy = -1;
2783 if (scrGeo.rBottom() == aGlobalPos.y()) dy = +1;
2784 }
2785 if (dx || dy)
2786 scrollBy (dx, dy);
2787 }
2788 }
2789
2790 if (mMouseAbsolute && mMouseIntegration)
2791 {
2792 int cw = contentsWidth(), ch = contentsHeight();
2793 int vw = visibleWidth(), vh = visibleHeight();
2794
2795 if (mode != VBoxDefs::SDLMode)
2796 {
2797 /* try to automatically scroll the guest canvas if the
2798 * mouse goes outside its visible part */
2799
2800 int dx = 0;
2801 if (aPos.x() > vw) dx = aPos.x() - vw;
2802 else if (aPos.x() < 0) dx = aPos.x();
2803 int dy = 0;
2804 if (aPos.y() > vh) dy = aPos.y() - vh;
2805 else if (aPos.y() < 0) dy = aPos.y();
2806 if (dx != 0 || dy != 0) scrollBy (dx, dy);
2807 }
2808
2809 QPoint cpnt = viewportToContents (aPos);
2810 if (cpnt.x() < 0) cpnt.setX (0);
2811 else if (cpnt.x() >= cw) cpnt.setX (cw - 1);
2812 if (cpnt.y() < 0) cpnt.setY (0);
2813 else if (cpnt.y() >= ch) cpnt.setY (ch - 1);
2814
2815 CMouse mouse = mConsole.GetMouse();
2816 mouse.PutMouseEventAbsolute (cpnt.x() + 1, cpnt.y() + 1,
2817 wheel, state);
2818 return true; /* stop further event handling */
2819 }
2820 else
2821 {
2822 if (hasFocus() &&
2823 (aType == QEvent::MouseButtonRelease &&
2824 !aStateAfter))
2825 {
2826 if (isPaused())
2827 {
2828 vboxProblem().remindAboutPausedVMInput();
2829 }
2830 else if (isRunning())
2831 {
2832 /* temporarily disable auto capture that will take
2833 * place after this dialog is dismissed because
2834 * the capture state is to be defined by the
2835 * dialog result itself */
2836 mDisableAutoCapture = true;
2837 bool autoConfirmed = false;
2838 bool ok = vboxProblem().confirmInputCapture (&autoConfirmed);
2839 if (autoConfirmed)
2840 mDisableAutoCapture = false;
2841 /* otherwise, the disable flag will be reset in
2842 * the next console view's foucs in event (since
2843 * may happen asynchronously on some platforms,
2844 * after we return from this code) */
2845
2846 if (ok)
2847 {
2848#ifdef Q_WS_X11
2849 /* make sure that pending FocusOut events from the
2850 * previous message box are handled, otherwise the
2851 * mouse is immediately ungrabbed again */
2852 qApp->processEvents();
2853#endif
2854 captureKbd (true);
2855 captureMouse (true);
2856 }
2857 }
2858 }
2859 }
2860 }
2861
2862 return false;
2863}
2864
2865void VBoxConsoleView::onStateChange (KMachineState state)
2866{
2867 switch (state)
2868 {
2869 case KMachineState_Paused:
2870 {
2871 if (mode != VBoxDefs::TimerMode && mFrameBuf)
2872 {
2873 /*
2874 * Take a screen snapshot. Note that TakeScreenShot() always
2875 * needs a 32bpp image
2876 */
2877 QImage shot = QImage (mFrameBuf->width(), mFrameBuf->height(), 32, 0);
2878 CDisplay dsp = mConsole.GetDisplay();
2879 dsp.TakeScreenShot (shot.bits(), shot.width(), shot.height());
2880 /*
2881 * TakeScreenShot() may fail if, e.g. the Paused notification
2882 * was delivered after the machine execution was resumed. It's
2883 * not fatal.
2884 */
2885 if (dsp.isOk())
2886 {
2887 dimImage (shot);
2888 mPausedShot = shot;
2889 /* fully repaint to pick up mPausedShot */
2890 viewport()->repaint();
2891 }
2892 }
2893 /* fall through */
2894 }
2895 case KMachineState_Stuck:
2896 {
2897 /* reuse the focus event handler to uncapture everything */
2898 if (hasFocus())
2899 focusEvent (false /* aHasFocus*/, false /* aReleaseHostKey */);
2900 break;
2901 }
2902 case KMachineState_Running:
2903 {
2904 if (mLastState == KMachineState_Paused)
2905 {
2906 if (mode != VBoxDefs::TimerMode && mFrameBuf)
2907 {
2908 /* reset the pixmap to free memory */
2909 mPausedShot.resize (0, 0);
2910 /*
2911 * ask for full guest display update (it will also update
2912 * the viewport through IFramebuffer::NotifyUpdate)
2913 */
2914 CDisplay dsp = mConsole.GetDisplay();
2915 dsp.InvalidateAndUpdate();
2916 }
2917 }
2918 /* reuse the focus event handler to capture input */
2919 if (hasFocus())
2920 focusEvent (true /* aHasFocus */);
2921 break;
2922 }
2923 default:
2924 break;
2925 }
2926
2927 mLastState = state;
2928}
2929
2930void VBoxConsoleView::doRefresh()
2931{
2932 repaintContents (false);
2933}
2934
2935void VBoxConsoleView::viewportPaintEvent (QPaintEvent *pe)
2936{
2937 if (mPausedShot.isNull())
2938 {
2939 /* delegate the paint function to the VBoxFrameBuffer interface */
2940 mFrameBuf->paintEvent (pe);
2941#ifdef Q_WS_MAC
2942 /* Update the dock icon if we are in the running state */
2943 if (isRunning())
2944 {
2945# if defined (VBOX_GUI_USE_QUARTZ2D)
2946 if (mode == VBoxDefs::Quartz2DMode)
2947 {
2948 /* If the render mode is Quartz2D we could use the
2949 * CGImageRef of the framebuffer for the dock icon creation.
2950 * This saves some conversion time. */
2951 CGImageRef ir =
2952 static_cast <VBoxQuartz2DFrameBuffer *> (mFrameBuf)->imageRef();
2953 ::DarwinUpdateDockPreview (ir, mVirtualBoxLogo);
2954 }
2955 else
2956# endif
2957 ::DarwinUpdateDockPreview (mFrameBuf, mVirtualBoxLogo);
2958 }
2959#endif
2960 return;
2961 }
2962
2963 /* we have a snapshot for the paused state */
2964 QRect r = pe->rect().intersect (viewport()->rect());
2965 QPainter pnt (viewport());
2966 pnt.drawPixmap (r.x(), r.y(), mPausedShot,
2967 r.x() + contentsX(), r.y() + contentsY(),
2968 r.width(), r.height());
2969
2970#ifdef Q_WS_MAC
2971 ::DarwinUpdateDockPreview (DarwinQPixmapToCGImage (&mPausedShot),
2972 mVirtualBoxLogo,
2973 mMainWnd->dockImageState());
2974#endif
2975}
2976
2977/**
2978 * Captures the keyboard. When captured, no keyboard input reaches the host
2979 * system (including most system combinations like Alt-Tab).
2980 *
2981 * @param aCapture true to capture, false to uncapture.
2982 * @param aEmitSignal Whether to emit keyboardStateChanged() or not.
2983 */
2984void VBoxConsoleView::captureKbd (bool aCapture, bool aEmitSignal /* = true */)
2985{
2986 AssertMsg (mAttached, ("Console must be attached"));
2987
2988 if (mKbdCaptured == aCapture)
2989 return;
2990
2991 /* On Win32, keyboard grabbing is ineffective, a low-level keyboard hook is
2992 * used instead. On X11, we use XGrabKey instead of XGrabKeyboard (called
2993 * by QWidget::grabKeyboard()) because the latter causes problems under
2994 * metacity 2.16 (in particular, due to a bug, a window cannot be moved
2995 * using the mouse if it is currently grabing the keyboard). On Mac OS X,
2996 * we use the Qt methods + disabling global hot keys + watching modifiers
2997 * (for right/left separation). */
2998#if defined (Q_WS_WIN32)
2999 /**/
3000#elif defined (Q_WS_X11)
3001 if (aCapture)
3002 XGrabKey (x11Display(), AnyKey, AnyModifier,
3003 topLevelWidget()->winId(), False,
3004 GrabModeAsync, GrabModeAsync);
3005 else
3006 XUngrabKey (x11Display(), AnyKey, AnyModifier,
3007 topLevelWidget()->winId());
3008#elif defined (Q_WS_MAC)
3009 if (aCapture)
3010 {
3011 ::DarwinDisableGlobalHotKeys (true);
3012 grabKeyboard();
3013 }
3014 else
3015 {
3016 ::DarwinDisableGlobalHotKeys (false);
3017 releaseKeyboard();
3018 }
3019#else
3020 if (aCapture)
3021 grabKeyboard();
3022 else
3023 releaseKeyboard();
3024#endif
3025
3026 mKbdCaptured = aCapture;
3027
3028 if (aEmitSignal)
3029 emitKeyboardStateChanged();
3030}
3031
3032/**
3033 * Captures the host mouse pointer. When captured, the mouse pointer is
3034 * unavailable to the host applications.
3035 *
3036 * @param aCapture true to capture, false to uncapture.
3037 * @param aEmitSignal Whether to emit mouseStateChanged() or not.
3038 */
3039void VBoxConsoleView::captureMouse (bool aCapture, bool aEmitSignal /* = true */)
3040{
3041 AssertMsg (mAttached, ("Console must be attached"));
3042
3043 if (mMouseCaptured == aCapture)
3044 return;
3045
3046 if (aCapture)
3047 {
3048 /* memorize the host position where the cursor was captured */
3049 mCapturedPos = QCursor::pos();
3050#ifdef Q_WS_WIN32
3051 viewport()->setCursor (QCursor (BlankCursor));
3052 /* move the mouse to the center of the visible area */
3053 QCursor::setPos (mapToGlobal (visibleRect().center()));
3054 mLastPos = QCursor::pos();
3055#elif defined (Q_WS_MAC)
3056 /* move the mouse to the center of the visible area */
3057 mLastPos = mapToGlobal (visibleRect().center());
3058 QCursor::setPos (mLastPos);
3059 /* grab all mouse events. */
3060 viewport()->grabMouse();
3061#else
3062 viewport()->grabMouse();
3063 mLastPos = QCursor::pos();
3064#endif
3065 }
3066 else
3067 {
3068#ifndef Q_WS_WIN32
3069 viewport()->releaseMouse();
3070#endif
3071 /* release mouse buttons */
3072 CMouse mouse = mConsole.GetMouse();
3073 mouse.PutMouseEvent (0, 0, 0, 0);
3074 }
3075
3076 mMouseCaptured = aCapture;
3077
3078 updateMouseClipping();
3079
3080 if (aEmitSignal)
3081 emitMouseStateChanged();
3082}
3083
3084/**
3085 * Searches for a menu item with a given hot key (shortcut). If the item
3086 * is found, activates it and returns true. Otherwise returns false.
3087 */
3088bool VBoxConsoleView::processHotKey (const QKeySequence &key, QMenuData *data)
3089{
3090 if (!data) return false;
3091
3092 /*
3093 * Note: below, we use the internal class QMenuItem, that is subject
3094 * to change w/o notice... (the alternative would be to explicitly assign
3095 * specific IDs to all popup submenus in VBoxConsoleWnd and then
3096 * look through its children in order to find a popup with a given ID,
3097 * which is unconvenient).
3098 */
3099
3100 for (uint i = 0; i < data->count(); i++)
3101 {
3102 int id = data->idAt (i);
3103 QMenuItem *item = data->findItem (id);
3104 if (item->popup())
3105 {
3106 if (processHotKey (key, item->popup()))
3107 return true;
3108 }
3109 else
3110 {
3111 QStringList list = QStringList::split ("\tHost+", data->text (id));
3112 if (list.count() == 2)
3113 {
3114 if (key.matches (QKeySequence (list[1])) == Identical)
3115 {
3116 /*
3117 * we asynchronously post a special event instead of calling
3118 * data->activateItemAt (i) directly, to let key presses
3119 * and releases be processed correctly by Qt first.
3120 * Note: we assume that nobody will delete the menu item
3121 * corresponding to the key sequence, so that the pointer to
3122 * menu data posted along with the event will remain valid in
3123 * the event handler, at least until the main window is closed.
3124 */
3125
3126 QApplication::postEvent (this,
3127 new ActivateMenuEvent (data, i));
3128 return true;
3129 }
3130 }
3131 }
3132 }
3133
3134 return false;
3135}
3136
3137/**
3138 * Send the KEY BREAK code to the VM for all currently pressed keys.
3139 *
3140 * @param aReleaseHostKey @c true to set the host key state to unpressed.
3141 */
3142void VBoxConsoleView::releaseAllPressedKeys (bool aReleaseHostKey /* = true*/)
3143{
3144 AssertMsg (mAttached, ("Console must be attached"));
3145
3146 CKeyboard keyboard = mConsole.GetKeyboard();
3147 bool fSentRESEND = false;
3148
3149 /* send a dummy scan code (RESEND) to prevent the guest OS from recognizing
3150 * a single key click (for ex., Alt) and performing an unwanted action
3151 * (for ex., activating the menu) when we release all pressed keys below.
3152 * Note, that it's just a guess that sending RESEND will give the desired
3153 * effect :), but at least it works with NT and W2k guests. */
3154
3155 /// @todo Sending 0xFE is responsible for the warning
3156 //
3157 // ``atkbd.c: Spurious NAK on isa0060/serio0. Some program might
3158 // be trying access hardware directly''
3159 //
3160 // on Linux guests (#1944). It might also be responsible for #1949. Don't
3161 // send this command unless we really have to release any key modifier.
3162 // --frank
3163
3164 for (uint i = 0; i < SIZEOF_ARRAY (mPressedKeys); i++)
3165 {
3166 if (mPressedKeys [i] & IsKeyPressed)
3167 {
3168 if (!fSentRESEND)
3169 {
3170 keyboard.PutScancode (0xFE);
3171 fSentRESEND = true;
3172 }
3173 keyboard.PutScancode (i | 0x80);
3174 }
3175 else if (mPressedKeys [i] & IsExtKeyPressed)
3176 {
3177 if (!fSentRESEND)
3178 {
3179 keyboard.PutScancode (0xFE);
3180 fSentRESEND = true;
3181 }
3182 LONG codes [2];
3183 codes[0] = 0xE0;
3184 codes[1] = i | 0x80;
3185 keyboard.PutScancodes (codes, 2);
3186 }
3187 mPressedKeys [i] = 0;
3188 }
3189
3190 if (aReleaseHostKey)
3191 mIsHostkeyPressed = false;
3192
3193#ifdef Q_WS_MAC
3194 /* clear most of the modifiers. */
3195 mDarwinKeyModifiers &=
3196 alphaLock | kEventKeyModifierNumLockMask |
3197 (aReleaseHostKey ? 0 : ::DarwinKeyCodeToDarwinModifierMask (gs.hostKey()));
3198#endif
3199
3200 emitKeyboardStateChanged();
3201}
3202
3203void VBoxConsoleView::saveKeyStates()
3204{
3205 ::memcpy (mPressedKeysCopy, mPressedKeys,
3206 SIZEOF_ARRAY (mPressedKeys));
3207}
3208
3209void VBoxConsoleView::sendChangedKeyStates()
3210{
3211 AssertMsg (mAttached, ("Console must be attached"));
3212
3213 LONG codes [2];
3214 CKeyboard keyboard = mConsole.GetKeyboard();
3215 for (uint i = 0; i < SIZEOF_ARRAY (mPressedKeys); ++ i)
3216 {
3217 uint8_t os = mPressedKeysCopy [i];
3218 uint8_t ns = mPressedKeys [i];
3219 if ((os & IsKeyPressed) != (ns & IsKeyPressed))
3220 {
3221 codes [0] = i;
3222 if (!(ns & IsKeyPressed))
3223 codes[0] |= 0x80;
3224 keyboard.PutScancode (codes[0]);
3225 }
3226 else if ((os & IsExtKeyPressed) != (ns & IsExtKeyPressed))
3227 {
3228 codes [0] = 0xE0;
3229 codes [1] = i;
3230 if (!(ns & IsExtKeyPressed))
3231 codes [1] |= 0x80;
3232 keyboard.PutScancodes (codes, 2);
3233 }
3234 }
3235}
3236
3237void VBoxConsoleView::updateMouseClipping()
3238{
3239 AssertMsg (mAttached, ("Console must be attached"));
3240
3241 if (mMouseCaptured)
3242 {
3243 viewport()->setCursor (QCursor (BlankCursor));
3244#ifdef Q_WS_WIN32
3245 QRect r = viewport()->rect();
3246 r.moveTopLeft (viewport()->mapToGlobal (QPoint (0, 0)));
3247 RECT rect = { r.left(), r.top(), r.right() + 1, r.bottom() + 1 };
3248 ::ClipCursor (&rect);
3249#endif
3250 }
3251 else
3252 {
3253#ifdef Q_WS_WIN32
3254 ::ClipCursor (NULL);
3255#endif
3256 /* return the cursor to where it was when we captured it and show it */
3257 QCursor::setPos (mCapturedPos);
3258 viewport()->unsetCursor();
3259 }
3260}
3261
3262void VBoxConsoleView::setPointerShape (MousePointerChangeEvent *me)
3263{
3264 if (me->shapeData() != NULL)
3265 {
3266 bool ok = false;
3267
3268 const uchar *srcAndMaskPtr = me->shapeData();
3269 uint andMaskSize = (me->width() + 7) / 8 * me->height();
3270 const uchar *srcShapePtr = me->shapeData() + ((andMaskSize + 3) & ~3);
3271 uint srcShapePtrScan = me->width() * 4;
3272
3273#if defined (Q_WS_WIN)
3274
3275 BITMAPV5HEADER bi;
3276 HBITMAP hBitmap;
3277 void *lpBits;
3278
3279 ::ZeroMemory (&bi, sizeof (BITMAPV5HEADER));
3280 bi.bV5Size = sizeof (BITMAPV5HEADER);
3281 bi.bV5Width = me->width();
3282 bi.bV5Height = - (LONG) me->height();
3283 bi.bV5Planes = 1;
3284 bi.bV5BitCount = 32;
3285 bi.bV5Compression = BI_BITFIELDS;
3286 // specifiy a supported 32 BPP alpha format for Windows XP
3287 bi.bV5RedMask = 0x00FF0000;
3288 bi.bV5GreenMask = 0x0000FF00;
3289 bi.bV5BlueMask = 0x000000FF;
3290 if (me->hasAlpha())
3291 bi.bV5AlphaMask = 0xFF000000;
3292 else
3293 bi.bV5AlphaMask = 0;
3294
3295 HDC hdc = GetDC (NULL);
3296
3297 // create the DIB section with an alpha channel
3298 hBitmap = CreateDIBSection (hdc, (BITMAPINFO *) &bi, DIB_RGB_COLORS,
3299 (void **) &lpBits, NULL, (DWORD) 0);
3300
3301 ReleaseDC (NULL, hdc);
3302
3303 HBITMAP hMonoBitmap = NULL;
3304 if (me->hasAlpha())
3305 {
3306 // create an empty mask bitmap
3307 hMonoBitmap = CreateBitmap (me->width(), me->height(), 1, 1, NULL);
3308 }
3309 else
3310 {
3311 /* Word aligned AND mask. Will be allocated and created if necessary. */
3312 uint8_t *pu8AndMaskWordAligned = NULL;
3313
3314 /* Width in bytes of the original AND mask scan line. */
3315 uint32_t cbAndMaskScan = (me->width() + 7) / 8;
3316
3317 if (cbAndMaskScan & 1)
3318 {
3319 /* Original AND mask is not word aligned. */
3320
3321 /* Allocate memory for aligned AND mask. */
3322 pu8AndMaskWordAligned = (uint8_t *)RTMemTmpAllocZ ((cbAndMaskScan + 1) * me->height());
3323
3324 Assert(pu8AndMaskWordAligned);
3325
3326 if (pu8AndMaskWordAligned)
3327 {
3328 /* According to MSDN the padding bits must be 0.
3329 * Compute the bit mask to set padding bits to 0 in the last byte of original AND mask.
3330 */
3331 uint32_t u32PaddingBits = cbAndMaskScan * 8 - me->width();
3332 Assert(u32PaddingBits < 8);
3333 uint8_t u8LastBytesPaddingMask = (uint8_t)(0xFF << u32PaddingBits);
3334
3335 Log(("u8LastBytesPaddingMask = %02X, aligned w = %d, width = %d, cbAndMaskScan = %d\n",
3336 u8LastBytesPaddingMask, (cbAndMaskScan + 1) * 8, me->width(), cbAndMaskScan));
3337
3338 uint8_t *src = (uint8_t *)srcAndMaskPtr;
3339 uint8_t *dst = pu8AndMaskWordAligned;
3340
3341 unsigned i;
3342 for (i = 0; i < me->height(); i++)
3343 {
3344 memcpy (dst, src, cbAndMaskScan);
3345
3346 dst[cbAndMaskScan - 1] &= u8LastBytesPaddingMask;
3347
3348 src += cbAndMaskScan;
3349 dst += cbAndMaskScan + 1;
3350 }
3351 }
3352 }
3353
3354 /* create the AND mask bitmap */
3355 hMonoBitmap = ::CreateBitmap (me->width(), me->height(), 1, 1,
3356 pu8AndMaskWordAligned? pu8AndMaskWordAligned: srcAndMaskPtr);
3357
3358 if (pu8AndMaskWordAligned)
3359 {
3360 RTMemTmpFree (pu8AndMaskWordAligned);
3361 }
3362 }
3363
3364 Assert (hBitmap);
3365 Assert (hMonoBitmap);
3366 if (hBitmap && hMonoBitmap)
3367 {
3368 DWORD *dstShapePtr = (DWORD *) lpBits;
3369
3370 for (uint y = 0; y < me->height(); y ++)
3371 {
3372 memcpy (dstShapePtr, srcShapePtr, srcShapePtrScan);
3373 srcShapePtr += srcShapePtrScan;
3374 dstShapePtr += me->width();
3375 }
3376
3377 ICONINFO ii;
3378 ii.fIcon = FALSE;
3379 ii.xHotspot = me->xHot();
3380 ii.yHotspot = me->yHot();
3381 ii.hbmMask = hMonoBitmap;
3382 ii.hbmColor = hBitmap;
3383
3384 HCURSOR hAlphaCursor = CreateIconIndirect (&ii);
3385 Assert (hAlphaCursor);
3386 if (hAlphaCursor)
3387 {
3388 viewport()->setCursor (QCursor (hAlphaCursor));
3389 ok = true;
3390 if (mAlphaCursor)
3391 DestroyIcon (mAlphaCursor);
3392 mAlphaCursor = hAlphaCursor;
3393 }
3394 }
3395
3396 if (hMonoBitmap)
3397 DeleteObject (hMonoBitmap);
3398 if (hBitmap)
3399 DeleteObject (hBitmap);
3400
3401#elif defined (Q_WS_X11) && !defined (VBOX_WITHOUT_XCURSOR)
3402
3403 XcursorImage *img = XcursorImageCreate (me->width(), me->height());
3404 Assert (img);
3405 if (img)
3406 {
3407 img->xhot = me->xHot();
3408 img->yhot = me->yHot();
3409
3410 XcursorPixel *dstShapePtr = img->pixels;
3411
3412 for (uint y = 0; y < me->height(); y ++)
3413 {
3414 memcpy (dstShapePtr, srcShapePtr, srcShapePtrScan);
3415
3416 if (!me->hasAlpha())
3417 {
3418 /* convert AND mask to the alpha channel */
3419 uchar byte = 0;
3420 for (uint x = 0; x < me->width(); x ++)
3421 {
3422 if (!(x % 8))
3423 byte = *(srcAndMaskPtr ++);
3424 else
3425 byte <<= 1;
3426
3427 if (byte & 0x80)
3428 {
3429 /* Linux doesn't support inverted pixels (XOR ops,
3430 * to be exact) in cursor shapes, so we detect such
3431 * pixels and always replace them with black ones to
3432 * make them visible at least over light colors */
3433 if (dstShapePtr [x] & 0x00FFFFFF)
3434 dstShapePtr [x] = 0xFF000000;
3435 else
3436 dstShapePtr [x] = 0x00000000;
3437 }
3438 else
3439 dstShapePtr [x] |= 0xFF000000;
3440 }
3441 }
3442
3443 srcShapePtr += srcShapePtrScan;
3444 dstShapePtr += me->width();
3445 }
3446
3447 Cursor cur = XcursorImageLoadCursor (x11Display(), img);
3448 Assert (cur);
3449 if (cur)
3450 {
3451 viewport()->setCursor (QCursor (cur));
3452 ok = true;
3453 }
3454
3455 XcursorImageDestroy (img);
3456 }
3457
3458#elif defined(Q_WS_MAC)
3459
3460 /*
3461 * Qt3/Mac only supports black/white cursors and it offers no way
3462 * to create your own cursors here unlike on X11 and Windows.
3463 * Which means we're pretty much forced to do it our own way.
3464 */
3465 int rc;
3466
3467 /* dispose of the old cursor. */
3468 if (!DarwinCursorIsNull (&mDarwinCursor))
3469 {
3470 rc = DarwinCursorDestroy (&mDarwinCursor);
3471 AssertRC (rc);
3472 }
3473
3474 /* create the new cursor */
3475 rc = DarwinCursorCreate (me->width(), me->height(), me->xHot(), me->yHot(), me->hasAlpha(),
3476 srcAndMaskPtr, srcShapePtr, &mDarwinCursor);
3477 AssertRC (rc);
3478 if (VBOX_SUCCESS (rc))
3479 {
3480 /** @todo check current mouse coordinates. */
3481 rc = DarwinCursorSet (&mDarwinCursor);
3482 AssertRC (rc);
3483 }
3484 ok = VBOX_SUCCESS (rc);
3485 NOREF (srcShapePtrScan);
3486
3487#else
3488
3489# warning "port me"
3490
3491#endif
3492 if (!ok)
3493 viewport()->unsetCursor();
3494 }
3495 else
3496 {
3497 /*
3498 * We did not get any shape data
3499 */
3500 if (me->isVisible())
3501 {
3502 /*
3503 * We're supposed to make the last shape we got visible.
3504 * We don't support that for now...
3505 */
3506 /// @todo viewport()->setCursor (QCursor());
3507 }
3508 else
3509 {
3510 viewport()->setCursor (QCursor::BlankCursor);
3511 }
3512 }
3513}
3514
3515inline QRgb qRgbIntensity (QRgb rgb, int mul, int div)
3516{
3517 int r = qRed (rgb);
3518 int g = qGreen (rgb);
3519 int b = qBlue (rgb);
3520 return qRgb (mul * r / div, mul * g / div, mul * b / div);
3521}
3522
3523/* static */
3524void VBoxConsoleView::dimImage (QImage &img)
3525{
3526 for (int y = 0; y < img.height(); y ++) {
3527 if (y % 2) {
3528 if (img.depth() == 32) {
3529 for (int x = 0; x < img.width(); x ++) {
3530 int gray = qGray (img.pixel (x, y)) / 2;
3531 img.setPixel (x, y, qRgb (gray, gray, gray));
3532// img.setPixel (x, y, qRgbIntensity (img.pixel (x, y), 1, 2));
3533 }
3534 } else {
3535 ::memset (img.scanLine (y), 0, img.bytesPerLine());
3536 }
3537 } else {
3538 if (img.depth() == 32) {
3539 for (int x = 0; x < img.width(); x ++) {
3540 int gray = (2 * qGray (img.pixel (x, y))) / 3;
3541 img.setPixel (x, y, qRgb (gray, gray, gray));
3542// img.setPixel (x, y, qRgbIntensity (img.pixel(x, y), 2, 3));
3543 }
3544 }
3545 }
3546 }
3547}
3548
3549void VBoxConsoleView::doResizeHint (const QSize &aToSize)
3550{
3551 if (mGuestSupportsGraphics && mAutoresizeGuest)
3552 {
3553 /* If this slot is invoked directly then use the passed size
3554 * otherwise get the available size for the guest display.
3555 * We assume here that the centralWidget() contains this view only
3556 * and gives it all available space. */
3557 QSize sz (aToSize.isValid() ? aToSize : mMainWnd->centralWidget()->size());
3558 if (!aToSize.isValid())
3559 sz -= QSize (frameWidth() * 2, frameWidth() * 2);
3560 /* We only actually send the hint if
3561 * 1) the autoresize property is set to true and
3562 * 2) either an explicit new size was given (e.g. if the request
3563 * was triggered directly by a console resize event) or if no
3564 * explicit size was specified but a resize is flagged as being
3565 * needed (e.g. the autoresize was just enabled and the console
3566 * was resized while it was disabled). */
3567 if (mAutoresizeGuest &&
3568 (aToSize.isValid() || mDoResize))
3569 {
3570 LogFlowFunc (("Will suggest %d x %d\n", sz.width(), sz.height()));
3571
3572 /* Increase the maximum allowed size to the new size if needed */
3573 setDesktopGeoHint (sz.width(), sz.height());
3574
3575 mConsole.GetDisplay().SetVideoModeHint (sz.width(), sz.height(), 0, 0);
3576 }
3577 }
3578}
3579
3580void VBoxConsoleView::doResizeDesktop (int)
3581{
3582 /* If the desktop geometry is set automatically, this will update it. */
3583 setDesktopGeometry (DesktopGeo_Unchanged, 0, 0);
3584}
3585
3586/**
3587 * Set the maximum size allowed for the guest desktop. This can either be
3588 * a fixed maximum size, or a lower bound on the maximum. In the second case,
3589 * the maximum will be set to the available desktop area minus 100 pixels each
3590 * way, or to the specified lower bound, whichever is greater.
3591 *
3592 * @param aWidth The maximum width for the guest screen (fixed geometry) or a
3593 * lower bound for the maximum
3594 * @param aHeight The maximum height for the guest screen (fixed geometry)
3595 * or a lower bound for the maximum
3596 */
3597void VBoxConsoleView::setDesktopGeoHint (int aWidth, int aHeight)
3598{
3599 LogFlowThisFunc (("aWidth=%d, aHeight=%d\n", aWidth, aHeight));
3600 mLastSizeHint = QRect (0, 0, aWidth, aHeight);
3601}
3602
3603/**
3604 * Set initial desktop geometry restrictions on the guest framebuffer. These
3605 * determine the maximum size the guest framebuffer can take on. Note that
3606 * a hint from the host will always override these restrictions.
3607 *
3608 * @param aGeo Values: fixed - the guest has a fixed maximum framebuffer
3609 * size automatic - we recalculate the maximum size
3610 * ourselves any - any size is allowed
3611 * @param aWidth The maximum width for the guest screen or zero for no change
3612 * (only used for fixed geometry)
3613 * @param aHeight The maximum height for the guest screen or zero for no change
3614 * (only used for fixed geometry)
3615 */
3616void VBoxConsoleView::setDesktopGeometry (DesktopGeo aGeo, int aWidth, int aHeight)
3617{
3618 LogFlowThisFunc (("aGeo=%s, aWidth=%d, aHeight=%d\n",
3619 (aGeo == DesktopGeo_Fixed ? "Fixed" :
3620 aGeo == DesktopGeo_Automatic ? "Automatic" :
3621 aGeo == DesktopGeo_Any ? "Any" :
3622 aGeo == DesktopGeo_Unchanged ? "Unchanged" : "Invalid"),
3623 aWidth, aHeight));
3624 Assert ((aGeo != DesktopGeo_Unchanged) || (mDesktopGeo != DesktopGeo_Invalid));
3625 if (DesktopGeo_Unchanged == aGeo)
3626 aGeo = mDesktopGeo;
3627 switch (aGeo)
3628 {
3629 case DesktopGeo_Fixed:
3630 mDesktopGeo = DesktopGeo_Fixed;
3631 if (aWidth != 0 && aHeight != 0)
3632 mDesktopGeometry = QRect (0, 0, aWidth, aHeight);
3633 setDesktopGeoHint (0, 0);
3634 break;
3635 case DesktopGeo_Automatic:
3636 {
3637 mDesktopGeo = DesktopGeo_Automatic;
3638 QRect desktop = QApplication::desktop()->screenGeometry (this);
3639 mDesktopGeometry = QRect (0, 0, desktop.width() - 100, desktop.height() - 100);
3640 LogFlowThisFunc (("Setting %d, %d\n", desktop.width() - 100, desktop.height() - 100));
3641 setDesktopGeoHint (0, 0);
3642 break;
3643 }
3644 case DesktopGeo_Any:
3645 mDesktopGeo = DesktopGeo_Any;
3646 mDesktopGeometry = QRect (0, 0, 0, 0);
3647 break;
3648 default:
3649 AssertMsgFailed(("Invalid desktop geometry type %d\n", aGeo));
3650 mDesktopGeo = DesktopGeo_Invalid;
3651 }
3652}
3653
3654/**
3655 * Sets the the minimum size restriction depending on the auto-resize feature
3656 * state and the current rendering mode.
3657 *
3658 * Currently, the restriction is set only in SDL mode and only when the
3659 * auto-resize feature is inactive. We need to do that because we cannot
3660 * correctly draw in a scrolled window in SDL mode.
3661 *
3662 * In all other modes, or when auto-resize is in force, this function does
3663 * nothing.
3664 */
3665void VBoxConsoleView::maybeRestrictMinimumSize()
3666{
3667 if (mode == VBoxDefs::SDLMode)
3668 {
3669 if (!mGuestSupportsGraphics || !mAutoresizeGuest)
3670 setMinimumSize (sizeHint());
3671 else
3672 setMinimumSize (0, 0);
3673 }
3674}
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use