VirtualBox

source: vbox/trunk/src/VBox/Frontends/VirtualBox/src/runtime/UISession.cpp@ 98402

Last change on this file since 98402 was 98402, checked in by vboxsync, 2 years ago

Merging r155437 and r155438 from gui4 branch: FE/Qt: Runtime UI: A bit of cleanup for UISession close stuff; Tiny cleanup for UIMachine factory and close stuff.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 33.7 KB
Line 
1/* $Id: UISession.cpp 98402 2023-02-01 14:58:03Z vboxsync $ */
2/** @file
3 * VBox Qt GUI - UISession class implementation.
4 */
5
6/*
7 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28/* Qt includes: */
29#include <QApplication>
30#include <QWidget>
31#ifdef VBOX_WS_WIN
32# include <iprt/win/windows.h> /* Workaround for compile errors if included directly by QtWin. */
33# include <QtWin>
34#endif
35
36/* GUI includes: */
37#include "UICommon.h"
38#include "UIExtraDataManager.h"
39#include "UISession.h"
40#include "UIMachine.h"
41#include "UIMedium.h"
42#include "UIActionPoolRuntime.h"
43#include "UIMachineLogic.h"
44#include "UIMachineView.h"
45#include "UIMachineWindow.h"
46#include "UIMessageCenter.h"
47#include "UIMousePointerShapeData.h"
48#include "UINotificationCenter.h"
49#include "UIConsoleEventHandler.h"
50#include "UIFrameBuffer.h"
51#include "UISettingsDialogSpecific.h"
52#ifdef VBOX_GUI_WITH_KEYS_RESET_HANDLER
53# include "UIKeyboardHandler.h"
54# include <signal.h>
55#endif
56
57/* COM includes: */
58#include "CGraphicsAdapter.h"
59#include "CHostNetworkInterface.h"
60#include "CHostUSBDevice.h"
61#include "CMedium.h"
62#include "CMediumAttachment.h"
63#include "CSnapshot.h"
64#include "CStorageController.h"
65#include "CSystemProperties.h"
66#include "CUSBController.h"
67#include "CUSBDeviceFilter.h"
68#include "CUSBDeviceFilters.h"
69#ifdef VBOX_WITH_NETFLT
70# include "CNetworkAdapter.h"
71#endif
72
73/* External includes: */
74#ifdef VBOX_WS_X11
75# include <X11/Xlib.h>
76# include <X11/Xutil.h>
77#endif
78
79
80#ifdef VBOX_GUI_WITH_KEYS_RESET_HANDLER
81static void signalHandlerSIGUSR1(int sig, siginfo_t *, void *);
82#endif
83
84/* static */
85bool UISession::create(UISession *&pSession, UIMachine *pMachine)
86{
87 /* Make sure NULL pointer passed: */
88 AssertReturn(!pSession, false);
89
90 /* Create session UI: */
91 pSession = new UISession(pMachine);
92 AssertPtrReturn(pSession, false);
93
94 /* Make sure it's prepared: */
95 if (!pSession->prepare())
96 {
97 /* Destroy session UI otherwise: */
98 destroy(pSession);
99 /* False in that case: */
100 return false;
101 }
102
103 /* True by default: */
104 return true;
105}
106
107/* static */
108void UISession::destroy(UISession *&pSession)
109{
110 /* Make sure valid pointer passed: */
111 AssertPtrReturnVoid(pSession);
112
113 /* Delete session: */
114 delete pSession;
115 pSession = 0;
116}
117
118bool UISession::initialize()
119{
120 /* Preprocess initialization: */
121 if (!preprocessInitialization())
122 return false;
123
124 /* Notify user about mouse&keyboard auto-capturing: */
125 if (gEDataManager->autoCaptureEnabled())
126 UINotificationMessage::remindAboutAutoCapture();
127
128 m_machineState = machine().GetState();
129
130 /* Apply debug settings from the command line. */
131 if (!debugger().isNull() && debugger().isOk())
132 {
133 if (uiCommon().areWeToExecuteAllInIem())
134 debugger().SetExecuteAllInIEM(true);
135 if (!uiCommon().isDefaultWarpPct())
136 debugger().SetVirtualTimeRate(uiCommon().getWarpPct());
137 }
138
139 /* Apply ad-hoc reconfigurations from the command line: */
140 if (uiCommon().hasFloppyImageToMount())
141 mountAdHocImage(KDeviceType_Floppy, UIMediumDeviceType_Floppy, uiCommon().getFloppyImage().toString());
142 if (uiCommon().hasDvdImageToMount())
143 mountAdHocImage(KDeviceType_DVD, UIMediumDeviceType_DVD, uiCommon().getDvdImage().toString());
144
145 /* Power UP if this is NOT separate process: */
146 if (!uiCommon().isSeparateProcess())
147 if (!powerUp())
148 return false;
149
150 /* Make sure all the pending Console events converted to signals
151 * during the powerUp() progress above reached their destinations.
152 * That is necessary to make sure all the pending machine state change events processed.
153 * We can't just use the machine state directly acquired from IMachine because there
154 * will be few places which are using stale machine state, not just this one. */
155 QApplication::sendPostedEvents(0, QEvent::MetaCall);
156
157 /* Check if we missed a really quick termination after successful startup: */
158 if (isTurnedOff())
159 {
160 LogRel(("GUI: Aborting startup due to invalid machine state detected: %d\n", machineState()));
161 return false;
162 }
163
164 /* Postprocess initialization: */
165 if (!postprocessInitialization())
166 return false;
167
168 /* Fetch corresponding states: */
169 if (uiCommon().isSeparateProcess())
170 {
171 sltAdditionsChange();
172 }
173 machineLogic()->initializePostPowerUp();
174
175 /* Load VM settings: */
176 loadVMSettings();
177
178#ifdef VBOX_GUI_WITH_PIDFILE
179 uiCommon().createPidfile();
180#endif /* VBOX_GUI_WITH_PIDFILE */
181
182 /* Warn listeners about we are initialized: */
183 m_fInitialized = true;
184 emit sigInitialized();
185
186 /* True by default: */
187 return true;
188}
189
190bool UISession::powerUp()
191{
192 /* Power UP machine: */
193 CProgress progress = uiCommon().shouldStartPaused() ? console().PowerUpPaused() : console().PowerUp();
194
195 /* Check for immediate failure: */
196 if (!console().isOk() || progress.isNull())
197 {
198 if (uiCommon().showStartVMErrors())
199 msgCenter().cannotStartMachine(console(), machineName());
200 LogRel(("GUI: Aborting startup due to power up issue detected...\n"));
201 return false;
202 }
203
204 /* Some logging right after we powered up: */
205 LogRel(("Qt version: %s\n", UICommon::qtRTVersionString().toUtf8().constData()));
206#ifdef VBOX_WS_X11
207 LogRel(("X11 Window Manager code: %d\n", (int)uiCommon().typeOfWindowManager()));
208#endif
209
210 /* Enable 'manual-override',
211 * preventing automatic Runtime UI closing
212 * and visual representation mode changes: */
213 setManualOverrideMode(true);
214
215 /* Show "Starting/Restoring" progress dialog: */
216 if (isSaved())
217 {
218 msgCenter().showModalProgressDialog(progress, machineName(), ":/progress_state_restore_90px.png", 0, 0);
219 /* After restoring from 'saved' state, machine-window(s) geometry should be adjusted: */
220 machineLogic()->adjustMachineWindowsGeometry();
221 }
222 else
223 {
224#ifdef VBOX_IS_QT6_OR_LATER /** @todo why is this any problem on qt6? */
225 msgCenter().showModalProgressDialog(progress, machineName(), ":/progress_start_90px.png", 0, 0);
226#else
227 msgCenter().showModalProgressDialog(progress, machineName(), ":/progress_start_90px.png");
228#endif
229 /* After VM start, machine-window(s) size-hint(s) should be sent: */
230 machineLogic()->sendMachineWindowsSizeHints();
231 }
232
233 /* Check for progress failure: */
234 if (!progress.isOk() || progress.GetResultCode() != 0)
235 {
236 if (uiCommon().showStartVMErrors())
237 msgCenter().cannotStartMachine(progress, machineName());
238 LogRel(("GUI: Aborting startup due to power up progress issue detected...\n"));
239 return false;
240 }
241
242 /* Disable 'manual-override' finally: */
243 setManualOverrideMode(false);
244
245 /* True by default: */
246 return true;
247}
248
249void UISession::detachUi()
250{
251 /* Manually close Runtime UI: */
252 LogRel(("GUI: Detaching UI..\n"));
253 closeRuntimeUI();
254}
255
256void UISession::saveState()
257{
258 /* Prepare VM to be saved: */
259 if (!prepareToBeSaved())
260 return;
261
262 /* Enable 'manual-override',
263 * preventing automatic Runtime UI closing: */
264 setManualOverrideMode(true);
265
266 /* Now, do the magic: */
267 LogRel(("GUI: Saving VM state..\n"));
268 UINotificationProgressMachineSaveState *pNotification =
269 new UINotificationProgressMachineSaveState(machine());
270 connect(pNotification, &UINotificationProgressMachineSaveState::sigMachineStateSaved,
271 this, &UISession::sltHandleMachineStateSaved);
272 gpNotificationCenter->append(pNotification);
273}
274
275void UISession::shutdown()
276{
277 /* Prepare VM to be shutdowned: */
278 if (!prepareToBeShutdowned())
279 return;
280
281 /* Now, do the magic: */
282 LogRel(("GUI: Sending ACPI shutdown signal..\n"));
283 CConsole comConsole = console();
284 comConsole.PowerButton();
285 if (!comConsole.isOk())
286 UINotificationMessage::cannotACPIShutdownMachine(console());
287}
288
289void UISession::powerOff(bool fIncludingDiscard)
290{
291 /* Enable 'manual-override',
292 * preventing automatic Runtime UI closing: */
293 setManualOverrideMode(true);
294
295 /* Now, do the magic: */
296 LogRel(("GUI: Powering VM off..\n"));
297 UINotificationProgressMachinePowerOff *pNotification =
298 new UINotificationProgressMachinePowerOff(machine(),
299 console(),
300 fIncludingDiscard);
301 connect(pNotification, &UINotificationProgressMachinePowerOff::sigMachinePoweredOff,
302 this, &UISession::sltHandleMachinePoweredOff);
303 gpNotificationCenter->append(pNotification);
304}
305
306UIMachineLogic* UISession::machineLogic() const
307{
308 return uimachine() ? uimachine()->machineLogic() : 0;
309}
310
311QWidget* UISession::mainMachineWindow() const
312{
313 return machineLogic() ? machineLogic()->mainMachineWindow() : 0;
314}
315
316WId UISession::mainMachineWindowId() const
317{
318 return mainMachineWindow()->winId();
319}
320
321UIMachineWindow *UISession::activeMachineWindow() const
322{
323 return machineLogic() ? machineLogic()->activeMachineWindow() : 0;
324}
325
326bool UISession::isVisualStateAllowed(UIVisualStateType state) const
327{
328 return uimachine()->isVisualStateAllowed(state);
329}
330
331void UISession::changeVisualState(UIVisualStateType visualStateType)
332{
333 uimachine()->asyncChangeVisualState(visualStateType);
334}
335
336void UISession::setRequestedVisualState(UIVisualStateType visualStateType)
337{
338 uimachine()->setRequestedVisualState(visualStateType);
339}
340
341UIVisualStateType UISession::requestedVisualState() const
342{
343 return uimachine()->requestedVisualState();
344}
345
346bool UISession::guestAdditionsUpgradable()
347{
348 if (!machine().isOk())
349 return false;
350
351 /* Auto GA update is currently for Windows and Linux guests only */
352 const CGuestOSType osType = uiCommon().vmGuestOSType(machine().GetOSTypeId());
353 if (!osType.isOk())
354 return false;
355
356 const QString strGuestFamily = osType.GetFamilyId();
357 bool fIsWindowOrLinux = strGuestFamily.contains("windows", Qt::CaseInsensitive) || strGuestFamily.contains("linux", Qt::CaseInsensitive);
358
359 if (!fIsWindowOrLinux)
360 return false;
361
362 /* Also check whether we have something to update automatically: */
363 if (m_ulGuestAdditionsRunLevel < (ULONG)KAdditionsRunLevelType_Userland)
364 return false;
365
366 return true;
367}
368
369bool UISession::setPause(bool fOn)
370{
371 if (fOn)
372 console().Pause();
373 else
374 console().Resume();
375
376 bool ok = console().isOk();
377 if (!ok)
378 {
379 if (fOn)
380 UINotificationMessage::cannotPauseMachine(console());
381 else
382 UINotificationMessage::cannotResumeMachine(console());
383 }
384
385 return ok;
386}
387
388void UISession::sltInstallGuestAdditionsFrom(const QString &strSource)
389{
390 if (!guestAdditionsUpgradable())
391 return sltMountDVDAdHoc(strSource);
392
393 /* Update guest additions automatically: */
394 UINotificationProgressGuestAdditionsInstall *pNotification =
395 new UINotificationProgressGuestAdditionsInstall(guest(), strSource);
396 connect(pNotification, &UINotificationProgressGuestAdditionsInstall::sigGuestAdditionsInstallationFailed,
397 this, &UISession::sltMountDVDAdHoc);
398 gpNotificationCenter->append(pNotification);
399}
400
401void UISession::sltMountDVDAdHoc(const QString &strSource)
402{
403 mountAdHocImage(KDeviceType_DVD, UIMediumDeviceType_DVD, strSource);
404}
405
406void UISession::closeRuntimeUI()
407{
408 /* First, we have to hide any opened modal/popup widgets.
409 * They then should unlock their event-loops asynchronously.
410 * If all such loops are unlocked, we can close Runtime UI. */
411 QWidget *pWidget = QApplication::activeModalWidget()
412 ? QApplication::activeModalWidget()
413 : QApplication::activePopupWidget()
414 ? QApplication::activePopupWidget()
415 : 0;
416 if (pWidget)
417 {
418 /* First we should try to close this widget: */
419 pWidget->close();
420 /* If widget rejected the 'close-event' we can
421 * still hide it and hope it will behave correctly
422 * and unlock his event-loop if any: */
423 if (!pWidget->isHidden())
424 pWidget->hide();
425 /* Asynchronously restart this slot: */
426 QMetaObject::invokeMethod(this, "closeRuntimeUI", Qt::QueuedConnection);
427 return;
428 }
429
430 /* Asynchronously ask UIMachine to close Runtime UI: */
431 LogRel(("GUI: Passing request to close Runtime UI from UI session to UI machine.\n"));
432 QMetaObject::invokeMethod(uimachine(), "closeRuntimeUI", Qt::QueuedConnection);
433}
434
435void UISession::sltDetachCOM()
436{
437 /* Cleanup everything COM related: */
438 cleanupFramebuffers();
439 cleanupConsoleEventHandlers();
440 cleanupNotificationCenter();
441 cleanupSession();
442}
443
444void UISession::sltStateChange(KMachineState state)
445{
446 /* Check if something had changed: */
447 if (m_machineState != state)
448 {
449 /* Store new data: */
450 m_machineStatePrevious = m_machineState;
451 m_machineState = state;
452
453 /* Notify listeners about machine state changed: */
454 emit sigMachineStateChange();
455 }
456}
457
458void UISession::sltHandleMachineStateSaved(bool fSuccess)
459{
460 /* Disable 'manual-override' finally: */
461 setManualOverrideMode(false);
462
463 /* Close Runtime UI if state was saved: */
464 if (fSuccess)
465 closeRuntimeUI();
466}
467
468void UISession::sltHandleMachinePoweredOff(bool fSuccess, bool fIncludingDiscard)
469{
470 /* Disable 'manual-override' finally: */
471 setManualOverrideMode(false);
472
473 /* Do we have other tasks? */
474 if (fSuccess)
475 {
476 if (!fIncludingDiscard)
477 closeRuntimeUI();
478 else
479 {
480 /* Now, do more magic! */
481 UINotificationProgressSnapshotRestore *pNotification =
482 new UINotificationProgressSnapshotRestore(uiCommon().managedVMUuid());
483 connect(pNotification, &UINotificationProgressSnapshotRestore::sigSnapshotRestored,
484 this, &UISession::sltHandleSnapshotRestored);
485 gpNotificationCenter->append(pNotification);
486 }
487 }
488}
489
490void UISession::sltHandleSnapshotRestored(bool)
491{
492 /* Close Runtime UI independent of snapshot restoring state: */
493 closeRuntimeUI();
494}
495
496void UISession::sltAdditionsChange()
497{
498 /* Acquire actual states: */
499 const ULONG ulGuestAdditionsRunLevel = guest().GetAdditionsRunLevel();
500 LONG64 lLastUpdatedIgnored;
501 const bool fIsGuestSupportsGraphics = guest().GetFacilityStatus(KAdditionsFacilityType_Graphics, lLastUpdatedIgnored)
502 == KAdditionsFacilityStatus_Active;
503 const bool fIsGuestSupportsSeamless = guest().GetFacilityStatus(KAdditionsFacilityType_Seamless, lLastUpdatedIgnored)
504 == KAdditionsFacilityStatus_Active;
505
506 /* Check if something had changed: */
507 if ( m_ulGuestAdditionsRunLevel != ulGuestAdditionsRunLevel
508 || m_fIsGuestSupportsGraphics != fIsGuestSupportsGraphics
509 || m_fIsGuestSupportsSeamless != fIsGuestSupportsSeamless)
510 {
511 /* Store new data: */
512 m_ulGuestAdditionsRunLevel = ulGuestAdditionsRunLevel;
513 m_fIsGuestSupportsGraphics = fIsGuestSupportsGraphics;
514 m_fIsGuestSupportsSeamless = fIsGuestSupportsSeamless;
515
516 /* Notify listeners about GA state really changed: */
517 LogRel(("GUI: UISession::sltAdditionsChange: GA state really changed, notifying listeners.\n"));
518 emit sigAdditionsStateActualChange();
519 }
520 else
521 LogRel(("GUI: UISession::sltAdditionsChange: GA state doesn't really changed, still notifying listeners.\n"));
522
523 /* Notify listeners about GA state change event came: */
524 emit sigAdditionsStateChange();
525}
526
527UISession::UISession(UIMachine *pMachine)
528 : QObject(pMachine)
529 /* Base variables: */
530 , m_pMachine(pMachine)
531 , m_pConsoleEventhandler(0)
532 /* Common variables: */
533 , m_machineStatePrevious(KMachineState_Null)
534 , m_machineState(KMachineState_Null)
535 /* Common flags: */
536 , m_fInitialized(false)
537 , m_fIsGuestResizeIgnored(false)
538 , m_fIsAutoCaptureDisabled(false)
539 , m_fIsManualOverride(false)
540 /* Guest additions flags: */
541 , m_ulGuestAdditionsRunLevel(0)
542 , m_fIsGuestSupportsGraphics(false)
543 , m_fIsGuestSupportsSeamless(false)
544 /* CPU hardware virtualization features for VM: */
545 , m_enmVMExecutionEngine(KVMExecutionEngine_NotSet)
546 , m_fIsHWVirtExNestedPagingEnabled(false)
547 , m_fIsHWVirtExUXEnabled(false)
548 /* VM's effective paravirtualization provider: */
549 , m_paraVirtProvider(KParavirtProvider_None)
550{
551}
552
553UISession::~UISession()
554{
555}
556
557bool UISession::prepare()
558{
559 /* Prepare COM stuff: */
560 if (!prepareSession())
561 return false;
562 prepareNotificationCenter();
563 prepareConsoleEventHandlers();
564 prepareFramebuffers();
565
566 /* Prepare GUI stuff: */
567 prepareConnections();
568 prepareSignalHandling();
569
570 /* True by default: */
571 return true;
572}
573
574bool UISession::prepareSession()
575{
576 /* Open session: */
577 m_session = uiCommon().openSession(uiCommon().managedVMUuid(),
578 uiCommon().isSeparateProcess()
579 ? KLockType_Shared
580 : KLockType_VM);
581 if (m_session.isNull())
582 return false;
583
584 /* Get machine: */
585 m_machine = m_session.GetMachine();
586 if (m_machine.isNull())
587 return false;
588
589 /* Get console: */
590 m_console = m_session.GetConsole();
591 if (m_console.isNull())
592 return false;
593
594 /* Get display: */
595 m_display = m_console.GetDisplay();
596 if (m_display.isNull())
597 return false;
598
599 /* Get guest: */
600 m_guest = m_console.GetGuest();
601 if (m_guest.isNull())
602 return false;
603
604 /* Get mouse: */
605 m_mouse = m_console.GetMouse();
606 if (m_mouse.isNull())
607 return false;
608
609 /* Get keyboard: */
610 m_keyboard = m_console.GetKeyboard();
611 if (m_keyboard.isNull())
612 return false;
613
614 /* Get debugger: */
615 m_debugger = m_console.GetDebugger();
616 if (m_debugger.isNull())
617 return false;
618
619 /* Update machine-name: */
620 m_strMachineName = machine().GetName();
621
622 /* Update machine-state: */
623 m_machineState = machine().GetState();
624
625 /* True by default: */
626 return true;
627}
628
629void UISession::prepareNotificationCenter()
630{
631 UINotificationCenter::create();
632}
633
634void UISession::prepareConsoleEventHandlers()
635{
636 /* Create console event-handler: */
637 m_pConsoleEventhandler = new UIConsoleEventHandler(this);
638
639 /* Console event connections: */
640 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigAdditionsChange,
641 this, &UISession::sltAdditionsChange);
642 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigAudioAdapterChange,
643 this, &UISession::sigAudioAdapterChange);
644 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigClipboardModeChange,
645 this, &UISession::sigClipboardModeChange);
646 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigCPUExecutionCapChange,
647 this, &UISession::sigCPUExecutionCapChange);
648 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigDnDModeChange,
649 this, &UISession::sigDnDModeChange);
650 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigGuestMonitorChange,
651 this, &UISession::sigGuestMonitorChange);
652 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigMediumChange,
653 this, &UISession::sigMediumChange);
654 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigNetworkAdapterChange,
655 this, &UISession::sigNetworkAdapterChange);
656 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigRecordingChange,
657 this, &UISession::sigRecordingChange);
658 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigSharedFolderChange,
659 this, &UISession::sigSharedFolderChange);
660 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigStateChange,
661 this, &UISession::sltStateChange);
662 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigStorageDeviceChange,
663 this, &UISession::sigStorageDeviceChange);
664 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigUSBControllerChange,
665 this, &UISession::sigUSBControllerChange);
666 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigUSBDeviceStateChange,
667 this, &UISession::sigUSBDeviceStateChange);
668 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigVRDEChange,
669 this, &UISession::sigVRDEChange);
670 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigRuntimeError,
671 this, &UISession::sigRuntimeError);
672
673#ifdef VBOX_WS_MAC
674 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigShowWindow,
675 this, &UISession::sigShowWindows, Qt::QueuedConnection);
676#endif
677
678 /* Console keyboard connections: */
679 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigKeyboardLedsChange,
680 this, &UISession::sigKeyboardLedsChange);
681
682 /* Console mouse connections: */
683 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigMousePointerShapeChange,
684 this, &UISession::sigMousePointerShapeChange);
685 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigMouseCapabilityChange,
686 this, &UISession::sigMouseCapabilityChange);
687 connect(m_pConsoleEventhandler, &UIConsoleEventHandler::sigCursorPositionChange,
688 this, &UISession::sigCursorPositionChange);
689}
690
691void UISession::prepareFramebuffers()
692{
693 /* Each framebuffer will be really prepared on first UIMachineView creation: */
694 m_frameBufferVector.resize(machine().GetGraphicsAdapter().GetMonitorCount());
695}
696
697void UISession::prepareConnections()
698{
699 /* UICommon connections: */
700 connect(&uiCommon(), &UICommon::sigAskToDetachCOM, this, &UISession::sltDetachCOM);
701}
702
703void UISession::prepareSignalHandling()
704{
705#ifdef VBOX_GUI_WITH_KEYS_RESET_HANDLER
706 struct sigaction sa;
707 sa.sa_sigaction = &signalHandlerSIGUSR1;
708 sigemptyset(&sa.sa_mask);
709 sa.sa_flags = SA_RESTART | SA_SIGINFO;
710 sigaction(SIGUSR1, &sa, NULL);
711#endif /* VBOX_GUI_WITH_KEYS_RESET_HANDLER */
712}
713
714void UISession::cleanupFramebuffers()
715{
716 /* Cleanup framebuffers finally: */
717 for (int i = m_frameBufferVector.size() - 1; i >= 0; --i)
718 {
719 UIFrameBuffer *pFrameBuffer = m_frameBufferVector[i];
720 if (pFrameBuffer)
721 {
722 /* Mark framebuffer as unused: */
723 pFrameBuffer->setMarkAsUnused(true);
724 /* Detach framebuffer from Display: */
725 pFrameBuffer->detach();
726 /* Delete framebuffer reference: */
727 delete pFrameBuffer;
728 }
729 }
730 m_frameBufferVector.clear();
731}
732
733void UISession::cleanupConsoleEventHandlers()
734{
735 /* Destroy console event-handler: */
736 delete m_pConsoleEventhandler;
737 m_pConsoleEventhandler = 0;
738}
739
740void UISession::cleanupNotificationCenter()
741{
742 UINotificationCenter::destroy();
743}
744
745void UISession::cleanupSession()
746{
747 /* Detach debugger: */
748 if (!m_debugger.isNull())
749 m_debugger.detach();
750
751 /* Detach keyboard: */
752 if (!m_keyboard.isNull())
753 m_keyboard.detach();
754
755 /* Detach mouse: */
756 if (!m_mouse.isNull())
757 m_mouse.detach();
758
759 /* Detach guest: */
760 if (!m_guest.isNull())
761 m_guest.detach();
762
763 /* Detach display: */
764 if (!m_display.isNull())
765 m_display.detach();
766
767 /* Detach console: */
768 if (!m_console.isNull())
769 m_console.detach();
770
771 /* Detach machine: */
772 if (!m_machine.isNull())
773 m_machine.detach();
774
775 /* Close session: */
776 if (!m_session.isNull() && uiCommon().isVBoxSVCAvailable())
777 {
778 m_session.UnlockMachine();
779 m_session.detach();
780 }
781}
782
783bool UISession::preprocessInitialization()
784{
785#ifdef VBOX_WITH_NETFLT
786 /* Skip further checks if VM in saved state */
787 if (isSaved())
788 return true;
789
790 /* Make sure all the attached and enabled network
791 * adapters are present on the host. This check makes sense
792 * in two cases only - when attachement type is Bridged Network
793 * or Host-only Interface. NOTE: Only currently enabled
794 * attachement type is checked (incorrect parameters check for
795 * currently disabled attachement types is skipped). */
796 QStringList failedInterfaceNames;
797 QStringList availableInterfaceNames;
798
799 /* Create host network interface names list */
800 foreach (const CHostNetworkInterface &iface, uiCommon().host().GetNetworkInterfaces())
801 {
802 availableInterfaceNames << iface.GetName();
803 availableInterfaceNames << iface.GetShortName();
804 }
805
806 ulong cCount = uiCommon().virtualBox().GetSystemProperties().GetMaxNetworkAdapters(machine().GetChipsetType());
807 for (ulong uAdapterIndex = 0; uAdapterIndex < cCount; ++uAdapterIndex)
808 {
809 CNetworkAdapter na = machine().GetNetworkAdapter(uAdapterIndex);
810
811 if (na.GetEnabled())
812 {
813 QString strIfName = QString();
814
815 /* Get physical network interface name for currently
816 * enabled network attachement type */
817 switch (na.GetAttachmentType())
818 {
819 case KNetworkAttachmentType_Bridged:
820 strIfName = na.GetBridgedInterface();
821 break;
822#ifndef VBOX_WITH_VMNET
823 case KNetworkAttachmentType_HostOnly:
824 strIfName = na.GetHostOnlyInterface();
825 break;
826#endif /* !VBOX_WITH_VMNET */
827 default: break; /* Shut up, MSC! */
828 }
829
830 if (!strIfName.isEmpty() &&
831 !availableInterfaceNames.contains(strIfName))
832 {
833 LogFlow(("Found invalid network interface: %s\n", strIfName.toStdString().c_str()));
834 failedInterfaceNames << QString("%1 (adapter %2)").arg(strIfName).arg(uAdapterIndex + 1);
835 }
836 }
837 }
838
839 /* Check if non-existent interfaces found */
840 if (!failedInterfaceNames.isEmpty())
841 {
842 if (msgCenter().warnAboutNetworkInterfaceNotFound(machineName(), failedInterfaceNames.join(", ")))
843 machineLogic()->openNetworkSettingsDialog();
844 else
845 {
846 LogRel(("GUI: Aborting startup due to preprocess initialization issue detected...\n"));
847 return false;
848 }
849 }
850#endif /* VBOX_WITH_NETFLT */
851
852 /* Check for USB enumeration warning. Don't return false even if we have a warning: */
853 CHost comHost = uiCommon().host();
854 if (comHost.GetUSBDevices().isEmpty() && comHost.isWarning())
855 {
856 /* Do not bitch if USB disabled: */
857 if (!machine().GetUSBControllers().isEmpty())
858 {
859 /* Do not bitch if there are no filters (check if enabled too?): */
860 if (!machine().GetUSBDeviceFilters().GetDeviceFilters().isEmpty())
861 UINotificationMessage::cannotEnumerateHostUSBDevices(comHost);
862 }
863 }
864
865 /* True by default: */
866 return true;
867}
868
869bool UISession::mountAdHocImage(KDeviceType enmDeviceType, UIMediumDeviceType enmMediumType, const QString &strMediumName)
870{
871 /* Get VBox: */
872 CVirtualBox comVBox = uiCommon().virtualBox();
873
874 /* Prepare medium to mount: */
875 UIMedium guiMedium;
876
877 /* The 'none' medium name means ejecting what ever is in the drive,
878 * in that case => leave the guiMedium variable null. */
879 if (strMediumName != "none")
880 {
881 /* Open the medium: */
882 const CMedium comMedium = comVBox.OpenMedium(strMediumName, enmDeviceType, KAccessMode_ReadWrite, false /* fForceNewUuid */);
883 if (!comVBox.isOk() || comMedium.isNull())
884 {
885 UINotificationMessage::cannotOpenMedium(comVBox, strMediumName);
886 return false;
887 }
888
889 /* Make sure medium ID is valid: */
890 const QUuid uMediumId = comMedium.GetId();
891 AssertReturn(!uMediumId.isNull(), false);
892
893 /* Try to find UIMedium among cached: */
894 guiMedium = uiCommon().medium(uMediumId);
895 if (guiMedium.isNull())
896 {
897 /* Cache new one if necessary: */
898 guiMedium = UIMedium(comMedium, enmMediumType, KMediumState_Created);
899 uiCommon().createMedium(guiMedium);
900 }
901 }
902
903 /* Search for a suitable storage slots: */
904 QList<ExactStorageSlot> aFreeStorageSlots;
905 QList<ExactStorageSlot> aBusyStorageSlots;
906 foreach (const CStorageController &comController, machine().GetStorageControllers())
907 {
908 foreach (const CMediumAttachment &comAttachment, machine().GetMediumAttachmentsOfController(comController.GetName()))
909 {
910 /* Look for an optical devices only: */
911 if (comAttachment.GetType() == enmDeviceType)
912 {
913 /* Append storage slot to corresponding list: */
914 if (comAttachment.GetMedium().isNull())
915 aFreeStorageSlots << ExactStorageSlot(comController.GetName(), comController.GetBus(),
916 comAttachment.GetPort(), comAttachment.GetDevice());
917 else
918 aBusyStorageSlots << ExactStorageSlot(comController.GetName(), comController.GetBus(),
919 comAttachment.GetPort(), comAttachment.GetDevice());
920 }
921 }
922 }
923
924 /* Make sure at least one storage slot found: */
925 QList<ExactStorageSlot> sStorageSlots = aFreeStorageSlots + aBusyStorageSlots;
926 if (sStorageSlots.isEmpty())
927 {
928 UINotificationMessage::cannotMountImage(machineName(), strMediumName);
929 return false;
930 }
931
932 /* Try to mount medium into first available storage slot: */
933 while (!sStorageSlots.isEmpty())
934 {
935 const ExactStorageSlot storageSlot = sStorageSlots.takeFirst();
936 machine().MountMedium(storageSlot.controller, storageSlot.port, storageSlot.device, guiMedium.medium(), false /* force */);
937 if (machine().isOk())
938 break;
939 }
940
941 /* Show error message if necessary: */
942 if (!machine().isOk())
943 {
944 msgCenter().cannotRemountMedium(machine(), guiMedium, true /* mount? */, false /* retry? */, activeMachineWindow());
945 return false;
946 }
947
948 /* Save machine settings: */
949 machine().SaveSettings();
950
951 /* Show error message if necessary: */
952 if (!machine().isOk())
953 {
954 UINotificationMessage::cannotSaveMachineSettings(machine());
955 return false;
956 }
957
958 /* True by default: */
959 return true;
960}
961
962bool UISession::postprocessInitialization()
963{
964 /* There used to be some raw-mode warnings here for raw-mode incompatible
965 guests (64-bit ones and OS/2). Nothing to do at present. */
966 return true;
967}
968
969CMediumVector UISession::machineMedia() const
970{
971 CMediumVector comMedia;
972 /* Enumerate all the controllers: */
973 foreach (const CStorageController &comController, m_machine.GetStorageControllers())
974 {
975 /* Enumerate all the attachments: */
976 foreach (const CMediumAttachment &comAttachment, m_machine.GetMediumAttachmentsOfController(comController.GetName()))
977 {
978 /* Skip unrelated device types: */
979 const KDeviceType enmDeviceType = comAttachment.GetType();
980 if ( enmDeviceType != KDeviceType_HardDisk
981 && enmDeviceType != KDeviceType_Floppy
982 && enmDeviceType != KDeviceType_DVD)
983 continue;
984 if ( comAttachment.GetIsEjected()
985 || comAttachment.GetMedium().isNull())
986 continue;
987 comMedia.append(comAttachment.GetMedium());
988 }
989 }
990 return comMedia;
991}
992
993bool UISession::prepareToBeSaved()
994{
995 return isPaused()
996 || (isRunning() && pause());
997}
998
999bool UISession::prepareToBeShutdowned()
1000{
1001 const bool fValidMode = console().GetGuestEnteredACPIMode();
1002 if (!fValidMode)
1003 UINotificationMessage::cannotSendACPIToMachine();
1004 return fValidMode;
1005}
1006
1007void UISession::loadVMSettings()
1008{
1009 /* Cache IMachine::ExecutionEngine value. */
1010 m_enmVMExecutionEngine = m_debugger.GetExecutionEngine();
1011 /* Load nested-paging CPU hardware virtualization extension: */
1012 m_fIsHWVirtExNestedPagingEnabled = m_debugger.GetHWVirtExNestedPagingEnabled();
1013 /* Load whether the VM is currently making use of the unrestricted execution feature of VT-x: */
1014 m_fIsHWVirtExUXEnabled = m_debugger.GetHWVirtExUXEnabled();
1015 /* Load VM's effective paravirtualization provider: */
1016 m_paraVirtProvider = m_machine.GetEffectiveParavirtProvider();
1017}
1018
1019UIFrameBuffer* UISession::frameBuffer(ulong uScreenId) const
1020{
1021 Assert(uScreenId < (ulong)m_frameBufferVector.size());
1022 return m_frameBufferVector.value((int)uScreenId, 0);
1023}
1024
1025void UISession::setFrameBuffer(ulong uScreenId, UIFrameBuffer* pFrameBuffer)
1026{
1027 Assert(uScreenId < (ulong)m_frameBufferVector.size());
1028 if (uScreenId < (ulong)m_frameBufferVector.size())
1029 m_frameBufferVector[(int)uScreenId] = pFrameBuffer;
1030}
1031
1032#ifdef VBOX_GUI_WITH_KEYS_RESET_HANDLER
1033/**
1034 * Custom signal handler. When switching VTs, we might not get release events
1035 * for Ctrl-Alt and in case a savestate is performed on the new VT, the VM will
1036 * be saved with modifier keys stuck. This is annoying enough for introducing
1037 * this hack.
1038 */
1039/* static */
1040static void signalHandlerSIGUSR1(int sig, siginfo_t * /* pInfo */, void * /*pSecret */)
1041{
1042 /* Only SIGUSR1 is interesting: */
1043 if (sig == SIGUSR1)
1044 if (gpMachine)
1045 gpMachine->uisession()->machineLogic()->keyboardHandler()->releaseAllPressedKeys();
1046}
1047#endif /* VBOX_GUI_WITH_KEYS_RESET_HANDLER */
Note: See TracBrowser for help on using the repository browser.

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