VirtualBox

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

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

Frontends/VirtualBox3/4: removed responsibility for remembering the last guest resolution from the GUI again

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

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