VirtualBox

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

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

Frontends/VirtualBox: do not suggest a new initial resolution if the saved one is too big for the screen, since we now implement the VideoModeSupported request

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

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